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
4cca9977e59aefa31a690c5603215f077a66d14a
4727251e0cd73359b15b664c3170e5d754078599
/src/data/mv_polynomial/invertible.lean
cae1d3c1874bf99899eaeaf5acefd6e275b62f04
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
1,045
lean
/- Copyright (c) 2020 Johan Commelin, Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Robert Y. Lewis -/ import data.mv_polynomial.basic import ring_theory.algebra_tower /-! # Invertible polynomials This file is a stub containing some basic facts about invertible elements in the ring of polynomials. -/ open mv_polynomial noncomputable instance mv_polynomial.invertible_C (σ : Type*) {R : Type*} [comm_semiring R] (r : R) [invertible r] : invertible (C r : mv_polynomial σ R) := invertible.map (C : R →+* mv_polynomial σ R) _ /-- A natural number that is invertible when coerced to a commutative semiring `R` is also invertible when coerced to any polynomial ring with rational coefficients. Short-cut for typeclass resolution. -/ noncomputable instance mv_polynomial.invertible_coe_nat (σ R : Type*) (p : ℕ) [comm_semiring R] [invertible (p : R)] : invertible (p : mv_polynomial σ R) := is_scalar_tower.invertible_algebra_coe_nat R _ _
2a205bcef03f7a4c05e419f0de4bd8694dcd3642
36938939954e91f23dec66a02728db08a7acfcf9
/lean/deps/galois_stdlib/src/galois/data/list/nth_le.lean
91020555f919604af6482f5f3e8e896bb1312bea
[ "Apache-2.0" ]
permissive
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
4,698
lean
import galois.algebra.order import galois.data.nat.basic import .basic namespace galois namespace list open list /-- Simplify a singleton list -/ theorem nth_le_singleton {α: Type _} (x : α) (i : ℕ) (p : i < 1) : list.nth_le [x] i p = x := begin cases i, case nat.zero { simp [list.nth_le], }, case nat.succ : i { have q := nat.not_succ_le_zero _ (nat.le_of_lt_succ p), exact (false.elim q), }, end section nth_le_reverse /-- Lemma to help with stating nth_le_cons_rest. -/ theorem nth_le_cons_rest.index {i j} (i_pos : i > 0) (p:i < j + 1) : i-1 < j := begin cases i, case nat.zero { have h : false := nat.not_lt_zero _ i_pos, contradiction, }, case nat.succ : i { simp only [nat.add_succ, nat.add_zero, nat.succ_lt_succ_iff] at p, exact p, }, end theorem nth_le_cons_rest {α} (x:α) {l:list α} {i:ℕ} (i_pos : i > 0) (p:i < l.length + 1) : nth_le (x :: l) i p = nth_le l (i-1) (nth_le_cons_rest.index i_pos p) := begin cases i, case nat.zero { have h : false := nat.not_lt_zero _ i_pos, contradiction, }, case nat.succ : i { simp only [nth_le, nat.succ_sub_succ], trivial, }, end theorem nth_le_reverse_core.index1 {α} {l:list α} {i:ℕ} (i_lt : i < l.length) : l.length - i - 1 < l.length := begin simp only [nat.sub_lt_to_add, nat.add_assoc], apply and.intro, apply and.intro, { apply nat.lt_add_of_pos_right, simp [nat.succ_add], exact nat.zero_lt_succ i, }, { have h := nat.le_of_lt i_lt, simp [h], }, { cases l, { have h := nat.not_lt_zero _ i_lt, contradiction, }, { exact or.inr (nat.zero_lt_succ _), }, }, end -- Utility lemms needed for nth_le_reverse_core. theorem nth_le_reverse_core.index2 {α} {l r:list α} {i:ℕ} (i_lt : i < (list.reverse_core l r).length) (i_ge_l : not (i < l.length)) : i - l.length < r.length := begin simp only [list.length_reverse_core] at i_lt, simp only [not_lt] at i_ge_l, simp [nat.sub_lt_to_add, i_lt, i_ge_l], end /- Define nth_le (reverse_core ..) equationally. -/ theorem nth_le_reverse_core {α} : ∀ (l r : list α) (i : nat) (i_lt : i < (reverse_core l r).length) , nth_le (reverse_core l r) i i_lt = if h : i < l.length then nth_le l (l.length - (i + 1)) (nth_le_reverse_core.index1 h) else nth_le r (i - l.length) (nth_le_reverse_core.index2 i_lt h) := begin intros l, induction l, case list.nil { intros r i i_lt, simp [reverse_core, length, nat.not_lt_zero], }, case list.cons : lh l_rest ind { intros r i i_lt, simp [reverse_core, ind], apply dite (i < length l_rest), { intro i_lt_l_rest, have i_lt_len : (i < length (lh :: l_rest)) := nat.lt_succ_of_lt i_lt_l_rest, have len_l_rest : length l_rest ≥ i + 1 := i_lt_l_rest, simp only [dif_pos, i_lt_l_rest, i_lt_len, i_lt_l_rest, nat.succ_add, nat.zero_add, nat.succ_sub len_l_rest, nth_le], trivial, }, { intro i_ge_l_rest, simp only [dif_neg i_ge_l_rest], simp at i_ge_l_rest, apply or.elim (nat.eq_or_lt_of_le (i_ge_l_rest)), { intro l_eq, have ite_cond : i < length (lh :: l_rest), { simp [length, l_eq, nat.zero_lt_succ, nat.add_succ, nat.lt_succ_iff, nat.le_refl], }, simp only [ dif_pos, ite_cond ], simp [nat.succ_add, l_eq, nat.sub_self], }, { intro l_lt, have ite_cond : ¬(i < length (lh :: l_rest)), { simp only [ length, not_lt], exact l_lt, }, simp [ite_cond], have pr : 0 < i - length l_rest, { simp [nat.lt_sub_iff], exact l_lt, }, simp [nth_le_cons_rest _ pr, nat.sub_sub], }, }, }, end /-- Lemma for nth_le_reverse_simp -/ theorem nth_le_reverse_simp.lemma {α} {l:list α} {i:ℕ} (i_lt : i < l.reverse.length) : l.length - i - 1 < l.length := begin simp only [length_reverse] at i_lt, simp only [nat.sub_lt_to_add, nat.add_assoc], apply and.intro, apply and.intro, { apply nat.lt_add_of_pos_right, simp [nat.succ_add], exact nat.zero_lt_succ i, }, { have h := nat.le_of_lt i_lt, simp [h], }, { cases l, { have h := nat.not_lt_zero _ i_lt, contradiction, }, { exact or.inr (nat.zero_lt_succ _), }, }, end /-- This is a version of nth_le_reverse designed for better use as a simp rule. -/ @[simp] theorem nth_le_reverse_simp {α} {l:list α} {i:ℕ} (i_lt : i < l.reverse.length) : nth_le l.reverse i i_lt = list.nth_le l (l.length - i - 1) (nth_le_reverse_simp.lemma i_lt) := begin simp only [length_reverse] at i_lt, simp only [reverse, nth_le_reverse_core , dif_pos i_lt, nat.sub_sub], trivial, end end nth_le_reverse end list end galois
8d45ed929d7e0938580e69966e43fe10e40776cb
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Init/System/Uri.lean
696342eaf0bf8461dd29d8f033afc81c3e4460ea
[ "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
4,548
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Lovett -/ prelude import Init.Data.String.Extra import Init.System.FilePath namespace System namespace Uri namespace UriEscape /- https://www.ietf.org/rfc/rfc3986.txt -/ @[inline] def zero : UInt8 := '0'.toNat.toUInt8 @[inline] def nine : UInt8 := '9'.toNat.toUInt8 @[inline] def lettera : UInt8 := 'a'.toNat.toUInt8 @[inline] def letterf : UInt8 := 'f'.toNat.toUInt8 @[inline] def letterA : UInt8 := 'A'.toNat.toUInt8 @[inline] def letterF : UInt8 := 'F'.toNat.toUInt8 /-- Decode %HH escapings in the given string. Note that sometimes a consecutive sequence of multiple escapings can represet a utf-8 encoded sequence for a single unicode code point and these will also be decoded correctly. -/ def decodeUri (uri : String) : String := Id.run do let mut decoded : ByteArray := ByteArray.empty let rawBytes := uri.toUTF8 let len := rawBytes.size let mut i := 0 let percent := '%'.toNat.toUInt8 while i < len do let c := rawBytes[i]! (decoded, i) := if c == percent && i + 1 < len then let h1 := rawBytes[i + 1]! if let some hd1 := hexDigitToUInt8? h1 then if i + 2 < len then let h2 := rawBytes[i + 2]! if let some hd2 := hexDigitToUInt8? h2 then -- decode the hex digits into a byte. (decoded.push (hd1 * 16 + hd2), i + 3) else -- not a valid second hex digit so keep the original bytes (((decoded.push c).push h1).push h2, i + 3) else -- hit end of string, there is no h2. ((decoded.push c).push h1, i + 2) else -- not a valid hex digit so keep the original bytes ((decoded.push c).push h1, i + 2) else (decoded.push c, i + 1) return String.fromUTF8Unchecked decoded where hexDigitToUInt8? (c : UInt8) : Option UInt8 := if zero ≤ c ∧ c ≤ nine then some (c - zero) else if lettera ≤ c ∧ c ≤ letterf then some (c - lettera + 10) else if letterA ≤ c ∧ c ≤ letterF then some (c - letterA + 10) else none def rfc3986ReservedChars : List Char := [ ';', ':', '?', '#', '[', ']', '@', '&', '=', '+', '$', ',', '!', '\'', '(', ')', '*', '%', ' ' ] def uriEscapeAsciiChar (c : Char) : String := if rfc3986ReservedChars.contains c || c < ' ' then "%" ++ uInt8ToHex c.toNat.toUInt8 else if (Char.toNat c) < 127 then c.toString else c.toString.toUTF8.foldl (fun s b => s ++ "%" ++ (uInt8ToHex b)) "" where uInt8ToHex (c : UInt8) : String := let d2 := c / 16; let d1 := c % 16; (hexDigitRepr d2.toNat ++ hexDigitRepr d1.toNat).toUpper end UriEscape /-- Replaces special characters in the given Uri with %HH Uri escapings. -/ def escapeUri (uri: String) : String := uri.foldl (fun s c => s ++ UriEscape.uriEscapeAsciiChar c) "" /-- Replaces all %HH Uri escapings in the given string with their corresponding unicode code points. Note that sometimes a consecutive sequence of multiple escapings can represet a utf-8 encoded sequence for a single unicode code point and these will also be decoded correctly. -/ def unescapeUri (s: String) : String := UriEscape.decodeUri s /-- Convert the given FilePath to a "file:///encodedpath" Uri. -/ def pathToUri (fname : System.FilePath) : String := Id.run do let mut uri := fname.normalize.toString if System.Platform.isWindows then -- normalize drive letter -- lower-case drive letters seem to be preferred in URIs if uri.length >= 2 && (uri.get 0).isUpper && uri.get ⟨1⟩ == ':' then uri := uri.set 0 (uri.get 0).toLower uri := uri.map (fun c => if c == '\\' then '/' else c) uri := uri.foldl (fun s c => s ++ UriEscape.uriEscapeAsciiChar c) "" let result := if uri.startsWith "/" then "file://" ++ uri else "file:///" ++ uri result /-- Convert the given uri to a FilePath stripping the 'file://' prefix, ignoring the optional host name. -/ def fileUriToPath? (uri : String) : Option System.FilePath := Id.run do if !uri.startsWith "file://" then none else let mut p := (unescapeUri uri).drop "file://".length p := p.dropWhile (λ c => c != '/') -- drop the hostname. -- On Windows, the path "/c:/temp" needs to become "C:/temp" if System.Platform.isWindows && p.length >= 2 && p.get 0 == '/' && (p.get ⟨1⟩).isAlpha && p.get ⟨2⟩ == ':' then -- see also `pathToUri` p := p.drop 1 |>.modify 0 .toUpper some p end Uri end System
1c888b79a53e06b21537cf111f3d897b3d59cd5f
367134ba5a65885e863bdc4507601606690974c1
/src/ring_theory/polynomial/rational_root.lean
c710f5a8876e0db3e57eab7058ca618f37ff4ef6
[ "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
4,994
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import ring_theory.polynomial.scale_roots import ring_theory.localization /-! # Rational root theorem and integral root theorem This file contains the rational root theorem and integral root theorem. The rational root theorem for a unique factorization domain `A` with localization `S`, states that the roots of `p : polynomial A` in `A`'s field of fractions are of the form `x / y` with `x y : A`, `x ∣ p.coeff 0` and `y ∣ p.leading_coeff`. The corollary is the integral root theorem `is_integer_of_is_root_of_monic`: if `p` is monic, its roots must be integers. Finally, we use this to show unique factorization domains are integrally closed. ## References * https://en.wikipedia.org/wiki/Rational_root_theorem -/ section scale_roots variables {A K R S : Type*} [integral_domain A] [field K] [comm_ring R] [comm_ring S] variables {M : submonoid A} {f : localization_map M S} {g : fraction_map A K} open finsupp polynomial lemma scale_roots_aeval_eq_zero_of_aeval_mk'_eq_zero {p : polynomial A} {r : A} {s : M} (hr : @aeval A f.codomain _ _ _ (f.mk' r s) p = 0) : @aeval A f.codomain _ _ _ (f.to_map r) (scale_roots p s) = 0 := begin convert scale_roots_eval₂_eq_zero f.to_map hr, rw aeval_def, congr, apply (f.mk'_spec' r s).symm end lemma num_is_root_scale_roots_of_aeval_eq_zero [unique_factorization_monoid A] (g : fraction_map A K) {p : polynomial A} {x : g.codomain} (hr : aeval x p = 0) : is_root (scale_roots p (g.denom x)) (g.num x) := begin apply is_root_of_eval₂_map_eq_zero g.injective, refine scale_roots_aeval_eq_zero_of_aeval_mk'_eq_zero _, rw g.mk'_num_denom, exact hr end end scale_roots section rational_root_theorem variables {A K : Type*} [integral_domain A] [unique_factorization_monoid A] [field K] variables {f : fraction_map A K} open polynomial unique_factorization_monoid /-- Rational root theorem part 1: if `r : f.codomain` is a root of a polynomial over the ufd `A`, then the numerator of `r` divides the constant coefficient -/ theorem num_dvd_of_is_root {p : polynomial A} {r : f.codomain} (hr : aeval r p = 0) : f.num r ∣ p.coeff 0 := begin suffices : f.num r ∣ (scale_roots p (f.denom r)).coeff 0, { simp only [coeff_scale_roots, nat.sub_zero] at this, haveI := classical.prop_decidable, by_cases hr : f.num r = 0, { obtain ⟨u, hu⟩ := (f.is_unit_denom_of_num_eq_zero hr).pow p.nat_degree, rw ←hu at this, exact units.dvd_mul_right.mp this }, { refine dvd_of_dvd_mul_left_of_no_prime_factors hr _ this, intros q dvd_num dvd_denom_pow hq, apply hq.not_unit, exact f.num_denom_reduced r dvd_num (hq.dvd_of_dvd_pow dvd_denom_pow) } }, convert dvd_term_of_is_root_of_dvd_terms 0 (num_is_root_scale_roots_of_aeval_eq_zero f hr) _, { rw [pow_zero, mul_one] }, intros j hj, apply dvd_mul_of_dvd_right, convert pow_dvd_pow (f.num r) (nat.succ_le_of_lt (bot_lt_iff_ne_bot.mpr hj)), exact (pow_one _).symm end /-- Rational root theorem part 2: if `r : f.codomain` is a root of a polynomial over the ufd `A`, then the denominator of `r` divides the leading coefficient -/ theorem denom_dvd_of_is_root {p : polynomial A} {r : f.codomain} (hr : aeval r p = 0) : (f.denom r : A) ∣ p.leading_coeff := begin suffices : (f.denom r : A) ∣ p.leading_coeff * f.num r ^ p.nat_degree, { refine dvd_of_dvd_mul_left_of_no_prime_factors (mem_non_zero_divisors_iff_ne_zero.mp (f.denom r).2) _ this, intros q dvd_denom dvd_num_pow hq, apply hq.not_unit, exact f.num_denom_reduced r (hq.dvd_of_dvd_pow dvd_num_pow) dvd_denom }, rw ←coeff_scale_roots_nat_degree, apply dvd_term_of_is_root_of_dvd_terms _ (num_is_root_scale_roots_of_aeval_eq_zero f hr), intros j hj, by_cases h : j < p.nat_degree, { refine dvd_mul_of_dvd_left (dvd_mul_of_dvd_right _ _) _, convert pow_dvd_pow _ (nat.succ_le_iff.mpr (nat.lt_sub_left_of_add_lt _)), { exact (pow_one _).symm }, simpa using h }, rw [←nat_degree_scale_roots p (f.denom r)] at *, rw [coeff_eq_zero_of_nat_degree_lt (lt_of_le_of_ne (le_of_not_gt h) hj.symm), zero_mul], exact dvd_zero _ end /-- Integral root theorem: if `r : f.codomain` is a root of a monic polynomial over the ufd `A`, then `r` is an integer -/ theorem is_integer_of_is_root_of_monic {p : polynomial A} (hp : monic p) {r : f.codomain} (hr : aeval r p = 0) : f.is_integer r := f.is_integer_of_is_unit_denom (is_unit_of_dvd_one _ (hp ▸ denom_dvd_of_is_root hr)) namespace unique_factorization_monoid lemma integer_of_integral {x : f.codomain} : is_integral A x → f.is_integer x := λ ⟨p, hp, hx⟩, is_integer_of_is_root_of_monic hp hx lemma integrally_closed : integral_closure A f.codomain = ⊥ := eq_bot_iff.mpr (λ x hx, algebra.mem_bot.mpr (integer_of_integral hx)) end unique_factorization_monoid end rational_root_theorem
cf0f0f1aa82cb7469a565c46d1ab5e1418ee8148
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/analysis/normed_space/banach.lean
03b226ecfe24f3bef6e107d7554fc5dc9fd58a3c
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
10,922
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel Banach spaces, i.e., complete vector spaces. This file contains the Banach open mapping theorem, i.e., the fact that a bijective bounded linear map between Banach spaces has a bounded inverse. -/ import topology.metric_space.baire analysis.normed_space.bounded_linear_maps open function metric set filter finset open_locale classical topological_space variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] (f : E →L[𝕜] F) include 𝕜 set_option class.instance_max_depth 70 variable [complete_space F] /-- First step of the proof of the Banach open mapping theorem (using completeness of `F`): by Baire's theorem, there exists a ball in `E` whose image closure has nonempty interior. Rescaling everything, it follows that any `y ∈ F` is arbitrarily well approached by images of elements of norm at most `C * ∥y∥`. For further use, we will only need such an element whose image is within distance `∥y∥/2` of `y`, to apply an iterative process. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma exists_approx_preimage_norm_le (surj : surjective f) : ∃C ≥ 0, ∀y, ∃x, dist (f x) y ≤ 1/2 * ∥y∥ ∧ ∥x∥ ≤ C * ∥y∥ := begin haveI : nonempty F := ⟨0⟩, have A : (⋃n:ℕ, closure (f '' (ball 0 n))) = univ, { refine subset.antisymm (subset_univ _) (λy hy, _), rcases surj y with ⟨x, hx⟩, rcases exists_nat_gt (∥x∥) with ⟨n, hn⟩, refine mem_Union.2 ⟨n, subset_closure _⟩, refine (mem_image _ _ _).2 ⟨x, ⟨_, hx⟩⟩, rwa [mem_ball, dist_eq_norm, sub_zero] }, have : ∃(n:ℕ) y ε, 0 < ε ∧ ball y ε ⊆ closure (f '' (ball 0 n)) := nonempty_interior_of_Union_of_closed (λn, is_closed_closure) A, rcases this with ⟨n, a, ε, ⟨εpos, H⟩⟩, rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩, refine ⟨(ε/2)⁻¹ * ∥c∥ * 2 * n, _, λy, _⟩, { refine mul_nonneg (mul_nonneg (mul_nonneg _ (norm_nonneg _)) (by norm_num)) _, refine inv_nonneg.2 (div_nonneg' (le_of_lt εpos) (by norm_num)), exact nat.cast_nonneg n }, { by_cases hy : y = 0, { use 0, simp [hy] }, { rcases rescale_to_shell hc (half_pos εpos) hy with ⟨d, hd, ydle, leyd, dinv⟩, let δ := ∥d∥ * ∥y∥/4, have δpos : 0 < δ := div_pos (mul_pos (norm_pos_iff.2 hd) (norm_pos_iff.2 hy)) (by norm_num), have : a + d • y ∈ ball a ε, by simp [dist_eq_norm, lt_of_le_of_lt ydle (half_lt_self εpos)], rcases metric.mem_closure_iff.1 (H this) _ δpos with ⟨z₁, z₁im, h₁⟩, rcases (mem_image _ _ _).1 z₁im with ⟨x₁, hx₁, xz₁⟩, rw ← xz₁ at h₁, rw [mem_ball, dist_eq_norm, sub_zero] at hx₁, have : a ∈ ball a ε, by { simp, exact εpos }, rcases metric.mem_closure_iff.1 (H this) _ δpos with ⟨z₂, z₂im, h₂⟩, rcases (mem_image _ _ _).1 z₂im with ⟨x₂, hx₂, xz₂⟩, rw ← xz₂ at h₂, rw [mem_ball, dist_eq_norm, sub_zero] at hx₂, let x := x₁ - x₂, have I : ∥f x - d • y∥ ≤ 2 * δ := calc ∥f x - d • y∥ = ∥f x₁ - (a + d • y) - (f x₂ - a)∥ : by { congr' 1, simp only [x, f.map_sub], abel } ... ≤ ∥f x₁ - (a + d • y)∥ + ∥f x₂ - a∥ : norm_sub_le _ _ ... ≤ δ + δ : begin apply add_le_add, { rw [← dist_eq_norm, dist_comm], exact le_of_lt h₁ }, { rw [← dist_eq_norm, dist_comm], exact le_of_lt h₂ } end ... = 2 * δ : (two_mul _).symm, have J : ∥f (d⁻¹ • x) - y∥ ≤ 1/2 * ∥y∥ := calc ∥f (d⁻¹ • x) - y∥ = ∥d⁻¹ • f x - (d⁻¹ * d) • y∥ : by rwa [f.map_smul _, inv_mul_cancel, one_smul] ... = ∥d⁻¹ • (f x - d • y)∥ : by rw [mul_smul, smul_sub] ... = ∥d∥⁻¹ * ∥f x - d • y∥ : by rw [norm_smul, normed_field.norm_inv] ... ≤ ∥d∥⁻¹ * (2 * δ) : begin apply mul_le_mul_of_nonneg_left I, rw inv_nonneg, exact norm_nonneg _ end ... = (∥d∥⁻¹ * ∥d∥) * ∥y∥ /2 : by { simp only [δ], ring } ... = ∥y∥/2 : by { rw [inv_mul_cancel, one_mul], simp [norm_eq_zero, hd] } ... = (1/2) * ∥y∥ : by ring, rw ← dist_eq_norm at J, have 𝕜 : ∥d⁻¹ • x∥ ≤ (ε / 2)⁻¹ * ∥c∥ * 2 * ↑n * ∥y∥ := calc ∥d⁻¹ • x∥ = ∥d∥⁻¹ * ∥x₁ - x₂∥ : by rw [norm_smul, normed_field.norm_inv] ... ≤ ((ε / 2)⁻¹ * ∥c∥ * ∥y∥) * (n + n) : begin refine mul_le_mul dinv _ (norm_nonneg _) _, { exact le_trans (norm_sub_le _ _) (add_le_add (le_of_lt hx₁) (le_of_lt hx₂)) }, { apply mul_nonneg (mul_nonneg _ (norm_nonneg _)) (norm_nonneg _), exact inv_nonneg.2 (le_of_lt (half_pos εpos)) } end ... = (ε / 2)⁻¹ * ∥c∥ * 2 * ↑n * ∥y∥ : by ring, exact ⟨d⁻¹ • x, J, 𝕜⟩ } }, end variable [complete_space E] /-- The Banach open mapping theorem: if a bounded linear map between Banach spaces is onto, then any point has a preimage with controlled norm. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem exists_preimage_norm_le (surj : surjective f) : ∃C > 0, ∀y, ∃x, f x = y ∧ ∥x∥ ≤ C * ∥y∥ := begin obtain ⟨C, C0, hC⟩ := exists_approx_preimage_norm_le f surj, /- Second step of the proof: starting from `y`, we want an exact preimage of `y`. Let `g y` be the approximate preimage of `y` given by the first step, and `h y = y - f(g y)` the part that has no preimage yet. We will iterate this process, taking the approximate preimage of `h y`, leaving only `h^2 y` without preimage yet, and so on. Let `u n` be the approximate preimage of `h^n y`. Then `u` is a converging series, and by design the sum of the series is a preimage of `y`. This uses completeness of `E`. -/ choose g hg using hC, let h := λy, y - f (g y), have hle : ∀y, ∥h y∥ ≤ (1/2) * ∥y∥, { assume y, rw [← dist_eq_norm, dist_comm], exact (hg y).1 }, refine ⟨2 * C + 1, by linarith, λy, _⟩, have hnle : ∀n:ℕ, ∥(h^[n]) y∥ ≤ (1/2)^n * ∥y∥, { assume n, induction n with n IH, { simp only [one_div_eq_inv, nat.nat_zero_eq_zero, one_mul, nat.iterate_zero, pow_zero] }, { rw [nat.iterate_succ'], apply le_trans (hle _) _, rw [pow_succ, mul_assoc], apply mul_le_mul_of_nonneg_left IH, norm_num } }, let u := λn, g((h^[n]) y), have ule : ∀n, ∥u n∥ ≤ (1/2)^n * (C * ∥y∥), { assume n, apply le_trans (hg _).2 _, calc C * ∥(h^[n]) y∥ ≤ C * ((1/2)^n * ∥y∥) : mul_le_mul_of_nonneg_left (hnle n) C0 ... = (1 / 2) ^ n * (C * ∥y∥) : by ring }, have sNu : summable (λn, ∥u n∥), { refine summable_of_nonneg_of_le (λn, norm_nonneg _) ule _, exact summable.mul_right _ (summable_geometric (by norm_num) (by norm_num)) }, have su : summable u := summable_of_summable_norm sNu, let x := tsum u, have x_ineq : ∥x∥ ≤ (2 * C + 1) * ∥y∥ := calc ∥x∥ ≤ (∑n, ∥u n∥) : norm_tsum_le_tsum_norm sNu ... ≤ (∑n, (1/2)^n * (C * ∥y∥)) : tsum_le_tsum ule sNu (summable.mul_right _ summable_geometric_two) ... = (∑n, (1/2)^n) * (C * ∥y∥) : by { rw tsum_mul_right, exact summable_geometric_two } ... = 2 * (C * ∥y∥) : by rw tsum_geometric_two ... = 2 * C * ∥y∥ + 0 : by rw [add_zero, mul_assoc] ... ≤ 2 * C * ∥y∥ + ∥y∥ : add_le_add (le_refl _) (norm_nonneg _) ... = (2 * C + 1) * ∥y∥ : by ring, have fsumeq : ∀n:ℕ, f((finset.range n).sum u) = y - (h^[n]) y, { assume n, induction n with n IH, { simp [f.map_zero] }, { rw [sum_range_succ, f.map_add, IH, nat.iterate_succ'], simp [u, h, sub_eq_add_neg, add_comm, add_left_comm] } }, have : tendsto (λn, (range n).sum u) at_top (𝓝 x) := su.has_sum.tendsto_sum_nat, have L₁ : tendsto (λn, f((range n).sum u)) at_top (𝓝 (f x)) := (f.continuous.tendsto _).comp this, simp only [fsumeq] at L₁, have L₂ : tendsto (λn, y - (h^[n]) y) at_top (𝓝 (y - 0)), { refine tendsto_const_nhds.sub _, rw tendsto_iff_norm_tendsto_zero, simp only [sub_zero], refine squeeze_zero (λ_, norm_nonneg _) hnle _, have : 0 = 0 * ∥y∥, by rw zero_mul, rw this, refine tendsto.mul _ tendsto_const_nhds, exact tendsto_pow_at_top_nhds_0_of_lt_1 (by norm_num) (by norm_num) }, have feq : f x = y - 0, { apply tendsto_nhds_unique _ L₁ L₂, simp }, rw sub_zero at feq, exact ⟨x, feq, x_ineq⟩ end /-- The Banach open mapping theorem: a surjective bounded linear map between Banach spaces is open. -/ theorem open_mapping (surj : surjective f) : is_open_map f := begin assume s hs, rcases exists_preimage_norm_le f surj with ⟨C, Cpos, hC⟩, refine is_open_iff.2 (λy yfs, _), rcases mem_image_iff_bex.1 yfs with ⟨x, xs, fxy⟩, rcases is_open_iff.1 hs x xs with ⟨ε, εpos, hε⟩, refine ⟨ε/C, div_pos εpos Cpos, λz hz, _⟩, rcases hC (z-y) with ⟨w, wim, wnorm⟩, have : f (x + w) = z, by { rw [f.map_add, wim, fxy, add_sub_cancel'_right] }, rw ← this, have : x + w ∈ ball x ε := calc dist (x+w) x = ∥w∥ : by { rw dist_eq_norm, simp } ... ≤ C * ∥z - y∥ : wnorm ... < C * (ε/C) : begin apply mul_lt_mul_of_pos_left _ Cpos, rwa [mem_ball, dist_eq_norm] at hz, end ... = ε : mul_div_cancel' _ (ne_of_gt Cpos), exact set.mem_image_of_mem _ (hε this) end /-- If a bounded linear map is a bijection, then its inverse is also a bounded linear map. -/ theorem linear_equiv.continuous_symm (e : E ≃ₗ[𝕜] F) (h : continuous e) : continuous e.symm := begin obtain ⟨M, Mpos, hM⟩ : ∃ M > 0, ∀ (y : F), ∃ (x : E), e x = y ∧ ∥x∥ ≤ M * ∥y∥, from exists_preimage_norm_le (continuous_linear_map.mk e.to_linear_map h) e.to_equiv.surjective, refine e.symm.to_linear_map.continuous_of_bound M (λ y, _), rcases hM y with ⟨x, hx, xnorm⟩, convert xnorm, rw ← hx, apply e.symm_apply_apply end /-- Associating to a linear equivalence between Banach spaces a continuous linear equivalence when the direct map is continuous, thanks to the Banach open mapping theorem that ensures that the inverse map is also continuous. -/ def linear_equiv.to_continuous_linear_equiv_of_continuous (e : E ≃ₗ[𝕜] F) (h : continuous e) : E ≃L[𝕜] F := { continuous_to_fun := h, continuous_inv_fun := e.continuous_symm h, ..e }
6949a352de01e8b3e2cf7d19a12620050d31995d
4727251e0cd73359b15b664c3170e5d754078599
/src/field_theory/splitting_field.lean
06699d272c09f181a3db831532646689a5b0d843
[ "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
44,373
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import field_theory.minpoly import ring_theory.adjoin_root import linear_algebra.finite_dimensional import algebra.polynomial.big_operators import ring_theory.algebraic import ring_theory.algebra_tower import tactic.field_simp /-! # Splitting fields This file introduces the notion of a splitting field of a polynomial and provides an embedding from a splitting field to any field that splits the polynomial. A polynomial `f : polynomial K` splits over a field extension `L` of `K` if it is zero or all of its irreducible factors over `L` have degree `1`. A field extension of `K` of a polynomial `f : polynomial K` is called a splitting field if it is the smallest field extension of `K` such that `f` splits. ## Main definitions * `polynomial.splits i f`: A predicate on a field homomorphism `i : K → L` and a polynomial `f` saying that `f` is zero or all of its irreducible factors over `L` have degree `1`. * `polynomial.splitting_field f`: A fixed splitting field of the polynomial `f`. * `polynomial.is_splitting_field`: A predicate on a field to be a splitting field of a polynomial `f`. ## Main statements * `polynomial.C_leading_coeff_mul_prod_multiset_X_sub_C`: If a polynomial has as many roots as its degree, it can be written as the product of its leading coefficient with `∏ (X - a)` where `a` ranges through its roots. * `lift_of_splits`: If `K` and `L` are field extensions of a field `F` and for some finite subset `S` of `K`, the minimal polynomial of every `x ∈ K` splits as a polynomial with coefficients in `L`, then `algebra.adjoin F S` embeds into `L`. * `polynomial.is_splitting_field.lift`: An embedding of a splitting field of the polynomial `f` into another field such that `f` splits. * `polynomial.is_splitting_field.alg_equiv`: Every splitting field of a polynomial `f` is isomorphic to `splitting_field f` and thus, being a splitting field is unique up to isomorphism. -/ noncomputable theory open_locale classical big_operators polynomial universes u v w variables {F : Type u} {K : Type v} {L : Type w} namespace polynomial variables [field K] [field L] [field F] open polynomial section splits variables (i : K →+* L) /-- A polynomial `splits` iff it is zero or all of its irreducible factors have `degree` 1. -/ def splits (f : K[X]) : Prop := f = 0 ∨ ∀ {g : L[X]}, irreducible g → g ∣ f.map i → degree g = 1 @[simp] lemma splits_zero : splits i (0 : K[X]) := or.inl rfl @[simp] lemma splits_C (a : K) : splits i (C a) := if ha : a = 0 then ha.symm ▸ (@C_0 K _).symm ▸ splits_zero i else have hia : i a ≠ 0, from mt ((injective_iff_map_eq_zero i).1 i.injective _) ha, or.inr $ λ g hg ⟨p, hp⟩, absurd hg.1 (not_not.2 (is_unit_iff_degree_eq_zero.2 $ by have := congr_arg degree hp; simp [degree_C hia, @eq_comm (with_bot ℕ) 0, nat.with_bot.add_eq_zero_iff] at this; clear _fun_match; tauto)) lemma splits_of_degree_eq_one {f : K[X]} (hf : degree f = 1) : splits i f := or.inr $ λ g hg ⟨p, hp⟩, by have := congr_arg degree hp; simp [nat.with_bot.add_eq_one_iff, hf, @eq_comm (with_bot ℕ) 1, mt is_unit_iff_degree_eq_zero.2 hg.1] at this; clear _fun_match; tauto lemma splits_of_degree_le_one {f : K[X]} (hf : degree f ≤ 1) : splits i f := begin cases h : degree f with n, { rw [degree_eq_bot.1 h]; exact splits_zero i }, { cases n with n, { rw [eq_C_of_degree_le_zero (trans_rel_right (≤) h le_rfl)]; exact splits_C _ _ }, { have hn : n = 0, { rw h at hf, cases n, { refl }, { exact absurd hf dec_trivial } }, exact splits_of_degree_eq_one _ (by rw [h, hn]; refl) } } end lemma splits_of_nat_degree_le_one {f : K[X]} (hf : nat_degree f ≤ 1) : splits i f := splits_of_degree_le_one i (degree_le_of_nat_degree_le hf) lemma splits_of_nat_degree_eq_one {f : K[X]} (hf : nat_degree f = 1) : splits i f := splits_of_nat_degree_le_one i (le_of_eq hf) lemma splits_mul {f g : K[X]} (hf : splits i f) (hg : splits i g) : splits i (f * g) := if h : f * g = 0 then by simp [h] else or.inr $ λ p hp hpf, ((principal_ideal_ring.irreducible_iff_prime.1 hp).2.2 _ _ (show p ∣ map i f * map i g, by convert hpf; rw polynomial.map_mul)).elim (hf.resolve_left (λ hf, by simpa [hf] using h) hp) (hg.resolve_left (λ hg, by simpa [hg] using h) hp) lemma splits_of_splits_mul {f g : K[X]} (hfg : f * g ≠ 0) (h : splits i (f * g)) : splits i f ∧ splits i g := ⟨or.inr $ λ g hgi hg, or.resolve_left h hfg hgi (by rw polynomial.map_mul; exact hg.trans (dvd_mul_right _ _)), or.inr $ λ g hgi hg, or.resolve_left h hfg hgi (by rw polynomial.map_mul; exact hg.trans (dvd_mul_left _ _))⟩ lemma splits_of_splits_of_dvd {f g : K[X]} (hf0 : f ≠ 0) (hf : splits i f) (hgf : g ∣ f) : splits i g := by { obtain ⟨f, rfl⟩ := hgf, exact (splits_of_splits_mul i hf0 hf).1 } lemma splits_of_splits_gcd_left {f g : K[X]} (hf0 : f ≠ 0) (hf : splits i f) : splits i (euclidean_domain.gcd f g) := polynomial.splits_of_splits_of_dvd i hf0 hf (euclidean_domain.gcd_dvd_left f g) lemma splits_of_splits_gcd_right {f g : K[X]} (hg0 : g ≠ 0) (hg : splits i g) : splits i (euclidean_domain.gcd f g) := polynomial.splits_of_splits_of_dvd i hg0 hg (euclidean_domain.gcd_dvd_right f g) lemma splits_map_iff (j : L →+* F) {f : K[X]} : splits j (f.map i) ↔ splits (j.comp i) f := by simp [splits, polynomial.map_map] theorem splits_one : splits i 1 := splits_C i 1 theorem splits_of_is_unit {u : K[X]} (hu : is_unit u) : u.splits i := splits_of_splits_of_dvd i one_ne_zero (splits_one _) $ is_unit_iff_dvd_one.1 hu theorem splits_X_sub_C {x : K} : (X - C x).splits i := splits_of_degree_eq_one _ $ degree_X_sub_C x theorem splits_X : X.splits i := splits_of_degree_eq_one _ $ degree_X theorem splits_id_iff_splits {f : K[X]} : (f.map i).splits (ring_hom.id L) ↔ f.splits i := by rw [splits_map_iff, ring_hom.id_comp] theorem splits_mul_iff {f g : K[X]} (hf : f ≠ 0) (hg : g ≠ 0) : (f * g).splits i ↔ f.splits i ∧ g.splits i := ⟨splits_of_splits_mul i (mul_ne_zero hf hg), λ ⟨hfs, hgs⟩, splits_mul i hfs hgs⟩ theorem splits_prod {ι : Type u} {s : ι → K[X]} {t : finset ι} : (∀ j ∈ t, (s j).splits i) → (∏ x in t, s x).splits i := begin refine finset.induction_on t (λ _, splits_one i) (λ a t hat ih ht, _), rw finset.forall_mem_insert at ht, rw finset.prod_insert hat, exact splits_mul i ht.1 (ih ht.2) end lemma splits_pow {f : K[X]} (hf : f.splits i) (n : ℕ) : (f ^ n).splits i := begin rw [←finset.card_range n, ←finset.prod_const], exact splits_prod i (λ j hj, hf), end lemma splits_X_pow (n : ℕ) : (X ^ n).splits i := splits_pow i (splits_X i) n theorem splits_prod_iff {ι : Type u} {s : ι → K[X]} {t : finset ι} : (∀ j ∈ t, s j ≠ 0) → ((∏ x in t, s x).splits i ↔ ∀ j ∈ t, (s j).splits i) := begin refine finset.induction_on t (λ _, ⟨λ _ _ h, h.elim, λ _, splits_one i⟩) (λ a t hat ih ht, _), rw finset.forall_mem_insert at ht ⊢, rw [finset.prod_insert hat, splits_mul_iff i ht.1 (finset.prod_ne_zero_iff.2 ht.2), ih ht.2] end lemma degree_eq_one_of_irreducible_of_splits {p : L[X]} (hp : irreducible p) (hp_splits : splits (ring_hom.id L) p) : p.degree = 1 := begin by_cases h_nz : p = 0, { exfalso, simp [*] at *, }, rcases hp_splits, { contradiction }, { apply hp_splits hp, simp } end lemma exists_root_of_splits {f : K[X]} (hs : splits i f) (hf0 : degree f ≠ 0) : ∃ x, eval₂ i x f = 0 := if hf0 : f = 0 then ⟨37, by simp [hf0]⟩ else let ⟨g, hg⟩ := wf_dvd_monoid.exists_irreducible_factor (show ¬ is_unit (f.map i), from mt is_unit_iff_degree_eq_zero.1 (by rwa degree_map)) (map_ne_zero hf0) in let ⟨x, hx⟩ := exists_root_of_degree_eq_one (hs.resolve_left hf0 hg.1 hg.2) in let ⟨i, hi⟩ := hg.2 in ⟨x, by rw [← eval_map, hi, eval_mul, show _ = _, from hx, zero_mul]⟩ lemma exists_multiset_of_splits {f : K[X]} : splits i f → ∃ (s : multiset L), f.map i = C (i f.leading_coeff) * (s.map (λ a : L, (X : L[X]) - C a)).prod := suffices splits (ring_hom.id _) (f.map i) → ∃ s : multiset L, f.map i = (C (f.map i).leading_coeff) * (s.map (λ a : L, (X : L[X]) - C a)).prod, by rwa [splits_map_iff, leading_coeff_map i] at this, wf_dvd_monoid.induction_on_irreducible (f.map i) (λ _, ⟨{37}, by simp [i.map_zero]⟩) (λ u hu _, ⟨0, by conv_lhs { rw eq_C_of_degree_eq_zero (is_unit_iff_degree_eq_zero.1 hu) }; simp [leading_coeff, nat_degree_eq_of_degree_eq_some (is_unit_iff_degree_eq_zero.1 hu)]⟩) (λ f p hf0 hp ih hfs, have hpf0 : p * f ≠ 0, from mul_ne_zero hp.ne_zero hf0, let ⟨s, hs⟩ := ih (splits_of_splits_mul _ hpf0 hfs).2 in ⟨-(p * norm_unit p).coeff 0 ::ₘ s, have hp1 : degree p = 1, from hfs.resolve_left hpf0 hp (by simp), begin rw [multiset.map_cons, multiset.prod_cons, leading_coeff_mul, C_mul, mul_assoc, mul_left_comm (C f.leading_coeff), ← hs, ← mul_assoc, mul_left_inj' hf0], conv_lhs {rw eq_X_add_C_of_degree_eq_one hp1}, simp only [mul_add, coe_norm_unit_of_ne_zero hp.ne_zero, mul_comm p, coeff_neg, C_neg, sub_eq_add_neg, neg_neg, coeff_C_mul, (mul_assoc _ _ _).symm, C_mul.symm, mul_inv_cancel (show p.leading_coeff ≠ 0, from mt leading_coeff_eq_zero.1 hp.ne_zero), one_mul], end⟩) /-- Pick a root of a polynomial that splits. -/ def root_of_splits {f : K[X]} (hf : f.splits i) (hfd : f.degree ≠ 0) : L := classical.some $ exists_root_of_splits i hf hfd theorem map_root_of_splits {f : K[X]} (hf : f.splits i) (hfd) : f.eval₂ i (root_of_splits i hf hfd) = 0 := classical.some_spec $ exists_root_of_splits i hf hfd theorem roots_map {f : K[X]} (hf : f.splits $ ring_hom.id K) : (f.map i).roots = (f.roots).map i := if hf0 : f = 0 then by rw [hf0, polynomial.map_zero, roots_zero, roots_zero, multiset.map_zero] else have hmf0 : f.map i ≠ 0 := map_ne_zero hf0, let ⟨m, hm⟩ := exists_multiset_of_splits _ hf in have h1 : (0 : K[X]) ∉ m.map (λ r, X - C r), from zero_nmem_multiset_map_X_sub_C _ _, have h2 : (0 : L[X]) ∉ m.map (λ r, X - C (i r)), from zero_nmem_multiset_map_X_sub_C _ _, begin rw map_id at hm, rw hm at hf0 hmf0 ⊢, rw polynomial.map_mul at hmf0 ⊢, rw [roots_mul hf0, roots_mul hmf0, map_C, roots_C, zero_add, roots_C, zero_add, polynomial.map_multiset_prod, multiset.map_map], simp_rw [(∘), polynomial.map_sub, map_X, map_C], rw [roots_multiset_prod _ h2, multiset.bind_map, roots_multiset_prod _ h1, multiset.bind_map], simp_rw roots_X_sub_C, rw [multiset.bind_singleton, multiset.bind_singleton, multiset.map_id'] end lemma eq_prod_roots_of_splits {p : K[X]} {i : K →+* L} (hsplit : splits i p) : p.map i = C (i p.leading_coeff) * ((p.map i).roots.map (λ a, X - C a)).prod := begin by_cases p_eq_zero : p = 0, { rw [p_eq_zero, polynomial.map_zero, leading_coeff_zero, i.map_zero, C.map_zero, zero_mul] }, obtain ⟨s, hs⟩ := exists_multiset_of_splits i hsplit, have map_ne_zero : p.map i ≠ 0 := map_ne_zero (p_eq_zero), have prod_ne_zero : C (i p.leading_coeff) * (multiset.map (λ a, X - C a) s).prod ≠ 0 := by rwa hs at map_ne_zero, have zero_nmem : (0 : L[X]) ∉ s.map (λ a, X - C a), from zero_nmem_multiset_map_X_sub_C _ _, have map_bind_roots_eq : (s.map (λ a, X - C a)).bind (λ a, a.roots) = s, { refine multiset.induction_on s (by rw [multiset.map_zero, multiset.zero_bind]) _, intros a s ih, rw [multiset.map_cons, multiset.cons_bind, ih, roots_X_sub_C, multiset.singleton_add] }, rw [hs, roots_mul prod_ne_zero, roots_C, zero_add, roots_multiset_prod _ zero_nmem, map_bind_roots_eq] end lemma eq_prod_roots_of_splits_id {p : K[X]} (hsplit : splits (ring_hom.id K) p) : p = C (p.leading_coeff) * (p.roots.map (λ a, X - C a)).prod := by simpa using eq_prod_roots_of_splits hsplit lemma eq_prod_roots_of_monic_of_splits_id {p : K[X]} (m : monic p) (hsplit : splits (ring_hom.id K) p) : p = (p.roots.map (λ a, X - C a)).prod := begin convert eq_prod_roots_of_splits_id hsplit, simp [m], end lemma eq_X_sub_C_of_splits_of_single_root {x : K} {h : K[X]} (h_splits : splits i h) (h_roots : (h.map i).roots = {i x}) : h = (C (leading_coeff h)) * (X - C x) := begin apply polynomial.map_injective _ i.injective, rw [eq_prod_roots_of_splits h_splits, h_roots], simp, end lemma nat_degree_eq_card_roots {p : K[X]} {i : K →+* L} (hsplit : splits i p) : p.nat_degree = (p.map i).roots.card := begin by_cases p_eq_zero : p = 0, { rw [p_eq_zero, nat_degree_zero, polynomial.map_zero, roots_zero, multiset.card_zero] }, have map_ne_zero : p.map i ≠ 0 := map_ne_zero (p_eq_zero), rw eq_prod_roots_of_splits hsplit at map_ne_zero, conv_lhs { rw [← nat_degree_map i, eq_prod_roots_of_splits hsplit] }, have : (0 : L[X]) ∉ (map i p).roots.map (λ a, X - C a), from zero_nmem_multiset_map_X_sub_C _ _, simp [nat_degree_mul (left_ne_zero_of_mul map_ne_zero) (right_ne_zero_of_mul map_ne_zero), nat_degree_multiset_prod _ this] end lemma degree_eq_card_roots {p : K[X]} {i : K →+* L} (p_ne_zero : p ≠ 0) (hsplit : splits i p) : p.degree = (p.map i).roots.card := by rw [degree_eq_nat_degree p_ne_zero, nat_degree_eq_card_roots hsplit] section UFD local attribute [instance, priority 10] principal_ideal_ring.to_unique_factorization_monoid local infix ` ~ᵤ ` : 50 := associated open unique_factorization_monoid associates lemma splits_of_exists_multiset {f : K[X]} {s : multiset L} (hs : f.map i = C (i f.leading_coeff) * (s.map (λ a : L, (X : L[X]) - C a)).prod) : splits i f := if hf0 : f = 0 then or.inl hf0 else or.inr $ λ p hp hdp, have ht : multiset.rel associated (normalized_factors (f.map i)) (s.map (λ a : L, (X : L[X]) - C a)) := factors_unique (λ p hp, irreducible_of_normalized_factor _ hp) (λ p' m, begin obtain ⟨a,m,rfl⟩ := multiset.mem_map.1 m, exact irreducible_of_degree_eq_one (degree_X_sub_C _), end) (associated.symm $ calc _ ~ᵤ f.map i : ⟨(units.map C.to_monoid_hom : Lˣ →* (polynomial L)ˣ) (units.mk0 (f.map i).leading_coeff (mt leading_coeff_eq_zero.1 (map_ne_zero hf0))), by conv_rhs { rw [hs, ← leading_coeff_map i, mul_comm] }; refl⟩ ... ~ᵤ _ : (unique_factorization_monoid.normalized_factors_prod (by simpa using hf0)).symm), let ⟨q, hq, hpq⟩ := exists_mem_normalized_factors_of_dvd (by simpa) hp hdp in let ⟨q', hq', hqq'⟩ := multiset.exists_mem_of_rel_of_mem ht hq in let ⟨a, ha⟩ := multiset.mem_map.1 hq' in by rw [← degree_X_sub_C a, ha.2]; exact degree_eq_degree_of_associated (hpq.trans hqq') lemma splits_of_splits_id {f : K[X]} : splits (ring_hom.id _) f → splits i f := unique_factorization_monoid.induction_on_prime f (λ _, splits_zero _) (λ _ hu _, splits_of_degree_le_one _ ((is_unit_iff_degree_eq_zero.1 hu).symm ▸ dec_trivial)) (λ a p ha0 hp ih hfi, splits_mul _ (splits_of_degree_eq_one _ ((splits_of_splits_mul _ (mul_ne_zero hp.1 ha0) hfi).1.resolve_left hp.1 hp.irreducible (by rw map_id))) (ih (splits_of_splits_mul _ (mul_ne_zero hp.1 ha0) hfi).2)) end UFD lemma splits_iff_exists_multiset {f : K[X]} : splits i f ↔ ∃ (s : multiset L), f.map i = C (i f.leading_coeff) * (s.map (λ a : L, (X : L[X]) - C a)).prod := ⟨exists_multiset_of_splits i, λ ⟨s, hs⟩, splits_of_exists_multiset i hs⟩ lemma splits_comp_of_splits (j : L →+* F) {f : K[X]} (h : splits i f) : splits (j.comp i) f := begin change i with ((ring_hom.id _).comp i) at h, rw [← splits_map_iff], rw [← splits_map_iff i] at h, exact splits_of_splits_id _ h end /-- A monic polynomial `p` that has as many roots as its degree can be written `p = ∏(X - a)`, for `a` in `p.roots`. -/ private lemma prod_multiset_X_sub_C_of_monic_of_roots_card_eq_of_field {p : K[X]} (hmonic : p.monic) (hroots : p.roots.card = p.nat_degree) : (multiset.map (λ (a : K), X - C a) p.roots).prod = p := begin have hprodmonic : (multiset.map (λ (a : K), X - C a) p.roots).prod.monic, { simp only [prod_multiset_root_eq_finset_root, monic_prod_of_monic, monic_X_sub_C, monic.pow, forall_true_iff] }, have hdegree : (multiset.map (λ (a : K), X - C a) p.roots).prod.nat_degree = p.nat_degree, { rw [← hroots, nat_degree_multiset_prod _ (zero_nmem_multiset_map_X_sub_C _ (λ a : K, a))], simp only [eq_self_iff_true, mul_one, nat.cast_id, nsmul_eq_mul, multiset.sum_repeat, multiset.map_const,nat_degree_X_sub_C, function.comp, multiset.map_map] }, obtain ⟨q, hq⟩ := prod_multiset_X_sub_C_dvd p, have qzero : q ≠ 0, { rintro rfl, apply hmonic.ne_zero, simpa only [mul_zero] using hq }, have degp : p.nat_degree = (multiset.map (λ (a : K), X - C a) p.roots).prod.nat_degree + q.nat_degree, { nth_rewrite 0 [hq], simp only [nat_degree_mul hprodmonic.ne_zero qzero] }, have degq : q.nat_degree = 0, { rw hdegree at degp, rw [← add_right_inj p.nat_degree, ← degp, add_zero], }, obtain ⟨u, hu⟩ := is_unit_iff_degree_eq_zero.2 ((degree_eq_iff_nat_degree_eq qzero).2 degq), have hassoc : associated (multiset.map (λ (a : K), X - C a) p.roots).prod p, { rw associated, use u, rw [hu, ← hq] }, exact eq_of_monic_of_associated hprodmonic hmonic hassoc end lemma prod_multiset_X_sub_C_of_monic_of_roots_card_eq {K : Type*} [comm_ring K] [is_domain K] {p : K[X]} (hmonic : p.monic) (hroots : p.roots.card = p.nat_degree) : (multiset.map (λ (a : K), X - C a) p.roots).prod = p := begin apply map_injective _ (is_fraction_ring.injective K (fraction_ring K)), rw polynomial.map_multiset_prod, simp only [map_C, function.comp_app, map_X, multiset.map_map, polynomial.map_sub], have : p.roots.map (algebra_map K (fraction_ring K)) = (map (algebra_map K (fraction_ring K)) p).roots := roots_map_of_injective_card_eq_total_degree (is_fraction_ring.injective K (fraction_ring K)) hroots, rw ← prod_multiset_X_sub_C_of_monic_of_roots_card_eq_of_field (hmonic.map (algebra_map K (fraction_ring K))), { simp only [map_C, function.comp_app, map_X, polynomial.map_sub], congr' 1, rw ← this, simp, }, { rw [nat_degree_map_eq_of_injective (is_fraction_ring.injective K (fraction_ring K)), ← this], simp only [←hroots, multiset.card_map], }, end /-- A polynomial `p` that has as many roots as its degree can be written `p = p.leading_coeff * ∏(X - a)`, for `a` in `p.roots`. Used to prove the more general `C_leading_coeff_mul_prod_multiset_X_sub_C` below. -/ private lemma C_leading_coeff_mul_prod_multiset_X_sub_C_of_field {p : K[X]} (hroots : p.roots.card = p.nat_degree) : C p.leading_coeff * (multiset.map (λ (a : K), X - C a) p.roots).prod = p := begin by_cases hzero : p = 0, { rw [hzero, leading_coeff_zero, ring_hom.map_zero, zero_mul], }, { have hcoeff : p.leading_coeff ≠ 0, { intro h, exact hzero (leading_coeff_eq_zero.1 h) }, have hrootsnorm : (normalize p).roots.card = (normalize p).nat_degree, { rw [roots_normalize, normalize_apply, nat_degree_mul hzero (units.ne_zero _), hroots, coe_norm_unit, nat_degree_C, add_zero], }, have hprod := prod_multiset_X_sub_C_of_monic_of_roots_card_eq (monic_normalize hzero) hrootsnorm, rw [roots_normalize, normalize_apply, coe_norm_unit_of_ne_zero hzero] at hprod, calc (C p.leading_coeff) * (multiset.map (λ (a : K), X - C a) p.roots).prod = p * C ((p.leading_coeff)⁻¹ * p.leading_coeff) : by rw [hprod, mul_comm, mul_assoc, ← C_mul] ... = p * C 1 : by field_simp ... = p : by simp only [mul_one, ring_hom.map_one], }, end /-- A polynomial `p` that has as many roots as its degree can be written `p = p.leading_coeff * ∏(X - a)`, for `a` in `p.roots`. -/ lemma C_leading_coeff_mul_prod_multiset_X_sub_C {K : Type*} [comm_ring K] [is_domain K] {p : K[X]} (hroots : p.roots.card = p.nat_degree) : C p.leading_coeff * (multiset.map (λ (a : K), X - C a) p.roots).prod = p := begin by_cases hzero : p = 0, { rw [hzero, leading_coeff_zero, ring_hom.map_zero, zero_mul], }, have hcoeff : p.leading_coeff ≠ 0, { intro h, exact hzero (leading_coeff_eq_zero.1 h) }, apply map_injective _ (is_fraction_ring.injective K (fraction_ring K)), rw [polynomial.map_mul, polynomial.map_multiset_prod], simp only [map_C, function.comp_app, map_X, multiset.map_map, polynomial.map_sub], have h : p.roots.map (algebra_map K (fraction_ring K)) = (map (algebra_map K (fraction_ring K)) p).roots := roots_map_of_injective_card_eq_total_degree (is_fraction_ring.injective K (fraction_ring K)) hroots, have : multiset.card (map (algebra_map K (fraction_ring K)) p).roots = (map (algebra_map K (fraction_ring K)) p).nat_degree, { rw [nat_degree_map_eq_of_injective (is_fraction_ring.injective K (fraction_ring K)), ← h], simp only [←hroots, multiset.card_map], }, rw [← C_leading_coeff_mul_prod_multiset_X_sub_C_of_field this], simp only [map_C, function.comp_app, map_X, polynomial.map_sub], have w : (algebra_map K (fraction_ring K)) p.leading_coeff ≠ 0, { intro hn, apply hcoeff, apply is_fraction_ring.injective K (fraction_ring K), simp [hn], }, rw [←h, leading_coeff_map_of_leading_coeff_ne_zero _ w, multiset.map_map], end /-- A polynomial splits if and only if it has as many roots as its degree. -/ lemma splits_iff_card_roots {p : K[X]} : splits (ring_hom.id K) p ↔ p.roots.card = p.nat_degree := begin split, { intro H, rw [nat_degree_eq_card_roots H, map_id] }, { intro hroots, apply (splits_iff_exists_multiset (ring_hom.id K)).2, use p.roots, simp only [ring_hom.id_apply, map_id], exact (C_leading_coeff_mul_prod_multiset_X_sub_C hroots).symm }, end lemma aeval_root_derivative_of_splits [algebra K L] {P : K[X]} (hmo : P.monic) (hP : P.splits (algebra_map K L)) {r : L} (hr : r ∈ (P.map (algebra_map K L)).roots) : aeval r P.derivative = (multiset.map (λ a, r - a) ((P.map (algebra_map K L)).roots.erase r)).prod := begin replace hmo := hmo.map (algebra_map K L), replace hP := (splits_id_iff_splits (algebra_map K L)).2 hP, rw [aeval_def, ← eval_map, ← derivative_map], nth_rewrite 0 [eq_prod_roots_of_monic_of_splits_id hmo hP], rw [eval_multiset_prod_X_sub_C_derivative hr] end /-- If `P` is a monic polynomial that splits, then `coeff P 0` equals the product of the roots. -/ lemma prod_roots_eq_coeff_zero_of_monic_of_split {P : K[X]} (hmo : P.monic) (hP : P.splits (ring_hom.id K)) : coeff P 0 = (-1) ^ P.nat_degree * P.roots.prod := begin nth_rewrite 0 [eq_prod_roots_of_monic_of_splits_id hmo hP], rw [coeff_zero_eq_eval_zero, eval_multiset_prod, multiset.map_map], simp_rw [function.comp_app, eval_sub, eval_X, zero_sub, eval_C], conv_lhs { congr, congr, funext, rw [neg_eq_neg_one_mul] }, rw [multiset.prod_map_mul, multiset.map_const, multiset.prod_repeat, multiset.map_id', splits_iff_card_roots.1 hP] end /-- If `P` is a monic polynomial that splits, then `P.next_coeff` equals the sum of the roots. -/ lemma sum_roots_eq_next_coeff_of_monic_of_split {P : K[X]} (hmo : P.monic) (hP : P.splits (ring_hom.id K)) : P.next_coeff = - P.roots.sum := begin nth_rewrite 0 [eq_prod_roots_of_monic_of_splits_id hmo hP], rw [monic.next_coeff_multiset_prod _ _ (λ a ha, _)], { simp_rw [next_coeff_X_sub_C, multiset.sum_map_neg] }, { exact monic_X_sub_C a } end end splits end polynomial section embeddings variables (F) [field F] /-- If `p` is the minimal polynomial of `a` over `F` then `F[a] ≃ₐ[F] F[x]/(p)` -/ def alg_equiv.adjoin_singleton_equiv_adjoin_root_minpoly {R : Type*} [comm_ring R] [algebra F R] (x : R) : algebra.adjoin F ({x} : set R) ≃ₐ[F] adjoin_root (minpoly F x) := alg_equiv.symm $ alg_equiv.of_bijective (alg_hom.cod_restrict (adjoin_root.lift_hom _ x $ minpoly.aeval F x) _ (λ p, adjoin_root.induction_on _ p $ λ p, (algebra.adjoin_singleton_eq_range_aeval F x).symm ▸ (polynomial.aeval _).mem_range.mpr ⟨p, rfl⟩)) ⟨(alg_hom.injective_cod_restrict _ _ _).2 $ (injective_iff_map_eq_zero _).2 $ λ p, adjoin_root.induction_on _ p $ λ p hp, ideal.quotient.eq_zero_iff_mem.2 $ ideal.mem_span_singleton.2 $ minpoly.dvd F x hp, λ y, let ⟨p, hp⟩ := (set_like.ext_iff.1 (algebra.adjoin_singleton_eq_range_aeval F x) (y : R)).1 y.2 in ⟨adjoin_root.mk _ p, subtype.eq hp⟩⟩ open finset /-- If a `subalgebra` is finite_dimensional as a submodule then it is `finite_dimensional`. -/ lemma finite_dimensional.of_subalgebra_to_submodule {K V : Type*} [field K] [ring V] [algebra K V] {s : subalgebra K V} (h : finite_dimensional K s.to_submodule) : finite_dimensional K s := h /-- If `K` and `L` are field extensions of `F` and we have `s : finset K` such that the minimal polynomial of each `x ∈ s` splits in `L` then `algebra.adjoin F s` embeds in `L`. -/ theorem lift_of_splits {F K L : Type*} [field F] [field K] [field L] [algebra F K] [algebra F L] (s : finset K) : (∀ x ∈ s, is_integral F x ∧ polynomial.splits (algebra_map F L) (minpoly F x)) → nonempty (algebra.adjoin F (↑s : set K) →ₐ[F] L) := begin refine finset.induction_on s (λ H, _) (λ a s has ih H, _), { rw [coe_empty, algebra.adjoin_empty], exact ⟨(algebra.of_id F L).comp (algebra.bot_equiv F K)⟩ }, rw forall_mem_insert at H, rcases H with ⟨⟨H1, H2⟩, H3⟩, cases ih H3 with f, choose H3 H4 using H3, rw [coe_insert, set.insert_eq, set.union_comm, algebra.adjoin_union_eq_adjoin_adjoin], letI := (f : algebra.adjoin F (↑s : set K) →+* L).to_algebra, haveI : finite_dimensional F (algebra.adjoin F (↑s : set K)) := ( (submodule.fg_iff_finite_dimensional _).1 (fg_adjoin_of_finite (set.finite_mem_finset s) H3)).of_subalgebra_to_submodule, letI := field_of_finite_dimensional F (algebra.adjoin F (↑s : set K)), have H5 : is_integral (algebra.adjoin F (↑s : set K)) a := is_integral_of_is_scalar_tower a H1, have H6 : (minpoly (algebra.adjoin F (↑s : set K)) a).splits (algebra_map (algebra.adjoin F (↑s : set K)) L), { refine polynomial.splits_of_splits_of_dvd _ (polynomial.map_ne_zero $ minpoly.ne_zero H1 : polynomial.map (algebra_map _ _) _ ≠ 0) ((polynomial.splits_map_iff _ _).2 _) (minpoly.dvd _ _ _), { rw ← is_scalar_tower.algebra_map_eq, exact H2 }, { rw [← is_scalar_tower.aeval_apply, minpoly.aeval] } }, obtain ⟨y, hy⟩ := polynomial.exists_root_of_splits _ H6 (ne_of_lt (minpoly.degree_pos H5)).symm, refine ⟨subalgebra.of_restrict_scalars _ _ _⟩, refine (adjoin_root.lift_hom (minpoly (algebra.adjoin F (↑s : set K)) a) y hy).comp _, exact alg_equiv.adjoin_singleton_equiv_adjoin_root_minpoly (algebra.adjoin F (↑s : set K)) a end end embeddings namespace polynomial variables [field K] [field L] [field F] open polynomial section splitting_field /-- Non-computably choose an irreducible factor from a polynomial. -/ def factor (f : K[X]) : K[X] := if H : ∃ g, irreducible g ∧ g ∣ f then classical.some H else X instance irreducible_factor (f : K[X]) : irreducible (factor f) := begin rw factor, split_ifs with H, { exact (classical.some_spec H).1 }, { exact irreducible_X } end theorem factor_dvd_of_not_is_unit {f : K[X]} (hf1 : ¬is_unit f) : factor f ∣ f := begin by_cases hf2 : f = 0, { rw hf2, exact dvd_zero _ }, rw [factor, dif_pos (wf_dvd_monoid.exists_irreducible_factor hf1 hf2)], exact (classical.some_spec $ wf_dvd_monoid.exists_irreducible_factor hf1 hf2).2 end theorem factor_dvd_of_degree_ne_zero {f : K[X]} (hf : f.degree ≠ 0) : factor f ∣ f := factor_dvd_of_not_is_unit (mt degree_eq_zero_of_is_unit hf) theorem factor_dvd_of_nat_degree_ne_zero {f : K[X]} (hf : f.nat_degree ≠ 0) : factor f ∣ f := factor_dvd_of_degree_ne_zero (mt nat_degree_eq_of_degree_eq_some hf) /-- Divide a polynomial f by X - C r where r is a root of f in a bigger field extension. -/ def remove_factor (f : K[X]) : polynomial (adjoin_root $ factor f) := map (adjoin_root.of f.factor) f /ₘ (X - C (adjoin_root.root f.factor)) theorem X_sub_C_mul_remove_factor (f : K[X]) (hf : f.nat_degree ≠ 0) : (X - C (adjoin_root.root f.factor)) * f.remove_factor = map (adjoin_root.of f.factor) f := let ⟨g, hg⟩ := factor_dvd_of_nat_degree_ne_zero hf in mul_div_by_monic_eq_iff_is_root.2 $ by rw [is_root.def, eval_map, hg, eval₂_mul, ← hg, adjoin_root.eval₂_root, zero_mul] theorem nat_degree_remove_factor (f : K[X]) : f.remove_factor.nat_degree = f.nat_degree - 1 := by rw [remove_factor, nat_degree_div_by_monic _ (monic_X_sub_C _), nat_degree_map, nat_degree_X_sub_C] theorem nat_degree_remove_factor' {f : K[X]} {n : ℕ} (hfn : f.nat_degree = n+1) : f.remove_factor.nat_degree = n := by rw [nat_degree_remove_factor, hfn, n.add_sub_cancel] /-- Auxiliary construction to a splitting field of a polynomial. Uses induction on the degree. -/ def splitting_field_aux (n : ℕ) : Π {K : Type u} [field K], by exactI Π (f : K[X]), f.nat_degree = n → Type u := nat.rec_on n (λ K _ _ _, K) $ λ n ih K _ f hf, by exactI ih f.remove_factor (nat_degree_remove_factor' hf) namespace splitting_field_aux theorem succ (n : ℕ) (f : K[X]) (hfn : f.nat_degree = n + 1) : splitting_field_aux (n+1) f hfn = splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn) := rfl instance field (n : ℕ) : Π {K : Type u} [field K], by exactI Π {f : K[X]} (hfn : f.nat_degree = n), field (splitting_field_aux n f hfn) := nat.rec_on n (λ K _ _ _, ‹field K›) $ λ n ih K _ f hf, ih _ instance inhabited {n : ℕ} {f : K[X]} (hfn : f.nat_degree = n) : inhabited (splitting_field_aux n f hfn) := ⟨37⟩ /- Note that the recursive nature of this definition and `splitting_field_aux.field` creates non-definitionally-equal diamonds in the `ℕ`- and `ℤ`- actions. ```lean example (n : ℕ) {K : Type u} [field K] {f : K[X]} (hfn : f.nat_degree = n) : (add_comm_monoid.nat_module : module ℕ (splitting_field_aux n f hfn)) = @algebra.to_module _ _ _ _ (splitting_field_aux.algebra n _ hfn) := rfl -- fails ``` It's not immediately clear whether this _can_ be fixed; the failure is much the same as the reason that the following fails: ```lean def cases_twice {α} (a₀ aₙ : α) : ℕ → α × α | 0 := (a₀, a₀) | (n + 1) := (aₙ, aₙ) example (x : ℕ) {α} (a₀ aₙ : α) : (cases_twice a₀ aₙ x).1 = (cases_twice a₀ aₙ x).2 := rfl -- fails ``` We don't really care at this point because this is an implementation detail (which is why this is not a docstring), but we do in `splitting_field.algebra'` below. -/ instance algebra (n : ℕ) : Π (R : Type*) {K : Type u} [comm_semiring R] [field K], by exactI Π [algebra R K] {f : K[X]} (hfn : f.nat_degree = n), algebra R (splitting_field_aux n f hfn) := nat.rec_on n (λ R K _ _ _ _ _, by exactI ‹algebra R K›) $ λ n ih R K _ _ _ f hfn, by exactI ih R (nat_degree_remove_factor' hfn) instance is_scalar_tower (n : ℕ) : Π (R₁ R₂ : Type*) {K : Type u} [comm_semiring R₁] [comm_semiring R₂] [has_scalar R₁ R₂] [field K], by exactI Π [algebra R₁ K] [algebra R₂ K], by exactI Π [is_scalar_tower R₁ R₂ K] {f : K[X]} (hfn : f.nat_degree = n), is_scalar_tower R₁ R₂ (splitting_field_aux n f hfn) := nat.rec_on n (λ R₁ R₂ K _ _ _ _ _ _ _ _ _, by exactI ‹is_scalar_tower R₁ R₂ K›) $ λ n ih R₁ R₂ K _ _ _ _ _ _ _ f hfn, by exactI ih R₁ R₂ (nat_degree_remove_factor' hfn) instance algebra''' {n : ℕ} {f : K[X]} (hfn : f.nat_degree = n + 1) : algebra (adjoin_root f.factor) (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)) := splitting_field_aux.algebra n _ _ instance algebra' {n : ℕ} {f : K[X]} (hfn : f.nat_degree = n + 1) : algebra (adjoin_root f.factor) (splitting_field_aux n.succ f hfn) := splitting_field_aux.algebra''' _ instance algebra'' {n : ℕ} {f : K[X]} (hfn : f.nat_degree = n + 1) : algebra K (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)) := splitting_field_aux.algebra n K _ instance scalar_tower' {n : ℕ} {f : K[X]} (hfn : f.nat_degree = n + 1) : is_scalar_tower K (adjoin_root f.factor) (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)) := begin -- finding this instance ourselves makes things faster haveI : is_scalar_tower K (adjoin_root f.factor) (adjoin_root f.factor) := is_scalar_tower.right, exact splitting_field_aux.is_scalar_tower n K (adjoin_root f.factor) (nat_degree_remove_factor' hfn), end instance scalar_tower {n : ℕ} {f : K[X]} (hfn : f.nat_degree = n + 1) : is_scalar_tower K (adjoin_root f.factor) (splitting_field_aux _ f hfn) := splitting_field_aux.scalar_tower' _ theorem algebra_map_succ (n : ℕ) (f : K[X]) (hfn : f.nat_degree = n + 1) : by exact algebra_map K (splitting_field_aux _ _ hfn) = (algebra_map (adjoin_root f.factor) (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn))).comp (adjoin_root.of f.factor) := is_scalar_tower.algebra_map_eq _ _ _ protected theorem splits (n : ℕ) : ∀ {K : Type u} [field K], by exactI ∀ (f : K[X]) (hfn : f.nat_degree = n), splits (algebra_map K $ splitting_field_aux n f hfn) f := nat.rec_on n (λ K _ _ hf, by exactI splits_of_degree_le_one _ (le_trans degree_le_nat_degree $ hf.symm ▸ with_bot.coe_le_coe.2 zero_le_one)) $ λ n ih K _ f hf, by { resetI, rw [← splits_id_iff_splits, algebra_map_succ, ← map_map, splits_id_iff_splits, ← X_sub_C_mul_remove_factor f (λ h, by { rw h at hf, cases hf })], exact splits_mul _ (splits_X_sub_C _) (ih _ _) } theorem exists_lift (n : ℕ) : ∀ {K : Type u} [field K], by exactI ∀ (f : K[X]) (hfn : f.nat_degree = n) {L : Type*} [field L], by exactI ∀ (j : K →+* L) (hf : splits j f), ∃ k : splitting_field_aux n f hfn →+* L, k.comp (algebra_map _ _) = j := nat.rec_on n (λ K _ _ _ L _ j _, by exactI ⟨j, j.comp_id⟩) $ λ n ih K _ f hf L _ j hj, by exactI have hndf : f.nat_degree ≠ 0, by { intro h, rw h at hf, cases hf }, have hfn0 : f ≠ 0, by { intro h, rw h at hndf, exact hndf rfl }, let ⟨r, hr⟩ := exists_root_of_splits _ (splits_of_splits_of_dvd j hfn0 hj (factor_dvd_of_nat_degree_ne_zero hndf)) (mt is_unit_iff_degree_eq_zero.2 f.irreducible_factor.1) in have hmf0 : map (adjoin_root.of f.factor) f ≠ 0, from map_ne_zero hfn0, have hsf : splits (adjoin_root.lift j r hr) f.remove_factor, by { rw ← X_sub_C_mul_remove_factor _ hndf at hmf0, refine (splits_of_splits_mul _ hmf0 _).2, rwa [X_sub_C_mul_remove_factor _ hndf, ← splits_id_iff_splits, map_map, adjoin_root.lift_comp_of, splits_id_iff_splits] }, let ⟨k, hk⟩ := ih f.remove_factor (nat_degree_remove_factor' hf) (adjoin_root.lift j r hr) hsf in ⟨k, by rw [algebra_map_succ, ← ring_hom.comp_assoc, hk, adjoin_root.lift_comp_of]⟩ theorem adjoin_roots (n : ℕ) : ∀ {K : Type u} [field K], by exactI ∀ (f : K[X]) (hfn : f.nat_degree = n), algebra.adjoin K (↑(f.map $ algebra_map K $ splitting_field_aux n f hfn).roots.to_finset : set (splitting_field_aux n f hfn)) = ⊤ := nat.rec_on n (λ K _ f hf, by exactI algebra.eq_top_iff.2 (λ x, subalgebra.range_le _ ⟨x, rfl⟩)) $ λ n ih K _ f hfn, by exactI have hndf : f.nat_degree ≠ 0, by { intro h, rw h at hfn, cases hfn }, have hfn0 : f ≠ 0, by { intro h, rw h at hndf, exact hndf rfl }, have hmf0 : map (algebra_map K (splitting_field_aux n.succ f hfn)) f ≠ 0 := map_ne_zero hfn0, by { rw [algebra_map_succ, ← map_map, ← X_sub_C_mul_remove_factor _ hndf, polynomial.map_mul] at hmf0 ⊢, rw [roots_mul hmf0, polynomial.map_sub, map_X, map_C, roots_X_sub_C, multiset.to_finset_add, finset.coe_union, multiset.to_finset_singleton, finset.coe_singleton, algebra.adjoin_union_eq_adjoin_adjoin, ← set.image_singleton, algebra.adjoin_algebra_map K (adjoin_root f.factor) (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)), adjoin_root.adjoin_root_eq_top, algebra.map_top, is_scalar_tower.adjoin_range_to_alg_hom K (adjoin_root f.factor) (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)), ih, subalgebra.restrict_scalars_top] } end splitting_field_aux /-- A splitting field of a polynomial. -/ def splitting_field (f : K[X]) := splitting_field_aux _ f rfl namespace splitting_field variables (f : K[X]) instance : field (splitting_field f) := splitting_field_aux.field _ _ instance inhabited : inhabited (splitting_field f) := ⟨37⟩ /-- This should be an instance globally, but it creates diamonds with the `ℕ` and `ℤ` actions: ```lean example : (add_comm_monoid.nat_module : module ℕ (splitting_field f)) = @algebra.to_module _ _ _ _ (splitting_field.algebra' f) := rfl -- fails example : (add_comm_group.int_module _ : module ℤ (splitting_field f)) = @algebra.to_module _ _ _ _ (splitting_field.algebra' f) := rfl -- fails ``` Until we resolve these diamonds, it's more convenient to only turn this instance on with `local attribute [instance]` in places where the benefit of having the instance outweighs the cost. In the meantime, the `splitting_field.algebra` instance below is immune to these particular diamonds since `K = ℕ` and `K = ℤ` are not possible due to the `field K` assumption. Diamonds in `algebra ℚ (splitting_field f)` instances are still possible, but this is a problem throughout the library and not unique to this `algebra` instance. -/ instance algebra' {R} [comm_semiring R] [algebra R K] : algebra R (splitting_field f) := splitting_field_aux.algebra _ _ _ instance : algebra K (splitting_field f) := splitting_field_aux.algebra _ _ _ protected theorem splits : splits (algebra_map K (splitting_field f)) f := splitting_field_aux.splits _ _ _ variables [algebra K L] (hb : splits (algebra_map K L) f) /-- Embeds the splitting field into any other field that splits the polynomial. -/ def lift : splitting_field f →ₐ[K] L := { commutes' := λ r, by { have := classical.some_spec (splitting_field_aux.exists_lift _ _ _ _ hb), exact ring_hom.ext_iff.1 this r }, .. classical.some (splitting_field_aux.exists_lift _ _ _ _ hb) } theorem adjoin_roots : algebra.adjoin K (↑(f.map (algebra_map K $ splitting_field f)).roots.to_finset : set (splitting_field f)) = ⊤ := splitting_field_aux.adjoin_roots _ _ _ theorem adjoin_root_set : algebra.adjoin K (f.root_set f.splitting_field) = ⊤ := adjoin_roots f end splitting_field variables (K L) [algebra K L] /-- Typeclass characterising splitting fields. -/ class is_splitting_field (f : K[X]) : Prop := (splits [] : splits (algebra_map K L) f) (adjoin_roots [] : algebra.adjoin K (↑(f.map (algebra_map K L)).roots.to_finset : set L) = ⊤) namespace is_splitting_field variables {K} instance splitting_field (f : K[X]) : is_splitting_field K (splitting_field f) f := ⟨splitting_field.splits f, splitting_field.adjoin_roots f⟩ section scalar_tower variables {K L F} [algebra F K] [algebra F L] [is_scalar_tower F K L] variables {K} instance map (f : F[X]) [is_splitting_field F L f] : is_splitting_field K L (f.map $ algebra_map F K) := ⟨by { rw [splits_map_iff, ← is_scalar_tower.algebra_map_eq], exact splits L f }, subalgebra.restrict_scalars_injective F $ by { rw [map_map, ← is_scalar_tower.algebra_map_eq, subalgebra.restrict_scalars_top, eq_top_iff, ← adjoin_roots L f, algebra.adjoin_le_iff], exact λ x hx, @algebra.subset_adjoin K _ _ _ _ _ _ hx }⟩ variables {K} (L) theorem splits_iff (f : K[X]) [is_splitting_field K L f] : polynomial.splits (ring_hom.id K) f ↔ (⊤ : subalgebra K L) = ⊥ := ⟨λ h, eq_bot_iff.2 $ adjoin_roots L f ▸ (roots_map (algebra_map K L) h).symm ▸ algebra.adjoin_le_iff.2 (λ y hy, let ⟨x, hxs, hxy⟩ := finset.mem_image.1 (by rwa multiset.to_finset_map at hy) in hxy ▸ set_like.mem_coe.2 $ subalgebra.algebra_map_mem _ _), λ h, @ring_equiv.to_ring_hom_refl K _ ▸ ring_equiv.self_trans_symm (ring_equiv.of_bijective _ $ algebra.bijective_algebra_map_iff.2 h) ▸ by { rw ring_equiv.to_ring_hom_trans, exact splits_comp_of_splits _ _ (splits L f) }⟩ theorem mul (f g : F[X]) (hf : f ≠ 0) (hg : g ≠ 0) [is_splitting_field F K f] [is_splitting_field K L (g.map $ algebra_map F K)] : is_splitting_field F L (f * g) := ⟨(is_scalar_tower.algebra_map_eq F K L).symm ▸ splits_mul _ (splits_comp_of_splits _ _ (splits K f)) ((splits_map_iff _ _).1 (splits L $ g.map $ algebra_map F K)), by rw [polynomial.map_mul, roots_mul (mul_ne_zero (map_ne_zero hf : f.map (algebra_map F L) ≠ 0) (map_ne_zero hg)), multiset.to_finset_add, finset.coe_union, algebra.adjoin_union_eq_adjoin_adjoin, is_scalar_tower.algebra_map_eq F K L, ← map_map, roots_map (algebra_map K L) ((splits_id_iff_splits $ algebra_map F K).2 $ splits K f), multiset.to_finset_map, finset.coe_image, algebra.adjoin_algebra_map, adjoin_roots, algebra.map_top, is_scalar_tower.adjoin_range_to_alg_hom, ← map_map, adjoin_roots, subalgebra.restrict_scalars_top]⟩ end scalar_tower /-- Splitting field of `f` embeds into any field that splits `f`. -/ def lift [algebra K F] (f : K[X]) [is_splitting_field K L f] (hf : polynomial.splits (algebra_map K F) f) : L →ₐ[K] F := if hf0 : f = 0 then (algebra.of_id K F).comp $ (algebra.bot_equiv K L : (⊥ : subalgebra K L) →ₐ[K] K).comp $ by { rw ← (splits_iff L f).1 (show f.splits (ring_hom.id K), from hf0.symm ▸ splits_zero _), exact algebra.to_top } else alg_hom.comp (by { rw ← adjoin_roots L f, exact classical.choice (lift_of_splits _ $ λ y hy, have aeval y f = 0, from (eval₂_eq_eval_map _).trans $ (mem_roots $ by exact map_ne_zero hf0).1 (multiset.mem_to_finset.mp hy), ⟨is_algebraic_iff_is_integral.1 ⟨f, hf0, this⟩, splits_of_splits_of_dvd _ hf0 hf $ minpoly.dvd _ _ this⟩) }) algebra.to_top theorem finite_dimensional (f : K[X]) [is_splitting_field K L f] : finite_dimensional K L := ⟨@algebra.top_to_submodule K L _ _ _ ▸ adjoin_roots L f ▸ fg_adjoin_of_finite (set.finite_mem_finset _) (λ y hy, if hf : f = 0 then by { rw [hf, polynomial.map_zero, roots_zero] at hy, cases hy } else is_algebraic_iff_is_integral.1 ⟨f, hf, (eval₂_eq_eval_map _).trans $ (mem_roots $ by exact map_ne_zero hf).1 (multiset.mem_to_finset.mp hy)⟩)⟩ instance (f : K[X]) : _root_.finite_dimensional K f.splitting_field := finite_dimensional f.splitting_field f /-- Any splitting field is isomorphic to `splitting_field f`. -/ def alg_equiv (f : K[X]) [is_splitting_field K L f] : L ≃ₐ[K] splitting_field f := begin refine alg_equiv.of_bijective (lift L f $ splits (splitting_field f) f) ⟨ring_hom.injective (lift L f $ splits (splitting_field f) f).to_ring_hom, _⟩, haveI := finite_dimensional (splitting_field f) f, haveI := finite_dimensional L f, have : finite_dimensional.finrank K L = finite_dimensional.finrank K (splitting_field f) := le_antisymm (linear_map.finrank_le_finrank_of_injective (show function.injective (lift L f $ splits (splitting_field f) f).to_linear_map, from ring_hom.injective (lift L f $ splits (splitting_field f) f : L →+* f.splitting_field))) (linear_map.finrank_le_finrank_of_injective (show function.injective (lift (splitting_field f) f $ splits L f).to_linear_map, from ring_hom.injective (lift (splitting_field f) f $ splits L f : f.splitting_field →+* L))), change function.surjective (lift L f $ splits (splitting_field f) f).to_linear_map, refine (linear_map.injective_iff_surjective_of_finrank_eq_finrank this).1 _, exact ring_hom.injective (lift L f $ splits (splitting_field f) f : L →+* f.splitting_field) end end is_splitting_field end splitting_field end polynomial
78eb864058c5ae084df65c0fb058533ea495ccf9
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/list/intervals.lean
ae1a7dc237a70413ea6bc1f4459717d3e7b5c621
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
6,011
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.list.range import Mathlib.data.list.bag_inter import Mathlib.PostPort namespace Mathlib namespace list /-- `Ico n m` is the list of natural numbers `n ≤ x < m`. (Ico stands for "interval, closed-open".) See also `data/set/intervals.lean` for `set.Ico`, modelling intervals in general preorders, and `multiset.Ico` and `finset.Ico` for `n ≤ x < m` as a multiset or as a finset. @TODO (anyone): Define `Ioo` and `Icc`, state basic lemmas about them. @TODO (anyone): Also do the versions for integers? @TODO (anyone): One could generalise even further, defining 'locally finite partial orders', for which `set.Ico a b` is `[finite]`, and 'locally finite total orders', for which there is a list model. -/ def Ico (n : ℕ) (m : ℕ) : List ℕ := range' n (m - n) namespace Ico theorem zero_bot (n : ℕ) : Ico 0 n = range n := eq.mpr (id (Eq._oldrec (Eq.refl (Ico 0 n = range n)) (equations._eqn_1 0 n))) (eq.mpr (id (Eq._oldrec (Eq.refl (range' 0 (n - 0) = range n)) (nat.sub_zero n))) (eq.mpr (id (Eq._oldrec (Eq.refl (range' 0 n = range n)) (range_eq_range' n))) (Eq.refl (range' 0 n)))) @[simp] theorem length (n : ℕ) (m : ℕ) : length (Ico n m) = m - n := sorry theorem pairwise_lt (n : ℕ) (m : ℕ) : pairwise Less (Ico n m) := id (eq.mpr (id (propext ((fun (s n : ℕ) => iff_true_intro (pairwise_lt_range' s n)) n (m - n)))) trivial) theorem nodup (n : ℕ) (m : ℕ) : nodup (Ico n m) := id (eq.mpr (id (propext ((fun (s n : ℕ) => iff_true_intro (nodup_range' s n)) n (m - n)))) trivial) @[simp] theorem mem {n : ℕ} {m : ℕ} {l : ℕ} : l ∈ Ico n m ↔ n ≤ l ∧ l < m := sorry theorem eq_nil_of_le {n : ℕ} {m : ℕ} (h : m ≤ n) : Ico n m = [] := sorry theorem map_add (n : ℕ) (m : ℕ) (k : ℕ) : map (Add.add k) (Ico n m) = Ico (n + k) (m + k) := sorry theorem map_sub (n : ℕ) (m : ℕ) (k : ℕ) (h₁ : k ≤ n) : map (fun (x : ℕ) => x - k) (Ico n m) = Ico (n - k) (m - k) := sorry @[simp] theorem self_empty {n : ℕ} : Ico n n = [] := eq_nil_of_le (le_refl n) @[simp] theorem eq_empty_iff {n : ℕ} {m : ℕ} : Ico n m = [] ↔ m ≤ n := sorry theorem append_consecutive {n : ℕ} {m : ℕ} {l : ℕ} (hnm : n ≤ m) (hml : m ≤ l) : Ico n m ++ Ico m l = Ico n l := sorry @[simp] theorem inter_consecutive (n : ℕ) (m : ℕ) (l : ℕ) : Ico n m ∩ Ico m l = [] := sorry @[simp] theorem bag_inter_consecutive (n : ℕ) (m : ℕ) (l : ℕ) : list.bag_inter (Ico n m) (Ico m l) = [] := iff.mpr (bag_inter_nil_iff_inter_nil (Ico n m) (Ico m l)) (inter_consecutive n m l) @[simp] theorem succ_singleton {n : ℕ} : Ico n (n + 1) = [n] := sorry theorem succ_top {n : ℕ} {m : ℕ} (h : n ≤ m) : Ico n (m + 1) = Ico n m ++ [m] := eq.mpr (id (Eq._oldrec (Eq.refl (Ico n (m + 1) = Ico n m ++ [m])) (Eq.symm succ_singleton))) (eq.mpr (id (Eq._oldrec (Eq.refl (Ico n (m + 1) = Ico n m ++ Ico m (m + 1))) (append_consecutive h (nat.le_succ m)))) (Eq.refl (Ico n (m + 1)))) theorem eq_cons {n : ℕ} {m : ℕ} (h : n < m) : Ico n m = n :: Ico (n + 1) m := eq.mpr (id (Eq._oldrec (Eq.refl (Ico n m = n :: Ico (n + 1) m)) (Eq.symm (append_consecutive (nat.le_succ n) h)))) (eq.mpr (id (Eq._oldrec (Eq.refl (Ico n (Nat.succ n) ++ Ico (Nat.succ n) m = n :: Ico (n + 1) m)) succ_singleton)) (Eq.refl ([n] ++ Ico (Nat.succ n) m))) @[simp] theorem pred_singleton {m : ℕ} (h : 0 < m) : Ico (m - 1) m = [m - 1] := sorry theorem chain'_succ (n : ℕ) (m : ℕ) : chain' (fun (a b : ℕ) => b = Nat.succ a) (Ico n m) := sorry @[simp] theorem not_mem_top {n : ℕ} {m : ℕ} : ¬m ∈ Ico n m := sorry theorem filter_lt_of_top_le {n : ℕ} {m : ℕ} {l : ℕ} (hml : m ≤ l) : filter (fun (x : ℕ) => x < l) (Ico n m) = Ico n m := iff.mpr filter_eq_self fun (k : ℕ) (hk : k ∈ Ico n m) => lt_of_lt_of_le (and.right (iff.mp mem hk)) hml theorem filter_lt_of_le_bot {n : ℕ} {m : ℕ} {l : ℕ} (hln : l ≤ n) : filter (fun (x : ℕ) => x < l) (Ico n m) = [] := iff.mpr filter_eq_nil fun (k : ℕ) (hk : k ∈ Ico n m) => not_lt_of_le (le_trans hln (and.left (iff.mp mem hk))) theorem filter_lt_of_ge {n : ℕ} {m : ℕ} {l : ℕ} (hlm : l ≤ m) : filter (fun (x : ℕ) => x < l) (Ico n m) = Ico n l := sorry @[simp] theorem filter_lt (n : ℕ) (m : ℕ) (l : ℕ) : filter (fun (x : ℕ) => x < l) (Ico n m) = Ico n (min m l) := sorry theorem filter_le_of_le_bot {n : ℕ} {m : ℕ} {l : ℕ} (hln : l ≤ n) : filter (fun (x : ℕ) => l ≤ x) (Ico n m) = Ico n m := iff.mpr filter_eq_self fun (k : ℕ) (hk : k ∈ Ico n m) => le_trans hln (and.left (iff.mp mem hk)) theorem filter_le_of_top_le {n : ℕ} {m : ℕ} {l : ℕ} (hml : m ≤ l) : filter (fun (x : ℕ) => l ≤ x) (Ico n m) = [] := iff.mpr filter_eq_nil fun (k : ℕ) (hk : k ∈ Ico n m) => not_le_of_gt (lt_of_lt_of_le (and.right (iff.mp mem hk)) hml) theorem filter_le_of_le {n : ℕ} {m : ℕ} {l : ℕ} (hnl : n ≤ l) : filter (fun (x : ℕ) => l ≤ x) (Ico n m) = Ico l m := sorry @[simp] theorem filter_le (n : ℕ) (m : ℕ) (l : ℕ) : filter (fun (x : ℕ) => l ≤ x) (Ico n m) = Ico (max n l) m := sorry theorem filter_lt_of_succ_bot {n : ℕ} {m : ℕ} (hnm : n < m) : filter (fun (x : ℕ) => x < n + 1) (Ico n m) = [n] := sorry @[simp] theorem filter_le_of_bot {n : ℕ} {m : ℕ} (hnm : n < m) : filter (fun (x : ℕ) => x ≤ n) (Ico n m) = [n] := eq.mpr (id (Eq._oldrec (Eq.refl (filter (fun (x : ℕ) => x ≤ n) (Ico n m) = [n])) (Eq.symm (filter_lt_of_succ_bot hnm)))) (filter_congr fun (_x : ℕ) (_x_1 : _x ∈ Ico n m) => iff.symm nat.lt_succ_iff) /-- For any natural numbers n, a, and b, one of the following holds: 1. n < a 2. n ≥ b 3. n ∈ Ico a b -/ theorem trichotomy (n : ℕ) (a : ℕ) (b : ℕ) : n < a ∨ b ≤ n ∨ n ∈ Ico a b := sorry
3b98111cab90e611f6c81d233eba62de5fe3c502
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/788.lean
a536bb22a24d5566bca09bbc202a794575d610e7
[ "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
134
lean
example : (0 : Nat) = Nat.zero := by simp only [OfNat.ofNat] example : (0 : Fin 9) = (Fin.ofNat 0) := by simp only [OfNat.ofNat]
0207d165010e5033095eda3429ff8ac8f762548c
856e2e1615a12f95b551ed48fa5b03b245abba44
/src/tactic/suggest.lean
a7a92e08cd69a0b2f3734f91b0d840198d85b568
[ "Apache-2.0" ]
permissive
pimsp/mathlib
8b77e1ccfab21703ba8fbe65988c7de7765aa0e5
913318ca9d6979686996e8d9b5ebf7e74aae1c63
refs/heads/master
1,669,812,465,182
1,597,133,610,000
1,597,133,610,000
281,890,685
1
0
null
1,595,491,577,000
1,595,491,576,000
null
UTF-8
Lean
false
false
20,622
lean
/- Copyright (c) 2019 Lucas Allen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Lucas Allen and Scott Morrison -/ import data.mllist import tactic.solve_by_elim /-! # `suggest` and `library_search` `suggest` and `library_search` are a pair of tactics for applying lemmas from the library to the current goal. * `suggest` prints a list of `exact ...` or `refine ...` statements, which may produce new goals * `library_search` prints a single `exact ...` which closes the goal, or fails -/ namespace tactic open native namespace suggest open solve_by_elim /-- Map a name (typically a head symbol) to a "canonical" definitional synonym. Given a name `n`, we want a name `n'` such that a sufficiently applied expression with head symbol `n` is always definitionally equal to an expression with head symbol `n'`. Thus, we can search through all lemmas with a result type of `n'` to solve a goal with head symbol `n`. For example, `>` is mapped to `<` because `a > b` is definitionally equal to `b < a`, and `not` is mapped to `false` because `¬ a` is definitionally equal to `p → false` The default is that the original argument is returned, so `<` is just mapped to `<`. `normalize_synonym` is called for every lemma in the library, so it needs to be fast. -/ -- TODO this is a hack; if you suspect more cases here would help, please report them meta def normalize_synonym : name → name | `gt := `has_lt.lt | `ge := `has_le.le | `monotone := `has_le.le | `not := `false | n := n /-- Compute the head symbol of an expression, then normalise synonyms. This is only used when analysing the goal, so it is okay to do more expensive analysis here. -/ -- We may want to tweak this further? meta def allowed_head_symbols : expr → list name -- We first have a various "customisations": -- Because in `ℕ` `a.succ ≤ b` is definitionally `a < b`, -- we add some special cases to allow looking for `<` lemmas even when the goal has a `≤`. -- Note we only do this in the `ℕ` case, for performance. | `(@has_le.le ℕ _ (nat.succ _) _) := [`has_le.le, `has_lt.lt] | `(@ge ℕ _ _ (nat.succ _)) := [`has_le.le, `has_lt.lt] | `(@has_le.le ℕ _ 1 _) := [`has_le.le, `has_lt.lt] | `(@ge ℕ _ _ 1) := [`has_le.le, `has_lt.lt] -- And then the generic cases: | (expr.pi _ _ _ t) := allowed_head_symbols t | (expr.app f _) := allowed_head_symbols f | (expr.const n _) := [normalize_synonym n] | _ := [`_] . /-- A declaration can match the head symbol of the current goal in four possible ways: * `ex` : an exact match * `mp` : the declaration returns an `iff`, and the right hand side matches the goal * `mpr` : the declaration returns an `iff`, and the left hand side matches the goal * `both`: the declaration returns an `iff`, and the both sides match the goal -/ @[derive decidable_eq, derive inhabited] inductive head_symbol_match | ex | mp | mpr | both open head_symbol_match /-- a textual representation of a `head_symbol_match`, for trace debugging. -/ def head_symbol_match.to_string : head_symbol_match → string | ex := "exact" | mp := "iff.mp" | mpr := "iff.mpr" | both := "iff.mp and iff.mpr" /-- Determine if, and in which way, a given expression matches the specified head symbol. -/ meta def match_head_symbol (hs : name_set) : expr → option head_symbol_match | (expr.pi _ _ _ t) := match_head_symbol t | `(%%a ↔ %%b) := if hs.contains `iff then some ex else match (match_head_symbol a, match_head_symbol b) with | (some ex, some ex) := some both | (some ex, _) := some mpr | (_, some ex) := some mp | _ := none end | (expr.app f _) := match_head_symbol f | (expr.const n _) := if hs.contains (normalize_synonym n) then some ex else none | _ := if hs.contains `_ then some ex else none /-- A package of `declaration` metadata, including the way in which its type matches the head symbol which we are searching for. -/ meta structure decl_data := (d : declaration) (n : name) (m : head_symbol_match) (l : ℕ) -- cached length of name /-- Generate a `decl_data` from the given declaration if it matches the head symbol `hs` for the current goal. -/ -- We used to check here for private declarations, or declarations with certain suffixes. -- It turns out `apply` is so fast, it's better to just try them all. meta def process_declaration (hs : name_set) (d : declaration) : option decl_data := let n := d.to_name in if !d.is_trusted || n.is_internal then none else (λ m, ⟨d, n, m, n.length⟩) <$> match_head_symbol hs d.type /-- Retrieve all library definitions with a given head symbol. -/ meta def library_defs (hs : name_set) : tactic (list decl_data) := do trace_if_enabled `suggest format!"Looking for lemmas with head symbols {hs}.", env ← get_env, let defs := env.decl_filter_map (process_declaration hs), -- Sort by length; people like short proofs let defs := defs.qsort(λ d₁ d₂, d₁.l ≤ d₂.l), trace_if_enabled `suggest format!"Found {defs.length} relevant lemmas:", trace_if_enabled `suggest $ defs.map (λ ⟨d, n, m, l⟩, (n, m.to_string)), return defs /-- We unpack any element of a list of `decl_data` corresponding to an `↔` statement that could apply in both directions into two separate elements. This ensures that both directions can be independently returned by `suggest`, and avoids a problem where the application of one direction prevents the application of the other direction. (See `exp_le_exp` in the tests.) -/ meta def unpack_iff_both : list decl_data → list decl_data | [] := [] | (⟨d, n, both, l⟩ :: L) := ⟨d, n, mp, l⟩ :: ⟨d, n, mpr, l⟩ :: unpack_iff_both L | (⟨d, n, m, l⟩ :: L) := ⟨d, n, m, l⟩ :: unpack_iff_both L /-- Apply the lemma `e`, then attempt to close all goals using `solve_by_elim opt`, failing if `close_goals = tt` and there are any goals remaining. Returns the number of subgoals which were closed using `solve_by_elim`. -/ -- Implementation note: as this is used by both `library_search` and `suggest`, -- we first run `solve_by_elim` separately on the independent goals, -- whether or not `close_goals` is set, -- and then run `solve_by_elim { all_goals := tt }`, -- requiring that it succeeds if `close_goals = tt`. meta def apply_and_solve (close_goals : bool) (opt : opt := { }) (e : expr) : tactic ℕ := do trace_if_enabled `suggest format!"Trying to apply lemma: {e}", opt.apply e, trace_if_enabled `suggest format!"Applied lemma: {e}", ng ← num_goals, -- Phase 1 -- Run `solve_by_elim` on each "safe" goal separately, not worrying about failures. -- (We only attempt the "safe" goals in this way in Phase 1. In Phase 2 we will do -- backtracking search across all goals, allowing us to guess solutions that involve data, or -- unify metavariables, but only as long as we can finish all goals.) try (any_goals (independent_goal >> solve_by_elim opt)), -- Phase 2 (done >> return ng) <|> (do -- If there were any goals that we did not attempt solving in the first phase -- (because they weren't propositional, or contained a metavariable) -- as a second phase we attempt to solve all remaining goals at once -- (with backtracking across goals). (any_goals (success_if_fail independent_goal) >> solve_by_elim { backtrack_all_goals := tt, ..opt }) <|> -- and fail unless `close_goals = ff` guard ¬ close_goals, ng' ← num_goals, return (ng - ng')) /-- Apply the declaration `d` (or the forward and backward implications separately, if it is an `iff`), and then attempt to solve the subgoal using `apply_and_solve`. Returns the number of subgoals successfully closed. -/ meta def apply_declaration (close_goals : bool) (opt : opt := { }) (d : decl_data) : tactic ℕ := let tac := apply_and_solve close_goals opt in do (e, t) ← decl_mk_const d.d, match d.m with | ex := tac e | mp := do l ← iff_mp_core e t, tac l | mpr := do l ← iff_mpr_core e t, tac l | both := undefined -- we use `unpack_iff_both` to ensure this isn't reachable end /-- An `application` records the result of a successful application of a library lemma. -/ meta structure application := (state : tactic_state) (script : string) (decl : option declaration) (num_goals : ℕ) (hyps_used : ℕ) end suggest open solve_by_elim open suggest declare_trace suggest -- Trace a list of all relevant lemmas -- Call `apply_declaration`, then prepare the tactic script and -- count the number of local hypotheses used. private meta def apply_declaration_script (g : expr) (hyps : list expr) (opt : opt := { }) (d : decl_data) : tactic application := -- (This tactic block is only executed when we evaluate the mllist, -- so we need to do the `focus1` here.) retrieve $ focus1 $ do apply_declaration ff opt d, ng ← num_goals, -- This `instantiate_mvars` is necessary so that we count used hypotheses correctly. g ← instantiate_mvars g, s ← read, m ← tactic_statement g, return { application . state := s, decl := d.d, script := m, num_goals := ng, hyps_used := hyps.countp (λ h, h.occurs g) } -- implementation note: we produce a `tactic (mllist tactic application)` first, -- because it's easier to work in the tactic monad, but in a moment we squash this -- down to an `mllist tactic application`. private meta def suggest_core' (opt : opt := { }) : tactic (mllist tactic application) := do g :: _ ← get_goals, hyps ← local_context, -- Make sure that `solve_by_elim` doesn't just solve the goal immediately: (retrieve (do focus1 $ solve_by_elim opt, s ← read, m ← tactic_statement g, -- This `instantiate_mvars` is necessary so that we count used hypotheses correctly. g ← instantiate_mvars g, return $ mllist.of_list [⟨s, m, none, 0, hyps.countp (λ h, h.occurs g)⟩])) <|> -- Otherwise, let's actually try applying library lemmas. (do -- Collect all definitions with the correct head symbol t ← infer_type g, defs ← unpack_iff_both <$> library_defs (name_set.of_list $ allowed_head_symbols t), let defs : mllist tactic _ := mllist.of_list defs, -- Try applying each lemma against the goal, -- recording the tactic script as a string, -- the number of remaining goals, -- and number of local hypotheses used. let results := defs.mfilter_map (apply_declaration_script g hyps opt), -- Now call `symmetry` and try again. -- (Because we are using `mllist`, this is essentially free if we've already found a lemma.) symm_state ← retrieve $ try_core $ symmetry >> read, let results_symm := match symm_state with | (some s) := defs.mfilter_map (λ d, retrieve $ set_state s >> apply_declaration_script g hyps opt d) | none := mllist.nil end, return (results.append results_symm)) /-- The core `suggest` tactic. It attempts to apply a declaration from the library, then solve new goals using `solve_by_elim`. It returns a list of `application`s consisting of fields: * `state`, a tactic state resulting from the successful application of a declaration from the library, * `script`, a string of the form `refine ...` or `exact ...` which will reproduce that tactic state, * `decl`, an `option declaration` indicating the declaration that was applied (or none, if `solve_by_elim` succeeded), * `num_goals`, the number of remaining goals, and * `hyps_used`, the number of local hypotheses used in the solution. -/ meta def suggest_core (opt : opt := { }) : mllist tactic application := (mllist.monad_lift (suggest_core' opt)).join /-- See `suggest_core`. Returns a list of at most `limit` `application`s, sorted by number of goals, and then (reverse) number of hypotheses used. -/ meta def suggest (limit : option ℕ := none) (opt : opt := { }) : tactic (list application) := do let results := suggest_core opt, -- Get the first n elements of the successful lemmas L ← if h : limit.is_some then results.take (option.get h) else results.force, -- Sort by number of remaining goals, then by number of hypotheses used. return $ L.qsort (λ d₁ d₂, d₁.num_goals < d₂.num_goals ∨ (d₁.num_goals = d₂.num_goals ∧ d₁.hyps_used ≥ d₂.hyps_used)) /-- Returns a list of at most `limit` strings, of the form `exact ...` or `refine ...`, which make progress on the current goal using a declaration from the library. -/ meta def suggest_scripts (limit : option ℕ := none) (opt : opt := { }) : tactic (list string) := do L ← suggest limit opt, return $ L.map application.script /-- Returns a string of the form `exact ...`, which closes the current goal. -/ meta def library_search (opt : opt := { }) : tactic string := (suggest_core opt).mfirst (λ a, do guard (a.num_goals = 0), write a.state, return a.script) namespace interactive open tactic open interactive open lean.parser open interactive.types open solve_by_elim local postfix `?`:9001 := optional declare_trace silence_suggest -- Turn off `exact/refine ...` trace messages for `suggest` /-- `suggest` tries to apply suitable theorems/defs from the library, and generates a list of `exact ...` or `refine ...` scripts that could be used at this step. It leaves the tactic state unchanged. It is intended as a complement of the search function in your editor, the `#find` tactic, and `library_search`. `suggest` takes an optional natural number `num` as input and returns the first `num` (or less, if all possibilities are exhausted) possibilities ordered by length of lemma names. The default for `num` is `50`. For performance reasons `suggest` uses monadic lazy lists (`mllist`). This means that `suggest` might miss some results if `num` is not large enough. However, because `suggest` uses monadic lazy lists, smaller values of `num` run faster than larger values. You can add additional lemmas to be used along with local hypotheses after the application of a library lemma, using the same syntax as for `solve_by_elim`, e.g. ``` example {a b c d: nat} (h₁ : a < c) (h₂ : b < d) : max (c + d) (a + b) = (c + d) := begin suggest [add_lt_add], -- Says: `exact max_eq_left_of_lt (add_lt_add h₁ h₂)` end ``` You can also use `suggest with attr` to include all lemmas with the attribute `attr`. -/ meta def suggest (n : parse (with_desc "n" small_nat)?) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (opt : opt := { }) : tactic unit := do asms ← mk_assumption_set ff hs attr_names, L ← tactic.suggest_scripts (n.get_or_else 50) { lemma_thunks := return asms, ..opt }, if is_trace_enabled_for `silence_suggest then skip else if L.length = 0 then fail "There are no applicable declarations" else L.mmap trace >> skip /-- `suggest` lists possible usages of the `refine` tactic and leaves the tactic state unchanged. It is intended as a complement of the search function in your editor, the `#find` tactic, and `library_search`. `suggest` takes an optional natural number `num` as input and returns the first `num` (or less, if all possibilities are exhausted) possibilities ordered by length of lemma names. The default for `num` is `50`. For performance reasons `suggest` uses monadic lazy lists (`mllist`). This means that `suggest` might miss some results if `num` is not large enough. However, because `suggest` uses monadic lazy lists, smaller values of `num` run faster than larger values. An example of `suggest` in action, ```lean example (n : nat) : n < n + 1 := begin suggest, sorry end ``` prints the list, ```lean Try this: exact nat.lt.base n Try this: exact nat.lt_succ_self n Try this: refine not_le.mp _ Try this: refine gt_iff_lt.mp _ Try this: refine nat.lt.step _ Try this: refine lt_of_not_ge _ ... ``` -/ add_tactic_doc { name := "suggest", category := doc_category.tactic, decl_names := [`tactic.interactive.suggest], tags := ["search", "Try this"] } declare_trace silence_library_search -- Turn off `exact ...` trace message for `library_search /-- `library_search` attempts to apply every definition in the library whose head symbol matches the goal, and then discharge any new goals using `solve_by_elim`. If it succeeds, it prints a trace message `exact ...` which can replace the invocation of `library_search`. By default `library_search` only unfolds `reducible` definitions when attempting to match lemmas against the goal. Previously, it would unfold most definitions, sometimes giving surprising answers, or slow answers. The old behaviour is still available via `library_search!`. You can add additional lemmas to be used along with local hypotheses after the application of a library lemma, using the same syntax as for `solve_by_elim`, e.g. ``` example {a b c d: nat} (h₁ : a < c) (h₂ : b < d) : max (c + d) (a + b) = (c + d) := begin library_search [add_lt_add], -- Says: `exact max_eq_left_of_lt (add_lt_add h₁ h₂)` end ``` You can also use `library_search with attr` to include all lemmas with the attribute `attr`. -/ meta def library_search (semireducible : parse $ optional (tk "!")) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (opt : opt := { }) : tactic unit := do asms ← mk_assumption_set ff hs attr_names, (tactic.library_search { backtrack_all_goals := tt, lemma_thunks := return asms, apply := λ e, tactic.apply e { md := if semireducible.is_some then tactic.transparency.semireducible else tactic.transparency.reducible }, ..opt } >>= if is_trace_enabled_for `silence_library_search then (λ _, skip) else trace) <|> fail "`library_search` failed. If you aren't sure what to do next, you can also try `library_search!`, `suggest`, or `hint`. Possible reasons why `library_search` failed: * `library_search` will only apply a single lemma from the library, and then try to fill in its hypotheses from local hypotheses. * If you haven't already, try stating the theorem you want in its own lemma. * Sometimes the library has one version of a lemma but not a very similar version obtained by permuting arguments. Try replacing `a + b` with `b + a`, or `a - b < c` with `a < b + c`, to see if maybe the lemma exists but isn't stated quite the way you would like. * Make sure that you have all the side conditions for your theorem to be true. For example you won't find `a - b + b = a` for natural numbers in the library because it's false! Search for `b ≤ a → a - b + b = a` instead. * If a definition you made is in the goal, you won't find any theorems about it in the library. Try unfolding the definition using `unfold my_definition`. * If all else fails, ask on https://leanprover.zulipchat.com/, and maybe we can improve the library and/or `library_search` for next time." /-- `library_search` is a tactic to identify existing lemmas in the library. It tries to close the current goal by applying a lemma from the library, then discharging any new goals using `solve_by_elim`. Typical usage is: ```lean example (n m k : ℕ) : n * (m - k) = n * m - n * k := by library_search -- Try this: exact nat.mul_sub_left_distrib n m k ``` `library_search` prints a trace message showing the proof it found, shown above as a comment. Typically you will then copy and paste this proof, replacing the call to `library_search`. -/ add_tactic_doc { name := "library_search", category := doc_category.tactic, decl_names := [`tactic.interactive.library_search], tags := ["search", "Try this"] } end interactive /-- Invoking the hole command `library_search` ("Use `library_search` to complete the goal") calls the tactic `library_search` to produce a proof term with the type of the hole. Running it on ```lean example : 0 < 1 := {!!} ``` produces ```lean example : 0 < 1 := nat.one_pos ``` -/ @[hole_command] meta def library_search_hole_cmd : hole_command := { name := "library_search", descr := "Use `library_search` to complete the goal.", action := λ _, do script ← library_search, -- Is there a better API for dropping the 'exact ' prefix on this string? return [((script.mk_iterator.remove 6).to_string, "by library_search")] } add_tactic_doc { name := "library_search", category := doc_category.hole_cmd, decl_names := [`tactic.library_search_hole_cmd], tags := ["search", "Try this"] } end tactic
365f9aa560264828e782448c343dc3fb302e21b6
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/ring_theory/unique_factorization_domain.lean
facd39e576eb68b0b9f4197ff6bf7bfcd3687d48
[ "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
19,673
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jens Wagemaker Theory of unique factorization domains. @TODO: setup the complete lattice structure on `factor_set`. -/ import algebra.gcd_domain variables {α : Type*} local infix ` ~ᵤ ` : 50 := associated /-- Unique factorization domains. In a unique factorization domain each element (except zero) is uniquely represented as a multiset of irreducible factors. Uniqueness is only up to associated elements. This is equivalent to defining a unique factorization domain as a domain in which each element (except zero) is non-uniquely represented as a multiset of prime factors. This definition is used. To define a UFD using the traditional definition in terms of multisets of irreducible factors, use the definition `of_unique_irreducible_factorization` -/ class unique_factorization_domain (α : Type*) [integral_domain α] := (factors : α → multiset α) (factors_prod : ∀{a : α}, a ≠ 0 → (factors a).prod ~ᵤ a) (prime_factors : ∀{a : α}, a ≠ 0 → ∀x∈factors a, prime x) namespace unique_factorization_domain variables [integral_domain α] [unique_factorization_domain α] @[elab_as_eliminator] lemma induction_on_prime {P : α → Prop} (a : α) (h₁ : P 0) (h₂ : ∀ x : α, is_unit x → P x) (h₃ : ∀ a p : α, a ≠ 0 → prime p → P a → P (p * a)) : P a := by haveI := classical.dec_eq α; exact if ha0 : a = 0 then ha0.symm ▸ h₁ else @multiset.induction_on _ (λ s : multiset α, ∀ (a : α), a ≠ 0 → s.prod ~ᵤ a → (∀ p ∈ s, prime p) → P a) (factors a) (λ _ _ h _, h₂ _ ((is_unit_iff_of_associated h.symm).2 is_unit_one)) (λ p s ih a ha0 ⟨u, hu⟩ hsp, have ha : a = (p * u) * s.prod, by simp [hu.symm, mul_comm, mul_assoc], have hs0 : s.prod ≠ 0, from λ _ : s.prod = 0, by simp * at *, ha.symm ▸ h₃ _ _ hs0 (prime_of_associated ⟨u, rfl⟩ (hsp p (multiset.mem_cons_self _ _))) (ih _ hs0 (by refl) (λ p hp, hsp p (multiset.mem_cons.2 (or.inr hp))))) _ ha0 (factors_prod ha0) (prime_factors ha0) lemma factors_irreducible {a : α} (ha : irreducible a) : ∃ p, a ~ᵤ p ∧ factors a = p :: 0 := by haveI := classical.dec_eq α; exact multiset.induction_on (factors a) (λ h, (ha.1 (associated_one_iff_is_unit.1 h.symm)).elim) (λ p s _ hp hs, let ⟨u, hu⟩ := hp in ⟨p, have hs0 : s = 0, from classical.by_contradiction (λ hs0, let ⟨q, hq⟩ := multiset.exists_mem_of_ne_zero hs0 in (hs q (by simp [hq])).2.1 $ (ha.2 ((p * u) * (s.erase q).prod) _ (by rw [mul_right_comm _ _ q, mul_assoc, ← multiset.prod_cons, multiset.cons_erase hq]; simp [hu.symm, mul_comm, mul_assoc])).resolve_left $ mt is_unit_of_mul_is_unit_left $ mt is_unit_of_mul_is_unit_left (hs p (multiset.mem_cons_self _ _)).2.1), ⟨associated.symm (by clear _let_match; simp * at *), hs0 ▸ rfl⟩⟩) (factors_prod ha.ne_zero) (prime_factors ha.ne_zero) lemma irreducible_iff_prime {p : α} : irreducible p ↔ prime p := by letI := classical.dec_eq α; exact if hp0 : p = 0 then by simp [hp0] else ⟨λ h, let ⟨q, hq⟩ := factors_irreducible h in have prime q, from hq.2 ▸ prime_factors hp0 _ (by simp [hq.2]), suffices prime (factors p).prod, from prime_of_associated (factors_prod hp0) this, hq.2.symm ▸ by simp [this], irreducible_of_prime⟩ lemma irreducible_factors : ∀{a : α}, a ≠ 0 → ∀x∈factors a, irreducible x := by simp only [irreducible_iff_prime]; exact @prime_factors _ _ _ lemma unique : ∀{f g : multiset α}, (∀x∈f, irreducible x) → (∀x∈g, irreducible x) → f.prod ~ᵤ g.prod → multiset.rel associated f g := by haveI := classical.dec_eq α; exact λ f, multiset.induction_on f (λ g _ hg h, multiset.rel_zero_left.2 $ multiset.eq_zero_of_forall_not_mem (λ x hx, have is_unit g.prod, by simpa [associated_one_iff_is_unit] using h.symm, (hg x hx).1 (is_unit_iff_dvd_one.2 (dvd.trans (multiset.dvd_prod hx) (is_unit_iff_dvd_one.1 this))))) (λ p f ih g hf hg hfg, let ⟨b, hbg, hb⟩ := exists_associated_mem_of_dvd_prod (irreducible_iff_prime.1 (hf p (by simp))) (λ q hq, irreducible_iff_prime.1 (hg _ hq)) $ (dvd_iff_dvd_of_rel_right hfg).1 (show p ∣ (p :: f).prod, by simp) in begin rw ← multiset.cons_erase hbg, exact multiset.rel.cons hb (ih (λ q hq, hf _ (by simp [hq])) (λ q (hq : q ∈ g.erase b), hg q (multiset.mem_of_mem_erase hq)) (associated_mul_left_cancel (by rwa [← multiset.prod_cons, ← multiset.prod_cons, multiset.cons_erase hbg]) hb (hf p (by simp)).ne_zero)) end) end unique_factorization_domain structure unique_irreducible_factorization (α : Type*) [integral_domain α] := (factors : α → multiset α) (factors_prod : ∀{a : α}, a ≠ 0 → (factors a).prod ~ᵤ a) (irreducible_factors : ∀{a : α}, a ≠ 0 → ∀x∈factors a, irreducible x) (unique : ∀{f g : multiset α}, (∀x∈f, irreducible x) → (∀x∈g, irreducible x) → f.prod ~ᵤ g.prod → multiset.rel associated f g) namespace unique_factorization_domain open unique_factorization_domain associated variables [integral_domain α] [unique_factorization_domain α] [decidable_eq (associates α)] lemma exists_mem_factors_of_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) : p ∣ a → ∃ q ∈ factors a, p ~ᵤ q := λ ⟨b, hb⟩, have hb0 : b ≠ 0, from λ hb0, by simp * at *, have multiset.rel associated (p :: factors b) (factors a), from unique (λ x hx, (multiset.mem_cons.1 hx).elim (λ h, h.symm ▸ hp) (irreducible_factors hb0 _)) (irreducible_factors ha0) (associated.symm $ calc multiset.prod (factors a) ~ᵤ a : factors_prod ha0 ... = p * b : hb ... ~ᵤ multiset.prod (p :: factors b) : by rw multiset.prod_cons; exact associated_mul_mul (associated.refl _) (associated.symm (factors_prod hb0))), multiset.exists_mem_of_rel_of_mem this (by simp) def of_unique_irreducible_factorization {α : Type*} [integral_domain α] (o : unique_irreducible_factorization α) : unique_factorization_domain α := by letI := classical.dec_eq α; exact { prime_factors := λ a h p (hpa : p ∈ o.factors a), have hpi : irreducible p, from o.irreducible_factors h _ hpa, ⟨hpi.ne_zero, hpi.1, λ a b ⟨x, hx⟩, if hab0 : a * b = 0 then (eq_zero_or_eq_zero_of_mul_eq_zero hab0).elim (λ ha0, by simp [ha0]) (λ hb0, by simp [hb0]) else have hx0 : x ≠ 0, from λ hx0, by simp * at *, have ha0 : a ≠ 0, from ne_zero_of_mul_ne_zero_right hab0, have hb0 : b ≠ 0, from ne_zero_of_mul_ne_zero_left hab0, have multiset.rel associated (p :: o.factors x) (o.factors a + o.factors b), from o.unique (λ i hi, (multiset.mem_cons.1 hi).elim (λ hip, hip.symm ▸ hpi) (o.irreducible_factors hx0 _)) (show ∀ x ∈ o.factors a + o.factors b, irreducible x, from λ x hx, (multiset.mem_add.1 hx).elim (o.irreducible_factors (ne_zero_of_mul_ne_zero_right hab0) _) (o.irreducible_factors (ne_zero_of_mul_ne_zero_left hab0) _)) $ calc multiset.prod (p :: o.factors x) ~ᵤ a * b : by rw [hx, multiset.prod_cons]; exact associated_mul_mul (by refl) (o.factors_prod hx0) ... ~ᵤ (o.factors a).prod * (o.factors b).prod : associated_mul_mul (o.factors_prod ha0).symm (o.factors_prod hb0).symm ... = _ : by rw multiset.prod_add, let ⟨q, hqf, hq⟩ := multiset.exists_mem_of_rel_of_mem this (multiset.mem_cons_self p _) in (multiset.mem_add.1 hqf).elim (λ hqa, or.inl $ (dvd_iff_dvd_of_rel_left hq).2 $ (dvd_iff_dvd_of_rel_right (o.factors_prod ha0)).1 (multiset.dvd_prod hqa)) (λ hqb, or.inr $ (dvd_iff_dvd_of_rel_left hq).2 $ (dvd_iff_dvd_of_rel_right (o.factors_prod hb0)).1 (multiset.dvd_prod hqb))⟩, ..o } end unique_factorization_domain namespace associates open unique_factorization_domain associated variables [integral_domain α] [unique_factorization_domain α] [decidable_eq (associates α)] /-- `factor_set α` representation elements of unique factorization domain as multisets. `multiset α` produced by `factors` are only unique up to associated elements, while the multisets in `factor_set α` are unqiue by equality and restricted to irreducible elements. This gives us a representation of each element as a unique multisets (or the added ⊤ for 0), which has a complete lattice struture. Infimum is the greatest common divisor and supremum is the least common multiple. -/ @[reducible] def {u} factor_set (α : Type u) [integral_domain α] [unique_factorization_domain α] : Type u := with_top (multiset { a : associates α // irreducible a }) local attribute [instance] associated.setoid theorem unique' {p q : multiset (associates α)} : (∀a∈p, irreducible a) → (∀a∈q, irreducible a) → p.prod = q.prod → p = q := begin apply multiset.induction_on_multiset_quot p, apply multiset.induction_on_multiset_quot q, assume s t hs ht eq, refine multiset.map_mk_eq_map_mk_of_rel (unique_factorization_domain.unique _ _ _), { exact assume a ha, ((irreducible_mk_iff _).1 $ hs _ $ multiset.mem_map_of_mem _ ha) }, { exact assume a ha, ((irreducible_mk_iff _).1 $ ht _ $ multiset.mem_map_of_mem _ ha) }, simpa [quot_mk_eq_mk, prod_mk, mk_eq_mk_iff_associated] using eq end private theorem forall_map_mk_factors_irreducible (x : α) (hx : x ≠ 0) : ∀(a : associates α), a ∈ multiset.map associates.mk (factors x) → irreducible a := begin assume a ha, rcases multiset.mem_map.1 ha with ⟨c, hc, rfl⟩, exact (irreducible_mk_iff c).2 (irreducible_factors hx _ hc) end theorem prod_le_prod_iff_le {p q : multiset (associates α)} (hp : ∀a∈p, irreducible a) (hq : ∀a∈q, irreducible a) : p.prod ≤ q.prod ↔ p ≤ q := iff.intro begin rintros ⟨⟨c⟩, eq⟩, have : c ≠ 0, from (mt mk_eq_zero_iff_eq_zero.2 $ assume (hc : quot.mk setoid.r c = 0), have (0 : associates α) ∈ q, from prod_eq_zero_iff.1 $ eq ▸ hc.symm ▸ mul_zero _, not_irreducible_zero ((irreducible_mk_iff 0).1 $ hq _ this)), have : associates.mk (factors c).prod = quot.mk setoid.r c, from mk_eq_mk_iff_associated.2 (factors_prod this), refine le_iff_exists_add.2 ⟨(factors c).map associates.mk, unique' hq _ _⟩, { assume x hx, rcases multiset.mem_add.1 hx with h | h, exact hp x h, exact forall_map_mk_factors_irreducible c ‹c ≠ 0› _ h }, { simp [multiset.prod_add, prod_mk, *] at * } end prod_le_prod @[simp, nolint simp_nf] -- takes a crazy amount of time to simplify lhs theorem factor_set.coe_add {a b : multiset { a : associates α // irreducible a }} : (↑a + ↑b : factor_set α) = ↑(a + b) := with_top.coe_add lemma factor_set.sup_add_inf_eq_add : ∀(a b : factor_set α), a ⊔ b + a ⊓ b = a + b | none b := show ⊤ ⊔ b + ⊤ ⊓ b = ⊤ + b, by simp | a none := show a ⊔ ⊤ + a ⊓ ⊤ = a + ⊤, by simp | (some a) (some b) := show (a : factor_set α) ⊔ b + a ⊓ b = a + b, from begin rw [← with_top.coe_sup, ← with_top.coe_inf, ← with_top.coe_add, ← with_top.coe_add, with_top.coe_eq_coe], exact multiset.union_add_inter _ _ end def factors' (a : α) (ha : a ≠ 0) : multiset { a : associates α // irreducible a } := (factors a).pmap (λa ha, ⟨associates.mk a, (irreducible_mk_iff _).2 ha⟩) (irreducible_factors $ ha) @[simp] theorem map_subtype_val_factors' {a : α} (ha : a ≠ 0) : (factors' a ha).map subtype.val = (factors a).map associates.mk := by simp [factors', multiset.map_pmap, multiset.pmap_eq_map] theorem factors'_cong {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) (h : a ~ᵤ b) : factors' a ha = factors' b hb := have multiset.rel associated (factors a) (factors b), from unique (irreducible_factors ha) (irreducible_factors hb) ((factors_prod ha).trans $ h.trans $ (factors_prod hb).symm), by simpa [(multiset.map_eq_map subtype.val_injective).symm, rel_associated_iff_map_eq_map.symm] def factors (a : associates α) : factor_set α := begin refine (if h : a = 0 then ⊤ else quotient.hrec_on a (λx h, some $ factors' x (mt mk_eq_zero_iff_eq_zero.2 h)) _ h), assume a b hab, apply function.hfunext, { have : a ~ᵤ 0 ↔ b ~ᵤ 0, from iff.intro (assume ha0, hab.symm.trans ha0) (assume hb0, hab.trans hb0), simp [quotient_mk_eq_mk, mk_eq_zero_iff_eq_zero, (associated_zero_iff_eq_zero _).symm, this] }, exact (assume ha hb eq, heq_of_eq $ congr_arg some $ factors'_cong _ _ hab) end @[simp] theorem factors_0 : (0 : associates α).factors = ⊤ := dif_pos rfl @[simp] theorem factors_mk (a : α) (h : a ≠ 0) : (associates.mk a).factors = factors' a h := dif_neg (mt mk_eq_zero_iff_eq_zero.1 h) def factor_set.prod : factor_set α → associates α | none := 0 | (some s) := (s.map subtype.val).prod @[simp] theorem prod_top : (⊤ : factor_set α).prod = 0 := rfl @[simp] theorem prod_coe {s : multiset { a : associates α // irreducible a }} : (s : factor_set α).prod = (s.map subtype.val).prod := rfl theorem prod_factors : ∀(s : factor_set α), s.prod.factors = s | none := by simp [factor_set.prod]; refl | (some s) := begin unfold factor_set.prod, generalize eq_a : (s.map subtype.val).prod = a, rcases a with ⟨a⟩, rw quot_mk_eq_mk at *, have : (s.map subtype.val).prod ≠ 0, from assume ha, let ⟨⟨a, ha⟩, h, eq⟩ := multiset.mem_map.1 (prod_eq_zero_iff.1 ha) in have irreducible (0 : associates α), from eq ▸ ha, not_irreducible_zero ((irreducible_mk_iff _).1 this), have ha : a ≠ 0, by simp [*] at *, suffices : (unique_factorization_domain.factors a).map associates.mk = s.map subtype.val, { rw [factors_mk a ha], apply congr_arg some _, simpa [(multiset.map_eq_map subtype.val_injective).symm] }, refine unique' (forall_map_mk_factors_irreducible _ ha) (assume a ha, let ⟨⟨x, hx⟩, ha, eq⟩ := multiset.mem_map.1 ha in eq ▸ hx) _, rw [prod_mk, eq_a, mk_eq_mk_iff_associated], exact factors_prod ha end theorem factors_prod (a : associates α) : a.factors.prod = a := quotient.induction_on a $ assume a, decidable.by_cases (assume : associates.mk a = 0, by simp [quotient_mk_eq_mk, this]) (assume : associates.mk a ≠ 0, have a ≠ 0, by simp * at *, by simp [this, quotient_mk_eq_mk, prod_mk, mk_eq_mk_iff_associated.2 (factors_prod this)]) theorem eq_of_factors_eq_factors {a b : associates α} (h : a.factors = b.factors) : a = b := have a.factors.prod = b.factors.prod, by rw h, by rwa [factors_prod, factors_prod] at this theorem eq_of_prod_eq_prod {a b : factor_set α} (h : a.prod = b.prod) : a = b := have a.prod.factors = b.prod.factors, by rw h, by rwa [prod_factors, prod_factors] at this @[simp] theorem prod_add : ∀(a b : factor_set α), (a + b).prod = a.prod * b.prod | none b := show (⊤ + b).prod = (⊤:factor_set α).prod * b.prod, by simp | a none := show (a + ⊤).prod = a.prod * (⊤:factor_set α).prod, by simp | (some a) (some b) := show (↑a + ↑b:factor_set α).prod = (↑a:factor_set α).prod * (↑b:factor_set α).prod, by rw [factor_set.coe_add, prod_coe, prod_coe, prod_coe, multiset.map_add, multiset.prod_add] theorem prod_mono : ∀{a b : factor_set α}, a ≤ b → a.prod ≤ b.prod | none b h := have b = ⊤, from top_unique h, by rw [this, prod_top]; exact le_refl _ | a none h := show a.prod ≤ (⊤ : factor_set α).prod, by simp; exact le_top | (some a) (some b) h := prod_le_prod $ multiset.map_le_map $ with_top.coe_le_coe.1 $ h @[simp] theorem factors_mul (a b : associates α) : (a * b).factors = a.factors + b.factors := eq_of_prod_eq_prod $ eq_of_factors_eq_factors $ by rw [prod_add, factors_prod, factors_prod, factors_prod] theorem factors_mono : ∀{a b : associates α}, a ≤ b → a.factors ≤ b.factors | s t ⟨d, rfl⟩ := by rw [factors_mul] ; exact le_add_of_nonneg_right' bot_le theorem factors_le {a b : associates α} : a.factors ≤ b.factors ↔ a ≤ b := iff.intro (assume h, have a.factors.prod ≤ b.factors.prod, from prod_mono h, by rwa [factors_prod, factors_prod] at this) factors_mono theorem prod_le {a b : factor_set α} : a.prod ≤ b.prod ↔ a ≤ b := iff.intro (assume h, have a.prod.factors ≤ b.prod.factors, from factors_mono h, by rwa [prod_factors, prod_factors] at this) prod_mono instance : has_sup (associates α) := ⟨λa b, (a.factors ⊔ b.factors).prod⟩ instance : has_inf (associates α) := ⟨λa b, (a.factors ⊓ b.factors).prod⟩ instance : bounded_lattice (associates α) := { sup := (⊔), inf := (⊓), sup_le := assume a b c hac hbc, factors_prod c ▸ prod_mono (sup_le (factors_mono hac) (factors_mono hbc)), le_sup_left := assume a b, le_trans (le_of_eq (factors_prod a).symm) $ prod_mono $ le_sup_left, le_sup_right := assume a b, le_trans (le_of_eq (factors_prod b).symm) $ prod_mono $ le_sup_right, le_inf := assume a b c hac hbc, factors_prod a ▸ prod_mono (le_inf (factors_mono hac) (factors_mono hbc)), inf_le_left := assume a b, le_trans (prod_mono inf_le_left) (le_of_eq (factors_prod a)), inf_le_right := assume a b, le_trans (prod_mono inf_le_right) (le_of_eq (factors_prod b)), .. associates.partial_order, .. associates.order_top, .. associates.order_bot } lemma sup_mul_inf (a b : associates α) : (a ⊔ b) * (a ⊓ b) = a * b := show (a.factors ⊔ b.factors).prod * (a.factors ⊓ b.factors).prod = a * b, begin refine eq_of_factors_eq_factors _, rw [← prod_add, prod_factors, factors_mul, factor_set.sup_add_inf_eq_add] end end associates section open associates unique_factorization_domain /-- `to_gcd_domain` constructs a GCD domain out of a unique factorization domain over a normalization domain. -/ def unique_factorization_domain.to_gcd_domain (α : Type*) [normalization_domain α] [unique_factorization_domain α] [decidable_eq (associates α)] : gcd_domain α := { gcd := λa b, (associates.mk a ⊓ associates.mk b).out, lcm := λa b, (associates.mk a ⊔ associates.mk b).out, gcd_dvd_left := assume a b, (out_dvd_iff a (associates.mk a ⊓ associates.mk b)).2 $ inf_le_left, gcd_dvd_right := assume a b, (out_dvd_iff b (associates.mk a ⊓ associates.mk b)).2 $ inf_le_right, dvd_gcd := assume a b c hac hab, show a ∣ (associates.mk c ⊓ associates.mk b).out, by rw [dvd_out_iff, le_inf_iff, mk_le_mk_iff_dvd_iff, mk_le_mk_iff_dvd_iff]; exact ⟨hac, hab⟩, lcm_zero_left := assume a, show (⊤ ⊔ associates.mk a).out = 0, by simp, lcm_zero_right := assume a, show (associates.mk a ⊔ ⊤).out = 0, by simp, gcd_mul_lcm := assume a b, show (associates.mk a ⊓ associates.mk b).out * (associates.mk a ⊔ associates.mk b).out = normalize (a * b), by rw [← out_mk, ← out_mul, mul_comm, sup_mul_inf]; refl, normalize_gcd := assume a b, by convert normalize_out _, .. ‹normalization_domain α› } end
5a7b0d301f9094971f78a5b944523e33bc104500
b9a81ebb9de684db509231c4469a7d2c88915808
/test/super_examples.lean
7d7defec0ea905664a5c9fd3038dc042bd47145f
[]
no_license
leanprover/super
3dd81ce8d9ac3cba20bce55e84833fadb2f5716e
47b107b4cec8f3b41d72daba9cbda2f9d54025de
refs/heads/master
1,678,482,996,979
1,676,526,367,000
1,676,526,367,000
92,215,900
12
6
null
1,513,327,539,000
1,495,570,640,000
Lean
UTF-8
Lean
false
false
3,193
lean
import super open tactic def prime (n : ℕ) := ∀ d, d ∣ n → d = 1 ∨ d = n lemma nat_mul_cancel_one {m n : ℕ} : m ≠ 0 → m * n = m → n = 1 := by cases m; super nat.zero_lt_succ nat.eq_of_mul_eq_mul_left nat.mul_one lemma not_prime_zero : ¬ prime 0 := by intro h; cases h 2 ⟨0, rfl⟩; cases h_1 @[simp] lemma nat.dvd_refl (m : ℕ) : m ∣ m := ⟨1, by simp [nat.mul_one]⟩ @[simp] theorem nat.dvd_mul_left (a b : ℕ) : a ∣ b * a := ⟨b, nat.mul_comm _ _⟩ example {m n : ℕ} : prime (m * n) → m = 1 ∨ n = 1 := by super with prime nat.dvd_refl nat.dvd_mul_right nat.dvd_mul_left nat_mul_cancel_one not_prime_zero nat.mul_zero nat.zero_mul example : nat.zero ≠ nat.succ nat.zero := by super example (x y : ℕ) : nat.succ x = nat.succ y → x = y := by super example (i) (a b c : i) : [a,b,c] = [b,c,a] -> a = b ∧ b = c := by super definition is_positive (n : ℕ) := n > 0 example (n : ℕ) : n > 0 ↔ is_positive n := by super with is_positive example (m n : ℕ) : 0 + m = 0 + n → m = n := by super with nat.zero_add example : ∀x y : ℕ, x + y = y + x := begin intros, have h : nat.zero = 0 := rfl, induction x, super with nat.add_zero nat.zero_add, super with nat.add_succ nat.succ_add end example (i) [inhabited i] : nonempty i := by super example (i) [nonempty i] : ¬(inhabited i → false) := by super example : nonempty ℕ := by super example : ¬(inhabited ℕ → false) := by super example {a b} : ¬(b ∨ ¬a) ∨ (a → b) := by super example {a} : a ∨ ¬a := by super example {a} : (a ∧ a) ∨ (¬a ∧ ¬a) := by super example (i) (c : i) (p : i → Prop) (f : i → i) : p c → (∀x, p x → p (f x)) → p (f (f (f c))) := by super example (i) (p : i → Prop) : ∀x, p x → ∃x, p x := by super example (i) [nonempty i] (p : i → i → Prop) : (∀x y, p x y) → ∃x, ∀z, p x z := by super example (i) [nonempty i] (p : i → Prop) : (∀x, p x) → ¬¬∀x, p x := by super -- Requires non-empty domain. example {i} [nonempty i] (p : i → Prop) : (∀x y, p x ∨ p y) → ∃x y, p x ∧ p y := by super example (i) (a b : i) (p : i → Prop) (H : a = b) : p b → p a := by super example (i) (a b : i) (p : i → Prop) (H : a = b) : p a → p b := by super example (i) (a b : i) (p : i → Prop) (H : a = b) : p b = p a := by super example (i) (c : i) (p : i → Prop) (f g : i → i) : p c → (∀x, p x → p (f x)) → (∀x, p x → f x = g x) → f (f c) = g (g c) := by super example (i) (p q : i → i → Prop) (a b c d : i) : (∀x y z, p x y ∧ p y z → p x z) → (∀x y z, q x y ∧ q y z → q x z) → (∀x y, q x y → q y x) → (∀x y, p x y ∨ q x y) → p a b ∨ q c d := by super -- This example from Davis-Putnam actually requires a non-empty domain example (i) [nonempty i] (f g : i → i → Prop) : ∃x y, ∀z, (f x y → f y z ∧ f z z) ∧ (f x y ∧ g x y → g x z ∧ g z z) := by super example (person) [nonempty person] (drinks : person → Prop) : ∃canary, drinks canary → ∀other, drinks other := by super example {p q : ℕ → Prop} {r} : (∀x y, p x ∧ q y ∧ r) -> ∀x, (p x ∧ r ∧ q x) := by super
246997a485f435ab790f0e1efb67299859706a88
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Util/Paths.lean
8fa1385d3e5e30607f25e9272cdf201b84ae88a2
[ "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
916
lean
/- Copyright (c) 2021 Sebastian Ullrich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ import Lean.Data.Json import Lean.Util.Path /-! Communicating Lean search paths between processes -/ namespace Lean open System structure LeanPaths where oleanPath : SearchPath srcPath : SearchPath loadDynlibPaths : Array FilePath := #[] deriving ToJson, FromJson def initSrcSearchPath (_leanSysroot : FilePath) (sp : SearchPath := ∅) : IO SearchPath := do let srcSearchPath := if let some p := (← IO.getEnv "LEAN_SRC_PATH") then System.SearchPath.parse p else [] let srcPath := (← IO.appDir) / ".." / "src" / "lean" -- `lake/` should come first since on case-insensitive file systems, Lean thinks that `src/` also contains `Lake/` return srcSearchPath ++ sp ++ [srcPath / "lake", srcPath] end Lean
892139510656c0316f3edd78a95476de6cbbd0c2
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/category/Group/basic_auto.lean
c575bd489dd7c8e77ef96b5e792400ce47e7d8cf
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
10,603
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.category.Mon.basic import Mathlib.category_theory.endomorphism import Mathlib.PostPort universes u u_1 namespace Mathlib /-! # Category instances for group, add_group, comm_group, and add_comm_group. We introduce the bundled categories: * `Group` * `AddGroup` * `CommGroup` * `AddCommGroup` along with the relevant forgetful functors between them, and to the bundled monoid categories. -/ /-- The category of groups and group morphisms. -/ def AddGroup := category_theory.bundled add_group /-- The category of additive groups and group morphisms -/ namespace Group protected instance Mathlib.AddGroup.group.to_monoid.category_theory.bundled_hom.parent_projection : category_theory.bundled_hom.parent_projection add_group.to_add_monoid := category_theory.bundled_hom.parent_projection.mk protected instance has_coe_to_sort : has_coe_to_sort Group := category_theory.bundled.has_coe_to_sort /-- Construct a bundled `Group` from the underlying type and typeclass. -/ def of (X : Type u) [group X] : Group := category_theory.bundled.of X /-- Construct a bundled `AddGroup` from the underlying type and typeclass. -/ protected instance group (G : Group) : group ↥G := category_theory.bundled.str G @[simp] theorem coe_of (R : Type u) [group R] : ↥(of R) = R := rfl protected instance Mathlib.AddGroup.has_zero : HasZero AddGroup := { zero := AddGroup.of PUnit } protected instance inhabited : Inhabited Group := { default := 1 } protected instance one.unique : unique ↥1 := unique.mk { default := 1 } sorry @[simp] theorem one_apply (G : Group) (H : Group) (g : ↥G) : coe_fn 1 g = 1 := rfl theorem ext (G : Group) (H : Group) (f₁ : G ⟶ H) (f₂ : G ⟶ H) (w : ∀ (x : ↥G), coe_fn f₁ x = coe_fn f₂ x) : f₁ = f₂ := monoid_hom.ext fun (x : ↥G) => w x -- should to_additive do this automatically? protected instance Mathlib.AddGroup.has_forget_to_AddMon : category_theory.has_forget₂ AddGroup AddMon := category_theory.bundled_hom.forget₂ add_monoid_hom add_group.to_add_monoid end Group /-- The category of commutative groups and group morphisms. -/ def AddCommGroup := category_theory.bundled add_comm_group /-- The category of additive commutative groups and group morphisms. -/ /-- `Ab` is an abbreviation for `AddCommGroup`, for the sake of mathematicians' sanity. -/ def Ab := AddCommGroup namespace CommGroup protected instance comm_group.to_group.category_theory.bundled_hom.parent_projection : category_theory.bundled_hom.parent_projection comm_group.to_group := category_theory.bundled_hom.parent_projection.mk protected instance large_category : category_theory.large_category CommGroup := category_theory.bundled_hom.category (category_theory.bundled_hom.map_hom (category_theory.bundled_hom.map_hom monoid_hom group.to_monoid) comm_group.to_group) /-- Construct a bundled `CommGroup` from the underlying type and typeclass. -/ def of (G : Type u) [comm_group G] : CommGroup := category_theory.bundled.of G /-- Construct a bundled `AddCommGroup` from the underlying type and typeclass. -/ protected instance Mathlib.AddCommGroup.add_comm_group_instance (G : AddCommGroup) : add_comm_group ↥G := category_theory.bundled.str G @[simp] theorem coe_of (R : Type u) [comm_group R] : ↥(of R) = R := rfl protected instance Mathlib.AddCommGroup.has_zero : HasZero AddCommGroup := { zero := AddCommGroup.of PUnit } protected instance inhabited : Inhabited CommGroup := { default := 1 } protected instance one.unique : unique ↥1 := unique.mk { default := 1 } sorry @[simp] theorem one_apply (G : CommGroup) (H : CommGroup) (g : ↥G) : coe_fn 1 g = 1 := rfl theorem ext (G : CommGroup) (H : CommGroup) (f₁ : G ⟶ H) (f₂ : G ⟶ H) (w : ∀ (x : ↥G), coe_fn f₁ x = coe_fn f₂ x) : f₁ = f₂ := monoid_hom.ext fun (x : ↥G) => w x protected instance Mathlib.AddCommGroup.has_forget_to_AddGroup : category_theory.has_forget₂ AddCommGroup AddGroup := category_theory.bundled_hom.forget₂ (category_theory.bundled_hom.map_hom add_monoid_hom add_group.to_add_monoid) add_comm_group.to_add_group protected instance Mathlib.AddCommGroup.has_forget_to_AddCommMon : category_theory.has_forget₂ AddCommGroup AddCommMon := category_theory.induced_category.has_forget₂ fun (G : AddCommGroup) => AddCommMon.of ↥G end CommGroup -- This example verifies an improvement possible in Lean 3.8. -- Before that, to have `monoid_hom.map_map` usable by `simp` here, -- we had to mark all the concrete category `has_coe_to_sort` instances reducible. -- Now, it just works. namespace AddCommGroup /-- Any element of an abelian group gives a unique morphism from `ℤ` sending `1` to that element. -/ -- Note that because `ℤ : Type 0`, this forces `G : AddCommGroup.{0}`, -- so we write this explicitly to be clear. -- TODO generalize this, requiring a `ulift_instances.lean` file def as_hom {G : AddCommGroup} (g : ↥G) : of ℤ ⟶ G := coe_fn (gmultiples_hom ↥G) g @[simp] theorem as_hom_apply {G : AddCommGroup} (g : ↥G) (i : ℤ) : coe_fn (as_hom g) i = i • g := rfl theorem as_hom_injective {G : AddCommGroup} : function.injective as_hom := sorry theorem int_hom_ext {G : AddCommGroup} (f : of ℤ ⟶ G) (g : of ℤ ⟶ G) (w : coe_fn f 1 = coe_fn g 1) : f = g := add_monoid_hom.ext_int w -- TODO: this argument should be generalised to the situation where -- the forgetful functor is representable. theorem injective_of_mono {G : AddCommGroup} {H : AddCommGroup} (f : G ⟶ H) [category_theory.mono f] : function.injective ⇑f := sorry end AddCommGroup /-- Build an isomorphism in the category `Group` from a `mul_equiv` between `group`s. -/ def mul_equiv.to_Group_iso {X : Type u} {Y : Type u} [group X] [group Y] (e : X ≃* Y) : Group.of X ≅ Group.of Y := category_theory.iso.mk (mul_equiv.to_monoid_hom e) (mul_equiv.to_monoid_hom (mul_equiv.symm e)) /-- Build an isomorphism in the category `AddGroup` from an `add_equiv` between `add_group`s. -/ /-- Build an isomorphism in the category `CommGroup` from a `mul_equiv` between `comm_group`s. -/ def add_equiv.to_AddCommGroup_iso {X : Type u} {Y : Type u} [add_comm_group X] [add_comm_group Y] (e : X ≃+ Y) : AddCommGroup.of X ≅ AddCommGroup.of Y := category_theory.iso.mk (add_equiv.to_add_monoid_hom e) (add_equiv.to_add_monoid_hom (add_equiv.symm e)) /-- Build an isomorphism in the category `AddCommGroup` from a `add_equiv` between `add_comm_group`s. -/ namespace category_theory.iso /-- Build a `mul_equiv` from an isomorphism in the category `Group`. -/ @[simp] theorem Group_iso_to_add_equiv_apply {X : AddGroup} {Y : AddGroup} (i : X ≅ Y) : ∀ (ᾰ : ↥X), coe_fn (AddGroup_iso_to_add_equiv i) ᾰ = coe_fn (hom i) ᾰ := fun (ᾰ : ↥X) => Eq.refl (coe_fn (hom i) ᾰ) /-- Build a `mul_equiv` from an isomorphism in the category `CommGroup`. -/ @[simp] theorem CommGroup_iso_to_add_equiv_apply {X : AddCommGroup} {Y : AddCommGroup} (i : X ≅ Y) : ∀ (ᾰ : ↥X), coe_fn (AddCommGroup_iso_to_add_equiv i) ᾰ = coe_fn (hom i) ᾰ := fun (ᾰ : ↥X) => Eq.refl (coe_fn (hom i) ᾰ) end category_theory.iso /-- multiplicative equivalences between `group`s are the same as (isomorphic to) isomorphisms in `Group` -/ def add_equiv_iso_AddGroup_iso {X : Type u} {Y : Type u} [add_group X] [add_group Y] : X ≃+ Y ≅ AddGroup.of X ≅ AddGroup.of Y := category_theory.iso.mk (fun (e : X ≃+ Y) => add_equiv.to_AddGroup_iso e) fun (i : AddGroup.of X ≅ AddGroup.of Y) => category_theory.iso.AddGroup_iso_to_add_equiv i /-- multiplicative equivalences between `comm_group`s are the same as (isomorphic to) isomorphisms in `CommGroup` -/ def mul_equiv_iso_CommGroup_iso {X : Type u} {Y : Type u} [comm_group X] [comm_group Y] : X ≃* Y ≅ CommGroup.of X ≅ CommGroup.of Y := category_theory.iso.mk (fun (e : X ≃* Y) => mul_equiv.to_CommGroup_iso e) fun (i : CommGroup.of X ≅ CommGroup.of Y) => category_theory.iso.CommGroup_iso_to_mul_equiv i namespace category_theory.Aut /-- The (bundled) group of automorphisms of a type is isomorphic to the (bundled) group of permutations. -/ def iso_perm {α : Type u} : Group.of (Aut α) ≅ Group.of (equiv.perm α) := iso.mk (monoid_hom.mk (fun (g : ↥(Group.of (Aut α))) => iso.to_equiv g) sorry sorry) (monoid_hom.mk (fun (g : ↥(Group.of (equiv.perm α))) => equiv.to_iso g) sorry sorry) /-- The (unbundled) group of automorphisms of a type is `mul_equiv` to the (unbundled) group of permutations. -/ def mul_equiv_perm {α : Type u} : Aut α ≃* equiv.perm α := iso.Group_iso_to_mul_equiv iso_perm end category_theory.Aut protected instance Group.forget_reflects_isos : category_theory.reflects_isomorphisms (category_theory.forget Group) := category_theory.reflects_isomorphisms.mk fun (X Y : Group) (f : X ⟶ Y) (_x : category_theory.is_iso (category_theory.functor.map (category_theory.forget Group) f)) => let i : category_theory.functor.obj (category_theory.forget Group) X ≅ category_theory.functor.obj (category_theory.forget Group) Y := category_theory.as_iso (category_theory.functor.map (category_theory.forget Group) f); let e : ↥X ≃* ↥Y := mul_equiv.mk (monoid_hom.to_fun f) (equiv.inv_fun (category_theory.iso.to_equiv i)) sorry sorry sorry; category_theory.is_iso.mk (category_theory.iso.inv (mul_equiv.to_Group_iso e)) protected instance CommGroup.forget_reflects_isos : category_theory.reflects_isomorphisms (category_theory.forget CommGroup) := category_theory.reflects_isomorphisms.mk fun (X Y : CommGroup) (f : X ⟶ Y) (_x : category_theory.is_iso (category_theory.functor.map (category_theory.forget CommGroup) f)) => let i : category_theory.functor.obj (category_theory.forget CommGroup) X ≅ category_theory.functor.obj (category_theory.forget CommGroup) Y := category_theory.as_iso (category_theory.functor.map (category_theory.forget CommGroup) f); let e : ↥X ≃* ↥Y := mul_equiv.mk (monoid_hom.to_fun f) (equiv.inv_fun (category_theory.iso.to_equiv i)) sorry sorry sorry; category_theory.is_iso.mk (category_theory.iso.inv (mul_equiv.to_CommGroup_iso e)) end Mathlib
c2d8265b3ff06626a9101d9d12df1bda678eac64
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/probability/kernel/with_density.lean
8a50da8a2afca5831141ef7e0ea43a4c0a98dcec
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
11,355
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 import measure_theory.integral.set_integral /-! # With Density > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. 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 integral_with_density {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [complete_space E] {f : β → E} [is_s_finite_kernel κ] {a : α} {g : α → β → ℝ≥0} (hg : measurable (function.uncurry g)) : ∫ b, f b ∂(with_density κ (λ a b, g a b) a) = ∫ b, (g a b) • f b ∂(κ a) := begin rw [kernel.with_density_apply, integral_with_density_eq_integral_smul], { exact measurable.of_uncurry_left hg, }, { exact measurable_coe_nnreal_ennreal.comp hg, }, 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
5b139a516ccd6076b741033069f1668eb5262d82
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/json.lean
d497e0acff8f17171eb9e82c3deae4e20dd3d3ed
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
11,015
lean
/- Copyright (c) 2022 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import tactic.core /-! # Json serialization typeclass This file provides helpers for serializing primitive types to json. `@[derive non_null_json_serializable]` will make any structure json serializable; for instance, ```lean @[derive non_null_json_serializable] structure my_struct := (success : bool) (verbose : ℕ := 0) (extras : option string := none) ``` can parse `{"success": true}` as `my_struct.mk true 0 none`, and reserializing give `{"success": true, "verbose": 0, "extras": null}`. ## Main definitions * `json_serializable`: a typeclass for objects which serialize to json * `json_serializable.to_json x`: convert `x` to json * `json_serializable.of_json α j`: read `j` in as an `α` -/ open exceptional meta instance : has_orelse exceptional := { orelse := λ α f g, match f with | success x := success x | exception msg := g end } /-- A class to indicate that a type is json serializable -/ meta class json_serializable (α : Type) := (to_json : α → json) (of_json [] : json → exceptional α) /-- A class for types which never serialize to null -/ meta class non_null_json_serializable (α : Type) extends json_serializable α export json_serializable (to_json of_json) /-- Describe the type of a json value -/ meta def json.typename : json → string | (json.of_string _) := "string" | (json.of_int _) := "number" | (json.of_float _) := "number" | (json.of_bool _) := "bool" | json.null := "null" | (json.object _) := "object" | (json.array _) := "array" /-! ### Primitive types -/ meta instance : non_null_json_serializable string := { to_json := json.of_string, of_json := λ j, do json.of_string s ← success j | exception (λ _, format!"string expected, got {j.typename}"), pure s } meta instance : non_null_json_serializable ℤ := { to_json := λ z, json.of_int z, of_json := λ j, do json.of_int z ← success j | do { json.of_float f ← success j | exception (λ _, format!"number expected, got {j.typename}"), exception (λ _, format!"number must be integral") }, pure z } meta instance : non_null_json_serializable native.float := { to_json := λ f, json.of_float f, of_json := λ j, do json.of_int z ← success j | do { json.of_float f ← success j | exception (λ _, format!"number expected, got {j.typename}"), pure f }, pure z } meta instance : non_null_json_serializable bool := { to_json := λ b, json.of_bool b, of_json := λ j, do json.of_bool b ← success j | exception (λ _, format!"boolean expected, got {j.typename}"), pure b } meta instance : json_serializable punit := { to_json := λ u, json.null, of_json := λ j, do json.null ← success j | exception (λ _, format!"null expected, got {j.typename}"), pure () } meta instance {α} [json_serializable α] : non_null_json_serializable (list α) := { to_json := λ l, json.array (l.map to_json), of_json := λ j, do json.array l ← success j | exception (λ _, format!"array expected, got {j.typename}"), l.mmap (of_json α) } meta instance {α} [json_serializable α] : json_serializable (rbmap string α) := { to_json := λ m, json.object (m.to_list.map $ λ x, (x.1, to_json x.2)), of_json := λ j, do json.object l ← success j | exception (λ _, format!"object expected, got {j.typename}"), l ← l.mmap (λ x : string × json, do x2 ← of_json α x.2, pure (x.1, x2)), l.mfoldl (λ m x, do none ← pure (m.find x.1) | exception (λ _, format!"duplicate key {x.1}"), pure (m.insert x.1 x.2)) (mk_rbmap _ _) } /-! ### Basic coercions -/ meta instance : non_null_json_serializable ℕ := { to_json := λ n, to_json (n : ℤ), of_json := λ j, do int.of_nat n ← of_json ℤ j | exception (λ _, format!"must be non-negative"), pure n } meta instance {n : ℕ} : non_null_json_serializable (fin n) := { to_json := λ i, to_json i.val, of_json := λ j, do i ← of_json ℕ j, if h : i < n then pure ⟨i, h⟩ else exception (λ _, format!"must be less than {n}") } meta instance {α : Type} [json_serializable α] (p : α → Prop) [decidable_pred p] : json_serializable (subtype p) := { to_json := λ x, to_json (x : α), of_json := λ j, do i ← of_json α j, if h : p i then pure (subtype.mk i h) else exception (λ _, format!"condition does not hold") } /-- Note this only makes sense on types which do not themselves serialize to `null` -/ meta instance {α} [non_null_json_serializable α] : json_serializable (option α) := { to_json := option.elim json.null to_json, of_json := λ j, do (of_json punit j >> pure none) <|> (some <$> of_json α j)} open tactic expr /-- Flatten a list of (p)exprs into a (p)expr forming a list of type `list t`. -/ meta def list.to_expr {elab : bool} (t : expr elab) (l : level) : list (expr elab) → expr elab | [] := expr.app (expr.const `list.nil [l]) t | (x :: xs) := (((expr.const `list.cons [l]).app t).app x).app xs.to_expr /-- Begin parsing fields -/ meta def json_serializable.field_starter (j : json) : exceptional (list (string × json)) := do json.object p ← pure j | exception (λ _, format!"object expected, got {j.typename}"), pure p /-- Check a field exists and is unique -/ meta def json_serializable.field_get (l : list (string × json)) (s : string) : exceptional (option json × list (string × json)) := let (p, n) := l.partition (λ x, prod.fst x = s) in match p with | [] := pure (none, n) | [x] := pure (some x.2, n) | x :: xs := exception (λ _, format!"duplicate {s} field") end /-- Check no fields remain -/ meta def json_serializable.field_terminator (l : list (string × json)) : exceptional unit := do [] ← pure l | exception (λ _, format!"unexpected fields {l.map prod.fst}"), pure () /-- ``((c_name, c_fun), [(p_name, p_fun), ...]) ← get_constructor_and_projections `(struct n)`` gets the names and partial invocations of the constructor and projections of a structure -/ meta def get_constructor_and_projections (t : expr) : tactic (name × (name × expr) × list (name × expr)):= do (const I ls, args) ← pure (get_app_fn_args t), env ← get_env, [ctor] ← pure (env.constructors_of I), ctor ← do { d ← get_decl ctor, let a := @expr.const tt ctor $ d.univ_params.map level.param, pure (ctor, a.mk_app args) }, ctor_type ← infer_type ctor.2, tt ← pure ctor_type.is_pi | pure (I, ctor, []), some fields ← pure (env.structure_fields I) | fail!"Not a structure", projs ← fields.mmap $ λ f, do { d ← get_decl (I ++ f), let a := @expr.const tt (I ++ f) $ d.univ_params.map level.param, pure (f, a.mk_app args) }, pure (I, ctor, projs) /-- Generate an expression that builds a term of type `t` (which is itself a parametrization of the structure `struct_name`) using the expressions resolving to parsed fields in `vars` and the expressions resolving to unparsed `option json` objects in `js`. This can handled dependently-typed and defaulted (via `:=` which for structures is not the same as `opt_param`) fields. -/ meta def of_json_helper (struct_name : name) (t : expr) : Π (vars : list (name × pexpr)) (js : list (name × option expr)), tactic expr | vars [] := do -- allow this partial constructor if `to_expr` allows it let struct := pexpr.mk_structure_instance ⟨some struct_name, vars.map prod.fst, vars.map prod.snd, []⟩, to_expr ``(pure %%struct : exceptional %%t) | vars ((fname, some fj) :: js) := do -- data fields u ← mk_meta_univ, ft : expr ← mk_meta_var (expr.sort u), f_binder ← mk_local' fname binder_info.default ft, let new_vars := vars.concat (fname, to_pexpr f_binder), with_field ← of_json_helper new_vars js >>= tactic.lambdas [f_binder], without_field ← of_json_helper vars js <|> to_expr ``(exception $ λ o, format!"field {%%`(fname)} is required" : exceptional %%t), to_expr ``(option.mmap (of_json _) %%fj >>= option.elim %%without_field %%with_field : exceptional %%t) | vars ((fname, none) :: js) := -- try a default value of_json_helper vars js <|> do { -- otherwise, use decidability u ← mk_meta_univ, ft ← mk_meta_var (expr.sort u), f_binder ← mk_local' fname binder_info.default ft, let new_vars := vars.concat (fname, to_pexpr f_binder), with_field ← of_json_helper new_vars js >>= tactic.lambdas [f_binder], to_expr ``(dite _ %%with_field (λ _, exception $ λ _, format!"condition does not hold")) } /-- A derive handler to serialize structures by their fields. For the following structure: ```lean structure has_default : Type := (x : ℕ := 2) (y : fin x.succ := 3 * fin.of_nat x) (z : ℕ := 3) ``` this generates an `of_json` parser along the lines of ```lean meta def has_default.of_json (j : json) : exceptional (has_default) := do p ← json_serializable.field_starter j, (f_y, p) ← json_serializable.field_get p "y", (f_z, p) ← json_serializable.field_get p "z", f_y.mmap (of_json _) >>= option.elim (f_z.mmap (of_json _) >>= option.elim (pure {has_default.}) (λ z, pure {has_default. z := z}) ) (λ y, f_z.mmap (of_json _) >>= option.elim (pure {has_default.}) (λ z, pure {has_default. y := y, z := z}) ) ``` -/ @[derive_handler, priority 2000] meta def non_null_json_serializable_handler : derive_handler := instance_derive_handler ``non_null_json_serializable $ do intros, `(non_null_json_serializable %%e) ← target >>= whnf, (struct_name, (ctor_name, ctor), fields) ← get_constructor_and_projections e, refine ``(@non_null_json_serializable.mk %%e ⟨λ x, json.object _, λ j, json_serializable.field_starter j >>= _ ⟩), -- the forward direction x ← get_local `x, (projs : list (option expr)) ← fields.mmap (λ ⟨f, a⟩, do let x_e := a.app x, t ← infer_type x_e, s ← infer_type t, expr.sort (level.succ u) ← pure s | pure (none : option expr), level.zero ← pure u | fail!"Only Type 0 is supported", j ← tactic.mk_app `json_serializable.to_json [x_e], pure (some `((%%`(f.to_string), %%j) : string × json)) ), tactic.exact (projs.reduce_option.to_expr `(string × json) level.zero), -- the reverse direction get_local `j >>= tactic.clear, -- check fields are present json_fields ← fields.mmap (λ ⟨f, e⟩, do t ← infer_type e, s ← infer_type t, expr.sort (level.succ u) ← pure s | pure (f, none), -- do nothing for prop fields refine ``(λ p, json_serializable.field_get p %%`(f.to_string) >>= _), tactic.applyc `prod.rec, get_local `p >>= tactic.clear, jf ← tactic.intro (`field ++ f), pure (f, some jf)), refine ``(λ p, json_serializable.field_terminator p >> _), get_local `p >>= tactic.clear, ctor ← of_json_helper struct_name e [] json_fields, exact ctor
8938007cddb5e70bef6941eb117795955f6c0704
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/metric_space/antilipschitz.lean
c08fbf9d2ef796491557b5a363c9bbf5115e2102
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
9,977
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import topology.metric_space.lipschitz import topology.uniform_space.complete_separated /-! # Antilipschitz functions > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We say that a map `f : α → β` between two (extended) metric spaces is `antilipschitz_with K`, `K ≥ 0`, if for all `x, y` we have `edist x y ≤ K * edist (f x) (f y)`. For a metric space, the latter inequality is equivalent to `dist x y ≤ K * dist (f x) (f y)`. ## Implementation notes The parameter `K` has type `ℝ≥0`. This way we avoid conjuction in the definition and have coercions both to `ℝ` and `ℝ≥0∞`. We do not require `0 < K` in the definition, mostly because we do not have a `posreal` type. -/ variables {α : Type*} {β : Type*} {γ : Type*} open_locale nnreal ennreal uniformity open set filter bornology /-- We say that `f : α → β` is `antilipschitz_with K` if for any two points `x`, `y` we have `edist x y ≤ K * edist (f x) (f y)`. -/ def antilipschitz_with [pseudo_emetric_space α] [pseudo_emetric_space β] (K : ℝ≥0) (f : α → β) := ∀ x y, edist x y ≤ K * edist (f x) (f y) lemma antilipschitz_with.edist_lt_top [pseudo_emetric_space α] [pseudo_metric_space β] {K : ℝ≥0} {f : α → β} (h : antilipschitz_with K f) (x y : α) : edist x y < ⊤ := (h x y).trans_lt $ ennreal.mul_lt_top ennreal.coe_ne_top (edist_ne_top _ _) lemma antilipschitz_with.edist_ne_top [pseudo_emetric_space α] [pseudo_metric_space β] {K : ℝ≥0} {f : α → β} (h : antilipschitz_with K f) (x y : α) : edist x y ≠ ⊤ := (h.edist_lt_top x y).ne section metric variables [pseudo_metric_space α] [pseudo_metric_space β] {K : ℝ≥0} {f : α → β} lemma antilipschitz_with_iff_le_mul_nndist : antilipschitz_with K f ↔ ∀ x y, nndist x y ≤ K * nndist (f x) (f y) := by { simp only [antilipschitz_with, edist_nndist], norm_cast } alias antilipschitz_with_iff_le_mul_nndist ↔ antilipschitz_with.le_mul_nndist antilipschitz_with.of_le_mul_nndist lemma antilipschitz_with_iff_le_mul_dist : antilipschitz_with K f ↔ ∀ x y, dist x y ≤ K * dist (f x) (f y) := by { simp only [antilipschitz_with_iff_le_mul_nndist, dist_nndist], norm_cast } alias antilipschitz_with_iff_le_mul_dist ↔ antilipschitz_with.le_mul_dist antilipschitz_with.of_le_mul_dist namespace antilipschitz_with lemma mul_le_nndist (hf : antilipschitz_with K f) (x y : α) : K⁻¹ * nndist x y ≤ nndist (f x) (f y) := by simpa only [div_eq_inv_mul] using nnreal.div_le_of_le_mul' (hf.le_mul_nndist x y) lemma mul_le_dist (hf : antilipschitz_with K f) (x y : α) : (K⁻¹ * dist x y : ℝ) ≤ dist (f x) (f y) := by exact_mod_cast hf.mul_le_nndist x y end antilipschitz_with end metric namespace antilipschitz_with variables [pseudo_emetric_space α] [pseudo_emetric_space β] [pseudo_emetric_space γ] variables {K : ℝ≥0} {f : α → β} open emetric /-- Extract the constant from `hf : antilipschitz_with K f`. This is useful, e.g., if `K` is given by a long formula, and we want to reuse this value. -/ @[nolint unused_arguments] -- uses neither `f` nor `hf` protected def K (hf : antilipschitz_with K f) : ℝ≥0 := K protected lemma injective {α : Type*} {β : Type*} [emetric_space α] [pseudo_emetric_space β] {K : ℝ≥0} {f : α → β} (hf : antilipschitz_with K f) : function.injective f := λ x y h, by simpa only [h, edist_self, mul_zero, edist_le_zero] using hf x y lemma mul_le_edist (hf : antilipschitz_with K f) (x y : α) : (K⁻¹ * edist x y : ℝ≥0∞) ≤ edist (f x) (f y) := begin rw [mul_comm, ← div_eq_mul_inv], exact ennreal.div_le_of_le_mul' (hf x y) end lemma ediam_preimage_le (hf : antilipschitz_with K f) (s : set β) : diam (f ⁻¹' s) ≤ K * diam s := diam_le $ λ x hx y hy, (hf x y).trans $ mul_le_mul_left' (edist_le_diam_of_mem hx hy) K lemma le_mul_ediam_image (hf : antilipschitz_with K f) (s : set α) : diam s ≤ K * diam (f '' s) := (diam_mono (subset_preimage_image _ _)).trans (hf.ediam_preimage_le (f '' s)) protected lemma id : antilipschitz_with 1 (id : α → α) := λ x y, by simp only [ennreal.coe_one, one_mul, id, le_refl] lemma comp {Kg : ℝ≥0} {g : β → γ} (hg : antilipschitz_with Kg g) {Kf : ℝ≥0} {f : α → β} (hf : antilipschitz_with Kf f) : antilipschitz_with (Kf * Kg) (g ∘ f) := λ x y, calc edist x y ≤ Kf * edist (f x) (f y) : hf x y ... ≤ Kf * (Kg * edist (g (f x)) (g (f y))) : ennreal.mul_left_mono (hg _ _) ... = _ : by rw [ennreal.coe_mul, mul_assoc] lemma restrict (hf : antilipschitz_with K f) (s : set α) : antilipschitz_with K (s.restrict f) := λ x y, hf x y lemma cod_restrict (hf : antilipschitz_with K f) {s : set β} (hs : ∀ x, f x ∈ s) : antilipschitz_with K (s.cod_restrict f hs) := λ x y, hf x y lemma to_right_inv_on' {s : set α} (hf : antilipschitz_with K (s.restrict f)) {g : β → α} {t : set β} (g_maps : maps_to g t s) (g_inv : right_inv_on g f t) : lipschitz_with K (t.restrict g) := λ x y, by simpa only [restrict_apply, g_inv x.mem, g_inv y.mem, subtype.edist_eq, subtype.coe_mk] using hf ⟨g x, g_maps x.mem⟩ ⟨g y, g_maps y.mem⟩ lemma to_right_inv_on (hf : antilipschitz_with K f) {g : β → α} {t : set β} (h : right_inv_on g f t) : lipschitz_with K (t.restrict g) := (hf.restrict univ).to_right_inv_on' (maps_to_univ g t) h lemma to_right_inverse (hf : antilipschitz_with K f) {g : β → α} (hg : function.right_inverse g f) : lipschitz_with K g := begin intros x y, have := hf (g x) (g y), rwa [hg x, hg y] at this end lemma comap_uniformity_le (hf : antilipschitz_with K f) : (𝓤 β).comap (prod.map f f) ≤ 𝓤 α := begin refine ((uniformity_basis_edist.comap _).le_basis_iff uniformity_basis_edist).2 (λ ε h₀, _), refine ⟨K⁻¹ * ε, ennreal.mul_pos (ennreal.inv_ne_zero.2 ennreal.coe_ne_top) h₀.ne', _⟩, refine λ x hx, (hf x.1 x.2).trans_lt _, rw [mul_comm, ← div_eq_mul_inv] at hx, rw mul_comm, exact ennreal.mul_lt_of_lt_div hx end protected lemma uniform_inducing (hf : antilipschitz_with K f) (hfc : uniform_continuous f) : uniform_inducing f := ⟨le_antisymm hf.comap_uniformity_le hfc.le_comap⟩ protected lemma uniform_embedding {α : Type*} {β : Type*} [emetric_space α] [pseudo_emetric_space β] {K : ℝ≥0} {f : α → β} (hf : antilipschitz_with K f) (hfc : uniform_continuous f) : uniform_embedding f := ⟨hf.uniform_inducing hfc, hf.injective⟩ lemma is_complete_range [complete_space α] (hf : antilipschitz_with K f) (hfc : uniform_continuous f) : is_complete (range f) := (hf.uniform_inducing hfc).is_complete_range lemma is_closed_range {α β : Type*} [pseudo_emetric_space α] [emetric_space β] [complete_space α] {f : α → β} {K : ℝ≥0} (hf : antilipschitz_with K f) (hfc : uniform_continuous f) : is_closed (range f) := (hf.is_complete_range hfc).is_closed lemma closed_embedding {α : Type*} {β : Type*} [emetric_space α] [emetric_space β] {K : ℝ≥0} {f : α → β} [complete_space α] (hf : antilipschitz_with K f) (hfc : uniform_continuous f) : closed_embedding f := { closed_range := hf.is_closed_range hfc, .. (hf.uniform_embedding hfc).embedding } lemma subtype_coe (s : set α) : antilipschitz_with 1 (coe : s → α) := antilipschitz_with.id.restrict s lemma of_subsingleton [subsingleton α] {K : ℝ≥0} : antilipschitz_with K f := λ x y, by simp only [subsingleton.elim x y, edist_self, zero_le] /-- If `f : α → β` is `0`-antilipschitz, then `α` is a `subsingleton`. -/ protected lemma subsingleton {α β} [emetric_space α] [pseudo_emetric_space β] {f : α → β} (h : antilipschitz_with 0 f) : subsingleton α := ⟨λ x y, edist_le_zero.1 $ (h x y).trans_eq $ zero_mul _⟩ end antilipschitz_with namespace antilipschitz_with open metric variables [pseudo_metric_space α] [pseudo_metric_space β] {K : ℝ≥0} {f : α → β} lemma bounded_preimage (hf : antilipschitz_with K f) {s : set β} (hs : bounded s) : bounded (f ⁻¹' s) := exists.intro (K * diam s) $ λ x hx y hy, calc dist x y ≤ K * dist (f x) (f y) : hf.le_mul_dist x y ... ≤ K * diam s : mul_le_mul_of_nonneg_left (dist_le_diam_of_mem hs hx hy) K.2 lemma tendsto_cobounded (hf : antilipschitz_with K f) : tendsto f (cobounded α) (cobounded β) := compl_surjective.forall.2 $ λ s (hs : is_bounded s), metric.is_bounded_iff.2 $ hf.bounded_preimage $ metric.is_bounded_iff.1 hs /-- The image of a proper space under an expanding onto map is proper. -/ protected lemma proper_space {α : Type*} [metric_space α] {K : ℝ≥0} {f : α → β} [proper_space α] (hK : antilipschitz_with K f) (f_cont : continuous f) (hf : function.surjective f) : proper_space β := begin apply proper_space_of_compact_closed_ball_of_le 0 (λx₀ r hr, _), let K := f ⁻¹' (closed_ball x₀ r), have A : is_closed K := is_closed_ball.preimage f_cont, have B : bounded K := hK.bounded_preimage bounded_closed_ball, have : is_compact K := is_compact_iff_is_closed_bounded.2 ⟨A, B⟩, convert this.image f_cont, exact (hf.image_preimage _).symm end end antilipschitz_with lemma lipschitz_with.to_right_inverse [pseudo_emetric_space α] [pseudo_emetric_space β] {K : ℝ≥0} {f : α → β} (hf : lipschitz_with K f) {g : β → α} (hg : function.right_inverse g f) : antilipschitz_with K g := λ x y, by simpa only [hg _] using hf (g x) (g y) /-- The preimage of a proper space under a Lipschitz homeomorphism is proper. -/ @[protected] theorem lipschitz_with.proper_space [pseudo_metric_space α] [metric_space β] [proper_space β] {K : ℝ≥0} {f : α ≃ₜ β} (hK : lipschitz_with K f) : proper_space α := (hK.to_right_inverse f.right_inv).proper_space f.symm.continuous f.symm.surjective
30bb38af09fe68cb3ee2339b2b49e48857e1f815
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/normed_space/pointwise.lean
c28ea4ad6cb4b03bef8c85fc8cb252b5625cc546
[ "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
16,424
lean
/- Copyright (c) 2021 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Yaël Dillies -/ import analysis.normed.group.add_torsor import analysis.normed.group.pointwise import analysis.normed_space.basic /-! # Properties of pointwise scalar multiplication of sets in normed spaces. We explore the relationships between scalar multiplication of sets in vector spaces, and the norm. Notably, we express arbitrary balls as rescaling of other balls, and we show that the multiplication of bounded sets remain bounded. -/ open metric set open_locale pointwise topological_space variables {𝕜 E : Type*} [normed_field 𝕜] section seminormed_add_comm_group variables [seminormed_add_comm_group E] [normed_space 𝕜 E] theorem smul_ball {c : 𝕜} (hc : c ≠ 0) (x : E) (r : ℝ) : c • ball x r = ball (c • x) (‖c‖ * r) := begin ext y, rw mem_smul_set_iff_inv_smul_mem₀ hc, conv_lhs { rw ←inv_smul_smul₀ hc x }, simp [← div_eq_inv_mul, div_lt_iff (norm_pos_iff.2 hc), mul_comm _ r, dist_smul], end lemma smul_unit_ball {c : 𝕜} (hc : c ≠ 0) : c • ball (0 : E) (1 : ℝ) = ball (0 : E) (‖c‖) := by rw [smul_ball hc, smul_zero, mul_one] theorem smul_sphere' {c : 𝕜} (hc : c ≠ 0) (x : E) (r : ℝ) : c • sphere x r = sphere (c • x) (‖c‖ * r) := begin ext y, rw mem_smul_set_iff_inv_smul_mem₀ hc, conv_lhs { rw ←inv_smul_smul₀ hc x }, simp only [mem_sphere, dist_smul, norm_inv, ← div_eq_inv_mul, div_eq_iff (norm_pos_iff.2 hc).ne', mul_comm r], end theorem smul_closed_ball' {c : 𝕜} (hc : c ≠ 0) (x : E) (r : ℝ) : c • closed_ball x r = closed_ball (c • x) (‖c‖ * r) := by simp only [← ball_union_sphere, set.smul_set_union, smul_ball hc, smul_sphere' hc] lemma metric.bounded.smul {s : set E} (hs : bounded s) (c : 𝕜) : bounded (c • s) := begin obtain ⟨R, hR⟩ : ∃ (R : ℝ), ∀ x ∈ s, ‖x‖ ≤ R := hs.exists_norm_le, refine bounded_iff_forall_norm_le.2 ⟨‖c‖ * R, λ z hz, _⟩, obtain ⟨y, ys, rfl⟩ : ∃ (y : E), y ∈ s ∧ c • y = z := mem_smul_set.1 hz, calc ‖c • y‖ = ‖c‖ * ‖y‖ : norm_smul _ _ ... ≤ ‖c‖ * R : mul_le_mul_of_nonneg_left (hR y ys) (norm_nonneg _) end /-- If `s` is a bounded set, then for small enough `r`, the set `{x} + r • s` is contained in any fixed neighborhood of `x`. -/ lemma eventually_singleton_add_smul_subset {x : E} {s : set E} (hs : bounded s) {u : set E} (hu : u ∈ 𝓝 x) : ∀ᶠ r in 𝓝 (0 : 𝕜), {x} + r • s ⊆ u := begin obtain ⟨ε, εpos, hε⟩ : ∃ ε (hε : 0 < ε), closed_ball x ε ⊆ u := nhds_basis_closed_ball.mem_iff.1 hu, obtain ⟨R, Rpos, hR⟩ : ∃ (R : ℝ), 0 < R ∧ s ⊆ closed_ball 0 R := hs.subset_ball_lt 0 0, have : metric.closed_ball (0 : 𝕜) (ε / R) ∈ 𝓝 (0 : 𝕜) := closed_ball_mem_nhds _ (div_pos εpos Rpos), filter_upwards [this] with r hr, simp only [image_add_left, singleton_add], assume y hy, obtain ⟨z, zs, hz⟩ : ∃ (z : E), z ∈ s ∧ r • z = -x + y, by simpa [mem_smul_set] using hy, have I : ‖r • z‖ ≤ ε := calc ‖r • z‖ = ‖r‖ * ‖z‖ : norm_smul _ _ ... ≤ (ε / R) * R : mul_le_mul (mem_closed_ball_zero_iff.1 hr) (mem_closed_ball_zero_iff.1 (hR zs)) (norm_nonneg _) (div_pos εpos Rpos).le ... = ε : by field_simp [Rpos.ne'], have : y = x + r • z, by simp only [hz, add_neg_cancel_left], apply hε, simpa only [this, dist_eq_norm, add_sub_cancel', mem_closed_ball] using I, end variables [normed_space ℝ E] {x y z : E} {δ ε : ℝ} /-- In a real normed space, the image of the unit ball under scalar multiplication by a positive constant `r` is the ball of radius `r`. -/ lemma smul_unit_ball_of_pos {r : ℝ} (hr : 0 < r) : r • ball 0 1 = ball (0 : E) r := by rw [smul_unit_ball hr.ne', real.norm_of_nonneg hr.le] -- This is also true for `ℚ`-normed spaces lemma exists_dist_eq (x z : E) {a b : ℝ} (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) : ∃ y, dist x y = b * dist x z ∧ dist y z = a * dist x z := begin use a • x + b • z, nth_rewrite 0 [←one_smul ℝ x], nth_rewrite 3 [←one_smul ℝ z], simp [dist_eq_norm, ←hab, add_smul, ←smul_sub, norm_smul_of_nonneg, ha, hb], end lemma exists_dist_le_le (hδ : 0 ≤ δ) (hε : 0 ≤ ε) (h : dist x z ≤ ε + δ) : ∃ y, dist x y ≤ δ ∧ dist y z ≤ ε := begin obtain rfl | hε' := hε.eq_or_lt, { exact ⟨z, by rwa zero_add at h, (dist_self _).le⟩ }, have hεδ := add_pos_of_pos_of_nonneg hε' hδ, refine (exists_dist_eq x z (div_nonneg hε $ add_nonneg hε hδ) (div_nonneg hδ $ add_nonneg hε hδ) $ by rw [←add_div, div_self hεδ.ne']).imp (λ y hy, _), rw [hy.1, hy.2, div_mul_comm, div_mul_comm ε], rw ←div_le_one hεδ at h, exact ⟨mul_le_of_le_one_left hδ h, mul_le_of_le_one_left hε h⟩, end -- This is also true for `ℚ`-normed spaces lemma exists_dist_le_lt (hδ : 0 ≤ δ) (hε : 0 < ε) (h : dist x z < ε + δ) : ∃ y, dist x y ≤ δ ∧ dist y z < ε := begin refine (exists_dist_eq x z (div_nonneg hε.le $ add_nonneg hε.le hδ) (div_nonneg hδ $ add_nonneg hε.le hδ) $ by rw [←add_div, div_self (add_pos_of_pos_of_nonneg hε hδ).ne']).imp (λ y hy, _), rw [hy.1, hy.2, div_mul_comm, div_mul_comm ε], rw ←div_lt_one (add_pos_of_pos_of_nonneg hε hδ) at h, exact ⟨mul_le_of_le_one_left hδ h.le, mul_lt_of_lt_one_left hε h⟩, end -- This is also true for `ℚ`-normed spaces lemma exists_dist_lt_le (hδ : 0 < δ) (hε : 0 ≤ ε) (h : dist x z < ε + δ) : ∃ y, dist x y < δ ∧ dist y z ≤ ε := begin obtain ⟨y, yz, xy⟩ := exists_dist_le_lt hε hδ (show dist z x < δ + ε, by simpa only [dist_comm, add_comm] using h), exact ⟨y, by simp [dist_comm x y, dist_comm y z, *]⟩, end -- This is also true for `ℚ`-normed spaces lemma exists_dist_lt_lt (hδ : 0 < δ) (hε : 0 < ε) (h : dist x z < ε + δ) : ∃ y, dist x y < δ ∧ dist y z < ε := begin refine (exists_dist_eq x z (div_nonneg hε.le $ add_nonneg hε.le hδ.le) (div_nonneg hδ.le $ add_nonneg hε.le hδ.le) $ by rw [←add_div, div_self (add_pos hε hδ).ne']).imp (λ y hy, _), rw [hy.1, hy.2, div_mul_comm, div_mul_comm ε], rw ←div_lt_one (add_pos hε hδ) at h, exact ⟨mul_lt_of_lt_one_left hδ h, mul_lt_of_lt_one_left hε h⟩, end -- This is also true for `ℚ`-normed spaces lemma disjoint_ball_ball_iff (hδ : 0 < δ) (hε : 0 < ε) : disjoint (ball x δ) (ball y ε) ↔ δ + ε ≤ dist x y := begin refine ⟨λ h, le_of_not_lt $ λ hxy, _, ball_disjoint_ball⟩, rw add_comm at hxy, obtain ⟨z, hxz, hzy⟩ := exists_dist_lt_lt hδ hε hxy, rw dist_comm at hxz, exact h.le_bot ⟨hxz, hzy⟩, end -- This is also true for `ℚ`-normed spaces lemma disjoint_ball_closed_ball_iff (hδ : 0 < δ) (hε : 0 ≤ ε) : disjoint (ball x δ) (closed_ball y ε) ↔ δ + ε ≤ dist x y := begin refine ⟨λ h, le_of_not_lt $ λ hxy, _, ball_disjoint_closed_ball⟩, rw add_comm at hxy, obtain ⟨z, hxz, hzy⟩ := exists_dist_lt_le hδ hε hxy, rw dist_comm at hxz, exact h.le_bot ⟨hxz, hzy⟩, end -- This is also true for `ℚ`-normed spaces lemma disjoint_closed_ball_ball_iff (hδ : 0 ≤ δ) (hε : 0 < ε) : disjoint (closed_ball x δ) (ball y ε) ↔ δ + ε ≤ dist x y := by rw [disjoint.comm, disjoint_ball_closed_ball_iff hε hδ, add_comm, dist_comm]; apply_instance lemma disjoint_closed_ball_closed_ball_iff (hδ : 0 ≤ δ) (hε : 0 ≤ ε) : disjoint (closed_ball x δ) (closed_ball y ε) ↔ δ + ε < dist x y := begin refine ⟨λ h, lt_of_not_ge $ λ hxy, _, closed_ball_disjoint_closed_ball⟩, rw add_comm at hxy, obtain ⟨z, hxz, hzy⟩ := exists_dist_le_le hδ hε hxy, rw dist_comm at hxz, exact h.le_bot ⟨hxz, hzy⟩, end open emetric ennreal @[simp] lemma inf_edist_thickening (hδ : 0 < δ) (s : set E) (x : E) : inf_edist x (thickening δ s) = inf_edist x s - ennreal.of_real δ := begin obtain hs | hs := lt_or_le (inf_edist x s) (ennreal.of_real δ), { rw [inf_edist_zero_of_mem, tsub_eq_zero_of_le hs.le], exact hs }, refine (tsub_le_iff_right.2 inf_edist_le_inf_edist_thickening_add).antisymm' _, refine le_sub_of_add_le_right of_real_ne_top _, refine le_inf_edist.2 (λ z hz, le_of_forall_lt' $ λ r h, _), cases r, { exact add_lt_top.2 ⟨lt_top_iff_ne_top.2 $ inf_edist_ne_top ⟨z, self_subset_thickening hδ _ hz⟩, of_real_lt_top⟩ }, have hr : 0 < ↑r - δ, { refine sub_pos_of_lt _, have := hs.trans_lt ((inf_edist_le_edist_of_mem hz).trans_lt h), rw [of_real_eq_coe_nnreal hδ.le, some_eq_coe] at this, exact_mod_cast this }, rw [some_eq_coe, edist_lt_coe, ←dist_lt_coe, ←add_sub_cancel'_right δ (↑r)] at h, obtain ⟨y, hxy, hyz⟩ := exists_dist_lt_lt hr hδ h, refine (ennreal.add_lt_add_right of_real_ne_top $ inf_edist_lt_iff.2 ⟨_, mem_thickening_iff.2 ⟨_, hz, hyz⟩, edist_lt_of_real.2 hxy⟩).trans_le _, rw [←of_real_add hr.le hδ.le, sub_add_cancel, of_real_coe_nnreal], exact le_rfl, end @[simp] lemma thickening_thickening (hε : 0 < ε) (hδ : 0 < δ) (s : set E) : thickening ε (thickening δ s) = thickening (ε + δ) s := (thickening_thickening_subset _ _ _).antisymm $ λ x, begin simp_rw mem_thickening_iff, rintro ⟨z, hz, hxz⟩, rw add_comm at hxz, obtain ⟨y, hxy, hyz⟩ := exists_dist_lt_lt hε hδ hxz, exact ⟨y, ⟨_, hz, hyz⟩, hxy⟩, end @[simp] lemma cthickening_thickening (hε : 0 ≤ ε) (hδ : 0 < δ) (s : set E) : cthickening ε (thickening δ s) = cthickening (ε + δ) s := (cthickening_thickening_subset hε _ _).antisymm $ λ x, begin simp_rw [mem_cthickening_iff, ennreal.of_real_add hε hδ.le, inf_edist_thickening hδ], exact tsub_le_iff_right.2, end -- Note: `interior (cthickening δ s) ≠ thickening δ s` in general @[simp] lemma closure_thickening (hδ : 0 < δ) (s : set E) : closure (thickening δ s) = cthickening δ s := by { rw [←cthickening_zero, cthickening_thickening le_rfl hδ, zero_add], apply_instance } @[simp] lemma inf_edist_cthickening (δ : ℝ) (s : set E) (x : E) : inf_edist x (cthickening δ s) = inf_edist x s - ennreal.of_real δ := begin obtain hδ | hδ := le_or_lt δ 0, { rw [cthickening_of_nonpos hδ, inf_edist_closure, of_real_of_nonpos hδ, tsub_zero] }, { rw [←closure_thickening hδ, inf_edist_closure, inf_edist_thickening hδ]; apply_instance } end @[simp] lemma thickening_cthickening (hε : 0 < ε) (hδ : 0 ≤ δ) (s : set E) : thickening ε (cthickening δ s) = thickening (ε + δ) s := begin obtain rfl | hδ := hδ.eq_or_lt, { rw [cthickening_zero, thickening_closure, add_zero] }, { rw [←closure_thickening hδ, thickening_closure, thickening_thickening hε hδ]; apply_instance } end @[simp] lemma cthickening_cthickening (hε : 0 ≤ ε) (hδ : 0 ≤ δ) (s : set E) : cthickening ε (cthickening δ s) = cthickening (ε + δ) s := (cthickening_cthickening_subset hε hδ _).antisymm $ λ x, begin simp_rw [mem_cthickening_iff, ennreal.of_real_add hε hδ, inf_edist_cthickening], exact tsub_le_iff_right.2, end @[simp] lemma thickening_ball (hε : 0 < ε) (hδ : 0 < δ) (x : E) : thickening ε (ball x δ) = ball x (ε + δ) := by rw [←thickening_singleton, thickening_thickening hε hδ, thickening_singleton]; apply_instance @[simp] lemma thickening_closed_ball (hε : 0 < ε) (hδ : 0 ≤ δ) (x : E) : thickening ε (closed_ball x δ) = ball x (ε + δ) := by rw [←cthickening_singleton _ hδ, thickening_cthickening hε hδ, thickening_singleton]; apply_instance @[simp] lemma cthickening_ball (hε : 0 ≤ ε) (hδ : 0 < δ) (x : E) : cthickening ε (ball x δ) = closed_ball x (ε + δ) := by rw [←thickening_singleton, cthickening_thickening hε hδ, cthickening_singleton _ (add_nonneg hε hδ.le)]; apply_instance @[simp] lemma cthickening_closed_ball (hε : 0 ≤ ε) (hδ : 0 ≤ δ) (x : E) : cthickening ε (closed_ball x δ) = closed_ball x (ε + δ) := by rw [←cthickening_singleton _ hδ, cthickening_cthickening hε hδ, cthickening_singleton _ (add_nonneg hε hδ)]; apply_instance lemma ball_add_ball (hε : 0 < ε) (hδ : 0 < δ) (a b : E) : ball a ε + ball b δ = ball (a + b) (ε + δ) := by rw [ball_add, thickening_ball hε hδ, vadd_ball, vadd_eq_add]; apply_instance lemma ball_sub_ball (hε : 0 < ε) (hδ : 0 < δ) (a b : E) : ball a ε - ball b δ = ball (a - b) (ε + δ) := by simp_rw [sub_eq_add_neg, neg_ball, ball_add_ball hε hδ] lemma ball_add_closed_ball (hε : 0 < ε) (hδ : 0 ≤ δ) (a b : E) : ball a ε + closed_ball b δ = ball (a + b) (ε + δ) := by rw [ball_add, thickening_closed_ball hε hδ, vadd_ball, vadd_eq_add]; apply_instance lemma ball_sub_closed_ball (hε : 0 < ε) (hδ : 0 ≤ δ) (a b : E) : ball a ε - closed_ball b δ = ball (a - b) (ε + δ) := by simp_rw [sub_eq_add_neg, neg_closed_ball, ball_add_closed_ball hε hδ] lemma closed_ball_add_ball (hε : 0 ≤ ε) (hδ : 0 < δ) (a b : E) : closed_ball a ε + ball b δ = ball (a + b) (ε + δ) := by rw [add_comm, ball_add_closed_ball hδ hε, add_comm, add_comm δ]; apply_instance lemma closed_ball_sub_ball (hε : 0 ≤ ε) (hδ : 0 < δ) (a b : E) : closed_ball a ε - ball b δ = ball (a - b) (ε + δ) := by simp_rw [sub_eq_add_neg, neg_ball, closed_ball_add_ball hε hδ] lemma closed_ball_add_closed_ball [proper_space E] (hε : 0 ≤ ε) (hδ : 0 ≤ δ) (a b : E) : closed_ball a ε + closed_ball b δ = closed_ball (a + b) (ε + δ) := by rw [(is_compact_closed_ball _ _).add_closed_ball hδ, cthickening_closed_ball hδ hε, vadd_closed_ball, vadd_eq_add, add_comm, add_comm δ]; apply_instance lemma closed_ball_sub_closed_ball [proper_space E] (hε : 0 ≤ ε) (hδ : 0 ≤ δ) (a b : E) : closed_ball a ε - closed_ball b δ = closed_ball (a - b) (ε + δ) := by simp_rw [sub_eq_add_neg, neg_closed_ball, closed_ball_add_closed_ball hε hδ] end seminormed_add_comm_group section normed_add_comm_group variables [normed_add_comm_group E] [normed_space 𝕜 E] theorem smul_closed_ball (c : 𝕜) (x : E) {r : ℝ} (hr : 0 ≤ r) : c • closed_ball x r = closed_ball (c • x) (‖c‖ * r) := begin rcases eq_or_ne c 0 with rfl|hc, { simp [hr, zero_smul_set, set.singleton_zero, ← nonempty_closed_ball] }, { exact smul_closed_ball' hc x r } end lemma smul_closed_unit_ball (c : 𝕜) : c • closed_ball (0 : E) (1 : ℝ) = closed_ball (0 : E) (‖c‖) := by rw [smul_closed_ball _ _ zero_le_one, smul_zero, mul_one] variables [normed_space ℝ E] /-- In a real normed space, the image of the unit closed ball under multiplication by a nonnegative number `r` is the closed ball of radius `r` with center at the origin. -/ lemma smul_closed_unit_ball_of_nonneg {r : ℝ} (hr : 0 ≤ r) : r • closed_ball 0 1 = closed_ball (0 : E) r := by rw [smul_closed_unit_ball, real.norm_of_nonneg hr] /-- In a nontrivial real normed space, a sphere is nonempty if and only if its radius is nonnegative. -/ @[simp] lemma normed_space.sphere_nonempty [nontrivial E] {x : E} {r : ℝ} : (sphere x r).nonempty ↔ 0 ≤ r := begin obtain ⟨y, hy⟩ := exists_ne x, refine ⟨λ h, nonempty_closed_ball.1 (h.mono sphere_subset_closed_ball), λ hr, ⟨r • ‖y - x‖⁻¹ • (y - x) + x, _⟩⟩, have : ‖y - x‖ ≠ 0, by simpa [sub_eq_zero], simp [norm_smul, this, real.norm_of_nonneg hr], end lemma smul_sphere [nontrivial E] (c : 𝕜) (x : E) {r : ℝ} (hr : 0 ≤ r) : c • sphere x r = sphere (c • x) (‖c‖ * r) := begin rcases eq_or_ne c 0 with rfl|hc, { simp [zero_smul_set, set.singleton_zero, hr] }, { exact smul_sphere' hc x r } end /-- Any ball `metric.ball x r`, `0 < r` is the image of the unit ball under `λ y, x + r • y`. -/ lemma affinity_unit_ball {r : ℝ} (hr : 0 < r) (x : E) : x +ᵥ r • ball 0 1 = ball x r := by rw [smul_unit_ball_of_pos hr, vadd_ball_zero] /-- Any closed ball `metric.closed_ball x r`, `0 ≤ r` is the image of the unit closed ball under `λ y, x + r • y`. -/ lemma affinity_unit_closed_ball {r : ℝ} (hr : 0 ≤ r) (x : E) : x +ᵥ r • closed_ball 0 1 = closed_ball x r := by rw [smul_closed_unit_ball, real.norm_of_nonneg hr, vadd_closed_ball_zero] end normed_add_comm_group
57bc30fe670152e52442c0a8a72f63d11c93f639
efa51dd2edbbbbd6c34bd0ce436415eb405832e7
/20161026_ICTAC_Tutorial/ex6.lean
dbef5fdbb489a1ed02e18784460fe0cc22aa6880
[ "Apache-2.0" ]
permissive
leanprover/presentations
dd031a05bcb12c8855676c77e52ed84246bd889a
3ce2d132d299409f1de269fa8e95afa1333d644e
refs/heads/master
1,688,703,388,796
1,686,838,383,000
1,687,465,742,000
29,750,158
12
9
Apache-2.0
1,540,211,670,000
1,422,042,683,000
Lean
UTF-8
Lean
false
false
123
lean
check Type /- The universe of "small" ordinary types -/ check Type 2 check Type 3 check Type 4 check Prop check Type 0
348ad470f32f0d68d7776ca89c97bba5128a8f93
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/Elab/Do.lean
3d97cc69c5f62889a1b63fbd3eb4b85bda802871
[ "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
72,057
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Term import Lean.Elab.BindersUtil import Lean.Elab.PatternVar import Lean.Elab.Quotation.Util import Lean.Parser.Do -- HACK: avoid code explosion until heuristics are improved set_option compiler.reuse false namespace Lean.Elab.Term open Lean.Parser.Term open Meta open TSyntax.Compat private def getDoSeqElems (doSeq : Syntax) : List Syntax := if doSeq.getKind == ``Parser.Term.doSeqBracketed then doSeq[1].getArgs.toList.map fun arg => arg[0] else if doSeq.getKind == ``Parser.Term.doSeqIndent then doSeq[0].getArgs.toList.map fun arg => arg[0] else [] private def getDoSeq (doStx : Syntax) : Syntax := doStx[1] @[builtinTermElab liftMethod] def elabLiftMethod : TermElab := fun stx _ => throwErrorAt stx "invalid use of `(<- ...)`, must be nested inside a 'do' expression" /-- Return true if we should not lift `(<- ...)` actions nested in the syntax nodes with the given kind. -/ private def liftMethodDelimiter (k : SyntaxNodeKind) : Bool := k == ``Parser.Term.do || k == ``Parser.Term.doSeqIndent || k == ``Parser.Term.doSeqBracketed || k == ``Parser.Term.termReturn || k == ``Parser.Term.termUnless || k == ``Parser.Term.termTry || k == ``Parser.Term.termFor /-- Given `stx` which is a `letPatDecl`, `letEqnsDecl`, or `letIdDecl`, return true if it has binders. -/ private def letDeclArgHasBinders (letDeclArg : Syntax) : Bool := let k := letDeclArg.getKind if k == ``Parser.Term.letPatDecl then false else if k == ``Parser.Term.letEqnsDecl then true else if k == ``Parser.Term.letIdDecl then -- letIdLhs := ident >> checkWsBefore "expected space before binders" >> many (ppSpace >> letIdBinder)) >> optType let binders := letDeclArg[1] binders.getNumArgs > 0 else false /-- Return `true` if the given `letDecl` contains binders. -/ private def letDeclHasBinders (letDecl : Syntax) : Bool := letDeclArgHasBinders letDecl[0] /-- Return true if we should generate an error message when lifting a method over this kind of syntax. -/ private def liftMethodForbiddenBinder (stx : Syntax) : Bool := let k := stx.getKind if k == ``Parser.Term.fun || k == ``Parser.Term.matchAlts || k == ``Parser.Term.doLetRec || k == ``Parser.Term.letrec then -- It is never ok to lift over this kind of binder true -- The following kinds of `let`-expressions require extra checks to decide whether they contain binders or not else if k == ``Parser.Term.let then letDeclHasBinders stx[1] else if k == ``Parser.Term.doLet then letDeclHasBinders stx[2] else if k == ``Parser.Term.doLetArrow then letDeclArgHasBinders stx[2] else false private partial def hasLiftMethod : Syntax → Bool | Syntax.node _ k args => if liftMethodDelimiter k then false -- NOTE: We don't check for lifts in quotations here, which doesn't break anything but merely makes this rare case a -- bit slower else if k == ``Parser.Term.liftMethod then true else args.any hasLiftMethod | _ => false structure ExtractMonadResult where m : Expr returnType : Expr expectedType : Expr private def mkUnknownMonadResult : MetaM ExtractMonadResult := do let u ← mkFreshLevelMVar let v ← mkFreshLevelMVar let m ← mkFreshExprMVar (← mkArrow (mkSort (mkLevelSucc u)) (mkSort (mkLevelSucc v))) let returnType ← mkFreshExprMVar (mkSort (mkLevelSucc u)) return { m, returnType, expectedType := mkApp m returnType } private partial def extractBind (expectedType? : Option Expr) : TermElabM ExtractMonadResult := do let some expectedType := expectedType? | mkUnknownMonadResult let extractStep? (type : Expr) : MetaM (Option ExtractMonadResult) := do let .app m returnType := type | return none try let bindInstType ← mkAppM ``Bind #[m] discard <| Meta.synthInstance bindInstType return some { m, returnType, expectedType } catch _ => return none let rec extract? (type : Expr) : MetaM (Option ExtractMonadResult) := do match (← extractStep? type) with | some r => return r | none => let typeNew ← whnfCore type if typeNew != type then extract? typeNew else if typeNew.getAppFn.isMVar then mkUnknownMonadResult else match (← unfoldDefinition? typeNew) with | some typeNew => extract? typeNew | none => return none match (← extract? expectedType) with | some r => return r | none => throwError "invalid `do` notation, expected type is not a monad application{indentExpr expectedType}\nYou can use the `do` notation in pure code by writing `Id.run do` instead of `do`, where `Id` is the identity monad." namespace Do abbrev Var := Syntax -- TODO: should be `Ident` /-- A `doMatch` alternative. `vars` is the array of variables declared by `patterns`. -/ structure Alt (σ : Type) where ref : Syntax vars : Array Var patterns : Syntax rhs : σ deriving Inhabited /-- Auxiliary datastructure for representing a `do` code block, and compiling "reassignments" (e.g., `x := x + 1`). We convert `Code` into a `Syntax` term representing the: - `do`-block, or - the visitor argument for the `forIn` combinator. We say the following constructors are terminals: - `break`: for interrupting a `for x in s` - `continue`: for interrupting the current iteration of a `for x in s` - `return e`: for returning `e` as the result for the whole `do` computation block - `action a`: for executing action `a` as a terminal - `ite`: if-then-else - `match`: pattern matching - `jmp` a goto to a join-point We say the terminals `break`, `continue`, `action`, and `return` are "exit points" Note that, `return e` is not equivalent to `action (pure e)`. Here is an example: ``` def f (x : Nat) : IO Unit := do if x == 0 then return () IO.println "hello" ``` Executing `#eval f 0` will not print "hello". Now, consider ``` def g (x : Nat) : IO Unit := do if x == 0 then pure () IO.println "hello" ``` The `if` statement is essentially a noop, and "hello" is printed when we execute `g 0`. - `decl` represents all declaration-like `doElem`s (e.g., `let`, `have`, `let rec`). The field `stx` is the actual `doElem`, `vars` is the array of variables declared by it, and `cont` is the next instruction in the `do` code block. `vars` is an array since we have declarations such as `let (a, b) := s`. - `reassign` is an reassignment-like `doElem` (e.g., `x := x + 1`). - `joinpoint` is a join point declaration: an auxiliary `let`-declaration used to represent the control-flow. - `seq a k` executes action `a`, ignores its result, and then executes `k`. We also store the do-elements `dbg_trace` and `assert!` as actions in a `seq`. A code block `C` is well-formed if - For every `jmp ref j as` in `C`, there is a `joinpoint j ps b k` and `jmp ref j as` is in `k`, and `ps.size == as.size` -/ inductive Code where | decl (xs : Array Var) (doElem : Syntax) (k : Code) | reassign (xs : Array Var) (doElem : Syntax) (k : Code) | /-- The Boolean value in `params` indicates whether we should use `(x : typeof! x)` when generating term Syntax or not -/ joinpoint (name : Name) (params : Array (Var × Bool)) (body : Code) (k : Code) | seq (action : Syntax) (k : Code) | action (action : Syntax) | break (ref : Syntax) | continue (ref : Syntax) | return (ref : Syntax) (val : Syntax) | /-- Recall that an if-then-else may declare a variable using `optIdent` for the branches `thenBranch` and `elseBranch`. We store the variable name at `var?`. -/ ite (ref : Syntax) (h? : Option Var) (optIdent : Syntax) (cond : Syntax) (thenBranch : Code) (elseBranch : Code) | match (ref : Syntax) (gen : Syntax) (discrs : Syntax) (optMotive : Syntax) (alts : Array (Alt Code)) | jmp (ref : Syntax) (jpName : Name) (args : Array Syntax) deriving Inhabited def Code.getRef? : Code → Option Syntax | .decl _ doElem _ => doElem | .reassign _ doElem _ => doElem | .joinpoint .. => none | .seq a _ => a | .action a => a | .break ref => ref | .continue ref => ref | .return ref _ => ref | .ite ref .. => ref | .match ref .. => ref | .jmp ref .. => ref abbrev VarSet := Std.RBMap Name Syntax Name.cmp /-- A code block, and the collection of variables updated by it. -/ structure CodeBlock where code : Code uvars : VarSet := {} -- set of variables updated by `code` private def varSetToArray (s : VarSet) : Array Var := s.fold (fun xs _ x => xs.push x) #[] private def varsToMessageData (vars : Array Var) : MessageData := MessageData.joinSep (vars.toList.map fun n => MessageData.ofName (n.getId.simpMacroScopes)) " " partial def CodeBlocl.toMessageData (codeBlock : CodeBlock) : MessageData := let us := MessageData.ofList <| (varSetToArray codeBlock.uvars).toList.map MessageData.ofSyntax let rec loop : Code → MessageData | .decl xs _ k => m!"let {varsToMessageData xs} := ...\n{loop k}" | .reassign xs _ k => m!"{varsToMessageData xs} := ...\n{loop k}" | .joinpoint n ps body k => m!"let {n.simpMacroScopes} {varsToMessageData (ps.map Prod.fst)} := {indentD (loop body)}\n{loop k}" | .seq e k => m!"{e}\n{loop k}" | .action e => e | .ite _ _ _ c t e => m!"if {c} then {indentD (loop t)}\nelse{loop e}" | .jmp _ j xs => m!"jmp {j.simpMacroScopes} {xs.toList}" | .break _ => m!"break {us}" | .continue _ => m!"continue {us}" | .return _ v => m!"return {v} {us}" | .match _ _ ds _ alts => m!"match {ds} with" ++ alts.foldl (init := m!"") fun acc alt => acc ++ m!"\n| {alt.patterns} => {loop alt.rhs}" loop codeBlock.code /-- Return true if the give code contains an exit point that satisfies `p` -/ partial def hasExitPointPred (c : Code) (p : Code → Bool) : Bool := let rec loop : Code → Bool | .decl _ _ k => loop k | .reassign _ _ k => loop k | .joinpoint _ _ b k => loop b || loop k | .seq _ k => loop k | .ite _ _ _ _ t e => loop t || loop e | .match _ _ _ _ alts => alts.any (loop ·.rhs) | .jmp .. => false | c => p c loop c def hasExitPoint (c : Code) : Bool := hasExitPointPred c fun _ => true def hasReturn (c : Code) : Bool := hasExitPointPred c fun | .return .. => true | _ => false def hasTerminalAction (c : Code) : Bool := hasExitPointPred c fun | .action _ => true | _ => false def hasBreakContinue (c : Code) : Bool := hasExitPointPred c fun | .break _ => true | .continue _ => true | _ => false def hasBreakContinueReturn (c : Code) : Bool := hasExitPointPred c fun | .break _ => true | .continue _ => true | .return _ _ => true | _ => false def mkAuxDeclFor {m} [Monad m] [MonadQuotation m] (e : Syntax) (mkCont : Syntax → m Code) : m Code := withRef e <| withFreshMacroScope do let y ← `(y) let doElem ← `(doElem| let y ← $e:term) -- Add elaboration hint for producing sane error message let y ← `(ensure_expected_type% "type mismatch, result value" $y) let k ← mkCont y return .decl #[y] doElem k /-- Convert `action _ e` instructions in `c` into `let y ← e; jmp _ jp (xs y)`. -/ partial def convertTerminalActionIntoJmp (code : Code) (jp : Name) (xs : Array Var) : MacroM Code := let rec loop : Code → MacroM Code | .decl xs stx k => return .decl xs stx (← loop k) | .reassign xs stx k => return .reassign xs stx (← loop k) | .joinpoint n ps b k => return .joinpoint n ps (← loop b) (← loop k) | .seq e k => return .seq e (← loop k) | .ite ref x? h c t e => return .ite ref x? h c (← loop t) (← loop e) | .match ref g ds t alts => return .match ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← loop alt.rhs) }) | .action e => mkAuxDeclFor e fun y => let ref := e -- We jump to `jp` with xs **and** y let jmpArgs := xs.push y return Code.jmp ref jp jmpArgs | c => return c loop code structure JPDecl where name : Name params : Array (Var × Bool) body : Code def attachJP (jpDecl : JPDecl) (k : Code) : Code := Code.joinpoint jpDecl.name jpDecl.params jpDecl.body k def attachJPs (jpDecls : Array JPDecl) (k : Code) : Code := jpDecls.foldr attachJP k def mkFreshJP (ps : Array (Var × Bool)) (body : Code) : TermElabM JPDecl := do let ps ← if ps.isEmpty then let y ← `(y) pure #[(y.raw, false)] else pure ps -- Remark: the compiler frontend implemented in C++ currently detects jointpoints created by -- the "do" notation by testing the name. See hack at method `visit_let` at `lcnf.cpp` -- We will remove this hack when we re-implement the compiler frontend in Lean. let name ← mkFreshUserName `_do_jp pure { name := name, params := ps, body := body } def addFreshJP (ps : Array (Var × Bool)) (body : Code) : StateRefT (Array JPDecl) TermElabM Name := do let jp ← mkFreshJP ps body modify fun (jps : Array JPDecl) => jps.push jp pure jp.name def insertVars (rs : VarSet) (xs : Array Var) : VarSet := xs.foldl (fun rs x => rs.insert x.getId x) rs def eraseVars (rs : VarSet) (xs : Array Var) : VarSet := xs.foldl (·.erase ·.getId) rs def eraseOptVar (rs : VarSet) (x? : Option Var) : VarSet := match x? with | none => rs | some x => rs.insert x.getId x /-- Create a new jointpoint for `c`, and jump to it with the variables `rs` -/ def mkSimpleJmp (ref : Syntax) (rs : VarSet) (c : Code) : StateRefT (Array JPDecl) TermElabM Code := do let xs := varSetToArray rs let jp ← addFreshJP (xs.map fun x => (x, true)) c if xs.isEmpty then let unit ← ``(Unit.unit) return Code.jmp ref jp #[unit] else return Code.jmp ref jp xs /-- Create a new joinpoint that takes `rs` and `val` as arguments. `val` must be syntax representing a pure value. The body of the joinpoint is created using `mkJPBody yFresh`, where `yFresh` is a fresh variable created by this method. -/ def mkJmp (ref : Syntax) (rs : VarSet) (val : Syntax) (mkJPBody : Syntax → MacroM Code) : StateRefT (Array JPDecl) TermElabM Code := do let xs := varSetToArray rs let args := xs.push val let yFresh ← withRef ref `(y) let ps := xs.map fun x => (x, true) let ps := ps.push (yFresh, false) let jpBody ← liftMacroM <| mkJPBody yFresh let jp ← addFreshJP ps jpBody return Code.jmp ref jp args /-- `pullExitPointsAux rs c` auxiliary method for `pullExitPoints`, `rs` is the set of update variable in the current path. -/ partial def pullExitPointsAux (rs : VarSet) (c : Code) : StateRefT (Array JPDecl) TermElabM Code := match c with | .decl xs stx k => return .decl xs stx (← pullExitPointsAux (eraseVars rs xs) k) | .reassign xs stx k => return .reassign xs stx (← pullExitPointsAux (insertVars rs xs) k) | .joinpoint j ps b k => return .joinpoint j ps (← pullExitPointsAux rs b) (← pullExitPointsAux rs k) | .seq e k => return .seq e (← pullExitPointsAux rs k) | .ite ref x? o c t e => return .ite ref x? o c (← pullExitPointsAux (eraseOptVar rs x?) t) (← pullExitPointsAux (eraseOptVar rs x?) e) | .match ref g ds t alts => return .match ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← pullExitPointsAux (eraseVars rs alt.vars) alt.rhs) }) | .jmp .. => return c | .break ref => mkSimpleJmp ref rs (.break ref) | .continue ref => mkSimpleJmp ref rs (.continue ref) | .return ref val => mkJmp ref rs val (fun y => return .return ref y) | .action e => -- We use `mkAuxDeclFor` because `e` is not pure. mkAuxDeclFor e fun y => let ref := e mkJmp ref rs y (fun yFresh => return .action (← ``(Pure.pure $yFresh))) /-- Auxiliary operation for adding new variables to the collection of updated variables in a CodeBlock. When a new variable is not already in the collection, but is shadowed by some declaration in `c`, we create auxiliary join points to make sure we preserve the semantics of the code block. Example: suppose we have the code block `print x; let x := 10; return x`. And we want to extend it with the reassignment `x := x + 1`. We first use `pullExitPoints` to create ``` let jp (x!1) := return x!1; print x; let x := 10; jmp jp x ``` and then we add the reassignment ``` x := x + 1 let jp (x!1) := return x!1; print x; let x := 10; jmp jp x ``` Note that we created a fresh variable `x!1` to avoid accidental name capture. As another example, consider ``` print x; let x := 10 y := y + 1; return x; ``` We transform it into ``` let jp (y x!1) := return x!1; print x; let x := 10 y := y + 1; jmp jp y x ``` and then we add the reassignment as in the previous example. We need to include `y` in the jump, because each exit point is implicitly returning the set of update variables. We implement the method as follows. Let `us` be `c.uvars`, then 1- for each `return _ y` in `c`, we create a join point `let j (us y!1) := return y!1` and replace the `return _ y` with `jmp us y` 2- for each `break`, we create a join point `let j (us) := break` and replace the `break` with `jmp us`. 3- Same as 2 for `continue`. -/ def pullExitPoints (c : Code) : TermElabM Code := do if hasExitPoint c then let (c, jpDecls) ← (pullExitPointsAux {} c).run #[] return attachJPs jpDecls c else return c partial def extendUpdatedVarsAux (c : Code) (ws : VarSet) : TermElabM Code := let rec update (c : Code) : TermElabM Code := do match c with | .joinpoint j ps b k => return .joinpoint j ps (← update b) (← update k) | .seq e k => return .seq e (← update k) | .match ref g ds t alts => if alts.any fun alt => alt.vars.any fun x => ws.contains x.getId then -- If a pattern variable is shadowing a variable in ws, we `pullExitPoints` pullExitPoints c else return .match ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← update alt.rhs) }) | .ite ref none o c t e => return .ite ref none o c (← update t) (← update e) | .ite ref (some h) o cond t e => if ws.contains h.getId then -- if the `h` at `if h:c then t else e` shadows a variable in `ws`, we `pullExitPoints` pullExitPoints c else return Code.ite ref (some h) o cond (← update t) (← update e) | .reassign xs stx k => return .reassign xs stx (← update k) | .decl xs stx k => do if xs.any fun x => ws.contains x.getId then -- One the declared variables is shadowing a variable in `ws` pullExitPoints c else return .decl xs stx (← update k) | c => return c update c /-- Extend the set of updated variables. It assumes `ws` is a super set of `c.uvars`. We **cannot** simply update the field `c.uvars`, because `c` may have shadowed some variable in `ws`. See discussion at `pullExitPoints`. -/ partial def extendUpdatedVars (c : CodeBlock) (ws : VarSet) : TermElabM CodeBlock := do if ws.any fun x _ => !c.uvars.contains x then -- `ws` contains a variable that is not in `c.uvars`, but in `c.dvars` (i.e., it has been shadowed) pure { code := (← extendUpdatedVarsAux c.code ws), uvars := ws } else pure { c with uvars := ws } private def union (s₁ s₂ : VarSet) : VarSet := s₁.fold (·.insert ·) s₂ /-- Given two code blocks `c₁` and `c₂`, make sure they have the same set of updated variables. Let `ws` the union of the updated variables in `c₁‵ and ‵c₂`. We use `extendUpdatedVars c₁ ws` and `extendUpdatedVars c₂ ws` -/ def homogenize (c₁ c₂ : CodeBlock) : TermElabM (CodeBlock × CodeBlock) := do let ws := union c₁.uvars c₂.uvars let c₁ ← extendUpdatedVars c₁ ws let c₂ ← extendUpdatedVars c₂ ws pure (c₁, c₂) /-- Extending code blocks with variable declarations: `let x : t := v` and `let x : t ← v`. We remove `x` from the collection of updated varibles. Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables declared by it. It is an array because we have let-declarations that declare multiple variables. Example: `let (x, y) := t` -/ def mkVarDeclCore (xs : Array Var) (stx : Syntax) (c : CodeBlock) : CodeBlock := { code := Code.decl xs stx c.code, uvars := eraseVars c.uvars xs } /-- Extending code blocks with reassignments: `x : t := v` and `x : t ← v`. Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables declared by it. It is an array because we have let-declarations that declare multiple variables. Example: `(x, y) ← t` -/ def mkReassignCore (xs : Array Var) (stx : Syntax) (c : CodeBlock) : TermElabM CodeBlock := do let us := c.uvars let ws := insertVars us xs -- If `xs` contains a new updated variable, then we must use `extendUpdatedVars`. -- See discussion at `pullExitPoints` let code ← if xs.any fun x => !us.contains x.getId then extendUpdatedVarsAux c.code ws else pure c.code pure { code := .reassign xs stx code, uvars := ws } def mkSeq (action : Syntax) (c : CodeBlock) : CodeBlock := { c with code := .seq action c.code } def mkTerminalAction (action : Syntax) : CodeBlock := { code := .action action } def mkReturn (ref : Syntax) (val : Syntax) : CodeBlock := { code := .return ref val } def mkBreak (ref : Syntax) : CodeBlock := { code := .break ref } def mkContinue (ref : Syntax) : CodeBlock := { code := .continue ref } def mkIte (ref : Syntax) (optIdent : Syntax) (cond : Syntax) (thenBranch : CodeBlock) (elseBranch : CodeBlock) : TermElabM CodeBlock := do let x? := optIdent.getOptional? let (thenBranch, elseBranch) ← homogenize thenBranch elseBranch return { code := .ite ref x? optIdent cond thenBranch.code elseBranch.code, uvars := thenBranch.uvars, } private def mkUnit : MacroM Syntax := ``((⟨⟩ : PUnit)) private def mkPureUnit : MacroM Syntax := ``(pure PUnit.unit) def mkPureUnitAction : MacroM CodeBlock := do return mkTerminalAction (← mkPureUnit) def mkUnless (cond : Syntax) (c : CodeBlock) : MacroM CodeBlock := do let thenBranch ← mkPureUnitAction return { c with code := .ite (← getRef) none mkNullNode cond thenBranch.code c.code } def mkMatch (ref : Syntax) (genParam : Syntax) (discrs : Syntax) (optMotive : Syntax) (alts : Array (Alt CodeBlock)) : TermElabM CodeBlock := do -- nary version of homogenize let ws := alts.foldl (union · ·.rhs.uvars) {} let alts ← alts.mapM fun alt => do let rhs ← extendUpdatedVars alt.rhs ws return { ref := alt.ref, vars := alt.vars, patterns := alt.patterns, rhs := rhs.code : Alt Code } return { code := .match ref genParam discrs optMotive alts, uvars := ws } /-- Return a code block that executes `terminal` and then `k` with the value produced by `terminal`. This method assumes `terminal` is a terminal -/ def concat (terminal : CodeBlock) (kRef : Syntax) (y? : Option Var) (k : CodeBlock) : TermElabM CodeBlock := do unless hasTerminalAction terminal.code do throwErrorAt kRef "`do` element is unreachable" let (terminal, k) ← homogenize terminal k let xs := varSetToArray k.uvars let y ← match y? with | some y => pure y | none => `(y) let ps := xs.map fun x => (x, true) let ps := ps.push (y, false) let jpDecl ← mkFreshJP ps k.code let jp := jpDecl.name let terminal ← liftMacroM <| convertTerminalActionIntoJmp terminal.code jp xs return { code := attachJP jpDecl terminal, uvars := k.uvars } def getLetIdDeclVar (letIdDecl : Syntax) : Var := letIdDecl[0] -- support both regular and syntax match def getPatternVarsEx (pattern : Syntax) : TermElabM (Array Var) := getPatternVars pattern <|> Quotation.getPatternVars pattern def getPatternsVarsEx (patterns : Array Syntax) : TermElabM (Array Var) := getPatternsVars patterns <|> Quotation.getPatternsVars patterns def getLetPatDeclVars (letPatDecl : Syntax) : TermElabM (Array Var) := do let pattern := letPatDecl[0] getPatternVarsEx pattern def getLetEqnsDeclVar (letEqnsDecl : Syntax) : Var := letEqnsDecl[0] def getLetDeclVars (letDecl : Syntax) : TermElabM (Array Var) := do let arg := letDecl[0] if arg.getKind == ``Parser.Term.letIdDecl then return #[getLetIdDeclVar arg] else if arg.getKind == ``Parser.Term.letPatDecl then getLetPatDeclVars arg else if arg.getKind == ``Parser.Term.letEqnsDecl then return #[getLetEqnsDeclVar arg] else throwError "unexpected kind of let declaration" def getDoLetVars (doLet : Syntax) : TermElabM (Array Var) := -- leading_parser "let " >> optional "mut " >> letDecl getLetDeclVars doLet[2] def getHaveIdLhsVar (optIdent : Syntax) : TermElabM Var := if optIdent.isNone then `(this) else pure optIdent[0] def getDoHaveVars (doHave : Syntax) : TermElabM (Array Var) := do -- doHave := leading_parser "have " >> Term.haveDecl -- haveDecl := leading_parser haveIdDecl <|> letPatDecl <|> haveEqnsDecl let arg := doHave[1][0] if arg.getKind == ``Parser.Term.haveIdDecl then -- haveIdDecl := leading_parser atomic (haveIdLhs >> " := ") >> termParser -- haveIdLhs := optional (ident >> many (ppSpace >> letIdBinder)) >> optType return #[← getHaveIdLhsVar arg[0]] else if arg.getKind == ``Parser.Term.letPatDecl then getLetPatDeclVars arg else if arg.getKind == ``Parser.Term.haveEqnsDecl then -- haveEqnsDecl := leading_parser haveIdLhs >> matchAlts return #[← getHaveIdLhsVar arg[0]] else throwError "unexpected kind of have declaration" def getDoLetRecVars (doLetRec : Syntax) : TermElabM (Array Var) := do -- letRecDecls is an array of `(group (optional attributes >> letDecl))` let letRecDecls := doLetRec[1][0].getSepArgs let letDecls := letRecDecls.map fun p => p[2] let mut allVars := #[] for letDecl in letDecls do let vars ← getLetDeclVars letDecl allVars := allVars ++ vars return allVars -- ident >> optType >> leftArrow >> termParser def getDoIdDeclVar (doIdDecl : Syntax) : Var := doIdDecl[0] -- termParser >> leftArrow >> termParser >> optional (" | " >> termParser) def getDoPatDeclVars (doPatDecl : Syntax) : TermElabM (Array Var) := do let pattern := doPatDecl[0] getPatternVarsEx pattern -- leading_parser "let " >> optional "mut " >> (doIdDecl <|> doPatDecl) def getDoLetArrowVars (doLetArrow : Syntax) : TermElabM (Array Var) := do let decl := doLetArrow[2] if decl.getKind == ``Parser.Term.doIdDecl then return #[getDoIdDeclVar decl] else if decl.getKind == ``Parser.Term.doPatDecl then getDoPatDeclVars decl else throwError "unexpected kind of `do` declaration" def getDoReassignVars (doReassign : Syntax) : TermElabM (Array Var) := do let arg := doReassign[0] if arg.getKind == ``Parser.Term.letIdDecl then return #[getLetIdDeclVar arg] else if arg.getKind == ``Parser.Term.letPatDecl then getLetPatDeclVars arg else throwError "unexpected kind of reassignment" def mkDoSeq (doElems : Array Syntax) : Syntax := mkNode `Lean.Parser.Term.doSeqIndent #[mkNullNode <| doElems.map fun doElem => mkNullNode #[doElem, mkNullNode]] def mkSingletonDoSeq (doElem : Syntax) : Syntax := mkDoSeq #[doElem] /-- If the given syntax is a `doIf`, return an equivalent `doIf` that has an `else` but no `else if`s or `if let`s. -/ private def expandDoIf? (stx : Syntax) : MacroM (Option Syntax) := match stx with | `(doElem|if $_:doIfProp then $_ else $_) => pure none | `(doElem|if $cond:doIfCond then $t $[else if $conds:doIfCond then $ts]* $[else $e?]?) => withRef stx do let mut e := e?.getD (← `(doSeq|pure PUnit.unit)) let mut eIsSeq := true for (cond, t) in Array.zip (conds.reverse.push cond) (ts.reverse.push t) do e ← if eIsSeq then pure e else `(doSeq|$e:doElem) e ← match cond with | `(doIfCond|let $pat := $d) => `(doElem| match $d:term with | $pat:term => $t | _ => $e) | `(doIfCond|let $pat ← $d) => `(doElem| match ← $d with | $pat:term => $t | _ => $e) | `(doIfCond|$cond:doIfProp) => `(doElem| if $cond:doIfProp then $t else $e) | _ => `(doElem| if $(Syntax.missing) then $t else $e) eIsSeq := false return some e | _ => pure none structure DoIfView where ref : Syntax optIdent : Syntax cond : Syntax thenBranch : Syntax elseBranch : Syntax /-- This method assumes `expandDoIf?` is not applicable. -/ private def mkDoIfView (doIf : Syntax) : DoIfView := { ref := doIf optIdent := doIf[1][0] cond := doIf[1][1] thenBranch := doIf[3] elseBranch := doIf[5][1] } /-- We use `MProd` instead of `Prod` to group values when expanding the `do` notation. `MProd` is a universe monomorphic product. The motivation is to generate simpler universe constraints in code that was not written by the user. Note that we are not restricting the macro power since the `Bind.bind` combinator already forces values computed by monadic actions to be in the same universe. -/ private def mkTuple (elems : Array Syntax) : MacroM Syntax := do if elems.size == 0 then mkUnit else if elems.size == 1 then return elems[0]! else elems.extract 0 (elems.size - 1) |>.foldrM (init := elems.back) fun elem tuple => ``(MProd.mk $elem $tuple) /-- Return `some action` if `doElem` is a `doExpr <action>`-/ def isDoExpr? (doElem : Syntax) : Option Syntax := if doElem.getKind == ``Parser.Term.doExpr then some doElem[0] else none /-- Given `uvars := #[a_1, ..., a_n, a_{n+1}]` construct term ``` let a_1 := x.1 let x := x.2 let a_2 := x.1 let x := x.2 ... let a_n := x.1 let a_{n+1} := x.2 body ``` Special cases - `uvars := #[]` => `body` - `uvars := #[a]` => `let a := x; body` We use this method when expanding the `for-in` notation. -/ private def destructTuple (uvars : Array Var) (x : Syntax) (body : Syntax) : MacroM Syntax := do if uvars.size == 0 then return body else if uvars.size == 1 then `(let $(uvars[0]!):ident := $x; $body) else destruct uvars.toList x body where destruct (as : List Var) (x : Syntax) (body : Syntax) : MacroM Syntax := do match as with | [a, b] => `(let $a:ident := $x.1; let $b:ident := $x.2; $body) | a :: as => withFreshMacroScope do let rest ← destruct as (← `(x)) body `(let $a:ident := $x.1; let x := $x.2; $rest) | _ => unreachable! /-! The procedure `ToTerm.run` converts a `CodeBlock` into a `Syntax` term. We use this method to convert 1- The `CodeBlock` for a root `do ...` term into a `Syntax` term. This kind of `CodeBlock` never contains `break` nor `continue`. Moreover, the collection of updated variables is not packed into the result. Thus, we have two kinds of exit points - `Code.action e` which is converted into `e` - `Code.return _ e` which is converted into `pure e` We use `Kind.regular` for this case. 2- The `CodeBlock` for `b` at `for x in xs do b`. In this case, we need to generate a `Syntax` term representing a function for the `xs.forIn` combinator. a) If `b` contain a `Code.return _ a` exit point. The generated `Syntax` term has type `m (ForInStep (Option α × σ))`, where `a : α`, and the `σ` is the type of the tuple of variables reassigned by `b`. We use `Kind.forInWithReturn` for this case b) If `b` does not contain a `Code.return _ a` exit point. Then, the generated `Syntax` term has type `m (ForInStep σ)`. We use `Kind.forIn` for this case. 3- The `CodeBlock` `c` for a `do` sequence nested in a monadic combinator (e.g., `MonadExcept.tryCatch`). The generated `Syntax` term for `c` must inform whether `c` "exited" using `Code.action`, `Code.return`, `Code.break` or `Code.continue`. We use the auxiliary types `DoResult`s for storing this information. For example, the auxiliary type `DoResultPBC α σ` is used for a code block that exits with `Code.action`, **and** `Code.break`/`Code.continue`, `α` is the type of values produced by the exit `action`, and `σ` is the type of the tuple of reassigned variables. The type `DoResult α β σ` is usedf for code blocks that exit with `Code.action`, `Code.return`, **and** `Code.break`/`Code.continue`, `β` is the type of the returned values. We don't use `DoResult α β σ` for all cases because: a) The elaborator would not be able to infer all type parameters without extra annotations. For example, if the code block does not contain `Code.return _ _`, the elaborator will not be able to infer `β`. b) We need to pattern match on the result produced by the combinator (e.g., `MonadExcept.tryCatch`), but we don't want to consider "unreachable" cases. We do not distinguish between cases that contain `break`, but not `continue`, and vice versa. When listing all cases, we use `a` to indicate the code block contains `Code.action _`, `r` for `Code.return _ _`, and `b/c` for a code block that contains `Code.break _` or `Code.continue _`. - `a`: `Kind.regular`, type `m (α × σ)` - `r`: `Kind.regular`, type `m (α × σ)` Note that the code that pattern matches on the result will behave differently in this case. It produces `return a` for this case, and `pure a` for the previous one. - `b/c`: `Kind.nestedBC`, type `m (DoResultBC σ)` - `a` and `r`: `Kind.nestedPR`, type `m (DoResultPR α β σ)` - `a` and `bc`: `Kind.nestedSBC`, type `m (DoResultSBC α σ)` - `r` and `bc`: `Kind.nestedSBC`, type `m (DoResultSBC α σ)` Again the code that pattern matches on the result will behave differently in this case and the previous one. It produces `return a` for the constructor `DoResultSPR.pureReturn a u` for this case, and `pure a` for the previous case. - `a`, `r`, `b/c`: `Kind.nestedPRBC`, type type `m (DoResultPRBC α β σ)` Here is the recipe for adding new combinators with nested `do`s. Example: suppose we want to support `repeat doSeq`. Assuming we have `repeat : m α → m α` 1- Convert `doSeq` into `codeBlock : CodeBlock` 2- Create term `term` using `mkNestedTerm code m uvars a r bc` where `code` is `codeBlock.code`, `uvars` is an array containing `codeBlock.uvars`, `m` is a `Syntax` representing the Monad, and `a` is true if `code` contains `Code.action _`, `r` is true if `code` contains `Code.return _ _`, `bc` is true if `code` contains `Code.break _` or `Code.continue _`. Remark: for combinators such as `repeat` that take a single `doSeq`, all arguments, but `m`, are extracted from `codeBlock`. 3- Create the term `repeat $term` 4- and then, convert it into a `doSeq` using `matchNestedTermResult ref (repeat $term) uvsar a r bc` -/ /-- Helper method for annotating `term` with the raw syntax `ref`. We use this method to implement finer-grained term infos for `do`-blocks. We use `withRef term` to make sure the synthetic position for the `with_annotate_term` is equal to the one for `term`. This is important for producing error messages when there is a type mismatch. Consider the following example: ``` opaque f : IO Nat def g : IO String := do f ``` There is at type mismatch at `f`, but it is detected when elaborating the expanded term containing the `with_annotate_term .. f`. The current `getRef` when this `annotate` is invoked is not necessarily `f`. Actually, it is the whole `do`-block. By using `withRef` we ensure the synthetic position for the `with_annotate_term ..` is equal to `term`. Recall that synthetic positions are used when generating error messages. -/ def annotate [Monad m] [MonadRef m] [MonadQuotation m] (ref : Syntax) (term : Syntax) : m Syntax := withRef term <| `(with_annotate_term $ref $term) namespace ToTerm inductive Kind where | regular | forIn | forInWithReturn | nestedBC | nestedPR | nestedSBC | nestedPRBC instance : Inhabited Kind := ⟨Kind.regular⟩ def Kind.isRegular : Kind → Bool | .regular => true | _ => false structure Context where /-- Syntax to reference the monad associated with the do notation. -/ m : Syntax /-- Syntax to reference the result of the monadic computation performed by the do notation. -/ returnType : Syntax uvars : Array Var kind : Kind abbrev M := ReaderT Context MacroM def mkUVarTuple : M Syntax := do let ctx ← read mkTuple ctx.uvars def returnToTerm (val : Syntax) : M Syntax := do let ctx ← read let u ← mkUVarTuple match ctx.kind with | .regular => if ctx.uvars.isEmpty then ``(Pure.pure $val) else ``(Pure.pure (MProd.mk $val $u)) | .forIn => ``(Pure.pure (ForInStep.done $u)) | .forInWithReturn => ``(Pure.pure (ForInStep.done (MProd.mk (some $val) $u))) | .nestedBC => unreachable! | .nestedPR => ``(Pure.pure (DoResultPR.«return» $val $u)) | .nestedSBC => ``(Pure.pure (DoResultSBC.«pureReturn» $val $u)) | .nestedPRBC => ``(Pure.pure (DoResultPRBC.«return» $val $u)) def continueToTerm : M Syntax := do let ctx ← read let u ← mkUVarTuple match ctx.kind with | .regular => unreachable! | .forIn => ``(Pure.pure (ForInStep.yield $u)) | .forInWithReturn => ``(Pure.pure (ForInStep.yield (MProd.mk none $u))) | .nestedBC => ``(Pure.pure (DoResultBC.«continue» $u)) | .nestedPR => unreachable! | .nestedSBC => ``(Pure.pure (DoResultSBC.«continue» $u)) | .nestedPRBC => ``(Pure.pure (DoResultPRBC.«continue» $u)) def breakToTerm : M Syntax := do let ctx ← read let u ← mkUVarTuple match ctx.kind with | .regular => unreachable! | .forIn => ``(Pure.pure (ForInStep.done $u)) | .forInWithReturn => ``(Pure.pure (ForInStep.done (MProd.mk none $u))) | .nestedBC => ``(Pure.pure (DoResultBC.«break» $u)) | .nestedPR => unreachable! | .nestedSBC => ``(Pure.pure (DoResultSBC.«break» $u)) | .nestedPRBC => ``(Pure.pure (DoResultPRBC.«break» $u)) def actionTerminalToTerm (action : Syntax) : M Syntax := withRef action <| withFreshMacroScope do let ctx ← read let u ← mkUVarTuple match ctx.kind with | .regular => if ctx.uvars.isEmpty then pure action else ``(Bind.bind $action fun y => Pure.pure (MProd.mk y $u)) | .forIn => ``(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield $u)) | .forInWithReturn => ``(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield (MProd.mk none $u))) | .nestedBC => unreachable! | .nestedPR => ``(Bind.bind $action fun y => (Pure.pure (DoResultPR.«pure» y $u))) | .nestedSBC => ``(Bind.bind $action fun y => (Pure.pure (DoResultSBC.«pureReturn» y $u))) | .nestedPRBC => ``(Bind.bind $action fun y => (Pure.pure (DoResultPRBC.«pure» y $u))) def seqToTerm (action : Syntax) (k : Syntax) : M Syntax := withRef action <| withFreshMacroScope do if action.getKind == ``Parser.Term.doDbgTrace then let msg := action[1] `(dbg_trace $msg; $k) else if action.getKind == ``Parser.Term.doAssert then let cond := action[1] `(assert! $cond; $k) else let action ← withRef action ``(($action : $((←read).m) PUnit)) ``(Bind.bind $action (fun (_ : PUnit) => $k)) def declToTerm (decl : Syntax) (k : Syntax) : M Syntax := withRef decl <| withFreshMacroScope do let kind := decl.getKind if kind == ``Parser.Term.doLet then let letDecl := decl[2] `(let $letDecl:letDecl; $k) else if kind == ``Parser.Term.doLetRec then let letRecToken := decl[0] let letRecDecls := decl[1] return mkNode ``Parser.Term.letrec #[letRecToken, letRecDecls, mkNullNode, k] else if kind == ``Parser.Term.doLetArrow then let arg := decl[2] if arg.getKind == ``Parser.Term.doIdDecl then let id := arg[0] let type := expandOptType id arg[1] let doElem := arg[3] -- `doElem` must be a `doExpr action`. See `doLetArrowToCode` match isDoExpr? doElem with | some action => let action ← withRef action `(($action : $((← read).m) $type)) ``(Bind.bind $action (fun ($id:ident : $type) => $k)) | none => Macro.throwErrorAt decl "unexpected kind of `do` declaration" else Macro.throwErrorAt decl "unexpected kind of `do` declaration" else if kind == ``Parser.Term.doHave then -- The `have` term is of the form `"have " >> haveDecl >> optSemicolon termParser` let args := decl.getArgs let args := args ++ #[mkNullNode /- optional ';' -/, k] return mkNode `Lean.Parser.Term.«have» args else Macro.throwErrorAt decl "unexpected kind of `do` declaration" def reassignToTerm (reassign : Syntax) (k : Syntax) : MacroM Syntax := withRef reassign <| withFreshMacroScope do match reassign with | `(doElem| $x:ident := $rhs) => `(let $x:ident := ensure_type_of% $x $(quote "invalid reassignment, value") $rhs; $k) | `(doElem| $e:term := $rhs) => `(let $e:term := ensure_type_of% $e $(quote "invalid reassignment, value") $rhs; $k) | _ => -- Note that `doReassignArrow` is expanded by `doReassignArrowToCode Macro.throwErrorAt reassign "unexpected kind of `do` reassignment" def mkIte (optIdent : Syntax) (cond : Syntax) (thenBranch : Syntax) (elseBranch : Syntax) : MacroM Syntax := do if optIdent.isNone then ``(if $cond then $thenBranch else $elseBranch) else let h := optIdent[0] ``(if $h:ident : $cond then $thenBranch else $elseBranch) def mkJoinPoint (j : Name) (ps : Array (Syntax × Bool)) (body : Syntax) (k : Syntax) : M Syntax := withRef body <| withFreshMacroScope do let pTypes ← ps.mapM fun ⟨id, useTypeOf⟩ => do if useTypeOf then `(type_of% $id) else `(_) let ps := ps.map (·.1) /- We use `let_delayed` instead of `let` for joinpoints to make sure `$k` is elaborated before `$body`. By elaborating `$k` first, we "learn" more about `$body`'s type. For example, consider the following example `do` expression ``` def f (x : Nat) : IO Unit := do if x > 0 then IO.println "x is not zero" -- Error is here IO.mkRef true ``` it is expanded into ``` def f (x : Nat) : IO Unit := do let jp (u : Unit) : IO _ := IO.mkRef true; if x > 0 then IO.println "not zero" jp () else jp () ``` If we use the regular `let` instead of `let_delayed`, the joinpoint `jp` will be elaborated and its type will be inferred to be `Unit → IO (IO.Ref Bool)`. Then, we get a typing error at `jp ()`. By using `let_delayed`, we first elaborate `if x > 0 ...` and learn that `jp` has type `Unit → IO Unit`. Then, we get the expected type mismatch error at `IO.mkRef true`. -/ `(let_delayed $(← mkIdentFromRef j):ident $[($ps : $pTypes)]* : $((← read).m) _ := $body; $k) def mkJmp (ref : Syntax) (j : Name) (args : Array Syntax) : Syntax := Syntax.mkApp (mkIdentFrom ref j) args partial def toTerm (c : Code) : M Syntax := do let term ← go c if let some ref := c.getRef? then annotate ref term else return term where go (c : Code) : M Syntax := do match c with | .return ref val => withRef ref <| returnToTerm val | .continue ref => withRef ref continueToTerm | .break ref => withRef ref breakToTerm | .action e => actionTerminalToTerm e | .joinpoint j ps b k => mkJoinPoint j ps (← toTerm b) (← toTerm k) | .jmp ref j args => return mkJmp ref j args | .decl _ stx k => declToTerm stx (← toTerm k) | .reassign _ stx k => reassignToTerm stx (← toTerm k) | .seq stx k => seqToTerm stx (← toTerm k) | .ite ref _ o c t e => withRef ref <| do mkIte o c (← toTerm t) (← toTerm e) | .match ref genParam discrs optMotive alts => let mut termAlts := #[] for alt in alts do let rhs ← toTerm alt.rhs let termAlt := mkNode `Lean.Parser.Term.matchAlt #[mkAtomFrom alt.ref "|", mkNullNode #[alt.patterns], mkAtomFrom alt.ref "=>", rhs] termAlts := termAlts.push termAlt let termMatchAlts := mkNode `Lean.Parser.Term.matchAlts #[mkNullNode termAlts] return mkNode `Lean.Parser.Term.«match» #[mkAtomFrom ref "match", genParam, optMotive, discrs, mkAtomFrom ref "with", termMatchAlts] def run (code : Code) (m : Syntax) (returnType : Syntax) (uvars : Array Var := #[]) (kind := Kind.regular) : MacroM Syntax := toTerm code { m, returnType, kind, uvars } /-- Given - `a` is true if the code block has a `Code.action _` exit point - `r` is true if the code block has a `Code.return _ _` exit point - `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point generate Kind. See comment at the beginning of the `ToTerm` namespace. -/ def mkNestedKind (a r bc : Bool) : Kind := match a, r, bc with | true, false, false => .regular | false, true, false => .regular | false, false, true => .nestedBC | true, true, false => .nestedPR | true, false, true => .nestedSBC | false, true, true => .nestedSBC | true, true, true => .nestedPRBC | false, false, false => unreachable! def mkNestedTerm (code : Code) (m : Syntax) (returnType : Syntax) (uvars : Array Var) (a r bc : Bool) : MacroM Syntax := do ToTerm.run code m returnType uvars (mkNestedKind a r bc) /-- Given a term `term` produced by `ToTerm.run`, pattern match on its result. See comment at the beginning of the `ToTerm` namespace. - `a` is true if the code block has a `Code.action _` exit point - `r` is true if the code block has a `Code.return _ _` exit point - `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point The result is a sequence of `doElem` -/ def matchNestedTermResult (term : Syntax) (uvars : Array Var) (a r bc : Bool) : MacroM (List Syntax) := do let toDoElems (auxDo : Syntax) : List Syntax := getDoSeqElems (getDoSeq auxDo) let u ← mkTuple uvars match a, r, bc with | true, false, false => if uvars.isEmpty then return toDoElems (← `(do $term:term)) else return toDoElems (← `(do let r ← $term:term; $u:term := r.2; pure r.1)) | false, true, false => if uvars.isEmpty then return toDoElems (← `(do let r ← $term:term; return r)) else return toDoElems (← `(do let r ← $term:term; $u:term := r.2; return r.1)) | false, false, true => toDoElems <$> `(do let r ← $term:term; match r with | .break u => $u:term := u; break | .continue u => $u:term := u; continue) | true, true, false => toDoElems <$> `(do let r ← $term:term; match r with | .pure a u => $u:term := u; pure a | .return b u => $u:term := u; return b) | true, false, true => toDoElems <$> `(do let r ← $term:term; match r with | .pureReturn a u => $u:term := u; pure a | .break u => $u:term := u; break | .continue u => $u:term := u; continue) | false, true, true => toDoElems <$> `(do let r ← $term:term; match r with | .pureReturn a u => $u:term := u; return a | .break u => $u:term := u; break | .continue u => $u:term := u; continue) | true, true, true => toDoElems <$> `(do let r ← $term:term; match r with | .pure a u => $u:term := u; pure a | .return a u => $u:term := u; return a | .break u => $u:term := u; break | .continue u => $u:term := u; continue) | false, false, false => unreachable! end ToTerm def isMutableLet (doElem : Syntax) : Bool := let kind := doElem.getKind (kind == ``doLetArrow || kind == ``doLet || kind == ``doLetElse) && !doElem[1].isNone namespace ToCodeBlock structure Context where ref : Syntax /-- Syntax representing the monad associated with the do notation. -/ m : Syntax /-- Syntax to reference the result of the monadic computation performed by the do notation. -/ returnType : Syntax mutableVars : VarSet := {} insideFor : Bool := false abbrev M := ReaderT Context TermElabM def withNewMutableVars {α} (newVars : Array Var) (mutable : Bool) (x : M α) : M α := withReader (fun ctx => if mutable then { ctx with mutableVars := insertVars ctx.mutableVars newVars } else ctx) x def checkReassignable (xs : Array Var) : M Unit := do let throwInvalidReassignment (x : Name) : M Unit := throwError "`{x.simpMacroScopes}` cannot be mutated, only variables declared using `let mut` can be mutated. If you did not intent to mutate but define `{x.simpMacroScopes}`, consider using `let {x.simpMacroScopes}` instead" let ctx ← read for x in xs do unless ctx.mutableVars.contains x.getId do throwInvalidReassignment x.getId def checkNotShadowingMutable (xs : Array Var) : M Unit := do let throwInvalidShadowing (x : Name) : M Unit := throwError "mutable variable `{x.simpMacroScopes}` cannot be shadowed" let ctx ← read for x in xs do if ctx.mutableVars.contains x.getId then withRef x <| throwInvalidShadowing x.getId def withFor {α} (x : M α) : M α := withReader (fun ctx => { ctx with insideFor := true }) x structure ToForInTermResult where uvars : Array Var term : Syntax def mkForInBody (_ : Syntax) (forInBody : CodeBlock) : M ToForInTermResult := do let ctx ← read let uvars := forInBody.uvars let uvars := varSetToArray uvars let term ← liftMacroM <| ToTerm.run forInBody.code ctx.m ctx.returnType uvars (if hasReturn forInBody.code then ToTerm.Kind.forInWithReturn else ToTerm.Kind.forIn) return ⟨uvars, term⟩ def ensureInsideFor : M Unit := unless (← read).insideFor do throwError "invalid `do` element, it must be inside `for`" def ensureEOS (doElems : List Syntax) : M Unit := unless doElems.isEmpty do throwError "must be last element in a `do` sequence" private partial def expandLiftMethodAux (inQuot : Bool) (inBinder : Bool) : Syntax → StateT (List Syntax) M Syntax | stx@(Syntax.node i k args) => if liftMethodDelimiter k then return stx else if k == ``Parser.Term.liftMethod && !inQuot then withFreshMacroScope do if inBinder then throwErrorAt stx "cannot lift `(<- ...)` over a binder, this error usually happens when you are trying to lift a method nested in a `fun`, `let`, or `match`-alternative, and it can often be fixed by adding a missing `do`" let term := args[1]! let term ← expandLiftMethodAux inQuot inBinder term let auxDoElem : Syntax ← `(doElem| let a ← $term:term) modify fun s => s ++ [auxDoElem] `(a) else do let inAntiquot := stx.isAntiquot && !stx.isEscapedAntiquot let inBinder := inBinder || (!inQuot && liftMethodForbiddenBinder stx) let args ← args.mapM (expandLiftMethodAux (inQuot && !inAntiquot || stx.isQuot) inBinder) return Syntax.node i k args | stx => return stx def expandLiftMethod (doElem : Syntax) : M (List Syntax × Syntax) := do if !hasLiftMethod doElem then return ([], doElem) else let (doElem, doElemsNew) ← (expandLiftMethodAux false false doElem).run [] return (doElemsNew, doElem) def checkLetArrowRHS (doElem : Syntax) : M Unit := do let kind := doElem.getKind if kind == ``Parser.Term.doLetArrow || kind == ``Parser.Term.doLet || kind == ``Parser.Term.doLetRec || kind == ``Parser.Term.doHave || kind == ``Parser.Term.doReassign || kind == ``Parser.Term.doReassignArrow then throwErrorAt doElem "invalid kind of value `{kind}` in an assignment" /-- Generate `CodeBlock` for `doReturn` which is of the form ``` "return " >> optional termParser ``` `doElems` is only used for sanity checking. -/ def doReturnToCode (doReturn : Syntax) (doElems: List Syntax) : M CodeBlock := withRef doReturn do ensureEOS doElems let argOpt := doReturn[1] let arg ← if argOpt.isNone then liftMacroM mkUnit else pure argOpt[0] return mkReturn (← getRef) arg structure Catch where x : Syntax optType : Syntax codeBlock : CodeBlock def getTryCatchUpdatedVars (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) : VarSet := let ws := tryCode.uvars let ws := catches.foldl (init := ws) fun ws alt => union alt.codeBlock.uvars ws let ws := match finallyCode? with | none => ws | some c => union c.uvars ws ws def tryCatchPred (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) (p : Code → Bool) : Bool := p tryCode.code || catches.any (fun «catch» => p «catch».codeBlock.code) || match finallyCode? with | none => false | some finallyCode => p finallyCode.code mutual /-- "Concatenate" `c` with `doSeqToCode doElems` -/ partial def concatWith (c : CodeBlock) (doElems : List Syntax) : M CodeBlock := match doElems with | [] => pure c | nextDoElem :: _ => do let k ← doSeqToCode doElems let ref := nextDoElem concat c ref none k /-- Generate `CodeBlock` for `doLetArrow; doElems` `doLetArrow` is of the form ``` "let " >> optional "mut " >> (doIdDecl <|> doPatDecl) ``` where ``` def doIdDecl := leading_parser ident >> optType >> leftArrow >> doElemParser def doPatDecl := leading_parser termParser >> leftArrow >> doElemParser >> optional (" | " >> doElemParser) ``` -/ partial def doLetArrowToCode (doLetArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do let decl := doLetArrow[2] if decl.getKind == ``Parser.Term.doIdDecl then let y := decl[0] checkNotShadowingMutable #[y] let doElem := decl[3] let k ← withNewMutableVars #[y] (isMutableLet doLetArrow) (doSeqToCode doElems) match isDoExpr? doElem with | some _ => return mkVarDeclCore #[y] doLetArrow k | none => checkLetArrowRHS doElem let c ← doSeqToCode [doElem] match doElems with | [] => pure c | kRef::_ => concat c kRef y k else if decl.getKind == ``Parser.Term.doPatDecl then let pattern := decl[0] let doElem := decl[2] let optElse := decl[3] if optElse.isNone then withFreshMacroScope do let auxDo ← if isMutableLet doLetArrow then `(do let%$doLetArrow discr ← $doElem; let%$doLetArrow mut $pattern:term := discr) else `(do let%$doLetArrow discr ← $doElem; let%$doLetArrow $pattern:term := discr) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems else let contSeq ← if isMutableLet doLetArrow then let vars ← (← getPatternVarsEx pattern).mapM fun var => `(doElem| let mut $var := $var) pure (vars ++ doElems.toArray) else pure doElems.toArray let contSeq := mkDoSeq contSeq let elseSeq := mkSingletonDoSeq optElse[1] let auxDo ← `(do let%$doLetArrow discr ← $doElem; match%$doLetArrow discr with | $pattern:term => $contSeq | _ => $elseSeq) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) else throwError "unexpected kind of `do` declaration" partial def doLetElseToCode (doLetElse : Syntax) (doElems : List Syntax) : M CodeBlock := do -- "let " >> optional "mut " >> termParser >> " := " >> termParser >> checkColGt >> " | " >> doElemParser let pattern := doLetElse[2] let val := doLetElse[4] let elseSeq := mkSingletonDoSeq doLetElse[6] let contSeq ← if isMutableLet doLetElse then let vars ← (← getPatternVarsEx pattern).mapM fun var => `(doElem| let mut $var := $var) pure (vars ++ doElems.toArray) else pure doElems.toArray let contSeq := mkDoSeq contSeq let auxDo ← `(do let discr := $val; match discr with | $pattern:term => $contSeq | _ => $elseSeq) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) /-- Generate `CodeBlock` for `doReassignArrow; doElems` `doReassignArrow` is of the form ``` (doIdDecl <|> doPatDecl) ``` -/ partial def doReassignArrowToCode (doReassignArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do let decl := doReassignArrow[0] if decl.getKind == ``Parser.Term.doIdDecl then let doElem := decl[3] let y := decl[0] let auxDo ← `(do let r ← $doElem; $y:ident := r) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems else if decl.getKind == ``Parser.Term.doPatDecl then let pattern := decl[0] let doElem := decl[2] let optElse := decl[3] if optElse.isNone then withFreshMacroScope do let auxDo ← `(do let discr ← $doElem; $pattern:term := discr) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems else throwError "reassignment with `|` (i.e., \"else clause\") is not currently supported" else throwError "unexpected kind of `do` reassignment" /-- Generate `CodeBlock` for `doIf; doElems` `doIf` is of the form ``` "if " >> optIdent >> termParser >> " then " >> doSeq >> many (group (try (group (" else " >> " if ")) >> optIdent >> termParser >> " then " >> doSeq)) >> optional (" else " >> doSeq) ``` -/ partial def doIfToCode (doIf : Syntax) (doElems : List Syntax) : M CodeBlock := do let view := mkDoIfView doIf let thenBranch ← doSeqToCode (getDoSeqElems view.thenBranch) let elseBranch ← doSeqToCode (getDoSeqElems view.elseBranch) let ite ← mkIte view.ref view.optIdent view.cond thenBranch elseBranch concatWith ite doElems /-- Generate `CodeBlock` for `doUnless; doElems` `doUnless` is of the form ``` "unless " >> termParser >> "do " >> doSeq ``` -/ partial def doUnlessToCode (doUnless : Syntax) (doElems : List Syntax) : M CodeBlock := withRef doUnless do let cond := doUnless[1] let doSeq := doUnless[3] let body ← doSeqToCode (getDoSeqElems doSeq) let unlessCode ← liftMacroM <| mkUnless cond body concatWith unlessCode doElems /-- Generate `CodeBlock` for `doFor; doElems` `doFor` is of the form ``` def doForDecl := leading_parser termParser >> " in " >> withForbidden "do" termParser def doFor := leading_parser "for " >> sepBy1 doForDecl ", " >> "do " >> doSeq ``` -/ partial def doForToCode (doFor : Syntax) (doElems : List Syntax) : M CodeBlock := do let doForDecls := doFor[1].getSepArgs if doForDecls.size > 1 then /- Expand ``` for x in xs, y in ys do body ``` into ``` let s := toStream ys for x in xs do match Stream.next? s with | none => break | some (y, s') => s := s' body ``` -/ -- Extract second element let doForDecl := doForDecls[1]! unless doForDecl[0].isNone do throwErrorAt doForDecl[0] "the proof annotation here has not been implemented yet" let y := doForDecl[1] let ys := doForDecl[3] let doForDecls := doForDecls.eraseIdx 1 let body := doFor[3] withFreshMacroScope do /- Recall that `@` (explicit) disables `coeAtOutParam`. We used `@` at `Stream` functions to make sure `resultIsOutParamSupport` is not used. -/ let toStreamApp ← withRef ys `(@toStream _ _ _ $ys) let auxDo ← `(do let mut s := $toStreamApp:term for $doForDecls:doForDecl,* do match @Stream.next? _ _ _ s with | none => break | some ($y, s') => s := s' do $body) doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems) else withRef doFor do let h? := if doForDecls[0]![0].isNone then none else some doForDecls[0]![0][0] let x := doForDecls[0]![1] withRef x <| checkNotShadowingMutable (← getPatternVarsEx x) let xs := doForDecls[0]![3] let forElems := getDoSeqElems doFor[3] let forInBodyCodeBlock ← withFor (doSeqToCode forElems) let ⟨uvars, forInBody⟩ ← mkForInBody x forInBodyCodeBlock let ctx ← read -- semantic no-op that replaces the `uvars`' position information (which all point inside the loop) -- with that of the respective mutable declarations outside the loop, which allows the language -- server to identify them as conceptually identical variables let uvars := uvars.map fun v => ctx.mutableVars.findD v.getId v let uvarsTuple ← liftMacroM do mkTuple uvars if hasReturn forInBodyCodeBlock.code then let forInBody ← liftMacroM <| destructTuple uvars (← `(r)) forInBody let optType ← `(Option $((← read).returnType)) let forInTerm ← if let some h := h? then annotate doFor (← `(for_in'% $(xs) (MProd.mk (none : $optType) $uvarsTuple) fun $x $h (r : MProd $optType _) => let r := r.2; $forInBody)) else annotate doFor (← `(for_in% $(xs) (MProd.mk (none : $optType) $uvarsTuple) fun $x (r : MProd $optType _) => let r := r.2; $forInBody)) let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r.2; match r.1 with | none => Pure.pure (ensure_expected_type% "type mismatch, `for`" PUnit.unit) | some a => return ensure_expected_type% "type mismatch, `for`" a) doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems) else let forInBody ← liftMacroM <| destructTuple uvars (← `(r)) forInBody let forInTerm ← if let some h := h? then annotate doFor (← `(for_in'% $(xs) $uvarsTuple fun $x $h r => $forInBody)) else annotate doFor (← `(for_in% $(xs) $uvarsTuple fun $x r => $forInBody)) if doElems.isEmpty then let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r; Pure.pure (ensure_expected_type% "type mismatch, `for`" PUnit.unit)) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) else let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems /-- Generate `CodeBlock` for `doMatch; doElems` -/ partial def doMatchToCode (doMatch : Syntax) (doElems: List Syntax) : M CodeBlock := do let ref := doMatch let genParam := doMatch[1] let optMotive := doMatch[2] let discrs := doMatch[3] let matchAlts := doMatch[5][0].getArgs -- Array of `doMatchAlt` let matchAlts ← matchAlts.foldlM (init := #[]) fun result matchAlt => return result ++ (← liftMacroM <| expandMatchAlt matchAlt) let alts ← matchAlts.mapM fun matchAlt => do let patterns := matchAlt[1][0] let vars ← getPatternsVarsEx patterns.getSepArgs withRef patterns <| checkNotShadowingMutable vars let rhs := matchAlt[3] let rhs ← doSeqToCode (getDoSeqElems rhs) pure { ref := matchAlt, vars := vars, patterns := patterns, rhs := rhs : Alt CodeBlock } let matchCode ← mkMatch ref genParam discrs optMotive alts concatWith matchCode doElems /-- Generate `CodeBlock` for `doTry; doElems` ``` def doTry := leading_parser "try " >> doSeq >> many (doCatch <|> doCatchMatch) >> optional doFinally def doCatch := leading_parser "catch " >> binderIdent >> optional (":" >> termParser) >> darrow >> doSeq def doCatchMatch := leading_parser "catch " >> doMatchAlts def doFinally := leading_parser "finally " >> doSeq ``` -/ partial def doTryToCode (doTry : Syntax) (doElems: List Syntax) : M CodeBlock := do let tryCode ← doSeqToCode (getDoSeqElems doTry[1]) let optFinally := doTry[3] let catches ← doTry[2].getArgs.mapM fun catchStx : Syntax => do if catchStx.getKind == ``Parser.Term.doCatch then let x := catchStx[1] if x.isIdent then withRef x <| checkNotShadowingMutable #[x] let optType := catchStx[2] let c ← doSeqToCode (getDoSeqElems catchStx[4]) return { x := x, optType := optType, codeBlock := c : Catch } else if catchStx.getKind == ``Parser.Term.doCatchMatch then let matchAlts := catchStx[1] let x ← `(ex) let auxDo ← `(do match ex with $matchAlts) let c ← doSeqToCode (getDoSeqElems (getDoSeq auxDo)) return { x := x, codeBlock := c, optType := mkNullNode : Catch } else throwError "unexpected kind of `catch`" let finallyCode? ← if optFinally.isNone then pure none else some <$> doSeqToCode (getDoSeqElems optFinally[0][1]) if catches.isEmpty && finallyCode?.isNone then throwError "invalid `try`, it must have a `catch` or `finally`" let ctx ← read let ws := getTryCatchUpdatedVars tryCode catches finallyCode? let uvars := varSetToArray ws let a := tryCatchPred tryCode catches finallyCode? hasTerminalAction let r := tryCatchPred tryCode catches finallyCode? hasReturn let bc := tryCatchPred tryCode catches finallyCode? hasBreakContinue let toTerm (codeBlock : CodeBlock) : M Syntax := do let codeBlock ← liftM $ extendUpdatedVars codeBlock ws liftMacroM <| ToTerm.mkNestedTerm codeBlock.code ctx.m ctx.returnType uvars a r bc let term ← toTerm tryCode let term ← catches.foldlM (init := term) fun term «catch» => do let catchTerm ← toTerm «catch».codeBlock if catch.optType.isNone then annotate doTry (← ``(MonadExcept.tryCatch $term (fun $(«catch».x):ident => $catchTerm))) else let type := «catch».optType[1] annotate doTry (← ``(tryCatchThe $type $term (fun $(«catch».x):ident => $catchTerm))) let term ← match finallyCode? with | none => pure term | some finallyCode => withRef optFinally do unless finallyCode.uvars.isEmpty do throwError "`finally` currently does not support reassignments" if hasBreakContinueReturn finallyCode.code then throwError "`finally` currently does `return`, `break`, nor `continue`" let finallyTerm ← liftMacroM <| ToTerm.run finallyCode.code ctx.m ctx.returnType {} ToTerm.Kind.regular annotate doTry (← ``(tryFinally $term $finallyTerm)) let doElemsNew ← liftMacroM <| ToTerm.matchNestedTermResult term uvars a r bc doSeqToCode (doElemsNew ++ doElems) partial def doSeqToCode : List Syntax → M CodeBlock | [] => do liftMacroM mkPureUnitAction | doElem::doElems => withIncRecDepth <| withRef doElem do checkMaxHeartbeats "`do`-expander" match (← liftMacroM <| expandMacro? doElem) with | some doElem => doSeqToCode (doElem::doElems) | none => match (← liftMacroM <| expandDoIf? doElem) with | some doElem => doSeqToCode (doElem::doElems) | none => let (liftedDoElems, doElem) ← expandLiftMethod doElem if !liftedDoElems.isEmpty then doSeqToCode (liftedDoElems ++ [doElem] ++ doElems) else let ref := doElem let k := doElem.getKind if k == ``Parser.Term.doLet then let vars ← getDoLetVars doElem checkNotShadowingMutable vars mkVarDeclCore vars doElem <$> withNewMutableVars vars (isMutableLet doElem) (doSeqToCode doElems) else if k == ``Parser.Term.doHave then let vars ← getDoHaveVars doElem checkNotShadowingMutable vars mkVarDeclCore vars doElem <$> (doSeqToCode doElems) else if k == ``Parser.Term.doLetRec then let vars ← getDoLetRecVars doElem checkNotShadowingMutable vars mkVarDeclCore vars doElem <$> (doSeqToCode doElems) else if k == ``Parser.Term.doReassign then let vars ← getDoReassignVars doElem checkReassignable vars let k ← doSeqToCode doElems mkReassignCore vars doElem k else if k == ``Parser.Term.doLetArrow then doLetArrowToCode doElem doElems else if k == ``Parser.Term.doLetElse then doLetElseToCode doElem doElems else if k == ``Parser.Term.doReassignArrow then doReassignArrowToCode doElem doElems else if k == ``Parser.Term.doIf then doIfToCode doElem doElems else if k == ``Parser.Term.doUnless then doUnlessToCode doElem doElems else if k == ``Parser.Term.doFor then withFreshMacroScope do doForToCode doElem doElems else if k == ``Parser.Term.doMatch then doMatchToCode doElem doElems else if k == ``Parser.Term.doTry then doTryToCode doElem doElems else if k == ``Parser.Term.doBreak then ensureInsideFor ensureEOS doElems return mkBreak ref else if k == ``Parser.Term.doContinue then ensureInsideFor ensureEOS doElems return mkContinue ref else if k == ``Parser.Term.doReturn then doReturnToCode doElem doElems else if k == ``Parser.Term.doDbgTrace then return mkSeq doElem (← doSeqToCode doElems) else if k == ``Parser.Term.doAssert then return mkSeq doElem (← doSeqToCode doElems) else if k == ``Parser.Term.doNested then let nestedDoSeq := doElem[1] doSeqToCode (getDoSeqElems nestedDoSeq ++ doElems) else if k == ``Parser.Term.doExpr then let term := doElem[0] if doElems.isEmpty then return mkTerminalAction term else return mkSeq term (← doSeqToCode doElems) else throwError "unexpected do-element of kind {doElem.getKind}:\n{doElem}" end def run (doStx : Syntax) (m : Syntax) (returnType : Syntax) : TermElabM CodeBlock := (doSeqToCode <| getDoSeqElems <| getDoSeq doStx).run { ref := doStx, m, returnType } end ToCodeBlock @[builtinTermElab «do»] def elabDo : TermElab := fun stx expectedType? => do tryPostponeIfNoneOrMVar expectedType? let bindInfo ← extractBind expectedType? let m ← Term.exprToSyntax bindInfo.m let returnType ← Term.exprToSyntax bindInfo.returnType let codeBlock ← ToCodeBlock.run stx m returnType let stxNew ← liftMacroM <| ToTerm.run codeBlock.code m returnType trace[Elab.do] stxNew withMacroExpansion stx stxNew <| elabTermEnsuringType stxNew bindInfo.expectedType end Do builtin_initialize registerTraceClass `Elab.do private def toDoElem (newKind : SyntaxNodeKind) : Macro := fun stx => do let stx := stx.setKind newKind withRef stx `(do $stx:doElem) @[builtinMacro Lean.Parser.Term.termFor] def expandTermFor : Macro := toDoElem ``Parser.Term.doFor @[builtinMacro Lean.Parser.Term.termTry] def expandTermTry : Macro := toDoElem ``Parser.Term.doTry @[builtinMacro Lean.Parser.Term.termUnless] def expandTermUnless : Macro := toDoElem ``Parser.Term.doUnless @[builtinMacro Lean.Parser.Term.termReturn] def expandTermReturn : Macro := toDoElem ``Parser.Term.doReturn end Lean.Elab.Term
abba708657a5967be852bfa1c9f3fbbfd2a21090
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/locally_convex/strong_topology.lean
24943723ea67b4e25b22d339fe94396291ae5be2
[ "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
2,506
lean
/- Copyright (c) 2022 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker -/ import topology.algebra.module.strong_topology import topology.algebra.module.locally_convex /-! # Local convexity of the strong topology > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we prove that the strong topology on `E →L[ℝ] F` is locally convex provided that `F` is locally convex. ## References * [N. Bourbaki, *Topological Vector Spaces*][bourbaki1987] ## Todo * Characterization in terms of seminorms ## Tags locally convex, bounded convergence -/ open_locale topology uniform_convergence variables {R 𝕜₁ 𝕜₂ E F : Type*} namespace continuous_linear_map variables [add_comm_group E] [topological_space E] [add_comm_group F] [topological_space F] [topological_add_group F] section general variables (R) variables [ordered_semiring R] variables [normed_field 𝕜₁] [normed_field 𝕜₂] [module 𝕜₁ E] [module 𝕜₂ F] {σ : 𝕜₁ →+* 𝕜₂} variables [module R F] [has_continuous_const_smul R F] [locally_convex_space R F] [smul_comm_class 𝕜₂ R F] lemma strong_topology.locally_convex_space (𝔖 : set (set E)) (h𝔖₁ : 𝔖.nonempty) (h𝔖₂ : directed_on (⊆) 𝔖) : @locally_convex_space R (E →SL[σ] F) _ _ _ (strong_topology σ F 𝔖) := begin letI : topological_space (E →SL[σ] F) := strong_topology σ F 𝔖, haveI : topological_add_group (E →SL[σ] F) := strong_topology.topological_add_group _ _ _, refine locally_convex_space.of_basis_zero _ _ _ _ (strong_topology.has_basis_nhds_zero_of_basis _ _ _ h𝔖₁ h𝔖₂ (locally_convex_space.convex_basis_zero R F)) _, rintros ⟨S, V⟩ ⟨hS, hVmem, hVconvex⟩ f hf g hg a b ha hb hab x hx, exact hVconvex (hf x hx) (hg x hx) ha hb hab, end end general section bounded_sets variables [ordered_semiring R] variables [normed_field 𝕜₁] [normed_field 𝕜₂] [module 𝕜₁ E] [module 𝕜₂ F] {σ : 𝕜₁ →+* 𝕜₂} variables [module R F] [has_continuous_const_smul R F] [locally_convex_space R F] [smul_comm_class 𝕜₂ R F] instance : locally_convex_space R (E →SL[σ] F) := strong_topology.locally_convex_space R _ ⟨∅, bornology.is_vonN_bounded_empty 𝕜₁ E⟩ (directed_on_of_sup_mem $ λ _ _, bornology.is_vonN_bounded.union) end bounded_sets end continuous_linear_map
27b095d77e4fcd58060f37762e52d67594b5840e
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/12_Axioms.org.29.lean
139894961195a6fe27e94dd0e3b07efb5024801f
[]
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
696
lean
import standard open classical function noncomputable definition linv {A B : Type} [h : inhabited A] (f : A → B) : B → A := λ b : B, if ex : (∃ a : A, f a = b) then some ex else arbitrary A theorem has_left_inverse_of_injective {A B : Type} {f : A → B} : inhabited A → injective f → ∃ g, g ∘ f = id := assume h : inhabited A, assume inj : ∀ a₁ a₂, f a₁ = f a₂ → a₁ = a₂, have is_linv : (linv f) ∘ f = id, from funext (λ a, assert ex : ∃ a₁ : A, f a₁ = f a, from exists.intro a rfl, have feq : f (some ex) = f a, from !some_spec, calc linv f (f a) = some ex : dif_pos ex ... = a : inj _ _ feq), exists.intro (linv f) is_linv
12fc3ecfd910c7937195ffeb5161fe79ea875d76
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/data/rat/basic.lean
2a612e16b2eb7d88285301901590429bb212b079
[ "Apache-2.0" ]
permissive
anrddh/mathlib
6a374da53c7e3a35cb0298b0cd67824efef362b4
a4266a01d2dcb10de19369307c986d038c7bb6a6
refs/heads/master
1,656,710,827,909
1,589,560,456,000
1,589,560,456,000
264,271,800
0
0
Apache-2.0
1,589,568,062,000
1,589,568,061,000
null
UTF-8
Lean
false
false
24,718
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.int.sqrt import data.equiv.encodable import algebra.group import algebra.euclidean_domain import algebra.ordered_field /-! # Basics for the Rational Numbers ## Summary We define a rational number `q` as a structure `{ num, denom, pos, cop }`, where - `num` is the numerator of `q`, - `denom` is the denominator of `q`, - `pos` is a proof that `denom > 0`, and - `cop` is a proof `num` and `denom` are coprime. We then define the expected (discrete) field structure on `ℚ` and prove basic lemmas about it. Moreoever, we provide the expected casts from `ℕ` and `ℤ` into `ℚ`, i.e. `(↑n : ℚ) = n / 1`. ## Main Definitions - `rat` is the structure encoding `ℚ`. - `rat.mk n d` constructs a rational number `q = n / d` from `n d : ℤ`. ## Notations - `/.` is infix notation for `rat.mk`. ## Tags rat, rationals, field, ℚ, numerator, denominator, num, denom -/ /-- `rat`, or `ℚ`, is the type of rational numbers. It is defined as the set of pairs ⟨n, d⟩ of integers such that `d` is positive and `n` and `d` are coprime. This representation is preferred to the quotient because without periodic reduction, the numerator and denominator can grow exponentially (for example, adding 1/2 to itself repeatedly). -/ structure rat := mk' :: (num : ℤ) (denom : ℕ) (pos : 0 < denom) (cop : num.nat_abs.coprime denom) notation `ℚ` := rat namespace rat protected def repr : ℚ → string | ⟨n, d, _, _⟩ := if d = 1 then _root_.repr n else _root_.repr n ++ "/" ++ _root_.repr d instance : has_repr ℚ := ⟨rat.repr⟩ instance : has_to_string ℚ := ⟨rat.repr⟩ meta instance : has_to_format ℚ := ⟨coe ∘ rat.repr⟩ instance : encodable ℚ := encodable.of_equiv (Σ n : ℤ, {d : ℕ // 0 < d ∧ n.nat_abs.coprime d}) ⟨λ ⟨a, b, c, d⟩, ⟨a, b, c, d⟩, λ⟨a, b, c, d⟩, ⟨a, b, c, d⟩, λ ⟨a, b, c, d⟩, rfl, λ⟨a, b, c, d⟩, rfl⟩ /-- Embed an integer as a rational number -/ def of_int (n : ℤ) : ℚ := ⟨n, 1, nat.one_pos, nat.coprime_one_right _⟩ instance : has_zero ℚ := ⟨of_int 0⟩ instance : has_one ℚ := ⟨of_int 1⟩ instance : inhabited ℚ := ⟨0⟩ /-- Form the quotient `n / d` where `n:ℤ` and `d:ℕ+` (not necessarily coprime) -/ def mk_pnat (n : ℤ) : ℕ+ → ℚ | ⟨d, dpos⟩ := let n' := n.nat_abs, g := n'.gcd d in ⟨n / g, d / g, begin apply (nat.le_div_iff_mul_le _ _ (nat.gcd_pos_of_pos_right _ dpos)).2, simp, exact nat.le_of_dvd dpos (nat.gcd_dvd_right _ _) end, begin have : int.nat_abs (n / ↑g) = n' / g, { cases int.nat_abs_eq n with e e; rw e, { refl }, rw [int.neg_div_of_dvd, int.nat_abs_neg], { refl }, exact int.coe_nat_dvd.2 (nat.gcd_dvd_left _ _) }, rw this, exact nat.coprime_div_gcd_div_gcd (nat.gcd_pos_of_pos_right _ dpos) end⟩ /-- Form the quotient `n / d` where `n:ℤ` and `d:ℕ`. In the case `d = 0`, we define `n / 0 = 0` by convention. -/ def mk_nat (n : ℤ) (d : ℕ) : ℚ := if d0 : d = 0 then 0 else mk_pnat n ⟨d, nat.pos_of_ne_zero d0⟩ /-- Form the quotient `n / d` where `n d : ℤ`. -/ def mk : ℤ → ℤ → ℚ | n (d : ℕ) := mk_nat n d | n -[1+ d] := mk_pnat (-n) d.succ_pnat localized "infix ` /. `:70 := rat.mk" in rat theorem mk_pnat_eq (n d h) : mk_pnat n ⟨d, h⟩ = n /. d := by change n /. d with dite _ _ _; simp [ne_of_gt h] theorem mk_nat_eq (n d) : mk_nat n d = n /. d := rfl @[simp] theorem mk_zero (n) : n /. 0 = 0 := rfl @[simp] theorem zero_mk_pnat (n) : mk_pnat 0 n = 0 := by cases n; simp [mk_pnat]; change int.nat_abs 0 with 0; simp *; refl @[simp] theorem zero_mk_nat (n) : mk_nat 0 n = 0 := by by_cases n = 0; simp [*, mk_nat] @[simp] theorem zero_mk (n) : 0 /. n = 0 := by cases n; simp [mk] private lemma gcd_abs_dvd_left {a b} : (nat.gcd (int.nat_abs a) b : ℤ) ∣ a := int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ nat.gcd_dvd_left (int.nat_abs a) b @[simp] theorem mk_eq_zero {a b : ℤ} (b0 : b ≠ 0) : a /. b = 0 ↔ a = 0 := begin constructor; intro h; [skip, {subst a, simp}], have : ∀ {a b}, mk_pnat a b = 0 → a = 0, { intros a b e, cases b with b h, injection e with e, apply int.eq_mul_of_div_eq_right gcd_abs_dvd_left e }, cases b with b; simp [mk, mk_nat] at h, { simp [mt (congr_arg int.of_nat) b0] at h, exact this h }, { apply neg_inj, simp [this h] } end theorem mk_eq : ∀ {a b c d : ℤ} (hb : b ≠ 0) (hd : d ≠ 0), a /. b = c /. d ↔ a * d = c * b := suffices ∀ a b c d hb hd, mk_pnat a ⟨b, hb⟩ = mk_pnat c ⟨d, hd⟩ ↔ a * d = c * b, begin intros, cases b with b b; simp [mk, mk_nat, nat.succ_pnat], simp [mt (congr_arg int.of_nat) hb], all_goals { cases d with d d; simp [mk, mk_nat, nat.succ_pnat], simp [mt (congr_arg int.of_nat) hd], all_goals { rw this, try {refl} } }, { change a * ↑(d.succ) = -c * ↑b ↔ a * -(d.succ) = c * b, constructor; intro h; apply neg_inj; simpa [left_distrib, neg_add_eq_iff_eq_add, eq_neg_iff_add_eq_zero, neg_eq_iff_add_eq_zero] using h }, { change -a * ↑d = c * b.succ ↔ a * d = c * -b.succ, constructor; intro h; apply neg_inj; simpa [left_distrib, eq_comm] using h }, { change -a * d.succ = -c * b.succ ↔ a * -d.succ = c * -b.succ, simp [left_distrib, sub_eq_add_neg], cc } end, begin intros, simp [mk_pnat], constructor; intro h, { cases h with ha hb, have ha, { have dv := @gcd_abs_dvd_left, have := int.eq_mul_of_div_eq_right dv ha, rw ← int.mul_div_assoc _ dv at this, exact int.eq_mul_of_div_eq_left (dvd_mul_of_dvd_right dv _) this.symm }, have hb, { have dv := λ {a b}, nat.gcd_dvd_right (int.nat_abs a) b, have := nat.eq_mul_of_div_eq_right dv hb, rw ← nat.mul_div_assoc _ dv at this, exact nat.eq_mul_of_div_eq_left (dvd_mul_of_dvd_right dv _) this.symm }, have m0 : (a.nat_abs.gcd b * c.nat_abs.gcd d : ℤ) ≠ 0, { refine int.coe_nat_ne_zero.2 (ne_of_gt _), apply mul_pos; apply nat.gcd_pos_of_pos_right; assumption }, apply eq_of_mul_eq_mul_right m0, simpa [mul_comm, mul_left_comm] using congr (congr_arg (*) ha.symm) (congr_arg coe hb) }, { suffices : ∀ a c, a * d = c * b → a / a.gcd b = c / c.gcd d ∧ b / a.gcd b = d / c.gcd d, { cases this a.nat_abs c.nat_abs (by simpa [int.nat_abs_mul] using congr_arg int.nat_abs h) with h₁ h₂, have hs := congr_arg int.sign h, simp [int.sign_eq_one_of_pos (int.coe_nat_lt.2 hb), int.sign_eq_one_of_pos (int.coe_nat_lt.2 hd)] at hs, conv in a { rw ← int.sign_mul_nat_abs a }, conv in c { rw ← int.sign_mul_nat_abs c }, rw [int.mul_div_assoc, int.mul_div_assoc], exact ⟨congr (congr_arg (*) hs) (congr_arg coe h₁), h₂⟩, all_goals { exact int.coe_nat_dvd.2 (nat.gcd_dvd_left _ _) } }, intros a c h, suffices bd : b / a.gcd b = d / c.gcd d, { refine ⟨_, bd⟩, apply nat.eq_of_mul_eq_mul_left hb, rw [← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _), mul_comm, nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), bd, ← nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), h, mul_comm, nat.mul_div_assoc _ (nat.gcd_dvd_left _ _)] }, suffices : ∀ {a c : ℕ} (b>0) (d>0), a * d = c * b → b / a.gcd b ≤ d / c.gcd d, { exact le_antisymm (this _ hb _ hd h) (this _ hd _ hb h.symm) }, intros a c b hb d hd h, have gb0 := nat.gcd_pos_of_pos_right a hb, have gd0 := nat.gcd_pos_of_pos_right c hd, apply nat.le_of_dvd, apply (nat.le_div_iff_mul_le _ _ gd0).2, simp, apply nat.le_of_dvd hd (nat.gcd_dvd_right _ _), apply (nat.coprime_div_gcd_div_gcd gb0).symm.dvd_of_dvd_mul_left, refine ⟨c / c.gcd d, _⟩, rw [← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _), ← nat.mul_div_assoc _ (nat.gcd_dvd_right _ _)], apply congr_arg (/ c.gcd d), rw [mul_comm, ← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _), mul_comm, h, nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), mul_comm] } end @[simp] theorem div_mk_div_cancel_left {a b c : ℤ} (c0 : c ≠ 0) : (a * c) /. (b * c) = a /. b := begin by_cases b0 : b = 0, { subst b0, simp }, apply (mk_eq (mul_ne_zero b0 c0) b0).2, simp [mul_comm, mul_assoc] end @[simp] theorem num_denom : ∀ {a : ℚ}, a.num /. a.denom = a | ⟨n, d, h, (c:_=1)⟩ := show mk_nat n d = _, by simp [mk_nat, ne_of_gt h, mk_pnat, c] theorem num_denom' {n d h c} : (⟨n, d, h, c⟩ : ℚ) = n /. d := num_denom.symm theorem of_int_eq_mk (z : ℤ) : of_int z = z /. 1 := num_denom' @[elab_as_eliminator] def {u} num_denom_cases_on {C : ℚ → Sort u} : ∀ (a : ℚ) (H : ∀ n d, 0 < d → (int.nat_abs n).coprime d → C (n /. d)), C a | ⟨n, d, h, c⟩ H := by rw num_denom'; exact H n d h c @[elab_as_eliminator] def {u} num_denom_cases_on' {C : ℚ → Sort u} (a : ℚ) (H : ∀ (n:ℤ) (d:ℕ), d ≠ 0 → C (n /. d)) : C a := num_denom_cases_on a $ λ n d h c, H n d $ ne_of_gt h theorem num_dvd (a) {b : ℤ} (b0 : b ≠ 0) : (a /. b).num ∣ a := begin cases e : a /. b with n d h c, rw [rat.num_denom', rat.mk_eq b0 (ne_of_gt (int.coe_nat_pos.2 h))] at e, refine (int.nat_abs_dvd.1 $ int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ c.dvd_of_dvd_mul_right _), have := congr_arg int.nat_abs e, simp [int.nat_abs_mul, int.nat_abs_of_nat] at this, simp [this] end theorem denom_dvd (a b : ℤ) : ((a /. b).denom : ℤ) ∣ b := begin by_cases b0 : b = 0, {simp [b0]}, cases e : a /. b with n d h c, rw [num_denom', mk_eq b0 (ne_of_gt (int.coe_nat_pos.2 h))] at e, refine (int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ c.symm.dvd_of_dvd_mul_left _), rw [← int.nat_abs_mul, ← int.coe_nat_dvd, int.dvd_nat_abs, ← e], simp end protected def add : ℚ → ℚ → ℚ | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := mk_pnat (n₁ * d₂ + n₂ * d₁) ⟨d₁ * d₂, mul_pos h₁ h₂⟩ instance : has_add ℚ := ⟨rat.add⟩ theorem lift_binop_eq (f : ℚ → ℚ → ℚ) (f₁ : ℤ → ℤ → ℤ → ℤ → ℤ) (f₂ : ℤ → ℤ → ℤ → ℤ → ℤ) (fv : ∀ {n₁ d₁ h₁ c₁ n₂ d₂ h₂ c₂}, f ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ = f₁ n₁ d₁ n₂ d₂ /. f₂ n₁ d₁ n₂ d₂) (f0 : ∀ {n₁ d₁ n₂ d₂} (d₁0 : d₁ ≠ 0) (d₂0 : d₂ ≠ 0), f₂ n₁ d₁ n₂ d₂ ≠ 0) (a b c d : ℤ) (b0 : b ≠ 0) (d0 : d ≠ 0) (H : ∀ {n₁ d₁ n₂ d₂} (h₁ : a * d₁ = n₁ * b) (h₂ : c * d₂ = n₂ * d), f₁ n₁ d₁ n₂ d₂ * f₂ a b c d = f₁ a b c d * f₂ n₁ d₁ n₂ d₂) : f (a /. b) (c /. d) = f₁ a b c d /. f₂ a b c d := begin generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha, generalize hc : c /. d = x, cases x with n₂ d₂ h₂ c₂, rw num_denom' at hc, rw fv, have d₁0 := ne_of_gt (int.coe_nat_lt.2 h₁), have d₂0 := ne_of_gt (int.coe_nat_lt.2 h₂), exact (mk_eq (f0 d₁0 d₂0) (f0 b0 d0)).2 (H ((mk_eq b0 d₁0).1 ha) ((mk_eq d0 d₂0).1 hc)) end @[simp] theorem add_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) : a /. b + c /. d = (a * d + c * b) /. (b * d) := begin apply lift_binop_eq rat.add; intros; try {assumption}, { apply mk_pnat_eq }, { apply mul_ne_zero d₁0 d₂0 }, calc (n₁ * d₂ + n₂ * d₁) * (b * d) = (n₁ * b) * d₂ * d + (n₂ * d) * (d₁ * b) : by simp [mul_add, mul_comm, mul_left_comm] ... = (a * d₁) * d₂ * d + (c * d₂) * (d₁ * b) : by rw [h₁, h₂] ... = (a * d + c * b) * (d₁ * d₂) : by simp [mul_add, mul_comm, mul_left_comm] end protected def neg : ℚ → ℚ | ⟨n, d, h, c⟩ := ⟨-n, d, h, by simp [c]⟩ instance : has_neg ℚ := ⟨rat.neg⟩ @[simp] theorem neg_def {a b : ℤ} : -(a /. b) = -a /. b := begin by_cases b0 : b = 0, { subst b0, simp, refl }, generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha, show rat.mk' _ _ _ _ = _, rw num_denom', have d0 := ne_of_gt (int.coe_nat_lt.2 h₁), apply (mk_eq d0 b0).2, have h₁ := (mk_eq b0 d0).1 ha, simp only [neg_mul_eq_neg_mul_symm, congr_arg has_neg.neg h₁] end protected def mul : ℚ → ℚ → ℚ | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := mk_pnat (n₁ * n₂) ⟨d₁ * d₂, mul_pos h₁ h₂⟩ instance : has_mul ℚ := ⟨rat.mul⟩ @[simp] theorem mul_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) : (a /. b) * (c /. d) = (a * c) /. (b * d) := begin apply lift_binop_eq rat.mul; intros; try {assumption}, { apply mk_pnat_eq }, { apply mul_ne_zero d₁0 d₂0 }, cc end protected def inv : ℚ → ℚ | ⟨(n+1:ℕ), d, h, c⟩ := ⟨d, n+1, n.succ_pos, c.symm⟩ | ⟨0, d, h, c⟩ := 0 | ⟨-[1+ n], d, h, c⟩ := ⟨-d, n+1, n.succ_pos, nat.coprime.symm $ by simp; exact c⟩ instance : has_inv ℚ := ⟨rat.inv⟩ @[simp] theorem inv_def {a b : ℤ} : (a /. b)⁻¹ = b /. a := begin by_cases a0 : a = 0, { subst a0, simp, refl }, by_cases b0 : b = 0, { subst b0, simp, refl }, generalize ha : a /. b = x, cases x with n d h c, rw num_denom' at ha, refine eq.trans (_ : rat.inv ⟨n, d, h, c⟩ = d /. n) _, { cases n with n; [cases n with n, skip], { refl }, { change int.of_nat n.succ with (n+1:ℕ), unfold rat.inv, rw num_denom' }, { unfold rat.inv, rw num_denom', refl } }, have n0 : n ≠ 0, { refine mt (λ (n0 : n = 0), _) a0, subst n0, simp at ha, exact (mk_eq_zero b0).1 ha }, have d0 := ne_of_gt (int.coe_nat_lt.2 h), have ha := (mk_eq b0 d0).1 ha, apply (mk_eq n0 a0).2, cc end variables (a b c : ℚ) protected theorem add_zero : a + 0 = a := num_denom_cases_on' a $ λ n d h, by rw [← zero_mk d]; simp [h, -zero_mk] protected theorem zero_add : 0 + a = a := num_denom_cases_on' a $ λ n d h, by rw [← zero_mk d]; simp [h, -zero_mk] protected theorem add_comm : a + b = b + a := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, by simp [h₁, h₂]; cc protected theorem add_assoc : a + b + c = a + (b + c) := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, num_denom_cases_on' c $ λ n₃ d₃ h₃, by simp [h₁, h₂, h₃, mul_ne_zero, mul_add, mul_comm, mul_left_comm, add_left_comm] protected theorem add_left_neg : -a + a = 0 := num_denom_cases_on' a $ λ n d h, by simp [h] protected theorem mul_one : a * 1 = a := num_denom_cases_on' a $ λ n d h, by change (1:ℚ) with 1 /. 1; simp [h] protected theorem one_mul : 1 * a = a := num_denom_cases_on' a $ λ n d h, by change (1:ℚ) with 1 /. 1; simp [h] protected theorem mul_comm : a * b = b * a := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, by simp [h₁, h₂, mul_comm] protected theorem mul_assoc : a * b * c = a * (b * c) := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, num_denom_cases_on' c $ λ n₃ d₃ h₃, by simp [h₁, h₂, h₃, mul_ne_zero, mul_comm, mul_left_comm] protected theorem add_mul : (a + b) * c = a * c + b * c := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, num_denom_cases_on' c $ λ n₃ d₃ h₃, by simp [h₁, h₂, h₃, mul_ne_zero]; refine (div_mk_div_cancel_left (int.coe_nat_ne_zero.2 h₃)).symm.trans _; simp [mul_add, mul_comm, mul_assoc, mul_left_comm] protected theorem mul_add : a * (b + c) = a * b + a * c := by rw [rat.mul_comm, rat.add_mul, rat.mul_comm, rat.mul_comm c a] protected theorem zero_ne_one : 0 ≠ (1:ℚ) := mt (λ (h : 0 = 1 /. 1), (mk_eq_zero one_ne_zero).1 h.symm) one_ne_zero protected theorem mul_inv_cancel : a ≠ 0 → a * a⁻¹ = 1 := num_denom_cases_on' a $ λ n d h a0, have n0 : n ≠ 0, from mt (by intro e; subst e; simp) a0, by simp [h, n0, mul_comm]; exact eq.trans (by simp) (@div_mk_div_cancel_left 1 1 _ n0) protected theorem inv_mul_cancel (h : a ≠ 0) : a⁻¹ * a = 1 := eq.trans (rat.mul_comm _ _) (rat.mul_inv_cancel _ h) instance : decidable_eq ℚ := by tactic.mk_dec_eq_instance instance : field ℚ := { zero := 0, add := rat.add, neg := rat.neg, one := 1, mul := rat.mul, inv := rat.inv, zero_add := rat.zero_add, add_zero := rat.add_zero, add_comm := rat.add_comm, add_assoc := rat.add_assoc, add_left_neg := rat.add_left_neg, mul_one := rat.mul_one, one_mul := rat.one_mul, mul_comm := rat.mul_comm, mul_assoc := rat.mul_assoc, left_distrib := rat.mul_add, right_distrib := rat.add_mul, zero_ne_one := rat.zero_ne_one, mul_inv_cancel := rat.mul_inv_cancel, inv_zero := rfl } /- Extra instances to short-circuit type class resolution -/ instance : division_ring ℚ := by apply_instance instance : integral_domain ℚ := by apply_instance -- TODO(Mario): this instance slows down data.real.basic --instance : domain ℚ := by apply_instance instance : nonzero_comm_ring ℚ := by apply_instance instance : comm_ring ℚ := by apply_instance --instance : ring ℚ := by apply_instance instance : comm_semiring ℚ := by apply_instance instance : semiring ℚ := by apply_instance instance : add_comm_group ℚ := by apply_instance instance : add_group ℚ := by apply_instance instance : add_comm_monoid ℚ := by apply_instance instance : add_monoid ℚ := by apply_instance instance : add_left_cancel_semigroup ℚ := by apply_instance instance : add_right_cancel_semigroup ℚ := by apply_instance instance : add_comm_semigroup ℚ := by apply_instance instance : add_semigroup ℚ := by apply_instance instance : comm_monoid ℚ := by apply_instance instance : monoid ℚ := by apply_instance instance : comm_semigroup ℚ := by apply_instance instance : semigroup ℚ := by apply_instance theorem sub_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) : a /. b - c /. d = (a * d - c * b) /. (b * d) := by simp [b0, d0, sub_eq_add_neg] @[simp] lemma denom_neg_eq_denom : ∀ q : ℚ, (-q).denom = q.denom | ⟨_, d, _, _⟩ := rfl @[simp] lemma num_neg_eq_neg_num : ∀ q : ℚ, (-q).num = -(q.num) | ⟨n, _, _, _⟩ := rfl @[simp] lemma num_zero : rat.num 0 = 0 := rfl lemma zero_of_num_zero {q : ℚ} (hq : q.num = 0) : q = 0 := have q = q.num /. q.denom, from num_denom.symm, by simpa [hq] lemma zero_iff_num_zero {q : ℚ} : q = 0 ↔ q.num = 0 := ⟨λ _, by simp *, zero_of_num_zero⟩ lemma num_ne_zero_of_ne_zero {q : ℚ} (h : q ≠ 0) : q.num ≠ 0 := assume : q.num = 0, h $ zero_of_num_zero this @[simp] lemma num_one : (1 : ℚ).num = 1 := rfl @[simp] lemma denom_one : (1 : ℚ).denom = 1 := rfl lemma denom_ne_zero (q : ℚ) : q.denom ≠ 0 := ne_of_gt q.pos lemma eq_iff_mul_eq_mul {p q : ℚ} : p = q ↔ p.num * q.denom = q.num * p.denom := begin conv_lhs { rw [←(@num_denom p), ←(@num_denom q)] }, apply rat.mk_eq, { exact_mod_cast p.denom_ne_zero }, { exact_mod_cast q.denom_ne_zero } end lemma mk_num_ne_zero_of_ne_zero {q : ℚ} {n d : ℤ} (hq : q ≠ 0) (hqnd : q = n /. d) : n ≠ 0 := assume : n = 0, hq $ by simpa [this] using hqnd lemma mk_denom_ne_zero_of_ne_zero {q : ℚ} {n d : ℤ} (hq : q ≠ 0) (hqnd : q = n /. d) : d ≠ 0 := assume : d = 0, hq $ by simpa [this] using hqnd lemma mk_ne_zero_of_ne_zero {n d : ℤ} (h : n ≠ 0) (hd : d ≠ 0) : n /. d ≠ 0 := assume : n /. d = 0, h $ (mk_eq_zero hd).1 this lemma mul_num_denom (q r : ℚ) : q * r = (q.num * r.num) /. ↑(q.denom * r.denom) := have hq' : (↑q.denom : ℤ) ≠ 0, by have := denom_ne_zero q; simpa, have hr' : (↑r.denom : ℤ) ≠ 0, by have := denom_ne_zero r; simpa, suffices (q.num /. ↑q.denom) * (r.num /. ↑r.denom) = (q.num * r.num) /. ↑(q.denom * r.denom), by simpa using this, by simp [mul_def hq' hr', -num_denom] lemma div_num_denom (q r : ℚ) : q / r = (q.num * r.denom) /. (q.denom * r.num) := if hr : r.num = 0 then have hr' : r = 0, from zero_of_num_zero hr, by simp * else calc q / r = q * r⁻¹ : div_eq_mul_inv ... = (q.num /. q.denom) * (r.num /. r.denom)⁻¹ : by simp ... = (q.num /. q.denom) * (r.denom /. r.num) : by rw inv_def ... = (q.num * r.denom) /. (q.denom * r.num) : mul_def (by simpa using denom_ne_zero q) hr lemma num_denom_mk {q : ℚ} {n d : ℤ} (hn : n ≠ 0) (hd : d ≠ 0) (qdf : q = n /. d) : ∃ c : ℤ, n = c * q.num ∧ d = c * q.denom := have hq : q ≠ 0, from assume : q = 0, hn $ (rat.mk_eq_zero hd).1 (by cc), have q.num /. q.denom = n /. d, by rwa [num_denom], have q.num * d = n * ↑(q.denom), from (rat.mk_eq (by simp [rat.denom_ne_zero]) hd).1 this, begin existsi n / q.num, have hqdn : q.num ∣ n, begin rw qdf, apply rat.num_dvd, assumption end, split, { rw int.div_mul_cancel hqdn }, { apply int.eq_mul_div_of_mul_eq_mul_of_dvd_left, { apply rat.num_ne_zero_of_ne_zero hq }, repeat { assumption } } end theorem mk_pnat_num (n : ℤ) (d : ℕ+) : (mk_pnat n d).num = n / nat.gcd n.nat_abs d := by cases d; refl theorem mk_pnat_denom (n : ℤ) (d : ℕ+) : (mk_pnat n d).denom = d / nat.gcd n.nat_abs d := by cases d; refl theorem mul_num (q₁ q₂ : ℚ) : (q₁ * q₂).num = (q₁.num * q₂.num) / nat.gcd (q₁.num * q₂.num).nat_abs (q₁.denom * q₂.denom) := by cases q₁; cases q₂; refl theorem mul_denom (q₁ q₂ : ℚ) : (q₁ * q₂).denom = (q₁.denom * q₂.denom) / nat.gcd (q₁.num * q₂.num).nat_abs (q₁.denom * q₂.denom) := by cases q₁; cases q₂; refl theorem mul_self_num (q : ℚ) : (q * q).num = q.num * q.num := by rw [mul_num, int.nat_abs_mul, nat.coprime.gcd_eq_one, int.coe_nat_one, int.div_one]; exact (q.cop.mul_right q.cop).mul (q.cop.mul_right q.cop) theorem mul_self_denom (q : ℚ) : (q * q).denom = q.denom * q.denom := by rw [rat.mul_denom, int.nat_abs_mul, nat.coprime.gcd_eq_one, nat.div_one]; exact (q.cop.mul_right q.cop).mul (q.cop.mul_right q.cop) lemma add_num_denom (q r : ℚ) : q + r = ((q.num * r.denom + q.denom * r.num : ℤ)) /. (↑q.denom * ↑r.denom : ℤ) := have hqd : (q.denom : ℤ) ≠ 0, from int.coe_nat_ne_zero_iff_pos.2 q.3, have hrd : (r.denom : ℤ) ≠ 0, from int.coe_nat_ne_zero_iff_pos.2 r.3, by conv_lhs { rw [←@num_denom q, ←@num_denom r, rat.add_def hqd hrd] }; simp [mul_comm] section casts theorem coe_int_eq_mk : ∀ (z : ℤ), ↑z = z /. 1 | (n : ℕ) := show (n:ℚ) = n /. 1, by induction n with n IH n; simp [*, show (1:ℚ) = 1 /. 1, from rfl] | -[1+ n] := show (-(n + 1) : ℚ) = -[1+ n] /. 1, begin induction n with n IH, {refl}, show -(n + 1 + 1 : ℚ) = -[1+ n.succ] /. 1, rw [neg_add, IH], simpa [show -1 = (-1) /. 1, from rfl] end theorem mk_eq_div (n d : ℤ) : n /. d = ((n : ℚ) / d) := begin by_cases d0 : d = 0, {simp [d0, div_zero]}, simp [division_def, coe_int_eq_mk, mul_def one_ne_zero d0] end theorem coe_int_eq_of_int (z : ℤ) : ↑z = of_int z := (coe_int_eq_mk z).trans (of_int_eq_mk z).symm @[simp, norm_cast] theorem coe_int_num (n : ℤ) : (n : ℚ).num = n := by rw coe_int_eq_of_int; refl @[simp, norm_cast] theorem coe_int_denom (n : ℤ) : (n : ℚ).denom = 1 := by rw coe_int_eq_of_int; refl lemma coe_int_num_of_denom_eq_one {q : ℚ} (hq : q.denom = 1) : ↑(q.num) = q := by { conv_rhs { rw [←(@num_denom q), hq] }, rw [coe_int_eq_mk], refl } instance : can_lift ℚ ℤ := ⟨coe, λ q, q.denom = 1, λ q hq, ⟨q.num, coe_int_num_of_denom_eq_one hq⟩⟩ theorem coe_nat_eq_mk (n : ℕ) : ↑n = n /. 1 := by rw [← int.cast_coe_nat, coe_int_eq_mk] @[simp, norm_cast] theorem coe_nat_num (n : ℕ) : (n : ℚ).num = n := by rw [← int.cast_coe_nat, coe_int_num] @[simp, norm_cast] theorem coe_nat_denom (n : ℕ) : (n : ℚ).denom = 1 := by rw [← int.cast_coe_nat, coe_int_denom] end casts lemma inv_def' {q : ℚ} : q⁻¹ = (q.denom : ℚ) / q.num := by { conv_lhs { rw ←(@num_denom q) }, cases q, simp [div_num_denom] } @[simp] lemma mul_own_denom_eq_num {q : ℚ} : q * q.denom = q.num := begin suffices : mk (q.num) ↑(q.denom) * mk ↑(q.denom) 1 = mk (q.num) 1, by { conv { for q [1] { rw ←(@num_denom q) }}, rwa [coe_int_eq_mk, coe_nat_eq_mk] }, have : (q.denom : ℤ) ≠ 0, from ne_of_gt (by exact_mod_cast q.pos), rw [(rat.mul_def this one_ne_zero), (mul_comm (q.denom : ℤ) 1), (div_mk_div_cancel_left this)] end end rat
9c8da3424cf9df1d82fc5a894b879510517bee7d
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/linear_algebra/multilinear/basic.lean
3395c35cac289c4135f0314396b864f5552c2653
[ "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
58,573
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import linear_algebra.basic import linear_algebra.matrix.to_lin import algebra.algebra.basic import algebra.big_operators.order import algebra.big_operators.ring import data.fin.tuple import data.fintype.card import data.fintype.sort /-! # Multilinear maps We define multilinear maps as maps from `Π(i : ι), M₁ i` to `M₂` which are linear in each coordinate. Here, `M₁ i` and `M₂` are modules over a ring `R`, and `ι` is an arbitrary type (although some statements will require it to be a fintype). This space, denoted by `multilinear_map R M₁ M₂`, inherits a module structure by pointwise addition and multiplication. ## Main definitions * `multilinear_map R M₁ M₂` is the space of multilinear maps from `Π(i : ι), M₁ i` to `M₂`. * `f.map_smul` is the multiplicativity of the multilinear map `f` along each coordinate. * `f.map_add` is the additivity of the multilinear map `f` along each coordinate. * `f.map_smul_univ` expresses the multiplicativity of `f` over all coordinates at the same time, writing `f (λi, c i • m i)` as `(∏ i, c i) • f m`. * `f.map_add_univ` expresses the additivity of `f` over all coordinates at the same time, writing `f (m + m')` as the sum over all subsets `s` of `ι` of `f (s.piecewise m m')`. * `f.map_sum` expresses `f (Σ_{j₁} g₁ j₁, ..., Σ_{jₙ} gₙ jₙ)` as the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all possible functions. We also register isomorphisms corresponding to currying or uncurrying variables, transforming a multilinear function `f` on `n+1` variables into a linear function taking values in multilinear functions in `n` variables, and into a multilinear function in `n` variables taking values in linear functions. These operations are called `f.curry_left` and `f.curry_right` respectively (with inverses `f.uncurry_left` and `f.uncurry_right`). These operations induce linear equivalences between spaces of multilinear functions in `n+1` variables and spaces of linear functions into multilinear functions in `n` variables (resp. multilinear functions in `n` variables taking values in linear functions), called respectively `multilinear_curry_left_equiv` and `multilinear_curry_right_equiv`. ## Implementation notes Expressing that a map is linear along the `i`-th coordinate when all other coordinates are fixed can be done in two (equivalent) different ways: * fixing a vector `m : Π(j : ι - i), M₁ j.val`, and then choosing separately the `i`-th coordinate * fixing a vector `m : Πj, M₁ j`, and then modifying its `i`-th coordinate The second way is more artificial as the value of `m` at `i` is not relevant, but it has the advantage of avoiding subtype inclusion issues. This is the definition we use, based on `function.update` that allows to change the value of `m` at `i`. -/ open function fin set open_locale big_operators universes u v v' v₁ v₂ v₃ w u' variables {R : Type u} {ι : Type u'} {n : ℕ} {M : fin n.succ → Type v} {M₁ : ι → Type v₁} {M₂ : Type v₂} {M₃ : Type v₃} {M' : Type v'} [decidable_eq ι] /-- Multilinear maps over the ring `R`, from `Πi, M₁ i` to `M₂` where `M₁ i` and `M₂` are modules over `R`. -/ structure multilinear_map (R : Type u) {ι : Type u'} (M₁ : ι → Type v) (M₂ : Type w) [decidable_eq ι] [semiring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [∀i, module R (M₁ i)] [module R M₂] := (to_fun : (Πi, M₁ i) → M₂) (map_add' : ∀(m : Πi, M₁ i) (i : ι) (x y : M₁ i), to_fun (update m i (x + y)) = to_fun (update m i x) + to_fun (update m i y)) (map_smul' : ∀(m : Πi, M₁ i) (i : ι) (c : R) (x : M₁ i), to_fun (update m i (c • x)) = c • to_fun (update m i x)) namespace multilinear_map section semiring variables [semiring R] [∀i, add_comm_monoid (M i)] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M'] [∀i, module R (M i)] [∀i, module R (M₁ i)] [module R M₂] [module R M₃] [module R M'] (f f' : multilinear_map R M₁ M₂) instance : has_coe_to_fun (multilinear_map R M₁ M₂) (λ f, (Πi, M₁ i) → M₂) := ⟨to_fun⟩ initialize_simps_projections multilinear_map (to_fun → apply) @[simp] lemma to_fun_eq_coe : f.to_fun = f := rfl @[simp] lemma coe_mk (f : (Π i, M₁ i) → M₂) (h₁ h₂ ) : ⇑(⟨f, h₁, h₂⟩ : multilinear_map R M₁ M₂) = f := rfl theorem congr_fun {f g : multilinear_map R M₁ M₂} (h : f = g) (x : Π i, M₁ i) : f x = g x := congr_arg (λ h : multilinear_map R M₁ M₂, h x) h theorem congr_arg (f : multilinear_map R M₁ M₂) {x y : Π i, M₁ i} (h : x = y) : f x = f y := congr_arg (λ x : Π i, M₁ i, f x) h theorem coe_injective : injective (coe_fn : multilinear_map R M₁ M₂ → ((Π i, M₁ i) → M₂)) := by { intros f g h, cases f, cases g, cases h, refl } @[simp, norm_cast] theorem coe_inj {f g : multilinear_map R M₁ M₂} : (f : (Π i, M₁ i) → M₂) = g ↔ f = g := coe_injective.eq_iff @[ext] theorem ext {f f' : multilinear_map R M₁ M₂} (H : ∀ x, f x = f' x) : f = f' := coe_injective (funext H) theorem ext_iff {f g : multilinear_map R M₁ M₂} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ @[simp] lemma mk_coe (f : multilinear_map R M₁ M₂) (h₁ h₂) : (⟨f, h₁, h₂⟩ : multilinear_map R M₁ M₂) = f := by { ext, refl, } @[simp] protected lemma map_add (m : Πi, M₁ i) (i : ι) (x y : M₁ i) : f (update m i (x + y)) = f (update m i x) + f (update m i y) := f.map_add' m i x y @[simp] lemma map_smul (m : Πi, M₁ i) (i : ι) (c : R) (x : M₁ i) : f (update m i (c • x)) = c • f (update m i x) := f.map_smul' m i c x lemma map_coord_zero {m : Πi, M₁ i} (i : ι) (h : m i = 0) : f m = 0 := begin have : (0 : R) • (0 : M₁ i) = 0, by simp, rw [← update_eq_self i m, h, ← this, f.map_smul, zero_smul] end @[simp] lemma map_update_zero (m : Πi, M₁ i) (i : ι) : f (update m i 0) = 0 := f.map_coord_zero i (update_same i 0 m) @[simp] lemma map_zero [nonempty ι] : f 0 = 0 := begin obtain ⟨i, _⟩ : ∃i:ι, i ∈ set.univ := set.exists_mem_of_nonempty ι, exact map_coord_zero f i rfl end instance : has_add (multilinear_map R M₁ M₂) := ⟨λf f', ⟨λx, f x + f' x, λm i x y, by simp [add_left_comm, add_assoc], λm i c x, by simp [smul_add]⟩⟩ @[simp] lemma add_apply (m : Πi, M₁ i) : (f + f') m = f m + f' m := rfl instance : has_zero (multilinear_map R M₁ M₂) := ⟨⟨λ _, 0, λm i x y, by simp, λm i c x, by simp⟩⟩ instance : inhabited (multilinear_map R M₁ M₂) := ⟨0⟩ @[simp] lemma zero_apply (m : Πi, M₁ i) : (0 : multilinear_map R M₁ M₂) m = 0 := rfl instance : add_comm_monoid (multilinear_map R M₁ M₂) := { zero := (0 : multilinear_map R M₁ M₂), add := (+), add_assoc := by intros; ext; simp [add_comm, add_left_comm], zero_add := by intros; ext; simp [add_comm, add_left_comm], add_zero := by intros; ext; simp [add_comm, add_left_comm], add_comm := by intros; ext; simp [add_comm, add_left_comm], nsmul := λ n f, ⟨λ m, n • f m, λm i x y, by simp [smul_add], λl i x d, by simp [←smul_comm x n] ⟩, nsmul_zero' := λ f, by { ext, simp }, nsmul_succ' := λ n f, by { ext, simp [add_smul, nat.succ_eq_one_add] } } @[simp] lemma sum_apply {α : Type*} (f : α → multilinear_map R M₁ M₂) (m : Πi, M₁ i) : ∀ {s : finset α}, (∑ a in s, f a) m = ∑ a in s, f a m := begin classical, apply finset.induction, { rw finset.sum_empty, simp }, { assume a s has H, rw finset.sum_insert has, simp [H, has] } end /-- If `f` is a multilinear map, then `f.to_linear_map m i` is the linear map obtained by fixing all coordinates but `i` equal to those of `m`, and varying the `i`-th coordinate. -/ @[simps] def to_linear_map (m : Πi, M₁ i) (i : ι) : M₁ i →ₗ[R] M₂ := { to_fun := λx, f (update m i x), map_add' := λx y, by simp, map_smul' := λc x, by simp } /-- The cartesian product of two multilinear maps, as a multilinear map. -/ def prod (f : multilinear_map R M₁ M₂) (g : multilinear_map R M₁ M₃) : multilinear_map R M₁ (M₂ × M₃) := { to_fun := λ m, (f m, g m), map_add' := λ m i x y, by simp, map_smul' := λ m i c x, by simp } /-- Combine a family of multilinear maps with the same domain and codomains `M' i` into a multilinear map taking values in the space of functions `Π i, M' i`. -/ @[simps] def pi {ι' : Type*} {M' : ι' → Type*} [Π i, add_comm_monoid (M' i)] [Π i, module R (M' i)] (f : Π i, multilinear_map R M₁ (M' i)) : multilinear_map R M₁ (Π i, M' i) := { to_fun := λ m i, f i m, map_add' := λ m i x y, funext $ λ j, (f j).map_add _ _ _ _, map_smul' := λ m i c x, funext $ λ j, (f j).map_smul _ _ _ _ } section variables (R M₂) /-- The evaluation map from `ι → M₂` to `M₂` is multilinear at a given `i` when `ι` is subsingleton. -/ @[simps] def of_subsingleton [subsingleton ι] (i' : ι) : multilinear_map R (λ _ : ι, M₂) M₂ := { to_fun := function.eval i', map_add' := λ m i x y, by { rw subsingleton.elim i i', simp only [function.eval, function.update_same], }, map_smul' := λ m i r x, by { rw subsingleton.elim i i', simp only [function.eval, function.update_same], } } variables {M₂} /-- The constant map is multilinear when `ι` is empty. -/ @[simps {fully_applied := ff}] def const_of_is_empty [is_empty ι] (m : M₂) : multilinear_map R M₁ M₂ := { to_fun := function.const _ m, map_add' := λ m, is_empty_elim, map_smul' := λ m, is_empty_elim } end /-- Given a multilinear map `f` on `n` variables (parameterized by `fin n`) and a subset `s` of `k` of these variables, one gets a new multilinear map on `fin k` by varying these variables, and fixing the other ones equal to a given value `z`. It is denoted by `f.restr s hk z`, where `hk` is a proof that the cardinality of `s` is `k`. The implicit identification between `fin k` and `s` that we use is the canonical (increasing) bijection. -/ def restr {k n : ℕ} (f : multilinear_map R (λ i : fin n, M') M₂) (s : finset (fin n)) (hk : s.card = k) (z : M') : multilinear_map R (λ i : fin k, M') M₂ := { to_fun := λ v, f (λ j, if h : j ∈ s then v ((s.order_iso_of_fin hk).symm ⟨j, h⟩) else z), map_add' := λ v i x y, by { erw [dite_comp_equiv_update, dite_comp_equiv_update, dite_comp_equiv_update], simp }, map_smul' := λ v i c x, by { erw [dite_comp_equiv_update, dite_comp_equiv_update], simp } } variable {R} /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the additivity of a multilinear map along the first variable. -/ lemma cons_add (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (x y : M 0) : f (cons (x+y) m) = f (cons x m) + f (cons y m) := by rw [← update_cons_zero x m (x+y), f.map_add, update_cons_zero, update_cons_zero] /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the multiplicativity of a multilinear map along the first variable. -/ lemma cons_smul (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (c : R) (x : M 0) : f (cons (c • x) m) = c • f (cons x m) := by rw [← update_cons_zero x m (c • x), f.map_smul, update_cons_zero] /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `snoc`, one can express directly the additivity of a multilinear map along the first variable. -/ lemma snoc_add (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.cast_succ) (x y : M (last n)) : f (snoc m (x+y)) = f (snoc m x) + f (snoc m y) := by rw [← update_snoc_last x m (x+y), f.map_add, update_snoc_last, update_snoc_last] /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the multiplicativity of a multilinear map along the first variable. -/ lemma snoc_smul (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.cast_succ) (c : R) (x : M (last n)) : f (snoc m (c • x)) = c • f (snoc m x) := by rw [← update_snoc_last x m (c • x), f.map_smul, update_snoc_last] section variables {M₁' : ι → Type*} [Π i, add_comm_monoid (M₁' i)] [Π i, module R (M₁' i)] variables {M₁'' : ι → Type*} [Π i, add_comm_monoid (M₁'' i)] [Π i, module R (M₁'' i)] /-- If `g` is a multilinear map and `f` is a collection of linear maps, then `g (f₁ m₁, ..., fₙ mₙ)` is again a multilinear map, that we call `g.comp_linear_map f`. -/ def comp_linear_map (g : multilinear_map R M₁' M₂) (f : Π i, M₁ i →ₗ[R] M₁' i) : multilinear_map R M₁ M₂ := { to_fun := λ m, g $ λ i, f i (m i), map_add' := λ m i x y, have ∀ j z, f j (update m i z j) = update (λ k, f k (m k)) i (f i z) j := λ j z, function.apply_update (λ k, f k) _ _ _ _, by simp [this], map_smul' := λ m i c x, have ∀ j z, f j (update m i z j) = update (λ k, f k (m k)) i (f i z) j := λ j z, function.apply_update (λ k, f k) _ _ _ _, by simp [this] } @[simp] lemma comp_linear_map_apply (g : multilinear_map R M₁' M₂) (f : Π i, M₁ i →ₗ[R] M₁' i) (m : Π i, M₁ i) : g.comp_linear_map f m = g (λ i, f i (m i)) := rfl /-- Composing a multilinear map twice with a linear map in each argument is the same as composing with their composition. -/ lemma comp_linear_map_assoc (g : multilinear_map R M₁'' M₂) (f₁ : Π i, M₁' i →ₗ[R] M₁'' i) (f₂ : Π i, M₁ i →ₗ[R] M₁' i) : (g.comp_linear_map f₁).comp_linear_map f₂ = g.comp_linear_map (λ i, f₁ i ∘ₗ f₂ i) := rfl /-- Composing the zero multilinear map with a linear map in each argument. -/ @[simp] lemma zero_comp_linear_map (f : Π i, M₁ i →ₗ[R] M₁' i) : (0 : multilinear_map R M₁' M₂).comp_linear_map f = 0 := ext $ λ _, rfl /-- Composing a multilinear map with the identity linear map in each argument. -/ @[simp] lemma comp_linear_map_id (g : multilinear_map R M₁' M₂) : g.comp_linear_map (λ i, linear_map.id) = g := ext $ λ _, rfl /-- Composing with a family of surjective linear maps is injective. -/ lemma comp_linear_map_injective (f : Π i, M₁ i →ₗ[R] M₁' i) (hf : ∀ i, surjective (f i)) : injective (λ g : multilinear_map R M₁' M₂, g.comp_linear_map f) := λ g₁ g₂ h, ext $ λ x, by simpa [λ i, surj_inv_eq (hf i)] using ext_iff.mp h (λ i, surj_inv (hf i) (x i)) lemma comp_linear_map_inj (f : Π i, M₁ i →ₗ[R] M₁' i) (hf : ∀ i, surjective (f i)) (g₁ g₂ : multilinear_map R M₁' M₂) : g₁.comp_linear_map f = g₂.comp_linear_map f ↔ g₁ = g₂ := (comp_linear_map_injective _ hf).eq_iff /-- Composing a multilinear map with a linear equiv on each argument gives the zero map if and only if the multilinear map is the zero map. -/ @[simp] lemma comp_linear_equiv_eq_zero_iff (g : multilinear_map R M₁' M₂) (f : Π i, M₁ i ≃ₗ[R] M₁' i) : g.comp_linear_map (λ i, (f i : M₁ i →ₗ[R] M₁' i)) = 0 ↔ g = 0 := begin set f' := (λ i, (f i : M₁ i →ₗ[R] M₁' i)), rw [←zero_comp_linear_map f', comp_linear_map_inj f' (λ i, (f i).surjective)], end end /-- If one adds to a vector `m'` another vector `m`, but only for coordinates in a finset `t`, then the image under a multilinear map `f` is the sum of `f (s.piecewise m m')` along all subsets `s` of `t`. This is mainly an auxiliary statement to prove the result when `t = univ`, given in `map_add_univ`, although it can be useful in its own right as it does not require the index set `ι` to be finite.-/ lemma map_piecewise_add (m m' : Πi, M₁ i) (t : finset ι) : f (t.piecewise (m + m') m') = ∑ s in t.powerset, f (s.piecewise m m') := begin revert m', refine finset.induction_on t (by simp) _, assume i t hit Hrec m', have A : (insert i t).piecewise (m + m') m' = update (t.piecewise (m + m') m') i (m i + m' i) := t.piecewise_insert _ _ _, have B : update (t.piecewise (m + m') m') i (m' i) = t.piecewise (m + m') m', { ext j, by_cases h : j = i, { rw h, simp [hit] }, { simp [h] } }, let m'' := update m' i (m i), have C : update (t.piecewise (m + m') m') i (m i) = t.piecewise (m + m'') m'', { ext j, by_cases h : j = i, { rw h, simp [m'', hit] }, { by_cases h' : j ∈ t; simp [h, hit, m'', h'] } }, rw [A, f.map_add, B, C, finset.sum_powerset_insert hit, Hrec, Hrec, add_comm], congr' 1, apply finset.sum_congr rfl (λs hs, _), have : (insert i s).piecewise m m' = s.piecewise m m'', { ext j, by_cases h : j = i, { rw h, simp [m'', finset.not_mem_of_mem_powerset_of_not_mem hs hit] }, { by_cases h' : j ∈ s; simp [h, m'', h'] } }, rw this end /-- Additivity of a multilinear map along all coordinates at the same time, writing `f (m + m')` as the sum of `f (s.piecewise m m')` over all sets `s`. -/ lemma map_add_univ [fintype ι] (m m' : Πi, M₁ i) : f (m + m') = ∑ s : finset ι, f (s.piecewise m m') := by simpa using f.map_piecewise_add m m' finset.univ section apply_sum variables {α : ι → Type*} (g : Π i, α i → M₁ i) (A : Π i, finset (α i)) open_locale classical open fintype finset /-- If `f` is multilinear, then `f (Σ_{j₁ ∈ A₁} g₁ j₁, ..., Σ_{jₙ ∈ Aₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions with `r 1 ∈ A₁`, ..., `r n ∈ Aₙ`. This follows from multilinearity by expanding successively with respect to each coordinate. Here, we give an auxiliary statement tailored for an inductive proof. Use instead `map_sum_finset`. -/ lemma map_sum_finset_aux [fintype ι] {n : ℕ} (h : ∑ i, (A i).card = n) : f (λ i, ∑ j in A i, g i j) = ∑ r in pi_finset A, f (λ i, g i (r i)) := begin induction n using nat.strong_induction_on with n IH generalizing A, -- If one of the sets is empty, then all the sums are zero by_cases Ai_empty : ∃ i, A i = ∅, { rcases Ai_empty with ⟨i, hi⟩, have : ∑ j in A i, g i j = 0, by rw [hi, finset.sum_empty], rw f.map_coord_zero i this, have : pi_finset A = ∅, { apply finset.eq_empty_of_forall_not_mem (λ r hr, _), have : r i ∈ A i := mem_pi_finset.mp hr i, rwa hi at this }, rw [this, finset.sum_empty] }, push_neg at Ai_empty, -- Otherwise, if all sets are at most singletons, then they are exactly singletons and the result -- is again straightforward by_cases Ai_singleton : ∀ i, (A i).card ≤ 1, { have Ai_card : ∀ i, (A i).card = 1, { assume i, have pos : finset.card (A i) ≠ 0, by simp [finset.card_eq_zero, Ai_empty i], have : finset.card (A i) ≤ 1 := Ai_singleton i, exact le_antisymm this (nat.succ_le_of_lt (_root_.pos_iff_ne_zero.mpr pos)) }, have : ∀ (r : Π i, α i), r ∈ pi_finset A → f (λ i, g i (r i)) = f (λ i, ∑ j in A i, g i j), { assume r hr, unfold_coes, congr' with i, have : ∀ j ∈ A i, g i j = g i (r i), { assume j hj, congr, apply finset.card_le_one_iff.1 (Ai_singleton i) hj, exact mem_pi_finset.mp hr i }, simp only [finset.sum_congr rfl this, finset.mem_univ, finset.sum_const, Ai_card i, one_nsmul] }, simp only [sum_congr rfl this, Ai_card, card_pi_finset, prod_const_one, one_nsmul, finset.sum_const] }, -- Remains the interesting case where one of the `A i`, say `A i₀`, has cardinality at least 2. -- We will split into two parts `B i₀` and `C i₀` of smaller cardinality, let `B i = C i = A i` -- for `i ≠ i₀`, apply the inductive assumption to `B` and `C`, and add up the corresponding -- parts to get the sum for `A`. push_neg at Ai_singleton, obtain ⟨i₀, hi₀⟩ : ∃ i, 1 < (A i).card := Ai_singleton, obtain ⟨j₁, j₂, hj₁, hj₂, j₁_ne_j₂⟩ : ∃ j₁ j₂, (j₁ ∈ A i₀) ∧ (j₂ ∈ A i₀) ∧ j₁ ≠ j₂ := finset.one_lt_card_iff.1 hi₀, let B := function.update A i₀ (A i₀ \ {j₂}), let C := function.update A i₀ {j₂}, have B_subset_A : ∀ i, B i ⊆ A i, { assume i, by_cases hi : i = i₀, { rw hi, simp only [B, sdiff_subset, update_same]}, { simp only [hi, B, update_noteq, ne.def, not_false_iff, finset.subset.refl] } }, have C_subset_A : ∀ i, C i ⊆ A i, { assume i, by_cases hi : i = i₀, { rw hi, simp only [C, hj₂, finset.singleton_subset_iff, update_same] }, { simp only [hi, C, update_noteq, ne.def, not_false_iff, finset.subset.refl] } }, -- split the sum at `i₀` as the sum over `B i₀` plus the sum over `C i₀`, to use additivity. have A_eq_BC : (λ i, ∑ j in A i, g i j) = function.update (λ i, ∑ j in A i, g i j) i₀ (∑ j in B i₀, g i₀ j + ∑ j in C i₀, g i₀ j), { ext i, by_cases hi : i = i₀, { rw [hi], simp only [function.update_same], have : A i₀ = B i₀ ∪ C i₀, { simp only [B, C, function.update_same, finset.sdiff_union_self_eq_union], symmetry, simp only [hj₂, finset.singleton_subset_iff, finset.union_eq_left_iff_subset] }, rw this, apply finset.sum_union, apply finset.disjoint_right.2 (λ j hj, _), have : j = j₂, by { dsimp [C] at hj, simpa using hj }, rw this, dsimp [B], simp only [mem_sdiff, eq_self_iff_true, not_true, not_false_iff, finset.mem_singleton, update_same, and_false] }, { simp [hi] } }, have Beq : function.update (λ i, ∑ j in A i, g i j) i₀ (∑ j in B i₀, g i₀ j) = (λ i, ∑ j in B i, g i j), { ext i, by_cases hi : i = i₀, { rw hi, simp only [update_same] }, { simp only [hi, B, update_noteq, ne.def, not_false_iff] } }, have Ceq : function.update (λ i, ∑ j in A i, g i j) i₀ (∑ j in C i₀, g i₀ j) = (λ i, ∑ j in C i, g i j), { ext i, by_cases hi : i = i₀, { rw hi, simp only [update_same] }, { simp only [hi, C, update_noteq, ne.def, not_false_iff] } }, -- Express the inductive assumption for `B` have Brec : f (λ i, ∑ j in B i, g i j) = ∑ r in pi_finset B, f (λ i, g i (r i)), { have : ∑ i, finset.card (B i) < ∑ i, finset.card (A i), { refine finset.sum_lt_sum (λ i hi, finset.card_le_of_subset (B_subset_A i)) ⟨i₀, finset.mem_univ _, _⟩, have : {j₂} ⊆ A i₀, by simp [hj₂], simp only [B, finset.card_sdiff this, function.update_same, finset.card_singleton], exact nat.pred_lt (ne_of_gt (lt_trans nat.zero_lt_one hi₀)) }, rw h at this, exact IH _ this B rfl }, -- Express the inductive assumption for `C` have Crec : f (λ i, ∑ j in C i, g i j) = ∑ r in pi_finset C, f (λ i, g i (r i)), { have : ∑ i, finset.card (C i) < ∑ i, finset.card (A i) := finset.sum_lt_sum (λ i hi, finset.card_le_of_subset (C_subset_A i)) ⟨i₀, finset.mem_univ _, by simp [C, hi₀]⟩, rw h at this, exact IH _ this C rfl }, have D : disjoint (pi_finset B) (pi_finset C), { have : disjoint (B i₀) (C i₀), by simp [B, C], exact pi_finset_disjoint_of_disjoint B C this }, have pi_BC : pi_finset A = pi_finset B ∪ pi_finset C, { apply finset.subset.antisymm, { assume r hr, by_cases hri₀ : r i₀ = j₂, { apply finset.mem_union_right, apply mem_pi_finset.2 (λ i, _), by_cases hi : i = i₀, { have : r i₀ ∈ C i₀, by simp [C, hri₀], convert this }, { simp [C, hi, mem_pi_finset.1 hr i] } }, { apply finset.mem_union_left, apply mem_pi_finset.2 (λ i, _), by_cases hi : i = i₀, { have : r i₀ ∈ B i₀, by simp [B, hri₀, mem_pi_finset.1 hr i₀], convert this }, { simp [B, hi, mem_pi_finset.1 hr i] } } }, { exact finset.union_subset (pi_finset_subset _ _ (λ i, B_subset_A i)) (pi_finset_subset _ _ (λ i, C_subset_A i)) } }, rw A_eq_BC, simp only [multilinear_map.map_add, Beq, Ceq, Brec, Crec, pi_BC], rw ← finset.sum_union D, end /-- If `f` is multilinear, then `f (Σ_{j₁ ∈ A₁} g₁ j₁, ..., Σ_{jₙ ∈ Aₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions with `r 1 ∈ A₁`, ..., `r n ∈ Aₙ`. This follows from multilinearity by expanding successively with respect to each coordinate. -/ lemma map_sum_finset [fintype ι] : f (λ i, ∑ j in A i, g i j) = ∑ r in pi_finset A, f (λ i, g i (r i)) := f.map_sum_finset_aux _ _ rfl /-- If `f` is multilinear, then `f (Σ_{j₁} g₁ j₁, ..., Σ_{jₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions `r`. This follows from multilinearity by expanding successively with respect to each coordinate. -/ lemma map_sum [fintype ι] [∀ i, fintype (α i)] : f (λ i, ∑ j, g i j) = ∑ r : Π i, α i, f (λ i, g i (r i)) := f.map_sum_finset g (λ i, finset.univ) lemma map_update_sum {α : Type*} (t : finset α) (i : ι) (g : α → M₁ i) (m : Π i, M₁ i): f (update m i (∑ a in t, g a)) = ∑ a in t, f (update m i (g a)) := begin induction t using finset.induction with a t has ih h, { simp }, { simp [finset.sum_insert has, ih] } end end apply_sum section restrict_scalar variables (R) {A : Type*} [semiring A] [has_scalar R A] [Π (i : ι), module A (M₁ i)] [module A M₂] [∀ i, is_scalar_tower R A (M₁ i)] [is_scalar_tower R A M₂] /-- Reinterpret an `A`-multilinear map as an `R`-multilinear map, if `A` is an algebra over `R` and their actions on all involved modules agree with the action of `R` on `A`. -/ def restrict_scalars (f : multilinear_map A M₁ M₂) : multilinear_map R M₁ M₂ := { to_fun := f, map_add' := f.map_add, map_smul' := λ m i, (f.to_linear_map m i).map_smul_of_tower } @[simp] lemma coe_restrict_scalars (f : multilinear_map A M₁ M₂) : ⇑(f.restrict_scalars R) = f := rfl end restrict_scalar section variables {ι₁ ι₂ ι₃ : Type*} [decidable_eq ι₁] [decidable_eq ι₂] [decidable_eq ι₃] /-- Transfer the arguments to a map along an equivalence between argument indices. The naming is derived from `finsupp.dom_congr`, noting that here the permutation applies to the domain of the domain. -/ @[simps apply] def dom_dom_congr (σ : ι₁ ≃ ι₂) (m : multilinear_map R (λ i : ι₁, M₂) M₃) : multilinear_map R (λ i : ι₂, M₂) M₃ := { to_fun := λ v, m (λ i, v (σ i)), map_add' := λ v i a b, by { simp_rw function.update_apply_equiv_apply v, rw m.map_add, }, map_smul' := λ v i a b, by { simp_rw function.update_apply_equiv_apply v, rw m.map_smul, }, } lemma dom_dom_congr_trans (σ₁ : ι₁ ≃ ι₂) (σ₂ : ι₂ ≃ ι₃) (m : multilinear_map R (λ i : ι₁, M₂) M₃) : m.dom_dom_congr (σ₁.trans σ₂) = (m.dom_dom_congr σ₁).dom_dom_congr σ₂ := rfl lemma dom_dom_congr_mul (σ₁ : equiv.perm ι₁) (σ₂ : equiv.perm ι₁) (m : multilinear_map R (λ i : ι₁, M₂) M₃) : m.dom_dom_congr (σ₂ * σ₁) = (m.dom_dom_congr σ₁).dom_dom_congr σ₂ := rfl /-- `multilinear_map.dom_dom_congr` as an equivalence. This is declared separately because it does not work with dot notation. -/ @[simps apply symm_apply] def dom_dom_congr_equiv (σ : ι₁ ≃ ι₂) : multilinear_map R (λ i : ι₁, M₂) M₃ ≃+ multilinear_map R (λ i : ι₂, M₂) M₃ := { to_fun := dom_dom_congr σ, inv_fun := dom_dom_congr σ.symm, left_inv := λ m, by {ext, simp}, right_inv := λ m, by {ext, simp}, map_add' := λ a b, by {ext, simp} } /-- The results of applying `dom_dom_congr` to two maps are equal if and only if those maps are. -/ @[simp] lemma dom_dom_congr_eq_iff (σ : ι₁ ≃ ι₂) (f g : multilinear_map R (λ i : ι₁, M₂) M₃) : f.dom_dom_congr σ = g.dom_dom_congr σ ↔ f = g := (dom_dom_congr_equiv σ : _ ≃+ multilinear_map R (λ i, M₂) M₃).apply_eq_iff_eq end end semiring end multilinear_map namespace linear_map variables [semiring R] [Πi, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M'] [∀i, module R (M₁ i)] [module R M₂] [module R M₃] [module R M'] /-- Composing a multilinear map with a linear map gives again a multilinear map. -/ def comp_multilinear_map (g : M₂ →ₗ[R] M₃) (f : multilinear_map R M₁ M₂) : multilinear_map R M₁ M₃ := { to_fun := g ∘ f, map_add' := λ m i x y, by simp, map_smul' := λ m i c x, by simp } @[simp] lemma coe_comp_multilinear_map (g : M₂ →ₗ[R] M₃) (f : multilinear_map R M₁ M₂) : ⇑(g.comp_multilinear_map f) = g ∘ f := rfl lemma comp_multilinear_map_apply (g : M₂ →ₗ[R] M₃) (f : multilinear_map R M₁ M₂) (m : Π i, M₁ i) : g.comp_multilinear_map f m = g (f m) := rfl variables {ι₁ ι₂ : Type*} [decidable_eq ι₁] [decidable_eq ι₂] @[simp] lemma comp_multilinear_map_dom_dom_congr (σ : ι₁ ≃ ι₂) (g : M₂ →ₗ[R] M₃) (f : multilinear_map R (λ i : ι₁, M') M₂) : (g.comp_multilinear_map f).dom_dom_congr σ = g.comp_multilinear_map (f.dom_dom_congr σ) := by { ext, simp } end linear_map namespace multilinear_map section comm_semiring variables [comm_semiring R] [∀i, add_comm_monoid (M₁ i)] [∀i, add_comm_monoid (M i)] [add_comm_monoid M₂] [∀i, module R (M i)] [∀i, module R (M₁ i)] [module R M₂] (f f' : multilinear_map R M₁ M₂) /-- If one multiplies by `c i` the coordinates in a finset `s`, then the image under a multilinear map is multiplied by `∏ i in s, c i`. This is mainly an auxiliary statement to prove the result when `s = univ`, given in `map_smul_univ`, although it can be useful in its own right as it does not require the index set `ι` to be finite. -/ lemma map_piecewise_smul (c : ι → R) (m : Πi, M₁ i) (s : finset ι) : f (s.piecewise (λi, c i • m i) m) = (∏ i in s, c i) • f m := begin refine s.induction_on (by simp) _, assume j s j_not_mem_s Hrec, have A : function.update (s.piecewise (λi, c i • m i) m) j (m j) = s.piecewise (λi, c i • m i) m, { ext i, by_cases h : i = j, { rw h, simp [j_not_mem_s] }, { simp [h] } }, rw [s.piecewise_insert, f.map_smul, A, Hrec], simp [j_not_mem_s, mul_smul] end /-- Multiplicativity of a multilinear map along all coordinates at the same time, writing `f (λi, c i • m i)` as `(∏ i, c i) • f m`. -/ lemma map_smul_univ [fintype ι] (c : ι → R) (m : Πi, M₁ i) : f (λi, c i • m i) = (∏ i, c i) • f m := by simpa using map_piecewise_smul f c m finset.univ @[simp] lemma map_update_smul [fintype ι] (m : Πi, M₁ i) (i : ι) (c : R) (x : M₁ i) : f (update (c • m) i x) = c^(fintype.card ι - 1) • f (update m i x) := begin have : f ((finset.univ.erase i).piecewise (c • update m i x) (update m i x)) = (∏ i in finset.univ.erase i, c) • f (update m i x) := map_piecewise_smul f _ _ _, simpa [←function.update_smul c m] using this, end section distrib_mul_action variables {R' A : Type*} [monoid R'] [semiring A] [Π i, module A (M₁ i)] [distrib_mul_action R' M₂] [module A M₂] [smul_comm_class A R' M₂] instance : has_scalar R' (multilinear_map A M₁ M₂) := ⟨λ c f, ⟨λ m, c • f m, λm i x y, by simp [smul_add], λl i x d, by simp [←smul_comm x c] ⟩⟩ @[simp] lemma smul_apply (f : multilinear_map A M₁ M₂) (c : R') (m : Πi, M₁ i) : (c • f) m = c • f m := rfl lemma coe_smul (c : R') (f : multilinear_map A M₁ M₂) : ⇑(c • f) = c • f := rfl instance : distrib_mul_action R' (multilinear_map A M₁ M₂) := { one_smul := λ f, ext $ λ x, one_smul _ _, mul_smul := λ c₁ c₂ f, ext $ λ x, mul_smul _ _ _, smul_zero := λ r, ext $ λ x, smul_zero _, smul_add := λ r f₁ f₂, ext $ λ x, smul_add _ _ _ } end distrib_mul_action section module variables {R' A : Type*} [semiring R'] [semiring A] [Π i, module A (M₁ i)] [module A M₂] [add_comm_monoid M₃] [module R' M₃] [module A M₃] [smul_comm_class A R' M₃] /-- The space of multilinear maps over an algebra over `R` is a module over `R`, for the pointwise addition and scalar multiplication. -/ instance [module R' M₂] [smul_comm_class A R' M₂] : module R' (multilinear_map A M₁ M₂) := { add_smul := λ r₁ r₂ f, ext $ λ x, add_smul _ _ _, zero_smul := λ f, ext $ λ x, zero_smul _ _ } instance [no_zero_smul_divisors R' M₃] : no_zero_smul_divisors R' (multilinear_map A M₁ M₃) := coe_injective.no_zero_smul_divisors _ rfl coe_smul variables (M₂ M₃ R' A) /-- `multilinear_map.dom_dom_congr` as a `linear_equiv`. -/ @[simps apply symm_apply] def dom_dom_congr_linear_equiv {ι₁ ι₂} [decidable_eq ι₁] [decidable_eq ι₂] (σ : ι₁ ≃ ι₂) : multilinear_map A (λ i : ι₁, M₂) M₃ ≃ₗ[R'] multilinear_map A (λ i : ι₂, M₂) M₃ := { map_smul' := λ c f, by { ext, simp }, .. (dom_dom_congr_equiv σ : multilinear_map A (λ i : ι₁, M₂) M₃ ≃+ multilinear_map A (λ i : ι₂, M₂) M₃) } variables (R M₁) /-- The dependent version of `multilinear_map.dom_dom_congr_linear_equiv`. -/ @[simps apply symm_apply] def dom_dom_congr_linear_equiv' {ι' : Type*} [decidable_eq ι'] (σ : ι ≃ ι') : multilinear_map R M₁ M₂ ≃ₗ[R] multilinear_map R (λ i, M₁ (σ.symm i)) M₂ := { to_fun := λ f, { to_fun := f ∘ (σ.Pi_congr_left' M₁).symm, map_add' := λ m i, begin rw ← σ.apply_symm_apply i, intros x y, simp only [comp_app, Pi_congr_left'_symm_update, f.map_add], end, map_smul' := λ m i c, begin rw ← σ.apply_symm_apply i, intros x, simp only [comp_app, Pi_congr_left'_symm_update, f.map_smul], end, }, inv_fun := λ f, { to_fun := f ∘ (σ.Pi_congr_left' M₁), map_add' := λ m i, begin rw ← σ.symm_apply_apply i, intros x y, simp only [comp_app, Pi_congr_left'_update, f.map_add], end, map_smul' := λ m i c, begin rw ← σ.symm_apply_apply i, intros x, simp only [comp_app, Pi_congr_left'_update, f.map_smul], end, }, map_add' := λ f₁ f₂, by { ext, simp only [comp_app, coe_mk, add_apply], }, map_smul' := λ c f, by { ext, simp only [comp_app, coe_mk, smul_apply, ring_hom.id_apply], }, left_inv := λ f, by { ext, simp only [comp_app, coe_mk, equiv.symm_apply_apply], }, right_inv := λ f, by { ext, simp only [comp_app, coe_mk, equiv.apply_symm_apply], }, } /-- The space of constant maps is equivalent to the space of maps that are multilinear with respect to an empty family. -/ @[simps] def const_linear_equiv_of_is_empty [is_empty ι] : M₂ ≃ₗ[R] multilinear_map R M₁ M₂ := { to_fun := multilinear_map.const_of_is_empty R, map_add' := λ x y, rfl, map_smul' := λ t x, rfl, inv_fun := λ f, f 0, left_inv := λ _, rfl, right_inv := λ f, ext $ λ x, multilinear_map.congr_arg f $ subsingleton.elim _ _ } end module section variables (R ι) (A : Type*) [comm_semiring A] [algebra R A] [fintype ι] /-- Given an `R`-algebra `A`, `mk_pi_algebra` is the multilinear map on `A^ι` associating to `m` the product of all the `m i`. See also `multilinear_map.mk_pi_algebra_fin` for a version that works with a non-commutative algebra `A` but requires `ι = fin n`. -/ protected def mk_pi_algebra : multilinear_map R (λ i : ι, A) A := { to_fun := λ m, ∏ i, m i, map_add' := λ m i x y, by simp [finset.prod_update_of_mem, add_mul], map_smul' := λ m i c x, by simp [finset.prod_update_of_mem] } variables {R A ι} @[simp] lemma mk_pi_algebra_apply (m : ι → A) : multilinear_map.mk_pi_algebra R ι A m = ∏ i, m i := rfl end section variables (R n) (A : Type*) [semiring A] [algebra R A] /-- Given an `R`-algebra `A`, `mk_pi_algebra_fin` is the multilinear map on `A^n` associating to `m` the product of all the `m i`. See also `multilinear_map.mk_pi_algebra` for a version that assumes `[comm_semiring A]` but works for `A^ι` with any finite type `ι`. -/ protected def mk_pi_algebra_fin : multilinear_map R (λ i : fin n, A) A := { to_fun := λ m, (list.of_fn m).prod, map_add' := begin intros m i x y, have : (list.fin_range n).index_of i < n, by simpa using list.index_of_lt_length.2 (list.mem_fin_range i), simp [list.of_fn_eq_map, (list.nodup_fin_range n).map_update, list.prod_update_nth, add_mul, this, mul_add, add_mul] end, map_smul' := begin intros m i c x, have : (list.fin_range n).index_of i < n, by simpa using list.index_of_lt_length.2 (list.mem_fin_range i), simp [list.of_fn_eq_map, (list.nodup_fin_range n).map_update, list.prod_update_nth, this] end } variables {R A n} @[simp] lemma mk_pi_algebra_fin_apply (m : fin n → A) : multilinear_map.mk_pi_algebra_fin R n A m = (list.of_fn m).prod := rfl lemma mk_pi_algebra_fin_apply_const (a : A) : multilinear_map.mk_pi_algebra_fin R n A (λ _, a) = a ^ n := by simp end /-- Given an `R`-multilinear map `f` taking values in `R`, `f.smul_right z` is the map sending `m` to `f m • z`. -/ def smul_right (f : multilinear_map R M₁ R) (z : M₂) : multilinear_map R M₁ M₂ := (linear_map.smul_right linear_map.id z).comp_multilinear_map f @[simp] lemma smul_right_apply (f : multilinear_map R M₁ R) (z : M₂) (m : Π i, M₁ i) : f.smul_right z m = f m • z := rfl variables (R ι) /-- The canonical multilinear map on `R^ι` when `ι` is finite, associating to `m` the product of all the `m i` (multiplied by a fixed reference element `z` in the target module). See also `mk_pi_algebra` for a more general version. -/ protected def mk_pi_ring [fintype ι] (z : M₂) : multilinear_map R (λ(i : ι), R) M₂ := (multilinear_map.mk_pi_algebra R ι R).smul_right z variables {R ι} @[simp] lemma mk_pi_ring_apply [fintype ι] (z : M₂) (m : ι → R) : (multilinear_map.mk_pi_ring R ι z : (ι → R) → M₂) m = (∏ i, m i) • z := rfl lemma mk_pi_ring_apply_one_eq_self [fintype ι] (f : multilinear_map R (λ(i : ι), R) M₂) : multilinear_map.mk_pi_ring R ι (f (λi, 1)) = f := begin ext m, have : m = (λi, m i • 1), by { ext j, simp }, conv_rhs { rw [this, f.map_smul_univ] }, refl end end comm_semiring section range_add_comm_group variables [semiring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_group M₂] [∀i, module R (M₁ i)] [module R M₂] (f g : multilinear_map R M₁ M₂) instance : has_neg (multilinear_map R M₁ M₂) := ⟨λ f, ⟨λ m, - f m, λm i x y, by simp [add_comm], λm i c x, by simp⟩⟩ @[simp] lemma neg_apply (m : Πi, M₁ i) : (-f) m = - (f m) := rfl instance : has_sub (multilinear_map R M₁ M₂) := ⟨λ f g, ⟨λ m, f m - g m, λ m i x y, by { simp only [multilinear_map.map_add, sub_eq_add_neg, neg_add], cc }, λ m i c x, by { simp only [map_smul, smul_sub] }⟩⟩ @[simp] lemma sub_apply (m : Πi, M₁ i) : (f - g) m = f m - g m := rfl instance : add_comm_group (multilinear_map R M₁ M₂) := by refine { zero := (0 : multilinear_map R M₁ M₂), add := (+), neg := has_neg.neg, sub := has_sub.sub, sub_eq_add_neg := _, nsmul := λ n f, ⟨λ m, n • f m, λm i x y, by simp [smul_add], λl i x d, by simp [←smul_comm x n] ⟩, zsmul := λ n f, ⟨λ m, n • f m, λm i x y, by simp [smul_add], λl i x d, by simp [←smul_comm x n] ⟩, zsmul_zero' := _, zsmul_succ' := _, zsmul_neg' := _, .. multilinear_map.add_comm_monoid, .. }; intros; ext; simp [add_comm, add_left_comm, sub_eq_add_neg, add_smul, nat.succ_eq_add_one] end range_add_comm_group section add_comm_group variables [semiring R] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂] [∀i, module R (M₁ i)] [module R M₂] (f : multilinear_map R M₁ M₂) @[simp] lemma map_neg (m : Πi, M₁ i) (i : ι) (x : M₁ i) : f (update m i (-x)) = -f (update m i x) := eq_neg_of_add_eq_zero $ by rw [←multilinear_map.map_add, add_left_neg, f.map_coord_zero i (update_same i 0 m)] @[simp] lemma map_sub (m : Πi, M₁ i) (i : ι) (x y : M₁ i) : f (update m i (x - y)) = f (update m i x) - f (update m i y) := by rw [sub_eq_add_neg, sub_eq_add_neg, multilinear_map.map_add, map_neg] end add_comm_group section comm_semiring variables [comm_semiring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [∀i, module R (M₁ i)] [module R M₂] /-- When `ι` is finite, multilinear maps on `R^ι` with values in `M₂` are in bijection with `M₂`, as such a multilinear map is completely determined by its value on the constant vector made of ones. We register this bijection as a linear equivalence in `multilinear_map.pi_ring_equiv`. -/ protected def pi_ring_equiv [fintype ι] : M₂ ≃ₗ[R] (multilinear_map R (λ(i : ι), R) M₂) := { to_fun := λ z, multilinear_map.mk_pi_ring R ι z, inv_fun := λ f, f (λi, 1), map_add' := λ z z', by { ext m, simp [smul_add] }, map_smul' := λ c z, by { ext m, simp [smul_smul, mul_comm] }, left_inv := λ z, by simp, right_inv := λ f, f.mk_pi_ring_apply_one_eq_self } end comm_semiring end multilinear_map section currying /-! ### Currying We associate to a multilinear map in `n+1` variables (i.e., based on `fin n.succ`) two curried functions, named `f.curry_left` (which is a linear map on `E 0` taking values in multilinear maps in `n` variables) and `f.curry_right` (wich is a multilinear map in `n` variables taking values in linear maps on `E 0`). In both constructions, the variable that is singled out is `0`, to take advantage of the operations `cons` and `tail` on `fin n`. The inverse operations are called `uncurry_left` and `uncurry_right`. We also register linear equiv versions of these correspondences, in `multilinear_curry_left_equiv` and `multilinear_curry_right_equiv`. -/ open multilinear_map variables {R M M₂} [comm_semiring R] [∀i, add_comm_monoid (M i)] [add_comm_monoid M'] [add_comm_monoid M₂] [∀i, module R (M i)] [module R M'] [module R M₂] /-! #### Left currying -/ /-- Given a linear map `f` from `M 0` to multilinear maps on `n` variables, construct the corresponding multilinear map on `n+1` variables obtained by concatenating the variables, given by `m ↦ f (m 0) (tail m)`-/ def linear_map.uncurry_left (f : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) : multilinear_map R M M₂ := { to_fun := λm, f (m 0) (tail m), map_add' := λm i x y, begin by_cases h : i = 0, { subst i, rw [update_same, update_same, update_same, f.map_add, add_apply, tail_update_zero, tail_update_zero, tail_update_zero] }, { rw [update_noteq (ne.symm h), update_noteq (ne.symm h), update_noteq (ne.symm h)], revert x y, rw ← succ_pred i h, assume x y, rw [tail_update_succ, multilinear_map.map_add, tail_update_succ, tail_update_succ] } end, map_smul' := λm i c x, begin by_cases h : i = 0, { subst i, rw [update_same, update_same, tail_update_zero, tail_update_zero, ← smul_apply, f.map_smul] }, { rw [update_noteq (ne.symm h), update_noteq (ne.symm h)], revert x, rw ← succ_pred i h, assume x, rw [tail_update_succ, tail_update_succ, map_smul] } end } @[simp] lemma linear_map.uncurry_left_apply (f : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) (m : Πi, M i) : f.uncurry_left m = f (m 0) (tail m) := rfl /-- Given a multilinear map `f` in `n+1` variables, split the first variable to obtain a linear map into multilinear maps in `n` variables, given by `x ↦ (m ↦ f (cons x m))`. -/ def multilinear_map.curry_left (f : multilinear_map R M M₂) : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂) := { to_fun := λx, { to_fun := λm, f (cons x m), map_add' := λm i y y', by simp, map_smul' := λm i y c, by simp }, map_add' := λx y, by { ext m, exact cons_add f m x y }, map_smul' := λc x, by { ext m, exact cons_smul f m c x } } @[simp] lemma multilinear_map.curry_left_apply (f : multilinear_map R M M₂) (x : M 0) (m : Π(i : fin n), M i.succ) : f.curry_left x m = f (cons x m) := rfl @[simp] lemma linear_map.curry_uncurry_left (f : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) : f.uncurry_left.curry_left = f := begin ext m x, simp only [tail_cons, linear_map.uncurry_left_apply, multilinear_map.curry_left_apply], rw cons_zero end @[simp] lemma multilinear_map.uncurry_curry_left (f : multilinear_map R M M₂) : f.curry_left.uncurry_left = f := by { ext m, simp, } variables (R M M₂) /-- The space of multilinear maps on `Π(i : fin (n+1)), M i` is canonically isomorphic to the space of linear maps from `M 0` to the space of multilinear maps on `Π(i : fin n), M i.succ `, by separating the first variable. We register this isomorphism as a linear isomorphism in `multilinear_curry_left_equiv R M M₂`. The direct and inverse maps are given by `f.uncurry_left` and `f.curry_left`. Use these unless you need the full framework of linear equivs. -/ def multilinear_curry_left_equiv : (M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) ≃ₗ[R] (multilinear_map R M M₂) := { to_fun := linear_map.uncurry_left, map_add' := λf₁ f₂, by { ext m, refl }, map_smul' := λc f, by { ext m, refl }, inv_fun := multilinear_map.curry_left, left_inv := linear_map.curry_uncurry_left, right_inv := multilinear_map.uncurry_curry_left } variables {R M M₂} /-! #### Right currying -/ /-- Given a multilinear map `f` in `n` variables to the space of linear maps from `M (last n)` to `M₂`, construct the corresponding multilinear map on `n+1` variables obtained by concatenating the variables, given by `m ↦ f (init m) (m (last n))`-/ def multilinear_map.uncurry_right (f : (multilinear_map R (λ(i : fin n), M i.cast_succ) (M (last n) →ₗ[R] M₂))) : multilinear_map R M M₂ := { to_fun := λm, f (init m) (m (last n)), map_add' := λm i x y, begin by_cases h : i.val < n, { have : last n ≠ i := ne.symm (ne_of_lt h), rw [update_noteq this, update_noteq this, update_noteq this], revert x y, rw [(cast_succ_cast_lt i h).symm], assume x y, rw [init_update_cast_succ, multilinear_map.map_add, init_update_cast_succ, init_update_cast_succ, linear_map.add_apply] }, { revert x y, rw eq_last_of_not_lt h, assume x y, rw [init_update_last, init_update_last, init_update_last, update_same, update_same, update_same, linear_map.map_add] } end, map_smul' := λm i c x, begin by_cases h : i.val < n, { have : last n ≠ i := ne.symm (ne_of_lt h), rw [update_noteq this, update_noteq this], revert x, rw [(cast_succ_cast_lt i h).symm], assume x, rw [init_update_cast_succ, init_update_cast_succ, map_smul, linear_map.smul_apply] }, { revert x, rw eq_last_of_not_lt h, assume x, rw [update_same, update_same, init_update_last, init_update_last, linear_map.map_smul] } end } @[simp] lemma multilinear_map.uncurry_right_apply (f : (multilinear_map R (λ(i : fin n), M i.cast_succ) ((M (last n)) →ₗ[R] M₂))) (m : Πi, M i) : f.uncurry_right m = f (init m) (m (last n)) := rfl /-- Given a multilinear map `f` in `n+1` variables, split the last variable to obtain a multilinear map in `n` variables taking values in linear maps from `M (last n)` to `M₂`, given by `m ↦ (x ↦ f (snoc m x))`. -/ def multilinear_map.curry_right (f : multilinear_map R M M₂) : multilinear_map R (λ(i : fin n), M (fin.cast_succ i)) ((M (last n)) →ₗ[R] M₂) := { to_fun := λm, { to_fun := λx, f (snoc m x), map_add' := λx y, by rw f.snoc_add, map_smul' := λc x, by simp only [f.snoc_smul, ring_hom.id_apply] }, map_add' := λm i x y, begin ext z, change f (snoc (update m i (x + y)) z) = f (snoc (update m i x) z) + f (snoc (update m i y) z), rw [snoc_update, snoc_update, snoc_update, f.map_add] end, map_smul' := λm i c x, begin ext z, change f (snoc (update m i (c • x)) z) = c • f (snoc (update m i x) z), rw [snoc_update, snoc_update, f.map_smul] end } @[simp] lemma multilinear_map.curry_right_apply (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.cast_succ) (x : M (last n)) : f.curry_right m x = f (snoc m x) := rfl @[simp] lemma multilinear_map.curry_uncurry_right (f : (multilinear_map R (λ(i : fin n), M i.cast_succ) ((M (last n)) →ₗ[R] M₂))) : f.uncurry_right.curry_right = f := begin ext m x, simp only [snoc_last, multilinear_map.curry_right_apply, multilinear_map.uncurry_right_apply], rw init_snoc end @[simp] lemma multilinear_map.uncurry_curry_right (f : multilinear_map R M M₂) : f.curry_right.uncurry_right = f := by { ext m, simp } variables (R M M₂) /-- The space of multilinear maps on `Π(i : fin (n+1)), M i` is canonically isomorphic to the space of linear maps from the space of multilinear maps on `Π(i : fin n), M i.cast_succ` to the space of linear maps on `M (last n)`, by separating the last variable. We register this isomorphism as a linear isomorphism in `multilinear_curry_right_equiv R M M₂`. The direct and inverse maps are given by `f.uncurry_right` and `f.curry_right`. Use these unless you need the full framework of linear equivs. -/ def multilinear_curry_right_equiv : (multilinear_map R (λ(i : fin n), M i.cast_succ) ((M (last n)) →ₗ[R] M₂)) ≃ₗ[R] (multilinear_map R M M₂) := { to_fun := multilinear_map.uncurry_right, map_add' := λf₁ f₂, by { ext m, refl }, map_smul' := λc f, by { ext m, rw [smul_apply], refl }, inv_fun := multilinear_map.curry_right, left_inv := multilinear_map.curry_uncurry_right, right_inv := multilinear_map.uncurry_curry_right } namespace multilinear_map variables {ι' : Type*} [decidable_eq ι'] [decidable_eq (ι ⊕ ι')] {R M₂} /-- A multilinear map on `Π i : ι ⊕ ι', M'` defines a multilinear map on `Π i : ι, M'` taking values in the space of multilinear maps on `Π i : ι', M'`. -/ def curry_sum (f : multilinear_map R (λ x : ι ⊕ ι', M') M₂) : multilinear_map R (λ x : ι, M') (multilinear_map R (λ x : ι', M') M₂) := { to_fun := λ u, { to_fun := λ v, f (sum.elim u v), map_add' := λ v i x y, by simp only [← sum.update_elim_inr, f.map_add], map_smul' := λ v i c x, by simp only [← sum.update_elim_inr, f.map_smul] }, map_add' := λ u i x y, ext $ λ v, by simp only [multilinear_map.coe_mk, add_apply, ← sum.update_elim_inl, f.map_add], map_smul' := λ u i c x, ext $ λ v, by simp only [multilinear_map.coe_mk, smul_apply, ← sum.update_elim_inl, f.map_smul] } @[simp] lemma curry_sum_apply (f : multilinear_map R (λ x : ι ⊕ ι', M') M₂) (u : ι → M') (v : ι' → M') : f.curry_sum u v = f (sum.elim u v) := rfl /-- A multilinear map on `Π i : ι, M'` taking values in the space of multilinear maps on `Π i : ι', M'` defines a multilinear map on `Π i : ι ⊕ ι', M'`. -/ def uncurry_sum (f : multilinear_map R (λ x : ι, M') (multilinear_map R (λ x : ι', M') M₂)) : multilinear_map R (λ x : ι ⊕ ι', M') M₂ := { to_fun := λ u, f (u ∘ sum.inl) (u ∘ sum.inr), map_add' := λ u i x y, by cases i; simp only [multilinear_map.map_add, add_apply, sum.update_inl_comp_inl, sum.update_inl_comp_inr, sum.update_inr_comp_inl, sum.update_inr_comp_inr], map_smul' := λ u i c x, by cases i; simp only [map_smul, smul_apply, sum.update_inl_comp_inl, sum.update_inl_comp_inr, sum.update_inr_comp_inl, sum.update_inr_comp_inr] } @[simp] lemma uncurry_sum_aux_apply (f : multilinear_map R (λ x : ι, M') (multilinear_map R (λ x : ι', M') M₂)) (u : ι ⊕ ι' → M') : f.uncurry_sum u = f (u ∘ sum.inl) (u ∘ sum.inr) := rfl variables (ι ι' R M₂ M') /-- Linear equivalence between the space of multilinear maps on `Π i : ι ⊕ ι', M'` and the space of multilinear maps on `Π i : ι, M'` taking values in the space of multilinear maps on `Π i : ι', M'`. -/ def curry_sum_equiv : multilinear_map R (λ x : ι ⊕ ι', M') M₂ ≃ₗ[R] multilinear_map R (λ x : ι, M') (multilinear_map R (λ x : ι', M') M₂) := { to_fun := curry_sum, inv_fun := uncurry_sum, left_inv := λ f, ext $ λ u, by simp, right_inv := λ f, by { ext, simp }, map_add' := λ f g, by { ext, refl }, map_smul' := λ c f, by { ext, refl } } variables {ι ι' R M₂ M'} @[simp] lemma coe_curry_sum_equiv : ⇑(curry_sum_equiv R ι M₂ M' ι') = curry_sum := rfl @[simp] lemma coe_curr_sum_equiv_symm : ⇑(curry_sum_equiv R ι M₂ M' ι').symm = uncurry_sum := rfl variables (R M₂ M') /-- If `s : finset (fin n)` is a finite set of cardinality `k` and its complement has cardinality `l`, then the space of multilinear maps on `λ i : fin n, M'` is isomorphic to the space of multilinear maps on `λ i : fin k, M'` taking values in the space of multilinear maps on `λ i : fin l, M'`. -/ def curry_fin_finset {k l n : ℕ} {s : finset (fin n)} (hk : s.card = k) (hl : sᶜ.card = l) : multilinear_map R (λ x : fin n, M') M₂ ≃ₗ[R] multilinear_map R (λ x : fin k, M') (multilinear_map R (λ x : fin l, M') M₂) := (dom_dom_congr_linear_equiv M' M₂ R R (fin_sum_equiv_of_finset hk hl).symm).trans (curry_sum_equiv R (fin k) M₂ M' (fin l)) variables {R M₂ M'} @[simp] lemma curry_fin_finset_apply {k l n : ℕ} {s : finset (fin n)} (hk : s.card = k) (hl : sᶜ.card = l) (f : multilinear_map R (λ x : fin n, M') M₂) (mk : fin k → M') (ml : fin l → M') : curry_fin_finset R M₂ M' hk hl f mk ml = f (λ i, sum.elim mk ml ((fin_sum_equiv_of_finset hk hl).symm i)) := rfl @[simp] lemma curry_fin_finset_symm_apply {k l n : ℕ} {s : finset (fin n)} (hk : s.card = k) (hl : sᶜ.card = l) (f : multilinear_map R (λ x : fin k, M') (multilinear_map R (λ x : fin l, M') M₂)) (m : fin n → M') : (curry_fin_finset R M₂ M' hk hl).symm f m = f (λ i, m $ fin_sum_equiv_of_finset hk hl (sum.inl i)) (λ i, m $ fin_sum_equiv_of_finset hk hl (sum.inr i)) := rfl @[simp] lemma curry_fin_finset_symm_apply_piecewise_const {k l n : ℕ} {s : finset (fin n)} (hk : s.card = k) (hl : sᶜ.card = l) (f : multilinear_map R (λ x : fin k, M') (multilinear_map R (λ x : fin l, M') M₂)) (x y : M') : (curry_fin_finset R M₂ M' hk hl).symm f (s.piecewise (λ _, x) (λ _, y)) = f (λ _, x) (λ _, y) := begin rw curry_fin_finset_symm_apply, congr, { ext i, rw [fin_sum_equiv_of_finset_inl, finset.piecewise_eq_of_mem], apply finset.order_emb_of_fin_mem }, { ext i, rw [fin_sum_equiv_of_finset_inr, finset.piecewise_eq_of_not_mem], exact finset.mem_compl.1 (finset.order_emb_of_fin_mem _ _ _) } end @[simp] lemma curry_fin_finset_symm_apply_const {k l n : ℕ} {s : finset (fin n)} (hk : s.card = k) (hl : sᶜ.card = l) (f : multilinear_map R (λ x : fin k, M') (multilinear_map R (λ x : fin l, M') M₂)) (x : M') : (curry_fin_finset R M₂ M' hk hl).symm f (λ _, x) = f (λ _, x) (λ _, x) := rfl @[simp] lemma curry_fin_finset_apply_const {k l n : ℕ} {s : finset (fin n)} (hk : s.card = k) (hl : sᶜ.card = l) (f : multilinear_map R (λ x : fin n, M') M₂) (x y : M') : curry_fin_finset R M₂ M' hk hl f (λ _, x) (λ _, y) = f (s.piecewise (λ _, x) (λ _, y)) := begin refine (curry_fin_finset_symm_apply_piecewise_const hk hl _ _ _).symm.trans _, -- `rw` fails rw linear_equiv.symm_apply_apply end end multilinear_map end currying namespace multilinear_map section submodule variables {R M M₂} [ring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M'] [add_comm_monoid M₂] [∀i, module R (M₁ i)] [module R M'] [module R M₂] /-- The pushforward of an indexed collection of submodule `p i ⊆ M₁ i` by `f : M₁ → M₂`. Note that this is not a submodule - it is not closed under addition. -/ def map [nonempty ι] (f : multilinear_map R M₁ M₂) (p : Π i, submodule R (M₁ i)) : sub_mul_action R M₂ := { carrier := f '' { v | ∀ i, v i ∈ p i}, smul_mem' := λ c _ ⟨x, hx, hf⟩, let ⟨i⟩ := ‹nonempty ι› in by { refine ⟨update x i (c • x i), λ j, if hij : j = i then _ else _, hf ▸ _⟩, { rw [hij, update_same], exact (p i).smul_mem _ (hx i) }, { rw [update_noteq hij], exact hx j }, { rw [f.map_smul, update_eq_self] } } } /-- The map is always nonempty. This lemma is needed to apply `sub_mul_action.zero_mem`. -/ lemma map_nonempty [nonempty ι] (f : multilinear_map R M₁ M₂) (p : Π i, submodule R (M₁ i)) : (map f p : set M₂).nonempty := ⟨f 0, 0, λ i, (p i).zero_mem, rfl⟩ /-- The range of a multilinear map, closed under scalar multiplication. -/ def range [nonempty ι] (f : multilinear_map R M₁ M₂) : sub_mul_action R M₂ := f.map (λ i, ⊤) end submodule section finite_dimensional variables [fintype ι] [field R] [add_comm_group M₂] [module R M₂] [finite_dimensional R M₂] variables [∀ i, add_comm_group (M₁ i)] [∀ i, module R (M₁ i)] [∀ i, finite_dimensional R (M₁ i)] instance : finite_dimensional R (multilinear_map R M₁ M₂) := begin suffices : ∀ n (N : fin n → Type*) [∀ i, add_comm_group (N i)], by exactI ∀ [∀ i, module R (N i)], by exactI ∀ [∀ i, finite_dimensional R (N i)], finite_dimensional R (multilinear_map R N M₂), { haveI := this _ (M₁ ∘ (fintype.equiv_fin ι).symm), have e := dom_dom_congr_linear_equiv' R M₁ M₂ (fintype.equiv_fin ι), exact e.symm.finite_dimensional, }, intros, induction n with n ih, { exactI (const_linear_equiv_of_is_empty R N M₂ : _).finite_dimensional, }, { resetI, suffices : finite_dimensional R (N 0 →ₗ[R] multilinear_map R (λ (i : fin n), N i.succ) M₂), { exact (multilinear_curry_left_equiv R N M₂).finite_dimensional, }, apply linear_map.finite_dimensional, }, end end finite_dimensional end multilinear_map
3bb5461c3df71310c8332f0781d066c4f0b08559
130c49f47783503e462c16b2eff31933442be6ff
/stage0/src/Lean/PrettyPrinter/Delaborator/Options.lean
1665094581ee24494bcdc617a3e8d3158140f170
[ "Apache-2.0" ]
permissive
Hazel-Brown/lean4
8aa5860e282435ffc30dcdfccd34006c59d1d39c
79e6732fc6bbf5af831b76f310f9c488d44e7a16
refs/heads/master
1,689,218,208,951
1,629,736,869,000
1,629,736,896,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,781
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ import Lean.Data.Options namespace Lean register_builtin_option pp.all : Bool := { defValue := false group := "pp" descr := "(pretty printer) display coercions, implicit parameters, proof terms, fully qualified names, universe, " ++ "and disable beta reduction and notations during pretty printing" } register_builtin_option pp.notation : Bool := { defValue := true group := "pp" descr := "(pretty printer) disable/enable notation (infix, mixfix, postfix operators and unicode characters)" } register_builtin_option pp.coercions : Bool := { defValue := true group := "pp" descr := "(pretty printer) hide coercion applications" } register_builtin_option pp.universes : Bool := { defValue := false group := "pp" descr := "(pretty printer) display universe" } register_builtin_option pp.fullNames : Bool := { defValue := false group := "pp" descr := "(pretty printer) display fully qualified names" } register_builtin_option pp.privateNames : Bool := { defValue := false group := "pp" descr := "(pretty printer) display internal names assigned to private declarations" } register_builtin_option pp.funBinderTypes : Bool := { defValue := false group := "pp" descr := "(pretty printer) display types of lambda parameters" } register_builtin_option pp.piBinderTypes : Bool := { defValue := true group := "pp" descr := "(pretty printer) display types of pi parameters" } register_builtin_option pp.letVarTypes : Bool := { defValue := false group := "pp" descr := "(pretty printer) display types of let-bound variables" } register_builtin_option pp.instantiateMVars : Bool := { defValue := false -- TODO: default to true? group := "pp" descr := "(pretty printer) instantiate mvars before delaborating" } register_builtin_option pp.structureInstances : Bool := { defValue := true group := "pp" -- TODO: implement second part descr := "(pretty printer) display structure instances using the '{ fieldName := fieldValue, ... }' notation " ++ "or '⟨fieldValue, ... ⟩' if structure is tagged with [pp_using_anonymous_constructor] attribute" } register_builtin_option pp.structureProjections : Bool := { defValue := true group := "pp" descr := "(pretty printer) display structure projections using field notation" } register_builtin_option pp.explicit : Bool := { defValue := false group := "pp" descr := "(pretty printer) display implicit arguments" } register_builtin_option pp.structureInstanceTypes : Bool := { defValue := false group := "pp" descr := "(pretty printer) display type of structure instances" } register_builtin_option pp.safeShadowing : Bool := { defValue := true group := "pp" descr := "(pretty printer) allow variable shadowing if there is no collision" } register_builtin_option pp.proofs : Bool := { defValue := false group := "pp" descr := "(pretty printer) if set to false, replace proofs appearing as an argument to a function with a placeholder" } register_builtin_option pp.proofs.withType : Bool := { defValue := true group := "pp" descr := "(pretty printer) when eliding a proof (see `pp.proofs`), show its type instead" } register_builtin_option pp.instances : Bool := { defValue := true group := "pp" descr := "(pretty printer) if set to false, replace inst-implicit arguments to explicit applications with placeholders" } register_builtin_option pp.instanceTypes : Bool := { defValue := false group := "pp" descr := "(pretty printer) when printing explicit applications, show the types of inst-implicit arguments" } register_builtin_option pp.motives.pi : Bool := { defValue := true group := "pp" descr := "(pretty printer) print all motives that return pi types" } register_builtin_option pp.motives.nonConst : Bool := { defValue := false group := "pp" descr := "(pretty printer) print all motives that are not constant functions" } register_builtin_option pp.motives.all : Bool := { defValue := false group := "pp" descr := "(pretty printer) print all motives" } -- TODO: /- register_builtin_option g_pp_max_depth : Nat := { defValue := false group := "pp" descr := "(pretty printer) maximum expression depth, after that it will use ellipsis" } register_builtin_option g_pp_max_steps : Nat := { defValue := false group := "pp" descr := "(pretty printer) maximum number of visited expressions, after that it will use ellipsis" } register_builtin_option g_pp_locals_full_names : Bool := { defValue := false group := "pp" descr := "(pretty printer) show full names of locals" } register_builtin_option g_pp_beta : Bool := { defValue := false group := "pp" descr := "(pretty printer) apply beta-reduction when pretty printing" } register_builtin_option g_pp_goal_compact : Bool := { defValue := false group := "pp" descr := "(pretty printer) try to display goal in a single line when possible" } register_builtin_option g_pp_goal_max_hyps : Nat := { defValue := false group := "pp" descr := "(pretty printer) maximum number of hypotheses to be displayed" } register_builtin_option g_pp_annotations : Bool := { defValue := false group := "pp" descr := "(pretty printer) display internal annotations (for debugging purposes only)" } register_builtin_option g_pp_compact_let : Bool := { defValue := false group := "pp" descr := "(pretty printer) minimal indentation at `let`-declarations" } -/ def getPPAll (o : Options) : Bool := o.get pp.all.name false def getPPFunBinderTypes (o : Options) : Bool := o.get pp.funBinderTypes.name (getPPAll o) def getPPPiBinderTypes (o : Options) : Bool := o.get pp.piBinderTypes.name pp.piBinderTypes.defValue def getPPLetVarTypes (o : Options) : Bool := o.get pp.letVarTypes.name (getPPAll o) def getPPCoercions (o : Options) : Bool := o.get pp.coercions.name (!getPPAll o) def getPPExplicit (o : Options) : Bool := o.get pp.explicit.name (getPPAll o) def getPPNotation (o : Options) : Bool := o.get pp.notation.name (!getPPAll o) def getPPStructureProjections (o : Options) : Bool := o.get pp.structureProjections.name (!getPPAll o) def getPPStructureInstances (o : Options) : Bool := o.get pp.structureInstances.name (!getPPAll o) def getPPStructureInstanceType (o : Options) : Bool := o.get pp.structureInstanceTypes.name (getPPAll o) def getPPUniverses (o : Options) : Bool := o.get pp.universes.name (getPPAll o) def getPPFullNames (o : Options) : Bool := o.get pp.fullNames.name (getPPAll o) def getPPPrivateNames (o : Options) : Bool := o.get pp.privateNames.name (getPPAll o) def getPPInstantiateMVars (o : Options) : Bool := o.get pp.instantiateMVars.name pp.instantiateMVars.defValue def getPPSafeShadowing (o : Options) : Bool := o.get pp.safeShadowing.name pp.safeShadowing.defValue def getPPProofs (o : Options) : Bool := o.get pp.proofs.name (getPPAll o) def getPPProofsWithType (o : Options) : Bool := o.get pp.proofs.withType.name pp.proofs.withType.defValue def getPPMotivesPi (o : Options) : Bool := o.get pp.motives.pi.name pp.motives.pi.defValue def getPPMotivesNonConst (o : Options) : Bool := o.get pp.motives.nonConst.name pp.motives.nonConst.defValue def getPPMotivesAll (o : Options) : Bool := o.get pp.motives.all.name pp.motives.all.defValue def getPPInstances (o : Options) : Bool := o.get pp.instances.name pp.instances.defValue def getPPInstanceTypes (o : Options) : Bool := o.get pp.instanceTypes.name pp.instanceTypes.defValue end Lean
c2cb668eac3b42d523686fea449ad7a462d70fd3
c777c32c8e484e195053731103c5e52af26a25d1
/src/number_theory/sum_four_squares.lean
c8aee31197186b7b77d0401563eceaa0b693058f
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
12,024
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import algebra.group_power.identities import data.zmod.basic import field_theory.finite.basic import data.int.parity import data.fintype.big_operators /-! # Lagrange's four square theorem The main result in this file is `sum_four_squares`, a proof that every natural number is the sum of four square numbers. ## Implementation Notes The proof used is close to Lagrange's original proof. -/ open finset polynomial finite_field equiv open_locale big_operators namespace int lemma sq_add_sq_of_two_mul_sq_add_sq {m x y : ℤ} (h : 2 * m = x^2 + y^2) : m = ((x - y) / 2) ^ 2 + ((x + y) / 2) ^ 2 := have even (x^2 + y^2), by simp [←h, even_mul], have hxaddy : even (x + y), by simpa [sq] with parity_simps, have hxsuby : even (x - y), by simpa [sq] with parity_simps, (mul_right_inj' (show (2*2 : ℤ) ≠ 0, from dec_trivial)).1 $ calc 2 * 2 * m = (x - y)^2 + (x + y)^2 : by rw [mul_assoc, h]; ring ... = (2 * ((x - y) / 2))^2 + (2 * ((x + y) / 2))^2 : by { rw even_iff_two_dvd at hxsuby hxaddy, rw [int.mul_div_cancel' hxsuby, int.mul_div_cancel' hxaddy] } ... = 2 * 2 * (((x - y) / 2) ^ 2 + ((x + y) / 2) ^ 2) : by simp [mul_add, pow_succ, mul_comm, mul_assoc, mul_left_comm] lemma exists_sq_add_sq_add_one_eq_k (p : ℕ) [hp : fact p.prime] : ∃ (a b : ℤ) (k : ℕ), a^2 + b^2 + 1 = k * p ∧ k < p := hp.1.eq_two_or_odd.elim (λ hp2, hp2.symm ▸ ⟨1, 0, 1, rfl, dec_trivial⟩) $ λ hp1, let ⟨a, b, hab⟩ := zmod.sq_add_sq p (-1) in have hab' : (p : ℤ) ∣ a.val_min_abs ^ 2 + b.val_min_abs ^ 2 + 1, from (char_p.int_cast_eq_zero_iff (zmod p) p _).1 $ by simpa [eq_neg_iff_add_eq_zero] using hab, let ⟨k, hk⟩ := hab' in have hk0 : 0 ≤ k, from nonneg_of_mul_nonneg_right (by rw ← hk; exact (add_nonneg (add_nonneg (sq_nonneg _) (sq_nonneg _)) zero_le_one)) (int.coe_nat_pos.2 hp.1.pos), ⟨a.val_min_abs, b.val_min_abs, k.nat_abs, by rw [hk, int.nat_abs_of_nonneg hk0, mul_comm], lt_of_mul_lt_mul_left (calc p * k.nat_abs = a.val_min_abs.nat_abs ^ 2 + b.val_min_abs.nat_abs ^ 2 + 1 : by rw [← int.coe_nat_inj', int.coe_nat_add, int.coe_nat_add, int.coe_nat_pow, int.coe_nat_pow, int.nat_abs_sq, int.nat_abs_sq, int.coe_nat_one, hk, int.coe_nat_mul, int.nat_abs_of_nonneg hk0] ... ≤ (p / 2) ^ 2 + (p / 2)^2 + 1 : add_le_add (add_le_add (nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _) (nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _)) le_rfl ... < (p / 2) ^ 2 + (p / 2)^ 2 + (p % 2)^2 + ((2 * (p / 2)^2 + (4 * (p / 2) * (p % 2)))) : by rw [hp1, one_pow, mul_one]; exact (lt_add_iff_pos_right _).2 (add_pos_of_nonneg_of_pos (nat.zero_le _) (mul_pos dec_trivial (nat.div_pos hp.1.two_le dec_trivial))) ... = p * p : by { conv_rhs { rw [← nat.mod_add_div p 2] }, ring }) (show 0 ≤ p, from nat.zero_le _)⟩ end int namespace nat open int open_locale classical private lemma sum_four_squares_of_two_mul_sum_four_squares {m a b c d : ℤ} (h : a^2 + b^2 + c^2 + d^2 = 2 * m) : ∃ w x y z : ℤ, w^2 + x^2 + y^2 + z^2 = m := have ∀ f : fin 4 → zmod 2, (f 0)^2 + (f 1)^2 + (f 2)^2 + (f 3)^2 = 0 → ∃ i : (fin 4), (f i)^2 + f (swap i 0 1)^2 = 0 ∧ f (swap i 0 2)^2 + f (swap i 0 3)^2 = 0, from dec_trivial, let f : fin 4 → ℤ := vector.nth (a ::ᵥ b ::ᵥ c ::ᵥ d ::ᵥ vector.nil) in let ⟨i, hσ⟩ := this (λ x, coe (f x)) (by rw [← @zero_mul (zmod 2) _ m, ← show ((2 : ℤ) : zmod 2) = 0, from rfl, ← int.cast_mul, ← h]; simp only [int.cast_add, int.cast_pow]; refl) in let σ := swap i 0 in have h01 : 2 ∣ f (σ 0) ^ 2 + f (σ 1) ^ 2, from (char_p.int_cast_eq_zero_iff (zmod 2) 2 _).1 $ by simpa only [int.cast_pow, int.cast_add, equiv.swap_apply_right, zmod.pow_card] using hσ.1, have h23 : 2 ∣ f (σ 2) ^ 2 + f (σ 3) ^ 2, from (char_p.int_cast_eq_zero_iff (zmod 2) 2 _).1 $ by simpa only [int.cast_pow, int.cast_add, zmod.pow_card] using hσ.2, let ⟨x, hx⟩ := h01 in let ⟨y, hy⟩ := h23 in ⟨(f (σ 0) - f (σ 1)) / 2, (f (σ 0) + f (σ 1)) / 2, (f (σ 2) - f (σ 3)) / 2, (f (σ 2) + f (σ 3)) / 2, begin rw [← int.sq_add_sq_of_two_mul_sq_add_sq hx.symm, add_assoc, ← int.sq_add_sq_of_two_mul_sq_add_sq hy.symm, ← mul_right_inj' (show (2 : ℤ) ≠ 0, from dec_trivial), ← h, mul_add, ← hx, ← hy], have : ∑ x, f (σ x)^2 = ∑ x, f x^2, { conv_rhs { rw ←equiv.sum_comp σ } }, simpa only [fin.sum_univ_four, add_assoc] using this, end⟩ private lemma prime_sum_four_squares (p : ℕ) [hp : fact p.prime] : ∃ a b c d : ℤ, a^2 + b^2 + c^2 + d^2 = p := have hm : ∃ m < p, 0 < m ∧ ∃ a b c d : ℤ, a^2 + b^2 + c^2 + d^2 = m * p, from let ⟨a, b, k, hk⟩ := exists_sq_add_sq_add_one_eq_k p in ⟨k, hk.2, nat.pos_of_ne_zero $ (λ hk0, by { rw [hk0, int.coe_nat_zero, zero_mul] at hk, exact ne_of_gt (show a^2 + b^2 + 1 > 0, from add_pos_of_nonneg_of_pos (add_nonneg (sq_nonneg _) (sq_nonneg _)) zero_lt_one) hk.1 }), a, b, 1, 0, by simpa only [zero_pow two_pos, one_pow, add_zero] using hk.1⟩, let m := nat.find hm in let ⟨a, b, c, d, (habcd : a^2 + b^2 + c^2 + d^2 = m * p)⟩ := (nat.find_spec hm).snd.2 in by haveI hm0 : ne_zero m := ne_zero.of_pos (nat.find_spec hm).snd.1; exact have hmp : m < p, from (nat.find_spec hm).fst, m.mod_two_eq_zero_or_one.elim (λ hm2 : m % 2 = 0, let ⟨k, hk⟩ := nat.dvd_iff_mod_eq_zero.2 hm2 in have hk0 : 0 < k, from nat.pos_of_ne_zero $ by { rintro rfl, rw mul_zero at hk, exact ne_zero.ne m hk }, have hkm : k < m, { rw [hk, two_mul], exact (lt_add_iff_pos_left _).2 hk0 }, false.elim $ nat.find_min hm hkm ⟨lt_trans hkm hmp, hk0, sum_four_squares_of_two_mul_sum_four_squares (show a^2 + b^2 + c^2 + d^2 = 2 * (k * p), by { rw [habcd, hk, int.coe_nat_mul, mul_assoc], norm_num })⟩) (λ hm2 : m % 2 = 1, if hm1 : m = 1 then ⟨a, b, c, d, by simp only [hm1, habcd, int.coe_nat_one, one_mul]⟩ else let w := (a : zmod m).val_min_abs, x := (b : zmod m).val_min_abs, y := (c : zmod m).val_min_abs, z := (d : zmod m).val_min_abs in have hnat_abs : w^2 + x^2 + y^2 + z^2 = (w.nat_abs^2 + x.nat_abs^2 + y.nat_abs ^2 + z.nat_abs ^ 2 : ℕ), by { push_cast, simp_rw sq_abs, }, have hwxyzlt : w^2 + x^2 + y^2 + z^2 < m^2, from calc w^2 + x^2 + y^2 + z^2 = (w.nat_abs^2 + x.nat_abs^2 + y.nat_abs ^2 + z.nat_abs ^ 2 : ℕ) : hnat_abs ... ≤ ((m / 2) ^ 2 + (m / 2) ^ 2 + (m / 2) ^ 2 + (m / 2) ^ 2 : ℕ) : int.coe_nat_le.2 $ add_le_add (add_le_add (add_le_add (nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _) (nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _)) (nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _)) (nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _) ... = 4 * (m / 2 : ℕ) ^ 2 : by simp only [bit0_mul, one_mul, two_smul, nat.cast_add, nat.cast_pow, add_assoc] ... < 4 * (m / 2 : ℕ) ^ 2 + ((4 * (m / 2) : ℕ) * (m % 2 : ℕ) + (m % 2 : ℕ)^2) : (lt_add_iff_pos_right _).2 (by { rw [hm2, int.coe_nat_one, one_pow, mul_one], exact add_pos_of_nonneg_of_pos (int.coe_nat_nonneg _) zero_lt_one }) ... = m ^ 2 : by { conv_rhs {rw [← nat.mod_add_div m 2]}, simp [-nat.mod_add_div, mul_add, add_mul, bit0, bit1, mul_comm, mul_assoc, mul_left_comm, pow_add, add_comm, add_left_comm] }, have hwxyzabcd : ((w^2 + x^2 + y^2 + z^2 : ℤ) : zmod m) = ((a^2 + b^2 + c^2 + d^2 : ℤ) : zmod m), by push_cast, have hwxyz0 : ((w^2 + x^2 + y^2 + z^2 : ℤ) : zmod m) = 0, by rw [hwxyzabcd, habcd, int.cast_mul, cast_coe_nat, zmod.nat_cast_self, zero_mul], let ⟨n, hn⟩ := ((char_p.int_cast_eq_zero_iff _ m _).1 hwxyz0) in have hn0 : 0 < n.nat_abs, from int.nat_abs_pos_of_ne_zero (λ hn0, have hwxyz0 : (w.nat_abs^2 + x.nat_abs^2 + y.nat_abs^2 + z.nat_abs^2 : ℕ) = 0, by { rw [← int.coe_nat_eq_zero, ← hnat_abs], rwa [hn0, mul_zero] at hn }, have habcd0 : (m : ℤ) ∣ a ∧ (m : ℤ) ∣ b ∧ (m : ℤ) ∣ c ∧ (m : ℤ) ∣ d, by simpa only [add_eq_zero_iff, int.nat_abs_eq_zero, zmod.val_min_abs_eq_zero, and.assoc, pow_eq_zero_iff two_pos, char_p.int_cast_eq_zero_iff _ m _] using hwxyz0, let ⟨ma, hma⟩ := habcd0.1, ⟨mb, hmb⟩ := habcd0.2.1, ⟨mc, hmc⟩ := habcd0.2.2.1, ⟨md, hmd⟩ := habcd0.2.2.2 in have hmdvdp : m ∣ p, from int.coe_nat_dvd.1 ⟨ma^2 + mb^2 + mc^2 + md^2, (mul_right_inj' (show (m : ℤ) ≠ 0, from int.coe_nat_ne_zero.2 hm0.1)).1 $ by { rw [← habcd, hma, hmb, hmc, hmd], ring }⟩, (hp.1.eq_one_or_self_of_dvd _ hmdvdp).elim hm1 (λ hmeqp, by simpa [lt_irrefl, hmeqp] using hmp)), have hawbxcydz : ((m : ℕ) : ℤ) ∣ a * w + b * x + c * y + d * z, from (char_p.int_cast_eq_zero_iff (zmod m) m _).1 $ by { rw [← hwxyz0], simp_rw [sq], push_cast }, have haxbwczdy : ((m : ℕ) : ℤ) ∣ a * x - b * w - c * z + d * y, from (char_p.int_cast_eq_zero_iff (zmod m) m _).1 $ by { push_cast, ring }, have haybzcwdx : ((m : ℕ) : ℤ) ∣ a * y + b * z - c * w - d * x, from (char_p.int_cast_eq_zero_iff (zmod m) m _).1 $ by { push_cast, ring }, have hazbycxdw : ((m : ℕ) : ℤ) ∣ a * z - b * y + c * x - d * w, from (char_p.int_cast_eq_zero_iff (zmod m) m _).1 $ by { push_cast, ring }, let ⟨s, hs⟩ := hawbxcydz, ⟨t, ht⟩ := haxbwczdy, ⟨u, hu⟩ := haybzcwdx, ⟨v, hv⟩ := hazbycxdw in have hn_nonneg : 0 ≤ n, from nonneg_of_mul_nonneg_right (by { erw [← hn], repeat {try {refine add_nonneg _ _}, try {exact sq_nonneg _}} }) (int.coe_nat_pos.2 $ ne_zero.pos m), have hnm : n.nat_abs < m, from int.coe_nat_lt.1 (lt_of_mul_lt_mul_left (by { rw [int.nat_abs_of_nonneg hn_nonneg, ← hn, ← sq], exact hwxyzlt }) (int.coe_nat_nonneg m)), have hstuv : s^2 + t^2 + u^2 + v^2 = n.nat_abs * p, from (mul_right_inj' (show (m^2 : ℤ) ≠ 0, from pow_ne_zero 2 (int.coe_nat_ne_zero.2 hm0.1))).1 $ calc (m : ℤ)^2 * (s^2 + t^2 + u^2 + v^2) = ((m : ℕ) * s)^2 + ((m : ℕ) * t)^2 + ((m : ℕ) * u)^2 + ((m : ℕ) * v)^2 : by { simp [mul_pow], ring } ... = (w^2 + x^2 + y^2 + z^2) * (a^2 + b^2 + c^2 + d^2) : by { simp only [hs.symm, ht.symm, hu.symm, hv.symm], ring } ... = _ : by { rw [hn, habcd, int.nat_abs_of_nonneg hn_nonneg], dsimp [m], ring }, false.elim $ nat.find_min hm hnm ⟨lt_trans hnm hmp, hn0, s, t, u, v, hstuv⟩) /-- **Four squares theorem** -/ lemma sum_four_squares : ∀ n : ℕ, ∃ a b c d : ℕ, a^2 + b^2 + c^2 + d^2 = n | 0 := ⟨0, 0, 0, 0, rfl⟩ | 1 := ⟨1, 0, 0, 0, rfl⟩ | n@(k+2) := have hm : fact (min_fac (k+2)).prime := ⟨min_fac_prime dec_trivial⟩, have n / min_fac n < n := factors_lemma, let ⟨a, b, c, d, h₁⟩ := show ∃ a b c d : ℤ, a^2 + b^2 + c^2 + d^2 = min_fac n, by exactI prime_sum_four_squares (min_fac (k+2)) in let ⟨w, x, y, z, h₂⟩ := sum_four_squares (n / min_fac n) in ⟨(a * w - b * x - c * y - d * z).nat_abs, (a * x + b * w + c * z - d * y).nat_abs, (a * y - b * z + c * w + d * x).nat_abs, (a * z + b * y - c * x + d * w).nat_abs, begin rw [← int.coe_nat_inj', ← nat.mul_div_cancel' (min_fac_dvd (k+2)), int.coe_nat_mul, ← h₁, ← h₂], simp [sum_four_sq_mul_sum_four_sq], end⟩ end nat
09b1f22591f02ff7599747c6b0cc2aa6c4ff0181
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/interactive/plainTermGoal.lean
109a3540e0708a31a400fbc207c16d369a53a289
[ "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
967
lean
-- example : 0 < 2 := Nat.lt_trans Nat.zero_lt_one (Nat.lt_succ_self _) --^ $/lean/plainTermGoal --^ $/lean/plainTermGoal --^ $/lean/plainTermGoal --^ $/lean/plainTermGoal --^ $/lean/plainTermGoal example : OptionM Unit := do let y : Int ← none let x ← Nat.zero --^ $/lean/plainTermGoal return () example (m n : Nat) : m < n := Nat.lt_trans _ _ --^ $/lean/plainTermGoal example : True := sorry --^ $/lean/plainTermGoal example : ∀ n, n < n + 42 := fun n => Nat.lt_of_le_of_lt (Nat.le_add_right n 41) (Nat.lt_succ_self _) --^ $/lean/plainTermGoal --^ $/lean/plainTermGoal example : ∀ n, n < 1 + n := by intro n rw [Nat.add_comm] --^ $/lean/plainTermGoal exact Nat.lt_succ_self _ --^ $/lean/plainTermGoal #check fun (n m : Nat) => m --^ $/lean/plainTermGoal
1cf2ea6ece9f9c139727511c6bbee8f6605a1687
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/geometry/euclidean/basic.lean
d895aee6a245e475fae2e192541485435ee1b79a
[]
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
39,465
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Joseph Myers. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.analysis.normed_space.inner_product import Mathlib.algebra.quadratic_discriminant import Mathlib.analysis.normed_space.add_torsor import Mathlib.data.matrix.notation import Mathlib.linear_algebra.affine_space.finite_dimensional import Mathlib.tactic.fin_cases import Mathlib.PostPort universes u_1 u_2 u_3 u_4 namespace Mathlib /-! # Euclidean spaces This file makes some definitions and proves very basic geometrical results about real inner product spaces and Euclidean affine spaces. Results about real inner product spaces that involve the norm and inner product but not angles generally go in `analysis.normed_space.inner_product`. Results with longer proofs or more geometrical content generally go in separate files. ## Main definitions * `inner_product_geometry.angle` is the undirected angle between two vectors. * `euclidean_geometry.angle`, with notation `∠`, is the undirected angle determined by three points. * `euclidean_geometry.orthogonal_projection` is the orthogonal projection of a point onto an affine subspace. * `euclidean_geometry.reflection` is the reflection of a point in an affine subspace. ## Implementation notes To declare `P` as the type of points in a Euclidean affine space with `V` as the type of vectors, use `[inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P]`. This works better with `out_param` to make `V` implicit in most cases than having a separate type alias for Euclidean affine spaces. Rather than requiring Euclidean affine spaces to be finite-dimensional (as in the definition on Wikipedia), this is specified only for those theorems that need it. ## References * https://en.wikipedia.org/wiki/Euclidean_space -/ namespace inner_product_geometry /-! ### Geometrical results on real inner product spaces This section develops some geometrical definitions and results on real inner product spaces, where those definitions and results can most conveniently be developed in terms of vectors and then used to deduce corresponding results for Euclidean affine spaces. -/ /-- The undirected angle between two vectors. If either vector is 0, this is π/2. -/ def angle {V : Type u_1} [inner_product_space ℝ V] (x : V) (y : V) : ℝ := real.arccos (inner x y / (norm x * norm y)) /-- The cosine of the angle between two vectors. -/ theorem cos_angle {V : Type u_1} [inner_product_space ℝ V] (x : V) (y : V) : real.cos (angle x y) = inner x y / (norm x * norm y) := real.cos_arccos (and.left (iff.mp abs_le (abs_real_inner_div_norm_mul_norm_le_one x y))) (and.right (iff.mp abs_le (abs_real_inner_div_norm_mul_norm_le_one x y))) /-- The angle between two vectors does not depend on their order. -/ theorem angle_comm {V : Type u_1} [inner_product_space ℝ V] (x : V) (y : V) : angle x y = angle y x := sorry /-- The angle between the negation of two vectors. -/ @[simp] theorem angle_neg_neg {V : Type u_1} [inner_product_space ℝ V] (x : V) (y : V) : angle (-x) (-y) = angle x y := sorry /-- The angle between two vectors is nonnegative. -/ theorem angle_nonneg {V : Type u_1} [inner_product_space ℝ V] (x : V) (y : V) : 0 ≤ angle x y := real.arccos_nonneg (inner x y / (norm x * norm y)) /-- The angle between two vectors is at most π. -/ theorem angle_le_pi {V : Type u_1} [inner_product_space ℝ V] (x : V) (y : V) : angle x y ≤ real.pi := real.arccos_le_pi (inner x y / (norm x * norm y)) /-- The angle between a vector and the negation of another vector. -/ theorem angle_neg_right {V : Type u_1} [inner_product_space ℝ V] (x : V) (y : V) : angle x (-y) = real.pi - angle x y := sorry /-- The angle between the negation of a vector and another vector. -/ theorem angle_neg_left {V : Type u_1} [inner_product_space ℝ V] (x : V) (y : V) : angle (-x) y = real.pi - angle x y := sorry /-- The angle between the zero vector and a vector. -/ @[simp] theorem angle_zero_left {V : Type u_1} [inner_product_space ℝ V] (x : V) : angle 0 x = real.pi / bit0 1 := sorry /-- The angle between a vector and the zero vector. -/ @[simp] theorem angle_zero_right {V : Type u_1} [inner_product_space ℝ V] (x : V) : angle x 0 = real.pi / bit0 1 := sorry /-- The angle between a nonzero vector and itself. -/ @[simp] theorem angle_self {V : Type u_1} [inner_product_space ℝ V] {x : V} (hx : x ≠ 0) : angle x x = 0 := sorry /-- The angle between a nonzero vector and its negation. -/ @[simp] theorem angle_self_neg_of_nonzero {V : Type u_1} [inner_product_space ℝ V] {x : V} (hx : x ≠ 0) : angle x (-x) = real.pi := eq.mpr (id (Eq._oldrec (Eq.refl (angle x (-x) = real.pi)) (angle_neg_right x x))) (eq.mpr (id (Eq._oldrec (Eq.refl (real.pi - angle x x = real.pi)) (angle_self hx))) (eq.mpr (id (Eq._oldrec (Eq.refl (real.pi - 0 = real.pi)) (sub_zero real.pi))) (Eq.refl real.pi))) /-- The angle between the negation of a nonzero vector and that vector. -/ @[simp] theorem angle_neg_self_of_nonzero {V : Type u_1} [inner_product_space ℝ V] {x : V} (hx : x ≠ 0) : angle (-x) x = real.pi := eq.mpr (id (Eq._oldrec (Eq.refl (angle (-x) x = real.pi)) (angle_comm (-x) x))) (eq.mpr (id (Eq._oldrec (Eq.refl (angle x (-x) = real.pi)) (angle_self_neg_of_nonzero hx))) (Eq.refl real.pi)) /-- The angle between a vector and a positive multiple of a vector. -/ @[simp] theorem angle_smul_right_of_pos {V : Type u_1} [inner_product_space ℝ V] (x : V) (y : V) {r : ℝ} (hr : 0 < r) : angle x (r • y) = angle x y := sorry /-- The angle between a positive multiple of a vector and a vector. -/ @[simp] theorem angle_smul_left_of_pos {V : Type u_1} [inner_product_space ℝ V] (x : V) (y : V) {r : ℝ} (hr : 0 < r) : angle (r • x) y = angle x y := eq.mpr (id (Eq._oldrec (Eq.refl (angle (r • x) y = angle x y)) (angle_comm (r • x) y))) (eq.mpr (id (Eq._oldrec (Eq.refl (angle y (r • x) = angle x y)) (angle_smul_right_of_pos y x hr))) (eq.mpr (id (Eq._oldrec (Eq.refl (angle y x = angle x y)) (angle_comm y x))) (Eq.refl (angle x y)))) /-- The angle between a vector and a negative multiple of a vector. -/ @[simp] theorem angle_smul_right_of_neg {V : Type u_1} [inner_product_space ℝ V] (x : V) (y : V) {r : ℝ} (hr : r < 0) : angle x (r • y) = angle x (-y) := sorry /-- The angle between a negative multiple of a vector and a vector. -/ @[simp] theorem angle_smul_left_of_neg {V : Type u_1} [inner_product_space ℝ V] (x : V) (y : V) {r : ℝ} (hr : r < 0) : angle (r • x) y = angle (-x) y := eq.mpr (id (Eq._oldrec (Eq.refl (angle (r • x) y = angle (-x) y)) (angle_comm (r • x) y))) (eq.mpr (id (Eq._oldrec (Eq.refl (angle y (r • x) = angle (-x) y)) (angle_smul_right_of_neg y x hr))) (eq.mpr (id (Eq._oldrec (Eq.refl (angle y (-x) = angle (-x) y)) (angle_comm y (-x)))) (Eq.refl (angle (-x) y)))) /-- The cosine of the angle between two vectors, multiplied by the product of their norms. -/ theorem cos_angle_mul_norm_mul_norm {V : Type u_1} [inner_product_space ℝ V] (x : V) (y : V) : real.cos (angle x y) * (norm x * norm y) = inner x y := sorry /-- The sine of the angle between two vectors, multiplied by the product of their norms. -/ theorem sin_angle_mul_norm_mul_norm {V : Type u_1} [inner_product_space ℝ V] (x : V) (y : V) : real.sin (angle x y) * (norm x * norm y) = real.sqrt (inner x x * inner y y - inner x y * inner x y) := sorry /-- The angle between two vectors is zero if and only if they are nonzero and one is a positive multiple of the other. -/ theorem angle_eq_zero_iff {V : Type u_1} [inner_product_space ℝ V] {x : V} {y : V} : angle x y = 0 ↔ x ≠ 0 ∧ ∃ (r : ℝ), 0 < r ∧ y = r • x := sorry /-- The angle between two vectors is π if and only if they are nonzero and one is a negative multiple of the other. -/ theorem angle_eq_pi_iff {V : Type u_1} [inner_product_space ℝ V] {x : V} {y : V} : angle x y = real.pi ↔ x ≠ 0 ∧ ∃ (r : ℝ), r < 0 ∧ y = r • x := sorry /-- If the angle between two vectors is π, the angles between those vectors and a third vector add to π. -/ theorem angle_add_angle_eq_pi_of_angle_eq_pi {V : Type u_1} [inner_product_space ℝ V] {x : V} {y : V} (z : V) (h : angle x y = real.pi) : angle x z + angle y z = real.pi := sorry /-- Two vectors have inner product 0 if and only if the angle between them is π/2. -/ theorem inner_eq_zero_iff_angle_eq_pi_div_two {V : Type u_1} [inner_product_space ℝ V] (x : V) (y : V) : inner x y = 0 ↔ angle x y = real.pi / bit0 1 := sorry end inner_product_geometry namespace euclidean_geometry /-! ### Geometrical results on Euclidean affine spaces This section develops some geometrical definitions and results on Euclidean affine spaces. -/ /-- The undirected angle at `p2` between the line segments to `p1` and `p3`. If either of those points equals `p2`, this is π/2. Use `open_locale euclidean_geometry` to access the `∠ p1 p2 p3` notation. -/ def angle {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] (p1 : P) (p2 : P) (p3 : P) : ℝ := inner_product_geometry.angle (p1 -ᵥ p2) (p3 -ᵥ p2) /-- The angle at a point does not depend on the order of the other two points. -/ theorem angle_comm {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] (p1 : P) (p2 : P) (p3 : P) : angle p1 p2 p3 = angle p3 p2 p1 := inner_product_geometry.angle_comm (p1 -ᵥ p2) (p3 -ᵥ p2) /-- The angle at a point is nonnegative. -/ theorem angle_nonneg {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] (p1 : P) (p2 : P) (p3 : P) : 0 ≤ angle p1 p2 p3 := inner_product_geometry.angle_nonneg (p1 -ᵥ p2) (p3 -ᵥ p2) /-- The angle at a point is at most π. -/ theorem angle_le_pi {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] (p1 : P) (p2 : P) (p3 : P) : angle p1 p2 p3 ≤ real.pi := inner_product_geometry.angle_le_pi (p1 -ᵥ p2) (p3 -ᵥ p2) /-- The angle ∠AAB at a point. -/ theorem angle_eq_left {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] (p1 : P) (p2 : P) : angle p1 p1 p2 = real.pi / bit0 1 := sorry /-- The angle ∠ABB at a point. -/ theorem angle_eq_right {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] (p1 : P) (p2 : P) : angle p1 p2 p2 = real.pi / bit0 1 := eq.mpr (id (Eq._oldrec (Eq.refl (angle p1 p2 p2 = real.pi / bit0 1)) (angle_comm p1 p2 p2))) (eq.mpr (id (Eq._oldrec (Eq.refl (angle p2 p2 p1 = real.pi / bit0 1)) (angle_eq_left p2 p1))) (Eq.refl (real.pi / bit0 1))) /-- The angle ∠ABA at a point. -/ theorem angle_eq_of_ne {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {p1 : P} {p2 : P} (h : p1 ≠ p2) : angle p1 p2 p1 = 0 := inner_product_geometry.angle_self fun (he : p1 -ᵥ p2 = 0) => h (iff.mp vsub_eq_zero_iff_eq he) /-- If the angle ∠ABC at a point is π, the angle ∠BAC is 0. -/ theorem angle_eq_zero_of_angle_eq_pi_left {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {p1 : P} {p2 : P} {p3 : P} (h : angle p1 p2 p3 = real.pi) : angle p2 p1 p3 = 0 := sorry /-- If the angle ∠ABC at a point is π, the angle ∠BCA is 0. -/ theorem angle_eq_zero_of_angle_eq_pi_right {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {p1 : P} {p2 : P} {p3 : P} (h : angle p1 p2 p3 = real.pi) : angle p2 p3 p1 = 0 := angle_eq_zero_of_angle_eq_pi_left (eq.mp (Eq._oldrec (Eq.refl (angle p1 p2 p3 = real.pi)) (angle_comm p1 p2 p3)) h) /-- If ∠BCD = π, then ∠ABC = ∠ABD. -/ theorem angle_eq_angle_of_angle_eq_pi {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] (p1 : P) {p2 : P} {p3 : P} {p4 : P} (h : angle p2 p3 p4 = real.pi) : angle p1 p2 p3 = angle p1 p2 p4 := sorry /-- If ∠BCD = π, then ∠ACB + ∠ACD = π. -/ theorem angle_add_angle_eq_pi_of_angle_eq_pi {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] (p1 : P) {p2 : P} {p3 : P} {p4 : P} (h : angle p2 p3 p4 = real.pi) : angle p1 p3 p2 + angle p1 p3 p4 = real.pi := sorry /-- The inner product of two vectors given with `weighted_vsub`, in terms of the pairwise distances. -/ theorem inner_weighted_vsub {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {ι₁ : Type u_3} {s₁ : finset ι₁} {w₁ : ι₁ → ℝ} (p₁ : ι₁ → P) (h₁ : (finset.sum s₁ fun (i : ι₁) => w₁ i) = 0) {ι₂ : Type u_4} {s₂ : finset ι₂} {w₂ : ι₂ → ℝ} (p₂ : ι₂ → P) (h₂ : (finset.sum s₂ fun (i : ι₂) => w₂ i) = 0) : inner (coe_fn (finset.weighted_vsub s₁ p₁) w₁) (coe_fn (finset.weighted_vsub s₂ p₂) w₂) = (-finset.sum s₁ fun (i₁ : ι₁) => finset.sum s₂ fun (i₂ : ι₂) => w₁ i₁ * w₂ i₂ * (dist (p₁ i₁) (p₂ i₂) * dist (p₁ i₁) (p₂ i₂))) / bit0 1 := sorry /-- The distance between two points given with `affine_combination`, in terms of the pairwise distances between the points in that combination. -/ theorem dist_affine_combination {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {ι : Type u_3} {s : finset ι} {w₁ : ι → ℝ} {w₂ : ι → ℝ} (p : ι → P) (h₁ : (finset.sum s fun (i : ι) => w₁ i) = 1) (h₂ : (finset.sum s fun (i : ι) => w₂ i) = 1) : dist (coe_fn (finset.affine_combination s p) w₁) (coe_fn (finset.affine_combination s p) w₂) * dist (coe_fn (finset.affine_combination s p) w₁) (coe_fn (finset.affine_combination s p) w₂) = (-finset.sum s fun (i₁ : ι) => finset.sum s fun (i₂ : ι) => Sub.sub w₁ w₂ i₁ * Sub.sub w₁ w₂ i₂ * (dist (p i₁) (p i₂) * dist (p i₁) (p i₂))) / bit0 1 := sorry /-- Suppose that `c₁` is equidistant from `p₁` and `p₂`, and the same applies to `c₂`. Then the vector between `c₁` and `c₂` is orthogonal to that between `p₁` and `p₂`. (In two dimensions, this says that the diagonals of a kite are orthogonal.) -/ theorem inner_vsub_vsub_of_dist_eq_of_dist_eq {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {c₁ : P} {c₂ : P} {p₁ : P} {p₂ : P} (hc₁ : dist p₁ c₁ = dist p₂ c₁) (hc₂ : dist p₁ c₂ = dist p₂ c₂) : inner (c₂ -ᵥ c₁) (p₂ -ᵥ p₁) = 0 := sorry /-- The squared distance between points on a line (expressed as a multiple of a fixed vector added to a point) and another point, expressed as a quadratic. -/ theorem dist_smul_vadd_square {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] (r : ℝ) (v : V) (p₁ : P) (p₂ : P) : dist (r • v +ᵥ p₁) p₂ * dist (r • v +ᵥ p₁) p₂ = inner v v * r * r + bit0 1 * inner v (p₁ -ᵥ p₂) * r + inner (p₁ -ᵥ p₂) (p₁ -ᵥ p₂) := sorry /-- The condition for two points on a line to be equidistant from another point. -/ theorem dist_smul_vadd_eq_dist {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {v : V} (p₁ : P) (p₂ : P) (hv : v ≠ 0) (r : ℝ) : dist (r • v +ᵥ p₁) p₂ = dist p₁ p₂ ↔ r = 0 ∨ r = -bit0 1 * inner v (p₁ -ᵥ p₂) / inner v v := sorry /-- Distances `r₁` `r₂` of `p` from two different points `c₁` `c₂` determine at most two points `p₁` `p₂` in a two-dimensional subspace containing those points (two circles intersect in at most two points). -/ theorem eq_of_dist_eq_of_dist_eq_of_mem_of_findim_eq_two {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {s : affine_subspace ℝ P} [finite_dimensional ℝ ↥(affine_subspace.direction s)] (hd : finite_dimensional.findim ℝ ↥(affine_subspace.direction s) = bit0 1) {c₁ : P} {c₂ : P} {p₁ : P} {p₂ : P} {p : P} (hc₁s : c₁ ∈ s) (hc₂s : c₂ ∈ s) (hp₁s : p₁ ∈ s) (hp₂s : p₂ ∈ s) (hps : p ∈ s) {r₁ : ℝ} {r₂ : ℝ} (hc : c₁ ≠ c₂) (hp : p₁ ≠ p₂) (hp₁c₁ : dist p₁ c₁ = r₁) (hp₂c₁ : dist p₂ c₁ = r₁) (hpc₁ : dist p c₁ = r₁) (hp₁c₂ : dist p₁ c₂ = r₂) (hp₂c₂ : dist p₂ c₂ = r₂) (hpc₂ : dist p c₂ = r₂) : p = p₁ ∨ p = p₂ := sorry /-- Distances `r₁` `r₂` of `p` from two different points `c₁` `c₂` determine at most two points `p₁` `p₂` in two-dimensional space (two circles intersect in at most two points). -/ theorem eq_of_dist_eq_of_dist_eq_of_findim_eq_two {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] [finite_dimensional ℝ V] (hd : finite_dimensional.findim ℝ V = bit0 1) {c₁ : P} {c₂ : P} {p₁ : P} {p₂ : P} {p : P} {r₁ : ℝ} {r₂ : ℝ} (hc : c₁ ≠ c₂) (hp : p₁ ≠ p₂) (hp₁c₁ : dist p₁ c₁ = r₁) (hp₂c₁ : dist p₂ c₁ = r₁) (hpc₁ : dist p c₁ = r₁) (hp₁c₂ : dist p₁ c₂ = r₂) (hp₂c₂ : dist p₂ c₂ = r₂) (hpc₂ : dist p c₂ = r₂) : p = p₁ ∨ p = p₂ := sorry /-- The orthogonal projection of a point onto a nonempty affine subspace, whose direction is complete, as an unbundled function. This definition is only intended for use in setting up the bundled version `orthogonal_projection` and should not be used once that is defined. -/ def orthogonal_projection_fn {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] (s : affine_subspace ℝ P) [Nonempty ↥s] [complete_space ↥(affine_subspace.direction s)] (p : P) : P := classical.some sorry /-- The intersection of the subspace and the orthogonal subspace through the given point is the `orthogonal_projection_fn` of that point onto the subspace. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ theorem inter_eq_singleton_orthogonal_projection_fn {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {s : affine_subspace ℝ P} [Nonempty ↥s] [complete_space ↥(affine_subspace.direction s)] (p : P) : ↑s ∩ ↑(affine_subspace.mk' p (affine_subspace.direction sᗮ)) = singleton (orthogonal_projection_fn s p) := sorry /-- The `orthogonal_projection_fn` lies in the given subspace. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ theorem orthogonal_projection_fn_mem {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {s : affine_subspace ℝ P} [Nonempty ↥s] [complete_space ↥(affine_subspace.direction s)] (p : P) : orthogonal_projection_fn s p ∈ s := sorry /-- The `orthogonal_projection_fn` lies in the orthogonal subspace. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ theorem orthogonal_projection_fn_mem_orthogonal {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {s : affine_subspace ℝ P} [Nonempty ↥s] [complete_space ↥(affine_subspace.direction s)] (p : P) : orthogonal_projection_fn s p ∈ affine_subspace.mk' p (affine_subspace.direction sᗮ) := sorry /-- Subtracting `p` from its `orthogonal_projection_fn` produces a result in the orthogonal direction. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ theorem orthogonal_projection_fn_vsub_mem_direction_orthogonal {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {s : affine_subspace ℝ P} [Nonempty ↥s] [complete_space ↥(affine_subspace.direction s)] (p : P) : orthogonal_projection_fn s p -ᵥ p ∈ (affine_subspace.direction sᗮ) := affine_subspace.direction_mk' p (affine_subspace.direction sᗮ) ▸ affine_subspace.vsub_mem_direction (orthogonal_projection_fn_mem_orthogonal p) (affine_subspace.self_mem_mk' p (affine_subspace.direction sᗮ)) /-- The orthogonal projection of a point onto a nonempty affine subspace, whose direction is complete. The corresponding linear map (mapping a vector to the difference between the projections of two points whose difference is that vector) is the `orthogonal_projection` for real inner product spaces, onto the direction of the affine subspace being projected onto. -/ def orthogonal_projection {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] (s : affine_subspace ℝ P) [Nonempty ↥s] [complete_space ↥(affine_subspace.direction s)] : affine_map ℝ P ↥s := affine_map.mk (fun (p : P) => { val := orthogonal_projection_fn s p, property := orthogonal_projection_fn_mem p }) ↑(orthogonal_projection (affine_subspace.direction s)) sorry @[simp] theorem orthogonal_projection_fn_eq {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {s : affine_subspace ℝ P} [Nonempty ↥s] [complete_space ↥(affine_subspace.direction s)] (p : P) : orthogonal_projection_fn s p = ↑(coe_fn (orthogonal_projection s) p) := rfl /-- The linear map corresponding to `orthogonal_projection`. -/ @[simp] theorem orthogonal_projection_linear {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {s : affine_subspace ℝ P} [Nonempty ↥s] [complete_space ↥(affine_subspace.direction s)] : affine_map.linear (orthogonal_projection s) = ↑(orthogonal_projection (affine_subspace.direction s)) := rfl /-- The intersection of the subspace and the orthogonal subspace through the given point is the `orthogonal_projection` of that point onto the subspace. -/ theorem inter_eq_singleton_orthogonal_projection {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {s : affine_subspace ℝ P} [Nonempty ↥s] [complete_space ↥(affine_subspace.direction s)] (p : P) : ↑s ∩ ↑(affine_subspace.mk' p (affine_subspace.direction sᗮ)) = singleton ↑(coe_fn (orthogonal_projection s) p) := sorry /-- The `orthogonal_projection` lies in the given subspace. -/ theorem orthogonal_projection_mem {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {s : affine_subspace ℝ P} [Nonempty ↥s] [complete_space ↥(affine_subspace.direction s)] (p : P) : ↑(coe_fn (orthogonal_projection s) p) ∈ s := subtype.property (coe_fn (orthogonal_projection s) p) /-- The `orthogonal_projection` lies in the orthogonal subspace. -/ theorem orthogonal_projection_mem_orthogonal {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] (s : affine_subspace ℝ P) [Nonempty ↥s] [complete_space ↥(affine_subspace.direction s)] (p : P) : ↑(coe_fn (orthogonal_projection s) p) ∈ affine_subspace.mk' p (affine_subspace.direction sᗮ) := orthogonal_projection_fn_mem_orthogonal p /-- Subtracting a point in the given subspace from the `orthogonal_projection` produces a result in the direction of the given subspace. -/ theorem orthogonal_projection_vsub_mem_direction {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {s : affine_subspace ℝ P} [Nonempty ↥s] [complete_space ↥(affine_subspace.direction s)] {p1 : P} (p2 : P) (hp1 : p1 ∈ s) : ↑(coe_fn (orthogonal_projection s) p2 -ᵥ { val := p1, property := hp1 }) ∈ affine_subspace.direction s := subtype.property (coe_fn (orthogonal_projection s) p2 -ᵥ { val := p1, property := hp1 }) /-- Subtracting the `orthogonal_projection` from a point in the given subspace produces a result in the direction of the given subspace. -/ theorem vsub_orthogonal_projection_mem_direction {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {s : affine_subspace ℝ P} [Nonempty ↥s] [complete_space ↥(affine_subspace.direction s)] {p1 : P} (p2 : P) (hp1 : p1 ∈ s) : ↑({ val := p1, property := hp1 } -ᵥ coe_fn (orthogonal_projection s) p2) ∈ affine_subspace.direction s := subtype.property ({ val := p1, property := hp1 } -ᵥ coe_fn (orthogonal_projection s) p2) /-- A point equals its orthogonal projection if and only if it lies in the subspace. -/ theorem orthogonal_projection_eq_self_iff {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {s : affine_subspace ℝ P} [Nonempty ↥s] [complete_space ↥(affine_subspace.direction s)] {p : P} : ↑(coe_fn (orthogonal_projection s) p) = p ↔ p ∈ s := sorry /-- Orthogonal projection is idempotent. -/ @[simp] theorem orthogonal_projection_orthogonal_projection {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] (s : affine_subspace ℝ P) [Nonempty ↥s] [complete_space ↥(affine_subspace.direction s)] (p : P) : coe_fn (orthogonal_projection s) ↑(coe_fn (orthogonal_projection s) p) = coe_fn (orthogonal_projection s) p := sorry theorem eq_orthogonal_projection_of_eq_subspace {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {s : affine_subspace ℝ P} {s' : affine_subspace ℝ P} [Nonempty ↥s] [Nonempty ↥s'] [complete_space ↥(affine_subspace.direction s)] [complete_space ↥(affine_subspace.direction s')] (h : s = s') (p : P) : ↑(coe_fn (orthogonal_projection s) p) = ↑(coe_fn (orthogonal_projection s') p) := sorry /-- The distance to a point's orthogonal projection is 0 iff it lies in the subspace. -/ theorem dist_orthogonal_projection_eq_zero_iff {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {s : affine_subspace ℝ P} [Nonempty ↥s] [complete_space ↥(affine_subspace.direction s)] {p : P} : dist p ↑(coe_fn (orthogonal_projection s) p) = 0 ↔ p ∈ s := sorry /-- The distance between a point and its orthogonal projection is nonzero if it does not lie in the subspace. -/ theorem dist_orthogonal_projection_ne_zero_of_not_mem {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {s : affine_subspace ℝ P} [Nonempty ↥s] [complete_space ↥(affine_subspace.direction s)] {p : P} (hp : ¬p ∈ s) : dist p ↑(coe_fn (orthogonal_projection s) p) ≠ 0 := mt (iff.mp dist_orthogonal_projection_eq_zero_iff) hp /-- Subtracting `p` from its `orthogonal_projection` produces a result in the orthogonal direction. -/ theorem orthogonal_projection_vsub_mem_direction_orthogonal {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] (s : affine_subspace ℝ P) [Nonempty ↥s] [complete_space ↥(affine_subspace.direction s)] (p : P) : ↑(coe_fn (orthogonal_projection s) p) -ᵥ p ∈ (affine_subspace.direction sᗮ) := orthogonal_projection_fn_vsub_mem_direction_orthogonal p /-- Subtracting the `orthogonal_projection` from `p` produces a result in the orthogonal direction. -/ theorem vsub_orthogonal_projection_mem_direction_orthogonal {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] (s : affine_subspace ℝ P) [Nonempty ↥s] [complete_space ↥(affine_subspace.direction s)] (p : P) : p -ᵥ ↑(coe_fn (orthogonal_projection s) p) ∈ (affine_subspace.direction sᗮ) := affine_subspace.direction_mk' p (affine_subspace.direction sᗮ) ▸ affine_subspace.vsub_mem_direction (affine_subspace.self_mem_mk' p (affine_subspace.direction sᗮ)) (orthogonal_projection_mem_orthogonal s p) /-- Adding a vector to a point in the given subspace, then taking the orthogonal projection, produces the original point if the vector was in the orthogonal direction. -/ theorem orthogonal_projection_vadd_eq_self {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {s : affine_subspace ℝ P} [Nonempty ↥s] [complete_space ↥(affine_subspace.direction s)] {p : P} (hp : p ∈ s) {v : V} (hv : v ∈ (affine_subspace.direction sᗮ)) : coe_fn (orthogonal_projection s) (v +ᵥ p) = { val := p, property := hp } := sorry /-- Adding a vector to a point in the given subspace, then taking the orthogonal projection, produces the original point if the vector is a multiple of the result of subtracting a point's orthogonal projection from that point. -/ theorem orthogonal_projection_vadd_smul_vsub_orthogonal_projection {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {s : affine_subspace ℝ P} [Nonempty ↥s] [complete_space ↥(affine_subspace.direction s)] {p1 : P} (p2 : P) (r : ℝ) (hp : p1 ∈ s) : coe_fn (orthogonal_projection s) (r • (p2 -ᵥ ↑(coe_fn (orthogonal_projection s) p2)) +ᵥ p1) = { val := p1, property := hp } := orthogonal_projection_vadd_eq_self hp (submodule.smul_mem (affine_subspace.direction sᗮ) r (vsub_orthogonal_projection_mem_direction_orthogonal s p2)) /-- The square of the distance from a point in `s` to `p2` equals the sum of the squares of the distances of the two points to the `orthogonal_projection`. -/ theorem dist_square_eq_dist_orthogonal_projection_square_add_dist_orthogonal_projection_square {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {s : affine_subspace ℝ P} [Nonempty ↥s] [complete_space ↥(affine_subspace.direction s)] {p1 : P} (p2 : P) (hp1 : p1 ∈ s) : dist p1 p2 * dist p1 p2 = dist p1 ↑(coe_fn (orthogonal_projection s) p2) * dist p1 ↑(coe_fn (orthogonal_projection s) p2) + dist p2 ↑(coe_fn (orthogonal_projection s) p2) * dist p2 ↑(coe_fn (orthogonal_projection s) p2) := sorry /-- The square of the distance between two points constructed by adding multiples of the same orthogonal vector to points in the same subspace. -/ theorem dist_square_smul_orthogonal_vadd_smul_orthogonal_vadd {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {s : affine_subspace ℝ P} {p1 : P} {p2 : P} (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) (r1 : ℝ) (r2 : ℝ) {v : V} (hv : v ∈ (affine_subspace.direction sᗮ)) : dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) * dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) = dist p1 p2 * dist p1 p2 + (r1 - r2) * (r1 - r2) * (norm v * norm v) := sorry /-- Reflection in an affine subspace, which is expected to be nonempty and complete. The word "reflection" is sometimes understood to mean specifically reflection in a codimension-one subspace, and sometimes more generally to cover operations such as reflection in a point. The definition here, of reflection in an affine subspace, is a more general sense of the word that includes both those common cases. If the subspace is empty or not complete, `orthogonal_projection` is defined as the identity map, which results in `reflection` being the identity map in that case as well. -/ def reflection {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] (s : affine_subspace ℝ P) [Nonempty ↥s] [complete_space ↥(affine_subspace.direction s)] : P ≃ᵢ P := isometric.mk (equiv.mk (fun (p : P) => ↑(coe_fn (orthogonal_projection s) p) -ᵥ p +ᵥ ↑(coe_fn (orthogonal_projection s) p)) (fun (p : P) => ↑(coe_fn (orthogonal_projection s) p) -ᵥ p +ᵥ ↑(coe_fn (orthogonal_projection s) p)) sorry sorry) sorry /-- The result of reflecting. -/ theorem reflection_apply {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] (s : affine_subspace ℝ P) [Nonempty ↥s] [complete_space ↥(affine_subspace.direction s)] (p : P) : coe_fn (reflection s) p = ↑(coe_fn (orthogonal_projection s) p) -ᵥ p +ᵥ ↑(coe_fn (orthogonal_projection s) p) := rfl theorem eq_reflection_of_eq_subspace {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {s : affine_subspace ℝ P} {s' : affine_subspace ℝ P} [Nonempty ↥s] [Nonempty ↥s'] [complete_space ↥(affine_subspace.direction s)] [complete_space ↥(affine_subspace.direction s')] (h : s = s') (p : P) : coe_fn (reflection s) p = coe_fn (reflection s') p := sorry /-- Reflection is its own inverse. -/ @[simp] theorem reflection_symm {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] (s : affine_subspace ℝ P) [Nonempty ↥s] [complete_space ↥(affine_subspace.direction s)] : isometric.symm (reflection s) = reflection s := rfl /-- Reflecting twice in the same subspace. -/ @[simp] theorem reflection_reflection {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] (s : affine_subspace ℝ P) [Nonempty ↥s] [complete_space ↥(affine_subspace.direction s)] (p : P) : coe_fn (reflection s) (coe_fn (reflection s) p) = p := equiv.left_inv (isometric.to_equiv (reflection s)) p /-- Reflection is involutive. -/ theorem reflection_involutive {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] (s : affine_subspace ℝ P) [Nonempty ↥s] [complete_space ↥(affine_subspace.direction s)] : function.involutive ⇑(reflection s) := reflection_reflection s /-- A point is its own reflection if and only if it is in the subspace. -/ theorem reflection_eq_self_iff {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {s : affine_subspace ℝ P} [Nonempty ↥s] [complete_space ↥(affine_subspace.direction s)] (p : P) : coe_fn (reflection s) p = p ↔ p ∈ s := sorry /-- Reflecting a point in two subspaces produces the same result if and only if the point has the same orthogonal projection in each of those subspaces. -/ theorem reflection_eq_iff_orthogonal_projection_eq {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] (s₁ : affine_subspace ℝ P) (s₂ : affine_subspace ℝ P) [Nonempty ↥s₁] [Nonempty ↥s₂] [complete_space ↥(affine_subspace.direction s₁)] [complete_space ↥(affine_subspace.direction s₂)] (p : P) : coe_fn (reflection s₁) p = coe_fn (reflection s₂) p ↔ ↑(coe_fn (orthogonal_projection s₁) p) = ↑(coe_fn (orthogonal_projection s₂) p) := sorry /-- The distance between `p₁` and the reflection of `p₂` equals that between the reflection of `p₁` and `p₂`. -/ theorem dist_reflection {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] (s : affine_subspace ℝ P) [Nonempty ↥s] [complete_space ↥(affine_subspace.direction s)] (p₁ : P) (p₂ : P) : dist p₁ (coe_fn (reflection s) p₂) = dist (coe_fn (reflection s) p₁) p₂ := sorry /-- A point in the subspace is equidistant from another point and its reflection. -/ theorem dist_reflection_eq_of_mem {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] (s : affine_subspace ℝ P) [Nonempty ↥s] [complete_space ↥(affine_subspace.direction s)] {p₁ : P} (hp₁ : p₁ ∈ s) (p₂ : P) : dist p₁ (coe_fn (reflection s) p₂) = dist p₁ p₂ := sorry /-- The reflection of a point in a subspace is contained in any larger subspace containing both the point and the subspace reflected in. -/ theorem reflection_mem_of_le_of_mem {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {s₁ : affine_subspace ℝ P} {s₂ : affine_subspace ℝ P} [Nonempty ↥s₁] [complete_space ↥(affine_subspace.direction s₁)] (hle : s₁ ≤ s₂) {p : P} (hp : p ∈ s₂) : coe_fn (reflection s₁) p ∈ s₂ := eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn (reflection s₁) p ∈ s₂)) (reflection_apply s₁ p))) (affine_subspace.vadd_mem_of_mem_direction (affine_subspace.vsub_mem_direction (hle (orthogonal_projection_mem p)) hp) (hle (orthogonal_projection_mem p))) /-- Reflecting an orthogonal vector plus a point in the subspace produces the negation of that vector plus the point. -/ theorem reflection_orthogonal_vadd {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {s : affine_subspace ℝ P} [Nonempty ↥s] [complete_space ↥(affine_subspace.direction s)] {p : P} (hp : p ∈ s) {v : V} (hv : v ∈ (affine_subspace.direction sᗮ)) : coe_fn (reflection s) (v +ᵥ p) = -v +ᵥ p := sorry /-- Reflecting a vector plus a point in the subspace produces the negation of that vector plus the point if the vector is a multiple of the result of subtracting a point's orthogonal projection from that point. -/ theorem reflection_vadd_smul_vsub_orthogonal_projection {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {s : affine_subspace ℝ P} [Nonempty ↥s] [complete_space ↥(affine_subspace.direction s)] {p₁ : P} (p₂ : P) (r : ℝ) (hp₁ : p₁ ∈ s) : coe_fn (reflection s) (r • (p₂ -ᵥ ↑(coe_fn (orthogonal_projection s) p₂)) +ᵥ p₁) = -(r • (p₂ -ᵥ ↑(coe_fn (orthogonal_projection s) p₂))) +ᵥ p₁ := reflection_orthogonal_vadd hp₁ (submodule.smul_mem (affine_subspace.direction sᗮ) r (vsub_orthogonal_projection_mem_direction_orthogonal s p₂)) /-- A set of points is cospherical if they are equidistant from some point. In two dimensions, this is the same thing as being concyclic. -/ def cospherical {P : Type u_2} [metric_space P] (ps : set P) := ∃ (center : P), ∃ (radius : ℝ), ∀ (p : P), p ∈ ps → dist p center = radius /-- The definition of `cospherical`. -/ theorem cospherical_def {P : Type u_2} [metric_space P] (ps : set P) : cospherical ps ↔ ∃ (center : P), ∃ (radius : ℝ), ∀ (p : P), p ∈ ps → dist p center = radius := iff.rfl /-- A subset of a cospherical set is cospherical. -/ theorem cospherical_subset {P : Type u_2} [metric_space P] {ps₁ : set P} {ps₂ : set P} (hs : ps₁ ⊆ ps₂) (hc : cospherical ps₂) : cospherical ps₁ := sorry /-- The empty set is cospherical. -/ theorem cospherical_empty {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] : cospherical ∅ := sorry /-- A single point is cospherical. -/ theorem cospherical_singleton {P : Type u_2} [metric_space P] (p : P) : cospherical (singleton p) := sorry /-- Two points are cospherical. -/ theorem cospherical_insert_singleton {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] (p₁ : P) (p₂ : P) : cospherical (insert p₁ (singleton p₂)) := sorry /-- Any three points in a cospherical set are affinely independent. -/ theorem cospherical.affine_independent {V : Type u_1} {P : Type u_2} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {s : set P} (hs : cospherical s) {p : fin (bit1 1) → P} (hps : set.range p ⊆ s) (hpi : function.injective p) : affine_independent ℝ p := sorry
69ee3ce25640a0a16a8ab135c37c4d950b9bc98d
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/field_theory/intermediate_field.lean
ac1e1187350ee9e6d1190ea2788977e7f421a31c
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,399
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import field_theory.subfield import field_theory.tower import ring_theory.algebraic /-! # Intermediate fields Let `L / K` be a field extension, given as an instance `algebra K L`. This file defines the type of fields in between `K` and `L`, `intermediate_field K L`. An `intermediate_field K L` is a subfield of `L` which contains (the image of) `K`, i.e. it is a `subfield L` and a `subalgebra K L`. ## Main definitions * `intermediate_field K L` : the type of intermediate fields between `K` and `L`. * `subalgebra.to_intermediate_field`: turns a subalgebra closed under `⁻¹` into an intermediate field * `subfield.to_intermediate_field`: turns a subfield containing the image of `K` into an intermediate field * `intermediate_field.map`: map an intermediate field along an `alg_hom` ## Implementation notes Intermediate fields are defined with a structure extending `subfield` and `subalgebra`. A `subalgebra` is closed under all operations except `⁻¹`, ## Tags intermediate field, field extension -/ open finite_dimensional open_locale big_operators variables (K L : Type*) [field K] [field L] [algebra K L] section set_option old_structure_cmd true /-- `S : intermediate_field K L` is a subset of `L` such that there is a field tower `L / S / K`. -/ structure intermediate_field extends subalgebra K L, subfield L /-- Reinterpret an `intermediate_field` as a `subalgebra`. -/ add_decl_doc intermediate_field.to_subalgebra /-- Reinterpret an `intermediate_field` as a `subfield`. -/ add_decl_doc intermediate_field.to_subfield end variables {K L} (S : intermediate_field K L) namespace intermediate_field instance : set_like (intermediate_field K L) L := ⟨intermediate_field.carrier, λ p q h, by cases p; cases q; congr'⟩ @[simp] lemma mem_carrier {s : intermediate_field K L} {x : L} : x ∈ s.carrier ↔ x ∈ s := iff.rfl /-- Two intermediate fields are equal if they have the same elements. -/ @[ext] theorem ext {S T : intermediate_field K L} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := set_like.ext h @[simp] lemma coe_to_subalgebra : (S.to_subalgebra : set L) = S := rfl @[simp] lemma coe_to_subfield : (S.to_subfield : set L) = S := rfl @[simp] lemma mem_mk (s : set L) (hK : ∀ x, algebra_map K L x ∈ s) (ho hm hz ha hn hi) (x : L) : x ∈ intermediate_field.mk s ho hm hz ha hK hn hi ↔ x ∈ s := iff.rfl @[simp] lemma mem_to_subalgebra (s : intermediate_field K L) (x : L) : x ∈ s.to_subalgebra ↔ x ∈ s := iff.rfl @[simp] lemma mem_to_subfield (s : intermediate_field K L) (x : L) : x ∈ s.to_subfield ↔ x ∈ s := iff.rfl /-- An intermediate field contains the image of the smaller field. -/ theorem algebra_map_mem (x : K) : algebra_map K L x ∈ S := S.algebra_map_mem' x /-- An intermediate field contains the ring's 1. -/ theorem one_mem : (1 : L) ∈ S := S.one_mem' /-- An intermediate field contains the ring's 0. -/ theorem zero_mem : (0 : L) ∈ S := S.zero_mem' /-- An intermediate field is closed under multiplication. -/ theorem mul_mem : ∀ {x y : L}, x ∈ S → y ∈ S → x * y ∈ S := S.mul_mem' /-- An intermediate field is closed under scalar multiplication. -/ theorem smul_mem {y : L} : y ∈ S → ∀ {x : K}, x • y ∈ S := S.to_subalgebra.smul_mem /-- An intermediate field is closed under addition. -/ theorem add_mem : ∀ {x y : L}, x ∈ S → y ∈ S → x + y ∈ S := S.add_mem' /-- An intermediate field is closed under subtraction -/ theorem sub_mem {x y : L} (hx : x ∈ S) (hy : y ∈ S) : x - y ∈ S := S.to_subfield.sub_mem hx hy /-- An intermediate field is closed under negation. -/ theorem neg_mem : ∀ {x : L}, x ∈ S → -x ∈ S := S.neg_mem' /-- An intermediate field is closed under inverses. -/ theorem inv_mem : ∀ {x : L}, x ∈ S → x⁻¹ ∈ S := S.inv_mem' /-- An intermediate field is closed under division. -/ theorem div_mem {x y : L} (hx : x ∈ S) (hy : y ∈ S) : x / y ∈ S := S.to_subfield.div_mem hx hy /-- Product of a list of elements in an intermediate_field is in the intermediate_field. -/ lemma list_prod_mem {l : list L} : (∀ x ∈ l, x ∈ S) → l.prod ∈ S := S.to_subfield.list_prod_mem /-- Sum of a list of elements in an intermediate field is in the intermediate_field. -/ lemma list_sum_mem {l : list L} : (∀ x ∈ l, x ∈ S) → l.sum ∈ S := S.to_subfield.list_sum_mem /-- Product of a multiset of elements in an intermediate field is in the intermediate_field. -/ lemma multiset_prod_mem (m : multiset L) : (∀ a ∈ m, a ∈ S) → m.prod ∈ S := S.to_subfield.multiset_prod_mem m /-- Sum of a multiset of elements in a `intermediate_field` is in the `intermediate_field`. -/ lemma multiset_sum_mem (m : multiset L) : (∀ a ∈ m, a ∈ S) → m.sum ∈ S := S.to_subfield.multiset_sum_mem m /-- Product of elements of an intermediate field indexed by a `finset` is in the intermediate_field. -/ lemma prod_mem {ι : Type*} {t : finset ι} {f : ι → L} (h : ∀ c ∈ t, f c ∈ S) : ∏ i in t, f i ∈ S := S.to_subfield.prod_mem h /-- Sum of elements in a `intermediate_field` indexed by a `finset` is in the `intermediate_field`. -/ lemma sum_mem {ι : Type*} {t : finset ι} {f : ι → L} (h : ∀ c ∈ t, f c ∈ S) : ∑ i in t, f i ∈ S := S.to_subfield.sum_mem h lemma pow_mem {x : L} (hx : x ∈ S) : ∀ (n : ℤ), x^n ∈ S | (n : ℕ) := by { rw gpow_coe_nat, exact S.to_subfield.pow_mem hx _, } | -[1+ n] := by { rw [gpow_neg_succ_of_nat], exact S.to_subfield.inv_mem (S.to_subfield.pow_mem hx _) } lemma gsmul_mem {x : L} (hx : x ∈ S) (n : ℤ) : n • x ∈ S := S.to_subfield.gsmul_mem hx n lemma coe_int_mem (n : ℤ) : (n : L) ∈ S := by simp only [← gsmul_one, gsmul_mem, one_mem] end intermediate_field /-- Turn a subalgebra closed under inverses into an intermediate field -/ def subalgebra.to_intermediate_field (S : subalgebra K L) (inv_mem : ∀ x ∈ S, x⁻¹ ∈ S) : intermediate_field K L := { neg_mem' := λ x, S.neg_mem, inv_mem' := inv_mem, .. S } @[simp] lemma to_subalgebra_to_intermediate_field (S : subalgebra K L) (inv_mem : ∀ x ∈ S, x⁻¹ ∈ S) : (S.to_intermediate_field inv_mem).to_subalgebra = S := by { ext, refl } @[simp] lemma to_intermediate_field_to_subalgebra (S : intermediate_field K L) (inv_mem : ∀ x ∈ S.to_subalgebra, x⁻¹ ∈ S) : S.to_subalgebra.to_intermediate_field inv_mem = S := by { ext, refl } /-- Turn a subfield of `L` containing the image of `K` into an intermediate field -/ def subfield.to_intermediate_field (S : subfield L) (algebra_map_mem : ∀ x, algebra_map K L x ∈ S) : intermediate_field K L := { algebra_map_mem' := algebra_map_mem, .. S } namespace intermediate_field /-- An intermediate field inherits a field structure -/ instance to_field : field S := S.to_subfield.to_field @[simp, norm_cast] lemma coe_add (x y : S) : (↑(x + y) : L) = ↑x + ↑y := rfl @[simp, norm_cast] lemma coe_neg (x : S) : (↑(-x) : L) = -↑x := rfl @[simp, norm_cast] lemma coe_mul (x y : S) : (↑(x * y) : L) = ↑x * ↑y := rfl @[simp, norm_cast] lemma coe_inv (x : S) : (↑(x⁻¹) : L) = (↑x)⁻¹ := rfl @[simp, norm_cast] lemma coe_zero : ((0 : S) : L) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : S) : L) = 1 := rfl @[simp, norm_cast] lemma coe_pow (x : S) (n : ℕ) : (↑(x ^ n) : L) = ↑x ^ n := begin induction n with n ih, { simp }, { simp [pow_succ, ih] } end instance algebra : algebra K S := S.to_subalgebra.algebra instance to_algebra {R : Type*} [semiring R] [algebra L R] : algebra S R := S.to_subalgebra.to_algebra instance is_scalar_tower_bot {R : Type*} [semiring R] [algebra L R] : is_scalar_tower S L R := is_scalar_tower.subalgebra _ _ _ S.to_subalgebra instance is_scalar_tower_mid {R : Type*} [semiring R] [algebra L R] [algebra K R] [is_scalar_tower K L R] : is_scalar_tower K S R := is_scalar_tower.subalgebra' _ _ _ S.to_subalgebra /-- Specialize `is_scalar_tower_mid` to the common case where the top field is `L` -/ instance is_scalar_tower_mid' : is_scalar_tower K S L := S.is_scalar_tower_mid variables {L' : Type*} [field L'] [algebra K L'] /-- If `f : L →+* L'` fixes `K`, `S.map f` is the intermediate field between `L'` and `K` such that `x ∈ S ↔ f x ∈ S.map f`. -/ def map (f : L →ₐ[K] L') : intermediate_field K L' := { inv_mem' := by { rintros _ ⟨x, hx, rfl⟩, exact ⟨x⁻¹, S.inv_mem hx, f.map_inv x⟩ }, neg_mem' := λ x hx, (S.to_subalgebra.map f).neg_mem hx, .. S.to_subalgebra.map f} /-- The embedding from an intermediate field of `L / K` to `L`. -/ def val : S →ₐ[K] L := S.to_subalgebra.val @[simp] theorem coe_val : ⇑S.val = coe := rfl @[simp] lemma val_mk {x : L} (hx : x ∈ S) : S.val ⟨x, hx⟩ = x := rfl variables {S} lemma to_subalgebra_injective {S S' : intermediate_field K L} (h : S.to_subalgebra = S'.to_subalgebra) : S = S' := by { ext, rw [← mem_to_subalgebra, ← mem_to_subalgebra, h] } variables (S) lemma set_range_subset : set.range (algebra_map K L) ⊆ S := S.to_subalgebra.range_subset lemma field_range_le : (algebra_map K L).field_range ≤ S.to_subfield := λ x hx, S.to_subalgebra.range_subset (by rwa [set.mem_range, ← ring_hom.mem_field_range]) @[simp] lemma to_subalgebra_le_to_subalgebra {S S' : intermediate_field K L} : S.to_subalgebra ≤ S'.to_subalgebra ↔ S ≤ S' := iff.rfl @[simp] lemma to_subalgebra_lt_to_subalgebra {S S' : intermediate_field K L} : S.to_subalgebra < S'.to_subalgebra ↔ S < S' := iff.rfl variables {S} section tower /-- Lift an intermediate_field of an intermediate_field -/ def lift1 {F : intermediate_field K L} (E : intermediate_field K F) : intermediate_field K L := map E (val F) /-- Lift an intermediate_field of an intermediate_field -/ def lift2 {F : intermediate_field K L} (E : intermediate_field F L) : intermediate_field K L := { carrier := E.carrier, zero_mem' := zero_mem E, add_mem' := λ x y, add_mem E, neg_mem' := λ x, neg_mem E, one_mem' := one_mem E, mul_mem' := λ x y, mul_mem E, inv_mem' := λ x, inv_mem E, algebra_map_mem' := λ x, algebra_map_mem E (algebra_map K F x) } instance has_lift1 {F : intermediate_field K L} : has_lift_t (intermediate_field K F) (intermediate_field K L) := ⟨lift1⟩ instance has_lift2 {F : intermediate_field K L} : has_lift_t (intermediate_field F L) (intermediate_field K L) := ⟨lift2⟩ @[simp] lemma mem_lift2 {F : intermediate_field K L} {E : intermediate_field F L} {x : L} : x ∈ (↑E : intermediate_field K L) ↔ x ∈ E := iff.rfl instance lift2_alg {F : intermediate_field K L} {E : intermediate_field F L} : algebra K E := { to_fun := (algebra_map F E).comp (algebra_map K F), map_zero' := ((algebra_map F E).comp (algebra_map K F)).map_zero, map_one' := ((algebra_map F E).comp (algebra_map K F)).map_one, map_add' := ((algebra_map F E).comp (algebra_map K F)).map_add, map_mul' := ((algebra_map F E).comp (algebra_map K F)).map_mul, smul := λ a b, (((algebra_map F E).comp (algebra_map K F)) a) * b, smul_def' := λ _ _, rfl, commutes' := λ a b, mul_comm (((algebra_map F E).comp (algebra_map K F)) a) b } instance lift2_tower {F : intermediate_field K L} {E : intermediate_field F L} : is_scalar_tower K F E := ⟨λ a b c, by { simp only [algebra.smul_def, ring_hom.map_mul, mul_assoc], refl }⟩ /-- `lift2` is isomorphic to the original `intermediate_field`. -/ def lift2_alg_equiv {F : intermediate_field K L} (E : intermediate_field F L) : (↑E : intermediate_field K L) ≃ₐ[K] E := { to_fun := λ x, x, inv_fun := λ x, x, left_inv := λ x, rfl, right_inv := λ x, rfl, map_add' := λ x y, rfl, map_mul' := λ x y, rfl, commutes' := λ x, rfl } end tower section finite_dimensional variables (F E : intermediate_field K L) instance finite_dimensional_left [finite_dimensional K L] : finite_dimensional K F := finite_dimensional.finite_dimensional_submodule F.to_subalgebra.to_submodule instance finite_dimensional_right [finite_dimensional K L] : finite_dimensional F L := right K F L @[simp] lemma dim_eq_dim_subalgebra : module.rank K F.to_subalgebra = module.rank K F := rfl @[simp] lemma finrank_eq_finrank_subalgebra : finrank K F.to_subalgebra = finrank K F := rfl variables {F} {E} @[simp] lemma to_subalgebra_eq_iff : F.to_subalgebra = E.to_subalgebra ↔ F = E := by { rw [set_like.ext_iff, set_like.ext'_iff, set.ext_iff], refl } lemma eq_of_le_of_finrank_le [finite_dimensional K L] (h_le : F ≤ E) (h_finrank : finrank K E ≤ finrank K F) : F = E := to_subalgebra_injective $ subalgebra.to_submodule_injective $ eq_of_le_of_finrank_le h_le h_finrank lemma eq_of_le_of_finrank_eq [finite_dimensional K L] (h_le : F ≤ E) (h_finrank : finrank K F = finrank K E) : F = E := eq_of_le_of_finrank_le h_le h_finrank.ge lemma eq_of_le_of_finrank_le' [finite_dimensional K L] (h_le : F ≤ E) (h_finrank : finrank F L ≤ finrank E L) : F = E := begin apply eq_of_le_of_finrank_le h_le, have h1 := finrank_mul_finrank K F L, have h2 := finrank_mul_finrank K E L, have h3 : 0 < finrank E L := finrank_pos, nlinarith, end lemma eq_of_le_of_finrank_eq' [finite_dimensional K L] (h_le : F ≤ E) (h_finrank : finrank F L = finrank E L) : F = E := eq_of_le_of_finrank_le' h_le h_finrank.le end finite_dimensional end intermediate_field /-- If `L/K` is algebraic, the `K`-subalgebras of `L` are all fields. -/ def subalgebra_equiv_intermediate_field (alg : algebra.is_algebraic K L) : subalgebra K L ≃o intermediate_field K L := { to_fun := λ S, S.to_intermediate_field (λ x hx, S.inv_mem_of_algebraic (alg (⟨x, hx⟩ : S))), inv_fun := λ S, S.to_subalgebra, left_inv := λ S, to_subalgebra_to_intermediate_field _ _, right_inv := λ S, to_intermediate_field_to_subalgebra _ _, map_rel_iff' := λ S S', iff.rfl } @[simp] lemma mem_subalgebra_equiv_intermediate_field (alg : algebra.is_algebraic K L) {S : subalgebra K L} {x : L} : x ∈ subalgebra_equiv_intermediate_field alg S ↔ x ∈ S := iff.rfl @[simp] lemma mem_subalgebra_equiv_intermediate_field_symm (alg : algebra.is_algebraic K L) {S : intermediate_field K L} {x : L} : x ∈ (subalgebra_equiv_intermediate_field alg).symm S ↔ x ∈ S := iff.rfl
8fffccddcad09d41cf6bc5abd2ffeea9ffb68cc7
fe84e287c662151bb313504482b218a503b972f3
/src/commutative_algebra/idempotent.lean
a80b32f91fea536cd93c0c978001d695a7080d2b
[]
no_license
NeilStrickland/lean_lib
91e163f514b829c42fe75636407138b5c75cba83
6a9563de93748ace509d9db4302db6cd77d8f92c
refs/heads/master
1,653,408,198,261
1,652,996,419,000
1,652,996,419,000
181,006,067
4
1
null
null
null
null
UTF-8
Lean
false
false
20,863
lean
import algebra.ring algebra.group_power group_theory.submonoid order.boolean_algebra import algebra.geom_sum import commutative_algebra.nilpotent commutative_algebra.regular import tactic.ring universe u variables {A : Type u} [comm_ring A] namespace commutative_algebra def is_idempotent (a : A) := a * a = a theorem is_idempotent' {a : A} : is_idempotent a ↔ a * (1 - a) = 0 := by { dsimp [is_idempotent], rw [mul_sub, mul_one,sub_eq_zero], exact comm} namespace is_idempotent /-- 0 and 1 are idempotent, and (1,0) and (0,1) are idempotent in a product ring. -/ theorem zero : is_idempotent (0 : A) := mul_zero 0 theorem one : is_idempotent (1 : A) := mul_one 1 theorem left {B : Type*} {C : Type*} [comm_ring B] [comm_ring C] : is_idempotent (⟨1, 0⟩ : B × C) := show prod.mk ((1 : B) * (1 : B)) ((0 : C) * (0 : C)) = ⟨1, 0⟩, by { rw [mul_one, mul_zero] } theorem right {B : Type*} {C : Type*} [comm_ring B] [comm_ring C] : is_idempotent (⟨0, 1⟩ : B × C) := show prod.mk ((0 : B) * (0 : B)) ((1 : C) * (1 : C)) = ⟨0, 1⟩, by { rw [mul_one, mul_zero] } /-- If a is idempotent, then (1 - 2 * a) ^ 2 = 1 -/ def invol (a : A) := 1 - 2 * a section one_variable variables {a : A} (ha : is_idempotent a) include ha /-- Positive powers of idempotents are idempotent -/ theorem pow : ∀ (n : ℕ), a ^ (n + 1) = a | 0 := by { rw [zero_add, pow_one] } | (n + 1) := by { have : a * a = a := ha, rw [pow_succ, pow n, this] } /-- If a is idempotent, then so is 1 - a. We call this (not a), because it is the negation operation for a boolean algebra structure on the set of idempotents. -/ theorem not : is_idempotent (1 - a) := by { rw [is_idempotent'] at ha ⊢, rw [mul_comm, sub_sub_cancel], exact ha } /-- 1 is the only regular idempotent -/ theorem regular (hr : is_regular a) : a = 1 := by { symmetry, rw [← sub_eq_zero], exact hr _ (is_idempotent'.mp ha) } /-- 0 is the only nilpotent idempotent -/ theorem nilpotent (hn : is_nilpotent a) : a = 0 := by { rcases hn with ⟨n, hn'⟩, rw [← pow ha n, pow_succ, hn', mul_zero] } theorem mul_self_invol : a * (invol a) = - a := by { dsimp [is_idempotent, invol] at *, rw [mul_sub, mul_one, two_mul, mul_add, ha], rw [← sub_sub, sub_self, zero_sub] } theorem invol_square : (invol a) * (invol a) = 1 := begin change (1 - 2 * a) * invol a = 1, rw [sub_mul, mul_assoc, mul_self_invol ha, one_mul], dsimp [invol], rw[mul_neg, sub_sub, add_neg_self, sub_zero] end end one_variable section two_variables variables {a b : A} (ha : is_idempotent a) (hb : is_idempotent b) include ha hb /-- The set of idempotents is a boolean algebra under the operations given below. -/ theorem and : is_idempotent (a * b) := show (a * b) * (a * b) = a * b, by { dsimp [is_idempotent] at ha hb, rw [mul_assoc, mul_comm b, mul_assoc, hb, ← mul_assoc, ha] } theorem add (hab : a * b = 0) : is_idempotent (a + b) := by { dsimp [is_idempotent] at *, rw [mul_add, add_mul, add_mul, mul_comm b a, ha, hb, hab, zero_add, add_zero] } theorem or : is_idempotent (a + b - a * b) := begin have : a + b - a * b = a + (1 - a) * b := by { rw [sub_mul, one_mul, add_sub] }, rw [this], apply add ha (and (not ha) hb), rw [← mul_assoc, is_idempotent'.mp ha, zero_mul], end theorem xor : is_idempotent (a + b - 2 * a * b) := begin let u := a * (1 - b), let v := (1 - a) * b, have : a + b - 2 * a * b = u + v := by { dsimp [u, v], ring }, rw [this], have hu := and ha (not hb), have hv := and (not ha) hb, have huv : u * v = 0 := by { dsimp [u, v], rw [mul_comm a, mul_assoc, ← mul_assoc a], have : a * (1 - a) = 0 := is_idempotent'.mp ha, rw [this, zero_mul, mul_zero] }, exact add hu hv huv end end two_variables /-- Idempotents are equal if their difference is nilpotent -/ theorem eq_of_sub_nilp {e₀ e₁ : A} (h₀ : is_idempotent e₀) (h₁ : is_idempotent e₁) (h : is_nilpotent (e₀ - e₁)) : e₀ = e₁ := begin dsimp [is_idempotent] at h₀ h₁, let x := e₀ - e₁, let u := 1 - 2 * e₀, let v := 1 + u * x, have hvx := calc v * x = (e₀ * e₀ - e₀) * (4 * e₁ - 2 * e₀ - 1) + (e₁ * e₁ - e₁) * (1 - 2 * e₀) : by { dsimp [v, u, x], ring } ... = 0 : by { rw [h₀, h₁, sub_self, sub_self, zero_mul, zero_mul, zero_add] }, have hv : is_regular v := regular.add_nilpotent_aux (is_regular_one A) (is_nilpotent_smul u h), have hx : x = 0 := hv x hvx, rw [← sub_eq_zero], exact hx, end /-- If e * (1 - e) is nilpotent, then there is a unique idempotent that is congruent to e mod nilpotents. -/ def lift : ∀ (e : A) (h : as_nilpotent (e * (1 - e))), A := λ e ⟨n, hx⟩, let y := (1 - e ^ (n + 2) - (1 - e) ^ (n + 2)) in e ^ (n + 2) * (finset.range n).sum (λ i, y ^ i) def lift_spec (e : A) (h : as_nilpotent (e * (1 - e))) : pprod (is_idempotent (lift e h)) (as_nilpotent ((lift e h) - e)) := begin rcases h with ⟨n, hx⟩, let x := e * (1 - e), change x ^ n = 0 at hx, let y := 1 - e ^ (n + 2) - (1 - e) ^ (n + 2), let u := (finset.range n).sum (λ i, y ^ i), let e₁ := e ^ (n + 2) * u, have : lift e ⟨n, hx⟩ = e₁ := rfl, rw [this], let f := λ (i : ℕ), e ^ i * (1 - e) ^ (n + 2 - i) * nat.choose (n + 2) i, let z := (finset.range (n + 1)).sum (λ j, e ^ j * (1 - e) ^ (n - j) * (nat.choose (n + 2) (j + 1))), let xz := (finset.range (n + 1)).sum (f ∘ nat.succ), have hxz : x * z = xz := by { dsimp [xz, x], rw [finset.mul_sum], apply finset.sum_congr rfl, intros i hi, replace hi : i ≤ n := nat.le_of_lt_succ (finset.mem_range.mp hi), have : (f ∘ nat.succ) i = f (i + 1) := rfl, rw [this], dsimp [f], have : n + 2 - (i + 1) = (n - i) + 1 := calc n + 2 - (i + 1) = n + 1 - i : by { rw [nat.succ_sub_succ] } ... = (i + (n - i)) + 1 - i : by { rw [nat.add_sub_of_le hi] } ... = (n - i) + 1 : by { simp only [add_comm, add_assoc, nat.add_sub_cancel_left] }, rw [this, pow_succ, pow_succ], repeat { rw [mul_assoc] }, congr' 1, repeat { rw [← mul_assoc] }, rw [mul_comm (1 - e) (e ^ i)], }, have hf₀ : f 0 = (1 - e) ^ (n + 2) := by { dsimp [f], rw [nat.choose, nat.cast_one, pow_zero, one_mul, mul_one] }, have hf₁ := finset.sum_range_succ' f (n + 1), rw[hf₀] at hf₁, have hf₂ : f (n + 2) = e ^ (n + 2) := by { dsimp [f], rw [nat.choose_self, nat.cast_one, nat.sub_self, pow_zero, mul_one, mul_one] }, have hf₃ := finset.sum_range_succ f (n + 2), rw[hf₂] at hf₃, have := calc (1 : A) = (1 : A) ^ (n + 2) : (one_pow (n + 2)).symm ... = (e + (1 - e)) ^ (n + 2) : by { congr, rw [add_sub, add_comm, add_sub_cancel] } ... = (finset.range (n + 2).succ).sum f : add_pow e (1 - e) (n + 2) ... = ((finset.range (n + 2)).sum f) + e ^ (n + 2): hf₃ ... = (xz + (1 - e) ^ (n + 2)) + e ^ (n + 2) : by { rw [hf₁] } ... = (x * z + (1 - e) ^ (n + 2)) + e ^ (n + 2) : by { rw [hxz] }, have hxyz := calc y = 1 - e ^ (n + 2) - (1 - e) ^ (n + 2) : rfl ... = ((x * z + (1 - e) ^ (n + 2)) + e ^ (n + 2)) - e ^ (n + 2) - (1 - e) ^ (n + 2) : by { congr' 2 } ... = x * z : by { simp only [sub_eq_add_neg, add_comm, add_left_comm, add_neg_cancel_left, add_neg_cancel_right] }, have hy : y ^ n = 0 := by { rw [hxyz, mul_pow, hx, zero_mul] }, have hu : u * (y - 1) = y ^ n - 1 := geom_sum_mul y n, rw [mul_comm, hy, zero_sub] at hu, replace hu := congr_arg has_neg.neg hu, rw [neg_neg, neg_mul_eq_neg_mul, neg_sub] at hu, have : 1 - y = e ^ (n + 2) + (1 - e) ^ (n + 2) := calc 1 - y = 1 - (1 - e ^ (n + 2) - (1 - e) ^ (n + 2)) : by { simp only [y] } ... = e ^ (n + 2) + (1 - e) ^ (n + 2) : by rw [sub_sub, sub_sub_cancel], let hu' := hu, rw [this] at hu', have := calc 1 - e₁ = (e ^ (n + 2) + (1 - e) ^ (n + 2)) * u - e₁ : by { rw [hu'] } ... = e ^ (n + 2) * u + (1 - e) ^ (n + 2) * u - e ^ (n + 2) * u : by { rw [add_mul] } ... = (1 - e) ^ (n + 2) * u : by { rw [add_comm, add_sub_cancel] }, have := calc e₁ * (1 - e₁) = (e ^ (n + 2) * u) * (1 - e₁) : rfl ... = u * (e ^ (n + 2) * (1 - e₁)) : by { rw [mul_comm (e ^ (n + 2))], rw [← mul_assoc] } ... = u * (e ^ (n + 2) * (1 - e) ^ (n + 2) * u) : by { rw [this, mul_assoc] } ... = u * (x ^ (n + 2) * u) : by { rw [mul_pow, pow_add] } ... = 0 : by { rw [pow_add, hx, zero_mul, zero_mul, mul_zero] }, split, exact is_idempotent'.mpr this, let w := geom_sum₂ 1 e (n + 1), have hw : x * w = e - e ^ (n + 2) := calc x * w = e * (w * (1 - e)) : by { dsimp [x], rw [mul_assoc, mul_comm _ w] } ... = e * (1 - e ^ (n + 1)) : by { rw [geom_sum₂_mul 1 e (n + 1), one_pow] } ... = e - e ^ (n + 2) : by { rw [mul_sub, mul_one, pow_succ e (n + 1)] }, have hu'' : u = 1 + x * z * u := by { rw [sub_mul, hxyz, one_mul] at hu, rw [← hu, sub_add_cancel], }, have := calc e₁ - e = e ^ (n + 2) * u - e : rfl ... = e ^ (n + 2) * (1 + x * z * u) - e : by { congr' 2 } ... = (e ^ (n + 2) * (x * z * u) + e ^ (n + 2)) - e : by { rw [mul_add, mul_one, add_comm] } ... = x * (e ^ (n + 2) * z * u) - (e - e ^ (n + 2)) : by { rw [← sub_add, sub_eq_add_neg, sub_eq_add_neg], rw [← mul_assoc, ← mul_assoc, mul_comm (e ^ (n + 2))], repeat { rw [add_assoc] }, rw [add_comm (e ^ (n + 2))], repeat { rw [mul_assoc] } } ... = x * (e ^ (n + 2) * z * u - w) : by { rw [mul_sub, hw] }, have : (e₁ - e) ^ n = 0 := by { rw [this, mul_pow, hx, zero_mul] }, exact ⟨n, this⟩, end theorem lift_unique (e e₁ : A) (h : as_nilpotent (e * (1 - e))) (hi : is_idempotent e₁) (hn : is_nilpotent (e₁ - e)) : e₁ = lift e h := begin rcases lift_spec e h with ⟨hi', hn'⟩, apply eq_of_sub_nilp hi hi', have : e₁ - lift e h = (e₁ - e) - (lift e h - e) := by { rw [sub_sub_sub_cancel_right] }, rw [this], apply is_nilpotent_sub hn ⟨hn'⟩ end end is_idempotent namespace is_idempotent variables {e : A} (he : is_idempotent e) include he /-- An idempotent e gives a splitting of the form A ≃ B × C. The first factor will be denoted by (axis he), where he is the proof that e is idempotent. -/ def axis := {b : A // b * e = b} namespace axis instance : has_coe (axis he) A := ⟨subtype.val⟩ theorem eq (b₁ b₂ : axis he) : (b₁ : A) = (b₂ : A) → b₁ = b₂ := subtype.eq def mk (b : A) (hb : b * e = b) : axis he := ⟨b, hb⟩ theorem coe_mk {b : A} (hb : b * e = b) : ((mk he b hb) : A) = b := rfl instance : has_zero (axis he) := ⟨⟨(0 : A), zero_mul e⟩⟩ instance : has_one (axis he) := ⟨⟨e, he⟩⟩ instance : has_neg (axis he) := ⟨λ b, axis.mk he (- b.val) (by { rw [← neg_mul_eq_neg_mul, b.property] })⟩ instance : has_add (axis he) := ⟨λ b₁ b₂, axis.mk he (b₁.val + b₂.val) (by { rw [add_mul, b₁.property, b₂.property] })⟩ instance : has_mul (axis he) := ⟨λ b₁ b₂, axis.mk he (b₁.val * b₂.val) (by { rw [mul_assoc, b₂.property] })⟩ @[simp] theorem zero_coe : ((0 : axis he) : A) = 0 := rfl @[simp] theorem one_coe : ((1 : axis he) : A) = e := rfl @[simp] theorem neg_coe (b : axis he) : (((- b) : axis he) : A) = - b := rfl @[simp] theorem add_coe (b₁ b₂ : axis he) : ((b₁ + b₂ : axis he) : A) = b₁ + b₂ := rfl @[simp] theorem mul_coe (b₁ b₂ : axis he) : ((b₁ * b₂ : axis he) : A) = b₁ * b₂ := rfl instance : comm_ring (axis he) := begin refine_struct { zero := has_zero.zero, add := (+), neg := has_neg.neg, sub := λ a b, a + (-b), one := has_one.one, mul := (*), nsmul := nsmul_rec, npow := npow_rec, zsmul := zsmul_rec, nsmul_zero' := λ x, rfl, nsmul_succ' := λ n x, rfl, zsmul_zero' := λ x, rfl, zsmul_succ' := λ n x, rfl, zsmul_neg' := λ n x, rfl, npow_zero' := λ x, rfl, npow_succ' := λ n x, rfl }; try { rintro a }; try { rintro b }; try { rintro c }; apply eq; repeat { rw[add_coe] }; repeat { rw[neg_coe] }; repeat { rw[mul_coe] }; repeat { rw[add_coe] }; repeat { rw[zero_coe] }; repeat { rw[one_coe] }, { rw[add_assoc] }, { rw[zero_add] }, { rw[add_zero] }, { rw[neg_add_self] }, { rw[add_comm] }, { rw[mul_assoc] }, { rw[mul_comm], exact a.property }, { exact a.property }, { rw[mul_add] }, { rw[add_mul] }, { rw[mul_comm] } end def proj : A →+* axis he := { to_fun := λ a, ⟨a * e, by { dsimp [is_idempotent] at he, rw [mul_assoc, he] }⟩, map_zero' := by { apply eq, change 0 * e = 0, exact zero_mul e }, map_one' := by { apply eq, change 1 * e = e, exact one_mul e }, map_add' := λ a b, by { apply eq, change (a + b) * e = a * e + b * e, rw [add_mul] }, map_mul' := λ a b, by { dsimp [is_idempotent] at he, apply eq, change (a * b) * e = (a * e) * (b * e), rw [mul_assoc a e, ← mul_assoc e b e, mul_comm e b, mul_assoc b e, he, mul_assoc] } } def split : A →+* (axis he) × (axis (is_idempotent.not he)) := let he' := is_idempotent.not he in { to_fun := λ a, ⟨(proj he a), (proj (is_idempotent.not he) a)⟩, map_zero' := by { rw[(proj he).map_zero, (proj _).map_zero], refl }, map_one' := by { rw[(proj he).map_one, (proj _).map_one], refl }, map_add' := λ a b, by { rw[(proj he).map_add, (proj _).map_add], refl }, map_mul' := λ a b, by { rw[(proj he).map_mul, (proj _).map_mul], refl } } theorem mul_eq_zero (b : axis he) (c : axis (is_idempotent.not he)) : (b : A) * (c : A) = 0 := begin rcases b with ⟨b, hb⟩, rcases c with ⟨c, hc⟩, change b * c = 0, exact calc b * c = (b * e) * (c * (1 - e)) : by rw [hb, hc] ... = b * (e * (1 - e)) * c : by { rw [mul_comm c, mul_assoc, mul_assoc, mul_assoc] } ... = 0 : by { rw [is_idempotent'.mp he, mul_zero, zero_mul] } end def combine : (axis he) × (axis (is_idempotent.not he)) →+* A := { to_fun := λ bc, (bc.1 : A) + (bc.2 : A), map_zero' := by { change ((0 : axis he) : A) + ((0 : axis (is_idempotent.not he)) : A) = 0, rw[zero_coe, zero_coe, zero_add] }, map_one' := by { change e + (1 - e) = 1, rw [add_sub_cancel'_right] }, map_add' := λ bc₁ bc₂, by { rcases bc₁ with ⟨⟨b₁, hb₁⟩, ⟨c₁, hc₁⟩⟩, rcases bc₂ with ⟨⟨b₂, hb₂⟩, ⟨c₂, hc₂⟩⟩, change (b₁ + b₂) + (c₁ + c₂) = (b₁ + c₁) + (b₂ + c₂), rw [add_assoc, ← add_assoc b₂, add_comm b₂ c₁, add_assoc, add_assoc] }, map_mul' := λ bc₁ bc₂, by { rcases bc₁ with ⟨⟨b₁, hb₁⟩, ⟨c₁, hc₁⟩⟩, rcases bc₂ with ⟨⟨b₂, hb₂⟩, ⟨c₂, hc₂⟩⟩, change (b₁ * b₂) + (c₁ * c₂) = (b₁ + c₁) * (b₂ + c₂), have ebc : b₁ * c₂ = 0 := mul_eq_zero he ⟨b₁, hb₁⟩ ⟨c₂, hc₂⟩, have ecb : b₂ * c₁ = 0 := mul_eq_zero he ⟨b₂, hb₂⟩ ⟨c₁, hc₁⟩, rw [mul_comm] at ecb, rw [mul_add, add_mul, add_mul, ebc, ecb, zero_add, add_zero] } } theorem combine_split (a : A) : combine he (split he a) = a := by { change a * e + a * (1 - e) = a, rw [mul_sub, mul_one, add_sub_cancel'_right] } theorem split_combine (bc : (axis he) × (axis (is_idempotent.not he))) : split he (combine he bc) = bc := begin have he' : e * (1 - e) = 0 := is_idempotent'.mp he, rcases bc with ⟨⟨b, hb⟩, ⟨c, hc⟩⟩, ext, { change (b + c) * e = b, rw [← hc, add_mul, hb, mul_assoc, mul_comm (1 - e), he', mul_zero, add_zero] }, { change (b + c) * (1 - e) = c, rw [← hb, add_mul, hc, mul_assoc, he', mul_zero, zero_add] } end end axis end is_idempotent variable (A) def idempotent := {a : A // is_idempotent a} variable {A} namespace idempotent variables (a b c : idempotent A) instance : has_coe (idempotent A) A := ⟨subtype.val⟩ theorem eq (a₁ a₂ : idempotent A) : (a₁ : A) = (a₂ : A) → a₁ = a₂ := subtype.eq theorem mul_self : (a * a : A) = a := a.property theorem mul_not : (a * (1 - a) : A) = 0 := is_idempotent'.mp a.property instance : has_le (idempotent A) := ⟨λ a b, (a * b : A) = a⟩ instance : has_bot (idempotent A) := ⟨⟨0, is_idempotent.zero⟩⟩ instance : has_top (idempotent A) := ⟨⟨1, is_idempotent.one⟩⟩ instance : has_compl (idempotent A) := ⟨λ a, ⟨((1 - a) : A), is_idempotent.not a.property⟩⟩ instance : has_inf (idempotent A) := ⟨λ a b, ⟨a * b, is_idempotent.and a.property b.property⟩⟩ instance : has_sup (idempotent A) := ⟨λ a b, ⟨a + b - a * b, is_idempotent.or a.property b.property⟩⟩ theorem le_iff {a b : idempotent A} : a ≤ b ↔ (a * b : A) = a := by { refl } theorem bot_coe : ((⊥ : idempotent A) : A) = 0 := rfl theorem top_coe : ((⊤ : idempotent A) : A) = 1 := rfl theorem compl_coe : ((aᶜ : idempotent A) : A) = 1 - a := rfl theorem inf_coe : ((a ⊓ b : idempotent A) : A) = a * b := rfl theorem sup_coe : ((a ⊔ b : idempotent A) : A) = a + b - a * b := rfl theorem compl_compl : aᶜᶜ = a := by { apply eq, rw [compl_coe, compl_coe, sub_sub_cancel] } theorem compl_inj {a b : idempotent A} (h : aᶜ = bᶜ) : a = b := by { rw [← compl_compl a, ← compl_compl b, h] } theorem compl_le_compl {a b : idempotent A} : a ≤ b ↔ bᶜ ≤ aᶜ := begin rw [le_iff, le_iff, compl_coe, compl_coe, mul_sub, sub_mul, sub_mul], rw [mul_one, mul_one, one_mul, sub_sub, mul_comm (b : A)], rw[sub_right_inj], split, { intro h, rw [h, sub_self, add_zero] }, { intro h, symmetry, rw [← sub_eq_zero], exact (add_right_inj (b : A)).mp (h.trans (add_zero (b : A)).symm) } end theorem compl_bot : (⊥ : idempotent A)ᶜ = ⊤ := by { apply eq, rw [compl_coe, bot_coe, top_coe, sub_zero] } theorem compl_sup : (a ⊔ b)ᶜ = aᶜ ⊓ bᶜ := by { apply eq, rw [compl_coe, sup_coe, inf_coe, compl_coe, compl_coe], ring } theorem compl_top : (⊤ : idempotent A)ᶜ = ⊥ := by { apply eq, rw [compl_coe, bot_coe, top_coe, sub_self] } theorem compl_inf : (a ⊓ b)ᶜ = aᶜ ⊔ bᶜ := by { apply compl_inj, rw [compl_sup, compl_compl, compl_compl, compl_compl] } theorem le_refl : a ≤ a := by { rw [le_iff, a.mul_self] } theorem le_antisymm {a b : idempotent A} (hab : a ≤ b) (hba : b ≤ a) : a = b := by { apply eq, rw [le_iff] at *, rw [mul_comm] at hba, exact hab.symm.trans hba } theorem le_trans {a b c : idempotent A} (hab : a ≤ b) (hbc : b ≤ c) : a ≤ c := by { rw [le_iff] at *, exact calc ((a * c) : A) = a * b * c : by rw [hab] ... = a : by rw [mul_assoc, hbc, hab] } theorem le_top : a ≤ ⊤ := by rw [le_iff, top_coe, mul_one] theorem le_inf (hab : a ≤ b) (hac : a ≤ c) : a ≤ b ⊓ c := by { rw [le_iff] at *, rw [inf_coe, ← mul_assoc, hab, hac] } theorem inf_le_left : a ⊓ b ≤ a := by { rw [le_iff, inf_coe, mul_comm, ← mul_assoc, a.mul_self] } theorem inf_le_right : a ⊓ b ≤ b := by { rw [le_iff, inf_coe, mul_assoc, b.mul_self] } theorem bot_le : ⊥ ≤ a := by { rw [le_iff, bot_coe, zero_mul] } theorem sup_le (hac : a ≤ c) (hbc : b ≤ c) : a ⊔ b ≤ c := by { rw [compl_le_compl] at *, rw [compl_sup], exact le_inf _ _ _ hac hbc } theorem le_sup_left : a ≤ a ⊔ b := by { rw [compl_le_compl, compl_sup], apply inf_le_left } theorem le_sup_right : b ≤ a ⊔ b := by { rw [compl_le_compl, compl_sup], apply inf_le_right } theorem inf_sup_distrib : a ⊓ (b ⊔ c) = (a ⊓ b) ⊔ (a ⊓ c) := by { apply eq, simp only [inf_coe, sup_coe, mul_add, mul_sub], congr' 1, rw [← mul_assoc, ← mul_assoc], congr' 1, rw [mul_assoc, mul_comm (b : A), ← mul_assoc, a.mul_self] } theorem sup_inf_distrib : a ⊔ (b ⊓ c) = (a ⊔ b) ⊓ (a ⊔ c) := by { apply compl_inj, rw [compl_sup, compl_inf], rw[compl_inf, compl_sup, compl_sup, inf_sup_distrib] } theorem inf_compl_eq_bot (a : idempotent A) : a ⊓ aᶜ = ⊥ := by { apply eq, rw [inf_coe, bot_coe, compl_coe, mul_not] } theorem sup_compl_eq_top (a : idempotent A) : a ⊔ aᶜ = ⊤ := by { apply compl_inj, rw [compl_sup, compl_top, inf_compl_eq_bot] } instance : boolean_algebra (idempotent A) := boolean_algebra.of_core { le := has_le.le, bot := ⊥, top := ⊤, sup := has_sup.sup, inf := has_inf.inf, compl := has_compl.compl, le_refl := le_refl, le_antisymm := λ a b hab hba, le_antisymm hab hba, le_trans := λ a b c hab hbc, le_trans hab hbc, bot_le := bot_le, le_top := le_top, le_inf := le_inf, inf_le_left := inf_le_left, inf_le_right := inf_le_right, sup_le := sup_le, le_sup_left := le_sup_left, le_sup_right := le_sup_right, le_sup_inf := λ a b c, by { rw [sup_inf_distrib] }, inf_compl_le_bot := λ a, by { rw[inf_compl_eq_bot] }, top_le_sup_compl := λ a, by { rw[sup_compl_eq_top] } } end idempotent end commutative_algebra
a5fd0f9e0812c1c0ed0c2dba7fe1f3c1bec36940
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/group_theory/subgroup.lean
668e30f6ec2493f5b625ed49310b3f0711a23cf6
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
52,621
lean
/- Copyright (c) 2020 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import group_theory.submonoid import algebra.group.conj import order.modular_lattice /-! # Subgroups This file defines multiplicative and additive subgroups as an extension of submonoids, in a bundled form (unbundled subgroups are in `deprecated/subgroups.lean`). We prove subgroups of a group form a complete lattice, and results about images and preimages of subgroups under group homomorphisms. The bundled subgroups use bundled monoid homomorphisms. There are also theorems about the subgroups generated by an element or a subset of a group, defined both inductively and as the infimum of the set of subgroups containing a given element/subset. Special thanks goes to Amelia Livingston and Yury Kudryashov for their help and inspiration. ## Main definitions Notation used here: - `G N` are `group`s - `A` is an `add_group` - `H K` are `subgroup`s of `G` or `add_subgroup`s of `A` - `x` is an element of type `G` or type `A` - `f g : N →* G` are group homomorphisms - `s k` are sets of elements of type `G` Definitions in the file: * `subgroup G` : the type of subgroups of a group `G` * `add_subgroup A` : the type of subgroups of an additive group `A` * `complete_lattice (subgroup G)` : the subgroups of `G` form a complete lattice * `subgroup.closure k` : the minimal subgroup that includes the set `k` * `subgroup.subtype` : the natural group homomorphism from a subgroup of group `G` to `G` * `subgroup.gi` : `closure` forms a Galois insertion with the coercion to set * `subgroup.comap H f` : the preimage of a subgroup `H` along the group homomorphism `f` is also a subgroup * `subgroup.map f H` : the image of a subgroup `H` along the group homomorphism `f` is also a subgroup * `subgroup.prod H K` : the product of subgroups `H`, `K` of groups `G`, `N` respectively, `H × K` is a subgroup of `G × N` * `monoid_hom.range f` : the range of the group homomorphism `f` is a subgroup * `monoid_hom.ker f` : the kernel of a group homomorphism `f` is the subgroup of elements `x : G` such that `f x = 1` * `monoid_hom.eq_locus f g` : given group homomorphisms `f`, `g`, the elements of `G` such that `f x = g x` form a subgroup of `G` ## Implementation notes Subgroup inclusion is denoted `≤` rather than `⊆`, although `∈` is defined as membership of a subgroup's underlying set. ## Tags subgroup, subgroups -/ open_locale big_operators variables {G : Type*} [group G] variables {A : Type*} [add_group A] set_option old_structure_cmd true /-- A subgroup of a group `G` is a subset containing 1, closed under multiplication and closed under multiplicative inverse. -/ structure subgroup (G : Type*) [group G] extends submonoid G := (inv_mem' {x} : x ∈ carrier → x⁻¹ ∈ carrier) /-- An additive subgroup of an additive group `G` is a subset containing 0, closed under addition and additive inverse. -/ structure add_subgroup (G : Type*) [add_group G] extends add_submonoid G:= (neg_mem' {x} : x ∈ carrier → -x ∈ carrier) attribute [to_additive] subgroup attribute [to_additive add_subgroup.to_add_submonoid] subgroup.to_submonoid /-- Reinterpret a `subgroup` as a `submonoid`. -/ add_decl_doc subgroup.to_submonoid /-- Reinterpret an `add_subgroup` as an `add_submonoid`. -/ add_decl_doc add_subgroup.to_add_submonoid /-- Map from subgroups of group `G` to `add_subgroup`s of `additive G`. -/ def subgroup.to_add_subgroup {G : Type*} [group G] (H : subgroup G) : add_subgroup (additive G) := { neg_mem' := H.inv_mem', .. submonoid.to_add_submonoid H.to_submonoid} /-- Map from `add_subgroup`s of `additive G` to subgroups of `G`. -/ def subgroup.of_add_subgroup {G : Type*} [group G] (H : add_subgroup (additive G)) : subgroup G := { inv_mem' := H.neg_mem', .. submonoid.of_add_submonoid H.to_add_submonoid} /-- Map from `add_subgroup`s of `add_group G` to subgroups of `multiplicative G`. -/ def add_subgroup.to_subgroup {G : Type*} [add_group G] (H : add_subgroup G) : subgroup (multiplicative G) := { inv_mem' := H.neg_mem', .. add_submonoid.to_submonoid H.to_add_submonoid} /-- Map from subgroups of `multiplicative G` to `add_subgroup`s of `add_group G`. -/ def add_subgroup.of_subgroup {G : Type*} [add_group G] (H : subgroup (multiplicative G)) : add_subgroup G := { neg_mem' := H.inv_mem', .. add_submonoid.of_submonoid H.to_submonoid } /-- Subgroups of group `G` are isomorphic to additive subgroups of `additive G`. -/ def subgroup.add_subgroup_equiv (G : Type*) [group G] : subgroup G ≃ add_subgroup (additive G) := { to_fun := subgroup.to_add_subgroup, inv_fun := subgroup.of_add_subgroup, left_inv := λ x, by cases x; refl, right_inv := λ x, by cases x; refl } namespace subgroup @[to_additive] instance : has_coe (subgroup G) (set G) := { coe := subgroup.carrier } @[simp, to_additive] lemma coe_to_submonoid (K : subgroup G) : (K.to_submonoid : set G) = K := rfl @[to_additive] instance : has_mem G (subgroup G) := ⟨λ m K, m ∈ (K : set G)⟩ @[to_additive] instance : has_coe_to_sort (subgroup G) := ⟨_, λ G, (G : Type*)⟩ @[simp, norm_cast, to_additive] lemma mem_coe {K : subgroup G} {g : G} : g ∈ (K : set G) ↔ g ∈ K := iff.rfl @[simp, norm_cast, to_additive] lemma coe_coe (K : subgroup G) : ↥(K : set G) = K := rfl -- note that `to_additive` transfers the `simp` attribute over but not the `norm_cast` attribute attribute [norm_cast] add_subgroup.mem_coe attribute [norm_cast] add_subgroup.coe_coe @[to_additive] instance (K : subgroup G) [d : decidable_pred K.carrier] [fintype G] : fintype K := show fintype {g : G // g ∈ K.carrier}, from infer_instance end subgroup @[to_additive] protected lemma subgroup.exists {K : subgroup G} {p : K → Prop} : (∃ x : K, p x) ↔ ∃ x ∈ K, p ⟨x, ‹x ∈ K›⟩ := set_coe.exists @[to_additive] protected lemma subgroup.forall {K : subgroup G} {p : K → Prop} : (∀ x : K, p x) ↔ ∀ x ∈ K, p ⟨x, ‹x ∈ K›⟩ := set_coe.forall namespace subgroup variables (H K : subgroup G) /-- Copy of a subgroup with a new `carrier` equal to the old one. Useful to fix definitional equalities.-/ @[to_additive "Copy of an additive subgroup with a new `carrier` equal to the old one. Useful to fix definitional equalities"] protected def copy (K : subgroup G) (s : set G) (hs : s = K) : subgroup G := { carrier := s, one_mem' := hs.symm ▸ K.one_mem', mul_mem' := hs.symm ▸ K.mul_mem', inv_mem' := hs.symm ▸ K.inv_mem' } /- Two subgroups are equal if the underlying set are the same. -/ @[to_additive "Two `add_group`s are equal if the underlying subsets are equal."] theorem ext' {H K : subgroup G} (h : (H : set G) = K) : H = K := by { cases H, cases K, congr, exact h } /- Two subgroups are equal if and only if the underlying subsets are equal. -/ @[to_additive "Two `add_subgroup`s are equal if and only if the underlying subsets are equal."] protected theorem ext'_iff {H K : subgroup G} : H = K ↔ (H : set G) = K := ⟨λ h, h ▸ rfl, ext'⟩ /-- Two subgroups are equal if they have the same elements. -/ @[ext, to_additive "Two `add_subgroup`s are equal if they have the same elements."] theorem ext {H K : subgroup G} (h : ∀ x, x ∈ H ↔ x ∈ K) : H = K := ext' $ set.ext h attribute [ext] add_subgroup.ext /-- A subgroup contains the group's 1. -/ @[to_additive "An `add_subgroup` contains the group's 0."] theorem one_mem : (1 : G) ∈ H := H.one_mem' /-- A subgroup is closed under multiplication. -/ @[to_additive "An `add_subgroup` is closed under addition."] theorem mul_mem {x y : G} : x ∈ H → y ∈ H → x * y ∈ H := λ hx hy, H.mul_mem' hx hy /-- A subgroup is closed under inverse. -/ @[to_additive "An `add_subgroup` is closed under inverse."] theorem inv_mem {x : G} : x ∈ H → x⁻¹ ∈ H := λ hx, H.inv_mem' hx /-- A subgroup is closed under division. -/ @[to_additive "An `add_subgroup` is closed under subtraction."] theorem div_mem {x y : G} (hx : x ∈ H) (hy : y ∈ H) : x / y ∈ H := by simpa only [div_eq_mul_inv] using H.mul_mem' hx (H.inv_mem' hy) @[simp, to_additive] theorem inv_mem_iff {x : G} : x⁻¹ ∈ H ↔ x ∈ H := ⟨λ h, inv_inv x ▸ H.inv_mem h, H.inv_mem⟩ @[to_additive] lemma mul_mem_cancel_right {x y : G} (h : x ∈ H) : y * x ∈ H ↔ y ∈ H := ⟨λ hba, by simpa using H.mul_mem hba (H.inv_mem h), λ hb, H.mul_mem hb h⟩ @[to_additive] lemma mul_mem_cancel_left {x y : G} (h : x ∈ H) : x * y ∈ H ↔ y ∈ H := ⟨λ hab, by simpa using H.mul_mem (H.inv_mem h) hab, H.mul_mem h⟩ /-- Product of a list of elements in a subgroup is in the subgroup. -/ @[to_additive "Sum of a list of elements in an `add_subgroup` is in the `add_subgroup`."] lemma list_prod_mem {l : list G} : (∀ x ∈ l, x ∈ K) → l.prod ∈ K := K.to_submonoid.list_prod_mem /-- Product of a multiset of elements in a subgroup of a `comm_group` is in the subgroup. -/ @[to_additive "Sum of a multiset of elements in an `add_subgroup` of an `add_comm_group` is in the `add_subgroup`."] lemma multiset_prod_mem {G} [comm_group G] (K : subgroup G) (g : multiset G) : (∀ a ∈ g, a ∈ K) → g.prod ∈ K := K.to_submonoid.multiset_prod_mem g /-- Product of elements of a subgroup of a `comm_group` indexed by a `finset` is in the subgroup. -/ @[to_additive "Sum of elements in an `add_subgroup` of an `add_comm_group` indexed by a `finset` is in the `add_subgroup`."] lemma prod_mem {G : Type*} [comm_group G] (K : subgroup G) {ι : Type*} {t : finset ι} {f : ι → G} (h : ∀ c ∈ t, f c ∈ K) : ∏ c in t, f c ∈ K := K.to_submonoid.prod_mem h lemma pow_mem {x : G} (hx : x ∈ K) : ∀ n : ℕ, x ^ n ∈ K := K.to_submonoid.pow_mem hx lemma gpow_mem {x : G} (hx : x ∈ K) : ∀ n : ℤ, x ^ n ∈ K | (int.of_nat n) := pow_mem _ hx n | -[1+ n] := K.inv_mem $ K.pow_mem hx n.succ /-- Construct a subgroup from a nonempty set that is closed under division. -/ @[to_additive "Construct a subgroup from a nonempty set that is closed under subtraction"] def of_div (s : set G) (hsn : s.nonempty) (hs : ∀ x y ∈ s, x * y⁻¹ ∈ s) : subgroup G := have one_mem : (1 : G) ∈ s, from let ⟨x, hx⟩ := hsn in by simpa using hs x x hx hx, have inv_mem : ∀ x, x ∈ s → x⁻¹ ∈ s, from λ x hx, by simpa using hs 1 x one_mem hx, { carrier := s, one_mem' := one_mem, inv_mem' := inv_mem, mul_mem' := λ x y hx hy, by simpa using hs x y⁻¹ hx (inv_mem y hy) } /-- A subgroup of a group inherits a multiplication. -/ @[to_additive "An `add_subgroup` of an `add_group` inherits an addition."] instance has_mul : has_mul H := H.to_submonoid.has_mul /-- A subgroup of a group inherits a 1. -/ @[to_additive "An `add_subgroup` of an `add_group` inherits a zero."] instance has_one : has_one H := H.to_submonoid.has_one /-- A subgroup of a group inherits an inverse. -/ @[to_additive "A `add_subgroup` of a `add_group` inherits an inverse."] instance has_inv : has_inv H := ⟨λ a, ⟨a⁻¹, H.inv_mem a.2⟩⟩ /-- A subgroup of a group inherits a division -/ @[to_additive "An `add_subgroup` of an `add_group` inherits a subtraction."] instance has_div : has_div H := ⟨λ a b, ⟨a / b, H.div_mem a.2 b.2⟩⟩ @[simp, norm_cast, to_additive] lemma coe_mul (x y : H) : (↑(x * y) : G) = ↑x * ↑y := rfl @[simp, norm_cast, to_additive] lemma coe_one : ((1 : H) : G) = 1 := rfl @[simp, norm_cast, to_additive] lemma coe_inv (x : H) : ↑(x⁻¹ : H) = (x⁻¹ : G) := rfl @[simp, norm_cast, to_additive] lemma coe_mk (x : G) (hx : x ∈ H) : ((⟨x, hx⟩ : H) : G) = x := rfl attribute [norm_cast] add_subgroup.coe_add add_subgroup.coe_zero add_subgroup.coe_neg add_subgroup.coe_mk /-- A subgroup of a group inherits a group structure. -/ @[to_additive "An `add_subgroup` of an `add_group` inherits an `add_group` structure."] instance to_group {G : Type*} [group G] (H : subgroup G) : group H := { inv := has_inv.inv, div := (/), div_eq_mul_inv := λ x y, subtype.eq $ div_eq_mul_inv x y, mul_left_inv := λ x, subtype.eq $ mul_left_inv x, .. H.to_submonoid.to_monoid } /-- A subgroup of a `comm_group` is a `comm_group`. -/ @[to_additive "An `add_subgroup` of an `add_comm_group` is an `add_comm_group`."] instance to_comm_group {G : Type*} [comm_group G] (H : subgroup G) : comm_group H := { mul_comm := λ _ _, subtype.eq $ mul_comm _ _, .. H.to_group} /-- The natural group hom from a subgroup of group `G` to `G`. -/ @[to_additive "The natural group hom from an `add_subgroup` of `add_group` `G` to `G`."] def subtype : H →* G := ⟨coe, rfl, λ _ _, rfl⟩ @[simp, to_additive] theorem coe_subtype : ⇑H.subtype = coe := rfl @[simp, norm_cast] lemma coe_pow (x : H) (n : ℕ) : ((x ^ n : H) : G) = x ^ n := coe_subtype H ▸ monoid_hom.map_pow _ _ _ @[simp, norm_cast] lemma coe_gpow (x : H) (n : ℤ) : ((x ^ n : H) : G) = x ^ n := coe_subtype H ▸ monoid_hom.map_gpow _ _ _ @[to_additive] instance : has_le (subgroup G) := ⟨λ H K, ∀ ⦃x⦄, x ∈ H → x ∈ K⟩ @[to_additive] lemma le_def {H K : subgroup G} : H ≤ K ↔ ∀ ⦃x : G⦄, x ∈ H → x ∈ K := iff.rfl @[simp, to_additive] lemma coe_subset_coe {H K : subgroup G} : (H : set G) ⊆ K ↔ H ≤ K := iff.rfl @[to_additive] instance : partial_order (subgroup G) := { le := (≤), .. partial_order.lift (coe : subgroup G → set G) (λ a b, ext') } /-- The subgroup `G` of the group `G`. -/ @[to_additive "The `add_subgroup G` of the `add_group G`."] instance : has_top (subgroup G) := ⟨{ inv_mem' := λ _ _, set.mem_univ _ , .. (⊤ : submonoid G) }⟩ /-- The trivial subgroup `{1}` of an group `G`. -/ @[to_additive "The trivial `add_subgroup` `{0}` of an `add_group` `G`."] instance : has_bot (subgroup G) := ⟨{ inv_mem' := λ _, by simp *, .. (⊥ : submonoid G) }⟩ @[to_additive] instance : inhabited (subgroup G) := ⟨⊥⟩ @[simp, to_additive] lemma mem_bot {x : G} : x ∈ (⊥ : subgroup G) ↔ x = 1 := iff.rfl @[simp, to_additive] lemma mem_top (x : G) : x ∈ (⊤ : subgroup G) := set.mem_univ x @[simp, to_additive] lemma coe_top : ((⊤ : subgroup G) : set G) = set.univ := rfl @[simp, to_additive] lemma coe_bot : ((⊥ : subgroup G) : set G) = {1} := rfl @[to_additive] lemma eq_bot_iff_forall : H = ⊥ ↔ ∀ x ∈ H, x = (1 : G) := begin split, { intros h x x_in, rwa [h, mem_bot] at x_in }, { intros h, ext x, rw mem_bot, exact ⟨h x, by { rintros rfl, exact H.one_mem }⟩ }, end @[to_additive] lemma eq_top_of_card_eq [fintype H] [fintype G] (h : fintype.card H = fintype.card G) : H = ⊤ := begin classical, rw fintype.card_congr (equiv.refl _) at h, -- this swaps the fintype instance to classical change fintype.card H.carrier = _ at h, unfreezingI { cases H with S hS1 hS2 hS3, }, have : S = set.univ, { suffices : S.to_finset = finset.univ, { rwa [←set.to_finset_univ, set.to_finset_inj] at this, }, apply finset.eq_univ_of_card, rwa set.to_finset_card }, change (⟨_, _, _, _⟩ : subgroup G) = ⟨_, _, _, _⟩, congr', end @[to_additive] lemma nontrivial_iff_exists_ne_one (H : subgroup G) : nontrivial H ↔ ∃ x ∈ H, x ≠ (1:G) := begin split, { introI h, rcases exists_ne (1 : H) with ⟨⟨h, h_in⟩, h_ne⟩, use [h, h_in], intro hyp, apply h_ne, simpa [hyp] }, { rintros ⟨x, x_in, hx⟩, apply nontrivial_of_ne (⟨x, x_in⟩ : H) 1, intro hyp, apply hx, simpa [has_one.one] using hyp }, end /-- A subgroup is either the trivial subgroup or nontrivial. -/ @[to_additive] lemma bot_or_nontrivial (H : subgroup G) : H = ⊥ ∨ nontrivial H := begin classical, by_cases h : ∀ x ∈ H, x = (1 : G), { left, exact H.eq_bot_iff_forall.mpr h }, { right, push_neg at h, simpa [nontrivial_iff_exists_ne_one] using h }, end /-- A subgroup is either the trivial subgroup or contains a nonzero element. -/ @[to_additive] lemma bot_or_exists_ne_one (H : subgroup G) : H = ⊥ ∨ ∃ x ∈ H, x ≠ (1:G) := begin convert H.bot_or_nontrivial, rw nontrivial_iff_exists_ne_one end /-- The inf of two subgroups is their intersection. -/ @[to_additive "The inf of two `add_subgroups`s is their intersection."] instance : has_inf (subgroup G) := ⟨λ H₁ H₂, { inv_mem' := λ _ ⟨hx, hx'⟩, ⟨H₁.inv_mem hx, H₂.inv_mem hx'⟩, .. H₁.to_submonoid ⊓ H₂.to_submonoid }⟩ @[simp, to_additive] lemma coe_inf (p p' : subgroup G) : ((p ⊓ p' : subgroup G) : set G) = p ∩ p' := rfl @[simp, to_additive] lemma mem_inf {p p' : subgroup G} {x : G} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl @[to_additive] instance : has_Inf (subgroup G) := ⟨λ s, { inv_mem' := λ x hx, set.mem_bInter $ λ i h, i.inv_mem (by apply set.mem_bInter_iff.1 hx i h), .. (⨅ S ∈ s, subgroup.to_submonoid S).copy (⋂ S ∈ s, ↑S) (by simp) }⟩ @[simp, to_additive] lemma coe_Inf (H : set (subgroup G)) : ((Inf H : subgroup G) : set G) = ⋂ s ∈ H, ↑s := rfl attribute [norm_cast] coe_Inf add_subgroup.coe_Inf @[simp, to_additive] lemma mem_Inf {S : set (subgroup G)} {x : G} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_bInter_iff @[to_additive] lemma mem_infi {ι : Sort*} {S : ι → subgroup G} {x : G} : (x ∈ ⨅ i, S i) ↔ ∀ i, x ∈ S i := by simp only [infi, mem_Inf, set.forall_range_iff] @[simp, to_additive] lemma coe_infi {ι : Sort*} {S : ι → subgroup G} : (↑(⨅ i, S i) : set G) = ⋂ i, S i := by simp only [infi, coe_Inf, set.bInter_range] attribute [norm_cast] coe_infi add_subgroup.coe_infi /-- Subgroups of a group form a complete lattice. -/ @[to_additive "The `add_subgroup`s of an `add_group` form a complete lattice."] instance : complete_lattice (subgroup G) := { bot := (⊥), bot_le := λ S x hx, (mem_bot.1 hx).symm ▸ S.one_mem, top := (⊤), le_top := λ S x hx, mem_top x, inf := (⊓), le_inf := λ a b c ha hb x hx, ⟨ha hx, hb hx⟩, inf_le_left := λ a b x, and.left, inf_le_right := λ a b x, and.right, .. complete_lattice_of_Inf (subgroup G) $ λ s, is_glb.of_image (λ H K, show (H : set G) ≤ K ↔ H ≤ K, from coe_subset_coe) is_glb_binfi } @[to_additive] lemma mem_sup_left {S T : subgroup G} : ∀ {x : G}, x ∈ S → x ∈ S ⊔ T := show S ≤ S ⊔ T, from le_sup_left @[to_additive] lemma mem_sup_right {S T : subgroup G} : ∀ {x : G}, x ∈ T → x ∈ S ⊔ T := show T ≤ S ⊔ T, from le_sup_right @[to_additive] lemma mem_supr_of_mem {ι : Type*} {S : ι → subgroup G} (i : ι) : ∀ {x : G}, x ∈ S i → x ∈ supr S := show S i ≤ supr S, from le_supr _ _ @[to_additive] lemma mem_Sup_of_mem {S : set (subgroup G)} {s : subgroup G} (hs : s ∈ S) : ∀ {x : G}, x ∈ s → x ∈ Sup S := show s ≤ Sup S, from le_Sup hs @[to_additive] lemma subsingleton_iff : subsingleton G ↔ subsingleton (subgroup G) := ⟨ λ h, by exactI ⟨λ x y, subgroup.ext $ λ i, subsingleton.elim 1 i ▸ by simp [subgroup.one_mem]⟩, λ h, by exactI ⟨λ x y, have ∀ i : G, i = 1 := λ i, mem_bot.mp $ subsingleton.elim (⊤ : subgroup G) ⊥ ▸ mem_top i, (this x).trans (this y).symm⟩⟩ @[to_additive] lemma nontrivial_iff : nontrivial G ↔ nontrivial (subgroup G) := not_iff_not.mp ( (not_nontrivial_iff_subsingleton.trans subsingleton_iff).trans not_nontrivial_iff_subsingleton.symm) @[to_additive] instance [subsingleton G] : subsingleton (subgroup G) := subsingleton_iff.mp ‹_› @[to_additive] instance [nontrivial G] : nontrivial (subgroup G) := nontrivial_iff.mp ‹_› /-- The `subgroup` generated by a set. -/ @[to_additive "The `add_subgroup` generated by a set"] def closure (k : set G) : subgroup G := Inf {K | k ⊆ K} variable {k : set G} @[to_additive] lemma mem_closure {x : G} : x ∈ closure k ↔ ∀ K : subgroup G, k ⊆ K → x ∈ K := mem_Inf /-- The subgroup generated by a set includes the set. -/ @[simp, to_additive "The `add_subgroup` generated by a set includes the set."] lemma subset_closure : k ⊆ closure k := λ x hx, mem_closure.2 $ λ K hK, hK hx open set /-- A subgroup `K` includes `closure k` if and only if it includes `k`. -/ @[simp, to_additive "An additive subgroup `K` includes `closure k` if and only if it includes `k`"] lemma closure_le : closure k ≤ K ↔ k ⊆ K := ⟨subset.trans subset_closure, λ h, Inf_le h⟩ @[to_additive] lemma closure_eq_of_le (h₁ : k ⊆ K) (h₂ : K ≤ closure k) : closure k = K := le_antisymm ((closure_le $ K).2 h₁) h₂ /-- An induction principle for closure membership. If `p` holds for `1` and all elements of `k`, and is preserved under multiplication and inverse, then `p` holds for all elements of the closure of `k`. -/ @[to_additive "An induction principle for additive closure membership. If `p` holds for `0` and all elements of `k`, and is preserved under addition and isvers, then `p` holds for all elements of the additive closure of `k`."] lemma closure_induction {p : G → Prop} {x} (h : x ∈ closure k) (Hk : ∀ x ∈ k, p x) (H1 : p 1) (Hmul : ∀ x y, p x → p y → p (x * y)) (Hinv : ∀ x, p x → p x⁻¹) : p x := (@closure_le _ _ ⟨p, H1, Hmul, Hinv⟩ _).2 Hk h attribute [elab_as_eliminator] subgroup.closure_induction add_subgroup.closure_induction /-- An induction principle on elements of the subtype `subgroup.closure`. If `p` holds for `1` and all elements of `k`, and is preserved under multiplication and inverse, then `p` holds for all elements `x : closure k`. The difference with `subgroup.closure_induction` is that this acts on the subtype. -/ @[to_additive "An induction principle on elements of the subtype `add_subgroup.closure`. If `p` holds for `0` and all elements of `k`, and is preserved under addition and negation, then `p` holds for all elements `x : closure k`. The difference with `add_subgroup.closure_induction` is that this acts on the subtype."] lemma closure_induction' (k : set G) {p : closure k → Prop} (Hk : ∀ x (h : x ∈ k), p ⟨x, subset_closure h⟩) (H1 : p 1) (Hmul : ∀ x y, p x → p y → p (x * y)) (Hinv : ∀ x, p x → p x⁻¹) (x : closure k) : p x := subtype.rec_on x $ λ x hx, begin refine exists.elim _ (λ (hx : x ∈ closure k) (hc : p ⟨x, hx⟩), hc), exact closure_induction hx (λ x hx, ⟨subset_closure hx, Hk x hx⟩) ⟨one_mem _, H1⟩ (λ x y hx hy, exists.elim hx $ λ hx' hx, exists.elim hy $ λ hy' hy, ⟨mul_mem _ hx' hy', Hmul _ _ hx hy⟩) (λ x hx, exists.elim hx $ λ hx' hx, ⟨inv_mem _ hx', Hinv _ hx⟩), end attribute [elab_as_eliminator] subgroup.closure_induction' add_subgroup.closure_induction' variable (G) /-- `closure` forms a Galois insertion with the coercion to set. -/ @[to_additive "`closure` forms a Galois insertion with the coercion to set."] protected def gi : galois_insertion (@closure G _) coe := { choice := λ s _, closure s, gc := λ s t, @closure_le _ _ t s, le_l_u := λ s, subset_closure, choice_eq := λ s h, rfl } variable {G} /-- Subgroup closure of a set is monotone in its argument: if `h ⊆ k`, then `closure h ≤ closure k`. -/ @[to_additive "Additive subgroup closure of a set is monotone in its argument: if `h ⊆ k`, then `closure h ≤ closure k`"] lemma closure_mono ⦃h k : set G⦄ (h' : h ⊆ k) : closure h ≤ closure k := (subgroup.gi G).gc.monotone_l h' /-- Closure of a subgroup `K` equals `K`. -/ @[simp, to_additive "Additive closure of an additive subgroup `K` equals `K`"] lemma closure_eq : closure (K : set G) = K := (subgroup.gi G).l_u_eq K @[simp, to_additive] lemma closure_empty : closure (∅ : set G) = ⊥ := (subgroup.gi G).gc.l_bot @[simp, to_additive] lemma closure_univ : closure (univ : set G) = ⊤ := @coe_top G _ ▸ closure_eq ⊤ @[to_additive] lemma closure_union (s t : set G) : closure (s ∪ t) = closure s ⊔ closure t := (subgroup.gi G).gc.l_sup @[to_additive] lemma closure_Union {ι} (s : ι → set G) : closure (⋃ i, s i) = ⨆ i, closure (s i) := (subgroup.gi G).gc.l_supr @[to_additive] lemma closure_eq_bot_iff (G : Type*) [group G] (S : set G) : closure S = ⊥ ↔ S ⊆ {1} := by { rw [← le_bot_iff], exact closure_le _} /-- The subgroup generated by an element of a group equals the set of integer number powers of the element. -/ lemma mem_closure_singleton {x y : G} : y ∈ closure ({x} : set G) ↔ ∃ n : ℤ, x ^ n = y := begin refine ⟨λ hy, closure_induction hy _ _ _ _, λ ⟨n, hn⟩, hn ▸ gpow_mem _ (subset_closure $ mem_singleton x) n⟩, { intros y hy, rw [eq_of_mem_singleton hy], exact ⟨1, gpow_one x⟩ }, { exact ⟨0, rfl⟩ }, { rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩, exact ⟨n + m, gpow_add x n m⟩ }, rintros _ ⟨n, rfl⟩, exact ⟨-n, gpow_neg x n⟩ end lemma closure_singleton_one : closure ({1} : set G) = ⊥ := by simp [eq_bot_iff_forall, mem_closure_singleton] @[to_additive] lemma mem_supr_of_directed {ι} [hι : nonempty ι] {K : ι → subgroup G} (hK : directed (≤) K) {x : G} : x ∈ (supr K : subgroup G) ↔ ∃ i, x ∈ K i := begin refine ⟨_, λ ⟨i, hi⟩, (le_def.1 $ le_supr K i) hi⟩, suffices : x ∈ closure (⋃ i, (K i : set G)) → ∃ i, x ∈ K i, by simpa only [closure_Union, closure_eq (K _)] using this, refine (λ hx, closure_induction hx (λ _, mem_Union.1) _ _ _), { exact hι.elim (λ i, ⟨i, (K i).one_mem⟩) }, { rintros x y ⟨i, hi⟩ ⟨j, hj⟩, rcases hK i j with ⟨k, hki, hkj⟩, exact ⟨k, (K k).mul_mem (hki hi) (hkj hj)⟩ }, rintros _ ⟨i, hi⟩, exact ⟨i, inv_mem (K i) hi⟩ end @[to_additive] lemma coe_supr_of_directed {ι} [nonempty ι] {S : ι → subgroup G} (hS : directed (≤) S) : ((⨆ i, S i : subgroup G) : set G) = ⋃ i, ↑(S i) := set.ext $ λ x, by simp [mem_supr_of_directed hS] @[to_additive] lemma mem_Sup_of_directed_on {K : set (subgroup G)} (Kne : K.nonempty) (hK : directed_on (≤) K) {x : G} : x ∈ Sup K ↔ ∃ s ∈ K, x ∈ s := begin haveI : nonempty K := Kne.to_subtype, simp only [Sup_eq_supr', mem_supr_of_directed hK.directed_coe, set_coe.exists, subtype.coe_mk] end variables {N : Type*} [group N] {P : Type*} [group P] /-- The preimage of a subgroup along a monoid homomorphism is a subgroup. -/ @[to_additive "The preimage of an `add_subgroup` along an `add_monoid` homomorphism is an `add_subgroup`."] def comap {N : Type*} [group N] (f : G →* N) (H : subgroup N) : subgroup G := { carrier := (f ⁻¹' H), inv_mem' := λ a ha, show f a⁻¹ ∈ H, by rw f.map_inv; exact H.inv_mem ha, .. H.to_submonoid.comap f } @[simp, to_additive] lemma coe_comap (K : subgroup N) (f : G →* N) : (K.comap f : set G) = f ⁻¹' K := rfl @[simp, to_additive] lemma mem_comap {K : subgroup N} {f : G →* N} {x : G} : x ∈ K.comap f ↔ f x ∈ K := iff.rfl @[to_additive] lemma comap_comap (K : subgroup P) (g : N →* P) (f : G →* N) : (K.comap g).comap f = K.comap (g.comp f) := rfl /-- The image of a subgroup along a monoid homomorphism is a subgroup. -/ @[to_additive "The image of an `add_subgroup` along an `add_monoid` homomorphism is an `add_subgroup`."] def map (f : G →* N) (H : subgroup G) : subgroup N := { carrier := (f '' H), inv_mem' := by { rintros _ ⟨x, hx, rfl⟩, exact ⟨x⁻¹, H.inv_mem hx, f.map_inv x⟩ }, .. H.to_submonoid.map f } @[simp, to_additive] lemma coe_map (f : G →* N) (K : subgroup G) : (K.map f : set N) = f '' K := rfl @[simp, to_additive] lemma mem_map {f : G →* N} {K : subgroup G} {y : N} : y ∈ K.map f ↔ ∃ x ∈ K, f x = y := mem_image_iff_bex @[to_additive] lemma map_map (g : N →* P) (f : G →* N) : (K.map f).map g = K.map (g.comp f) := ext' $ image_image _ _ _ @[to_additive] lemma map_le_iff_le_comap {f : G →* N} {K : subgroup G} {H : subgroup N} : K.map f ≤ H ↔ K ≤ H.comap f := image_subset_iff @[to_additive] lemma gc_map_comap (f : G →* N) : galois_connection (map f) (comap f) := λ _ _, map_le_iff_le_comap @[to_additive] lemma map_sup (H K : subgroup G) (f : G →* N) : (H ⊔ K).map f = H.map f ⊔ K.map f := (gc_map_comap f).l_sup @[to_additive] lemma map_supr {ι : Sort*} (f : G →* N) (s : ι → subgroup G) : (supr s).map f = ⨆ i, (s i).map f := (gc_map_comap f).l_supr @[to_additive] lemma comap_inf (H K : subgroup N) (f : G →* N) : (H ⊓ K).comap f = H.comap f ⊓ K.comap f := (gc_map_comap f).u_inf @[to_additive] lemma comap_infi {ι : Sort*} (f : G →* N) (s : ι → subgroup N) : (infi s).comap f = ⨅ i, (s i).comap f := (gc_map_comap f).u_infi @[simp, to_additive] lemma map_bot (f : G →* N) : (⊥ : subgroup G).map f = ⊥ := (gc_map_comap f).l_bot @[simp, to_additive] lemma comap_top (f : G →* N) : (⊤ : subgroup N).comap f = ⊤ := (gc_map_comap f).u_top @[to_additive] lemma map_eq_bot_iff {G' : Type*} [group G'] {f : G →* G'} (hf : function.injective f) (H : subgroup G) : H.map f = ⊥ ↔ H = ⊥ := begin split, { rw [eq_bot_iff_forall, eq_bot_iff_forall], intros h x hx, have hfx : f x = 1 := h (f x) ⟨x, hx, rfl⟩, exact hf (show f x = f 1, by simp only [hfx, monoid_hom.map_one]), }, { intros h, rw [h, map_bot], }, end /-- Given `subgroup`s `H`, `K` of groups `G`, `N` respectively, `H × K` as a subgroup of `G × N`. -/ @[to_additive prod "Given `add_subgroup`s `H`, `K` of `add_group`s `A`, `B` respectively, `H × K` as an `add_subgroup` of `A × B`."] def prod (H : subgroup G) (K : subgroup N) : subgroup (G × N) := { inv_mem' := λ _ hx, ⟨H.inv_mem' hx.1, K.inv_mem' hx.2⟩, .. submonoid.prod H.to_submonoid K.to_submonoid} @[to_additive coe_prod] lemma coe_prod (H : subgroup G) (K : subgroup N) : (H.prod K : set (G × N)) = (H : set G).prod (K : set N) := rfl @[to_additive mem_prod] lemma mem_prod {H : subgroup G} {K : subgroup N} {p : G × N} : p ∈ H.prod K ↔ p.1 ∈ H ∧ p.2 ∈ K := iff.rfl @[to_additive prod_mono] lemma prod_mono : ((≤) ⇒ (≤) ⇒ (≤)) (@prod G _ N _) (@prod G _ N _) := λ s s' hs t t' ht, set.prod_mono hs ht @[to_additive prod_mono_right] lemma prod_mono_right (K : subgroup G) : monotone (λ t : subgroup N, K.prod t) := prod_mono (le_refl K) @[to_additive prod_mono_left] lemma prod_mono_left (H : subgroup N) : monotone (λ K : subgroup G, K.prod H) := λ s₁ s₂ hs, prod_mono hs (le_refl H) @[to_additive prod_top] lemma prod_top (K : subgroup G) : K.prod (⊤ : subgroup N) = K.comap (monoid_hom.fst G N) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst] @[to_additive top_prod] lemma top_prod (H : subgroup N) : (⊤ : subgroup G).prod H = H.comap (monoid_hom.snd G N) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd] @[simp, to_additive top_prod_top] lemma top_prod_top : (⊤ : subgroup G).prod (⊤ : subgroup N) = ⊤ := (top_prod _).trans $ comap_top _ @[to_additive] lemma bot_prod_bot : (⊥ : subgroup G).prod (⊥ : subgroup N) = ⊥ := ext' $ by simp [coe_prod, prod.one_eq_mk] /-- Product of subgroups is isomorphic to their product as groups. -/ @[to_additive prod_equiv "Product of additive subgroups is isomorphic to their product as additive groups"] def prod_equiv (H : subgroup G) (K : subgroup N) : H.prod K ≃* H × K := { map_mul' := λ x y, rfl, .. equiv.set.prod ↑H ↑K } /-- A subgroup is normal if whenever `n ∈ H`, then `g * n * g⁻¹ ∈ H` for every `g : G` -/ structure normal : Prop := (conj_mem : ∀ n, n ∈ H → ∀ g : G, g * n * g⁻¹ ∈ H) attribute [class] normal end subgroup namespace add_subgroup /-- An add_subgroup is normal if whenever `n ∈ H`, then `g + n - g ∈ H` for every `g : G` -/ structure normal (H : add_subgroup A) : Prop := (conj_mem [] : ∀ n, n ∈ H → ∀ g : A, g + n + -g ∈ H) attribute [to_additive add_subgroup.normal] subgroup.normal attribute [class] normal end add_subgroup namespace subgroup variables {H K : subgroup G} @[priority 100, to_additive] instance normal_of_comm {G : Type*} [comm_group G] (H : subgroup G) : H.normal := ⟨by simp [mul_comm, mul_left_comm]⟩ namespace normal variable (nH : H.normal) @[to_additive] lemma mem_comm {a b : G} (h : a * b ∈ H) : b * a ∈ H := have a⁻¹ * (a * b) * a⁻¹⁻¹ ∈ H, from nH.conj_mem (a * b) h a⁻¹, by simpa @[to_additive] lemma mem_comm_iff {a b : G} : a * b ∈ H ↔ b * a ∈ H := ⟨nH.mem_comm, nH.mem_comm⟩ end normal @[priority 100, to_additive] instance bot_normal : normal (⊥ : subgroup G) := ⟨by simp⟩ @[priority 100, to_additive] instance top_normal : normal (⊤ : subgroup G) := ⟨λ _ _, mem_top⟩ variable (G) /-- The center of a group `G` is the set of elements that commute with everything in `G` -/ @[to_additive "The center of a group `G` is the set of elements that commute with everything in `G`"] def center : subgroup G := { carrier := {z | ∀ g, g * z = z * g}, one_mem' := by simp, mul_mem' := λ a b (ha : ∀ g, g * a = a * g) (hb : ∀ g, g * b = b * g) g, by assoc_rw [ha, hb g], inv_mem' := λ a (ha : ∀ g, g * a = a * g) g, by rw [← inv_inj, mul_inv_rev, inv_inv, ← ha, mul_inv_rev, inv_inv] } variable {G} @[to_additive] lemma mem_center_iff {z : G} : z ∈ center G ↔ ∀ g, g * z = z * g := iff.rfl @[priority 100, to_additive] instance center_normal : (center G).normal := ⟨begin assume n hn g h, assoc_rw [hn (h * g), hn g], simp end⟩ variables {G} (H) /-- The `normalizer` of `H` is the smallest subgroup of `G` inside which `H` is normal. -/ @[to_additive "The `normalizer` of `H` is the smallest subgroup of `G` inside which `H` is normal."] def normalizer : subgroup G := { carrier := {g : G | ∀ n, n ∈ H ↔ g * n * g⁻¹ ∈ H}, one_mem' := by simp, mul_mem' := λ a b (ha : ∀ n, n ∈ H ↔ a * n * a⁻¹ ∈ H) (hb : ∀ n, n ∈ H ↔ b * n * b⁻¹ ∈ H) n, by { rw [hb, ha], simp [mul_assoc] }, inv_mem' := λ a (ha : ∀ n, n ∈ H ↔ a * n * a⁻¹ ∈ H) n, by { rw [ha (a⁻¹ * n * a⁻¹⁻¹)], simp [mul_assoc] } } -- variant for sets. -- TODO should this replace `normalizer`? /-- The `set_normalizer` of `S` is the subgroup of `G` whose elements satisfy `g*S*g⁻¹=S` -/ @[to_additive "The `set_normalizer` of `S` is the subgroup of `G` whose elements satisfy `g+S-g=S`."] def set_normalizer (S : set G) : subgroup G := { carrier := {g : G | ∀ n, n ∈ S ↔ g * n * g⁻¹ ∈ S}, one_mem' := by simp, mul_mem' := λ a b (ha : ∀ n, n ∈ S ↔ a * n * a⁻¹ ∈ S) (hb : ∀ n, n ∈ S ↔ b * n * b⁻¹ ∈ S) n, by { rw [hb, ha], simp [mul_assoc] }, inv_mem' := λ a (ha : ∀ n, n ∈ S ↔ a * n * a⁻¹ ∈ S) n, by { rw [ha (a⁻¹ * n * a⁻¹⁻¹)], simp [mul_assoc] } } variable {H} @[to_additive] lemma mem_normalizer_iff {g : G} : g ∈ normalizer H ↔ ∀ n, n ∈ H ↔ g * n * g⁻¹ ∈ H := iff.rfl @[to_additive] lemma le_normalizer : H ≤ normalizer H := λ x xH n, by rw [H.mul_mem_cancel_right (H.inv_mem xH), H.mul_mem_cancel_left xH] @[priority 100, to_additive] instance normal_in_normalizer : (H.comap H.normalizer.subtype).normal := ⟨λ x xH g, by simpa using (g.2 x).1 xH⟩ open_locale classical @[to_additive] lemma le_normalizer_of_normal [hK : (H.comap K.subtype).normal] (HK : H ≤ K) : K ≤ H.normalizer := λ x hx y, ⟨λ yH, hK.conj_mem ⟨y, HK yH⟩ yH ⟨x, hx⟩, λ yH, by simpa [mem_comap, mul_assoc] using hK.conj_mem ⟨x * y * x⁻¹, HK yH⟩ yH ⟨x⁻¹, K.inv_mem hx⟩⟩ end subgroup namespace group variables {s : set G} /-- Given an element `a`, `conjugates a` is the set of conjugates. -/ def conjugates (a : G) : set G := {b | is_conj a b} lemma mem_conjugates_self {a : G} : a ∈ conjugates a := is_conj_refl _ /-- Given a set `s`, `conjugates_of_set s` is the set of all conjugates of the elements of `s`. -/ def conjugates_of_set (s : set G) : set G := ⋃ a ∈ s, conjugates a lemma mem_conjugates_of_set_iff {x : G} : x ∈ conjugates_of_set s ↔ ∃ a ∈ s, is_conj a x := set.mem_bUnion_iff theorem subset_conjugates_of_set : s ⊆ conjugates_of_set s := λ (x : G) (h : x ∈ s), mem_conjugates_of_set_iff.2 ⟨x, h, is_conj_refl _⟩ theorem conjugates_of_set_mono {s t : set G} (h : s ⊆ t) : conjugates_of_set s ⊆ conjugates_of_set t := set.bUnion_subset_bUnion_left h lemma conjugates_subset_normal {N : subgroup G} [tn : N.normal] {a : G} (h : a ∈ N) : conjugates a ⊆ N := by { rintros a ⟨c, rfl⟩, exact tn.conj_mem a h c } theorem conjugates_of_set_subset {s : set G} {N : subgroup G} [N.normal] (h : s ⊆ N) : conjugates_of_set s ⊆ N := set.bUnion_subset (λ x H, conjugates_subset_normal (h H)) /-- The set of conjugates of `s` is closed under conjugation. -/ lemma conj_mem_conjugates_of_set {x c : G} : x ∈ conjugates_of_set s → (c * x * c⁻¹ ∈ conjugates_of_set s) := λ H, begin rcases (mem_conjugates_of_set_iff.1 H) with ⟨a,h₁,h₂⟩, exact mem_conjugates_of_set_iff.2 ⟨a, h₁, is_conj_trans h₂ ⟨c,rfl⟩⟩, end end group namespace subgroup open group variable {s : set G} /-- The normal closure of a set `s` is the subgroup closure of all the conjugates of elements of `s`. It is the smallest normal subgroup containing `s`. -/ def normal_closure (s : set G) : subgroup G := closure (conjugates_of_set s) theorem conjugates_of_set_subset_normal_closure : conjugates_of_set s ⊆ normal_closure s := subset_closure theorem subset_normal_closure : s ⊆ normal_closure s := set.subset.trans subset_conjugates_of_set conjugates_of_set_subset_normal_closure theorem le_normal_closure {H : subgroup G} : H ≤ normal_closure ↑H := λ _ h, subset_normal_closure h /-- The normal closure of `s` is a normal subgroup. -/ instance normal_closure_normal : (normal_closure s).normal := ⟨λ n h g, begin refine subgroup.closure_induction h (λ x hx, _) _ (λ x y ihx ihy, _) (λ x ihx, _), { exact (conjugates_of_set_subset_normal_closure (conj_mem_conjugates_of_set hx)) }, { simpa using (normal_closure s).one_mem }, { rw ← conj_mul, exact mul_mem _ ihx ihy }, { rw ← conj_inv, exact inv_mem _ ihx } end⟩ /-- The normal closure of `s` is the smallest normal subgroup containing `s`. -/ theorem normal_closure_le_normal {N : subgroup G} [N.normal] (h : s ⊆ N) : normal_closure s ≤ N := begin assume a w, refine closure_induction w (λ x hx, _) _ (λ x y ihx ihy, _) (λ x ihx, _), { exact (conjugates_of_set_subset h hx) }, { exact subgroup.one_mem _ }, { exact subgroup.mul_mem _ ihx ihy }, { exact subgroup.inv_mem _ ihx } end lemma normal_closure_subset_iff {N : subgroup G} [N.normal] : s ⊆ N ↔ normal_closure s ≤ N := ⟨normal_closure_le_normal, set.subset.trans (subset_normal_closure)⟩ theorem normal_closure_mono {s t : set G} (h : s ⊆ t) : normal_closure s ≤ normal_closure t := normal_closure_le_normal (set.subset.trans h subset_normal_closure) theorem normal_closure_eq_infi : normal_closure s = ⨅ (N : subgroup G) [normal N] (hs : s ⊆ N), N := le_antisymm (le_infi (λ N, le_infi (λ hN, by exactI le_infi (normal_closure_le_normal)))) (infi_le_of_le (normal_closure s) (infi_le_of_le (by apply_instance) (infi_le_of_le subset_normal_closure (le_refl _)))) @[simp] theorem normal_closure_eq_self (H : subgroup G) [H.normal] : normal_closure ↑H = H := le_antisymm (normal_closure_le_normal rfl.subset) (le_normal_closure) @[simp] theorem normal_closure_idempotent : normal_closure ↑(normal_closure s) = normal_closure s := normal_closure_eq_self _ theorem closure_le_normal_closure {s : set G} : closure s ≤ normal_closure s := by simp only [subset_normal_closure, closure_le] @[simp] theorem normal_closure_closure_eq_normal_closure {s : set G} : normal_closure ↑(closure s) = normal_closure s := le_antisymm (normal_closure_le_normal closure_le_normal_closure) (normal_closure_mono subset_closure) end subgroup namespace add_subgroup open set lemma gsmul_mem (H : add_subgroup A) {x : A} (hx : x ∈ H) : ∀ n : ℤ, gsmul n x ∈ H | (int.of_nat n) := add_submonoid.nsmul_mem H.to_add_submonoid hx n | -[1+ n] := H.neg_mem' $ H.add_mem hx $ add_submonoid.nsmul_mem H.to_add_submonoid hx n /-- The `add_subgroup` generated by an element of an `add_group` equals the set of natural number multiples of the element. -/ lemma mem_closure_singleton {x y : A} : y ∈ closure ({x} : set A) ↔ ∃ n : ℤ, gsmul n x = y := begin refine ⟨λ hy, closure_induction hy _ _ _ _, λ ⟨n, hn⟩, hn ▸ gsmul_mem _ (subset_closure $ mem_singleton x) n⟩, { intros y hy, rw [eq_of_mem_singleton hy], exact ⟨1, one_gsmul x⟩ }, { exact ⟨0, rfl⟩ }, { rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩, exact ⟨n + m, add_gsmul x n m⟩ }, { rintros _ ⟨n, rfl⟩, refine ⟨-n, neg_gsmul x n⟩ } end lemma closure_singleton_zero : closure ({0} : set A) = ⊥ := by simp [eq_bot_iff_forall, mem_closure_singleton] variable (H : add_subgroup A) @[simp] lemma coe_smul (x : H) (n : ℕ) : ((nsmul n x : H) : A) = nsmul n x := coe_subtype H ▸ add_monoid_hom.map_nsmul _ _ _ @[simp] lemma coe_gsmul (x : H) (n : ℤ) : ((n •ℤ x : H) : A) = n •ℤ x := coe_subtype H ▸ add_monoid_hom.map_gsmul _ _ _ attribute [to_additive add_subgroup.coe_smul] subgroup.coe_pow attribute [to_additive add_subgroup.coe_gsmul] subgroup.coe_gpow end add_subgroup namespace monoid_hom variables {N : Type*} {P : Type*} [group N] [group P] (K : subgroup G) open subgroup /-- The range of a monoid homomorphism from a group is a subgroup. -/ @[to_additive "The range of an `add_monoid_hom` from an `add_group` is an `add_subgroup`."] def range (f : G →* N) : subgroup N := subgroup.copy ((⊤ : subgroup G).map f) (set.range f) (by simp [set.ext_iff]) @[to_additive] instance decidable_mem_range (f : G →* N) [fintype G] [decidable_eq N] : decidable_pred (λ x, x ∈ f.range) := λ x, fintype.decidable_exists_fintype @[simp, to_additive] lemma coe_range (f : G →* N) : (f.range : set N) = set.range f := rfl @[simp, to_additive] lemma mem_range {f : G →* N} {y : N} : y ∈ f.range ↔ ∃ x, f x = y := iff.rfl @[to_additive] lemma range_eq_map (f : G →* N) : f.range = (⊤ : subgroup G).map f := by ext; simp /-- The canonical surjective group homomorphism `G →* f(G)` induced by a group homomorphism `G →* N`. -/ @[to_additive "The canonical surjective `add_group` homomorphism `G →+ f(G)` induced by a group homomorphism `G →+ N`."] def to_range (f : G →* N) : G →* f.range := monoid_hom.mk' (λ g, ⟨f g, ⟨g, rfl⟩⟩) $ λ a b, by {ext, exact f.map_mul' _ _} @[to_additive] lemma map_range (g : N →* P) (f : G →* N) : f.range.map g = (g.comp f).range := by rw [range_eq_map, range_eq_map]; exact (⊤ : subgroup G).map_map g f @[to_additive] lemma range_top_iff_surjective {N} [group N] {f : G →* N} : f.range = (⊤ : subgroup N) ↔ function.surjective f := subgroup.ext'_iff.trans $ iff.trans (by rw [coe_range, coe_top]) set.range_iff_surjective /-- The range of a surjective monoid homomorphism is the whole of the codomain. -/ @[to_additive "The range of a surjective `add_monoid` homomorphism is the whole of the codomain."] lemma range_top_of_surjective {N} [group N] (f : G →* N) (hf : function.surjective f) : f.range = (⊤ : subgroup N) := range_top_iff_surjective.2 hf /-- Restriction of a group hom to a subgroup of the codomain. -/ @[to_additive "Restriction of an `add_group` hom to an `add_subgroup` of the codomain."] def cod_restrict (f : G →* N) (S : subgroup N) (h : ∀ x, f x ∈ S) : G →* S := { to_fun := λ n, ⟨f n, h n⟩, map_one' := subtype.eq f.map_one, map_mul' := λ x y, subtype.eq (f.map_mul x y) } /-- The multiplicative kernel of a monoid homomorphism is the subgroup of elements `x : G` such that `f x = 1` -/ @[to_additive "The additive kernel of an `add_monoid` homomorphism is the `add_subgroup` of elements such that `f x = 0`"] def ker (f : G →* N) := (⊥ : subgroup N).comap f @[to_additive] lemma mem_ker (f : G →* N) {x : G} : x ∈ f.ker ↔ f x = 1 := iff.rfl @[to_additive] lemma comap_ker (g : N →* P) (f : G →* N) : g.ker.comap f = (g.comp f).ker := rfl @[to_additive] lemma to_range_ker (f : G →* N) : ker (to_range f) = ker f := begin ext, change (⟨f x, _⟩ : range f) = ⟨1, _⟩ ↔ f x = 1, simp only [], end /-- The subgroup of elements `x : G` such that `f x = g x` -/ @[to_additive "The additive subgroup of elements `x : G` such that `f x = g x`"] def eq_locus (f g : G →* N) : subgroup G := { inv_mem' := λ x (hx : f x = g x), show f x⁻¹ = g x⁻¹, by rw [f.map_inv, g.map_inv, hx], .. eq_mlocus f g} /-- If two monoid homomorphisms are equal on a set, then they are equal on its subgroup closure. -/ @[to_additive] lemma eq_on_closure {f g : G →* N} {s : set G} (h : set.eq_on f g s) : set.eq_on f g (closure s) := show closure s ≤ f.eq_locus g, from (closure_le _).2 h @[to_additive] lemma eq_of_eq_on_top {f g : G →* N} (h : set.eq_on f g (⊤ : subgroup G)) : f = g := ext $ λ x, h trivial @[to_additive] lemma eq_of_eq_on_dense {s : set G} (hs : closure s = ⊤) {f g : G →* N} (h : s.eq_on f g) : f = g := eq_of_eq_on_top $ hs ▸ eq_on_closure h @[to_additive] lemma gclosure_preimage_le (f : G →* N) (s : set N) : closure (f ⁻¹' s) ≤ (closure s).comap f := (closure_le _).2 $ λ x hx, by rw [mem_coe, mem_comap]; exact subset_closure hx /-- The image under a monoid homomorphism of the subgroup generated by a set equals the subgroup generated by the image of the set. -/ @[to_additive "The image under an `add_monoid` hom of the `add_subgroup` generated by a set equals the `add_subgroup` generated by the image of the set."] lemma map_closure (f : G →* N) (s : set G) : (closure s).map f = closure (f '' s) := le_antisymm (map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image f s) (gclosure_preimage_le _ _)) ((closure_le _).2 $ set.image_subset _ subset_closure) end monoid_hom namespace monoid_hom variables {G₁ G₂ G₃ : Type*} [group G₁] [group G₂] [group G₃] variables (f : G₁ →* G₂) /-- `lift_of_surjective f hf g hg` is the unique group homomorphism `φ` * such that `φ.comp f = g` (`lift_of_surjective_comp`), * where `f : G₁ →+* G₂` is surjective (`hf`), * and `g : G₂ →+* G₃` satisfies `hg : f.ker ≤ g.ker`. See `lift_of_surjective_eq` for the uniqueness lemma. ``` G₁. | \ f | \ g | \ v \⌟ G₂----> G₃ ∃!φ ``` -/ @[to_additive "`lift_of_surjective f hf g hg` is the unique additive group homomorphism `φ` * such that `φ.comp f = g` (`lift_of_surjective_comp`), * where `f : G₁ →+* G₂` is surjective (`hf`), * and `g : G₂ →+* G₃` satisfies `hg : f.ker ≤ g.ker`. See `lift_of_surjective_eq` for the uniqueness lemma. ``` G₁. | \\ f | \\ g | \\ v \\⌟ G₂----> G₃ ∃!φ ```"] noncomputable def lift_of_surjective (hf : function.surjective f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) : G₂ →* G₃ := { to_fun := λ b, g (classical.some (hf b)), map_one' := hg (classical.some_spec (hf 1)), map_mul' := begin intros x y, rw [← g.map_mul, ← mul_inv_eq_one, ← g.map_inv, ← g.map_mul, ← g.mem_ker], apply hg, rw [f.mem_ker, f.map_mul, f.map_inv, mul_inv_eq_one, f.map_mul], simp only [classical.some_spec (hf _)], end } @[simp, to_additive] lemma lift_of_surjective_comp_apply (hf : function.surjective f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) (x : G₁) : (f.lift_of_surjective hf g hg) (f x) = g x := begin dsimp [lift_of_surjective], rw [← mul_inv_eq_one, ← g.map_inv, ← g.map_mul, ← g.mem_ker], apply hg, rw [f.mem_ker, f.map_mul, f.map_inv, mul_inv_eq_one], simp only [classical.some_spec (hf _)], end @[simp, to_additive] lemma lift_of_surjective_comp (hf : function.surjective f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) : (f.lift_of_surjective hf g hg).comp f = g := by { ext, simp only [comp_apply, lift_of_surjective_comp_apply] } @[to_additive] lemma eq_lift_of_surjective (hf : function.surjective f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) (h : G₂ →* G₃) (hh : h.comp f = g) : h = (f.lift_of_surjective hf g hg) := begin ext b, rcases hf b with ⟨a, rfl⟩, simp only [← comp_apply, hh, f.lift_of_surjective_comp], end end monoid_hom variables {N : Type*} [group N] -- Here `H.normal` is an explicit argument so we can use dot notation with `comap`. @[to_additive] lemma subgroup.normal.comap {H : subgroup N} (hH : H.normal) (f : G →* N) : (H.comap f).normal := ⟨λ _, by simp [subgroup.mem_comap, hH.conj_mem] {contextual := tt}⟩ @[priority 100, to_additive] instance subgroup.normal_comap {H : subgroup N} [nH : H.normal] (f : G →* N) : (H.comap f).normal := nH.comap _ @[priority 100, to_additive] instance monoid_hom.normal_ker (f : G →* N) : f.ker.normal := by rw [monoid_hom.ker]; apply_instance namespace subgroup /-- The subgroup generated by an element. -/ def gpowers (g : G) : subgroup G := subgroup.copy (gpowers_hom G g).range (set.range ((^) g : ℤ → G)) rfl @[simp] lemma mem_gpowers (g : G) : g ∈ gpowers g := ⟨1, gpow_one _⟩ lemma gpowers_eq_closure (g : G) : gpowers g = closure {g} := by { ext, exact mem_closure_singleton.symm } @[simp] lemma range_gpowers_hom (g : G) : (gpowers_hom G g).range = gpowers g := rfl lemma gpowers_subset {a : G} {K : subgroup G} (h : a ∈ K) : gpowers a ≤ K := λ x hx, match x, hx with _, ⟨i, rfl⟩ := K.gpow_mem h i end end subgroup namespace add_subgroup /-- The subgroup generated by an element. -/ def gmultiples (a : A) : add_subgroup A := add_subgroup.copy (gmultiples_hom A a).range (set.range ((•ℤ a) : ℤ → A)) rfl @[simp] lemma mem_gmultiples (a : A) : a ∈ gmultiples a := ⟨1, one_gsmul _⟩ lemma gmultiples_eq_closure (a : A) : gmultiples a = closure {a} := by { ext, exact mem_closure_singleton.symm } @[simp] lemma range_gmultiples_hom (a : A) : (gmultiples_hom A a).range = gmultiples a := rfl lemma gmultiples_subset {a : A} {B : add_subgroup A} (h : a ∈ B) : gmultiples a ≤ B := @subgroup.gpowers_subset (multiplicative A) _ _ (B.to_subgroup) h attribute [to_additive add_subgroup.gmultiples] subgroup.gpowers attribute [to_additive add_subgroup.mem_gmultiples] subgroup.mem_gpowers attribute [to_additive add_subgroup.gmultiples_eq_closure] subgroup.gpowers_eq_closure attribute [to_additive add_subgroup.range_gmultiples_hom] subgroup.range_gpowers_hom attribute [to_additive add_subgroup.gmultiples_subset] subgroup.gpowers_subset end add_subgroup namespace mul_equiv variables {H K : subgroup G} /-- Makes the identity isomorphism from a proof two subgroups of a multiplicative group are equal. -/ @[to_additive "Makes the identity additive isomorphism from a proof two subgroups of an additive group are equal."] def subgroup_congr (h : H = K) : H ≃* K := { map_mul' := λ _ _, rfl, ..equiv.set_congr $ subgroup.ext'_iff.1 h } end mul_equiv -- TODO : ↥(⊤ : subgroup H) ≃* H ? namespace subgroup variables {C : Type*} [comm_group C] {s t : subgroup C} {x : C} @[to_additive] lemma mem_sup : x ∈ s ⊔ t ↔ ∃ (y ∈ s) (z ∈ t), y * z = x := ⟨λ h, begin rw [← closure_eq s, ← closure_eq t, ← closure_union] at h, apply closure_induction h, { rintro y (h | h), { exact ⟨y, h, 1, t.one_mem, by simp⟩ }, { exact ⟨1, s.one_mem, y, h, by simp⟩ } }, { exact ⟨1, s.one_mem, 1, ⟨t.one_mem, mul_one 1⟩⟩ }, { rintro _ _ ⟨y₁, hy₁, z₁, hz₁, rfl⟩ ⟨y₂, hy₂, z₂, hz₂, rfl⟩, exact ⟨_, mul_mem _ hy₁ hy₂, _, mul_mem _ hz₁ hz₂, by simp [mul_assoc]; cc⟩ }, { rintro _ ⟨y, hy, z, hz, rfl⟩, exact ⟨_, inv_mem _ hy, _, inv_mem _ hz, mul_comm z y ▸ (mul_inv_rev z y).symm⟩ } end, by rintro ⟨y, hy, z, hz, rfl⟩; exact mul_mem _ ((le_sup_left : s ≤ s ⊔ t) hy) ((le_sup_right : t ≤ s ⊔ t) hz)⟩ @[to_additive] lemma mem_sup' : x ∈ s ⊔ t ↔ ∃ (y : s) (z : t), (y:C) * z = x := mem_sup.trans $ by simp only [subgroup.exists, coe_mk] @[to_additive] instance : is_modular_lattice (subgroup C) := ⟨λ x y z xz a ha, begin rw [mem_inf, mem_sup] at ha, rcases ha with ⟨⟨b, hb, c, hc, rfl⟩, haz⟩, rw mem_sup, refine ⟨b, hb, c, mem_inf.2 ⟨hc, _⟩, rfl⟩, rw ← inv_mul_cancel_left b c, apply z.mul_mem (z.inv_mem (xz hb)) haz, end⟩ end subgroup
48356292f9aeaba376ba96b3961ade6cf2ed2787
9cb9db9d79fad57d80ca53543dc07efb7c4f3838
/src/breen_deligne/basic.lean
e03d28d557bed109f7ec8d95a6c9f736e8aa4562
[]
no_license
mr-infty/lean-liquid
3ff89d1f66244b434654c59bdbd6b77cb7de0109
a8db559073d2101173775ccbd85729d3a4f1ed4d
refs/heads/master
1,678,465,145,334
1,614,565,310,000
1,614,565,310,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,071
lean
import linear_algebra.matrix import group_theory.free_abelian_group import algebra.direct_sum import algebra.big_operators.finsupp import for_mathlib.linear_algebra import hacks_and_tricks.type_pow import hacks_and_tricks.by_exactI_hack /-! # Breen-Deligne resolutions Reference: https://www.math.uni-bonn.de/people/scholze/Condensed.pdf#section*.4 ("Appendix to Lecture IV", p. 28) We formalize the notion of `breen_deligne_data`. Roughly speaking, this is a collection of formal finite sums of matrices that encode that data that rolls out of the Breen--Deligne resolution. -/ noncomputable theory -- get some notation working: open_locale big_operators direct_sum local attribute [instance] type_pow local notation `ℤ[` A `]` := free_abelian_group A namespace breen_deligne open free_abelian_group /-! Suppose you have an abelian group `A`. What data do you need to specify a "universal" map `f : ℤ[A^m] → ℤ[A^n]`? That is, it should be functorial in `A`. Well, such a map is specified by what it does to `(a 1, a 2, a 3, ..., a m)`. It can send this element to an arbitrary element of `ℤ[A^n]`, but it has to be "universal". In the end, this means that `f` will be a `ℤ`-linear combination of "basic universal maps", where a "basic universal map" is one that sends `(a 1, a 2, ..., a m)` to `(b 1, ..., b n)`, where `b i` is a `ℤ`-linear combination `c i 1 * a 1 + ... + c i m * a m`. So a "basic universal map" is specified by the `n × m`-matrix `c`. -/ /-- A `basic_universal_map m n` is an `n × m`-matrix. It captures data for a homomorphism `ℤ[A^m] → ℤ[A^n]` functorial in the abelian group `A`. A general such homomorphism is a formal linear combination of `basic_universal_map`s, which we aptly call `universal_map`s. -/ @[derive add_comm_group] def basic_universal_map (m n : ℕ) := matrix (fin n) (fin m) ℤ namespace basic_universal_map variables {k l m n : ℕ} (g : basic_universal_map m n) (f : basic_universal_map l m) variables (A : Type*) [add_comm_group A] /-- `f.eval A` for a `f : basic_universal_map m n` is the homomorphism `ℤ[A^m] →+ ℤ[A^n]` induced by matrix multiplication. -/ def eval : ℤ[A^m] →+ ℤ[A^n] := map $ λ x i, ∑ j, g i j • (x : fin _ → A) j @[simp] lemma eval_of (x : A^m) : g.eval A (of x) = (of $ λ i, ∑ j, g i j • x j) := lift.of _ _ /-- The composition of basic universal maps, defined as matrix multiplication. -/ def comp : basic_universal_map l n := matrix.mul g f lemma eval_comp : (g.comp f).eval A = (g.eval A).comp (f.eval A) := begin ext1 x, simp only [add_monoid_hom.coe_comp, function.comp_app, eval_of, comp, finset.smul_sum, matrix.mul_apply, finset.sum_smul, mul_smul], congr' 1, ext1 i, exact finset.sum_comm end lemma comp_assoc (h : basic_universal_map m n) (g : basic_universal_map l m) (f : basic_universal_map k l) : comp (comp h g) f = comp h (comp g f) := matrix.mul_assoc _ _ _ /-- The identity `basic_universal_map`. -/ def id (n : ℕ) : basic_universal_map n n := (1 : matrix (fin n) (fin n) ℤ) @[simp] lemma id_comp : (id _).comp f = f := by simp only [comp, id, matrix.one_mul] @[simp] lemma comp_id : g.comp (id _) = g := by simp only [comp, id, matrix.mul_one] end basic_universal_map /-- A `universal_map m n` is a formal `ℤ`-linear combination of `basic_universal_map`s. It captures the data for a homomorphism `ℤ[A^m] → ℤ[A^n]`. -/ @[derive add_comm_group] def universal_map (m n : ℕ) := ℤ[basic_universal_map m n] namespace universal_map universe variable u variables {k l m n : ℕ} (g : universal_map m n) (f : universal_map l m) variables (A : Type u) [add_comm_group A] /-- `f.eval A` for a `f : universal_map m n` is the homomorphism `ℤ[A^m] →+ ℤ[A^n]` induced by matrix multiplication of the summands occurring in the formal linear combination `f`. -/ def eval : universal_map m n →+ ℤ[A^m] →+ ℤ[A^n] := free_abelian_group.lift $ λ (f : basic_universal_map m n), f.eval A @[simp] lemma eval_of (f : basic_universal_map m n) : eval A (of f) = f.eval A := lift.of _ _ /-- The composition of `universal_map`s `g` and `f`, given by the formal linear combination of all compositions of summands occurring in `g` and `f`. -/ def comp : universal_map m n →+ universal_map l m →+ universal_map l n := free_abelian_group.lift $ λ (g : basic_universal_map m n), free_abelian_group.lift $ λ f, of $ g.comp f @[simp] lemma comp_of (g : basic_universal_map m n) (f : basic_universal_map l m) : comp (of g) (of f) = of (g.comp f) := by rw [comp, lift.of, lift.of] section open add_monoid_hom lemma eval_comp : eval A (comp g f) = (eval A g).comp (eval A f) := show comp_hom (comp_hom (@eval l n A _)) (comp) g f = comp_hom (comp_hom (comp_hom.flip (@eval l m A _)) (comp_hom)) (@eval m n A _) g f, begin congr' 2, clear f g, ext g f : 2, show eval A (comp (of g) (of f)) = (eval A (of g)).comp (eval A (of f)), simp only [basic_universal_map.eval_comp, comp_of, eval_of] end lemma comp_assoc (h : universal_map m n) (g : universal_map l m) (f : universal_map k l) : comp (comp h g) f = comp h (comp g f) := show comp_hom (comp_hom (@comp k l n)) (@comp l m n) h g f = comp_hom (comp_hom (comp_hom.flip (@comp k l m)) (comp_hom)) (@comp k m n) h g f, begin congr' 3, clear h g f, ext h g f : 3, show comp (comp (of h) (of g)) (of f) = comp (of h) (comp (of g) (of f)), simp only [basic_universal_map.comp_assoc, comp_of] end /-- The identity `universal_map`. -/ def id (n : ℕ) : universal_map n n := of (basic_universal_map.id n) @[simp] lemma id_comp : comp (id _) f = f := show comp (id _) f = add_monoid_hom.id _ f, begin congr' 1, clear f, ext1 f, simp only [id, comp_of, id_apply, basic_universal_map.id_comp] end @[simp] lemma comp_id : comp g (id _) = g := show (@comp m m n).flip (id _) g = add_monoid_hom.id _ g, begin congr' 1, clear g, ext1 g, show comp (of g) (id _) = (of g), simp only [id, comp_of, id_apply, basic_universal_map.comp_id] end /-- `double f` is the `universal_map` from `ℤ[A^m ⊕ A^m]` to `ℤ[A^n ⊕ A^n]` given by applying `f` on both "components". -/ def double : universal_map m n →+ universal_map (m + m) (n + n) := map $ λ f, matrix.reindex_linear_equiv sum_fin_sum_equiv sum_fin_sum_equiv $ matrix.from_blocks f 0 0 f lemma double_of (f : basic_universal_map m n) : double (of f) = of (matrix.reindex_linear_equiv sum_fin_sum_equiv sum_fin_sum_equiv $ matrix.from_blocks f 0 0 f) := rfl lemma comp_double_double (g : universal_map m n) (f : universal_map l m) : comp (double g) (double f) = double (comp g f) := show comp_hom (comp_hom (comp_hom.flip (@double l m)) ((@comp (l+l) (m+m) (n+n)))) (double) g f = comp_hom (comp_hom (@double l n)) (@comp l m n) g f, begin congr' 2, clear g f, ext g f : 2, show comp (double (of g)) (double (of f)) = double (comp (of g) (of f)), simp only [double_of, comp_of, basic_universal_map.comp], rw [matrix.reindex_mul, matrix.from_blocks_multiply], congr' 2, simp only [add_zero, matrix.zero_mul, zero_add, matrix.mul_zero], end lemma double_zero : double (0 : universal_map m n) = 0 := double.map_zero end end universal_map /-- Roughly speaking, this is a collection of formal finite sums of matrices that encode that data that rolls out of the Breen--Deligne resolution. -/ structure data := (rank : ℕ → ℕ) (map : Π n, universal_map (rank (n+1)) (rank n)) /-- Breen--Deligne data is a complex if the composition of all pairs of two subsequent maps in the data is `0`. -/ def is_complex (BD : data) : Prop := ∀ n, universal_map.comp (BD.map n) (BD.map (n+1)) = 0 /- We use a small hack: mathlib only has block matrices with 4 blocks. So we add two zero-width blocks in the definition of `σ_add` and `σ_proj`. -/ /-- The universal map `ℤ[A^n ⊕ A^n] → ℤ[A^n]` induced by the addition on `A^n`. -/ def σ_add (n : ℕ) : universal_map (n + n) n := of $ matrix.reindex_linear_equiv (equiv.sum_empty _) sum_fin_sum_equiv $ matrix.from_blocks 1 1 0 0 /-- The universal map `ℤ[A^n ⊕ A^n] → ℤ[A^n]` that is the formal sum of the two projection maps. -/ def σ_proj (n : ℕ) : universal_map (n + n) n := (of $ matrix.reindex_linear_equiv (equiv.sum_empty _) sum_fin_sum_equiv $ matrix.from_blocks 1 0 0 0) + (of $ matrix.reindex_linear_equiv (equiv.sum_empty _) sum_fin_sum_equiv $ matrix.from_blocks 0 1 0 0) /-- The universal map `ℤ[A^n ⊕ A^n] → ℤ[A^n]` that is the difference between `σ_diff` (induced by the addition on `A^n`) and `σ_proj` (the formal sum of the two projections). -/ def σ_diff (n : ℕ) := σ_add n - σ_proj n section universe variables u open universal_map variables {m n : ℕ} (A : Type u) [add_comm_group A] (f : universal_map m n) -- lemma eval_σ_add (n : ℕ) : eval A (σ_add n) = map (λ x, x.left + x.right) := -- begin -- ext x, apply lift.ext; clear x, intro x, -- delta σ_add, -- rw [eval_of, basic_universal_map.eval_of], -- congr' 1, -- ext i, -- simp only [pi.add_apply], -- rw (sum_fin_sum_equiv.sum_comp _).symm, -- swap, { apply_instance }, -- admit -- end lemma σ_add_comp_double : comp (σ_add n) (double f) = comp f (σ_add m) := show add_monoid_hom.comp_hom ((@comp (m+m) (n+n) n) (σ_add _)) (double) f = (@comp (m+m) m n).flip (σ_add _) f, begin congr' 1, clear f, ext1 f, show comp (σ_add n) (double (of f)) = comp (of f) (σ_add m), dsimp only [double_of, σ_add], simp only [comp_of], conv_rhs { rw ← (matrix.reindex_linear_equiv (equiv.sum_empty _) (equiv.sum_empty _)).apply_symm_apply f }, simp only [basic_universal_map.comp, matrix.reindex_mul, matrix.from_blocks_multiply, add_zero, matrix.one_mul, matrix.mul_one, matrix.zero_mul, zero_add, matrix.reindex_linear_equiv_sum_empty_symm] end -- lemma eval_σ_proj (n : ℕ) : eval A (σ_proj n) = map tuple.left + map tuple.right := -- begin -- ext x, apply lift.ext; clear x, intro x, -- delta σ_proj, -- simp only [add_monoid_hom.map_add, add_monoid_hom.add_apply, -- eval_of, basic_universal_map.eval_of], -- congr' 2, -- { ext i, -- rw [(sum_fin_sum_equiv.sum_comp _).symm, finset.sum_eq_single (sum.inl i)], -- { dsimp, admit }, -- all_goals { admit } }, -- admit -- end lemma σ_proj_comp_double : comp (σ_proj n) (double f) = comp f (σ_proj m) := show add_monoid_hom.comp_hom ((@comp (m+m) (n+n) n) (σ_proj _)) (double) f = (@comp (m+m) m n).flip (σ_proj _) f, begin congr' 1, clear f, ext1 f, show comp (σ_proj n) (double (of f)) = comp (of f) (σ_proj m), dsimp only [double_of, σ_proj], simp only [add_monoid_hom.map_add, add_monoid_hom.add_apply, comp_of], conv_rhs { rw ← (matrix.reindex_linear_equiv (equiv.sum_empty _) (equiv.sum_empty _)).apply_symm_apply f }, simp only [basic_universal_map.comp, matrix.reindex_mul, matrix.from_blocks_multiply, add_zero, matrix.one_mul, matrix.mul_one, matrix.zero_mul, matrix.mul_zero, zero_add, matrix.reindex_linear_equiv_sum_empty_symm], end lemma σ_diff_comp_double : comp (σ_diff n) (double f) = comp f (σ_diff m) := begin simp only [σ_diff, add_monoid_hom.map_sub, ← σ_add_comp_double, ← σ_proj_comp_double], simp only [sub_eq_add_neg, ← add_monoid_hom.neg_apply, ← add_monoid_hom.add_apply] end end /-- A `homotopy` for Breen--Deligne data `BD` consists of maps `map n`, for each natural number `n`, that constitute a homotopy between the two universal maps `σ_add` and `σ_proj`. -/ structure homotopy (BD : data) := (map : Π n, universal_map (BD.rank n + BD.rank n) (BD.rank (n+1))) (is_homotopy : ∀ n, σ_diff (BD.rank (n+1)) = universal_map.comp (BD.map (n+1)) (map (n+1)) + universal_map.comp (map n) (BD.map n).double) (is_homotopy_zero : σ_add (BD.rank 0) - σ_proj (BD.rank 0) = universal_map.comp (BD.map 0) (map 0)) -- TODO! Is ↑ the thing we want? /-- A Breen--Deligne `package` consists of Breen--Deligne `data` that forms a complex, together with a `homotopy` between the two universal maps `σ_add` and `σ_proj`. -/ structure package := (data : data) (is_complex : is_complex data) (homotopy : homotopy data) namespace package /-- `BD.rank i` is the rank of the `i`th entry in the Breen--Deligne resolution described by `BD`. -/ def rank (BD : package) := BD.data.rank /-- `BD.map i` is the `i`-th universal mapin the Breen--Deligne resolution described by `BD`. -/ def map (BD : package) := BD.data.map @[simp] lemma map_comp_map (BD : package) (n : ℕ) : universal_map.comp (BD.map n) (BD.map (n+1)) = 0 := BD.is_complex n end package namespace eg /-! ## An explicit nontrivial example -/ open universal_map /-- The `i`-th rank of this BD package is `2^i`. -/ def rank : ℕ → ℕ | 0 := 1 | (n+1) := rank n + rank n lemma rank_eq : ∀ n, rank n = 2 ^ n | 0 := rfl | (n+1) := by rw [pow_succ, two_mul, rank, rank_eq] /-- The `i`-th map of this BD package is inductively defined as the simplest solution to the homotopy condition, so that the homotopy will consist of identity maps. -/ def map : Π n, universal_map (rank (n+1)) (rank n) | 0 := σ_diff 1 | (n+1) := (σ_diff (rank (n+1))) - (map n).double /-- The Breen--Deligne data for the example BD package. -/ @[simps] def data : data := ⟨rank, map⟩ /-- The `n`-th homotopy map for the example BD package is the identity. -/ def hmap (n : ℕ) : universal_map (rank n + rank n) (rank (n+1)) := universal_map.id _ lemma hmap_is_homotopy : ∀ n, σ_diff (rank (n+1)) = comp (map (n+1)) (hmap (n+1)) + comp (hmap n) (map n).double | _ := by { simp only [hmap, id_comp, comp_id, map], simp only [sub_add_cancel], } lemma hmap_is_homotopy_zero : σ_diff (rank 0) = universal_map.comp (map 0) (hmap 0) := begin simp only [hmap, id_comp, comp_id, map, σ_diff, σ_add, σ_proj, sub_sub], congr' 3; { ext (j : fin 1) (i : fin 2), fin_cases j, fin_cases i; refl } end /-- The homotopy for the example BD package. -/ @[simps] def homotopy : homotopy data := ⟨hmap, hmap_is_homotopy, hmap_is_homotopy_zero⟩ lemma is_complex_zero : comp (map 0) (map 1) = 0 := begin show comp (σ_diff 1) (σ_diff (1+1) - double (σ_diff 1)) = 0, rw [add_monoid_hom.map_sub, σ_diff_comp_double, sub_self], end lemma is_complex_succ (n : ℕ) (ih : (comp (map n)) (map (n + 1)) = 0) : comp (map (n+1)) (map (n+1+1)) = 0 := begin have H := hmap_is_homotopy n, simp only [hmap, comp_id, id_comp] at H, show comp (map (n+1)) ((σ_diff (rank $ n+1+1)) - double (map (n+1))) = 0, simp only [add_monoid_hom.map_sub, ← σ_diff_comp_double, H], simp only [add_monoid_hom.map_add, add_monoid_hom.add_apply], simp only [comp_double_double, ih, double_zero, add_zero, sub_self], end lemma is_complex : is_complex data | 0 := is_complex_zero | (n+1) := is_complex_succ n (is_complex n) end eg /-- An example of a Breen--Deligne data coming from a nontrivial complex. -/ def eg : package := ⟨eg.data, eg.is_complex, eg.homotopy⟩ end breen_deligne #lint- only unused_arguments def_lemma doc_blame
fdc616d0a358688ea7bd5f97fb66d8dcab9c82ce
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/order/max.lean
429746fc4ab8a5caddc0f7cb698988543526b822
[ "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,388
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Yury Kudryashov, Yaël Dillies -/ import order.order_dual /-! # Minimal/maximal and bottom/top elements This file defines predicates for elements to be minimal/maximal or bottom/top and typeclasses saying that there are no such elements. ## Predicates * `is_bot`: An element is *bottom* if all elements are greater than it. * `is_top`: An element is *top* if all elements are less than it. * `is_min`: An element is *minimal* if no element is strictly less than it. * `is_max`: An element is *maximal* if no element is strictly greater than it. See also `is_bot_iff_is_min` and `is_top_iff_is_max` for the equivalences in a (co)directed order. ## Typeclasses * `no_bot_order`: An order without bottom elements. * `no_top_order`: An order without top elements. * `no_min_order`: An order without minimal elements. * `no_max_order`: An order without maximal elements. -/ open order_dual variables {α : Type*} /-- Order without bottom elements. -/ class no_bot_order (α : Type*) [has_le α] : Prop := (exists_not_ge (a : α) : ∃ b, ¬ a ≤ b) /-- Order without top elements. -/ class no_top_order (α : Type*) [has_le α] : Prop := (exists_not_le (a : α) : ∃ b, ¬ b ≤ a) /-- Order without minimal elements. Sometimes called coinitial or dense. -/ class no_min_order (α : Type*) [has_lt α] : Prop := (exists_lt (a : α) : ∃ b, b < a) /-- Order without maximal elements. Sometimes called cofinal. -/ class no_max_order (α : Type*) [has_lt α] : Prop := (exists_gt (a : α) : ∃ b, a < b) export no_bot_order (exists_not_ge) export no_top_order (exists_not_le) export no_min_order (exists_lt) export no_max_order (exists_gt) instance nonempty_lt [has_lt α] [no_min_order α] (a : α) : nonempty {x // x < a} := nonempty_subtype.2 (exists_lt a) instance nonempty_gt [has_lt α] [no_max_order α] (a : α) : nonempty {x // a < x} := nonempty_subtype.2 (exists_gt a) instance order_dual.no_bot_order (α : Type*) [has_le α] [no_top_order α] : no_bot_order (order_dual α) := ⟨λ a, @exists_not_le α _ _ a⟩ instance order_dual.no_top_order (α : Type*) [has_le α] [no_bot_order α] : no_top_order (order_dual α) := ⟨λ a, @exists_not_ge α _ _ a⟩ instance order_dual.no_min_order (α : Type*) [has_lt α] [no_max_order α] : no_min_order (order_dual α) := ⟨λ a, @exists_gt α _ _ a⟩ instance order_dual.no_max_order (α : Type*) [has_lt α] [no_min_order α] : no_max_order (order_dual α) := ⟨λ a, @exists_lt α _ _ a⟩ @[priority 100] -- See note [lower instance priority] instance no_min_order.to_no_bot_order (α : Type*) [preorder α] [no_min_order α] : no_bot_order α := ⟨λ a, (exists_lt a).imp $ λ _, not_le_of_lt⟩ @[priority 100] -- See note [lower instance priority] instance no_max_order.to_no_top_order (α : Type*) [preorder α] [no_max_order α] : no_top_order α := ⟨λ a, (exists_gt a).imp $ λ _, not_le_of_lt⟩ section has_le variables [has_le α] {a b : α} /-- `a : α` is a bottom element of `α` if it is less than or equal to any other element of `α`. This predicate is roughly an unbundled version of `order_bot`, except that a preorder may have several bottom elements. When `α` is linear, this is useful to make a case disjunction on `no_min_order α` within a proof. -/ def is_bot (a : α) : Prop := ∀ b, a ≤ b /-- `a : α` is a top element of `α` if it is greater than or equal to any other element of `α`. This predicate is roughly an unbundled version of `order_bot`, except that a preorder may have several top elements. When `α` is linear, this is useful to make a case disjunction on `no_max_order α` within a proof. -/ def is_top (a : α) : Prop := ∀ b, b ≤ a /-- `a` is a minimal element of `α` if no element is strictly less than it. We spell it without `<` to avoid having to convert between `≤` and `<`. Instead, `is_min_iff_forall_not_lt` does the conversion. -/ def is_min (a : α) : Prop := ∀ ⦃b⦄, b ≤ a → a ≤ b /-- `a` is a maximal element of `α` if no element is strictly greater than it. We spell it without `<` to avoid having to convert between `≤` and `<`. Instead, `is_max_iff_forall_not_lt` does the conversion. -/ def is_max (a : α) : Prop := ∀ ⦃b⦄, a ≤ b → b ≤ a @[simp] lemma not_is_bot [no_bot_order α] (a : α) : ¬is_bot a := λ h, let ⟨b, hb⟩ := exists_not_ge a in hb $ h _ @[simp] lemma not_is_top [no_top_order α] (a : α) : ¬is_top a := λ h, let ⟨b, hb⟩ := exists_not_le a in hb $ h _ protected lemma is_bot.is_min (h : is_bot a) : is_min a := λ b _, h b protected lemma is_top.is_max (h : is_top a) : is_max a := λ b _, h b @[simp] lemma is_bot_to_dual_iff : is_bot (to_dual a) ↔ is_top a := iff.rfl @[simp] lemma is_top_to_dual_iff : is_top (to_dual a) ↔ is_bot a := iff.rfl @[simp] lemma is_min_to_dual_iff : is_min (to_dual a) ↔ is_max a := iff.rfl @[simp] lemma is_max_to_dual_iff : is_max (to_dual a) ↔ is_min a := iff.rfl @[simp] lemma is_bot_of_dual_iff {a : order_dual α} : is_bot (of_dual a) ↔ is_top a := iff.rfl @[simp] lemma is_top_of_dual_iff {a : order_dual α} : is_top (of_dual a) ↔ is_bot a := iff.rfl @[simp] lemma is_min_of_dual_iff {a : order_dual α} : is_min (of_dual a) ↔ is_max a := iff.rfl @[simp] lemma is_max_of_dual_iff {a : order_dual α} : is_max (of_dual a) ↔ is_min a := iff.rfl alias is_bot_to_dual_iff ↔ _ is_top.to_dual alias is_top_to_dual_iff ↔ _ is_bot.to_dual alias is_min_to_dual_iff ↔ _ is_max.to_dual alias is_max_to_dual_iff ↔ _ is_min.to_dual alias is_bot_of_dual_iff ↔ _ is_top.of_dual alias is_top_of_dual_iff ↔ _ is_bot.of_dual alias is_min_of_dual_iff ↔ _ is_max.of_dual alias is_max_of_dual_iff ↔ _ is_min.of_dual end has_le section preorder variables [preorder α] {a b : α} lemma is_bot.mono (ha : is_bot a) (h : b ≤ a) : is_bot b := λ c, h.trans $ ha _ lemma is_top.mono (ha : is_top a) (h : a ≤ b) : is_top b := λ c, (ha _).trans h lemma is_min.mono (ha : is_min a) (h : b ≤ a) : is_min b := λ c hc, h.trans $ ha $ hc.trans h lemma is_max.mono (ha : is_max a) (h : a ≤ b) : is_max b := λ c hc, (ha $ h.trans hc).trans h lemma is_min.not_lt (h : is_min a) : ¬ b < a := λ hb, hb.not_le $ h hb.le lemma is_max.not_lt (h : is_max a) : ¬ a < b := λ hb, hb.not_le $ h hb.le lemma is_min_iff_forall_not_lt : is_min a ↔ ∀ b, ¬ b < a := ⟨λ h _, h.not_lt, λ h b hba, of_not_not $ λ hab, h _ $ hba.lt_of_not_le hab⟩ lemma is_max_iff_forall_not_lt : is_max a ↔ ∀ b, ¬ a < b := ⟨λ h _, h.not_lt, λ h b hba, of_not_not $ λ hab, h _ $ hba.lt_of_not_le hab⟩ @[simp] lemma not_is_min_iff : ¬ is_min a ↔ ∃ b, b < a := by simp_rw [lt_iff_le_not_le, is_min, not_forall, exists_prop] @[simp] lemma not_is_max_iff : ¬ is_max a ↔ ∃ b, a < b := by simp_rw [lt_iff_le_not_le, is_max, not_forall, exists_prop] @[simp] lemma not_is_min [no_min_order α] (a : α) : ¬ is_min a := not_is_min_iff.2 $ exists_lt a @[simp] lemma not_is_max [no_max_order α] (a : α) : ¬ is_max a := not_is_max_iff.2 $ exists_gt a namespace subsingleton variable [subsingleton α] protected lemma is_bot (a : α) : is_bot a := λ _, (subsingleton.elim _ _).le protected lemma is_top (a : α) : is_top a := λ _, (subsingleton.elim _ _).le protected lemma is_min (a : α) : is_min a := (subsingleton.is_bot _).is_min protected lemma is_max (a : α) : is_max a := (subsingleton.is_top _).is_max end subsingleton end preorder section partial_order variables [partial_order α] {a b : α} protected lemma is_min.eq_of_le (ha : is_min a) (h : b ≤ a) : b = a := h.antisymm $ ha h protected lemma is_min.eq_of_ge (ha : is_min a) (h : b ≤ a) : a = b := h.antisymm' $ ha h protected lemma is_max.eq_of_le (ha : is_max a) (h : a ≤ b) : a = b := h.antisymm $ ha h protected lemma is_max.eq_of_ge (ha : is_max a) (h : a ≤ b) : b = a := h.antisymm' $ ha h end partial_order section linear_order variables [linear_order α] --TODO: Delete in favor of the directed version lemma is_top_or_exists_gt (a : α) : is_top a ∨ ∃ b, a < b := by simpa only [or_iff_not_imp_left, is_top, not_forall, not_le] using id lemma is_bot_or_exists_lt (a : α) : is_bot a ∨ ∃ b, b < a := @is_top_or_exists_gt (order_dual α) _ a end linear_order
1b4f2d24fed6a742d63eb6b95bbc2174d289021b
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/data/nat/enat.lean
ff626de1de661ee0ce56ca5334c7f3d67443ed4f
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
12,662
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes Natural numbers with infinity, represented as roption ℕ. -/ import data.pfun algebra.ordered_group import tactic.norm_cast tactic.norm_num open roption def enat : Type := roption ℕ namespace enat instance : has_zero enat := ⟨some 0⟩ instance : inhabited enat := ⟨0⟩ instance : has_one enat := ⟨some 1⟩ instance : has_add enat := ⟨λ x y, ⟨x.dom ∧ y.dom, λ h, get x h.1 + get y h.2⟩⟩ instance : has_coe ℕ enat := ⟨some⟩ instance (n : ℕ) : decidable (n : enat).dom := is_true trivial @[simp] lemma coe_inj {x y : ℕ} : (x : enat) = y ↔ x = y := roption.some_inj instance : add_comm_monoid enat := { add := (+), zero := (0), add_comm := λ x y, roption.ext' and.comm (λ _ _, add_comm _ _), zero_add := λ x, roption.ext' (true_and _) (λ _ _, zero_add _), add_zero := λ x, roption.ext' (and_true _) (λ _ _, add_zero _), add_assoc := λ x y z, roption.ext' and.assoc (λ _ _, add_assoc _ _ _) } instance : has_le enat := ⟨λ x y, ∃ h : y.dom → x.dom, ∀ hy : y.dom, x.get (h hy) ≤ y.get hy⟩ instance : has_top enat := ⟨none⟩ instance : has_bot enat := ⟨0⟩ instance : has_sup enat := ⟨λ x y, ⟨x.dom ∧ y.dom, λ h, x.get h.1 ⊔ y.get h.2⟩⟩ @[elab_as_eliminator] protected lemma cases_on {P : enat → Prop} : ∀ a : enat, P ⊤ → (∀ n : ℕ, P n) → P a := roption.induction_on @[simp] lemma top_add (x : enat) : ⊤ + x = ⊤ := roption.ext' (false_and _) (λ h, h.left.elim) @[simp] lemma add_top (x : enat) : x + ⊤ = ⊤ := by rw [add_comm, top_add] @[simp, squash_cast] lemma coe_zero : ((0 : ℕ) : enat) = 0 := rfl @[simp, squash_cast] lemma coe_one : ((1 : ℕ) : enat) = 1 := rfl @[simp, move_cast] lemma coe_add (x y : ℕ) : ((x + y : ℕ) : enat) = x + y := roption.ext' (and_true _).symm (λ _ _, rfl) @[simp, elim_cast] lemma get_coe {x : ℕ} : get (x : enat) true.intro = x := rfl lemma coe_add_get {x : ℕ} {y : enat} (h : ((x : enat) + y).dom) : get ((x : enat) + y) h = x + get y h.2 := rfl @[simp] lemma get_add {x y : enat} (h : (x + y).dom) : get (x + y) h = x.get h.1 + y.get h.2 := rfl @[simp, squash_cast] lemma coe_get {x : enat} (h : x.dom) : (x.get h : enat) = x := roption.ext' (iff_of_true trivial h) (λ _ _, rfl) @[simp] lemma get_zero (h : (0 : enat).dom) : (0 : enat).get h = 0 := rfl @[simp] lemma get_one (h : (1 : enat).dom) : (1 : enat).get h = 1 := rfl lemma dom_of_le_some {x : enat} {y : ℕ} : x ≤ y → x.dom := λ ⟨h, _⟩, h trivial instance : partial_order enat := { le := (≤), le_refl := λ x, ⟨id, λ _, le_refl _⟩, le_trans := λ x y z ⟨hxy₁, hxy₂⟩ ⟨hyz₁, hyz₂⟩, ⟨hxy₁ ∘ hyz₁, λ _, le_trans (hxy₂ _) (hyz₂ _)⟩, le_antisymm := λ x y ⟨hxy₁, hxy₂⟩ ⟨hyx₁, hyx₂⟩, roption.ext' ⟨hyx₁, hxy₁⟩ (λ _ _, le_antisymm (hxy₂ _) (hyx₂ _)) } @[simp, elim_cast] lemma coe_le_coe {x y : ℕ} : (x : enat) ≤ y ↔ x ≤ y := ⟨λ ⟨_, h⟩, h trivial, λ h, ⟨λ _, trivial, λ _, h⟩⟩ @[simp, elim_cast] lemma coe_lt_coe {x y : ℕ} : (x : enat) < y ↔ x < y := by rw [lt_iff_le_not_le, lt_iff_le_not_le, coe_le_coe, coe_le_coe] lemma get_le_get {x y : enat} {hx : x.dom} {hy : y.dom} : x.get hx ≤ y.get hy ↔ x ≤ y := by conv { to_lhs, rw [← coe_le_coe, coe_get, coe_get]} instance semilattice_sup_bot : semilattice_sup_bot enat := { sup := (⊔), bot := (⊥), bot_le := λ _, ⟨λ _, trivial, λ _, nat.zero_le _⟩, le_sup_left := λ _ _, ⟨and.left, λ _, le_sup_left⟩, le_sup_right := λ _ _, ⟨and.right, λ _, le_sup_right⟩, sup_le := λ x y z ⟨hx₁, hx₂⟩ ⟨hy₁, hy₂⟩, ⟨λ hz, ⟨hx₁ hz, hy₁ hz⟩, λ _, sup_le (hx₂ _) (hy₂ _)⟩, ..enat.partial_order } instance order_top : order_top enat := { top := (⊤), le_top := λ x, ⟨λ h, false.elim h, λ hy, false.elim hy⟩, ..enat.semilattice_sup_bot } lemma top_eq_none : (⊤ : enat) = none := rfl lemma coe_lt_top (x : ℕ) : (x : enat) < ⊤ := lt_of_le_of_ne le_top (λ h, absurd (congr_arg dom h) true_ne_false) @[simp] lemma coe_ne_top (x : ℕ) : (x : enat) ≠ ⊤ := ne_of_lt (coe_lt_top x) lemma ne_top_iff {x : enat} : x ≠ ⊤ ↔ ∃(n : ℕ), x = n := roption.ne_none_iff lemma ne_top_iff_dom {x : enat} : x ≠ ⊤ ↔ x.dom := by classical; exact not_iff_comm.1 roption.eq_none_iff'.symm lemma ne_top_of_lt {x y : enat} (h : x < y) : x ≠ ⊤ := ne_of_lt $ lt_of_lt_of_le h le_top lemma pos_iff_one_le {x : enat} : 0 < x ↔ 1 ≤ x := enat.cases_on x ⟨λ _, le_top, λ _, coe_lt_top _⟩ (λ n, ⟨λ h, enat.coe_le_coe.2 (enat.coe_lt_coe.1 h), λ h, enat.coe_lt_coe.2 (enat.coe_le_coe.1 h)⟩) noncomputable instance : decidable_linear_order enat := { le_total := λ x y, enat.cases_on x (or.inr le_top) (enat.cases_on y (λ _, or.inl le_top) (λ x y, (le_total x y).elim (or.inr ∘ coe_le_coe.2) (or.inl ∘ coe_le_coe.2))), decidable_le := classical.dec_rel _, ..enat.partial_order } noncomputable instance : bounded_lattice enat := { inf := min, inf_le_left := min_le_left, inf_le_right := min_le_right, le_inf := λ _ _ _, le_min, ..enat.order_top, ..enat.semilattice_sup_bot } lemma sup_eq_max {a b : enat} : a ⊔ b = max a b := le_antisymm (sup_le (le_max_left _ _) (le_max_right _ _)) (max_le le_sup_left le_sup_right) lemma inf_eq_min {a b : enat} : a ⊓ b = min a b := rfl instance : ordered_add_comm_monoid enat := { add_le_add_left := λ a b ⟨h₁, h₂⟩ c, enat.cases_on c (by simp) (λ c, ⟨λ h, and.intro trivial (h₁ h.2), λ _, add_le_add_left (h₂ _) c⟩), lt_of_add_lt_add_left := λ a b c, enat.cases_on a (λ h, by simpa [lt_irrefl] using h) (λ a, enat.cases_on b (λ h, absurd h (not_lt_of_ge (by rw add_top; exact le_top))) (λ b, enat.cases_on c (λ _, coe_lt_top _) (λ c h, coe_lt_coe.2 (by rw [← coe_add, ← coe_add, coe_lt_coe] at h; exact lt_of_add_lt_add_left h)))), ..enat.decidable_linear_order, ..enat.add_comm_monoid } instance : canonically_ordered_add_monoid enat := { le_iff_exists_add := λ a b, enat.cases_on b (iff_of_true le_top ⟨⊤, (add_top _).symm⟩) (λ b, enat.cases_on a (iff_of_false (not_le_of_gt (coe_lt_top _)) (not_exists.2 (λ x, ne_of_lt (by rw [top_add]; exact coe_lt_top _)))) (λ a, ⟨λ h, ⟨(b - a : ℕ), by rw [← coe_add, coe_inj, add_comm, nat.sub_add_cancel (coe_le_coe.1 h)]⟩, (λ ⟨c, hc⟩, enat.cases_on c (λ hc, hc.symm ▸ show (a : enat) ≤ a + ⊤, by rw [add_top]; exact le_top) (λ c (hc : (b : enat) = a + c), coe_le_coe.2 (by rw [← coe_add, coe_inj] at hc; rw hc; exact nat.le_add_right _ _)) hc)⟩)), ..enat.semilattice_sup_bot, ..enat.ordered_add_comm_monoid } protected lemma add_lt_add_right {x y z : enat} (h : x < y) (hz : z ≠ ⊤) : x + z < y + z := begin rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩, rcases ne_top_iff.mp hz with ⟨k, rfl⟩, induction y using enat.cases_on with n, { rw [top_add], apply_mod_cast coe_lt_top }, norm_cast at h, apply_mod_cast add_lt_add_right h end protected lemma add_lt_add_iff_right {x y z : enat} (hz : z ≠ ⊤) : x + z < y + z ↔ x < y := ⟨lt_of_add_lt_add_right', λ h, enat.add_lt_add_right h hz⟩ protected lemma add_lt_add_iff_left {x y z : enat} (hz : z ≠ ⊤) : z + x < z + y ↔ x < y := by rw [add_comm z, add_comm z, enat.add_lt_add_iff_right hz] protected lemma lt_add_iff_pos_right {x y : enat} (hx : x ≠ ⊤) : x < x + y ↔ 0 < y := by { conv_rhs { rw [← enat.add_lt_add_iff_left hx] }, rw [add_zero] } lemma lt_add_one {x : enat} (hx : x ≠ ⊤) : x < x + 1 := by { rw [enat.lt_add_iff_pos_right hx], norm_cast, norm_num } lemma le_of_lt_add_one {x y : enat} (h : x < y + 1) : x ≤ y := begin induction y using enat.cases_on with n, apply le_top, rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩, apply_mod_cast nat.le_of_lt_succ, apply_mod_cast h end lemma add_one_le_of_lt {x y : enat} (h : x < y) : x + 1 ≤ y := begin induction y using enat.cases_on with n, apply le_top, rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩, apply_mod_cast nat.succ_le_of_lt, apply_mod_cast h end lemma add_one_le_iff_lt {x y : enat} (hx : x ≠ ⊤) : x + 1 ≤ y ↔ x < y := begin split, swap, exact add_one_le_of_lt, intro h, rcases ne_top_iff.mp hx with ⟨m, rfl⟩, induction y using enat.cases_on with n, apply coe_lt_top, apply_mod_cast nat.lt_of_succ_le, apply_mod_cast h end lemma lt_add_one_iff_lt {x y : enat} (hx : x ≠ ⊤) : x < y + 1 ↔ x ≤ y := begin split, exact le_of_lt_add_one, intro h, rcases ne_top_iff.mp hx with ⟨m, rfl⟩, induction y using enat.cases_on with n, { rw [top_add], apply coe_lt_top }, apply_mod_cast nat.lt_succ_of_le, apply_mod_cast h end lemma add_eq_top_iff {a b : enat} : a + b = ⊤ ↔ a = ⊤ ∨ b = ⊤ := by apply enat.cases_on a; apply enat.cases_on b; simp; simp only [(enat.coe_add _ _).symm, enat.coe_ne_top]; simp protected lemma add_right_cancel_iff {a b c : enat} (hc : c ≠ ⊤) : a + c = b + c ↔ a = b := begin rcases ne_top_iff.1 hc with ⟨c, rfl⟩, apply enat.cases_on a; apply enat.cases_on b; simp [add_eq_top_iff, coe_ne_top, @eq_comm _ (⊤ : enat)]; simp only [(enat.coe_add _ _).symm, add_left_cancel_iff, enat.coe_inj, add_comm]; tauto end protected lemma add_left_cancel_iff {a b c : enat} (ha : a ≠ ⊤) : a + b = a + c ↔ b = c := by rw [add_comm a, add_comm a, enat.add_right_cancel_iff ha] section with_top /-- Computably converts an `enat` to a `with_top ℕ`. -/ def to_with_top (x : enat) [decidable x.dom]: with_top ℕ := x.to_option lemma to_with_top_top : to_with_top ⊤ = ⊤ := rfl @[simp] lemma to_with_top_top' {h : decidable (⊤ : enat).dom} : to_with_top ⊤ = ⊤ := by convert to_with_top_top lemma to_with_top_zero : to_with_top 0 = 0 := rfl @[simp] lemma to_with_top_zero' {h : decidable (0 : enat).dom}: to_with_top 0 = 0 := by convert to_with_top_zero lemma to_with_top_coe (n : ℕ) : to_with_top n = n := rfl @[simp] lemma to_with_top_coe' (n : ℕ) {h : decidable (n : enat).dom} : to_with_top (n : enat) = n := by convert to_with_top_coe n @[simp] lemma to_with_top_le {x y : enat} : Π [decidable x.dom] [decidable y.dom], by exactI to_with_top x ≤ to_with_top y ↔ x ≤ y := enat.cases_on y (by simp) (enat.cases_on x (by simp) (by intros; simp)) @[simp] lemma to_with_top_lt {x y : enat} [decidable x.dom] [decidable y.dom] : to_with_top x < to_with_top y ↔ x < y := by simp only [lt_iff_le_not_le, to_with_top_le] end with_top section with_top_equiv open_locale classical /-- Order isomorphism between `enat` and `with_top ℕ`. -/ noncomputable def with_top_equiv : enat ≃ with_top ℕ := { to_fun := λ x, to_with_top x, inv_fun := λ x, match x with (some n) := coe n | none := ⊤ end, left_inv := λ x, by apply enat.cases_on x; intros; simp; refl, right_inv := λ x, by cases x; simp [with_top_equiv._match_1]; refl } @[simp] lemma with_top_equiv_top : with_top_equiv ⊤ = ⊤ := to_with_top_top' @[simp] lemma with_top_equiv_coe (n : nat) : with_top_equiv n = n := to_with_top_coe' _ @[simp] lemma with_top_equiv_zero : with_top_equiv 0 = 0 := with_top_equiv_coe _ @[simp] lemma with_top_equiv_le {x y : enat} : with_top_equiv x ≤ with_top_equiv y ↔ x ≤ y := to_with_top_le @[simp] lemma with_top_equiv_lt {x y : enat} : with_top_equiv x < with_top_equiv y ↔ x < y := to_with_top_lt @[simp] lemma with_top_equiv_symm_top : with_top_equiv.symm ⊤ = ⊤ := rfl @[simp] lemma with_top_equiv_symm_coe (n : nat) : with_top_equiv.symm n = n := rfl @[simp] lemma with_top_equiv_symm_zero : with_top_equiv.symm 0 = 0 := rfl @[simp] lemma with_top_equiv_symm_le {x y : with_top ℕ} : with_top_equiv.symm x ≤ with_top_equiv.symm y ↔ x ≤ y := by rw ← with_top_equiv_le; simp @[simp] lemma with_top_equiv_symm_lt {x y : with_top ℕ} : with_top_equiv.symm x < with_top_equiv.symm y ↔ x < y := by rw ← with_top_equiv_lt; simp end with_top_equiv lemma lt_wf : well_founded ((<) : enat → enat → Prop) := show well_founded (λ a b : enat, a < b), by haveI := classical.dec; simp only [to_with_top_lt.symm] {eta := ff}; exact inv_image.wf _ (with_top.well_founded_lt nat.lt_wf) instance : has_well_founded enat := ⟨(<), lt_wf⟩ end enat
384d08a6fbd5fa62b1da2735341d030c444ef836
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/monad/basic.lean
39ef7f54e7773f1fb2c15b888a4f50f3e1dba84c
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
10,489
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta, Adam Topaz -/ import category_theory.functor.category import category_theory.functor.fully_faithful import category_theory.functor.reflects_isomorphisms namespace category_theory open category universes v₁ u₁ -- morphism levels before object levels. See note [category_theory universes]. variables (C : Type u₁) [category.{v₁} C] /-- The data of a monad on C consists of an endofunctor T together with natural transformations η : 𝟭 C ⟶ T and μ : T ⋙ T ⟶ T satisfying three equations: - T μ_X ≫ μ_X = μ_(TX) ≫ μ_X (associativity) - η_(TX) ≫ μ_X = 1_X (left unit) - Tη_X ≫ μ_X = 1_X (right unit) -/ structure monad extends C ⥤ C := (η' [] : 𝟭 _ ⟶ to_functor) (μ' [] : to_functor ⋙ to_functor ⟶ to_functor) (assoc' : ∀ X, to_functor.map (nat_trans.app μ' X) ≫ μ'.app _ = μ'.app _ ≫ μ'.app _ . obviously) (left_unit' : ∀ X : C, η'.app (to_functor.obj X) ≫ μ'.app _ = 𝟙 _ . obviously) (right_unit' : ∀ X : C, to_functor.map (η'.app X) ≫ μ'.app _ = 𝟙 _ . obviously) /-- The data of a comonad on C consists of an endofunctor G together with natural transformations ε : G ⟶ 𝟭 C and δ : G ⟶ G ⋙ G satisfying three equations: - δ_X ≫ G δ_X = δ_X ≫ δ_(GX) (coassociativity) - δ_X ≫ ε_(GX) = 1_X (left counit) - δ_X ≫ G ε_X = 1_X (right counit) -/ structure comonad extends C ⥤ C := (ε' [] : to_functor ⟶ 𝟭 _) (δ' [] : to_functor ⟶ to_functor ⋙ to_functor) (coassoc' : ∀ X, nat_trans.app δ' _ ≫ to_functor.map (δ'.app X) = δ'.app _ ≫ δ'.app _ . obviously) (left_counit' : ∀ X : C, δ'.app X ≫ ε'.app (to_functor.obj X) = 𝟙 _ . obviously) (right_counit' : ∀ X : C, δ'.app X ≫ to_functor.map (ε'.app X) = 𝟙 _ . obviously) variables {C} (T : monad C) (G : comonad C) instance coe_monad : has_coe (monad C) (C ⥤ C) := ⟨λ T, T.to_functor⟩ instance coe_comonad : has_coe (comonad C) (C ⥤ C) := ⟨λ G, G.to_functor⟩ @[simp] lemma monad_to_functor_eq_coe : T.to_functor = T := rfl @[simp] lemma comonad_to_functor_eq_coe : G.to_functor = G := rfl /-- The unit for the monad `T`. -/ def monad.η : 𝟭 _ ⟶ (T : C ⥤ C) := T.η' /-- The multiplication for the monad `T`. -/ def monad.μ : (T : C ⥤ C) ⋙ (T : C ⥤ C) ⟶ T := T.μ' /-- The counit for the comonad `G`. -/ def comonad.ε : (G : C ⥤ C) ⟶ 𝟭 _ := G.ε' /-- The comultiplication for the comonad `G`. -/ def comonad.δ : (G : C ⥤ C) ⟶ (G : C ⥤ C) ⋙ G := G.δ' /-- A custom simps projection for the functor part of a monad, as a coercion. -/ def monad.simps.coe := (T : C ⥤ C) /-- A custom simps projection for the unit of a monad, in simp normal form. -/ def monad.simps.η : 𝟭 _ ⟶ (T : C ⥤ C) := T.η /-- A custom simps projection for the multiplication of a monad, in simp normal form. -/ def monad.simps.μ : (T : C ⥤ C) ⋙ (T : C ⥤ C) ⟶ (T : C ⥤ C) := T.μ /-- A custom simps projection for the functor part of a comonad, as a coercion. -/ def comonad.simps.coe := (G : C ⥤ C) /-- A custom simps projection for the counit of a comonad, in simp normal form. -/ def comonad.simps.ε : (G : C ⥤ C) ⟶ 𝟭 _ := G.ε /-- A custom simps projection for the comultiplication of a comonad, in simp normal form. -/ def comonad.simps.δ : (G : C ⥤ C) ⟶ (G : C ⥤ C) ⋙ (G : C ⥤ C) := G.δ initialize_simps_projections category_theory.monad (to_functor → coe, η' → η, μ' → μ) initialize_simps_projections category_theory.comonad (to_functor → coe, ε' → ε, δ' → δ) @[reassoc] lemma monad.assoc (T : monad C) (X : C) : (T : C ⥤ C).map (T.μ.app X) ≫ T.μ.app _ = T.μ.app _ ≫ T.μ.app _ := T.assoc' X @[simp, reassoc] lemma monad.left_unit (T : monad C) (X : C) : T.η.app ((T : C ⥤ C).obj X) ≫ T.μ.app X = 𝟙 ((T : C ⥤ C).obj X) := T.left_unit' X @[simp, reassoc] lemma monad.right_unit (T : monad C) (X : C) : (T : C ⥤ C).map (T.η.app X) ≫ T.μ.app X = 𝟙 ((T : C ⥤ C).obj X) := T.right_unit' X @[reassoc] lemma comonad.coassoc (G : comonad C) (X : C) : G.δ.app _ ≫ (G : C ⥤ C).map (G.δ.app X) = G.δ.app _ ≫ G.δ.app _ := G.coassoc' X @[simp, reassoc] lemma comonad.left_counit (G : comonad C) (X : C) : G.δ.app X ≫ G.ε.app ((G : C ⥤ C).obj X) = 𝟙 ((G : C ⥤ C).obj X) := G.left_counit' X @[simp, reassoc] lemma comonad.right_counit (G : comonad C) (X : C) : G.δ.app X ≫ (G : C ⥤ C).map (G.ε.app X) = 𝟙 ((G : C ⥤ C).obj X) := G.right_counit' X /-- A morphism of monads is a natural transformation compatible with η and μ. -/ @[ext] structure monad_hom (T₁ T₂ : monad C) extends nat_trans (T₁ : C ⥤ C) T₂ := (app_η' : ∀ X, T₁.η.app X ≫ app X = T₂.η.app X . obviously) (app_μ' : ∀ X, T₁.μ.app X ≫ app X = ((T₁ : C ⥤ C).map (app X) ≫ app _) ≫ T₂.μ.app X . obviously) /-- A morphism of comonads is a natural transformation compatible with ε and δ. -/ @[ext] structure comonad_hom (M N : comonad C) extends nat_trans (M : C ⥤ C) N := (app_ε' : ∀ X, app X ≫ N.ε.app X = M.ε.app X . obviously) (app_δ' : ∀ X, app X ≫ N.δ.app X = M.δ.app X ≫ app _ ≫ (N : C ⥤ C).map (app X) . obviously) restate_axiom monad_hom.app_η' restate_axiom monad_hom.app_μ' attribute [simp, reassoc] monad_hom.app_η monad_hom.app_μ restate_axiom comonad_hom.app_ε' restate_axiom comonad_hom.app_δ' attribute [simp, reassoc] comonad_hom.app_ε comonad_hom.app_δ instance : category (monad C) := { hom := monad_hom, id := λ M, { to_nat_trans := 𝟙 (M : C ⥤ C) }, comp := λ _ _ _ f g, { to_nat_trans := { app := λ X, f.app X ≫ g.app X } } } instance : category (comonad C) := { hom := comonad_hom, id := λ M, { to_nat_trans := 𝟙 (M : C ⥤ C) }, comp := λ M N L f g, { to_nat_trans := { app := λ X, f.app X ≫ g.app X } } } instance {T : monad C} : inhabited (monad_hom T T) := ⟨𝟙 T⟩ @[simp] lemma monad_hom.id_to_nat_trans (T : monad C) : (𝟙 T : T ⟶ T).to_nat_trans = 𝟙 (T : C ⥤ C) := rfl @[simp] lemma monad_hom.comp_to_nat_trans {T₁ T₂ T₃ : monad C} (f : T₁ ⟶ T₂) (g : T₂ ⟶ T₃) : (f ≫ g).to_nat_trans = ((f.to_nat_trans : _ ⟶ (T₂ : C ⥤ C)) ≫ g.to_nat_trans : (T₁ : C ⥤ C) ⟶ T₃) := rfl instance {G : comonad C} : inhabited (comonad_hom G G) := ⟨𝟙 G⟩ @[simp] lemma comonad_hom.id_to_nat_trans (T : comonad C) : (𝟙 T : T ⟶ T).to_nat_trans = 𝟙 (T : C ⥤ C) := rfl @[simp] lemma comp_to_nat_trans {T₁ T₂ T₃ : comonad C} (f : T₁ ⟶ T₂) (g : T₂ ⟶ T₃) : (f ≫ g).to_nat_trans = ((f.to_nat_trans : _ ⟶ (T₂ : C ⥤ C)) ≫ g.to_nat_trans : (T₁ : C ⥤ C) ⟶ T₃) := rfl /-- Construct a monad isomorphism from a natural isomorphism of functors where the forward direction is a monad morphism. -/ @[simps] def monad_iso.mk {M N : monad C} (f : (M : C ⥤ C) ≅ N) (f_η f_μ) : M ≅ N := { hom := { to_nat_trans := f.hom, app_η' := f_η, app_μ' := f_μ }, inv := { to_nat_trans := f.inv, app_η' := λ X, by simp [←f_η], app_μ' := λ X, begin rw ←nat_iso.cancel_nat_iso_hom_right f, simp only [nat_trans.naturality, iso.inv_hom_id_app, assoc, comp_id, f_μ, nat_trans.naturality_assoc, iso.inv_hom_id_app_assoc, ←functor.map_comp_assoc], simp, end } } /-- Construct a comonad isomorphism from a natural isomorphism of functors where the forward direction is a comonad morphism. -/ @[simps] def comonad_iso.mk {M N : comonad C} (f : (M : C ⥤ C) ≅ N) (f_ε f_δ) : M ≅ N := { hom := { to_nat_trans := f.hom, app_ε' := f_ε, app_δ' := f_δ }, inv := { to_nat_trans := f.inv, app_ε' := λ X, by simp [←f_ε], app_δ' := λ X, begin rw ←nat_iso.cancel_nat_iso_hom_left f, simp only [reassoc_of (f_δ X), iso.hom_inv_id_app_assoc, nat_trans.naturality_assoc], rw [←functor.map_comp, iso.hom_inv_id_app, functor.map_id], apply (comp_id _).symm end } } variable (C) /-- The forgetful functor from the category of monads to the category of endofunctors. -/ @[simps] def monad_to_functor : monad C ⥤ (C ⥤ C) := { obj := λ T, T, map := λ M N f, f.to_nat_trans } instance : faithful (monad_to_functor C) := {}. @[simp] lemma monad_to_functor_map_iso_monad_iso_mk {M N : monad C} (f : (M : C ⥤ C) ≅ N) (f_η f_μ) : (monad_to_functor _).map_iso (monad_iso.mk f f_η f_μ) = f := by { ext, refl } instance : reflects_isomorphisms (monad_to_functor C) := { reflects := λ M N f i, begin resetI, convert is_iso.of_iso (monad_iso.mk (as_iso ((monad_to_functor C).map f)) f.app_η f.app_μ), ext; refl, end } /-- The forgetful functor from the category of comonads to the category of endofunctors. -/ @[simps] def comonad_to_functor : comonad C ⥤ (C ⥤ C) := { obj := λ G, G, map := λ M N f, f.to_nat_trans } instance : faithful (comonad_to_functor C) := {}. @[simp] lemma comonad_to_functor_map_iso_comonad_iso_mk {M N : comonad C} (f : (M : C ⥤ C) ≅ N) (f_ε f_δ) : (comonad_to_functor _).map_iso (comonad_iso.mk f f_ε f_δ) = f := by { ext, refl } instance : reflects_isomorphisms (comonad_to_functor C) := { reflects := λ M N f i, begin resetI, convert is_iso.of_iso (comonad_iso.mk (as_iso ((comonad_to_functor C).map f)) f.app_ε f.app_δ), ext; refl, end } variable {C} /-- An isomorphism of monads gives a natural isomorphism of the underlying functors. -/ @[simps {rhs_md := semireducible}] def monad_iso.to_nat_iso {M N : monad C} (h : M ≅ N) : (M : C ⥤ C) ≅ N := (monad_to_functor C).map_iso h /-- An isomorphism of comonads gives a natural isomorphism of the underlying functors. -/ @[simps {rhs_md := semireducible}] def comonad_iso.to_nat_iso {M N : comonad C} (h : M ≅ N) : (M : C ⥤ C) ≅ N := (comonad_to_functor C).map_iso h variable (C) namespace monad /-- The identity monad. -/ @[simps] def id : monad C := { to_functor := 𝟭 C, η' := 𝟙 (𝟭 C), μ' := 𝟙 (𝟭 C) } instance : inhabited (monad C) := ⟨monad.id C⟩ end monad namespace comonad /-- The identity comonad. -/ @[simps] def id : comonad C := { to_functor := 𝟭 _, ε' := 𝟙 (𝟭 C), δ' := 𝟙 (𝟭 C) } instance : inhabited (comonad C) := ⟨comonad.id C⟩ end comonad end category_theory
ef19c79b7a3873f99f0efb586b3fc54d07c93fca
5a8eb1c11f93715e070b588e85f2961065c3714d
/books/theorem-proving-in-lean/ch02-06.lean
cde2749acca17c078f79a3afad2aea1642035597
[ "MIT" ]
permissive
luksamuk/study
0e19bf99d33e0793127c3d3f8ad3936fbeb36505
6a9417e071a8624c4cd9db696c16a3abcc430219
refs/heads/master
1,677,960,533,266
1,676,234,529,000
1,676,234,529,000
151,009,060
4
1
MIT
1,676,234,531,000
1,538,343,224,000
C++
UTF-8
Lean
false
false
830
lean
-- Explicitly declaring types in definitions def compose (α β γ : Type) (g : β → γ) (f : α → β) (x : α) : γ := g (f x) def do_twice (α : Type) (h : α → α) (x : α) : α := h (h x) def do_thrice (α : Type) (h : α → α) (x : α) : α := h (h (h x)) -- Using variables variables (α β γ : Type) def compose' (g : β → γ) (f : α → β) (x : α) : γ := g (f x) def do_twice' (h : α → α) (x : α) : α := h (h x) def do_thrice' (h : α → α) (x : α) : α := h (h (h x)) -- Variables can actually be of any type variables (g' : β → γ) (f' : α → β) (h' : α → α) variable x' : α def compose'' := g' (f' x') def do_twice'' := h' (h' x') def do_thrice'' := h' (h' (h' x')) #print compose'' #print do_twice'' #print do_thrice''
8744759fcfefd32c3cf5a5c50f7b03244a90e1a5
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/number_theory/function_field.lean
a89d7f2671bc4ba2338d3d98ee928bf770af2a95
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
10,601
lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen, Ashvni Narayanan -/ import field_theory.ratfunc import ring_theory.algebraic import ring_theory.dedekind_domain.integral_closure import ring_theory.integrally_closed import topology.algebra.valued_field /-! # Function fields This file defines a function field and the ring of integers corresponding to it. ## Main definitions - `function_field Fq F` states that `F` is a function field over the (finite) field `Fq`, i.e. it is a finite extension of the field of rational functions in one variable over `Fq`. - `function_field.ring_of_integers` defines the ring of integers corresponding to a function field as the integral closure of `polynomial Fq` in the function field. - `function_field.infty_valuation` : The place at infinity on `Fq(t)` is the nonarchimedean valuation on `Fq(t)` with uniformizer `1/t`. - `function_field.Fqt_infty` : The completion `Fq((t⁻¹))` of `Fq(t)` with respect to the valuation at infinity. ## Implementation notes The definitions that involve a field of fractions choose a canonical field of fractions, but are independent of that choice. We also omit assumptions like `finite Fq` or `is_scalar_tower Fq[X] (fraction_ring Fq[X]) F` in definitions, adding them back in lemmas when they are needed. ## References * [D. Marcus, *Number Fields*][marcus1977number] * [J.W.S. Cassels, A. Frölich, *Algebraic Number Theory*][cassels1967algebraic] * [P. Samuel, *Algebraic Theory of Numbers*][samuel1970algebraic] ## Tags function field, ring of integers -/ noncomputable theory open_locale non_zero_divisors polynomial discrete_valuation variables (Fq F : Type) [field Fq] [field F] /-- `F` is a function field over the finite field `Fq` if it is a finite extension of the field of rational functions in one variable over `Fq`. Note that `F` can be a function field over multiple, non-isomorphic, `Fq`. -/ abbreviation function_field [algebra (ratfunc Fq) F] : Prop := finite_dimensional (ratfunc Fq) F /-- `F` is a function field over `Fq` iff it is a finite extension of `Fq(t)`. -/ protected lemma function_field_iff (Fqt : Type*) [field Fqt] [algebra Fq[X] Fqt] [is_fraction_ring Fq[X] Fqt] [algebra (ratfunc Fq) F] [algebra Fqt F] [algebra Fq[X] F] [is_scalar_tower Fq[X] Fqt F] [is_scalar_tower Fq[X] (ratfunc Fq) F] : function_field Fq F ↔ finite_dimensional Fqt F := begin let e := is_localization.alg_equiv Fq[X]⁰ (ratfunc Fq) Fqt, have : ∀ c (x : F), e c • x = c • x, { intros c x, rw [algebra.smul_def, algebra.smul_def], congr, refine congr_fun _ c, refine is_localization.ext (non_zero_divisors (Fq[X])) _ _ _ _ _ _ _; intros; simp only [alg_equiv.map_one, ring_hom.map_one, alg_equiv.map_mul, ring_hom.map_mul, alg_equiv.commutes, ← is_scalar_tower.algebra_map_apply], }, split; intro h; resetI, { let b := finite_dimensional.fin_basis (ratfunc Fq) F, exact finite_dimensional.of_fintype_basis (b.map_coeffs e this) }, { let b := finite_dimensional.fin_basis Fqt F, refine finite_dimensional.of_fintype_basis (b.map_coeffs e.symm _), intros c x, convert (this (e.symm c) x).symm, simp only [e.apply_symm_apply] }, end lemma algebra_map_injective [algebra Fq[X] F] [algebra (ratfunc Fq) F] [is_scalar_tower Fq[X] (ratfunc Fq) F] : function.injective ⇑(algebra_map Fq[X] F) := begin rw is_scalar_tower.algebra_map_eq Fq[X] (ratfunc Fq) F, exact function.injective.comp ((algebra_map (ratfunc Fq) F).injective) (is_fraction_ring.injective Fq[X] (ratfunc Fq)), end namespace function_field /-- The function field analogue of `number_field.ring_of_integers`: `function_field.ring_of_integers Fq Fqt F` is the integral closure of `Fq[t]` in `F`. We don't actually assume `F` is a function field over `Fq` in the definition, only when proving its properties. -/ def ring_of_integers [algebra Fq[X] F] := integral_closure Fq[X] F namespace ring_of_integers variables [algebra Fq[X] F] instance : is_domain (ring_of_integers Fq F) := (ring_of_integers Fq F).is_domain instance : is_integral_closure (ring_of_integers Fq F) Fq[X] F := integral_closure.is_integral_closure _ _ variables [algebra (ratfunc Fq) F] [is_scalar_tower Fq[X] (ratfunc Fq) F] lemma algebra_map_injective : function.injective ⇑(algebra_map Fq[X] (ring_of_integers Fq F)) := begin have hinj : function.injective ⇑(algebra_map Fq[X] F), { rw is_scalar_tower.algebra_map_eq Fq[X] (ratfunc Fq) F, exact function.injective.comp ((algebra_map (ratfunc Fq) F).injective) (is_fraction_ring.injective Fq[X] (ratfunc Fq)), }, rw injective_iff_map_eq_zero (algebra_map Fq[X] ↥(ring_of_integers Fq F)), intros p hp, rw [← subtype.coe_inj, subalgebra.coe_zero] at hp, rw injective_iff_map_eq_zero (algebra_map Fq[X] F) at hinj, exact hinj p hp, end lemma not_is_field : ¬ is_field (ring_of_integers Fq F) := by simpa [← ((is_integral_closure.is_integral_algebra Fq[X] F).is_field_iff_is_field (algebra_map_injective Fq F))] using (polynomial.not_is_field Fq) variables [function_field Fq F] instance : is_fraction_ring (ring_of_integers Fq F) F := integral_closure.is_fraction_ring_of_finite_extension (ratfunc Fq) F instance : is_integrally_closed (ring_of_integers Fq F) := integral_closure.is_integrally_closed_of_finite_extension (ratfunc Fq) instance [is_separable (ratfunc Fq) F] : is_noetherian Fq[X] (ring_of_integers Fq F) := is_integral_closure.is_noetherian _ (ratfunc Fq) F _ instance [is_separable (ratfunc Fq) F] : is_dedekind_domain (ring_of_integers Fq F) := is_integral_closure.is_dedekind_domain Fq[X] (ratfunc Fq) F _ end ring_of_integers /-! ### The place at infinity on Fq(t) -/ section infty_valuation variable [decidable_eq (ratfunc Fq)] /-- The valuation at infinity is the nonarchimedean valuation on `Fq(t)` with uniformizer `1/t`. Explicitly, if `f/g ∈ Fq(t)` is a nonzero quotient of polynomials, its valuation at infinity is `multiplicative.of_add(degree(f) - degree(g))`. -/ def infty_valuation_def (r : ratfunc Fq) : ℤₘ₀ := if r = 0 then 0 else (multiplicative.of_add r.int_degree) lemma infty_valuation.map_zero' : infty_valuation_def Fq 0 = 0 := if_pos rfl lemma infty_valuation.map_one' : infty_valuation_def Fq 1 = 1 := (if_neg one_ne_zero).trans $ by rw [ratfunc.int_degree_one, of_add_zero, with_zero.coe_one] lemma infty_valuation.map_mul' (x y : ratfunc Fq) : infty_valuation_def Fq (x * y) = infty_valuation_def Fq x * infty_valuation_def Fq y := begin rw [infty_valuation_def, infty_valuation_def, infty_valuation_def], by_cases hx : x = 0, { rw [hx, zero_mul, if_pos (eq.refl _), zero_mul] }, { by_cases hy : y = 0, { rw [hy, mul_zero, if_pos (eq.refl _), mul_zero] }, { rw [if_neg hx, if_neg hy, if_neg (mul_ne_zero hx hy), ← with_zero.coe_mul, with_zero.coe_inj, ← of_add_add, ratfunc.int_degree_mul hx hy], }} end lemma infty_valuation.map_add_le_max' (x y : ratfunc Fq) : infty_valuation_def Fq (x + y) ≤ max (infty_valuation_def Fq x) (infty_valuation_def Fq y) := begin by_cases hx : x = 0, { rw [hx, zero_add], conv_rhs { rw [infty_valuation_def, if_pos (eq.refl _)] }, rw max_eq_right (with_zero.zero_le (infty_valuation_def Fq y)), exact le_refl _ }, { by_cases hy : y = 0, { rw [hy, add_zero], conv_rhs { rw [max_comm, infty_valuation_def, if_pos (eq.refl _)] }, rw max_eq_right (with_zero.zero_le (infty_valuation_def Fq x)), exact le_refl _ }, { by_cases hxy : x + y = 0, { rw [infty_valuation_def, if_pos hxy], exact zero_le',}, { rw [infty_valuation_def, infty_valuation_def, infty_valuation_def, if_neg hx, if_neg hy, if_neg hxy], rw [le_max_iff, with_zero.coe_le_coe, multiplicative.of_add_le, with_zero.coe_le_coe, multiplicative.of_add_le, ← le_max_iff], exact ratfunc.int_degree_add_le hy hxy }}} end @[simp] lemma infty_valuation_of_nonzero {x : ratfunc Fq} (hx : x ≠ 0) : infty_valuation_def Fq x = (multiplicative.of_add x.int_degree) := by rw [infty_valuation_def, if_neg hx] /-- The valuation at infinity on `Fq(t)`. -/ def infty_valuation : valuation (ratfunc Fq) ℤₘ₀ := { to_fun := infty_valuation_def Fq, map_zero' := infty_valuation.map_zero' Fq, map_one' := infty_valuation.map_one' Fq, map_mul' := infty_valuation.map_mul' Fq, map_add_le_max' := infty_valuation.map_add_le_max' Fq } @[simp] lemma infty_valuation_apply {x : ratfunc Fq} : infty_valuation Fq x = infty_valuation_def Fq x := rfl @[simp] lemma infty_valuation.C {k : Fq} (hk : k ≠ 0) : infty_valuation_def Fq (ratfunc.C k) = (multiplicative.of_add (0 : ℤ)) := begin have hCk : ratfunc.C k ≠ 0 := (ring_hom.map_ne_zero _).mpr hk, rw [infty_valuation_def, if_neg hCk, ratfunc.int_degree_C], end @[simp] lemma infty_valuation.X : infty_valuation_def Fq (ratfunc.X) = (multiplicative.of_add (1 : ℤ)) := by rw [infty_valuation_def, if_neg ratfunc.X_ne_zero, ratfunc.int_degree_X] @[simp] lemma infty_valuation.polynomial {p : polynomial Fq} (hp : p ≠ 0) : infty_valuation_def Fq (algebra_map (polynomial Fq) (ratfunc Fq) p) = (multiplicative.of_add (p.nat_degree : ℤ)) := begin have hp' : algebra_map (polynomial Fq) (ratfunc Fq) p ≠ 0, { rw [ne.def, ratfunc.algebra_map_eq_zero_iff], exact hp }, rw [infty_valuation_def, if_neg hp', ratfunc.int_degree_polynomial] end /-- The valued field `Fq(t)` with the valuation at infinity. -/ def infty_valued_Fqt : valued (ratfunc Fq) ℤₘ₀ := valued.mk' $ infty_valuation Fq lemma infty_valued_Fqt.def {x : ratfunc Fq} : @valued.v (ratfunc Fq) _ _ _ (infty_valued_Fqt Fq) x = infty_valuation_def Fq x := rfl /-- The completion `Fq((t⁻¹))` of `Fq(t)` with respect to the valuation at infinity. -/ def Fqt_infty := @uniform_space.completion (ratfunc Fq) $ (infty_valued_Fqt Fq).to_uniform_space instance : field (Fqt_infty Fq) := by { letI := infty_valued_Fqt Fq, exact uniform_space.completion.field } instance : inhabited (Fqt_infty Fq) := ⟨(0 : Fqt_infty Fq)⟩ /-- The valuation at infinity on `k(t)` extends to a valuation on `Fqt_infty`. -/ instance valued_Fqt_infty : valued (Fqt_infty Fq) ℤₘ₀ := @valued.valued_completion _ _ _ _ (infty_valued_Fqt Fq) lemma valued_Fqt_infty.def {x : Fqt_infty Fq} : valued.v x = @valued.extension (ratfunc Fq) _ _ _ (infty_valued_Fqt Fq) x := rfl end infty_valuation end function_field
cd480e3d250cbd1f721d515aa6eaffe86c36d61e
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/2344.lean
20cd775ed2d66dbc2004cb505dab4f1b0a640dc7
[ "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
444
lean
namespace Value inductive Primitive where | Bool (b : Bool) | Int (i : Int) | String (s : String) deriving instance DecidableEq for Primitive -- Works inductive Value where | Primitive (p : Primitive) deriving instance DecidableEq for Primitive -- (no longer) fails deriving instance DecidableEq for _root_.Value.Primitive -- (no longer) fails deriving instance Repr for Primitive deriving instance Repr for _root_.Value.Primitive
63ff739fd815c5b745174954410131246bc7dc0f
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/set/basic.lean
050dbb4a0a079ad054b3cbf8937450c1d3b2b2c6
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
112,284
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 order.boolean_algebra /-! # 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 coercion 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: * `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`) * `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` * `sᶜ` for the complement of `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. * For `s : set α`, do not use `subtype s`. Instead use `↥s` or `(s : Type*)` or `s`. ## Tags set, sets, subset, subsets, image, preimage, pre-image, range, union, intersection, insert, singleton, complement, powerset -/ /-! ### Set coercion to a type -/ open function universes u v w x namespace set variable {α : Type*} instance : has_le (set α) := ⟨λ s t, ∀ ⦃x⦄, x ∈ s → x ∈ t⟩ instance : has_subset (set α) := ⟨(≤)⟩ instance {α : Type*} : boolean_algebra (set α) := { sup := λ s t, {x | x ∈ s ∨ x ∈ t}, le := (≤), lt := λ s t, s ⊆ t ∧ ¬t ⊆ s, inf := λ s t, {x | x ∈ s ∧ x ∈ t}, bot := ∅, compl := λ s, {x | x ∉ s}, top := univ, sdiff := λ s t, {x | x ∈ s ∧ x ∉ t}, .. (infer_instance : boolean_algebra (α → Prop)) } instance : has_ssubset (set α) := ⟨(<)⟩ instance : has_union (set α) := ⟨(⊔)⟩ instance : has_inter (set α) := ⟨(⊓)⟩ @[simp] lemma top_eq_univ : (⊤ : set α) = univ := rfl @[simp] lemma bot_eq_empty : (⊥ : set α) = ∅ := rfl @[simp] lemma sup_eq_union : ((⊔) : set α → set α → set α) = (∪) := rfl @[simp] lemma inf_eq_inter : ((⊓) : set α → set α → set α) = (∩) := rfl @[simp] lemma le_eq_subset : ((≤) : set α → set α → Prop) = (⊆) := rfl @[simp] lemma lt_eq_ssubset : ((<) : set α → set α → Prop) = (⊂) := rfl /-- Coercion from a set to the corresponding subtype. -/ instance {α : Type u} : has_coe_to_sort (set α) (Type u) := ⟨λ s, {x // x ∈ s}⟩ instance pi_set_coe.can_lift (ι : Type u) (α : Π i : ι, Type v) [ne : Π i, nonempty (α i)] (s : set ι) : can_lift (Π i : s, α i) (Π i, α i) := { coe := λ f i, f i, .. pi_subtype.can_lift ι α s } instance pi_set_coe.can_lift' (ι : Type u) (α : Type v) [ne : nonempty α] (s : set ι) : can_lift (s → α) (ι → α) := pi_set_coe.can_lift ι (λ _, α) s end set section set_coe variables {α : Type u} theorem set.coe_eq_subtype (s : set α) : ↥s = {x // x ∈ s} := rfl @[simp] theorem set.coe_set_of (p : α → Prop) : ↥{x | p x} = {x // p x} := 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 x.2) := (@set_coe.exists _ _ $ λ x, p x.1 x.2).symm theorem set_coe.forall' {s : set α} {p : Π x, x ∈ s → Prop} : (∀ x (h : x ∈ s), p x h) ↔ (∀ x : s, p x x.2) := (@set_coe.forall _ _ $ λ x, p x.1 x.2).symm @[simp] theorem set_coe_cast : ∀ {s t : set α} (H' : s = t) (H : ↥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 /-- See also `subtype.prop` -/ lemma subtype.mem {α : Type*} {s : set α} (p : s) : (p : α) ∈ s := p.prop /-- Duplicate of `eq.subset'`, which currently has elaboration problems. -/ lemma eq.subset {α} {s t : set α} : s = t → s ⊆ t := by { rintro rfl x hx, exact hx } namespace set variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {a b : α} {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 lemma forall_in_swap {p : α → β → Prop} : (∀ (a ∈ s) b, p a b) ↔ ∀ b (a ∈ s), p a b := by tauto /-! ### Lemmas about `mem` and `set_of` -/ lemma mem_set_of {a : α} {p : α → Prop} : a ∈ {x | p x} ↔ p a := iff.rfl /-- If `h : a ∈ {x | p x}` then `h.out : p x`. These are definitionally equal, but this can nevertheless be useful for various reasons, e.g. to apply further projection notation or in an argument to `simp`. -/ lemma _root_.has_mem.mem.out {p : α → Prop} {a : α} (h : a ∈ {x | p x}) : p a := h theorem nmem_set_of_eq {a : α} {p : α → Prop} : a ∉ {x | p x} = ¬ p a := rfl @[simp] theorem set_of_mem_eq {s : set α} : {x | x ∈ s} = s := rfl theorem set_of_set {s : set α} : set_of 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 lemma set_of_bijective : bijective (set_of : (α → Prop) → set α) := bijective_id @[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 lemma set_of_and {p q : α → Prop} : {a | p a ∧ q a} = {a | p a} ∩ {a | q a} := rfl lemma set_of_or {p q : α → Prop} : {a | p a ∨ q a} = {a | p a} ∪ {a | q a} := rfl /-! ### Subset and strict subset relations -/ instance : is_refl (set α) (⊆) := has_le.le.is_refl instance : is_trans (set α) (⊆) := has_le.le.is_trans instance : is_antisymm (set α) (⊆) := has_le.le.is_antisymm instance : is_irrefl (set α) (⊂) := has_lt.lt.is_irrefl instance : is_trans (set α) (⊂) := has_lt.lt.is_trans instance : is_asymm (set α) (⊂) := has_lt.lt.is_asymm instance : is_nonstrict_strict_order (set α) (⊆) (⊂) := ⟨λ _ _, iff.rfl⟩ -- TODO(Jeremy): write a tactic to unfold specific instances of generic notation? lemma subset_def : (s ⊆ t) = ∀ x, x ∈ s → x ∈ t := rfl lemma ssubset_def : s ⊂ t = (s ⊆ t ∧ ¬ t ⊆ s) := rfl @[refl] theorem subset.refl (a : set α) : a ⊆ a := assume x, id theorem subset.rfl {s : set α} : s ⊆ s := subset.refl s @[trans] theorem subset.trans {a b c : set α} (ab : a ⊆ b) (bc : b ⊆ c) : a ⊆ c := λ 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 := set.ext $ λ x, ⟨@h₁ _, @h₂ _⟩ theorem subset.antisymm_iff {a b : set α} : a = b ↔ a ⊆ b ∧ b ⊆ a := ⟨λ e, ⟨e.subset, e.symm.subset⟩, λ ⟨h₁, h₂⟩, subset.antisymm h₁ h₂⟩ -- an alternative name theorem eq_of_subset_of_subset {a b : set α} : a ⊆ b → b ⊆ a → a = b := subset.antisymm theorem mem_of_subset_of_mem {s₁ s₂ : set α} {a : α} (h : s₁ ⊆ s₂) : a ∈ s₁ → a ∈ s₂ := @h _ theorem not_mem_subset (h : s ⊆ t) : a ∉ t → a ∉ s := mt $ mem_of_subset_of_mem h theorem not_subset : (¬ s ⊆ t) ↔ ∃a ∈ s, a ∉ t := by simp only [subset_def, not_forall] theorem nontrivial_mono {α : Type*} {s t : set α} (h₁ : s ⊆ t) (h₂ : nontrivial s) : nontrivial t := begin rw nontrivial_iff at h₂ ⊢, obtain ⟨⟨x, hx⟩, ⟨y, hy⟩, hxy⟩ := h₂, exact ⟨⟨x, h₁ hx⟩, ⟨y, h₁ hy⟩, by simpa using hxy⟩, end /-! ### Definition of strict subsets `s ⊂ t` and basic properties. -/ protected theorem eq_or_ssubset_of_subset (h : s ⊆ t) : s = t ∨ s ⊂ t := eq_or_lt_of_le h lemma exists_of_ssubset {s t : set α} (h : s ⊂ t) : (∃x∈t, x ∉ s) := not_subset.1 h.2 protected lemma ssubset_iff_subset_ne {s t : set α} : s ⊂ t ↔ s ⊆ t ∧ s ≠ t := @lt_iff_le_and_ne (set α) _ s t lemma ssubset_iff_of_subset {s t : set α} (h : s ⊆ t) : s ⊂ t ↔ ∃ x ∈ t, x ∉ s := ⟨exists_of_ssubset, λ ⟨x, hxt, hxs⟩, ⟨h, λ h, hxs $ h hxt⟩⟩ protected lemma ssubset_of_ssubset_of_subset {s₁ s₂ s₃ : set α} (hs₁s₂ : s₁ ⊂ s₂) (hs₂s₃ : s₂ ⊆ s₃) : s₁ ⊂ s₃ := ⟨subset.trans hs₁s₂.1 hs₂s₃, λ hs₃s₁, hs₁s₂.2 (subset.trans hs₂s₃ hs₃s₁)⟩ protected lemma ssubset_of_subset_of_ssubset {s₁ s₂ s₃ : set α} (hs₁s₂ : s₁ ⊆ s₂) (hs₂s₃ : s₂ ⊂ s₃) : s₁ ⊂ s₃ := ⟨subset.trans hs₁s₂ hs₂s₃.1, λ hs₃s₁, hs₂s₃.2 (subset.trans hs₃s₁ hs₁s₂)⟩ theorem not_mem_empty (x : α) : ¬ (x ∈ (∅ : set α)) := id @[simp] theorem not_not_mem : ¬ (a ∉ s) ↔ a ∈ s := 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 @[simp] lemma nonempty_coe_sort {s : set α} : nonempty ↥s ↔ s.nonempty := nonempty_subtype lemma nonempty_def : s.nonempty ↔ ∃ x, x ∈ s := iff.rfl 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 : set α}, s.nonempty → s ≠ ∅ | _ ⟨x, hx⟩ rfl := hx @[simp] theorem not_nonempty_empty : ¬(∅ : set α).nonempty := λ h, h.ne_empty rfl /-- 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_not_subset (h : ¬s ⊆ t) : (s \ t).nonempty := let ⟨x, xs, xt⟩ := not_subset.1 h in ⟨x, xs, xt⟩ lemma nonempty_of_ssubset (ht : s ⊂ t) : (t \ s).nonempty := nonempty_of_not_subset ht.2 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_inter_iff_exists_right : (s ∩ t).nonempty ↔ ∃ x : t, ↑x ∈ s := ⟨λ ⟨x, xs, xt⟩, ⟨⟨x, xt⟩, xs⟩, λ ⟨⟨x, xt⟩, xs⟩, ⟨x, xs, xt⟩⟩ lemma nonempty_inter_iff_exists_left : (s ∩ t).nonempty ↔ ∃ x : s, ↑x ∈ t := ⟨λ ⟨x, xs, xt⟩, ⟨⟨x, xs⟩, xt⟩, λ ⟨⟨x, xt⟩, xs⟩, ⟨x, xt, xs⟩⟩ 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 instance [nonempty α] : nonempty (set.univ : set α) := set.univ_nonempty.to_subtype lemma nonempty_of_nonempty_subtype [nonempty s] : s.nonempty := nonempty_subtype.mp ‹_› /-! ### 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 @[simp] theorem empty_subset (s : set α) : ∅ ⊆ s. theorem subset_empty_iff {s : set α} : s ⊆ ∅ ↔ s = ∅ := (subset.antisymm_iff.trans $ and_iff_left (empty_subset _)).symm theorem eq_empty_iff_forall_not_mem {s : set α} : s = ∅ ↔ ∀ x, x ∉ s := subset_empty_iff.symm lemma eq_empty_of_forall_not_mem (h : ∀ x, x ∉ s) : s = ∅ := subset_empty_iff.1 h theorem eq_empty_of_subset_empty {s : set α} : s ⊆ ∅ → s = ∅ := subset_empty_iff.1 theorem eq_empty_of_is_empty [is_empty α] (s : set α) : s = ∅ := eq_empty_of_subset_empty $ λ x hx, is_empty_elim x /-- There is exactly one set of a type that is empty. -/ instance unique_empty [is_empty α] : unique (set α) := { default := ∅, uniq := eq_empty_of_is_empty } 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 := λ h, h.ne_empty rfl theorem ne_empty_iff_nonempty : s ≠ ∅ ↔ s.nonempty := not_iff_comm.1 not_nonempty_iff_eq_empty @[simp] lemma is_empty_coe_sort {s : set α} : is_empty ↥s ↔ s = ∅ := not_iff_not.1 $ by simpa using ne_empty_iff_nonempty.symm lemma eq_empty_or_nonempty (s : set α) : s = ∅ ∨ s.nonempty := or_iff_not_imp_left.2 ne_empty_iff_nonempty.1 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 := iff_true_intro $ λ x, false.elim instance (α : Type u) : is_empty.{u+1} (∅ : set α) := ⟨λ x, x.2⟩ @[simp] lemma empty_ssubset : ∅ ⊂ s ↔ s.nonempty := (@bot_lt_iff_ne_bot (set α) _ _ _).trans ne_empty_iff_nonempty /-! ### 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. -/ @[simp] theorem set_of_true : {x : α | true} = univ := rfl @[simp] theorem mem_univ (x : α) : x ∈ @univ α := trivial @[simp] lemma univ_eq_empty_iff : (univ : set α) = ∅ ↔ is_empty α := eq_empty_iff_forall_not_mem.trans ⟨λ H, ⟨λ x, H x trivial⟩, λ H x _, @is_empty.false α H x⟩ theorem empty_ne_univ [nonempty α] : (∅ : set α) ≠ univ := λ e, not_is_empty_of_nonempty α $ univ_eq_empty_iff.1 e.symm @[simp] theorem subset_univ (s : set α) : s ⊆ univ := λ x H, trivial theorem univ_subset_iff {s : set α} : univ ⊆ s ↔ s = univ := (subset.antisymm_iff.trans $ and_iff_right (subset_univ _)).symm 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 := univ_subset_iff.symm.trans $ forall_congr $ λ x, imp_iff_right ⟨⟩ theorem eq_univ_of_forall {s : set α} : (∀ x, x ∈ s) → s = univ := eq_univ_iff_forall.2 lemma eq_univ_of_subset {s t : set α} (h : s ⊆ t) (hs : s = univ) : t = univ := eq_univ_of_univ_subset $ hs ▸ h lemma exists_mem_of_nonempty (α) : ∀ [nonempty α], ∃x:α, x ∈ (univ : set α) | ⟨x⟩ := ⟨x, trivial⟩ lemma ne_univ_iff_exists_not_mem {α : Type*} (s : set α) : s ≠ univ ↔ ∃ a, a ∉ s := by rw [←not_forall, ←eq_univ_iff_forall] lemma not_subset_iff_exists_mem_not_mem {α : Type*} {s t : set α} : ¬ s ⊆ t ↔ ∃ x, x ∈ s ∧ x ∉ t := by simp [subset_def] lemma univ_unique [unique α] : @set.univ α = {default} := set.ext $ λ x, iff_of_true trivial $ subsingleton.elim x default /-! ### 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 $ λ x, or_self _ @[simp] theorem union_empty (a : set α) : a ∪ ∅ = a := ext $ λ x, or_false _ @[simp] theorem empty_union (a : set α) : ∅ ∪ a = a := ext $ λ x, false_or _ theorem union_comm (a b : set α) : a ∪ b = b ∪ a := ext $ λ x, or.comm theorem union_assoc (a b c : set α) : (a ∪ b) ∪ c = a ∪ (b ∪ c) := ext $ λ 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₃) := ext $ λ x, or.left_comm theorem union_right_comm (s₁ s₂ s₃ : set α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := ext $ λ x, or.right_comm @[simp] theorem union_eq_left_iff_subset {s t : set α} : s ∪ t = s ↔ t ⊆ s := sup_eq_left @[simp] theorem union_eq_right_iff_subset {s t : set α} : s ∪ t = t ↔ s ⊆ t := sup_eq_right theorem union_eq_self_of_subset_left {s t : set α} (h : s ⊆ t) : s ∪ t = t := union_eq_right_iff_subset.mpr h theorem union_eq_self_of_subset_right {s t : set α} (h : t ⊆ s) : s ∪ t = s := union_eq_left_iff_subset.mpr h @[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 := λ x, or.rec (@sr _) (@tr _) @[simp] theorem union_subset_iff {s t u : set α} : s ∪ t ⊆ u ↔ s ⊆ u ∧ t ⊆ u := (forall_congr (by exact λ x, or_imp_distrib)).trans forall_and_distrib theorem union_subset_union {s₁ s₂ t₁ t₂ : set α} (h₁ : s₁ ⊆ s₂) (h₂ : t₁ ⊆ t₂) : s₁ ∪ t₁ ⊆ s₂ ∪ t₂ := λ x, or.imp (@h₁ _) (@h₂ _) theorem union_subset_union_left {s₁ s₂ : set α} (t) (h : s₁ ⊆ s₂) : s₁ ∪ t ⊆ s₂ ∪ t := union_subset_union h subset.rfl theorem union_subset_union_right (s) {t₁ t₂ : set α} (h : t₁ ⊆ t₂) : s ∪ t₁ ⊆ s ∪ t₂ := union_subset_union subset.rfl 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) lemma union_eq_union_of_subset_of_subset {s t a : set α} (h1 : s ⊆ t ∪ a) (h2 : t ⊆ s ∪ a) : s ∪ a = t ∪ a := sup_eq_sup_of_le_of_le h1 h2 lemma union_eq_union_iff_subset_subset {s t a : set α} : s ∪ a = t ∪ a ↔ s ⊆ t ∪ a ∧ t ⊆ s ∪ a := sup_eq_sup_iff_le_le @[simp] theorem union_empty_iff {s t : set α} : s ∪ t = ∅ ↔ s = ∅ ∧ t = ∅ := by simp only [← subset_empty_iff]; exact union_subset_iff @[simp] lemma union_univ {s : set α} : s ∪ univ = univ := sup_top_eq @[simp] lemma univ_union {s : set α} : univ ∪ s = univ := top_sup_eq /-! ### 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 $ λ x, and_self _ @[simp] theorem inter_empty (a : set α) : a ∩ ∅ = ∅ := ext $ λ x, and_false _ @[simp] theorem empty_inter (a : set α) : ∅ ∩ a = ∅ := ext $ λ x, false_and _ theorem inter_comm (a b : set α) : a ∩ b = b ∩ a := ext $ λ x, and.comm theorem inter_assoc (a b c : set α) : (a ∩ b) ∩ c = a ∩ (b ∩ c) := ext $ λ 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₃) := ext $ λ x, and.left_comm theorem inter_right_comm (s₁ s₂ s₃ : set α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := ext $ λ x, and.right_comm @[simp] theorem inter_subset_left (s t : set α) : s ∩ t ⊆ s := λ x, and.left @[simp] theorem inter_subset_right (s t : set α) : s ∩ t ⊆ t := λ x, and.right theorem subset_inter {s t r : set α} (rs : r ⊆ s) (rt : r ⊆ t) : r ⊆ s ∩ t := λ x h, ⟨rs h, rt h⟩ @[simp] theorem subset_inter_iff {s t r : set α} : r ⊆ s ∩ t ↔ r ⊆ s ∧ r ⊆ t := (forall_congr (by exact λ x, imp_and_distrib)).trans forall_and_distrib @[simp] theorem inter_eq_left_iff_subset {s t : set α} : s ∩ t = s ↔ s ⊆ t := inf_eq_left @[simp] theorem inter_eq_right_iff_subset {s t : set α} : s ∩ t = t ↔ t ⊆ s := inf_eq_right theorem inter_eq_self_of_subset_left {s t : set α} : s ⊆ t → s ∩ t = s := inter_eq_left_iff_subset.mpr theorem inter_eq_self_of_subset_right {s t : set α} : t ⊆ s → s ∩ t = t := inter_eq_right_iff_subset.mpr lemma inter_eq_inter_of_subset_of_subset {s t a : set α} (h1 : t ∩ a ⊆ s) (h2 : s ∩ a ⊆ t) : s ∩ a = t ∩ a := inf_eq_inf_of_le_of_le h1 h2 lemma inter_eq_inter_iff_subset_subset {s t a : set α} : s ∩ a = t ∩ a ↔ t ∩ a ⊆ s ∧ s ∩ a ⊆ t := inf_eq_inf_iff_le_le @[simp] theorem inter_univ (a : set α) : a ∩ univ = a := inf_top_eq @[simp] theorem univ_inter (a : set α) : univ ∩ a = a := top_inf_eq theorem inter_subset_inter {s₁ s₂ t₁ t₂ : set α} (h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) : s₁ ∩ s₂ ⊆ t₁ ∩ t₂ := λ x, and.imp (@h₁ _) (@h₂ _) theorem inter_subset_inter_left {s t : set α} (u : set α) (H : s ⊆ t) : s ∩ u ⊆ t ∩ u := inter_subset_inter H subset.rfl theorem inter_subset_inter_right {s t : set α} (u : set α) (H : s ⊆ t) : u ∩ s ⊆ u ∩ t := inter_subset_inter subset.rfl H theorem union_inter_cancel_left {s t : set α} : (s ∪ t) ∩ s = s := inter_eq_self_of_subset_right $ subset_union_left _ _ theorem union_inter_cancel_right {s t : set α} : (s ∪ t) ∩ t = t := inter_eq_self_of_subset_right $ subset_union_right _ _ /-! ### Distributivity laws -/ theorem inter_distrib_left (s t u : set α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := inf_sup_left theorem inter_union_distrib_left {s t u : set α} : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := inf_sup_left theorem inter_distrib_right (s t u : set α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := inf_sup_right theorem union_inter_distrib_right {s t u : set α} : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := inf_sup_right theorem union_distrib_left (s t u : set α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := sup_inf_left theorem union_inter_distrib_left {s t u : set α} : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := sup_inf_left theorem union_distrib_right (s t u : set α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := sup_inf_right theorem inter_union_distrib_right {s t u : set α} : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := sup_inf_right lemma union_union_distrib_left (s t u : set α) : s ∪ (t ∪ u) = (s ∪ t) ∪ (s ∪ u) := sup_sup_distrib_left _ _ _ lemma union_union_distrib_right (s t u : set α) : (s ∪ t) ∪ u = (s ∪ u) ∪ (t ∪ u) := sup_sup_distrib_right _ _ _ lemma inter_inter_distrib_left (s t u : set α) : s ∩ (t ∩ u) = (s ∩ t) ∩ (s ∩ u) := inf_inf_distrib_left _ _ _ lemma inter_inter_distrib_right (s t u : set α) : (s ∩ t) ∩ u = (s ∩ u) ∩ (t ∩ u) := inf_inf_distrib_right _ _ _ lemma union_union_union_comm (s t u v : set α) : (s ∪ t) ∪ (u ∪ v) = (s ∪ u) ∪ (t ∪ v) := sup_sup_sup_comm _ _ _ _ lemma inter_inter_inter_comm (s t u v : set α) : (s ∩ t) ∩ (u ∩ v) = (s ∩ u) ∩ (t ∩ v) := inf_inf_inf_comm _ _ _ _ /-! ### 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 := λ y, or.inr 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 lemma mem_of_mem_insert_of_ne : b ∈ insert a s → b ≠ a → b ∈ s := or.resolve_left lemma eq_of_not_mem_of_mem_insert : b ∈ insert a s → b ∉ s → b = a := or.resolve_right @[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 := ext $ λ x, or_iff_right_of_imp $ λ e, e.symm ▸ h lemma ne_insert_of_not_mem {s : set α} (t : set α) {a : α} : a ∉ s → s ≠ insert a t := mt $ λ e, e.symm ▸ mem_insert _ _ theorem insert_subset : insert a s ⊆ t ↔ (a ∈ t ∧ s ⊆ t) := by simp only [subset_def, or_imp_distrib, forall_and_distrib, forall_eq, mem_insert_iff] theorem insert_subset_insert (h : s ⊆ t) : insert a s ⊆ insert a t := λ x, or.imp_right (@h _) theorem insert_subset_insert_iff (ha : a ∉ s) : insert a s ⊆ insert a t ↔ s ⊆ t := begin refine ⟨λ h x hx, _, insert_subset_insert⟩, rcases h (subset_insert _ _ hx) with (rfl|hxt), exacts [(ha hx).elim, hxt] end theorem ssubset_iff_insert {s t : set α} : s ⊂ t ↔ ∃ a ∉ s, insert a s ⊆ t := begin simp only [insert_subset, exists_and_distrib_right, ssubset_def, not_subset], simp only [exists_prop, and_comm] end theorem ssubset_insert {s : set α} {a : α} (h : a ∉ s) : s ⊂ insert a s := ssubset_iff_insert.2 ⟨a, h, subset.rfl⟩ theorem insert_comm (a b : α) (s : set α) : insert a (insert b s) = insert b (insert a s) := ext $ λ x, or.left_comm @[simp] lemma insert_idem (a : α) (s : set α) : insert a (insert a s) = insert a s := insert_eq_of_mem $ mem_insert _ _ theorem insert_union : insert a s ∪ t = insert a (s ∪ t) := ext $ λ x, or.assoc @[simp] theorem union_insert : s ∪ insert a t = insert a (s ∪ t) := ext $ λ x, or.left_comm @[simp] theorem insert_nonempty (a : α) (s : set α) : (insert a s).nonempty := ⟨a, mem_insert a s⟩ instance (a : α) (s : set α) : nonempty (insert a s : set α) := (insert_nonempty a s).to_subtype lemma insert_inter_distrib (a : α) (s t : set α) : insert a (s ∩ t) = insert a s ∩ insert a t := ext $ λ y, or_and_distrib_left lemma insert_union_distrib (a : α) (s t : set α) : insert a (s ∪ t) = insert a s ∪ insert a t := ext $ λ _, or_or_distrib_left _ _ _ lemma insert_inj (ha : a ∉ s) : insert a s = insert b s ↔ a = b := ⟨λ h, eq_of_not_mem_of_mem_insert (h.subst $ mem_insert a s) ha, congr_arg _⟩ -- useful in proofs by induction theorem forall_of_forall_insert {P : α → Prop} {a : α} {s : set α} (H : ∀ x, x ∈ insert a s → P x) (x) (h : x ∈ s) : P x := H _ (or.inr h) theorem forall_insert_of_forall {P : α → Prop} {a : α} {s : set α} (H : ∀ x, x ∈ s → P x) (ha : P a) (x) (h : x ∈ insert a s) : P x := h.elim (λ e, e.symm ▸ ha) (H _) theorem bex_insert_iff {P : α → Prop} {a : α} {s : set α} : (∃ x ∈ insert a s, P x) ↔ P a ∨ (∃ x ∈ s, P x) := bex_or_left_distrib.trans $ or_congr_left' bex_eq_left theorem ball_insert_iff {P : α → Prop} {a : α} {s : set α} : (∀ x ∈ insert a s, P x) ↔ P a ∧ (∀x ∈ s, P x) := ball_or_left_distrib.trans $ and_congr_left' forall_eq /-! ### 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} := rfl @[simp] lemma set_of_eq_eq_singleton' {a : α} : {x | a = x} = {a} := ext $ λ x, eq_comm -- TODO: again, annotation needed @[simp] theorem mem_singleton (a : α) : a ∈ ({a} : set α) := @rfl _ _ theorem eq_of_mem_singleton {x y : α} (h : x ∈ ({y} : set α)) : x = y := h @[simp] theorem singleton_eq_singleton_iff {x y : α} : {x} = ({y} : set α) ↔ x = y := ext_iff.trans eq_iff_eq_cancel_left lemma singleton_injective : injective (singleton : α → set α) := λ _ _, singleton_eq_singleton_iff.mp theorem mem_singleton_of_eq {x y : α} (H : x = y) : x ∈ ({y} : set α) := H theorem insert_eq (x : α) (s : set α) : insert x s = ({x} : set α) ∪ s := rfl @[simp] theorem pair_eq_singleton (a : α) : ({a, a} : set α) = {a} := union_self _ theorem pair_comm (a b : α) : ({a, b} : set α) = {b, a} := union_comm _ _ @[simp] theorem singleton_nonempty (a : α) : ({a} : set α).nonempty := ⟨a, rfl⟩ @[simp] theorem singleton_subset_iff {a : α} {s : set α} : {a} ⊆ s ↔ a ∈ s := forall_eq theorem set_compr_eq_eq_singleton {a : α} : {b | b = a} = {a} := rfl @[simp] theorem singleton_union : {a} ∪ s = insert a s := rfl @[simp] theorem union_singleton : s ∪ {a} = insert a s := union_comm _ _ @[simp] theorem singleton_inter_nonempty : ({a} ∩ s).nonempty ↔ a ∈ s := by simp only [set.nonempty, mem_inter_eq, mem_singleton_iff, exists_eq_left] @[simp] theorem inter_singleton_nonempty : (s ∩ {a}).nonempty ↔ a ∈ s := by rw [inter_comm, singleton_inter_nonempty] @[simp] theorem singleton_inter_eq_empty : {a} ∩ s = ∅ ↔ a ∉ s := not_nonempty_iff_eq_empty.symm.trans singleton_inter_nonempty.not @[simp] 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 := ne_empty_iff_nonempty instance unique_singleton (a : α) : unique ↥({a} : set α) := ⟨⟨⟨a, mem_singleton a⟩⟩, λ ⟨x, h⟩, subtype.eq h⟩ lemma eq_singleton_iff_unique_mem : s = {a} ↔ a ∈ s ∧ ∀ x ∈ s, x = a := subset.antisymm_iff.trans $ and.comm.trans $ and_congr_left' singleton_subset_iff lemma eq_singleton_iff_nonempty_unique_mem : s = {a} ↔ s.nonempty ∧ ∀ x ∈ s, x = a := eq_singleton_iff_unique_mem.trans $ and_congr_left $ λ H, ⟨λ h', ⟨_, h'⟩, λ ⟨x, h⟩, H x h ▸ h⟩ -- while `simp` is capable of proving this, it is not capable of turning the LHS into the RHS. @[simp] lemma default_coe_singleton (x : α) : (default : ({x} : set α)) = ⟨x, rfl⟩ := rfl /-! ### 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 sep_mem_eq {s t : set α} : {x ∈ s | x ∈ t} = s ∩ t := rfl @[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 α} (h : s ⊆ t) : s = {x ∈ t | x ∈ s} := (inter_eq_self_of_subset_right h).symm @[simp] theorem sep_subset (s : set α) (p : α → Prop) : {x ∈ s | p x} ⊆ s := λ x, and.left @[simp] lemma sep_empty (p : α → Prop) : {x ∈ (∅ : set α) | p x} = ∅ := by { ext, exact false_and _ } theorem forall_not_of_sep_empty {s : set α} {p : α → Prop} (H : {x ∈ s | p x} = ∅) (x) : x ∈ s → ¬ p x := not_and.1 (eq_empty_iff_forall_not_mem.1 H x : _) @[simp] lemma sep_univ {α} {p : α → Prop} : {a ∈ (univ : set α) | p a} = {a | p a} := univ_inter _ @[simp] lemma sep_true : {a ∈ s | true} = s := by { ext, simp } @[simp] lemma sep_false : {a ∈ s | false} = ∅ := by { ext, simp } lemma sep_inter_sep {p q : α → Prop} : {x ∈ s | p x} ∩ {x ∈ s | q x} = {x ∈ s | p x ∧ q x} := begin ext, simp_rw [mem_inter_iff, mem_sep_iff], rw [and_and_and_comm, and_self], end @[simp] lemma subset_singleton_iff {α : Type*} {s : set α} {x : α} : s ⊆ {x} ↔ ∀ y ∈ s, y = x := iff.rfl lemma subset_singleton_iff_eq {s : set α} {x : α} : s ⊆ {x} ↔ s = ∅ ∨ s = {x} := begin obtain (rfl | hs) := s.eq_empty_or_nonempty, use ⟨λ _, or.inl rfl, λ _, empty_subset _⟩, simp [eq_singleton_iff_nonempty_unique_mem, hs, ne_empty_iff_nonempty.2 hs], end lemma nonempty.subset_singleton_iff (h : s.nonempty) : s ⊆ {a} ↔ s = {a} := subset_singleton_iff_eq.trans $ or_iff_right h.ne_empty lemma ssubset_singleton_iff {s : set α} {x : α} : s ⊂ {x} ↔ s = ∅ := begin rw [ssubset_iff_subset_ne, subset_singleton_iff_eq, or_and_distrib_right, and_not_self, or_false, and_iff_left_iff_imp], rintro rfl, refine ne_comm.1 (ne_empty_iff_nonempty.2 (singleton_nonempty _)), end lemma eq_empty_of_ssubset_singleton {s : set α} {x : α} (hs : s ⊂ {x}) : s = ∅ := ssubset_singleton_iff.1 hs /-! ### Disjointness -/ lemma _root_.disjoint.inter_eq : disjoint s t → s ∩ t = ∅ := disjoint.eq_bot lemma disjoint_left : disjoint s t ↔ ∀ ⦃a⦄, a ∈ s → a ∉ t := forall_congr $ λ _, not_and lemma disjoint_right : disjoint s t ↔ ∀ ⦃a⦄, a ∈ t → a ∉ s := by rw [disjoint.comm, disjoint_left] /-! ### Lemmas about complement -/ lemma compl_def (s : set α) : sᶜ = {x | x ∉ s} := rfl 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 lemma not_mem_compl_iff {x : α} : x ∉ sᶜ ↔ x ∈ s := not_not @[simp] theorem inter_compl_self (s : set α) : s ∩ sᶜ = ∅ := inf_compl_eq_bot @[simp] theorem compl_inter_self (s : set α) : sᶜ ∩ s = ∅ := compl_inf_eq_bot @[simp] theorem compl_empty : (∅ : set α)ᶜ = univ := compl_bot @[simp] theorem compl_union (s t : set α) : (s ∪ t)ᶜ = sᶜ ∩ tᶜ := compl_sup theorem compl_inter (s t : set α) : (s ∩ t)ᶜ = sᶜ ∪ tᶜ := compl_inf @[simp] theorem compl_univ : (univ : set α)ᶜ = ∅ := compl_top @[simp] lemma compl_empty_iff {s : set α} : sᶜ = ∅ ↔ s = univ := compl_eq_bot @[simp] lemma compl_univ_iff {s : set α} : sᶜ = univ ↔ s = ∅ := compl_eq_top lemma compl_ne_univ : sᶜ ≠ univ ↔ s.nonempty := compl_univ_iff.not.trans ne_empty_iff_nonempty lemma nonempty_compl {s : set α} : sᶜ.nonempty ↔ s ≠ univ := ne_empty_iff_nonempty.symm.trans compl_empty_iff.not lemma mem_compl_singleton_iff {a x : α} : x ∈ ({a} : set α)ᶜ ↔ x ≠ a := mem_singleton_iff.not lemma compl_singleton_eq (a : α) : ({a} : set α)ᶜ = {x | x ≠ a} := ext $ λ x, mem_compl_singleton_iff @[simp] lemma compl_ne_eq_singleton (a : α) : ({x | x ≠ a} : set α)ᶜ = {a} := by { ext, simp, } theorem union_eq_compl_compl_inter_compl (s t : set α) : s ∪ t = (sᶜ ∩ tᶜ)ᶜ := ext $ λ x, or_iff_not_and_not theorem inter_eq_compl_compl_union_compl (s t : set α) : s ∩ t = (sᶜ ∪ tᶜ)ᶜ := ext $ λ x, and_iff_not_or_not @[simp] theorem union_compl_self (s : set α) : s ∪ sᶜ = univ := eq_univ_iff_forall.2 $ λ x, em _ @[simp] theorem compl_union_self (s : set α) : sᶜ ∪ s = univ := by rw [union_comm, union_compl_self] lemma compl_subset_comm : sᶜ ⊆ t ↔ tᶜ ⊆ s := @compl_le_iff_compl_le _ s _ _ lemma subset_compl_comm : s ⊆ tᶜ ↔ t ⊆ sᶜ := @le_compl_iff_le_compl _ t _ _ @[simp] lemma compl_subset_compl : sᶜ ⊆ tᶜ ↔ t ⊆ s := @compl_le_compl_iff_le (set α) _ _ _ lemma subset_compl_iff_disjoint_left : s ⊆ tᶜ ↔ disjoint t s := @le_compl_iff_disjoint_left (set α) _ _ _ lemma subset_compl_iff_disjoint_right : s ⊆ tᶜ ↔ disjoint s t := @le_compl_iff_disjoint_right (set α) _ _ _ lemma disjoint_compl_left_iff_subset : disjoint sᶜ t ↔ t ⊆ s := disjoint_compl_left_iff lemma disjoint_compl_right_iff_subset : disjoint s tᶜ ↔ s ⊆ t := disjoint_compl_right_iff alias subset_compl_iff_disjoint_right ↔ _ _root_.disjoint.subset_compl_right alias subset_compl_iff_disjoint_left ↔ _ _root_.disjoint.subset_compl_left alias disjoint_compl_left_iff_subset ↔ _ _root_.has_subset.subset.disjoint_compl_left alias disjoint_compl_right_iff_subset ↔ _ _root_.has_subset.subset.disjoint_compl_right theorem subset_union_compl_iff_inter_subset {s t u : set α} : s ⊆ t ∪ uᶜ ↔ s ∩ u ⊆ t := (@is_compl_compl _ u _).le_sup_right_iff_inf_left_le theorem compl_subset_iff_union {s t : set α} : sᶜ ⊆ t ↔ s ∪ t = univ := iff.symm $ eq_univ_iff_forall.trans $ forall_congr $ λ a, or_iff_not_imp_left @[simp] lemma subset_compl_singleton_iff {a : α} {s : set α} : s ⊆ {a}ᶜ ↔ a ∉ s := subset_compl_comm.trans singleton_subset_iff theorem inter_subset (a b c : set α) : a ∩ b ⊆ c ↔ a ⊆ bᶜ ∪ c := forall_congr $ λ x, and_imp.trans $ imp_congr_right $ λ _, imp_iff_not_or lemma inter_compl_nonempty_iff {s t : set α} : (s ∩ tᶜ).nonempty ↔ ¬ s ⊆ t := (not_subset.trans $ exists_congr $ by exact λ x, by simp [mem_compl]).symm /-! ### 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 diff_eq_compl_inter {s t : set α} : s \ t = tᶜ ∩ s := by rw [diff_eq, inter_comm] theorem nonempty_diff {s t : set α} : (s \ t).nonempty ↔ ¬ (s ⊆ t) := inter_compl_nonempty_iff theorem diff_subset (s t : set α) : s \ t ⊆ s := show s \ t ≤ s, from sdiff_le theorem union_diff_cancel' {s t u : set α} (h₁ : s ⊆ t) (h₂ : t ⊆ u) : t ∪ (u \ s) = u := sup_sdiff_cancel' h₁ h₂ theorem union_diff_cancel {s t : set α} (h : s ⊆ t) : s ∪ (t \ s) = t := sup_sdiff_cancel_right h theorem union_diff_cancel_left {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ s = t := disjoint.sup_sdiff_cancel_left h theorem union_diff_cancel_right {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ t = s := disjoint.sup_sdiff_cancel_right h @[simp] theorem union_diff_left {s t : set α} : (s ∪ t) \ s = t \ s := sup_sdiff_left_self @[simp] theorem union_diff_right {s t : set α} : (s ∪ t) \ t = s \ t := sup_sdiff_right_self theorem union_diff_distrib {s t u : set α} : (s ∪ t) \ u = s \ u ∪ t \ u := sup_sdiff theorem inter_diff_assoc (a b c : set α) : (a ∩ b) \ c = a ∩ (b \ c) := inf_sdiff_assoc @[simp] theorem inter_diff_self (a b : set α) : a ∩ (b \ a) = ∅ := inf_sdiff_self_right @[simp] theorem inter_union_diff (s t : set α) : (s ∩ t) ∪ (s \ t) = s := sup_inf_sdiff s t @[simp] lemma diff_union_inter (s t : set α) : (s \ t) ∪ (s ∩ t) = s := by { rw union_comm, exact sup_inf_sdiff _ _ } @[simp] theorem inter_union_compl (s t : set α) : (s ∩ t) ∪ (s ∩ tᶜ) = s := inter_union_diff _ _ theorem diff_subset_diff {s₁ s₂ t₁ t₂ : set α} : s₁ ⊆ s₂ → t₂ ⊆ t₁ → s₁ \ t₁ ⊆ s₂ \ t₂ := show s₁ ≤ s₂ → t₂ ≤ t₁ → s₁ \ t₁ ≤ s₂ \ t₂, from sdiff_le_sdiff theorem diff_subset_diff_left {s₁ s₂ t : set α} (h : s₁ ⊆ s₂) : s₁ \ t ⊆ s₂ \ t := sdiff_le_sdiff_right ‹s₁ ≤ s₂› theorem diff_subset_diff_right {s t u : set α} (h : t ⊆ u) : s \ u ⊆ s \ t := sdiff_le_sdiff_left ‹t ≤ u› theorem compl_eq_univ_diff (s : set α) : sᶜ = univ \ s := top_sdiff.symm @[simp] lemma empty_diff (s : set α) : (∅ \ s : set α) = ∅ := bot_sdiff theorem diff_eq_empty {s t : set α} : s \ t = ∅ ↔ s ⊆ t := sdiff_eq_bot_iff @[simp] theorem diff_empty {s : set α} : s \ ∅ = s := sdiff_bot @[simp] lemma diff_univ (s : set α) : s \ univ = ∅ := diff_eq_empty.2 (subset_univ s) theorem diff_diff {u : set α} : s \ t \ u = s \ (t ∪ u) := sdiff_sdiff_left -- the following statement contains parentheses to help the reader lemma diff_diff_comm {s t u : set α} : (s \ t) \ u = (s \ u) \ t := sdiff_sdiff_comm lemma diff_subset_iff {s t u : set α} : s \ t ⊆ u ↔ s ⊆ t ∪ u := show s \ t ≤ u ↔ s ≤ t ∪ u, from sdiff_le_iff lemma subset_diff_union (s t : set α) : s ⊆ (s \ t) ∪ t := show s ≤ (s \ t) ∪ t, from le_sdiff_sup lemma diff_union_of_subset {s t : set α} (h : t ⊆ s) : (s \ t) ∪ t = s := subset.antisymm (union_subset (diff_subset _ _) h) (subset_diff_union _ _) @[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 := show s \ t ≤ u ↔ s \ u ≤ t, from sdiff_le_comm lemma diff_inter {s t u : set α} : s \ (t ∩ u) = (s \ t) ∪ (s \ u) := sdiff_inf lemma diff_inter_diff {s t u : set α} : s \ t ∩ (s \ u) = s \ (t ∪ u) := sdiff_sup.symm lemma diff_compl : s \ tᶜ = s ∩ t := sdiff_compl lemma diff_diff_right {s t u : set α} : s \ (t \ u) = (s \ t) ∪ (s ∩ u) := sdiff_sdiff_right' @[simp] theorem insert_diff_of_mem (s) (h : a ∈ t) : insert a s \ t = s \ t := by { ext, split; 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 lemma insert_diff_self_of_not_mem {a : α} {s : set α} (h : a ∉ s) : insert a s \ {a} = s := by { ext, simp [and_iff_left_of_imp (λ hx : x ∈ s, show x ≠ a, from λ hxa, h $ hxa ▸ hx)] } @[simp] lemma insert_diff_eq_singleton {a : α} {s : set α} (h : a ∉ s) : insert a s \ s = {a} := begin ext, rw [set.mem_diff, set.mem_insert_iff, set.mem_singleton_iff, or_and_distrib_right, and_not_self, or_false, and_iff_left_iff_imp], rintro rfl, exact h, end lemma inter_insert_of_mem (h : a ∈ s) : s ∩ insert a t = insert a (s ∩ t) := by rw [insert_inter_distrib, insert_eq_of_mem h] lemma insert_inter_of_mem (h : a ∈ t) : insert a s ∩ t = insert a (s ∩ t) := by rw [insert_inter_distrib, insert_eq_of_mem h] lemma inter_insert_of_not_mem (h : a ∉ s) : s ∩ insert a t = s ∩ t := ext $ λ x, and_congr_right $ λ hx, or_iff_right $ ne_of_mem_of_not_mem hx h lemma insert_inter_of_not_mem (h : a ∉ t) : insert a s ∩ t = s ∩ t := ext $ λ x, and_congr_left $ λ hx, or_iff_right $ ne_of_mem_of_not_mem hx h @[simp] theorem union_diff_self {s t : set α} : s ∪ (t \ s) = s ∪ t := sup_sdiff_self_right @[simp] theorem diff_union_self {s t : set α} : (s \ t) ∪ t = s ∪ t := sup_sdiff_self_left @[simp] theorem diff_inter_self {a b : set α} : (b \ a) ∩ a = ∅ := inf_sdiff_self_left @[simp] theorem diff_inter_self_eq_diff {s t : set α} : s \ (t ∩ s) = s \ t := sdiff_inf_self_right @[simp] theorem diff_self_inter {s t : set α} : s \ (s ∩ t) = s \ t := sdiff_inf_self_left @[simp] theorem diff_eq_self {s t : set α} : s \ t = s ↔ t ∩ s ⊆ ∅ := show s \ t = s ↔ t ⊓ s ≤ ⊥, from sdiff_eq_self_iff_disjoint @[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 = ∅ := sdiff_self lemma diff_diff_right_self (s t : set α) : s \ (s \ t) = s ∩ t := sdiff_sdiff_right_self lemma diff_diff_cancel_left {s t : set α} (h : s ⊆ t) : t \ (t \ s) = s := sdiff_sdiff_eq_self h 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 $ iff.rfl.and ne_empty_iff_nonempty lemma union_eq_diff_union_diff_union_inter (s t : set α) : s ∪ t = (s \ t) ∪ (t \ s) ∪ (s ∩ t) := sup_eq_sdiff_sup_sdiff_sup_inf /-! ### Powerset -/ /-- `𝒫 s = set.powerset s` is the set of all subsets of `s`. -/ def powerset (s : set α) : set (set α) := {t | t ⊆ s} prefix `𝒫`:100 := powerset theorem mem_powerset {x s : set α} (h : x ⊆ s) : x ∈ 𝒫 s := h theorem subset_of_mem_powerset {x s : set α} (h : x ∈ 𝒫 s) : x ⊆ s := h @[simp] theorem mem_powerset_iff (x s : set α) : x ∈ 𝒫 s ↔ x ⊆ s := iff.rfl theorem powerset_inter (s t : set α) : 𝒫 (s ∩ t) = 𝒫 s ∩ 𝒫 t := ext $ λ u, subset_inter_iff @[simp] theorem powerset_mono : 𝒫 s ⊆ 𝒫 t ↔ s ⊆ t := ⟨λ h, h (subset.refl s), λ h u hu, subset.trans hu h⟩ theorem monotone_powerset : monotone (powerset : set α → set (set α)) := λ s t, powerset_mono.2 @[simp] theorem powerset_nonempty : (𝒫 s).nonempty := ⟨∅, empty_subset s⟩ @[simp] theorem powerset_empty : 𝒫 (∅ : set α) = {∅} := ext $ λ s, subset_empty_iff @[simp] theorem powerset_univ : 𝒫 (univ : set α) = univ := eq_univ_of_forall subset_univ /-! ### If-then-else for sets -/ /-- `ite` for sets: `set.ite t s s' ∩ t = s ∩ t`, `set.ite t s s' ∩ tᶜ = s' ∩ tᶜ`. Defined as `s ∩ t ∪ s' \ t`. -/ protected def ite (t s s' : set α) : set α := s ∩ t ∪ s' \ t @[simp] lemma ite_inter_self (t s s' : set α) : t.ite s s' ∩ t = s ∩ t := by rw [set.ite, union_inter_distrib_right, diff_inter_self, inter_assoc, inter_self, union_empty] @[simp] lemma ite_compl (t s s' : set α) : tᶜ.ite s s' = t.ite s' s := by rw [set.ite, set.ite, diff_compl, union_comm, diff_eq] @[simp] lemma ite_inter_compl_self (t s s' : set α) : t.ite s s' ∩ tᶜ = s' ∩ tᶜ := by rw [← ite_compl, ite_inter_self] @[simp] lemma ite_diff_self (t s s' : set α) : t.ite s s' \ t = s' \ t := ite_inter_compl_self t s s' @[simp] lemma ite_same (t s : set α) : t.ite s s = s := inter_union_diff _ _ @[simp] lemma ite_left (s t : set α) : s.ite s t = s ∪ t := by simp [set.ite] @[simp] lemma ite_right (s t : set α) : s.ite t s = t ∩ s := by simp [set.ite] @[simp] lemma ite_empty (s s' : set α) : set.ite ∅ s s' = s' := by simp [set.ite] @[simp] lemma ite_univ (s s' : set α) : set.ite univ s s' = s := by simp [set.ite] @[simp] lemma ite_empty_left (t s : set α) : t.ite ∅ s = s \ t := by simp [set.ite] @[simp] lemma ite_empty_right (t s : set α) : t.ite s ∅ = s ∩ t := by simp [set.ite] lemma ite_mono (t : set α) {s₁ s₁' s₂ s₂' : set α} (h : s₁ ⊆ s₂) (h' : s₁' ⊆ s₂') : t.ite s₁ s₁' ⊆ t.ite s₂ s₂' := union_subset_union (inter_subset_inter_left _ h) (inter_subset_inter_left _ h') lemma ite_subset_union (t s s' : set α) : t.ite s s' ⊆ s ∪ s' := union_subset_union (inter_subset_left _ _) (diff_subset _ _) lemma inter_subset_ite (t s s' : set α) : s ∩ s' ⊆ t.ite s s' := ite_same t (s ∩ s') ▸ ite_mono _ (inter_subset_left _ _) (inter_subset_right _ _) lemma ite_inter_inter (t s₁ s₂ s₁' s₂' : set α) : t.ite (s₁ ∩ s₂) (s₁' ∩ s₂') = t.ite s₁ s₁' ∩ t.ite s₂ s₂' := by { ext x, simp only [set.ite, set.mem_inter_eq, set.mem_diff, set.mem_union_eq], itauto } lemma ite_inter (t s₁ s₂ s : set α) : t.ite (s₁ ∩ s) (s₂ ∩ s) = t.ite s₁ s₂ ∩ s := by rw [ite_inter_inter, ite_same] lemma ite_inter_of_inter_eq (t : set α) {s₁ s₂ s : set α} (h : s₁ ∩ s = s₂ ∩ s) : t.ite s₁ s₂ ∩ s = s₁ ∩ s := by rw [← ite_inter, ← h, ite_same] lemma subset_ite {t s s' u : set α} : u ⊆ t.ite s s' ↔ u ∩ t ⊆ s ∧ u \ t ⊆ s' := begin simp only [subset_def, ← forall_and_distrib], refine forall_congr (λ x, _), by_cases hx : x ∈ t; simp [*, set.ite] end /-! ### 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 lemma preimage_congr {f g : α → β} {s : set β} (h : ∀ (x : α), f x = g x) : f ⁻¹' s = g ⁻¹' s := by { congr' with x, apply_assumption } 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_ite (f : α → β) (s t₁ t₂ : set β) : f ⁻¹' (s.ite t₁ t₂) = (f ⁻¹' s).ite (f ⁻¹' t₁) (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 @[simp] theorem preimage_id' {s : set α} : (λ x, x) ⁻¹' s = s := rfl @[simp] theorem preimage_const_of_mem {b : β} {s : set β} (h : b ∈ s) : (λ (x : α), b) ⁻¹' s = univ := eq_univ_of_forall $ λ x, h @[simp] theorem preimage_const_of_not_mem {b : β} {s : set β} (h : b ∉ s) : (λ (x : α), b) ⁻¹' s = ∅ := eq_empty_of_subset_empty $ λ x hx, h hx theorem preimage_const (b : β) (s : set β) [decidable (b ∈ s)] : (λ (x : α), b) ⁻¹' s = if b ∈ s then univ else ∅ := by { split_ifs with hb hb, exacts [preimage_const_of_mem hb, preimage_const_of_not_mem hb] } theorem preimage_comp {s : set γ} : (g ∘ f) ⁻¹' s = f ⁻¹' (g ⁻¹' s) := rfl lemma preimage_preimage {g : β → γ} {f : α → β} {s : set γ} : f ⁻¹' (g ⁻¹' s) = (λ x, g (f x)) ⁻¹' s := preimage_comp.symm 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 $ λ ⟨x, hx⟩, by simp [h]⟩ lemma nonempty_of_nonempty_preimage {s : set β} {f : α → β} (hf : (f ⁻¹' s).nonempty) : s.nonempty := let ⟨x, hx⟩ := hf in ⟨f x, hx⟩ end preimage /-! ### Image of a set under a function -/ section image /-- The image of `s : set α` by `f : α → β`, written `f '' s`, is the set of `y : β` such that `f x = y` for some `x ∈ s`. -/ def image (f : α → β) (s : set α) : set β := {y | ∃ x, x ∈ s ∧ f x = y} infix ` '' `:80 := 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 lemma image_eta (f : α → β) : f '' s = (λ x, f x) '' s := rfl theorem mem_image_of_mem (f : α → β) {x : α} {a : set α} (h : x ∈ a) : f x ∈ f '' a := ⟨_, h, rfl⟩ theorem _root_.function.injective.mem_set_image {f : α → β} (hf : injective f) {s : set α} {a : α} : f a ∈ f '' s ↔ a ∈ s := ⟨λ ⟨b, hb, eq⟩, (hf eq) ▸ hb, mem_image_of_mem f⟩ theorem ball_image_iff {f : α → β} {s : set α} {p : β → Prop} : (∀ y ∈ f '' s, p y) ↔ (∀ x ∈ s, p (f x)) := by simp theorem ball_image_of_ball {f : α → β} {s : set α} {p : β → Prop} (h : ∀ x ∈ s, p (f x)) : ∀ y ∈ f '' s, p y := ball_image_iff.2 h 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) /-- 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 lemma image_comm {β'} {f : β → γ} {g : α → β} {f' : α → β'} {g' : β' → γ} (h_comm : ∀ a, f (g a) = g' (f' a)) : (s.image g).image f = (s.image f').image g' := by simp_rw [image_image, h_comm] lemma _root_.function.semiconj.set_image {f : α → β} {ga : α → α} {gb : β → β} (h : function.semiconj f ga gb) : function.semiconj (image f) (image ga) (image gb) := λ s, image_comm h lemma _root_.function.commute.set_image {f g : α → α} (h : function.commute f g) : function.commute (image f) (image g) := h.set_image /-- 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 { simp only [subset_def, mem_image_eq], exact λ x, λ ⟨w, h1, h2⟩, ⟨w, h h1, h2⟩ } theorem image_union (f : α → β) (s t : set α) : f '' (s ∪ t) = f '' s ∪ f '' t := ext $ λ x, ⟨by rintro ⟨a, h|h, rfl⟩; [left, right]; exact ⟨_, h, rfl⟩, by rintro (⟨a, h, rfl⟩ | ⟨a, h, rfl⟩); refine ⟨_, _, rfl⟩; [left, right]; exact h⟩ @[simp] theorem image_empty (f : α → β) : f '' ∅ = ∅ := by { ext, 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 { simpa [image] } @[simp] theorem image_singleton {f : α → β} {a : α} : f '' {a} = {f a} := by { ext, simp [image, eq_comm] } @[simp] 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 preimage_compl_eq_image_compl [boolean_algebra α] (S : set α) : compl ⁻¹' S = compl '' S := set.ext (λ x, ⟨λ h, ⟨xᶜ,h, compl_compl x⟩, λ h, exists.elim h (λ y hy, (compl_eq_comm.mp hy.2).symm.subst hy.1)⟩) theorem mem_compl_image [boolean_algebra α] (t : α) (S : set α) : t ∈ compl '' S ↔ tᶜ ∈ S := by simp [←preimage_compl_eq_image_compl] /-- A variant of `image_id` -/ @[simp] lemma image_id' (s : set α) : (λx, x) '' s = s := by { ext, simp } theorem image_id (s : set α) : id '' s = s := by simp theorem compl_compl_image [boolean_algebra α] (S : 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) := by { ext, 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)ᶜ := disjoint.subset_compl_left $ by simp [disjoint, 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) theorem subset_image_diff (f : α → β) (s t : set α) : f '' s \ f '' t ⊆ f '' (s \ t) := begin rw [diff_subset_iff, ← image_union, union_diff_self], exact image_subset f (subset_union_right t s) end theorem image_diff {f : α → β} (hf : injective f) (s t : set α) : f '' (s \ t) = f '' s \ f '' t := subset.antisymm (subset.trans (image_inter_subset _ _ _) $ inter_subset_inter_right _ $ image_compl_subset hf) (subset_image_diff f s t) 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⟩ lemma nonempty.preimage {s : set β} (hs : s.nonempty) {f : α → β} (hf : surjective f) : (f ⁻¹' s).nonempty := let ⟨y, hy⟩ := hs, ⟨x, hx⟩ := hf y in ⟨x, mem_preimage.2 $ hx.symm ▸ hy⟩ instance (f : α → β) (s : set α) [nonempty s] : nonempty (f '' s) := (set.nonempty.image f nonempty_of_nonempty_subtype).to_subtype /-- image and preimage are a Galois connection -/ @[simp] 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.rfl 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 = f ⁻¹' t ↔ s = t := iff.intro (assume eq, by rw [← image_preimage_eq s hf, ← image_preimage_eq t hf, eq]) (assume eq, eq ▸ rfl) lemma image_inter_preimage (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 lemma image_preimage_inter (f : α → β) (s : set α) (t : set β) : f '' (f ⁻¹' t ∩ s) = t ∩ f '' s := by simp only [inter_comm, image_inter_preimage] @[simp] lemma image_inter_nonempty_iff {f : α → β} {s : set α} {t : set β} : (f '' s ∩ t).nonempty ↔ (s ∩ f ⁻¹' t).nonempty := by rw [←image_inter_preimage, nonempty_image_iff] lemma image_diff_preimage {f : α → β} {s : set α} {t : set β} : f '' (s \ f ⁻¹' t) = f '' s \ t := by simp_rw [diff_eq, ← preimage_compl, image_inter_preimage] theorem compl_image : image (compl : set α → set α) = 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 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₁⟩) lemma exists_image_iff (f : α → β) (x : set α) (P : β → Prop) : (∃ (a : f '' x), P a) ↔ ∃ (a : x), P (f a) := ⟨λ ⟨a, h⟩, ⟨⟨_, a.prop.some_spec.1⟩, a.prop.some_spec.2.symm ▸ h⟩, λ ⟨a, h⟩, ⟨⟨_, _, a.prop, rfl⟩, 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⟩ /-- If the only elements outside `s` are those left fixed by `σ`, then mapping by `σ` has no effect. -/ lemma image_perm {s : set α} {σ : equiv.perm α} (hs : {a : α | σ a ≠ a} ⊆ s) : σ '' s = s := begin ext i, obtain hi | hi := eq_or_ne (σ i) i, { refine ⟨_, λ h, ⟨i, h, hi⟩⟩, rintro ⟨j, hj, h⟩, rwa σ.injective (hi.trans h.symm) }, { refine iff_of_true ⟨σ.symm i, hs $ λ h, hi _, σ.apply_symm_apply _⟩ (hs hi), convert congr_arg σ h; exact (σ.apply_symm_apply _).symm } end 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⟩ @[simp] lemma subsingleton_empty : (∅ : set α).subsingleton := λ x, false.elim @[simp] 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_of_subset_singleton (h : s ⊆ {a}) : s.subsingleton := subsingleton_singleton.mono h lemma subsingleton_of_forall_eq (a : α) (h : ∀ b ∈ s, b = a) : s.subsingleton := λ b hb c hc, (h _ hb).trans (h _ hc).symm lemma subsingleton_iff_singleton {x} (hx : x ∈ s) : s.subsingleton ↔ s = {x} := ⟨λ h, h.eq_singleton_of_mem hx, λ h,h.symm ▸ subsingleton_singleton⟩ 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.induction_on {p : set α → Prop} (hs : s.subsingleton) (he : p ∅) (h₁ : ∀ x, p {x}) : p s := by { rcases hs.eq_empty_or_singleton with rfl|⟨x, rfl⟩, exacts [he, h₁ _] } lemma subsingleton_univ [subsingleton α] : (univ : set α).subsingleton := λ x hx y hy, subsingleton.elim x y lemma subsingleton_of_univ_subsingleton (h : (univ : set α).subsingleton) : subsingleton α := ⟨λ a b, h (mem_univ a) (mem_univ b)⟩ @[simp] lemma subsingleton_univ_iff : (univ : set α).subsingleton ↔ subsingleton α := ⟨subsingleton_of_univ_subsingleton, λ h, @subsingleton_univ _ h⟩ lemma subsingleton_of_subsingleton [subsingleton α] {s : set α} : set.subsingleton s := subsingleton.mono subsingleton_univ (subset_univ s) lemma subsingleton_is_top (α : Type*) [partial_order α] : set.subsingleton {x : α | is_top x} := λ x hx y hy, hx.is_max.eq_of_le (hy x) lemma subsingleton_is_bot (α : Type*) [partial_order α] : set.subsingleton {x : α | is_bot x} := λ x hx y hy, hx.is_min.eq_of_ge (hy x) lemma exists_eq_singleton_iff_nonempty_subsingleton : (∃ a : α, s = {a}) ↔ s.nonempty ∧ s.subsingleton := begin refine ⟨_, λ h, _⟩, { rintros ⟨a, rfl⟩, exact ⟨singleton_nonempty a, subsingleton_singleton⟩ }, { exact h.2.eq_empty_or_singleton.resolve_left h.1.ne_empty }, end /-- `s`, coerced to a type, is a subsingleton type if and only if `s` is a subsingleton set. -/ @[simp, norm_cast] lemma subsingleton_coe (s : set α) : subsingleton s ↔ s.subsingleton := begin split, { refine λ h, (λ a ha b hb, _), exact set_coe.ext_iff.2 (@subsingleton.elim s h ⟨a, ha⟩ ⟨b, hb⟩) }, { exact λ h, subsingleton.intro (λ a b, set_coe.ext (h a.property b.property)) } end /-- The `coe_sort` of a set `s` in a subsingleton type is a subsingleton. For the corresponding result for `subtype`, see `subtype.subsingleton`. -/ instance subsingleton_coe_of_subsingleton [subsingleton α] {s : set α} : subsingleton s := by { rw [s.subsingleton_coe], exact subsingleton_of_subsingleton } /-- The preimage of a subsingleton under an injective map is a subsingleton. -/ theorem subsingleton.preimage {s : set β} (hs : s.subsingleton) {f : α → β} (hf : function.injective f) : (f ⁻¹' s).subsingleton := λ a ha b hb, hf $ hs ha hb /-- `s` is a subsingleton, if its image of an injective function is. -/ theorem subsingleton_of_image {α β : Type*} {f : α → β} (hf : function.injective f) (s : set α) (hs : (f '' s).subsingleton) : s.subsingleton := (hs.preimage hf).mono $ subset_preimage_image _ _ 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 @[simp] 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)) := by simp theorem forall_subtype_range_iff {p : range f → Prop} : (∀ a : range f, p a) ↔ ∀ i, p ⟨f i, mem_range_self _⟩ := ⟨λ H i, H _, λ H ⟨y, i, hi⟩, by { subst hi, apply H }⟩ 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 lemma exists_subtype_range_iff {p : range f → Prop} : (∃ a : range f, p a) ↔ ∃ i, p ⟨f i, mem_range_self _⟩ := ⟨λ ⟨⟨a, i, hi⟩, ha⟩, by { subst a, exact ⟨i, ha⟩}, λ ⟨i, hi⟩, ⟨_, hi⟩⟩ theorem range_iff_surjective : range f = univ ↔ surjective f := eq_univ_iff_forall alias range_iff_surjective ↔ _ _root_.function.surjective.range_eq @[simp] theorem image_univ {f : α → β} : f '' univ = range f := by { ext, simp [image, range] } theorem image_subset_range (f : α → β) (s) : f '' s ⊆ range f := by rw ← image_univ; exact image_subset _ (subset_univ _) theorem mem_range_of_mem_image (f : α → β) (s) {x : β} (h : x ∈ f '' s) : x ∈ range f := image_subset_range f s h lemma nonempty.preimage' {s : set β} (hs : s.nonempty) {f : α → β} (hf : s ⊆ set.range f) : (f ⁻¹' s).nonempty := let ⟨y, hy⟩ := hs, ⟨x, hx⟩ := hf hy in ⟨x, set.mem_preimage.2 $ hx.symm ▸ hy⟩ theorem range_comp (g : α → β) (f : ι → α) : 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 : range f ⊆ s ↔ ∀ y, f y ∈ s := forall_range_iff theorem range_eq_iff (f : α → β) (s : set β) : range f = s ↔ (∀ a, f a ∈ s) ∧ ∀ b ∈ s, ∃ a, f a = b := by { rw ←range_subset_iff, exact le_antisymm_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_iff {f : ι → α} : range f = ∅ ↔ is_empty ι := by rw [← not_nonempty_iff, ← range_nonempty_iff_nonempty, not_nonempty_iff_eq_empty] lemma range_eq_empty [is_empty ι] (f : ι → α) : range f = ∅ := range_eq_empty_iff.2 ‹_› instance [nonempty ι] (f : ι → α) : nonempty (range f) := (range_nonempty f).to_subtype @[simp] lemma image_union_image_compl_eq_range (f : α → β) : (f '' s) ∪ (f '' sᶜ) = range f := by rw [← image_union, ← image_univ, ← union_compl_self] lemma insert_image_compl_eq_range (f : α → β) (x : α) : insert (f x) (f '' {x}ᶜ) = range f := begin ext y, rw [mem_range, mem_insert_iff, mem_image], split, { rintro (h | ⟨x', hx', h⟩), { exact ⟨x, h.symm⟩ }, { exact ⟨x', h⟩ } }, { rintro ⟨x', h⟩, by_cases hx : x' = x, { left, rw [← h, hx] }, { right, refine ⟨_, _, h⟩, rw mem_compl_singleton_iff, exact hx } } end 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 image_preimage_eq_iff {f : α → β} {s : set β} : f '' (f ⁻¹' s) = s ↔ s ⊆ range f := ⟨by { intro h, rw [← h], apply image_subset_range }, image_preimage_eq_of_subset⟩ lemma subset_range_iff_exists_image_eq {f : α → β} {s : set β} : s ⊆ range f ↔ ∃ t, f '' t = s := ⟨λ h, ⟨_, image_preimage_eq_iff.2 h⟩, λ ⟨t, ht⟩, ht ▸ image_subset_range _ _⟩ lemma range_image (f : α → β) : range (image f) = 𝒫 (range f) := ext $ λ s, subset_range_iff_exists_image_eq.symm 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 @[simp] theorem preimage_inter_range {f : α → β} {s : set β} : f ⁻¹' (s ∩ range f) = f ⁻¹' s := set.ext $ λ x, and_iff_left ⟨x, rfl⟩ @[simp] theorem preimage_range_inter {f : α → β} {s : set β} : f ⁻¹' (range f ∩ s) = f ⁻¹' s := by rw [inter_comm, preimage_inter_range] 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 range_id : range (@id α) = univ := range_iff_surjective.2 surjective_id @[simp] theorem range_id' : range (λ (x : α), x) = univ := range_id @[simp] theorem _root_.prod.range_fst [nonempty β] : range (prod.fst : α × β → α) = univ := prod.fst_surjective.range_eq @[simp] theorem _root_.prod.range_snd [nonempty α] : range (prod.snd : α × β → β) = univ := prod.snd_surjective.range_eq @[simp] theorem range_eval {ι : Type*} {α : ι → Sort*} [Π i, nonempty (α i)] (i : ι) : range (eval i : (Π i, α i) → α i) = univ := (surjective_eval i).range_eq theorem is_compl_range_inl_range_inr : is_compl (range $ @sum.inl α β) (range sum.inr) := ⟨by { rintro y ⟨⟨x₁, rfl⟩, ⟨x₂, _⟩⟩, cc }, by { rintro (x|y) -; [left, right]; exact mem_range_self _ }⟩ @[simp] theorem range_inl_union_range_inr : range (sum.inl : α → α ⊕ β) ∪ range sum.inr = univ := is_compl_range_inl_range_inr.sup_eq_top @[simp] theorem range_inl_inter_range_inr : range (sum.inl : α → α ⊕ β) ∩ range sum.inr = ∅ := is_compl_range_inl_range_inr.inf_eq_bot @[simp] theorem range_inr_union_range_inl : range (sum.inr : β → α ⊕ β) ∪ range sum.inl = univ := is_compl_range_inl_range_inr.symm.sup_eq_top @[simp] theorem range_inr_inter_range_inl : range (sum.inr : β → α ⊕ β) ∩ range sum.inl = ∅ := is_compl_range_inl_range_inr.symm.inf_eq_bot @[simp] theorem preimage_inl_image_inr (s : set β) : sum.inl ⁻¹' (@sum.inr α β '' s) = ∅ := by { ext, simp } @[simp] theorem preimage_inr_image_inl (s : set α) : sum.inr ⁻¹' (@sum.inl α β '' s) = ∅ := by { ext, simp } @[simp] theorem preimage_inl_range_inr : sum.inl ⁻¹' range (sum.inr : β → α ⊕ β) = ∅ := by rw [← image_univ, preimage_inl_image_inr] @[simp] theorem preimage_inr_range_inl : sum.inr ⁻¹' range (sum.inl : α → α ⊕ β) = ∅ := by rw [← image_univ, preimage_inr_image_inl] @[simp] lemma compl_range_inl : (range (sum.inl : α → α ⊕ β))ᶜ = range (sum.inr : β → α ⊕ β) := is_compl_range_inl_range_inr.compl_eq @[simp] lemma compl_range_inr : (range (sum.inr : β → α ⊕ β))ᶜ = range (sum.inl : α → α ⊕ β) := is_compl_range_inl_range_inr.symm.compl_eq @[simp] theorem range_quot_mk (r : α → α → Prop) : range (quot.mk r) = univ := (surjective_quot_mk r).range_eq instance can_lift [can_lift α β] : can_lift (set α) (set β) := { coe := λ s, can_lift.coe '' s, cond := λ s, ∀ x ∈ s, can_lift.cond β x, prf := λ s hs, subset_range_iff_exists_image_eq.mp (λ x hx, can_lift.prf _ (hs x hx)) } @[simp] theorem range_quotient_mk [setoid α] : range (λx : α, ⟦x⟧) = univ := range_quot_mk _ 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 lemma 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 preimage_singleton_nonempty {f : α → β} {y : β} : (f ⁻¹' {y}).nonempty ↔ y ∈ range f := iff.rfl theorem preimage_singleton_eq_empty {f : α → β} {y : β} : f ⁻¹' {y} = ∅ ↔ y ∉ range f := not_nonempty_iff_eq_empty.symm.trans preimage_singleton_nonempty.not lemma range_subset_singleton {f : ι → α} {x : α} : range f ⊆ {x} ↔ f = const ι x := by simp [range_subset_iff, funext_iff, mem_singleton] lemma image_compl_preimage {f : α → β} {s : set β} : f '' ((f ⁻¹' s)ᶜ) = range f \ s := by rw [compl_eq_univ_diff, image_diff_preimage, image_univ] /-- 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 @[simp] lemma range_factorization_coe (f : ι → β) (a : ι) : (range_factorization f a : β) = f a := rfl @[simp] lemma coe_comp_range_factorization (f : ι → β) : coe ∘ range_factorization f = f := 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) := 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 @[simp] lemma preimage_range (f : α → β) : f ⁻¹' (range f) = univ := eq_univ_of_forall mem_range_self /-- The range of a function from a `unique` type contains just the function applied to its single value. -/ lemma range_unique [h : unique ι] : range f = {f default} := begin ext x, rw mem_range, split, { rintros ⟨i, hi⟩, rw h.uniq i at hi, exact hi ▸ mem_singleton _ }, { exact λ h, ⟨default, h.symm⟩ } end lemma range_diff_image_subset (f : α → β) (s : set α) : range f \ f '' s ⊆ f '' sᶜ := λ y ⟨⟨x, h₁⟩, h₂⟩, ⟨x, λ h, h₂ ⟨x, h, h₁⟩, h₁⟩ lemma range_diff_image {f : α → β} (H : injective f) (s : set α) : range f \ f '' s = f '' sᶜ := subset.antisymm (range_diff_image_subset f s) $ λ y ⟨x, hx, hy⟩, hy ▸ ⟨mem_range_self _, λ ⟨x', hx', eq⟩, hx $ H eq ▸ hx'⟩ /-- We can use the axiom of choice to pick a preimage for every element of `range f`. -/ noncomputable def range_splitting (f : α → β) : range f → α := λ x, x.2.some -- This can not be a `@[simp]` lemma because the head of the left hand side is a variable. lemma apply_range_splitting (f : α → β) (x : range f) : f (range_splitting f x) = x := x.2.some_spec attribute [irreducible] range_splitting @[simp] lemma comp_range_splitting (f : α → β) : f ∘ range_splitting f = coe := by { ext, simp only [function.comp_app], apply apply_range_splitting, } -- When `f` is injective, see also `equiv.of_injective`. lemma left_inverse_range_splitting (f : α → β) : left_inverse (range_factorization f) (range_splitting f) := λ x, by { ext, simp only [range_factorization_coe], apply apply_range_splitting, } lemma range_splitting_injective (f : α → β) : injective (range_splitting f) := (left_inverse_range_splitting f).injective lemma right_inverse_range_splitting {f : α → β} (h : injective f) : right_inverse (range_factorization f) (range_splitting f) := (left_inverse_range_splitting f).right_inverse_of_injective $ λ x y hxy, h $ subtype.ext_iff.1 hxy lemma preimage_range_splitting {f : α → β} (hf : injective f) : preimage (range_splitting f) = image (range_factorization f) := (image_eq_preimage_of_inverse (right_inverse_range_splitting hf) (left_inverse_range_splitting f)).symm lemma is_compl_range_some_none (α : Type*) : is_compl (range (some : α → option α)) {none} := ⟨λ x ⟨⟨a, ha⟩, (hn : x = none)⟩, option.some_ne_none _ (ha.trans hn), λ x hx, option.cases_on x (or.inr rfl) (λ x, or.inl $ mem_range_self _)⟩ @[simp] lemma compl_range_some (α : Type*) : (range (some : α → option α))ᶜ = {none} := (is_compl_range_some_none α).compl_eq @[simp] lemma range_some_inter_none (α : Type*) : range (some : α → option α) ∩ {none} = ∅ := (is_compl_range_some_none α).inf_eq_bot @[simp] lemma range_some_union_none (α : Type*) : range (some : α → option α) ∪ {none} = univ := (is_compl_range_some_none α).sup_eq_top @[simp] lemma insert_none_range_some (α : Type*) : insert none (range (some : α → option α)) = univ := (is_compl_range_some_none α).symm.sup_eq_top end range end set open set namespace function variables {ι : Sort*} {α : Type*} {β : Type*} {f : α → β} lemma surjective.preimage_injective (hf : surjective f) : injective (preimage f) := assume s t, (preimage_eq_preimage hf).1 lemma injective.preimage_image (hf : injective f) (s : set α) : f ⁻¹' (f '' s) = s := preimage_image_eq s hf lemma injective.preimage_surjective (hf : injective f) : surjective (preimage f) := by { intro s, use f '' s, rw hf.preimage_image } lemma injective.subsingleton_image_iff (hf : injective f) {s : set α} : (f '' s).subsingleton ↔ s.subsingleton := ⟨subsingleton_of_image hf s, λ h, h.image f⟩ lemma surjective.image_preimage (hf : surjective f) (s : set β) : f '' (f ⁻¹' s) = s := image_preimage_eq s hf lemma surjective.image_surjective (hf : surjective f) : surjective (image f) := by { intro s, use f ⁻¹' s, rw hf.image_preimage } lemma surjective.nonempty_preimage (hf : surjective f) {s : set β} : (f ⁻¹' s).nonempty ↔ s.nonempty := by rw [← nonempty_image_iff, hf.image_preimage] lemma injective.image_injective (hf : injective f) : injective (image f) := by { intros s t h, rw [←preimage_image_eq s hf, ←preimage_image_eq t hf, h] } lemma surjective.preimage_subset_preimage_iff {s t : set β} (hf : surjective f) : f ⁻¹' s ⊆ f ⁻¹' t ↔ s ⊆ t := by { apply preimage_subset_preimage_iff, rw [hf.range_eq], apply subset_univ } lemma surjective.range_comp {ι' : Sort*} {f : ι → ι'} (hf : surjective f) (g : ι' → α) : range (g ∘ f) = range g := ext $ λ y, (@surjective.exists _ _ _ hf (λ x, g x = y)).symm lemma injective.nonempty_apply_iff {f : set α → set β} (hf : injective f) (h2 : f ∅ = ∅) {s : set α} : (f s).nonempty ↔ s.nonempty := by rw [← ne_empty_iff_nonempty, ← h2, ← ne_empty_iff_nonempty, hf.ne_iff] lemma injective.mem_range_iff_exists_unique (hf : injective f) {b : β} : b ∈ range f ↔ ∃! a, f a = b := ⟨λ ⟨a, h⟩, ⟨a, h, λ a' ha, hf (ha.trans h.symm)⟩, exists_unique.exists⟩ lemma injective.exists_unique_of_mem_range (hf : injective f) {b : β} (hb : b ∈ range f) : ∃! a, f a = b := hf.mem_range_iff_exists_unique.mp hb theorem injective.compl_image_eq (hf : injective f) (s : set α) : (f '' s)ᶜ = f '' sᶜ ∪ (range f)ᶜ := begin ext y, rcases em (y ∈ range f) with ⟨x, rfl⟩|hx, { simp [hf.eq_iff] }, { rw [mem_range, not_exists] at hx, simp [hx] } end lemma left_inverse.image_image {g : β → α} (h : left_inverse g f) (s : set α) : g '' (f '' s) = s := by rw [← image_comp, h.comp_eq_id, image_id] lemma left_inverse.preimage_preimage {g : β → α} (h : left_inverse g f) (s : set α) : f ⁻¹' (g ⁻¹' s) = s := by rw [← preimage_comp, h.comp_eq_id, preimage_id] end function open function lemma option.injective_iff {α β} {f : option α → β} : injective f ↔ injective (f ∘ some) ∧ f none ∉ range (f ∘ some) := begin simp only [mem_range, not_exists, (∘)], refine ⟨λ hf, ⟨hf.comp (option.some_injective _), λ x, hf.ne $ option.some_ne_none _⟩, _⟩, rintro ⟨h_some, h_none⟩ (_|a) (_|b) hab, exacts [rfl, (h_none _ hab.symm).elim, (h_none _ hab).elim, congr_arg some (h_some hab)] end /-! ### Image and preimage on subtypes -/ namespace subtype variable {α : Type*} lemma coe_image {p : α → Prop} {s : set (subtype p)} : coe '' 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 coe_image_of_subset {s t : set α} (h : t ⊆ s) : coe '' {x : ↥s | ↑x ∈ t} = t := begin ext x, rw set.mem_image, exact ⟨λ ⟨x', hx', hx⟩, hx ▸ hx', λ hx, ⟨⟨x, h hx⟩, hx, rfl⟩⟩, end lemma range_coe {s : set α} : range (coe : s → α) = s := by { rw ← set.image_univ, simp [-set.image_univ, coe_image] } /-- A variant of `range_coe`. Try to use `range_coe` if possible. This version is useful when defining a new type that is defined as the subtype of something. In that case, the coercion doesn't fire anymore. -/ lemma range_val {s : set α} : range (subtype.val : s → α) = s := range_coe /-- We make this the simp lemma instead of `range_coe`. The reason is that if we write for `s : set α` the function `coe : s → α`, then the inferred implicit arguments of `coe` are `coe α (λ x, x ∈ s)`. -/ @[simp] lemma range_coe_subtype {p : α → Prop} : range (coe : subtype p → α) = {x | p x} := range_coe @[simp] lemma coe_preimage_self (s : set α) : (coe : s → α) ⁻¹' s = univ := by rw [← preimage_range (coe : s → α), range_coe] lemma range_val_subtype {p : α → Prop} : range (subtype.val : subtype p → α) = {x | p x} := range_coe theorem coe_image_subset (s : set α) (t : set s) : coe '' t ⊆ s := λ x ⟨y, yt, yvaleq⟩, by rw ←yvaleq; exact y.property theorem coe_image_univ (s : set α) : (coe : s → α) '' set.univ = s := image_univ.trans range_coe @[simp] theorem image_preimage_coe (s t : set α) : (coe : s → α) '' (coe ⁻¹' t) = t ∩ s := image_preimage_eq_inter_range.trans $ congr_arg _ range_coe theorem image_preimage_val (s t : set α) : (subtype.val : s → α) '' (subtype.val ⁻¹' t) = t ∩ s := image_preimage_coe s t theorem preimage_coe_eq_preimage_coe_iff {s t u : set α} : ((coe : s → α) ⁻¹' t = coe ⁻¹' u) ↔ t ∩ s = u ∩ s := by rw [← image_preimage_coe, ← image_preimage_coe, coe_injective.image_injective.eq_iff] @[simp] theorem preimage_coe_inter_self (s t : set α) : (coe : s → α) ⁻¹' (t ∩ s) = coe ⁻¹' t := by rw [preimage_coe_eq_preimage_coe_iff, inter_assoc, inter_self] theorem preimage_val_eq_preimage_val_iff (s t u : set α) : ((subtype.val : s → α) ⁻¹' t = subtype.val ⁻¹' u) ↔ (t ∩ s = u ∩ s) := preimage_coe_eq_preimage_coe_iff lemma exists_set_subtype {t : set α} (p : set α → Prop) : (∃(s : set t), p (coe '' s)) ↔ ∃(s : set α), s ⊆ t ∧ p s := begin split, { rintro ⟨s, hs⟩, refine ⟨coe '' s, _, hs⟩, convert image_subset_range _ _, rw [range_coe] }, rintro ⟨s, hs₁, hs₂⟩, refine ⟨coe ⁻¹' s, _⟩, rw [image_preimage_eq_of_subset], exact hs₂, rw [range_coe], exact hs₁ end lemma preimage_coe_nonempty {s t : set α} : ((coe : s → α) ⁻¹' t).nonempty ↔ (s ∩ t).nonempty := by rw [inter_comm, ← image_preimage_coe, nonempty_image_iff] lemma preimage_coe_eq_empty {s t : set α} : (coe : s → α) ⁻¹' t = ∅ ↔ s ∩ t = ∅ := by simp only [← not_nonempty_iff_eq_empty, preimage_coe_nonempty] @[simp] lemma preimage_coe_compl (s : set α) : (coe : s → α) ⁻¹' sᶜ = ∅ := preimage_coe_eq_empty.2 (inter_compl_self s) @[simp] lemma preimage_coe_compl' (s : set α) : (coe : sᶜ → α) ⁻¹' s = ∅ := preimage_coe_eq_empty.2 (compl_inter_self s) end subtype namespace set /-! ### Lemmas about `inclusion`, the injection of subtypes induced by `⊆` -/ section inclusion variables {α : Type*} {s t u : set α} /-- `inclusion` is the "identity" function between two subsets `s` and `t`, where `s ⊆ t` -/ def inclusion (h : s ⊆ t) : s → t := λ x : s, (⟨x, h x.2⟩ : t) @[simp] lemma inclusion_self (x : s) : inclusion subset.rfl x = x := by { cases x, refl } lemma inclusion_eq_id (h : s ⊆ s) : inclusion h = id := funext inclusion_self @[simp] lemma inclusion_mk {h : s ⊆ t} (a : α) (ha : a ∈ s) : inclusion h ⟨a, ha⟩ = ⟨a, h ha⟩ := rfl lemma inclusion_right (h : s ⊆ t) (x : t) (m : (x : α) ∈ s) : inclusion h ⟨x, m⟩ = x := by { cases x, refl } @[simp] lemma inclusion_inclusion (hst : s ⊆ t) (htu : t ⊆ u) (x : s) : inclusion htu (inclusion hst x) = inclusion (hst.trans htu) x := by { cases x, refl } @[simp] lemma inclusion_comp_inclusion {α} {s t u : set α} (hst : s ⊆ t) (htu : t ⊆ u) : inclusion htu ∘ inclusion hst = inclusion (hst.trans htu) := funext (inclusion_inclusion hst htu) @[simp] lemma coe_inclusion (h : s ⊆ t) (x : s) : (inclusion h x : α) = (x : α) := rfl lemma inclusion_injective (h : s ⊆ t) : injective (inclusion h) | ⟨_, _⟩ ⟨_, _⟩ := subtype.ext_iff_val.2 ∘ subtype.ext_iff_val.1 @[simp] lemma range_inclusion (h : s ⊆ t) : range (inclusion h) = {x : t | (x:α) ∈ s} := by { ext ⟨x, hx⟩, simp [inclusion] } lemma eq_of_inclusion_surjective {s t : set α} {h : s ⊆ t} (h_surj : function.surjective (inclusion h)) : s = t := begin rw [← range_iff_surjective, range_inclusion, eq_univ_iff_forall] at h_surj, exact set.subset.antisymm h (λ x hx, h_surj ⟨x, hx⟩) end end inclusion /-! ### Injectivity and surjectivity lemmas for image and preimage -/ section image_preimage variables {α : Type u} {β : Type v} {f : α → β} @[simp] lemma preimage_injective : injective (preimage f) ↔ surjective f := begin refine ⟨λ h y, _, surjective.preimage_injective⟩, obtain ⟨x, hx⟩ : (f ⁻¹' {y}).nonempty, { rw [h.nonempty_apply_iff preimage_empty], apply singleton_nonempty }, exact ⟨x, hx⟩ end @[simp] lemma preimage_surjective : surjective (preimage f) ↔ injective f := begin refine ⟨λ h x x' hx, _, injective.preimage_surjective⟩, cases h {x} with s hs, have := mem_singleton x, rwa [← hs, mem_preimage, hx, ← mem_preimage, hs, mem_singleton_iff, eq_comm] at this end @[simp] lemma image_surjective : surjective (image f) ↔ surjective f := begin refine ⟨λ h y, _, surjective.image_surjective⟩, cases h {y} with s hs, have := mem_singleton y, rw [← hs] at this, rcases this with ⟨x, h1x, h2x⟩, exact ⟨x, h2x⟩ end @[simp] lemma image_injective : injective (image f) ↔ injective f := begin refine ⟨λ h x x' hx, _, injective.image_injective⟩, rw [← singleton_eq_singleton_iff], apply h, rw [image_singleton, image_singleton, hx] end lemma preimage_eq_iff_eq_image {f : α → β} (hf : bijective f) {s t} : f ⁻¹' s = t ↔ s = f '' t := by rw [← image_eq_image hf.1, hf.2.image_preimage] lemma eq_preimage_iff_image_eq {f : α → β} (hf : bijective f) {s t} : s = f ⁻¹' t ↔ f '' s = t := by rw [← image_eq_image hf.1, hf.2.image_preimage] end image_preimage /-! ### Images of binary and ternary functions This section is very similar to `order.filter.n_ary`. Please keep them in sync. -/ section n_ary_image variables {α α' β β' γ γ' δ δ' ε ε' : Type*} {f f' : α → β → γ} {g g' : α → β → γ → δ} variables {s s' : set α} {t t' : set β} {u u' : set γ} {a a' : α} {b b' : β} {c c' : γ} {d d' : δ} /-- The image of a binary function `f : α → β → γ` as a function `set α → set β → set γ`. Mathematically this should be thought of as the image of the corresponding function `α × β → γ`. -/ def image2 (f : α → β → γ) (s : set α) (t : set β) : set γ := {c | ∃ a b, a ∈ s ∧ b ∈ t ∧ f a b = c } lemma mem_image2_eq : c ∈ image2 f s t = ∃ a b, a ∈ s ∧ b ∈ t ∧ f a b = c := rfl @[simp] lemma mem_image2 : c ∈ image2 f s t ↔ ∃ a b, a ∈ s ∧ b ∈ t ∧ f a b = c := iff.rfl lemma mem_image2_of_mem (h1 : a ∈ s) (h2 : b ∈ t) : f a b ∈ image2 f s t := ⟨a, b, h1, h2, rfl⟩ lemma mem_image2_iff (hf : injective2 f) : f a b ∈ image2 f s t ↔ a ∈ s ∧ b ∈ t := ⟨ by { rintro ⟨a', b', ha', hb', h⟩, rcases hf h with ⟨rfl, rfl⟩, exact ⟨ha', hb'⟩ }, λ ⟨ha, hb⟩, mem_image2_of_mem ha hb⟩ /-- image2 is monotone with respect to `⊆`. -/ lemma image2_subset (hs : s ⊆ s') (ht : t ⊆ t') : image2 f s t ⊆ image2 f s' t' := by { rintro _ ⟨a, b, ha, hb, rfl⟩, exact mem_image2_of_mem (hs ha) (ht hb) } lemma image2_subset_left (ht : t ⊆ t') : image2 f s t ⊆ image2 f s t' := image2_subset subset.rfl ht lemma image2_subset_right (hs : s ⊆ s') : image2 f s t ⊆ image2 f s' t := image2_subset hs subset.rfl lemma image_subset_image2_left (hb : b ∈ t) : (λ a, f a b) '' s ⊆ image2 f s t := ball_image_of_ball $ λ a ha, mem_image2_of_mem ha hb lemma image_subset_image2_right (ha : a ∈ s) : f a '' t ⊆ image2 f s t := ball_image_of_ball $ λ b, mem_image2_of_mem ha lemma forall_image2_iff {p : γ → Prop} : (∀ z ∈ image2 f s t, p z) ↔ ∀ (x ∈ s) (y ∈ t), p (f x y) := ⟨λ h x hx y hy, h _ ⟨x, y, hx, hy, rfl⟩, λ h z ⟨x, y, hx, hy, hz⟩, hz ▸ h x hx y hy⟩ @[simp] lemma image2_subset_iff {u : set γ} : image2 f s t ⊆ u ↔ ∀ (x ∈ s) (y ∈ t), f x y ∈ u := forall_image2_iff lemma image2_union_left : image2 f (s ∪ s') t = image2 f s t ∪ image2 f s' t := begin ext c, split, { rintros ⟨a, b, h1a|h2a, hb, rfl⟩;[left, right]; exact ⟨_, _, ‹_›, ‹_›, rfl⟩ }, { rintro (⟨_, _, _, _, rfl⟩|⟨_, _, _, _, rfl⟩); refine ⟨_, _, _, ‹_›, rfl⟩; simp [mem_union, *] } end lemma image2_union_right : image2 f s (t ∪ t') = image2 f s t ∪ image2 f s t' := begin ext c, split, { rintros ⟨a, b, ha, h1b|h2b, rfl⟩;[left, right]; exact ⟨_, _, ‹_›, ‹_›, rfl⟩ }, { rintro (⟨_, _, _, _, rfl⟩|⟨_, _, _, _, rfl⟩); refine ⟨_, _, ‹_›, _, rfl⟩; simp [mem_union, *] } end @[simp] lemma image2_empty_left : image2 f ∅ t = ∅ := ext $ by simp @[simp] lemma image2_empty_right : image2 f s ∅ = ∅ := ext $ by simp lemma nonempty.image2 : s.nonempty → t.nonempty → (image2 f s t).nonempty := λ ⟨a, ha⟩ ⟨b, hb⟩, ⟨_, mem_image2_of_mem ha hb⟩ @[simp] lemma image2_nonempty_iff : (image2 f s t).nonempty ↔ s.nonempty ∧ t.nonempty := ⟨λ ⟨_, a, b, ha, hb, _⟩, ⟨⟨a, ha⟩, b, hb⟩, λ h, h.1.image2 h.2⟩ lemma nonempty.of_image2_left (h : (image2 f s t).nonempty) : s.nonempty := (image2_nonempty_iff.1 h).1 lemma nonempty.of_image2_right (h : (image2 f s t).nonempty) : t.nonempty := (image2_nonempty_iff.1 h).2 @[simp] lemma image2_eq_empty_iff : image2 f s t = ∅ ↔ s = ∅ ∨ t = ∅ := by simp_rw [←not_nonempty_iff_eq_empty, image2_nonempty_iff, not_and_distrib] lemma image2_inter_subset_left : image2 f (s ∩ s') t ⊆ image2 f s t ∩ image2 f s' t := by { rintro _ ⟨a, b, ⟨h1a, h2a⟩, hb, rfl⟩, split; exact ⟨_, _, ‹_›, ‹_›, rfl⟩ } lemma image2_inter_subset_right : image2 f s (t ∩ t') ⊆ image2 f s t ∩ image2 f s t' := by { rintro _ ⟨a, b, ha, ⟨h1b, h2b⟩, rfl⟩, split; exact ⟨_, _, ‹_›, ‹_›, rfl⟩ } @[simp] lemma image2_singleton_left : image2 f {a} t = f a '' t := ext $ λ x, by simp @[simp] lemma image2_singleton_right : image2 f s {b} = (λ a, f a b) '' s := ext $ λ x, by simp lemma image2_singleton : image2 f {a} {b} = {f a b} := by simp @[congr] lemma image2_congr (h : ∀ (a ∈ s) (b ∈ t), f a b = f' a b) : image2 f s t = image2 f' s t := by { ext, split; rintro ⟨a, b, ha, hb, rfl⟩; refine ⟨a, b, ha, hb, by rw h a ha b hb⟩ } /-- A common special case of `image2_congr` -/ lemma image2_congr' (h : ∀ a b, f a b = f' a b) : image2 f s t = image2 f' s t := image2_congr (λ a _ b _, h a b) /-- The image of a ternary function `f : α → β → γ → δ` as a function `set α → set β → set γ → set δ`. Mathematically this should be thought of as the image of the corresponding function `α × β × γ → δ`. -/ def image3 (g : α → β → γ → δ) (s : set α) (t : set β) (u : set γ) : set δ := {d | ∃ a b c, a ∈ s ∧ b ∈ t ∧ c ∈ u ∧ g a b c = d } @[simp] lemma mem_image3 : d ∈ image3 g s t u ↔ ∃ a b c, a ∈ s ∧ b ∈ t ∧ c ∈ u ∧ g a b c = d := iff.rfl lemma image3_mono (hs : s ⊆ s') (ht : t ⊆ t') (hu : u ⊆ u') : image3 g s t u ⊆ image3 g s' t' u' := λ x, Exists₃.imp $ λ a b c ⟨ha, hb, hc, hx⟩, ⟨hs ha, ht hb, hu hc, hx⟩ @[congr] lemma image3_congr (h : ∀ (a ∈ s) (b ∈ t) (c ∈ u), g a b c = g' a b c) : image3 g s t u = image3 g' s t u := by { ext x, split; rintro ⟨a, b, c, ha, hb, hc, rfl⟩; exact ⟨a, b, c, ha, hb, hc, by rw h a ha b hb c hc⟩ } /-- A common special case of `image3_congr` -/ lemma image3_congr' (h : ∀ a b c, g a b c = g' a b c) : image3 g s t u = image3 g' s t u := image3_congr (λ a _ b _ c _, h a b c) lemma image2_image2_left (f : δ → γ → ε) (g : α → β → δ) : image2 f (image2 g s t) u = image3 (λ a b c, f (g a b) c) s t u := begin ext, split, { rintro ⟨_, c, ⟨a, b, ha, hb, rfl⟩, hc, rfl⟩, refine ⟨a, b, c, ha, hb, hc, rfl⟩ }, { rintro ⟨a, b, c, ha, hb, hc, rfl⟩, refine ⟨_, c, ⟨a, b, ha, hb, rfl⟩, hc, rfl⟩ } end lemma image2_image2_right (f : α → δ → ε) (g : β → γ → δ) : image2 f s (image2 g t u) = image3 (λ a b c, f a (g b c)) s t u := begin ext, split, { rintro ⟨a, _, ha, ⟨b, c, hb, hc, rfl⟩, rfl⟩, refine ⟨a, b, c, ha, hb, hc, rfl⟩ }, { rintro ⟨a, b, c, ha, hb, hc, rfl⟩, refine ⟨a, _, ha, ⟨b, c, hb, hc, rfl⟩, rfl⟩ } end lemma image_image2 (f : α → β → γ) (g : γ → δ) : g '' image2 f s t = image2 (λ a b, g (f a b)) s t := begin ext, split, { rintro ⟨_, ⟨a, b, ha, hb, rfl⟩, rfl⟩, refine ⟨a, b, ha, hb, rfl⟩ }, { rintro ⟨a, b, ha, hb, rfl⟩, refine ⟨_, ⟨a, b, ha, hb, rfl⟩, rfl⟩ } end lemma image2_image_left (f : γ → β → δ) (g : α → γ) : image2 f (g '' s) t = image2 (λ a b, f (g a) b) s t := begin ext, split, { rintro ⟨_, b, ⟨a, ha, rfl⟩, hb, rfl⟩, refine ⟨a, b, ha, hb, rfl⟩ }, { rintro ⟨a, b, ha, hb, rfl⟩, refine ⟨_, b, ⟨a, ha, rfl⟩, hb, rfl⟩ } end lemma image2_image_right (f : α → γ → δ) (g : β → γ) : image2 f s (g '' t) = image2 (λ a b, f a (g b)) s t := begin ext, split, { rintro ⟨a, _, ha, ⟨b, hb, rfl⟩, rfl⟩, refine ⟨a, b, ha, hb, rfl⟩ }, { rintro ⟨a, b, ha, hb, rfl⟩, refine ⟨a, _, ha, ⟨b, hb, rfl⟩, rfl⟩ } end lemma image2_swap (f : α → β → γ) (s : set α) (t : set β) : image2 f s t = image2 (λ a b, f b a) t s := by { ext, split; rintro ⟨a, b, ha, hb, rfl⟩; refine ⟨b, a, hb, ha, rfl⟩ } @[simp] lemma image2_left (h : t.nonempty) : image2 (λ x y, x) s t = s := by simp [nonempty_def.mp h, ext_iff] @[simp] lemma image2_right (h : s.nonempty) : image2 (λ x y, y) s t = t := by simp [nonempty_def.mp h, ext_iff] lemma image2_assoc {f : δ → γ → ε} {g : α → β → δ} {f' : α → ε' → ε} {g' : β → γ → ε'} (h_assoc : ∀ a b c, f (g a b) c = f' a (g' b c)) : image2 f (image2 g s t) u = image2 f' s (image2 g' t u) := by simp only [image2_image2_left, image2_image2_right, h_assoc] lemma image2_comm {g : β → α → γ} (h_comm : ∀ a b, f a b = g b a) : image2 f s t = image2 g t s := (image2_swap _ _ _).trans $ by simp_rw h_comm lemma image2_left_comm {f : α → δ → ε} {g : β → γ → δ} {f' : α → γ → δ'} {g' : β → δ' → ε} (h_left_comm : ∀ a b c, f a (g b c) = g' b (f' a c)) : image2 f s (image2 g t u) = image2 g' t (image2 f' s u) := by { rw [image2_swap f', image2_swap f], exact image2_assoc (λ _ _ _, h_left_comm _ _ _) } lemma image2_right_comm {f : δ → γ → ε} {g : α → β → δ} {f' : α → γ → δ'} {g' : δ' → β → ε} (h_right_comm : ∀ a b c, f (g a b) c = g' (f' a c) b) : image2 f (image2 g s t) u = image2 g' (image2 f' s u) t := by { rw [image2_swap g, image2_swap g'], exact image2_assoc (λ _ _ _, h_right_comm _ _ _) } lemma image_image2_distrib {g : γ → δ} {f' : α' → β' → δ} {g₁ : α → α'} {g₂ : β → β'} (h_distrib : ∀ a b, g (f a b) = f' (g₁ a) (g₂ b)) : (image2 f s t).image g = image2 f' (s.image g₁) (t.image g₂) := by simp_rw [image_image2, image2_image_left, image2_image_right, h_distrib] /-- Symmetric of `set.image2_image_left_comm`. -/ lemma image_image2_distrib_left {g : γ → δ} {f' : α' → β → δ} {g' : α → α'} (h_distrib : ∀ a b, g (f a b) = f' (g' a) b) : (image2 f s t).image g = image2 f' (s.image g') t := (image_image2_distrib h_distrib).trans $ by rw image_id' /-- Symmetric of `set.image_image2_right_comm`. -/ lemma image_image2_distrib_right {g : γ → δ} {f' : α → β' → δ} {g' : β → β'} (h_distrib : ∀ a b, g (f a b) = f' a (g' b)) : (image2 f s t).image g = image2 f' s (t.image g') := (image_image2_distrib h_distrib).trans $ by rw image_id' /-- Symmetric of `set.image_image2_distrib_left`. -/ lemma image2_image_left_comm {f : α' → β → γ} {g : α → α'} {f' : α → β → δ} {g' : δ → γ} (h_left_comm : ∀ a b, f (g a) b = g' (f' a b)) : image2 f (s.image g) t = (image2 f' s t).image g' := (image_image2_distrib_left $ λ a b, (h_left_comm a b).symm).symm /-- Symmetric of `set.image_image2_distrib_right`. -/ lemma image_image2_right_comm {f : α → β' → γ} {g : β → β'} {f' : α → β → δ} {g' : δ → γ} (h_right_comm : ∀ a b, f a (g b) = g' (f' a b)) : image2 f s (t.image g) = (image2 f' s t).image g' := (image_image2_distrib_right $ λ a b, (h_right_comm a b).symm).symm /-- The other direction does not hold because of the `s`-`s` cross terms on the RHS. -/ lemma image2_distrib_subset_left {f : α → δ → ε} {g : β → γ → δ} {f₁ : α → β → β'} {f₂ : α → γ → γ'} {g' : β' → γ' → ε} (h_distrib : ∀ a b c, f a (g b c) = g' (f₁ a b) (f₂ a c)) : image2 f s (image2 g t u) ⊆ image2 g' (image2 f₁ s t) (image2 f₂ s u) := begin rintro _ ⟨a, _, ha, ⟨b, c, hb, hc, rfl⟩, rfl⟩, rw h_distrib, exact mem_image2_of_mem (mem_image2_of_mem ha hb) (mem_image2_of_mem ha hc), end /-- The other direction does not hold because of the `u`-`u` cross terms on the RHS. -/ lemma image2_distrib_subset_right {f : δ → γ → ε} {g : α → β → δ} {f₁ : α → γ → α'} {f₂ : β → γ → β'} {g' : α' → β' → ε} (h_distrib : ∀ a b c, f (g a b) c = g' (f₁ a c) (f₂ b c)) : image2 f (image2 g s t) u ⊆ image2 g' (image2 f₁ s u) (image2 f₂ t u) := begin rintro _ ⟨_, c, ⟨a, b, ha, hb, rfl⟩, hc, rfl⟩, rw h_distrib, exact mem_image2_of_mem (mem_image2_of_mem ha hc) (mem_image2_of_mem hb hc), end lemma image_image2_antidistrib {g : γ → δ} {f' : β' → α' → δ} {g₁ : β → β'} {g₂ : α → α'} (h_antidistrib : ∀ a b, g (f a b) = f' (g₁ b) (g₂ a)) : (image2 f s t).image g = image2 f' (t.image g₁) (s.image g₂) := by { rw image2_swap f, exact image_image2_distrib (λ _ _, h_antidistrib _ _) } /-- Symmetric of `set.image2_image_left_anticomm`. -/ lemma image_image2_antidistrib_left {g : γ → δ} {f' : β' → α → δ} {g' : β → β'} (h_antidistrib : ∀ a b, g (f a b) = f' (g' b) a) : (image2 f s t).image g = image2 f' (t.image g') s := (image_image2_antidistrib h_antidistrib).trans $ by rw image_id' /-- Symmetric of `set.image_image2_right_anticomm`. -/ lemma image_image2_antidistrib_right {g : γ → δ} {f' : β → α' → δ} {g' : α → α'} (h_antidistrib : ∀ a b, g (f a b) = f' b (g' a)) : (image2 f s t).image g = image2 f' t (s.image g') := (image_image2_antidistrib h_antidistrib).trans $ by rw image_id' /-- Symmetric of `set.image_image2_antidistrib_left`. -/ lemma image2_image_left_anticomm {f : α' → β → γ} {g : α → α'} {f' : β → α → δ} {g' : δ → γ} (h_left_anticomm : ∀ a b, f (g a) b = g' (f' b a)) : image2 f (s.image g) t = (image2 f' t s).image g' := (image_image2_antidistrib_left $ λ a b, (h_left_anticomm b a).symm).symm /-- Symmetric of `set.image_image2_antidistrib_right`. -/ lemma image_image2_right_anticomm {f : α → β' → γ} {g : β → β'} {f' : β → α → δ} {g' : δ → γ} (h_right_anticomm : ∀ a b, f a (g b) = g' (f' b a)) : image2 f s (t.image g) = (image2 f' t s).image g' := (image_image2_antidistrib_right $ λ a b, (h_right_anticomm b a).symm).symm end n_ary_image 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 lemma mem_iff_nonempty {α : Type*} [subsingleton α] {s : set α} {x : α} : x ∈ s ↔ s.nonempty := ⟨λ hx, ⟨x, hx⟩, λ ⟨y, hy⟩, subsingleton.elim y x ▸ hy⟩ end subsingleton /-! ### Decidability instances for sets -/ namespace set variables {α : Type u} (s t : set α) (a : α) instance decidable_sdiff [decidable (a ∈ s)] [decidable (a ∈ t)] : decidable (a ∈ s \ t) := (by apply_instance : decidable (a ∈ s ∧ a ∉ t)) instance decidable_inter [decidable (a ∈ s)] [decidable (a ∈ t)] : decidable (a ∈ s ∩ t) := (by apply_instance : decidable (a ∈ s ∧ a ∈ t)) instance decidable_union [decidable (a ∈ s)] [decidable (a ∈ t)] : decidable (a ∈ s ∪ t) := (by apply_instance : decidable (a ∈ s ∨ a ∈ t)) instance decidable_compl [decidable (a ∈ s)] : decidable (a ∈ sᶜ) := (by apply_instance : decidable (a ∉ s)) instance decidable_emptyset : decidable_pred (∈ (∅ : set α)) := λ _, decidable.is_false (by simp) instance decidable_univ : decidable_pred (∈ (set.univ : set α)) := λ _, decidable.is_true (by simp) instance decidable_set_of (p : α → Prop) [decidable (p a)] : decidable (a ∈ {a | p a}) := by assumption end set
739aa61fc2e1a3f92f0960f014e5958f01b5d8c9
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/measure_theory/giry_monad.lean
05576f44bb97d94acdf23ffb29adb6b189ec2eb0
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
6,505
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.measure_theory.integration import Mathlib.PostPort universes u_1 u_2 u_3 namespace Mathlib /-! # The Giry monad Let X be a measurable space. The collection of all measures on X again forms a measurable space. This construction forms a monad on measurable spaces and measurable functions, called the Giry monad. Note that most sources use the term "Giry monad" for the restriction to *probability* measures. Here we include all measures on X. See also `measure_theory/category/Meas.lean`, containing an upgrade of the type-level monad to an honest monad of the functor `Measure : Meas ⥤ Meas`. ## References * <https://ncatlab.org/nlab/show/Giry+monad> ## Tags giry monad -/ namespace measure_theory namespace measure /-- Measurability structure on `measure`: Measures are measurable w.r.t. all projections -/ protected instance measurable_space {α : Type u_1} [measurable_space α] : measurable_space (measure α) := supr fun (s : set α) => supr fun (hs : is_measurable s) => measurable_space.comap (fun (μ : measure α) => coe_fn μ s) (borel ennreal) theorem measurable_coe {α : Type u_1} [measurable_space α] {s : set α} (hs : is_measurable s) : measurable fun (μ : measure α) => coe_fn μ s := measurable.of_comap_le (le_supr_of_le s (le_supr_of_le hs (le_refl (measurable_space.comap (fun (μ : measure α) => coe_fn μ s) ennreal.measurable_space)))) theorem measurable_of_measurable_coe {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] (f : β → measure α) (h : ∀ (s : set α), is_measurable s → measurable fun (b : β) => coe_fn (f b) s) : measurable f := sorry theorem measurable_measure {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] {μ : α → measure β} : measurable μ ↔ ∀ (s : set β), is_measurable s → measurable fun (b : α) => coe_fn (μ b) s := { mp := fun (hμ : measurable μ) (s : set β) (hs : is_measurable s) => measurable.comp (measurable_coe hs) hμ, mpr := measurable_of_measurable_coe μ } theorem measurable_map {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] (f : α → β) (hf : measurable f) : measurable fun (μ : measure α) => coe_fn (map f) μ := sorry theorem measurable_dirac {α : Type u_1} [measurable_space α] : measurable dirac := sorry theorem measurable_lintegral {α : Type u_1} [measurable_space α] {f : α → ennreal} (hf : measurable f) : measurable fun (μ : measure α) => lintegral μ fun (x : α) => f x := sorry /-- Monadic join on `measure` in the category of measurable spaces and measurable functions. -/ def join {α : Type u_1} [measurable_space α] (m : measure (measure α)) : measure α := of_measurable (fun (s : set α) (hs : is_measurable s) => lintegral m fun (μ : measure α) => coe_fn μ s) sorry sorry @[simp] theorem join_apply {α : Type u_1} [measurable_space α] {m : measure (measure α)} {s : set α} : is_measurable s → coe_fn (join m) s = lintegral m fun (μ : measure α) => coe_fn μ s := of_measurable_apply theorem measurable_join {α : Type u_1} [measurable_space α] : measurable join := sorry theorem lintegral_join {α : Type u_1} [measurable_space α] {m : measure (measure α)} {f : α → ennreal} (hf : measurable f) : (lintegral (join m) fun (x : α) => f x) = lintegral m fun (μ : measure α) => lintegral μ fun (x : α) => f x := sorry /-- Monadic bind on `measure`, only works in the category of measurable spaces and measurable functions. When the function `f` is not measurable the result is not well defined. -/ def bind {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] (m : measure α) (f : α → measure β) : measure β := join (coe_fn (map f) m) @[simp] theorem bind_apply {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] {m : measure α} {f : α → measure β} {s : set β} (hs : is_measurable s) (hf : measurable f) : coe_fn (bind m f) s = lintegral m fun (a : α) => coe_fn (f a) s := sorry theorem measurable_bind' {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] {g : α → measure β} (hg : measurable g) : measurable fun (m : measure α) => bind m g := measurable.comp measurable_join (measurable_map g hg) theorem lintegral_bind {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] {m : measure α} {μ : α → measure β} {f : β → ennreal} (hμ : measurable μ) (hf : measurable f) : (lintegral (bind m μ) fun (x : β) => f x) = lintegral m fun (a : α) => lintegral (μ a) fun (x : β) => f x := Eq.trans (lintegral_join hf) (lintegral_map (measurable_lintegral hf) hμ) theorem bind_bind {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] {γ : Type u_3} [measurable_space γ] {m : measure α} {f : α → measure β} {g : β → measure γ} (hf : measurable f) (hg : measurable g) : bind (bind m f) g = bind m fun (a : α) => bind (f a) g := sorry theorem bind_dirac {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] {f : α → measure β} (hf : measurable f) (a : α) : bind (dirac a) f = f a := sorry theorem dirac_bind {α : Type u_1} [measurable_space α] {m : measure α} : bind m dirac = m := sorry theorem join_eq_bind {α : Type u_1} [measurable_space α] (μ : measure (measure α)) : join μ = bind μ id := eq.mpr (id (Eq._oldrec (Eq.refl (join μ = bind μ id)) (bind.equations._eqn_1 μ id))) (eq.mpr (id (Eq._oldrec (Eq.refl (join μ = join (coe_fn (map id) μ))) map_id)) (Eq.refl (join μ))) theorem join_map_map {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] {f : α → β} (hf : measurable f) (μ : measure (measure α)) : join (coe_fn (map ⇑(map f)) μ) = coe_fn (map f) (join μ) := sorry theorem join_map_join {α : Type u_1} [measurable_space α] (μ : measure (measure (measure α))) : join (coe_fn (map join) μ) = join (join μ) := sorry theorem join_map_dirac {α : Type u_1} [measurable_space α] (μ : measure α) : join (coe_fn (map dirac) μ) = μ := dirac_bind theorem join_dirac {α : Type u_1} [measurable_space α] (μ : measure α) : join (dirac μ) = μ := Eq.trans (join_eq_bind (dirac μ)) (bind_dirac measurable_id μ)
dc27239086ccb44aabf09330ec0402b885052307
618003631150032a5676f229d13a079ac875ff77
/src/data/complex/exponential.lean
5b10a7774540b474ac692f9c73a3fc8d51b12b72
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
47,723
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir -/ import algebra.geom_sum import data.nat.choose import data.complex.basic local notation `abs'` := _root_.abs open is_absolute_value open_locale classical section open real is_absolute_value finset lemma forall_ge_le_of_forall_le_succ {α : Type*} [preorder α] (f : ℕ → α) {m : ℕ} (h : ∀ n ≥ m, f n.succ ≤ f n) : ∀ {l}, ∀ k ≥ m, k ≤ l → f l ≤ f k := begin assume l k hkm hkl, generalize hp : l - k = p, have : l = k + p := add_comm p k ▸ (nat.sub_eq_iff_eq_add hkl).1 hp, subst this, clear hkl hp, induction p with p ih, { simp }, { exact le_trans (h _ (le_trans hkm (nat.le_add_right _ _))) ih } end variables {α : Type*} {β : Type*} [ring β] [discrete_linear_ordered_field α] [archimedean α] {abv : β → α} [is_absolute_value abv] lemma is_cau_of_decreasing_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, abs (f n) ≤ a) (hnm : ∀ n ≥ m, f n.succ ≤ f n) : is_cau_seq abs f := λ ε ε0, let ⟨k, hk⟩ := archimedean.arch a ε0 in have h : ∃ l, ∀ n ≥ m, a - l •ℕ ε < f n := ⟨k + k + 1, λ n hnm, lt_of_lt_of_le (show a - (k + (k + 1)) •ℕ ε < -abs (f n), from lt_neg.1 $ lt_of_le_of_lt (ham n hnm) (begin rw [neg_sub, lt_sub_iff_add_lt, add_nsmul], exact add_lt_add_of_le_of_lt hk (lt_of_le_of_lt hk (lt_add_of_pos_left _ ε0)), end)) (neg_le.2 $ (abs_neg (f n)) ▸ le_abs_self _)⟩, let l := nat.find h in have hl : ∀ (n : ℕ), n ≥ m → f n > a - l •ℕ ε := nat.find_spec h, have hl0 : l ≠ 0 := λ hl0, not_lt_of_ge (ham m (le_refl _)) (lt_of_lt_of_le (by have := hl m (le_refl m); simpa [hl0] using this) (le_abs_self (f m))), begin cases classical.not_forall.1 (nat.find_min h (nat.pred_lt hl0)) with i hi, rw [not_imp, not_lt] at hi, existsi i, assume j hj, have hfij : f j ≤ f i := forall_ge_le_of_forall_le_succ f hnm _ hi.1 hj, rw [abs_of_nonpos (sub_nonpos.2 hfij), neg_sub, sub_lt_iff_lt_add'], exact calc f i ≤ a - (nat.pred l) •ℕ ε : hi.2 ... = a - l •ℕ ε + ε : by conv {to_rhs, rw [← nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero hl0), succ_nsmul', sub_add, add_sub_cancel] } ... < f j + ε : add_lt_add_right (hl j (le_trans hi.1 hj)) _ end lemma is_cau_of_mono_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, abs (f n) ≤ a) (hnm : ∀ n ≥ m, f n ≤ f n.succ) : is_cau_seq abs f := begin refine @eq.rec_on (ℕ → α) _ (is_cau_seq abs) _ _ (-⟨_, @is_cau_of_decreasing_bounded _ _ _ (λ n, -f n) a m (by simpa) (by simpa)⟩ : cau_seq α abs).2, ext, exact neg_neg _ end lemma is_cau_series_of_abv_le_cau {f : ℕ → β} {g : ℕ → α} (n : ℕ) : (∀ m, n ≤ m → abv (f m) ≤ g m) → is_cau_seq abs (λ n, (range n).sum g) → is_cau_seq abv (λ n, (range n).sum f) := begin assume hm hg ε ε0, cases hg (ε / 2) (div_pos ε0 (by norm_num)) with i hi, existsi max n i, assume j ji, have hi₁ := hi j (le_trans (le_max_right n i) ji), have hi₂ := hi (max n i) (le_max_right n i), have sub_le := abs_sub_le ((range j).sum g) ((range i).sum g) ((range (max n i)).sum g), have := add_lt_add hi₁ hi₂, rw [abs_sub ((range (max n i)).sum g), add_halves ε] at this, refine lt_of_le_of_lt (le_trans (le_trans _ (le_abs_self _)) sub_le) this, generalize hk : j - max n i = k, clear this hi₂ hi₁ hi ε0 ε hg sub_le, rw nat.sub_eq_iff_eq_add ji at hk, rw hk, clear hk ji j, induction k with k' hi, { simp [abv_zero abv] }, { dsimp at *, simp only [nat.succ_add, sum_range_succ, sub_eq_add_neg, add_assoc], refine le_trans (abv_add _ _ _) _, exact add_le_add (hm _ (le_add_of_nonneg_of_le (nat.zero_le _) (le_max_left _ _))) hi }, end lemma is_cau_series_of_abv_cau {f : ℕ → β} : is_cau_seq abs (λ m, (range m).sum (λ n, abv (f n))) → is_cau_seq abv (λ m, (range m).sum f) := is_cau_series_of_abv_le_cau 0 (λ n h, le_refl _) lemma is_cau_geo_series {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] (x : β) (hx1 : abv x < 1) : is_cau_seq abv (λ n, (range n).sum (λ m, x ^ m)) := have hx1' : abv x ≠ 1 := λ h, by simpa [h, lt_irrefl] using hx1, is_cau_series_of_abv_cau begin simp only [abv_pow abv] {eta := ff}, have : (λ (m : ℕ), (range m).sum (λ n, (abv x) ^ n)) = λ m, geom_series (abv x) m := rfl, simp only [this, geom_sum hx1'] {eta := ff}, conv in (_ / _) { rw [← neg_div_neg_eq, neg_sub, neg_sub] }, refine @is_cau_of_mono_bounded _ _ _ _ ((1 : α) / (1 - abv x)) 0 _ _, { assume n hn, rw abs_of_nonneg, refine div_le_div_of_le_of_pos (sub_le_self _ (abv_pow abv x n ▸ abv_nonneg _ _)) (sub_pos.2 hx1), refine div_nonneg (sub_nonneg.2 _) (sub_pos.2 hx1), clear hn, induction n with n ih, { simp }, { rw [_root_.pow_succ, ← one_mul (1 : α)], refine mul_le_mul (le_of_lt hx1) ih (abv_pow abv x n ▸ abv_nonneg _ _) (by norm_num) } }, { assume n hn, refine div_le_div_of_le_of_pos (sub_le_sub_left _ _) (sub_pos.2 hx1), rw [← one_mul (_ ^ n), _root_.pow_succ], exact mul_le_mul_of_nonneg_right (le_of_lt hx1) (pow_nonneg (abv_nonneg _ _) _) } end lemma is_cau_geo_series_const (a : α) {x : α} (hx1 : abs x < 1) : is_cau_seq abs (λ m, (range m).sum (λ n, a * x ^ n)) := have is_cau_seq abs (λ m, a * (range m).sum (λ n, x ^ n)) := (cau_seq.const abs a * ⟨_, is_cau_geo_series x hx1⟩).2, by simpa only [mul_sum] lemma series_ratio_test {f : ℕ → β} (n : ℕ) (r : α) (hr0 : 0 ≤ r) (hr1 : r < 1) (h : ∀ m, n ≤ m → abv (f m.succ) ≤ r * abv (f m)) : is_cau_seq abv (λ m, (range m).sum f) := have har1 : abs r < 1, by rwa abs_of_nonneg hr0, begin refine is_cau_series_of_abv_le_cau n.succ _ (is_cau_geo_series_const (abv (f n.succ) * r⁻¹ ^ n.succ) har1), assume m hmn, cases classical.em (r = 0) with r_zero r_ne_zero, { have m_pos := lt_of_lt_of_le (nat.succ_pos n) hmn, have := h m.pred (nat.le_of_succ_le_succ (by rwa [nat.succ_pred_eq_of_pos m_pos])), simpa [r_zero, nat.succ_pred_eq_of_pos m_pos, pow_succ] }, generalize hk : m - n.succ = k, have r_pos : 0 < r := lt_of_le_of_ne hr0 (ne.symm r_ne_zero), replace hk : m = k + n.succ := (nat.sub_eq_iff_eq_add hmn).1 hk, induction k with k ih generalizing m n, { rw [hk, zero_add, mul_right_comm, inv_pow' _ _, ← div_eq_mul_inv, mul_div_cancel], exact (ne_of_lt (pow_pos r_pos _)).symm }, { have kn : k + n.succ ≥ n.succ, by rw ← zero_add n.succ; exact add_le_add (zero_le _) (by simp), rw [hk, nat.succ_add, pow_succ' r, ← mul_assoc], exact le_trans (by rw mul_comm; exact h _ (nat.le_of_succ_le kn)) (mul_le_mul_of_nonneg_right (ih (k + n.succ) n h kn rfl) hr0) } end lemma sum_range_diag_flip {α : Type*} [add_comm_monoid α] (n : ℕ) (f : ℕ → ℕ → α) : (range n).sum (λ m, (range (m + 1)).sum (λ k, f k (m - k))) = (range n).sum (λ m, (range (n - m)).sum (f m)) := have h₁ : ((range n).sigma (range ∘ nat.succ)).sum (λ (a : Σ m, ℕ), f (a.2) (a.1 - a.2)) = (range n).sum (λ m, (range (m + 1)).sum (λ k, f k (m - k))) := sum_sigma, have h₂ : ((range n).sigma (λ m, range (n - m))).sum (λ a : Σ (m : ℕ), ℕ, f (a.1) (a.2)) = (range n).sum (λ m, (range (n - m)).sum (f m)) := sum_sigma, h₁ ▸ h₂ ▸ sum_bij (λ a _, ⟨a.2, a.1 - a.2⟩) (λ a ha, have h₁ : a.1 < n := mem_range.1 (mem_sigma.1 ha).1, have h₂ : a.2 < nat.succ a.1 := mem_range.1 (mem_sigma.1 ha).2, mem_sigma.2 ⟨mem_range.2 (lt_of_lt_of_le h₂ h₁), mem_range.2 ((nat.sub_lt_sub_right_iff (nat.le_of_lt_succ h₂)).2 h₁)⟩) (λ _ _, rfl) (λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩ ha hb h, have ha : a₁ < n ∧ a₂ ≤ a₁ := ⟨mem_range.1 (mem_sigma.1 ha).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 ha).2)⟩, have hb : b₁ < n ∧ b₂ ≤ b₁ := ⟨mem_range.1 (mem_sigma.1 hb).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 hb).2)⟩, have h : a₂ = b₂ ∧ _ := sigma.mk.inj h, have h' : a₁ = b₁ - b₂ + a₂ := (nat.sub_eq_iff_eq_add ha.2).1 (eq_of_heq h.2), sigma.mk.inj_iff.2 ⟨nat.sub_add_cancel hb.2 ▸ h'.symm ▸ h.1 ▸ rfl, (heq_of_eq h.1)⟩) (λ ⟨a₁, a₂⟩ ha, have ha : a₁ < n ∧ a₂ < n - a₁ := ⟨mem_range.1 (mem_sigma.1 ha).1, (mem_range.1 (mem_sigma.1 ha).2)⟩, ⟨⟨a₂ + a₁, a₁⟩, ⟨mem_sigma.2 ⟨mem_range.2 (nat.lt_sub_right_iff_add_lt.1 ha.2), mem_range.2 (nat.lt_succ_of_le (nat.le_add_left _ _))⟩, sigma.mk.inj_iff.2 ⟨rfl, heq_of_eq (nat.add_sub_cancel _ _).symm⟩⟩⟩) lemma abv_sum_le_sum_abv {γ : Type*} (f : γ → β) (s : finset γ) : abv (s.sum f) ≤ s.sum (abv ∘ f) := by haveI := classical.dec_eq γ; exact finset.induction_on s (by simp [abv_zero abv]) (λ a s has ih, by rw [sum_insert has, sum_insert has]; exact le_trans (abv_add abv _ _) (add_le_add_left ih _)) lemma sum_range_sub_sum_range {α : Type*} [add_comm_group α] {f : ℕ → α} {n m : ℕ} (hnm : n ≤ m) : (range m).sum f - (range n).sum f = ((range m).filter (λ k, n ≤ k)).sum f := begin rw [← sum_sdiff (@filter_subset _ (λ k, n ≤ k) _ (range m)), sub_eq_iff_eq_add, ← eq_sub_iff_add_eq, add_sub_cancel'], refine finset.sum_congr (finset.ext.2 $ λ a, ⟨λ h, by simp at *; finish, λ h, have ham : a < m := lt_of_lt_of_le (mem_range.1 h) hnm, by simp * at *⟩) (λ _ _, rfl), end lemma cauchy_product {a b : ℕ → β} (ha : is_cau_seq abs (λ m, (range m).sum (λ n, abv (a n)))) (hb : is_cau_seq abv (λ m, (range m).sum b)) (ε : α) (ε0 : 0 < ε) : ∃ i : ℕ, ∀ j ≥ i, abv ((range j).sum a * (range j).sum b - (range j).sum (λ n, (range (n + 1)).sum (λ m, a m * b (n - m)))) < ε := let ⟨Q, hQ⟩ := cau_seq.bounded ⟨_, hb⟩ in let ⟨P, hP⟩ := cau_seq.bounded ⟨_, ha⟩ in have hP0 : 0 < P, from lt_of_le_of_lt (abs_nonneg _) (hP 0), have hPε0 : 0 < ε / (2 * P), from div_pos ε0 (mul_pos (show (2 : α) > 0, from by norm_num) hP0), let ⟨N, hN⟩ := cau_seq.cauchy₂ ⟨_, hb⟩ hPε0 in have hQε0 : 0 < ε / (4 * Q), from div_pos ε0 (mul_pos (show (0 : α) < 4, by norm_num) (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))), let ⟨M, hM⟩ := cau_seq.cauchy₂ ⟨_, ha⟩ hQε0 in ⟨2 * (max N M + 1), λ K hK, have h₁ : (range K).sum (λ m, (range (m + 1)).sum (λ k, a k * b (m - k))) = (range K).sum (λ m, (range (K - m)).sum (λ n, a m * b n)), by simpa using sum_range_diag_flip K (λ m n, a m * b n), have h₂ : (λ i, (range (K - i)).sum (λ k, a i * b k)) = (λ i, a i * (range (K - i)).sum b), by simp [finset.mul_sum], have h₃ : (range K).sum (λ i, a i * (range (K - i)).sum b) = (range K).sum (λ i, a i * ((range (K - i)).sum b - (range K).sum b)) + (range K).sum (λ i, a i * (range K).sum b), by rw ← sum_add_distrib; simp [(mul_add _ _ _).symm], have two_mul_two : (4 : α) = 2 * 2, by norm_num, have hQ0 : Q ≠ 0, from λ h, by simpa [h, lt_irrefl] using hQε0, have h2Q0 : 2 * Q ≠ 0, from mul_ne_zero two_ne_zero hQ0, have hε : ε / (2 * P) * P + ε / (4 * Q) * (2 * Q) = ε, by rw [← div_div_eq_div_mul, div_mul_cancel _ (ne.symm (ne_of_lt hP0)), two_mul_two, mul_assoc, ← div_div_eq_div_mul, div_mul_cancel _ h2Q0, add_halves], have hNMK : max N M + 1 < K, from lt_of_lt_of_le (by rw two_mul; exact lt_add_of_pos_left _ (nat.succ_pos _)) hK, have hKN : N < K, from calc N ≤ max N M : le_max_left _ _ ... < max N M + 1 : nat.lt_succ_self _ ... < K : hNMK, have hsumlesum : (range (max N M + 1)).sum (λ i, abv (a i) * abv ((range (K - i)).sum b - (range K).sum b)) ≤ (range (max N M + 1)).sum (λ i, abv (a i) * (ε / (2 * P))), from sum_le_sum (λ m hmJ, mul_le_mul_of_nonneg_left (le_of_lt (hN (K - m) K (nat.le_sub_left_of_add_le (le_trans (by rw two_mul; exact add_le_add (le_of_lt (mem_range.1 hmJ)) (le_trans (le_max_left _ _) (le_of_lt (lt_add_one _)))) hK)) (le_of_lt hKN))) (abv_nonneg abv _)), have hsumltP : (range (max N M + 1)).sum (λ n, abv (a n)) < P := calc (range (max N M + 1)).sum (λ n, abv (a n)) = abs ((range (max N M + 1)).sum (λ n, abv (a n))) : eq.symm (abs_of_nonneg (sum_nonneg (λ x h, abv_nonneg abv (a x)))) ... < P : hP (max N M + 1), begin rw [h₁, h₂, h₃, sum_mul, ← sub_sub, sub_right_comm, sub_self, zero_sub, abv_neg abv], refine lt_of_le_of_lt (abv_sum_le_sum_abv _ _) _, suffices : (range (max N M + 1)).sum (λ (i : ℕ), abv (a i) * abv ((range (K - i)).sum b - (range K).sum b)) + ((range K).sum (λ (i : ℕ), abv (a i) * abv ((range (K - i)).sum b - (range K).sum b)) -(range (max N M + 1)).sum (λ (i : ℕ), abv (a i) * abv ((range (K - i)).sum b - (range K).sum b))) < ε / (2 * P) * P + ε / (4 * Q) * (2 * Q), { rw hε at this, simpa [abv_mul abv] }, refine add_lt_add (lt_of_le_of_lt hsumlesum (by rw [← sum_mul, mul_comm]; exact (mul_lt_mul_left hPε0).mpr hsumltP)) _, rw sum_range_sub_sum_range (le_of_lt hNMK), exact calc ((range K).filter (λ k, max N M + 1 ≤ k)).sum (λ i, abv (a i) * abv ((range (K - i)).sum b - (range K).sum b)) ≤ ((range K).filter (λ k, max N M + 1 ≤ k)).sum (λ i, abv (a i) * (2 * Q)) : sum_le_sum (λ n hn, begin refine mul_le_mul_of_nonneg_left _ (abv_nonneg _ _), rw sub_eq_add_neg, refine le_trans (abv_add _ _ _) _, rw [two_mul, abv_neg abv], exact add_le_add (le_of_lt (hQ _)) (le_of_lt (hQ _)), end) ... < ε / (4 * Q) * (2 * Q) : by rw [← sum_mul, ← sum_range_sub_sum_range (le_of_lt hNMK)]; refine (mul_lt_mul_right $ by rw two_mul; exact add_pos (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0)) (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))).2 (lt_of_le_of_lt (le_abs_self _) (hM _ _ (le_trans (nat.le_succ_of_le (le_max_right _ _)) (le_of_lt hNMK)) (nat.le_succ_of_le (le_max_right _ _)))) end⟩ end open finset open cau_seq namespace complex lemma is_cau_abs_exp (z : ℂ) : is_cau_seq _root_.abs (λ n, (range n).sum (λ m, abs (z ^ m / nat.fact m))) := let ⟨n, hn⟩ := exists_nat_gt (abs z) in have hn0 : (0 : ℝ) < n, from lt_of_le_of_lt (abs_nonneg _) hn, series_ratio_test n (complex.abs z / n) (div_nonneg_of_nonneg_of_pos (complex.abs_nonneg _) hn0) (by rwa [div_lt_iff hn0, one_mul]) (λ m hm, by rw [abs_abs, abs_abs, nat.fact_succ, pow_succ, mul_comm m.succ, nat.cast_mul, ← div_div_eq_div_mul, mul_div_assoc, mul_div_right_comm, abs_mul, abs_div, abs_cast_nat]; exact mul_le_mul_of_nonneg_right (div_le_div_of_le_left (abs_nonneg _) hn0 (nat.cast_le.2 (le_trans hm (nat.le_succ _)))) (abs_nonneg _)) noncomputable theory lemma is_cau_exp (z : ℂ) : is_cau_seq abs (λ n, (range n).sum (λ m, z ^ m / nat.fact m)) := is_cau_series_of_abv_cau (is_cau_abs_exp z) def exp' (z : ℂ) : cau_seq ℂ complex.abs := ⟨λ n, (range n).sum (λ m, z ^ m / nat.fact m), is_cau_exp z⟩ def exp (z : ℂ) : ℂ := lim (exp' z) def sin (z : ℂ) : ℂ := ((exp (-z * I) - exp (z * I)) * I) / 2 def cos (z : ℂ) : ℂ := (exp (z * I) + exp (-z * I)) / 2 def tan (z : ℂ) : ℂ := sin z / cos z def sinh (z : ℂ) : ℂ := (exp z - exp (-z)) / 2 def cosh (z : ℂ) : ℂ := (exp z + exp (-z)) / 2 def tanh (z : ℂ) : ℂ := sinh z / cosh z end complex namespace real open complex def exp (x : ℝ) : ℝ := (exp x).re def sin (x : ℝ) : ℝ := (sin x).re def cos (x : ℝ) : ℝ := (cos x).re def tan (x : ℝ) : ℝ := (tan x).re def sinh (x : ℝ) : ℝ := (sinh x).re def cosh (x : ℝ) : ℝ := (cosh x).re def tanh (x : ℝ) : ℝ := (tanh x).re end real namespace complex variables (x y : ℂ) @[simp] lemma exp_zero : exp 0 = 1 := lim_eq_of_equiv_const $ λ ε ε0, ⟨1, λ j hj, begin convert ε0, cases j, { exact absurd hj (not_le_of_gt zero_lt_one) }, { dsimp [exp'], induction j with j ih, { dsimp [exp']; simp }, { rw ← ih dec_trivial, simp only [sum_range_succ, pow_succ], simp } } end⟩ lemma exp_add : exp (x + y) = exp x * exp y := show lim (⟨_, is_cau_exp (x + y)⟩ : cau_seq ℂ abs) = lim (show cau_seq ℂ abs, from ⟨_, is_cau_exp x⟩) * lim (show cau_seq ℂ abs, from ⟨_, is_cau_exp y⟩), from have hj : ∀ j : ℕ, (range j).sum (λ m, (x + y) ^ m / m.fact) = (range j).sum (λ i, (range (i + 1)).sum (λ k, x ^ k / k.fact * (y ^ (i - k) / (i - k).fact))), from assume j, finset.sum_congr rfl (λ m hm, begin rw [add_pow, div_eq_mul_inv, sum_mul], refine finset.sum_congr rfl (λ i hi, _), have h₁ : (nat.choose m i : ℂ) ≠ 0 := nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 (nat.choose_pos (nat.le_of_lt_succ (mem_range.1 hi)))), have h₂ := nat.choose_mul_fact_mul_fact (nat.le_of_lt_succ $ finset.mem_range.1 hi), rw [← h₂, nat.cast_mul, nat.cast_mul, mul_inv', mul_inv'], simp only [mul_left_comm (nat.choose m i : ℂ), mul_assoc, mul_left_comm (nat.choose m i : ℂ)⁻¹, mul_comm (nat.choose m i : ℂ)], rw inv_mul_cancel h₁, simp [div_eq_mul_inv, mul_comm, mul_assoc, mul_left_comm] end), by rw lim_mul_lim; exact eq.symm (lim_eq_lim_of_equiv (by dsimp; simp only [hj]; exact cauchy_product (is_cau_abs_exp x) (is_cau_exp y))) attribute [irreducible] complex.exp lemma exp_list_sum (l : list ℂ) : exp l.sum = (l.map exp).prod := @monoid_hom.map_list_prod (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ l lemma exp_multiset_sum (s : multiset ℂ) : exp s.sum = (s.map exp).prod := @monoid_hom.map_multiset_prod (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ s lemma exp_sum {α : Type*} (s : finset α) (f : α → ℂ) : exp (s.sum f) = s.prod (exp ∘ f) := @monoid_hom.map_prod α (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ f s lemma exp_nat_mul (x : ℂ) : ∀ n : ℕ, exp(n*x) = (exp x)^n | 0 := by rw [nat.cast_zero, zero_mul, exp_zero, pow_zero] | (nat.succ n) := by rw [pow_succ', nat.cast_add_one, add_mul, exp_add, ←exp_nat_mul, one_mul] lemma exp_ne_zero : exp x ≠ 0 := λ h, zero_ne_one $ by rw [← exp_zero, ← add_neg_self x, exp_add, h]; simp lemma exp_neg : exp (-x) = (exp x)⁻¹ := by rw [← domain.mul_right_inj (exp_ne_zero x), ← exp_add]; simp [mul_inv_cancel (exp_ne_zero x)] lemma exp_sub : exp (x - y) = exp x / exp y := by simp [sub_eq_add_neg, exp_add, exp_neg, div_eq_mul_inv] @[simp] lemma exp_conj : exp (conj x) = conj (exp x) := begin dsimp [exp], rw [← lim_conj], refine congr_arg lim (cau_seq.ext (λ _, _)), dsimp [exp', function.comp, cau_seq_conj], rw ← sum_hom _ conj, refine sum_congr rfl (λ n hn, _), rw [conj_div, conj_pow, ← of_real_nat_cast, conj_of_real] end @[simp] lemma of_real_exp_of_real_re (x : ℝ) : ((exp x).re : ℂ) = exp x := eq_conj_iff_re.1 $ by rw [← exp_conj, conj_of_real] @[simp] lemma of_real_exp (x : ℝ) : (real.exp x : ℂ) = exp x := of_real_exp_of_real_re _ @[simp] lemma exp_of_real_im (x : ℝ) : (exp x).im = 0 := by rw [← of_real_exp_of_real_re, of_real_im] lemma exp_of_real_re (x : ℝ) : (exp x).re = real.exp x := rfl lemma two_sinh : 2 * sinh x = exp x - exp (-x) := mul_div_cancel' _ two_ne_zero' lemma two_cosh : 2 * cosh x = exp x + exp (-x) := mul_div_cancel' _ two_ne_zero' @[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh] @[simp] lemma sinh_neg : sinh (-x) = -sinh x := by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul] private lemma sinh_add_aux {a b c d : ℂ} : (a - b) * (c + d) + (a + b) * (c - d) = 2 * (a * c - b * d) := by ring lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y := begin rw [← domain.mul_right_inj (@two_ne_zero' ℂ _ _ _), two_sinh, exp_add, neg_add, exp_add, eq_comm, mul_add, ← mul_assoc, two_sinh, mul_left_comm, two_sinh, ← domain.mul_right_inj (@two_ne_zero' ℂ _ _ _), mul_add, mul_left_comm, two_cosh, ← mul_assoc, two_cosh], exact sinh_add_aux end @[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh] @[simp] lemma cosh_neg : cosh (-x) = cosh x := by simp [add_comm, cosh, exp_neg] private lemma cosh_add_aux {a b c d : ℂ} : (a + b) * (c + d) + (a - b) * (c - d) = 2 * (a * c + b * d) := by ring lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y := begin rw [← domain.mul_right_inj (@two_ne_zero' ℂ _ _ _), two_cosh, exp_add, neg_add, exp_add, eq_comm, mul_add, ← mul_assoc, two_cosh, ← mul_assoc, two_sinh, ← domain.mul_right_inj (@two_ne_zero' ℂ _ _ _), mul_add, mul_left_comm, two_cosh, mul_left_comm, two_sinh], exact cosh_add_aux end lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y := by simp [sub_eq_add_neg, sinh_add, sinh_neg, cosh_neg] lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y := by simp [sub_eq_add_neg, cosh_add, sinh_neg, cosh_neg] lemma sinh_conj : sinh (conj x) = conj (sinh x) := by rw [sinh, ← conj_neg, exp_conj, exp_conj, ← conj_sub, sinh, conj_div, conj_two] @[simp] lemma of_real_sinh_of_real_re (x : ℝ) : ((sinh x).re : ℂ) = sinh x := eq_conj_iff_re.1 $ by rw [← sinh_conj, conj_of_real] @[simp] lemma of_real_sinh (x : ℝ) : (real.sinh x : ℂ) = sinh x := of_real_sinh_of_real_re _ @[simp] lemma sinh_of_real_im (x : ℝ) : (sinh x).im = 0 := by rw [← of_real_sinh_of_real_re, of_real_im] lemma sinh_of_real_re (x : ℝ) : (sinh x).re = real.sinh x := rfl lemma cosh_conj : cosh (conj x) = conj (cosh x) := by rw [cosh, ← conj_neg, exp_conj, exp_conj, ← conj_add, cosh, conj_div, conj_two] @[simp] lemma of_real_cosh_of_real_re (x : ℝ) : ((cosh x).re : ℂ) = cosh x := eq_conj_iff_re.1 $ by rw [← cosh_conj, conj_of_real] @[simp] lemma of_real_cosh (x : ℝ) : (real.cosh x : ℂ) = cosh x := of_real_cosh_of_real_re _ @[simp] lemma cosh_of_real_im (x : ℝ) : (cosh x).im = 0 := by rw [← of_real_cosh_of_real_re, of_real_im] lemma cosh_of_real_re (x : ℝ) : (cosh x).re = real.cosh x := rfl lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x := rfl @[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh] @[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div] lemma tanh_conj : tanh (conj x) = conj (tanh x) := by rw [tanh, sinh_conj, cosh_conj, ← conj_div, tanh] @[simp] lemma of_real_tanh_of_real_re (x : ℝ) : ((tanh x).re : ℂ) = tanh x := eq_conj_iff_re.1 $ by rw [← tanh_conj, conj_of_real] @[simp] lemma of_real_tanh (x : ℝ) : (real.tanh x : ℂ) = tanh x := of_real_tanh_of_real_re _ @[simp] lemma tanh_of_real_im (x : ℝ) : (tanh x).im = 0 := by rw [← of_real_tanh_of_real_re, of_real_im] lemma tanh_of_real_re (x : ℝ) : (tanh x).re = real.tanh x := rfl lemma cosh_add_sinh : cosh x + sinh x = exp x := by rw [← domain.mul_right_inj (@two_ne_zero' ℂ _ _ _), mul_add, two_cosh, two_sinh, add_add_sub_cancel, two_mul] lemma sinh_add_cosh : sinh x + cosh x = exp x := by rw [add_comm, cosh_add_sinh] lemma cosh_sub_sinh : cosh x - sinh x = exp (-x) := by rw [← domain.mul_right_inj (@two_ne_zero' ℂ _ _ _), mul_sub, two_cosh, two_sinh, add_sub_sub_cancel, two_mul] lemma cosh_sq_sub_sinh_sq : cosh x ^ 2 - sinh x ^ 2 = 1 := by rw [sq_sub_sq, cosh_add_sinh, cosh_sub_sinh, ← exp_add, add_neg_self, exp_zero] @[simp] lemma sin_zero : sin 0 = 0 := by simp [sin] @[simp] lemma sin_neg : sin (-x) = -sin x := by simp [sin, sub_eq_add_neg, exp_neg, (neg_div _ _).symm, add_mul] lemma two_sin : 2 * sin x = (exp (-x * I) - exp (x * I)) * I := mul_div_cancel' _ two_ne_zero' lemma two_cos : 2 * cos x = exp (x * I) + exp (-x * I) := mul_div_cancel' _ two_ne_zero' lemma sinh_mul_I : sinh (x * I) = sin x * I := by rw [← domain.mul_right_inj (@two_ne_zero' ℂ _ _ _), two_sinh, ← mul_assoc, two_sin, mul_assoc, I_mul_I, mul_neg_one, neg_sub, neg_mul_eq_neg_mul] lemma cosh_mul_I : cosh (x * I) = cos x := by rw [← domain.mul_right_inj (@two_ne_zero' ℂ _ _ _), two_cosh, two_cos, neg_mul_eq_neg_mul] lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y := by rw [← domain.mul_left_inj I_ne_zero, ← sinh_mul_I, add_mul, add_mul, mul_right_comm, ← sinh_mul_I, mul_assoc, ← sinh_mul_I, ← cosh_mul_I, ← cosh_mul_I, sinh_add] @[simp] lemma cos_zero : cos 0 = 1 := by simp [cos] @[simp] lemma cos_neg : cos (-x) = cos x := by simp [cos, sub_eq_add_neg, exp_neg, add_comm] private lemma cos_add_aux {a b c d : ℂ} : (a + b) * (c + d) - (b - a) * (d - c) * (-1) = 2 * (a * c + b * d) := by ring lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y := by rw [← cosh_mul_I, add_mul, cosh_add, cosh_mul_I, cosh_mul_I, sinh_mul_I, sinh_mul_I, mul_mul_mul_comm, I_mul_I, mul_neg_one, sub_eq_add_neg] lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y := by simp [sub_eq_add_neg, sin_add, sin_neg, cos_neg] lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y := by simp [sub_eq_add_neg, cos_add, sin_neg, cos_neg] lemma sin_conj : sin (conj x) = conj (sin x) := by rw [← domain.mul_left_inj I_ne_zero, ← sinh_mul_I, ← conj_neg_I, ← conj_mul, ← conj_mul, sinh_conj, mul_neg_eq_neg_mul_symm, sinh_neg, sinh_mul_I, mul_neg_eq_neg_mul_symm] @[simp] lemma of_real_sin_of_real_re (x : ℝ) : ((sin x).re : ℂ) = sin x := eq_conj_iff_re.1 $ by rw [← sin_conj, conj_of_real] @[simp] lemma of_real_sin (x : ℝ) : (real.sin x : ℂ) = sin x := of_real_sin_of_real_re _ @[simp] lemma sin_of_real_im (x : ℝ) : (sin x).im = 0 := by rw [← of_real_sin_of_real_re, of_real_im] lemma sin_of_real_re (x : ℝ) : (sin x).re = real.sin x := rfl lemma cos_conj : cos (conj x) = conj (cos x) := by rw [← cosh_mul_I, ← conj_neg_I, ← conj_mul, ← cosh_mul_I, cosh_conj, mul_neg_eq_neg_mul_symm, cosh_neg] @[simp] lemma of_real_cos_of_real_re (x : ℝ) : ((cos x).re : ℂ) = cos x := eq_conj_iff_re.1 $ by rw [← cos_conj, conj_of_real] @[simp] lemma of_real_cos (x : ℝ) : (real.cos x : ℂ) = cos x := of_real_cos_of_real_re _ @[simp] lemma cos_of_real_im (x : ℝ) : (cos x).im = 0 := by rw [← of_real_cos_of_real_re, of_real_im] lemma cos_of_real_re (x : ℝ) : (cos x).re = real.cos x := rfl @[simp] lemma tan_zero : tan 0 = 0 := by simp [tan] lemma tan_eq_sin_div_cos : tan x = sin x / cos x := rfl @[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div] lemma tan_conj : tan (conj x) = conj (tan x) := by rw [tan, sin_conj, cos_conj, ← conj_div, tan] @[simp] lemma of_real_tan_of_real_re (x : ℝ) : ((tan x).re : ℂ) = tan x := eq_conj_iff_re.1 $ by rw [← tan_conj, conj_of_real] @[simp] lemma of_real_tan (x : ℝ) : (real.tan x : ℂ) = tan x := of_real_tan_of_real_re _ @[simp] lemma tan_of_real_im (x : ℝ) : (tan x).im = 0 := by rw [← of_real_tan_of_real_re, of_real_im] lemma tan_of_real_re (x : ℝ) : (tan x).re = real.tan x := rfl lemma cos_add_sin_I : cos x + sin x * I = exp (x * I) := by rw [← cosh_add_sinh, sinh_mul_I, cosh_mul_I] lemma cos_sub_sin_I : cos x - sin x * I = exp (-x * I) := by rw [← neg_mul_eq_neg_mul, ← cosh_sub_sinh, sinh_mul_I, cosh_mul_I] lemma sin_sq_add_cos_sq : sin x ^ 2 + cos x ^ 2 = 1 := eq.trans (by rw [cosh_mul_I, sinh_mul_I, mul_pow, I_sq, mul_neg_one, sub_neg_eq_add, add_comm]) (cosh_sq_sub_sinh_sq (x * I)) lemma cos_two_mul' : cos (2 * x) = cos x ^ 2 - sin x ^ 2 := by rw [two_mul, cos_add, ← pow_two, ← pow_two] lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 := by rw [cos_two_mul', eq_sub_iff_add_eq.2 (sin_sq_add_cos_sq x), ← sub_add, sub_add_eq_add_sub, two_mul] lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x := by rw [two_mul, sin_add, two_mul, add_mul, mul_comm] lemma cos_square : cos x ^ 2 = 1 / 2 + cos (2 * x) / 2 := by simp [cos_two_mul, div_add_div_same, mul_div_cancel_left, two_ne_zero', -one_div_eq_inv] lemma sin_square : sin x ^ 2 = 1 - cos x ^ 2 := by { rw [←sin_sq_add_cos_sq x], simp } lemma exp_mul_I : exp (x * I) = cos x + sin x * I := (cos_add_sin_I _).symm lemma exp_add_mul_I : exp (x + y * I) = exp x * (cos y + sin y * I) := by rw [exp_add, exp_mul_I] lemma exp_eq_exp_re_mul_sin_add_cos : exp x = exp x.re * (cos x.im + sin x.im * I) := by rw [← exp_add_mul_I, re_add_im] theorem cos_add_sin_mul_I_pow (n : ℕ) (z : ℂ) : (cos z + sin z * I) ^ n = cos (↑n * z) + sin (↑n * z) * I := begin rw [← exp_mul_I, ← exp_mul_I], induction n with n ih, { rw [pow_zero, nat.cast_zero, zero_mul, zero_mul, exp_zero] }, { rw [pow_succ', ih, nat.cast_succ, add_mul, add_mul, one_mul, exp_add] } end end complex namespace real open complex variables (x y : ℝ) @[simp] lemma exp_zero : exp 0 = 1 := by simp [real.exp] lemma exp_add : exp (x + y) = exp x * exp y := by simp [exp_add, exp] lemma exp_list_sum (l : list ℝ) : exp l.sum = (l.map exp).prod := @monoid_hom.map_list_prod (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ l lemma exp_multiset_sum (s : multiset ℝ) : exp s.sum = (s.map exp).prod := @monoid_hom.map_multiset_prod (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ s lemma exp_sum {α : Type*} (s : finset α) (f : α → ℝ) : exp (s.sum f) = s.prod (exp ∘ f) := @monoid_hom.map_prod α (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ f s lemma exp_nat_mul (x : ℝ) : ∀ n : ℕ, exp(n*x) = (exp x)^n | 0 := by rw [nat.cast_zero, zero_mul, exp_zero, pow_zero] | (nat.succ n) := by rw [pow_succ', nat.cast_add_one, add_mul, exp_add, ←exp_nat_mul, one_mul] lemma exp_ne_zero : exp x ≠ 0 := λ h, exp_ne_zero x $ by rw [exp, ← of_real_inj] at h; simp * at * lemma exp_neg : exp (-x) = (exp x)⁻¹ := by rw [← of_real_inj, exp, of_real_exp_of_real_re, of_real_neg, exp_neg, of_real_inv, of_real_exp] lemma exp_sub : exp (x - y) = exp x / exp y := by simp [sub_eq_add_neg, exp_add, exp_neg, div_eq_mul_inv] @[simp] lemma sin_zero : sin 0 = 0 := by simp [sin] @[simp] lemma sin_neg : sin (-x) = -sin x := by simp [sin, exp_neg, (neg_div _ _).symm, add_mul] lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y := by rw [← of_real_inj]; simp [sin, sin_add] @[simp] lemma cos_zero : cos 0 = 1 := by simp [cos] @[simp] lemma cos_neg : cos (-x) = cos x := by simp [cos, exp_neg] lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y := by rw ← of_real_inj; simp [cos, cos_add] lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y := by simp [sub_eq_add_neg, sin_add, sin_neg, cos_neg] lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y := by simp [sub_eq_add_neg, cos_add, sin_neg, cos_neg] lemma tan_eq_sin_div_cos : tan x = sin x / cos x := if h : complex.cos x = 0 then by simp [sin, cos, tan, *, complex.tan, div_eq_mul_inv] at * else by rw [sin, cos, tan, complex.tan, ← of_real_inj, div_eq_mul_inv, mul_re]; simp [norm_sq, (div_div_eq_div_mul _ _ _).symm, div_self h]; refl @[simp] lemma tan_zero : tan 0 = 0 := by simp [tan] @[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div] lemma sin_sq_add_cos_sq : sin x ^ 2 + cos x ^ 2 = 1 := of_real_inj.1 $ by simpa using sin_sq_add_cos_sq x lemma sin_sq_le_one : sin x ^ 2 ≤ 1 := by rw ← sin_sq_add_cos_sq x; exact le_add_of_nonneg_right' (pow_two_nonneg _) lemma cos_sq_le_one : cos x ^ 2 ≤ 1 := by rw ← sin_sq_add_cos_sq x; exact le_add_of_nonneg_left' (pow_two_nonneg _) lemma abs_sin_le_one : abs' (sin x) ≤ 1 := (mul_self_le_mul_self_iff (_root_.abs_nonneg (sin x)) (by exact zero_le_one)).2 $ by rw [← _root_.abs_mul, abs_mul_self, mul_one, ← pow_two]; apply sin_sq_le_one lemma abs_cos_le_one : abs' (cos x) ≤ 1 := (mul_self_le_mul_self_iff (_root_.abs_nonneg (cos x)) (by exact zero_le_one)).2 $ by rw [← _root_.abs_mul, abs_mul_self, mul_one, ← pow_two]; apply cos_sq_le_one lemma sin_le_one : sin x ≤ 1 := (abs_le.1 (abs_sin_le_one _)).2 lemma cos_le_one : cos x ≤ 1 := (abs_le.1 (abs_cos_le_one _)).2 lemma neg_one_le_sin : -1 ≤ sin x := (abs_le.1 (abs_sin_le_one _)).1 lemma neg_one_le_cos : -1 ≤ cos x := (abs_le.1 (abs_cos_le_one _)).1 lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 := by rw ← of_real_inj; simp [cos_two_mul] lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x := by rw ← of_real_inj; simp [sin_two_mul] lemma cos_square : cos x ^ 2 = 1 / 2 + cos (2 * x) / 2 := of_real_inj.1 $ by simpa using cos_square x lemma sin_square : sin x ^ 2 = 1 - cos x ^ 2 := eq_sub_iff_add_eq.2 $ sin_sq_add_cos_sq _ @[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh] @[simp] lemma sinh_neg : sinh (-x) = -sinh x := by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul] lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y := by rw ← of_real_inj; simp [sinh_add] @[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh] @[simp] lemma cosh_neg : cosh (-x) = cosh x := by simp [cosh, exp_neg] lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y := by rw ← of_real_inj; simp [cosh, cosh_add] lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y := by simp [sub_eq_add_neg, sinh_add, sinh_neg, cosh_neg] lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y := by simp [sub_eq_add_neg, cosh_add, sinh_neg, cosh_neg] lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x := of_real_inj.1 $ by simp [tanh_eq_sinh_div_cosh] @[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh] @[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div] open is_absolute_value /- TODO make this private and prove ∀ x -/ lemma add_one_le_exp_of_nonneg {x : ℝ} (hx : 0 ≤ x) : x + 1 ≤ exp x := calc x + 1 ≤ lim (⟨(λ n : ℕ, ((exp' x) n).re), is_cau_seq_re (exp' x)⟩ : cau_seq ℝ abs') : le_lim (cau_seq.le_of_exists ⟨2, λ j hj, show x + (1 : ℝ) ≤ ((range j).sum (λ m, (x ^ m / m.fact : ℂ))).re, from have h₁ : (((λ m : ℕ, (x ^ m / m.fact : ℂ)) ∘ nat.succ) 0).re = x, by simp, have h₂ : ((x : ℂ) ^ 0 / nat.fact 0).re = 1, by simp, begin rw [← nat.sub_add_cancel hj, sum_range_succ', sum_range_succ', add_re, add_re, h₁, h₂, add_assoc, ← @sum_hom _ _ _ _ _ _ _ complex.re (is_add_group_hom.to_is_add_monoid_hom _)], refine le_add_of_nonneg_of_le (sum_nonneg (λ m hm, _)) (le_refl _), rw [← of_real_pow, ← of_real_nat_cast, ← of_real_div, of_real_re], exact div_nonneg (pow_nonneg hx _) (nat.cast_pos.2 (nat.fact_pos _)), end⟩) ... = exp x : by rw [exp, complex.exp, ← cau_seq_re, lim_re] lemma one_le_exp {x : ℝ} (hx : 0 ≤ x) : 1 ≤ exp x := by linarith [add_one_le_exp_of_nonneg hx] lemma exp_pos (x : ℝ) : 0 < exp x := (le_total 0 x).elim (lt_of_lt_of_le zero_lt_one ∘ one_le_exp) (λ h, by rw [← neg_neg x, real.exp_neg]; exact inv_pos.2 (lt_of_lt_of_le zero_lt_one (one_le_exp (neg_nonneg.2 h)))) @[simp] lemma abs_exp (x : ℝ) : abs' (exp x) = exp x := abs_of_pos (exp_pos _) lemma exp_strict_mono : strict_mono exp := λ x y h, by rw [← sub_add_cancel y x, real.exp_add]; exact (lt_mul_iff_one_lt_left (exp_pos _)).2 (lt_of_lt_of_le (by linarith) (add_one_le_exp_of_nonneg (by linarith))) lemma exp_lt_exp {x y : ℝ} : exp x < exp y ↔ x < y := exp_strict_mono.lt_iff_lt lemma exp_le_exp {x y : ℝ} : exp x ≤ exp y ↔ x ≤ y := exp_strict_mono.le_iff_le lemma exp_injective : function.injective exp := exp_strict_mono.injective @[simp] lemma exp_eq_one_iff : exp x = 1 ↔ x = 0 := by rw [← exp_zero, exp_injective.eq_iff] lemma one_lt_exp_iff {x : ℝ} : 1 < exp x ↔ 0 < x := by rw [← exp_zero, exp_lt_exp] lemma exp_lt_one_iff {x : ℝ} : exp x < 1 ↔ x < 0 := by rw [← exp_zero, exp_lt_exp] end real namespace complex lemma sum_div_fact_le {α : Type*} [discrete_linear_ordered_field α] (n j : ℕ) (hn : 0 < n) : (filter (λ k, n ≤ k) (range j)).sum (λ m : ℕ, (1 / m.fact : α)) ≤ n.succ * (n.fact * n)⁻¹ := calc (filter (λ k, n ≤ k) (range j)).sum (λ m : ℕ, (1 / m.fact : α)) = (range (j - n)).sum (λ m, 1 / (m + n).fact) : sum_bij (λ m _, m - n) (λ m hm, mem_range.2 $ (nat.sub_lt_sub_right_iff (by simp at hm; tauto)).2 (by simp at hm; tauto)) (λ m hm, by rw nat.sub_add_cancel; simp at *; tauto) (λ a₁ a₂ ha₁ ha₂ h, by rwa [nat.sub_eq_iff_eq_add, ← nat.sub_add_comm, eq_comm, nat.sub_eq_iff_eq_add, add_left_inj, eq_comm] at h; simp at *; tauto) (λ b hb, ⟨b + n, mem_filter.2 ⟨mem_range.2 $ nat.add_lt_of_lt_sub_right (mem_range.1 hb), nat.le_add_left _ _⟩, by rw nat.add_sub_cancel⟩) ... ≤ (range (j - n)).sum (λ m, (nat.fact n * n.succ ^ m)⁻¹) : begin refine sum_le_sum (assume m n, _), rw [one_div_eq_inv, inv_le_inv], { rw [← nat.cast_pow, ← nat.cast_mul, nat.cast_le, add_comm], exact nat.fact_mul_pow_le_fact }, { exact nat.cast_pos.2 (nat.fact_pos _) }, { exact mul_pos (nat.cast_pos.2 (nat.fact_pos _)) (pow_pos (nat.cast_pos.2 (nat.succ_pos _)) _) }, end ... = (nat.fact n)⁻¹ * (range (j - n)).sum (λ m, n.succ⁻¹ ^ m) : by simp [mul_inv', mul_sum.symm, sum_mul.symm, -nat.fact_succ, mul_comm, inv_pow'] ... = (n.succ - n.succ * n.succ⁻¹ ^ (j - n)) / (n.fact * n) : have h₁ : (n.succ : α) ≠ 1, from @nat.cast_one α _ _ ▸ mt nat.cast_inj.1 (mt nat.succ_inj (nat.pos_iff_ne_zero.1 hn)), have h₂ : (n.succ : α) ≠ 0, from nat.cast_ne_zero.2 (nat.succ_ne_zero _), have h₃ : (n.fact * n : α) ≠ 0, from mul_ne_zero (nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 (nat.fact_pos _))) (nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 hn)), have h₄ : (n.succ - 1 : α) = n, by simp, by rw [← geom_series_def, geom_sum_inv h₁ h₂, eq_div_iff_mul_eq _ _ h₃, mul_comm _ (n.fact * n : α), ← mul_assoc (n.fact⁻¹ : α), ← mul_inv', h₄, ← mul_assoc (n.fact * n : α), mul_comm (n : α) n.fact, mul_inv_cancel h₃]; simp [mul_add, add_mul, mul_assoc, mul_comm] ... ≤ n.succ / (n.fact * n) : begin refine iff.mpr (div_le_div_right (mul_pos _ _)) _, exact nat.cast_pos.2 (nat.fact_pos _), exact nat.cast_pos.2 hn, exact sub_le_self _ (mul_nonneg (nat.cast_nonneg _) (pow_nonneg (inv_nonneg.2 (nat.cast_nonneg _)) _)) end lemma exp_bound {x : ℂ} (hx : abs x ≤ 1) {n : ℕ} (hn : 0 < n) : abs (exp x - (range n).sum (λ m, x ^ m / m.fact)) ≤ abs x ^ n * (n.succ * (n.fact * n)⁻¹) := begin rw [← lim_const ((range n).sum _), exp, sub_eq_add_neg, ← lim_neg, lim_add, ← lim_abs], refine lim_le (cau_seq.le_of_exists ⟨n, λ j hj, _⟩), show abs ((range j).sum (λ m, x ^ m / m.fact) - (range n).sum (λ m, x ^ m / m.fact)) ≤ abs x ^ n * (n.succ * (n.fact * n)⁻¹), rw sum_range_sub_sum_range hj, exact calc abs (((range j).filter (λ k, n ≤ k)).sum (λ m : ℕ, (x ^ m / m.fact : ℂ))) = abs (((range j).filter (λ k, n ≤ k)).sum (λ m : ℕ, (x ^ n * (x ^ (m - n) / m.fact) : ℂ))) : congr_arg abs (sum_congr rfl (λ m hm, by rw [← mul_div_assoc, ← pow_add, nat.add_sub_cancel']; simp at hm; tauto)) ... ≤ (filter (λ k, n ≤ k) (range j)).sum (λ m, abs (x ^ n * (_ / m.fact))) : abv_sum_le_sum_abv _ _ ... ≤ (filter (λ k, n ≤ k) (range j)).sum (λ m, abs x ^ n * (1 / m.fact)) : begin refine sum_le_sum (λ m hm, _), rw [abs_mul, abv_pow abs, abs_div, abs_cast_nat], refine mul_le_mul_of_nonneg_left ((div_le_div_right _).2 _) _, exact nat.cast_pos.2 (nat.fact_pos _), rw abv_pow abs, exact (pow_le_one _ (abs_nonneg _) hx), exact pow_nonneg (abs_nonneg _) _ end ... = abs x ^ n * (((range j).filter (λ k, n ≤ k)).sum (λ m : ℕ, (1 / m.fact : ℝ))) : by simp [abs_mul, abv_pow abs, abs_div, mul_sum.symm] ... ≤ abs x ^ n * (n.succ * (n.fact * n)⁻¹) : mul_le_mul_of_nonneg_left (sum_div_fact_le _ _ hn) (pow_nonneg (abs_nonneg _) _) end lemma abs_exp_sub_one_le {x : ℂ} (hx : abs x ≤ 1) : abs (exp x - 1) ≤ 2 * abs x := calc abs (exp x - 1) = abs (exp x - (range 1).sum (λ m, x ^ m / m.fact)) : by simp [sum_range_succ] ... ≤ abs x ^ 1 * ((nat.succ 1) * (nat.fact 1 * (1 : ℕ))⁻¹) : exp_bound hx dec_trivial ... = 2 * abs x : by simp [two_mul, mul_two, mul_add, mul_comm] lemma abs_exp_sub_one_sub_id_le {x : ℂ} (hx : abs x ≤ 1) : abs (exp x - 1 - x) ≤ (abs x)^2 := calc abs (exp x - 1 - x) = abs (exp x - (range 2).sum (λ m, x ^ m / m.fact)) : by simp [sub_eq_add_neg, sum_range_succ, add_assoc] ... ≤ (abs x)^2 * (nat.succ 2 * (nat.fact 2 * (2 : ℕ))⁻¹) : exp_bound hx dec_trivial ... ≤ (abs x)^2 * 1 : mul_le_mul_of_nonneg_left (by norm_num) (pow_two_nonneg (abs x)) ... = (abs x)^2 : by rw [mul_one] end complex namespace real open complex finset lemma cos_bound {x : ℝ} (hx : abs' x ≤ 1) : abs' (cos x - (1 - x ^ 2 / 2)) ≤ abs' x ^ 4 * (5 / 96) := calc abs' (cos x - (1 - x ^ 2 / 2)) = abs (complex.cos x - (1 - x ^ 2 / 2)) : by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv] ... = abs ((complex.exp (x * I) + complex.exp (-x * I) - (2 - x ^ 2)) / 2) : by simp [complex.cos, sub_div, add_div, neg_div, div_self (@two_ne_zero' ℂ _ _ _)] ... = abs (((complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact)) + ((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact)))) / 2) : congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin simp only [sum_range_succ], simp [pow_succ], apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring end) ... ≤ abs ((complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact)) / 2) + abs ((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact)) / 2) : by rw add_div; exact abs_add _ _ ... = (abs ((complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact))) / 2 + abs ((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact))) / 2) : by simp [complex.abs_div] ... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2 + (complex.abs (-x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2) : add_le_add ((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial)) ((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial)) ... ≤ abs' x ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc] lemma sin_bound {x : ℝ} (hx : abs' x ≤ 1) : abs' (sin x - (x - x ^ 3 / 6)) ≤ abs' x ^ 4 * (5 / 96) := calc abs' (sin x - (x - x ^ 3 / 6)) = abs (complex.sin x - (x - x ^ 3 / 6)) : by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv] ... = abs (((complex.exp (-x * I) - complex.exp (x * I)) * I - (2 * x - x ^ 3 / 3)) / 2) : by simp [complex.sin, sub_div, add_div, neg_div, mul_div_cancel_left _ (@two_ne_zero' ℂ _ _ _), div_div_eq_div_mul, show (3 : ℂ) * 2 = 6, by norm_num] ... = abs ((((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact)) - (complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact))) * I) / 2) : congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin simp only [sum_range_succ], simp [pow_succ], apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring end) ... ≤ abs ((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact)) * I / 2) + abs (-((complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact)) * I) / 2) : by rw [sub_mul, sub_eq_add_neg, add_div]; exact abs_add _ _ ... = (abs ((complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact))) / 2 + abs ((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact))) / 2) : by simp [add_comm, complex.abs_div, complex.abs_mul] ... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2 + (complex.abs (-x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2) : add_le_add ((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial)) ((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial)) ... ≤ abs' x ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc] lemma cos_pos_of_le_one {x : ℝ} (hx : abs' x ≤ 1) : 0 < cos x := calc 0 < (1 - x ^ 2 / 2) - abs' x ^ 4 * (5 / 96) : sub_pos.2 $ lt_sub_iff_add_lt.2 (calc abs' x ^ 4 * (5 / 96) + x ^ 2 / 2 ≤ 1 * (5 / 96) + 1 / 2 : add_le_add (mul_le_mul_of_nonneg_right (pow_le_one _ (abs_nonneg _) hx) (by norm_num)) ((div_le_div_right (by norm_num)).2 (by rw [pow_two, ← abs_mul_self, _root_.abs_mul]; exact mul_le_one hx (abs_nonneg _) hx)) ... < 1 : by norm_num) ... ≤ cos x : sub_le.1 (abs_sub_le_iff.1 (cos_bound hx)).2 lemma sin_pos_of_pos_of_le_one {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 1) : 0 < sin x := calc 0 < x - x ^ 3 / 6 - abs' x ^ 4 * (5 / 96) : sub_pos.2 $ lt_sub_iff_add_lt.2 (calc abs' x ^ 4 * (5 / 96) + x ^ 3 / 6 ≤ x * (5 / 96) + x / 6 : add_le_add (mul_le_mul_of_nonneg_right (calc abs' x ^ 4 ≤ abs' x ^ 1 : pow_le_pow_of_le_one (abs_nonneg _) (by rwa _root_.abs_of_nonneg (le_of_lt hx0)) dec_trivial ... = x : by simp [_root_.abs_of_nonneg (le_of_lt (hx0))]) (by norm_num)) ((div_le_div_right (by norm_num)).2 (calc x ^ 3 ≤ x ^ 1 : pow_le_pow_of_le_one (le_of_lt hx0) hx dec_trivial ... = x : pow_one _)) ... < x : by linarith) ... ≤ sin x : sub_le.1 (abs_sub_le_iff.1 (sin_bound (by rwa [_root_.abs_of_nonneg (le_of_lt hx0)]))).2 lemma sin_pos_of_pos_of_le_two {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 2) : 0 < sin x := have x / 2 ≤ 1, from div_le_of_le_mul (by norm_num) (by simpa), calc 0 < 2 * sin (x / 2) * cos (x / 2) : mul_pos (mul_pos (by norm_num) (sin_pos_of_pos_of_le_one (half_pos hx0) this)) (cos_pos_of_le_one (by rwa [_root_.abs_of_nonneg (le_of_lt (half_pos hx0))])) ... = sin x : by rw [← sin_two_mul, two_mul, add_halves] lemma cos_one_le : cos 1 ≤ 2 / 3 := calc cos 1 ≤ abs' (1 : ℝ) ^ 4 * (5 / 96) + (1 - 1 ^ 2 / 2) : sub_le_iff_le_add.1 (abs_sub_le_iff.1 (cos_bound (by simp))).1 ... ≤ 2 / 3 : by norm_num lemma cos_one_pos : 0 < cos 1 := cos_pos_of_le_one (by simp) lemma cos_two_neg : cos 2 < 0 := calc cos 2 = cos (2 * 1) : congr_arg cos (mul_one _).symm ... = _ : real.cos_two_mul 1 ... ≤ 2 * (2 / 3) ^ 2 - 1 : sub_le_sub_right (mul_le_mul_of_nonneg_left (by rw [pow_two, pow_two]; exact mul_self_le_mul_self (le_of_lt cos_one_pos) cos_one_le) (by norm_num)) _ ... < 0 : by norm_num end real namespace complex lemma abs_cos_add_sin_mul_I (x : ℝ) : abs (cos x + sin x * I) = 1 := have _ := real.sin_sq_add_cos_sq x, by simp [add_comm, abs, norm_sq, pow_two, *, sin_of_real_re, cos_of_real_re, mul_re] at * lemma abs_exp_eq_iff_re_eq {x y : ℂ} : abs (exp x) = abs (exp y) ↔ x.re = y.re := by rw [exp_eq_exp_re_mul_sin_add_cos, exp_eq_exp_re_mul_sin_add_cos y, abs_mul, abs_mul, abs_cos_add_sin_mul_I, abs_cos_add_sin_mul_I, ← of_real_exp, ← of_real_exp, abs_of_nonneg (le_of_lt (real.exp_pos _)), abs_of_nonneg (le_of_lt (real.exp_pos _)), mul_one, mul_one]; exact ⟨λ h, real.exp_injective h, congr_arg _⟩ @[simp] lemma abs_exp_of_real (x : ℝ) : abs (exp x) = real.exp x := by rw [← of_real_exp]; exact abs_of_nonneg (le_of_lt (real.exp_pos _)) end complex
70ae67119bc22297e9fc483e122c695bd280a825
19cc34575500ee2e3d4586c15544632aa07a8e66
/src/topology/algebra/multilinear.lean
82f6dc7428be1cc634a6269b19562809cac9b6ea
[ "Apache-2.0" ]
permissive
LibertasSpZ/mathlib
b9fcd46625eb940611adb5e719a4b554138dade6
33f7870a49d7cc06d2f3036e22543e6ec5046e68
refs/heads/master
1,672,066,539,347
1,602,429,158,000
1,602,429,158,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,145
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.algebra.module import linear_algebra.multilinear /-! # Continuous multilinear maps We define continuous multilinear maps as maps from `Π(i : ι), M₁ i` to `M₂` which are multilinear and continuous, by extending the space of multilinear maps with a continuity assumption. Here, `M₁ i` and `M₂` are modules over a ring `R`, and `ι` is an arbitrary type, and all these spaces are also topological spaces. ## Main definitions * `continuous_multilinear_map R M₁ M₂` is the space of continuous multilinear maps from `Π(i : ι), M₁ i` to `M₂`. We show that it is an `R`-module. ## Implementation notes We mostly follow the API of multilinear maps. ## Notation We introduce the notation `M [×n]→L[R] M'` for the space of continuous `n`-multilinear maps from `M^n` to `M'`. This is a particular case of the general notion (where we allow varying dependent types as the arguments of our continuous multilinear maps), but arguably the most important one, especially when defining iterated derivatives. -/ open function fin set open_locale big_operators universes u v w w₁ w₁' w₂ w₃ w₄ variables {R : Type u} {ι : Type v} {n : ℕ} {M : fin n.succ → Type w} {M₁ : ι → Type w₁} {M₁' : ι → Type w₁'} {M₂ : Type w₂} {M₃ : Type w₃} {M₄ : Type w₄} [decidable_eq ι] /-- Continuous multilinear maps over the ring `R`, from `Πi, M₁ i` to `M₂` where `M₁ i` and `M₂` are modules over `R` with a topological structure. In applications, there will be compatibility conditions between the algebraic and the topological structures, but this is not needed for the definition. -/ structure continuous_multilinear_map (R : Type u) {ι : Type v} (M₁ : ι → Type w₁) (M₂ : Type w₂) [decidable_eq ι] [semiring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [∀i, semimodule R (M₁ i)] [semimodule R M₂] [∀i, topological_space (M₁ i)] [topological_space M₂] extends multilinear_map R M₁ M₂ := (cont : continuous to_fun) notation M `[×`:25 n `]→L[`:25 R `] ` M' := continuous_multilinear_map R (λ (i : fin n), M) M' namespace continuous_multilinear_map section semiring variables [semiring R] [Πi, add_comm_monoid (M i)] [Πi, add_comm_monoid (M₁ i)] [Πi, add_comm_monoid (M₁' i)] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] [Π i, semimodule R (M i)] [Π i, semimodule R (M₁ i)] [Π i, semimodule R (M₁' i)] [semimodule R M₂] [semimodule R M₃] [semimodule R M₄] [Π i, topological_space (M i)] [Π i, topological_space (M₁ i)] [Π i, topological_space (M₁' i)] [topological_space M₂] [topological_space M₃] [topological_space M₄] (f f' : continuous_multilinear_map R M₁ M₂) instance : has_coe_to_fun (continuous_multilinear_map R M₁ M₂) := ⟨_, λ f, f.to_multilinear_map.to_fun⟩ @[continuity] lemma coe_continuous : continuous (f : (Π i, M₁ i) → M₂) := f.cont @[simp] lemma coe_coe : (f.to_multilinear_map : (Π i, M₁ i) → M₂) = f := rfl @[ext] theorem ext {f f' : continuous_multilinear_map R M₁ M₂} (H : ∀ x, f x = f' x) : f = f' := by { cases f, cases f', congr' with x, exact H x } @[simp] lemma map_add (m : Πi, M₁ i) (i : ι) (x y : M₁ i) : f (update m i (x + y)) = f (update m i x) + f (update m i y) := f.map_add' m i x y @[simp] lemma map_smul (m : Πi, M₁ i) (i : ι) (c : R) (x : M₁ i) : f (update m i (c • x)) = c • f (update m i x) := f.map_smul' m i c x lemma map_coord_zero {m : Πi, M₁ i} (i : ι) (h : m i = 0) : f m = 0 := f.to_multilinear_map.map_coord_zero i h @[simp] lemma map_zero [nonempty ι] : f 0 = 0 := f.to_multilinear_map.map_zero instance : has_zero (continuous_multilinear_map R M₁ M₂) := ⟨{ cont := continuous_const, ..(0 : multilinear_map R M₁ M₂) }⟩ instance : inhabited (continuous_multilinear_map R M₁ M₂) := ⟨0⟩ @[simp] lemma zero_apply (m : Πi, M₁ i) : (0 : continuous_multilinear_map R M₁ M₂) m = 0 := rfl section has_continuous_add variable [has_continuous_add M₂] instance : has_add (continuous_multilinear_map R M₁ M₂) := ⟨λ f f', {cont := f.cont.add f'.cont, ..(f.to_multilinear_map + f'.to_multilinear_map)}⟩ @[simp] lemma add_apply (m : Πi, M₁ i) : (f + f') m = f m + f' m := rfl instance add_comm_monoid : add_comm_monoid (continuous_multilinear_map R M₁ M₂) := by refine {zero := 0, add := (+), ..}; intros; ext; simp [add_comm, add_left_comm] @[simp] lemma sum_apply {α : Type*} (f : α → continuous_multilinear_map R M₁ M₂) (m : Πi, M₁ i) : ∀ {s : finset α}, (∑ a in s, f a) m = ∑ a in s, f a m := begin classical, apply finset.induction, { rw finset.sum_empty, simp }, { assume a s has H, rw finset.sum_insert has, simp [H, has] } end end has_continuous_add /-- If `f` is a continuous multilinear map, then `f.to_continuous_linear_map m i` is the continuous linear map obtained by fixing all coordinates but `i` equal to those of `m`, and varying the `i`-th coordinate. -/ def to_continuous_linear_map (m : Πi, M₁ i) (i : ι) : M₁ i →L[R] M₂ := { cont := f.cont.comp continuous_update, ..(f.to_multilinear_map.to_linear_map m i) } /-- The cartesian product of two continuous multilinear maps, as a continuous multilinear map. -/ def prod (f : continuous_multilinear_map R M₁ M₂) (g : continuous_multilinear_map R M₁ M₃) : continuous_multilinear_map R M₁ (M₂ × M₃) := { cont := f.cont.prod_mk g.cont, .. f.to_multilinear_map.prod g.to_multilinear_map } @[simp] lemma prod_apply (f : continuous_multilinear_map R M₁ M₂) (g : continuous_multilinear_map R M₁ M₃) (m : Πi, M₁ i) : (f.prod g) m = (f m, g m) := rfl /-- If `g` is continuous multilinear and `f` is a collection of continuous linear maps, then `g (f₁ m₁, ..., fₙ mₙ)` is again a continuous multilinear map, that we call `g.comp_continuous_linear_map f`. -/ def comp_continuous_linear_map (g : continuous_multilinear_map R M₁' M₄) (f : Π i : ι, M₁ i →L[R] M₁' i) : continuous_multilinear_map R M₁ M₄ := { cont := g.cont.comp $ continuous_pi $ λj, (f j).cont.comp $ continuous_apply _, .. g.to_multilinear_map.comp_linear_map (λ i, (f i).to_linear_map) } @[simp] lemma comp_continuous_linear_map_apply (g : continuous_multilinear_map R M₁' M₄) (f : Π i : ι, M₁ i →L[R] M₁' i) (m : Π i, M₁ i) : g.comp_continuous_linear_map f m = g (λ i, f i $ m i) := rfl /-- In the specific case of continuous multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the additivity of a multilinear map along the first variable. -/ lemma cons_add (f : continuous_multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (x y : M 0) : f (cons (x+y) m) = f (cons x m) + f (cons y m) := f.to_multilinear_map.cons_add m x y /-- In the specific case of continuous multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the multiplicativity of a multilinear map along the first variable. -/ lemma cons_smul (f : continuous_multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (c : R) (x : M 0) : f (cons (c • x) m) = c • f (cons x m) := f.to_multilinear_map.cons_smul m c x lemma map_piecewise_add (m m' : Πi, M₁ i) (t : finset ι) : f (t.piecewise (m + m') m') = ∑ s in t.powerset, f (s.piecewise m m') := f.to_multilinear_map.map_piecewise_add _ _ _ /-- Additivity of a continuous multilinear map along all coordinates at the same time, writing `f (m + m')` as the sum of `f (s.piecewise m m')` over all sets `s`. -/ lemma map_add_univ [fintype ι] (m m' : Πi, M₁ i) : f (m + m') = ∑ s : finset ι, f (s.piecewise m m') := f.to_multilinear_map.map_add_univ _ _ section apply_sum open fintype finset variables {α : ι → Type*} [fintype ι] (g : Π i, α i → M₁ i) (A : Π i, finset (α i)) /-- If `f` is continuous multilinear, then `f (Σ_{j₁ ∈ A₁} g₁ j₁, ..., Σ_{jₙ ∈ Aₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions with `r 1 ∈ A₁`, ..., `r n ∈ Aₙ`. This follows from multilinearity by expanding successively with respect to each coordinate. -/ lemma map_sum_finset : f (λ i, ∑ j in A i, g i j) = ∑ r in pi_finset A, f (λ i, g i (r i)) := f.to_multilinear_map.map_sum_finset _ _ /-- If `f` is continuous multilinear, then `f (Σ_{j₁} g₁ j₁, ..., Σ_{jₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions `r`. This follows from multilinearity by expanding successively with respect to each coordinate. -/ lemma map_sum [∀ i, fintype (α i)] : f (λ i, ∑ j, g i j) = ∑ r : Π i, α i, f (λ i, g i (r i)) := f.to_multilinear_map.map_sum _ end apply_sum end semiring section ring variables [ring R] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂] [∀i, semimodule R (M₁ i)] [semimodule R M₂] [∀i, topological_space (M₁ i)] [topological_space M₂] (f f' : continuous_multilinear_map R M₁ M₂) @[simp] lemma map_sub (m : Πi, M₁ i) (i : ι) (x y : M₁ i) : f (update m i (x - y)) = f (update m i x) - f (update m i y) := f.to_multilinear_map.map_sub _ _ _ _ section topological_add_group variable [topological_add_group M₂] instance : has_neg (continuous_multilinear_map R M₁ M₂) := ⟨λ f, {cont := f.cont.neg, ..(-f.to_multilinear_map)}⟩ @[simp] lemma neg_apply (m : Πi, M₁ i) : (-f) m = - (f m) := rfl instance : add_comm_group (continuous_multilinear_map R M₁ M₂) := by refine {zero := 0, add := (+), neg := has_neg.neg, ..}; intros; ext; simp [add_comm, add_left_comm] @[simp] lemma sub_apply (m : Πi, M₁ i) : (f - f') m = f m - f' m := rfl end topological_add_group end ring section comm_ring variables [comm_ring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [∀i, semimodule R (M₁ i)] [semimodule R M₂] [∀i, topological_space (M₁ i)] [topological_space M₂] (f : continuous_multilinear_map R M₁ M₂) lemma map_piecewise_smul (c : ι → R) (m : Πi, M₁ i) (s : finset ι) : f (s.piecewise (λ i, c i • m i) m) = (∏ i in s, c i) • f m := f.to_multilinear_map.map_piecewise_smul _ _ _ /-- Multiplicativity of a continuous multilinear map along all coordinates at the same time, writing `f (λ i, c i • m i)` as `(∏ i, c i) • f m`. -/ lemma map_smul_univ [fintype ι] (c : ι → R) (m : Πi, M₁ i) : f (λ i, c i • m i) = (∏ i, c i) • f m := f.to_multilinear_map.map_smul_univ _ _ variables [topological_space R] [topological_semimodule R M₂] instance : has_scalar R (continuous_multilinear_map R M₁ M₂) := ⟨λ c f, { cont := continuous.smul continuous_const f.cont, .. c • f.to_multilinear_map }⟩ @[simp] lemma smul_apply (c : R) (m : Πi, M₁ i) : (c • f) m = c • f m := rfl end comm_ring section comm_ring variables [comm_ring R] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂] [∀i, semimodule R (M₁ i)] [semimodule R M₂] [∀i, topological_space (M₁ i)] [topological_space M₂] [topological_add_group M₂] [topological_space R] [topological_semimodule R M₂] (f : continuous_multilinear_map R M₁ M₂) /-- The space of continuous multilinear maps is a module over `R`, for the pointwise addition and scalar multiplication. -/ instance : semimodule R (continuous_multilinear_map R M₁ M₂) := semimodule.of_core $ by refine { smul := (•), .. }; intros; ext; simp [smul_add, add_smul, smul_smul] /-- Linear map version of the map `to_multilinear_map` associating to a continuous multilinear map the corresponding multilinear map. -/ def to_multilinear_map_linear : (continuous_multilinear_map R M₁ M₂) →ₗ[R] (multilinear_map R M₁ M₂) := { to_fun := λ f, f.to_multilinear_map, map_add' := λ f g, rfl, map_smul' := λ c f, rfl } end comm_ring end continuous_multilinear_map namespace continuous_linear_map variables [ring R] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂] [add_comm_group M₃] [∀i, module R (M₁ i)] [module R M₂] [module R M₃] [∀i, topological_space (M₁ i)] [topological_space M₂] [topological_space M₃] /-- Composing a continuous multilinear map with a continuous linear map gives again a continuous multilinear map. -/ def comp_continuous_multilinear_map (g : M₂ →L[R] M₃) (f : continuous_multilinear_map R M₁ M₂) : continuous_multilinear_map R M₁ M₃ := { cont := g.cont.comp f.cont, .. g.to_linear_map.comp_multilinear_map f.to_multilinear_map } @[simp] lemma comp_continuous_multilinear_map_coe (g : M₂ →L[R] M₃) (f : continuous_multilinear_map R M₁ M₂) : ((g.comp_continuous_multilinear_map f) : (Πi, M₁ i) → M₃) = (g : M₂ → M₃) ∘ (f : (Πi, M₁ i) → M₂) := by { ext m, refl } end continuous_linear_map
f38fdf2d1f8e07614ee07b7fc11fd8e667c9d11d
74caf7451c921a8d5ab9c6e2b828c9d0a35aae95
/library/system/io.lean
0220dbf106706c0dcc839223b19609ba6a7f2e47
[ "Apache-2.0" ]
permissive
sakas--/lean
f37b6fad4fd4206f2891b89f0f8135f57921fc3f
570d9052820be1d6442a5cc58ece37397f8a9e4c
refs/heads/master
1,586,127,145,194
1,480,960,018,000
1,480,960,635,000
40,137,176
0
0
null
1,438,621,351,000
1,438,621,351,000
null
UTF-8
Lean
false
false
823
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Luke Nelson, Jared Roesch and Leonardo de Moura -/ constant {u} io : Type u → Type u constant io.functor : functor io constant io.monad : monad io attribute [instance] io.functor io.monad constant put_str : string → io unit constant put_nat : nat → io unit constant get_line : io string meta constant format.print_using : format → options → io unit meta definition format.print (fmt : format) : io unit := format.print_using fmt options.mk meta definition pp_using {α : Type} [has_to_format α] (a : α) (o : options) : io unit := format.print_using (to_fmt a) o meta definition pp {α : Type} [has_to_format α] (a : α) : io unit := format.print (to_fmt a)
338a744cd226b73cd0763c0bd33c32e4e29ca2af
8e31b9e0d8cec76b5aa1e60a240bbd557d01047c
/src/partition.lean
4877ea4f05034a8fe03209606fb8d626148a6b79
[]
no_license
ChrisHughes24/LP
7bdd62cb648461c67246457f3ddcb9518226dd49
e3ed64c2d1f642696104584e74ae7226d8e916de
refs/heads/master
1,685,642,642,858
1,578,070,602,000
1,578,070,602,000
195,268,102
4
3
null
1,569,229,518,000
1,562,255,287,000
Lean
UTF-8
Lean
false
false
18,632
lean
import data.matrix.pequiv data.rat.basic data.vector2 variables {m n : ℕ} /-- The type of ordered partitions of `m + n` elements into vectors of `m` row variables and `n` column variables -/ structure partition (m n : ℕ) : Type := (row_indices : vector (fin (m + n)) m) (col_indices : vector (fin (m + n)) n) (mem_row_indices_or_col_indices : ∀ v : fin (m + n), v ∈ row_indices.to_list ∨ v ∈ col_indices.to_list) open pequiv function matrix finset fintype namespace partition local infix ` ⬝ `:70 := matrix.mul local postfix `ᵀ` : 1500 := transpose variable (P : partition m n) def fintype_aux : partition m n ≃ { x : vector (fin (m + n)) m × vector (fin (m + n)) n // ∀ v : fin (m + n), v ∈ x.1.to_list ∨ v ∈ x.2.to_list } := { to_fun := λ ⟨r, c, h⟩, ⟨⟨r, c⟩, h⟩, inv_fun := λ ⟨⟨r, c⟩, h⟩, ⟨r, c, h⟩, left_inv := λ ⟨r, c, h⟩, rfl, right_inv := λ ⟨⟨r, c⟩, h⟩, rfl } instance : fintype (partition m n) := fintype.of_equiv _ fintype_aux.symm def rowg : fin m → fin (m + n) := P.row_indices.nth def colg : fin n → fin (m + n) := P.col_indices.nth lemma mem_row_indices_iff_exists {v : fin (m + n)} : v ∈ P.row_indices.to_list ↔ ∃ i, v = P.rowg i := by simp only [vector.mem_iff_nth, eq_comm, rowg] lemma mem_col_indices_iff_exists {v : fin (m + n)} : v ∈ P.col_indices.to_list ↔ ∃ j, v = P.colg j := by simp only [vector.mem_iff_nth, eq_comm, colg] lemma eq_rowg_or_colg (v : fin (m + n)) : (∃ i, v = P.rowg i) ∨ (∃ j, v = P.colg j) := by rw [← mem_row_indices_iff_exists, ← mem_col_indices_iff_exists]; exact P.mem_row_indices_or_col_indices _ lemma row_indices_append_col_indices_nodup : (P.row_indices.append P.col_indices).to_list.nodup := vector.nodup_iff_nth_inj.2 $ fintype.injective_iff_surjective.2 $ λ v, (P.mem_row_indices_or_col_indices v).elim (by rw [← vector.mem_iff_nth]; simp {contextual := tt}) (by rw [← vector.mem_iff_nth]; simp {contextual := tt}) lemma row_indices_nodup : P.row_indices.to_list.nodup := begin have := P.row_indices_append_col_indices_nodup, simp [list.nodup_append] at this, tauto end lemma col_indices_nodup : P.col_indices.to_list.nodup := begin have := P.row_indices_append_col_indices_nodup, simp [list.nodup_append] at this, tauto end @[simp] lemma rowg_ne_colg (i j) : P.rowg i ≠ P.colg j := λ h, begin rw [rowg, colg] at h, have := P.row_indices_append_col_indices_nodup, rw [vector.to_list_append (P.row_indices) (P.col_indices), list.nodup_append, list.disjoint_right] at this, exact this.2.2 (by rw h; exact vector.nth_mem _ _) (vector.nth_mem i P.row_indices) end @[simp] lemma colg_ne_rowg (i j) : P.colg j ≠ P.rowg i := ne.symm $ rowg_ne_colg _ _ _ lemma injective_rowg : injective P.rowg := vector.nodup_iff_nth_inj.1 P.row_indices_nodup @[simp] lemma rowg_inj {i i' : fin m} : P.rowg i = P.rowg i' ↔ i = i' := P.injective_rowg.eq_iff lemma injective_colg : injective P.colg := vector.nodup_iff_nth_inj.1 P.col_indices_nodup @[simp] lemma colg_inj {j j' : fin n} : P.colg j = P.colg j' ↔ j = j' := P.injective_colg.eq_iff def rowp : fin (m + n) ≃. fin m := { to_fun := λ v, fin.find (λ i, P.rowg i = v), inv_fun := λ i, some (P.rowg i), inv := λ v i, begin cases h : fin.find (λ i, P.rowg i = v), { simp [fin.find_eq_none_iff, *] at * }, { rw [fin.find_eq_some_iff] at h, cases h with h _, subst h, simp [P.injective_rowg.eq_iff, eq_comm] } end } def colp : fin (m + n) ≃. fin n := { to_fun := λ v, fin.find (λ j, P.colg j = v), inv_fun := λ j, some (P.colg j), inv := λ v j, begin cases h : fin.find (λ j, P.colg j = v), { simp [fin.find_eq_none_iff, *] at * }, { rw [fin.find_eq_some_iff] at h, cases h with h _, subst h, simp [P.injective_rowg.eq_iff, eq_comm] } end } @[simp] lemma rowp_trans_rowp_symm : P.rowp.symm.trans P.rowp = pequiv.refl _ := trans_symm_eq_iff_forall_is_some.2 (λ _, rfl) @[simp] lemma colp_trans_colp_symm : P.colp.symm.trans P.colp = pequiv.refl _ := trans_symm_eq_iff_forall_is_some.2 (λ _, rfl) @[simp] lemma rowg_mem (P : partition m n) (r : fin m) : (P.rowg r) ∈ P.rowp.symm r := eq.refl _ lemma rowp_symm_eq_some_rowg (P : partition m n) (r : fin m) : P.rowp.symm r = some (P.rowg r) := rfl @[simp] lemma colg_mem (P : partition m n) (s : fin n) : (P.colg s) ∈ P.colp.symm s := eq.refl _ lemma colp_symm_eq_some_colg (P : partition m n) (s : fin n) : P.colp.symm s = some (P.colg s) := rfl @[simp] lemma rowp_rowg (P : partition m n) (r : fin m) : P.rowp (P.rowg r) = some r := P.rowp.symm.mem_iff_mem.2 (rowg_mem _ _) @[simp] lemma colp_colg (P : partition m n) (s : fin n) : P.colp (P.colg s) = some s := P.colp.symm.mem_iff_mem.2 (colg_mem _ _) @[simp] lemma rowp_symm_trans_colp : P.rowp.symm.trans P.colp = ⊥ := begin ext, dsimp [pequiv.trans, colp], simp [P.rowp_symm_eq_some_rowg, fin.find_eq_some_iff], end @[simp] lemma colg_get_colp_symm (v : fin (m + n)) (h : (P.colp v).is_some) : P.colg (option.get h) = v := let ⟨j, hj⟩ := option.is_some_iff_exists.1 h in have hj' : j ∈ P.colp (P.colg (option.get h)), by simpa, P.colp.inj hj' hj @[simp] lemma rowg_get_rowp_symm (v : fin (m + n)) (h : (P.rowp v).is_some) : P.rowg (option.get h) = v := let ⟨i, hi⟩ := option.is_some_iff_exists.1 h in have hi' : i ∈ P.rowp (P.rowg (option.get h)), by simpa, P.rowp.inj hi' hi def default : partition m n := { row_indices := ⟨(list.fin_range m).map (fin.cast_add _), by simp⟩, col_indices := ⟨(list.fin_range n).map (λ i, ⟨m + i.1, add_lt_add_of_le_of_lt (le_refl _) i.2⟩), by simp⟩, mem_row_indices_or_col_indices := λ v, if h : v.1 < m then or.inl (list.mem_map.2 ⟨⟨v.1, h⟩, list.mem_fin_range _, fin.eta _ _⟩) else have v.val - m < n, from (nat.sub_lt_left_iff_lt_add (le_of_not_gt h)).2 v.2, or.inr (list.mem_map.2 ⟨⟨v.1 - m, this⟩, list.mem_fin_range _, by simp [nat.add_sub_cancel' (le_of_not_gt h)]⟩) } instance : inhabited (partition m n) := ⟨default⟩ lemma is_some_rowp_symm (P : partition m n) : ∀ (i : fin m), (P.rowp.symm i).is_some := λ _, rfl lemma is_some_colp_symm (P : partition m n) : ∀ (k : fin n), (P.colp.symm k).is_some := λ _, rfl lemma injective_rowp_symm (P : partition m n) : injective P.rowp.symm := injective_of_forall_is_some (is_some_rowp_symm P) lemma injective_colp_symm (P : partition m n) : injective P.colp.symm := injective_of_forall_is_some (is_some_colp_symm P) @[elab_as_eliminator] def row_col_cases_on {C : fin (m + n) → Sort*} (P : partition m n) (v : fin (m + n)) (row : fin m → C v) (col : fin n → C v) : C v := begin cases h : P.rowp v with r, { exact col (option.get (show (P.colp v).is_some, from (P.eq_rowg_or_colg v).elim (λ ⟨r, hr⟩, absurd h (hr.symm ▸ by simp)) (λ ⟨c, hc⟩, hc.symm ▸ by simp))) }, { exact row r } end @[simp] lemma row_col_cases_on_rowg {C : fin (m + n) → Sort*} (P : partition m n) (r : fin m) (row : fin m → C (P.rowg r)) (col : fin n → C (P.rowg r)) : (row_col_cases_on P (P.rowg r) row col : C (P.rowg r)) = row r := by simp [row_col_cases_on] local infix ` ♠ `: 70 := pequiv.trans def swap (P : partition m n) (r : fin m) (s : fin n) : partition m n := { row_indices := P.row_indices.update_nth r (P.col_indices.nth s), col_indices := P.col_indices.update_nth s (P.row_indices.nth r), mem_row_indices_or_col_indices := λ v, (P.mem_row_indices_or_col_indices v).elim (λ h, begin revert h, simp only [vector.mem_iff_nth, exists_imp_distrib, vector.nth_update_nth_eq_if], intros i hi, subst hi, by_cases r = i, { right, use s, simp [h] }, { left, use i, simp [h] } end) (λ h, begin revert h, simp only [vector.mem_iff_nth, exists_imp_distrib, vector.nth_update_nth_eq_if], intros j hj, subst hj, by_cases s = j, { left, use r, simp [h] }, { right, use j, simp [h] } end)} lemma not_is_some_colp_of_is_some_rowp (P : partition m n) (j : fin (m + n)) : (P.rowp j).is_some → (P.colp j).is_some → false := begin rw [option.is_some_iff_exists, option.is_some_iff_exists], rintros ⟨i, hi⟩ ⟨k, hk⟩, have : P.rowp.symm.trans P.colp i = none, { rw [P.rowp_symm_trans_colp, pequiv.bot_apply] }, rw [pequiv.trans_eq_none] at this, rw [← pequiv.eq_some_iff] at hi, exact (this j k).resolve_left (not_not.2 hi) hk end lemma colp_ne_none_of_rowp_eq_none (P : partition m n) (v : fin (m + n)) (hb : P.rowp v = none) (hnb : P.colp v = none) : false := have hs : card (univ.image P.rowg) = m, by rw [card_image_of_injective _ (P.injective_rowg), card_univ, card_fin], have ht : card (univ.image P.colg) = n, by rw [card_image_of_injective _ (P.injective_colg), card_univ, card_fin], have hst : disjoint (univ.image P.rowg) (univ.image P.colg), from finset.disjoint_left.2 begin simp only [mem_image, exists_imp_distrib, not_exists], assume v i _ hi j _ hj, subst hi, exact not_is_some_colp_of_is_some_rowp P (P.rowg i) (option.is_some_iff_exists.2 ⟨i, by simp⟩) (hj ▸ option.is_some_iff_exists.2 ⟨j, by simp⟩), end, have (univ.image P.rowg) ∪ (univ.image P.colg) = univ, from eq_of_subset_of_card_le (λ _ _, mem_univ _) (by rw [card_disjoint_union hst, hs, ht, card_univ, card_fin]), begin cases mem_union.1 (eq_univ_iff_forall.1 this v); rcases mem_image.1 h with ⟨_, _, h⟩; subst h; simp * at * end lemma is_some_rowp_iff (P : partition m n) (j : fin (m + n)) : (P.rowp j).is_some ↔ ¬(P.colp j).is_some := ⟨not_is_some_colp_of_is_some_rowp P j, by erw [option.not_is_some_iff_eq_none, ← option.ne_none_iff_is_some, forall_swap]; exact colp_ne_none_of_rowp_eq_none P j⟩ @[simp] lemma colp_rowg_eq_none (P : partition m n) (r : fin m) : P.colp (P.rowg r) = none := option.not_is_some_iff_eq_none.1 ((P.is_some_rowp_iff _).1 (by simp)) @[simp] lemma rowp_colg_eq_none (P : partition m n) (s : fin n) : P.rowp (P.colg s) = none := option.not_is_some_iff_eq_none.1 (mt (P.is_some_rowp_iff _).1 (by simp)) @[simp] lemma row_col_cases_on_colg {C : fin (m + n) → Sort*} (P : partition m n) (c : fin n) (row : fin m → C (P.colg c)) (col : fin n → C (P.colg c)) : (row_col_cases_on P (P.colg c) row col : C (P.colg c)) = col c := have ∀ (v' : option (fin m)) (p : option (fin m) → Prop) (h : p v') (h1 : v' = none) (f : Π (hpn : p none), fin n), (option.rec (λ (h : p none), col (f h)) (λ (r : fin m) (h : p (some r)), row r) v' h : C (colg P c)) = col (f (h1 ▸ h)), from λ v' p pv' hn f, by subst hn, begin convert this (P.rowp (P.colg c)) (λ x, P.rowp (P.colg c) = x) rfl (by simp) (λ h, option.get (row_col_cases_on._proof_1 P (colg P c) h)), erw [← option.some_inj, option.some_get, colp_colg] end @[simp] lemma option.get_inj {α : Type*} : Π {a b : option α} {ha : a.is_some} {hb : b.is_some}, option.get ha = option.get hb ↔ a = b | (some a) (some b) _ _ := by rw [option.get_some, option.get_some, option.some_inj] @[ext] lemma ext {P C : partition m n} (h : ∀ i, P.rowg i = C.rowg i) (h₂ : ∀ j, P.colg j = C.colg j) : P = C := begin cases P, cases C, simp [rowg, colg, function.funext_iff] at *, split; apply vector.ext; assumption end @[simp] lemma single_rowg_mul_rowp (P : partition m n) (i : fin m) : ((single (0 : fin 1) (P.rowg i)).to_matrix : matrix _ _ ℚ) ⬝ P.rowp.to_matrix = (single (0 : fin 1) i).to_matrix := by rw [← to_matrix_trans, single_trans_of_mem _ (rowp_rowg _ _)] @[simp] lemma single_rowg_mul_colp (P : partition m n) (i : fin m) : ((single (0 : fin 1) (P.rowg i)).to_matrix : matrix _ _ ℚ) ⬝ P.colp.to_matrix = 0 := by rw [← to_matrix_trans, single_trans_of_eq_none _ (colp_rowg_eq_none _ _), to_matrix_bot]; apply_instance @[simp] lemma single_colg_mul_colp (P : partition m n) (k : fin n) : ((single (0 : fin 1) (P.colg k)).to_matrix : matrix _ _ ℚ) ⬝ P.colp.to_matrix = (single (0 : fin 1) k).to_matrix := by rw [← to_matrix_trans, single_trans_of_mem _ (colp_colg _ _)] lemma single_colg_mul_rowp (P : partition m n) (k : fin n) : ((single (0 : fin 1) (P.colg k)).to_matrix : matrix _ _ ℚ) ⬝ P.rowp.to_matrix = 0 := by rw [← to_matrix_trans, single_trans_of_eq_none _ (rowp_colg_eq_none _ _), to_matrix_bot]; apply_instance lemma colp_symm_trans_rowp (P : partition m n) : P.colp.symm.trans P.rowp = ⊥ := symm_injective $ by rw [symm_trans_rev, symm_symm, rowp_symm_trans_colp, symm_bot] @[simp] lemma colp_transpose_mul_rowp (P : partition m n) : (P.colp.to_matrix : matrix _ _ ℚ)ᵀ ⬝ P.rowp.to_matrix = 0 := by rw [← to_matrix_bot, ← P.colp_symm_trans_rowp, to_matrix_trans, to_matrix_symm] @[simp] lemma rowp_transpose_mul_colp (P : partition m n) : (P.rowp.to_matrix : matrix _ _ ℚ)ᵀ ⬝ P.colp.to_matrix = 0 := by rw [← to_matrix_bot, ← P.rowp_symm_trans_colp, to_matrix_trans, to_matrix_symm] @[simp] lemma colp_transpose_mul_colp (P : partition m n) : (P.colp.to_matrix : matrix _ _ ℚ)ᵀ ⬝ P.colp.to_matrix = 1 := by rw [← to_matrix_refl, ← P.colp_trans_colp_symm, to_matrix_trans, to_matrix_symm] @[simp] lemma rowp_transpose_mul_rowp (P : partition m n) : (P.rowp.to_matrix : matrix _ _ ℚ)ᵀ ⬝ P.rowp.to_matrix = 1 := by rw [← to_matrix_refl, ← P.rowp_trans_rowp_symm, to_matrix_trans, to_matrix_symm] lemma mul_transpose_add_mul_transpose (P : partition m n) : (P.rowp.to_matrix ⬝ P.rowp.to_matrixᵀ : matrix _ _ ℚ) + P.colp.to_matrix ⬝ P.colp.to_matrixᵀ = 1 := begin ext, repeat {rw [← to_matrix_symm, ← to_matrix_trans] }, simp only [add_val, pequiv.trans_symm, pequiv.to_matrix, one_val, pequiv.mem_of_set_iff, set.mem_set_of_eq], have := is_some_rowp_iff P j, split_ifs; tauto end @[simp] lemma rowg_swap (P : partition m n) (r : fin m) (s : fin n) : (P.swap r s).rowg r = P.colg s := option.some_inj.1 begin dsimp [swap, rowg, colg, pequiv.trans], simp end @[simp] lemma colg_swap (P : partition m n) (r : fin m) (s : fin n) : (P.swap r s).colg s = P.rowg r := option.some_inj.1 begin dsimp [swap, rowg, colg, pequiv.trans], simp end @[simp] lemma swap_ne_self (P : partition m n) (r : fin m) (c : fin n) : (P.swap r c) ≠ P := mt (congr_arg (λ P : partition m n, P.rowg r)) $ by simp lemma rowg_swap_of_ne (P : partition m n) {i r : fin m} {s : fin n} (h : i ≠ r) : (P.swap r s).rowg i = P.rowg i := option.some_inj.1 begin dsimp [swap, rowg, colg, pequiv.trans], simp [vector.nth_update_nth_of_ne h.symm] end lemma colg_swap_of_ne (P : partition m n) {r : fin m} {j s : fin n} (h : j ≠ s) : (P.swap r s).colg j = P.colg j := option.some_inj.1 begin dsimp [swap, rowg, colg, pequiv.trans], simp [vector.nth_update_nth_of_ne h.symm] end lemma rowg_swap' (P : partition m n) (i r : fin m) (s : fin n) : (P.swap r s).rowg i = if i = r then P.colg s else P.rowg i := if hir : i = r then by simp [hir] else by rw [if_neg hir, rowg_swap_of_ne _ hir] lemma colg_swap' (P : partition m n) (r : fin m) (j s : fin n) : (P.swap r s).colg j = if j = s then P.rowg r else P.colg j := if hjs : j = s then by simp [hjs] else by rw [if_neg hjs, colg_swap_of_ne _ hjs] @[simp] lemma swap_swap (P : partition m n) (r : fin m) (s : fin n) : (P.swap r s).swap r s = P := by ext; intros; simp [rowg_swap', colg_swap']; split_ifs; cc def fin.lastp : fin (m + 1 + n) := fin.cast (add_right_comm _ _ _) (fin.last (m + n)) def fin.castp (v : fin (m + n)) : fin (m + 1 + n) := fin.cast (add_right_comm _ _ _) (fin.cast_succ v) @[simp] lemma fin.castp_ne_lastp (v : fin (m + n)) : (fin.lastp : fin (m + 1 + n)) ≠ fin.castp v := ne_of_gt v.2 @[simp] lemma fin.lastp_ne_castp (v : fin (m + n)) : fin.castp v ≠ fin.lastp := ne_of_lt v.2 lemma fin.injective_castp : injective (@fin.castp m n) := λ ⟨_, _⟩ ⟨_, _⟩, by simp [fin.castp, fin.cast, fin.cast_le, fin.cast_lt, fin.cast_succ] def add_row (P : partition m n) : partition (m + 1) n := { row_indices := (P.row_indices.map fin.castp).append ⟨[fin.lastp], rfl⟩, col_indices := P.col_indices.map (fin.cast (add_right_comm _ _ _) ∘ fin.cast_succ), mem_row_indices_or_col_indices := begin rintros ⟨v, hv⟩, simp only [fin.cast, fin.cast_le, fin.cast_lt, fin.last, vector.to_list_map, fin.eq_iff_veq, list.mem_map, fin.cast_le, vector.to_list_append, list.mem_append, function.comp, fin.cast_succ, fin.cast_add, fin.exists_iff, and_comm _ (_ = _), exists_and_distrib_left, exists_eq_left, fin.lastp, fin.castp], by_cases hvmn : v = m + n, { simp [hvmn] }, { have hv : v < m + n, from lt_of_le_of_ne (nat.le_of_lt_succ $ by simpa using hv) hvmn, cases P.mem_row_indices_or_col_indices ⟨v, hv⟩; simp * } end } lemma add_row_rowg_last (P : partition m n) : P.add_row.rowg (fin.last m) = fin.lastp := have (fin.last m).1 = (P.row_indices.map fin.castp).to_list.length := by simp [fin.last], option.some_inj.1 $ by simp only [add_row, rowg, vector.nth_eq_nth_le, vector.to_list_append, (list.nth_le_nth _).symm, list.nth_concat_length, this, vector.to_list_mk]; refl lemma add_row_rowg_cast_succ (P : partition m n) (i : fin m) : P.add_row.rowg (fin.cast_succ i) = fin.castp (P.rowg i) := have i.1 < (P.row_indices.to_list.map fin.castp).length, by simp [i.2], by simp [add_row, rowg, vector.nth_eq_nth_le, vector.to_list_append, (list.nth_le_nth _).symm, list.nth_concat_length, vector.to_list_mk, list.nth_le_append _ this, list.nth_le_map] lemma add_row_colg (P : partition m n) (j : fin n) : P.add_row.colg j = fin.castp (P.colg j) := fin.eq_of_veq $ by simp [add_row, colg, vector.nth_eq_nth_le, fin.castp] def dual (P : partition m n) : partition n m := { row_indices := P.col_indices.map (fin.cast (add_comm _ _)), col_indices := P.row_indices.map (fin.cast (add_comm _ _)), mem_row_indices_or_col_indices := λ v, (P.mem_row_indices_or_col_indices (fin.cast (add_comm _ _) v)).elim (λ h, or.inr begin simp only [vector.to_list_map, list.mem_map], use fin.cast (add_comm _ _) v, simp [fin.eq_iff_veq, h], end) (λ h, or.inl begin simp only [vector.to_list_map, list.mem_map], use fin.cast (add_comm _ _) v, simp [fin.eq_iff_veq, h], end) } @[simp] lemma dual_dual (P : partition m n) : P.dual.dual = P := by cases P; simp [dual]; split; ext; simp [fin.eq_iff_veq] end partition
9e0f17c7c47cbaf105a82b0231fe10e51f476986
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/monoidal/internal/Module.lean
007186419584833e88af360d0448a4dc6ab46bf8
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
3,252
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.category.Module.monoidal import Mathlib.algebra.category.Algebra.basic import Mathlib.category_theory.monoidal.Mon_ import Mathlib.PostPort universes u namespace Mathlib /-! # `Mon_ (Module R) ≌ Algebra R` The category of internal monoid objects in `Module R` is equivalent to the category of "native" bundled `R`-algebras. Moreover, this equivalence is compatible with the forgetful functors to `Module R`. -/ namespace Module namespace Mon_Module_equivalence_Algebra @[simp] theorem Mon_.X.ring_zero {R : Type u} [comm_ring R] (A : Mon_ (Module R)) : 0 = add_comm_group.zero := Eq.refl 0 protected instance Mon_.X.algebra {R : Type u} [comm_ring R] (A : Mon_ (Module R)) : algebra R ↥(Mon_.X A) := algebra.mk (ring_hom.mk (linear_map.to_fun (Mon_.one A)) sorry sorry sorry sorry) sorry sorry @[simp] theorem algebra_map {R : Type u} [comm_ring R] (A : Mon_ (Module R)) (r : R) : coe_fn (algebra_map R ↥(Mon_.X A)) r = coe_fn (Mon_.one A) r := rfl /-- Converting a monoid object in `Module R` to a bundled algebra. -/ @[simp] theorem functor_obj {R : Type u} [comm_ring R] (A : Mon_ (Module R)) : category_theory.functor.obj functor A = Algebra.of R ↥(Mon_.X A) := Eq.refl (category_theory.functor.obj functor A) /-- Converting a bundled algebra to a monoid object in `Module R`. -/ def inverse_obj {R : Type u} [comm_ring R] (A : Algebra R) : Mon_ (Module R) := Mon_.mk (of R ↥A) (algebra.linear_map R ↥A) (algebra.lmul' R) /-- Converting a bundled algebra to a monoid object in `Module R`. -/ @[simp] theorem inverse_map_hom {R : Type u} [comm_ring R] (A : Algebra R) (B : Algebra R) (f : A ⟶ B) : Mon_.hom.hom (category_theory.functor.map inverse f) = alg_hom.to_linear_map f := Eq.refl (Mon_.hom.hom (category_theory.functor.map inverse f)) end Mon_Module_equivalence_Algebra /-- The category of internal monoid objects in `Module R` is equivalent to the category of "native" bundled `R`-algebras. -/ def Mon_Module_equivalence_Algebra {R : Type u} [comm_ring R] : Mon_ (Module R) ≌ Algebra R := category_theory.equivalence.mk' sorry sorry (category_theory.nat_iso.of_components (fun (A : Mon_ (Module R)) => category_theory.iso.mk (Mon_.hom.mk (linear_map.mk id sorry sorry)) (Mon_.hom.mk (linear_map.mk id sorry sorry))) sorry) (category_theory.nat_iso.of_components (fun (A : Algebra R) => category_theory.iso.mk (alg_hom.mk id sorry sorry sorry sorry sorry) (alg_hom.mk id sorry sorry sorry sorry sorry)) sorry) /-- The equivalence `Mon_ (Module R) ≌ Algebra R` is naturally compatible with the forgetful functors to `Module R`. -/ def Mon_Module_equivalence_Algebra_forget {R : Type u} [comm_ring R] : Mon_Module_equivalence_Algebra.functor ⋙ category_theory.forget₂ (Algebra R) (Module R) ≅ Mon_.forget (Module R) := category_theory.nat_iso.of_components (fun (A : Mon_ (Module R)) => category_theory.iso.mk (linear_map.mk id sorry sorry) (linear_map.mk id sorry sorry)) sorry
e91fda9f4d7fa315a5dfaab5883c7e5cd5a7675f
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/ring_theory/integral_domain.lean
9d05e2be2049242e823fec26e20e4823bed2282e
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
7,037
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Chris Hughes -/ import data.fintype.card import data.polynomial.ring_division import group_theory.specific_groups.cyclic import algebra.geom_sum /-! # Integral domains Assorted theorems about integral domains. ## Main theorems * `is_cyclic_of_subgroup_integral_domain` : A finite subgroup of the units of an integral domain is cyclic. * `field_of_integral_domain` : A finite integral domain is a field. ## Tags integral domain, finite integral domain, finite field -/ section open finset polynomial function open_locale big_operators nat variables {R : Type*} {G : Type*} [integral_domain R] [group G] [fintype G] lemma card_nth_roots_subgroup_units (f : G →* R) (hf : injective f) {n : ℕ} (hn : 0 < n) (g₀ : G) : ({g ∈ univ | g ^ n = g₀} : finset G).card ≤ (nth_roots n (f g₀)).card := begin haveI : decidable_eq R := classical.dec_eq _, refine le_trans _ (nth_roots n (f g₀)).to_finset_card_le, apply card_le_card_of_inj_on f, { intros g hg, rw [sep_def, mem_filter] at hg, rw [multiset.mem_to_finset, mem_nth_roots hn, ← f.map_pow, hg.2] }, { intros, apply hf, assumption } end /-- A finite subgroup of the unit group of an integral domain is cyclic. -/ lemma is_cyclic_of_subgroup_integral_domain (f : G →* R) (hf : injective f) : is_cyclic G := begin classical, apply is_cyclic_of_card_pow_eq_one_le, intros n hn, convert (le_trans (card_nth_roots_subgroup_units f hf hn 1) (card_nth_roots n (f 1))) end /-- The unit group of a finite integral domain is cyclic. -/ instance [fintype R] : is_cyclic (units R) := is_cyclic_of_subgroup_integral_domain (units.coe_hom R) $ units.ext /-- Every finite integral domain is a field. -/ def field_of_integral_domain [decidable_eq R] [fintype R] : field R := { inv := λ a, if h : a = 0 then 0 else fintype.bij_inv (show function.bijective (* a), from fintype.injective_iff_bijective.1 $ λ _ _, mul_right_cancel' h) 1, mul_inv_cancel := λ a ha, show a * dite _ _ _ = _, by rw [dif_neg ha, mul_comm]; exact fintype.right_inverse_bij_inv (show function.bijective (* a), from _) 1, inv_zero := dif_pos rfl, ..show integral_domain R, by apply_instance } section variables (S : set (units R)) [is_subgroup S] [fintype S] local attribute [instance] subtype.group /-- A finite subgroup of the units of an integral domain is cyclic. -/ instance subgroup_units_cyclic : is_cyclic S := begin refine is_cyclic_of_subgroup_integral_domain ⟨(coe : S → R), _, _⟩ (units.ext.comp subtype.val_injective), { simp only [is_submonoid.coe_one, units.coe_one, coe_coe] }, { intros, simp only [is_submonoid.coe_mul, units.coe_mul, coe_coe] }, end end lemma card_fiber_eq_of_mem_range {H : Type*} [group H] [decidable_eq H] (f : G →* H) {x y : H} (hx : x ∈ set.range f) (hy : y ∈ set.range f) : (univ.filter $ λ g, f g = x).card = (univ.filter $ λ g, f g = y).card := begin rcases hx with ⟨x, rfl⟩, rcases hy with ⟨y, rfl⟩, refine card_congr (λ g _, g * x⁻¹ * y) _ _ (λ g hg, ⟨g * y⁻¹ * x, _⟩), { simp only [mem_filter, one_mul, monoid_hom.map_mul, mem_univ, mul_right_inv, eq_self_iff_true, monoid_hom.map_mul_inv, and_self, forall_true_iff] {contextual := tt} }, { simp only [mul_left_inj, imp_self, forall_2_true_iff], }, { simp only [true_and, mem_filter, mem_univ] at hg, simp only [hg, mem_filter, one_mul, monoid_hom.map_mul, mem_univ, mul_right_inv, eq_self_iff_true, exists_prop_of_true, monoid_hom.map_mul_inv, and_self, mul_inv_cancel_right, inv_mul_cancel_right], } end section local attribute [instance] subtype.group subtype.monoid range.is_submonoid /-- In an integral domain, a sum indexed by a nontrivial homomorphism from a finite group is zero. -/ lemma sum_hom_units_eq_zero (f : G →* R) (hf : f ≠ 1) : ∑ g : G, f g = 0 := begin classical, obtain ⟨x, hx⟩ : ∃ x : set.range f.to_hom_units, ∀ y : set.range f.to_hom_units, y ∈ powers x, from is_cyclic.exists_monoid_generator, have hx1 : x ≠ 1, { rintro rfl, apply hf, ext g, rw [monoid_hom.one_apply], cases hx ⟨f.to_hom_units g, g, rfl⟩ with n hn, rwa [subtype.ext_iff, units.ext_iff, subtype.coe_mk, monoid_hom.coe_to_hom_units, is_submonoid.coe_pow, units.coe_pow, is_submonoid.coe_one, units.coe_one, one_pow, eq_comm] at hn, }, replace hx1 : (x : R) - 1 ≠ 0, from λ h, hx1 (subtype.eq (units.ext (sub_eq_zero.1 h))), let c := (univ.filter (λ g, f.to_hom_units g = 1)).card, calc ∑ g : G, f g = ∑ g : G, f.to_hom_units g : rfl ... = ∑ u : units R in univ.image f.to_hom_units, (univ.filter (λ g, f.to_hom_units g = u)).card • u : sum_comp (coe : units R → R) f.to_hom_units ... = ∑ u : units R in univ.image f.to_hom_units, c • u : sum_congr rfl (λ u hu, congr_arg2 _ _ rfl) -- remaining goal 1, proven below ... = ∑ b : set.range f.to_hom_units, c • ↑b : finset.sum_subtype _ (by simp only [mem_image, set.mem_range, forall_const, iff_self, mem_univ, exists_prop_of_true]) _ ... = c • ∑ b : set.range f.to_hom_units, (b : R) : smul_sum.symm ... = c • 0 : congr_arg2 _ rfl _ -- remaining goal 2, proven below ... = 0 : smul_zero _, { -- remaining goal 1 show (univ.filter (λ (g : G), f.to_hom_units g = u)).card = c, apply card_fiber_eq_of_mem_range f.to_hom_units, { simpa only [mem_image, mem_univ, exists_prop_of_true, set.mem_range] using hu, }, { exact ⟨1, f.to_hom_units.map_one⟩ } }, -- remaining goal 2 show ∑ b : set.range f.to_hom_units, (b : R) = 0, calc ∑ b : set.range f.to_hom_units, (b : R) = ∑ n in range (order_of x), x ^ n : eq.symm $ sum_bij (λ n _, x ^ n) (by simp only [mem_univ, forall_true_iff]) (by simp only [is_submonoid.coe_pow, eq_self_iff_true, units.coe_pow, coe_coe, forall_true_iff]) (λ m n hm hn, pow_injective_of_lt_order_of _ (by simpa only [mem_range] using hm) (by simpa only [mem_range] using hn)) (λ b hb, let ⟨n, hn⟩ := hx b in ⟨n % order_of x, mem_range.2 (nat.mod_lt _ (order_of_pos _)), by rw [← pow_eq_mod_order_of, hn]⟩) ... = 0 : _, rw [← mul_left_inj' hx1, zero_mul, ← geom_sum, geom_sum_mul, coe_coe], norm_cast, rw [pow_order_of_eq_one, is_submonoid.coe_one, units.coe_one, sub_self], end end /-- In an integral domain, a sum indexed by a homomorphism from a finite group is zero, unless the homomorphism is trivial, in which case the sum is equal to the cardinality of the group. -/ lemma sum_hom_units (f : G →* R) [decidable (f = 1)] : ∑ g : G, f g = if f = 1 then fintype.card G else 0 := begin split_ifs with h h, { simp [h, card_univ] }, { exact sum_hom_units_eq_zero f h } end end
99ddc0177630eb1101cb2f6f70bbb3ef6a9971f9
a46270e2f76a375564f3b3e9c1bf7b635edc1f2c
/7.5.lean
b045d8ca06def2551707c27a19f84d2bd58c22ab
[ "CC0-1.0" ]
permissive
wudcscheme/lean-exercise
88ea2506714eac343de2a294d1132ee8ee6d3a20
5b23b9be3d361fff5e981d5be3a0a1175504b9f6
refs/heads/master
1,678,958,930,293
1,583,197,205,000
1,583,197,205,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,081
lean
universe u namespace hidden inductive list (α : Type u) | nil {} : list | cons : α → list → list namespace list notation `[` l:(foldr `,` (h t, cons h t) nil) `]` := l variable {α : Type} notation h :: t := cons h t def append (s t : list α) : list α := list.rec_on s t (λ x l u, x::u) notation s ++ t := append s t theorem nil_append (t : list α) : nil ++ t = t := rfl theorem cons_append (x : α) (s t : list α) : x::s ++ t = x::(s ++ t) := rfl -- BEGIN theorem append_nil (t : list α) : t ++ nil = t := list.rec_on t ( nil_append nil ) ( λ h l, assume ih: (append l nil = l), calc append (h::l) nil = h::(append l nil): cons_append h l nil ... = h::l: by rw ih ) theorem append_assoc (r s t : list α) : r ++ s ++ t = r ++ (s ++ t) := list.rec_on r ( by simp [nil_append (s++t), nil_append s] ) ( λ h r, assume ih: r ++ s ++ t = r ++ (s ++ t), calc (h::r) ++ s ++ t = h::(r ++ s ++ t): cons_append h (r++s) t ... = h::(r ++ (s++t)): by rw ih ) -- END end list end hidden
a40bb9328b1adc1f04a8166a9dfc4bcd060f52d8
0845ae2ca02071debcfd4ac24be871236c01784f
/library/init/core.lean
13c075e03c07df8ca88a9ed99061e1ce489c4b9e
[ "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
61,631
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura notation, basic datatypes and type classes -/ prelude notation `Prop` := Sort 0 notation f ` $ `:1 a:0 := f a /- Logical operations and relations -/ reserve prefix `¬`:40 reserve prefix `~`:40 reserve infixr ` ∧ `:35 reserve infixr ` /\ `:35 reserve infixr ` \/ `:30 reserve infixr ` ∨ `:30 reserve infix ` <-> `:20 reserve infix ` ↔ `:20 reserve infix ` = `:50 reserve infix ` == `:50 reserve infix ` != `:50 reserve infix ` ~= `:50 reserve infix ` ≅ `:50 reserve infix ` ≠ `:50 reserve infix ` ≈ `:50 reserve infix ` ~ `:50 reserve infix ` ≡ `:50 reserve infixl ` ⬝ `:75 reserve infixr ` ▸ `:75 reserve infixr ` ▹ `:75 /- types and Type constructors -/ reserve infixr ` ⊕ `:30 reserve infixr ` × `:35 /- arithmetic operations -/ reserve infixl ` + `:65 reserve infixl ` - `:65 reserve infixl ` * `:70 reserve infixl ` / `:70 reserve infixl ` % `:70 reserve infixl ` %ₙ `:70 reserve prefix `-`:100 reserve infixr ` ^ `:80 reserve infixr ` ∘ `:90 reserve infix ` <= `:50 reserve infix ` ≤ `:50 reserve infix ` < `:50 reserve infix ` >= `:50 reserve infix ` ≥ `:50 reserve infix ` > `:50 /- boolean operations -/ reserve prefix `!`:40 reserve infixl ` && `:35 reserve infixl ` || `:30 /- set operations -/ reserve infix ` ∈ `:50 reserve infix ` ∉ `:50 reserve infixl ` ∩ `:70 reserve infixl ` ∪ `:65 reserve infix ` ⊆ `:50 reserve infix ` ⊇ `:50 reserve infix ` ⊂ `:50 reserve infix ` ⊃ `:50 reserve infix ` \ `:70 /- other symbols -/ reserve infix ` ∣ `:50 reserve infixl ` ++ `:65 reserve infixr ` :: `:67 /- Control -/ reserve infixr ` <|> `:2 reserve infixr `; ` :3 reserve infixr ` >>= `:55 reserve infixr ` >=> `:55 reserve infixl ` <*> `:60 reserve infixl ` <* ` :60 reserve infixr ` *> ` :60 reserve infixr ` >> ` :60 reserve infixr ` <$> `:100 reserve infixr ` <$ ` :100 reserve infixr ` $> ` :100 reserve infixl ` <&> `:100 universes u v w /-- Auxiliary unsafe constant used by the Compiler when erasing proofs from code. -/ unsafe axiom lcProof {α : Prop} : α /-- Auxiliary unsafe constant used by the Compiler to mark unreachable code. -/ unsafe axiom lcUnreachable {α : Sort u} : α @[inline] def id {α : Sort u} (a : α) : α := a def inline {α : Sort u} (a : α) : α := a @[inline] def flip {α : Sort u} {β : Sort v} {φ : Sort w} (f : α → β → φ) : β → α → φ := fun b a => f a b /- The kernel definitional equality test (t =?= s) has special support for idDelta applications. It implements the following rules 1) (idDelta t) =?= t 2) t =?= (idDelta t) 3) (idDelta t) =?= s IF (unfoldOf t) =?= s 4) t =?= idDelta s IF t =?= (unfoldOf s) This is mechanism for controlling the delta reduction (aka unfolding) used in the kernel. We use idDelta applications to address performance problems when Type checking theorems generated by the equation Compiler. -/ @[inline] def idDelta {α : Sort u} (a : α) : α := a /-- Gadget for optional parameter support. -/ @[reducible] def optParam (α : Sort u) (default : α) : Sort u := α /-- Gadget for marking output parameters in type classes. -/ @[reducible] def outParam (α : Sort u) : Sort u := α /-- Auxiliary Declaration used to implement the notation (a : α) -/ @[reducible] def typedExpr (α : Sort u) (a : α) : α := a /- `idRhs` is an auxiliary Declaration used in the equation Compiler to address performance issues when proving equational theorems. The equation Compiler uses it as a marker. -/ @[macroInline, reducible] def idRhs (α : Sort u) (a : α) : α := a inductive PUnit : Sort u | unit : PUnit /-- An abbreviation for `PUnit.{0}`, its most common instantiation. This Type should be preferred over `PUnit` where possible to avoid unnecessary universe parameters. -/ abbrev Unit : Type := PUnit @[matchPattern] abbrev Unit.unit : Unit := PUnit.unit /- Remark: thunks have an efficient implementation in the runtime. -/ structure Thunk (α : Type u) : Type u := (fn : Unit → α) attribute [extern cpp inline "lean::mk_thunk(#2)"] Thunk.mk @[noinline, extern cpp inline "lean::thunk_pure(#2)"] protected def Thunk.pure {α : Type u} (a : α) : Thunk α := ⟨fun _ => a⟩ @[noinline, extern cpp inline "lean::thunk_get_own(#2)"] protected def Thunk.get {α : Type u} (x : @& Thunk α) : α := x.fn () @[noinline, extern cpp inline "lean::thunk_map(#3, #4)"] protected def Thunk.map {α : Type u} {β : Type v} (f : α → β) (x : Thunk α) : Thunk β := ⟨fun _ => f x.get⟩ @[noinline, extern cpp inline "lean::thunk_bind(#3, #4)"] protected def Thunk.bind {α : Type u} {β : Type v} (x : Thunk α) (f : α → Thunk β) : Thunk β := ⟨fun _ => (f x.get).get⟩ /- Remark: tasks have an efficient implementation in the runtime. -/ structure Task (α : Type u) : Type u := (fn : Unit → α) attribute [extern cpp inline "lean::mk_task(#2)"] Task.mk @[noinline, extern cpp inline "lean::task_pure(#2)"] protected def Task.pure {α : Type u} (a : α) : Task α := ⟨fun _ => a⟩ @[noinline, extern cpp inline "lean::task_get(#2)"] protected def Task.get {α : Type u} (x : @& Task α) : α := x.fn () @[noinline, extern cpp inline "lean::task_map(#3, #4)"] protected def Task.map {α : Type u} {β : Type v} (f : α → β) (x : Task α) : Task β := ⟨fun _ => f x.get⟩ @[noinline, extern cpp inline "lean::task_bind(#3, #4)"] protected def Task.bind {α : Type u} {β : Type v} (x : Task α) (f : α → Task β) : Task β := ⟨fun _ => (f x.get).get⟩ inductive True : Prop | intro : True inductive False : Prop inductive Empty : Type def Not (a : Prop) : Prop := a → False prefix `¬` := Not inductive Eq {α : Sort u} (a : α) : α → Prop | refl : Eq a @[elabAsEliminator, inline, reducible] def Eq.ndrec.{u1, u2} {α : Sort u2} {a : α} {C : α → Sort u1} (m : C a) {b : α} (h : Eq a b) : C b := @Eq.rec α a (fun α _ => C α) m b h @[elabAsEliminator, inline, reducible] def Eq.ndrecOn.{u1, u2} {α : Sort u2} {a : α} {C : α → Sort u1} {b : α} (h : Eq a b) (m : C a) : C b := @Eq.rec α a (fun α _ => C α) m b h /- Initialize the Quotient Module, which effectively adds the following definitions: constant Quot {α : Sort u} (r : α → α → Prop) : Sort u constant Quot.mk {α : Sort u} (r : α → α → Prop) (a : α) : Quot r constant Quot.lift {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) : (∀ a b : α, r a b → Eq (f a) (f b)) → Quot r → β constant Quot.ind {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} : (∀ a : α, β (Quot.mk r a)) → ∀ q : Quot r, β q -/ initQuot inductive Heq {α : Sort u} (a : α) : ∀ {β : Sort u}, β → Prop | refl : Heq a structure Prod (α : Type u) (β : Type v) := (fst : α) (snd : β) /-- Similar to `Prod`, but α and β can be propositions. We use this Type internally to automatically generate the brecOn recursor. -/ structure PProd (α : Sort u) (β : Sort v) := (fst : α) (snd : β) structure And (a b : Prop) : Prop := intro :: (left : a) (right : b) structure Iff (a b : Prop) : Prop := intro :: (mp : a → b) (mpr : b → a) /- Eq basic support -/ infix = := Eq @[matchPattern] def rfl {α : Sort u} {a : α} : a = a := Eq.refl a @[elabAsEliminator] theorem Eq.subst {α : Sort u} {P : α → Prop} {a b : α} (h₁ : a = b) (h₂ : P a) : P b := Eq.ndrec h₂ h₁ infixr ▸ := Eq.subst theorem Eq.trans {α : Sort u} {a b c : α} (h₁ : a = b) (h₂ : b = c) : a = c := h₂ ▸ h₁ theorem Eq.symm {α : Sort u} {a b : α} (h : a = b) : b = a := h ▸ rfl infix ~= := Heq infix ≅ := Heq @[matchPattern] def Heq.rfl {α : Sort u} {a : α} : a ≅ a := Heq.refl a theorem eqOfHeq {α : Sort u} {a a' : α} (h : a ≅ a') : a = a' := have ∀ (α' : Sort u) (a' : α') (h₁ : @Heq α a α' a') (h₂ : α = α'), (Eq.recOn h₂ a : α') = a' := fun (α' : Sort u) (a' : α') (h₁ : @Heq α a α' a') => Heq.recOn h₁ (fun (h₂ : α = α) => rfl); show (Eq.ndrecOn (Eq.refl α) a : α) = a' from this α a' h (Eq.refl α) inductive Sum (α : Type u) (β : Type v) | inl {} (val : α) : Sum | inr {} (val : β) : Sum inductive PSum (α : Sort u) (β : Sort v) | inl {} (val : α) : PSum | inr {} (val : β) : PSum inductive Or (a b : Prop) : Prop | inl {} (h : a) : Or | inr {} (h : b) : Or def Or.introLeft {a : Prop} (b : Prop) (ha : a) : Or a b := Or.inl ha def Or.introRight (a : Prop) {b : Prop} (hb : b) : Or a b := Or.inr hb structure Sigma {α : Type u} (β : α → Type v) := mk :: (fst : α) (snd : β fst) structure PSigma {α : Sort u} (β : α → Sort v) := mk :: (fst : α) (snd : β fst) inductive Bool : Type | false : Bool | true : Bool /- Remark: Subtype must take a Sort instead of Type because of the axiom strongIndefiniteDescription. -/ structure Subtype {α : Sort u} (p : α → Prop) := (val : α) (property : p val) inductive Exists {α : Sort u} (p : α → Prop) : Prop | intro (w : α) (h : p w) : Exists class inductive Decidable (p : Prop) | isFalse (h : ¬p) : Decidable | isTrue (h : p) : Decidable @[reducible] def DecidablePred {α : Sort u} (r : α → Prop) := ∀ (a : α), Decidable (r a) @[reducible] def DecidableRel {α : Sort u} (r : α → α → Prop) := ∀ (a b : α), Decidable (r a b) class DecidableEq (α : Sort u) := {decEq : ∀ (a b : α), Decidable (a = b)} export DecidableEq (decEq) @[inline] instance decidableOfDecidableEq {α : Sort u} (a b : α) [DecidableEq α] : Decidable (a = b) := decEq a b inductive Option (α : Type u) | none {} : Option | some (val : α) : Option export Option (none some) export Bool (false true) inductive List (T : Type u) | nil {} : List | cons (hd : T) (tl : List) : List infixr :: := List.cons inductive Nat | zero : Nat | succ (n : Nat) : Nat /- Auxiliary axiom used to implement `sorry`. TODO: add this theorem on-demand. That is, we should only add it if after the first error. -/ unsafe axiom sorryAx (α : Sort u) (synthetic := true) : α /- Declare builtin and reserved notation -/ class HasZero (α : Type u) := (zero : α) class HasOne (α : Type u) := (one : α) class HasAdd (α : Type u) := (add : α → α → α) class HasMul (α : Type u) := (mul : α → α → α) class HasNeg (α : Type u) := (neg : α → α) class HasSub (α : Type u) := (sub : α → α → α) class HasDiv (α : Type u) := (div : α → α → α) class HasDivides (α : Type u) := (Divides : α → α → Prop) class HasMod (α : Type u) := (mod : α → α → α) class HasModn (α : Type u) := (modn : α → Nat → α) class HasLessEq (α : Type u) := (LessEq : α → α → Prop) class HasLess (α : Type u) := (Less : α → α → Prop) class HasBeq (α : Type u) := (beq : α → α → Bool) class HasAppend (α : Type u) := (append : α → α → α) class HasOrelse (α : Type u) := (orelse : α → α → α) class HasAndthen (α : Type u) := (andthen : α → α → α) class HasUnion (α : Type u) := (union : α → α → α) class HasInter (α : Type u) := (inter : α → α → α) class HasSDiff (α : Type u) := (sdiff : α → α → α) class HasEquiv (α : Sort u) := (Equiv : α → α → Prop) class HasSubset (α : Type u) := (Subset : α → α → Prop) class HasSSubset (α : Type u) := (SSubset : α → α → Prop) /- Type classes HasEmptyc and HasInsert are used to implement polymorphic notation for collections. Example: {a, b, c}. -/ class HasEmptyc (α : Type u) := (emptyc : α) class HasInsert (α : outParam $ Type u) (γ : Type v) := (insert : α → γ → γ) /- Type class used to implement the notation { a ∈ c | p a } -/ class HasSep (α : outParam $ Type u) (γ : Type v) := (sep : (α → Prop) → γ → γ) /- Type class for set-like membership -/ class HasMem (α : outParam $ Type u) (γ : Type v) := (mem : α → γ → Prop) class HasPow (α : Type u) (β : Type v) := (pow : α → β → α) export HasAndthen (andthen) export HasPow (pow) infix ∈ := HasMem.mem notation a ` ∉ ` s := ¬ HasMem.mem a s infix + := HasAdd.add infix * := HasMul.mul infix - := HasSub.sub infix / := HasDiv.div infix ∣ := HasDivides.Divides infix % := HasMod.mod infix %ₙ := HasModn.modn prefix - := HasNeg.neg infix <= := HasLessEq.LessEq infix ≤ := HasLessEq.LessEq infix < := HasLess.Less infix == := HasBeq.beq infix ++ := HasAppend.append notation `∅` := HasEmptyc.emptyc _ infix ∪ := HasUnion.union infix ∩ := HasInter.inter infix ⊆ := HasSubset.Subset infix ⊂ := HasSSubset.SSubset infix \ := HasSDiff.sdiff infix ≈ := HasEquiv.Equiv infixr ^ := HasPow.pow infixr /\ := And infixr ∧ := And infixr \/ := Or infixr ∨ := Or infix <-> := Iff infix ↔ := Iff -- notation `exists` binders `, ` r:(scoped P, Exists P) := r -- notation `∃` binders `, ` r:(scoped P, Exists P) := r infixr <|> := HasOrelse.orelse infixr >> := HasAndthen.andthen export HasAppend (append) @[reducible] def GreaterEq {α : Type u} [HasLessEq α] (a b : α) : Prop := HasLessEq.LessEq b a @[reducible] def Greater {α : Type u} [HasLess α] (a b : α) : Prop := HasLess.Less b a infix >= := GreaterEq infix ≥ := GreaterEq infix > := Greater @[reducible] def Superset {α : Type u} [HasSubset α] (a b : α) : Prop := HasSubset.Subset b a @[reducible] def SSuperset {α : Type u} [HasSSubset α] (a b : α) : Prop := HasSSubset.SSubset b a infix ⊇ := Superset infix ⊃ := SSuperset @[inline] def bit0 {α : Type u} [s : HasAdd α] (a : α) : α := a + a @[inline] def bit1 {α : Type u} [s₁ : HasOne α] [s₂ : HasAdd α] (a : α) : α := (bit0 a) + 1 attribute [matchPattern] HasZero.zero HasOne.one bit0 bit1 HasAdd.add HasNeg.neg export HasInsert (insert) /- The Empty collection -/ @[inline] def singleton {α : Type u} {γ : Type v} [HasEmptyc γ] [HasInsert α γ] (a : α) : γ := HasInsert.insert a ∅ /- Nat basic instances -/ @[extern cpp "lean::nat_add"] protected def Nat.add : (@& Nat) → (@& Nat) → Nat | a Nat.zero := a | a (Nat.succ b) := Nat.succ (Nat.add a b) /- We mark the following definitions as pattern to make sure they can be used in recursive equations, and reduced by the equation Compiler. -/ attribute [matchPattern] Nat.add Nat.add._main instance : HasZero Nat := ⟨Nat.zero⟩ instance : HasOne Nat := ⟨Nat.succ (Nat.zero)⟩ instance : HasAdd Nat := ⟨Nat.add⟩ /- Auxiliary constant used by equation compiler. -/ constant hugeFuel : Nat := 10000 def std.priority.default : Nat := 1000 def std.priority.max : Nat := 0xFFFFFFFF protected def Nat.prio := std.priority.default + 100 /- Global declarations of right binding strength If a Module reassigns these, it will be incompatible with other modules that adhere to these conventions. When hovering over a symbol, use "C-c C-k" to see how to input it. -/ def std.prec.max : Nat := 1024 -- the strength of application, identifiers, (, [, etc. def std.prec.arrow : Nat := 25 /- The next def is "max + 10". It can be used e.g. for postfix operations that should be stronger than application. -/ def std.prec.maxPlus : Nat := std.prec.max + 10 infixr × := Prod -- notation for n-ary tuples /- Some type that is not a scalar value in our runtime. TODO: mark opaque -/ structure NonScalar := (val : Nat) /- sizeof -/ class HasSizeof (α : Sort u) := (sizeof : α → Nat) export HasSizeof (sizeof) /- Declare sizeof instances and theorems for types declared before HasSizeof. From now on, the inductive Compiler will automatically generate sizeof instances and theorems. -/ /- Every Type `α` has a default HasSizeof instance that just returns 0 for every element of `α` -/ protected def default.sizeof (α : Sort u) : α → Nat | a := 0 instance defaultHasSizeof (α : Sort u) : HasSizeof α := ⟨default.sizeof α⟩ protected def Nat.sizeof : Nat → Nat | n := n instance : HasSizeof Nat := ⟨Nat.sizeof⟩ protected def Prod.sizeof {α : Type u} {β : Type v} [HasSizeof α] [HasSizeof β] : (Prod α β) → Nat | ⟨a, b⟩ := 1 + sizeof a + sizeof b instance (α : Type u) (β : Type v) [HasSizeof α] [HasSizeof β] : HasSizeof (Prod α β) := ⟨Prod.sizeof⟩ protected def Sum.sizeof {α : Type u} {β : Type v} [HasSizeof α] [HasSizeof β] : (Sum α β) → Nat | (Sum.inl a) := 1 + sizeof a | (Sum.inr b) := 1 + sizeof b instance (α : Type u) (β : Type v) [HasSizeof α] [HasSizeof β] : HasSizeof (Sum α β) := ⟨Sum.sizeof⟩ protected def PSum.sizeof {α : Type u} {β : Type v} [HasSizeof α] [HasSizeof β] : (PSum α β) → Nat | (PSum.inl a) := 1 + sizeof a | (PSum.inr b) := 1 + sizeof b instance (α : Type u) (β : Type v) [HasSizeof α] [HasSizeof β] : HasSizeof (PSum α β) := ⟨PSum.sizeof⟩ protected def Sigma.sizeof {α : Type u} {β : α → Type v} [HasSizeof α] [∀ a, HasSizeof (β a)] : Sigma β → Nat | ⟨a, b⟩ := 1 + sizeof a + sizeof b instance (α : Type u) (β : α → Type v) [HasSizeof α] [∀ a, HasSizeof (β a)] : HasSizeof (Sigma β) := ⟨Sigma.sizeof⟩ protected def PSigma.sizeof {α : Type u} {β : α → Type v} [HasSizeof α] [∀ a, HasSizeof (β a)] : PSigma β → Nat | ⟨a, b⟩ := 1 + sizeof a + sizeof b instance (α : Type u) (β : α → Type v) [HasSizeof α] [∀ a, HasSizeof (β a)] : HasSizeof (PSigma β) := ⟨PSigma.sizeof⟩ protected def PUnit.sizeof : PUnit → Nat | u := 1 instance : HasSizeof PUnit := ⟨PUnit.sizeof⟩ protected def Bool.sizeof : Bool → Nat | b := 1 instance : HasSizeof Bool := ⟨Bool.sizeof⟩ protected def Option.sizeof {α : Type u} [HasSizeof α] : Option α → Nat | none := 1 | (some a) := 1 + sizeof a instance (α : Type u) [HasSizeof α] : HasSizeof (Option α) := ⟨Option.sizeof⟩ protected def List.sizeof {α : Type u} [HasSizeof α] : List α → Nat | List.nil := 1 | (List.cons a l) := 1 + sizeof a + List.sizeof l instance (α : Type u) [HasSizeof α] : HasSizeof (List α) := ⟨List.sizeof⟩ protected def Subtype.sizeof {α : Type u} [HasSizeof α] {p : α → Prop} : Subtype p → Nat | ⟨a, _⟩ := sizeof a instance {α : Type u} [HasSizeof α] (p : α → Prop) : HasSizeof (Subtype p) := ⟨Subtype.sizeof⟩ theorem natAddZero (n : Nat) : n + 0 = n := rfl theorem optParamEq (α : Sort u) (default : α) : optParam α default = α := rfl /-- Like `by applyInstance`, but not dependent on the tactic framework. -/ @[reducible] def inferInstance {α : Type u} [i : α] : α := i @[reducible, elabSimple] def inferInstanceAs (α : Type u) [i : α] : α := i /- Boolean operators -/ @[macroInline] def cond {a : Type u} : Bool → a → a → a | true x y := x | false x y := y @[macroInline] def or : Bool → Bool → Bool | true _ := true | false b := b @[macroInline] def and : Bool → Bool → Bool | false _ := false | true b := b @[macroInline] def not : Bool → Bool | true := false | false := true @[macroInline] def xor : Bool → Bool → Bool | true b := not b | false b := b prefix ! := not infix || := or infix && := and @[extern cpp inline "#1 || #2"] def strictOr (b₁ b₂ : Bool) := b₁ || b₂ @[extern cpp inline "#1 && #2"] def strictAnd (b₁ b₂ : Bool) := b₁ && b₂ @[inline] def bne {α : Type u} [HasBeq α] (a b : α) : Bool := !(a == b) infix != := bne /- Logical connectives an equality -/ def implies (a b : Prop) := a → b theorem implies.trans {p q r : Prop} (h₁ : implies p q) (h₂ : implies q r) : implies p r := fun hp => h₂ (h₁ hp) def trivial : True := ⟨⟩ @[macroInline] def False.elim {C : Sort u} (h : False) : C := False.rec (fun _ => C) h @[macroInline] def absurd {a : Prop} {b : Sort v} (h₁ : a) (h₂ : ¬a) : b := False.elim (h₂ h₁) theorem mt {a b : Prop} (h₁ : a → b) (h₂ : ¬b) : ¬a := fun ha => h₂ (h₁ ha) theorem notFalse : ¬False := id -- proof irrelevance is built in theorem proofIrrel {a : Prop} (h₁ h₂ : a) : h₁ = h₂ := rfl theorem id.def {α : Sort u} (a : α) : id a = a := rfl @[macroInline] def Eq.mp {α β : Sort u} (h₁ : α = β) (h₂ : α) : β := Eq.recOn h₁ h₂ @[macroInline] def Eq.mpr {α β : Sort u} : (α = β) → β → α := fun h₁ h₂ => Eq.recOn (Eq.symm h₁) h₂ @[elabAsEliminator] theorem Eq.substr {α : Sort u} {p : α → Prop} {a b : α} (h₁ : b = a) (h₂ : p a) : p b := Eq.subst (Eq.symm h₁) h₂ theorem congr {α : Sort u} {β : Sort v} {f₁ f₂ : α → β} {a₁ a₂ : α} (h₁ : f₁ = f₂) (h₂ : a₁ = a₂) : f₁ a₁ = f₂ a₂ := Eq.subst h₁ (Eq.subst h₂ rfl) theorem congrFun {α : Sort u} {β : α → Sort v} {f g : ∀ x, β x} (h : f = g) (a : α) : f a = g a := Eq.subst h (Eq.refl (f a)) theorem congrArg {α : Sort u} {β : Sort v} {a₁ a₂ : α} (f : α → β) (h : a₁ = a₂) : f a₁ = f a₂ := congr rfl h theorem transRelLeft {α : Sort u} {a b c : α} (r : α → α → Prop) (h₁ : r a b) (h₂ : b = c) : r a c := h₂ ▸ h₁ theorem transRelRight {α : Sort u} {a b c : α} (r : α → α → Prop) (h₁ : a = b) (h₂ : r b c) : r a c := h₁.symm ▸ h₂ theorem ofEqTrue {p : Prop} (h : p = True) : p := h.symm ▸ trivial theorem notOfEqFalse {p : Prop} (h : p = False) : ¬p := fun hp => h ▸ hp @[macroInline] def cast {α β : Sort u} (h : α = β) (a : α) : β := Eq.rec a h theorem castProofIrrel {α β : Sort u} (h₁ h₂ : α = β) (a : α) : cast h₁ a = cast h₂ a := rfl theorem castEq {α : Sort u} (h : α = α) (a : α) : cast h a = a := rfl @[reducible] def Ne {α : Sort u} (a b : α) := ¬(a = b) infix ≠ := Ne theorem Ne.def {α : Sort u} (a b : α) : a ≠ b = ¬ (a = b) := rfl section Ne variable {α : Sort u} variables {a b : α} {p : Prop} theorem Ne.intro (h : a = b → False) : a ≠ b := h theorem Ne.elim (h : a ≠ b) : a = b → False := h theorem Ne.irrefl (h : a ≠ a) : False := h rfl theorem Ne.symm (h : a ≠ b) : b ≠ a := fun h₁ => h (h₁.symm) theorem falseOfNe : a ≠ a → False := Ne.irrefl theorem neFalseOfSelf : p → p ≠ False := fun (hp : p) (Heq : p = False) => Heq ▸ hp theorem neTrueOfNot : ¬p → p ≠ True := fun (hnp : ¬p) (Heq : p = True) => (Heq ▸ hnp) trivial theorem trueNeFalse : ¬True = False := neFalseOfSelf trivial end Ne theorem eqFalseOfNeTrue : ∀ {b : Bool}, b ≠ true → b = false | true h := False.elim (h rfl) | false h := rfl theorem eqTrueOfNeFalse : ∀ {b : Bool}, b ≠ false → b = true | true h := rfl | false h := False.elim (h rfl) section variables {α β φ : Sort u} {a a' : α} {b b' : β} {c : φ} @[elabAsEliminator] theorem Heq.ndrec.{u1, u2} {α : Sort u2} {a : α} {C : ∀ {β : Sort u2}, β → Sort u1} (m : C a) {β : Sort u2} {b : β} (h : a ≅ b) : C b := @Heq.rec α a (fun β b _ => C b) m β b h @[elabAsEliminator] theorem Heq.ndrecOn.{u1, u2} {α : Sort u2} {a : α} {C : ∀ {β : Sort u2}, β → Sort u1} {β : Sort u2} {b : β} (h : a ≅ b) (m : C a) : C b := @Heq.rec α a (fun β b _ => C b) m β b h theorem Heq.elim {α : Sort u} {a : α} {p : α → Sort v} {b : α} (h₁ : a ≅ b) (h₂ : p a) : p b := Eq.recOn (eqOfHeq h₁) h₂ theorem Heq.subst {p : ∀ (T : Sort u), T → Prop} (h₁ : a ≅ b) (h₂ : p α a) : p β b := Heq.ndrecOn h₁ h₂ theorem Heq.symm (h : a ≅ b) : b ≅ a := Heq.ndrecOn h (Heq.refl a) theorem heqOfEq (h : a = a') : a ≅ a' := Eq.subst h (Heq.refl a) theorem Heq.trans (h₁ : a ≅ b) (h₂ : b ≅ c) : a ≅ c := Heq.subst h₂ h₁ theorem heqOfHeqOfEq (h₁ : a ≅ b) (h₂ : b = b') : a ≅ b' := Heq.trans h₁ (heqOfEq h₂) theorem heqOfEqOfHeq (h₁ : a = a') (h₂ : a' ≅ b) : a ≅ b := Heq.trans (heqOfEq h₁) h₂ def typeEqOfHeq (h : a ≅ b) : α = β := Heq.ndrecOn h (Eq.refl α) end theorem eqRecHeq {α : Sort u} {φ : α → Sort v} : ∀ {a a' : α} (h : a = a') (p : φ a), (Eq.recOn h p : φ a') ≅ p | a _ rfl p := Heq.refl p theorem ofHeqTrue {a : Prop} (h : a ≅ True) : a := ofEqTrue (eqOfHeq h) theorem castHeq : ∀ {α β : Sort u} (h : α = β) (a : α), cast h a ≅ a | α _ rfl a := Heq.refl a variables {a b c d : Prop} theorem And.elim (h₁ : a ∧ b) (h₂ : a → b → c) : c := And.rec h₂ h₁ theorem And.swap : a ∧ b → b ∧ a := fun ⟨ha, hb⟩ => ⟨hb, ha⟩ def And.symm := @And.swap theorem Or.elim (h₁ : a ∨ b) (h₂ : a → c) (h₃ : b → c) : c := Or.rec h₂ h₃ h₁ theorem Or.swap (h : a ∨ b) : b ∨ a := Or.elim h Or.inr Or.inl def Or.symm := @Or.swap /- xor -/ def Xor (a b : Prop) : Prop := (a ∧ ¬ b) ∨ (b ∧ ¬ a) theorem Iff.elim (h₁ : (a → b) → (b → a) → c) (h₂ : a ↔ b) : c := Iff.rec h₁ h₂ theorem Iff.left : (a ↔ b) → a → b := Iff.mp theorem Iff.right : (a ↔ b) → b → a := Iff.mpr theorem iffIffImpliesAndImplies (a b : Prop) : (a ↔ b) ↔ (a → b) ∧ (b → a) := Iff.intro (fun h => And.intro h.mp h.mpr) (fun h => Iff.intro h.left h.right) theorem Iff.refl (a : Prop) : a ↔ a := Iff.intro (fun h => h) (fun h => h) theorem Iff.rfl {a : Prop} : a ↔ a := Iff.refl a theorem Iff.trans (h₁ : a ↔ b) (h₂ : b ↔ c) : a ↔ c := Iff.intro (fun ha => Iff.mp h₂ (Iff.mp h₁ ha)) (fun hc => Iff.mpr h₁ (Iff.mpr h₂ hc)) theorem Iff.symm (h : a ↔ b) : b ↔ a := Iff.intro (Iff.right h) (Iff.left h) theorem Iff.comm : (a ↔ b) ↔ (b ↔ a) := Iff.intro Iff.symm Iff.symm theorem Eq.toIff {a b : Prop} (h : a = b) : a ↔ b := Eq.recOn h Iff.rfl theorem neqOfNotIff {a b : Prop} : ¬(a ↔ b) → a ≠ b := fun h₁ h₂ => have a ↔ b from Eq.subst h₂ (Iff.refl a); absurd this h₁ theorem notIffNotOfIff (h₁ : a ↔ b) : ¬a ↔ ¬b := Iff.intro (fun (hna : ¬ a) (hb : b) => hna (Iff.right h₁ hb)) (fun (hnb : ¬ b) (ha : a) => hnb (Iff.left h₁ ha)) theorem ofIffTrue (h : a ↔ True) : a := Iff.mp (Iff.symm h) trivial theorem notOfIffFalse : (a ↔ False) → ¬a := Iff.mp theorem iffTrueIntro (h : a) : a ↔ True := Iff.intro (fun hl => trivial) (fun hr => h) theorem iffFalseIntro (h : ¬a) : a ↔ False := Iff.intro h (False.rec (fun _ => a)) theorem notNotIntro (ha : a) : ¬¬a := fun hna => hna ha theorem notTrue : (¬ True) ↔ False := iffFalseIntro (notNotIntro trivial) /- or resolution rulses -/ theorem resolveLeft {a b : Prop} (h : a ∨ b) (na : ¬ a) : b := Or.elim h (fun ha => absurd ha na) id theorem negResolveLeft {a b : Prop} (h : ¬ a ∨ b) (ha : a) : b := Or.elim h (fun na => absurd ha na) id theorem resolveRight {a b : Prop} (h : a ∨ b) (nb : ¬ b) : a := Or.elim h id (fun hb => absurd hb nb) theorem negResolveRight {a b : Prop} (h : a ∨ ¬ b) (hb : b) : a := Or.elim h id (fun nb => absurd hb nb) /- Exists -/ theorem Exists.elim {α : Sort u} {p : α → Prop} {b : Prop} (h₁ : Exists (fun x => p x)) (h₂ : ∀ (a : α), p a → b) : b := Exists.rec h₂ h₁ /- Decidable -/ @[inlineIfReduce, nospecialize] def Decidable.decide (p : Prop) [h : Decidable p] : Bool := Decidable.casesOn h (fun h₁ => false) (fun h₂ => true) export Decidable (isTrue isFalse decide) instance beqOfEq {α : Type u} [DecidableEq α] : HasBeq α := ⟨fun a b => decide (a = b)⟩ theorem decideTrueEqTrue (h : Decidable True) : @decide True h = true := Decidable.casesOn h (fun h => False.elim (Iff.mp notTrue h)) (fun _ => rfl) theorem decideFalseEqFalse (h : Decidable False) : @decide False h = false := Decidable.casesOn h (fun h => rfl) (fun h => False.elim h) instance : Decidable True := isTrue trivial instance : Decidable False := isFalse notFalse -- We use "dependent" if-then-else to be able to communicate the if-then-else condition -- to the branches @[macroInline] def dite (c : Prop) [h : Decidable c] {α : Sort u} : (c → α) → (¬ c → α) → α := fun t e => Decidable.casesOn h e t /- if-then-else -/ @[macroInline] def ite (c : Prop) [h : Decidable c] {α : Sort u} (t e : α) : α := Decidable.casesOn h (fun hnc => e) (fun hc => t) namespace Decidable variables {p q : Prop} def recOnTrue [h : Decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} (h₃ : p) (h₄ : h₁ h₃) : (Decidable.recOn h h₂ h₁ : Sort u) := Decidable.casesOn h (fun h => False.rec _ (h h₃)) (fun h => h₄) def recOnFalse [h : Decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} (h₃ : ¬p) (h₄ : h₂ h₃) : (Decidable.recOn h h₂ h₁ : Sort u) := Decidable.casesOn h (fun h => h₄) (fun h => False.rec _ (h₃ h)) @[macroInline] def byCases {q : Sort u} [s : Decidable p] (h1 : p → q) (h2 : ¬p → q) : q := match s with | isTrue h => h1 h | isFalse h => h2 h theorem em (p : Prop) [Decidable p] : p ∨ ¬p := byCases Or.inl Or.inr theorem byContradiction [Decidable p] (h : ¬p → False) : p := byCases id (fun np => False.elim (h np)) theorem ofNotNot [Decidable p] : ¬ ¬ p → p := fun hnn => byContradiction (fun hn => absurd hn hnn) theorem notNotIff (p) [Decidable p] : (¬ ¬ p) ↔ p := Iff.intro ofNotNot notNotIntro theorem notAndIffOrNot (p q : Prop) [d₁ : Decidable p] [d₂ : Decidable q] : ¬ (p ∧ q) ↔ ¬ p ∨ ¬ q := Iff.intro (fun h => match d₁, d₂ with | isTrue h₁, isTrue h₂ => absurd (And.intro h₁ h₂) h | _, isFalse h₂ => Or.inr h₂ | isFalse h₁, _ => Or.inl h₁) (fun (h) ⟨hp, hq⟩ => Or.elim h (fun h => h hp) (fun h => h hq)) end Decidable section variables {p q : Prop} @[inline] def decidableOfDecidableOfIff (hp : Decidable p) (h : p ↔ q) : Decidable q := if hp : p then isTrue (Iff.mp h hp) else isFalse (Iff.mp (notIffNotOfIff h) hp) @[inline] def decidableOfDecidableOfEq (hp : Decidable p) (h : p = q) : Decidable q := decidableOfDecidableOfIff hp h.toIff end section variables {p q : Prop} @[macroInline] instance [Decidable p] [Decidable q] : Decidable (p ∧ q) := if hp : p then if hq : q then isTrue ⟨hp, hq⟩ else isFalse (fun h => hq (And.right h)) else isFalse (fun h => hp (And.left h)) @[macroInline] instance [Decidable p] [Decidable q] : Decidable (p ∨ q) := if hp : p then isTrue (Or.inl hp) else if hq : q then isTrue (Or.inr hq) else isFalse (fun h => Or.elim h hp hq) instance [Decidable p] : Decidable (¬p) := if hp : p then isFalse (absurd hp) else isTrue hp @[macroInline] instance implies.Decidable [Decidable p] [Decidable q] : Decidable (p → q) := if hp : p then if hq : q then isTrue (fun h => hq) else isFalse (fun h => absurd (h hp) hq) else isTrue (fun h => absurd h hp) instance [Decidable p] [Decidable q] : Decidable (p ↔ q) := if hp : p then if hq : q then isTrue ⟨fun _ => hq, fun _ => hp⟩ else isFalse $ fun h => hq (h.1 hp) else if hq : q then isFalse $ fun h => hp (h.2 hq) else isTrue $ ⟨fun h => absurd h hp, fun h => absurd h hq⟩ instance [Decidable p] [Decidable q] : Decidable (Xor p q) := if hp : p then if hq : q then isFalse (fun h => Or.elim h (fun ⟨_, h⟩ => h hq : ¬(p ∧ ¬ q)) (fun ⟨_, h⟩ => h hp : ¬(q ∧ ¬ p))) else isTrue $ Or.inl ⟨hp, hq⟩ else if hq : q then isTrue $ Or.inr ⟨hq, hp⟩ else isFalse (fun h => Or.elim h (fun ⟨h, _⟩ => hp h : ¬(p ∧ ¬ q)) (fun ⟨h, _⟩ => hq h : ¬(q ∧ ¬ p))) end @[inline] instance {α : Sort u} [DecidableEq α] (a b : α) : Decidable (a ≠ b) := match decEq a b with | isTrue h => isFalse $ fun h' => absurd h h' | isFalse h => isTrue h theorem Bool.falseNeTrue (h : false = true) : False := Bool.noConfusion h instance : DecidableEq Bool := {decEq := fun a b => match a, b with | false, false => isTrue rfl | false, true => isFalse Bool.falseNeTrue | true, false => isFalse (Ne.symm Bool.falseNeTrue) | true, true => isTrue rfl} /- if-then-else expression theorems -/ theorem ifPos {c : Prop} [h : Decidable c] (hc : c) {α : Sort u} {t e : α} : (ite c t e) = t := match h with | (isTrue hc) => rfl | (isFalse hnc) => absurd hc hnc theorem ifNeg {c : Prop} [h : Decidable c] (hnc : ¬c) {α : Sort u} {t e : α} : (ite c t e) = e := match h with | (isTrue hc) => absurd hc hnc | (isFalse hnc) => rfl -- Remark: dite and ite are "defally equal" when we ignore the proofs. theorem difEqIf (c : Prop) [h : Decidable c] {α : Sort u} (t : α) (e : α) : dite c (fun h => t) (fun h => e) = ite c t e := match h with | (isTrue hc) => rfl | (isFalse hnc) => rfl instance {c t e : Prop} [dC : Decidable c] [dT : Decidable t] [dE : Decidable e] : Decidable (if c then t else e) := match dC with | (isTrue hc) => dT | (isFalse hc) => dE instance {c : Prop} {t : c → Prop} {e : ¬c → Prop} [dC : Decidable c] [dT : ∀ h, Decidable (t h)] [dE : ∀ h, Decidable (e h)] : Decidable (if h : c then t h else e h) := match dC with | (isTrue hc) => dT hc | (isFalse hc) => dE hc /-- Universe lifting operation -/ structure ULift.{r, s} (α : Type s) : Type (max s r) := up :: (down : α) namespace ULift /- Bijection between α and ULift.{v} α -/ theorem upDown {α : Type u} : ∀ (b : ULift.{v} α), up (down b) = b | (up a) := rfl theorem downUp {α : Type u} (a : α) : down (up.{v} a) = a := rfl end ULift /-- Universe lifting operation from Sort to Type -/ structure PLift (α : Sort u) : Type u := up :: (down : α) namespace PLift /- Bijection between α and PLift α -/ theorem upDown {α : Sort u} : ∀ (b : PLift α), up (down b) = b | (up a) := rfl theorem downUp {α : Sort u} (a : α) : down (up a) = a := rfl end PLift /- pointed types -/ structure PointedType := (type : Type u) (val : type) /- Inhabited -/ class Inhabited (α : Sort u) := (default : α) constant default (α : Sort u) [Inhabited α] : α := Inhabited.default α @[inline, irreducible] def arbitrary (α : Sort u) [Inhabited α] : α := default α instance Prop.Inhabited : Inhabited Prop := ⟨True⟩ instance Fun.Inhabited (α : Sort u) {β : Sort v} [h : Inhabited β] : Inhabited (α → β) := Inhabited.casesOn h (fun b => ⟨fun a => b⟩) instance Forall.Inhabited (α : Sort u) {β : α → Sort v} [∀ x, Inhabited (β x)] : Inhabited (∀ x, β x) := ⟨fun a => default (β a)⟩ instance : Inhabited Bool := ⟨false⟩ instance : Inhabited True := ⟨trivial⟩ instance : Inhabited Nat := ⟨0⟩ instance : Inhabited NonScalar := ⟨⟨default _⟩⟩ instance : Inhabited PointedType := ⟨{type := PUnit, val := ⟨⟩}⟩ class inductive Nonempty (α : Sort u) : Prop | intro (val : α) : Nonempty protected def Nonempty.elim {α : Sort u} {p : Prop} (h₁ : Nonempty α) (h₂ : α → p) : p := Nonempty.rec h₂ h₁ instance nonemptyOfInhabited {α : Sort u} [Inhabited α] : Nonempty α := ⟨default α⟩ theorem nonemptyOfExists {α : Sort u} {p : α → Prop} : Exists (fun x => p x) → Nonempty α | ⟨w, h⟩ := ⟨w⟩ /- Subsingleton -/ class inductive Subsingleton (α : Sort u) : Prop | intro (h : ∀ (a b : α), a = b) : Subsingleton protected def Subsingleton.elim {α : Sort u} [h : Subsingleton α] : ∀ (a b : α), a = b := Subsingleton.casesOn h (fun p => p) protected def Subsingleton.helim {α β : Sort u} [h : Subsingleton α] (h : α = β) : ∀ (a : α) (b : β), a ≅ b := Eq.recOn h (fun a b => heqOfEq (Subsingleton.elim a b)) instance subsingletonProp (p : Prop) : Subsingleton p := ⟨fun a b => proofIrrel a b⟩ instance (p : Prop) : Subsingleton (Decidable p) := Subsingleton.intro $ fun d₁ => match d₁ with | (isTrue t₁) => fun d₂ => match d₂ with | (isTrue t₂) => Eq.recOn (proofIrrel t₁ t₂) rfl | (isFalse f₂) => absurd t₁ f₂ | (isFalse f₁) => fun d₂ => match d₂ with | (isTrue t₂) => absurd t₂ f₁ | (isFalse f₂) => Eq.recOn (proofIrrel f₁ f₂) rfl protected theorem recSubsingleton {p : Prop} [h : Decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} [h₃ : ∀ (h : p), Subsingleton (h₁ h)] [h₄ : ∀ (h : ¬p), Subsingleton (h₂ h)] : Subsingleton (Decidable.casesOn h h₂ h₁) := match h with | (isTrue h) => h₃ h | (isFalse h) => h₄ h section relation variables {α : Sort u} {β : Sort v} (r : β → β → Prop) def Reflexive := ∀ x, r x x def Symmetric := ∀ {x y}, r x y → r y x def Transitive := ∀ {x y z}, r x y → r y z → r x z def Equivalence := Reflexive r ∧ Symmetric r ∧ Transitive r def Total := ∀ x y, r x y ∨ r y x def mkEquivalence (rfl : Reflexive r) (symm : Symmetric r) (trans : Transitive r) : Equivalence r := ⟨rfl, @symm, @trans⟩ def Irreflexive := ∀ x, ¬ r x x def AntiSymmetric := ∀ {x y}, r x y → r y x → x = y def emptyRelation (a₁ a₂ : α) : Prop := False def Subrelation (q r : β → β → Prop) := ∀ {x y}, q x y → r x y def InvImage (f : α → β) : α → α → Prop := fun a₁ a₂ => r (f a₁) (f a₂) theorem InvImage.Transitive (f : α → β) (h : Transitive r) : Transitive (InvImage r f) := fun (a₁ a₂ a₃ : α) (h₁ : InvImage r f a₁ a₂) (h₂ : InvImage r f a₂ a₃) => h h₁ h₂ theorem InvImage.Irreflexive (f : α → β) (h : Irreflexive r) : Irreflexive (InvImage r f) := fun (a : α) (h₁ : InvImage r f a a) => h (f a) h₁ inductive TC {α : Sort u} (r : α → α → Prop) : α → α → Prop | base : ∀ a b, r a b → TC a b | trans : ∀ a b c, TC a b → TC b c → TC a c @[elabAsEliminator] theorem TC.ndrec.{u1, u2} {α : Sort u} {r : α → α → Prop} {C : α → α → Prop} (m₁ : ∀ (a b : α), r a b → C a b) (m₂ : ∀ (a b c : α), TC r a b → TC r b c → C a b → C b c → C a c) {a b : α} (h : TC r a b) : C a b := @TC.rec α r (fun a b _ => C a b) m₁ m₂ a b h @[elabAsEliminator] theorem TC.ndrecOn.{u1, u2} {α : Sort u} {r : α → α → Prop} {C : α → α → Prop} {a b : α} (h : TC r a b) (m₁ : ∀ (a b : α), r a b → C a b) (m₂ : ∀ (a b c : α), TC r a b → TC r b c → C a b → C b c → C a c) : C a b := @TC.rec α r (fun a b _ => C a b) m₁ m₂ a b h end relation section Binary variables {α : Type u} {β : Type v} variable f : α → α → α def Commutative := ∀ a b, f a b = f b a def Associative := ∀ a b c, f (f a b) c = f a (f b c) def RightCommutative (h : β → α → β) := ∀ b a₁ a₂, h (h b a₁) a₂ = h (h b a₂) a₁ def LeftCommutative (h : α → β → β) := ∀ a₁ a₂ b, h a₁ (h a₂ b) = h a₂ (h a₁ b) theorem leftComm : Commutative f → Associative f → LeftCommutative f := fun hcomm hassoc a b c => ((Eq.symm (hassoc a b c)).trans (hcomm a b ▸ rfl : f (f a b) c = f (f b a) c)).trans (hassoc b a c) theorem rightComm : Commutative f → Associative f → RightCommutative f := fun hcomm hassoc a b c => ((hassoc a b c).trans (hcomm b c ▸ rfl : f a (f b c) = f a (f c b))).trans (Eq.symm (hassoc a c b)) end Binary /- Subtype -/ namespace Subtype def existsOfSubtype {α : Type u} {p : α → Prop} : { x // p x } → Exists (fun x => p x) | ⟨a, h⟩ := ⟨a, h⟩ variables {α : Type u} {p : α → Prop} theorem tagIrrelevant {a : α} (h1 h2 : p a) : mk a h1 = mk a h2 := rfl protected theorem eq : ∀ {a1 a2 : {x // p x}}, val a1 = val a2 → a1 = a2 | ⟨x, h1⟩ ⟨.(x), h2⟩ rfl := rfl theorem eta (a : {x // p x}) (h : p (val a)) : mk (val a) h = a := Subtype.eq rfl instance {α : Type u} {p : α → Prop} {a : α} (h : p a) : Inhabited {x // p x} := ⟨⟨a, h⟩⟩ instance {α : Type u} {p : α → Prop} [DecidableEq α] : DecidableEq {x : α // p x} := {decEq := fun ⟨a, h₁⟩ ⟨b, h₂⟩ => if h : a = b then isTrue (Subtype.eq h) else isFalse (fun h' => Subtype.noConfusion h' (fun h' => absurd h' h))} end Subtype /- Sum -/ infixr ⊕ := Sum section variables {α : Type u} {β : Type v} instance Sum.inhabitedLeft [h : Inhabited α] : Inhabited (α ⊕ β) := ⟨Sum.inl (default α)⟩ instance Sum.inhabitedRight [h : Inhabited β] : Inhabited (α ⊕ β) := ⟨Sum.inr (default β)⟩ instance {α : Type u} {β : Type v} [DecidableEq α] [DecidableEq β] : DecidableEq (α ⊕ β) := {decEq := fun a b => match a, b with | (Sum.inl a), (Sum.inl b) => if h : a = b then isTrue (h ▸ rfl) else isFalse (fun h' => Sum.noConfusion h' (fun h' => absurd h' h)) | (Sum.inr a), (Sum.inr b) => if h : a = b then isTrue (h ▸ rfl) else isFalse (fun h' => Sum.noConfusion h' (fun h' => absurd h' h)) | (Sum.inr a), (Sum.inl b) => isFalse (fun h => Sum.noConfusion h) | (Sum.inl a), (Sum.inr b) => isFalse (fun h => Sum.noConfusion h)} end /- Product -/ section variables {α : Type u} {β : Type v} instance [Inhabited α] [Inhabited β] : Inhabited (Prod α β) := ⟨(default α, default β)⟩ instance [DecidableEq α] [DecidableEq β] : DecidableEq (α × β) := {decEq := fun ⟨a, b⟩ ⟨a', b'⟩ => match (decEq a a') with | (isTrue e₁) => match (decEq b b') with | (isTrue e₂) => isTrue (Eq.recOn e₁ (Eq.recOn e₂ rfl)) | (isFalse n₂) => isFalse (fun h => Prod.noConfusion h (fun e₁' e₂' => absurd e₂' n₂)) | (isFalse n₁) => isFalse (fun h => Prod.noConfusion h (fun e₁' e₂' => absurd e₁' n₁))} instance [HasLess α] [HasLess β] : HasLess (α × β) := ⟨fun s t => s.1 < t.1 ∨ (s.1 = t.1 ∧ s.2 < t.2)⟩ instance prodHasDecidableLt [HasLess α] [HasLess β] [DecidableEq α] [DecidableEq β] [∀ (a b : α), Decidable (a < b)] [∀ (a b : β), Decidable (a < b)] : ∀ (s t : α × β), Decidable (s < t) := fun t s => Or.Decidable theorem Prod.ltDef [HasLess α] [HasLess β] (s t : α × β) : (s < t) = (s.1 < t.1 ∨ (s.1 = t.1 ∧ s.2 < t.2)) := rfl end def Prod.map.{u₁, u₂, v₁, v₂} {α₁ : Type u₁} {α₂ : Type u₂} {β₁ : Type v₁} {β₂ : Type v₂} (f : α₁ → α₂) (g : β₁ → β₂) : α₁ × β₁ → α₂ × β₂ | (a, b) := (f a, g b) /- Dependent products -/ -- notation `Σ` binders `, ` r:(scoped p, Sigma p) := r -- notation `Σ'` binders `, ` r:(scoped p, PSigma p) := r theorem exOfPsig {α : Type u} {p : α → Prop} : (PSigma (fun x => p x)) → Exists (fun x => p x) | ⟨x, hx⟩ := ⟨x, hx⟩ section variables {α : Type u} {β : α → Type v} protected theorem Sigma.eq : ∀ {p₁ p₂ : Sigma (fun a => β a)} (h₁ : p₁.1 = p₂.1), (Eq.recOn h₁ p₁.2 : β p₂.1) = p₂.2 → p₁ = p₂ | ⟨a, b⟩ ⟨.(a), .(b)⟩ rfl rfl := rfl end section variables {α : Sort u} {β : α → Sort v} protected theorem PSigma.eq : ∀ {p₁ p₂ : PSigma β} (h₁ : p₁.1 = p₂.1), (Eq.recOn h₁ p₁.2 : β p₂.1) = p₂.2 → p₁ = p₂ | ⟨a, b⟩ ⟨.(a), .(b)⟩ rfl rfl := rfl end /- Universe polymorphic unit -/ theorem punitEq (a b : PUnit) : a = b := PUnit.recOn a (PUnit.recOn b rfl) theorem punitEqPUnit (a : PUnit) : a = () := punitEq a () instance : Subsingleton PUnit := Subsingleton.intro punitEq instance : Inhabited PUnit := ⟨⟨⟩⟩ instance : DecidableEq PUnit := {decEq := fun a b => isTrue (punitEq a b)} /- Setoid -/ class Setoid (α : Sort u) := (r : α → α → Prop) (iseqv : Equivalence r) instance setoidHasEquiv {α : Sort u} [Setoid α] : HasEquiv α := ⟨Setoid.r⟩ namespace Setoid variables {α : Sort u} [Setoid α] theorem refl (a : α) : a ≈ a := match Setoid.iseqv α with | ⟨hRefl, hSymm, hTrans⟩ => hRefl a theorem symm {a b : α} (hab : a ≈ b) : b ≈ a := match Setoid.iseqv α with | ⟨hRefl, hSymm, hTrans⟩ => hSymm hab theorem trans {a b c : α} (hab : a ≈ b) (hbc : b ≈ c) : a ≈ c := match Setoid.iseqv α with | ⟨hRefl, hSymm, hTrans⟩ => hTrans hab hbc end Setoid /- Propositional extensionality -/ axiom propext {a b : Prop} : (a ↔ b) → a = b theorem eqTrueIntro {a : Prop} (h : a) : a = True := propext (iffTrueIntro h) theorem eqFalseIntro {a : Prop} (h : ¬a) : a = False := propext (iffFalseIntro h) /- Quotients -/ -- Iff can now be used to do substitutions in a calculation theorem iffSubst {a b : Prop} {p : Prop → Prop} (h₁ : a ↔ b) (h₂ : p a) : p b := Eq.subst (propext h₁) h₂ namespace Quot axiom sound : ∀ {α : Sort u} {r : α → α → Prop} {a b : α}, r a b → Quot.mk r a = Quot.mk r b attribute [elabAsEliminator] lift ind protected theorem liftBeta {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) (c : ∀ a b, r a b → f a = f b) (a : α) : lift f c (Quot.mk r a) = f a := rfl protected theorem indBeta {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} (p : ∀ a, β (Quot.mk r a)) (a : α) : (ind p (Quot.mk r a) : β (Quot.mk r a)) = p a := rfl @[reducible, elabAsEliminator, inline] protected def liftOn {α : Sort u} {β : Sort v} {r : α → α → Prop} (q : Quot r) (f : α → β) (c : ∀ a b, r a b → f a = f b) : β := lift f c q @[elabAsEliminator] protected theorem inductionOn {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} (q : Quot r) (h : ∀ a, β (Quot.mk r a)) : β q := ind h q theorem existsRep {α : Sort u} {r : α → α → Prop} (q : Quot r) : Exists (fun a => (Quot.mk r a) = q) := Quot.inductionOn q (fun a => ⟨a, rfl⟩) section variable {α : Sort u} variable {r : α → α → Prop} variable {β : Quot r → Sort v} @[reducible, macroInline] protected def indep (f : ∀ a, β (Quot.mk r a)) (a : α) : PSigma β := ⟨Quot.mk r a, f a⟩ protected theorem indepCoherent (f : ∀ a, β (Quot.mk r a)) (h : ∀ (a b : α) (p : r a b), (Eq.rec (f a) (sound p) : β (Quot.mk r b)) = f b) : ∀ a b, r a b → Quot.indep f a = Quot.indep f b := fun a b e => PSigma.eq (sound e) (h a b e) protected theorem liftIndepPr1 (f : ∀ a, β (Quot.mk r a)) (h : ∀ (a b : α) (p : r a b), (Eq.rec (f a) (sound p) : β (Quot.mk r b)) = f b) (q : Quot r) : (lift (Quot.indep f) (Quot.indepCoherent f h) q).1 = q := Quot.ind (fun (a : α) => Eq.refl (Quot.indep f a).1) q @[reducible, elabAsEliminator, inline] protected def rec (f : ∀ a, β (Quot.mk r a)) (h : ∀ (a b : α) (p : r a b), (Eq.rec (f a) (sound p) : β (Quot.mk r b)) = f b) (q : Quot r) : β q := Eq.ndrecOn (Quot.liftIndepPr1 f h q) ((lift (Quot.indep f) (Quot.indepCoherent f h) q).2) @[reducible, elabAsEliminator, inline] protected def recOn (q : Quot r) (f : ∀ a, β (Quot.mk r a)) (h : ∀ (a b : α) (p : r a b), (Eq.rec (f a) (sound p) : β (Quot.mk r b)) = f b) : β q := Quot.rec f h q @[reducible, elabAsEliminator, inline] protected def recOnSubsingleton [h : ∀ a, Subsingleton (β (Quot.mk r a))] (q : Quot r) (f : ∀ a, β (Quot.mk r a)) : β q := Quot.rec f (fun a b h => Subsingleton.elim _ (f b)) q @[reducible, elabAsEliminator, inline] protected def hrecOn (q : Quot r) (f : ∀ a, β (Quot.mk r a)) (c : ∀ (a b : α) (p : r a b), f a ≅ f b) : β q := Quot.recOn q f $ fun a b p => eqOfHeq $ have p₁ : (Eq.rec (f a) (sound p) : β (Quot.mk r b)) ≅ f a := eqRecHeq (sound p) (f a); Heq.trans p₁ (c a b p) end end Quot def Quotient {α : Sort u} (s : Setoid α) := @Quot α Setoid.r namespace Quotient @[inline] protected def mk {α : Sort u} [s : Setoid α] (a : α) : Quotient s := Quot.mk Setoid.r a notation `⟦`:max a `⟧`:0 := Quotient.mk a def sound {α : Sort u} [s : Setoid α] {a b : α} : a ≈ b → ⟦a⟧ = ⟦b⟧ := Quot.sound @[reducible, elabAsEliminator] protected def lift {α : Sort u} {β : Sort v} [s : Setoid α] (f : α → β) : (∀ a b, a ≈ b → f a = f b) → Quotient s → β := Quot.lift f @[elabAsEliminator] protected theorem ind {α : Sort u} [s : Setoid α] {β : Quotient s → Prop} : (∀ a, β ⟦a⟧) → ∀ q, β q := Quot.ind @[reducible, elabAsEliminator, inline] protected def liftOn {α : Sort u} {β : Sort v} [s : Setoid α] (q : Quotient s) (f : α → β) (c : ∀ a b, a ≈ b → f a = f b) : β := Quot.liftOn q f c @[elabAsEliminator] protected theorem inductionOn {α : Sort u} [s : Setoid α] {β : Quotient s → Prop} (q : Quotient s) (h : ∀ a, β ⟦a⟧) : β q := Quot.inductionOn q h theorem existsRep {α : Sort u} [s : Setoid α] (q : Quotient s) : Exists (fun (a : α) => ⟦a⟧ = q) := Quot.existsRep q section variable {α : Sort u} variable [s : Setoid α] variable {β : Quotient s → Sort v} @[inline] protected def rec (f : ∀ a, β ⟦a⟧) (h : ∀ (a b : α) (p : a ≈ b), (Eq.rec (f a) (Quotient.sound p) : β ⟦b⟧) = f b) (q : Quotient s) : β q := Quot.rec f h q @[reducible, elabAsEliminator, inline] protected def recOn (q : Quotient s) (f : ∀ a, β ⟦a⟧) (h : ∀ (a b : α) (p : a ≈ b), (Eq.rec (f a) (Quotient.sound p) : β ⟦b⟧) = f b) : β q := Quot.recOn q f h @[reducible, elabAsEliminator, inline] protected def recOnSubsingleton [h : ∀ a, Subsingleton (β ⟦a⟧)] (q : Quotient s) (f : ∀ a, β ⟦a⟧) : β q := @Quot.recOnSubsingleton _ _ _ h q f @[reducible, elabAsEliminator, inline] protected def hrecOn (q : Quotient s) (f : ∀ a, β ⟦a⟧) (c : ∀ (a b : α) (p : a ≈ b), f a ≅ f b) : β q := Quot.hrecOn q f c end section universes uA uB uC variables {α : Sort uA} {β : Sort uB} {φ : Sort uC} variables [s₁ : Setoid α] [s₂ : Setoid β] @[reducible, elabAsEliminator, inline] protected def lift₂ (f : α → β → φ)(c : ∀ a₁ a₂ b₁ b₂, a₁ ≈ b₁ → a₂ ≈ b₂ → f a₁ a₂ = f b₁ b₂) (q₁ : Quotient s₁) (q₂ : Quotient s₂) : φ := Quotient.lift (fun (a₁ : α) => Quotient.lift (f a₁) (fun (a b : β) => c a₁ a a₁ b (Setoid.refl a₁)) q₂) (fun (a b : α) (h : a ≈ b) => @Quotient.ind β s₂ (fun (a1 : Quotient s₂) => (Quotient.lift (f a) (fun (a1 b : β) => c a a1 a b (Setoid.refl a)) a1) = (Quotient.lift (f b) (fun (a b1 : β) => c b a b b1 (Setoid.refl b)) a1)) (fun (a' : β) => c a a' b a' h (Setoid.refl a')) q₂) q₁ @[reducible, elabAsEliminator, inline] protected def liftOn₂ (q₁ : Quotient s₁) (q₂ : Quotient s₂) (f : α → β → φ) (c : ∀ a₁ a₂ b₁ b₂, a₁ ≈ b₁ → a₂ ≈ b₂ → f a₁ a₂ = f b₁ b₂) : φ := Quotient.lift₂ f c q₁ q₂ @[elabAsEliminator] protected theorem ind₂ {φ : Quotient s₁ → Quotient s₂ → Prop} (h : ∀ a b, φ ⟦a⟧ ⟦b⟧) (q₁ : Quotient s₁) (q₂ : Quotient s₂) : φ q₁ q₂ := Quotient.ind (fun a₁ => Quotient.ind (fun a₂ => h a₁ a₂) q₂) q₁ @[elabAsEliminator] protected theorem inductionOn₂ {φ : Quotient s₁ → Quotient s₂ → Prop} (q₁ : Quotient s₁) (q₂ : Quotient s₂) (h : ∀ a b, φ ⟦a⟧ ⟦b⟧) : φ q₁ q₂ := Quotient.ind (fun a₁ => Quotient.ind (fun a₂ => h a₁ a₂) q₂) q₁ @[elabAsEliminator] protected theorem inductionOn₃ [s₃ : Setoid φ] {δ : Quotient s₁ → Quotient s₂ → Quotient s₃ → Prop} (q₁ : Quotient s₁) (q₂ : Quotient s₂) (q₃ : Quotient s₃) (h : ∀ a b c, δ ⟦a⟧ ⟦b⟧ ⟦c⟧) : δ q₁ q₂ q₃ := Quotient.ind (fun a₁ => Quotient.ind (fun a₂ => Quotient.ind (fun a₃ => h a₁ a₂ a₃) q₃) q₂) q₁ end section Exact variable {α : Sort u} private def rel [s : Setoid α] (q₁ q₂ : Quotient s) : Prop := Quotient.liftOn₂ q₁ q₂ (fun a₁ a₂ => a₁ ≈ a₂) (fun a₁ a₂ b₁ b₂ a₁b₁ a₂b₂ => propext (Iff.intro (fun a₁a₂ => Setoid.trans (Setoid.symm a₁b₁) (Setoid.trans a₁a₂ a₂b₂)) (fun b₁b₂ => Setoid.trans a₁b₁ (Setoid.trans b₁b₂ (Setoid.symm a₂b₂))))) private theorem rel.refl [s : Setoid α] : ∀ (q : Quotient s), rel q q := fun q => Quot.inductionOn q (fun a => Setoid.refl a) private theorem eqImpRel [s : Setoid α] {q₁ q₂ : Quotient s} : q₁ = q₂ → rel q₁ q₂ := fun h => Eq.ndrecOn h (rel.refl q₁) theorem exact [s : Setoid α] {a b : α} : ⟦a⟧ = ⟦b⟧ → a ≈ b := fun h => eqImpRel h end Exact section universes uA uB uC variables {α : Sort uA} {β : Sort uB} variables [s₁ : Setoid α] [s₂ : Setoid β] @[reducible, elabAsEliminator] protected def recOnSubsingleton₂ {φ : Quotient s₁ → Quotient s₂ → Sort uC} [h : ∀ a b, Subsingleton (φ ⟦a⟧ ⟦b⟧)] (q₁ : Quotient s₁) (q₂ : Quotient s₂) (f : ∀ a b, φ ⟦a⟧ ⟦b⟧) : φ q₁ q₂:= @Quotient.recOnSubsingleton _ s₁ (fun q => φ q q₂) (fun a => Quotient.ind (fun b => h a b) q₂) q₁ (fun a => Quotient.recOnSubsingleton q₂ (fun b => f a b)) end end Quotient section variable {α : Type u} variable (r : α → α → Prop) inductive EqvGen : α → α → Prop | rel {} : ∀ x y, r x y → EqvGen x y | refl {} : ∀ x, EqvGen x x | symm {} : ∀ x y, EqvGen x y → EqvGen y x | trans {} : ∀ x y z, EqvGen x y → EqvGen y z → EqvGen x z theorem EqvGen.isEquivalence : Equivalence (@EqvGen α r) := mkEquivalence _ EqvGen.refl EqvGen.symm EqvGen.trans def EqvGen.Setoid : Setoid α := Setoid.mk _ (EqvGen.isEquivalence r) theorem Quot.exact {a b : α} (H : Quot.mk r a = Quot.mk r b) : EqvGen r a b := @Quotient.exact _ (EqvGen.Setoid r) a b (@congrArg _ _ _ _ (Quot.lift (@Quotient.mk _ (EqvGen.Setoid r)) (fun x y h => Quot.sound (EqvGen.rel x y h))) H) theorem Quot.eqvGenSound {r : α → α → Prop} {a b : α} (H : EqvGen r a b) : Quot.mk r a = Quot.mk r b := EqvGen.recOn H (fun x y h => Quot.sound h) (fun x => rfl) (fun x y _ IH => Eq.symm IH) (fun x y z _ _ IH₁ IH₂ => Eq.trans IH₁ IH₂) end instance {α : Sort u} {s : Setoid α} [d : ∀ (a b : α), Decidable (a ≈ b)] : DecidableEq (Quotient s) := {decEq := fun (q₁ q₂ : Quotient s) => Quotient.recOnSubsingleton₂ q₁ q₂ (fun a₁ a₂ => match (d a₁ a₂) with | (isTrue h₁) => isTrue (Quotient.sound h₁) | (isFalse h₂) => isFalse (fun h => absurd (Quotient.exact h) h₂))} /- Function extensionality -/ namespace Function variables {α : Sort u} {β : α → Sort v} def Equiv (f₁ f₂ : ∀ (x : α), β x) : Prop := ∀ x, f₁ x = f₂ x protected theorem Equiv.refl (f : ∀ (x : α), β x) : Equiv f f := fun x => rfl protected theorem Equiv.symm {f₁ f₂ : ∀ (x : α), β x} : Equiv f₁ f₂ → Equiv f₂ f₁ := fun h x => Eq.symm (h x) protected theorem Equiv.trans {f₁ f₂ f₃ : ∀ (x : α), β x} : Equiv f₁ f₂ → Equiv f₂ f₃ → Equiv f₁ f₃ := fun h₁ h₂ x => Eq.trans (h₁ x) (h₂ x) protected theorem Equiv.isEquivalence (α : Sort u) (β : α → Sort v) : Equivalence (@Function.Equiv α β) := mkEquivalence (@Function.Equiv α β) (@Equiv.refl α β) (@Equiv.symm α β) (@Equiv.trans α β) end Function section open Quotient variables {α : Sort u} {β : α → Sort v} @[instance] private def funSetoid (α : Sort u) (β : α → Sort v) : Setoid (∀ (x : α), β x) := Setoid.mk (@Function.Equiv α β) (Function.Equiv.isEquivalence α β) private def extfunApp (f : Quotient $ funSetoid α β) : ∀ (x : α), β x := fun x => Quot.liftOn f (fun (f : ∀ (x : α), β x) => f x) (fun f₁ f₂ h => h x) theorem funext {f₁ f₂ : ∀ (x : α), β x} (h : ∀ x, f₁ x = f₂ x) : f₁ = f₂ := show extfunApp ⟦f₁⟧ = extfunApp ⟦f₂⟧ from congrArg extfunApp (sound h) end instance Forall.Subsingleton {α : Sort u} {β : α → Sort v} [∀ a, Subsingleton (β a)] : Subsingleton (∀ a, β a) := ⟨fun f₁ f₂ => funext (fun a => Subsingleton.elim (f₁ a) (f₂ a))⟩ /- General operations on functions -/ namespace Function universes u₁ u₂ u₃ u₄ variables {α : Sort u₁} {β : Sort u₂} {φ : Sort u₃} {δ : Sort u₄} {ζ : Sort u₁} @[inline, reducible] def comp (f : β → φ) (g : α → β) : α → φ := fun x => f (g x) infixr ` ∘ ` := Function.comp @[inline, reducible] def onFun (f : β → β → φ) (g : α → β) : α → α → φ := fun x y => f (g x) (g y) @[inline, reducible] def combine (f : α → β → φ) (op : φ → δ → ζ) (g : α → β → δ) : α → β → ζ := fun x y => op (f x y) (g x y) @[inline, reducible] def const (β : Sort u₂) (a : α) : β → α := fun x => a @[inline, reducible] def swap {φ : α → β → Sort u₃} (f : ∀ x y, φ x y) : ∀ y x, φ x y := fun y x => f x y end Function /- Classical reasoning support -/ namespace Classical axiom choice {α : Sort u} : Nonempty α → α noncomputable def indefiniteDescription {α : Sort u} (p : α → Prop) (h : Exists (fun x => p x)) : {x // p x} := choice $ let ⟨x, px⟩ := h; ⟨⟨x, px⟩⟩ noncomputable def choose {α : Sort u} {p : α → Prop} (h : Exists (fun x => p x)) : α := (indefiniteDescription p h).val theorem chooseSpec {α : Sort u} {p : α → Prop} (h : Exists (fun x => p x)) : p (choose h) := (indefiniteDescription p h).property /- Diaconescu's theorem: excluded middle from choice, Function extensionality and propositional extensionality. -/ theorem em (p : Prop) : p ∨ ¬p := let U (x : Prop) : Prop := x = True ∨ p; let V (x : Prop) : Prop := x = False ∨ p; have exU : Exists (fun x => U x) from ⟨True, Or.inl rfl⟩; have exV : Exists (fun x => V x) from ⟨False, Or.inl rfl⟩; let u : Prop := choose exU; let v : Prop := choose exV; have uDef : U u from chooseSpec exU; have vDef : V v from chooseSpec exV; have notUvOrP : u ≠ v ∨ p from Or.elim uDef (fun hut => Or.elim vDef (fun hvf => have hne : u ≠ v from hvf.symm ▸ hut.symm ▸ trueNeFalse; Or.inl hne) Or.inr) Or.inr; have pImpliesUv : p → u = v from fun hp => have hpred : U = V from funext $ fun x => have hl : (x = True ∨ p) → (x = False ∨ p) from fun a => Or.inr hp; have hr : (x = False ∨ p) → (x = True ∨ p) from fun a => Or.inr hp; show (x = True ∨ p) = (x = False ∨ p) from propext (Iff.intro hl hr); have h₀ : ∀ exU exV, @choose _ U exU = @choose _ V exV from hpred ▸ fun exU exV => rfl; show u = v from h₀ _ _; Or.elim notUvOrP (fun (hne : u ≠ v) => Or.inr (mt pImpliesUv hne)) Or.inl theorem existsTrueOfNonempty {α : Sort u} : Nonempty α → Exists (fun (x : α) => True) | ⟨x⟩ := ⟨x, trivial⟩ noncomputable def inhabitedOfNonempty {α : Sort u} (h : Nonempty α) : Inhabited α := ⟨choice h⟩ noncomputable def inhabitedOfExists {α : Sort u} {p : α → Prop} (h : Exists (fun x => p x)) : Inhabited α := inhabitedOfNonempty (Exists.elim h (fun w hw => ⟨w⟩)) /- all propositions are Decidable -/ noncomputable def propDecidable (a : Prop) : Decidable a := choice $ Or.elim (em a) (fun ha => ⟨isTrue ha⟩) (fun hna => ⟨isFalse hna⟩) noncomputable def decidableInhabited (a : Prop) : Inhabited (Decidable a) := ⟨propDecidable a⟩ noncomputable def typeDecidableEq (α : Sort u) : DecidableEq α := {decEq := fun x y => propDecidable (x = y)} noncomputable def typeDecidable (α : Sort u) : PSum α (α → False) := match (propDecidable (Nonempty α)) with | (isTrue hp) => PSum.inl (@Inhabited.default _ (inhabitedOfNonempty hp)) | (isFalse hn) => PSum.inr (fun a => absurd (Nonempty.intro a) hn) noncomputable def strongIndefiniteDescription {α : Sort u} (p : α → Prop) (h : Nonempty α) : {x : α // Exists (fun (y : α) => p y) → p x} := @dite (Exists (fun (x : α) => p x)) (propDecidable _) _ (fun (hp : Exists (fun (x : α) => p x)) => show {x : α // Exists (fun (y : α) => p y) → p x} from let xp := indefiniteDescription _ hp; ⟨xp.val, fun h' => xp.property⟩) (fun hp => ⟨choice h, fun h => absurd h hp⟩) /- the Hilbert epsilon Function -/ noncomputable def epsilon {α : Sort u} [h : Nonempty α] (p : α → Prop) : α := (strongIndefiniteDescription p h).val theorem epsilonSpecAux {α : Sort u} (h : Nonempty α) (p : α → Prop) : Exists (fun y => p y) → p (@epsilon α h p) := (strongIndefiniteDescription p h).property theorem epsilonSpec {α : Sort u} {p : α → Prop} (hex : Exists (fun y => p y)) : p (@epsilon α (nonemptyOfExists hex) p) := epsilonSpecAux (nonemptyOfExists hex) p hex theorem epsilonSingleton {α : Sort u} (x : α) : @epsilon α ⟨x⟩ (fun y => y = x) = x := @epsilonSpec α (fun y => y = x) ⟨x, rfl⟩ /- the axiom of choice -/ theorem axiomOfChoice {α : Sort u} {β : α → Sort v} {r : ∀ x, β x → Prop} (h : ∀ x, Exists (fun y => r x y)) : Exists (fun (f : ∀ x, β x) => ∀ x, r x (f x)) := ⟨_, fun x => chooseSpec (h x)⟩ theorem skolem {α : Sort u} {b : α → Sort v} {p : ∀ x, b x → Prop} : (∀ x, Exists (fun y => p x y)) ↔ Exists (fun (f : ∀ x, b x) => ∀ x, p x (f x)) := ⟨axiomOfChoice, fun ⟨f, hw⟩ (x) => ⟨f x, hw x⟩⟩ theorem propComplete (a : Prop) : a = True ∨ a = False := Or.elim (em a) (fun t => Or.inl (eqTrueIntro t)) (fun f => Or.inr (eqFalseIntro f)) -- this supercedes byCases in Decidable theorem byCases {p q : Prop} (hpq : p → q) (hnpq : ¬p → q) : q := @Decidable.byCases _ _ (propDecidable _) hpq hnpq -- this supercedes byContradiction in Decidable theorem byContradiction {p : Prop} (h : ¬p → False) : p := @Decidable.byContradiction _ (propDecidable _) h end Classical
8a92566e10a9334c4bc1d20ee963ab537ac02c3c
130c49f47783503e462c16b2eff31933442be6ff
/stage0/src/Lean/Parser/Term.lean
4b7db28d8c18dc911598cb746ccf34e91490c074
[ "Apache-2.0" ]
permissive
Hazel-Brown/lean4
8aa5860e282435ffc30dcdfccd34006c59d1d39c
79e6732fc6bbf5af831b76f310f9c488d44e7a16
refs/heads/master
1,689,218,208,951
1,629,736,869,000
1,629,736,896,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,654
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Parser.Attr import Lean.Parser.Level namespace Lean namespace Parser namespace Command def commentBody : Parser := { fn := rawFn (finishCommentBlock 1) (trailingWs := true) } @[combinatorParenthesizer Lean.Parser.Command.commentBody] def commentBody.parenthesizer := PrettyPrinter.Parenthesizer.visitToken @[combinatorFormatter Lean.Parser.Command.commentBody] def commentBody.formatter := PrettyPrinter.Formatter.visitAtom Name.anonymous def docComment := leading_parser ppDedent $ "/--" >> commentBody >> ppLine end Command builtin_initialize registerBuiltinParserAttribute `builtinTacticParser `tactic LeadingIdentBehavior.both registerBuiltinDynamicParserAttribute `tacticParser `tactic @[inline] def tacticParser (rbp : Nat := 0) : Parser := categoryParser `tactic rbp namespace Tactic def tacticSeq1Indented : Parser := leading_parser many1Indent (group (ppLine >> tacticParser >> optional ";")) def tacticSeqBracketed : Parser := leading_parser "{" >> many (group (ppLine >> tacticParser >> optional ";")) >> ppDedent (ppLine >> "}") def tacticSeq := nodeWithAntiquot "tacticSeq" `Lean.Parser.Tactic.tacticSeq (tacticSeqBracketed <|> tacticSeq1Indented) /- Raw sequence for quotation and grouping -/ def seq1 := node `Lean.Parser.Tactic.seq1 $ sepBy1 tacticParser ";\n" (allowTrailingSep := true) end Tactic def darrow : Parser := " => " namespace Term /- Built-in parsers -/ @[builtinTermParser] def byTactic := leading_parser:leadPrec "by " >> Tactic.tacticSeq def optSemicolon (p : Parser) : Parser := ppDedent $ optional ";" >> ppLine >> p -- `checkPrec` necessary for the pretty printer @[builtinTermParser] def ident := checkPrec maxPrec >> Parser.ident @[builtinTermParser] def num : Parser := checkPrec maxPrec >> numLit @[builtinTermParser] def scientific : Parser := checkPrec maxPrec >> scientificLit @[builtinTermParser] def str : Parser := checkPrec maxPrec >> strLit @[builtinTermParser] def char : Parser := checkPrec maxPrec >> charLit @[builtinTermParser] def type := leading_parser "Type" >> optional (checkWsBefore "" >> checkPrec leadPrec >> checkColGt >> levelParser maxPrec) @[builtinTermParser] def sort := leading_parser "Sort" >> optional (checkWsBefore "" >> checkPrec leadPrec >> checkColGt >> levelParser maxPrec) @[builtinTermParser] def prop := leading_parser "Prop" @[builtinTermParser] def hole := leading_parser "_" @[builtinTermParser] def syntheticHole := leading_parser "?" >> (ident <|> hole) @[builtinTermParser] def «sorry» := leading_parser "sorry" @[builtinTermParser] def cdot := leading_parser symbol "·" <|> "." def typeAscription := leading_parser " : " >> termParser def tupleTail := leading_parser ", " >> sepBy1 termParser ", " def parenSpecial : Parser := optional (tupleTail <|> typeAscription) @[builtinTermParser] def paren := leading_parser "(" >> ppDedent (withoutPosition (withoutForbidden (optional (termParser >> parenSpecial)))) >> ")" @[builtinTermParser] def anonymousCtor := leading_parser "⟨" >> sepBy termParser ", " >> "⟩" def optIdent : Parser := optional (atomic (ident >> " : ")) def fromTerm := leading_parser " from " >> termParser def sufficesDecl := leading_parser optIdent >> termParser >> (fromTerm <|> byTactic) @[builtinTermParser] def «suffices» := leading_parser:leadPrec withPosition ("suffices " >> sufficesDecl) >> optSemicolon termParser @[builtinTermParser] def «show» := leading_parser:leadPrec "show " >> termParser >> (fromTerm <|> byTactic) def structInstArrayRef := leading_parser "[" >> termParser >>"]" def structInstLVal := leading_parser (ident <|> fieldIdx <|> structInstArrayRef) >> many (group ("." >> (ident <|> fieldIdx)) <|> structInstArrayRef) def structInstField := ppGroup $ leading_parser structInstLVal >> " := " >> termParser def structInstFieldAbbrev := leading_parser atomic (ident >> notFollowedBy ("." <|> ":=" <|> symbol "[") "invalid field abbreviation") -- `x` is an abbreviation for `x := x` def optEllipsis := leading_parser optional ".." @[builtinTermParser] def structInst := leading_parser "{" >> ppHardSpace >> optional (atomic (sepBy1 termParser ", " >> " with ")) >> manyIndent (group ((structInstFieldAbbrev <|> structInstField) >> optional ", ")) >> optEllipsis >> optional (" : " >> termParser) >> " }" def typeSpec := leading_parser " : " >> termParser def optType : Parser := optional typeSpec @[builtinTermParser] def explicit := leading_parser "@" >> termParser maxPrec @[builtinTermParser] def inaccessible := leading_parser ".(" >> termParser >> ")" def binderIdent : Parser := ident <|> hole def binderType (requireType := false) : Parser := if requireType then node nullKind (" : " >> termParser) else optional (" : " >> termParser) def binderTactic := leading_parser atomic (symbol " := " >> " by ") >> Tactic.tacticSeq def binderDefault := leading_parser " := " >> termParser def explicitBinder (requireType := false) := ppGroup $ leading_parser "(" >> many1 binderIdent >> binderType requireType >> optional (binderTactic <|> binderDefault) >> ")" def implicitBinder (requireType := false) := ppGroup $ leading_parser "{" >> many1 binderIdent >> binderType requireType >> "}" def strictImplicitLeftBracket := atomic (group (symbol "{" >> "{")) <|> "⦃" def strictImplicitRightBracket := atomic (group (symbol "}" >> "}")) <|> "⦄" def strictImplicitBinder (requireType := false) := ppGroup $ leading_parser strictImplicitLeftBracket >> many1 binderIdent >> binderType requireType >> strictImplicitRightBracket def instBinder := ppGroup $ leading_parser "[" >> optIdent >> termParser >> "]" def bracketedBinder (requireType := false) := withAntiquot (mkAntiquot "bracketedBinder" none (anonymous := false)) <| explicitBinder requireType <|> strictImplicitBinder requireType <|> implicitBinder requireType <|> instBinder /- It is feasible to support dependent arrows such as `{α} → α → α` without sacrificing the quality of the error messages for the longer case. `{α} → α → α` would be short for `{α : Type} → α → α` Here is the encoding: ``` def implicitShortBinder := node `Lean.Parser.Term.implicitBinder $ "{" >> many1 binderIdent >> pushNone >> "}" def depArrowShortPrefix := try (implicitShortBinder >> unicodeSymbol " → " " -> ") def depArrowLongPrefix := bracketedBinder true >> unicodeSymbol " → " " -> " def depArrowPrefix := depArrowShortPrefix <|> depArrowLongPrefix @[builtinTermParser] def depArrow := leading_parser depArrowPrefix >> termParser ``` Note that no changes in the elaborator are needed. We decided to not use it because terms such as `{α} → α → α` may look too cryptic. Note that we did not add a `explicitShortBinder` parser since `(α) → α → α` is really cryptic as a short for `(α : Type) → α → α`. -/ @[builtinTermParser] def depArrow := leading_parser:25 bracketedBinder true >> unicodeSymbol " → " " -> " >> termParser def simpleBinder := leading_parser many1 binderIdent >> optType @[builtinTermParser] def «forall» := leading_parser:leadPrec unicodeSymbol "∀" "forall" >> many1 (ppSpace >> (simpleBinder <|> bracketedBinder)) >> ", " >> termParser def matchAlt (rhsParser : Parser := termParser) : Parser := nodeWithAntiquot "matchAlt" `Lean.Parser.Term.matchAlt $ "| " >> ppIndent (sepBy1 termParser ", " >> darrow >> checkColGe "alternative right-hand-side to start in a column greater than or equal to the corresponding '|'" >> rhsParser) /-- Useful for syntax quotations. Note that generic patterns such as `` `(matchAltExpr| | ... => $rhs) `` should also work with other `rhsParser`s (of arity 1). -/ def matchAltExpr := matchAlt def matchAlts (rhsParser : Parser := termParser) : Parser := leading_parser ppDedent $ withPosition $ many1Indent (ppLine >> matchAlt rhsParser) def matchDiscr := leading_parser optional (atomic (ident >> checkNoWsBefore "no space before ':'" >> ":")) >> termParser def trueVal := leading_parser nonReservedSymbol "true" def falseVal := leading_parser nonReservedSymbol "false" def generalizingParam := leading_parser atomic ("(" >> nonReservedSymbol "generalizing") >> " := " >> (trueVal <|> falseVal) >> ")" @[builtinTermParser] def «match» := leading_parser:leadPrec "match " >> optional generalizingParam >> sepBy1 matchDiscr ", " >> optType >> " with " >> matchAlts @[builtinTermParser] def «nomatch» := leading_parser:leadPrec "nomatch " >> termParser def funImplicitBinder := atomic (lookahead ("{" >> many1 binderIdent >> (symbol " : " <|> "}"))) >> implicitBinder def funStrictImplicitBinder := atomic (lookahead (strictImplicitLeftBracket >> many1 binderIdent >> (symbol " : " <|> strictImplicitRightBracket))) >> strictImplicitBinder def funSimpleBinder := atomic (lookahead (many1 binderIdent >> " : ")) >> simpleBinder def funBinder : Parser := funStrictImplicitBinder <|> funImplicitBinder <|> instBinder <|> funSimpleBinder <|> termParser maxPrec -- NOTE: we use `nodeWithAntiquot` to ensure that `fun $b => ...` remains a `term` antiquotation def basicFun : Parser := nodeWithAntiquot "basicFun" `Lean.Parser.Term.basicFun (many1 (ppSpace >> funBinder) >> darrow >> termParser) @[builtinTermParser] def «fun» := leading_parser:maxPrec unicodeSymbol "λ" "fun" >> (basicFun <|> matchAlts) def optExprPrecedence := optional (atomic ":" >> termParser maxPrec) @[builtinTermParser] def «leading_parser» := leading_parser:leadPrec "leading_parser " >> optExprPrecedence >> termParser @[builtinTermParser] def «trailing_parser» := leading_parser:leadPrec "trailing_parser " >> optExprPrecedence >> optExprPrecedence >> termParser @[builtinTermParser] def borrowed := leading_parser "@&" >> termParser leadPrec @[builtinTermParser] def quotedName := leading_parser nameLit -- use `rawCh` because ``"`" >> ident`` overlaps with `nameLit`, with the latter being preferred by the tokenizer -- note that we cannot use ```"``"``` as a new token either because it would break `precheckedQuot` @[builtinTermParser] def doubleQuotedName := leading_parser "`" >> checkNoWsBefore >> rawCh '`' (trailingWs := false) >> ident def simpleBinderWithoutType := nodeWithAntiquot "simpleBinder" `Lean.Parser.Term.simpleBinder (anonymous := true) (many1 binderIdent >> pushNone) /- Remark: we use `checkWsBefore` to ensure `let x[i] := e; b` is not parsed as `let x [i] := e; b` where `[i]` is an `instBinder`. -/ def letIdLhs : Parser := ident >> checkWsBefore "expected space before binders" >> many (ppSpace >> (simpleBinderWithoutType <|> bracketedBinder)) >> optType def letIdDecl := nodeWithAntiquot "letIdDecl" `Lean.Parser.Term.letIdDecl $ atomic (letIdLhs >> " := ") >> termParser def letPatDecl := nodeWithAntiquot "letPatDecl" `Lean.Parser.Term.letPatDecl $ atomic (termParser >> pushNone >> optType >> " := ") >> termParser def letEqnsDecl := nodeWithAntiquot "letEqnsDecl" `Lean.Parser.Term.letEqnsDecl $ letIdLhs >> matchAlts -- Remark: we use `nodeWithAntiquot` here to make sure anonymous antiquotations (e.g., `$x`) are not `letDecl` def letDecl := nodeWithAntiquot "letDecl" `Lean.Parser.Term.letDecl (notFollowedBy (nonReservedSymbol "rec") "rec" >> (letIdDecl <|> letPatDecl <|> letEqnsDecl)) @[builtinTermParser] def «let» := leading_parser:leadPrec withPosition ("let " >> letDecl) >> optSemicolon termParser @[builtinTermParser] def «let_fun» := leading_parser:leadPrec withPosition ((symbol "let_fun " <|> "let_λ") >> letDecl) >> optSemicolon termParser @[builtinTermParser] def «let_delayed» := leading_parser:leadPrec withPosition ("let_delayed " >> letDecl) >> optSemicolon termParser -- like `let_fun` but with optional name def haveIdLhs := optional (ident >> many (ppSpace >> (simpleBinderWithoutType <|> bracketedBinder))) >> optType def haveIdDecl := nodeWithAntiquot "haveIdDecl" `Lean.Parser.Term.haveIdDecl $ atomic (haveIdLhs >> " := ") >> termParser def haveEqnsDecl := nodeWithAntiquot "haveEqnsDecl" `Lean.Parser.Term.haveEqnsDecl $ haveIdLhs >> matchAlts def haveDecl := nodeWithAntiquot "haveDecl" `Lean.Parser.Term.haveDecl (haveIdDecl <|> letPatDecl <|> haveEqnsDecl) @[builtinTermParser] def «have» := leading_parser:leadPrec withPosition ("have " >> haveDecl) >> optSemicolon termParser def «scoped» := leading_parser "scoped " def «local» := leading_parser "local " def attrKind := leading_parser optional («scoped» <|> «local») def attrInstance := ppGroup $ leading_parser attrKind >> attrParser def attributes := leading_parser "@[" >> sepBy1 attrInstance ", " >> "]" def letRecDecl := leading_parser optional Command.docComment >> optional «attributes» >> letDecl def letRecDecls := leading_parser sepBy1 letRecDecl ", " @[builtinTermParser] def «letrec» := leading_parser:leadPrec withPosition (group ("let " >> nonReservedSymbol "rec ") >> letRecDecls) >> optSemicolon termParser @[runBuiltinParserAttributeHooks] def whereDecls := leading_parser "where " >> many1Indent (group (letRecDecl >> optional ";")) @[runBuiltinParserAttributeHooks] def matchAltsWhereDecls := leading_parser matchAlts >> optional whereDecls @[builtinTermParser] def noindex := leading_parser "no_index " >> termParser maxPrec @[builtinTermParser] def binrel := leading_parser "binrel% " >> ident >> ppSpace >> termParser maxPrec >> termParser maxPrec @[builtinTermParser] def binop := leading_parser "binop% " >> ident >> ppSpace >> termParser maxPrec >> termParser maxPrec @[builtinTermParser] def forInMacro := leading_parser "forIn% " >> termParser maxPrec >> termParser maxPrec >> termParser maxPrec @[builtinTermParser] def typeOf := leading_parser "typeOf% " >> termParser maxPrec @[builtinTermParser] def ensureTypeOf := leading_parser "ensureTypeOf% " >> termParser maxPrec >> strLit >> termParser @[builtinTermParser] def ensureExpectedType := leading_parser "ensureExpectedType% " >> strLit >> termParser maxPrec @[builtinTermParser] def noImplicitLambda := leading_parser "noImplicitLambda% " >> termParser maxPrec def namedArgument := leading_parser atomic ("(" >> ident >> " := ") >> termParser >> ")" def ellipsis := leading_parser ".." def argument := checkWsBefore "expected space" >> checkColGt "expected to be indented" >> (namedArgument <|> ellipsis <|> termParser argPrec) -- `app` precedence is `lead` (cannot be used as argument) -- `lhs` precedence is `max` (i.e. does not accept `arg` precedence) -- argument precedence is `arg` (i.e. does not accept `lead` precedence) @[builtinTermParser] def app := trailing_parser:leadPrec:maxPrec many1 argument @[builtinTermParser] def proj := trailing_parser checkNoWsBefore >> "." >> checkNoWsBefore >> (fieldIdx <|> ident) @[builtinTermParser] def completion := trailing_parser checkNoWsBefore >> "." @[builtinTermParser] def arrayRef := trailing_parser checkNoWsBefore >> "[" >> termParser >>"]" @[builtinTermParser] def arrow := trailing_parser checkPrec 25 >> unicodeSymbol " → " " -> " >> termParser 25 def isIdent (stx : Syntax) : Bool := -- antiquotations should also be allowed where an identifier is expected stx.isAntiquot || stx.isIdent @[builtinTermParser] def explicitUniv : TrailingParser := trailing_parser checkStackTop isIdent "expected preceding identifier" >> checkNoWsBefore "no space before '.{'" >> ".{" >> sepBy1 levelParser ", " >> "}" @[builtinTermParser] def namedPattern : TrailingParser := trailing_parser checkStackTop isIdent "expected preceding identifier" >> checkNoWsBefore "no space before '@'" >> "@" >> termParser maxPrec @[builtinTermParser] def pipeProj := trailing_parser:minPrec " |>." >> checkNoWsBefore >> (fieldIdx <|> ident) >> many argument @[builtinTermParser] def pipeCompletion := trailing_parser:minPrec " |>." @[builtinTermParser] def subst := trailing_parser:75 " ▸ " >> sepBy1 (termParser 75) " ▸ " -- NOTE: Doesn't call `categoryParser` directly in contrast to most other "static" quotations, so call `evalInsideQuot` explicitly @[builtinTermParser] def funBinder.quot : Parser := leading_parser "`(funBinder|" >> incQuotDepth (evalInsideQuot ``funBinder funBinder) >> ")" def bracketedBinderF := bracketedBinder -- no default arg @[builtinTermParser] def bracketedBinder.quot : Parser := leading_parser "`(bracketedBinder|" >> incQuotDepth (evalInsideQuot ``bracketedBinderF bracketedBinder) >> ")" @[builtinTermParser] def matchDiscr.quot : Parser := leading_parser "`(matchDiscr|" >> incQuotDepth (evalInsideQuot ``matchDiscr matchDiscr) >> ")" @[builtinTermParser] def attr.quot : Parser := leading_parser "`(attr|" >> incQuotDepth attrParser >> ")" @[builtinTermParser] def panic := leading_parser:leadPrec "panic! " >> termParser @[builtinTermParser] def unreachable := leading_parser:leadPrec "unreachable!" @[builtinTermParser] def dbgTrace := leading_parser:leadPrec withPosition ("dbg_trace" >> ((interpolatedStr termParser) <|> termParser)) >> optSemicolon termParser @[builtinTermParser] def assert := leading_parser:leadPrec withPosition ("assert! " >> termParser) >> optSemicolon termParser def macroArg := termParser maxPrec def macroDollarArg := leading_parser "$" >> termParser 10 def macroLastArg := macroDollarArg <|> macroArg -- Macro for avoiding exponentially big terms when using `STWorld` @[builtinTermParser] def stateRefT := leading_parser "StateRefT" >> macroArg >> macroLastArg @[builtinTermParser] def dynamicQuot := leading_parser "`(" >> ident >> "|" >> incQuotDepth (parserOfStack 1) >> ")" end Term @[builtinTermParser default+1] def Tactic.quot : Parser := leading_parser "`(tactic|" >> incQuotDepth tacticParser >> ")" @[builtinTermParser] def Tactic.quotSeq : Parser := leading_parser "`(tactic|" >> incQuotDepth Tactic.seq1 >> ")" @[builtinTermParser] def Level.quot : Parser := leading_parser "`(level|" >> incQuotDepth levelParser >> ")" builtin_initialize register_parser_alias "letDecl" Term.letDecl register_parser_alias "haveDecl" Term.haveDecl register_parser_alias "sufficesDecl" Term.sufficesDecl register_parser_alias "letRecDecls" Term.letRecDecls register_parser_alias "hole" Term.hole register_parser_alias "syntheticHole" Term.syntheticHole register_parser_alias "matchDiscr" Term.matchDiscr register_parser_alias "bracketedBinder" Term.bracketedBinder register_parser_alias "attrKind" Term.attrKind end Parser end Lean
c60b94938b126e40446d53343a05884b32298352
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/const.lean
56057e2fefcda4722245a1c800bde64388fd2b34
[ "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
285
lean
import logic definition foo {A : Type} [H : inhabited A] : A := inhabited.rec (λa, a) H constant bla {A : Type} [H : inhabited A] : Type.{1} set_option pp.implicit true section variable A : Type variable S : inhabited A variable B : @bla A _ check B check @foo A _ end
20de8a7e0e8550ff460dfe950332d1628d8efe4d
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/control/option.lean
b61320a37aa236eaec7948115eba54223bccb508
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
2,859
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, Sebastian Ullrich -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.control.alternative import Mathlib.Lean3Lib.init.control.lift import Mathlib.Lean3Lib.init.control.except universes u v l u_1 u_2 namespace Mathlib structure option_t (m : Type u → Type v) (α : Type u) where run : m (Option α) namespace option_t protected def bind_cont {m : Type u → Type v} [Monad m] {α : Type u} {β : Type u} (f : α → option_t m β) : Option α → m (Option β) := sorry protected def bind {m : Type u → Type v} [Monad m] {α : Type u} {β : Type u} (ma : option_t m α) (f : α → option_t m β) : option_t m β := mk (run ma >>= option_t.bind_cont f) protected def pure {m : Type u → Type v} [Monad m] {α : Type u} (a : α) : option_t m α := mk (pure (some a)) protected instance monad {m : Type u → Type v} [Monad m] : Monad (option_t m) := sorry protected def orelse {m : Type u → Type v} [Monad m] {α : Type u} (ma : option_t m α) (mb : option_t m α) : option_t m α := mk do run ma sorry protected def fail {m : Type u → Type v} [Monad m] {α : Type u} : option_t m α := mk (pure none) def of_option {m : Type u → Type v} [Monad m] {α : Type u} : Option α → option_t m α := sorry protected instance alternative {m : Type u → Type v} [Monad m] : alternative (option_t m) := alternative.mk option_t.fail protected def lift {m : Type u → Type v} [Monad m] {α : Type u} (ma : m α) : option_t m α := mk (some <$> ma) protected instance has_monad_lift {m : Type u → Type v} [Monad m] : has_monad_lift m (option_t m) := has_monad_lift.mk option_t.lift protected def monad_map {m : Type u → Type v} [Monad m] {m' : Type u → Type u_1} [Monad m'] {α : Type u} (f : {α : Type u} → m α → m' α) : option_t m α → option_t m' α := fun (x : option_t m α) => mk (f (run x)) protected instance monad_functor {m : Type u → Type v} [Monad m] (m' : Type u → Type v) [Monad m'] : monad_functor m m' (option_t m) (option_t m') := monad_functor.mk fun (α : Type u) => option_t.monad_map protected def catch {m : Type u → Type v} [Monad m] {α : Type u} (ma : option_t m α) (handle : Unit → option_t m α) : option_t m α := mk do run ma sorry protected instance monad_except {m : Type u → Type v} [Monad m] : monad_except Unit (option_t m) := monad_except.mk (fun (_x : Type u) (_x_1 : Unit) => option_t.fail) option_t.catch protected instance monad_run (m : Type u_1 → Type u_2) (out : outParam (Type u_1 → Type u_2)) [monad_run out m] : monad_run (fun (α : Type u_1) => out (Option α)) (option_t m) := monad_run.mk fun (α : Type u_1) => run ∘ run
57fcdfa14f946fd6fbef6d49523e7ccbcef2afc1
18a72c9e704298dc782e2cc8d85d0a37e783a3f4
/Expander.lean
4732a3bb049992700518cecedbfc687f7bffeb05
[]
no_license
Kha/macro-supplement
dfb6298f8aafc700a2aea1820ace70e3d0f6ab43
1d98fe918cc70433a489cae1dab5b2b2f889829d
refs/heads/master
1,677,039,200,024
1,675,790,384,000
1,675,790,384,000
236,180,481
7
1
null
1,650,524,499,000
1,579,962,356,000
Lean
UTF-8
Lean
false
false
12,144
lean
import Lean namespace Lean namespace Expander open Lean.Syntax -- Result of name resolution. As in the paper, we will ignore the second component here. abbrev NameRes := Name × List String -- We model the global context more precisely as a mapping from symbols to qualified symbols, -- e.g. (`a ↦ [`ns1.a, `ns2.a]) abbrev GlobalContext := Name → List NameRes -- the simplified transformer monad structure TransformerContext where gctx : GlobalContext currMacroScope : MacroScope abbrev TransformerM := ReaderT TransformerContext Id abbrev Transformer := Syntax → TransformerM Syntax -- support syntax quotations in transformers instance : MonadQuotation TransformerM where getCurrMacroScope := do let ctx ← read; pure ctx.currMacroScope -- dummy impls, unused withFreshMacroScope := fun x => x getRef := pure Syntax.missing withRef := fun _ x => x -- The actual implementation also adds the current module name to macro scopes for global uniqueness, -- which we can ignore in this single-file example. getMainModule := pure `Expander -- the expander extension of the transformer monad structure ExpanderContext extends TransformerContext where lctx : NameSet macros : Name → Option Transformer abbrev ExpanderM := ReaderT ExpanderContext <| StateT MacroScope <| ExceptT String <| Id instance MonadQuotation : MonadQuotation ExpanderM where getCurrMacroScope := do let ctx ← read; pure ctx.currMacroScope withFreshMacroScope := fun x => do let fresh ← modifyGet (fun n => (n, n + 1)) withReader (fun ctx => { ctx with currMacroScope := fresh }) x getMainModule := pure `Expander -- dummy impls, unused getRef := pure Syntax.missing withRef := fun _ x => x -- implicitly coerce transformer monad into expander monad instance : Coe (TransformerM α) (ExpanderM α) where coe t := fun ctx => t ctx.toTransformerContext -- simplified: ignore the module name parameter def addMacroScope (n : Name) (scp : MacroScope) : Name := Lean.addMacroScope `Expander n scp def getGlobalContext : TransformerM GlobalContext := do return (← read).gctx def getLocalContext : ExpanderM NameSet := do return (← read).lctx def resolve (gctx : GlobalContext) (n : Name) : List NameRes := gctx n -- slightly more meaningful name def getIdentVal : Syntax → Name := Syntax.getId def getPreresolved : Syntax → List NameRes | Syntax.ident (preresolved := preresolved) .. => preresolved | _ => [] def mkOverloadedIds (cs : List NameRes) : Syntax := Syntax.node SourceInfo.none choiceKind (cs.toArray.map (mkIdent ∘ Prod.fst)) def withLocal (l : Name) : ExpanderM Syntax → ExpanderM Syntax := withReader (fun ctx => { ctx with lctx := ctx.lctx.insert l }) def getTransformerFor (k : SyntaxNodeKind) : ExpanderM (Syntax → ExpanderM Syntax) := do match (← read).macros k with | some t => return fun stx => t stx | none => throw ("unknown macro " ++ toString k) -- slightly simplified from the actual implementation partial def getAntiquotationIds (stx : Syntax) : ExpanderM (Array Syntax) := do let mut ids := #[] for stx in stx.topDown do if (isAntiquot stx || isTokenAntiquot stx) && !isEscapedAntiquot stx then let anti := getAntiquotTerm stx if anti.isIdent then ids := ids.push anti else throw "complex antiquotation not allowed here" return ids -- Get all pattern vars (as `Syntax.ident`s) in `stx` partial def getPatternVars (stx : Syntax) : ExpanderM (Array Syntax) := if stx.isQuot then getAntiquotationIds stx else match stx with | `(_) => pure #[] | `($id:ident) => pure #[id] | `($id:ident@$e) => do return (← getPatternVars e).push id | _ => throw "unsupported pattern in syntax match" -- expand partial def expand : Syntax → ExpanderM Syntax | `($id:ident) => do let val : Name := getIdentVal id let gctx ← getGlobalContext let lctx ← getLocalContext if lctx.contains val then pure (mkIdent val) else match resolve gctx val ++ getPreresolved id with | [] => throw ("unknown identifier " ++ toString val) | [(id, _)] => pure (mkIdent id) | ids => pure (mkOverloadedIds ids) | `(fun ($id : $ty) => $e) => do let val := getIdentVal id let ty ← expand ty let e ← withLocal val (expand e) `(fun ($(mkIdent val) : $ty) => $e) -- end -- more core forms | `(fun $id:ident => $e) => do let e ← withLocal (getIdentVal id) (expand e) `(fun $id:ident => $e) | `($num:num) => `($num:num) | `($str:str) => `($str:str) | `($n:quotedName) => `($n:quotedName) | `($fn $args*) => do let fn ← expand fn let args ← args.mapM expand `($fn $args*) | `(def $id := $e) => do let e ← expand e `(def $id := $e) -- syntax: keep as-is | `(syntax $[(name := $n)]? $[(priority := $prio)]? $[$args:stx]* : $kind) => `(syntax $[(name := $n)]? $[(priority := $prio)]? $[$args:stx]* : $kind) -- macro_rules: expand rhs (but not lhs) to exercise syntax quotation macro | `(macro_rules | $lhs => $rhs) => do let vars ← getPatternVars lhs let rhs ← vars.foldr (fun var ex => withLocal var.getId ex) (expand rhs) `(macro_rules | $lhs => $rhs) -- we will ignore double-backtick quotations generated by `notation` for this example | `(``($e)) => `(`($e)) | stx => do -- expansion consists of multiple commands => yield and get called back per command if stx.isOfKind nullKind then pure stx else do let t ← getTransformerFor stx.getKind let stx ← withFreshMacroScope (t stx) expand stx open Lean.Elab.Term.Quotation -- quoteSyntax partial def quoteSyntax : Syntax → TransformerM Syntax | Syntax.ident info rawVal val preresolved => do let gctx ← getGlobalContext let preresolved := resolve gctx val ++ preresolved `(Syntax.ident SourceInfo.none $(quote rawVal) (addMacroScope $(quote val) msc) $(quote preresolved)) | stx@(Syntax.node _ k args) => if isAntiquot stx then pure (getAntiquotTerm stx) else do let args ← args.mapM quoteSyntax `(Syntax.node SourceInfo.none $(quote k) $(quote args)) | Syntax.atom info val => `(Syntax.atom SourceInfo.none $(quote val)) | Syntax.missing => pure Syntax.missing def expandStxQuot (stx : Syntax) : TransformerM Syntax := do let stx ← quoteSyntax (stx.getArg 1) `(do msc ← getCurrMacroScope; pure $stx) -- end -- two more, simple macros def expandDo : Transformer | `(do $id:ident ← $val:term; $body:term) => `(Bind.bind $val (fun $id:ident => $body)) | _ => pure Syntax.missing def expandParen : Transformer | `(($e)) => pure e | _ => pure Syntax.missing -- custom Syntax pretty printer for our core forms that uses the paper's notation for hygienic identifiers def ppIdent (n : Name) : Format := let v := extractMacroScopes n format <| v.scopes.foldl Name.mkNum v.name -- flip to make output more readable def hideMacroRulesRhs := false open Std.Format partial def pp : Syntax → Format | `($id:ident) => match getPreresolved id with | [] => ppIdent id.getId | ps => ppIdent id.getId ++ bracket "{" (joinSep (ps.map (format ∘ Prod.fst)) ", ") "}" | `(fun ($id : $ty) => $e) => paren f!"fun {paren (pp id ++ " : " ++ pp ty)} => {pp e}" | `(fun $id => $e) => paren f!"fun {pp id} => {pp e}" | `($num:num) => format (num.isNatLit?.getD 0) | `($str:str) => repr (str.isStrLit?.getD "") | `($fn $args*) => paren <| pp fn ++ " " ++ joinSep (args.toList.map pp) line | `(def $id:ident := $e) => f!"def {ppIdent id.getId} := {pp e}" | `(syntax $[(name := $n)]? $[(priority := $prio)]? $[$args:stx]* : $kind) => "syntax ..." -- irrelevant for this example | `(macro_rules | $lhs => $rhs) => f!"macro_rules |{lhs.reprint.getD ""} => {if hideMacroRulesRhs then f!"..." else pp rhs}" | stx => f!"<not a core form: {stx}>" -- integrate example expander into frontend, between parser and elaborator. Not pretty. section Elaboration open Lean.Elab open Lean.Elab.Frontend -- run expander: adapt global context and set of macro from Environment def expanderToFrontend (ref : Syntax) (e : ExpanderM Syntax) : FrontendM Syntax := runCommandElabM <| withRef ref do let st ← get let scope := st.scopes.head! match e { gctx := fun n => (match st.env.find? n with | some _ => [(n, [])] | none => [] : List NameRes), lctx := {}, currMacroScope := st.nextMacroScope, macros := fun k => -- our hardcoded example macros if k == `Lean.Parser.Term.quot then some expandStxQuot else if k == `Lean.Parser.Term.do then some expandDo else if k == `Lean.Parser.Term.paren then some expandParen -- `notation`, `macro`, and macros generated at runtime else match macroAttribute.getValues st.env k with | t::_ => some (fun stx ctx => match t stx { mainModule := `Expander currMacroScope := ctx.currMacroScope ref := ref methods := Macro.mkMethods { expandMacro? := fun stx => do match (← expandMacroImpl? st.env stx) with | some (_, Except.ok stx') => return some stx' | _ => return none hasDecl := fun declName => return st.env.contains declName getCurrNamespace := return scope.currNamespace resolveNamespace? := fun n => return ResolveName.resolveNamespace? st.env scope.currNamespace scope.openDecls n resolveGlobalName := fun n => return ResolveName.resolveGlobalName st.env scope.currNamespace scope.openDecls n } } { macroScope := 0 } with | EStateM.Result.ok stx s => stx | _ => Syntax.missing) | _ => none } (st.nextMacroScope + 1) with | Except.ok (stx, nextMacroScope) => do modify (fun st => {st with nextMacroScope := nextMacroScope}) pure stx | Except.error e => do logError e pure Syntax.missing partial def processCommand (cmd : Syntax) : FrontendM Unit := do let cmd' ← expanderToFrontend cmd <| expand cmd if cmd'.isOfKind nullKind then -- expander returned multiple commands => process in turn cmd'.getArgs.forM processCommand else do runCommandElabM <| logInfo (pp cmd') elabCommandAtFrontend cmd' partial def processCommands : FrontendM Unit := do let cmdState ← getCommandState let parserState ← getParserState let inputCtx ← getInputContext let scope := cmdState.scopes.head! let pmctx := { env := cmdState.env, options := scope.opts, currNamespace := scope.currNamespace, openDecls := scope.openDecls } let (cmd, ps, messages) ← pure (Parser.parseCommand inputCtx pmctx parserState cmdState.messages) setParserState ps setMessages messages if Parser.isEOI cmd then do pure () else do processCommand cmd processCommands def process (input : String) (env : Environment) (opts : Options) (fileName : Option String := none) : IO (Environment × MessageLog) := do let fileName := fileName.getD "<input>" let inputCtx := Parser.mkInputContext input fileName let (_, st) ← processCommands { inputCtx := inputCtx } |>.run { commandState := Command.mkState env {} opts, parserState := {}, cmdPos := 0 } pure (st.commandState.env, st.commandState.messages) def run (input : String) : CoreM Unit := do let env ← getEnv let opts ← getOptions let (env, messages) ← liftM $ process input env opts messages.forM fun msg => do IO.println (← msg.toString) end Elaboration -- examples -- see also `hideMacroRulesRhs` above #eval run " def x := 1 def e := fun (y : Nat) => x notation \"const\" e => fun (x : Nat) => e def y := const x " #eval run " macro \"m\" n:ident : command => `( def f := 1 macro \"mm\" : command => `( def $n:ident := f def f := $n:ident)) m f mm mm " end Expander end Lean
9a3c998cbb28d27eda22b39e473e16839f2c43e4
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/category/GroupWithZero.lean
522d953a2e39672d0b1f3ad41a4b511b51308aa4
[ "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
2,147
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import category_theory.category.Bipointed import algebra.category.Mon.basic /-! # The category of groups with zero > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines `GroupWithZero`, the category of groups with zero. -/ universes u open category_theory order /-- The category of groups with zero. -/ def GroupWithZero := bundled group_with_zero namespace GroupWithZero instance : has_coe_to_sort GroupWithZero Type* := bundled.has_coe_to_sort instance (X : GroupWithZero) : group_with_zero X := X.str /-- Construct a bundled `GroupWithZero` from a `group_with_zero`. -/ def of (α : Type*) [group_with_zero α] : GroupWithZero := bundled.of α instance : inhabited GroupWithZero := ⟨of (with_zero punit)⟩ instance : large_category.{u} GroupWithZero := { hom := λ X Y, monoid_with_zero_hom X Y, id := λ X, monoid_with_zero_hom.id X, comp := λ X Y Z f g, g.comp f, id_comp' := λ X Y, monoid_with_zero_hom.comp_id, comp_id' := λ X Y, monoid_with_zero_hom.id_comp, assoc' := λ W X Y Z _ _ _, monoid_with_zero_hom.comp_assoc _ _ _ } instance : concrete_category GroupWithZero := { forget := ⟨coe_sort, λ X Y, coe_fn, λ X, rfl, λ X Y Z f g, rfl⟩, forget_faithful := ⟨λ X Y f g h, fun_like.coe_injective h⟩ } instance has_forget_to_Bipointed : has_forget₂ GroupWithZero Bipointed := { forget₂ := { obj := λ X, ⟨X, 0, 1⟩, map := λ X Y f, ⟨f, f.map_zero', f.map_one'⟩ } } instance has_forget_to_Mon : has_forget₂ GroupWithZero Mon := { forget₂ := { obj := λ X, ⟨X⟩, map := λ X Y, monoid_with_zero_hom.to_monoid_hom } } /-- Constructs an isomorphism of groups with zero from a group isomorphism between them. -/ @[simps] def iso.mk {α β : GroupWithZero.{u}} (e : α ≃* β) : α ≅ β := { hom := e, inv := e.symm, hom_inv_id' := by { ext, exact e.symm_apply_apply _ }, inv_hom_id' := by { ext, exact e.apply_symm_apply _ } } end GroupWithZero
700901b5b6d644bc52f0337388e01cee923b0882
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/data/mv_polynomial/monad.lean
7511e15b03d8d500d2f850bac511aa0a3fc86427
[ "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
13,429
lean
/- Copyright (c) 2020 Johan Commelin, Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Robert Y. Lewis -/ import data.mv_polynomial.rename /-! # Monad operations on `mv_polynomial` This file defines two monadic operations on `mv_polynomial`. Given `p : mv_polynomial σ R`, * `mv_polynomial.bind₁` and `mv_polynomial.join₁` operate on the variable type `σ`. * `mv_polynomial.bind₂` and `mv_polynomial.join₂` operate on the coefficient type `R`. - `mv_polynomial.bind₁ f φ` with `f : σ → mv_polynomial τ R` and `φ : mv_polynomial σ R`, is the polynomial `φ(f 1, ..., f i, ...) : mv_polynomial τ R`. - `mv_polynomial.join₁ φ` with `φ : mv_polynomial (mv_polynomial σ R) R` collapses `φ` to a `mv_polynomial σ R`, by evaluating `φ` under the map `X f ↦ f` for `f : mv_polynomial σ R`. In other words, if you have a polynomial `φ` in a set of variables indexed by a polynomial ring, you evaluate the polynomial in these indexing polynomials. - `mv_polynomial.bind₂ f φ` with `f : R →+* mv_polynomial σ S` and `φ : mv_polynomial σ R` is the `mv_polynomial σ S` obtained from `φ` by mapping the coefficients of `φ` through `f` and considering the resulting polynomial as polynomial expression in `mv_polynomial σ R`. - `mv_polynomial.join₂ φ` with `φ : mv_polynomial σ (mv_polynomial σ R)` collapses `φ` to a `mv_polynomial σ R`, by considering `φ` as polynomial expression in `mv_polynomial σ R`. These operations themselves have algebraic structure: `mv_polynomial.bind₁` and `mv_polynomial.join₁` are algebra homs and `mv_polynomial.bind₂` and `mv_polynomial.join₂` are ring homs. They interact in convenient ways with `mv_polynomial.rename`, `mv_polynomial.map`, `mv_polynomial.vars`, and other polynomial operations. Indeed, `mv_polynomial.rename` is the "map" operation for the (`bind₁`, `join₁`) pair, whereas `mv_polynomial.map` is the "map" operation for the other pair. ## Implementation notes We add an `is_lawful_monad` instance for the (`bind₁`, `join₁`) pair. The second pair cannot be instantiated as a `monad`, since it is not a monad in `Type` but in `CommRing` (or rather `CommSemiRing`). -/ open_locale big_operators noncomputable theory namespace mv_polynomial open finsupp variables {σ : Type*} {τ : Type*} variables {R S T : Type*} [comm_semiring R] [comm_semiring S] [comm_semiring T] /-- `bind₁` is the "left hand side" bind operation on `mv_polynomial`, operating on the variable type. Given a polynomial `p : mv_polynomial σ R` and a map `f : σ → mv_polynomial τ R` taking variables in `p` to polynomials in the variable type `τ`, `bind₁ f p` replaces each variable in `p` with its value under `f`, producing a new polynomial in `τ`. The coefficient type remains the same. This operation is an algebra hom. -/ def bind₁ (f : σ → mv_polynomial τ R) : mv_polynomial σ R →ₐ[R] mv_polynomial τ R := aeval f /-- `bind₂` is the "right hand side" bind operation on `mv_polynomial`, operating on the coefficient type. Given a polynomial `p : mv_polynomial σ R` and a map `f : R → mv_polynomial σ S` taking coefficients in `p` to polynomials over a new ring `S`, `bind₂ f p` replaces each coefficient in `p` with its value under `f`, producing a new polynomial over `S`. The variable type remains the same. This operation is a ring hom. -/ def bind₂ (f : R →+* mv_polynomial σ S) : mv_polynomial σ R →+* mv_polynomial σ S := eval₂_hom f X /-- `join₁` is the monadic join operation corresponding to `mv_polynomial.bind₁`. Given a polynomial `p` with coefficients in `R` whose variables are polynomials in `σ` with coefficients in `R`, `join₁ p` collapses `p` to a polynomial with variables in `σ` and coefficients in `R`. This operation is an algebra hom. -/ def join₁ : mv_polynomial (mv_polynomial σ R) R →ₐ[R] mv_polynomial σ R := aeval id /-- `join₂` is the monadic join operation corresponding to `mv_polynomial.bind₂`. Given a polynomial `p` with variables in `σ` whose coefficients are polynomials in `σ` with coefficients in `R`, `join₂ p` collapses `p` to a polynomial with variables in `σ` and coefficients in `R`. This operation is a ring hom. -/ def join₂ : mv_polynomial σ (mv_polynomial σ R) →+* mv_polynomial σ R := eval₂_hom (ring_hom.id _) X @[simp] lemma aeval_eq_bind₁ (f : σ → mv_polynomial τ R) : aeval f = bind₁ f := rfl @[simp] lemma eval₂_hom_C_eq_bind₁ (f : σ → mv_polynomial τ R) : eval₂_hom C f = bind₁ f := rfl @[simp] lemma eval₂_hom_eq_bind₂ (f : R →+* mv_polynomial σ S) : eval₂_hom f X = bind₂ f := rfl section variables (σ R) @[simp] lemma aeval_id_eq_join₁ : aeval id = @join₁ σ R _ := rfl lemma eval₂_hom_C_id_eq_join₁ (φ : mv_polynomial (mv_polynomial σ R) R) : eval₂_hom C id φ = join₁ φ := rfl @[simp] lemma eval₂_hom_id_X_eq_join₂ : eval₂_hom (ring_hom.id _) X = @join₂ σ R _ := rfl end -- In this file, we don't want to use these simp lemmas, -- because we first need to show how these new definitions interact -- and the proofs fall back on unfolding the definitions and call simp afterwards local attribute [-simp] aeval_eq_bind₁ eval₂_hom_C_eq_bind₁ eval₂_hom_eq_bind₂ aeval_id_eq_join₁ eval₂_hom_id_X_eq_join₂ @[simp] lemma bind₁_X_right (f : σ → mv_polynomial τ R) (i : σ) : bind₁ f (X i) = f i := aeval_X f i @[simp] lemma bind₂_X_right (f : R →+* mv_polynomial σ S) (i : σ) : bind₂ f (X i) = X i := eval₂_hom_X' f X i @[simp] lemma bind₁_X_left : bind₁ (X : σ → mv_polynomial σ R) = alg_hom.id R _ := by { ext1 i, simp } lemma aeval_X_left : aeval (X : σ → mv_polynomial σ R) = alg_hom.id R _ := by rw [aeval_eq_bind₁, bind₁_X_left] lemma aeval_X_left_apply (φ : mv_polynomial σ R) : aeval X φ = φ := by rw [aeval_eq_bind₁, bind₁_X_left, alg_hom.id_apply] variable (f : σ → mv_polynomial τ R) @[simp] lemma bind₁_C_right (f : σ → mv_polynomial τ R) (x) : bind₁ f (C x) = C x := by simp [bind₁, C, aeval_monomial, finsupp.prod_zero_index]; refl @[simp] lemma bind₂_C_right (f : R →+* mv_polynomial σ S) (r : R) : bind₂ f (C r) = f r := eval₂_hom_C f X r @[simp] lemma bind₂_C_left : bind₂ (C : R →+* mv_polynomial σ R) = ring_hom.id _ := by { ext : 2; simp } @[simp] lemma bind₂_comp_C (f : R →+* mv_polynomial σ S) : (bind₂ f).comp C = f := ring_hom.ext $ bind₂_C_right _ @[simp] lemma join₂_map (f : R →+* mv_polynomial σ S) (φ : mv_polynomial σ R) : join₂ (map f φ) = bind₂ f φ := by simp only [join₂, bind₂, eval₂_hom_map_hom, ring_hom.id_comp] @[simp] lemma join₂_comp_map (f : R →+* mv_polynomial σ S) : join₂.comp (map f) = bind₂ f := ring_hom.ext $ join₂_map _ lemma aeval_id_rename (f : σ → mv_polynomial τ R) (p : mv_polynomial σ R) : aeval id (rename f p) = aeval f p := by rw [aeval_rename, function.comp.left_id] @[simp] lemma join₁_rename (f : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : join₁ (rename f φ) = bind₁ f φ := aeval_id_rename _ _ @[simp] lemma bind₁_id : bind₁ (@id (mv_polynomial σ R)) = join₁ := rfl @[simp] lemma bind₂_id : bind₂ (ring_hom.id (mv_polynomial σ R)) = join₂ := rfl lemma bind₁_bind₁ {υ : Type*} (f : σ → mv_polynomial τ R) (g : τ → mv_polynomial υ R) (φ : mv_polynomial σ R) : (bind₁ g) (bind₁ f φ) = bind₁ (λ i, bind₁ g (f i)) φ := by simp [bind₁, ← comp_aeval] lemma bind₁_comp_bind₁ {υ : Type*} (f : σ → mv_polynomial τ R) (g : τ → mv_polynomial υ R) : (bind₁ g).comp (bind₁ f) = bind₁ (λ i, bind₁ g (f i)) := by { ext1, apply bind₁_bind₁ } lemma bind₂_comp_bind₂ (f : R →+* mv_polynomial σ S) (g : S →+* mv_polynomial σ T) : (bind₂ g).comp (bind₂ f) = bind₂ ((bind₂ g).comp f) := by { ext : 2; simp } lemma bind₂_bind₂ (f : R →+* mv_polynomial σ S) (g : S →+* mv_polynomial σ T) (φ : mv_polynomial σ R) : (bind₂ g) (bind₂ f φ) = bind₂ ((bind₂ g).comp f) φ := ring_hom.congr_fun (bind₂_comp_bind₂ f g) φ lemma rename_comp_bind₁ {υ : Type*} (f : σ → mv_polynomial τ R) (g : τ → υ) : (rename g).comp (bind₁ f) = bind₁ (λ i, rename g $ f i) := by { ext1 i, simp } lemma rename_bind₁ {υ : Type*} (f : σ → mv_polynomial τ R) (g : τ → υ) (φ : mv_polynomial σ R) : rename g (bind₁ f φ) = bind₁ (λ i, rename g $ f i) φ := alg_hom.congr_fun (rename_comp_bind₁ f g) φ lemma map_bind₂ (f : R →+* mv_polynomial σ S) (g : S →+* T) (φ : mv_polynomial σ R) : map g (bind₂ f φ) = bind₂ ((map g).comp f) φ := begin simp only [bind₂, eval₂_comp_right, coe_eval₂_hom, eval₂_map], congr' 1 with : 1, simp only [function.comp_app, map_X] end lemma bind₁_comp_rename {υ : Type*} (f : τ → mv_polynomial υ R) (g : σ → τ) : (bind₁ f).comp (rename g) = bind₁ (f ∘ g) := by { ext1 i, simp } lemma bind₁_rename {υ : Type*} (f : τ → mv_polynomial υ R) (g : σ → τ) (φ : mv_polynomial σ R) : bind₁ f (rename g φ) = bind₁ (f ∘ g) φ := alg_hom.congr_fun (bind₁_comp_rename f g) φ lemma bind₂_map (f : S →+* mv_polynomial σ T) (g : R →+* S) (φ : mv_polynomial σ R) : bind₂ f (map g φ) = bind₂ (f.comp g) φ := by simp [bind₂] @[simp] lemma map_comp_C (f : R →+* S) : (map f).comp (C : R →+* mv_polynomial σ R) = C.comp f := by { ext1, apply map_C } -- mixing the two monad structures lemma hom_bind₁ (f : mv_polynomial τ R →+* S) (g : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : f (bind₁ g φ) = eval₂_hom (f.comp C) (λ i, f (g i)) φ := by rw [bind₁, map_aeval, algebra_map_eq] lemma map_bind₁ (f : R →+* S) (g : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : map f (bind₁ g φ) = bind₁ (λ (i : σ), (map f) (g i)) (map f φ) := by { rw [hom_bind₁, map_comp_C, ← eval₂_hom_map_hom], refl } @[simp] lemma eval₂_hom_comp_C (f : R →+* S) (g : σ → S) : (eval₂_hom f g).comp C = f := by { ext1 r, exact eval₂_C f g r } lemma eval₂_hom_bind₁ (f : R →+* S) (g : τ → S) (h : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : eval₂_hom f g (bind₁ h φ) = eval₂_hom f (λ i, eval₂_hom f g (h i)) φ := by rw [hom_bind₁, eval₂_hom_comp_C] lemma aeval_bind₁ [algebra R S] (f : τ → S) (g : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : aeval f (bind₁ g φ) = aeval (λ i, aeval f (g i)) φ := eval₂_hom_bind₁ _ _ _ _ lemma aeval_comp_bind₁ [algebra R S] (f : τ → S) (g : σ → mv_polynomial τ R) : (aeval f).comp (bind₁ g) = aeval (λ i, aeval f (g i)) := by { ext1, apply aeval_bind₁ } lemma eval₂_hom_comp_bind₂ (f : S →+* T) (g : σ → T) (h : R →+* mv_polynomial σ S) : (eval₂_hom f g).comp (bind₂ h) = eval₂_hom ((eval₂_hom f g).comp h) g := by { ext : 2; simp } lemma eval₂_hom_bind₂ (f : S →+* T) (g : σ → T) (h : R →+* mv_polynomial σ S) (φ : mv_polynomial σ R) : eval₂_hom f g (bind₂ h φ) = eval₂_hom ((eval₂_hom f g).comp h) g φ := ring_hom.congr_fun (eval₂_hom_comp_bind₂ f g h) φ lemma aeval_bind₂ [algebra S T] (f : σ → T) (g : R →+* mv_polynomial σ S) (φ : mv_polynomial σ R) : aeval f (bind₂ g φ) = eval₂_hom ((↑(aeval f : _ →ₐ[S] _) : _ →+* _).comp g) f φ := eval₂_hom_bind₂ _ _ _ _ lemma eval₂_hom_C_left (f : σ → mv_polynomial τ R) : eval₂_hom C f = bind₁ f := rfl lemma bind₁_monomial (f : σ → mv_polynomial τ R) (d : σ →₀ ℕ) (r : R) : bind₁ f (monomial d r) = C r * ∏ i in d.support, f i ^ d i := by simp only [monomial_eq, alg_hom.map_mul, bind₁_C_right, finsupp.prod, alg_hom.map_prod, alg_hom.map_pow, bind₁_X_right] lemma bind₂_monomial (f : R →+* mv_polynomial σ S) (d : σ →₀ ℕ) (r : R) : bind₂ f (monomial d r) = f r * monomial d 1 := by simp only [monomial_eq, ring_hom.map_mul, bind₂_C_right, finsupp.prod, ring_hom.map_prod, ring_hom.map_pow, bind₂_X_right, C_1, one_mul] @[simp] lemma bind₂_monomial_one (f : R →+* mv_polynomial σ S) (d : σ →₀ ℕ) : bind₂ f (monomial d 1) = monomial d 1 := by rw [bind₂_monomial, f.map_one, one_mul] instance monad : monad (λ σ, mv_polynomial σ R) := { map := λ α β f p, rename f p, pure := λ _, X, bind := λ _ _ p f, bind₁ f p } instance is_lawful_functor : is_lawful_functor (λ σ, mv_polynomial σ R) := { id_map := by intros; simp [(<$>)], comp_map := by intros; simp [(<$>)] } instance is_lawful_monad : is_lawful_monad (λ σ, mv_polynomial σ R) := { pure_bind := by intros; simp [pure, bind], bind_assoc := by intros; simp [bind, ← bind₁_comp_bind₁] } /- Possible TODO for the future: Enable the following definitions, and write a lot of supporting lemmas. def bind (f : R →+* mv_polynomial τ S) (g : σ → mv_polynomial τ S) : mv_polynomial σ R →+* mv_polynomial τ S := eval₂_hom f g def join (f : R →+* S) : mv_polynomial (mv_polynomial σ R) S →ₐ[S] mv_polynomial σ S := aeval (map f) def ajoin [algebra R S] : mv_polynomial (mv_polynomial σ R) S →ₐ[S] mv_polynomial σ S := join (algebra_map R S) -/ end mv_polynomial
2d93dc2e85f5f6c44aaeb3a465542f189d61b089
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/order/conditionally_complete_lattice.lean
700eeaafb65c0a069c0268ab9343a86af7687fec
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
28,023
lean
/- Copyright (c) 2018 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel Adapted from the corresponding theory for complete lattices. -/ import order.lattice order.complete_lattice order.bounds tactic.finish data.nat.enat /-! # Theory of conditionally complete lattices. A conditionally complete lattice is a lattice in which every non-empty bounded subset s has a least upper bound and a greatest lower bound, denoted below by Sup s and Inf s. Typical examples are real, nat, int with their usual orders. The theory is very comparable to the theory of complete lattices, except that suitable boundedness and nonemptiness assumptions have to be added to most statements. We introduce two predicates bdd_above and bdd_below to express this boundedness, prove their basic properties, and then go on to prove most useful properties of Sup and Inf in conditionally complete lattices. To differentiate the statements between complete lattices and conditionally complete lattices, we prefix Inf and Sup in the statements by c, giving cInf and cSup. For instance, Inf_le is a statement in complete lattices ensuring Inf s ≤ x, while cInf_le is the same statement in conditionally complete lattices with an additional assumption that s is bounded below. -/ set_option old_structure_cmd true open set universes u v w variables {α : Type u} {β : Type v} {ι : Sort w} section /-! Extension of Sup and Inf from a preorder `α` to `with_top α` and `with_bot α` -/ open_locale classical noncomputable instance {α : Type*} [preorder α] [has_Sup α] : has_Sup (with_top α) := ⟨λ S, if ⊤ ∈ S then ⊤ else if bdd_above (coe ⁻¹' S : set α) then ↑(Sup (coe ⁻¹' S : set α)) else ⊤⟩ noncomputable instance {α : Type*} [has_Inf α] : has_Inf (with_top α) := ⟨λ S, if S ⊆ {⊤} then ⊤ else ↑(Inf (coe ⁻¹' S : set α))⟩ noncomputable instance {α : Type*} [has_Sup α] : has_Sup (with_bot α) := ⟨(@with_top.has_Inf (order_dual α) _).Inf⟩ noncomputable instance {α : Type*} [preorder α] [has_Inf α] : has_Inf (with_bot α) := ⟨(@with_top.has_Sup (order_dual α) _ _).Sup⟩ end -- section section prio set_option default_priority 100 -- see Note [default priority] /-- A conditionally complete lattice is a lattice in which every nonempty subset which is bounded above has a supremum, and every nonempty subset which is bounded below has an infimum. Typical examples are real numbers or natural numbers. To differentiate the statements from the corresponding statements in (unconditional) complete lattices, we prefix Inf and Sup by a c everywhere. The same statements should hold in both worlds, sometimes with additional assumptions of nonemptiness or boundedness.-/ class conditionally_complete_lattice (α : Type u) extends lattice α, has_Sup α, has_Inf α := (le_cSup : ∀s a, bdd_above s → a ∈ s → a ≤ Sup s) (cSup_le : ∀ s a, set.nonempty s → a ∈ upper_bounds s → Sup s ≤ a) (cInf_le : ∀s a, bdd_below s → a ∈ s → Inf s ≤ a) (le_cInf : ∀s a, set.nonempty s → a ∈ lower_bounds s → a ≤ Inf s) class conditionally_complete_linear_order (α : Type u) extends conditionally_complete_lattice α, decidable_linear_order α class conditionally_complete_linear_order_bot (α : Type u) extends conditionally_complete_lattice α, decidable_linear_order α, order_bot α := (cSup_empty : Sup ∅ = ⊥) end prio /- A complete lattice is a conditionally complete lattice, as there are no restrictions on the properties of Inf and Sup in a complete lattice.-/ @[priority 100] -- see Note [lower instance priority] instance conditionally_complete_lattice_of_complete_lattice [complete_lattice α]: conditionally_complete_lattice α := { le_cSup := by intros; apply le_Sup; assumption, cSup_le := by intros; apply Sup_le; assumption, cInf_le := by intros; apply Inf_le; assumption, le_cInf := by intros; apply le_Inf; assumption, ..‹complete_lattice α› } @[priority 100] -- see Note [lower instance priority] instance conditionally_complete_linear_order_of_complete_linear_order [complete_linear_order α]: conditionally_complete_linear_order α := { ..conditionally_complete_lattice_of_complete_lattice, .. ‹complete_linear_order α› } section conditionally_complete_lattice variables [conditionally_complete_lattice α] {s t : set α} {a b : α} theorem le_cSup (h₁ : bdd_above s) (h₂ : a ∈ s) : a ≤ Sup s := conditionally_complete_lattice.le_cSup s a h₁ h₂ theorem cSup_le (h₁ : s.nonempty) (h₂ : ∀b∈s, b ≤ a) : Sup s ≤ a := conditionally_complete_lattice.cSup_le s a h₁ h₂ theorem cInf_le (h₁ : bdd_below s) (h₂ : a ∈ s) : Inf s ≤ a := conditionally_complete_lattice.cInf_le s a h₁ h₂ theorem le_cInf (h₁ : s.nonempty) (h₂ : ∀b∈s, a ≤ b) : a ≤ Inf s := conditionally_complete_lattice.le_cInf s a h₁ h₂ theorem le_cSup_of_le (_ : bdd_above s) (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s := le_trans h (le_cSup ‹bdd_above s› hb) theorem cInf_le_of_le (_ : bdd_below s) (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a := le_trans (cInf_le ‹bdd_below s› hb) h theorem cSup_le_cSup (_ : bdd_above t) (_ : s.nonempty) (h : s ⊆ t) : Sup s ≤ Sup t := cSup_le ‹_› (assume (a) (ha : a ∈ s), le_cSup ‹bdd_above t› (h ha)) theorem cInf_le_cInf (_ : bdd_below t) (_ : s.nonempty) (h : s ⊆ t) : Inf t ≤ Inf s := le_cInf ‹_› (assume (a) (ha : a ∈ s), cInf_le ‹bdd_below t› (h ha)) lemma is_lub_cSup (ne : s.nonempty) (H : bdd_above s) : is_lub s (Sup s) := ⟨assume x, le_cSup H, assume x, cSup_le ne⟩ lemma is_glb_cInf (ne : s.nonempty) (H : bdd_below s) : is_glb s (Inf s) := ⟨assume x, cInf_le H, assume x, le_cInf ne⟩ lemma is_lub.cSup_eq (H : is_lub s a) (ne : s.nonempty) : Sup s = a := (is_lub_cSup ne ⟨a, H.1⟩).unique H /-- A greatest element of a set is the supremum of this set. -/ lemma is_greatest.cSup_eq (H : is_greatest s a) : Sup s = a := H.is_lub.cSup_eq H.nonempty lemma is_glb.cInf_eq (H : is_glb s a) (ne : s.nonempty) : Inf s = a := (is_glb_cInf ne ⟨a, H.1⟩).unique H /-- A least element of a set is the infimum of this set. -/ lemma is_least.cInf_eq (H : is_least s a) : Inf s = a := H.is_glb.cInf_eq H.nonempty theorem cSup_le_iff (hb : bdd_above s) (ne : s.nonempty) : Sup s ≤ a ↔ (∀b ∈ s, b ≤ a) := is_lub_le_iff (is_lub_cSup ne hb) theorem le_cInf_iff (hb : bdd_below s) (ne : s.nonempty) : a ≤ Inf s ↔ (∀b ∈ s, a ≤ b) := le_is_glb_iff (is_glb_cInf ne hb) lemma cSup_lower_bounds_eq_cInf {s : set α} (h : bdd_below s) (hs : s.nonempty) : Sup (lower_bounds s) = Inf s := (is_lub_cSup h $ hs.mono $ λ x hx y hy, hy hx).unique (is_glb_cInf hs h).is_lub lemma cInf_upper_bounds_eq_cSup {s : set α} (h : bdd_above s) (hs : s.nonempty) : Inf (upper_bounds s) = Sup s := (is_glb_cInf h $ hs.mono $ λ x hx y hy, hy hx).unique (is_lub_cSup hs h).is_glb /--Introduction rule to prove that b is the supremum of s: it suffices to check that b is larger than all elements of s, and that this is not the case of any `w<b`.-/ theorem cSup_intro (_ : s.nonempty) (_ : ∀a∈s, a ≤ b) (H : ∀w, w < b → (∃a∈s, w < a)) : Sup s = b := have bdd_above s := ⟨b, by assumption⟩, have (Sup s < b) ∨ (Sup s = b) := lt_or_eq_of_le (cSup_le ‹_› ‹∀a∈s, a ≤ b›), have ¬(Sup s < b) := assume: Sup s < b, let ⟨a, _, _⟩ := (H (Sup s) ‹Sup s < b›) in /- a ∈ s, Sup s < a-/ have Sup s < Sup s := lt_of_lt_of_le ‹Sup s < a› (le_cSup ‹bdd_above s› ‹a ∈ s›), show false, by finish [lt_irrefl (Sup s)], show Sup s = b, by finish /--Introduction rule to prove that b is the infimum of s: it suffices to check that b is smaller than all elements of s, and that this is not the case of any `w>b`.-/ theorem cInf_intro (_ : s.nonempty) (_ : ∀a∈s, b ≤ a) (H : ∀w, b < w → (∃a∈s, a < w)) : Inf s = b := have bdd_below s := ⟨b, by assumption⟩, have (b < Inf s) ∨ (b = Inf s) := lt_or_eq_of_le (le_cInf ‹_› ‹∀a∈s, b ≤ a›), have ¬(b < Inf s) := assume: b < Inf s, let ⟨a, _, _⟩ := (H (Inf s) ‹b < Inf s›) in /- a ∈ s, a < Inf s-/ have Inf s < Inf s := lt_of_le_of_lt (cInf_le ‹bdd_below s› ‹a ∈ s›) ‹a < Inf s› , show false, by finish [lt_irrefl (Inf s)], show Inf s = b, by finish /--b < Sup s when there is an element a in s with b < a, when s is bounded above. This is essentially an iff, except that the assumptions for the two implications are slightly different (one needs boundedness above for one direction, nonemptiness and linear order for the other one), so we formulate separately the two implications, contrary to the complete_lattice case.-/ lemma lt_cSup_of_lt (_ : bdd_above s) (_ : a ∈ s) (_ : b < a) : b < Sup s := lt_of_lt_of_le ‹b < a› (le_cSup ‹bdd_above s› ‹a ∈ s›) /--Inf s < b when there is an element a in s with a < b, when s is bounded below. This is essentially an iff, except that the assumptions for the two implications are slightly different (one needs boundedness below for one direction, nonemptiness and linear order for the other one), so we formulate separately the two implications, contrary to the complete_lattice case.-/ lemma cInf_lt_of_lt (_ : bdd_below s) (_ : a ∈ s) (_ : a < b) : Inf s < b := lt_of_le_of_lt (cInf_le ‹bdd_below s› ‹a ∈ s›) ‹a < b› /-- If all elements of a nonempty set `s` are less than or equal to all elements of a nonempty set `t`, then there exists an element between these sets. -/ lemma exists_between_of_forall_le (sne : s.nonempty) (tne : t.nonempty) (hst : ∀ (x ∈ s) (y ∈ t), x ≤ y) : (upper_bounds s ∩ lower_bounds t).nonempty := ⟨Inf t, λ x hx, le_cInf tne $ hst x hx, λ y hy, cInf_le (sne.mono hst) hy⟩ /--The supremum of a singleton is the element of the singleton-/ @[simp] theorem cSup_singleton (a : α) : Sup {a} = a := is_greatest_singleton.cSup_eq /--The infimum of a singleton is the element of the singleton-/ @[simp] theorem cInf_singleton (a : α) : Inf {a} = a := is_least_singleton.cInf_eq /--If a set is bounded below and above, and nonempty, its infimum is less than or equal to its supremum.-/ theorem cInf_le_cSup (hb : bdd_below s) (ha : bdd_above s) (ne : s.nonempty) : Inf s ≤ Sup s := is_glb_le_is_lub (is_glb_cInf ne hb) (is_lub_cSup ne ha) ne /--The sup of a union of two sets is the max of the suprema of each subset, under the assumptions that all sets are bounded above and nonempty.-/ theorem cSup_union (hs : bdd_above s) (sne : s.nonempty) (ht : bdd_above t) (tne : t.nonempty) : Sup (s ∪ t) = Sup s ⊔ Sup t := ((is_lub_cSup sne hs).union (is_lub_cSup tne ht)).cSup_eq sne.inl /--The inf of a union of two sets is the min of the infima of each subset, under the assumptions that all sets are bounded below and nonempty.-/ theorem cInf_union (hs : bdd_below s) (sne : s.nonempty) (ht : bdd_below t) (tne : t.nonempty) : Inf (s ∪ t) = Inf s ⊓ Inf t := ((is_glb_cInf sne hs).union (is_glb_cInf tne ht)).cInf_eq sne.inl /--The supremum of an intersection of two sets is bounded by the minimum of the suprema of each set, if all sets are bounded above and nonempty.-/ theorem cSup_inter_le (_ : bdd_above s) (_ : bdd_above t) (hst : (s ∩ t).nonempty) : Sup (s ∩ t) ≤ Sup s ⊓ Sup t := begin apply cSup_le hst, simp only [le_inf_iff, and_imp, set.mem_inter_eq], intros b _ _, split, apply le_cSup ‹bdd_above s› ‹b ∈ s›, apply le_cSup ‹bdd_above t› ‹b ∈ t› end /--The infimum of an intersection of two sets is bounded below by the maximum of the infima of each set, if all sets are bounded below and nonempty.-/ theorem le_cInf_inter (_ : bdd_below s) (_ : bdd_below t) (hst : (s ∩ t).nonempty) : Inf s ⊔ Inf t ≤ Inf (s ∩ t) := begin apply le_cInf hst, simp only [and_imp, set.mem_inter_eq, sup_le_iff], intros b _ _, split, apply cInf_le ‹bdd_below s› ‹b ∈ s›, apply cInf_le ‹bdd_below t› ‹b ∈ t› end /-- The supremum of insert a s is the maximum of a and the supremum of s, if s is nonempty and bounded above.-/ theorem cSup_insert (hs : bdd_above s) (sne : s.nonempty) : Sup (insert a s) = a ⊔ Sup s := ((is_lub_cSup sne hs).insert a).cSup_eq (insert_nonempty a s) /-- The infimum of insert a s is the minimum of a and the infimum of s, if s is nonempty and bounded below.-/ theorem cInf_insert (hs : bdd_below s) (sne : s.nonempty) : Inf (insert a s) = a ⊓ Inf s := ((is_glb_cInf sne hs).insert a).cInf_eq (insert_nonempty a s) @[simp] lemma cInf_Ici : Inf (Ici a) = a := is_least_Ici.cInf_eq @[simp] lemma cSup_Iic : Sup (Iic a) = a := is_greatest_Iic.cSup_eq /--The indexed supremum of two functions are comparable if the functions are pointwise comparable-/ lemma csupr_le_csupr {f g : ι → α} (B : bdd_above (range g)) (H : ∀x, f x ≤ g x) : supr f ≤ supr g := begin classical, by_cases hι : nonempty ι, { have Rf : (range f).nonempty := range_nonempty _, apply cSup_le Rf, rintros y ⟨x, rfl⟩, have : g x ∈ range g := ⟨x, rfl⟩, exact le_cSup_of_le B this (H x) }, { have Rf : range f = ∅, from range_eq_empty.2 hι, have Rg : range g = ∅, from range_eq_empty.2 hι, unfold supr, rw [Rf, Rg] } end /--The indexed supremum of a function is bounded above by a uniform bound-/ lemma csupr_le [nonempty ι] {f : ι → α} {c : α} (H : ∀x, f x ≤ c) : supr f ≤ c := cSup_le (range_nonempty f) (by rwa forall_range_iff) /--The indexed supremum of a function is bounded below by the value taken at one point-/ lemma le_csupr {f : ι → α} (H : bdd_above (range f)) {c : ι} : f c ≤ supr f := le_cSup H (mem_range_self _) /--The indexed infimum of two functions are comparable if the functions are pointwise comparable-/ lemma cinfi_le_cinfi {f g : ι → α} (B : bdd_below (range f)) (H : ∀x, f x ≤ g x) : infi f ≤ infi g := begin classical, by_cases hι : nonempty ι, { have Rg : (range g).nonempty, from range_nonempty _, apply le_cInf Rg, rintros y ⟨x, rfl⟩, have : f x ∈ range f := ⟨x, rfl⟩, exact cInf_le_of_le B this (H x) }, { have Rf : range f = ∅, from range_eq_empty.2 hι, have Rg : range g = ∅, from range_eq_empty.2 hι, unfold infi, rw [Rf, Rg] } end /--The indexed minimum of a function is bounded below by a uniform lower bound-/ lemma le_cinfi [nonempty ι] {f : ι → α} {c : α} (H : ∀x, c ≤ f x) : c ≤ infi f := le_cInf (range_nonempty f) (by rwa forall_range_iff) /--The indexed infimum of a function is bounded above by the value taken at one point-/ lemma cinfi_le {f : ι → α} (H : bdd_below (range f)) {c : ι} : infi f ≤ f c := cInf_le H (mem_range_self _) @[simp] theorem cinfi_const [hι : nonempty ι] {a : α} : (⨅ b:ι, a) = a := by rw [infi, range_const, cInf_singleton] @[simp] theorem csupr_const [hι : nonempty ι] {a : α} : (⨆ b:ι, a) = a := by rw [supr, range_const, cSup_singleton] end conditionally_complete_lattice section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] {s t : set α} {a b : α} /-- When b < Sup s, there is an element a in s with b < a, if s is nonempty and the order is a linear order. -/ lemma exists_lt_of_lt_cSup (hs : s.nonempty) (hb : b < Sup s) : ∃a∈s, b < a := begin classical, contrapose! hb, exact cSup_le hs hb end /-- Indexed version of the above lemma `exists_lt_of_lt_cSup`. When `b < supr f`, there is an element `i` such that `b < f i`. -/ lemma exists_lt_of_lt_csupr [nonempty ι] {f : ι → α} (h : b < supr f) : ∃i, b < f i := let ⟨_, ⟨i, rfl⟩, h⟩ := exists_lt_of_lt_cSup (range_nonempty f) h in ⟨i, h⟩ /--When Inf s < b, there is an element a in s with a < b, if s is nonempty and the order is a linear order.-/ lemma exists_lt_of_cInf_lt (hs : s.nonempty) (hb : Inf s < b) : ∃a∈s, a < b := begin classical, contrapose! hb, exact le_cInf hs hb end /-- Indexed version of the above lemma `exists_lt_of_cInf_lt` When `infi f < a`, there is an element `i` such that `f i < a`. -/ lemma exists_lt_of_cinfi_lt [nonempty ι] {f : ι → α} (h : infi f < a) : (∃i, f i < a) := let ⟨_, ⟨i, rfl⟩, h⟩ := exists_lt_of_cInf_lt (range_nonempty f) h in ⟨i, h⟩ /--Introduction rule to prove that b is the supremum of s: it suffices to check that 1) b is an upper bound 2) every other upper bound b' satisfies b ≤ b'.-/ theorem cSup_intro' (_ : s.nonempty) (h_is_ub : ∀ a ∈ s, a ≤ b) (h_b_le_ub : ∀ub, (∀ a ∈ s, a ≤ ub) → (b ≤ ub)) : Sup s = b := le_antisymm (show Sup s ≤ b, from cSup_le ‹s.nonempty› h_is_ub) (show b ≤ Sup s, from h_b_le_ub _ $ assume a, le_cSup ⟨b, h_is_ub⟩) end conditionally_complete_linear_order section conditionally_complete_linear_order_bot lemma cSup_empty [conditionally_complete_linear_order_bot α] : (Sup ∅ : α) = ⊥ := conditionally_complete_linear_order_bot.cSup_empty end conditionally_complete_linear_order_bot section open_locale classical noncomputable instance : has_Inf ℕ := ⟨λs, if h : ∃n, n ∈ s then @nat.find (λn, n ∈ s) _ h else 0⟩ noncomputable instance : has_Sup ℕ := ⟨λs, if h : ∃n, ∀a∈s, a ≤ n then @nat.find (λn, ∀a∈s, a ≤ n) _ h else 0⟩ lemma Inf_nat_def {s : set ℕ} (h : ∃n, n ∈ s) : Inf s = @nat.find (λn, n ∈ s) _ h := dif_pos _ lemma Sup_nat_def {s : set ℕ} (h : ∃n, ∀a∈s, a ≤ n) : Sup s = @nat.find (λn, ∀a∈s, a ≤ n) _ h := dif_pos _ /-- This instance is necessary, otherwise the lattice operations would be derived via conditionally_complete_linear_order_bot and marked as noncomputable. -/ instance : lattice ℕ := infer_instance noncomputable instance : conditionally_complete_linear_order_bot ℕ := { Sup := Sup, Inf := Inf, le_cSup := assume s a hb ha, by rw [Sup_nat_def hb]; revert a ha; exact @nat.find_spec _ _ hb, cSup_le := assume s a hs ha, by rw [Sup_nat_def ⟨a, ha⟩]; exact nat.find_min' _ ha, le_cInf := assume s a hs hb, by rw [Inf_nat_def hs]; exact hb (@nat.find_spec (λn, n ∈ s) _ _), cInf_le := assume s a hb ha, by rw [Inf_nat_def ⟨a, ha⟩]; exact nat.find_min' _ ha, cSup_empty := begin simp only [Sup_nat_def, set.mem_empty_eq, forall_const, forall_prop_of_false, not_false_iff, exists_const], apply bot_unique (nat.find_min' _ _), trivial end, .. (infer_instance : order_bot ℕ), .. (infer_instance : lattice ℕ), .. (infer_instance : decidable_linear_order ℕ) } end namespace with_top open_locale classical variables [conditionally_complete_linear_order_bot α] /-- The Sup of a non-empty set is its least upper bound for a conditionally complete lattice with a top. -/ lemma is_lub_Sup' {β : Type*} [conditionally_complete_lattice β] {s : set (with_top β)} (hs : s.nonempty) : is_lub s (Sup s) := begin split, { show ite _ _ _ ∈ _, split_ifs, { intros _ _, exact le_top }, { rintro (⟨⟩|a) ha, { contradiction }, apply some_le_some.2, exact le_cSup h_1 ha }, { intros _ _, exact le_top } }, { show ite _ _ _ ∈ _, split_ifs, { rintro (⟨⟩|a) ha, { exact _root_.le_refl _ }, { exact false.elim (not_top_le_coe a (ha h)) } }, { rintro (⟨⟩|b) hb, { exact le_top }, refine some_le_some.2 (cSup_le _ _), { rcases hs with ⟨⟨⟩|b, hb⟩, { exact absurd hb h }, { exact ⟨b, hb⟩ } }, { intros a ha, exact some_le_some.1 (hb ha) } }, { rintro (⟨⟩|b) hb, { exact _root_.le_refl _ }, { exfalso, apply h_1, use b, intros a ha, exact some_le_some.1 (hb ha) } } } end lemma is_lub_Sup (s : set (with_top α)) : is_lub s (Sup s) := begin cases s.eq_empty_or_nonempty with hs hs, { rw hs, show is_lub ∅ (ite _ _ _), split_ifs, { cases h }, { rw [preimage_empty, cSup_empty], exact is_lub_empty }, { exfalso, apply h_1, use ⊥, rintro a ⟨⟩ } }, exact is_lub_Sup' hs, end /-- The Inf of a bounded-below set is its greatest lower bound for a conditionally complete lattice with a top. -/ lemma is_glb_Inf' {β : Type*} [conditionally_complete_lattice β] {s : set (with_top β)} (hs : bdd_below s) : is_glb s (Inf s) := begin split, { show ite _ _ _ ∈ _, split_ifs, { intros a ha, exact top_le_iff.2 (set.mem_singleton_iff.1 (h ha)) }, { rintro (⟨⟩|a) ha, { exact le_top }, refine some_le_some.2 (cInf_le _ ha), rcases hs with ⟨⟨⟩|b, hb⟩, { exfalso, apply h, intros c hc, rw [mem_singleton_iff, ←top_le_iff], exact hb hc }, use b, intros c hc, exact some_le_some.1 (hb hc) } }, { show ite _ _ _ ∈ _, split_ifs, { intros _ _, exact le_top }, { rintro (⟨⟩|a) ha, { exfalso, apply h, intros b hb, exact set.mem_singleton_iff.2 (top_le_iff.1 (ha hb)) }, { refine some_le_some.2 (le_cInf _ _), { classical, contrapose! h, rintros (⟨⟩|a) ha, { exact mem_singleton ⊤ }, { exact (h ⟨a, ha⟩).elim }}, { intros b hb, rw ←some_le_some, exact ha hb } } } } end lemma is_glb_Inf (s : set (with_top α)) : is_glb s (Inf s) := begin by_cases hs : bdd_below s, { exact is_glb_Inf' hs }, { exfalso, apply hs, use ⊥, intros _ _, exact bot_le }, end noncomputable instance : complete_linear_order (with_top α) := { Sup := Sup, le_Sup := assume s, (is_lub_Sup s).1, Sup_le := assume s, (is_lub_Sup s).2, Inf := Inf, le_Inf := assume s, (is_glb_Inf s).2, Inf_le := assume s, (is_glb_Inf s).1, decidable_le := classical.dec_rel _, .. with_top.linear_order, ..with_top.lattice, ..with_top.order_top, ..with_top.order_bot } lemma coe_Sup {s : set α} (hb : bdd_above s) : (↑(Sup s) : with_top α) = (⨆a∈s, ↑a) := begin cases s.eq_empty_or_nonempty with hs hs, { rw [hs, cSup_empty], simp only [set.mem_empty_eq, supr_bot, supr_false], refl }, apply le_antisymm, { refine ((coe_le_iff _ _).2 $ assume b hb, cSup_le hs $ assume a has, coe_le_coe.1 $ hb ▸ _), exact (le_supr_of_le a $ le_supr_of_le has $ _root_.le_refl _) }, { exact (supr_le $ assume a, supr_le $ assume ha, coe_le_coe.2 $ le_cSup hb ha) } end lemma coe_Inf {s : set α} (hs : s.nonempty) : (↑(Inf s) : with_top α) = (⨅a∈s, ↑a) := let ⟨x, hx⟩ := hs in have (⨅a∈s, ↑a : with_top α) ≤ x, from infi_le_of_le x $ infi_le_of_le hx $ _root_.le_refl _, let ⟨r, r_eq, hr⟩ := (le_coe_iff _ _).1 this in le_antisymm (le_infi $ assume a, le_infi $ assume ha, coe_le_coe.2 $ cInf_le (order_bot.bdd_below s) ha) begin refine (r_eq.symm ▸ coe_le_coe.2 $ le_cInf hs $ assume a has, coe_le_coe.1 $ _), refine (r_eq ▸ infi_le_of_le a _), exact (infi_le_of_le has $ _root_.le_refl _), end end with_top namespace enat open_locale classical noncomputable instance : complete_linear_order enat := { Sup := λ s, with_top_equiv.symm $ Sup (with_top_equiv '' s), Inf := λ s, with_top_equiv.symm $ Inf (with_top_equiv '' s), le_Sup := by intros; rw ← with_top_equiv_le; simp; apply le_Sup _; simpa, Inf_le := by intros; rw ← with_top_equiv_le; simp; apply Inf_le _; simpa, Sup_le := begin intros s a h1, rw [← with_top_equiv_le, with_top_equiv.right_inverse_symm], apply Sup_le _, rintros b ⟨x, h2, rfl⟩, rw with_top_equiv_le, apply h1, assumption end, le_Inf := begin intros s a h1, rw [← with_top_equiv_le, with_top_equiv.right_inverse_symm], apply le_Inf _, rintros b ⟨x, h2, rfl⟩, rw with_top_equiv_le, apply h1, assumption end, ..enat.decidable_linear_order, ..enat.bounded_lattice } end enat section order_dual instance (α : Type*) [conditionally_complete_lattice α] : conditionally_complete_lattice (order_dual α) := { le_cSup := @cInf_le α _, cSup_le := @le_cInf α _, le_cInf := @cSup_le α _, cInf_le := @le_cSup α _, ..order_dual.has_Inf α, ..order_dual.has_Sup α, ..order_dual.lattice α } instance (α : Type*) [conditionally_complete_linear_order α] : conditionally_complete_linear_order (order_dual α) := { ..order_dual.conditionally_complete_lattice α, ..order_dual.decidable_linear_order α } end order_dual section with_top_bot /-! ### Complete lattice structure on `with_top (with_bot α)` If `α` is a `conditionally_complete_lattice`, then we show that `with_top α` and `with_bot α` also inherit the structure of conditionally complete lattices. Furthermore, we show that `with_top (with_bot α)` naturally inherits the structure of a complete lattice. Note that for α a conditionally complete lattice, `Sup` and `Inf` both return junk values for sets which are empty or unbounded. The extension of `Sup` to `with_top α` fixes the unboundedness problem and the extension to `with_bot α` fixes the problem with the empty set. This result can be used to show that the extended reals [-∞, ∞] are a complete lattice. -/ open_locale classical /-- Adding a top element to a conditionally complete lattice gives a conditionally complete lattice -/ noncomputable instance with_top.conditionally_complete_lattice {α : Type*} [conditionally_complete_lattice α] : conditionally_complete_lattice (with_top α) := { le_cSup := λ S a hS haS, (with_top.is_lub_Sup' ⟨a, haS⟩).1 haS, cSup_le := λ S a hS haS, (with_top.is_lub_Sup' hS).2 haS, cInf_le := λ S a hS haS, (with_top.is_glb_Inf' hS).1 haS, le_cInf := λ S a hS haS, (with_top.is_glb_Inf' ⟨a, haS⟩).2 haS, ..with_top.lattice, ..with_top.has_Sup, ..with_top.has_Inf } /-- Adding a bottom element to a conditionally complete lattice gives a conditionally complete lattice -/ noncomputable instance with_bot.conditionally_complete_lattice {α : Type*} [conditionally_complete_lattice α] : conditionally_complete_lattice (with_bot α) := { le_cSup := (@with_top.conditionally_complete_lattice (order_dual α) _).cInf_le, cSup_le := (@with_top.conditionally_complete_lattice (order_dual α) _).le_cInf, cInf_le := (@with_top.conditionally_complete_lattice (order_dual α) _).le_cSup, le_cInf := (@with_top.conditionally_complete_lattice (order_dual α) _).cSup_le, ..with_bot.lattice, ..with_bot.has_Sup, ..with_bot.has_Inf } /-- Adding a bottom and a top to a conditionally complete lattice gives a bounded lattice-/ noncomputable instance with_top.with_bot.bounded_lattice {α : Type*} [conditionally_complete_lattice α] : bounded_lattice (with_top (with_bot α)) := { ..with_top.order_bot, ..with_top.order_top, ..conditionally_complete_lattice.to_lattice _ } theorem with_bot.cSup_empty {α : Type*} [conditionally_complete_lattice α] : Sup (∅ : set (with_bot α)) = ⊥ := begin show ite _ _ _ = ⊥, split_ifs; finish, end noncomputable instance with_top.with_bot.complete_lattice {α : Type*} [conditionally_complete_lattice α] : complete_lattice (with_top (with_bot α)) := { le_Sup := λ S a haS, (with_top.is_lub_Sup' ⟨a, haS⟩).1 haS, Sup_le := λ S a ha, begin cases S.eq_empty_or_nonempty with h, { show ite _ _ _ ≤ a, split_ifs, { rw h at h_1, cases h_1 }, { convert bot_le, convert with_bot.cSup_empty, rw h, refl }, { exfalso, apply h_2, use ⊥, rw h, rintro b ⟨⟩ } }, { refine (with_top.is_lub_Sup' h).2 ha } end, Inf_le := λ S a haS, show ite _ _ _ ≤ a, begin split_ifs, { cases a with a, exact _root_.le_refl _, cases (h haS); tauto }, { cases a, { exact le_top }, { apply with_top.some_le_some.2, refine cInf_le _ haS, use ⊥, intros b hb, exact bot_le } } end, le_Inf := λ S a haS, (with_top.is_glb_Inf' ⟨a, haS⟩).2 haS, ..with_top.has_Inf, ..with_top.has_Sup, ..with_top.with_bot.bounded_lattice } end with_top_bot
76b6f2728e9af73942278dc9cc120d4a125e9595
f313d4982feee650661f61ed73f0cb6635326350
/Mathlib/Algebra/GroupWithZero/Defs.lean
eaee2beafbdaf57cf169cd42760cdd253f34a7f4
[ "Apache-2.0" ]
permissive
shingtaklam1324/mathlib4
38c6e172eec1385944db5a70a3b5545c924980ee
50610c343b7065e8eec056d641f859ceed608e69
refs/heads/master
1,683,032,333,313
1,621,942,699,000
1,621,942,699,000
371,130,608
0
0
Apache-2.0
1,622,053,166,000
1,622,053,166,000
null
UTF-8
Lean
false
false
766
lean
import Mathlib.Algebra.Group.Defs class MonoidWithZero (M₀ : Type u) extends Monoid M₀, Zero M₀ where zero_mul (a : M₀) : 0 * a = 0 mul_zero (a : M₀) : a * 0 = 0 class GroupWithZero (G₀ : Type u) extends MonoidWithZero G₀, Inv G₀, Div G₀ where mul_left_inv (a : G₀) : a⁻¹ * a = 1 div_eq_mul_inv (a b : G₀) : a / b = a * b⁻¹ gpow : ℤ → G₀ → G₀ := gpow_rec gpow_zero' (a : G₀) : gpow 0 a = 1 -- try rfl gpow_succ' (n : ℕ) (a : G₀) : gpow (Int.ofNat n.succ) a = a * gpow (Int.ofNat n) a gpow_neg' (n : ℕ) (a : G₀) : gpow (Int.negSucc n) a = (gpow ↑(n.succ) a)⁻¹ exists_pair_ne : ∃ (x y : G₀), x ≠ y inv_zero : (0 : G₀)⁻¹ = 0 mul_inv_cancel (a : G₀) : a ≠ 0 → a * a⁻¹ = 1
96f8cadd15d7d030afbf500d9612baafc1ab542f
dc253be9829b840f15d96d986e0c13520b085033
/pointed.hlean
513ac8fa471117e32ccc7b55ee55ebcd04a2341f
[ "Apache-2.0" ]
permissive
cmu-phil/Spectral
4ce68e5c1ef2a812ffda5260e9f09f41b85ae0ea
3b078f5f1de251637decf04bd3fc8aa01930a6b3
refs/heads/master
1,685,119,195,535
1,684,169,772,000
1,684,169,772,000
46,450,197
42
13
null
1,505,516,767,000
1,447,883,921,000
Lean
UTF-8
Lean
false
false
28,778
hlean
/- equalities between pointed homotopies and other facts about pointed types/functions/homotopies -/ -- Author: Floris van Doorn import types.pointed2 .move_to_lib open pointed eq equiv function is_equiv unit is_trunc trunc nat algebra sigma group lift option namespace pointed definition phomotopy_mk_eq {A B : Type*} {f g : A →* B} {h k : f ~ g} {h₀ : h pt ⬝ respect_pt g = respect_pt f} {k₀ : k pt ⬝ respect_pt g = respect_pt f} (p : h ~ k) (q : whisker_right (respect_pt g) (p pt) ⬝ k₀ = h₀) : phomotopy.mk h h₀ = phomotopy.mk k k₀ := phomotopy_eq p (idp ◾ to_right_inv !eq_con_inv_equiv_con_eq _ ⬝ q ⬝ (to_right_inv !eq_con_inv_equiv_con_eq _)⁻¹) section phsquare /- Squares of pointed homotopies -/ variables {A : Type*} {P : A → Type} {p₀ : P pt} {f f' f₀₀ f₂₀ f₄₀ f₀₂ f₂₂ f₄₂ f₀₄ f₂₄ f₄₄ : ppi P p₀} {p₁₀ : f₀₀ ~* f₂₀} {p₃₀ : f₂₀ ~* f₄₀} {p₀₁ : f₀₀ ~* f₀₂} {p₂₁ : f₂₀ ~* f₂₂} {p₄₁ : f₄₀ ~* f₄₂} {p₁₂ : f₀₂ ~* f₂₂} {p₃₂ : f₂₂ ~* f₄₂} {p₀₃ : f₀₂ ~* f₀₄} {p₂₃ : f₂₂ ~* f₂₄} {p₄₃ : f₄₂ ~* f₄₄} {p₁₄ : f₀₄ ~* f₂₄} {p₃₄ : f₂₄ ~* f₄₄} definition phtranspose (p : phsquare p₁₀ p₁₂ p₀₁ p₂₁) : phsquare p₀₁ p₂₁ p₁₀ p₁₂ := p⁻¹ definition eq_top_of_phsquare (p : phsquare p₁₀ p₁₂ p₀₁ p₂₁) : p₁₀ = p₀₁ ⬝* p₁₂ ⬝* p₂₁⁻¹* := eq_trans_symm_of_trans_eq p definition eq_bot_of_phsquare (p : phsquare p₁₀ p₁₂ p₀₁ p₂₁) : p₁₂ = p₀₁⁻¹* ⬝* p₁₀ ⬝* p₂₁ := eq_symm_trans_of_trans_eq p⁻¹ ⬝ !trans_assoc⁻¹ definition eq_left_of_phsquare (p : phsquare p₁₀ p₁₂ p₀₁ p₂₁) : p₀₁ = p₁₀ ⬝* p₂₁ ⬝* p₁₂⁻¹* := eq_top_of_phsquare (phtranspose p) definition eq_right_of_phsquare (p : phsquare p₁₀ p₁₂ p₀₁ p₂₁) : p₂₁ = p₁₀⁻¹* ⬝* p₀₁ ⬝* p₁₂ := eq_bot_of_phsquare (phtranspose p) end phsquare -- /- the pointed type of (unpointed) dependent maps -/ -- definition pupi [constructor] {A : Type} (P : A → Type*) : Type* := -- pointed.mk' (Πa, P a) -- definition loop_pupi_commute {A : Type} (B : A → Type*) : Ω(pupi B) ≃* pupi (λa, Ω (B a)) := -- pequiv_of_equiv eq_equiv_homotopy rfl -- definition equiv_pupi_right {A : Type} {P Q : A → Type*} (g : Πa, P a ≃* Q a) -- : pupi P ≃* pupi Q := -- pequiv_of_equiv (pi_equiv_pi_right g) -- begin esimp, apply eq_of_homotopy, intros a, esimp, exact (respect_pt (g a)) end -- definition pmap_eq_equiv {X Y : Type*} (f g : X →* Y) : (f = g) ≃ (f ~* g) := -- begin -- refine eq_equiv_fn_eq_of_equiv (@pmap.sigma_char X Y) f g ⬝e _, -- refine !sigma_eq_equiv ⬝e _, -- refine _ ⬝e (phomotopy.sigma_char f g)⁻¹ᵉ, -- fapply sigma_equiv_sigma, -- { esimp, apply eq_equiv_homotopy }, -- { induction g with g gp, induction Y with Y y0, esimp, intro p, induction p, esimp at *, -- refine !pathover_idp ⬝e _, refine _ ⬝e !eq_equiv_eq_symm, -- apply equiv_eq_closed_right, exact !idp_con⁻¹ } -- end /- todo: make type argument explicit in ppcompose_left and ppcompose_left_* -/ /- todo: delete papply_pcompose -/ /- todo: pmap_pbool_equiv is a special case of ppmap_pbool_pequiv. -/ definition ppcompose_left_pid [constructor] (A B : Type*) : ppcompose_left (pid B) ~* pid (ppmap A B) := phomotopy_mk_ppmap (λf, pid_pcompose f) (!trans_refl ⬝ !phomotopy_of_eq_of_phomotopy⁻¹) definition ppcompose_right_pid [constructor] (A B : Type*) : ppcompose_right (pid A) ~* pid (ppmap A B) := phomotopy_mk_ppmap (λf, pcompose_pid f) (!trans_refl ⬝ !phomotopy_of_eq_of_phomotopy⁻¹) section variables {A A' : Type*} {P : A → Type} {P' : A' → Type} {p₀ : P pt} {p₀' : P' pt} {k l : ppi P p₀} definition phomotopy_of_eq_inv (p : k = l) : phomotopy_of_eq p⁻¹ = (phomotopy_of_eq p)⁻¹* := begin induction p, exact !refl_symm⁻¹ end /- todo: replace regular pap -/ definition pap' (f : ppi P p₀ → ppi P' p₀') (p : k ~* l) : f k ~* f l := by induction p using phomotopy_rec_idp; reflexivity definition phomotopy_of_eq_ap (f : ppi P p₀ → ppi P' p₀') (p : k = l) : phomotopy_of_eq (ap f p) = pap' f (phomotopy_of_eq p) := begin induction p, exact !phomotopy_rec_idp_refl⁻¹ end end /- remove some duplicates: loop_ppmap_commute, loop_ppmap_pequiv, loop_ppmap_pequiv', pfunext -/ -- definition pfunext (X Y : Type*) : ppmap X (Ω Y) ≃* Ω (ppmap X Y) := -- (loop_ppmap_commute X Y)⁻¹ᵉ* -- definition loop_phomotopy [constructor] {A B : Type*} (f : A →* B) : Type* := -- pointed.MK (f ~* f) phomotopy.rfl -- definition ppcompose_left_loop_phomotopy [constructor] {A B C : Type*} (g : B →* C) {f : A →* B} -- {h : A →* C} (p : g ∘* f ~* h) : loop_phomotopy f →* loop_phomotopy h := -- pmap.mk (λq, p⁻¹* ⬝* pwhisker_left g q ⬝* p) -- (idp ◾** !pwhisker_left_refl ◾** idp ⬝ !trans_refl ◾** idp ⬝ !trans_left_inv) -- definition ppcompose_left_loop_phomotopy' [constructor] {A B C : Type*} (g : B →* C) (f : A →* B) -- : loop_phomotopy f →* loop_phomotopy (g ∘* f) := -- pmap.mk (λq, pwhisker_left g q) !pwhisker_left_refl -- definition loop_ppmap_pequiv' [constructor] (A B : Type*) : -- Ω(ppmap A B) ≃* loop_phomotopy (pconst A B) := -- pequiv_of_equiv (pmap_eq_equiv _ _) idp -- definition ppmap_loop_pequiv' [constructor] (A B : Type*) : -- loop_phomotopy (pconst A B) ≃* ppmap A (Ω B) := -- pequiv_of_equiv (!phomotopy.sigma_char ⬝e !pmap.sigma_char⁻¹ᵉ) idp -- definition loop_ppmap_pequiv [constructor] (A B : Type*) : Ω(ppmap A B) ≃* ppmap A (Ω B) := -- loop_ppmap_pequiv' A B ⬝e* ppmap_loop_pequiv' A B -- definition loop_ppmap_pequiv'_natural_right' {X X' : Type} (x₀ : X) (A : Type*) (f : X → X') : -- psquare (loop_ppmap_pequiv' A _) (loop_ppmap_pequiv' A _) -- (Ω→ (ppcompose_left (pmap_of_map f x₀))) -- (ppcompose_left_loop_phomotopy' (pmap_of_map f x₀) !pconst) := -- begin -- fapply phomotopy.mk, -- { esimp, intro p, -- refine _ ⬝ ap011 (λx y, phomotopy_of_eq (ap1_gen _ x y _)) -- proof !eq_of_phomotopy_refl⁻¹ qed proof !eq_of_phomotopy_refl⁻¹ qed, -- refine _ ⬝ ap phomotopy_of_eq !ap1_gen_idp_left⁻¹, -- exact !phomotopy_of_eq_pcompose_left⁻¹ }, -- { refine _ ⬝ !idp_con⁻¹, exact sorry } -- end -- definition loop_ppmap_pequiv'_natural_right {X X' : Type*} (A : Type*) (f : X →* X') : -- psquare (loop_ppmap_pequiv' A X) (loop_ppmap_pequiv' A X') -- (Ω→ (ppcompose_left f)) (ppcompose_left_loop_phomotopy f !pcompose_pconst) := -- begin -- induction X' with X' x₀', induction f with f f₀, esimp at f, esimp at f₀, induction f₀, -- apply psquare_of_phomotopy, -- exact sorry -- end -- definition ppmap_loop_pequiv'_natural_right {X X' : Type*} (A : Type*) (f : X →* X') : -- psquare (ppmap_loop_pequiv' A X) (ppmap_loop_pequiv' A X') -- (ppcompose_left_loop_phomotopy f !pcompose_pconst) (ppcompose_left (Ω→ f)) := -- begin -- exact sorry -- end -- definition loop_pmap_commute_natural_right_direct {X X' : Type*} (A : Type*) (f : X →* X') : -- psquare (loop_ppmap_pequiv A X) (loop_ppmap_pequiv A X') -- (Ω→ (ppcompose_left f)) (ppcompose_left (Ω→ f)) := -- begin -- induction X' with X' x₀', induction f with f f₀, esimp at f, esimp at f₀, induction f₀, -- -- refine _ ⬝* _ ◾* _, rotate 4, -- fapply phomotopy.mk, -- { intro p, esimp, esimp [pmap_eq_equiv, pcompose_pconst], exact sorry }, -- { exact sorry } -- end -- definition loop_pmap_commute_natural_left {A A' : Type*} (X : Type*) (f : A' →* A) : -- psquare (loop_ppmap_commute A X) (loop_ppmap_commute A' X) -- (Ω→ (ppcompose_right f)) (ppcompose_right f) := -- sorry -- definition loop_pmap_commute_natural_right {X X' : Type*} (A : Type*) (f : X →* X') : -- psquare (loop_ppmap_commute A X) (loop_ppmap_commute A X') -- (Ω→ (ppcompose_left f)) (ppcompose_left (Ω→ f)) := -- loop_ppmap_pequiv'_natural_right A f ⬝h* ppmap_loop_pequiv'_natural_right A f /- Do we want to use a structure of homotopies between pointed homotopies? Or are equalities fine? If we set up things more generally, we could define this as "pointed homotopies between the dependent pointed maps p and q" -/ structure phomotopy2 {A B : Type*} {f g : A →* B} (p q : f ~* g) : Type := (homotopy_eq : p ~ q) (homotopy_pt_eq : whisker_right (respect_pt g) (homotopy_eq pt) ⬝ to_homotopy_pt q = to_homotopy_pt p) /- this sets it up more generally, for illustrative purposes -/ structure ppi' (A : Type*) (P : A → Type) (p : P pt) := (to_fun : Π a : A, P a) (resp_pt : to_fun (Point A) = p) attribute ppi'.to_fun [coercion] definition phomotopy' {A : Type*} {P : A → Type} {x : P pt} (f g : ppi' A P x) : Type := ppi' A (λa, f a = g a) (ppi'.resp_pt f ⬝ (ppi'.resp_pt g)⁻¹) definition phomotopy2' {A : Type*} {P : A → Type} {x : P pt} {f g : ppi' A P x} (p q : phomotopy' f g) : Type := phomotopy' p q -- infix ` ~*2 `:50 := phomotopy2 -- variables {A B : Type*} {f g : A →* B} (p q : f ~* g) -- definition phomotopy_eq_equiv_phomotopy2 : p = q ≃ p ~*2 q := -- sorry definition pconst_pcompose_phomotopy {A B C : Type*} {f f' : A →* B} (p : f ~* f') : pwhisker_left (pconst B C) p ⬝* pconst_pcompose f' = pconst_pcompose f := begin fapply phomotopy_eq, { intro a, apply ap_constant }, { induction p using phomotopy_rec_idp, induction B with B b₀, induction f with f f₀, esimp at *, induction f₀, reflexivity } end /- Homotopy between a function and its eta expansion -/ definition papply_point [constructor] (A B : Type*) : papply B pt ~* pconst (ppmap A B) B := phomotopy.mk (λf, respect_pt f) idp definition pmap_swap_map [constructor] {A B C : Type*} (f : A →* ppmap B C) : ppmap B (ppmap A C) := begin fapply pmap.mk, { intro b, exact papply C b ∘* f }, { apply eq_of_phomotopy, exact pwhisker_right f (papply_point B C) ⬝* !pconst_pcompose } end definition pmap_swap_map_pconst (A B C : Type*) : pmap_swap_map (pconst A (ppmap B C)) ~* pconst B (ppmap A C) := begin fapply phomotopy_mk_ppmap, { intro b, reflexivity }, { refine !refl_trans ⬝ !phomotopy_of_eq_of_phomotopy⁻¹ } end definition papply_pmap_swap_map [constructor] {A B C : Type*} (f : A →* ppmap B C) (a : A) : papply C a ∘* pmap_swap_map f ~* f a := begin fapply phomotopy.mk, { intro b, reflexivity }, { exact !idp_con ⬝ !ap_eq_of_phomotopy⁻¹ } end definition pmap_swap_map_pmap_swap_map {A B C : Type*} (f : A →* ppmap B C) : pmap_swap_map (pmap_swap_map f) ~* f := begin fapply phomotopy_mk_ppmap, { exact papply_pmap_swap_map f }, { refine _ ⬝ !phomotopy_of_eq_of_phomotopy⁻¹, fapply phomotopy_mk_eq, intro b, exact !idp_con, refine !whisker_right_idp ◾ (!idp_con ◾ idp) ⬝ _ ⬝ !idp_con⁻¹ ◾ idp, symmetry, exact sorry } end definition pmap_swap [constructor] (A B C : Type*) : ppmap A (ppmap B C) →* ppmap B (ppmap A C) := begin fapply pmap.mk, { exact pmap_swap_map }, { exact eq_of_phomotopy (pmap_swap_map_pconst A B C) } end definition pmap_swap_pequiv [constructor] (A B C : Type*) : ppmap A (ppmap B C) ≃* ppmap B (ppmap A C) := begin fapply pequiv_of_pmap, { exact pmap_swap A B C }, fapply adjointify, { exact pmap_swap B A C }, { intro f, apply eq_of_phomotopy, exact pmap_swap_map_pmap_swap_map f }, { intro f, apply eq_of_phomotopy, exact pmap_swap_map_pmap_swap_map f } end -- this should replace pnatural_square definition pnatural_square2 {A B : Type} (X : B → Type*) (Y : B → Type*) {f g : A → B} (h : Πa, X (f a) →* Y (g a)) {a a' : A} (p : a = a') : h a' ∘* ptransport X (ap f p) ~* ptransport Y (ap g p) ∘* h a := by induction p; exact !pcompose_pid ⬝* !pid_pcompose⁻¹* definition ptransport_ap {A B : Type} (X : B → Type*) (f : A → B) {a a' : A} (p : a = a') : ptransport X (ap f p) ~* ptransport (X ∘ f) p := by induction p; reflexivity definition ptransport_constant (A : Type) (B : Type*) {a a' : A} (p : a = a') : ptransport (λ(a : A), B) p ~* pid B := by induction p; reflexivity definition ptransport_natural {A : Type} (X : A → Type*) (Y : A → Type*) (h : Πa, X a →* Y a) {a a' : A} (p : a = a') : h a' ∘* ptransport X p ~* ptransport Y p ∘* h a := by induction p; exact !pcompose_pid ⬝* !pid_pcompose⁻¹* section psquare variables {A A' A₀₀ A₂₀ A₄₀ A₀₂ A₂₂ A₄₂ A₀₄ A₂₄ A₄₄ : Type*} {f₁₀ f₁₀' : A₀₀ →* A₂₀} {f₃₀ : A₂₀ →* A₄₀} {f₀₁ f₀₁' : A₀₀ →* A₀₂} {f₂₁ f₂₁' : A₂₀ →* A₂₂} {f₄₁ f₄₁' : A₄₀ →* A₄₂} {f₁₂ f₁₂' : A₀₂ →* A₂₂} {f₃₂ : A₂₂ →* A₄₂} {f₀₃ : A₀₂ →* A₀₄} {f₂₃ : A₂₂ →* A₂₄} {f₄₃ : A₄₂ →* A₄₄} {f₁₄ f₁₄' : A₀₄ →* A₂₄} {f₃₄ : A₂₄ →* A₄₄} definition pvconst_square_pcompose (f₃₀ : A₂₀ →* A₄₀) (f₁₀ : A₀₀ →* A₂₀) (f₃₂ : A₂₂ →* A₄₂) (f₁₂ : A₀₂ →* A₂₂) : pvconst_square (f₃₀ ∘* f₁₀) (f₃₂ ∘* f₁₂) = pvconst_square f₁₀ f₁₂ ⬝h* pvconst_square f₃₀ f₃₂ := begin refine eq_right_of_phsquare !passoc_pconst_left ◾** !passoc_pconst_right⁻¹⁻²** ⬝ idp ◾** (!trans_symm ⬝ !trans_symm ◾** idp) ⬝ !trans_assoc⁻¹ ⬝ _ ◾** idp, refine !trans_assoc⁻¹ ⬝ _ ◾** !pwhisker_left_symm⁻¹ ⬝ !trans_assoc ⬝ idp ◾** !pwhisker_left_trans⁻¹, apply trans_symm_eq_of_eq_trans, refine _ ⬝ idp ◾** !passoc_pconst_middle⁻¹ ⬝ !trans_assoc⁻¹ ⬝ !trans_assoc⁻¹, refine _ ◾** idp ⬝ !trans_assoc, refine idp ◾** _ ⬝ !trans_assoc⁻¹, refine ap (pwhisker_right f₁₀) _ ⬝ !pwhisker_right_trans, refine !trans_refl⁻¹ ⬝ idp ◾** !trans_left_inv⁻¹ ⬝ !trans_assoc⁻¹, end definition phconst_square_pcompose (f₀₃ : A₀₂ →* A₀₄) (f₁₀ : A₀₀ →* A₂₀) (f₂₃ : A₂₂ →* A₂₄) (f₂₁ : A₂₀ →* A₂₂) : phconst_square (f₀₃ ∘* f₀₁) (f₂₃ ∘* f₁₂) = phconst_square f₀₁ f₁₂ ⬝v* phconst_square f₀₃ f₂₃ := sorry definition rfl_phomotopy_hconcat (p : psquare f₁₀ f₁₂ f₀₁ f₂₁) : phomotopy.rfl ⬝ph* p = p := idp ◾** (ap (pwhisker_left f₁₂) !refl_symm ⬝ !pwhisker_left_refl) ⬝ !trans_refl definition hconcat_phomotopy_rfl (p : psquare f₁₀ f₁₂ f₀₁ f₂₁) : p ⬝hp* phomotopy.rfl = p := !pwhisker_right_refl ◾** idp ⬝ !refl_trans definition rfl_phomotopy_vconcat (p : psquare f₁₀ f₁₂ f₀₁ f₂₁) : phomotopy.rfl ⬝pv* p = p := !pwhisker_left_refl ◾** idp ⬝ !refl_trans definition vconcat_phomotopy_rfl (p : psquare f₁₀ f₁₂ f₀₁ f₂₁) : p ⬝vp* phomotopy.rfl = p := idp ◾** (ap (pwhisker_right f₀₁) !refl_symm ⬝ !pwhisker_right_refl) ⬝ !trans_refl definition phomotopy_hconcat_phconcat (p : f₀₁' ~* f₀₁) (q : psquare f₁₀ f₁₂ f₀₁ f₂₁) (r : psquare f₃₀ f₃₂ f₂₁ f₄₁) : (p ⬝ph* q) ⬝h* r = p ⬝ph* (q ⬝h* r) := begin induction p using phomotopy_rec_idp, exact !refl_phomotopy_hconcat ◾h* idp ⬝ !refl_phomotopy_hconcat⁻¹ end definition phconcat_hconcat_phomotopy (p : psquare f₁₀ f₁₂ f₀₁ f₂₁) (q : psquare f₃₀ f₃₂ f₂₁ f₄₁) (r : f₄₁' ~* f₄₁) : (p ⬝h* q) ⬝hp* r = p ⬝h* (q ⬝hp* r) := begin induction r using phomotopy_rec_idp, exact !hconcat_phomotopy_rfl ⬝ idp ◾h* !hconcat_phomotopy_rfl⁻¹ end definition phomotopy_hconcat_phomotopy (p : f₀₁' ~* f₀₁) (q : psquare f₁₀ f₁₂ f₀₁ f₂₁) (r : f₂₁' ~* f₂₁) : (p ⬝ph* q) ⬝hp* r = p ⬝ph* (q ⬝hp* r) := begin induction r using phomotopy_rec_idp, exact !hconcat_phomotopy_rfl ⬝ idp ◾ph* !hconcat_phomotopy_rfl⁻¹ end definition hconcat_phomotopy_phconcat (p : psquare f₁₀ f₁₂ f₀₁ f₂₁) (q : f₂₁' ~* f₂₁) (r : psquare f₃₀ f₃₂ f₂₁' f₄₁) : (p ⬝hp* q) ⬝h* r = p ⬝h* (q⁻¹* ⬝ph* r) := begin induction q using phomotopy_rec_idp, exact !hconcat_phomotopy_rfl ◾h* idp ⬝ idp ◾h* (!refl_symm ◾ph* idp ⬝ !refl_phomotopy_hconcat)⁻¹ end definition phconcat_phomotopy_hconcat (p : psquare f₁₀ f₁₂ f₀₁ f₂₁) (q : f₂₁ ~* f₂₁') (r : psquare f₃₀ f₃₂ f₂₁' f₄₁) : p ⬝h* (q ⬝ph* r) = (p ⬝hp* q⁻¹*) ⬝h* r := begin induction q using phomotopy_rec_idp, exact idp ◾h* !refl_phomotopy_hconcat ⬝ (idp ◾hp* !refl_symm ⬝ !hconcat_phomotopy_rfl)⁻¹ ◾h* idp end definition hconcat_phomotopy_hconcat_cancel (p : psquare f₁₀ f₁₂ f₀₁ f₂₁) (q : f₂₁' ~* f₂₁) (r : psquare f₃₀ f₃₂ f₂₁ f₄₁) : (p ⬝hp* q) ⬝h* (q ⬝ph* r) = p ⬝h* r := begin induction q using phomotopy_rec_idp, exact !hconcat_phomotopy_rfl ◾h* !refl_phomotopy_hconcat end definition phomotopy_hconcat_phinverse {f₁₀ : A₀₀ ≃* A₂₀} {f₁₂ : A₀₂ ≃* A₂₂} (p : f₀₁' ~* f₀₁) (q : psquare f₁₀ f₁₂ f₀₁ f₂₁) : (p ⬝ph* q)⁻¹ʰ* = q⁻¹ʰ* ⬝hp* p := begin induction p using phomotopy_rec_idp, exact !refl_phomotopy_hconcat⁻²ʰ* ⬝ !hconcat_phomotopy_rfl⁻¹ end definition hconcat_phomotopy_phinverse {f₁₀ : A₀₀ ≃* A₂₀} {f₁₂ : A₀₂ ≃* A₂₂} (p : psquare f₁₀ f₁₂ f₀₁ f₂₁) (q : f₂₁' ~* f₂₁) : (p ⬝hp* q)⁻¹ʰ* = q ⬝ph* p⁻¹ʰ* := begin induction q using phomotopy_rec_idp, exact !hconcat_phomotopy_rfl⁻²ʰ* ⬝ !refl_phomotopy_hconcat⁻¹ end definition pvconst_square_phinverse (f₁₀ : A₀₀ ≃* A₂₀) (f₁₂ : A₀₂ ≃* A₂₂) : (pvconst_square f₁₀ f₁₂)⁻¹ʰ* = pvconst_square f₁₀⁻¹ᵉ* f₁₂⁻¹ᵉ* := begin exact sorry end definition ppcompose_left_phomotopy_hconcat (A : Type*) (p : f₀₁' ~* f₀₁) (q : psquare f₁₀ f₁₂ f₀₁ f₂₁) : ppcompose_left_psquare (p ⬝ph* q) = @ppcompose_left_phomotopy A _ _ _ _ p ⬝ph* ppcompose_left_psquare q := sorry --used definition ppcompose_left_hconcat_phomotopy (A : Type*) (p : psquare f₁₀ f₁₂ f₀₁ f₂₁) (q : f₂₁' ~* f₂₁) : ppcompose_left_psquare (p ⬝hp* q) = ppcompose_left_psquare p ⬝hp* @ppcompose_left_phomotopy A _ _ _ _ q := sorry definition ppcompose_left_pvconst_square (A : Type*) (f₁₀ : A₀₀ →* A₂₀) (f₁₂ : A₀₂ →* A₂₂) : ppcompose_left_psquare (pvconst_square f₁₀ f₁₂) = !ppcompose_left_pconst ⬝ph* pvconst_square (ppcompose_left f₁₀) (@ppcompose_left A _ _ f₁₂) ⬝hp* !ppcompose_left_pconst := sorry end psquare definition ap1_pequiv_ap {A : Type} (B : A → Type*) {a a' : A} (p : a = a') : Ω→ (pequiv_ap B p) ~* pequiv_ap (Ω ∘ B) p := begin induction p, apply ap1_pid end definition pequiv_ap_natural {A : Type} (B C : A → Type*) {a a' : A} (p : a = a') (f : Πa, B a →* C a) : psquare (pequiv_ap B p) (pequiv_ap C p) (f a) (f a') := begin induction p, exact phrfl end definition is_contr_loop (A : Type*) [is_set A] : is_contr (Ω A) := is_contr.mk idp (λa, !is_prop.elim) definition is_contr_loop_of_is_contr {A : Type*} (H : is_contr A) : is_contr (Ω A) := is_contr_loop A definition is_contr_punit [instance] : is_contr punit := is_contr_unit definition pequiv_of_is_contr (A B : Type*) (HA : is_contr A) (HB : is_contr B) : A ≃* B := pequiv_punit_of_is_contr A _ ⬝e* (pequiv_punit_of_is_contr B _)⁻¹ᵉ* definition loop_pequiv_punit_of_is_set (X : Type*) [is_set X] : Ω X ≃* punit := pequiv_punit_of_is_contr _ (is_contr_loop X) definition loop_punit : Ω punit ≃* punit := loop_pequiv_punit_of_is_set punit definition add_point_functor' [unfold 4] {A B : Type} (e : A → B) (a : A₊) : B₊ := begin induction a with a, exact none, exact some (e a) end definition add_point_functor [constructor] {A B : Type} (e : A → B) : A₊ →* B₊ := pmap.mk (add_point_functor' e) idp definition add_point_functor_compose {A B C : Type} (f : B → C) (e : A → B) : add_point_functor (f ∘ e) ~* add_point_functor f ∘* add_point_functor e := begin fapply phomotopy.mk, { intro x, induction x: reflexivity }, reflexivity end definition add_point_functor_id (A : Type) : add_point_functor id ~* pid A₊ := begin fapply phomotopy.mk, { intro x, induction x: reflexivity }, reflexivity end definition add_point_functor_phomotopy {A B : Type} {e e' : A → B} (p : e ~ e') : add_point_functor e ~* add_point_functor e' := begin fapply phomotopy.mk, { intro x, induction x with a, reflexivity, exact ap some (p a) }, reflexivity end definition add_point_pequiv {A B : Type} (e : A ≃ B) : A₊ ≃* B₊ := pequiv.MK (add_point_functor e) (add_point_functor e⁻¹ᵉ) abstract !add_point_functor_compose⁻¹* ⬝* add_point_functor_phomotopy (left_inv e) ⬝* !add_point_functor_id end abstract !add_point_functor_compose⁻¹* ⬝* add_point_functor_phomotopy (right_inv e) ⬝* !add_point_functor_id end definition add_point_over [unfold 3] {A : Type} (B : A → Type*) : A₊ → Type* | (some a) := B a | none := plift punit definition add_point_over_pequiv {A : Type} {B B' : A → Type*} (e : Πa, B a ≃* B' a) : Π(a : A₊), add_point_over B a ≃* add_point_over B' a | (some a) := e a | none := pequiv.rfl definition phomotopy_group_plift_punit.{u} (n : ℕ) [H : is_at_least_two n] : πag[n] (plift.{0 u} punit) ≃g trivial_ab_group_lift.{u} := begin induction H with n, have H : 0 <[ℕ] n+2, from !zero_lt_succ, have is_set unit, from _, have is_trunc (trunc_index.of_nat 0) punit, from this, exact isomorphism_of_is_contr (@trivial_homotopy_group_of_is_trunc _ _ _ !is_trunc_lift H) !is_trunc_lift end definition pmap_of_map_pt [constructor] {A : Type*} {B : Type} (f : A → B) : A →* pointed.MK B (f pt) := pmap.mk f idp definition papply_natural_right [constructor] {A B B' : Type*} (f : B →* B') (a : A) : psquare (papply B a) (papply B' a) (ppcompose_left f) f := begin fapply phomotopy.mk, { intro g, reflexivity }, { refine !idp_con ⬝ !ap_eq_of_phomotopy ⬝ !idp_con⁻¹ } end -- definition foo {A B : Type} {f : A → B} {a₀ a₁ a₂ : A} {b₀ b₁ b₂ : B} -- {p₀ : a₀ = a₀} {p₁ : a₀ = a₀} (q₀ : ap f p₀ = idp) (q₁ : ap f p₁ = idp) : -- whisker_right (ap f p₁) (idp_con (ap f p₀⁻¹) ⬝ !ap_inv ⬝ q₀⁻²)⁻¹ ⬝ !con.assoc ⬝ -- whisker_left idp (con_eq_of_eq_con_inv (eq_con_inv_of_con_eq _)) ⬝ _ -- = !idp_con ⬝ q₁ := -- _ /- whisker_right (ap (λ f, pppi.to_fun f a) (eq_of_phomotopy (pcompose_pconst (pconst B B')))) (idp_con (ap (λ y, pppi.to_fun y a) (eq_of_phomotopy (pconst_pcompose (ppi_const (λ a, B))))⁻¹) ⬝ ap_inv (λ y, pppi.to_fun y a) (eq_of_phomotopy (pconst_pcompose (ppi_const (λ a, B)))) ⬝ inverse2 (ap_eq_of_phomotopy (pconst_pcompose (ppi_const (λ a, B))) a))⁻¹ ⬝ (con.assoc (ppi.to_fun (pvconst_square (papply B a) (papply B' a)) (ppi_const (λ a, B))) (ap (λ f, pppi.to_fun f a) (eq_of_phomotopy (pconst_pcompose (ppi_const (λ a, B))))⁻¹) (ap (λ f, pppi.to_fun f a) (eq_of_phomotopy (pcompose_pconst (pconst B B')))) ⬝ whisker_left (ppi.to_fun (pvconst_square (papply B a) (papply B' a)) (ppi_const (λ a, B))) (con_eq_of_eq_con_inv (eq_con_inv_of_con_eq (pwhisker_left_1 B' (ppmap A B) (ppmap A B') (papply B' a) (pconst (ppmap A B) (ppmap A B')) (ppcompose_left (pconst B B')) (ppcompose_left_pconst A B B')⁻¹*))) ⬝ respect_pt (pvconst_square (papply B a) (papply B' a))) = idp_con (ap (λ f, pppi.to_fun f a) (eq_of_phomotopy (pcompose_pconst (pconst B B')))) ⬝ ap_eq_of_phomotopy (pcompose_pconst (pconst B B')) a -/ definition papply_natural_right_pconst {A : Type*} (B B' : Type*) (a : A) : papply_natural_right (pconst B B') a = !ppcompose_left_pconst ⬝ph* !pvconst_square := begin fapply phomotopy_mk_eq, { intro g, symmetry, refine !idp_con ⬝ !ap_inv ⬝ !ap_eq_of_phomotopy⁻² }, { esimp [pvconst_square], --esimp [inv_con_eq_of_eq_con, pwhisker_left_1] exact sorry } end /- TODO: computation rule -/ open pi definition fiberwise_pointed_map_rec {A : Type} {B : A → Type*} (P : Π(C : A → Type*) (g : Πa, B a →* C a), Type) (H : Π(C : A → Type) (g : Πa, B a → C a), P _ (λa, pmap_of_map_pt (g a))) : Π⦃C : A → Type*⦄ (g : Πa, B a →* C a), P C g := begin refine equiv_rect (!sigma_pi_equiv_pi_sigma ⬝e arrow_equiv_arrow_right A !pType.sigma_char⁻¹ᵉ) _ _, intro R, cases R with R r₀, refine equiv_rect (!sigma_pi_equiv_pi_sigma ⬝e pi_equiv_pi_right (λa, !pmap.sigma_char⁻¹ᵉ)) _ _, intro g, cases g with g g₀, esimp at (g, g₀), revert g₀, change (Π(g : (λa, g a (Point (B a))) ~ r₀), _), refine homotopy.rec_idp _ _, esimp, apply H end definition ap1_gen_idp_eq {A B : Type} (f : A → B) {a : A} (q : f a = f a) (r : q = idp) : ap1_gen_idp f q = ap (λx, ap1_gen f x x idp) r := begin cases r, reflexivity end definition pointed_change_point [constructor] (A : Type*) {a : A} (p : a = pt) : pointed.MK A a ≃* A := pequiv_of_eq_pt p ⬝e* (pointed_eta_pequiv A)⁻¹ᵉ* definition change_path_psquare {A B : Type*} (f : A →* B) {a' : A} {b' : B} (p : a' = pt) (q : pt = b') : psquare (pointed_change_point _ p) (pointed_change_point _ q⁻¹) (pmap.mk f (ap f p ⬝ respect_pt f ⬝ q)) f := begin fapply phomotopy.mk, exact homotopy.rfl, exact !idp_con ⬝ !ap_id ◾ !ap_id ⬝ !con_inv_cancel_right ⬝ whisker_right _ (ap02 f !ap_id⁻¹) end definition change_path_psquare_cod {A B : Type*} (f : A →* B) {b' : B} (p : pt = b') : f ~* pointed_change_point _ p⁻¹ ∘* pmap.mk f (respect_pt f ⬝ p) := begin fapply phomotopy.mk, exact homotopy.rfl, exact !idp_con ⬝ !ap_id ◾ !ap_id ⬝ !con_inv_cancel_right end definition change_path_psquare_cod' {A B : Type} (f : A → B) (a : A) {b' : B} (p : f a = b') : pointed_change_point _ p ∘* pmap_of_map f a ~* pmap.mk f p := begin fapply phomotopy.mk, exact homotopy.rfl, refine whisker_left idp (ap_id p)⁻¹ end structure deloopable.{u} [class] (A : pType.{u}) : Type.{u+1} := (deloop : pType.{u}) (deloop_pequiv : Ω deloop ≃* A) abbreviation deloop [unfold 2] := deloopable.deloop abbreviation deloop_pequiv [unfold 2] := deloopable.deloop_pequiv definition deloopable_loop [instance] [constructor] (A : Type*) : deloopable (Ω A) := deloopable.mk A pequiv.rfl definition deloopable_loopn [instance] [priority 500] (n : ℕ) [H : is_succ n] (A : Type*) : deloopable (Ω[n] A) := by induction H with n; exact deloopable.mk (Ω[n] A) pequiv.rfl definition inf_group_of_deloopable (A : Type*) [deloopable A] : inf_group A := inf_group_equiv_closed (deloop_pequiv A) _ definition InfGroup_of_deloopable (A : Type*) [deloopable A] : InfGroup := InfGroup.mk A (inf_group_of_deloopable A) definition deloop_isomorphism [constructor] (A : Type*) [deloopable A] : Ωg (deloop A) ≃∞g InfGroup_of_deloopable A := InfGroup_equiv_closed_isomorphism (Ωg (deloop A)) (deloop_pequiv A) end pointed
8dd7f0bff9367b6a7d67fa891523b3ff404c1410
82e44445c70db0f03e30d7be725775f122d72f3e
/src/topology/continuous_function/weierstrass.lean
2fc66b4eb6dcc11494c09d7ef09cfd34a3f1fab9
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
5,416
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import analysis.special_functions.bernstein import topology.algebra.algebra /-! # The Weierstrass approximation theorem for continuous functions on `[a,b]` We've already proved the Weierstrass approximation theorem in the sense that we've shown that the Bernstein approximations to a continuous function on `[0,1]` converge uniformly. Here we rephrase this more abstractly as `polynomial_functions_closure_eq_top' : (polynomial_functions I).topological_closure = ⊤` and then, by precomposing with suitable affine functions, `polynomial_functions_closure_eq_top : (polynomial_functions (set.Icc a b)).topological_closure = ⊤` -/ open continuous_map filter open_locale unit_interval /-- The special case of the Weierstrass approximation theorem for the interval `[0,1]`. This is just a matter of unravelling definitions and using the Bernstein approximations. -/ theorem polynomial_functions_closure_eq_top' : (polynomial_functions I).topological_closure = ⊤ := begin apply eq_top_iff.mpr, rintros f -, refine filter.frequently.mem_closure _, refine filter.tendsto.frequently (bernstein_approximation_uniform f) _, apply frequently_of_forall, intro n, simp only [set_like.mem_coe], apply subalgebra.sum_mem, rintro n -, apply subalgebra.smul_mem, dsimp [bernstein, polynomial_functions], simp, end /-- The **Weierstrass Approximation Theorem**: polynomials functions on `[a, b] ⊆ ℝ` are dense in `C([a,b],ℝ)` (While we could deduce this as an application of the Stone-Weierstrass theorem, our proof of that relies on the fact that `abs` is in the closure of polynomials on `[-M, M]`, so we may as well get this done first.) -/ theorem polynomial_functions_closure_eq_top (a b : ℝ) : (polynomial_functions (set.Icc a b)).topological_closure = ⊤ := begin by_cases h : a < b, -- (Otherwise it's easy; we'll deal with that later.) { -- We can pullback continuous functions on `[a,b]` to continuous functions on `[0,1]`, -- by precomposing with an affine map. let W : C(set.Icc a b, ℝ) →ₐ[ℝ] C(I, ℝ) := comp_right_alg_hom ℝ (Icc_homeo_I a b h).symm.to_continuous_map, -- This operation is itself a homeomorphism -- (with respect to the norm topologies on continuous functions). let W' : C(set.Icc a b, ℝ) ≃ₜ C(I, ℝ) := comp_right_homeomorph ℝ (Icc_homeo_I a b h).symm, have w : (W : C(set.Icc a b, ℝ) → C(I, ℝ)) = W' := rfl, -- Thus we take the statement of the Weierstrass approximation theorem for `[0,1]`, have p := polynomial_functions_closure_eq_top', -- and pullback both sides, obtaining an equation between subalgebras of `C([a,b], ℝ)`. apply_fun (λ s, s.comap' W) at p, simp only [algebra.comap_top] at p, -- Since the pullback operation is continuous, it commutes with taking `topological_closure`, rw subalgebra.topological_closure_comap'_homeomorph _ W W' w at p, -- and precomposing with an affine map takes polynomial functions to polynomial functions. rw polynomial_functions.comap'_comp_right_alg_hom_Icc_homeo_I at p, -- 🎉 exact p }, { -- Otherwise, `b ≤ a`, and the interval is a subsingleton, -- so all subalgebras are the same anyway. haveI : subsingleton (set.Icc a b) := ⟨λ x y, le_antisymm ((x.2.2.trans (not_lt.mp h)).trans y.2.1) ((y.2.2.trans (not_lt.mp h)).trans x.2.1)⟩, haveI := (continuous_map.subsingleton_subalgebra (set.Icc a b) ℝ), apply subsingleton.elim, } end /-- An alternative statement of Weierstrass' theorem. Every real-valued continuous function on `[a,b]` is a uniform limit of polynomials. -/ theorem continuous_map_mem_polynomial_functions_closure (a b : ℝ) (f : C(set.Icc a b, ℝ)) : f ∈ (polynomial_functions (set.Icc a b)).topological_closure := begin rw polynomial_functions_closure_eq_top _ _, simp, end /-- An alternative statement of Weierstrass' theorem, for those who like their epsilons. Every real-valued continuous function on `[a,b]` is within any `ε > 0` of some polynomial. -/ theorem exists_polynomial_near_continuous_map (a b : ℝ) (f : C(set.Icc a b, ℝ)) (ε : ℝ) (pos : 0 < ε) : ∃ (p : polynomial ℝ), ∥p.to_continuous_map_on _ - f∥ < ε := begin have w := mem_closure_iff_frequently.mp (continuous_map_mem_polynomial_functions_closure _ _ f), rw metric.nhds_basis_ball.frequently_iff at w, obtain ⟨-, H, ⟨m, ⟨-, rfl⟩⟩⟩ := w ε pos, rw [metric.mem_ball, dist_eq_norm] at H, exact ⟨m, H⟩, end /-- Another alternative statement of Weierstrass's theorem, for those who like epsilons, but not bundled continuous functions. Every real-valued function `ℝ → ℝ` which is continuous on `[a,b]` can be approximated to within any `ε > 0` on `[a,b]` by some polynomial. -/ theorem exists_polynomial_near_of_continuous_on (a b : ℝ) (f : ℝ → ℝ) (c : continuous_on f (set.Icc a b)) (ε : ℝ) (pos : 0 < ε) : ∃ (p : polynomial ℝ), ∀ x ∈ set.Icc a b, abs (p.eval x - f x) < ε := begin let f' : C(set.Icc a b, ℝ) := ⟨λ x, f x, continuous_on_iff_continuous_restrict.mp c⟩, obtain ⟨p, b⟩ := exists_polynomial_near_continuous_map a b f' ε pos, use p, rw norm_lt_iff _ pos at b, intros x m, exact b ⟨x, m⟩, end
e57995e7ee574382cd3ced5281567bfd42bcbbdb
618003631150032a5676f229d13a079ac875ff77
/src/linear_algebra/direct_sum_module.lean
2b84875b8b82137106ff7c27475a68666a3037cf
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
3,524
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Direct sum of modules over commutative rings, indexed by a discrete type. -/ import algebra.direct_sum import linear_algebra.basic universes u v w u₁ variables (R : Type u) [semiring R] variables (ι : Type v) [decidable_eq ι] (M : ι → Type w) variables [Π i, add_comm_group (M i)] [Π i, semimodule R (M i)] include R namespace direct_sum variables {R ι M} instance : semimodule R (direct_sum ι M) := dfinsupp.to_semimodule variables R ι M def lmk : Π s : finset ι, (Π i : (↑s : set ι), M i.1) →ₗ[R] direct_sum ι M := dfinsupp.lmk M R def lof : Π i : ι, M i →ₗ[R] direct_sum ι M := dfinsupp.lsingle M R variables {ι M} lemma single_eq_lof (i : ι) (b : M i) : dfinsupp.single i b = lof R ι M i b := rfl theorem mk_smul (s : finset ι) (c : R) (x) : mk M s (c • x) = c • mk M s x := (lmk R ι M s).map_smul c x theorem of_smul (i : ι) (c : R) (x) : of M i (c • x) = c • of M i x := (lof R ι M i).map_smul c x variables {N : Type u₁} [add_comm_group N] [semimodule R N] variables (φ : Π i, M i →ₗ[R] N) variables (ι N φ) def to_module : direct_sum ι M →ₗ[R] N := { to_fun := to_group (λ i, φ i), add := to_group_add _, smul := λ c x, direct_sum.induction_on x (by rw [smul_zero, to_group_zero, smul_zero]) (λ i x, by rw [← of_smul, to_group_of, to_group_of, (φ i).map_smul c x]) (λ x y ihx ihy, by rw [smul_add, to_group_add, ihx, ihy, to_group_add, smul_add]) } variables {ι N φ} @[simp] lemma to_module_lof (i) (x : M i) : to_module R ι N φ (lof R ι M i x) = φ i x := to_group_of (λ i, φ i) i x variables (ψ : direct_sum ι M →ₗ[R] N) theorem to_module.unique (f : direct_sum ι M) : ψ f = to_module R ι N (λ i, ψ.comp $ lof R ι M i) f := to_group.unique ψ f variables {ψ} {ψ' : direct_sum ι M →ₗ[R] N} theorem to_module.ext (H : ∀ i, ψ.comp (lof R ι M i) = ψ'.comp (lof R ι M i)) (f : direct_sum ι M) : ψ f = ψ' f := by rw [to_module.unique R ψ, to_module.unique R ψ', funext H] def lset_to_set (S T : set ι) (H : S ⊆ T) : direct_sum S (M ∘ subtype.val) →ₗ direct_sum T (M ∘ subtype.val) := to_module R _ _ $ λ i, lof R T (M ∘ @subtype.val _ T) ⟨i.1, H i.2⟩ protected def lid (M : Type v) [add_comm_group M] [semimodule R M] : direct_sum punit (λ _, M) ≃ₗ M := { .. direct_sum.id M, .. to_module R punit M (λ i, linear_map.id) } variables (ι M) def component (i : ι) : direct_sum ι M →ₗ[R] M i := { to_fun := λ f, f i, add := λ _ _, dfinsupp.add_apply, smul := λ _ _, dfinsupp.smul_apply } variables {ι M} @[simp] lemma lof_apply (i : ι) (b : M i) : ((lof R ι M i) b) i = b := by rw [lof, dfinsupp.lsingle_apply, dfinsupp.single_apply, dif_pos rfl] lemma apply_eq_component (f : direct_sum ι M) (i : ι) : f i = component R ι M i f := rfl @[simp] lemma component.lof_self (i : ι) (b : M i) : component R ι M i ((lof R ι M i) b) = b := lof_apply R i b lemma component.of (i j : ι) (b : M j) : component R ι M i ((lof R ι M j) b) = if h : j = i then eq.rec_on h b else 0 := dfinsupp.single_apply @[ext] lemma ext {f g : direct_sum ι M} (h : ∀ i, component R ι M i f = component R ι M i g) : f = g := dfinsupp.ext h lemma ext_iff {f g : direct_sum ι M} : f = g ↔ ∀ i, component R ι M i f = component R ι M i g := ⟨λ h _, by rw h, ext R⟩ end direct_sum
66d49862e17fd91f145e67bd570fd41558e45ba9
ebf7140a9ea507409ff4c994124fa36e79b4ae35
/src/exercises_sources/monday/metaprogramming.lean
63fa64730250264cfc4e57d9c3af639f317868fe
[]
no_license
fundou/lftcm2020
3e88d58a92755ea5dd49f19c36239c35286ecf5e
99d11bf3bcd71ffeaef0250caa08ecc46e69b55b
refs/heads/master
1,685,610,799,304
1,624,070,416,000
1,624,070,416,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,898
lean
import tactic open tactic /-! This file contains three tactic-programming exercises of increasing difficulty. They were (hastily) written to follow the metaprogramming tutorial at Lean for the Curious Mathematician 2020. If you're looking for more (better) exercises, we strongly recommend the exercises by Blanchette et al for the course Logical Verification at the Vrije Universiteit Amsterdam, and the corresponding chapter of the course notes: https://github.com/blanchette/logical_verification_2020/blob/master/lean/love07_metaprogramming_exercise_sheet.lean https://github.com/blanchette/logical_verification_2020/raw/master/hitchhikers_guide.pdf ## Exercise 1 Write a `contradiction` tactic. The tactic should look through the hypotheses in the local context trying to find two that contradict each other, i.e. proving `P` and `¬ P` for some proposition `P`. It should use this contradiction to close the goal. Bonus: handle `P → false` as well as `¬ P`. This exercise is to practice manipulating the hypotheses and goal. Note: this exists as `tactic.interactive.contradiction`. -/ meta def tactic.interactive.contr : tactic unit := admit -- change this example (P Q R : Prop) (hp : P) (hq : Q) (hr : ¬ R) (hnq : ¬ Q) : false := by contr example (P Q R : Prop) (hnq : ¬ Q) (hp : P) (hq : Q) (hr : ¬ R) : 0 = 1 := by contr example (P Q R : Prop) (hp : P) (hq : Q) (hr : ¬ R) (hnq : Q → false) : false := by contr /-! ## Exercise 2 Write a tactic that proves a given `nat`-valued declaration is nonnegative. The tactic should take the name of a declaration whose return type is `ℕ` (presumably with some arguments), e.g. `nat.add : ℕ → ℕ → ℕ` or `list.length : Π α : Type, list α → ℕ`. It should add a new declaration to the environment which proves all applications of this function are nonnegative, e.g. `nat.add_nonneg : ∀ m n : ℕ, 0 ≤ nat.add m n`. Bonus: create reasonable names for these declarations, and/or take an optional argument for the new name. This tactic is not useful by itself, but it's a good way to practice querying and modifying an environment and working under binders. It is not a tactic to be used during a proof, but rather as a command. Hints: * For looking at declarations in the environment, you will need the `declaration` type, as well as the tactics `get_decl` and `add_decl`. * You will have to manipulate an expression under binders. The tactics `mk_local_pis` and `pis`, or their lambda equivalents, will be helpful here. * `mk_mapp` is a variant of `mk_app` that lets you provide implicit arguments. -/ meta def add_nonneg_proof (n : name) : tactic unit := sorry -- these test cases should succeed when you're done -- run_cmd add_nonneg_proof `nat.add -- run_cmd add_nonneg_proof `list.length -- #check nat.add_nonneg -- #check list.length_nonneg /-! ## Exercise 3 (challenge!) The mathlib tactic `cancel_denoms` is intended to get rid of division by numerals in expressions where this makes sense. For example, -/ example (q : ℚ) (h : q / 3 > 0) : q > 0 := begin cancel_denoms at h, exact h end /-! But it is not complete. In particular, it doesn't like nested division or other operators in denominators. These all fail: -/ example (q : ℚ) (h : q / (3 / 4) > 0) : false := begin -- cancel_denoms at h, sorry end example (p q : ℚ) (h : q / 2 / 3 < q) : false := begin -- cancel_denoms at h, sorry end example (p q : ℚ) (h : q / 2 < 3 / (4*q)) : false := begin -- cancel_denoms at h, sorry end -- this one succeeds but doesn't do what it should example (p q : ℚ) (h : q / (2*3) < q) : false := begin -- cancel_denoms at h, sorry end /-! Look at the code in `src/tactic/cancel_denoms.lean` and try to fix it. See if you can solve any or all of these failing test cases. If you succeed, a pull request to mathlib is strongly encouraged! -/
6b9682ce081f74db436114e483e122c208ee81ab
572fb32b6f5b7c2bf26921ffa2abea054cce881a
/src/week_2/Part_A_groups.lean
4a14e654280679915b78bf740127e0c80282bec5
[ "Apache-2.0" ]
permissive
kgeorgiy/lean-formalising-mathematics
2deb30756d5a54bee1cfa64873e86f641c59c7dc
73429a8ded68f641c896b6ba9342450d4d3ae50f
refs/heads/master
1,683,029,640,682
1,621,403,041,000
1,621,403,041,000
367,790,347
0
0
null
null
null
null
UTF-8
Lean
false
false
12,236
lean
import tactic /-! # Groups Definition and basic properties of a group. -/ -- Technical note: We work in a namespace `xena` because Lean already has groups. namespace xena -- Now our definition of a group will really be called `xena.group`. /- ## Definition of a group The `group` class will extend `has_mul`, `has_one` and `has_inv`. `has_mul G` means that `G` has a multiplication `* : G → G → G` `has_one G` means that `G` has a `1 : G` `has_inv G` means that `G` has an `⁻¹ : G → G` All of `*`, `1` and `⁻¹` are notation for functions -- no axioms yet. A `group` has all of this notation, and the group axioms too. Let's now define the group class. -/ /-- A `group` structure on a type `G` is multiplication, identity and inverse, plus the usual axioms -/ class group (G : Type) extends has_mul G, has_one G, has_inv G := (mul_assoc : ∀ (a b c : G), a * b * c = a * (b * c)) (one_mul : ∀ (a : G), 1 * a = a) (mul_left_inv : ∀ (a : G), a⁻¹ * a = 1) /- Formally, a term of type `group G` is now the following data: a multiplication, 1, and inverse function, and proofs that the group axioms are satisfied. The way to say "let G be a group" is now `(G : Type) [group G]` The square bracket notation is the notation used for classes. Formally, it means "put a term of type `group G` into the type class inference system". In practice this just means "you can use group notation and axioms in proofs, and Lean will figure out why they're true" We have been extremely mean with our axioms. Some authors also add the axioms `mul_one : ∀ (a : G), a * 1 = a` and `mul_right_inv : ∀ (a : G), a * a⁻¹ = 1`. But these follow from the three axioms we used. Our first job is to prove them. As you might imagine, mathematically this is pretty much the trickiest part, because we have to be careful not to accidentally assume these axioms when we're proving them. Here are the four lemmas we will prove next. `mul_left_cancel : ∀ (a b c : G), a * b = a * c → b = c` `mul_eq_of_eq_inv_mul {a x y : G} : x = a⁻¹ * y → a * x = y` `mul_one (a : G) : a * 1 = a` `mul_right_inv (a : G) : a * a⁻¹ = 1` -/ -- We're proving things about groups so let's work in the `group` namespace -- (really this is `xena.group`) namespace group -- let `G` be a group. variables {G : Type} [group G] /- We start by proving `mul_left_cancel : ∀ a b c, a * b = a * c → b = c`. We assume `Habac : a * b = a * c` and deduce `b = c`. I've written down the maths proof. Your job is to supply the rewrites that are necessary to justify each step. Each rewrite is either one of the axioms of a group, or an assumption. A reminder of the axioms: `mul_assoc : ∀ (a b c : G), a * b * c = a * (b * c)` `one_mul : ∀ (a : G), 1 * a = a` `mul_left_inv : ∀ (a : G), a⁻¹ * a = 1` This proof could be done using rewrites, but I will take this opportunity to introduce the `calc` tactic. -/ lemma mul_left_cancel (a b c : G) (Habac : a * b = a * c) : b = c := begin calc b = 1 * b : by rw one_mul ... = (a⁻¹ * a) * b : by rw mul_left_inv ... = a⁻¹ * (a * b) : by rw mul_assoc ... = a⁻¹ * (a * c) : by rw Habac ... = (a⁻¹ * a) * c : by rw mul_assoc ... = 1 * c : by rw ← mul_left_inv ... = c : by rw one_mul end /- Next we prove that if `x = a⁻¹ * y` then `a * x = y`. Remember we are still missing `mul_one` and `mul_right_inv`. A proof that avoids them is the following: we want `a * x = y`. Now `apply`ing the previous lemma, it suffices to prove that `a⁻¹ * (a * x) = a⁻¹ * y.` Now use associativity and left cancellation on on the left, to reduce to `h`. Note that `mul_left_cancel` is a function, and its first input is called `a`, but you had better give it `a⁻¹` instead. -/ lemma mul_eq_of_eq_inv_mul {a x y : G} (h : x = a⁻¹ * y) : a * x = y := begin apply mul_left_cancel a⁻¹, rw ← mul_assoc, rw mul_left_inv, rwa one_mul, end -- It's a bore to keep introducing variable names. -- Let `a,b,c,x,y` be elements of `G`. variables (a b c x y : G) /- We can use `mul_eq_of_eq_inv_mul` to prove the two "missing" axioms `mul_one` and `mul_right_inv`, and then our lives will be much easier. Try `apply`ing it in the theorems below. -/ @[simp] theorem mul_one : a * 1 = a := begin apply mul_eq_of_eq_inv_mul, rw mul_left_inv, end @[simp] theorem mul_right_inv : a * a⁻¹ = 1 := begin apply mul_eq_of_eq_inv_mul, rw mul_one, end -- Now let's talk about what that `@[simp]` means. /- ## Lean's simplifier A human sees `a * a⁻¹` in group theory, and instantly replaces it with `1`. We are going to train a simple AI called `simp` to do the same thing. Lean's simplifier `simp` is a "term rewriting system". This means that if you teach it a bunch of theorems of the form `A = B` or `P ↔ Q` (by tagging them with the `@[simp]` attribute) and then give it a complicated goal, like `example : (a * b) * 1⁻¹⁻¹ * b⁻¹ * (a⁻¹ * a⁻¹⁻¹⁻¹) * a = 1` then it will try to use the `rw` tactic as much as it can, using the lemmas it has been taught, in an attempt to simplify the goal. If it manages to solve it completely, then great! If it does not, but you feel like it should have done, you might want to tag more lemmas with `@[simp]`. `simp` should only be used to completely close goals. We are now going to train the simplifier to solve the example above (indeed, we are going to train it to reduce an arbitrary element of a free group into a unique normal form, so it will solve any equalities which are true for all groups, like the example above). ## Important note Lean's simplifier does a series of rewrites, each one replacing something with something else. But the simplifier will always rewrite from left to right! If you tell it that `A = B` is a `simp` lemma then it will replace `A`s with `B`s, but it will never replace `B`s with `A`s. If you tag a proof of `A = B` with `@[simp]` and you also tag a proof of `B = A` with `@[simp]`, then the simplifier will get stuck in an infinite loop when it runs into an `A`! Equality should not be thought of as symmetric here. Because the simplifier works from left to right, an important rule of thumb is that if `A = B` is a `simp` lemma, then `B` should probably be simpler than `A`! In particular, equality should not be thought of as symmetric here. It is not a coincidence that in the theorems below `@[simp] theorem mul_one (a : G) : a * 1 = a` `@[simp] theorem mul_right_inv (a : G) : a * a⁻¹ = 1` the right hand side is simpler than the left hand side. It would be a > disaster to tag `a = a * 1` with the `@[simp]` tag -- can you see why? Let's train Lean's simplifier! Let's teach it the axioms of a `group` next. We have already done the axioms, so we have to retrospectively tag them with the `@[simp]` attribute. -/ attribute [simp] one_mul mul_left_inv mul_assoc /- Now let's teach the simplifier the following five lemmas: `inv_mul_cancel_left : a⁻¹ * (a * b) = b` `mul_inv_cancel_left : a * (a⁻¹ * b) = b` `inv_mul : (a * b)⁻¹ = b⁻¹ * a⁻¹` `one_inv : (1 : G)⁻¹ = 1` `inv_inv : (a⁻¹)⁻¹ = a` Note that in each case, the right hand side is simpler than the left hand side. Try using the simplifier in your proofs! I will do the first one for you. -/ @[simp] lemma inv_mul_cancel_left : a⁻¹ * (a * b) = b := begin rw ← mul_assoc, -- the simplifier wouldn't do it that way -- so we have to do it manually simp, -- simplifier takes it from here, -- rewriting a⁻¹ * a to 1 and then 1 * b to b end @[simp] lemma mul_inv_cancel_left : a * (a⁻¹ * b) = b := begin rw ← mul_assoc, simp, end @[simp] lemma inv_mul : (a * b)⁻¹ = b⁻¹ * a⁻¹ := begin apply mul_left_cancel (a * b), rw [mul_right_inv, mul_assoc a, ← mul_assoc b], simp, end @[simp] lemma one_inv : (1 : G)⁻¹ = 1 := begin apply mul_left_cancel (1 : G), rw [mul_right_inv, one_mul], end @[simp] lemma inv_inv : a ⁻¹ ⁻¹ = a := begin apply mul_left_cancel a⁻¹, simp, end /- The reason I choose these five lemmas in particular, is that term rewriting systems are very well understood by computer scientists, and in particular there is something called the Knuth-Bendix algorithm, which, given as input the three axioms for a group which we used, produces a "confluent and noetherian term rewrite system" that transforms every term into a unique normal form. The system it produces is precisely the `simp` lemmas which we haven proven above! See https://en.wikipedia.org/wiki/Word_problem_(mathematics)#Example:_A_term_rewriting_system_to_decide_the_word_problem_in_the_free_group for more information. I won't talk any more about the Knuth-Bendix algorithm because it's really computer science, and I don't really understand it, but apparently if you apply it to polynomial rings then you get Buchberger's algorithm for computing Gröbner bases. -/ -- Now let's try our example... example : (a * b) * 1⁻¹⁻¹ * b⁻¹ * (a⁻¹ * a⁻¹⁻¹⁻¹) * a = 1 := by simp -- short for begin simp end -- The simplifier solves it! -- try your own identities. `simp` will solve them all! /- This is everything I wanted to show you about groups and the simplifier today. You can now either go on to subgroups in Part B, or practice your group theory skills by proving the lemmas below. -/ /- We already proved `mul_eq_of_eq_inv_mul` but there are several other similar-looking, but slightly different, versions of this. Here is one. -/ lemma eq_mul_inv_of_mul_eq {a b c : G} (h : a * c = b) : a = b * c⁻¹ := begin rw [← h], simp, end lemma eq_inv_mul_of_mul_eq {a b c : G} (h : b * a = c) : a = b⁻¹ * c := begin rw [← h], simp, end lemma mul_left_eq_self {a b : G} : a * b = b ↔ a = 1 := begin split, intro h, simp [eq_mul_inv_of_mul_eq h], rintro rfl, simp, end lemma mul_right_eq_self {a b : G} : a * b = a ↔ b = 1 := begin split, intro h, simp [eq_inv_mul_of_mul_eq h], rintro rfl, simp, end lemma eq_inv_of_mul_eq_one {a b : G} (h : a * b = 1) : a = b⁻¹ := begin convert eq_mul_inv_of_mul_eq h, --rw [← mul_one a, ← mul_right_inv b, ← mul_assoc, h], simp, end lemma inv_eq_of_mul_eq_one {a b : G} (h : a * b = 1) : a⁻¹ = b := begin apply mul_left_cancel a, simp [h], end lemma unique_left_id {e : G} (h : ∀ x : G, e * x = x) : e = 1 := begin rw [← h 1], simp, end lemma unique_right_inv {a b : G} (h : a * b = 1) : b = a⁻¹ := begin apply mul_left_cancel a, simp [h], end lemma mul_left_cancel_iff (a x y : G) : a * x = a * y ↔ x = y := begin split, apply mul_left_cancel, intro hxy, rwa hxy end -- You don't even need to go into tactic mode (begin/end) to use `calc`: lemma mul_right_cancel (a x y : G) (Habac : x * a = y * a) : x = y := calc x = x * 1 : by rw mul_one ... = x * (a * a⁻¹) : by rw mul_right_inv ... = (x * a) * a⁻¹ : by rw mul_assoc ... = (y * a) * a⁻¹ : by rw Habac -- ... = y * (a * a⁻¹) : by rw mul_assoc -- ... = y * 1 : by rw mul_right_inv -- ... = y : by rw mul_one ... = y : by simp -- mul_assoc : a * b * c = a * (b * c) -- one_mul : 1 * a = a -- mul_one : a * 1 = a -- mul_left_inv : a⁻¹ * a = 1 -- mul_right_inv : a * a⁻¹ = 1 -- mul_left_cancel : a * b = a * c → b = c -- mul_eq_of_eq_inv_mul : x = a⁻¹ * y → a * x = y -- eq_mul_inv_of_mul_eq : a * c = b → a = b * c⁻¹ -- eq_inv_mul_of_mul_eq : b * a = c → a = b⁻¹ * c -- mul_left_eq_self : a * b = b ↔ a = 1 -- mul_right_eq_self : a * b = a ↔ b = 1 -- unique_left_id : ∀ x, e * x = x → e = 1 -- unique_right_inv : a * b = 1 → b = a⁻¹ -- mul_left_cancel_iff : a * x = a * y ↔ x = y -- `↔` lemmas are good simp lemmas too. @[simp] theorem inv_inj_iff {a b : G}: a⁻¹ = b⁻¹ ↔ a = b := begin split, intro h, --rw [← inv_inv a, h, inv_inv b], apply mul_left_cancel a⁻¹, rw [mul_left_inv], simp [h], rintro rfl, refl, end theorem inv_eq {a b : G}: a⁻¹ = b ↔ b⁻¹ = a := begin split; rintro rfl; rw inv_inv, end end group end xena
53dcea59d0555684f744c0d76dd6dcba42508230
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/analysis/special_functions/integrals.lean
948ee9f89c7a7ca8d5414472638d102f224241fc
[ "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
20,514
lean
/- Copyright (c) 2021 Benjamin Davidson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Benjamin Davidson -/ import measure_theory.integral.interval_integral /-! # Integration of specific interval integrals This file contains proofs of the integrals of various specific functions. This includes: * Integrals of simple functions, such as `id`, `pow`, `inv`, `exp`, `log` * Integrals of some trigonometric functions, such as `sin`, `cos`, `1 / (1 + x^2)` * The integral of `cos x ^ 2 - sin x ^ 2` * Reduction formulae for the integrals of `sin x ^ n` and `cos x ^ n` for `n ≥ 2` * The computation of `∫ x in 0..π, sin x ^ n` as a product for even and odd `n` (used in proving the Wallis product for pi) * Integrals of the form `sin x ^ m * cos x ^ n` With these lemmas, many simple integrals can be computed by `simp` or `norm_num`. See `test/integration.lean` for specific examples. This file also contains some facts about the interval integrability of specific functions. This file is still being developed. ## Tags integrate, integration, integrable, integrability -/ open real nat set finset open_locale real big_operators interval variables {a b : ℝ} (n : ℕ) namespace interval_integral open measure_theory variables {f : ℝ → ℝ} {μ ν : measure ℝ} [is_locally_finite_measure μ] (c d : ℝ) /-! ### Interval integrability -/ @[simp] lemma interval_integrable_pow : interval_integrable (λ x, x^n) μ a b := (continuous_pow n).interval_integrable a b @[simp] lemma interval_integrable_id : interval_integrable (λ x, x) μ a b := continuous_id.interval_integrable a b @[simp] lemma interval_integrable_const : interval_integrable (λ x, c) μ a b := continuous_const.interval_integrable a b @[simp] lemma interval_integrable.const_mul (h : interval_integrable f ν a b) : interval_integrable (λ x, c * f x) ν a b := by convert h.smul c @[simp] lemma interval_integrable.mul_const (h : interval_integrable f ν a b) : interval_integrable (λ x, f x * c) ν a b := by simp only [mul_comm, interval_integrable.const_mul c h] @[simp] lemma interval_integrable.div (h : interval_integrable f ν a b) : interval_integrable (λ x, f x / c) ν a b := interval_integrable.mul_const c⁻¹ h lemma interval_integrable_one_div (h : ∀ x : ℝ, x ∈ [a, b] → f x ≠ 0) (hf : continuous_on f [a, b]) : interval_integrable (λ x, 1 / f x) μ a b := (continuous_on_const.div hf h).interval_integrable @[simp] lemma interval_integrable_inv (h : ∀ x : ℝ, x ∈ [a, b] → f x ≠ 0) (hf : continuous_on f [a, b]) : interval_integrable (λ x, (f x)⁻¹) μ a b := by simpa only [one_div] using interval_integrable_one_div h hf @[simp] lemma interval_integrable_exp : interval_integrable exp μ a b := continuous_exp.interval_integrable a b @[simp] lemma interval_integrable.log (hf : continuous_on f [a, b]) (h : ∀ x : ℝ, x ∈ [a, b] → f x ≠ 0) : interval_integrable (λ x, log (f x)) μ a b := (continuous_on.log hf h).interval_integrable @[simp] lemma interval_integrable_log (h : (0:ℝ) ∉ [a, b]) : interval_integrable log μ a b := interval_integrable.log continuous_on_id $ λ x hx, ne_of_mem_of_not_mem hx h @[simp] lemma interval_integrable_sin : interval_integrable sin μ a b := continuous_sin.interval_integrable a b @[simp] lemma interval_integrable_cos : interval_integrable cos μ a b := continuous_cos.interval_integrable a b lemma interval_integrable_one_div_one_add_sq : interval_integrable (λ x : ℝ, 1 / (1 + x^2)) μ a b := begin refine (continuous_const.div _ (λ x, _)).interval_integrable a b, { continuity }, { nlinarith }, end @[simp] lemma interval_integrable_inv_one_add_sq : interval_integrable (λ x : ℝ, (1 + x^2)⁻¹) μ a b := by simpa only [one_div] using interval_integrable_one_div_one_add_sq /-! ### Integral of a function scaled by a constant -/ @[simp] lemma integral_const_mul : ∫ x in a..b, c * f x = c * ∫ x in a..b, f x := integral_smul c f @[simp] lemma integral_mul_const : ∫ x in a..b, f x * c = (∫ x in a..b, f x) * c := by simp only [mul_comm, integral_const_mul] @[simp] lemma integral_div : ∫ x in a..b, f x / c = (∫ x in a..b, f x) / c := integral_mul_const c⁻¹ /-! ### Integrals of the form `c * ∫ x in a..b, f (c * x + d)` -/ @[simp] lemma mul_integral_comp_mul_right : c * ∫ x in a..b, f (x * c) = ∫ x in a*c..b*c, f x := smul_integral_comp_mul_right f c @[simp] lemma mul_integral_comp_mul_left : c * ∫ x in a..b, f (c * x) = ∫ x in c*a..c*b, f x := smul_integral_comp_mul_left f c @[simp] lemma inv_mul_integral_comp_div : c⁻¹ * ∫ x in a..b, f (x / c) = ∫ x in a/c..b/c, f x := inv_smul_integral_comp_div f c @[simp] lemma mul_integral_comp_mul_add : c * ∫ x in a..b, f (c * x + d) = ∫ x in c*a+d..c*b+d, f x := smul_integral_comp_mul_add f c d @[simp] lemma mul_integral_comp_add_mul : c * ∫ x in a..b, f (d + c * x) = ∫ x in d+c*a..d+c*b, f x := smul_integral_comp_add_mul f c d @[simp] lemma inv_mul_integral_comp_div_add : c⁻¹ * ∫ x in a..b, f (x / c + d) = ∫ x in a/c+d..b/c+d, f x := inv_smul_integral_comp_div_add f c d @[simp] lemma inv_mul_integral_comp_add_div : c⁻¹ * ∫ x in a..b, f (d + x / c) = ∫ x in d+a/c..d+b/c, f x := inv_smul_integral_comp_add_div f c d @[simp] lemma mul_integral_comp_mul_sub : c * ∫ x in a..b, f (c * x - d) = ∫ x in c*a-d..c*b-d, f x := smul_integral_comp_mul_sub f c d @[simp] lemma mul_integral_comp_sub_mul : c * ∫ x in a..b, f (d - c * x) = ∫ x in d-c*b..d-c*a, f x := smul_integral_comp_sub_mul f c d @[simp] lemma inv_mul_integral_comp_div_sub : c⁻¹ * ∫ x in a..b, f (x / c - d) = ∫ x in a/c-d..b/c-d, f x := inv_smul_integral_comp_div_sub f c d @[simp] lemma inv_mul_integral_comp_sub_div : c⁻¹ * ∫ x in a..b, f (d - x / c) = ∫ x in d-b/c..d-a/c, f x := inv_smul_integral_comp_sub_div f c d end interval_integral open interval_integral /-! ### Integrals of simple functions -/ @[simp] lemma integral_pow : ∫ x in a..b, x ^ n = (b ^ (n + 1) - a ^ (n + 1)) / (n + 1) := begin have hderiv : deriv (λ x : ℝ, x ^ (n + 1) / (n + 1)) = λ x, x ^ n, { ext, have hne : (n + 1 : ℝ) ≠ 0 := by exact_mod_cast succ_ne_zero n, simp [mul_div_assoc, mul_div_cancel' _ hne] }, rw integral_deriv_eq_sub' _ hderiv; norm_num [div_sub_div_same, continuous_on_pow], end /-- Integral of `|x - a| ^ n` over `Ι a b`. This integral appears in the proof of the Picard-Lindelöf/Cauchy-Lipschitz theorem. -/ lemma integral_pow_abs_sub_interval_oc : ∫ x in Ι a b, |x - a| ^ n = |b - a| ^ (n + 1) / (n + 1) := begin cases le_or_lt a b with hab hab, { calc ∫ x in Ι a b, |x - a| ^ n = ∫ x in a..b, |x - a| ^ n : by rw [interval_oc_of_le hab, ← integral_of_le hab] ... = ∫ x in 0..(b - a), x ^ n : begin simp only [integral_comp_sub_right (λ x, |x| ^ n), sub_self], refine integral_congr (λ x hx, congr_arg2 has_pow.pow (abs_of_nonneg $ _) rfl), rw interval_of_le (sub_nonneg.2 hab) at hx, exact hx.1 end ... = |b - a| ^ (n + 1) / (n + 1) : by simp [abs_of_nonneg (sub_nonneg.2 hab)] }, { calc ∫ x in Ι a b, |x - a| ^ n = ∫ x in b..a, |x - a| ^ n : by rw [interval_oc_of_lt hab, ← integral_of_le hab.le] ... = ∫ x in b - a..0, (-x) ^ n : begin simp only [integral_comp_sub_right (λ x, |x| ^ n), sub_self], refine integral_congr (λ x hx, congr_arg2 has_pow.pow (abs_of_nonpos $ _) rfl), rw interval_of_le (sub_nonpos.2 hab.le) at hx, exact hx.2 end ... = |b - a| ^ (n + 1) / (n + 1) : by simp [integral_comp_neg (λ x, x ^ n), abs_of_neg (sub_neg.2 hab)] } end @[simp] lemma integral_id : ∫ x in a..b, x = (b ^ 2 - a ^ 2) / 2 := by simpa using integral_pow 1 @[simp] lemma integral_one : ∫ x in a..b, (1 : ℝ) = b - a := by simp only [mul_one, smul_eq_mul, integral_const] @[simp] lemma integral_inv (h : (0:ℝ) ∉ [a, b]) : ∫ x in a..b, x⁻¹ = log (b / a) := begin have h' := λ x hx, ne_of_mem_of_not_mem hx h, rw [integral_deriv_eq_sub' _ deriv_log' (λ x hx, differentiable_at_log (h' x hx)) (continuous_on_inv₀.mono $ subset_compl_singleton_iff.mpr h), log_div (h' b right_mem_interval) (h' a left_mem_interval)], end @[simp] lemma integral_inv_of_pos (ha : 0 < a) (hb : 0 < b) : ∫ x in a..b, x⁻¹ = log (b / a) := integral_inv $ not_mem_interval_of_lt ha hb @[simp] lemma integral_inv_of_neg (ha : a < 0) (hb : b < 0) : ∫ x in a..b, x⁻¹ = log (b / a) := integral_inv $ not_mem_interval_of_gt ha hb lemma integral_one_div (h : (0:ℝ) ∉ [a, b]) : ∫ x : ℝ in a..b, 1/x = log (b / a) := by simp only [one_div, integral_inv h] lemma integral_one_div_of_pos (ha : 0 < a) (hb : 0 < b) : ∫ x : ℝ in a..b, 1/x = log (b / a) := by simp only [one_div, integral_inv_of_pos ha hb] lemma integral_one_div_of_neg (ha : a < 0) (hb : b < 0) : ∫ x : ℝ in a..b, 1/x = log (b / a) := by simp only [one_div, integral_inv_of_neg ha hb] @[simp] lemma integral_exp : ∫ x in a..b, exp x = exp b - exp a := by rw integral_deriv_eq_sub'; norm_num [continuous_on_exp] @[simp] lemma integral_log (h : (0:ℝ) ∉ [a, b]) : ∫ x in a..b, log x = b * log b - a * log a - b + a := begin obtain ⟨h', heq⟩ := ⟨λ x hx, ne_of_mem_of_not_mem hx h, λ x hx, mul_inv_cancel (h' x hx)⟩, convert integral_mul_deriv_eq_deriv_mul (λ x hx, has_deriv_at_log (h' x hx)) (λ x hx, has_deriv_at_id x) (continuous_on_inv₀.mono $ subset_compl_singleton_iff.mpr h).interval_integrable continuous_on_const.interval_integrable using 1; simp [integral_congr heq, mul_comm, ← sub_add], end @[simp] lemma integral_log_of_pos (ha : 0 < a) (hb : 0 < b) : ∫ x in a..b, log x = b * log b - a * log a - b + a := integral_log $ not_mem_interval_of_lt ha hb @[simp] lemma integral_log_of_neg (ha : a < 0) (hb : b < 0) : ∫ x in a..b, log x = b * log b - a * log a - b + a := integral_log $ not_mem_interval_of_gt ha hb @[simp] lemma integral_sin : ∫ x in a..b, sin x = cos a - cos b := by rw integral_deriv_eq_sub' (λ x, -cos x); norm_num [continuous_on_sin] @[simp] lemma integral_cos : ∫ x in a..b, cos x = sin b - sin a := by rw integral_deriv_eq_sub'; norm_num [continuous_on_cos] lemma integral_cos_sq_sub_sin_sq : ∫ x in a..b, cos x ^ 2 - sin x ^ 2 = sin b * cos b - sin a * cos a := by simpa only [sq, sub_eq_add_neg, neg_mul_eq_mul_neg] using integral_deriv_mul_eq_sub (λ x hx, has_deriv_at_sin x) (λ x hx, has_deriv_at_cos x) continuous_on_cos.interval_integrable continuous_on_sin.neg.interval_integrable @[simp] lemma integral_inv_one_add_sq : ∫ x : ℝ in a..b, (1 + x^2)⁻¹ = arctan b - arctan a := begin simp only [← one_div], refine integral_deriv_eq_sub' _ _ _ (continuous_const.div _ (λ x, _)).continuous_on, { norm_num }, { norm_num }, { continuity }, { nlinarith }, end lemma integral_one_div_one_add_sq : ∫ x : ℝ in a..b, 1 / (1 + x^2) = arctan b - arctan a := by simp only [one_div, integral_inv_one_add_sq] /-! ### Integral of `sin x ^ n` -/ lemma integral_sin_pow_aux : ∫ x in a..b, sin x ^ (n + 2) = sin a ^ (n + 1) * cos a - sin b ^ (n + 1) * cos b + (n + 1) * (∫ x in a..b, sin x ^ n) - (n + 1) * ∫ x in a..b, sin x ^ (n + 2) := begin let C := sin a ^ (n + 1) * cos a - sin b ^ (n + 1) * cos b, have h : ∀ α β γ : ℝ, α * (β * α * γ) = β * (α * α * γ) := λ α β γ, by ring, have hu : ∀ x ∈ _, has_deriv_at (λ y, sin y ^ (n + 1)) ((n + 1) * cos x * sin x ^ n) x := λ x hx, by simpa only [mul_right_comm] using (has_deriv_at_sin x).pow, have hv : ∀ x ∈ [a, b], has_deriv_at (-cos) (sin x) x := λ x hx, by simpa only [neg_neg] using (has_deriv_at_cos x).neg, have H := integral_mul_deriv_eq_deriv_mul hu hv _ _, calc ∫ x in a..b, sin x ^ (n + 2) = ∫ x in a..b, sin x ^ (n + 1) * sin x : by simp only [pow_succ'] ... = C + (n + 1) * ∫ x in a..b, cos x ^ 2 * sin x ^ n : by simp [H, h, sq] ... = C + (n + 1) * ∫ x in a..b, sin x ^ n - sin x ^ (n + 2) : by simp [cos_sq', sub_mul, ← pow_add, add_comm] ... = C + (n + 1) * (∫ x in a..b, sin x ^ n) - (n + 1) * ∫ x in a..b, sin x ^ (n + 2) : by rw [integral_sub, mul_sub, add_sub_assoc]; apply continuous.interval_integrable; continuity, all_goals { apply continuous.interval_integrable, continuity }, end /-- The reduction formula for the integral of `sin x ^ n` for any natural `n ≥ 2`. -/ lemma integral_sin_pow : ∫ x in a..b, sin x ^ (n + 2) = (sin a ^ (n + 1) * cos a - sin b ^ (n + 1) * cos b) / (n + 2) + (n + 1) / (n + 2) * ∫ x in a..b, sin x ^ n := begin have : (n : ℝ) + 2 ≠ 0 := by exact_mod_cast succ_ne_zero n.succ, field_simp, convert eq_sub_iff_add_eq.mp (integral_sin_pow_aux n), ring, end @[simp] lemma integral_sin_sq : ∫ x in a..b, sin x ^ 2 = (sin a * cos a - sin b * cos b + b - a) / 2 := by field_simp [integral_sin_pow, add_sub_assoc] theorem integral_sin_pow_odd : ∫ x in 0..π, sin x ^ (2 * n + 1) = 2 * ∏ i in range n, (2 * i + 2) / (2 * i + 3) := begin induction n with k ih, { norm_num }, rw [prod_range_succ_comm, mul_left_comm, ← ih, mul_succ, integral_sin_pow], norm_cast, simp [-cast_add] with field_simps, end theorem integral_sin_pow_even : ∫ x in 0..π, sin x ^ (2 * n) = π * ∏ i in range n, (2 * i + 1) / (2 * i + 2) := begin induction n with k ih, { simp }, rw [prod_range_succ_comm, mul_left_comm, ← ih, mul_succ, integral_sin_pow], norm_cast, simp [-cast_add] with field_simps, end lemma integral_sin_pow_pos : 0 < ∫ x in 0..π, sin x ^ n := begin rcases even_or_odd' n with ⟨k, (rfl | rfl)⟩; simp only [integral_sin_pow_even, integral_sin_pow_odd]; refine mul_pos (by norm_num [pi_pos]) (prod_pos (λ n hn, div_pos _ _)); norm_cast; linarith, end lemma integral_sin_pow_succ_le : ∫ x in 0..π, sin x ^ (n + 1) ≤ ∫ x in 0..π, sin x ^ n := let H := λ x h, pow_le_pow_of_le_one (sin_nonneg_of_mem_Icc h) (sin_le_one x) (n.le_add_right 1) in by refine integral_mono_on pi_pos.le _ _ H; exact (continuous_sin.pow _).interval_integrable 0 π lemma integral_sin_pow_antitone : antitone (λ n : ℕ, ∫ x in 0..π, sin x ^ n) := antitone_nat_of_succ_le integral_sin_pow_succ_le /-! ### Integral of `cos x ^ n` -/ lemma integral_cos_pow_aux : ∫ x in a..b, cos x ^ (n + 2) = cos b ^ (n + 1) * sin b - cos a ^ (n + 1) * sin a + (n + 1) * (∫ x in a..b, cos x ^ n) - (n + 1) * ∫ x in a..b, cos x ^ (n + 2) := begin let C := cos b ^ (n + 1) * sin b - cos a ^ (n + 1) * sin a, have h : ∀ α β γ : ℝ, α * (β * α * γ) = β * (α * α * γ) := λ α β γ, by ring, have hu : ∀ x ∈ _, has_deriv_at (λ y, cos y ^ (n + 1)) (-(n + 1) * sin x * cos x ^ n) x := λ x hx, by simpa only [mul_right_comm, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm] using (has_deriv_at_cos x).pow, have hv : ∀ x ∈ [a, b], has_deriv_at sin (cos x) x := λ x hx, has_deriv_at_sin x, have H := integral_mul_deriv_eq_deriv_mul hu hv _ _, calc ∫ x in a..b, cos x ^ (n + 2) = ∫ x in a..b, cos x ^ (n + 1) * cos x : by simp only [pow_succ'] ... = C + (n + 1) * ∫ x in a..b, sin x ^ 2 * cos x ^ n : by simp [H, h, sq, -neg_add_rev] ... = C + (n + 1) * ∫ x in a..b, cos x ^ n - cos x ^ (n + 2) : by simp [sin_sq, sub_mul, ← pow_add, add_comm] ... = C + (n + 1) * (∫ x in a..b, cos x ^ n) - (n + 1) * ∫ x in a..b, cos x ^ (n + 2) : by rw [integral_sub, mul_sub, add_sub_assoc]; apply continuous.interval_integrable; continuity, all_goals { apply continuous.interval_integrable, continuity }, end /-- The reduction formula for the integral of `cos x ^ n` for any natural `n ≥ 2`. -/ lemma integral_cos_pow : ∫ x in a..b, cos x ^ (n + 2) = (cos b ^ (n + 1) * sin b - cos a ^ (n + 1) * sin a) / (n + 2) + (n + 1) / (n + 2) * ∫ x in a..b, cos x ^ n := begin have : (n : ℝ) + 2 ≠ 0 := by exact_mod_cast succ_ne_zero n.succ, field_simp, convert eq_sub_iff_add_eq.mp (integral_cos_pow_aux n), ring, end @[simp] lemma integral_cos_sq : ∫ x in a..b, cos x ^ 2 = (cos b * sin b - cos a * sin a + b - a) / 2 := by field_simp [integral_cos_pow, add_sub_assoc] /-! ### Integral of `sin x ^ m * cos x ^ n` -/ /-- Simplification of the integral of `sin x ^ m * cos x ^ n`, case `n` is odd. -/ lemma integral_sin_pow_mul_cos_pow_odd (m n : ℕ) : ∫ x in a..b, sin x ^ m * cos x ^ (2 * n + 1) = ∫ u in sin a..sin b, u ^ m * (1 - u ^ 2) ^ n := have hc : continuous (λ u : ℝ, u ^ m * (1 - u ^ 2) ^ n), by continuity, calc ∫ x in a..b, sin x ^ m * cos x ^ (2 * n + 1) = ∫ x in a..b, sin x ^ m * (1 - sin x ^ 2) ^ n * cos x : by simp only [pow_succ', ← mul_assoc, pow_mul, cos_sq'] ... = ∫ u in sin a..sin b, u ^ m * (1 - u ^ 2) ^ n : integral_comp_mul_deriv (λ x hx, has_deriv_at_sin x) continuous_on_cos hc /-- The integral of `sin x * cos x`, given in terms of sin². See `integral_sin_mul_cos₂` below for the integral given in terms of cos². -/ @[simp] lemma integral_sin_mul_cos₁ : ∫ x in a..b, sin x * cos x = (sin b ^ 2 - sin a ^ 2) / 2 := by simpa using integral_sin_pow_mul_cos_pow_odd 1 0 @[simp] lemma integral_sin_sq_mul_cos : ∫ x in a..b, sin x ^ 2 * cos x = (sin b ^ 3 - sin a ^ 3) / 3 := by simpa using integral_sin_pow_mul_cos_pow_odd 2 0 @[simp] lemma integral_cos_pow_three : ∫ x in a..b, cos x ^ 3 = sin b - sin a - (sin b ^ 3 - sin a ^ 3) / 3 := by simpa using integral_sin_pow_mul_cos_pow_odd 0 1 /-- Simplification of the integral of `sin x ^ m * cos x ^ n`, case `m` is odd. -/ lemma integral_sin_pow_odd_mul_cos_pow (m n : ℕ) : ∫ x in a..b, sin x ^ (2 * m + 1) * cos x ^ n = ∫ u in cos b..cos a, u ^ n * (1 - u ^ 2) ^ m := have hc : continuous (λ u : ℝ, u ^ n * (1 - u ^ 2) ^ m), by continuity, calc ∫ x in a..b, sin x ^ (2 * m + 1) * cos x ^ n = -∫ x in b..a, sin x ^ (2 * m + 1) * cos x ^ n : by rw integral_symm ... = ∫ x in b..a, (1 - cos x ^ 2) ^ m * -sin x * cos x ^ n : by simp [pow_succ', pow_mul, sin_sq] ... = ∫ x in b..a, cos x ^ n * (1 - cos x ^ 2) ^ m * -sin x : by { congr, ext, ring } ... = ∫ u in cos b..cos a, u ^ n * (1 - u ^ 2) ^ m : integral_comp_mul_deriv (λ x hx, has_deriv_at_cos x) continuous_on_sin.neg hc /-- The integral of `sin x * cos x`, given in terms of cos². See `integral_sin_mul_cos₁` above for the integral given in terms of sin². -/ lemma integral_sin_mul_cos₂ : ∫ x in a..b, sin x * cos x = (cos a ^ 2 - cos b ^ 2) / 2 := by simpa using integral_sin_pow_odd_mul_cos_pow 0 1 @[simp] lemma integral_sin_mul_cos_sq : ∫ x in a..b, sin x * cos x ^ 2 = (cos a ^ 3 - cos b ^ 3) / 3 := by simpa using integral_sin_pow_odd_mul_cos_pow 0 2 @[simp] lemma integral_sin_pow_three : ∫ x in a..b, sin x ^ 3 = cos a - cos b - (cos a ^ 3 - cos b ^ 3) / 3 := by simpa using integral_sin_pow_odd_mul_cos_pow 1 0 /-- Simplification of the integral of `sin x ^ m * cos x ^ n`, case `m` and `n` are both even. -/ lemma integral_sin_pow_even_mul_cos_pow_even (m n : ℕ) : ∫ x in a..b, sin x ^ (2 * m) * cos x ^ (2 * n) = ∫ x in a..b, ((1 - cos (2 * x)) / 2) ^ m * ((1 + cos (2 * x)) / 2) ^ n := by field_simp [pow_mul, sin_sq, cos_sq, ← sub_sub, (by ring : (2:ℝ) - 1 = 1)] @[simp] lemma integral_sin_sq_mul_cos_sq : ∫ x in a..b, sin x ^ 2 * cos x ^ 2 = (b - a) / 8 - (sin (4 * b) - sin (4 * a)) / 32 := begin convert integral_sin_pow_even_mul_cos_pow_even 1 1 using 1, have h1 : ∀ c : ℝ, (1 - c) / 2 * ((1 + c) / 2) = (1 - c ^ 2) / 4 := λ c, by ring, have h2 : continuous (λ x, cos (2 * x) ^ 2) := by continuity, have h3 : ∀ x, cos x * sin x = sin (2 * x) / 2, { intro, rw sin_two_mul, ring }, have h4 : ∀ d : ℝ, 2 * (2 * d) = 4 * d := λ d, by ring, simp [h1, h2.interval_integrable, integral_comp_mul_left (λ x, cos x ^ 2), h3, h4], ring, end
c066d6e62485bcb36551f2447371d55b50772c75
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/model_theory/language_map.lean
8bbbe065e63ab3721d353e401b03c69dd9eda682
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
17,683
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 ` ∘ `: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 (on_function ϕ : L.functions n → L'.functions n)) (on_relation {n} : function.injective (on_relation ϕ : L.relations n → L'.relations n)) /-- 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 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
65959d911cc9e3891aa2e83635eed0d59d066ff3
63abd62053d479eae5abf4951554e1064a4c45b4
/src/category_theory/limits/over.lean
b76aeba002c5fac165c13665b1f1ff9870053529
[ "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,481
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Reid Barton, Bhavik Mehta -/ import category_theory.over import category_theory.limits.preserves.basic noncomputable theory universes v u -- declare the `v`'s first; see `category_theory.category` for an explanation open category_theory category_theory.limits variables {J : Type v} [small_category J] variables {C : Type u} [category.{v} C] variable {X : C} namespace category_theory.functor /-- We can interpret a functor `F` into the category of arrows with codomain `X` as a cocone over the diagram given by the domains of the arrows in the image of `F` such that the apex of the cocone is `X`. -/ @[simps] def to_cocone (F : J ⥤ over X) : cocone (F ⋙ over.forget X) := { X := X, ι := { app := λ j, (F.obj j).hom } } /-- We can interpret a functor `F` into the category of arrows with domain `X` as a cone over the diagram given by the codomains of the arrows in the image of `F` such that the apex of the cone is `X`. -/ @[simps] def to_cone (F : J ⥤ under X) : cone (F ⋙ under.forget X) := { X := X, π := { app := λ j, (F.obj j).hom } } end category_theory.functor namespace category_theory.over /-- A colimit of `F ⋙ over.forget` induces a cocone over `F`. This is an implementation detail, use the `has_colimit` instance provided below. -/ @[simps] def colimit (F : J ⥤ over X) [has_colimit (F ⋙ forget X)] : cocone F := { X := mk $ colimit.desc (F ⋙ forget X) F.to_cocone, ι := { app := λ j, hom_mk $ colimit.ι (F ⋙ forget X) j, naturality' := begin intros j j' f, have := colimit.w (F ⋙ forget X) f, tidy end } } /-- The cocone constructed from the colimit of `F ⋙ forget X` is a colimit. This is an implementation detail, use the `has_colimit` instance provided below. -/ def forget_colimit_is_colimit (F : J ⥤ over X) [has_colimit (F ⋙ forget X)] : is_colimit ((forget X).map_cocone (colimit F)) := is_colimit.of_iso_colimit (colimit.is_colimit (F ⋙ forget X)) (cocones.ext (iso.refl _) (by tidy)) instance : reflects_colimits (forget X) := { reflects_colimits_of_shape := λ J 𝒥, { reflects_colimit := λ F, by constructor; exactI λ t ht, { desc := λ s, hom_mk (ht.desc ((forget X).map_cocone s)) begin apply ht.hom_ext, intro j, rw [←category.assoc, ht.fac], transitivity (F.obj j).hom, exact w (s.ι.app j), -- TODO: How to write (s.ι.app j).w? exact (w (t.ι.app j)).symm, end, fac' := begin intros s j, ext, exact ht.fac ((forget X).map_cocone s) j -- TODO: Ask Simon about multiple ext lemmas for defeq types (comma_morphism & over.category.hom) end, uniq' := begin intros s m w, ext1 j, exact ht.uniq ((forget X).map_cocone s) m.left (λ j, congr_arg comma_morphism.left (w j)) end } } } instance has_colimit {F : J ⥤ over X} [has_colimit (F ⋙ forget X)] : has_colimit F := has_colimit.mk { cocone := colimit F, is_colimit := reflects_colimit.reflects (forget_colimit_is_colimit F) } instance has_colimits_of_shape [has_colimits_of_shape J C] : has_colimits_of_shape J (over X) := { has_colimit := λ F, by apply_instance } instance has_colimits [has_colimits C] : has_colimits (over X) := { has_colimits_of_shape := λ J 𝒥, by resetI; apply_instance } instance forget_preserves_colimit {X : C} {F : J ⥤ over X} [has_colimit (F ⋙ forget X)] : preserves_colimit F (forget X) := preserves_colimit_of_preserves_colimit_cocone (reflects_colimit.reflects (forget_colimit_is_colimit F)) (forget_colimit_is_colimit F) instance forget_preserves_colimits_of_shape [has_colimits_of_shape J C] {X : C} : preserves_colimits_of_shape J (forget X) := { preserves_colimit := λ F, by apply_instance } instance forget_preserves_colimits [has_colimits C] {X : C} : preserves_colimits (forget X) := { preserves_colimits_of_shape := λ J 𝒥, by apply_instance } end category_theory.over namespace category_theory.under /-- A limit of `F ⋙ under.forget` induces a cone over `F`. This is an implementation detail, use the `has_limit` instance provided below. -/ @[simps] def limit (F : J ⥤ under X) [has_limit (F ⋙ forget X)] : cone F := { X := mk $ limit.lift (F ⋙ forget X) F.to_cone, π := { app := λ j, hom_mk $ limit.π (F ⋙ forget X) j, naturality' := begin intros j j' f, have := (limit.w (F ⋙ forget X) f).symm, tidy end } } /-- The cone constructed from the limit of `F ⋙ forget X` is a limit. This is an implementation detail, use the `has_limit` instance provided below. -/ def forget_limit_is_limit (F : J ⥤ under X) [has_limit (F ⋙ forget X)] : is_limit ((forget X).map_cone (limit F)) := is_limit.of_iso_limit (limit.is_limit (F ⋙ forget X)) (cones.ext (iso.refl _) (by tidy)) instance : reflects_limits (forget X) := { reflects_limits_of_shape := λ J 𝒥, { reflects_limit := λ F, by constructor; exactI λ t ht, { lift := λ s, hom_mk (ht.lift ((forget X).map_cone s)) begin apply ht.hom_ext, intro j, rw [category.assoc, ht.fac], transitivity (F.obj j).hom, exact w (s.π.app j), exact (w (t.π.app j)).symm, end, fac' := begin intros s j, ext, exact ht.fac ((forget X).map_cone s) j end, uniq' := begin intros s m w, ext1 j, exact ht.uniq ((forget X).map_cone s) m.right (λ j, congr_arg comma_morphism.right (w j)) end } } } instance has_limit {F : J ⥤ under X} [has_limit (F ⋙ forget X)] : has_limit F := has_limit.mk { cone := limit F, is_limit := reflects_limit.reflects (forget_limit_is_limit F) } instance has_limits_of_shape [has_limits_of_shape J C] : has_limits_of_shape J (under X) := { has_limit := λ F, by apply_instance } instance has_limits [has_limits C] : has_limits (under X) := { has_limits_of_shape := λ J 𝒥, by resetI; apply_instance } instance forget_preserves_limits [has_limits C] {X : C} : preserves_limits (forget X) := { preserves_limits_of_shape := λ J 𝒥, { preserves_limit := λ F, by exactI preserves_limit_of_preserves_limit_cone (reflects_limit.reflects (forget_limit_is_limit F)) (forget_limit_is_limit F) } } end category_theory.under
e2eb4833db62ee6ea227af2435d100bf21db20dc
bb31430994044506fa42fd667e2d556327e18dfe
/src/analysis/special_functions/trigonometric/deriv.lean
30bf58d9099024ed5b74e651a789a415f3afda8f
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
37,990
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Benjamin Davidson -/ import order.monotone.odd import analysis.special_functions.exp_deriv import analysis.special_functions.trigonometric.basic import data.set.intervals.monotone /-! # Differentiability of trigonometric functions ## Main statements The differentiability of the usual trigonometric functions is proved, and their derivatives are computed. ## Tags sin, cos, tan, angle -/ noncomputable theory open_locale classical topological_space filter open set filter namespace complex /-- The complex sine function is everywhere strictly differentiable, with the derivative `cos x`. -/ lemma has_strict_deriv_at_sin (x : ℂ) : has_strict_deriv_at sin (cos x) x := begin simp only [cos, div_eq_mul_inv], convert ((((has_strict_deriv_at_id x).neg.mul_const I).cexp.sub ((has_strict_deriv_at_id x).mul_const I).cexp).mul_const I).mul_const (2:ℂ)⁻¹, simp only [function.comp, id], rw [sub_mul, mul_assoc, mul_assoc, I_mul_I, neg_one_mul, neg_neg, mul_one, one_mul, mul_assoc, I_mul_I, mul_neg_one, sub_neg_eq_add, add_comm] end /-- The complex sine function is everywhere differentiable, with the derivative `cos x`. -/ lemma has_deriv_at_sin (x : ℂ) : has_deriv_at sin (cos x) x := (has_strict_deriv_at_sin x).has_deriv_at lemma cont_diff_sin {n} : cont_diff ℂ n sin := (((cont_diff_neg.mul cont_diff_const).cexp.sub (cont_diff_id.mul cont_diff_const).cexp).mul cont_diff_const).div_const lemma differentiable_sin : differentiable ℂ sin := λx, (has_deriv_at_sin x).differentiable_at lemma differentiable_at_sin {x : ℂ} : differentiable_at ℂ sin x := differentiable_sin x @[simp] lemma deriv_sin : deriv sin = cos := funext $ λ x, (has_deriv_at_sin x).deriv /-- The complex cosine function is everywhere strictly differentiable, with the derivative `-sin x`. -/ lemma has_strict_deriv_at_cos (x : ℂ) : has_strict_deriv_at cos (-sin x) x := begin simp only [sin, div_eq_mul_inv, neg_mul_eq_neg_mul], convert (((has_strict_deriv_at_id x).mul_const I).cexp.add ((has_strict_deriv_at_id x).neg.mul_const I).cexp).mul_const (2:ℂ)⁻¹, simp only [function.comp, id], ring end /-- The complex cosine function is everywhere differentiable, with the derivative `-sin x`. -/ lemma has_deriv_at_cos (x : ℂ) : has_deriv_at cos (-sin x) x := (has_strict_deriv_at_cos x).has_deriv_at lemma cont_diff_cos {n} : cont_diff ℂ n cos := ((cont_diff_id.mul cont_diff_const).cexp.add (cont_diff_neg.mul cont_diff_const).cexp).div_const lemma differentiable_cos : differentiable ℂ cos := λx, (has_deriv_at_cos x).differentiable_at lemma differentiable_at_cos {x : ℂ} : differentiable_at ℂ cos x := differentiable_cos x lemma deriv_cos {x : ℂ} : deriv cos x = -sin x := (has_deriv_at_cos x).deriv @[simp] lemma deriv_cos' : deriv cos = (λ x, -sin x) := funext $ λ x, deriv_cos /-- The complex hyperbolic sine function is everywhere strictly differentiable, with the derivative `cosh x`. -/ lemma has_strict_deriv_at_sinh (x : ℂ) : has_strict_deriv_at sinh (cosh x) x := begin simp only [cosh, div_eq_mul_inv], convert ((has_strict_deriv_at_exp x).sub (has_strict_deriv_at_id x).neg.cexp).mul_const (2:ℂ)⁻¹, rw [id, mul_neg_one, sub_eq_add_neg, neg_neg] end /-- The complex hyperbolic sine function is everywhere differentiable, with the derivative `cosh x`. -/ lemma has_deriv_at_sinh (x : ℂ) : has_deriv_at sinh (cosh x) x := (has_strict_deriv_at_sinh x).has_deriv_at lemma cont_diff_sinh {n} : cont_diff ℂ n sinh := (cont_diff_exp.sub cont_diff_neg.cexp).div_const lemma differentiable_sinh : differentiable ℂ sinh := λx, (has_deriv_at_sinh x).differentiable_at lemma differentiable_at_sinh {x : ℂ} : differentiable_at ℂ sinh x := differentiable_sinh x @[simp] lemma deriv_sinh : deriv sinh = cosh := funext $ λ x, (has_deriv_at_sinh x).deriv /-- The complex hyperbolic cosine function is everywhere strictly differentiable, with the derivative `sinh x`. -/ lemma has_strict_deriv_at_cosh (x : ℂ) : has_strict_deriv_at cosh (sinh x) x := begin simp only [sinh, div_eq_mul_inv], convert ((has_strict_deriv_at_exp x).add (has_strict_deriv_at_id x).neg.cexp).mul_const (2:ℂ)⁻¹, rw [id, mul_neg_one, sub_eq_add_neg] end /-- The complex hyperbolic cosine function is everywhere differentiable, with the derivative `sinh x`. -/ lemma has_deriv_at_cosh (x : ℂ) : has_deriv_at cosh (sinh x) x := (has_strict_deriv_at_cosh x).has_deriv_at lemma cont_diff_cosh {n} : cont_diff ℂ n cosh := (cont_diff_exp.add cont_diff_neg.cexp).div_const lemma differentiable_cosh : differentiable ℂ cosh := λx, (has_deriv_at_cosh x).differentiable_at lemma differentiable_at_cosh {x : ℂ} : differentiable_at ℂ cosh x := differentiable_cosh x @[simp] lemma deriv_cosh : deriv cosh = sinh := funext $ λ x, (has_deriv_at_cosh x).deriv end complex section /-! ### Simp lemmas for derivatives of `λ x, complex.cos (f x)` etc., `f : ℂ → ℂ` -/ variables {f : ℂ → ℂ} {f' x : ℂ} {s : set ℂ} /-! #### `complex.cos` -/ lemma has_strict_deriv_at.ccos (hf : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ x, complex.cos (f x)) (- complex.sin (f x) * f') x := (complex.has_strict_deriv_at_cos (f x)).comp x hf lemma has_deriv_at.ccos (hf : has_deriv_at f f' x) : has_deriv_at (λ x, complex.cos (f x)) (- complex.sin (f x) * f') x := (complex.has_deriv_at_cos (f x)).comp x hf lemma has_deriv_within_at.ccos (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, complex.cos (f x)) (- complex.sin (f x) * f') s x := (complex.has_deriv_at_cos (f x)).comp_has_deriv_within_at x hf lemma deriv_within_ccos (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : deriv_within (λx, complex.cos (f x)) s x = - complex.sin (f x) * (deriv_within f s x) := hf.has_deriv_within_at.ccos.deriv_within hxs @[simp] lemma deriv_ccos (hc : differentiable_at ℂ f x) : deriv (λx, complex.cos (f x)) x = - complex.sin (f x) * (deriv f x) := hc.has_deriv_at.ccos.deriv /-! #### `complex.sin` -/ lemma has_strict_deriv_at.csin (hf : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ x, complex.sin (f x)) (complex.cos (f x) * f') x := (complex.has_strict_deriv_at_sin (f x)).comp x hf lemma has_deriv_at.csin (hf : has_deriv_at f f' x) : has_deriv_at (λ x, complex.sin (f x)) (complex.cos (f x) * f') x := (complex.has_deriv_at_sin (f x)).comp x hf lemma has_deriv_within_at.csin (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, complex.sin (f x)) (complex.cos (f x) * f') s x := (complex.has_deriv_at_sin (f x)).comp_has_deriv_within_at x hf lemma deriv_within_csin (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : deriv_within (λx, complex.sin (f x)) s x = complex.cos (f x) * (deriv_within f s x) := hf.has_deriv_within_at.csin.deriv_within hxs @[simp] lemma deriv_csin (hc : differentiable_at ℂ f x) : deriv (λx, complex.sin (f x)) x = complex.cos (f x) * (deriv f x) := hc.has_deriv_at.csin.deriv /-! #### `complex.cosh` -/ lemma has_strict_deriv_at.ccosh (hf : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ x, complex.cosh (f x)) (complex.sinh (f x) * f') x := (complex.has_strict_deriv_at_cosh (f x)).comp x hf lemma has_deriv_at.ccosh (hf : has_deriv_at f f' x) : has_deriv_at (λ x, complex.cosh (f x)) (complex.sinh (f x) * f') x := (complex.has_deriv_at_cosh (f x)).comp x hf lemma has_deriv_within_at.ccosh (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, complex.cosh (f x)) (complex.sinh (f x) * f') s x := (complex.has_deriv_at_cosh (f x)).comp_has_deriv_within_at x hf lemma deriv_within_ccosh (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : deriv_within (λx, complex.cosh (f x)) s x = complex.sinh (f x) * (deriv_within f s x) := hf.has_deriv_within_at.ccosh.deriv_within hxs @[simp] lemma deriv_ccosh (hc : differentiable_at ℂ f x) : deriv (λx, complex.cosh (f x)) x = complex.sinh (f x) * (deriv f x) := hc.has_deriv_at.ccosh.deriv /-! #### `complex.sinh` -/ lemma has_strict_deriv_at.csinh (hf : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ x, complex.sinh (f x)) (complex.cosh (f x) * f') x := (complex.has_strict_deriv_at_sinh (f x)).comp x hf lemma has_deriv_at.csinh (hf : has_deriv_at f f' x) : has_deriv_at (λ x, complex.sinh (f x)) (complex.cosh (f x) * f') x := (complex.has_deriv_at_sinh (f x)).comp x hf lemma has_deriv_within_at.csinh (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, complex.sinh (f x)) (complex.cosh (f x) * f') s x := (complex.has_deriv_at_sinh (f x)).comp_has_deriv_within_at x hf lemma deriv_within_csinh (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : deriv_within (λx, complex.sinh (f x)) s x = complex.cosh (f x) * (deriv_within f s x) := hf.has_deriv_within_at.csinh.deriv_within hxs @[simp] lemma deriv_csinh (hc : differentiable_at ℂ f x) : deriv (λx, complex.sinh (f x)) x = complex.cosh (f x) * (deriv f x) := hc.has_deriv_at.csinh.deriv end section /-! ### Simp lemmas for derivatives of `λ x, complex.cos (f x)` etc., `f : E → ℂ` -/ variables {E : Type*} [normed_add_comm_group E] [normed_space ℂ E] {f : E → ℂ} {f' : E →L[ℂ] ℂ} {x : E} {s : set E} /-! #### `complex.cos` -/ lemma has_strict_fderiv_at.ccos (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, complex.cos (f x)) (- complex.sin (f x) • f') x := (complex.has_strict_deriv_at_cos (f x)).comp_has_strict_fderiv_at x hf lemma has_fderiv_at.ccos (hf : has_fderiv_at f f' x) : has_fderiv_at (λ x, complex.cos (f x)) (- complex.sin (f x) • f') x := (complex.has_deriv_at_cos (f x)).comp_has_fderiv_at x hf lemma has_fderiv_within_at.ccos (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, complex.cos (f x)) (- complex.sin (f x) • f') s x := (complex.has_deriv_at_cos (f x)).comp_has_fderiv_within_at x hf lemma differentiable_within_at.ccos (hf : differentiable_within_at ℂ f s x) : differentiable_within_at ℂ (λ x, complex.cos (f x)) s x := hf.has_fderiv_within_at.ccos.differentiable_within_at @[simp] lemma differentiable_at.ccos (hc : differentiable_at ℂ f x) : differentiable_at ℂ (λx, complex.cos (f x)) x := hc.has_fderiv_at.ccos.differentiable_at lemma differentiable_on.ccos (hc : differentiable_on ℂ f s) : differentiable_on ℂ (λx, complex.cos (f x)) s := λx h, (hc x h).ccos @[simp] lemma differentiable.ccos (hc : differentiable ℂ f) : differentiable ℂ (λx, complex.cos (f x)) := λx, (hc x).ccos lemma fderiv_within_ccos (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : fderiv_within ℂ (λx, complex.cos (f x)) s x = - complex.sin (f x) • (fderiv_within ℂ f s x) := hf.has_fderiv_within_at.ccos.fderiv_within hxs @[simp] lemma fderiv_ccos (hc : differentiable_at ℂ f x) : fderiv ℂ (λx, complex.cos (f x)) x = - complex.sin (f x) • (fderiv ℂ f x) := hc.has_fderiv_at.ccos.fderiv lemma cont_diff.ccos {n} (h : cont_diff ℂ n f) : cont_diff ℂ n (λ x, complex.cos (f x)) := complex.cont_diff_cos.comp h lemma cont_diff_at.ccos {n} (hf : cont_diff_at ℂ n f x) : cont_diff_at ℂ n (λ x, complex.cos (f x)) x := complex.cont_diff_cos.cont_diff_at.comp x hf lemma cont_diff_on.ccos {n} (hf : cont_diff_on ℂ n f s) : cont_diff_on ℂ n (λ x, complex.cos (f x)) s := complex.cont_diff_cos.comp_cont_diff_on hf lemma cont_diff_within_at.ccos {n} (hf : cont_diff_within_at ℂ n f s x) : cont_diff_within_at ℂ n (λ x, complex.cos (f x)) s x := complex.cont_diff_cos.cont_diff_at.comp_cont_diff_within_at x hf /-! #### `complex.sin` -/ lemma has_strict_fderiv_at.csin (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, complex.sin (f x)) (complex.cos (f x) • f') x := (complex.has_strict_deriv_at_sin (f x)).comp_has_strict_fderiv_at x hf lemma has_fderiv_at.csin (hf : has_fderiv_at f f' x) : has_fderiv_at (λ x, complex.sin (f x)) (complex.cos (f x) • f') x := (complex.has_deriv_at_sin (f x)).comp_has_fderiv_at x hf lemma has_fderiv_within_at.csin (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, complex.sin (f x)) (complex.cos (f x) • f') s x := (complex.has_deriv_at_sin (f x)).comp_has_fderiv_within_at x hf lemma differentiable_within_at.csin (hf : differentiable_within_at ℂ f s x) : differentiable_within_at ℂ (λ x, complex.sin (f x)) s x := hf.has_fderiv_within_at.csin.differentiable_within_at @[simp] lemma differentiable_at.csin (hc : differentiable_at ℂ f x) : differentiable_at ℂ (λx, complex.sin (f x)) x := hc.has_fderiv_at.csin.differentiable_at lemma differentiable_on.csin (hc : differentiable_on ℂ f s) : differentiable_on ℂ (λx, complex.sin (f x)) s := λx h, (hc x h).csin @[simp] lemma differentiable.csin (hc : differentiable ℂ f) : differentiable ℂ (λx, complex.sin (f x)) := λx, (hc x).csin lemma fderiv_within_csin (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : fderiv_within ℂ (λx, complex.sin (f x)) s x = complex.cos (f x) • (fderiv_within ℂ f s x) := hf.has_fderiv_within_at.csin.fderiv_within hxs @[simp] lemma fderiv_csin (hc : differentiable_at ℂ f x) : fderiv ℂ (λx, complex.sin (f x)) x = complex.cos (f x) • (fderiv ℂ f x) := hc.has_fderiv_at.csin.fderiv lemma cont_diff.csin {n} (h : cont_diff ℂ n f) : cont_diff ℂ n (λ x, complex.sin (f x)) := complex.cont_diff_sin.comp h lemma cont_diff_at.csin {n} (hf : cont_diff_at ℂ n f x) : cont_diff_at ℂ n (λ x, complex.sin (f x)) x := complex.cont_diff_sin.cont_diff_at.comp x hf lemma cont_diff_on.csin {n} (hf : cont_diff_on ℂ n f s) : cont_diff_on ℂ n (λ x, complex.sin (f x)) s := complex.cont_diff_sin.comp_cont_diff_on hf lemma cont_diff_within_at.csin {n} (hf : cont_diff_within_at ℂ n f s x) : cont_diff_within_at ℂ n (λ x, complex.sin (f x)) s x := complex.cont_diff_sin.cont_diff_at.comp_cont_diff_within_at x hf /-! #### `complex.cosh` -/ lemma has_strict_fderiv_at.ccosh (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, complex.cosh (f x)) (complex.sinh (f x) • f') x := (complex.has_strict_deriv_at_cosh (f x)).comp_has_strict_fderiv_at x hf lemma has_fderiv_at.ccosh (hf : has_fderiv_at f f' x) : has_fderiv_at (λ x, complex.cosh (f x)) (complex.sinh (f x) • f') x := (complex.has_deriv_at_cosh (f x)).comp_has_fderiv_at x hf lemma has_fderiv_within_at.ccosh (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, complex.cosh (f x)) (complex.sinh (f x) • f') s x := (complex.has_deriv_at_cosh (f x)).comp_has_fderiv_within_at x hf lemma differentiable_within_at.ccosh (hf : differentiable_within_at ℂ f s x) : differentiable_within_at ℂ (λ x, complex.cosh (f x)) s x := hf.has_fderiv_within_at.ccosh.differentiable_within_at @[simp] lemma differentiable_at.ccosh (hc : differentiable_at ℂ f x) : differentiable_at ℂ (λx, complex.cosh (f x)) x := hc.has_fderiv_at.ccosh.differentiable_at lemma differentiable_on.ccosh (hc : differentiable_on ℂ f s) : differentiable_on ℂ (λx, complex.cosh (f x)) s := λx h, (hc x h).ccosh @[simp] lemma differentiable.ccosh (hc : differentiable ℂ f) : differentiable ℂ (λx, complex.cosh (f x)) := λx, (hc x).ccosh lemma fderiv_within_ccosh (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : fderiv_within ℂ (λx, complex.cosh (f x)) s x = complex.sinh (f x) • (fderiv_within ℂ f s x) := hf.has_fderiv_within_at.ccosh.fderiv_within hxs @[simp] lemma fderiv_ccosh (hc : differentiable_at ℂ f x) : fderiv ℂ (λx, complex.cosh (f x)) x = complex.sinh (f x) • (fderiv ℂ f x) := hc.has_fderiv_at.ccosh.fderiv lemma cont_diff.ccosh {n} (h : cont_diff ℂ n f) : cont_diff ℂ n (λ x, complex.cosh (f x)) := complex.cont_diff_cosh.comp h lemma cont_diff_at.ccosh {n} (hf : cont_diff_at ℂ n f x) : cont_diff_at ℂ n (λ x, complex.cosh (f x)) x := complex.cont_diff_cosh.cont_diff_at.comp x hf lemma cont_diff_on.ccosh {n} (hf : cont_diff_on ℂ n f s) : cont_diff_on ℂ n (λ x, complex.cosh (f x)) s := complex.cont_diff_cosh.comp_cont_diff_on hf lemma cont_diff_within_at.ccosh {n} (hf : cont_diff_within_at ℂ n f s x) : cont_diff_within_at ℂ n (λ x, complex.cosh (f x)) s x := complex.cont_diff_cosh.cont_diff_at.comp_cont_diff_within_at x hf /-! #### `complex.sinh` -/ lemma has_strict_fderiv_at.csinh (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, complex.sinh (f x)) (complex.cosh (f x) • f') x := (complex.has_strict_deriv_at_sinh (f x)).comp_has_strict_fderiv_at x hf lemma has_fderiv_at.csinh (hf : has_fderiv_at f f' x) : has_fderiv_at (λ x, complex.sinh (f x)) (complex.cosh (f x) • f') x := (complex.has_deriv_at_sinh (f x)).comp_has_fderiv_at x hf lemma has_fderiv_within_at.csinh (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, complex.sinh (f x)) (complex.cosh (f x) • f') s x := (complex.has_deriv_at_sinh (f x)).comp_has_fderiv_within_at x hf lemma differentiable_within_at.csinh (hf : differentiable_within_at ℂ f s x) : differentiable_within_at ℂ (λ x, complex.sinh (f x)) s x := hf.has_fderiv_within_at.csinh.differentiable_within_at @[simp] lemma differentiable_at.csinh (hc : differentiable_at ℂ f x) : differentiable_at ℂ (λx, complex.sinh (f x)) x := hc.has_fderiv_at.csinh.differentiable_at lemma differentiable_on.csinh (hc : differentiable_on ℂ f s) : differentiable_on ℂ (λx, complex.sinh (f x)) s := λx h, (hc x h).csinh @[simp] lemma differentiable.csinh (hc : differentiable ℂ f) : differentiable ℂ (λx, complex.sinh (f x)) := λx, (hc x).csinh lemma fderiv_within_csinh (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : fderiv_within ℂ (λx, complex.sinh (f x)) s x = complex.cosh (f x) • (fderiv_within ℂ f s x) := hf.has_fderiv_within_at.csinh.fderiv_within hxs @[simp] lemma fderiv_csinh (hc : differentiable_at ℂ f x) : fderiv ℂ (λx, complex.sinh (f x)) x = complex.cosh (f x) • (fderiv ℂ f x) := hc.has_fderiv_at.csinh.fderiv lemma cont_diff.csinh {n} (h : cont_diff ℂ n f) : cont_diff ℂ n (λ x, complex.sinh (f x)) := complex.cont_diff_sinh.comp h lemma cont_diff_at.csinh {n} (hf : cont_diff_at ℂ n f x) : cont_diff_at ℂ n (λ x, complex.sinh (f x)) x := complex.cont_diff_sinh.cont_diff_at.comp x hf lemma cont_diff_on.csinh {n} (hf : cont_diff_on ℂ n f s) : cont_diff_on ℂ n (λ x, complex.sinh (f x)) s := complex.cont_diff_sinh.comp_cont_diff_on hf lemma cont_diff_within_at.csinh {n} (hf : cont_diff_within_at ℂ n f s x) : cont_diff_within_at ℂ n (λ x, complex.sinh (f x)) s x := complex.cont_diff_sinh.cont_diff_at.comp_cont_diff_within_at x hf end namespace real variables {x y z : ℝ} lemma has_strict_deriv_at_sin (x : ℝ) : has_strict_deriv_at sin (cos x) x := (complex.has_strict_deriv_at_sin x).real_of_complex lemma has_deriv_at_sin (x : ℝ) : has_deriv_at sin (cos x) x := (has_strict_deriv_at_sin x).has_deriv_at lemma cont_diff_sin {n} : cont_diff ℝ n sin := complex.cont_diff_sin.real_of_complex lemma differentiable_sin : differentiable ℝ sin := λx, (has_deriv_at_sin x).differentiable_at lemma differentiable_at_sin : differentiable_at ℝ sin x := differentiable_sin x @[simp] lemma deriv_sin : deriv sin = cos := funext $ λ x, (has_deriv_at_sin x).deriv lemma has_strict_deriv_at_cos (x : ℝ) : has_strict_deriv_at cos (-sin x) x := (complex.has_strict_deriv_at_cos x).real_of_complex lemma has_deriv_at_cos (x : ℝ) : has_deriv_at cos (-sin x) x := (complex.has_deriv_at_cos x).real_of_complex lemma cont_diff_cos {n} : cont_diff ℝ n cos := complex.cont_diff_cos.real_of_complex lemma differentiable_cos : differentiable ℝ cos := λx, (has_deriv_at_cos x).differentiable_at lemma differentiable_at_cos : differentiable_at ℝ cos x := differentiable_cos x lemma deriv_cos : deriv cos x = - sin x := (has_deriv_at_cos x).deriv @[simp] lemma deriv_cos' : deriv cos = (λ x, - sin x) := funext $ λ _, deriv_cos lemma has_strict_deriv_at_sinh (x : ℝ) : has_strict_deriv_at sinh (cosh x) x := (complex.has_strict_deriv_at_sinh x).real_of_complex lemma has_deriv_at_sinh (x : ℝ) : has_deriv_at sinh (cosh x) x := (complex.has_deriv_at_sinh x).real_of_complex lemma cont_diff_sinh {n} : cont_diff ℝ n sinh := complex.cont_diff_sinh.real_of_complex lemma differentiable_sinh : differentiable ℝ sinh := λx, (has_deriv_at_sinh x).differentiable_at lemma differentiable_at_sinh : differentiable_at ℝ sinh x := differentiable_sinh x @[simp] lemma deriv_sinh : deriv sinh = cosh := funext $ λ x, (has_deriv_at_sinh x).deriv lemma has_strict_deriv_at_cosh (x : ℝ) : has_strict_deriv_at cosh (sinh x) x := (complex.has_strict_deriv_at_cosh x).real_of_complex lemma has_deriv_at_cosh (x : ℝ) : has_deriv_at cosh (sinh x) x := (complex.has_deriv_at_cosh x).real_of_complex lemma cont_diff_cosh {n} : cont_diff ℝ n cosh := complex.cont_diff_cosh.real_of_complex lemma differentiable_cosh : differentiable ℝ cosh := λx, (has_deriv_at_cosh x).differentiable_at lemma differentiable_at_cosh : differentiable_at ℝ cosh x := differentiable_cosh x @[simp] lemma deriv_cosh : deriv cosh = sinh := funext $ λ x, (has_deriv_at_cosh x).deriv /-- `sinh` is strictly monotone. -/ lemma sinh_strict_mono : strict_mono sinh := strict_mono_of_deriv_pos $ by { rw real.deriv_sinh, exact cosh_pos } /-- `sinh` is injective, `∀ a b, sinh a = sinh b → a = b`. -/ lemma sinh_injective : function.injective sinh := sinh_strict_mono.injective @[simp] lemma sinh_inj : sinh x = sinh y ↔ x = y := sinh_injective.eq_iff @[simp] lemma sinh_le_sinh : sinh x ≤ sinh y ↔ x ≤ y := sinh_strict_mono.le_iff_le @[simp] lemma sinh_lt_sinh : sinh x < sinh y ↔ x < y := sinh_strict_mono.lt_iff_lt @[simp] lemma sinh_pos_iff : 0 < sinh x ↔ 0 < x := by simpa only [sinh_zero] using @sinh_lt_sinh 0 x @[simp] lemma sinh_nonpos_iff : sinh x ≤ 0 ↔ x ≤ 0 := by simpa only [sinh_zero] using @sinh_le_sinh x 0 @[simp] lemma sinh_neg_iff : sinh x < 0 ↔ x < 0 := by simpa only [sinh_zero] using @sinh_lt_sinh x 0 @[simp] lemma sinh_nonneg_iff : 0 ≤ sinh x ↔ 0 ≤ x := by simpa only [sinh_zero] using @sinh_le_sinh 0 x lemma abs_sinh (x : ℝ) : |sinh x| = sinh (|x|) := by cases le_total x 0; simp [abs_of_nonneg, abs_of_nonpos, *] lemma cosh_strict_mono_on : strict_mono_on cosh (Ici 0) := (convex_Ici _).strict_mono_on_of_deriv_pos continuous_cosh.continuous_on $ λ x hx, by { rw [interior_Ici, mem_Ioi] at hx, rwa [deriv_cosh, sinh_pos_iff] } @[simp] lemma cosh_le_cosh : cosh x ≤ cosh y ↔ |x| ≤ |y| := cosh_abs x ▸ cosh_abs y ▸ cosh_strict_mono_on.le_iff_le (_root_.abs_nonneg x) (_root_.abs_nonneg y) @[simp] lemma cosh_lt_cosh : cosh x < cosh y ↔ |x| < |y| := lt_iff_lt_of_le_iff_le cosh_le_cosh @[simp] lemma one_le_cosh (x : ℝ) : 1 ≤ cosh x := cosh_zero ▸ cosh_le_cosh.2 (by simp only [_root_.abs_zero, _root_.abs_nonneg]) @[simp] lemma one_lt_cosh : 1 < cosh x ↔ x ≠ 0 := cosh_zero ▸ cosh_lt_cosh.trans (by simp only [_root_.abs_zero, abs_pos]) lemma sinh_sub_id_strict_mono : strict_mono (λ x, sinh x - x) := begin refine strict_mono_of_odd_strict_mono_on_nonneg (λ x, by simp) _, refine (convex_Ici _).strict_mono_on_of_deriv_pos _ (λ x hx, _), { exact (continuous_sinh.sub continuous_id).continuous_on }, { rw [interior_Ici, mem_Ioi] at hx, rw [deriv_sub, deriv_sinh, deriv_id'', sub_pos, one_lt_cosh], exacts [hx.ne', differentiable_at_sinh, differentiable_at_id] } end @[simp] lemma self_le_sinh_iff : x ≤ sinh x ↔ 0 ≤ x := calc x ≤ sinh x ↔ sinh 0 - 0 ≤ sinh x - x : by simp ... ↔ 0 ≤ x : sinh_sub_id_strict_mono.le_iff_le @[simp] lemma sinh_le_self_iff : sinh x ≤ x ↔ x ≤ 0 := calc sinh x ≤ x ↔ sinh x - x ≤ sinh 0 - 0 : by simp ... ↔ x ≤ 0 : sinh_sub_id_strict_mono.le_iff_le @[simp] lemma self_lt_sinh_iff : x < sinh x ↔ 0 < x := lt_iff_lt_of_le_iff_le sinh_le_self_iff @[simp] lemma sinh_lt_self_iff : sinh x < x ↔ x < 0 := lt_iff_lt_of_le_iff_le self_le_sinh_iff end real section /-! ### Simp lemmas for derivatives of `λ x, real.cos (f x)` etc., `f : ℝ → ℝ` -/ variables {f : ℝ → ℝ} {f' x : ℝ} {s : set ℝ} /-! #### `real.cos` -/ lemma has_strict_deriv_at.cos (hf : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ x, real.cos (f x)) (- real.sin (f x) * f') x := (real.has_strict_deriv_at_cos (f x)).comp x hf lemma has_deriv_at.cos (hf : has_deriv_at f f' x) : has_deriv_at (λ x, real.cos (f x)) (- real.sin (f x) * f') x := (real.has_deriv_at_cos (f x)).comp x hf lemma has_deriv_within_at.cos (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, real.cos (f x)) (- real.sin (f x) * f') s x := (real.has_deriv_at_cos (f x)).comp_has_deriv_within_at x hf lemma deriv_within_cos (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, real.cos (f x)) s x = - real.sin (f x) * (deriv_within f s x) := hf.has_deriv_within_at.cos.deriv_within hxs @[simp] lemma deriv_cos (hc : differentiable_at ℝ f x) : deriv (λx, real.cos (f x)) x = - real.sin (f x) * (deriv f x) := hc.has_deriv_at.cos.deriv /-! #### `real.sin` -/ lemma has_strict_deriv_at.sin (hf : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ x, real.sin (f x)) (real.cos (f x) * f') x := (real.has_strict_deriv_at_sin (f x)).comp x hf lemma has_deriv_at.sin (hf : has_deriv_at f f' x) : has_deriv_at (λ x, real.sin (f x)) (real.cos (f x) * f') x := (real.has_deriv_at_sin (f x)).comp x hf lemma has_deriv_within_at.sin (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, real.sin (f x)) (real.cos (f x) * f') s x := (real.has_deriv_at_sin (f x)).comp_has_deriv_within_at x hf lemma deriv_within_sin (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, real.sin (f x)) s x = real.cos (f x) * (deriv_within f s x) := hf.has_deriv_within_at.sin.deriv_within hxs @[simp] lemma deriv_sin (hc : differentiable_at ℝ f x) : deriv (λx, real.sin (f x)) x = real.cos (f x) * (deriv f x) := hc.has_deriv_at.sin.deriv /-! #### `real.cosh` -/ lemma has_strict_deriv_at.cosh (hf : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ x, real.cosh (f x)) (real.sinh (f x) * f') x := (real.has_strict_deriv_at_cosh (f x)).comp x hf lemma has_deriv_at.cosh (hf : has_deriv_at f f' x) : has_deriv_at (λ x, real.cosh (f x)) (real.sinh (f x) * f') x := (real.has_deriv_at_cosh (f x)).comp x hf lemma has_deriv_within_at.cosh (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, real.cosh (f x)) (real.sinh (f x) * f') s x := (real.has_deriv_at_cosh (f x)).comp_has_deriv_within_at x hf lemma deriv_within_cosh (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, real.cosh (f x)) s x = real.sinh (f x) * (deriv_within f s x) := hf.has_deriv_within_at.cosh.deriv_within hxs @[simp] lemma deriv_cosh (hc : differentiable_at ℝ f x) : deriv (λx, real.cosh (f x)) x = real.sinh (f x) * (deriv f x) := hc.has_deriv_at.cosh.deriv /-! #### `real.sinh` -/ lemma has_strict_deriv_at.sinh (hf : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ x, real.sinh (f x)) (real.cosh (f x) * f') x := (real.has_strict_deriv_at_sinh (f x)).comp x hf lemma has_deriv_at.sinh (hf : has_deriv_at f f' x) : has_deriv_at (λ x, real.sinh (f x)) (real.cosh (f x) * f') x := (real.has_deriv_at_sinh (f x)).comp x hf lemma has_deriv_within_at.sinh (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, real.sinh (f x)) (real.cosh (f x) * f') s x := (real.has_deriv_at_sinh (f x)).comp_has_deriv_within_at x hf lemma deriv_within_sinh (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, real.sinh (f x)) s x = real.cosh (f x) * (deriv_within f s x) := hf.has_deriv_within_at.sinh.deriv_within hxs @[simp] lemma deriv_sinh (hc : differentiable_at ℝ f x) : deriv (λx, real.sinh (f x)) x = real.cosh (f x) * (deriv f x) := hc.has_deriv_at.sinh.deriv end section /-! ### Simp lemmas for derivatives of `λ x, real.cos (f x)` etc., `f : E → ℝ` -/ variables {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] {f : E → ℝ} {f' : E →L[ℝ] ℝ} {x : E} {s : set E} /-! #### `real.cos` -/ lemma has_strict_fderiv_at.cos (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, real.cos (f x)) (- real.sin (f x) • f') x := (real.has_strict_deriv_at_cos (f x)).comp_has_strict_fderiv_at x hf lemma has_fderiv_at.cos (hf : has_fderiv_at f f' x) : has_fderiv_at (λ x, real.cos (f x)) (- real.sin (f x) • f') x := (real.has_deriv_at_cos (f x)).comp_has_fderiv_at x hf lemma has_fderiv_within_at.cos (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, real.cos (f x)) (- real.sin (f x) • f') s x := (real.has_deriv_at_cos (f x)).comp_has_fderiv_within_at x hf lemma differentiable_within_at.cos (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (λ x, real.cos (f x)) s x := hf.has_fderiv_within_at.cos.differentiable_within_at @[simp] lemma differentiable_at.cos (hc : differentiable_at ℝ f x) : differentiable_at ℝ (λx, real.cos (f x)) x := hc.has_fderiv_at.cos.differentiable_at lemma differentiable_on.cos (hc : differentiable_on ℝ f s) : differentiable_on ℝ (λx, real.cos (f x)) s := λx h, (hc x h).cos @[simp] lemma differentiable.cos (hc : differentiable ℝ f) : differentiable ℝ (λx, real.cos (f x)) := λx, (hc x).cos lemma fderiv_within_cos (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : fderiv_within ℝ (λx, real.cos (f x)) s x = - real.sin (f x) • (fderiv_within ℝ f s x) := hf.has_fderiv_within_at.cos.fderiv_within hxs @[simp] lemma fderiv_cos (hc : differentiable_at ℝ f x) : fderiv ℝ (λx, real.cos (f x)) x = - real.sin (f x) • (fderiv ℝ f x) := hc.has_fderiv_at.cos.fderiv lemma cont_diff.cos {n} (h : cont_diff ℝ n f) : cont_diff ℝ n (λ x, real.cos (f x)) := real.cont_diff_cos.comp h lemma cont_diff_at.cos {n} (hf : cont_diff_at ℝ n f x) : cont_diff_at ℝ n (λ x, real.cos (f x)) x := real.cont_diff_cos.cont_diff_at.comp x hf lemma cont_diff_on.cos {n} (hf : cont_diff_on ℝ n f s) : cont_diff_on ℝ n (λ x, real.cos (f x)) s := real.cont_diff_cos.comp_cont_diff_on hf lemma cont_diff_within_at.cos {n} (hf : cont_diff_within_at ℝ n f s x) : cont_diff_within_at ℝ n (λ x, real.cos (f x)) s x := real.cont_diff_cos.cont_diff_at.comp_cont_diff_within_at x hf /-! #### `real.sin` -/ lemma has_strict_fderiv_at.sin (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, real.sin (f x)) (real.cos (f x) • f') x := (real.has_strict_deriv_at_sin (f x)).comp_has_strict_fderiv_at x hf lemma has_fderiv_at.sin (hf : has_fderiv_at f f' x) : has_fderiv_at (λ x, real.sin (f x)) (real.cos (f x) • f') x := (real.has_deriv_at_sin (f x)).comp_has_fderiv_at x hf lemma has_fderiv_within_at.sin (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, real.sin (f x)) (real.cos (f x) • f') s x := (real.has_deriv_at_sin (f x)).comp_has_fderiv_within_at x hf lemma differentiable_within_at.sin (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (λ x, real.sin (f x)) s x := hf.has_fderiv_within_at.sin.differentiable_within_at @[simp] lemma differentiable_at.sin (hc : differentiable_at ℝ f x) : differentiable_at ℝ (λx, real.sin (f x)) x := hc.has_fderiv_at.sin.differentiable_at lemma differentiable_on.sin (hc : differentiable_on ℝ f s) : differentiable_on ℝ (λx, real.sin (f x)) s := λx h, (hc x h).sin @[simp] lemma differentiable.sin (hc : differentiable ℝ f) : differentiable ℝ (λx, real.sin (f x)) := λx, (hc x).sin lemma fderiv_within_sin (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : fderiv_within ℝ (λx, real.sin (f x)) s x = real.cos (f x) • (fderiv_within ℝ f s x) := hf.has_fderiv_within_at.sin.fderiv_within hxs @[simp] lemma fderiv_sin (hc : differentiable_at ℝ f x) : fderiv ℝ (λx, real.sin (f x)) x = real.cos (f x) • (fderiv ℝ f x) := hc.has_fderiv_at.sin.fderiv lemma cont_diff.sin {n} (h : cont_diff ℝ n f) : cont_diff ℝ n (λ x, real.sin (f x)) := real.cont_diff_sin.comp h lemma cont_diff_at.sin {n} (hf : cont_diff_at ℝ n f x) : cont_diff_at ℝ n (λ x, real.sin (f x)) x := real.cont_diff_sin.cont_diff_at.comp x hf lemma cont_diff_on.sin {n} (hf : cont_diff_on ℝ n f s) : cont_diff_on ℝ n (λ x, real.sin (f x)) s := real.cont_diff_sin.comp_cont_diff_on hf lemma cont_diff_within_at.sin {n} (hf : cont_diff_within_at ℝ n f s x) : cont_diff_within_at ℝ n (λ x, real.sin (f x)) s x := real.cont_diff_sin.cont_diff_at.comp_cont_diff_within_at x hf /-! #### `real.cosh` -/ lemma has_strict_fderiv_at.cosh (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, real.cosh (f x)) (real.sinh (f x) • f') x := (real.has_strict_deriv_at_cosh (f x)).comp_has_strict_fderiv_at x hf lemma has_fderiv_at.cosh (hf : has_fderiv_at f f' x) : has_fderiv_at (λ x, real.cosh (f x)) (real.sinh (f x) • f') x := (real.has_deriv_at_cosh (f x)).comp_has_fderiv_at x hf lemma has_fderiv_within_at.cosh (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, real.cosh (f x)) (real.sinh (f x) • f') s x := (real.has_deriv_at_cosh (f x)).comp_has_fderiv_within_at x hf lemma differentiable_within_at.cosh (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (λ x, real.cosh (f x)) s x := hf.has_fderiv_within_at.cosh.differentiable_within_at @[simp] lemma differentiable_at.cosh (hc : differentiable_at ℝ f x) : differentiable_at ℝ (λx, real.cosh (f x)) x := hc.has_fderiv_at.cosh.differentiable_at lemma differentiable_on.cosh (hc : differentiable_on ℝ f s) : differentiable_on ℝ (λx, real.cosh (f x)) s := λx h, (hc x h).cosh @[simp] lemma differentiable.cosh (hc : differentiable ℝ f) : differentiable ℝ (λx, real.cosh (f x)) := λx, (hc x).cosh lemma fderiv_within_cosh (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : fderiv_within ℝ (λx, real.cosh (f x)) s x = real.sinh (f x) • (fderiv_within ℝ f s x) := hf.has_fderiv_within_at.cosh.fderiv_within hxs @[simp] lemma fderiv_cosh (hc : differentiable_at ℝ f x) : fderiv ℝ (λx, real.cosh (f x)) x = real.sinh (f x) • (fderiv ℝ f x) := hc.has_fderiv_at.cosh.fderiv lemma cont_diff.cosh {n} (h : cont_diff ℝ n f) : cont_diff ℝ n (λ x, real.cosh (f x)) := real.cont_diff_cosh.comp h lemma cont_diff_at.cosh {n} (hf : cont_diff_at ℝ n f x) : cont_diff_at ℝ n (λ x, real.cosh (f x)) x := real.cont_diff_cosh.cont_diff_at.comp x hf lemma cont_diff_on.cosh {n} (hf : cont_diff_on ℝ n f s) : cont_diff_on ℝ n (λ x, real.cosh (f x)) s := real.cont_diff_cosh.comp_cont_diff_on hf lemma cont_diff_within_at.cosh {n} (hf : cont_diff_within_at ℝ n f s x) : cont_diff_within_at ℝ n (λ x, real.cosh (f x)) s x := real.cont_diff_cosh.cont_diff_at.comp_cont_diff_within_at x hf /-! #### `real.sinh` -/ lemma has_strict_fderiv_at.sinh (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, real.sinh (f x)) (real.cosh (f x) • f') x := (real.has_strict_deriv_at_sinh (f x)).comp_has_strict_fderiv_at x hf lemma has_fderiv_at.sinh (hf : has_fderiv_at f f' x) : has_fderiv_at (λ x, real.sinh (f x)) (real.cosh (f x) • f') x := (real.has_deriv_at_sinh (f x)).comp_has_fderiv_at x hf lemma has_fderiv_within_at.sinh (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, real.sinh (f x)) (real.cosh (f x) • f') s x := (real.has_deriv_at_sinh (f x)).comp_has_fderiv_within_at x hf lemma differentiable_within_at.sinh (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (λ x, real.sinh (f x)) s x := hf.has_fderiv_within_at.sinh.differentiable_within_at @[simp] lemma differentiable_at.sinh (hc : differentiable_at ℝ f x) : differentiable_at ℝ (λx, real.sinh (f x)) x := hc.has_fderiv_at.sinh.differentiable_at lemma differentiable_on.sinh (hc : differentiable_on ℝ f s) : differentiable_on ℝ (λx, real.sinh (f x)) s := λx h, (hc x h).sinh @[simp] lemma differentiable.sinh (hc : differentiable ℝ f) : differentiable ℝ (λx, real.sinh (f x)) := λx, (hc x).sinh lemma fderiv_within_sinh (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : fderiv_within ℝ (λx, real.sinh (f x)) s x = real.cosh (f x) • (fderiv_within ℝ f s x) := hf.has_fderiv_within_at.sinh.fderiv_within hxs @[simp] lemma fderiv_sinh (hc : differentiable_at ℝ f x) : fderiv ℝ (λx, real.sinh (f x)) x = real.cosh (f x) • (fderiv ℝ f x) := hc.has_fderiv_at.sinh.fderiv lemma cont_diff.sinh {n} (h : cont_diff ℝ n f) : cont_diff ℝ n (λ x, real.sinh (f x)) := real.cont_diff_sinh.comp h lemma cont_diff_at.sinh {n} (hf : cont_diff_at ℝ n f x) : cont_diff_at ℝ n (λ x, real.sinh (f x)) x := real.cont_diff_sinh.cont_diff_at.comp x hf lemma cont_diff_on.sinh {n} (hf : cont_diff_on ℝ n f s) : cont_diff_on ℝ n (λ x, real.sinh (f x)) s := real.cont_diff_sinh.comp_cont_diff_on hf lemma cont_diff_within_at.sinh {n} (hf : cont_diff_within_at ℝ n f s x) : cont_diff_within_at ℝ n (λ x, real.sinh (f x)) s x := real.cont_diff_sinh.cont_diff_at.comp_cont_diff_within_at x hf end
dbee4ddd9de7adde39ed67d822b2e4895af50fbe
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/topology/constructions.lean
997ce0128731ea022593bc8f458f5e85bf79b090
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
33,887
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot -/ import topology.maps /-! # Constructions of new topological spaces from old ones This file constructs products, sums, subtypes and quotients of topological spaces and sets up their basic theory, such as criteria for maps into or out of these constructions to be continuous; descriptions of the open sets, neighborhood filters, and generators of these constructions; and their behavior with respect to embeddings and other specific classes of maps. ## Implementation note The constructed topologies are defined using induced and coinduced topologies along with the complete lattice structure on topologies. Their universal properties (for example, a map `X → Y × Z` is continuous if and only if both projections `X → Y`, `X → Z` are) follow easily using order-theoretic descriptions of continuity. With more work we can also extract descriptions of the open sets, neighborhood filters and so on. ## Tags product, sum, disjoint union, subspace, quotient space -/ noncomputable theory open topological_space set filter open_locale classical topological_space filter universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} section constructions instance {p : α → Prop} [t : topological_space α] : topological_space (subtype p) := induced coe t instance {r : α → α → Prop} [t : topological_space α] : topological_space (quot r) := coinduced (quot.mk r) t instance {s : setoid α} [t : topological_space α] : topological_space (quotient s) := coinduced quotient.mk t instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α × β) := induced prod.fst t₁ ⊓ induced prod.snd t₂ instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α ⊕ β) := coinduced sum.inl t₁ ⊔ coinduced sum.inr t₂ instance {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (sigma β) := ⨆a, coinduced (sigma.mk a) (t₂ a) instance Pi.topological_space {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (Πa, β a) := ⨅a, induced (λf, f a) (t₂ a) instance ulift.topological_space [t : topological_space α] : topological_space (ulift.{v u} α) := t.induced ulift.down lemma quotient_dense_of_dense [setoid α] [topological_space α] {s : set α} (H : ∀ x, x ∈ closure s) : closure (quotient.mk '' s) = univ := eq_univ_of_forall $ λ x, begin rw mem_closure_iff, intros U U_op x_in_U, let V := quotient.mk ⁻¹' U, cases quotient.exists_rep x with y y_x, have y_in_V : y ∈ V, by simp only [mem_preimage, y_x, x_in_U], have V_op : is_open V := U_op, obtain ⟨w, w_in_V, w_in_range⟩ : (V ∩ s).nonempty := mem_closure_iff.1 (H y) V V_op y_in_V, exact ⟨_, w_in_V, mem_image_of_mem quotient.mk w_in_range⟩ end instance {p : α → Prop} [topological_space α] [discrete_topology α] : discrete_topology (subtype p) := ⟨bot_unique $ assume s hs, ⟨coe '' s, is_open_discrete _, (set.preimage_image_eq _ subtype.coe_injective)⟩⟩ instance sum.discrete_topology [topological_space α] [topological_space β] [hα : discrete_topology α] [hβ : discrete_topology β] : discrete_topology (α ⊕ β) := ⟨by unfold sum.topological_space; simp [hα.eq_bot, hβ.eq_bot]⟩ instance sigma.discrete_topology {β : α → Type v} [Πa, topological_space (β a)] [h : Πa, discrete_topology (β a)] : discrete_topology (sigma β) := ⟨by { unfold sigma.topological_space, simp [λ a, (h a).eq_bot] }⟩ section topα variable [topological_space α] /- The 𝓝 filter and the subspace topology. -/ theorem mem_nhds_subtype (s : set α) (a : {x // x ∈ s}) (t : set {x // x ∈ s}) : t ∈ 𝓝 a ↔ ∃ u ∈ 𝓝 (a : α), coe ⁻¹' u ⊆ t := mem_nhds_induced coe a t theorem nhds_subtype (s : set α) (a : {x // x ∈ s}) : 𝓝 a = comap coe (𝓝 (a : α)) := nhds_induced coe a end topα end constructions section prod variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] @[continuity] lemma continuous_fst : continuous (@prod.fst α β) := continuous_inf_dom_left continuous_induced_dom lemma continuous_at_fst {p : α × β} : continuous_at prod.fst p := continuous_fst.continuous_at @[continuity] lemma continuous_snd : continuous (@prod.snd α β) := continuous_inf_dom_right continuous_induced_dom lemma continuous_at_snd {p : α × β} : continuous_at prod.snd p := continuous_snd.continuous_at @[continuity] lemma continuous.prod_mk {f : γ → α} {g : γ → β} (hf : continuous f) (hg : continuous g) : continuous (λx, (f x, g x)) := continuous_inf_rng (continuous_induced_rng hf) (continuous_induced_rng hg) lemma continuous.prod_map {f : γ → α} {g : δ → β} (hf : continuous f) (hg : continuous g) : continuous (λ x : γ × δ, (f x.1, g x.2)) := (hf.comp continuous_fst).prod_mk (hg.comp continuous_snd) lemma filter.eventually.prod_inl_nhds {p : α → Prop} {a : α} (h : ∀ᶠ x in 𝓝 a, p x) (b : β) : ∀ᶠ x in 𝓝 (a, b), p (x : α × β).1 := continuous_at_fst h lemma filter.eventually.prod_inr_nhds {p : β → Prop} {b : β} (h : ∀ᶠ x in 𝓝 b, p x) (a : α) : ∀ᶠ x in 𝓝 (a, b), p (x : α × β).2 := continuous_at_snd h lemma filter.eventually.prod_mk_nhds {pa : α → Prop} {a} (ha : ∀ᶠ x in 𝓝 a, pa x) {pb : β → Prop} {b} (hb : ∀ᶠ y in 𝓝 b, pb y) : ∀ᶠ p in 𝓝 (a, b), pa (p : α × β).1 ∧ pb p.2 := (ha.prod_inl_nhds b).and (hb.prod_inr_nhds a) lemma continuous_swap : continuous (prod.swap : α × β → β × α) := continuous.prod_mk continuous_snd continuous_fst lemma is_open_prod {s : set α} {t : set β} (hs : is_open s) (ht : is_open t) : is_open (set.prod s t) := is_open_inter (continuous_fst s hs) (continuous_snd t ht) lemma nhds_prod_eq {a : α} {b : β} : 𝓝 (a, b) = filter.prod (𝓝 a) (𝓝 b) := by rw [filter.prod, prod.topological_space, nhds_inf, nhds_induced, nhds_induced] instance [discrete_topology α] [discrete_topology β] : discrete_topology (α × β) := ⟨eq_of_nhds_eq_nhds $ assume ⟨a, b⟩, by rw [nhds_prod_eq, nhds_discrete α, nhds_discrete β, nhds_bot, filter.prod_pure_pure]⟩ lemma prod_mem_nhds_sets {s : set α} {t : set β} {a : α} {b : β} (ha : s ∈ 𝓝 a) (hb : t ∈ 𝓝 b) : set.prod s t ∈ 𝓝 (a, b) := by rw [nhds_prod_eq]; exact prod_mem_prod ha hb lemma nhds_swap (a : α) (b : β) : 𝓝 (a, b) = (𝓝 (b, a)).map prod.swap := by rw [nhds_prod_eq, filter.prod_comm, nhds_prod_eq]; refl lemma filter.tendsto.prod_mk_nhds {γ} {a : α} {b : β} {f : filter γ} {ma : γ → α} {mb : γ → β} (ha : tendsto ma f (𝓝 a)) (hb : tendsto mb f (𝓝 b)) : tendsto (λc, (ma c, mb c)) f (𝓝 (a, b)) := by rw [nhds_prod_eq]; exact filter.tendsto.prod_mk ha hb lemma filter.eventually.curry_nhds {p : α × β → Prop} {x : α} {y : β} (h : ∀ᶠ x in 𝓝 (x, y), p x) : ∀ᶠ x' in 𝓝 x, ∀ᶠ y' in 𝓝 y, p (x', y') := by { rw [nhds_prod_eq] at h, exact h.curry } lemma continuous_at.prod {f : α → β} {g : α → γ} {x : α} (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λx, (f x, g x)) x := hf.prod_mk_nhds hg lemma continuous_at.prod_map {f : α → γ} {g : β → δ} {p : α × β} (hf : continuous_at f p.fst) (hg : continuous_at g p.snd) : continuous_at (λ p : α × β, (f p.1, g p.2)) p := (hf.comp continuous_fst.continuous_at).prod (hg.comp continuous_snd.continuous_at) lemma continuous_at.prod_map' {f : α → γ} {g : β → δ} {x : α} {y : β} (hf : continuous_at f x) (hg : continuous_at g y) : continuous_at (λ p : α × β, (f p.1, g p.2)) (x, y) := have hf : continuous_at f (x, y).fst, from hf, have hg : continuous_at g (x, y).snd, from hg, hf.prod_map hg lemma prod_generate_from_generate_from_eq {α : Type*} {β : Type*} {s : set (set α)} {t : set (set β)} (hs : ⋃₀ s = univ) (ht : ⋃₀ t = univ) : @prod.topological_space α β (generate_from s) (generate_from t) = generate_from {g | ∃u∈s, ∃v∈t, g = set.prod u v} := let G := generate_from {g | ∃u∈s, ∃v∈t, g = set.prod u v} in le_antisymm (le_generate_from $ assume g ⟨u, hu, v, hv, g_eq⟩, g_eq.symm ▸ @is_open_prod _ _ (generate_from s) (generate_from t) _ _ (generate_open.basic _ hu) (generate_open.basic _ hv)) (le_inf (coinduced_le_iff_le_induced.mp $ le_generate_from $ assume u hu, have (⋃v∈t, set.prod u v) = prod.fst ⁻¹' u, from calc (⋃v∈t, set.prod u v) = set.prod u univ : set.ext $ assume ⟨a, b⟩, by rw ← ht; simp [and.left_comm] {contextual:=tt} ... = prod.fst ⁻¹' u : by simp [set.prod, preimage], show G.is_open (prod.fst ⁻¹' u), from this ▸ @is_open_Union _ _ G _ $ assume v, @is_open_Union _ _ G _ $ assume hv, generate_open.basic _ ⟨_, hu, _, hv, rfl⟩) (coinduced_le_iff_le_induced.mp $ le_generate_from $ assume v hv, have (⋃u∈s, set.prod u v) = prod.snd ⁻¹' v, from calc (⋃u∈s, set.prod u v) = set.prod univ v: set.ext $ assume ⟨a, b⟩, by rw [←hs]; by_cases b ∈ v; simp [h] {contextual:=tt} ... = prod.snd ⁻¹' v : by simp [set.prod, preimage], show G.is_open (prod.snd ⁻¹' v), from this ▸ @is_open_Union _ _ G _ $ assume u, @is_open_Union _ _ G _ $ assume hu, generate_open.basic _ ⟨_, hu, _, hv, rfl⟩)) lemma prod_eq_generate_from : prod.topological_space = generate_from {g | ∃(s:set α) (t:set β), is_open s ∧ is_open t ∧ g = set.prod s t} := le_antisymm (le_generate_from $ assume g ⟨s, t, hs, ht, g_eq⟩, g_eq.symm ▸ is_open_prod hs ht) (le_inf (ball_image_of_ball $ λt ht, generate_open.basic _ ⟨t, univ, by simpa [set.prod_eq] using ht⟩) (ball_image_of_ball $ λt ht, generate_open.basic _ ⟨univ, t, by simpa [set.prod_eq] using ht⟩)) lemma is_open_prod_iff {s : set (α×β)} : is_open s ↔ (∀a b, (a, b) ∈ s → ∃u v, is_open u ∧ is_open v ∧ a ∈ u ∧ b ∈ v ∧ set.prod u v ⊆ s) := begin rw [is_open_iff_nhds], simp [nhds_prod_eq, mem_prod_iff], simp [mem_nhds_sets_iff], exact forall_congr (assume a, ball_congr $ assume b h, ⟨assume ⟨u', ⟨u, us, uo, au⟩, v', ⟨v, vs, vo, bv⟩, h⟩, ⟨u, uo, v, vo, au, bv, subset.trans (set.prod_mono us vs) h⟩, assume ⟨u, uo, v, vo, au, bv, h⟩, ⟨u, ⟨u, subset.refl u, uo, au⟩, v, ⟨v, subset.refl v, vo, bv⟩, h⟩⟩) end /-- Given an open neighborhood `s` of `(x, x)`, then `(x, x)` has a square open neighborhood that is a subset of `s`. -/ lemma exists_nhds_square {s : set (α × α)} (hs : is_open s) {x : α} (hx : (x, x) ∈ s) : ∃U, is_open U ∧ x ∈ U ∧ set.prod U U ⊆ s := begin rcases is_open_prod_iff.mp hs x x hx with ⟨u, v, hu, hv, h1x, h2x, h2s⟩, refine ⟨u ∩ v, is_open_inter hu hv, ⟨h1x, h2x⟩, subset.trans _ h2s⟩, simp only [prod_subset_prod_iff, inter_subset_left, true_or, inter_subset_right, and_self], end /-- The first projection in a product of topological spaces sends open sets to open sets. -/ lemma is_open_map_fst : is_open_map (@prod.fst α β) := begin assume s hs, rw is_open_iff_forall_mem_open, assume x xs, rw mem_image_eq at xs, rcases xs with ⟨⟨y₁, y₂⟩, ys, yx⟩, rcases is_open_prod_iff.1 hs _ _ ys with ⟨o₁, o₂, o₁_open, o₂_open, yo₁, yo₂, ho⟩, simp at yx, rw yx at yo₁, refine ⟨o₁, _, o₁_open, yo₁⟩, assume z zs, rw mem_image_eq, exact ⟨(z, y₂), ho (by simp [zs, yo₂]), rfl⟩ end /-- The second projection in a product of topological spaces sends open sets to open sets. -/ lemma is_open_map_snd : is_open_map (@prod.snd α β) := begin /- This lemma could be proved by composing the fact that the first projection is open, and exchanging coordinates is a homeomorphism, hence open. As the `prod_comm` homeomorphism is defined later, we rather go for the direct proof, copy-pasting the proof for the first projection. -/ assume s hs, rw is_open_iff_forall_mem_open, assume x xs, rw mem_image_eq at xs, rcases xs with ⟨⟨y₁, y₂⟩, ys, yx⟩, rcases is_open_prod_iff.1 hs _ _ ys with ⟨o₁, o₂, o₁_open, o₂_open, yo₁, yo₂, ho⟩, simp at yx, rw yx at yo₂, refine ⟨o₂, _, o₂_open, yo₂⟩, assume z zs, rw mem_image_eq, exact ⟨(y₁, z), ho (by simp [zs, yo₁]), rfl⟩ end /-- A product set is open in a product space if and only if each factor is open, or one of them is empty -/ lemma is_open_prod_iff' {s : set α} {t : set β} : is_open (set.prod s t) ↔ (is_open s ∧ is_open t) ∨ (s = ∅) ∨ (t = ∅) := begin 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, from prod_nonempty_iff.1 h, split, { assume H : is_open (set.prod s t), refine or.inl ⟨_, _⟩, show is_open s, { rw ← fst_image_prod s st.2, exact is_open_map_fst _ H }, show is_open t, { rw ← snd_image_prod st.1 t, exact is_open_map_snd _ H } }, { assume H, simp [st.1.ne_empty, st.2.ne_empty] at H, exact is_open_prod H.1 H.2 } } end lemma closure_prod_eq {s : set α} {t : set β} : closure (set.prod s t) = set.prod (closure s) (closure t) := set.ext $ assume ⟨a, b⟩, have filter.prod (𝓝 a) (𝓝 b) ⊓ 𝓟 (set.prod s t) = filter.prod (𝓝 a ⊓ 𝓟 s) (𝓝 b ⊓ 𝓟 t), by rw [←prod_inf_prod, prod_principal_principal], by simp [closure_eq_cluster_pts, cluster_pt, nhds_prod_eq, this]; exact prod_ne_bot lemma mem_closure2 {s : set α} {t : set β} {u : set γ} {f : α → β → γ} {a : α} {b : β} (hf : continuous (λp:α×β, f p.1 p.2)) (ha : a ∈ closure s) (hb : b ∈ closure t) (hu : ∀a b, a ∈ s → b ∈ t → f a b ∈ u) : f a b ∈ closure u := have (a, b) ∈ closure (set.prod s t), by rw [closure_prod_eq]; from ⟨ha, hb⟩, show (λp:α×β, f p.1 p.2) (a, b) ∈ closure u, from mem_closure hf this $ assume ⟨a, b⟩ ⟨ha, hb⟩, hu a b ha hb lemma is_closed_prod {s₁ : set α} {s₂ : set β} (h₁ : is_closed s₁) (h₂ : is_closed s₂) : is_closed (set.prod s₁ s₂) := closure_eq_iff_is_closed.mp $ by simp only [h₁.closure_eq, h₂.closure_eq, closure_prod_eq] lemma inducing.prod_mk {f : α → β} {g : γ → δ} (hf : inducing f) (hg : inducing g) : inducing (λx:α×γ, (f x.1, g x.2)) := ⟨by rw [prod.topological_space, prod.topological_space, hf.induced, hg.induced, induced_compose, induced_compose, induced_inf, induced_compose, induced_compose]⟩ lemma embedding.prod_mk {f : α → β} {g : γ → δ} (hf : embedding f) (hg : embedding g) : embedding (λx:α×γ, (f x.1, g x.2)) := { inj := assume ⟨x₁, x₂⟩ ⟨y₁, y₂⟩, by simp; exact assume h₁ h₂, ⟨hf.inj h₁, hg.inj h₂⟩, ..hf.to_inducing.prod_mk hg.to_inducing } protected lemma is_open_map.prod {f : α → β} {g : γ → δ} (hf : is_open_map f) (hg : is_open_map g) : is_open_map (λ p : α × γ, (f p.1, g p.2)) := begin rw [is_open_map_iff_nhds_le], rintros ⟨a, b⟩, rw [nhds_prod_eq, nhds_prod_eq, ← filter.prod_map_map_eq], exact filter.prod_mono (is_open_map_iff_nhds_le.1 hf a) (is_open_map_iff_nhds_le.1 hg b) end protected lemma open_embedding.prod {f : α → β} {g : γ → δ} (hf : open_embedding f) (hg : open_embedding g) : open_embedding (λx:α×γ, (f x.1, g x.2)) := open_embedding_of_embedding_open (hf.1.prod_mk hg.1) (hf.is_open_map.prod hg.is_open_map) lemma embedding_graph {f : α → β} (hf : continuous f) : embedding (λx, (x, f x)) := embedding_of_embedding_compose (continuous_id.prod_mk hf) continuous_fst embedding_id end prod section sum open sum variables [topological_space α] [topological_space β] [topological_space γ] @[continuity] lemma continuous_inl : continuous (@inl α β) := continuous_sup_rng_left continuous_coinduced_rng @[continuity] lemma continuous_inr : continuous (@inr α β) := continuous_sup_rng_right continuous_coinduced_rng @[continuity] lemma continuous_sum_rec {f : α → γ} {g : β → γ} (hf : continuous f) (hg : continuous g) : @continuous (α ⊕ β) γ _ _ (@sum.rec α β (λ_, γ) f g) := continuous_sup_dom hf hg lemma is_open_sum_iff {s : set (α ⊕ β)} : is_open s ↔ is_open (inl ⁻¹' s) ∧ is_open (inr ⁻¹' s) := iff.rfl lemma is_open_map_sum {f : α ⊕ β → γ} (h₁ : is_open_map (λ a, f (inl a))) (h₂ : is_open_map (λ b, f (inr b))) : is_open_map f := begin intros u hu, rw is_open_sum_iff at hu, cases hu with hu₁ hu₂, have : u = inl '' (inl ⁻¹' u) ∪ inr '' (inr ⁻¹' u), { ext (_|_); simp }, rw [this, set.image_union, set.image_image, set.image_image], exact is_open_union (h₁ _ hu₁) (h₂ _ hu₂) end lemma embedding_inl : embedding (@inl α β) := { induced := begin unfold sum.topological_space, apply le_antisymm, { rw ← coinduced_le_iff_le_induced, exact le_sup_left }, { intros u hu, existsi (inl '' u), change (is_open (inl ⁻¹' (@inl α β '' u)) ∧ is_open (inr ⁻¹' (@inl α β '' u))) ∧ inl ⁻¹' (inl '' u) = u, have : inl ⁻¹' (@inl α β '' u) = u := preimage_image_eq u (λ _ _, inl.inj_iff.mp), rw this, have : inr ⁻¹' (@inl α β '' u) = ∅ := eq_empty_iff_forall_not_mem.mpr (assume a ⟨b, _, h⟩, inl_ne_inr h), rw this, exact ⟨⟨hu, is_open_empty⟩, rfl⟩ } end, inj := λ _ _, inl.inj_iff.mp } lemma embedding_inr : embedding (@inr α β) := { induced := begin unfold sum.topological_space, apply le_antisymm, { rw ← coinduced_le_iff_le_induced, exact le_sup_right }, { intros u hu, existsi (inr '' u), change (is_open (inl ⁻¹' (@inr α β '' u)) ∧ is_open (inr ⁻¹' (@inr α β '' u))) ∧ inr ⁻¹' (inr '' u) = u, have : inl ⁻¹' (@inr α β '' u) = ∅ := eq_empty_iff_forall_not_mem.mpr (assume b ⟨a, _, h⟩, inr_ne_inl h), rw this, have : inr ⁻¹' (@inr α β '' u) = u := preimage_image_eq u (λ _ _, inr.inj_iff.mp), rw this, exact ⟨⟨is_open_empty, hu⟩, rfl⟩ } end, inj := λ _ _, inr.inj_iff.mp } lemma open_embedding_inl : open_embedding (inl : α → α ⊕ β) := { open_range := begin rw is_open_sum_iff, convert and.intro is_open_univ is_open_empty; { ext, simp } end, .. embedding_inl } lemma open_embedding_inr : open_embedding (inr : β → α ⊕ β) := { open_range := begin rw is_open_sum_iff, convert and.intro is_open_empty is_open_univ; { ext, simp } end, .. embedding_inr } end sum section subtype variables [topological_space α] [topological_space β] [topological_space γ] {p : α → Prop} lemma embedding_subtype_coe : embedding (coe : subtype p → α) := ⟨⟨rfl⟩, subtype.coe_injective⟩ @[continuity] lemma continuous_subtype_val : continuous (@subtype.val α p) := continuous_induced_dom lemma continuous_subtype_coe : continuous (coe : subtype p → α) := continuous_subtype_val lemma is_open.open_embedding_subtype_coe {s : set α} (hs : is_open s) : open_embedding (coe : s → α) := { induced := rfl, inj := subtype.coe_injective, open_range := (subtype.range_coe : range coe = s).symm ▸ hs } lemma is_open.is_open_map_subtype_coe {s : set α} (hs : is_open s) : is_open_map (coe : s → α) := hs.open_embedding_subtype_coe.is_open_map lemma is_open_map.restrict {f : α → β} (hf : is_open_map f) {s : set α} (hs : is_open s) : is_open_map (s.restrict f) := hf.comp hs.is_open_map_subtype_coe lemma is_closed.closed_embedding_subtype_coe {s : set α} (hs : is_closed s) : closed_embedding (coe : {x // x ∈ s} → α) := { induced := rfl, inj := subtype.coe_injective, closed_range := (subtype.range_coe : range coe = s).symm ▸ hs } @[continuity] lemma continuous_subtype_mk {f : β → α} (hp : ∀x, p (f x)) (h : continuous f) : continuous (λx, (⟨f x, hp x⟩ : subtype p)) := continuous_induced_rng h lemma continuous_inclusion {s t : set α} (h : s ⊆ t) : continuous (inclusion h) := continuous_subtype_mk _ continuous_subtype_coe lemma continuous_at_subtype_coe {p : α → Prop} {a : subtype p} : continuous_at (coe : subtype p → α) a := continuous_iff_continuous_at.mp continuous_subtype_coe _ lemma map_nhds_subtype_coe_eq {a : α} (ha : p a) (h : {a | p a} ∈ 𝓝 a) : map (coe : subtype p → α) (𝓝 ⟨a, ha⟩) = 𝓝 a := map_nhds_induced_eq $ by simpa only [subtype.coe_mk, subtype.range_coe] using h lemma nhds_subtype_eq_comap {a : α} {h : p a} : 𝓝 (⟨a, h⟩ : subtype p) = comap coe (𝓝 a) := nhds_induced _ _ lemma tendsto_subtype_rng {β : Type*} {p : α → Prop} {b : filter β} {f : β → subtype p} : ∀{a:subtype p}, tendsto f b (𝓝 a) ↔ tendsto (λx, (f x : α)) b (𝓝 (a : α)) | ⟨a, ha⟩ := by rw [nhds_subtype_eq_comap, tendsto_comap_iff, subtype.coe_mk] lemma continuous_subtype_nhds_cover {ι : Sort*} {f : α → β} {c : ι → α → Prop} (c_cover : ∀x:α, ∃i, {x | c i x} ∈ 𝓝 x) (f_cont : ∀i, continuous (λ(x : subtype (c i)), f x)) : continuous f := continuous_iff_continuous_at.mpr $ assume x, let ⟨i, (c_sets : {x | c i x} ∈ 𝓝 x)⟩ := c_cover x in let x' : subtype (c i) := ⟨x, mem_of_nhds c_sets⟩ in calc map f (𝓝 x) = map f (map coe (𝓝 x')) : congr_arg (map f) (map_nhds_subtype_coe_eq _ $ c_sets).symm ... = map (λx:subtype (c i), f x) (𝓝 x') : rfl ... ≤ 𝓝 (f x) : continuous_iff_continuous_at.mp (f_cont i) x' lemma continuous_subtype_is_closed_cover {ι : Sort*} {f : α → β} (c : ι → α → Prop) (h_lf : locally_finite (λi, {x | c i x})) (h_is_closed : ∀i, is_closed {x | c i x}) (h_cover : ∀x, ∃i, c i x) (f_cont : ∀i, continuous (λ(x : subtype (c i)), f x)) : continuous f := continuous_iff_is_closed.mpr $ assume s hs, have ∀i, is_closed ((coe : {x | c i x} → α) '' (f ∘ coe ⁻¹' s)), from assume i, embedding_is_closed embedding_subtype_coe (by simp [subtype.range_coe]; exact h_is_closed i) (continuous_iff_is_closed.mp (f_cont i) _ hs), have is_closed (⋃i, (coe : {x | c i x} → α) '' (f ∘ coe ⁻¹' s)), from is_closed_Union_of_locally_finite (locally_finite_subset h_lf $ assume i x ⟨⟨x', hx'⟩, _, heq⟩, heq ▸ hx') this, have f ⁻¹' s = (⋃i, (coe : {x | c i x} → α) '' (f ∘ coe ⁻¹' s)), begin apply set.ext, have : ∀ (x : α), f x ∈ s ↔ ∃ (i : ι), c i x ∧ f x ∈ s := λ x, ⟨λ hx, let ⟨i, hi⟩ := h_cover x in ⟨i, hi, hx⟩, λ ⟨i, hi, hx⟩, hx⟩, simpa [and.comm, @and.left_comm (c _ _), ← exists_and_distrib_right], end, by rwa [this] lemma closure_subtype {x : {a // p a}} {s : set {a // p a}}: x ∈ closure s ↔ (x : α) ∈ closure ((coe : _ → α) '' s) := closure_induced $ assume x y, subtype.eq end subtype section quotient variables [topological_space α] [topological_space β] [topological_space γ] variables {r : α → α → Prop} {s : setoid α} lemma quotient_map_quot_mk : quotient_map (@quot.mk α r) := ⟨quot.exists_rep, rfl⟩ @[continuity] lemma continuous_quot_mk : continuous (@quot.mk α r) := continuous_coinduced_rng @[continuity] lemma continuous_quot_lift {f : α → β} (hr : ∀ a b, r a b → f a = f b) (h : continuous f) : continuous (quot.lift f hr : quot r → β) := continuous_coinduced_dom h lemma quotient_map_quotient_mk : quotient_map (@quotient.mk α s) := quotient_map_quot_mk lemma continuous_quotient_mk : continuous (@quotient.mk α s) := continuous_coinduced_rng lemma continuous_quotient_lift {f : α → β} (hs : ∀ a b, a ≈ b → f a = f b) (h : continuous f) : continuous (quotient.lift f hs : quotient s → β) := continuous_coinduced_dom h end quotient section pi variables {ι : Type*} {π : ι → Type*} @[continuity] lemma continuous_pi [topological_space α] [∀i, topological_space (π i)] {f : α → Πi:ι, π i} (h : ∀i, continuous (λa, f a i)) : continuous f := continuous_infi_rng $ assume i, continuous_induced_rng $ h i @[continuity] lemma continuous_apply [∀i, topological_space (π i)] (i : ι) : continuous (λp:Πi, π i, p i) := continuous_infi_dom continuous_induced_dom /-- Embedding a factor into a product space (by fixing arbitrarily all the other coordinates) is continuous. -/ @[continuity] lemma continuous_update [decidable_eq ι] [∀i, topological_space (π i)] {i : ι} {f : Πi:ι, π i} : continuous (λ x : π i, function.update f i x) := begin refine continuous_pi (λj, _), by_cases h : j = i, { rw h, simpa using continuous_id }, { simpa [h] using continuous_const } end lemma nhds_pi [t : ∀i, topological_space (π i)] {a : Πi, π i} : 𝓝 a = (⨅i, comap (λx, x i) (𝓝 (a i))) := calc 𝓝 a = (⨅i, @nhds _ (@topological_space.induced _ _ (λx:Πi, π i, x i) (t i)) a) : nhds_infi ... = (⨅i, comap (λx, x i) (𝓝 (a i))) : by simp [nhds_induced] lemma is_open_set_pi [∀a, topological_space (π a)] {i : set ι} {s : Πa, set (π a)} (hi : finite i) (hs : ∀a∈i, is_open (s a)) : is_open (pi i s) := by rw [pi_def]; exact (is_open_bInter hi $ assume a ha, continuous_apply a _ $ hs a ha) lemma pi_eq_generate_from [∀a, topological_space (π a)] : Pi.topological_space = generate_from {g | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, is_open (s a)) ∧ g = pi ↑i s} := le_antisymm (le_generate_from $ assume g ⟨s, i, hi, eq⟩, eq.symm ▸ is_open_set_pi (finset.finite_to_set _) hi) (le_infi $ assume a s ⟨t, ht, s_eq⟩, generate_open.basic _ $ ⟨function.update (λa, univ) a t, {a}, by simpa using ht, by ext f; simp [s_eq.symm, pi]⟩) lemma pi_generate_from_eq {g : Πa, set (set (π a))} : @Pi.topological_space ι π (λa, generate_from (g a)) = generate_from {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} := let G := {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} in begin rw [pi_eq_generate_from], refine le_antisymm (generate_from_mono _) (le_generate_from _), exact assume s ⟨t, i, ht, eq⟩, ⟨t, i, assume a ha, generate_open.basic _ (ht a ha), eq⟩, { rintros s ⟨t, i, hi, rfl⟩, rw [pi_def], apply is_open_bInter (finset.finite_to_set _), assume a ha, show ((generate_from G).coinduced (λf:Πa, π a, f a)).is_open (t a), refine le_generate_from _ _ (hi a ha), exact assume s hs, generate_open.basic _ ⟨function.update (λa, univ) a s, {a}, by simp [hs]⟩ } end lemma pi_generate_from_eq_fintype {g : Πa, set (set (π a))} [fintype ι] (hg : ∀a, ⋃₀ g a = univ) : @Pi.topological_space ι π (λa, generate_from (g a)) = generate_from {t | ∃(s:Πa, set (π a)), (∀a, s a ∈ g a) ∧ t = pi univ s} := let G := {t | ∃(s:Πa, set (π a)), (∀a, s a ∈ g a) ∧ t = pi univ s} in begin rw [pi_generate_from_eq], refine le_antisymm (generate_from_mono _) (le_generate_from _), exact assume s ⟨t, ht, eq⟩, ⟨t, finset.univ, by simp [ht, eq]⟩, { rintros s ⟨t, i, ht, rfl⟩, apply is_open_iff_forall_mem_open.2 _, assume f hf, choose c hc using show ∀a, ∃s, s ∈ g a ∧ f a ∈ s, { assume a, have : f a ∈ ⋃₀ g a, { rw [hg], apply mem_univ }, simpa }, refine ⟨pi univ (λa, if a ∈ i then t a else (c : Πa, set (π a)) a), _, _, _⟩, { simp [pi_if] }, { refine generate_open.basic _ ⟨_, assume a, _, rfl⟩, by_cases a ∈ i; simp [*, pi] at * }, { have : f ∈ pi {a | a ∉ i} c, { simp [*, pi] at * }, simpa [pi_if, hf] } } end end pi section sigma variables {ι : Type*} {σ : ι → Type*} [Π i, topological_space (σ i)] @[continuity] lemma continuous_sigma_mk {i : ι} : continuous (@sigma.mk ι σ i) := continuous_supr_rng continuous_coinduced_rng lemma is_open_sigma_iff {s : set (sigma σ)} : is_open s ↔ ∀ i, is_open (sigma.mk i ⁻¹' s) := by simp only [is_open_supr_iff, is_open_coinduced] lemma is_closed_sigma_iff {s : set (sigma σ)} : is_closed s ↔ ∀ i, is_closed (sigma.mk i ⁻¹' s) := is_open_sigma_iff lemma is_open_map_sigma_mk {i : ι} : is_open_map (@sigma.mk ι σ i) := begin intros s hs, rw is_open_sigma_iff, intro j, classical, by_cases h : i = j, { subst j, convert hs, exact set.preimage_image_eq _ sigma_mk_injective }, { convert is_open_empty, apply set.eq_empty_of_subset_empty, rintro x ⟨y, _, hy⟩, have : i = j, by cc, contradiction } end lemma is_open_range_sigma_mk {i : ι} : is_open (set.range (@sigma.mk ι σ i)) := by { rw ←set.image_univ, exact is_open_map_sigma_mk _ is_open_univ } lemma is_closed_map_sigma_mk {i : ι} : is_closed_map (@sigma.mk ι σ i) := begin intros s hs, rw is_closed_sigma_iff, intro j, classical, by_cases h : i = j, { subst j, convert hs, exact set.preimage_image_eq _ sigma_mk_injective }, { convert is_closed_empty, apply set.eq_empty_of_subset_empty, rintro x ⟨y, _, hy⟩, have : i = j, by cc, contradiction } end lemma is_closed_sigma_mk {i : ι} : is_closed (set.range (@sigma.mk ι σ i)) := by { rw ←set.image_univ, exact is_closed_map_sigma_mk _ is_closed_univ } lemma open_embedding_sigma_mk {i : ι} : open_embedding (@sigma.mk ι σ i) := open_embedding_of_continuous_injective_open continuous_sigma_mk sigma_mk_injective is_open_map_sigma_mk lemma closed_embedding_sigma_mk {i : ι} : closed_embedding (@sigma.mk ι σ i) := closed_embedding_of_continuous_injective_closed continuous_sigma_mk sigma_mk_injective is_closed_map_sigma_mk lemma embedding_sigma_mk {i : ι} : embedding (@sigma.mk ι σ i) := closed_embedding_sigma_mk.1 /-- A map out of a sum type is continuous if its restriction to each summand is. -/ @[continuity] lemma continuous_sigma [topological_space β] {f : sigma σ → β} (h : ∀ i, continuous (λ a, f ⟨i, a⟩)) : continuous f := continuous_supr_dom (λ i, continuous_coinduced_dom (h i)) @[continuity] lemma continuous_sigma_map {κ : Type*} {τ : κ → Type*} [Π k, topological_space (τ k)] {f₁ : ι → κ} {f₂ : Π i, σ i → τ (f₁ i)} (hf : ∀ i, continuous (f₂ i)) : continuous (sigma.map f₁ f₂) := continuous_sigma $ λ i, show continuous (λ a, sigma.mk (f₁ i) (f₂ i a)), from continuous_sigma_mk.comp (hf i) lemma is_open_map_sigma [topological_space β] {f : sigma σ → β} (h : ∀ i, is_open_map (λ a, f ⟨i, a⟩)) : is_open_map f := begin intros s hs, rw is_open_sigma_iff at hs, have : s = ⋃ i, sigma.mk i '' (sigma.mk i ⁻¹' s), { rw Union_image_preimage_sigma_mk_eq_self }, rw this, rw [image_Union], apply is_open_Union, intro i, rw [image_image], exact h i _ (hs i) end /-- The sum of embeddings is an embedding. -/ lemma embedding_sigma_map {τ : ι → Type*} [Π i, topological_space (τ i)] {f : Π i, σ i → τ i} (hf : ∀ i, embedding (f i)) : embedding (sigma.map id f) := begin refine ⟨⟨_⟩, function.injective_id.sigma_map (λ i, (hf i).inj)⟩, refine le_antisymm (continuous_iff_le_induced.mp (continuous_sigma_map (λ i, (hf i).continuous))) _, intros s hs, replace hs := is_open_sigma_iff.mp hs, have : ∀ i, ∃ t, is_open t ∧ f i ⁻¹' t = sigma.mk i ⁻¹' s, { intro i, apply is_open_induced_iff.mp, convert hs i, exact (hf i).induced.symm }, choose t ht using this, apply is_open_induced_iff.mpr, refine ⟨⋃ i, sigma.mk i '' t i, is_open_Union (λ i, is_open_map_sigma_mk _ (ht i).1), _⟩, ext ⟨i, x⟩, change (sigma.mk i (f i x) ∈ ⋃ (i : ι), sigma.mk i '' t i) ↔ x ∈ sigma.mk i ⁻¹' s, rw [←(ht i).2, mem_Union], split, { rintro ⟨j, hj⟩, rw mem_image at hj, rcases hj with ⟨y, hy₁, hy₂⟩, rcases sigma.mk.inj_iff.mp hy₂ with ⟨rfl, hy⟩, replace hy := eq_of_heq hy, subst y, exact hy₁ }, { intro hx, use i, rw mem_image, exact ⟨f i x, hx, rfl⟩ } end end sigma section ulift @[continuity] lemma continuous_ulift_down [topological_space α] : continuous (ulift.down : ulift.{v u} α → α) := continuous_induced_dom @[continuity] lemma continuous_ulift_up [topological_space α] : continuous (ulift.up : α → ulift.{v u} α) := continuous_induced_rng continuous_id end ulift lemma mem_closure_of_continuous [topological_space α] [topological_space β] {f : α → β} {a : α} {s : set α} {t : set β} (hf : continuous f) (ha : a ∈ closure s) (h : maps_to f s (closure t)) : f a ∈ closure t := calc f a ∈ f '' closure s : mem_image_of_mem _ ha ... ⊆ closure (f '' s) : image_closure_subset_closure_image hf ... ⊆ closure t : closure_minimal h.image_subset is_closed_closure lemma mem_closure_of_continuous2 [topological_space α] [topological_space β] [topological_space γ] {f : α → β → γ} {a : α} {b : β} {s : set α} {t : set β} {u : set γ} (hf : continuous (λp:α×β, f p.1 p.2)) (ha : a ∈ closure s) (hb : b ∈ closure t) (h : ∀a∈s, ∀b∈t, f a b ∈ closure u) : f a b ∈ closure u := have (a,b) ∈ closure (set.prod s t), by simp [closure_prod_eq, ha, hb], show f (a, b).1 (a, b).2 ∈ closure u, from @mem_closure_of_continuous (α×β) _ _ _ (λp:α×β, f p.1 p.2) (a,b) _ u hf this $ assume ⟨p₁, p₂⟩ ⟨h₁, h₂⟩, h p₁ h₁ p₂ h₂
447c938f637736e5aec9e10c782a2b5b69dc785f
367134ba5a65885e863bdc4507601606690974c1
/src/data/fin_enum.lean
42b2840fee967a3cc5292ee4c0467e16ef9636d8
[ "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
8,907
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author(s): Simon Hudon -/ import control.monad.basic import data.fintype.basic /-! Type class for finitely enumerable types. The property is stronger than `fintype` in that it assigns each element a rank in a finite enumeration. -/ open finset /-- `fin_enum α` means that `α` is finite and can be enumerated in some order, i.e. `α` has an explicit bijection with `fin n` for some n. -/ class fin_enum (α : Sort*) := (card : ℕ) (equiv [] : α ≃ fin card) [dec_eq : decidable_eq α] attribute [instance, priority 100] fin_enum.dec_eq namespace fin_enum variables {α : Type*} /-- transport a `fin_enum` instance across an equivalence -/ def of_equiv (α) {β} [fin_enum α] (h : β ≃ α) : fin_enum β := { card := card α, equiv := h.trans (equiv α), dec_eq := (h.trans (equiv _)).decidable_eq } /-- create a `fin_enum` instance from an exhaustive list without duplicates -/ def of_nodup_list [decidable_eq α] (xs : list α) (h : ∀ x : α, x ∈ xs) (h' : list.nodup xs) : fin_enum α := { card := xs.length, equiv := ⟨λ x, ⟨xs.index_of x,by rw [list.index_of_lt_length]; apply h⟩, λ ⟨i,h⟩, xs.nth_le _ h, λ x, by simp [of_nodup_list._match_1], λ ⟨i,h⟩, by simp [of_nodup_list._match_1,*]; rw list.nth_le_index_of; apply list.nodup_erase_dup ⟩ } /-- create a `fin_enum` instance from an exhaustive list; duplicates are removed -/ def of_list [decidable_eq α] (xs : list α) (h : ∀ x : α, x ∈ xs) : fin_enum α := of_nodup_list xs.erase_dup (by simp *) (list.nodup_erase_dup _) /-- create an exhaustive list of the values of a given type -/ def to_list (α) [fin_enum α] : list α := (list.fin_range (card α)).map (equiv α).symm open function @[simp] lemma mem_to_list [fin_enum α] (x : α) : x ∈ to_list α := by simp [to_list]; existsi equiv α x; simp @[simp] lemma nodup_to_list [fin_enum α] : list.nodup (to_list α) := by simp [to_list]; apply list.nodup_map; [apply equiv.injective, apply list.nodup_fin_range] /-- create a `fin_enum` instance using a surjection -/ def of_surjective {β} (f : β → α) [decidable_eq α] [fin_enum β] (h : surjective f) : fin_enum α := of_list ((to_list β).map f) (by intro; simp; exact h _) /-- create a `fin_enum` instance using an injection -/ noncomputable def of_injective {α β} (f : α → β) [decidable_eq α] [fin_enum β] (h : injective f) : fin_enum α := of_list ((to_list β).filter_map (partial_inv f)) begin intro x, simp only [mem_to_list, true_and, list.mem_filter_map], use f x, simp only [h, function.partial_inv_left], end instance pempty : fin_enum pempty := of_list [] (λ x, pempty.elim x) instance empty : fin_enum empty := of_list [] (λ x, empty.elim x) instance punit : fin_enum punit := of_list [punit.star] (λ x, by cases x; simp) instance prod {β} [fin_enum α] [fin_enum β] : fin_enum (α × β) := of_list ( (to_list α).product (to_list β) ) (λ x, by cases x; simp) instance sum {β} [fin_enum α] [fin_enum β] : fin_enum (α ⊕ β) := of_list ( (to_list α).map sum.inl ++ (to_list β).map sum.inr ) (λ x, by cases x; simp) instance fin {n} : fin_enum (fin n) := of_list (list.fin_range _) (by simp) instance quotient.enum [fin_enum α] (s : setoid α) [decidable_rel ((≈) : α → α → Prop)] : fin_enum (quotient s) := fin_enum.of_surjective quotient.mk (λ x, quotient.induction_on x (λ x, ⟨x, rfl⟩)) /-- enumerate all finite sets of a given type -/ def finset.enum [decidable_eq α] : list α → list (finset α) | [] := [∅] | (x :: xs) := do r ← finset.enum xs, [r,{x} ∪ r] @[simp]lemma finset.mem_enum [decidable_eq α] (s : finset α) (xs : list α) : s ∈ finset.enum xs ↔ ∀ x ∈ s, x ∈ xs := begin induction xs generalizing s; simp [*,finset.enum], { simp [finset.eq_empty_iff_forall_not_mem,(∉)], refl }, { split, rintro ⟨a,h,h'⟩ x hx, cases h', { right, apply h, subst a, exact hx, }, { simp only [h', mem_union, mem_singleton] at hx ⊢, cases hx, { exact or.inl hx }, { exact or.inr (h _ hx) } }, intro h, existsi s \ ({xs_hd} : finset α), simp only [and_imp, union_comm, mem_sdiff, mem_singleton], simp only [or_iff_not_imp_left] at h, existsi h, by_cases xs_hd ∈ s, { have : {xs_hd} ⊆ s, simp only [has_subset.subset, *, forall_eq, mem_singleton], simp only [union_sdiff_of_subset this, or_true, finset.union_sdiff_of_subset, eq_self_iff_true], }, { left, symmetry, simp only [sdiff_eq_self], intro a, simp only [and_imp, mem_inter, mem_singleton, not_mem_empty], intros h₀ h₁, subst a, apply h h₀, } } end instance finset.fin_enum [fin_enum α] : fin_enum (finset α) := of_list (finset.enum (to_list α)) (by intro; simp) instance subtype.fin_enum [fin_enum α] (p : α → Prop) [decidable_pred p] : fin_enum {x // p x} := of_list ((to_list α).filter_map $ λ x, if h : p x then some ⟨_,h⟩ else none) (by rintro ⟨x,h⟩; simp; existsi x; simp *) instance (β : α → Type*) [fin_enum α] [∀ a, fin_enum (β a)] : fin_enum (sigma β) := of_list ((to_list α).bind $ λ a, (to_list (β a)).map $ sigma.mk a) (by intro x; cases x; simp) instance psigma.fin_enum {β : α → Type*} [fin_enum α] [∀ a, fin_enum (β a)] : fin_enum (Σ' a, β a) := fin_enum.of_equiv _ (equiv.psigma_equiv_sigma _) instance psigma.fin_enum_prop_left {α : Prop} {β : α → Type*} [∀ a, fin_enum (β a)] [decidable α] : fin_enum (Σ' a, β a) := if h : α then of_list ((to_list (β h)).map $ psigma.mk h) (λ ⟨a,Ba⟩, by simp) else of_list [] (λ ⟨a,Ba⟩, (h a).elim) instance psigma.fin_enum_prop_right {β : α → Prop} [fin_enum α] [∀ a, decidable (β a)] : fin_enum (Σ' a, β a) := fin_enum.of_equiv {a // β a} ⟨λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, rfl, λ ⟨x, y⟩, rfl⟩ instance psigma.fin_enum_prop_prop {α : Prop} {β : α → Prop} [decidable α] [∀ a, decidable (β a)] : fin_enum (Σ' a, β a) := if h : ∃ a, β a then of_list [⟨h.fst,h.snd⟩] (by rintro ⟨⟩; simp) else of_list [] (λ a, (h ⟨a.fst,a.snd⟩).elim) @[priority 100] instance [fin_enum α] : fintype α := { elems := univ.map (equiv α).symm.to_embedding, complete := by intros; simp; existsi (equiv α x); simp } /-- For `pi.cons x xs y f` create a function where every `i ∈ xs` is mapped to `f i` and `x` is mapped to `y` -/ def pi.cons {β : α → Type*} [decidable_eq α] (x : α) (xs : list α) (y : β x) (f : Π a, a ∈ xs → β a) : Π a, a ∈ (x :: xs : list α) → β a | b h := if h' : b = x then cast (by rw h') y else f b (list.mem_of_ne_of_mem h' h) /-- Given `f` a function whose domain is `x :: xs`, produce a function whose domain is restricted to `xs`. -/ def pi.tail {α : Type*} {β : α → Type*} {x : α} {xs : list α} (f : Π a, a ∈ (x :: xs : list α) → β a) : Π a, a ∈ xs → β a | a h := f a (list.mem_cons_of_mem _ h) /-- `pi xs f` creates the list of functions `g` such that, for `x ∈ xs`, `g x ∈ f x` -/ def pi {α : Type*} {β : α → Type*} [decidable_eq α] : Π xs : list α, (Π a, list (β a)) → list (Π a, a ∈ xs → β a) | [] fs := [λ x h, h.elim] | (x :: xs) fs := fin_enum.pi.cons x xs <$> fs x <*> pi xs fs lemma mem_pi {α : Type*} {β : α → Type*} [fin_enum α] [∀a, fin_enum (β a)] (xs : list α) (f : Π a, a ∈ xs → β a) : f ∈ pi xs (λ x, to_list (β x)) := begin induction xs; simp [pi,-list.map_eq_map] with monad_norm functor_norm, { ext a ⟨ ⟩ }, { existsi pi.cons xs_hd xs_tl (f _ (list.mem_cons_self _ _)), split, exact ⟨_,rfl⟩, existsi pi.tail f, split, { apply xs_ih, }, { ext x h, simp [pi.cons], split_ifs, subst x, refl, refl }, } end /-- enumerate all functions whose domain and range are finitely enumerable -/ def pi.enum {α : Type*} (β : α → Type*) [fin_enum α] [∀a, fin_enum (β a)] : list (Π a, β a) := (pi (to_list α) (λ x, to_list (β x))).map (λ f x, f x (mem_to_list _)) lemma pi.mem_enum {α : Type*} {β : α → Type*} [fin_enum α] [∀a, fin_enum (β a)] (f : Π a, β a) : f ∈ pi.enum β := by simp [pi.enum]; refine ⟨λ a h, f a, mem_pi _ _, rfl⟩ instance pi.fin_enum {α : Type*} {β : α → Type*} [fin_enum α] [∀a, fin_enum (β a)] : fin_enum (Πa, β a) := of_list (pi.enum _) (λ x, pi.mem_enum _) instance pfun_fin_enum (p : Prop) [decidable p] (α : p → Type*) [Π hp, fin_enum (α hp)] : fin_enum (Π hp : p, α hp) := if hp : p then of_list ( (to_list (α hp)).map $ λ x hp', x ) (by intro; simp; exact ⟨x hp,rfl⟩) else of_list [λ hp', (hp hp').elim] (by intro; simp; ext hp'; cases hp hp') end fin_enum
8bc2ce6d08fc7b267826b6760028caa82689f5a6
f618aea02cb4104ad34ecf3b9713065cc0d06103
/src/data/list/defs.lean
d4515c9a6481b6cbfc69a9baffe08aa9c1ecc9de
[ "Apache-2.0" ]
permissive
joehendrix/mathlib
84b6603f6be88a7e4d62f5b1b0cbb523bb82b9a5
c15eab34ad754f9ecd738525cb8b5a870e834ddc
refs/heads/master
1,589,606,591,630
1,555,946,393,000
1,555,946,393,000
182,813,854
0
0
null
1,555,946,309,000
1,555,946,308,000
null
UTF-8
Lean
false
false
18,745
lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro Extra definitions on lists. -/ import data.option.defs logic.basic logic.relator namespace list open function nat universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} instance [decidable_eq α] : has_sdiff (list α) := ⟨ list.diff ⟩ /-- Split a list at an index. split_at 2 [a, b, c] = ([a, b], [c]) -/ def split_at : ℕ → list α → list α × list α | 0 a := ([], a) | (succ n) [] := ([], []) | (succ n) (x :: xs) := let (l, r) := split_at n xs in (x :: l, r) def split_on_p_aux {α : Type u} (P : α → Prop) [decidable_pred P] : list α → (list α → list α) → list (list α) | [] f := [f []] | (h :: t) f := if P h then f [] :: split_on_p_aux t id else split_on_p_aux t (λ l, f (h :: l)) /-- Split a list at every element satisfying a predicate. -/ def split_on_p {α : Type u} (P : α → Prop) [decidable_pred P] (l : list α) : list (list α) := split_on_p_aux P l id /-- Split a list at every occurrence of an element. [1,1,2,3,2,4,4].split_on 2 = [[1,1],[3],[4,4]] -/ def split_on {α : Type u} [decidable_eq α] (a : α) (as : list α) : list (list α) := as.split_on_p (=a) /-- Concatenate an element at the end of a list. concat [a, b] c = [a, b, c] -/ @[simp] def concat : list α → α → list α | [] a := [a] | (b::l) a := b :: concat l a @[simp] def head' : list α → option α | [] := none | (a :: l) := some a /-- Convert a list into an array (whose length is the length of `l`). -/ def to_array (l : list α) : array l.length α := {data := λ v, l.nth_le v.1 v.2} /-- "inhabited" `nth` function: returns `default` instead of `none` in the case that the index is out of bounds. -/ @[simp] def inth [h : inhabited α] (l : list α) (n : nat) : α := (nth l n).iget /-- Apply a function to the nth tail of `l`. Returns the input without using `f` if the index is larger than the length of the list. modify_nth_tail f 2 [a, b, c] = [a, b] ++ f [c] -/ @[simp] def modify_nth_tail (f : list α → list α) : ℕ → list α → list α | 0 l := f l | (n+1) [] := [] | (n+1) (a::l) := a :: modify_nth_tail n l /-- Apply `f` to the head of the list, if it exists. -/ @[simp] def modify_head (f : α → α) : list α → list α | [] := [] | (a::l) := f a :: l /-- Apply `f` to the nth element of the list, if it exists. -/ def modify_nth (f : α → α) : ℕ → list α → list α := modify_nth_tail (modify_head f) def insert_nth (n : ℕ) (a : α) : list α → list α := modify_nth_tail (list.cons a) n section take' variable [inhabited α] def take' : ∀ n, list α → list α | 0 l := [] | (n+1) l := l.head :: take' n l.tail end take' /-- Get the longest initial segment of the list whose members all satisfy `p`. take_while (λ x, x < 3) [0, 2, 5, 1] = [0, 2] -/ def take_while (p : α → Prop) [decidable_pred p] : list α → list α | [] := [] | (a::l) := if p a then a :: take_while l else [] /-- Fold a function `f` over the list from the left, returning the list of partial results. scanl (+) 0 [1, 2, 3] = [0, 1, 3, 6] -/ def scanl (f : α → β → α) : α → list β → list α | a [] := [a] | a (b::l) := a :: scanl (f a b) l def scanr_aux (f : α → β → β) (b : β) : list α → β × list β | [] := (b, []) | (a::l) := let (b', l') := scanr_aux l in (f a b', b' :: l') /-- Fold a function `f` over the list from the right, returning the list of partial results. scanr (+) 0 [1, 2, 3] = [6, 5, 3, 0] -/ def scanr (f : α → β → β) (b : β) (l : list α) : list β := let (b', l') := scanr_aux f b l in b' :: l' /-- Product of a list. prod [a, b, c] = ((1 * a) * b) * c -/ def prod [has_mul α] [has_one α] : list α → α := foldl (*) 1 def partition_map (f : α → β ⊕ γ) : list α → list β × list γ | [] := ([],[]) | (x::xs) := match f x with | (sum.inr r) := prod.map id (cons r) $ partition_map xs | (sum.inl l) := prod.map (cons l) id $ partition_map xs end /-- `find p l` is the first element of `l` satisfying `p`, or `none` if no such element exists. -/ def find (p : α → Prop) [decidable_pred p] : list α → option α | [] := none | (a::l) := if p a then some a else find l def find_indexes_aux (p : α → Prop) [decidable_pred p] : list α → nat → list nat | [] n := [] | (a::l) n := let t := find_indexes_aux l (succ n) in if p a then n :: t else t /-- `find_indexes p l` is the list of indexes of elements of `l` that satisfy `p`. -/ def find_indexes (p : α → Prop) [decidable_pred p] (l : list α) : list nat := find_indexes_aux p l 0 /-- `lookmap` is a combination of `lookup` and `filter_map`. `lookmap f l` will apply `f : α → option α` to each element of the list, replacing `a -> b` at the first value `a` in the list such that `f a = some b`. -/ def lookmap (f : α → option α) : list α → list α | [] := [] | (a::l) := match f a with | some b := b :: l | none := a :: lookmap l end def map_with_index_core (f : ℕ → α → β) : ℕ → list α → list β | k [] := [] | k (a::as) := f k a::(map_with_index_core (k+1) as) def map_with_index (f : ℕ → α → β) (as : list α) : list β := map_with_index_core f 0 as /-- `indexes_of a l` is the list of all indexes of `a` in `l`. indexes_of a [a, b, a, a] = [0, 2, 3] -/ def indexes_of [decidable_eq α] (a : α) : list α → list nat := find_indexes (eq a) /-- `countp p l` is the number of elements of `l` that satisfy `p`. -/ def countp (p : α → Prop) [decidable_pred p] : list α → nat | [] := 0 | (x::xs) := if p x then succ (countp xs) else countp xs /-- `count a l` is the number of occurrences of `a` in `l`. -/ def count [decidable_eq α] (a : α) : list α → nat := countp (eq a) /-- `is_prefix l₁ l₂`, or `l₁ <+: l₂`, means that `l₁` is a prefix of `l₂`, that is, `l₂` has the form `l₁ ++ t` for some `t`. -/ def is_prefix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, l₁ ++ t = l₂ /-- `is_suffix l₁ l₂`, or `l₁ <:+ l₂`, means that `l₁` is a suffix of `l₂`, that is, `l₂` has the form `t ++ l₁` for some `t`. -/ def is_suffix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, t ++ l₁ = l₂ /-- `is_infix l₁ l₂`, or `l₁ <:+: l₂`, means that `l₁` is a contiguous substring of `l₂`, that is, `l₂` has the form `s ++ l₁ ++ t` for some `s, t`. -/ def is_infix (l₁ : list α) (l₂ : list α) : Prop := ∃ s t, s ++ l₁ ++ t = l₂ infix ` <+: `:50 := is_prefix infix ` <:+ `:50 := is_suffix infix ` <:+: `:50 := is_infix /-- `inits l` is the list of initial segments of `l`. inits [1, 2, 3] = [[], [1], [1, 2], [1, 2, 3]] -/ @[simp] def inits : list α → list (list α) | [] := [[]] | (a::l) := [] :: map (λt, a::t) (inits l) /-- `tails l` is the list of terminal segments of `l`. tails [1, 2, 3] = [[1, 2, 3], [2, 3], [3], []] -/ @[simp] def tails : list α → list (list α) | [] := [[]] | (a::l) := (a::l) :: tails l def sublists'_aux : list α → (list α → list β) → list (list β) → list (list β) | [] f r := f [] :: r | (a::l) f r := sublists'_aux l f (sublists'_aux l (f ∘ cons a) r) /-- `sublists' l` is the list of all (non-contiguous) sublists of `l`. It differs from `sublists` only in the order of appearance of the sublists; `sublists'` uses the first element of the list as the MSB, `sublists` uses the first element of the list as the LSB. sublists' [1, 2, 3] = [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]] -/ def sublists' (l : list α) : list (list α) := sublists'_aux l id [] def sublists_aux : list α → (list α → list β → list β) → list β | [] f := [] | (a::l) f := f [a] (sublists_aux l (λys r, f ys (f (a :: ys) r))) /-- `sublists l` is the list of all (non-contiguous) sublists of `l`; cf. `sublists'` for a different ordering. sublists [1, 2, 3] = [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]] -/ def sublists (l : list α) : list (list α) := [] :: sublists_aux l cons def sublists_aux₁ : list α → (list α → list β) → list β | [] f := [] | (a::l) f := f [a] ++ sublists_aux₁ l (λys, f ys ++ f (a :: ys)) section forall₂ variables {r : α → β → Prop} {p : γ → δ → Prop} open relator inductive forall₂ (R : α → β → Prop) : list α → list β → Prop | nil {} : forall₂ [] [] | cons {a b l₁ l₂} : R a b → forall₂ l₁ l₂ → forall₂ (a::l₁) (b::l₂) attribute [simp] forall₂.nil end forall₂ def transpose_aux : list α → list (list α) → list (list α) | [] ls := ls | (a::i) [] := [a] :: transpose_aux i [] | (a::i) (l::ls) := (a::l) :: transpose_aux i ls /-- transpose of a list of lists, treated as a matrix. transpose [[1, 2], [3, 4], [5, 6]] = [[1, 3, 5], [2, 4, 6]] -/ def transpose : list (list α) → list (list α) | [] := [] | (l::ls) := transpose_aux l (transpose ls) /-- List of all sections through a list of lists. A section of `[L₁, L₂, ..., Lₙ]` is a list whose first element comes from `L₁`, whose second element comes from `L₂`, and so on. -/ def sections : list (list α) → list (list α) | [] := [[]] | (l::L) := bind (sections L) $ λ s, map (λ a, a::s) l section permutations def permutations_aux2 (t : α) (ts : list α) (r : list β) : list α → (list α → β) → list α × list β | [] f := (ts, r) | (y::ys) f := let (us, zs) := permutations_aux2 ys (λx : list α, f (y::x)) in (y :: us, f (t :: y :: us) :: zs) private def meas : (Σ'_:list α, list α) → ℕ × ℕ | ⟨l, i⟩ := (length l + length i, length l) local infix ` ≺ `:50 := inv_image (prod.lex (<) (<)) meas @[elab_as_eliminator] def permutations_aux.rec {C : list α → list α → Sort v} (H0 : ∀ is, C [] is) (H1 : ∀ t ts is, C ts (t::is) → C is [] → C (t::ts) is) : ∀ l₁ l₂, C l₁ l₂ | [] is := H0 is | (t::ts) is := have h1 : ⟨ts, t :: is⟩ ≺ ⟨t :: ts, is⟩, from show prod.lex _ _ (succ (length ts + length is), length ts) (succ (length ts) + length is, length (t :: ts)), by rw nat.succ_add; exact prod.lex.right _ _ (lt_succ_self _), have h2 : ⟨is, []⟩ ≺ ⟨t :: ts, is⟩, from prod.lex.left _ _ _ (lt_add_of_pos_left _ (succ_pos _)), H1 t ts is (permutations_aux.rec ts (t::is)) (permutations_aux.rec is []) using_well_founded { dec_tac := tactic.assumption, rel_tac := λ _ _, `[exact ⟨(≺), @inv_image.wf _ _ _ meas (prod.lex_wf lt_wf lt_wf)⟩] } def permutations_aux : list α → list α → list (list α) := @@permutations_aux.rec (λ _ _, list (list α)) (λ is, []) (λ t ts is IH1 IH2, foldr (λy r, (permutations_aux2 t ts r y id).2) IH1 (is :: IH2)) /-- List of all permutations of `l`. permutations [1, 2, 3] = [[1, 2, 3], [2, 1, 3], [3, 2, 1], [2, 3, 1], [3, 1, 2], [1, 3, 2]] -/ def permutations (l : list α) : list (list α) := l :: permutations_aux l [] end permutations def erasep (p : α → Prop) [decidable_pred p] : list α → list α | [] := [] | (a::l) := if p a then l else a :: erasep l def extractp (p : α → Prop) [decidable_pred p] : list α → option α × list α | [] := (none, []) | (a::l) := if p a then (some a, l) else let (a', l') := extractp l in (a', a :: l') def revzip (l : list α) : list (α × α) := zip l l.reverse /-- `product l₁ l₂` is the list of pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂`. product [1, 2] [5, 6] = [(1, 5), (1, 6), (2, 5), (2, 6)] -/ def product (l₁ : list α) (l₂ : list β) : list (α × β) := l₁.bind $ λ a, l₂.map $ prod.mk a /-- `sigma l₁ l₂` is the list of dependent pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂ a`. sigma [1, 2] (λ_, [(5 : ℕ), 6]) = [(1, 5), (1, 6), (2, 5), (2, 6)] -/ protected def sigma {σ : α → Type*} (l₁ : list α) (l₂ : Π a, list (σ a)) : list (Σ a, σ a) := l₁.bind $ λ a, (l₂ a).map $ sigma.mk a def of_fn_aux {n} (f : fin n → α) : ∀ m, m ≤ n → list α → list α | 0 h l := l | (succ m) h l := of_fn_aux m (le_of_lt h) (f ⟨m, h⟩ :: l) def of_fn {n} (f : fin n → α) : list α := of_fn_aux f n (le_refl _) [] def of_fn_nth_val {n} (f : fin n → α) (i : ℕ) : option α := if h : _ then some (f ⟨i, h⟩) else none /-- `disjoint l₁ l₂` means that `l₁` and `l₂` have no elements in common. -/ def disjoint (l₁ l₂ : list α) : Prop := ∀ ⦃a⦄, a ∈ l₁ → a ∈ l₂ → false section pairwise variables (R : α → α → Prop) /-- `pairwise R l` means that all the elements with earlier indexes are `R`-related to all the elements with later indexes. pairwise R [1, 2, 3] ↔ R 1 2 ∧ R 1 3 ∧ R 2 3 For example if `R = (≠)` then it asserts `l` has no duplicates, and if `R = (<)` then it asserts that `l` is (strictly) sorted. -/ inductive pairwise : list α → Prop | nil {} : pairwise [] | cons : ∀ {a : α} {l : list α}, (∀ a' ∈ l, R a a') → pairwise l → pairwise (a::l) variables {R} @[simp] theorem pairwise_cons {a : α} {l : list α} : pairwise R (a::l) ↔ (∀ a' ∈ l, R a a') ∧ pairwise R l := ⟨λ p, by cases p with a l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩ instance decidable_pairwise [decidable_rel R] (l : list α) : decidable (pairwise R l) := by induction l with hd tl ih; [exact is_true pairwise.nil, exactI decidable_of_iff' _ pairwise_cons] end pairwise /-- `pw_filter R l` is a maximal sublist of `l` which is `pairwise R`. `pw_filter (≠)` is the erase duplicates function (cf. `erase_dup`), and `pw_filter (<)` finds a maximal increasing subsequence in `l`. For example, pw_filter (<) [0, 1, 5, 2, 6, 3, 4] = [0, 1, 2, 3, 4] -/ def pw_filter (R : α → α → Prop) [decidable_rel R] : list α → list α | [] := [] | (x :: xs) := let IH := pw_filter xs in if ∀ y ∈ IH, R x y then x :: IH else IH section chain variable (R : α → α → Prop) /-- `chain R a l` means that `R` holds between adjacent elements of `a::l`. chain R a [b, c, d] ↔ R a b ∧ R b c ∧ R c d -/ inductive chain : α → list α → Prop | nil {} {a : α} : chain a [] | cons : ∀ {a b : α} {l : list α}, R a b → chain b l → chain a (b::l) /-- `chain' R l` means that `R` holds between adjacent elements of `l`. chain' R [a, b, c, d] ↔ R a b ∧ R b c ∧ R c d -/ def chain' : list α → Prop | [] := true | (a :: l) := chain R a l variable {R} @[simp] theorem chain_cons {a b : α} {l : list α} : chain R a (b::l) ↔ R a b ∧ chain R b l := ⟨λ p, by cases p with _ a b l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩ instance decidable_chain [decidable_rel R] (a : α) (l : list α) : decidable (chain R a l) := by induction l generalizing a; simp only [chain.nil, chain_cons]; resetI; apply_instance instance decidable_chain' [decidable_rel R] (a : α) (l : list α) : decidable (chain' R l) := by cases l; dunfold chain'; apply_instance end chain /-- `nodup l` means that `l` has no duplicates, that is, any element appears at most once in the list. It is defined as `pairwise (≠)`. -/ def nodup : list α → Prop := pairwise (≠) instance nodup_decidable [decidable_eq α] : ∀ l : list α, decidable (nodup l) := list.decidable_pairwise /-- `erase_dup l` removes duplicates from `l` (taking only the first occurrence). Defined as `pw_filter (≠)`. erase_dup [1, 0, 2, 2, 1] = [0, 2, 1] -/ def erase_dup [decidable_eq α] : list α → list α := pw_filter (≠) /-- `range' s n` is the list of numbers `[s, s+1, ..., s+n-1]`. It is intended mainly for proving properties of `range` and `iota`. -/ @[simp] def range' : ℕ → ℕ → list ℕ | s 0 := [] | s (n+1) := s :: range' (s+1) n def reduce_option {α} : list (option α) → list α := list.filter_map id def map_head {α} (f : α → α) : list α → list α | [] := [] | (x :: xs) := f x :: xs def map_last {α} (f : α → α) : list α → list α | [] := [] | [x] := [f x] | (x :: xs) := x :: map_last xs @[simp] def last' {α} : α → list α → α | a [] := a | a (b::l) := last' b l /- tfae: The Following (propositions) Are Equivalent -/ def tfae (l : list Prop) : Prop := ∀ x ∈ l, ∀ y ∈ l, x ↔ y /-- `rotate l n` rotates the elements of `l` to the left by `n` rotate [0, 1, 2, 3, 4, 5] 2 = [2, 3, 4, 5, 0, 1] -/ def rotate (l : list α) (n : ℕ) : list α := let (l₁, l₂) := list.split_at (n % l.length) l in l₂ ++ l₁ /-- rotate' is the same as `rotate`, but slower. Used for proofs about `rotate`-/ def rotate' : list α → ℕ → list α | [] n := [] | l 0 := l | (a::l) (n+1) := rotate' (l ++ [a]) n section choose variables (p : α → Prop) [decidable_pred p] (l : list α) def choose_x : Π l : list α, Π hp : (∃ a, a ∈ l ∧ p a), { a // a ∈ l ∧ p a } | [] hp := false.elim (exists.elim hp (assume a h, not_mem_nil a h.left)) | (l :: ls) hp := if pl : p l then ⟨l, ⟨or.inl rfl, pl⟩⟩ else let ⟨a, ⟨a_mem_ls, pa⟩⟩ := choose_x ls (hp.imp (λ b ⟨o, h₂⟩, ⟨o.resolve_left (λ e, pl $ e ▸ h₂), h₂⟩)) in ⟨a, ⟨or.inr a_mem_ls, pa⟩⟩ def choose (hp : ∃ a, a ∈ l ∧ p a) : α := choose_x p l hp end choose namespace func /- Definitions for using lists as finite representations of functions with domain ℕ. -/ variables [inhabited α] [inhabited β] @[simp] def set (a : α) : list α → ℕ → list α | (_::as) 0 := a::as | [] 0 := [a] | (h::as) (k+1) := h::(set as k) | [] (k+1) := (default α)::(set ([] : list α) k) @[simp] def get : ℕ → list α → α | _ [] := default α | 0 (a::as) := a | (n+1) (a::as) := get n as def equiv (as1 as2 : list α) : Prop := ∀ (m : nat), get m as1 = get m as2 def neg [has_neg α] (as : list α) := as.map (λ a, -a) @[simp] def pointwise (f : α → β → γ) : list α → list β → list γ | [] [] := [] | [] (b::bs) := map (f $ default α) (b::bs) | (a::as) [] := map (λ x, f x $ default β) (a::as) | (a::as) (b::bs) := (f a b)::(pointwise as bs) def add {α : Type u} [has_zero α] [has_add α] : list α → list α → list α := @pointwise α α α ⟨0⟩ ⟨0⟩ (+) def sub {α : Type u} [has_zero α] [has_sub α] : list α → list α → list α := @pointwise α α α ⟨0⟩ ⟨0⟩ (@has_sub.sub α _) end func end list
501446b25239a2971ba06281874dbc580277ddc3
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/cc3.lean
1c610502581712eeb22438f4a3b4b0f2973e1138
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
1,752
lean
open tactic example (a b : nat) : (a = b ↔ a = b) := by cc example (a b : nat) : (a = b) = (b = a) := by cc example (a b : nat) : (a = b) == (b = a) := by cc example (p : nat → nat → Prop) (f : nat → nat) (a b c d : nat) : p (f a) (f b) → a = c → b = d → b = c → p (f c) (f c) := by cc example (p : nat → nat → Prop) (a b c d : nat) : p a b → a = c → b = d → p c d := by cc example (p : nat → nat → Prop) (f : nat → nat) (a b c d : nat) : p (f (f (f (f (f (f a)))))) (f (f (f (f (f (f b)))))) → a = c → b = d → b = c → p (f (f (f (f (f (f c)))))) (f (f (f (f (f (f c)))))) := by cc constant R : nat → nat → Prop example (a b c : nat) : a = b → R a b → R a a := by cc example (a b c : Prop) : a = b → b = c → (a ↔ c) := by cc example (a b c : Prop) : a = b → b == c → (a ↔ c) := by cc example (a b c : nat) : a == b → b = c → a == c := by cc example (a b c : nat) : a == b → b = c → a = c := by cc example (a b c d : nat) : a == b → b == c → c == d → a = d := by cc example (a b c d : nat) : a == b → b = c → c == d → a = d := by cc example (a b c : Prop) : a = b → b = c → (a ↔ c) := by cc example (a b c : Prop) : a == b → b = c → (a ↔ c) := by cc example (a b c d : Prop) : a == b → b == c → c == d → (a ↔ d) := by cc definition foo (a b c d : Prop) : a == b → b = c → c == d → (a ↔ d) := by cc example (a b c : nat) (f : nat → nat) : a == b → b = c → f a == f c := by cc example (a b c : nat) (f : nat → nat) : a == b → b = c → f a = f c := by cc example (a b c d : nat) (f : nat → nat) : a == b → b = c → c == f d → f a = f (f d) := by cc
5de21de6e1c71dcc97b215a3e993602300a1d6de
4727251e0cd73359b15b664c3170e5d754078599
/src/ring_theory/witt_vector/identities.lean
5f30cbae076ab73343488d4c661cf42b63ee34e8
[ "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
6,584
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.witt_vector.frobenius import ring_theory.witt_vector.verschiebung import ring_theory.witt_vector.mul_p /-! ## Identities between operations on the ring of Witt vectors In this file we derive common identities between the Frobenius and Verschiebung operators. ## Main declarations * `frobenius_verschiebung`: the composition of Frobenius and Verschiebung is multiplication by `p` * `verschiebung_mul_frobenius`: the “projection formula”: `V(x * F y) = V x * y` * `iterate_verschiebung_mul_coeff`: an identity from [Haze09] 6.2 ## References * [Hazewinkel, *Witt Vectors*][Haze09] * [Commelin and Lewis, *Formalizing the Ring of Witt Vectors*][CL21] -/ namespace witt_vector variables {p : ℕ} {R : Type*} [hp : fact p.prime] [comm_ring R] local notation `𝕎` := witt_vector p -- type as `\bbW` include hp noncomputable theory /-- The composition of Frobenius and Verschiebung is multiplication by `p`. -/ lemma frobenius_verschiebung (x : 𝕎 R) : frobenius (verschiebung x) = x * p := by { ghost_calc x, ghost_simp [mul_comm] } /-- Verschiebung is the same as multiplication by `p` on the ring of Witt vectors of `zmod p`. -/ lemma verschiebung_zmod (x : 𝕎 (zmod p)) : verschiebung x = x * p := by rw [← frobenius_verschiebung, frobenius_zmodp] variables (p R) lemma coeff_p_pow [char_p R p] (i : ℕ) : (p ^ i : 𝕎 R).coeff i = 1 := begin induction i with i h, { simp only [one_coeff_zero, ne.def, pow_zero] }, { rw [pow_succ', ← frobenius_verschiebung, coeff_frobenius_char_p, verschiebung_coeff_succ, h, one_pow], } end lemma coeff_p_pow_eq_zero [char_p R p] {i j : ℕ} (hj : j ≠ i) : (p ^ i : 𝕎 R).coeff j = 0 := begin induction i with i hi generalizing j, { rw [pow_zero, one_coeff_eq_of_pos], exact nat.pos_of_ne_zero hj }, { rw [pow_succ', ← frobenius_verschiebung, coeff_frobenius_char_p], cases j, { rw [verschiebung_coeff_zero, zero_pow], exact nat.prime.pos hp.out }, { rw [verschiebung_coeff_succ, hi, zero_pow], { exact nat.prime.pos hp.out }, { exact ne_of_apply_ne (λ (j : ℕ), j.succ) hj } } } end lemma coeff_p [char_p R p] (i : ℕ) : (p : 𝕎 R).coeff i = if i = 1 then 1 else 0 := begin split_ifs with hi, { simpa only [hi, pow_one] using coeff_p_pow p R 1, }, { simpa only [pow_one] using coeff_p_pow_eq_zero p R hi, } end @[simp] lemma coeff_p_zero [char_p R p] : (p : 𝕎 R).coeff 0 = 0 := by { rw [coeff_p, if_neg], exact zero_ne_one } @[simp] lemma coeff_p_one [char_p R p] : (p : 𝕎 R).coeff 1 = 1 := by rw [coeff_p, if_pos rfl] lemma p_nonzero [nontrivial R] [char_p R p] : (p : 𝕎 R) ≠ 0 := by { intros h, simpa only [h, zero_coeff, zero_ne_one] using coeff_p_one p R } lemma fraction_ring.p_nonzero [nontrivial R] [char_p R p] : (p : fraction_ring (𝕎 R)) ≠ 0 := by simpa using (is_fraction_ring.injective (𝕎 R) (fraction_ring (𝕎 R))).ne (p_nonzero _ _) variables {p R} /-- The “projection formula” for Frobenius and Verschiebung. -/ lemma verschiebung_mul_frobenius (x y : 𝕎 R) : verschiebung (x * frobenius y) = verschiebung x * y := by { ghost_calc x y, rintro ⟨⟩; ghost_simp [mul_assoc] } lemma mul_char_p_coeff_zero [char_p R p] (x : 𝕎 R) : (x * p).coeff 0 = 0 := begin rw [← frobenius_verschiebung, coeff_frobenius_char_p, verschiebung_coeff_zero, zero_pow], exact nat.prime.pos hp.out end lemma mul_char_p_coeff_succ [char_p R p] (x : 𝕎 R) (i : ℕ) : (x * p).coeff (i + 1) = (x.coeff i)^p := by rw [← frobenius_verschiebung, coeff_frobenius_char_p, verschiebung_coeff_succ] lemma verschiebung_frobenius [char_p R p] (x : 𝕎 R) : verschiebung (frobenius x) = x * p := begin ext ⟨i⟩, { rw [mul_char_p_coeff_zero, verschiebung_coeff_zero], }, { rw [mul_char_p_coeff_succ, verschiebung_coeff_succ, coeff_frobenius_char_p], } end lemma verschiebung_frobenius_comm [char_p R p] : function.commute (verschiebung : 𝕎 R → 𝕎 R) frobenius := λ x, by rw [verschiebung_frobenius, frobenius_verschiebung] /-! ## Iteration lemmas -/ open function lemma iterate_verschiebung_coeff (x : 𝕎 R) (n k : ℕ) : (verschiebung^[n] x).coeff (k + n) = x.coeff k := begin induction n with k ih, { simp }, { rw [iterate_succ_apply', nat.add_succ, verschiebung_coeff_succ], exact ih } end lemma iterate_verschiebung_mul_left (x y : 𝕎 R) (i : ℕ) : (verschiebung^[i] x) * y = (verschiebung^[i] (x * (frobenius^[i] y))) := begin induction i with i ih generalizing y, { simp }, { rw [iterate_succ_apply', ← verschiebung_mul_frobenius, ih, iterate_succ_apply'], refl } end section char_p variable [char_p R p] lemma iterate_verschiebung_mul (x y : 𝕎 R) (i j : ℕ) : (verschiebung^[i] x) * (verschiebung^[j] y) = (verschiebung^[i + j] ((frobenius^[j] x) * (frobenius^[i] y))) := begin calc _ = (verschiebung^[i] (x * (frobenius^[i] ((verschiebung^[j] y))))) : _ ... = (verschiebung^[i] (x * (verschiebung^[j] ((frobenius^[i] y))))) : _ ... = (verschiebung^[i] ((verschiebung^[j] ((frobenius^[i] y)) * x))) : _ ... = (verschiebung^[i] ((verschiebung^[j] ((frobenius^[i] y) * (frobenius^[j] x))))) : _ ... = (verschiebung^[i + j] ((frobenius^[i] y) * (frobenius^[j] x))) : _ ... = _ : _, { apply iterate_verschiebung_mul_left }, { rw verschiebung_frobenius_comm.iterate_iterate; apply_instance }, { rw mul_comm }, { rw iterate_verschiebung_mul_left }, { rw iterate_add_apply }, { rw mul_comm } end lemma iterate_frobenius_coeff (x : 𝕎 R) (i k : ℕ) : ((frobenius^[i] x)).coeff k = (x.coeff k)^(p^i) := begin induction i with i ih, { simp }, { rw [iterate_succ_apply', coeff_frobenius_char_p, ih], ring_exp } end /-- This is a slightly specialized form of [Hazewinkel, *Witt Vectors*][Haze09] 6.2 equation 5. -/ lemma iterate_verschiebung_mul_coeff (x y : 𝕎 R) (i j : ℕ) : ((verschiebung^[i] x) * (verschiebung^[j] y)).coeff (i + j) = (x.coeff 0)^(p ^ j) * (y.coeff 0)^(p ^ i) := begin calc _ = (verschiebung^[i + j] ((frobenius^[j] x) * (frobenius^[i] y))).coeff (i + j) : _ ... = ((frobenius^[j] x) * (frobenius^[i] y)).coeff 0 : _ ... = (frobenius^[j] x).coeff 0 * ((frobenius^[i] y)).coeff 0 : _ ... = _ : _, { rw iterate_verschiebung_mul }, { convert iterate_verschiebung_coeff _ _ _ using 2, rw zero_add }, { apply mul_coeff_zero }, { simp only [iterate_frobenius_coeff] } end end char_p end witt_vector
b88be8868bc0f86066a5522a99a29771b61fd2f6
a721fe7446524f18ba361625fc01033d9c8b7a78
/src/principia/myset/finite.lean
a699bb0e09a45ccc3c4b04aa3000c1dfd6924f5f
[]
no_license
Sterrs/leaning
8fd80d1f0a6117a220bb2e57ece639b9a63deadc
3901cc953694b33adda86cb88ca30ba99594db31
refs/heads/master
1,627,023,822,744
1,616,515,221,000
1,616,515,221,000
245,512,190
2
0
null
1,616,429,050,000
1,583,527,118,000
Lean
UTF-8
Lean
false
false
5,411
lean
-- vim: ts=2 sw=0 sts=-1 et ai tw=70 import ..mynat.lt import .equinumerous import ..mylist.map -- Definitions and theorems relating to finite sets namespace hidden namespace myset universes u variable {α : Type u} open myset open mynat -- Exclude the actual value so there are m elements def zero_to (m : mynat) : myset mynat := λ n, n < m theorem emp_zero_to_zero : empty (zero_to 0) := begin intro m, assume hm, from lt_nzero hm, end def of_size (s : myset α) (m : mynat) : Prop := equinumerous s (zero_to m) def finite (s : myset α) : Prop := ∃ m : mynat, of_size s m def infinite (s : myset α) : Prop := ¬finite s theorem zero_to_le_subset (m n: mynat) (h: m ≤ n): (zero_to m) ⊆ (zero_to n) := (λ k h', @lt_le_chain k n m h' h) -- function swapping two naturals. Useful in proving things -- by induction on finite sets def swap_naturals (a b x: mynat): mynat := if x = a then b else if x = b then a else x theorem swap_well_defined (n a b: mynat) (ha: a < n) (hb: b < n): well_defined (zero_to n) (zero_to n) (swap_naturals a b) := begin intro x, assume hx, unfold swap_naturals, by_cases hxa: x = a, { rw if_pos hxa, from hb, }, { rw if_neg hxa, by_cases hxb: x = b, { rw if_pos hxb, from ha, }, { rw if_neg hxb, from hx, }, }, end -- candidate for wlog_le? It's not clear because -- we can have a = b theorem swap_injective (n a b: mynat) (ha: a < n) (hb: b < n): injective (swap_well_defined n a b ha hb) := begin intros x y, assume hx hy, unfold swap_naturals, assume hswap_xy, by_cases hxy: x = y, { assumption, }, { exfalso, by_cases hxa: x = a, { rw if_pos hxa at hswap_xy, by_cases hya: y = a, { from hxy (eq.trans hxa hya.symm), }, { rw if_neg hya at hswap_xy, by_cases hyb: y = b, { rw if_pos hyb at hswap_xy, from hya (hswap_xy ▸ hyb), }, { rw if_neg hyb at hswap_xy, from hyb hswap_xy.symm, }, }, }, { rw if_neg hxa at hswap_xy, by_cases hxb: x = b, { rw if_pos hxb at hswap_xy, by_cases hya: y = a, { rw if_pos hya at hswap_xy, from (hswap_xy ▸ hxa) hxb, }, { rw if_neg hya at hswap_xy, by_cases hyb: y = b, { from (hyb ▸ hxy) hxb, }, { rw if_neg hyb at hswap_xy, from hya hswap_xy.symm, }, }, }, { rw if_neg hxb at hswap_xy, by_cases hya: y = a, { rw if_pos hya at hswap_xy, from hxb hswap_xy, }, { rw if_neg hya at hswap_xy, by_cases hyb: y = b, { rw if_pos hyb at hswap_xy, from hxa hswap_xy, }, { rw if_neg hyb at hswap_xy, from hxy hswap_xy, }, }, }, }, }, end -- pigeonhole principle, basically -- have I overthought this? -- and can this be done without classical? probably.. theorem no_injection_from_zero_to_succ (n: mynat) (f: mynat → mynat) (hwf: well_defined (zero_to (n + 1)) (zero_to n) f): ¬injective hwf := begin assume h, revert f, induction n with n hn, { intro f, assume hwf, exfalso, revert hwf, apply @no_wdefined_func_nemp_to_emp _ _ (zero_to 1) (zero_to 0) f, { assume h, have : (0 : mynat) ∈ zero_to 1, { from zero_lt_one, }, from h 0 this, }, { from emp_zero_to_zero, }, }, { -- we are trying to show that if -- f: {0, ..., n + 1} → {0, ..., n} -- is well-defined then it is not injective. -- Consider the pre-image of n. By injectivity, this at most one -- number. If it's empty, skip to the restriction. -- If not, call it x. Define f': {0, ..., n + 1} → {0, ..., n} -- by composing f with the function swapping n + 1 and x. This -- function is still injective and has n + 1 ↦ n, so we can -- restrict it to {0, ..., n} and its range will restrict to -- {0, ..., n - 1}. Then we are done by induction. sorry, }, end theorem no_injection_if_gt (m n: mynat) (f: mynat → mynat) (hmn: n < m) (hwf: well_defined (zero_to m) (zero_to n) f): ¬injective hwf := begin assume hif, cases m, { from lt_nzero hmn, }, { have hwf': well_defined (zero_to (succ m)) (zero_to m) f, { apply wf_by_inclusion (zero_to (succ m)) (zero_to n) (zero_to m) hwf, from zero_to_le_subset _ _ (le_iff_lt_succ.mpr hmn), }, have hif': injective hwf' := hif, from no_injection_from_zero_to_succ _ _ _ hif', }, end theorem equinum_zero_to_iff_eq {m n : mynat} : equinumerous (zero_to m) (zero_to n) → m = n := sorry -- A set cannot have two different natural sizes theorem unique_size {α : Type u} (s : myset α) (m n : mynat) : of_size s m → of_size s n → m = n := begin assume hm hn, unfold of_size at hm hn, have hm₂ := equinumerous_symm _ _ hm, have h := equinumerous_trans _ _ _ hm₂ hn, from equinum_zero_to_iff_eq h, end theorem naturals_infinite: infinite (all_of mynat) := begin assume hfinite, cases hfinite with n hn, cases hn with f hf, cases hf with hwf h, sorry, end theorem inf_iff_powerset_inf (s : myset α): infinite s ↔ infinite (power_set s) := begin split; assume hinf, { sorry, }, { sorry, }, end end myset end hidden
ca6ed510254e7166b39d741abc51fd5daf42d120
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/contra2.lean
f591521703f1aa7b9e761ec6e9641b6cacd487d3
[ "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
495
lean
open nat tactic example (q p : Prop) (h₁ : p) (h₂ : ¬ p) : q := by contradiction example (q p : Prop) (h₁ : p) (h₂ : p → false) : q := by do intros, contradiction example (q : Prop) (a b : nat) (h₁ : a + b = 0) (h₂ : ¬ a + b = 0) : q := by do intros, contradiction example (q : Prop) (a b : nat) (h₁ : a + b = 0) (h₂ : a + b ≠ 0) : q := by do intros, contradiction example (q : Prop) (a b : nat) (h₁ : a + b = 0) (h₂ : a + b = 0 → false) : q := by contradiction
0af368aabbc4fffcceaacdf9940b463e533d2f05
df561f413cfe0a88b1056655515399c546ff32a5
/4-proposition-world/l6.lean
b358908c54eae74addde993f7cef52e7b4eccd78
[]
no_license
nicholaspun/natural-number-game-solutions
31d5158415c6f582694680044c5c6469032c2a06
1e2aed86d2e76a3f4a275c6d99e795ad30cf6df0
refs/heads/main
1,675,123,625,012
1,607,633,548,000
1,607,633,548,000
318,933,860
3
1
null
null
null
null
UTF-8
Lean
false
false
129
lean
example (P Q R : Prop) : (P → (Q → R)) → ((P → Q) → (P → R)) := begin intros f g p, apply f, exact p, exact g(p), end
4819b28161f9f467880dfc2daad53d33a52d9069
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/algebra/big_operators/basic.lean
213165414598fac094b601bea1e1bf14ea75fccd
[ "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
62,705
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import algebra.group.pi import data.equiv.mul_add import data.finset.fold import data.fintype.basic import data.set.pairwise /-! # Big operators In this file we define products and sums indexed by finite sets (specifically, `finset`). ## Notation We introduce the following notation, localized in `big_operators`. To enable the notation, use `open_locale big_operators`. Let `s` be a `finset α`, and `f : α → β` a function. * `∏ x in s, f x` is notation for `finset.prod s f` (assuming `β` is a `comm_monoid`) * `∑ x in s, f x` is notation for `finset.sum s f` (assuming `β` is an `add_comm_monoid`) * `∏ x, f x` is notation for `finset.prod finset.univ f` (assuming `α` is a `fintype` and `β` is a `comm_monoid`) * `∑ x, f x` is notation for `finset.sum finset.univ f` (assuming `α` is a `fintype` and `β` is an `add_comm_monoid`) ## Implementation Notes The first arguments in all definitions and lemmas is the codomain of the function of the big operator. This is necessary for the heuristic in `@[to_additive]`. See the documentation of `to_additive.attr` for more information. -/ universes u v w variables {β : Type u} {α : Type v} {γ : Type w} namespace finset /-- `∏ x in s, f x` is the product of `f x` as `x` ranges over the elements of the finite set `s`. -/ @[to_additive "`∑ x in s, f x` is the sum of `f x` as `x` ranges over the elements of the finite set `s`."] protected def prod [comm_monoid β] (s : finset α) (f : α → β) : β := (s.1.map f).prod @[simp, to_additive] lemma prod_mk [comm_monoid β] (s : multiset α) (hs : s.nodup) (f : α → β) : (⟨s, hs⟩ : finset α).prod f = (s.map f).prod := rfl end finset /-- There is no established mathematical convention for the operator precedence of big operators like `∏` and `∑`. We will have to make a choice. Online discussions, such as https://math.stackexchange.com/q/185538/30839 seem to suggest that `∏` and `∑` should have the same precedence, and that this should be somewhere between `*` and `+`. The latter have precedence levels `70` and `65` respectively, and we therefore choose the level `67`. In practice, this means that parentheses should be placed as follows: ```lean ∑ k in K, (a k + b k) = ∑ k in K, a k + ∑ k in K, b k → ∏ k in K, a k * b k = (∏ k in K, a k) * (∏ k in K, b k) ``` (Example taken from page 490 of Knuth's *Concrete Mathematics*.) -/ library_note "operator precedence of big operators" localized "notation `∑` binders `, ` r:(scoped:67 f, finset.sum finset.univ f) := r" in big_operators localized "notation `∏` binders `, ` r:(scoped:67 f, finset.prod finset.univ f) := r" in big_operators localized "notation `∑` binders ` in ` s `, ` r:(scoped:67 f, finset.sum s f) := r" in big_operators localized "notation `∏` binders ` in ` s `, ` r:(scoped:67 f, finset.prod s f) := r" in big_operators open_locale big_operators namespace finset variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} @[to_additive] lemma prod_eq_multiset_prod [comm_monoid β] (s : finset α) (f : α → β) : ∏ x in s, f x = (s.1.map f).prod := rfl @[to_additive] theorem prod_eq_fold [comm_monoid β] (s : finset α) (f : α → β) : ∏ x in s, f x = s.fold (*) 1 f := rfl @[simp] lemma sum_multiset_singleton (s : finset α) : s.sum (λ x, {x}) = s.val := by simp only [sum_eq_multiset_sum, multiset.sum_map_singleton] end finset @[to_additive] lemma monoid_hom.map_prod [comm_monoid β] [comm_monoid γ] (g : β →* γ) (f : α → β) (s : finset α) : g (∏ x in s, f x) = ∏ x in s, g (f x) := by simp only [finset.prod_eq_multiset_prod, g.map_multiset_prod, multiset.map_map] @[to_additive] lemma mul_equiv.map_prod [comm_monoid β] [comm_monoid γ] (g : β ≃* γ) (f : α → β) (s : finset α) : g (∏ x in s, f x) = ∏ x in s, g (f x) := g.to_monoid_hom.map_prod f s lemma ring_hom.map_list_prod [semiring β] [semiring γ] (f : β →+* γ) (l : list β) : f l.prod = (l.map f).prod := f.to_monoid_hom.map_list_prod l lemma ring_hom.map_list_sum [non_assoc_semiring β] [non_assoc_semiring γ] (f : β →+* γ) (l : list β) : f l.sum = (l.map f).sum := f.to_add_monoid_hom.map_list_sum l /-- A morphism into the opposite ring acts on the product by acting on the reversed elements -/ lemma ring_hom.unop_map_list_prod [semiring β] [semiring γ] (f : β →+* γᵒᵖ) (l : list β) : opposite.unop (f l.prod) = (l.map (opposite.unop ∘ f)).reverse.prod := f.to_monoid_hom.unop_map_list_prod l lemma ring_hom.map_multiset_prod [comm_semiring β] [comm_semiring γ] (f : β →+* γ) (s : multiset β) : f s.prod = (s.map f).prod := f.to_monoid_hom.map_multiset_prod s lemma ring_hom.map_multiset_sum [non_assoc_semiring β] [non_assoc_semiring γ] (f : β →+* γ) (s : multiset β) : f s.sum = (s.map f).sum := f.to_add_monoid_hom.map_multiset_sum s lemma ring_hom.map_prod [comm_semiring β] [comm_semiring γ] (g : β →+* γ) (f : α → β) (s : finset α) : g (∏ x in s, f x) = ∏ x in s, g (f x) := g.to_monoid_hom.map_prod f s lemma ring_hom.map_sum [non_assoc_semiring β] [non_assoc_semiring γ] (g : β →+* γ) (f : α → β) (s : finset α) : g (∑ x in s, f x) = ∑ x in s, g (f x) := g.to_add_monoid_hom.map_sum f s @[to_additive] lemma monoid_hom.coe_prod [mul_one_class β] [comm_monoid γ] (f : α → β →* γ) (s : finset α) : ⇑(∏ x in s, f x) = ∏ x in s, f x := (monoid_hom.coe_fn β γ).map_prod _ _ -- See also `finset.prod_apply`, with the same conclusion -- but with the weaker hypothesis `f : α → β → γ`. @[simp, to_additive] lemma monoid_hom.finset_prod_apply [mul_one_class β] [comm_monoid γ] (f : α → β →* γ) (s : finset α) (b : β) : (∏ x in s, f x) b = ∏ x in s, f x b := (monoid_hom.eval b).map_prod _ _ variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} namespace finset section comm_monoid variables [comm_monoid β] @[simp, to_additive] lemma prod_empty {f : α → β} : (∏ x in (∅:finset α), f x) = 1 := rfl @[simp, to_additive] lemma prod_cons (h : a ∉ s) : (∏ x in (cons a s h), f x) = f a * ∏ x in s, f x := fold_cons h @[simp, to_additive] lemma prod_insert [decidable_eq α] : a ∉ s → (∏ x in (insert a s), f x) = f a * ∏ x in s, f x := fold_insert /-- The product of `f` over `insert a s` is the same as the product over `s`, as long as `a` is in `s` or `f a = 1`. -/ @[simp, to_additive "The sum of `f` over `insert a s` is the same as the sum over `s`, as long as `a` is in `s` or `f a = 0`."] lemma prod_insert_of_eq_one_if_not_mem [decidable_eq α] (h : a ∉ s → f a = 1) : ∏ x in insert a s, f x = ∏ x in s, f x := begin by_cases hm : a ∈ s, { simp_rw insert_eq_of_mem hm }, { rw [prod_insert hm, h hm, one_mul] }, end /-- The product of `f` over `insert a s` is the same as the product over `s`, as long as `f a = 1`. -/ @[simp, to_additive "The sum of `f` over `insert a s` is the same as the sum over `s`, as long as `f a = 0`."] lemma prod_insert_one [decidable_eq α] (h : f a = 1) : ∏ x in insert a s, f x = ∏ x in s, f x := prod_insert_of_eq_one_if_not_mem (λ _, h) @[simp, to_additive] lemma prod_singleton : (∏ x in (singleton a), f x) = f a := eq.trans fold_singleton $ mul_one _ @[to_additive] lemma prod_pair [decidable_eq α] {a b : α} (h : a ≠ b) : (∏ x in ({a, b} : finset α), f x) = f a * f b := by rw [prod_insert (not_mem_singleton.2 h), prod_singleton] @[simp, priority 1100, to_additive] lemma prod_const_one : (∏ x in s, (1 : β)) = 1 := by simp only [finset.prod, multiset.map_const, multiset.prod_repeat, one_pow] @[simp, to_additive] lemma prod_image [decidable_eq α] {s : finset γ} {g : γ → α} : (∀ x ∈ s, ∀ y ∈ s, g x = g y → x = y) → (∏ x in (s.image g), f x) = ∏ x in s, f (g x) := fold_image @[simp, to_additive] lemma prod_map (s : finset α) (e : α ↪ γ) (f : γ → β) : (∏ x in (s.map e), f x) = ∏ x in s, f (e x) := by rw [finset.prod, finset.map_val, multiset.map_map]; refl @[congr, to_additive] lemma prod_congr (h : s₁ = s₂) : (∀ x ∈ s₂, f x = g x) → s₁.prod f = s₂.prod g := by rw [h]; exact fold_congr attribute [congr] finset.sum_congr @[to_additive] lemma prod_union_inter [decidable_eq α] : (∏ x in (s₁ ∪ s₂), f x) * (∏ x in (s₁ ∩ s₂), f x) = (∏ x in s₁, f x) * (∏ x in s₂, f x) := fold_union_inter @[to_additive] lemma prod_union [decidable_eq α] (h : disjoint s₁ s₂) : (∏ x in (s₁ ∪ s₂), f x) = (∏ x in s₁, f x) * (∏ x in s₂, f x) := by rw [←prod_union_inter, (disjoint_iff_inter_eq_empty.mp h)]; exact (mul_one _).symm @[to_additive] lemma prod_filter_mul_prod_filter_not (s : finset α) (p : α → Prop) [decidable_pred p] [decidable_pred (λ x, ¬p x)] (f : α → β) : (∏ x in s.filter p, f x) * (∏ x in s.filter (λ x, ¬p x), f x) = ∏ x in s, f x := begin haveI := classical.dec_eq α, rw [← prod_union (filter_inter_filter_neg_eq p s).le, filter_union_filter_neg_eq] end end comm_monoid end finset section open finset variables [fintype α] [decidable_eq α] [comm_monoid β] @[to_additive] lemma is_compl.prod_mul_prod {s t : finset α} (h : is_compl s t) (f : α → β) : (∏ i in s, f i) * (∏ i in t, f i) = ∏ i, f i := (finset.prod_union h.disjoint).symm.trans $ by rw [← finset.sup_eq_union, h.sup_eq_top]; refl end namespace finset section comm_monoid variables [comm_monoid β] /-- Multiplying the products of a function over `s` and over `sᶜ` gives the whole product. For a version expressed with subtypes, see `fintype.prod_subtype_mul_prod_subtype`. -/ @[to_additive "Adding the sums of a function over `s` and over `sᶜ` gives the whole sum. For a version expressed with subtypes, see `fintype.sum_subtype_add_sum_subtype`. "] lemma prod_mul_prod_compl [fintype α] [decidable_eq α] (s : finset α) (f : α → β) : (∏ i in s, f i) * (∏ i in sᶜ, f i) = ∏ i, f i := is_compl_compl.prod_mul_prod f @[to_additive] lemma prod_compl_mul_prod [fintype α] [decidable_eq α] (s : finset α) (f : α → β) : (∏ i in sᶜ, f i) * (∏ i in s, f i) = ∏ i, f i := is_compl_compl.symm.prod_mul_prod f @[to_additive] lemma prod_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) : (∏ x in (s₂ \ s₁), f x) * (∏ x in s₁, f x) = (∏ x in s₂, f x) := by rw [←prod_union sdiff_disjoint, sdiff_union_of_subset h] @[simp, to_additive] lemma prod_sum_elim [decidable_eq (α ⊕ γ)] (s : finset α) (t : finset γ) (f : α → β) (g : γ → β) : ∏ x in s.map function.embedding.inl ∪ t.map function.embedding.inr, sum.elim f g x = (∏ x in s, f x) * (∏ x in t, g x) := begin rw [prod_union, prod_map, prod_map], { simp only [sum.elim_inl, function.embedding.inl_apply, function.embedding.inr_apply, sum.elim_inr] }, { simp only [disjoint_left, finset.mem_map, finset.mem_map], rintros _ ⟨i, hi, rfl⟩ ⟨j, hj, H⟩, cases H } end @[to_additive] lemma prod_bUnion [decidable_eq α] {s : finset γ} {t : γ → finset α} (hs : set.pairwise_disjoint ↑s t) : (∏ x in (s.bUnion t), f x) = ∏ x in s, ∏ i in t x, f i := begin haveI := classical.dec_eq γ, induction s using finset.induction_on with x s hxs ih hd, { simp_rw [bUnion_empty, prod_empty] }, { simp_rw [coe_insert, set.pairwise_disjoint_insert, mem_coe] at hs, have : disjoint (t x) (finset.bUnion s t), { exact (disjoint_bUnion_right _ _ _).mpr (λ y hy, hs.2 y hy $ λ H, hxs $ H.substr hy) }, rw [bUnion_insert, prod_insert hxs, prod_union this, ih hs.1] } end @[to_additive] lemma prod_product {s : finset γ} {t : finset α} {f : γ×α → β} : (∏ x in s.product t, f x) = ∏ x in s, ∏ y in t, f (x, y) := begin haveI := classical.dec_eq α, haveI := classical.dec_eq γ, rw [product_eq_bUnion, prod_bUnion], { congr, funext, exact prod_image (λ _ _ _ _ H, (prod.mk.inj H).2) }, simp only [disjoint_iff_ne, mem_image], rintro x _ y _ h ⟨i, z⟩ hz, rw [inf_eq_inter, mem_inter, mem_image, mem_image] at hz, obtain ⟨⟨_, _, rfl, _⟩, _, _, rfl, _⟩ := hz, exact h rfl, end /-- An uncurried version of `finset.prod_product`. -/ @[to_additive "An uncurried version of `finset.sum_product`"] lemma prod_product' {s : finset γ} {t : finset α} {f : γ → α → β} : (∏ x in s.product t, f x.1 x.2) = ∏ x in s, ∏ y in t, f x y := prod_product /-- Product over a sigma type equals the product of fiberwise products. For rewriting in the reverse direction, use `finset.prod_sigma'`. -/ @[to_additive "Sum over a sigma type equals the sum of fiberwise sums. For rewriting in the reverse direction, use `finset.sum_sigma'`"] lemma prod_sigma {σ : α → Type*} (s : finset α) (t : Π a, finset (σ a)) (f : sigma σ → β) : (∏ x in s.sigma t, f x) = ∏ a in s, ∏ s in (t a), f ⟨a, s⟩ := by classical; calc (∏ x in s.sigma t, f x) = ∏ x in s.bUnion (λ a, (t a).map (function.embedding.sigma_mk a)), f x : by rw sigma_eq_bUnion ... = ∏ a in s, ∏ x in (t a).map (function.embedding.sigma_mk a), f x : prod_bUnion $ assume a₁ ha a₂ ha₂ h x hx, by { simp only [inf_eq_inter, mem_inter, mem_map, function.embedding.sigma_mk_apply] at hx, rcases hx with ⟨⟨y, hy, rfl⟩, ⟨z, hz, hz'⟩⟩, cc } ... = ∏ a in s, ∏ s in t a, f ⟨a, s⟩ : prod_congr rfl $ λ _ _, prod_map _ _ _ @[to_additive] lemma prod_sigma' {σ : α → Type*} (s : finset α) (t : Π a, finset (σ a)) (f : Π a, σ a → β) : (∏ a in s, ∏ s in (t a), f a s) = ∏ x in s.sigma t, f x.1 x.2 := eq.symm $ prod_sigma s t (λ x, f x.1 x.2) @[to_additive] lemma prod_fiberwise_of_maps_to [decidable_eq γ] {s : finset α} {t : finset γ} {g : α → γ} (h : ∀ x ∈ s, g x ∈ t) (f : α → β) : (∏ y in t, ∏ x in s.filter (λ x, g x = y), f x) = ∏ x in s, f x := begin letI := classical.dec_eq α, rw [← bUnion_filter_eq_of_maps_to h] {occs := occurrences.pos [2]}, refine (prod_bUnion $ λ x' hx y' hy hne, _).symm, rw [function.on_fun, disjoint_filter], rintros x hx rfl, exact hne end @[to_additive] lemma prod_image' [decidable_eq α] {s : finset γ} {g : γ → α} (h : γ → β) (eq : ∀ c ∈ s, f (g c) = ∏ x in s.filter (λ c', g c' = g c), h x) : (∏ x in s.image g, f x) = ∏ x in s, h x := calc (∏ x in s.image g, f x) = ∏ x in s.image g, ∏ x in s.filter (λ c', g c' = x), h x : prod_congr rfl $ λ x hx, let ⟨c, hcs, hc⟩ := mem_image.1 hx in hc ▸ (eq c hcs) ... = ∏ x in s, h x : prod_fiberwise_of_maps_to (λ x, mem_image_of_mem g) _ @[to_additive] lemma prod_mul_distrib : ∏ x in s, (f x * g x) = (∏ x in s, f x) * (∏ x in s, g x) := eq.trans (by rw one_mul; refl) fold_op_distrib @[to_additive] lemma prod_comm {s : finset γ} {t : finset α} {f : γ → α → β} : (∏ x in s, ∏ y in t, f x y) = (∏ y in t, ∏ x in s, f x y) := begin classical, apply finset.induction_on s, { simp only [prod_empty, prod_const_one] }, { intros _ _ H ih, simp only [prod_insert H, prod_mul_distrib, ih] } end @[to_additive] lemma prod_hom_rel [comm_monoid γ] {r : β → γ → Prop} {f : α → β} {g : α → γ} {s : finset α} (h₁ : r 1 1) (h₂ : ∀ a b c, r b c → r (f a * b) (g a * c)) : r (∏ x in s, f x) (∏ x in s, g x) := by { delta finset.prod, apply multiset.prod_hom_rel; assumption } @[to_additive] lemma prod_eq_one {f : α → β} {s : finset α} (h : ∀ x ∈ s, f x = 1) : (∏ x in s, f x) = 1 := calc (∏ x in s, f x) = ∏ x in s, 1 : finset.prod_congr rfl h ... = 1 : finset.prod_const_one @[to_additive] lemma prod_subset_one_on_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) (hg : ∀ x ∈ (s₂ \ s₁), g x = 1) (hfg : ∀ x ∈ s₁, f x = g x) : ∏ i in s₁, f i = ∏ i in s₂, g i := begin rw [← prod_sdiff h, prod_eq_one hg, one_mul], exact prod_congr rfl hfg end @[to_additive] lemma prod_subset (h : s₁ ⊆ s₂) (hf : ∀ x ∈ s₂, x ∉ s₁ → f x = 1) : (∏ x in s₁, f x) = ∏ x in s₂, f x := by haveI := classical.dec_eq α; exact prod_subset_one_on_sdiff h (by simpa) (λ _ _, rfl) @[to_additive] lemma prod_filter_of_ne {p : α → Prop} [decidable_pred p] (hp : ∀ x ∈ s, f x ≠ 1 → p x) : (∏ x in (s.filter p), f x) = (∏ x in s, f x) := prod_subset (filter_subset _ _) $ λ x, by { classical, rw [not_imp_comm, mem_filter], exact λ h₁ h₂, ⟨h₁, hp _ h₁ h₂⟩ } -- If we use `[decidable_eq β]` here, some rewrites fail because they find a wrong `decidable` -- instance first; `{∀ x, decidable (f x ≠ 1)}` doesn't work with `rw ← prod_filter_ne_one` @[to_additive] lemma prod_filter_ne_one [∀ x, decidable (f x ≠ 1)] : (∏ x in (s.filter $ λ x, f x ≠ 1), f x) = (∏ x in s, f x) := prod_filter_of_ne $ λ _ _, id @[to_additive] lemma prod_filter (p : α → Prop) [decidable_pred p] (f : α → β) : (∏ a in s.filter p, f a) = (∏ a in s, if p a then f a else 1) := calc (∏ a in s.filter p, f a) = ∏ a in s.filter p, if p a then f a else 1 : prod_congr rfl (assume a h, by rw [if_pos (mem_filter.1 h).2]) ... = ∏ a in s, if p a then f a else 1 : begin refine prod_subset (filter_subset _ s) (assume x hs h, _), rw [mem_filter, not_and] at h, exact if_neg (h hs) end @[to_additive] lemma prod_eq_single_of_mem {s : finset α} {f : α → β} (a : α) (h : a ∈ s) (h₀ : ∀ b ∈ s, b ≠ a → f b = 1) : (∏ x in s, f x) = f a := begin haveI := classical.dec_eq α, calc (∏ x in s, f x) = ∏ x in {a}, f x : begin refine (prod_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { simpa only [mem_singleton] } end ... = f a : prod_singleton end @[to_additive] lemma prod_eq_single {s : finset α} {f : α → β} (a : α) (h₀ : ∀ b ∈ s, b ≠ a → f b = 1) (h₁ : a ∉ s → f a = 1) : (∏ x in s, f x) = f a := by haveI := classical.dec_eq α; from classical.by_cases (assume : a ∈ s, prod_eq_single_of_mem a this h₀) (assume : a ∉ s, (prod_congr rfl $ λ b hb, h₀ b hb $ by rintro rfl; cc).trans $ prod_const_one.trans (h₁ this).symm) @[to_additive] lemma prod_eq_mul_of_mem {s : finset α} {f : α → β} (a b : α) (ha : a ∈ s) (hb : b ∈ s) (hn : a ≠ b) (h₀ : ∀ c ∈ s, c ≠ a ∧ c ≠ b → f c = 1) : (∏ x in s, f x) = (f a) * (f b) := begin haveI := classical.dec_eq α; let s' := ({a, b} : finset α), have hu : s' ⊆ s, { refine insert_subset.mpr _, apply and.intro ha, apply singleton_subset_iff.mpr hb }, have hf : ∀ c ∈ s, c ∉ s' → f c = 1, { intros c hc hcs, apply h₀ c hc, apply not_or_distrib.mp, intro hab, apply hcs, apply mem_insert.mpr, rw mem_singleton, exact hab }, rw ←prod_subset hu hf, exact finset.prod_pair hn end @[to_additive] lemma prod_eq_mul {s : finset α} {f : α → β} (a b : α) (hn : a ≠ b) (h₀ : ∀ c ∈ s, c ≠ a ∧ c ≠ b → f c = 1) (ha : a ∉ s → f a = 1) (hb : b ∉ s → f b = 1) : (∏ x in s, f x) = (f a) * (f b) := begin haveI := classical.dec_eq α; by_cases h₁ : a ∈ s; by_cases h₂ : b ∈ s, { exact prod_eq_mul_of_mem a b h₁ h₂ hn h₀ }, { rw [hb h₂, mul_one], apply prod_eq_single_of_mem a h₁, exact λ c hc hca, h₀ c hc ⟨hca, ne_of_mem_of_not_mem hc h₂⟩ }, { rw [ha h₁, one_mul], apply prod_eq_single_of_mem b h₂, exact λ c hc hcb, h₀ c hc ⟨ne_of_mem_of_not_mem hc h₁, hcb⟩ }, { rw [ha h₁, hb h₂, mul_one], exact trans (prod_congr rfl (λ c hc, h₀ c hc ⟨ne_of_mem_of_not_mem hc h₁, ne_of_mem_of_not_mem hc h₂⟩)) prod_const_one } end @[to_additive] lemma prod_attach {f : α → β} : (∏ x in s.attach, f x) = (∏ x in s, f x) := by haveI := classical.dec_eq α; exact calc (∏ x in s.attach, f x.val) = (∏ x in (s.attach).image subtype.val, f x) : by rw [prod_image]; exact assume x _ y _, subtype.eq ... = _ : by rw [attach_image_val] /-- A product over `s.subtype p` equals one over `s.filter p`. -/ @[simp, to_additive "A sum over `s.subtype p` equals one over `s.filter p`."] lemma prod_subtype_eq_prod_filter (f : α → β) {p : α → Prop} [decidable_pred p] : ∏ x in s.subtype p, f x = ∏ x in s.filter p, f x := begin conv_lhs { erw ←prod_map (s.subtype p) (function.embedding.subtype _) f }, exact prod_congr (subtype_map _) (λ x hx, rfl) end /-- If all elements of a `finset` satisfy the predicate `p`, a product over `s.subtype p` equals that product over `s`. -/ @[to_additive "If all elements of a `finset` satisfy the predicate `p`, a sum over `s.subtype p` equals that sum over `s`."] lemma prod_subtype_of_mem (f : α → β) {p : α → Prop} [decidable_pred p] (h : ∀ x ∈ s, p x) : ∏ x in s.subtype p, f x = ∏ x in s, f x := by simp_rw [prod_subtype_eq_prod_filter, filter_true_of_mem h] /-- A product of a function over a `finset` in a subtype equals a product in the main type of a function that agrees with the first function on that `finset`. -/ @[to_additive "A sum of a function over a `finset` in a subtype equals a sum in the main type of a function that agrees with the first function on that `finset`."] lemma prod_subtype_map_embedding {p : α → Prop} {s : finset {x // p x}} {f : {x // p x} → β} {g : α → β} (h : ∀ x : {x // p x}, x ∈ s → g x = f x) : ∏ x in s.map (function.embedding.subtype _), g x = ∏ x in s, f x := begin rw finset.prod_map, exact finset.prod_congr rfl h end @[to_additive] lemma prod_finset_coe (f : α → β) (s : finset α) : ∏ (i : (s : set α)), f i = ∏ i in s, f i := prod_attach @[to_additive] lemma prod_subtype {p : α → Prop} {F : fintype (subtype p)} (s : finset α) (h : ∀ x, x ∈ s ↔ p x) (f : α → β) : ∏ a in s, f a = ∏ a : subtype p, f a := have (∈ s) = p, from set.ext h, by { substI p, rw [←prod_finset_coe], congr } @[to_additive] lemma prod_apply_dite {s : finset α} {p : α → Prop} {hp : decidable_pred p} [decidable_pred (λ x, ¬ p x)] (f : Π (x : α), p x → γ) (g : Π (x : α), ¬p x → γ) (h : γ → β) : (∏ x in s, h (if hx : p x then f x hx else g x hx)) = (∏ x in (s.filter p).attach, h (f x.1 (mem_filter.mp x.2).2)) * (∏ x in (s.filter (λ x, ¬ p x)).attach, h (g x.1 (mem_filter.mp x.2).2)) := calc ∏ x in s, h (if hx : p x then f x hx else g x hx) = (∏ x in s.filter p, h (if hx : p x then f x hx else g x hx)) * (∏ x in s.filter (λ x, ¬ p x), h (if hx : p x then f x hx else g x hx)) : (prod_filter_mul_prod_filter_not s p _).symm ... = (∏ x in (s.filter p).attach, h (if hx : p x.1 then f x.1 hx else g x.1 hx)) * (∏ x in (s.filter (λ x, ¬ p x)).attach, h (if hx : p x.1 then f x.1 hx else g x.1 hx)) : congr_arg2 _ prod_attach.symm prod_attach.symm ... = (∏ x in (s.filter p).attach, h (f x.1 (mem_filter.mp x.2).2)) * (∏ x in (s.filter (λ x, ¬ p x)).attach, h (g x.1 (mem_filter.mp x.2).2)) : congr_arg2 _ (prod_congr rfl (λ x hx, congr_arg h (dif_pos (mem_filter.mp x.2).2))) (prod_congr rfl (λ x hx, congr_arg h (dif_neg (mem_filter.mp x.2).2))) @[to_additive] lemma prod_apply_ite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f g : α → γ) (h : γ → β) : (∏ x in s, h (if p x then f x else g x)) = (∏ x in s.filter p, h (f x)) * (∏ x in s.filter (λ x, ¬ p x), h (g x)) := trans (prod_apply_dite _ _ _) (congr_arg2 _ (@prod_attach _ _ _ _ (h ∘ f)) (@prod_attach _ _ _ _ (h ∘ g))) @[to_additive] lemma prod_dite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f : Π (x : α), p x → β) (g : Π (x : α), ¬p x → β) : (∏ x in s, if hx : p x then f x hx else g x hx) = (∏ x in (s.filter p).attach, f x.1 (mem_filter.mp x.2).2) * (∏ x in (s.filter (λ x, ¬ p x)).attach, g x.1 (mem_filter.mp x.2).2) := by simp [prod_apply_dite _ _ (λ x, x)] @[to_additive] lemma prod_ite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f g : α → β) : (∏ x in s, if p x then f x else g x) = (∏ x in s.filter p, f x) * (∏ x in s.filter (λ x, ¬ p x), g x) := by simp [prod_apply_ite _ _ (λ x, x)] @[to_additive] lemma prod_ite_of_false {p : α → Prop} {hp : decidable_pred p} (f g : α → β) (h : ∀ x ∈ s, ¬p x) : (∏ x in s, if p x then f x else g x) = (∏ x in s, g x) := by { rw prod_ite, simp [filter_false_of_mem h, filter_true_of_mem h] } @[to_additive] lemma prod_ite_of_true {p : α → Prop} {hp : decidable_pred p} (f g : α → β) (h : ∀ x ∈ s, p x) : (∏ x in s, if p x then f x else g x) = (∏ x in s, f x) := by { simp_rw ←(ite_not (p _)), apply prod_ite_of_false, simpa } @[to_additive] lemma prod_apply_ite_of_false {p : α → Prop} {hp : decidable_pred p} (f g : α → γ) (k : γ → β) (h : ∀ x ∈ s, ¬p x) : (∏ x in s, k (if p x then f x else g x)) = (∏ x in s, k (g x)) := by { simp_rw apply_ite k, exact prod_ite_of_false _ _ h } @[to_additive] lemma prod_apply_ite_of_true {p : α → Prop} {hp : decidable_pred p} (f g : α → γ) (k : γ → β) (h : ∀ x ∈ s, p x) : (∏ x in s, k (if p x then f x else g x)) = (∏ x in s, k (f x)) := by { simp_rw apply_ite k, exact prod_ite_of_true _ _ h } @[to_additive] lemma prod_extend_by_one [decidable_eq α] (s : finset α) (f : α → β) : ∏ i in s, (if i ∈ s then f i else 1) = ∏ i in s, f i := prod_congr rfl $ λ i hi, if_pos hi @[simp, to_additive] lemma prod_dite_eq [decidable_eq α] (s : finset α) (a : α) (b : Π x : α, a = x → β) : (∏ x in s, (if h : a = x then b x h else 1)) = ite (a ∈ s) (b a rfl) 1 := begin split_ifs with h, { rw [finset.prod_eq_single a, dif_pos rfl], { intros, rw dif_neg, cc }, { cc } }, { rw finset.prod_eq_one, intros, rw dif_neg, intro, cc } end @[simp, to_additive] lemma prod_dite_eq' [decidable_eq α] (s : finset α) (a : α) (b : Π x : α, x = a → β) : (∏ x in s, (if h : x = a then b x h else 1)) = ite (a ∈ s) (b a rfl) 1 := begin split_ifs with h, { rw [finset.prod_eq_single a, dif_pos rfl], { intros, rw dif_neg, cc }, { cc } }, { rw finset.prod_eq_one, intros, rw dif_neg, intro, cc } end @[simp, to_additive] lemma prod_ite_eq [decidable_eq α] (s : finset α) (a : α) (b : α → β) : (∏ x in s, (ite (a = x) (b x) 1)) = ite (a ∈ s) (b a) 1 := prod_dite_eq s a (λ x _, b x) /-- When a product is taken over a conditional whose condition is an equality test on the index and whose alternative is 1, then the product's value is either the term at that index or `1`. The difference with `prod_ite_eq` is that the arguments to `eq` are swapped. -/ @[simp, to_additive] lemma prod_ite_eq' [decidable_eq α] (s : finset α) (a : α) (b : α → β) : (∏ x in s, (ite (x = a) (b x) 1)) = ite (a ∈ s) (b a) 1 := prod_dite_eq' s a (λ x _, b x) @[to_additive] lemma prod_ite_index (p : Prop) [decidable p] (s t : finset α) (f : α → β) : (∏ x in if p then s else t, f x) = if p then ∏ x in s, f x else ∏ x in t, f x := apply_ite (λ s, ∏ x in s, f x) _ _ _ @[simp, to_additive] lemma prod_dite_irrel (p : Prop) [decidable p] (s : finset α) (f : p → α → β) (g : ¬p → α → β): (∏ x in s, if h : p then f h x else g h x) = if h : p then ∏ x in s, f h x else ∏ x in s, g h x := by { split_ifs with h; refl } @[simp] lemma sum_pi_single' {ι M : Type*} [decidable_eq ι] [add_comm_monoid M] (i : ι) (x : M) (s : finset ι) : ∑ j in s, pi.single i x j = if i ∈ s then x else 0 := sum_dite_eq' _ _ _ @[simp] lemma sum_pi_single {ι : Type*} {M : ι → Type*} [decidable_eq ι] [Π i, add_comm_monoid (M i)] (i : ι) (f : Π i, M i) (s : finset ι) : ∑ j in s, pi.single j (f j) i = if i ∈ s then f i else 0 := sum_dite_eq _ _ _ /-- Reorder a product. The difference with `prod_bij'` is that the bijection is specified as a surjective injection, rather than by an inverse function. -/ @[to_additive " Reorder a sum. The difference with `sum_bij'` is that the bijection is specified as a surjective injection, rather than by an inverse function. "] lemma prod_bij {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Π a ∈ s, γ) (hi : ∀ a ha, i a ha ∈ t) (h : ∀ a ha, f a = g (i a ha)) (i_inj : ∀ a₁ a₂ ha₁ ha₂, i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂) (i_surj : ∀ b ∈ t, ∃ a ha, b = i a ha) : (∏ x in s, f x) = (∏ x in t, g x) := congr_arg multiset.prod (multiset.map_eq_map_of_bij_of_nodup f g s.2 t.2 i hi h i_inj i_surj) /-- Reorder a product. The difference with `prod_bij` is that the bijection is specified with an inverse, rather than as a surjective injection. -/ @[to_additive " Reorder a sum. The difference with `sum_bij` is that the bijection is specified with an inverse, rather than as a surjective injection. "] lemma prod_bij' {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Π a ∈ s, γ) (hi : ∀ a ha, i a ha ∈ t) (h : ∀ a ha, f a = g (i a ha)) (j : Π a ∈ t, α) (hj : ∀ a ha, j a ha ∈ s) (left_inv : ∀ a ha, j (i a ha) (hi a ha) = a) (right_inv : ∀ a ha, i (j a ha) (hj a ha) = a) : (∏ x in s, f x) = (∏ x in t, g x) := begin refine prod_bij i hi h _ _, {intros a1 a2 h1 h2 eq, rw [←left_inv a1 h1, ←left_inv a2 h2], cc,}, {intros b hb, use j b hb, use hj b hb, exact (right_inv b hb).symm,}, end @[to_additive] lemma prod_bij_ne_one {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Π a ∈ s, f a ≠ 1 → γ) (hi : ∀ a h₁ h₂, i a h₁ h₂ ∈ t) (i_inj : ∀ a₁ a₂ h₁₁ h₁₂ h₂₁ h₂₂, i a₁ h₁₁ h₁₂ = i a₂ h₂₁ h₂₂ → a₁ = a₂) (i_surj : ∀ b ∈ t, g b ≠ 1 → ∃ a h₁ h₂, b = i a h₁ h₂) (h : ∀ a h₁ h₂, f a = g (i a h₁ h₂)) : (∏ x in s, f x) = (∏ x in t, g x) := by classical; exact calc (∏ x in s, f x) = ∏ x in (s.filter $ λ x, f x ≠ 1), f x : prod_filter_ne_one.symm ... = ∏ x in (t.filter $ λ x, g x ≠ 1), g x : prod_bij (assume a ha, i a (mem_filter.mp ha).1 (mem_filter.mp ha).2) (assume a ha, (mem_filter.mp ha).elim $ λ h₁ h₂, mem_filter.mpr ⟨hi a h₁ h₂, λ hg, h₂ (hg ▸ h a h₁ h₂)⟩) (assume a ha, (mem_filter.mp ha).elim $ h a) (assume a₁ a₂ ha₁ ha₂, (mem_filter.mp ha₁).elim $ λ ha₁₁ ha₁₂, (mem_filter.mp ha₂).elim $ λ ha₂₁ ha₂₂, i_inj a₁ a₂ _ _ _ _) (assume b hb, (mem_filter.mp hb).elim $ λ h₁ h₂, let ⟨a, ha₁, ha₂, eq⟩ := i_surj b h₁ h₂ in ⟨a, mem_filter.mpr ⟨ha₁, ha₂⟩, eq⟩) ... = (∏ x in t, g x) : prod_filter_ne_one @[to_additive] lemma prod_dite_of_false {p : α → Prop} {hp : decidable_pred p} (h : ∀ x ∈ s, ¬ p x) (f : Π (x : α), p x → β) (g : Π (x : α), ¬p x → β) : (∏ x in s, if hx : p x then f x hx else g x hx) = ∏ (x : s), g x.val (h x.val x.property) := prod_bij (λ x hx, ⟨x,hx⟩) (λ x hx, by simp) (λ a ha, by { dsimp, rw dif_neg }) (λ a₁ a₂ h₁ h₂ hh, congr_arg coe hh) (λ b hb, ⟨b.1, b.2, by simp⟩) @[to_additive] lemma prod_dite_of_true {p : α → Prop} {hp : decidable_pred p} (h : ∀ x ∈ s, p x) (f : Π (x : α), p x → β) (g : Π (x : α), ¬p x → β) : (∏ x in s, if hx : p x then f x hx else g x hx) = ∏ (x : s), f x.val (h x.val x.property) := prod_bij (λ x hx, ⟨x,hx⟩) (λ x hx, by simp) (λ a ha, by { dsimp, rw dif_pos }) (λ a₁ a₂ h₁ h₂ hh, congr_arg coe hh) (λ b hb, ⟨b.1, b.2, by simp⟩) @[to_additive] lemma nonempty_of_prod_ne_one (h : (∏ x in s, f x) ≠ 1) : s.nonempty := s.eq_empty_or_nonempty.elim (λ H, false.elim $ h $ H.symm ▸ prod_empty) id @[to_additive] lemma exists_ne_one_of_prod_ne_one (h : (∏ x in s, f x) ≠ 1) : ∃ a ∈ s, f a ≠ 1 := begin classical, rw ← prod_filter_ne_one at h, rcases nonempty_of_prod_ne_one h with ⟨x, hx⟩, exact ⟨x, (mem_filter.1 hx).1, (mem_filter.1 hx).2⟩ end @[to_additive] lemma prod_range_succ_comm (f : ℕ → β) (n : ℕ) : ∏ x in range (n + 1), f x = f n * ∏ x in range n, f x := by rw [range_succ, prod_insert not_mem_range_self] @[to_additive] lemma prod_range_succ (f : ℕ → β) (n : ℕ) : ∏ x in range (n + 1), f x = (∏ x in range n, f x) * f n := by simp only [mul_comm, prod_range_succ_comm] @[to_additive] lemma prod_range_succ' (f : ℕ → β) : ∀ n : ℕ, (∏ k in range (n + 1), f k) = (∏ k in range n, f (k+1)) * f 0 | 0 := prod_range_succ _ _ | (n + 1) := by rw [prod_range_succ _ n, mul_right_comm, ← prod_range_succ', prod_range_succ] @[to_additive] lemma eventually_constant_prod {u : ℕ → β} {N : ℕ} (hu : ∀ n ≥ N, u n = 1) {n : ℕ} (hn : N ≤ n) : ∏ k in range (n + 1), u k = ∏ k in range (N + 1), u k := begin obtain ⟨m, rfl : n = N + m⟩ := le_iff_exists_add.mp hn, clear hn, induction m with m hm, { simp }, erw [prod_range_succ, hm], simp [hu] end @[to_additive] lemma prod_range_add (f : ℕ → β) (n m : ℕ) : ∏ x in range (n + m), f x = (∏ x in range n, f x) * (∏ x in range m, f (n + x)) := begin induction m with m hm, { simp }, { rw [nat.add_succ, prod_range_succ, hm, prod_range_succ, mul_assoc], }, end @[to_additive] lemma prod_range_add_div_prod_range {α : Type*} [comm_group α] (f : ℕ → α) (n m : ℕ) : (∏ k in range (n + m), f k) / (∏ k in range n, f k) = ∏ k in finset.range m, f (n + k) := div_eq_of_eq_mul' (prod_range_add f n m) @[to_additive] lemma prod_range_zero (f : ℕ → β) : ∏ k in range 0, f k = 1 := by rw [range_zero, prod_empty] @[to_additive sum_range_one] lemma prod_range_one (f : ℕ → β) : ∏ k in range 1, f k = f 0 := by { rw [range_one], apply @prod_singleton β ℕ 0 f } open multiset @[to_additive] lemma prod_multiset_map_count [decidable_eq α] (s : multiset α) {M : Type*} [comm_monoid M] (f : α → M) : (s.map f).prod = ∏ m in s.to_finset, (f m) ^ (s.count m) := begin induction s using multiset.induction_on with a s ih, { simp only [prod_const_one, count_zero, prod_zero, pow_zero, map_zero] }, simp only [multiset.prod_cons, map_cons, to_finset_cons, ih], by_cases has : a ∈ s.to_finset, { rw [insert_eq_of_mem has, ← insert_erase has, prod_insert (not_mem_erase _ _), prod_insert (not_mem_erase _ _), ← mul_assoc, count_cons_self, pow_succ], congr' 1, refine prod_congr rfl (λ x hx, _), rw [count_cons_of_ne (ne_of_mem_erase hx)] }, rw [prod_insert has, count_cons_self, count_eq_zero_of_not_mem (mt mem_to_finset.2 has), pow_one], congr' 1, refine prod_congr rfl (λ x hx, _), rw count_cons_of_ne, rintro rfl, exact has hx end @[to_additive] lemma prod_multiset_count [decidable_eq α] [comm_monoid α] (s : multiset α) : s.prod = ∏ m in s.to_finset, m ^ (s.count m) := by { convert prod_multiset_map_count s id, rw map_id } @[to_additive] lemma prod_mem_multiset [decidable_eq α] (m : multiset α) (f : {x // x ∈ m} → β) (g : α → β) (hfg : ∀ x, f x = g x) : ∏ (x : {x // x ∈ m}), f x = ∏ x in m.to_finset, g x := prod_bij (λ x _, x.1) (λ x _, multiset.mem_to_finset.mpr x.2) (λ _ _, hfg _) (λ _ _ _ _ h, by { ext, assumption }) (λ y hy, ⟨⟨y, multiset.mem_to_finset.mp hy⟩, finset.mem_univ _, rfl⟩) /-- To prove a property of a product, it suffices to prove that the property is multiplicative and holds on factors. -/ @[to_additive "To prove a property of a sum, it suffices to prove that the property is additive and holds on summands."] lemma prod_induction {M : Type*} [comm_monoid M] (f : α → M) (p : M → Prop) (p_mul : ∀ a b, p a → p b → p (a * b)) (p_one : p 1) (p_s : ∀ x ∈ s, p $ f x) : p $ ∏ x in s, f x := multiset.prod_induction _ _ p_mul p_one (multiset.forall_mem_map_iff.mpr p_s) /-- To prove a property of a product, it suffices to prove that the property is multiplicative and holds on factors. -/ @[to_additive "To prove a property of a sum, it suffices to prove that the property is additive and holds on summands."] lemma prod_induction_nonempty {M : Type*} [comm_monoid M] (f : α → M) (p : M → Prop) (p_mul : ∀ a b, p a → p b → p (a * b)) (hs_nonempty : s.nonempty) (p_s : ∀ x ∈ s, p $ f x) : p $ ∏ x in s, f x := multiset.prod_induction_nonempty p p_mul (by simp [nonempty_iff_ne_empty.mp hs_nonempty]) (multiset.forall_mem_map_iff.mpr p_s) /-- For any product along `{0, ..., n-1}` of a commutative-monoid-valued function, we can verify that it's equal to a different function just by checking ratios of adjacent terms. This is a multiplicative discrete analogue of the fundamental theorem of calculus. -/ lemma prod_range_induction {M : Type*} [comm_monoid M] (f s : ℕ → M) (h0 : s 0 = 1) (h : ∀ n, s (n + 1) = s n * f n) (n : ℕ) : ∏ k in finset.range n, f k = s n := begin induction n with k hk, { simp only [h0, finset.prod_range_zero] }, { simp only [hk, finset.prod_range_succ, h, mul_comm] } end /-- For any sum along `{0, ..., n-1}` of a commutative-monoid-valued function, we can verify that it's equal to a different function just by checking differences of adjacent terms. This is a discrete analogue of the fundamental theorem of calculus. -/ lemma sum_range_induction {M : Type*} [add_comm_monoid M] (f s : ℕ → M) (h0 : s 0 = 0) (h : ∀ n, s (n + 1) = s n + f n) (n : ℕ) : ∑ k in finset.range n, f k = s n := @prod_range_induction (multiplicative M) _ f s h0 h n /-- A telescoping sum along `{0, ..., n-1}` of an additive commutative group valued function reduces to the difference of the last and first terms.-/ lemma sum_range_sub {G : Type*} [add_comm_group G] (f : ℕ → G) (n : ℕ) : ∑ i in range n, (f (i+1) - f i) = f n - f 0 := by { apply sum_range_induction; simp } lemma sum_range_sub' {G : Type*} [add_comm_group G] (f : ℕ → G) (n : ℕ) : ∑ i in range n, (f i - f (i+1)) = f 0 - f n := by { apply sum_range_induction; simp } /-- A telescoping product along `{0, ..., n-1}` of a commutative group valued function reduces to the ratio of the last and first factors.-/ @[to_additive] lemma prod_range_div {M : Type*} [comm_group M] (f : ℕ → M) (n : ℕ) : ∏ i in range n, (f (i+1) * (f i)⁻¹) = f n * (f 0)⁻¹ := by simpa only [← div_eq_mul_inv] using @sum_range_sub (additive M) _ f n @[to_additive] lemma prod_range_div' {M : Type*} [comm_group M] (f : ℕ → M) (n : ℕ) : ∏ i in range n, (f i * (f (i+1))⁻¹) = (f 0) * (f n)⁻¹ := by simpa only [← div_eq_mul_inv] using @sum_range_sub' (additive M) _ f n /-- A telescoping sum along `{0, ..., n-1}` of an `ℕ`-valued function reduces to the difference of the last and first terms when the function we are summing is monotone. -/ lemma sum_range_sub_of_monotone {f : ℕ → ℕ} (h : monotone f) (n : ℕ) : ∑ i in range n, (f (i+1) - f i) = f n - f 0 := begin refine sum_range_induction _ _ (tsub_self _) (λ n, _) _, have h₁ : f n ≤ f (n+1) := h (nat.le_succ _), have h₂ : f 0 ≤ f n := h (nat.zero_le _), rw [tsub_add_eq_add_tsub h₂, add_tsub_cancel_of_le h₁], end @[simp, to_additive] lemma prod_const (b : β) : (∏ x in s, b) = b ^ s.card := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (λ a s has ih, by rw [prod_insert has, card_insert_of_not_mem has, pow_succ, ih]) @[to_additive] lemma pow_eq_prod_const (b : β) : ∀ n, b ^ n = ∏ k in range n, b := by simp @[to_additive sum_nsmul] lemma prod_pow (s : finset α) (n : ℕ) (f : α → β) : ∏ x in s, f x ^ n = (∏ x in s, f x) ^ n := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (by simp [mul_pow] {contextual := tt}) @[to_additive] lemma prod_flip {n : ℕ} (f : ℕ → β) : ∏ r in range (n + 1), f (n - r) = ∏ k in range (n + 1), f k := begin induction n with n ih, { rw [prod_range_one, prod_range_one] }, { rw [prod_range_succ', prod_range_succ _ (nat.succ n)], simp [← ih] } end @[to_additive] lemma prod_involution {s : finset α} {f : α → β} : ∀ (g : Π a ∈ s, α) (h : ∀ a ha, f a * f (g a ha) = 1) (g_ne : ∀ a ha, f a ≠ 1 → g a ha ≠ a) (g_mem : ∀ a ha, g a ha ∈ s) (g_inv : ∀ a ha, g (g a ha) (g_mem a ha) = a), (∏ x in s, f x) = 1 := by haveI := classical.dec_eq α; haveI := classical.dec_eq β; exact finset.strong_induction_on s (λ s ih g h g_ne g_mem g_inv, s.eq_empty_or_nonempty.elim (λ hs, hs.symm ▸ rfl) (λ ⟨x, hx⟩, have hmem : ∀ y ∈ (s.erase x).erase (g x hx), y ∈ s, from λ y hy, (mem_of_mem_erase (mem_of_mem_erase hy)), have g_inj : ∀ {x hx y hy}, g x hx = g y hy → x = y, from λ x hx y hy h, by rw [← g_inv x hx, ← g_inv y hy]; simp [h], have ih': ∏ y in erase (erase s x) (g x hx), f y = (1 : β) := ih ((s.erase x).erase (g x hx)) ⟨subset.trans (erase_subset _ _) (erase_subset _ _), λ h, not_mem_erase (g x hx) (s.erase x) (h (g_mem x hx))⟩ (λ y hy, g y (hmem y hy)) (λ y hy, h y (hmem y hy)) (λ y hy, g_ne y (hmem y hy)) (λ y hy, mem_erase.2 ⟨λ (h : g y _ = g x hx), by simpa [g_inj h] using hy, mem_erase.2 ⟨λ (h : g y _ = x), have y = g x hx, from g_inv y (hmem y hy) ▸ by simp [h], by simpa [this] using hy, g_mem y (hmem y hy)⟩⟩) (λ y hy, g_inv y (hmem y hy)), if hx1 : f x = 1 then ih' ▸ eq.symm (prod_subset hmem (λ y hy hy₁, have y = x ∨ y = g x hx, by simp [hy] at hy₁; tauto, this.elim (λ hy, hy.symm ▸ hx1) (λ hy, h x hx ▸ hy ▸ hx1.symm ▸ (one_mul _).symm))) else by rw [← insert_erase hx, prod_insert (not_mem_erase _ _), ← insert_erase (mem_erase.2 ⟨g_ne x hx hx1, g_mem x hx⟩), prod_insert (not_mem_erase _ _), ih', mul_one, h x hx])) /-- The product of the composition of functions `f` and `g`, is the product over `b ∈ s.image g` of `f b` to the power of the cardinality of the fibre of `b`. See also `finset.prod_image`. -/ lemma prod_comp [decidable_eq γ] (f : γ → β) (g : α → γ) : ∏ a in s, f (g a) = ∏ b in s.image g, f b ^ (s.filter (λ a, g a = b)).card := calc ∏ a in s, f (g a) = ∏ x in (s.image g).sigma (λ b : γ, s.filter (λ a, g a = b)), f (g x.2) : prod_bij (λ a ha, ⟨g a, a⟩) (by simp; tauto) (λ _ _, rfl) (by simp) (by finish) ... = ∏ b in s.image g, ∏ a in s.filter (λ a, g a = b), f (g a) : prod_sigma _ _ _ ... = ∏ b in s.image g, ∏ a in s.filter (λ a, g a = b), f b : prod_congr rfl (λ b hb, prod_congr rfl (by simp {contextual := tt})) ... = ∏ b in s.image g, f b ^ (s.filter (λ a, g a = b)).card : prod_congr rfl (λ _ _, prod_const _) @[to_additive] lemma prod_piecewise [decidable_eq α] (s t : finset α) (f g : α → β) : (∏ x in s, (t.piecewise f g) x) = (∏ x in s ∩ t, f x) * (∏ x in s \ t, g x) := by { rw [piecewise, prod_ite, filter_mem_eq_inter, ← sdiff_eq_filter], } @[to_additive] lemma prod_inter_mul_prod_diff [decidable_eq α] (s t : finset α) (f : α → β) : (∏ x in s ∩ t, f x) * (∏ x in s \ t, f x) = (∏ x in s, f x) := by { convert (s.prod_piecewise t f f).symm, simp [finset.piecewise] } @[to_additive] lemma prod_eq_mul_prod_diff_singleton [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) : ∏ x in s, f x = f i * ∏ x in s \ {i}, f x := by { convert (s.prod_inter_mul_prod_diff {i} f).symm, simp [h] } @[to_additive] lemma prod_eq_prod_diff_singleton_mul [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) : ∏ x in s, f x = (∏ x in s \ {i}, f x) * f i := by { rw [prod_eq_mul_prod_diff_singleton h, mul_comm] } @[to_additive] lemma _root_.fintype.prod_eq_mul_prod_compl [decidable_eq α] [fintype α] (a : α) (f : α → β) : ∏ i, f i = (f a) * ∏ i in {a}ᶜ, f i := prod_eq_mul_prod_diff_singleton (mem_univ a) f @[to_additive] lemma _root_.fintype.prod_eq_prod_compl_mul [decidable_eq α] [fintype α] (a : α) (f : α → β) : ∏ i, f i = (∏ i in {a}ᶜ, f i) * f a := prod_eq_prod_diff_singleton_mul (mem_univ a) f lemma dvd_prod_of_mem (f : α → β) {a : α} {s : finset α} (ha : a ∈ s) : f a ∣ ∏ i in s, f i := begin classical, rw finset.prod_eq_mul_prod_diff_singleton ha, exact dvd_mul_right _ _, end /-- A product can be partitioned into a product of products, each equivalent under a setoid. -/ @[to_additive "A sum can be partitioned into a sum of sums, each equivalent under a setoid."] lemma prod_partition (R : setoid α) [decidable_rel R.r] : (∏ x in s, f x) = ∏ xbar in s.image quotient.mk, ∏ y in s.filter (λ y, ⟦y⟧ = xbar), f y := begin refine (finset.prod_image' f (λ x hx, _)).symm, refl, end /-- If we can partition a product into subsets that cancel out, then the whole product cancels. -/ @[to_additive "If we can partition a sum into subsets that cancel out, then the whole sum cancels."] lemma prod_cancels_of_partition_cancels (R : setoid α) [decidable_rel R.r] (h : ∀ x ∈ s, (∏ a in s.filter (λ y, y ≈ x), f a) = 1) : (∏ x in s, f x) = 1 := begin rw [prod_partition R, ←finset.prod_eq_one], intros xbar xbar_in_s, obtain ⟨x, x_in_s, xbar_eq_x⟩ := mem_image.mp xbar_in_s, rw [←xbar_eq_x, filter_congr (λ y _, @quotient.eq _ R y x)], apply h x x_in_s, end @[to_additive] lemma prod_update_of_not_mem [decidable_eq α] {s : finset α} {i : α} (h : i ∉ s) (f : α → β) (b : β) : (∏ x in s, function.update f i b x) = (∏ x in s, f x) := begin apply prod_congr rfl (λ j hj, _), have : j ≠ i, by { assume eq, rw eq at hj, exact h hj }, simp [this] end @[to_additive] lemma prod_update_of_mem [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) (b : β) : (∏ x in s, function.update f i b x) = b * (∏ x in s \ (singleton i), f x) := by { rw [update_eq_piecewise, prod_piecewise], simp [h] } /-- If a product of a `finset` of size at most 1 has a given value, so do the terms in that product. -/ @[to_additive eq_of_card_le_one_of_sum_eq "If a sum of a `finset` of size at most 1 has a given value, so do the terms in that sum."] lemma eq_of_card_le_one_of_prod_eq {s : finset α} (hc : s.card ≤ 1) {f : α → β} {b : β} (h : ∏ x in s, f x = b) : ∀ x ∈ s, f x = b := begin intros x hx, by_cases hc0 : s.card = 0, { exact false.elim (card_ne_zero_of_mem hx hc0) }, { have h1 : s.card = 1 := le_antisymm hc (nat.one_le_of_lt (nat.pos_of_ne_zero hc0)), rw card_eq_one at h1, cases h1 with x2 hx2, rw [hx2, mem_singleton] at hx, simp_rw hx2 at h, rw hx, rw prod_singleton at h, exact h } end /-- Taking a product over `s : finset α` is the same as multiplying the value on a single element `f a` by the product of `s.erase a`. -/ @[to_additive "Taking a sum over `s : finset α` is the same as adding the value on a single element `f a` to the sum over `s.erase a`."] lemma mul_prod_erase [decidable_eq α] (s : finset α) (f : α → β) {a : α} (h : a ∈ s) : f a * (∏ x in s.erase a, f x) = ∏ x in s, f x := by rw [← prod_insert (not_mem_erase a s), insert_erase h] /-- A variant of `finset.mul_prod_erase` with the multiplication swapped. -/ @[to_additive "A variant of `finset.add_sum_erase` with the addition swapped."] lemma prod_erase_mul [decidable_eq α] (s : finset α) (f : α → β) {a : α} (h : a ∈ s) : (∏ x in s.erase a, f x) * f a = ∏ x in s, f x := by rw [mul_comm, mul_prod_erase s f h] /-- If a function applied at a point is 1, a product is unchanged by removing that point, if present, from a `finset`. -/ @[to_additive "If a function applied at a point is 0, a sum is unchanged by removing that point, if present, from a `finset`."] lemma prod_erase [decidable_eq α] (s : finset α) {f : α → β} {a : α} (h : f a = 1) : ∏ x in s.erase a, f x = ∏ x in s, f x := begin rw ←sdiff_singleton_eq_erase, refine prod_subset (sdiff_subset _ _) (λ x hx hnx, _), rw sdiff_singleton_eq_erase at hnx, rwa eq_of_mem_of_not_mem_erase hx hnx end /-- If a product is 1 and the function is 1 except possibly at one point, it is 1 everywhere on the `finset`. -/ @[to_additive "If a sum is 0 and the function is 0 except possibly at one point, it is 0 everywhere on the `finset`."] lemma eq_one_of_prod_eq_one {s : finset α} {f : α → β} {a : α} (hp : ∏ x in s, f x = 1) (h1 : ∀ x ∈ s, x ≠ a → f x = 1) : ∀ x ∈ s, f x = 1 := begin intros x hx, classical, by_cases h : x = a, { rw h, rw h at hx, rw [←prod_subset (singleton_subset_iff.2 hx) (λ t ht ha, h1 t ht (not_mem_singleton.1 ha)), prod_singleton] at hp, exact hp }, { exact h1 x hx h } end lemma prod_pow_boole [decidable_eq α] (s : finset α) (f : α → β) (a : α) : (∏ x in s, (f x)^(ite (a = x) 1 0)) = ite (a ∈ s) (f a) 1 := by simp end comm_monoid /-- If `f = g = h` everywhere but at `i`, where `f i = g i + h i`, then the product of `f` over `s` is the sum of the products of `g` and `h`. -/ lemma prod_add_prod_eq [comm_semiring β] {s : finset α} {i : α} {f g h : α → β} (hi : i ∈ s) (h1 : g i + h i = f i) (h2 : ∀ j ∈ s, j ≠ i → g j = f j) (h3 : ∀ j ∈ s, j ≠ i → h j = f j) : ∏ i in s, g i + ∏ i in s, h i = ∏ i in s, f i := by { classical, simp_rw [prod_eq_mul_prod_diff_singleton hi, ← h1, right_distrib], congr' 2; apply prod_congr rfl; simpa } lemma card_eq_sum_ones (s : finset α) : s.card = ∑ _ in s, 1 := by simp lemma sum_const_nat {m : ℕ} {f : α → ℕ} (h₁ : ∀ x ∈ s, f x = m) : (∑ x in s, f x) = card s * m := begin rw [← nat.nsmul_eq_mul, ← sum_const], apply sum_congr rfl h₁ end @[simp] lemma sum_boole {s : finset α} {p : α → Prop} [non_assoc_semiring β] {hp : decidable_pred p} : (∑ x in s, if p x then (1 : β) else (0 : β)) = (s.filter p).card := by simp [sum_ite] lemma sum_comp [add_comm_monoid β] [decidable_eq γ] (f : γ → β) (g : α → γ) : ∑ a in s, f (g a) = ∑ b in s.image g, (s.filter (λ a, g a = b)).card • (f b) := @prod_comp (multiplicative β) _ _ _ _ _ _ _ attribute [to_additive "The sum of the composition of functions `f` and `g`, is the sum over `b ∈ s.image g` of `f b` times of the cardinality of the fibre of `b`. See also `finset.sum_image`."] prod_comp lemma eq_sum_range_sub [add_comm_group β] (f : ℕ → β) (n : ℕ) : f n = f 0 + ∑ i in range n, (f (i+1) - f i) := by rw [finset.sum_range_sub, add_sub_cancel'_right] lemma eq_sum_range_sub' [add_comm_group β] (f : ℕ → β) (n : ℕ) : f n = ∑ i in range (n + 1), if i = 0 then f 0 else f i - f (i - 1) := begin conv_lhs { rw [finset.eq_sum_range_sub f] }, simp [finset.sum_range_succ', add_comm] end section opposite open opposite /-- Moving to the opposite additive commutative monoid commutes with summing. -/ @[simp] lemma op_sum [add_comm_monoid β] {s : finset α} (f : α → β) : op (∑ x in s, f x) = ∑ x in s, op (f x) := (op_add_equiv : β ≃+ βᵒᵖ).map_sum _ _ @[simp] lemma unop_sum [add_comm_monoid β] {s : finset α} (f : α → βᵒᵖ) : unop (∑ x in s, f x) = ∑ x in s, unop (f x) := (op_add_equiv : β ≃+ βᵒᵖ).symm.map_sum _ _ end opposite section comm_group variables [comm_group β] @[simp, to_additive] lemma prod_inv_distrib : (∏ x in s, (f x)⁻¹) = (∏ x in s, f x)⁻¹ := (monoid_hom.map_prod (comm_group.inv_monoid_hom : β →* β) f s).symm @[to_additive zsmul_sum] lemma prod_zpow (f : α → β) (s : finset α) (n : ℤ) : (∏ a in s, f a) ^ n = ∏ a in s, (f a) ^ n := (zpow_group_hom n : β →* β).map_prod f s end comm_group @[simp] theorem card_sigma {σ : α → Type*} (s : finset α) (t : Π a, finset (σ a)) : card (s.sigma t) = ∑ a in s, card (t a) := multiset.card_sigma _ _ lemma card_bUnion [decidable_eq β] {s : finset α} {t : α → finset β} (h : ∀ x ∈ s, ∀ y ∈ s, x ≠ y → disjoint (t x) (t y)) : (s.bUnion t).card = ∑ u in s, card (t u) := calc (s.bUnion t).card = ∑ i in s.bUnion t, 1 : by simp ... = ∑ a in s, ∑ i in t a, 1 : finset.sum_bUnion h ... = ∑ u in s, card (t u) : by simp lemma card_bUnion_le [decidable_eq β] {s : finset α} {t : α → finset β} : (s.bUnion t).card ≤ ∑ a in s, (t a).card := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (λ a s has ih, calc ((insert a s).bUnion t).card ≤ (t a).card + (s.bUnion t).card : by rw bUnion_insert; exact finset.card_union_le _ _ ... ≤ ∑ a in insert a s, card (t a) : by rw sum_insert has; exact add_le_add_left ih _) theorem card_eq_sum_card_fiberwise [decidable_eq β] {f : α → β} {s : finset α} {t : finset β} (H : ∀ x ∈ s, f x ∈ t) : s.card = ∑ a in t, (s.filter (λ x, f x = a)).card := by simp only [card_eq_sum_ones, sum_fiberwise_of_maps_to H] theorem card_eq_sum_card_image [decidable_eq β] (f : α → β) (s : finset α) : s.card = ∑ a in s.image f, (s.filter (λ x, f x = a)).card := card_eq_sum_card_fiberwise (λ _, mem_image_of_mem _) @[simp] lemma sum_sub_distrib [add_comm_group β] : ∑ x in s, (f x - g x) = (∑ x in s, f x) - (∑ x in s, g x) := by simpa only [sub_eq_add_neg] using sum_add_distrib.trans (congr_arg _ sum_neg_distrib) section prod_eq_zero variables [comm_monoid_with_zero β] lemma prod_eq_zero (ha : a ∈ s) (h : f a = 0) : (∏ x in s, f x) = 0 := by { haveI := classical.dec_eq α, rw [←prod_erase_mul _ _ ha, h, mul_zero] } lemma prod_boole {s : finset α} {p : α → Prop} [decidable_pred p] : ∏ i in s, ite (p i) (1 : β) (0 : β) = ite (∀ i ∈ s, p i) 1 0 := begin split_ifs, { apply prod_eq_one, intros i hi, rw if_pos (h i hi) }, { push_neg at h, rcases h with ⟨i, hi, hq⟩, apply prod_eq_zero hi, rw [if_neg hq] }, end variables [nontrivial β] [no_zero_divisors β] lemma prod_eq_zero_iff : (∏ x in s, f x) = 0 ↔ (∃ a ∈ s, f a = 0) := begin classical, apply finset.induction_on s, exact ⟨not.elim one_ne_zero, λ ⟨_, H, _⟩, H.elim⟩, assume a s ha ih, rw [prod_insert ha, mul_eq_zero, bex_def, exists_mem_insert, ih, ← bex_def] end theorem prod_ne_zero_iff : (∏ x in s, f x) ≠ 0 ↔ (∀ a ∈ s, f a ≠ 0) := by { rw [ne, prod_eq_zero_iff], push_neg } end prod_eq_zero section comm_group_with_zero variables [comm_group_with_zero β] @[simp] lemma prod_inv_distrib' : (∏ x in s, (f x)⁻¹) = (∏ x in s, f x)⁻¹ := begin classical, by_cases h : ∃ x ∈ s, f x = 0, { simpa [prod_eq_zero_iff.mpr h, prod_eq_zero_iff] using h }, { push_neg at h, have h' := prod_ne_zero_iff.mpr h, have hf : ∀ x ∈ s, (f x)⁻¹ * f x = 1 := λ x hx, inv_mul_cancel (h x hx), apply mul_right_cancel₀ h', simp [h, h', ← finset.prod_mul_distrib, prod_congr rfl hf] } end end comm_group_with_zero @[to_additive] lemma prod_unique_nonempty {α β : Type*} [comm_monoid β] [unique α] (s : finset α) (f : α → β) (h : s.nonempty) : (∏ x in s, f x) = f (default α) := begin obtain ⟨a, ha⟩ := h, have : s = {a}, { ext b, simpa [subsingleton.elim a b] using ha }, rw [this, finset.prod_singleton, subsingleton.elim a (default α)] end end finset namespace fintype open finset /-- `fintype.prod_bijective` is a variant of `finset.prod_bij` that accepts `function.bijective`. See `function.bijective.prod_comp` for a version without `h`. -/ @[to_additive "`fintype.sum_equiv` is a variant of `finset.sum_bij` that accepts `function.bijective`. See `function.bijective.sum_comp` for a version without `h`. "] lemma prod_bijective {α β M : Type*} [fintype α] [fintype β] [comm_monoid M] (e : α → β) (he : function.bijective e) (f : α → M) (g : β → M) (h : ∀ x, f x = g (e x)) : ∏ x : α, f x = ∏ x : β, g x := prod_bij (λ x _, e x) (λ x _, mem_univ (e x)) (λ x _, h x) (λ x x' _ _ h, he.injective h) (λ y _, (he.surjective y).imp $ λ a h, ⟨mem_univ _, h.symm⟩) /-- `fintype.prod_equiv` is a specialization of `finset.prod_bij` that automatically fills in most arguments. See `equiv.prod_comp` for a version without `h`. -/ @[to_additive "`fintype.sum_equiv` is a specialization of `finset.sum_bij` that automatically fills in most arguments. See `equiv.sum_comp` for a version without `h`. "] lemma prod_equiv {α β M : Type*} [fintype α] [fintype β] [comm_monoid M] (e : α ≃ β) (f : α → M) (g : β → M) (h : ∀ x, f x = g (e x)) : ∏ x : α, f x = ∏ x : β, g x := prod_bijective e e.bijective f g h @[to_additive] lemma prod_finset_coe [comm_monoid β] : ∏ (i : (s : set α)), f i = ∏ i in s, f i := (finset.prod_subtype s (λ _, iff.rfl) f).symm @[to_additive] lemma prod_unique {α β : Type*} [comm_monoid β] [unique α] (f : α → β) : (∏ x : α, f x) = f (default α) := by rw [univ_unique, prod_singleton] @[to_additive] lemma prod_empty {α β : Type*} [comm_monoid β] [is_empty α] (f : α → β) : (∏ x : α, f x) = 1 := by rw [eq_empty_of_is_empty (univ : finset α), finset.prod_empty] @[to_additive] lemma prod_subsingleton {α β : Type*} [comm_monoid β] [subsingleton α] (f : α → β) (a : α) : (∏ x : α, f x) = f a := begin haveI : unique α := unique_of_subsingleton a, convert prod_unique f end @[to_additive] lemma prod_subtype_mul_prod_subtype {α β : Type*} [fintype α] [comm_monoid β] (p : α → Prop) (f : α → β) [decidable_pred p] : (∏ (i : {x // p x}), f i) * (∏ i : {x // ¬ p x}, f i) = ∏ i, f i := begin classical, let s := {x | p x}.to_finset, rw [← finset.prod_subtype s, ← finset.prod_subtype sᶜ], { exact finset.prod_mul_prod_compl _ _ }, { simp }, { simp } end end fintype namespace list @[to_additive] lemma prod_to_finset {M : Type*} [decidable_eq α] [comm_monoid M] (f : α → M) : ∀ {l : list α} (hl : l.nodup), l.to_finset.prod f = (l.map f).prod | [] _ := by simp | (a :: l) hl := let ⟨not_mem, hl⟩ := list.nodup_cons.mp hl in by simp [finset.prod_insert (mt list.mem_to_finset.mp not_mem), prod_to_finset hl] end list namespace multiset variables [decidable_eq α] @[simp] lemma to_finset_sum_count_eq (s : multiset α) : (∑ a in s.to_finset, s.count a) = s.card := multiset.induction_on s rfl (assume a s ih, calc (∑ x in to_finset (a ::ₘ s), count x (a ::ₘ s)) = ∑ x in to_finset (a ::ₘ s), ((if x = a then 1 else 0) + count x s) : finset.sum_congr rfl $ λ _ _, by split_ifs; [simp only [h, count_cons_self, nat.one_add], simp only [count_cons_of_ne h, zero_add]] ... = card (a ::ₘ s) : begin by_cases a ∈ s.to_finset, { have : ∑ x in s.to_finset, ite (x = a) 1 0 = ∑ x in {a}, ite (x = a) 1 0, { rw [finset.sum_ite_eq', if_pos h, finset.sum_singleton, if_pos rfl], }, rw [to_finset_cons, finset.insert_eq_of_mem h, finset.sum_add_distrib, ih, this, finset.sum_singleton, if_pos rfl, add_comm, card_cons] }, { have ha : a ∉ s, by rwa mem_to_finset at h, have : ∑ x in to_finset s, ite (x = a) 1 0 = ∑ x in to_finset s, 0, from finset.sum_congr rfl (λ x hx, if_neg $ by rintro rfl; cc), rw [to_finset_cons, finset.sum_insert h, if_pos rfl, finset.sum_add_distrib, this, finset.sum_const_zero, ih, count_eq_zero_of_not_mem ha, zero_add, add_comm, card_cons] } end) lemma count_sum' {s : finset β} {a : α} {f : β → multiset α} : count a (∑ x in s, f x) = ∑ x in s, count a (f x) := by { dunfold finset.sum, rw count_sum } @[simp] lemma to_finset_sum_count_nsmul_eq (s : multiset α) : (∑ a in s.to_finset, s.count a • {a}) = s := begin apply ext', intro b, rw count_sum', have h : count b s = count b (count b s • {b}), { rw [count_nsmul, count_singleton_self, mul_one] }, rw h, clear h, apply finset.sum_eq_single b, { intros c h hcb, rw count_nsmul, convert mul_zero (count c s), apply count_eq_zero.mpr, exact finset.not_mem_singleton.mpr (ne.symm hcb) }, { intro hb, rw [count_eq_zero_of_not_mem (mt mem_to_finset.2 hb), count_nsmul, zero_mul]} end theorem exists_smul_of_dvd_count (s : multiset α) {k : ℕ} (h : ∀ (a : α), a ∈ s → k ∣ multiset.count a s) : ∃ (u : multiset α), s = k • u := begin use ∑ a in s.to_finset, (s.count a / k) • {a}, have h₂ : ∑ (x : α) in s.to_finset, k • (count x s / k) • ({x} : multiset α) = ∑ (x : α) in s.to_finset, count x s • {x}, { apply finset.sum_congr rfl, intros x hx, rw [← mul_nsmul, nat.mul_div_cancel' (h x (mem_to_finset.mp hx))] }, rw [← finset.sum_nsmul, h₂, to_finset_sum_count_nsmul_eq] end end multiset @[simp, norm_cast] lemma nat.cast_sum [add_comm_monoid β] [has_one β] (s : finset α) (f : α → ℕ) : ↑(∑ x in s, f x : ℕ) = (∑ x in s, (f x : β)) := (nat.cast_add_monoid_hom β).map_sum f s @[simp, norm_cast] lemma int.cast_sum [add_comm_group β] [has_one β] (s : finset α) (f : α → ℤ) : ↑(∑ x in s, f x : ℤ) = (∑ x in s, (f x : β)) := (int.cast_add_hom β).map_sum f s @[simp, norm_cast] lemma nat.cast_prod {R : Type*} [comm_semiring R] (f : α → ℕ) (s : finset α) : (↑∏ i in s, f i : R) = ∏ i in s, f i := (nat.cast_ring_hom R).map_prod _ _ @[simp, norm_cast] lemma int.cast_prod {R : Type*} [comm_ring R] (f : α → ℤ) (s : finset α) : (↑∏ i in s, f i : R) = ∏ i in s, f i := (int.cast_ring_hom R).map_prod _ _ @[simp, norm_cast] lemma units.coe_prod {M : Type*} [comm_monoid M] (f : α → units M) (s : finset α) : (↑∏ i in s, f i : M) = ∏ i in s, f i := (units.coe_hom M).map_prod _ _ lemma nat_abs_sum_le {ι : Type*} (s : finset ι) (f : ι → ℤ) : (∑ i in s, f i).nat_abs ≤ ∑ i in s, (f i).nat_abs := begin classical, apply finset.induction_on s, { simp only [finset.sum_empty, int.nat_abs_zero] }, { intros i s his IH, simp only [his, finset.sum_insert, not_false_iff], exact (int.nat_abs_add_le _ _).trans (add_le_add le_rfl IH) } end
c932b0925f8a2914b4897f19f7a2d22ba54ee5cd
dc06cc9775d64d571bf4778459ec6fde1f344116
/src/data/matrix.lean
6f1339b4db7615c044faa28cf14c78f7594b2423
[ "Apache-2.0" ]
permissive
mgubi/mathlib
8c1ea39035776ad52cf189a7af8cc0eee7dea373
7c09ed5eec8434176fbc493e0115555ccc4c8f99
refs/heads/master
1,642,222,572,514
1,563,782,424,000
1,563,782,424,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,616
lean
/- Copyright (c) 2018 Ellen Arlt. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ellen Arlt, Blair Shi, Sean Leather, Mario Carneiro, Johan Commelin Matrices -/ import algebra.module algebra.pi_instances import data.fintype universes u v def matrix (m n : Type u) [fintype m] [fintype n] (α : Type v) : Type (max u v) := m → n → α namespace matrix variables {l m n o : Type u} [fintype l] [fintype m] [fintype n] [fintype o] variables {α : Type v} section ext variables {M N : matrix m n α} theorem ext_iff : (∀ i j, M i j = N i j) ↔ M = N := ⟨λ h, funext $ λ i, funext $ h i, λ h, by simp [h]⟩ @[extensionality] theorem ext : (∀ i j, M i j = N i j) → M = N := ext_iff.mp def transpose (M : matrix m n α) : matrix n m α | x y := M y x def col (w : m → α) : matrix m punit α | x y := w x def row (v : n → α) : matrix punit n α | x y := v y end ext instance [has_add α] : has_add (matrix m n α) := pi.has_add instance [add_semigroup α] : add_semigroup (matrix m n α) := pi.add_semigroup instance [add_comm_semigroup α] : add_comm_semigroup (matrix m n α) := pi.add_comm_semigroup instance [has_zero α] : has_zero (matrix m n α) := pi.has_zero instance [add_monoid α] : add_monoid (matrix m n α) := pi.add_monoid instance [add_comm_monoid α] : add_comm_monoid (matrix m n α) := pi.add_comm_monoid instance [has_neg α] : has_neg (matrix m n α) := pi.has_neg instance [add_group α] : add_group (matrix m n α) := pi.add_group instance [add_comm_group α] : add_comm_group (matrix m n α) := pi.add_comm_group @[simp] theorem zero_val [has_zero α] (i j) : (0 : matrix m n α) i j = 0 := rfl @[simp] theorem neg_val [has_neg α] (M : matrix m n α) (i j) : (- M) i j = - M i j := rfl @[simp] theorem add_val [has_add α] (M N : matrix m n α) (i j) : (M + N) i j = M i j + N i j := rfl section diagonal variables [decidable_eq n] def diagonal [has_zero α] (d : n → α) : matrix n n α := λ i j, if i = j then d i else 0 @[simp] theorem diagonal_val_eq [has_zero α] {d : n → α} (i : n) : (diagonal d) i i = d i := by simp [diagonal] @[simp] theorem diagonal_val_ne [has_zero α] {d : n → α} {i j : n} (h : i ≠ j) : (diagonal d) i j = 0 := by simp [diagonal, h] theorem diagonal_val_ne' [has_zero α] {d : n → α} {i j : n} (h : j ≠ i) : (diagonal d) i j = 0 := diagonal_val_ne h.symm @[simp] theorem diagonal_zero [has_zero α] : (diagonal (λ _, 0) : matrix n n α) = 0 := by simp [diagonal]; refl section one variables [has_zero α] [has_one α] instance : has_one (matrix n n α) := ⟨diagonal (λ _, 1)⟩ @[simp] theorem diagonal_one : (diagonal (λ _, 1) : matrix n n α) = 1 := rfl theorem one_val {i j} : (1 : matrix n n α) i j = if i = j then 1 else 0 := rfl @[simp] theorem one_val_eq (i) : (1 : matrix n n α) i i = 1 := diagonal_val_eq i @[simp] theorem one_val_ne {i j} : i ≠ j → (1 : matrix n n α) i j = 0 := diagonal_val_ne theorem one_val_ne' {i j} : j ≠ i → (1 : matrix n n α) i j = 0 := diagonal_val_ne' end one end diagonal @[simp] theorem diagonal_add [decidable_eq n] [add_monoid α] (d₁ d₂ : n → α) : diagonal d₁ + diagonal d₂ = diagonal (λ i, d₁ i + d₂ i) := by ext i j; by_cases i = j; simp [h] protected def mul [has_mul α] [add_comm_monoid α] (M : matrix l m α) (N : matrix m n α) : matrix l n α := λ i k, finset.univ.sum (λ j, M i j * N j k) local notation M `⬝` N := M.mul N theorem mul_val [has_mul α] [add_comm_monoid α] {M : matrix l m α} {N : matrix m n α} {i k} : (M ⬝ N) i k = finset.univ.sum (λ j, M i j * N j k) := rfl local attribute [simp] mul_val instance [has_mul α] [add_comm_monoid α] : has_mul (matrix n n α) := ⟨matrix.mul⟩ @[simp] theorem mul_eq_mul [has_mul α] [add_comm_monoid α] (M N : matrix n n α) : M * N = M ⬝ N := rfl theorem mul_val' [has_mul α] [add_comm_monoid α] {M N : matrix n n α} {i k} : (M * N) i k = finset.univ.sum (λ j, M i j * N j k) := rfl section semigroup variables [semiring α] protected theorem mul_assoc (L : matrix l m α) (M : matrix m n α) (N : matrix n o α) : (L ⬝ M) ⬝ N = L ⬝ (M ⬝ N) := by classical; funext i k; simp [finset.mul_sum, finset.sum_mul, mul_assoc]; rw finset.sum_comm instance : semigroup (matrix n n α) := { mul_assoc := matrix.mul_assoc, ..matrix.has_mul } end semigroup @[simp] theorem diagonal_neg [decidable_eq n] [add_group α] (d : n → α) : -diagonal d = diagonal (λ i, -d i) := by ext i j; by_cases i = j; simp [h] section semiring variables [semiring α] @[simp] theorem mul_zero (M : matrix m n α) : M ⬝ (0 : matrix n o α) = 0 := by ext i j; simp @[simp] theorem zero_mul (M : matrix m n α) : (0 : matrix l m α) ⬝ M = 0 := by ext i j; simp theorem mul_add (L : matrix m n α) (M N : matrix n o α) : L ⬝ (M + N) = L ⬝ M + L ⬝ N := by ext i j; simp [finset.sum_add_distrib, mul_add] theorem add_mul (L M : matrix l m α) (N : matrix m n α) : (L + M) ⬝ N = L ⬝ N + M ⬝ N := by ext i j; simp [finset.sum_add_distrib, add_mul] @[simp] theorem diagonal_mul [decidable_eq m] (d : m → α) (M : matrix m n α) (i j) : (diagonal d).mul M i j = d i * M i j := by simp; rw finset.sum_eq_single i; simp [diagonal_val_ne'] {contextual := tt} @[simp] theorem mul_diagonal [decidable_eq n] (d : n → α) (M : matrix m n α) (i j) : (M ⬝ diagonal d) i j = M i j * d j := by simp; rw finset.sum_eq_single j; simp {contextual := tt} @[simp] protected theorem one_mul [decidable_eq m] (M : matrix m n α) : (1 : matrix m m α) ⬝ M = M := by ext i j; rw [← diagonal_one, diagonal_mul, one_mul] @[simp] protected theorem mul_one [decidable_eq n] (M : matrix m n α) : M ⬝ (1 : matrix n n α) = M := by ext i j; rw [← diagonal_one, mul_diagonal, mul_one] instance [decidable_eq n] : monoid (matrix n n α) := { one_mul := matrix.one_mul, mul_one := matrix.mul_one, ..matrix.has_one, ..matrix.semigroup } instance [decidable_eq n] : semiring (matrix n n α) := { mul_zero := mul_zero, zero_mul := zero_mul, left_distrib := mul_add, right_distrib := add_mul, ..matrix.add_comm_monoid, ..matrix.monoid } @[simp] theorem diagonal_mul_diagonal' [decidable_eq n] (d₁ d₂ : n → α) : (diagonal d₁) ⬝ (diagonal d₂) = diagonal (λ i, d₁ i * d₂ i) := by ext i j; by_cases i = j; simp [h] theorem diagonal_mul_diagonal [decidable_eq n] (d₁ d₂ : n → α) : diagonal d₁ * diagonal d₂ = diagonal (λ i, d₁ i * d₂ i) := diagonal_mul_diagonal' _ _ end semiring section ring variables [ring α] @[simp] theorem neg_mul (M : matrix m n α) (N : matrix n o α) : (-M) ⬝ N = -(M ⬝ N) := by ext; simp [matrix.mul] @[simp] theorem mul_neg (M : matrix m n α) (N : matrix n o α) : M ⬝ (-N) = -(M ⬝ N) := by ext; simp [matrix.mul] end ring instance [decidable_eq n] [ring α] : ring (matrix n n α) := { ..matrix.add_comm_group, ..matrix.semiring } instance [semiring α] : has_scalar α (matrix m n α) := pi.has_scalar instance [ring α] : module α (matrix m n α) := pi.module _ section comm_ring variables [comm_ring α] @[simp] lemma mul_smul (M : matrix m n α) (a : α) (N : matrix n l α) : M ⬝ (a • N) = a • M ⬝ N := begin ext i j, unfold matrix.mul has_scalar.smul, rw finset.mul_sum, congr, ext, ac_refl end @[simp] lemma smul_mul (M : matrix m n α) (a : α) (N : matrix n l α) : (a • M) ⬝ N = a • M ⬝ N := begin ext i j, unfold matrix.mul has_scalar.smul, rw finset.mul_sum, congr, ext, ac_refl end end comm_ring section semiring variables [semiring α] def vec_mul_vec (w : m → α) (v : n → α) : matrix m n α | x y := w x * v y def mul_vec (M : matrix m n α) (v : n → α) : m → α | x := finset.univ.sum (λy:n, M x y * v y) def vec_mul (v : m → α) (M : matrix m n α) : n → α | y := finset.univ.sum (λx:m, v x * M x y) instance mul_vec.is_add_monoid_hom_left (v : n → α) : is_add_monoid_hom (λM:matrix m n α, mul_vec M v) := { map_zero := by ext; simp [mul_vec]; refl, map_add := begin intros x y, ext m, rw pi.add_apply (mul_vec x v) (mul_vec y v) m, simp [mul_vec, finset.sum_add_distrib, right_distrib] end } lemma mul_vec_diagonal [decidable_eq m] (v w : m → α) (x : m) : mul_vec (diagonal v) w x = v x * w x := begin transitivity, refine finset.sum_eq_single x _ _, { assume b _ ne, simp [diagonal, ne.symm] }, { simp }, { rw [diagonal_val_eq] } end lemma vec_mul_vec_eq (w : m → α) (v : n → α) : vec_mul_vec w v = (col w) ⬝ (row v) := by simp [matrix.mul]; refl end semiring section transpose local postfix `ᵀ` : 1500 := transpose lemma transpose_transpose (M : matrix m n α) : Mᵀᵀ = M := by ext; refl @[simp] lemma transpose_zero [has_zero α] : (0 : matrix m n α)ᵀ = 0 := by ext i j; refl @[simp] lemma transpose_add [has_add α] (M : matrix m n α) (N : matrix m n α) : (M + N)ᵀ = Mᵀ + Nᵀ := begin ext i j, dsimp [transpose], refl end @[simp] lemma transpose_mul [comm_ring α] (M : matrix m n α) (N : matrix n l α) : (M ⬝ N)ᵀ = Nᵀ ⬝ Mᵀ := begin ext i j, unfold matrix.mul transpose, congr, ext, ac_refl end @[simp] lemma transpose_neg [comm_ring α] (M : matrix m n α) : (- M)ᵀ = - Mᵀ := by ext i j; refl end transpose def minor (A : matrix m n α) (row : l → m) (col : o → n) : matrix l o α := λ i j, A (row i) (col j) @[reducible] def sub_left {m l r : nat} (A : matrix (fin m) (fin (l + r)) α) : matrix (fin m) (fin l) α := minor A id (fin.cast_add r) @[reducible] def sub_right {m l r : nat} (A : matrix (fin m) (fin (l + r)) α) : matrix (fin m) (fin r) α := minor A id (fin.nat_add l) @[reducible] def sub_up {d u n : nat} (A : matrix (fin (u + d)) (fin n) α) : matrix (fin u) (fin n) α := minor A (fin.cast_add d) id @[reducible] def sub_down {d u n : nat} (A : matrix (fin (u + d)) (fin n) α) : matrix (fin d) (fin n) α := minor A (fin.nat_add u) id @[reducible] def sub_up_right {d u l r : nat} (A: matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin u) (fin r) α := sub_up (sub_right A) @[reducible] def sub_down_right {d u l r : nat} (A : matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin d) (fin r) α := sub_down (sub_right A) @[reducible] def sub_up_left {d u l r : nat} (A : matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin u) (fin (l)) α := sub_up (sub_left A) @[reducible] def sub_down_left {d u l r : nat} (A: matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin d) (fin (l)) α := sub_down (sub_left A) end matrix
a088b6217cf52d227027c3368b03eaccb32a4c89
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch3/ex0204.lean
8de9bdffcfa6fd39cd4baa1aafcfff47928d3799
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
104
lean
constants p q : Prop theorem t1 : p → q → p := assume hp : p, assume hq : q, show p, from hp
8d5b21b31a2b3df3bd2e810f211ead0e5ad52fbe
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/simp_symm.lean
7e65699c373b6f59214a9cf8f49e7d6131d4ebac
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
1,146
lean
constants f g : nat → nat -- Test `simp` with lemmas in reverse direction axiom f_id : ∀ x, f x = x axiom f_g : ∀ x, f x = g x example (a : nat) : g a = a := by simp [←f_g, f_id] -- works -- Alternate syntax: example (a : nat) : g a = a := by simp [<-f_g, f_id] -- works -- Universe polymorphic lemmas work: universe u variable {α : Type u} constants fu gu : α → α axiom fu_id : ∀ (x : α), fu x = id x axiom fu_gu : ∀ (x : α), fu x = gu x example (a : nat) : gu a = a := by simp [←fu_gu, fu_id] -- works -- Reverse direction also works for `↔` constants p q : α → Prop axiom pq : ∀ (x : α), p x ↔ q x example (a : nat) (h : p a) : q a := by { simp [←pq], assumption } section reverse_conflict open interactive open tactic.interactive open tactic.simp_arg_type def op : nat → nat → nat := sorry @[simp] lemma op_assoc (a b c : nat) : op (op a b) c = op a (op b c) := sorry example (a b c : nat) : op (op a b) c = op a (op b c) := by tactic.try_for 1000 `[ simp [← op_assoc] ] example (a b c : nat) : a + b + c = a + (b + c) := by tactic.try_for 1000 `[ simp [← nat.add_assoc] ] end reverse_conflict
b0baeef8a1419401c7bea5d86c9856c942faf6ba
3692989e196fb48405e5baf3b03e67d12ac6d234
/bin/netkan-all.lean
fe11d347339af1b06d996afb982490685d0e8807
[ "CC0-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
KSP-CKAN/NetKAN-dev
0a7917112da6df60d63d7a1404457a2eeaa10810
1d25b6ea7e4c8122c096168c557ee3f2c30d37ad
refs/heads/master
1,611,223,769,071
1,584,935,607,000
1,584,935,607,000
28,596,366
3
4
CC0-1.0
1,584,935,608,000
1,419,866,595,000
Perl
UTF-8
Lean
false
false
609
lean
#!/usr/bin/perl use 5.010; use strict; use warnings; use autodie qw(:all); use JSON::PP qw(decode_json); use FindBin qw($Bin); use Try::Tiny; my $NETKAN_EXE = "$Bin/../../CKAN/netkan.exe"; my $NETKAN_DIR = "$Bin/../NetKAN"; my $CKAN_META = "$Bin/../../CKAN-meta"; # Convert KerbalStuff and GitHub releases into CKAN metadata! # It's the Networked Kerbal Archive Network. (NetKAN) :) chdir($NETKAN_DIR); foreach my $file (glob("*.netkan")) { say "$file..."; try { system($NETKAN_EXE, "--outputdir=$CKAN_META", $file); } catch { warn "Processing $file FAILED\n"; }; }
329b944b8152c68448823b19afc1d073e7fbb825
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/mv_polynomial/homogeneous.lean
b19dda3233d45b268936928e3abf1a715c01e94f
[ "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
10,866
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Eric Wieser -/ import algebra.direct_sum.internal import algebra.graded_monoid import data.mv_polynomial.variables /-! # Homogeneous polynomials A multivariate polynomial `φ` is homogeneous of degree `n` if all monomials occuring in `φ` have degree `n`. ## Main definitions/lemmas * `is_homogeneous φ n`: a predicate that asserts that `φ` is homogeneous of degree `n`. * `homogeneous_submodule σ R n`: the submodule of homogeneous polynomials of degree `n`. * `homogeneous_component n`: the additive morphism that projects polynomials onto their summand that is homogeneous of degree `n`. * `sum_homogeneous_component`: every polynomial is the sum of its homogeneous components -/ open_locale big_operators namespace mv_polynomial variables {σ : Type*} {τ : Type*} {R : Type*} {S : Type*} /- TODO * create definition for `∑ i in d.support, d i` * show that `mv_polynomial σ R ≃ₐ[R] ⨁ i, homogeneous_submodule σ R i` -/ /-- A multivariate polynomial `φ` is homogeneous of degree `n` if all monomials occuring in `φ` have degree `n`. -/ def is_homogeneous [comm_semiring R] (φ : mv_polynomial σ R) (n : ℕ) := ∀ ⦃d⦄, coeff d φ ≠ 0 → ∑ i in d.support, d i = n variables (σ R) /-- The submodule of homogeneous `mv_polynomial`s of degree `n`. -/ def homogeneous_submodule [comm_semiring R] (n : ℕ) : submodule R (mv_polynomial σ R) := { carrier := { x | x.is_homogeneous n }, smul_mem' := λ r a ha c hc, begin rw coeff_smul at hc, apply ha, intro h, apply hc, rw h, exact smul_zero r, end, zero_mem' := λ d hd, false.elim (hd $ coeff_zero _), add_mem' := λ a b ha hb c hc, begin rw coeff_add at hc, obtain h|h : coeff c a ≠ 0 ∨ coeff c b ≠ 0, { contrapose! hc, simp only [hc, add_zero] }, { exact ha h }, { exact hb h } end } variables {σ R} @[simp] lemma mem_homogeneous_submodule [comm_semiring R] (n : ℕ) (p : mv_polynomial σ R) : p ∈ homogeneous_submodule σ R n ↔ p.is_homogeneous n := iff.rfl variables (σ R) /-- While equal, the former has a convenient definitional reduction. -/ lemma homogeneous_submodule_eq_finsupp_supported [comm_semiring R] (n : ℕ) : homogeneous_submodule σ R n = finsupp.supported _ R {d | ∑ i in d.support, d i = n} := begin ext, rw [finsupp.mem_supported, set.subset_def], simp only [finsupp.mem_support_iff, finset.mem_coe], refl, end variables {σ R} lemma homogeneous_submodule_mul [comm_semiring R] (m n : ℕ) : homogeneous_submodule σ R m * homogeneous_submodule σ R n ≤ homogeneous_submodule σ R (m + n) := begin rw submodule.mul_le, intros φ hφ ψ hψ c hc, rw [coeff_mul] at hc, obtain ⟨⟨d, e⟩, hde, H⟩ := finset.exists_ne_zero_of_sum_ne_zero hc, have aux : coeff d φ ≠ 0 ∧ coeff e ψ ≠ 0, { contrapose! H, by_cases h : coeff d φ = 0; simp only [*, ne.def, not_false_iff, zero_mul, mul_zero] at * }, specialize hφ aux.1, specialize hψ aux.2, rw finsupp.mem_antidiagonal at hde, classical, have hd' : d.support ⊆ d.support ∪ e.support := finset.subset_union_left _ _, have he' : e.support ⊆ d.support ∪ e.support := finset.subset_union_right _ _, rw [← hde, ← hφ, ← hψ, finset.sum_subset (finsupp.support_add), finset.sum_subset hd', finset.sum_subset he', ← finset.sum_add_distrib], { congr }, all_goals { intros i hi, apply finsupp.not_mem_support_iff.mp }, end section variables [comm_semiring R] variables {σ R} lemma is_homogeneous_monomial (d : σ →₀ ℕ) (r : R) (n : ℕ) (hn : ∑ i in d.support, d i = n) : is_homogeneous (monomial d r) n := begin intros c hc, classical, rw coeff_monomial at hc, split_ifs at hc with h, { subst c, exact hn }, { contradiction } end variables (σ) {R} lemma is_homogeneous_of_total_degree_zero {p : mv_polynomial σ R} (hp : p.total_degree = 0) : is_homogeneous p 0 := begin erw [total_degree, finset.sup_eq_bot_iff] at hp, -- we have to do this in two steps to stop simp changing bot to zero simp_rw [mem_support_iff] at hp, exact hp, end lemma is_homogeneous_C (r : R) : is_homogeneous (C r : mv_polynomial σ R) 0 := begin apply is_homogeneous_monomial, simp only [finsupp.zero_apply, finset.sum_const_zero], end variables (σ R) lemma is_homogeneous_zero (n : ℕ) : is_homogeneous (0 : mv_polynomial σ R) n := (homogeneous_submodule σ R n).zero_mem lemma is_homogeneous_one : is_homogeneous (1 : mv_polynomial σ R) 0 := is_homogeneous_C _ _ variables {σ} (R) lemma is_homogeneous_X (i : σ) : is_homogeneous (X i : mv_polynomial σ R) 1 := begin apply is_homogeneous_monomial, simp only [finsupp.support_single_ne_zero _ one_ne_zero, finset.sum_singleton], exact finsupp.single_eq_same end end namespace is_homogeneous variables [comm_semiring R] {φ ψ : mv_polynomial σ R} {m n : ℕ} lemma coeff_eq_zero (hφ : is_homogeneous φ n) (d : σ →₀ ℕ) (hd : ∑ i in d.support, d i ≠ n) : coeff d φ = 0 := by { have aux := mt (@hφ d) hd, classical, rwa not_not at aux } lemma inj_right (hm : is_homogeneous φ m) (hn : is_homogeneous φ n) (hφ : φ ≠ 0) : m = n := begin obtain ⟨d, hd⟩ : ∃ d, coeff d φ ≠ 0 := exists_coeff_ne_zero hφ, rw [← hm hd, ← hn hd] end lemma add (hφ : is_homogeneous φ n) (hψ : is_homogeneous ψ n) : is_homogeneous (φ + ψ) n := (homogeneous_submodule σ R n).add_mem hφ hψ lemma sum {ι : Type*} (s : finset ι) (φ : ι → mv_polynomial σ R) (n : ℕ) (h : ∀ i ∈ s, is_homogeneous (φ i) n) : is_homogeneous (∑ i in s, φ i) n := (homogeneous_submodule σ R n).sum_mem h lemma mul (hφ : is_homogeneous φ m) (hψ : is_homogeneous ψ n) : is_homogeneous (φ * ψ) (m + n) := homogeneous_submodule_mul m n $ submodule.mul_mem_mul hφ hψ lemma prod {ι : Type*} (s : finset ι) (φ : ι → mv_polynomial σ R) (n : ι → ℕ) (h : ∀ i ∈ s, is_homogeneous (φ i) (n i)) : is_homogeneous (∏ i in s, φ i) (∑ i in s, n i) := begin classical, revert h, apply finset.induction_on s, { intro, simp only [is_homogeneous_one, finset.sum_empty, finset.prod_empty] }, { intros i s his IH h, simp only [his, finset.prod_insert, finset.sum_insert, not_false_iff], apply (h i (finset.mem_insert_self _ _)).mul (IH _), intros j hjs, exact h j (finset.mem_insert_of_mem hjs) } end lemma total_degree (hφ : is_homogeneous φ n) (h : φ ≠ 0) : total_degree φ = n := begin rw total_degree, apply le_antisymm, { apply finset.sup_le, intros d hd, rw mem_support_iff at hd, rw [finsupp.sum, hφ hd], }, { obtain ⟨d, hd⟩ : ∃ d, coeff d φ ≠ 0 := exists_coeff_ne_zero h, simp only [← hφ hd, finsupp.sum], replace hd := finsupp.mem_support_iff.mpr hd, exact finset.le_sup hd, } end /-- The homogeneous submodules form a graded ring. This instance is used by `direct_sum.comm_semiring` and `direct_sum.algebra`. -/ instance homogeneous_submodule.gcomm_semiring : set_like.graded_monoid (homogeneous_submodule σ R) := { one_mem := is_homogeneous_one σ R, mul_mem := λ i j xi xj, is_homogeneous.mul} open_locale direct_sum noncomputable example : comm_semiring (⨁ i, homogeneous_submodule σ R i) := infer_instance noncomputable example : algebra R (⨁ i, homogeneous_submodule σ R i) := infer_instance end is_homogeneous section noncomputable theory open_locale classical open finset /-- `homogeneous_component n φ` is the part of `φ` that is homogeneous of degree `n`. See `sum_homogeneous_component` for the statement that `φ` is equal to the sum of all its homogeneous components. -/ def homogeneous_component [comm_semiring R] (n : ℕ) : mv_polynomial σ R →ₗ[R] mv_polynomial σ R := (submodule.subtype _).comp $ finsupp.restrict_dom _ _ {d | ∑ i in d.support, d i = n} section homogeneous_component open finset variables [comm_semiring R] (n : ℕ) (φ ψ : mv_polynomial σ R) lemma coeff_homogeneous_component (d : σ →₀ ℕ) : coeff d (homogeneous_component n φ) = if ∑ i in d.support, d i = n then coeff d φ else 0 := by convert finsupp.filter_apply (λ d : σ →₀ ℕ, ∑ i in d.support, d i = n) φ d lemma homogeneous_component_apply : homogeneous_component n φ = ∑ d in φ.support.filter (λ d, ∑ i in d.support, d i = n), monomial d (coeff d φ) := by convert finsupp.filter_eq_sum (λ d : σ →₀ ℕ, ∑ i in d.support, d i = n) φ lemma homogeneous_component_is_homogeneous : (homogeneous_component n φ).is_homogeneous n := begin intros d hd, contrapose! hd, rw [coeff_homogeneous_component, if_neg hd] end @[simp] lemma homogeneous_component_zero : homogeneous_component 0 φ = C (coeff 0 φ) := begin ext1 d, rcases em (d = 0) with (rfl|hd), { simp only [coeff_homogeneous_component, sum_eq_zero_iff, finsupp.zero_apply, if_true, coeff_C, eq_self_iff_true, forall_true_iff] }, { rw [coeff_homogeneous_component, if_neg, coeff_C, if_neg (ne.symm hd)], simp only [finsupp.ext_iff, finsupp.zero_apply] at hd, simp [hd] } end @[simp] lemma homogeneous_component_C_mul (n : ℕ) (r : R) : homogeneous_component n (C r * φ) = C r * homogeneous_component n φ := by simp only [C_mul', linear_map.map_smul] lemma homogeneous_component_eq_zero' (h : ∀ d : σ →₀ ℕ, d ∈ φ.support → ∑ i in d.support, d i ≠ n) : homogeneous_component n φ = 0 := begin rw [homogeneous_component_apply, sum_eq_zero], intros d hd, rw mem_filter at hd, exfalso, exact h _ hd.1 hd.2 end lemma homogeneous_component_eq_zero (h : φ.total_degree < n) : homogeneous_component n φ = 0 := begin apply homogeneous_component_eq_zero', rw [total_degree, finset.sup_lt_iff] at h, { intros d hd, exact ne_of_lt (h d hd), }, { exact lt_of_le_of_lt (nat.zero_le _) h, } end lemma sum_homogeneous_component : ∑ i in range (φ.total_degree + 1), homogeneous_component i φ = φ := begin ext1 d, suffices : φ.total_degree < d.support.sum d → 0 = coeff d φ, by simpa [coeff_sum, coeff_homogeneous_component], exact λ h, (coeff_eq_zero_of_total_degree_lt h).symm end lemma homogeneous_component_homogeneous_polynomial (m n : ℕ) (p : mv_polynomial σ R) (h : p ∈ homogeneous_submodule σ R n) : homogeneous_component m p = if m = n then p else 0 := begin simp only [mem_homogeneous_submodule] at h, ext x, rw coeff_homogeneous_component, by_cases zero_coeff : coeff x p = 0, { split_ifs, all_goals { simp only [zero_coeff, coeff_zero], }, }, { rw h zero_coeff, simp only [show n = m ↔ m = n, from eq_comm], split_ifs with h1, { refl }, { simp only [coeff_zero] } } end end homogeneous_component end end mv_polynomial
d1ad0005acfc801c84ebdd48b360809fab9c8f6c
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/convex/side.lean
3b2f0899197eba297b7364d46bc77c75ff8b1861
[ "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
39,308
lean
/- Copyright (c) 2022 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import analysis.convex.between import analysis.convex.topology import analysis.normed.group.add_torsor /-! # Sides of affine subspaces This file defines notions of two points being on the same or opposite sides of an affine subspace. ## Main definitions * `s.w_same_side x y`: The points `x` and `y` are weakly on the same side of the affine subspace `s`. * `s.s_same_side x y`: The points `x` and `y` are strictly on the same side of the affine subspace `s`. * `s.w_opp_side x y`: The points `x` and `y` are weakly on opposite sides of the affine subspace `s`. * `s.s_opp_side x y`: The points `x` and `y` are strictly on opposite sides of the affine subspace `s`. -/ variables {R V V' P P' : Type*} open affine_equiv affine_map namespace affine_subspace section strict_ordered_comm_ring variables [strict_ordered_comm_ring R] [add_comm_group V] [module R V] [add_torsor V P] variables [add_comm_group V'] [module R V'] [add_torsor V' P'] include V /-- The points `x` and `y` are weakly on the same side of `s`. -/ def w_same_side (s : affine_subspace R P) (x y : P) : Prop := ∃ p₁ p₂ ∈ s, same_ray R (x -ᵥ p₁) (y -ᵥ p₂) /-- The points `x` and `y` are strictly on the same side of `s`. -/ def s_same_side (s : affine_subspace R P) (x y : P) : Prop := s.w_same_side x y ∧ x ∉ s ∧ y ∉ s /-- The points `x` and `y` are weakly on opposite sides of `s`. -/ def w_opp_side (s : affine_subspace R P) (x y : P) : Prop := ∃ p₁ p₂ ∈ s, same_ray R (x -ᵥ p₁) (p₂ -ᵥ y) /-- The points `x` and `y` are strictly on opposite sides of `s`. -/ def s_opp_side (s : affine_subspace R P) (x y : P) : Prop := s.w_opp_side x y ∧ x ∉ s ∧ y ∉ s include V' lemma w_same_side.map {s : affine_subspace R P} {x y : P} (h : s.w_same_side x y) (f : P →ᵃ[R] P') : (s.map f).w_same_side (f x) (f y) := begin rcases h with ⟨p₁, hp₁, p₂, hp₂, h⟩, refine ⟨f p₁, mem_map_of_mem f hp₁, f p₂, mem_map_of_mem f hp₂, _⟩, simp_rw [←linear_map_vsub], exact h.map f.linear end lemma _root_.function.injective.w_same_side_map_iff {s : affine_subspace R P} {x y : P} {f : P →ᵃ[R] P'} (hf : function.injective f) : (s.map f).w_same_side (f x) (f y) ↔ s.w_same_side x y := begin refine ⟨λ h, _, λ h, h.map _⟩, rcases h with ⟨fp₁, hfp₁, fp₂, hfp₂, h⟩, rw mem_map at hfp₁ hfp₂, rcases hfp₁ with ⟨p₁, hp₁, rfl⟩, rcases hfp₂ with ⟨p₂, hp₂, rfl⟩, refine ⟨p₁, hp₁, p₂, hp₂, _⟩, simp_rw [←linear_map_vsub, (f.injective_iff_linear_injective.2 hf).same_ray_map_iff] at h, exact h end lemma _root_.function.injective.s_same_side_map_iff {s : affine_subspace R P} {x y : P} {f : P →ᵃ[R] P'} (hf : function.injective f) : (s.map f).s_same_side (f x) (f y) ↔ s.s_same_side x y := by simp_rw [s_same_side, hf.w_same_side_map_iff, mem_map_iff_mem_of_injective hf] @[simp] lemma _root_.affine_equiv.w_same_side_map_iff {s : affine_subspace R P} {x y : P} (f : P ≃ᵃ[R] P') : (s.map ↑f).w_same_side (f x) (f y) ↔ s.w_same_side x y := (show function.injective f.to_affine_map, from f.injective).w_same_side_map_iff @[simp] lemma _root_.affine_equiv.s_same_side_map_iff {s : affine_subspace R P} {x y : P} (f : P ≃ᵃ[R] P') : (s.map ↑f).s_same_side (f x) (f y) ↔ s.s_same_side x y := (show function.injective f.to_affine_map, from f.injective).s_same_side_map_iff lemma w_opp_side.map {s : affine_subspace R P} {x y : P} (h : s.w_opp_side x y) (f : P →ᵃ[R] P') : (s.map f).w_opp_side (f x) (f y) := begin rcases h with ⟨p₁, hp₁, p₂, hp₂, h⟩, refine ⟨f p₁, mem_map_of_mem f hp₁, f p₂, mem_map_of_mem f hp₂, _⟩, simp_rw [←linear_map_vsub], exact h.map f.linear end lemma _root_.function.injective.w_opp_side_map_iff {s : affine_subspace R P} {x y : P} {f : P →ᵃ[R] P'} (hf : function.injective f) : (s.map f).w_opp_side (f x) (f y) ↔ s.w_opp_side x y := begin refine ⟨λ h, _, λ h, h.map _⟩, rcases h with ⟨fp₁, hfp₁, fp₂, hfp₂, h⟩, rw mem_map at hfp₁ hfp₂, rcases hfp₁ with ⟨p₁, hp₁, rfl⟩, rcases hfp₂ with ⟨p₂, hp₂, rfl⟩, refine ⟨p₁, hp₁, p₂, hp₂, _⟩, simp_rw [←linear_map_vsub, (f.injective_iff_linear_injective.2 hf).same_ray_map_iff] at h, exact h end lemma _root_.function.injective.s_opp_side_map_iff {s : affine_subspace R P} {x y : P} {f : P →ᵃ[R] P'} (hf : function.injective f) : (s.map f).s_opp_side (f x) (f y) ↔ s.s_opp_side x y := by simp_rw [s_opp_side, hf.w_opp_side_map_iff, mem_map_iff_mem_of_injective hf] @[simp] lemma _root_.affine_equiv.w_opp_side_map_iff {s : affine_subspace R P} {x y : P} (f : P ≃ᵃ[R] P') : (s.map ↑f).w_opp_side (f x) (f y) ↔ s.w_opp_side x y := (show function.injective f.to_affine_map, from f.injective).w_opp_side_map_iff @[simp] lemma _root_.affine_equiv.s_opp_side_map_iff {s : affine_subspace R P} {x y : P} (f : P ≃ᵃ[R] P') : (s.map ↑f).s_opp_side (f x) (f y) ↔ s.s_opp_side x y := (show function.injective f.to_affine_map, from f.injective).s_opp_side_map_iff omit V' lemma w_same_side.nonempty {s : affine_subspace R P} {x y : P} (h : s.w_same_side x y) : (s : set P).nonempty := ⟨h.some, h.some_spec.some⟩ lemma s_same_side.nonempty {s : affine_subspace R P} {x y : P} (h : s.s_same_side x y) : (s : set P).nonempty := ⟨h.1.some, h.1.some_spec.some⟩ lemma w_opp_side.nonempty {s : affine_subspace R P} {x y : P} (h : s.w_opp_side x y) : (s : set P).nonempty := ⟨h.some, h.some_spec.some⟩ lemma s_opp_side.nonempty {s : affine_subspace R P} {x y : P} (h : s.s_opp_side x y) : (s : set P).nonempty := ⟨h.1.some, h.1.some_spec.some⟩ lemma s_same_side.w_same_side {s : affine_subspace R P} {x y : P} (h : s.s_same_side x y) : s.w_same_side x y := h.1 lemma s_same_side.left_not_mem {s : affine_subspace R P} {x y : P} (h : s.s_same_side x y) : x ∉ s := h.2.1 lemma s_same_side.right_not_mem {s : affine_subspace R P} {x y : P} (h : s.s_same_side x y) : y ∉ s := h.2.2 lemma s_opp_side.w_opp_side {s : affine_subspace R P} {x y : P} (h : s.s_opp_side x y) : s.w_opp_side x y := h.1 lemma s_opp_side.left_not_mem {s : affine_subspace R P} {x y : P} (h : s.s_opp_side x y) : x ∉ s := h.2.1 lemma s_opp_side.right_not_mem {s : affine_subspace R P} {x y : P} (h : s.s_opp_side x y) : y ∉ s := h.2.2 lemma w_same_side_comm {s : affine_subspace R P} {x y : P} : s.w_same_side x y ↔ s.w_same_side y x := ⟨λ ⟨p₁, hp₁, p₂, hp₂, h⟩, ⟨p₂, hp₂, p₁, hp₁, h.symm⟩, λ ⟨p₁, hp₁, p₂, hp₂, h⟩, ⟨p₂, hp₂, p₁, hp₁, h.symm⟩⟩ alias w_same_side_comm ↔ w_same_side.symm _ lemma s_same_side_comm {s : affine_subspace R P} {x y : P} : s.s_same_side x y ↔ s.s_same_side y x := by rw [s_same_side, s_same_side, w_same_side_comm, and_comm (x ∉ s)] alias s_same_side_comm ↔ s_same_side.symm _ lemma w_opp_side_comm {s : affine_subspace R P} {x y : P} : s.w_opp_side x y ↔ s.w_opp_side y x := begin split, { rintro ⟨p₁, hp₁, p₂, hp₂, h⟩, refine ⟨p₂, hp₂, p₁, hp₁, _⟩, rwa [same_ray_comm, ←same_ray_neg_iff, neg_vsub_eq_vsub_rev, neg_vsub_eq_vsub_rev] }, { rintro ⟨p₁, hp₁, p₂, hp₂, h⟩, refine ⟨p₂, hp₂, p₁, hp₁, _⟩, rwa [same_ray_comm, ←same_ray_neg_iff, neg_vsub_eq_vsub_rev, neg_vsub_eq_vsub_rev] } end alias w_opp_side_comm ↔ w_opp_side.symm _ lemma s_opp_side_comm {s : affine_subspace R P} {x y : P} : s.s_opp_side x y ↔ s.s_opp_side y x := by rw [s_opp_side, s_opp_side, w_opp_side_comm, and_comm (x ∉ s)] alias s_opp_side_comm ↔ s_opp_side.symm _ lemma not_w_same_side_bot (x y : P) : ¬ (⊥ : affine_subspace R P).w_same_side x y := by simp [w_same_side, not_mem_bot] lemma not_s_same_side_bot (x y : P) : ¬ (⊥ : affine_subspace R P).s_same_side x y := λ h, not_w_same_side_bot x y h.w_same_side lemma not_w_opp_side_bot (x y : P) : ¬ (⊥ : affine_subspace R P).w_opp_side x y := by simp [w_opp_side, not_mem_bot] lemma not_s_opp_side_bot (x y : P) : ¬ (⊥ : affine_subspace R P).s_opp_side x y := λ h, not_w_opp_side_bot x y h.w_opp_side @[simp] lemma w_same_side_self_iff {s : affine_subspace R P} {x : P} : s.w_same_side x x ↔ (s : set P).nonempty := ⟨λ h, h.nonempty, λ ⟨p, hp⟩, ⟨p, hp, p, hp, same_ray.rfl⟩⟩ lemma s_same_side_self_iff {s : affine_subspace R P} {x : P} : s.s_same_side x x ↔ (s : set P).nonempty ∧ x ∉ s := ⟨λ ⟨h, hx, _⟩, ⟨w_same_side_self_iff.1 h, hx⟩, λ ⟨h, hx⟩, ⟨w_same_side_self_iff.2 h, hx, hx⟩⟩ lemma w_same_side_of_left_mem {s : affine_subspace R P} {x : P} (y : P) (hx : x ∈ s) : s.w_same_side x y := begin refine ⟨x, hx, x, hx, _⟩, simp end lemma w_same_side_of_right_mem {s : affine_subspace R P} (x : P) {y : P} (hy : y ∈ s) : s.w_same_side x y := (w_same_side_of_left_mem x hy).symm lemma w_opp_side_of_left_mem {s : affine_subspace R P} {x : P} (y : P) (hx : x ∈ s) : s.w_opp_side x y := begin refine ⟨x, hx, x, hx, _⟩, simp end lemma w_opp_side_of_right_mem {s : affine_subspace R P} (x : P) {y : P} (hy : y ∈ s) : s.w_opp_side x y := (w_opp_side_of_left_mem x hy).symm lemma w_same_side_vadd_left_iff {s : affine_subspace R P} {x y : P} {v : V} (hv : v ∈ s.direction) : s.w_same_side (v +ᵥ x) y ↔ s.w_same_side x y := begin split, { rintro ⟨p₁, hp₁, p₂, hp₂, h⟩, refine ⟨-v +ᵥ p₁, affine_subspace.vadd_mem_of_mem_direction (submodule.neg_mem _ hv) hp₁, p₂, hp₂, _⟩, rwa [vsub_vadd_eq_vsub_sub, sub_neg_eq_add, add_comm, ←vadd_vsub_assoc] }, { rintro ⟨p₁, hp₁, p₂, hp₂, h⟩, refine ⟨v +ᵥ p₁, affine_subspace.vadd_mem_of_mem_direction hv hp₁, p₂, hp₂, _⟩, rwa vadd_vsub_vadd_cancel_left } end lemma w_same_side_vadd_right_iff {s : affine_subspace R P} {x y : P} {v : V} (hv : v ∈ s.direction) : s.w_same_side x (v +ᵥ y) ↔ s.w_same_side x y := by rw [w_same_side_comm, w_same_side_vadd_left_iff hv, w_same_side_comm] lemma s_same_side_vadd_left_iff {s : affine_subspace R P} {x y : P} {v : V} (hv : v ∈ s.direction) : s.s_same_side (v +ᵥ x) y ↔ s.s_same_side x y := by rw [s_same_side, s_same_side, w_same_side_vadd_left_iff hv, vadd_mem_iff_mem_of_mem_direction hv] lemma s_same_side_vadd_right_iff {s : affine_subspace R P} {x y : P} {v : V} (hv : v ∈ s.direction) : s.s_same_side x (v +ᵥ y) ↔ s.s_same_side x y := by rw [s_same_side_comm, s_same_side_vadd_left_iff hv, s_same_side_comm] lemma w_opp_side_vadd_left_iff {s : affine_subspace R P} {x y : P} {v : V} (hv : v ∈ s.direction) : s.w_opp_side (v +ᵥ x) y ↔ s.w_opp_side x y := begin split, { rintro ⟨p₁, hp₁, p₂, hp₂, h⟩, refine ⟨-v +ᵥ p₁, affine_subspace.vadd_mem_of_mem_direction (submodule.neg_mem _ hv) hp₁, p₂, hp₂, _⟩, rwa [vsub_vadd_eq_vsub_sub, sub_neg_eq_add, add_comm, ←vadd_vsub_assoc] }, { rintro ⟨p₁, hp₁, p₂, hp₂, h⟩, refine ⟨v +ᵥ p₁, affine_subspace.vadd_mem_of_mem_direction hv hp₁, p₂, hp₂, _⟩, rwa vadd_vsub_vadd_cancel_left } end lemma w_opp_side_vadd_right_iff {s : affine_subspace R P} {x y : P} {v : V} (hv : v ∈ s.direction) : s.w_opp_side x (v +ᵥ y) ↔ s.w_opp_side x y := by rw [w_opp_side_comm, w_opp_side_vadd_left_iff hv, w_opp_side_comm] lemma s_opp_side_vadd_left_iff {s : affine_subspace R P} {x y : P} {v : V} (hv : v ∈ s.direction) : s.s_opp_side (v +ᵥ x) y ↔ s.s_opp_side x y := by rw [s_opp_side, s_opp_side, w_opp_side_vadd_left_iff hv, vadd_mem_iff_mem_of_mem_direction hv] lemma s_opp_side_vadd_right_iff {s : affine_subspace R P} {x y : P} {v : V} (hv : v ∈ s.direction) : s.s_opp_side x (v +ᵥ y) ↔ s.s_opp_side x y := by rw [s_opp_side_comm, s_opp_side_vadd_left_iff hv, s_opp_side_comm] lemma w_same_side_smul_vsub_vadd_left {s : affine_subspace R P} {p₁ p₂ : P} (x : P) (hp₁ : p₁ ∈ s) (hp₂ : p₂ ∈ s) {t : R} (ht : 0 ≤ t) : s.w_same_side (t • (x -ᵥ p₁) +ᵥ p₂) x := begin refine ⟨p₂, hp₂, p₁, hp₁, _⟩, rw vadd_vsub, exact same_ray_nonneg_smul_left _ ht end lemma w_same_side_smul_vsub_vadd_right {s : affine_subspace R P} {p₁ p₂ : P} (x : P) (hp₁ : p₁ ∈ s) (hp₂ : p₂ ∈ s) {t : R} (ht : 0 ≤ t) : s.w_same_side x (t • (x -ᵥ p₁) +ᵥ p₂) := (w_same_side_smul_vsub_vadd_left x hp₁ hp₂ ht).symm lemma w_same_side_line_map_left {s : affine_subspace R P} {x : P} (y : P) (h : x ∈ s) {t : R} (ht : 0 ≤ t) : s.w_same_side (line_map x y t) y := w_same_side_smul_vsub_vadd_left y h h ht lemma w_same_side_line_map_right {s : affine_subspace R P} {x : P} (y : P) (h : x ∈ s) {t : R} (ht : 0 ≤ t) : s.w_same_side y (line_map x y t) := (w_same_side_line_map_left y h ht).symm lemma w_opp_side_smul_vsub_vadd_left {s : affine_subspace R P} {p₁ p₂ : P} (x : P) (hp₁ : p₁ ∈ s) (hp₂ : p₂ ∈ s) {t : R} (ht : t ≤ 0) : s.w_opp_side (t • (x -ᵥ p₁) +ᵥ p₂) x := begin refine ⟨p₂, hp₂, p₁, hp₁, _⟩, rw [vadd_vsub, ←neg_neg t, neg_smul, ←smul_neg, neg_vsub_eq_vsub_rev], exact same_ray_nonneg_smul_left _ (neg_nonneg.2 ht) end lemma w_opp_side_smul_vsub_vadd_right {s : affine_subspace R P} {p₁ p₂ : P} (x : P) (hp₁ : p₁ ∈ s) (hp₂ : p₂ ∈ s) {t : R} (ht : t ≤ 0) : s.w_opp_side x (t • (x -ᵥ p₁) +ᵥ p₂) := (w_opp_side_smul_vsub_vadd_left x hp₁ hp₂ ht).symm lemma w_opp_side_line_map_left {s : affine_subspace R P} {x : P} (y : P) (h : x ∈ s) {t : R} (ht : t ≤ 0) : s.w_opp_side (line_map x y t) y := w_opp_side_smul_vsub_vadd_left y h h ht lemma w_opp_side_line_map_right {s : affine_subspace R P} {x : P} (y : P) (h : x ∈ s) {t : R} (ht : t ≤ 0) : s.w_opp_side y (line_map x y t) := (w_opp_side_line_map_left y h ht).symm lemma _root_.wbtw.w_same_side₂₃ {s : affine_subspace R P} {x y z : P} (h : wbtw R x y z) (hx : x ∈ s) : s.w_same_side y z := begin rcases h with ⟨t, ⟨ht0, -⟩, rfl⟩, exact w_same_side_line_map_left z hx ht0 end lemma _root_.wbtw.w_same_side₃₂ {s : affine_subspace R P} {x y z : P} (h : wbtw R x y z) (hx : x ∈ s) : s.w_same_side z y := (h.w_same_side₂₃ hx).symm lemma _root_.wbtw.w_same_side₁₂ {s : affine_subspace R P} {x y z : P} (h : wbtw R x y z) (hz : z ∈ s) : s.w_same_side x y := h.symm.w_same_side₃₂ hz lemma _root_.wbtw.w_same_side₂₁ {s : affine_subspace R P} {x y z : P} (h : wbtw R x y z) (hz : z ∈ s) : s.w_same_side y x := h.symm.w_same_side₂₃ hz lemma _root_.wbtw.w_opp_side₁₃ {s : affine_subspace R P} {x y z : P} (h : wbtw R x y z) (hy : y ∈ s) : s.w_opp_side x z := begin rcases h with ⟨t, ⟨ht0, ht1⟩, rfl⟩, refine ⟨_, hy, _, hy, _⟩, rcases ht1.lt_or_eq with ht1' | rfl, swap, { simp }, rcases ht0.lt_or_eq with ht0' | rfl, swap, { simp }, refine or.inr (or.inr ⟨1 - t, t, sub_pos.2 ht1', ht0', _⟩), simp_rw [line_map_apply, vadd_vsub_assoc, vsub_vadd_eq_vsub_sub, ←neg_vsub_eq_vsub_rev z x, vsub_self, zero_sub, ←neg_one_smul R (z -ᵥ x), ←add_smul, smul_neg, ←neg_smul, smul_smul], ring_nf end lemma _root_.wbtw.w_opp_side₃₁ {s : affine_subspace R P} {x y z : P} (h : wbtw R x y z) (hy : y ∈ s) : s.w_opp_side z x := h.symm.w_opp_side₁₃ hy end strict_ordered_comm_ring section linear_ordered_field variables [linear_ordered_field R] [add_comm_group V] [module R V] [add_torsor V P] variables [add_comm_group V'] [module R V'] [add_torsor V' P'] include V variables {R} @[simp] lemma w_opp_side_self_iff {s : affine_subspace R P} {x : P} : s.w_opp_side x x ↔ x ∈ s := begin split, { rintro ⟨p₁, hp₁, p₂, hp₂, h⟩, obtain ⟨a, -, -, -, -, h₁, -⟩ := h.exists_eq_smul_add, rw [add_comm, vsub_add_vsub_cancel, ←eq_vadd_iff_vsub_eq] at h₁, rw h₁, exact s.smul_vsub_vadd_mem a hp₂ hp₁ hp₁ }, { exact λ h, ⟨x, h, x, h, same_ray.rfl⟩ } end lemma not_s_opp_side_self (s : affine_subspace R P) (x : P) : ¬s.s_opp_side x x := by simp [s_opp_side] lemma w_same_side_iff_exists_left {s : affine_subspace R P} {x y p₁ : P} (h : p₁ ∈ s) : s.w_same_side x y ↔ x ∈ s ∨ ∃ p₂ ∈ s, same_ray R (x -ᵥ p₁) (y -ᵥ p₂) := begin split, { rintro ⟨p₁', hp₁', p₂', hp₂', h0 | h0 | ⟨r₁, r₂, hr₁, hr₂, hr⟩⟩, { rw vsub_eq_zero_iff_eq at h0, rw h0, exact or.inl hp₁' }, { refine or.inr ⟨p₂', hp₂', _⟩, rw h0, exact same_ray.zero_right _ }, { refine or.inr ⟨(r₁ / r₂) • (p₁ -ᵥ p₁') +ᵥ p₂', s.smul_vsub_vadd_mem _ h hp₁' hp₂', or.inr (or.inr ⟨r₁, r₂, hr₁, hr₂, _⟩)⟩, rw [vsub_vadd_eq_vsub_sub, smul_sub, ←hr, smul_smul, mul_div_cancel' _ hr₂.ne.symm, ←smul_sub, vsub_sub_vsub_cancel_right] } }, { rintro (h' | h'), { exact w_same_side_of_left_mem y h' }, { exact ⟨p₁, h, h'⟩ } } end lemma w_same_side_iff_exists_right {s : affine_subspace R P} {x y p₂ : P} (h : p₂ ∈ s) : s.w_same_side x y ↔ y ∈ s ∨ ∃ p₁ ∈ s, same_ray R (x -ᵥ p₁) (y -ᵥ p₂) := begin rw [w_same_side_comm, w_same_side_iff_exists_left h], simp_rw same_ray_comm end lemma s_same_side_iff_exists_left {s : affine_subspace R P} {x y p₁ : P} (h : p₁ ∈ s) : s.s_same_side x y ↔ x ∉ s ∧ y ∉ s ∧ ∃ p₂ ∈ s, same_ray R (x -ᵥ p₁) (y -ᵥ p₂) := begin rw [s_same_side, and_comm, w_same_side_iff_exists_left h, and_assoc, and.congr_right_iff], intro hx, rw or_iff_right hx end lemma s_same_side_iff_exists_right {s : affine_subspace R P} {x y p₂ : P} (h : p₂ ∈ s) : s.s_same_side x y ↔ x ∉ s ∧ y ∉ s ∧ ∃ p₁ ∈ s, same_ray R (x -ᵥ p₁) (y -ᵥ p₂) := begin rw [s_same_side_comm, s_same_side_iff_exists_left h, ←and_assoc, and_comm (y ∉ s), and_assoc], simp_rw same_ray_comm end lemma w_opp_side_iff_exists_left {s : affine_subspace R P} {x y p₁ : P} (h : p₁ ∈ s) : s.w_opp_side x y ↔ x ∈ s ∨ ∃ p₂ ∈ s, same_ray R (x -ᵥ p₁) (p₂ -ᵥ y) := begin split, { rintro ⟨p₁', hp₁', p₂', hp₂', h0 | h0 | ⟨r₁, r₂, hr₁, hr₂, hr⟩⟩, { rw vsub_eq_zero_iff_eq at h0, rw h0, exact or.inl hp₁' }, { refine or.inr ⟨p₂', hp₂', _⟩, rw h0, exact same_ray.zero_right _ }, { refine or.inr ⟨(-r₁ / r₂) • (p₁ -ᵥ p₁') +ᵥ p₂', s.smul_vsub_vadd_mem _ h hp₁' hp₂', or.inr (or.inr ⟨r₁, r₂, hr₁, hr₂, _⟩)⟩, rw [vadd_vsub_assoc, smul_add, ←hr, smul_smul, neg_div, mul_neg, mul_div_cancel' _ hr₂.ne.symm, neg_smul, neg_add_eq_sub, ←smul_sub, vsub_sub_vsub_cancel_right] } }, { rintro (h' | h'), { exact w_opp_side_of_left_mem y h' }, { exact ⟨p₁, h, h'⟩ } } end lemma w_opp_side_iff_exists_right {s : affine_subspace R P} {x y p₂ : P} (h : p₂ ∈ s) : s.w_opp_side x y ↔ y ∈ s ∨ ∃ p₁ ∈ s, same_ray R (x -ᵥ p₁) (p₂ -ᵥ y) := begin rw [w_opp_side_comm, w_opp_side_iff_exists_left h], split, { rintro (hy | ⟨p, hp, hr⟩), { exact or.inl hy }, refine or.inr ⟨p, hp, _⟩, rwa [same_ray_comm, ←same_ray_neg_iff, neg_vsub_eq_vsub_rev, neg_vsub_eq_vsub_rev] }, { rintro (hy | ⟨p, hp, hr⟩), { exact or.inl hy }, refine or.inr ⟨p, hp, _⟩, rwa [same_ray_comm, ←same_ray_neg_iff, neg_vsub_eq_vsub_rev, neg_vsub_eq_vsub_rev] } end lemma s_opp_side_iff_exists_left {s : affine_subspace R P} {x y p₁ : P} (h : p₁ ∈ s) : s.s_opp_side x y ↔ x ∉ s ∧ y ∉ s ∧ ∃ p₂ ∈ s, same_ray R (x -ᵥ p₁) (p₂ -ᵥ y) := begin rw [s_opp_side, and_comm, w_opp_side_iff_exists_left h, and_assoc, and.congr_right_iff], intro hx, rw or_iff_right hx end lemma s_opp_side_iff_exists_right {s : affine_subspace R P} {x y p₂ : P} (h : p₂ ∈ s) : s.s_opp_side x y ↔ x ∉ s ∧ y ∉ s ∧ ∃ p₁ ∈ s, same_ray R (x -ᵥ p₁) (p₂ -ᵥ y) := begin rw [s_opp_side, and_comm, w_opp_side_iff_exists_right h, and_assoc, and.congr_right_iff, and.congr_right_iff], rintro hx hy, rw or_iff_right hy end lemma w_same_side.trans {s : affine_subspace R P} {x y z : P} (hxy : s.w_same_side x y) (hyz : s.w_same_side y z) (hy : y ∉ s) : s.w_same_side x z := begin rcases hxy with ⟨p₁, hp₁, p₂, hp₂, hxy⟩, rw [w_same_side_iff_exists_left hp₂, or_iff_right hy] at hyz, rcases hyz with ⟨p₃, hp₃, hyz⟩, refine ⟨p₁, hp₁, p₃, hp₃, hxy.trans hyz _⟩, refine λ h, false.elim _, rw vsub_eq_zero_iff_eq at h, exact hy (h.symm ▸ hp₂) end lemma w_same_side.trans_s_same_side {s : affine_subspace R P} {x y z : P} (hxy : s.w_same_side x y) (hyz : s.s_same_side y z) : s.w_same_side x z := hxy.trans hyz.1 hyz.2.1 lemma w_same_side.trans_w_opp_side {s : affine_subspace R P} {x y z : P} (hxy : s.w_same_side x y) (hyz : s.w_opp_side y z) (hy : y ∉ s) : s.w_opp_side x z := begin rcases hxy with ⟨p₁, hp₁, p₂, hp₂, hxy⟩, rw [w_opp_side_iff_exists_left hp₂, or_iff_right hy] at hyz, rcases hyz with ⟨p₃, hp₃, hyz⟩, refine ⟨p₁, hp₁, p₃, hp₃, hxy.trans hyz _⟩, refine λ h, false.elim _, rw vsub_eq_zero_iff_eq at h, exact hy (h.symm ▸ hp₂) end lemma w_same_side.trans_s_opp_side {s : affine_subspace R P} {x y z : P} (hxy : s.w_same_side x y) (hyz : s.s_opp_side y z) : s.w_opp_side x z := hxy.trans_w_opp_side hyz.1 hyz.2.1 lemma s_same_side.trans_w_same_side {s : affine_subspace R P} {x y z : P} (hxy : s.s_same_side x y) (hyz : s.w_same_side y z) : s.w_same_side x z := (hyz.symm.trans_s_same_side hxy.symm).symm lemma s_same_side.trans {s : affine_subspace R P} {x y z : P} (hxy : s.s_same_side x y) (hyz : s.s_same_side y z) : s.s_same_side x z := ⟨hxy.w_same_side.trans_s_same_side hyz, hxy.2.1, hyz.2.2⟩ lemma s_same_side.trans_w_opp_side {s : affine_subspace R P} {x y z : P} (hxy : s.s_same_side x y) (hyz : s.w_opp_side y z) : s.w_opp_side x z := hxy.w_same_side.trans_w_opp_side hyz hxy.2.2 lemma s_same_side.trans_s_opp_side {s : affine_subspace R P} {x y z : P} (hxy : s.s_same_side x y) (hyz : s.s_opp_side y z) : s.s_opp_side x z := ⟨hxy.trans_w_opp_side hyz.1, hxy.2.1, hyz.2.2⟩ lemma w_opp_side.trans_w_same_side {s : affine_subspace R P} {x y z : P} (hxy : s.w_opp_side x y) (hyz : s.w_same_side y z) (hy : y ∉ s) : s.w_opp_side x z := (hyz.symm.trans_w_opp_side hxy.symm hy).symm lemma w_opp_side.trans_s_same_side {s : affine_subspace R P} {x y z : P} (hxy : s.w_opp_side x y) (hyz : s.s_same_side y z) : s.w_opp_side x z := hxy.trans_w_same_side hyz.1 hyz.2.1 lemma w_opp_side.trans {s : affine_subspace R P} {x y z : P} (hxy : s.w_opp_side x y) (hyz : s.w_opp_side y z) (hy : y ∉ s) : s.w_same_side x z := begin rcases hxy with ⟨p₁, hp₁, p₂, hp₂, hxy⟩, rw [w_opp_side_iff_exists_left hp₂, or_iff_right hy] at hyz, rcases hyz with ⟨p₃, hp₃, hyz⟩, rw [←same_ray_neg_iff, neg_vsub_eq_vsub_rev, neg_vsub_eq_vsub_rev] at hyz, refine ⟨p₁, hp₁, p₃, hp₃, hxy.trans hyz _⟩, refine λ h, false.elim _, rw vsub_eq_zero_iff_eq at h, exact hy (h ▸ hp₂) end lemma w_opp_side.trans_s_opp_side {s : affine_subspace R P} {x y z : P} (hxy : s.w_opp_side x y) (hyz : s.s_opp_side y z) : s.w_same_side x z := hxy.trans hyz.1 hyz.2.1 lemma s_opp_side.trans_w_same_side {s : affine_subspace R P} {x y z : P} (hxy : s.s_opp_side x y) (hyz : s.w_same_side y z) : s.w_opp_side x z := (hyz.symm.trans_s_opp_side hxy.symm).symm lemma s_opp_side.trans_s_same_side {s : affine_subspace R P} {x y z : P} (hxy : s.s_opp_side x y) (hyz : s.s_same_side y z) : s.s_opp_side x z := (hyz.symm.trans_s_opp_side hxy.symm).symm lemma s_opp_side.trans_w_opp_side {s : affine_subspace R P} {x y z : P} (hxy : s.s_opp_side x y) (hyz : s.w_opp_side y z) : s.w_same_side x z := (hyz.symm.trans_s_opp_side hxy.symm).symm lemma s_opp_side.trans {s : affine_subspace R P} {x y z : P} (hxy : s.s_opp_side x y) (hyz : s.s_opp_side y z) : s.s_same_side x z := ⟨hxy.trans_w_opp_side hyz.1, hxy.2.1, hyz.2.2⟩ lemma w_same_side_and_w_opp_side_iff {s : affine_subspace R P} {x y : P} : (s.w_same_side x y ∧ s.w_opp_side x y) ↔ (x ∈ s ∨ y ∈ s) := begin split, { rintro ⟨hs, ho⟩, rw w_opp_side_comm at ho, by_contra h, rw not_or_distrib at h, exact h.1 (w_opp_side_self_iff.1 (hs.trans_w_opp_side ho h.2)) }, { rintro (h | h), { exact ⟨w_same_side_of_left_mem y h, w_opp_side_of_left_mem y h⟩ }, { exact ⟨w_same_side_of_right_mem x h, w_opp_side_of_right_mem x h⟩ } } end lemma w_same_side.not_s_opp_side {s : affine_subspace R P} {x y : P} (h : s.w_same_side x y) : ¬s.s_opp_side x y := begin intro ho, have hxy := w_same_side_and_w_opp_side_iff.1 ⟨h, ho.1⟩, rcases hxy with hx | hy, { exact ho.2.1 hx }, { exact ho.2.2 hy } end lemma s_same_side.not_w_opp_side {s : affine_subspace R P} {x y : P} (h : s.s_same_side x y) : ¬s.w_opp_side x y := begin intro ho, have hxy := w_same_side_and_w_opp_side_iff.1 ⟨h.1, ho⟩, rcases hxy with hx | hy, { exact h.2.1 hx }, { exact h.2.2 hy } end lemma s_same_side.not_s_opp_side {s : affine_subspace R P} {x y : P} (h : s.s_same_side x y) : ¬s.s_opp_side x y := λ ho, h.not_w_opp_side ho.1 lemma w_opp_side.not_s_same_side {s : affine_subspace R P} {x y : P} (h : s.w_opp_side x y) : ¬s.s_same_side x y := λ hs, hs.not_w_opp_side h lemma s_opp_side.not_w_same_side {s : affine_subspace R P} {x y : P} (h : s.s_opp_side x y) : ¬s.w_same_side x y := λ hs, hs.not_s_opp_side h lemma s_opp_side.not_s_same_side {s : affine_subspace R P} {x y : P} (h : s.s_opp_side x y) : ¬s.s_same_side x y := λ hs, h.not_w_same_side hs.1 lemma w_opp_side_iff_exists_wbtw {s : affine_subspace R P} {x y : P} : s.w_opp_side x y ↔ ∃ p ∈ s, wbtw R x p y := begin refine ⟨λ h, _, λ ⟨p, hp, h⟩, h.w_opp_side₁₃ hp⟩, rcases h with ⟨p₁, hp₁, p₂, hp₂, (h | h | ⟨r₁, r₂, hr₁, hr₂, h⟩)⟩, { rw vsub_eq_zero_iff_eq at h, rw h, exact ⟨p₁, hp₁, wbtw_self_left _ _ _⟩ }, { rw vsub_eq_zero_iff_eq at h, rw ←h, exact ⟨p₂, hp₂, wbtw_self_right _ _ _⟩ }, { refine ⟨line_map x y (r₂ / (r₁ + r₂)), _, _⟩, { rw [line_map_apply, ←vsub_vadd x p₁, ←vsub_vadd y p₂, vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, ←vadd_assoc, vadd_eq_add], convert s.smul_vsub_vadd_mem (r₂ / (r₁ + r₂)) hp₂ hp₁ hp₁, rw [add_comm (y -ᵥ p₂), smul_sub, smul_add, add_sub_assoc, add_assoc, add_right_eq_self, div_eq_inv_mul, ←neg_vsub_eq_vsub_rev, smul_neg, ←smul_smul, ←h, smul_smul, ←neg_smul, ←sub_smul, ←div_eq_inv_mul, ←div_eq_inv_mul, ←neg_div, ←sub_div, sub_eq_add_neg, ←neg_add, neg_div, div_self (left.add_pos hr₁ hr₂).ne.symm, neg_one_smul, neg_add_self] }, { exact set.mem_image_of_mem _ ⟨div_nonneg hr₂.le (left.add_pos hr₁ hr₂).le, div_le_one_of_le (le_add_of_nonneg_left hr₁.le) (left.add_pos hr₁ hr₂).le⟩ } } end lemma s_opp_side.exists_sbtw {s : affine_subspace R P} {x y : P} (h : s.s_opp_side x y) : ∃ p ∈ s, sbtw R x p y := begin obtain ⟨p, hp, hw⟩ := w_opp_side_iff_exists_wbtw.1 h.w_opp_side, refine ⟨p, hp, hw, _, _⟩, { rintro rfl, exact h.2.1 hp }, { rintro rfl, exact h.2.2 hp }, end lemma _root_.sbtw.s_opp_side_of_not_mem_of_mem {s : affine_subspace R P} {x y z : P} (h : sbtw R x y z) (hx : x ∉ s) (hy : y ∈ s) : s.s_opp_side x z := begin refine ⟨h.wbtw.w_opp_side₁₃ hy, hx, λ hz, hx _⟩, rcases h with ⟨⟨t, ⟨ht0, ht1⟩, rfl⟩, hyx, hyz⟩, rw line_map_apply at hy, have ht : t ≠ 1, { rintro rfl, simpa [line_map_apply] using hyz }, have hy' := vsub_mem_direction hy hz, rw [vadd_vsub_assoc, ←neg_vsub_eq_vsub_rev z, ←neg_one_smul R (z -ᵥ x), ←add_smul, ←sub_eq_add_neg, s.direction.smul_mem_iff (sub_ne_zero_of_ne ht)] at hy', rwa vadd_mem_iff_mem_of_mem_direction (submodule.smul_mem _ _ hy') at hy end lemma s_same_side_smul_vsub_vadd_left {s : affine_subspace R P} {x p₁ p₂ : P} (hx : x ∉ s) (hp₁ : p₁ ∈ s) (hp₂ : p₂ ∈ s) {t : R} (ht : 0 < t) : s.s_same_side (t • (x -ᵥ p₁) +ᵥ p₂) x := begin refine ⟨w_same_side_smul_vsub_vadd_left x hp₁ hp₂ ht.le, λ h, hx _, hx⟩, rwa [vadd_mem_iff_mem_direction _ hp₂, s.direction.smul_mem_iff ht.ne.symm, vsub_right_mem_direction_iff_mem hp₁] at h end lemma s_same_side_smul_vsub_vadd_right {s : affine_subspace R P} {x p₁ p₂ : P} (hx : x ∉ s) (hp₁ : p₁ ∈ s) (hp₂ : p₂ ∈ s) {t : R} (ht : 0 < t) : s.s_same_side x (t • (x -ᵥ p₁) +ᵥ p₂) := (s_same_side_smul_vsub_vadd_left hx hp₁ hp₂ ht).symm lemma s_same_side_line_map_left {s : affine_subspace R P} {x y : P} (hx : x ∈ s) (hy : y ∉ s) {t : R} (ht : 0 < t) : s.s_same_side (line_map x y t) y := s_same_side_smul_vsub_vadd_left hy hx hx ht lemma s_same_side_line_map_right {s : affine_subspace R P} {x y : P} (hx : x ∈ s) (hy : y ∉ s) {t : R} (ht : 0 < t) : s.s_same_side y (line_map x y t) := (s_same_side_line_map_left hx hy ht).symm lemma s_opp_side_smul_vsub_vadd_left {s : affine_subspace R P} {x p₁ p₂ : P} (hx : x ∉ s) (hp₁ : p₁ ∈ s) (hp₂ : p₂ ∈ s) {t : R} (ht : t < 0) : s.s_opp_side (t • (x -ᵥ p₁) +ᵥ p₂) x := begin refine ⟨w_opp_side_smul_vsub_vadd_left x hp₁ hp₂ ht.le, λ h, hx _, hx⟩, rwa [vadd_mem_iff_mem_direction _ hp₂, s.direction.smul_mem_iff ht.ne, vsub_right_mem_direction_iff_mem hp₁] at h end lemma s_opp_side_smul_vsub_vadd_right {s : affine_subspace R P} {x p₁ p₂ : P} (hx : x ∉ s) (hp₁ : p₁ ∈ s) (hp₂ : p₂ ∈ s) {t : R} (ht : t < 0) : s.s_opp_side x (t • (x -ᵥ p₁) +ᵥ p₂) := (s_opp_side_smul_vsub_vadd_left hx hp₁ hp₂ ht).symm lemma s_opp_side_line_map_left {s : affine_subspace R P} {x y : P} (hx : x ∈ s) (hy : y ∉ s) {t : R} (ht : t < 0) : s.s_opp_side (line_map x y t) y := s_opp_side_smul_vsub_vadd_left hy hx hx ht lemma s_opp_side_line_map_right {s : affine_subspace R P} {x y : P} (hx : x ∈ s) (hy : y ∉ s) {t : R} (ht : t < 0) : s.s_opp_side y (line_map x y t) := (s_opp_side_line_map_left hx hy ht).symm lemma set_of_w_same_side_eq_image2 {s : affine_subspace R P} {x p : P} (hx : x ∉ s) (hp : p ∈ s) : {y | s.w_same_side x y} = set.image2 (λ (t : R) q, t • (x -ᵥ p) +ᵥ q) (set.Ici 0) s := begin ext y, simp_rw [set.mem_set_of, set.mem_image2, set.mem_Ici, mem_coe], split, { rw [w_same_side_iff_exists_left hp, or_iff_right hx], rintro ⟨p₂, hp₂, h | h | ⟨r₁, r₂, hr₁, hr₂, h⟩⟩, { rw vsub_eq_zero_iff_eq at h, exact false.elim (hx (h.symm ▸ hp)) }, { rw vsub_eq_zero_iff_eq at h, refine ⟨0, p₂, le_refl _, hp₂, _⟩, simp [h] }, { refine ⟨r₁ / r₂, p₂, (div_pos hr₁ hr₂).le, hp₂, _⟩, rw [div_eq_inv_mul, ←smul_smul, h, smul_smul, inv_mul_cancel hr₂.ne.symm, one_smul, vsub_vadd] } }, { rintro ⟨t, p', ht, hp', rfl⟩, exact w_same_side_smul_vsub_vadd_right x hp hp' ht } end lemma set_of_s_same_side_eq_image2 {s : affine_subspace R P} {x p : P} (hx : x ∉ s) (hp : p ∈ s) : {y | s.s_same_side x y} = set.image2 (λ (t : R) q, t • (x -ᵥ p) +ᵥ q) (set.Ioi 0) s := begin ext y, simp_rw [set.mem_set_of, set.mem_image2, set.mem_Ioi, mem_coe], split, { rw s_same_side_iff_exists_left hp, rintro ⟨-, hy, p₂, hp₂, h | h | ⟨r₁, r₂, hr₁, hr₂, h⟩⟩, { rw vsub_eq_zero_iff_eq at h, exact false.elim (hx (h.symm ▸ hp)) }, { rw vsub_eq_zero_iff_eq at h, exact false.elim (hy (h.symm ▸ hp₂)) }, { refine ⟨r₁ / r₂, p₂, div_pos hr₁ hr₂, hp₂, _⟩, rw [div_eq_inv_mul, ←smul_smul, h, smul_smul, inv_mul_cancel hr₂.ne.symm, one_smul, vsub_vadd] } }, { rintro ⟨t, p', ht, hp', rfl⟩, exact s_same_side_smul_vsub_vadd_right hx hp hp' ht } end lemma set_of_w_opp_side_eq_image2 {s : affine_subspace R P} {x p : P} (hx : x ∉ s) (hp : p ∈ s) : {y | s.w_opp_side x y} = set.image2 (λ (t : R) q, t • (x -ᵥ p) +ᵥ q) (set.Iic 0) s := begin ext y, simp_rw [set.mem_set_of, set.mem_image2, set.mem_Iic, mem_coe], split, { rw [w_opp_side_iff_exists_left hp, or_iff_right hx], rintro ⟨p₂, hp₂, h | h | ⟨r₁, r₂, hr₁, hr₂, h⟩⟩, { rw vsub_eq_zero_iff_eq at h, exact false.elim (hx (h.symm ▸ hp)) }, { rw vsub_eq_zero_iff_eq at h, refine ⟨0, p₂, le_refl _, hp₂, _⟩, simp [h] }, { refine ⟨-r₁ / r₂, p₂, (div_neg_of_neg_of_pos (left.neg_neg_iff.2 hr₁) hr₂).le, hp₂, _⟩, rw [div_eq_inv_mul, ←smul_smul, neg_smul, h, smul_neg, smul_smul, inv_mul_cancel hr₂.ne.symm, one_smul, neg_vsub_eq_vsub_rev, vsub_vadd] } }, { rintro ⟨t, p', ht, hp', rfl⟩, exact w_opp_side_smul_vsub_vadd_right x hp hp' ht } end lemma set_of_s_opp_side_eq_image2 {s : affine_subspace R P} {x p : P} (hx : x ∉ s) (hp : p ∈ s) : {y | s.s_opp_side x y} = set.image2 (λ (t : R) q, t • (x -ᵥ p) +ᵥ q) (set.Iio 0) s := begin ext y, simp_rw [set.mem_set_of, set.mem_image2, set.mem_Iio, mem_coe], split, { rw s_opp_side_iff_exists_left hp, rintro ⟨-, hy, p₂, hp₂, h | h | ⟨r₁, r₂, hr₁, hr₂, h⟩⟩, { rw vsub_eq_zero_iff_eq at h, exact false.elim (hx (h.symm ▸ hp)) }, { rw vsub_eq_zero_iff_eq at h, exact false.elim (hy (h ▸ hp₂)) }, { refine ⟨-r₁ / r₂, p₂, div_neg_of_neg_of_pos (left.neg_neg_iff.2 hr₁) hr₂, hp₂, _⟩, rw [div_eq_inv_mul, ←smul_smul, neg_smul, h, smul_neg, smul_smul, inv_mul_cancel hr₂.ne.symm, one_smul, neg_vsub_eq_vsub_rev, vsub_vadd] } }, { rintro ⟨t, p', ht, hp', rfl⟩, exact s_opp_side_smul_vsub_vadd_right hx hp hp' ht } end lemma w_opp_side_point_reflection {s : affine_subspace R P} {x : P} (y : P) (hx : x ∈ s) : s.w_opp_side y (point_reflection R x y) := (wbtw_point_reflection R _ _).w_opp_side₁₃ hx lemma s_opp_side_point_reflection {s : affine_subspace R P} {x y : P} (hx : x ∈ s) (hy : y ∉ s) : s.s_opp_side y (point_reflection R x y) := begin refine (sbtw_point_reflection_of_ne R (λ h, hy _)).s_opp_side_of_not_mem_of_mem hy hx, rwa ←h end end linear_ordered_field section normed variables [seminormed_add_comm_group V] [normed_space ℝ V] [pseudo_metric_space P] variables [normed_add_torsor V P] include V lemma is_connected_set_of_w_same_side {s : affine_subspace ℝ P} (x : P) (h : (s : set P).nonempty) : is_connected {y | s.w_same_side x y} := begin obtain ⟨p, hp⟩ := h, haveI : nonempty s := ⟨⟨p, hp⟩⟩, by_cases hx : x ∈ s, { convert is_connected_univ, { simp [w_same_side_of_left_mem, hx] }, { exact add_torsor.connected_space V P } }, { rw [set_of_w_same_side_eq_image2 hx hp, ←set.image_prod], refine (is_connected_Ici.prod (is_connected_iff_connected_space.2 _)).image _ ((continuous_fst.smul continuous_const).vadd continuous_snd).continuous_on, convert add_torsor.connected_space s.direction s } end lemma is_preconnected_set_of_w_same_side (s : affine_subspace ℝ P) (x : P) : is_preconnected {y | s.w_same_side x y} := begin rcases set.eq_empty_or_nonempty (s : set P) with h | h, { convert is_preconnected_empty, rw coe_eq_bot_iff at h, simp only [h, not_w_same_side_bot], refl }, { exact (is_connected_set_of_w_same_side x h).is_preconnected } end lemma is_connected_set_of_s_same_side {s : affine_subspace ℝ P} {x : P} (hx : x ∉ s) (h : (s : set P).nonempty) : is_connected {y | s.s_same_side x y} := begin obtain ⟨p, hp⟩ := h, haveI : nonempty s := ⟨⟨p, hp⟩⟩, rw [set_of_s_same_side_eq_image2 hx hp, ←set.image_prod], refine (is_connected_Ioi.prod (is_connected_iff_connected_space.2 _)).image _ ((continuous_fst.smul continuous_const).vadd continuous_snd).continuous_on, convert add_torsor.connected_space s.direction s end lemma is_preconnected_set_of_s_same_side (s : affine_subspace ℝ P) (x : P) : is_preconnected {y | s.s_same_side x y} := begin rcases set.eq_empty_or_nonempty (s : set P) with h | h, { convert is_preconnected_empty, rw coe_eq_bot_iff at h, simp only [h, not_s_same_side_bot], refl }, { by_cases hx : x ∈ s, { convert is_preconnected_empty, simp only [hx, s_same_side, not_true, false_and, and_false], refl }, { exact (is_connected_set_of_s_same_side hx h).is_preconnected } } end lemma is_connected_set_of_w_opp_side {s : affine_subspace ℝ P} (x : P) (h : (s : set P).nonempty) : is_connected {y | s.w_opp_side x y} := begin obtain ⟨p, hp⟩ := h, haveI : nonempty s := ⟨⟨p, hp⟩⟩, by_cases hx : x ∈ s, { convert is_connected_univ, { simp [w_opp_side_of_left_mem, hx] }, { exact add_torsor.connected_space V P } }, { rw [set_of_w_opp_side_eq_image2 hx hp, ←set.image_prod], refine (is_connected_Iic.prod (is_connected_iff_connected_space.2 _)).image _ ((continuous_fst.smul continuous_const).vadd continuous_snd).continuous_on, convert add_torsor.connected_space s.direction s } end lemma is_preconnected_set_of_w_opp_side (s : affine_subspace ℝ P) (x : P) : is_preconnected {y | s.w_opp_side x y} := begin rcases set.eq_empty_or_nonempty (s : set P) with h | h, { convert is_preconnected_empty, rw coe_eq_bot_iff at h, simp only [h, not_w_opp_side_bot], refl }, { exact (is_connected_set_of_w_opp_side x h).is_preconnected } end lemma is_connected_set_of_s_opp_side {s : affine_subspace ℝ P} {x : P} (hx : x ∉ s) (h : (s : set P).nonempty) : is_connected {y | s.s_opp_side x y} := begin obtain ⟨p, hp⟩ := h, haveI : nonempty s := ⟨⟨p, hp⟩⟩, rw [set_of_s_opp_side_eq_image2 hx hp, ←set.image_prod], refine (is_connected_Iio.prod (is_connected_iff_connected_space.2 _)).image _ ((continuous_fst.smul continuous_const).vadd continuous_snd).continuous_on, convert add_torsor.connected_space s.direction s end lemma is_preconnected_set_of_s_opp_side (s : affine_subspace ℝ P) (x : P) : is_preconnected {y | s.s_opp_side x y} := begin rcases set.eq_empty_or_nonempty (s : set P) with h | h, { convert is_preconnected_empty, rw coe_eq_bot_iff at h, simp only [h, not_s_opp_side_bot], refl }, { by_cases hx : x ∈ s, { convert is_preconnected_empty, simp only [hx, s_opp_side, not_true, false_and, and_false], refl }, { exact (is_connected_set_of_s_opp_side hx h).is_preconnected } } end end normed end affine_subspace
65dd1a5b075f914e456279ef8faf39dc1111a31a
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/order/modular_lattice.lean
a284aa81ce0b666bce7e94647a650d746d70e810
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,735
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 order.rel_iso import order.lattice_intervals import order.order_dual /-! # Modular Lattices This file defines Modular Lattices, a kind of lattice useful in algebra. For examples, look to the subobject lattices of abelian groups, submodules, and ideals, or consider any distributive lattice. ## Main Definitions - `is_modular_lattice` defines a modular lattice to be one such that `x ≤ z → (x ⊔ y) ⊓ z ≤ x ⊔ (y ⊓ z)` - `inf_Icc_order_iso_Icc_sup` gives an order isomorphism between the intervals `[a ⊓ b, a]` and `[b, a ⊔ b]`. This corresponds to the diamond (or second) isomorphism theorems of algebra. ## Main Results - `is_modular_lattice_iff_sup_inf_sup_assoc`: Modularity is equivalent to the `sup_inf_sup_assoc`: `(x ⊓ z) ⊔ (y ⊓ z) = ((x ⊓ z) ⊔ y) ⊓ z` - `distrib_lattice.is_modular_lattice`: Distributive lattices are modular. ## To do - Relate atoms and coatoms in modular lattices -/ variable {α : Type*} /-- A modular lattice is one with a limited associativity between `⊓` and `⊔`. -/ class is_modular_lattice α [lattice α] : Prop := (sup_inf_le_assoc_of_le : ∀ {x : α} (y : α) {z : α}, x ≤ z → (x ⊔ y) ⊓ z ≤ x ⊔ (y ⊓ z)) section is_modular_lattice variables [lattice α] [is_modular_lattice α ] theorem sup_inf_assoc_of_le {x : α} (y : α) {z : α} (h : x ≤ z) : (x ⊔ y) ⊓ z = x ⊔ (y ⊓ z) := le_antisymm (is_modular_lattice.sup_inf_le_assoc_of_le y h) (le_inf (sup_le_sup_left inf_le_left _) (sup_le h inf_le_right)) theorem is_modular_lattice.sup_inf_sup_assoc {x y z : α} : (x ⊓ z) ⊔ (y ⊓ z) = ((x ⊓ z) ⊔ y) ⊓ z := (sup_inf_assoc_of_le y inf_le_right).symm lemma inf_sup_assoc_of_le {x : α} (y : α) {z : α} (h : z ≤ x) : (x ⊓ y) ⊔ z = x ⊓ (y ⊔ z) := by rw [inf_comm, sup_comm, ← sup_inf_assoc_of_le y h, inf_comm, sup_comm] instance : is_modular_lattice (order_dual α) := ⟨λ x y z xz, le_of_eq (by { rw [inf_comm, sup_comm, eq_comm, inf_comm, sup_comm], convert sup_inf_assoc_of_le (order_dual.of_dual y) (order_dual.dual_le.2 xz) })⟩ /-- The diamond isomorphism between the intervals `[a ⊓ b, a]` and `[b, a ⊔ b]` -/ def inf_Icc_order_iso_Icc_sup (a b : α) : set.Icc (a ⊓ b) a ≃o set.Icc b (a ⊔ b) := { to_fun := λ x, ⟨x ⊔ b, ⟨le_sup_right, sup_le_sup_right x.prop.2 b⟩⟩, inv_fun := λ x, ⟨a ⊓ x, ⟨inf_le_inf_left a x.prop.1, inf_le_left⟩⟩, left_inv := λ x, subtype.ext (by { change a ⊓ (↑x ⊔ b) = ↑x, rw [sup_comm, ← inf_sup_assoc_of_le _ x.prop.2, sup_eq_right.2 x.prop.1] }), right_inv := λ x, subtype.ext (by { change a ⊓ ↑x ⊔ b = ↑x, rw [inf_comm, inf_sup_assoc_of_le _ x.prop.1, inf_eq_left.2 x.prop.2] }), map_rel_iff' := λ x y, begin simp only [subtype.mk_le_mk, equiv.coe_fn_mk, and_true, le_sup_right], rw [← subtype.coe_le_coe], refine ⟨λ h, _, λ h, sup_le_sup_right h _⟩, rw [← sup_eq_right.2 x.prop.1, inf_sup_assoc_of_le _ x.prop.2, sup_comm, ← sup_eq_right.2 y.prop.1, inf_sup_assoc_of_le _ y.prop.2, @sup_comm _ _ b], exact inf_le_inf_left _ h end } end is_modular_lattice namespace is_compl variables [bounded_lattice α] [is_modular_lattice α] /-- The diamond isomorphism between the intervals `set.Iic a` and `set.Ici b`. -/ def Iic_order_iso_Ici {a b : α} (h : is_compl a b) : set.Iic a ≃o set.Ici b := (order_iso.set_congr (set.Iic a) (set.Icc (a ⊓ b) a) (h.inf_eq_bot.symm ▸ set.Icc_bot.symm)).trans $ (inf_Icc_order_iso_Icc_sup a b).trans (order_iso.set_congr (set.Icc b (a ⊔ b)) (set.Ici b) (h.sup_eq_top.symm ▸ set.Icc_top)) end is_compl theorem is_modular_lattice_iff_sup_inf_sup_assoc [lattice α] : is_modular_lattice α ↔ ∀ (x y z : α), (x ⊓ z) ⊔ (y ⊓ z) = ((x ⊓ z) ⊔ y) ⊓ z := ⟨λ h, @is_modular_lattice.sup_inf_sup_assoc _ _ h, λ h, ⟨λ x y z xz, by rw [← inf_eq_left.2 xz, h]⟩⟩ namespace distrib_lattice @[priority 100] instance [distrib_lattice α] : is_modular_lattice α := ⟨λ x y z xz, by rw [inf_sup_right, inf_eq_left.2 xz]⟩ end distrib_lattice namespace is_modular_lattice variables [bounded_lattice α] [is_modular_lattice α] {a : α} instance is_modular_lattice_Iic : is_modular_lattice (set.Iic a) := ⟨λ x y z xz, (sup_inf_le_assoc_of_le (y : α) xz : (↑x ⊔ ↑y) ⊓ ↑z ≤ ↑x ⊔ ↑y ⊓ ↑z)⟩ instance is_modular_lattice_Ici : is_modular_lattice (set.Ici a) := ⟨λ x y z xz, (sup_inf_le_assoc_of_le (y : α) xz : (↑x ⊔ ↑y) ⊓ ↑z ≤ ↑x ⊔ ↑y ⊓ ↑z)⟩ end is_modular_lattice
a25da3911da9fb20ac68766214d8879e71ea643b
63abd62053d479eae5abf4951554e1064a4c45b4
/src/algebra/module/ordered.lean
2732b6fc12a198d5b2556239f2ac4b7ce6b66a90
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
8,079
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 algebra.module.pi import algebra.module.prod import algebra.ordered_field /-! # 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. -/ @[protect_proj, ancestor semimodule] class ordered_semimodule (R M : Type*) [ordered_semiring R] [ordered_add_comm_monoid M] [semimodule R M] : Prop := (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) section ordered_semimodule variables {R M : Type*} [ordered_semiring R] [ordered_add_comm_monoid M] [semimodule R M] [ordered_semimodule R M] {a b : M} {c : R} lemma smul_lt_smul_of_pos : a < b → 0 < c → c • a < c • b := ordered_semimodule.smul_lt_smul_of_pos lemma smul_le_smul_of_nonneg (h₁ : a ≤ b) (h₂ : 0 ≤ c) : c • a ≤ c • b := begin by_cases H₁ : c = 0, { simp [H₁, zero_smul] }, { by_cases H₂ : a = b, { rw H₂ }, { exact le_of_lt (smul_lt_smul_of_pos (lt_of_le_of_ne h₁ H₂) (lt_of_le_of_ne h₂ (ne.symm H₁))), } } end lemma eq_of_smul_eq_smul_of_pos_of_le (h₁ : c • a = c • b) (hc : 0 < c) (hle : a ≤ b) : a = b := hle.lt_or_eq.resolve_left $ λ hlt, (smul_lt_smul_of_pos hlt hc).ne h₁ lemma lt_of_smul_lt_smul_of_nonneg (h : c • a < c • b) (hc : 0 ≤ c) : a < b := hc.eq_or_lt.elim (λ hc, false.elim $ lt_irrefl (0:M) $ by rwa [← hc, zero_smul, zero_smul] at h) (ordered_semimodule.lt_of_smul_lt_smul_of_pos h) lemma smul_lt_smul_iff_of_pos (hc : 0 < c) : c • a < c • b ↔ a < b := ⟨λ h, lt_of_smul_lt_smul_of_nonneg h hc.le, λ h, smul_lt_smul_of_pos h hc⟩ lemma smul_pos_iff_of_pos (hc : 0 < c) : 0 < c • a ↔ 0 < a := calc 0 < c • a ↔ c • 0 < c • a : by rw smul_zero ... ↔ 0 < a : smul_lt_smul_iff_of_pos hc end ordered_semimodule /-- 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. -/ lemma ordered_semimodule.mk'' {R M : Type*} [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 := begin have hlt' : ∀ ⦃a b : M⦄ ⦃c : R⦄, a < b → 0 < c → c • a < c • b, { refine λ a b c hab hc, (hlt hab hc).lt_of_ne _, rw [ne.def, (hR hc.ne').smul_left_cancel], exact hab.ne }, refine { smul_lt_smul_of_pos := hlt', .. }, intros a b c h hc, rcases (hR hc.ne') with ⟨c, rfl⟩, rw [← c.inv_smul_smul a, ← c.inv_smul_smul b], refine hlt' h (pos_of_mul_pos_left _ hc.le), simp only [c.mul_inv, zero_lt_one] end /-- If `R` is a linear ordered field, then it suffices to verify only the first axiom of `ordered_semimodule`. -/ lemma ordered_semimodule.mk' {k M : Type*} [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'' (λ c hc, is_unit.mk0 _ hc) hlt instance linear_ordered_semiring.to_ordered_semimodule {R : Type*} [linear_ordered_semiring R] : ordered_semimodule R R := { smul_lt_smul_of_pos := ordered_semiring.mul_lt_mul_of_pos_left, lt_of_smul_lt_smul_of_pos := λ _ _ _ h hc, lt_of_mul_lt_mul_left h hc.le } section field variables {k M N : Type*} [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] {a b : M} {c : k} lemma smul_le_smul_iff_of_pos (hc : 0 < c) : c • a ≤ c • b ↔ a ≤ b := ⟨λ h, inv_smul_smul' hc.ne' a ▸ inv_smul_smul' hc.ne' b ▸ smul_le_smul_of_nonneg h (inv_nonneg.2 hc.le), λ h, smul_le_smul_of_nonneg h hc.le⟩ lemma smul_le_smul_iff_of_neg (hc : c < 0) : c • a ≤ c • b ↔ b ≤ a := begin rw [← neg_neg c, neg_smul, neg_smul (-c), neg_le_neg_iff, smul_le_smul_iff_of_pos (neg_pos.2 hc)], apply_instance, end lemma smul_lt_iff_of_pos (hc : 0 < c) : c • a < b ↔ a < c⁻¹ • b := calc c • a < b ↔ c • a < c • c⁻¹ • b : by rw [smul_inv_smul' hc.ne'] ... ↔ a < c⁻¹ • b : smul_lt_smul_iff_of_pos hc lemma smul_le_iff_of_pos (hc : 0 < c) : c • a ≤ b ↔ a ≤ c⁻¹ • b := calc c • a ≤ b ↔ c • a ≤ c • c⁻¹ • b : by rw [smul_inv_smul' hc.ne'] ... ↔ a ≤ c⁻¹ • b : smul_le_smul_iff_of_pos hc lemma le_smul_iff_of_pos (hc : 0 < c) : a ≤ c • b ↔ c⁻¹ • a ≤ b := calc a ≤ c • b ↔ c • c⁻¹ • a ≤ c • b : by rw [smul_inv_smul' hc.ne'] ... ↔ c⁻¹ • a ≤ b : smul_le_smul_iff_of_pos hc instance prod.ordered_semimodule : ordered_semimodule k (M × N) := ordered_semimodule.mk' $ λ v u c h hc, ⟨smul_le_smul_of_nonneg h.1.1 hc.le, smul_le_smul_of_nonneg h.1.2 hc.le⟩ instance pi.ordered_semimodule {ι : Type*} {M : ι → Type*} [Π i, ordered_add_comm_group (M i)] [Π i, semimodule k (M i)] [∀ i, ordered_semimodule k (M i)] : ordered_semimodule k (Π i : ι, M i) := begin refine (ordered_semimodule.mk' $ λ v u c h hc i, _), change c • v i ≤ c • u i, exact smul_le_smul_of_nonneg (h.le i) hc.le, end -- Sometimes Lean fails to apply the dependent version to non-dependent functions, -- so we define another instance instance pi.ordered_semimodule' {ι : Type*} {M : Type*} [ordered_add_comm_group M] [semimodule k M] [ordered_semimodule k M] : ordered_semimodule k (ι → M) := pi.ordered_semimodule end field section order_dual variables {R M : Type*} instance [semiring R] [ordered_add_comm_monoid M] [semimodule R M] : has_scalar R (order_dual M) := { smul := @has_scalar.smul R M _ } instance [semiring R] [ordered_add_comm_monoid M] [semimodule R M] : mul_action R (order_dual M) := { one_smul := @mul_action.one_smul R M _ _, mul_smul := @mul_action.mul_smul R M _ _ } instance [semiring R] [ordered_add_comm_monoid M] [semimodule R M] : distrib_mul_action R (order_dual M) := { smul_add := @distrib_mul_action.smul_add R M _ _ _, smul_zero := @distrib_mul_action.smul_zero R M _ _ _ } instance [semiring R] [ordered_add_comm_monoid M] [semimodule R M] : semimodule R (order_dual M) := { add_smul := @semimodule.add_smul R M _ _ _, zero_smul := @semimodule.zero_smul R M _ _ _ } instance [ordered_semiring R] [ordered_add_comm_monoid M] [semimodule R M] [ordered_semimodule R M] : ordered_semimodule R (order_dual M) := { smul_lt_smul_of_pos := λ a b, @ordered_semimodule.smul_lt_smul_of_pos R M _ _ _ _ b a, lt_of_smul_lt_smul_of_pos := λ a b, @ordered_semimodule.lt_of_smul_lt_smul_of_pos R M _ _ _ _ b a } end order_dual
edecbd1ce0db2a35bd5b91934a9a9a537ab016d8
957a80ea22c5abb4f4670b250d55534d9db99108
/library/init/algebra/ordered_field.lean
7b6c69befffe9cb1c8f5a0fd444567bba22c0428
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
19,504
lean
/- Copyright (c) 2014 Robert Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Lewis, Leonardo de Moura -/ prelude import init.algebra.ordered_ring init.algebra.field set_option old_structure_cmd true universe u class linear_ordered_field (α : Type u) extends linear_ordered_ring α, field α section linear_ordered_field variables {α : Type u} [linear_ordered_field α] lemma mul_zero_lt_mul_inv_of_pos {a : α} (h : 0 < a) : a * 0 < a * (1 / a) := calc a * 0 = 0 : by rw mul_zero ... < 1 : zero_lt_one ... = a * a⁻¹ : eq.symm (mul_inv_cancel (ne.symm (ne_of_lt h))) ... = a * (1 / a) : by rw inv_eq_one_div lemma mul_zero_lt_mul_inv_of_neg {a : α} (h : a < 0) : a * 0 < a * (1 / a) := calc a * 0 = 0 : by rw mul_zero ... < 1 : zero_lt_one ... = a * a⁻¹ : eq.symm (mul_inv_cancel (ne_of_lt h)) ... = a * (1 / a) : by rw inv_eq_one_div lemma one_div_pos_of_pos {a : α} (h : 0 < a) : 0 < 1 / a := lt_of_mul_lt_mul_left (mul_zero_lt_mul_inv_of_pos h) (le_of_lt h) lemma one_div_neg_of_neg {a : α} (h : a < 0) : 1 / a < 0 := gt_of_mul_lt_mul_neg_left (mul_zero_lt_mul_inv_of_neg h) (le_of_lt h) lemma le_mul_of_ge_one_right {a b : α} (hb : b ≥ 0) (h : a ≥ 1) : b ≤ b * a := suffices b * 1 ≤ b * a, by rwa mul_one at this, mul_le_mul_of_nonneg_left h hb lemma le_mul_of_ge_one_left {a b : α} (hb : b ≥ 0) (h : a ≥ 1) : b ≤ a * b := by rw mul_comm; exact le_mul_of_ge_one_right hb h lemma lt_mul_of_gt_one_right {a b : α} (hb : b > 0) (h : a > 1) : b < b * a := suffices b * 1 < b * a, by rwa mul_one at this, mul_lt_mul_of_pos_left h hb lemma one_le_div_of_le (a : α) {b : α} (hb : b > 0) (h : b ≤ a) : 1 ≤ a / b := have hb' : b ≠ 0, from ne.symm (ne_of_lt hb), have hbinv : 1 / b > 0, from one_div_pos_of_pos hb, calc 1 = b * (1 / b) : eq.symm (mul_one_div_cancel hb') ... ≤ a * (1 / b) : mul_le_mul_of_nonneg_right h (le_of_lt hbinv) ... = a / b : eq.symm $ div_eq_mul_one_div a b lemma le_of_one_le_div (a : α) {b : α} (hb : b > 0) (h : 1 ≤ a / b) : b ≤ a := have hb' : b ≠ 0, from ne.symm (ne_of_lt hb), calc b ≤ b * (a / b) : le_mul_of_ge_one_right (le_of_lt hb) h ... = a : by rw [mul_div_cancel' _ hb'] lemma one_lt_div_of_lt (a : α) {b : α} (hb : b > 0) (h : b < a) : 1 < a / b := have hb' : b ≠ 0, from ne.symm (ne_of_lt hb), have hbinv : 1 / b > 0, from one_div_pos_of_pos hb, calc 1 = b * (1 / b) : eq.symm (mul_one_div_cancel hb') ... < a * (1 / b) : mul_lt_mul_of_pos_right h hbinv ... = a / b : eq.symm $ div_eq_mul_one_div a b lemma lt_of_one_lt_div (a : α) {b : α} (hb : b > 0) (h : 1 < a / b) : b < a := have hb' : b ≠ 0, from ne.symm (ne_of_lt hb), calc b < b * (a / b) : lt_mul_of_gt_one_right hb h ... = a : by rw [mul_div_cancel' _ hb'] -- the following lemmas amount to four iffs, for <, ≤, ≥, >. lemma mul_le_of_le_div {a b c : α} (hc : 0 < c) (h : a ≤ b / c) : a * c ≤ b := div_mul_cancel b (ne.symm (ne_of_lt hc)) ▸ mul_le_mul_of_nonneg_right h (le_of_lt hc) lemma le_div_of_mul_le {a b c : α} (hc : 0 < c) (h : a * c ≤ b) : a ≤ b / c := calc a = a * c * (1 / c) : mul_mul_div a (ne.symm (ne_of_lt hc)) ... ≤ b * (1 / c) : mul_le_mul_of_nonneg_right h (le_of_lt (one_div_pos_of_pos hc)) ... = b / c : eq.symm $ div_eq_mul_one_div b c lemma mul_lt_of_lt_div {a b c : α} (hc : 0 < c) (h : a < b / c) : a * c < b := div_mul_cancel b (ne.symm (ne_of_lt hc)) ▸ mul_lt_mul_of_pos_right h hc lemma lt_div_of_mul_lt {a b c : α} (hc : 0 < c) (h : a * c < b) : a < b / c := calc a = a * c * (1 / c) : mul_mul_div a (ne.symm (ne_of_lt hc)) ... < b * (1 / c) : mul_lt_mul_of_pos_right h (one_div_pos_of_pos hc) ... = b / c : eq.symm $ div_eq_mul_one_div b c lemma mul_le_of_div_le_of_neg {a b c : α} (hc : c < 0) (h : b / c ≤ a) : a * c ≤ b := div_mul_cancel b (ne_of_lt hc) ▸ mul_le_mul_of_nonpos_right h (le_of_lt hc) lemma div_le_of_mul_le_of_neg {a b c : α} (hc : c < 0) (h : a * c ≤ b) : b / c ≤ a := calc a = a * c * (1 / c) : mul_mul_div a (ne_of_lt hc) ... ≥ b * (1 / c) : mul_le_mul_of_nonpos_right h (le_of_lt (one_div_neg_of_neg hc)) ... = b / c : eq.symm $ div_eq_mul_one_div b c lemma mul_lt_of_gt_div_of_neg {a b c : α} (hc : c < 0) (h : a > b / c) : a * c < b := div_mul_cancel b (ne_of_lt hc) ▸ mul_lt_mul_of_neg_right h hc lemma div_lt_of_mul_lt_of_pos {a b c : α} (hc : c > 0) (h : b < a * c) : b / c < a := calc a = a * c * (1 / c) : mul_mul_div a (ne_of_gt hc) ... > b * (1 / c) : mul_lt_mul_of_pos_right h (one_div_pos_of_pos hc) ... = b / c : eq.symm $ div_eq_mul_one_div b c lemma div_lt_of_mul_gt_of_neg {a b c : α} (hc : c < 0) (h : a * c < b) : b / c < a := calc a = a * c * (1 / c) : mul_mul_div a (ne_of_lt hc) ... > b * (1 / c) : mul_lt_mul_of_neg_right h (one_div_neg_of_neg hc) ... = b / c : eq.symm $ div_eq_mul_one_div b c lemma div_le_of_le_mul {a b c : α} (hb : b > 0) (h : a ≤ b * c) : a / b ≤ c := calc a / b = a * (1 / b) : div_eq_mul_one_div a b ... ≤ (b * c) * (1 / b) : mul_le_mul_of_nonneg_right h (le_of_lt (one_div_pos_of_pos hb)) ... = (b * c) / b : eq.symm $ div_eq_mul_one_div (b * c) b ... = c : by rw [mul_div_cancel_left _ (ne.symm (ne_of_lt hb))] lemma le_mul_of_div_le {a b c : α} (hc : c > 0) (h : a / c ≤ b) : a ≤ b * c := calc a = a / c * c : by rw (div_mul_cancel _ (ne.symm (ne_of_lt hc))) ... ≤ b * c : mul_le_mul_of_nonneg_right h (le_of_lt hc) -- following these in the isabelle file, there are 8 biconditionals for the above with - signs -- skipping for now lemma mul_sub_mul_div_mul_neg {a b c d : α} (hc : c ≠ 0) (hd : d ≠ 0) (h : a / c < b / d) : (a * d - b * c) / (c * d) < 0 := have h1 : a / c - b / d < 0, from calc a / c - b / d < b / d - b / d : sub_lt_sub_right h _ ... = 0 : by rw sub_self, calc 0 > a / c - b / d : h1 ... = (a * d - c * b) / (c * d) : div_sub_div _ _ hc hd ... = (a * d - b * c) / (c * d) : by rw (mul_comm b c) lemma mul_sub_mul_div_mul_nonpos {a b c d : α} (hc : c ≠ 0) (hd : d ≠ 0) (h : a / c ≤ b / d) : (a * d - b * c) / (c * d) ≤ 0 := have h1 : a / c - b / d ≤ 0, from calc a / c - b / d ≤ b / d - b / d : sub_le_sub_right h _ ... = 0 : by rw sub_self, calc 0 ≥ a / c - b / d : h1 ... = (a * d - c * b) / (c * d) : div_sub_div _ _ hc hd ... = (a * d - b * c) / (c * d) : by rw (mul_comm b c) lemma div_lt_div_of_mul_sub_mul_div_neg {a b c d : α} (hc : c ≠ 0) (hd : d ≠ 0) (h : (a * d - b * c) / (c * d) < 0) : a / c < b / d := have (a * d - c * b) / (c * d) < 0, by rwa [mul_comm c b], have a / c - b / d < 0, by rwa [div_sub_div _ _ hc hd], have a / c - b / d + b / d < 0 + b / d, from add_lt_add_right this _, by rwa [zero_add, sub_eq_add_neg, neg_add_cancel_right] at this lemma div_le_div_of_mul_sub_mul_div_nonpos {a b c d : α} (hc : c ≠ 0) (hd : d ≠ 0) (h : (a * d - b * c) / (c * d) ≤ 0) : a / c ≤ b / d := have (a * d - c * b) / (c * d) ≤ 0, by rwa [mul_comm c b], have a / c - b / d ≤ 0, by rwa [div_sub_div _ _ hc hd], have a / c - b / d + b / d ≤ 0 + b / d, from add_le_add_right this _, by rwa [zero_add, sub_eq_add_neg, neg_add_cancel_right] at this lemma div_pos_of_pos_of_pos {a b : α} : 0 < a → 0 < b → 0 < a / b := begin intros, rw div_eq_mul_one_div, apply mul_pos, assumption, apply one_div_pos_of_pos, assumption end lemma div_nonneg_of_nonneg_of_pos {a b : α} : 0 ≤ a → 0 < b → 0 ≤ a / b := begin intros, rw div_eq_mul_one_div, apply mul_nonneg, assumption, apply le_of_lt, apply one_div_pos_of_pos, assumption end lemma div_neg_of_neg_of_pos {a b : α} : a < 0 → 0 < b → a / b < 0 := begin intros, rw div_eq_mul_one_div, apply mul_neg_of_neg_of_pos, assumption, apply one_div_pos_of_pos, assumption end lemma div_nonpos_of_nonpos_of_pos {a b : α} : a ≤ 0 → 0 < b → a / b ≤ 0 := begin intros, rw div_eq_mul_one_div, apply mul_nonpos_of_nonpos_of_nonneg, assumption, apply le_of_lt, apply one_div_pos_of_pos, assumption end lemma div_neg_of_pos_of_neg {a b : α} : 0 < a → b < 0 → a / b < 0 := begin intros, rw div_eq_mul_one_div, apply mul_neg_of_pos_of_neg, assumption, apply one_div_neg_of_neg, assumption end lemma div_nonpos_of_nonneg_of_neg {a b : α} : 0 ≤ a → b < 0 → a / b ≤ 0 := begin intros, rw div_eq_mul_one_div, apply mul_nonpos_of_nonneg_of_nonpos, assumption, apply le_of_lt, apply one_div_neg_of_neg, assumption end lemma div_pos_of_neg_of_neg {a b : α} : a < 0 → b < 0 → 0 < a / b := begin intros, rw div_eq_mul_one_div, apply mul_pos_of_neg_of_neg, assumption, apply one_div_neg_of_neg, assumption end lemma div_nonneg_of_nonpos_of_neg {a b : α} : a ≤ 0 → b < 0 → 0 ≤ a / b := begin intros, rw div_eq_mul_one_div, apply mul_nonneg_of_nonpos_of_nonpos, assumption, apply le_of_lt, apply one_div_neg_of_neg, assumption end lemma div_lt_div_of_lt_of_pos {a b c : α} (h : a < b) (hc : 0 < c) : a / c < b / c := begin intros, rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_lt_mul_of_pos_right h (one_div_pos_of_pos hc) end lemma div_le_div_of_le_of_pos {a b c : α} (h : a ≤ b) (hc : 0 < c) : a / c ≤ b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_le_mul_of_nonneg_right h (le_of_lt (one_div_pos_of_pos hc)) end lemma div_lt_div_of_lt_of_neg {a b c : α} (h : b < a) (hc : c < 0) : a / c < b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_lt_mul_of_neg_right h (one_div_neg_of_neg hc) end lemma div_le_div_of_le_of_neg {a b c : α} (h : b ≤ a) (hc : c < 0) : a / c ≤ b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_le_mul_of_nonpos_right h (le_of_lt (one_div_neg_of_neg hc)) end lemma two_pos : (2:α) > 0 := begin unfold bit0, exact add_pos zero_lt_one zero_lt_one end lemma two_ne_zero : (2:α) ≠ 0 := ne.symm (ne_of_lt two_pos) lemma add_halves (a : α) : a / 2 + a / 2 = a := calc a / 2 + a / 2 = (a + a) / 2 : by rw div_add_div_same ... = (a * 1 + a * 1) / 2 : by rw mul_one ... = (a * (1 + 1)) / 2 : by rw left_distrib ... = (a * 2) / 2 : by rw one_add_one_eq_two ... = a : by rw [@mul_div_cancel α _ _ _ two_ne_zero] lemma sub_self_div_two (a : α) : a - a / 2 = a / 2 := suffices a / 2 + a / 2 - a / 2 = a / 2, by rwa add_halves at this, by rw [add_sub_cancel] lemma add_midpoint {a b : α} (h : a < b) : a + (b - a) / 2 < b := begin rw [← div_sub_div_same, sub_eq_add_neg, add_comm (b/2), ← add_assoc, ← sub_eq_add_neg], apply add_lt_of_lt_sub_right, rw [sub_self_div_two, sub_self_div_two], apply div_lt_div_of_lt_of_pos h two_pos end lemma div_two_sub_self (a : α) : a / 2 - a = - (a / 2) := suffices a / 2 - (a / 2 + a / 2) = - (a / 2), by rwa add_halves at this, by rw [sub_add_eq_sub_sub, sub_self, zero_sub] lemma add_self_div_two (a : α) : (a + a) / 2 = a := eq.symm (iff.mpr (eq_div_iff_mul_eq _ _ (ne_of_gt (add_pos (@zero_lt_one α _) zero_lt_one))) (begin unfold bit0, rw [left_distrib, mul_one] end)) lemma two_gt_one : (2:α) > 1 := calc (2:α) = 1+1 : one_add_one_eq_two ... > 1+0 : add_lt_add_left zero_lt_one _ ... = 1 : add_zero 1 lemma two_ge_one : (2:α) ≥ 1 := le_of_lt two_gt_one lemma four_pos : (4:α) > 0 := add_pos two_pos two_pos lemma mul_le_mul_of_mul_div_le {a b c d : α} (h : a * (b / c) ≤ d) (hc : c > 0) : b * a ≤ d * c := begin rw [← mul_div_assoc] at h, rw [mul_comm b], apply le_mul_of_div_le hc h end lemma div_two_lt_of_pos {a : α} (h : a > 0) : a / 2 < a := suffices a / (1 + 1) < a, begin unfold bit0, assumption end, have ha : a / 2 > 0, from div_pos_of_pos_of_pos h (add_pos zero_lt_one zero_lt_one), calc a / 2 < a / 2 + a / 2 : lt_add_of_pos_left _ ha ... = a : add_halves a lemma div_mul_le_div_mul_of_div_le_div_pos {a b c d e : α} (hb : b ≠ 0) (hd : d ≠ 0) (h : a / b ≤ c / d) (he : e > 0) : a / (b * e) ≤ c / (d * e) := begin have h₁ := field.div_mul_eq_div_mul_one_div a hb (ne_of_gt he), have h₂ := field.div_mul_eq_div_mul_one_div c hd (ne_of_gt he), rw [h₁, h₂], apply mul_le_mul_of_nonneg_right h, apply le_of_lt, apply one_div_pos_of_pos he end lemma exists_add_lt_and_pos_of_lt {a b : α} (h : b < a) : ∃ c : α, b + c < a ∧ c > 0 := begin apply exists.intro ((a - b) / (1 + 1)), split, {have h2 : a + a > (b + b) + (a - b), calc a + a > b + a : add_lt_add_right h _ ... = b + a + b - b : by rw add_sub_cancel ... = b + b + a - b : by simp ... = (b + b) + (a - b) : by rw add_sub, have h3 : (a + a) / 2 > ((b + b) + (a - b)) / 2, exact div_lt_div_of_lt_of_pos h2 two_pos, rw [one_add_one_eq_two, sub_eq_add_neg], rw [add_self_div_two, ← div_add_div_same, add_self_div_two, sub_eq_add_neg] at h3, exact h3}, exact div_pos_of_pos_of_pos (sub_pos_of_lt h) two_pos end lemma ge_of_forall_ge_sub {a b : α} (h : ∀ ε : α, ε > 0 → a ≥ b - ε) : a ≥ b := begin apply le_of_not_gt, intro hb, cases exists_add_lt_and_pos_of_lt hb with c hc, have hc' := h c (and.right hc), apply (not_le_of_gt (and.left hc)) (le_add_of_sub_right_le hc') end end linear_ordered_field class discrete_linear_ordered_field (α : Type u) extends linear_ordered_field α, decidable_linear_ordered_comm_ring α := (inv_zero : inv zero = zero) section discrete_linear_ordered_field variables {α : Type u} instance discrete_linear_ordered_field.to_discrete_field [s : discrete_linear_ordered_field α] : discrete_field α := {s with has_decidable_eq := @decidable_linear_ordered_comm_ring.decidable_eq α (@discrete_linear_ordered_field.to_decidable_linear_ordered_comm_ring α s) } variables [discrete_linear_ordered_field α] lemma pos_of_one_div_pos {a : α} (h : 0 < 1 / a) : 0 < a := have h1 : 0 < 1 / (1 / a), from one_div_pos_of_pos h, have h2 : 1 / a ≠ 0, from (assume h3 : 1 / a = 0, have h4 : 1 / (1 / a) = 0, from eq.symm h3 ▸ div_zero 1, absurd h4 (ne.symm (ne_of_lt h1))), (division_ring.one_div_one_div (ne_zero_of_one_div_ne_zero h2)) ▸ h1 lemma neg_of_one_div_neg {a : α} (h : 1 / a < 0) : a < 0 := have h1 : 0 < - (1 / a), from neg_pos_of_neg h, have ha : a ≠ 0, from ne_zero_of_one_div_ne_zero (ne_of_lt h), have h2 : 0 < 1 / (-a), from eq.symm (division_ring.one_div_neg_eq_neg_one_div ha) ▸ h1, have h3 : 0 < -a, from pos_of_one_div_pos h2, neg_of_neg_pos h3 lemma le_of_one_div_le_one_div {a b : α} (h : 0 < a) (hl : 1 / a ≤ 1 / b) : b ≤ a := have hb : 0 < b, from pos_of_one_div_pos (calc 0 < 1 / a : one_div_pos_of_pos h ... ≤ 1 / b : hl), have h' : 1 ≤ a / b, from (calc 1 = a / a : eq.symm (div_self (ne.symm (ne_of_lt h))) ... = a * (1 / a) : div_eq_mul_one_div a a ... ≤ a * (1 / b) : mul_le_mul_of_nonneg_left hl (le_of_lt h) ... = a / b : eq.symm $ div_eq_mul_one_div a b ), le_of_one_le_div _ hb h' lemma le_of_one_div_le_one_div_of_neg {a b : α} (h : b < 0) (hl : 1 / a ≤ 1 / b) : b ≤ a := have ha : a ≠ 0, from ne_of_lt (neg_of_one_div_neg (calc 1 / a ≤ 1 / b : hl ... < 0 : one_div_neg_of_neg h)), have h' : -b > 0, from neg_pos_of_neg h, have - (1 / b) ≤ - (1 / a), from neg_le_neg hl, have 1 / - b ≤ 1 / - a, from calc 1 / -b = - (1 / b) : by rw [division_ring.one_div_neg_eq_neg_one_div (ne_of_lt h)] ... ≤ - (1 / a) : this ... = 1 / -a : by rw [division_ring.one_div_neg_eq_neg_one_div ha], le_of_neg_le_neg (le_of_one_div_le_one_div h' this) lemma lt_of_one_div_lt_one_div {a b : α} (h : 0 < a) (hl : 1 / a < 1 / b) : b < a := have hb : 0 < b, from pos_of_one_div_pos (calc 0 < 1 / a : one_div_pos_of_pos h ... < 1 / b : hl), have h : 1 < a / b, from (calc 1 = a / a : eq.symm (div_self (ne.symm (ne_of_lt h))) ... = a * (1 / a) : div_eq_mul_one_div a a ... < a * (1 / b) : mul_lt_mul_of_pos_left hl h ... = a / b : eq.symm $ div_eq_mul_one_div a b), lt_of_one_lt_div _ hb h lemma lt_of_one_div_lt_one_div_of_neg {a b : α} (h : b < 0) (hl : 1 / a < 1 / b) : b < a := have h1 : b ≤ a, from le_of_one_div_le_one_div_of_neg h (le_of_lt hl), have hn : b ≠ a, from (assume hn' : b = a, have hl' : 1 / a = 1 / b, by rw hn', absurd hl' (ne_of_lt hl)), lt_of_le_of_ne h1 hn lemma one_div_lt_one_div_of_lt {a b : α} (ha : 0 < a) (h : a < b) : 1 / b < 1 / a := lt_of_not_ge (assume h', absurd h (not_lt_of_ge (le_of_one_div_le_one_div ha h'))) lemma one_div_le_one_div_of_le {a b : α} (ha : 0 < a) (h : a ≤ b) : 1 / b ≤ 1 / a := le_of_not_gt (assume h', absurd h (not_le_of_gt (lt_of_one_div_lt_one_div ha h'))) lemma one_div_lt_one_div_of_lt_of_neg {a b : α} (hb : b < 0) (h : a < b) : 1 / b < 1 / a := lt_of_not_ge (assume h', absurd h (not_lt_of_ge (le_of_one_div_le_one_div_of_neg hb h'))) lemma one_div_le_one_div_of_le_of_neg {a b : α} (hb : b < 0) (h : a ≤ b) : 1 / b ≤ 1 / a := le_of_not_gt (assume h', absurd h (not_le_of_gt (lt_of_one_div_lt_one_div_of_neg hb h'))) lemma one_div_le_of_one_div_le_of_pos {a b : α} (ha : a > 0) (h : 1 / a ≤ b) : 1 / b ≤ a := begin rw [← one_div_one_div a], apply one_div_le_one_div_of_le, apply one_div_pos_of_pos, repeat {assumption} end lemma one_div_le_of_one_div_le_of_neg {a b : α} (ha : b < 0) (h : 1 / a ≤ b) : 1 / b ≤ a := begin rw [← one_div_one_div a], apply one_div_le_one_div_of_le_of_neg, repeat {assumption} end lemma one_lt_one_div {a : α} (h1 : 0 < a) (h2 : a < 1) : 1 < 1 / a := suffices 1 / 1 < 1 / a, by rwa one_div_one at this, one_div_lt_one_div_of_lt h1 h2 lemma one_le_one_div {a : α} (h1 : 0 < a) (h2 : a ≤ 1) : 1 ≤ 1 / a := suffices 1 / 1 ≤ 1 / a, by rwa one_div_one at this, one_div_le_one_div_of_le h1 h2 lemma one_div_lt_neg_one {a : α} (h1 : a < 0) (h2 : -1 < a) : 1 / a < -1 := suffices 1 / a < 1 / -1, by rwa one_div_neg_one_eq_neg_one at this, one_div_lt_one_div_of_lt_of_neg h1 h2 lemma one_div_le_neg_one {a : α} (h1 : a < 0) (h2 : -1 ≤ a) : 1 / a ≤ -1 := suffices 1 / a ≤ 1 / -1, by rwa one_div_neg_one_eq_neg_one at this, one_div_le_one_div_of_le_of_neg h1 h2 lemma div_lt_div_of_pos_of_lt_of_pos {a b c : α} (hb : 0 < b) (h : b < a) (hc : 0 < c) : c / a < c / b := begin apply lt_of_sub_neg, rw [div_eq_mul_one_div, div_eq_mul_one_div c b, ← mul_sub_left_distrib], apply mul_neg_of_pos_of_neg, exact hc, apply sub_neg_of_lt, apply one_div_lt_one_div_of_lt, repeat {assumption} end lemma div_mul_le_div_mul_of_div_le_div_pos' {a b c d e : α} (h : a / b ≤ c / d) (he : e > 0) : a / (b * e) ≤ c / (d * e) := begin rw [div_mul_eq_div_mul_one_div, div_mul_eq_div_mul_one_div], apply mul_le_mul_of_nonneg_right h, apply le_of_lt, apply one_div_pos_of_pos he end end discrete_linear_ordered_field
444d3ccf0fad2e955e4152231f7c818698ecafa9
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebraic_topology/dold_kan/notations.lean
3276ab335e94ae1023f59f562d6f74944e3646a5
[ "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
980
lean
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import algebraic_topology.alternating_face_map_complex /-! # Notations for the Dold-Kan equivalence > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the notation `K[X] : chain_complex C ℕ` for the alternating face map complex of `(X : simplicial_object C)` where `C` is a preadditive category, as well as `N[X]` for the normalized subcomplex in the case `C` is an abelian category. (See `equivalence.lean` for the general strategy of proof of the Dold-Kan equivalence.) -/ localized "notation (name := alternating_face_map_complex) `K[`X`]` := algebraic_topology.alternating_face_map_complex.obj X" in dold_kan localized "notation (name := normalized_Moore_complex) `N[`X`]` := algebraic_topology.normalized_Moore_complex.obj X" in dold_kan
ad8be31119536e424f9b422849837c0f738cf206
17d3c61bf162bf88be633867ed4cb201378a8769
/library/init/meta/tactic.lean
d879bee2121bdd8d7a72213547342bd23c1ab380
[ "Apache-2.0" ]
permissive
u20024804/lean
11def01468fb4796fb0da76015855adceac7e311
d315e424ff17faf6fe096a0a1407b70193009726
refs/heads/master
1,611,388,567,561
1,485,836,506,000
1,485,836,625,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
33,778
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.function init.data.option.basic init.util import init.category.combinators init.category.monad init.category.alternative import init.data.nat.div init.meta.exceptional init.meta.format init.meta.environment import init.meta.pexpr init.data.to_string init.data.string.basic meta constant tactic_state : Type universe variables u v namespace tactic_state meta constant env : tactic_state → environment meta constant to_format : tactic_state → format /- Format expression with respect to the main goal in the tactic state. If the tactic state does not contain any goals, then format expression using an empty local context. -/ meta constant format_expr : tactic_state → expr → format meta constant get_options : tactic_state → options meta constant set_options : tactic_state → options → tactic_state end tactic_state meta instance : has_to_format tactic_state := ⟨tactic_state.to_format⟩ meta inductive tactic_result (α : Type u) | success : α → tactic_state → tactic_result | exception : (unit → format) → option expr → tactic_state → tactic_result open tactic_result section variables {α : Type u} variables [has_to_string α] meta def tactic_result_to_string : tactic_result α → string | (success a s) := to_string a | (exception .α t ref s) := "Exception: " ++ to_string (t ()) meta instance : has_to_string (tactic_result α) := ⟨tactic_result_to_string⟩ end attribute [reducible] meta def tactic (α : Type u) := tactic_state → tactic_result α section variables {α : Type u} {β : Type v} @[inline] meta def tactic_fmap (f : α → β) (t : tactic α) : tactic β := λ s, tactic_result.cases_on (t s) (λ a s', success (f a) s') (λ e s', exception β e s') @[inline] meta def tactic_bind (t₁ : tactic α) (t₂ : α → tactic β) : tactic β := λ s, tactic_result.cases_on (t₁ s) (λ a s', t₂ a s') (λ e s', exception β e s') @[inline] meta def tactic_return (a : α) : tactic α := λ s, success a s meta def tactic_orelse {α : Type u} (t₁ t₂ : tactic α) : tactic α := λ s, tactic_result.cases_on (t₁ s) success (λ e₁ ref₁ s', tactic_result.cases_on (t₂ s) success (exception α)) @[inline] meta def tactic_seq (t₁ : tactic α) (t₂ : tactic β) : tactic β := tactic_bind t₁ (λ a, t₂) infixl ` >>=[tactic] `:2 := tactic_bind infixl ` >>[tactic] `:2 := tactic_seq end meta instance : monad tactic := {map := @tactic_fmap, ret := @tactic_return, bind := @tactic_bind} meta def tactic.fail {α : Type u} {β : Type v} [has_to_format β] (msg : β) : tactic α := λ s, exception α (λ u, to_fmt msg) none s meta def tactic.failed {α : Type u} : tactic α := tactic.fail "failed" meta instance : alternative tactic := ⟨@tactic_fmap, (λ α a s, success a s), (@fapp _ _), @tactic.failed, @tactic_orelse⟩ meta def {u₁ u₂} tactic.up {α : Type u₂} (t : tactic α) : tactic (ulift.{u₁} α) := λ s, match t s with | success a s' := success (ulift.up a) s' | exception .α t ref s := exception (ulift α) t ref s end meta def {u₁ u₂} tactic.down {α : Type u₂} (t : tactic (ulift.{u₁} α)) : tactic α := λ s, match t s with | success (ulift.up a) s' := success a s' | exception .(ulift α) t ref s := exception α t ref s end namespace tactic variables {α : Type u} meta def try (t : tactic α) : tactic unit := λ s, tactic_result.cases_on (t s) (λ a, success ()) (λ e ref s', success () s) meta def skip : tactic unit := success () meta def fail_if_success {α : Type u} (t : tactic α) : tactic unit := λ s, tactic_result.cases_on (t s) (λ a s, exception _ (λ _, to_fmt "fail_if_success combinator failed, given tactic succeeded") none s) (λ e ref s', success () s) open list meta def foreach : list α → (α → tactic unit) → tactic unit | [] fn := skip | (e::es) fn := do fn e, foreach es fn open nat /- (repeat_at_most n t): repeat the given tactic at most n times or until t fails -/ meta def repeat_at_most : nat → tactic unit → tactic unit | 0 t := skip | (succ n) t := (do t, repeat_at_most n t) <|> skip /- (repeat_exactly n t) : execute t n times -/ meta def repeat_exactly : nat → tactic unit → tactic unit | 0 t := skip | (succ n) t := do t, repeat_exactly n t meta def repeat : tactic unit → tactic unit := repeat_at_most 100000 meta def returnex {α : Type} (e : exceptional α) : tactic α := λ s, match e with | (exceptional.success a) := tactic_result.success a s | (exceptional.exception .α f) := tactic_result.exception α (λ u, f options.mk) none s -- TODO(Leo): extract options from environment end meta def returnopt (e : option α) : tactic α := λ s, match e with | (some a) := tactic_result.success a s | none := tactic_result.exception α (λ u, to_fmt "failed") none s end /- Decorate t's exceptions with msg -/ meta def decorate_ex (msg : format) (t : tactic α) : tactic α := λ s, tactic_result.cases_on (t s) success (λ e, exception α (λ u, msg ++ format.nest 2 (format.line ++ e u))) @[inline] meta def write (s' : tactic_state) : tactic unit := λ s, success () s' @[inline] meta def read : tactic tactic_state := λ s, success s s end tactic meta def tactic_format_expr (e : expr) : tactic format := do s ← tactic.read, return (tactic_state.format_expr s e) meta class has_to_tactic_format (α : Type u) := (to_tactic_format : α → tactic format) meta instance : has_to_tactic_format expr := ⟨tactic_format_expr⟩ meta def tactic.pp {α : Type u} [has_to_tactic_format α] : α → tactic format := has_to_tactic_format.to_tactic_format open tactic format meta def list_to_tactic_format_aux {α : Type u} [has_to_tactic_format α] : bool → list α → tactic format | b [] := return $ to_fmt "" | b (x::xs) := do f₁ ← pp x, f₂ ← list_to_tactic_format_aux ff xs, return $ (if ¬ b then to_fmt "," ++ line else nil) ++ f₁ ++ f₂ meta def list_to_tactic_format {α : Type u} [has_to_tactic_format α] : list α → tactic format | [] := return $ to_fmt "[]" | (x::xs) := do f ← list_to_tactic_format_aux tt (x::xs), return $ to_fmt "[" ++ group (nest 1 f) ++ to_fmt "]" meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (list α) := ⟨list_to_tactic_format⟩ meta instance has_to_format_to_has_to_tactic_format (α : Type) [has_to_format α] : has_to_tactic_format α := ⟨(λ x, return x) ∘ to_fmt⟩ namespace tactic open tactic_state meta def get_env : tactic environment := do s ← read, return $ env s meta def get_decl (n : name) : tactic declaration := do s ← read, returnex $ environment.get (env s) n meta def trace {α : Type u} [has_to_tactic_format α] (a : α) : tactic unit := do fmt ← pp a, return $ _root_.trace_fmt fmt (λ u, ()) meta def trace_call_stack : tactic unit := take state, trace_call_stack (λ u, success u state) meta def trace_state : tactic unit := do s ← read, trace $ to_fmt s meta def get_options : tactic options := do s ← read, return s^.get_options meta def set_options (o : options) : tactic unit := do s ← read, write (s^.set_options o) meta def save_options {α : Type} (t : tactic α) : tactic α := do o ← get_options, a ← t, set_options o, return a inductive transparency | all | semireducible | reducible | none export transparency (reducible semireducible) /- (eval_expr α α_as_expr e) evaluates 'e' IF 'e' has type 'α'. 'α' must be a closed term. 'α_as_expr' is synthesized by the code generator. 'e' must be a closed expression at runtime. -/ meta constant eval_expr (α : Type u) {α_expr : pexpr} : expr → tactic α /- Return the partial term/proof constructed so far. Note that the resultant expression may contain variables that are not declarate in the current main goal. -/ meta constant result : tactic expr /- Display the partial term/proof constructed so far. This tactic is *not* equivalent to do { r ← result, s ← read, return (format_expr s r) } because this one will format the result with respect to the current goal, and trace_result will do it with respect to the initial goal. -/ meta constant format_result : tactic format /- Return target type of the main goal. Fail if tactic_state does not have any goal left. -/ meta constant target : tactic expr meta constant intro_core : name → tactic expr meta constant intron : nat → tactic unit meta constant rename : name → name → tactic unit /- Clear the given local constant. The tactic fails if the given expression is not a local constant. -/ meta constant clear : expr → tactic unit meta constant revert_lst : list expr → tactic nat meta constant whnf_core : transparency → expr → tactic expr /- (head) eta expand the given expression -/ meta constant eta_expand : expr → tactic expr /- (head) beta reduction -/ meta constant beta : expr → tactic expr /- (head) zeta reduction -/ meta constant zeta : expr → tactic expr /- (head) eta reduction -/ meta constant eta : expr → tactic expr meta constant unify_core : transparency → expr → expr → tactic unit /- is_def_eq_core is similar to unify_core, but it treats metavariables as constants. -/ meta constant is_def_eq_core : transparency → expr → expr → tactic unit /- Infer the type of the given expression. Remark: transparency does not affect type inference -/ meta constant infer_type : expr → tactic expr meta constant get_local : name → tactic expr /- Resolve a name using the current local context, environment, aliases, etc. -/ meta constant resolve_name : name → tactic expr /- Return the hypothesis in the main goal. Fail if tactic_state does not have any goal left. -/ meta constant local_context : tactic (list expr) meta constant get_unused_name : name → option nat → tactic name /- Helper tactic for creating simple applications where some arguments are inferred using type inference. Example, given rel.{l_1 l_2} : Pi (α : Type.{l_1}) (β : α -> Type.{l_2}), (Pi x : α, β x) -> (Pi x : α, β x) -> , Prop nat : Type real : Type vec.{l} : Pi (α : Type l) (n : nat), Type.{l1} f g : Pi (n : nat), vec real n then mk_app_core semireducible "rel" [f, g] returns the application rel.{1 2} nat (fun n : nat, vec real n) f g -/ meta constant mk_app_core : transparency → name → list expr → tactic expr /- Similar to mk_app, but allows to specify which arguments are explicit/implicit. Example, given a b : nat then mk_mapp_core semireducible "ite" [some (a > b), none, none, some a, some b] returns the application @ite.{1} (a > b) (nat.decidable_gt a b) nat a b -/ meta constant mk_mapp_core : transparency → name → list (option expr) → tactic expr /-- (mk_congr_arg h₁ h₂) is a more efficient version of (mk_app `congr_arg [h₁, h₂]) -/ meta constant mk_congr_arg : expr → expr → tactic expr /-- (mk_congr_fun h₁ h₂) is a more efficient version of (mk_app `congr_fun [h₁, h₂]) -/ meta constant mk_congr_fun : expr → expr → tactic expr /-- (mk_congr h₁ h₂) is a more efficient version of (mk_app `congr [h₁, h₂]) -/ meta constant mk_congr : expr → expr → tactic expr /-- (mk_eq_refl h) is a more efficient version of (mk_app `eq.refl [h]) -/ meta constant mk_eq_refl : expr → tactic expr /-- (mk_eq_symm h) is a more efficient version of (mk_app `eq.symm [h]) -/ meta constant mk_eq_symm : expr → tactic expr /-- (mk_eq_trans h₁ h₂) is a more efficient version of (mk_app `eq.trans [h₁, h₂]) -/ meta constant mk_eq_trans : expr → expr → tactic expr /-- (mk_eq_mp h₁ h₂) is a more efficient version of (mk_app `eq.mp [h₁, h₂]) -/ meta constant mk_eq_mp : expr → expr → tactic expr /-- (mk_eq_mpr h₁ h₂) is a more efficient version of (mk_app `eq.mpr [h₁, h₂]) -/ meta constant mk_eq_mpr : expr → expr → tactic expr /- Given a local constant t, if t has type (lhs = rhs) apply susbstitution. Otherwise, try to find a local constant that has type of the form (t = t') or (t' = t). The tactic fails if the given expression is not a local constant. -/ meta constant subst : expr → tactic unit meta constant exact_core : transparency → expr → tactic unit /- Elaborate the given quoted expression with respect to the current main goal. If the boolean argument is tt, then metavariables are tolerated and become new goals. -/ meta constant to_expr_core : bool → pexpr → tactic expr /- Return true if the given expression is a type class. -/ meta constant is_class : expr → tactic bool /- Try to create an instance of the given type class. -/ meta constant mk_instance : expr → tactic expr /- Change the target of the main goal. The input expression must be definitionally equal to the current target. -/ meta constant change : expr → tactic unit /- (assert_core H T), adds a new goal for T, and change target to (T -> target). -/ meta constant assert_core : name → expr → tactic unit /- (assertv_core H T P), change target to (T -> target) if P has type T. -/ meta constant assertv_core : name → expr → expr → tactic unit /- (define_core H T), adds a new goal for T, and change target to (let H : T := ?M in target) in the current goal. -/ meta constant define_core : name → expr → tactic unit /- (definev_core H T P), change target to (Let H : T := P in target) if P has type T. -/ meta constant definev_core : name → expr → expr → tactic unit /- rotate goals to the left -/ meta constant rotate_left : nat → tactic unit meta constant get_goals : tactic (list expr) meta constant set_goals : list expr → tactic unit /- (apply_core t approx all insts e), apply the expression e to the main goal, the unification is performed using the given transparency mode. If approx is tt, then fallback to first-order unification, and approximate context during unification. If all is tt, then all unassigned meta-variables are added as new goals. If insts is tt, then use type class resolution to instantiate unassigned meta-variables. -/ meta constant apply_core : transparency → bool → bool → bool → expr → tactic unit /- Create a fresh meta universe variable. -/ meta constant mk_meta_univ : tactic level /- Create a fresh meta-variable with the given type. The scope of the new meta-variable is the local context of the main goal. -/ meta constant mk_meta_var : expr → tactic expr /- Return the value assigned to the given universe meta-variable. Fail if argument is not an universe meta-variable or if it is not assigned. -/ meta constant get_univ_assignment : level → tactic level /- Return the value assigned to the given meta-variable. Fail if argument is not a meta-variable or if it is not assigned. -/ meta constant get_assignment : expr → tactic expr meta constant mk_fresh_name : tactic name /- Return a hash code for expr that ignores inst_implicit arguments, and proofs. -/ meta constant abstract_hash : expr → tactic nat /- Return the "weight" of the given expr while ignoring inst_implicit arguments, and proofs. -/ meta constant abstract_weight : expr → tactic nat meta constant abstract_eq : expr → expr → tactic bool /- (induction_core m H rec ns) induction on H using recursor rec, names for the new hypotheses are retrieved from ns. If ns does not have sufficient names, then use the internal binder names in the recursor. -/ meta constant induction_core : transparency → expr → name → list name → tactic unit /- (cases_core m H ns) apply cases_on recursor, names for the new hypotheses are retrieved from ns. H must be a local constant -/ meta constant cases_core : transparency → expr → list name → tactic unit /- (destruct_core m e) similar to cases tactic, but does not revert/intro/clear hypotheses. -/ meta constant destruct_core : transparency → expr → tactic unit /- (generalize_core m e n) -/ meta constant generalize_core : transparency → expr → name → tactic unit /- instantiate assigned metavariables in the given expression -/ meta constant instantiate_mvars : expr → tactic expr /- Add the given declaration to the environment -/ meta constant add_decl : declaration → tactic unit /- (doc_string env d k) return the doc string for d (if available) -/ meta constant doc_string : name → tactic string meta constant add_doc_string : name → string → tactic unit meta constant module_doc_strings : tactic (list (option name × string)) /- (set_basic_attribute_core attr_name c_name persistent prio) set attribute attr_name for constant c_name with the given priority. If the priority is none, then use default -/ meta constant set_basic_attribute_core : name → name → bool → option nat → tactic unit /- (unset_attribute attr_name c_name) -/ meta constant unset_attribute : name → name → tactic unit /- (has_attribute attr_name c_name) succeeds if the declaration `decl_name` has the attribute `attr_name`. The result is the priority. -/ meta constant has_attribute : name → name → tactic nat meta def set_basic_attribute : name → name → bool → tactic unit := λ a n p, set_basic_attribute_core a n p none /- (copy_attribute attr_name c_name d_name) copy attribute `attr_name` from `src` to `tgt` if it is defined for `src` -/ meta def copy_attribute (attr_name : name) (src : name) (p : bool) (tgt : name) : tactic unit := try $ do prio ← has_attribute attr_name src, set_basic_attribute_core attr_name tgt p (some prio) /-- Name of the declaration currently being elaborated. -/ meta constant decl_name : tactic name /- (save_type_info e ref) save (typeof e) at position associated with ref -/ meta constant save_type_info : expr → expr → tactic unit meta constant save_info_thunk : nat → nat → (unit → format) → tactic unit meta constant report_error : nat → nat → format → tactic unit /- Return list of currently opened namespace -/ meta constant open_namespaces : tactic (list name) open list nat /- Remark: set_goals will erase any solved goal -/ meta def cleanup : tactic unit := get_goals >>= set_goals /- Auxiliary definition used to implement begin ... end blocks -/ meta def step {α : Type u} (t : tactic α) : tactic unit := t >>[tactic] cleanup /- Auxiliary definition used to implement begin ... end blocks. It is similar to step, but it reports an error at the given line/col if the tactic t fails. -/ meta def rstep {α : Type u} (line : nat) (col : nat) (t : tactic α) : tactic unit := λ s, tactic_result.cases_on (@scope_trace _ line col (λ _, (t >>[tactic] cleanup) s)) (λ a new_s, tactic_result.success () new_s) (λ msg_thunk e new_s, let msg := msg_thunk () ++ format.line ++ to_fmt "state:" ++ format.line ++ new_s^.to_format in (tactic.report_error line col msg >> tactic.failed) new_s) meta def is_prop (e : expr) : tactic bool := do t ← infer_type e, return (to_bool (t = expr.prop)) /-- Return true iff n is the name of declaration that is a proposition. -/ meta def is_prop_decl (n : name) : tactic bool := do env ← get_env, d ← returnex $ env^.get n, t ← return $ d^.type, is_prop t meta def is_proof (e : expr) : tactic bool := infer_type e >>= is_prop meta def whnf : expr → tactic expr := whnf_core semireducible meta def whnf_no_delta : expr → tactic expr := whnf_core transparency.none meta def whnf_target : tactic unit := target >>= whnf >>= change meta def intro (n : name) : tactic expr := do t ← target, if expr.is_pi t ∨ expr.is_let t then intro_core n else whnf_target >> intro_core n meta def intro1 : tactic expr := intro `_ /- Remark: the unit argument is a trick to allow us to write a recursive definition. Lean3 only allows recursive functions when "equations" are used. -/ meta def intros_core : unit → tactic (list expr) | u := do t ← target, match t with | (expr.pi n bi d b) := do H ← intro1, Hs ← intros_core u, return (H :: Hs) | (expr.elet n t v b) := do H ← intro1, Hs ← intros_core u, return (H :: Hs) | e := return [] end meta def intros : tactic (list expr) := intros_core () meta def intro_lst : list name → tactic (list expr) | [] := return [] | (n::ns) := do H ← intro n, Hs ← intro_lst ns, return (H :: Hs) meta def mk_app : name → list expr → tactic expr := mk_app_core semireducible meta def mk_mapp : name → list (option expr) → tactic expr := mk_mapp_core semireducible meta def to_expr : pexpr → tactic expr := to_expr_core tt meta def to_expr_strict : pexpr → tactic expr := to_expr_core ff meta def revert (l : expr) : tactic nat := revert_lst [l] meta def clear_lst : list name → tactic unit | [] := skip | (n::ns) := do H ← get_local n, clear H, clear_lst ns meta def unify : expr → expr → tactic unit := unify_core semireducible meta def is_def_eq : expr → expr → tactic unit := is_def_eq_core semireducible meta def match_not (e : expr) : tactic expr := match (expr.is_not e) with | (some a) := return a | none := fail "expression is not a negation" end meta def match_eq (e : expr) : tactic (expr × expr) := match (expr.is_eq e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not an equality" end meta def match_ne (e : expr) : tactic (expr × expr) := match (expr.is_ne e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not a disequality" end meta def match_heq (e : expr) : tactic (expr × expr × expr × expr) := do match (expr.is_heq e) with | (some (α, lhs, β, rhs)) := return (α, lhs, β, rhs) | none := fail "expression is not a heterogeneous equality" end meta def match_refl_app (e : expr) : tactic (name × expr × expr) := do env ← get_env, match (environment.is_refl_app env e) with | (some (R, lhs, rhs)) := return (R, lhs, rhs) | none := fail "expression is not an application of a reflexive relation" end meta def match_app_of (e : expr) (n : name) : tactic (list expr) := guard (expr.is_app_of e n) >> return e^.get_app_args meta def get_local_type (n : name) : tactic expr := get_local n >>= infer_type meta def trace_result : tactic unit := format_result >>= trace meta def exact : expr → tactic unit := exact_core semireducible meta def rexact : expr → tactic unit := exact_core reducible /- (find_same_type t es) tries to find in es an expression with type definitionally equal to t -/ meta def find_same_type : expr → list expr → tactic expr | e [] := failed | e (H :: Hs) := do t ← infer_type H, (unify e t >> return H) <|> find_same_type e Hs meta def find_assumption (e : expr) : tactic expr := do ctx ← local_context, find_same_type e ctx meta def assumption : tactic unit := do { ctx ← local_context, t ← target, H ← find_same_type t ctx, exact H } <|> fail "assumption tactic failed" meta def save_info (line : nat) (col : nat) : tactic unit := do s ← read, tactic.save_info_thunk line col (λ _, tactic_state.to_format s) notation `‹` p `›` := show p, by assumption /- Swap first two goals, do nothing if tactic state does not have at least two goals. -/ meta def swap : tactic unit := do gs ← get_goals, match gs with | (g₁ :: g₂ :: rs) := set_goals (g₂ :: g₁ :: rs) | e := skip end /- (assert h t), adds a new goal for t, and the hypothesis (h : t) in the current goal. -/ meta def assert (h : name) (t : expr) : tactic unit := assert_core h t >> swap >> intro h >> swap /- (assertv h t v), adds the hypothesis (h : t) in the current goal if v has type t. -/ meta def assertv (h : name) (t : expr) (v : expr) : tactic unit := assertv_core h t v >> intro h >> return () /- (define h t), adds a new goal for t, and the hypothesis (h : t := ?M) in the current goal. -/ meta def define (h : name) (t : expr) : tactic unit := define_core h t >> swap >> intro h >> swap /- (definev h t v), adds the hypothesis (h : t := v) in the current goal if v has type t. -/ meta def definev (h : name) (t : expr) (v : expr) : tactic unit := definev_core h t v >> intro h >> return () /- Add (h : t := pr) to the current goal -/ meta def pose (h : name) (pr : expr) : tactic unit := do t ← infer_type pr, definev h t pr /- Add (h : t) to the current goal, given a proof (pr : t) -/ meta def note (n : name) (pr : expr) : tactic unit := do t ← infer_type pr, assertv n t pr /- Return the number of goals that need to be solved -/ meta def num_goals : tactic nat := do gs ← get_goals, return (length gs) /- We have to provide the instance argument `[has_mod nat]` because mod for nat was not defined yet -/ meta def rotate_right (n : nat) [has_mod nat] : tactic unit := do ng ← num_goals, if ng = 0 then skip else rotate_left (ng - n % ng) meta def rotate : nat → tactic unit := rotate_left /- first [t_1, ..., t_n] applies the first tactic that doesn't fail. The tactic fails if all t_i's fail. -/ meta def first {α : Type u} : list (tactic α) → tactic α | [] := fail "first tactic failed, no more alternatives" | (t::ts) := t <|> first ts /- Applies the given tactic to the main goal and fails if it is not solved. -/ meta def solve1 (tac : tactic unit) : tactic unit := do gs ← get_goals, match gs with | [] := fail "focus tactic failed, there isn't any goal left to focus" | (g::rs) := do set_goals [g], tac, gs' ← get_goals, match gs' with | [] := set_goals rs | gs := fail "focus tactic failed, focused goal has not been solved" end end /- solve [t_1, ... t_n] applies the first tactic that solves the main goal. -/ meta def solve (ts : list (tactic unit)) : tactic unit := first $ map solve1 ts private meta def focus_aux : list (tactic unit) → list expr → list expr → tactic unit | [] gs rs := set_goals $ gs ++ rs | (t::ts) (g::gs) rs := do set_goals [g], t, rs' ← get_goals, focus_aux ts gs (rs ++ rs') | (t::ts) [] rs := fail "focus tactic failed, insufficient number of goals" /- focus [t_1, ..., t_n] applies t_i to the i-th goal. Fails if there are less tha n goals. -/ meta def focus (ts : list (tactic unit)) : tactic unit := do gs ← get_goals, focus_aux ts gs [] private meta def all_goals_core : tactic unit → list expr → list expr → tactic unit | tac [] ac := set_goals ac | tac (g :: gs) ac := do set_goals [g], tac, new_gs ← get_goals, all_goals_core tac gs (ac ++ new_gs) /- Apply the given tactic to all goals. -/ meta def all_goals (tac : tactic unit) : tactic unit := do gs ← get_goals, all_goals_core tac gs [] /- LCF-style AND_THEN tactic. It applies tac1, and if succeed applies tac2 to each subgoal produced by tac1 -/ meta def seq (tac1 : tactic unit) (tac2 : tactic unit) : tactic unit := do g::gs ← get_goals | failed, set_goals [g], tac1, all_goals tac2, gs' ← get_goals, set_goals (gs' ++ gs) meta instance : has_andthen (tactic unit) := ⟨seq⟩ /- Applies tac if c holds -/ meta def when (c : Prop) [decidable c] (tac : tactic unit) : tactic unit := if c then tac else skip meta constant is_trace_enabled_for : name → bool /- Execute tac only if option trace.n is set to true. -/ meta def when_tracing (n : name) (tac : tactic unit) : tactic unit := when (is_trace_enabled_for n = tt) tac /- Fail if there are no remaining goals. -/ meta def fail_if_no_goals : tactic unit := do n ← num_goals, when (n = 0) (fail "tactic failed, there are no goals to be solved") /- Fail if there are unsolved goals. -/ meta def now : tactic unit := do n ← num_goals, when (n ≠ 0) (fail "now tactic failed, there are unsolved goals") meta def apply : expr → tactic unit := apply_core semireducible tt ff tt meta def fapply : expr → tactic unit := apply_core semireducible tt tt tt /- Try to solve the main goal using type class resolution. -/ meta def apply_instance : tactic unit := do tgt ← target >>= instantiate_mvars, b ← is_class tgt, if b then mk_instance tgt >>= exact else fail "apply_instance tactic fail, target is not a type class" /- Create a list of universe meta-variables of the given size. -/ meta def mk_num_meta_univs : nat → tactic (list level) | 0 := return [] | (succ n) := do l ← mk_meta_univ, ls ← mk_num_meta_univs n, return (l::ls) /- Return (expr.const c [l_1, ..., l_n]) where l_i's are fresh universe meta-variables. -/ meta def mk_const (c : name) : tactic expr := do env ← get_env, decl ← returnex (environment.get env c), num ← return (length (declaration.univ_params decl)), ls ← mk_num_meta_univs num, return (expr.const c ls) meta def save_const_type_info (n : name) (ref : expr) : tactic unit := try (do c ← mk_const n, save_type_info c ref) /- Create a fresh universe ?u, a metavariable (?T : Type.{?u}), and return metavariable (?M : ?T). This action can be used to create a meta-variable when we don't know its type at creation time -/ meta def mk_mvar : tactic expr := do u ← mk_meta_univ, t ← mk_meta_var (expr.sort u), mk_meta_var t meta def mk_local' (pp_name : name) (bi : binder_info) (type : expr) : tactic expr := do uniq_name ← mk_fresh_name, return $ expr.local_const uniq_name pp_name bi type meta def mk_local_def (pp_name : name) (type : expr) : tactic expr := mk_local' pp_name binder_info.default type private meta def get_pi_arity_aux : expr → tactic nat | (expr.pi n bi d b) := do m ← mk_fresh_name, l ← return (expr.local_const m n bi d), new_b ← whnf (expr.instantiate_var b l), r ← get_pi_arity_aux new_b, return (r + 1) | e := return 0 /- Compute the arity of the given (Pi-)type -/ meta def get_pi_arity (type : expr) : tactic nat := whnf type >>= get_pi_arity_aux /- Compute the arity of the given function -/ meta def get_arity (fn : expr) : tactic nat := infer_type fn >>= get_pi_arity meta def triv : tactic unit := mk_const `trivial >>= exact notation `dec_trivial` := of_as_true (by tactic.triv) meta def by_contradiction (H : name) : tactic expr := do tgt : expr ← target, (match_not tgt >> return ()) <|> (mk_mapp `decidable.by_contradiction [some tgt, none] >>= apply) <|> fail "tactic by_contradiction failed, target is not a negation nor a decidable proposition (remark: when 'local attribute classical.prop_decidable [instance]' is used all propositions are decidable)", intro H meta def cases (H : expr) : tactic unit := cases_core semireducible H [] meta def cases_using : expr → list name → tactic unit := cases_core semireducible meta def induction : expr → name → list name → tactic unit := induction_core semireducible meta def destruct (e : expr) : tactic unit := destruct_core semireducible e meta def generalize : expr → name → tactic unit := generalize_core semireducible meta def generalizes : list expr → tactic unit | [] := skip | (e::es) := generalize e `x >> generalizes es meta def refine (e : pexpr) : tactic unit := do tgt : expr ← target, to_expr `((%%e : %%tgt)) >>= exact /- (solve_aux type tac) synthesize an element of 'type' using tactic 'tac' -/ meta def solve_aux {α : Type} (type : expr) (tac : tactic α) : tactic (α × expr) := do m ← mk_meta_var type, gs ← get_goals, set_goals [m], a ← tac, set_goals gs, return (a, m) end tactic open tactic meta def nat.to_expr : nat → tactic expr | n := if n = 0 then to_expr `(0) else if n = 1 then to_expr `(1) else do r : expr ← nat.to_expr (n / 2), if n % 2 = 0 then to_expr `(bit0 %%r) else to_expr `(bit1 %%r) meta def char.to_expr : char → tactic expr | ⟨n, pr⟩ := do e ← n^.to_expr, to_expr `(char.of_nat %%e) meta def string.to_expr : string → tactic expr | [] := to_expr `(string.empty) | (c::cs) := do e ← c^.to_expr, es ← string.to_expr cs, to_expr `(string.str %%e %%es) meta def unsigned.to_expr : unsigned → tactic expr | ⟨n, pr⟩ := do e ← n^.to_expr, to_expr `(unsigned.of_nat %%e) meta def name.to_expr : name → tactic expr | name.anonymous := to_expr `(name.anonymous) | (name.mk_string s n) := do es ← s^.to_expr, en ← name.to_expr n, to_expr `(name.mk_string %%es %%en) | (name.mk_numeral i n) := do is ← i^.to_expr, en ← name.to_expr n, to_expr `(name.mk_string %%is %%en) meta def list_name.to_expr : list name → tactic expr | [] := to_expr `(([] : list name)) | (h::t) := do eh ← h^.to_expr, et ← list_name.to_expr t, to_expr `(%%eh :: %%et) notation [parsing_only] `command`:max := tactic unit open tactic /- Define id_locked using meta-programming because we don't have syntax for setting reducibility_hints. See module init.meta.declaration. Remark: id_locked is used in the builtin implementation of tactic.change -/ run_command do l ← return $ level.param `l, Ty ← return $ expr.sort l, type ← to_expr `(Π (α : %%Ty), α → α), val ← to_expr `(λ (α : %%Ty) (a : α), a), add_decl (declaration.defn `id_locked [`l] type val reducibility_hints.opaque tt) lemma id_locked_eq {α : Type u} (a : α) : id_locked α a = a := rfl
270111c0731f8f11d0814d5cad01f13175b0cdbe
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/triangulated/pretriangulated.lean
bf6c5f20d62423b574beeeef52abc25a6ef05c8d
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
5,662
lean
/- Copyright (c) 2021 Luke Kershaw. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Luke Kershaw -/ import category_theory.preadditive.additive_functor import category_theory.shift.basic import category_theory.triangulated.rotate /-! # Pretriangulated Categories > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file contains the definition of pretriangulated categories and triangulated functors between them. ## Implementation Notes We work under the assumption that pretriangulated categories are preadditive categories, but not necessarily additive categories, as is assumed in some sources. TODO: generalise this to n-angulated categories as in https://arxiv.org/abs/1006.4592 -/ noncomputable theory open category_theory open category_theory.preadditive open category_theory.limits universes v v₀ v₁ v₂ u u₀ u₁ u₂ namespace category_theory open category pretriangulated /- We work in a preadditive category `C` equipped with an additive shift. -/ variables (C : Type u) [category.{v} C] [has_zero_object C] [has_shift C ℤ] [preadditive C] [∀ n : ℤ, functor.additive (shift_functor C n)] variables (D : Type u₂) [category.{v₂} D] [has_zero_object D] [has_shift D ℤ] [preadditive D] [∀ n : ℤ, functor.additive (shift_functor D n)] /-- A preadditive category `C` with an additive shift, and a class of "distinguished triangles" relative to that shift is called pretriangulated if the following hold: * Any triangle that is isomorphic to a distinguished triangle is also distinguished. * Any triangle of the form `(X,X,0,id,0,0)` is distinguished. * For any morphism `f : X ⟶ Y` there exists a distinguished triangle of the form `(X,Y,Z,f,g,h)`. * The triangle `(X,Y,Z,f,g,h)` is distinguished if and only if `(Y,Z,X⟦1⟧,g,h,-f⟦1⟧)` is. * Given a diagram: ``` f g h X ───> Y ───> Z ───> X⟦1⟧ │ │ │ │a │b │a⟦1⟧' V V V X' ───> Y' ───> Z' ───> X'⟦1⟧ f' g' h' ``` where the left square commutes, and whose rows are distinguished triangles, there exists a morphism `c : Z ⟶ Z'` such that `(a,b,c)` is a triangle morphism. See <https://stacks.math.columbia.edu/tag/0145> -/ class pretriangulated := (distinguished_triangles [] : set (triangle C)) (isomorphic_distinguished : Π (T₁ ∈ distinguished_triangles) (T₂ ≅ T₁), T₂ ∈ distinguished_triangles) (contractible_distinguished : Π (X : C), (contractible_triangle X) ∈ distinguished_triangles) (distinguished_cocone_triangle : Π (X Y : C) (f : X ⟶ Y), (∃ (Z : C) (g : Y ⟶ Z) (h : Z ⟶ X⟦(1:ℤ)⟧), triangle.mk f g h ∈ distinguished_triangles)) (rotate_distinguished_triangle : Π (T : triangle C), T ∈ distinguished_triangles ↔ T.rotate ∈ distinguished_triangles) (complete_distinguished_triangle_morphism : Π (T₁ T₂ : triangle C) (h₁ : T₁ ∈ distinguished_triangles) (h₂ : T₂ ∈ distinguished_triangles) (a : T₁.obj₁ ⟶ T₂.obj₁) (b : T₁.obj₂ ⟶ T₂.obj₂) (comm₁ : T₁.mor₁ ≫ b = a ≫ T₂.mor₁), (∃ (c : T₁.obj₃ ⟶ T₂.obj₃), (T₁.mor₂ ≫ c = b ≫ T₂.mor₂) ∧ (T₁.mor₃ ≫ a⟦1⟧' = c ≫ T₂.mor₃) )) namespace pretriangulated variables [hC : pretriangulated C] include hC notation `dist_triang `:20 C := distinguished_triangles C /-- Given any distinguished triangle `T`, then we know `T.rotate` is also distinguished. -/ lemma rot_of_dist_triangle (T ∈ dist_triang C) : (T.rotate ∈ dist_triang C) := (rotate_distinguished_triangle T).mp H /-- Given any distinguished triangle `T`, then we know `T.inv_rotate` is also distinguished. -/ lemma inv_rot_of_dist_triangle (T ∈ dist_triang C) : (T.inv_rotate ∈ dist_triang C) := (rotate_distinguished_triangle (T.inv_rotate)).mpr (isomorphic_distinguished T H T.inv_rotate.rotate (inv_rot_comp_rot.app T)) /-- Given any distinguished triangle ``` f g h X ───> Y ───> Z ───> X⟦1⟧ ``` the composition `f ≫ g = 0`. See <https://stacks.math.columbia.edu/tag/0146> -/ lemma comp_dist_triangle_mor_zero₁₂ (T ∈ dist_triang C) : T.mor₁ ≫ T.mor₂ = 0 := begin obtain ⟨c, hc⟩ := complete_distinguished_triangle_morphism _ _ (contractible_distinguished T.obj₁) H (𝟙 T.obj₁) T.mor₁ rfl, simpa only [contractible_triangle_mor₂, zero_comp] using hc.left.symm, end /-- Given any distinguished triangle ``` f g h X ───> Y ───> Z ───> X⟦1⟧ ``` the composition `g ≫ h = 0`. See <https://stacks.math.columbia.edu/tag/0146> -/ lemma comp_dist_triangle_mor_zero₂₃ (T ∈ dist_triang C) : T.mor₂ ≫ T.mor₃ = 0 := comp_dist_triangle_mor_zero₁₂ C T.rotate (rot_of_dist_triangle C T H) /-- Given any distinguished triangle ``` f g h X ───> Y ───> Z ───> X⟦1⟧ ``` the composition `h ≫ f⟦1⟧ = 0`. See <https://stacks.math.columbia.edu/tag/0146> -/ lemma comp_dist_triangle_mor_zero₃₁ (T ∈ dist_triang C) : T.mor₃ ≫ ((shift_equiv C 1).functor.map T.mor₁) = 0 := have H₂ : _ := rot_of_dist_triangle C T.rotate (rot_of_dist_triangle C T H), by simpa using comp_dist_triangle_mor_zero₁₂ C (T.rotate.rotate) H₂ /- TODO: If `C` is pretriangulated with respect to a shift, then `Cᵒᵖ` is pretriangulated with respect to the inverse shift. -/ end pretriangulated end category_theory
ca92f3981f756d8706905318f5a88c4f5e88530b
bb31430994044506fa42fd667e2d556327e18dfe
/src/data/mv_polynomial/variables.lean
b7ce2c7c96b80e8958da7d998873e9e9861a72c5
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
29,530
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.monad /-! # Degrees and variables of polynomials 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_locale classical big_operators 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 σ := p.support.sup (λs:σ →₀ ℕ, s.to_multiset) lemma degrees_monomial (s : σ →₀ ℕ) (a : R) : degrees (monomial s a) ≤ s.to_multiset := finset.sup_le $ assume t h, begin 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 := le_antisymm (degrees_monomial s a) $ finset.le_sup $ by rw [support_monomial, if_neg ha, finset.mem_singleton] 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 (p q : mv_polynomial σ R) : (p + q).degrees ≤ p.degrees ⊔ q.degrees := begin 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*} (s : finset ι) (f : ι → mv_polynomial σ R) : (∑ i in s, f i).degrees ≤ s.sup (λi, (f i).degrees) := begin 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 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 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 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 {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 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 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 σ := p.degrees.to_finset @[simp] lemma vars_0 : (0 : mv_polynomial σ R).vars = ∅ := by rw [vars, degrees_zero, multiset.to_finset_zero] @[simp] lemma vars_monomial (h : r ≠ 0) : (monomial s r).vars = s.support := by rw [vars, degrees_monomial_eq _ _ h, finsupp.to_finset_to_multiset] @[simp] lemma vars_C : (C r : mv_polynomial σ R).vars = ∅ := by rw [vars, 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 rw [vars, multiset.mem_to_finset] at h, rw ← finsupp.not_mem_support_iff, contrapose! h, unfold degrees, 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 (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 (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, 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 (φ ψ : 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 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*} {s : finset ι} (f : ι → mv_polynomial σ R) : (∏ i in s, f i).vars ⊆ s.bUnion (λ i, (f i).vars) := begin 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 : (∑ i in t, φ i).vars ⊆ finset.bUnion t (λ i, (φ i).vars) := begin 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 (h : pairwise $ disjoint on (λ i, (φ i).vars)) : (∑ i in t, φ i).vars = finset.bUnion t (λ i, (φ i).vars) := begin 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 : 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) : ℕ := p.degrees.count n lemma degree_of_eq_sup (n : σ) (f : mv_polynomial σ R) : degree_of n f = f.support.sup (λ m, m n) := begin rw [degree_of, degrees, 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 (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 repeat {rw degree_of}, 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 repeat {rw degree_of}, 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 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 repeat {rw degree_of}, 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 simp only [degree_of, 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 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, have _ := finsupp.support_add hn, begin 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, have _ := add_monoid_algebra.support_mul a b hn, begin 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 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, 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 := ⟨bind₁ (λ 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_bind₁ (f : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : (bind₁ f φ).vars ⊆ φ.vars.bUnion (λ i, (f i).vars) := begin calc (bind₁ f φ).vars = (φ.support.sum (λ (x : σ →₀ ℕ), (bind₁ f) (monomial x (coeff x φ)))).vars : by { rw [← alg_hom.map_sum, ← φ.as_sum], } ... ≤ φ.support.bUnion (λ (i : σ →₀ ℕ), ((bind₁ f) (monomial i (coeff i φ))).vars) : vars_sum_subset _ _ ... = φ.support.bUnion (λ (d : σ →₀ ℕ), (C (coeff d φ) * ∏ i in d.support, f i ^ d i).vars) : by simp only [bind₁_monomial] ... ≤ φ.support.bUnion (λ (d : σ →₀ ℕ), d.support.bUnion (λ i, (f i).vars)) : _ -- proof below ... ≤ φ.vars.bUnion (λ (i : σ), (f i).vars) : _, -- proof below { apply finset.bUnion_mono, intros d hd, calc (C (coeff d φ) * ∏ (i : σ) in d.support, f i ^ d i).vars ≤ (C (coeff d φ)).vars ∪ (∏ (i : σ) in d.support, f i ^ d i).vars : vars_mul _ _ ... ≤ (∏ (i : σ) in d.support, f i ^ d i).vars : by simp only [finset.empty_union, vars_C, finset.le_iff_subset, finset.subset.refl] ... ≤ d.support.bUnion (λ (i : σ), (f i ^ d i).vars) : vars_prod _ ... ≤ d.support.bUnion (λ (i : σ), (f i).vars) : _, apply finset.bUnion_mono, intros i hi, apply vars_pow, }, { intro j, simp_rw finset.mem_bUnion, rintro ⟨d, hd, ⟨i, hi, hj⟩⟩, exact ⟨i, (mem_vars _).mpr ⟨d, hd, hi⟩, hj⟩ } end lemma mem_vars_bind₁ (f : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) {j : τ} (h : j ∈ (bind₁ f φ).vars) : ∃ (i : σ), i ∈ φ.vars ∧ j ∈ (f i).vars := by simpa only [exists_prop, finset.mem_bUnion, mem_support_iff, ne.def] using vars_bind₁ f φ h lemma vars_rename (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 simpa only [exists_prop, finset.mem_image] using vars_rename f φ h end eval_vars end comm_semiring end mv_polynomial
3e07c56327897bbbb3e39e8aa167d034dc0c3c34
7490bf5d40d31857a58062614642bb5a41c36154
/hw4.lean
4fadaef07dc822829cf677d64856c8196d6001f9
[]
no_license
reesegrayallen/Lean-Discrete-Mathematics
9f1d6fe1c814cc9264ce868a67adcf5a82566e22
00c875284613ea12e0a729f519738aab8599456b
refs/heads/main
1,674,181,372,629
1,606,801,004,000
1,606,801,004,000
317,387,970
0
0
null
null
null
null
UTF-8
Lean
false
false
8,305
lean
/- REESE ALLEN (rga2uz) Homework 4 CS 2102, Sullivan S20 -/ /- #1 Representing Partial Functions as Total Functions [20 points] Consider the strictly partial function, pid, from natural numbers to natural numbers, defined by cases as follows. If n is zero, the function is undefined, otherwise pid n = n. We can't represent this function directly in Lean, because Lean requires all functions to be total. The usual approach is to represent such a partial function as a total function that returns not a nat (for then it would have to return a nat, even when the argument is zero) but a value of type option nat. Use this approach to implement pid in Lean. Use "by cases" syntax. (Fill in the blanks.) -/ def pid : ℕ → option ℕ | 0 := option.none | x := option.some x #reduce pid 4 -- some 4 #reduce pid 0 -- none /- #2 Defining functions by cases (by pattern matching) [15 points] Given a value of type option ℕ, the value might be none or it might be some n, where n is a value of type ℕ. Write a funtion option_to_nat that takes any value of type option ℕ as an argument and that returns a natural number: namely 0 if the option value is none, and n if the option value is some n. Write your definition using C-style syntax, with an explicit return type specified. You will want to use a "match ... with ... end" expression to do the required pattern matching. (Note that it will be impossible to tell from the return value alone whether a given option was none or some 0.) -/ def option_to_nat (op : option ℕ) := match op with | option.none := 0 | option.some x := x end #eval option_to_nat (option.some 5) -- 5 #eval option_to_nat (option.none) -- 0 /- Personal Notes: there is not built-in notion of a partial function in dependent type theory; every element of a function is assumed to have a value at every input - option type provides a way of representing partial functions ex - an element of option β is either none or of the form some b, for some value b : β can think of an element f of type α → option β as being a partial function from α to β: for every a : α, f either returns none, indicating f is "undefined", or some b -/ /- #3 Inductive definitions. [15 points] You have probably yelled into a canyon (or maybe between two buildings) and heard a reverberating echo. An echo is a sound followed by another echo, or, eventually an echo is no sound at all (at which point the reverberation ends). Define a data type, echo, values of which represent echoes. For our purposes, an echo comes in one of two forms: it is either "silence" (at which point there is no more reverberation) OR it is a "sound" followed another echo. You can think of "silence" as a "base case" and "sound" as an inductive case, in the sense that an echo of this form is a sound followed by a smaller echo. Give each of these cases its own constructor. Once you've defined your data type, define e0, e1, and e3 to be identifiers bound to three values of this type, where e0 is bound to "silence", e1 is bound to an echo with one sound followed by silence, and e3 is bound to an echo with three sounds followed by silence. -/ -- this is not a "flat" type; constructors can act on elements of the very type being defined -- (opposed to those that just wrap data and insert it into a type, which the recursor unpacks) inductive echo : Type | silence : echo | succ (e : echo) : echo def e0 := echo.silence def e1 := echo.succ e0 def e2 := echo.succ (echo.succ e1) #check e0 -- e0 : echo #reduce e0 -- echo.silence #check e1 -- e1 : echo #reduce e1 -- echo.succ echo.silence #check e2 #check @echo.rec_on -- this is just another way to write the same thing inductive echo' : Type | silence' : echo' | succ : echo' → echo' def e0' := echo'.silence' def e1' := echo'.succ e0' #check echo'.rec_on /- #4 Lists. A word list type. [10 points] Define a data type, list_words_ values of which represent lists of words, where words are represented as values of type string. For our purposes, such a list comes in one of two forms: it is either "nil" (the word we tend to use for empty lists), or it is *constructed* from a word followed by a smaller list of words. Give each form of list its own constructor. Call the constructors nil and cons. Once you've defined your data type, define l0, l1, and l3 to be identifiers bound to three values of this type, where l0 is bound to an empty list of words, l1 is bound to a list with one word (followed by the empty list), and l3 is bound to a list with three words. We don't care what words you put in your lists (but be nice :-). -/ -- inductive list_words_ : Type -- | nil : list_words_ -- | cons : list_words_ → string→ list_words_ inductive list_words_: Type | nil : list_words_ | cons (h: list_words_) (t: string) : list_words_ #check list_words_ #check @list_words_.rec_on def l0 := list_words_.nil def l1 := list_words_.cons l0 "first" def l3 := (list_words_.cons(list_words_.cons l1 "second") "third") #check l0 #check l1 #check l3 /- #5 Recursive definitions. Length of word list. [10 points] Define a function, num_words, that takes a word list (as just defined) as an argument and that returns the length of the list as a value of type ℕ. -/ def num_words : list_words_ → ℕ | (list_words_.nil) := 0 | (list_words_.cons α β) := 1 + (num_words α) #reduce num_words l0 -- 0 #reduce num_words l1 -- 1 #reduce num_words l3 -- 3 /- #6 Recursion. Number of permutations of a set. [10 points] Suppose you have a set containing n objects, where n is a natural number. How many ways are there to make an ordered list of n objects from this (unordered) set? Such an ordered list is called a permutation. As an example, consider the set, { x, y, z}. Here are the lists: - x, y, z - x, z, y - y, x, z - y, z, x - z, x, y - z, y, x It's not too hard to see the answer to the question. First, if the set is empty, there is only *one* way to make a list: it is the empty list. If the list is not empty, there are n ways to pick the first element of the list (so in our example, there are three ways to pick the first element: it has to be x or y or z); and then what's left is to make the rest of each list from remaining n-1 (in our example, 2) elements. So the number of lists has to be n *times* the number of lists that can be produced from a set of size n-1. We can express this idea as a function. Let's call it the permutations function, or perms, for short. As we've seen, perms 0 must be one. This is the base case. Implement the function, perms: ℕ → ℕ, to compute the number of perms for a set of any given size, n. Note that in Lean you'll need to use "by cases" syntax to define a recursive function. -/ -- n! def perms : ℕ → ℕ | 0 := 1 | (nat.succ n) := nat.succ n * perms n #eval perms nat.zero -- 1 #eval perms 4 -- 24 /- #7 Recursion. Number of subsets of a given set. [20 points] How many subsets are there of a set of size n? A subset of a set, s, is a set all of whose elements are in s. So every set is a subset of itself, and the empty set is a subset of every set, s (since all of its elements, of which there are none(!), are in s). So how many subsets are there of a set of size n? We can answer this question nicely using recursion. First, how many subsets are there of the empty set? It's one, right? If you don't see this immediately, reread the preceding explanation. Now, consider a set, s, of size n, where n is one more than some number, n'. How many subsets does s have? To see the answer, ask the question, how many subsets does a subset of s of size n' = (n-1) have? If you have the answer to that question, then you can easily compute the number of subsets of s. A set, s', of size n' must have left out one element of s, let's call it e. For each subset of s', you can form *two* subsets of s: one with, and one without e. Write a function, power_set_cardinality, that takes a natural number representing the size of a set, s, and that then returns a natural number expressing the number of subsets there are of a set of that size. -/ def power_set_cardinality: ℕ → ℕ | nat.zero := 1 | (nat.succ n) := 2 * (power_set_cardinality n) #eval power_set_cardinality 5 -- 32
be2120a03e28ecd418525a653bd981755141e7d8
7cef822f3b952965621309e88eadf618da0c8ae9
/src/analysis/specific_limits.lean
ebed7c6a42951d018af78de2c3a9efd97c884bce
[ "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
18,385
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 A collection of specific limit computations. -/ import analysis.normed_space.basic algebra.geom_sum import topology.instances.ennreal noncomputable theory open_locale classical topological_space open classical function lattice filter finset metric variables {α : Type*} {β : Type*} {ι : Type*} /-- If a function tends to infinity along a filter, then this function multiplied by a positive constant (on the left) also tends to infinity. The archimedean assumption is convenient to get a statement that works on `ℕ`, `ℤ` and `ℝ`, although not necessary (a version in ordered fields is given in `tendsto_at_top_mul_left'`). -/ lemma tendsto_at_top_mul_left [decidable_linear_ordered_semiring α] [archimedean α] {l : filter β} {r : α} (hr : 0 < r) {f : β → α} (hf : tendsto f l at_top) : tendsto (λx, r * f x) l at_top := begin apply (tendsto_at_top _ _).2 (λb, _), obtain ⟨n, hn⟩ : ∃ (n : ℕ), (1 : α) ≤ n • r := archimedean.arch 1 hr, have hn' : 1 ≤ r * n, by rwa add_monoid.smul_eq_mul' at hn, filter_upwards [(tendsto_at_top _ _).1 hf (n * max b 0)], assume x hx, calc b ≤ 1 * max b 0 : by { rw [one_mul], exact le_max_left _ _ } ... ≤ (r * n) * max b 0 : mul_le_mul_of_nonneg_right hn' (le_max_right _ _) ... = r * (n * max b 0) : by rw [mul_assoc] ... ≤ r * f x : mul_le_mul_of_nonneg_left hx (le_of_lt hr) end /-- If a function tends to infinity along a filter, then this function multiplied by a positive constant (on the right) also tends to infinity. The archimedean assumption is convenient to get a statement that works on `ℕ`, `ℤ` and `ℝ`, although not necessary (a version in ordered fields is given in `tendsto_at_top_mul_right'`). -/ lemma tendsto_at_top_mul_right [decidable_linear_ordered_semiring α] [archimedean α] {l : filter β} {r : α} (hr : 0 < r) {f : β → α} (hf : tendsto f l at_top) : tendsto (λx, f x * r) l at_top := begin apply (tendsto_at_top _ _).2 (λb, _), obtain ⟨n, hn⟩ : ∃ (n : ℕ), (1 : α) ≤ n • r := archimedean.arch 1 hr, have hn' : 1 ≤ (n : α) * r, by rwa add_monoid.smul_eq_mul at hn, filter_upwards [(tendsto_at_top _ _).1 hf (max b 0 * n)], assume x hx, calc b ≤ max b 0 * 1 : by { rw [mul_one], exact le_max_left _ _ } ... ≤ max b 0 * (n * r) : mul_le_mul_of_nonneg_left hn' (le_max_right _ _) ... = (max b 0 * n) * r : by rw [mul_assoc] ... ≤ f x * r : mul_le_mul_of_nonneg_right hx (le_of_lt hr) end /-- If a function tends to infinity along a filter, then this function multiplied by a positive constant (on the left) also tends to infinity. For a version working in `ℕ` or `ℤ`, use `tendsto_at_top_mul_left` instead. -/ lemma tendsto_at_top_mul_left' [linear_ordered_field α] {l : filter β} {r : α} (hr : 0 < r) {f : β → α} (hf : tendsto f l at_top) : tendsto (λx, r * f x) l at_top := begin apply (tendsto_at_top _ _).2 (λb, _), filter_upwards [(tendsto_at_top _ _).1 hf (b/r)], assume x hx, simpa [div_le_iff' hr] using hx end /-- If a function tends to infinity along a filter, then this function multiplied by a positive constant (on the right) also tends to infinity. For a version working in `ℕ` or `ℤ`, use `tendsto_at_top_mul_right` instead. -/ lemma tendsto_at_top_mul_right' [linear_ordered_field α] {l : filter β} {r : α} (hr : 0 < r) {f : β → α} (hf : tendsto f l at_top) : tendsto (λx, f x * r) l at_top := by simpa [mul_comm] using tendsto_at_top_mul_left' hr hf /-- If a function tends to infinity along a filter, then this function divided by a positive constant also tends to infinity. -/ lemma tendsto_at_top_div [linear_ordered_field α] {l : filter β} {r : α} (hr : 0 < r) {f : β → α} (hf : tendsto f l at_top) : tendsto (λx, f x / r) l at_top := tendsto_at_top_mul_right' (inv_pos hr) hf lemma summable_of_absolute_convergence_real {f : ℕ → ℝ} : (∃r, tendsto (λn, (range n).sum (λi, abs (f i))) at_top (𝓝 r)) → summable f | ⟨r, hr⟩ := begin refine summable_of_summable_norm ⟨r, (has_sum_iff_tendsto_nat_of_nonneg _ _).2 _⟩, exact assume i, norm_nonneg _, simpa only using hr end lemma tendsto_pow_at_top_at_top_of_gt_1 {r : ℝ} (h : 1 < r) : tendsto (λn:ℕ, r ^ n) at_top at_top := (tendsto_at_top_at_top _).2 $ assume p, let ⟨n, hn⟩ := pow_unbounded_of_one_lt p h in ⟨n, λ m hnm, le_of_lt $ lt_of_lt_of_le hn (pow_le_pow (le_of_lt h) hnm)⟩ lemma tendsto_inverse_at_top_nhds_0 : tendsto (λr:ℝ, r⁻¹) at_top (𝓝 0) := tendsto_orderable_unbounded (no_top 0) (no_bot 0) $ assume l u hl hu, mem_at_top_sets.mpr ⟨u⁻¹ + 1, assume b hb, have u⁻¹ < b, from lt_of_lt_of_le (lt_add_of_pos_right _ zero_lt_one) hb, ⟨lt_trans hl $ inv_pos $ lt_trans (inv_pos hu) this, lt_of_one_div_lt_one_div hu $ begin rw [inv_eq_one_div], simp [-one_div_eq_inv, div_div_eq_mul_div, div_one], simp [this] end⟩⟩ lemma tendsto_pow_at_top_nhds_0_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : tendsto (λn:ℕ, r^n) at_top (𝓝 0) := by_cases (assume : r = 0, (tendsto_add_at_top_iff_nat 1).mp $ by simp [pow_succ, this, tendsto_const_nhds]) (assume : r ≠ 0, have tendsto (λn, (r⁻¹ ^ n)⁻¹) at_top (𝓝 0), from tendsto.comp tendsto_inverse_at_top_nhds_0 (tendsto_pow_at_top_at_top_of_gt_1 $ one_lt_inv (lt_of_le_of_ne h₁ this.symm) h₂), tendsto.congr' (univ_mem_sets' $ by simp *) this) lemma nnreal.tendsto_pow_at_top_nhds_0_of_lt_1 {r : nnreal} (hr : r < 1) : tendsto (λ n:ℕ, r^n) at_top (𝓝 0) := nnreal.tendsto_coe.1 $ by simp only [nnreal.coe_pow, nnreal.coe_zero, tendsto_pow_at_top_nhds_0_of_lt_1 r.coe_nonneg hr] lemma ennreal.tendsto_pow_at_top_nhds_0_of_lt_1 {r : ennreal} (hr : r < 1) : tendsto (λ n:ℕ, r^n) at_top (𝓝 0) := begin rcases ennreal.lt_iff_exists_coe.1 hr with ⟨r, rfl, hr'⟩, rw [← ennreal.coe_zero], norm_cast at *, apply nnreal.tendsto_pow_at_top_nhds_0_of_lt_1 hr end lemma tendsto_pow_at_top_nhds_0_of_lt_1_normed_field {K : Type*} [normed_field K] {ξ : K} (_ : ∥ξ∥ < 1) : tendsto (λ n : ℕ, ξ^n) at_top (𝓝 0) := begin rw[tendsto_iff_norm_tendsto_zero], convert tendsto_pow_at_top_nhds_0_of_lt_1 (norm_nonneg ξ) ‹∥ξ∥ < 1›, ext n, simp end lemma tendsto_pow_at_top_at_top_of_gt_1_nat {k : ℕ} (h : 1 < k) : tendsto (λn:ℕ, k ^ n) at_top at_top := tendsto_coe_nat_real_at_top_iff.1 $ have hr : 1 < (k : ℝ), by rw [← nat.cast_one, nat.cast_lt]; exact h, by simpa using tendsto_pow_at_top_at_top_of_gt_1 hr lemma tendsto_inverse_at_top_nhds_0_nat : tendsto (λ n : ℕ, (n : ℝ)⁻¹) at_top (𝓝 0) := tendsto.comp tendsto_inverse_at_top_nhds_0 (tendsto_coe_nat_real_at_top_iff.2 tendsto_id) lemma tendsto_const_div_at_top_nhds_0_nat (C : ℝ) : tendsto (λ n : ℕ, C / n) at_top (𝓝 0) := by simpa only [mul_zero] using tendsto_const_nhds.mul tendsto_inverse_at_top_nhds_0_nat lemma tendsto_one_div_add_at_top_nhds_0_nat : tendsto (λ n : ℕ, 1 / ((n : ℝ) + 1)) at_top (𝓝 0) := suffices tendsto (λ n : ℕ, 1 / (↑(n + 1) : ℝ)) at_top (𝓝 0), by simpa, (tendsto_add_at_top_iff_nat 1).2 (tendsto_const_div_at_top_nhds_0_nat 1) lemma has_sum_geometric {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : has_sum (λn:ℕ, r ^ n) (1 - r)⁻¹ := have r ≠ 1, from ne_of_lt h₂, have r + -1 ≠ 0, by rw [←sub_eq_add_neg, ne, sub_eq_iff_eq_add]; simp; assumption, have tendsto (λn, (r ^ n - 1) * (r - 1)⁻¹) at_top (𝓝 ((0 - 1) * (r - 1)⁻¹)), from ((tendsto_pow_at_top_nhds_0_of_lt_1 h₁ h₂).sub tendsto_const_nhds).mul tendsto_const_nhds, have (λ n, (range n).sum (λ i, r ^ i)) = (λ n, geom_series r n) := rfl, (has_sum_iff_tendsto_nat_of_nonneg (pow_nonneg h₁) _).mpr $ by simp [neg_inv, geom_sum, div_eq_mul_inv, *] at * lemma summable_geometric {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : summable (λn:ℕ, r ^ n) := ⟨_, has_sum_geometric h₁ h₂⟩ lemma tsum_geometric {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : (∑n:ℕ, r ^ n) = (1 - r)⁻¹ := tsum_eq_has_sum (has_sum_geometric h₁ h₂) lemma has_sum_geometric_two : has_sum (λn:ℕ, ((1:ℝ)/2) ^ n) 2 := by convert has_sum_geometric _ _; norm_num lemma summable_geometric_two : summable (λn:ℕ, ((1:ℝ)/2) ^ n) := ⟨_, has_sum_geometric_two⟩ lemma tsum_geometric_two : (∑n:ℕ, ((1:ℝ)/2) ^ n) = 2 := tsum_eq_has_sum has_sum_geometric_two lemma has_sum_geometric_two' (a : ℝ) : has_sum (λn:ℕ, (a / 2) / 2 ^ n) a := begin convert has_sum_mul_left (a / 2) (has_sum_geometric (le_of_lt one_half_pos) one_half_lt_one), { funext n, simp, rw ← pow_inv; [refl, exact two_ne_zero] }, { norm_num, rw div_mul_cancel _ two_ne_zero } end lemma summable_geometric_two' (a : ℝ) : summable (λ n:ℕ, (a / 2) / 2 ^ n) := ⟨a, has_sum_geometric_two' a⟩ lemma tsum_geometric_two' (a : ℝ) : (∑ n:ℕ, (a / 2) / 2^n) = a := tsum_eq_has_sum $ has_sum_geometric_two' a lemma nnreal.has_sum_geometric {r : nnreal} (hr : r < 1) : has_sum (λ n : ℕ, r ^ n) (1 - r)⁻¹ := begin apply nnreal.has_sum_coe.1, push_cast, rw [nnreal.coe_sub (le_of_lt hr)], exact has_sum_geometric r.coe_nonneg hr end lemma nnreal.summable_geometric {r : nnreal} (hr : r < 1) : summable (λn:ℕ, r ^ n) := ⟨_, nnreal.has_sum_geometric hr⟩ lemma tsum_geometric_nnreal {r : nnreal} (hr : r < 1) : (∑n:ℕ, r ^ n) = (1 - r)⁻¹ := tsum_eq_has_sum (nnreal.has_sum_geometric hr) /-- The series `pow r` converges to `(1-r)⁻¹`. For `r < 1` the RHS is a finite number, and for `1 ≤ r` the RHS equals `∞`. -/ lemma ennreal.tsum_geometric (r : ennreal) : (∑n:ℕ, r ^ n) = (1 - r)⁻¹ := begin cases lt_or_le r 1 with hr hr, { rcases ennreal.lt_iff_exists_coe.1 hr with ⟨r, rfl, hr'⟩, norm_cast at *, convert ennreal.tsum_coe_eq (nnreal.has_sum_geometric hr), rw [ennreal.coe_inv $ ne_of_gt $ nnreal.sub_pos.2 hr] }, { rw [ennreal.sub_eq_zero_of_le hr, ennreal.inv_zero, ennreal.tsum_eq_supr_nat, supr_eq_top], refine λ a ha, (ennreal.exists_nat_gt (lt_top_iff_ne_top.1 ha)).imp (λ n hn, lt_of_lt_of_le hn _), have : ∀ k:ℕ, 1 ≤ r^k, by simpa using canonically_ordered_semiring.pow_le_pow_of_le_left hr, calc (n:ennreal) = (range n).sum (λ _, 1) : by rw [sum_const, add_monoid.smul_one, card_range] ... ≤ (range n).sum (pow r) : sum_le_sum (λ k _, this k) } end /-- For any positive `ε`, define on an encodable type a positive sequence with sum less than `ε` -/ def pos_sum_of_encodable {ε : ℝ} (hε : 0 < ε) (ι) [encodable ι] : {ε' : ι → ℝ // (∀ i, 0 < ε' i) ∧ ∃ c, has_sum ε' c ∧ c ≤ ε} := begin let f := λ n, (ε / 2) / 2 ^ n, have hf : has_sum f ε := has_sum_geometric_two' _, have f0 : ∀ n, 0 < f n := λ n, div_pos (half_pos hε) (pow_pos two_pos _), refine ⟨f ∘ encodable.encode, λ i, f0 _, _⟩, rcases summable_comp_of_summable_of_injective f (summable_spec hf) (@encodable.encode_injective ι _) with ⟨c, hg⟩, refine ⟨c, hg, has_sum_le_inj _ (@encodable.encode_injective ι _) _ _ hg hf⟩, { assume i _, exact le_of_lt (f0 _) }, { assume n, exact le_refl _ } end section edist_le_geometric variables [emetric_space α] (r C : ennreal) (hr : r < 1) (hC : C ≠ ⊤) {f : ℕ → α} (hu : ∀n, edist (f n) (f (n+1)) ≤ C * r^n) include hr hC hu /-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, `C ≠ ∞`, `r < 1`, then `f` is a Cauchy sequence.-/ lemma cauchy_seq_of_edist_le_geometric : cauchy_seq f := begin refine cauchy_seq_of_edist_le_of_tsum_ne_top _ hu _, rw [ennreal.mul_tsum, ennreal.tsum_geometric], refine ennreal.mul_ne_top hC (ennreal.inv_ne_top.2 _), exact ne_of_gt (ennreal.zero_lt_sub_iff_lt.2 hr) end omit hr hC /-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, then the distance from `f n` to the limit of `f` is bounded above by `C * r^n / (1 - r)`. -/ lemma edist_le_of_edist_le_geometric_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : edist (f n) a ≤ (C * r^n) / (1 - r) := begin convert edist_le_tsum_of_edist_le_of_tendsto _ hu ha _, simp only [pow_add, ennreal.mul_tsum, ennreal.tsum_geometric, ennreal.div_def, mul_assoc] end /-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, then the distance from `f 0` to the limit of `f` is bounded above by `C / (1 - r)`. -/ lemma edist_le_of_edist_le_geometric_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) : edist (f 0) a ≤ C / (1 - r) := by simpa only [pow_zero, mul_one] using edist_le_of_edist_le_geometric_of_tendsto r C hu ha 0 end edist_le_geometric section edist_le_geometric_two variables [emetric_space α] (C : ennreal) (hC : C ≠ ⊤) {f : ℕ → α} (hu : ∀n, edist (f n) (f (n+1)) ≤ C / 2^n) {a : α} (ha : tendsto f at_top (𝓝 a)) include hC hu /-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then `f` is a Cauchy sequence.-/ lemma cauchy_seq_of_edist_le_geometric_two : cauchy_seq f := begin simp only [ennreal.div_def, ennreal.inv_pow'] at hu, refine cauchy_seq_of_edist_le_geometric 2⁻¹ C _ hC hu, simp [ennreal.one_lt_two] end omit hC include ha /-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then the distance from `f n` to the limit of `f` is bounded above by `2 * C * 2^-n`. -/ lemma edist_le_of_edist_le_geometric_two_of_tendsto (n : ℕ) : edist (f n) a ≤ 2 * C / 2^n := begin simp only [ennreal.div_def, ennreal.inv_pow'] at hu, rw [ennreal.div_def, mul_assoc, mul_comm, ennreal.inv_pow'], convert edist_le_of_edist_le_geometric_of_tendsto 2⁻¹ C hu ha n, rw [ennreal.one_sub_inv_two, ennreal.inv_inv] end /-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then the distance from `f 0` to the limit of `f` is bounded above by `2 * C`. -/ lemma edist_le_of_edist_le_geometric_two_of_tendsto₀: edist (f 0) a ≤ 2 * C := by simpa only [pow_zero, ennreal.div_def, ennreal.inv_one, mul_one] using edist_le_of_edist_le_geometric_two_of_tendsto C hu ha 0 end edist_le_geometric_two section le_geometric variables [metric_space α] {r C : ℝ} (hr : r < 1) {f : ℕ → α} (hu : ∀n, dist (f n) (f (n+1)) ≤ C * r^n) include hr hu lemma aux_has_sum_of_le_geometric : has_sum (λ n : ℕ, C * r^n) (C / (1 - r)) := begin have h0 : 0 ≤ C, by simpa using le_trans dist_nonneg (hu 0), rcases eq_or_lt_of_le h0 with rfl | Cpos, { simp [has_sum_zero] }, { have rnonneg: r ≥ 0, from nonneg_of_mul_nonneg_left (by simpa only [pow_one] using le_trans dist_nonneg (hu 1)) Cpos, refine has_sum_mul_left C _, by simpa using has_sum_geometric rnonneg hr } end variables (r C) /-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then `f` is a Cauchy sequence. Note that this lemma does not assume `0 ≤ C` or `0 ≤ r`. -/ lemma cauchy_seq_of_le_geometric : cauchy_seq f := cauchy_seq_of_dist_le_of_summable _ hu ⟨_, aux_has_sum_of_le_geometric hr hu⟩ /-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then the distance from `f n` to the limit of `f` is bounded above by `C * r^n / (1 - r)`. -/ lemma dist_le_of_le_geometric_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≤ C / (1 - r) := (tsum_eq_has_sum $ aux_has_sum_of_le_geometric hr hu) ▸ dist_le_tsum_of_dist_le_of_tendsto₀ _ hu ⟨_, aux_has_sum_of_le_geometric hr hu⟩ ha /-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then the distance from `f 0` to the limit of `f` is bounded above by `C / (1 - r)`. -/ lemma dist_le_of_le_geometric_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : dist (f n) a ≤ (C * r^n) / (1 - r) := begin have := aux_has_sum_of_le_geometric hr hu, convert dist_le_tsum_of_dist_le_of_tendsto _ hu ⟨_, this⟩ ha n, simp only [pow_add, mul_left_comm C, mul_div_right_comm], rw [mul_comm], exact (eq.symm $ tsum_eq_has_sum $ has_sum_mul_left _ this) end omit hr hu variable (hu₂ : ∀ n, dist (f n) (f (n+1)) ≤ (C / 2) / 2^n) /-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then `f` is a Cauchy sequence. -/ lemma cauchy_seq_of_le_geometric_two : cauchy_seq f := cauchy_seq_of_dist_le_of_summable _ hu₂ $ ⟨_, has_sum_geometric_two' C⟩ /-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then the distance from `f 0` to the limit of `f` is bounded above by `C`. -/ lemma dist_le_of_le_geometric_two_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≤ C := (tsum_geometric_two' C) ▸ dist_le_tsum_of_dist_le_of_tendsto₀ _ hu₂ (summable_geometric_two' C) ha include hu₂ /-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then the distance from `f n` to the limit of `f` is bounded above by `C / 2^n`. -/ lemma dist_le_of_le_geometric_two_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : dist (f n) a ≤ C / 2^n := begin convert dist_le_tsum_of_dist_le_of_tendsto _ hu₂ (summable_geometric_two' C) ha n, simp only [add_comm n, pow_add, (div_div_eq_div_mul _ _ _).symm], symmetry, exact tsum_eq_has_sum (has_sum_mul_right _ $ has_sum_geometric_two' C) end end le_geometric namespace nnreal theorem exists_pos_sum_of_encodable {ε : nnreal} (hε : 0 < ε) (ι) [encodable ι] : ∃ ε' : ι → nnreal, (∀ i, 0 < ε' i) ∧ ∃c, has_sum ε' c ∧ c < ε := let ⟨a, a0, aε⟩ := dense hε in let ⟨ε', hε', c, hc, hcε⟩ := pos_sum_of_encodable a0 ι in ⟨ λi, ⟨ε' i, le_of_lt $ hε' i⟩, assume i, nnreal.coe_lt.2 $ hε' i, ⟨c, has_sum_le (assume i, le_of_lt $ hε' i) has_sum_zero hc ⟩, nnreal.has_sum_coe.1 hc, lt_of_le_of_lt (nnreal.coe_le.1 hcε) aε ⟩ end nnreal namespace ennreal theorem exists_pos_sum_of_encodable {ε : ennreal} (hε : 0 < ε) (ι) [encodable ι] : ∃ ε' : ι → nnreal, (∀ i, 0 < ε' i) ∧ (∑ i, (ε' i : ennreal)) < ε := begin rcases dense hε with ⟨r, h0r, hrε⟩, rcases lt_iff_exists_coe.1 hrε with ⟨x, rfl, hx⟩, rcases nnreal.exists_pos_sum_of_encodable (coe_lt_coe.1 h0r) ι with ⟨ε', hp, c, hc, hcr⟩, exact ⟨ε', hp, (ennreal.tsum_coe_eq hc).symm ▸ lt_trans (coe_lt_coe.2 hcr) hrε⟩ end end ennreal
d8492c6b75538defc547cd65bd029242704198c3
82e44445c70db0f03e30d7be725775f122d72f3e
/src/combinatorics/hall.lean
64fee1867fc37d8a104b3f1094ad672b774a9d13
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
14,809
lean
/- Copyright (c) 2021 Alena Gusakov, Bhavik Mehta, Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alena Gusakov, Bhavik Mehta, Kyle Miller -/ import data.fintype.basic import data.rel import data.set.finite /-! # Hall's Marriage Theorem Given a list of finite subsets $X_1,X_2,\dots,X_n$ of some given set $S$, Hall in [Hall1935] gave a necessary and sufficient condition for there to be a list of distinct elements $x_1,x_2,\dots,x_n$ with $x_i\in X_i$ for each $i$: it is when for each $k$, the union of every $k$ of these subsets has at least $k$ elements. This file proves this for an indexed family `t : ι → finset α` of finite sets, with `[fintype ι]`, along with some variants of the statement. The list of distinct representatives is given by an injective function `f : ι → α` such that `∀ i, f i ∈ t i`. A description of this formalization is in [Gusakov2021]. ## Main statements * `finset.all_card_le_bUnion_card_iff_exists_injective` is in terms of `t : ι → finset α`. * `fintype.all_card_le_rel_image_card_iff_exists_injective` is in terms of a relation `r : α → β → Prop` such that `rel.image r {a}` is a finite set for all `a : α`. * `fintype.all_card_le_filter_rel_iff_exists_injective` is in terms of a relation `r : α → β → Prop` on finite types, with the Hall condition given in terms of `finset.univ.filter`. ## Todo * The theorem is still true even if `ι` is not a finite type. The infinite case follows from a compactness argument. * The statement of the theorem in terms of bipartite graphs is in preparation. ## Tags Hall's Marriage Theorem, indexed families -/ open finset universes u v namespace hall_marriage_theorem variables {ι : Type u} {α : Type v} [fintype ι] theorem hall_hard_inductive_zero (t : ι → finset α) (hn : fintype.card ι = 0) : ∃ (f : ι → α), function.injective f ∧ ∀ x, f x ∈ t x := begin rw fintype.card_eq_zero_iff at hn, exactI ⟨is_empty_elim, is_empty_elim, is_empty_elim⟩, end variables {t : ι → finset α} [decidable_eq α] lemma hall_cond_of_erase {x : ι} (a : α) (ha : ∀ (s : finset ι), s.nonempty → s ≠ univ → s.card < (s.bUnion t).card) (s' : finset {x' : ι | x' ≠ x}) : s'.card ≤ (s'.bUnion (λ x', (t x').erase a)).card := begin haveI := classical.dec_eq ι, specialize ha (s'.image coe), rw [nonempty.image_iff, finset.card_image_of_injective s' subtype.coe_injective] at ha, by_cases he : s'.nonempty, { have ha' : s'.card < (s'.bUnion (λ x, t x)).card, { specialize ha he (λ h, by { have h' := mem_univ x, rw ←h at h', simpa using h' }), convert ha using 2, ext x, simp only [mem_image, mem_bUnion, exists_prop, set_coe.exists, exists_and_distrib_right, exists_eq_right, subtype.coe_mk], }, rw ←erase_bUnion, by_cases hb : a ∈ s'.bUnion (λ x, t x), { rw card_erase_of_mem hb, exact nat.le_pred_of_lt ha' }, { rw erase_eq_of_not_mem hb, exact nat.le_of_lt ha' }, }, { rw [nonempty_iff_ne_empty, not_not] at he, subst s', simp }, end /-- First case of the inductive step: assuming that `∀ (s : finset ι), s.nonempty → s ≠ univ → s.card < (s.bUnion t).card` and that the statement of **Hall's Marriage Theorem** is true for all `ι'` of cardinality ≤ `n`, then it is true for `ι` of cardinality `n + 1`. -/ lemma hall_hard_inductive_step_A {n : ℕ} (hn : fintype.card ι = n + 1) (ht : ∀ (s : finset ι), s.card ≤ (s.bUnion t).card) (ih : ∀ {ι' : Type u} [fintype ι'] (t' : ι' → finset α), by exactI fintype.card ι' ≤ n → (∀ (s' : finset ι'), s'.card ≤ (s'.bUnion t').card) → ∃ (f : ι' → α), function.injective f ∧ ∀ x, f x ∈ t' x) (ha : ∀ (s : finset ι), s.nonempty → s ≠ univ → s.card < (s.bUnion t).card) : ∃ (f : ι → α), function.injective f ∧ ∀ x, f x ∈ t x := begin haveI : nonempty ι := fintype.card_pos_iff.mp (hn.symm ▸ nat.succ_pos _), haveI := classical.dec_eq ι, /- Choose an arbitrary element `x : ι` and `y : t x`. -/ let x := classical.arbitrary ι, have tx_ne : (t x).nonempty, { rw ←finset.card_pos, apply nat.lt_of_lt_of_le nat.one_pos, convert ht {x}, rw finset.singleton_bUnion, }, rcases classical.indefinite_description _ tx_ne with ⟨y, hy⟩, /- Restrict to everything except `x` and `y`. -/ let ι' := {x' : ι | x' ≠ x}, let t' : ι' → finset α := λ x', (t x').erase y, have card_ι' : fintype.card ι' = n, { convert congr_arg (λ m, m - 1) hn, convert set.card_ne_eq _, }, rcases ih t' card_ι'.le (hall_cond_of_erase y ha) with ⟨f', hfinj, hfr⟩, /- Extend the resulting function. -/ refine ⟨λ z, if h : z = x then y else f' ⟨z, h⟩, _, _⟩, { rintro z₁ z₂, have key : ∀ {x}, y ≠ f' x, { intros x h, specialize hfr x, rw ←h at hfr, simpa using hfr, }, by_cases h₁ : z₁ = x; by_cases h₂ : z₂ = x; simp [h₁, h₂, hfinj.eq_iff, key, key.symm], }, { intro z, split_ifs with hz, { rwa hz }, { specialize hfr ⟨z, hz⟩, rw mem_erase at hfr, exact hfr.2, }, }, end lemma hall_cond_of_restrict {ι : Type u} {t : ι → finset α} {s : finset ι} (ht : ∀ (s : finset ι), s.card ≤ (s.bUnion t).card) (s' : finset (s : set ι)) : s'.card ≤ (s'.bUnion (λ a', t a')).card := begin haveI := classical.dec_eq ι, convert ht (s'.image coe) using 1, { rw card_image_of_injective _ subtype.coe_injective, }, { apply congr_arg, ext y, simp, }, end lemma hall_cond_of_compl {ι : Type u} {t : ι → finset α} {s : finset ι} (hus : s.card = (s.bUnion t).card) (ht : ∀ (s : finset ι), s.card ≤ (s.bUnion t).card) (s' : finset (sᶜ : set ι)) : s'.card ≤ (s'.bUnion (λ x', t x' \ s.bUnion t)).card := begin haveI := classical.dec_eq ι, have : s'.card = (s ∪ s'.image coe).card - s.card, { rw [card_disjoint_union, nat.add_sub_cancel_left, card_image_of_injective _ subtype.coe_injective], simp only [disjoint_left, not_exists, mem_image, exists_prop, set_coe.exists, exists_and_distrib_right, exists_eq_right, subtype.coe_mk], intros x hx hc h, exact (hc hx).elim }, rw [this, hus], apply (nat.sub_le_sub_right (ht _) _).trans _, rw ← card_sdiff, { have : (s ∪ s'.image subtype.val).bUnion t \ s.bUnion t ⊆ s'.bUnion (λ x', t x' \ s.bUnion t), { intros t, simp only [mem_bUnion, mem_sdiff, not_exists, mem_image, and_imp, mem_union, exists_and_distrib_right, exists_imp_distrib], rintro x (hx | ⟨x', hx', rfl⟩) rat hs, { exact (hs x hx rat).elim }, { exact ⟨⟨x', hx', rat⟩, hs⟩, } }, exact (card_le_of_subset this).trans le_rfl, }, { apply bUnion_subset_bUnion_of_subset_left, apply subset_union_left } end /-- Second case of the inductive step: assuming that `∃ (s : finset ι), s ≠ univ → s.card = (s.bUnion t).card` and that the statement of Hall's Marriage Theorem is true for all `ι'` of cardinality ≤ `n`, then it is true for `ι` of cardinality `n + 1`. -/ lemma hall_hard_inductive_step_B {n : ℕ} (hn : fintype.card ι = n + 1) (ht : ∀ (s : finset ι), s.card ≤ (s.bUnion t).card) (ih : ∀ {ι' : Type u} [fintype ι'] (t' : ι' → finset α), by exactI fintype.card ι' ≤ n → (∀ (s' : finset ι'), s'.card ≤ (s'.bUnion t').card) → ∃ (f : ι' → α), function.injective f ∧ ∀ x, f x ∈ t' x) (s : finset ι) (hs : s.nonempty) (hns : s ≠ univ) (hus : s.card = (s.bUnion t).card) : ∃ (f : ι → α), function.injective f ∧ ∀ x, f x ∈ t x := begin haveI := classical.dec_eq ι, /- Restrict to `s` -/ let t' : s → finset α := λ x', t x', rw nat.add_one at hn, have card_ι'_le : fintype.card s ≤ n, { apply nat.le_of_lt_succ, rw ←hn, convert (card_lt_iff_ne_univ _).mpr hns, convert fintype.card_coe _ }, rcases ih t' card_ι'_le (hall_cond_of_restrict ht) with ⟨f', hf', hsf'⟩, /- Restrict to `sᶜ` in the domain and `(s.bUnion t)ᶜ` in the codomain. -/ set ι'' := (s : set ι)ᶜ with ι''_def, let t'' : ι'' → finset α := λ a'', t a'' \ s.bUnion t, have card_ι''_le : fintype.card ι'' ≤ n, { apply nat.le_of_lt_succ, rw ←hn, convert (card_compl_lt_iff_nonempty _).mpr hs, convert fintype.card_coe (sᶜ), exact (finset.coe_compl s).symm }, rcases ih t'' card_ι''_le (hall_cond_of_compl hus ht) with ⟨f'', hf'', hsf''⟩, /- Put them together -/ have f'_mem_bUnion : ∀ {x'} (hx' : x' ∈ s), f' ⟨x', hx'⟩ ∈ s.bUnion t, { intros x' hx', rw mem_bUnion, exact ⟨x', hx', hsf' _⟩, }, have f''_not_mem_bUnion : ∀ {x''} (hx'' : ¬ x'' ∈ s), ¬ f'' ⟨x'', hx''⟩ ∈ s.bUnion t, { intros x'' hx'', have h := hsf'' ⟨x'', hx''⟩, rw mem_sdiff at h, exact h.2, }, have im_disj : ∀ {x' x'' : ι} {hx' : x' ∈ s} {hx'' : ¬x'' ∈ s}, f' ⟨x', hx'⟩ ≠ f'' ⟨x'', hx''⟩, { intros _ _ hx' hx'' h, apply f''_not_mem_bUnion hx'', rw ←h, apply f'_mem_bUnion, }, refine ⟨λ x, if h : x ∈ s then f' ⟨x, h⟩ else f'' ⟨x, h⟩, _, _⟩, { exact hf'.dite _ hf'' @im_disj }, { intro x, split_ifs, { exact hsf' ⟨x, h⟩ }, { exact sdiff_subset _ _ (hsf'' ⟨x, h⟩) } } end /-- If `ι` has cardinality `n + 1` and the statement of Hall's Marriage Theorem is true for all `ι'` of cardinality ≤ `n`, then it is true for `ι`. -/ theorem hall_hard_inductive_step {n : ℕ} (hn : fintype.card ι = n + 1) (ht : ∀ (s : finset ι), s.card ≤ (s.bUnion t).card) (ih : ∀ {ι' : Type u} [fintype ι'] (t' : ι' → finset α), by exactI fintype.card ι' ≤ n → (∀ (s' : finset ι'), s'.card ≤ (s'.bUnion t').card) → ∃ (f : ι' → α), function.injective f ∧ ∀ x, f x ∈ t' x) : ∃ (f : ι → α), function.injective f ∧ ∀ x, f x ∈ t x := begin by_cases h : ∀ (s : finset ι), s.nonempty → s ≠ univ → s.card < (s.bUnion t).card, { exact hall_hard_inductive_step_A hn ht @ih h, }, { push_neg at h, rcases h with ⟨s, sne, snu, sle⟩, have seq := nat.le_antisymm (ht _) sle, exact hall_hard_inductive_step_B hn ht @ih s sne snu seq, }, end /-- Here we combine the base case and the inductive step into a full strong induction proof, thus completing the proof of the second direction. -/ theorem hall_hard_inductive {n : ℕ} (hn : fintype.card ι = n) (ht : ∀ (s : finset ι), s.card ≤ (s.bUnion t).card) : ∃ (f : ι → α), function.injective f ∧ ∀ x, f x ∈ t x := begin tactic.unfreeze_local_instances, revert ι, refine nat.strong_induction_on n (λ n' ih, _), intros _ _ t hn ht, rcases n' with (_|_), { exact hall_hard_inductive_zero t hn }, { apply hall_hard_inductive_step hn ht, introsI ι' _ _ hι', exact ih (fintype.card ι') (nat.lt_succ_of_le hι') rfl, }, end end hall_marriage_theorem /-- This the version of **Hall's Marriage Theorem** in terms of indexed families of finite sets `t : ι → finset α`. It states that there is a set of distinct representatives if and only if every union of `k` of the sets has at least `k` elements. Recall that `s.bUnion t` is the union of all the sets `t i` for `i ∈ s`. -/ theorem finset.all_card_le_bUnion_card_iff_exists_injective {ι α : Type*} [fintype ι] [decidable_eq α] (t : ι → finset α) : (∀ (s : finset ι), s.card ≤ (s.bUnion t).card) ↔ (∃ (f : ι → α), function.injective f ∧ ∀ x, f x ∈ t x) := begin split, { exact hall_marriage_theorem.hall_hard_inductive rfl }, { rintro ⟨f, hf₁, hf₂⟩ s, rw ←card_image_of_injective s hf₁, apply card_le_of_subset, intro _, rw [mem_image, mem_bUnion], rintros ⟨x, hx, rfl⟩, exact ⟨x, hx, hf₂ x⟩, }, end /-- Given a relation such that the image of every singleton set is finite, then the image of every finite set is finite. -/ instance {α β : Type*} [decidable_eq β] (r : α → β → Prop) [∀ (a : α), fintype (rel.image r {a})] (A : finset α) : fintype (rel.image r A) := begin have h : rel.image r A = (A.bUnion (λ a, (rel.image r {a}).to_finset) : set β), { ext, simp [rel.image], }, rw [h], apply finset_coe.fintype, end /-- This is a version of **Hall's Marriage Theorem** in terms of a relation between types `α` and `β` such that `α` is finite and the image of each `x : α` is finite (it suffices for `β` to be finite). There is an injective function `α → β` respecting the relation iff every subset of `k` terms of `α` is related to at least `k` terms of `β`. If `[fintype β]`, then `[∀ (a : α), fintype (rel.image r {a})]` is automatically implied. -/ theorem fintype.all_card_le_rel_image_card_iff_exists_injective {α β : Type*} [fintype α] [decidable_eq β] (r : α → β → Prop) [∀ (a : α), fintype (rel.image r {a})] : (∀ (A : finset α), A.card ≤ fintype.card (rel.image r A)) ↔ (∃ (f : α → β), function.injective f ∧ ∀ x, r x (f x)) := begin let r' := λ a, (rel.image r {a}).to_finset, have h : ∀ (A : finset α), fintype.card (rel.image r A) = (A.bUnion r').card, { intro A, rw ←set.to_finset_card, apply congr_arg, ext b, simp [rel.image], }, have h' : ∀ (f : α → β) x, r x (f x) ↔ f x ∈ r' x, { simp [rel.image], }, simp only [h, h'], apply finset.all_card_le_bUnion_card_iff_exists_injective, end /-- This is a version of **Hall's Marriage Theorem** in terms of a relation between finite types. There is an injective function `α → β` respecting the relation iff every subset of `k` terms of `α` is related to at least `k` terms of `β`. It is like `fintype.all_card_le_rel_image_card_iff_exists_injective` but uses `finset.filter` rather than `rel.image`. -/ theorem fintype.all_card_le_filter_rel_iff_exists_injective {α β : Type*} [fintype α] [fintype β] (r : α → β → Prop) [∀ a, decidable_pred (r a)] : (∀ (A : finset α), A.card ≤ (univ.filter (λ (b : β), ∃ a ∈ A, r a b)).card) ↔ (∃ (f : α → β), function.injective f ∧ ∀ x, r x (f x)) := begin haveI := classical.dec_eq β, let r' := λ a, univ.filter (λ b, r a b), have h : ∀ (A : finset α), (univ.filter (λ (b : β), ∃ a ∈ A, r a b)) = (A.bUnion r'), { intro A, ext b, simp, }, have h' : ∀ (f : α → β) x, r x (f x) ↔ f x ∈ r' x, { simp, }, simp_rw [h, h'], apply finset.all_card_le_bUnion_card_iff_exists_injective, end
3f1e807fbb07ae60d04d583539286b9b287a31fa
4727251e0cd73359b15b664c3170e5d754078599
/src/field_theory/fixed.lean
af1fd0a57bfad1ee854b4d3fa2ae05d1f3e568c7
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
14,416
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.polynomial.group_ring_action import field_theory.normal import field_theory.separable import field_theory.tower /-! # Fixed field under a group action. This is the basis of the Fundamental Theorem of Galois Theory. Given a (finite) group `G` that acts on a field `F`, we define `fixed_points G F`, the subfield consisting of elements of `F` fixed_points by every element of `G`. This subfield is then normal and separable, and in addition (TODO) if `G` acts faithfully on `F` then `finrank (fixed_points G F) F = fintype.card G`. ## Main Definitions - `fixed_points G F`, the subfield consisting of elements of `F` fixed_points by every element of `G`, where `G` is a group that acts on `F`. -/ noncomputable theory open_locale classical big_operators open mul_action finset finite_dimensional universes u v w variables {M : Type u} [monoid M] variables (G : Type u) [group G] variables (F : Type v) [field F] [mul_semiring_action M F] [mul_semiring_action G F] (m : M) /-- The subfield of F fixed by the field endomorphism `m`. -/ def fixed_by.subfield : subfield F := { carrier := fixed_by M F m, zero_mem' := smul_zero m, add_mem' := λ x y hx hy, (smul_add m x y).trans $ congr_arg2 _ hx hy, neg_mem' := λ x hx, (smul_neg m x).trans $ congr_arg _ hx, one_mem' := smul_one m, mul_mem' := λ x y hx hy, (smul_mul' m x y).trans $ congr_arg2 _ hx hy, inv_mem' := λ x hx, (smul_inv'' m x).trans $ congr_arg _ hx } section invariant_subfields variables (M) {F} /-- A typeclass for subrings invariant under a `mul_semiring_action`. -/ class is_invariant_subfield (S : subfield F) : Prop := (smul_mem : ∀ (m : M) {x : F}, x ∈ S → m • x ∈ S) variable (S : subfield F) instance is_invariant_subfield.to_mul_semiring_action [is_invariant_subfield M S] : mul_semiring_action M S := { smul := λ m x, ⟨m • x, is_invariant_subfield.smul_mem m x.2⟩, one_smul := λ s, subtype.eq $ one_smul M s, mul_smul := λ m₁ m₂ s, subtype.eq $ mul_smul m₁ m₂ s, smul_add := λ m s₁ s₂, subtype.eq $ smul_add m s₁ s₂, smul_zero := λ m, subtype.eq $ smul_zero m, smul_one := λ m, subtype.eq $ smul_one m, smul_mul := λ m s₁ s₂, subtype.eq $ smul_mul' m s₁ s₂ } instance [is_invariant_subfield M S] : is_invariant_subring M (S.to_subring) := { smul_mem := is_invariant_subfield.smul_mem } end invariant_subfields namespace fixed_points variable (M) -- we use `subfield.copy` so that the underlying set is `fixed_points M F` /-- The subfield of fixed points by a monoid action. -/ def subfield : subfield F := subfield.copy (⨅ (m : M), fixed_by.subfield F m) (fixed_points M F) (by { ext z, simp [fixed_points, fixed_by.subfield, infi, subfield.mem_Inf] }) instance : is_invariant_subfield M (fixed_points.subfield M F) := { smul_mem := λ g x hx g', by rw [hx, hx] } instance : smul_comm_class M (fixed_points.subfield M F) F := { smul_comm := λ m f f', show m • (↑f * f') = f * (m • f'), by rw [smul_mul', f.prop m] } instance smul_comm_class' : smul_comm_class (fixed_points.subfield M F) M F := smul_comm_class.symm _ _ _ @[simp] theorem smul (m : M) (x : fixed_points.subfield M F) : m • x = x := subtype.eq $ x.2 m -- Why is this so slow? @[simp] theorem smul_polynomial (m : M) (p : polynomial (fixed_points.subfield M F)) : m • p = p := polynomial.induction_on p (λ x, by rw [polynomial.smul_C, smul]) (λ p q ihp ihq, by rw [smul_add, ihp, ihq]) (λ n x ih, by rw [smul_mul', polynomial.smul_C, smul, smul_pow', polynomial.smul_X]) instance : algebra (fixed_points.subfield M F) F := by apply_instance theorem coe_algebra_map : algebra_map (fixed_points.subfield M F) F = subfield.subtype (fixed_points.subfield M F) := rfl lemma linear_independent_smul_of_linear_independent {s : finset F} : linear_independent (fixed_points.subfield G F) (λ i : (s : set F), (i : F)) → linear_independent F (λ i : (s : set F), mul_action.to_fun G F i) := begin haveI : is_empty ((∅ : finset F) : set F) := ⟨subtype.prop⟩, refine finset.induction_on s (λ _, linear_independent_empty_type) (λ a s has ih hs, _), rw coe_insert at hs ⊢, rw linear_independent_insert (mt mem_coe.1 has) at hs, rw linear_independent_insert' (mt mem_coe.1 has), refine ⟨ih hs.1, λ ha, _⟩, rw finsupp.mem_span_image_iff_total at ha, rcases ha with ⟨l, hl, hla⟩, rw [finsupp.total_apply_of_mem_supported F hl] at hla, suffices : ∀ i ∈ s, l i ∈ fixed_points.subfield G F, { replace hla := (sum_apply _ _ (λ i, l i • to_fun G F i)).symm.trans (congr_fun hla 1), simp_rw [pi.smul_apply, to_fun_apply, one_smul] at hla, refine hs.2 (hla ▸ submodule.sum_mem _ (λ c hcs, _)), change (⟨l c, this c hcs⟩ : fixed_points.subfield G F) • c ∈ _, exact submodule.smul_mem _ _ (submodule.subset_span $ mem_coe.2 hcs) }, intros i his g, refine eq_of_sub_eq_zero (linear_independent_iff'.1 (ih hs.1) s.attach (λ i, g • l i - l i) _ ⟨i, his⟩ (mem_attach _ _) : _), refine (@sum_attach _ _ s _ (λ i, (g • l i - l i) • mul_action.to_fun G F i)).trans _, ext g', dsimp only, conv_lhs { rw sum_apply, congr, skip, funext, rw [pi.smul_apply, sub_smul, smul_eq_mul] }, rw [sum_sub_distrib, pi.zero_apply, sub_eq_zero], conv_lhs { congr, skip, funext, rw [to_fun_apply, ← mul_inv_cancel_left g g', mul_smul, ← smul_mul', ← to_fun_apply _ x] }, show ∑ x in s, g • (λ y, l y • mul_action.to_fun G F y) x (g⁻¹ * g') = ∑ x in s, (λ y, l y • mul_action.to_fun G F y) x g', rw [← smul_sum, ← sum_apply _ _ (λ y, l y • to_fun G F y), ← sum_apply _ _ (λ y, l y • to_fun G F y)], dsimp only, rw [hla, to_fun_apply, to_fun_apply, smul_smul, mul_inv_cancel_left] end variables [fintype G] (x : F) /-- `minpoly G F x` is the minimal polynomial of `(x : F)` over `fixed_points G F`. -/ def minpoly : polynomial (fixed_points.subfield G F) := (prod_X_sub_smul G F x).to_subring (fixed_points.subfield G F).to_subring $ λ c hc g, let ⟨n, hc0, hn⟩ := polynomial.mem_frange_iff.1 hc in hn.symm ▸ prod_X_sub_smul.coeff G F x g n namespace minpoly theorem monic : (minpoly G F x).monic := by { simp only [minpoly, polynomial.monic_to_subring], exact prod_X_sub_smul.monic G F x } theorem eval₂ : polynomial.eval₂ (subring.subtype $ (fixed_points.subfield G F).to_subring) x (minpoly G F x) = 0 := begin rw [← prod_X_sub_smul.eval G F x, polynomial.eval₂_eq_eval_map], simp only [minpoly, polynomial.map_to_subring], end theorem eval₂' : polynomial.eval₂ (subfield.subtype $ (fixed_points.subfield G F)) x (minpoly G F x) = 0 := eval₂ G F x theorem ne_one : minpoly G F x ≠ (1 : polynomial (fixed_points.subfield G F)) := λ H, have _ := eval₂ G F x, (one_ne_zero : (1 : F) ≠ 0) $ by rwa [H, polynomial.eval₂_one] at this theorem of_eval₂ (f : polynomial (fixed_points.subfield G F)) (hf : polynomial.eval₂ (subfield.subtype $ fixed_points.subfield G F) x f = 0) : minpoly G F x ∣ f := begin erw [← polynomial.map_dvd_map' (subfield.subtype $ fixed_points.subfield G F), minpoly, polynomial.map_to_subring _ (subfield G F).to_subring, prod_X_sub_smul], refine fintype.prod_dvd_of_coprime (polynomial.pairwise_coprime_X_sub $ mul_action.injective_of_quotient_stabilizer G x) (λ y, quotient_group.induction_on y $ λ g, _), rw [polynomial.dvd_iff_is_root, polynomial.is_root.def, mul_action.of_quotient_stabilizer_mk, polynomial.eval_smul', ← subfield.to_subring.subtype_eq_subtype, ← is_invariant_subring.coe_subtype_hom' G (fixed_points.subfield G F).to_subring, ← mul_semiring_action_hom.coe_polynomial, ← mul_semiring_action_hom.map_smul, smul_polynomial, mul_semiring_action_hom.coe_polynomial, is_invariant_subring.coe_subtype_hom', polynomial.eval_map, subfield.to_subring.subtype_eq_subtype, hf, smul_zero] end /- Why is this so slow? -/ theorem irreducible_aux (f g : polynomial (fixed_points.subfield G F)) (hf : f.monic) (hg : g.monic) (hfg : f * g = minpoly G F x) : f = 1 ∨ g = 1 := begin have hf2 : f ∣ minpoly G F x, { rw ← hfg, exact dvd_mul_right _ _ }, have hg2 : g ∣ minpoly G F x, { rw ← hfg, exact dvd_mul_left _ _ }, have := eval₂ G F x, rw [← hfg, polynomial.eval₂_mul, mul_eq_zero] at this, cases this, { right, have hf3 : f = minpoly G F x, { exact polynomial.eq_of_monic_of_associated hf (monic G F x) (associated_of_dvd_dvd hf2 $ @of_eval₂ G _ F _ _ _ x f this) }, rwa [← mul_one (minpoly G F x), hf3, mul_right_inj' (monic G F x).ne_zero] at hfg }, { left, have hg3 : g = minpoly G F x, { exact polynomial.eq_of_monic_of_associated hg (monic G F x) (associated_of_dvd_dvd hg2 $ @of_eval₂ G _ F _ _ _ x g this) }, rwa [← one_mul (minpoly G F x), hg3, mul_left_inj' (monic G F x).ne_zero] at hfg } end theorem irreducible : irreducible (minpoly G F x) := (polynomial.irreducible_of_monic (monic G F x) (ne_one G F x)).2 (irreducible_aux G F x) end minpoly theorem is_integral : is_integral (fixed_points.subfield G F) x := ⟨minpoly G F x, minpoly.monic G F x, minpoly.eval₂ G F x⟩ theorem minpoly_eq_minpoly : minpoly G F x = _root_.minpoly (fixed_points.subfield G F) x := minpoly.eq_of_irreducible_of_monic (minpoly.irreducible G F x) (minpoly.eval₂ G F x) (minpoly.monic G F x) instance normal : normal (fixed_points.subfield G F) F := ⟨λ x, is_integral G F x, λ x, (polynomial.splits_id_iff_splits _).1 $ by { rw [← minpoly_eq_minpoly, minpoly, coe_algebra_map, ← subfield.to_subring.subtype_eq_subtype, polynomial.map_to_subring _ (fixed_points.subfield G F).to_subring, prod_X_sub_smul], exact polynomial.splits_prod _ (λ _ _, polynomial.splits_X_sub_C _) }⟩ instance separable : is_separable (fixed_points.subfield G F) F := ⟨λ x, is_integral G F x, λ x, by { -- this was a plain rw when we were using unbundled subrings erw [← minpoly_eq_minpoly, ← polynomial.separable_map (fixed_points.subfield G F).subtype, minpoly, polynomial.map_to_subring _ ((subfield G F).to_subring) ], exact polynomial.separable_prod_X_sub_C_iff.2 (injective_of_quotient_stabilizer G x) }⟩ lemma dim_le_card : module.rank (fixed_points.subfield G F) F ≤ fintype.card G := dim_le $ λ s hs, by simpa only [dim_fun', cardinal.mk_finset, finset.coe_sort_coe, cardinal.lift_nat_cast, cardinal.nat_cast_le] using cardinal_lift_le_dim_of_linear_independent' (linear_independent_smul_of_linear_independent G F hs) instance : finite_dimensional (fixed_points.subfield G F) F := is_noetherian.iff_fg.1 $ is_noetherian.iff_dim_lt_omega.2 $ lt_of_le_of_lt (dim_le_card G F) (cardinal.nat_lt_omega _) lemma finrank_le_card : finrank (fixed_points.subfield G F) F ≤ fintype.card G := begin rw [← cardinal.nat_cast_le, finrank_eq_dim], apply dim_le_card, end end fixed_points lemma linear_independent_to_linear_map (R : Type u) (A : Type v) (B : Type w) [comm_semiring R] [ring A] [algebra R A] [comm_ring B] [is_domain B] [algebra R B] : linear_independent B (alg_hom.to_linear_map : (A →ₐ[R] B) → (A →ₗ[R] B)) := have linear_independent B (linear_map.lto_fun R A B ∘ alg_hom.to_linear_map), from ((linear_independent_monoid_hom A B).comp (coe : (A →ₐ[R] B) → (A →* B)) (λ f g hfg, alg_hom.ext $ monoid_hom.ext_iff.1 hfg) : _), this.of_comp _ lemma cardinal_mk_alg_hom (K : Type u) (V : Type v) (W : Type w) [field K] [field V] [algebra K V] [finite_dimensional K V] [field W] [algebra K W] [finite_dimensional K W] : cardinal.mk (V →ₐ[K] W) ≤ finrank W (V →ₗ[K] W) := cardinal_mk_le_finrank_of_linear_independent $ linear_independent_to_linear_map K V W noncomputable instance alg_hom.fintype (K : Type u) (V : Type v) (W : Type w) [field K] [field V] [algebra K V] [finite_dimensional K V] [field W] [algebra K W] [finite_dimensional K W] : fintype (V →ₐ[K] W) := classical.choice $ cardinal.lt_omega_iff_fintype.1 $ lt_of_le_of_lt (cardinal_mk_alg_hom K V W) (cardinal.nat_lt_omega _) noncomputable instance alg_equiv.fintype (K : Type u) (V : Type v) [field K] [field V] [algebra K V] [finite_dimensional K V] : fintype (V ≃ₐ[K] V) := fintype.of_equiv (V →ₐ[K] V) (alg_equiv_equiv_alg_hom K V).symm lemma finrank_alg_hom (K : Type u) (V : Type v) [field K] [field V] [algebra K V] [finite_dimensional K V] : fintype.card (V →ₐ[K] V) ≤ finrank V (V →ₗ[K] V) := fintype_card_le_finrank_of_linear_independent $ linear_independent_to_linear_map K V V namespace fixed_points theorem finrank_eq_card (G : Type u) (F : Type v) [group G] [field F] [fintype G] [mul_semiring_action G F] [has_faithful_scalar G F] : finrank (fixed_points.subfield G F) F = fintype.card G := le_antisymm (fixed_points.finrank_le_card G F) $ calc fintype.card G ≤ fintype.card (F →ₐ[fixed_points.subfield G F] F) : fintype.card_le_of_injective _ (mul_semiring_action.to_alg_hom_injective _ F) ... ≤ finrank F (F →ₗ[fixed_points.subfield G F] F) : finrank_alg_hom (fixed_points G F) F ... = finrank (fixed_points.subfield G F) F : finrank_linear_map' _ _ _ /-- `mul_semiring_action.to_alg_hom` is bijective. -/ theorem to_alg_hom_bijective (G : Type u) (F : Type v) [group G] [field F] [fintype G] [mul_semiring_action G F] [has_faithful_scalar G F] : function.bijective (mul_semiring_action.to_alg_hom _ _ : G → F →ₐ[subfield G F] F) := begin rw fintype.bijective_iff_injective_and_card, split, { exact mul_semiring_action.to_alg_hom_injective _ F }, { apply le_antisymm, { exact fintype.card_le_of_injective _ (mul_semiring_action.to_alg_hom_injective _ F) }, { rw ← finrank_eq_card G F, exact has_le.le.trans_eq (finrank_alg_hom _ F) (finrank_linear_map' _ _ _) } }, end /-- Bijection between G and algebra homomorphisms that fix the fixed points -/ def to_alg_hom_equiv (G : Type u) (F : Type v) [group G] [field F] [fintype G] [mul_semiring_action G F] [has_faithful_scalar G F] : G ≃ (F →ₐ[fixed_points.subfield G F] F) := equiv.of_bijective _ (to_alg_hom_bijective G F) end fixed_points
dcc55523fa95922196d802a0442cf5f44e30bfeb
6772a11d96d69b3f90d6eeaf7f9accddf2a7691d
/enriched_category.lean
e2ff7bdc6c9c9de5981403b89fc4208e7c05fb0b
[]
no_license
lbordowitz/lean-category-theory
5397361f0f81037d65762da48de2c16ec85a5e4b
8c59893e44af3804eba4dbc5f7fa5928ed2e0ae6
refs/heads/master
1,611,310,752,156
1,487,070,172,000
1,487,070,172,000
82,003,141
0
0
null
1,487,118,553,000
1,487,118,553,000
null
UTF-8
Lean
false
false
816
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan, Scott Morrison import .category import .functor import .natural_transformation import .products import .monoidal_category namespace tqft.categories.enriched open tqft.categories.monoidal_category structure EnrichedCategory := (V: MonoidalCategory) (Obj : Type ) (Hom : Obj -> Obj -> V^.Obj) (compose : Π ⦃X Y Z : Obj⦄, V^.Hom ((Hom X Y) ⊗ (Hom Y Z)) (Hom X Z)) -- TODO and so on -- TODO How would we define an additive category, now? We don't want to say: -- Hom : Obj -> Obj -> AdditiveGroup -- instead we want to express something like: -- Hom : Obj -> Obj -> [something coercible to AdditiveGroup] end tqft.categories.enriched
5b89501693f89aa94ba419b25d03464b8987e2a6
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/analysis/calculus/local_extr.lean
6a129d80e95120e1d165f3c2966c76afb1f1d6c3
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
16,938
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 topology.local_extr import analysis.calculus.deriv /-! # Local extrema of smooth functions ## Main definitions In a real normed space `E` we define `pos_tangent_cone_at (s : set E) (x : E)`. This would be the same as `tangent_cone_at ℝ≥0 s x` if we had a theory of normed semifields. This set is used in the proof of Fermat's Theorem (see below), and can be used to formalize [Lagrange multipliers](https://en.wikipedia.org/wiki/Lagrange_multiplier) and/or [Karush–Kuhn–Tucker conditions](https://en.wikipedia.org/wiki/Karush–Kuhn–Tucker_conditions). ## Main statements For each theorem name listed below, we also prove similar theorems for `min`, `extr` (if applicable)`, and `(f)deriv` instead of `has_fderiv`. * `is_local_max_on.has_fderiv_within_at_nonpos` : `f' y ≤ 0` whenever `a` is a local maximum of `f` on `s`, `f` has derivative `f'` at `a` within `s`, and `y` belongs to the positive tangent cone of `s` at `a`. * `is_local_max_on.has_fderiv_within_at_eq_zero` : In the settings of the previous theorem, if both `y` and `-y` belong to the positive tangent cone, then `f' y = 0`. * `is_local_max.has_fderiv_at_eq_zero` : [Fermat's Theorem](https://en.wikipedia.org/wiki/Fermat's_theorem_(stationary_points)), the derivative of a differentiable function at a local extremum point equals zero. * `exists_has_deriv_at_eq_zero` : [Rolle's Theorem](https://en.wikipedia.org/wiki/Rolle's_theorem): given a function `f` continuous on `[a, b]` and differentiable on `(a, b)`, there exists `c ∈ (a, b)` such that `f' c = 0`. ## Implementation notes For each mathematical fact we prove several versions of its formalization: * for maxima and minima; * using `has_fderiv*`/`has_deriv*` or `fderiv*`/`deriv*`. For the `fderiv*`/`deriv*` versions we omit the differentiability condition whenever it is possible due to the fact that `fderiv` and `deriv` are defined to be zero for non-differentiable functions. ## References * [Fermat's Theorem](https://en.wikipedia.org/wiki/Fermat's_theorem_(stationary_points)); * [Rolle's Theorem](https://en.wikipedia.org/wiki/Rolle's_theorem); * [Tangent cone](https://en.wikipedia.org/wiki/Tangent_cone); ## Tags local extremum, Fermat's Theorem, Rolle's Theorem -/ universes u v open filter set open_locale topological_space classical section vector_space variables {E : Type u} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {a : E} {f' : E →L[ℝ] ℝ} /-- "Positive" tangent cone to `s` at `x`; the only difference from `tangent_cone_at` is that we require `c n → ∞` instead of `∥c n∥ → ∞`. One can think about `pos_tangent_cone_at` as `tangent_cone_at nnreal` but we have no theory of normed semifields yet. -/ def pos_tangent_cone_at (s : set E) (x : E) : set E := {y : E | ∃(c : ℕ → ℝ) (d : ℕ → E), (∀ᶠ n in at_top, x + d n ∈ s) ∧ (tendsto c at_top at_top) ∧ (tendsto (λn, c n • d n) at_top (𝓝 y))} lemma pos_tangent_cone_at_mono : monotone (λ s, pos_tangent_cone_at s a) := begin rintros s t hst y ⟨c, d, hd, hc, hcd⟩, exact ⟨c, d, mem_sets_of_superset hd $ λ h hn, hst hn, hc, hcd⟩ end lemma mem_pos_tangent_cone_at_of_segment_subset {s : set E} {x y : E} (h : segment x y ⊆ s) : y - x ∈ pos_tangent_cone_at s x := begin let c := λn:ℕ, (2:ℝ)^n, let d := λn:ℕ, (c n)⁻¹ • (y-x), refine ⟨c, d, filter.univ_mem_sets' (λn, h _), tendsto_pow_at_top_at_top_of_one_lt one_lt_two, _⟩, show x + d n ∈ segment x y, { rw segment_eq_image', refine ⟨(c n)⁻¹, ⟨_, _⟩, rfl⟩, exacts [inv_nonneg.2 (pow_nonneg zero_le_two _), inv_le_one (one_le_pow_of_one_le one_le_two _)] }, show tendsto (λ n, c n • d n) at_top (𝓝 (y - x)), { convert tendsto_const_nhds, ext n, simp only [d, smul_smul], rw [mul_inv_cancel, one_smul], exact pow_ne_zero _ two_ne_zero } end lemma mem_pos_tangent_cone_at_of_segment_subset' {s : set E} {x y : E} (h : segment x (x + y) ⊆ s) : y ∈ pos_tangent_cone_at s x := by simpa only [add_sub_cancel'] using mem_pos_tangent_cone_at_of_segment_subset h lemma pos_tangent_cone_at_univ : pos_tangent_cone_at univ a = univ := eq_univ_of_forall $ λ x, mem_pos_tangent_cone_at_of_segment_subset' (subset_univ _) /-- If `f` has a local max on `s` at `a`, `f'` is the derivative of `f` at `a` within `s`, and `y` belongs to the positive tangent cone of `s` at `a`, then `f' y ≤ 0`. -/ lemma is_local_max_on.has_fderiv_within_at_nonpos {s : set E} (h : is_local_max_on f s a) (hf : has_fderiv_within_at f f' s a) {y} (hy : y ∈ pos_tangent_cone_at s a) : f' y ≤ 0 := begin rcases hy with ⟨c, d, hd, hc, hcd⟩, have hc' : tendsto (λ n, ∥c n∥) at_top at_top, from tendsto_at_top_mono (λ n, le_abs_self _) hc, refine le_of_tendsto (hf.lim at_top hd hc' hcd) _, replace hd : tendsto (λ n, a + d n) at_top (𝓝[s] (a + 0)), from tendsto_inf.2 ⟨tendsto_const_nhds.add (tangent_cone_at.lim_zero _ hc' hcd), by rwa tendsto_principal⟩, rw [add_zero] at hd, replace h : ∀ᶠ n in at_top, f (a + d n) ≤ f a, from mem_map.1 (hd h), replace hc : ∀ᶠ n in at_top, 0 ≤ c n, from mem_map.1 (hc (mem_at_top (0:ℝ))), filter_upwards [h, hc], simp only [smul_eq_mul, mem_preimage, subset_def], assume n hnf hn, exact mul_nonpos_of_nonneg_of_nonpos hn (sub_nonpos.2 hnf) end /-- If `f` has a local max on `s` at `a` and `y` belongs to the positive tangent cone of `s` at `a`, then `f' y ≤ 0`. -/ lemma is_local_max_on.fderiv_within_nonpos {s : set E} (h : is_local_max_on f s a) {y} (hy : y ∈ pos_tangent_cone_at s a) : (fderiv_within ℝ f s a : E → ℝ) y ≤ 0 := if hf : differentiable_within_at ℝ f s a then h.has_fderiv_within_at_nonpos hf.has_fderiv_within_at hy else by { rw fderiv_within_zero_of_not_differentiable_within_at hf, refl } /-- If `f` has a local max on `s` at `a`, `f'` is a derivative of `f` at `a` within `s`, and both `y` and `-y` belong to the positive tangent cone of `s` at `a`, then `f' y ≤ 0`. -/ lemma is_local_max_on.has_fderiv_within_at_eq_zero {s : set E} (h : is_local_max_on f s a) (hf : has_fderiv_within_at f f' s a) {y} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) : f' y = 0 := le_antisymm (h.has_fderiv_within_at_nonpos hf hy) $ by simpa using h.has_fderiv_within_at_nonpos hf hy' /-- If `f` has a local max on `s` at `a` and both `y` and `-y` belong to the positive tangent cone of `s` at `a`, then `f' y = 0`. -/ lemma is_local_max_on.fderiv_within_eq_zero {s : set E} (h : is_local_max_on f s a) {y} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) : (fderiv_within ℝ f s a : E → ℝ) y = 0 := if hf : differentiable_within_at ℝ f s a then h.has_fderiv_within_at_eq_zero hf.has_fderiv_within_at hy hy' else by { rw fderiv_within_zero_of_not_differentiable_within_at hf, refl } /-- If `f` has a local min on `s` at `a`, `f'` is the derivative of `f` at `a` within `s`, and `y` belongs to the positive tangent cone of `s` at `a`, then `0 ≤ f' y`. -/ lemma is_local_min_on.has_fderiv_within_at_nonneg {s : set E} (h : is_local_min_on f s a) (hf : has_fderiv_within_at f f' s a) {y} (hy : y ∈ pos_tangent_cone_at s a) : 0 ≤ f' y := by simpa using h.neg.has_fderiv_within_at_nonpos hf.neg hy /-- If `f` has a local min on `s` at `a` and `y` belongs to the positive tangent cone of `s` at `a`, then `0 ≤ f' y`. -/ lemma is_local_min_on.fderiv_within_nonneg {s : set E} (h : is_local_min_on f s a) {y} (hy : y ∈ pos_tangent_cone_at s a) : (0:ℝ) ≤ (fderiv_within ℝ f s a : E → ℝ) y := if hf : differentiable_within_at ℝ f s a then h.has_fderiv_within_at_nonneg hf.has_fderiv_within_at hy else by { rw [fderiv_within_zero_of_not_differentiable_within_at hf], refl } /-- If `f` has a local max on `s` at `a`, `f'` is a derivative of `f` at `a` within `s`, and both `y` and `-y` belong to the positive tangent cone of `s` at `a`, then `f' y ≤ 0`. -/ lemma is_local_min_on.has_fderiv_within_at_eq_zero {s : set E} (h : is_local_min_on f s a) (hf : has_fderiv_within_at f f' s a) {y} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) : f' y = 0 := by simpa using h.neg.has_fderiv_within_at_eq_zero hf.neg hy hy' /-- If `f` has a local min on `s` at `a` and both `y` and `-y` belong to the positive tangent cone of `s` at `a`, then `f' y = 0`. -/ lemma is_local_min_on.fderiv_within_eq_zero {s : set E} (h : is_local_min_on f s a) {y} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) : (fderiv_within ℝ f s a : E → ℝ) y = 0 := if hf : differentiable_within_at ℝ f s a then h.has_fderiv_within_at_eq_zero hf.has_fderiv_within_at hy hy' else by { rw fderiv_within_zero_of_not_differentiable_within_at hf, refl } /-- Fermat's Theorem: the derivative of a function at a local minimum equals zero. -/ lemma is_local_min.has_fderiv_at_eq_zero (h : is_local_min f a) (hf : has_fderiv_at f f' a) : f' = 0 := begin ext y, apply (h.on univ).has_fderiv_within_at_eq_zero hf.has_fderiv_within_at; rw pos_tangent_cone_at_univ; apply mem_univ end /-- Fermat's Theorem: the derivative of a function at a local minimum equals zero. -/ lemma is_local_min.fderiv_eq_zero (h : is_local_min f a) : fderiv ℝ f a = 0 := if hf : differentiable_at ℝ f a then h.has_fderiv_at_eq_zero hf.has_fderiv_at else fderiv_zero_of_not_differentiable_at hf /-- Fermat's Theorem: the derivative of a function at a local maximum equals zero. -/ lemma is_local_max.has_fderiv_at_eq_zero (h : is_local_max f a) (hf : has_fderiv_at f f' a) : f' = 0 := neg_eq_zero.1 $ h.neg.has_fderiv_at_eq_zero hf.neg /-- Fermat's Theorem: the derivative of a function at a local maximum equals zero. -/ lemma is_local_max.fderiv_eq_zero (h : is_local_max f a) : fderiv ℝ f a = 0 := if hf : differentiable_at ℝ f a then h.has_fderiv_at_eq_zero hf.has_fderiv_at else fderiv_zero_of_not_differentiable_at hf /-- Fermat's Theorem: the derivative of a function at a local extremum equals zero. -/ lemma is_local_extr.has_fderiv_at_eq_zero (h : is_local_extr f a) : has_fderiv_at f f' a → f' = 0 := h.elim is_local_min.has_fderiv_at_eq_zero is_local_max.has_fderiv_at_eq_zero /-- Fermat's Theorem: the derivative of a function at a local extremum equals zero. -/ lemma is_local_extr.fderiv_eq_zero (h : is_local_extr f a) : fderiv ℝ f a = 0 := h.elim is_local_min.fderiv_eq_zero is_local_max.fderiv_eq_zero end vector_space section real variables {f : ℝ → ℝ} {f' : ℝ} {a b : ℝ} /-- Fermat's Theorem: the derivative of a function at a local minimum equals zero. -/ lemma is_local_min.has_deriv_at_eq_zero (h : is_local_min f a) (hf : has_deriv_at f f' a) : f' = 0 := by simpa using continuous_linear_map.ext_iff.1 (h.has_fderiv_at_eq_zero (has_deriv_at_iff_has_fderiv_at.1 hf)) 1 /-- Fermat's Theorem: the derivative of a function at a local minimum equals zero. -/ lemma is_local_min.deriv_eq_zero (h : is_local_min f a) : deriv f a = 0 := if hf : differentiable_at ℝ f a then h.has_deriv_at_eq_zero hf.has_deriv_at else deriv_zero_of_not_differentiable_at hf /-- Fermat's Theorem: the derivative of a function at a local maximum equals zero. -/ lemma is_local_max.has_deriv_at_eq_zero (h : is_local_max f a) (hf : has_deriv_at f f' a) : f' = 0 := neg_eq_zero.1 $ h.neg.has_deriv_at_eq_zero hf.neg /-- Fermat's Theorem: the derivative of a function at a local maximum equals zero. -/ lemma is_local_max.deriv_eq_zero (h : is_local_max f a) : deriv f a = 0 := if hf : differentiable_at ℝ f a then h.has_deriv_at_eq_zero hf.has_deriv_at else deriv_zero_of_not_differentiable_at hf /-- Fermat's Theorem: the derivative of a function at a local extremum equals zero. -/ lemma is_local_extr.has_deriv_at_eq_zero (h : is_local_extr f a) : has_deriv_at f f' a → f' = 0 := h.elim is_local_min.has_deriv_at_eq_zero is_local_max.has_deriv_at_eq_zero /-- Fermat's Theorem: the derivative of a function at a local extremum equals zero. -/ lemma is_local_extr.deriv_eq_zero (h : is_local_extr f a) : deriv f a = 0 := h.elim is_local_min.deriv_eq_zero is_local_max.deriv_eq_zero end real section Rolle variables (f f' : ℝ → ℝ) {a b : ℝ} /-- A continuous function on a closed interval with `f a = f b` takes either its maximum or its minimum value at a point in the interior of the interval. -/ lemma exists_Ioo_extr_on_Icc (hab : a < b) (hfc : continuous_on f (Icc a b)) (hfI : f a = f b) : ∃ c ∈ Ioo a b, is_extr_on f (Icc a b) c := begin have ne : (Icc a b).nonempty, from nonempty_Icc.2 (le_of_lt hab), -- Consider absolute min and max points obtain ⟨c, cmem, cle⟩ : ∃ c ∈ Icc a b, ∀ x ∈ Icc a b, f c ≤ f x, from compact_Icc.exists_forall_le ne hfc, obtain ⟨C, Cmem, Cge⟩ : ∃ C ∈ Icc a b, ∀ x ∈ Icc a b, f x ≤ f C, from compact_Icc.exists_forall_ge ne hfc, by_cases hc : f c = f a, { by_cases hC : f C = f a, { have : ∀ x ∈ Icc a b, f x = f a, from λ x hx, le_antisymm (hC ▸ Cge x hx) (hc ▸ cle x hx), -- `f` is a constant, so we can take any point in `Ioo a b` rcases exists_between hab with ⟨c', hc'⟩, refine ⟨c', hc', or.inl _⟩, assume x hx, rw [mem_set_of_eq, this x hx, ← hC], exact Cge c' ⟨le_of_lt hc'.1, le_of_lt hc'.2⟩ }, { refine ⟨C, ⟨lt_of_le_of_ne Cmem.1 $ mt _ hC, lt_of_le_of_ne Cmem.2 $ mt _ hC⟩, or.inr Cge⟩, exacts [λ h, by rw h, λ h, by rw [h, hfI]] } }, { refine ⟨c, ⟨lt_of_le_of_ne cmem.1 $ mt _ hc, lt_of_le_of_ne cmem.2 $ mt _ hc⟩, or.inl cle⟩, exacts [λ h, by rw h, λ h, by rw [h, hfI]] } end /-- A continuous function on a closed interval with `f a = f b` has a local extremum at some point of the corresponding open interval. -/ lemma exists_local_extr_Ioo (hab : a < b) (hfc : continuous_on f (Icc a b)) (hfI : f a = f b) : ∃ c ∈ Ioo a b, is_local_extr f c := let ⟨c, cmem, hc⟩ := exists_Ioo_extr_on_Icc f hab hfc hfI in ⟨c, cmem, hc.is_local_extr $ Icc_mem_nhds cmem.1 cmem.2⟩ /-- Rolle's Theorem `has_deriv_at` version -/ lemma exists_has_deriv_at_eq_zero (hab : a < b) (hfc : continuous_on f (Icc a b)) (hfI : f a = f b) (hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) : ∃ c ∈ Ioo a b, f' c = 0 := let ⟨c, cmem, hc⟩ := exists_local_extr_Ioo f hab hfc hfI in ⟨c, cmem, hc.has_deriv_at_eq_zero $ hff' c cmem⟩ /-- Rolle's Theorem `deriv` version -/ lemma exists_deriv_eq_zero (hab : a < b) (hfc : continuous_on f (Icc a b)) (hfI : f a = f b) : ∃ c ∈ Ioo a b, deriv f c = 0 := let ⟨c, cmem, hc⟩ := exists_local_extr_Ioo f hab hfc hfI in ⟨c, cmem, hc.deriv_eq_zero⟩ variables {f f'} {l : ℝ} /-- Rolle's Theorem, a version for a function on an open interval: if `f` has derivative `f'` on `(a, b)` and has the same limit `l` at `𝓝[Ioi a] a` and `𝓝[Iio b] b`, then `f' c = 0` for some `c ∈ (a, b)`. -/ lemma exists_has_deriv_at_eq_zero' (hab : a < b) (hfa : tendsto f (𝓝[Ioi a] a) (𝓝 l)) (hfb : tendsto f (𝓝[Iio b] b) (𝓝 l)) (hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) : ∃ c ∈ Ioo a b, f' c = 0 := begin have : continuous_on f (Ioo a b) := λ x hx, (hff' x hx).continuous_at.continuous_within_at, have hcont := continuous_on_Icc_extend_from_Ioo hab this hfa hfb, obtain ⟨c, hc, hcextr⟩ : ∃ c ∈ Ioo a b, is_local_extr (extend_from (Ioo a b) f) c, { apply exists_local_extr_Ioo _ hab hcont, rw eq_lim_at_right_extend_from_Ioo hab hfb, exact eq_lim_at_left_extend_from_Ioo hab hfa }, use [c, hc], apply (hcextr.congr _).has_deriv_at_eq_zero (hff' c hc), rw eventually_eq_iff_exists_mem, exact ⟨Ioo a b, Ioo_mem_nhds hc.1 hc.2, extend_from_extends this⟩ end /-- Rolle's Theorem, a version for a function on an open interval: if `f` has the same limit `l` at `𝓝[Ioi a] a` and `𝓝[Iio b] b`, then `deriv f c = 0` for some `c ∈ (a, b)`. This version does not require differentiability of `f` because we define `deriv f c = 0` whenever `f` is not differentiable at `c`. -/ lemma exists_deriv_eq_zero' (hab : a < b) (hfa : tendsto f (𝓝[Ioi a] a) (𝓝 l)) (hfb : tendsto f (𝓝[Iio b] b) (𝓝 l)) : ∃ c ∈ Ioo a b, deriv f c = 0 := classical.by_cases (assume h : ∀ x ∈ Ioo a b, differentiable_at ℝ f x, show ∃ c ∈ Ioo a b, deriv f c = 0, from exists_has_deriv_at_eq_zero' hab hfa hfb (λ x hx, (h x hx).has_deriv_at)) (assume h : ¬∀ x ∈ Ioo a b, differentiable_at ℝ f x, have h : ∃ x, x ∈ Ioo a b ∧ ¬differentiable_at ℝ f x, by { push_neg at h, exact h }, let ⟨c, hc, hcdiff⟩ := h in ⟨c, hc, deriv_zero_of_not_differentiable_at hcdiff⟩) end Rolle
d926f6a43000416f674964b6490d682b87c5eb64
9028d228ac200bbefe3a711342514dd4e4458bff
/src/category_theory/sites/sieves.lean
3a0306ed19f342b5647d581277f0618fb6af666d
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,735
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, E. W. Ayers -/ import category_theory.over import category_theory.limits.shapes.finite_limits import category_theory.yoneda import order.complete_lattice import data.set.lattice /-! # Theory of sieves - For an object `X` of a category `C`, a `sieve X` is a set of morphisms to `X` which is closed under left-composition. - The complete lattice structure on sieves is given, as well as the Galois insertion given by downward-closing. - A `sieve X` (functorially) induces a presheaf on `C` together with a monomorphism to the yoneda embedding of `X`. ## Tags sieve, pullback -/ universes v u namespace category_theory /-- For an object `X` of a category `C`, a `sieve X` is a set of morphisms to `X` which is closed under left-composition. -/ structure sieve {C : Type u} [category.{v} C] (X : C) := (arrows : Π {Y}, set (Y ⟶ X)) (downward_closed : ∀ {Y Z f} (hf : arrows f) (g : Z ⟶ Y), arrows (g ≫ f)) attribute [simp, priority 100] sieve.downward_closed namespace sieve variables {C : Type u} [category.{v} C] variables {X Y Z : C} {S R : sieve X} /-- A sieve gives a subset of the over category of `X`. -/ def set_over (S : sieve X) : set (over X) := λ f, S.arrows f.hom lemma arrows_ext : Π {R S : sieve X}, R.arrows = S.arrows → R = S | ⟨Ra, _⟩ ⟨Sa, _⟩ rfl := rfl @[ext] protected lemma ext {R S : sieve X} (h : ∀ ⦃Y⦄ (f : Y ⟶ X), R.arrows f ↔ S.arrows f) : R = S := arrows_ext $ funext $ λ x, funext $ λ f, propext $ h f protected lemma ext_iff {R S : sieve X} : R = S ↔ (∀ ⦃Y⦄ (f : Y ⟶ X), R.arrows f ↔ S.arrows f) := ⟨λ h Y f, h ▸ iff.rfl, sieve.ext⟩ open lattice /-- The supremum of a collection of sieves: the union of them all. -/ protected def Sup (𝒮 : set (sieve X)) : (sieve X) := { arrows := λ Y, {f | ∃ S ∈ 𝒮, sieve.arrows S f}, downward_closed := λ Y Z f, by { rintro ⟨S, hS, hf⟩ g, exact ⟨S, hS, S.downward_closed hf _⟩ } } /-- The infimum of a collection of sieves: the intersection of them all. -/ protected def Inf (𝒮 : set (sieve X)) : (sieve X) := { arrows := λ Y, {f | ∀ S ∈ 𝒮, sieve.arrows S f}, downward_closed := λ Y Z f hf g S H, S.downward_closed (hf S H) g } /-- The union of two sieves is a sieve. -/ protected def union (S R : sieve X) : sieve X := { arrows := λ Y f, S.arrows f ∨ R.arrows f, downward_closed := by { rintros Y Z f (h | h) g; simp [h] } } /-- The intersection of two sieves is a sieve. -/ protected def inter (S R : sieve X) : sieve X := { arrows := λ Y f, S.arrows f ∧ R.arrows f, downward_closed := by { rintros Y Z f ⟨h₁, h₂⟩ g, simp [h₁, h₂] } } /-- Sieves on an object `X` form a complete lattice. We generate this directly rather than using the galois insertion for nicer definitional properties. -/ instance : complete_lattice (sieve X) := { le := λ S R, ∀ Y (f : Y ⟶ X), S.arrows f → R.arrows f, le_refl := λ S f q, id, le_trans := λ S₁ S₂ S₃ S₁₂ S₂₃ Y f h, S₂₃ _ _ (S₁₂ _ _ h), le_antisymm := λ S R p q, sieve.ext (λ Y f, ⟨p _ _, q _ _⟩), top := { arrows := λ _, set.univ, downward_closed := λ Y Z f g h, ⟨⟩ }, bot := { arrows := λ _, ∅, downward_closed := λ _ _ _ p _, false.elim p }, sup := sieve.union, inf := sieve.inter, Sup := sieve.Sup, Inf := sieve.Inf, le_Sup := λ 𝒮 S hS Y f hf, ⟨S, hS, hf⟩, Sup_le := λ ℰ S hS Y f, by { rintro ⟨R, hR, hf⟩, apply hS R hR _ _ hf }, Inf_le := λ _ _ hS _ _ h, h _ hS, le_Inf := λ _ _ hS _ _ hf _ hR, hS _ hR _ _ hf, le_sup_left := λ _ _ _ _, or.inl, le_sup_right := λ _ _ _ _, or.inr, sup_le := λ _ _ _ a b _ _ hf, hf.elim (a _ _) (b _ _), inf_le_left := λ _ _ _ _, and.left, inf_le_right := λ _ _ _ _, and.right, le_inf := λ _ _ _ p q _ _ z, ⟨p _ _ z, q _ _ z⟩, le_top := λ _ _ _ _, trivial, bot_le := λ _ _ _, false.elim } /-- The maximal sieve always exists. -/ instance sieve_inhabited : inhabited (sieve X) := ⟨⊤⟩ @[simp] lemma mem_Inf {Ss : set (sieve X)} {Y} (f : Y ⟶ X) : (Inf Ss).arrows f ↔ ∀ S ∈ Ss, sieve.arrows S f := iff.rfl @[simp] lemma mem_Sup {Ss : set (sieve X)} {Y} (f : Y ⟶ X) : (Sup Ss).arrows f ↔ ∃ S ∈ Ss, sieve.arrows S f := iff.rfl @[simp] lemma mem_inter {R S : sieve X} {Y} (f : Y ⟶ X) : (R ⊓ S).arrows f ↔ R.arrows f ∧ S.arrows f := iff.rfl @[simp] lemma mem_union {R S : sieve X} {Y} (f : Y ⟶ X) : (R ⊔ S).arrows f ↔ R.arrows f ∨ S.arrows f := iff.rfl @[simp] lemma mem_top (f : Y ⟶ X) : (⊤ : sieve X).arrows f := trivial /-- Take the downward-closure of a set of morphisms to `X`. -/ inductive generate_sets (𝒢 : set (over X)) : Π (Y : C), set (Y ⟶ X) | basic : Π {Y : C} {f : Y ⟶ X}, over.mk f ∈ 𝒢 → generate_sets _ f | close : Π {Y Z} {f : Y ⟶ X} (g : Z ⟶ Y), generate_sets _ f → generate_sets _ (g ≫ f) /-- Generate the smallest sieve containing the given set of arrows. -/ def generate (𝒢 : set (over X)) : sieve X := { arrows := generate_sets 𝒢, downward_closed := λ _ _ _ h _, generate_sets.close _ h } open order lattice lemma sets_iff_generate (S : set (over X)) (S' : sieve X) : generate S ≤ S' ↔ S ≤ S'.set_over := ⟨λ H g hg, begin have : over.mk g.hom = g, cases g, dsimp [over.mk], congr' 1, apply subsingleton.elim, rw ← this at *, exact H _ _ (generate_sets.basic hg), end, λ ss Y f hf, begin induction hf, case basic : X g hg { exact ss hg }, case close : Y Z f g hf₁ hf₂ { exact S'.downward_closed hf₂ _ }, end⟩ /-- Show that there is a galois insertion (generate, set_over). -/ def gi_generate : galois_insertion (generate : set (over X) → sieve X) set_over := { gc := sets_iff_generate, choice := λ 𝒢 _, generate 𝒢, choice_eq := λ _ _, rfl, le_l_u := λ S Y f hf, generate_sets.basic hf } /-- Given a morphism `h : Y ⟶ X`, send a sieve S on X to a sieve on Y as the inverse image of S with `_ ≫ h`. That is, `sieve.pullback S h := (≫ h) '⁻¹ S`. -/ def pullback (h : Y ⟶ X) (S : sieve X) : sieve Y := { arrows := λ Y sl, S.arrows (sl ≫ h), downward_closed := λ Z W f g h, by simp [g] } @[simp] lemma mem_pullback (h : Y ⟶ X) {f : Z ⟶ Y} : (S.pullback h).arrows f ↔ S.arrows (f ≫ h) := iff.rfl lemma pullback_top {f : Y ⟶ X} : (⊤ : sieve X).pullback f = ⊤ := top_unique (λ _ g, id) lemma pullback_comp {f : Y ⟶ X} {g : Z ⟶ Y} (S : sieve X) : S.pullback (g ≫ f) = (S.pullback f).pullback g := by simp [sieve.ext_iff] lemma pullback_inter {f : Y ⟶ X} (S R : sieve X) : (S ⊓ R).pullback f = S.pullback f ⊓ R.pullback f := by simp [sieve.ext_iff] /-- If the identity arrow is in a sieve, the sieve is maximal. -/ lemma id_mem_iff_eq_top : S.arrows (𝟙 X) ↔ S = ⊤ := ⟨λ h, top_unique $ λ Y f _, by simpa using downward_closed _ h f, λ h, h.symm ▸ trivial⟩ lemma pullback_eq_top_iff_mem (f : Y ⟶ X) : S.arrows f ↔ S.pullback f = ⊤ := by rw [← id_mem_iff_eq_top, mem_pullback, category.id_comp] /-- Push a sieve `R` on `Y` forward along an arrow `f : Y ⟶ X`: `gf : Z ⟶ X` is in the sieve if `gf` factors through some `g : Z ⟶ Y` which is in `R`. -/ def pushforward (f : Y ⟶ X) (R : sieve Y) : sieve X := { arrows := λ Z gf, ∃ g, g ≫ f = gf ∧ R.arrows g, downward_closed := λ Z₁ Z₂ g ⟨j, k, z⟩ h, ⟨h ≫ j, by simp [k], by simp [z]⟩ } @[simp] lemma mem_pushforward_of_comp {R : sieve Y} {Z : C} {g : Z ⟶ Y} (hg : R.arrows g) (f : Y ⟶ X) : (R.pushforward f).arrows (g ≫ f) := ⟨g, rfl, hg⟩ lemma pushforward_comp {f : Y ⟶ X} {g : Z ⟶ Y} (R : sieve Z) : R.pushforward (g ≫ f) = (R.pushforward g).pushforward f := sieve.ext (λ W h, ⟨λ ⟨f₁, hq, hf₁⟩, ⟨f₁ ≫ g, by simpa, f₁, rfl, hf₁⟩, λ ⟨y, hy, z, hR, hz⟩, ⟨z, by rwa reassoc_of hR, hz⟩⟩) lemma galois_connection (f : Y ⟶ X) : galois_connection (sieve.pushforward f) (sieve.pullback f) := λ S R, ⟨λ hR Z g hg, hR _ _ ⟨g, rfl, hg⟩, λ hS Z g ⟨h, hg, hh⟩, hg ▸ hS Z h hh⟩ lemma pullback_monotone (f : Y ⟶ X) : monotone (sieve.pullback f) := (galois_connection f).monotone_u lemma pushforward_monotone (f : Y ⟶ X) : monotone (sieve.pushforward f) := (galois_connection f).monotone_l lemma le_pushforward_pullback (f : Y ⟶ X) (R : sieve Y) : R ≤ (R.pushforward f).pullback f := (galois_connection f).le_u_l _ lemma pullback_pushforward_le (f : Y ⟶ X) (R : sieve X) : (R.pullback f).pushforward f ≤ R := (galois_connection f).l_u_le _ lemma pushforward_union {f : Y ⟶ X} (S R : sieve Y) : (S ⊔ R).pushforward f = S.pushforward f ⊔ R.pushforward f := (galois_connection f).l_sup /-- If `f` is a monomorphism, the pushforward-pullback adjunction on sieves is coreflective. -/ def galois_coinsertion_of_mono (f : Y ⟶ X) [mono f] : galois_coinsertion (sieve.pushforward f) (sieve.pullback f) := begin apply (galois_connection f).to_galois_coinsertion, rintros S Z g ⟨g₁, hf, hg₁⟩, rw cancel_mono f at hf, rwa ← hf, end /-- If `f` is a split epi, the pushforward-pullback adjunction on sieves is reflective. -/ def galois_insertion_of_split_epi (f : Y ⟶ X) [split_epi f] : galois_insertion (sieve.pushforward f) (sieve.pullback f) := begin apply (galois_connection f).to_galois_insertion, intros S Z g hg, refine ⟨g ≫ section_ f, by simpa⟩, end /-- A sieve induces a presheaf. -/ @[simps] def functor (S : sieve X) : Cᵒᵖ ⥤ Type v := { obj := λ Y, {g : Y.unop ⟶ X // S.arrows g}, map := λ Y Z f g, ⟨f.unop ≫ g.1, downward_closed _ g.2 _⟩ } /-- If a sieve S is contained in a sieve T, then we have a morphism of presheaves on their induced presheaves. -/ @[simps] def nat_trans_of_le {S T : sieve X} (h : S ≤ T) : S.functor ⟶ T.functor := { app := λ Y f, ⟨f.1, h _ _ f.2⟩ }. /-- The natural inclusion from the functor induced by a sieve to the yoneda embedding. -/ @[simps] def functor_inclusion (S : sieve X) : S.functor ⟶ yoneda.obj X := { app := λ Y f, f.1 }. lemma nat_trans_of_le_comm {S T : sieve X} (h : S ≤ T) : nat_trans_of_le h ≫ functor_inclusion _ = functor_inclusion _ := rfl /-- The presheaf induced by a sieve is a subobject of the yoneda embedding. -/ instance functor_inclusion_is_mono : mono (functor_inclusion S) := ⟨λ Z f g h, by { ext Y y, apply congr_fun (nat_trans.congr_app h Y) y }⟩ end sieve end category_theory
ef851b1a0c3635f9b8de293b446a2be7e85d4061
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/hott/types/nat/order.hlean
eec65841968281c3e11ae813528d1852560ec0eb
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
18,524
hlean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Leonardo de Moura, Jeremy Avigad The order relation on the natural numbers. -/ import .basic algebra.ordered_ring open eq eq.ops algebra algebra namespace nat /- lt and le -/ protected theorem le_of_lt_sum_eq {m n : ℕ} (H : m < n ⊎ m = n) : m ≤ n := nat.le_of_eq_sum_lt (sum.swap H) protected theorem lt_sum_eq_of_le {m n : ℕ} (H : m ≤ n) : m < n ⊎ m = n := sum.swap (nat.eq_sum_lt_of_le H) protected theorem le_iff_lt_sum_eq (m n : ℕ) : m ≤ n ↔ m < n ⊎ m = n := iff.intro nat.lt_sum_eq_of_le nat.le_of_lt_sum_eq protected theorem lt_of_le_prod_ne {m n : ℕ} (H1 : m ≤ n) : m ≠ n → m < n := sum_resolve_right (nat.eq_sum_lt_of_le H1) protected theorem lt_iff_le_prod_ne (m n : ℕ) : m < n ↔ m ≤ n × m ≠ n := iff.intro (take H, pair (nat.le_of_lt H) (take H1, !nat.lt_irrefl (H1 ▸ H))) (prod.rec nat.lt_of_le_prod_ne) theorem le_add_right (n k : ℕ) : n ≤ n + k := nat.rec !nat.le_refl (λ k, le_succ_of_le) k theorem le_add_left (n m : ℕ): n ≤ m + n := !add.comm ▸ !le_add_right theorem le.intro {n m k : ℕ} (h : n + k = m) : n ≤ m := h ▸ !le_add_right theorem le.elim {n m : ℕ} : n ≤ m → Σ k, n + k = m := le.rec (sigma.mk 0 rfl) (λm h, sigma.rec (λ k H, sigma.mk (succ k) (H ▸ rfl))) protected theorem le_total {m n : ℕ} : m ≤ n ⊎ n ≤ m := sum.imp_left nat.le_of_lt !nat.lt_sum_ge /- addition -/ protected theorem add_le_add_left {n m : ℕ} (H : n ≤ m) (k : ℕ) : k + n ≤ k + m := obtain l Hl, from le.elim H, le.intro (Hl ▸ !add.assoc) protected theorem add_le_add_right {n m : ℕ} (H : n ≤ m) (k : ℕ) : n + k ≤ m + k := !add.comm ▸ !add.comm ▸ nat.add_le_add_left H k protected theorem le_of_add_le_add_left {k n m : ℕ} (H : k + n ≤ k + m) : n ≤ m := obtain l Hl, from le.elim H, le.intro (nat.add_left_cancel (!add.assoc⁻¹ ⬝ Hl)) protected theorem lt_of_add_lt_add_left {k n m : ℕ} (H : k + n < k + m) : n < m := let H' := nat.le_of_lt H in nat.lt_of_le_prod_ne (nat.le_of_add_le_add_left H') (assume Heq, !nat.lt_irrefl (Heq ▸ H)) protected theorem add_lt_add_left {n m : ℕ} (H : n < m) (k : ℕ) : k + n < k + m := lt_of_succ_le (!add_succ ▸ nat.add_le_add_left (succ_le_of_lt H) k) protected theorem add_lt_add_right {n m : ℕ} (H : n < m) (k : ℕ) : n + k < m + k := !add.comm ▸ !add.comm ▸ nat.add_lt_add_left H k protected theorem lt_add_of_pos_right {n k : ℕ} (H : k > 0) : n < n + k := !add_zero ▸ nat.add_lt_add_left H n /- multiplication -/ theorem mul_le_mul_left {n m : ℕ} (k : ℕ) (H : n ≤ m) : k * n ≤ k * m := obtain (l : ℕ) (Hl : n + l = m), from le.elim H, have k * n + k * l = k * m, by rewrite [-left_distrib, Hl], le.intro this theorem mul_le_mul_right {n m : ℕ} (k : ℕ) (H : n ≤ m) : n * k ≤ m * k := !mul.comm ▸ !mul.comm ▸ !mul_le_mul_left H protected theorem mul_le_mul {n m k l : ℕ} (H1 : n ≤ k) (H2 : m ≤ l) : n * m ≤ k * l := nat.le_trans (!nat.mul_le_mul_right H1) (!nat.mul_le_mul_left H2) protected theorem mul_lt_mul_of_pos_left {n m k : ℕ} (H : n < m) (Hk : k > 0) : k * n < k * m := nat.lt_of_lt_of_le (nat.lt_add_of_pos_right Hk) (!mul_succ ▸ nat.mul_le_mul_left k (succ_le_of_lt H)) protected theorem mul_lt_mul_of_pos_right {n m k : ℕ} (H : n < m) (Hk : k > 0) : n * k < m * k := !mul.comm ▸ !mul.comm ▸ nat.mul_lt_mul_of_pos_left H Hk /- nat is an instance of a linearly ordered semiring and a lattice -/ protected definition decidable_linear_ordered_semiring [reducible] [trans_instance] : decidable_linear_ordered_semiring nat := ⦃ decidable_linear_ordered_semiring, nat.comm_semiring, add_left_cancel := @nat.add_left_cancel, add_right_cancel := @nat.add_right_cancel, lt := nat.lt, le := nat.le, le_refl := nat.le_refl, le_trans := @nat.le_trans, le_antisymm := @nat.le_antisymm, le_total := @nat.le_total, le_iff_lt_sum_eq := @nat.le_iff_lt_sum_eq, le_of_lt := @nat.le_of_lt, lt_irrefl := @nat.lt_irrefl, lt_of_lt_of_le := @nat.lt_of_lt_of_le, lt_of_le_of_lt := @nat.lt_of_le_of_lt, lt_of_add_lt_add_left := @nat.lt_of_add_lt_add_left, add_lt_add_left := @nat.add_lt_add_left, add_le_add_left := @nat.add_le_add_left, le_of_add_le_add_left := @nat.le_of_add_le_add_left, zero_lt_one := zero_lt_succ 0, mul_le_mul_of_nonneg_left := (take a b c H1 H2, nat.mul_le_mul_left c H1), mul_le_mul_of_nonneg_right := (take a b c H1 H2, nat.mul_le_mul_right c H1), 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_lt := nat.decidable_lt ⦄ definition nat_has_dvd [reducible] [instance] [priority nat.prio] : has_dvd nat := has_dvd.mk has_dvd.dvd theorem add_pos_left {a : ℕ} (H : 0 < a) (b : ℕ) : 0 < a + b := @add_pos_of_pos_of_nonneg _ _ a b H !zero_le theorem add_pos_right {a : ℕ} (H : 0 < a) (b : ℕ) : 0 < b + a := by rewrite add.comm; apply add_pos_left H b theorem add_eq_zero_iff_eq_zero_prod_eq_zero {a b : ℕ} : a + b = 0 ↔ a = 0 × b = 0 := @add_eq_zero_iff_eq_zero_prod_eq_zero_of_nonneg_of_nonneg _ _ a b !zero_le !zero_le theorem le_add_of_le_left {a b c : ℕ} (H : b ≤ c) : b ≤ a + c := @le_add_of_nonneg_of_le _ _ a b c !zero_le H theorem le_add_of_le_right {a b c : ℕ} (H : b ≤ c) : b ≤ c + a := @le_add_of_le_of_nonneg _ _ a b c H !zero_le theorem lt_add_of_lt_left {b c : ℕ} (H : b < c) (a : ℕ) : b < a + c := @lt_add_of_nonneg_of_lt _ _ a b c !zero_le H theorem lt_add_of_lt_right {b c : ℕ} (H : b < c) (a : ℕ) : b < c + a := @lt_add_of_lt_of_nonneg _ _ a b c H !zero_le theorem lt_of_mul_lt_mul_left {a b c : ℕ} (H : c * a < c * b) : a < b := @lt_of_mul_lt_mul_left _ _ a b c H !zero_le theorem lt_of_mul_lt_mul_right {a b c : ℕ} (H : a * c < b * c) : a < b := @lt_of_mul_lt_mul_right _ _ a b c H !zero_le theorem pos_of_mul_pos_left {a b : ℕ} (H : 0 < a * b) : 0 < b := @pos_of_mul_pos_left _ _ a b H !zero_le theorem pos_of_mul_pos_right {a b : ℕ} (H : 0 < a * b) : 0 < a := @pos_of_mul_pos_right _ _ a b H !zero_le theorem zero_le_one : (0:nat) ≤ 1 := dec_star /- properties specific to nat -/ theorem lt_intro {n m k : ℕ} (H : succ n + k = m) : n < m := lt_of_succ_le (le.intro H) theorem lt_elim {n m : ℕ} (H : n < m) : Σk, succ n + k = m := le.elim (succ_le_of_lt H) theorem lt_add_succ (n m : ℕ) : n < n + succ m := lt_intro !succ_add_eq_succ_add theorem eq_zero_of_le_zero {n : ℕ} (H : n ≤ 0) : n = 0 := obtain (k : ℕ) (Hk : n + k = 0), from le.elim H, eq_zero_of_add_eq_zero_right Hk /- succ and pred -/ theorem le_of_lt_succ {m n : nat} : m < succ n → m ≤ n := le_of_succ_le_succ theorem lt_iff_succ_le (m n : nat) : m < n ↔ succ m ≤ n := iff.rfl theorem lt_succ_iff_le (m n : nat) : m < succ n ↔ m ≤ n := iff.intro le_of_lt_succ lt_succ_of_le theorem self_le_succ (n : ℕ) : n ≤ succ n := le.intro !add_one theorem succ_le_sum_eq_of_le {n m : ℕ} : n ≤ m → succ n ≤ m ⊎ n = m := lt_sum_eq_of_le theorem pred_le_of_le_succ {n m : ℕ} : n ≤ succ m → pred n ≤ m := pred_le_pred theorem succ_le_of_le_pred {n m : ℕ} : succ n ≤ m → n ≤ pred m := pred_le_pred theorem pred_le_pred_of_le {n m : ℕ} : n ≤ m → pred n ≤ pred m := pred_le_pred theorem pre_lt_of_lt {n m : ℕ} : n < m → pred n < m := lt_of_le_of_lt !pred_le theorem lt_of_pred_lt_pred {n m : ℕ} (H : pred n < pred m) : n < m := lt_of_not_ge (suppose m ≤ n, not_lt_of_ge (pred_le_pred_of_le this) H) theorem le_sum_eq_succ_of_le_succ {n m : ℕ} (H : n ≤ succ m) : n ≤ m ⊎ n = succ m := sum.imp_left le_of_succ_le_succ (succ_le_sum_eq_of_le H) theorem le_pred_self (n : ℕ) : pred n ≤ n := !pred_le theorem succ_pos (n : ℕ) : 0 < succ n := !zero_lt_succ theorem succ_pred_of_pos {n : ℕ} (H : n > 0) : succ (pred n) = n := (sum_resolve_right (eq_zero_sum_eq_succ_pred n) (ne.symm (ne_of_lt H)))⁻¹ theorem exists_eq_succ_of_lt {n : ℕ} : Π {m : ℕ}, n < m → Σk, m = succ k | 0 H := absurd H !not_lt_zero | (succ k) H := sigma.mk k rfl theorem lt_succ_self (n : ℕ) : n < succ n := lt.base n lemma lt_succ_of_lt {i j : nat} : i < j → i < succ j := assume Plt, lt.trans Plt (self_lt_succ j) /- other forms of induction -/ protected definition strong_rec_on {P : nat → Type} (n : ℕ) (H : Πn, (Πm, m < n → P m) → P n) : P n := nat.rec (λm h, absurd h !not_lt_zero) (λn' (IH : Π {m : ℕ}, m < n' → P m) m l, sum.elim (lt_sum_eq_of_le (le_of_lt_succ l)) IH (λ e, eq.rec (H n' @IH) e⁻¹)) (succ n) n !lt_succ_self protected theorem case_strong_rec_on {P : nat → Type} (a : nat) (H0 : P 0) (Hind : Π(n : nat), (Πm, m ≤ n → P m) → P (succ n)) : P a := nat.strong_rec_on a (take n, show (Π m, m < n → P m) → P n, from nat.cases_on n (suppose (Π m, m < 0 → P m), show P 0, from H0) (take n, suppose (Π m, m < succ n → P m), show P (succ n), from Hind n (take m, assume H1 : m ≤ n, this _ (lt_succ_of_le H1)))) /- pos -/ theorem by_cases_zero_pos {P : ℕ → Type} (y : ℕ) (H0 : P 0) (H1 : Π {y : nat}, y > 0 → P y) : P y := nat.cases_on y H0 (take y, H1 !succ_pos) theorem eq_zero_sum_pos (n : ℕ) : n = 0 ⊎ n > 0 := sum_of_sum_of_imp_left (sum.swap (lt_sum_eq_of_le !zero_le)) (suppose 0 = n, by subst n) theorem pos_of_ne_zero {n : ℕ} (H : n ≠ 0) : n > 0 := sum.elim !eq_zero_sum_pos (take H2 : n = 0, by contradiction) (take H2 : n > 0, H2) theorem ne_zero_of_pos {n : ℕ} (H : n > 0) : n ≠ 0 := ne.symm (ne_of_lt H) theorem exists_eq_succ_of_pos {n : ℕ} (H : n > 0) : Σl, n = succ l := exists_eq_succ_of_lt H theorem pos_of_dvd_of_pos {m n : ℕ} (H1 : m ∣ n) (H2 : n > 0) : m > 0 := pos_of_ne_zero (suppose m = 0, assert n = 0, from eq_zero_of_zero_dvd (this ▸ H1), ne_of_lt H2 (by subst n)) /- multiplication -/ theorem mul_lt_mul_of_le_of_lt {n m k l : ℕ} (Hk : k > 0) (H1 : n ≤ k) (H2 : m < l) : n * m < k * l := lt_of_le_of_lt (mul_le_mul_right m H1) (mul_lt_mul_of_pos_left H2 Hk) theorem mul_lt_mul_of_lt_of_le {n m k l : ℕ} (Hl : l > 0) (H1 : n < k) (H2 : m ≤ l) : n * m < k * l := lt_of_le_of_lt (mul_le_mul_left n H2) (mul_lt_mul_of_pos_right H1 Hl) theorem mul_lt_mul_of_le_of_le {n m k l : ℕ} (H1 : n < k) (H2 : m < l) : n * m < k * l := have H3 : n * m ≤ k * m, from mul_le_mul_right m (le_of_lt H1), have H4 : k * m < k * l, from mul_lt_mul_of_pos_left H2 (lt_of_le_of_lt !zero_le H1), lt_of_le_of_lt H3 H4 theorem eq_of_mul_eq_mul_left {m k n : ℕ} (Hn : n > 0) (H : n * m = n * k) : m = k := have n * m ≤ n * k, by rewrite H, have m ≤ k, from le_of_mul_le_mul_left this Hn, have n * k ≤ n * m, by rewrite H, have k ≤ m, from le_of_mul_le_mul_left this Hn, le.antisymm `m ≤ k` this theorem eq_of_mul_eq_mul_right {n m k : ℕ} (Hm : m > 0) (H : n * m = k * m) : n = k := eq_of_mul_eq_mul_left Hm (!mul.comm ▸ !mul.comm ▸ H) theorem eq_zero_sum_eq_of_mul_eq_mul_left {n m k : ℕ} (H : n * m = n * k) : n = 0 ⊎ m = k := sum_of_sum_of_imp_right !eq_zero_sum_pos (assume Hn : n > 0, eq_of_mul_eq_mul_left Hn H) theorem eq_zero_sum_eq_of_mul_eq_mul_right {n m k : ℕ} (H : n * m = k * m) : m = 0 ⊎ n = k := eq_zero_sum_eq_of_mul_eq_mul_left (!mul.comm ▸ !mul.comm ▸ H) theorem eq_one_of_mul_eq_one_right {n m : ℕ} (H : n * m = 1) : n = 1 := have H2 : n * m > 0, by rewrite H; apply succ_pos, sum.elim (le_sum_gt n 1) (suppose n ≤ 1, have n > 0, from pos_of_mul_pos_right H2, show n = 1, from le.antisymm `n ≤ 1` (succ_le_of_lt this)) (suppose n > 1, have m > 0, from pos_of_mul_pos_left H2, have n * m ≥ 2 * 1, from nat.mul_le_mul (succ_le_of_lt `n > 1`) (succ_le_of_lt this), have 1 ≥ 2, from !mul_one ▸ H ▸ this, absurd !lt_succ_self (not_lt_of_ge this)) theorem eq_one_of_mul_eq_one_left {n m : ℕ} (H : n * m = 1) : m = 1 := eq_one_of_mul_eq_one_right (!mul.comm ▸ H) theorem eq_one_of_mul_eq_self_left {n m : ℕ} (Hpos : n > 0) (H : m * n = n) : m = 1 := eq_of_mul_eq_mul_right Hpos (H ⬝ !one_mul⁻¹) theorem eq_one_of_mul_eq_self_right {n m : ℕ} (Hpos : m > 0) (H : m * n = m) : n = 1 := eq_one_of_mul_eq_self_left Hpos (!mul.comm ▸ H) theorem eq_one_of_dvd_one {n : ℕ} (H : n ∣ 1) : n = 1 := dvd.elim H (take m, suppose 1 = n * m, eq_one_of_mul_eq_one_right this⁻¹) /- min and max -/ open decidable theorem min_zero [simp] (a : ℕ) : min a 0 = 0 := by rewrite [min_eq_right !zero_le] theorem zero_min [simp] (a : ℕ) : min 0 a = 0 := by rewrite [min_eq_left !zero_le] theorem max_zero [simp] (a : ℕ) : max a 0 = a := by rewrite [max_eq_left !zero_le] theorem zero_max [simp] (a : ℕ) : max 0 a = a := by rewrite [max_eq_right !zero_le] theorem min_succ_succ [simp] (a b : ℕ) : min (succ a) (succ b) = succ (min a b) := sum.elim !lt_sum_ge (suppose a < b, by rewrite [min_eq_left_of_lt this, min_eq_left_of_lt (succ_lt_succ this)]) (suppose a ≥ b, by rewrite [min_eq_right this, min_eq_right (succ_le_succ this)]) theorem max_succ_succ [simp] (a b : ℕ) : max (succ a) (succ b) = succ (max a b) := sum.elim !lt_sum_ge (suppose a < b, by rewrite [max_eq_right_of_lt this, max_eq_right_of_lt (succ_lt_succ this)]) (suppose a ≥ b, by rewrite [max_eq_left this, max_eq_left (succ_le_succ this)]) /- In algebra.ordered_group, these next four are only proved for additive groups, not additive semigroups. -/ protected theorem min_add_add_left (a b c : ℕ) : min (a + b) (a + c) = a + min b c := decidable.by_cases (suppose b ≤ c, assert a + b ≤ a + c, from add_le_add_left this _, by rewrite [min_eq_left `b ≤ c`, min_eq_left this]) (suppose ¬ b ≤ c, assert c ≤ b, from le_of_lt (lt_of_not_ge this), assert a + c ≤ a + b, from add_le_add_left this _, by rewrite [min_eq_right `c ≤ b`, min_eq_right this]) protected theorem min_add_add_right (a b c : ℕ) : min (a + c) (b + c) = min a b + c := by rewrite [add.comm a c, add.comm b c, add.comm _ c]; apply nat.min_add_add_left protected theorem max_add_add_left (a b c : ℕ) : max (a + b) (a + c) = a + max b c := decidable.by_cases (suppose b ≤ c, assert a + b ≤ a + c, from add_le_add_left this _, by rewrite [max_eq_right `b ≤ c`, max_eq_right this]) (suppose ¬ b ≤ c, assert c ≤ b, from le_of_lt (lt_of_not_ge this), assert a + c ≤ a + b, from add_le_add_left this _, by rewrite [max_eq_left `c ≤ b`, max_eq_left this]) protected theorem max_add_add_right (a b c : ℕ) : max (a + c) (b + c) = max a b + c := by rewrite [add.comm a c, add.comm b c, add.comm _ c]; apply nat.max_add_add_left /- least and greatest -/ section least_prod_greatest variable (P : ℕ → Type) variable [decP : Π n, decidable (P n)] include decP -- returns the least i < n satisfying P, sum n if there is none definition least : ℕ → ℕ | 0 := 0 | (succ n) := if P (least n) then least n else succ n theorem least_of_bound {n : ℕ} (H : P n) : P (least P n) := begin induction n with [m, ih], rewrite ↑least, apply H, rewrite ↑least, cases decidable.em (P (least P m)) with [Hlp, Hlp], rewrite [if_pos Hlp], apply Hlp, rewrite [if_neg Hlp], apply H end theorem least_le (n : ℕ) : least P n ≤ n:= begin induction n with [m, ih], {rewrite ↑least}, rewrite ↑least, cases decidable.em (P (least P m)) with [Psm, Pnsm], rewrite [if_pos Psm], apply le.trans ih !le_succ, rewrite [if_neg Pnsm] end theorem least_of_lt {i n : ℕ} (ltin : i < n) (H : P i) : P (least P n) := begin induction n with [m, ih], exact absurd ltin !not_lt_zero, rewrite ↑least, cases decidable.em (P (least P m)) with [Psm, Pnsm], rewrite [if_pos Psm], apply Psm, rewrite [if_neg Pnsm], cases (lt_sum_eq_of_le (le_of_lt_succ ltin)) with [Hlt, Heq], exact absurd (ih Hlt) Pnsm, rewrite Heq at H, exact absurd (least_of_bound P H) Pnsm end theorem ge_least_of_lt {i n : ℕ} (ltin : i < n) (Hi : P i) : i ≥ least P n := begin induction n with [m, ih], exact absurd ltin !not_lt_zero, rewrite ↑least, cases decidable.em (P (least P m)) with [Psm, Pnsm], rewrite [if_pos Psm], cases (lt_sum_eq_of_le (le_of_lt_succ ltin)) with [Hlt, Heq], apply ih Hlt, rewrite Heq, apply least_le, rewrite [if_neg Pnsm], cases (lt_sum_eq_of_le (le_of_lt_succ ltin)) with [Hlt, Heq], apply absurd (least_of_lt P Hlt Hi) Pnsm, rewrite Heq at Hi, apply absurd (least_of_bound P Hi) Pnsm end theorem least_lt {n i : ℕ} (ltin : i < n) (Hi : P i) : least P n < n := lt_of_le_of_lt (ge_least_of_lt P ltin Hi) ltin -- returns the largest i < n satisfying P, sum n if there is none. definition greatest : ℕ → ℕ | 0 := 0 | (succ n) := if P n then n else greatest n theorem greatest_of_lt {i n : ℕ} (ltin : i < n) (Hi : P i) : P (greatest P n) := begin induction n with [m, ih], {exact absurd ltin !not_lt_zero}, {cases (decidable.em (P m)) with [Psm, Pnsm], {rewrite [↑greatest, if_pos Psm]; exact Psm}, {rewrite [↑greatest, if_neg Pnsm], have neim : i ≠ m, from assume H : i = m, absurd (H ▸ Hi) Pnsm, have ltim : i < m, from lt_of_le_of_ne (le_of_lt_succ ltin) neim, apply ih ltim}} end theorem le_greatest_of_lt {i n : ℕ} (ltin : i < n) (Hi : P i) : i ≤ greatest P n := begin induction n with [m, ih], {exact absurd ltin !not_lt_zero}, {cases (decidable.em (P m)) with [Psm, Pnsm], {rewrite [↑greatest, if_pos Psm], apply le_of_lt_succ ltin}, {rewrite [↑greatest, if_neg Pnsm], have neim : i ≠ m, from assume H : i = m, absurd (H ▸ Hi) Pnsm, have ltim : i < m, from lt_of_le_of_ne (le_of_lt_succ ltin) neim, apply ih ltim}} end end least_prod_greatest end nat
4d88b5f8ea199f5be2425d89d5189af13316881a
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/coercion_bug.lean
0dd664e224101cfc0f98b3dbe00f4aed7021b85a
[ "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
91
lean
import data.nat open nat definition tst1 : Prop := zero = 0 definition tst2 : nat := 0
f564f652c9a47b89f48cd6fd23779d9936784f18
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/list/intervals_auto.lean
242d8512dbc4c23297b3c0a2b230423c1efef478
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
6,202
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.list.range import Mathlib.data.list.bag_inter import Mathlib.PostPort namespace Mathlib namespace list /-- `Ico n m` is the list of natural numbers `n ≤ x < m`. (Ico stands for "interval, closed-open".) See also `data/set/intervals.lean` for `set.Ico`, modelling intervals in general preorders, and `multiset.Ico` and `finset.Ico` for `n ≤ x < m` as a multiset or as a finset. @TODO (anyone): Define `Ioo` and `Icc`, state basic lemmas about them. @TODO (anyone): Also do the versions for integers? @TODO (anyone): One could generalise even further, defining 'locally finite partial orders', for which `set.Ico a b` is `[finite]`, and 'locally finite total orders', for which there is a list model. -/ def Ico (n : ℕ) (m : ℕ) : List ℕ := range' n (m - n) namespace Ico theorem zero_bot (n : ℕ) : Ico 0 n = range n := eq.mpr (id (Eq._oldrec (Eq.refl (Ico 0 n = range n)) (equations._eqn_1 0 n))) (eq.mpr (id (Eq._oldrec (Eq.refl (range' 0 (n - 0) = range n)) (nat.sub_zero n))) (eq.mpr (id (Eq._oldrec (Eq.refl (range' 0 n = range n)) (range_eq_range' n))) (Eq.refl (range' 0 n)))) @[simp] theorem length (n : ℕ) (m : ℕ) : length (Ico n m) = m - n := sorry theorem pairwise_lt (n : ℕ) (m : ℕ) : pairwise Less (Ico n m) := id (eq.mpr (id (propext ((fun (s n : ℕ) => iff_true_intro (pairwise_lt_range' s n)) n (m - n)))) trivial) theorem nodup (n : ℕ) (m : ℕ) : nodup (Ico n m) := id (eq.mpr (id (propext ((fun (s n : ℕ) => iff_true_intro (nodup_range' s n)) n (m - n)))) trivial) @[simp] theorem mem {n : ℕ} {m : ℕ} {l : ℕ} : l ∈ Ico n m ↔ n ≤ l ∧ l < m := sorry theorem eq_nil_of_le {n : ℕ} {m : ℕ} (h : m ≤ n) : Ico n m = [] := sorry theorem map_add (n : ℕ) (m : ℕ) (k : ℕ) : map (Add.add k) (Ico n m) = Ico (n + k) (m + k) := sorry theorem map_sub (n : ℕ) (m : ℕ) (k : ℕ) (h₁ : k ≤ n) : map (fun (x : ℕ) => x - k) (Ico n m) = Ico (n - k) (m - k) := sorry @[simp] theorem self_empty {n : ℕ} : Ico n n = [] := eq_nil_of_le (le_refl n) @[simp] theorem eq_empty_iff {n : ℕ} {m : ℕ} : Ico n m = [] ↔ m ≤ n := sorry theorem append_consecutive {n : ℕ} {m : ℕ} {l : ℕ} (hnm : n ≤ m) (hml : m ≤ l) : Ico n m ++ Ico m l = Ico n l := sorry @[simp] theorem inter_consecutive (n : ℕ) (m : ℕ) (l : ℕ) : Ico n m ∩ Ico m l = [] := sorry @[simp] theorem bag_inter_consecutive (n : ℕ) (m : ℕ) (l : ℕ) : list.bag_inter (Ico n m) (Ico m l) = [] := iff.mpr (bag_inter_nil_iff_inter_nil (Ico n m) (Ico m l)) (inter_consecutive n m l) @[simp] theorem succ_singleton {n : ℕ} : Ico n (n + 1) = [n] := sorry theorem succ_top {n : ℕ} {m : ℕ} (h : n ≤ m) : Ico n (m + 1) = Ico n m ++ [m] := eq.mpr (id (Eq._oldrec (Eq.refl (Ico n (m + 1) = Ico n m ++ [m])) (Eq.symm succ_singleton))) (eq.mpr (id (Eq._oldrec (Eq.refl (Ico n (m + 1) = Ico n m ++ Ico m (m + 1))) (append_consecutive h (nat.le_succ m)))) (Eq.refl (Ico n (m + 1)))) theorem eq_cons {n : ℕ} {m : ℕ} (h : n < m) : Ico n m = n :: Ico (n + 1) m := eq.mpr (id (Eq._oldrec (Eq.refl (Ico n m = n :: Ico (n + 1) m)) (Eq.symm (append_consecutive (nat.le_succ n) h)))) (eq.mpr (id (Eq._oldrec (Eq.refl (Ico n (Nat.succ n) ++ Ico (Nat.succ n) m = n :: Ico (n + 1) m)) succ_singleton)) (Eq.refl ([n] ++ Ico (Nat.succ n) m))) @[simp] theorem pred_singleton {m : ℕ} (h : 0 < m) : Ico (m - 1) m = [m - 1] := sorry theorem chain'_succ (n : ℕ) (m : ℕ) : chain' (fun (a b : ℕ) => b = Nat.succ a) (Ico n m) := sorry @[simp] theorem not_mem_top {n : ℕ} {m : ℕ} : ¬m ∈ Ico n m := sorry theorem filter_lt_of_top_le {n : ℕ} {m : ℕ} {l : ℕ} (hml : m ≤ l) : filter (fun (x : ℕ) => x < l) (Ico n m) = Ico n m := iff.mpr filter_eq_self fun (k : ℕ) (hk : k ∈ Ico n m) => lt_of_lt_of_le (and.right (iff.mp mem hk)) hml theorem filter_lt_of_le_bot {n : ℕ} {m : ℕ} {l : ℕ} (hln : l ≤ n) : filter (fun (x : ℕ) => x < l) (Ico n m) = [] := iff.mpr filter_eq_nil fun (k : ℕ) (hk : k ∈ Ico n m) => not_lt_of_le (le_trans hln (and.left (iff.mp mem hk))) theorem filter_lt_of_ge {n : ℕ} {m : ℕ} {l : ℕ} (hlm : l ≤ m) : filter (fun (x : ℕ) => x < l) (Ico n m) = Ico n l := sorry @[simp] theorem filter_lt (n : ℕ) (m : ℕ) (l : ℕ) : filter (fun (x : ℕ) => x < l) (Ico n m) = Ico n (min m l) := sorry theorem filter_le_of_le_bot {n : ℕ} {m : ℕ} {l : ℕ} (hln : l ≤ n) : filter (fun (x : ℕ) => l ≤ x) (Ico n m) = Ico n m := iff.mpr filter_eq_self fun (k : ℕ) (hk : k ∈ Ico n m) => le_trans hln (and.left (iff.mp mem hk)) theorem filter_le_of_top_le {n : ℕ} {m : ℕ} {l : ℕ} (hml : m ≤ l) : filter (fun (x : ℕ) => l ≤ x) (Ico n m) = [] := iff.mpr filter_eq_nil fun (k : ℕ) (hk : k ∈ Ico n m) => not_le_of_gt (lt_of_lt_of_le (and.right (iff.mp mem hk)) hml) theorem filter_le_of_le {n : ℕ} {m : ℕ} {l : ℕ} (hnl : n ≤ l) : filter (fun (x : ℕ) => l ≤ x) (Ico n m) = Ico l m := sorry @[simp] theorem filter_le (n : ℕ) (m : ℕ) (l : ℕ) : filter (fun (x : ℕ) => l ≤ x) (Ico n m) = Ico (max n l) m := sorry theorem filter_lt_of_succ_bot {n : ℕ} {m : ℕ} (hnm : n < m) : filter (fun (x : ℕ) => x < n + 1) (Ico n m) = [n] := sorry @[simp] theorem filter_le_of_bot {n : ℕ} {m : ℕ} (hnm : n < m) : filter (fun (x : ℕ) => x ≤ n) (Ico n m) = [n] := eq.mpr (id (Eq._oldrec (Eq.refl (filter (fun (x : ℕ) => x ≤ n) (Ico n m) = [n])) (Eq.symm (filter_lt_of_succ_bot hnm)))) (filter_congr fun (_x : ℕ) (_x_1 : _x ∈ Ico n m) => iff.symm nat.lt_succ_iff) /-- For any natural numbers n, a, and b, one of the following holds: 1. n < a 2. n ≥ b 3. n ∈ Ico a b -/ theorem trichotomy (n : ℕ) (a : ℕ) (b : ℕ) : n < a ∨ b ≤ n ∨ n ∈ Ico a b := sorry end Mathlib
139815b11618b38a13f5b9a42f96d6693592e6d6
9dc8cecdf3c4634764a18254e94d43da07142918
/src/analysis/inner_product_space/symmetric.lean
1f67e8494da201f2b9407823b489680999f424ca
[ "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
5,690
lean
/- Copyright (c) 2022 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Moritz Doll, Frédéric Dupuis, Heather Macbeth -/ import analysis.inner_product_space.basic /-! # Symmetric linear maps in an inner product space This file defines and proves basic theorems about symmetric **not necessarily bounded** operators on an inner product space, i.e linear maps `T : E → E` such that `∀ x y, ⟪T x, y⟫ = ⟪x, T y⟫`. In comparison to `is_self_adjoint`, this definition works for non-continuous linear maps, and doesn't rely on the definition of the adjoint, which allows it to be stated in non-complete space. ## Main definitions * `linear_map.is_symmetric`: a (not necessarily bounded) operator on an inner product space is symmetric, if for all `x`, `y`, we have `⟪T x, y⟫ = ⟪x, T y⟫` ## Main statements * `is_symmetric.continuous`: if a symmetric operator is defined on a complete space, then it is automatically continuous. ## Tags self-adjoint, symmetric -/ open is_R_or_C open_locale complex_conjugate variables {𝕜 E E' F G : Type*} [is_R_or_C 𝕜] variables [inner_product_space 𝕜 E] [inner_product_space 𝕜 F] [inner_product_space 𝕜 G] variables [inner_product_space ℝ E'] local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y namespace linear_map /-! ### Symmetric operators -/ /-- A (not necessarily bounded) operator on an inner product space is symmetric, if for all `x`, `y`, we have `⟪T x, y⟫ = ⟪x, T y⟫`. -/ def is_symmetric (T : E →ₗ[𝕜] E) : Prop := ∀ x y, ⟪T x, y⟫ = ⟪x, T y⟫ section real variables -- Todo: Generalize this to `is_R_or_C`. /-- An operator `T` on a `ℝ`-inner product space is symmetric if and only if it is `bilin_form.is_self_adjoint` with respect to the bilinear form given by the inner product. -/ lemma is_symmetric_iff_bilin_form (T : E' →ₗ[ℝ] E') : is_symmetric T ↔ bilin_form_of_real_inner.is_self_adjoint T := by simp [is_symmetric, bilin_form.is_self_adjoint, bilin_form.is_adjoint_pair] end real lemma is_symmetric.conj_inner_sym {T : E →ₗ[𝕜] E} (hT : is_symmetric T) (x y : E) : conj ⟪T x, y⟫ = ⟪T y, x⟫ := by rw [hT x y, inner_conj_sym] @[simp] lemma is_symmetric.apply_clm {T : E →L[𝕜] E} (hT : is_symmetric (T : E →ₗ[𝕜] E)) (x y : E) : ⟪T x, y⟫ = ⟪x, T y⟫ := hT x y lemma is_symmetric_zero : (0 : E →ₗ[𝕜] E).is_symmetric := λ x y, (inner_zero_right : ⟪x, 0⟫ = 0).symm ▸ (inner_zero_left : ⟪0, y⟫ = 0) lemma is_symmetric_id : (linear_map.id : E →ₗ[𝕜] E).is_symmetric := λ x y, rfl lemma is_symmetric.add {T S : E →ₗ[𝕜] E} (hT : T.is_symmetric) (hS : S.is_symmetric) : (T + S).is_symmetric := begin intros x y, rw [linear_map.add_apply, inner_add_left, hT x y, hS x y, ← inner_add_right], refl end /-- The **Hellinger--Toeplitz theorem**: if a symmetric operator is defined on a complete space, then it is automatically continuous. -/ lemma is_symmetric.continuous [complete_space E] {T : E →ₗ[𝕜] E} (hT : is_symmetric T) : continuous T := begin -- We prove it by using the closed graph theorem refine T.continuous_of_seq_closed_graph (λ u x y hu hTu, _), rw [←sub_eq_zero, ←inner_self_eq_zero], have hlhs : ∀ k : ℕ, ⟪T (u k) - T x, y - T x⟫ = ⟪u k - x, T (y - T x)⟫ := by { intro k, rw [←T.map_sub, hT] }, refine tendsto_nhds_unique ((hTu.sub_const _).inner tendsto_const_nhds) _, simp_rw hlhs, rw ←@inner_zero_left 𝕜 E _ _ (T (y - T x)), refine filter.tendsto.inner _ tendsto_const_nhds, rw ←sub_self x, exact hu.sub_const _, end /-- For a symmetric operator `T`, the function `λ x, ⟪T x, x⟫` is real-valued. -/ @[simp] lemma is_symmetric.coe_re_apply_inner_self_apply {T : E →L[𝕜] E} (hT : is_symmetric (T : E →ₗ[𝕜] E)) (x : E) : (T.re_apply_inner_self x : 𝕜) = ⟪T x, x⟫ := begin rsuffices ⟨r, hr⟩ : ∃ r : ℝ, ⟪T x, x⟫ = r, { simp [hr, T.re_apply_inner_self_apply] }, rw ← eq_conj_iff_real, exact hT.conj_inner_sym x x end /-- If a symmetric operator preserves a submodule, its restriction to that submodule is symmetric. -/ lemma is_symmetric.restrict_invariant {T : E →ₗ[𝕜] E} (hT : is_symmetric T) {V : submodule 𝕜 E} (hV : ∀ v ∈ V, T v ∈ V) : is_symmetric (T.restrict hV) := λ v w, hT v w lemma is_symmetric.restrict_scalars {T : E →ₗ[𝕜] E} (hT : T.is_symmetric) : @linear_map.is_symmetric ℝ E _ (inner_product_space.is_R_or_C_to_real 𝕜 E) (@linear_map.restrict_scalars ℝ 𝕜 _ _ _ _ _ _ (inner_product_space.is_R_or_C_to_real 𝕜 E).to_module (inner_product_space.is_R_or_C_to_real 𝕜 E).to_module _ _ _ T) := λ x y, by simp [hT x y, real_inner_eq_re_inner, linear_map.coe_restrict_scalars_eq_coe] section complex variables {V : Type*} [inner_product_space ℂ V] /-- A linear operator on a complex inner product space is symmetric precisely when `⟪T v, v⟫_ℂ` is real for all v.-/ lemma is_symmetric_iff_inner_map_self_real (T : V →ₗ[ℂ] V): is_symmetric T ↔ ∀ (v : V), conj ⟪T v, v⟫_ℂ = ⟪T v, v⟫_ℂ := begin split, { intros hT v, apply is_symmetric.conj_inner_sym hT }, { intros h x y, nth_rewrite 1 ← inner_conj_sym, nth_rewrite 1 inner_map_polarization, simp only [star_ring_end_apply, star_div', star_sub, star_add, star_mul], simp only [← star_ring_end_apply], rw [h (x + y), h (x - y), h (x + complex.I • y), h (x - complex.I • y)], simp only [complex.conj_I], rw inner_map_polarization', norm_num, ring }, end end complex end linear_map
085c03ed0258a78a5ca5542d7c28d52562f214ce
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/field_theory/subfield.lean
ac87fc636da1ed2f6e571bb4037a65fdc4886367
[ "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
4,455
lean
/- Copyright (c) 2018 Andreas Swerdlow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andreas Swerdlow -/ import ring_theory.subring variables {F : Type*} [field F] (S : set F) section prio set_option default_priority 100 -- see Note [default priority] class is_subfield extends is_subring S : Prop := (inv_mem : ∀ {x : F}, x ∈ S → x⁻¹ ∈ S) end prio instance is_subfield.field [is_subfield S] : field S := { inv := λ x, ⟨x⁻¹, is_subfield.inv_mem x.2⟩, zero_ne_one := λ h : 0 = 1, (@zero_ne_one F _) (subtype.ext.1 h), mul_inv_cancel := λ a ha, subtype.ext.2 (mul_inv_cancel (λ h, ha $ subtype.ext.2 h)), inv_zero := subtype.ext.2 inv_zero, ..show comm_ring S, by apply_instance } instance univ.is_subfield : is_subfield (@set.univ F) := { inv_mem := by intros; trivial } /- note: in the next two declarations, if we let type-class inference figure out the instance `is_ring_hom.is_subring_preimage` then that instance only applies when particular instances of `is_add_subgroup _` and `is_submonoid _` are chosen (which are not the default ones). If we specify it explicitly, then it doesn't complain. -/ instance preimage.is_subfield {K : Type*} [field K] (f : F →+* K) (s : set K) [is_subfield s] : is_subfield (f ⁻¹' s) := { inv_mem := λ a (ha : f a ∈ s), show f a⁻¹ ∈ s, by { rw [f.map_inv], exact is_subfield.inv_mem ha }, ..f.is_subring_preimage s } instance image.is_subfield {K : Type*} [field K] (f : F →+* K) (s : set F) [is_subfield s] : is_subfield (f '' s) := { inv_mem := λ a ⟨x, xmem, ha⟩, ⟨x⁻¹, is_subfield.inv_mem xmem, ha ▸ f.map_inv⟩, ..f.is_subring_image s } instance range.is_subfield {K : Type*} [field K] (f : F →+* K) : is_subfield (set.range f) := by { rw ← set.image_univ, apply_instance } namespace field def closure : set F := { x | ∃ y ∈ ring.closure S, ∃ z ∈ ring.closure S, y / z = x } variables {S} theorem ring_closure_subset : ring.closure S ⊆ closure S := λ x hx, ⟨x, hx, 1, is_submonoid.one_mem _, div_one x⟩ instance closure.is_submonoid : is_submonoid (closure S) := { mul_mem := by rintros _ _ ⟨p, hp, q, hq, hq0, rfl⟩ ⟨r, hr, s, hs, hs0, rfl⟩; exact ⟨p * r, is_submonoid.mul_mem hp hr, q * s, is_submonoid.mul_mem hq hs, (div_mul_div _ _ _ _).symm⟩, one_mem := ring_closure_subset $ is_submonoid.one_mem _ } instance closure.is_subfield : is_subfield (closure S) := have h0 : (0:F) ∈ closure S, from ring_closure_subset $ is_add_submonoid.zero_mem _, { add_mem := begin intros a b ha hb, rcases (id ha) with ⟨p, hp, q, hq, rfl⟩, rcases (id hb) with ⟨r, hr, s, hs, rfl⟩, classical, by_cases hq0 : q = 0, by simp [hb, hq0], by_cases hs0 : s = 0, by simp [ha, hs0], exact ⟨p * s + q * r, is_add_submonoid.add_mem (is_submonoid.mul_mem hp hs) (is_submonoid.mul_mem hq hr), q * s, is_submonoid.mul_mem hq hs, (div_add_div p r hq0 hs0).symm⟩ end, zero_mem := h0, neg_mem := begin rintros _ ⟨p, hp, q, hq, rfl⟩, exact ⟨-p, is_add_subgroup.neg_mem hp, q, hq, neg_div q p⟩ end, inv_mem := begin rintros _ ⟨p, hp, q, hq, rfl⟩, classical, by_cases hp0 : p = 0, by simp [hp0, h0], exact ⟨q, hq, p, hp, inv_div.symm⟩ end } theorem mem_closure {a : F} (ha : a ∈ S) : a ∈ closure S := ring_closure_subset $ ring.mem_closure ha theorem subset_closure : S ⊆ closure S := λ _, mem_closure theorem closure_subset {T : set F} [is_subfield T] (H : S ⊆ T) : closure S ⊆ T := by rintros _ ⟨p, hp, q, hq, hq0, rfl⟩; exact is_submonoid.mul_mem (ring.closure_subset H hp) (is_subfield.inv_mem $ ring.closure_subset H hq) theorem closure_subset_iff (s t : set F) [is_subfield t] : closure s ⊆ t ↔ s ⊆ t := ⟨set.subset.trans subset_closure, closure_subset⟩ theorem closure_mono {s t : set F} (H : s ⊆ t) : closure s ⊆ closure t := closure_subset $ set.subset.trans H subset_closure end field lemma is_subfield_Union_of_directed {ι : Type*} [hι : nonempty ι] (s : ι → set F) [∀ i, is_subfield (s i)] (directed : ∀ i j, ∃ k, s i ⊆ s k ∧ s j ⊆ s k) : is_subfield (⋃i, s i) := { inv_mem := λ x hx, let ⟨i, hi⟩ := set.mem_Union.1 hx in set.mem_Union.2 ⟨i, is_subfield.inv_mem hi⟩, to_is_subring := is_subring_Union_of_directed s directed }
7f6b7f71623ad47bbcc2fde69ce1fece576edf5b
4727251e0cd73359b15b664c3170e5d754078599
/src/tactic/replacer.lean
4d4d3944753670c43100998bfe9c3ee128b192de
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
5,813
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import tactic.core /-! # `def_replacer` A mechanism for defining tactics for use in auto params, whose meaning is defined incrementally through attributes. -/ namespace tactic meta def replacer_core {α : Type} [reflected α] (ntac : name) (eval : ∀ β [reflected β], expr → tactic β) : list name → tactic α | [] := fail ("no implementation defined for " ++ to_string ntac) | (n::ns) := do d ← get_decl n, let t := d.type, tac ← do { mk_const n >>= eval (tactic α) } <|> do { tac ← mk_const n >>= eval (tactic α → tactic α), return (tac (replacer_core ns)) } <|> do { tac ← mk_const n >>= eval (option (tactic α) → tactic α), return (tac (guard (ns ≠ []) >> some (replacer_core ns))) }, tac meta def replacer (ntac : name) {α : Type} [reflected α] (F : Type → Type) (eF : ∀ β, reflected β → reflected (F β)) (R : ∀ β, F β → β) : tactic α := attribute.get_instances ntac >>= replacer_core ntac (λ β eβ e, R β <$> @eval_expr' (F β) (eF β eβ) e) meta def mk_replacer₁ : expr → nat → expr × expr | (expr.pi n bi d b) i := let (e₁, e₂) := mk_replacer₁ b (i+1) in (expr.pi n bi d e₁, (`(expr.pi n bi d) : expr) e₂) | _ i := (expr.var i, expr.var 0) meta def mk_replacer₂ (ntac : name) (v : expr × expr) : expr → nat → option expr | (expr.pi n bi d b) i := do b' ← mk_replacer₂ b (i+1), some (expr.lam n bi d b') | `(tactic %%β) i := some $ (expr.const ``replacer []).mk_app [ reflect ntac, β, reflect β, expr.lam `γ binder_info.default `(Type) v.1, expr.lam `γ binder_info.default `(Type) $ expr.lam `eγ binder_info.inst_implicit ((`(@reflected Type) : expr) β) v.2, expr.lam `γ binder_info.default `(Type) $ expr.lam `f binder_info.default v.1 $ (list.range i).foldr (λ i e', e' (expr.var (i+2))) (expr.var 0) ] | _ i := none meta def mk_replacer (ntac : name) (e : expr) : tactic expr := mk_replacer₂ ntac (mk_replacer₁ e 0) e 0 meta def valid_types : expr → list expr | (expr.pi n bi d b) := expr.pi n bi d <$> valid_types b | `(tactic %%β) := [`(tactic.{0} %%β), `(tactic.{0} %%β → tactic.{0} %%β), `(option (tactic.{0} %%β) → tactic.{0} %%β)] | _ := [] meta def replacer_attr (ntac : name) : user_attribute := { name := ntac, descr := "Replaces the definition of `" ++ to_string ntac ++ "`. This should be " ++ "applied to a definition with the type `tactic unit`, which will be " ++ "called whenever `" ++ to_string ntac ++ "` is called. The definition " ++ "can optionally have an argument of type `tactic unit` or " ++ "`option (tactic unit)` which refers to the previous definition, if any.", after_set := some $ λ n _ _, do d ← get_decl n, base ← get_decl ntac, guardb ((valid_types base.type).any (=ₐ d.type)) <|> fail format!"incorrect type for @[{ntac}]" } /-- Define a new replaceable tactic. -/ meta def def_replacer (ntac : name) (ty : expr) : tactic unit := let nattr := ntac <.> "attr" in do add_meta_definition nattr [] `(user_attribute) `(replacer_attr %%(reflect ntac)), set_basic_attribute `user_attribute nattr tt, v ← mk_replacer ntac ty, add_meta_definition ntac [] ty v, add_doc_string ntac $ "The `" ++ to_string ntac ++ "` tactic is a \"replaceable\" " ++ "tactic, which means that its meaning is defined by tactics that " ++ "are defined later with the `@[" ++ to_string ntac ++ "]` attribute. " ++ "It is intended for use with `auto_param`s for structure fields." setup_tactic_parser /-- `def_replacer foo` sets up a stub definition `foo : tactic unit`, which can effectively be defined and re-defined later, by tagging definitions with `@[foo]`. - `@[foo] meta def foo_1 : tactic unit := ...` replaces the current definition of `foo`. - `@[foo] meta def foo_2 (old : tactic unit) : tactic unit := ...` replaces the current definition of `foo`, and provides access to the previous definition via `old`. (The argument can also be an `option (tactic unit)`, which is provided as `none` if this is the first definition tagged with `@[foo]` since `def_replacer` was invoked.) `def_replacer foo : α → β → tactic γ` allows the specification of a replacer with custom input and output types. In this case all subsequent redefinitions must have the same type, or the type `α → β → tactic γ → tactic γ` or `α → β → option (tactic γ) → tactic γ` analogously to the previous cases. -/ @[user_command] meta def def_replacer_cmd (_ : parse $ tk "def_replacer") : lean.parser unit := do ntac ← ident, ty ← optional (tk ":" *> types.texpr), match ty with | (some p) := do t ← to_expr p, def_replacer ntac t | none := def_replacer ntac `(tactic unit) end add_tactic_doc { name := "def_replacer", category := doc_category.cmd, decl_names := [`tactic.def_replacer_cmd], tags := ["environment", "renaming"] } meta def unprime : name → tactic name | nn@(name.mk_string s n) := let s' := (s.split_on ''').head in if s'.length < s.length then pure (name.mk_string s' n) else fail format!"expecting primed name: {nn}" | n := fail format!"invalid name: {n}" @[user_attribute] meta def replaceable_attr : user_attribute := { name := `replaceable, descr := "make definition replaceable in dependent modules", after_set := some $ λ n' _ _, do { n ← unprime n', d ← get_decl n', «def_replacer» n d.type, (replacer_attr n).set n' () tt } } end tactic
986838c4373bdf06d699451cbe57425c956b2c13
367134ba5a65885e863bdc4507601606690974c1
/src/algebraic_geometry/Scheme.lean
cff30c009b1628bcc22f83cd03bf74e6b822a64d
[ "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
3,814
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 algebraic_geometry.Spec /-! # The category of schemes A scheme is a locally ringed space such that every point is contained in some open set where there is an isomorphism of presheaves between the restriction to that open set, and the structure sheaf of `Spec R`, for some commutative ring `R`. A morphism of schemes is just a morphism of the underlying locally ringed spaces. -/ open topological_space open category_theory open Top open opposite namespace algebraic_geometry /-- We define `Scheme` as a `X : LocallyRingedSpace`, along with a proof that every point has an open neighbourhood `U` so that that the restriction of `X` to `U` is isomorphic, as a space with a presheaf of commutative rings, to `Spec.PresheafedSpace R` for some `R : CommRing`. (Note we're not asking in the definition that this is an isomorphism as locally ringed spaces, although that is a consequence.) -/ structure Scheme extends X : LocallyRingedSpace := (local_affine : ∀ x : carrier, ∃ (U : opens carrier) (m : x ∈ U) (R : CommRing) (i : X.to_SheafedSpace.to_PresheafedSpace.restrict _ (opens.inclusion_open_embedding U) ≅ Spec.PresheafedSpace R), true) -- PROJECT -- In fact, we can make the isomorphism `i` above an isomorphism in `LocallyRingedSpace`. -- However this is a consequence of the above definition, and not necessary for defining schemes. -- We haven't done this yet because we haven't shown that you can restrict a `LocallyRingedSpace` -- along an open embedding. -- We can do this already for `SheafedSpace` (as above), but we need to know that -- the stalks of the restriction are still local rings, which we follow if we knew that -- the stalks didn't change. -- This will follow if we define cofinal functors, and show precomposing with a cofinal functor -- doesn't change colimits, because open neighbourhoods of `x` within `U` are cofinal in -- all open neighbourhoods of `x`. namespace Scheme /-- Every `Scheme` is a `LocallyRingedSpace`. -/ -- (This parent projection is apparently not automatically generated because -- we used the `extends X : LocallyRingedSpace` syntax.) def to_LocallyRingedSpace (S : Scheme) : LocallyRingedSpace := { ..S } /-- `Spec R` as a `Scheme`. -/ noncomputable def Spec (R : CommRing) : Scheme := { local_affine := λ x, ⟨⊤, trivial, R, (Spec.PresheafedSpace R).restrict_top_iso, trivial⟩, .. Spec.LocallyRingedSpace R } /-- The empty scheme, as `Spec 0`. -/ noncomputable def empty : Scheme := Spec (CommRing.of punit) noncomputable instance : has_emptyc Scheme := ⟨empty⟩ noncomputable instance : inhabited Scheme := ⟨∅⟩ /-- Schemes are a full subcategory of locally ringed spaces. -/ instance : category Scheme := induced_category.category Scheme.to_LocallyRingedSpace /-- The global sections, notated Gamma. -/ def Γ : Schemeᵒᵖ ⥤ CommRing := (induced_functor Scheme.to_LocallyRingedSpace).op ⋙ LocallyRingedSpace.Γ lemma Γ_def : Γ = (induced_functor Scheme.to_LocallyRingedSpace).op ⋙ LocallyRingedSpace.Γ := rfl @[simp] lemma Γ_obj (X : Schemeᵒᵖ) : Γ.obj X = (unop X).presheaf.obj (op ⊤) := rfl lemma Γ_obj_op (X : Scheme) : Γ.obj (op X) = X.presheaf.obj (op ⊤) := rfl @[simp] lemma Γ_map {X Y : Schemeᵒᵖ} (f : X ⟶ Y) : Γ.map f = f.unop.1.c.app (op ⊤) ≫ (unop Y).presheaf.map (opens.le_map_top _ _).op := rfl lemma Γ_map_op {X Y : Scheme} (f : X ⟶ Y) : Γ.map f.op = f.1.c.app (op ⊤) ≫ X.presheaf.map (opens.le_map_top _ _).op := rfl -- PROJECTS: -- 1. Make `Spec` a functor. -- 2. Construct `Spec ≫ Γ ≅ functor.id _`. -- 3. Adjunction between `Γ` and `Spec`. -- end Scheme end algebraic_geometry