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
2435597d9e53d00397bd79e9a3f4dbfee4642c1f
95dcf8dea2baf2b4b0a60d438f27c35ae3dd3990
/src/topology/instances/nnreal.lean
9ea710aa3e6b6baef9aa93e5ce22fae543b045e0
[ "Apache-2.0" ]
permissive
uniformity1/mathlib
829341bad9dfa6d6be9adaacb8086a8a492e85a4
dd0e9bd8f2e5ec267f68e72336f6973311909105
refs/heads/master
1,588,592,015,670
1,554,219,842,000
1,554,219,842,000
179,110,702
0
0
Apache-2.0
1,554,220,076,000
1,554,220,076,000
null
UTF-8
Lean
false
false
3,976
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin Nonnegative real numbers. -/ import data.real.nnreal topology.instances.real topology.algebra.infinite_sum noncomputable theory open set topological_space metric namespace nnreal local notation ` ℝ≥0 ` := nnreal instance : topological_space ℝ≥0 := infer_instance instance : topological_semiring ℝ≥0 := { continuous_mul := continuous_subtype_mk _ (continuous_mul (continuous.comp continuous_fst continuous_subtype_val) (continuous.comp continuous_snd continuous_subtype_val)), continuous_add := continuous_subtype_mk _ (continuous_add (continuous.comp continuous_fst continuous_subtype_val) (continuous.comp continuous_snd continuous_subtype_val)) } instance : second_countable_topology nnreal := topological_space.subtype.second_countable_topology _ _ instance : orderable_topology ℝ≥0 := ⟨ le_antisymm begin apply induced_le_iff_le_coinduced.2, rw [orderable_topology.topology_eq_generate_intervals ℝ], apply generate_from_le, assume s hs, rcases hs with ⟨a, rfl | rfl⟩, { show topological_space.generate_open _ {b : ℝ≥0 | a < b }, by_cases ha : 0 ≤ a, { exact topological_space.generate_open.basic _ ⟨⟨a, ha⟩, or.inl rfl⟩ }, { have : a < 0, from lt_of_not_ge ha, have : {b : ℝ≥0 | a < b } = set.univ, from (set.eq_univ_iff_forall.2 $ assume b, lt_of_lt_of_le this b.2), rw [this], exact topological_space.generate_open.univ _ } }, { show (topological_space.generate_from _).is_open {b : ℝ≥0 | a > b }, by_cases ha : 0 ≤ a, { exact topological_space.generate_open.basic _ ⟨⟨a, ha⟩, or.inr rfl⟩ }, { have : {b : ℝ≥0 | a > b } = ∅, from (set.eq_empty_iff_forall_not_mem.2 $ assume b hb, ha $ show 0 ≤ a, from le_trans b.2 (le_of_lt hb)), rw [this], apply @is_open_empty } }, end (generate_from_le $ assume s hs, match s, hs with | _, ⟨⟨a, ha⟩, or.inl rfl⟩ := ⟨{b : ℝ | a < b}, is_open_lt' a, rfl⟩ | _, ⟨⟨a, ha⟩, or.inr rfl⟩ := ⟨{b : ℝ | b < a}, is_open_gt' a, set.ext $ assume b, iff.refl _⟩ end) ⟩ section coe variable {α : Type*} open filter lemma continuous_of_real : continuous nnreal.of_real := continuous_subtype_mk _ $ continuous_max continuous_id continuous_const lemma continuous_coe : continuous (coe : nnreal → ℝ) := continuous_subtype_val lemma tendsto_coe {f : filter α} {m : α → nnreal} : ∀{x : nnreal}, tendsto (λa, (m a : ℝ)) f (nhds (x : ℝ)) ↔ tendsto m f (nhds x) | ⟨r, hr⟩ := by rw [nhds_subtype_eq_comap, tendsto_comap_iff]; refl lemma tendsto_of_real {f : filter α} {m : α → ℝ} {x : ℝ} (h : tendsto m f (nhds x)): tendsto (λa, nnreal.of_real (m a)) f (nhds (nnreal.of_real x)) := h.comp (continuous_iff_continuous_at.1 continuous_of_real _) lemma tendsto_sub {f : filter α} {m n : α → nnreal} {r p : nnreal} (hm : tendsto m f (nhds r)) (hn : tendsto n f (nhds p)) : tendsto (λa, m a - n a) f (nhds (r - p)) := tendsto_of_real $ tendsto_sub (tendsto_coe.2 hm) (tendsto_coe.2 hn) lemma is_sum_coe {f : α → nnreal} {r : nnreal} : is_sum (λa, (f a : ℝ)) (r : ℝ) ↔ is_sum f r := by simp [is_sum, sum_coe.symm, tendsto_coe] lemma has_sum_coe {f : α → nnreal} : has_sum (λa, (f a : ℝ)) ↔ has_sum f := begin simp [has_sum], split, exact assume ⟨a, ha⟩, ⟨⟨a, is_sum_le (λa, (f a).2) is_sum_zero ha⟩, is_sum_coe.1 ha⟩, exact assume ⟨a, ha⟩, ⟨a.1, is_sum_coe.2 ha⟩ end lemma tsum_coe {f : α → nnreal} (hf : has_sum f) : (∑a, (f a : ℝ)) = ↑(∑a, f a) := tsum_eq_is_sum $ is_sum_coe.2 $ is_sum_tsum $ hf end coe end nnreal
5803a13bcbf792870c510d514a7a6e5a20f00ca0
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/tests/lean/extra/num_norm1.lean
422a19632ee38e07b18499e92771baa10a3e4591
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,640
lean
import algebra.numeral data.real open algebra real /- variable {A : Type} variable [s : linear_ordered_field A] include s-/ notation `A` := real example : (-1 :A) * 1 = -1 := by norm_num example : (-2 :A) * 1 = -2 := by norm_num example : (-2 :A) * -1 = 2 := by norm_num example : (-2 :A) * -2 = 4 := by norm_num example : (1 : A) * 0 = 0 := by norm_num example : ((1 : A) + 1) * 5 = 6 + 4 := by norm_num example : (1 : A) = 0 + 1 := by norm_num example : (1 : A) = 1 + 0 := by norm_num example : (2 : A) = 1 + 1 := by norm_num example : (2 : A) = 0 + 2 := by norm_num example : (3 : A) = 1 + 2 := by norm_num example : (3 : A) = 2 + 1 := by norm_num example : (4 : A) = 3 + 1 := by norm_num example : (4 : A) = 2 + 2 := by norm_num example : (5 : A) = 4 + 1 := by norm_num example : (5 : A) = 3 + 2 := by norm_num example : (5 : A) = 2 + 3 := by norm_num example : (6 : A) = 0 + 6 := by norm_num example : (6 : A) = 3 + 3 := by norm_num example : (6 : A) = 4 + 2 := by norm_num example : (6 : A) = 5 + 1 := by norm_num example : (7 : A) = 4 + 3 := by norm_num example : (7 : A) = 1 + 6 := by norm_num example : (7 : A) = 6 + 1 := by norm_num example : 33 = 5 + (28 : A) := by norm_num example : (12 : A) = 0 + (2 + 3) + 7 := by norm_num example : (105 : A) = 70 + (33 + 2) := by norm_num theorem name : (45000000000 : A) = 23000000000 + 22000000000 := by norm_num example : (0 : A) - 3 = -3 := by norm_num example : (0 : A) - 2 = -2 := by norm_num example : (1 : A) - 3 = -2 := by norm_num example : (1 : A) - 1 = 0 := by norm_num example : (0 : A) - 3 = -3 := by norm_num example : (0 : A) - 3 = -3 := by norm_num example : (12 : A) - 4 - (5 + -2) = 5 := by norm_num example : (12 : A) - 4 - (5 + -2) - 20 = -15 := by norm_num example : (0 : A) * 0 = 0 := by norm_num example : (0 : A) * 1 = 0 := by norm_num example : (0 : A) * 2 = 0 := by norm_num example : (2 : A) * 0 = 0 := by norm_num example : (1 : A) * 0 = 0 := by norm_num example : (1 : A) * 1 = 1 := by norm_num example : (2 : A) * 1 = 2 := by norm_num example : (1 : A) * 2 = 2 := by norm_num example : (2 : A) * 2 = 4 := by norm_num example : (3 : A) * 2 = 6 := by norm_num example : (2 : A) * 3 = 6 := by norm_num example : (4 : A) * 1 = 4 := by norm_num example : (1 : A) * 4 = 4 := by norm_num example : (3 : A) * 3 = 9 := by norm_num example : (3 : A) * 4 = 12 := by norm_num example : (4 : A) * 4 = 16 := by norm_num example : (11 : A) * 2 = 22 := by norm_num example : (15 : A) * 6 = 90 := by norm_num example : (123456 : A) * 123456 = 15241383936 := by norm_num example : (4 : A) / 2 = 2 := by norm_num example : (4 : A) / 1 = 4 := by norm_num example : (4 : A) / 3 = 4 / 3 := by norm_num example : (50 : A) / 5 = 10 := by norm_num example : (1056 : A) / 1 = 1056 := by norm_num example : (6 : A) / 4 = 3/2 := by norm_num example : (0 : A) / 3 = 0 := by norm_num --example : (3 : A) / 0 = 0 := by norm_num -- this should fail example : (9 * 9 * 9) * (12 : A) / 27 = 81 * (2 + 2) := by norm_num example : (-2 : A) * 4 / 3 = -8 / 3 := by norm_num example : - (-4 / 3) = 1 / (3 / (4 : A)) := by norm_num -- auto gen tests example : ((25 * (1 / 1)) + (30 - 16)) = (39 : A) := by norm_num example : ((19 * (- 2 - 3)) / 6) = (-95/6 : A) := by norm_num example : - (3 * 28) = (-84 : A) := by norm_num example : - - (16 / ((11 / (- - (6 * 19) + 12)) * 21)) = (96/11 : A) := by norm_num example : (- (- 21 + 24) - - (- - (28 + (- 21 / - (16 / ((1 * 26) * ((0 * - 11) + 13))))) * 21)) = (79209/8 : A) := by norm_num example : (27 * (((16 + - (12 + 4)) + (22 - - 19)) - 23)) = (486 : A) := by norm_num example : - (13 * (- 30 / ((7 / 24) + - 7))) = (-9360/161 : A) := by norm_num example : - (0 + 20) = (-20 : A) := by norm_num example : (- 2 - (27 + (((2 / 14) - (7 + 21)) + (16 - - - 14)))) = (-22/7 : A) := by norm_num example : (25 + ((8 - 2) + 16)) = (47 : A) := by norm_num example : (- - 26 / 27) = (26/27 : A) := by norm_num example : ((((16 * (22 / 14)) - 18) / 11) + 30) = (2360/77 : A) := by norm_num example : (((- 28 * 28) / (29 - 24)) * 24) = (-18816/5 : A) := by norm_num example : ((- (18 - ((- - (10 + - 2) - - (23 / 5)) / 5)) - (21 * 22)) - (((20 / - ((((19 + 18) + 15) + 3) + - 22)) + 14) / 17)) = (-394571/825 : A) := by norm_num example : ((3 + 25) - - 4) = (32 : A) := by norm_num example : ((1 - 0) - 22) = (-21 : A) := by norm_num example : (((- (8 / 7) / 14) + 20) + 22) = (2054/49 : A) := by norm_num example : ((21 / 20) - 29) = (-559/20 : A) := by norm_num example : - - 20 = (20 : A) := by norm_num example : (24 - (- 9 / 4)) = (105/4 : A) := by norm_num example : (((7 / ((23 * 19) + (27 * 10))) - ((28 - - 15) * 24)) + (9 / - (10 * - 3))) = (-1042007/1010 : A) := by norm_num example : (26 - (- 29 + (12 / 25))) = (1363/25 : A) := by norm_num example : ((11 * 27) / (4 - 5)) = (-297 : A) := by norm_num example : (24 - (9 + 15)) = (0 : A) := by norm_num example : (- 9 - - 0) = (-9 : A) := by norm_num example : (- 10 / (30 + 10)) = (-1/4 : A) := by norm_num example : (22 - (6 * (28 * - 8))) = (1366 : A) := by norm_num example : ((- - 2 * (9 * - 3)) + (22 / 30)) = (-799/15 : A) := by norm_num example : - (26 / ((3 + 7) / - (27 * (12 / - 16)))) = (-1053/20 : A) := by norm_num example : ((- 29 / 1) + 28) = (-1 : A) := by norm_num example : ((21 * ((10 - (((17 + 28) - - 0) + 20)) + 26)) + ((17 + - 16) * 7)) = (-602 : A) := by norm_num example : (((- 5 - ((24 + - - 8) + 3)) + 20) + - 23) = (-43 : A) := by norm_num example : ((- ((14 - 15) * (14 + 8)) + ((- (18 - 27) - 0) + 12)) - 11) = (32 : A) := by norm_num example : (((15 / 17) * (26 / 27)) + 28) = (4414/153 : A) := by norm_num example : (14 - ((- 16 - 3) * - (20 * 19))) = (-7206 : A) := by norm_num example : (21 - - - (28 - (12 * 11))) = (125 : A) := by norm_num example : ((0 + (7 + (25 + 8))) * - (11 * 27)) = (-11880 : A) := by norm_num example : (19 * - 5) = (-95 : A) := by norm_num example : (29 * - 8) = (-232 : A) := by norm_num example : ((22 / 9) - 29) = (-239/9 : A) := by norm_num example : (3 + (19 / 12)) = (55/12 : A) := by norm_num example : - (13 + 30) = (-43 : A) := by norm_num example : - - - (((21 * - - ((- 25 - (- (30 - 5) / (- 5 - 5))) / (((6 + ((25 * - 13) + 22)) - 3) / 2))) / (- 3 / 10)) * (- 8 - 0)) = (-308/3 : A) := by norm_num example : - (2 * - (- 24 * 22)) = (-1056 : A) := by norm_num example : - - (((28 / - ((- 13 * - 5) / - (((7 - 30) / 16) + 6))) * 0) - 24) = (-24 : A) := by norm_num example : ((13 + 24) - (27 / (21 * 13))) = (3358/91 : A) := by norm_num example : ((3 / - 21) * 25) = (-25/7 : A) := by norm_num example : (17 - (29 - 18)) = (6 : A) := by norm_num example : ((28 / 20) * 15) = (21 : A) := by norm_num example : ((((26 * (- (23 - 13) - 3)) / 20) / (14 - (10 + 20))) / ((16 / 6) / (16 * - (3 / 28)))) = (-1521/2240 : A) := by norm_num example : (46 / (- ((- 17 * 28) - 77) + 87)) = (23/320 : A) := by norm_num example : (73 * - (67 - (74 * - - 11))) = (54531 : A) := by norm_num example : ((8 * (25 / 9)) + 59) = (731/9 : A) := by norm_num example : - ((59 + 85) * - 70) = (10080 : A) := by norm_num example : (66 + (70 * 58)) = (4126 : A) := by norm_num example : (- - 49 * 0) = (0 : A) := by norm_num example : ((- 78 - 69) * 9) = (-1323 : A) := by norm_num example : - - (7 - - (50 * 79)) = (3957 : A) := by norm_num example : - (85 * (((4 * 93) * 19) * - 31)) = (18624180 : A) := by norm_num example : (21 + (- 5 / ((74 * 85) / 45))) = (26373/1258 : A) := by norm_num example : (42 - ((27 + 64) + 26)) = (-75 : A) := by norm_num example : (- ((38 - - 17) + 86) - (74 + 58)) = (-273 : A) := by norm_num example : ((29 * - (75 + - 68)) + (- 41 / 28)) = (-5725/28 : A) := by norm_num example : (- - (40 - 11) - (68 * 86)) = (-5819 : A) := by norm_num example : (6 + ((65 - 14) + - 89)) = (-32 : A) := by norm_num example : (97 * - (29 * 35)) = (-98455 : A) := by norm_num example : - (66 / 33) = (-2 : A) := by norm_num example : - ((94 * 89) + (79 - (23 - (((- 1 / 55) + 95) * (28 - (54 / - - - 22)))))) = (-1369070/121 : A) := by norm_num example : (- 23 + 61) = (38 : A) := by norm_num example : - (93 / 69) = (-31/23 : A) := by norm_num example : (- - ((68 / (39 + (((45 * - (59 - (37 + 35))) / (53 - 75)) - - (100 + - (50 / (- 30 - 59)))))) - (69 - (23 * 30))) / (57 + 17)) = (137496481/16368578 : A) := by norm_num example : (- 19 * - - (75 * - - 41)) = (-58425 : A) := by norm_num example : ((3 / ((- 28 * 45) * (19 + ((- (- 88 - (- (- 1 + 90) + 8)) + 87) * 48)))) + 1) = (1903019/1903020 : A) := by norm_num example : ((- - (28 + 48) / 75) + ((- 59 - 14) - 0)) = (-5399/75 : A) := by norm_num example : (- ((- (((66 - 86) - 36) / 94) - 3) / - - (77 / (56 - - - 79))) + 87) = (312254/3619 : A) := by norm_num
8143c39258fd1e87f6f7058e05036cef32c6c4fa
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/stage0/src/Init/Control/Basic.lean
b242bbd8dfd402c909c11dcd9e3f79d183ee79d7
[ "Apache-2.0" ]
permissive
dupuisf/lean4
d082d13b01243e1de29ae680eefb476961221eef
6a39c65bd28eb0e28c3870188f348c8914502718
refs/heads/master
1,676,948,755,391
1,610,665,114,000
1,610,665,114,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,628
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura, Sebastian Ullrich -/ prelude import Init.Core universes u v w @[reducible] def Functor.mapRev {f : Type u → Type v} [Functor f] {α β : Type u} : f α → (α → β) → f β := fun a f => f <$> a infixr:100 " <&> " => Functor.mapRev @[inline] def Functor.discard {f : Type u → Type v} {α : Type u} [Functor f] (x : f α) : f PUnit := Functor.mapConst PUnit.unit x export Functor (discard) @[macroInline] def when {m : Type → Type u} [Applicative m] (c : Prop) [h : Decidable c] (t : m Unit) : m Unit := if c then t else pure () @[macroInline] def «unless» {m : Type → Type u} [Applicative m] (c : Prop) [h : Decidable c] (e : m Unit) : m Unit := if c then pure () else e class Alternative (f : Type u → Type v) extends Applicative f : Type (max (u+1) v) where failure : {α : Type u} → f α orElse : {α : Type u} → f α → f α → f α instance (f : Type u → Type v) (α : Type u) [Alternative f] : OrElse (f α) := ⟨Alternative.orElse⟩ variables {f : Type u → Type v} [Alternative f] {α : Type u} export Alternative (failure) @[inline] def guard {f : Type → Type v} [Alternative f] (p : Prop) [Decidable p] : f Unit := if p then pure () else failure @[inline] def optional (x : f α) : f (Option α) := some <$> x <|> pure none class ToBool (α : Type u) where toBool : α → Bool export ToBool (toBool) instance : ToBool Bool where toBool b := b @[macroInline] def bool {β : Type u} {α : Type v} [ToBool β] (f t : α) (b : β) : α := match toBool b with | true => t | false => f @[macroInline] def orM {m : Type u → Type v} {β : Type u} [Monad m] [ToBool β] (x y : m β) : m β := do let b ← x match toBool b with | true => pure b | false => y infixr:30 " <||> " => orM @[macroInline] def andM {m : Type u → Type v} {β : Type u} [Monad m] [ToBool β] (x y : m β) : m β := do let b ← x match toBool b with | true => y | false => pure b infixr:35 " <&&> " => andM @[macroInline] def notM {m : Type → Type v} [Applicative m] (x : m Bool) : m Bool := not <$> x class MonadControl (m : Type u → Type v) (n : Type u → Type w) where stM : Type u → Type u liftWith : {α : Type u} → (({β : Type u} → n β → m (stM β)) → m α) → n α restoreM : {α : Type u} → m (stM α) → n α class MonadControlT (m : Type u → Type v) (n : Type u → Type w) where stM : Type u → Type u liftWith : {α : Type u} → (({β : Type u} → n β → m (stM β)) → m α) → n α restoreM {α : Type u} : stM α → n α export MonadControlT (stM liftWith restoreM) instance (m n o) [MonadControl n o] [MonadControlT m n] : MonadControlT m o where stM α := stM m n (MonadControl.stM n o α) liftWith f := MonadControl.liftWith fun x₂ => liftWith fun x₁ => f (x₁ ∘ x₂) restoreM := MonadControl.restoreM ∘ restoreM instance (m : Type u → Type v) [Pure m] : MonadControlT m m where stM α := α liftWith f := f fun x => x restoreM x := pure x @[inline] def controlAt (m : Type u → Type v) {n : Type u → Type w} [s1 : MonadControlT m n] [s2 : Bind n] {α : Type u} (f : ({β : Type u} → n β → m (stM m n β)) → m (stM m n α)) : n α := liftWith f >>= restoreM @[inline] def control {m : Type u → Type v} {n : Type u → Type w} [MonadControlT m n] [Bind n] {α : Type u} (f : ({β : Type u} → n β → m (stM m n β)) → m (stM m n α)) : n α := controlAt m f
1ab7281cdda2bc110bc574d244619cd599d41d45
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/data/equiv/list.lean
e70148bb51d68c2f5c85b5b1ded8279b3e7c3a23
[ "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
10,322
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Additional equiv and encodable instances for lists, finsets, and fintypes. -/ import data.equiv.denumerable import data.finset.sort open nat list namespace encodable variables {α : Type*} section list variable [encodable α] def encode_list : list α → ℕ | [] := 0 | (a::l) := succ (mkpair (encode a) (encode_list l)) def decode_list : ℕ → option (list α) | 0 := some [] | (succ v) := match unpair v, unpair_le_right v with | (v₁, v₂), h := have v₂ < succ v, from lt_succ_of_le h, (::) <$> decode α v₁ <*> decode_list v₂ end instance list : encodable (list α) := ⟨encode_list, decode_list, λ l, by induction l with a l IH; simp [encode_list, decode_list, unpair_mkpair, encodek, *]⟩ @[simp] theorem encode_list_nil : encode (@nil α) = 0 := rfl @[simp] theorem encode_list_cons (a : α) (l : list α) : encode (a :: l) = succ (mkpair (encode a) (encode l)) := rfl @[simp] theorem decode_list_zero : decode (list α) 0 = some [] := rfl @[simp] theorem decode_list_succ (v : ℕ) : decode (list α) (succ v) = (::) <$> decode α v.unpair.1 <*> decode (list α) v.unpair.2 := show decode_list (succ v) = _, begin cases e : unpair v with v₁ v₂, simp [decode_list, e], refl end theorem length_le_encode : ∀ (l : list α), length l ≤ encode l | [] := _root_.zero_le _ | (a :: l) := succ_le_succ $ le_trans (length_le_encode l) (le_mkpair_right _ _) end list section finset variables [encodable α] private def enle : α → α → Prop := encode ⁻¹'o (≤) private lemma enle.is_linear_order : is_linear_order α enle := (order_embedding.preimage ⟨encode, encode_injective⟩ (≤)).is_linear_order private def decidable_enle (a b : α) : decidable (enle a b) := by unfold enle order.preimage; apply_instance local attribute [instance] enle.is_linear_order decidable_enle def encode_multiset (s : multiset α) : ℕ := encode (s.sort enle) def decode_multiset (n : ℕ) : option (multiset α) := coe <$> decode (list α) n instance multiset : encodable (multiset α) := ⟨encode_multiset, decode_multiset, λ s, by simp [encode_multiset, decode_multiset, encodek]⟩ end finset def encodable_of_list [decidable_eq α] (l : list α) (H : ∀ x, x ∈ l) : encodable α := ⟨λ a, index_of a l, l.nth, λ a, index_of_nth (H _)⟩ def trunc_encodable_of_fintype (α : Type*) [decidable_eq α] [fintype α] : trunc (encodable α) := @@quot.rec_on_subsingleton _ (λ s : multiset α, (∀ x:α, x ∈ s) → trunc (encodable α)) _ finset.univ.1 (λ l H, trunc.mk $ encodable_of_list l H) finset.mem_univ instance vector [encodable α] {n} : encodable (vector α n) := encodable.subtype instance fin_arrow [encodable α] {n} : encodable (fin n → α) := of_equiv _ (equiv.vector_equiv_fin _ _).symm instance fin_pi (n) (π : fin n → Type*) [∀i, encodable (π i)] : encodable (Πi, π i) := of_equiv _ (equiv.pi_equiv_subtype_sigma (fin n) π) instance array [encodable α] {n} : encodable (array n α) := of_equiv _ (equiv.array_equiv_fin _ _) instance finset [encodable α] : encodable (finset α) := by haveI := decidable_eq_of_encodable α; exact of_equiv {s : multiset α // s.nodup} ⟨λ ⟨a, b⟩, ⟨a, b⟩, λ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, rfl, λ⟨a, b⟩, rfl⟩ def fintype_arrow (α : Type*) (β : Type*) [fintype α] [decidable_eq α] [encodable β] : trunc (encodable (α → β)) := (fintype.equiv_fin α).map $ λf, encodable.of_equiv (fin (fintype.card α) → β) $ equiv.arrow_congr f (equiv.refl _) def fintype_pi (α : Type*) (π : α → Type*) [fintype α] [decidable_eq α] [∀a, encodable (π a)] : trunc (encodable (Πa, π a)) := (encodable.trunc_encodable_of_fintype α).bind $ λa, (@fintype_arrow α (Σa, π a) _ _ (@encodable.sigma _ _ a _)).bind $ λf, trunc.mk $ @encodable.of_equiv _ _ (@encodable.subtype _ _ f _) (equiv.pi_equiv_subtype_sigma α π) /-- The elements of a `fintype` as a sorted list. -/ def sorted_univ (α) [fintype α] [encodable α] : list α := finset.univ.sort (encodable.encode' α ⁻¹'o (≤)) theorem mem_sorted_univ {α} [fintype α] [encodable α] (x : α) : x ∈ sorted_univ α := (finset.mem_sort _).2 (finset.mem_univ _) theorem length_sorted_univ {α} [fintype α] [encodable α] : (sorted_univ α).length = fintype.card α := finset.length_sort _ theorem sorted_univ_nodup {α} [fintype α] [encodable α] : (sorted_univ α).nodup := finset.sort_nodup _ _ /-- An encodable `fintype` is equivalent a `fin`.-/ def fintype_equiv_fin {α} [fintype α] [encodable α] : α ≃ fin (fintype.card α) := begin haveI : decidable_eq α := encodable.decidable_eq_of_encodable _, transitivity, { exact fintype.equiv_fin_of_forall_mem_list mem_sorted_univ (@sorted_univ_nodup α _ _) }, exact equiv.cast (congr_arg _ (@length_sorted_univ α _ _)) end instance fintype_arrow_of_encodable {α β : Type*} [encodable α] [fintype α] [encodable β] : encodable (α → β) := of_equiv (fin (fintype.card α) → β) $ equiv.arrow_congr fintype_equiv_fin (equiv.refl _) end encodable namespace denumerable variables {α : Type*} {β : Type*} [denumerable α] [denumerable β] open encodable section list theorem denumerable_list_aux : ∀ n : ℕ, ∃ a ∈ @decode_list α _ n, encode_list a = n | 0 := ⟨_, rfl, rfl⟩ | (succ v) := begin cases e : unpair v with v₁ v₂, have h := unpair_le_right v, rw e at h, rcases have v₂ < succ v, from lt_succ_of_le h, denumerable_list_aux v₂ with ⟨a, h₁, h₂⟩, simp at h₁, simp [decode_list, e, h₂, h₁, encode_list, mkpair_unpair' e] end instance denumerable_list : denumerable (list α) := ⟨denumerable_list_aux⟩ @[simp] theorem list_of_nat_zero : of_nat (list α) 0 = [] := rfl @[simp] theorem list_of_nat_succ (v : ℕ) : of_nat (list α) (succ v) = of_nat α v.unpair.1 :: of_nat (list α) v.unpair.2 := of_nat_of_decode $ show decode_list (succ v) = _, begin cases e : unpair v with v₁ v₂, simp [decode_list, e], rw [show decode_list v₂ = decode (list α) v₂, from rfl, decode_eq_of_nat]; refl end end list section multiset def lower : list ℕ → ℕ → list ℕ | [] n := [] | (m :: l) n := (m - n) :: lower l m def raise : list ℕ → ℕ → list ℕ | [] n := [] | (m :: l) n := (m + n) :: raise l (m + n) lemma lower_raise : ∀ l n, lower (raise l n) n = l | [] n := rfl | (m :: l) n := by simp [raise, lower, nat.add_sub_cancel, lower_raise] lemma raise_lower : ∀ {l n}, list.sorted (≤) (n :: l) → raise (lower l n) n = l | [] n h := rfl | (m :: l) n h := have n ≤ m, from list.rel_of_sorted_cons h _ (l.mem_cons_self _), by simp [raise, lower, nat.sub_add_cancel this, raise_lower (list.sorted_of_sorted_cons h)] lemma raise_chain : ∀ l n, list.chain (≤) n (raise l n) | [] n := list.chain.nil | (m :: l) n := list.chain.cons (nat.le_add_left _ _) (raise_chain _ _) lemma raise_sorted : ∀ l n, list.sorted (≤) (raise l n) | [] n := list.sorted_nil | (m :: l) n := (list.chain_iff_pairwise (@le_trans _ _)).1 (raise_chain _ _) /- Warning: this is not the same encoding as used in `encodable` -/ instance multiset : denumerable (multiset α) := mk' ⟨ λ s : multiset α, encode $ lower ((s.map encode).sort (≤)) 0, λ n, multiset.map (of_nat α) (raise (of_nat (list ℕ) n) 0), λ s, by have := raise_lower (list.sorted_cons.2 ⟨λ n _, zero_le n, (s.map encode).sort_sorted _⟩); simp [-multiset.coe_map, this], λ n, by simp [-multiset.coe_map, list.merge_sort_eq_self _ (raise_sorted _ _), lower_raise]⟩ end multiset section finset def lower' : list ℕ → ℕ → list ℕ | [] n := [] | (m :: l) n := (m - n) :: lower' l (m + 1) def raise' : list ℕ → ℕ → list ℕ | [] n := [] | (m :: l) n := (m + n) :: raise' l (m + n + 1) lemma lower_raise' : ∀ l n, lower' (raise' l n) n = l | [] n := rfl | (m :: l) n := by simp [raise', lower', nat.add_sub_cancel, lower_raise'] lemma raise_lower' : ∀ {l n}, (∀ m ∈ l, n ≤ m) → list.sorted (<) l → raise' (lower' l n) n = l | [] n h₁ h₂ := rfl | (m :: l) n h₁ h₂ := have n ≤ m, from h₁ _ (l.mem_cons_self _), by simp [raise', lower', nat.sub_add_cancel this, raise_lower' (list.rel_of_sorted_cons h₂ : ∀ a ∈ l, m < a) (list.sorted_of_sorted_cons h₂)] lemma raise'_chain : ∀ l {m n}, m < n → list.chain (<) m (raise' l n) | [] m n h := list.chain.nil | (a :: l) m n h := list.chain.cons (lt_of_lt_of_le h (nat.le_add_left _ _)) (raise'_chain _ (lt_succ_self _)) lemma raise'_sorted : ∀ l n, list.sorted (<) (raise' l n) | [] n := list.sorted_nil | (m :: l) n := (list.chain_iff_pairwise (@lt_trans _ _)).1 (raise'_chain _ (lt_succ_self _)) def raise'_finset (l : list ℕ) (n : ℕ) : finset ℕ := ⟨raise' l n, (raise'_sorted _ _).imp (@ne_of_lt _ _)⟩ /- Warning: this is not the same encoding as used in `encodable` -/ instance finset : denumerable (finset α) := mk' ⟨ λ s : finset α, encode $ lower' ((s.map (eqv α).to_embedding).sort (≤)) 0, λ n, finset.map (eqv α).symm.to_embedding (raise'_finset (of_nat (list ℕ) n) 0), λ s, finset.eq_of_veq $ by simp [-multiset.coe_map, raise'_finset, raise_lower' (λ n _, zero_le n) (finset.sort_sorted_lt _)], λ n, by simp [-multiset.coe_map, finset.map, raise'_finset, finset.sort, list.merge_sort_eq_self (≤) ((raise'_sorted _ _).imp (@le_of_lt _ _)), lower_raise']⟩ end finset end denumerable namespace equiv /-- The type lists on unit is canonically equivalent to the natural numbers. -/ def list_unit_equiv : list unit ≃ ℕ := { to_fun := list.length, inv_fun := list.repeat (), left_inv := λ u, list.length_injective (by simp), right_inv := λ n, list.length_repeat () n } def list_nat_equiv_nat : list ℕ ≃ ℕ := denumerable.eqv _ def list_equiv_self_of_equiv_nat {α : Type} (e : α ≃ ℕ) : list α ≃ α := calc list α ≃ list ℕ : list_equiv_of_equiv e ... ≃ ℕ : list_nat_equiv_nat ... ≃ α : e.symm end equiv
b6c8f48843581e287ac4c32f859ec092b1091fc4
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/measure_theory/constructions/borel_space.lean
af3d4e86e00fc18a01139f719687165bc80ac03b
[ "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
68,520
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Yury Kudryashov -/ import measure_theory.function.ae_measurable_sequence import analysis.complex.basic import analysis.normed_space.finite_dimension import topology.G_delta import measure_theory.group.arithmetic import topology.semicontinuous import topology.instances.ereal /-! # Borel (measurable) space ## Main definitions * `borel α` : the least `σ`-algebra that contains all open sets; * `class borel_space` : a space with `topological_space` and `measurable_space` structures such that `‹measurable_space α› = borel α`; * `class opens_measurable_space` : a space with `topological_space` and `measurable_space` structures such that all open sets are measurable; equivalently, `borel α ≤ ‹measurable_space α›`. * `borel_space` instances on `empty`, `unit`, `bool`, `nat`, `int`, `rat`; * `measurable` and `borel_space` instances on `ℝ`, `ℝ≥0`, `ℝ≥0∞`. ## Main statements * `is_open.measurable_set`, `is_closed.measurable_set`: open and closed sets are measurable; * `continuous.measurable` : a continuous function is measurable; * `continuous.measurable2` : if `f : α → β` and `g : α → γ` are measurable and `op : β × γ → δ` is continuous, then `λ x, op (f x, g y)` is measurable; * `measurable.add` etc : dot notation for arithmetic operations on `measurable` predicates, and similarly for `dist` and `edist`; * `ae_measurable.add` : similar dot notation for almost everywhere measurable functions; * `measurable.ennreal*` : special cases for arithmetic operations on `ℝ≥0∞`. -/ noncomputable theory open classical set filter measure_theory open_locale classical big_operators topological_space nnreal ennreal interval universes u v w x y variables {α β γ γ₂ δ : Type*} {ι : Sort y} {s t u : set α} open measurable_space topological_space /-- `measurable_space` structure generated by `topological_space`. -/ def borel (α : Type u) [topological_space α] : measurable_space α := generate_from {s : set α | is_open s} lemma borel_eq_top_of_discrete [topological_space α] [discrete_topology α] : borel α = ⊤ := top_le_iff.1 $ λ s hs, generate_measurable.basic s (is_open_discrete s) lemma borel_eq_top_of_encodable [topological_space α] [t1_space α] [encodable α] : borel α = ⊤ := begin refine (top_le_iff.1 $ λ s hs, bUnion_of_singleton s ▸ _), apply measurable_set.bUnion s.countable_encodable, intros x hx, apply measurable_set.of_compl, apply generate_measurable.basic, exact is_closed_singleton.is_open_compl end lemma borel_eq_generate_from_of_subbasis {s : set (set α)} [t : topological_space α] [second_countable_topology α] (hs : t = generate_from s) : borel α = generate_from s := le_antisymm (generate_from_le $ assume u (hu : t.is_open u), begin rw [hs] at hu, induction hu, case generate_open.basic : u hu { exact generate_measurable.basic u hu }, case generate_open.univ { exact @measurable_set.univ α (generate_from s) }, case generate_open.inter : s₁ s₂ _ _ hs₁ hs₂ { exact @measurable_set.inter α (generate_from s) _ _ hs₁ hs₂ }, case generate_open.sUnion : f hf ih { rcases is_open_sUnion_countable f (by rwa hs) with ⟨v, hv, vf, vu⟩, rw ← vu, exact @measurable_set.sUnion α (generate_from s) _ hv (λ x xv, ih _ (vf xv)) } end) (generate_from_le $ assume u hu, generate_measurable.basic _ $ show t.is_open u, by rw [hs]; exact generate_open.basic _ hu) lemma topological_space.is_topological_basis.borel_eq_generate_from [topological_space α] [second_countable_topology α] {s : set (set α)} (hs : is_topological_basis s) : borel α = generate_from s := borel_eq_generate_from_of_subbasis hs.eq_generate_from lemma is_pi_system_is_open [topological_space α] : is_pi_system (is_open : set α → Prop) := λ s t hs ht hst, is_open.inter hs ht lemma borel_eq_generate_from_is_closed [topological_space α] : borel α = generate_from {s | is_closed s} := le_antisymm (generate_from_le $ λ t ht, @measurable_set.of_compl α _ (generate_from {s | is_closed s}) (generate_measurable.basic _ $ is_closed_compl_iff.2 ht)) (generate_from_le $ λ t ht, @measurable_set.of_compl α _ (borel α) (generate_measurable.basic _ $ is_open_compl_iff.2 ht)) section order_topology variable (α) variables [topological_space α] [second_countable_topology α] [linear_order α] [order_topology α] lemma is_pi_system_Ioo_mem {α : Type*} [linear_order α] (s t : set α) : is_pi_system {S | ∃ (l ∈ s) (u ∈ t), l < u ∧ Ioo l u = S} := begin rintro _ _ ⟨l₁, hls₁, u₁, hut₁, hlu₁, rfl⟩ ⟨l₂, hls₂, u₂, hut₂, hlu₂, rfl⟩ ⟨x, ⟨hlx₁ : l₁ < x, hxu₁ : x < u₁⟩, ⟨hlx₂ : l₂ < x, hxu₂ : x < u₂⟩⟩, refine ⟨l₁ ⊔ l₂, sup_ind l₁ l₂ hls₁ hls₂, u₁ ⊓ u₂, inf_ind u₁ u₂ hut₁ hut₂, _, Ioo_inter_Ioo.symm⟩, simp [hlx₂.trans hxu₁, hlx₁.trans hxu₂, *] end lemma is_pi_system_Ioo {α β : Type*} [linear_order β] (f : α → β) : @is_pi_system β (⋃ l u (h : f l < f u), {Ioo (f l) (f u)}) := begin convert is_pi_system_Ioo_mem (range f) (range f), ext s, simp [@eq_comm _ _ s] end lemma borel_eq_generate_Iio : borel α = generate_from (range Iio) := begin refine le_antisymm _ (generate_from_le _), { rw borel_eq_generate_from_of_subbasis (@order_topology.topology_eq_generate_intervals α _ _ _), letI : measurable_space α := measurable_space.generate_from (range Iio), have H : ∀ a : α, measurable_set (Iio a) := λ a, generate_measurable.basic _ ⟨_, rfl⟩, refine generate_from_le _, rintro _ ⟨a, rfl | rfl⟩; [skip, apply H], by_cases h : ∃ a', ∀ b, a < b ↔ a' ≤ b, { rcases h with ⟨a', ha'⟩, rw (_ : Ioi a = (Iio a')ᶜ), { exact (H _).compl }, simp [set.ext_iff, ha'] }, { rcases is_open_Union_countable (λ a' : {a' : α // a < a'}, {b | a'.1 < b}) (λ a', is_open_lt' _) with ⟨v, ⟨hv⟩, vu⟩, simp [set.ext_iff] at vu, have : Ioi a = ⋃ x : v, (Iio x.1.1)ᶜ, { simp [set.ext_iff], refine λ x, ⟨λ ax, _, λ ⟨a', ⟨h, av⟩, ax⟩, lt_of_lt_of_le h ax⟩, rcases (vu x).2 _ with ⟨a', h₁, h₂⟩, { exact ⟨a', h₁, le_of_lt h₂⟩ }, refine not_imp_comm.1 (λ h, _) h, exact ⟨x, λ b, ⟨λ ab, le_of_not_lt (λ h', h ⟨b, ab, h'⟩), lt_of_lt_of_le ax⟩⟩ }, rw this, resetI, apply measurable_set.Union, exact λ _, (H _).compl } }, { rw forall_range_iff, intro a, exact generate_measurable.basic _ is_open_Iio } end lemma borel_eq_generate_Ioi : borel α = generate_from (range Ioi) := @borel_eq_generate_Iio (order_dual α) _ (by apply_instance : second_countable_topology α) _ _ end order_topology lemma borel_comap {f : α → β} {t : topological_space β} : @borel α (t.induced f) = (@borel β t).comap f := comap_generate_from.symm lemma continuous.borel_measurable [topological_space α] [topological_space β] {f : α → β} (hf : continuous f) : @measurable α β (borel α) (borel β) f := measurable.of_le_map $ generate_from_le $ λ s hs, generate_measurable.basic (f ⁻¹' s) (hs.preimage hf) /-- A space with `measurable_space` and `topological_space` structures such that all open sets are measurable. -/ class opens_measurable_space (α : Type*) [topological_space α] [h : measurable_space α] : Prop := (borel_le : borel α ≤ h) /-- A space with `measurable_space` and `topological_space` structures such that the `σ`-algebra of measurable sets is exactly the `σ`-algebra generated by open sets. -/ class borel_space (α : Type*) [topological_space α] [measurable_space α] : Prop := (measurable_eq : ‹measurable_space α› = borel α) /-- In a `borel_space` all open sets are measurable. -/ @[priority 100] instance borel_space.opens_measurable {α : Type*} [topological_space α] [measurable_space α] [borel_space α] : opens_measurable_space α := ⟨ge_of_eq $ borel_space.measurable_eq⟩ instance subtype.borel_space {α : Type*} [topological_space α] [measurable_space α] [hα : borel_space α] (s : set α) : borel_space s := ⟨by { rw [hα.1, subtype.measurable_space, ← borel_comap], refl }⟩ instance subtype.opens_measurable_space {α : Type*} [topological_space α] [measurable_space α] [h : opens_measurable_space α] (s : set α) : opens_measurable_space s := ⟨by { rw [borel_comap], exact comap_mono h.1 }⟩ theorem _root_.measurable_set.induction_on_open [topological_space α] [measurable_space α] [borel_space α] {C : set α → Prop} (h_open : ∀ U, is_open U → C U) (h_compl : ∀ t, measurable_set t → C t → C tᶜ) (h_union : ∀ f : ℕ → set α, pairwise (disjoint on f) → (∀ i, measurable_set (f i)) → (∀ i, C (f i)) → C (⋃ i, f i)) : ∀ ⦃t⦄, measurable_set t → C t := measurable_space.induction_on_inter borel_space.measurable_eq is_pi_system_is_open (h_open _ is_open_empty) h_open h_compl h_union section variables [topological_space α] [measurable_space α] [opens_measurable_space α] [topological_space β] [measurable_space β] [opens_measurable_space β] [topological_space γ] [measurable_space γ] [borel_space γ] [topological_space γ₂] [measurable_space γ₂] [borel_space γ₂] [measurable_space δ] lemma is_open.measurable_set (h : is_open s) : measurable_set s := opens_measurable_space.borel_le _ $ generate_measurable.basic _ h @[measurability] lemma measurable_set_interior : measurable_set (interior s) := is_open_interior.measurable_set lemma is_Gδ.measurable_set (h : is_Gδ s) : measurable_set s := begin rcases h with ⟨S, hSo, hSc, rfl⟩, exact measurable_set.sInter hSc (λ t ht, (hSo t ht).measurable_set) end lemma measurable_set_of_continuous_at {β} [emetric_space β] (f : α → β) : measurable_set {x | continuous_at f x} := (is_Gδ_set_of_continuous_at f).measurable_set lemma is_closed.measurable_set (h : is_closed s) : measurable_set s := h.is_open_compl.measurable_set.of_compl lemma is_compact.measurable_set [t2_space α] (h : is_compact s) : measurable_set s := h.is_closed.measurable_set @[measurability] lemma measurable_set_closure : measurable_set (closure s) := is_closed_closure.measurable_set lemma measurable_of_is_open {f : δ → γ} (hf : ∀ s, is_open s → measurable_set (f ⁻¹' s)) : measurable f := by { rw [‹borel_space γ›.measurable_eq], exact measurable_generate_from hf } lemma measurable_of_is_closed {f : δ → γ} (hf : ∀ s, is_closed s → measurable_set (f ⁻¹' s)) : measurable f := begin apply measurable_of_is_open, intros s hs, rw [← measurable_set.compl_iff, ← preimage_compl], apply hf, rw [is_closed_compl_iff], exact hs end lemma measurable_of_is_closed' {f : δ → γ} (hf : ∀ s, is_closed s → s.nonempty → s ≠ univ → measurable_set (f ⁻¹' s)) : measurable f := begin apply measurable_of_is_closed, intros s hs, cases eq_empty_or_nonempty s with h1 h1, { simp [h1] }, by_cases h2 : s = univ, { simp [h2] }, exact hf s hs h1 h2 end instance nhds_is_measurably_generated (a : α) : (𝓝 a).is_measurably_generated := begin rw [nhds, infi_subtype'], refine @filter.infi_is_measurably_generated _ _ _ _ (λ i, _), exact i.2.2.measurable_set.principal_is_measurably_generated end /-- If `s` is a measurable set, then `𝓝[s] a` is a measurably generated filter for each `a`. This cannot be an `instance` because it depends on a non-instance `hs : measurable_set s`. -/ lemma measurable_set.nhds_within_is_measurably_generated {s : set α} (hs : measurable_set s) (a : α) : (𝓝[s] a).is_measurably_generated := by haveI := hs.principal_is_measurably_generated; exact filter.inf_is_measurably_generated _ _ @[priority 100] -- see Note [lower instance priority] instance opens_measurable_space.to_measurable_singleton_class [t1_space α] : measurable_singleton_class α := ⟨λ x, is_closed_singleton.measurable_set⟩ instance pi.opens_measurable_space {ι : Type*} {π : ι → Type*} [fintype ι] [t' : Π i, topological_space (π i)] [Π i, measurable_space (π i)] [∀ i, second_countable_topology (π i)] [∀ i, opens_measurable_space (π i)] : opens_measurable_space (Π i, π i) := begin constructor, have : Pi.topological_space = generate_from {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ countable_basis (π a)) ∧ t = pi ↑i s}, { rw [funext (λ a, @eq_generate_from_countable_basis (π a) _ _), pi_generate_from_eq] }, rw [borel_eq_generate_from_of_subbasis this], apply generate_from_le, rintros _ ⟨s, i, hi, rfl⟩, refine measurable_set.pi i.countable_to_set (λ a ha, is_open.measurable_set _), rw [eq_generate_from_countable_basis (π a)], exact generate_open.basic _ (hi a ha) end instance prod.opens_measurable_space [second_countable_topology α] [second_countable_topology β] : opens_measurable_space (α × β) := begin constructor, rw [((is_basis_countable_basis α).prod (is_basis_countable_basis β)).borel_eq_generate_from], apply generate_from_le, rintros _ ⟨u, v, hu, hv, rfl⟩, exact (is_open_of_mem_countable_basis hu).measurable_set.prod (is_open_of_mem_countable_basis hv).measurable_set end variables {α' : Type*} [topological_space α'] [measurable_space α'] lemma meas_interior_of_null_bdry {μ : measure α'} {s : set α'} (h_nullbdry : μ (frontier s) = 0) : μ (interior s) = μ s := meas_eq_meas_smaller_of_between_null_diff interior_subset subset_closure h_nullbdry lemma meas_closure_of_null_bdry {μ : measure α'} {s : set α'} (h_nullbdry : μ (frontier s) = 0) : μ (closure s) = μ s := (meas_eq_meas_larger_of_between_null_diff interior_subset subset_closure h_nullbdry).symm section preorder variables [preorder α] [order_closed_topology α] {a b x : α} @[simp, measurability] lemma measurable_set_Ici : measurable_set (Ici a) := is_closed_Ici.measurable_set @[simp, measurability] lemma measurable_set_Iic : measurable_set (Iic a) := is_closed_Iic.measurable_set @[simp, measurability] lemma measurable_set_Icc : measurable_set (Icc a b) := is_closed_Icc.measurable_set instance nhds_within_Ici_is_measurably_generated : (𝓝[Ici b] a).is_measurably_generated := measurable_set_Ici.nhds_within_is_measurably_generated _ instance nhds_within_Iic_is_measurably_generated : (𝓝[Iic b] a).is_measurably_generated := measurable_set_Iic.nhds_within_is_measurably_generated _ instance nhds_within_Icc_is_measurably_generated : is_measurably_generated (𝓝[Icc a b] x) := by { rw [← Ici_inter_Iic, nhds_within_inter], apply_instance } instance at_top_is_measurably_generated : (filter.at_top : filter α).is_measurably_generated := @filter.infi_is_measurably_generated _ _ _ _ $ λ a, (measurable_set_Ici : measurable_set (Ici a)).principal_is_measurably_generated instance at_bot_is_measurably_generated : (filter.at_bot : filter α).is_measurably_generated := @filter.infi_is_measurably_generated _ _ _ _ $ λ a, (measurable_set_Iic : measurable_set (Iic a)).principal_is_measurably_generated end preorder section partial_order variables [partial_order α] [order_closed_topology α] [second_countable_topology α] {a b : α} @[measurability] lemma measurable_set_le' : measurable_set {p : α × α | p.1 ≤ p.2} := order_closed_topology.is_closed_le'.measurable_set @[measurability] lemma measurable_set_le {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable_set {a | f a ≤ g a} := hf.prod_mk hg measurable_set_le' end partial_order section linear_order variables [linear_order α] [order_closed_topology α] {a b x : α} @[simp, measurability] lemma measurable_set_Iio : measurable_set (Iio a) := is_open_Iio.measurable_set @[simp, measurability] lemma measurable_set_Ioi : measurable_set (Ioi a) := is_open_Ioi.measurable_set @[simp, measurability] lemma measurable_set_Ioo : measurable_set (Ioo a b) := is_open_Ioo.measurable_set @[simp, measurability] lemma measurable_set_Ioc : measurable_set (Ioc a b) := measurable_set_Ioi.inter measurable_set_Iic @[simp, measurability] lemma measurable_set_Ico : measurable_set (Ico a b) := measurable_set_Ici.inter measurable_set_Iio instance nhds_within_Ioi_is_measurably_generated : (𝓝[Ioi b] a).is_measurably_generated := measurable_set_Ioi.nhds_within_is_measurably_generated _ instance nhds_within_Iio_is_measurably_generated : (𝓝[Iio b] a).is_measurably_generated := measurable_set_Iio.nhds_within_is_measurably_generated _ instance nhds_within_interval_is_measurably_generated : is_measurably_generated (𝓝[[a, b]] x) := nhds_within_Icc_is_measurably_generated @[measurability] lemma measurable_set_lt' [second_countable_topology α] : measurable_set {p : α × α | p.1 < p.2} := (is_open_lt continuous_fst continuous_snd).measurable_set @[measurability] lemma measurable_set_lt [second_countable_topology α] {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable_set {a | f a < g a} := hf.prod_mk hg measurable_set_lt' lemma set.ord_connected.measurable_set (h : ord_connected s) : measurable_set s := begin let u := ⋃ (x ∈ s) (y ∈ s), Ioo x y, have huopen : is_open u := is_open_bUnion (λ x hx, is_open_bUnion (λ y hy, is_open_Ioo)), have humeas : measurable_set u := huopen.measurable_set, have hfinite : (s \ u).finite, { refine set.finite_of_forall_between_eq_endpoints (s \ u) (λ x hx y hy z hz hxy hyz, _), by_contra h, push_neg at h, exact hy.2 (mem_bUnion_iff.mpr ⟨x, hx.1, mem_bUnion_iff.mpr ⟨z, hz.1, lt_of_le_of_ne hxy h.1, lt_of_le_of_ne hyz h.2⟩⟩) }, have : u ⊆ s := bUnion_subset (λ x hx, bUnion_subset (λ y hy, Ioo_subset_Icc_self.trans (h.out hx hy))), rw ← union_diff_cancel this, exact humeas.union hfinite.measurable_set end lemma is_preconnected.measurable_set (h : is_preconnected s) : measurable_set s := h.ord_connected.measurable_set end linear_order section linear_order variables [linear_order α] [order_closed_topology α] @[measurability] lemma measurable_set_interval {a b : α} : measurable_set (interval a b) := measurable_set_Icc variables [second_countable_topology α] @[measurability] lemma measurable.max {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable (λ a, max (f a) (g a)) := by simpa only [max_def] using hf.piecewise (measurable_set_le hg hf) hg @[measurability] lemma ae_measurable.max {f g : δ → α} {μ : measure δ} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, max (f a) (g a)) μ := ⟨λ a, max (hf.mk f a) (hg.mk g a), hf.measurable_mk.max hg.measurable_mk, eventually_eq.comp₂ hf.ae_eq_mk _ hg.ae_eq_mk⟩ @[measurability] lemma measurable.min {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable (λ a, min (f a) (g a)) := by simpa only [min_def] using hf.piecewise (measurable_set_le hf hg) hg @[measurability] lemma ae_measurable.min {f g : δ → α} {μ : measure δ} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, min (f a) (g a)) μ := ⟨λ a, min (hf.mk f a) (hg.mk g a), hf.measurable_mk.min hg.measurable_mk, eventually_eq.comp₂ hf.ae_eq_mk _ hg.ae_eq_mk⟩ end linear_order /-- A continuous function from an `opens_measurable_space` to a `borel_space` is measurable. -/ lemma continuous.measurable {f : α → γ} (hf : continuous f) : measurable f := hf.borel_measurable.mono opens_measurable_space.borel_le (le_of_eq $ borel_space.measurable_eq) /-- A continuous function from an `opens_measurable_space` to a `borel_space` is ae-measurable. -/ lemma continuous.ae_measurable {f : α → γ} (h : continuous f) (μ : measure α) : ae_measurable f μ := h.measurable.ae_measurable lemma closed_embedding.measurable {f : α → γ} (hf : closed_embedding f) : measurable f := hf.continuous.measurable @[priority 100, to_additive] instance has_continuous_mul.has_measurable_mul [has_mul γ] [has_continuous_mul γ] : has_measurable_mul γ := { measurable_const_mul := λ c, (continuous_const.mul continuous_id).measurable, measurable_mul_const := λ c, (continuous_id.mul continuous_const).measurable } @[priority 100] instance has_continuous_sub.has_measurable_sub [has_sub γ] [has_continuous_sub γ] : has_measurable_sub γ := { measurable_const_sub := λ c, (continuous_const.sub continuous_id).measurable, measurable_sub_const := λ c, (continuous_id.sub continuous_const).measurable } @[priority 100, to_additive] instance topological_group.has_measurable_inv [group γ] [topological_group γ] : has_measurable_inv γ := ⟨continuous_inv.measurable⟩ @[priority 100] instance has_continuous_smul.has_measurable_smul {M α} [topological_space M] [topological_space α] [measurable_space M] [measurable_space α] [opens_measurable_space M] [borel_space α] [has_scalar M α] [has_continuous_smul M α] : has_measurable_smul M α := ⟨λ c, (continuous_const.smul continuous_id).measurable, λ y, (continuous_id.smul continuous_const).measurable⟩ section homeomorph /-- A homeomorphism between two Borel spaces is a measurable equivalence.-/ def homeomorph.to_measurable_equiv (h : γ ≃ₜ γ₂) : γ ≃ᵐ γ₂ := { measurable_to_fun := h.continuous_to_fun.measurable, measurable_inv_fun := h.continuous_inv_fun.measurable, .. h } @[simp] lemma homeomorph.to_measurable_equiv_coe (h : γ ≃ₜ γ₂) : (h.to_measurable_equiv : γ → γ₂) = h := rfl @[simp] lemma homeomorph.to_measurable_equiv_symm_coe (h : γ ≃ₜ γ₂) : (h.to_measurable_equiv.symm : γ₂ → γ) = h.symm := rfl @[measurability] lemma homeomorph.measurable (h : α ≃ₜ γ) : measurable h := h.continuous.measurable end homeomorph lemma measurable_of_continuous_on_compl_singleton [t1_space α] {f : α → γ} (a : α) (hf : continuous_on f {a}ᶜ) : measurable f := measurable_of_measurable_on_compl_singleton a (continuous_on_iff_continuous_restrict.1 hf).measurable lemma continuous.measurable2 [second_countable_topology α] [second_countable_topology β] {f : δ → α} {g : δ → β} {c : α → β → γ} (h : continuous (λ p : α × β, c p.1 p.2)) (hf : measurable f) (hg : measurable g) : measurable (λ a, c (f a) (g a)) := h.measurable.comp (hf.prod_mk hg) lemma continuous.ae_measurable2 [second_countable_topology α] [second_countable_topology β] {f : δ → α} {g : δ → β} {c : α → β → γ} {μ : measure δ} (h : continuous (λ p : α × β, c p.1 p.2)) (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, c (f a) (g a)) μ := h.measurable.comp_ae_measurable (hf.prod_mk hg) @[priority 100] instance has_continuous_inv₀.has_measurable_inv [group_with_zero γ] [t1_space γ] [has_continuous_inv₀ γ] : has_measurable_inv γ := ⟨measurable_of_continuous_on_compl_singleton 0 continuous_on_inv₀⟩ @[priority 100, to_additive] instance has_continuous_mul.has_measurable_mul₂ [second_countable_topology γ] [has_mul γ] [has_continuous_mul γ] : has_measurable_mul₂ γ := ⟨continuous_mul.measurable⟩ @[priority 100] instance has_continuous_sub.has_measurable_sub₂ [second_countable_topology γ] [has_sub γ] [has_continuous_sub γ] : has_measurable_sub₂ γ := ⟨continuous_sub.measurable⟩ @[priority 100] instance has_continuous_smul.has_measurable_smul₂ {M α} [topological_space M] [second_countable_topology M] [measurable_space M] [opens_measurable_space M] [topological_space α] [second_countable_topology α] [measurable_space α] [borel_space α] [has_scalar M α] [has_continuous_smul M α] : has_measurable_smul₂ M α := ⟨continuous_smul.measurable⟩ end section borel_space variables [topological_space α] [measurable_space α] [borel_space α] [topological_space β] [measurable_space β] [borel_space β] [topological_space γ] [measurable_space γ] [borel_space γ] [measurable_space δ] lemma pi_le_borel_pi {ι : Type*} {π : ι → Type*} [Π i, topological_space (π i)] [Π i, measurable_space (π i)] [∀ i, borel_space (π i)] : measurable_space.pi ≤ borel (Π i, π i) := begin have : ‹Π i, measurable_space (π i)› = λ i, borel (π i) := funext (λ i, borel_space.measurable_eq), rw [this], exact supr_le (λ i, comap_le_iff_le_map.2 $ (continuous_apply i).borel_measurable) end lemma prod_le_borel_prod : prod.measurable_space ≤ borel (α × β) := begin rw [‹borel_space α›.measurable_eq, ‹borel_space β›.measurable_eq], refine sup_le _ _, { exact comap_le_iff_le_map.mpr continuous_fst.borel_measurable }, { exact comap_le_iff_le_map.mpr continuous_snd.borel_measurable } end instance pi.borel_space {ι : Type*} {π : ι → Type*} [fintype ι] [t' : Π i, topological_space (π i)] [Π i, measurable_space (π i)] [∀ i, second_countable_topology (π i)] [∀ i, borel_space (π i)] : borel_space (Π i, π i) := ⟨le_antisymm pi_le_borel_pi opens_measurable_space.borel_le⟩ instance prod.borel_space [second_countable_topology α] [second_countable_topology β] : borel_space (α × β) := ⟨le_antisymm prod_le_borel_prod opens_measurable_space.borel_le⟩ lemma closed_embedding.measurable_inv_fun [n : nonempty β] {g : β → γ} (hg : closed_embedding g) : measurable (function.inv_fun g) := begin refine measurable_of_is_closed (λ s hs, _), by_cases h : classical.choice n ∈ s, { rw preimage_inv_fun_of_mem hg.to_embedding.inj h, exact (hg.closed_iff_image_closed.mp hs).measurable_set.union hg.closed_range.measurable_set.compl }, { rw preimage_inv_fun_of_not_mem hg.to_embedding.inj h, exact (hg.closed_iff_image_closed.mp hs).measurable_set } end lemma measurable_comp_iff_of_closed_embedding {f : δ → β} (g : β → γ) (hg : closed_embedding g) : measurable (g ∘ f) ↔ measurable f := begin refine ⟨λ hf, _, λ hf, hg.measurable.comp hf⟩, apply measurable_of_is_closed, intros s hs, convert hf (hg.is_closed_map s hs).measurable_set, rw [@preimage_comp _ _ _ f g, preimage_image_eq _ hg.to_embedding.inj] end lemma ae_measurable_comp_iff_of_closed_embedding {f : δ → β} {μ : measure δ} (g : β → γ) (hg : closed_embedding g) : ae_measurable (g ∘ f) μ ↔ ae_measurable f μ := begin casesI is_empty_or_nonempty β, { haveI := function.is_empty f, simp only [(measurable_of_empty (g ∘ f)).ae_measurable, (measurable_of_empty f).ae_measurable] }, { refine ⟨λ hf, _, λ hf, hg.measurable.comp_ae_measurable hf⟩, convert hg.measurable_inv_fun.comp_ae_measurable hf, ext x, exact (function.left_inverse_inv_fun hg.to_embedding.inj (f x)).symm }, end lemma ae_measurable_comp_right_iff_of_closed_embedding {g : α → β} {μ : measure α} {f : β → δ} (hg : closed_embedding g) : ae_measurable (f ∘ g) μ ↔ ae_measurable f (measure.map g μ) := begin refine ⟨λ h, _, λ h, h.comp_measurable hg.measurable⟩, casesI is_empty_or_nonempty α, { simp [μ.eq_zero_of_is_empty] }, refine ⟨(h.mk _) ∘ (function.inv_fun g), h.measurable_mk.comp hg.measurable_inv_fun, _⟩, have : μ = measure.map (function.inv_fun g) (measure.map g μ), by rw [measure.map_map hg.measurable_inv_fun hg.measurable, (function.left_inverse_inv_fun hg.to_embedding.inj).comp_eq_id, measure.map_id], rw this at h, filter_upwards [ae_of_ae_map hg.measurable_inv_fun h.ae_eq_mk, ae_map_mem_range g hg.closed_range.measurable_set μ], assume x hx₁ hx₂, convert hx₁, exact ((function.left_inverse_inv_fun hg.to_embedding.inj).right_inv_on_range hx₂).symm, end section linear_order variables [linear_order α] [order_topology α] [second_countable_topology α] lemma measurable_of_Iio {f : δ → α} (hf : ∀ x, measurable_set (f ⁻¹' Iio x)) : measurable f := begin convert measurable_generate_from _, exact borel_space.measurable_eq.trans (borel_eq_generate_Iio _), rintro _ ⟨x, rfl⟩, exact hf x end lemma upper_semicontinuous.measurable [topological_space δ] [opens_measurable_space δ] {f : δ → α} (hf : upper_semicontinuous f) : measurable f := measurable_of_Iio (λ y, (hf.is_open_preimage y).measurable_set) lemma measurable_of_Ioi {f : δ → α} (hf : ∀ x, measurable_set (f ⁻¹' Ioi x)) : measurable f := begin convert measurable_generate_from _, exact borel_space.measurable_eq.trans (borel_eq_generate_Ioi _), rintro _ ⟨x, rfl⟩, exact hf x end lemma lower_semicontinuous.measurable [topological_space δ] [opens_measurable_space δ] {f : δ → α} (hf : lower_semicontinuous f) : measurable f := measurable_of_Ioi (λ y, (hf.is_open_preimage y).measurable_set) lemma measurable_of_Iic {f : δ → α} (hf : ∀ x, measurable_set (f ⁻¹' Iic x)) : measurable f := begin apply measurable_of_Ioi, simp_rw [← compl_Iic, preimage_compl, measurable_set.compl_iff], assumption end lemma measurable_of_Ici {f : δ → α} (hf : ∀ x, measurable_set (f ⁻¹' Ici x)) : measurable f := begin apply measurable_of_Iio, simp_rw [← compl_Ici, preimage_compl, measurable_set.compl_iff], assumption end lemma measurable.is_lub {ι} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, measurable (f i)) (hg : ∀ b, is_lub {a | ∃ i, f i b = a} (g b)) : measurable g := begin change ∀ b, is_lub (range $ λ i, f i b) (g b) at hg, rw [‹borel_space α›.measurable_eq, borel_eq_generate_Ioi α], apply measurable_generate_from, rintro _ ⟨a, rfl⟩, simp_rw [set.preimage, mem_Ioi, lt_is_lub_iff (hg _), exists_range_iff, set_of_exists], exact measurable_set.Union (λ i, hf i (is_open_lt' _).measurable_set) end private lemma ae_measurable.is_lub_of_nonempty {ι} (hι : nonempty ι) {μ : measure δ} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, ae_measurable (f i) μ) (hg : ∀ᵐ b ∂μ, is_lub {a | ∃ i, f i b = a} (g b)) : ae_measurable g μ := begin let p : δ → (ι → α) → Prop := λ x f', is_lub {a | ∃ i, f' i = a} (g x), let g_seq := λ x, ite (x ∈ ae_seq_set hf p) (g x) (⟨g x⟩ : nonempty α).some, have hg_seq : ∀ b, is_lub {a | ∃ i, ae_seq hf p i b = a} (g_seq b), { intro b, haveI hα : nonempty α := nonempty.map g ⟨b⟩, simp only [ae_seq, g_seq], split_ifs, { have h_set_eq : {a : α | ∃ (i : ι), (hf i).mk (f i) b = a} = {a : α | ∃ (i : ι), f i b = a}, { ext x, simp_rw [set.mem_set_of_eq, ae_seq.mk_eq_fun_of_mem_ae_seq_set hf h], }, rw h_set_eq, exact ae_seq.fun_prop_of_mem_ae_seq_set hf h, }, { have h_singleton : {a : α | ∃ (i : ι), hα.some = a} = {hα.some}, { ext1 x, exact ⟨λ hx, hx.some_spec.symm, λ hx, ⟨hι.some, hx.symm⟩⟩, }, rw h_singleton, exact is_lub_singleton, }, }, refine ⟨g_seq, measurable.is_lub (ae_seq.measurable hf p) hg_seq, _⟩, exact (ite_ae_eq_of_measure_compl_zero g (λ x, (⟨g x⟩ : nonempty α).some) (ae_seq_set hf p) (ae_seq.measure_compl_ae_seq_set_eq_zero hf hg)).symm, end lemma ae_measurable.is_lub {ι} {μ : measure δ} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, ae_measurable (f i) μ) (hg : ∀ᵐ b ∂μ, is_lub {a | ∃ i, f i b = a} (g b)) : ae_measurable g μ := begin by_cases hμ : μ = 0, { rw hμ, exact ae_measurable_zero_measure }, haveI : μ.ae.ne_bot, { simpa [ne_bot_iff] }, by_cases hι : nonempty ι, { exact ae_measurable.is_lub_of_nonempty hι hf hg, }, suffices : ∃ x, g =ᵐ[μ] λ y, g x, by { exact ⟨(λ y, g this.some), measurable_const, this.some_spec⟩, }, have h_empty : ∀ x, {a : α | ∃ (i : ι), f i x = a} = ∅, { intro x, ext1 y, rw [set.mem_set_of_eq, set.mem_empty_eq, iff_false], exact λ hi, hι (nonempty_of_exists hi), }, simp_rw h_empty at hg, exact ⟨hg.exists.some, hg.mono (λ y hy, is_lub.unique hy hg.exists.some_spec)⟩, end lemma measurable.is_glb {ι} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, measurable (f i)) (hg : ∀ b, is_glb {a | ∃ i, f i b = a} (g b)) : measurable g := begin change ∀ b, is_glb (range $ λ i, f i b) (g b) at hg, rw [‹borel_space α›.measurable_eq, borel_eq_generate_Iio α], apply measurable_generate_from, rintro _ ⟨a, rfl⟩, simp_rw [set.preimage, mem_Iio, is_glb_lt_iff (hg _), exists_range_iff, set_of_exists], exact measurable_set.Union (λ i, hf i (is_open_gt' _).measurable_set) end private lemma ae_measurable.is_glb_of_nonempty {ι} (hι : nonempty ι) {μ : measure δ} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, ae_measurable (f i) μ) (hg : ∀ᵐ b ∂μ, is_glb {a | ∃ i, f i b = a} (g b)) : ae_measurable g μ := begin let p : δ → (ι → α) → Prop := λ x f', is_glb {a | ∃ i, f' i = a} (g x), let g_seq := λ x, ite (x ∈ ae_seq_set hf p) (g x) (⟨g x⟩ : nonempty α).some, have hg_seq : ∀ b, is_glb {a | ∃ i, ae_seq hf p i b = a} (g_seq b), { intro b, haveI hα : nonempty α := nonempty.map g ⟨b⟩, simp only [ae_seq, g_seq], split_ifs, { have h_set_eq : {a : α | ∃ (i : ι), (hf i).mk (f i) b = a} = {a : α | ∃ (i : ι), f i b = a}, { ext x, simp_rw [set.mem_set_of_eq, ae_seq.mk_eq_fun_of_mem_ae_seq_set hf h], }, rw h_set_eq, exact ae_seq.fun_prop_of_mem_ae_seq_set hf h, }, { have h_singleton : {a : α | ∃ (i : ι), hα.some = a} = {hα.some}, { ext1 x, exact ⟨λ hx, hx.some_spec.symm, λ hx, ⟨hι.some, hx.symm⟩⟩, }, rw h_singleton, exact is_glb_singleton, }, }, refine ⟨g_seq, measurable.is_glb (ae_seq.measurable hf p) hg_seq, _⟩, exact (ite_ae_eq_of_measure_compl_zero g (λ x, (⟨g x⟩ : nonempty α).some) (ae_seq_set hf p) (ae_seq.measure_compl_ae_seq_set_eq_zero hf hg)).symm, end lemma ae_measurable.is_glb {ι} {μ : measure δ} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, ae_measurable (f i) μ) (hg : ∀ᵐ b ∂μ, is_glb {a | ∃ i, f i b = a} (g b)) : ae_measurable g μ := begin by_cases hμ : μ = 0, { rw hμ, exact ae_measurable_zero_measure }, haveI : μ.ae.ne_bot, { simpa [ne_bot_iff] }, by_cases hι : nonempty ι, { exact ae_measurable.is_glb_of_nonempty hι hf hg, }, suffices : ∃ x, g =ᵐ[μ] λ y, g x, by { exact ⟨(λ y, g this.some), measurable_const, this.some_spec⟩, }, have h_empty : ∀ x, {a : α | ∃ (i : ι), f i x = a} = ∅, { intro x, ext1 y, rw [set.mem_set_of_eq, set.mem_empty_eq, iff_false], exact λ hi, hι (nonempty_of_exists hi), }, simp_rw h_empty at hg, exact ⟨hg.exists.some, hg.mono (λ y hy, is_glb.unique hy hg.exists.some_spec)⟩, end protected lemma monotone.measurable [linear_order β] [order_closed_topology β] {f : β → α} (hf : monotone f) : measurable f := suffices h : ∀ x, ord_connected (f ⁻¹' Ioi x), from measurable_of_Ioi (λ x, (h x).measurable_set), λ x, ord_connected_def.mpr (λ a ha b hb c hc, lt_of_lt_of_le ha (hf hc.1)) lemma ae_measurable_restrict_of_monotone_on [linear_order β] [order_closed_topology β] {μ : measure β} {s : set β} (hs : measurable_set s) {f : β → α} (hf : monotone_on f s) : ae_measurable f (μ.restrict s) := have this : monotone (f ∘ coe : s → α), from λ ⟨x, hx⟩ ⟨y, hy⟩ (hxy : x ≤ y), hf hx hy hxy, ae_measurable_restrict_of_measurable_subtype hs this.measurable protected lemma antitone.measurable [linear_order β] [order_closed_topology β] {f : β → α} (hf : antitone f) : measurable f := @monotone.measurable (order_dual α) β _ _ ‹_› _ _ _ _ _ ‹_› _ _ _ hf lemma ae_measurable_restrict_of_antitone_on [linear_order β] [order_closed_topology β] {μ : measure β} {s : set β} (hs : measurable_set s) {f : β → α} (hf : antitone_on f s) : ae_measurable f (μ.restrict s) := @ae_measurable_restrict_of_monotone_on (order_dual α) β _ _ ‹_› _ _ _ _ _ ‹_› _ _ _ _ hs _ hf end linear_order @[measurability] lemma measurable.supr_Prop {α} [measurable_space α] [complete_lattice α] (p : Prop) {f : δ → α} (hf : measurable f) : measurable (λ b, ⨆ h : p, f b) := classical.by_cases (assume h : p, begin convert hf, funext, exact supr_pos h end) (assume h : ¬p, begin convert measurable_const, funext, exact supr_neg h end) @[measurability] lemma measurable.infi_Prop {α} [measurable_space α] [complete_lattice α] (p : Prop) {f : δ → α} (hf : measurable f) : measurable (λ b, ⨅ h : p, f b) := classical.by_cases (assume h : p, begin convert hf, funext, exact infi_pos h end ) (assume h : ¬p, begin convert measurable_const, funext, exact infi_neg h end) section complete_linear_order variables [complete_linear_order α] [order_topology α] [second_countable_topology α] @[measurability] lemma measurable_supr {ι} [encodable ι] {f : ι → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨆ i, f i b) := measurable.is_lub hf $ λ b, is_lub_supr @[measurability] lemma ae_measurable_supr {ι} {μ : measure δ} [encodable ι] {f : ι → δ → α} (hf : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ b, ⨆ i, f i b) μ := ae_measurable.is_lub hf $ (ae_of_all μ (λ b, is_lub_supr)) @[measurability] lemma measurable_infi {ι} [encodable ι] {f : ι → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨅ i, f i b) := measurable.is_glb hf $ λ b, is_glb_infi @[measurability] lemma ae_measurable_infi {ι} {μ : measure δ} [encodable ι] {f : ι → δ → α} (hf : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ b, ⨅ i, f i b) μ := ae_measurable.is_glb hf $ (ae_of_all μ (λ b, is_glb_infi)) lemma measurable_bsupr {ι} (s : set ι) {f : ι → δ → α} (hs : countable s) (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨆ i ∈ s, f i b) := by { haveI : encodable s := hs.to_encodable, simp only [supr_subtype'], exact measurable_supr (λ i, hf i) } lemma ae_measurable_bsupr {ι} {μ : measure δ} (s : set ι) {f : ι → δ → α} (hs : countable s) (hf : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ b, ⨆ i ∈ s, f i b) μ := begin haveI : encodable s := hs.to_encodable, simp only [supr_subtype'], exact ae_measurable_supr (λ i, hf i), end lemma measurable_binfi {ι} (s : set ι) {f : ι → δ → α} (hs : countable s) (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨅ i ∈ s, f i b) := by { haveI : encodable s := hs.to_encodable, simp only [infi_subtype'], exact measurable_infi (λ i, hf i) } lemma ae_measurable_binfi {ι} {μ : measure δ} (s : set ι) {f : ι → δ → α} (hs : countable s) (hf : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ b, ⨅ i ∈ s, f i b) μ := begin haveI : encodable s := hs.to_encodable, simp only [infi_subtype'], exact ae_measurable_infi (λ i, hf i), end /-- `liminf` over a general filter is measurable. See `measurable_liminf` for the version over `ℕ`. -/ lemma measurable_liminf' {ι ι'} {f : ι → δ → α} {u : filter ι} (hf : ∀ i, measurable (f i)) {p : ι' → Prop} {s : ι' → set ι} (hu : u.has_countable_basis p s) (hs : ∀ i, (s i).countable) : measurable (λ x, liminf u (λ i, f i x)) := begin simp_rw [hu.to_has_basis.liminf_eq_supr_infi], refine measurable_bsupr _ hu.countable _, exact λ i, measurable_binfi _ (hs i) hf end /-- `limsup` over a general filter is measurable. See `measurable_limsup` for the version over `ℕ`. -/ lemma measurable_limsup' {ι ι'} {f : ι → δ → α} {u : filter ι} (hf : ∀ i, measurable (f i)) {p : ι' → Prop} {s : ι' → set ι} (hu : u.has_countable_basis p s) (hs : ∀ i, (s i).countable) : measurable (λ x, limsup u (λ i, f i x)) := begin simp_rw [hu.to_has_basis.limsup_eq_infi_supr], refine measurable_binfi _ hu.countable _, exact λ i, measurable_bsupr _ (hs i) hf end /-- `liminf` over `ℕ` is measurable. See `measurable_liminf'` for a version with a general filter. -/ @[measurability] lemma measurable_liminf {f : ℕ → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ x, liminf at_top (λ i, f i x)) := measurable_liminf' hf at_top_countable_basis (λ i, countable_encodable _) /-- `limsup` over `ℕ` is measurable. See `measurable_limsup'` for a version with a general filter. -/ @[measurability] lemma measurable_limsup {f : ℕ → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ x, limsup at_top (λ i, f i x)) := measurable_limsup' hf at_top_countable_basis (λ i, countable_encodable _) end complete_linear_order section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] [order_topology α] [second_countable_topology α] lemma measurable_cSup {ι} {f : ι → δ → α} {s : set ι} (hs : s.countable) (hf : ∀ i, measurable (f i)) (bdd : ∀ x, bdd_above ((λ i, f i x) '' s)) : measurable (λ x, Sup ((λ i, f i x) '' s)) := begin cases eq_empty_or_nonempty s with h2s h2s, { simp [h2s, measurable_const] }, { apply measurable_of_Iic, intro y, simp_rw [preimage, mem_Iic, cSup_le_iff (bdd _) (h2s.image _), ball_image_iff, set_of_forall], exact measurable_set.bInter hs (λ i hi, measurable_set_le (hf i) measurable_const) } end end conditionally_complete_linear_order /-- Convert a `homeomorph` to a `measurable_equiv`. -/ def homemorph.to_measurable_equiv (h : α ≃ₜ β) : α ≃ᵐ β := { to_equiv := h.to_equiv, measurable_to_fun := h.continuous_to_fun.measurable, measurable_inv_fun := h.continuous_inv_fun.measurable } end borel_space instance empty.borel_space : borel_space empty := ⟨borel_eq_top_of_discrete.symm⟩ instance unit.borel_space : borel_space unit := ⟨borel_eq_top_of_discrete.symm⟩ instance bool.borel_space : borel_space bool := ⟨borel_eq_top_of_discrete.symm⟩ instance nat.borel_space : borel_space ℕ := ⟨borel_eq_top_of_discrete.symm⟩ instance int.borel_space : borel_space ℤ := ⟨borel_eq_top_of_discrete.symm⟩ instance rat.borel_space : borel_space ℚ := ⟨borel_eq_top_of_encodable.symm⟩ instance real.measurable_space : measurable_space ℝ := borel ℝ instance real.borel_space : borel_space ℝ := ⟨rfl⟩ instance nnreal.measurable_space : measurable_space ℝ≥0 := subtype.measurable_space instance nnreal.borel_space : borel_space ℝ≥0 := subtype.borel_space _ instance ennreal.measurable_space : measurable_space ℝ≥0∞ := borel ℝ≥0∞ instance ennreal.borel_space : borel_space ℝ≥0∞ := ⟨rfl⟩ instance ereal.measurable_space : measurable_space ereal := borel ereal instance ereal.borel_space : borel_space ereal := ⟨rfl⟩ instance complex.measurable_space : measurable_space ℂ := borel ℂ instance complex.borel_space : borel_space ℂ := ⟨rfl⟩ section metric_space variables [metric_space α] [measurable_space α] [opens_measurable_space α] variables [measurable_space β] {x : α} {ε : ℝ} open metric @[measurability] lemma measurable_set_ball : measurable_set (metric.ball x ε) := metric.is_open_ball.measurable_set @[measurability] lemma measurable_set_closed_ball : measurable_set (metric.closed_ball x ε) := metric.is_closed_ball.measurable_set @[measurability] lemma measurable_inf_dist {s : set α} : measurable (λ x, inf_dist x s) := (continuous_inf_dist_pt s).measurable @[measurability] lemma measurable.inf_dist {f : β → α} (hf : measurable f) {s : set α} : measurable (λ x, inf_dist (f x) s) := measurable_inf_dist.comp hf @[measurability] lemma measurable_inf_nndist {s : set α} : measurable (λ x, inf_nndist x s) := (continuous_inf_nndist_pt s).measurable @[measurability] lemma measurable.inf_nndist {f : β → α} (hf : measurable f) {s : set α} : measurable (λ x, inf_nndist (f x) s) := measurable_inf_nndist.comp hf variables [second_countable_topology α] @[measurability] lemma measurable_dist : measurable (λ p : α × α, dist p.1 p.2) := continuous_dist.measurable @[measurability] lemma measurable.dist {f g : β → α} (hf : measurable f) (hg : measurable g) : measurable (λ b, dist (f b) (g b)) := (@continuous_dist α _).measurable2 hf hg @[measurability] lemma measurable_nndist : measurable (λ p : α × α, nndist p.1 p.2) := continuous_nndist.measurable @[measurability] lemma measurable.nndist {f g : β → α} (hf : measurable f) (hg : measurable g) : measurable (λ b, nndist (f b) (g b)) := (@continuous_nndist α _).measurable2 hf hg end metric_space section emetric_space variables [emetric_space α] [measurable_space α] [opens_measurable_space α] variables [measurable_space β] {x : α} {ε : ℝ≥0∞} open emetric @[measurability] lemma measurable_set_eball : measurable_set (emetric.ball x ε) := emetric.is_open_ball.measurable_set @[measurability] lemma measurable_edist_right : measurable (edist x) := (continuous_const.edist continuous_id).measurable @[measurability] lemma measurable_edist_left : measurable (λ y, edist y x) := (continuous_id.edist continuous_const).measurable @[measurability] lemma measurable_inf_edist {s : set α} : measurable (λ x, inf_edist x s) := continuous_inf_edist.measurable @[measurability] lemma measurable.inf_edist {f : β → α} (hf : measurable f) {s : set α} : measurable (λ x, inf_edist (f x) s) := measurable_inf_edist.comp hf variables [second_countable_topology α] @[measurability] lemma measurable_edist : measurable (λ p : α × α, edist p.1 p.2) := continuous_edist.measurable @[measurability] lemma measurable.edist {f g : β → α} (hf : measurable f) (hg : measurable g) : measurable (λ b, edist (f b) (g b)) := (@continuous_edist α _).measurable2 hf hg @[measurability] lemma ae_measurable.edist {f g : β → α} {μ : measure β} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, edist (f a) (g a)) μ := (@continuous_edist α _).ae_measurable2 hf hg end emetric_space namespace real open measurable_space measure_theory lemma borel_eq_generate_from_Ioo_rat : borel ℝ = generate_from (⋃(a b : ℚ) (h : a < b), {Ioo a b}) := is_topological_basis_Ioo_rat.borel_eq_generate_from lemma is_pi_system_Ioo_rat : @is_pi_system ℝ (⋃ (a b : ℚ) (h : a < b), {Ioo a b}) := by simpa using is_pi_system_Ioo (coe : ℚ → ℝ) /-- The intervals `(-(n + 1), (n + 1))` form a finite spanning sets in the set of open intervals with rational endpoints for a locally finite measure `μ` on `ℝ`. -/ def finite_spanning_sets_in_Ioo_rat (μ : measure ℝ) [is_locally_finite_measure μ] : μ.finite_spanning_sets_in (⋃ (a b : ℚ) (h : a < b), {Ioo a b}) := { set := λ n, Ioo (-(n + 1)) (n + 1), set_mem := λ n, begin simp only [mem_Union, mem_singleton_iff], refine ⟨-(n + 1), n + 1, _, by norm_cast⟩, exact (neg_nonpos.2 (@nat.cast_nonneg ℚ _ (n + 1))).trans_lt n.cast_add_one_pos end, finite := λ n, measure_Ioo_lt_top, spanning := Union_eq_univ_iff.2 $ λ x, ⟨⌊|x|⌋₊, neg_lt.1 ((neg_le_abs_self x).trans_lt (lt_nat_floor_add_one _)), (le_abs_self x).trans_lt (lt_nat_floor_add_one _)⟩ } lemma measure_ext_Ioo_rat {μ ν : measure ℝ} [is_locally_finite_measure μ] (h : ∀ a b : ℚ, μ (Ioo a b) = ν (Ioo a b)) : μ = ν := (finite_spanning_sets_in_Ioo_rat μ).ext borel_eq_generate_from_Ioo_rat is_pi_system_Ioo_rat $ by { simp only [mem_Union, mem_singleton_iff], rintro _ ⟨a, b, -, rfl⟩, apply h } lemma borel_eq_generate_from_Iio_rat : borel ℝ = generate_from (⋃ a : ℚ, {Iio a}) := begin let g : measurable_space ℝ := generate_from (⋃ a : ℚ, {Iio a}), apply le_antisymm _ (measurable_space.generate_from_le (λ t, _)), { rw borel_eq_generate_from_Ioo_rat, refine generate_from_le (λ t, _), simp only [mem_Union, mem_singleton_iff], rintro ⟨a, b, h, rfl⟩, rw (set.ext (λ x, _) : Ioo (a : ℝ) b = (⋃c>a, (Iio c)ᶜ) ∩ Iio b), { have hg : ∀ q : ℚ, g.measurable_set' (Iio q) := λ q, generate_measurable.basic (Iio q) (by { simp, exact ⟨_, rfl⟩ }), refine @measurable_set.inter _ g _ _ _ (hg _), refine @measurable_set.bUnion _ _ g _ _ (countable_encodable _) (λ c h, _), exact @measurable_set.compl _ _ g (hg _) }, { suffices : x < ↑b → (↑a < x ↔ ∃ (i : ℚ), a < i ∧ ↑i ≤ x), by simpa, refine λ _, ⟨λ h, _, λ ⟨i, hai, hix⟩, (rat.cast_lt.2 hai).trans_le hix⟩, rcases exists_rat_btwn h with ⟨c, ac, cx⟩, exact ⟨c, rat.cast_lt.1 ac, cx.le⟩ } }, { simp only [mem_Union, mem_singleton_iff], rintro ⟨r, rfl⟩, exact measurable_set_Iio } end end real variable [measurable_space α] @[measurability] lemma measurable_real_to_nnreal : measurable (real.to_nnreal) := nnreal.continuous_of_real.measurable @[measurability] lemma measurable.real_to_nnreal {f : α → ℝ} (hf : measurable f) : measurable (λ x, real.to_nnreal (f x)) := measurable_real_to_nnreal.comp hf @[measurability] lemma ae_measurable.real_to_nnreal {f : α → ℝ} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, real.to_nnreal (f x)) μ := measurable_real_to_nnreal.comp_ae_measurable hf @[measurability] lemma measurable_coe_nnreal_real : measurable (coe : ℝ≥0 → ℝ) := nnreal.continuous_coe.measurable @[measurability] lemma measurable.coe_nnreal_real {f : α → ℝ≥0} (hf : measurable f) : measurable (λ x, (f x : ℝ)) := measurable_coe_nnreal_real.comp hf @[measurability] lemma ae_measurable.coe_nnreal_real {f : α → ℝ≥0} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x : ℝ)) μ := measurable_coe_nnreal_real.comp_ae_measurable hf @[measurability] lemma measurable_coe_nnreal_ennreal : measurable (coe : ℝ≥0 → ℝ≥0∞) := ennreal.continuous_coe.measurable @[measurability] lemma measurable.coe_nnreal_ennreal {f : α → ℝ≥0} (hf : measurable f) : measurable (λ x, (f x : ℝ≥0∞)) := ennreal.continuous_coe.measurable.comp hf @[measurability] lemma ae_measurable.coe_nnreal_ennreal {f : α → ℝ≥0} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x : ℝ≥0∞)) μ := ennreal.continuous_coe.measurable.comp_ae_measurable hf @[measurability] lemma measurable.ennreal_of_real {f : α → ℝ} (hf : measurable f) : measurable (λ x, ennreal.of_real (f x)) := ennreal.continuous_of_real.measurable.comp hf /-- The set of finite `ℝ≥0∞` numbers is `measurable_equiv` to `ℝ≥0`. -/ def measurable_equiv.ennreal_equiv_nnreal : {r : ℝ≥0∞ | r ≠ ∞} ≃ᵐ ℝ≥0 := ennreal.ne_top_homeomorph_nnreal.to_measurable_equiv namespace ennreal lemma measurable_of_measurable_nnreal {f : ℝ≥0∞ → α} (h : measurable (λ p : ℝ≥0, f p)) : measurable f := measurable_of_measurable_on_compl_singleton ∞ (measurable_equiv.ennreal_equiv_nnreal.symm.measurable_coe_iff.1 h) /-- `ℝ≥0∞` is `measurable_equiv` to `ℝ≥0 ⊕ unit`. -/ def ennreal_equiv_sum : ℝ≥0∞ ≃ᵐ ℝ≥0 ⊕ unit := { measurable_to_fun := measurable_of_measurable_nnreal measurable_inl, measurable_inv_fun := measurable_sum measurable_coe_nnreal_ennreal (@measurable_const ℝ≥0∞ unit _ _ ∞), .. equiv.option_equiv_sum_punit ℝ≥0 } open function (uncurry) lemma measurable_of_measurable_nnreal_prod [measurable_space β] [measurable_space γ] {f : ℝ≥0∞ × β → γ} (H₁ : measurable (λ p : ℝ≥0 × β, f (p.1, p.2))) (H₂ : measurable (λ x, f (∞, x))) : measurable f := let e : ℝ≥0∞ × β ≃ᵐ ℝ≥0 × β ⊕ unit × β := (ennreal_equiv_sum.prod_congr (measurable_equiv.refl β)).trans (measurable_equiv.sum_prod_distrib _ _ _) in e.symm.measurable_coe_iff.1 $ measurable_sum H₁ (H₂.comp measurable_id.snd) lemma measurable_of_measurable_nnreal_nnreal [measurable_space β] {f : ℝ≥0∞ × ℝ≥0∞ → β} (h₁ : measurable (λ p : ℝ≥0 × ℝ≥0, f (p.1, p.2))) (h₂ : measurable (λ r : ℝ≥0, f (∞, r))) (h₃ : measurable (λ r : ℝ≥0, f (r, ∞))) : measurable f := measurable_of_measurable_nnreal_prod (measurable_swap_iff.1 $ measurable_of_measurable_nnreal_prod (h₁.comp measurable_swap) h₃) (measurable_of_measurable_nnreal h₂) @[measurability] lemma measurable_of_real : measurable ennreal.of_real := ennreal.continuous_of_real.measurable @[measurability] lemma measurable_to_real : measurable ennreal.to_real := ennreal.measurable_of_measurable_nnreal measurable_coe_nnreal_real @[measurability] lemma measurable_to_nnreal : measurable ennreal.to_nnreal := ennreal.measurable_of_measurable_nnreal measurable_id instance : has_measurable_mul₂ ℝ≥0∞ := begin refine ⟨measurable_of_measurable_nnreal_nnreal _ _ _⟩, { simp only [← ennreal.coe_mul, measurable_mul.coe_nnreal_ennreal] }, { simp only [ennreal.top_mul, ennreal.coe_eq_zero], exact measurable_const.piecewise (measurable_set_singleton _) measurable_const }, { simp only [ennreal.mul_top, ennreal.coe_eq_zero], exact measurable_const.piecewise (measurable_set_singleton _) measurable_const } end instance : has_measurable_sub₂ ℝ≥0∞ := ⟨by apply measurable_of_measurable_nnreal_nnreal; simp [← ennreal.coe_sub, continuous_sub.measurable.coe_nnreal_ennreal]⟩ instance : has_measurable_inv ℝ≥0∞ := ⟨ennreal.continuous_inv.measurable⟩ end ennreal @[measurability] lemma measurable.ennreal_to_nnreal {f : α → ℝ≥0∞} (hf : measurable f) : measurable (λ x, (f x).to_nnreal) := ennreal.measurable_to_nnreal.comp hf @[measurability] lemma ae_measurable.ennreal_to_nnreal {f : α → ℝ≥0∞} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x).to_nnreal) μ := ennreal.measurable_to_nnreal.comp_ae_measurable hf lemma measurable_coe_nnreal_ennreal_iff {f : α → ℝ≥0} : measurable (λ x, (f x : ℝ≥0∞)) ↔ measurable f := ⟨λ h, h.ennreal_to_nnreal, λ h, h.coe_nnreal_ennreal⟩ @[measurability] lemma measurable.ennreal_to_real {f : α → ℝ≥0∞} (hf : measurable f) : measurable (λ x, ennreal.to_real (f x)) := ennreal.measurable_to_real.comp hf @[measurability] lemma ae_measurable.ennreal_to_real {f : α → ℝ≥0∞} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, ennreal.to_real (f x)) μ := ennreal.measurable_to_real.comp_ae_measurable hf /-- note: `ℝ≥0∞` can probably be generalized in a future version of this lemma. -/ @[measurability] lemma measurable.ennreal_tsum {ι} [encodable ι] {f : ι → α → ℝ≥0∞} (h : ∀ i, measurable (f i)) : measurable (λ x, ∑' i, f i x) := by { simp_rw [ennreal.tsum_eq_supr_sum], apply measurable_supr, exact λ s, s.measurable_sum (λ i _, h i) } @[measurability] lemma measurable.ennreal_tsum' {ι} [encodable ι] {f : ι → α → ℝ≥0∞} (h : ∀ i, measurable (f i)) : measurable (∑' i, f i) := begin convert measurable.ennreal_tsum h, ext1 x, exact tsum_apply (pi.summable.2 (λ _, ennreal.summable)), end @[measurability] lemma measurable.nnreal_tsum {ι} [encodable ι] {f : ι → α → ℝ≥0} (h : ∀ i, measurable (f i)) : measurable (λ x, ∑' i, f i x) := begin simp_rw [nnreal.tsum_eq_to_nnreal_tsum], exact (measurable.ennreal_tsum (λ i, (h i).coe_nnreal_ennreal)).ennreal_to_nnreal, end @[measurability] lemma ae_measurable.ennreal_tsum {ι} [encodable ι] {f : ι → α → ℝ≥0∞} {μ : measure α} (h : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ x, ∑' i, f i x) μ := by { simp_rw [ennreal.tsum_eq_supr_sum], apply ae_measurable_supr, exact λ s, finset.ae_measurable_sum s (λ i _, h i) } @[measurability] lemma measurable_coe_real_ereal : measurable (coe : ℝ → ereal) := continuous_coe_real_ereal.measurable @[measurability] lemma measurable.coe_real_ereal {f : α → ℝ} (hf : measurable f) : measurable (λ x, (f x : ereal)) := measurable_coe_real_ereal.comp hf @[measurability] lemma ae_measurable.coe_real_ereal {f : α → ℝ} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x : ereal)) μ := measurable_coe_real_ereal.comp_ae_measurable hf /-- The set of finite `ereal` numbers is `measurable_equiv` to `ℝ`. -/ def measurable_equiv.ereal_equiv_real : ({⊥, ⊤} : set ereal).compl ≃ᵐ ℝ := ereal.ne_bot_top_homeomorph_real.to_measurable_equiv lemma ereal.measurable_of_measurable_real {f : ereal → α} (h : measurable (λ p : ℝ, f p)) : measurable f := measurable_of_measurable_on_compl_finite {⊥, ⊤} (by simp) (measurable_equiv.ereal_equiv_real.symm.measurable_coe_iff.1 h) @[measurability] lemma measurable_ereal_to_real : measurable ereal.to_real := ereal.measurable_of_measurable_real (by simpa using measurable_id) @[measurability] lemma measurable.ereal_to_real {f : α → ereal} (hf : measurable f) : measurable (λ x, (f x).to_real) := measurable_ereal_to_real.comp hf @[measurability] lemma ae_measurable.ereal_to_real {f : α → ereal} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x).to_real) μ := measurable_ereal_to_real.comp_ae_measurable hf @[measurability] lemma measurable_coe_ennreal_ereal : measurable (coe : ℝ≥0∞ → ereal) := continuous_coe_ennreal_ereal.measurable @[measurability] lemma measurable.coe_ereal_ennreal {f : α → ℝ≥0∞} (hf : measurable f) : measurable (λ x, (f x : ereal)) := measurable_coe_ennreal_ereal.comp hf @[measurability] lemma ae_measurable.coe_ereal_ennreal {f : α → ℝ≥0∞} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x : ereal)) μ := measurable_coe_ennreal_ereal.comp_ae_measurable hf section normed_group variables [normed_group α] [opens_measurable_space α] [measurable_space β] @[measurability] lemma measurable_norm : measurable (norm : α → ℝ) := continuous_norm.measurable @[measurability] lemma measurable.norm {f : β → α} (hf : measurable f) : measurable (λ a, norm (f a)) := measurable_norm.comp hf @[measurability] lemma ae_measurable.norm {f : β → α} {μ : measure β} (hf : ae_measurable f μ) : ae_measurable (λ a, norm (f a)) μ := measurable_norm.comp_ae_measurable hf @[measurability] lemma measurable_nnnorm : measurable (nnnorm : α → ℝ≥0) := continuous_nnnorm.measurable @[measurability] lemma measurable.nnnorm {f : β → α} (hf : measurable f) : measurable (λ a, nnnorm (f a)) := measurable_nnnorm.comp hf @[measurability] lemma ae_measurable.nnnorm {f : β → α} {μ : measure β} (hf : ae_measurable f μ) : ae_measurable (λ a, nnnorm (f a)) μ := measurable_nnnorm.comp_ae_measurable hf @[measurability] lemma measurable_ennnorm : measurable (λ x : α, (nnnorm x : ℝ≥0∞)) := measurable_nnnorm.coe_nnreal_ennreal @[measurability] lemma measurable.ennnorm {f : β → α} (hf : measurable f) : measurable (λ a, (nnnorm (f a) : ℝ≥0∞)) := hf.nnnorm.coe_nnreal_ennreal @[measurability] lemma ae_measurable.ennnorm {f : β → α} {μ : measure β} (hf : ae_measurable f μ) : ae_measurable (λ a, (nnnorm (f a) : ℝ≥0∞)) μ := measurable_ennnorm.comp_ae_measurable hf end normed_group section limits variables [measurable_space β] [metric_space β] [borel_space β] open metric /-- A limit (over a general filter) of measurable `ℝ≥0` valued functions is measurable. The assumption `hs` can be dropped using `filter.is_countably_generated.has_antitone_basis`, but we don't need that case yet. -/ lemma measurable_of_tendsto_nnreal' {ι ι'} {f : ι → α → ℝ≥0} {g : α → ℝ≥0} (u : filter ι) [ne_bot u] (hf : ∀ i, measurable (f i)) (lim : tendsto f u (𝓝 g)) {p : ι' → Prop} {s : ι' → set ι} (hu : u.has_countable_basis p s) (hs : ∀ i, (s i).countable) : measurable g := begin rw [tendsto_pi] at lim, rw [← measurable_coe_nnreal_ennreal_iff], have : ∀ x, liminf u (λ n, (f n x : ℝ≥0∞)) = (g x : ℝ≥0∞) := λ x, ((ennreal.continuous_coe.tendsto (g x)).comp (lim x)).liminf_eq, simp_rw [← this], show measurable (λ x, liminf u (λ n, (f n x : ℝ≥0∞))), exact measurable_liminf' (λ i, (hf i).coe_nnreal_ennreal) hu hs, end /-- A sequential limit of measurable `ℝ≥0` valued functions is measurable. -/ lemma measurable_of_tendsto_nnreal {f : ℕ → α → ℝ≥0} {g : α → ℝ≥0} (hf : ∀ i, measurable (f i)) (lim : tendsto f at_top (𝓝 g)) : measurable g := measurable_of_tendsto_nnreal' at_top hf lim at_top_countable_basis (λ i, countable_encodable _) /-- A limit (over a general filter) of measurable functions valued in a metric space is measurable. The assumption `hs` can be dropped using `filter.is_countably_generated.has_antitone_basis`, but we don't need that case yet. -/ lemma measurable_of_tendsto_metric' {ι ι'} {f : ι → α → β} {g : α → β} (u : filter ι) [ne_bot u] (hf : ∀ i, measurable (f i)) (lim : tendsto f u (𝓝 g)) {p : ι' → Prop} {s : ι' → set ι} (hu : u.has_countable_basis p s) (hs : ∀ i, (s i).countable) : measurable g := begin apply measurable_of_is_closed', intros s h1s h2s h3s, have : measurable (λ x, inf_nndist (g x) s), { refine measurable_of_tendsto_nnreal' u (λ i, (hf i).inf_nndist) _ hu hs, swap, rw [tendsto_pi], rw [tendsto_pi] at lim, intro x, exact ((continuous_inf_nndist_pt s).tendsto (g x)).comp (lim x) }, have h4s : g ⁻¹' s = (λ x, inf_nndist (g x) s) ⁻¹' {0}, { ext x, simp [h1s, ← mem_iff_inf_dist_zero_of_closed h1s h2s, ← nnreal.coe_eq_zero] }, rw [h4s], exact this (measurable_set_singleton 0), end /-- A sequential limit of measurable functions valued in a metric space is measurable. -/ lemma measurable_of_tendsto_metric {f : ℕ → α → β} {g : α → β} (hf : ∀ i, measurable (f i)) (lim : tendsto f at_top (𝓝 g)) : measurable g := measurable_of_tendsto_metric' at_top hf lim at_top_countable_basis (λ i, countable_encodable _) lemma ae_measurable_of_tendsto_metric_ae {μ : measure α} {f : ℕ → α → β} {g : α → β} (hf : ∀ n, ae_measurable (f n) μ) (h_ae_tendsto : ∀ᵐ x ∂μ, filter.at_top.tendsto (λ n, f n x) (𝓝 (g x))) : ae_measurable g μ := begin let p : α → (ℕ → β) → Prop := λ x f', filter.at_top.tendsto (λ n, f' n) (𝓝 (g x)), let hp : ∀ᵐ x ∂μ, p x (λ n, f n x), from h_ae_tendsto, let ae_seq_lim := λ x, ite (x ∈ ae_seq_set hf p) (g x) (⟨f 0 x⟩ : nonempty β).some, refine ⟨ae_seq_lim, _, (ite_ae_eq_of_measure_compl_zero g (λ x, (⟨f 0 x⟩ : nonempty β).some) (ae_seq_set hf p) (ae_seq.measure_compl_ae_seq_set_eq_zero hf hp)).symm⟩, refine measurable_of_tendsto_metric (@ae_seq.measurable α β _ _ _ f μ hf p) _, refine tendsto_pi.mpr (λ x, _), simp_rw [ae_seq, ae_seq_lim], split_ifs with hx, { simp_rw ae_seq.mk_eq_fun_of_mem_ae_seq_set hf hx, exact @ae_seq.fun_prop_of_mem_ae_seq_set α β _ _ _ _ _ _ hf x hx, }, { exact tendsto_const_nhds, }, end lemma measurable_of_tendsto_metric_ae {μ : measure α} [μ.is_complete] {f : ℕ → α → β} {g : α → β} (hf : ∀ n, measurable (f n)) (h_ae_tendsto : ∀ᵐ x ∂μ, filter.at_top.tendsto (λ n, f n x) (𝓝 (g x))) : measurable g := ae_measurable_iff_measurable.mp (ae_measurable_of_tendsto_metric_ae (λ i, (hf i).ae_measurable) h_ae_tendsto) lemma measurable_limit_of_tendsto_metric_ae {μ : measure α} {f : ℕ → α → β} (hf : ∀ n, ae_measurable (f n) μ) (h_ae_tendsto : ∀ᵐ x ∂μ, ∃ l : β, filter.at_top.tendsto (λ n, f n x) (𝓝 l)) : ∃ (f_lim : α → β) (hf_lim_meas : measurable f_lim), ∀ᵐ x ∂μ, filter.at_top.tendsto (λ n, f n x) (𝓝 (f_lim x)) := begin let p : α → (ℕ → β) → Prop := λ x f', ∃ l : β, filter.at_top.tendsto (λ n, f' n) (𝓝 l), have hp_mem : ∀ x, x ∈ ae_seq_set hf p → p x (λ n, f n x), from λ x hx, ae_seq.fun_prop_of_mem_ae_seq_set hf hx, have hμ_compl : μ (ae_seq_set hf p)ᶜ = 0, from ae_seq.measure_compl_ae_seq_set_eq_zero hf h_ae_tendsto, let f_lim : α → β := λ x, dite (x ∈ ae_seq_set hf p) (λ h, (hp_mem x h).some) (λ h, (⟨f 0 x⟩ : nonempty β).some), have hf_lim_conv : ∀ x, x ∈ ae_seq_set hf p → filter.at_top.tendsto (λ n, f n x) (𝓝 (f_lim x)), { intros x hx_conv, simp only [f_lim, hx_conv, dif_pos], exact (hp_mem x hx_conv).some_spec, }, have hf_lim : ∀ x, filter.at_top.tendsto (λ n, ae_seq hf p n x) (𝓝 (f_lim x)), { intros x, simp only [f_lim, ae_seq], split_ifs, { rw funext (λ n, ae_seq.mk_eq_fun_of_mem_ae_seq_set hf h n), exact (hp_mem x h).some_spec, }, { exact tendsto_const_nhds, }, }, have h_ae_tendsto_f_lim : ∀ᵐ x ∂μ, filter.at_top.tendsto (λ n, f n x) (𝓝 (f_lim x)), { refine le_antisymm (le_of_eq (measure_mono_null _ hμ_compl)) (zero_le _), exact set.compl_subset_compl.mpr (λ x hx, hf_lim_conv x hx), }, have h_f_lim_meas : measurable f_lim, from measurable_of_tendsto_metric (ae_seq.measurable hf p) (tendsto_pi.mpr (λ x, hf_lim x)), exact ⟨f_lim, h_f_lim_meas, h_ae_tendsto_f_lim⟩, end end limits namespace continuous_linear_map variables {𝕜 : Type*} [normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] [measurable_space E] variables [opens_measurable_space E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] [measurable_space F] [borel_space F] @[measurability] protected lemma measurable (L : E →L[𝕜] F) : measurable L := L.continuous.measurable lemma measurable_comp (L : E →L[𝕜] F) {φ : α → E} (φ_meas : measurable φ) : measurable (λ (a : α), L (φ a)) := L.measurable.comp φ_meas end continuous_linear_map namespace continuous_linear_map variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] instance : measurable_space (E →L[𝕜] F) := borel _ instance : borel_space (E →L[𝕜] F) := ⟨rfl⟩ @[measurability] lemma measurable_apply [measurable_space F] [borel_space F] (x : E) : measurable (λ f : E →L[𝕜] F, f x) := (apply 𝕜 F x).continuous.measurable @[measurability] lemma measurable_apply' [measurable_space E] [opens_measurable_space E] [measurable_space F] [borel_space F] : measurable (λ (x : E) (f : E →L[𝕜] F), f x) := measurable_pi_lambda _ $ λ f, f.measurable @[measurability] lemma measurable_coe [measurable_space F] [borel_space F] : measurable (λ (f : E →L[𝕜] F) (x : E), f x) := measurable_pi_lambda _ measurable_apply end continuous_linear_map section continuous_linear_map_nondiscrete_normed_field variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] [measurable_space E] [borel_space E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] @[measurability] lemma measurable.apply_continuous_linear_map {φ : α → F →L[𝕜] E} (hφ : measurable φ) (v : F) : measurable (λ a, φ a v) := (continuous_linear_map.apply 𝕜 E v).measurable.comp hφ @[measurability] lemma ae_measurable.apply_continuous_linear_map {φ : α → F →L[𝕜] E} {μ : measure α} (hφ : ae_measurable φ μ) (v : F) : ae_measurable (λ a, φ a v) μ := (continuous_linear_map.apply 𝕜 E v).measurable.comp_ae_measurable hφ end continuous_linear_map_nondiscrete_normed_field section normed_space variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] [complete_space 𝕜] [measurable_space 𝕜] variables [borel_space 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] [measurable_space E] [borel_space E] lemma measurable_smul_const {f : α → 𝕜} {c : E} (hc : c ≠ 0) : measurable (λ x, f x • c) ↔ measurable f := measurable_comp_iff_of_closed_embedding (λ y : 𝕜, y • c) (closed_embedding_smul_left hc) lemma ae_measurable_smul_const {f : α → 𝕜} {μ : measure α} {c : E} (hc : c ≠ 0) : ae_measurable (λ x, f x • c) μ ↔ ae_measurable f μ := ae_measurable_comp_iff_of_closed_embedding (λ y : 𝕜, y • c) (closed_embedding_smul_left hc) end normed_space
b850ab57552566cc4e5b348df91ee70b1808f5c7
02fbe05a45fda5abde7583464416db4366eedfbf
/library/init/data/int/basic.lean
c43c37a4b8bf36a99a778541541ba3206b63cd07
[ "Apache-2.0" ]
permissive
jasonrute/lean
cc12807e11f9ac6b01b8951a8bfb9c2eb35a0154
4be962c167ca442a0ec5e84472d7ff9f5302788f
refs/heads/master
1,672,036,664,637
1,601,642,826,000
1,601,642,826,000
260,777,966
0
0
Apache-2.0
1,588,454,819,000
1,588,454,818,000
null
UTF-8
Lean
false
false
23,225
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad The integers, with addition, multiplication, and subtraction. -/ prelude import init.data.nat.lemmas init.data.nat.gcd open nat /- the type, coercions, and notation -/ @[derive decidable_eq] inductive int : Type | of_nat : nat → int | neg_succ_of_nat : nat → int notation `ℤ` := int instance : has_coe nat int := ⟨int.of_nat⟩ notation `-[1+ ` n `]` := int.neg_succ_of_nat n protected def int.repr : int → string | (int.of_nat n) := repr n | (int.neg_succ_of_nat n) := "-" ++ repr (succ n) instance : has_repr int := ⟨int.repr⟩ instance : has_to_string int := ⟨int.repr⟩ namespace int protected lemma coe_nat_eq (n : ℕ) : ↑n = int.of_nat n := rfl protected def zero : ℤ := of_nat 0 protected def one : ℤ := of_nat 1 instance : has_zero ℤ := ⟨int.zero⟩ instance : has_one ℤ := ⟨int.one⟩ lemma of_nat_zero : of_nat (0 : nat) = (0 : int) := rfl lemma of_nat_one : of_nat (1 : nat) = (1 : int) := rfl /- definitions of basic functions -/ def neg_of_nat : ℕ → ℤ | 0 := 0 | (succ m) := -[1+ m] def sub_nat_nat (m n : ℕ) : ℤ := match (n - m : nat) with | 0 := of_nat (m - n) -- m ≥ n | (succ k) := -[1+ k] -- m < n, and n - m = succ k end lemma sub_nat_nat_of_sub_eq_zero {m n : ℕ} (h : n - m = 0) : sub_nat_nat m n = of_nat (m - n) := begin unfold sub_nat_nat, rw h, unfold sub_nat_nat._match_1 end lemma sub_nat_nat_of_sub_eq_succ {m n k : ℕ} (h : n - m = succ k) : sub_nat_nat m n = -[1+ k] := begin unfold sub_nat_nat, rw h, unfold sub_nat_nat._match_1 end protected def neg : ℤ → ℤ | (of_nat n) := neg_of_nat n | -[1+ n] := succ n protected def add : ℤ → ℤ → ℤ | (of_nat m) (of_nat n) := of_nat (m + n) | (of_nat m) -[1+ n] := sub_nat_nat m (succ n) | -[1+ m] (of_nat n) := sub_nat_nat n (succ m) | -[1+ m] -[1+ n] := -[1+ succ (m + n)] protected def mul : ℤ → ℤ → ℤ | (of_nat m) (of_nat n) := of_nat (m * n) | (of_nat m) -[1+ n] := neg_of_nat (m * succ n) | -[1+ m] (of_nat n) := neg_of_nat (succ m * n) | -[1+ m] -[1+ n] := of_nat (succ m * succ n) instance : has_neg ℤ := ⟨int.neg⟩ instance : has_add ℤ := ⟨int.add⟩ instance : has_mul ℤ := ⟨int.mul⟩ -- defeq to algebra.sub which gives subtraction for arbitrary `add_group`s protected def sub : ℤ → ℤ → ℤ := λ m n, m + -n instance : has_sub ℤ := ⟨int.sub⟩ protected lemma neg_zero : -(0:ℤ) = 0 := rfl lemma of_nat_add (n m : ℕ) : of_nat (n + m) = of_nat n + of_nat m := rfl lemma of_nat_mul (n m : ℕ) : of_nat (n * m) = of_nat n * of_nat m := rfl lemma of_nat_succ (n : ℕ) : of_nat (succ n) = of_nat n + 1 := rfl lemma neg_of_nat_zero : -(of_nat 0) = 0 := rfl lemma neg_of_nat_of_succ (n : ℕ) : -(of_nat (succ n)) = -[1+ n] := rfl lemma neg_neg_of_nat_succ (n : ℕ) : -(-[1+ n]) = of_nat (succ n) := rfl lemma of_nat_eq_coe (n : ℕ) : of_nat n = ↑n := rfl lemma neg_succ_of_nat_coe (n : ℕ) : -[1+ n] = -↑(n + 1) := rfl protected lemma coe_nat_add (m n : ℕ) : (↑(m + n) : ℤ) = ↑m + ↑n := rfl protected lemma coe_nat_mul (m n : ℕ) : (↑(m * n) : ℤ) = ↑m * ↑n := rfl protected lemma coe_nat_zero : ↑(0 : ℕ) = (0 : ℤ) := rfl protected lemma coe_nat_one : ↑(1 : ℕ) = (1 : ℤ) := rfl protected lemma coe_nat_succ (n : ℕ) : (↑(succ n) : ℤ) = ↑n + 1 := rfl protected lemma coe_nat_add_out (m n : ℕ) : ↑m + ↑n = (m + n : ℤ) := rfl protected lemma coe_nat_mul_out (m n : ℕ) : ↑m * ↑n = (↑(m * n) : ℤ) := rfl protected lemma coe_nat_add_one_out (n : ℕ) : ↑n + (1 : ℤ) = ↑(succ n) := rfl /- these are only for internal use -/ lemma of_nat_add_of_nat (m n : nat) : of_nat m + of_nat n = of_nat (m + n) := rfl lemma of_nat_add_neg_succ_of_nat (m n : nat) : of_nat m + -[1+ n] = sub_nat_nat m (succ n) := rfl lemma neg_succ_of_nat_add_of_nat (m n : nat) : -[1+ m] + of_nat n = sub_nat_nat n (succ m) := rfl lemma neg_succ_of_nat_add_neg_succ_of_nat (m n : nat) : -[1+ m] + -[1+ n] = -[1+ succ (m + n)] := rfl lemma of_nat_mul_of_nat (m n : nat) : of_nat m * of_nat n = of_nat (m * n) := rfl lemma of_nat_mul_neg_succ_of_nat (m n : nat) : of_nat m * -[1+ n] = neg_of_nat (m * succ n) := rfl lemma neg_succ_of_nat_of_nat (m n : nat) : -[1+ m] * of_nat n = neg_of_nat (succ m * n) := rfl lemma mul_neg_succ_of_nat_neg_succ_of_nat (m n : nat) : -[1+ m] * -[1+ n] = of_nat (succ m * succ n) := rfl local attribute [simp] of_nat_add_of_nat of_nat_mul_of_nat neg_of_nat_zero neg_of_nat_of_succ neg_neg_of_nat_succ of_nat_add_neg_succ_of_nat neg_succ_of_nat_add_of_nat neg_succ_of_nat_add_neg_succ_of_nat of_nat_mul_neg_succ_of_nat neg_succ_of_nat_of_nat mul_neg_succ_of_nat_neg_succ_of_nat /- some basic functions and properties -/ protected lemma coe_nat_inj {m n : ℕ} (h : (↑m : ℤ) = ↑n) : m = n := int.of_nat.inj h lemma of_nat_eq_of_nat_iff (m n : ℕ) : of_nat m = of_nat n ↔ m = n := iff.intro int.of_nat.inj (congr_arg _) protected lemma coe_nat_eq_coe_nat_iff (m n : ℕ) : (↑m : ℤ) = ↑n ↔ m = n := of_nat_eq_of_nat_iff m n lemma neg_succ_of_nat_inj_iff {m n : ℕ} : neg_succ_of_nat m = neg_succ_of_nat n ↔ m = n := ⟨neg_succ_of_nat.inj, assume H, by simp [H]⟩ lemma neg_succ_of_nat_eq (n : ℕ) : -[1+ n] = -(n + 1) := rfl /- neg -/ protected lemma neg_neg : ∀ a : ℤ, -(-a) = a | (of_nat 0) := rfl | (of_nat (n+1)) := rfl | -[1+ n] := rfl protected lemma neg_inj {a b : ℤ} (h : -a = -b) : a = b := by rw [← int.neg_neg a, ← int.neg_neg b, h] protected lemma sub_eq_add_neg {a b : ℤ} : a - b = a + -b := rfl /- basic properties of sub_nat_nat -/ lemma sub_nat_nat_elim (m n : ℕ) (P : ℕ → ℕ → ℤ → Prop) (hp : ∀i n, P (n + i) n (of_nat i)) (hn : ∀i m, P m (m + i + 1) (-[1+ i])) : P m n (sub_nat_nat m n) := begin have H : ∀k, n - m = k → P m n (nat.cases_on k (of_nat (m - n)) (λa, -[1+ a])), { intro k, cases k, { intro e, cases (nat.le.dest (nat.le_of_sub_eq_zero e)) with k h, rw [h.symm, nat.add_sub_cancel_left], apply hp }, { intro heq, have h : m ≤ n, { exact nat.le_of_lt (nat.lt_of_sub_eq_succ heq) }, rw [nat.sub_eq_iff_eq_add h] at heq, rw [heq, nat.add_comm], apply hn } }, delta sub_nat_nat, exact H _ rfl end lemma sub_nat_nat_add_left {m n : ℕ} : sub_nat_nat (m + n) m = of_nat n := begin dunfold sub_nat_nat, rw [nat.sub_eq_zero_of_le], dunfold sub_nat_nat._match_1, rw [nat.add_sub_cancel_left], apply nat.le_add_right end lemma sub_nat_nat_add_right {m n : ℕ} : sub_nat_nat m (m + n + 1) = neg_succ_of_nat n := calc sub_nat_nat._match_1 m (m + n + 1) (m + n + 1 - m) = sub_nat_nat._match_1 m (m + n + 1) (m + (n + 1) - m) : by rw [nat.add_assoc] ... = sub_nat_nat._match_1 m (m + n + 1) (n + 1) : by rw [nat.add_sub_cancel_left] ... = neg_succ_of_nat n : rfl lemma sub_nat_nat_add_add (m n k : ℕ) : sub_nat_nat (m + k) (n + k) = sub_nat_nat m n := sub_nat_nat_elim m n (λm n i, sub_nat_nat (m + k) (n + k) = i) (assume i n, have n + i + k = (n + k) + i, by simp [nat.add_comm, nat.add_left_comm], begin rw [this], exact sub_nat_nat_add_left end) (assume i m, have m + i + 1 + k = (m + k) + i + 1, by simp [nat.add_comm, nat.add_left_comm], begin rw [this], exact sub_nat_nat_add_right end) lemma sub_nat_nat_of_ge {m n : ℕ} (h : m ≥ n) : sub_nat_nat m n = of_nat (m - n) := sub_nat_nat_of_sub_eq_zero (sub_eq_zero_of_le h) lemma sub_nat_nat_of_lt {m n : ℕ} (h : m < n) : sub_nat_nat m n = -[1+ pred (n - m)] := have n - m = succ (pred (n - m)), from eq.symm (succ_pred_eq_of_pos (nat.sub_pos_of_lt h)), by rewrite sub_nat_nat_of_sub_eq_succ this /- nat_abs -/ @[simp] def nat_abs : ℤ → ℕ | (of_nat m) := m | -[1+ m] := succ m lemma nat_abs_of_nat (n : ℕ) : nat_abs ↑n = n := rfl lemma eq_zero_of_nat_abs_eq_zero : Π {a : ℤ}, nat_abs a = 0 → a = 0 | (of_nat m) H := congr_arg of_nat H | -[1+ m'] H := absurd H (succ_ne_zero _) lemma nat_abs_pos_of_ne_zero {a : ℤ} (h : a ≠ 0) : nat_abs a > 0 := (eq_zero_or_pos _).resolve_left $ mt eq_zero_of_nat_abs_eq_zero h lemma nat_abs_zero : nat_abs (0 : int) = (0 : nat) := rfl lemma nat_abs_one : nat_abs (1 : int) = (1 : nat) := rfl lemma nat_abs_mul_self : Π {a : ℤ}, ↑(nat_abs a * nat_abs a) = a * a | (of_nat m) := rfl | -[1+ m'] := rfl @[simp] lemma nat_abs_neg (a : ℤ) : nat_abs (-a) = nat_abs a := by {cases a with n n, cases n; refl, refl} lemma nat_abs_eq : Π (a : ℤ), a = nat_abs a ∨ a = -(nat_abs a) | (of_nat m) := or.inl rfl | -[1+ m'] := or.inr rfl lemma eq_coe_or_neg (a : ℤ) : ∃n : ℕ, a = n ∨ a = -n := ⟨_, nat_abs_eq a⟩ /- sign -/ def sign : ℤ → ℤ | (n+1:ℕ) := 1 | 0 := 0 | -[1+ n] := -1 @[simp] theorem sign_zero : sign 0 = 0 := rfl @[simp] theorem sign_one : sign 1 = 1 := rfl @[simp] theorem sign_neg_one : sign (-1) = -1 := rfl /- Quotient and remainder -/ -- There are three main conventions for integer division, -- referred here as the E, F, T rounding conventions. -- All three pairs satisfy the identity x % y + (x / y) * y = x -- unconditionally. -- E-rounding: This pair satisfies 0 ≤ mod x y < nat_abs y for y ≠ 0 protected def div : ℤ → ℤ → ℤ | (m : ℕ) (n : ℕ) := of_nat (m / n) | (m : ℕ) -[1+ n] := -of_nat (m / succ n) | -[1+ m] 0 := 0 | -[1+ m] (n+1:ℕ) := -[1+ m / succ n] | -[1+ m] -[1+ n] := of_nat (succ (m / succ n)) protected def mod : ℤ → ℤ → ℤ | (m : ℕ) n := (m % nat_abs n : ℕ) | -[1+ m] n := sub_nat_nat (nat_abs n) (succ (m % nat_abs n)) -- F-rounding: This pair satisfies fdiv x y = floor (x / y) def fdiv : ℤ → ℤ → ℤ | 0 _ := 0 | (m : ℕ) (n : ℕ) := of_nat (m / n) | (m+1:ℕ) -[1+ n] := -[1+ m / succ n] | -[1+ m] 0 := 0 | -[1+ m] (n+1:ℕ) := -[1+ m / succ n] | -[1+ m] -[1+ n] := of_nat (succ m / succ n) def fmod : ℤ → ℤ → ℤ | 0 _ := 0 | (m : ℕ) (n : ℕ) := of_nat (m % n) | (m+1:ℕ) -[1+ n] := sub_nat_nat (m % succ n) n | -[1+ m] (n : ℕ) := sub_nat_nat n (succ (m % n)) | -[1+ m] -[1+ n] := -of_nat (succ m % succ n) -- T-rounding: This pair satisfies quot x y = round_to_zero (x / y) def quot : ℤ → ℤ → ℤ | (of_nat m) (of_nat n) := of_nat (m / n) | (of_nat m) -[1+ n] := -of_nat (m / succ n) | -[1+ m] (of_nat n) := -of_nat (succ m / n) | -[1+ m] -[1+ n] := of_nat (succ m / succ n) def rem : ℤ → ℤ → ℤ | (of_nat m) (of_nat n) := of_nat (m % n) | (of_nat m) -[1+ n] := of_nat (m % succ n) | -[1+ m] (of_nat n) := -of_nat (succ m % n) | -[1+ m] -[1+ n] := -of_nat (succ m % succ n) instance : has_div ℤ := ⟨int.div⟩ instance : has_mod ℤ := ⟨int.mod⟩ /- gcd -/ def gcd (m n : ℤ) : ℕ := gcd (nat_abs m) (nat_abs n) /- int is a ring -/ /- addition -/ protected lemma add_comm : ∀ a b : ℤ, a + b = b + a | (of_nat n) (of_nat m) := by simp [nat.add_comm] | (of_nat n) -[1+ m] := rfl | -[1+ n] (of_nat m) := rfl | -[1+ n] -[1+m] := by simp [nat.add_comm] protected lemma add_zero : ∀ a : ℤ, a + 0 = a | (of_nat n) := rfl | -[1+ n] := rfl protected lemma zero_add (a : ℤ) : 0 + a = a := int.add_comm a 0 ▸ int.add_zero a lemma sub_nat_nat_sub {m n : ℕ} (h : m ≥ n) (k : ℕ) : sub_nat_nat (m - n) k = sub_nat_nat m (k + n) := calc sub_nat_nat (m - n) k = sub_nat_nat (m - n + n) (k + n) : by rewrite [sub_nat_nat_add_add] ... = sub_nat_nat m (k + n) : by rewrite [nat.sub_add_cancel h] lemma sub_nat_nat_add (m n k : ℕ) : sub_nat_nat (m + n) k = of_nat m + sub_nat_nat n k := begin have h := decidable.le_or_lt k n, cases h with h' h', { rw [sub_nat_nat_of_ge h'], have h₂ : k ≤ m + n, exact (le_trans h' (le_add_left _ _)), rw [sub_nat_nat_of_ge h₂], simp, rw nat.add_sub_assoc h' }, rw [sub_nat_nat_of_lt h'], simp, rw [succ_pred_eq_of_pos (nat.sub_pos_of_lt h')], transitivity, rw [← nat.sub_add_cancel (le_of_lt h')], apply sub_nat_nat_add_add end lemma sub_nat_nat_add_neg_succ_of_nat (m n k : ℕ) : sub_nat_nat m n + -[1+ k] = sub_nat_nat m (n + succ k) := begin have h := decidable.le_or_lt n m, cases h with h' h', { rw [sub_nat_nat_of_ge h'], simp, rw [sub_nat_nat_sub h', nat.add_comm] }, have h₂ : m < n + succ k, exact nat.lt_of_lt_of_le h' (le_add_right _ _), have h₃ : m ≤ n + k, exact le_of_succ_le_succ h₂, rw [sub_nat_nat_of_lt h', sub_nat_nat_of_lt h₂], simp [nat.add_comm], rw [← add_succ, succ_pred_eq_of_pos (nat.sub_pos_of_lt h'), add_succ, succ_sub h₃, pred_succ], rw [nat.add_comm n, nat.add_sub_assoc (le_of_lt h')] end lemma add_assoc_aux1 (m n : ℕ) : ∀ c : ℤ, of_nat m + of_nat n + c = of_nat m + (of_nat n + c) | (of_nat k) := by simp [nat.add_assoc] | -[1+ k] := by simp [sub_nat_nat_add] lemma add_assoc_aux2 (m n k : ℕ) : -[1+ m] + -[1+ n] + of_nat k = -[1+ m] + (-[1+ n] + of_nat k) := begin simp [add_succ], rw [int.add_comm, sub_nat_nat_add_neg_succ_of_nat], simp [add_succ, succ_add, nat.add_comm] end protected lemma add_assoc : ∀ a b c : ℤ, a + b + c = a + (b + c) | (of_nat m) (of_nat n) c := add_assoc_aux1 _ _ _ | (of_nat m) b (of_nat k) := by rw [int.add_comm, ← add_assoc_aux1, int.add_comm (of_nat k), add_assoc_aux1, int.add_comm b] | a (of_nat n) (of_nat k) := by rw [int.add_comm, int.add_comm a, ← add_assoc_aux1, int.add_comm a, int.add_comm (of_nat k)] | -[1+ m] -[1+ n] (of_nat k) := add_assoc_aux2 _ _ _ | -[1+ m] (of_nat n) -[1+ k] := by rw [int.add_comm, ← add_assoc_aux2, int.add_comm (of_nat n), ← add_assoc_aux2, int.add_comm -[1+ m] ] | (of_nat m) -[1+ n] -[1+ k] := by rw [int.add_comm, int.add_comm (of_nat m), int.add_comm (of_nat m), ← add_assoc_aux2, int.add_comm -[1+ k] ] | -[1+ m] -[1+ n] -[1+ k] := by simp [add_succ, nat.add_comm, nat.add_left_comm, neg_of_nat_of_succ] /- negation -/ lemma sub_nat_self : ∀ n, sub_nat_nat n n = 0 | 0 := rfl | (succ m) := begin rw [sub_nat_nat_of_sub_eq_zero, nat.sub_self, of_nat_zero], rw nat.sub_self end local attribute [simp] sub_nat_self protected lemma add_left_neg : ∀ a : ℤ, -a + a = 0 | (of_nat 0) := rfl | (of_nat (succ m)) := by simp | -[1+ m] := by simp protected lemma add_right_neg (a : ℤ) : a + -a = 0 := by rw [int.add_comm, int.add_left_neg] /- multiplication -/ protected lemma mul_comm : ∀ a b : ℤ, a * b = b * a | (of_nat m) (of_nat n) := by simp [nat.mul_comm] | (of_nat m) -[1+ n] := by simp [nat.mul_comm] | -[1+ m] (of_nat n) := by simp [nat.mul_comm] | -[1+ m] -[1+ n] := by simp [nat.mul_comm] lemma of_nat_mul_neg_of_nat (m : ℕ) : ∀ n, of_nat m * neg_of_nat n = neg_of_nat (m * n) | 0 := rfl | (succ n) := begin unfold neg_of_nat, simp end lemma neg_of_nat_mul_of_nat (m n : ℕ) : neg_of_nat m * of_nat n = neg_of_nat (m * n) := begin rw int.mul_comm, simp [of_nat_mul_neg_of_nat, nat.mul_comm] end lemma neg_succ_of_nat_mul_neg_of_nat (m : ℕ) : ∀ n, -[1+ m] * neg_of_nat n = of_nat (succ m * n) | 0 := rfl | (succ n) := begin unfold neg_of_nat, simp end lemma neg_of_nat_mul_neg_succ_of_nat (m n : ℕ) : neg_of_nat n * -[1+ m] = of_nat (n * succ m) := begin rw int.mul_comm, simp [neg_succ_of_nat_mul_neg_of_nat, nat.mul_comm] end local attribute [simp] of_nat_mul_neg_of_nat neg_of_nat_mul_of_nat neg_succ_of_nat_mul_neg_of_nat neg_of_nat_mul_neg_succ_of_nat protected lemma mul_assoc : ∀ a b c : ℤ, a * b * c = a * (b * c) | (of_nat m) (of_nat n) (of_nat k) := by simp [nat.mul_assoc] | (of_nat m) (of_nat n) -[1+ k] := by simp [nat.mul_assoc] | (of_nat m) -[1+ n] (of_nat k) := by simp [nat.mul_assoc] | (of_nat m) -[1+ n] -[1+ k] := by simp [nat.mul_assoc] | -[1+ m] (of_nat n) (of_nat k) := by simp [nat.mul_assoc] | -[1+ m] (of_nat n) -[1+ k] := by simp [nat.mul_assoc] | -[1+ m] -[1+ n] (of_nat k) := by simp [nat.mul_assoc] | -[1+ m] -[1+ n] -[1+ k] := by simp [nat.mul_assoc] protected lemma mul_zero : ∀ (a : ℤ), a * 0 = 0 | (of_nat m) := rfl | -[1+ m] := rfl protected lemma zero_mul (a : ℤ) : 0 * a = 0 := int.mul_comm a 0 ▸ int.mul_zero a lemma neg_of_nat_eq_sub_nat_nat_zero : ∀ n, neg_of_nat n = sub_nat_nat 0 n | 0 := rfl | (succ n) := rfl lemma of_nat_mul_sub_nat_nat (m n k : ℕ) : of_nat m * sub_nat_nat n k = sub_nat_nat (m * n) (m * k) := begin have h₀ : m > 0 ∨ 0 = m, exact decidable.lt_or_eq_of_le (zero_le _), cases h₀ with h₀ h₀, { have h := nat.lt_or_ge n k, cases h with h h, { have h' : m * n < m * k, exact nat.mul_lt_mul_of_pos_left h h₀, rw [sub_nat_nat_of_lt h, sub_nat_nat_of_lt h'], simp, rw [succ_pred_eq_of_pos (nat.sub_pos_of_lt h)], rw [← neg_of_nat_of_succ, nat.mul_sub_left_distrib], rw [← succ_pred_eq_of_pos (nat.sub_pos_of_lt h')], reflexivity }, have h' : m * k ≤ m * n, exact mul_le_mul_left _ h, rw [sub_nat_nat_of_ge h, sub_nat_nat_of_ge h'], simp, rw [nat.mul_sub_left_distrib] }, have h₂ : of_nat 0 = 0, exact rfl, subst h₀, simp [h₂, int.zero_mul, nat.zero_mul] end lemma neg_of_nat_add (m n : ℕ) : neg_of_nat m + neg_of_nat n = neg_of_nat (m + n) := begin cases m, { cases n, { simp, reflexivity }, simp [nat.zero_add], reflexivity }, cases n, { simp, reflexivity }, simp [nat.succ_add], reflexivity end lemma neg_succ_of_nat_mul_sub_nat_nat (m n k : ℕ) : -[1+ m] * sub_nat_nat n k = sub_nat_nat (succ m * k) (succ m * n) := begin have h := nat.lt_or_ge n k, cases h with h h, { have h' : succ m * n < succ m * k, exact nat.mul_lt_mul_of_pos_left h (nat.succ_pos m), rw [sub_nat_nat_of_lt h, sub_nat_nat_of_ge (le_of_lt h')], simp [succ_pred_eq_of_pos (nat.sub_pos_of_lt h), nat.mul_sub_left_distrib]}, have h' : n > k ∨ k = n, exact decidable.lt_or_eq_of_le h, cases h' with h' h', { have h₁ : succ m * n > succ m * k, exact nat.mul_lt_mul_of_pos_left h' (nat.succ_pos m), rw [sub_nat_nat_of_ge h, sub_nat_nat_of_lt h₁], simp [nat.mul_sub_left_distrib, nat.mul_comm], rw [nat.mul_comm k, nat.mul_comm n, ← succ_pred_eq_of_pos (nat.sub_pos_of_lt h₁), ← neg_of_nat_of_succ], reflexivity }, subst h', simp, reflexivity end local attribute [simp] of_nat_mul_sub_nat_nat neg_of_nat_add neg_succ_of_nat_mul_sub_nat_nat protected lemma distrib_left : ∀ a b c : ℤ, a * (b + c) = a * b + a * c | (of_nat m) (of_nat n) (of_nat k) := by simp [nat.left_distrib] | (of_nat m) (of_nat n) -[1+ k] := begin simp [neg_of_nat_eq_sub_nat_nat_zero], rw ← sub_nat_nat_add, reflexivity end | (of_nat m) -[1+ n] (of_nat k) := begin simp [neg_of_nat_eq_sub_nat_nat_zero], rw [int.add_comm, ← sub_nat_nat_add], reflexivity end | (of_nat m) -[1+ n] -[1+ k] := begin simp, rw [← nat.left_distrib, succ_add] end | -[1+ m] (of_nat n) (of_nat k) := begin simp [nat.mul_comm], rw [← nat.right_distrib, nat.mul_comm] end | -[1+ m] (of_nat n) -[1+ k] := begin simp [neg_of_nat_eq_sub_nat_nat_zero], rw [int.add_comm, ← sub_nat_nat_add], reflexivity end | -[1+ m] -[1+ n] (of_nat k) := begin simp [neg_of_nat_eq_sub_nat_nat_zero], rw [← sub_nat_nat_add], reflexivity end | -[1+ m] -[1+ n] -[1+ k] := begin simp, rw [← nat.left_distrib, succ_add] end protected lemma distrib_right (a b c : ℤ) : (a + b) * c = a * c + b * c := begin rw [int.mul_comm, int.distrib_left], simp [int.mul_comm] end protected lemma zero_ne_one : (0 : int) ≠ 1 := assume h : 0 = 1, succ_ne_zero _ (int.of_nat.inj h).symm lemma of_nat_sub {n m : ℕ} (h : m ≤ n) : of_nat (n - m) = of_nat n - of_nat m := show of_nat (n - m) = of_nat n + neg_of_nat m, from match m, h with | 0, h := rfl | succ m, h := show of_nat (n - succ m) = sub_nat_nat n (succ m), by delta sub_nat_nat; rw sub_eq_zero_of_le h; refl end protected lemma add_left_comm (a b c : ℤ) : a + (b + c) = b + (a + c) := by rw [← int.add_assoc, int.add_comm a, int.add_assoc] protected lemma add_left_cancel {a b c : ℤ} (h : a + b = a + c) : b = c := have -a + (a + b) = -a + (a + c), by rw h, by rwa [← int.add_assoc, ← int.add_assoc, int.add_left_neg, int.zero_add, int.zero_add] at this protected lemma neg_add {a b : ℤ} : - (a + b) = -a + -b := calc - (a + b) = -(a + b) + (a + b) + -a + -b : begin rw [int.add_assoc, int.add_comm (-a), int.add_assoc, int.add_assoc, ← int.add_assoc b], rw [int.add_right_neg, int.zero_add, int.add_right_neg, int.add_zero], end ... = -a + -b : by { rw [int.add_left_neg, int.zero_add] } lemma neg_succ_of_nat_coe' (n : ℕ) : -[1+ n] = -↑n - 1 := by rw [int.sub_eq_add_neg, ← int.neg_add]; refl protected lemma coe_nat_sub {n m : ℕ} : n ≤ m → (↑(m - n) : ℤ) = ↑m - ↑n := of_nat_sub local attribute [simp] int.sub_eq_add_neg protected lemma sub_nat_nat_eq_coe {m n : ℕ} : sub_nat_nat m n = ↑m - ↑n := sub_nat_nat_elim m n (λm n i, i = ↑m - ↑n) (λi n, by { simp [int.coe_nat_add, int.add_left_comm, int.add_assoc, int.add_right_neg], refl }) (λi n, by { rw [int.coe_nat_add, int.coe_nat_add, int.coe_nat_one, int.neg_succ_of_nat_eq, int.sub_eq_add_neg, int.neg_add, int.neg_add, int.neg_add, ← int.add_assoc, ← int.add_assoc, int.add_right_neg, int.zero_add] }) def to_nat : ℤ → ℕ | (n : ℕ) := n | -[1+ n] := 0 theorem to_nat_sub (m n : ℕ) : to_nat (m - n) = m - n := by rw [← int.sub_nat_nat_eq_coe]; exact sub_nat_nat_elim m n (λm n i, to_nat i = m - n) (λi n, by rw [nat.add_sub_cancel_left]; refl) (λi n, by rw [nat.add_assoc, nat.sub_eq_zero_of_le (nat.le_add_right _ _)]; refl) -- Since mod x y is always nonnegative when y ≠ 0, we can make a nat version of it def nat_mod (m n : ℤ) : ℕ := (m % n).to_nat protected lemma one_mul : ∀ (a : ℤ), (1 : ℤ) * a = a | (of_nat n) := show of_nat (1 * n) = of_nat n, by rw nat.one_mul | -[1+ n] := show -[1+ (1 * n)] = -[1+ n], by rw nat.one_mul protected lemma mul_one (a : ℤ) : a * 1 = a := by rw [int.mul_comm, int.one_mul] protected lemma neg_eq_neg_one_mul : ∀ a : ℤ, -a = -1 * a | (of_nat 0) := rfl | (of_nat (n+1)) := show _ = -[1+ (1*n)+0], by { rw nat.one_mul, refl } | -[1+ n] := show _ = of_nat _, by { rw nat.one_mul, refl } theorem sign_mul_nat_abs : ∀ (a : ℤ), sign a * nat_abs a = a | (n+1:ℕ) := int.one_mul _ | 0 := rfl | -[1+ n] := (int.neg_eq_neg_one_mul _).symm end int
f1c4c6006bc1521ffc3bc1daba6df3c08c67a7ae
e09201d437062e1f95e6e5360aab0c9f947901aa
/src/regular/dfa_to_regex.lean
8da075a5837c9a4b3a984243e6599a4c36ce971c
[]
no_license
VArtem/lean-regular-languages
34f4b093f28ef2f09ba7e684e642a0f97c901560
e877243188253d0ac17ccf0ae2da7bf608686ff0
refs/heads/master
1,683,590,111,306
1,622,307,234,000
1,622,307,234,000
284,232,653
7
0
null
null
null
null
UTF-8
Lean
false
false
10,993
lean
import tactic import languages.basic import languages.star import regular.regex import automata.dfa import data.set.basic import data.finset.basic import data.finset.fold import data.finset.lattice import data.finset.order import data.fintype.basic import data.set.finite open languages regex DFA finset list namespace regex.from_dfa variables {S Q : Type} [fintype S] [fintype Q] [decidable_eq S] [decidable_eq Q] {dfa : DFA S Q} inductive go_restr (dfa : DFA S Q) (allowed : finset Q) : Q → list S → Q → Prop | finish {q : Q} : go_restr q [] q | last_step {ch : S} {q nxt : Q} : dfa.next q ch = nxt → go_restr q [ch] nxt | step {head : S} {tail : list S} {q nxt f : Q} : dfa.next q head = nxt → nxt ∈ allowed → go_restr nxt tail f → go_restr q (head::tail) f lemma go_restr_univ {a b : Q} {w : list S} : go_restr dfa (fintype.elems Q) a w b ↔ go dfa a w = b := begin split, { intro go_re, induction go_re, case go_restr.finish {rw go_finish}, case go_restr.last_step { simpa only }, case go_restr.step : _ _ _ _ _ h_nxt h_allow go_prev { rwa [go_step, h_nxt], }, }, { intro go_dfa, induction w generalizing a, { cases go_dfa, exact go_restr.finish, }, { cases go_dfa, refine go_restr.step rfl (mem_univ _) (@w_ih (dfa.next a w_hd) rfl), } } end lemma go_restr_insert {a b ins : Q} {w : list S} {allowed : finset Q} : go_restr dfa allowed a w b → go_restr dfa (insert ins allowed) a w b := begin rintro go_allowed, induction go_allowed, case go_restr.finish : { exact go_restr.finish }, case go_restr.last_step : _ _ _ h_nxt { exact go_restr.last_step h_nxt, }, case go_restr.step : _ _ _ _ _ h_nxt h_allow go_prev { refine go_restr.step h_nxt _ go_allowed_ih, simp only [h_allow, mem_insert, or_true, to_finset_cons], } end lemma go_restr_append {a b c : Q} {left right : list S} {allowed : finset Q} : b ∈ allowed → go_restr dfa allowed a left b → go_restr dfa allowed b right c → go_restr dfa allowed a (left ++ right) c := begin rintro b_allowed go_ab go_bc, induction go_ab, case go_restr.finish : { simp only [go_bc, nil_append] }, case go_restr.last_step : _ _ _ h_nxt { exact go_restr.step h_nxt b_allowed go_bc, }, case go_restr.step : _ _ _ _ _ h_nxt h_allow go_prev { replace go_bc := go_ab_ih b_allowed go_bc, refine go_restr.step h_nxt h_allow go_bc, } end lemma go_restr_list_join {a : Q} {l : list (list S)} {allowed : finset Q} : a ∈ allowed → (∀ x, x ∈ l → go_restr dfa allowed a x a) → go_restr dfa allowed a (join l) a := begin rintro a_allowed hl, induction l with head tail lst_ih, { simp [go_restr.finish], }, { refine go_restr_append a_allowed (hl head _) (lst_ih _), simp only [mem_cons_iff, true_or, eq_self_iff_true], rintro x xtail, refine hl x _, simp only [xtail, mem_cons_iff, or_true], } end def all_edges (dfa : DFA S Q) (a b : Q) : set (list S) := (⋃ c : S, if dfa.next a c = b then {[c]} else ∅) def FW (dfa : DFA S Q) : Q → Q → (list Q) → set (list S) | a b [] := if a = b then all_edges dfa a b ∪ {[]} else all_edges dfa a b | a b (head :: tail) := (FW a b tail) ∪ (FW a head tail * kleene_star (FW head head tail) * FW head b tail) lemma FW_to_go_restr {dfa : DFA S Q} {a b : Q} {allowed : list Q} {w : list S} : w ∈ FW dfa a b allowed → go_restr dfa allowed.to_finset a w b := begin induction allowed with head tail ih generalizing a b w, { intro hw, by_cases h : a = b, { simp [FW, all_edges, h] at hw, rcases hw with hw | ⟨ch, win⟩, { substs hw h, exact go_restr.finish, }, { split_ifs at win, { simp only [set.mem_singleton_iff] at win, substs h win, refine go_restr.last_step h_1, }, { simpa only [set.mem_empty_eq] using win, } } }, { simp [FW, all_edges, h] at hw, rcases hw with ⟨i, win⟩, split_ifs at win, { convert go_restr.last_step h_1 }, { simpa only [set.mem_empty_eq] using win }, }, }, { intro hw, cases hw, { rw [to_finset_cons], exact go_restr_insert (ih hw), }, { rcases hw with ⟨_, right, ⟨left, mid, hleft, hmid, rfl⟩, hright, rfl⟩, rw to_finset_cons, replace hleft := ih hleft, replace hright := ih hright, rw [star_eq_list_join] at hmid, rcases hmid with ⟨l, hlist, rfl⟩, have h_head := finset.mem_insert_self head tail.to_finset, refine go_restr_append h_head _ _, refine go_restr_append h_head _ _, all_goals {try {apply go_restr_list_join}, try {apply go_restr_insert}, try {assumption}}, rintro x xl, specialize ih (hlist x xl), exact go_restr_insert ih, } } end -- inductive go_restr (dfa : DFA S Q) (allow : finset Q) : Q → list S → Q → Prop -- | finish {q : Q} : go_restr q [] q -- | last_step {ch : S} {q nxt : Q} : nxt = dfa.next q ch → go_restr q [ch] nxt -- | step {head : S} {tail : list S} {q nxt f : Q} : -- nxt = dfa.next q head → nxt ∈ allow → go_restr nxt tail f → go_restr q (head::tail) f lemma go_restr_split {dfa : DFA S Q} {a b s : Q} {allowed : finset Q} {w : list S} : go_restr dfa (insert s allowed) a w b → (go_restr dfa allowed a w b) ∨ (∃ pref (inf : list (list S)) suf, go_restr dfa allowed a pref s ∧ (∀ x, x ∈ inf → go_restr dfa allowed s x s) ∧ go_restr dfa allowed s suf b ∧ pref ++ inf.join ++ suf = w) := begin intro go_ab, induction go_ab, case finish { left, exact go_restr.finish, }, case last_step : ch q nxt h_nxt { left, exact go_restr.last_step h_nxt, }, case step : head tail q nxt f h_nxt h_allow go_tail ih { by_cases nxt = s, { subst h, right, cases ih, { use [[head], [], tail], use [go_restr.last_step h_nxt, forall_mem_nil _, ih], simp only [join, eq_self_iff_true, and_self, singleton_append], }, { rcases ih with ⟨pref, inf, suf, go_pref, go_inf, go_suf, rfl⟩, use [[head], pref :: inf, suf], use [go_restr.last_step h_nxt], split, { rintro x hx, cases hx, { rw ← hx at go_pref, exact go_pref, }, { exact go_inf x hx, } }, { use go_suf, simp only [join, cons_append, eq_self_iff_true, list.append_assoc, and_self, singleton_append], } } }, { simp only [h, mem_insert, false_or, to_finset_cons] at h_allow, cases ih, { left, refine go_restr.step h_nxt h_allow ih, }, { right, rcases ih with ⟨pref, inf, suf, go_pref, go_inf, go_suf, rfl⟩, use [head :: pref, inf, suf], use [go_restr.step h_nxt h_allow go_pref], use [go_inf, go_suf], simp only [cons_append, eq_self_iff_true, and_self], } } } end lemma FW_from_go_restr {dfa : DFA S Q} {a b : Q} {allow_list : list Q} {w : list S} : go_restr dfa allow_list.to_finset a w b → w ∈ FW dfa a b allow_list := begin intro go_ab, induction allow_list with head tail ih generalizing a b w, { dsimp [FW, all_edges], cases go_ab, case go_restr.finish : { simp, }, case go_restr.last_step : _ _ _ go_ab_nxt { split_ifs; { simp [mem_sup], use [go_ab_ch], simp [go_ab_nxt], }, }, case go_restr.step : _ _ _ _ _ go_ab_nxt go_ab_allow go_ab_prev { simpa only [to_finset_nil, not_mem_empty] using go_ab_allow, } }, { dsimp [FW, all_edges], rw [to_finset_cons] at go_ab, replace go_ab := go_restr_split go_ab, rcases go_ab with _ | ⟨pref, inf, suf, go_pref, go_inf, go_suf, rfl⟩, { left, exact ih go_ab, }, { right, use [pref ++ inf.join, suf, pref, inf.join], refine ⟨ih go_pref, _, rfl⟩, apply star_eq_list_join.2 ⟨inf, λ x hx, ih (go_inf x hx), rfl⟩, use ih go_suf, } } end lemma FW_is_regex {dfa : DFA S Q} (a b : Q) {allowed : list Q} : regex_lang (FW dfa a b allowed) := begin induction allowed with head tail ih generalizing a b, { rw FW, split_ifs, all_goals {try {apply union_is_regex _ eps_is_regex}, clear h}, all_goals { simp [all_edges], rw [←set.bUnion_univ], lift (set.univ : set S) to finset S using set.finite.of_fintype (set.univ : set S), apply finset_bUnion_is_regex, intros c cx, split_ifs with hnext, { exact one_is_regex, }, { exact empty_is_regex, }, }, }, { rw FW, have rAB := ih a b, have rAH := ih a head, have rHH := ih head head, have rHB := ih head b, apply union_is_regex rAB, apply append_is_regex (append_is_regex rAH (star_is_regex rHH)) rHB, } end lemma FW_is_DFA {dfa : DFA S Q} {allowed : list Q} (hQ : allowed.to_finset = fintype.elems Q) : (⋃ c ∈ dfa.term, FW dfa dfa.start c allowed) = lang_of_dfa dfa := begin apply set.subset.antisymm, { apply set.bUnion_subset, rintro x x_term w w_fw, replace w_fw := FW_to_go_restr w_fw, rw [hQ, go_restr_univ] at w_fw, subst w_fw, exact x_term, }, { rintro w hw, refine set.mem_bUnion hw _, apply FW_from_go_restr, rw [hQ, go_restr_univ], } end theorem dfa_to_regex {L : set (list S)} : dfa_lang L → regex_lang L := begin rintro ⟨Q, fQ, dQ, dfa, rfl⟩, resetI, letI := fQ, rcases to_finset_surjective (fintype.elems Q) with ⟨Qlist, hQ⟩, rw ← FW_is_DFA hQ, apply finset_bUnion_is_regex, rintro c cx, exact FW_is_regex dfa.start c, end end regex.from_dfa
3cc28f31d27781412bc70f40756fe6f809caee26
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/library/data/int/basic.lean
af13ee87e72df49c1eb2db0ee206a874684851b9
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,796
lean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Jeremy Avigad The integers, with addition, multiplication, and subtraction. The representation of the integers is chosen to compute efficiently. To faciliate proving things about these operations, we show that the integers are a quotient of ℕ × ℕ with the usual equivalence relation, ≡, and functions abstr : ℕ × ℕ → ℤ repr : ℤ → ℕ × ℕ satisfying: abstr_repr (a : ℤ) : abstr (repr a) = a repr_abstr (p : ℕ × ℕ) : repr (abstr p) ≡ p abstr_eq (p q : ℕ × ℕ) : p ≡ q → abstr p = abstr q For example, to "lift" statements about add to statements about padd, we need to prove the following: repr_add (a b : ℤ) : repr (a + b) = padd (repr a) (repr b) padd_congr (p p' q q' : ℕ × ℕ) (H1 : p ≡ p') (H2 : q ≡ q') : padd p q ≡ p' q' -/ import data.nat.basic data.nat.order data.nat.sub data.prod import algebra.relation algebra.binary algebra.ordered_ring open eq.ops open prod relation nat open decidable binary open algebra /- the type of integers -/ inductive int : Type := | of_nat : nat → int | neg_succ_of_nat : nat → int notation `ℤ` := int definition int.of_num [coercion] [reducible] [constructor] (n : num) : ℤ := int.of_nat (nat.of_num n) namespace int attribute int.of_nat [coercion] notation `-[1+ ` n `]` := int.neg_succ_of_nat n -- for pretty-printing output protected definition prio : num := num.pred nat.prio definition int_has_zero [reducible] [instance] [priority int.prio] : has_zero int := has_zero.mk (of_nat 0) definition int_has_one [reducible] [instance] [priority int.prio] : has_one int := has_one.mk (of_nat 1) theorem of_nat_zero : of_nat (0:nat) = (0:int) := rfl theorem of_nat_one : of_nat (1:nat) = (1:int) := rfl /- definitions of basic functions -/ definition neg_of_nat : ℕ → ℤ | 0 := 0 | (succ m) := -[1+ m] definition sub_nat_nat (m n : ℕ) : ℤ := match (n - m : nat) with | 0 := of_nat (m - n) -- m ≥ n | (succ k) := -[1+ k] -- m < n, and n - m = succ k end protected definition neg (a : ℤ) : ℤ := int.cases_on a neg_of_nat succ protected definition add : ℤ → ℤ → ℤ | (of_nat m) (of_nat n) := m + n | (of_nat m) -[1+ n] := sub_nat_nat m (succ n) | -[1+ m] (of_nat n) := sub_nat_nat n (succ m) | -[1+ m] -[1+ n] := neg_of_nat (succ m + succ n) protected definition mul : ℤ → ℤ → ℤ | (of_nat m) (of_nat n) := m * n | (of_nat m) -[1+ n] := neg_of_nat (m * succ n) | -[1+ m] (of_nat n) := neg_of_nat (succ m * n) | -[1+ m] -[1+ n] := succ m * succ n /- notation -/ definition int_has_add [reducible] [instance] [priority int.prio] : has_add int := has_add.mk int.add definition int_has_neg [reducible] [instance] [priority int.prio] : has_neg int := has_neg.mk int.neg definition int_has_mul [reducible] [instance] [priority int.prio] : has_mul int := has_mul.mk int.mul lemma mul_of_nat_of_nat (m n : nat) : of_nat m * of_nat n = of_nat (m * n) := rfl lemma mul_of_nat_neg_succ_of_nat (m n : nat) : of_nat m * -[1+ n] = neg_of_nat (m * succ n) := rfl lemma mul_neg_succ_of_nat_of_nat (m n : nat) : -[1+ m] * of_nat n = neg_of_nat (succ m * n) := rfl lemma mul_neg_succ_of_nat_neg_succ_of_nat (m n : nat) : -[1+ m] * -[1+ n] = succ m * succ n := rfl /- some basic functions and properties -/ theorem of_nat.inj {m n : ℕ} (H : of_nat m = of_nat n) : m = n := int.no_confusion H imp.id theorem eq_of_of_nat_eq_of_nat {m n : ℕ} (H : of_nat m = of_nat n) : m = n := of_nat.inj H theorem of_nat_eq_of_nat_iff (m n : ℕ) : of_nat m = of_nat n ↔ m = n := iff.intro of_nat.inj !congr_arg theorem neg_succ_of_nat.inj {m n : ℕ} (H : neg_succ_of_nat m = neg_succ_of_nat n) : m = n := int.no_confusion H imp.id theorem neg_succ_of_nat_eq (n : ℕ) : -[1+ n] = -(n + 1) := rfl private definition has_decidable_eq₂ : Π (a b : ℤ), decidable (a = b) | (of_nat m) (of_nat n) := decidable_of_decidable_of_iff (nat.has_decidable_eq m n) (iff.symm (of_nat_eq_of_nat_iff m n)) | (of_nat m) -[1+ n] := inr (by contradiction) | -[1+ m] (of_nat n) := inr (by contradiction) | -[1+ m] -[1+ n] := if H : m = n then inl (congr_arg neg_succ_of_nat H) else inr (not.mto neg_succ_of_nat.inj H) definition has_decidable_eq [instance] [priority int.prio] : decidable_eq ℤ := has_decidable_eq₂ theorem of_nat_add (n m : nat) : of_nat (n + m) = of_nat n + of_nat m := rfl theorem of_nat_succ (n : ℕ) : of_nat (succ n) = of_nat n + 1 := rfl theorem of_nat_mul (n m : ℕ) : of_nat (n * m) = of_nat n * of_nat m := rfl theorem sub_nat_nat_of_ge {m n : ℕ} (H : m ≥ n) : sub_nat_nat m n = of_nat (m - n) := show sub_nat_nat m n = nat.cases_on 0 (m -[nat] n) _, from (sub_eq_zero_of_le H) ▸ rfl section local attribute sub_nat_nat [reducible] theorem sub_nat_nat_of_lt {m n : ℕ} (H : m < n) : sub_nat_nat m n = -[1+ pred (n - m)] := have H1 : n - m = succ (pred (n - m)), from eq.symm (succ_pred_of_pos (nat.sub_pos_of_lt H)), show sub_nat_nat m n = nat.cases_on (succ (nat.pred (n - m))) (m -[nat] n) _, from H1 ▸ rfl end definition nat_abs (a : ℤ) : ℕ := int.cases_on a id succ theorem nat_abs_of_nat (n : ℕ) : nat_abs n = n := rfl theorem eq_zero_of_nat_abs_eq_zero : Π {a : ℤ}, nat_abs a = 0 → a = 0 | (of_nat m) H := congr_arg of_nat H | -[1+ m'] H := absurd H !succ_ne_zero theorem nat_abs_zero : nat_abs (0:int) = (0:nat) := rfl theorem nat_abs_one : nat_abs (1:int) = (1:nat) := rfl /- int is a quotient of ordered pairs of natural numbers -/ protected definition equiv (p q : ℕ × ℕ) : Prop := pr1 p + pr2 q = pr2 p + pr1 q local infix ≡ := int.equiv protected theorem equiv.refl [refl] {p : ℕ × ℕ} : p ≡ p := !add.comm protected theorem equiv.symm [symm] {p q : ℕ × ℕ} (H : p ≡ q) : q ≡ p := calc pr1 q + pr2 p = pr2 p + pr1 q : by rewrite add.comm ... = pr1 p + pr2 q : H⁻¹ ... = pr2 q + pr1 p : by rewrite add.comm protected theorem equiv.trans [trans] {p q r : ℕ × ℕ} (H1 : p ≡ q) (H2 : q ≡ r) : p ≡ r := add.right_cancel (calc pr1 p + pr2 r + pr2 q = pr1 p + pr2 q + pr2 r : by rewrite add.right_comm ... = pr2 p + pr1 q + pr2 r : {H1} ... = pr2 p + (pr1 q + pr2 r) : by rewrite add.assoc ... = pr2 p + (pr2 q + pr1 r) : {H2} ... = pr2 p + pr2 q + pr1 r : by rewrite add.assoc ... = pr2 p + pr1 r + pr2 q : by rewrite add.right_comm) protected theorem equiv_equiv : is_equivalence int.equiv := is_equivalence.mk @equiv.refl @equiv.symm @equiv.trans protected theorem equiv_cases {p q : ℕ × ℕ} (H : p ≡ q) : (pr1 p ≥ pr2 p ∧ pr1 q ≥ pr2 q) ∨ (pr1 p < pr2 p ∧ pr1 q < pr2 q) := or.elim (@le_or_gt _ _ (pr2 p) (pr1 p)) (suppose pr1 p ≥ pr2 p, have pr2 p + pr1 q ≥ pr2 p + pr2 q, from H ▸ add_le_add_right this (pr2 q), or.inl (and.intro `pr1 p ≥ pr2 p` (le_of_add_le_add_left this))) (suppose H₁ : pr1 p < pr2 p, have pr2 p + pr1 q < pr2 p + pr2 q, from H ▸ add_lt_add_right H₁ (pr2 q), or.inr (and.intro H₁ (lt_of_add_lt_add_left this))) protected theorem equiv_of_eq {p q : ℕ × ℕ} (H : p = q) : p ≡ q := H ▸ equiv.refl /- the representation and abstraction functions -/ definition abstr (a : ℕ × ℕ) : ℤ := sub_nat_nat (pr1 a) (pr2 a) theorem abstr_of_ge {p : ℕ × ℕ} (H : pr1 p ≥ pr2 p) : abstr p = of_nat (pr1 p - pr2 p) := sub_nat_nat_of_ge H theorem abstr_of_lt {p : ℕ × ℕ} (H : pr1 p < pr2 p) : abstr p = -[1+ pred (pr2 p - pr1 p)] := sub_nat_nat_of_lt H definition repr : ℤ → ℕ × ℕ | (of_nat m) := (m, 0) | -[1+ m] := (0, succ m) theorem abstr_repr : Π (a : ℤ), abstr (repr a) = a | (of_nat m) := (sub_nat_nat_of_ge (zero_le m)) | -[1+ m] := rfl theorem repr_sub_nat_nat (m n : ℕ) : repr (sub_nat_nat m n) ≡ (m, n) := nat.lt_ge_by_cases (take H : m < n, have H1 : repr (sub_nat_nat m n) = (0, n - m), by rewrite [sub_nat_nat_of_lt H, -(succ_pred_of_pos (nat.sub_pos_of_lt H))], H1⁻¹ ▸ (!zero_add ⬝ (nat.sub_add_cancel (le_of_lt H))⁻¹)) (take H : m ≥ n, have H1 : repr (sub_nat_nat m n) = (m - n, 0), from sub_nat_nat_of_ge H ▸ rfl, H1⁻¹ ▸ ((nat.sub_add_cancel H) ⬝ !zero_add⁻¹)) theorem repr_abstr (p : ℕ × ℕ) : repr (abstr p) ≡ p := !prod.eta ▸ !repr_sub_nat_nat theorem abstr_eq {p q : ℕ × ℕ} (Hequiv : p ≡ q) : abstr p = abstr q := or.elim (int.equiv_cases Hequiv) (and.rec (assume (Hp : pr1 p ≥ pr2 p) (Hq : pr1 q ≥ pr2 q), have H : pr1 p - pr2 p = pr1 q - pr2 q, from calc pr1 p - pr2 p = pr1 p + pr2 q - pr2 q - pr2 p : by rewrite nat.add_sub_cancel ... = pr2 p + pr1 q - pr2 q - pr2 p : Hequiv ... = pr2 p + (pr1 q - pr2 q) - pr2 p : nat.add_sub_assoc Hq ... = pr1 q - pr2 q + pr2 p - pr2 p : by rewrite add.comm ... = pr1 q - pr2 q : by rewrite nat.add_sub_cancel, abstr_of_ge Hp ⬝ (H ▸ rfl) ⬝ (abstr_of_ge Hq)⁻¹)) (and.rec (assume (Hp : pr1 p < pr2 p) (Hq : pr1 q < pr2 q), have H : pr2 p - pr1 p = pr2 q - pr1 q, from calc pr2 p - pr1 p = pr2 p + pr1 q - pr1 q - pr1 p : by rewrite nat.add_sub_cancel ... = pr1 p + pr2 q - pr1 q - pr1 p : Hequiv ... = pr1 p + (pr2 q - pr1 q) - pr1 p : nat.add_sub_assoc (le_of_lt Hq) ... = pr2 q - pr1 q + pr1 p - pr1 p : by rewrite add.comm ... = pr2 q - pr1 q : by rewrite nat.add_sub_cancel, abstr_of_lt Hp ⬝ (H ▸ rfl) ⬝ (abstr_of_lt Hq)⁻¹)) theorem equiv_iff (p q : ℕ × ℕ) : (p ≡ q) ↔ (abstr p = abstr q) := iff.intro abstr_eq (assume H, equiv.trans (H ▸ equiv.symm (repr_abstr p)) (repr_abstr q)) theorem equiv_iff3 (p q : ℕ × ℕ) : (p ≡ q) ↔ ((p ≡ p) ∧ (q ≡ q) ∧ (abstr p = abstr q)) := iff.trans !equiv_iff (iff.symm (iff.trans (and_iff_right !equiv.refl) (and_iff_right !equiv.refl))) theorem eq_abstr_of_equiv_repr {a : ℤ} {p : ℕ × ℕ} (Hequiv : repr a ≡ p) : a = abstr p := !abstr_repr⁻¹ ⬝ abstr_eq Hequiv theorem eq_of_repr_equiv_repr {a b : ℤ} (H : repr a ≡ repr b) : a = b := eq_abstr_of_equiv_repr H ⬝ !abstr_repr section local attribute abstr [reducible] local attribute dist [reducible] theorem nat_abs_abstr : Π (p : ℕ × ℕ), nat_abs (abstr p) = dist (pr1 p) (pr2 p) | (m, n) := nat.lt_ge_by_cases (assume H : m < n, calc nat_abs (abstr (m, n)) = nat_abs (-[1+ pred (n - m)]) : int.abstr_of_lt H ... = n - m : succ_pred_of_pos (nat.sub_pos_of_lt H) ... = dist m n : dist_eq_sub_of_le (le_of_lt H)) (assume H : m ≥ n, (abstr_of_ge H)⁻¹ ▸ (dist_eq_sub_of_ge H)⁻¹) end theorem cases_of_nat_succ (a : ℤ) : (∃n : ℕ, a = of_nat n) ∨ (∃n : ℕ, a = - (of_nat (succ n))) := int.cases_on a (take m, or.inl (exists.intro _ rfl)) (take m, or.inr (exists.intro _ rfl)) theorem cases_of_nat (a : ℤ) : (∃n : ℕ, a = of_nat n) ∨ (∃n : ℕ, a = - of_nat n) := or.imp_right (Exists.rec (take n, (exists.intro _))) !cases_of_nat_succ theorem by_cases_of_nat {P : ℤ → Prop} (a : ℤ) (H1 : ∀n : ℕ, P (of_nat n)) (H2 : ∀n : ℕ, P (- of_nat n)) : P a := or.elim (cases_of_nat a) (assume H, obtain (n : ℕ) (H3 : a = n), from H, H3⁻¹ ▸ H1 n) (assume H, obtain (n : ℕ) (H3 : a = -n), from H, H3⁻¹ ▸ H2 n) theorem by_cases_of_nat_succ {P : ℤ → Prop} (a : ℤ) (H1 : ∀n : ℕ, P (of_nat n)) (H2 : ∀n : ℕ, P (- of_nat (succ n))) : P a := or.elim (cases_of_nat_succ a) (assume H, obtain (n : ℕ) (H3 : a = n), from H, H3⁻¹ ▸ H1 n) (assume H, obtain (n : ℕ) (H3 : a = -(succ n)), from H, H3⁻¹ ▸ H2 n) /- int is a ring -/ /- addition -/ definition padd (p q : ℕ × ℕ) : ℕ × ℕ := (pr1 p + pr1 q, pr2 p + pr2 q) theorem repr_add : Π (a b : ℤ), repr (add a b) ≡ padd (repr a) (repr b) | (of_nat m) (of_nat n) := !equiv.refl | (of_nat m) -[1+ n] := begin change repr (sub_nat_nat m (succ n)) ≡ (m + 0, 0 + succ n), rewrite [zero_add, add_zero], apply repr_sub_nat_nat end | -[1+ m] (of_nat n) := begin change repr (-[1+ m] + n) ≡ (0 + n, succ m + 0), rewrite [zero_add, add_zero], apply repr_sub_nat_nat end | -[1+ m] -[1+ n] := !repr_sub_nat_nat theorem padd_congr {p p' q q' : ℕ × ℕ} (Ha : p ≡ p') (Hb : q ≡ q') : padd p q ≡ padd p' q' := calc pr1 p + pr1 q + (pr2 p' + pr2 q') = pr1 p + pr2 p' + (pr1 q + pr2 q') : add.comm4 ... = pr2 p + pr1 p' + (pr1 q + pr2 q') : {Ha} ... = pr2 p + pr1 p' + (pr2 q + pr1 q') : {Hb} ... = pr2 p + pr2 q + (pr1 p' + pr1 q') : add.comm4 theorem padd_comm (p q : ℕ × ℕ) : padd p q = padd q p := calc (pr1 p + pr1 q, pr2 p + pr2 q) = (pr1 q + pr1 p, pr2 p + pr2 q) : by rewrite add.comm ... = (pr1 q + pr1 p, pr2 q + pr2 p) : by rewrite (add.comm (pr2 p) (pr2 q)) theorem padd_assoc (p q r : ℕ × ℕ) : padd (padd p q) r = padd p (padd q r) := calc (pr1 p + pr1 q + pr1 r, pr2 p + pr2 q + pr2 r) = (pr1 p + (pr1 q + pr1 r), pr2 p + pr2 q + pr2 r) : by rewrite add.assoc ... = (pr1 p + (pr1 q + pr1 r), pr2 p + (pr2 q + pr2 r)) : by rewrite add.assoc protected theorem add_comm (a b : ℤ) : a + b = b + a := eq_of_repr_equiv_repr (equiv.trans !repr_add (equiv.symm (!padd_comm ▸ !repr_add))) protected theorem add_assoc (a b c : ℤ) : a + b + c = a + (b + c) := eq_of_repr_equiv_repr (calc repr (a + b + c) ≡ padd (repr (a + b)) (repr c) : repr_add ... ≡ padd (padd (repr a) (repr b)) (repr c) : padd_congr !repr_add !equiv.refl ... = padd (repr a) (padd (repr b) (repr c)) : !padd_assoc ... ≡ padd (repr a) (repr (b + c)) : padd_congr !equiv.refl !repr_add ... ≡ repr (a + (b + c)) : repr_add) protected theorem add_zero : Π (a : ℤ), a + 0 = a := int.rec (λm, rfl) (λm, rfl) protected theorem zero_add (a : ℤ) : 0 + a = a := !int.add_comm ▸ !int.add_zero /- negation -/ definition pneg (p : ℕ × ℕ) : ℕ × ℕ := (pr2 p, pr1 p) -- note: this is =, not just ≡ theorem repr_neg : Π (a : ℤ), repr (- a) = pneg (repr a) | 0 := rfl | (succ m) := rfl | -[1+ m] := rfl theorem pneg_congr {p p' : ℕ × ℕ} (H : p ≡ p') : pneg p ≡ pneg p' := eq.symm H theorem pneg_pneg (p : ℕ × ℕ) : pneg (pneg p) = p := !prod.eta theorem nat_abs_neg (a : ℤ) : nat_abs (-a) = nat_abs a := calc nat_abs (-a) = nat_abs (abstr (repr (-a))) : abstr_repr ... = nat_abs (abstr (pneg (repr a))) : repr_neg ... = dist (pr1 (pneg (repr a))) (pr2 (pneg (repr a))) : nat_abs_abstr ... = dist (pr2 (pneg (repr a))) (pr1 (pneg (repr a))) : dist.comm ... = nat_abs (abstr (repr a)) : nat_abs_abstr ... = nat_abs a : abstr_repr theorem padd_pneg (p : ℕ × ℕ) : padd p (pneg p) ≡ (0, 0) := show pr1 p + pr2 p + 0 = pr2 p + pr1 p + 0, from !nat.add_comm ▸ rfl theorem padd_padd_pneg (p q : ℕ × ℕ) : padd (padd p q) (pneg q) ≡ p := calc pr1 p + pr1 q + pr2 q + pr2 p = pr1 p + (pr1 q + pr2 q) + pr2 p : algebra.add.assoc ... = pr1 p + (pr1 q + pr2 q + pr2 p) : algebra.add.assoc ... = pr1 p + (pr2 q + pr1 q + pr2 p) : algebra.add.comm ... = pr1 p + (pr2 q + pr2 p + pr1 q) : algebra.add.right_comm ... = pr1 p + (pr2 p + pr2 q + pr1 q) : algebra.add.comm ... = pr2 p + pr2 q + pr1 q + pr1 p : algebra.add.comm protected theorem add_left_inv (a : ℤ) : -a + a = 0 := have H : repr (-a + a) ≡ repr 0, from calc repr (-a + a) ≡ padd (repr (neg a)) (repr a) : repr_add ... = padd (pneg (repr a)) (repr a) : repr_neg ... ≡ repr 0 : padd_pneg, eq_of_repr_equiv_repr H /- nat abs -/ definition pabs (p : ℕ × ℕ) : ℕ := dist (pr1 p) (pr2 p) theorem pabs_congr {p q : ℕ × ℕ} (H : p ≡ q) : pabs p = pabs q := calc pabs p = nat_abs (abstr p) : nat_abs_abstr ... = nat_abs (abstr q) : abstr_eq H ... = pabs q : nat_abs_abstr theorem nat_abs_eq_pabs_repr (a : ℤ) : nat_abs a = pabs (repr a) := calc nat_abs a = nat_abs (abstr (repr a)) : abstr_repr ... = pabs (repr a) : nat_abs_abstr theorem nat_abs_add_le (a b : ℤ) : nat_abs (a + b) ≤ nat_abs a + nat_abs b := calc nat_abs (a + b) = pabs (repr (a + b)) : nat_abs_eq_pabs_repr ... = pabs (padd (repr a) (repr b)) : pabs_congr !repr_add ... ≤ pabs (repr a) + pabs (repr b) : dist_add_add_le_add_dist_dist ... = pabs (repr a) + nat_abs b : nat_abs_eq_pabs_repr ... = nat_abs a + nat_abs b : nat_abs_eq_pabs_repr theorem nat_abs_neg_of_nat (n : nat) : nat_abs (neg_of_nat n) = n := begin cases n, reflexivity, reflexivity end section local attribute nat_abs [reducible] theorem nat_abs_mul : Π (a b : ℤ), nat_abs (a * b) = (nat_abs a) * (nat_abs b) | (of_nat m) (of_nat n) := rfl | (of_nat m) -[1+ n] := by rewrite [mul_of_nat_neg_succ_of_nat, nat_abs_neg_of_nat] | -[1+ m] (of_nat n) := by rewrite [mul_neg_succ_of_nat_of_nat, nat_abs_neg_of_nat] | -[1+ m] -[1+ n] := rfl end /- multiplication -/ definition pmul (p q : ℕ × ℕ) : ℕ × ℕ := (pr1 p * pr1 q + pr2 p * pr2 q, pr1 p * pr2 q + pr2 p * pr1 q) theorem repr_neg_of_nat (m : ℕ) : repr (neg_of_nat m) = (0, m) := nat.cases_on m rfl (take m', rfl) -- note: we have =, not just ≡ theorem repr_mul : Π (a b : ℤ), repr (a * b) = pmul (repr a) (repr b) | (of_nat m) (of_nat n) := calc (m * n + 0 * 0, m * 0 + 0) = (m * n + 0 * 0, m * 0 + 0 * n) : by rewrite *zero_mul | (of_nat m) -[1+ n] := calc repr ((m : int) * -[1+ n]) = (m * 0 + 0, m * succ n + 0 * 0) : repr_neg_of_nat ... = (m * 0 + 0 * succ n, m * succ n + 0 * 0) : by rewrite *zero_mul | -[1+ m] (of_nat n) := calc repr (-[1+ m] * (n:int)) = (0 + succ m * 0, succ m * n) : repr_neg_of_nat ... = (0 + succ m * 0, 0 + succ m * n) : nat.zero_add ... = (0 * n + succ m * 0, 0 + succ m * n) : by rewrite zero_mul | -[1+ m] -[1+ n] := calc (succ m * succ n, 0) = (succ m * succ n, 0 * succ n) : by rewrite zero_mul ... = (0 + succ m * succ n, 0 * succ n) : nat.zero_add theorem equiv_mul_prep {xa ya xb yb xn yn xm ym : ℕ} (H1 : xa + yb = ya + xb) (H2 : xn + ym = yn + xm) : xa*xn+ya*yn+(xb*ym+yb*xm) = xa*yn+ya*xn+(xb*xm+yb*ym) := nat.add_right_cancel (calc xa*xn+ya*yn + (xb*ym+yb*xm) + (yb*xn+xb*yn + (xb*xn+yb*yn)) = xa*xn+ya*yn + (yb*xn+xb*yn) + (xb*ym+yb*xm + (xb*xn+yb*yn)) : by rewrite add.comm4 ... = xa*xn+ya*yn + (yb*xn+xb*yn) + (xb*xn+yb*yn + (xb*ym+yb*xm)) : by rewrite {xb*ym+yb*xm +_}nat.add_comm ... = xa*xn+yb*xn + (ya*yn+xb*yn) + (xb*xn+xb*ym + (yb*yn+yb*xm)) : by exact !congr_arg2 !add.comm4 !add.comm4 ... = ya*xn+xb*xn + (xa*yn+yb*yn) + (xb*yn+xb*xm + (yb*xn+yb*ym)) : by rewrite[-+left_distrib,-+right_distrib]; exact H1 ▸ H2 ▸ rfl ... = ya*xn+xa*yn + (xb*xn+yb*yn) + (xb*yn+yb*xn + (xb*xm+yb*ym)) : by exact !congr_arg2 !add.comm4 !add.comm4 ... = xa*yn+ya*xn + (xb*xn+yb*yn) + (xb*yn+yb*xn + (xb*xm+yb*ym)) : by rewrite {xa*yn + _}nat.add_comm ... = xa*yn+ya*xn + (xb*xn+yb*yn) + (yb*xn+xb*yn + (xb*xm+yb*ym)) : by rewrite {xb*yn + _}nat.add_comm ... = xa*yn+ya*xn + (yb*xn+xb*yn) + (xb*xn+yb*yn + (xb*xm+yb*ym)) : by rewrite (!add.comm4) ... = xa*yn+ya*xn + (yb*xn+xb*yn) + (xb*xm+yb*ym + (xb*xn+yb*yn)) : by rewrite {xb*xn+yb*yn + _}nat.add_comm ... = xa*yn+ya*xn + (xb*xm+yb*ym) + (yb*xn+xb*yn + (xb*xn+yb*yn)) : by rewrite add.comm4) theorem pmul_congr {p p' q q' : ℕ × ℕ} : p ≡ p' → q ≡ q' → pmul p q ≡ pmul p' q' := equiv_mul_prep theorem pmul_comm (p q : ℕ × ℕ) : pmul p q = pmul q p := show (_,_) = (_,_), begin congruence, { congruence, repeat rewrite mul.comm }, { rewrite algebra.add.comm, congruence, repeat rewrite mul.comm } end protected theorem mul_comm (a b : ℤ) : a * b = b * a := eq_of_repr_equiv_repr ((calc repr (a * b) = pmul (repr a) (repr b) : repr_mul ... = pmul (repr b) (repr a) : pmul_comm ... = repr (b * a) : repr_mul) ▸ !equiv.refl) private theorem pmul_assoc_prep {p1 p2 q1 q2 r1 r2 : ℕ} : ((p1*q1+p2*q2)*r1+(p1*q2+p2*q1)*r2, (p1*q1+p2*q2)*r2+(p1*q2+p2*q1)*r1) = (p1*(q1*r1+q2*r2)+p2*(q1*r2+q2*r1), p1*(q1*r2+q2*r1)+p2*(q1*r1+q2*r2)) := begin rewrite[+left_distrib,+right_distrib,*algebra.mul.assoc], exact (congr_arg2 pair (!add.comm4 ⬝ (!congr_arg !nat.add_comm)) (!add.comm4 ⬝ (!congr_arg !nat.add_comm))) end theorem pmul_assoc (p q r: ℕ × ℕ) : pmul (pmul p q) r = pmul p (pmul q r) := pmul_assoc_prep protected theorem mul_assoc (a b c : ℤ) : (a * b) * c = a * (b * c) := eq_of_repr_equiv_repr ((calc repr (a * b * c) = pmul (repr (a * b)) (repr c) : repr_mul ... = pmul (pmul (repr a) (repr b)) (repr c) : repr_mul ... = pmul (repr a) (pmul (repr b) (repr c)) : pmul_assoc ... = pmul (repr a) (repr (b * c)) : repr_mul ... = repr (a * (b * c)) : repr_mul) ▸ !equiv.refl) protected theorem mul_one : Π (a : ℤ), a * 1 = a | (of_nat m) := !int.zero_add -- zero_add happens to be def. = to this thm | -[1+ m] := !nat.zero_add ▸ rfl protected theorem one_mul (a : ℤ) : 1 * a = a := int.mul_comm a 1 ▸ int.mul_one a private theorem mul_distrib_prep {a1 a2 b1 b2 c1 c2 : ℕ} : ((a1+b1)*c1+(a2+b2)*c2, (a1+b1)*c2+(a2+b2)*c1) = (a1*c1+a2*c2+(b1*c1+b2*c2), a1*c2+a2*c1+(b1*c2+b2*c1)) := begin rewrite +right_distrib, congruence, {rewrite add.comm4}, {rewrite add.comm4} end protected theorem right_distrib (a b c : ℤ) : (a + b) * c = a * c + b * c := eq_of_repr_equiv_repr (calc repr ((a + b) * c) = pmul (repr (a + b)) (repr c) : repr_mul ... ≡ pmul (padd (repr a) (repr b)) (repr c) : pmul_congr !repr_add equiv.refl ... = padd (pmul (repr a) (repr c)) (pmul (repr b) (repr c)) : mul_distrib_prep ... = padd (repr (a * c)) (pmul (repr b) (repr c)) : repr_mul ... = padd (repr (a * c)) (repr (b * c)) : repr_mul ... ≡ repr (a * c + b * c) : repr_add) protected theorem left_distrib (a b c : ℤ) : a * (b + c) = a * b + a * c := calc a * (b + c) = (b + c) * a : int.mul_comm ... = b * a + c * a : int.right_distrib ... = a * b + c * a : int.mul_comm ... = a * b + a * c : int.mul_comm protected theorem zero_ne_one : (0 : int) ≠ 1 := assume H : 0 = 1, !succ_ne_zero (of_nat.inj H)⁻¹ protected theorem eq_zero_or_eq_zero_of_mul_eq_zero {a b : ℤ} (H : a * b = 0) : a = 0 ∨ b = 0 := or.imp eq_zero_of_nat_abs_eq_zero eq_zero_of_nat_abs_eq_zero (eq_zero_or_eq_zero_of_mul_eq_zero (by rewrite [-nat_abs_mul, H])) protected definition integral_domain [reducible] [trans_instance] : algebra.integral_domain int := ⦃algebra.integral_domain, add := int.add, add_assoc := int.add_assoc, zero := 0, zero_add := int.zero_add, add_zero := int.add_zero, neg := int.neg, add_left_inv := int.add_left_inv, add_comm := int.add_comm, mul := int.mul, mul_assoc := int.mul_assoc, one := 1, one_mul := int.one_mul, mul_one := int.mul_one, left_distrib := int.left_distrib, right_distrib := int.right_distrib, mul_comm := int.mul_comm, zero_ne_one := int.zero_ne_one, eq_zero_or_eq_zero_of_mul_eq_zero := @int.eq_zero_or_eq_zero_of_mul_eq_zero⦄ definition int_has_sub [reducible] [instance] [priority int.prio] : has_sub int := has_sub.mk has_sub.sub definition int_has_dvd [reducible] [instance] [priority int.prio] : has_dvd int := has_dvd.mk has_dvd.dvd /- additional properties -/ theorem of_nat_sub {m n : ℕ} (H : m ≥ n) : of_nat (m - n) = of_nat m - of_nat n := assert m - n + n = m, from nat.sub_add_cancel H, begin symmetry, apply algebra.sub_eq_of_eq_add, rewrite [-of_nat_add, this] end theorem neg_succ_of_nat_eq' (m : ℕ) : -[1+ m] = -m - 1 := by rewrite [neg_succ_of_nat_eq, neg_add] definition succ (a : ℤ) := a + (succ zero) definition pred (a : ℤ) := a - (succ zero) theorem pred_succ (a : ℤ) : pred (succ a) = a := !sub_add_cancel theorem succ_pred (a : ℤ) : succ (pred a) = a := !add_sub_cancel theorem neg_succ (a : ℤ) : -succ a = pred (-a) := by rewrite [↑succ,neg_add] theorem succ_neg_succ (a : ℤ) : succ (-succ a) = -a := by rewrite [neg_succ,succ_pred] theorem neg_pred (a : ℤ) : -pred a = succ (-a) := by rewrite [↑pred,neg_sub,sub_eq_add_neg,add.comm] theorem pred_neg_pred (a : ℤ) : pred (-pred a) = -a := by rewrite [neg_pred,pred_succ] theorem pred_nat_succ (n : ℕ) : pred (nat.succ n) = n := pred_succ n theorem neg_nat_succ (n : ℕ) : -nat.succ n = pred (-n) := !neg_succ theorem succ_neg_nat_succ (n : ℕ) : succ (-nat.succ n) = -n := !succ_neg_succ definition rec_nat_on [unfold 2] {P : ℤ → Type} (z : ℤ) (H0 : P 0) (Hsucc : Π⦃n : ℕ⦄, P n → P (succ n)) (Hpred : Π⦃n : ℕ⦄, P (-n) → P (-nat.succ n)) : P z := int.rec (nat.rec H0 Hsucc) (λn, nat.rec H0 Hpred (nat.succ n)) z --the only computation rule of rec_nat_on which is not definitional theorem rec_nat_on_neg {P : ℤ → Type} (n : nat) (H0 : P zero) (Hsucc : Π⦃n : nat⦄, P n → P (succ n)) (Hpred : Π⦃n : nat⦄, P (-n) → P (-nat.succ n)) : rec_nat_on (-nat.succ n) H0 Hsucc Hpred = Hpred (rec_nat_on (-n) H0 Hsucc Hpred) := nat.rec rfl (λn H, rfl) n end int
3127c483cd4a3a1b02d6bec670e945134e663e60
6dacdff2020860f2468bb8dacf344e6b043d6a78
/love/src/demo_gptf.lean
0ed4569bd186a3dd18119257217ae2bad74713ae
[]
no_license
alexjbest/talks
514ca57af312a14cf68c30efa1c7228294edc190
84976b4329ea768c754da72cc15d5ce29332466d
refs/heads/master
1,686,993,465,308
1,686,315,975,000
1,686,315,975,000
16,347,963
2
0
null
null
null
null
UTF-8
Lean
false
false
170
lean
import tactic.gptf lemma my_lemma {α} (a : α) : a = a := begin gptf {n := 32, temp := 1.0} -- this will query the server and return a set of 'try this' commands. end
e4fb05a77039ce611e2bbb60825454d0732da14b
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/hom/non_unital_alg.lean
1c82398d8a8a311bc86b4fa8d15ea83b46cef35a
[ "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,063
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.algebra.basic /-! # Morphisms of non-unital algebras This file defines morphisms between two types, each of which carries: * an addition, * an additive zero, * a multiplication, * a scalar action. The multiplications are not assumed to be associative or unital, or even to be compatible with the scalar actions. In a typical application, the operations will satisfy compatibility conditions making them into algebras (albeit possibly non-associative and/or non-unital) but such conditions are not required to make this definition. This notion of morphism should be useful for any category of non-unital algebras. The motivating application at the time it was introduced was to be able to state the adjunction property for magma algebras. These are non-unital, non-associative algebras obtained by applying the group-algebra construction except where we take a type carrying just `has_mul` instead of `group`. For a plausible future application, one could take the non-unital algebra of compactly-supported functions on a non-compact topological space. A proper map between a pair of such spaces (contravariantly) induces a morphism between their algebras of compactly-supported functions which will be a `non_unital_alg_hom`. TODO: add `non_unital_alg_equiv` when needed. ## Main definitions * `non_unital_alg_hom` * `alg_hom.to_non_unital_alg_hom` ## Tags non-unital, algebra, morphism -/ universes u v w w₁ w₂ w₃ variables (R : Type u) (A : Type v) (B : Type w) (C : Type w₁) set_option old_structure_cmd true /-- A morphism respecting addition, multiplication, and scalar multiplication. When these arise from algebra structures, this is the same as a not-necessarily-unital morphism of algebras. -/ structure non_unital_alg_hom [monoid R] [non_unital_non_assoc_semiring A] [distrib_mul_action R A] [non_unital_non_assoc_semiring B] [distrib_mul_action R B] extends A →+[R] B, A →ₙ* B infixr ` →ₙₐ `:25 := non_unital_alg_hom _ notation A ` →ₙₐ[`:25 R `] ` B := non_unital_alg_hom R A B attribute [nolint doc_blame] non_unital_alg_hom.to_distrib_mul_action_hom attribute [nolint doc_blame] non_unital_alg_hom.to_mul_hom namespace non_unital_alg_hom variables {R A B C} [monoid R] variables [non_unital_non_assoc_semiring A] [distrib_mul_action R A] variables [non_unital_non_assoc_semiring B] [distrib_mul_action R B] variables [non_unital_non_assoc_semiring C] [distrib_mul_action R C] /-- see Note [function coercion] -/ instance : has_coe_to_fun (A →ₙₐ[R] B) (λ _, A → B) := ⟨to_fun⟩ @[simp] lemma to_fun_eq_coe (f : A →ₙₐ[R] B) : f.to_fun = ⇑f := rfl initialize_simps_projections non_unital_alg_hom (to_fun → apply) lemma coe_injective : @function.injective (A →ₙₐ[R] B) (A → B) coe_fn := by rintro ⟨f, _⟩ ⟨g, _⟩ ⟨h⟩; congr @[ext] lemma ext {f g : A →ₙₐ[R] B} (h : ∀ x, f x = g x) : f = g := coe_injective $ funext h lemma ext_iff {f g : A →ₙₐ[R] B} : f = g ↔ ∀ x, f x = g x := ⟨by { rintro rfl x, refl }, ext⟩ lemma congr_fun {f g : A →ₙₐ[R] B} (h : f = g) (x : A) : f x = g x := h ▸ rfl @[simp] lemma coe_mk (f : A → B) (h₁ h₂ h₃ h₄) : ((⟨f, h₁, h₂, h₃, h₄⟩ : A →ₙₐ[R] B) : A → B) = f := rfl @[simp] lemma mk_coe (f : A →ₙₐ[R] B) (h₁ h₂ h₃ h₄) : (⟨f, h₁, h₂, h₃, h₄⟩ : A →ₙₐ[R] B) = f := by { ext, refl, } instance : has_coe (A →ₙₐ[R] B) (A →+[R] B) := ⟨to_distrib_mul_action_hom⟩ instance : has_coe (A →ₙₐ[R] B) (A →ₙ* B) := ⟨to_mul_hom⟩ @[simp] lemma to_distrib_mul_action_hom_eq_coe (f : A →ₙₐ[R] B) : f.to_distrib_mul_action_hom = ↑f := rfl @[simp] lemma to_mul_hom_eq_coe (f : A →ₙₐ[R] B) : f.to_mul_hom = ↑f := rfl @[simp, norm_cast] lemma coe_to_distrib_mul_action_hom (f : A →ₙₐ[R] B) : ((f : A →+[R] B) : A → B) = f := rfl @[simp, norm_cast] lemma coe_to_mul_hom (f : A →ₙₐ[R] B) : ((f : A →ₙ* B) : A → B) = f := rfl lemma to_distrib_mul_action_hom_injective {f g : A →ₙₐ[R] B} (h : (f : A →+[R] B) = (g : A →+[R] B)) : f = g := by { ext a, exact distrib_mul_action_hom.congr_fun h a, } lemma to_mul_hom_injective {f g : A →ₙₐ[R] B} (h : (f : A →ₙ* B) = (g : A →ₙ* B)) : f = g := by { ext a, exact mul_hom.congr_fun h a, } @[norm_cast] lemma coe_distrib_mul_action_hom_mk (f : A →ₙₐ[R] B) (h₁ h₂ h₃ h₄) : ((⟨f, h₁, h₂, h₃, h₄⟩ : A →ₙₐ[R] B) : A →+[R] B) = ⟨f, h₁, h₂, h₃⟩ := by { ext, refl, } @[norm_cast] lemma coe_mul_hom_mk (f : A →ₙₐ[R] B) (h₁ h₂ h₃ h₄) : ((⟨f, h₁, h₂, h₃, h₄⟩ : A →ₙₐ[R] B) : A →ₙ* B) = ⟨f, h₄⟩ := by { ext, refl, } @[simp] lemma map_smul (f : A →ₙₐ[R] B) (c : R) (x : A) : f (c • x) = c • f x := f.to_distrib_mul_action_hom.map_smul c x @[simp] lemma map_add (f : A →ₙₐ[R] B) (x y : A) : f (x + y) = (f x) + (f y) := f.to_distrib_mul_action_hom.map_add x y @[simp] lemma map_mul (f : A →ₙₐ[R] B) (x y : A) : f (x * y) = (f x) * (f y) := f.to_mul_hom.map_mul x y @[simp] lemma map_zero (f : A →ₙₐ[R] B) : f 0 = 0 := f.to_distrib_mul_action_hom.map_zero instance : has_zero (A →ₙₐ[R] B) := ⟨{ map_mul' := by simp, .. (0 : A →+[R] B) }⟩ instance : has_one (A →ₙₐ[R] A) := ⟨{ map_mul' := by simp, .. (1 : A →+[R] A) }⟩ @[simp] lemma coe_zero : ((0 : A →ₙₐ[R] B) : A → B) = 0 := rfl @[simp] lemma coe_one : ((1 : A →ₙₐ[R] A) : A → A) = id := rfl lemma zero_apply (a : A) : (0 : A →ₙₐ[R] B) a = 0 := rfl lemma one_apply (a : A) : (1 : A →ₙₐ[R] A) a = a := rfl instance : inhabited (A →ₙₐ[R] B) := ⟨0⟩ /-- The composition of morphisms is a morphism. -/ def comp (f : B →ₙₐ[R] C) (g : A →ₙₐ[R] B) : A →ₙₐ[R] C := { .. (f : B →ₙ* C).comp (g : A →ₙ* B), .. (f : B →+[R] C).comp (g : A →+[R] B) } @[simp, norm_cast] lemma coe_comp (f : B →ₙₐ[R] C) (g : A →ₙₐ[R] B) : (f.comp g : A → C) = (f : B → C) ∘ (g : A → B) := rfl lemma comp_apply (f : B →ₙₐ[R] C) (g : A →ₙₐ[R] B) (x : A) : f.comp g x = f (g x) := rfl /-- The inverse of a bijective morphism is a morphism. -/ def inverse (f : A →ₙₐ[R] B) (g : B → A) (h₁ : function.left_inverse g f) (h₂ : function.right_inverse g f) : B →ₙₐ[R] A := { .. (f : A →ₙ* B).inverse g h₁ h₂, .. (f : A →+[R] B).inverse g h₁ h₂ } @[simp] lemma coe_inverse (f : A →ₙₐ[R] B) (g : B → A) (h₁ : function.left_inverse g f) (h₂ : function.right_inverse g f) : (inverse f g h₁ h₂ : B → A) = g := rfl /-! ### Operations on the product type Note that much of this is copied from [`linear_algebra/prod`](../../linear_algebra/prod). -/ section prod variables (R A B) /-- The first projection of a product is a non-unital alg_hom. -/ @[simps] def fst : A × B →ₙₐ[R] A := { to_fun := prod.fst, map_zero' := rfl, map_add' := λ x y, rfl, map_smul' := λ x y, rfl, map_mul' := λ x y, rfl } /-- The second projection of a product is a non-unital alg_hom. -/ @[simps] def snd : A × B →ₙₐ[R] B := { to_fun := prod.snd, map_zero' := rfl, map_add' := λ x y, rfl, map_smul' := λ x y, rfl, map_mul' := λ x y, rfl } variables {R A B} /-- The prod of two morphisms is a morphism. -/ @[simps] def prod (f : A →ₙₐ[R] B) (g : A →ₙₐ[R] C) : (A →ₙₐ[R] B × C) := { to_fun := pi.prod f g, map_zero' := by simp only [pi.prod, prod.zero_eq_mk, map_zero], map_add' := λ x y, by simp only [pi.prod, prod.mk_add_mk, map_add], map_mul' := λ x y, by simp only [pi.prod, prod.mk_mul_mk, map_mul], map_smul' := λ c x, by simp only [pi.prod, prod.smul_mk, map_smul, ring_hom.id_apply] } lemma coe_prod (f : A →ₙₐ[R] B) (g : A →ₙₐ[R] C) : ⇑(f.prod g) = pi.prod f g := rfl @[simp] theorem fst_prod (f : A →ₙₐ[R] B) (g : A →ₙₐ[R] C) : (fst R B C).comp (prod f g) = f := by ext; refl @[simp] theorem snd_prod (f : A →ₙₐ[R] B) (g : A →ₙₐ[R] C) : (snd R B C).comp (prod f g) = g := by ext; refl @[simp] theorem prod_fst_snd : prod (fst R A B) (snd R A B) = 1 := coe_injective pi.prod_fst_snd /-- Taking the product of two maps with the same domain is equivalent to taking the product of their codomains. -/ @[simps] def prod_equiv : ((A →ₙₐ[R] B) × (A →ₙₐ[R] C)) ≃ (A →ₙₐ[R] B × C) := { to_fun := λ f, f.1.prod f.2, inv_fun := λ f, ((fst _ _ _).comp f, (snd _ _ _).comp f), left_inv := λ f, by ext; refl, right_inv := λ f, by ext; refl } variables (R A B) /-- The left injection into a product is a non-unital algebra homomorphism. -/ def inl : A →ₙₐ[R] A × B := prod 1 0 /-- The right injection into a product is a non-unital algebra homomorphism. -/ def inr : B →ₙₐ[R] A × B := prod 0 1 variables {R A B} @[simp] theorem coe_inl : (inl R A B : A → A × B) = λ x, (x, 0) := rfl theorem inl_apply (x : A) : inl R A B x = (x, 0) := rfl @[simp] theorem coe_inr : (inr R A B : B → A × B) = prod.mk 0 := rfl theorem inr_apply (x : B) : inr R A B x = (0, x) := rfl end prod end non_unital_alg_hom /-! ### Interaction with `alg_hom` -/ namespace alg_hom variables {R A B} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] /-- A unital morphism of algebras is a `non_unital_alg_hom`. -/ def to_non_unital_alg_hom (f : A →ₐ[R] B) : A →ₙₐ[R] B := { map_smul' := f.map_smul, .. f, } instance non_unital_alg_hom.has_coe : has_coe (A →ₐ[R] B) (A →ₙₐ[R] B) := ⟨to_non_unital_alg_hom⟩ @[simp] lemma to_non_unital_alg_hom_eq_coe (f : A →ₐ[R] B) : f.to_non_unital_alg_hom = f := rfl @[simp, norm_cast] lemma coe_to_non_unital_alg_hom (f : A →ₐ[R] B) : ((f : A →ₙₐ[R] B) : A → B) = f := rfl end alg_hom
2c3c837ea47d0a652ec11d57d02bfe242ce038d4
9dc8cecdf3c4634764a18254e94d43da07142918
/src/analysis/box_integral/divergence_theorem.lean
c23bc769cc82e49edaf90368db54b1f6d907f78e
[ "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
16,446
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.box_integral.basic import analysis.box_integral.partition.additive import analysis.calculus.fderiv /-! # Divergence integral for Henstock-Kurzweil integral In this file we prove the Divergence Theorem for a Henstock-Kurzweil style integral. The theorem says the following. Let `f : ℝⁿ → Eⁿ` be a function differentiable on a closed rectangular box `I` with derivative `f' x : ℝⁿ →L[ℝ] Eⁿ` at `x ∈ I`. Then the divergence `λ x, ∑ k, f' x eₖ k`, where `eₖ = pi.single k 1` is the `k`-th basis vector, is integrable on `I`, and its integral is equal to the sum of integrals of `f` over the faces of `I` taken with appropriate signs. To make the proof work, we had to ban tagged partitions with “long and thin” boxes. More precisely, we use the following generalization of one-dimensional Henstock-Kurzweil integral to functions defined on a box in `ℝⁿ` (it corresponds to the value `box_integral.integration_params.GP = ⊥` of `box_integral.integration_params` in the definition of `box_integral.has_integral`). We say that `f : ℝⁿ → E` has integral `y : E` over a box `I ⊆ ℝⁿ` if for an arbitrarily small positive `ε` and an arbitrarily large `c`, there exists a function `r : ℝⁿ → (0, ∞)` such that for any tagged partition `π` of `I` such that * `π` is a Henstock partition, i.e., each tag belongs to its box; * `π` is subordinate to `r`; * for every box of `π`, the maximum of the ratios of its sides is less than or equal to `c`, the integral sum of `f` over `π` is `ε`-close to `y`. In case of dimension one, the last condition trivially holds for any `c ≥ 1`, so this definition is equivalent to the standard definition of Henstock-Kurzweil integral. ## Tags Henstock-Kurzweil integral, integral, Stokes theorem, divergence theorem -/ open_locale classical big_operators nnreal ennreal topological_space box_integral open continuous_linear_map (lsmul) filter set finset metric box_integral.integration_params (GP GP_le) noncomputable theory universes u variables {E : Type u} [normed_add_comm_group E] [normed_space ℝ E] {n : ℕ} namespace box_integral local notation `ℝⁿ` := fin n → ℝ local notation `ℝⁿ⁺¹` := fin (n + 1) → ℝ local notation `Eⁿ⁺¹` := fin (n + 1) → E variables [complete_space E] (I : box (fin (n + 1))) {i : fin (n + 1)} open measure_theory /-- Auxiliary lemma for the divergence theorem. -/ lemma norm_volume_sub_integral_face_upper_sub_lower_smul_le {f : ℝⁿ⁺¹ → E} {f' : ℝⁿ⁺¹ →L[ℝ] E} (hfc : continuous_on f I.Icc) {x : ℝⁿ⁺¹} (hxI : x ∈ I.Icc) {a : E} {ε : ℝ} (h0 : 0 < ε) (hε : ∀ y ∈ I.Icc, ∥f y - a - f' (y - x)∥ ≤ ε * ∥y - x∥) {c : ℝ≥0} (hc : I.distortion ≤ c) : ∥(∏ j, (I.upper j - I.lower j)) • f' (pi.single i 1) - (integral (I.face i) ⊥ (f ∘ i.insert_nth (I.upper i)) box_additive_map.volume - integral (I.face i) ⊥ (f ∘ i.insert_nth (I.lower i)) box_additive_map.volume)∥ ≤ 2 * ε * c * ∏ j, (I.upper j - I.lower j) := begin /- **Plan of the proof**. The difference of the integrals of the affine function `λ y, a + f' (y - x)` over the faces `x i = I.upper i` and `x i = I.lower i` is equal to the volume of `I` multiplied by `f' (pi.single i 1)`, so it suffices to show that the integral of `f y - a - f' (y - x)` over each of these faces is less than or equal to `ε * c * vol I`. We integrate a function of the norm `≤ ε * diam I.Icc` over a box of volume `∏ j ≠ i, (I.upper j - I.lower j)`. Since `diam I.Icc ≤ c * (I.upper i - I.lower i)`, we get the required estimate. -/ have Hl : I.lower i ∈ Icc (I.lower i) (I.upper i) := set.left_mem_Icc.2 (I.lower_le_upper i), have Hu : I.upper i ∈ Icc (I.lower i) (I.upper i) := set.right_mem_Icc.2 (I.lower_le_upper i), have Hi : ∀ x ∈ Icc (I.lower i) (I.upper i), integrable.{0 u u} (I.face i) ⊥ (f ∘ i.insert_nth x) box_additive_map.volume, from λ x hx, integrable_of_continuous_on _ (box.continuous_on_face_Icc hfc hx) volume, /- We start with an estimate: the difference of the values of `f` at the corresponding points of the faces `x i = I.lower i` and `x i = I.upper i` is `(2 * ε * diam I.Icc)`-close to the value of `f'` on `pi.single i (I.upper i - I.lower i) = lᵢ • eᵢ`, where `lᵢ = I.upper i - I.lower i` is the length of `i`-th edge of `I` and `eᵢ = pi.single i 1` is the `i`-th unit vector. -/ have : ∀ y ∈ (I.face i).Icc, ∥f' (pi.single i (I.upper i - I.lower i)) - (f (i.insert_nth (I.upper i) y) - f (i.insert_nth (I.lower i) y))∥ ≤ 2 * ε * diam I.Icc, { intros y hy, set g := λ y, f y - a - f' (y - x) with hg, change ∀ y ∈ I.Icc, ∥g y∥ ≤ ε * ∥y - x∥ at hε, clear_value g, obtain rfl : f = λ y, a + f' (y - x) + g y, by simp [hg], convert_to ∥g (i.insert_nth (I.lower i) y) - g (i.insert_nth (I.upper i) y)∥ ≤ _, { congr' 1, have := fin.insert_nth_sub_same i (I.upper i) (I.lower i) y, simp only [← this, f'.map_sub], abel }, { have : ∀ z ∈ Icc (I.lower i) (I.upper i), i.insert_nth z y ∈ I.Icc, from λ z hz, I.maps_to_insert_nth_face_Icc hz hy, replace hε : ∀ y ∈ I.Icc, ∥g y∥ ≤ ε * diam I.Icc, { intros y hy, refine (hε y hy).trans (mul_le_mul_of_nonneg_left _ h0.le), rw ← dist_eq_norm, exact dist_le_diam_of_mem I.is_compact_Icc.bounded hy hxI }, rw [two_mul, add_mul], exact norm_sub_le_of_le (hε _ (this _ Hl)) (hε _ (this _ Hu)) } }, calc ∥(∏ j, (I.upper j - I.lower j)) • f' (pi.single i 1) - (integral (I.face i) ⊥ (f ∘ i.insert_nth (I.upper i)) box_additive_map.volume - integral (I.face i) ⊥ (f ∘ i.insert_nth (I.lower i)) box_additive_map.volume)∥ = ∥integral.{0 u u} (I.face i) ⊥ (λ (x : fin n → ℝ), f' (pi.single i (I.upper i - I.lower i)) - (f (i.insert_nth (I.upper i) x) - f (i.insert_nth (I.lower i) x))) box_additive_map.volume∥ : begin rw [← integral_sub (Hi _ Hu) (Hi _ Hl), ← box.volume_face_mul i, mul_smul, ← box.volume_apply, ← box_additive_map.to_smul_apply, ← integral_const, ← box_additive_map.volume, ← integral_sub (integrable_const _) ((Hi _ Hu).sub (Hi _ Hl))], simp only [(∘), pi.sub_def, ← f'.map_smul, ← pi.single_smul', smul_eq_mul, mul_one] end ... ≤ (volume (I.face i : set ℝⁿ)).to_real * (2 * ε * c * (I.upper i - I.lower i)) : begin -- The hard part of the estimate was done above, here we just replace `diam I.Icc` -- with `c * (I.upper i - I.lower i)` refine norm_integral_le_of_le_const (λ y hy, (this y hy).trans _) volume, rw mul_assoc (2 * ε), exact mul_le_mul_of_nonneg_left (I.diam_Icc_le_of_distortion_le i hc) (mul_nonneg zero_le_two h0.le) end ... = 2 * ε * c * ∏ j, (I.upper j - I.lower j) : begin rw [← measure.to_box_additive_apply, box.volume_apply, ← I.volume_face_mul i], ac_refl end end /-- If `f : ℝⁿ⁺¹ → E` is differentiable on a closed rectangular box `I` with derivative `f'`, then the partial derivative `λ x, f' x (pi.single i 1)` is Henstock-Kurzweil integrable with integral equal to the difference of integrals of `f` over the faces `x i = I.upper i` and `x i = I.lower i`. More precisely, we use a non-standard generalization of the Henstock-Kurzweil integral and we allow `f` to be non-differentiable (but still continuous) at a countable set of points. TODO: If `n > 0`, then the condition at `x ∈ s` can be replaced by a much weaker estimate but this requires either better integrability theorems, or usage of a filter depending on the countable set `s` (we need to ensure that none of the faces of a partition contain a point from `s`). -/ lemma has_integral_GP_pderiv (f : ℝⁿ⁺¹ → E) (f' : ℝⁿ⁺¹ → ℝⁿ⁺¹ →L[ℝ] E) (s : set ℝⁿ⁺¹) (hs : s.countable) (Hs : ∀ x ∈ s, continuous_within_at f I.Icc x) (Hd : ∀ x ∈ I.Icc \ s, has_fderiv_within_at f (f' x) I.Icc x) (i : fin (n + 1)) : has_integral.{0 u u} I GP (λ x, f' x (pi.single i 1)) box_additive_map.volume (integral.{0 u u} (I.face i) GP (λ x, f (i.insert_nth (I.upper i) x)) box_additive_map.volume - integral.{0 u u} (I.face i) GP (λ x, f (i.insert_nth (I.lower i) x)) box_additive_map.volume) := begin /- Note that `f` is continuous on `I.Icc`, hence it is integrable on the faces of all boxes `J ≤ I`, thus the difference of integrals over `x i = J.upper i` and `x i = J.lower i` is a box-additive function of `J ≤ I`. -/ have Hc : continuous_on f I.Icc, { intros x hx, by_cases hxs : x ∈ s, exacts [Hs x hxs, (Hd x ⟨hx, hxs⟩).continuous_within_at] }, set fI : ℝ → box (fin n) → E := λ y J, integral.{0 u u} J GP (λ x, f (i.insert_nth y x)) box_additive_map.volume, set fb : Icc (I.lower i) (I.upper i) → fin n →ᵇᵃ[↑(I.face i)] E := λ x, (integrable_of_continuous_on GP (box.continuous_on_face_Icc Hc x.2) volume).to_box_additive, set F : fin (n + 1) →ᵇᵃ[I] E := box_additive_map.upper_sub_lower I i fI fb (λ x hx J, rfl), /- Thus our statement follows from some local estimates. -/ change has_integral I GP (λ x, f' x (pi.single i 1)) _ (F I), refine has_integral_of_le_Henstock_of_forall_is_o GP_le _ _ _ s hs _ _, { /- We use the volume as an upper estimate. -/ exact (volume : measure ℝⁿ⁺¹).to_box_additive.restrict _ le_top }, { exact λ J, ennreal.to_real_nonneg }, { intros c x hx ε ε0, /- Near `x ∈ s` we choose `δ` so that both vectors are small. `volume J • eᵢ` is small because `volume J ≤ (2 * δ) ^ (n + 1)` is small, and the difference of the integrals is small because each of the integrals is close to `volume (J.face i) • f x`. TODO: there should be a shorter and more readable way to formalize this simple proof. -/ have : ∀ᶠ δ in 𝓝[>] (0 : ℝ), δ ∈ Ioc (0 : ℝ) (1 / 2) ∧ (∀ y₁ y₂ ∈ closed_ball x δ ∩ I.Icc, ∥f y₁ - f y₂∥ ≤ ε / 2) ∧ ((2 * δ) ^ (n + 1) * ∥f' x (pi.single i 1)∥ ≤ ε / 2), { refine eventually.and _ (eventually.and _ _), { exact Ioc_mem_nhds_within_Ioi ⟨le_rfl, one_half_pos⟩ }, { rcases ((nhds_within_has_basis nhds_basis_closed_ball _).tendsto_iff nhds_basis_closed_ball).1 (Hs x hx.2) _ (half_pos $ half_pos ε0) with ⟨δ₁, δ₁0, hδ₁⟩, filter_upwards [Ioc_mem_nhds_within_Ioi ⟨le_rfl, δ₁0⟩] with δ hδ y₁ hy₁ y₂ hy₂, have : closed_ball x δ ∩ I.Icc ⊆ closed_ball x δ₁ ∩ I.Icc, from inter_subset_inter_left _ (closed_ball_subset_closed_ball hδ.2), rw ← dist_eq_norm, calc dist (f y₁) (f y₂) ≤ dist (f y₁) (f x) + dist (f y₂) (f x) : dist_triangle_right _ _ _ ... ≤ ε / 2 / 2 + ε / 2 / 2 : add_le_add (hδ₁ _ $ this hy₁) (hδ₁ _ $ this hy₂) ... = ε / 2 : add_halves _ }, { have : continuous_within_at (λ δ, (2 * δ) ^ (n + 1) * ∥f' x (pi.single i 1)∥) (Ioi (0 : ℝ)) 0 := ((continuous_within_at_id.const_mul _).pow _).mul_const _, refine this.eventually (ge_mem_nhds _), simpa using half_pos ε0 } }, rcases this.exists with ⟨δ, ⟨hδ0, hδ12⟩, hdfδ, hδ⟩, refine ⟨δ, hδ0, λ J hJI hJδ hxJ hJc, add_halves ε ▸ _⟩, have Hl : J.lower i ∈ Icc (J.lower i) (J.upper i) := set.left_mem_Icc.2 (J.lower_le_upper i), have Hu : J.upper i ∈ Icc (J.lower i) (J.upper i) := set.right_mem_Icc.2 (J.lower_le_upper i), have Hi : ∀ x ∈ Icc (J.lower i) (J.upper i), integrable.{0 u u} (J.face i) GP (λ y, f (i.insert_nth x y)) box_additive_map.volume, from λ x hx, integrable_of_continuous_on _ (box.continuous_on_face_Icc (Hc.mono $ box.le_iff_Icc.1 hJI) hx) volume, have hJδ' : J.Icc ⊆ closed_ball x δ ∩ I.Icc, from subset_inter hJδ (box.le_iff_Icc.1 hJI), have Hmaps : ∀ z ∈ Icc (J.lower i) (J.upper i), maps_to (i.insert_nth z) (J.face i).Icc (closed_ball x δ ∩ I.Icc), from λ z hz, (J.maps_to_insert_nth_face_Icc hz).mono subset.rfl hJδ', simp only [dist_eq_norm, F, fI], dsimp, rw [← integral_sub (Hi _ Hu) (Hi _ Hl)], refine (norm_sub_le _ _).trans (add_le_add _ _), { simp_rw [box_additive_map.volume_apply, norm_smul, real.norm_eq_abs, abs_prod], refine (mul_le_mul_of_nonneg_right _ $ norm_nonneg _).trans hδ, have : ∀ j, |J.upper j - J.lower j| ≤ 2 * δ, { intro j, calc dist (J.upper j) (J.lower j) ≤ dist J.upper J.lower : dist_le_pi_dist _ _ _ ... ≤ dist J.upper x + dist J.lower x : dist_triangle_right _ _ _ ... ≤ δ + δ : add_le_add (hJδ J.upper_mem_Icc) (hJδ J.lower_mem_Icc) ... = 2 * δ : (two_mul δ).symm }, calc (∏ j, |J.upper j - J.lower j|) ≤ ∏ j : fin (n + 1), (2 * δ) : prod_le_prod (λ _ _ , abs_nonneg _) (λ j hj, this j) ... = (2 * δ) ^ (n + 1) : by simp }, { refine (norm_integral_le_of_le_const (λ y hy, hdfδ _ (Hmaps _ Hu hy) _ (Hmaps _ Hl hy)) _).trans _, refine (mul_le_mul_of_nonneg_right _ (half_pos ε0).le).trans_eq (one_mul _), rw [box.coe_eq_pi, real.volume_pi_Ioc_to_real (box.lower_le_upper _)], refine prod_le_one (λ _ _, sub_nonneg.2 $ box.lower_le_upper _ _) (λ j hj, _), calc J.upper (i.succ_above j) - J.lower (i.succ_above j) ≤ dist (J.upper (i.succ_above j)) (J.lower (i.succ_above j)) : le_abs_self _ ... ≤ dist J.upper J.lower : dist_le_pi_dist J.upper J.lower (i.succ_above j) ... ≤ dist J.upper x + dist J.lower x : dist_triangle_right _ _ _ ... ≤ δ + δ : add_le_add (hJδ J.upper_mem_Icc) (hJδ J.lower_mem_Icc) ... ≤ 1 / 2 + 1 / 2 : add_le_add hδ12 hδ12 ... = 1 : add_halves 1 } }, { intros c x hx ε ε0, /- At a point `x ∉ s`, we unfold the definition of Fréchet differentiability, then use an estimate we proved earlier in this file. -/ rcases exists_pos_mul_lt ε0 (2 * c) with ⟨ε', ε'0, hlt⟩, rcases (nhds_within_has_basis nhds_basis_closed_ball _).mem_iff.1 ((Hd x hx).def ε'0) with ⟨δ, δ0, Hδ⟩, refine ⟨δ, δ0, λ J hle hJδ hxJ hJc, _⟩, simp only [box_additive_map.volume_apply, box.volume_apply, dist_eq_norm], refine (norm_volume_sub_integral_face_upper_sub_lower_smul_le _ (Hc.mono $ box.le_iff_Icc.1 hle) hxJ ε'0 (λ y hy, Hδ _) (hJc rfl)).trans _, { exact ⟨hJδ hy, box.le_iff_Icc.1 hle hy⟩ }, { rw [mul_right_comm (2 : ℝ), ← box.volume_apply], exact mul_le_mul_of_nonneg_right hlt.le ennreal.to_real_nonneg } } end /-- Divergence theorem for a Henstock-Kurzweil style integral. If `f : ℝⁿ⁺¹ → Eⁿ⁺¹` is differentiable on a closed rectangular box `I` with derivative `f'`, then the divergence `∑ i, f' x (pi.single i 1) i` is Henstock-Kurzweil integrable with integral equal to the sum of integrals of `f` over the faces of `I` taken with appropriate signs. More precisely, we use a non-standard generalization of the Henstock-Kurzweil integral and we allow `f` to be non-differentiable (but still continuous) at a countable set of points. -/ lemma has_integral_GP_divergence_of_forall_has_deriv_within_at (f : ℝⁿ⁺¹ → Eⁿ⁺¹) (f' : ℝⁿ⁺¹ → ℝⁿ⁺¹ →L[ℝ] Eⁿ⁺¹) (s : set ℝⁿ⁺¹) (hs : s.countable) (Hs : ∀ x ∈ s, continuous_within_at f I.Icc x) (Hd : ∀ x ∈ I.Icc \ s, has_fderiv_within_at f (f' x) I.Icc x) : has_integral.{0 u u} I GP (λ x, ∑ i, f' x (pi.single i 1) i) box_additive_map.volume (∑ i, (integral.{0 u u} (I.face i) GP (λ x, f (i.insert_nth (I.upper i) x) i) box_additive_map.volume - integral.{0 u u} (I.face i) GP (λ x, f (i.insert_nth (I.lower i) x) i) box_additive_map.volume)) := begin refine has_integral_sum (λ i hi, _), clear hi, simp only [has_fderiv_within_at_pi', continuous_within_at_pi] at Hd Hs, convert has_integral_GP_pderiv I _ _ s hs (λ x hx, Hs x hx i) (λ x hx, Hd x hx i) i end end box_integral
8ce26f5082743bbeb8647e5cb2971106401e26b1
e514e8b939af519a1d5e9b30a850769d058df4e9
/src/tactic/rewrite_search/discovery/collect.lean
2579c8ddf9bb94b9fa978b82b82b5bb4bbfedebc
[]
no_license
semorrison/lean-rewrite-search
dca317c5a52e170fb6ffc87c5ab767afb5e3e51a
e804b8f2753366b8957be839908230ee73f9e89f
refs/heads/master
1,624,051,754,485
1,614,160,817,000
1,614,160,817,000
162,660,605
0
1
null
null
null
null
UTF-8
Lean
false
false
2,028
lean
import tactic.rewrite_search.core.common import .types import .screening import .bundle import .suggest import .collector import .common open tactic universe u namespace tactic.rewrite_search.discovery open tactic.rewrite_search -- TODO trace only when we have success. -- TODO add configurable "persistence" meta def default_collectors : list collector := [try_bundles, try_everything] /-- Bundle names are names like ```logic``. -/ meta def collect (use_suggest_annotations : bool) (p : persistence) (suggested_bundle_names : list name) (extra_names : list name) : tactic (progress × list (expr × bool)) := do n_bs ← suggested_bundle_names.mmap get_bundle, i_bs ← if use_suggest_annotations then get_suggested_bundle_idents >>= list.mmap lookup_bundle else pure [], let bs := n_bs ++ i_bs, exprs ← collect_bundle_members bs >>= load_names, extra_exprs ← load_names extra_names, extra_exprs.mmap assert_acceptable_lemma, return (⟨p, bs⟩, rewrite_list_from_lemmas $ exprs ++ extra_exprs) -- Currently, we guarentee that each rewrite we return gives some expression the environment -- hasn't seen before. meta def collect_more_using : list collector → config → list (expr × bool) → progress → list expr → tactic (progress × list (expr × bool)) | [] conf rs p _ := do if conf.trace_discovery ∧ ¬(p.persistence = persistence.speedy) then discovery_trace "Giving up." ff else skip, return (p, []) | (fn :: rest) conf rs p sample := do (p, rws) ← fn conf rs p sample, if rws.length = 0 then collect_more_using rest conf rs p sample else return (p, rws) meta def collect_more (conf : config) (rs : list (expr × bool)) (prog : progress) (sample : list expr) : tactic (progress × list (expr × bool)) := do if conf.trace_discovery ∧ ¬(prog.persistence = persistence.speedy) then tactic.trace "rewrite_search is getting desperate...\n" else skip, collect_more_using default_collectors conf rs prog sample end tactic.rewrite_search.discovery
f870a8fc6331f8695925fae6b6d14c16581c0c07
367134ba5a65885e863bdc4507601606690974c1
/src/logic/function/iterate.lean
ee3614fd7429ca8a299bd9f7b7ee24410d35d652
[ "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
5,300
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Yury Kudryashov -/ import logic.function.conjugate /-! # Iterations of a function In this file we prove simple properties of `nat.iterate f n` a.k.a. `f^[n]`: * `iterate_zero`, `iterate_succ`, `iterate_succ'`, `iterate_add`, `iterate_mul`: formulas for `f^[0]`, `f^[n+1]` (two versions), `f^[n+m]`, and `f^[n*m]`; * `iterate_id` : `id^[n]=id`; * `injective.iterate`, `surjective.iterate`, `bijective.iterate` : iterates of an injective/surjective/bijective function belong to the same class; * `left_inverse.iterate`, `right_inverse.iterate`, `commute.iterate_left`, `comute.iterate_right`, `commute.iterate_iterate`: some properties of pairs of functions survive under iterations * `iterate_fixed`, `semiconj.iterate_*`, `semiconj₂.iterate`: if `f` fixes a point (resp., semiconjugates unary/binary operarations), then so does `f^[n]`. -/ universes u v variables {α : Type u} {β : Type v} namespace function variable (f : α → α) @[simp] theorem iterate_zero : f^[0] = id := rfl theorem iterate_zero_apply (x : α) : f^[0] x = x := rfl @[simp] theorem iterate_succ (n : ℕ) : f^[n.succ] = (f^[n]) ∘ f := rfl theorem iterate_succ_apply (n : ℕ) (x : α) : f^[n.succ] x = (f^[n]) (f x) := rfl @[simp] theorem iterate_id (n : ℕ) : (id : α → α)^[n] = id := nat.rec_on n rfl $ λ n ihn, by rw [iterate_succ, ihn, comp.left_id] theorem iterate_add : ∀ (m n : ℕ), f^[m + n] = (f^[m]) ∘ (f^[n]) | m 0 := rfl | m (nat.succ n) := by rw [iterate_succ, iterate_succ, iterate_add] theorem iterate_add_apply (m n : ℕ) (x : α) : f^[m + n] x = (f^[m] (f^[n] x)) := by rw iterate_add @[simp] theorem iterate_one : f^[1] = f := funext $ λ a, rfl lemma iterate_mul (m : ℕ) : ∀ n, f^[m * n] = (f^[m]^[n]) | 0 := by simp only [nat.mul_zero, iterate_zero] | (n + 1) := by simp only [nat.mul_succ, nat.mul_one, iterate_one, iterate_add, iterate_mul n] variable {f} theorem iterate_fixed {x} (h : f x = x) (n : ℕ) : f^[n] x = x := nat.rec_on n rfl $ λ n ihn, by rw [iterate_succ_apply, h, ihn] theorem injective.iterate (Hinj : injective f) (n : ℕ) : injective (f^[n]) := nat.rec_on n injective_id $ λ n ihn, ihn.comp Hinj theorem surjective.iterate (Hsurj : surjective f) (n : ℕ) : surjective (f^[n]) := nat.rec_on n surjective_id $ λ n ihn, ihn.comp Hsurj theorem bijective.iterate (Hbij : bijective f) (n : ℕ) : bijective (f^[n]) := ⟨Hbij.1.iterate n, Hbij.2.iterate n⟩ namespace semiconj lemma iterate_right {f : α → β} {ga : α → α} {gb : β → β} (h : semiconj f ga gb) (n : ℕ) : semiconj f (ga^[n]) (gb^[n]) := nat.rec_on n id_right $ λ n ihn, ihn.comp_right h lemma iterate_left {g : ℕ → α → α} (H : ∀ n, semiconj f (g n) (g $ n + 1)) (n k : ℕ) : semiconj (f^[n]) (g k) (g $ n + k) := begin induction n with n ihn generalizing k, { rw [nat.zero_add], exact id_left }, { rw [nat.succ_eq_add_one, nat.add_right_comm, nat.add_assoc], exact (H k).comp_left (ihn (k + 1)) } end end semiconj namespace commute variable {g : α → α} lemma iterate_right (h : commute f g) (n : ℕ) : commute f (g^[n]) := h.iterate_right n lemma iterate_left (h : commute f g) (n : ℕ) : commute (f^[n]) g := (h.symm.iterate_right n).symm lemma iterate_iterate (h : commute f g) (m n : ℕ) : commute (f^[m]) (g^[n]) := (h.iterate_left m).iterate_right n lemma iterate_eq_of_map_eq (h : commute f g) (n : ℕ) {x} (hx : f x = g x) : f^[n] x = (g^[n]) x := nat.rec_on n rfl $ λ n ihn, by simp only [iterate_succ_apply, hx, (h.iterate_left n).eq, ihn, ((refl g).iterate_right n).eq] lemma comp_iterate (h : commute f g) (n : ℕ) : (f ∘ g)^[n] = (f^[n]) ∘ (g^[n]) := begin induction n with n ihn, { refl }, funext x, simp only [ihn, (h.iterate_right n).eq, iterate_succ, comp_app] end variable (f) lemma iterate_self (n : ℕ) : commute (f^[n]) f := (refl f).iterate_left n lemma self_iterate (n : ℕ) : commute f (f^[n]) := (refl f).iterate_right n lemma iterate_iterate_self (m n : ℕ) : commute (f^[m]) (f^[n]) := (refl f).iterate_iterate m n end commute lemma semiconj₂.iterate {f : α → α} {op : α → α → α} (hf : semiconj₂ f op op) (n : ℕ) : semiconj₂ (f^[n]) op op := nat.rec_on n (semiconj₂.id_left op) (λ n ihn, ihn.comp hf) variable (f) theorem iterate_succ' (n : ℕ) : f^[n.succ] = f ∘ (f^[n]) := by rw [iterate_succ, (commute.self_iterate f n).comp_eq] theorem iterate_succ_apply' (n : ℕ) (x : α) : f^[n.succ] x = f (f^[n] x) := by rw [iterate_succ'] theorem iterate_pred_comp_of_pos {n : ℕ} (hn : 0 < n) : f^[n.pred] ∘ f = (f^[n]) := by rw [← iterate_succ, nat.succ_pred_eq_of_pos hn] theorem comp_iterate_pred_of_pos {n : ℕ} (hn : 0 < n) : f ∘ (f^[n.pred]) = (f^[n]) := by rw [← iterate_succ', nat.succ_pred_eq_of_pos hn] variable {f} theorem left_inverse.iterate {g : α → α} (hg : left_inverse g f) (n : ℕ) : left_inverse (g^[n]) (f^[n]) := nat.rec_on n (λ _, rfl) $ λ n ihn, by { rw [iterate_succ', iterate_succ], exact ihn.comp hg } theorem right_inverse.iterate {g : α → α} (hg : right_inverse g f) (n : ℕ) : right_inverse (g^[n]) (f^[n]) := hg.iterate n end function
caf31e23a2a86c9f795afd2098fd30777432a88d
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/uniform_space/uniform_convergence_auto.lean
fba60a3f7162991cb85229cb705d1ace4ee7d12b
[]
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
20,122
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.uniform_space.basic import Mathlib.PostPort universes u v u_1 w namespace Mathlib /-! # Uniform convergence A sequence of functions `Fₙ` (with values in a metric space) converges uniformly on a set `s` to a function `f` if, for all `ε > 0`, for all large enough `n`, one has for all `y ∈ s` the inequality `dist (f y, Fₙ y) < ε`. Under uniform convergence, many properties of the `Fₙ` pass to the limit, most notably continuity. We prove this in the file, defining the notion of uniform convergence in the more general setting of uniform spaces, and with respect to an arbitrary indexing set endowed with a filter (instead of just `ℕ` with `at_top`). ## Main results Let `α` be a topological space, `β` a uniform space, `Fₙ` and `f` be functions from `α`to `β` (where the index `n` belongs to an indexing type `ι` endowed with a filter `p`). * `tendsto_uniformly_on F f p s`: the fact that `Fₙ` converges uniformly to `f` on `s`. This means that, for any entourage `u` of the diagonal, for large enough `n` (with respect to `p`), one has `(f y, Fₙ y) ∈ u` for all `y ∈ s`. * `tendsto_uniformly F f p`: same notion with `s = univ`. * `tendsto_uniformly_on.continuous_on`: a uniform limit on a set of functions which are continuous on this set is itself continuous on this set. * `tendsto_uniformly.continuous`: a uniform limit of continuous functions is continuous. * `tendsto_uniformly_on.tendsto_comp`: If `Fₙ` tends uniformly to `f` on a set `s`, and `gₙ` tends to `x` within `s`, then `Fₙ gₙ` tends to `f x` if `f` is continuous at `x` within `s`. * `tendsto_uniformly.tendsto_comp`: If `Fₙ` tends uniformly to `f`, and `gₙ` tends to `x`, then `Fₙ gₙ` tends to `f x`. We also define notions where the convergence is locally uniform, called `tendsto_locally_uniformly_on F f p s` and `tendsto_locally_uniformly F f p`. The previous theorems all have corresponding versions under locally uniform convergence. ## Implementation notes Most results hold under weaker assumptions of locally uniform approximation. In a first section, we prove the results under these weaker assumptions. Then, we derive the results on uniform convergence from them. ## Tags Uniform limit, uniform convergence, tends uniformly to -/ /-! ### Different notions of uniform convergence We define uniform convergence and locally uniform convergence, on a set or in the whole space. -/ /-- A sequence of functions `Fₙ` converges uniformly on a set `s` to a limiting function `f` with respect to the filter `p` if, for any entourage of the diagonal `u`, one has `p`-eventually `(f x, Fₙ x) ∈ u` for all `x ∈ s`. -/ def tendsto_uniformly_on {α : Type u} {β : Type v} {ι : Type u_1} [uniform_space β] (F : ι → α → β) (f : α → β) (p : filter ι) (s : set α) := ∀ (u : set (β × β)), u ∈ uniformity β → filter.eventually (fun (n : ι) => ∀ (x : α), x ∈ s → (f x, F n x) ∈ u) p /-- A sequence of functions `Fₙ` converges uniformly to a limiting function `f` with respect to a filter `p` if, for any entourage of the diagonal `u`, one has `p`-eventually `(f x, Fₙ x) ∈ u` for all `x`. -/ def tendsto_uniformly {α : Type u} {β : Type v} {ι : Type u_1} [uniform_space β] (F : ι → α → β) (f : α → β) (p : filter ι) := ∀ (u : set (β × β)), u ∈ uniformity β → filter.eventually (fun (n : ι) => ∀ (x : α), (f x, F n x) ∈ u) p theorem tendsto_uniformly_on_univ {α : Type u} {β : Type v} {ι : Type u_1} [uniform_space β] {F : ι → α → β} {f : α → β} {p : filter ι} : tendsto_uniformly_on F f p set.univ ↔ tendsto_uniformly F f p := sorry theorem tendsto_uniformly_on.mono {α : Type u} {β : Type v} {ι : Type u_1} [uniform_space β] {F : ι → α → β} {f : α → β} {s : set α} {p : filter ι} {s' : set α} (h : tendsto_uniformly_on F f p s) (h' : s' ⊆ s) : tendsto_uniformly_on F f p s' := fun (u : set (β × β)) (hu : u ∈ uniformity β) => filter.eventually.mono (h u hu) fun (n : ι) (hn : ∀ (x : α), x ∈ s → (f x, F n x) ∈ u) (x : α) (hx : x ∈ s') => hn x (h' hx) theorem tendsto_uniformly.tendsto_uniformly_on {α : Type u} {β : Type v} {ι : Type u_1} [uniform_space β] {F : ι → α → β} {f : α → β} {s : set α} {p : filter ι} (h : tendsto_uniformly F f p) : tendsto_uniformly_on F f p s := tendsto_uniformly_on.mono (iff.mpr tendsto_uniformly_on_univ h) (set.subset_univ s) /-- Composing on the right by a function preserves uniform convergence on a set -/ theorem tendsto_uniformly_on.comp {α : Type u} {β : Type v} {γ : Type w} {ι : Type u_1} [uniform_space β] {F : ι → α → β} {f : α → β} {s : set α} {p : filter ι} (h : tendsto_uniformly_on F f p s) (g : γ → α) : tendsto_uniformly_on (fun (n : ι) => F n ∘ g) (f ∘ g) p (g ⁻¹' s) := sorry /-- Composing on the right by a function preserves uniform convergence -/ theorem tendsto_uniformly.comp {α : Type u} {β : Type v} {γ : Type w} {ι : Type u_1} [uniform_space β] {F : ι → α → β} {f : α → β} {p : filter ι} (h : tendsto_uniformly F f p) (g : γ → α) : tendsto_uniformly (fun (n : ι) => F n ∘ g) (f ∘ g) p := id fun (u : set (β × β)) (hu : u ∈ uniformity β) => filter.eventually.mono (h u hu) fun (n : ι) (hn : ∀ (x : α), (f x, F n x) ∈ u) (x : γ) => hn (g x) /-- A sequence of functions `Fₙ` converges locally uniformly on a set `s` to a limiting function `f` with respect to a filter `p` if, for any entourage of the diagonal `u`, for any `x ∈ s`, one has `p`-eventually `(f x, Fₙ x) ∈ u` for all `y` in a neighborhood of `x` in `s`. -/ def tendsto_locally_uniformly_on {α : Type u} {β : Type v} {ι : Type u_1} [uniform_space β] [topological_space α] (F : ι → α → β) (f : α → β) (p : filter ι) (s : set α) := ∀ (u : set (β × β)) (H : u ∈ uniformity β) (x : α) (H : x ∈ s), ∃ (t : set α), ∃ (H : t ∈ nhds_within x s), filter.eventually (fun (n : ι) => ∀ (y : α), y ∈ t → (f y, F n y) ∈ u) p /-- A sequence of functions `Fₙ` converges locally uniformly to a limiting function `f` with respect to a filter `p` if, for any entourage of the diagonal `u`, for any `x`, one has `p`-eventually `(f x, Fₙ x) ∈ u` for all `y` in a neighborhood of `x`. -/ def tendsto_locally_uniformly {α : Type u} {β : Type v} {ι : Type u_1} [uniform_space β] [topological_space α] (F : ι → α → β) (f : α → β) (p : filter ι) := ∀ (u : set (β × β)) (H : u ∈ uniformity β) (x : α), ∃ (t : set α), ∃ (H : t ∈ nhds x), filter.eventually (fun (n : ι) => ∀ (y : α), y ∈ t → (f y, F n y) ∈ u) p theorem tendsto_uniformly_on.tendsto_locally_uniformly_on {α : Type u} {β : Type v} {ι : Type u_1} [uniform_space β] {F : ι → α → β} {f : α → β} {s : set α} {p : filter ι} [topological_space α] (h : tendsto_uniformly_on F f p s) : tendsto_locally_uniformly_on F f p s := fun (u : set (β × β)) (hu : u ∈ uniformity β) (x : α) (hx : x ∈ s) => Exists.intro s (Exists.intro self_mem_nhds_within (h u hu)) theorem tendsto_uniformly.tendsto_locally_uniformly {α : Type u} {β : Type v} {ι : Type u_1} [uniform_space β] {F : ι → α → β} {f : α → β} {p : filter ι} [topological_space α] (h : tendsto_uniformly F f p) : tendsto_locally_uniformly F f p := sorry theorem tendsto_locally_uniformly_on.mono {α : Type u} {β : Type v} {ι : Type u_1} [uniform_space β] {F : ι → α → β} {f : α → β} {s : set α} {s' : set α} {p : filter ι} [topological_space α] (h : tendsto_locally_uniformly_on F f p s) (h' : s' ⊆ s) : tendsto_locally_uniformly_on F f p s' := sorry theorem tendsto_locally_uniformly_on_univ {α : Type u} {β : Type v} {ι : Type u_1} [uniform_space β] {F : ι → α → β} {f : α → β} {p : filter ι} [topological_space α] : tendsto_locally_uniformly_on F f p set.univ ↔ tendsto_locally_uniformly F f p := sorry theorem tendsto_locally_uniformly_on.comp {α : Type u} {β : Type v} {γ : Type w} {ι : Type u_1} [uniform_space β] {F : ι → α → β} {f : α → β} {s : set α} {p : filter ι} [topological_space α] [topological_space γ] {t : set γ} (h : tendsto_locally_uniformly_on F f p s) (g : γ → α) (hg : set.maps_to g t s) (cg : continuous_on g t) : tendsto_locally_uniformly_on (fun (n : ι) => F n ∘ g) (f ∘ g) p t := sorry theorem tendsto_locally_uniformly.comp {α : Type u} {β : Type v} {γ : Type w} {ι : Type u_1} [uniform_space β] {F : ι → α → β} {f : α → β} {p : filter ι} [topological_space α] [topological_space γ] (h : tendsto_locally_uniformly F f p) (g : γ → α) (cg : continuous g) : tendsto_locally_uniformly (fun (n : ι) => F n ∘ g) (f ∘ g) p := sorry /-! ### Uniform approximation In this section, we give lemmas ensuring that a function is continuous if it can be approximated uniformly by continuous functions. We give various versions, within a set or the whole space, at a single point or at all points, with locally uniform approximation or uniform approximation. All the statements are derived from a statement about locally uniform approximation within a set at a point, called `continuous_within_at_of_locally_uniform_approx_of_continuous_within_at`. -/ /-- A function which can be locally uniformly approximated by functions which are continuous within a set at a point is continuous within this set at this point. -/ theorem continuous_within_at_of_locally_uniform_approx_of_continuous_within_at {α : Type u} {β : Type v} {ι : Type u_1} [uniform_space β] {F : ι → α → β} {f : α → β} {s : set α} {x : α} [topological_space α] (hx : x ∈ s) (L : ∀ (u : set (β × β)) (H : u ∈ uniformity β), ∃ (t : set α), ∃ (H : t ∈ nhds_within x s), ∃ (n : ι), ∀ (y : α), y ∈ t → (f y, F n y) ∈ u) (C : ∀ (n : ι), continuous_within_at (F n) s x) : continuous_within_at f s x := sorry /-- A function which can be locally uniformly approximated by functions which are continuous at a point is continuous at this point. -/ theorem continuous_at_of_locally_uniform_approx_of_continuous_at {α : Type u} {β : Type v} {ι : Type u_1} [uniform_space β] {F : ι → α → β} {f : α → β} {x : α} [topological_space α] (L : ∀ (u : set (β × β)) (H : u ∈ uniformity β), ∃ (t : set α), ∃ (H : t ∈ nhds x), ∃ (n : ι), ∀ (y : α), y ∈ t → (f y, F n y) ∈ u) (C : ∀ (n : ι), continuous_at (F n) x) : continuous_at f x := sorry /-- A function which can be locally uniformly approximated by functions which are continuous on a set is continuous on this set. -/ theorem continuous_on_of_locally_uniform_approx_of_continuous_on {α : Type u} {β : Type v} {ι : Type u_1} [uniform_space β] {F : ι → α → β} {f : α → β} {s : set α} [topological_space α] (L : ∀ (x : α) (H : x ∈ s) (u : set (β × β)) (H : u ∈ uniformity β), ∃ (t : set α), ∃ (H : t ∈ nhds_within x s), ∃ (n : ι), ∀ (y : α), y ∈ t → (f y, F n y) ∈ u) (C : ∀ (n : ι), continuous_on (F n) s) : continuous_on f s := fun (x : α) (hx : x ∈ s) => continuous_within_at_of_locally_uniform_approx_of_continuous_within_at hx (L x hx) fun (n : ι) => C n x hx /-- A function which can be uniformly approximated by functions which are continuous on a set is continuous on this set. -/ theorem continuous_on_of_uniform_approx_of_continuous_on {α : Type u} {β : Type v} {ι : Type u_1} [uniform_space β] {F : ι → α → β} {f : α → β} {s : set α} [topological_space α] (L : ∀ (u : set (β × β)), u ∈ uniformity β → ∃ (n : ι), ∀ (y : α), y ∈ s → (f y, F n y) ∈ u) : (∀ (n : ι), continuous_on (F n) s) → continuous_on f s := continuous_on_of_locally_uniform_approx_of_continuous_on fun (x : α) (hx : x ∈ s) (u : set (β × β)) (hu : u ∈ uniformity β) => Exists.intro s (Exists.intro self_mem_nhds_within (L u hu)) /-- A function which can be locally uniformly approximated by continuous functions is continuous. -/ theorem continuous_of_locally_uniform_approx_of_continuous {α : Type u} {β : Type v} {ι : Type u_1} [uniform_space β] {F : ι → α → β} {f : α → β} [topological_space α] (L : ∀ (x : α) (u : set (β × β)) (H : u ∈ uniformity β), ∃ (t : set α), ∃ (H : t ∈ nhds x), ∃ (n : ι), ∀ (y : α), y ∈ t → (f y, F n y) ∈ u) (C : ∀ (n : ι), continuous (F n)) : continuous f := sorry /-- A function which can be uniformly approximated by continuous functions is continuous. -/ theorem continuous_of_uniform_approx_of_continuous {α : Type u} {β : Type v} {ι : Type u_1} [uniform_space β] {F : ι → α → β} {f : α → β} [topological_space α] (L : ∀ (u : set (β × β)), u ∈ uniformity β → ∃ (N : ι), ∀ (y : α), (f y, F N y) ∈ u) : (∀ (n : ι), continuous (F n)) → continuous f := sorry /-! ### Uniform limits From the previous statements on uniform approximation, we deduce continuity results for uniform limits. -/ /-- A locally uniform limit on a set of functions which are continuous on this set is itself continuous on this set. -/ theorem tendsto_locally_uniformly_on.continuous_on {α : Type u} {β : Type v} {ι : Type u_1} [uniform_space β] {F : ι → α → β} {f : α → β} {s : set α} {p : filter ι} [topological_space α] (h : tendsto_locally_uniformly_on F f p s) (hc : ∀ (n : ι), continuous_on (F n) s) [filter.ne_bot p] : continuous_on f s := sorry /-- A uniform limit on a set of functions which are continuous on this set is itself continuous on this set. -/ theorem tendsto_uniformly_on.continuous_on {α : Type u} {β : Type v} {ι : Type u_1} [uniform_space β] {F : ι → α → β} {f : α → β} {s : set α} {p : filter ι} [topological_space α] (h : tendsto_uniformly_on F f p s) (hc : ∀ (n : ι), continuous_on (F n) s) [filter.ne_bot p] : continuous_on f s := tendsto_locally_uniformly_on.continuous_on (tendsto_uniformly_on.tendsto_locally_uniformly_on h) hc /-- A locally uniform limit of continuous functions is continuous. -/ theorem tendsto_locally_uniformly.continuous {α : Type u} {β : Type v} {ι : Type u_1} [uniform_space β] {F : ι → α → β} {f : α → β} {p : filter ι} [topological_space α] (h : tendsto_locally_uniformly F f p) (hc : ∀ (n : ι), continuous (F n)) [filter.ne_bot p] : continuous f := sorry /-- A uniform limit of continuous functions is continuous. -/ theorem tendsto_uniformly.continuous {α : Type u} {β : Type v} {ι : Type u_1} [uniform_space β] {F : ι → α → β} {f : α → β} {p : filter ι} [topological_space α] (h : tendsto_uniformly F f p) (hc : ∀ (n : ι), continuous (F n)) [filter.ne_bot p] : continuous f := tendsto_locally_uniformly.continuous (tendsto_uniformly.tendsto_locally_uniformly h) hc /-! ### Composing limits under uniform convergence In general, if `Fₙ` converges pointwise to a function `f`, and `gₙ` tends to `x`, it is not true that `Fₙ gₙ` tends to `f x`. It is true however if the convergence of `Fₙ` to `f` is uniform. In this paragraph, we prove variations around this statement. -/ /-- If `Fₙ` converges locally uniformly on a neighborhood of `x` within a set `s` to a function `f` which is continuous at `x` within `s `, and `gₙ` tends to `x` within `s`, then `Fₙ (gₙ)` tends to `f x`. -/ theorem tendsto_comp_of_locally_uniform_limit_within {α : Type u} {β : Type v} {ι : Type u_1} [uniform_space β] {F : ι → α → β} {f : α → β} {s : set α} {x : α} {p : filter ι} {g : ι → α} [topological_space α] (h : continuous_within_at f s x) (hg : filter.tendsto g p (nhds_within x s)) (hunif : ∀ (u : set (β × β)) (H : u ∈ uniformity β), ∃ (t : set α), ∃ (H : t ∈ nhds_within x s), filter.eventually (fun (n : ι) => ∀ (y : α), y ∈ t → (f y, F n y) ∈ u) p) : filter.tendsto (fun (n : ι) => F n (g n)) p (nhds (f x)) := sorry /-- If `Fₙ` converges locally uniformly on a neighborhood of `x` to a function `f` which is continuous at `x`, and `gₙ` tends to `x`, then `Fₙ (gₙ)` tends to `f x`. -/ theorem tendsto_comp_of_locally_uniform_limit {α : Type u} {β : Type v} {ι : Type u_1} [uniform_space β] {F : ι → α → β} {f : α → β} {x : α} {p : filter ι} {g : ι → α} [topological_space α] (h : continuous_at f x) (hg : filter.tendsto g p (nhds x)) (hunif : ∀ (u : set (β × β)) (H : u ∈ uniformity β), ∃ (t : set α), ∃ (H : t ∈ nhds x), filter.eventually (fun (n : ι) => ∀ (y : α), y ∈ t → (f y, F n y) ∈ u) p) : filter.tendsto (fun (n : ι) => F n (g n)) p (nhds (f x)) := sorry /-- If `Fₙ` tends locally uniformly to `f` on a set `s`, and `gₙ` tends to `x` within `s`, then `Fₙ gₙ` tends to `f x` if `f` is continuous at `x` within `s` and `x ∈ s`. -/ theorem tendsto_locally_uniformly_on.tendsto_comp {α : Type u} {β : Type v} {ι : Type u_1} [uniform_space β] {F : ι → α → β} {f : α → β} {s : set α} {x : α} {p : filter ι} {g : ι → α} [topological_space α] (h : tendsto_locally_uniformly_on F f p s) (hf : continuous_within_at f s x) (hx : x ∈ s) (hg : filter.tendsto g p (nhds_within x s)) : filter.tendsto (fun (n : ι) => F n (g n)) p (nhds (f x)) := tendsto_comp_of_locally_uniform_limit_within hf hg fun (u : set (β × β)) (hu : u ∈ uniformity β) => h u hu x hx /-- If `Fₙ` tends uniformly to `f` on a set `s`, and `gₙ` tends to `x` within `s`, then `Fₙ gₙ` tends to `f x` if `f` is continuous at `x` within `s`. -/ theorem tendsto_uniformly_on.tendsto_comp {α : Type u} {β : Type v} {ι : Type u_1} [uniform_space β] {F : ι → α → β} {f : α → β} {s : set α} {x : α} {p : filter ι} {g : ι → α} [topological_space α] (h : tendsto_uniformly_on F f p s) (hf : continuous_within_at f s x) (hg : filter.tendsto g p (nhds_within x s)) : filter.tendsto (fun (n : ι) => F n (g n)) p (nhds (f x)) := tendsto_comp_of_locally_uniform_limit_within hf hg fun (u : set (β × β)) (hu : u ∈ uniformity β) => Exists.intro s (Exists.intro self_mem_nhds_within (h u hu)) /-- If `Fₙ` tends locally uniformly to `f`, and `gₙ` tends to `x`, then `Fₙ gₙ` tends to `f x`. -/ theorem tendsto_locally_uniformly.tendsto_comp {α : Type u} {β : Type v} {ι : Type u_1} [uniform_space β] {F : ι → α → β} {f : α → β} {x : α} {p : filter ι} {g : ι → α} [topological_space α] (h : tendsto_locally_uniformly F f p) (hf : continuous_at f x) (hg : filter.tendsto g p (nhds x)) : filter.tendsto (fun (n : ι) => F n (g n)) p (nhds (f x)) := tendsto_comp_of_locally_uniform_limit hf hg fun (u : set (β × β)) (hu : u ∈ uniformity β) => h u hu x /-- If `Fₙ` tends uniformly to `f`, and `gₙ` tends to `x`, then `Fₙ gₙ` tends to `f x`. -/ theorem tendsto_uniformly.tendsto_comp {α : Type u} {β : Type v} {ι : Type u_1} [uniform_space β] {F : ι → α → β} {f : α → β} {x : α} {p : filter ι} {g : ι → α} [topological_space α] (h : tendsto_uniformly F f p) (hf : continuous_at f x) (hg : filter.tendsto g p (nhds x)) : filter.tendsto (fun (n : ι) => F n (g n)) p (nhds (f x)) := tendsto_locally_uniformly.tendsto_comp (tendsto_uniformly.tendsto_locally_uniformly h) hf hg end Mathlib
c367ff9c55d042875deb7cbc7b825f56f2537b6d
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/331.lean
c3d13b8e99f6ff3cfc1d39939f89ae77beecc0fe
[ "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
171
lean
structure Foo where foo : Nat def baz {x : _} := Foo.mk x -- works fine example {x : _} := Foo.mk x def qux {x : _} : Foo := Foo.mk x example {x : _} : Foo := Foo.mk x
78352e149ba1c371099c677455dc9493e763e73b
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/analysis/topology_auto.lean
a79f4636b0c3dd5f5d8e342efaf32a20588d29c1
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
8,425
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Computational realization of topological spaces (experimental). -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.bases import Mathlib.data.analysis.filter import Mathlib.PostPort universes u_1 u_2 l u_3 u_4 u_5 u_6 namespace Mathlib /-- A `ctop α σ` is a realization of a topology (basis) on `α`, represented by a type `σ` together with operations for the top element and the intersection operation. -/ structure ctop (α : Type u_1) (σ : Type u_2) where f : σ → set α top : α → σ top_mem : ∀ (x : α), x ∈ f (top x) inter : (a b : σ) → (x : α) → x ∈ f a ∩ f b → σ inter_mem : ∀ (a b : σ) (x : α) (h : x ∈ f a ∩ f b), x ∈ f (inter a b x h) inter_sub : ∀ (a b : σ) (x : α) (h : x ∈ f a ∩ f b), f (inter a b x h) ⊆ f a ∩ f b namespace ctop protected instance has_coe_to_fun {α : Type u_1} {σ : Type u_3} : has_coe_to_fun (ctop α σ) := has_coe_to_fun.mk (fun (x : ctop α σ) => σ → set α) f @[simp] theorem coe_mk {α : Type u_1} {σ : Type u_3} (f : σ → set α) (T : α → σ) (h₁ : ∀ (x : α), x ∈ f (T x)) (I : (a b : σ) → (x : α) → x ∈ f a ∩ f b → σ) (h₂ : ∀ (a b : σ) (x : α) (h : x ∈ f a ∩ f b), x ∈ f (I a b x h)) (h₃ : ∀ (a b : σ) (x : α) (h : x ∈ f a ∩ f b), f (I a b x h) ⊆ f a ∩ f b) (a : σ) : coe_fn (mk f T h₁ I h₂ h₃) a = f a := rfl /-- Map a ctop to an equivalent representation type. -/ def of_equiv {α : Type u_1} {σ : Type u_3} {τ : Type u_4} (E : σ ≃ τ) : ctop α σ → ctop α τ := sorry @[simp] theorem of_equiv_val {α : Type u_1} {σ : Type u_3} {τ : Type u_4} (E : σ ≃ τ) (F : ctop α σ) (a : τ) : coe_fn (of_equiv E F) a = coe_fn F (coe_fn (equiv.symm E) a) := sorry /-- Every `ctop` is a topological space. -/ def to_topsp {α : Type u_1} {σ : Type u_3} (F : ctop α σ) : topological_space α := topological_space.generate_from (set.range (f F)) theorem to_topsp_is_topological_basis {α : Type u_1} {σ : Type u_3} (F : ctop α σ) : topological_space.is_topological_basis (set.range (f F)) := sorry @[simp] theorem mem_nhds_to_topsp {α : Type u_1} {σ : Type u_3} (F : ctop α σ) {s : set α} {a : α} : s ∈ nhds a ↔ ∃ (b : σ), a ∈ coe_fn F b ∧ coe_fn F b ⊆ s := sorry end ctop /-- A `ctop` realizer for the topological space `T` is a `ctop` which generates `T`. -/ structure ctop.realizer (α : Type u_5) [T : topological_space α] where σ : Type u_6 F : ctop α σ eq : ctop.to_topsp F = T protected def ctop.to_realizer {α : Type u_1} {σ : Type u_3} (F : ctop α σ) : ctop.realizer α := ctop.realizer.mk σ F sorry namespace ctop.realizer protected theorem is_basis {α : Type u_1} [T : topological_space α] (F : realizer α) : topological_space.is_topological_basis (set.range (f (F F))) := eq.mp (Eq._oldrec (Eq.refl (topological_space.is_topological_basis (set.range (f (F F))))) (eq F)) (to_topsp_is_topological_basis (F F)) protected theorem mem_nhds {α : Type u_1} [T : topological_space α] (F : realizer α) {s : set α} {a : α} : s ∈ nhds a ↔ ∃ (b : σ F), a ∈ coe_fn (F F) b ∧ coe_fn (F F) b ⊆ s := eq.mp (Eq._oldrec (Eq.refl (s ∈ nhds a ↔ ∃ (b : σ F), a ∈ coe_fn (F F) b ∧ coe_fn (F F) b ⊆ s)) (eq F)) (mem_nhds_to_topsp (F F)) theorem is_open_iff {α : Type u_1} [topological_space α] (F : realizer α) {s : set α} : is_open s ↔ ∀ (a : α), a ∈ s → ∃ (b : σ F), a ∈ coe_fn (F F) b ∧ coe_fn (F F) b ⊆ s := iff.trans is_open_iff_mem_nhds (ball_congr fun (a : α) (h : a ∈ s) => realizer.mem_nhds F) theorem is_closed_iff {α : Type u_1} [topological_space α] (F : realizer α) {s : set α} : is_closed s ↔ ∀ (a : α), (∀ (b : σ F), a ∈ coe_fn (F F) b → ∃ (z : α), z ∈ coe_fn (F F) b ∩ s) → a ∈ s := sorry theorem mem_interior_iff {α : Type u_1} [topological_space α] (F : realizer α) {s : set α} {a : α} : a ∈ interior s ↔ ∃ (b : σ F), a ∈ coe_fn (F F) b ∧ coe_fn (F F) b ⊆ s := iff.trans mem_interior_iff_mem_nhds (realizer.mem_nhds F) protected theorem is_open {α : Type u_1} [topological_space α] (F : realizer α) (s : σ F) : is_open (coe_fn (F F) s) := sorry theorem ext' {α : Type u_1} [T : topological_space α] {σ : Type u_2} {F : ctop α σ} (H : ∀ (a : α) (s : set α), s ∈ nhds a ↔ ∃ (b : σ), a ∈ coe_fn F b ∧ coe_fn F b ⊆ s) : to_topsp F = T := sorry theorem ext {α : Type u_1} [T : topological_space α] {σ : Type u_2} {F : ctop α σ} (H₁ : ∀ (a : σ), is_open (coe_fn F a)) (H₂ : ∀ (a : α) (s : set α), s ∈ nhds a → ∃ (b : σ), a ∈ coe_fn F b ∧ coe_fn F b ⊆ s) : to_topsp F = T := sorry protected def id {α : Type u_1} [topological_space α] : realizer α := mk (Subtype fun (x : set α) => is_open x) (mk subtype.val (fun (_x : α) => { val := set.univ, property := is_open_univ }) set.mem_univ (fun (_x : Subtype fun (x : set α) => is_open x) => sorry) sorry sorry) sorry def of_equiv {α : Type u_1} {τ : Type u_4} [topological_space α] (F : realizer α) (E : σ F ≃ τ) : realizer α := mk τ (of_equiv E (F F)) sorry @[simp] theorem of_equiv_σ {α : Type u_1} {τ : Type u_4} [topological_space α] (F : realizer α) (E : σ F ≃ τ) : σ (of_equiv F E) = τ := rfl @[simp] theorem of_equiv_F {α : Type u_1} {τ : Type u_4} [topological_space α] (F : realizer α) (E : σ F ≃ τ) (s : τ) : coe_fn (F (of_equiv F E)) s = coe_fn (F F) (coe_fn (equiv.symm E) s) := sorry protected def nhds {α : Type u_1} [topological_space α] (F : realizer α) (a : α) : filter.realizer (nhds a) := filter.realizer.mk (Subtype fun (s : σ F) => a ∈ coe_fn (F F) s) (cfilter.mk (fun (s : Subtype fun (s : σ F) => a ∈ coe_fn (F F) s) => coe_fn (F F) (subtype.val s)) { val := top (F F) a, property := sorry } (fun (_x : Subtype fun (s : σ F) => a ∈ coe_fn (F F) s) => sorry) sorry sorry) sorry @[simp] theorem nhds_σ {α : Type u_1} {β : Type u_2} [topological_space α] (m : α → β) (F : realizer α) (a : α) : filter.realizer.σ (realizer.nhds F a) = Subtype fun (s : σ F) => a ∈ coe_fn (F F) s := rfl @[simp] theorem nhds_F {α : Type u_1} {β : Type u_2} [topological_space α] (m : α → β) (F : realizer α) (a : α) (s : filter.realizer.σ (realizer.nhds F a)) : coe_fn (filter.realizer.F (realizer.nhds F a)) s = coe_fn (F F) (subtype.val s) := rfl theorem tendsto_nhds_iff {α : Type u_1} {β : Type u_2} [topological_space α] {m : β → α} {f : filter β} (F : filter.realizer f) (R : realizer α) {a : α} : filter.tendsto m f (nhds a) ↔ ∀ (t : σ R), a ∈ coe_fn (F R) t → ∃ (s : filter.realizer.σ F), ∀ (x : β), x ∈ coe_fn (filter.realizer.F F) s → m x ∈ coe_fn (F R) t := iff.trans (filter.realizer.tendsto_iff m F (realizer.nhds R a)) subtype.forall end ctop.realizer structure locally_finite.realizer {α : Type u_1} {β : Type u_2} [topological_space α] (F : ctop.realizer α) (f : β → set α) where bas : (a : α) → Subtype fun (s : ctop.realizer.σ F) => a ∈ coe_fn (ctop.realizer.F F) s sets : (x : α) → fintype ↥(set_of fun (i : β) => set.nonempty (f i ∩ coe_fn (ctop.realizer.F F) ↑(bas x))) theorem locally_finite.realizer.to_locally_finite {α : Type u_1} {β : Type u_2} [topological_space α] {F : ctop.realizer α} {f : β → set α} (R : locally_finite.realizer F f) : locally_finite f := sorry theorem locally_finite_iff_exists_realizer {α : Type u_1} {β : Type u_2} [topological_space α] (F : ctop.realizer α) {f : β → set α} : locally_finite f ↔ Nonempty (locally_finite.realizer F f) := sorry def compact.realizer {α : Type u_1} [topological_space α] (R : ctop.realizer α) (s : set α) := {f : filter α} → (F : filter.realizer f) → (x : filter.realizer.σ F) → f ≠ ⊥ → coe_fn (filter.realizer.F F) x ⊆ s → Subtype fun (a : α) => a ∈ s ∧ nhds a ⊓ f ≠ ⊥ end Mathlib
d5fd0611ff5cf10f55ac4d70903026a2c9772bfd
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/tactic/doc_commands.lean
3fd0389491b8af41f1099ac98e0fe27a40400cd9
[ "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
17,320
lean
/- Copyright (c) 2020 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import tactic.fix_reflect_string /-! # Documentation commands We generate html documentation from mathlib. It is convenient to collect lists of tactics, commands, notes, etc. To facilitate this, we declare these documentation entries in the library using special commands. * `library_note` adds a note describing a certain feature or design decision. These can be referenced in doc strings with the text `note [name of note]`. * `add_tactic_doc` adds an entry documenting an interactive tactic, command, hole command, or attribute. Since these commands are used in files imported by `tactic.core`, this file has no imports. ## Implementation details `library_note note_id note_msg` creates a declaration `` `library_note.i `` for some `i`. This declaration is a pair of strings `note_id` and `note_msg`, and it gets tagged with the `library_note` attribute. Similarly, `add_tactic_doc` creates a declaration `` `tactic_doc.i `` that stores the provided information. -/ /-- A rudimentary hash function on strings. -/ def string.hash (s : string) : ℕ := s.fold 1 (λ h c, (33*h + c.val) % unsigned_sz) /-- `mk_hashed_name nspace id` hashes the string `id` to a value `i` and returns the name `nspace._i` -/ meta def string.mk_hashed_name (nspace : name) (id : string) : name := nspace <.> ("_" ++ to_string id.hash) open tactic /-- `copy_doc_string fr to` copies the docstring from the declaration named `fr` to each declaration named in the list `to`. -/ meta def tactic.copy_doc_string (fr : name) (to : list name) : tactic unit := do fr_ds ← doc_string fr, to.mmap' $ λ tgt, add_doc_string tgt fr_ds open lean lean.parser interactive /-- `copy_doc_string source → target_1 target_2 ... target_n` copies the doc string of the declaration named `source` to each of `target_1`, `target_2`, ..., `target_n`. -/ @[user_command] meta def copy_doc_string_cmd (_ : parse (tk "copy_doc_string")) : parser unit := do fr ← parser.ident, tk "->", to ← parser.many parser.ident, expr.const fr _ ← resolve_name fr, to ← parser.of_tactic (to.mmap $ λ n, expr.const_name <$> resolve_name n), tactic.copy_doc_string fr to /-! ### The `library_note` command -/ /-- A user attribute `library_note` for tagging decls of type `string × string` for use in note output. -/ @[user_attribute] meta def library_note_attr : user_attribute := { name := `library_note, descr := "Notes about library features to be included in documentation", parser := failed } /-- `mk_reflected_definition name val` constructs a definition declaration by reflection. Example: ``mk_reflected_definition `foo 17`` constructs the definition declaration corresponding to `def foo : ℕ := 17` -/ meta def mk_reflected_definition (decl_name : name) {type} [reflected type] (body : type) [reflected body] : declaration := mk_definition decl_name (reflect type).collect_univ_params (reflect type) (reflect body) /-- If `note_name` and `note` are `pexpr`s representing strings, `add_library_note note_name note` adds a declaration of type `string × string` and tags it with the `library_note` attribute. -/ meta def tactic.add_library_note (note_name note : string) : tactic unit := do let decl_name := note_name.mk_hashed_name `library_note, add_decl $ mk_reflected_definition decl_name (note_name, note), library_note_attr.set decl_name () tt none open tactic /-- A command to add library notes. Syntax: ``` /-- note message -/ library_note "note id" ``` -/ @[user_command] meta def library_note (mi : interactive.decl_meta_info) (_ : parse (tk "library_note")) : parser unit := do note_name ← parser.pexpr, note_name ← eval_pexpr string note_name, some doc_string ← pure mi.doc_string | fail "library_note requires a doc string", add_library_note note_name doc_string /-- Collects all notes in the current environment. Returns a list of pairs `(note_id, note_content)` -/ meta def tactic.get_library_notes : tactic (list (string × string)) := attribute.get_instances `library_note >>= list.mmap (λ dcl, mk_const dcl >>= eval_expr (string × string)) /-! ### The `add_tactic_doc_entry` command -/ /-- The categories of tactic doc entry. -/ @[derive [decidable_eq, has_reflect]] inductive doc_category | tactic | cmd | hole_cmd | attr /-- Format a `doc_category` -/ meta def doc_category.to_string : doc_category → string | doc_category.tactic := "tactic" | doc_category.cmd := "command" | doc_category.hole_cmd := "hole_command" | doc_category.attr := "attribute" meta instance : has_to_format doc_category := ⟨↑doc_category.to_string⟩ /-- The information used to generate a tactic doc entry -/ @[derive has_reflect] structure tactic_doc_entry := (name : string) (category : doc_category) (decl_names : list _root_.name) (tags : list string := []) (description : string := "") (inherit_description_from : option _root_.name := none) /-- Turns a `tactic_doc_entry` into a JSON representation. -/ meta def tactic_doc_entry.to_json (d : tactic_doc_entry) : json := json.object [ ("name", d.name), ("category", d.category.to_string), ("decl_names", d.decl_names.map (json.of_string ∘ to_string)), ("tags", d.tags.map json.of_string), ("description", d.description) ] meta instance : has_to_string tactic_doc_entry := ⟨json.unparse ∘ tactic_doc_entry.to_json⟩ /-- `update_description_from tde inh_id` replaces the `description` field of `tde` with the doc string of the declaration named `inh_id`. -/ meta def tactic_doc_entry.update_description_from (tde : tactic_doc_entry) (inh_id : name) : tactic tactic_doc_entry := do ds ← doc_string inh_id <|> fail (to_string inh_id ++ " has no doc string"), return { description := ds .. tde } /-- `update_description tde` replaces the `description` field of `tde` with: * the doc string of `tde.inherit_description_from`, if this field has a value * the doc string of the entry in `tde.decl_names`, if this field has length 1 If neither of these conditions are met, it returns `tde`. -/ meta def tactic_doc_entry.update_description (tde : tactic_doc_entry) : tactic tactic_doc_entry := match tde.inherit_description_from, tde.decl_names with | some inh_id, _ := tde.update_description_from inh_id | none, [inh_id] := tde.update_description_from inh_id | none, _ := return tde end /-- A user attribute `tactic_doc` for tagging decls of type `tactic_doc_entry` for use in doc output -/ @[user_attribute] meta def tactic_doc_entry_attr : user_attribute := { name := `tactic_doc, descr := "Information about a tactic to be included in documentation", parser := failed } /-- Collects everything in the environment tagged with the attribute `tactic_doc`. -/ meta def tactic.get_tactic_doc_entries : tactic (list tactic_doc_entry) := attribute.get_instances `tactic_doc >>= list.mmap (λ dcl, mk_const dcl >>= eval_expr tactic_doc_entry) /-- `add_tactic_doc tde` adds a declaration to the environment with `tde` as its body and tags it with the `tactic_doc` attribute. If `tde.decl_names` has exactly one entry `` `decl`` and if `tde.description` is the empty string, `add_tactic_doc` uses the doc string of `decl` as the description. -/ meta def tactic.add_tactic_doc (tde : tactic_doc_entry) : tactic unit := do when (tde.description = "" ∧ tde.inherit_description_from.is_none ∧ tde.decl_names.length ≠ 1) $ fail "A tactic doc entry must either: 1. have a description written as a doc-string for the `add_tactic_doc` invocation, or 2. have a single declaration in the `decl_names` field, to inherit a description from, or 3. explicitly indicate the declaration to inherit the description from using `inherit_description_from`.", tde ← if tde.description = "" then tde.update_description else return tde, let decl_name := (tde.name ++ tde.category.to_string).mk_hashed_name `tactic_doc, add_decl $ mk_definition decl_name [] `(tactic_doc_entry) (reflect tde), tactic_doc_entry_attr.set decl_name () tt none /-- A command used to add documentation for a tactic, command, hole command, or attribute. Usage: after defining an interactive tactic, command, or attribute, add its documentation as follows. ```lean /-- describe what the command does here -/ add_tactic_doc { name := "display name of the tactic", category := cat, decl_names := [`dcl_1, `dcl_2], tags := ["tag_1", "tag_2"] } ``` The argument to `add_tactic_doc` is a structure of type `tactic_doc_entry`. * `name` refers to the display name of the tactic; it is used as the header of the doc entry. * `cat` refers to the category of doc entry. Options: `doc_category.tactic`, `doc_category.cmd`, `doc_category.hole_cmd`, `doc_category.attr` * `decl_names` is a list of the declarations associated with this doc. For instance, the entry for `linarith` would set ``decl_names := [`tactic.interactive.linarith]``. Some entries may cover multiple declarations. It is only necessary to list the interactive versions of tactics. * `tags` is an optional list of strings used to categorize entries. * The doc string is the body of the entry. It can be formatted with markdown. What you are reading now is the description of `add_tactic_doc`. If only one related declaration is listed in `decl_names` and if this invocation of `add_tactic_doc` does not have a doc string, the doc string of that declaration will become the body of the tactic doc entry. If there are multiple declarations, you can select the one to be used by passing a name to the `inherit_description_from` field. If you prefer a tactic to have a doc string that is different then the doc entry, you should write the doc entry as a doc string for the `add_tactic_doc` invocation. Note that providing a badly formed `tactic_doc_entry` to the command can result in strange error messages. -/ @[user_command] meta def add_tactic_doc_command (mi : interactive.decl_meta_info) (_ : parse $ tk "add_tactic_doc") : parser unit := do pe ← parser.pexpr, e ← eval_pexpr tactic_doc_entry pe, let e : tactic_doc_entry := match mi.doc_string with | some desc := { description := desc, ..e } | none := e end, tactic.add_tactic_doc e . /-- At various places in mathlib, we leave implementation notes that are referenced from many other files. To keep track of these notes, we use the command `library_note`. This makes it easy to retrieve a list of all notes, e.g. for documentation output. These notes can be referenced in mathlib with the syntax `Note [note id]`. Often, these references will be made in code comments (`--`) that won't be displayed in docs. If such a reference is made in a doc string or module doc, it will be linked to the corresponding note in the doc display. Syntax: ``` /-- note message -/ library_note "note id" ``` An example from `meta.expr`: ``` /-- Some declarations work with open expressions, i.e. an expr that has free variables. Terms will free variables are not well-typed, and one should not use them in tactics like `infer_type` or `unify`. You can still do syntactic analysis/manipulation on them. The reason for working with open types is for performance: instantiating variables requires iterating through the expression. In one performance test `pi_binders` was more than 6x quicker than `mk_local_pis` (when applied to the type of all imported declarations 100x). -/ library_note "open expressions" ``` This note can be referenced near a usage of `pi_binders`: ``` -- See Note [open expressions] /-- behavior of f -/ def f := pi_binders ... ``` -/ add_tactic_doc { name := "library_note", category := doc_category.cmd, decl_names := [`library_note, `tactic.add_library_note], tags := ["documentation"], inherit_description_from := `library_note } add_tactic_doc { name := "add_tactic_doc", category := doc_category.cmd, decl_names := [`add_tactic_doc_command, `tactic.add_tactic_doc], tags := ["documentation"], inherit_description_from := `add_tactic_doc_command } add_tactic_doc { name := "copy_doc_string", category := doc_category.cmd, decl_names := [`copy_doc_string_cmd, `tactic.copy_doc_string], tags := ["documentation"], inherit_description_from := `copy_doc_string_cmd } -- add docs to core tactics /-- The congruence closure tactic `cc` tries to solve the goal by chaining equalities from context and applying congruence (i.e. if `a = b`, then `f a = f b`). It is a finishing tactic, i.e. it is meant to close the current goal, not to make some inconclusive progress. A mostly trivial example would be: ```lean example (a b c : ℕ) (f : ℕ → ℕ) (h: a = b) (h' : b = c) : f a = f c := by cc ``` As an example requiring some thinking to do by hand, consider: ```lean example (f : ℕ → ℕ) (x : ℕ) (H1 : f (f (f x)) = x) (H2 : f (f (f (f (f x)))) = x) : f x = x := by cc ``` The tactic works by building an equality matching graph. It's a graph where the vertices are terms and they are linked by edges if they are known to be equal. Once you've added all the equalities in your context, you take the transitive closure of the graph and, for each connected component (i.e. equivalence class) you can elect a term that will represent the whole class and store proofs that the other elements are equal to it. You then take the transitive closure of these equalities under the congruence lemmas. The `cc` implementation in Lean does a few more tricks: for example it derives `a=b` from `nat.succ a = nat.succ b`, and `nat.succ a != nat.zero` for any `a`. * The starting reference point is Nelson, Oppen, [Fast decision procedures based on congruence closure](http://www.cs.colorado.edu/~bec/courses/csci5535-s09/reading/nelson-oppen-congruence.pdf), Journal of the ACM (1980) * The congruence lemmas for dependent type theory as used in Lean are described in [Congruence closure in intensional type theory](https://leanprover.github.io/papers/congr.pdf) (de Moura, Selsam IJCAR 2016). -/ add_tactic_doc { name := "cc (congruence closure)", category := doc_category.tactic, decl_names := [`tactic.interactive.cc], tags := ["core", "finishing"] } /-- `conv {...}` allows the user to perform targeted rewriting on a goal or hypothesis, by focusing on particular subexpressions. See <https://leanprover-community.github.io/extras/conv.html> for more details. Inside `conv` blocks, mathlib currently additionally provides * `erw`, * `ring`, `ring2` and `ring_exp`, * `norm_num`, * `norm_cast`, * `apply_congr`, and * `conv` (within another `conv`). `apply_congr` applies congruence lemmas to step further inside expressions, and sometimes gives between results than the automatically generated congruence lemmas used by `congr`. Using `conv` inside a `conv` block allows the user to return to the previous state of the outer `conv` block after it is finished. Thus you can continue editing an expression without having to start a new `conv` block and re-scoping everything. For example: ```lean example (a b c d : ℕ) (h₁ : b = c) (h₂ : a + c = a + d) : a + b = a + d := by conv { to_lhs, conv { congr, skip, rw h₁ }, rw h₂, } ``` Without `conv`, the above example would need to be proved using two successive `conv` blocks, each beginning with `to_lhs`. Also, as a shorthand, `conv_lhs` and `conv_rhs` are provided, so that ```lean example : 0 + 0 = 0 := begin conv_lhs { simp } end ``` just means ```lean example : 0 + 0 = 0 := begin conv { to_lhs, simp } end ``` and likewise for `to_rhs`. -/ add_tactic_doc { name := "conv", category := doc_category.tactic, decl_names := [`tactic.interactive.conv], tags := ["core"] } add_tactic_doc { name := "simp", category := doc_category.tactic, decl_names := [`tactic.interactive.simp], tags := ["core", "simplification"] } /-- Accepts terms with the type `component tactic_state string` or `html empty` and renders them interactively. Requires a compatible version of the vscode extension to view the resulting widget. ### Example: ```lean /-- A simple counter that can be incremented or decremented with some buttons. -/ meta def counter_widget {π α : Type} : component π α := component.ignore_props $ component.mk_simple int int 0 (λ _ x y, (x + y, none)) (λ _ s, h "div" [] [ button "+" (1 : int), html.of_string $ to_string $ s, button "-" (-1) ] ) #html counter_widget ``` -/ add_tactic_doc { name := "#html", category := doc_category.cmd, decl_names := [`show_widget_cmd], tags := ["core", "widgets"] } /-- The `add_decl_doc` command is used to add a doc string to an existing declaration. ```lean def foo := 5 /-- Doc string for foo. -/ add_decl_doc foo ``` -/ @[user_command] meta def add_decl_doc_command (mi : interactive.decl_meta_info) (_ : parse $ tk "add_decl_doc") : parser unit := do n ← parser.ident, n ← resolve_constant n, some doc ← pure mi.doc_string | fail "add_decl_doc requires a doc string", add_doc_string n doc add_tactic_doc { name := "add_decl_doc", category := doc_category.cmd, decl_names := [``add_decl_doc_command], tags := ["documentation"] }
e12678ec9d139d75b074201d257128f541d9be1a
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/multiset/dedup.lean
2373d990007364b8669839e04aae79ca4a179d8c
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
3,328
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.multiset.nodup /-! # Erasing duplicates in a multiset. -/ namespace multiset open list variables {α β : Type*} [decidable_eq α] /-! ### dedup -/ /-- `dedup s` removes duplicates from `s`, yielding a `nodup` multiset. -/ def dedup (s : multiset α) : multiset α := quot.lift_on s (λ l, (l.dedup : multiset α)) (λ s t p, quot.sound p.dedup) @[simp] theorem coe_dedup (l : list α) : @dedup α _ l = l.dedup := rfl @[simp] theorem dedup_zero : @dedup α _ 0 = 0 := rfl @[simp] theorem mem_dedup {a : α} {s : multiset α} : a ∈ dedup s ↔ a ∈ s := quot.induction_on s $ λ l, mem_dedup @[simp] theorem dedup_cons_of_mem {a : α} {s : multiset α} : a ∈ s → dedup (a ::ₘ s) = dedup s := quot.induction_on s $ λ l m, @congr_arg _ _ _ _ coe $ dedup_cons_of_mem m @[simp] theorem dedup_cons_of_not_mem {a : α} {s : multiset α} : a ∉ s → dedup (a ::ₘ s) = a ::ₘ dedup s := quot.induction_on s $ λ l m, congr_arg coe $ dedup_cons_of_not_mem m theorem dedup_le (s : multiset α) : dedup s ≤ s := quot.induction_on s $ λ l, (dedup_sublist _).subperm theorem dedup_subset (s : multiset α) : dedup s ⊆ s := subset_of_le $ dedup_le _ theorem subset_dedup (s : multiset α) : s ⊆ dedup s := λ a, mem_dedup.2 @[simp] theorem dedup_subset' {s t : multiset α} : dedup s ⊆ t ↔ s ⊆ t := ⟨subset.trans (subset_dedup _), subset.trans (dedup_subset _)⟩ @[simp] theorem subset_dedup' {s t : multiset α} : s ⊆ dedup t ↔ s ⊆ t := ⟨λ h, subset.trans h (dedup_subset _), λ h, subset.trans h (subset_dedup _)⟩ @[simp] theorem nodup_dedup (s : multiset α) : nodup (dedup s) := quot.induction_on s nodup_dedup theorem dedup_eq_self {s : multiset α} : dedup s = s ↔ nodup s := ⟨λ e, e ▸ nodup_dedup s, quot.induction_on s $ λ l h, congr_arg coe h.dedup⟩ alias dedup_eq_self ↔ _ nodup.dedup theorem dedup_eq_zero {s : multiset α} : dedup s = 0 ↔ s = 0 := ⟨λ h, eq_zero_of_subset_zero $ h ▸ subset_dedup _, λ h, h.symm ▸ dedup_zero⟩ @[simp] theorem dedup_singleton {a : α} : dedup ({a} : multiset α) = {a} := (nodup_singleton _).dedup theorem le_dedup {s t : multiset α} : s ≤ dedup t ↔ s ≤ t ∧ nodup s := ⟨λ h, ⟨le_trans h (dedup_le _), nodup_of_le h (nodup_dedup _)⟩, λ ⟨l, d⟩, (le_iff_subset d).2 $ subset.trans (subset_of_le l) (subset_dedup _)⟩ theorem dedup_ext {s t : multiset α} : dedup s = dedup t ↔ ∀ a, a ∈ s ↔ a ∈ t := by simp [nodup.ext] theorem dedup_map_dedup_eq [decidable_eq β] (f : α → β) (s : multiset α) : dedup (map f (dedup s)) = dedup (map f s) := by simp [dedup_ext] @[simp] lemma dedup_nsmul {s : multiset α} {n : ℕ} (h0 : n ≠ 0) : (n • s).dedup = s.dedup := begin ext a, by_cases h : a ∈ s; simp [h,h0] end lemma nodup.le_dedup_iff_le {s t : multiset α} (hno : s.nodup) : s ≤ t.dedup ↔ s ≤ t := by simp [le_dedup, hno] end multiset lemma multiset.nodup.le_nsmul_iff_le {α : Type*} {s t : multiset α} {n : ℕ} (h : s.nodup) (hn : n ≠ 0) : s ≤ n • t ↔ s ≤ t := begin classical, rw [← h.le_dedup_iff_le, iff.comm, ← h.le_dedup_iff_le], simp [hn] end
09026c65406a1feeaf90342c73aa144b4ab45ccd
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/linear_algebra/basis.lean
be833c1cec027bdf31d2a7a3bf8d3acb993ec72c
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
56,537
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Alexander Bentkamp -/ import linear_algebra.finsupp import linear_algebra.projection import order.zorn import data.fintype.card import data.finset.order /-! # Linear independence and bases This file defines linear independence and bases in a module or vector space. It is inspired by Isabelle/HOL's linear algebra, and hence indirectly by HOL Light. ## Main definitions All definitions are given for families of vectors, i.e. `v : ι → M` where `M` is the module or vector space and `ι : Type*` is an arbitrary indexing type. * `linear_independent R v` states that the elements of the family `v` are linearly independent. * `linear_independent.repr hv x` returns the linear combination representing `x : span R (range v)` on the linearly independent vectors `v`, given `hv : linear_independent R v` (using classical choice). `linear_independent.repr hv` is provided as a linear map. * `is_basis R v` states that the vector family `v` is a basis, i.e. it is linearly independent and spans the entire space. * `is_basis.repr hv x` is the basis version of `linear_independent.repr hv x`. It returns the linear combination representing `x : M` on a basis `v` of `M` (using classical choice). The argument `hv` must be a proof that `is_basis R v`. `is_basis.repr hv` is given as a linear map as well. * `is_basis.constr hv f` constructs a linear map `M₁ →ₗ[R] M₂` given the values `f : ι → M₂` at the basis `v : ι → M₁`, given `hv : is_basis R v`. ## Main statements * `is_basis.ext` states that two linear maps are equal if they coincide on a basis. * `exists_is_basis` states that every vector space has a basis. ## Implementation notes We use families instead of sets because it allows us to say that two identical vectors are linearly dependent. For bases, this is useful as well because we can easily derive ordered bases by using an ordered index type `ι`. If you want to use sets, use the family `(λ x, x : s → M)` given a set `s : set M`. The lemmas `linear_independent.to_subtype_range` and `linear_independent.of_subtype_range` connect those two worlds. ## Tags linearly dependent, linear dependence, linearly independent, linear independence, basis -/ noncomputable theory open function set submodule open_locale classical big_operators universe u variables {ι : Type*} {ι' : Type*} {R : Type*} {K : Type*} {M : Type*} {M' M'' : Type*} {V : Type u} {V' : Type*} section module variables {v : ι → M} variables [ring R] [add_comm_group M] [add_comm_group M'] [add_comm_group M''] variables [module R M] [module R M'] [module R M''] variables {a b : R} {x y : M} variables (R) (v) /-- Linearly independent family of vectors -/ def linear_independent : Prop := (finsupp.total ι M R v).ker = ⊥ variables {R} {v} theorem linear_independent_iff : linear_independent R v ↔ ∀l, finsupp.total ι M R v l = 0 → l = 0 := by simp [linear_independent, linear_map.ker_eq_bot'] theorem linear_independent_iff' : linear_independent R v ↔ ∀ s : finset ι, ∀ g : ι → R, ∑ i in s, g i • v i = 0 → ∀ i ∈ s, g i = 0 := linear_independent_iff.trans ⟨λ hf s g hg i his, have h : _ := hf (∑ i in s, finsupp.single i (g i)) $ by simpa only [linear_map.map_sum, finsupp.total_single] using hg, calc g i = (finsupp.lapply i : (ι →₀ R) →ₗ[R] R) (finsupp.single i (g i)) : by rw [finsupp.lapply_apply, finsupp.single_eq_same] ... = ∑ j in s, (finsupp.lapply i : (ι →₀ R) →ₗ[R] R) (finsupp.single j (g j)) : eq.symm $ finset.sum_eq_single i (λ j hjs hji, by rw [finsupp.lapply_apply, finsupp.single_eq_of_ne hji]) (λ hnis, hnis.elim his) ... = (∑ j in s, finsupp.single j (g j)) i : (finsupp.lapply i : (ι →₀ R) →ₗ[R] R).map_sum.symm ... = 0 : finsupp.ext_iff.1 h i, λ hf l hl, finsupp.ext $ λ i, classical.by_contradiction $ λ hni, hni $ hf _ _ hl _ $ finsupp.mem_support_iff.2 hni⟩ theorem linear_independent_iff'' : linear_independent R v ↔ ∀ (s : finset ι) (g : ι → R) (hg : ∀ i ∉ s, g i = 0), ∑ i in s, g i • v i = 0 → ∀ i, g i = 0 := linear_independent_iff'.trans ⟨λ H s g hg hv i, if his : i ∈ s then H s g hv i his else hg i his, λ H s g hg i hi, by { convert H s (λ j, if j ∈ s then g j else 0) (λ j hj, if_neg hj) (by simp_rw [ite_smul, zero_smul, finset.sum_extend_by_zero, hg]) i, exact (if_pos hi).symm }⟩ theorem linear_dependent_iff : ¬ linear_independent R v ↔ ∃ s : finset ι, ∃ g : ι → R, s.sum (λ i, g i • v i) = 0 ∧ (∃ i ∈ s, g i ≠ 0) := begin rw linear_independent_iff', simp only [exists_prop, not_forall], end lemma linear_independent_empty_type (h : ¬ nonempty ι) : linear_independent R v := begin rw [linear_independent_iff], intros, ext i, exact false.elim (not_nonempty_iff_imp_false.1 h i) end lemma linear_independent.ne_zero [nontrivial R] {i : ι} (hv : linear_independent R v) : v i ≠ 0 := λ h, @zero_ne_one R _ _ $ eq.symm begin suffices : (finsupp.single i 1 : ι →₀ R) i = 0, {simpa}, rw linear_independent_iff.1 hv (finsupp.single i 1), {simp}, {simp [h]} end lemma linear_independent.comp (h : linear_independent R v) (f : ι' → ι) (hf : injective f) : linear_independent R (v ∘ f) := begin rw [linear_independent_iff, finsupp.total_comp], intros l hl, have h_map_domain : ∀ x, (finsupp.map_domain f l) (f x) = 0, by rw linear_independent_iff.1 h (finsupp.map_domain f l) hl; simp, ext, convert h_map_domain a, simp only [finsupp.map_domain_apply hf], end lemma linear_independent_of_zero_eq_one (zero_eq_one : (0 : R) = 1) : linear_independent R v := linear_independent_iff.2 (λ l hl, finsupp.eq_zero_of_zero_eq_one zero_eq_one _) lemma linear_independent.unique (hv : linear_independent R v) {l₁ l₂ : ι →₀ R} : finsupp.total ι M R v l₁ = finsupp.total ι M R v l₂ → l₁ = l₂ := by apply linear_map.ker_eq_bot.1 hv lemma linear_independent.injective [nontrivial R] (hv : linear_independent R v) : injective v := begin intros i j hij, let l : ι →₀ R := finsupp.single i (1 : R) - finsupp.single j 1, have h_total : finsupp.total ι M R v l = 0, { rw finsupp.total_apply, rw finsupp.sum_sub_index, { simp [finsupp.sum_single_index, hij] }, { intros, apply sub_smul } }, have h_single_eq : finsupp.single i (1 : R) = finsupp.single j 1, { rw linear_independent_iff at hv, simp [eq_add_of_sub_eq' (hv l h_total)] }, show i = j, { apply or.elim ((finsupp.single_eq_single_iff _ _ _ _).1 h_single_eq), simp, exact λ h, false.elim (zero_ne_one.symm h.1) } end lemma linear_independent_span (hs : linear_independent R v) : @linear_independent ι R (span R (range v)) (λ i : ι, ⟨v i, subset_span (mem_range_self i)⟩) _ _ _ := begin rw linear_independent_iff at *, intros l hl, apply hs l, have := congr_arg (submodule.subtype (span R (range v))) hl, convert this, rw [finsupp.total_apply, finsupp.total_apply], unfold finsupp.sum, rw linear_map.map_sum (submodule.subtype (span R (range v))), simp end section subtype /-! The following lemmas use the subtype defined by a set in `M` as the index set `ι`. -/ theorem linear_independent_comp_subtype {s : set ι} : linear_independent R (v ∘ coe : s → M) ↔ ∀ l ∈ (finsupp.supported R R s), (finsupp.total ι M R v) l = 0 → l = 0 := begin rw [linear_independent_iff, finsupp.total_comp], simp only [linear_map.comp_apply], split, { intros h l hl₁ hl₂, have h_bij : bij_on coe (coe ⁻¹' ↑l.support : set s) ↑l.support, { apply bij_on.mk, { apply maps_to_preimage }, { apply subtype.coe_injective.inj_on }, intros i hi, rw [image_preimage_eq_inter_range, subtype.range_coe], exact ⟨hi, (finsupp.mem_supported _ _).1 hl₁ hi⟩ }, show l = 0, { apply finsupp.eq_zero_of_comap_domain_eq_zero (coe : s → ι) _ h_bij, apply h, convert hl₂, rw [finsupp.lmap_domain_apply, finsupp.map_domain_comap_domain], exact subtype.coe_injective, rw subtype.range_coe, exact (finsupp.mem_supported _ _).1 hl₁ } }, { intros h l hl, have hl' : finsupp.total ι M R v (finsupp.emb_domain ⟨coe, subtype.coe_injective⟩ l) = 0, { rw finsupp.emb_domain_eq_map_domain ⟨coe, subtype.coe_injective⟩ l, apply hl }, apply finsupp.emb_domain_inj.1, rw [h (finsupp.emb_domain ⟨coe, subtype.coe_injective⟩ l) _ hl', finsupp.emb_domain_zero], rw [finsupp.mem_supported, finsupp.support_emb_domain], intros x hx, rw [finset.mem_coe, finset.mem_map] at hx, rcases hx with ⟨i, x', hx'⟩, rw ←hx', simp } end theorem linear_independent_subtype {s : set M} : linear_independent R (λ x, x : s → M) ↔ ∀ l ∈ (finsupp.supported R R s), (finsupp.total M M R id) l = 0 → l = 0 := by apply @linear_independent_comp_subtype _ _ _ id theorem linear_independent_comp_subtype_disjoint {s : set ι} : linear_independent R (v ∘ coe : s → M) ↔ disjoint (finsupp.supported R R s) (finsupp.total ι M R v).ker := by rw [linear_independent_comp_subtype, linear_map.disjoint_ker] theorem linear_independent_subtype_disjoint {s : set M} : linear_independent R (λ x, x : s → M) ↔ disjoint (finsupp.supported R R s) (finsupp.total M M R id).ker := by apply @linear_independent_comp_subtype_disjoint _ _ _ id theorem linear_independent_iff_total_on {s : set M} : linear_independent R (λ x, x : s → M) ↔ (finsupp.total_on M M R id s).ker = ⊥ := by rw [finsupp.total_on, linear_map.ker, linear_map.comap_cod_restrict, map_bot, comap_bot, linear_map.ker_comp, linear_independent_subtype_disjoint, disjoint, ← map_comap_subtype, map_le_iff_le_comap, comap_bot, ker_subtype, le_bot_iff] lemma linear_independent.to_subtype_range (hv : linear_independent R v) : linear_independent R (λ x, x : range v → M) := begin by_cases zero_eq_one : (0 : R) = 1, { apply linear_independent_of_zero_eq_one zero_eq_one }, haveI : nontrivial R := ⟨⟨0, 1, zero_eq_one⟩⟩, rw linear_independent_subtype, intros l hl₁ hl₂, have h_bij : bij_on v (v ⁻¹' ↑l.support) ↑l.support, { apply bij_on.mk, { apply maps_to_preimage }, { apply (linear_independent.injective hv).inj_on }, intros x hx, rcases mem_range.1 (((finsupp.mem_supported _ _).1 hl₁ : ↑(l.support) ⊆ range v) hx) with ⟨i, hi⟩, rw mem_image, use i, rw [mem_preimage, hi], exact ⟨hx, rfl⟩ }, apply finsupp.eq_zero_of_comap_domain_eq_zero v l h_bij, apply linear_independent_iff.1 hv, rw [finsupp.total_comap_domain, finset.sum_preimage_of_bij v l.support h_bij (λ (x : M), l x • x)], rwa [finsupp.total_apply, finsupp.sum] at hl₂ end lemma linear_independent.of_subtype_range (hv : injective v) (h : linear_independent R (λ x, x : range v → M)) : linear_independent R v := begin rw linear_independent_iff, intros l hl, apply finsupp.map_domain_injective hv, apply linear_independent_subtype.1 h (l.map_domain v), { rw finsupp.mem_supported, intros x hx, have := finset.mem_coe.2 (finsupp.map_domain_support hx), rw finset.coe_image at this, apply set.image_subset_range _ _ this, }, { rwa [finsupp.total_map_domain _ _ hv, left_id] } end lemma linear_independent.restrict_of_comp_subtype {s : set ι} (hs : linear_independent R (v ∘ coe : s → M)) : linear_independent R (s.restrict v) := begin have h_restrict : restrict v s = v ∘ coe := rfl, rw [linear_independent_iff, h_restrict, finsupp.total_comp], intros l hl, have h_map_domain_subtype_eq_0 : l.map_domain coe = 0, { rw linear_independent_comp_subtype at hs, apply hs (finsupp.lmap_domain R R coe l) _ hl, rw finsupp.mem_supported, simp, intros x hx, have := finset.mem_coe.2 (finsupp.map_domain_support (finset.mem_coe.1 hx)), rw finset.coe_image at this, exact subtype.coe_image_subset _ _ this }, apply @finsupp.map_domain_injective _ (subtype s) ι, { apply subtype.coe_injective }, { simpa }, end variables (R M) lemma linear_independent_empty : linear_independent R (λ x, x : (∅ : set M) → M) := by simp [linear_independent_subtype_disjoint] variables {R M} lemma linear_independent.mono {t s : set M} (h : t ⊆ s) : linear_independent R (λ x, x : s → M) → linear_independent R (λ x, x : t → M) := begin simp only [linear_independent_subtype_disjoint], exact (disjoint.mono_left (finsupp.supported_mono h)) end lemma linear_independent.union {s t : set M} (hs : linear_independent R (λ x, x : s → M)) (ht : linear_independent R (λ x, x : t → M)) (hst : disjoint (span R s) (span R t)) : linear_independent R (λ x, x : (s ∪ t) → M) := begin rw [linear_independent_subtype_disjoint, disjoint_def, finsupp.supported_union], intros l h₁ h₂, rw mem_sup at h₁, rcases h₁ with ⟨ls, hls, lt, hlt, rfl⟩, have h_ls_mem_t : finsupp.total M M R id ls ∈ span R t, { rw [← image_id t, finsupp.span_eq_map_total], apply (add_mem_iff_left (map _ _) (mem_image_of_mem _ hlt)).1, rw [← linear_map.map_add, linear_map.mem_ker.1 h₂], apply zero_mem }, have h_lt_mem_s : finsupp.total M M R id lt ∈ span R s, { rw [← image_id s, finsupp.span_eq_map_total], apply (add_mem_iff_left (map _ _) (mem_image_of_mem _ hls)).1, rw [← linear_map.map_add, add_comm, linear_map.mem_ker.1 h₂], apply zero_mem }, have h_ls_mem_s : (finsupp.total M M R id) ls ∈ span R s, { rw ← image_id s, apply (finsupp.mem_span_iff_total _).2 ⟨ls, hls, rfl⟩ }, have h_lt_mem_t : (finsupp.total M M R id) lt ∈ span R t, { rw ← image_id t, apply (finsupp.mem_span_iff_total _).2 ⟨lt, hlt, rfl⟩ }, have h_ls_0 : ls = 0 := disjoint_def.1 (linear_independent_subtype_disjoint.1 hs) _ hls (linear_map.mem_ker.2 $ disjoint_def.1 hst (finsupp.total M M R id ls) h_ls_mem_s h_ls_mem_t), have h_lt_0 : lt = 0 := disjoint_def.1 (linear_independent_subtype_disjoint.1 ht) _ hlt (linear_map.mem_ker.2 $ disjoint_def.1 hst (finsupp.total M M R id lt) h_lt_mem_s h_lt_mem_t), show ls + lt = 0, by simp [h_ls_0, h_lt_0], end lemma linear_independent_of_finite (s : set M) (H : ∀ t ⊆ s, finite t → linear_independent R (λ x, x : t → M)) : linear_independent R (λ x, x : s → M) := linear_independent_subtype.2 $ λ l hl, linear_independent_subtype.1 (H _ hl (finset.finite_to_set _)) l (subset.refl _) lemma linear_independent_Union_of_directed {η : Type*} {s : η → set M} (hs : directed (⊆) s) (h : ∀ i, linear_independent R (λ x, x : s i → M)) : linear_independent R (λ x, x : (⋃ i, s i) → M) := begin by_cases hη : nonempty η, { resetI, refine linear_independent_of_finite (⋃ i, s i) (λ t ht ft, _), rcases finite_subset_Union ft ht with ⟨I, fi, hI⟩, rcases hs.finset_le fi.to_finset with ⟨i, hi⟩, exact (h i).mono (subset.trans hI $ bUnion_subset $ λ j hj, hi j (finite.mem_to_finset.2 hj)) }, { refine (linear_independent_empty _ _).mono _, rintro _ ⟨_, ⟨i, _⟩, _⟩, exact hη ⟨i⟩ } end lemma linear_independent_sUnion_of_directed {s : set (set M)} (hs : directed_on (⊆) s) (h : ∀ a ∈ s, linear_independent R (λ x, x : (a : set M) → M)) : linear_independent R (λ x, x : (⋃₀ s) → M) := by rw sUnion_eq_Union; exact linear_independent_Union_of_directed hs.directed_coe (by simpa using h) lemma linear_independent_bUnion_of_directed {η} {s : set η} {t : η → set M} (hs : directed_on (t ⁻¹'o (⊆)) s) (h : ∀a∈s, linear_independent R (λ x, x : t a → M)) : linear_independent R (λ x, x : (⋃a∈s, t a) → M) := by rw bUnion_eq_Union; exact linear_independent_Union_of_directed (directed_comp.2 $ hs.directed_coe) (by simpa using h) lemma linear_independent_Union_finite_subtype {ι : Type*} {f : ι → set M} (hl : ∀i, linear_independent R (λ x, x : f i → M)) (hd : ∀i, ∀t:set ι, finite t → i ∉ t → disjoint (span R (f i)) (⨆i∈t, span R (f i))) : linear_independent R (λ x, x : (⋃i, f i) → M) := begin rw [Union_eq_Union_finset f], apply linear_independent_Union_of_directed, apply directed_of_sup, exact (assume t₁ t₂ ht, Union_subset_Union $ assume i, Union_subset_Union_const $ assume h, ht h), assume t, rw [set.Union, ← finset.sup_eq_supr], refine t.induction_on _ _, { rw finset.sup_empty, apply linear_independent_empty_type (not_nonempty_iff_imp_false.2 _), exact λ x, set.not_mem_empty x (subtype.mem x) }, { rintros i s his ih, rw [finset.sup_insert], refine (hl _).union ih _, rw [finset.sup_eq_supr], refine (hd i _ _ his).mono_right _, { simp only [(span_Union _).symm], refine span_mono (@supr_le_supr2 (set M) _ _ _ _ _ _), rintros i, exact ⟨i, le_refl _⟩ }, { exact s.finite_to_set } } end lemma linear_independent_Union_finite {η : Type*} {ιs : η → Type*} {f : Π j : η, ιs j → M} (hindep : ∀j, linear_independent R (f j)) (hd : ∀i, ∀t:set η, finite t → i ∉ t → disjoint (span R (range (f i))) (⨆i∈t, span R (range (f i)))) : linear_independent R (λ ji : Σ j, ιs j, f ji.1 ji.2) := begin by_cases zero_eq_one : (0 : R) = 1, { apply linear_independent_of_zero_eq_one zero_eq_one }, haveI : nontrivial R := ⟨⟨0, 1, zero_eq_one⟩⟩, apply linear_independent.of_subtype_range, { rintros ⟨x₁, x₂⟩ ⟨y₁, y₂⟩ hxy, by_cases h_cases : x₁ = y₁, subst h_cases, { apply sigma.eq, rw linear_independent.injective (hindep _) hxy, refl }, { have h0 : f x₁ x₂ = 0, { apply disjoint_def.1 (hd x₁ {y₁} (finite_singleton y₁) (λ h, h_cases (eq_of_mem_singleton h))) (f x₁ x₂) (subset_span (mem_range_self _)), rw supr_singleton, simp only at hxy, rw hxy, exact (subset_span (mem_range_self y₂)) }, exact false.elim ((hindep x₁).ne_zero h0) } }, rw range_sigma_eq_Union_range, apply linear_independent_Union_finite_subtype (λ j, (hindep j).to_subtype_range) hd, end end subtype section repr variables (hv : linear_independent R v) /-- Canonical isomorphism between linear combinations and the span of linearly independent vectors. -/ def linear_independent.total_equiv (hv : linear_independent R v) : (ι →₀ R) ≃ₗ[R] span R (range v) := begin apply linear_equiv.of_bijective (linear_map.cod_restrict (span R (range v)) (finsupp.total ι M R v) _), { rw linear_map.ker_cod_restrict, apply hv }, { rw [linear_map.range, linear_map.map_cod_restrict, ← linear_map.range_le_iff_comap, range_subtype, map_top], rw finsupp.range_total, apply le_refl (span R (range v)) }, { intro l, rw ← finsupp.range_total, rw linear_map.mem_range, apply mem_range_self l } end /-- Linear combination representing a vector in the span of linearly independent vectors. Given a family of linearly independent vectors, we can represent any vector in their span as a linear combination of these vectors. These are provided by this linear map. It is simply one direction of `linear_independent.total_equiv`. -/ def linear_independent.repr (hv : linear_independent R v) : span R (range v) →ₗ[R] ι →₀ R := hv.total_equiv.symm lemma linear_independent.total_repr (x) : finsupp.total ι M R v (hv.repr x) = x := subtype.ext_iff.1 (linear_equiv.apply_symm_apply hv.total_equiv x) lemma linear_independent.total_comp_repr : (finsupp.total ι M R v).comp hv.repr = submodule.subtype _ := linear_map.ext $ hv.total_repr lemma linear_independent.repr_ker : hv.repr.ker = ⊥ := by rw [linear_independent.repr, linear_equiv.ker] lemma linear_independent.repr_range : hv.repr.range = ⊤ := by rw [linear_independent.repr, linear_equiv.range] lemma linear_independent.repr_eq {l : ι →₀ R} {x} (eq : finsupp.total ι M R v l = ↑x) : hv.repr x = l := begin have : ↑((linear_independent.total_equiv hv : (ι →₀ R) →ₗ[R] span R (range v)) l) = finsupp.total ι M R v l := rfl, have : (linear_independent.total_equiv hv : (ι →₀ R) →ₗ[R] span R (range v)) l = x, { rw eq at this, exact subtype.ext_iff.2 this }, rw ←linear_equiv.symm_apply_apply hv.total_equiv l, rw ←this, refl, end lemma linear_independent.repr_eq_single (i) (x) (hx : ↑x = v i) : hv.repr x = finsupp.single i 1 := begin apply hv.repr_eq, simp [finsupp.total_single, hx] end -- TODO: why is this so slow? lemma linear_independent_iff_not_smul_mem_span : linear_independent R v ↔ (∀ (i : ι) (a : R), a • (v i) ∈ span R (v '' (univ \ {i})) → a = 0) := ⟨ λ hv i a ha, begin rw [finsupp.span_eq_map_total, mem_map] at ha, rcases ha with ⟨l, hl, e⟩, rw sub_eq_zero.1 (linear_independent_iff.1 hv (l - finsupp.single i a) (by simp [e])) at hl, by_contra hn, exact (not_mem_of_mem_diff (hl $ by simp [hn])) (mem_singleton _), end, λ H, linear_independent_iff.2 $ λ l hl, begin ext i, simp only [finsupp.zero_apply], by_contra hn, refine hn (H i _ _), refine (finsupp.mem_span_iff_total _).2 ⟨finsupp.single i (l i) - l, _, _⟩, { rw finsupp.mem_supported', intros j hj, have hij : j = i := not_not.1 (λ hij : j ≠ i, hj ((mem_diff _).2 ⟨mem_univ _, λ h, hij (eq_of_mem_singleton h)⟩)), simp [hij] }, { simp [hl] } end⟩ end repr lemma surjective_of_linear_independent_of_span [nontrivial R] (hv : linear_independent R v) (f : ι' ↪ ι) (hss : range v ⊆ span R (range (v ∘ f))) : surjective f := begin intros i, let repr : (span R (range (v ∘ f)) : Type*) → ι' →₀ R := (hv.comp f f.injective).repr, let l := (repr ⟨v i, hss (mem_range_self i)⟩).map_domain f, have h_total_l : finsupp.total ι M R v l = v i, { dsimp only [l], rw finsupp.total_map_domain, rw (hv.comp f f.injective).total_repr, { refl }, { exact f.injective } }, have h_total_eq : (finsupp.total ι M R v) l = (finsupp.total ι M R v) (finsupp.single i 1), by rw [h_total_l, finsupp.total_single, one_smul], have l_eq : l = _ := linear_map.ker_eq_bot.1 hv h_total_eq, dsimp only [l] at l_eq, rw ←finsupp.emb_domain_eq_map_domain at l_eq, rcases finsupp.single_of_emb_domain_single (repr ⟨v i, _⟩) f i (1 : R) zero_ne_one.symm l_eq with ⟨i', hi'⟩, use i', exact hi'.2 end lemma eq_of_linear_independent_of_span_subtype [nontrivial R] {s t : set M} (hs : linear_independent R (λ x, x : s → M)) (h : t ⊆ s) (hst : s ⊆ span R t) : s = t := begin let f : t ↪ s := ⟨λ x, ⟨x.1, h x.2⟩, λ a b hab, subtype.coe_injective (subtype.mk.inj hab)⟩, have h_surj : surjective f, { apply surjective_of_linear_independent_of_span hs f _, convert hst; simp [f, comp], }, show s = t, { apply subset.antisymm _ h, intros x hx, rcases h_surj ⟨x, hx⟩ with ⟨y, hy⟩, convert y.mem, rw ← subtype.mk.inj hy, refl } end open linear_map lemma linear_independent.image (hv : linear_independent R v) {f : M →ₗ M'} (hf_inj : disjoint (span R (range v)) f.ker) : linear_independent R (f ∘ v) := begin rw [disjoint, ← set.image_univ, finsupp.span_eq_map_total, map_inf_eq_map_inf_comap, map_le_iff_le_comap, comap_bot, finsupp.supported_univ, top_inf_eq] at hf_inj, unfold linear_independent at hv, rw hv at hf_inj, haveI : inhabited M := ⟨0⟩, rw [linear_independent, finsupp.total_comp], rw [@finsupp.lmap_domain_total _ _ R _ _ _ _ _ _ _ _ _ _ f, ker_comp, eq_bot_iff], apply hf_inj, exact λ _, rfl, end lemma linear_independent.image_subtype {s : set M} {f : M →ₗ M'} (hs : linear_independent R (λ x, x : s → M)) (hf_inj : disjoint (span R s) f.ker) : linear_independent R (λ x, x : f '' s → M') := begin rw [disjoint, ← set.image_id s, finsupp.span_eq_map_total, map_inf_eq_map_inf_comap, map_le_iff_le_comap, comap_bot] at hf_inj, haveI : inhabited M := ⟨0⟩, rw [linear_independent_subtype_disjoint, disjoint, ← finsupp.lmap_domain_supported _ _ f, map_inf_eq_map_inf_comap, map_le_iff_le_comap, ← ker_comp], rw [@finsupp.lmap_domain_total _ _ R _ _ _, ker_comp], { exact le_trans (le_inf inf_le_left hf_inj) (le_trans (linear_independent_subtype_disjoint.1 hs) bot_le) }, { simp } end lemma linear_independent.inl_union_inr {s : set M} {t : set M'} (hs : linear_independent R (λ x, x : s → M)) (ht : linear_independent R (λ x, x : t → M')) : linear_independent R (λ x, x : inl R M M' '' s ∪ inr R M M' '' t → M × M') := begin refine (hs.image_subtype _).union (ht.image_subtype _) _; [simp, simp, skip], simp only [span_image], simp [disjoint_iff, prod_inf_prod] end lemma linear_independent_inl_union_inr' {v : ι → M} {v' : ι' → M'} (hv : linear_independent R v) (hv' : linear_independent R v') : linear_independent R (sum.elim (inl R M M' ∘ v) (inr R M M' ∘ v')) := begin by_cases zero_eq_one : (0 : R) = 1, { apply linear_independent_of_zero_eq_one zero_eq_one }, haveI : nontrivial R := ⟨⟨0, 1, zero_eq_one⟩⟩, have inj_v : injective v := (linear_independent.injective hv), have inj_v' : injective v' := (linear_independent.injective hv'), apply linear_independent.of_subtype_range, { apply sum.elim_injective, { exact inl_injective.comp inj_v }, { exact inr_injective.comp inj_v' }, { intros, simp [hv.ne_zero] } }, { rw sum.elim_range, refine (hv.image _).to_subtype_range.union (hv'.image _).to_subtype_range _; [simp, simp, skip], apply disjoint_inl_inr.mono _ _; simp only [set.range_comp, span_image, linear_map.map_le_range] } end /-- Dedekind's linear independence of characters -/ -- See, for example, Keith Conrad's note <https://kconrad.math.uconn.edu/blurbs/galoistheory/linearchar.pdf> theorem linear_independent_monoid_hom (G : Type*) [monoid G] (L : Type*) [integral_domain L] : @linear_independent _ L (G → L) (λ f, f : (G →* L) → (G → L)) _ _ _ := by letI := classical.dec_eq (G →* L); letI : mul_action L L := distrib_mul_action.to_mul_action; -- We prove linear independence by showing that only the trivial linear combination vanishes. exact linear_independent_iff'.2 -- To do this, we use `finset` induction, (λ s, finset.induction_on s (λ g hg i, false.elim) $ λ a s has ih g hg, -- Here -- * `a` is a new character we will insert into the `finset` of characters `s`, -- * `ih` is the fact that only the trivial linear combination of characters in `s` is zero -- * `hg` is the fact that `g` are the coefficients of a linear combination summing to zero -- and it remains to prove that `g` vanishes on `insert a s`. -- We now make the key calculation: -- For any character `i` in the original `finset`, we have `g i • i = g i • a` as functions on the monoid `G`. have h1 : ∀ i ∈ s, (g i • i : G → L) = g i • a, from λ i his, funext $ λ x : G, -- We prove these expressions are equal by showing -- the differences of their values on each monoid element `x` is zero eq_of_sub_eq_zero $ ih (λ j, g j * j x - g j * a x) (funext $ λ y : G, calc -- After that, it's just a chase scene. (∑ i in s, ((g i * i x - g i * a x) • i : G → L)) y = ∑ i in s, (g i * i x - g i * a x) * i y : finset.sum_apply _ _ _ ... = ∑ i in s, (g i * i x * i y - g i * a x * i y) : finset.sum_congr rfl (λ _ _, sub_mul _ _ _) ... = ∑ i in s, g i * i x * i y - ∑ i in s, g i * a x * i y : finset.sum_sub_distrib ... = (g a * a x * a y + ∑ i in s, g i * i x * i y) - (g a * a x * a y + ∑ i in s, g i * a x * i y) : by rw add_sub_add_left_eq_sub ... = ∑ i in insert a s, g i * i x * i y - ∑ i in insert a s, g i * a x * i y : by rw [finset.sum_insert has, finset.sum_insert has] ... = ∑ i in insert a s, g i * i (x * y) - ∑ i in insert a s, a x * (g i * i y) : congr (congr_arg has_sub.sub (finset.sum_congr rfl $ λ i _, by rw [i.map_mul, mul_assoc])) (finset.sum_congr rfl $ λ _ _, by rw [mul_assoc, mul_left_comm]) ... = (∑ i in insert a s, (g i • i : G → L)) (x * y) - a x * (∑ i in insert a s, (g i • i : G → L)) y : by rw [finset.sum_apply, finset.sum_apply, finset.mul_sum]; refl ... = 0 - a x * 0 : by rw hg; refl ... = 0 : by rw [mul_zero, sub_zero]) i his, -- On the other hand, since `a` is not already in `s`, for any character `i ∈ s` -- there is some element of the monoid on which it differs from `a`. have h2 : ∀ i : G →* L, i ∈ s → ∃ y, i y ≠ a y, from λ i his, classical.by_contradiction $ λ h, have hia : i = a, from monoid_hom.ext $ λ y, classical.by_contradiction $ λ hy, h ⟨y, hy⟩, has $ hia ▸ his, -- From these two facts we deduce that `g` actually vanishes on `s`, have h3 : ∀ i ∈ s, g i = 0, from λ i his, let ⟨y, hy⟩ := h2 i his in have h : g i • i y = g i • a y, from congr_fun (h1 i his) y, or.resolve_right (mul_eq_zero.1 $ by rw [mul_sub, sub_eq_zero]; exact h) (sub_ne_zero_of_ne hy), -- And so, using the fact that the linear combination over `s` and over `insert a s` both vanish, -- we deduce that `g a = 0`. have h4 : g a = 0, from calc g a = g a * 1 : (mul_one _).symm ... = (g a • a : G → L) 1 : by rw ← a.map_one; refl ... = (∑ i in insert a s, (g i • i : G → L)) 1 : begin rw finset.sum_eq_single a, { intros i his hia, rw finset.mem_insert at his, rw [h3 i (his.resolve_left hia), zero_smul] }, { intros haas, exfalso, apply haas, exact finset.mem_insert_self a s } end ... = 0 : by rw hg; refl, -- Now we're done; the last two facts together imply that `g` vanishes on every element of `insert a s`. (finset.forall_mem_insert _ _ _).2 ⟨h4, h3⟩) lemma le_of_span_le_span [nontrivial R] {s t u: set M} (hl : linear_independent R (coe : u → M )) (hsu : s ⊆ u) (htu : t ⊆ u) (hst : span R s ≤ span R t) : s ⊆ t := begin have := eq_of_linear_independent_of_span_subtype (hl.mono (set.union_subset hsu htu)) (set.subset_union_right _ _) (set.union_subset (set.subset.trans subset_span hst) subset_span), rw ← this, apply set.subset_union_left end lemma span_le_span_iff [nontrivial R] {s t u: set M} (hl : linear_independent R (coe : u → M)) (hsu : s ⊆ u) (htu : t ⊆ u) : span R s ≤ span R t ↔ s ⊆ t := ⟨le_of_span_le_span hl hsu htu, span_mono⟩ variables (R) (v) /-- A family of vectors is a basis if it is linearly independent and all vectors are in the span. -/ def is_basis := linear_independent R v ∧ span R (range v) = ⊤ variables {R} {v} section is_basis variables {s t : set M} (hv : is_basis R v) lemma is_basis.mem_span (hv : is_basis R v) : ∀ x, x ∈ span R (range v) := eq_top_iff'.1 hv.2 lemma is_basis.comp (hv : is_basis R v) (f : ι' → ι) (hf : bijective f) : is_basis R (v ∘ f) := begin split, { apply hv.1.comp f hf.1 }, { rw[set.range_comp, range_iff_surjective.2 hf.2, image_univ, hv.2] } end lemma is_basis.injective [nontrivial R] (hv : is_basis R v) : injective v := λ x y h, linear_independent.injective hv.1 h lemma is_basis.range (hv : is_basis R v) : is_basis R (λ x, x : range v → M) := ⟨hv.1.to_subtype_range, by { convert hv.2, ext i, exact ⟨λ ⟨p, hp⟩, hp ▸ p.2, λ hi, ⟨⟨i, hi⟩, rfl⟩⟩ }⟩ /-- Given a basis, any vector can be written as a linear combination of the basis vectors. They are given by this linear map. This is one direction of `module_equiv_finsupp`. -/ def is_basis.repr : M →ₗ (ι →₀ R) := (hv.1.repr).comp (linear_map.id.cod_restrict _ hv.mem_span) lemma is_basis.total_repr (x) : finsupp.total ι M R v (hv.repr x) = x := hv.1.total_repr ⟨x, _⟩ lemma is_basis.total_comp_repr : (finsupp.total ι M R v).comp hv.repr = linear_map.id := linear_map.ext hv.total_repr lemma is_basis.repr_ker : hv.repr.ker = ⊥ := linear_map.ker_eq_bot.2 $ left_inverse.injective hv.total_repr lemma is_basis.repr_range : hv.repr.range = finsupp.supported R R univ := by rw [is_basis.repr, linear_map.range, submodule.map_comp, linear_map.map_cod_restrict, submodule.map_id, comap_top, map_top, hv.1.repr_range, finsupp.supported_univ] lemma is_basis.repr_total (x : ι →₀ R) (hx : x ∈ finsupp.supported R R (univ : set ι)) : hv.repr (finsupp.total ι M R v x) = x := begin rw [← hv.repr_range, linear_map.mem_range] at hx, cases hx with w hw, rw [← hw, hv.total_repr], end lemma is_basis.repr_eq_single {i} : hv.repr (v i) = finsupp.single i 1 := by apply hv.1.repr_eq_single; simp @[simp] lemma is_basis.repr_self_apply (i j : ι) : hv.repr (v i) j = if i = j then 1 else 0 := by rw [hv.repr_eq_single, finsupp.single_apply] /-- Construct a linear map given the value at the basis. -/ def is_basis.constr (f : ι → M') : M →ₗ[R] M' := (finsupp.total M' M' R id).comp $ (finsupp.lmap_domain R R f).comp hv.repr theorem is_basis.constr_apply (f : ι → M') (x : M) : (hv.constr f : M → M') x = (hv.repr x).sum (λb a, a • f b) := by dsimp [is_basis.constr]; rw [finsupp.total_apply, finsupp.sum_map_domain_index]; simp [add_smul] lemma is_basis.ext {f g : M →ₗ[R] M'} (hv : is_basis R v) (h : ∀i, f (v i) = g (v i)) : f = g := begin apply linear_map.ext (λ x, linear_eq_on (range v) _ (hv.mem_span x)), exact (λ y hy, exists.elim (set.mem_range.1 hy) (λ i hi, by rw ←hi; exact h i)) end @[simp] lemma constr_basis {f : ι → M'} {i : ι} (hv : is_basis R v) : (hv.constr f : M → M') (v i) = f i := by simp [is_basis.constr_apply, hv.repr_eq_single, finsupp.sum_single_index] lemma constr_eq {g : ι → M'} {f : M →ₗ[R] M'} (hv : is_basis R v) (h : ∀i, g i = f (v i)) : hv.constr g = f := hv.ext $ λ i, (constr_basis hv).trans (h i) lemma constr_self (f : M →ₗ[R] M') : hv.constr (λ i, f (v i)) = f := constr_eq hv $ λ x, rfl lemma constr_zero (hv : is_basis R v) : hv.constr (λi, (0 : M')) = 0 := constr_eq hv $ λ x, rfl lemma constr_add {g f : ι → M'} (hv : is_basis R v) : hv.constr (λi, f i + g i) = hv.constr f + hv.constr g := constr_eq hv $ λ b, by simp lemma constr_neg {f : ι → M'} (hv : is_basis R v) : hv.constr (λi, - f i) = - hv.constr f := constr_eq hv $ λ b, by simp lemma constr_sub {g f : ι → M'} (hs : is_basis R v) : hv.constr (λi, f i - g i) = hs.constr f - hs.constr g := by simp [sub_eq_add_neg, constr_add, constr_neg] -- this only works on functions if `R` is a commutative ring lemma constr_smul {ι R M} [comm_ring R] [add_comm_group M] [module R M] {v : ι → R} {f : ι → M} {a : R} (hv : is_basis R v) : hv.constr (λb, a • f b) = a • hv.constr f := constr_eq hv $ by simp [constr_basis hv] {contextual := tt} lemma constr_range [nonempty ι] (hv : is_basis R v) {f : ι → M'} : (hv.constr f).range = span R (range f) := by rw [is_basis.constr, linear_map.range_comp, linear_map.range_comp, is_basis.repr_range, finsupp.lmap_domain_supported, ←set.image_univ, ←finsupp.span_eq_map_total, image_id] /-- Canonical equivalence between a module and the linear combinations of basis vectors. -/ def module_equiv_finsupp (hv : is_basis R v) : M ≃ₗ[R] ι →₀ R := (hv.1.total_equiv.trans (linear_equiv.of_top _ hv.2)).symm @[simp] theorem module_equiv_finsupp_apply_basis (hv : is_basis R v) (i : ι) : module_equiv_finsupp hv (v i) = finsupp.single i 1 := (linear_equiv.symm_apply_eq _).2 $ by simp [linear_independent.total_equiv] /-- Isomorphism between the two modules, given two modules `M` and `M'` with respective bases `v` and `v'` and a bijection between the indexing sets of the two bases. -/ def equiv_of_is_basis {v : ι → M} {v' : ι' → M'} (hv : is_basis R v) (hv' : is_basis R v') (e : ι ≃ ι') : M ≃ₗ[R] M' := { inv_fun := hv'.constr (v ∘ e.symm), left_inv := have (hv'.constr (v ∘ e.symm)).comp (hv.constr (v' ∘ e)) = linear_map.id, from hv.ext $ by simp, λ x, congr_arg (λ h : M →ₗ[R] M, h x) this, right_inv := have (hv.constr (v' ∘ e)).comp (hv'.constr (v ∘ e.symm)) = linear_map.id, from hv'.ext $ by simp, λ y, congr_arg (λ h : M' →ₗ[R] M', h y) this, ..hv.constr (v' ∘ e) } /-- Isomorphism between the two modules, given two modules `M` and `M'` with respective bases `v` and `v'` and a bijection between the two bases. -/ def equiv_of_is_basis' {v : ι → M} {v' : ι' → M'} (f : M → M') (g : M' → M) (hv : is_basis R v) (hv' : is_basis R v') (hf : ∀i, f (v i) ∈ range v') (hg : ∀i, g (v' i) ∈ range v) (hgf : ∀i, g (f (v i)) = v i) (hfg : ∀i, f (g (v' i)) = v' i) : M ≃ₗ M' := { inv_fun := hv'.constr (g ∘ v'), left_inv := have (hv'.constr (g ∘ v')).comp (hv.constr (f ∘ v)) = linear_map.id, from hv.ext $ λ i, exists.elim (hf i) (λ i' hi', by simp [constr_basis, hi'.symm]; rw [hi', hgf]), λ x, congr_arg (λ h:M →ₗ[R] M, h x) this, right_inv := have (hv.constr (f ∘ v)).comp (hv'.constr (g ∘ v')) = linear_map.id, from hv'.ext $ λ i', exists.elim (hg i') (λ i hi, by simp [constr_basis, hi.symm]; rw [hi, hfg]), λ y, congr_arg (λ h:M' →ₗ[R] M', h y) this, ..hv.constr (f ∘ v) } @[simp] lemma equiv_of_is_basis_comp {ι'' : Type*} {v : ι → M} {v' : ι' → M'} {v'' : ι'' → M''} (hv : is_basis R v) (hv' : is_basis R v') (hv'' : is_basis R v'') (e : ι ≃ ι') (f : ι' ≃ ι'' ) : (equiv_of_is_basis hv hv' e).trans (equiv_of_is_basis hv' hv'' f) = equiv_of_is_basis hv hv'' (e.trans f) := begin apply linear_equiv.eq_of_linear_map_eq, apply hv.ext, intros i, simp [equiv_of_is_basis] end @[simp] lemma equiv_of_is_basis_refl : equiv_of_is_basis hv hv (equiv.refl ι) = linear_equiv.refl R M := begin apply linear_equiv.eq_of_linear_map_eq, apply hv.ext, intros i, simp [equiv_of_is_basis] end lemma equiv_of_is_basis_trans_symm (e : ι ≃ ι') {v' : ι' → M'} (hv' : is_basis R v') : (equiv_of_is_basis hv hv' e).trans (equiv_of_is_basis hv' hv e.symm) = linear_equiv.refl R M := by simp lemma equiv_of_is_basis_symm_trans (e : ι ≃ ι') {v' : ι' → M'} (hv' : is_basis R v') : (equiv_of_is_basis hv' hv e.symm).trans (equiv_of_is_basis hv hv' e) = linear_equiv.refl R M' := by simp lemma is_basis_inl_union_inr {v : ι → M} {v' : ι' → M'} (hv : is_basis R v) (hv' : is_basis R v') : is_basis R (sum.elim (inl R M M' ∘ v) (inr R M M' ∘ v')) := begin split, apply linear_independent_inl_union_inr' hv.1 hv'.1, rw [sum.elim_range, span_union, set.range_comp, span_image (inl R M M'), hv.2, map_top, set.range_comp, span_image (inr R M M'), hv'.2, map_top], exact linear_map.sup_range_inl_inr end end is_basis lemma is_basis_singleton_one (R : Type*) [unique ι] [ring R] : is_basis R (λ (_ : ι), (1 : R)) := begin split, { refine linear_independent_iff.2 (λ l, _), rw [finsupp.unique_single l, finsupp.total_single, smul_eq_mul, mul_one], intro hi, simp [hi] }, { refine top_unique (λ _ _, _), simp only [mem_span_singleton, range_const, mul_one, exists_eq, smul_eq_mul] } end protected lemma linear_equiv.is_basis (hs : is_basis R v) (f : M ≃ₗ[R] M') : is_basis R (f ∘ v) := begin split, { apply @linear_independent.image _ _ _ _ _ _ _ _ _ _ hs.1 (f : M →ₗ[R] M'), simp [linear_equiv.ker f] }, { rw set.range_comp, have : span R ((f : M →ₗ[R] M') '' range v) = ⊤, { rw [span_image (f : M →ₗ[R] M'), hs.2], simp }, exact this } end lemma is_basis_span (hs : linear_independent R v) : @is_basis ι R (span R (range v)) (λ i : ι, ⟨v i, subset_span (mem_range_self _)⟩) _ _ _ := begin split, { apply linear_independent_span hs }, { rw eq_top_iff', intro x, have h₁ : subtype.val '' set.range (λ i, subtype.mk (v i) _) = range v, by rw ←set.range_comp, have h₂ : map (submodule.subtype _) (span R (set.range (λ i, subtype.mk (v i) _))) = span R (range v), by rw [←span_image, submodule.subtype_eq_val, h₁], have h₃ : (x : M) ∈ map (submodule.subtype _) (span R (set.range (λ i, subtype.mk (v i) _))), by rw h₂; apply subtype.mem x, rcases mem_map.1 h₃ with ⟨y, hy₁, hy₂⟩, have h_x_eq_y : x = y, by rw [subtype.ext_iff, ← hy₂]; simp, rw h_x_eq_y, exact hy₁ } end lemma is_basis_empty (h_empty : ¬ nonempty ι) (h : ∀x:M, x = 0) : is_basis R (λ x : ι, (0 : M)) := ⟨ linear_independent_empty_type h_empty, eq_top_iff'.2 $ assume x, (h x).symm ▸ submodule.zero_mem _ ⟩ lemma is_basis_empty_bot (h_empty : ¬ nonempty ι) : is_basis R (λ _ : ι, (0 : (⊥ : submodule R M))) := begin apply is_basis_empty h_empty, intro x, apply subtype.ext_iff_val.2, exact (submodule.mem_bot R).1 (subtype.mem x), end open fintype variables [fintype ι] (h : is_basis R v) /-- A module over `R` with a finite basis is linearly equivalent to functions from its basis to `R`. -/ def is_basis.equiv_fun : M ≃ₗ[R] (ι → R) := linear_equiv.trans (module_equiv_finsupp h) { to_fun := finsupp.to_fun, map_add' := λ x y, by ext; exact finsupp.add_apply, map_smul' := λ x y, by ext; exact finsupp.smul_apply, ..finsupp.equiv_fun_on_fintype } /-- A module over a finite ring that admits a finite basis is finite. -/ def module.fintype_of_fintype [fintype R] : fintype M := fintype.of_equiv _ h.equiv_fun.to_equiv.symm theorem module.card_fintype [fintype R] [fintype M] : card M = (card R) ^ (card ι) := calc card M = card (ι → R) : card_congr h.equiv_fun.to_equiv ... = card R ^ card ι : card_fun /-- Given a basis `v` indexed by `ι`, the canonical linear equivalence between `ι → R` and `M` maps a function `x : ι → R` to the linear combination `∑_i x i • v i`. -/ @[simp] lemma is_basis.equiv_fun_symm_apply (x : ι → R) : h.equiv_fun.symm x = ∑ i, x i • v i := begin change finsupp.sum ((finsupp.equiv_fun_on_fintype.symm : (ι → R) ≃ (ι →₀ R)) x) (λ (i : ι) (a : R), a • v i) = ∑ i, x i • v i, dsimp [finsupp.equiv_fun_on_fintype, finsupp.sum], rw finset.sum_filter, refine finset.sum_congr rfl (λi hi, _), by_cases H : x i = 0, { simp [H] }, { simp [H], refl } end lemma is_basis.equiv_fun_apply (u : M) : h.equiv_fun u = h.repr u := rfl lemma is_basis.equiv_fun_total (u : M) : ∑ i, h.equiv_fun u i • v i = u:= begin conv_rhs { rw ← h.total_repr u }, simp [finsupp.total_apply, finsupp.sum_fintype, h.equiv_fun_apply] end @[simp] lemma is_basis.equiv_fun_self (i j : ι) : h.equiv_fun (v i) j = if i = j then 1 else 0 := by { rw [h.equiv_fun_apply, h.repr_self_apply] } end module section vector_space variables {v : ι → V} [field K] [add_comm_group V] [add_comm_group V'] [vector_space K V] [vector_space K V'] {s t : set V} {x y z : V} include K open submodule /- TODO: some of the following proofs can generalized with a zero_ne_one predicate type class (instead of a data containing type class) -/ section lemma mem_span_insert_exchange : x ∈ span K (insert y s) → x ∉ span K s → y ∈ span K (insert x s) := begin simp [mem_span_insert], rintro a z hz rfl h, refine ⟨a⁻¹, -a⁻¹ • z, smul_mem _ _ hz, _⟩, have a0 : a ≠ 0, {rintro rfl, simp * at *}, simp [a0, smul_add, smul_smul] end end lemma linear_independent_iff_not_mem_span : linear_independent K v ↔ (∀i, v i ∉ span K (v '' (univ \ {i}))) := begin apply linear_independent_iff_not_smul_mem_span.trans, split, { intros h i h_in_span, apply one_ne_zero (h i 1 (by simp [h_in_span])) }, { intros h i a ha, by_contradiction ha', exact false.elim (h _ ((smul_mem_iff _ ha').1 ha)) } end lemma linear_independent_unique [unique ι] (h : v (default ι) ≠ 0): linear_independent K v := begin rw linear_independent_iff, intros l hl, ext i, rw [unique.eq_default i, finsupp.zero_apply], by_contra hc, have := smul_smul (l (default ι))⁻¹ (l (default ι)) (v (default ι)), rw [finsupp.unique_single l, finsupp.total_single] at hl, rw [hl, inv_mul_cancel hc, smul_zero, one_smul] at this, exact h this.symm end lemma linear_independent_singleton {x : V} (hx : x ≠ 0) : linear_independent K (λ x, x : ({x} : set V) → V) := begin apply @linear_independent_unique _ _ _ _ _ _ _ _ _, apply set.unique_singleton, apply hx, end lemma disjoint_span_singleton {p : submodule K V} {x : V} (x0 : x ≠ 0) : disjoint p (span K {x}) ↔ x ∉ p := ⟨λ H xp, x0 (disjoint_def.1 H _ xp (singleton_subset_iff.1 subset_span:_)), begin simp [disjoint_def, mem_span_singleton], rintro xp y yp a rfl, by_cases a0 : a = 0, {simp [a0]}, exact xp.elim ((smul_mem_iff p a0).1 yp), end⟩ lemma linear_independent.insert (hs : linear_independent K (λ b, b : s → V)) (hx : x ∉ span K s) : linear_independent K (λ b, b : insert x s → V) := begin rw ← union_singleton, have x0 : x ≠ 0 := mt (by rintro rfl; apply zero_mem _) hx, apply hs.union (linear_independent_singleton x0), rwa [disjoint_span_singleton x0] end lemma exists_linear_independent (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ t) : ∃b⊆t, s ⊆ b ∧ t ⊆ span K b ∧ linear_independent K (λ x, x : b → V) := begin rcases zorn.zorn_subset₀ {b | b ⊆ t ∧ linear_independent K (λ x, x : b → V)} _ _ ⟨hst, hs⟩ with ⟨b, ⟨bt, bi⟩, sb, h⟩, { refine ⟨b, bt, sb, λ x xt, _, bi⟩, by_contra hn, apply hn, rw ← h _ ⟨insert_subset.2 ⟨xt, bt⟩, bi.insert hn⟩ (subset_insert _ _), exact subset_span (mem_insert _ _) }, { refine λ c hc cc c0, ⟨⋃₀ c, ⟨_, _⟩, λ x, _⟩, { exact sUnion_subset (λ x xc, (hc xc).1) }, { exact linear_independent_sUnion_of_directed cc.directed_on (λ x xc, (hc xc).2) }, { exact subset_sUnion_of_mem } } end lemma exists_subset_is_basis (hs : linear_independent K (λ x, x : s → V)) : ∃b, s ⊆ b ∧ is_basis K (coe : b → V) := let ⟨b, hb₀, hx, hb₂, hb₃⟩ := exists_linear_independent hs (@subset_univ _ _) in ⟨ b, hx, @linear_independent.restrict_of_comp_subtype _ _ _ id _ _ _ _ hb₃, by simp; exact eq_top_iff.2 hb₂⟩ lemma exists_sum_is_basis (hs : linear_independent K v) : ∃ (ι' : Type u) (v' : ι' → V), is_basis K (sum.elim v v') := begin -- This is a hack: we jump through hoops to reuse `exists_subset_is_basis`. let s := set.range v, let e : ι ≃ s := equiv.set.range v hs.injective, have : (λ x, x : s → V) = v ∘ e.symm := by { funext, dsimp, rw [equiv.set.apply_range_symm v], }, have : linear_independent K (λ x, x : s → V), { rw this, exact linear_independent.comp hs _ (e.symm.injective), }, obtain ⟨b, ss, is⟩ := exists_subset_is_basis this, let e' : ι ⊕ (b \ s : set V) ≃ b := calc ι ⊕ (b \ s : set V) ≃ s ⊕ (b \ s : set V) : equiv.sum_congr e (equiv.refl _) ... ≃ b : equiv.set.sum_diff_subset ss, refine ⟨(b \ s : set V), λ x, x.1, _⟩, convert is_basis.comp is e' _, { funext x, cases x; simp; refl, }, { exact e'.bijective, }, end variables (K V) lemma exists_is_basis : ∃b : set V, is_basis K (λ i, i : b → V) := let ⟨b, _, hb⟩ := exists_subset_is_basis (linear_independent_empty K V : _) in ⟨b, hb⟩ variables {K V} -- TODO(Mario): rewrite? lemma exists_of_linear_independent_of_finite_span {t : finset V} (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ (span K ↑t : submodule K V)) : ∃t':finset V, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = t.card := have ∀t, ∀(s' : finset V), ↑s' ⊆ s → s ∩ ↑t = ∅ → s ⊆ (span K ↑(s' ∪ t) : submodule K V) → ∃t':finset V, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = (s' ∪ t).card := assume t, finset.induction_on t (assume s' hs' _ hss', have s = ↑s', from eq_of_linear_independent_of_span_subtype hs hs' $ by simpa using hss', ⟨s', by simp [this]⟩) (assume b₁ t hb₁t ih s' hs' hst hss', have hb₁s : b₁ ∉ s, from assume h, have b₁ ∈ s ∩ ↑(insert b₁ t), from ⟨h, finset.mem_insert_self _ _⟩, by rwa [hst] at this, have hb₁s' : b₁ ∉ s', from assume h, hb₁s $ hs' h, have hst : s ∩ ↑t = ∅, from eq_empty_of_subset_empty $ subset.trans (by simp [inter_subset_inter, subset.refl]) (le_of_eq hst), classical.by_cases (assume : s ⊆ (span K ↑(s' ∪ t) : submodule K V), let ⟨u, hust, hsu, eq⟩ := ih _ hs' hst this in have hb₁u : b₁ ∉ u, from assume h, (hust h).elim hb₁s hb₁t, ⟨insert b₁ u, by simp [insert_subset_insert hust], subset.trans hsu (by simp), by simp [eq, hb₁t, hb₁s', hb₁u]⟩) (assume : ¬ s ⊆ (span K ↑(s' ∪ t) : submodule K V), let ⟨b₂, hb₂s, hb₂t⟩ := not_subset.mp this in have hb₂t' : b₂ ∉ s' ∪ t, from assume h, hb₂t $ subset_span h, have s ⊆ (span K ↑(insert b₂ s' ∪ t) : submodule K V), from assume b₃ hb₃, have ↑(s' ∪ insert b₁ t) ⊆ insert b₁ (insert b₂ ↑(s' ∪ t) : set V), by simp [insert_eq, -singleton_union, -union_singleton, union_subset_union, subset.refl, subset_union_right], have hb₃ : b₃ ∈ span K (insert b₁ (insert b₂ ↑(s' ∪ t) : set V)), from span_mono this (hss' hb₃), have s ⊆ (span K (insert b₁ ↑(s' ∪ t)) : submodule K V), by simpa [insert_eq, -singleton_union, -union_singleton] using hss', have hb₁ : b₁ ∈ span K (insert b₂ ↑(s' ∪ t)), from mem_span_insert_exchange (this hb₂s) hb₂t, by rw [span_insert_eq_span hb₁] at hb₃; simpa using hb₃, let ⟨u, hust, hsu, eq⟩ := ih _ (by simp [insert_subset, hb₂s, hs']) hst this in ⟨u, subset.trans hust $ union_subset_union (subset.refl _) (by simp [subset_insert]), hsu, by simp [eq, hb₂t', hb₁t, hb₁s']⟩)), begin have eq : t.filter (λx, x ∈ s) ∪ t.filter (λx, x ∉ s) = t, { ext1 x, by_cases x ∈ s; simp * }, apply exists.elim (this (t.filter (λx, x ∉ s)) (t.filter (λx, x ∈ s)) (by simp [set.subset_def]) (by simp [set.ext_iff] {contextual := tt}) (by rwa [eq])), intros u h, exact ⟨u, subset.trans h.1 (by simp [subset_def, and_imp, or_imp_distrib] {contextual:=tt}), h.2.1, by simp only [h.2.2, eq]⟩ end lemma exists_finite_card_le_of_finite_of_linear_independent_of_span (ht : finite t) (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ span K t) : ∃h : finite s, h.to_finset.card ≤ ht.to_finset.card := have s ⊆ (span K ↑(ht.to_finset) : submodule K V), by simp; assumption, let ⟨u, hust, hsu, eq⟩ := exists_of_linear_independent_of_finite_span hs this in have finite s, from u.finite_to_set.subset hsu, ⟨this, by rw [←eq]; exact (finset.card_le_of_subset $ finset.coe_subset.mp $ by simp [hsu])⟩ lemma linear_map.exists_left_inverse_of_injective (f : V →ₗ[K] V') (hf_inj : f.ker = ⊥) : ∃g:V' →ₗ V, g.comp f = linear_map.id := begin rcases exists_is_basis K V with ⟨B, hB⟩, have hB₀ : _ := hB.1.to_subtype_range, have : linear_independent K (λ x, x : f '' B → V'), { have h₁ := hB₀.image_subtype (show disjoint (span K (range (λ i : B, i.val))) (linear_map.ker f), by simp [hf_inj]), rwa subtype.range_coe at h₁ }, rcases exists_subset_is_basis this with ⟨C, BC, hC⟩, haveI : inhabited V := ⟨0⟩, use hC.constr (C.restrict (inv_fun f)), refine hB.ext (λ b, _), rw image_subset_iff at BC, have : f b = (⟨f b, BC b.2⟩ : C) := rfl, dsimp, rw [this, constr_basis hC], exact left_inverse_inv_fun (linear_map.ker_eq_bot.1 hf_inj) _ end lemma submodule.exists_is_compl (p : submodule K V) : ∃ q : submodule K V, is_compl p q := let ⟨f, hf⟩ := p.subtype.exists_left_inverse_of_injective p.ker_subtype in ⟨f.ker, linear_map.is_compl_of_proj $ linear_map.ext_iff.1 hf⟩ lemma linear_map.exists_right_inverse_of_surjective (f : V →ₗ[K] V') (hf_surj : f.range = ⊤) : ∃g:V' →ₗ V, f.comp g = linear_map.id := begin rcases exists_is_basis K V' with ⟨C, hC⟩, haveI : inhabited V := ⟨0⟩, use hC.constr (C.restrict (inv_fun f)), refine hC.ext (λ c, _), simp [constr_basis hC, right_inverse_inv_fun (linear_map.range_eq_top.1 hf_surj) c] end open submodule linear_map theorem quotient_prod_linear_equiv (p : submodule K V) : nonempty ((p.quotient × p) ≃ₗ[K] V) := let ⟨q, hq⟩ := p.exists_is_compl in nonempty.intro $ ((quotient_equiv_of_is_compl p q hq).prod (linear_equiv.refl _ _)).trans (prod_equiv_of_is_compl q p hq.symm) open fintype variables (K) (V) theorem vector_space.card_fintype [fintype K] [fintype V] : ∃ n : ℕ, card V = (card K) ^ n := exists.elim (exists_is_basis K V) $ λ b hb, ⟨card b, module.card_fintype hb⟩ end vector_space namespace pi open set linear_map section module variables {η : Type*} {ιs : η → Type*} {Ms : η → Type*} variables [ring R] [∀i, add_comm_group (Ms i)] [∀i, module R (Ms i)] lemma linear_independent_std_basis (v : Πj, ιs j → (Ms j)) (hs : ∀i, linear_independent R (v i)) : linear_independent R (λ (ji : Σ j, ιs j), std_basis R Ms ji.1 (v ji.1 ji.2)) := begin have hs' : ∀j : η, linear_independent R (λ i : ιs j, std_basis R Ms j (v j i)), { intro j, apply linear_independent.image (hs j), simp [ker_std_basis] }, apply linear_independent_Union_finite hs', { assume j J _ hiJ, simp [(set.Union.equations._eqn_1 _).symm, submodule.span_image, submodule.span_Union], have h₀ : ∀ j, span R (range (λ (i : ιs j), std_basis R Ms j (v j i))) ≤ range (std_basis R Ms j), { intro j, rw [span_le, linear_map.range_coe], apply range_comp_subset_range }, have h₁ : span R (range (λ (i : ιs j), std_basis R Ms j (v j i))) ≤ ⨆ i ∈ {j}, range (std_basis R Ms i), { rw @supr_singleton _ _ _ (λ i, linear_map.range (std_basis R (λ (j : η), Ms j) i)), apply h₀ }, have h₂ : (⨆ j ∈ J, span R (range (λ (i : ιs j), std_basis R Ms j (v j i)))) ≤ ⨆ j ∈ J, range (std_basis R (λ (j : η), Ms j) j) := supr_le_supr (λ i, supr_le_supr (λ H, h₀ i)), have h₃ : disjoint (λ (i : η), i ∈ {j}) J, { convert set.disjoint_singleton_left.2 hiJ, rw ←@set_of_mem_eq _ {j}, refl }, exact (disjoint_std_basis_std_basis _ _ _ _ h₃).mono h₁ h₂ } end variable [fintype η] lemma is_basis_std_basis (s : Πj, ιs j → (Ms j)) (hs : ∀j, is_basis R (s j)) : is_basis R (λ (ji : Σ j, ιs j), std_basis R Ms ji.1 (s ji.1 ji.2)) := begin split, { apply linear_independent_std_basis _ (assume i, (hs i).1) }, have h₁ : Union (λ j, set.range (std_basis R Ms j ∘ s j)) ⊆ range (λ (ji : Σ (j : η), ιs j), (std_basis R Ms (ji.fst)) (s (ji.fst) (ji.snd))), { apply Union_subset, intro i, apply range_comp_subset_range (λ x : ιs i, (⟨i, x⟩ : Σ (j : η), ιs j)) (λ (ji : Σ (j : η), ιs j), std_basis R Ms (ji.fst) (s (ji.fst) (ji.snd))) }, have h₂ : ∀ i, span R (range (std_basis R Ms i ∘ s i)) = range (std_basis R Ms i), { intro i, rw [set.range_comp, submodule.span_image, (assume i, (hs i).2), submodule.map_top] }, apply eq_top_mono, apply span_mono h₁, rw span_Union, simp only [h₂], apply supr_range_std_basis end section variables (R η) lemma is_basis_fun₀ : is_basis R (λ (ji : Σ (j : η), unit), (std_basis R (λ (i : η), R) (ji.fst)) 1) := @is_basis_std_basis R η (λi:η, unit) (λi:η, R) _ _ _ _ (λ _ _, (1 : R)) (assume i, @is_basis_singleton_one _ _ _ _) lemma is_basis_fun : is_basis R (λ i, std_basis R (λi:η, R) i 1) := begin apply (is_basis_fun₀ R η).comp (λ i, ⟨i, punit.star⟩), apply bijective_iff_has_inverse.2, use sigma.fst, simp [function.left_inverse, function.right_inverse] end end end module end pi
56cec46abe46b16b8bef17e6791eb4adfc8ab0cc
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Parser/Extra.lean
d0dd0a35abec92e34ed74476d1ecd9de8113af2c
[ "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
7,398
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.Extension -- necessary for auto-generation import Lean.PrettyPrinter.Parenthesizer import Lean.PrettyPrinter.Formatter namespace Lean namespace Parser -- synthesize pretty printers for parsers declared prior to `Lean.PrettyPrinter` -- (because `Parser.Extension` depends on them) attribute [runBuiltinParserAttributeHooks] leadingNode termParser commandParser mkAntiquot nodeWithAntiquot sepBy sepBy1 unicodeSymbol nonReservedSymbol @[runBuiltinParserAttributeHooks] def optional (p : Parser) : Parser := optionalNoAntiquot (withAntiquotSpliceAndSuffix `optional p (symbol "?")) @[runBuiltinParserAttributeHooks] def many (p : Parser) : Parser := manyNoAntiquot (withAntiquotSpliceAndSuffix `many p (symbol "*")) @[runBuiltinParserAttributeHooks] def many1 (p : Parser) : Parser := many1NoAntiquot (withAntiquotSpliceAndSuffix `many p (symbol "*")) @[runBuiltinParserAttributeHooks] def ident : Parser := withAntiquot (mkAntiquot "ident" identKind) identNoAntiquot -- `ident` and `rawIdent` produce the same syntax tree, so we reuse the antiquotation kind name @[runBuiltinParserAttributeHooks] def rawIdent : Parser := withAntiquot (mkAntiquot "ident" identKind) rawIdentNoAntiquot @[runBuiltinParserAttributeHooks] def numLit : Parser := withAntiquot (mkAntiquot "numLit" numLitKind) numLitNoAntiquot @[runBuiltinParserAttributeHooks] def scientificLit : Parser := withAntiquot (mkAntiquot "scientificLit" scientificLitKind) scientificLitNoAntiquot @[runBuiltinParserAttributeHooks] def strLit : Parser := withAntiquot (mkAntiquot "strLit" strLitKind) strLitNoAntiquot @[runBuiltinParserAttributeHooks] def charLit : Parser := withAntiquot (mkAntiquot "charLit" charLitKind) charLitNoAntiquot @[runBuiltinParserAttributeHooks] def nameLit : Parser := withAntiquot (mkAntiquot "nameLit" nameLitKind) nameLitNoAntiquot @[runBuiltinParserAttributeHooks, inline] def group (p : Parser) : Parser := node groupKind p @[runBuiltinParserAttributeHooks, inline] def many1Indent (p : Parser) : Parser := withPosition $ many1 (checkColGe "irrelevant" >> p) @[runBuiltinParserAttributeHooks, inline] def manyIndent (p : Parser) : Parser := withPosition $ many (checkColGe "irrelevant" >> p) @[runBuiltinParserAttributeHooks] abbrev notSymbol (s : String) : Parser := notFollowedBy (symbol s) s /-- No-op parser that advises the pretty printer to emit a non-breaking space. -/ @[inline] def ppHardSpace : Parser := skip /-- No-op parser that advises the pretty printer to emit a space/soft line break. -/ @[inline] def ppSpace : Parser := skip /-- No-op parser that advises the pretty printer to emit a hard line break. -/ @[inline] def ppLine : Parser := skip /-- No-op parser combinator that advises the pretty printer to emit a `Format.fill` node. -/ @[inline] def ppRealFill : Parser → Parser := id /-- No-op parser combinator that advises the pretty printer to emit a `Format.group` node. -/ @[inline] def ppRealGroup : Parser → Parser := id /-- No-op parser combinator that advises the pretty printer to indent the given syntax without grouping it. -/ @[inline] def ppIndent : Parser → Parser := id /-- No-op parser combinator that advises the pretty printer to group and indent the given syntax. By default, only syntax categories are grouped. -/ @[inline] def ppGroup (p : Parser) : Parser := ppRealFill (ppIndent p) /-- No-op parser combinator that advises the pretty printer to dedent the given syntax. Dedenting can in particular be used to counteract automatic indentation. -/ @[inline] def ppDedent : Parser → Parser := id /-- No-op parser combinator that allows the pretty printer to omit the group and indent operation in the enclosing category parser. ``` syntax ppAllowUngrouped "by " tacticSeq : term -- allows a `by` after `:=` without linebreak in between: theorem foo : True := by trivial ``` -/ @[inline] def ppAllowUngrouped : Parser := skip /-- No-op parser combinator that advises the pretty printer to dedent the given syntax, if it was grouped by the category parser. Dedenting can in particular be used to counteract automatic indentation. -/ @[inline] def ppDedentIfGrouped : Parser → Parser := id /-- No-op parser combinator that prints a line break. The line break is soft if the combinator is followed by an ungrouped parser (see ppAllowUngrouped), otherwise hard. -/ @[inline] def ppHardLineUnlessUngrouped : Parser := skip end Parser section open PrettyPrinter @[combinatorFormatter Lean.Parser.ppHardSpace] def ppHardSpace.formatter : Formatter := Formatter.pushWhitespace " " @[combinatorFormatter Lean.Parser.ppSpace] def ppSpace.formatter : Formatter := Formatter.pushLine @[combinatorFormatter Lean.Parser.ppLine] def ppLine.formatter : Formatter := Formatter.pushWhitespace "\n" @[combinatorFormatter Lean.Parser.ppRealFill] def ppRealFill.formatter (p : Formatter) : Formatter := Formatter.fill p @[combinatorFormatter Lean.Parser.ppRealGroup] def ppRealGroup.formatter (p : Formatter) : Formatter := Formatter.group p @[combinatorFormatter Lean.Parser.ppIndent] def ppIndent.formatter (p : Formatter) : Formatter := Formatter.indent p @[combinatorFormatter Lean.Parser.ppDedent] def ppDedent.formatter (p : Formatter) : Formatter := do let opts ← getOptions Formatter.indent p (some ((0:Int) - Std.Format.getIndent opts)) @[combinatorFormatter Lean.Parser.ppAllowUngrouped] def ppAllowUngrouped.formatter : Formatter := do modify ({ · with mustBeGrouped := false }) @[combinatorFormatter Lean.Parser.ppDedentIfGrouped] def ppDedentIfGrouped.formatter (p : Formatter) : Formatter := do Formatter.concat p let indent := Std.Format.getIndent (← getOptions) unless (← get).isUngrouped do modify fun st => { st with stack := st.stack.modify (st.stack.size - 1) (·.nest (0 - indent)) } @[combinatorFormatter Lean.Parser.ppHardLineUnlessUngrouped] def ppHardLineUnlessUngrouped.formatter : Formatter := do if (← get).isUngrouped then Formatter.pushLine else ppLine.formatter end namespace Parser -- now synthesize parenthesizers attribute [runBuiltinParserAttributeHooks] ppHardSpace ppSpace ppLine ppGroup ppRealGroup ppRealFill ppIndent ppDedent ppAllowUngrouped ppDedentIfGrouped ppHardLineUnlessUngrouped macro "register_parser_alias" aliasName?:optional(strLit) declName:ident : term => let aliasName := aliasName?.getD (Syntax.mkStrLit declName.getId.toString) `(do Parser.registerAlias $aliasName $declName PrettyPrinter.Formatter.registerAlias $aliasName $(mkIdentFrom declName (declName.getId ++ `formatter)) PrettyPrinter.Parenthesizer.registerAlias $aliasName $(mkIdentFrom declName (declName.getId ++ `parenthesizer))) builtin_initialize register_parser_alias group register_parser_alias ppHardSpace register_parser_alias ppSpace register_parser_alias ppLine register_parser_alias ppGroup register_parser_alias ppRealGroup register_parser_alias ppRealFill register_parser_alias ppIndent register_parser_alias ppDedent register_parser_alias ppAllowUngrouped register_parser_alias ppDedentIfGrouped register_parser_alias ppHardLineUnlessUngrouped end Parser end Lean
8de7304966d4823620419bf58bd165964acf74a1
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/int/cast/defs.lean
5dedeb0a57e154f1fa9ab16e8a51db256588436d
[ "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,102
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Gabriel Ebner -/ import data.nat.cast.defs /-! # Cast of integers This file defines the *canonical* homomorphism from the integers into an additive group with a one (typically a `ring`). In additive groups with a one element, there exists a unique such homomorphism and we store it in the `int_cast : ℤ → R` field. Preferentially, the homomorphism is written as a coercion. ## Main declarations * `int.cast`: Canonical homomorphism `ℤ → R`. * `add_group_with_one`: Type class for `int.cast`. -/ universes u set_option old_structure_cmd true attribute [simp] int.of_nat_eq_coe /-- Default value for `add_group_with_one.int_cast`. -/ protected def int.cast_def {R : Type u} [has_nat_cast R] [has_neg R] : ℤ → R | (n : ℕ) := n | -[1+ n] := -(n+1 : ℕ) /-- Type class for the canonical homomorphism `ℤ → R`. -/ class has_int_cast (R : Type u) := (int_cast : ℤ → R) /-- An `add_group_with_one` is an `add_group` with a `1`. It also contains data for the unique homomorphisms `ℕ → R` and `ℤ → R`. -/ @[protect_proj] class add_group_with_one (R : Type u) extends has_int_cast R, add_group R, add_monoid_with_one R := (int_cast := int.cast_def) (int_cast_of_nat : ∀ n : ℕ, int_cast n = (n : R) . control_laws_tac) (int_cast_neg_succ_of_nat : ∀ n : ℕ, int_cast (-(n+1 : ℕ)) = -((n+1 : ℕ) : R) . control_laws_tac) /-- An `add_comm_group_with_one` is an `add_group_with_one` satisfying `a + b = b + a`. -/ @[protect_proj] class add_comm_group_with_one (R : Type u) extends add_comm_group R, add_group_with_one R /-- Canonical homomorphism from the integers to any ring(-like) structure `R` -/ protected def int.cast {R : Type u} [has_int_cast R] (i : ℤ) : R := has_int_cast.int_cast i namespace nat variables {R : Type u} [add_group_with_one R] @[simp, norm_cast] theorem cast_sub {m n} (h : m ≤ n) : ((n - m : ℕ) : R) = n - m := eq_sub_of_add_eq $ by rw [← cast_add, nat.sub_add_cancel h] @[simp, norm_cast] theorem cast_pred : ∀ {n}, 0 < n → ((n - 1 : ℕ) : R) = n - 1 | 0 h := by cases h | (n+1) h := by rw [cast_succ, add_sub_cancel]; refl end nat open nat namespace int variables {R : Type u} [add_group_with_one R] -- see Note [coercion into rings] @[priority 900] instance cast_coe {R} [has_int_cast R] : has_coe_t ℤ R := ⟨int.cast⟩ theorem cast_of_nat (n : ℕ) : (of_nat n : R) = n := add_group_with_one.int_cast_of_nat n @[simp] theorem cast_neg_succ_of_nat (n : ℕ) : (-[1+ n] : R) = -(n + 1 : ℕ) := add_group_with_one.int_cast_neg_succ_of_nat n @[simp, norm_cast] theorem cast_zero : ((0 : ℤ) : R) = 0 := (cast_of_nat 0).trans nat.cast_zero @[simp, norm_cast] theorem cast_coe_nat (n : ℕ) : ((n : ℤ) : R) = n := cast_of_nat _ @[simp, norm_cast] theorem cast_one : ((1 : ℤ) : R) = 1 := show (((1 : ℕ) : ℤ) : R) = 1, by simp @[simp, norm_cast] theorem cast_neg : ∀ n, ((-n : ℤ) : R) = -n | (0 : ℕ) := by erw [cast_zero, neg_zero] | (n + 1 : ℕ) := by erw [cast_of_nat, cast_neg_succ_of_nat]; refl | -[1+ n] := by erw [cast_of_nat, cast_neg_succ_of_nat, neg_neg] @[simp] theorem cast_sub_nat_nat (m n) : ((int.sub_nat_nat m n : ℤ) : R) = m - n := begin unfold sub_nat_nat, cases e : n - m, { simp only [sub_nat_nat, cast_of_nat], simp [e, nat.le_of_sub_eq_zero e] }, { rw [sub_nat_nat, cast_neg_succ_of_nat, nat.add_one, ← e, nat.cast_sub $ _root_.le_of_lt $ nat.lt_of_sub_eq_succ e, neg_sub] }, end lemma neg_of_nat_eq (n : ℕ) : neg_of_nat n = -(n : ℤ) := by cases n; refl @[simp] theorem cast_neg_of_nat (n : ℕ) : ((neg_of_nat n : ℤ) : R) = -n := by simp [neg_of_nat_eq] @[simp, norm_cast] theorem cast_add : ∀ m n, ((m + n : ℤ) : R) = m + n | (m : ℕ) (n : ℕ) := by simp [← int.coe_nat_add] | (m : ℕ) -[1+ n] := by erw [cast_sub_nat_nat, cast_coe_nat, cast_neg_succ_of_nat, sub_eq_add_neg] | -[1+ m] (n : ℕ) := by erw [cast_sub_nat_nat, cast_coe_nat, cast_neg_succ_of_nat, sub_eq_iff_eq_add, add_assoc, eq_neg_add_iff_add_eq, ← nat.cast_add, ← nat.cast_add, nat.add_comm] | -[1+ m] -[1+ n] := show (-[1+ m + n + 1] : R) = _, by rw [cast_neg_succ_of_nat, cast_neg_succ_of_nat, cast_neg_succ_of_nat, ← neg_add_rev, ← nat.cast_add, nat.add_right_comm m n 1, nat.add_assoc, nat.add_comm] @[simp, norm_cast] theorem cast_sub (m n) : ((m - n : ℤ) : R) = m - n := by simp [int.sub_eq_add_neg, sub_eq_add_neg] @[simp, norm_cast] theorem coe_nat_bit0 (n : ℕ) : (↑(bit0 n) : ℤ) = bit0 ↑n := rfl @[simp, norm_cast] theorem coe_nat_bit1 (n : ℕ) : (↑(bit1 n) : ℤ) = bit1 ↑n := rfl @[simp, norm_cast] theorem cast_bit0 (n : ℤ) : ((bit0 n : ℤ) : R) = bit0 n := cast_add _ _ @[simp, norm_cast] theorem cast_bit1 (n : ℤ) : ((bit1 n : ℤ) : R) = bit1 n := by rw [bit1, cast_add, cast_one, cast_bit0]; refl lemma cast_two : ((2 : ℤ) : R) = 2 := by simp lemma cast_three : ((3 : ℤ) : R) = 3 := by simp lemma cast_four : ((4 : ℤ) : R) = 4 := by simp end int
7f4e1f05349ca6bc22490e14e2b9305166dfa360
41ebf3cb010344adfa84907b3304db00e02db0a6
/uexp/src/uexp/rules/aggregateProjectMerge.lean
f2b442155e11d8e07c813ddc2bc6a84aa6370bfb
[ "BSD-2-Clause" ]
permissive
ReinierKoops/Cosette
e061b2ba58b26f4eddf4cd052dcf7abd16dfe8fb
eb8dadd06ee05fe7b6b99de431dd7c4faef5cb29
refs/heads/master
1,686,483,953,198
1,624,293,498,000
1,624,293,498,000
378,997,885
0
0
BSD-2-Clause
1,624,293,485,000
1,624,293,484,000
null
UTF-8
Lean
false
false
1,616
lean
import ..extra_constants import ..sql import ..u_semiring import ..tactics import ..meta.cosette_tactics open SQL open Proj open Pred open Expr theorem rule : forall (Γ scm_emp : Schema) (rel_emp : relation scm_emp) (emp_empno : Column datatypes.int scm_emp) (emp_ename : Column datatypes.int scm_emp) (emp_job : Column datatypes.int scm_emp) (emp_mgr : Column datatypes.int scm_emp) (emp_hiredate : Column datatypes.int scm_emp) (emp_comm : Column datatypes.int scm_emp) (emp_sal : Column datatypes.int scm_emp) (emp_deptno : Column datatypes.int scm_emp) (emp_slacker : Column datatypes.int scm_emp), denoteSQL (SELECT (combineGroupByProj PLAIN(uvariable (right⋅emp_deptno)) (combineGroupByProj SUM(uvariable (right⋅emp_sal)) PLAIN(uvariable (right⋅emp_empno)))) FROM1 table rel_emp GROUP BY combine (right⋅emp_deptno) (right⋅emp_empno) : SQL Γ _) = denoteSQL (SELECT (combineGroupByProj PLAIN(uvariable (right⋅emp_deptno)) (combineGroupByProj SUM(uvariable (right⋅emp_sal)) PLAIN(uvariable (right⋅emp_empno)))) FROM1 table rel_emp GROUP BY combine (right⋅emp_empno) (right⋅emp_deptno) : SQL Γ _) := begin intros, unfold_all_denotations, funext, simp, print_size, sorry end
6c6e91f1e35caf60b23f70b197c61e800808f1c7
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/real/ereal.lean
3d989b14c8591959547febb0a9f85ca173ee770e
[ "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
19,202
lean
/- Copyright (c) 2019 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard -/ import data.real.basic import data.real.ennreal /-! # The extended reals [-∞, ∞]. This file defines `ereal`, the real numbers together with a top and bottom element, referred to as ⊤ and ⊥. It is implemented as `with_top (with_bot ℝ)` Addition and multiplication are problematic in the presence of ±∞, but negation has a natural definition and satisfies the usual properties. An ad hoc addition is defined, for which `ereal` is an `add_comm_monoid`, and even an ordered one (if `a ≤ a'` and `b ≤ b'` then `a + b ≤ a' + b'`). Note however that addition is badly behaved at `(⊥, ⊤)` and `(⊤, ⊥)` so this can not be upgraded to a group structure. Our choice is that `⊥ + ⊤ = ⊤ + ⊥ = ⊤`. An ad hoc subtraction is then defined by `x - y = x + (-y)`. It does not have nice properties, but it is sometimes convenient to have. An ad hoc multiplication is defined, for which `ereal` is a `comm_monoid_with_zero`. This does not distribute with addition, as `⊤ = ⊤ - ⊥ = 1*⊤ - 1*⊤ ≠ (1 - 1) * ⊤ = 0 * ⊤ = 0`. `ereal` is a `complete_linear_order`; this is deduced by type class inference from the fact that `with_top (with_bot L)` is a complete linear order if `L` is a conditionally complete linear order. Coercions from `ℝ` and from `ℝ≥0∞` are registered, and their basic properties are proved. The main one is the real coercion, and is usually referred to just as `coe` (lemmas such as `ereal.coe_add` deal with this coercion). The one from `ennreal` is usually called `coe_ennreal` in the `ereal` namespace. ## Tags real, ereal, complete lattice ## TODO abs : ereal → ℝ≥0∞ In Isabelle they define + - * and / (making junk choices for things like -∞ + ∞) and then prove whatever bits of the ordered ring/field axioms still hold. They also do some limits stuff (liminf/limsup etc). See https://isabelle.in.tum.de/dist/library/HOL/HOL-Library/Extended_Real.html -/ open_locale ennreal nnreal /-- ereal : The type `[-∞, ∞]` -/ @[derive [has_top, comm_monoid_with_zero, has_Sup, has_Inf, complete_linear_order, linear_ordered_add_comm_monoid_with_top]] def ereal := with_top (with_bot ℝ) /-- The canonical inclusion froms reals to ereals. Do not use directly: as this is registered as a coercion, use the coercion instead. -/ def real.to_ereal : ℝ → ereal := some ∘ some namespace ereal -- TODO: Provide explicitly, otherwise it is inferred noncomputably from `complete_linear_order` instance : has_bot ereal := ⟨some ⊥⟩ @[simp] lemma bot_lt_top : (⊥ : ereal) < ⊤ := with_top.coe_lt_top _ @[simp] lemma bot_ne_top : (⊥ : ereal) ≠ ⊤ := bot_lt_top.ne instance : has_coe ℝ ereal := ⟨real.to_ereal⟩ @[simp, norm_cast] protected lemma coe_le_coe_iff {x y : ℝ} : (x : ereal) ≤ (y : ereal) ↔ x ≤ y := by { unfold_coes, simp [real.to_ereal] } @[simp, norm_cast] protected lemma coe_lt_coe_iff {x y : ℝ} : (x : ereal) < (y : ereal) ↔ x < y := by { unfold_coes, simp [real.to_ereal] } @[simp, norm_cast] protected lemma coe_eq_coe_iff {x y : ℝ} : (x : ereal) = (y : ereal) ↔ x = y := by { unfold_coes, simp [real.to_ereal, option.some_inj] } /-- The canonical map from nonnegative extended reals to extended reals -/ def _root_.ennreal.to_ereal : ℝ≥0∞ → ereal | ⊤ := ⊤ | (some x) := x.1 instance has_coe_ennreal : has_coe ℝ≥0∞ ereal := ⟨ennreal.to_ereal⟩ instance : has_zero ereal := ⟨(0 : ℝ)⟩ instance : inhabited ereal := ⟨0⟩ /-- A recursor for `ereal` in terms of the coercion. A typical invocation looks like `induction x using ereal.rec`. Note that using `induction` directly will unfold `ereal` to `option` which is undesirable. When working in term mode, note that pattern matching can be used directly. -/ @[elab_as_eliminator] protected def rec {C : ereal → Sort*} (h_bot : C ⊥) (h_real : Π a : ℝ, C a) (h_top : C ⊤) : ∀ a : ereal, C a | ⊥ := h_bot | (a : ℝ) := h_real a | ⊤ := h_top /-! ### Real coercion -/ instance : can_lift ereal ℝ := { coe := coe, cond := λ r, r ≠ ⊤ ∧ r ≠ ⊥, prf := λ x hx, begin induction x using ereal.rec, { simpa using hx }, { simp }, { simpa using hx } end } /-- The map from extended reals to reals sending infinities to zero. -/ def to_real : ereal → ℝ | ⊥ := 0 | ⊤ := 0 | (x : ℝ) := x @[simp] lemma to_real_top : to_real ⊤ = 0 := rfl @[simp] lemma to_real_bot : to_real ⊥ = 0 := rfl @[simp] lemma to_real_zero : to_real 0 = 0 := rfl @[simp] lemma to_real_coe (x : ℝ) : to_real (x : ereal) = x := rfl @[simp] lemma bot_lt_coe (x : ℝ) : (⊥ : ereal) < x := by { apply with_top.coe_lt_coe.2, exact with_bot.bot_lt_coe _ } @[simp] lemma coe_ne_bot (x : ℝ) : (x : ereal) ≠ ⊥ := (bot_lt_coe x).ne' @[simp] lemma bot_ne_coe (x : ℝ) : (⊥ : ereal) ≠ x := (bot_lt_coe x).ne @[simp] lemma coe_lt_top (x : ℝ) : (x : ereal) < ⊤ := with_top.coe_lt_top _ @[simp] lemma coe_ne_top (x : ℝ) : (x : ereal) ≠ ⊤ := (coe_lt_top x).ne @[simp] lemma top_ne_coe (x : ℝ) : (⊤ : ereal) ≠ x := (coe_lt_top x).ne' @[simp] lemma bot_lt_zero : (⊥ : ereal) < 0 := bot_lt_coe 0 @[simp] lemma bot_ne_zero : (⊥ : ereal) ≠ 0 := (coe_ne_bot 0).symm @[simp] lemma zero_ne_bot : (0 : ereal) ≠ ⊥ := coe_ne_bot 0 @[simp] lemma zero_lt_top : (0 : ereal) < ⊤ := coe_lt_top 0 @[simp] lemma zero_ne_top : (0 : ereal) ≠ ⊤ := coe_ne_top 0 @[simp] lemma top_ne_zero : (⊤ : ereal) ≠ 0 := (coe_ne_top 0).symm @[simp, norm_cast] lemma coe_add (x y : ℝ) : ((x + y : ℝ) : ereal) = (x : ereal) + (y : ereal) := rfl @[simp] lemma coe_zero : ((0 : ℝ) : ereal) = 0 := rfl lemma to_real_le_to_real {x y : ereal} (h : x ≤ y) (hx : x ≠ ⊥) (hy : y ≠ ⊤) : x.to_real ≤ y.to_real := begin lift x to ℝ, lift y to ℝ, { simpa using h }, { simp [hy, ((bot_lt_iff_ne_bot.2 hx).trans_le h).ne'] }, { simp [hx, (h.trans_lt (lt_top_iff_ne_top.2 hy)).ne], }, end lemma coe_to_real {x : ereal} (hx : x ≠ ⊤) (h'x : x ≠ ⊥) : (x.to_real : ereal) = x := begin induction x using ereal.rec, { simpa using h'x }, { refl }, { simpa using hx }, end lemma le_coe_to_real {x : ereal} (h : x ≠ ⊤) : x ≤ x.to_real := begin by_cases h' : x = ⊥, { simp only [h', bot_le] }, { simp only [le_refl, coe_to_real h h'] }, end lemma coe_to_real_le {x : ereal} (h : x ≠ ⊥) : ↑x.to_real ≤ x := begin by_cases h' : x = ⊤, { simp only [h', le_top] }, { simp only [le_refl, coe_to_real h' h] }, end lemma eq_top_iff_forall_lt (x : ereal) : x = ⊤ ↔ ∀ (y : ℝ), (y : ereal) < x := begin split, { rintro rfl, exact ereal.coe_lt_top }, { contrapose!, intro h, exact ⟨x.to_real, le_coe_to_real h⟩, }, end lemma eq_bot_iff_forall_lt (x : ereal) : x = ⊥ ↔ ∀ (y : ℝ), x < (y : ereal) := begin split, { rintro rfl, exact bot_lt_coe }, { contrapose!, intro h, exact ⟨x.to_real, coe_to_real_le h⟩, }, end /-! ### ennreal coercion -/ @[simp] lemma to_real_coe_ennreal : ∀ {x : ℝ≥0∞}, to_real (x : ereal) = ennreal.to_real x | ⊤ := rfl | (some x) := rfl lemma coe_nnreal_eq_coe_real (x : ℝ≥0) : ((x : ℝ≥0∞) : ereal) = (x : ℝ) := rfl @[simp] lemma coe_ennreal_top : ((⊤ : ℝ≥0∞) : ereal) = ⊤ := rfl @[simp] lemma coe_ennreal_eq_top_iff : ∀ {x : ℝ≥0∞}, (x : ereal) = ⊤ ↔ x = ⊤ | ⊤ := by simp | (some x) := by { simp only [ennreal.coe_ne_top, iff_false, ennreal.some_eq_coe], dec_trivial } lemma coe_nnreal_ne_top (x : ℝ≥0) : ((x : ℝ≥0∞) : ereal) ≠ ⊤ := dec_trivial @[simp] lemma coe_nnreal_lt_top (x : ℝ≥0) : ((x : ℝ≥0∞) : ereal) < ⊤ := dec_trivial @[simp, norm_cast] lemma coe_ennreal_le_coe_ennreal_iff : ∀ {x y : ℝ≥0∞}, (x : ereal) ≤ (y : ereal) ↔ x ≤ y | x ⊤ := by simp | ⊤ (some y) := by simp | (some x) (some y) := by simp [coe_nnreal_eq_coe_real] @[simp, norm_cast] lemma coe_ennreal_lt_coe_ennreal_iff : ∀ {x y : ℝ≥0∞}, (x : ereal) < (y : ereal) ↔ x < y | ⊤ ⊤ := by simp | (some x) ⊤ := by simp | ⊤ (some y) := by simp | (some x) (some y) := by simp [coe_nnreal_eq_coe_real] @[simp, norm_cast] lemma coe_ennreal_eq_coe_ennreal_iff : ∀ {x y : ℝ≥0∞}, (x : ereal) = (y : ereal) ↔ x = y | ⊤ ⊤ := by simp | (some x) ⊤ := by simp | ⊤ (some y) := by simp [(coe_nnreal_lt_top y).ne'] | (some x) (some y) := by simp [coe_nnreal_eq_coe_real] lemma coe_ennreal_nonneg (x : ℝ≥0∞) : (0 : ereal) ≤ x := coe_ennreal_le_coe_ennreal_iff.2 (zero_le x) @[simp] lemma bot_lt_coe_ennreal (x : ℝ≥0∞) : (⊥ : ereal) < x := (bot_lt_coe 0).trans_le (coe_ennreal_nonneg _) @[simp] lemma coe_ennreal_ne_bot (x : ℝ≥0∞) : (x : ereal) ≠ ⊥ := (bot_lt_coe_ennreal x).ne' @[simp, norm_cast] lemma coe_ennreal_add : ∀ (x y : ennreal), ((x + y : ℝ≥0∞) : ereal) = x + y | ⊤ y := rfl | x ⊤ := by simp | (some x) (some y) := rfl @[simp] lemma coe_ennreal_zero : ((0 : ℝ≥0∞) : ereal) = 0 := rfl /-! ### Order -/ lemma exists_rat_btwn_of_lt : Π {a b : ereal} (hab : a < b), ∃ (x : ℚ), a < (x : ℝ) ∧ ((x : ℝ) : ereal) < b | ⊤ b h := (not_top_lt h).elim | (a : ℝ) ⊥ h := (lt_irrefl _ ((bot_lt_coe a).trans h)).elim | (a : ℝ) (b : ℝ) h := by simp [exists_rat_btwn (ereal.coe_lt_coe_iff.1 h)] | (a : ℝ) ⊤ h := let ⟨b, hab⟩ := exists_rat_gt a in ⟨b, by simpa using hab, coe_lt_top _⟩ | ⊥ ⊥ h := (lt_irrefl _ h).elim | ⊥ (a : ℝ) h := let ⟨b, hab⟩ := exists_rat_lt a in ⟨b, bot_lt_coe _, by simpa using hab⟩ | ⊥ ⊤ h := ⟨0, bot_lt_coe _, coe_lt_top _⟩ lemma lt_iff_exists_rat_btwn {a b : ereal} : a < b ↔ ∃ (x : ℚ), a < (x : ℝ) ∧ ((x : ℝ) : ereal) < b := ⟨λ hab, exists_rat_btwn_of_lt hab, λ ⟨x, ax, xb⟩, ax.trans xb⟩ lemma lt_iff_exists_real_btwn {a b : ereal} : a < b ↔ ∃ (x : ℝ), a < x ∧ (x : ereal) < b := ⟨λ hab, let ⟨x, ax, xb⟩ := exists_rat_btwn_of_lt hab in ⟨(x : ℝ), ax, xb⟩, λ ⟨x, ax, xb⟩, ax.trans xb⟩ /-- The set of numbers in `ereal` that are not equal to `±∞` is equivalent to `ℝ`. -/ def ne_top_bot_equiv_real : ({⊥, ⊤}ᶜ : set ereal) ≃ ℝ := { to_fun := λ x, ereal.to_real x, inv_fun := λ x, ⟨x, by simp⟩, left_inv := λ ⟨x, hx⟩, subtype.eq $ begin lift x to ℝ, { simp }, { simpa [not_or_distrib, and_comm] using hx } end, right_inv := λ x, by simp } /-! ### Addition -/ @[simp] lemma add_top (x : ereal) : x + ⊤ = ⊤ := add_top _ @[simp] lemma top_add (x : ereal) : ⊤ + x = ⊤ := top_add _ @[simp] lemma bot_add_bot : (⊥ : ereal) + ⊥ = ⊥ := rfl @[simp] lemma bot_add_coe (x : ℝ) : (⊥ : ereal) + x = ⊥ := rfl @[simp] lemma coe_add_bot (x : ℝ) : (x : ereal) + ⊥ = ⊥ := rfl lemma to_real_add : ∀ {x y : ereal} (hx : x ≠ ⊤) (h'x : x ≠ ⊥) (hy : y ≠ ⊤) (h'y : y ≠ ⊥), to_real (x + y) = to_real x + to_real y | ⊥ y hx h'x hy h'y := (h'x rfl).elim | ⊤ y hx h'x hy h'y := (hx rfl).elim | x ⊤ hx h'x hy h'y := (hy rfl).elim | x ⊥ hx h'x hy h'y := (h'y rfl).elim | (x : ℝ) (y : ℝ) hx h'x hy h'y := by simp [← ereal.coe_add] lemma add_lt_add_right_coe {x y : ereal} (h : x < y) (z : ℝ) : x + z < y + z := begin induction x using ereal.rec; induction y using ereal.rec, { exact (lt_irrefl _ h).elim }, { simp only [bot_lt_coe, bot_add_coe, ← coe_add] }, { simp }, { exact (lt_irrefl _ (h.trans (bot_lt_coe x))).elim }, { norm_cast at h ⊢, exact add_lt_add_right h _ }, { simp only [← coe_add, top_add, coe_lt_top] }, { exact (lt_irrefl _ (h.trans_le le_top)).elim }, { exact (lt_irrefl _ (h.trans_le le_top)).elim }, { exact (lt_irrefl _ (h.trans_le le_top)).elim }, end lemma add_lt_add_of_lt_of_le {x y z t : ereal} (h : x < y) (h' : z ≤ t) (hz : z ≠ ⊥) (ht : t ≠ ⊤) : x + z < y + t := begin induction z using ereal.rec, { simpa only using hz }, { calc x + z < y + z : add_lt_add_right_coe h _ ... ≤ y + t : add_le_add le_rfl h' }, { exact (ht (top_le_iff.1 h')).elim } end lemma add_lt_add_left_coe {x y : ereal} (h : x < y) (z : ℝ) : (z : ereal) + x < z + y := by simpa [add_comm] using add_lt_add_right_coe h z lemma add_lt_add {x y z t : ereal} (h1 : x < y) (h2 : z < t) : x + z < y + t := begin induction y using ereal.rec, { exact (lt_irrefl _ (bot_le.trans_lt h1)).elim }, { calc x + z ≤ y + z : add_le_add h1.le le_rfl ... < y + t : add_lt_add_left_coe h2 _ }, { simp [lt_top_iff_ne_top, with_top.add_eq_top, h1.ne, (h2.trans_le le_top).ne] } end @[simp] lemma add_eq_top_iff {x y : ereal} : x + y = ⊤ ↔ x = ⊤ ∨ y = ⊤ := begin induction x using ereal.rec; induction y using ereal.rec; simp [← ereal.coe_add], end @[simp] lemma add_lt_top_iff {x y : ereal} : x + y < ⊤ ↔ x < ⊤ ∧ y < ⊤ := by simp [lt_top_iff_ne_top, not_or_distrib] /-! ### Negation -/ /-- negation on `ereal` -/ protected def neg : ereal → ereal | ⊥ := ⊤ | ⊤ := ⊥ | (x : ℝ) := (-x : ℝ) instance : has_neg ereal := ⟨ereal.neg⟩ @[norm_cast] protected lemma neg_def (x : ℝ) : ((-x : ℝ) : ereal) = -x := rfl @[simp] lemma neg_top : - (⊤ : ereal) = ⊥ := rfl @[simp] lemma neg_bot : - (⊥ : ereal) = ⊤ := rfl @[simp] lemma neg_zero : - (0 : ereal) = 0 := by { change ((-0 : ℝ) : ereal) = 0, simp } instance : has_involutive_neg ereal := { neg := has_neg.neg, neg_neg := λ a, match a with | ⊥ := rfl | ⊤ := rfl | (a : ℝ) := by { norm_cast, simp [neg_neg a] } end } @[simp] lemma to_real_neg : ∀ {a : ereal}, to_real (-a) = - to_real a | ⊤ := by simp | ⊥ := by simp | (x : ℝ) := rfl @[simp] lemma neg_eg_top_iff {x : ereal} : - x = ⊤ ↔ x = ⊥ := by { rw neg_eq_iff_neg_eq, simp [eq_comm] } @[simp] lemma neg_eg_bot_iff {x : ereal} : - x = ⊥ ↔ x = ⊤ := by { rw neg_eq_iff_neg_eq, simp [eq_comm] } @[simp] lemma neg_eg_zero_iff {x : ereal} : - x = 0 ↔ x = 0 := by { rw neg_eq_iff_neg_eq, simp [eq_comm] } /-- if `-a ≤ b` then `-b ≤ a` on `ereal`. -/ protected theorem neg_le_of_neg_le : ∀ {a b : ereal} (h : -a ≤ b), -b ≤ a | ⊥ ⊥ h := h | ⊥ (some b) h := by cases (top_le_iff.1 h) | ⊤ l h := le_top | (a : ℝ) ⊥ h := by cases (le_bot_iff.1 h) | l ⊤ h := bot_le | (a : ℝ) (b : ℝ) h := by { norm_cast at h ⊢, exact neg_le.mp h } /-- `-a ≤ b ↔ -b ≤ a` on `ereal`. -/ protected theorem neg_le {a b : ereal} : -a ≤ b ↔ -b ≤ a := ⟨ereal.neg_le_of_neg_le, ereal.neg_le_of_neg_le⟩ /-- `a ≤ -b → b ≤ -a` on ereal -/ theorem le_neg_of_le_neg {a b : ereal} (h : a ≤ -b) : b ≤ -a := by rwa [←neg_neg b, ereal.neg_le, neg_neg] @[simp] lemma neg_le_neg_iff {a b : ereal} : - a ≤ - b ↔ b ≤ a := by conv_lhs { rw [ereal.neg_le, neg_neg] } @[simp, norm_cast] lemma coe_neg (x : ℝ) : ((- x : ℝ) : ereal) = - (x : ereal) := rfl /-- Negation as an order reversing isomorphism on `ereal`. -/ def neg_order_iso : ereal ≃o erealᵒᵈ := { to_fun := λ x, order_dual.to_dual (-x), inv_fun := λ x, -x.of_dual, map_rel_iff' := λ x y, neg_le_neg_iff, ..equiv.neg ereal } lemma neg_lt_of_neg_lt {a b : ereal} (h : -a < b) : -b < a := begin apply lt_of_le_of_ne (ereal.neg_le_of_neg_le h.le), assume H, rw [← H, neg_neg] at h, exact lt_irrefl _ h end lemma neg_lt_iff_neg_lt {a b : ereal} : -a < b ↔ -b < a := ⟨λ h, ereal.neg_lt_of_neg_lt h, λ h, ereal.neg_lt_of_neg_lt h⟩ /-! ### Subtraction -/ /-- Subtraction on `ereal`, defined by `x - y = x + (-y)`. Since addition is badly behaved at some points, so is subtraction. There is no standard algebraic typeclass involving subtraction that is registered on `ereal` because of this bad behavior. -/ protected noncomputable def sub (x y : ereal) : ereal := x + (-y) noncomputable instance : has_sub ereal := ⟨ereal.sub⟩ @[simp] lemma top_sub (x : ereal) : ⊤ - x = ⊤ := top_add x @[simp] lemma sub_bot (x : ereal) : x - ⊥ = ⊤ := add_top x @[simp] lemma bot_sub_top : (⊥ : ereal) - ⊤ = ⊥ := rfl @[simp] lemma bot_sub_coe (x : ℝ) : (⊥ : ereal) - x = ⊥ := rfl @[simp] lemma coe_sub_bot (x : ℝ) : (x : ereal) - ⊤ = ⊥ := rfl @[simp] lemma sub_zero (x : ereal) : x - 0 = x := by { change x + (-0) = x, simp } @[simp] lemma zero_sub (x : ereal) : 0 - x = - x := by { change 0 + (-x) = - x, simp } lemma sub_eq_add_neg (x y : ereal) : x - y = x + -y := rfl lemma sub_le_sub {x y z t : ereal} (h : x ≤ y) (h' : t ≤ z) : x - z ≤ y - t := add_le_add h (neg_le_neg_iff.2 h') lemma sub_lt_sub_of_lt_of_le {x y z t : ereal} (h : x < y) (h' : z ≤ t) (hz : z ≠ ⊥) (ht : t ≠ ⊤) : x - t < y - z := add_lt_add_of_lt_of_le h (neg_le_neg_iff.2 h') (by simp [ht]) (by simp [hz]) lemma coe_real_ereal_eq_coe_to_nnreal_sub_coe_to_nnreal (x : ℝ) : (x : ereal) = real.to_nnreal x - real.to_nnreal (-x) := begin rcases le_or_lt 0 x with h|h, { have : real.to_nnreal x = ⟨x, h⟩, by { ext, simp [h] }, simp only [real.to_nnreal_of_nonpos (neg_nonpos.mpr h), this, sub_zero, ennreal.coe_zero, coe_ennreal_zero, coe_coe], refl }, { have : (x : ereal) = - (- x : ℝ), by simp, conv_lhs { rw this }, have : real.to_nnreal (-x) = ⟨-x, neg_nonneg.mpr h.le⟩, by { ext, simp [neg_nonneg.mpr h.le], }, simp only [real.to_nnreal_of_nonpos h.le, this, zero_sub, neg_inj, coe_neg, ennreal.coe_zero, coe_ennreal_zero, coe_coe], refl } end lemma to_real_sub {x y : ereal} (hx : x ≠ ⊤) (h'x : x ≠ ⊥) (hy : y ≠ ⊤) (h'y : y ≠ ⊥) : to_real (x - y) = to_real x - to_real y := begin rw [ereal.sub_eq_add_neg, to_real_add hx h'x, to_real_neg], { refl }, { simpa using hy }, { simpa using h'y } end /-! ### Multiplication -/ @[simp] lemma coe_one : ((1 : ℝ) : ereal) = 1 := rfl @[simp, norm_cast] lemma coe_mul (x y : ℝ) : ((x * y : ℝ) : ereal) = (x : ereal) * (y : ereal) := eq.trans (with_bot.coe_eq_coe.mpr with_bot.coe_mul) with_top.coe_mul @[simp] lemma mul_top (x : ereal) (h : x ≠ 0) : x * ⊤ = ⊤ := with_top.mul_top h @[simp] lemma top_mul (x : ereal) (h : x ≠ 0) : ⊤ * x = ⊤ := with_top.top_mul h @[simp] lemma bot_mul_bot : (⊥ : ereal) * ⊥ = ⊥ := rfl @[simp] lemma bot_mul_coe (x : ℝ) (h : x ≠ 0) : (⊥ : ereal) * x = ⊥ := with_top.coe_mul.symm.trans $ with_bot.coe_eq_coe.mpr $ with_bot.bot_mul $ function.injective.ne (@option.some.inj _) h @[simp] lemma coe_mul_bot (x : ℝ) (h : x ≠ 0) : (x : ereal) * ⊥ = ⊥ := with_top.coe_mul.symm.trans $ with_bot.coe_eq_coe.mpr $ with_bot.mul_bot $ function.injective.ne (@option.some.inj _) h @[simp] lemma to_real_one : to_real 1 = 1 := rfl lemma to_real_mul : ∀ {x y : ereal}, to_real (x * y) = to_real x * to_real y | ⊤ y := by by_cases hy : y = 0; simp [hy] | x ⊤ := by by_cases hx : x = 0; simp [hx] | (x : ℝ) (y : ℝ) := by simp [← ereal.coe_mul] | ⊥ (y : ℝ) := by by_cases hy : y = 0; simp [hy] | (x : ℝ) ⊥ := by by_cases hx : x = 0; simp [hx] | ⊥ ⊥ := by simp end ereal
c5bd057fd6e7d845f06cd05e298ac0d4358e0880
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/category/Group/adjunctions.lean
2167941a3068acc09a941daf0e077f8be1ab4a70
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
4,033
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Johannes Hölzl -/ import algebra.category.Group.basic import group_theory.free_abelian_group /-! # Adjunctions regarding the category of (abelian) groups This file contains construction of basic adjunctions concerning the category of groups and the category of abelian groups. ## Main definitions * `AddCommGroup.free`: constructs the functor associating to a type `X` the free abelian group with generators `x : X`. * `Group.free`: constructs the functor associating to a type `X` the free group with generators `x : X`. * `abelianize`: constructs the functor which associates to a group `G` its abelianization `Gᵃᵇ`. ## Main statements * `AddCommGroup.adj`: proves that `AddCommGroup.free` is the left adjoint of the forgetful functor from abelian groups to types. * `Group.adj`: proves that `Group.free` is the left adjoint of the forgetful functor from groups to types. * `abelianize_adj`: proves that `abelianize` is left adjoint to the forgetful functor from abelian groups to groups. -/ noncomputable theory universe u open category_theory namespace AddCommGroup open_locale classical /-- The free functor `Type u ⥤ AddCommGroup` sending a type `X` to the free abelian group with generators `x : X`. -/ def free : Type u ⥤ AddCommGroup := { obj := λ α, of (free_abelian_group α), map := λ X Y, free_abelian_group.map, map_id' := λ X, add_monoid_hom.ext free_abelian_group.map_id_apply, map_comp' := λ X Y Z f g, add_monoid_hom.ext free_abelian_group.map_comp_apply, } @[simp] lemma free_obj_coe {α : Type u} : (free.obj α : Type u) = (free_abelian_group α) := rfl @[simp] lemma free_map_coe {α β : Type u} {f : α → β} (x : free_abelian_group α) : (free.map f) x = f <$> x := rfl /-- The free-forgetful adjunction for abelian groups. -/ def adj : free ⊣ forget AddCommGroup.{u} := adjunction.mk_of_hom_equiv { hom_equiv := λ X G, free_abelian_group.lift.symm, hom_equiv_naturality_left_symm' := by { intros, ext, refl} } /-- As an example, we now give a high-powered proof that the monomorphisms in `AddCommGroup` are just the injective functions. (This proof works in all universes.) -/ example {G H : AddCommGroup.{u}} (f : G ⟶ H) [mono f] : function.injective f := (mono_iff_injective f).1 (right_adjoint_preserves_mono adj (by apply_instance : mono f)) instance : is_right_adjoint (forget AddCommGroup.{u}) := ⟨_, adj⟩ end AddCommGroup namespace Group /-- The free functor `Type u ⥤ Group` sending a type `X` to the free group with generators `x : X`. -/ def free : Type u ⥤ Group := { obj := λ α, of (free_group α), map := λ X Y, free_group.map, map_id' := by { intros, ext1, refl }, map_comp' := by { intros, ext1, refl } } /-- The free-forgetful adjunction for groups. -/ def adj : free ⊣ forget Group.{u} := adjunction.mk_of_hom_equiv { hom_equiv := λ X G, free_group.lift.symm, hom_equiv_naturality_left_symm' := λ X Y G f g, by { ext1, refl } } instance : is_right_adjoint (forget Group.{u}) := ⟨_, adj⟩ end Group section abelianization /-- The abelianization functor `Group ⥤ CommGroup` sending a group `G` to its abelianization `Gᵃᵇ`. -/ def abelianize : Group.{u} ⥤ CommGroup.{u} := { obj := λ G, { α := abelianization G, str := by apply_instance }, map := λ G H f, abelianization.lift ( { to_fun := λ x, abelianization.of (f x), map_one' := by simp, map_mul' := by simp } ), map_id' := by { intros, simp only [monoid_hom.mk_coe, coe_id], ext1, refl }, map_comp' := by { intros, simp only [coe_comp], ext1, refl } } /-- The abelianization-forgetful adjuction from `Group` to `CommGroup`.-/ def abelianize_adj : abelianize ⊣ forget₂ CommGroup.{u} Group.{u} := adjunction.mk_of_hom_equiv { hom_equiv := λ G A, abelianization.lift.symm, hom_equiv_naturality_left_symm' := λ G H A f g, by { ext1, refl } } end abelianization
df4603a8025fa537558bc17e6c94f5ce3ada1b1d
80746c6dba6a866de5431094bf9f8f841b043d77
/src/category/applicative.lean
ce1af4d2be1408bd945e55105adf6db79135dda3
[ "Apache-2.0" ]
permissive
leanprover-fork/mathlib-backup
8b5c95c535b148fca858f7e8db75a76252e32987
0eb9db6a1a8a605f0cf9e33873d0450f9f0ae9b0
refs/heads/master
1,585,156,056,139
1,548,864,430,000
1,548,864,438,000
143,964,213
0
0
Apache-2.0
1,550,795,966,000
1,533,705,322,000
Lean
UTF-8
Lean
false
false
5,887
lean
/- Copyright (c) 2017 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon Instances for identity and composition functors -/ import category.functor universe variables u v w section lemmas open function variables {F : Type u → Type v} variables [applicative F] [is_lawful_applicative F] variables {α β γ σ : Type u} attribute [functor_norm] seq_assoc pure_seq_eq_map map_pure seq_map_assoc map_seq lemma applicative.map_seq_map (f : α → β → γ) (g : σ → β) (x : F α) (y : F σ) : (f <$> x) <*> (g <$> y) = (flip (∘) g ∘ f) <$> x <*> y := by simp [flip] with functor_norm lemma applicative.pure_seq_eq_map' (f : α → β) : (<*>) (pure f : F (α → β)) = (<$>) f := by ext; simp with functor_norm theorem applicative.ext {F} : ∀ {A1 : applicative F} {A2 : applicative F} [@is_lawful_applicative F A1] [@is_lawful_applicative F A2] (H1 : ∀ {α : Type u} (x : α), @has_pure.pure _ A1.to_has_pure _ x = @has_pure.pure _ A2.to_has_pure _ x) (H2 : ∀ {α β : Type u} (f : F (α → β)) (x : F α), @has_seq.seq _ A1.to_has_seq _ _ f x = @has_seq.seq _ A2.to_has_seq _ _ f x), A1 = A2 | {to_functor := F1, seq := s1, pure := p1, seq_left := sl1, seq_right := sr1} {to_functor := F2, seq := s2, pure := p2, seq_left := sl2, seq_right := sr2} L1 L2 H1 H2 := begin have : @p1 = @p2, {funext α x, apply H1}, subst this, have : @s1 = @s2, {funext α β f x, apply H2}, subst this, cases L1, cases L2, have : F1 = F2, { resetI, apply functor.ext, intros, exact (L1_pure_seq_eq_map _ _).symm.trans (L2_pure_seq_eq_map _ _) }, subst this, congr; funext α β x y, { exact (L1_seq_left_eq _ _).trans (L2_seq_left_eq _ _).symm }, { exact (L1_seq_right_eq _ _).trans (L2_seq_right_eq _ _).symm } end end lemmas instance : is_comm_applicative id := by refine { .. }; intros; refl namespace const open functor variables {γ : Type u} [monoid γ] protected def pure {α} (x : α) : const γ α := (1 : γ) protected def seq {α β : Type*} (f : const γ (α → β)) (x : const γ α) : const γ β := (f * x : γ) instance : applicative (const γ) := { pure := @const.pure γ _, seq := @const.seq γ _ } instance : is_lawful_applicative (const γ) := by refine { .. }; intros; simp! [const.seq,const.pure,mul_assoc] end const namespace add_const open functor variables {γ : Type u} [add_monoid γ] protected def pure {α} (x : α) : add_const γ α := (0 : γ) protected def seq {α β : Type*} (f : add_const γ (α → β)) (x : add_const γ α) : add_const γ β := (f + x : γ) instance : applicative (add_const γ) := { pure := @add_const.pure γ _, seq := @add_const.seq γ _ } instance : is_lawful_applicative (add_const γ) := by refine { .. }; intros; simp! [add_const.seq,add_const.pure,add_assoc] end add_const namespace comp open function (hiding comp) open functor variables {F : Type u → Type w} {G : Type v → Type u} variables [applicative F] [applicative G] protected def seq {α β : Type v} : comp F G (α → β) → comp F G α → comp F G β | (comp.mk f) (comp.mk x) := comp.mk $ (<*>) <$> f <*> x instance : has_pure (comp F G) := ⟨λ _ x, comp.mk $ pure $ pure x⟩ instance : has_seq (comp F G) := ⟨λ _ _ f x, comp.seq f x⟩ @[simp] protected lemma run_pure {α : Type v} : ∀ x : α, (pure x : comp F G α).run = pure (pure x) | _ := rfl @[simp] protected lemma run_seq {α β : Type v} (f : comp F G (α → β)) (x : comp F G α) : (f <*> x).run = (<*>) <$> f.run <*> x.run := rfl instance : applicative (comp F G) := { map := @comp.map F G _ _, seq := @comp.seq F G _ _, ..comp.has_pure } variables [is_lawful_applicative F] [is_lawful_applicative G] variables {α β γ : Type v} lemma map_pure (f : α → β) (x : α) : (f <$> pure x : comp F G β) = pure (f x) := comp.ext $ by simp lemma seq_pure (f : comp F G (α → β)) (x : α) : f <*> pure x = (λ g : α → β, g x) <$> f := comp.ext $ by simp [(∘)] with functor_norm lemma seq_assoc (x : comp F G α) (f : comp F G (α → β)) (g : comp F G (β → γ)) : g <*> (f <*> x) = (@function.comp α β γ <$> g) <*> f <*> x := comp.ext $ by simp [(∘)] with functor_norm lemma pure_seq_eq_map (f : α → β) (x : comp F G α) : pure f <*> x = f <$> x := comp.ext $ by simp [applicative.pure_seq_eq_map'] with functor_norm instance : is_lawful_applicative (comp F G) := { pure_seq_eq_map := @comp.pure_seq_eq_map F G _ _ _ _, map_pure := @comp.map_pure F G _ _ _ _, seq_pure := @comp.seq_pure F G _ _ _ _, seq_assoc := @comp.seq_assoc F G _ _ _ _ } theorem applicative_id_comp {F} [AF : applicative F] [LF : is_lawful_applicative F] : @comp.applicative id F _ _ = AF := @applicative.ext F _ _ (@comp.is_lawful_applicative id F _ _ _ _) _ (λ α x, rfl) (λ α β f x, rfl) theorem applicative_comp_id {F} [AF : applicative F] [LF : is_lawful_applicative F] : @comp.applicative F id _ _ = AF := @applicative.ext F _ _ (@comp.is_lawful_applicative F id _ _ _ _) _ (λ α x, rfl) (λ α β f x, show id <$> f <*> x = f <*> x, by rw id_map) open is_comm_applicative instance {f : Type u → Type w} {g : Type v → Type u} [applicative f] [applicative g] [is_comm_applicative f] [is_comm_applicative g] : is_comm_applicative (comp f g) := by { refine { .. @comp.is_lawful_applicative f g _ _ _ _, .. }, intros, casesm* comp _ _ _, simp! [map,has_seq.seq] with functor_norm, rw [commutative_map], simp [comp.mk,flip,(∘)] with functor_norm, congr, funext, rw [commutative_map], congr } end comp open functor @[functor_norm] lemma comp.seq_mk {α β : Type w} {f : Type u → Type v} {g : Type w → Type u} [applicative f] [applicative g] (h : f (g (α → β))) (x : f (g α)) : comp.mk h <*> comp.mk x = comp.mk (has_seq.seq <$> h <*> x) := rfl
0719c83d5c793728cf2b70f7227c4e968bf7ebb7
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/Lake/Config/Package.lean
5e1a59d729bdd9fea83097d12e191eb86251aa45
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
12,895
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Sebastian Ullrich, Mac Malone -/ import Lake.Config.Opaque import Lake.Config.LeanLibConfig import Lake.Config.LeanExeConfig import Lake.Config.ExternLibConfig import Lake.Config.WorkspaceConfig import Lake.Config.Dependency import Lake.Config.Script import Lake.Util.DRBMap import Lake.Util.OrdHashSet open System Lean namespace Lake /-- A string descriptor of the `System.Platform` OS (`windows`, `macOS`, or `linux`). -/ def osDescriptor : String := if Platform.isWindows then "windows" else if Platform.isOSX then "macOS" else "linux" /-- A `tar.gz` file name suffix encoding the the current Platform. (i.e, `osDescriptor` joined with `System.Platform.numBits`). -/ def archiveSuffix := s!"{osDescriptor}-{Platform.numBits}.tar.gz" /-- If `name?`, `{name}-{archiveSuffix}`, otherwise just `archiveSuffix`. -/ def nameToArchive (name? : Option String) : String := match name? with | none => archiveSuffix | some name => s!"{name}-{archiveSuffix}" /-- First tries to convert a string into a legal name. If that fails, defaults to making it a simple name (e.g., `Lean.Name.mkSimple`). Currently used for package and target names taken from the CLI. -/ def stringToLegalOrSimpleName (s : String) : Name := if s.toName.isAnonymous then Lean.Name.mkSimple s else s.toName -------------------------------------------------------------------------------- /-! # Defaults -/ -------------------------------------------------------------------------------- /-- The default setting for a `PackageConfig`'s `manifestFile` option. -/ def defaultManifestFile := "lake-manifest.json" /-- The default setting for a `PackageConfig`'s `buildDir` option. -/ def defaultBuildDir : FilePath := "build" /-- The default setting for a `PackageConfig`'s `leanLibDir` option. -/ def defaultLeanLibDir : FilePath := "lib" /-- The default setting for a `PackageConfig`'s `nativeLibDir` option. -/ def defaultNativeLibDir : FilePath := "lib" /-- The default setting for a `PackageConfig`'s `binDir` option. -/ def defaultBinDir : FilePath := "bin" /-- The default setting for a `PackageConfig`'s `irDir` option. -/ def defaultIrDir : FilePath := "ir" -------------------------------------------------------------------------------- /-! # PackageConfig -/ -------------------------------------------------------------------------------- /-- A `Package`'s declarative configuration. -/ structure PackageConfig extends WorkspaceConfig, LeanConfig where /-- The `Name` of the package. -/ name : Name /-- The path of a package's manifest file, which stores the exact versions of its resolved dependencies. Defaults to `defaultManifestFile` (i.e., `lake-manifest.json`). -/ manifestFile := defaultManifestFile /-- An `Array` of target names to build whenever the package is used. -/ extraDepTargets : Array Name := #[] /-- Whether to compile each of the package's module into a native shared library that is loaded whenever the module is imported. This speeds up evaluation of metaprograms and enables the interpreter to run functions marked `@[extern]`. Defaults to `false`. -/ precompileModules : Bool := false /-- Additional arguments to pass to the Lean language server (i.e., `lean --server`) launched by `lake server`. -/ moreServerArgs : Array String := #[] /-- The directory containing the package's Lean source files. Defaults to the package's directory. (This will be passed to `lean` as the `-R` option.) -/ srcDir : FilePath := "." /-- The directory to which Lake should output the package's build results. Defaults to `defaultBuildDir` (i.e., `build`). -/ buildDir : FilePath := defaultBuildDir /-- The build subdirectory to which Lake should output the package's binary Lean libraries (e.g., `.olean`, `.ilean` files). Defaults to `defaultLeanLibDir` (i.e., `lib`). -/ leanLibDir : FilePath := defaultLeanLibDir /-- The build subdirectory to which Lake should output the package's native libraries (e.g., `.a`, `.so`, `.dll` files). Defaults to `defaultNativeLibDir` (i.e., `lib`). -/ nativeLibDir : FilePath := defaultNativeLibDir /-- The build subdirectory to which Lake should output the package's binary executable. Defaults to `defaultBinDir` (i.e., `bin`). -/ binDir : FilePath := defaultBinDir /-- The build subdirectory to which Lake should output the package's intermediary results (e.g., `.c` and `.o` files). Defaults to `defaultIrDir` (i.e., `ir`). -/ irDir : FilePath := defaultIrDir /-- The URL of the GitHub repository to upload and download releases of this package. If `none` (the default), for downloads, Lake uses the URL the package was download from (if it is a dependency) and for uploads, uses `gh`'s default. -/ releaseRepo? : Option String := none /-- The name of the build archive on GitHub. Defaults to `none`. The archive's full file name will be `nameToArchive buildArchive?`. -/ buildArchive? : Option String := none /-- Whether to prefer downloading a prebuilt release (from GitHub) rather than building this package from the source when this package is used as a dependency. -/ preferReleaseBuild : Bool := false deriving Inhabited -------------------------------------------------------------------------------- /-! # Package -/ -------------------------------------------------------------------------------- abbrev DNameMap α := DRBMap Name α Name.quickCmp @[inline] def DNameMap.empty : DNameMap α := DRBMap.empty /-- A Lake package -- its location plus its configuration. -/ structure Package where /-- The path to the package's directory. -/ dir : FilePath /-- The package's user-defined configuration. -/ config : PackageConfig /-- The elaboration environment of the package's configuration file. -/ configEnv : Environment /-- The Lean `Options` the package configuration was elaborated with. -/ leanOpts : Options /-- The URL to this package's Git remote. -/ remoteUrl? : Option String := none /-- The Git tag of this package. -/ gitTag? : Option String := none /-- (Opaque references to) the package's direct dependencies. -/ opaqueDeps : Array OpaquePackage := #[] /-- Lean library configurations for the package. -/ leanLibConfigs : NameMap LeanLibConfig := {} /-- Lean binary executable configurations for the package. -/ leanExeConfigs : NameMap LeanExeConfig := {} /-- External library targets for the package. -/ externLibConfigs : DNameMap (ExternLibConfig config.name) := {} /-- (Opaque references to) targets defined in the package. -/ opaqueTargetConfigs : DNameMap (OpaqueTargetConfig config.name) := {} /-- The names of the package's targets to build by default (i.e., on a bare `lake build` of the package). -/ defaultTargets : Array Name := #[] /-- Scripts for the package. -/ scripts : NameMap Script := {} /-- The names of the package's scripts run by default (i.e., on a bare `lake run` of the package). -/ defaultScripts : Array Script := #[] instance : Nonempty Package := have : Inhabited Environment := Classical.inhabited_of_nonempty inferInstance by refine' ⟨{..}⟩ <;> exact default hydrate_opaque_type OpaquePackage Package instance : Hashable Package where hash pkg := hash pkg.config.name instance : BEq Package where beq p1 p2 := p1.config.name == p2.config.name abbrev PackageSet := HashSet Package @[inline] def PackageSet.empty : PackageSet := HashSet.empty abbrev OrdPackageSet := OrdHashSet Package @[inline] def OrdPackageSet.empty : OrdPackageSet := OrdHashSet.empty /-- The package's name. -/ abbrev Package.name (self : Package) : Name := self.config.name /-- A package with a name known at type-level. -/ structure NPackage (name : Name) extends Package where name_eq : toPackage.name = name attribute [simp] NPackage.name_eq instance : CoeOut (NPackage name) Package := ⟨NPackage.toPackage⟩ instance : CoeDep Package pkg (NPackage pkg.name) := ⟨⟨pkg, rfl⟩⟩ /-- The package's name. -/ abbrev NPackage.name (_ : NPackage n) := n namespace Package /-- The package's direct dependencies. -/ @[inline] def deps (self : Package) : Array Package := self.opaqueDeps.map (·.get) /-- The path for storing the package's remote dependencies relative to `dir`. Either its `packagesDir` configuration or `defaultPackagesDir`. -/ def relPkgsDir (self : Package) : FilePath := self.config.packagesDir.getD defaultPackagesDir /-- The package's `dir` joined with its `relPkgsDir` -/ def pkgsDir (self : Package) : FilePath := self.dir / self.relPkgsDir /-- The package's JSON manifest of remote dependencies. -/ def manifestFile (self : Package) : FilePath := self.dir / self.config.manifestFile /-- The package's `dir` joined with its `buildDir` configuration. -/ @[inline] def buildDir (self : Package) : FilePath := self.dir / self.config.buildDir /-- The package's `extraDepTargets` configuration. -/ @[inline] def extraDepTargets (self : Package) : Array Name := self.config.extraDepTargets /-- The package's `releaseRepo?` configuration. -/ @[inline] def releaseRepo? (self : Package) : Option String := self.config.releaseRepo? /-- The package's URL × tag release. Tries `releaseRepo?` first and then falls back to `remoteUrl?`. -/ def release? (self : Package) : Option (String × String) := do let url ← self.releaseRepo? <|> self.remoteUrl? let tag ← self.gitTag? return (url, tag) /-- The package's `buildArchive?` configuration. -/ @[inline] def buildArchive? (self : Package) : Option String := self.config.buildArchive? /-- The file name of the package's build archive derived from `buildArchive?`. -/ @[inline] def buildArchive (self : Package) : String := nameToArchive self.buildArchive? /-- The package's `buildDir` joined with its `buildArchive` configuration. -/ @[inline] def buildArchiveFile (self : Package) : FilePath := self.buildDir / self.buildArchive /-- The package's `preferReleaseBuild` configuration. -/ @[inline] def preferReleaseBuild (self : Package) : Bool := self.config.preferReleaseBuild /-- The package's `precompileModules` configuration. -/ @[inline] def precompileModules (self : Package) : Bool := self.config.precompileModules /-- The package's `moreServerArgs` configuration. -/ @[inline] def moreServerArgs (self : Package) : Array String := self.config.moreServerArgs /-- The package's `buildType` configuration. -/ @[inline] def buildType (self : Package) : BuildType := self.config.buildType /-- The package's `moreLeanArgs` configuration. -/ @[inline] def moreLeanArgs (self : Package) : Array String := self.config.moreLeanArgs /-- The package's `weakLeanArgs` configuration. -/ @[inline] def weakLeanArgs (self : Package) : Array String := self.config.weakLeanArgs /-- The package's `moreLeancArgs` configuration. -/ @[inline] def moreLeancArgs (self : Package) : Array String := self.config.moreLeancArgs /-- The package's `moreLinkArgs` configuration. -/ @[inline] def moreLinkArgs (self : Package) : Array String := self.config.moreLinkArgs /-- The package's `dir` joined with its `srcDir` configuration. -/ @[inline] def srcDir (self : Package) : FilePath := self.dir / self.config.srcDir /-- The package's root directory for `lean` (i.e., `srcDir`). -/ @[inline] def rootDir (self : Package) : FilePath := self.srcDir /-- The package's `buildDir` joined with its `leanLibDir` configuration. -/ @[inline] def leanLibDir (self : Package) : FilePath := self.buildDir / self.config.leanLibDir /-- The package's `buildDir` joined with its `nativeLibDir` configuration. -/ @[inline] def nativeLibDir (self : Package) : FilePath := self.buildDir / self.config.nativeLibDir /-- The package's `buildDir` joined with its `binDir` configuration. -/ @[inline] def binDir (self : Package) : FilePath := self.buildDir / self.config.binDir /-- The package's `buildDir` joined with its `irDir` configuration. -/ @[inline] def irDir (self : Package) : FilePath := self.buildDir / self.config.irDir /-- Whether the given module is considered local to the package. -/ def isLocalModule (mod : Name) (self : Package) : Bool := self.leanLibConfigs.any (fun _ lib => lib.isLocalModule mod) /-- Whether the given module is in the package (i.e., can build it). -/ def isBuildableModule (mod : Name) (self : Package) : Bool := self.leanLibConfigs.any (fun _ lib => lib.isBuildableModule mod) || self.leanExeConfigs.any (fun _ exe => exe.root == mod) /-- Remove the package's build outputs (i.e., delete its build directory). -/ def clean (self : Package) : IO PUnit := do if (← self.buildDir.pathExists) then IO.FS.removeDirAll self.buildDir
7dc8312858f5aa32967683954b9dcb6d80830104
367134ba5a65885e863bdc4507601606690974c1
/src/category_theory/adjunction/limits.lean
ee665e749cb8457219a17e24746c4631b3715e60
[ "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
11,027
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Johan Commelin -/ import category_theory.adjunction.basic import category_theory.limits.creates open opposite namespace category_theory.adjunction open category_theory open category_theory.functor open category_theory.limits universes u₁ u₂ v variables {C : Type u₁} [category.{v} C] {D : Type u₂} [category.{v} D] variables {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) include adj section preservation_colimits variables {J : Type v} [small_category J] (K : J ⥤ C) /-- The right adjoint of `cocones.functoriality K F : cocone K ⥤ cocone (K ⋙ F)`. Auxiliary definition for `functoriality_is_left_adjoint`. -/ def functoriality_right_adjoint : cocone (K ⋙ F) ⥤ cocone K := (cocones.functoriality _ G) ⋙ (cocones.precompose (K.right_unitor.inv ≫ (whisker_left K adj.unit) ≫ (associator _ _ _).inv)) local attribute [reducible] functoriality_right_adjoint /-- The unit for the adjunction for `cocones.functoriality K F : cocone K ⥤ cocone (K ⋙ F)`. Auxiliary definition for `functoriality_is_left_adjoint`. -/ @[simps] def functoriality_unit : 𝟭 (cocone K) ⟶ cocones.functoriality _ F ⋙ functoriality_right_adjoint adj K := { app := λ c, { hom := adj.unit.app c.X } } /-- The counit for the adjunction for `cocones.functoriality K F : cocone K ⥤ cocone (K ⋙ F)`. Auxiliary definition for `functoriality_is_left_adjoint`. -/ @[simps] def functoriality_counit : functoriality_right_adjoint adj K ⋙ cocones.functoriality _ F ⟶ 𝟭 (cocone (K ⋙ F)) := { app := λ c, { hom := adj.counit.app c.X } } /-- The functor `cocones.functoriality K F : cocone K ⥤ cocone (K ⋙ F)` is a left adjoint. -/ def functoriality_is_left_adjoint : is_left_adjoint (cocones.functoriality K F) := { right := functoriality_right_adjoint adj K, adj := mk_of_unit_counit { unit := functoriality_unit adj K, counit := functoriality_counit adj K } } /-- A left adjoint preserves colimits. See https://stacks.math.columbia.edu/tag/0038. -/ def left_adjoint_preserves_colimits : preserves_colimits F := { preserves_colimits_of_shape := λ J 𝒥, { preserves_colimit := λ F, by exactI { preserves := λ c hc, is_colimit.iso_unique_cocone_morphism.inv (λ s, @equiv.unique _ _ (is_colimit.iso_unique_cocone_morphism.hom hc _) (((adj.functoriality_is_left_adjoint _).adj).hom_equiv _ _)) } } }. omit adj @[priority 100] -- see Note [lower instance priority] instance is_equivalence_preserves_colimits (E : C ⥤ D) [is_equivalence E] : preserves_colimits E := left_adjoint_preserves_colimits E.adjunction @[priority 100] -- see Note [lower instance priority] instance is_equivalence_reflects_colimits (E : D ⥤ C) [is_equivalence E] : reflects_colimits E := { reflects_colimits_of_shape := λ J 𝒥, by exactI { reflects_colimit := λ K, { reflects := λ c t, begin have l := (is_colimit_of_preserves E.inv t).map_cocone_equiv E.as_equivalence.unit_iso.symm, refine (((is_colimit.precompose_inv_equiv K.right_unitor _).symm) l).of_iso_colimit _, tidy, end } } } @[priority 100] -- see Note [lower instance priority] instance is_equivalence_creates_colimits (H : D ⥤ C) [is_equivalence H] : creates_colimits H := { creates_colimits_of_shape := λ J 𝒥, by exactI { creates_colimit := λ F, { lifts := λ c t, { lifted_cocone := H.map_cocone_inv c, valid_lift := H.map_cocone_map_cocone_inv c } } } } -- verify the preserve_colimits instance works as expected: example (E : C ⥤ D) [is_equivalence E] (c : cocone K) (h : is_colimit c) : is_colimit (E.map_cocone c) := preserves_colimit.preserves h instance has_colimit_comp_equivalence (E : C ⥤ D) [is_equivalence E] [has_colimit K] : has_colimit (K ⋙ E) := has_colimit.mk { cocone := E.map_cocone (colimit.cocone K), is_colimit := preserves_colimit.preserves (colimit.is_colimit K) } lemma has_colimit_of_comp_equivalence (E : C ⥤ D) [is_equivalence E] [has_colimit (K ⋙ E)] : has_colimit K := @has_colimit_of_iso _ _ _ _ (K ⋙ E ⋙ inv E) K (@adjunction.has_colimit_comp_equivalence _ _ _ _ _ _ (K ⋙ E) (inv E) _ _) ((functor.right_unitor _).symm ≪≫ iso_whisker_left K (E.as_equivalence.unit_iso)) end preservation_colimits section preservation_limits variables {J : Type v} [small_category J] (K : J ⥤ D) /-- The left adjoint of `cones.functoriality K G : cone K ⥤ cone (K ⋙ G)`. Auxiliary definition for `functoriality_is_right_adjoint`. -/ def functoriality_left_adjoint : cone (K ⋙ G) ⥤ cone K := (cones.functoriality _ F) ⋙ (cones.postcompose ((associator _ _ _).hom ≫ (whisker_left K adj.counit) ≫ K.right_unitor.hom)) local attribute [reducible] functoriality_left_adjoint /-- The unit for the adjunction for`cones.functoriality K G : cone K ⥤ cone (K ⋙ G)`. Auxiliary definition for `functoriality_is_right_adjoint`. -/ @[simps] def functoriality_unit' : 𝟭 (cone (K ⋙ G)) ⟶ functoriality_left_adjoint adj K ⋙ cones.functoriality _ G := { app := λ c, { hom := adj.unit.app c.X, } } /-- The counit for the adjunction for`cones.functoriality K G : cone K ⥤ cone (K ⋙ G)`. Auxiliary definition for `functoriality_is_right_adjoint`. -/ @[simps] def functoriality_counit' : cones.functoriality _ G ⋙ functoriality_left_adjoint adj K ⟶ 𝟭 (cone K) := { app := λ c, { hom := adj.counit.app c.X, } } /-- The functor `cones.functoriality K G : cone K ⥤ cone (K ⋙ G)` is a right adjoint. -/ def functoriality_is_right_adjoint : is_right_adjoint (cones.functoriality K G) := { left := functoriality_left_adjoint adj K, adj := mk_of_unit_counit { unit := functoriality_unit' adj K, counit := functoriality_counit' adj K } } /-- A right adjoint preserves limits. See https://stacks.math.columbia.edu/tag/0038. -/ def right_adjoint_preserves_limits : preserves_limits G := { preserves_limits_of_shape := λ J 𝒥, { preserves_limit := λ K, by exactI { preserves := λ c hc, is_limit.iso_unique_cone_morphism.inv (λ s, @equiv.unique _ _ (is_limit.iso_unique_cone_morphism.hom hc _) (((adj.functoriality_is_right_adjoint _).adj).hom_equiv _ _).symm) } } }. omit adj @[priority 100] -- see Note [lower instance priority] instance is_equivalence_preserves_limits (E : D ⥤ C) [is_equivalence E] : preserves_limits E := right_adjoint_preserves_limits E.inv.adjunction @[priority 100] -- see Note [lower instance priority] instance is_equivalence_reflects_limits (E : D ⥤ C) [is_equivalence E] : reflects_limits E := { reflects_limits_of_shape := λ J 𝒥, by exactI { reflects_limit := λ K, { reflects := λ c t, begin have := (is_limit_of_preserves E.inv t).map_cone_equiv E.as_equivalence.unit_iso.symm, refine (((is_limit.postcompose_hom_equiv K.left_unitor _).symm) this).of_iso_limit _, tidy, end } } } @[priority 100] -- see Note [lower instance priority] instance is_equivalence_creates_limits (H : D ⥤ C) [is_equivalence H] : creates_limits H := { creates_limits_of_shape := λ J 𝒥, by exactI { creates_limit := λ F, { lifts := λ c t, { lifted_cone := H.map_cone_inv c, valid_lift := H.map_cone_map_cone_inv c } } } } -- verify the preserve_limits instance works as expected: example (E : D ⥤ C) [is_equivalence E] (c : cone K) [h : is_limit c] : is_limit (E.map_cone c) := preserves_limit.preserves h instance has_limit_comp_equivalence (E : D ⥤ C) [is_equivalence E] [has_limit K] : has_limit (K ⋙ E) := has_limit.mk { cone := E.map_cone (limit.cone K), is_limit := preserves_limit.preserves (limit.is_limit K) } lemma has_limit_of_comp_equivalence (E : D ⥤ C) [is_equivalence E] [has_limit (K ⋙ E)] : has_limit K := @has_limit_of_iso _ _ _ _ (K ⋙ E ⋙ inv E) K (@adjunction.has_limit_comp_equivalence _ _ _ _ _ _ (K ⋙ E) (inv E) _ _) ((iso_whisker_left K E.as_equivalence.unit_iso.symm) ≪≫ (functor.right_unitor _)) end preservation_limits /-- auxiliary construction for `cocones_iso` -/ @[simps] def cocones_iso_component_hom {J : Type v} [small_category J] {K : J ⥤ C} (Y : D) (t : ((cocones J D).obj (op (K ⋙ F))).obj Y) : (G ⋙ (cocones J C).obj (op K)).obj Y := { app := λ j, (adj.hom_equiv (K.obj j) Y) (t.app j), naturality' := λ j j' f, by { erw [← adj.hom_equiv_naturality_left, t.naturality], dsimp, simp } } /-- auxiliary construction for `cocones_iso` -/ @[simps] def cocones_iso_component_inv {J : Type v} [small_category J] {K : J ⥤ C} (Y : D) (t : (G ⋙ (cocones J C).obj (op K)).obj Y) : ((cocones J D).obj (op (K ⋙ F))).obj Y := { app := λ j, (adj.hom_equiv (K.obj j) Y).symm (t.app j), naturality' := λ j j' f, begin erw [← adj.hom_equiv_naturality_left_symm, ← adj.hom_equiv_naturality_right_symm, t.naturality], dsimp, simp end } /-- When `F ⊣ G`, the functor associating to each `Y` the cocones over `K ⋙ F` with cone point `Y` is naturally isomorphic to the functor associating to each `Y` the cocones over `K` with cone point `G.obj Y`. -/ -- Note: this is natural in K, but we do not yet have the tools to formulate that. def cocones_iso {J : Type v} [small_category J] {K : J ⥤ C} : (cocones J D).obj (op (K ⋙ F)) ≅ G ⋙ ((cocones J C).obj (op K)) := nat_iso.of_components (λ Y, { hom := cocones_iso_component_hom adj Y, inv := cocones_iso_component_inv adj Y, }) (by tidy) /-- auxiliary construction for `cones_iso` -/ @[simps] def cones_iso_component_hom {J : Type v} [small_category J] {K : J ⥤ D} (X : Cᵒᵖ) (t : (functor.op F ⋙ (cones J D).obj K).obj X) : ((cones J C).obj (K ⋙ G)).obj X := { app := λ j, (adj.hom_equiv (unop X) (K.obj j)) (t.app j), naturality' := λ j j' f, begin erw [← adj.hom_equiv_naturality_right, ← t.naturality, category.id_comp, category.id_comp], refl end } /-- auxiliary construction for `cones_iso` -/ @[simps] def cones_iso_component_inv {J : Type v} [small_category J] {K : J ⥤ D} (X : Cᵒᵖ) (t : ((cones J C).obj (K ⋙ G)).obj X) : (functor.op F ⋙ (cones J D).obj K).obj X := { app := λ j, (adj.hom_equiv (unop X) (K.obj j)).symm (t.app j), naturality' := λ j j' f, begin erw [← adj.hom_equiv_naturality_right_symm, ← t.naturality, category.id_comp, category.id_comp] end } -- Note: this is natural in K, but we do not yet have the tools to formulate that. /-- When `F ⊣ G`, the functor associating to each `X` the cones over `K` with cone point `F.op.obj X` is naturally isomorphic to the functor associating to each `X` the cones over `K ⋙ G` with cone point `X`. -/ def cones_iso {J : Type v} [small_category J] {K : J ⥤ D} : F.op ⋙ ((cones J D).obj K) ≅ (cones J C).obj (K ⋙ G) := nat_iso.of_components (λ X, { hom := cones_iso_component_hom adj X, inv := cones_iso_component_inv adj X, } ) (by tidy) end category_theory.adjunction
5f75729e8d7a9341c6532a56cef40738f89491d0
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Elab/Notation.lean
113f2d0c55978534d47645a53851abffbc893b85
[ "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
6,909
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Syntax import Lean.Elab.AuxDef import Lean.Elab.BuiltinNotation namespace Lean.Elab.Command open Lean.Syntax open Lean.Parser.Term hiding macroArg open Lean.Parser.Command /-- Wrap all occurrences of the given `ident` nodes in antiquotations -/ private partial def antiquote (vars : Array Syntax) : Syntax → Syntax | stx => match stx with | `($id:ident) => if (vars.findIdx? (fun var => var.getId == id.getId)).isSome then mkAntiquotNode id (kind := `term) (isPseudoKind := true) else stx | _ => match stx with | Syntax.node i k args => Syntax.node i k (args.map (antiquote vars)) | stx => stx /-- Convert `notation` command lhs item into a `syntax` command item -/ def expandNotationItemIntoSyntaxItem : TSyntax ``notationItem → MacroM (TSyntax `stx) | `(notationItem| $_:ident$[:$prec?]?) => `(stx| term $[:$prec?]?) | `(notationItem| $s:str) => `(stx| $s:str) | _ => Macro.throwUnsupported /-- Convert `notation` command lhs item into a pattern element -/ def expandNotationItemIntoPattern (stx : Syntax) : MacroM Syntax := let k := stx.getKind if k == `Lean.Parser.Command.identPrec then return mkAntiquotNode stx[0] (kind := `term) (isPseudoKind := true) else if k == strLitKind then strLitToPattern stx else Macro.throwUnsupported def removeParenthesesAux (parens body : Syntax) : Syntax := match parens.getHeadInfo, body.getHeadInfo, body.getTailInfo, parens.getTailInfo with | .original lead _ _ _, .original _ pos trail pos', .original endLead endPos _ endPos', .original _ _ endTrail _ => body.setHeadInfo (.original lead pos trail pos') |>.setTailInfo (.original endLead endPos endTrail endPos') | _, _, _, _ => body partial def removeParentheses (stx : Syntax) : MacroM Syntax := do match stx with | `(($e)) => pure $ removeParenthesesAux stx (←removeParentheses $ (←Term.expandCDot? e).getD e) | _ => match stx with | .node info kind args => pure $ .node info kind (←args.mapM removeParentheses) | _ => pure stx partial def hasDuplicateAntiquot (stxs : Array Syntax) : Bool := Id.run do let mut seen := NameSet.empty for stx in stxs do for node in Syntax.topDown stx true do if node.isAntiquot then let ident := node.getAntiquotTerm.getId if seen.contains ident then return true else seen := seen.insert ident pure false /-- Try to derive a `SimpleDelab` from a notation. The notation must be of the form `notation ... => c body` where `c` is a declaration in the current scope and `body` any syntax that contains each variable from the LHS at most once. -/ def mkSimpleDelab (attrKind : TSyntax ``attrKind) (pat qrhs : Term) : OptionT MacroM Syntax := do let (c, args) ← match qrhs with | `($c:ident $args*) => pure (c, args) | `($c:ident) => pure (c, #[]) | _ => failure let [(c, [])] ← Macro.resolveGlobalName c.getId | failure /- Try to remove all non semantic parenthesis. Since the parenthesizer runs after appUnexpanders we should not match on parenthesis that the user syntax inserted here for example the right hand side of: notation "{" x "|" p "}" => setOf (fun x => p) Should be matched as: setOf fun x => p -/ let args ← liftM <| args.mapM removeParentheses /- The user could mention the same antiquotation from the lhs multiple times on the rhs, this heuristic does not support this. -/ guard !hasDuplicateAntiquot args -- replace head constant with antiquotation so we're not dependent on the exact pretty printing of the head -- The reference is attached to the syntactic representation of the called function itself, not the entire function application let lhs ← `($$f:ident) let lhs := Syntax.mkApp lhs (.mk args) `(@[$attrKind appUnexpander $(mkIdent c)] aux_def unexpand $(mkIdent c) : Lean.PrettyPrinter.Unexpander := fun | `($lhs) => withRef f `($pat) -- must be a separate case as the LHS and RHS above might not be `app` nodes | `($lhs $$moreArgs*) => withRef f `($pat $$moreArgs*) | _ => throw ()) private def isLocalAttrKind (attrKind : Syntax) : Bool := match attrKind with | `(Parser.Term.attrKind| local) => true | _ => false private def expandNotationAux (ref : Syntax) (currNamespace : Name) (doc? : Option (TSyntax ``docComment)) (attrs? : Option (TSepArray ``attrInstance ",")) (attrKind : TSyntax ``attrKind) (prec? : Option Prec) (name? : Option Ident) (prio? : Option Prio) (items : Array (TSyntax ``notationItem)) (rhs : Term) : MacroM Syntax := do let prio ← evalOptPrio prio? -- build parser let syntaxParts ← items.mapM expandNotationItemIntoSyntaxItem let cat := mkIdentFrom ref `term let name ← match name? with | some name => pure name.getId | none => mkNameFromParserSyntax `term (mkNullNode syntaxParts) -- build macro rules let vars := items.filter fun item => item.raw.getKind == ``identPrec let vars := vars.map fun var => var.raw[0] let qrhs := ⟨antiquote vars rhs⟩ let patArgs ← items.mapM expandNotationItemIntoPattern /- The command `syntax [<kind>] ...` adds the current namespace to the syntax node kind. So, we must include current namespace when we create a pattern for the following `macro_rules` commands. -/ let fullName := currNamespace ++ name let pat : Term := ⟨mkNode fullName patArgs⟩ let stxDecl ← `($[$doc?:docComment]? $[@[$attrs?,*]]? $attrKind:attrKind syntax $[: $prec?]? (name := $(mkIdent name)) (priority := $(quote prio)) $[$syntaxParts]* : $cat) let macroDecl ← `(macro_rules | `($pat) => ``($qrhs)) let macroDecls ← if isLocalAttrKind attrKind then -- Make sure the quotation pre-checker takes section variables into account for local notation. `(section set_option quotPrecheck.allowSectionVars true $macroDecl end) else pure ⟨mkNullNode #[macroDecl]⟩ match (← mkSimpleDelab attrKind pat qrhs |>.run) with | some delabDecl => return mkNullNode #[stxDecl, macroDecls, delabDecl] | none => return mkNullNode #[stxDecl, macroDecls] @[builtinMacro Lean.Parser.Command.notation] def expandNotation : Macro | stx@`($[$doc?:docComment]? $[@[$attrs?,*]]? $attrKind:attrKind notation $[: $prec?]? $[(name := $name?)]? $[(priority := $prio?)]? $items* => $rhs) => do -- trigger scoped checks early and only once let _ ← toAttributeKind attrKind expandNotationAux stx (← Macro.getCurrNamespace) doc? attrs? attrKind prec? name? prio? items rhs | _ => Macro.throwUnsupported end Lean.Elab.Command
a04b965317c2ff4ad805ceb199938728d0844e23
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/topology/algebra/localization.lean
00b65f616e8dbd23124c2a0c2eda033e15598320
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,287
lean
/- Copyright (c) 2021 María Inés de Frutos-Fernández. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: María Inés de Frutos-Fernández Localization of topological rings. -/ import topology.algebra.ring import ring_theory.localization /-! # Localization of topological rings The topological localization of a topological commutative ring `R` at a submonoid `M` is the ring `localization M` endowed with the final ring topology of the natural homomorphism sending `x : R` to the equivalence class of `(x, 1)` in the localization of `R` at a `M`. ## Main Results - `localization.topological_ring`: The localization of a topological commutative ring at a submonoid is a topological ring. -/ variables {R : Type*} [comm_ring R] [topological_space R] {M : submonoid R} /-- The ring topology on `localization M` coinduced from the natural homomorphism sending `x : R` to the equivalence class of `(x, 1)`. -/ def localization.ring_topology : ring_topology (localization M) := ring_topology.coinduced (localization.monoid_of M).to_fun instance : topological_space (localization M) := localization.ring_topology.to_topological_space instance : topological_ring (localization M) := localization.ring_topology.to_topological_ring
c92f71da7e14d9d5b6519bdd8ff4c4cdf49db5a2
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/linear_algebra/matrix/charpoly/coeff.lean
f92caae53968159d01e2eeb814cda6a5a776e2ba
[ "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
8,806
lean
/- Copyright (c) 2020 Aaron Anderson, Jalex Stark. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Jalex Stark -/ import data.polynomial.expand import linear_algebra.matrix.charpoly.basic /-! # Characteristic polynomials We give methods for computing coefficients of the characteristic polynomial. ## Main definitions - `matrix.charpoly_degree_eq_dim` proves that the degree of the characteristic polynomial over a nonzero ring is the dimension of the matrix - `matrix.det_eq_sign_charpoly_coeff` proves that the determinant is the constant term of the characteristic polynomial, up to sign. - `matrix.trace_eq_neg_charpoly_coeff` proves that the trace is the negative of the (d-1)th coefficient of the characteristic polynomial, where d is the dimension of the matrix. For a nonzero ring, this is the second-highest coefficient. -/ noncomputable theory universes u v w z open polynomial matrix open_locale big_operators polynomial variables {R : Type u} [comm_ring R] variables {n G : Type v} [decidable_eq n] [fintype n] variables {α β : Type v} [decidable_eq α] open finset variable {M : matrix n n R} lemma charmatrix_apply_nat_degree [nontrivial R] (i j : n) : (charmatrix M i j).nat_degree = ite (i = j) 1 0 := by { by_cases i = j; simp [h, ← degree_eq_iff_nat_degree_eq_of_pos (nat.succ_pos 0)], } lemma charmatrix_apply_nat_degree_le (i j : n) : (charmatrix M i j).nat_degree ≤ ite (i = j) 1 0 := by split_ifs; simp [h, nat_degree_X_sub_C_le] namespace matrix variable (M) lemma charpoly_sub_diagonal_degree_lt : (M.charpoly - ∏ (i : n), (X - C (M i i))).degree < ↑(fintype.card n - 1) := begin rw [charpoly, det_apply', ← insert_erase (mem_univ (equiv.refl n)), sum_insert (not_mem_erase (equiv.refl n) univ), add_comm], simp only [charmatrix_apply_eq, one_mul, equiv.perm.sign_refl, id.def, int.cast_one, units.coe_one, add_sub_cancel, equiv.coe_refl], rw ← mem_degree_lt, apply submodule.sum_mem (degree_lt R (fintype.card n - 1)), intros c hc, rw [← C_eq_int_cast, C_mul'], apply submodule.smul_mem (degree_lt R (fintype.card n - 1)) ↑↑(equiv.perm.sign c), rw mem_degree_lt, apply lt_of_le_of_lt degree_le_nat_degree _, rw with_bot.coe_lt_coe, apply lt_of_le_of_lt _ (equiv.perm.fixed_point_card_lt_of_ne_one (ne_of_mem_erase hc)), apply le_trans (polynomial.nat_degree_prod_le univ (λ i : n, (charmatrix M (c i) i))) _, rw card_eq_sum_ones, rw sum_filter, apply sum_le_sum, intros, apply charmatrix_apply_nat_degree_le, end lemma charpoly_coeff_eq_prod_coeff_of_le {k : ℕ} (h : fintype.card n - 1 ≤ k) : M.charpoly.coeff k = (∏ i : n, (X - C (M i i))).coeff k := begin apply eq_of_sub_eq_zero, rw ← coeff_sub, apply polynomial.coeff_eq_zero_of_degree_lt, apply lt_of_lt_of_le (charpoly_sub_diagonal_degree_lt M) _, rw with_bot.coe_le_coe, apply h, end lemma det_of_card_zero (h : fintype.card n = 0) (M : matrix n n R) : M.det = 1 := by { rw fintype.card_eq_zero_iff at h, suffices : M = 1, { simp [this] }, ext i, exact h.elim i } theorem charpoly_degree_eq_dim [nontrivial R] (M : matrix n n R) : M.charpoly.degree = fintype.card n := begin by_cases fintype.card n = 0, { rw h, unfold charpoly, rw det_of_card_zero, {simp}, {assumption} }, rw ← sub_add_cancel M.charpoly (∏ (i : n), (X - C (M i i))), have h1 : (∏ (i : n), (X - C (M i i))).degree = fintype.card n, { rw degree_eq_iff_nat_degree_eq_of_pos, swap, apply nat.pos_of_ne_zero h, rw nat_degree_prod', simp_rw nat_degree_X_sub_C, unfold fintype.card, simp, simp_rw (monic_X_sub_C _).leading_coeff, simp, }, rw degree_add_eq_right_of_degree_lt, exact h1, rw h1, apply lt_trans (charpoly_sub_diagonal_degree_lt M), rw with_bot.coe_lt_coe, rw ← nat.pred_eq_sub_one, apply nat.pred_lt, apply h, end theorem charpoly_nat_degree_eq_dim [nontrivial R] (M : matrix n n R) : M.charpoly.nat_degree = fintype.card n := nat_degree_eq_of_degree_eq_some (charpoly_degree_eq_dim M) lemma charpoly_monic (M : matrix n n R) : M.charpoly.monic := begin nontriviality, by_cases fintype.card n = 0, {rw [charpoly, det_of_card_zero h], apply monic_one}, have mon : (∏ (i : n), (X - C (M i i))).monic, { apply monic_prod_of_monic univ (λ i : n, (X - C (M i i))), simp [monic_X_sub_C], }, rw ← sub_add_cancel (∏ (i : n), (X - C (M i i))) M.charpoly at mon, rw monic at *, rw leading_coeff_add_of_degree_lt at mon, rw ← mon, rw charpoly_degree_eq_dim, rw ← neg_sub, rw degree_neg, apply lt_trans (charpoly_sub_diagonal_degree_lt M), rw with_bot.coe_lt_coe, rw ← nat.pred_eq_sub_one, apply nat.pred_lt, apply h, end theorem trace_eq_neg_charpoly_coeff [nonempty n] (M : matrix n n R) : trace M = -M.charpoly.coeff (fintype.card n - 1) := begin rw charpoly_coeff_eq_prod_coeff_of_le, swap, refl, rw [fintype.card, prod_X_sub_C_coeff_card_pred univ (λ i : n, M i i) fintype.card_pos, neg_neg, trace], refl end -- I feel like this should use polynomial.alg_hom_eval₂_algebra_map lemma mat_poly_equiv_eval (M : matrix n n R[X]) (r : R) (i j : n) : (mat_poly_equiv M).eval ((scalar n) r) i j = (M i j).eval r := begin unfold polynomial.eval, unfold eval₂, transitivity polynomial.sum (mat_poly_equiv M) (λ (e : ℕ) (a : matrix n n R), (a * (scalar n) r ^ e) i j), { unfold polynomial.sum, rw sum_apply, dsimp, refl }, { simp_rw [←ring_hom.map_pow, ←(scalar.commute _ _).eq], simp only [coe_scalar, matrix.one_mul, ring_hom.id_apply, pi.smul_apply, smul_eq_mul, mul_eq_mul, algebra.smul_mul_assoc], have h : ∀ x : ℕ, (λ (e : ℕ) (a : R), r ^ e * a) x 0 = 0 := by simp, simp only [polynomial.sum, mat_poly_equiv_coeff_apply, mul_comm], apply (finset.sum_subset (support_subset_support_mat_poly_equiv _ _ _) _).symm, assume n hn h'n, rw not_mem_support_iff at h'n, simp only [h'n, zero_mul] } end lemma eval_det (M : matrix n n R[X]) (r : R) : polynomial.eval r M.det = (polynomial.eval (scalar n r) (mat_poly_equiv M)).det := begin rw [polynomial.eval, ← coe_eval₂_ring_hom, ring_hom.map_det], apply congr_arg det, ext, symmetry, convert mat_poly_equiv_eval _ _ _ _, end theorem det_eq_sign_charpoly_coeff (M : matrix n n R) : M.det = (-1)^(fintype.card n) * M.charpoly.coeff 0:= begin rw [coeff_zero_eq_eval_zero, charpoly, eval_det, mat_poly_equiv_charmatrix, ← det_smul], simp end end matrix variables {p : ℕ} [fact p.prime] lemma mat_poly_equiv_eq_X_pow_sub_C {K : Type*} (k : ℕ) [field K] (M : matrix n n K) : mat_poly_equiv ((expand K (k) : K[X] →+* K[X]).map_matrix (charmatrix (M ^ k))) = X ^ k - C (M ^ k) := begin ext m, rw [coeff_sub, coeff_C, mat_poly_equiv_coeff_apply, ring_hom.map_matrix_apply, matrix.map_apply, alg_hom.coe_to_ring_hom, dmatrix.sub_apply, coeff_X_pow], by_cases hij : i = j, { rw [hij, charmatrix_apply_eq, alg_hom.map_sub, expand_C, expand_X, coeff_sub, coeff_X_pow, coeff_C], split_ifs with mp m0; simp only [matrix.one_apply_eq, dmatrix.zero_apply] }, { rw [charmatrix_apply_ne _ _ _ hij, alg_hom.map_neg, expand_C, coeff_neg, coeff_C], split_ifs with m0 mp; simp only [hij, zero_sub, dmatrix.zero_apply, sub_zero, neg_zero, matrix.one_apply_ne, ne.def, not_false_iff] } end namespace matrix /-- Any matrix polynomial `p` is equivalent under evaluation to `p %ₘ M.charpoly`; that is, `p` is equivalent to a polynomial with degree less than the dimension of the matrix. -/ lemma aeval_eq_aeval_mod_charpoly (M : matrix n n R) (p : R[X]) : aeval M p = aeval M (p %ₘ M.charpoly) := (aeval_mod_by_monic_eq_self_of_root M.charpoly_monic M.aeval_self_charpoly).symm /-- Any matrix power can be computed as the sum of matrix powers less than `fintype.card n`. TODO: add the statement for negative powers phrased with `zpow`. -/ lemma pow_eq_aeval_mod_charpoly (M : matrix n n R) (k : ℕ) : M^k = aeval M (X^k %ₘ M.charpoly) := by rw [←aeval_eq_aeval_mod_charpoly, map_pow, aeval_X] end matrix section ideal lemma coeff_charpoly_mem_ideal_pow {I : ideal R} (h : ∀ i j, M i j ∈ I) (k : ℕ) : M.charpoly.coeff k ∈ I ^ (fintype.card n - k) := begin delta charpoly, rw [matrix.det_apply, finset_sum_coeff], apply sum_mem, rintro c -, rw [coeff_smul, submodule.smul_mem_iff'], have : ∑ (x : n), 1 = fintype.card n := by rw [finset.sum_const, card_univ, smul_eq_mul, mul_one], rw ← this, apply coeff_prod_mem_ideal_pow_tsub, rintro i - (_|k), { rw [tsub_zero, pow_one, charmatrix_apply, coeff_sub, coeff_X_mul_zero, coeff_C_zero, zero_sub, neg_mem_iff], exact h (c i) i }, { rw [nat.succ_eq_one_add, tsub_self_add, pow_zero, ideal.one_eq_top], exact submodule.mem_top } end end ideal
2c108a1c91b9dd36eb8c551694687ac2396d2d3b
82e44445c70db0f03e30d7be725775f122d72f3e
/src/combinatorics/colex.lean
837914171e729bb3ab159752526102a63ef755d0
[ "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
15,029
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Alena Gusakov -/ import data.finset import data.fintype.basic import algebra.geom_sum /-! # Colex We define the colex ordering for finite sets, and give a couple of important lemmas and properties relating to it. The colex ordering likes to avoid large values - it can be thought of on `finset ℕ` as the "binary" ordering. That is, order A based on `∑_{i ∈ A} 2^i`. It's defined here in a slightly more general way, requiring only `has_lt α` in the definition of colex on `finset α`. In the context of the Kruskal-Katona theorem, we are interested in particular on how colex behaves for sets of a fixed size. If the size is 3, colex on ℕ starts 123, 124, 134, 234, 125, 135, 235, 145, 245, 345, ... ## Main statements * `colex.hom_lt_iff`: strictly monotone functions preserve colex * Colex order properties - linearity, decidability and so on. * `forall_lt_of_colex_lt_of_forall_lt`: if A < B in colex, and everything in B is < t, then everything in A is < t. This confirms the idea that an enumeration under colex will exhaust all sets using elements < t before allowing t to be included. * `sum_two_pow_le_iff_lt`: colex for α = ℕ is the same as binary (this also proves binary expansions are unique) ## Notation We define `<` and `≤` to denote colex ordering, useful in particular when multiple orderings are available in context. ## Tags colex, colexicographic, binary ## References * https://github.com/b-mehta/maths-notes/blob/master/iii/mich/combinatorics.pdf -/ variable {α : Type*} open finset open_locale big_operators /-- We define this type synonym to refer to the colexicographic ordering on finsets rather than the natural subset ordering. -/ @[derive inhabited] def finset.colex (α) := finset α /-- A convenience constructor to turn a `finset α` into a `finset.colex α`, useful in order to use the colex ordering rather than the subset ordering. -/ def finset.to_colex {α} (s : finset α) : finset.colex α := s @[simp] lemma colex.eq_iff (A B : finset α) : A.to_colex = B.to_colex ↔ A = B := iff.rfl /-- `A` is less than `B` in the colex ordering if the largest thing that's not in both sets is in B. In other words, max (A Δ B) ∈ B (if the maximum exists). -/ instance [has_lt α] : has_lt (finset.colex α) := ⟨λ (A B : finset α), ∃ (k : α), (∀ {x}, k < x → (x ∈ A ↔ x ∈ B)) ∧ k ∉ A ∧ k ∈ B⟩ /-- We can define (≤) in the obvious way. -/ instance [has_lt α] : has_le (finset.colex α) := ⟨λ A B, A < B ∨ A = B⟩ lemma colex.lt_def [has_lt α] (A B : finset α) : A.to_colex < B.to_colex ↔ ∃ k, (∀ {x}, k < x → (x ∈ A ↔ x ∈ B)) ∧ k ∉ A ∧ k ∈ B := iff.rfl lemma colex.le_def [has_lt α] (A B : finset α) : A.to_colex ≤ B.to_colex ↔ A.to_colex < B.to_colex ∨ A = B := iff.rfl /-- If everything in `A` is less than `k`, we can bound the sum of powers. -/ lemma nat.sum_two_pow_lt {k : ℕ} {A : finset ℕ} (h₁ : ∀ {x}, x ∈ A → x < k) : A.sum (pow 2) < 2^k := begin apply lt_of_le_of_lt (sum_le_sum_of_subset (λ t, mem_range.2 ∘ h₁)), have z := geom_sum_mul_add 1 k, rw [geom_sum, mul_one, one_add_one_eq_two] at z, rw ← z, apply nat.lt_succ_self, end namespace colex /-- Strictly monotone functions preserve the colex ordering. -/ lemma hom_lt_iff {β : Type*} [linear_order α] [decidable_eq β] [preorder β] {f : α → β} (h₁ : strict_mono f) (A B : finset α) : (A.image f).to_colex < (B.image f).to_colex ↔ A.to_colex < B.to_colex := begin simp only [colex.lt_def, not_exists, mem_image, exists_prop, not_and], split, { rintro ⟨k, z, q, k', _, rfl⟩, exact ⟨k', λ x hx, by simpa [h₁.injective.eq_iff] using z (h₁ hx), λ t, q _ t rfl, ‹k' ∈ B›⟩ }, rintro ⟨k, z, ka, _⟩, refine ⟨f k, λ x hx, _, _, k, ‹k ∈ B›, rfl⟩, { split, any_goals { rintro ⟨x', hx', rfl⟩, refine ⟨x', _, rfl⟩, rwa ← z _ <|> rwa z _, rwa strict_mono.lt_iff_lt h₁ at hx } }, { simp only [h₁.injective, function.injective.eq_iff], exact λ x hx, ne_of_mem_of_not_mem hx ka } end /-- A special case of `colex.hom_lt_iff` which is sometimes useful. -/ @[simp] lemma hom_fin_lt_iff {n : ℕ} (A B : finset (fin n)) : (A.image (λ i : fin n, (i : ℕ))).to_colex < (B.image (λ i : fin n, (i : ℕ))).to_colex ↔ A.to_colex < B.to_colex := colex.hom_lt_iff (λ x y k, k) _ _ instance [has_lt α] : is_irrefl (finset.colex α) (<) := ⟨λ A h, exists.elim h (λ _ ⟨_,a,b⟩, a b)⟩ @[trans] lemma lt_trans [linear_order α] {a b c : finset.colex α} : a < b → b < c → a < c := begin rintros ⟨k₁, k₁z, notinA, inB⟩ ⟨k₂, k₂z, notinB, inC⟩, cases lt_or_gt_of_ne (ne_of_mem_of_not_mem inB notinB), { refine ⟨k₂, _, by rwa k₁z h, inC⟩, intros x hx, rw ← k₂z hx, apply k₁z (trans h hx) }, { refine ⟨k₁, _, notinA, by rwa ← k₂z h⟩, intros x hx, rw k₁z hx, apply k₂z (trans h hx) } end @[trans] lemma le_trans [linear_order α] (a b c : finset.colex α) : a ≤ b → b ≤ c → a ≤ c := λ AB BC, AB.elim (λ k, BC.elim (λ t, or.inl (lt_trans k t)) (λ t, t ▸ AB)) (λ k, k.symm ▸ BC) instance [linear_order α] : is_trans (finset.colex α) (<) := ⟨λ _ _ _, colex.lt_trans⟩ lemma lt_trichotomy [linear_order α] (A B : finset.colex α) : A < B ∨ A = B ∨ B < A := begin by_cases h₁ : (A = B), { tauto }, rcases (exists_max_image (A \ B ∪ B \ A) id _) with ⟨k, hk, z⟩, { simp only [mem_union, mem_sdiff] at hk, cases hk, { right, right, refine ⟨k, λ t th, _, hk.2, hk.1⟩, specialize z t, by_contra h₂, simp only [mem_union, mem_sdiff, id.def] at z, rw [not_iff, iff_iff_and_or_not_and_not, not_not, and_comm] at h₂, apply not_le_of_lt th (z h₂) }, { left, refine ⟨k, λ t th, _, hk.2, hk.1⟩, specialize z t, by_contra h₃, simp only [mem_union, mem_sdiff, id.def] at z, rw [not_iff, iff_iff_and_or_not_and_not, not_not, and_comm, or_comm] at h₃, apply not_le_of_lt th (z h₃) }, }, rw nonempty_iff_ne_empty, intro a, simp only [union_eq_empty_iff, sdiff_eq_empty_iff_subset] at a, apply h₁ (subset.antisymm a.1 a.2) end instance [linear_order α] : is_trichotomous (finset.colex α) (<) := ⟨lt_trichotomy⟩ instance decidable_lt [linear_order α] : ∀ {A B : finset.colex α}, decidable (A < B) := show ∀ A B : finset α, decidable (A.to_colex < B.to_colex), from λ A B, decidable_of_iff' (∃ (k ∈ B), (∀ x ∈ A ∪ B, k < x → (x ∈ A ↔ x ∈ B)) ∧ k ∉ A) begin rw colex.lt_def, apply exists_congr, simp only [mem_union, exists_prop, or_imp_distrib, and_comm (_ ∈ B), and_assoc], intro k, refine and_congr_left' (forall_congr _), tauto, end instance [linear_order α] : linear_order (finset.colex α) := { le_refl := λ A, or.inr rfl, le_trans := le_trans, le_antisymm := λ A B AB BA, AB.elim (λ k, BA.elim (λ t, (asymm k t).elim) (λ t, t.symm)) id, le_total := λ A B, (lt_trichotomy A B).elim3 (or.inl ∘ or.inl) (or.inl ∘ or.inr) (or.inr ∘ or.inl), decidable_le := λ A B, by apply_instance, decidable_lt := λ A B, by apply_instance, decidable_eq := λ A B, by apply_instance, lt_iff_le_not_le := λ A B, begin split, { intro t, refine ⟨or.inl t, _⟩, rintro (i | rfl), { apply asymm_of _ t i }, { apply irrefl _ t } }, rintro ⟨h₁ | rfl, h₂⟩, { apply h₁ }, apply h₂.elim (or.inr rfl), end, ..finset.colex.has_lt, ..finset.colex.has_le } /-- The instances set up let us infer that `colex.lt` is a strict total order. -/ example [linear_order α] : is_strict_total_order (finset.colex α) (<) := infer_instance /-- Strictly monotone functions preserve the colex ordering. -/ lemma hom_le_iff {β : Type*} [linear_order α] [linear_order β] {f : α → β} (h₁ : strict_mono f) (A B : finset α) : (A.image f).to_colex ≤ (B.image f).to_colex ↔ A.to_colex ≤ B.to_colex := by rw [le_iff_le_iff_lt_iff_lt, hom_lt_iff h₁] /-- A special case of `colex_hom` which is sometimes useful. -/ @[simp] lemma hom_fin_le_iff {n : ℕ} (A B : finset (fin n)) : (A.image (λ i : fin n, (i : ℕ))).to_colex ≤ (B.image (λ i : fin n, (i : ℕ))).to_colex ↔ A.to_colex ≤ B.to_colex := colex.hom_le_iff (λ x y k, k) _ _ /-- If `A` is before `B` in colex, and everything in `B` is small, then everything in `A` is small. -/ lemma forall_lt_of_colex_lt_of_forall_lt [linear_order α] {A B : finset α} (t : α) (h₁ : A.to_colex < B.to_colex) (h₂ : ∀ x ∈ B, x < t) : ∀ x ∈ A, x < t := begin rw colex.lt_def at h₁, rcases h₁ with ⟨k, z, _, _⟩, intros x hx, apply lt_of_not_ge, intro a, refine not_lt_of_ge a (h₂ x _), rwa ← z, apply lt_of_lt_of_le (h₂ k ‹_›) a, end /-- `s.to_colex < {r}.to_colex` iff all elements of `s` are less than `r`. -/ lemma lt_singleton_iff_mem_lt [linear_order α] {r : α} {s : finset α} : s.to_colex < ({r} : finset α).to_colex ↔ ∀ x ∈ s, x < r := begin simp only [lt_def, mem_singleton, ←and_assoc, exists_eq_right], split, { intros t x hx, rw ←not_le, intro h, rcases lt_or_eq_of_le h with h₁ | rfl, { exact ne_of_irrefl h₁ ((t.1 h₁).1 hx).symm }, { exact t.2 hx } }, { exact λ h, ⟨λ z hz, ⟨λ i, (asymm hz (h _ i)).elim, λ i, (hz.ne' i).elim⟩, by simpa using h r⟩ } end /-- If {r} is less than or equal to s in the colexicographical sense, then s contains an element greater than or equal to r. -/ lemma mem_le_of_singleton_le [linear_order α] {r : α} {s : finset α}: ({r} : finset α).to_colex ≤ s.to_colex ↔ ∃ x ∈ s, r ≤ x := by { rw ←not_lt, simp [lt_singleton_iff_mem_lt] } /-- Colex is an extension of the base ordering on α. -/ lemma singleton_lt_iff_lt [linear_order α] {r s : α} : ({r} : finset α).to_colex < ({s} : finset α).to_colex ↔ r < s := by simp [lt_singleton_iff_mem_lt] /-- Colex is an extension of the base ordering on α. -/ lemma singleton_le_iff_le [linear_order α] {r s : α} : ({r} : finset α).to_colex ≤ ({s} : finset α).to_colex ↔ r ≤ s := by rw [le_iff_le_iff_lt_iff_lt, singleton_lt_iff_lt] /-- Colex doesn't care if you remove the other set -/ @[simp] lemma sdiff_lt_sdiff_iff_lt [has_lt α] [decidable_eq α] (A B : finset α) : (A \ B).to_colex < (B \ A).to_colex ↔ A.to_colex < B.to_colex := begin rw [colex.lt_def, colex.lt_def], apply exists_congr, intro k, simp only [mem_sdiff, not_and, not_not], split, { rintro ⟨z, kAB, kB, kA⟩, refine ⟨_, kA, kB⟩, { intros x hx, specialize z hx, tauto } }, { rintro ⟨z, kA, kB⟩, refine ⟨_, λ _, kB, kB, kA⟩, intros x hx, rw z hx }, end /-- Colex doesn't care if you remove the other set -/ @[simp] lemma sdiff_le_sdiff_iff_le [linear_order α] (A B : finset α) : (A \ B).to_colex ≤ (B \ A).to_colex ↔ A.to_colex ≤ B.to_colex := by rw [le_iff_le_iff_lt_iff_lt, sdiff_lt_sdiff_iff_lt] lemma empty_to_colex_lt [linear_order α] {A : finset α} (hA : A.nonempty) : (∅ : finset α).to_colex < A.to_colex := begin rw [colex.lt_def], refine ⟨max' _ hA, _, by simp, max'_mem _ _⟩, simp only [false_iff, not_mem_empty], intros x hx t, apply not_le_of_lt hx (le_max' _ _ t), end /-- If `A ⊂ B`, then `A` is less than `B` in the colex order. Note the converse does not hold, as `⊆` is not a linear order. -/ lemma colex_lt_of_ssubset [linear_order α] {A B : finset α} (h : A ⊂ B) : A.to_colex < B.to_colex := begin rw [←sdiff_lt_sdiff_iff_lt, sdiff_eq_empty_iff_subset.2 h.1], exact empty_to_colex_lt (by simpa [finset.nonempty] using exists_of_ssubset h), end @[simp] lemma empty_to_colex_le [linear_order α] {A : finset α} : (∅ : finset α).to_colex ≤ A.to_colex := begin rcases A.eq_empty_or_nonempty with rfl | hA, { simp }, { apply (empty_to_colex_lt hA).le }, end /-- If `A ⊆ B`, then `A ≤ B` in the colex order. Note the converse does not hold, as `⊆` is not a linear order. -/ lemma colex_le_of_subset [linear_order α] {A B : finset α} (h : A ⊆ B) : A.to_colex ≤ B.to_colex := begin rw [←sdiff_le_sdiff_iff_le, sdiff_eq_empty_iff_subset.2 h], apply empty_to_colex_le end /-- The function from finsets to finsets with the colex order is a relation homomorphism. -/ @[simps] def to_colex_rel_hom [linear_order α] : ((⊆) : finset α → finset α → Prop) →r ((≤) : finset.colex α → finset.colex α → Prop) := { to_fun := finset.to_colex, map_rel' := λ A B, colex_le_of_subset } instance [linear_order α] : order_bot (finset.colex α) := { bot := (∅ : finset α).to_colex, bot_le := λ x, empty_to_colex_le, ..(by apply_instance : partial_order (finset.colex α)) } instance [linear_order α] : semilattice_inf_bot (finset.colex α) := { ..finset.colex.order_bot, ..(by apply_instance : semilattice_inf (finset.colex α)) } instance [linear_order α] : semilattice_sup_bot (finset.colex α) := { ..finset.colex.order_bot, ..(by apply_instance : semilattice_sup (finset.colex α)) } instance [linear_order α] [fintype α] : bounded_lattice (finset.colex α) := { top := finset.univ.to_colex, le_top := λ x, colex_le_of_subset (subset_univ _), ..(by apply_instance : semilattice_sup (finset.colex α)), ..(by apply_instance : semilattice_inf_bot (finset.colex α)) } /-- For subsets of ℕ, we can show that colex is equivalent to binary. -/ lemma sum_two_pow_lt_iff_lt (A B : finset ℕ) : ∑ i in A, 2^i < ∑ i in B, 2^i ↔ A.to_colex < B.to_colex := begin have z : ∀ (A B : finset ℕ), A.to_colex < B.to_colex → ∑ i in A, 2^i < ∑ i in B, 2^i, { intros A B, rw [← sdiff_lt_sdiff_iff_lt, colex.lt_def], rintro ⟨k, z, kA, kB⟩, rw ← sdiff_union_inter A B, conv_rhs { rw ← sdiff_union_inter B A }, rw [sum_union (disjoint_sdiff_inter _ _), sum_union (disjoint_sdiff_inter _ _), inter_comm, add_lt_add_iff_right], apply lt_of_lt_of_le (@nat.sum_two_pow_lt k (A \ B) _), { apply single_le_sum (λ _ _, nat.zero_le _) kB }, intros x hx, apply lt_of_le_of_ne (le_of_not_lt (λ kx, _)), { apply (ne_of_mem_of_not_mem hx kA) }, have := (z kx).1 hx, rw mem_sdiff at this hx, exact hx.2 this.1 }, refine ⟨λ h, (lt_trichotomy A B).resolve_right (λ h₁, h₁.elim _ (not_lt_of_gt h ∘ z _ _)), z A B⟩, rintro rfl, apply irrefl _ h end /-- For subsets of ℕ, we can show that colex is equivalent to binary. -/ lemma sum_two_pow_le_iff_lt (A B : finset ℕ) : ∑ i in A, 2^i ≤ ∑ i in B, 2^i ↔ A.to_colex ≤ B.to_colex := by rw [le_iff_le_iff_lt_iff_lt, sum_two_pow_lt_iff_lt] end colex
55619d581e1df0063ce80019001196583301b24b
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/import_middle.lean
2e04148c1af059b8894196f0ac0b5ff0867e1c92
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
50
lean
import data.set print "hello" import data.tuple
12a90f31a18c27439bd7b3888fc5c185a1431bf1
6b10c15e653d49d146378acda9f3692e9b5b1950
/examples/logic/unnamed_269.lean
7becfddb2ea9cc60d8ccab7666ef6c7627bcf691
[]
no_license
gebner/mathematics_in_lean
3cf7f18767208ea6c3307ec3a67c7ac266d8514d
6d1462bba46d66a9b948fc1aef2714fd265cde0b
refs/heads/master
1,655,301,945,565
1,588,697,505,000
1,588,697,505,000
261,523,603
0
0
null
1,588,695,611,000
1,588,695,610,000
null
UTF-8
Lean
false
false
125
lean
variables A B : Prop -- BEGIN example : A ∧ B → B ∧ A := begin intro h, split, apply h.2, apply h.1 end -- END
ef9b16a31e9e5006d3e9d3d3a09bb696abf95b5b
5756a081670ba9c1d1d3fca7bd47cb4e31beae66
/Mathport/Util/Json.lean
996bc2be066a64ec6719a9ba0fdf546d45b97523
[ "Apache-2.0" ]
permissive
leanprover-community/mathport
2c9bdc8292168febf59799efdc5451dbf0450d4a
13051f68064f7638970d39a8fecaede68ffbf9e1
refs/heads/master
1,693,841,364,079
1,693,813,111,000
1,693,813,111,000
379,357,010
27
10
Apache-2.0
1,691,309,132,000
1,624,384,521,000
Lean
UTF-8
Lean
false
false
1,387
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Daniel Selsam -/ import Lean import Mathport.Util.String open Lean Lean.Json open System (FilePath) instance : FromJson FilePath where fromJson? json := do let s : String ← fromJson? json pure ⟨s⟩ instance : FromJson Position where fromJson? | Json.arr #[line, col] => return ⟨← fromJson? line, ← fromJson? col⟩ | _ => throw "expected array with two elements" instance : FromJson Unit := ⟨fun _ => pure ()⟩ instance {α : Type u} {β : Type v} [FromJson α] [FromJson β] : FromJson (Sum α β) := ⟨fun j => (fromJson? j).map Sum.inl <|> (@fromJson? β _ j).map Sum.inr⟩ open Lean.Json in instance [FromJson α] [BEq α] [Hashable α] : FromJson (Lean.HashSet α) where fromJson? json := do let Structured.arr elems ← fromJson? json | throw "JSON array expected" elems.foldlM (init := {}) fun acc x => return acc.insert (← fromJson? x) open Lean.Json in instance [FromJson α] [BEq α] [Hashable α] [FromJson β] : FromJson (Lean.HashMap α β) where fromJson? json := do let Structured.obj kvs ← fromJson? json | throw "JSON obj expected" kvs.foldM (init := {}) fun acc (k : String) v => return acc.insert (← fromJson? k) (← fromJson? v)
49e94e8e424c5ba6433db8cb9457accc8e413a9a
92b50235facfbc08dfe7f334827d47281471333b
/tests/lean/run/tactic28.lean
0f1e51c7f1063e7e78146ca7c1aab728f98adf5b
[ "Apache-2.0" ]
permissive
htzh/lean
24f6ed7510ab637379ec31af406d12584d31792c
d70c79f4e30aafecdfc4a60b5d3512199200ab6e
refs/heads/master
1,607,677,731,270
1,437,089,952,000
1,437,089,952,000
37,078,816
0
0
null
1,433,780,956,000
1,433,780,955,000
null
UTF-8
Lean
false
false
921
lean
import logic data.num open tactic inhabited namespace foo inductive sum (A : Type) (B : Type) : Type := | inl : A → sum A B | inr : B → sum A B theorem inl_inhabited {A : Type} (B : Type) (H : inhabited A) : inhabited (sum A B) := inhabited.destruct H (λ a, inhabited.mk (sum.inl B a)) theorem inr_inhabited (A : Type) {B : Type} (H : inhabited B) : inhabited (sum A B) := inhabited.destruct H (λ b, inhabited.mk (sum.inr A b)) infixl `..`:10 := append notation `(` h `|` r:(foldl `|` (e r, tactic.or_else r e) h) `)` := r infixl `;`:15 := tactic.and_then definition my_tac := repeat (trace "iteration"; state; ( apply @inl_inhabited; trace "used inl" .. apply @inr_inhabited; trace "used inr" .. apply @num.is_inhabited; trace "used num")) ; now tactic_hint my_tac theorem T : inhabited (sum false num) end foo
d8e77c5144739971a76266b9e4af935f733b1b8d
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/tauto.lean
7bd627e1dec77278a0c7214ff3aa36596cf97be3
[ "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,648
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import tactic.hint namespace tactic open expr open tactic.interactive ( casesm constructor_matching ) /-- find all assumptions of the shape `¬ (p ∧ q)` or `¬ (p ∨ q)` and replace them using de Morgan's law. -/ meta def distrib_not : tactic unit := do hs ← local_context, hs.for_each $ λ h, all_goals' $ iterate_at_most' 3 $ do h ← get_local h.local_pp_name, e ← infer_type h, match e with | `(¬ _ = _) := replace h.local_pp_name ``(mt iff.to_eq %%h) | `(_ ≠ _) := replace h.local_pp_name ``(mt iff.to_eq %%h) | `(_ = _) := replace h.local_pp_name ``(eq.to_iff %%h) | `(¬ (_ ∧ _)) := replace h.local_pp_name ``(decidable.not_and_distrib'.mp %%h) <|> replace h.local_pp_name ``(decidable.not_and_distrib.mp %%h) | `(¬ (_ ∨ _)) := replace h.local_pp_name ``(not_or_distrib.mp %%h) | `(¬ _ ≠ _) := replace h.local_pp_name ``(decidable.of_not_not %%h) | `(¬ ¬ _) := replace h.local_pp_name ``(decidable.of_not_not %%h) | `(¬ (_ → (_ : Prop))) := replace h.local_pp_name ``(decidable.not_imp.mp %%h) | `(¬ (_ ↔ _)) := replace h.local_pp_name ``(decidable.not_iff.mp %%h) | `(_ ↔ _) := replace h.local_pp_name ``(decidable.iff_iff_and_or_not_and_not.mp %%h) <|> replace h.local_pp_name ``(decidable.iff_iff_and_or_not_and_not.mp (%%h).symm) <|> () <$ tactic.cases h | `(_ → _) := replace h.local_pp_name ``(decidable.not_or_of_imp %%h) | _ := failed end /-! The following definitions maintain a path compression datastructure, i.e. a forest such that: - every node is the type of a hypothesis - there is a edge between two nodes only if they are provably equivalent - every edge is labelled with a proof of equivalence for its vertices - edges are added when normalizing propositions. -/ meta def tauto_state := ref $ expr_map (option (expr × expr)) meta def modify_ref {α : Type} (r : ref α) (f : α → α) := read_ref r >>= write_ref r ∘ f meta def add_refl (r : tauto_state) (e : expr) : tactic (expr × expr) := do m ← read_ref r, p ← mk_mapp `rfl [none,e], write_ref r $ m.insert e none, return (e,p) /-- If there exists a symmetry lemma that can be applied to the hypothesis `e`, store it. -/ meta def add_symm_proof (r : tauto_state) (e : expr) : tactic (expr × expr) := do env ← get_env, let rel := e.get_app_fn.const_name, some symm ← pure $ environment.symm_for env rel | add_refl r e, (do e' ← mk_meta_var `(Prop), iff_t ← to_expr ``(%%e = %%e'), (_,p) ← solve_aux iff_t (applyc `iff.to_eq ; () <$ split ; applyc symm), e' ← instantiate_mvars e', m ← read_ref r, write_ref r $ (m.insert e (e',p)).insert e' none, return (e',p) ) <|> add_refl r e meta def add_edge (r : tauto_state) (x y p : expr) : tactic unit := modify_ref r $ λ m, m.insert x (y,p) /-- Retrieve the root of the hypothesis `e` from the proof forest. If `e` has not been internalized, add it to the proof forest. -/ meta def root (r : tauto_state) : expr → tactic (expr × expr) | e := do m ← read_ref r, let record_e : tactic (expr × expr) := match e with | v@(expr.mvar _ _ _) := (do (e,p) ← get_assignment v >>= root, add_edge r v e p, return (e,p)) <|> add_refl r e | _ := add_refl r e end, some e' ← pure $ m.find e | record_e, match e' with | (some (e',p')) := do (e'',p'') ← root e', p'' ← mk_app `eq.trans [p',p''], add_edge r e e'' p'', pure (e'',p'') | none := prod.mk e <$> mk_mapp `rfl [none,some e] end /-- Given hypotheses `a` and `b`, build a proof that `a` is equivalent to `b`, applying congruence and recursing into arguments if `a` and `b` are applications of function symbols. -/ meta def symm_eq (r : tauto_state) : expr → expr → tactic expr | a b := do m ← read_ref r, (a',pa) ← root r a, (b',pb) ← root r b, (unify a' b' >> add_refl r a' *> mk_mapp `rfl [none,a]) <|> do p ← match (a', b') with | (`(¬ %%a₀), `(¬ %%b₀)) := do p ← symm_eq a₀ b₀, p' ← mk_app `congr_arg [`(not),p], add_edge r a' b' p', return p' | (`(%%a₀ ∧ %%a₁), `(%%b₀ ∧ %%b₁)) := do p₀ ← symm_eq a₀ b₀, p₁ ← symm_eq a₁ b₁, p' ← to_expr ``(congr (congr_arg and %%p₀) %%p₁), add_edge r a' b' p', return p' | (`(%%a₀ ∨ %%a₁), `(%%b₀ ∨ %%b₁)) := do p₀ ← symm_eq a₀ b₀, p₁ ← symm_eq a₁ b₁, p' ← to_expr ``(congr (congr_arg or %%p₀) %%p₁), add_edge r a' b' p', return p' | (`(%%a₀ ↔ %%a₁), `(%%b₀ ↔ %%b₁)) := (do p₀ ← symm_eq a₀ b₀, p₁ ← symm_eq a₁ b₁, p' ← to_expr ``(congr (congr_arg iff %%p₀) %%p₁), add_edge r a' b' p', return p') <|> do p₀ ← symm_eq a₀ b₁, p₁ ← symm_eq a₁ b₀, p' ← to_expr ``(eq.trans (congr (congr_arg iff %%p₀) %%p₁) (iff.to_eq iff.comm ) ), add_edge r a' b' p', return p' | (`(%%a₀ → %%a₁), `(%%b₀ → %%b₁)) := if ¬ a₁.has_var ∧ ¬ b₁.has_var then do p₀ ← symm_eq a₀ b₀, p₁ ← symm_eq a₁ b₁, p' ← mk_app `congr_arg [`(implies),p₀,p₁], add_edge r a' b' p', return p' else unify a' b' >> add_refl r a' *> mk_mapp `rfl [none,a] | (_, _) := (do guard $ a'.get_app_fn.is_constant ∧ a'.get_app_fn.const_name = b'.get_app_fn.const_name, (a'',pa') ← add_symm_proof r a', guard $ a'' =ₐ b', pure pa' ) end, p' ← mk_eq_trans pa p, add_edge r a' b' p', mk_eq_symm pb >>= mk_eq_trans p' meta def find_eq_type (r : tauto_state) : expr → list expr → tactic (expr × expr) | e [] := failed | e (H :: Hs) := do t ← infer_type H, (prod.mk H <$> symm_eq r e t) <|> find_eq_type e Hs private meta def contra_p_not_p (r : tauto_state) : list expr → list expr → tactic unit | [] Hs := failed | (H1 :: Rs) Hs := do t ← (extract_opt_auto_param <$> infer_type H1) >>= whnf, (do a ← match_not t, (H2,p) ← find_eq_type r a Hs, H2 ← to_expr ``( (%%p).mpr %%H2 ), tgt ← target, pr ← mk_app `absurd [tgt, H2, H1], tactic.exact pr) <|> contra_p_not_p Rs Hs meta def contradiction_with (r : tauto_state) : tactic unit := contradiction <|> do tactic.try intro1, ctx ← local_context, contra_p_not_p r ctx ctx meta def contradiction_symm := using_new_ref (native.rb_map.mk _ _) contradiction_with meta def assumption_with (r : tauto_state) : tactic unit := do { ctx ← local_context, t ← target, (H,p) ← find_eq_type r t ctx, mk_eq_mpr p H >>= tactic.exact } <|> fail "assumption tactic failed" meta def assumption_symm := using_new_ref (native.rb_map.mk _ _) assumption_with /-- Configuration options for `tauto`. If `classical` is `tt`, runs `classical` before the rest of `tauto`. `closer` is run on any remaining subgoals left by `tauto_core; basic_tauto_tacs`. -/ meta structure tauto_cfg := (classical : bool := ff) (closer : tactic unit := pure ()) meta def tautology (cfg : tauto_cfg := {}) : tactic unit := focus1 $ let basic_tauto_tacs : list (tactic unit) := [reflexivity, solve_by_elim, constructor_matching none [``(_ ∧ _),``(_ ↔ _),``(Exists _),``(true)]], tauto_core (r : tauto_state) : tactic unit := do try (contradiction_with r); try (assumption_with r); repeat (do gs ← get_goals, repeat (() <$ tactic.intro1); distrib_not; casesm (some ()) [``(_ ∧ _),``(_ ∨ _),``(Exists _),``(false)]; try (contradiction_with r); try (target >>= match_or >> refine ``( or_iff_not_imp_left.mpr _)); try (target >>= match_or >> refine ``( or_iff_not_imp_right.mpr _)); repeat (() <$ tactic.intro1); constructor_matching (some ()) [``(_ ∧ _),``(_ ↔ _),``(true)]; try (assumption_with r), gs' ← get_goals, guard (gs ≠ gs') ) in do when cfg.classical (classical tt), using_new_ref (expr_map.mk _) tauto_core; repeat (first basic_tauto_tacs); cfg.closer, done namespace interactive local postfix (name := parser.optional) `?`:9001 := optional setup_tactic_parser /-- `tautology` breaks down assumptions of the form `_ ∧ _`, `_ ∨ _`, `_ ↔ _` and `∃ _, _` and splits a goal of the form `_ ∧ _`, `_ ↔ _` or `∃ _, _` until it can be discharged using `reflexivity` or `solve_by_elim`. This is a finishing tactic: it either closes the goal or raises an error. The variant `tautology!` uses the law of excluded middle. `tautology {closer := tac}` will use `tac` on any subgoals created by `tautology` that it is unable to solve before failing. -/ meta def tautology (c : parse $ (tk "!")?) (cfg : tactic.tauto_cfg := {}) := tactic.tautology $ { classical := c.is_some, ..cfg } -- Now define a shorter name for the tactic `tautology`. /-- `tauto` breaks down assumptions of the form `_ ∧ _`, `_ ∨ _`, `_ ↔ _` and `∃ _, _` and splits a goal of the form `_ ∧ _`, `_ ↔ _` or `∃ _, _` until it can be discharged using `reflexivity` or `solve_by_elim`. This is a finishing tactic: it either closes the goal or raises an error. The variant `tauto!` uses the law of excluded middle. `tauto {closer := tac}` will use `tac` on any subgoals created by `tauto` that it is unable to solve before failing. -/ meta def tauto (c : parse $ (tk "!")?) (cfg : tactic.tauto_cfg := {}) : tactic unit := tautology c cfg add_hint_tactic "tauto" /-- This tactic (with shorthand `tauto`) breaks down assumptions of the form `_ ∧ _`, `_ ∨ _`, `_ ↔ _` and `∃ _, _` and splits a goal of the form `_ ∧ _`, `_ ↔ _` or `∃ _, _` until it can be discharged using `reflexivity` or `solve_by_elim`. This is a finishing tactic: it either closes the goal or raises an error. The variants `tautology!` and `tauto!` use the law of excluded middle. For instance, one can write: ```lean example (p q r : Prop) [decidable p] [decidable r] : p ∨ (q ∧ r) ↔ (p ∨ q) ∧ (r ∨ p ∨ r) := by tauto ``` and the decidability assumptions can be dropped if `tauto!` is used instead of `tauto`. `tauto {closer := tac}` will use `tac` on any subgoals created by `tauto` that it is unable to solve before failing. -/ add_tactic_doc { name := "tautology", category := doc_category.tactic, decl_names := [`tactic.interactive.tautology, `tactic.interactive.tauto], tags := ["logic", "decision procedure"] } end interactive end tactic
12e1fbe4f59b187722e0f2da47e809a30e27fbfd
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/category_theory/sums/associator.lean
e0c088666cba479d5dbdba685599372a6de3ea80
[ "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
3,203
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.sums.basic /-# The associator functor `((C ⊕ D) ⊕ E) ⥤ (C ⊕ (D ⊕ E))` and its inverse form an equivalence. -/ universes v u open category_theory open sum namespace category_theory.sum variables (C : Type u) [𝒞 : category.{v} C] (D : Type u) [𝒟 : category.{v} D] (E : Type u) [ℰ : category.{v} E] include 𝒞 𝒟 ℰ def associator : ((C ⊕ D) ⊕ E) ⥤ (C ⊕ (D ⊕ E)) := { obj := λ X, match X with | inl (inl X) := inl X | inl (inr X) := inr (inl X) | inr X := inr (inr X) end, map := λ X Y f, match X, Y, f with | inl (inl X), inl (inl Y), f := f | inl (inr X), inl (inr Y), f := f | inr X, inr Y, f := f end } @[simp] lemma associator_obj_inl_inl (X) : (associator C D E).obj (inl (inl X)) = inl X := rfl @[simp] lemma associator_obj_inl_inr (X) : (associator C D E).obj (inl (inr X)) = inr (inl X) := rfl @[simp] lemma associator_obj_inr (X) : (associator C D E).obj (inr X) = inr (inr X) := rfl @[simp] lemma associator_map_inl_inl {X Y : C} (f : inl (inl X) ⟶ inl (inl Y)) : (associator C D E).map f = f := rfl @[simp] lemma associator_map_inl_inr {X Y : D} (f : inl (inr X) ⟶ inl (inr Y)) : (associator C D E).map f = f := rfl @[simp] lemma associator_map_inr {X Y : E} (f : inr X ⟶ inr Y) : (associator C D E).map f = f := rfl def inverse_associator : (C ⊕ (D ⊕ E)) ⥤ ((C ⊕ D) ⊕ E) := { obj := λ X, match X with | inl X := inl (inl X) | inr (inl X) := inl (inr X) | inr (inr X) := inr X end, map := λ X Y f, match X, Y, f with | inl X, inl Y, f := f | inr (inl X), inr (inl Y), f := f | inr (inr X), inr (inr Y), f := f end } @[simp] lemma inverse_associator_obj_inl (X) : (inverse_associator C D E).obj (inl X) = inl (inl X) := rfl @[simp] lemma inverse_associator_obj_inr_inl (X) : (inverse_associator C D E).obj (inr (inl X)) = inl (inr X) := rfl @[simp] lemma inverse_associator_obj_inr_inr (X) : (inverse_associator C D E).obj (inr (inr X)) = inr X := rfl @[simp] lemma inverse_associator_map_inl {X Y : C} (f : inl X ⟶ inl Y) : (inverse_associator C D E).map f = f := rfl @[simp] lemma inverse_associator_map_inr_inl {X Y : D} (f : inr (inl X) ⟶ inr (inl Y)) : (inverse_associator C D E).map f = f := rfl @[simp] lemma inverse_associator_map_inr_inr {X Y : E} (f : inr (inr X) ⟶ inr (inr Y)) : (inverse_associator C D E).map f = f := rfl def associativity : (C ⊕ D) ⊕ E ≌ C ⊕ (D ⊕ E) := equivalence.mk (associator C D E) (inverse_associator C D E) (nat_iso.of_components (λ X, eq_to_iso (by tidy)) (by tidy)) (nat_iso.of_components (λ X, eq_to_iso (by tidy)) (by tidy)) instance associator_is_equivalence : is_equivalence (associator C D E) := (by apply_instance : is_equivalence (associativity C D E).functor) instance inverse_associator_is_equivalence : is_equivalence (inverse_associator C D E) := (by apply_instance : is_equivalence (associativity C D E).inverse) -- TODO unitors? -- TODO pentagon natural transformation? ...satisfying? end category_theory.sum
53adfe30b40baa7f99eb52ace5f990fac12c97f9
94637389e03c919023691dcd05bd4411b1034aa5
/src/inClassNotes/propositions/predicates_equality.lean
b179d78cc16aad44025cde75a3fd9953dcdfb1d9
[]
no_license
kevinsullivan/complogic-s21
7c4eef2105abad899e46502270d9829d913e8afc
99039501b770248c8ceb39890be5dfe129dc1082
refs/heads/master
1,682,985,669,944
1,621,126,241,000
1,621,126,241,000
335,706,272
0
38
null
1,618,325,669,000
1,612,374,118,000
Lean
UTF-8
Lean
false
false
5,780
lean
import inClassNotes.propositions.propositions_as_types_the_idea /- It's now an easy jump to using type families indexed by two types to represent predicates with two arguments. For example, here's an equality predicate, representing an equality relation, on terms of type day. -/ open day inductive eq_day : day → day → Prop | eq_day_mo : eq_day mo mo | eq_day_tu : eq_day tu tu | eq_day_we : eq_day we we | eq_day_th : eq_day th th | eq_day_fr : eq_day fr fr | eq_day_sa : eq_day sa sa | eq_day_su : eq_day su su /- eq_day = { (mo,mo), (tu,tu), ..., (su,su) } -/ open eq_day #check eq_day mo mo -- inhabited thus true #check eq_day mo tu -- not inhabited, not true #check eq_day fr sa -- not inhabited, not true lemma mos_equal : eq_day mo mo := eq_day_mo lemma mo_tu_equal : eq_day mo tu := _ -- stuck /- We use predicates specify sets and relations. Unary predicates specify sets. Binary and n-ary predicates more generally specify relations. For example, always_rains_on : day → Prop *with its particular proof constructors* represents the set { mo }, as mo is the only proposition in the family of propositions for which there's a proof, i.e., that is inhabited. Similarly, our eq_day : day → day → Prop type family / binary predicate specifies the 7-element binary relation (a set of pairs), { (mo,mo), ..., (su,su)}, in the sense these are all of and the only values for which eq_day yields a proposition for which there's a proof. -/ /- We can even use our home-grown equality predicate (a binary relation) on days to re-write our (always_rains_on d) predicate using eq_day so that we can finish our proof above. -/ inductive always_rains_on' : day → Prop | mo_rainy' : ∀ (d : day), (eq_day d mo) → always_rains_on' d open always_rains_on' lemma bad_tuesdays' : always_rains_on' tu := mo_rainy' tu _ -- stuck lemma bad_fridays' : always_rains_on' fr := mo_rainy' fr _ -- stuck lemma bad_mondays' : always_rains_on' mo := mo_rainy' mo eq_day_mo /- As an aside you can of course use tactic mode. -/ lemma bad_mondays'' : always_rains_on' mo := /- term -/ begin apply mo_rainy' _ _, exact eq_day_mo, end /- We're now completely set up to look at a first crucial application of these ideas: the definition of an equality predicate in Lean. We just saw how we can represent an equality relation on days as a two-place predicate. We generalize our approach by defining a polymorphic type family, eq. The eq type family takes on type parameter, α, and two *values* of that type, a1 and a2, (just as our eq_day predicate takes two values of type day). The resulting proposition is (eq a b), for which Lean gives us infix syntactic sugar, a = b. The type parameter is implicit. That defines our family of propositions. They include propositions such as follow. -/ #check eq 1 1 -- a1=1 #check eq 0 1 -- 0 = 1 #check eq tt tt -- tt = tt #check eq tt ff -- tt = ff #check eq "hi" "there" -- "hi" = "there" #check eq mo tu -- mo = tu /- The following terms are not propositions in Lean, for they do not even type check. -/ #check eq 1 tt #check eq "hi" 2 #check eq tt "Lean!" /- The final trick is that there is just one constructor for eq, called "refl" (generally written eq.refl) that takes *one* argument, a : α, and constructs a value of type (eq a a), aka a=a, which we take to be a proof of equality. The upshot is that you can generate a proof that any value of any type is equal to itself and there is no way to create a proof of any other equality. -/ #check @eq /- Here's Lean's exact definition of the eq relation as a type family with some members having proofs of equalty, and other members not. The real key is to define the constructors/axioms so that you get exacty the relation you want! -/ namespace eql universe u inductive eq {α : Sort u} (a : α) : α → Prop | refl [] : eq a -- skip notation for now -- You can see exactly what's going on here #check @eq #check eq 1 1 #check 1 = 1 -- same thing #check @eq.refl #check eq.refl 1 end eql example : 1 = 1 := eq.refl 1 example : 1 = 2 := _ /- Moreover, Lean reduces arguments to calls so you can use eq.refl to construct proofs of propositions such as 1 + 1 = 2. -/ example : 1 + 1 = 2 := eq.refl 2 example : "Hello, " ++ "Lean!" = "Hello, Lean!" := eq.refl "Hello, Lean!" /- By the way, "example", is like def, lemma or theorem, but you don't bind a name to a term. It's useful for show that a type is inhabited by giving an example of a value of that type. It's particularly useful when you don't care which value of a type is produced, since you're not go to do anything else with it anyway, given that it's unnamed. -/ /- A note on convenient shortcuts. The rfl function uses inference pretty heavily. -/ example : 1 + 1 = 4 - 2 := rfl /- Here's the definition of rfl from Lean's library. def rfl {α : Sort u} {a : α} : a = a := eq.refl a Lean has to be able to infer both the (α : Type) and (a : α) value for this definition to work. -/ /- We've thus specified the binary relation, equality, the equality predicate, on terms of any type. What are its properties and related functions? -/ /- Properties of equality -- reflexive -- symmetric -- transitive An equivalence relation -/ #check eq.refl #check eq.symm #check eq.trans #check @eq.rec inductive ev : ℕ → Prop | ev_0 : ev 0 | ev_ss : ∀ (n : ℕ), ev n → ev (n+2) open ev lemma zero_even : ev 0 := ev_0 lemma two_even : ev 2 := ev_ss 0 ev_0 lemma four_even : ev 4 := ev_ss 2 two_even lemma four_even' : ev 4 := ev_ss -- emphasizes recursive structure of proof term 2 (ev_ss 0 ev_0 ) lemma five_hundred_even : ev 500 := begin repeat { apply ev_ss }, _ end
43f06eb3449ee0a493b025ecf2ddc12b791a429a
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/limits/shapes/regular_mono_auto.lean
51ac59a457974a23fe17df8c9d23d5a3b48fdd1c
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
8,058
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.limits.preserves.basic import Mathlib.category_theory.limits.shapes.equalizers import Mathlib.category_theory.limits.shapes.strong_epi import Mathlib.category_theory.limits.shapes.pullbacks import Mathlib.PostPort universes v₁ u₁ l namespace Mathlib /-! # Definitions and basic properties of regular monomorphisms and epimorphisms. A regular monomorphism is a morphism that is the equalizer of some parallel pair. We give the constructions * `split_mono → regular_mono` and * `regular_mono → mono` as well as the dual constructions for regular epimorphisms. Additionally, we give the construction * `regular_epi ⟶ strong_epi`. -/ namespace category_theory /-- A regular monomorphism is a morphism which is the equalizer of some parallel pair. -/ class regular_mono {C : Type u₁} [category C] {X : C} {Y : C} (f : X ⟶ Y) where Z : C left : Y ⟶ Z right : Y ⟶ Z w : f ≫ left = f ≫ right is_limit : limits.is_limit (limits.fork.of_ι f w) theorem regular_mono.w_assoc {C : Type u₁} [category C] {X : C} {Y : C} {f : X ⟶ Y} [c : regular_mono f] {X' : C} (f' : regular_mono.Z f ⟶ X') : f ≫ regular_mono.left ≫ f' = f ≫ regular_mono.right ≫ f' := sorry /-- Every regular monomorphism is a monomorphism. -/ protected instance regular_mono.mono {C : Type u₁} [category C] {X : C} {Y : C} (f : X ⟶ Y) [regular_mono f] : mono f := limits.mono_of_is_limit_parallel_pair regular_mono.is_limit protected instance equalizer_regular {C : Type u₁} [category C] {X : C} {Y : C} (g : X ⟶ Y) (h : X ⟶ Y) [limits.has_limit (limits.parallel_pair g h)] : regular_mono (limits.equalizer.ι g h) := regular_mono.mk Y g h (limits.equalizer.condition g h) (limits.fork.is_limit.mk (limits.fork.of_ι (limits.equalizer.ι g h) (limits.equalizer.condition g h)) (fun (s : limits.fork g h) => limits.limit.lift (limits.parallel_pair g h) s) sorry sorry) /-- Every split monomorphism is a regular monomorphism. -/ protected instance regular_mono.of_split_mono {C : Type u₁} [category C] {X : C} {Y : C} (f : X ⟶ Y) [split_mono f] : regular_mono f := regular_mono.mk Y 𝟙 (retraction f ≫ f) (limits.cone_of_split_mono._proof_1 f) (limits.split_mono_equalizes f) /-- If `f` is a regular mono, then any map `k : W ⟶ Y` equalizing `regular_mono.left` and `regular_mono.right` induces a morphism `l : W ⟶ X` such that `l ≫ f = k`. -/ def regular_mono.lift' {C : Type u₁} [category C] {X : C} {Y : C} {W : C} (f : X ⟶ Y) [regular_mono f] (k : W ⟶ Y) (h : k ≫ regular_mono.left = k ≫ regular_mono.right) : Subtype fun (l : W ⟶ X) => l ≫ f = k := limits.fork.is_limit.lift' regular_mono.is_limit k h /-- The second leg of a pullback cone is a regular monomorphism if the right component is too. See also `pullback.snd_of_mono` for the basic monomorphism version, and `regular_of_is_pullback_fst_of_regular` for the flipped version. -/ def regular_of_is_pullback_snd_of_regular {C : Type u₁} [category C] {P : C} {Q : C} {R : C} {S : C} {f : P ⟶ Q} {g : P ⟶ R} {h : Q ⟶ S} {k : R ⟶ S} [hr : regular_mono h] (comm : f ≫ h = g ≫ k) (t : limits.is_limit (limits.pullback_cone.mk f g comm)) : regular_mono g := sorry /-- The first leg of a pullback cone is a regular monomorphism if the left component is too. See also `pullback.fst_of_mono` for the basic monomorphism version, and `regular_of_is_pullback_snd_of_regular` for the flipped version. -/ def regular_of_is_pullback_fst_of_regular {C : Type u₁} [category C] {P : C} {Q : C} {R : C} {S : C} {f : P ⟶ Q} {g : P ⟶ R} {h : Q ⟶ S} {k : R ⟶ S} [hr : regular_mono k] (comm : f ≫ h = g ≫ k) (t : limits.is_limit (limits.pullback_cone.mk f g comm)) : regular_mono f := regular_of_is_pullback_snd_of_regular sorry (limits.pullback_cone.flip_is_limit t) /-- A regular monomorphism is an isomorphism if it is an epimorphism. -/ def is_iso_of_regular_mono_of_epi {C : Type u₁} [category C] {X : C} {Y : C} (f : X ⟶ Y) [regular_mono f] [e : epi f] : is_iso f := limits.is_iso_limit_cone_parallel_pair_of_epi regular_mono.is_limit /-- A regular epimorphism is a morphism which is the coequalizer of some parallel pair. -/ class regular_epi {C : Type u₁} [category C] {X : C} {Y : C} (f : X ⟶ Y) where W : C left : W ⟶ X right : W ⟶ X w : left ≫ f = right ≫ f is_colimit : limits.is_colimit (limits.cofork.of_π f w) theorem regular_epi.w_assoc {C : Type u₁} [category C] {X : C} {Y : C} {f : X ⟶ Y} [c : regular_epi f] {X' : C} (f' : Y ⟶ X') : regular_epi.left ≫ f ≫ f' = regular_epi.right ≫ f ≫ f' := sorry /-- Every regular epimorphism is an epimorphism. -/ protected instance regular_epi.epi {C : Type u₁} [category C] {X : C} {Y : C} (f : X ⟶ Y) [regular_epi f] : epi f := limits.epi_of_is_colimit_parallel_pair regular_epi.is_colimit protected instance coequalizer_regular {C : Type u₁} [category C] {X : C} {Y : C} (g : X ⟶ Y) (h : X ⟶ Y) [limits.has_colimit (limits.parallel_pair g h)] : regular_epi (limits.coequalizer.π g h) := regular_epi.mk X g h (limits.coequalizer.condition g h) (limits.cofork.is_colimit.mk (limits.cofork.of_π (limits.coequalizer.π g h) (limits.coequalizer.condition g h)) (fun (s : limits.cofork g h) => limits.colimit.desc (limits.parallel_pair g h) s) sorry sorry) /-- Every split epimorphism is a regular epimorphism. -/ protected instance regular_epi.of_split_epi {C : Type u₁} [category C] {X : C} {Y : C} (f : X ⟶ Y) [split_epi f] : regular_epi f := regular_epi.mk X 𝟙 (f ≫ section_ f) (limits.cocone_of_split_epi._proof_1 f) (limits.split_epi_coequalizes f) /-- If `f` is a regular epi, then every morphism `k : X ⟶ W` coequalizing `regular_epi.left` and `regular_epi.right` induces `l : Y ⟶ W` such that `f ≫ l = k`. -/ def regular_epi.desc' {C : Type u₁} [category C] {X : C} {Y : C} {W : C} (f : X ⟶ Y) [regular_epi f] (k : X ⟶ W) (h : regular_epi.left ≫ k = regular_epi.right ≫ k) : Subtype fun (l : Y ⟶ W) => f ≫ l = k := limits.cofork.is_colimit.desc' regular_epi.is_colimit k h /-- The second leg of a pushout cocone is a regular epimorphism if the right component is too. See also `pushout.snd_of_epi` for the basic epimorphism version, and `regular_of_is_pushout_fst_of_regular` for the flipped version. -/ def regular_of_is_pushout_snd_of_regular {C : Type u₁} [category C] {P : C} {Q : C} {R : C} {S : C} {f : P ⟶ Q} {g : P ⟶ R} {h : Q ⟶ S} {k : R ⟶ S} [gr : regular_epi g] (comm : f ≫ h = g ≫ k) (t : limits.is_colimit (limits.pushout_cocone.mk h k comm)) : regular_epi h := sorry /-- The first leg of a pushout cocone is a regular epimorphism if the left component is too. See also `pushout.fst_of_epi` for the basic epimorphism version, and `regular_of_is_pushout_snd_of_regular` for the flipped version. -/ def regular_of_is_pushout_fst_of_regular {C : Type u₁} [category C] {P : C} {Q : C} {R : C} {S : C} {f : P ⟶ Q} {g : P ⟶ R} {h : Q ⟶ S} {k : R ⟶ S} [fr : regular_epi f] (comm : f ≫ h = g ≫ k) (t : limits.is_colimit (limits.pushout_cocone.mk h k comm)) : regular_epi k := regular_of_is_pushout_snd_of_regular sorry (limits.pushout_cocone.flip_is_colimit t) /-- A regular epimorphism is an isomorphism if it is a monomorphism. -/ def is_iso_of_regular_epi_of_mono {C : Type u₁} [category C] {X : C} {Y : C} (f : X ⟶ Y) [regular_epi f] [m : mono f] : is_iso f := limits.is_iso_limit_cocone_parallel_pair_of_epi regular_epi.is_colimit protected instance strong_epi_of_regular_epi {C : Type u₁} [category C] {X : C} {Y : C} (f : X ⟶ Y) [regular_epi f] : strong_epi f := sorry end Mathlib
e915fa2a4a79ae0476bbd32a1945979abe480fa8
586535ff9853f5b85dc5fdeb5b78f1ad2d573a6e
/src/type_system.lean
4c9933a9e5bf2845966bcf08a9661feb15029d51
[ "Apache-2.0" ]
permissive
Kha/rc-correctness
fede4ae228c5f04985cf332e718a5a433230b150
be5a521f1b0528ccbc685619b265cd11ea854edf
refs/heads/master
1,595,967,325,275
1,568,889,756,000
1,568,889,756,000
209,523,947
0
0
Apache-2.0
1,568,888,337,000
1,568,888,336,000
null
UTF-8
Lean
false
false
4,660
lean
import ast namespace rc_correctness @[derive decidable_eq] inductive ob_lin_type : Type | 𝕆 | 𝔹 @[derive decidable_eq] inductive lin_type : Type | ob : ob_lin_type → lin_type | ℝ : lin_type instance ob_lin_type_to_lin_type : has_coe ob_lin_type lin_type := ⟨lin_type.ob⟩ @[simp] lemma coe_eq_coe {t1 t2 : ob_lin_type} : (↑t1 : lin_type) = ↑t2 ↔ t1 = t2 := begin split; intro h, { exact lin_type.ob.inj h }, rw h end structure typed_rc := (c : rc) (ty : lin_type) @[derive decidable_eq] structure typed_var := (x : var) (ty : lin_type) notation x ` ∶ `:2 τ := typed_var.mk x τ notation xs ` [∶] `:2 τ := (list.map (λ x, (x ∶ τ)) xs : multiset typed_var) notation xs ` {∶} `:2 τ := multiset.map (λ x, (x ∶ τ)) xs notation c ` ∷ `:2 τ := typed_rc.mk c τ abbreviation type_context := multiset typed_var open rc_correctness.expr open rc_correctness.fn_body open rc_correctness.ob_lin_type open rc_correctness.lin_type inductive linear (β : const → var → ob_lin_type) : type_context → typed_rc → Prop notation Γ ` ⊩ `:1 t := linear Γ t | var (x : var) (τ : lin_type) : (x ∶ τ)::0 ⊩ x ∷ τ | weaken {Γ : type_context} {t : typed_rc} (x : var) (t_typed : Γ ⊩ t) : (x ∶ 𝔹) :: Γ ⊩ t | contract {Γ : type_context} {x : var} {t : typed_rc} (x_𝔹 : (x ∶ 𝔹) ∈ Γ) (t_typed : (x ∶ 𝔹) :: Γ ⊩ t) : Γ ⊩ t | inc_o {Γ : type_context} {x : var} {F : fn_body} (x_𝕆 : (x ∶ 𝕆) ∈ Γ) (F_𝕆 : (x ∶ 𝕆) :: Γ ⊩ F ∷ 𝕆) : Γ ⊩ (inc x; F) ∷ 𝕆 | inc_b {Γ : type_context} {x : var} {F : fn_body} (x_𝔹 : (x ∶ 𝔹) ∈ Γ) (F_𝕆 : (x ∶ 𝕆) :: Γ ⊩ F ∷ 𝕆) : Γ ⊩ (inc x; F) ∷ 𝕆 | dec_o {Γ : type_context} (x : var) {F : fn_body} (F_𝕆 : Γ ⊩ F ∷ 𝕆) : (x ∶ 𝕆) :: Γ ⊩ (dec x; F) ∷ 𝕆 | dec_r {Γ : type_context} (x : var) {F : fn_body} (F_𝕆 : Γ ⊩ F ∷ 𝕆) : (x ∶ ℝ) :: Γ ⊩ (dec x; F) ∷ 𝕆 | ret {Γ : type_context} {x : var} (x_𝕆 : Γ ⊩ x ∷ 𝕆) : Γ ⊩ (ret x) ∷ 𝕆 | case_o {Γ : type_context} {x : var} {Fs : list fn_body} (x_𝕆 : (x ∶ 𝕆) ∈ Γ) (Fs_𝕆 : ∀ F ∈ Fs, Γ ⊩ ↑F ∷ 𝕆) : Γ ⊩ (case x of Fs) ∷ 𝕆 | case_b {Γ : type_context} {x : var} {Fs : list fn_body} (x_𝔹 : (x ∶ 𝔹) ∈ Γ) (Fs_𝕆 : ∀ F ∈ Fs, Γ ⊩ ↑F ∷ 𝕆) : Γ ⊩ (case x of Fs) ∷ 𝕆 | const_app_full {Γys : list (type_context × var)} {c : const} (ys_β_c : ∀ Γy ∈ Γys, (Γy : type_context × var).1 ⊩ Γy.2 ∷ β c Γy.2) : multiset.join (Γys.map prod.fst) ⊩ c⟦Γys.map prod.snd…⟧ ∷ 𝕆 | const_app_part (ys : list var) (c : const) : ys [∶] 𝕆 ⊩ c⟦ys…, _⟧ ∷ 𝕆 | var_app (x y : var) : (x ∶ 𝕆) :: (y ∶ 𝕆) :: 0 ⊩ x⟦y⟧ ∷ 𝕆 | cnstr_app (ys : list var) (i : cnstr) : ys [∶] 𝕆 ⊩ (⟪ys⟫i) ∷ 𝕆 | reset (x : var) : (x ∶ 𝕆) :: 0 ⊩ (reset x) ∷ ℝ | «reuse» (x : var) (ys : list var) (i : cnstr) : (x ∶ ℝ) :: (ys [∶] 𝕆) ⊩ (reuse x in ⟪ys⟫i) ∷ 𝕆 | let_o {Γ : type_context} {xs : list var} {e : expr} {Δ : type_context} {z : var} {F : fn_body} (xs_𝕆 : (xs [∶] 𝕆) ⊆ Δ) (e_𝕆 : Γ + (xs [∶] 𝔹) ⊩ e ∷ 𝕆) (F_𝕆 : (z ∶ 𝕆) :: Δ ⊩ F ∷ 𝕆) : Γ + Δ ⊩ (z ≔ e; F) ∷ 𝕆 | let_r {Γ : type_context} {xs : list var} {e : expr} {Δ : type_context} {z : var} {F : fn_body} (xs_𝕆 : (xs [∶] 𝕆) ⊆ Δ) (e_𝕆 : Γ + (xs [∶] 𝔹) ⊩ e ∷ 𝕆) (F_𝕆 : (z ∶ ℝ) :: Δ ⊩ F ∷ 𝕆) : Γ + Δ ⊩ (z ≔ e; F) ∷ 𝕆 | proj_bor {Γ : type_context} {x y : var} {F : fn_body} (i : cnstr) (x_𝔹 : (x ∶ 𝔹) ∈ Γ) (F_𝕆 : (y ∶ 𝔹) :: Γ ⊩ F ∷ 𝕆) : Γ ⊩ (y ≔ x[i]; F) ∷ 𝕆 | proj_own {Γ : type_context} {x y : var} {F : fn_body} (i : cnstr) (x_𝕆 : (x ∶ 𝕆) ∈ Γ) (F_𝕆 : (y ∶ 𝕆) :: Γ ⊩ F ∷ 𝕆) : Γ ⊩ (y ≔ x[i]; inc y; F) ∷ 𝕆 notation β `; ` Γ ` ⊩ `:1 t := linear β Γ t inductive linear_const (β : const → var → ob_lin_type) (δ : const → fn) : const → Prop notation ` ⊩ `:1 c := linear_const c | const {c : const} (F_𝕆 : β; (δ c).ys.map (λ y, y ∶ β c y) ⊩ (δ c).F ∷ 𝕆) : ⊩ c notation β `; ` δ ` ⊩ `:1 c := linear_const β δ c inductive linear_program (β : const → var → ob_lin_type) : (const → fn) → Prop notation ` ⊩ `:1 δ := linear_program δ | program {δ : const → fn} (const_typed : ∀ c : const, (β; δ ⊩ c)) : ⊩ δ notation β ` ⊩ `:1 δ := linear_program β δ end rc_correctness
26381793e99ebbd998c3d760834dbe1e12966b69
4727251e0cd73359b15b664c3170e5d754078599
/src/linear_algebra/affine_space/finite_dimensional.lean
f782f009cb68a5435e66dc02558310a4233ca2e8
[ "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
16,395
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import linear_algebra.affine_space.independent import linear_algebra.finite_dimensional /-! # Finite-dimensional subspaces of affine spaces. This file provides a few results relating to finite-dimensional subspaces of affine spaces. ## Main definitions * `collinear` defines collinear sets of points as those that span a subspace of dimension at most 1. -/ noncomputable theory open_locale big_operators classical affine section affine_space' variables (k : Type*) {V : Type*} {P : Type*} variables {ι : Type*} include V open affine_subspace finite_dimensional module variables [division_ring k] [add_comm_group V] [module k V] [affine_space V P] /-- The `vector_span` of a finite set is finite-dimensional. -/ lemma finite_dimensional_vector_span_of_finite {s : set P} (h : set.finite s) : finite_dimensional k (vector_span k s) := span_of_finite k $ h.vsub h /-- The `vector_span` of a family indexed by a `fintype` is finite-dimensional. -/ instance finite_dimensional_vector_span_of_fintype [fintype ι] (p : ι → P) : finite_dimensional k (vector_span k (set.range p)) := finite_dimensional_vector_span_of_finite k (set.finite_range _) /-- The `vector_span` of a subset of a family indexed by a `fintype` is finite-dimensional. -/ instance finite_dimensional_vector_span_image_of_fintype [fintype ι] (p : ι → P) (s : set ι) : finite_dimensional k (vector_span k (p '' s)) := finite_dimensional_vector_span_of_finite k ((set.finite.of_fintype _).image _) /-- The direction of the affine span of a finite set is finite-dimensional. -/ lemma finite_dimensional_direction_affine_span_of_finite {s : set P} (h : set.finite s) : finite_dimensional k (affine_span k s).direction := (direction_affine_span k s).symm ▸ finite_dimensional_vector_span_of_finite k h /-- The direction of the affine span of a family indexed by a `fintype` is finite-dimensional. -/ instance finite_dimensional_direction_affine_span_of_fintype [fintype ι] (p : ι → P) : finite_dimensional k (affine_span k (set.range p)).direction := finite_dimensional_direction_affine_span_of_finite k (set.finite_range _) /-- The direction of the affine span of a subset of a family indexed by a `fintype` is finite-dimensional. -/ instance finite_dimensional_direction_affine_span_image_of_fintype [fintype ι] (p : ι → P) (s : set ι) : finite_dimensional k (affine_span k (p '' s)).direction := finite_dimensional_direction_affine_span_of_finite k ((set.finite.of_fintype _).image _) /-- An affine-independent family of points in a finite-dimensional affine space is finite. -/ noncomputable def fintype_of_fin_dim_affine_independent [finite_dimensional k V] {p : ι → P} (hi : affine_independent k p) : fintype ι := if hι : is_empty ι then (@fintype.of_is_empty _ hι) else begin let q := (not_is_empty_iff.mp hι).some, rw affine_independent_iff_linear_independent_vsub k p q at hi, letI : is_noetherian k V := is_noetherian.iff_fg.2 infer_instance, exact fintype_of_fintype_ne _ (fintype_of_is_noetherian_linear_independent hi) end /-- An affine-independent subset of a finite-dimensional affine space is finite. -/ lemma finite_of_fin_dim_affine_independent [finite_dimensional k V] {s : set P} (hi : affine_independent k (coe : s → P)) : s.finite := ⟨fintype_of_fin_dim_affine_independent k hi⟩ variables {k} /-- The `vector_span` of a finite subset of an affinely independent family has dimension one less than its cardinality. -/ lemma affine_independent.finrank_vector_span_image_finset {p : ι → P} (hi : affine_independent k p) {s : finset ι} {n : ℕ} (hc : finset.card s = n + 1) : finrank k (vector_span k (s.image p : set P)) = n := begin have hi' := hi.range.mono (set.image_subset_range p ↑s), have hc' : (s.image p).card = n + 1, { rwa s.card_image_of_injective hi.injective }, have hn : (s.image p).nonempty, { simp [hc', ←finset.card_pos] }, rcases hn with ⟨p₁, hp₁⟩, have hp₁' : p₁ ∈ p '' s := by simpa using hp₁, rw [affine_independent_set_iff_linear_independent_vsub k hp₁', ← finset.coe_singleton, ← finset.coe_image, ← finset.coe_sdiff, finset.sdiff_singleton_eq_erase, ← finset.coe_image] at hi', have hc : (finset.image (λ (p : P), p -ᵥ p₁) ((finset.image p s).erase p₁)).card = n, { rw [finset.card_image_of_injective _ (vsub_left_injective _), finset.card_erase_of_mem hp₁], exact nat.pred_eq_of_eq_succ hc' }, rwa [vector_span_eq_span_vsub_finset_right_ne k hp₁, finrank_span_finset_eq_card, hc] end /-- The `vector_span` of a finite affinely independent family has dimension one less than its cardinality. -/ lemma affine_independent.finrank_vector_span [fintype ι] {p : ι → P} (hi : affine_independent k p) {n : ℕ} (hc : fintype.card ι = n + 1) : finrank k (vector_span k (set.range p)) = n := begin rw ← finset.card_univ at hc, rw [← set.image_univ, ← finset.coe_univ, ← finset.coe_image], exact hi.finrank_vector_span_image_finset hc end /-- The `vector_span` of a finite affinely independent family whose cardinality is one more than that of the finite-dimensional space is `⊤`. -/ lemma affine_independent.vector_span_eq_top_of_card_eq_finrank_add_one [finite_dimensional k V] [fintype ι] {p : ι → P} (hi : affine_independent k p) (hc : fintype.card ι = finrank k V + 1) : vector_span k (set.range p) = ⊤ := eq_top_of_finrank_eq $ hi.finrank_vector_span hc variables (k) /-- The `vector_span` of `n + 1` points in an indexed family has dimension at most `n`. -/ lemma finrank_vector_span_image_finset_le (p : ι → P) (s : finset ι) {n : ℕ} (hc : finset.card s = n + 1) : finrank k (vector_span k (s.image p : set P)) ≤ n := begin have hn : (s.image p).nonempty, { rw [finset.nonempty.image_iff, ← finset.card_pos, hc], apply nat.succ_pos }, rcases hn with ⟨p₁, hp₁⟩, rw [vector_span_eq_span_vsub_finset_right_ne k hp₁], refine le_trans (finrank_span_finset_le_card (((s.image p).erase p₁).image (λ p, p -ᵥ p₁))) _, rw [finset.card_image_of_injective _ (vsub_left_injective p₁), finset.card_erase_of_mem hp₁, tsub_le_iff_right, ← hc], apply finset.card_image_le end /-- The `vector_span` of an indexed family of `n + 1` points has dimension at most `n`. -/ lemma finrank_vector_span_range_le [fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 1) : finrank k (vector_span k (set.range p)) ≤ n := begin rw [←set.image_univ, ←finset.coe_univ, ← finset.coe_image], rw ←finset.card_univ at hc, exact finrank_vector_span_image_finset_le _ _ _ hc end /-- `n + 1` points are affinely independent if and only if their `vector_span` has dimension `n`. -/ lemma affine_independent_iff_finrank_vector_span_eq [fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 1) : affine_independent k p ↔ finrank k (vector_span k (set.range p)) = n := begin have hn : nonempty ι, by simp [←fintype.card_pos_iff, hc], cases hn with i₁, rw [affine_independent_iff_linear_independent_vsub _ _ i₁, linear_independent_iff_card_eq_finrank_span, eq_comm, vector_span_range_eq_span_range_vsub_right_ne k p i₁], congr', rw ←finset.card_univ at hc, rw fintype.subtype_card, simp [finset.filter_ne', finset.card_erase_of_mem, hc] end /-- `n + 1` points are affinely independent if and only if their `vector_span` has dimension at least `n`. -/ lemma affine_independent_iff_le_finrank_vector_span [fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 1) : affine_independent k p ↔ n ≤ finrank k (vector_span k (set.range p)) := begin rw affine_independent_iff_finrank_vector_span_eq k p hc, split, { rintro rfl, refl }, { exact λ hle, le_antisymm (finrank_vector_span_range_le k p hc) hle } end /-- `n + 2` points are affinely independent if and only if their `vector_span` does not have dimension at most `n`. -/ lemma affine_independent_iff_not_finrank_vector_span_le [fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 2) : affine_independent k p ↔ ¬ finrank k (vector_span k (set.range p)) ≤ n := by rw [affine_independent_iff_le_finrank_vector_span k p hc, ←nat.lt_iff_add_one_le, lt_iff_not_ge] /-- `n + 2` points have a `vector_span` with dimension at most `n` if and only if they are not affinely independent. -/ lemma finrank_vector_span_le_iff_not_affine_independent [fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 2) : finrank k (vector_span k (set.range p)) ≤ n ↔ ¬ affine_independent k p := (not_iff_comm.1 (affine_independent_iff_not_finrank_vector_span_le k p hc).symm).symm variables {k} /-- If the `vector_span` of a finite subset of an affinely independent family lies in a submodule with dimension one less than its cardinality, it equals that submodule. -/ lemma affine_independent.vector_span_image_finset_eq_of_le_of_card_eq_finrank_add_one {p : ι → P} (hi : affine_independent k p) {s : finset ι} {sm : submodule k V} [finite_dimensional k sm] (hle : vector_span k (s.image p : set P) ≤ sm) (hc : finset.card s = finrank k sm + 1) : vector_span k (s.image p : set P) = sm := eq_of_le_of_finrank_eq hle $ hi.finrank_vector_span_image_finset hc /-- If the `vector_span` of a finite affinely independent family lies in a submodule with dimension one less than its cardinality, it equals that submodule. -/ lemma affine_independent.vector_span_eq_of_le_of_card_eq_finrank_add_one [fintype ι] {p : ι → P} (hi : affine_independent k p) {sm : submodule k V} [finite_dimensional k sm] (hle : vector_span k (set.range p) ≤ sm) (hc : fintype.card ι = finrank k sm + 1) : vector_span k (set.range p) = sm := eq_of_le_of_finrank_eq hle $ hi.finrank_vector_span hc /-- If the `affine_span` of a finite subset of an affinely independent family lies in an affine subspace whose direction has dimension one less than its cardinality, it equals that subspace. -/ lemma affine_independent.affine_span_image_finset_eq_of_le_of_card_eq_finrank_add_one {p : ι → P} (hi : affine_independent k p) {s : finset ι} {sp : affine_subspace k P} [finite_dimensional k sp.direction] (hle : affine_span k (s.image p : set P) ≤ sp) (hc : finset.card s = finrank k sp.direction + 1) : affine_span k (s.image p : set P) = sp := begin have hn : (s.image p).nonempty, { rw [finset.nonempty.image_iff, ← finset.card_pos, hc], apply nat.succ_pos }, refine eq_of_direction_eq_of_nonempty_of_le _ ((affine_span_nonempty k _).2 hn) hle, have hd := direction_le hle, rw direction_affine_span at ⊢ hd, exact hi.vector_span_image_finset_eq_of_le_of_card_eq_finrank_add_one hd hc end /-- If the `affine_span` of a finite affinely independent family lies in an affine subspace whose direction has dimension one less than its cardinality, it equals that subspace. -/ lemma affine_independent.affine_span_eq_of_le_of_card_eq_finrank_add_one [fintype ι] {p : ι → P} (hi : affine_independent k p) {sp : affine_subspace k P} [finite_dimensional k sp.direction] (hle : affine_span k (set.range p) ≤ sp) (hc : fintype.card ι = finrank k sp.direction + 1) : affine_span k (set.range p) = sp := begin rw ←finset.card_univ at hc, rw [←set.image_univ, ←finset.coe_univ, ← finset.coe_image] at ⊢ hle, exact hi.affine_span_image_finset_eq_of_le_of_card_eq_finrank_add_one hle hc end /-- The `affine_span` of a finite affinely independent family is `⊤` iff the family's cardinality is one more than that of the finite-dimensional space. -/ lemma affine_independent.affine_span_eq_top_iff_card_eq_finrank_add_one [finite_dimensional k V] [fintype ι] {p : ι → P} (hi : affine_independent k p) : affine_span k (set.range p) = ⊤ ↔ fintype.card ι = finrank k V + 1 := begin split, { intros h_tot, let n := fintype.card ι - 1, have hn : fintype.card ι = n + 1, { exact (nat.succ_pred_eq_of_pos (card_pos_of_affine_span_eq_top k V P h_tot)).symm, }, rw [hn, ← finrank_top, ← (vector_span_eq_top_of_affine_span_eq_top k V P) h_tot, ← hi.finrank_vector_span hn], }, { intros hc, rw [← finrank_top, ← direction_top k V P] at hc, exact hi.affine_span_eq_of_le_of_card_eq_finrank_add_one le_top hc, }, end variables (k) /-- A set of points is collinear if their `vector_span` has dimension at most `1`. -/ def collinear (s : set P) : Prop := module.rank k (vector_span k s) ≤ 1 /-- The definition of `collinear`. -/ lemma collinear_iff_dim_le_one (s : set P) : collinear k s ↔ module.rank k (vector_span k s) ≤ 1 := iff.rfl /-- A set of points, whose `vector_span` is finite-dimensional, is collinear if and only if their `vector_span` has dimension at most `1`. -/ lemma collinear_iff_finrank_le_one (s : set P) [finite_dimensional k (vector_span k s)] : collinear k s ↔ finrank k (vector_span k s) ≤ 1 := begin have h := collinear_iff_dim_le_one k s, rw ←finrank_eq_dim at h, exact_mod_cast h end variables (P) /-- The empty set is collinear. -/ lemma collinear_empty : collinear k (∅ : set P) := begin rw [collinear_iff_dim_le_one, vector_span_empty], simp end variables {P} /-- A single point is collinear. -/ lemma collinear_singleton (p : P) : collinear k ({p} : set P) := begin rw [collinear_iff_dim_le_one, vector_span_singleton], simp end /-- Given a point `p₀` in a set of points, that set is collinear if and only if the points can all be expressed as multiples of the same vector, added to `p₀`. -/ lemma collinear_iff_of_mem {s : set P} {p₀ : P} (h : p₀ ∈ s) : collinear k s ↔ ∃ v : V, ∀ p ∈ s, ∃ r : k, p = r • v +ᵥ p₀ := begin simp_rw [collinear_iff_dim_le_one, dim_submodule_le_one_iff', submodule.le_span_singleton_iff], split, { rintro ⟨v₀, hv⟩, use v₀, intros p hp, obtain ⟨r, hr⟩ := hv (p -ᵥ p₀) (vsub_mem_vector_span k hp h), use r, rw eq_vadd_iff_vsub_eq, exact hr.symm }, { rintro ⟨v, hp₀v⟩, use v, intros w hw, have hs : vector_span k s ≤ k ∙ v, { rw [vector_span_eq_span_vsub_set_right k h, submodule.span_le, set.subset_def], intros x hx, rw [set_like.mem_coe, submodule.mem_span_singleton], rw set.mem_image at hx, rcases hx with ⟨p, hp, rfl⟩, rcases hp₀v p hp with ⟨r, rfl⟩, use r, simp }, have hw' := set_like.le_def.1 hs hw, rwa submodule.mem_span_singleton at hw' } end /-- A set of points is collinear if and only if they can all be expressed as multiples of the same vector, added to the same base point. -/ lemma collinear_iff_exists_forall_eq_smul_vadd (s : set P) : collinear k s ↔ ∃ (p₀ : P) (v : V), ∀ p ∈ s, ∃ r : k, p = r • v +ᵥ p₀ := begin rcases set.eq_empty_or_nonempty s with rfl | ⟨⟨p₁, hp₁⟩⟩, { simp [collinear_empty] }, { rw collinear_iff_of_mem k hp₁, split, { exact λ h, ⟨p₁, h⟩ }, { rintros ⟨p, v, hv⟩, use v, intros p₂ hp₂, rcases hv p₂ hp₂ with ⟨r, rfl⟩, rcases hv p₁ hp₁ with ⟨r₁, rfl⟩, use r - r₁, simp [vadd_vadd, ←add_smul] } } end /-- Two points are collinear. -/ lemma collinear_insert_singleton (p₁ p₂ : P) : collinear k ({p₁, p₂} : set P) := begin rw collinear_iff_exists_forall_eq_smul_vadd, use [p₁, p₂ -ᵥ p₁], intros p hp, rw [set.mem_insert_iff, set.mem_singleton_iff] at hp, cases hp, { use 0, simp [hp] }, { use 1, simp [hp] } end /-- Three points are affinely independent if and only if they are not collinear. -/ lemma affine_independent_iff_not_collinear (p : fin 3 → P) : affine_independent k p ↔ ¬ collinear k (set.range p) := by rw [collinear_iff_finrank_le_one, affine_independent_iff_not_finrank_vector_span_le k p (fintype.card_fin 3)] /-- Three points are collinear if and only if they are not affinely independent. -/ lemma collinear_iff_not_affine_independent (p : fin 3 → P) : collinear k (set.range p) ↔ ¬ affine_independent k p := by rw [collinear_iff_finrank_le_one, finrank_vector_span_le_iff_not_affine_independent k p (fintype.card_fin 3)] end affine_space'
162a5ef5e70496e458150ccc0bd05e280a6d9893
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/mvar2.lean
2465c8d5c2fc6fdfa9aaabb07ed9a9726433198c
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,447
lean
import Lean.MetavarContext new_frontend open Lean def check (b : Bool) : IO Unit := «unless» b (throw $ IO.userError "error") def f := mkConst `f [] def g := mkConst `g [] def a := mkConst `a [] def b := mkConst `b [] def c := mkConst `c [] def b0 := mkBVar 0 def b1 := mkBVar 1 def b2 := mkBVar 2 def u := mkLevelParam `u def typeE := mkSort levelOne def natE := mkConst `Nat [] def boolE := mkConst `Bool [] def vecE := mkConst `Vec [levelZero] def α := mkFVar `α def x := mkFVar `x def y := mkFVar `y def z := mkFVar `z def w := mkFVar `w def m1 := mkMVar `m1 def m2 := mkMVar `m2 def m3 := mkMVar `m3 def bi := BinderInfo.default def arrow (d b : Expr) := mkForall `_ bi d b def lctx1 : LocalContext := {} def lctx2 := lctx1.mkLocalDecl `α `α typeE def lctx3 := lctx2.mkLocalDecl `x `x m1 def lctx4 := lctx3.mkLocalDecl `y `y (arrow natE (mkAppN m3 #[α, x])) def mctx1 : MetavarContext := {} def mctx2 := mctx1.addExprMVarDecl `m1 `m1 lctx1 #[] typeE def mctx3 := mctx2.addExprMVarDecl `m2 `m2 lctx3 #[] natE def mctx4 := mctx3.addExprMVarDecl `m3 `m3 lctx1 #[] (arrow typeE (arrow natE natE)) def mctx5 := mctx4.assignDelayed `m3 lctx3 #[α, x] m2 def mctx6 := mctx5.assignExpr `m2 (arrow α α) def mctx7 := mctx6.assignExpr `m1 natE def t2 := lctx4.mkLambda #[α, x, y] $ mkAppN f #[mkAppN m3 #[α, x], x] #eval check (!t2.hasFVar) #eval t2 #eval (mctx6.instantiateMVars t2).1 #eval (mctx7.instantiateMVars t2).1
35a9ed3931634d4b8b70a8f4f918ca2106c389ed
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/order/monoid/canonical/defs.lean
ddce37a99ab5118f81f7305f4bddc8ae448a2191
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
10,574
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl -/ import order.bounded_order import order.min_max import algebra.ne_zero import algebra.order.monoid.defs /-! # Canonically ordered monoids > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ universe u variables {α : Type u} set_option old_structure_cmd true /-- An `ordered_comm_monoid` with one-sided 'division' in the sense that if `a ≤ b`, there is some `c` for which `a * c = b`. This is a weaker version of the condition on canonical orderings defined by `canonically_ordered_monoid`. -/ class has_exists_mul_of_le (α : Type u) [has_mul α] [has_le α] : Prop := (exists_mul_of_le : ∀ {a b : α}, a ≤ b → ∃ (c : α), b = a * c) /-- An `ordered_add_comm_monoid` with one-sided 'subtraction' in the sense that if `a ≤ b`, then there is some `c` for which `a + c = b`. This is a weaker version of the condition on canonical orderings defined by `canonically_ordered_add_monoid`. -/ class has_exists_add_of_le (α : Type u) [has_add α] [has_le α] : Prop := (exists_add_of_le : ∀ {a b : α}, a ≤ b → ∃ (c : α), b = a + c) attribute [to_additive] has_exists_mul_of_le export has_exists_mul_of_le (exists_mul_of_le) export has_exists_add_of_le (exists_add_of_le) @[priority 100, to_additive] -- See note [lower instance priority] instance group.has_exists_mul_of_le (α : Type u) [group α] [has_le α] : has_exists_mul_of_le α := ⟨λ a b hab, ⟨a⁻¹ * b, (mul_inv_cancel_left _ _).symm⟩⟩ section mul_one_class variables [mul_one_class α] [preorder α] [contravariant_class α α (*) (<)] [has_exists_mul_of_le α] {a b : α} @[to_additive] lemma exists_one_lt_mul_of_lt' (h : a < b) : ∃ c, 1 < c ∧ a * c = b := by { obtain ⟨c, rfl⟩ := exists_mul_of_le h.le, exact ⟨c, one_lt_of_lt_mul_right h, rfl⟩ } end mul_one_class section has_exists_mul_of_le variables [linear_order α] [densely_ordered α] [monoid α] [has_exists_mul_of_le α] [covariant_class α α (*) (<)] [contravariant_class α α (*) (<)] {a b : α} @[to_additive] lemma le_of_forall_one_lt_le_mul (h : ∀ ε : α, 1 < ε → a ≤ b * ε) : a ≤ b := le_of_forall_le_of_dense $ λ x hxb, by { obtain ⟨ε, rfl⟩ := exists_mul_of_le hxb.le, exact h _ ((lt_mul_iff_one_lt_right' b).1 hxb) } @[to_additive] lemma le_of_forall_one_lt_lt_mul' (h : ∀ ε : α, 1 < ε → a < b * ε) : a ≤ b := le_of_forall_one_lt_le_mul $ λ ε hε, (h _ hε).le @[to_additive] lemma le_iff_forall_one_lt_lt_mul' : a ≤ b ↔ ∀ ε, 1 < ε → a < b * ε := ⟨λ h ε, lt_mul_of_le_of_one_lt h, le_of_forall_one_lt_lt_mul'⟩ end has_exists_mul_of_le /-- A canonically ordered additive monoid is an ordered commutative additive monoid in which the ordering coincides with the subtractibility relation, which is to say, `a ≤ b` iff there exists `c` with `b = a + c`. This is satisfied by the natural numbers, for example, but not the integers or other nontrivial `ordered_add_comm_group`s. -/ @[protect_proj, ancestor ordered_add_comm_monoid has_bot] class canonically_ordered_add_monoid (α : Type*) extends ordered_add_comm_monoid α, has_bot α := (bot_le : ∀ x : α, ⊥ ≤ x) (exists_add_of_le : ∀ {a b : α}, a ≤ b → ∃ c, b = a + c) (le_self_add : ∀ a b : α, a ≤ a + b) @[priority 100] -- see Note [lower instance priority] instance canonically_ordered_add_monoid.to_order_bot (α : Type u) [h : canonically_ordered_add_monoid α] : order_bot α := { ..h } /-- A canonically ordered monoid is an ordered commutative monoid in which the ordering coincides with the divisibility relation, which is to say, `a ≤ b` iff there exists `c` with `b = a * c`. Examples seem rare; it seems more likely that the `order_dual` of a naturally-occurring lattice satisfies this than the lattice itself (for example, dual of the lattice of ideals of a PID or Dedekind domain satisfy this; collections of all things ≤ 1 seem to be more natural that collections of all things ≥ 1). -/ @[protect_proj, ancestor ordered_comm_monoid has_bot, to_additive] class canonically_ordered_monoid (α : Type*) extends ordered_comm_monoid α, has_bot α := (bot_le : ∀ x : α, ⊥ ≤ x) (exists_mul_of_le : ∀ {a b : α}, a ≤ b → ∃ c, b = a * c) (le_self_mul : ∀ a b : α, a ≤ a * b) @[priority 100, to_additive] -- see Note [lower instance priority] instance canonically_ordered_monoid.to_order_bot (α : Type u) [h : canonically_ordered_monoid α] : order_bot α := { ..h } @[priority 100, to_additive] -- see Note [lower instance priority] instance canonically_ordered_monoid.has_exists_mul_of_le (α : Type u) [h : canonically_ordered_monoid α] : has_exists_mul_of_le α := { ..h } section canonically_ordered_monoid variables [canonically_ordered_monoid α] {a b c d : α} @[to_additive] lemma le_self_mul : a ≤ a * c := canonically_ordered_monoid.le_self_mul _ _ @[to_additive] lemma le_mul_self : a ≤ b * a := by { rw mul_comm, exact le_self_mul } @[to_additive] lemma self_le_mul_right (a b : α) : a ≤ a * b := le_self_mul @[to_additive] lemma self_le_mul_left (a b : α) : a ≤ b * a := le_mul_self @[to_additive] lemma le_of_mul_le_left : a * b ≤ c → a ≤ c := le_self_mul.trans @[to_additive] lemma le_of_mul_le_right : a * b ≤ c → b ≤ c := le_mul_self.trans @[to_additive] lemma le_mul_of_le_left : a ≤ b → a ≤ b * c := le_self_mul.trans' @[to_additive] lemma le_mul_of_le_right : a ≤ c → a ≤ b * c := le_mul_self.trans' @[to_additive] lemma le_iff_exists_mul : a ≤ b ↔ ∃ c, b = a * c := ⟨exists_mul_of_le, by { rintro ⟨c, rfl⟩, exact le_self_mul }⟩ @[to_additive] lemma le_iff_exists_mul' : a ≤ b ↔ ∃ c, b = c * a := by simpa only [mul_comm _ a] using le_iff_exists_mul @[simp, to_additive zero_le] lemma one_le (a : α) : 1 ≤ a := le_iff_exists_mul.mpr ⟨a, (one_mul _).symm⟩ @[to_additive] lemma bot_eq_one : (⊥ : α) = 1 := le_antisymm bot_le (one_le ⊥) --TODO: This is a special case of `mul_eq_one`. We need the instance -- `canonically_ordered_monoid α → unique αˣ` @[simp, to_additive] lemma mul_eq_one_iff : a * b = 1 ↔ a = 1 ∧ b = 1 := mul_eq_one_iff' (one_le _) (one_le _) @[simp, to_additive] lemma le_one_iff_eq_one : a ≤ 1 ↔ a = 1 := (one_le a).le_iff_eq @[to_additive] lemma one_lt_iff_ne_one : 1 < a ↔ a ≠ 1 := (one_le a).lt_iff_ne.trans ne_comm @[to_additive] lemma eq_one_or_one_lt : a = 1 ∨ 1 < a := (one_le a).eq_or_lt.imp_left eq.symm @[simp, to_additive add_pos_iff] lemma one_lt_mul_iff : 1 < a * b ↔ 1 < a ∨ 1 < b := by simp only [one_lt_iff_ne_one, ne.def, mul_eq_one_iff, not_and_distrib] @[to_additive] lemma exists_one_lt_mul_of_lt (h : a < b) : ∃ c (hc : 1 < c), a * c = b := begin obtain ⟨c, hc⟩ := le_iff_exists_mul.1 h.le, refine ⟨c, one_lt_iff_ne_one.2 _, hc.symm⟩, rintro rfl, simpa [hc, lt_irrefl] using h end @[to_additive] lemma le_mul_left (h : a ≤ c) : a ≤ b * c := calc a = 1 * a : by simp ... ≤ b * c : mul_le_mul' (one_le _) h @[to_additive] lemma le_mul_right (h : a ≤ b) : a ≤ b * c := calc a = a * 1 : by simp ... ≤ b * c : mul_le_mul' h (one_le _) @[to_additive] lemma lt_iff_exists_mul [covariant_class α α (*) (<)] : a < b ↔ ∃ c > 1, b = a * c := begin simp_rw [lt_iff_le_and_ne, and_comm, le_iff_exists_mul, ← exists_and_distrib_left, exists_prop], apply exists_congr, intro c, rw [and.congr_left_iff, gt_iff_lt], rintro rfl, split, { rw [one_lt_iff_ne_one], apply mt, rintro rfl, rw [mul_one] }, { rw [← (self_le_mul_right a c).lt_iff_ne], apply lt_mul_of_one_lt_right' } end end canonically_ordered_monoid lemma pos_of_gt {M : Type*} [canonically_ordered_add_monoid M] {n m : M} (h : n < m) : 0 < m := lt_of_le_of_lt (zero_le _) h namespace ne_zero lemma pos {M} (a : M) [canonically_ordered_add_monoid M] [ne_zero a] : 0 < a := (zero_le a).lt_of_ne $ ne_zero.out.symm lemma of_gt {M} [canonically_ordered_add_monoid M] {x y : M} (h : x < y) : ne_zero y := of_pos $ pos_of_gt h -- 1 < p is still an often-used `fact`, due to `nat.prime` implying it, and it implying `nontrivial` -- on `zmod`'s ring structure. We cannot just set this to be any `x < y`, else that becomes a -- metavariable and it will hugely slow down typeclass inference. @[priority 10] instance of_gt' {M} [canonically_ordered_add_monoid M] [has_one M] {y : M} [fact (1 < y)] : ne_zero y := of_gt $ fact.out $ 1 < y instance bit0 {M} [canonically_ordered_add_monoid M] {x : M} [ne_zero x] : ne_zero (bit0 x) := of_pos $ bit0_pos $ ne_zero.pos x end ne_zero /-- A canonically linear-ordered additive monoid is a canonically ordered additive monoid whose ordering is a linear order. -/ @[protect_proj, ancestor canonically_ordered_add_monoid linear_order] class canonically_linear_ordered_add_monoid (α : Type*) extends canonically_ordered_add_monoid α, linear_order α /-- A canonically linear-ordered monoid is a canonically ordered monoid whose ordering is a linear order. -/ @[protect_proj, ancestor canonically_ordered_monoid linear_order, to_additive] class canonically_linear_ordered_monoid (α : Type*) extends canonically_ordered_monoid α, linear_order α section canonically_linear_ordered_monoid variables [canonically_linear_ordered_monoid α] @[priority 100, to_additive] -- see Note [lower instance priority] instance canonically_linear_ordered_monoid.semilattice_sup : semilattice_sup α := { ..linear_order.to_lattice } @[to_additive] lemma min_mul_distrib (a b c : α) : min a (b * c) = min a (min a b * min a c) := begin cases le_total a b with hb hb, { simp [hb, le_mul_right] }, { cases le_total a c with hc hc, { simp [hc, le_mul_left] }, { simp [hb, hc] } } end @[to_additive] lemma min_mul_distrib' (a b c : α) : min (a * b) c = min (min a c * min b c) c := by simpa [min_comm _ c] using min_mul_distrib c a b @[simp, to_additive] lemma one_min (a : α) : min 1 a = 1 := min_eq_left (one_le a) @[simp, to_additive] lemma min_one (a : α) : min a 1 = 1 := min_eq_right (one_le a) /-- In a linearly ordered monoid, we are happy for `bot_eq_one` to be a `@[simp]` lemma. -/ @[simp, to_additive "In a linearly ordered monoid, we are happy for `bot_eq_zero` to be a `@[simp]` lemma"] lemma bot_eq_one' : (⊥ : α) = 1 := bot_eq_one end canonically_linear_ordered_monoid
20c978eb26890b389fe4d65cc2510ac31fb290e3
3f7026ea8bef0825ca0339a275c03b911baef64d
/src/tactic/basic.lean
222f973e580b242c283bc6792a5d22a707236631
[ "Apache-2.0" ]
permissive
rspencer01/mathlib
b1e3afa5c121362ef0881012cc116513ab09f18c
c7d36292c6b9234dc40143c16288932ae38fdc12
refs/heads/master
1,595,010,346,708
1,567,511,503,000
1,567,511,503,000
206,071,681
0
0
Apache-2.0
1,567,513,643,000
1,567,513,643,000
null
UTF-8
Lean
false
false
414
lean
import tactic.alias tactic.cache tactic.converter.interactive tactic.core tactic.doc_blame tactic.ext tactic.generalize_proofs tactic.interactive tactic.library_search tactic.lift tactic.mk_iff_of_inductive_prop tactic.push_neg tactic.rcases tactic.replacer tactic.restate_axiom tactic.rewrite tactic.sanity_check tactic.simpa tactic.split_ifs tactic.squeeze tactic.where
bf40f0f2a04f6091f1a2b2ea5cfcd22e3df45882
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/category_theory/instances/Top/adjunctions.lean
f8dca5472c67cf1fec32e8ac1768e4e0f7b86d52
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
943
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Patrick Massot, Mario Carneiro import category_theory.instances.Top.basic import category_theory.adjunction universe u open category_theory open category_theory.instances namespace category_theory.instances.Top def adj₁ : adjunction discrete forget := { hom_equiv := λ X Y, { to_fun := λ f, f, inv_fun := λ f, ⟨f, continuous_top⟩, left_inv := by tidy, right_inv := by tidy }, unit := { app := λ X, id }, counit := { app := λ X, ⟨id, continuous_top⟩ } } def adj₂ : adjunction forget trivial := { hom_equiv := λ X Y, { to_fun := λ f, ⟨f, continuous_bot⟩, inv_fun := λ f, f, left_inv := by tidy, right_inv := by tidy }, unit := { app := λ X, ⟨id, continuous_bot⟩ }, counit := { app := λ X, id } } end category_theory.instances.Top
29e5e76c814d00d2f2ad08eb6b3b83a96e8b80e1
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch2/ex0801.lean
f6217476304cb6579f4e72828360f8fa30bd6320
[]
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
352
lean
namespace hidden universe u constant list : Type u → Type u constant cons : Π α : Type u, α → list α → list α constant nil : Π α : Type u, list α constant head : Π α : Type u, list α → α constant tail : Π α : Type u, list α → list α constant append : Π α : Type u, list α → list α → list α end hidden
b0b0a8c8479330a11d24bcf7423363d34f073c3f
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/meta/smt/ematch.lean
952f36990a7d8c465a723fe066feefd462166b76
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
1,201
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 -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.meta.smt.congruence_closure import Mathlib.Lean3Lib.init.meta.attribute import Mathlib.Lean3Lib.init.meta.simp_tactic import Mathlib.Lean3Lib.init.meta.interactive_base import Mathlib.Lean3Lib.init.meta.derive universes l namespace Mathlib /-- Heuristic instantiation lemma -/ /-- `mk_core m e as_simp`, m is used to decide which definitions will be unfolded in patterns. If as_simp is tt, then this tactic will try to use the left-hand-side of the conclusion as a pattern. -/ /-- Create a new "cached" attribute (attr_name : user_attribute hinst_lemmas). It also creates "cached" attributes for each attr_names and simp_attr_names if they have not been defined yet. Moreover, the hinst_lemmas for attr_name will be the union of the lemmas tagged with attr_name, attrs_name, and simp_attr_names. For the ones in simp_attr_names, we use the left-hand-side of the conclusion as the pattern. -/ structure ematch_config where max_instances : ℕ max_generation : ℕ
53cb7bc7b3127bc259e6a4eefc80168e6128580a
976d2334b51721ddc405deb2e1754016d454286e
/src/QQuiz/2012_q4.lean
5ee5f45ff289c185d02dd55fcb5e9649db023999
[]
no_license
kbuzzard/lean-at-MC2020
11bb6ac9ec38a6caace9d5d9a1705d6794d9f477
1f7ca65a7ba5cc17eb49f525c02dc6b0e65d6543
refs/heads/master
1,668,496,422,317
1,594,131,838,000
1,594,131,838,000
277,877,735
0
0
null
1,594,142,006,000
1,594,142,005,000
null
UTF-8
Lean
false
false
779
lean
import tactic import data.real.basic noncomputable theory open_locale classical -- Let a be a rational number with 0 < a < 1. -- A lollipop in the xy-plane with base (a,0) consists of ---- a line segment from (a,0) to some point (a,b) with b > 0, ---- together with a filled in disc of radius less than b, centered at (a,b). def lollipop (a b r : ℝ) (hb : 0 < b) (hr : r < b) : set ℝ := begin end -- Determine whether or not it is possible to have a set of lollipops in the xy-plane satisfying both of the following conditions: -- for every rational number a with 0 < a < 1, there is a lollipop whose base is the point (a,0), -- no two lollipops touch or overlap each other. -- If such a set of lollipops exists, explain how to construct it. If not, justify why not.
800b6785ec4eedd6128e4e635656c06b3c3cf8b2
4727251e0cd73359b15b664c3170e5d754078599
/src/probability/integration.lean
25f55ffae32319eef026fb6d90a25af3f0570fd7
[ "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
13,732
lean
/- Copyright (c) 2021 Martin Zinkevich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Martin Zinkevich, Vincent Beffara -/ import measure_theory.integral.set_integral import probability.independence /-! # Integration in Probability Theory Integration results for independent random variables. Specifically, for two independent random variables X and Y over the extended non-negative reals, `E[X * Y] = E[X] * E[Y]`, and similar results. ## Implementation notes Many lemmas in this file take two arguments of the same typeclass. It is worth remembering that lean will always pick the later typeclass in this situation, and does not care whether the arguments are `[]`, `{}`, or `()`. All of these use the `measurable_space` `M2` to define `μ`: ```lean example {M1 : measurable_space α} [M2 : measurable_space α] {μ : measure α} : sorry := sorry example [M1 : measurable_space α] {M2 : measurable_space α} {μ : measure α} : sorry := sorry ``` -/ noncomputable theory open set measure_theory open_locale ennreal variables {α : Type*} {mα : measurable_space α} {μ : measure α} {f g : α → ℝ≥0∞} {X Y : α → ℝ} namespace probability_theory /-- If a random variable `f` in `ℝ≥0∞` is independent of an event `T`, then if you restrict the random variable to `T`, then `E[f * indicator T c 0]=E[f] * E[indicator T c 0]`. It is useful for `lintegral_mul_eq_lintegral_mul_lintegral_of_independent_measurable_space`. -/ lemma lintegral_mul_indicator_eq_lintegral_mul_lintegral_indicator {Mf mα : measurable_space α} {μ : measure α} (hMf : Mf ≤ mα) (c : ℝ≥0∞) {T : set α} (h_meas_T : measurable_set T) (h_ind : indep_sets Mf.measurable_set' {T} μ) (h_meas_f : @measurable α ℝ≥0∞ Mf _ f) : ∫⁻ a, f a * T.indicator (λ _, c) a ∂μ = ∫⁻ a, f a ∂μ * ∫⁻ a, T.indicator (λ _, c) a ∂μ := begin revert f, have h_mul_indicator : ∀ g, measurable g → measurable (λ a, g a * T.indicator (λ x, c) a), from λ g h_mg, h_mg.mul (measurable_const.indicator h_meas_T), apply measurable.ennreal_induction, { intros c' s' h_meas_s', simp_rw [← inter_indicator_mul], rw [lintegral_indicator _ (measurable_set.inter (hMf _ h_meas_s') (h_meas_T)), lintegral_indicator _ (hMf _ h_meas_s'), lintegral_indicator _ h_meas_T], simp only [measurable_const, lintegral_const, univ_inter, lintegral_const_mul, measurable_set.univ, measure.restrict_apply], ring_nf, congr, rw [mul_comm, h_ind s' T h_meas_s' (set.mem_singleton _)], }, { intros f' g h_univ h_meas_f' h_meas_g h_ind_f' h_ind_g, have h_measM_f' : measurable f', from h_meas_f'.mono hMf le_rfl, have h_measM_g : measurable g, from h_meas_g.mono hMf le_rfl, simp_rw [pi.add_apply, right_distrib], rw [lintegral_add (h_mul_indicator _ h_measM_f') (h_mul_indicator _ h_measM_g), lintegral_add h_measM_f' h_measM_g, right_distrib, h_ind_f', h_ind_g] }, { intros f h_meas_f h_mono_f h_ind_f, have h_measM_f : ∀ n, measurable (f n), from λ n, (h_meas_f n).mono hMf le_rfl, simp_rw [ennreal.supr_mul], rw [lintegral_supr h_measM_f h_mono_f, lintegral_supr, ennreal.supr_mul], { simp_rw [← h_ind_f] }, { exact λ n, h_mul_indicator _ (h_measM_f n) }, { exact λ m n h_le a, ennreal.mul_le_mul (h_mono_f h_le a) le_rfl, }, }, end /-- If `f` and `g` are independent random variables with values in `ℝ≥0∞`, then `E[f * g] = E[f] * E[g]`. However, instead of directly using the independence of the random variables, it uses the independence of measurable spaces for the domains of `f` and `g`. This is similar to the sigma-algebra approach to independence. See `lintegral_mul_eq_lintegral_mul_lintegral_of_independent_fn` for a more common variant of the product of independent variables. -/ lemma lintegral_mul_eq_lintegral_mul_lintegral_of_independent_measurable_space {Mf Mg mα : measurable_space α} {μ : measure α} (hMf : Mf ≤ mα) (hMg : Mg ≤ mα) (h_ind : indep Mf Mg μ) (h_meas_f : @measurable α ℝ≥0∞ Mf _ f) (h_meas_g : @measurable α ℝ≥0∞ Mg _ g) : ∫⁻ a, f a * g a ∂μ = ∫⁻ a, f a ∂μ * ∫⁻ a, g a ∂μ := begin revert g, have h_measM_f : measurable f, from h_meas_f.mono hMf le_rfl, apply measurable.ennreal_induction, { intros c s h_s, apply lintegral_mul_indicator_eq_lintegral_mul_lintegral_indicator hMf _ (hMg _ h_s) _ h_meas_f, apply indep_sets_of_indep_sets_of_le_right h_ind, rwa singleton_subset_iff, }, { intros f' g h_univ h_measMg_f' h_measMg_g h_ind_f' h_ind_g', have h_measM_f' : measurable f', from h_measMg_f'.mono hMg le_rfl, have h_measM_g : measurable g, from h_measMg_g.mono hMg le_rfl, simp_rw [pi.add_apply, left_distrib], rw [lintegral_add h_measM_f' h_measM_g, lintegral_add (h_measM_f.mul h_measM_f') (h_measM_f.mul h_measM_g), left_distrib, h_ind_f', h_ind_g'] }, { intros f' h_meas_f' h_mono_f' h_ind_f', have h_measM_f' : ∀ n, measurable (f' n), from λ n, (h_meas_f' n).mono hMg le_rfl, simp_rw [ennreal.mul_supr], rw [lintegral_supr, lintegral_supr h_measM_f' h_mono_f', ennreal.mul_supr], { simp_rw [← h_ind_f'], }, { exact λ n, h_measM_f.mul (h_measM_f' n), }, { exact λ n m (h_le : n ≤ m) a, ennreal.mul_le_mul le_rfl (h_mono_f' h_le a), }, } end /-- If `f` and `g` are independent random variables with values in `ℝ≥0∞`, then `E[f * g] = E[f] * E[g]`. -/ lemma lintegral_mul_eq_lintegral_mul_lintegral_of_indep_fun (h_meas_f : measurable f) (h_meas_g : measurable g) (h_indep_fun : indep_fun f g μ) : ∫⁻ a, (f * g) a ∂μ = ∫⁻ a, f a ∂μ * ∫⁻ a, g a ∂μ := lintegral_mul_eq_lintegral_mul_lintegral_of_independent_measurable_space (measurable_iff_comap_le.1 h_meas_f) (measurable_iff_comap_le.1 h_meas_g) h_indep_fun (measurable.of_comap_le le_rfl) (measurable.of_comap_le le_rfl) /-- If `f` and `g` with values in `ℝ≥0∞` are independent and almost everywhere measurable, then `E[f * g] = E[f] * E[g]` (slightly generalizing `lintegral_mul_eq_lintegral_mul_lintegral_of_indep_fun`). -/ lemma lintegral_mul_eq_lintegral_mul_lintegral_of_indep_fun' (h_meas_f : ae_measurable f μ) (h_meas_g : ae_measurable g μ) (h_indep_fun : indep_fun f g μ) : ∫⁻ a, (f * g) a ∂μ = ∫⁻ a, f a ∂μ * ∫⁻ a, g a ∂μ := begin have fg_ae : f * g =ᵐ[μ] (h_meas_f.mk _) * (h_meas_g.mk _), from h_meas_f.ae_eq_mk.mul h_meas_g.ae_eq_mk, rw [lintegral_congr_ae h_meas_f.ae_eq_mk, lintegral_congr_ae h_meas_g.ae_eq_mk, lintegral_congr_ae fg_ae], apply lintegral_mul_eq_lintegral_mul_lintegral_of_indep_fun h_meas_f.measurable_mk h_meas_g.measurable_mk, exact h_indep_fun.ae_eq h_meas_f.ae_eq_mk h_meas_g.ae_eq_mk end /-- The product of two independent, integrable, real_valued random variables is integrable. -/ lemma indep_fun.integrable_mul {β : Type*} [measurable_space β] {X Y : α → β} [normed_division_ring β] [borel_space β] (hXY : indep_fun X Y μ) (hX : integrable X μ) (hY : integrable Y μ) : integrable (X * Y) μ := begin let nX : α → ennreal := λ a, ∥X a∥₊, let nY : α → ennreal := λ a, ∥Y a∥₊, have hXY' : indep_fun (λ a, ∥X a∥₊) (λ a, ∥Y a∥₊) μ := hXY.comp measurable_nnnorm measurable_nnnorm, have hXY'' : indep_fun nX nY μ := hXY'.comp measurable_coe_nnreal_ennreal measurable_coe_nnreal_ennreal, have hnX : ae_measurable nX μ := hX.1.ae_measurable.nnnorm.coe_nnreal_ennreal, have hnY : ae_measurable nY μ := hY.1.ae_measurable.nnnorm.coe_nnreal_ennreal, have hmul : ∫⁻ a, nX a * nY a ∂μ = ∫⁻ a, nX a ∂μ * ∫⁻ a, nY a ∂μ := by convert lintegral_mul_eq_lintegral_mul_lintegral_of_indep_fun' hnX hnY hXY'', refine ⟨hX.1.mul hY.1, _⟩, simp_rw [has_finite_integral, pi.mul_apply, nnnorm_mul, ennreal.coe_mul, hmul], exact ennreal.mul_lt_top_iff.mpr (or.inl ⟨hX.2, hY.2⟩) end /-- The (Bochner) integral of the product of two independent, nonnegative random variables is the product of their integrals. The proof is just plumbing around `lintegral_mul_eq_lintegral_mul_lintegral_of_indep_fun'`. -/ lemma indep_fun.integral_mul_of_nonneg (hXY : indep_fun X Y μ) (hXp : 0 ≤ X) (hYp : 0 ≤ Y) (hXm : ae_measurable X μ) (hYm : ae_measurable Y μ) : integral μ (X * Y) = integral μ X * integral μ Y := begin have h1 : ae_measurable (λ a, ennreal.of_real (X a)) μ := ennreal.measurable_of_real.comp_ae_measurable hXm, have h2 : ae_measurable (λ a, ennreal.of_real (Y a)) μ := ennreal.measurable_of_real.comp_ae_measurable hYm, have h3 : ae_measurable (X * Y) μ := hXm.mul hYm, have h4 : 0 ≤ᵐ[μ] (X * Y) := ae_of_all _ (λ ω, mul_nonneg (hXp ω) (hYp ω)), rw [integral_eq_lintegral_of_nonneg_ae (ae_of_all _ hXp) hXm.ae_strongly_measurable, integral_eq_lintegral_of_nonneg_ae (ae_of_all _ hYp) hYm.ae_strongly_measurable, integral_eq_lintegral_of_nonneg_ae h4 h3.ae_strongly_measurable], simp_rw [←ennreal.to_real_mul, pi.mul_apply, ennreal.of_real_mul (hXp _)], congr, apply lintegral_mul_eq_lintegral_mul_lintegral_of_indep_fun' h1 h2, exact hXY.comp ennreal.measurable_of_real ennreal.measurable_of_real end /-- The (Bochner) integral of the product of two independent, integrable random variables is the product of their integrals. The proof is pedestrian decomposition into their positive and negative parts in order to apply `indep_fun.integral_mul_of_nonneg` four times. -/ theorem indep_fun.integral_mul_of_integrable (hXY : indep_fun X Y μ) (hX : integrable X μ) (hY : integrable Y μ) : integral μ (X * Y) = integral μ X * integral μ Y := begin let pos : ℝ → ℝ := (λ x, max x 0), let neg : ℝ → ℝ := (λ x, max (-x) 0), have posm : measurable pos := measurable_id'.max measurable_const, have negm : measurable neg := measurable_id'.neg.max measurable_const, let Xp := pos ∘ X, -- `X⁺` would look better but it makes `simp_rw` below fail let Xm := neg ∘ X, let Yp := pos ∘ Y, let Ym := neg ∘ Y, have hXpm : X = Xp - Xm := funext (λ ω, (max_zero_sub_max_neg_zero_eq_self (X ω)).symm), have hYpm : Y = Yp - Ym := funext (λ ω, (max_zero_sub_max_neg_zero_eq_self (Y ω)).symm), have hp1 : 0 ≤ Xm := λ ω, le_max_right _ _, have hp2 : 0 ≤ Xp := λ ω, le_max_right _ _, have hp3 : 0 ≤ Ym := λ ω, le_max_right _ _, have hp4 : 0 ≤ Yp := λ ω, le_max_right _ _, have hm1 : ae_measurable Xm μ := hX.1.ae_measurable.neg.max ae_measurable_const, have hm2 : ae_measurable Xp μ := hX.1.ae_measurable.max ae_measurable_const, have hm3 : ae_measurable Ym μ := hY.1.ae_measurable.neg.max ae_measurable_const, have hm4 : ae_measurable Yp μ := hY.1.ae_measurable.max ae_measurable_const, have hv1 : integrable Xm μ := hX.neg_part, have hv2 : integrable Xp μ := hX.pos_part, have hv3 : integrable Ym μ := hY.neg_part, have hv4 : integrable Yp μ := hY.pos_part, have hi1 : indep_fun Xm Ym μ := hXY.comp negm negm, have hi2 : indep_fun Xp Ym μ := hXY.comp posm negm, have hi3 : indep_fun Xm Yp μ := hXY.comp negm posm, have hi4 : indep_fun Xp Yp μ := hXY.comp posm posm, have hl1 : integrable (Xm * Ym) μ := hi1.integrable_mul hv1 hv3, have hl2 : integrable (Xp * Ym) μ := hi2.integrable_mul hv2 hv3, have hl3 : integrable (Xm * Yp) μ := hi3.integrable_mul hv1 hv4, have hl4 : integrable (Xp * Yp) μ := hi4.integrable_mul hv2 hv4, have hl5 : integrable (Xp * Yp - Xm * Yp) μ := hl4.sub hl3, have hl6 : integrable (Xp * Ym - Xm * Ym) μ := hl2.sub hl1, simp_rw [hXpm, hYpm, mul_sub, sub_mul], rw [integral_sub' hl5 hl6, integral_sub' hl4 hl3, integral_sub' hl2 hl1, integral_sub' hv2 hv1, integral_sub' hv4 hv3, hi1.integral_mul_of_nonneg hp1 hp3 hm1 hm3, hi2.integral_mul_of_nonneg hp2 hp3 hm2 hm3, hi3.integral_mul_of_nonneg hp1 hp4 hm1 hm4, hi4.integral_mul_of_nonneg hp2 hp4 hm2 hm4], ring end theorem indep_fun.integral_mul_of_integrable' (hXY : indep_fun X Y μ) (hX : integrable X μ) (hY : integrable Y μ) : integral μ (λ x, X x * Y x) = integral μ X * integral μ Y := hXY.integral_mul_of_integrable hX hY /-- Independence of functions `f` and `g` into arbitrary types is characterized by the relation `E[(φ ∘ f) * (ψ ∘ g)] = E[φ ∘ f] * E[ψ ∘ g]` for all measurable `φ` and `ψ` with values in `ℝ` satisfying appropriate integrability conditions. -/ theorem indep_fun_iff_integral_comp_mul [is_finite_measure μ] {β β' : Type*} {mβ : measurable_space β} {mβ' : measurable_space β'} {f : α → β} {g : α → β'} {hfm : measurable f} {hgm : measurable g} : indep_fun f g μ ↔ ∀ {φ : β → ℝ} {ψ : β' → ℝ}, measurable φ → measurable ψ → integrable (φ ∘ f) μ → integrable (ψ ∘ g) μ → integral μ ((φ ∘ f) * (ψ ∘ g)) = integral μ (φ ∘ f) * integral μ (ψ ∘ g) := begin refine ⟨λ hfg _ _ hφ hψ, indep_fun.integral_mul_of_integrable (hfg.comp hφ hψ), _⟩, rintro h _ _ ⟨A, hA, rfl⟩ ⟨B, hB, rfl⟩, specialize h (measurable_one.indicator hA) (measurable_one.indicator hB) ((integrable_const 1).indicator (hfm.comp measurable_id hA)) ((integrable_const 1).indicator (hgm.comp measurable_id hB)), rwa [← ennreal.to_real_eq_to_real (measure_ne_top μ _), ennreal.to_real_mul, ← integral_indicator_one ((hfm hA).inter (hgm hB)), ← integral_indicator_one (hfm hA), ← integral_indicator_one (hgm hB), set.inter_indicator_one], exact ennreal.mul_ne_top (measure_ne_top μ _) (measure_ne_top μ _) end end probability_theory
a041b7c659ad0175a47730bf54e6192a0df4b409
e61a235b8468b03aee0120bf26ec615c045005d2
/src/Init/Lean/Delaborator.lean
6d1e159663a37a7824a1a4d881a37d53d2094d84
[ "Apache-2.0" ]
permissive
SCKelemen/lean4
140dc63a80539f7c61c8e43e1c174d8500ec3230
e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc
refs/heads/master
1,660,973,595,917
1,590,278,033,000
1,590,278,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,785
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ /-! The delaborator is the first stage of the pretty printer, and the inverse of the elaborator: it turns fully elaborated `Expr` core terms back into surface-level `Syntax`, omitting some implicit information again and using higher-level syntax abstractions like notations where possible. The exact behavior can be customized using pretty printer options; activating `pp.all` should guarantee that the delaborator is injective and that re-elaborating the resulting `Syntax` round-trips. Pretty printer options can be given not only for the whole term, but also specific subterms. This is used both when automatically refining pp options until round-trip and when interactively selecting pp options for a subterm (both TBD). The association of options to subterms is done by assigning a unique, synthetic Nat position to each subterm derived from its position in the full term. This position is added to the corresponding Syntax object so that elaboration errors and interactions with the pretty printer output can be traced back to the subterm. The delaborator is extensible via the `[delab]` attribute. -/ prelude import Init.Lean.KeyedDeclsAttribute import Init.Lean.ProjFns import Init.Lean.Syntax import Init.Lean.Elab.Term namespace Lean -- TODO: move, maybe namespace Level protected partial def quote : Level → Syntax | zero _ => Unhygienic.run `(level|0) | l@(succ _ _) => match l.toNat with | some n => Unhygienic.run `(level|$(mkStxNumLitAux n):numLit) | none => Unhygienic.run `(level|$(quote l.getLevelOffset) + $(mkStxNumLitAux l.getOffset):numLit) | max l1 l2 _ => match_syntax quote l2 with | `(level|max $ls*) => Unhygienic.run `(level|max $(quote l1) $ls*) | l2 => Unhygienic.run `(level|max $(quote l1) $l2) | imax l1 l2 _ => match_syntax quote l2 with | `(level|imax $ls*) => Unhygienic.run `(level|imax $(quote l1) $ls*) | l2 => Unhygienic.run `(level|imax $(quote l1) $l2) | param n _ => Unhygienic.run `(level|$(mkIdent n):ident) -- HACK: approximation | mvar n _ => Unhygienic.run `(level|_) instance HasQuote : HasQuote Level := ⟨Level.quote⟩ end Level def getPPBinderTypes (o : Options) : Bool := o.get `pp.binder_types true def getPPCoercions (o : Options) : Bool := o.get `pp.coercions true def getPPExplicit (o : Options) : Bool := o.get `pp.explicit false def getPPStructureProjections (o : Options) : Bool := o.get `pp.structure_projections true def getPPUniverses (o : Options) : Bool := o.get `pp.universes false def getPPAll (o : Options) : Bool := o.get `pp.all false @[init] def ppOptions : IO Unit := do registerOption `pp.explicit { defValue := false, group := "pp", descr := "(pretty printer) display implicit arguments" }; -- TODO: register other options when old pretty printer is removed --registerOption `pp.universes { defValue := false, group := "pp", descr := "(pretty printer) display universes" }; pure () /-- Associate pretty printer options to a specific subterm using a synthetic position. -/ abbrev OptionsPerPos := RBMap Nat Options (fun a b => a < b) namespace Delaborator open Lean.Meta structure Context := -- In contrast to other systems like the elaborator, we do not pass the current term explicitly as a -- parameter, but store it in the monad so that we can keep it in sync with `pos`. (expr : Expr) (pos : Nat := 1) (defaultOptions : Options) (optionsPerPos : OptionsPerPos) -- Exceptions from delaborators are not expected, so use a simple `OptionT` to signal whether -- the delaborator was able to produce a Syntax object. abbrev DelabM := ReaderT Context $ OptionT MetaM abbrev Delab := DelabM Syntax instance DelabM.inhabited {α} : Inhabited (DelabM α) := ⟨failure⟩ -- Macro scopes in the delaborator output are ultimately ignored by the pretty printer, -- so give a trivial implementation. instance DelabM.monadQuotation : MonadQuotation DelabM := { getCurrMacroScope := pure $ arbitrary _, getMainModule := pure $ arbitrary _, withFreshMacroScope := fun α x => x, } unsafe def mkDelabAttribute : IO (KeyedDeclsAttribute Delab) := KeyedDeclsAttribute.init { builtinName := `builtinDelab, name := `delab, descr := "Register a delaborator. [delab k] registers a declaration of type `Lean.Delaborator.Delab` for the `Lean.Expr` constructor `k`. Multiple delaborators for a single constructor are tried in turn until the first success. If the term to be delaborated is an application of a constant `c`, elaborators for `app.c` are tried first; this is also done for `Expr.const`s (\"nullary applications\") to reduce special casing. If the term is an `Expr.mdata` with a single key `k`, `mdata.k` is tried first.", valueTypeName := `Lean.Delaborator.Delab } `Lean.Delaborator.delabAttribute @[init mkDelabAttribute] constant delabAttribute : KeyedDeclsAttribute Delab := arbitrary _ def getExpr : DelabM Expr := do ctx ← read; pure ctx.expr def getExprKind : DelabM Name := do e ← getExpr; pure $ match e with | Expr.bvar _ _ => `bvar | Expr.fvar _ _ => `fvar | Expr.mvar _ _ => `mvar | Expr.sort _ _ => `sort | Expr.const c _ _ => -- we identify constants as "nullary applications" to reduce special casing `app ++ c | Expr.app fn _ _ => match fn.getAppFn with | Expr.const c _ _ => `app ++ c | _ => `app | Expr.lam _ _ _ _ => `lam | Expr.forallE _ _ _ _ => `forallE | Expr.letE _ _ _ _ _ => `letE | Expr.lit _ _ => `lit | Expr.mdata m _ _ => match m.entries with | [(key, _)] => `mdata ++ key | _ => `mdata | Expr.proj _ _ _ _ => `proj | Expr.localE _ _ _ _ => `localE /-- Evaluate option accessor, using subterm-specific options if set. Default to `true` if `pp.all` is set. -/ def getPPOption (opt : Options → Bool) : DelabM Bool := do ctx ← read; let opt := fun opts => opt opts || getPPAll opts; let val := opt ctx.defaultOptions; match ctx.optionsPerPos.find? ctx.pos with | some opts => pure $ opt opts | none => pure val def whenPPOption (opt : Options → Bool) (d : Delab) : Delab := do b ← getPPOption opt; if b then d else failure def whenNotPPOption (opt : Options → Bool) (d : Delab) : Delab := do b ← getPPOption opt; if b then failure else d /-- Descend into `child`, the `childIdx`-th subterm of the current term, and update position. Because `childIdx < 3` in the case of `Expr`, we can injectively map a path `childIdxs` to a natural number by computing the value of the 3-ary representation `1 :: childIdxs`, since n-ary representations without leading zeros are unique. Note that `pos` is initialized to `1` (case `childIdxs == []`). -/ def descend {α} (child : Expr) (childIdx : Nat) (d : DelabM α) : DelabM α := adaptReader (fun (cfg : Context) => { cfg with expr := child, pos := cfg.pos * 3 + childIdx }) d def withAppFn {α} (d : DelabM α) : DelabM α := do Expr.app fn _ _ ← getExpr | unreachable!; descend fn 0 d def withAppArg {α} (d : DelabM α) : DelabM α := do Expr.app _ arg _ ← getExpr | unreachable!; descend arg 1 d partial def withAppFnArgs {α} : DelabM α → (α → DelabM α) → DelabM α | fnD, argD => do Expr.app fn arg _ ← getExpr | fnD; a ← withAppFn (withAppFnArgs fnD argD); withAppArg (argD a) def withBindingDomain {α} (d : DelabM α) : DelabM α := do e ← getExpr; descend e.bindingDomain! 0 d def withBindingBody {α} (n : Name) (d : DelabM α) : DelabM α := do e ← getExpr; fun ctx => withLocalDecl n e.bindingDomain! e.binderInfo $ fun fvar => let b := e.bindingBody!.instantiate1 fvar; descend b 1 d ctx def withProj {α} (d : DelabM α) : DelabM α := do Expr.app fn _ _ ← getExpr | unreachable!; descend fn 0 d partial def annotatePos (pos : Nat) : Syntax → Syntax | stx@(Syntax.ident _ _ _ _) => stx.setInfo { pos := pos } -- Term.ids => annotate ident -- TODO: universes? | stx@(Syntax.node `Lean.Parser.Term.id args) => stx.modifyArg 0 annotatePos -- app => annotate function | stx@(Syntax.node `Lean.Parser.Term.app args) => stx.modifyArg 0 annotatePos -- otherwise, annotate first direct child token if any | stx => match stx.getArgs.findIdx? Syntax.isAtom with | some idx => stx.modifyArg idx (Syntax.setInfo { pos := pos }) | none => stx def annotateCurPos (stx : Syntax) : Delab := do ctx ← read; pure $ annotatePos ctx.pos stx partial def delabFor : Name → Delab | k => do env ← liftM getEnv; (match (delabAttribute.ext.getState env).table.find? k with | some delabs => delabs.firstM id >>= annotateCurPos | none => failure) <|> (match k with | Name.str Name.anonymous _ _ => failure | Name.str n _ _ => delabFor n.getRoot -- have `app.Option.some` fall back to `app` etc. | _ => failure) def delab : Delab := do k ← getExprKind; delabFor k <|> (liftM $ show MetaM Syntax from throw $ Meta.Exception.other $ "don't know how to delaborate '" ++ toString k ++ "'") @[builtinDelab fvar] def delabFVar : Delab := do Expr.fvar id _ ← getExpr | unreachable!; l ← liftM $ getLocalDecl id; pure $ mkTermId l.userName @[builtinDelab mvar] def delabMVar : Delab := do Expr.mvar n _ ← getExpr | unreachable!; `(?$(mkIdent n)) @[builtinDelab sort] def delabSort : Delab := do expr ← getExpr; match expr with | Expr.sort (Level.zero _) _ => `(Prop) | Expr.sort (Level.succ (Level.zero _) _) _ => `(Type) | Expr.sort l _ => match l.dec with | some l' => `(Type $(quote l')) | none => `(Sort $(quote l)) | _ => unreachable! -- NOTE: not a registered delaborator, as `const` is never called (see [delab] description) def delabConst : Delab := do Expr.const c ls _ ← getExpr | unreachable!; ppUnivs ← getPPOption getPPUniverses; if ls.isEmpty || !ppUnivs then `($(mkIdent c):ident) else `($(mkIdent c):ident.{$(ls.toArray.map quote)*}) /-- Return array with n-th element set to `true` iff n-th parameter of `e` is implicit. -/ def getImplicitParams (e : Expr) : MetaM (Array Bool) := do t ← inferType e; forallTelescopeReducing t $ fun params _ => params.mapM $ fun param => do l ← getLocalDecl param.fvarId!; pure (!l.binderInfo.isExplicit) @[builtinDelab app] def delabAppExplicit : Delab := do (fnStx, argStxs) ← withAppFnArgs (do fn ← getExpr; stx ← if fn.isConst then delabConst else delab; implicitParams ← liftM $ getImplicitParams fn; stx ← if implicitParams.any id then `(@$stx) else pure stx; pure (stx, #[])) (fun ⟨fnStx, argStxs⟩ => do argStx ← delab; pure (fnStx, argStxs.push argStx)); -- avoid degenerate `app` node if argStxs.isEmpty then pure fnStx else `($fnStx $argStxs*) @[builtinDelab app] def delabAppImplicit : Delab := whenNotPPOption getPPExplicit $ do (fnStx, _, argStxs) ← withAppFnArgs (do fn ← getExpr; stx ← if fn.isConst then delabConst else delab; implicitParams ← liftM $ getImplicitParams fn; pure (stx, implicitParams.toList, #[])) (fun ⟨fnStx, implicitParams, argStxs⟩ => match implicitParams with | true :: implicitParams => pure (fnStx, implicitParams, argStxs) | _ => do argStx ← delab; pure (fnStx, implicitParams.tailD [], argStxs.push argStx)); -- avoid degenerate `app` node if argStxs.isEmpty then pure fnStx else `($fnStx $argStxs*) /-- Check for a `Syntax.ident` of the given name anywhere in the tree. This is usually a bad idea since it does not check for shadowing bindings, but in the delaborator we assume that bindings are never shadowed. -/ partial def hasIdent (id : Name) : Syntax → Bool | Syntax.ident _ _ id' _ => id == id' | Syntax.node _ args => args.any hasIdent | _ => false /-- Return `true` iff current binder should be merged with the nested binder, if any, into a single binder group: * both binders must have same binder info and domain * they cannot be inst-implicit (`[a b : A]` is not valid syntax) * `pp.binder_types` must be the same value for both terms * prefer `fun a b` over `fun (a b)` -/ private def shouldGroupWithNext : DelabM Bool := do e ← getExpr; ppEType ← getPPOption getPPBinderTypes; let go (e' : Expr) := do { ppE'Type ← withBindingBody `_ $ getPPOption getPPBinderTypes; pure $ e.binderInfo == e'.binderInfo && e.bindingDomain! == e'.bindingDomain! && e'.binderInfo != BinderInfo.instImplicit && ppEType == ppE'Type && (e'.binderInfo != BinderInfo.default || ppE'Type) }; match e with | Expr.lam _ _ e'@(Expr.lam _ _ _ _) _ => go e' | Expr.forallE _ _ e'@(Expr.forallE _ _ _ _) _ => go e' | _ => pure false private partial def delabBinders (delabGroup : Array Syntax → Syntax → Delab) : optParam (Array Syntax) #[] → Delab -- Accumulate names (`Syntax.ident`s with position information) of the current, unfinished -- binder group `(d e ...)` as determined by `shouldGroupWithNext`. We cannot do grouping -- inside-out, on the Syntax level, because it depends on comparing the Expr binder types. | curNames => do lctx ← liftM $ getLCtx; e ← getExpr; let n := lctx.getUnusedName e.bindingName!; stxN ← annotateCurPos (mkIdent n); let curNames := curNames.push stxN; condM shouldGroupWithNext -- group with nested binder => recurse immediately (withBindingBody n $ delabBinders curNames) -- don't group => delab body and prepend current binder group (withBindingBody n delab >>= delabGroup curNames) @[builtinDelab lam] def delabLam : Delab := delabBinders $ fun curNames stxBody => do e ← getExpr | unreachable!; stxT ← withBindingDomain delab; ppTypes ← getPPOption getPPBinderTypes; expl ← getPPOption getPPExplicit; -- leave lambda implicit if possible let blockImplicitLambda := expl || e.binderInfo == BinderInfo.default || Elab.Term.blockImplicitLambda stxBody || curNames.any (fun n => hasIdent n.getId stxBody); if !blockImplicitLambda then pure stxBody else do group ← match e.binderInfo, ppTypes with | BinderInfo.default, true => do -- "default" binder group is the only one that expects binder names -- as a term, i.e. a single `Term.id` or an application thereof let curNames := curNames.map mkTermIdFromIdent; stxCurNames ← if curNames.size > 1 then `($(curNames.get! 0) $(curNames.eraseIdx 0)*) else pure $ curNames.get! 0; `(funBinder| ($stxCurNames : $stxT)) | BinderInfo.default, false => pure $ mkTermIdFromIdent curNames.back -- here `curNames.size == 1` | BinderInfo.implicit, true => `(funBinder| {$curNames* : $stxT}) | BinderInfo.implicit, false => `(funBinder| {$curNames*}) | BinderInfo.instImplicit, _ => `(funBinder| [$curNames.back : $stxT]) -- here `curNames.size == 1` | _ , _ => unreachable!; match_syntax stxBody with | `(fun $binderGroups* => $stxBody) => `(fun $group $binderGroups* => $stxBody) | _ => `(fun $group => $stxBody) @[builtinDelab forallE] def delabForall : Delab := delabBinders $ fun curNames stxBody => do e ← getExpr; stxT ← withBindingDomain delab; match e.binderInfo with | BinderInfo.default => -- heuristic: use non-dependent arrows only if possible for whole group to avoid -- noisy mix like `(α : Type) → Type → (γ : Type) → ...`. let dependent := curNames.any $ fun n => hasIdent n.getId stxBody; -- NOTE: non-dependent arrows are available only for the default binder info if dependent then do `(($curNames* : $stxT) → $stxBody) else curNames.foldrM (fun _ stxBody => `($stxT → $stxBody)) stxBody | BinderInfo.implicit => `({$curNames* : $stxT} → $stxBody) -- here `curNames.size == 1` | BinderInfo.instImplicit => `([$curNames.back : $stxT] → $stxBody) | _ => unreachable! @[builtinDelab lit] def delabLit : Delab := do Expr.lit l _ ← getExpr | unreachable!; match l with | Literal.natVal n => pure $ quote n | Literal.strVal s => pure $ quote s -- `ofNat 0` ~> `0` @[builtinDelab app.HasOfNat.ofNat] def delabOfNat : Delab := whenPPOption getPPCoercions $ do e@(Expr.app _ (Expr.lit (Literal.natVal n) _) _) ← getExpr | failure; pure $ quote n /-- Delaborate a projection primitive. These do not usually occur in user code, but are pretty-printed when e.g. `#print`ing a projection function. -/ @[builtinDelab proj] def delabProj : Delab := do Expr.proj _ idx e _ ← getExpr | unreachable!; e ← withProj delab; -- not perfectly authentic: elaborates to the `idx`-th named projection -- function (e.g. `e.1` is `Prod.fst e`), which unfolds to the actual -- `proj`. `($(e).$(mkStxNumLitAux idx):fieldIdx) /-- Delaborate a call to a projection function such as `Prod.fst`. -/ @[builtinDelab app] def delabProjectionApp : Delab := whenPPOption getPPStructureProjections $ do e@(Expr.app fn _ _) ← getExpr | failure; Expr.const c@(Name.str _ f _) _ _ ← pure fn.getAppFn | failure; env ← liftM getEnv; some info ← pure $ env.getProjectionFnInfo c | failure; -- can't use with classes since the instance parameter is implicit guard $ !info.fromClass; -- projection function should be fully applied (#struct params + 1 instance parameter) -- TODO: support over-application guard $ e.getAppNumArgs == info.nparams + 1; -- If pp.explicit is true, and the structure has parameters, we should not -- use field notation because we will not be able to see the parameters. expl ← getPPOption getPPExplicit; guard $ !expl || info.nparams == 0; appStx ← withAppArg delab; `($(appStx).$(mkIdent f):ident) -- abbrev coe {α : Sort u} {β : Sort v} (a : α) [CoeT α a β] : β @[builtinDelab app.coe] def delabCoe : Delab := whenPPOption getPPCoercions $ do e ← getExpr; guard $ e.getAppNumArgs >= 4; -- delab as application, then discard function stx ← delabAppImplicit; match_syntax stx with | `($fn $args*) => if args.size == 1 then pure $ args.get! 0 else `($(args.get! 0) $(args.eraseIdx 0)*) | _ => failure -- abbrev coeFun {α : Sort u} {γ : α → Sort v} (a : α) [CoeFun α γ] : γ a @[builtinDelab app.coeFun] def delabCoeFun : Delab := delabCoe end Delaborator /-- "Delaborate" the given term into surface-level syntax using the given general and subterm-specific options. -/ def delab (e : Expr) (defaultOptions : Options) (optionsPerPos : OptionsPerPos := {}) : MetaM Syntax := do some stx ← Delaborator.delab { expr := e, defaultOptions := defaultOptions, optionsPerPos := optionsPerPos } | unreachable!; pure stx end Lean
35ca2f4fb723c65ff7b8ac179d2c7724cc22064d
05b503addd423dd68145d68b8cde5cd595d74365
/src/measure_theory/l1_space.lean
65ed26f4013c6618ab8b50406ad1724977e1d534
[ "Apache-2.0" ]
permissive
aestriplex/mathlib
77513ff2b176d74a3bec114f33b519069788811d
e2fa8b2b1b732d7c25119229e3cdfba8370cb00f
refs/heads/master
1,621,969,960,692
1,586,279,279,000
1,586,279,279,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
28,769
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou -/ import measure_theory.ae_eq_fun /-! # Integrable functions and `L¹` space In the first part of this file, the predicate `integrable` is defined and basic properties of integrable functions are proved. In the second part, the space `L¹` of equivalence classes of integrable functions under the relation of being almost everywhere equal is defined as a subspace of the space `L⁰`. See the file `src/measure_theory/ae_eq_fun.lean` for information on `L⁰` space. ## Notation * `α →₁ β` is the type of `L¹` space, where `α` is a `measure_space` and `β` is a `normed_group` with a `second_countable_topology`. `f : α →ₘ β` is a "function" in `L¹`. In comments, `[f]` is also used to denote an `L¹` function. `₁` can be typed as `\1`. ## Main definitions * Let `f : α → β` be a function, where `α` is a `measure_space` and `β` a `normed_group`. Then `f` is called `integrable` if `(∫⁻ a, nnnorm (f a)) < ⊤` holds. * The space `L¹` is defined as a subspace of `L⁰` : An `ae_eq_fun` `[f] : α →ₘ β` is in the space `L¹` if `edist [f] 0 < ⊤`, which means `(∫⁻ a, edist (f a) 0) < ⊤` if we expand the definition of `edist` in `L⁰`. ## Main statements `L¹`, as a subspace, inherits most of the structures of `L⁰`. ## Implementation notes Maybe `integrable f` should be mean `(∫⁻ a, edist (f a) 0) < ⊤`, so that `integrable` and `ae_eq_fun.integrable` are more aligned. But in the end one can use the lemma `lintegral_nnnorm_eq_lintegral_edist : (∫⁻ a, nnnorm (f a)) = (∫⁻ a, edist (f a) 0)` to switch the two forms. ## Tags integrable, function space, l1 -/ noncomputable theory open_locale classical topological_space set_option class.instance_max_depth 100 namespace measure_theory open set filter topological_space ennreal emetric universes u v w variables {α : Type u} [measure_space α] variables {β : Type v} [normed_group β] {γ : Type w} [normed_group γ] /-- A function is `integrable` if the integral of its pointwise norm is less than infinity. -/ def integrable (f : α → β) : Prop := (∫⁻ a, nnnorm (f a)) < ⊤ lemma integrable_iff_norm (f : α → β) : integrable f ↔ (∫⁻ a, ennreal.of_real ∥f a∥) < ⊤ := by simp only [integrable, of_real_norm_eq_coe_nnnorm] lemma integrable_iff_edist (f : α → β) : integrable f ↔ (∫⁻ a, edist (f a) 0) < ⊤ := have eq : (λa, edist (f a) 0) = (λa, (nnnorm(f a) : ennreal)), by { funext, rw edist_eq_coe_nnnorm }, iff.intro (by { rw eq, exact λh, h }) $ by { rw eq, exact λh, h } lemma integrable_iff_of_real {f : α → ℝ} (h : ∀ₘ a, 0 ≤ f a) : integrable f ↔ (∫⁻ a, ennreal.of_real (f a)) < ⊤ := have lintegral_eq : (∫⁻ a, ennreal.of_real ∥f a∥) = (∫⁻ a, ennreal.of_real (f a)) := begin apply lintegral_congr_ae, filter_upwards [h], simp only [mem_set_of_eq], assume a h, rw [real.norm_eq_abs, abs_of_nonneg], exact h end, by rw [integrable_iff_norm, lintegral_eq] lemma integrable_of_ae_eq {f g : α → β} (hf : integrable f) (h : ∀ₘ a, f a = g a) : integrable g := begin simp only [integrable] at *, have : (∫⁻ (a : α), ↑(nnnorm (f a))) = (∫⁻ (a : α), ↑(nnnorm (g a))), { apply lintegral_congr_ae, filter_upwards [h], assume a, simp only [mem_set_of_eq], assume h, rw h }, rwa ← this end lemma integrable_congr_ae {f g : α → β} (h : ∀ₘ a, f a = g a) : integrable f ↔ integrable g := iff.intro (λhf, integrable_of_ae_eq hf h) (λhg, integrable_of_ae_eq hg (all_ae_eq_symm h)) lemma integrable_of_le_ae {f : α → β} {g : α → γ} (h : ∀ₘ a, ∥f a∥ ≤ ∥g a∥) (hg : integrable g) : integrable f := begin simp only [integrable_iff_norm] at *, calc (∫⁻ a, ennreal.of_real ∥f a∥) ≤ (∫⁻ (a : α), ennreal.of_real ∥g a∥) : lintegral_le_lintegral_ae (by { filter_upwards [h], assume a h, exact of_real_le_of_real h }) ... < ⊤ : hg end lemma integrable_of_le {f : α → β} {g : α → γ} (h : ∀a, ∥f a∥ ≤ ∥g a∥) (hg : integrable g) : integrable f := integrable_of_le_ae (all_ae_of_all h) hg lemma lintegral_nnnorm_eq_lintegral_edist (f : α → β) : (∫⁻ a, nnnorm (f a)) = ∫⁻ a, edist (f a) 0 := by simp only [edist_eq_coe_nnnorm] lemma lintegral_norm_eq_lintegral_edist (f : α → β) : (∫⁻ a, ennreal.of_real ∥f a∥) = ∫⁻ a, edist (f a) 0 := by simp only [of_real_norm_eq_coe_nnnorm, edist_eq_coe_nnnorm] lemma lintegral_edist_triangle [second_countable_topology β] [measurable_space β] [opens_measurable_space β] {f g h : α → β} (hf : measurable f) (hg : measurable g) (hh : measurable h) : (∫⁻ a, edist (f a) (g a)) ≤ (∫⁻ a, edist (f a) (h a)) + ∫⁻ a, edist (g a) (h a) := begin rw ← lintegral_add (hf.edist hh) (hg.edist hh), apply lintegral_mono, assume a, have := edist_triangle (f a) (h a) (g a), convert this, rw edist_comm (h a) (g a), end lemma lintegral_edist_lt_top [second_countable_topology β] [measurable_space β] [opens_measurable_space β] {f g : α → β} (hfm : measurable f) (hfi : integrable f) (hgm : measurable g) (hgi : integrable g) : (∫⁻ a, edist (f a) (g a)) < ⊤ := lt_of_le_of_lt (lintegral_edist_triangle hfm hgm (measurable_const : measurable (λa, (0 : β)))) (ennreal.add_lt_top.2 $ by { split; rw ← integrable_iff_edist; assumption }) lemma lintegral_nnnorm_zero : (∫⁻ a : α, nnnorm (0 : β)) = 0 := by simp variables (α β) @[simp] lemma integrable_zero : integrable (λa:α, (0:β)) := by { have := coe_lt_top, simpa [integrable] } variables {α β} lemma lintegral_nnnorm_add [measurable_space β] [opens_measurable_space β] [measurable_space γ] [opens_measurable_space γ] {f : α → β} {g : α → γ} (hf : measurable f) (hg : measurable g) : (∫⁻ a, nnnorm (f a) + nnnorm (g a)) = (∫⁻ a, nnnorm (f a)) + ∫⁻ a, nnnorm (g a) := lintegral_add hf.ennnorm hg.ennnorm lemma integrable.add [measurable_space β] [opens_measurable_space β] {f g : α → β} (hfm : measurable f) (hfi : integrable f) (hgm : measurable g) (hgi : integrable g) : integrable (λa, f a + g a) := calc (∫⁻ (a : α), ↑(nnnorm ((f + g) a))) ≤ ∫⁻ (a : α), ↑(nnnorm (f a)) + ↑(nnnorm (g a)) : lintegral_mono (assume a, by { simp only [← coe_add, coe_le_coe], exact nnnorm_add_le _ _ }) ... = _ : lintegral_nnnorm_add hfm hgm ... < ⊤ : add_lt_top.2 ⟨hfi, hgi⟩ lemma integrable_finset_sum {ι} [measurable_space β] [borel_space β] [second_countable_topology β] (s : finset ι) {f : ι → α → β} (hfm : ∀ i, measurable (f i)) (hfi : ∀ i, integrable (f i)) : integrable (λ a, s.sum (λ i, f i a)) := begin refine finset.induction_on s _ _, { simp only [finset.sum_empty, integrable_zero] }, { assume i s his ih, simp only [his, finset.sum_insert, not_false_iff], refine (hfi _).add (hfm _) (s.measurable_sum hfm) ih } end lemma lintegral_nnnorm_neg {f : α → β} : (∫⁻ (a : α), ↑(nnnorm ((-f) a))) = ∫⁻ (a : α), ↑(nnnorm ((f) a)) := by simp only [pi.neg_apply, nnnorm_neg] lemma integrable.neg {f : α → β} : integrable f → integrable (λa, -f a) := assume hfi, calc _ = _ : lintegral_nnnorm_neg ... < ⊤ : hfi @[simp] lemma integrable_neg_iff (f : α → β) : integrable (λa, -f a) ↔ integrable f := begin split, { assume h, simpa only [_root_.neg_neg] using h.neg }, exact integrable.neg end lemma integrable.sub [measurable_space β] [opens_measurable_space β] {f g : α → β} (hfm : measurable f) (hfi : integrable f) (hgm : measurable g) (hgi : integrable g) : integrable (λa, f a - g a) := calc (∫⁻ (a : α), ↑(nnnorm ((f - g) a))) ≤ ∫⁻ (a : α), ↑(nnnorm (f a)) + ↑(nnnorm (-g a)) : lintegral_mono (assume a, by { simp only [← coe_add, coe_le_coe], exact nnnorm_add_le _ _ }) ... = _ : by { simp only [nnnorm_neg], exact lintegral_nnnorm_add hfm hgm } ... < ⊤ : add_lt_top.2 ⟨hfi, hgi⟩ lemma integrable.norm {f : α → β} (hfi : integrable f) : integrable (λa, ∥f a∥) := have eq : (λa, (nnnorm ∥f a∥ : ennreal)) = λa, (nnnorm (f a) : ennreal), by { funext, rw nnnorm_norm }, by { rwa [integrable, eq] } lemma integrable_norm_iff (f : α → β) : integrable (λa, ∥f a∥) ↔ integrable f := have eq : (λa, (nnnorm ∥f a∥ : ennreal)) = λa, (nnnorm (f a) : ennreal), by { funext, rw nnnorm_norm }, by { rw [integrable, integrable, eq] } lemma integrable_of_integrable_bound {f : α → β} {bound : α → ℝ} (h : integrable bound) (h_bound : ∀ₘ a, ∥f a∥ ≤ bound a) : integrable f := have h₁ : ∀ₘ a, (nnnorm (f a) : ennreal) ≤ ennreal.of_real (bound a), begin filter_upwards [h_bound], simp only [mem_set_of_eq], assume a h, calc (nnnorm (f a) : ennreal) = ennreal.of_real (∥f a∥) : by rw of_real_norm_eq_coe_nnnorm ... ≤ ennreal.of_real (bound a) : ennreal.of_real_le_of_real h end, calc (∫⁻ a, nnnorm (f a)) ≤ (∫⁻ a, ennreal.of_real (bound a)) : by { apply lintegral_le_lintegral_ae, exact h₁ } ... ≤ (∫⁻ a, ennreal.of_real ∥bound a∥) : lintegral_mono $ by { assume a, apply ennreal.of_real_le_of_real, exact le_max_left (bound a) (-bound a) } ... < ⊤ : by { rwa [integrable_iff_norm] at h } section dominated_convergence variables {F : ℕ → α → β} {f : α → β} {bound : α → ℝ} lemma all_ae_of_real_F_le_bound (h : ∀ n, ∀ₘ a, ∥F n a∥ ≤ bound a) : ∀ n, ∀ₘ a, ennreal.of_real ∥F n a∥ ≤ ennreal.of_real (bound a) := λn, by filter_upwards [h n] λ a h, ennreal.of_real_le_of_real h lemma all_ae_tendsto_of_real_norm (h : ∀ₘ a, tendsto (λ n, F n a) at_top $ 𝓝 $ f a) : ∀ₘ a, tendsto (λn, ennreal.of_real ∥F n a∥) at_top $ 𝓝 $ ennreal.of_real ∥f a∥ := by filter_upwards [h] λ a h, tendsto_of_real $ tendsto.comp (continuous.tendsto continuous_norm _) h lemma all_ae_of_real_f_le_bound (h_bound : ∀ n, ∀ₘ a, ∥F n a∥ ≤ bound a) (h_lim : ∀ₘ a, tendsto (λ n, F n a) at_top (𝓝 (f a))) : ∀ₘ a, ennreal.of_real ∥f a∥ ≤ ennreal.of_real (bound a) := begin have F_le_bound := all_ae_of_real_F_le_bound h_bound, rw ← all_ae_all_iff at F_le_bound, apply F_le_bound.mp ((all_ae_tendsto_of_real_norm h_lim).mono _), assume a tendsto_norm F_le_bound, exact le_of_tendsto' at_top_ne_bot tendsto_norm (F_le_bound) end lemma integrable_of_dominated_convergence {F : ℕ → α → β} {f : α → β} {bound : α → ℝ} (bound_integrable : integrable bound) (h_bound : ∀ n, ∀ₘ a, ∥F n a∥ ≤ bound a) (h_lim : ∀ₘ a, tendsto (λ n, F n a) at_top (𝓝 (f a))) : integrable f := /- `∥F n a∥ ≤ bound a` and `∥F n a∥ --> ∥f a∥` implies `∥f a∥ ≤ bound a`, and so `∫ ∥f∥ ≤ ∫ bound < ⊤` since `bound` is integrable -/ begin rw integrable_iff_norm, calc (∫⁻ a, (ennreal.of_real ∥f a∥)) ≤ ∫⁻ a, ennreal.of_real (bound a) : lintegral_le_lintegral_ae $ all_ae_of_real_f_le_bound h_bound h_lim ... < ⊤ : begin rw ← integrable_iff_of_real, { exact bound_integrable }, filter_upwards [h_bound 0] λ a h, le_trans (norm_nonneg _) h, end end lemma tendsto_lintegral_norm_of_dominated_convergence [measurable_space β] [borel_space β] [second_countable_topology β] {F : ℕ → α → β} {f : α → β} {bound : α → ℝ} (F_measurable : ∀ n, measurable (F n)) (f_measurable : measurable f) (bound_integrable : integrable bound) (h_bound : ∀ n, ∀ₘ a, ∥F n a∥ ≤ bound a) (h_lim : ∀ₘ a, tendsto (λ n, F n a) at_top (𝓝 (f a))) : tendsto (λn, ∫⁻ a, ennreal.of_real ∥F n a - f a∥) at_top (𝓝 0) := let b := λa, 2 * ennreal.of_real (bound a) in /- `∥F n a∥ ≤ bound a` and `F n a --> f a` implies `∥f a∥ ≤ bound a`, and thus by the triangle inequality, have `∥F n a - f a∥ ≤ 2 * (bound a). -/ have hb : ∀ n, ∀ₘ a, ennreal.of_real ∥F n a - f a∥ ≤ b a, begin assume n, filter_upwards [all_ae_of_real_F_le_bound h_bound n, all_ae_of_real_f_le_bound h_bound h_lim], assume a h₁ h₂, calc ennreal.of_real ∥F n a - f a∥ ≤ (ennreal.of_real ∥F n a∥) + (ennreal.of_real ∥f a∥) : begin rw [← ennreal.of_real_add], apply of_real_le_of_real, { apply norm_sub_le }, { exact norm_nonneg _ }, { exact norm_nonneg _ } end ... ≤ (ennreal.of_real (bound a)) + (ennreal.of_real (bound a)) : add_le_add' h₁ h₂ ... = b a : by rw ← two_mul end, /- On the other hand, `F n a --> f a` implies that `∥F n a - f a∥ --> 0` -/ have h : ∀ₘ a, tendsto (λ n, ennreal.of_real ∥F n a - f a∥) at_top (𝓝 0), begin suffices h : ∀ₘ a, tendsto (λ n, ennreal.of_real ∥F n a - f a∥) at_top (𝓝 $ ennreal.of_real 0), { rwa ennreal.of_real_zero at h }, filter_upwards [h_lim], assume a h, refine tendsto.comp (continuous.tendsto continuous_of_real _) _, rw ← tendsto_iff_norm_tendsto_zero, exact h end, /- Therefore, by the dominated convergence theorem for nonnegative integration, have ` ∫ ∥f a - F n a∥ --> 0 ` -/ begin suffices h : tendsto (λn, ∫⁻ a, ennreal.of_real ∥F n a - f a∥) at_top (𝓝 (∫⁻ (a:α), 0)), { rwa lintegral_zero at h }, -- Using the dominated convergence theorem. refine tendsto_lintegral_of_dominated_convergence _ _ hb _ _, -- Show `λa, ∥f a - F n a∥` is measurable for all `n` { exact λn, measurable_of_real.comp ((F_measurable n).sub f_measurable).norm }, -- Show `2 * bound` is integrable { rw integrable_iff_of_real at bound_integrable, { calc (∫⁻ a, b a) = 2 * (∫⁻ a, ennreal.of_real (bound a)) : by { rw lintegral_const_mul', exact coe_ne_top } ... < ⊤ : mul_lt_top (coe_lt_top) bound_integrable }, filter_upwards [h_bound 0] λ a h, le_trans (norm_nonneg _) h }, -- Show `∥f a - F n a∥ --> 0` { exact h } end end dominated_convergence section pos_part /-! Lemmas used for defining the positive part of a `L¹` function -/ lemma integrable.max_zero {f : α → ℝ} (hf : integrable f) : integrable (λa, max (f a) 0) := begin simp only [integrable_iff_norm] at *, calc (∫⁻ a, ennreal.of_real ∥max (f a) 0∥) ≤ (∫⁻ (a : α), ennreal.of_real ∥f a∥) : lintegral_mono begin assume a, apply of_real_le_of_real, simp only [real.norm_eq_abs], calc abs (max (f a) 0) = max (f a) 0 : by { rw abs_of_nonneg, apply le_max_right } ... ≤ abs (f a) : max_le (le_abs_self _) (abs_nonneg _) end ... < ⊤ : hf end lemma integrable.min_zero {f : α → ℝ} (hf : integrable f) : integrable (λa, min (f a) 0) := begin have : (λa, min (f a) 0) = (λa, - max (-f a) 0), { funext, rw [min_eq_neg_max_neg_neg, neg_zero] }, rw this, exact (integrable.max_zero hf.neg).neg, end end pos_part section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma integrable.smul (c : 𝕜) {f : α → β} : integrable f → integrable (λa, c • f a) := begin simp only [integrable], assume hfi, calc (∫⁻ (a : α), nnnorm ((c • f) a)) = (∫⁻ (a : α), (nnnorm c) * nnnorm (f a)) : begin apply lintegral_congr_ae, filter_upwards [], assume a, simp only [nnnorm_smul, set.mem_set_of_eq, pi.smul_apply, ennreal.coe_mul] end ... < ⊤ : begin rw lintegral_const_mul', apply mul_lt_top, { exact coe_lt_top }, { exact hfi }, { simp only [ennreal.coe_ne_top, ne.def, not_false_iff] } end end lemma integrable_smul_iff {c : 𝕜} (hc : c ≠ 0) (f : α → β) : integrable (λa, c • f a) ↔ integrable f := begin split, { assume h, simpa only [smul_smul, inv_mul_cancel hc, one_smul] using h.smul c⁻¹ }, exact integrable.smul _ end end normed_space variables [second_countable_topology β] namespace ae_eq_fun variable [measurable_space β] section variable [opens_measurable_space β] /-- An almost everywhere equal function is `integrable` if it has a finite distance to the origin. Should mean the same thing as the predicate `integrable` over functions. -/ def integrable (f : α →ₘ β) : Prop := f ∈ ball (0 : α →ₘ β) ⊤ lemma integrable_mk {f : α → β} (hf : measurable f) : (integrable (mk f hf)) ↔ measure_theory.integrable f := by simp [integrable, zero_def, edist_mk_mk', measure_theory.integrable, nndist_eq_nnnorm] lemma integrable_to_fun (f : α →ₘ β) : integrable f ↔ (measure_theory.integrable f.to_fun) := by conv_lhs { rw [self_eq_mk f, integrable_mk] } local attribute [simp] integrable_mk lemma integrable_zero : integrable (0 : α →ₘ β) := mem_ball_self coe_lt_top end section variable [borel_space β] lemma integrable.add : ∀ {f g : α →ₘ β}, integrable f → integrable g → integrable (f + g) := begin rintros ⟨f, hf⟩ ⟨g, hg⟩, simp only [mem_ball, zero_def, mk_add_mk, integrable_mk, quot_mk_eq_mk], assume hfi hgi, exact hfi.add hf hg hgi end lemma integrable.neg : ∀ {f : α →ₘ β}, integrable f → integrable (-f) := begin rintros ⟨f, hfm⟩ hfi, exact (integrable_mk _).2 ((integrable_mk hfm).1 hfi).neg end lemma integrable.sub : ∀ {f g : α →ₘ β}, integrable f → integrable g → integrable (f - g) := begin rintros ⟨f, hfm⟩ ⟨g, hgm⟩, simp only [quot_mk_eq_mk, integrable_mk, mk_sub_mk], exact λ hfi hgi, hfi.sub hfm hgm hgi end protected lemma is_add_subgroup : is_add_subgroup (ball (0 : α →ₘ β) ⊤) := { zero_mem := integrable_zero, add_mem := λ _ _, integrable.add, neg_mem := λ _, integrable.neg } section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma integrable.smul : ∀ {c : 𝕜} {f : α →ₘ β}, integrable f → integrable (c • f) := begin rintros c ⟨f, hfm⟩, simp only [quot_mk_eq_mk, integrable_mk, smul_mk], exact λ hfi, hfi.smul c end end normed_space end end ae_eq_fun section variables (α β) [measurable_space β] [opens_measurable_space β] /-- The space of equivalence classes of integrable (and measurable) functions, where two integrable functions are equivalent if they agree almost everywhere, i.e., they differ on a set of measure `0`. -/ def l1 : Type (max u v) := subtype (@ae_eq_fun.integrable α _ β _ _ _ _) infixr ` →₁ `:25 := l1 end namespace l1 open ae_eq_fun local attribute [instance] ae_eq_fun.is_add_subgroup variables [measurable_space β] section variable [opens_measurable_space β] instance : has_coe (α →₁ β) (α →ₘ β) := ⟨subtype.val⟩ protected lemma eq {f g : α →₁ β} : (f : α →ₘ β) = (g : α →ₘ β) → f = g := subtype.eq @[elim_cast] protected lemma eq_iff {f g : α →₁ β} : (f : α →ₘ β) = (g : α →ₘ β) ↔ f = g := iff.intro (l1.eq) (congr_arg coe) /- TODO : order structure of l1-/ /-- `L¹` space forms a `emetric_space`, with the emetric being inherited from almost everywhere functions, i.e., `edist f g = ∫⁻ a, edist (f a) (g a)`. -/ instance : emetric_space (α →₁ β) := subtype.emetric_space /-- `L¹` space forms a `metric_space`, with the metric being inherited from almost everywhere functions, i.e., `edist f g = ennreal.to_real (∫⁻ a, edist (f a) (g a))`. -/ instance : metric_space (α →₁ β) := metric_space_emetric_ball 0 ⊤ end variable [borel_space β] instance : add_comm_group (α →₁ β) := subtype.add_comm_group instance : inhabited (α →₁ β) := ⟨0⟩ @[simp, elim_cast] lemma coe_zero : ((0 : α →₁ β) : α →ₘ β) = 0 := rfl @[simp, move_cast] lemma coe_add (f g : α →₁ β) : ((f + g : α →₁ β) : α →ₘ β) = f + g := rfl @[simp, move_cast] lemma coe_neg (f : α →₁ β) : ((-f : α →₁ β) : α →ₘ β) = -f := rfl @[simp, move_cast] lemma coe_sub (f g : α →₁ β) : ((f - g : α →₁ β) : α →ₘ β) = f - g := rfl @[simp] lemma edist_eq (f g : α →₁ β) : edist f g = edist (f : α →ₘ β) (g : α →ₘ β) := rfl lemma dist_eq (f g : α →₁ β) : dist f g = ennreal.to_real (edist (f : α →ₘ β) (g : α →ₘ β)) := rfl /-- The norm on `L¹` space is defined to be `∥f∥ = ∫⁻ a, edist (f a) 0`. -/ instance : has_norm (α →₁ β) := ⟨λ f, dist f 0⟩ lemma norm_eq (f : α →₁ β) : ∥f∥ = ennreal.to_real (edist (f : α →ₘ β) 0) := rfl instance : normed_group (α →₁ β) := normed_group.of_add_dist (λ x, rfl) $ by { intros, simp only [dist_eq, coe_add], rw edist_eq_add_add } section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] instance : has_scalar 𝕜 (α →₁ β) := ⟨λ x f, ⟨x • (f : α →ₘ β), ae_eq_fun.integrable.smul f.2⟩⟩ @[simp, move_cast] lemma coe_smul (c : 𝕜) (f : α →₁ β) : ((c • f : α →₁ β) : α →ₘ β) = c • (f : α →ₘ β) := rfl instance : semimodule 𝕜 (α →₁ β) := { one_smul := λf, l1.eq (by { simp only [coe_smul], exact one_smul _ _ }), mul_smul := λx y f, l1.eq (by { simp only [coe_smul], exact mul_smul _ _ _ }), smul_add := λx f g, l1.eq (by { simp only [coe_smul, coe_add], exact smul_add _ _ _ }), smul_zero := λx, l1.eq (by { simp only [coe_zero, coe_smul], exact smul_zero _ }), add_smul := λx y f, l1.eq (by { simp only [coe_smul], exact add_smul _ _ _ }), zero_smul := λf, l1.eq (by { simp only [coe_smul], exact zero_smul _ _ }) } instance : module 𝕜 (α →₁ β) := { .. l1.semimodule } instance : vector_space 𝕜 (α →₁ β) := { .. l1.semimodule } instance : normed_space 𝕜 (α →₁ β) := ⟨ begin rintros x ⟨f, hf⟩, show ennreal.to_real (edist (x • f) 0) = ∥x∥ * ennreal.to_real (edist f 0), rw [edist_smul, to_real_of_real_mul], exact norm_nonneg _ end ⟩ end normed_space section of_fun /-- Construct the equivalence class `[f]` of a measurable and integrable function `f`. -/ def of_fun (f : α → β) (hfm : measurable f) (hfi : integrable f) : (α →₁ β) := ⟨mk f hfm, by { rw integrable_mk, exact hfi }⟩ lemma of_fun_eq_mk (f : α → β) (hfm hfi) : (of_fun f hfm hfi : α →ₘ β) = mk f hfm := rfl lemma of_fun_eq_of_fun (f g : α → β) (hfm hfi hgm hgi) : of_fun f hfm hfi = of_fun g hgm hgi ↔ ∀ₘ a, f a = g a := by { rw ← l1.eq_iff, simp only [of_fun_eq_mk, mk_eq_mk] } lemma of_fun_zero : of_fun (λa:α, (0:β)) (@measurable_const _ _ _ _ (0:β)) (integrable_zero α β) = 0 := rfl lemma of_fun_add (f g : α → β) (hfm hfi hgm hgi) : of_fun (λa, f a + g a) (measurable.add hfm hgm) (integrable.add hfm hfi hgm hgi) = of_fun f hfm hfi + of_fun g hgm hgi := rfl lemma of_fun_neg (f : α → β) (hfm hfi) : of_fun (λa, - f a) (measurable.neg hfm) (integrable.neg hfi) = - of_fun f hfm hfi := rfl lemma of_fun_sub (f g : α → β) (hfm hfi hgm hgi) : of_fun (λa, f a - g a) (measurable.sub hfm hgm) (integrable.sub hfm hfi hgm hgi) = of_fun f hfm hfi - of_fun g hgm hgi := rfl lemma norm_of_fun (f : α → β) (hfm hfi) : ∥of_fun f hfm hfi∥ = ennreal.to_real (∫⁻ a, edist (f a) 0) := rfl lemma norm_of_fun_eq_lintegral_norm (f : α → β) (hfm hfi) : ∥of_fun f hfm hfi∥ = ennreal.to_real (∫⁻ a, ennreal.of_real ∥f a∥) := by { rw [norm_of_fun, lintegral_norm_eq_lintegral_edist] } variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma of_fun_smul (f : α → β) (hfm : measurable f) (hfi : integrable f) (k : 𝕜) : of_fun (λa, k • f a) (hfm.const_smul _) (hfi.smul _) = k • of_fun f hfm hfi := rfl end of_fun section to_fun /-- Find a representative of an `L¹` function [f] -/ @[reducible] protected def to_fun (f : α →₁ β) : α → β := (f : α →ₘ β).to_fun protected lemma measurable (f : α →₁ β) : measurable f.to_fun := f.1.measurable protected lemma integrable (f : α →₁ β) : integrable f.to_fun := by { rw [l1.to_fun, ← integrable_to_fun], exact f.2 } lemma of_fun_to_fun (f : α →₁ β) : of_fun (f.to_fun) f.measurable f.integrable = f := begin rcases f with ⟨f, hfi⟩, rw [of_fun, subtype.mk_eq_mk], exact (self_eq_mk f).symm end lemma mk_to_fun (f : α →₁ β) : mk (f.to_fun) f.measurable = f := by { rw ← of_fun_eq_mk, rw l1.eq_iff, exact of_fun_to_fun f } lemma to_fun_of_fun (f : α → β) (hfm hfi) : ∀ₘ a, (of_fun f hfm hfi).to_fun a = f a := (all_ae_mk_to_fun f hfm).mono $ assume a, id variables (α β) lemma zero_to_fun : ∀ₘ a, (0 : α →₁ β).to_fun a = 0 := ae_eq_fun.zero_to_fun variables {α β} lemma add_to_fun (f g : α →₁ β) : ∀ₘ a, (f + g).to_fun a = f.to_fun a + g.to_fun a := ae_eq_fun.add_to_fun _ _ lemma neg_to_fun (f : α →₁ β) : ∀ₘ a, (-f).to_fun a = -f.to_fun a := ae_eq_fun.neg_to_fun _ lemma sub_to_fun (f g : α →₁ β) : ∀ₘ a, (f - g).to_fun a = f.to_fun a - g.to_fun a := ae_eq_fun.sub_to_fun _ _ lemma dist_to_fun (f g : α →₁ β) : dist f g = ennreal.to_real (∫⁻ x, edist (f.to_fun x) (g.to_fun x)) := by { simp only [dist_eq, edist_to_fun] } lemma norm_eq_nnnorm_to_fun (f : α →₁ β) : ∥f∥ = ennreal.to_real (∫⁻ a, nnnorm (f.to_fun a)) := by { rw [lintegral_nnnorm_eq_lintegral_edist, ← edist_zero_to_fun], refl } lemma norm_eq_norm_to_fun (f : α →₁ β) : ∥f∥ = ennreal.to_real (∫⁻ a, ennreal.of_real ∥f.to_fun a∥) := by { rw norm_eq_nnnorm_to_fun, congr, funext, rw of_real_norm_eq_coe_nnnorm } lemma lintegral_edist_to_fun_lt_top (f g : α →₁ β) : (∫⁻ a, edist (f.to_fun a) (g.to_fun a)) < ⊤ := begin apply lintegral_edist_lt_top, exact f.measurable, exact f.integrable, exact g.measurable, exact g.integrable end variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma smul_to_fun (c : 𝕜) (f : α →₁ β) : ∀ₘ a, (c • f).to_fun a = c • f.to_fun a := ae_eq_fun.smul_to_fun _ _ end to_fun section pos_part /-- Positive part of a function in `L¹` space. -/ def pos_part (f : α →₁ ℝ) : α →₁ ℝ := ⟨ ae_eq_fun.pos_part f, begin rw [ae_eq_fun.integrable_to_fun, integrable_congr_ae (pos_part_to_fun _)], exact integrable.max_zero f.integrable end ⟩ /-- Negative part of a function in `L¹` space. -/ def neg_part (f : α →₁ ℝ) : α →₁ ℝ := pos_part (-f) @[move_cast] lemma coe_pos_part (f : α →₁ ℝ) : (f.pos_part : α →ₘ ℝ) = (f : α →ₘ ℝ).pos_part := rfl lemma pos_part_to_fun (f : α →₁ ℝ) : ∀ₘ a, (pos_part f).to_fun a = max (f.to_fun a) 0 := ae_eq_fun.pos_part_to_fun _ lemma neg_part_to_fun_eq_max (f : α →₁ ℝ) : ∀ₘ a, (neg_part f).to_fun a = max (- f.to_fun a) 0 := begin rw neg_part, filter_upwards [pos_part_to_fun (-f), neg_to_fun f], simp only [mem_set_of_eq], assume a h₁ h₂, rw [h₁, h₂] end lemma neg_part_to_fun_eq_min (f : α →₁ ℝ) : ∀ₘ a, (neg_part f).to_fun a = - min (f.to_fun a) 0 := begin filter_upwards [neg_part_to_fun_eq_max f], simp only [mem_set_of_eq], assume a h, rw [h, min_eq_neg_max_neg_neg, _root_.neg_neg, neg_zero], end lemma norm_le_norm_of_ae_le {f g : α →₁ β} (h : ∀ₘ a, ∥f.to_fun a∥ ≤ ∥g.to_fun a∥) : ∥f∥ ≤ ∥g∥ := begin simp only [l1.norm_eq_norm_to_fun], rw to_real_le_to_real, { apply lintegral_le_lintegral_ae, filter_upwards [h], simp only [mem_set_of_eq], assume a h, exact of_real_le_of_real h }, { rw [← lt_top_iff_ne_top, ← integrable_iff_norm], exact f.integrable }, { rw [← lt_top_iff_ne_top, ← integrable_iff_norm], exact g.integrable } end lemma continuous_pos_part : continuous $ λf : α →₁ ℝ, pos_part f := begin simp only [metric.continuous_iff], assume g ε hε, use ε, use hε, simp only [dist_eq_norm], assume f hfg, refine lt_of_le_of_lt (norm_le_norm_of_ae_le _) hfg, filter_upwards [l1.sub_to_fun f g, l1.sub_to_fun (pos_part f) (pos_part g), pos_part_to_fun f, pos_part_to_fun g], simp only [mem_set_of_eq], assume a h₁ h₂ h₃ h₄, simp only [real.norm_eq_abs, h₁, h₂, h₃, h₄], exact abs_max_sub_max_le_abs _ _ _ end lemma continuous_neg_part : continuous $ λf : α →₁ ℝ, neg_part f := have eq : (λf : α →₁ ℝ, neg_part f) = (λf : α →₁ ℝ, pos_part (-f)) := rfl, by { rw eq, exact continuous_pos_part.comp continuous_neg } end pos_part /- TODO: l1 is a complete space -/ end l1 end measure_theory
31df59789ee1416d1fd9eb5c286ebfc97b36842d
4f643cce24b2d005aeeb5004c2316a8d6cc7f3b1
/src/o_minimal/tame/basic.lean
8b7a15d8cd0b6ef0ebc47f677633cb428388486e
[]
no_license
rwbarton/lean-omin
da209ed061d64db65a8f7f71f198064986f30eb9
fd733c6d95ef6f4743aae97de5e15df79877c00e
refs/heads/master
1,674,408,673,325
1,607,343,535,000
1,607,343,535,000
285,150,399
9
0
null
null
null
null
UTF-8
Lean
false
false
8,989
lean
import for_mathlib.boolean_subalgebra import for_mathlib.finite import for_mathlib.order import o_minimal.dunlo /- Basic properties of tame sets. A tame set is a subset of a DUNLO which is a finite union of points and intervals. They can also be described as the boolean subalgebra generated by half-infinite intervals. By definition, these are the definable sets in any o-minimal structure. -/ namespace o_minimal variables {R : Type*} [DUNLO R] /-- A (nonempty) open interval (possibly unbounded on one or both sides) or a single point. One of the building blocks of a tame set. -/ inductive interval_or_point : set R → Prop | pt (r : R) : interval_or_point {r} | Iii : interval_or_point set.univ | Ioi (a : R) : interval_or_point (set.Ioi a) | Iio (b : R) : interval_or_point (set.Iio b) | Ioo (a b : R) (h : a < b) : interval_or_point (set.Ioo a b) lemma interval_or_point.as_IOO {s : set R} (hs : interval_or_point s) : (∃ r, s = {r}) ∨ (∃ (a : with_bot R) (b : with_top R), s = {x | a < ↑x ∧ ↑x < b}) := begin -- Use `induction` because `cases` does undesired definitional unfolding. induction hs with r a b a b; [ exact or.inl ⟨r, rfl⟩, refine or.inr ⟨⊥, ⊤, _⟩, refine or.inr ⟨a, ⊤, _⟩, refine or.inr ⟨⊥, b, _⟩, refine or.inr ⟨a, b, _⟩ ]; { ext x, simp [with_bot.bot_lt_coe, with_top.coe_lt_top, with_bot.coe_lt_coe, with_top.coe_lt_coe] } end /-- A tame subset of `R` is one that can be expressed as a finite union of intervals and points. -/ def tame : set R → Prop := finite_union_closure interval_or_point lemma tame_iff {s : set R} : tame s ↔ ∃ (I : finset (set R)), (∀ i ∈ I, interval_or_point i) ∧ s = ⋃ i ∈ I, i := finite_union_closure_iff_bUnion lemma tame_single {i : set R} (h : interval_or_point i) : tame i := finite_union_closure.basic h lemma tame_empty : tame (∅ : set R) := finite_union_closure.empty lemma tame_univ : tame (set.univ : set R) := tame_single interval_or_point.Iii lemma tame_const {p : Prop} : tame {r : R | p} := begin by_cases h : p, { convert tame_univ, simp [h] }, { convert tame_empty, simp [h], refl } end lemma tame.union {s t : set R} (hs : tame s) (ht : tame t) : tame (s ∪ t) := finite_union_closure.union hs ht -- TODO: for_mathlib. after finset.singleton_inter_of_not_mem. Fix proof. lemma set.singleton_inter_of_mem {α : Type*} {a : α} {s : set α} (h : a ∈ s) : {a} ∩ s = {a} := by { ext x, simp [h], intro H, rwa H } -- Rather specialized lemma for use in closure under finite intersections. lemma tame_singleton_inter (r : R) (s : set R) : tame ({r} ∩ s) := begin by_cases h : r ∈ s, { rw set.singleton_inter_of_mem h, exact tame_single (interval_or_point.pt r) }, { rw set.singleton_inter_eq_empty.mpr h, exact finite_union_closure.empty } end lemma tame_IOO (a : with_bot R) (b : with_top R) : tame {x : R | a < ↑x ∧ ↑x < b} := begin induction a using with_bot.rec_bot_coe with a; induction b using with_top.rec_top_coe with b; simp [with_bot.bot_lt_coe, with_top.coe_lt_top, with_bot.coe_lt_coe, with_top.coe_lt_coe], all_goals { try { { apply tame_single, constructor } } }, -- { { } }, because only do it if we're done. by_cases h : a < b, { exact tame_single (interval_or_point.Ioo a b h) }, { convert finite_union_closure.empty, rw set.eq_empty_iff_forall_not_mem, rintros x ⟨hx₁, hx₂⟩, exact h (lt_trans hx₁ hx₂) } end lemma closed_under_finite_inters_tame : closed_under_finite_inters (tame : set R → Prop) := begin apply closed_under_finite_inters_finite_union_closure, { exact tame_single interval_or_point.Iii }, { intros s s' hs hs', rcases hs.as_IOO with ⟨r, rfl⟩ | ⟨a, b, rfl⟩, { apply tame_singleton_inter }, rcases hs'.as_IOO with ⟨r', rfl⟩ | ⟨a', b', rfl⟩, { rw set.inter_comm, apply tame_singleton_inter }, convert tame_IOO (a ⊔ a') (b ⊓ b') using 1, ext x, simp only [set.mem_inter_iff, set.mem_set_of_eq], rw [sup_lt_iff, lt_inf_iff], tauto } end -- TODO: A tame set has a normal form as the union of -- a minimal list of nonoverlapping intervals and points, arranged in increasing order. -- Is this useful? /-- Induction principle: Every tame set of R can be built up from the empty set by repeatedly forming the union with a single interval or point. -/ -- TODO: Generalize this to finite_union_closure lemma tame.induction {C : set R → Prop} (h₀ : C ∅) (h₁ : ∀ {s : set R} {i : set R}, /- tame_r s → -/ interval_or_point i → C s → C (i ∪ s)) : ∀ {s : set R}, tame s → C s := begin suffices : ∀ (I : finset (set R)), (∀ i ∈ I, interval_or_point i) → C (⋃ i ∈ I, i), { intros s hs, obtain ⟨I, hI, rfl⟩ := tame_iff.mp hs, exact this I hI }, classical, refine finset.induction (by { intro, simpa }) _, intros i I hi IH hI, rw finset.bUnion_insert, exact h₁ (hI i (finset.mem_insert_self i I)) (IH (λ i' hi', hI i' (finset.mem_insert_of_mem hi'))) end section -- Tame sets as the boolean subalgebra of `set R` -- generated by sets of the form (-∞, b) and (a, ∞). @[simp] lemma le_and_le_iff_eq {α : Type*} [partial_order α] (x y : α) : (x ≤ y ∧ y ≤ x) ↔ x = y := le_antisymm_iff.symm lemma tame_Iic (b : R) : tame (set.Iic b) := begin convert (tame_single (interval_or_point.Iio b)).union (tame_single (interval_or_point.pt b)), ext x, simp end lemma tame_Ici (a : R) : tame (set.Ici a) := begin convert (tame_single (interval_or_point.pt a)).union (tame_single (interval_or_point.Ioi a)), ext x, simp [le_iff_eq_or_lt, eq_comm] end -- TODO: We could avoid doing this work by using the simple o-minimal structure lemma tame_compl_interval_or_pt {s : set R} (h : interval_or_point s) : tame (sᶜ) := begin induction h with r a b a b hab, { convert (tame_single (interval_or_point.Iio r)).union (tame_single (interval_or_point.Ioi r)), ext x, rw ←not_iff_not, simp [not_or_distrib, eq_comm] }, { convert tame_empty, simp }, { convert tame_Iic a, rw set.compl_Ioi }, { convert tame_Ici b, rw set.compl_Iio }, { convert (tame_Iic a).union (tame_Ici b), ext x, change ¬ (a < x ∧ x < b) ↔ x ≤ a ∨ b ≤ x, rw [not_and_distrib, not_lt, not_lt] } end lemma is_boolean_subalgebra_tame : is_boolean_subalgebra (tame : set R → Prop) := begin refine ⟨tame_empty, λ _ _, finite_union_closure.union, _⟩, apply closed_under_complements_finite_union_closure, { exact closed_under_finite_inters_tame.mem_univ }, { intros s t hs ht, exact closed_under_finite_inters_tame.mem_inter (tame_single hs) (tame_single ht) }, { intros s hs, exact tame_compl_interval_or_pt hs } end inductive half_infinite_interval : set R → Prop | Iio (b : R) : half_infinite_interval (set.Iio b) | Ioi (a : R) : half_infinite_interval (set.Ioi a) open boolean_subalgebra half_infinite_interval lemma tame_eq_gen_half_infinite_interval : (tame : set R → Prop) = gen half_infinite_interval := begin apply set.subset.antisymm, { unfold tame, refine set.subset.trans finite_union_closure_subset_gen _, rw gen_subset_gen_iff_subset_gen, intros s hs, induction hs with r a b a b hab, { convert gen.compl (gen.sup (gen.basic (Ioi r)) (gen.basic (Iio r))), ext x, simp }, { convert gen.compl gen.bot, simp }, { exact gen.basic (Ioi a) }, { exact gen.basic (Iio b) }, { convert gen.inf (gen.basic (Ioi a)) (gen.basic (Iio b)) } }, { rw gen_subset_iff_subset is_boolean_subalgebra_tame, rintros _ (_|_); apply tame_single; constructor } end end lemma interval_or_point.finite_or_contains_interval {i : set R} (h : interval_or_point i) : i.finite ∨ ∃ (a b : R), a < b ∧ set.Ioo a b ⊆ i := begin rcases h with _|_|⟨a⟩|⟨b⟩|⟨a,b,hab⟩, { exact or.inl (set.finite_singleton _) }, all_goals { right }, { have a : R := classical.arbitrary R, -- classical is unnecessary, but standard library is annoying here obtain ⟨b, h⟩ := no_top a, exact ⟨a, b, h, set.subset_univ _⟩ }, { obtain ⟨b, h⟩ := no_top a, exact ⟨a, b, h, λ x ⟨hax, hxb⟩, hax⟩ }, { obtain ⟨a, h⟩ := no_bot b, exact ⟨a, b, h, λ x ⟨hax, hxb⟩, hxb⟩ }, { exact ⟨a, b, hab, set.subset.refl _⟩ } end /-- A dichotomy for tame sets: either they are finite or they contain an entire interval. -/ lemma tame.finite_or_contains_interval {s : set R} (h : tame s) : s.finite ∨ ∃ (a b : R), a < b ∧ set.Ioo a b ⊆ s := begin revert h, refine tame.induction (or.inl set.finite_empty) _, clear s, rintros s i hi (fin|⟨a,b,ab,hab⟩), { rcases hi.finite_or_contains_interval with ifin|⟨ia,ib,iab,ih⟩, { left, exact set.finite.union ifin fin }, { right, exact ⟨ia, ib, iab, set.subset.trans ih (set.subset_union_left _ _)⟩ } }, { right, exact ⟨a, b, ab, set.subset.trans hab (set.subset_union_right _ _)⟩ } end end o_minimal
0536a90f9d97ccade6d03793143034ad20911164
e6b8240a90527fd55d42d0ec6649253d5d0bd414
/src/tactic/lint.lean
f24d1cea3a20e7d9d096203e764fe22e3cec85ab
[ "Apache-2.0" ]
permissive
mattearnshaw/mathlib
ac90f9fb8168aa642223bea3ffd0286b0cfde44f
d8dc1445cf8a8c74f8df60b9f7a1f5cf10946666
refs/heads/master
1,606,308,351,137
1,576,594,130,000
1,576,594,130,000
228,666,195
0
0
Apache-2.0
1,576,603,094,000
1,576,603,093,000
null
UTF-8
Lean
false
false
24,991
lean
/- Copyright (c) 2019 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Robert Y. Lewis -/ import tactic.core /-! # lint command This file defines the following user commands to spot common mistakes in the code. * `#lint`: check all declarations in the current file * `#lint_mathlib`: check all declarations in mathlib (so excluding core or other projects, and also excluding the current file) * `#lint_all`: check all declarations in the environment (the current file and all imported files) The following linters are run by default: 1. `unused_arguments` checks for unused arguments in declarations. 2. `def_lemma` checks whether a declaration is incorrectly marked as a def/lemma. 3. `dup_namespce` checks whether a namespace is duplicated in the name of a declaration. 4. `illegal_constant` checks whether ≥/> is used in the declaration. 5. `instance_priority` checks that instances that always apply have priority below default. 6. `doc_blame` checks for missing doc strings on definitions and constants. Another linter, `doc_blame_thm`, checks for missing doc strings on lemmas and theorems. This is not run by default. The command `#list_linters` prints a list of the names of all available linters. You can append a `*` to any command (e.g. `#lint_mathlib*`) to omit the slow tests (4). You can append a `-` to any command (e.g. `#lint_mathlib-`) to run a silent lint that suppresses the output of passing checks. A silent lint will fail if any test fails. You can append a sequence of linter names to any command to run extra tests, in addition to the default ones. e.g. `#lint doc_blame_thm` will run all default tests and `doc_blame_thm`. You can append `only name1 name2 ...` to any command to run a subset of linters, e.g. `#lint only unused_arguments` You can add custom linters by defining a term of type `linter` in the `linter` namespace. A linter defined with the name `linter.my_new_check` can be run with `#lint my_new_check` or `lint only my_new_check`. If you add the attribute `@[linter]` to `linter.my_new_check` it will run by default. Adding the attribute `@[nolint]` to a declaration omits it from all linter checks. ## Tags sanity check, lint, cleanup, command, tactic -/ universe variable u open expr tactic native reserve notation `#lint` reserve notation `#lint_mathlib` reserve notation `#lint_all` reserve notation `#list_linters` run_cmd tactic.skip -- apparently doc strings can't come directly after `reserve notation` /-- Defines the user attribute `nolint` for skipping `#lint` -/ @[user_attribute] meta def nolint_attr : user_attribute := { name := "nolint", descr := "Do not report this declaration in any of the tests of `#lint`" } attribute [nolint] imp_intro classical.dec classical.dec_pred classical.dec_rel classical.dec_eq /-- A linting test for the `#lint` command. `test` defines a test to perform on every declaration. It should never fail. Returning `none` signifies a passing test. Returning `some msg` reports a failing test with error `msg`. `no_errors_found` is the message printed when all tests are negative, and `errors_found` is printed when at least one test is positive. If `is_fast` is false, this test will be omitted from `#lint-`. -/ meta structure linter := (test : declaration → tactic (option string)) (no_errors_found : string) (errors_found : string) (is_fast : bool := tt) /-- Takes a list of names that resolve to declarations of type `linter`, and produces a list of linters. -/ meta def get_linters (l : list name) : tactic (list linter) := l.mmap (λ n, mk_const n >>= eval_expr linter <|> fail format!"invalid linter: {n}") /-- Defines the user attribute `linter` for adding a linter to the default set. Linters should be defined in the `linter` namespace. A linter `linter.my_new_linter` is referred to as `my_new_linter` (without the `linter` namespace) when used in `#lint`. -/ @[user_attribute] meta def linter_attr : user_attribute unit unit := { name := "linter", descr := "Use this declaration as a linting test in #lint", after_set := some $ λ nm _ _, mk_const nm >>= infer_type >>= unify `(linter) } setup_tactic_parser universe variable v /-- Find all declarations in `l` where tac returns `some x` and list them. -/ meta def fold_over_with_cond {α} (l : list declaration) (tac : declaration → tactic (option α)) : tactic (list (declaration × α)) := l.mmap_filter $ λ d, option.map (λ x, (d, x)) <$> tac d /-- Find all declarations in `l` where tac returns `some x` and sort the resulting list by file name. -/ meta def fold_over_with_cond_sorted {α} (l : list declaration) (tac : declaration → tactic (option α)) : tactic (list (string × list (declaration × α))) := do e ← get_env, ds ← fold_over_with_cond l tac, let ds₂ := rb_lmap.of_list (ds.map (λ x, ((e.decl_olean x.1.to_name).iget, x))), return $ ds₂.to_list /-- Make the output of `fold_over_with_cond` printable, in the following form: `#print <name> <open multiline comment> <elt of α> <close multiline comment>` -/ meta def print_decls {α} [has_to_format α] (ds : list (declaration × α)) : format := ds.foldl (λ f x, f ++ "\n" ++ to_fmt "#print " ++ to_fmt x.1.to_name ++ " /- " ++ to_fmt x.2 ++ " -/") format.nil /-- Make the output of `fold_over_with_cond_sorted` printable, with the file path + name inserted.-/ meta def print_decls_sorted {α} [has_to_format α] (ds : list (string × list (declaration × α))) : format := ds.foldl (λ f x, f ++ "\n\n" ++ to_fmt "-- " ++ to_fmt x.1 ++ print_decls x.2) format.nil /-- Same as `print_decls_sorted`, but removing the first `n` characters from the string. Useful for omitting the mathlib directory from the output. -/ meta def print_decls_sorted_mathlib {α} [has_to_format α] (n : ℕ) (ds : list (string × list (declaration × α))) : format := ds.foldl (λ f x, f ++ "\n\n" ++ to_fmt "-- " ++ to_fmt (x.1.popn n) ++ print_decls x.2) format.nil /-- Auxilliary definition for `check_unused_arguments` -/ meta def check_unused_arguments_aux : list ℕ → ℕ → ℕ → expr → list ℕ | l n n_max e := if n > n_max then l else if ¬ is_lambda e ∧ ¬ is_pi e then l else let b := e.binding_body in let l' := if b.has_var_idx 0 then l else n :: l in check_unused_arguments_aux l' (n+1) n_max b /-- Check which arguments of a declaration are not used. Prints a list of natural numbers corresponding to which arguments are not used (e.g. this outputs [1, 4] if the first and fourth arguments are unused). Checks both the type and the value of `d` for whether the argument is used (in rare cases an argument is used in the type but not in the value). We return [] if the declaration was automatically generated. We print arguments that are larger than the arity of the type of the declaration (without unfolding definitions). -/ meta def check_unused_arguments (d : declaration) : option (list ℕ) := let l := check_unused_arguments_aux [] 1 d.type.pi_arity d.value in if l = [] then none else let l2 := check_unused_arguments_aux [] 1 d.type.pi_arity d.type in (l.filter $ λ n, n ∈ l2).reverse /-- Check for unused arguments, and print them with their position, variable name, type and whether the argument is a duplicate. See also `check_unused_arguments`. This tactic additionally filters out all unused arguments of type `parse _` -/ meta def unused_arguments (d : declaration) : tactic (option string) := do let ns := check_unused_arguments d, if ¬ ns.is_some then return none else do let ns := ns.iget, (ds, _) ← get_pi_binders d.type, let ns := ns.map (λ n, (n, (ds.nth $ n - 1).iget)), let ns := ns.filter (λ x, x.2.type.get_app_fn ≠ const `interactive.parse []), if ns = [] then return none else do ds' ← ds.mmap pp, ns ← ns.mmap (λ ⟨n, b⟩, (λ s, to_fmt "argument " ++ to_fmt n ++ ": " ++ s ++ (if ds.countp (λ b', b.type = b'.type) ≥ 2 then " (duplicate)" else "")) <$> pp b), return $ some $ ns.to_string_aux tt /-- A linter object for checking for unused arguments. This is in the default linter set. -/ @[linter, priority 1500] meta def linter.unused_arguments : linter := { test := unused_arguments, no_errors_found := "No unused arguments", errors_found := "UNUSED ARGUMENTS" } /-- Checks whether the correct declaration constructor (definition or theorem) by comparing it to its sort. Instances will not be printed. -/ /- This test is not very quick: maybe we can speed-up testing that something is a proposition? This takes almost all of the execution time. -/ meta def incorrect_def_lemma (d : declaration) : tactic (option string) := if d.is_constant ∨ d.is_axiom then return none else do is_instance_d ← is_instance d.to_name, if is_instance_d then return none else do -- the following seems to be a little quicker than `is_prop d.type`. expr.sort n ← infer_type d.type, return $ if d.is_theorem ↔ n = level.zero then none else if (d.is_definition : bool) then "is a def, should be a lemma/theorem" else "is a lemma/theorem, should be a def" /-- A linter for checking whether the correct declaration constructor (definition or theorem) has been used. -/ @[linter, priority 1490] meta def linter.def_lemma : linter := { test := incorrect_def_lemma, no_errors_found := "All declarations correctly marked as def/lemma", errors_found := "INCORRECT DEF/LEMMA" } /-- Checks whether a declaration has a namespace twice consecutively in its name -/ meta def dup_namespace (d : declaration) : tactic (option string) := is_instance d.to_name >>= λ is_inst, return $ let nm := d.to_name.components in if nm.chain' (≠) ∨ is_inst then none else let s := (nm.find $ λ n, nm.count n ≥ 2).iget.to_string in some $ "The namespace `" ++ s ++ "` is duplicated in the name" /-- A linter for checking whether a declaration has a namespace twice consecutively in its name. -/ @[linter, priority 1480] meta def linter.dup_namespace : linter := { test := dup_namespace, no_errors_found := "No declarations have a duplicate namespace", errors_found := "DUPLICATED NAMESPACES IN NAME" } /-- Checks whether a `>`/`≥` is used in the statement of `d`. -/ -- TODO: the commented out code also checks for classicality in statements, but needs fixing -- TODO: this probably needs to also check whether the argument is a variable or @eq <var> _ _ -- meta def illegal_constants_in_statement (d : declaration) : tactic (option string) := -- return $ if d.type.contains_constant (λ n, (n.get_prefix = `classical ∧ -- n.last ∈ ["prop_decidable", "dec", "dec_rel", "dec_eq"]) ∨ n ∈ [`gt, `ge]) -- then -- let illegal1 := [`classical.prop_decidable, `classical.dec, `classical.dec_rel, `classical.dec_eq], -- illegal2 := [`gt, `ge], -- occur1 := illegal1.filter (λ n, d.type.contains_constant (eq n)), -- occur2 := illegal2.filter (λ n, d.type.contains_constant (eq n)) in -- some $ sformat!"the type contains the following declarations: {occur1 ++ occur2}." ++ -- (if occur1 = [] then "" else " Add decidability type-class arguments instead.") ++ -- (if occur2 = [] then "" else " Use ≤/< instead.") -- else none meta def illegal_constants_in_statement (d : declaration) : tactic (option string) := return $ let illegal := [`gt, `ge] in if d.type.contains_constant (λ n, n ∈ illegal) then some "the type contains ≥/>. Use ≤/< instead." else none /-- A linter for checking whether illegal constants (≥, >) appear in a declaration's type. -/ @[linter, priority 1470] meta def linter.illegal_constants : linter := { test := illegal_constants_in_statement, no_errors_found := "No illegal constants in declarations", errors_found := "ILLEGAL CONSTANTS IN DECLARATIONS", is_fast := ff } /-- checks whether an instance that always applies has priority ≥ 1000. -/ -- TODO: instance_priority should also be tested on automatically-generated declarations meta def instance_priority (d : declaration) : tactic (option string) := do let nm := d.to_name, b ← is_instance nm, /- return `none` if `d` is not an instance -/ if ¬ b then return none else do prio ← has_attribute `instance nm, /- return `none` if `d` is has low priority -/ if prio < 1000 then return none else do let (fn, args) := d.type.pi_codomain.get_app_fn_args, cls ← get_decl fn.const_name, let (pi_args, _) := cls.type.pi_binders, guard (args.length = pi_args.length), /- List all the arguments of the class that block type-class inference from firing (if they are metavariables). These are all the arguments except instance-arguments and out-params. -/ let relevant_args := (args.zip pi_args).filter_map $ λ⟨e, ⟨_, info, tp⟩⟩, if info = binder_info.inst_implicit ∨ tp.get_app_fn.is_constant_of `out_param then none else some e, let always_applies := relevant_args.all expr.is_var ∧ relevant_args.nodup, if always_applies then return $ some "set priority below 1000" else return none /- Note [lower instance priority]: Certain instances always apply during type-class resolution. For example, the instance `add_comm_group.to_add_group {α} [add_comm_group α] : add_group α` applies to all type-class resolution problems of the form `add_group _`, and type-class inference will then do an exhaustive search to find a commutative group. These instances take a long time to fail. Other instances will only apply if the goal has a certain shape. For example `int.add_group : add_group ℤ` or `add_group.prod {α β} [add_group α] [add_group β] : add_group (α × β)`. Usually these instances will fail quickly, and when they apply, they are almost the desired instance. For this reason, we want the instances of the second type (that only apply in specific cases) to always have higher priority than the instances of the first type (that always apply). See also #1561. Therefore, if we create an instance that always applies, we set the priority of these instances to 100 (or something similar, which is below the default value of 1000). -/ /- Note [default priority]: Instances that always apply should be applied after instances that only apply in specific cases, see note [lower instance priority] above. Classes that use the `extends` keyword automatically generate instances that always apply. Therefore, we set the priority of these instances to 100 (or something similar, which is below the default value of 1000) using `set_option default_priority 100`. We have to put this option inside a section, so that the default priority is the default 1000 outside the section. -/ /-- A linter object for checking instance priorities of instances that always apply. This is in the default linter set. -/ @[linter, priority 1460] meta def linter.instance_priority : linter := { test := instance_priority, no_errors_found := "All instance priorities are good", errors_found := "DANGEROUS INSTANCE PRIORITIES.\nThe following instances always apply, and therefore should have a priority < 1000.\nIf you don't know what priority to choose, use priority 100." } /-- Reports definitions and constants that are missing doc strings -/ meta def doc_blame_report_defn : declaration → tactic (option string) | (declaration.defn n _ _ _ _ _) := doc_string n >> return none <|> return "def missing doc string" | (declaration.cnst n _ _ _) := doc_string n >> return none <|> return "constant missing doc string" | _ := return none /-- Reports definitions and constants that are missing doc strings -/ meta def doc_blame_report_thm : declaration → tactic (option string) | (declaration.thm n _ _ _) := doc_string n >> return none <|> return "theorem missing doc string" | _ := return none /-- A linter for checking definition doc strings -/ @[linter, priority 1450] meta def linter.doc_blame : linter := { test := λ d, mcond (bnot <$> has_attribute' `instance d.to_name) (doc_blame_report_defn d) (return none), no_errors_found := "No definitions are missing documentation.", errors_found := "DEFINITIONS ARE MISSING DOCUMENTATION STRINGS" } /-- A linter for checking theorem doc strings. This is not in the default linter set. -/ meta def linter.doc_blame_thm : linter := { test := doc_blame_report_thm, no_errors_found := "No theorems are missing documentation.", errors_found := "THEOREMS ARE MISSING DOCUMENTATION STRINGS", is_fast := ff } /-- `get_checks slow extra use_only` produces a list of linters. `extras` is a list of names that should resolve to declarations with type `linter`. If `use_only` is true, it only uses the linters in `extra`. Otherwise, it uses all linters in the environment tagged with `@[linter]`. If `slow` is false, it only uses the fast default tests. -/ meta def get_checks (slow : bool) (extra : list name) (use_only : bool) : tactic (list linter) := do default ← if use_only then return [] else attribute.get_instances `linter >>= get_linters, let default := if slow then default else default.filter (λ l, l.is_fast), list.append default <$> get_linters extra /-- If `verbose` is true, return `old ++ new`, else return `old`. -/ private meta def append_when (verbose : bool) (old new : format) : format := cond verbose (old ++ new) old private meta def check_fold (printer : (declaration → tactic (option string)) → tactic (name_set × format)) (verbose : bool) : name_set × format → linter → tactic (name_set × format) | (ns, s) ⟨tac, ok_string, warning_string, _⟩ := do (new_ns, f) ← printer tac, if f.is_nil then return $ (ns, append_when verbose s format!"/- OK: {ok_string}. -/\n") else return $ (ns.union new_ns, s ++ format!"/- {warning_string}: -/" ++ f ++ "\n\n") /-- The common denominator of `#lint[|mathlib|all]`. The different commands have different configurations for `l`, `printer` and `where_desc`. If `slow` is false, doesn't do the checks that take a lot of time. If `verbose` is false, it will suppress messages from passing checks. By setting `checks` you can customize which checks are performed. Returns a `name_set` containing the names of all declarations that fail any check in `check`, and a `format` object describing the failures. -/ meta def lint_aux (l : list declaration) (printer : (declaration → tactic (option string)) → tactic (name_set × format)) (where_desc : string) (slow verbose : bool) (checks : list linter) : tactic (name_set × format) := do let s : format := append_when verbose format.nil "/- Note: This command is still in development. -/\n", let s := append_when verbose s format!"/- Checking {l.length} declarations {where_desc} -/\n\n", (ns, s) ← checks.mfoldl (check_fold printer verbose) (mk_name_set, s), return $ (ns, if slow then s else append_when verbose s "/- (slow tests skipped) -/\n") /-- Return the message printed by `#lint` and a `name_set` containing all declarations that fail. -/ meta def lint (slow : bool := tt) (verbose : bool := tt) (extra : list name := []) (use_only : bool := ff) : tactic (name_set × format) := do checks ← get_checks slow extra use_only, e ← get_env, l ← e.mfilter (λ d, if e.in_current_file' d.to_name ∧ ¬ d.to_name.is_internal ∧ ¬ d.is_auto_generated e then bnot <$> has_attribute' `nolint d.to_name else return ff), lint_aux l (λ t, do lst ← fold_over_with_cond l t, return (name_set.of_list (lst.map (declaration.to_name ∘ prod.fst)), print_decls lst)) "in the current file" slow verbose checks private meta def name_list_of_decl_lists (l : list (string × list (declaration × string))) : name_set := name_set.of_list $ list.join $ l.map $ λ ⟨_, l'⟩, l'.map $ declaration.to_name ∘ prod.fst /-- Return the message printed by `#lint_mathlib` and a `name_set` containing all declarations that fail. -/ meta def lint_mathlib (slow : bool := tt) (verbose : bool := tt) (extra : list name := []) (use_only : bool := ff) : tactic (name_set × format) := do checks ← get_checks slow extra use_only, e ← get_env, ml ← get_mathlib_dir, /- note: we don't separate out some of these tests in `lint_aux` because that causes a performance hit. That is also the reason for the current formulation using if then else. -/ l ← e.mfilter (λ d, if e.is_prefix_of_file ml d.to_name ∧ ¬ d.to_name.is_internal ∧ ¬ d.is_auto_generated e then bnot <$> has_attribute' `nolint d.to_name else return ff), let ml' := ml.length, lint_aux l (λ t, do lst ← fold_over_with_cond_sorted l t, return (name_list_of_decl_lists lst, print_decls_sorted_mathlib ml' lst)) "in mathlib (only in imported files)" slow verbose checks /-- Return the message printed by `#lint_all` and a `name_set` containing all declarations that fail. -/ meta def lint_all (slow : bool := tt) (verbose : bool := tt) (extra : list name := []) (use_only : bool := ff) : tactic (name_set × format) := do checks ← get_checks slow extra use_only, e ← get_env, l ← e.mfilter (λ d, if ¬ d.to_name.is_internal ∧ ¬ d.is_auto_generated e then bnot <$> has_attribute' `nolint d.to_name else return ff), lint_aux l (λ t, do lst ← fold_over_with_cond_sorted l t, return (name_list_of_decl_lists lst, print_decls_sorted lst)) "in all imported files (including this one)" slow verbose checks /-- Parses an optional `only`, followed by a sequence of zero or more identifiers. Prepends `linter.` to each of these identifiers. -/ private meta def parse_lint_additions : parser (bool × list name) := prod.mk <$> only_flag <*> (list.map (name.append `linter) <$> ident_*) /-- The common denominator of `lint_cmd`, `lint_mathlib_cmd`, `lint_all_cmd` -/ private meta def lint_cmd_aux (scope : bool → bool → list name → bool → tactic (name_set × format)) : parser unit := do silent ← optional (tk "-"), fast_only ← optional (tk "*"), silent ← if silent.is_some then return silent else optional (tk "-"), -- allow either order of *- (use_only, extra) ← parse_lint_additions, (_, s) ← scope fast_only.is_none silent.is_none extra use_only, when (¬ s.is_nil) $ do trace s, when silent.is_some $ fail "Linting did not succeed" /-- The command `#lint` at the bottom of a file will warn you about some common mistakes in that file. Usage: `#lint`, `#lint linter_1 linter_2`, `#lint only linter_1 linter_2`. `#lint-` will suppress the output of passing checks. Use the command `#list_linters` to see all available linters. -/ @[user_command] meta def lint_cmd (_ : parse $ tk "#lint") : parser unit := lint_cmd_aux @lint /-- The command `#lint_mathlib` checks all of mathlib for certain mistakes. Usage: `#lint_mathlib`, `#lint_mathlib linter_1 linter_2`, `#lint_mathlib only linter_1 linter_2`. `#lint_mathlib-` will suppress the output of passing checks. Use the command `#list_linters` to see all available linters. -/ @[user_command] meta def lint_mathlib_cmd (_ : parse $ tk "#lint_mathlib") : parser unit := lint_cmd_aux @lint_mathlib /-- The command `#lint_all` checks all imported files for certain mistakes. Usage: `#lint_all`, `#lint_all linter_1 linter_2`, `#lint_all only linter_1 linter_2`. `#lint_all-` will suppress the output of passing checks. Use the command `#list_linters` to see all available linters. -/ @[user_command] meta def lint_all_cmd (_ : parse $ tk "#lint_all") : parser unit := lint_cmd_aux @lint_all /-- The command `#list_linters` prints a list of all available linters. -/ @[user_command] meta def list_linters (_ : parse $ tk "#list_linters") : parser unit := do env ← get_env, let ns := env.decl_filter_map $ λ dcl, if (dcl.to_name.get_prefix = `linter) && (dcl.type = `(linter)) then some dcl.to_name else none, trace "Available linters:\n linters marked with (*) are in the default lint set\n", ns.mmap' $ λ n, do b ← has_attribute' `linter n, trace $ n.pop_prefix.to_string ++ if b then " (*)" else "" /-- Use `lint` as a hole command. Note: In a large file, there might be some delay between choosing the option and the information appearing -/ @[hole_command] meta def lint_hole_cmd : hole_command := { name := "Lint", descr := "Lint: Find common mistakes in current file.", action := λ es, do (_, s) ← lint, return [(s.to_string,"")] } /-- Tries to apply the `nolint` attribute to a list of declarations. Always succeeds, even if some of the declarations don't exist. -/ meta def apply_nolint_tac (decls : list name) : tactic unit := decls.mmap' (λ d, try (nolint_attr.set d () tt)) /-- `apply_nolint id1 id2 ...` tries to apply the `nolint` attribute to `id1`, `id2`, ... It will always succeed, even if some of the declarations do not exist. -/ @[user_command] meta def apply_nolint_cmd (_ : parse $ tk "apply_nolint") : parser unit := ident_* >>= ↑apply_nolint_tac
c434237376dda2d6b676e2347f24cce820c226b4
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/itac.lean
4fce0c2114835ea76344cfc7b1d771439e8ddfe5
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
361
lean
axiom addz {A : Type} [has_add A] [has_zero A] : ∀ a : A, a + 0 = a example {A : Type} [has_add A] [has_zero A] (a b c : A) : (a + 0) + (b + 0) + (c + 0) = a + b + c := begin repeat {rw addz} end example {A : Type} [has_add A] [has_zero A] (a b c : A) : (a + 0) + (b + 0) + (c + 0) = a + b + c := begin repeat {rw addz, trace "------", trace_state} end
010ce9d04dbf859da509a4b7ecfc04108f484980
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/set_theory/schroeder_bernstein.lean
a3a80ca27deb203ab2aa2ff6332480eccc2a41ac
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
5,075
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 The Schröder-Bernstein theorem, and well ordering of cardinals. -/ import order.fixed_points import order.zorn open set classical open_locale classical universes u v namespace function namespace embedding section antisymm variables {α : Type u} {β : Type v} theorem schroeder_bernstein {f : α → β} {g : β → α} (hf : function.injective f) (hg : function.injective g) : ∃ h : α → β, bijective h := let s : set α := lfp $ λ s, (g '' (f '' s)ᶜ)ᶜ in have hs : (g '' (f '' s)ᶜ)ᶜ = s, from lfp_fixed_point (λ x y hxy, compl_subset_compl.mpr $ image_subset _ $ compl_subset_compl.mpr $ image_subset _ hxy : monotone (λ s, (g '' (f '' s)ᶜ)ᶜ)), have hns : sᶜ = g '' (f '' s)ᶜ, from compl_injective $ by simp [hs], let g' := λ a, @inv_fun β ⟨f a⟩ α g a in have g'g : g' ∘ g = id, from funext $ λ b, @left_inverse_inv_fun _ ⟨f (g b)⟩ _ _ hg b, have hg'ns : g' '' sᶜ = (f '' s)ᶜ, by rw [hns, ←image_comp, g'g, image_id], let h := λ a, if a ∈ s then f a else g' a in have h '' univ = univ, from calc h '' univ = h '' s ∪ h '' sᶜ : by rw [←image_union, union_compl_self] ... = f '' s ∪ g' '' sᶜ : congr (congr_arg (∪) (image_congr $ by simp [h, if_pos] {contextual := tt})) (image_congr $ by simp [h, if_neg] {contextual := tt}) ... = univ : by rw [hg'ns, union_compl_self], have surjective h, from λ b, have b ∈ h '' univ, by rw [this]; trivial, let ⟨a, _, eq⟩ := this in ⟨a, eq⟩, have split : ∀x ∈ s, ∀y ∉ s, h x = h y → false, from λ x hx y hy eq, have y ∈ g '' (f '' s)ᶜ, by rwa [←hns], let ⟨y', hy', eq_y'⟩ := this in have f x = y', from calc f x = g' y : by simp [h, hx, hy, if_pos, if_neg] at eq; assumption ... = (g' ∘ g) y' : by simp [(∘), eq_y'] ... = _ : by simp [g'g], have y' ∈ f '' s, from this ▸ mem_image_of_mem _ hx, hy' this, have function.injective h, from λ x y eq, by_cases (λ hx : x ∈ s, by_cases (λ hy : y ∈ s, by simp [h, hx, hy, if_pos, if_neg] at eq; exact hf eq) (λ hy : y ∉ s, (split x hx y hy eq).elim)) (λ hx : x ∉ s, by_cases (λ hy : y ∈ s, (split y hy x hx eq.symm).elim) (λ hy : y ∉ s, have x ∈ g '' (f '' s)ᶜ, by rwa [←hns], let ⟨x', hx', eqx⟩ := this in have y ∈ g '' (f '' s)ᶜ, by rwa [←hns], let ⟨y', hy', eqy⟩ := this in have g' x = g' y, by simp [h, hx, hy, if_pos, if_neg] at eq; assumption, have (g' ∘ g) x' = (g' ∘ g) y', by simp [(∘), eqx, eqy, this], have x' = y', by rwa [g'g] at this, calc x = g x' : eqx.symm ... = g y' : by rw [this] ... = y : eqy)), ⟨h, ‹function.injective h›, ‹function.surjective h›⟩ theorem antisymm : (α ↪ β) → (β ↪ α) → nonempty (α ≃ β) | ⟨e₁, h₁⟩ ⟨e₂, h₂⟩ := let ⟨f, hf⟩ := schroeder_bernstein h₁ h₂ in ⟨equiv.of_bijective f hf⟩ end antisymm section wo parameters {ι : Type u} {β : ι → Type v} @[reducible] private def sets := {s : set (∀ i, β i) | ∀ (x ∈ s) (y ∈ s) i, (x : ∀ i, β i) i = y i → x = y} theorem min_injective (I : nonempty ι) : ∃ i, nonempty (∀ j, β i ↪ β j) := let ⟨s, hs, ms⟩ := show ∃ s ∈ sets, ∀a ∈ sets, s ⊆ a → a = s, from zorn.zorn_subset sets (λ c hc hcc, ⟨⋃₀ c, λ x ⟨p, hpc, hxp⟩ y ⟨q, hqc, hyq⟩ i hi, (hcc.total hpc hqc).elim (λ h, hc hqc x (h hxp) y hyq i hi) (λ h, hc hpc x hxp y (h hyq) i hi), λ _, subset_sUnion_of_mem⟩) in let ⟨i, e⟩ := show ∃ i, ∀ y, ∃ x ∈ s, (x : ∀ i, β i) i = y, from classical.by_contradiction $ λ h, have h : ∀ i, ∃ y, ∀ x ∈ s, (x : ∀ i, β i) i ≠ y, by simpa only [not_exists, not_forall] using h, let ⟨f, hf⟩ := axiom_of_choice h in have f ∈ s, from have insert f s ∈ sets := λ x hx y hy, begin cases hx; cases hy, {simp [hx, hy]}, { subst x, exact λ i e, (hf i y hy e.symm).elim }, { subst y, exact λ i e, (hf i x hx e).elim }, { exact hs x hx y hy } end, ms _ this (subset_insert f s) ▸ mem_insert _ _, let ⟨i⟩ := I in hf i f this rfl in let ⟨f, hf⟩ := axiom_of_choice e in ⟨i, ⟨λ j, ⟨λ a, f a j, λ a b e', let ⟨sa, ea⟩ := hf a, ⟨sb, eb⟩ := hf b in by rw [← ea, ← eb, hs _ sa _ sb _ e']⟩⟩⟩ end wo theorem total {α : Type u} {β : Type v} : nonempty (α ↪ β) ∨ nonempty (β ↪ α) := match @min_injective bool (λ b, cond b (ulift α) (ulift.{(max u v) v} β)) ⟨tt⟩ with | ⟨tt, ⟨h⟩⟩ := let ⟨f, hf⟩ := h ff in or.inl ⟨embedding.congr equiv.ulift equiv.ulift ⟨f, hf⟩⟩ | ⟨ff, ⟨h⟩⟩ := let ⟨f, hf⟩ := h tt in or.inr ⟨embedding.congr equiv.ulift equiv.ulift ⟨f, hf⟩⟩ end end embedding end function
ecd985148268f0cdbf2ba518a8bb4bfa92f6308f
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/tactic/omega/int/form.lean
45ea52ad6b193e1259cfde033add5a47aa581fe5
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
4,170
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Seul Baek -/ /- Linear integer arithmetic formulas in pre-normalized form. -/ import tactic.omega.int.preterm namespace omega namespace int /-- Intermediate shadow syntax for LNA formulas that includes unreified exprs -/ meta inductive exprform | eq : exprterm → exprterm → exprform | le : exprterm → exprterm → exprform | not : exprform → exprform | or : exprform → exprform → exprform | and : exprform → exprform → exprform /-- Intermediate shadow syntax for LIA formulas that includes non-canonical terms -/ @[derive has_reflect, derive inhabited] inductive preform | eq : preterm → preterm → preform | le : preterm → preterm → preform | not : preform → preform | or : preform → preform → preform | and : preform → preform → preform localized "notation x ` =* ` y := omega.int.preform.eq x y" in omega.int localized "notation x ` ≤* ` y := omega.int.preform.le x y" in omega.int localized "notation `¬* ` p := omega.int.preform.not p" in omega.int localized "notation p ` ∨* ` q := omega.int.preform.or p q" in omega.int localized "notation p ` ∧* ` q := omega.int.preform.and p q" in omega.int namespace preform /-- Evaluate a preform into prop using the valuation v. -/ @[simp] def holds (v : nat → int) : preform → Prop | (t =* s) := t.val v = s.val v | (t ≤* s) := t.val v ≤ s.val v | (¬* p) := ¬ p.holds | (p ∨* q) := p.holds ∨ q.holds | (p ∧* q) := p.holds ∧ q.holds end preform /-- univ_close p n := p closed by prepending n universal quantifiers -/ @[simp] def univ_close (p : preform) : (nat → int) → nat → Prop | v 0 := p.holds v | v (k+1) := ∀ i : int, univ_close (update_zero i v) k namespace preform /-- Fresh de Brujin index not used by any variable in argument -/ def fresh_index : preform → nat | (t =* s) := max t.fresh_index s.fresh_index | (t ≤* s) := max t.fresh_index s.fresh_index | (¬* p) := p.fresh_index | (p ∨* q) := max p.fresh_index q.fresh_index | (p ∧* q) := max p.fresh_index q.fresh_index /-- All valuations satisfy argument -/ def valid (p : preform) : Prop := ∀ v, holds v p /-- There exists some valuation that satisfies argument -/ def sat (p : preform) : Prop := ∃ v, holds v p /-- implies p q := under any valuation, q holds if p holds -/ def implies (p q : preform) : Prop := ∀ v, (holds v p → holds v q) /-- equiv p q := under any valuation, p holds iff q holds -/ def equiv (p q : preform) : Prop := ∀ v, (holds v p ↔ holds v q) lemma sat_of_implies_of_sat {p q : preform} : implies p q → sat p → sat q := begin intros h1 h2, apply exists_imp_exists h1 h2 end lemma sat_or {p q : preform} : sat (p ∨* q) ↔ sat p ∨ sat q := begin constructor; intro h1, { cases h1 with v h1, cases h1 with h1 h1; [left,right]; refine ⟨v,_⟩; assumption }, { cases h1 with h1 h1; cases h1 with v h1; refine ⟨v,_⟩; [left,right]; assumption } end /-- There does not exist any valuation that satisfies argument -/ def unsat (p : preform) : Prop := ¬ sat p def repr : preform → string | (t =* s) := "(" ++ t.repr ++ " = " ++ s.repr ++ ")" | (t ≤* s) := "(" ++ t.repr ++ " ≤ " ++ s.repr ++ ")" | (¬* p) := "¬" ++ p.repr | (p ∨* q) := "(" ++ p.repr ++ " ∨ " ++ q.repr ++ ")" | (p ∧* q) := "(" ++ p.repr ++ " ∧ " ++ q.repr ++ ")" instance has_repr : has_repr preform := ⟨repr⟩ meta instance has_to_format : has_to_format preform := ⟨λ x, x.repr⟩ end preform lemma univ_close_of_valid {p : preform} : ∀ {m v}, p.valid → univ_close p v m | 0 v h1 := h1 _ | (m+1) v h1 := λ i, univ_close_of_valid h1 lemma valid_of_unsat_not {p : preform} : (¬*p).unsat → p.valid := begin simp only [preform.sat, preform.unsat, preform.valid, preform.holds], rw not_exists_not, intro h, assumption end /-- Tactic for setting up proof by induction over preforms. -/ meta def preform.induce (t : tactic unit := tactic.skip) : tactic unit := `[ intro p, induction p with t s t s p ih p q ihp ihq p q ihp ihq; t] end int end omega
eb7133c84e0387d942ad9a825a685aca701c62a8
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/tests/lean/hott/len_eq.hlean
a3a4ea436f3c0f880801130f10ebb51a7fd25e7e
[ "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
2,974
hlean
import init.ua open nat unit equiv is_trunc inductive vector (A : Type) : nat → Type := | nil {} : vector A zero | cons : Π {n}, A → vector A n → vector A (succ n) open vector notation a :: b := cons a b definition const {A : Type} : Π (n : nat), A → vector A n | zero a := nil | (succ n) a := a :: const n a definition head {A : Type} : Π {n : nat}, vector A (succ n) → A | n (x :: xs) := x theorem singlenton_vector_unit : ∀ {n : nat} (v w : vector unit n), v = w | zero nil nil := rfl | (succ n) (star::xs) (star::ys) := begin have h₁ : xs = ys, from singlenton_vector_unit xs ys, rewrite h₁ end private definition f (n m : nat) (v : vector unit n) : vector unit m := const m star theorem vn_eqv_vm (n m : nat) : vector unit n ≃ vector unit m := equiv.MK (f n m) (f m n) (take v : vector unit m, singlenton_vector_unit (f n m (f m n v)) v) (take v : vector unit n, singlenton_vector_unit (f m n (f n m v)) v) theorem vn_eq_vm (n m : nat) : vector unit n = vector unit m := ua (vn_eqv_vm n m) definition vector_inj (A : Type) := ∀ (n m : nat), vector A n = vector A m → n = m theorem not_vector_inj : ¬ vector_inj unit := assume H : vector_inj unit, have aux₁ : 0 = 1, from H 0 1 (vn_eq_vm 0 1), lift.down (nat.no_confusion aux₁) definition cast {A B : Type} (H : A = B) (a : A) : B := eq.rec_on H a open sigma definition heq {A B : Type} (a : A) (b : B) := Σ (H : A = B), cast H a = b infix `==`:50 := heq definition heq.type_eq {A B : Type} {a : A} {b : B} : a == b → A = B | ⟨H, e⟩ := H definition heq.symm : ∀ {A B : Type} {a : A} {b : B}, a == b → b == a | A A a a ⟨eq.refl A, eq.refl a⟩ := ⟨eq.refl A, eq.refl a⟩ definition heq.trans : ∀ {A B C : Type} {a : A} {b : B} {c : C}, a == b → b == c → a == c | A A A a a a ⟨eq.refl A, eq.refl a⟩ ⟨eq.refl A, eq.refl a⟩ := ⟨eq.refl A, eq.refl a⟩ theorem cast_heq : ∀ {A B : Type} (H : A = B) (a : A), cast H a == a | A A (eq.refl A) a := ⟨eq.refl A, eq.refl a⟩ definition lem_eq (A : Type) : Type := ∀ (n m : nat) (v : vector A n) (w : vector A m), v == w → n = m theorem lem_eq_iff_vector_inj (A : Type) [inh : inhabited A] : lem_eq A ↔ vector_inj A := iff.intro (assume Hl : lem_eq A, assume n m he, assert a : A, from default A, assert v : vector A n, from const n a, have e₁ : v == cast he v, from heq.symm (cast_heq he v), Hl n m v (cast he v) e₁) (assume Hr : vector_inj A, assume n m v w he, Hr n m (heq.type_eq he)) theorem lem_eq_of_not_inhabited (A : Type) [ninh : inhabited A → empty] : lem_eq A := take (n m : nat), match n with | zero := match m with | zero := take v w He, rfl | (succ m₁) := take (v : vector A zero) (w : vector A (succ m₁)), empty.elim (ninh (inhabited.mk (head w))) end | (succ n₁) := take (v : vector A (succ n₁)) (w : vector A m), empty.elim (ninh (inhabited.mk (head v))) end
b5a554b7b6e63351b902c338b89ee07342f95bc0
9dc8cecdf3c4634764a18254e94d43da07142918
/src/group_theory/free_group.lean
fcca4d3aee03eb22cfdaafac0b6637245a25b60e
[ "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
36,036
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import data.fintype.basic import group_theory.subgroup.basic /-! # Free groups This file defines free groups over a type. Furthermore, it is shown that the free group construction is an instance of a monad. For the result that `free_group` is the left adjoint to the forgetful functor from groups to types, see `algebra/category/Group/adjunctions`. ## Main definitions * `free_group`: the free group associated to a type `α` defined as the words over `a : α × bool` modulo the relation `a * x * x⁻¹ * b = a * b`. * `free_group.mk`: the canonical quotient map `list (α × bool) → free_group α`. * `free_group.of`: the canoical injection `α → free_group α`. * `free_group.lift f`: the canonical group homomorphism `free_group α →* G` given a group `G` and a function `f : α → G`. ## Main statements * `free_group.church_rosser`: The Church-Rosser theorem for word reduction (also known as Newman's diamond lemma). * `free_group.free_group_unit_equiv_int`: The free group over the one-point type is isomorphic to the integers. * The free group construction is an instance of a monad. ## Implementation details First we introduce the one step reduction relation `free_group.red.step`: `w * x * x⁻¹ * v ~> w * v`, its reflexive transitive closure `free_group.red.trans` and prove that its join is an equivalence relation. Then we introduce `free_group α` as a quotient over `free_group.red.step`. ## Tags free group, Newman's diamond lemma, Church-Rosser theorem -/ open relation universes u v w variables {α : Type u} local attribute [simp] list.append_eq_has_append namespace free_group variables {L L₁ L₂ L₃ L₄ : list (α × bool)} /-- Reduction step: `w * x * x⁻¹ * v ~> w * v` -/ inductive red.step : list (α × bool) → list (α × bool) → Prop | bnot {L₁ L₂ x b} : red.step (L₁ ++ (x, b) :: (x, bnot b) :: L₂) (L₁ ++ L₂) attribute [simp] red.step.bnot /-- Reflexive-transitive closure of red.step -/ def red : list (α × bool) → list (α × bool) → Prop := refl_trans_gen red.step @[refl] lemma red.refl : red L L := refl_trans_gen.refl @[trans] lemma red.trans : red L₁ L₂ → red L₂ L₃ → red L₁ L₃ := refl_trans_gen.trans namespace red /-- Predicate asserting that word `w₁` can be reduced to `w₂` in one step, i.e. there are words `w₃ w₄` and letter `x` such that `w₁ = w₃xx⁻¹w₄` and `w₂ = w₃w₄` -/ theorem step.length : ∀ {L₁ L₂ : list (α × bool)}, step L₁ L₂ → L₂.length + 2 = L₁.length | _ _ (@red.step.bnot _ L1 L2 x b) := by rw [list.length_append, list.length_append]; refl @[simp] lemma step.bnot_rev {x b} : step (L₁ ++ (x, bnot b) :: (x, b) :: L₂) (L₁ ++ L₂) := by cases b; from step.bnot @[simp] lemma step.cons_bnot {x b} : red.step ((x, b) :: (x, bnot b) :: L) L := @step.bnot _ [] _ _ _ @[simp] lemma step.cons_bnot_rev {x b} : red.step ((x, bnot b) :: (x, b) :: L) L := @red.step.bnot_rev _ [] _ _ _ theorem step.append_left : ∀ {L₁ L₂ L₃ : list (α × bool)}, step L₂ L₃ → step (L₁ ++ L₂) (L₁ ++ L₃) | _ _ _ red.step.bnot := by rw [← list.append_assoc, ← list.append_assoc]; constructor theorem step.cons {x} (H : red.step L₁ L₂) : red.step (x :: L₁) (x :: L₂) := @step.append_left _ [x] _ _ H theorem step.append_right : ∀ {L₁ L₂ L₃ : list (α × bool)}, step L₁ L₂ → step (L₁ ++ L₃) (L₂ ++ L₃) | _ _ _ red.step.bnot := by simp lemma not_step_nil : ¬ step [] L := begin generalize h' : [] = L', assume h, cases h with L₁ L₂, simp [list.nil_eq_append_iff] at h', contradiction end lemma step.cons_left_iff {a : α} {b : bool} : step ((a, b) :: L₁) L₂ ↔ (∃L, step L₁ L ∧ L₂ = (a, b) :: L) ∨ (L₁ = (a, bnot b)::L₂) := begin split, { generalize hL : ((a, b) :: L₁ : list _) = L, assume h, rcases h with ⟨_ | ⟨p, s'⟩, e, a', b'⟩, { simp at hL, simp [*] }, { simp at hL, rcases hL with ⟨rfl, rfl⟩, refine or.inl ⟨s' ++ e, step.bnot, _⟩, simp } }, { assume h, rcases h with ⟨L, h, rfl⟩ | rfl, { exact step.cons h }, { exact step.cons_bnot } } end lemma not_step_singleton : ∀ {p : α × bool}, ¬ step [p] L | (a, b) := by simp [step.cons_left_iff, not_step_nil] lemma step.cons_cons_iff : ∀{p : α × bool}, step (p :: L₁) (p :: L₂) ↔ step L₁ L₂ := by simp [step.cons_left_iff, iff_def, or_imp_distrib] {contextual := tt} lemma step.append_left_iff : ∀L, step (L ++ L₁) (L ++ L₂) ↔ step L₁ L₂ | [] := by simp | (p :: l) := by simp [step.append_left_iff l, step.cons_cons_iff] private theorem step.diamond_aux : ∀ {L₁ L₂ L₃ L₄ : list (α × bool)} {x1 b1 x2 b2}, L₁ ++ (x1, b1) :: (x1, bnot b1) :: L₂ = L₃ ++ (x2, b2) :: (x2, bnot b2) :: L₄ → L₁ ++ L₂ = L₃ ++ L₄ ∨ ∃ L₅, red.step (L₁ ++ L₂) L₅ ∧ red.step (L₃ ++ L₄) L₅ | [] _ [] _ _ _ _ _ H := by injections; subst_vars; simp | [] _ [(x3,b3)] _ _ _ _ _ H := by injections; subst_vars; simp | [(x3,b3)] _ [] _ _ _ _ _ H := by injections; subst_vars; simp | [] _ ((x3,b3)::(x4,b4)::tl) _ _ _ _ _ H := by injections; subst_vars; simp; right; exact ⟨_, red.step.bnot, red.step.cons_bnot⟩ | ((x3,b3)::(x4,b4)::tl) _ [] _ _ _ _ _ H := by injections; subst_vars; simp; right; exact ⟨_, red.step.cons_bnot, red.step.bnot⟩ | ((x3,b3)::tl) _ ((x4,b4)::tl2) _ _ _ _ _ H := let ⟨H1, H2⟩ := list.cons.inj H in match step.diamond_aux H2 with | or.inl H3 := or.inl $ by simp [H1, H3] | or.inr ⟨L₅, H3, H4⟩ := or.inr ⟨_, step.cons H3, by simpa [H1] using step.cons H4⟩ end theorem step.diamond : ∀ {L₁ L₂ L₃ L₄ : list (α × bool)}, red.step L₁ L₃ → red.step L₂ L₄ → L₁ = L₂ → L₃ = L₄ ∨ ∃ L₅, red.step L₃ L₅ ∧ red.step L₄ L₅ | _ _ _ _ red.step.bnot red.step.bnot H := step.diamond_aux H lemma step.to_red : step L₁ L₂ → red L₁ L₂ := refl_trans_gen.single /-- **Church-Rosser theorem** for word reduction: If `w1 w2 w3` are words such that `w1` reduces to `w2` and `w3` respectively, then there is a word `w4` such that `w2` and `w3` reduce to `w4` respectively. This is also known as Newman's diamond lemma. -/ theorem church_rosser : red L₁ L₂ → red L₁ L₃ → join red L₂ L₃ := relation.church_rosser (assume a b c hab hac, match b, c, red.step.diamond hab hac rfl with | b, _, or.inl rfl := ⟨b, by refl, by refl⟩ | b, c, or.inr ⟨d, hbd, hcd⟩ := ⟨d, refl_gen.single hbd, hcd.to_red⟩ end) lemma cons_cons {p} : red L₁ L₂ → red (p :: L₁) (p :: L₂) := refl_trans_gen.lift (list.cons p) (assume a b, step.cons) lemma cons_cons_iff (p) : red (p :: L₁) (p :: L₂) ↔ red L₁ L₂ := iff.intro begin generalize eq₁ : (p :: L₁ : list _) = LL₁, generalize eq₂ : (p :: L₂ : list _) = LL₂, assume h, induction h using relation.refl_trans_gen.head_induction_on with L₁ L₂ h₁₂ h ih generalizing L₁ L₂, { subst_vars, cases eq₂, constructor }, { subst_vars, cases p with a b, rw [step.cons_left_iff] at h₁₂, rcases h₁₂ with ⟨L, h₁₂, rfl⟩ | rfl, { exact (ih rfl rfl).head h₁₂ }, { exact (cons_cons h).tail step.cons_bnot_rev } } end cons_cons lemma append_append_left_iff : ∀L, red (L ++ L₁) (L ++ L₂) ↔ red L₁ L₂ | [] := iff.rfl | (p :: L) := by simp [append_append_left_iff L, cons_cons_iff] lemma append_append (h₁ : red L₁ L₃) (h₂ : red L₂ L₄) : red (L₁ ++ L₂) (L₃ ++ L₄) := (h₁.lift (λL, L ++ L₂) (assume a b, step.append_right)).trans ((append_append_left_iff _).2 h₂) lemma to_append_iff : red L (L₁ ++ L₂) ↔ (∃L₃ L₄, L = L₃ ++ L₄ ∧ red L₃ L₁ ∧ red L₄ L₂) := iff.intro begin generalize eq : L₁ ++ L₂ = L₁₂, assume h, induction h with L' L₁₂ hLL' h ih generalizing L₁ L₂, { exact ⟨_, _, eq.symm, by refl, by refl⟩ }, { cases h with s e a b, rcases list.append_eq_append_iff.1 eq with ⟨s', rfl, rfl⟩ | ⟨e', rfl, rfl⟩, { have : L₁ ++ (s' ++ ((a, b) :: (a, bnot b) :: e)) = (L₁ ++ s') ++ ((a, b) :: (a, bnot b) :: e), { simp }, rcases ih this with ⟨w₁, w₂, rfl, h₁, h₂⟩, exact ⟨w₁, w₂, rfl, h₁, h₂.tail step.bnot⟩ }, { have : (s ++ ((a, b) :: (a, bnot b) :: e')) ++ L₂ = s ++ ((a, b) :: (a, bnot b) :: (e' ++ L₂)), { simp }, rcases ih this with ⟨w₁, w₂, rfl, h₁, h₂⟩, exact ⟨w₁, w₂, rfl, h₁.tail step.bnot, h₂⟩ }, } end (assume ⟨L₃, L₄, eq, h₃, h₄⟩, eq.symm ▸ append_append h₃ h₄) /-- The empty word `[]` only reduces to itself. -/ theorem nil_iff : red [] L ↔ L = [] := refl_trans_gen_iff_eq (assume l, red.not_step_nil) /-- A letter only reduces to itself. -/ theorem singleton_iff {x} : red [x] L₁ ↔ L₁ = [x] := refl_trans_gen_iff_eq (assume l, not_step_singleton) /-- If `x` is a letter and `w` is a word such that `xw` reduces to the empty word, then `w` reduces to `x⁻¹` -/ theorem cons_nil_iff_singleton {x b} : red ((x, b) :: L) [] ↔ red L [(x, bnot b)] := iff.intro (assume h, have h₁ : red ((x, bnot b) :: (x, b) :: L) [(x, bnot b)], from cons_cons h, have h₂ : red ((x, bnot b) :: (x, b) :: L) L, from refl_trans_gen.single step.cons_bnot_rev, let ⟨L', h₁, h₂⟩ := church_rosser h₁ h₂ in by rw [singleton_iff] at h₁; subst L'; assumption) (assume h, (cons_cons h).tail step.cons_bnot) theorem red_iff_irreducible {x1 b1 x2 b2} (h : (x1, b1) ≠ (x2, b2)) : red [(x1, bnot b1), (x2, b2)] L ↔ L = [(x1, bnot b1), (x2, b2)] := begin apply refl_trans_gen_iff_eq, generalize eq : [(x1, bnot b1), (x2, b2)] = L', assume L h', cases h', simp [list.cons_eq_append_iff, list.nil_eq_append_iff] at eq, rcases eq with ⟨rfl, ⟨rfl, rfl⟩, ⟨rfl, rfl⟩, rfl⟩, subst_vars, simp at h, contradiction end /-- If `x` and `y` are distinct letters and `w₁ w₂` are words such that `xw₁` reduces to `yw₂`, then `w₁` reduces to `x⁻¹yw₂`. -/ theorem inv_of_red_of_ne {x1 b1 x2 b2} (H1 : (x1, b1) ≠ (x2, b2)) (H2 : red ((x1, b1) :: L₁) ((x2, b2) :: L₂)) : red L₁ ((x1, bnot b1) :: (x2, b2) :: L₂) := begin have : red ((x1, b1) :: L₁) ([(x2, b2)] ++ L₂), from H2, rcases to_append_iff.1 this with ⟨_ | ⟨p, L₃⟩, L₄, eq, h₁, h₂⟩, { simp [nil_iff] at h₁, contradiction }, { cases eq, show red (L₃ ++ L₄) ([(x1, bnot b1), (x2, b2)] ++ L₂), apply append_append _ h₂, have h₁ : red ((x1, bnot b1) :: (x1, b1) :: L₃) [(x1, bnot b1), (x2, b2)], { exact cons_cons h₁ }, have h₂ : red ((x1, bnot b1) :: (x1, b1) :: L₃) L₃, { exact step.cons_bnot_rev.to_red }, rcases church_rosser h₁ h₂ with ⟨L', h₁, h₂⟩, rw [red_iff_irreducible H1] at h₁, rwa [h₁] at h₂ } end theorem step.sublist (H : red.step L₁ L₂) : L₂ <+ L₁ := by cases H; simp; constructor; constructor; refl /-- If `w₁ w₂` are words such that `w₁` reduces to `w₂`, then `w₂` is a sublist of `w₁`. -/ protected theorem sublist : red L₁ L₂ → L₂ <+ L₁ := refl_trans_gen_of_transitive_reflexive (λl, list.sublist.refl l) (λa b c hab hbc, list.sublist.trans hbc hab) (λa b, red.step.sublist) theorem length_le (h : red L₁ L₂) : L₂.length ≤ L₁.length := list.length_le_of_sublist h.sublist theorem sizeof_of_step : ∀ {L₁ L₂ : list (α × bool)}, step L₁ L₂ → L₂.sizeof < L₁.sizeof | _ _ (@step.bnot _ L1 L2 x b) := begin induction L1 with hd tl ih, case list.nil { dsimp [list.sizeof], have H : 1 + sizeof (x, b) + (1 + sizeof (x, bnot b) + list.sizeof L2) = (list.sizeof L2 + 1) + (sizeof (x, b) + sizeof (x, bnot b) + 1), { ac_refl }, rw H, exact nat.le_add_right _ _ }, case list.cons { dsimp [list.sizeof], exact nat.add_lt_add_left ih _ } end theorem length (h : red L₁ L₂) : ∃ n, L₁.length = L₂.length + 2 * n := begin induction h with L₂ L₃ h₁₂ h₂₃ ih, { exact ⟨0, rfl⟩ }, { rcases ih with ⟨n, eq⟩, existsi (1 + n), simp [mul_add, eq, (step.length h₂₃).symm, add_assoc] } end theorem antisymm (h₁₂ : red L₁ L₂) (h₂₁ : red L₂ L₁) : L₁ = L₂ := h₂₁.sublist.antisymm h₁₂.sublist end red theorem equivalence_join_red : equivalence (join (@red α)) := equivalence_join_refl_trans_gen $ assume a b c hab hac, (match b, c, red.step.diamond hab hac rfl with | b, _, or.inl rfl := ⟨b, by refl, by refl⟩ | b, c, or.inr ⟨d, hbd, hcd⟩ := ⟨d, refl_gen.single hbd, refl_trans_gen.single hcd⟩ end) theorem join_red_of_step (h : red.step L₁ L₂) : join red L₁ L₂ := join_of_single reflexive_refl_trans_gen h.to_red theorem eqv_gen_step_iff_join_red : eqv_gen red.step L₁ L₂ ↔ join red L₁ L₂ := iff.intro (assume h, have eqv_gen (join red) L₁ L₂ := h.mono (assume a b, join_red_of_step), equivalence_join_red.eqv_gen_iff.1 this) (join_of_equivalence (eqv_gen.is_equivalence _) $ assume a b, refl_trans_gen_of_equivalence (eqv_gen.is_equivalence _) eqv_gen.rel) end free_group /-- The free group over a type, i.e. the words formed by the elements of the type and their formal inverses, quotient by one step reduction. -/ def free_group (α : Type u) : Type u := quot $ @free_group.red.step α namespace free_group variables {α} {L L₁ L₂ L₃ L₄ : list (α × bool)} /-- The canonical map from `list (α × bool)` to the free group on `α`. -/ def mk (L) : free_group α := quot.mk red.step L @[simp] lemma quot_mk_eq_mk : quot.mk red.step L = mk L := rfl @[simp] lemma quot_lift_mk (β : Type v) (f : list (α × bool) → β) (H : ∀ L₁ L₂, red.step L₁ L₂ → f L₁ = f L₂) : quot.lift f H (mk L) = f L := rfl @[simp] lemma quot_lift_on_mk (β : Type v) (f : list (α × bool) → β) (H : ∀ L₁ L₂, red.step L₁ L₂ → f L₁ = f L₂) : quot.lift_on (mk L) f H = f L := rfl @[simp] lemma quot_map_mk (β : Type v) (f : list (α × bool) → list (β × bool)) (H : (red.step ⇒ red.step) f f) : quot.map f H (mk L) = mk (f L) := rfl instance : has_one (free_group α) := ⟨mk []⟩ lemma one_eq_mk : (1 : free_group α) = mk [] := rfl instance : inhabited (free_group α) := ⟨1⟩ instance : has_mul (free_group α) := ⟨λ x y, quot.lift_on x (λ L₁, quot.lift_on y (λ L₂, mk $ L₁ ++ L₂) (λ L₂ L₃ H, quot.sound $ red.step.append_left H)) (λ L₁ L₂ H, quot.induction_on y $ λ L₃, quot.sound $ red.step.append_right H)⟩ @[simp] lemma mul_mk : mk L₁ * mk L₂ = mk (L₁ ++ L₂) := rfl /-- Transform a word representing a free group element into a word representing its inverse. --/ def inv_rev (w : list (α × bool)) : list (α × bool) := (list.map (λ (g : α × bool), (g.1, bnot g.2)) w).reverse @[simp] lemma inv_rev_length : (inv_rev L₁).length = L₁.length := by simp [inv_rev] @[simp] lemma inv_rev_inv_rev : (inv_rev (inv_rev L₁) = L₁) := by simp [inv_rev, (∘)] @[simp] lemma inv_rev_empty : inv_rev ([] : list (α × bool)) = [] := rfl lemma inv_rev_involutive : function.involutive (@inv_rev α) := λ _, inv_rev_inv_rev lemma inv_rev_injective : function.injective (@inv_rev α) := inv_rev_involutive.injective lemma inv_rev_surjective : function.surjective (@inv_rev α) := inv_rev_involutive.surjective lemma inv_rev_bijective : function.bijective (@inv_rev α) := inv_rev_involutive.bijective instance : has_inv (free_group α) := ⟨quot.map inv_rev (by { intros a b h, cases h, simp [inv_rev], })⟩ @[simp] lemma inv_mk : (mk L)⁻¹ = mk (inv_rev L) := rfl lemma red.step.inv_rev {L₁ L₂ : list (α × bool)} (h : red.step L₁ L₂) : red.step (inv_rev L₁) (inv_rev L₂) := begin cases h with a b x y, simp [inv_rev], end lemma red.inv_rev {L₁ L₂ : list (α × bool)} (h : red L₁ L₂) : red (inv_rev L₁) (inv_rev L₂) := relation.refl_trans_gen.lift _ (λ a b, red.step.inv_rev) h @[simp] lemma red.step_inv_rev_iff : red.step (inv_rev L₁) (inv_rev L₂) ↔ red.step L₁ L₂ := ⟨λ h, by simpa only [inv_rev_inv_rev] using h.inv_rev, λ h, h.inv_rev⟩ @[simp] lemma red_inv_rev_iff : red (inv_rev L₁) (inv_rev L₂) ↔ red L₁ L₂ := ⟨λ h, by simpa only [inv_rev_inv_rev] using h.inv_rev, λ h, h.inv_rev⟩ instance : group (free_group α) := { mul := (*), one := 1, inv := has_inv.inv, mul_assoc := by rintros ⟨L₁⟩ ⟨L₂⟩ ⟨L₃⟩; simp, one_mul := by rintros ⟨L⟩; refl, mul_one := by rintros ⟨L⟩; simp [one_eq_mk], mul_left_inv := by rintros ⟨L⟩; exact (list.rec_on L rfl $ λ ⟨x, b⟩ tl ih, eq.trans (quot.sound $ by simp [inv_rev, one_eq_mk]) ih) } /-- `of` is the canonical injection from the type to the free group over that type by sending each element to the equivalence class of the letter that is the element. -/ def of (x : α) : free_group α := mk [(x, tt)] theorem red.exact : mk L₁ = mk L₂ ↔ join red L₁ L₂ := calc (mk L₁ = mk L₂) ↔ eqv_gen red.step L₁ L₂ : iff.intro (quot.exact _) quot.eqv_gen_sound ... ↔ join red L₁ L₂ : eqv_gen_step_iff_join_red /-- The canonical injection from the type to the free group is an injection. -/ theorem of_injective : function.injective (@of α) := λ _ _ H, let ⟨L₁, hx, hy⟩ := red.exact.1 H in by simp [red.singleton_iff] at hx hy; cc section lift variables {β : Type v} [group β] (f : α → β) {x y : free_group α} /-- Given `f : α → β` with `β` a group, the canonical map `list (α × bool) → β` -/ def lift.aux : list (α × bool) → β := λ L, list.prod $ L.map $ λ x, cond x.2 (f x.1) (f x.1)⁻¹ theorem red.step.lift {f : α → β} (H : red.step L₁ L₂) : lift.aux f L₁ = lift.aux f L₂ := by cases H with _ _ _ b; cases b; simp [lift.aux] /-- If `β` is a group, then any function from `α` to `β` extends uniquely to a group homomorphism from the free group over `α` to `β` -/ @[simps symm_apply] def lift : (α → β) ≃ (free_group α →* β) := { to_fun := λ f, monoid_hom.mk' (quot.lift (lift.aux f) $ λ L₁ L₂, red.step.lift) $ begin rintros ⟨L₁⟩ ⟨L₂⟩, simp [lift.aux], end, inv_fun := λ g, g ∘ of, left_inv := λ f, one_mul _, right_inv := λ g, monoid_hom.ext $ begin rintros ⟨L⟩, apply list.rec_on L, { exact g.map_one.symm, }, { rintros ⟨x, _ | _⟩ t (ih : _ = g (mk t)), { show _ = g ((of x)⁻¹ * mk t), simpa [lift.aux] using ih }, { show _ = g (of x * mk t), simpa [lift.aux] using ih }, }, end } variable {f} @[simp] lemma lift.mk : lift f (mk L) = list.prod (L.map $ λ x, cond x.2 (f x.1) (f x.1)⁻¹) := rfl @[simp] lemma lift.of {x} : lift f (of x) = f x := one_mul _ theorem lift.unique (g : free_group α →* β) (hg : ∀ x, g (of x) = f x) : ∀{x}, g x = lift f x := monoid_hom.congr_fun $ (lift.symm_apply_eq).mp (funext hg : g ∘ of = f) /-- Two homomorphisms out of a free group are equal if they are equal on generators. See note [partially-applied ext lemmas]. -/ @[ext] lemma ext_hom {G : Type*} [group G] (f g : free_group α →* G) (h : ∀ a, f (of a) = g (of a)) : f = g := lift.symm.injective $ funext h theorem lift.of_eq (x : free_group α) : lift of x = x := monoid_hom.congr_fun (lift.apply_symm_apply (monoid_hom.id _)) x theorem lift.range_le {s : subgroup β} (H : set.range f ⊆ s) : (lift f).range ≤ s := by rintros _ ⟨⟨L⟩, rfl⟩; exact list.rec_on L s.one_mem (λ ⟨x, b⟩ tl ih, bool.rec_on b (by simp at ih ⊢; from s.mul_mem (s.inv_mem $ H ⟨x, rfl⟩) ih) (by simp at ih ⊢; from s.mul_mem (H ⟨x, rfl⟩) ih)) theorem lift.range_eq_closure : (lift f).range = subgroup.closure (set.range f) := begin apply le_antisymm (lift.range_le subgroup.subset_closure), rw subgroup.closure_le, rintros _ ⟨a, rfl⟩, exact ⟨of a, by simp only [lift.of]⟩, end end lift section map variables {β : Type v} (f : α → β) {x y : free_group α} /-- Any function from `α` to `β` extends uniquely to a group homomorphism from the free group ver `α` to the free group over `β`. -/ def map : free_group α →* free_group β := monoid_hom.mk' (quot.map (list.map $ λ x, (f x.1, x.2)) $ λ L₁ L₂ H, by cases H; simp) (by { rintros ⟨L₁⟩ ⟨L₂⟩, simp }) variable {f} @[simp] lemma map.mk : map f (mk L) = mk (L.map (λ x, (f x.1, x.2))) := rfl @[simp] lemma map.id (x : free_group α) : map id x = x := by rcases x with ⟨L⟩; simp [list.map_id'] @[simp] lemma map.id' (x : free_group α) : map (λ z, z) x = x := map.id x theorem map.comp {γ : Type w} (f : α → β) (g : β → γ) (x) : map g (map f x) = map (g ∘ f) x := by rcases x with ⟨L⟩; simp @[simp] lemma map.of {x} : map f (of x) = of (f x) := rfl theorem map.unique (g : free_group α →* free_group β) (hg : ∀ x, g (of x) = of (f x)) : ∀{x}, g x = map f x := by rintros ⟨L⟩; exact list.rec_on L g.map_one (λ ⟨x, b⟩ t (ih : g (mk t) = map f (mk t)), bool.rec_on b (show g ((of x)⁻¹ * mk t) = map f ((of x)⁻¹ * mk t), by simp [g.map_mul, g.map_inv, hg, ih]) (show g (of x * mk t) = map f (of x * mk t), by simp [g.map_mul, hg, ih])) theorem map_eq_lift : map f x = lift (of ∘ f) x := eq.symm $ map.unique _ $ λ x, by simp /-- Equivalent types give rise to multiplicatively equivalent free groups. The converse can be found in `group_theory.free_abelian_group_finsupp`, as `equiv.of_free_group_equiv` -/ @[simps apply] def free_group_congr {α β} (e : α ≃ β) : free_group α ≃* free_group β := { to_fun := map e, inv_fun := map e.symm, left_inv := λ x, by simp [function.comp, map.comp], right_inv := λ x, by simp [function.comp, map.comp], map_mul' := monoid_hom.map_mul _ } @[simp] lemma free_group_congr_refl : free_group_congr (equiv.refl α) = mul_equiv.refl _ := mul_equiv.ext map.id @[simp] lemma free_group_congr_symm {α β} (e : α ≃ β) : (free_group_congr e).symm = free_group_congr e.symm := rfl lemma free_group_congr_trans {α β γ} (e : α ≃ β) (f : β ≃ γ) : (free_group_congr e).trans (free_group_congr f) = free_group_congr (e.trans f) := mul_equiv.ext $ map.comp _ _ end map section prod variables [group α] (x y : free_group α) /-- If `α` is a group, then any function from `α` to `α` extends uniquely to a homomorphism from the free group over `α` to `α`. This is the multiplicative version of `sum`. -/ def prod : free_group α →* α := lift id variables {x y} @[simp] lemma prod_mk : prod (mk L) = list.prod (L.map $ λ x, cond x.2 x.1 x.1⁻¹) := rfl @[simp] lemma prod.of {x : α} : prod (of x) = x := lift.of lemma prod.unique (g : free_group α →* α) (hg : ∀ x, g (of x) = x) {x} : g x = prod x := lift.unique g hg end prod theorem lift_eq_prod_map {β : Type v} [group β] {f : α → β} {x} : lift f x = prod (map f x) := begin rw ←lift.unique (prod.comp (map f)), { refl }, { simp } end section sum variables [add_group α] (x y : free_group α) /-- If `α` is a group, then any function from `α` to `α` extends uniquely to a homomorphism from the free group over `α` to `α`. This is the additive version of `prod`. -/ def sum : α := @prod (multiplicative _) _ x variables {x y} @[simp] lemma sum_mk : sum (mk L) = list.sum (L.map $ λ x, cond x.2 x.1 (-x.1)) := rfl @[simp] lemma sum.of {x : α} : sum (of x) = x := prod.of -- note: there are no bundled homs with different notation in the domain and codomain, so we copy -- these manually @[simp] lemma sum.map_mul : sum (x * y) = sum x + sum y := (@prod (multiplicative _) _).map_mul _ _ @[simp] lemma sum.map_one : sum (1:free_group α) = 0 := (@prod (multiplicative _) _).map_one @[simp] lemma sum.map_inv : sum x⁻¹ = -sum x := (prod : free_group (multiplicative α) →* multiplicative α).map_inv _ end sum /-- The bijection between the free group on the empty type, and a type with one element. -/ def free_group_empty_equiv_unit : free_group empty ≃ unit := { to_fun := λ _, (), inv_fun := λ _, 1, left_inv := by rintros ⟨_ | ⟨⟨⟨⟩, _⟩, _⟩⟩; refl, right_inv := λ ⟨⟩, rfl } /-- The bijection between the free group on a singleton, and the integers. -/ def free_group_unit_equiv_int : free_group unit ≃ ℤ := { to_fun := λ x, sum begin revert x, apply monoid_hom.to_fun, apply map (λ _, (1 : ℤ)), end, inv_fun := λ x, of () ^ x, left_inv := begin rintros ⟨L⟩, refine list.rec_on L rfl _, exact (λ ⟨⟨⟩, b⟩ tl ih, by cases b; simp [zpow_add] at ih ⊢; rw ih; refl), end, right_inv := λ x, int.induction_on x (by simp) (λ i ih, by simp at ih; simp [zpow_add, ih]) (λ i ih, by simp at ih; simp [zpow_add, ih, sub_eq_add_neg, -int.add_neg_one]) } section category variables {β : Type u} instance : monad free_group.{u} := { pure := λ α, of, map := λ α β f, (map f), bind := λ α β x f, lift f x } @[elab_as_eliminator] protected theorem induction_on {C : free_group α → Prop} (z : free_group α) (C1 : C 1) (Cp : ∀ x, C $ pure x) (Ci : ∀ x, C (pure x) → C (pure x)⁻¹) (Cm : ∀ x y, C x → C y → C (x * y)) : C z := quot.induction_on z $ λ L, list.rec_on L C1 $ λ ⟨x, b⟩ tl ih, bool.rec_on b (Cm _ _ (Ci _ $ Cp x) ih) (Cm _ _ (Cp x) ih) @[simp] lemma map_pure (f : α → β) (x : α) : f <$> (pure x : free_group α) = pure (f x) := map.of @[simp] lemma map_one (f : α → β) : f <$> (1 : free_group α) = 1 := (map f).map_one @[simp] lemma map_mul (f : α → β) (x y : free_group α) : f <$> (x * y) = f <$> x * f <$> y := (map f).map_mul x y @[simp] lemma map_inv (f : α → β) (x : free_group α) : f <$> (x⁻¹) = (f <$> x)⁻¹ := (map f).map_inv x @[simp] lemma pure_bind (f : α → free_group β) (x) : pure x >>= f = f x := lift.of @[simp] lemma one_bind (f : α → free_group β) : 1 >>= f = 1 := (lift f).map_one @[simp] lemma mul_bind (f : α → free_group β) (x y : free_group α) : x * y >>= f = (x >>= f) * (y >>= f) := (lift f).map_mul _ _ @[simp] lemma inv_bind (f : α → free_group β) (x : free_group α) : x⁻¹ >>= f = (x >>= f)⁻¹ := (lift f).map_inv _ instance : is_lawful_monad free_group.{u} := { id_map := λ α x, free_group.induction_on x (map_one id) (λ x, map_pure id x) (λ x ih, by rw [map_inv, ih]) (λ x y ihx ihy, by rw [map_mul, ihx, ihy]), pure_bind := λ α β x f, pure_bind f x, bind_assoc := λ α β γ x f g, free_group.induction_on x (by iterate 3 { rw one_bind }) (λ x, by iterate 2 { rw pure_bind }) (λ x ih, by iterate 3 { rw inv_bind }; rw ih) (λ x y ihx ihy, by iterate 3 { rw mul_bind }; rw [ihx, ihy]), bind_pure_comp_eq_map := λ α β f x, free_group.induction_on x (by rw [one_bind, map_one]) (λ x, by rw [pure_bind, map_pure]) (λ x ih, by rw [inv_bind, map_inv, ih]) (λ x y ihx ihy, by rw [mul_bind, map_mul, ihx, ihy]) } end category section reduce variable [decidable_eq α] /-- The maximal reduction of a word. It is computable iff `α` has decidable equality. -/ def reduce (L : list (α × bool)) : list (α × bool) := list.rec_on L [] $ λ hd1 tl1 ih, list.cases_on ih [hd1] $ λ hd2 tl2, if hd1.1 = hd2.1 ∧ hd1.2 = bnot hd2.2 then tl2 else hd1 :: hd2 :: tl2 @[simp] lemma reduce.cons (x) : reduce (x :: L) = list.cases_on (reduce L) [x] (λ hd tl, if x.1 = hd.1 ∧ x.2 = bnot hd.2 then tl else x :: hd :: tl) := rfl /-- The first theorem that characterises the function `reduce`: a word reduces to its maximal reduction. -/ theorem reduce.red : red L (reduce L) := begin induction L with hd1 tl1 ih, case list.nil { constructor }, case list.cons { dsimp, revert ih, generalize htl : reduce tl1 = TL, intro ih, cases TL with hd2 tl2, case list.nil { exact red.cons_cons ih }, case list.cons { dsimp, by_cases h : hd1.fst = hd2.fst ∧ hd1.snd = bnot (hd2.snd), { rw [if_pos h], transitivity, { exact red.cons_cons ih }, { cases hd1, cases hd2, cases h, dsimp at *, subst_vars, exact red.step.cons_bnot_rev.to_red } }, { rw [if_neg h], exact red.cons_cons ih } } } end theorem reduce.not {p : Prop} : ∀ {L₁ L₂ L₃ : list (α × bool)} {x b}, reduce L₁ = L₂ ++ (x, b) :: (x, bnot b) :: L₃ → p | [] L2 L3 _ _ := λ h, by cases L2; injections | ((x,b)::L1) L2 L3 x' b' := begin dsimp, cases r : reduce L1, { dsimp, intro h, have := congr_arg list.length h, simp [-add_comm] at this, exact absurd this dec_trivial }, cases hd with y c, by_cases x = y ∧ b = bnot c; simp [h]; intro H, { rw H at r, exact @reduce.not L1 ((y,c)::L2) L3 x' b' r }, rcases L2 with _|⟨a, L2⟩, { injections, subst_vars, simp at h, cc }, { refine @reduce.not L1 L2 L3 x' b' _, injection H with _ H, rw [r, H], refl } end /-- The second theorem that characterises the function `reduce`: the maximal reduction of a word only reduces to itself. -/ theorem reduce.min (H : red (reduce L₁) L₂) : reduce L₁ = L₂ := begin induction H with L1 L' L2 H1 H2 ih, { refl }, { cases H1 with L4 L5 x b, exact reduce.not H2 } end /-- `reduce` is idempotent, i.e. the maximal reduction of the maximal reduction of a word is the maximal reduction of the word. -/ @[simp] theorem reduce.idem : reduce (reduce L) = reduce L := eq.symm $ reduce.min reduce.red theorem reduce.step.eq (H : red.step L₁ L₂) : reduce L₁ = reduce L₂ := let ⟨L₃, HR13, HR23⟩ := red.church_rosser reduce.red (reduce.red.head H) in (reduce.min HR13).trans (reduce.min HR23).symm /-- If a word reduces to another word, then they have a common maximal reduction. -/ theorem reduce.eq_of_red (H : red L₁ L₂) : reduce L₁ = reduce L₂ := let ⟨L₃, HR13, HR23⟩ := red.church_rosser reduce.red (red.trans H reduce.red) in (reduce.min HR13).trans (reduce.min HR23).symm alias reduce.eq_of_red ← red.reduce_eq lemma red.reduce_right (h : red L₁ L₂) : red L₁ (reduce L₂) := reduce.eq_of_red h ▸ reduce.red lemma red.reduce_left (h : red L₁ L₂) : red L₂ (reduce L₁) := (reduce.eq_of_red h).symm ▸ reduce.red /-- If two words correspond to the same element in the free group, then they have a common maximal reduction. This is the proof that the function that sends an element of the free group to its maximal reduction is well-defined. -/ theorem reduce.sound (H : mk L₁ = mk L₂) : reduce L₁ = reduce L₂ := let ⟨L₃, H13, H23⟩ := red.exact.1 H in (reduce.eq_of_red H13).trans (reduce.eq_of_red H23).symm /-- If two words have a common maximal reduction, then they correspond to the same element in the free group. -/ theorem reduce.exact (H : reduce L₁ = reduce L₂) : mk L₁ = mk L₂ := red.exact.2 ⟨reduce L₂, H ▸ reduce.red, reduce.red⟩ /-- A word and its maximal reduction correspond to the same element of the free group. -/ theorem reduce.self : mk (reduce L) = mk L := reduce.exact reduce.idem /-- If words `w₁ w₂` are such that `w₁` reduces to `w₂`, then `w₂` reduces to the maximal reduction of `w₁`. -/ theorem reduce.rev (H : red L₁ L₂) : red L₂ (reduce L₁) := (reduce.eq_of_red H).symm ▸ reduce.red /-- The function that sends an element of the free group to its maximal reduction. -/ def to_word : free_group α → list (α × bool) := quot.lift reduce $ λ L₁ L₂ H, reduce.step.eq H lemma mk_to_word : ∀{x : free_group α}, mk (to_word x) = x := by rintros ⟨L⟩; exact reduce.self lemma to_word_injective : function.injective (to_word : free_group α → list (α × bool)) := by rintros ⟨L₁⟩ ⟨L₂⟩; exact reduce.exact @[simp] lemma to_word_inj {x y : free_group α} : to_word x = to_word y ↔ x = y := to_word_injective.eq_iff @[simp] lemma to_word_mk : (mk L₁).to_word = reduce L₁ := rfl @[simp] lemma reduce_to_word : ∀ (x : free_group α), reduce (to_word x) = to_word x := by { rintro ⟨L⟩, exact reduce.idem } @[simp] lemma to_word_one : (1 : free_group α).to_word = [] := rfl @[simp] lemma to_word_eq_nil_iff {x : free_group α} : (x.to_word = []) ↔ (x = 1) := to_word_injective.eq_iff' to_word_one lemma reduce_inv_rev {w : list (α × bool)} : reduce (inv_rev w) = inv_rev (reduce w) := begin apply reduce.min, rw [← red_inv_rev_iff, inv_rev_inv_rev], apply red.reduce_left, have : red (inv_rev (inv_rev w)) (inv_rev (reduce (inv_rev w))) := reduce.red.inv_rev, rwa inv_rev_inv_rev at this end lemma to_word_inv {x : free_group α} : (x⁻¹).to_word = inv_rev x.to_word := begin rcases x with ⟨L⟩, rw [quot_mk_eq_mk, inv_mk, to_word_mk, to_word_mk, reduce_inv_rev] end /-- Constructive Church-Rosser theorem (compare `church_rosser`). -/ def reduce.church_rosser (H12 : red L₁ L₂) (H13 : red L₁ L₃) : { L₄ // red L₂ L₄ ∧ red L₃ L₄ } := ⟨reduce L₁, reduce.rev H12, reduce.rev H13⟩ instance : decidable_eq (free_group α) := to_word_injective.decidable_eq instance red.decidable_rel : decidable_rel (@red α) | [] [] := is_true red.refl | [] (hd2::tl2) := is_false $ λ H, list.no_confusion (red.nil_iff.1 H) | ((x,b)::tl) [] := match red.decidable_rel tl [(x, bnot b)] with | is_true H := is_true $ red.trans (red.cons_cons H) $ (@red.step.bnot _ [] [] _ _).to_red | is_false H := is_false $ λ H2, H $ red.cons_nil_iff_singleton.1 H2 end | ((x1,b1)::tl1) ((x2,b2)::tl2) := if h : (x1, b1) = (x2, b2) then match red.decidable_rel tl1 tl2 with | is_true H := is_true $ h ▸ red.cons_cons H | is_false H := is_false $ λ H2, H $ h ▸ (red.cons_cons_iff _).1 $ H2 end else match red.decidable_rel tl1 ((x1,bnot b1)::(x2,b2)::tl2) with | is_true H := is_true $ (red.cons_cons H).tail red.step.cons_bnot | is_false H := is_false $ λ H2, H $ red.inv_of_red_of_ne h H2 end /-- A list containing every word that `w₁` reduces to. -/ def red.enum (L₁ : list (α × bool)) : list (list (α × bool)) := list.filter (λ L₂, red L₁ L₂) (list.sublists L₁) theorem red.enum.sound (H : L₂ ∈ red.enum L₁) : red L₁ L₂ := list.of_mem_filter H theorem red.enum.complete (H : red L₁ L₂) : L₂ ∈ red.enum L₁ := list.mem_filter_of_mem (list.mem_sublists.2 $ red.sublist H) H instance : fintype { L₂ // red L₁ L₂ } := fintype.subtype (list.to_finset $ red.enum L₁) $ λ L₂, ⟨λ H, red.enum.sound $ list.mem_to_finset.1 H, λ H, list.mem_to_finset.2 $ red.enum.complete H⟩ end reduce section metric variable [decidable_eq α] /-- The length of reduced words provides a norm on a free group. --/ def norm (x : free_group α) : ℕ := x.to_word.length @[simp] lemma norm_inv_eq {x : free_group α} : norm x⁻¹ = norm x := by simp only [norm, to_word_inv, inv_rev_length] @[simp] lemma norm_eq_zero {x : free_group α} : norm x = 0 ↔ x = 1 := by simp only [norm, list.length_eq_zero, to_word_eq_nil_iff] @[simp] lemma norm_one : norm (1 : free_group α) = 0 := rfl theorem norm_mk_le : norm (mk L₁) ≤ L₁.length := reduce.red.length_le lemma norm_mul_le (x y : free_group α) : norm (x * y) ≤ norm x + norm y := calc norm (x * y) = norm (mk (x.to_word ++ y.to_word)) : by rw [← mul_mk, mk_to_word, mk_to_word] ... ≤ (x.to_word ++ y.to_word).length : norm_mk_le ... = norm x + norm y : list.length_append _ _ end metric end free_group
10aae618931ed9b90c6a5d0e86dd6d55be8990ff
94e33a31faa76775069b071adea97e86e218a8ee
/src/category_theory/limits/shapes/finite_products.lean
0e6f79c7a08c2b9eaa069ea978bbabf722485056
[ "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
3,484
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.shapes.binary_products import category_theory.limits.shapes.finite_limits import category_theory.limits.shapes.products import category_theory.limits.shapes.terminal /-! # Categories with finite (co)products Typeclasses representing categories with (co)products over finite indexing types. -/ universes w v u open category_theory open_locale classical namespace category_theory.limits variables (C : Type u) [category.{v} C] /-- A category has finite products if there is a chosen limit for every diagram with shape `discrete J`, where we have `[fintype J]`. -/ -- We can't simply make this an abbreviation, as we do with other `has_Xs` limits typeclasses, -- because of https://github.com/leanprover-community/lean/issues/429 class has_finite_products : Prop := (out (J : Type) [fintype J] : has_limits_of_shape (discrete J) C) instance has_limits_of_shape_discrete (J : Type) [fintype J] [has_finite_products C] : has_limits_of_shape (discrete J) C := by { haveI := @has_finite_products.out C _ _ J, apply_instance } /-- If `C` has finite limits then it has finite products. -/ @[priority 10] instance has_finite_products_of_has_finite_limits [has_finite_limits C] : has_finite_products C := ⟨λ J 𝒥, by { resetI, apply_instance }⟩ instance has_fintype_products [has_finite_products C] (ι : Type w) [fintype ι] : has_limits_of_shape (discrete ι) C := has_limits_of_shape_of_equivalence (discrete.equivalence ((show ulift.{0} (fin (fintype.card ι)) ≃ fin (fintype.card ι), by tidy).trans (fintype.equiv_fin ι).symm)) /-- We can now write this for powers. -/ noncomputable example [has_finite_products C] (X : C) : C := ∏ (λ (i : fin 5), X) /-- If a category has all products then in particular it has finite products. -/ lemma has_finite_products_of_has_products [has_products.{w} C] : has_finite_products C := ⟨λ J _, has_limits_of_shape_of_equivalence (discrete.equivalence (equiv.ulift.{w}))⟩ /-- A category has finite coproducts if there is a chosen colimit for every diagram with shape `discrete J`, where we have `[fintype J]`. -/ class has_finite_coproducts : Prop := (out (J : Type) [fintype J] : has_colimits_of_shape (discrete J) C) attribute [class] has_finite_coproducts instance has_colimits_of_shape_discrete (J : Type) [fintype J] [has_finite_coproducts C] : has_colimits_of_shape (discrete J) C := by { haveI := @has_finite_coproducts.out C _ _ J, apply_instance } /-- If `C` has finite colimits then it has finite coproducts. -/ @[priority 10] instance has_finite_coproducts_of_has_finite_colimits [has_finite_colimits C] : has_finite_coproducts C := ⟨λ J 𝒥, by { resetI, apply_instance }⟩ instance has_fintype_coproducts [has_finite_coproducts C] (ι : Type w) [fintype ι] : has_colimits_of_shape (discrete ι) C := has_colimits_of_shape_of_equivalence (discrete.equivalence ((show ulift.{0} (fin (fintype.card ι)) ≃ fin (fintype.card ι), by tidy).trans (fintype.equiv_fin ι).symm)) /-- If a category has all coproducts then in particular it has finite coproducts. -/ lemma has_finite_coproducts_of_has_coproducts [has_coproducts.{w} C] : has_finite_coproducts C := ⟨λ J _, has_colimits_of_shape_of_equivalence (discrete.equivalence (equiv.ulift.{w}))⟩ end category_theory.limits
ca3257ebebe1f83916111b35d7b93b52f7e216f9
83c8119e3298c0bfc53fc195c41a6afb63d01513
/tests/lean/run/conv_tac1.lean
ab9b4429090b5e3827ef2405513adab0486e157c
[ "Apache-2.0" ]
permissive
anfelor/lean
584b91c4e87a6d95f7630c2a93fb082a87319ed0
31cfc2b6bf7d674f3d0f73848b842c9c9869c9f1
refs/heads/master
1,610,067,141,310
1,585,992,232,000
1,585,992,232,000
251,683,543
0
0
Apache-2.0
1,585,676,570,000
1,585,676,569,000
null
UTF-8
Lean
false
false
3,509
lean
local attribute [simp] add_comm add_left_comm example (a b : nat) : (λ x, a + x) 0 = b + 1 + a := begin conv in (_ + 1) { change nat.succ b }, guard_target (λ x, a + x) 0 = nat.succ b + a, admit end def Div : nat → nat → nat | x y := if h : 0 < y ∧ y ≤ x then have x - y < x, from sorry, Div (x - y) y + 1 else 0 example (x y : nat) : 0 < y → y ≤ x → Div x y = Div (x - y) y + 1 := begin intros h1 h2, -- Use conv to focus on the lhs conv { to_lhs, simp [Div] {single_pass := tt}, simp [h1, h2] }, guard_target 1 + Div (x - y) y = Div (x - y) y + 1, simp end example (x y : nat) (f : nat → nat) (h : f (0 + x + y) = 0 + y) : f (x + y) = 0 + y := begin -- use conv to rewrite subterm of a hypothesis conv at h in (0 + _) { simp }, assumption end example (x y : nat) (f : nat → nat) (h : f (0 + x + y) = 0 + y) : f (x + y) = 0 + y := begin -- use conv to rewrite subterm of a hypothesis conv at h in (0 + x) { simp }, assumption end example (x y : nat) (f : nat → nat) (h : f (0 + x + y) = 0 + y) : f (x + y) = 0 + y := begin -- use congr primitive to find term to be modified conv at h { guard_lhs f (0 + x + y) = 0 + y, congr, { guard_lhs f (0 + x + y), congr, congr, simp }, { guard_lhs 0 + y } }, assumption end example (x y : nat) (f : nat → nat) (h : f (0 + x + y) = 0 + y) : f (x + y) = 0 + y := begin -- use congr primitive to find term to be modified conv at h { guard_lhs f (0 + x + y) = 0 + y, to_lhs, guard_lhs f (0 + x + y), congr, guard_lhs 0 + x + y, congr, simp, }, assumption end example (x y : nat) (f : nat → nat) (h : f (0 + x + y) = 0 + y) : f (x + y) = 0 + y := begin -- use conv to rewrite subterm of a hypothesis conv at h in (0 + _) { rw [zero_add] }, assumption end example (x y : nat) (f : nat → nat) (h : f (0 + x + y) = 0 + y) : f (0 + x + y) = y := begin -- use conv to rewrite rhs a hypothesis conv at h { to_rhs, rw [zero_add] }, assumption end example (x : nat) (f : nat → nat) (h₁ : x = 0) (h₂ : ∀ x, f x = x + x) : f x = x := begin conv { to_rhs, rw [h₁, <- add_zero 0, <- h₁], }, exact h₂ x end lemma addz (x : nat) : x + 0 = x := rfl example (x : nat) (g : nat → nat) (f : nat → (nat → nat) → nat) (h : f (x + 0) (λ x, g x) = x) : f x g = x := begin conv at h {dsimp [addz] {eta := ff}}, conv at h {dsimp}, exact h, end example (x : nat) (g : nat → nat) (f : nat → (nat → nat) → nat) (h : f (x + 0) (λ x, g x) = x) : f x g = x := begin conv at h {dsimp [addz] {eta := ff}, guard_lhs f x (λ x, g x) = x, dsimp, guard_lhs f x g = x}, exact h, end def f (x y : nat) : nat := x + y + 1 example (x y : nat) : f x y + f x x + f y y = x + y + 1 + y + y + 1 + f x x := begin conv { -- execute `rw [f]` for 1st and 3rd occurrences of f-applications for (f _ _) [1, 3] { rw [f] }, guard_lhs (x + y + 1) + f x x + (y + y + 1) = x + y + 1 + y + y + 1 + f x x, simp } end example (x : nat) : f x x + f x x + f x x = f x x + x + x + x + x + 1 + 1 := begin conv { -- execute `rw [f]` for 1st and 3rd occurrences of f-applications for (f _ _) [1, 3] { rw [f] }, guard_lhs (x + x + 1) + f x x + (x + x + 1) = f x x + x + x + x + x + 1 + 1, simp } end example (x : nat) : f x x + f x x = f x x + x + x + 1 := begin conv in (f _ _) { rw [f] }, guard_target (x + x + 1) + f x x = f x x + x + x + 1, simp end
288c94f2fe7caa512a8c96f296651b3655f2f655
5c5878e769950eabe897ad08485b3ba1a619cea9
/src/categories/universal/cones.lean
5f8220a9a5ce0c2fb49f46722b1d60ceaed2ee0f
[ "Apache-2.0" ]
permissive
semorrison/lean-category-theory-pr
39dc2077fcb41b438e61be1685e4cbca298767ed
7adc8d91835e883db0fe75aa33661bc1480dbe55
refs/heads/master
1,583,748,682,010
1,535,111,040,000
1,535,111,040,000
128,731,071
1
2
Apache-2.0
1,528,069,880,000
1,523,258,452,000
Lean
UTF-8
Lean
false
false
7,185
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_theory.functor import .initial open category_theory open category_theory.initial namespace category_theory.universal universes u v variables {J : Type v} [small_category J] variables {C : Type u} [𝒞 : category.{u v} C] include 𝒞 structure Cone (F : J ↝ C) : Type (max u v) := (cone_point : C) (cone_maps : Π j : J, cone_point ⟶ (F j)) (commutativity : Π {j k : J}, Π f : j ⟶ k, (cone_maps j) ≫ (F.map f) = cone_maps k . obviously) restate_axiom Cone.commutativity attribute [simp,ematch] Cone.commutativity_lemma variable {F : J ↝ C} structure ConeMorphism (X Y : Cone F) : Type v := (cone_morphism : X.cone_point ⟶ Y.cone_point) (commutativity : Π j : J, cone_morphism ≫ (Y.cone_maps j) = (X.cone_maps j) . obviously) restate_axiom ConeMorphism.commutativity attribute [simp,ematch] ConeMorphism.commutativity_lemma namespace ConeMorphism @[simp,ematch] def commutativity_lemma_assoc {X Y : Cone F} (c : ConeMorphism X Y) (j : J) {Z : C} (z : (F j) ⟶ Z): c.cone_morphism ≫ Y.cone_maps j ≫ z = X.cone_maps j ≫ z := begin /- obviously' say: -/ rw ← category.assoc, simp, end @[extensionality] lemma ext {X Y : Cone F} {f g : ConeMorphism X Y} (w : f.cone_morphism = g.cone_morphism) : f = g := begin /- obviously' say: -/ induction f, induction g, dsimp at w, induction w, refl, end end ConeMorphism instance Cones (F : J ↝ C) : category.{(max u v) v} (Cone F) := { hom := λ X Y, ConeMorphism X Y, comp := λ X Y Z f g, { cone_morphism := f.cone_morphism ≫ g.cone_morphism, commutativity := begin /- `obviously'` says: -/ intros, simp end }, id := λ X, { cone_morphism := 𝟙 X.cone_point, commutativity := begin /- `obviously'` says: -/ intros, simp end }, id_comp := begin /- `obviously'` says: -/ intros, ext, dsimp, simp end, comp_id := begin /- `obviously'` says: -/ intros, ext, dsimp, simp end, assoc := begin /- `obviously'` says: -/ intros, ext, dsimp, simp end } -- TODO rename or namespace? @[simp] lemma Cones.identity.cone_morphism {F : J ↝ C} (c : Cone F) : (𝟙 c : ConeMorphism c c).cone_morphism = 𝟙 (c.cone_point) := rfl @[simp] lemma Cones.compose.cone_morphism {F : J ↝ C} {c d e : Cone F} (f : c ⟶ d) (g : d ⟶ e) : ((f ≫ g) : ConeMorphism c e).cone_morphism = (f : ConeMorphism c d).cone_morphism ≫ (g : ConeMorphism d e).cone_morphism := rfl section variables {D : Type u} [𝒟 : category.{u v} D] include 𝒟 def Cones_functoriality (F : J ↝ C) (G : C ↝ D) : (Cone F) ↝ (Cone (F ⋙ G)) := { obj := λ X, { cone_point := G X.cone_point, cone_maps := λ j, G.map (X.cone_maps j), commutativity := begin /- `obviously'` says: -/ intros, simp, erw [←functor.map_comp_lemma, Cone.commutativity_lemma] end }, map := λ X Y f, { cone_morphism := G.map f.cone_morphism, commutativity := begin /- `obviously'` says: -/ intros, dsimp, erw [←functor.map_comp_lemma, ConeMorphism.commutativity_lemma] end }, map_id := begin /- `obviously'` says: -/ intros, ext, dsimp, simp end, map_comp := begin /- `obviously'` says: -/ intros, ext, dsimp, simp end } end structure Cocone (F : J ↝ C) := (cocone_point : C) (cocone_maps : Π j : J, (F j) ⟶ cocone_point) (commutativity : Π {j k : J}, Π f : j ⟶ k, (F.map f) ≫ (cocone_maps k) = cocone_maps j . obviously) restate_axiom Cocone.commutativity attribute [simp,ematch] Cocone.commutativity_lemma structure CoconeMorphism (X Y : Cocone F) := (cocone_morphism : X.cocone_point ⟶ Y.cocone_point) (commutativity : Π j : J, (X.cocone_maps j) ≫ cocone_morphism = (Y.cocone_maps j) . obviously) restate_axiom CoconeMorphism.commutativity attribute [simp,ematch] CoconeMorphism.commutativity_lemma namespace CoconeMorphism @[simp,ematch] def commutativity_lemma_assoc {X Y : Cocone F} (c : CoconeMorphism X Y) (j : J) {Z : C} (z : Y.cocone_point ⟶ Z): (X.cocone_maps j) ≫ c.cocone_morphism ≫ z = (Y.cocone_maps j) ≫ z := begin -- `obviously'` says: erw [←category.assoc_lemma, CoconeMorphism.commutativity_lemma] end @[extensionality] lemma ext {X Y : Cocone F} {f g : CoconeMorphism X Y} (w : f.cocone_morphism = g.cocone_morphism) : f = g := begin induction f, induction g, -- `obviously'` says: dsimp at *, induction w, refl, end end CoconeMorphism instance Cocones (F : J ↝ C) : category.{(max u v) v} (Cocone F) := { hom := λ X Y, CoconeMorphism X Y, comp := λ X Y Z f g, { cocone_morphism := f.cocone_morphism ≫ g.cocone_morphism, commutativity := begin /- `obviously'` says: -/ intros, simp end }, id := λ X, { cocone_morphism := 𝟙 X.cocone_point, commutativity := begin /- `obviously'` says: -/ intros, simp end }, id_comp := begin /- `obviously'` says: -/ intros, ext, dsimp, simp end, comp_id := begin /- `obviously'` says: -/ intros, ext, dsimp, simp end, assoc := begin /- `obviously'` says: -/ intros, ext, dsimp, simp end } -- TODO rename or namespace? @[simp] lemma Cocones.identity.cone_morphism {F : J ↝ C} (c : Cocone F) : (𝟙 c : CoconeMorphism c c).cocone_morphism = 𝟙 (c.cocone_point) := rfl @[simp] lemma Cocones.compose.cone_morphism {F : J ↝ C} {c d e : Cocone F} (f : c ⟶ d) (g : d ⟶ e) : ((f ≫ g) : CoconeMorphism c e).cocone_morphism = (f : CoconeMorphism c d).cocone_morphism ≫ (g : CoconeMorphism d e).cocone_morphism := rfl section variables {D : Type u} [𝒟 : category.{u v} D] include 𝒟 def Cocones_functoriality (F : J ↝ C) (G : C ↝ D) : (Cocone F) ↝ (Cocone (F ⋙ G)) := { obj := λ X, { cocone_point := G X.cocone_point, cocone_maps := λ j, G.map (X.cocone_maps j), commutativity := begin /- `obviously'` says: -/ intros, simp, erw [←functor.map_comp_lemma, Cocone.commutativity_lemma] end }, map := λ X Y f, { cocone_morphism := G.map f.cocone_morphism, commutativity := begin /- `obviously'` says: -/ intros, dsimp, erw [←functor.map_comp_lemma, CoconeMorphism.commutativity_lemma] end }, map_id := begin /- `obviously'` says -/ intros, ext, dsimp, simp end, map_comp := begin /- `obviously'` says -/ intros, ext, dsimp, simp end } end def LimitCone (F : J ↝ C) := terminal_object (Cone F) def ColimitCocone (F : J ↝ C) := initial_object (Cocone F) end category_theory.universal namespace category_theory.functor universes u v variables {J : Type v} [small_category J] variables {C : Type u} [category.{u v} C] {D : Type u} [category.{u v} D] variable {F : J ↝ C} open category_theory.universal def on_cone (G : C ↝ D) (c : Cone F) : Cone (F ⋙ G) := (Cones_functoriality F G) c def on_cocone (G : C ↝ D) (c : Cocone F) : Cocone (F ⋙ G) := (Cocones_functoriality F G) c end category_theory.functor
962e7b6752a467cfd1b96ec8838b7feaeb75949f
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/category/Quiv.lean
423cb7d97b5a0908199be2f13cb450afa51dc731
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
3,178
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 category_theory.adjunction.basic import category_theory.category.Cat import category_theory.path_category /-! # The category of quivers The category of (bundled) quivers, and the free/forgetful adjunction between `Cat` and `Quiv`. -/ universes v u namespace category_theory /-- Category of quivers. -/ @[nolint check_univs] -- intended to be used with explicit universe parameters def Quiv := bundled quiver.{(v+1) u} namespace Quiv instance : has_coe_to_sort Quiv (Type u) := { coe := bundled.α } instance str (C : Quiv.{v u}) : quiver.{(v+1) u} C := C.str /-- Construct a bundled `Quiv` from the underlying type and the typeclass. -/ def of (C : Type u) [quiver.{v+1} C] : Quiv.{v u} := bundled.of C instance : inhabited Quiv := ⟨Quiv.of (quiver.empty pempty)⟩ /-- Category structure on `Quiv` -/ instance category : large_category.{max v u} Quiv.{v u} := { hom := λ C D, prefunctor C D, id := λ C, prefunctor.id C, comp := λ C D E F G, prefunctor.comp F G, id_comp' := λ C D F, by cases F; refl, comp_id' := λ C D F, by cases F; refl, assoc' := by intros; refl } /-- The forgetful functor from categories to quivers. -/ @[simps] def forget : Cat.{v u} ⥤ Quiv.{v u} := { obj := λ C, Quiv.of C, map := λ C D F, F.to_prefunctor, } end Quiv namespace Cat /-- The functor sending each quiver to its path category. -/ @[simps] def free : Quiv.{v u} ⥤ Cat.{(max u v) u} := { obj := λ V, Cat.of (paths V), map := λ V W F, { obj := λ X, F.obj X, map := λ X Y f, F.map_path f, map_comp' := λ X Y Z f g, F.map_path_comp f g, }, map_id' := λ V, by { change (show paths V ⥤ _, from _) = _, ext, apply eq_conj_eq_to_hom, refl }, map_comp' := λ U V W F G, by { change (show paths U ⥤ _, from _) = _, ext, apply eq_conj_eq_to_hom, refl } } end Cat namespace Quiv /-- Any prefunctor into a category lifts to a functor from the path category. -/ @[simps] def lift {V : Type u} [quiver.{v+1} V] {C : Type u} [category.{v} C] (F : prefunctor V C) : paths V ⥤ C := { obj := λ X, F.obj X, map := λ X Y f, compose_path (F.map_path f), } -- We might construct `of_lift_iso_self : paths.of ⋙ lift F ≅ F` -- (and then show that `lift F` is initial amongst such functors) -- but it would require lifting quite a bit of machinery to quivers! /-- The adjunction between forming the free category on a quiver, and forgetting a category to a quiver. -/ def adj : Cat.free ⊣ Quiv.forget := adjunction.mk_of_hom_equiv { hom_equiv := λ V C, { to_fun := λ F, paths.of.comp F.to_prefunctor, inv_fun := λ F, lift F, left_inv := λ F, by { ext, { erw (eq_conj_eq_to_hom _).symm, apply category.id_comp }, refl }, right_inv := begin rintro ⟨obj,map⟩, dsimp only [prefunctor.comp], congr, ext X Y f, exact category.id_comp _, end, }, hom_equiv_naturality_left_symm' := λ V W C f g, by { change (show paths V ⥤ _, from _) = _, ext, apply eq_conj_eq_to_hom, refl } } end Quiv end category_theory
fbbec63aea7e1a854e9e0a8ab0f9781875585b77
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/group_theory/specific_groups/quaternion.lean
0af5ef908c007dc28f6beab33661b43f1481ebff
[ "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
8,917
lean
/- Copyright (c) 2021 Julian Kuelshammer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Julian Kuelshammer -/ import data.zmod.basic import data.nat.basic import tactic.interval_cases import group_theory.specific_groups.dihedral import group_theory.specific_groups.cyclic /-! # Quaternion Groups > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We define the (generalised) quaternion groups `quaternion_group n` of order `4n`, also known as dicyclic groups, with elements `a i` and `xa i` for `i : zmod n`. The (generalised) quaternion groups can be defined by the presentation $\langle a, x | a^{2n} = 1, x^2 = a^n, x^{-1}ax=a^{-1}\rangle$. We write `a i` for $a^i$ and `xa i` for $x * a^i$. For `n=2` the quaternion group `quaternion_group 2` is isomorphic to the unit integral quaternions `(quaternion ℤ)ˣ`. ## Main definition `quaternion_group n`: The (generalised) quaternion group of order `4n`. ## Implementation notes This file is heavily based on `dihedral_group` by Shing Tak Lam. In mathematics, the name "quaternion group" is reserved for the cases `n ≥ 2`. Since it would be inconvenient to carry around this condition we define `quaternion_group` also for `n = 0` and `n = 1`. `quaternion_group 0` is isomorphic to the infinite dihedral group, while `quaternion_group 1` is isomorphic to a cyclic group of order `4`. ## References * https://en.wikipedia.org/wiki/Dicyclic_group * https://en.wikipedia.org/wiki/Quaternion_group ## TODO Show that `quaternion_group 2 ≃* (quaternion ℤ)ˣ`. -/ /-- The (generalised) quaternion group `quaternion_group n` of order `4n`. It can be defined by the presentation $\langle a, x | a^{2n} = 1, x^2 = a^n, x^{-1}ax=a^{-1}\rangle$. We write `a i` for $a^i$ and `xa i` for $x * a^i$. -/ @[derive decidable_eq] inductive quaternion_group (n : ℕ) : Type | a : zmod (2 * n) → quaternion_group | xa : zmod (2 * n) → quaternion_group namespace quaternion_group variables {n : ℕ} /-- Multiplication of the dihedral group. -/ private def mul : quaternion_group n → quaternion_group n → quaternion_group n | (a i) (a j) := a (i + j) | (a i) (xa j) := xa (j - i) | (xa i) (a j) := xa (i + j) | (xa i) (xa j) := a (n + j - i) /-- The identity `1` is given by `aⁱ`. -/ private def one : quaternion_group n := a 0 instance : inhabited (quaternion_group n) := ⟨one⟩ /-- The inverse of an element of the quaternion group. -/ private def inv : quaternion_group n → quaternion_group n | (a i) := a (-i) | (xa i) := xa (n + i) /-- The group structure on `quaternion_group n`. -/ instance : group (quaternion_group n) := { mul := mul, mul_assoc := begin rintros (i | i) (j | j) (k | k); simp only [mul]; abel, simp only [neg_mul, one_mul, int.cast_one, zsmul_eq_mul, int.cast_neg, add_right_inj], calc -(n : zmod (2 * n)) = 0 - n : by rw zero_sub ... = 2 * n - n : by { norm_cast, simp, } ... = n : by ring end, one := one, one_mul := begin rintros (i | i), { exact congr_arg a (zero_add i) }, { exact congr_arg xa (sub_zero i) }, end, mul_one := begin rintros (i | i), { exact congr_arg a (add_zero i) }, { exact congr_arg xa (add_zero i) }, end, inv := inv, mul_left_inv := begin rintros (i | i), { exact congr_arg a (neg_add_self i) }, { exact congr_arg a (sub_self (n + i)) }, end } variable {n} @[simp] lemma a_mul_a (i j : zmod (2 * n)) : a i * a j = a (i + j) := rfl @[simp] lemma a_mul_xa (i j : zmod (2 * n)) : a i * xa j = xa (j - i) := rfl @[simp] lemma xa_mul_a (i j : zmod (2 * n)) : xa i * a j = xa (i + j) := rfl @[simp] lemma xa_mul_xa (i j : zmod (2 * n)) : xa i * xa j = a (n + j - i) := rfl lemma one_def : (1 : quaternion_group n) = a 0 := rfl private def fintype_helper : (zmod (2 * n) ⊕ zmod (2 * n)) ≃ quaternion_group n := { inv_fun := λ i, match i with | (a j) := sum.inl j | (xa j) := sum.inr j end, to_fun := λ i, match i with | (sum.inl j) := a j | (sum.inr j) := xa j end, left_inv := by rintro (x | x); refl, right_inv := by rintro (x | x); refl } /-- The special case that more or less by definition `quaternion_group 0` is isomorphic to the infinite dihedral group. -/ def quaternion_group_zero_equiv_dihedral_group_zero : quaternion_group 0 ≃* dihedral_group 0 := { to_fun := λ i, quaternion_group.rec_on i dihedral_group.r dihedral_group.sr, inv_fun := λ i, match i with | (dihedral_group.r j) := a j | (dihedral_group.sr j) := xa j end, left_inv := by rintro (k | k); refl, right_inv := by rintro (k | k); refl, map_mul' := by { rintros (k | k) (l | l); { dsimp, simp, }, } } /-- If `0 < n`, then `quaternion_group n` is a finite group. -/ instance [ne_zero n] : fintype (quaternion_group n) := fintype.of_equiv _ fintype_helper instance : nontrivial (quaternion_group n) := ⟨⟨a 0, xa 0, dec_trivial⟩⟩ /-- If `0 < n`, then `quaternion_group n` has `4n` elements. -/ lemma card [ne_zero n] : fintype.card (quaternion_group n) = 4 * n := begin rw [← fintype.card_eq.mpr ⟨fintype_helper⟩, fintype.card_sum, zmod.card, two_mul], ring end @[simp] lemma a_one_pow (k : ℕ) : (a 1 : quaternion_group n) ^ k = a k := begin induction k with k IH, { rw nat.cast_zero, refl }, { rw [pow_succ, IH, a_mul_a], congr' 1, norm_cast, rw nat.one_add } end @[simp] lemma a_one_pow_n : (a 1 : quaternion_group n)^(2 * n) = 1 := begin rw [a_one_pow, one_def], congr' 1, exact zmod.nat_cast_self _ end @[simp] lemma xa_sq (i : zmod (2 * n)) : xa i ^ 2 = a n := begin simp [sq] end @[simp] lemma xa_pow_four (i : zmod (2 * n)) : xa i ^ 4 = 1 := begin simp only [pow_succ, sq, xa_mul_xa, xa_mul_a, add_sub_cancel, add_sub_assoc, add_sub_cancel', sub_self, add_zero], norm_cast, rw ← two_mul, simp [one_def], end /-- If `0 < n`, then `xa i` has order 4. -/ @[simp] lemma order_of_xa [ne_zero n] (i : zmod (2 * n)) : order_of (xa i) = 4 := begin change _ = 2^2, haveI : fact(nat.prime 2) := fact.mk (nat.prime_two), apply order_of_eq_prime_pow, { intro h, simp only [pow_one, xa_sq] at h, injection h with h', apply_fun zmod.val at h', apply_fun ( / n) at h', simp only [zmod.val_nat_cast, zmod.val_zero, nat.zero_div, nat.mod_mul_left_div_self, nat.div_self (ne_zero.pos n)] at h', norm_num at h' }, { norm_num } end /-- In the special case `n = 1`, `quaternion 1` is a cyclic group (of order `4`). -/ lemma quaternion_group_one_is_cyclic : is_cyclic (quaternion_group 1) := begin apply is_cyclic_of_order_of_eq_card, rw [card, mul_one], exact order_of_xa 0 end /-- If `0 < n`, then `a 1` has order `2 * n`. -/ @[simp] lemma order_of_a_one : order_of (a 1 : quaternion_group n) = 2 * n := begin casesI eq_zero_or_ne_zero n with hn hn, { subst hn, simp_rw [mul_zero, order_of_eq_zero_iff'], intros n h, rw [one_def, a_one_pow], apply mt a.inj, haveI : char_zero (zmod (2 * 0)) := zmod.char_zero, simpa using h.ne' }, apply (nat.le_of_dvd (ne_zero.pos _) (order_of_dvd_of_pow_eq_one (@a_one_pow_n n))).lt_or_eq.resolve_left, intro h, have h1 : (a 1 : quaternion_group n)^(order_of (a 1)) = 1 := pow_order_of_eq_one _, rw a_one_pow at h1, injection h1 with h2, rw [← zmod.val_eq_zero, zmod.val_nat_cast, nat.mod_eq_of_lt h] at h2, exact absurd h2.symm (order_of_pos _).ne end /-- If `0 < n`, then `a i` has order `(2 * n) / gcd (2 * n) i`. -/ lemma order_of_a [ne_zero n] (i : zmod (2 * n)) : order_of (a i) = (2 * n) / nat.gcd (2 * n) i.val := begin conv_lhs { rw ← zmod.nat_cast_zmod_val i }, rw [← a_one_pow, order_of_pow, order_of_a_one] end lemma exponent : monoid.exponent (quaternion_group n) = 2 * lcm n 2 := begin rw [←normalize_eq 2, ←lcm_mul_left, normalize_eq], norm_num, casesI eq_zero_or_ne_zero n with hn hn, { subst hn, simp only [lcm_zero_left, mul_zero], exact monoid.exponent_eq_zero_of_order_zero order_of_a_one }, apply nat.dvd_antisymm, { apply monoid.exponent_dvd_of_forall_pow_eq_one, rintro (m | m), { rw [←order_of_dvd_iff_pow_eq_one, order_of_a], refine nat.dvd_trans ⟨gcd (2 * n) m.val, _⟩ (dvd_lcm_left (2 * n) 4), exact (nat.div_mul_cancel (nat.gcd_dvd_left (2 * n) (m.val))).symm }, { rw [←order_of_dvd_iff_pow_eq_one, order_of_xa], exact dvd_lcm_right (2 * n) 4 } }, { apply lcm_dvd, { convert monoid.order_dvd_exponent (a 1), exact order_of_a_one.symm }, { convert monoid.order_dvd_exponent (xa 0), exact (order_of_xa 0).symm } } end end quaternion_group
3ff7a6913938f11200ee55825b6ab59bfd1ba9c8
f57749ca63d6416f807b770f67559503fdb21001
/library/algebra/ordered_field.lean
756f5afef9044c2b85ff82daa62632c094b08f97
[ "Apache-2.0" ]
permissive
aliassaf/lean
bd54e85bed07b1ff6f01396551867b2677cbc6ac
f9b069b6a50756588b309b3d716c447004203152
refs/heads/master
1,610,982,152,948
1,438,916,029,000
1,438,916,029,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
20,407
lean
/- Copyright (c) 2014 Robert Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Lewis -/ import algebra.ordered_ring algebra.field open eq eq.ops namespace algebra structure linear_ordered_field [class] (A : Type) extends linear_ordered_ring A, field A section linear_ordered_field variable {A : Type} variables [s : linear_ordered_field A] {a b c d : A} include s -- helpers for following theorem mul_zero_lt_mul_inv_of_pos (H : 0 < a) : a * 0 < a * (1 / a) := calc a * 0 = 0 : mul_zero ... < 1 : zero_lt_one ... = a * a⁻¹ : mul_inv_cancel (ne.symm (ne_of_lt H)) ... = a * (1 / a) : inv_eq_one_div theorem mul_zero_lt_mul_inv_of_neg (H : a < 0) : a * 0 < a * (1 / a) := calc a * 0 = 0 : mul_zero ... < 1 : zero_lt_one ... = a * a⁻¹ : mul_inv_cancel (ne_of_lt H) ... = a * (1 / a) : inv_eq_one_div theorem div_pos_of_pos (H : 0 < a) : 0 < 1 / a := lt_of_mul_lt_mul_left (mul_zero_lt_mul_inv_of_pos H) (le_of_lt H) theorem div_neg_of_neg (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) theorem le_mul_of_ge_one_right (Hb : b ≥ 0) (H : a ≥ 1) : b ≤ b * a := mul_one _ ▸ (mul_le_mul_of_nonneg_left H Hb) theorem lt_mul_of_gt_one_right (Hb : b > 0) (H : a > 1) : b < b * a := mul_one _ ▸ (mul_lt_mul_of_pos_left H Hb) theorem one_le_div_iff_le (Hb : b > 0) : 1 ≤ a / b ↔ b ≤ a := have Hb' : b ≠ 0, from ne.symm (ne_of_lt Hb), iff.intro (assume H : 1 ≤ a / b, calc b = b : refl ... ≤ b * (a / b) : le_mul_of_ge_one_right (le_of_lt Hb) H ... = a : mul_div_cancel' Hb') (assume H : b ≤ a, have Hbinv : 1 / b > 0, from div_pos_of_pos Hb, calc 1 = b * (1 / b) : mul_one_div_cancel Hb' ... ≤ a * (1 / b) : mul_le_mul_of_nonneg_right H (le_of_lt Hbinv) ... = a / b : div_eq_mul_one_div) theorem le_of_one_le_div (Hb : b > 0) (H : 1 ≤ a / b) : b ≤ a := (iff.mp (one_le_div_iff_le Hb)) H theorem one_le_div_of_le (Hb : b > 0) (H : b ≤ a) : 1 ≤ a / b := (iff.mpr (one_le_div_iff_le Hb)) H theorem one_lt_div_iff_lt (Hb : b > 0) : 1 < a / b ↔ b < a := have Hb' : b ≠ 0, from ne.symm (ne_of_lt Hb), iff.intro (assume H : 1 < a / b, calc b < b * (a / b) : lt_mul_of_gt_one_right Hb H ... = a : mul_div_cancel' Hb') (assume H : b < a, have Hbinv : 1 / b > 0, from div_pos_of_pos Hb, calc 1 = b * (1 / b) : mul_one_div_cancel Hb' ... < a * (1 / b) : mul_lt_mul_of_pos_right H Hbinv ... = a / b : div_eq_mul_one_div) theorem lt_of_one_lt_div (Hb : b > 0) (H : 1 < a / b) : b < a := (iff.mp (one_lt_div_iff_lt Hb)) H theorem one_lt_div_of_lt (Hb : b > 0) (H : b < a) : 1 < a / b := (iff.mpr (one_lt_div_iff_lt Hb)) H theorem exists_lt : ∃ x, x < a := have H : a - 1 < a, from add_lt_of_le_of_neg (le.refl _) zero_gt_neg_one, exists.intro _ H theorem exists_gt : ∃ x, x > a := have H : a + 1 > a, from lt_add_of_le_of_pos (le.refl _) zero_lt_one, exists.intro _ H -- the following theorems amount to four iffs, for <, ≤, ≥, >. theorem mul_le_of_le_div (Hc : 0 < c) (H : a ≤ b / c) : a * c ≤ b := div_mul_cancel (ne.symm (ne_of_lt Hc)) ▸ mul_le_mul_of_nonneg_right H (le_of_lt Hc) theorem le_div_of_mul_le (Hc : 0 < c) (H : a * c ≤ b) : a ≤ b / c := calc a = a * c * (1 / c) : mul_mul_div (ne.symm (ne_of_lt Hc)) ... ≤ b * (1 / c) : mul_le_mul_of_nonneg_right H (le_of_lt (div_pos_of_pos Hc)) ... = b / c : div_eq_mul_one_div theorem mul_lt_of_lt_div (Hc : 0 < c) (H : a < b / c) : a * c < b := div_mul_cancel (ne.symm (ne_of_lt Hc)) ▸ mul_lt_mul_of_pos_right H Hc theorem lt_div_of_mul_lt (Hc : 0 < c) (H : a * c < b) : a < b / c := calc a = a * c * (1 / c) : mul_mul_div (ne.symm (ne_of_lt Hc)) ... < b * (1 / c) : mul_lt_mul_of_pos_right H (div_pos_of_pos Hc) ... = b / c : div_eq_mul_one_div theorem mul_le_of_ge_div_neg (Hc : c < 0) (H : a ≥ b / c) : a * c ≤ b := div_mul_cancel (ne_of_lt Hc) ▸ mul_le_mul_of_nonpos_right H (le_of_lt Hc) theorem ge_div_of_mul_le_neg (Hc : c < 0) (H : a * c ≤ b) : a ≥ b / c := calc a = a * c * (1 / c) : mul_mul_div (ne_of_lt Hc) ... ≥ b * (1 / c) : mul_le_mul_of_nonpos_right H (le_of_lt (div_neg_of_neg Hc)) ... = b / c : div_eq_mul_one_div theorem mul_lt_of_gt_div_neg (Hc : c < 0) (H : a > b / c) : a * c < b := div_mul_cancel (ne_of_lt Hc) ▸ mul_lt_mul_of_neg_right H Hc theorem gt_div_of_mul_gt_neg (Hc : c < 0) (H : a * c < b) : a > b / c := calc a = a * c * (1 / c) : mul_mul_div (ne_of_lt Hc) ... > b * (1 / c) : mul_lt_mul_of_neg_right H (div_neg_of_neg Hc) ... = b / c : div_eq_mul_one_div ----- theorem div_le_of_le_mul (Hb : b > 0) (H : a ≤ b * c) : a / b ≤ c := calc a / b = a * (1 / b) : div_eq_mul_one_div ... ≤ (b * c) * (1 / b) : mul_le_mul_of_nonneg_right H (le_of_lt (div_pos_of_pos Hb)) ... = (b * c) / b : div_eq_mul_one_div ... = c : mul_div_cancel_left (ne.symm (ne_of_lt Hb)) theorem le_mul_of_div_le (Hc : c > 0) (H : a / c ≤ b) : a ≤ b * c := calc a = a / c * c : 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 theorem mul_sub_mul_div_mul_neg (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 : 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) : mul.comm theorem mul_sub_mul_div_mul_nonpos (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 : 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) : mul.comm theorem div_lt_div_of_mul_sub_mul_div_neg (Hc : c ≠ 0) (Hd : d ≠ 0) (H : (a * d - b * c) / (c * d) < 0) : a / c < b / d := assert H1 : (a * d - c * b) / (c * d) < 0, by rewrite [mul.comm c b]; exact H, assert H2 : a / c - b / d < 0, by rewrite [div_sub_div Hc Hd]; exact H1, assert H3 : a / c - b / d + b / d < 0 + b / d, from add_lt_add_right H2 _, begin rewrite [zero_add at H3, neg_add_cancel_right at H3], exact H3 end theorem div_le_div_of_mul_sub_mul_div_nonpos (Hc : c ≠ 0) (Hd : d ≠ 0) (H : (a * d - b * c) / (c * d) ≤ 0) : a / c ≤ b / d := assert H1 : (a * d - c * b) / (c * d) ≤ 0, by rewrite [mul.comm c b]; exact H, assert H2 : a / c - b / d ≤ 0, by rewrite [div_sub_div Hc Hd]; exact H1, assert H3 : a / c - b / d + b / d ≤ 0 + b / d, from add_le_add_right H2 _, begin rewrite [zero_add at H3, neg_add_cancel_right at H3], exact H3 end theorem pos_div_of_pos_of_pos (Ha : 0 < a) (Hb : 0 < b) : 0 < a / b := begin rewrite div_eq_mul_one_div, apply mul_pos, exact Ha, apply div_pos_of_pos, exact Hb end theorem nonneg_div_of_nonneg_of_pos (Ha : 0 ≤ a) (Hb : 0 < b) : 0 ≤ a / b := begin rewrite div_eq_mul_one_div, apply mul_nonneg, exact Ha, apply le_of_lt, apply div_pos_of_pos, exact Hb end theorem neg_div_of_neg_of_pos (Ha : a < 0) (Hb : 0 < b) : a / b < 0:= begin rewrite div_eq_mul_one_div, apply mul_neg_of_neg_of_pos, exact Ha, apply div_pos_of_pos, exact Hb end theorem nonpos_div_of_nonpos_of_pos (Ha : a ≤ 0) (Hb : 0 < b) : a / b ≤ 0 := begin rewrite div_eq_mul_one_div, apply mul_nonpos_of_nonpos_of_nonneg, exact Ha, apply le_of_lt, apply div_pos_of_pos, exact Hb end theorem neg_div_of_pos_of_neg (Ha : 0 < a) (Hb : b < 0) : a / b < 0 := begin rewrite div_eq_mul_one_div, apply mul_neg_of_pos_of_neg, exact Ha, apply div_neg_of_neg, exact Hb end theorem nonpos_div_of_nonneg_of_neg (Ha : 0 ≤ a) (Hb : b < 0) : a / b ≤ 0 := begin rewrite div_eq_mul_one_div, apply mul_nonpos_of_nonneg_of_nonpos, exact Ha, apply le_of_lt, apply div_neg_of_neg, exact Hb end theorem pos_div_of_neg_of_neg (Ha : a < 0) (Hb : b < 0) : 0 < a / b := begin rewrite div_eq_mul_one_div, apply mul_pos_of_neg_of_neg, exact Ha, apply div_neg_of_neg, exact Hb end theorem nonneg_div_of_nonpos_of_neg (Ha : a ≤ 0) (Hb : b < 0) : 0 ≤ a / b := begin rewrite div_eq_mul_one_div, apply mul_nonneg_of_nonpos_of_nonpos, exact Ha, apply le_of_lt, apply div_neg_of_neg, exact Hb end theorem div_lt_div_of_lt_of_pos (H : a < b) (Hc : 0 < c) : a / c < b / c := begin rewrite [{a/c}div_eq_mul_one_div, {b/c}div_eq_mul_one_div], exact mul_lt_mul_of_pos_right H (div_pos_of_pos Hc) end theorem div_le_div_of_le_of_pos (H : a ≤ b) (Hc : 0 < c) : a / c ≤ b / c := begin rewrite [{a/c}div_eq_mul_one_div, {b/c}div_eq_mul_one_div], exact mul_le_mul_of_nonneg_right H (le_of_lt (div_pos_of_pos Hc)) end theorem div_lt_div_of_lt_of_neg (H : b < a) (Hc : c < 0) : a / c < b / c := begin rewrite [{a/c}div_eq_mul_one_div, {b/c}div_eq_mul_one_div], exact mul_lt_mul_of_neg_right H (div_neg_of_neg Hc) end theorem div_le_div_of_le_of_neg (H : b ≤ a) (Hc : c < 0) : a / c ≤ b / c := begin rewrite [{a/c}div_eq_mul_one_div, {b/c}div_eq_mul_one_div], exact mul_le_mul_of_nonpos_right H (le_of_lt (div_neg_of_neg Hc)) end theorem two_pos : (1 : A) + 1 > 0 := add_pos zero_lt_one zero_lt_one theorem two_ne_zero : (1 : A) + 1 ≠ 0 := ne.symm (ne_of_lt two_pos) notation 2 := 1 + 1 theorem add_halves : a / 2 + a / 2 = a := calc a / 2 + a / 2 = (a + a) / 2 : by rewrite div_add_div_same ... = (a * 1 + a * 1) / 2 : by rewrite mul_one ... = (a * 2) / 2 : by rewrite left_distrib ... = a : by rewrite [@mul_div_cancel A _ _ _ two_ne_zero] theorem sub_self_div_two : a - a / 2 = a / 2 := by rewrite [-{a}add_halves at {1}, add_sub_cancel] theorem div_two_sub_self : a / 2 - a = - (a / 2) := by rewrite [-{a}add_halves at {2}, sub_add_eq_sub_sub, sub_self, zero_sub] theorem nonneg_le_nonneg_of_squares_le (Ha : a ≥ 0) (Hb : b ≥ 0) (H : a * a ≤ b * b) : a ≤ b := begin apply le_of_not_gt, intro Hab, let Hposa := lt_of_le_of_lt Hb Hab, let H' := calc b * b ≤ a * b : mul_le_mul_of_nonneg_right (le_of_lt Hab) Hb ... < a * a : mul_lt_mul_of_pos_left Hab Hposa, apply (not_le_of_gt H') H end theorem div_two : (a + a) / 2 = a := symm (iff.mpr (eq_div_iff_mul_eq (ne_of_gt (add_pos zero_lt_one zero_lt_one))) (by rewrite [left_distrib, *mul_one])) theorem two_ge_one : (2 : A) ≥ 1 := by rewrite -(add_zero 1) at {3}; apply add_le_add_left; apply zero_le_one theorem mul_le_mul_of_mul_div_le (H : a * (b / c) ≤ d) (Hc : c > 0) : b * a ≤ d * c := begin rewrite [-mul_div_assoc at H, mul.comm b], apply le_mul_of_div_le Hc H end theorem div_two_lt_of_pos (H : a > 0) : a / (1 + 1) < a := have Ha : a / (1 + 1) > 0, from pos_div_of_pos_of_pos H (add_pos zero_lt_one zero_lt_one), calc a / (1 + 1) < a / (1 + 1) + a / (1 + 1) : lt_add_of_pos_left Ha ... = a : add_halves theorem div_mul_le_div_mul_of_div_le_div_pos {e : A} (Hb : b ≠ 0) (Hd : d ≠ 0) (H : a / b ≤ c / d) (He : e > 0) : a / (b * e) ≤ c / (d * e) := begin rewrite [div_mul_eq_div_mul_one_div Hb (ne_of_gt He), div_mul_eq_div_mul_one_div Hd (ne_of_gt He)], apply mul_le_mul_of_nonneg_right H, apply le_of_lt, apply div_pos_of_pos He end theorem find_midpoint (H : a > b) : ∃ c : A, a > b + c ∧ c > 0 := exists.intro ((a - b) / (1 + 1)) (and.intro (assert H2 : a + a > (b + b) + (a - b), from calc a + a > b + a : add_lt_add_right H ... = b + a + b - b : add_sub_cancel ... = b + b + a - b : add.right_comm ... = (b + b) + (a - b) : add_sub, assert H3 : (a + a) / (1 + 1) > ((b + b) + (a - b)) / (1 + 1), from div_lt_div_of_lt_of_pos H2 two_pos, by rewrite [div_two at H3, -div_add_div_same at H3, div_two at H3]; exact H3) (pos_div_of_pos_of_pos (iff.mpr !sub_pos_iff_lt H) two_pos)) end linear_ordered_field structure discrete_linear_ordered_field [class] (A : Type) extends linear_ordered_field A, decidable_linear_ordered_comm_ring A := (inv_zero : inv zero = zero) section discrete_linear_ordered_field variable {A : Type} variables [s : discrete_linear_ordered_field A] {a b c : A} include s definition dec_eq_of_dec_lt : ∀ x y : A, decidable (x = y) := take x y, decidable.by_cases (assume H : x < y, decidable.inr (ne_of_lt H)) (assume H : ¬ x < y, decidable.by_cases (assume H' : y < x, decidable.inr (ne.symm (ne_of_lt H'))) (assume H' : ¬ y < x, decidable.inl (le.antisymm (le_of_not_gt H') (le_of_not_gt H)))) definition discrete_linear_ordered_field.to_discrete_field [trans-instance] [reducible] [coercion] : discrete_field A := ⦃ discrete_field, s, has_decidable_eq := dec_eq_of_dec_lt⦄ theorem pos_of_div_pos (H : 0 < 1 / a) : 0 < a := have H1 : 0 < 1 / (1 / a), from div_pos_of_pos H, have H2 : 1 / a ≠ 0, from (assume H3 : 1 / a = 0, have H4 : 1 / (1 / a) = 0, from H3⁻¹ ▸ div_zero, absurd H4 (ne.symm (ne_of_lt H1))), (div_div (ne_zero_of_one_div_ne_zero H2)) ▸ H1 theorem neg_of_div_neg (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 (one_div_neg_eq_neg_one_div Ha)⁻¹ ▸ H1, have H3 : 0 < -a, from pos_of_div_pos H2, neg_of_neg_pos H3 -- why is mul_le_mul under ordered_ring namespace? theorem le_of_div_le (H : 0 < a) (Hl : 1 / a ≤ 1 / b) : b ≤ a := have Hb : 0 < b, from pos_of_div_pos (calc 0 < 1 / a : div_pos_of_pos H ... ≤ 1 / b : Hl), have H' : 1 ≤ a / b, from (calc 1 = a / a : div_self (ne.symm (ne_of_lt H)) ... = a * (1 / a) : div_eq_mul_one_div ... ≤ a * (1 / b) : ordered_ring.mul_le_mul_of_nonneg_left Hl (le_of_lt H) ... = a / b : div_eq_mul_one_div ), le_of_one_le_div Hb H' theorem le_of_div_le_neg (H : b < 0) (Hl : 1 / a ≤ 1 / b) : b ≤ a := assert Ha : a ≠ 0, from ne_of_lt (neg_of_div_neg (calc 1 / a ≤ 1 / b : Hl ... < 0 : div_neg_of_neg H)), have H' : -b > 0, from neg_pos_of_neg H, have Hl' : - (1 / b) ≤ - (1 / a), from neg_le_neg Hl, have Hl'' : 1 / - b ≤ 1 / - a, from calc 1 / -b = - (1 / b) : by rewrite [one_div_neg_eq_neg_one_div (ne_of_lt H)] ... ≤ - (1 / a) : Hl' ... = 1 / -a : by rewrite [one_div_neg_eq_neg_one_div Ha], le_of_neg_le_neg (le_of_div_le H' Hl'') theorem lt_of_div_lt (H : 0 < a) (Hl : 1 / a < 1 / b) : b < a := have Hb : 0 < b, from pos_of_div_pos (calc 0 < 1 / a : div_pos_of_pos H ... < 1 / b : Hl), have H : 1 < a / b, from (calc 1 = a / a : div_self (ne.symm (ne_of_lt H)) ... = a * (1 / a) : div_eq_mul_one_div ... < a * (1 / b) : mul_lt_mul_of_pos_left Hl H ... = a / b : div_eq_mul_one_div), lt_of_one_lt_div Hb H theorem lt_of_div_lt_neg (H : b < 0) (Hl : 1 / a < 1 / b) : b < a := have H1 : b ≤ a, from le_of_div_le_neg H (le_of_lt Hl), have Hn : b ≠ a, from (assume Hn' : b = a, have Hl' : 1 / a = 1 / b, from Hn' ▸ refl _, absurd Hl' (ne_of_lt Hl)), lt_of_le_of_ne H1 Hn theorem div_lt_div_of_lt (Ha : 0 < a) (H : a < b) : 1 / b < 1 / a := lt_of_not_ge (assume H', absurd H (not_lt_of_ge (le_of_div_le Ha H'))) theorem div_le_div_of_le (Ha : 0 < a) (H : a ≤ b) : 1 / b ≤ 1 / a := le_of_not_gt (assume H', absurd H (not_le_of_gt (lt_of_div_lt Ha H'))) theorem div_lt_div_of_lt_neg (Hb : b < 0) (H : a < b) : 1 / b < 1 / a := lt_of_not_ge (assume H', absurd H (not_lt_of_ge (le_of_div_le_neg Hb H'))) theorem div_le_div_of_le_neg (Hb : b < 0) (H : a ≤ b) : 1 / b ≤ 1 / a := le_of_not_gt (assume H', absurd H (not_le_of_gt (lt_of_div_lt_neg Hb H'))) theorem one_lt_div (H1 : 0 < a) (H2 : a < 1) : 1 < 1 / a := one_div_one ▸ div_lt_div_of_lt H1 H2 theorem one_le_div (H1 : 0 < a) (H2 : a ≤ 1) : 1 ≤ 1 / a := one_div_one ▸ div_le_div_of_le H1 H2 theorem neg_one_lt_div_neg (H1 : a < 0) (H2 : -1 < a) : 1 / a < -1 := one_div_neg_one_eq_neg_one ▸ div_lt_div_of_lt_neg H1 H2 theorem neg_one_le_div_neg (H1 : a < 0) (H2 : -1 ≤ a) : 1 / a ≤ -1 := one_div_neg_one_eq_neg_one ▸ div_le_div_of_le_neg H1 H2 theorem div_lt_div_of_pos_of_lt_of_pos (Hb : 0 < b) (H : b < a) (Hc : 0 < c) : c / a < c / b := begin apply iff.mp (sub_neg_iff_lt _ _), rewrite [div_eq_mul_one_div, {c / b}div_eq_mul_one_div], rewrite -mul_sub_left_distrib, apply mul_neg_of_pos_of_neg, exact Hc, apply iff.mpr (sub_neg_iff_lt _ _), apply div_lt_div_of_lt, exact Hb, exact H end theorem div_mul_le_div_mul_of_div_le_div_pos' {d e : A} (H : a / b ≤ c / d) (He : e > 0) : a / (b * e) ≤ c / (d * e) := begin rewrite [2 div_mul_eq_div_mul_one_div'], apply mul_le_mul_of_nonneg_right H, apply le_of_lt, apply div_pos_of_pos He end theorem abs_one_div : abs (1 / a) = 1 / abs a := if H : a > 0 then by rewrite [abs_of_pos H, abs_of_pos (div_pos_of_pos H)] else (if H' : a < 0 then by rewrite [abs_of_neg H', abs_of_neg (div_neg_of_neg H'), -(one_div_neg_eq_neg_one_div (ne_of_lt H'))] else have Heq [visible] : a = 0, from eq_of_le_of_ge (le_of_not_gt H) (le_of_not_gt H'), by rewrite [Heq, div_zero, *abs_zero, div_zero]) theorem ge_sub_of_abs_sub_le_left (H : abs (a - b) ≤ c) : a ≥ b - c := if Hz : 0 ≤ a - b then (calc a ≥ b : (iff.mp !sub_nonneg_iff_le) Hz ... ≥ b - c : sub_le_of_nonneg _ _ (le.trans !abs_nonneg H)) else (have Habs : b - a ≤ c, by rewrite [abs_of_neg (lt_of_not_ge Hz) at H, neg_sub at H]; apply H, have Habs' : b ≤ c + a, from (iff.mpr !le_add_iff_sub_right_le) Habs, (iff.mp !le_add_iff_sub_left_le) Habs') theorem ge_sub_of_abs_sub_le_right (H : abs (a - b) ≤ c) : b ≥ a - c := ge_sub_of_abs_sub_le_left (!abs_sub ▸ H) theorem abs_sub_square : abs (a - b) * abs (a - b) = a * a + b * b - 2 * a * b := by rewrite [abs_mul_self, *mul_sub_left_distrib, *mul_sub_right_distrib, sub_add_eq_sub_sub, sub_neg_eq_add, *right_distrib, sub_add_eq_sub_sub, *one_mul, *add.assoc, {_ + b * b}add.comm, {_ + (b * b + _)}add.comm, mul.comm b a, *add.assoc] theorem abs_abs_sub_abs_le_abs_sub (a b : A) : abs (abs a - abs b) ≤ abs (a - b) := begin apply nonneg_le_nonneg_of_squares_le, repeat apply abs_nonneg, rewrite [*abs_sub_square, *abs_abs, *abs_mul_self], apply sub_le_sub_left, rewrite *mul.assoc, apply mul_le_mul_of_nonneg_left, rewrite -abs_mul, apply le_abs_self, apply le_of_lt, apply two_pos end end discrete_linear_ordered_field end algebra
f77e58973092dda548f51c2fa341401e6d21ffb2
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/run/e1.lean
1cb094254d1333c7f0e01e6b6d43f8ed77fbed45
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
324
lean
prelude definition Prop : Sort.{1} := Sort.{0} constant eq : forall {A : Type}, A → A → Prop constant N : Type constants a b c : N infix `=`:50 := eq check a = b constant f : Prop → N → N constant g : N → N → N precedence `+`:50 infixl + := f infixl + := g check a + b + c constant p : Prop check p + a + b + c
231609729c8c7f1788dd3c878116e9e634223129
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/analysis/subadditive.lean
0e8e549093dd37f5b867a52c26ca1ca7170e7c95
[ "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
4,724
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 -/ import topology.instances.real import order.filter.archimedean /-! # Convergence of subadditive sequences A subadditive sequence `u : ℕ → ℝ` is a sequence satisfying `u (m + n) ≤ u m + u n` for all `m, n`. We define this notion as `subadditive u`, and prove in `subadditive.tendsto_lim` that, if `u n / n` is bounded below, then it converges to a limit (that we denote by `subadditive.lim` for convenience). This result is known as Fekete's lemma in the literature. -/ noncomputable theory open set filter open_locale topological_space /-- A real-valued sequence is subadditive if it satisfies the inequality `u (m + n) ≤ u m + u n` for all `m, n`. -/ def subadditive (u : ℕ → ℝ) : Prop := ∀ m n, u (m + n) ≤ u m + u n namespace subadditive variables {u : ℕ → ℝ} (h : subadditive u) include h /-- The limit of a bounded-below subadditive sequence. The fact that the sequence indeed tends to this limit is given in `subadditive.tendsto_lim` -/ @[irreducible, nolint unused_arguments] protected def lim := Inf ((λ (n : ℕ), u n / n) '' (Ici 1)) lemma lim_le_div (hbdd : bdd_below (range (λ n, u n / n))) {n : ℕ} (hn : n ≠ 0) : h.lim ≤ u n / n := begin rw subadditive.lim, apply cInf_le _ _, { rcases hbdd with ⟨c, hc⟩, exact ⟨c, λ x hx, hc (image_subset_range _ _ hx)⟩ }, { apply mem_image_of_mem, exact zero_lt_iff.2 hn } end lemma apply_mul_add_le (k n r) : u (k * n + r) ≤ k * u n + u r := begin induction k with k IH, { simp only [nat.cast_zero, zero_mul, zero_add] }, calc u ((k+1) * n + r) = u (n + (k * n + r)) : by { congr' 1, ring } ... ≤ u n + u (k * n + r) : h _ _ ... ≤ u n + (k * u n + u r) : add_le_add_left IH _ ... = (k+1) * u n + u r : by ring end lemma eventually_div_lt_of_div_lt {L : ℝ} {n : ℕ} (hn : n ≠ 0) (hL : u n / n < L) : ∀ᶠ p in at_top, u p / p < L := begin have I : ∀ (i : ℕ), 0 < i → (i : ℝ) ≠ 0, { assume i hi, simp only [hi.ne', ne.def, nat.cast_eq_zero, not_false_iff] }, obtain ⟨w, nw, wL⟩ : ∃ w, u n / n < w ∧ w < L := exists_between hL, obtain ⟨x, hx⟩ : ∃ x, ∀ i < n, u i - i * w ≤ x, { obtain ⟨x, hx⟩ : bdd_above (↑(finset.image (λ i, u i - i * w) (finset.range n))) := finset.bdd_above _, refine ⟨x, λ i hi, _⟩, simp only [upper_bounds, mem_image, and_imp, forall_exists_index, mem_set_of_eq, forall_apply_eq_imp_iff₂, finset.mem_range, finset.mem_coe, finset.coe_image] at hx, exact hx _ hi }, have A : ∀ (p : ℕ), u p ≤ p * w + x, { assume p, let s := p / n, let r := p % n, have hp : p = s * n + r, by rw [mul_comm, nat.div_add_mod], calc u p = u (s * n + r) : by rw hp ... ≤ s * u n + u r : h.apply_mul_add_le _ _ _ ... = s * n * (u n / n) + u r : by { field_simp [I _ hn.bot_lt], ring } ... ≤ s * n * w + u r : add_le_add_right (mul_le_mul_of_nonneg_left nw.le (mul_nonneg (nat.cast_nonneg _) (nat.cast_nonneg _))) _ ... = (s * n + r) * w + (u r - r * w) : by ring ... = p * w + (u r - r * w) : by { rw hp, simp only [nat.cast_add, nat.cast_mul] } ... ≤ p * w + x : add_le_add_left (hx _ (nat.mod_lt _ hn.bot_lt)) _ }, have B : ∀ᶠ p in at_top, u p / p ≤ w + x / p, { refine eventually_at_top.2 ⟨1, λ p hp, _⟩, simp only [I p hp, ne.def, not_false_iff] with field_simps, refine div_le_div_of_le_of_nonneg _ (nat.cast_nonneg _), rw mul_comm, exact A _ }, have C : ∀ᶠ (p : ℕ) in at_top, w + x / p < L, { have : tendsto (λ (p : ℕ), w + x / p) at_top (𝓝 (w + 0)) := tendsto_const_nhds.add (tendsto_const_nhds.div_at_top tendsto_coe_nat_at_top_at_top), rw add_zero at this, exact (tendsto_order.1 this).2 _ wL }, filter_upwards [B, C], assume p hp h'p, exact hp.trans_lt h'p end /-- Fekete's lemma: a subadditive sequence which is bounded below converges. -/ theorem tendsto_lim (hbdd : bdd_below (range (λ n, u n / n))) : tendsto (λ n, u n / n) at_top (𝓝 h.lim) := begin refine tendsto_order.2 ⟨λ l hl, _, λ L hL, _⟩, { refine eventually_at_top.2 ⟨1, λ n hn, hl.trans_le (h.lim_le_div hbdd ((zero_lt_one.trans_le hn).ne'))⟩ }, { obtain ⟨n, npos, hn⟩ : ∃ (n : ℕ), 0 < n ∧ u n / n < L, { rw subadditive.lim at hL, rcases exists_lt_of_cInf_lt (by simp) hL with ⟨x, hx, xL⟩, rcases (mem_image _ _ _).1 hx with ⟨n, hn, rfl⟩, exact ⟨n, zero_lt_one.trans_le hn, xL⟩ }, exact h.eventually_div_lt_of_div_lt npos.ne' hn } end end subadditive
6df32c69f67e781da52f5f88a899f2fa4bd1bb62
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Lean/Compiler/InitAttr.lean
2b3f6c93b1eb1c2f7cb530b3a4a75a637ccada72
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
5,967
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.InfoTree.Main namespace Lean private def getIOTypeArg : Expr → Option Expr | Expr.app (Expr.const `IO _) arg => some arg | _ => none private def isUnitType : Expr → Bool | Expr.const `Unit _ => true | _ => false private def isIOUnit (type : Expr) : Bool := match getIOTypeArg type with | some type => isUnitType type | _ => false /-- Run the initializer of the given module (without `builtin_initialize` commands). Return `false` if the initializer is not available as native code. Initializers do not have corresponding Lean definitions, so they cannot be interpreted in this case. -/ @[extern "lean_run_mod_init"] unsafe opaque runModInit (mod : Name) : IO Bool /-- Run the initializer for `decl` and store its value for global access. Should only be used while importing. -/ @[extern "lean_run_init"] unsafe opaque runInit (env : @& Environment) (opts : @& Options) (decl initDecl : @& Name) : IO Unit unsafe def registerInitAttrUnsafe (attrName : Name) (runAfterImport : Bool) (ref : Name) : IO (ParametricAttribute Name) := registerParametricAttribute { ref := ref name := attrName descr := "initialization procedure for global references" getParam := fun declName stx => do let decl ← getConstInfo declName match (← Attribute.Builtin.getIdent? stx) with | some initFnName => let initFnName ← Elab.resolveGlobalConstNoOverloadWithInfo initFnName let initDecl ← getConstInfo initFnName match getIOTypeArg initDecl.type with | none => throwError "initialization function '{initFnName}' must have type of the form `IO <type>`" | some initTypeArg => if decl.type == initTypeArg then pure initFnName else throwError "initialization function '{initFnName}' type mismatch" | none => if isIOUnit decl.type then pure Name.anonymous else throwError "initialization function must have type `IO Unit`" afterImport := fun entries => do let ctx ← read if runAfterImport && (← isInitializerExecutionEnabled) then for mod in ctx.env.header.moduleNames, modEntries in entries do -- any native Lean code reachable by the interpreter (i.e. from shared -- libraries with their corresponding module in the Environment) must -- first be initialized if !(← runModInit mod) then -- If no native code for the module is available, run `[init]` decls manually. -- All other constants (nullary functions) are lazily initialized by the interpreter. for (decl, initDecl) in modEntries do if initDecl.isAnonymous then let initFn ← IO.ofExcept <| ctx.env.evalConst (IO Unit) ctx.opts decl initFn else runInit ctx.env ctx.opts decl initDecl } @[implementedBy registerInitAttrUnsafe] private opaque registerInitAttrInner (attrName : Name) (runAfterImport : Bool) (ref : Name) : IO (ParametricAttribute Name) @[inline] def registerInitAttr (attrName : Name) (runAfterImport : Bool) (ref : Name := by exact decl_name%) : IO (ParametricAttribute Name) := registerInitAttrInner attrName runAfterImport ref builtin_initialize regularInitAttr : ParametricAttribute Name ← registerInitAttr `init true builtin_initialize builtinInitAttr : ParametricAttribute Name ← registerInitAttr `builtinInit false def getInitFnNameForCore? (env : Environment) (attr : ParametricAttribute Name) (fn : Name) : Option Name := match attr.getParam? env fn with | some Name.anonymous => none | some n => some n | _ => none @[export lean_get_builtin_init_fn_name_for] def getBuiltinInitFnNameFor? (env : Environment) (fn : Name) : Option Name := getInitFnNameForCore? env builtinInitAttr fn @[export lean_get_regular_init_fn_name_for] def getRegularInitFnNameFor? (env : Environment) (fn : Name) : Option Name := getInitFnNameForCore? env regularInitAttr fn @[export lean_get_init_fn_name_for] def getInitFnNameFor? (env : Environment) (fn : Name) : Option Name := getBuiltinInitFnNameFor? env fn <|> getRegularInitFnNameFor? env fn def isIOUnitInitFnCore (env : Environment) (attr : ParametricAttribute Name) (fn : Name) : Bool := match attr.getParam? env fn with | some Name.anonymous => true | _ => false @[export lean_is_io_unit_regular_init_fn] def isIOUnitRegularInitFn (env : Environment) (fn : Name) : Bool := isIOUnitInitFnCore env regularInitAttr fn @[export lean_is_io_unit_builtin_init_fn] def isIOUnitBuiltinInitFn (env : Environment) (fn : Name) : Bool := isIOUnitInitFnCore env builtinInitAttr fn def isIOUnitInitFn (env : Environment) (fn : Name) : Bool := isIOUnitBuiltinInitFn env fn || isIOUnitRegularInitFn env fn def hasInitAttr (env : Environment) (fn : Name) : Bool := (getInitFnNameFor? env fn).isSome def setBuiltinInitAttr (env : Environment) (declName : Name) (initFnName : Name := Name.anonymous) : Except String Environment := builtinInitAttr.setParam env declName initFnName def declareBuiltin (forDecl : Name) (value : Expr) : CoreM Unit := do let name := `_regBuiltin ++ forDecl let type := mkApp (mkConst `IO) (mkConst `Unit) let decl := Declaration.defnDecl { name, levelParams := [], type, value, hints := ReducibilityHints.opaque, safety := DefinitionSafety.safe } match (← getEnv).addAndCompile {} decl with -- TODO: pretty print error | Except.error e => do let msg ← (e.toMessageData {}).toString throwError "failed to emit registration code for builtin '{forDecl}': {msg}" | Except.ok env => IO.ofExcept (setBuiltinInitAttr env name) >>= setEnv end Lean
5e724068c7e976e406063eb563da4a7440c2ee49
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/algebra/polynomial/big_operators.lean
885770a970f01900bf88e70a7af16aad25e3748e
[ "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
12,414
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Jalex Stark -/ import data.polynomial.monic import data.polynomial.ring_division import tactic.linarith /-! # Lemmas for the interaction between polynomials and `∑` and `∏`. Recall that `∑` and `∏` are notation for `finset.sum` and `finset.prod` respectively. ## Main results - `polynomial.nat_degree_prod_of_monic` : the degree of a product of monic polynomials is the product of degrees. We prove this only for `[comm_semiring R]`, but it ought to be true for `[semiring R]` and `list.prod`. - `polynomial.nat_degree_prod` : for polynomials over an integral domain, the degree of the product is the sum of degrees. - `polynomial.leading_coeff_prod` : for polynomials over an integral domain, the leading coefficient is the product of leading coefficients. - `polynomial.prod_X_sub_C_coeff_card_pred` carries most of the content for computing the second coefficient of the characteristic polynomial. -/ open finset open multiset open_locale big_operators universes u w variables {R : Type u} {ι : Type w} namespace polynomial variables (s : finset ι) section semiring variables {α : Type*} [semiring α] lemma nat_degree_list_sum_le (l : list (polynomial α)) : nat_degree l.sum ≤ (l.map nat_degree).foldr max 0 := list.sum_le_foldr_max nat_degree (by simp) nat_degree_add_le _ lemma nat_degree_multiset_sum_le (l : multiset (polynomial α)) : nat_degree l.sum ≤ (l.map nat_degree).foldr max max_left_comm 0 := quotient.induction_on l (by simpa using nat_degree_list_sum_le) lemma nat_degree_sum_le (f : ι → polynomial α) : nat_degree (∑ i in s, f i) ≤ s.fold max 0 (nat_degree ∘ f) := by simpa using nat_degree_multiset_sum_le (s.val.map f) lemma degree_list_sum_le (l : list (polynomial α)) : degree l.sum ≤ (l.map nat_degree).maximum := begin by_cases h : l.sum = 0, { simp [h] }, { rw degree_eq_nat_degree h, suffices : (l.map nat_degree).maximum = ((l.map nat_degree).foldr max 0 : ℕ), { rw this, simpa [this] using nat_degree_list_sum_le l }, rw list.maximum_eq_coe_foldr_max_of_ne_nil, { congr }, contrapose! h, rw [list.map_eq_nil] at h, simp [h] } end lemma nat_degree_list_prod_le (l : list (polynomial α)) : nat_degree l.prod ≤ (l.map nat_degree).sum := begin induction l with hd tl IH, { simp }, { simpa using nat_degree_mul_le.trans (add_le_add_left IH _) } end lemma coeff_list_prod_of_nat_degree_le (l : list (polynomial α)) (n : ℕ) (hl : ∀ p ∈ l, nat_degree p ≤ n) : coeff (list.prod l) (l.length * n) = (l.map (λ p, coeff p n)).prod := begin induction l with hd tl IH, { simp }, { have hl' : ∀ (p ∈ tl), nat_degree p ≤ n := λ p hp, hl p (list.mem_cons_of_mem _ hp), simp only [list.prod_cons, list.map, list.length], rw [add_mul, one_mul, add_comm, ←IH hl', mul_comm tl.length], have h : nat_degree tl.prod ≤ n * tl.length, { refine (nat_degree_list_prod_le _).trans _, rw [←tl.length_map nat_degree, mul_comm], refine list.sum_le_of_forall_le _ _ _, simpa using hl' }, have hdn : nat_degree hd ≤ n := hl _ (list.mem_cons_self _ _), rcases hdn.eq_or_lt with rfl|hdn', { cases h.eq_or_lt with h' h', { rw [←h', coeff_mul_degree_add_degree, leading_coeff, leading_coeff] }, { rw [coeff_eq_zero_of_nat_degree_lt, coeff_eq_zero_of_nat_degree_lt h', mul_zero], exact nat_degree_mul_le.trans_lt (add_lt_add_left h' _) } }, { rw [coeff_eq_zero_of_nat_degree_lt hdn', coeff_eq_zero_of_nat_degree_lt, zero_mul], exact nat_degree_mul_le.trans_lt (add_lt_add_of_lt_of_le hdn' h) } } end end semiring section comm_semiring variables [comm_semiring R] (f : ι → polynomial R) (t : multiset (polynomial R)) lemma nat_degree_multiset_prod_le : t.prod.nat_degree ≤ (t.map nat_degree).sum := quotient.induction_on t (by simpa using nat_degree_list_prod_le) lemma nat_degree_prod_le : (∏ i in s, f i).nat_degree ≤ ∑ i in s, (f i).nat_degree := by simpa using nat_degree_multiset_prod_le (s.1.map f) /-- The leading coefficient of a product of polynomials is equal to the product of the leading coefficients, provided that this product is nonzero. See `polynomial.leading_coeff_multiset_prod` (without the `'`) for a version for integral domains, where this condition is automatically satisfied. -/ lemma leading_coeff_multiset_prod' (h : (t.map leading_coeff).prod ≠ 0) : t.prod.leading_coeff = (t.map leading_coeff).prod := begin revert h, refine multiset.induction_on t _ (λ a t ih ht, _), { simp }, rw [map_cons, prod_cons] at ht, simp only [map_cons, prod_cons], rw polynomial.leading_coeff_mul'; { rwa ih, apply right_ne_zero_of_mul ht } end /-- The leading coefficient of a product of polynomials is equal to the product of the leading coefficients, provided that this product is nonzero. See `polynomial.leading_coeff_prod` (without the `'`) for a version for integral domains, where this condition is automatically satisfied. -/ lemma leading_coeff_prod' (h : ∏ i in s, (f i).leading_coeff ≠ 0) : (∏ i in s, f i).leading_coeff = ∏ i in s, (f i).leading_coeff := by simpa using leading_coeff_multiset_prod' (s.1.map f) (by simpa using h) /-- The degree of a product of polynomials is equal to the sum of the degrees, provided that the product of leading coefficients is nonzero. See `polynomial.nat_degree_multiset_prod` (without the `'`) for a version for integral domains, where this condition is automatically satisfied. -/ lemma nat_degree_multiset_prod' (h : (t.map (λ f, leading_coeff f)).prod ≠ 0) : t.prod.nat_degree = (t.map (λ f, nat_degree f)).sum := begin revert h, refine multiset.induction_on t _ (λ a t ih ht, _), { simp }, rw [map_cons, prod_cons] at ht ⊢, rw [sum_cons, polynomial.nat_degree_mul', ih], { apply right_ne_zero_of_mul ht }, { rwa polynomial.leading_coeff_multiset_prod', apply right_ne_zero_of_mul ht }, end /-- The degree of a product of polynomials is equal to the sum of the degrees, provided that the product of leading coefficients is nonzero. See `polynomial.nat_degree_prod` (without the `'`) for a version for integral domains, where this condition is automatically satisfied. -/ lemma nat_degree_prod' (h : ∏ i in s, (f i).leading_coeff ≠ 0) : (∏ i in s, f i).nat_degree = ∑ i in s, (f i).nat_degree := by simpa using nat_degree_multiset_prod' (s.1.map f) (by simpa using h) lemma nat_degree_multiset_prod_of_monic [nontrivial R] (h : ∀ f ∈ t, monic f) : t.prod.nat_degree = (t.map nat_degree).sum := begin apply nat_degree_multiset_prod', suffices : (t.map (λ f, leading_coeff f)).prod = 1, { rw this, simp }, convert prod_repeat (1 : R) t.card, { simp only [eq_repeat, multiset.card_map, eq_self_iff_true, true_and], rintros i hi, obtain ⟨i, hi, rfl⟩ := multiset.mem_map.mp hi, apply h, assumption }, { simp } end lemma nat_degree_prod_of_monic [nontrivial R] (h : ∀ i ∈ s, (f i).monic) : (∏ i in s, f i).nat_degree = ∑ i in s, (f i).nat_degree := by simpa using nat_degree_multiset_prod_of_monic (s.1.map f) (by simpa using h) lemma coeff_multiset_prod_of_nat_degree_le (n : ℕ) (hl : ∀ p ∈ t, nat_degree p ≤ n) : coeff t.prod (t.card * n) = (t.map (λ p, coeff p n)).prod := begin induction t using quotient.induction_on, simpa using coeff_list_prod_of_nat_degree_le _ _ hl end lemma coeff_prod_of_nat_degree_le (f : ι → polynomial R) (n : ℕ) (h : ∀ p ∈ s, nat_degree (f p) ≤ n) : coeff (∏ i in s, f i) (s.card * n) = ∏ i in s, coeff (f i) n := begin cases s with l hl, convert coeff_multiset_prod_of_nat_degree_le (l.map f) _ _, { simp }, { simp }, { simpa using h } end lemma coeff_zero_multiset_prod : t.prod.coeff 0 = (t.map (λ f, coeff f 0)).prod := begin refine multiset.induction_on t _ (λ a t ht, _), { simp }, rw [prod_cons, map_cons, prod_cons, polynomial.mul_coeff_zero, ht] end lemma coeff_zero_prod : (∏ i in s, f i).coeff 0 = ∏ i in s, (f i).coeff 0 := by simpa using coeff_zero_multiset_prod (s.1.map f) end comm_semiring section comm_ring variables [comm_ring R] open monic -- Eventually this can be generalized with Vieta's formulas -- plus the connection between roots and factorization. lemma multiset_prod_X_sub_C_next_coeff [nontrivial R] (t : multiset R) : next_coeff (t.map (λ x, X - C x)).prod = -t.sum := begin rw next_coeff_multiset_prod, { simp only [next_coeff_X_sub_C], refine t.sum_hom ⟨has_neg.neg, _, _⟩; simp [add_comm] }, { intros, apply monic_X_sub_C } end lemma prod_X_sub_C_next_coeff [nontrivial R] {s : finset ι} (f : ι → R) : next_coeff ∏ i in s, (X - C (f i)) = -∑ i in s, f i := by simpa using multiset_prod_X_sub_C_next_coeff (s.1.map f) lemma multiset_prod_X_sub_C_coeff_card_pred [nontrivial R] (t : multiset R) (ht : 0 < t.card) : (t.map (λ x, (X - C x))).prod.coeff (t.card - 1) = -t.sum := begin convert multiset_prod_X_sub_C_next_coeff (by assumption), rw next_coeff, split_ifs, { rw nat_degree_multiset_prod_of_monic at h; simp only [multiset.mem_map] at *, swap, { rintros _ ⟨_, _, rfl⟩, apply monic_X_sub_C }, simp_rw [multiset.sum_eq_zero_iff, multiset.mem_map] at h, contrapose! h, obtain ⟨x, hx⟩ := card_pos_iff_exists_mem.mp ht, exact ⟨_, ⟨_, ⟨x, hx, rfl⟩, nat_degree_X_sub_C _⟩, one_ne_zero⟩ }, congr, rw nat_degree_multiset_prod_of_monic; { simp [nat_degree_X_sub_C, monic_X_sub_C] }, end lemma prod_X_sub_C_coeff_card_pred [nontrivial R] (s : finset ι) (f : ι → R) (hs : 0 < s.card) : (∏ i in s, (X - C (f i))).coeff (s.card - 1) = - ∑ i in s, f i := by simpa using multiset_prod_X_sub_C_coeff_card_pred (s.1.map f) (by simpa using hs) end comm_ring section no_zero_divisors variables [comm_ring R] [no_zero_divisors R] (f : ι → polynomial R) (t : multiset (polynomial R)) /-- The degree of a product of polynomials is equal to the sum of the degrees. See `polynomial.nat_degree_prod'` (with a `'`) for a version for commutative semirings, where additionally, the product of the leading coefficients must be nonzero. -/ lemma nat_degree_prod [nontrivial R] (h : ∀ i ∈ s, f i ≠ 0) : (∏ i in s, f i).nat_degree = ∑ i in s, (f i).nat_degree := begin apply nat_degree_prod', rw prod_ne_zero_iff, intros x hx, simp [h x hx] end lemma nat_degree_multiset_prod [nontrivial R] (s : multiset (polynomial R)) (h : (0 : polynomial R) ∉ s) : nat_degree s.prod = (s.map nat_degree).sum := begin rw nat_degree_multiset_prod', simp_rw [ne.def, multiset.prod_eq_zero_iff, multiset.mem_map, leading_coeff_eq_zero], rintro ⟨_, h, rfl⟩, contradiction end /-- The degree of a product of polynomials is equal to the sum of the degrees, where the degree of the zero polynomial is ⊥. -/ lemma degree_multiset_prod [nontrivial R] : t.prod.degree = (t.map (λ f, degree f)).sum := begin refine multiset.induction_on t _ (λ a t ht, _), { simp }, { rw [prod_cons, degree_mul, ht, map_cons, sum_cons] } end /-- The degree of a product of polynomials is equal to the sum of the degrees, where the degree of the zero polynomial is ⊥. -/ lemma degree_prod [nontrivial R] : (∏ i in s, f i).degree = ∑ i in s, (f i).degree := by simpa using degree_multiset_prod (s.1.map f) /-- The leading coefficient of a product of polynomials is equal to the product of the leading coefficients. See `polynomial.leading_coeff_multiset_prod'` (with a `'`) for a version for commutative semirings, where additionally, the product of the leading coefficients must be nonzero. -/ lemma leading_coeff_multiset_prod : t.prod.leading_coeff = (t.map (λ f, leading_coeff f)).prod := by { rw [← leading_coeff_hom_apply, monoid_hom.map_multiset_prod], refl } /-- The leading coefficient of a product of polynomials is equal to the product of the leading coefficients. See `polynomial.leading_coeff_prod'` (with a `'`) for a version for commutative semirings, where additionally, the product of the leading coefficients must be nonzero. -/ lemma leading_coeff_prod : (∏ i in s, f i).leading_coeff = ∏ i in s, (f i).leading_coeff := by simpa using leading_coeff_multiset_prod (s.1.map f) end no_zero_divisors end polynomial
00bd265fcbbfe6b09cd825db5db20b3d046f8de2
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/data/rbtree/insert.lean
ca5b72114652f2c9e40733cbe1d367b3077fd767
[]
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
23,141
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 -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.Lean3Lib.data.rbtree.find universes u v namespace Mathlib namespace rbnode @[simp] theorem balance1_eq₁ {α : Type u} (l : rbnode α) (x : α) (r₁ : rbnode α) (y : α) (r₂ : rbnode α) (v : α) (t : rbnode α) : balance1 (red_node l x r₁) y r₂ v t = red_node (black_node l x r₁) y (black_node r₂ v t) := sorry @[simp] theorem balance1_eq₂ {α : Type u} (l₁ : rbnode α) (y : α) (l₂ : rbnode α) (x : α) (r : rbnode α) (v : α) (t : rbnode α) : get_color l₁ ≠ color.red → balance1 l₁ y (red_node l₂ x r) v t = red_node (black_node l₁ y l₂) x (black_node r v t) := sorry @[simp] theorem balance1_eq₃ {α : Type u} (l : rbnode α) (y : α) (r : rbnode α) (v : α) (t : rbnode α) : get_color l ≠ color.red → get_color r ≠ color.red → balance1 l y r v t = black_node (red_node l y r) v t := sorry @[simp] theorem balance2_eq₁ {α : Type u} (l : rbnode α) (x₁ : α) (r₁ : rbnode α) (y : α) (r₂ : rbnode α) (v : α) (t : rbnode α) : balance2 (red_node l x₁ r₁) y r₂ v t = red_node (black_node t v l) x₁ (black_node r₁ y r₂) := sorry @[simp] theorem balance2_eq₂ {α : Type u} (l₁ : rbnode α) (y : α) (l₂ : rbnode α) (x₂ : α) (r₂ : rbnode α) (v : α) (t : rbnode α) : get_color l₁ ≠ color.red → balance2 l₁ y (red_node l₂ x₂ r₂) v t = red_node (black_node t v l₁) y (black_node l₂ x₂ r₂) := sorry @[simp] theorem balance2_eq₃ {α : Type u} (l : rbnode α) (y : α) (r : rbnode α) (v : α) (t : rbnode α) : get_color l ≠ color.red → get_color r ≠ color.red → balance2 l y r v t = black_node t v (red_node l y r) := sorry /- We can use the same induction principle for balance1 and balance2 -/ theorem balance.cases {α : Type u} {p : rbnode α → α → rbnode α → Prop} (l : rbnode α) (y : α) (r : rbnode α) (red_left : ∀ (l : rbnode α) (x : α) (r₁ : rbnode α) (y : α) (r₂ : rbnode α), p (red_node l x r₁) y r₂) (red_right : ∀ (l₁ : rbnode α) (y : α) (l₂ : rbnode α) (x : α) (r : rbnode α), get_color l₁ ≠ color.red → p l₁ y (red_node l₂ x r)) (other : ∀ (l : rbnode α) (y : α) (r : rbnode α), get_color l ≠ color.red → get_color r ≠ color.red → p l y r) : p l y r := sorry theorem balance1_ne_leaf {α : Type u} (l : rbnode α) (x : α) (r : rbnode α) (v : α) (t : rbnode α) : balance1 l x r v t ≠ leaf := sorry theorem balance1_node_ne_leaf {α : Type u} {s : rbnode α} (a : α) (t : rbnode α) : s ≠ leaf → balance1_node s a t ≠ leaf := sorry theorem balance2_ne_leaf {α : Type u} (l : rbnode α) (x : α) (r : rbnode α) (v : α) (t : rbnode α) : balance2 l x r v t ≠ leaf := sorry theorem balance2_node_ne_leaf {α : Type u} {s : rbnode α} (a : α) (t : rbnode α) : s ≠ leaf → balance2_node s a t ≠ leaf := sorry theorem ins.induction {α : Type u} (lt : α → α → Prop) [DecidableRel lt] {p : rbnode α → Prop} (t : rbnode α) (x : α) (is_leaf : p leaf) (is_red_lt : ∀ (a : rbnode α) (y : α) (b : rbnode α), cmp_using lt x y = ordering.lt → p a → p (red_node a y b)) (is_red_eq : ∀ (a : rbnode α) (y : α) (b : rbnode α), cmp_using lt x y = ordering.eq → p (red_node a y b)) (is_red_gt : ∀ (a : rbnode α) (y : α) (b : rbnode α), cmp_using lt x y = ordering.gt → p b → p (red_node a y b)) (is_black_lt_red : ∀ (a : rbnode α) (y : α) (b : rbnode α), cmp_using lt x y = ordering.lt → get_color a = color.red → p a → p (black_node a y b)) (is_black_lt_not_red : ∀ (a : rbnode α) (y : α) (b : rbnode α), cmp_using lt x y = ordering.lt → get_color a ≠ color.red → p a → p (black_node a y b)) (is_black_eq : ∀ (a : rbnode α) (y : α) (b : rbnode α), cmp_using lt x y = ordering.eq → p (black_node a y b)) (is_black_gt_red : ∀ (a : rbnode α) (y : α) (b : rbnode α), cmp_using lt x y = ordering.gt → get_color b = color.red → p b → p (black_node a y b)) (is_black_gt_not_red : ∀ (a : rbnode α) (y : α) (b : rbnode α), cmp_using lt x y = ordering.gt → get_color b ≠ color.red → p b → p (black_node a y b)) : p t := sorry theorem is_searchable_balance1 {α : Type u} (lt : α → α → Prop) [DecidableRel lt] {l : rbnode α} {y : α} {r : rbnode α} {v : α} {t : rbnode α} {lo : Option α} {hi : Option α} : is_searchable lt l lo (some y) → is_searchable lt r (some y) (some v) → is_searchable lt t (some v) hi → is_searchable lt (balance1 l y r v t) lo hi := sorry theorem is_searchable_balance1_node {α : Type u} (lt : α → α → Prop) [DecidableRel lt] {t : rbnode α} [is_trans α lt] {y : α} {s : rbnode α} {lo : Option α} {hi : Option α} : is_searchable lt t lo (some y) → is_searchable lt s (some y) hi → is_searchable lt (balance1_node t y s) lo hi := sorry theorem is_searchable_balance2 {α : Type u} (lt : α → α → Prop) [DecidableRel lt] {l : rbnode α} {y : α} {r : rbnode α} {v : α} {t : rbnode α} {lo : Option α} {hi : Option α} : is_searchable lt t lo (some v) → is_searchable lt l (some v) (some y) → is_searchable lt r (some y) hi → is_searchable lt (balance2 l y r v t) lo hi := sorry theorem is_searchable_balance2_node {α : Type u} (lt : α → α → Prop) [DecidableRel lt] {t : rbnode α} [is_trans α lt] {y : α} {s : rbnode α} {lo : Option α} {hi : Option α} : is_searchable lt s lo (some y) → is_searchable lt t (some y) hi → is_searchable lt (balance2_node t y s) lo hi := sorry theorem is_searchable_ins {α : Type u} (lt : α → α → Prop) [DecidableRel lt] {t : rbnode α} {x : α} [is_strict_weak_order α lt] {lo : Option α} {hi : Option α} (h : is_searchable lt t lo hi) : lift lt lo (some x) → lift lt (some x) hi → is_searchable lt (ins lt t x) lo hi := sorry theorem is_searchable_mk_insert_result {α : Type u} (lt : α → α → Prop) [DecidableRel lt] {c : color} {t : rbnode α} : is_searchable lt t none none → is_searchable lt (mk_insert_result c t) none none := sorry theorem is_searchable_insert {α : Type u} (lt : α → α → Prop) [DecidableRel lt] {t : rbnode α} {x : α} [is_strict_weak_order α lt] : is_searchable lt t none none → is_searchable lt (insert lt t x) none none := sorry end rbnode namespace rbnode theorem mem_balance1_node_of_mem_left {α : Type u} (lt : α → α → Prop) [DecidableRel lt] {x : α} {s : rbnode α} (v : α) (t : rbnode α) : mem lt x s → mem lt x (balance1_node s v t) := sorry theorem mem_balance2_node_of_mem_left {α : Type u} (lt : α → α → Prop) [DecidableRel lt] {x : α} {s : rbnode α} (v : α) (t : rbnode α) : mem lt x s → mem lt x (balance2_node s v t) := sorry theorem mem_balance1_node_of_mem_right {α : Type u} (lt : α → α → Prop) [DecidableRel lt] {x : α} {t : rbnode α} (v : α) (s : rbnode α) : mem lt x t → mem lt x (balance1_node s v t) := sorry theorem mem_balance2_node_of_mem_right {α : Type u} (lt : α → α → Prop) [DecidableRel lt] {x : α} {t : rbnode α} (v : α) (s : rbnode α) : mem lt x t → mem lt x (balance2_node s v t) := sorry theorem mem_balance1_node_of_incomp {α : Type u} (lt : α → α → Prop) [DecidableRel lt] {x : α} {v : α} (s : rbnode α) (t : rbnode α) : ¬lt x v ∧ ¬lt v x → s ≠ leaf → mem lt x (balance1_node s v t) := sorry theorem mem_balance2_node_of_incomp {α : Type u} (lt : α → α → Prop) [DecidableRel lt] {x : α} {v : α} (s : rbnode α) (t : rbnode α) : ¬lt v x ∧ ¬lt x v → s ≠ leaf → mem lt x (balance2_node s v t) := sorry theorem ins_ne_leaf {α : Type u} (lt : α → α → Prop) [DecidableRel lt] (t : rbnode α) (x : α) : ins lt t x ≠ leaf := sorry theorem insert_ne_leaf {α : Type u} (lt : α → α → Prop) [DecidableRel lt] (t : rbnode α) (x : α) : insert lt t x ≠ leaf := sorry theorem mem_ins_of_incomp {α : Type u} (lt : α → α → Prop) [DecidableRel lt] (t : rbnode α) {x : α} {y : α} (h : ¬lt x y ∧ ¬lt y x) : mem lt x (ins lt t y) := sorry theorem mem_ins_of_mem {α : Type u} (lt : α → α → Prop) [DecidableRel lt] [is_strict_weak_order α lt] {t : rbnode α} (z : α) {x : α} (h : mem lt x t) : mem lt x (ins lt t z) := sorry theorem mem_mk_insert_result {α : Type u} (lt : α → α → Prop) [DecidableRel lt] {a : α} {t : rbnode α} (c : color) : mem lt a t → mem lt a (mk_insert_result c t) := sorry theorem mem_of_mem_mk_insert_result {α : Type u} (lt : α → α → Prop) [DecidableRel lt] {a : α} {t : rbnode α} {c : color} : mem lt a (mk_insert_result c t) → mem lt a t := sorry theorem mem_insert_of_incomp {α : Type u} (lt : α → α → Prop) [DecidableRel lt] (t : rbnode α) {x : α} {y : α} (h : ¬lt x y ∧ ¬lt y x) : mem lt x (insert lt t y) := sorry theorem mem_insert_of_mem {α : Type u} (lt : α → α → Prop) [DecidableRel lt] [is_strict_weak_order α lt] {t : rbnode α} {x : α} (z : α) : mem lt x t → mem lt x (insert lt t z) := fun (ᾰ : mem lt x t) => mem_mk_insert_result lt (get_color t) (mem_ins_of_mem lt z ᾰ) theorem of_mem_balance1_node {α : Type u} (lt : α → α → Prop) [DecidableRel lt] [is_strict_weak_order α lt] {x : α} {s : rbnode α} {v : α} {t : rbnode α} : mem lt x (balance1_node s v t) → mem lt x s ∨ ¬lt x v ∧ ¬lt v x ∨ mem lt x t := sorry theorem of_mem_balance2_node {α : Type u} (lt : α → α → Prop) [DecidableRel lt] [is_strict_weak_order α lt] {x : α} {s : rbnode α} {v : α} {t : rbnode α} : mem lt x (balance2_node s v t) → mem lt x s ∨ ¬lt x v ∧ ¬lt v x ∨ mem lt x t := sorry theorem equiv_or_mem_of_mem_ins {α : Type u} (lt : α → α → Prop) [DecidableRel lt] [is_strict_weak_order α lt] {t : rbnode α} {x : α} {z : α} (h : mem lt x (ins lt t z)) : strict_weak_order.equiv x z ∨ mem lt x t := sorry theorem equiv_or_mem_of_mem_insert {α : Type u} (lt : α → α → Prop) [DecidableRel lt] [is_strict_weak_order α lt] {t : rbnode α} {x : α} {z : α} (h : mem lt x (insert lt t z)) : strict_weak_order.equiv x z ∨ mem lt x t := sorry theorem mem_exact_balance1_node_of_mem_exact {α : Type u} {x : α} {s : rbnode α} (v : α) (t : rbnode α) : mem_exact x s → mem_exact x (balance1_node s v t) := sorry theorem mem_exact_balance2_node_of_mem_exact {α : Type u} {x : α} {s : rbnode α} (v : α) (t : rbnode α) : mem_exact x s → mem_exact x (balance2_node s v t) := sorry theorem find_balance1_node {α : Type u} (lt : α → α → Prop) [DecidableRel lt] [is_strict_weak_order α lt] {x : α} {y : α} {z : α} {t : rbnode α} {s : rbnode α} {lo : Option α} {hi : Option α} : is_searchable lt t lo (some z) → is_searchable lt s (some z) hi → find lt t y = some x → strict_weak_order.equiv y x → find lt (balance1_node t z s) y = some x := sorry theorem find_balance2_node {α : Type u} (lt : α → α → Prop) [DecidableRel lt] [is_strict_weak_order α lt] {x : α} {y : α} {z : α} {s : rbnode α} {t : rbnode α} [is_trans α lt] {lo : Option α} {hi : Option α} : is_searchable lt s lo (some z) → is_searchable lt t (some z) hi → find lt t y = some x → strict_weak_order.equiv y x → find lt (balance2_node t z s) y = some x := sorry /- Auxiliary lemma -/ theorem ite_eq_of_not_lt {α : Type u} (lt : α → α → Prop) [DecidableRel lt] [is_strict_order α lt] {a : α} {b : α} {β : Type v} (t : β) (s : β) (h : lt b a) : ite (lt a b) t s = s := sorry theorem find_ins_of_eqv {α : Type u} (lt : α → α → Prop) [DecidableRel lt] [is_strict_weak_order α lt] {x : α} {y : α} {t : rbnode α} (he : strict_weak_order.equiv x y) {lo : Option α} {hi : Option α} (hs : is_searchable lt t lo hi) (hlt₁ : lift lt lo (some x)) (hlt₂ : lift lt (some x) hi) : find lt (ins lt t x) y = some x := sorry theorem find_mk_insert_result {α : Type u} (lt : α → α → Prop) [DecidableRel lt] (c : color) (t : rbnode α) (x : α) : find lt (mk_insert_result c t) x = find lt t x := sorry theorem find_insert_of_eqv {α : Type u} (lt : α → α → Prop) [DecidableRel lt] [is_strict_weak_order α lt] {x : α} {y : α} {t : rbnode α} (he : strict_weak_order.equiv x y) : is_searchable lt t none none → find lt (insert lt t x) y = some x := sorry theorem weak_trichotomous {α : Type u} (lt : α → α → Prop) [DecidableRel lt] (x : α) (y : α) {p : Prop} (is_lt : lt x y → p) (is_eqv : ¬lt x y ∧ ¬lt y x → p) (is_gt : lt y x → p) : p := dite (lt x y) (fun (h : lt x y) => dite (lt y x) (fun (h_1 : lt y x) => is_lt h) fun (h_1 : ¬lt y x) => is_lt h) fun (h : ¬lt x y) => dite (lt y x) (fun (h : lt y x) => is_gt h) fun (h_1 : ¬lt y x) => is_eqv { left := h, right := h_1 } theorem find_black_eq_find_red {α : Type u} (lt : α → α → Prop) [DecidableRel lt] {l : rbnode α} {y : α} {r : rbnode α} {x : α} : find lt (black_node l y r) x = find lt (red_node l y r) x := sorry theorem find_red_of_lt {α : Type u} (lt : α → α → Prop) [DecidableRel lt] {l : rbnode α} {y : α} {r : rbnode α} {x : α} (h : lt x y) : find lt (red_node l y r) x = find lt l x := sorry theorem find_red_of_gt {α : Type u} (lt : α → α → Prop) [DecidableRel lt] [is_strict_order α lt] {l : rbnode α} {y : α} {r : rbnode α} {x : α} (h : lt y x) : find lt (red_node l y r) x = find lt r x := sorry theorem find_red_of_incomp {α : Type u} (lt : α → α → Prop) [DecidableRel lt] {l : rbnode α} {y : α} {r : rbnode α} {x : α} (h : ¬lt x y ∧ ¬lt y x) : find lt (red_node l y r) x = some y := sorry theorem find_balance1_lt {α : Type u} (lt : α → α → Prop) [DecidableRel lt] [is_strict_weak_order α lt] {l : rbnode α} {r : rbnode α} {t : rbnode α} {v : α} {x : α} {y : α} {lo : Option α} {hi : Option α} (h : lt x y) (hl : is_searchable lt l lo (some v)) (hr : is_searchable lt r (some v) (some y)) (ht : is_searchable lt t (some y) hi) : find lt (balance1 l v r y t) x = find lt (red_node l v r) x := sorry theorem find_balance1_node_lt {α : Type u} (lt : α → α → Prop) [DecidableRel lt] [is_strict_weak_order α lt] {t : rbnode α} {s : rbnode α} {x : α} {y : α} {lo : Option α} {hi : Option α} (hlt : lt y x) (ht : is_searchable lt t lo (some x)) (hs : is_searchable lt s (some x) hi) (hne : autoParam (t ≠ leaf) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.rbnode.ins_ne_leaf_tac") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "rbnode") "ins_ne_leaf_tac") [])) : find lt (balance1_node t x s) y = find lt t y := sorry theorem find_balance1_gt {α : Type u} (lt : α → α → Prop) [DecidableRel lt] [is_strict_weak_order α lt] {l : rbnode α} {r : rbnode α} {t : rbnode α} {v : α} {x : α} {y : α} {lo : Option α} {hi : Option α} (h : lt y x) (hl : is_searchable lt l lo (some v)) (hr : is_searchable lt r (some v) (some y)) (ht : is_searchable lt t (some y) hi) : find lt (balance1 l v r y t) x = find lt t x := sorry theorem find_balance1_node_gt {α : Type u} (lt : α → α → Prop) [DecidableRel lt] [is_strict_weak_order α lt] {t : rbnode α} {s : rbnode α} {x : α} {y : α} {lo : Option α} {hi : Option α} (h : lt x y) (ht : is_searchable lt t lo (some x)) (hs : is_searchable lt s (some x) hi) (hne : autoParam (t ≠ leaf) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.rbnode.ins_ne_leaf_tac") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "rbnode") "ins_ne_leaf_tac") [])) : find lt (balance1_node t x s) y = find lt s y := sorry theorem find_balance1_eqv {α : Type u} (lt : α → α → Prop) [DecidableRel lt] [is_strict_weak_order α lt] {l : rbnode α} {r : rbnode α} {t : rbnode α} {v : α} {x : α} {y : α} {lo : Option α} {hi : Option α} (h : ¬lt x y ∧ ¬lt y x) (hl : is_searchable lt l lo (some v)) (hr : is_searchable lt r (some v) (some y)) (ht : is_searchable lt t (some y) hi) : find lt (balance1 l v r y t) x = some y := sorry theorem find_balance1_node_eqv {α : Type u} (lt : α → α → Prop) [DecidableRel lt] [is_strict_weak_order α lt] {t : rbnode α} {s : rbnode α} {x : α} {y : α} {lo : Option α} {hi : Option α} (h : ¬lt x y ∧ ¬lt y x) (ht : is_searchable lt t lo (some y)) (hs : is_searchable lt s (some y) hi) (hne : autoParam (t ≠ leaf) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.rbnode.ins_ne_leaf_tac") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "rbnode") "ins_ne_leaf_tac") [])) : find lt (balance1_node t y s) x = some y := sorry theorem find_balance2_lt {α : Type u} (lt : α → α → Prop) [DecidableRel lt] [is_strict_weak_order α lt] {l : rbnode α} {v : α} {r : rbnode α} {t : rbnode α} {x : α} {y : α} {lo : Option α} {hi : Option α} (h : lt x y) (hl : is_searchable lt l (some y) (some v)) (hr : is_searchable lt r (some v) hi) (ht : is_searchable lt t lo (some y)) : find lt (balance2 l v r y t) x = find lt t x := sorry theorem find_balance2_node_lt {α : Type u} (lt : α → α → Prop) [DecidableRel lt] [is_strict_weak_order α lt] {s : rbnode α} {t : rbnode α} {x : α} {y : α} {lo : Option α} {hi : Option α} (h : lt x y) (ht : is_searchable lt t (some y) hi) (hs : is_searchable lt s lo (some y)) (hne : autoParam (t ≠ leaf) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.rbnode.ins_ne_leaf_tac") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "rbnode") "ins_ne_leaf_tac") [])) : find lt (balance2_node t y s) x = find lt s x := sorry theorem find_balance2_gt {α : Type u} (lt : α → α → Prop) [DecidableRel lt] [is_strict_weak_order α lt] {l : rbnode α} {v : α} {r : rbnode α} {t : rbnode α} {x : α} {y : α} {lo : Option α} {hi : Option α} (h : lt y x) (hl : is_searchable lt l (some y) (some v)) (hr : is_searchable lt r (some v) hi) (ht : is_searchable lt t lo (some y)) : find lt (balance2 l v r y t) x = find lt (red_node l v r) x := sorry theorem find_balance2_node_gt {α : Type u} (lt : α → α → Prop) [DecidableRel lt] [is_strict_weak_order α lt] {s : rbnode α} {t : rbnode α} {x : α} {y : α} {lo : Option α} {hi : Option α} (h : lt y x) (ht : is_searchable lt t (some y) hi) (hs : is_searchable lt s lo (some y)) (hne : autoParam (t ≠ leaf) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.rbnode.ins_ne_leaf_tac") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "rbnode") "ins_ne_leaf_tac") [])) : find lt (balance2_node t y s) x = find lt t x := sorry theorem find_balance2_eqv {α : Type u} (lt : α → α → Prop) [DecidableRel lt] [is_strict_weak_order α lt] {l : rbnode α} {v : α} {r : rbnode α} {t : rbnode α} {x : α} {y : α} {lo : Option α} {hi : Option α} (h : ¬lt x y ∧ ¬lt y x) (hl : is_searchable lt l (some y) (some v)) (hr : is_searchable lt r (some v) hi) (ht : is_searchable lt t lo (some y)) : find lt (balance2 l v r y t) x = some y := sorry theorem find_balance2_node_eqv {α : Type u} (lt : α → α → Prop) [DecidableRel lt] [is_strict_weak_order α lt] {t : rbnode α} {s : rbnode α} {x : α} {y : α} {lo : Option α} {hi : Option α} (h : ¬lt x y ∧ ¬lt y x) (ht : is_searchable lt t (some y) hi) (hs : is_searchable lt s lo (some y)) (hne : autoParam (t ≠ leaf) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.rbnode.ins_ne_leaf_tac") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "rbnode") "ins_ne_leaf_tac") [])) : find lt (balance2_node t y s) x = some y := sorry theorem find_ins_of_disj {α : Type u} (lt : α → α → Prop) [DecidableRel lt] [is_strict_weak_order α lt] {x : α} {y : α} {t : rbnode α} (hn : lt x y ∨ lt y x) {lo : Option α} {hi : Option α} (hs : is_searchable lt t lo hi) (hlt₁ : lift lt lo (some x)) (hlt₂ : lift lt (some x) hi) : find lt (ins lt t x) y = find lt t y := sorry theorem find_insert_of_disj {α : Type u} (lt : α → α → Prop) [DecidableRel lt] [is_strict_weak_order α lt] {x : α} {y : α} {t : rbnode α} (hd : lt x y ∨ lt y x) : is_searchable lt t none none → find lt (insert lt t x) y = find lt t y := sorry theorem find_insert_of_not_eqv {α : Type u} (lt : α → α → Prop) [DecidableRel lt] [is_strict_weak_order α lt] {x : α} {y : α} {t : rbnode α} (hn : ¬strict_weak_order.equiv x y) : is_searchable lt t none none → find lt (insert lt t x) y = find lt t y := sorry inductive is_bad_red_black {α : Type u} : rbnode α → ℕ → Prop where | bad_red : ∀ {c₁ c₂ : color} {n : ℕ} {l r : rbnode α} {v : α}, is_red_black l c₁ n → is_red_black r c₂ n → is_bad_red_black (red_node l v r) n theorem balance1_rb {α : Type u} {l : rbnode α} {r : rbnode α} {t : rbnode α} {y : α} {v : α} {c_l : color} {c_r : color} {c_t : color} {n : ℕ} : is_red_black l c_l n → is_red_black r c_r n → is_red_black t c_t n → ∃ (c : color), is_red_black (balance1 l y r v t) c (Nat.succ n) := sorry theorem balance2_rb {α : Type u} {l : rbnode α} {r : rbnode α} {t : rbnode α} {y : α} {v : α} {c_l : color} {c_r : color} {c_t : color} {n : ℕ} : is_red_black l c_l n → is_red_black r c_r n → is_red_black t c_t n → ∃ (c : color), is_red_black (balance2 l y r v t) c (Nat.succ n) := sorry theorem balance1_node_rb {α : Type u} {t : rbnode α} {s : rbnode α} {y : α} {c : color} {n : ℕ} : is_bad_red_black t n → is_red_black s c n → ∃ (c : color), is_red_black (balance1_node t y s) c (Nat.succ n) := sorry theorem balance2_node_rb {α : Type u} {t : rbnode α} {s : rbnode α} {y : α} {c : color} {n : ℕ} : is_bad_red_black t n → is_red_black s c n → ∃ (c : color), is_red_black (balance2_node t y s) c (Nat.succ n) := sorry def ins_rb_result {α : Type u} : rbnode α → color → ℕ → Prop := sorry theorem of_get_color_eq_red {α : Type u} {t : rbnode α} {c : color} {n : ℕ} : get_color t = color.red → is_red_black t c n → c = color.red := sorry theorem of_get_color_ne_red {α : Type u} {t : rbnode α} {c : color} {n : ℕ} : get_color t ≠ color.red → is_red_black t c n → c = color.black := sorry theorem ins_rb {α : Type u} (lt : α → α → Prop) [DecidableRel lt] {t : rbnode α} (x : α) {c : color} {n : ℕ} (h : is_red_black t c n) : ins_rb_result (ins lt t x) c n := sorry def insert_rb_result {α : Type u} : rbnode α → color → ℕ → Prop := sorry theorem insert_rb {α : Type u} (lt : α → α → Prop) [DecidableRel lt] {t : rbnode α} (x : α) {c : color} {n : ℕ} (h : is_red_black t c n) : insert_rb_result (insert lt t x) c n := sorry theorem insert_is_red_black {α : Type u} (lt : α → α → Prop) [DecidableRel lt] {t : rbnode α} {c : color} {n : ℕ} (x : α) : is_red_black t c n → ∃ (c : color), ∃ (n : ℕ), is_red_black (insert lt t x) c n := sorry
4345dfba7c3d18285c623db2f813a7c8be36dd45
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/topology/metric_space/emetric_space.lean
202540918cb66235764d38eb9c36f20e38875a7d
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
45,897
lean
/- Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel -/ import data.nat.interval import data.real.ennreal import topology.uniform_space.pi import topology.uniform_space.uniform_convergence import topology.uniform_space.uniform_embedding /-! # Extended metric spaces This file is devoted to the definition and study of `emetric_spaces`, i.e., metric spaces in which the distance is allowed to take the value ∞. This extended distance is called `edist`, and takes values in `ℝ≥0∞`. Many definitions and theorems expected on emetric spaces are already introduced on uniform spaces and topological spaces. For example: open and closed sets, compactness, completeness, continuity and uniform continuity. The class `emetric_space` therefore extends `uniform_space` (and `topological_space`). Since a lot of elementary properties don't require `eq_of_edist_eq_zero` we start setting up the theory of `pseudo_emetric_space`, where we don't require `edist x y = 0 → x = y` and we specialize to `emetric_space` at the end. -/ open set filter classical noncomputable theory open_locale uniformity topological_space big_operators filter nnreal ennreal universes u v w variables {α : Type u} {β : Type v} /-- Characterizing uniformities associated to a (generalized) distance function `D` in terms of the elements of the uniformity. -/ theorem uniformity_dist_of_mem_uniformity [linear_order β] {U : filter (α × α)} (z : β) (D : α → α → β) (H : ∀ s, s ∈ U ↔ ∃ε>z, ∀{a b:α}, D a b < ε → (a, b) ∈ s) : U = ⨅ ε>z, 𝓟 {p:α×α | D p.1 p.2 < ε} := le_antisymm (le_infi $ λ ε, le_infi $ λ ε0, le_principal_iff.2 $ (H _).2 ⟨ε, ε0, λ a b, id⟩) (λ r ur, let ⟨ε, ε0, h⟩ := (H _).1 ur in mem_infi_of_mem ε $ mem_infi_of_mem ε0 $ mem_principal.2 $ λ ⟨a, b⟩, h) /-- `has_edist α` means that `α` is equipped with an extended distance. -/ class has_edist (α : Type*) := (edist : α → α → ℝ≥0∞) export has_edist (edist) /-- Creating a uniform space from an extended distance. -/ def uniform_space_of_edist (edist : α → α → ℝ≥0∞) (edist_self : ∀ x : α, edist x x = 0) (edist_comm : ∀ x y : α, edist x y = edist y x) (edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) : uniform_space α := uniform_space.of_core { uniformity := (⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε}), refl := le_infi $ assume ε, le_infi $ by simp [set.subset_def, id_rel, edist_self, (>)] {contextual := tt}, comp := le_infi $ assume ε, le_infi $ assume h, have (2 : ℝ≥0∞) = (2 : ℕ) := by simp, have A : 0 < ε / 2 := ennreal.div_pos_iff.2 ⟨ne_of_gt h, by { convert ennreal.nat_ne_top 2 }⟩, lift'_le (mem_infi_of_mem (ε / 2) $ mem_infi_of_mem A (subset.refl _)) $ have ∀ (a b c : α), edist a c < ε / 2 → edist c b < ε / 2 → edist a b < ε, from assume a b c hac hcb, calc edist a b ≤ edist a c + edist c b : edist_triangle _ _ _ ... < ε / 2 + ε / 2 : ennreal.add_lt_add hac hcb ... = ε : by rw [ennreal.add_halves], by simpa [comp_rel], symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h, tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [edist_comm] } -- the uniform structure is embedded in the emetric space structure -- to avoid instance diamond issues. See Note [forgetful inheritance]. /-- Extended (pseudo) metric spaces, with an extended distance `edist` possibly taking the value ∞ Each pseudo_emetric space induces a canonical `uniform_space` and hence a canonical `topological_space`. This is enforced in the type class definition, by extending the `uniform_space` structure. When instantiating a `pseudo_emetric_space` structure, the uniformity fields are not necessary, they will be filled in by default. There is a default value for the uniformity, that can be substituted in cases of interest, for instance when instantiating a `pseudo_emetric_space` structure on a product. Continuity of `edist` is proved in `topology.instances.ennreal` -/ class pseudo_emetric_space (α : Type u) extends has_edist α : Type u := (edist_self : ∀ x : α, edist x x = 0) (edist_comm : ∀ x y : α, edist x y = edist y x) (edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) (to_uniform_space : uniform_space α := uniform_space_of_edist edist edist_self edist_comm edist_triangle) (uniformity_edist : 𝓤 α = ⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε} . control_laws_tac) /- Pseudoemetric spaces are less common than metric spaces. Therefore, we work in a dedicated namespace, while notions associated to metric spaces are mostly in the root namespace. -/ variables [pseudo_emetric_space α] @[priority 100] -- see Note [lower instance priority] instance pseudo_emetric_space.to_uniform_space' : uniform_space α := pseudo_emetric_space.to_uniform_space export pseudo_emetric_space (edist_self edist_comm edist_triangle) attribute [simp] edist_self /-- Triangle inequality for the extended distance -/ theorem edist_triangle_left (x y z : α) : edist x y ≤ edist z x + edist z y := by rw edist_comm z; apply edist_triangle theorem edist_triangle_right (x y z : α) : edist x y ≤ edist x z + edist y z := by rw edist_comm y; apply edist_triangle lemma edist_triangle4 (x y z t : α) : edist x t ≤ edist x y + edist y z + edist z t := calc edist x t ≤ edist x z + edist z t : edist_triangle x z t ... ≤ (edist x y + edist y z) + edist z t : add_le_add_right (edist_triangle x y z) _ /-- The triangle (polygon) inequality for sequences of points; `finset.Ico` version. -/ lemma edist_le_Ico_sum_edist (f : ℕ → α) {m n} (h : m ≤ n) : edist (f m) (f n) ≤ ∑ i in finset.Ico m n, edist (f i) (f (i + 1)) := begin revert n, refine nat.le_induction _ _, { simp only [finset.sum_empty, finset.Ico_self, edist_self], -- TODO: Why doesn't Lean close this goal automatically? `apply le_refl` fails too. exact le_refl (0:ℝ≥0∞) }, { assume n hn hrec, calc edist (f m) (f (n+1)) ≤ edist (f m) (f n) + edist (f n) (f (n+1)) : edist_triangle _ _ _ ... ≤ ∑ i in finset.Ico m n, _ + _ : add_le_add hrec le_rfl ... = ∑ i in finset.Ico m (n+1), _ : by rw [nat.Ico_succ_right_eq_insert_Ico hn, finset.sum_insert, add_comm]; simp } end /-- The triangle (polygon) inequality for sequences of points; `finset.range` version. -/ lemma edist_le_range_sum_edist (f : ℕ → α) (n : ℕ) : edist (f 0) (f n) ≤ ∑ i in finset.range n, edist (f i) (f (i + 1)) := nat.Ico_zero_eq_range n ▸ edist_le_Ico_sum_edist f (nat.zero_le n) /-- A version of `edist_le_Ico_sum_edist` with each intermediate distance replaced with an upper estimate. -/ lemma edist_le_Ico_sum_of_edist_le {f : ℕ → α} {m n} (hmn : m ≤ n) {d : ℕ → ℝ≥0∞} (hd : ∀ {k}, m ≤ k → k < n → edist (f k) (f (k + 1)) ≤ d k) : edist (f m) (f n) ≤ ∑ i in finset.Ico m n, d i := le_trans (edist_le_Ico_sum_edist f hmn) $ finset.sum_le_sum $ λ k hk, hd (finset.mem_Ico.1 hk).1 (finset.mem_Ico.1 hk).2 /-- A version of `edist_le_range_sum_edist` with each intermediate distance replaced with an upper estimate. -/ lemma edist_le_range_sum_of_edist_le {f : ℕ → α} (n : ℕ) {d : ℕ → ℝ≥0∞} (hd : ∀ {k}, k < n → edist (f k) (f (k + 1)) ≤ d k) : edist (f 0) (f n) ≤ ∑ i in finset.range n, d i := nat.Ico_zero_eq_range n ▸ edist_le_Ico_sum_of_edist_le (zero_le n) (λ _ _, hd) /-- Reformulation of the uniform structure in terms of the extended distance -/ theorem uniformity_pseudoedist : 𝓤 α = ⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε} := pseudo_emetric_space.uniformity_edist theorem uniformity_basis_edist : (𝓤 α).has_basis (λ ε : ℝ≥0∞, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 < ε}) := (@uniformity_pseudoedist α _).symm ▸ has_basis_binfi_principal (λ r hr p hp, ⟨min r p, lt_min hr hp, λ x hx, lt_of_lt_of_le hx (min_le_left _ _), λ x hx, lt_of_lt_of_le hx (min_le_right _ _)⟩) ⟨1, ennreal.zero_lt_one⟩ /-- Characterization of the elements of the uniformity in terms of the extended distance -/ theorem mem_uniformity_edist {s : set (α×α)} : s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, edist a b < ε → (a, b) ∈ s) := uniformity_basis_edist.mem_uniformity_iff /-- Given `f : β → ℝ≥0∞`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`. For specific bases see `uniformity_basis_edist`, `uniformity_basis_edist'`, `uniformity_basis_edist_nnreal`, and `uniformity_basis_edist_inv_nat`. -/ protected theorem emetric.mk_uniformity_basis {β : Type*} {p : β → Prop} {f : β → ℝ≥0∞} (hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) : (𝓤 α).has_basis p (λ x, {p:α×α | edist p.1 p.2 < f x}) := begin refine ⟨λ s, uniformity_basis_edist.mem_iff.trans _⟩, split, { rintros ⟨ε, ε₀, hε⟩, rcases hf ε ε₀ with ⟨i, hi, H⟩, exact ⟨i, hi, λ x hx, hε $ lt_of_lt_of_le hx H⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, H⟩ } end /-- Given `f : β → ℝ≥0∞`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then closed `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`. For specific bases see `uniformity_basis_edist_le` and `uniformity_basis_edist_le'`. -/ protected theorem emetric.mk_uniformity_basis_le {β : Type*} {p : β → Prop} {f : β → ℝ≥0∞} (hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) : (𝓤 α).has_basis p (λ x, {p:α×α | edist p.1 p.2 ≤ f x}) := begin refine ⟨λ s, uniformity_basis_edist.mem_iff.trans _⟩, split, { rintros ⟨ε, ε₀, hε⟩, rcases exists_between ε₀ with ⟨ε', hε'⟩, rcases hf ε' hε'.1 with ⟨i, hi, H⟩, exact ⟨i, hi, λ x hx, hε $ lt_of_le_of_lt (le_trans hx H) hε'.2⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, λ x hx, H (le_of_lt hx)⟩ } end theorem uniformity_basis_edist_le : (𝓤 α).has_basis (λ ε : ℝ≥0∞, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 ≤ ε}) := emetric.mk_uniformity_basis_le (λ _, id) (λ ε ε₀, ⟨ε, ε₀, le_refl ε⟩) theorem uniformity_basis_edist' (ε' : ℝ≥0∞) (hε' : 0 < ε') : (𝓤 α).has_basis (λ ε : ℝ≥0∞, ε ∈ Ioo 0 ε') (λ ε, {p:α×α | edist p.1 p.2 < ε}) := emetric.mk_uniformity_basis (λ _, and.left) (λ ε ε₀, let ⟨δ, hδ⟩ := exists_between hε' in ⟨min ε δ, ⟨lt_min ε₀ hδ.1, lt_of_le_of_lt (min_le_right _ _) hδ.2⟩, min_le_left _ _⟩) theorem uniformity_basis_edist_le' (ε' : ℝ≥0∞) (hε' : 0 < ε') : (𝓤 α).has_basis (λ ε : ℝ≥0∞, ε ∈ Ioo 0 ε') (λ ε, {p:α×α | edist p.1 p.2 ≤ ε}) := emetric.mk_uniformity_basis_le (λ _, and.left) (λ ε ε₀, let ⟨δ, hδ⟩ := exists_between hε' in ⟨min ε δ, ⟨lt_min ε₀ hδ.1, lt_of_le_of_lt (min_le_right _ _) hδ.2⟩, min_le_left _ _⟩) theorem uniformity_basis_edist_nnreal : (𝓤 α).has_basis (λ ε : ℝ≥0, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 < ε}) := emetric.mk_uniformity_basis (λ _, ennreal.coe_pos.2) (λ ε ε₀, let ⟨δ, hδ⟩ := ennreal.lt_iff_exists_nnreal_btwn.1 ε₀ in ⟨δ, ennreal.coe_pos.1 hδ.1, le_of_lt hδ.2⟩) theorem uniformity_basis_edist_inv_nat : (𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | edist p.1 p.2 < (↑n)⁻¹}) := emetric.mk_uniformity_basis (λ n _, ennreal.inv_pos.2 $ ennreal.nat_ne_top n) (λ ε ε₀, let ⟨n, hn⟩ := ennreal.exists_inv_nat_lt (ne_of_gt ε₀) in ⟨n, trivial, le_of_lt hn⟩) theorem uniformity_basis_edist_inv_two_pow : (𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | edist p.1 p.2 < 2⁻¹ ^ n}) := emetric.mk_uniformity_basis (λ n _, ennreal.pow_pos (ennreal.inv_pos.2 ennreal.two_ne_top) _) (λ ε ε₀, let ⟨n, hn⟩ := ennreal.exists_inv_two_pow_lt (ne_of_gt ε₀) in ⟨n, trivial, le_of_lt hn⟩) /-- Fixed size neighborhoods of the diagonal belong to the uniform structure -/ theorem edist_mem_uniformity {ε:ℝ≥0∞} (ε0 : 0 < ε) : {p:α×α | edist p.1 p.2 < ε} ∈ 𝓤 α := mem_uniformity_edist.2 ⟨ε, ε0, λ a b, id⟩ namespace emetric @[priority 900] instance : is_countably_generated (𝓤 α) := is_countably_generated_of_seq ⟨_, uniformity_basis_edist_inv_nat.eq_infi⟩ /-- ε-δ characterization of uniform continuity on a set for pseudoemetric spaces -/ theorem uniform_continuous_on_iff [pseudo_emetric_space β] {f : α → β} {s : set α} : uniform_continuous_on f s ↔ ∀ ε > 0, ∃ δ > 0, ∀{a b}, a ∈ s → b ∈ s → edist a b < δ → edist (f a) (f b) < ε := uniformity_basis_edist.uniform_continuous_on_iff uniformity_basis_edist /-- ε-δ characterization of uniform continuity on pseudoemetric spaces -/ theorem uniform_continuous_iff [pseudo_emetric_space β] {f : α → β} : uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0, ∀{a b:α}, edist a b < δ → edist (f a) (f b) < ε := uniformity_basis_edist.uniform_continuous_iff uniformity_basis_edist /-- ε-δ characterization of uniform embeddings on pseudoemetric spaces -/ theorem uniform_embedding_iff [pseudo_emetric_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ := uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl ⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (edist_mem_uniformity δ0), ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 tu in ⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩, λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_edist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in ⟨_, edist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩ /-- If a map between pseudoemetric spaces is a uniform embedding then the edistance between `f x` and `f y` is controlled in terms of the distance between `x` and `y`. -/ theorem controlled_of_uniform_embedding [pseudo_emetric_space β] {f : α → β} : uniform_embedding f → (∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, edist a b < δ → edist (f a) (f b) < ε) ∧ (∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ) := begin assume h, exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1, (uniform_embedding_iff.1 h).2.2⟩, end /-- ε-δ characterization of Cauchy sequences on pseudoemetric spaces -/ protected lemma cauchy_iff {f : filter α} : cauchy f ↔ f ≠ ⊥ ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, edist x y < ε := by rw ← ne_bot_iff; exact uniformity_basis_edist.cauchy_iff /-- A very useful criterion to show that a space is complete is to show that all sequences which satisfy a bound of the form `edist (u n) (u m) < B N` for all `n m ≥ N` are converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to `0`, which makes it possible to use arguments of converging series, while this is impossible to do in general for arbitrary Cauchy sequences. -/ theorem complete_of_convergent_controlled_sequences (B : ℕ → ℝ≥0∞) (hB : ∀n, 0 < B n) (H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → edist (u n) (u m) < B N) → ∃x, tendsto u at_top (𝓝 x)) : complete_space α := uniform_space.complete_of_convergent_controlled_sequences (λ n, {p:α×α | edist p.1 p.2 < B n}) (λ n, edist_mem_uniformity $ hB n) H /-- A sequentially complete pseudoemetric space is complete. -/ theorem complete_of_cauchy_seq_tendsto : (∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) → complete_space α := uniform_space.complete_of_cauchy_seq_tendsto /-- Expressing locally uniform convergence on a set using `edist`. -/ lemma tendsto_locally_uniformly_on_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_locally_uniformly_on F f p s ↔ ∀ ε > 0, ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, ∀ᶠ n in p, ∀ y ∈ t, edist (f y) (F n y) < ε := begin refine ⟨λ H ε hε, H _ (edist_mem_uniformity hε), λ H u hu x hx, _⟩, rcases mem_uniformity_edist.1 hu with ⟨ε, εpos, hε⟩, rcases H ε εpos x hx with ⟨t, ht, Ht⟩, exact ⟨t, ht, Ht.mono (λ n hs x hx, hε (hs x hx))⟩ end /-- Expressing uniform convergence on a set using `edist`. -/ lemma tendsto_uniformly_on_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_uniformly_on F f p s ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x ∈ s, edist (f x) (F n x) < ε := begin refine ⟨λ H ε hε, H _ (edist_mem_uniformity hε), λ H u hu, _⟩, rcases mem_uniformity_edist.1 hu with ⟨ε, εpos, hε⟩, exact (H ε εpos).mono (λ n hs x hx, hε (hs x hx)) end /-- Expressing locally uniform convergence using `edist`. -/ lemma tendsto_locally_uniformly_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_locally_uniformly F f p ↔ ∀ ε > 0, ∀ (x : β), ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, edist (f y) (F n y) < ε := by simp only [← tendsto_locally_uniformly_on_univ, tendsto_locally_uniformly_on_iff, mem_univ, forall_const, exists_prop, nhds_within_univ] /-- Expressing uniform convergence using `edist`. -/ lemma tendsto_uniformly_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_uniformly F f p ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x, edist (f x) (F n x) < ε := by simp only [← tendsto_uniformly_on_univ, tendsto_uniformly_on_iff, mem_univ, forall_const] end emetric open emetric /-- Auxiliary function to replace the uniformity on a pseudoemetric space with a uniformity which is equal to the original one, but maybe not defeq. This is useful if one wants to construct a pseudoemetric space with a specified uniformity. See Note [forgetful inheritance] explaining why having definitionally the right uniformity is often important. -/ def pseudo_emetric_space.replace_uniformity {α} [U : uniform_space α] (m : pseudo_emetric_space α) (H : @uniformity _ U = @uniformity _ pseudo_emetric_space.to_uniform_space) : pseudo_emetric_space α := { edist := @edist _ m.to_has_edist, edist_self := edist_self, edist_comm := edist_comm, edist_triangle := edist_triangle, to_uniform_space := U, uniformity_edist := H.trans (@pseudo_emetric_space.uniformity_edist α _) } /-- The extended pseudometric induced by a function taking values in a pseudoemetric space. -/ def pseudo_emetric_space.induced {α β} (f : α → β) (m : pseudo_emetric_space β) : pseudo_emetric_space α := { edist := λ x y, edist (f x) (f y), edist_self := λ x, edist_self _, edist_comm := λ x y, edist_comm _ _, edist_triangle := λ x y z, edist_triangle _ _ _, to_uniform_space := uniform_space.comap f m.to_uniform_space, uniformity_edist := begin apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, edist (f x) (f y)), refine λ s, mem_comap.trans _, split; intro H, { rcases H with ⟨r, ru, rs⟩, rcases mem_uniformity_edist.1 ru with ⟨ε, ε0, hε⟩, refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h }, { rcases H with ⟨ε, ε0, hε⟩, exact ⟨_, edist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ } end } /-- Pseudoemetric space instance on subsets of pseudoemetric spaces -/ instance {α : Type*} {p : α → Prop} [t : pseudo_emetric_space α] : pseudo_emetric_space (subtype p) := t.induced coe /-- The extended psuedodistance on a subset of a pseudoemetric space is the restriction of the original pseudodistance, by definition -/ theorem subtype.edist_eq {p : α → Prop} (x y : subtype p) : edist x y = edist (x : α) y := rfl /-- The product of two pseudoemetric spaces, with the max distance, is an extended pseudometric spaces. We make sure that the uniform structure thus constructed is the one corresponding to the product of uniform spaces, to avoid diamond problems. -/ instance prod.pseudo_emetric_space_max [pseudo_emetric_space β] : pseudo_emetric_space (α × β) := { edist := λ x y, max (edist x.1 y.1) (edist x.2 y.2), edist_self := λ x, by simp, edist_comm := λ x y, by simp [edist_comm], edist_triangle := λ x y z, max_le (le_trans (edist_triangle _ _ _) (add_le_add (le_max_left _ _) (le_max_left _ _))) (le_trans (edist_triangle _ _ _) (add_le_add (le_max_right _ _) (le_max_right _ _))), uniformity_edist := begin refine uniformity_prod.trans _, simp [pseudo_emetric_space.uniformity_edist, comap_infi], rw ← infi_inf_eq, congr, funext, rw ← infi_inf_eq, congr, funext, simp [inf_principal, ext_iff, max_lt_iff] end, to_uniform_space := prod.uniform_space } lemma prod.edist_eq [pseudo_emetric_space β] (x y : α × β) : edist x y = max (edist x.1 y.1) (edist x.2 y.2) := rfl section pi open finset variables {π : β → Type*} [fintype β] /-- The product of a finite number of pseudoemetric spaces, with the max distance, is still a pseudoemetric space. This construction would also work for infinite products, but it would not give rise to the product topology. Hence, we only formalize it in the good situation of finitely many spaces. -/ instance pseudo_emetric_space_pi [∀b, pseudo_emetric_space (π b)] : pseudo_emetric_space (Πb, π b) := { edist := λ f g, finset.sup univ (λb, edist (f b) (g b)), edist_self := assume f, bot_unique $ finset.sup_le $ by simp, edist_comm := assume f g, by unfold edist; congr; funext a; exact edist_comm _ _, edist_triangle := assume f g h, begin simp only [finset.sup_le_iff], assume b hb, exact le_trans (edist_triangle _ (g b) _) (add_le_add (le_sup hb) (le_sup hb)) end, to_uniform_space := Pi.uniform_space _, uniformity_edist := begin simp only [Pi.uniformity, pseudo_emetric_space.uniformity_edist, comap_infi, gt_iff_lt, preimage_set_of_eq, comap_principal], rw infi_comm, congr, funext ε, rw infi_comm, congr, funext εpos, change 0 < ε at εpos, simp [set.ext_iff, εpos] end } lemma edist_pi_def [Π b, pseudo_emetric_space (π b)] (f g : Π b, π b) : edist f g = finset.sup univ (λb, edist (f b) (g b)) := rfl @[simp] lemma edist_pi_const [nonempty β] (a b : α) : edist (λ x : β, a) (λ _, b) = edist a b := finset.sup_const univ_nonempty (edist a b) lemma edist_le_pi_edist [Π b, pseudo_emetric_space (π b)] (f g : Π b, π b) (b : β) : edist (f b) (g b) ≤ edist f g := finset.le_sup (finset.mem_univ b) lemma edist_pi_le_iff [Π b, pseudo_emetric_space (π b)] {f g : Π b, π b} {d : ℝ≥0∞} : edist f g ≤ d ↔ ∀ b, edist (f b) (g b) ≤ d := finset.sup_le_iff.trans $ by simp only [finset.mem_univ, forall_const] end pi namespace emetric variables {x y z : α} {ε ε₁ ε₂ : ℝ≥0∞} {s : set α} /-- `emetric.ball x ε` is the set of all points `y` with `edist y x < ε` -/ def ball (x : α) (ε : ℝ≥0∞) : set α := {y | edist y x < ε} @[simp] theorem mem_ball : y ∈ ball x ε ↔ edist y x < ε := iff.rfl theorem mem_ball' : y ∈ ball x ε ↔ edist x y < ε := by rw edist_comm; refl /-- `emetric.closed_ball x ε` is the set of all points `y` with `edist y x ≤ ε` -/ def closed_ball (x : α) (ε : ℝ≥0∞) := {y | edist y x ≤ ε} @[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ edist y x ≤ ε := iff.rfl @[simp] theorem closed_ball_top (x : α) : closed_ball x ∞ = univ := eq_univ_of_forall $ λ y, @le_top _ _ (edist y x) theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε := assume y hy, le_of_lt hy theorem pos_of_mem_ball (hy : y ∈ ball x ε) : 0 < ε := lt_of_le_of_lt (zero_le _) hy theorem mem_ball_self (h : 0 < ε) : x ∈ ball x ε := show edist x x < ε, by rw edist_self; assumption theorem mem_closed_ball_self : x ∈ closed_ball x ε := show edist x x ≤ ε, by rw edist_self; exact bot_le theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε := by simp [edist_comm] theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ := λ y (yx : _ < ε₁), lt_of_lt_of_le yx h theorem closed_ball_subset_closed_ball (h : ε₁ ≤ ε₂) : closed_ball x ε₁ ⊆ closed_ball x ε₂ := λ y (yx : _ ≤ ε₁), le_trans yx h theorem ball_disjoint (h : ε₁ + ε₂ ≤ edist x y) : ball x ε₁ ∩ ball y ε₂ = ∅ := eq_empty_iff_forall_not_mem.2 $ λ z ⟨h₁, h₂⟩, not_lt_of_le (edist_triangle_left x y z) (lt_of_lt_of_le (ennreal.add_lt_add h₁ h₂) h) theorem ball_subset (h : edist x y + ε₁ ≤ ε₂) (h' : edist x y ≠ ∞) : ball x ε₁ ⊆ ball y ε₂ := λ z zx, calc edist z y ≤ edist z x + edist x y : edist_triangle _ _ _ ... = edist x y + edist z x : add_comm _ _ ... < edist x y + ε₁ : ennreal.add_lt_add_left h' zx ... ≤ ε₂ : h theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε := begin have : 0 < ε - edist y x := by simpa using h, refine ⟨ε - edist y x, this, ball_subset _ (ne_top_of_lt h)⟩, exact (add_tsub_cancel_of_le (mem_ball.mp h).le).le end theorem ball_eq_empty_iff : ball x ε = ∅ ↔ ε = 0 := eq_empty_iff_forall_not_mem.trans ⟨λh, le_bot_iff.1 (le_of_not_gt (λ ε0, h _ (mem_ball_self ε0))), λε0 y h, not_lt_of_le (le_of_eq ε0) (pos_of_mem_ball h)⟩ /-- Relation “two points are at a finite edistance” is an equivalence relation. -/ def edist_lt_top_setoid : setoid α := { r := λ x y, edist x y < ⊤, iseqv := ⟨λ x, by { rw edist_self, exact ennreal.coe_lt_top }, λ x y h, by rwa edist_comm, λ x y z hxy hyz, lt_of_le_of_lt (edist_triangle x y z) (ennreal.add_lt_top.2 ⟨hxy, hyz⟩)⟩ } @[simp] lemma ball_zero : ball x 0 = ∅ := by rw [emetric.ball_eq_empty_iff] theorem nhds_basis_eball : (𝓝 x).has_basis (λ ε:ℝ≥0∞, 0 < ε) (ball x) := nhds_basis_uniformity uniformity_basis_edist theorem nhds_basis_closed_eball : (𝓝 x).has_basis (λ ε:ℝ≥0∞, 0 < ε) (closed_ball x) := nhds_basis_uniformity uniformity_basis_edist_le theorem nhds_eq : 𝓝 x = (⨅ε>0, 𝓟 (ball x ε)) := nhds_basis_eball.eq_binfi theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ε>0, ball x ε ⊆ s := nhds_basis_eball.mem_iff theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s := by simp [is_open_iff_nhds, mem_nhds_iff] theorem is_open_ball : is_open (ball x ε) := is_open_iff.2 $ λ y, exists_ball_subset_ball theorem is_closed_ball_top : is_closed (ball x ⊤) := is_open_compl_iff.1 $ is_open_iff.2 $ λ y hy, ⟨⊤, ennreal.coe_lt_top, subset_compl_iff_disjoint.2 $ ball_disjoint $ by { rw ennreal.top_add, exact le_of_not_lt hy }⟩ theorem ball_mem_nhds (x : α) {ε : ℝ≥0∞} (ε0 : 0 < ε) : ball x ε ∈ 𝓝 x := is_open_ball.mem_nhds (mem_ball_self ε0) theorem closed_ball_mem_nhds (x : α) {ε : ℝ≥0∞} (ε0 : 0 < ε) : closed_ball x ε ∈ 𝓝 x := mem_of_superset (ball_mem_nhds x ε0) ball_subset_closed_ball theorem ball_prod_same [pseudo_emetric_space β] (x : α) (y : β) (r : ℝ≥0∞) : (ball x r).prod (ball y r) = ball (x, y) r := ext $ λ z, max_lt_iff.symm theorem closed_ball_prod_same [pseudo_emetric_space β] (x : α) (y : β) (r : ℝ≥0∞) : (closed_ball x r).prod (closed_ball y r) = closed_ball (x, y) r := ext $ λ z, max_le_iff.symm /-- ε-characterization of the closure in pseudoemetric spaces -/ theorem mem_closure_iff : x ∈ closure s ↔ ∀ε>0, ∃y ∈ s, edist x y < ε := (mem_closure_iff_nhds_basis nhds_basis_eball).trans $ by simp only [mem_ball, edist_comm x] theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, edist (u x) a < ε := nhds_basis_eball.tendsto_right_iff theorem tendsto_at_top [nonempty β] [semilattice_sup β] {u : β → α} {a : α} : tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, edist (u n) a < ε := (at_top_basis.tendsto_iff nhds_basis_eball).trans $ by simp only [exists_prop, true_and, mem_Ici, mem_ball] /-- In a pseudoemetric space, Cauchy sequences are characterized by the fact that, eventually, the pseudoedistance between its elements is arbitrarily small -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem cauchy_seq_iff [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, edist (u m) (u n) < ε := uniformity_basis_edist.cauchy_seq_iff /-- A variation around the emetric characterization of Cauchy sequences -/ theorem cauchy_seq_iff' [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ε>(0 : ℝ≥0∞), ∃N, ∀n≥N, edist (u n) (u N) < ε := uniformity_basis_edist.cauchy_seq_iff' /-- A variation of the emetric characterization of Cauchy sequences that deals with `ℝ≥0` upper bounds. -/ theorem cauchy_seq_iff_nnreal [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ ε : ℝ≥0, 0 < ε → ∃ N, ∀ n, N ≤ n → edist (u n) (u N) < ε := uniformity_basis_edist_nnreal.cauchy_seq_iff' theorem totally_bounded_iff {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t : set α, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, H _ (edist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨t, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ theorem totally_bounded_iff' {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t⊆s, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, (totally_bounded_iff_subset.1 H) _ (edist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨t, _, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ section compact /-- For a set `s` in a pseudo emetric space, if for every `ε > 0` there exists a countable set that is `ε`-dense in `s`, then there exists a countable subset `t ⊆ s` that is dense in `s`. -/ lemma subset_countable_closure_of_almost_dense_set (s : set α) (hs : ∀ ε > 0, ∃ t : set α, countable t ∧ s ⊆ ⋃ x ∈ t, closed_ball x ε) : ∃ t ⊆ s, (countable t ∧ s ⊆ closure t) := begin rcases s.eq_empty_or_nonempty with rfl|⟨x₀, hx₀⟩, { exact ⟨∅, empty_subset _, countable_empty, empty_subset _⟩ }, choose! T hTc hsT using (λ n : ℕ, hs n⁻¹ (by simp)), have : ∀ r x, ∃ y ∈ s, closed_ball x r ∩ s ⊆ closed_ball y (r * 2), { intros r x, rcases (closed_ball x r ∩ s).eq_empty_or_nonempty with he|⟨y, hxy, hys⟩, { refine ⟨x₀, hx₀, _⟩, rw he, exact empty_subset _ }, { refine ⟨y, hys, λ z hz, _⟩, calc edist z y ≤ edist z x + edist y x : edist_triangle_right _ _ _ ... ≤ r + r : add_le_add hz.1 hxy ... = r * 2 : (mul_two r).symm } }, choose f hfs hf, refine ⟨⋃ n : ℕ, (f n⁻¹) '' (T n), Union_subset $ λ n, image_subset_iff.2 (λ z hz, hfs _ _), countable_Union $ λ n, (hTc n).image _, _⟩, refine λ x hx, mem_closure_iff.2 (λ ε ε0, _), rcases ennreal.exists_inv_nat_lt (ennreal.half_pos ε0.lt.ne').ne' with ⟨n, hn⟩, rcases mem_bUnion_iff.1 (hsT n hx) with ⟨y, hyn, hyx⟩, refine ⟨f n⁻¹ y, mem_Union.2 ⟨n, mem_image_of_mem _ hyn⟩, _⟩, calc edist x (f n⁻¹ y) ≤ n⁻¹ * 2 : hf _ _ ⟨hyx, hx⟩ ... < ε : ennreal.mul_lt_of_lt_div hn end /-- A compact set in a pseudo emetric space is separable, i.e., it is a subset of the closure of a countable set. -/ lemma subset_countable_closure_of_compact {s : set α} (hs : is_compact s) : ∃ t ⊆ s, (countable t ∧ s ⊆ closure t) := begin refine subset_countable_closure_of_almost_dense_set s (λ ε hε, _), rcases totally_bounded_iff'.1 hs.totally_bounded ε hε with ⟨t, hts, htf, hst⟩, exact ⟨t, htf.countable, subset.trans hst (bUnion_mono $ λ _ _, ball_subset_closed_ball)⟩ end end compact section second_countable open _root_.topological_space variables (α) /-- A sigma compact pseudo emetric space has second countable topology. This is not an instance to avoid a loop with `sigma_compact_space_of_locally_compact_second_countable`. -/ lemma second_countable_of_sigma_compact [sigma_compact_space α] : second_countable_topology α := begin suffices : separable_space α, by exactI uniform_space.second_countable_of_separable α, choose T hTsub hTc hsubT using λ n, subset_countable_closure_of_compact (is_compact_compact_covering α n), refine ⟨⟨⋃ n, T n, countable_Union hTc, λ x, _⟩⟩, rcases Union_eq_univ_iff.1 (Union_compact_covering α) x with ⟨n, hn⟩, exact closure_mono (subset_Union _ n) (hsubT _ hn) end variable {α} lemma second_countable_of_almost_dense_set (hs : ∀ ε > 0, ∃ t : set α, countable t ∧ (⋃ x ∈ t, closed_ball x ε) = univ) : second_countable_topology α := begin suffices : separable_space α, by exactI uniform_space.second_countable_of_separable α, rcases subset_countable_closure_of_almost_dense_set (univ : set α) (λ ε ε0, _) with ⟨t, -, htc, ht⟩, { exact ⟨⟨t, htc, λ x, ht (mem_univ x)⟩⟩ }, { rcases hs ε ε0 with ⟨t, htc, ht⟩, exact ⟨t, htc, univ_subset_iff.2 ht⟩ } end end second_countable section diam /-- The diameter of a set in a pseudoemetric space, named `emetric.diam` -/ def diam (s : set α) := ⨆ (x ∈ s) (y ∈ s), edist x y lemma diam_le_iff {d : ℝ≥0∞} : diam s ≤ d ↔ ∀ (x ∈ s) (y ∈ s), edist x y ≤ d := by simp only [diam, supr_le_iff] lemma diam_image_le_iff {d : ℝ≥0∞} {f : β → α} {s : set β} : diam (f '' s) ≤ d ↔ ∀ (x ∈ s) (y ∈ s), edist (f x) (f y) ≤ d := by simp only [diam_le_iff, ball_image_iff] lemma edist_le_of_diam_le {d} (hx : x ∈ s) (hy : y ∈ s) (hd : diam s ≤ d) : edist x y ≤ d := diam_le_iff.1 hd x hx y hy /-- If two points belong to some set, their edistance is bounded by the diameter of the set -/ lemma edist_le_diam_of_mem (hx : x ∈ s) (hy : y ∈ s) : edist x y ≤ diam s := edist_le_of_diam_le hx hy le_rfl /-- If the distance between any two points in a set is bounded by some constant, this constant bounds the diameter. -/ lemma diam_le {d : ℝ≥0∞} (h : ∀ (x ∈ s) (y ∈ s), edist x y ≤ d) : diam s ≤ d := diam_le_iff.2 h /-- The diameter of a subsingleton vanishes. -/ lemma diam_subsingleton (hs : s.subsingleton) : diam s = 0 := nonpos_iff_eq_zero.1 $ diam_le $ λ x hx y hy, (hs hx hy).symm ▸ edist_self y ▸ le_rfl /-- The diameter of the empty set vanishes -/ @[simp] lemma diam_empty : diam (∅ : set α) = 0 := diam_subsingleton subsingleton_empty /-- The diameter of a singleton vanishes -/ @[simp] lemma diam_singleton : diam ({x} : set α) = 0 := diam_subsingleton subsingleton_singleton lemma diam_Union_mem_option {ι : Type*} (o : option ι) (s : ι → set α) : diam (⋃ i ∈ o, s i) = ⨆ i ∈ o, diam (s i) := by cases o; simp lemma diam_insert : diam (insert x s) = max (⨆ y ∈ s, edist x y) (diam s) := eq_of_forall_ge_iff $ λ d, by simp only [diam_le_iff, ball_insert_iff, edist_self, edist_comm x, max_le_iff, supr_le_iff, zero_le, true_and, forall_and_distrib, and_self, ← and_assoc] lemma diam_pair : diam ({x, y} : set α) = edist x y := by simp only [supr_singleton, diam_insert, diam_singleton, ennreal.max_zero_right] lemma diam_triple : diam ({x, y, z} : set α) = max (max (edist x y) (edist x z)) (edist y z) := by simp only [diam_insert, supr_insert, supr_singleton, diam_singleton, ennreal.max_zero_right, ennreal.sup_eq_max] /-- The diameter is monotonous with respect to inclusion -/ lemma diam_mono {s t : set α} (h : s ⊆ t) : diam s ≤ diam t := diam_le $ λ x hx y hy, edist_le_diam_of_mem (h hx) (h hy) /-- The diameter of a union is controlled by the diameter of the sets, and the edistance between two points in the sets. -/ lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) : diam (s ∪ t) ≤ diam s + edist x y + diam t := begin have A : ∀a ∈ s, ∀b ∈ t, edist a b ≤ diam s + edist x y + diam t := λa ha b hb, calc edist a b ≤ edist a x + edist x y + edist y b : edist_triangle4 _ _ _ _ ... ≤ diam s + edist x y + diam t : add_le_add (add_le_add (edist_le_diam_of_mem ha xs) (le_refl _)) (edist_le_diam_of_mem yt hb), refine diam_le (λa ha b hb, _), cases (mem_union _ _ _).1 ha with h'a h'a; cases (mem_union _ _ _).1 hb with h'b h'b, { calc edist a b ≤ diam s : edist_le_diam_of_mem h'a h'b ... ≤ diam s + (edist x y + diam t) : le_self_add ... = diam s + edist x y + diam t : (add_assoc _ _ _).symm }, { exact A a h'a b h'b }, { have Z := A b h'b a h'a, rwa [edist_comm] at Z }, { calc edist a b ≤ diam t : edist_le_diam_of_mem h'a h'b ... ≤ (diam s + edist x y) + diam t : le_add_self } end lemma diam_union' {t : set α} (h : (s ∩ t).nonempty) : diam (s ∪ t) ≤ diam s + diam t := let ⟨x, ⟨xs, xt⟩⟩ := h in by simpa using diam_union xs xt lemma diam_closed_ball {r : ℝ≥0∞} : diam (closed_ball x r) ≤ 2 * r := diam_le $ λa ha b hb, calc edist a b ≤ edist a x + edist b x : edist_triangle_right _ _ _ ... ≤ r + r : add_le_add ha hb ... = 2 * r : (two_mul r).symm lemma diam_ball {r : ℝ≥0∞} : diam (ball x r) ≤ 2 * r := le_trans (diam_mono ball_subset_closed_ball) diam_closed_ball lemma diam_pi_le_of_le {π : β → Type*} [fintype β] [∀ b, pseudo_emetric_space (π b)] {s : Π (b : β), set (π b)} {c : ℝ≥0∞} (h : ∀ b, diam (s b) ≤ c) : diam (set.pi univ s) ≤ c := begin apply diam_le (λ x hx y hy, edist_pi_le_iff.mpr _), rw [mem_univ_pi] at hx hy, exact λ b, diam_le_iff.1 (h b) (x b) (hx b) (y b) (hy b), end end diam end emetric --namespace /-- We now define `emetric_space`, extending `pseudo_emetric_space`. -/ class emetric_space (α : Type u) extends pseudo_emetric_space α : Type u := (eq_of_edist_eq_zero : ∀ {x y : α}, edist x y = 0 → x = y) variables {γ : Type w} [emetric_space γ] @[priority 100] -- see Note [lower instance priority] instance emetric_space.to_uniform_space' : uniform_space γ := pseudo_emetric_space.to_uniform_space export emetric_space (eq_of_edist_eq_zero) /-- Characterize the equality of points by the vanishing of their extended distance -/ @[simp] theorem edist_eq_zero {x y : γ} : edist x y = 0 ↔ x = y := iff.intro eq_of_edist_eq_zero (assume : x = y, this ▸ edist_self _) @[simp] theorem zero_eq_edist {x y : γ} : 0 = edist x y ↔ x = y := iff.intro (assume h, eq_of_edist_eq_zero (h.symm)) (assume : x = y, this ▸ (edist_self _).symm) theorem edist_le_zero {x y : γ} : (edist x y ≤ 0) ↔ x = y := nonpos_iff_eq_zero.trans edist_eq_zero @[simp] theorem edist_pos {x y : γ} : 0 < edist x y ↔ x ≠ y := by simp [← not_le] /-- Two points coincide if their distance is `< ε` for all positive ε -/ theorem eq_of_forall_edist_le {x y : γ} (h : ∀ε > 0, edist x y ≤ ε) : x = y := eq_of_edist_eq_zero (eq_of_le_of_forall_le_of_dense bot_le h) /-- A map between emetric spaces is a uniform embedding if and only if the edistance between `f x` and `f y` is controlled in terms of the distance between `x` and `y` and conversely. -/ theorem uniform_embedding_iff' [emetric_space β] {f : γ → β} : uniform_embedding f ↔ (∀ ε > 0, ∃ δ > 0, ∀ {a b : γ}, edist a b < δ → edist (f a) (f b) < ε) ∧ (∀ δ > 0, ∃ ε > 0, ∀ {a b : γ}, edist (f a) (f b) < ε → edist a b < δ) := begin split, { assume h, exact ⟨emetric.uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1, (uniform_embedding_iff.1 h).2.2⟩ }, { rintros ⟨h₁, h₂⟩, refine uniform_embedding_iff.2 ⟨_, emetric.uniform_continuous_iff.2 h₁, h₂⟩, assume x y hxy, have : edist x y ≤ 0, { refine le_of_forall_lt' (λδ δpos, _), rcases h₂ δ δpos with ⟨ε, εpos, hε⟩, have : edist (f x) (f y) < ε, by simpa [hxy], exact hε this }, simpa using this } end /-- An emetric space is separated -/ @[priority 100] -- see Note [lower instance priority] instance to_separated : separated_space γ := separated_def.2 $ λ x y h, eq_of_forall_edist_le $ λ ε ε0, le_of_lt (h _ (edist_mem_uniformity ε0)) /-- If a `pseudo_emetric_space` is separated, then it is an `emetric_space`. -/ def emetric_of_t2_pseudo_emetric_space {α : Type*} [pseudo_emetric_space α] (h : separated_space α) : emetric_space α := { eq_of_edist_eq_zero := λ x y hdist, begin refine separated_def.1 h x y (λ s hs, _), obtain ⟨ε, hε, H⟩ := mem_uniformity_edist.1 hs, exact H (show edist x y < ε, by rwa [hdist]) end ..‹pseudo_emetric_space α› } /-- Auxiliary function to replace the uniformity on an emetric space with a uniformity which is equal to the original one, but maybe not defeq. This is useful if one wants to construct an emetric space with a specified uniformity. See Note [forgetful inheritance] explaining why having definitionally the right uniformity is often important. -/ def emetric_space.replace_uniformity {γ} [U : uniform_space γ] (m : emetric_space γ) (H : @uniformity _ U = @uniformity _ pseudo_emetric_space.to_uniform_space) : emetric_space γ := { edist := @edist _ m.to_has_edist, edist_self := edist_self, eq_of_edist_eq_zero := @eq_of_edist_eq_zero _ _, edist_comm := edist_comm, edist_triangle := edist_triangle, to_uniform_space := U, uniformity_edist := H.trans (@pseudo_emetric_space.uniformity_edist γ _) } /-- The extended metric induced by an injective function taking values in a emetric space. -/ def emetric_space.induced {γ β} (f : γ → β) (hf : function.injective f) (m : emetric_space β) : emetric_space γ := { edist := λ x y, edist (f x) (f y), edist_self := λ x, edist_self _, eq_of_edist_eq_zero := λ x y h, hf (edist_eq_zero.1 h), edist_comm := λ x y, edist_comm _ _, edist_triangle := λ x y z, edist_triangle _ _ _, to_uniform_space := uniform_space.comap f m.to_uniform_space, uniformity_edist := begin apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, edist (f x) (f y)), refine λ s, mem_comap.trans _, split; intro H, { rcases H with ⟨r, ru, rs⟩, rcases mem_uniformity_edist.1 ru with ⟨ε, ε0, hε⟩, refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h }, { rcases H with ⟨ε, ε0, hε⟩, exact ⟨_, edist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ } end } /-- Emetric space instance on subsets of emetric spaces -/ instance {α : Type*} {p : α → Prop} [t : emetric_space α] : emetric_space (subtype p) := t.induced coe (λ x y, subtype.ext_iff_val.2) /-- The product of two emetric spaces, with the max distance, is an extended metric spaces. We make sure that the uniform structure thus constructed is the one corresponding to the product of uniform spaces, to avoid diamond problems. -/ instance prod.emetric_space_max [emetric_space β] : emetric_space (γ × β) := { eq_of_edist_eq_zero := λ x y h, begin cases max_le_iff.1 (le_of_eq h) with h₁ h₂, have A : x.fst = y.fst := edist_le_zero.1 h₁, have B : x.snd = y.snd := edist_le_zero.1 h₂, exact prod.ext_iff.2 ⟨A, B⟩ end, ..prod.pseudo_emetric_space_max } /-- Reformulation of the uniform structure in terms of the extended distance -/ theorem uniformity_edist : 𝓤 γ = ⨅ ε>0, 𝓟 {p:γ×γ | edist p.1 p.2 < ε} := pseudo_emetric_space.uniformity_edist section pi open finset variables {π : β → Type*} [fintype β] /-- The product of a finite number of emetric spaces, with the max distance, is still an emetric space. This construction would also work for infinite products, but it would not give rise to the product topology. Hence, we only formalize it in the good situation of finitely many spaces. -/ instance emetric_space_pi [∀b, emetric_space (π b)] : emetric_space (Πb, π b) := { eq_of_edist_eq_zero := assume f g eq0, begin have eq1 : sup univ (λ (b : β), edist (f b) (g b)) ≤ 0 := le_of_eq eq0, simp only [finset.sup_le_iff] at eq1, exact (funext $ assume b, edist_le_zero.1 $ eq1 b $ mem_univ b), end, ..pseudo_emetric_space_pi } end pi namespace emetric /-- A compact set in an emetric space is separable, i.e., it is the closure of a countable set. -/ lemma countable_closure_of_compact {s : set γ} (hs : is_compact s) : ∃ t ⊆ s, (countable t ∧ s = closure t) := begin rcases subset_countable_closure_of_compact hs with ⟨t, hts, htc, hsub⟩, exact ⟨t, hts, htc, subset.antisymm hsub (closure_minimal hts hs.is_closed)⟩ end section diam variables {s : set γ} lemma diam_eq_zero_iff : diam s = 0 ↔ s.subsingleton := ⟨λ h x hx y hy, edist_le_zero.1 $ h ▸ edist_le_diam_of_mem hx hy, diam_subsingleton⟩ lemma diam_pos_iff : 0 < diam s ↔ ∃ (x ∈ s) (y ∈ s), x ≠ y := begin have := not_congr (@diam_eq_zero_iff _ _ s), dunfold set.subsingleton at this, push_neg at this, simpa only [pos_iff_ne_zero, exists_prop] using this end end diam end emetric
fe02dbe6e7e402c89a36cc319b344fe60c308c97
6df8d5ae3acf20ad0d7f0247d2cee1957ef96df1
/HW/hw5_higher_order_functions.lean
dae655562f1598817b2e55b23d4cd47eaa2791e4
[]
no_license
derekjohnsonva/CS2102
8ed45daa6658e6121bac0f6691eac6147d08246d
b3f507d4be824a2511838a1054d04fc9aef3304c
refs/heads/master
1,648,529,162,527
1,578,851,859,000
1,578,851,859,000
233,433,207
0
0
null
null
null
null
UTF-8
Lean
false
false
9,108
lean
open list /- #1. You are to implement a function that takes a "predicate" function and a list and that returns a new list: namely a list that contains all and only those elements of the first list for which the given predicate function returns true. We start by giving you two predicate functions. Each takes an argument, n, of type ℕ. The first returns true if and only if n < 5. The second returns true if and only if n is even. -/ /- Here's a "predicate" function that takes a natural number as an argument and returns true if the number is less than 5 otherwise it returns false. -/ def lt_5 (n : ℕ) : bool := n < 5 -- example cases #eval lt_5 2 #eval lt_5 6 /- Here's another predicate function, one that returns true if a given nat is even, and false otherwise. Note that we have defined this function recursively. Zero is even, one is not, and (2 + n') is if and only if n' is. You can think of a predicate function as a function that answers the question, does some value (here a nat) have some property? The properties in these two cases are (1) the property of being less than 5, and (2) the property of being even. -/ def evenb : ℕ → bool | 0 := tt | 1 := ff | (n' + 2) := evenb n' #eval evenb 0 #eval evenb 3 #eval evenb 4 #eval evenb 5 /- We call the function you are going to implement a "filter" function, because it takes a list and returns a "filtered" version of the list. Call you function "myfilter". If you filter an empty list you always get an empty list as a result. If you filter a non-empty list, l = (cons h t), the returned list has h at its head if and only if the predicate function applied to h returns true, otherwise the returned value is just the filtered version of t. A. [15 points] Your task is to complete an incomplete version of the definition of the myfilter function. We use a Lean construct new to you: the if ... then ... else. It works as you would expect from your work with other programming languages. Replace the underscores to complete the definition. -/ def myfilter : (ℕ → bool) → list ℕ → list ℕ | p [] := [] | p (cons h t) := if p h then (cons h (myfilter p t)) else myfilter p t /- Here's the definition of a simple list. -/ def a_list := [0,1,2,3,4,5,6,7,8,9] /- B. [10 points] Replace the underscores in the first two eval commands below as follows. Replace the first one with an expression in which myfilter is used to compute a new list that contains the numbers in a_list that are less than 5. Replace the second one with an expression in which myfilter is used to compute a list containing even elements of a_list. You may use the predicate functions we defined above. Replace the third underscore with a similar expression but where you use a λ expression to specify a predicate function that takes a nat, n, and returns tt if n is equal to three and false otherwise. Hint: n=3 is an expression that will return the desired bool. -/ def equals3 : ℕ → bool | 3 := tt | _ := ff #eval myfilter lt_5 a_list #eval myfilter evenb a_list #eval myfilter (λ (n : ℕ ), n=3) a_list /- #2. Here's a function that takes a function, f, from ℕ to ℕ, and a value, n, of type ℕ, and that returns the value that is obtained by simply applying f to n. -/ def f_apply : (ℕ → ℕ) → ℕ → ℕ | f n := (f n) -- examples of its use #eval f_apply nat.succ 3 #eval f_apply (λ n : ℕ, n * n) 3 /- A. [10 points] Write a function, f_apply_2, that takes a function, f, from ℕ to ℕ, and a value, n, of type ℕ, and that returns (read this carefully) the value obtained by applying f twice to n: the result of applying f to the result of applying f to n. For example, if f is the function that squares its nat argument, then (f_apply_2 f 3) returns 81, as f applied to 3 is 9 and f applied to 9 is 81. -/ -- Your answer here def f_apply_2 : (ℕ → ℕ) → ℕ → ℕ | f n := f(f n) #eval f_apply_2 nat.succ 3 #eval f_apply_2 (λ n : ℕ, n * n) 3 /- B. [10 points] Write a function f_apply_k that takes (1) a function, f, of type ℕ to ℕ, (2) a value, n, of type ℕ, and (3) a value, k of type ℕ, and that returns the result of applying f to n k times. Note that f_apply applies f to n once and f_apply_2 applies f to n twice. Your job is to write a function that is general in the sense that you specify by a parameter, k, how many times to apply f. Hint 1: Use recursion. Note: The result of applying any function, f, to n, zero times is just n. -/ open nat -- Answer here def f_apply_k : (ℕ → ℕ) → ℕ → ℕ → ℕ | f n 0 := n | f n (succ k) := f (f_apply_k f n (k)) /- Use #eval to evaluate an expression in which the squaring function, expressed as a λ expression, is applied to 3 two times. You should be able to confirm that you get the same answer given by using the f_apply_2 function in the example above. -/ -- Answer here #eval f_apply_k (λ n : ℕ, n * n) 3 2 #eval f_apply_2 (λ n : ℕ, n * n) 3 /- C. [Extra Credit] Write a function f_apply_k_fun that takes (1) a function, f, of type ℕ to ℕ, (2) a value, k of type ℕ, and that returns a function that, when applied to a natural number, n, returns the result of applying f to n k times. -/ def f_apply_k_fun : (ℕ → ℕ) → ℕ → (ℕ → ℕ) | f k := λ (n : ℕ), (f_apply_k f n k) /- #3: [15 points] Write a function, mcompose, that takes two functions, g and f (in that order), each of type ℕ → ℕ, and that returns *a function* that, when applied to an argument, n, of type ℕ, returns the result of applying g to the result of applying f to n. -/ -- Answer here def mcompose : (ℕ → ℕ) → (ℕ → ℕ) → (ℕ → ℕ) | g f := λ (n : ℕ), g (f n) def k := mcompose (λ (n : ℕ ), n*n) (λ (n : ℕ), n+1) #check k #eval k 4 /- #4. Higher-Order Functions 4A. [10 points] Provide an implementatation of a function, map_pred that takes as its arguments (1) a predicate function of type ℕ → bool, (2) a list of natural numbers (of type "list nat"), and that returns a list in which each ℕ value, n,in the argument list is replaced by true (tt) if the predicate returns true for a, otherwise false (ff). For example, if the predicate function returns true if and only if its argument is zero, then applying map to this function and to the list [0,1,2,0,1,0] must return [tt,ff,ff,tt,ff,tt]. Test your code by using #eval or #reduce to evaluate an expression in which map_pred is applied to such an "is_zero" predicate function and to the list 0,1,2,0,1,0]. Express the predicate function as a lambda abstraction within the #eval command. NOTE: You will have to use list.nil and list.cons to refer to the nil and cons constructors of the library-provided list data type, as you already have definitions for list and cons in the current namespace. -/ def map_pred : (ℕ → bool) → list nat → (list bool) | _ [] := [] | f (cons h t) := if (f h) then (cons tt (map_pred f t)) else (cons ff (map_pred f t)) -- Answer here def b_list := [0,1,2,5,1,0] #eval map_pred lt_5 b_list /- 4B. [10 points] Implement a function, reduce_or, that takes as its argument a list of Boolean values and that reduces the list to a single Boolean value: tt if there is at least one true value in the list, otherwise ff. Note: the Lean libraries provide the function "bor" to compute "b1 or b2", where b1 and b2 are Booleans. We recommend that you include tests of your solution. -/ -- example #reduce bor tt tt -- Answer here def reduce_or : list bool → bool | [] := ff | (cons tt t) := tt | (cons ff t) := reduce_or t def bools : list bool := [tt,ff,ff,ff] def bools2 : list bool := [ff,ff,ff,ff] def bools3 : list bool := [ff,ff,ff,tt] #eval reduce_or bools --tt #eval reduce_or bools2 --ff #eval reduce_or bools3 --tt /- 4C. [10points] Implement a function, reduce_and, that takes as its argument a list of Boolean values and that reduces the list to a single Boolean value: tt if every value in the list is true, otherwise ff. -/ -- Note: band implements the Boolean "and" function #reduce band tt tt -- Answer here def reduce_and : list bool → bool | [] := tt | (cons ff t) := ff | (cons tt t) := reduce_and t def boolsa : list bool := [tt,tt,tt,tt] def bools2a : list bool := [tt,tt,tt,ff] def bools3a : list bool := [ff,ff,ff,tt] #eval reduce_and boolsa --tt #eval reduce_and bools2a --ff /- 4D. [10 points] Define a function, all_zero, that takes a list of nat values and returns true if and only if they are all zero. Express your answer using map and reduce functions that you have previously defined above. Again we recommend that you test your solution. -/ -- Answer here (replace the _'s as needed) def is_zero : nat → bool --helper function for all_zero, checks | zero := tt --if a value == zero | _ := ff def all_zero : list nat → bool | [] := ff | l := reduce_and(map_pred is_zero l) /- Some tests -/ #reduce all_zero [] #reduce all_zero [0,0,0,0] #reduce all_zero [1,0,0,0] #reduce all_zero [0,1,0,0] #reduce all_zero [1,0,0,1]
a1be3c787b5eb69672f43f65e3c08c50cc754d3d
9b9a16fa2cb737daee6b2785474678b6fa91d6d4
/src/category_theory/instances/topological_spaces.lean
fd92393ea9ee60da29dab3a3ccb992853d960d07
[ "Apache-2.0" ]
permissive
johoelzl/mathlib
253f46daa30b644d011e8e119025b01ad69735c4
592e3c7a2dfbd5826919b4605559d35d4d75938f
refs/heads/master
1,625,657,216,488
1,551,374,946,000
1,551,374,946,000
98,915,829
0
0
Apache-2.0
1,522,917,267,000
1,501,524,499,000
Lean
UTF-8
Lean
false
false
5,127
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Patrick Massot, Scott Morrison, Mario Carneiro import category_theory.concrete_category import category_theory.full_subcategory import category_theory.functor_category import category_theory.adjunction import category_theory.limits.types import category_theory.natural_isomorphism import category_theory.eq_to_hom import topology.basic import topology.continuity import order.galois_connection open category_theory open category_theory.nat_iso open topological_space universe u namespace category_theory.instances /-- The category of topological spaces and continuous maps. -/ @[reducible] def Top : Type (u+1) := bundled topological_space instance (x : Top) : topological_space x := x.str namespace Top instance : concrete_category @continuous := ⟨@continuous_id, @continuous.comp⟩ -- local attribute [class] continuous -- instance {R S : Top} (f : R ⟶ S) : continuous (f : R → S) := f.2 section open category_theory.limits variables {J : Type u} [small_category J] def limit (F : J ⥤ Top.{u}) : cone F := { X := ⟨limit (F ⋙ forget), ⨆ j, (F.obj j).str.induced (limit.π (F ⋙ forget) j)⟩, π := { app := λ j, ⟨limit.π (F ⋙ forget) j, continuous_iff_induced_le.mpr (lattice.le_supr _ j)⟩, naturality' := λ j j' f, subtype.eq ((limit.cone (F ⋙ forget)).π.naturality f) } } def limit_is_limit (F : J ⥤ Top.{u}) : is_limit (limit F) := by refine is_limit.of_faithful forget (limit.is_limit _) (λ s, ⟨_, _⟩) (λ s, rfl); exact continuous_iff_le_coinduced.mpr (lattice.supr_le $ λ j, induced_le_iff_le_coinduced.mpr $ continuous_iff_le_coinduced.mp (s.π.app j).property) instance : has_limits.{u} Top.{u} := λ J 𝒥 F, by exactI { cone := limit F, is_limit := limit_is_limit F } instance : preserves_limits (forget : Top.{u} ⥤ Type u) := λ J 𝒥 F, by exactI preserves_limit_of_preserves_limit_cone (limit.is_limit F) (limit.is_limit (F ⋙ forget)) def colimit (F : J ⥤ Top.{u}) : cocone F := { X := ⟨colimit (F ⋙ forget), ⨅ j, (F.obj j).str.coinduced (colimit.ι (F ⋙ forget) j)⟩, ι := { app := λ j, ⟨colimit.ι (F ⋙ forget) j, continuous_iff_le_coinduced.mpr (lattice.infi_le _ j)⟩, naturality' := λ j j' f, subtype.eq ((colimit.cocone (F ⋙ forget)).ι.naturality f) } } def colimit_is_colimit (F : J ⥤ Top.{u}) : is_colimit (colimit F) := by refine is_colimit.of_faithful forget (colimit.is_colimit _) (λ s, ⟨_, _⟩) (λ s, rfl); exact continuous_iff_induced_le.mpr (lattice.le_infi $ λ j, induced_le_iff_le_coinduced.mpr $ continuous_iff_le_coinduced.mp (s.ι.app j).property) instance : has_colimits.{u} Top.{u} := λ J 𝒥 F, by exactI { cocone := colimit F, is_colimit := colimit_is_colimit F } instance : preserves_colimits (forget : Top.{u} ⥤ Type u) := λ J 𝒥 F, by exactI preserves_colimit_of_preserves_colimit_cocone (colimit.is_colimit F) (colimit.is_colimit (F ⋙ forget)) end def discrete : Type u ⥤ Top.{u} := { obj := λ X, ⟨X, ⊤⟩, map := λ X Y f, ⟨f, continuous_top⟩ } def trivial : Type u ⥤ Top.{u} := { obj := λ X, ⟨X, ⊥⟩, map := λ X Y f, ⟨f, continuous_bot⟩ } def adj₁ : adjunction discrete forget := { hom_equiv := λ X Y, { to_fun := λ f, f, inv_fun := λ f, ⟨f, continuous_top⟩, left_inv := by tidy, right_inv := by tidy }, unit := { app := λ X, id }, counit := { app := λ X, ⟨id, continuous_top⟩ } } def adj₂ : adjunction forget trivial := { hom_equiv := λ X Y, { to_fun := λ f, ⟨f, continuous_bot⟩, inv_fun := λ f, f, left_inv := by tidy, right_inv := by tidy }, unit := { app := λ X, ⟨id, continuous_bot⟩ }, counit := { app := λ X, id } } end Top variables {X : Top.{u}} instance : small_category (opens X) := by apply_instance def nbhd (x : X.α) := { U : opens X // x ∈ U } def nbhds (x : X.α) : small_category (nbhd x) := begin unfold nbhd, apply_instance end end category_theory.instances open category_theory.instances namespace topological_space.opens /-- `opens.map f` gives the functor from open sets in Y to open set in X, given by taking preimages under f. -/ def map {X Y : Top.{u}} (f : X ⟶ Y) : opens Y ⥤ opens X := { obj := λ U, ⟨ f.val ⁻¹' U, f.property _ U.property ⟩, map := λ U V i, ⟨ ⟨ λ a b, i.down.down b ⟩ ⟩ }. @[simp] lemma map_id_obj (X : Top.{u}) (U : opens X) : (map (𝟙 X)).obj U = U := by tidy @[simp] def map_id (X : Top.{u}) : map (𝟙 X) ≅ functor.id (opens X) := { hom := { app := λ U, 𝟙 U }, inv := { app := λ U, 𝟙 U } } -- We could make f g implicit here, but it's nice to be able to see when -- they are the identity (often!) def map_iso {X Y : Top.{u}} (f g : X ⟶ Y) (h : f = g) : map f ≅ map g := nat_iso.of_components (λ U, eq_to_iso (congr_fun (congr_arg _ (congr_arg _ h)) _) ) (by obviously) @[simp] def map_iso_id {X : Top.{u}} (h) : map_iso (𝟙 X) (𝟙 X) h = iso.refl (map _) := rfl end topological_space.opens
4594ec1053bf00c8e08b4fc9730d288cfc457642
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/order/order_iso.lean
9fff2b5d009da8f7d1f878205b0df5469737fd30
[ "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
14,253
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import logic.embedding import data.nat.basic open function universes u v w variables {α : Type*} {β : Type*} {γ : Type*} {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} /-- An increasing function is injective -/ lemma injective_of_increasing (r : α → α → Prop) (s : β → β → Prop) [is_trichotomous α r] [is_irrefl β s] (f : α → β) (hf : ∀{x y}, r x y → s (f x) (f y)) : injective f := begin intros x y hxy, rcases trichotomous_of r x y with h | h | h, have := hf h, rw hxy at this, exfalso, exact irrefl_of s (f y) this, exact h, have := hf h, rw hxy at this, exfalso, exact irrefl_of s (f y) this end /-- An order embedding with respect to a given pair of orders `r` and `s` is an embedding `f : α ↪ β` such that `r a b ↔ s (f a) (f b)`. -/ structure order_embedding {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends α ↪ β := (ord' : ∀ {a b}, r a b ↔ s (to_embedding a) (to_embedding b)) infix ` ≼o `:25 := order_embedding /-- the induced order on a subtype is an embedding under the natural inclusion. -/ definition subtype.order_embedding {X : Type*} (r : X → X → Prop) (p : X → Prop) : ((subtype.val : subtype p → X) ⁻¹'o r) ≼o r := ⟨⟨subtype.val,subtype.val_injective⟩,by intros;refl⟩ theorem preimage_equivalence {α β} (f : α → β) {s : β → β → Prop} (hs : equivalence s) : equivalence (f ⁻¹'o s) := ⟨λ a, hs.1 _, λ a b h, hs.2.1 h, λ a b c h₁ h₂, hs.2.2 h₁ h₂⟩ namespace order_embedding instance : has_coe_to_fun (r ≼o s) := ⟨λ _, α → β, λ o, o.to_embedding⟩ theorem inj (f : r ≼o s) : injective f := f.inj' theorem ord (f : r ≼o s) : ∀ {a b}, r a b ↔ s (f a) (f b) := f.ord' @[simp] theorem coe_fn_mk (f : α ↪ β) (o) : (@order_embedding.mk _ _ r s f o : α → β) = f := rfl @[simp] theorem coe_fn_to_embedding (f : r ≼o s) : (f.to_embedding : α → β) = f := rfl theorem eq_of_to_fun_eq : ∀ {e₁ e₂ : r ≼o s}, (e₁ : α → β) = e₂ → e₁ = e₂ | ⟨⟨f₁, h₁⟩, o₁⟩ ⟨⟨f₂, h₂⟩, o₂⟩ h := by congr; exact h @[refl] protected def refl (r : α → α → Prop) : r ≼o r := ⟨embedding.refl _, λ a b, iff.rfl⟩ @[trans] protected def trans (f : r ≼o s) (g : s ≼o t) : r ≼o t := ⟨f.1.trans g.1, λ a b, by rw [f.2, g.2]; simp⟩ @[simp] theorem refl_apply (x : α) : order_embedding.refl r x = x := rfl @[simp] theorem trans_apply (f : r ≼o s) (g : s ≼o t) (a : α) : (f.trans g) a = g (f a) := rfl /-- An order embedding is also an order embedding between dual orders. -/ def rsymm (f : r ≼o s) : swap r ≼o swap s := ⟨f.to_embedding, λ a b, f.ord⟩ /-- If `f` is injective, then it is an order embedding from the preimage order of `s` to `s`. -/ def preimage (f : α ↪ β) (s : β → β → Prop) : f ⁻¹'o s ≼o s := ⟨f, λ a b, iff.rfl⟩ theorem eq_preimage (f : r ≼o s) : r = f ⁻¹'o s := by { ext a b, exact f.ord } protected theorem is_irrefl : ∀ (f : r ≼o s) [is_irrefl β s], is_irrefl α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a h, H _ (o.1 h)⟩ protected theorem is_refl : ∀ (f : r ≼o s) [is_refl β s], is_refl α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a, o.2 (H _)⟩ protected theorem is_symm : ∀ (f : r ≼o s) [is_symm β s], is_symm α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b h, o.2 (H _ _ (o.1 h))⟩ protected theorem is_asymm : ∀ (f : r ≼o s) [is_asymm β s], is_asymm α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b h₁ h₂, H _ _ (o.1 h₁) (o.1 h₂)⟩ protected theorem is_antisymm : ∀ (f : r ≼o s) [is_antisymm β s], is_antisymm α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b h₁ h₂, f.inj' (H _ _ (o.1 h₁) (o.1 h₂))⟩ protected theorem is_trans : ∀ (f : r ≼o s) [is_trans β s], is_trans α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b c h₁ h₂, o.2 (H _ _ _ (o.1 h₁) (o.1 h₂))⟩ protected theorem is_total : ∀ (f : r ≼o s) [is_total β s], is_total α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b, (or_congr o o).2 (H _ _)⟩ protected theorem is_preorder : ∀ (f : r ≼o s) [is_preorder β s], is_preorder α r | f H := by exactI {..f.is_refl, ..f.is_trans} protected theorem is_partial_order : ∀ (f : r ≼o s) [is_partial_order β s], is_partial_order α r | f H := by exactI {..f.is_preorder, ..f.is_antisymm} protected theorem is_linear_order : ∀ (f : r ≼o s) [is_linear_order β s], is_linear_order α r | f H := by exactI {..f.is_partial_order, ..f.is_total} protected theorem is_strict_order : ∀ (f : r ≼o s) [is_strict_order β s], is_strict_order α r | f H := by exactI {..f.is_irrefl, ..f.is_trans} protected theorem is_trichotomous : ∀ (f : r ≼o s) [is_trichotomous β s], is_trichotomous α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b, (or_congr o (or_congr f.inj'.eq_iff.symm o)).2 (H _ _)⟩ protected theorem is_strict_total_order' : ∀ (f : r ≼o s) [is_strict_total_order' β s], is_strict_total_order' α r | f H := by exactI {..f.is_trichotomous, ..f.is_strict_order} protected theorem acc (f : r ≼o s) (a : α) : acc s (f a) → acc r a := begin generalize h : f a = b, intro ac, induction ac with _ H IH generalizing a, subst h, exact ⟨_, λ a' h, IH (f a') (f.ord.1 h) _ rfl⟩ end protected theorem well_founded : ∀ (f : r ≼o s) (h : well_founded s), well_founded r | f ⟨H⟩ := ⟨λ a, f.acc _ (H _)⟩ protected theorem is_well_order : ∀ (f : r ≼o s) [is_well_order β s], is_well_order α r | f H := by exactI {wf := f.well_founded H.wf, ..f.is_strict_total_order'} /-- It suffices to prove `f` is monotone between strict orders to show it is an order embedding. -/ def of_monotone [is_trichotomous α r] [is_asymm β s] (f : α → β) (H : ∀ a b, r a b → s (f a) (f b)) : r ≼o s := begin haveI := @is_irrefl_of_is_asymm β s _, refine ⟨⟨f, λ a b e, _⟩, λ a b, ⟨H _ _, λ h, _⟩⟩, { refine ((@trichotomous _ r _ a b).resolve_left _).resolve_right _; exact λ h, @irrefl _ s _ _ (by simpa [e] using H _ _ h) }, { refine (@trichotomous _ r _ a b).resolve_right (or.rec (λ e, _) (λ h', _)), { subst e, exact irrefl _ h }, { exact asymm (H _ _ h') h } } end @[simp] theorem of_monotone_coe [is_trichotomous α r] [is_asymm β s] (f : α → β) (H) : (@of_monotone _ _ r s _ _ f H : α → β) = f := rfl -- If le is preserved by an order embedding of preorders, then lt is too def lt_embedding_of_le_embedding [preorder α] [preorder β] (f : (has_le.le : α → α → Prop) ≼o (has_le.le : β → β → Prop)) : (has_lt.lt : α → α → Prop) ≼o (has_lt.lt : β → β → Prop) := { ord' := by intros; simp [lt_iff_le_not_le,f.ord], .. f } def nat_lt [is_strict_order α r] (f : ℕ → α) (H : ∀ n:ℕ, r (f n) (f (n+1))) : ((<) : ℕ → ℕ → Prop) ≼o r := of_monotone f $ λ a b h, begin induction b with b IH, {exact (nat.not_lt_zero _ h).elim}, cases nat.lt_succ_iff_lt_or_eq.1 h with h e, { exact trans (IH h) (H _) }, { subst b, apply H } end def nat_gt [is_strict_order α r] (f : ℕ → α) (H : ∀ n:ℕ, r (f (n+1)) (f n)) : ((>) : ℕ → ℕ → Prop) ≼o r := by haveI := is_strict_order.swap r; exact rsymm (nat_lt f H) theorem well_founded_iff_no_descending_seq [is_strict_order α r] : well_founded r ↔ ¬ nonempty (((>) : ℕ → ℕ → Prop) ≼o r) := ⟨λ ⟨h⟩ ⟨⟨f, o⟩⟩, suffices ∀ a, acc r a → ∀ n, a ≠ f n, from this (f 0) (h _) 0 rfl, λ a ac, begin induction ac with a _ IH, intros n h, subst a, exact IH (f (n+1)) (o.1 (nat.lt_succ_self _)) _ rfl end, λ N, ⟨λ a, classical.by_contradiction $ λ na, let ⟨f, h⟩ := classical.axiom_of_choice $ show ∀ x : {a // ¬ acc r a}, ∃ y : {a // ¬ acc r a}, r y.1 x.1, from λ ⟨x, h⟩, classical.by_contradiction $ λ hn, h $ ⟨_, λ y h, classical.by_contradiction $ λ na, hn ⟨⟨y, na⟩, h⟩⟩ in N ⟨nat_gt (λ n, (f^[n] ⟨a, na⟩).1) $ λ n, by rw nat.iterate_succ'; apply h⟩⟩⟩ end order_embedding /-- The inclusion map `fin n → ℕ` is an order embedding. -/ def fin.val.order_embedding (n) : @order_embedding (fin n) ℕ (<) (<) := ⟨⟨fin.val, @fin.eq_of_veq _⟩, λ a b, iff.rfl⟩ /-- The inclusion map `fin m → fin n` is an order embedding. -/ def fin_fin.order_embedding {m n} (h : m ≤ n) : @order_embedding (fin m) (fin n) (<) (<) := ⟨⟨λ ⟨x, h'⟩, ⟨x, lt_of_lt_of_le h' h⟩, λ ⟨a, _⟩ ⟨b, _⟩ h, by congr; injection h⟩, by intros; cases a; cases b; refl⟩ instance fin.lt.is_well_order (n) : is_well_order (fin n) (<) := (fin.val.order_embedding _).is_well_order /-- An order isomorphism is an equivalence that is also an order embedding. -/ structure order_iso {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends α ≃ β := (ord' : ∀ {a b}, r a b ↔ s (to_equiv a) (to_equiv b)) infix ` ≃o `:25 := order_iso namespace order_iso /-- Convert an `order_iso` to an `order_embedding`. This function is also available as a coercion but often it is easier to write `f.to_order_embedding` than to write explicitly `r` and `s` in the target type. -/ def to_order_embedding (f : r ≃o s) : r ≼o s := ⟨f.to_equiv.to_embedding, f.ord'⟩ instance : has_coe (r ≃o s) (r ≼o s) := ⟨to_order_embedding⟩ -- see Note [function coercion] instance : has_coe_to_fun (r ≃o s) := ⟨λ _, α → β, λ f, f⟩ @[simp] lemma to_order_embedding_eq_coe (f : r ≃o s) : f.to_order_embedding = f := rfl @[simp] lemma coe_coe_fn (f : r ≃o s) : ((f : r ≼o s) : α → β) = f := rfl @[simp] lemma to_equiv_to_fun (f : r ≃o s) (x : α) : f.to_equiv.to_fun x = f x := rfl theorem ord (f : r ≃o s) : ∀ {a b}, r a b ↔ s (f a) (f b) := f.ord' lemma ord'' {r : α → α → Prop} {s : β → β → Prop} (f : r ≃o s) {x y : α} : r x y ↔ s ((↑f : r ≼o s) x) ((↑f : r ≼o s) y) := f.ord @[simp] theorem coe_fn_mk (f : α ≃ β) (o) : (@order_iso.mk _ _ r s f o : α → β) = f := rfl @[simp] theorem coe_fn_to_equiv (f : r ≃o s) : (f.to_equiv : α → β) = f := rfl theorem eq_of_to_fun_eq : ∀ {e₁ e₂ : r ≃o s}, (e₁ : α → β) = e₂ → e₁ = e₂ | ⟨e₁, o₁⟩ ⟨e₂, o₂⟩ h := by congr; exact equiv.eq_of_to_fun_eq h @[refl] protected def refl (r : α → α → Prop) : r ≃o r := ⟨equiv.refl _, λ a b, iff.rfl⟩ @[symm] protected def symm (f : r ≃o s) : s ≃o r := ⟨f.to_equiv.symm, λ a b, by cases f with f o; rw o; simp⟩ @[trans] protected def trans (f₁ : r ≃o s) (f₂ : s ≃o t) : r ≃o t := ⟨f₁.to_equiv.trans f₂.to_equiv, λ a b, by cases f₁ with f₁ o₁; cases f₂ with f₂ o₂; rw [o₁, o₂]; simp⟩ @[simp] theorem coe_fn_symm_mk (f o) : ((@order_iso.mk _ _ r s f o).symm : β → α) = f.symm := rfl @[simp] theorem refl_apply (x : α) : order_iso.refl r x = x := rfl @[simp] theorem trans_apply : ∀ (f : r ≃o s) (g : s ≃o t) (a : α), (f.trans g) a = g (f a) | ⟨f₁, o₁⟩ ⟨f₂, o₂⟩ a := equiv.trans_apply _ _ _ @[simp] theorem apply_symm_apply : ∀ (e : r ≃o s) (x : β), e (e.symm x) = x | ⟨f₁, o₁⟩ x := by simp @[simp] theorem symm_apply_apply : ∀ (e : r ≃o s) (x : α), e.symm (e x) = x | ⟨f₁, o₁⟩ x := by simp /-- Any equivalence lifts to an order isomorphism between `s` and its preimage. -/ def preimage (f : α ≃ β) (s : β → β → Prop) : f ⁻¹'o s ≃o s := ⟨f, λ a b, iff.rfl⟩ noncomputable def of_surjective (f : r ≼o s) (H : surjective f) : r ≃o s := ⟨equiv.of_bijective ⟨f.inj, H⟩, by simp [f.ord']⟩ @[simp] theorem of_surjective_coe (f : r ≼o s) (H) : (of_surjective f H : α → β) = f := by delta of_surjective; simp def sum_lex_congr {α₁ α₂ β₁ β₂ r₁ r₂ s₁ s₂} (e₁ : @order_iso α₁ α₂ r₁ r₂) (e₂ : @order_iso β₁ β₂ s₁ s₂) : sum.lex r₁ s₁ ≃o sum.lex r₂ s₂ := ⟨equiv.sum_congr e₁.to_equiv e₂.to_equiv, λ a b, by cases e₁ with f hf; cases e₂ with g hg; cases a; cases b; simp [hf, hg]⟩ def prod_lex_congr {α₁ α₂ β₁ β₂ r₁ r₂ s₁ s₂} (e₁ : @order_iso α₁ α₂ r₁ r₂) (e₂ : @order_iso β₁ β₂ s₁ s₂) : prod.lex r₁ s₁ ≃o prod.lex r₂ s₂ := ⟨equiv.prod_congr e₁.to_equiv e₂.to_equiv, λ a b, begin cases e₁ with f hf; cases e₂ with g hg, cases a with a₁ a₂; cases b with b₁ b₂, suffices : prod.lex r₁ s₁ (a₁, a₂) (b₁, b₂) ↔ prod.lex r₂ s₂ (f a₁, g a₂) (f b₁, g b₂), {simpa [hf, hg]}, split, { intro h, cases h with _ _ _ _ h _ _ _ h, { left, exact hf.1 h }, { right, exact hg.1 h } }, { generalize e : f b₁ = fb₁, intro h, cases h with _ _ _ _ h _ _ _ h, { subst e, left, exact hf.2 h }, { have := f.injective e, subst b₁, right, exact hg.2 h } } end⟩ end order_iso /-- A subset `p : set α` embeds into `α` -/ def set_coe_embedding {α : Type*} (p : set α) : p ↪ α := ⟨subtype.val, @subtype.eq _ _⟩ /-- `subrel r p` is the inherited relation on a subset. -/ def subrel (r : α → α → Prop) (p : set α) : p → p → Prop := @subtype.val _ p ⁻¹'o r @[simp] theorem subrel_val (r : α → α → Prop) (p : set α) {a b} : subrel r p a b ↔ r a.1 b.1 := iff.rfl namespace subrel protected def order_embedding (r : α → α → Prop) (p : set α) : subrel r p ≼o r := ⟨set_coe_embedding _, λ a b, iff.rfl⟩ @[simp] theorem order_embedding_apply (r : α → α → Prop) (p a) : subrel.order_embedding r p a = a.1 := rfl instance (r : α → α → Prop) [is_well_order α r] (p : set α) : is_well_order p (subrel r p) := order_embedding.is_well_order (subrel.order_embedding r p) end subrel /-- Restrict the codomain of an order embedding -/ def order_embedding.cod_restrict (p : set β) (f : r ≼o s) (H : ∀ a, f a ∈ p) : r ≼o subrel s p := ⟨f.to_embedding.cod_restrict p H, f.ord'⟩ @[simp] theorem order_embedding.cod_restrict_apply (p) (f : r ≼o s) (H a) : order_embedding.cod_restrict p f H a = ⟨f a, H a⟩ := rfl
f243f131fe62a1c7a3bc6284124730ed52abba05
205f0fc16279a69ea36e9fd158e3a97b06834ce2
/src/11_Existential_Quantification/00_intro.lean
22627aba326d9802477491e35c50ce4ccacda4cf
[]
no_license
kevinsullivan/cs-dm-lean
b21d3ca1a9b2a0751ba13fcb4e7b258010a5d124
a06a94e98be77170ca1df486c8189338b16cf6c6
refs/heads/master
1,585,948,743,595
1,544,339,346,000
1,544,339,346,000
155,570,767
1
3
null
1,541,540,372,000
1,540,995,993,000
Lean
UTF-8
Lean
false
false
16,643
lean
/- ***********************-/ /- *** ∃ Introduction *** -/ /-************************-/ /- An existentially quantified proposition asserts that there exists *some* value of some type that makes a given predicate true. Here's an example. -/ def anExistsProp := ∃ m , m + m = 8 /- This proposition asserts that there is some value m (inferred to be of type ℕ) that makes the predicate, m + m = 8, true. Basic algebra tells us that there is such a value, namely 4, so this existentially quantified proposition can be proved and is true. The key thing to remember is that a proof of such an existentially quantified proposition is a pair. The first element is a value that makes the sub-proposition true. We call such a value a "witness". In the example, the witness is 4. The second element in a proof is a proof of that the proposition obtained by substituting the witness in for the value of the variable in the predicate is true. Here, the proof must be a proof of 4 + 4 = 8. A proof of ∃ m , m + m = 8, is thus the pair, ⟨ 4, eq.refl 8 ⟩. Here we use special angle brackets, a notation that Lean recognizes for writing proofs of existentially quantified propositions. -/ /- Here are a couple more examples. Note, as with all propositions, these existential propositions do not have to be true. -/ def anotherExistsProp := exists m, m > 10 def yetAnotherExistsProp := exists m, m - m = 3 /- Consider a familiar expression: You can fool all of the people some of the time… ∀ p ∈ People, ∃ t ∈ time, fool(p, t) — everybody can be fooled at one time or another ∃ t ∈ time, ∀ p ∈ People, fool(p, t) — there exists a time when all of the people can be fooled simultaneously ∃ t ∈ time, ∀ p ∈ People, fool(p, t) → ∀ p ∈ People, ∃ t ∈ time, fool(p, t) …and some of the people all of the time. ∃ p ∈ People, ∀ t ∈ time, fool(p, t) — there exists somebody who can be fooled all of the time ∀ t ∈ time, ∃ p ∈ People, fool(p, t) — at any given moment, there exists somebody who can be fooled ∃ p ∈ People, ∀ t ∈ time, fool(p, t) → ∀ t ∈ time, ∃ p ∈ People, fool(p, t) -/ /- More generally the introduction rule for ∃ is as follows: { T : Type } { p: T → Prop } (w : T) (e : p w) ---------------------------------------------- exists.intr ∃ a : T, p a -/ #print exists.intro /- Here's code that illustrates the use of -/ def existsIntro (T: Type) -- arguments (pred: T → Prop) (w : T) (e : pred w) : exists w, pred w -- return type := exists.intro w e -- direct use of exists. intro #check existsIntro /- Abstract example -/ variable T : Type variable witness : T variable predicate : T → Prop #check predicate witness variable proof : predicate witness -- direct use of exists.intro def pfOfExists : ∃ m, predicate m := exists.intro witness proof -- shorthand def pfOfExists' : ∃ m, predicate m := ⟨ witness, proof ⟩ -- a script in which we build the proof interactively def fourAgain : exists m, m + m = 8 := begin apply exists.intro 4, exact rfl, end #reduce fourAgain /- Concrete example -/ def isEven (n : nat) : Prop := exists m : nat, m + m = n #check isEven /- A bad definition of isEven (last time). -/ def isEvenBadDef (n : nat) : Prop := exists m : nat, n / m = 2 example : isEvenBadDef 7 := ⟨ 3.5, rfl ⟩ -- OOPS "/"" is natural number division #reduce (7 / 2 : nat) #reduce isEven 8 -- def eightEven := isEven 8 #check eightEven #reduce eightEven -- exact proof term using exists.intro theorem even8 : eightEven := exists.intro 4 rfl -- syntactic sugar theorem even8' : eightEven := ⟨ 4, rfl ⟩ -- as a tactic script -- unfold expands a definition theorem even8'' : isEven 8 := begin unfold isEven, -- not necessary apply exists.intro 4, exact rfl end /- EXERCISE: Construct a proof, isNonZ, of the proposition that there exists a natural number n such that 0 ≠ n. -/ -- Possible Answers -- theorem isNonZ : exists n : nat, 0 ≠ n := exists.intro 1 (λ pf : (0 = 1), nat.no_confusion pf) -- second arg is a pf of 0=1→false theorem isNonZ' : exists n : nat, 0 ≠ n := begin apply exists.intro 1, assume contra: 0=1, exact nat.no_confusion contra end theorem isNonZ'' : exists n : nat, 0 ≠ n := begin have pf0isnt1: (0 ≠ 2), apply nat.no_confusion, exact ⟨ 2, pf0isnt1 ⟩ end theorem isNonZ''' : exists n : nat, 0 ≠ n := ⟨ 3, dec_trivial ⟩ /- **********************-/ /- *** ∃ Elimination *** -/ /-***********************-/ /- Suppose you want to show: ∃ x, P x → Q. If one assumes that ∃ x, P x, then one can assume there is some specific value, w, such that P w is true. If one can then show, without making additional assumptions about w, that some conclusion, Q (that does not depend on w), follows, then one has shown that Q follows from the mere existence of a w with property P, and thus from ∃ x, P x. The formal rule is a little bit involved. Here it is as an inference rule. We explain each piece below. ∀ {Q : Prop}, ∀ {T : Type }, ∀ { P : T → Prop}, pfEx: (∃ x : T, P x), pfP2Q: ∀ w : T, P w → Q ---------------------------------------------- Q Ignore the implicit parameters for a moment, and focus on pfEx and pfP2Q. This rule says that (1) if there is some object, x that has property P, and (2) if whenever *any* object has this property, Q follows, then Q follows. This is the elimination rule for ∃. It lets you draw a conclusion, Q, from the premise that ∃ x, P x (there is an x with property P) and from a proof that if any x has this property (and we just assumed there is one) then there is a proof of Q. The following function shows all of the pieces needed to use exists.elim and how to use it. Note that the conclusion, Q, the type of elements involved, T, and the property, P, are given implicitly, as they can be inferred from the ∃ and from the proof that Q follows from any such value. -/ def existsElim { Q : Prop } { T : Type } { P : T → Prop } ( ex : exists x, P x) ( pw2q : ∀ w : T, P w → Q) : Q := exists.elim ex pw2q /- EXAMPLE. Let's prove that if there is a value of some type that has two properties, P and Q, then it has one of those properties. -/ -- assume pred1 and pred2 are properties of nats variable pred1 : ℕ → Prop variable pred2 : ℕ → Prop /- ∀ {Q : Prop}, ∀ {T : Type }, ∀ { P : T → Prop}, pfEx: (∃ x : T, P x), pfP2Q: ∀ w : T, P w → Q ---------------------------------------------- Q -/ theorem forgetAProperty : (exists n, pred1 n ∧ pred2 n) → (exists n, pred1 n) := -- here "Q", the conclusion, is (exists n, pred1 n) begin assume ex, show ∃ (n : ℕ), pred1 n, from begin apply exists.elim ex, -- give one arg, build other assume w Pw, -- assume w and proof of P w show ∃ (n : ℕ), pred1 n, from exists.intro w Pw.left, end, end /- We'll need to understand the following fact to fully understand the proof of the theorem that follows. This fact says that if "a" is a value (here of type ℕ) and pred is a predicate on values (or type ℕ), and if you further have a function that takes a value, x, and returns pred x, then applying that function to a value a returns pred a. Just keep this in mind as we work through the follow-on proof. -/ example: ∀ (a: ℕ), ∀ (pred: ℕ → Prop), (λ (x: ℕ), pred x) a = (pred a) := begin assume a pred, apply rfl end /- We now define two simple predicates, gt1 (λ x, x > 1) and pred4 (λ x, x < 4), and two more complex predicates, P and Q. P is the predicate that asserts that both gt1 and pred4 are true of some x, and Q is the predicate that asserts that there is some x that satisfies gt1. The reason for this "set up" is so that we can state the main theorem that follows in a way that makes cler the relevance of the elimination rule for exists. We want to prove Q from ∃(x: ℕ), P x. -/ def gt1: ℕ → Prop := λ (x: ℕ), x > 1 def lt4: ℕ → Prop := λ (x: ℕ), x < 4 abbreviation P : ℕ → Prop := λ (x: ℕ), gt1 x ∧ lt4 x abbreviation Q : Prop := ∃ (x: ℕ), gt1 x #check P 2 theorem forgetAProperty': (∃(x: ℕ), P x) → Q := begin assume pf_existsP, show Q, -- document goal for readability from begin apply exists.elim pf_existsP, -- give one arg, build other assume w pf_Pw, -- assume w and proof of P w show Q, apply exists.intro w, exact pf_Pw.left, end, end /- *** EXERCISE: Prove: Assuming n is a natural number and P and S are properties of natural numbers, prove that (∃ n, P n ∧ S n) → (∃ n, S n ∧ P n). -/ -- Answer theorem reverseProperty : ∀ (P S : ℕ → Prop), (exists n, P n ∧ S n) → (exists n, S n ∧ P n) := -- here Q, the conclusion, is (exists n, S n ∧ P n) begin assume P S, assume ex, show ∃ (n : ℕ), S n ∧ P n, from begin apply exists.elim ex, -- give one arg, build other assume w Pw, -- assume w and proof of P w show ∃ (n : ℕ), S n ∧ P n, -- here's some new notation for and.intro from ⟨ w, ⟨ Pw.right, Pw.left ⟩ ⟩ end, end /- The difficulty of proving propositions in predicate logic is often related to the nesting of quantifiers. Here's a little example illustrating such nesting. We formalize and prove this claim: if there is a person who can be fooled at any time, then at any time someone can be fooled. Here's a logical rendition of this idea: ∃ p ∈ Person, ∀ t ∈ Time, canFool(p, t) → ∀ t ∈ Time, ∃ p ∈ Person, canFool(p, t). Note the different nestings of the quantifiers. Let's prove it. -/ theorem existsforall_impl_forallexists: ∀ (Time Person: Type), ∀ (canFool: Time → Person → Prop), (∃ p: Person, ∀ t: Time, canFool t p) → (∀ t: Time, ∃ p: Person, canFool t p) := begin assume Time Person, assume canFool, assume someoneCanBeFooledAllTheTime, show ∀ (t : Time), ∃ (p : Person), canFool t p, from begin assume aTime, show ∃ (p : Person), canFool aTime p, from begin apply exists.elim someoneCanBeFooledAllTheTime, assume somePerson, assume canFoolThatPersonAnytime, have canFoolThatPersonSometime := canFoolThatPersonAnytime aTime, exact exists.intro somePerson canFoolThatPersonSometime, --exact ⟨ somePerson, canFoolThatPersonSometime ⟩, end, end, end /- The same proposition and proof using neutral identifiers. -/ theorem existsforall_impl_forallexists': ∀ (T P: Type), ∀ (rel: T → P → Prop), (∃ p: P, ∀ t: T, rel t p) → (∀ t: T, ∃ p: P, rel t p) := begin assume T P, assume rel, assume somePrelAllT, assume someT, apply exists.elim somePrelAllT, assume someP, assume thatPrelAllT, have thatTrelThatP := thatPrelAllT someT, exact ⟨ someP, thatTrelThatP ⟩, end /- Discussion: Is the converse proposition true? -/ /- Negating Existential and Universal Quantifiers What happens when you negate an existential quantifier? What does this mean: ¬(∃ t ∈ time, fool(me, t)) - there does not exist a time when you can fool me ∀ t ∈ time, ¬fool(me, t) - at any time, you will not fool me Are these equivalent? How about this: ¬(∀ t ∈ time, fool(me, t)) - you cannot fool me all of the time ∃ t ∈ time, ¬fool(me, t) - there exists a time when you cannot fool me Are these equivalent? -/ theorem not_exists_t_iff_always_not_t: ∀ (T: Type) (pred: (T → Prop)), (¬(∃(t: T), pred(t))) ↔ ∀(t: T), ¬pred(t) := begin assume T pred, apply iff.intro, -- forward show (¬∃ (t : T), pred t) → ∀ (t : T), ¬pred t, from begin assume pf_not_exists_t, show ∀ (t : T), ¬pred t, from begin assume t, assume pred_t, have pf_exists_t := exists.intro t pred_t, exact (pf_not_exists_t pf_exists_t), -- contradiction, end, end, -- reverse show (∀ (t : T), ¬pred t) → (¬∃ (t : T), pred t), from begin assume all_not_pred, show ¬∃ (t : T), pred t, from begin assume ex_t_pred, show false, from begin apply exists.elim ex_t_pred, assume t, assume pred_t, have not_pred_t := all_not_pred t, --exact pf_not_pred_t pf_pred_t contradiction, end, end, end, end open classical -- em is axiom of the excluded middle theorem not_all_t_iff_exists_not_t: ∀ (T: Type) (pred: (T → Prop)), (¬(∀ t: T, pred(t))) ↔ ∃ t: T, ¬pred(t) := begin intros, apply iff.intro, assume pf_not_all_t, cases (em (∃ (t : T), ¬pred t)) with pf_exists_not_t pf_not_exists_not_t, exact pf_exists_not_t, have contra_double_neg: ∀(t: T), ¬¬pred t, assume t, assume pf_n_pred_t, have pf_exists_t := exists.intro t pf_n_pred_t, exact (pf_not_exists_not_t pf_exists_t), have contra: ∀(t: T), pred t, assume t, have pf_nn_pred_t := (contra_double_neg t), cases em (pred t) with pf_pred_t pf_n_pred_t, assumption, exact false.elim (pf_nn_pred_t pf_n_pred_t), exact false.elim (pf_not_all_t contra), assume pf_exists_not_t, apply exists.elim pf_exists_not_t, assume w not_pred_w, assume pf_all_t, show false, from begin have pred_w := pf_all_t w, exact not_pred_w pred_w, end, end /- Satisfiability Satisfiability is about finding values for sub-propositions that make a larger proposition true. We typically like to formulate these questions in something known as conjunctive normal form (or CNF). In CNF we have a series of disjunctions, e.g., x1 ∨ x2 ∨ ¬x3 ∨ x4. These disjunctions are then combined into the larger proposition using conjunctions, e.g.: (x1 ∨ x2 ∨ ¬x3 ∨ x4) ∧ (¬x1 ∨ x2 ∨ ¬x3). For example, do there exist values for P and Q such that: (P ∨ Q) ∧ (¬P ∨ ¬Q) is true? -/ example: ∃(P Q: Prop), (P ∨ Q) ∧ (¬P ∨ ¬Q) := begin apply exists.intro true, apply exists.intro false, apply and.intro, -- prove true or false apply or.inl true.intro, -- prove not true or not false, apply or.inr false.elim, end /- Exercise: Do there exist values for P and Q such that: (P ∨ Q) ∧ (¬P ∨ ¬Q) ∧ (¬P or Q) is true? If so, prove it. -/ -- Answer: example: ∃(P Q: Prop), (P ∨ Q) ∧ (¬P ∨ ¬Q) ∧ (¬P ∨ Q) := begin apply exists.intro false, apply exists.intro true, apply and.intro, -- prove true or false apply or.inr true.intro, apply and.intro, -- prove not true or not false apply or.inl false.elim, -- prove not false or true apply or.inr true.intro end /- Exercise: Do there exist values for P and Q such that: (P ∨ Q) ∧ (¬P ∨ ¬Q) ∧ (¬P ∨ Q) ∧ (¬Q) is true? If so, prove it. -/ -- Answer: -- No such values exist /- 3-SAT 3-SAT is a special case of satisfiability (SAT) where there are no more than 3 terms in each disjunction. E.g., (P ∨ Q ∨ R) ∧ (¬P ∨ ¬Q ∨ ¬S) ∧ (¬P ∨ Q ∨ T) ∧ … 3-SAT is SAT, and 2-SAT is 3-SAT. The prior problems were technically all 3-SAT. All SAT problems can be reduced to 3-SAT problems. 3-SAT (and hence SAT) is NP-complete. Here is one that uses all 3 terms: Exercise: Do there exist values for P, Q, and R such that: (P ∨ Q ∨ R) ∧ (¬P ∨ ¬Q ∨ ¬R) ∧ (¬P ∨ Q ∨ R) ∧ (¬Q ∨ ¬R) is true? If so, prove it. -/ -- Answer: example: ∃(P Q R: Prop), (P ∨ Q ∨ R) ∧ (¬P ∨ ¬Q ∨ ¬R) ∧ (¬P ∨ Q ∨ R) ∧ (¬Q ∨ ¬R) := begin apply exists.intro false, apply exists.intro true, apply exists.intro false, apply and.intro, -- prove false ∨ true ∨ false apply or.inr, exact or.inl true.intro, apply and.intro, -- prove ¬false ∨ ¬true ∨ ¬false exact or.inl false.elim, apply and.intro, -- prove ¬false ∨ true ∨ false exact or.inl false.elim, -- prove ¬true or ¬false exact or.inr false.elim end
5ec40c2e3b11e920358d6a9c018161fb821cec7a
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/deprecated/subfield.lean
2c68a30c862e5f800032bc567e44c6b1a83d642f
[ "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
6,232
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 deprecated.subring /-! # Unbundled subfields (deprecated) > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file is deprecated, and is no longer imported by anything in mathlib other than other deprecated files, and test files. You should not need to import it. This file defines predicates for unbundled subfields. Instead of using this file, please use `subfield`, defined in `field_theory.subfield`, for subfields of fields. ## Main definitions `is_subfield (S : set F) : Prop` : the predicate that `S` is the underlying set of a subfield of the field `F`. The bundled variant `subfield F` should be used in preference to this. ## Tags is_subfield -/ variables {F : Type*} [field F] (S : set F) /-- `is_subfield (S : set F)` is the predicate saying that a given subset of a field is the set underlying a subfield. This structure is deprecated; use the bundled variant `subfield F` to model subfields of a field. -/ structure is_subfield extends is_subring S : Prop := (inv_mem : ∀ {x : F}, x ∈ S → x⁻¹ ∈ S) lemma is_subfield.div_mem {S : set F} (hS : is_subfield S) {x y : F} (hx : x ∈ S) (hy : y ∈ S) : x / y ∈ S := by { rw div_eq_mul_inv, exact hS.to_is_subring.to_is_submonoid.mul_mem hx (hS.inv_mem hy) } lemma is_subfield.pow_mem {a : F} {n : ℤ} {s : set F} (hs : is_subfield s) (h : a ∈ s) : a ^ n ∈ s := begin cases n, { rw zpow_of_nat, exact hs.to_is_subring.to_is_submonoid.pow_mem h }, { rw zpow_neg_succ_of_nat, exact hs.inv_mem (hs.to_is_subring.to_is_submonoid.pow_mem h) }, end lemma univ.is_subfield : is_subfield (@set.univ F) := { inv_mem := by intros; trivial, ..univ.is_submonoid, ..is_add_subgroup.univ_add_subgroup } lemma preimage.is_subfield {K : Type*} [field K] (f : F →+* K) {s : set K} (hs : is_subfield s) : is_subfield (f ⁻¹' s) := { inv_mem := λ a (ha : f a ∈ s), show f a⁻¹ ∈ s, by { rw [map_inv₀], exact hs.inv_mem ha }, ..f.is_subring_preimage hs.to_is_subring } lemma image.is_subfield {K : Type*} [field K] (f : F →+* K) {s : set F} (hs : is_subfield s) : is_subfield (f '' s) := { inv_mem := λ a ⟨x, xmem, ha⟩, ⟨x⁻¹, hs.inv_mem xmem, ha ▸ map_inv₀ f _⟩, ..f.is_subring_image hs.to_is_subring } lemma range.is_subfield {K : Type*} [field K] (f : F →+* K) : is_subfield (set.range f) := by { rw ← set.image_univ, apply image.is_subfield _ univ.is_subfield } namespace field /-- `field.closure s` is the minimal subfield that includes `s`. -/ 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, ring.closure.is_subring.to_is_submonoid.one_mem, div_one x⟩ lemma 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 ring.closure.is_subring.to_is_submonoid hp hr, q * s, is_submonoid.mul_mem ring.closure.is_subring.to_is_submonoid hq hs, (div_mul_div_comm _ _ _ _).symm⟩, one_mem := ring_closure_subset $ is_submonoid.one_mem ring.closure.is_subring.to_is_submonoid } lemma closure.is_subfield : is_subfield (closure S) := have h0 : (0:F) ∈ closure S, from ring_closure_subset $ ring.closure.is_subring.to_is_add_subgroup.to_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 ring.closure.is_subring.to_is_add_subgroup.to_is_add_submonoid (ring.closure.is_subring.to_is_submonoid.mul_mem hp hs) (ring.closure.is_subring.to_is_submonoid.mul_mem hq hr), q * s, ring.closure.is_subring.to_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, ring.closure.is_subring.to_is_add_subgroup.neg_mem hp, q, hq, neg_div q p⟩ end, inv_mem := begin rintros _ ⟨p, hp, q, hq, rfl⟩, exact ⟨q, hq, p, hp, (inv_div _ _).symm⟩ end, ..closure.is_submonoid } 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} (hT : is_subfield T) (H : S ⊆ T) : closure S ⊆ T := by rintros _ ⟨p, hp, q, hq, hq0, rfl⟩; exact hT.div_mem (ring.closure_subset hT.to_is_subring H hp) (ring.closure_subset hT.to_is_subring H hq) theorem closure_subset_iff {s t : set F} (ht : is_subfield t) : closure s ⊆ t ↔ s ⊆ t := ⟨set.subset.trans subset_closure, closure_subset ht⟩ theorem closure_mono {s t : set F} (H : s ⊆ t) : closure s ⊆ closure t := closure_subset closure.is_subfield $ set.subset.trans H subset_closure end field lemma is_subfield_Union_of_directed {ι : Type*} [hι : nonempty ι] {s : ι → set F} (hs : ∀ 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, (hs i).inv_mem hi⟩, to_is_subring := is_subring_Union_of_directed (λ i, (hs i).to_is_subring) directed } lemma is_subfield.inter {S₁ S₂ : set F} (hS₁ : is_subfield S₁) (hS₂ : is_subfield S₂) : is_subfield (S₁ ∩ S₂) := { inv_mem := λ x hx, ⟨hS₁.inv_mem hx.1, hS₂.inv_mem hx.2⟩, ..is_subring.inter hS₁.to_is_subring hS₂.to_is_subring } lemma is_subfield.Inter {ι : Sort*} {S : ι → set F} (h : ∀ y : ι, is_subfield (S y)) : is_subfield (set.Inter S) := { inv_mem := λ x hx, set.mem_Inter.2 $ λ y, (h y).inv_mem $ set.mem_Inter.1 hx y, ..is_subring.Inter (λ y, (h y).to_is_subring) }
1533f3868942178276fa3fa33ce46722b4323348
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/extra/755.hlean
c045817a603957f69e5ef4fb6972651e6ccc226b
[ "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,743
hlean
import types.eq types.pi hit.colimit open eq is_trunc unit quotient seq_colim equiv axiom mysorry : ∀ {A : Type*}, A namespace one_step_tr section parameters {A : Type*} variables (a a' : A) protected definition R (a a' : A) : Type₀ := unit parameter (A) definition one_step_tr : Type* := quotient R parameter {A} definition tr : one_step_tr := class_of R a definition tr_eq : tr a = tr a' := eq_of_rel _ star protected definition rec {P : one_step_tr → Type*} (Pt : Π(a : A), P (tr a)) (Pe : Π(a a' : A), Pt a =[tr_eq a a'] Pt a') (x : one_step_tr) : P x := begin fapply (quotient.rec_on x), { intro a, apply Pt}, { intro a a' H, cases H, apply Pe} end protected definition elim {P : Type*} (Pt : A → P) (Pe : Π(a a' : A), Pt a = Pt a') (x : one_step_tr) : P := rec Pt (λa a', pathover_of_eq (Pe a a')) x theorem rec_tr_eq {P : one_step_tr → Type*} (Pt : Π(a : A), P (tr a)) (Pe : Π(a a' : A), Pt a =[tr_eq a a'] Pt a') (a a' : A) : apdo (rec Pt Pe) (tr_eq a a') = Pe a a' := !rec_eq_of_rel theorem elim_tr_eq {P : Type*} (Pt : A → P) (Pe : Π(a a' : A), Pt a = Pt a') (a a' : A) : ap (elim Pt Pe) (tr_eq a a') = Pe a a' := begin apply eq_of_fn_eq_fn_inv !(pathover_constant (tr_eq a a')), rewrite [▸*,-apdo_eq_pathover_of_eq_ap,↑elim,rec_tr_eq], end end end one_step_tr attribute one_step_tr.rec one_step_tr.elim [recursor 5] open one_step_tr definition one_step_tr_up (A B : Type*) : (one_step_tr A → B) ≃ Σ(f : A → B), Π(x y : A), f x = f y := begin fapply equiv.MK, { intro f, fconstructor, intro a, exact f (tr a), intros, exact ap f !tr_eq}, { exact mysorry}, { exact mysorry}, { exact mysorry}, end
fafb9508a9101744469f14d920915cc34f6e9c4e
b73bd2854495d87ad5ce4f247cfcd6faa7e71c7e
/src/game/world3/level3.lean
0a461227079730e87bb9641bb3b715975a8aa5a4
[]
no_license
agusakov/category-theory-game
20db0b26270e0c95a3d5605498570273d72f731d
652dd7e90ae706643b2a597e2c938403653e167d
refs/heads/master
1,669,201,216,310
1,595,740,057,000
1,595,740,057,000
280,895,295
12
0
null
null
null
null
UTF-8
Lean
false
false
1,009
lean
import category_theory.category.default universes v u -- The order in this declaration matters: v often needs to be explicitly specified while u often can be omitted namespace category_theory variables (C : Type u) [category.{v} C] --rewrite this /- # Category world ## Level 7: Cancellations With monomorphisms and epimorphisms, we get some new useful cancellation laws. You will notice that the following two lemmas are pretty similar to the lemma we had in level 5 of world 1. See if you can spot the difference. -/ /- Lemma If $$f : X ⟶ Y$$ and $$g : X ⟶ Y$$ are morphisms such that $$f = g$$, then $$f ≫ h = g ≫ h$$. -/ lemma cancel_mono_id' (X Y : C) (f : X ⟶ Y) [mono f] {g : X ⟶ X} : (g ≫ f = f) ↔ g = 𝟙 X := begin split, intro hyp, rw ← category.id_comp f at hyp, rw ← category.assoc at hyp, rw category.comp_id at hyp, rw ← cancel_mono f, exact hyp, intro hyp, rw hyp, exact category.id_comp f, end end category_theory
a52962b49c344fad7ab3f71a2d6ec0175749da74
38bf3fd2bb651ab70511408fcf70e2029e2ba310
/src/analysis/complex/exponential.lean
cac139b2cd26e28d1e1a51e0612c5694619c0bfe
[ "Apache-2.0" ]
permissive
JaredCorduan/mathlib
130392594844f15dad65a9308c242551bae6cd2e
d5de80376088954d592a59326c14404f538050a1
refs/heads/master
1,595,862,206,333
1,570,816,457,000
1,570,816,457,000
209,134,499
0
0
Apache-2.0
1,568,746,811,000
1,568,746,811,000
null
UTF-8
Lean
false
false
74,177
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 -/ import topology.instances.complex tactic.linarith data.complex.exponential group_theory.quotient_group topology.metric_space.basic /-! # Exponential ## Main definitions This file contains the following definitions: • π, arcsin, arccos, arctan • argument of a complex number • logarithm on real and complex numbers • complex and real power function ## Main statements The following functions are shown to be continuous: • complex and real exponential function • sin, cos, tan, sinh, cosh • logarithm on real numbers • real power function • square root function ## Tags exp, log, sin, cos, tan, arcsin, arccos, arctan, angle, argument, power, square root, -/ open finset filter metric namespace complex lemma tendsto_exp_zero_one : tendsto exp (nhds 0) (nhds 1) := tendsto_nhds_nhds.2 $ λ ε ε0, ⟨min (ε / 2) 1, lt_min (div_pos ε0 (by norm_num)) (by norm_num), λ x h, have h : abs x < min (ε / 2) 1, by simpa [dist_eq] using h, calc abs (exp x - 1) ≤ 2 * abs x : abs_exp_sub_one_le (le_trans (le_of_lt h) (min_le_right _ _)) ... = abs x + abs x : two_mul (abs x) ... < ε / 2 + ε / 2 : add_lt_add (lt_of_lt_of_le h (min_le_left _ _)) (lt_of_lt_of_le h (min_le_left _ _)) ... = ε : by rw add_halves⟩ lemma continuous_exp : continuous exp := continuous_iff_continuous_at.2 (λ x, have H1 : tendsto (λ h, exp (x + h)) (nhds 0) (nhds (exp x)), by simpa [exp_add] using tendsto_mul tendsto_const_nhds tendsto_exp_zero_one, have H2 : tendsto (λ y, y - x) (nhds x) (nhds (x - x)) := tendsto_sub tendsto_id (@tendsto_const_nhds _ _ _ x _), suffices tendsto ((λ h, exp (x + h)) ∘ (λ y, id y - (λ z, x) y)) (nhds x) (nhds (exp x)), by simp only [function.comp, add_sub_cancel'_right, id.def] at this; exact this, tendsto.comp H1 (by rw [sub_self] at H2; exact H2)) lemma continuous_sin : continuous sin := continuous_mul (continuous_mul (continuous_sub (continuous_exp.comp (continuous_mul continuous_neg' continuous_const)) (continuous_exp.comp (continuous_mul continuous_id continuous_const))) continuous_const) continuous_const lemma continuous_cos : continuous cos := continuous_mul (continuous_add (continuous_exp.comp (continuous_mul continuous_id continuous_const)) (continuous_exp.comp (continuous_mul continuous_neg' continuous_const))) continuous_const lemma continuous_tan : continuous (λ x : {x // cos x ≠ 0}, tan x) := continuous_mul (continuous_sin.comp continuous_subtype_val) (continuous_inv subtype.property (continuous_cos.comp continuous_subtype_val)) lemma continuous_sinh : continuous sinh := continuous_mul (continuous_sub continuous_exp (continuous_exp.comp continuous_neg')) continuous_const lemma continuous_cosh : continuous cosh := continuous_mul (continuous_add continuous_exp (continuous_exp.comp continuous_neg')) continuous_const end complex namespace real variables {x y z : ℝ} lemma continuous_exp : continuous exp := complex.continuous_re.comp (complex.continuous_exp.comp complex.continuous_of_real) lemma continuous_sin : continuous sin := complex.continuous_re.comp (complex.continuous_sin.comp complex.continuous_of_real) lemma continuous_cos : continuous cos := complex.continuous_re.comp (complex.continuous_cos.comp complex.continuous_of_real) lemma continuous_tan : continuous (λ x : {x // cos x ≠ 0}, tan x) := by simp only [tan_eq_sin_div_cos]; exact continuous_mul (continuous_sin.comp continuous_subtype_val) (continuous_inv subtype.property (continuous_cos.comp continuous_subtype_val)) lemma continuous_sinh : continuous sinh := complex.continuous_re.comp (complex.continuous_sinh.comp complex.continuous_of_real) lemma continuous_cosh : continuous cosh := complex.continuous_re.comp (complex.continuous_cosh.comp complex.continuous_of_real) private lemma exists_exp_eq_of_one_le {x : ℝ} (hx : 1 ≤ x) : ∃ y, exp y = x := let ⟨y, hy⟩ := @intermediate_value real.exp 0 (x - 1) x (λ _ _ _, continuous_iff_continuous_at.1 continuous_exp _) (by simpa) (by simpa using add_one_le_exp_of_nonneg (sub_nonneg.2 hx)) (sub_nonneg.2 hx) in ⟨y, hy.2.2⟩ lemma exists_exp_eq_of_pos {x : ℝ} (hx : 0 < x) : ∃ y, exp y = x := match le_total x 1 with | (or.inl hx1) := let ⟨y, hy⟩ := exists_exp_eq_of_one_le (one_le_inv hx hx1) in ⟨-y, by rw [exp_neg, hy, inv_inv']⟩ | (or.inr hx1) := exists_exp_eq_of_one_le hx1 end noncomputable def log (x : ℝ) : ℝ := if hx : 0 < x then classical.some (exists_exp_eq_of_pos hx) else 0 lemma exp_log {x : ℝ} (hx : 0 < x) : exp (log x) = x := by rw [log, dif_pos hx]; exact classical.some_spec (exists_exp_eq_of_pos hx) @[simp] lemma log_exp (x : ℝ) : log (exp x) = x := exp_injective $ exp_log (exp_pos x) @[simp] lemma log_zero : log 0 = 0 := by simp [log, lt_irrefl] @[simp] lemma log_one : log 1 = 0 := exp_injective $ by rw [exp_log zero_lt_one, exp_zero] lemma log_mul {x y : ℝ} (hx : 0 < x) (hy : 0 < y) : log (x * y) = log x + log y := exp_injective $ by rw [exp_log (mul_pos hx hy), exp_add, exp_log hx, exp_log hy] lemma log_le_log {x y : ℝ} (h : 0 < x) (h₁ : 0 < y) : real.log x ≤ real.log y ↔ x ≤ y := ⟨λ h₂, by rwa [←real.exp_le_exp, real.exp_log h, real.exp_log h₁] at h₂, λ h₂, (real.exp_le_exp).1 $ by rwa [real.exp_log h₁, real.exp_log h]⟩ lemma log_lt_log (hx : 0 < x) : x < y → log x < log y := by { intro h, rwa [← exp_lt_exp, exp_log hx, exp_log (lt_trans hx h)] } lemma log_lt_log_iff (hx : 0 < x) (hy : 0 < y) : log x < log y ↔ x < y := by { rw [← exp_lt_exp, exp_log hx, exp_log hy] } lemma log_pos_iff (x : ℝ) : 0 < log x ↔ 1 < x := begin by_cases h : 0 < x, { rw ← log_one, exact log_lt_log_iff (by norm_num) h }, { rw [log, dif_neg], split, repeat {intro, linarith} } end lemma log_pos : 1 < x → 0 < log x := (log_pos_iff x).2 lemma log_neg_iff (h : 0 < x) : log x < 0 ↔ x < 1 := by { rw ← log_one, exact log_lt_log_iff h (by norm_num) } lemma log_neg (h0 : 0 < x) (h1 : x < 1) : log x < 0 := (log_neg_iff h0).2 h1 lemma log_nonneg : 1 ≤ x → 0 ≤ log x := by { intro, rwa [← log_one, log_le_log], norm_num, linarith } lemma log_nonpos : x ≤ 1 → log x ≤ 0 := begin intro, by_cases hx : 0 < x, { rwa [← log_one, log_le_log], exact hx, norm_num }, { simp [log, dif_neg hx] } end section prove_log_is_continuous lemma tendsto_log_one_zero : tendsto log (nhds 1) (nhds 0) := begin rw tendsto_nhds_nhds, assume ε ε0, let δ := min (exp ε - 1) (1 - exp (-ε)), have : 0 < δ, refine lt_min (sub_pos_of_lt (by rwa one_lt_exp_iff)) (sub_pos_of_lt _), by { rw exp_lt_one_iff, linarith }, use [δ, this], assume x h, cases le_total 1 x with hx hx, { have h : x < exp ε, rw [dist_eq, abs_of_nonneg (sub_nonneg_of_le hx)] at h, linarith [(min_le_left _ _ : δ ≤ exp ε - 1)], calc abs (log x - 0) = abs (log x) : by simp ... = log x : abs_of_nonneg $ log_nonneg hx ... < ε : by { rwa [← exp_lt_exp, exp_log], linarith }}, { have h : exp (-ε) < x, rw [dist_eq, abs_of_nonpos (sub_nonpos_of_le hx)] at h, linarith [(min_le_right _ _ : δ ≤ 1 - exp (-ε))], have : 0 < x := lt_trans (exp_pos _) h, calc abs (log x - 0) = abs (log x) : by simp ... = -log x : abs_of_nonpos $ log_nonpos hx ... < ε : by { rw [neg_lt, ← exp_lt_exp, exp_log], assumption' } } end lemma continuous_log' : continuous (λx : {x:ℝ // 0 < x}, log x.val) := continuous_iff_continuous_at.2 $ λ x, begin rw continuous_at, let f₁ := λ h:{h:ℝ // 0 < h}, log (x.1 * h.1), let f₂ := λ y:{y:ℝ // 0 < y}, subtype.mk (x.1 ⁻¹ * y.1) (mul_pos (inv_pos x.2) y.2), have H1 : tendsto f₁ (nhds ⟨1, zero_lt_one⟩) (nhds (log (x.1*1))), have : f₁ = λ h:{h:ℝ // 0 < h}, log x.1 + log h.1, ext h, rw ← log_mul x.2 h.2, simp only [this, log_mul x.2 zero_lt_one, log_one], exact tendsto_add tendsto_const_nhds (tendsto.comp tendsto_log_one_zero continuous_at_subtype_val), have H2 : tendsto f₂ (nhds x) (nhds ⟨x.1⁻¹ * x.1, mul_pos (inv_pos x.2) x.2⟩), rw tendsto_subtype_rng, exact tendsto_mul tendsto_const_nhds continuous_at_subtype_val, suffices h : tendsto (f₁ ∘ f₂) (nhds x) (nhds (log x.1)), begin convert h, ext y, have : x.val * (x.val⁻¹ * y.val) = y.val, rw [← mul_assoc, mul_inv_cancel (ne_of_gt x.2), one_mul], show log (y.val) = log (x.val * (x.val⁻¹ * y.val)), rw this end, exact tendsto.comp (by rwa mul_one at H1) (by { simp only [inv_mul_cancel (ne_of_gt x.2)] at H2, assumption }) end lemma continuous_at_log (hx : 0 < x) : continuous_at log x := continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_log' _ hx) (mem_nhds_sets (is_open_lt' _) hx) /-- Three forms of the continuity of `real.log` is provided. For the other two forms, see `real.continuous_log'` and `real.continuous_at_log` -/ lemma continuous_log {α : Type*} [topological_space α] {f : α → ℝ} (h : ∀a, 0 < f a) (hf : continuous f) : continuous (λa, log (f a)) := show continuous ((log ∘ @subtype.val ℝ (λr, 0 < r)) ∘ λa, ⟨f a, h a⟩), from continuous_log'.comp (continuous_subtype_mk _ hf) end prove_log_is_continuous lemma exists_cos_eq_zero : ∃ x, 1 ≤ x ∧ x ≤ 2 ∧ cos x = 0 := real.intermediate_value' (λ x _ _, continuous_iff_continuous_at.1 continuous_cos _) (le_of_lt cos_one_pos) (le_of_lt cos_two_neg) (by norm_num) noncomputable def pi : ℝ := 2 * classical.some exists_cos_eq_zero localized "notation `π` := real.pi" in real @[simp] lemma cos_pi_div_two : cos (π / 2) = 0 := by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)]; exact (classical.some_spec exists_cos_eq_zero).2.2 lemma one_le_pi_div_two : (1 : ℝ) ≤ π / 2 := by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)]; exact (classical.some_spec exists_cos_eq_zero).1 lemma pi_div_two_le_two : π / 2 ≤ 2 := by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)]; exact (classical.some_spec exists_cos_eq_zero).2.1 lemma two_le_pi : (2 : ℝ) ≤ π := (div_le_div_right (show (0 : ℝ) < 2, by norm_num)).1 (by rw div_self (@two_ne_zero' ℝ _ _ _); exact one_le_pi_div_two) lemma pi_le_four : π ≤ 4 := (div_le_div_right (show (0 : ℝ) < 2, by norm_num)).1 (calc π / 2 ≤ 2 : pi_div_two_le_two ... = 4 / 2 : by norm_num) lemma pi_pos : 0 < π := lt_of_lt_of_le (by norm_num) two_le_pi lemma pi_div_two_pos : 0 < π / 2 := half_pos pi_pos lemma two_pi_pos : 0 < 2 * π := by linarith [pi_pos] @[simp] lemma sin_pi : sin π = 0 := by rw [← mul_div_cancel_left pi (@two_ne_zero ℝ _), two_mul, add_div, sin_add, cos_pi_div_two]; simp @[simp] lemma cos_pi : cos π = -1 := by rw [← mul_div_cancel_left pi (@two_ne_zero ℝ _), mul_div_assoc, cos_two_mul, cos_pi_div_two]; simp [bit0, pow_add] @[simp] lemma sin_two_pi : sin (2 * π) = 0 := by simp [two_mul, sin_add] @[simp] lemma cos_two_pi : cos (2 * π) = 1 := by simp [two_mul, cos_add] lemma sin_add_pi (x : ℝ) : sin (x + π) = -sin x := by simp [sin_add] lemma sin_add_two_pi (x : ℝ) : sin (x + 2 * π) = sin x := by simp [sin_add_pi, sin_add, sin_two_pi, cos_two_pi] lemma cos_add_two_pi (x : ℝ) : cos (x + 2 * π) = cos x := by simp [cos_add, cos_two_pi, sin_two_pi] lemma sin_pi_sub (x : ℝ) : sin (π - x) = sin x := by simp [sin_add] lemma cos_add_pi (x : ℝ) : cos (x + π) = -cos x := by simp [cos_add] lemma cos_pi_sub (x : ℝ) : cos (π - x) = -cos x := by simp [cos_add] lemma sin_pos_of_pos_of_lt_pi {x : ℝ} (h0x : 0 < x) (hxp : x < π) : 0 < sin x := if hx2 : x ≤ 2 then sin_pos_of_pos_of_le_two h0x hx2 else have (2 : ℝ) + 2 = 4, from rfl, have π - x ≤ 2, from sub_le_iff_le_add.2 (le_trans pi_le_four (this ▸ add_le_add_left (le_of_not_ge hx2) _)), sin_pi_sub x ▸ sin_pos_of_pos_of_le_two (sub_pos.2 hxp) this lemma sin_nonneg_of_nonneg_of_le_pi {x : ℝ} (h0x : 0 ≤ x) (hxp : x ≤ π) : 0 ≤ sin x := match lt_or_eq_of_le h0x with | or.inl h0x := (lt_or_eq_of_le hxp).elim (le_of_lt ∘ sin_pos_of_pos_of_lt_pi h0x) (λ hpx, by simp [hpx]) | or.inr h0x := by simp [h0x.symm] end lemma sin_neg_of_neg_of_neg_pi_lt {x : ℝ} (hx0 : x < 0) (hpx : -π < x) : sin x < 0 := neg_pos.1 $ sin_neg x ▸ sin_pos_of_pos_of_lt_pi (neg_pos.2 hx0) (neg_lt.1 hpx) lemma sin_nonpos_of_nonnpos_of_neg_pi_le {x : ℝ} (hx0 : x ≤ 0) (hpx : -π ≤ x) : sin x ≤ 0 := neg_nonneg.1 $ sin_neg x ▸ sin_nonneg_of_nonneg_of_le_pi (neg_nonneg.2 hx0) (neg_le.1 hpx) @[simp] lemma sin_pi_div_two : sin (π / 2) = 1 := have sin (π / 2) = 1 ∨ sin (π / 2) = -1 := by simpa [pow_two, mul_self_eq_one_iff] using sin_sq_add_cos_sq (π / 2), this.resolve_right (λ h, (show ¬(0 : ℝ) < -1, by norm_num) $ h ▸ sin_pos_of_pos_of_lt_pi pi_div_two_pos (half_lt_self pi_pos)) lemma sin_add_pi_div_two (x : ℝ) : sin (x + π / 2) = cos x := by simp [sin_add] lemma sin_sub_pi_div_two (x : ℝ) : sin (x - π / 2) = -cos x := by simp [sin_add] lemma sin_pi_div_two_sub (x : ℝ) : sin (π / 2 - x) = cos x := by simp [sin_add] lemma cos_add_pi_div_two (x : ℝ) : cos (x + π / 2) = -sin x := by simp [cos_add] lemma cos_sub_pi_div_two (x : ℝ) : cos (x - π / 2) = sin x := by simp [cos_add] lemma cos_pi_div_two_sub (x : ℝ) : cos (π / 2 - x) = sin x := by rw [← cos_neg, neg_sub, cos_sub_pi_div_two] lemma cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two {x : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) : 0 < cos x := sin_add_pi_div_two x ▸ sin_pos_of_pos_of_lt_pi (by linarith) (by linarith) lemma cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two {x : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) : 0 ≤ cos x := match lt_or_eq_of_le hx₁, lt_or_eq_of_le hx₂ with | or.inl hx₁, or.inl hx₂ := le_of_lt (cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two hx₁ hx₂) | or.inl hx₁, or.inr hx₂ := by simp [hx₂] | or.inr hx₁, _ := by simp [hx₁.symm] end lemma cos_neg_of_pi_div_two_lt_of_lt {x : ℝ} (hx₁ : π / 2 < x) (hx₂ : x < π + π / 2) : cos x < 0 := neg_pos.1 $ cos_pi_sub x ▸ cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) (by linarith) lemma cos_nonpos_of_pi_div_two_le_of_le {x : ℝ} (hx₁ : π / 2 ≤ x) (hx₂ : x ≤ π + π / 2) : cos x ≤ 0 := neg_nonneg.1 $ cos_pi_sub x ▸ cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two (by linarith) (by linarith) lemma sin_nat_mul_pi (n : ℕ) : sin (n * π) = 0 := by induction n; simp [add_mul, sin_add, *] lemma sin_int_mul_pi (n : ℤ) : sin (n * π) = 0 := by cases n; simp [add_mul, sin_add, *, sin_nat_mul_pi] lemma cos_nat_mul_two_pi (n : ℕ) : cos (n * (2 * π)) = 1 := by induction n; simp [*, mul_add, cos_add, add_mul, cos_two_pi, sin_two_pi] lemma cos_int_mul_two_pi (n : ℤ) : cos (n * (2 * π)) = 1 := by cases n; simp only [cos_nat_mul_two_pi, int.of_nat_eq_coe, int.neg_succ_of_nat_coe, int.cast_coe_nat, int.cast_neg, (neg_mul_eq_neg_mul _ _).symm, cos_neg] lemma cos_int_mul_two_pi_add_pi (n : ℤ) : cos (n * (2 * π) + π) = -1 := by simp [cos_add, sin_add, cos_int_mul_two_pi] lemma sin_eq_zero_iff_of_lt_of_lt {x : ℝ} (hx₁ : -π < x) (hx₂ : x < π) : sin x = 0 ↔ x = 0 := ⟨λ h, le_antisymm (le_of_not_gt (λ h0, lt_irrefl (0 : ℝ) $ calc 0 < sin x : sin_pos_of_pos_of_lt_pi h0 hx₂ ... = 0 : h)) (le_of_not_gt (λ h0, lt_irrefl (0 : ℝ) $ calc 0 = sin x : h.symm ... < 0 : sin_neg_of_neg_of_neg_pi_lt h0 hx₁)), λ h, by simp [h]⟩ lemma sin_eq_zero_iff {x : ℝ} : sin x = 0 ↔ ∃ n : ℤ, (n : ℝ) * π = x := ⟨λ h, ⟨⌊x / π⌋, le_antisymm (sub_nonneg.1 (sub_floor_div_mul_nonneg _ pi_pos)) (sub_nonpos.1 $ le_of_not_gt $ λ h₃, ne_of_lt (sin_pos_of_pos_of_lt_pi h₃ (sub_floor_div_mul_lt _ pi_pos)) (by simp [sin_add, h, sin_int_mul_pi]))⟩, λ ⟨n, hn⟩, hn ▸ sin_int_mul_pi _⟩ lemma sin_eq_zero_iff_cos_eq {x : ℝ} : sin x = 0 ↔ cos x = 1 ∨ cos x = -1 := by rw [← mul_self_eq_one_iff (cos x), ← sin_sq_add_cos_sq x, pow_two, pow_two, ← sub_eq_iff_eq_add, sub_self]; exact ⟨λ h, by rw [h, mul_zero], eq_zero_of_mul_self_eq_zero ∘ eq.symm⟩ theorem sin_sub_sin (θ ψ : ℝ) : sin θ - sin ψ = 2 * sin((θ - ψ)/2) * cos((θ + ψ)/2) := begin have s1 := sin_add ((θ + ψ) / 2) ((θ - ψ) / 2), have s2 := sin_sub ((θ + ψ) / 2) ((θ - ψ) / 2), rw [div_add_div_same, add_sub, add_right_comm, add_sub_cancel, add_self_div_two] at s1, rw [div_sub_div_same, ←sub_add, add_sub_cancel', add_self_div_two] at s2, rw [s1, s2, ←sub_add, add_sub_cancel', ← two_mul, ← mul_assoc, mul_right_comm] end lemma cos_eq_one_iff (x : ℝ) : cos x = 1 ↔ ∃ n : ℤ, (n : ℝ) * (2 * π) = x := ⟨λ h, let ⟨n, hn⟩ := sin_eq_zero_iff.1 (sin_eq_zero_iff_cos_eq.2 (or.inl h)) in ⟨n / 2, (int.mod_two_eq_zero_or_one n).elim (λ hn0, by rwa [← mul_assoc, ← @int.cast_two ℝ, ← int.cast_mul, int.div_mul_cancel ((int.dvd_iff_mod_eq_zero _ _).2 hn0)]) (λ hn1, by rw [← int.mod_add_div n 2, hn1, int.cast_add, int.cast_one, add_mul, one_mul, add_comm, mul_comm (2 : ℤ), int.cast_mul, mul_assoc, int.cast_two] at hn; rw [← hn, cos_int_mul_two_pi_add_pi] at h; exact absurd h (by norm_num))⟩, λ ⟨n, hn⟩, hn ▸ cos_int_mul_two_pi _⟩ theorem cos_eq_zero_iff {θ : ℝ} : cos θ = 0 ↔ ∃ k : ℤ, θ = (2 * k + 1) * pi / 2 := begin rw [←real.sin_pi_div_two_sub, sin_eq_zero_iff], split, { rintro ⟨n, hn⟩, existsi -n, rw [int.cast_neg, add_mul, add_div, mul_assoc, mul_div_cancel_left _ two_ne_zero, one_mul, ←neg_mul_eq_neg_mul, hn, neg_sub, sub_add_cancel] }, { rintro ⟨n, hn⟩, existsi -n, rw [hn, add_mul, one_mul, add_div, mul_assoc, mul_div_cancel_left _ two_ne_zero, sub_add_eq_sub_sub_swap, sub_self, zero_sub, neg_mul_eq_neg_mul, int.cast_neg] } end lemma cos_eq_one_iff_of_lt_of_lt {x : ℝ} (hx₁ : -(2 * π) < x) (hx₂ : x < 2 * π) : cos x = 1 ↔ x = 0 := ⟨λ h, let ⟨n, hn⟩ := (cos_eq_one_iff x).1 h in begin clear _let_match, subst hn, rw [mul_lt_iff_lt_one_left two_pi_pos, ← int.cast_one, int.cast_lt, ← int.le_sub_one_iff, sub_self] at hx₂, rw [neg_lt, neg_mul_eq_neg_mul, mul_lt_iff_lt_one_left two_pi_pos, neg_lt, ← int.cast_one, ← int.cast_neg, int.cast_lt, ← int.add_one_le_iff, neg_add_self] at hx₁, exact mul_eq_zero.2 (or.inl (int.cast_eq_zero.2 (le_antisymm hx₂ hx₁))), end, λ h, by simp [h]⟩ theorem cos_sub_cos (θ ψ : ℝ) : cos θ - cos ψ = -2 * sin((θ + ψ)/2) * sin((θ - ψ)/2) := by rw [← sin_pi_div_two_sub, ← sin_pi_div_two_sub, sin_sub_sin, sub_sub_sub_cancel_left, add_sub, sub_add_eq_add_sub, add_halves, sub_sub, sub_div π, cos_pi_div_two_sub, ← neg_sub, neg_div, sin_neg, ← neg_mul_eq_mul_neg, neg_mul_eq_neg_mul, mul_right_comm] lemma cos_lt_cos_of_nonneg_of_le_pi_div_two {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π / 2) (hxy : x < y) : cos y < cos x := calc cos y = cos x * cos (y - x) - sin x * sin (y - x) : by rw [← cos_add, add_sub_cancel'_right] ... < (cos x * 1) - sin x * sin (y - x) : sub_lt_sub_right ((mul_lt_mul_left (cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (lt_of_lt_of_le (neg_neg_of_pos pi_div_two_pos) hx₁) (lt_of_lt_of_le hxy hy₂))).2 (lt_of_le_of_ne (cos_le_one _) (mt (cos_eq_one_iff_of_lt_of_lt (show -(2 * π) < y - x, by linarith) (show y - x < 2 * π, by linarith)).1 (sub_ne_zero.2 (ne_of_lt hxy).symm)))) _ ... ≤ _ : by rw mul_one; exact sub_le_self _ (mul_nonneg (sin_nonneg_of_nonneg_of_le_pi hx₁ (by linarith)) (sin_nonneg_of_nonneg_of_le_pi (by linarith) (by linarith))) lemma cos_lt_cos_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π) (hxy : x < y) : cos y < cos x := match (le_total x (π / 2) : x ≤ π / 2 ∨ π / 2 ≤ x), le_total y (π / 2) with | or.inl hx, or.inl hy := cos_lt_cos_of_nonneg_of_le_pi_div_two hx₁ hx hy₁ hy hxy | or.inl hx, or.inr hy := (lt_or_eq_of_le hx).elim (λ hx, calc cos y ≤ 0 : cos_nonpos_of_pi_div_two_le_of_le hy (by linarith [pi_pos]) ... < cos x : cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) hx) (λ hx, calc cos y < 0 : cos_neg_of_pi_div_two_lt_of_lt (by linarith) (by linarith [pi_pos]) ... = cos x : by rw [hx, cos_pi_div_two]) | or.inr hx, or.inl hy := by linarith | or.inr hx, or.inr hy := neg_lt_neg_iff.1 (by rw [← cos_pi_sub, ← cos_pi_sub]; apply cos_lt_cos_of_nonneg_of_le_pi_div_two; linarith) end lemma cos_le_cos_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π) (hxy : x ≤ y) : cos y ≤ cos x := (lt_or_eq_of_le hxy).elim (le_of_lt ∘ cos_lt_cos_of_nonneg_of_le_pi hx₁ hx₂ hy₁ hy₂) (λ h, h ▸ le_refl _) lemma sin_lt_sin_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : -(π / 2) ≤ y) (hy₂ : y ≤ π / 2) (hxy : x < y) : sin x < sin y := by rw [← cos_sub_pi_div_two, ← cos_sub_pi_div_two, ← cos_neg (x - _), ← cos_neg (y - _)]; apply cos_lt_cos_of_nonneg_of_le_pi; linarith lemma sin_le_sin_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : -(π / 2) ≤ y) (hy₂ : y ≤ π / 2) (hxy : x ≤ y) : sin x ≤ sin y := (lt_or_eq_of_le hxy).elim (le_of_lt ∘ sin_lt_sin_of_le_of_le_pi_div_two hx₁ hx₂ hy₁ hy₂) (λ h, h ▸ le_refl _) lemma sin_inj_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : -(π / 2) ≤ y) (hy₂ : y ≤ π / 2) (hxy : sin x = sin y) : x = y := match lt_trichotomy x y with | or.inl h := absurd (sin_lt_sin_of_le_of_le_pi_div_two hx₁ hx₂ hy₁ hy₂ h) (by rw hxy; exact lt_irrefl _) | or.inr (or.inl h) := h | or.inr (or.inr h) := absurd (sin_lt_sin_of_le_of_le_pi_div_two hy₁ hy₂ hx₁ hx₂ h) (by rw hxy; exact lt_irrefl _) end lemma cos_inj_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π) (hxy : cos x = cos y) : x = y := begin rw [← sin_pi_div_two_sub, ← sin_pi_div_two_sub] at hxy, refine (sub_left_inj).1 (sin_inj_of_le_of_le_pi_div_two _ _ _ _ hxy); linarith end lemma exists_sin_eq {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : ∃ y, -(π / 2) ≤ y ∧ y ≤ π / 2 ∧ sin y = x := @real.intermediate_value sin (-(π / 2)) (π / 2) x (λ _ _ _, continuous_iff_continuous_at.1 continuous_sin _) (by rwa [sin_neg, sin_pi_div_two]) (by rwa sin_pi_div_two) (le_trans (neg_nonpos.2 (le_of_lt pi_div_two_pos)) (le_of_lt pi_div_two_pos)) lemma sin_lt {x : ℝ} (h : 0 < x) : sin x < x := begin cases le_or_gt x 1 with h' h', { have hx : abs x = x := abs_of_nonneg (le_of_lt h), have : abs x ≤ 1, rwa [hx], have := sin_bound this, rw [abs_le] at this, have := this.2, rw [sub_le_iff_le_add', hx] at this, apply lt_of_le_of_lt this, rw [sub_add], apply lt_of_lt_of_le _ (le_of_eq (sub_zero x)), apply sub_lt_sub_left, rw sub_pos, apply mul_lt_mul', { rw [pow_succ x 3], refine le_trans _ (le_of_eq (one_mul _)), rw mul_le_mul_right, exact h', apply pow_pos h }, norm_num, norm_num, apply pow_pos h }, exact lt_of_le_of_lt (sin_le_one x) h' end /- note 1: this inequality is not tight, the tighter inequality is sin x > x - x ^ 3 / 6. note 2: this is also true for x > 1, but it's nontrivial for x just above 1. -/ lemma sin_gt_sub_cube {x : ℝ} (h : 0 < x) (h' : x ≤ 1) : sin x > x - x ^ 3 / 4 := begin have hx : abs x = x := abs_of_nonneg (le_of_lt h), have : abs x ≤ 1, rwa [hx], have := sin_bound this, rw [abs_le] at this, have := this.1, rw [le_sub_iff_add_le, hx] at this, refine lt_of_lt_of_le _ this, rw [add_comm, sub_add, sub_neg_eq_add], apply sub_lt_sub_left, apply add_lt_of_lt_sub_left, rw (show x ^ 3 / 4 - x ^ 3 / 6 = x ^ 3 / 12, by simp [div_eq_mul_inv, (mul_sub _ _ _).symm, -sub_eq_add_neg]; congr; norm_num), apply mul_lt_mul', { rw [pow_succ x 3], refine le_trans _ (le_of_eq (one_mul _)), rw mul_le_mul_right, exact h', apply pow_pos h }, norm_num, norm_num, apply pow_pos h end /-- The type of angles -/ def angle : Type := quotient_add_group.quotient (gmultiples (2 * π)) namespace angle instance angle.add_comm_group : add_comm_group angle := quotient_add_group.add_comm_group _ instance angle.has_coe : has_coe ℝ angle := ⟨quotient.mk'⟩ instance angle.is_add_group_hom : is_add_group_hom (coe : ℝ → angle) := @quotient_add_group.is_add_group_hom _ _ _ (normal_add_subgroup_of_add_comm_group _) @[simp] lemma coe_zero : ↑(0 : ℝ) = (0 : angle) := rfl @[simp] lemma coe_add (x y : ℝ) : ↑(x + y : ℝ) = (↑x + ↑y : angle) := rfl @[simp] lemma coe_neg (x : ℝ) : ↑(-x : ℝ) = -(↑x : angle) := rfl @[simp] lemma coe_sub (x y : ℝ) : ↑(x - y : ℝ) = (↑x - ↑y : angle) := rfl @[simp] lemma coe_gsmul (x : ℝ) (n : ℤ) : ↑(gsmul n x : ℝ) = gsmul n (↑x : angle) := is_add_group_hom.map_gsmul _ _ _ @[simp] lemma coe_two_pi : ↑(2 * π : ℝ) = (0 : angle) := quotient.sound' ⟨-1, by dsimp only; rw [neg_one_gsmul, add_zero]⟩ lemma angle_eq_iff_two_pi_dvd_sub {ψ θ : ℝ} : (θ : angle) = ψ ↔ ∃ k : ℤ, θ - ψ = 2 * π * k := by simp only [quotient_add_group.eq, gmultiples, set.mem_range, gsmul_eq_mul', (sub_eq_neg_add _ _).symm, eq_comm] theorem cos_eq_iff_eq_or_eq_neg {θ ψ : ℝ} : cos θ = cos ψ ↔ (θ : angle) = ψ ∨ (θ : angle) = -ψ := begin split, { intro Hcos, rw [←sub_eq_zero, cos_sub_cos, mul_eq_zero, mul_eq_zero, neg_eq_zero, eq_false_intro two_ne_zero, false_or, sin_eq_zero_iff, sin_eq_zero_iff] at Hcos, rcases Hcos with ⟨n, hn⟩ | ⟨n, hn⟩, { right, rw [eq_div_iff_mul_eq _ _ two_ne_zero, ← sub_eq_iff_eq_add] at hn, rw [← hn, coe_sub, eq_neg_iff_add_eq_zero, sub_add_cancel, mul_assoc, ← gsmul_eq_mul, coe_gsmul, mul_comm, coe_two_pi, gsmul_zero] }, { left, rw [eq_div_iff_mul_eq _ _ two_ne_zero, eq_sub_iff_add_eq] at hn, rw [← hn, coe_add, mul_assoc, ← gsmul_eq_mul, coe_gsmul, mul_comm, coe_two_pi, gsmul_zero, zero_add] } }, { rw [angle_eq_iff_two_pi_dvd_sub, ← coe_neg, angle_eq_iff_two_pi_dvd_sub], rintro (⟨k, H⟩ | ⟨k, H⟩), rw [← sub_eq_zero_iff_eq, cos_sub_cos, H, mul_assoc 2 π k, mul_div_cancel_left _ two_ne_zero, mul_comm π _, sin_int_mul_pi, mul_zero], rw [←sub_eq_zero_iff_eq, cos_sub_cos, ← sub_neg_eq_add, H, mul_assoc 2 π k, mul_div_cancel_left _ two_ne_zero, mul_comm π _, sin_int_mul_pi, mul_zero, zero_mul] } end theorem sin_eq_iff_eq_or_add_eq_pi {θ ψ : ℝ} : sin θ = sin ψ ↔ (θ : angle) = ψ ∨ (θ : angle) + ψ = π := begin split, { intro Hsin, rw [← cos_pi_div_two_sub, ← cos_pi_div_two_sub] at Hsin, cases cos_eq_iff_eq_or_eq_neg.mp Hsin with h h, { left, rw coe_sub at h, exact sub_left_inj.1 h }, right, rw [coe_sub, coe_sub, eq_neg_iff_add_eq_zero, add_sub, sub_add_eq_add_sub, ← coe_add, add_halves, sub_sub, sub_eq_zero] at h, exact h.symm }, { rw [angle_eq_iff_two_pi_dvd_sub, ←eq_sub_iff_add_eq, ←coe_sub, angle_eq_iff_two_pi_dvd_sub], rintro (⟨k, H⟩ | ⟨k, H⟩), rw [← sub_eq_zero_iff_eq, sin_sub_sin, H, mul_assoc 2 π k, mul_div_cancel_left _ two_ne_zero, mul_comm π _, sin_int_mul_pi, mul_zero, zero_mul], have H' : θ + ψ = (2 * k) * π + π := by rwa [←sub_add, sub_add_eq_add_sub, sub_eq_iff_eq_add, mul_assoc, mul_comm π _, ←mul_assoc] at H, rw [← sub_eq_zero_iff_eq, sin_sub_sin, H', add_div, mul_assoc 2 _ π, mul_div_cancel_left _ two_ne_zero, cos_add_pi_div_two, sin_int_mul_pi, neg_zero, mul_zero] } end theorem cos_sin_inj {θ ψ : ℝ} (Hcos : cos θ = cos ψ) (Hsin : sin θ = sin ψ) : (θ : angle) = ψ := begin cases cos_eq_iff_eq_or_eq_neg.mp Hcos with hc hc, { exact hc }, cases sin_eq_iff_eq_or_add_eq_pi.mp Hsin with hs hs, { exact hs }, rw [eq_neg_iff_add_eq_zero, hs] at hc, cases quotient.exact' hc with n hn, dsimp only at hn, rw [← neg_one_mul, add_zero, ← sub_eq_zero_iff_eq, gsmul_eq_mul, ← mul_assoc, ← sub_mul, mul_eq_zero, eq_false_intro (ne_of_gt pi_pos), or_false, sub_neg_eq_add, ← int.cast_zero, ← int.cast_one, ← int.cast_bit0, ← int.cast_mul, ← int.cast_add, int.cast_inj] at hn, have : (n * 2 + 1) % (2:ℤ) = 0 % (2:ℤ) := congr_arg (%(2:ℤ)) hn, rw [add_comm, int.add_mul_mod_self] at this, exact absurd this one_ne_zero end end angle /-- Inverse of the `sin` function, returns values in the range `-π / 2 ≤ arcsin x` and `arcsin x ≤ π / 2`. If the argument is not between `-1` and `1` it defaults to `0` -/ noncomputable def arcsin (x : ℝ) : ℝ := if hx : -1 ≤ x ∧ x ≤ 1 then classical.some (exists_sin_eq hx.1 hx.2) else 0 lemma arcsin_le_pi_div_two (x : ℝ) : arcsin x ≤ π / 2 := if hx : -1 ≤ x ∧ x ≤ 1 then by rw [arcsin, dif_pos hx]; exact (classical.some_spec (exists_sin_eq hx.1 hx.2)).2.1 else by rw [arcsin, dif_neg hx]; exact le_of_lt pi_div_two_pos lemma neg_pi_div_two_le_arcsin (x : ℝ) : -(π / 2) ≤ arcsin x := if hx : -1 ≤ x ∧ x ≤ 1 then by rw [arcsin, dif_pos hx]; exact (classical.some_spec (exists_sin_eq hx.1 hx.2)).1 else by rw [arcsin, dif_neg hx]; exact neg_nonpos.2 (le_of_lt pi_div_two_pos) lemma sin_arcsin {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : sin (arcsin x) = x := by rw [arcsin, dif_pos (and.intro hx₁ hx₂)]; exact (classical.some_spec (exists_sin_eq hx₁ hx₂)).2.2 lemma arcsin_sin {x : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) : arcsin (sin x) = x := sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) hx₁ hx₂ (by rw sin_arcsin (neg_one_le_sin _) (sin_le_one _)) lemma arcsin_inj {x y : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) (hy₁ : -1 ≤ y) (hy₂ : y ≤ 1) (hxy : arcsin x = arcsin y) : x = y := by rw [← sin_arcsin hx₁ hx₂, ← sin_arcsin hy₁ hy₂, hxy] @[simp] lemma arcsin_zero : arcsin 0 = 0 := sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (neg_nonpos.2 (le_of_lt pi_div_two_pos)) (le_of_lt pi_div_two_pos) (by rw [sin_arcsin, sin_zero]; norm_num) @[simp] lemma arcsin_one : arcsin 1 = π / 2 := sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (by linarith [pi_pos]) (le_refl _) (by rw [sin_arcsin, sin_pi_div_two]; norm_num) @[simp] lemma arcsin_neg (x : ℝ) : arcsin (-x) = -arcsin x := if h : -1 ≤ x ∧ x ≤ 1 then have -1 ≤ -x ∧ -x ≤ 1, by rwa [neg_le_neg_iff, neg_le, and.comm], sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (neg_le_neg (arcsin_le_pi_div_two _)) (neg_le.1 (neg_pi_div_two_le_arcsin _)) (by rw [sin_arcsin this.1 this.2, sin_neg, sin_arcsin h.1 h.2]) else have ¬(-1 ≤ -x ∧ -x ≤ 1) := by rwa [neg_le_neg_iff, neg_le, and.comm], by rw [arcsin, arcsin, dif_neg h, dif_neg this, neg_zero] @[simp] lemma arcsin_neg_one : arcsin (-1) = -(π / 2) := by simp lemma arcsin_nonneg {x : ℝ} (hx : 0 ≤ x) : 0 ≤ arcsin x := if hx₁ : x ≤ 1 then not_lt.1 (λ h, not_lt.2 hx begin have := sin_lt_sin_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (neg_nonpos.2 (le_of_lt pi_div_two_pos)) (le_of_lt pi_div_two_pos) h, rw [real.sin_arcsin, sin_zero] at this; linarith end) else by rw [arcsin, dif_neg]; simp [hx₁] lemma arcsin_eq_zero_iff {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : arcsin x = 0 ↔ x = 0 := ⟨λ h, have sin (arcsin x) = 0, by simp [h], by rwa [sin_arcsin hx₁ hx₂] at this, λ h, by simp [h]⟩ lemma arcsin_pos {x : ℝ} (hx₁ : 0 < x) (hx₂ : x ≤ 1) : 0 < arcsin x := lt_of_le_of_ne (arcsin_nonneg (le_of_lt hx₁)) (ne.symm (mt (arcsin_eq_zero_iff (by linarith) hx₂).1 (ne_of_lt hx₁).symm)) lemma arcsin_nonpos {x : ℝ} (hx : x ≤ 0) : arcsin x ≤ 0 := neg_nonneg.1 (arcsin_neg x ▸ arcsin_nonneg (neg_nonneg.2 hx)) /-- Inverse of the `cos` function, returns values in the range `0 ≤ arccos x` and `arccos x ≤ π`. If the argument is not between `-1` and `1` it defaults to `π / 2` -/ noncomputable def arccos (x : ℝ) : ℝ := π / 2 - arcsin x lemma arccos_eq_pi_div_two_sub_arcsin (x : ℝ) : arccos x = π / 2 - arcsin x := rfl lemma arcsin_eq_pi_div_two_sub_arccos (x : ℝ) : arcsin x = π / 2 - arccos x := by simp [arccos] lemma arccos_le_pi (x : ℝ) : arccos x ≤ π := by unfold arccos; linarith [neg_pi_div_two_le_arcsin x] lemma arccos_nonneg (x : ℝ) : 0 ≤ arccos x := by unfold arccos; linarith [arcsin_le_pi_div_two x] lemma cos_arccos {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : cos (arccos x) = x := by rw [arccos, cos_pi_div_two_sub, sin_arcsin hx₁ hx₂] lemma arccos_cos {x : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) : arccos (cos x) = x := by rw [arccos, ← sin_pi_div_two_sub, arcsin_sin]; simp; linarith lemma arccos_inj {x y : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) (hy₁ : -1 ≤ y) (hy₂ : y ≤ 1) (hxy : arccos x = arccos y) : x = y := arcsin_inj hx₁ hx₂ hy₁ hy₂ $ by simp [arccos, *] at * @[simp] lemma arccos_zero : arccos 0 = π / 2 := by simp [arccos] @[simp] lemma arccos_one : arccos 1 = 0 := by simp [arccos] @[simp] lemma arccos_neg_one : arccos (-1) = π := by simp [arccos, add_halves] lemma arccos_neg (x : ℝ) : arccos (-x) = π - arccos x := by rw [← add_halves π, arccos, arcsin_neg, arccos, add_sub_assoc, sub_sub_self]; simp lemma cos_arcsin_nonneg (x : ℝ) : 0 ≤ cos (arcsin x) := cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) lemma cos_arcsin {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : cos (arcsin x) = sqrt (1 - x ^ 2) := have sin (arcsin x) ^ 2 + cos (arcsin x) ^ 2 = 1 := sin_sq_add_cos_sq (arcsin x), begin rw [← eq_sub_iff_add_eq', ← sqrt_inj (pow_two_nonneg _) (sub_nonneg.2 (sin_sq_le_one (arcsin x))), pow_two, sqrt_mul_self (cos_arcsin_nonneg _)] at this, rw [this, sin_arcsin hx₁ hx₂], end lemma sin_arccos {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : sin (arccos x) = sqrt (1 - x ^ 2) := by rw [arccos_eq_pi_div_two_sub_arcsin, sin_pi_div_two_sub, cos_arcsin hx₁ hx₂] lemma abs_div_sqrt_one_add_lt (x : ℝ) : abs (x / sqrt (1 + x ^ 2)) < 1 := have h₁ : 0 < 1 + x ^ 2, from add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg _), have h₂ : 0 < sqrt (1 + x ^ 2), from sqrt_pos.2 h₁, by rw [abs_div, div_lt_iff (abs_pos_of_pos h₂), one_mul, mul_self_lt_mul_self_iff (abs_nonneg x) (abs_nonneg _), ← abs_mul, ← abs_mul, mul_self_sqrt (add_nonneg zero_le_one (pow_two_nonneg _)), abs_of_nonneg (mul_self_nonneg x), abs_of_nonneg (le_of_lt h₁), pow_two, add_comm]; exact lt_add_one _ lemma div_sqrt_one_add_lt_one (x : ℝ) : x / sqrt (1 + x ^ 2) < 1 := (abs_lt.1 (abs_div_sqrt_one_add_lt _)).2 lemma neg_one_lt_div_sqrt_one_add (x : ℝ) : -1 < x / sqrt (1 + x ^ 2) := (abs_lt.1 (abs_div_sqrt_one_add_lt _)).1 lemma tan_pos_of_pos_of_lt_pi_div_two {x : ℝ} (h0x : 0 < x) (hxp : x < π / 2) : 0 < tan x := by rw tan_eq_sin_div_cos; exact div_pos (sin_pos_of_pos_of_lt_pi h0x (by linarith)) (cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) hxp) lemma tan_nonneg_of_nonneg_of_le_pi_div_two {x : ℝ} (h0x : 0 ≤ x) (hxp : x ≤ π / 2) : 0 ≤ tan x := match lt_or_eq_of_le h0x, lt_or_eq_of_le hxp with | or.inl hx0, or.inl hxp := le_of_lt (tan_pos_of_pos_of_lt_pi_div_two hx0 hxp) | or.inl hx0, or.inr hxp := by simp [hxp, tan_eq_sin_div_cos] | or.inr hx0, _ := by simp [hx0.symm] end lemma tan_neg_of_neg_of_pi_div_two_lt {x : ℝ} (hx0 : x < 0) (hpx : -(π / 2) < x) : tan x < 0 := neg_pos.1 (tan_neg x ▸ tan_pos_of_pos_of_lt_pi_div_two (by linarith) (by linarith [pi_pos])) lemma tan_nonpos_of_nonpos_of_neg_pi_div_two_le {x : ℝ} (hx0 : x ≤ 0) (hpx : -(π / 2) ≤ x) : tan x ≤ 0 := neg_nonneg.1 (tan_neg x ▸ tan_nonneg_of_nonneg_of_le_pi_div_two (by linarith) (by linarith [pi_pos])) lemma tan_lt_tan_of_nonneg_of_lt_pi_div_two {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x < π / 2) (hy₁ : 0 ≤ y) (hy₂ : y < π / 2) (hxy : x < y) : tan x < tan y := begin rw [tan_eq_sin_div_cos, tan_eq_sin_div_cos], exact div_lt_div (sin_lt_sin_of_le_of_le_pi_div_two (by linarith) (le_of_lt hx₂) (by linarith) (le_of_lt hy₂) hxy) (cos_le_cos_of_nonneg_of_le_pi hx₁ (by linarith) hy₁ (by linarith) (le_of_lt hxy)) (sin_nonneg_of_nonneg_of_le_pi hy₁ (by linarith)) (cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) hy₂) end lemma tan_lt_tan_of_lt_of_lt_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) (hy₁ : -(π / 2) < y) (hy₂ : y < π / 2) (hxy : x < y) : tan x < tan y := match le_total x 0, le_total y 0 with | or.inl hx0, or.inl hy0 := neg_lt_neg_iff.1 $ by rw [← tan_neg, ← tan_neg]; exact tan_lt_tan_of_nonneg_of_lt_pi_div_two (neg_nonneg.2 hy0) (neg_lt.2 hy₁) (neg_nonneg.2 hx0) (neg_lt.2 hx₁) (neg_lt_neg hxy) | or.inl hx0, or.inr hy0 := (lt_or_eq_of_le hy0).elim (λ hy0, calc tan x ≤ 0 : tan_nonpos_of_nonpos_of_neg_pi_div_two_le hx0 (le_of_lt hx₁) ... < tan y : tan_pos_of_pos_of_lt_pi_div_two hy0 hy₂) (λ hy0, by rw [← hy0, tan_zero]; exact tan_neg_of_neg_of_pi_div_two_lt (hy0.symm ▸ hxy) hx₁) | or.inr hx0, or.inl hy0 := by linarith | or.inr hx0, or.inr hy0 := tan_lt_tan_of_nonneg_of_lt_pi_div_two hx0 hx₂ hy0 hy₂ hxy end lemma tan_inj_of_lt_of_lt_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) (hy₁ : -(π / 2) < y) (hy₂ : y < π / 2) (hxy : tan x = tan y) : x = y := match lt_trichotomy x y with | or.inl h := absurd (tan_lt_tan_of_lt_of_lt_pi_div_two hx₁ hx₂ hy₁ hy₂ h) (by rw hxy; exact lt_irrefl _) | or.inr (or.inl h) := h | or.inr (or.inr h) := absurd (tan_lt_tan_of_lt_of_lt_pi_div_two hy₁ hy₂ hx₁ hx₂ h) (by rw hxy; exact lt_irrefl _) end /-- Inverse of the `tan` function, returns values in the range `-π / 2 < arctan x` and `arctan x < π / 2` -/ noncomputable def arctan (x : ℝ) : ℝ := arcsin (x / sqrt (1 + x ^ 2)) lemma sin_arctan (x : ℝ) : sin (arctan x) = x / sqrt (1 + x ^ 2) := sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)) lemma cos_arctan (x : ℝ) : cos (arctan x) = 1 / sqrt (1 + x ^ 2) := have h₁ : (0 : ℝ) < 1 + x ^ 2, from add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg _), have h₂ : (x / sqrt (1 + x ^ 2)) ^ 2 < 1, by rw [pow_two, ← abs_mul_self, _root_.abs_mul]; exact mul_lt_one_of_nonneg_of_lt_one_left (abs_nonneg _) (abs_div_sqrt_one_add_lt _) (le_of_lt (abs_div_sqrt_one_add_lt _)), by rw [arctan, cos_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)), one_div_eq_inv, ← sqrt_inv, sqrt_inj (sub_nonneg.2 (le_of_lt h₂)) (inv_nonneg.2 (le_of_lt h₁)), div_pow _ (mt sqrt_eq_zero'.1 (not_le.2 h₁)), pow_two (sqrt _), mul_self_sqrt (le_of_lt h₁), ← domain.mul_left_inj (ne.symm (ne_of_lt h₁)), mul_sub, mul_div_cancel' _ (ne.symm (ne_of_lt h₁)), mul_inv_cancel (ne.symm (ne_of_lt h₁))]; simp lemma tan_arctan (x : ℝ) : tan (arctan x) = x := by rw [tan_eq_sin_div_cos, sin_arctan, cos_arctan, div_div_div_div_eq, mul_one, mul_div_assoc, div_self (mt sqrt_eq_zero'.1 (not_le_of_gt (add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg x)))), mul_one] lemma arctan_lt_pi_div_two (x : ℝ) : arctan x < π / 2 := lt_of_le_of_ne (arcsin_le_pi_div_two _) (λ h, ne_of_lt (div_sqrt_one_add_lt_one x) $ by rw [← sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)), ← arctan, h, sin_pi_div_two]) lemma neg_pi_div_two_lt_arctan (x : ℝ) : -(π / 2) < arctan x := lt_of_le_of_ne (neg_pi_div_two_le_arcsin _) (λ h, ne_of_lt (neg_one_lt_div_sqrt_one_add x) $ by rw [← sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)), ← arctan, ← h, sin_neg, sin_pi_div_two]) lemma tan_surjective : function.surjective tan := function.surjective_of_has_right_inverse ⟨_, tan_arctan⟩ lemma arctan_tan {x : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) : arctan (tan x) = x := tan_inj_of_lt_of_lt_pi_div_two (neg_pi_div_two_lt_arctan _) (arctan_lt_pi_div_two _) hx₁ hx₂ (by rw tan_arctan) @[simp] lemma arctan_zero : arctan 0 = 0 := by simp [arctan] @[simp] lemma arctan_neg (x : ℝ) : arctan (-x) = - arctan x := by simp [arctan, neg_div] end real namespace complex open_locale real /-- `arg` returns values in the range (-π, π], such that for `x ≠ 0`, `sin (arg x) = x.im / x.abs` and `cos (arg x) = x.re / x.abs`, `arg 0` defaults to `0` -/ noncomputable def arg (x : ℂ) : ℝ := if 0 ≤ x.re then real.arcsin (x.im / x.abs) else if 0 ≤ x.im then real.arcsin ((-x).im / x.abs) + π else real.arcsin ((-x).im / x.abs) - π lemma arg_le_pi (x : ℂ) : arg x ≤ π := if hx₁ : 0 ≤ x.re then by rw [arg, if_pos hx₁]; exact le_trans (real.arcsin_le_pi_div_two _) (le_of_lt (half_lt_self real.pi_pos)) else have hx : x ≠ 0, from λ h, by simpa [h, lt_irrefl] using hx₁, if hx₂ : 0 ≤ x.im then by rw [arg, if_neg hx₁, if_pos hx₂]; exact le_sub_iff_add_le.1 (by rw sub_self; exact real.arcsin_nonpos (by rw [neg_im, neg_div, neg_nonpos]; exact div_nonneg hx₂ (abs_pos.2 hx))) else by rw [arg, if_neg hx₁, if_neg hx₂]; exact sub_le_iff_le_add.2 (le_trans (real.arcsin_le_pi_div_two _) (by linarith [real.pi_pos])) lemma neg_pi_lt_arg (x : ℂ) : -π < arg x := if hx₁ : 0 ≤ x.re then by rw [arg, if_pos hx₁]; exact lt_of_lt_of_le (neg_lt_neg (half_lt_self real.pi_pos)) (real.neg_pi_div_two_le_arcsin _) else have hx : x ≠ 0, from λ h, by simpa [h, lt_irrefl] using hx₁, if hx₂ : 0 ≤ x.im then by rw [arg, if_neg hx₁, if_pos hx₂]; exact sub_lt_iff_lt_add.1 (lt_of_lt_of_le (by linarith [real.pi_pos]) (real.neg_pi_div_two_le_arcsin _)) else by rw [arg, if_neg hx₁, if_neg hx₂]; exact lt_sub_iff_add_lt.2 (by rw neg_add_self; exact real.arcsin_pos (by rw [neg_im]; exact div_pos (neg_pos.2 (lt_of_not_ge hx₂)) (abs_pos.2 hx)) (by rw [← abs_neg x]; exact (abs_le.1 (abs_im_div_abs_le_one _)).2)) lemma arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg {x : ℂ} (hxr : x.re < 0) (hxi : 0 ≤ x.im) : arg x = arg (-x) + π := have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos], by rw [arg, arg, if_neg (not_le.2 hxr), if_pos this, if_pos hxi, abs_neg] lemma arg_eq_arg_neg_sub_pi_of_im_neg_of_re_neg {x : ℂ} (hxr : x.re < 0) (hxi : x.im < 0) : arg x = arg (-x) - π := have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos], by rw [arg, arg, if_neg (not_le.2 hxr), if_neg (not_le.2 hxi), if_pos this, abs_neg] @[simp] lemma arg_zero : arg 0 = 0 := by simp [arg, le_refl] @[simp] lemma arg_one : arg 1 = 0 := by simp [arg, zero_le_one] @[simp] lemma arg_neg_one : arg (-1) = π := by simp [arg, le_refl, not_le.2 (@zero_lt_one ℝ _)] @[simp] lemma arg_I : arg I = π / 2 := by simp [arg, le_refl] @[simp] lemma arg_neg_I : arg (-I) = -(π / 2) := by simp [arg, le_refl] lemma sin_arg (x : ℂ) : real.sin (arg x) = x.im / x.abs := by unfold arg; split_ifs; simp [arg, real.sin_arcsin (abs_le.1 (abs_im_div_abs_le_one x)).1 (abs_le.1 (abs_im_div_abs_le_one x)).2, real.sin_add, neg_div, real.arcsin_neg, real.sin_neg] private lemma cos_arg_of_re_nonneg {x : ℂ} (hx : x ≠ 0) (hxr : 0 ≤ x.re) : real.cos (arg x) = x.re / x.abs := have 0 ≤ 1 - (x.im / abs x) ^ 2, from sub_nonneg.2 $ by rw [pow_two, ← _root_.abs_mul_self, _root_.abs_mul, ← pow_two]; exact pow_le_one _ (_root_.abs_nonneg _) (abs_im_div_abs_le_one _), by rw [eq_div_iff_mul_eq _ _ (mt abs_eq_zero.1 hx), ← real.mul_self_sqrt (abs_nonneg x), arg, if_pos hxr, real.cos_arcsin (abs_le.1 (abs_im_div_abs_le_one x)).1 (abs_le.1 (abs_im_div_abs_le_one x)).2, ← real.sqrt_mul (abs_nonneg _), ← real.sqrt_mul this, sub_mul, div_pow _ (mt abs_eq_zero.1 hx), ← pow_two, div_mul_cancel _ (pow_ne_zero 2 (mt abs_eq_zero.1 hx)), one_mul, pow_two, mul_self_abs, norm_sq, pow_two, add_sub_cancel, real.sqrt_mul_self hxr] lemma cos_arg {x : ℂ} (hx : x ≠ 0) : real.cos (arg x) = x.re / x.abs := if hxr : 0 ≤ x.re then cos_arg_of_re_nonneg hx hxr else have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos] using hxr, if hxi : 0 ≤ x.im then have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos] using hxr, by rw [arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg (not_le.1 hxr) hxi, real.cos_add_pi, cos_arg_of_re_nonneg (neg_ne_zero.2 hx) this]; simp [neg_div] else by rw [arg_eq_arg_neg_sub_pi_of_im_neg_of_re_neg (not_le.1 hxr) (not_le.1 hxi)]; simp [real.cos_add, neg_div, cos_arg_of_re_nonneg (neg_ne_zero.2 hx) this] lemma tan_arg {x : ℂ} : real.tan (arg x) = x.im / x.re := if hx : x = 0 then by simp [hx] else by rw [real.tan_eq_sin_div_cos, sin_arg, cos_arg hx, div_div_div_cancel_right _ _ (mt abs_eq_zero.1 hx)] lemma arg_cos_add_sin_mul_I {x : ℝ} (hx₁ : -π < x) (hx₂ : x ≤ π) : arg (cos x + sin x * I) = x := if hx₃ : -(π / 2) ≤ x ∧ x ≤ π / 2 then have hx₄ : 0 ≤ (cos x + sin x * I).re, by simp; exact real.cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two hx₃.1 hx₃.2, by rw [arg, if_pos hx₄]; simp [abs_cos_add_sin_mul_I, sin_of_real_re, real.arcsin_sin hx₃.1 hx₃.2] else if hx₄ : x < -(π / 2) then have hx₅ : ¬0 ≤ (cos x + sin x * I).re := suffices ¬ 0 ≤ real.cos x, by simpa, not_le.2 $ by rw ← real.cos_neg; apply real.cos_neg_of_pi_div_two_lt_of_lt; linarith, have hx₆ : ¬0 ≤ (cos ↑x + sin ↑x * I).im := suffices real.sin x < 0, by simpa, by apply real.sin_neg_of_neg_of_neg_pi_lt; linarith, suffices -π + -real.arcsin (real.sin x) = x, by rw [arg, if_neg hx₅, if_neg hx₆]; simpa [abs_cos_add_sin_mul_I, sin_of_real_re], by rw [← real.arcsin_neg, ← real.sin_add_pi, real.arcsin_sin]; simp; linarith else have hx₅ : π / 2 < x, by cases not_and_distrib.1 hx₃; linarith, have hx₆ : ¬0 ≤ (cos x + sin x * I).re := suffices ¬0 ≤ real.cos x, by simpa, not_le.2 $ by apply real.cos_neg_of_pi_div_two_lt_of_lt; linarith, have hx₇ : 0 ≤ (cos x + sin x * I).im := suffices 0 ≤ real.sin x, by simpa, by apply real.sin_nonneg_of_nonneg_of_le_pi; linarith, suffices π - real.arcsin (real.sin x) = x, by rw [arg, if_neg hx₆, if_pos hx₇]; simpa [abs_cos_add_sin_mul_I, sin_of_real_re], by rw [← real.sin_pi_sub, real.arcsin_sin]; simp; linarith lemma arg_eq_arg_iff {x y : ℂ} (hx : x ≠ 0) (hy : y ≠ 0) : arg x = arg y ↔ (abs y / abs x : ℂ) * x = y := have hax : abs x ≠ 0, from (mt abs_eq_zero.1 hx), have hay : abs y ≠ 0, from (mt abs_eq_zero.1 hy), ⟨λ h, begin have hcos := congr_arg real.cos h, rw [cos_arg hx, cos_arg hy, div_eq_div_iff hax hay] at hcos, have hsin := congr_arg real.sin h, rw [sin_arg, sin_arg, div_eq_div_iff hax hay] at hsin, apply complex.ext, { rw [mul_re, ← of_real_div, of_real_re, of_real_im, zero_mul, sub_zero, mul_comm, ← mul_div_assoc, hcos, mul_div_cancel _ hax] }, { rw [mul_im, ← of_real_div, of_real_re, of_real_im, zero_mul, add_zero, mul_comm, ← mul_div_assoc, hsin, mul_div_cancel _ hax] } end, λ h, have hre : abs (y / x) * x.re = y.re, by rw ← of_real_div at h; simpa [-of_real_div] using congr_arg re h, have hre' : abs (x / y) * y.re = x.re, by rw [← hre, abs_div, abs_div, ← mul_assoc, div_mul_div, mul_comm (abs _), div_self (mul_ne_zero hay hax), one_mul], have him : abs (y / x) * x.im = y.im, by rw ← of_real_div at h; simpa [-of_real_div] using congr_arg im h, have him' : abs (x / y) * y.im = x.im, by rw [← him, abs_div, abs_div, ← mul_assoc, div_mul_div, mul_comm (abs _), div_self (mul_ne_zero hay hax), one_mul], have hxya : x.im / abs x = y.im / abs y, by rw [← him, abs_div, mul_comm, ← mul_div_comm, mul_div_cancel_left _ hay], have hnxya : (-x).im / abs x = (-y).im / abs y, by rw [neg_im, neg_im, neg_div, neg_div, hxya], if hxr : 0 ≤ x.re then have hyr : 0 ≤ y.re, from hre ▸ mul_nonneg (abs_nonneg _) hxr, by simp [arg, *] at * else have hyr : ¬ 0 ≤ y.re, from λ hyr, hxr $ hre' ▸ mul_nonneg (abs_nonneg _) hyr, if hxi : 0 ≤ x.im then have hyi : 0 ≤ y.im, from him ▸ mul_nonneg (abs_nonneg _) hxi, by simp [arg, *] at * else have hyi : ¬ 0 ≤ y.im, from λ hyi, hxi $ him' ▸ mul_nonneg (abs_nonneg _) hyi, by simp [arg, *] at *⟩ lemma arg_real_mul (x : ℂ) {r : ℝ} (hr : 0 < r) : arg (r * x) = arg x := if hx : x = 0 then by simp [hx] else (arg_eq_arg_iff (mul_ne_zero (of_real_ne_zero.2 (ne_of_lt hr).symm) hx) hx).2 $ by rw [abs_mul, abs_of_nonneg (le_of_lt hr), ← mul_assoc, of_real_mul, mul_comm (r : ℂ), ← div_div_eq_div_mul, div_mul_cancel _ (of_real_ne_zero.2 (ne_of_lt hr).symm), div_self (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), one_mul] lemma ext_abs_arg {x y : ℂ} (h₁ : x.abs = y.abs) (h₂ : x.arg = y.arg) : x = y := if hy : y = 0 then by simp * at * else have hx : x ≠ 0, from λ hx, by simp [*, eq_comm] at *, by rwa [arg_eq_arg_iff hx hy, h₁, div_self (of_real_ne_zero.2 (mt abs_eq_zero.1 hy)), one_mul] at h₂ lemma arg_of_real_of_nonneg {x : ℝ} (hx : 0 ≤ x) : arg x = 0 := by simp [arg, hx] lemma arg_of_real_of_neg {x : ℝ} (hx : x < 0) : arg x = π := by rw [arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg, ← of_real_neg, arg_of_real_of_nonneg]; simp [*, le_iff_eq_or_lt, lt_neg] /-- Inverse of the `exp` function. Returns values such that `(log x).im > - π` and `(log x).im ≤ π`. `log 0 = 0`-/ noncomputable def log (x : ℂ) : ℂ := x.abs.log + arg x * I lemma log_re (x : ℂ) : x.log.re = x.abs.log := by simp [log] lemma log_im (x : ℂ) : x.log.im = x.arg := by simp [log] lemma exp_log {x : ℂ} (hx : x ≠ 0) : exp (log x) = x := by rw [log, exp_add_mul_I, ← of_real_sin, sin_arg, ← of_real_cos, cos_arg hx, ← of_real_exp, real.exp_log (abs_pos.2 hx), mul_add, of_real_div, of_real_div, mul_div_cancel' _ (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), ← mul_assoc, mul_div_cancel' _ (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), re_add_im] lemma exp_inj_of_neg_pi_lt_of_le_pi {x y : ℂ} (hx₁ : -π < x.im) (hx₂ : x.im ≤ π) (hy₁ : - π < y.im) (hy₂ : y.im ≤ π) (hxy : exp x = exp y) : x = y := by rw [exp_eq_exp_re_mul_sin_add_cos, exp_eq_exp_re_mul_sin_add_cos y] at hxy; exact complex.ext (real.exp_injective $ by simpa [abs_mul, abs_cos_add_sin_mul_I] using congr_arg complex.abs hxy) (by simpa [(of_real_exp _).symm, - of_real_exp, arg_real_mul _ (real.exp_pos _), arg_cos_add_sin_mul_I hx₁ hx₂, arg_cos_add_sin_mul_I hy₁ hy₂] using congr_arg arg hxy) lemma log_exp {x : ℂ} (hx₁ : -π < x.im) (hx₂: x.im ≤ π) : log (exp x) = x := exp_inj_of_neg_pi_lt_of_le_pi (by rw log_im; exact neg_pi_lt_arg _) (by rw log_im; exact arg_le_pi _) hx₁ hx₂ (by rw [exp_log (exp_ne_zero _)]) lemma of_real_log {x : ℝ} (hx : 0 ≤ x) : (x.log : ℂ) = log x := complex.ext (by rw [log_re, of_real_re, abs_of_nonneg hx]) (by rw [of_real_im, log_im, arg_of_real_of_nonneg hx]) @[simp] lemma log_zero : log 0 = 0 := by simp [log] @[simp] lemma log_one : log 1 = 0 := by simp [log] lemma log_neg_one : log (-1) = π * I := by simp [log] lemma log_I : log I = π / 2 * I := by simp [log] lemma log_neg_I : log (-I) = -(π / 2) * I := by simp [log] lemma exp_eq_one_iff {x : ℂ} : exp x = 1 ↔ ∃ n : ℤ, x = n * ((2 * π) * I) := have real.exp (x.re) * real.cos (x.im) = 1 → real.cos x.im ≠ -1, from λ h₁ h₂, begin rw [h₂, mul_neg_eq_neg_mul_symm, mul_one, neg_eq_iff_neg_eq] at h₁, have := real.exp_pos x.re, rw ← h₁ at this, exact absurd this (by norm_num) end, calc exp x = 1 ↔ (exp x).re = 1 ∧ (exp x).im = 0 : by simp [complex.ext_iff] ... ↔ real.cos x.im = 1 ∧ real.sin x.im = 0 ∧ x.re = 0 : begin rw exp_eq_exp_re_mul_sin_add_cos, simp [complex.ext_iff, cos_of_real_re, sin_of_real_re, exp_of_real_re, real.exp_ne_zero], split; finish [real.sin_eq_zero_iff_cos_eq] end ... ↔ (∃ n : ℤ, ↑n * (2 * π) = x.im) ∧ (∃ n : ℤ, ↑n * π = x.im) ∧ x.re = 0 : by rw [real.sin_eq_zero_iff, real.cos_eq_one_iff] ... ↔ ∃ n : ℤ, x = n * ((2 * π) * I) : ⟨λ ⟨⟨n, hn⟩, ⟨m, hm⟩, h⟩, ⟨n, by simp [complex.ext_iff, hn.symm, h]⟩, λ ⟨n, hn⟩, ⟨⟨n, by simp [hn]⟩, ⟨2 * n, by simp [hn, mul_comm, mul_assoc, mul_left_comm]⟩, by simp [hn]⟩⟩ lemma exp_eq_exp_iff_exp_sub_eq_one {x y : ℂ} : exp x = exp y ↔ exp (x - y) = 1 := by rw [exp_sub, div_eq_one_iff_eq _ (exp_ne_zero _)] lemma exp_eq_exp_iff_exists_int {x y : ℂ} : exp x = exp y ↔ ∃ n : ℤ, x = y + n * ((2 * π) * I) := by simp only [exp_eq_exp_iff_exp_sub_eq_one, exp_eq_one_iff, sub_eq_iff_eq_add'] @[simp] lemma cos_pi_div_two : cos (π / 2) = 0 := calc cos (π / 2) = real.cos (π / 2) : by rw [of_real_cos]; simp ... = 0 : by simp @[simp] lemma sin_pi_div_two : sin (π / 2) = 1 := calc sin (π / 2) = real.sin (π / 2) : by rw [of_real_sin]; simp ... = 1 : by simp @[simp] lemma sin_pi : sin π = 0 := by rw [← of_real_sin, real.sin_pi]; simp @[simp] lemma cos_pi : cos π = -1 := by rw [← of_real_cos, real.cos_pi]; simp @[simp] lemma sin_two_pi : sin (2 * π) = 0 := by simp [two_mul, sin_add] @[simp] lemma cos_two_pi : cos (2 * π) = 1 := by simp [two_mul, cos_add] lemma sin_add_pi (x : ℝ) : sin (x + π) = -sin x := by simp [sin_add] lemma sin_add_two_pi (x : ℝ) : sin (x + 2 * π) = sin x := by simp [sin_add_pi, sin_add, sin_two_pi, cos_two_pi] lemma cos_add_two_pi (x : ℝ) : cos (x + 2 * π) = cos x := by simp [cos_add, cos_two_pi, sin_two_pi] lemma sin_pi_sub (x : ℝ) : sin (π - x) = sin x := by simp [sin_add] lemma cos_add_pi (x : ℝ) : cos (x + π) = -cos x := by simp [cos_add] lemma cos_pi_sub (x : ℝ) : cos (π - x) = -cos x := by simp [cos_add] lemma sin_add_pi_div_two (x : ℝ) : sin (x + π / 2) = cos x := by simp [sin_add] lemma sin_sub_pi_div_two (x : ℝ) : sin (x - π / 2) = -cos x := by simp [sin_add] lemma sin_pi_div_two_sub (x : ℝ) : sin (π / 2 - x) = cos x := by simp [sin_add] lemma cos_add_pi_div_two (x : ℝ) : cos (x + π / 2) = -sin x := by simp [cos_add] lemma cos_sub_pi_div_two (x : ℝ) : cos (x - π / 2) = sin x := by simp [cos_add] lemma cos_pi_div_two_sub (x : ℝ) : cos (π / 2 - x) = sin x := by rw [← cos_neg, neg_sub, cos_sub_pi_div_two] lemma sin_nat_mul_pi (n : ℕ) : sin (n * π) = 0 := by induction n; simp [add_mul, sin_add, *] lemma sin_int_mul_pi (n : ℤ) : sin (n * π) = 0 := by cases n; simp [add_mul, sin_add, *, sin_nat_mul_pi] lemma cos_nat_mul_two_pi (n : ℕ) : cos (n * (2 * π)) = 1 := by induction n; simp [*, mul_add, cos_add, add_mul, cos_two_pi, sin_two_pi] lemma cos_int_mul_two_pi (n : ℤ) : cos (n * (2 * π)) = 1 := by cases n; simp only [cos_nat_mul_two_pi, int.of_nat_eq_coe, int.neg_succ_of_nat_coe, int.cast_coe_nat, int.cast_neg, (neg_mul_eq_neg_mul _ _).symm, cos_neg] lemma cos_int_mul_two_pi_add_pi (n : ℤ) : cos (n * (2 * π) + π) = -1 := by simp [cos_add, sin_add, cos_int_mul_two_pi] section pow noncomputable def cpow (x y : ℂ) : ℂ := if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) noncomputable instance : has_pow ℂ ℂ := ⟨cpow⟩ lemma cpow_def (x y : ℂ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) := rfl @[simp] lemma cpow_zero (x : ℂ) : x ^ (0 : ℂ) = 1 := by simp [cpow_def] @[simp] lemma zero_cpow {x : ℂ} (h : x ≠ 0) : (0 : ℂ) ^ x = 0 := by simp [cpow_def, *] @[simp] lemma cpow_one (x : ℂ) : x ^ (1 : ℂ) = x := if hx : x = 0 then by simp [hx, cpow_def] else by rw [cpow_def, if_neg (@one_ne_zero ℂ _), if_neg hx, mul_one, exp_log hx] @[simp] lemma one_cpow (x : ℂ) : (1 : ℂ) ^ x = 1 := by rw cpow_def; split_ifs; simp [one_ne_zero, *] at * lemma cpow_add {x : ℂ} (y z : ℂ) (hx : x ≠ 0) : x ^ (y + z) = x ^ y * x ^ z := by simp [cpow_def]; split_ifs; simp [*, exp_add, mul_add] at * lemma cpow_mul {x y : ℂ} (z : ℂ) (h₁ : -π < (log x * y).im) (h₂ : (log x * y).im ≤ π) : x ^ (y * z) = (x ^ y) ^ z := begin simp [cpow_def], split_ifs; simp [*, exp_ne_zero, log_exp h₁ h₂, mul_assoc] at * end lemma cpow_neg (x y : ℂ) : x ^ -y = (x ^ y)⁻¹ := by simp [cpow_def]; split_ifs; simp [exp_neg] @[simp] lemma cpow_nat_cast (x : ℂ) : ∀ (n : ℕ), x ^ (n : ℂ) = x ^ n | 0 := by simp | (n + 1) := if hx : x = 0 then by simp only [hx, pow_succ, complex.zero_cpow (nat.cast_ne_zero.2 (nat.succ_ne_zero _)), zero_mul] else by simp [cpow_def, hx, mul_add, exp_add, pow_succ, (cpow_nat_cast n).symm, exp_log hx] @[simp] lemma cpow_int_cast (x : ℂ) : ∀ (n : ℤ), x ^ (n : ℂ) = x ^ n | (n : ℕ) := by simp; refl | -[1+ n] := by rw fpow_neg_succ_of_nat; simp only [int.neg_succ_of_nat_coe, int.cast_neg, complex.cpow_neg, inv_eq_one_div, int.cast_coe_nat, cpow_nat_cast] lemma cpow_nat_inv_pow (x : ℂ) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℂ)) ^ n = x := have (log x * (↑n)⁻¹).im = (log x).im / n, by rw [div_eq_mul_inv, ← of_real_nat_cast, ← of_real_inv, mul_im, of_real_re, of_real_im]; simp, have h : -π < (log x * (↑n)⁻¹).im ∧ (log x * (↑n)⁻¹).im ≤ π, from (le_total (log x).im 0).elim (λ h, ⟨calc -π < (log x).im : by simp [log, neg_pi_lt_arg] ... ≤ ((log x).im * 1) / n : le_div_of_mul_le (nat.cast_pos.2 hn) (mul_le_mul_of_nonpos_left (by rw ← nat.cast_one; exact nat.cast_le.2 hn) h) ... = (log x * (↑n)⁻¹).im : by simp [this], this.symm ▸ le_trans (div_nonpos_of_nonpos_of_pos h (nat.cast_pos.2 hn)) (le_of_lt real.pi_pos)⟩) (λ h, ⟨this.symm ▸ lt_of_lt_of_le (neg_neg_of_pos real.pi_pos) (div_nonneg h (nat.cast_pos.2 hn)), calc (log x * (↑n)⁻¹).im = (1 * (log x).im) / n : by simp [this] ... ≤ (log x).im : (div_le_of_le_mul (nat.cast_pos.2 hn) (mul_le_mul_of_nonneg_right (by rw ← nat.cast_one; exact nat.cast_le.2 hn) h)) ... ≤ _ : by simp [log, arg_le_pi]⟩), by rw [← cpow_nat_cast, ← cpow_mul _ h.1 h.2, inv_mul_cancel (show (n : ℂ) ≠ 0, from nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 hn)), cpow_one] end pow end complex namespace real noncomputable def rpow (x y : ℝ) := ((x : ℂ) ^ (y : ℂ)).re noncomputable instance : has_pow ℝ ℝ := ⟨rpow⟩ lemma rpow_def (x y : ℝ) : x ^ y = ((x : ℂ) ^ (y : ℂ)).re := rfl lemma rpow_def_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) := by simp only [rpow_def, complex.cpow_def]; split_ifs; simp [*, (complex.of_real_log hx).symm, -complex.of_real_mul, (complex.of_real_mul _ _).symm, complex.exp_of_real_re] at * lemma rpow_def_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : x ^ y = exp (log x * y) := by rw [rpow_def_of_nonneg (le_of_lt hx), if_neg (ne_of_gt hx)] open_locale real lemma rpow_def_of_neg {x : ℝ} (hx : x < 0) (y : ℝ) : x ^ y = exp (log (-x) * y) * cos (y * π) := begin rw [rpow_def, complex.cpow_def, if_neg], have : complex.log x * y = ↑(log(-x) * y) + ↑(y * π) * complex.I, simp only [complex.log, abs_of_neg hx, complex.arg_of_real_of_neg hx, complex.abs_of_real, complex.of_real_mul], ring, { rw [this, complex.exp_add_mul_I, ← complex.of_real_exp, ← complex.of_real_cos, ← complex.of_real_sin, mul_add, ← complex.of_real_mul, ← mul_assoc, ← complex.of_real_mul, complex.add_re, complex.of_real_re, complex.mul_re, complex.I_re, complex.of_real_im], ring }, { rw complex.of_real_eq_zero, exact ne_of_lt hx } end lemma rpow_def_of_nonpos {x : ℝ} (hx : x ≤ 0) (y : ℝ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log (-x) * y) * cos (y * π) := by split_ifs; simp [rpow_def, *]; exact rpow_def_of_neg (lt_of_le_of_ne hx h) _ lemma rpow_pos_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : 0 < x ^ y := by rw rpow_def_of_pos hx; apply exp_pos lemma abs_rpow_le_abs_rpow (x y : ℝ) : abs (x ^ y) ≤ abs (x) ^ y := abs_le_of_le_of_neg_le begin cases lt_trichotomy 0 x, { rw abs_of_pos h }, cases h, { simp [h.symm] }, rw [rpow_def_of_neg h, rpow_def_of_pos (abs_pos_of_neg h), abs_of_neg h], calc exp (log (-x) * y) * cos (y * π) ≤ exp (log (-x) * y) * 1 : mul_le_mul_of_nonneg_left (cos_le_one _) (le_of_lt $ exp_pos _) ... = _ : mul_one _ end begin cases lt_trichotomy 0 x, { rw abs_of_pos h, have : 0 < x^y := rpow_pos_of_pos h _, linarith }, cases h, { simp only [h.symm, abs_zero, rpow_def_of_nonneg], split_ifs, repeat {norm_num}}, rw [rpow_def_of_neg h, rpow_def_of_pos (abs_pos_of_neg h), abs_of_neg h], calc -(exp (log (-x) * y) * cos (y * π)) = exp (log (-x) * y) * (-cos (y * π)) : by ring ... ≤ exp (log (-x) * y) * 1 : mul_le_mul_of_nonneg_left (neg_le.2 $ neg_one_le_cos _) (le_of_lt $ exp_pos _) ... = exp (log (-x) * y) : mul_one _ end end real namespace complex lemma of_real_cpow {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : ((x ^ y : ℝ) : ℂ) = (x : ℂ) ^ (y : ℂ) := by simp [real.rpow_def_of_nonneg hx, complex.cpow_def]; split_ifs; simp [complex.of_real_log hx] @[simp] lemma abs_cpow_real (x : ℂ) (y : ℝ) : abs (x ^ (y : ℂ)) = x.abs ^ y := begin rw [real.rpow_def_of_nonneg (abs_nonneg _), complex.cpow_def], split_ifs; simp [*, abs_of_nonneg (le_of_lt (real.exp_pos _)), complex.log, complex.exp_add, add_mul, mul_right_comm _ I, exp_mul_I, abs_cos_add_sin_mul_I, (complex.of_real_mul _ _).symm, -complex.of_real_mul] at * end @[simp] lemma abs_cpow_inv_nat (x : ℂ) (n : ℕ) : abs (x ^ (n⁻¹ : ℂ)) = x.abs ^ (n⁻¹ : ℝ) := by rw ← abs_cpow_real; simp [-abs_cpow_real] end complex namespace real open_locale real variables {x y z : ℝ} @[simp] lemma rpow_zero (x : ℝ) : x ^ (0 : ℝ) = 1 := by simp [rpow_def] @[simp] lemma zero_rpow {x : ℝ} (h : x ≠ 0) : (0 : ℝ) ^ x = 0 := by simp [rpow_def, *] @[simp] lemma rpow_one (x : ℝ) : x ^ (1 : ℝ) = x := by simp [rpow_def] @[simp] lemma one_rpow (x : ℝ) : (1 : ℝ) ^ x = 1 := by simp [rpow_def] lemma rpow_nonneg_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : 0 ≤ x ^ y := by rw [rpow_def_of_nonneg hx]; split_ifs; simp only [zero_le_one, le_refl, le_of_lt (exp_pos _)] lemma rpow_add {x : ℝ} (y z : ℝ) (hx : 0 < x) : x ^ (y + z) = x ^ y * x ^ z := by simp only [rpow_def_of_pos hx, mul_add, exp_add] lemma rpow_mul {x : ℝ} (hx : 0 ≤ x) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := by rw [← complex.of_real_inj, complex.of_real_cpow (rpow_nonneg_of_nonneg hx _), complex.of_real_cpow hx, complex.of_real_mul, complex.cpow_mul, complex.of_real_cpow hx]; simp only [(complex.of_real_mul _ _).symm, (complex.of_real_log hx).symm, complex.of_real_im, neg_lt_zero, pi_pos, le_of_lt pi_pos] lemma rpow_neg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ := by simp only [rpow_def_of_nonneg hx]; split_ifs; simp [*, exp_neg] at * @[simp] lemma rpow_nat_cast (x : ℝ) (n : ℕ) : x ^ (n : ℝ) = x ^ n := by simp only [rpow_def, (complex.of_real_pow _ _).symm, complex.cpow_nat_cast, complex.of_real_nat_cast, complex.of_real_re] @[simp] lemma rpow_int_cast (x : ℝ) (n : ℤ) : x ^ (n : ℝ) = x ^ n := by simp only [rpow_def, (complex.of_real_fpow _ _).symm, complex.cpow_int_cast, complex.of_real_int_cast, complex.of_real_re] lemma mul_rpow {x y z : ℝ} (h : 0 ≤ x) (h₁ : 0 ≤ y) : (x*y)^z = x^z * y^z := begin iterate 3 { rw real.rpow_def_of_nonneg }, split_ifs; simp * at *, { have hx : 0 < x, cases lt_or_eq_of_le h with h₂ h₂, exact h₂, exfalso, apply h_2, exact eq.symm h₂, have hy : 0 < y, cases lt_or_eq_of_le h₁ with h₂ h₂, exact h₂, exfalso, apply h_3, exact eq.symm h₂, rw [log_mul hx hy, add_mul, exp_add]}, { exact h₁}, { exact h}, { exact mul_nonneg h h₁}, end lemma one_le_rpow {x z : ℝ} (h : 1 ≤ x) (h₁ : 0 ≤ z) : 1 ≤ x^z := begin rw real.rpow_def_of_nonneg, split_ifs with h₂ h₃, { refl}, { simp [*, not_le_of_gt zero_lt_one] at *}, { have hx : 0 < x, exact lt_of_lt_of_le zero_lt_one h, rw [←log_le_log zero_lt_one hx, log_one] at h, have pos : 0 ≤ log x * z, exact mul_nonneg h h₁, rwa [←exp_le_exp, exp_zero] at pos}, { exact le_trans zero_le_one h}, end lemma rpow_le_rpow {x y z: ℝ} (h : 0 ≤ x) (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z := begin rw le_iff_eq_or_lt at h h₂, cases h₂, { rw [←h₂, rpow_zero, rpow_zero]}, { cases h, { rw [←h, zero_rpow], rw real.rpow_def_of_nonneg, split_ifs, { exact zero_le_one}, { refl}, { exact le_of_lt (exp_pos (log y * z))}, { rwa ←h at h₁}, { exact ne.symm (ne_of_lt h₂)}}, { have one_le : 1 ≤ y / x, rw one_le_div_iff_le h, exact h₁, have one_le_pow : 1 ≤ (y / x)^z, exact one_le_rpow one_le (le_of_lt h₂), rw [←mul_div_cancel y (ne.symm (ne_of_lt h)), mul_comm, mul_div_assoc], rw [mul_rpow (le_of_lt h) (le_trans zero_le_one one_le), mul_comm], exact (le_mul_of_ge_one_left (rpow_nonneg_of_nonneg (le_of_lt h) z) one_le_pow) } } end lemma rpow_lt_rpow (hx : 0 ≤ x) (hxy : x < y) (hz : 0 < z) : x^z < y^z := begin rw le_iff_eq_or_lt at hx, cases hx, { rw [← hx, zero_rpow (ne_of_gt hz)], exact rpow_pos_of_pos (by rwa ← hx at hxy) _ }, rw [rpow_def_of_pos hx, rpow_def_of_pos (lt_trans hx hxy), exp_lt_exp], exact mul_lt_mul_of_pos_right (log_lt_log hx hxy) hz end lemma rpow_lt_rpow_of_exponent_lt (hx : 1 < x) (hyz : y < z) : x^y < x^z := begin repeat {rw [rpow_def_of_pos (lt_trans zero_lt_one hx)]}, rw exp_lt_exp, exact mul_lt_mul_of_pos_left hyz (log_pos hx), end lemma rpow_le_rpow_of_exponent_le (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z := begin repeat {rw [rpow_def_of_pos (lt_of_lt_of_le zero_lt_one hx)]}, rw exp_le_exp, exact mul_le_mul_of_nonneg_left hyz (log_nonneg hx), end lemma rpow_lt_rpow_of_exponent_gt (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) : x^y < x^z := begin repeat {rw [rpow_def_of_pos hx0]}, rw exp_lt_exp, exact mul_lt_mul_of_neg_left hyz (log_neg hx0 hx1), end lemma rpow_le_rpow_of_exponent_ge (hx0 : 0 < x) (hx1 : x ≤ 1) (hyz : z ≤ y) : x^y ≤ x^z := begin repeat {rw [rpow_def_of_pos hx0]}, rw exp_le_exp, exact mul_le_mul_of_nonpos_left hyz (log_nonpos hx1), end lemma rpow_le_one {x e : ℝ} (he : 0 ≤ e) (hx : 0 ≤ x) (hx2 : x ≤ 1) : x^e ≤ 1 := by rw ←one_rpow e; apply rpow_le_rpow; assumption lemma one_lt_rpow (hx : 1 < x) (hz : 0 < z) : 1 < x^z := by { rw ← one_rpow z, exact rpow_lt_rpow zero_le_one hx hz } lemma rpow_lt_one (hx : 0 < x) (hx1 : x < 1) (hz : 0 < z) : x^z < 1 := by { rw ← one_rpow z, exact rpow_lt_rpow (le_of_lt hx) hx1 hz } lemma pow_nat_rpow_nat_inv {x : ℝ} (hx : 0 ≤ x) {n : ℕ} (hn : 0 < n) : (x ^ n) ^ (n⁻¹ : ℝ) = x := have hn0 : (n : ℝ) ≠ 0, by simpa [nat.pos_iff_ne_zero'] using hn, by rw [← rpow_nat_cast, ← rpow_mul hx, mul_inv_cancel hn0, rpow_one] section prove_rpow_is_continuous lemma continuous_rpow_aux1 : continuous (λp : {p:ℝ×ℝ // 0 < p.1}, p.val.1 ^ p.val.2) := suffices h : continuous (λ p : {p:ℝ×ℝ // 0 < p.1 }, exp (log p.val.1 * p.val.2)), by { convert h, ext p, rw rpow_def_of_pos p.2 }, continuous_exp.comp $ continuous_mul (show continuous ((λp:{p:ℝ//0 < p}, log (p.val)) ∘ (λp:{p:ℝ×ℝ//0<p.fst}, ⟨p.val.1, p.2⟩)), from continuous_log'.comp $ continuous_subtype_mk _ $ continuous_fst.comp continuous_subtype_val) (continuous_snd.comp $ continuous_subtype_val.comp continuous_id) lemma continuous_rpow_aux2 : continuous (λ p : {p:ℝ×ℝ // p.1 < 0}, p.val.1 ^ p.val.2) := suffices h : continuous (λp:{p:ℝ×ℝ // p.1 < 0}, exp (log (-p.val.1) * p.val.2) * cos (p.val.2 * π)), by { convert h, ext p, rw [rpow_def_of_neg p.2] }, continuous_mul (continuous_exp.comp $ continuous_mul (show continuous $ (λp:{p:ℝ//0<p}, log (p.val))∘(λp:{p:ℝ×ℝ//p.1<0}, ⟨-p.val.1, neg_pos_of_neg p.2⟩), from continuous_log'.comp $ continuous_subtype_mk _ $ continuous_neg'.comp $ continuous_fst.comp continuous_subtype_val) (continuous_snd.comp $ continuous_subtype_val.comp continuous_id)) (continuous_cos.comp $ continuous_mul (continuous_snd.comp $ continuous_subtype_val.comp continuous_id) continuous_const) lemma continuous_at_rpow_of_ne_zero (hx : x ≠ 0) (y : ℝ) : continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) := begin cases lt_trichotomy 0 x, exact continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux1 _ h) (mem_nhds_sets (by { convert is_open_prod (is_open_lt' (0:ℝ)) is_open_univ, ext, finish }) h), cases h, { exact absurd h.symm hx }, exact continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux2 _ h) (mem_nhds_sets (by { convert is_open_prod (is_open_gt' (0:ℝ)) is_open_univ, ext, finish }) h) end lemma continuous_rpow_aux3 : continuous (λ p : {p:ℝ×ℝ // 0 < p.2}, p.val.1 ^ p.val.2) := continuous_iff_continuous_at.2 $ λ ⟨(x₀, y₀), hy₀⟩, begin by_cases hx₀ : x₀ = 0, { simp only [continuous_at, hx₀, zero_rpow (ne_of_gt hy₀), tendsto_nhds_nhds], assume ε ε0, rcases exists_pos_rat_lt (half_pos hy₀) with ⟨q, q_pos, q_lt⟩, let q := (q:ℝ), replace q_pos : 0 < q := rat.cast_pos.2 q_pos, let δ := min (min q (ε ^ (1 / q))) (1/2), have δ0 : 0 < δ := lt_min (lt_min q_pos (rpow_pos_of_pos ε0 _)) (by norm_num), have : δ ≤ q := le_trans (min_le_left _ _) (min_le_left _ _), have : δ ≤ ε ^ (1 / q) := le_trans (min_le_left _ _) (min_le_right _ _), have : δ < 1 := lt_of_le_of_lt (min_le_right _ _) (by norm_num), use δ, use δ0, rintros ⟨⟨x, y⟩, hy⟩, simp only [subtype.dist_eq, real.dist_eq, prod.dist_eq, sub_zero], assume h, rw max_lt_iff at h, cases h with xδ yy₀, have qy : q < y, calc q < y₀ / 2 : q_lt ... = y₀ - y₀ / 2 : (sub_half _).symm ... ≤ y₀ - δ : by linarith ... < y : sub_lt_of_abs_sub_lt_left yy₀, calc abs(x^y) ≤ abs(x)^y : abs_rpow_le_abs_rpow _ _ ... < δ ^ y : rpow_lt_rpow (abs_nonneg _) xδ hy ... < δ ^ q : by { refine rpow_lt_rpow_of_exponent_gt _ _ _, repeat {linarith} } ... ≤ (ε ^ (1 / q)) ^ q : by { refine rpow_le_rpow _ _ _, repeat {linarith} } ... = ε : by { rw [← rpow_mul, div_mul_cancel, rpow_one], exact ne_of_gt q_pos, linarith }}, { exact (continuous_within_at_iff_continuous_at_restrict (λp:ℝ×ℝ, p.1^p.2) _).1 (continuous_at_rpow_of_ne_zero hx₀ _).continuous_within_at } end lemma continuous_at_rpow_of_pos (hy : 0 < y) (x : ℝ) : continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) := continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux3 _ hy) (mem_nhds_sets (by { convert is_open_prod is_open_univ (is_open_lt' (0:ℝ)), ext, finish }) hy) variables {α : Type*} [topological_space α] {f g : α → ℝ} /-- `real.rpow` is continuous at all points except for the lower half of the y-axis. In other words, the function `λp:ℝ×ℝ, p.1^p.2` is continuous at `(x, y)` if `x ≠ 0` or `y > 0`. Multiple forms of the claim is provided in the current section. -/ lemma continuous_rpow (h : ∀a, f a ≠ 0 ∨ 0 < g a) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_iff_continuous_at.2 $ λ a, begin show continuous_at ((λp:ℝ×ℝ, p.1^p.2) ∘ (λa, (f a, g a))) a, refine continuous_at.comp _ (continuous_iff_continuous_at.1 (hf.prod_mk hg) _), { replace h := h a, cases h, { exact continuous_at_rpow_of_ne_zero h _ }, { exact continuous_at_rpow_of_pos h _ }}, end lemma continuous_rpow_of_ne_zero (h : ∀a, f a ≠ 0) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_rpow (λa, or.inl $ h a) hf hg lemma continuous_rpow_of_pos (h : ∀a, 0 < g a) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_rpow (λa, or.inr $ h a) hf hg end prove_rpow_is_continuous section sqrt lemma sqrt_eq_rpow : sqrt = λx:ℝ, x ^ (1/(2:ℝ)) := begin funext, by_cases h : 0 ≤ x, { rw [← mul_self_inj_of_nonneg, mul_self_sqrt h, ← pow_two, ← rpow_nat_cast, ← rpow_mul h], norm_num, exact sqrt_nonneg _, exact rpow_nonneg_of_nonneg h _ }, { replace h : x < 0 := lt_of_not_ge h, have : 1 / (2:ℝ) * π = π / (2:ℝ), ring, rw [sqrt_eq_zero_of_nonpos (le_of_lt h), rpow_def_of_neg h, this, cos_pi_div_two, mul_zero] } end lemma continuous_sqrt : continuous sqrt := by rw sqrt_eq_rpow; exact continuous_rpow_of_pos (λa, by norm_num) continuous_id continuous_const end sqrt end real
035706df543a674d03d0cbaa75455ad563c8dae2
bb31430994044506fa42fd667e2d556327e18dfe
/src/analysis/inner_product_space/basic.lean
fdac512a030767c4f555ddf904b398122f4460c6
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
109,962
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Sébastien Gouëzel, Frédéric Dupuis -/ import algebra.direct_sum.module import analysis.complex.basic import analysis.convex.uniform import analysis.normed_space.completion import analysis.normed_space.bounded_linear_maps /-! # Inner product space This file defines inner product spaces and proves the basic properties. We do not formally define Hilbert spaces, but they can be obtained using the pair of assumptions `[inner_product_space 𝕜 E] [complete_space E]`. An inner product space is a vector space endowed with an inner product. It generalizes the notion of dot product in `ℝ^n` and provides the means of defining the length of a vector and the angle between two vectors. In particular vectors `x` and `y` are orthogonal if their inner product equals zero. We define both the real and complex cases at the same time using the `is_R_or_C` typeclass. This file proves general results on inner product spaces. For the specific construction of an inner product structure on `n → 𝕜` for `𝕜 = ℝ` or `ℂ`, see `euclidean_space` in `analysis.inner_product_space.pi_L2`. ## Main results - We define the class `inner_product_space 𝕜 E` extending `normed_space 𝕜 E` with a number of basic properties, most notably the Cauchy-Schwarz inequality. Here `𝕜` is understood to be either `ℝ` or `ℂ`, through the `is_R_or_C` typeclass. - We show that the inner product is continuous, `continuous_inner`, and bundle it as the the continuous sesquilinear map `innerSL` (see also `innerₛₗ` for the non-continuous version). - We define `orthonormal`, a predicate on a function `v : ι → E`, and prove the existence of a maximal orthonormal set, `exists_maximal_orthonormal`. Bessel's inequality, `orthonormal.tsum_inner_products_le`, states that given an orthonormal set `v` and a vector `x`, the sum of the norm-squares of the inner products `⟪v i, x⟫` is no more than the norm-square of `x`. For the existence of orthonormal bases, Hilbert bases, etc., see the file `analysis.inner_product_space.projection`. - The `orthogonal_complement` of a submodule `K` is defined, and basic API established. Some of the more subtle results about the orthogonal complement are delayed to `analysis.inner_product_space.projection`. ## Notation We globally denote the real and complex inner products by `⟪·, ·⟫_ℝ` and `⟪·, ·⟫_ℂ` respectively. We also provide two notation namespaces: `real_inner_product_space`, `complex_inner_product_space`, which respectively introduce the plain notation `⟪·, ·⟫` for the real and complex inner product. The orthogonal complement of a submodule `K` is denoted by `Kᗮ`. ## Implementation notes We choose the convention that inner products are conjugate linear in the first argument and linear in the second. ## Tags inner product space, Hilbert space, norm ## References * [Clément & Martin, *The Lax-Milgram Theorem. A detailed proof to be formalized in Coq*] * [Clément & Martin, *A Coq formal proof of the Lax–Milgram theorem*] The Coq code is available at the following address: <http://www.lri.fr/~sboldo/elfic/index.html> -/ noncomputable theory open is_R_or_C real filter open_locale big_operators topological_space complex_conjugate variables {𝕜 E F : Type*} [is_R_or_C 𝕜] /-- Syntactic typeclass for types endowed with an inner product -/ class has_inner (𝕜 E : Type*) := (inner : E → E → 𝕜) export has_inner (inner) notation `⟪`x`, `y`⟫_ℝ` := @inner ℝ _ _ x y notation `⟪`x`, `y`⟫_ℂ` := @inner ℂ _ _ x y section notations localized "notation (name := inner.real) `⟪`x`, `y`⟫` := @inner ℝ _ _ x y" in real_inner_product_space localized "notation (name := inner.complex) `⟪`x`, `y`⟫` := @inner ℂ _ _ x y" in complex_inner_product_space end notations /-- An inner product space is a vector space with an additional operation called inner product. The norm could be derived from the inner product, instead we require the existence of a norm and the fact that `‖x‖^2 = re ⟪x, x⟫` to be able to put instances on `𝕂` or product spaces. To construct a norm from an inner product, see `inner_product_space.of_core`. -/ class inner_product_space (𝕜 : Type*) (E : Type*) [is_R_or_C 𝕜] extends normed_add_comm_group E, normed_space 𝕜 E, has_inner 𝕜 E := (norm_sq_eq_inner : ∀ (x : E), ‖x‖^2 = re (inner x x)) (conj_sym : ∀ x y, conj (inner y x) = inner x y) (add_left : ∀ x y z, inner (x + y) z = inner x z + inner y z) (smul_left : ∀ x y r, inner (r • x) y = (conj r) * inner x y) attribute [nolint dangerous_instance] inner_product_space.to_normed_add_comm_group -- note [is_R_or_C instance] /-! ### Constructing a normed space structure from an inner product In the definition of an inner product space, we require the existence of a norm, which is equal (but maybe not defeq) to the square root of the scalar product. This makes it possible to put an inner product space structure on spaces with a preexisting norm (for instance `ℝ`), with good properties. However, sometimes, one would like to define the norm starting only from a well-behaved scalar product. This is what we implement in this paragraph, starting from a structure `inner_product_space.core` stating that we have a nice scalar product. Our goal here is not to develop a whole theory with all the supporting API, as this will be done below for `inner_product_space`. Instead, we implement the bare minimum to go as directly as possible to the construction of the norm and the proof of the triangular inequality. Warning: Do not use this `core` structure if the space you are interested in already has a norm instance defined on it, otherwise this will create a second non-defeq norm instance! -/ /-- A structure requiring that a scalar product is positive definite and symmetric, from which one can construct an `inner_product_space` instance in `inner_product_space.of_core`. -/ @[nolint has_nonempty_instance] structure inner_product_space.core (𝕜 : Type*) (F : Type*) [is_R_or_C 𝕜] [add_comm_group F] [module 𝕜 F] := (inner : F → F → 𝕜) (conj_sym : ∀ x y, conj (inner y x) = inner x y) (nonneg_re : ∀ x, 0 ≤ re (inner x x)) (definite : ∀ x, inner x x = 0 → x = 0) (add_left : ∀ x y z, inner (x + y) z = inner x z + inner y z) (smul_left : ∀ x y r, inner (r • x) y = (conj r) * inner x y) /- We set `inner_product_space.core` to be a class as we will use it as such in the construction of the normed space structure that it produces. However, all the instances we will use will be local to this proof. -/ attribute [class] inner_product_space.core namespace inner_product_space.of_core variables [add_comm_group F] [module 𝕜 F] [c : inner_product_space.core 𝕜 F] include c local notation `⟪`x`, `y`⟫` := @inner 𝕜 F _ x y local notation `norm_sqK` := @is_R_or_C.norm_sq 𝕜 _ local notation `reK` := @is_R_or_C.re 𝕜 _ local notation `absK` := @is_R_or_C.abs 𝕜 _ local notation `ext_iff` := @is_R_or_C.ext_iff 𝕜 _ local postfix `†`:90 := star_ring_end _ /-- Inner product defined by the `inner_product_space.core` structure. -/ def to_has_inner : has_inner 𝕜 F := { inner := c.inner } local attribute [instance] to_has_inner /-- The norm squared function for `inner_product_space.core` structure. -/ def norm_sq (x : F) := reK ⟪x, x⟫ local notation `norm_sqF` := @norm_sq 𝕜 F _ _ _ _ lemma inner_conj_sym (x y : F) : ⟪y, x⟫† = ⟪x, y⟫ := c.conj_sym x y lemma inner_self_nonneg {x : F} : 0 ≤ re ⟪x, x⟫ := c.nonneg_re _ lemma inner_self_nonneg_im {x : F} : im ⟪x, x⟫ = 0 := by rw [← @of_real_inj 𝕜, im_eq_conj_sub]; simp [inner_conj_sym] lemma inner_self_im_zero {x : F} : im ⟪x, x⟫ = 0 := inner_self_nonneg_im lemma inner_add_left {x y z : F} : ⟪x + y, z⟫ = ⟪x, z⟫ + ⟪y, z⟫ := c.add_left _ _ _ lemma inner_add_right {x y z : F} : ⟪x, y + z⟫ = ⟪x, y⟫ + ⟪x, z⟫ := by rw [←inner_conj_sym, inner_add_left, ring_hom.map_add]; simp only [inner_conj_sym] lemma inner_norm_sq_eq_inner_self (x : F) : (norm_sqF x : 𝕜) = ⟪x, x⟫ := begin rw ext_iff, exact ⟨by simp only [of_real_re]; refl, by simp only [inner_self_nonneg_im, of_real_im]⟩ end lemma inner_re_symm {x y : F} : re ⟪x, y⟫ = re ⟪y, x⟫ := by rw [←inner_conj_sym, conj_re] lemma inner_im_symm {x y : F} : im ⟪x, y⟫ = -im ⟪y, x⟫ := by rw [←inner_conj_sym, conj_im] lemma inner_smul_left {x y : F} {r : 𝕜} : ⟪r • x, y⟫ = r† * ⟪x, y⟫ := c.smul_left _ _ _ lemma inner_smul_right {x y : F} {r : 𝕜} : ⟪x, r • y⟫ = r * ⟪x, y⟫ := by rw [←inner_conj_sym, inner_smul_left]; simp only [conj_conj, inner_conj_sym, ring_hom.map_mul] lemma inner_zero_left {x : F} : ⟪0, x⟫ = 0 := by rw [←zero_smul 𝕜 (0 : F), inner_smul_left]; simp only [zero_mul, ring_hom.map_zero] lemma inner_zero_right {x : F} : ⟪x, 0⟫ = 0 := by rw [←inner_conj_sym, inner_zero_left]; simp only [ring_hom.map_zero] lemma inner_self_eq_zero {x : F} : ⟪x, x⟫ = 0 ↔ x = 0 := iff.intro (c.definite _) (by { rintro rfl, exact inner_zero_left }) lemma inner_self_re_to_K {x : F} : (re ⟪x, x⟫ : 𝕜) = ⟪x, x⟫ := by norm_num [ext_iff, inner_self_nonneg_im] lemma inner_abs_conj_sym {x y : F} : abs ⟪x, y⟫ = abs ⟪y, x⟫ := by rw [←inner_conj_sym, abs_conj] lemma inner_neg_left {x y : F} : ⟪-x, y⟫ = -⟪x, y⟫ := by { rw [← neg_one_smul 𝕜 x, inner_smul_left], simp } lemma inner_neg_right {x y : F} : ⟪x, -y⟫ = -⟪x, y⟫ := by rw [←inner_conj_sym, inner_neg_left]; simp only [ring_hom.map_neg, inner_conj_sym] lemma inner_sub_left {x y z : F} : ⟪x - y, z⟫ = ⟪x, z⟫ - ⟪y, z⟫ := by { simp [sub_eq_add_neg, inner_add_left, inner_neg_left] } lemma inner_sub_right {x y z : F} : ⟪x, y - z⟫ = ⟪x, y⟫ - ⟪x, z⟫ := by { simp [sub_eq_add_neg, inner_add_right, inner_neg_right] } lemma inner_mul_conj_re_abs {x y : F} : re (⟪x, y⟫ * ⟪y, x⟫) = abs (⟪x, y⟫ * ⟪y, x⟫) := by { rw [←inner_conj_sym, mul_comm], exact re_eq_abs_of_mul_conj (inner y x), } /-- Expand `inner (x + y) (x + y)` -/ lemma inner_add_add_self {x y : F} : ⟪x + y, x + y⟫ = ⟪x, x⟫ + ⟪x, y⟫ + ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_add_left, inner_add_right]; ring /- Expand `inner (x - y) (x - y)` -/ lemma inner_sub_sub_self {x y : F} : ⟪x - y, x - y⟫ = ⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_sub_left, inner_sub_right]; ring /-- **Cauchy–Schwarz inequality**. This proof follows "Proof 2" on Wikipedia. We need this for the `core` structure to prove the triangle inequality below when showing the core is a normed group. -/ lemma inner_mul_inner_self_le (x y : F) : abs ⟪x, y⟫ * abs ⟪y, x⟫ ≤ re ⟪x, x⟫ * re ⟪y, y⟫ := begin by_cases hy : y = 0, { rw [hy], simp only [is_R_or_C.abs_zero, inner_zero_left, mul_zero, add_monoid_hom.map_zero] }, { change y ≠ 0 at hy, have hy' : ⟪y, y⟫ ≠ 0 := λ h, by rw [inner_self_eq_zero] at h; exact hy h, set T := ⟪y, x⟫ / ⟪y, y⟫ with hT, have h₁ : re ⟪y, x⟫ = re ⟪x, y⟫ := inner_re_symm, have h₂ : im ⟪y, x⟫ = -im ⟪x, y⟫ := inner_im_symm, have h₃ : ⟪y, x⟫ * ⟪x, y⟫ * ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = ⟪y, x⟫ * ⟪x, y⟫ / ⟪y, y⟫, { rw [mul_div_assoc], have : ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = 1 / ⟪y, y⟫ := by rw [div_mul_eq_div_mul_one_div, div_self hy', one_mul], rw [this, div_eq_mul_inv, one_mul, ←div_eq_mul_inv] }, have h₄ : ⟪y, y⟫ = re ⟪y, y⟫ := by simp only [inner_self_re_to_K], have h₅ : re ⟪y, y⟫ > 0, { refine lt_of_le_of_ne inner_self_nonneg _, intro H, apply hy', rw ext_iff, exact ⟨by simp only [H, zero_re'], by simp only [inner_self_nonneg_im, add_monoid_hom.map_zero]⟩ }, have h₆ : re ⟪y, y⟫ ≠ 0 := ne_of_gt h₅, have hmain := calc 0 ≤ re ⟪x - T • y, x - T • y⟫ : inner_self_nonneg ... = re ⟪x, x⟫ - re ⟪T • y, x⟫ - re ⟪x, T • y⟫ + re ⟪T • y, T • y⟫ : by simp only [inner_sub_sub_self, inner_smul_left, inner_smul_right, h₁, h₂, neg_mul, add_monoid_hom.map_add, mul_re, conj_im, add_monoid_hom.map_sub, mul_neg, conj_re, neg_neg] ... = re ⟪x, x⟫ - re (T† * ⟪y, x⟫) - re (T * ⟪x, y⟫) + re (T * T† * ⟪y, y⟫) : by simp only [inner_smul_left, inner_smul_right, mul_assoc] ... = re ⟪x, x⟫ - re (⟪x, y⟫ / ⟪y, y⟫ * ⟪y, x⟫) : by field_simp [-mul_re, inner_conj_sym, hT, map_div₀, h₁, h₃] ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / ⟪y, y⟫) : by rw ←mul_div_right_comm ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / re ⟪y, y⟫) : by conv_lhs { rw [h₄] } ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [div_re_of_real] ... = re ⟪x, x⟫ - abs (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [inner_mul_conj_re_abs] ... = re ⟪x, x⟫ - abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ : by rw is_R_or_C.abs_mul, have hmain' : abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ ≤ re ⟪x, x⟫ := by linarith, have := (mul_le_mul_right h₅).mpr hmain', rwa [div_mul_cancel (abs ⟪x, y⟫ * abs ⟪y, x⟫) h₆] at this } end /-- Norm constructed from a `inner_product_space.core` structure, defined to be the square root of the scalar product. -/ def to_has_norm : has_norm F := { norm := λ x, sqrt (re ⟪x, x⟫) } local attribute [instance] to_has_norm lemma norm_eq_sqrt_inner (x : F) : ‖x‖ = sqrt (re ⟪x, x⟫) := rfl lemma inner_self_eq_norm_mul_norm (x : F) : re ⟪x, x⟫ = ‖x‖ * ‖x‖ := by rw [norm_eq_sqrt_inner, ←sqrt_mul inner_self_nonneg (re ⟪x, x⟫), sqrt_mul_self inner_self_nonneg] lemma sqrt_norm_sq_eq_norm {x : F} : sqrt (norm_sqF x) = ‖x‖ := rfl /-- Cauchy–Schwarz inequality with norm -/ lemma abs_inner_le_norm (x y : F) : abs ⟪x, y⟫ ≤ ‖x‖ * ‖y‖ := nonneg_le_nonneg_of_sq_le_sq (mul_nonneg (sqrt_nonneg _) (sqrt_nonneg _)) begin have H : ‖x‖ * ‖y‖ * (‖x‖ * ‖y‖) = re ⟪y, y⟫ * re ⟪x, x⟫, { simp only [inner_self_eq_norm_mul_norm], ring, }, rw H, conv begin to_lhs, congr, rw [inner_abs_conj_sym], end, exact inner_mul_inner_self_le y x, end /-- Normed group structure constructed from an `inner_product_space.core` structure -/ def to_normed_add_comm_group : normed_add_comm_group F := add_group_norm.to_normed_add_comm_group { to_fun := λ x, sqrt (re ⟪x, x⟫), map_zero' := by simp only [sqrt_zero, inner_zero_right, map_zero], neg' := λ x, by simp only [inner_neg_left, neg_neg, inner_neg_right], add_le' := λ x y, begin have h₁ : abs ⟪x, y⟫ ≤ ‖x‖ * ‖y‖ := abs_inner_le_norm _ _, have h₂ : re ⟪x, y⟫ ≤ abs ⟪x, y⟫ := re_le_abs _, have h₃ : re ⟪x, y⟫ ≤ ‖x‖ * ‖y‖ := by linarith, have h₄ : re ⟪y, x⟫ ≤ ‖x‖ * ‖y‖ := by rwa [←inner_conj_sym, conj_re], have : ‖x + y‖ * ‖x + y‖ ≤ (‖x‖ + ‖y‖) * (‖x‖ + ‖y‖), { simp only [←inner_self_eq_norm_mul_norm, inner_add_add_self, mul_add, mul_comm, map_add], linarith }, exact nonneg_le_nonneg_of_sq_le_sq (add_nonneg (sqrt_nonneg _) (sqrt_nonneg _)) this, end, eq_zero_of_map_eq_zero' := λ x hx, (inner_self_eq_zero : ⟪x, x⟫ = 0 ↔ x = 0).1 $ begin change sqrt (re ⟪x, x⟫) = 0 at hx, rw [sqrt_eq_zero inner_self_nonneg] at hx, exact ext (by simp [hx]) (by simp [inner_self_im_zero]), end } local attribute [instance] to_normed_add_comm_group /-- Normed space structure constructed from a `inner_product_space.core` structure -/ def to_normed_space : normed_space 𝕜 F := { norm_smul_le := assume r x, begin rw [norm_eq_sqrt_inner, inner_smul_left, inner_smul_right, ←mul_assoc], rw [conj_mul_eq_norm_sq_left, of_real_mul_re, sqrt_mul, ←inner_norm_sq_eq_inner_self, of_real_re], { simp [sqrt_norm_sq_eq_norm, is_R_or_C.sqrt_norm_sq_eq_norm] }, { exact norm_sq_nonneg r } end } end inner_product_space.of_core /-- Given a `inner_product_space.core` structure on a space, one can use it to turn the space into an inner product space, constructing the norm out of the inner product -/ def inner_product_space.of_core [add_comm_group F] [module 𝕜 F] (c : inner_product_space.core 𝕜 F) : inner_product_space 𝕜 F := begin letI : normed_add_comm_group F := @inner_product_space.of_core.to_normed_add_comm_group 𝕜 F _ _ _ c, letI : normed_space 𝕜 F := @inner_product_space.of_core.to_normed_space 𝕜 F _ _ _ c, exact { norm_sq_eq_inner := λ x, begin have h₁ : ‖x‖^2 = (sqrt (re (c.inner x x))) ^ 2 := rfl, have h₂ : 0 ≤ re (c.inner x x) := inner_product_space.of_core.inner_self_nonneg, simp [h₁, sq_sqrt, h₂], end, ..c } end /-! ### Properties of inner product spaces -/ variables [inner_product_space 𝕜 E] [inner_product_space ℝ F] variables [dec_E : decidable_eq E] local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y local notation `IK` := @is_R_or_C.I 𝕜 _ local notation `absR` := has_abs.abs local notation `absK` := @is_R_or_C.abs 𝕜 _ local postfix `†`:90 := star_ring_end _ export inner_product_space (norm_sq_eq_inner) section basic_properties @[simp] lemma inner_conj_sym (x y : E) : ⟪y, x⟫† = ⟪x, y⟫ := inner_product_space.conj_sym _ _ lemma real_inner_comm (x y : F) : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := @inner_conj_sym ℝ _ _ _ x y lemma inner_eq_zero_sym {x y : E} : ⟪x, y⟫ = 0 ↔ ⟪y, x⟫ = 0 := ⟨λ h, by simp [←inner_conj_sym, h], λ h, by simp [←inner_conj_sym, h]⟩ @[simp] lemma inner_self_nonneg_im {x : E} : im ⟪x, x⟫ = 0 := by rw [← @of_real_inj 𝕜, im_eq_conj_sub]; simp lemma inner_self_im_zero {x : E} : im ⟪x, x⟫ = 0 := inner_self_nonneg_im lemma inner_add_left {x y z : E} : ⟪x + y, z⟫ = ⟪x, z⟫ + ⟪y, z⟫ := inner_product_space.add_left _ _ _ lemma inner_add_right {x y z : E} : ⟪x, y + z⟫ = ⟪x, y⟫ + ⟪x, z⟫ := by { rw [←inner_conj_sym, inner_add_left, ring_hom.map_add], simp only [inner_conj_sym] } lemma inner_re_symm {x y : E} : re ⟪x, y⟫ = re ⟪y, x⟫ := by rw [←inner_conj_sym, conj_re] lemma inner_im_symm {x y : E} : im ⟪x, y⟫ = -im ⟪y, x⟫ := by rw [←inner_conj_sym, conj_im] lemma inner_smul_left {x y : E} {r : 𝕜} : ⟪r • x, y⟫ = r† * ⟪x, y⟫ := inner_product_space.smul_left _ _ _ lemma real_inner_smul_left {x y : F} {r : ℝ} : ⟪r • x, y⟫_ℝ = r * ⟪x, y⟫_ℝ := inner_smul_left lemma inner_smul_real_left {x y : E} {r : ℝ} : ⟪(r : 𝕜) • x, y⟫ = r • ⟪x, y⟫ := by { rw [inner_smul_left, conj_of_real, algebra.smul_def], refl } lemma inner_smul_right {x y : E} {r : 𝕜} : ⟪x, r • y⟫ = r * ⟪x, y⟫ := by rw [←inner_conj_sym, inner_smul_left, ring_hom.map_mul, conj_conj, inner_conj_sym] lemma real_inner_smul_right {x y : F} {r : ℝ} : ⟪x, r • y⟫_ℝ = r * ⟪x, y⟫_ℝ := inner_smul_right lemma inner_smul_real_right {x y : E} {r : ℝ} : ⟪x, (r : 𝕜) • y⟫ = r • ⟪x, y⟫ := by { rw [inner_smul_right, algebra.smul_def], refl } /-- The inner product as a sesquilinear form. Note that in the case `𝕜 = ℝ` this is a bilinear form. -/ @[simps] def sesq_form_of_inner : E →ₗ[𝕜] E →ₗ⋆[𝕜] 𝕜 := linear_map.mk₂'ₛₗ (ring_hom.id 𝕜) (star_ring_end _) (λ x y, ⟪y, x⟫) (λ x y z, inner_add_right) (λ r x y, inner_smul_right) (λ x y z, inner_add_left) (λ r x y, inner_smul_left) /-- An inner product with a sum on the left. -/ lemma sum_inner {ι : Type*} (s : finset ι) (f : ι → E) (x : E) : ⟪∑ i in s, f i, x⟫ = ∑ i in s, ⟪f i, x⟫ := (sesq_form_of_inner x).map_sum /-- An inner product with a sum on the right. -/ lemma inner_sum {ι : Type*} (s : finset ι) (f : ι → E) (x : E) : ⟪x, ∑ i in s, f i⟫ = ∑ i in s, ⟪x, f i⟫ := (linear_map.flip sesq_form_of_inner x).map_sum /-- An inner product with a sum on the left, `finsupp` version. -/ lemma finsupp.sum_inner {ι : Type*} (l : ι →₀ 𝕜) (v : ι → E) (x : E) : ⟪l.sum (λ (i : ι) (a : 𝕜), a • v i), x⟫ = l.sum (λ (i : ι) (a : 𝕜), (conj a) • ⟪v i, x⟫) := by { convert sum_inner l.support (λ a, l a • v a) x, simp only [inner_smul_left, finsupp.sum, smul_eq_mul] } /-- An inner product with a sum on the right, `finsupp` version. -/ lemma finsupp.inner_sum {ι : Type*} (l : ι →₀ 𝕜) (v : ι → E) (x : E) : ⟪x, l.sum (λ (i : ι) (a : 𝕜), a • v i)⟫ = l.sum (λ (i : ι) (a : 𝕜), a • ⟪x, v i⟫) := by { convert inner_sum l.support (λ a, l a • v a) x, simp only [inner_smul_right, finsupp.sum, smul_eq_mul] } lemma dfinsupp.sum_inner {ι : Type*} [dec : decidable_eq ι] {α : ι → Type*} [Π i, add_zero_class (α i)] [Π i (x : α i), decidable (x ≠ 0)] (f : Π i, α i → E) (l : Π₀ i, α i) (x : E) : ⟪l.sum f, x⟫ = l.sum (λ i a, ⟪f i a, x⟫) := by simp only [dfinsupp.sum, sum_inner, smul_eq_mul] {contextual := tt} lemma dfinsupp.inner_sum {ι : Type*} [dec : decidable_eq ι] {α : ι → Type*} [Π i, add_zero_class (α i)] [Π i (x : α i), decidable (x ≠ 0)] (f : Π i, α i → E) (l : Π₀ i, α i) (x : E) : ⟪x, l.sum f⟫ = l.sum (λ i a, ⟪x, f i a⟫) := by simp only [dfinsupp.sum, inner_sum, smul_eq_mul] {contextual := tt} @[simp] lemma inner_zero_left {x : E} : ⟪0, x⟫ = 0 := by rw [← zero_smul 𝕜 (0:E), inner_smul_left, ring_hom.map_zero, zero_mul] lemma inner_re_zero_left {x : E} : re ⟪0, x⟫ = 0 := by simp only [inner_zero_left, add_monoid_hom.map_zero] @[simp] lemma inner_zero_right {x : E} : ⟪x, 0⟫ = 0 := by rw [←inner_conj_sym, inner_zero_left, ring_hom.map_zero] lemma inner_re_zero_right {x : E} : re ⟪x, 0⟫ = 0 := by simp only [inner_zero_right, add_monoid_hom.map_zero] lemma inner_self_nonneg {x : E} : 0 ≤ re ⟪x, x⟫ := by rw [←norm_sq_eq_inner]; exact pow_nonneg (norm_nonneg x) 2 lemma real_inner_self_nonneg {x : F} : 0 ≤ ⟪x, x⟫_ℝ := @inner_self_nonneg ℝ F _ _ x @[simp] lemma inner_self_eq_zero {x : E} : ⟪x, x⟫ = 0 ↔ x = 0 := begin split, { intro h, have h₁ : re ⟪x, x⟫ = 0 := by rw is_R_or_C.ext_iff at h; simp only [h.1, zero_re'], rw [←norm_sq_eq_inner x] at h₁, rw [←norm_eq_zero], exact pow_eq_zero h₁ }, { rintro rfl, exact inner_zero_left } end @[simp] lemma inner_self_nonpos {x : E} : re ⟪x, x⟫ ≤ 0 ↔ x = 0 := begin split, { intro h, rw ←inner_self_eq_zero, have H₁ : re ⟪x, x⟫ ≥ 0, exact inner_self_nonneg, have H₂ : re ⟪x, x⟫ = 0, exact le_antisymm h H₁, rw is_R_or_C.ext_iff, exact ⟨by simp [H₂], by simp [inner_self_nonneg_im]⟩ }, { rintro rfl, simp only [inner_zero_left, add_monoid_hom.map_zero] } end lemma real_inner_self_nonpos {x : F} : ⟪x, x⟫_ℝ ≤ 0 ↔ x = 0 := by { have h := @inner_self_nonpos ℝ F _ _ x, simpa using h } @[simp] lemma inner_self_re_to_K {x : E} : (re ⟪x, x⟫ : 𝕜) = ⟪x, x⟫ := is_R_or_C.ext_iff.2 ⟨by simp only [of_real_re], by simp only [inner_self_nonneg_im, of_real_im]⟩ lemma inner_self_eq_norm_sq_to_K (x : E) : ⟪x, x⟫ = (‖x‖ ^ 2 : 𝕜) := begin suffices : (is_R_or_C.re ⟪x, x⟫ : 𝕜) = ‖x‖ ^ 2, { simpa only [inner_self_re_to_K] using this }, exact_mod_cast (norm_sq_eq_inner x).symm end lemma inner_self_re_abs {x : E} : re ⟪x, x⟫ = abs ⟪x, x⟫ := begin conv_rhs { rw [←inner_self_re_to_K] }, symmetry, exact is_R_or_C.abs_of_nonneg inner_self_nonneg, end lemma inner_self_abs_to_K {x : E} : (absK ⟪x, x⟫ : 𝕜) = ⟪x, x⟫ := by { rw [←inner_self_re_abs], exact inner_self_re_to_K } lemma real_inner_self_abs {x : F} : absR ⟪x, x⟫_ℝ = ⟪x, x⟫_ℝ := by { have h := @inner_self_abs_to_K ℝ F _ _ x, simpa using h } lemma inner_abs_conj_sym {x y : E} : abs ⟪x, y⟫ = abs ⟪y, x⟫ := by rw [←inner_conj_sym, abs_conj] @[simp] lemma inner_neg_left {x y : E} : ⟪-x, y⟫ = -⟪x, y⟫ := by { rw [← neg_one_smul 𝕜 x, inner_smul_left], simp } @[simp] lemma inner_neg_right {x y : E} : ⟪x, -y⟫ = -⟪x, y⟫ := by rw [←inner_conj_sym, inner_neg_left]; simp only [ring_hom.map_neg, inner_conj_sym] lemma inner_neg_neg {x y : E} : ⟪-x, -y⟫ = ⟪x, y⟫ := by simp @[simp] lemma inner_self_conj {x : E} : ⟪x, x⟫† = ⟪x, x⟫ := by rw [is_R_or_C.ext_iff]; exact ⟨by rw [conj_re], by rw [conj_im, inner_self_im_zero, neg_zero]⟩ lemma inner_sub_left {x y z : E} : ⟪x - y, z⟫ = ⟪x, z⟫ - ⟪y, z⟫ := by { simp [sub_eq_add_neg, inner_add_left] } lemma inner_sub_right {x y z : E} : ⟪x, y - z⟫ = ⟪x, y⟫ - ⟪x, z⟫ := by { simp [sub_eq_add_neg, inner_add_right] } lemma inner_mul_conj_re_abs {x y : E} : re (⟪x, y⟫ * ⟪y, x⟫) = abs (⟪x, y⟫ * ⟪y, x⟫) := by { rw [←inner_conj_sym, mul_comm], exact re_eq_abs_of_mul_conj (inner y x), } /-- Expand `⟪x + y, x + y⟫` -/ lemma inner_add_add_self {x y : E} : ⟪x + y, x + y⟫ = ⟪x, x⟫ + ⟪x, y⟫ + ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_add_left, inner_add_right]; ring /-- Expand `⟪x + y, x + y⟫_ℝ` -/ lemma real_inner_add_add_self {x y : F} : ⟪x + y, x + y⟫_ℝ = ⟪x, x⟫_ℝ + 2 * ⟪x, y⟫_ℝ + ⟪y, y⟫_ℝ := begin have : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_sym]; refl, simp only [inner_add_add_self, this, add_left_inj], ring, end /- Expand `⟪x - y, x - y⟫` -/ lemma inner_sub_sub_self {x y : E} : ⟪x - y, x - y⟫ = ⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_sub_left, inner_sub_right]; ring /-- Expand `⟪x - y, x - y⟫_ℝ` -/ lemma real_inner_sub_sub_self {x y : F} : ⟪x - y, x - y⟫_ℝ = ⟪x, x⟫_ℝ - 2 * ⟪x, y⟫_ℝ + ⟪y, y⟫_ℝ := begin have : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_sym]; refl, simp only [inner_sub_sub_self, this, add_left_inj], ring, end variable (𝕜) include 𝕜 lemma ext_inner_left {x y : E} (h : ∀ v, ⟪v, x⟫ = ⟪v, y⟫) : x = y := by rw [←sub_eq_zero, ←inner_self_eq_zero, inner_sub_right, sub_eq_zero, h (x - y)] lemma ext_inner_right {x y : E} (h : ∀ v, ⟪x, v⟫ = ⟪y, v⟫) : x = y := by rw [←sub_eq_zero, ←inner_self_eq_zero, inner_sub_left, sub_eq_zero, h (x - y)] omit 𝕜 variable {𝕜} /-- Parallelogram law -/ lemma parallelogram_law {x y : E} : ⟪x + y, x + y⟫ + ⟪x - y, x - y⟫ = 2 * (⟪x, x⟫ + ⟪y, y⟫) := by simp [inner_add_add_self, inner_sub_sub_self, two_mul, sub_eq_add_neg, add_comm, add_left_comm] /-- Cauchy–Schwarz inequality. This proof follows "Proof 2" on Wikipedia. -/ lemma inner_mul_inner_self_le (x y : E) : abs ⟪x, y⟫ * abs ⟪y, x⟫ ≤ re ⟪x, x⟫ * re ⟪y, y⟫ := begin by_cases hy : y = 0, { rw [hy], simp only [is_R_or_C.abs_zero, inner_zero_left, mul_zero, add_monoid_hom.map_zero] }, { have hy' : ⟪y, y⟫ ≠ 0 := inner_self_eq_zero.not.2 hy, set T := ⟪y, x⟫ / ⟪y, y⟫ with hT, have h₁ : re ⟪y, x⟫ = re ⟪x, y⟫ := inner_re_symm, have h₂ : im ⟪y, x⟫ = -im ⟪x, y⟫ := inner_im_symm, have h₃ : ⟪y, x⟫ * ⟪x, y⟫ * ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = ⟪y, x⟫ * ⟪x, y⟫ / ⟪y, y⟫, { rw [mul_div_assoc], have : ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = 1 / ⟪y, y⟫ := by rw [div_mul_eq_div_mul_one_div, div_self hy', one_mul], rw [this, div_eq_mul_inv, one_mul, ←div_eq_mul_inv] }, have h₄ : ⟪y, y⟫ = re ⟪y, y⟫ := inner_self_re_to_K.symm, have h₅ : re ⟪y, y⟫ > 0, { refine lt_of_le_of_ne inner_self_nonneg _, intro H, apply hy', rw is_R_or_C.ext_iff, exact ⟨by simp only [H, zero_re'], by simp only [inner_self_nonneg_im, add_monoid_hom.map_zero]⟩ }, have h₆ : re ⟪y, y⟫ ≠ 0 := ne_of_gt h₅, have hmain := calc 0 ≤ re ⟪x - T • y, x - T • y⟫ : inner_self_nonneg ... = re ⟪x, x⟫ - re ⟪T • y, x⟫ - re ⟪x, T • y⟫ + re ⟪T • y, T • y⟫ : by simp only [inner_sub_sub_self, inner_smul_left, inner_smul_right, h₁, h₂, neg_mul, add_monoid_hom.map_add, conj_im, add_monoid_hom.map_sub, mul_neg, conj_re, neg_neg, mul_re] ... = re ⟪x, x⟫ - re (T† * ⟪y, x⟫) - re (T * ⟪x, y⟫) + re (T * T† * ⟪y, y⟫) : by simp only [inner_smul_left, inner_smul_right, mul_assoc] ... = re ⟪x, x⟫ - re (⟪x, y⟫ / ⟪y, y⟫ * ⟪y, x⟫) : by simp only [map_div₀, h₃, inner_conj_sym, sub_add_cancel] with field_simps {discharger := tactic.field_simp.ne_zero} ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / ⟪y, y⟫) : by rw ←mul_div_right_comm ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / re ⟪y, y⟫) : by conv_lhs { rw [h₄] } ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [div_re_of_real] ... = re ⟪x, x⟫ - abs (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [inner_mul_conj_re_abs] ... = re ⟪x, x⟫ - abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ : by rw is_R_or_C.abs_mul, have hmain' : abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ ≤ re ⟪x, x⟫ := by linarith, have := (mul_le_mul_right h₅).mpr hmain', rwa [div_mul_cancel (abs ⟪x, y⟫ * abs ⟪y, x⟫) h₆] at this } end /-- Cauchy–Schwarz inequality for real inner products. -/ lemma real_inner_mul_inner_self_le (x y : F) : ⟪x, y⟫_ℝ * ⟪x, y⟫_ℝ ≤ ⟪x, x⟫_ℝ * ⟪y, y⟫_ℝ := begin have h₁ : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_sym]; refl, have h₂ := @inner_mul_inner_self_le ℝ F _ _ x y, dsimp at h₂, have h₃ := abs_mul_abs_self ⟪x, y⟫_ℝ, rw [h₁] at h₂, simpa [h₃] using h₂, end /-- A family of vectors is linearly independent if they are nonzero and orthogonal. -/ lemma linear_independent_of_ne_zero_of_inner_eq_zero {ι : Type*} {v : ι → E} (hz : ∀ i, v i ≠ 0) (ho : ∀ i j, i ≠ j → ⟪v i, v j⟫ = 0) : linear_independent 𝕜 v := begin rw linear_independent_iff', intros s g hg i hi, have h' : g i * inner (v i) (v i) = inner (v i) (∑ j in s, g j • v j), { rw inner_sum, symmetry, convert finset.sum_eq_single i _ _, { rw inner_smul_right }, { intros j hj hji, rw [inner_smul_right, ho i j hji.symm, mul_zero] }, { exact λ h, false.elim (h hi) } }, simpa [hg, hz] using h' end end basic_properties section orthonormal_sets variables {ι : Type*} [dec_ι : decidable_eq ι] (𝕜) include 𝕜 /-- An orthonormal set of vectors in an `inner_product_space` -/ def orthonormal (v : ι → E) : Prop := (∀ i, ‖v i‖ = 1) ∧ (∀ {i j}, i ≠ j → ⟪v i, v j⟫ = 0) omit 𝕜 variables {𝕜} include dec_ι /-- `if ... then ... else` characterization of an indexed set of vectors being orthonormal. (Inner product equals Kronecker delta.) -/ lemma orthonormal_iff_ite {v : ι → E} : orthonormal 𝕜 v ↔ ∀ i j, ⟪v i, v j⟫ = if i = j then (1:𝕜) else (0:𝕜) := begin split, { intros hv i j, split_ifs, { simp [h, inner_self_eq_norm_sq_to_K, hv.1] }, { exact hv.2 h } }, { intros h, split, { intros i, have h' : ‖v i‖ ^ 2 = 1 ^ 2 := by simp [norm_sq_eq_inner, h i i], have h₁ : 0 ≤ ‖v i‖ := norm_nonneg _, have h₂ : (0:ℝ) ≤ 1 := zero_le_one, rwa sq_eq_sq h₁ h₂ at h' }, { intros i j hij, simpa [hij] using h i j } } end omit dec_ι include dec_E /-- `if ... then ... else` characterization of a set of vectors being orthonormal. (Inner product equals Kronecker delta.) -/ theorem orthonormal_subtype_iff_ite {s : set E} : orthonormal 𝕜 (coe : s → E) ↔ (∀ v ∈ s, ∀ w ∈ s, ⟪v, w⟫ = if v = w then 1 else 0) := begin rw orthonormal_iff_ite, split, { intros h v hv w hw, convert h ⟨v, hv⟩ ⟨w, hw⟩ using 1, simp }, { rintros h ⟨v, hv⟩ ⟨w, hw⟩, convert h v hv w hw using 1, simp } end omit dec_E /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_right_finsupp {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι →₀ 𝕜) (i : ι) : ⟪v i, finsupp.total ι E 𝕜 v l⟫ = l i := by classical; simp [finsupp.total_apply, finsupp.inner_sum, orthonormal_iff_ite.mp hv] /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_right_sum {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι → 𝕜) {s : finset ι} {i : ι} (hi : i ∈ s) : ⟪v i, ∑ i in s, (l i) • (v i)⟫ = l i := by classical; simp [inner_sum, inner_smul_right, orthonormal_iff_ite.mp hv, hi] /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_right_fintype [fintype ι] {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι → 𝕜) (i : ι) : ⟪v i, ∑ i : ι, (l i) • (v i)⟫ = l i := hv.inner_right_sum l (finset.mem_univ _) /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_left_finsupp {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι →₀ 𝕜) (i : ι) : ⟪finsupp.total ι E 𝕜 v l, v i⟫ = conj (l i) := by rw [← inner_conj_sym, hv.inner_right_finsupp] /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_left_sum {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι → 𝕜) {s : finset ι} {i : ι} (hi : i ∈ s) : ⟪∑ i in s, (l i) • (v i), v i⟫ = conj (l i) := by classical; simp only [sum_inner, inner_smul_left, orthonormal_iff_ite.mp hv, hi, mul_boole, finset.sum_ite_eq', if_true] /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_left_fintype [fintype ι] {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι → 𝕜) (i : ι) : ⟪∑ i : ι, (l i) • (v i), v i⟫ = conj (l i) := hv.inner_left_sum l (finset.mem_univ _) /-- The inner product of two linear combinations of a set of orthonormal vectors, expressed as a sum over the first `finsupp`. -/ lemma orthonormal.inner_finsupp_eq_sum_left {v : ι → E} (hv : orthonormal 𝕜 v) (l₁ l₂ : ι →₀ 𝕜) : ⟪finsupp.total ι E 𝕜 v l₁, finsupp.total ι E 𝕜 v l₂⟫ = l₁.sum (λ i y, conj y * l₂ i) := by simp only [l₁.total_apply _, finsupp.sum_inner, hv.inner_right_finsupp, smul_eq_mul] /-- The inner product of two linear combinations of a set of orthonormal vectors, expressed as a sum over the second `finsupp`. -/ lemma orthonormal.inner_finsupp_eq_sum_right {v : ι → E} (hv : orthonormal 𝕜 v) (l₁ l₂ : ι →₀ 𝕜) : ⟪finsupp.total ι E 𝕜 v l₁, finsupp.total ι E 𝕜 v l₂⟫ = l₂.sum (λ i y, conj (l₁ i) * y) := by simp only [l₂.total_apply _, finsupp.inner_sum, hv.inner_left_finsupp, mul_comm, smul_eq_mul] /-- The inner product of two linear combinations of a set of orthonormal vectors, expressed as a sum. -/ lemma orthonormal.inner_sum {v : ι → E} (hv : orthonormal 𝕜 v) (l₁ l₂ : ι → 𝕜) (s : finset ι) : ⟪∑ i in s, l₁ i • v i, ∑ i in s, l₂ i • v i⟫ = ∑ i in s, conj (l₁ i) * l₂ i := begin simp_rw [sum_inner, inner_smul_left], refine finset.sum_congr rfl (λ i hi, _), rw hv.inner_right_sum l₂ hi end /-- The double sum of weighted inner products of pairs of vectors from an orthonormal sequence is the sum of the weights. -/ lemma orthonormal.inner_left_right_finset {s : finset ι} {v : ι → E} (hv : orthonormal 𝕜 v) {a : ι → ι → 𝕜} : ∑ i in s, ∑ j in s, (a i j) • ⟪v j, v i⟫ = ∑ k in s, a k k := by classical; simp [orthonormal_iff_ite.mp hv, finset.sum_ite_of_true] /-- An orthonormal set is linearly independent. -/ lemma orthonormal.linear_independent {v : ι → E} (hv : orthonormal 𝕜 v) : linear_independent 𝕜 v := begin rw linear_independent_iff, intros l hl, ext i, have key : ⟪v i, finsupp.total ι E 𝕜 v l⟫ = ⟪v i, 0⟫ := by rw hl, simpa only [hv.inner_right_finsupp, inner_zero_right] using key end /-- A subfamily of an orthonormal family (i.e., a composition with an injective map) is an orthonormal family. -/ lemma orthonormal.comp {ι' : Type*} {v : ι → E} (hv : orthonormal 𝕜 v) (f : ι' → ι) (hf : function.injective f) : orthonormal 𝕜 (v ∘ f) := begin classical, rw orthonormal_iff_ite at ⊢ hv, intros i j, convert hv (f i) (f j) using 1, simp [hf.eq_iff] end /-- An injective family `v : ι → E` is orthonormal if and only if `coe : (range v) → E` is orthonormal. -/ lemma orthonormal_subtype_range {v : ι → E} (hv : function.injective v) : orthonormal 𝕜 (coe : set.range v → E) ↔ orthonormal 𝕜 v := begin let f : ι ≃ set.range v := equiv.of_injective v hv, refine ⟨λ h, h.comp f f.injective, λ h, _⟩, rw ← equiv.self_comp_of_injective_symm hv, exact h.comp f.symm f.symm.injective, end /-- If `v : ι → E` is an orthonormal family, then `coe : (range v) → E` is an orthonormal family. -/ lemma orthonormal.to_subtype_range {v : ι → E} (hv : orthonormal 𝕜 v) : orthonormal 𝕜 (coe : set.range v → E) := (orthonormal_subtype_range hv.linear_independent.injective).2 hv /-- A linear combination of some subset of an orthonormal set is orthogonal to other members of the set. -/ lemma orthonormal.inner_finsupp_eq_zero {v : ι → E} (hv : orthonormal 𝕜 v) {s : set ι} {i : ι} (hi : i ∉ s) {l : ι →₀ 𝕜} (hl : l ∈ finsupp.supported 𝕜 𝕜 s) : ⟪finsupp.total ι E 𝕜 v l, v i⟫ = 0 := begin rw finsupp.mem_supported' at hl, simp only [hv.inner_left_finsupp, hl i hi, map_zero], end /-- Given an orthonormal family, a second family of vectors is orthonormal if every vector equals the corresponding vector in the original family or its negation. -/ lemma orthonormal.orthonormal_of_forall_eq_or_eq_neg {v w : ι → E} (hv : orthonormal 𝕜 v) (hw : ∀ i, w i = v i ∨ w i = -(v i)) : orthonormal 𝕜 w := begin classical, rw orthonormal_iff_ite at *, intros i j, cases hw i with hi hi; cases hw j with hj hj; split_ifs with h; simpa only [hi, hj, h, inner_neg_right, inner_neg_left, neg_neg, eq_self_iff_true, neg_eq_zero] using hv i j end /- The material that follows, culminating in the existence of a maximal orthonormal subset, is adapted from the corresponding development of the theory of linearly independents sets. See `exists_linear_independent` in particular. -/ variables (𝕜 E) lemma orthonormal_empty : orthonormal 𝕜 (λ x, x : (∅ : set E) → E) := by classical; simp [orthonormal_subtype_iff_ite] variables {𝕜 E} lemma orthonormal_Union_of_directed {η : Type*} {s : η → set E} (hs : directed (⊆) s) (h : ∀ i, orthonormal 𝕜 (λ x, x : s i → E)) : orthonormal 𝕜 (λ x, x : (⋃ i, s i) → E) := begin classical, rw orthonormal_subtype_iff_ite, rintros x ⟨_, ⟨i, rfl⟩, hxi⟩ y ⟨_, ⟨j, rfl⟩, hyj⟩, obtain ⟨k, hik, hjk⟩ := hs i j, have h_orth : orthonormal 𝕜 (λ x, x : (s k) → E) := h k, rw orthonormal_subtype_iff_ite at h_orth, exact h_orth x (hik hxi) y (hjk hyj) end lemma orthonormal_sUnion_of_directed {s : set (set E)} (hs : directed_on (⊆) s) (h : ∀ a ∈ s, orthonormal 𝕜 (λ x, x : (a : set E) → E)) : orthonormal 𝕜 (λ x, x : (⋃₀ s) → E) := by rw set.sUnion_eq_Union; exact orthonormal_Union_of_directed hs.directed_coe (by simpa using h) /-- Given an orthonormal set `v` of vectors in `E`, there exists a maximal orthonormal set containing it. -/ lemma exists_maximal_orthonormal {s : set E} (hs : orthonormal 𝕜 (coe : s → E)) : ∃ w ⊇ s, orthonormal 𝕜 (coe : w → E) ∧ ∀ u ⊇ w, orthonormal 𝕜 (coe : u → E) → u = w := begin obtain ⟨b, bi, sb, h⟩ := zorn_subset_nonempty {b | orthonormal 𝕜 (coe : b → E)} _ _ hs, { refine ⟨b, sb, bi, _⟩, exact λ u hus hu, h u hu hus }, { refine λ c hc cc c0, ⟨⋃₀ c, _, _⟩, { exact orthonormal_sUnion_of_directed cc.directed_on (λ x xc, hc xc) }, { exact λ _, set.subset_sUnion_of_mem } } end lemma orthonormal.ne_zero {v : ι → E} (hv : orthonormal 𝕜 v) (i : ι) : v i ≠ 0 := begin have : ‖v i‖ ≠ 0, { rw hv.1 i, norm_num }, simpa using this end open finite_dimensional /-- A family of orthonormal vectors with the correct cardinality forms a basis. -/ def basis_of_orthonormal_of_card_eq_finrank [fintype ι] [nonempty ι] {v : ι → E} (hv : orthonormal 𝕜 v) (card_eq : fintype.card ι = finrank 𝕜 E) : basis ι 𝕜 E := basis_of_linear_independent_of_card_eq_finrank hv.linear_independent card_eq @[simp] lemma coe_basis_of_orthonormal_of_card_eq_finrank [fintype ι] [nonempty ι] {v : ι → E} (hv : orthonormal 𝕜 v) (card_eq : fintype.card ι = finrank 𝕜 E) : (basis_of_orthonormal_of_card_eq_finrank hv card_eq : ι → E) = v := coe_basis_of_linear_independent_of_card_eq_finrank _ _ end orthonormal_sets section norm lemma norm_eq_sqrt_inner (x : E) : ‖x‖ = sqrt (re ⟪x, x⟫) := calc ‖x‖ = sqrt (‖x‖ ^ 2) : (sqrt_sq (norm_nonneg _)).symm ... = sqrt (re ⟪x, x⟫) : congr_arg _ (norm_sq_eq_inner _) lemma norm_eq_sqrt_real_inner (x : F) : ‖x‖ = sqrt ⟪x, x⟫_ℝ := by { have h := @norm_eq_sqrt_inner ℝ F _ _ x, simpa using h } lemma inner_self_eq_norm_mul_norm (x : E) : re ⟪x, x⟫ = ‖x‖ * ‖x‖ := by rw [norm_eq_sqrt_inner, ←sqrt_mul inner_self_nonneg (re ⟪x, x⟫), sqrt_mul_self inner_self_nonneg] lemma inner_self_eq_norm_sq (x : E) : re ⟪x, x⟫ = ‖x‖^2 := by rw [pow_two, inner_self_eq_norm_mul_norm] lemma real_inner_self_eq_norm_mul_norm (x : F) : ⟪x, x⟫_ℝ = ‖x‖ * ‖x‖ := by { have h := @inner_self_eq_norm_mul_norm ℝ F _ _ x, simpa using h } lemma real_inner_self_eq_norm_sq (x : F) : ⟪x, x⟫_ℝ = ‖x‖^2 := by rw [pow_two, real_inner_self_eq_norm_mul_norm] /-- Expand the square -/ lemma norm_add_sq {x y : E} : ‖x + y‖^2 = ‖x‖^2 + 2 * (re ⟪x, y⟫) + ‖y‖^2 := begin repeat {rw [sq, ←inner_self_eq_norm_mul_norm]}, rw [inner_add_add_self, two_mul], simp only [add_assoc, add_left_inj, add_right_inj, add_monoid_hom.map_add], rw [←inner_conj_sym, conj_re], end alias norm_add_sq ← norm_add_pow_two /-- Expand the square -/ lemma norm_add_sq_real {x y : F} : ‖x + y‖^2 = ‖x‖^2 + 2 * ⟪x, y⟫_ℝ + ‖y‖^2 := by { have h := @norm_add_sq ℝ F _ _, simpa using h } alias norm_add_sq_real ← norm_add_pow_two_real /-- Expand the square -/ lemma norm_add_mul_self {x y : E} : ‖x + y‖ * ‖x + y‖ = ‖x‖ * ‖x‖ + 2 * (re ⟪x, y⟫) + ‖y‖ * ‖y‖ := by { repeat {rw [← sq]}, exact norm_add_sq } /-- Expand the square -/ lemma norm_add_mul_self_real {x y : F} : ‖x + y‖ * ‖x + y‖ = ‖x‖ * ‖x‖ + 2 * ⟪x, y⟫_ℝ + ‖y‖ * ‖y‖ := by { have h := @norm_add_mul_self ℝ F _ _, simpa using h } /-- Expand the square -/ lemma norm_sub_sq {x y : E} : ‖x - y‖^2 = ‖x‖^2 - 2 * (re ⟪x, y⟫) + ‖y‖^2 := begin repeat {rw [sq, ←inner_self_eq_norm_mul_norm]}, rw [inner_sub_sub_self], calc re (⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫) = re ⟪x, x⟫ - re ⟪x, y⟫ - re ⟪y, x⟫ + re ⟪y, y⟫ : by simp only [map_add, map_sub] ... = -re ⟪y, x⟫ - re ⟪x, y⟫ + re ⟪x, x⟫ + re ⟪y, y⟫ : by ring ... = -re (⟪x, y⟫†) - re ⟪x, y⟫ + re ⟪x, x⟫ + re ⟪y, y⟫ : by rw [inner_conj_sym] ... = -re ⟪x, y⟫ - re ⟪x, y⟫ + re ⟪x, x⟫ + re ⟪y, y⟫ : by rw [conj_re] ... = re ⟪x, x⟫ - 2*re ⟪x, y⟫ + re ⟪y, y⟫ : by ring end alias norm_sub_sq ← norm_sub_pow_two /-- Expand the square -/ lemma norm_sub_sq_real {x y : F} : ‖x - y‖^2 = ‖x‖^2 - 2 * ⟪x, y⟫_ℝ + ‖y‖^2 := norm_sub_sq alias norm_sub_sq_real ← norm_sub_pow_two_real /-- Expand the square -/ lemma norm_sub_mul_self {x y : E} : ‖x - y‖ * ‖x - y‖ = ‖x‖ * ‖x‖ - 2 * re ⟪x, y⟫ + ‖y‖ * ‖y‖ := by { repeat {rw [← sq]}, exact norm_sub_sq } /-- Expand the square -/ lemma norm_sub_mul_self_real {x y : F} : ‖x - y‖ * ‖x - y‖ = ‖x‖ * ‖x‖ - 2 * ⟪x, y⟫_ℝ + ‖y‖ * ‖y‖ := by { have h := @norm_sub_mul_self ℝ F _ _, simpa using h } /-- Cauchy–Schwarz inequality with norm -/ lemma abs_inner_le_norm (x y : E) : abs ⟪x, y⟫ ≤ ‖x‖ * ‖y‖ := nonneg_le_nonneg_of_sq_le_sq (mul_nonneg (norm_nonneg _) (norm_nonneg _)) begin have : ‖x‖ * ‖y‖ * (‖x‖ * ‖y‖) = (re ⟪x, x⟫) * (re ⟪y, y⟫), simp only [inner_self_eq_norm_mul_norm], ring, rw this, conv_lhs { congr, skip, rw [inner_abs_conj_sym] }, exact inner_mul_inner_self_le _ _ end lemma norm_inner_le_norm (x y : E) : ‖⟪x, y⟫‖ ≤ ‖x‖ * ‖y‖ := (is_R_or_C.norm_eq_abs _).le.trans (abs_inner_le_norm x y) lemma nnnorm_inner_le_nnnorm (x y : E) : ‖⟪x, y⟫‖₊ ≤ ‖x‖₊ * ‖y‖₊ := norm_inner_le_norm x y lemma re_inner_le_norm (x y : E) : re ⟪x, y⟫ ≤ ‖x‖ * ‖y‖ := le_trans (re_le_abs (inner x y)) (abs_inner_le_norm x y) /-- Cauchy–Schwarz inequality with norm -/ lemma abs_real_inner_le_norm (x y : F) : absR ⟪x, y⟫_ℝ ≤ ‖x‖ * ‖y‖ := by { have h := @abs_inner_le_norm ℝ F _ _ x y, simpa using h } /-- Cauchy–Schwarz inequality with norm -/ lemma real_inner_le_norm (x y : F) : ⟪x, y⟫_ℝ ≤ ‖x‖ * ‖y‖ := le_trans (le_abs_self _) (abs_real_inner_le_norm _ _) include 𝕜 lemma parallelogram_law_with_norm (x y : E) : ‖x + y‖ * ‖x + y‖ + ‖x - y‖ * ‖x - y‖ = 2 * (‖x‖ * ‖x‖ + ‖y‖ * ‖y‖) := begin simp only [← inner_self_eq_norm_mul_norm], rw [← re.map_add, parallelogram_law, two_mul, two_mul], simp only [re.map_add], end lemma parallelogram_law_with_nnnorm (x y : E) : ‖x + y‖₊ * ‖x + y‖₊ + ‖x - y‖₊ * ‖x - y‖₊ = 2 * (‖x‖₊ * ‖x‖₊ + ‖y‖₊ * ‖y‖₊) := subtype.ext $ parallelogram_law_with_norm x y omit 𝕜 /-- Polarization identity: The real part of the inner product, in terms of the norm. -/ lemma re_inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two (x y : E) : re ⟪x, y⟫ = (‖x + y‖ * ‖x + y‖ - ‖x‖ * ‖x‖ - ‖y‖ * ‖y‖) / 2 := by { rw norm_add_mul_self, ring } /-- Polarization identity: The real part of the inner product, in terms of the norm. -/ lemma re_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two (x y : E) : re ⟪x, y⟫ = (‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ - ‖x - y‖ * ‖x - y‖) / 2 := by { rw [norm_sub_mul_self], ring } /-- Polarization identity: The real part of the inner product, in terms of the norm. -/ lemma re_inner_eq_norm_add_mul_self_sub_norm_sub_mul_self_div_four (x y : E) : re ⟪x, y⟫ = (‖x + y‖ * ‖x + y‖ - ‖x - y‖ * ‖x - y‖) / 4 := by { rw [norm_add_mul_self, norm_sub_mul_self], ring } /-- Polarization identity: The imaginary part of the inner product, in terms of the norm. -/ lemma im_inner_eq_norm_sub_I_smul_mul_self_sub_norm_add_I_smul_mul_self_div_four (x y : E) : im ⟪x, y⟫ = (‖x - IK • y‖ * ‖x - IK • y‖ - ‖x + IK • y‖ * ‖x + IK • y‖) / 4 := by { simp only [norm_add_mul_self, norm_sub_mul_self, inner_smul_right, I_mul_re], ring } /-- Polarization identity: The inner product, in terms of the norm. -/ lemma inner_eq_sum_norm_sq_div_four (x y : E) : ⟪x, y⟫ = (‖x + y‖ ^ 2 - ‖x - y‖ ^ 2 + (‖x - IK • y‖ ^ 2 - ‖x + IK • y‖ ^ 2) * IK) / 4 := begin rw [← re_add_im ⟪x, y⟫, re_inner_eq_norm_add_mul_self_sub_norm_sub_mul_self_div_four, im_inner_eq_norm_sub_I_smul_mul_self_sub_norm_add_I_smul_mul_self_div_four], push_cast, simp only [sq, ← mul_div_right_comm, ← add_div] end /-- Formula for the distance between the images of two nonzero points under an inversion with center zero. See also `euclidean_geometry.dist_inversion_inversion` for inversions around a general point. -/ lemma dist_div_norm_sq_smul {x y : F} (hx : x ≠ 0) (hy : y ≠ 0) (R : ℝ) : dist ((R / ‖x‖) ^ 2 • x) ((R / ‖y‖) ^ 2 • y) = (R ^ 2 / (‖x‖ * ‖y‖)) * dist x y := have hx' : ‖x‖ ≠ 0, from norm_ne_zero_iff.2 hx, have hy' : ‖y‖ ≠ 0, from norm_ne_zero_iff.2 hy, calc dist ((R / ‖x‖) ^ 2 • x) ((R / ‖y‖) ^ 2 • y) = sqrt (‖(R / ‖x‖) ^ 2 • x - (R / ‖y‖) ^ 2 • y‖^2) : by rw [dist_eq_norm, sqrt_sq (norm_nonneg _)] ... = sqrt ((R ^ 2 / (‖x‖ * ‖y‖)) ^ 2 * ‖x - y‖ ^ 2) : congr_arg sqrt $ by { field_simp [sq, norm_sub_mul_self_real, norm_smul, real_inner_smul_left, inner_smul_right, real.norm_of_nonneg (mul_self_nonneg _)], ring } ... = (R ^ 2 / (‖x‖ * ‖y‖)) * dist x y : by rw [sqrt_mul (sq_nonneg _), sqrt_sq (norm_nonneg _), sqrt_sq (div_nonneg (sq_nonneg _) (mul_nonneg (norm_nonneg _) (norm_nonneg _))), dist_eq_norm] @[priority 100] -- See note [lower instance priority] instance inner_product_space.to_uniform_convex_space : uniform_convex_space F := ⟨λ ε hε, begin refine ⟨2 - sqrt (4 - ε^2), sub_pos_of_lt $ (sqrt_lt' zero_lt_two).2 _, λ x hx y hy hxy, _⟩, { norm_num, exact pow_pos hε _ }, rw sub_sub_cancel, refine le_sqrt_of_sq_le _, rw [sq, eq_sub_iff_add_eq.2 (parallelogram_law_with_norm x y), ←sq (‖x - y‖), hx, hy], norm_num, exact pow_le_pow_of_le_left hε.le hxy _, end⟩ section complex variables {V : Type*} [inner_product_space ℂ V] /-- A complex polarization identity, with a linear map -/ lemma inner_map_polarization (T : V →ₗ[ℂ] V) (x y : V): ⟪ T y, x ⟫_ℂ = (⟪T (x + y) , x + y⟫_ℂ - ⟪T (x - y) , x - y⟫_ℂ + complex.I * ⟪T (x + complex.I • y) , x + complex.I • y⟫_ℂ - complex.I * ⟪T (x - complex.I • y), x - complex.I • y ⟫_ℂ) / 4 := begin simp only [map_add, map_sub, inner_add_left, inner_add_right, linear_map.map_smul, inner_smul_left, inner_smul_right, complex.conj_I, ←pow_two, complex.I_sq, inner_sub_left, inner_sub_right, mul_add, ←mul_assoc, mul_neg, neg_neg, sub_neg_eq_add, one_mul, neg_one_mul, mul_sub, sub_sub], ring, end lemma inner_map_polarization' (T : V →ₗ[ℂ] V) (x y : V): ⟪ T x, y ⟫_ℂ = (⟪T (x + y) , x + y⟫_ℂ - ⟪T (x - y) , x - y⟫_ℂ - complex.I * ⟪T (x + complex.I • y) , x + complex.I • y⟫_ℂ + complex.I * ⟪T (x - complex.I • y), x - complex.I • y ⟫_ℂ) / 4 := begin simp only [map_add, map_sub, inner_add_left, inner_add_right, linear_map.map_smul, inner_smul_left, inner_smul_right, complex.conj_I, ←pow_two, complex.I_sq, inner_sub_left, inner_sub_right, mul_add, ←mul_assoc, mul_neg, neg_neg, sub_neg_eq_add, one_mul, neg_one_mul, mul_sub, sub_sub], ring, end /-- A linear map `T` is zero, if and only if the identity `⟪T x, x⟫_ℂ = 0` holds for all `x`. -/ lemma inner_map_self_eq_zero (T : V →ₗ[ℂ] V) : (∀ (x : V), ⟪T x, x⟫_ℂ = 0) ↔ T = 0 := begin split, { intro hT, ext x, simp only [linear_map.zero_apply, ← inner_self_eq_zero, inner_map_polarization, hT], norm_num }, { rintro rfl x, simp only [linear_map.zero_apply, inner_zero_left] } end /-- Two linear maps `S` and `T` are equal, if and only if the identity `⟪S x, x⟫_ℂ = ⟪T x, x⟫_ℂ` holds for all `x`. -/ lemma ext_inner_map (S T : V →ₗ[ℂ] V) : (∀ (x : V), ⟪S x, x⟫_ℂ = ⟪T x, x⟫_ℂ) ↔ S = T := begin rw [←sub_eq_zero, ←inner_map_self_eq_zero], refine forall_congr (λ x, _), rw [linear_map.sub_apply, inner_sub_left, sub_eq_zero], end end complex section variables {ι : Type*} {ι' : Type*} {ι'' : Type*} variables {E' : Type*} [inner_product_space 𝕜 E'] variables {E'' : Type*} [inner_product_space 𝕜 E''] /-- A linear isometry preserves the inner product. -/ @[simp] lemma linear_isometry.inner_map_map (f : E →ₗᵢ[𝕜] E') (x y : E) : ⟪f x, f y⟫ = ⟪x, y⟫ := by simp [inner_eq_sum_norm_sq_div_four, ← f.norm_map] /-- A linear isometric equivalence preserves the inner product. -/ @[simp] lemma linear_isometry_equiv.inner_map_map (f : E ≃ₗᵢ[𝕜] E') (x y : E) : ⟪f x, f y⟫ = ⟪x, y⟫ := f.to_linear_isometry.inner_map_map x y /-- A linear map that preserves the inner product is a linear isometry. -/ def linear_map.isometry_of_inner (f : E →ₗ[𝕜] E') (h : ∀ x y, ⟪f x, f y⟫ = ⟪x, y⟫) : E →ₗᵢ[𝕜] E' := ⟨f, λ x, by simp only [norm_eq_sqrt_inner, h]⟩ @[simp] lemma linear_map.coe_isometry_of_inner (f : E →ₗ[𝕜] E') (h) : ⇑(f.isometry_of_inner h) = f := rfl @[simp] lemma linear_map.isometry_of_inner_to_linear_map (f : E →ₗ[𝕜] E') (h) : (f.isometry_of_inner h).to_linear_map = f := rfl /-- A linear equivalence that preserves the inner product is a linear isometric equivalence. -/ def linear_equiv.isometry_of_inner (f : E ≃ₗ[𝕜] E') (h : ∀ x y, ⟪f x, f y⟫ = ⟪x, y⟫) : E ≃ₗᵢ[𝕜] E' := ⟨f, ((f : E →ₗ[𝕜] E').isometry_of_inner h).norm_map⟩ @[simp] lemma linear_equiv.coe_isometry_of_inner (f : E ≃ₗ[𝕜] E') (h) : ⇑(f.isometry_of_inner h) = f := rfl @[simp] lemma linear_equiv.isometry_of_inner_to_linear_equiv (f : E ≃ₗ[𝕜] E') (h) : (f.isometry_of_inner h).to_linear_equiv = f := rfl /-- A linear isometry preserves the property of being orthonormal. -/ lemma linear_isometry.orthonormal_comp_iff {v : ι → E} (f : E →ₗᵢ[𝕜] E') : orthonormal 𝕜 (f ∘ v) ↔ orthonormal 𝕜 v := begin classical, simp_rw [orthonormal_iff_ite, linear_isometry.inner_map_map] end /-- A linear isometry preserves the property of being orthonormal. -/ lemma orthonormal.comp_linear_isometry {v : ι → E} (hv : orthonormal 𝕜 v) (f : E →ₗᵢ[𝕜] E') : orthonormal 𝕜 (f ∘ v) := by rwa f.orthonormal_comp_iff /-- A linear isometric equivalence preserves the property of being orthonormal. -/ lemma orthonormal.comp_linear_isometry_equiv {v : ι → E} (hv : orthonormal 𝕜 v) (f : E ≃ₗᵢ[𝕜] E') : orthonormal 𝕜 (f ∘ v) := hv.comp_linear_isometry f.to_linear_isometry /-- A linear isometric equivalence, applied with `basis.map`, preserves the property of being orthonormal. -/ lemma orthonormal.map_linear_isometry_equiv {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) (f : E ≃ₗᵢ[𝕜] E') : orthonormal 𝕜 (v.map f.to_linear_equiv) := hv.comp_linear_isometry_equiv f /-- A linear map that sends an orthonormal basis to orthonormal vectors is a linear isometry. -/ def linear_map.isometry_of_orthonormal (f : E →ₗ[𝕜] E') {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) (hf : orthonormal 𝕜 (f ∘ v)) : E →ₗᵢ[𝕜] E' := f.isometry_of_inner $ λ x y, by rw [←v.total_repr x, ←v.total_repr y, finsupp.apply_total, finsupp.apply_total, hv.inner_finsupp_eq_sum_left, hf.inner_finsupp_eq_sum_left] @[simp] lemma linear_map.coe_isometry_of_orthonormal (f : E →ₗ[𝕜] E') {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) (hf : orthonormal 𝕜 (f ∘ v)) : ⇑(f.isometry_of_orthonormal hv hf) = f := rfl @[simp] lemma linear_map.isometry_of_orthonormal_to_linear_map (f : E →ₗ[𝕜] E') {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) (hf : orthonormal 𝕜 (f ∘ v)) : (f.isometry_of_orthonormal hv hf).to_linear_map = f := rfl /-- A linear equivalence that sends an orthonormal basis to orthonormal vectors is a linear isometric equivalence. -/ def linear_equiv.isometry_of_orthonormal (f : E ≃ₗ[𝕜] E') {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) (hf : orthonormal 𝕜 (f ∘ v)) : E ≃ₗᵢ[𝕜] E' := f.isometry_of_inner $ λ x y, begin rw ←linear_equiv.coe_coe at hf, rw [←v.total_repr x, ←v.total_repr y, ←linear_equiv.coe_coe, finsupp.apply_total, finsupp.apply_total, hv.inner_finsupp_eq_sum_left, hf.inner_finsupp_eq_sum_left] end @[simp] lemma linear_equiv.coe_isometry_of_orthonormal (f : E ≃ₗ[𝕜] E') {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) (hf : orthonormal 𝕜 (f ∘ v)) : ⇑(f.isometry_of_orthonormal hv hf) = f := rfl @[simp] lemma linear_equiv.isometry_of_orthonormal_to_linear_equiv (f : E ≃ₗ[𝕜] E') {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) (hf : orthonormal 𝕜 (f ∘ v)) : (f.isometry_of_orthonormal hv hf).to_linear_equiv = f := rfl /-- A linear isometric equivalence that sends an orthonormal basis to a given orthonormal basis. -/ def orthonormal.equiv {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) {v' : basis ι' 𝕜 E'} (hv' : orthonormal 𝕜 v') (e : ι ≃ ι') : E ≃ₗᵢ[𝕜] E' := (v.equiv v' e).isometry_of_orthonormal hv begin have h : (v.equiv v' e) ∘ v = v' ∘ e, { ext i, simp }, rw h, exact hv'.comp _ e.injective end @[simp] lemma orthonormal.equiv_to_linear_equiv {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) {v' : basis ι' 𝕜 E'} (hv' : orthonormal 𝕜 v') (e : ι ≃ ι') : (hv.equiv hv' e).to_linear_equiv = v.equiv v' e := rfl @[simp] lemma orthonormal.equiv_apply {ι' : Type*} {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) {v' : basis ι' 𝕜 E'} (hv' : orthonormal 𝕜 v') (e : ι ≃ ι') (i : ι) : hv.equiv hv' e (v i) = v' (e i) := basis.equiv_apply _ _ _ _ @[simp] lemma orthonormal.equiv_refl {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) : hv.equiv hv (equiv.refl ι) = linear_isometry_equiv.refl 𝕜 E := v.ext_linear_isometry_equiv $ λ i, by simp only [orthonormal.equiv_apply, equiv.coe_refl, id.def, linear_isometry_equiv.coe_refl] @[simp] lemma orthonormal.equiv_symm {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) {v' : basis ι' 𝕜 E'} (hv' : orthonormal 𝕜 v') (e : ι ≃ ι') : (hv.equiv hv' e).symm = hv'.equiv hv e.symm := v'.ext_linear_isometry_equiv $ λ i, (hv.equiv hv' e).injective $ by simp only [linear_isometry_equiv.apply_symm_apply, orthonormal.equiv_apply, e.apply_symm_apply] @[simp] lemma orthonormal.equiv_trans {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) {v' : basis ι' 𝕜 E'} (hv' : orthonormal 𝕜 v') (e : ι ≃ ι') {v'' : basis ι'' 𝕜 E''} (hv'' : orthonormal 𝕜 v'') (e' : ι' ≃ ι'') : (hv.equiv hv' e).trans (hv'.equiv hv'' e') = hv.equiv hv'' (e.trans e') := v.ext_linear_isometry_equiv $ λ i, by simp only [linear_isometry_equiv.trans_apply, orthonormal.equiv_apply, e.coe_trans] lemma orthonormal.map_equiv {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) {v' : basis ι' 𝕜 E'} (hv' : orthonormal 𝕜 v') (e : ι ≃ ι') : v.map ((hv.equiv hv' e).to_linear_equiv) = v'.reindex e.symm := v.map_equiv _ _ end /-- Polarization identity: The real inner product, in terms of the norm. -/ lemma real_inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two (x y : F) : ⟪x, y⟫_ℝ = (‖x + y‖ * ‖x + y‖ - ‖x‖ * ‖x‖ - ‖y‖ * ‖y‖) / 2 := re_to_real.symm.trans $ re_inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two x y /-- Polarization identity: The real inner product, in terms of the norm. -/ lemma real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two (x y : F) : ⟪x, y⟫_ℝ = (‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ - ‖x - y‖ * ‖x - y‖) / 2 := re_to_real.symm.trans $ re_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two x y /-- Pythagorean theorem, if-and-only-if vector inner product form. -/ lemma norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero (x y : F) : ‖x + y‖ * ‖x + y‖ = ‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ ↔ ⟪x, y⟫_ℝ = 0 := begin rw [norm_add_mul_self, add_right_cancel_iff, add_right_eq_self, mul_eq_zero], norm_num end /-- Pythagorean theorem, if-and-if vector inner product form using square roots. -/ lemma norm_add_eq_sqrt_iff_real_inner_eq_zero {x y : F} : ‖x + y‖ = sqrt (‖x‖ * ‖x‖ + ‖y‖ * ‖y‖) ↔ ⟪x, y⟫_ℝ = 0 := by rw [←norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero, eq_comm, sqrt_eq_iff_mul_self_eq (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _)) (norm_nonneg _)] /-- Pythagorean theorem, vector inner product form. -/ lemma norm_add_sq_eq_norm_sq_add_norm_sq_of_inner_eq_zero (x y : E) (h : ⟪x, y⟫ = 0) : ‖x + y‖ * ‖x + y‖ = ‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ := begin rw [norm_add_mul_self, add_right_cancel_iff, add_right_eq_self, mul_eq_zero], apply or.inr, simp only [h, zero_re'], end /-- Pythagorean theorem, vector inner product form. -/ lemma norm_add_sq_eq_norm_sq_add_norm_sq_real {x y : F} (h : ⟪x, y⟫_ℝ = 0) : ‖x + y‖ * ‖x + y‖ = ‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ := (norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero x y).2 h /-- Pythagorean theorem, subtracting vectors, if-and-only-if vector inner product form. -/ lemma norm_sub_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero (x y : F) : ‖x - y‖ * ‖x - y‖ = ‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ ↔ ⟪x, y⟫_ℝ = 0 := begin rw [norm_sub_mul_self, add_right_cancel_iff, sub_eq_add_neg, add_right_eq_self, neg_eq_zero, mul_eq_zero], norm_num end /-- Pythagorean theorem, subtracting vectors, if-and-if vector inner product form using square roots. -/ lemma norm_sub_eq_sqrt_iff_real_inner_eq_zero {x y : F} : ‖x - y‖ = sqrt (‖x‖ * ‖x‖ + ‖y‖ * ‖y‖) ↔ ⟪x, y⟫_ℝ = 0 := by rw [←norm_sub_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero, eq_comm, sqrt_eq_iff_mul_self_eq (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _)) (norm_nonneg _)] /-- Pythagorean theorem, subtracting vectors, vector inner product form. -/ lemma norm_sub_sq_eq_norm_sq_add_norm_sq_real {x y : F} (h : ⟪x, y⟫_ℝ = 0) : ‖x - y‖ * ‖x - y‖ = ‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ := (norm_sub_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero x y).2 h /-- The sum and difference of two vectors are orthogonal if and only if they have the same norm. -/ lemma real_inner_add_sub_eq_zero_iff (x y : F) : ⟪x + y, x - y⟫_ℝ = 0 ↔ ‖x‖ = ‖y‖ := begin conv_rhs { rw ←mul_self_inj_of_nonneg (norm_nonneg _) (norm_nonneg _) }, simp only [←inner_self_eq_norm_mul_norm, inner_add_left, inner_sub_right, real_inner_comm y x, sub_eq_zero, re_to_real], split, { intro h, rw [add_comm] at h, linarith }, { intro h, linarith } end /-- Given two orthogonal vectors, their sum and difference have equal norms. -/ lemma norm_sub_eq_norm_add {v w : E} (h : ⟪v, w⟫ = 0) : ‖w - v‖ = ‖w + v‖ := begin rw ←mul_self_inj_of_nonneg (norm_nonneg _) (norm_nonneg _), simp only [h, ←inner_self_eq_norm_mul_norm, sub_neg_eq_add, sub_zero, map_sub, zero_re', zero_sub, add_zero, map_add, inner_add_right, inner_sub_left, inner_sub_right, inner_re_symm, zero_add] end /-- The real inner product of two vectors, divided by the product of their norms, has absolute value at most 1. -/ lemma abs_real_inner_div_norm_mul_norm_le_one (x y : F) : absR (⟪x, y⟫_ℝ / (‖x‖ * ‖y‖)) ≤ 1 := begin rw _root_.abs_div, by_cases h : 0 = absR (‖x‖ * ‖y‖), { rw [←h, div_zero], norm_num }, { change 0 ≠ absR (‖x‖ * ‖y‖) at h, rw div_le_iff' (lt_of_le_of_ne (ge_iff_le.mp (_root_.abs_nonneg (‖x‖ * ‖y‖))) h), convert abs_real_inner_le_norm x y using 1, rw [_root_.abs_mul, _root_.abs_of_nonneg (norm_nonneg x), _root_.abs_of_nonneg (norm_nonneg y), mul_one] } end /-- The inner product of a vector with a multiple of itself. -/ lemma real_inner_smul_self_left (x : F) (r : ℝ) : ⟪r • x, x⟫_ℝ = r * (‖x‖ * ‖x‖) := by rw [real_inner_smul_left, ←real_inner_self_eq_norm_mul_norm] /-- The inner product of a vector with a multiple of itself. -/ lemma real_inner_smul_self_right (x : F) (r : ℝ) : ⟪x, r • x⟫_ℝ = r * (‖x‖ * ‖x‖) := by rw [inner_smul_right, ←real_inner_self_eq_norm_mul_norm] /-- The inner product of a nonzero vector with a nonzero multiple of itself, divided by the product of their norms, has absolute value 1. -/ lemma abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul {x : E} {r : 𝕜} (hx : x ≠ 0) (hr : r ≠ 0) : abs ⟪x, r • x⟫ / (‖x‖ * ‖r • x‖) = 1 := begin have hx' : ‖x‖ ≠ 0 := by simp [norm_eq_zero, hx], have hr' : abs r ≠ 0 := by simp [is_R_or_C.abs_eq_zero, hr], rw [inner_smul_right, is_R_or_C.abs_mul, ←inner_self_re_abs, inner_self_eq_norm_mul_norm, norm_smul], rw [is_R_or_C.norm_eq_abs, ←mul_assoc, ←div_div, mul_div_cancel _ hx', ←div_div, mul_comm, mul_div_cancel _ hr', div_self hx'], end /-- The inner product of a nonzero vector with a nonzero multiple of itself, divided by the product of their norms, has absolute value 1. -/ lemma abs_real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul {x : F} {r : ℝ} (hx : x ≠ 0) (hr : r ≠ 0) : absR ⟪x, r • x⟫_ℝ / (‖x‖ * ‖r • x‖) = 1 := begin rw ← abs_to_real, exact abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul hx hr end /-- The inner product of a nonzero vector with a positive multiple of itself, divided by the product of their norms, has value 1. -/ lemma real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul {x : F} {r : ℝ} (hx : x ≠ 0) (hr : 0 < r) : ⟪x, r • x⟫_ℝ / (‖x‖ * ‖r • x‖) = 1 := begin rw [real_inner_smul_self_right, norm_smul, real.norm_eq_abs, ←mul_assoc ‖x‖, mul_comm _ (absR r), mul_assoc, _root_.abs_of_nonneg (le_of_lt hr), div_self], exact mul_ne_zero (ne_of_gt hr) (λ h, hx (norm_eq_zero.1 (eq_zero_of_mul_self_eq_zero h))) end /-- The inner product of a nonzero vector with a negative multiple of itself, divided by the product of their norms, has value -1. -/ lemma real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul {x : F} {r : ℝ} (hx : x ≠ 0) (hr : r < 0) : ⟪x, r • x⟫_ℝ / (‖x‖ * ‖r • x‖) = -1 := begin rw [real_inner_smul_self_right, norm_smul, real.norm_eq_abs, ←mul_assoc ‖x‖, mul_comm _ (absR r), mul_assoc, abs_of_neg hr, neg_mul, div_neg_eq_neg_div, div_self], exact mul_ne_zero (ne_of_lt hr) (λ h, hx (norm_eq_zero.1 (eq_zero_of_mul_self_eq_zero h))) end /-- The inner product of two vectors, divided by the product of their norms, has absolute value 1 if and only if they are nonzero and one is a multiple of the other. One form of equality case for Cauchy-Schwarz. -/ lemma abs_inner_div_norm_mul_norm_eq_one_iff (x y : E) : abs (⟪x, y⟫ / (‖x‖ * ‖y‖)) = 1 ↔ (x ≠ 0 ∧ ∃ (r : 𝕜), r ≠ 0 ∧ y = r • x) := begin split, { intro h, have hx0 : x ≠ 0, { intro hx0, rw [hx0, inner_zero_left, zero_div] at h, norm_num at h, }, refine and.intro hx0 _, set r := ⟪x, y⟫ / (‖x‖ * ‖x‖) with hr, use r, set t := y - r • x with ht, have ht0 : ⟪x, t⟫ = 0, { rw [ht, inner_sub_right, inner_smul_right, hr], norm_cast, rw [←inner_self_eq_norm_mul_norm, inner_self_re_to_K, div_mul_cancel _ (λ h, hx0 (inner_self_eq_zero.1 h)), sub_self] }, replace h : ‖r • x‖ / ‖t + r • x‖ = 1, { rw [←sub_add_cancel y (r • x), ←ht, inner_add_right, ht0, zero_add, inner_smul_right, is_R_or_C.abs_div, is_R_or_C.abs_mul, ←inner_self_re_abs, inner_self_eq_norm_mul_norm] at h, norm_cast at h, rwa [_root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm, ←mul_assoc, mul_comm, mul_div_mul_left _ _ (λ h, hx0 (norm_eq_zero.1 h)), ←is_R_or_C.norm_eq_abs, ←norm_smul] at h }, have hr0 : r ≠ 0, { intro hr0, rw [hr0, zero_smul, norm_zero, zero_div] at h, norm_num at h }, refine and.intro hr0 _, have h2 : ‖r • x‖ ^ 2 = ‖t + r • x‖ ^ 2, { rw [eq_of_div_eq_one h] }, replace h2 : ⟪r • x, r • x⟫ = ⟪t, t⟫ + ⟪t, r • x⟫ + ⟪r • x, t⟫ + ⟪r • x, r • x⟫, { rw [sq, sq, ←inner_self_eq_norm_mul_norm, ←inner_self_eq_norm_mul_norm ] at h2, have h2' := congr_arg (λ z : ℝ, (z : 𝕜)) h2, simp_rw [inner_self_re_to_K, inner_add_add_self] at h2', exact h2' }, conv at h2 in ⟪r • x, t⟫ { rw [inner_smul_left, ht0, mul_zero] }, symmetry' at h2, have h₁ : ⟪t, r • x⟫ = 0 := by { rw [inner_smul_right, ←inner_conj_sym, ht0], simp }, rw [add_zero, h₁, add_left_eq_self, add_zero, inner_self_eq_zero] at h2, rw h2 at ht, exact eq_of_sub_eq_zero ht.symm }, { intro h, rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, rw [hy, is_R_or_C.abs_div], norm_cast, rw [_root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm], exact abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul hx hr } end /-- The inner product of two vectors, divided by the product of their norms, has absolute value 1 if and only if they are nonzero and one is a multiple of the other. One form of equality case for Cauchy-Schwarz. -/ lemma abs_real_inner_div_norm_mul_norm_eq_one_iff (x y : F) : absR (⟪x, y⟫_ℝ / (‖x‖ * ‖y‖)) = 1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r ≠ 0 ∧ y = r • x) := begin have := @abs_inner_div_norm_mul_norm_eq_one_iff ℝ F _ _ x y, simpa [coe_real_eq_id] using this, end /-- If the inner product of two vectors is equal to the product of their norms, then the two vectors are multiples of each other. One form of the equality case for Cauchy-Schwarz. Compare `inner_eq_norm_mul_iff`, which takes the stronger hypothesis `⟪x, y⟫ = ‖x‖ * ‖y‖`. -/ lemma abs_inner_eq_norm_iff (x y : E) (hx0 : x ≠ 0) (hy0 : y ≠ 0): abs ⟪x, y⟫ = ‖x‖ * ‖y‖ ↔ ∃ (r : 𝕜), r ≠ 0 ∧ y = r • x := begin have hxy0 : ‖x‖ * ‖y‖ ≠ 0 := mul_ne_zero (norm_eq_zero.not.2 hx0) (norm_eq_zero.not.2 hy0), have h₁ : abs ⟪x, y⟫ = ‖x‖ * ‖y‖ ↔ abs (⟪x, y⟫ / (‖x‖ * ‖y‖)) = 1, { rw [←algebra_map.coe_mul, is_R_or_C.abs_div, is_R_or_C.abs_of_nonneg, div_eq_one_iff_eq hxy0], positivity }, rw [h₁, abs_inner_div_norm_mul_norm_eq_one_iff x y], exact and_iff_right hx0, end /-- The inner product of two vectors, divided by the product of their norms, has value 1 if and only if they are nonzero and one is a positive multiple of the other. -/ lemma real_inner_div_norm_mul_norm_eq_one_iff (x y : F) : ⟪x, y⟫_ℝ / (‖x‖ * ‖y‖) = 1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), 0 < r ∧ y = r • x) := begin split, { intro h, have ha := h, apply_fun absR at ha, norm_num at ha, rcases (abs_real_inner_div_norm_mul_norm_eq_one_iff x y).1 ha with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, use [hx, r], refine and.intro _ hy, by_contradiction hrneg, rw hy at h, rw real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul hx (lt_of_le_of_ne (le_of_not_lt hrneg) hr) at h, norm_num at h }, { intro h, rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, rw hy, exact real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul hx hr } end /-- The inner product of two vectors, divided by the product of their norms, has value -1 if and only if they are nonzero and one is a negative multiple of the other. -/ lemma real_inner_div_norm_mul_norm_eq_neg_one_iff (x y : F) : ⟪x, y⟫_ℝ / (‖x‖ * ‖y‖) = -1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r < 0 ∧ y = r • x) := begin split, { intro h, have ha := h, apply_fun absR at ha, norm_num at ha, rcases (abs_real_inner_div_norm_mul_norm_eq_one_iff x y).1 ha with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, use [hx, r], refine and.intro _ hy, by_contradiction hrpos, rw hy at h, rw real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul hx (lt_of_le_of_ne (le_of_not_lt hrpos) hr.symm) at h, norm_num at h }, { intro h, rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, rw hy, exact real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul hx hr } end /-- If the inner product of two vectors is equal to the product of their norms (i.e., `⟪x, y⟫ = ‖x‖ * ‖y‖`), then the two vectors are nonnegative real multiples of each other. One form of the equality case for Cauchy-Schwarz. Compare `abs_inner_eq_norm_iff`, which takes the weaker hypothesis `abs ⟪x, y⟫ = ‖x‖ * ‖y‖`. -/ lemma inner_eq_norm_mul_iff {x y : E} : ⟪x, y⟫ = (‖x‖ : 𝕜) * ‖y‖ ↔ (‖y‖ : 𝕜) • x = (‖x‖ : 𝕜) • y := begin by_cases h : (x = 0 ∨ y = 0), -- WLOG `x` and `y` are nonzero { cases h; simp [h] }, calc ⟪x, y⟫ = (‖x‖ : 𝕜) * ‖y‖ ↔ ‖x‖ * ‖y‖ = re ⟪x, y⟫ : begin norm_cast, split, { intros h', simp [h'] }, { have cauchy_schwarz := abs_inner_le_norm x y, intros h', rw h' at ⊢ cauchy_schwarz, rwa re_eq_self_of_le } end ... ↔ 2 * ‖x‖ * ‖y‖ * (‖x‖ * ‖y‖ - re ⟪x, y⟫) = 0 : by simp [h, show (2:ℝ) ≠ 0, by norm_num, sub_eq_zero] ... ↔ ‖(‖y‖:𝕜) • x - (‖x‖:𝕜) • y‖ * ‖(‖y‖:𝕜) • x - (‖x‖:𝕜) • y‖ = 0 : begin simp only [norm_sub_mul_self, inner_smul_left, inner_smul_right, norm_smul, conj_of_real, is_R_or_C.norm_eq_abs, abs_of_real, of_real_im, of_real_re, mul_re, abs_norm_eq_norm], refine eq.congr _ rfl, ring end ... ↔ (‖y‖ : 𝕜) • x = (‖x‖ : 𝕜) • y : by simp [norm_sub_eq_zero_iff] end /-- If the inner product of two vectors is equal to the product of their norms (i.e., `⟪x, y⟫ = ‖x‖ * ‖y‖`), then the two vectors are nonnegative real multiples of each other. One form of the equality case for Cauchy-Schwarz. Compare `abs_inner_eq_norm_iff`, which takes the weaker hypothesis `abs ⟪x, y⟫ = ‖x‖ * ‖y‖`. -/ lemma inner_eq_norm_mul_iff_real {x y : F} : ⟪x, y⟫_ℝ = ‖x‖ * ‖y‖ ↔ ‖y‖ • x = ‖x‖ • y := inner_eq_norm_mul_iff /-- If the inner product of two unit vectors is `1`, then the two vectors are equal. One form of the equality case for Cauchy-Schwarz. -/ lemma inner_eq_norm_mul_iff_of_norm_one {x y : E} (hx : ‖x‖ = 1) (hy : ‖y‖ = 1) : ⟪x, y⟫ = 1 ↔ x = y := by { convert inner_eq_norm_mul_iff using 2; simp [hx, hy] } lemma inner_lt_norm_mul_iff_real {x y : F} : ⟪x, y⟫_ℝ < ‖x‖ * ‖y‖ ↔ ‖y‖ • x ≠ ‖x‖ • y := calc ⟪x, y⟫_ℝ < ‖x‖ * ‖y‖ ↔ ⟪x, y⟫_ℝ ≠ ‖x‖ * ‖y‖ : ⟨ne_of_lt, lt_of_le_of_ne (real_inner_le_norm _ _)⟩ ... ↔ ‖y‖ • x ≠ ‖x‖ • y : not_congr inner_eq_norm_mul_iff_real /-- If the inner product of two unit vectors is strictly less than `1`, then the two vectors are distinct. One form of the equality case for Cauchy-Schwarz. -/ lemma inner_lt_one_iff_real_of_norm_one {x y : F} (hx : ‖x‖ = 1) (hy : ‖y‖ = 1) : ⟪x, y⟫_ℝ < 1 ↔ x ≠ y := by { convert inner_lt_norm_mul_iff_real; simp [hx, hy] } /-- The inner product of two weighted sums, where the weights in each sum add to 0, in terms of the norms of pairwise differences. -/ lemma inner_sum_smul_sum_smul_of_sum_eq_zero {ι₁ : Type*} {s₁ : finset ι₁} {w₁ : ι₁ → ℝ} (v₁ : ι₁ → F) (h₁ : ∑ i in s₁, w₁ i = 0) {ι₂ : Type*} {s₂ : finset ι₂} {w₂ : ι₂ → ℝ} (v₂ : ι₂ → F) (h₂ : ∑ i in s₂, w₂ i = 0) : ⟪(∑ i₁ in s₁, w₁ i₁ • v₁ i₁), (∑ i₂ in s₂, w₂ i₂ • v₂ i₂)⟫_ℝ = (-∑ i₁ in s₁, ∑ i₂ in s₂, w₁ i₁ * w₂ i₂ * (‖v₁ i₁ - v₂ i₂‖ * ‖v₁ i₁ - v₂ i₂‖)) / 2 := by simp_rw [sum_inner, inner_sum, real_inner_smul_left, real_inner_smul_right, real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two, ←div_sub_div_same, ←div_add_div_same, mul_sub_left_distrib, left_distrib, finset.sum_sub_distrib, finset.sum_add_distrib, ←finset.mul_sum, ←finset.sum_mul, h₁, h₂, zero_mul, mul_zero, finset.sum_const_zero, zero_add, zero_sub, finset.mul_sum, neg_div, finset.sum_div, mul_div_assoc, mul_assoc] /-- The inner product as a sesquilinear map. -/ def innerₛₗ : E →ₗ⋆[𝕜] E →ₗ[𝕜] 𝕜 := linear_map.mk₂'ₛₗ _ _ (λ v w, ⟪v, w⟫) (λ _ _ _, inner_add_left) (λ _ _ _, inner_smul_left) (λ _ _ _, inner_add_right) (λ _ _ _, inner_smul_right) @[simp] lemma innerₛₗ_apply_coe (v : E) : (innerₛₗ v : E → 𝕜) = λ w, ⟪v, w⟫ := rfl @[simp] lemma innerₛₗ_apply (v w : E) : innerₛₗ v w = ⟪v, w⟫ := rfl /-- The inner product as a continuous sesquilinear map. Note that `to_dual_map` (resp. `to_dual`) in `inner_product_space.dual` is a version of this given as a linear isometry (resp. linear isometric equivalence). -/ def innerSL : E →L⋆[𝕜] E →L[𝕜] 𝕜 := linear_map.mk_continuous₂ innerₛₗ 1 (λ x y, by simp only [norm_inner_le_norm, one_mul, innerₛₗ_apply]) @[simp] lemma innerSL_apply_coe (v : E) : (innerSL v : E → 𝕜) = λ w, ⟪v, w⟫ := rfl @[simp] lemma innerSL_apply (v w : E) : innerSL v w = ⟪v, w⟫ := rfl /-- `innerSL` is an isometry. Note that the associated `linear_isometry` is defined in `inner_product_space.dual` as `to_dual_map`. -/ @[simp] lemma innerSL_apply_norm {x : E} : ‖(innerSL x : E →L[𝕜] 𝕜)‖ = ‖x‖ := begin refine le_antisymm ((innerSL x : E →L[𝕜] 𝕜).op_norm_le_bound (norm_nonneg _) (λ y, norm_inner_le_norm _ _)) _, cases eq_or_lt_of_le (norm_nonneg x) with h h, { have : x = 0 := norm_eq_zero.mp (eq.symm h), simp [this] }, { refine (mul_le_mul_right h).mp _, calc ‖x‖ * ‖x‖ = ‖x‖ ^ 2 : by ring ... = re ⟪x, x⟫ : norm_sq_eq_inner _ ... ≤ abs ⟪x, x⟫ : re_le_abs _ ... = ‖innerSL x x‖ : by { rw [←is_R_or_C.norm_eq_abs], refl } ... ≤ ‖innerSL x‖ * ‖x‖ : (innerSL x : E →L[𝕜] 𝕜).le_op_norm _ } end /-- The inner product as a continuous sesquilinear map, with the two arguments flipped. -/ def innerSL_flip : E →L[𝕜] E →L⋆[𝕜] 𝕜 := @continuous_linear_map.flipₗᵢ' 𝕜 𝕜 𝕜 E E 𝕜 _ _ _ _ _ _ _ _ _ (ring_hom.id 𝕜) (star_ring_end 𝕜) _ _ innerSL @[simp] lemma innerSL_flip_apply {x y : E} : innerSL_flip x y = ⟪y, x⟫ := rfl namespace continuous_linear_map variables {E' : Type*} [inner_product_space 𝕜 E'] /-- Given `f : E →L[𝕜] E'`, construct the continuous sesquilinear form `λ x y, ⟪x, A y⟫`, given as a continuous linear map. -/ def to_sesq_form : (E →L[𝕜] E') →L[𝕜] E' →L⋆[𝕜] E →L[𝕜] 𝕜 := ↑((continuous_linear_map.flipₗᵢ' E E' 𝕜 (star_ring_end 𝕜) (ring_hom.id 𝕜)).to_continuous_linear_equiv) ∘L (continuous_linear_map.compSL E E' (E' →L⋆[𝕜] 𝕜) (ring_hom.id 𝕜) (ring_hom.id 𝕜) innerSL_flip) @[simp] lemma to_sesq_form_apply_coe (f : E →L[𝕜] E') (x : E') : to_sesq_form f x = (innerSL x).comp f := rfl lemma to_sesq_form_apply_norm_le {f : E →L[𝕜] E'} {v : E'} : ‖to_sesq_form f v‖ ≤ ‖f‖ * ‖v‖ := begin refine op_norm_le_bound _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) _, intro x, have h₁ : ‖f x‖ ≤ ‖f‖ * ‖x‖ := le_op_norm _ _, have h₂ := @norm_inner_le_norm 𝕜 E' _ _ v (f x), calc ‖⟪v, f x⟫‖ ≤ ‖v‖ * ‖f x‖ : h₂ ... ≤ ‖v‖ * (‖f‖ * ‖x‖) : mul_le_mul_of_nonneg_left h₁ (norm_nonneg v) ... = ‖f‖ * ‖v‖ * ‖x‖ : by ring, end end continuous_linear_map /-- When an inner product space `E` over `𝕜` is considered as a real normed space, its inner product satisfies `is_bounded_bilinear_map`. In order to state these results, we need a `normed_space ℝ E` instance. We will later establish such an instance by restriction-of-scalars, `inner_product_space.is_R_or_C_to_real 𝕜 E`, but this instance may be not definitionally equal to some other “natural” instance. So, we assume `[normed_space ℝ E]`. -/ lemma is_bounded_bilinear_map_inner [normed_space ℝ E] : is_bounded_bilinear_map ℝ (λ p : E × E, ⟪p.1, p.2⟫) := { add_left := λ _ _ _, inner_add_left, smul_left := λ r x y, by simp only [← algebra_map_smul 𝕜 r x, algebra_map_eq_of_real, inner_smul_real_left], add_right := λ _ _ _, inner_add_right, smul_right := λ r x y, by simp only [← algebra_map_smul 𝕜 r y, algebra_map_eq_of_real, inner_smul_real_right], bound := ⟨1, zero_lt_one, λ x y, by { rw [one_mul], exact norm_inner_le_norm x y, }⟩ } end norm section bessels_inequality variables {ι: Type*} (x : E) {v : ι → E} /-- Bessel's inequality for finite sums. -/ lemma orthonormal.sum_inner_products_le {s : finset ι} (hv : orthonormal 𝕜 v) : ∑ i in s, ‖⟪v i, x⟫‖ ^ 2 ≤ ‖x‖ ^ 2 := begin have h₂ : ∑ i in s, ∑ j in s, ⟪v i, x⟫ * ⟪x, v j⟫ * ⟪v j, v i⟫ = (∑ k in s, (⟪v k, x⟫ * ⟪x, v k⟫) : 𝕜), { exact hv.inner_left_right_finset }, have h₃ : ∀ z : 𝕜, re (z * conj (z)) = ‖z‖ ^ 2, { intro z, simp only [mul_conj, norm_sq_eq_def'], norm_cast, }, suffices hbf: ‖x - ∑ i in s, ⟪v i, x⟫ • (v i)‖ ^ 2 = ‖x‖ ^ 2 - ∑ i in s, ‖⟪v i, x⟫‖ ^ 2, { rw [←sub_nonneg, ←hbf], simp only [norm_nonneg, pow_nonneg], }, rw [norm_sub_sq, sub_add], simp only [inner_product_space.norm_sq_eq_inner, inner_sum], simp only [sum_inner, two_mul, inner_smul_right, inner_conj_sym, ←mul_assoc, h₂, ←h₃, inner_conj_sym, add_monoid_hom.map_sum, finset.mul_sum, ←finset.sum_sub_distrib, inner_smul_left, add_sub_cancel'], end /-- Bessel's inequality. -/ lemma orthonormal.tsum_inner_products_le (hv : orthonormal 𝕜 v) : ∑' i, ‖⟪v i, x⟫‖ ^ 2 ≤ ‖x‖ ^ 2 := begin refine tsum_le_of_sum_le' _ (λ s, hv.sum_inner_products_le x), simp only [norm_nonneg, pow_nonneg] end /-- The sum defined in Bessel's inequality is summable. -/ lemma orthonormal.inner_products_summable (hv : orthonormal 𝕜 v) : summable (λ i, ‖⟪v i, x⟫‖ ^ 2) := begin use ⨆ s : finset ι, ∑ i in s, ‖⟪v i, x⟫‖ ^ 2, apply has_sum_of_is_lub_of_nonneg, { intro b, simp only [norm_nonneg, pow_nonneg], }, { refine is_lub_csupr _, use ‖x‖ ^ 2, rintro y ⟨s, rfl⟩, exact hv.sum_inner_products_le x } end end bessels_inequality /-- A field `𝕜` satisfying `is_R_or_C` is itself a `𝕜`-inner product space. -/ instance is_R_or_C.inner_product_space : inner_product_space 𝕜 𝕜 := { to_normed_add_comm_group := non_unital_normed_ring.to_normed_add_comm_group, inner := λ x y, conj x * y, norm_sq_eq_inner := λ x, by { unfold inner, rw [mul_comm, mul_conj, of_real_re, norm_sq_eq_def'] }, conj_sym := λ x y, by simp only [mul_comm, map_mul, star_ring_end_self_apply], add_left := λ x y z, by simp only [add_mul, map_add], smul_left := λ x y z, by simp only [mul_assoc, smul_eq_mul, map_mul] } @[simp] lemma is_R_or_C.inner_apply (x y : 𝕜) : ⟪x, y⟫ = (conj x) * y := rfl /-! ### Inner product space structure on subspaces -/ /-- Induced inner product on a submodule. -/ instance submodule.inner_product_space (W : submodule 𝕜 E) : inner_product_space 𝕜 W := { to_normed_add_comm_group := submodule.normed_add_comm_group _, inner := λ x y, ⟪(x:E), (y:E)⟫, conj_sym := λ _ _, inner_conj_sym _ _ , norm_sq_eq_inner := λ _, norm_sq_eq_inner _, add_left := λ _ _ _ , inner_add_left, smul_left := λ _ _ _, inner_smul_left, ..submodule.normed_space W } /-- The inner product on submodules is the same as on the ambient space. -/ @[simp] lemma submodule.coe_inner (W : submodule 𝕜 E) (x y : W) : ⟪x, y⟫ = ⟪(x:E), ↑y⟫ := rfl lemma orthonormal.cod_restrict {ι : Type*} {v : ι → E} (hv : orthonormal 𝕜 v) (s : submodule 𝕜 E) (hvs : ∀ i, v i ∈ s) : @orthonormal 𝕜 s _ _ ι (set.cod_restrict v s hvs) := s.subtypeₗᵢ.orthonormal_comp_iff.mp hv lemma orthonormal_span {ι : Type*} {v : ι → E} (hv : orthonormal 𝕜 v) : @orthonormal 𝕜 (submodule.span 𝕜 (set.range v)) _ _ ι (λ i : ι, ⟨v i, submodule.subset_span (set.mem_range_self i)⟩) := hv.cod_restrict (submodule.span 𝕜 (set.range v)) (λ i, submodule.subset_span (set.mem_range_self i)) /-! ### Families of mutually-orthogonal subspaces of an inner product space -/ section orthogonal_family variables {ι : Type*} [dec_ι : decidable_eq ι] (𝕜) open_locale direct_sum /-- An indexed family of mutually-orthogonal subspaces of an inner product space `E`. The simple way to express this concept would be as a condition on `V : ι → submodule 𝕜 E`. We We instead implement it as a condition on a family of inner product spaces each equipped with an isometric embedding into `E`, thus making it a property of morphisms rather than subobjects. This definition is less lightweight, but allows for better definitional properties when the inner product space structure on each of the submodules is important -- for example, when considering their Hilbert sum (`pi_lp V 2`). For example, given an orthonormal set of vectors `v : ι → E`, we have an associated orthogonal family of one-dimensional subspaces of `E`, which it is convenient to be able to discuss using `ι → 𝕜` rather than `Π i : ι, span 𝕜 (v i)`. -/ def orthogonal_family {G : ι → Type*} [Π i, inner_product_space 𝕜 (G i)] (V : Π i, G i →ₗᵢ[𝕜] E) : Prop := ∀ ⦃i j⦄, i ≠ j → ∀ v : G i, ∀ w : G j, ⟪V i v, V j w⟫ = 0 variables {𝕜} {G : ι → Type*} [Π i, inner_product_space 𝕜 (G i)] {V : Π i, G i →ₗᵢ[𝕜] E} (hV : orthogonal_family 𝕜 V) [dec_V : Π i (x : G i), decidable (x ≠ 0)] lemma orthonormal.orthogonal_family {v : ι → E} (hv : orthonormal 𝕜 v) : @orthogonal_family 𝕜 _ _ _ _ (λ i : ι, 𝕜) _ (λ i, linear_isometry.to_span_singleton 𝕜 E (hv.1 i)) := λ i j hij a b, by simp [inner_smul_left, inner_smul_right, hv.2 hij] include hV dec_ι lemma orthogonal_family.eq_ite {i j : ι} (v : G i) (w : G j) : ⟪V i v, V j w⟫ = ite (i = j) ⟪V i v, V j w⟫ 0 := begin split_ifs, { refl }, { exact hV h v w } end include dec_V lemma orthogonal_family.inner_right_dfinsupp (l : ⨁ i, G i) (i : ι) (v : G i) : ⟪V i v, l.sum (λ j, V j)⟫ = ⟪v, l i⟫ := calc ⟪V i v, l.sum (λ j, V j)⟫ = l.sum (λ j, λ w, ⟪V i v, V j w⟫) : dfinsupp.inner_sum (λ j, V j) l (V i v) ... = l.sum (λ j, λ w, ite (i=j) ⟪V i v, V j w⟫ 0) : congr_arg l.sum $ funext $ λ j, funext $ hV.eq_ite v ... = ⟪v, l i⟫ : begin simp only [dfinsupp.sum, submodule.coe_inner, finset.sum_ite_eq, ite_eq_left_iff, dfinsupp.mem_support_to_fun], split_ifs with h h, { simp only [linear_isometry.inner_map_map] }, { simp only [of_not_not h, inner_zero_right] }, end omit dec_ι dec_V lemma orthogonal_family.inner_right_fintype [fintype ι] (l : Π i, G i) (i : ι) (v : G i) : ⟪V i v, ∑ j : ι, V j (l j)⟫ = ⟪v, l i⟫ := by classical; calc ⟪V i v, ∑ j : ι, V j (l j)⟫ = ∑ j : ι, ⟪V i v, V j (l j)⟫: by rw inner_sum ... = ∑ j, ite (i = j) ⟪V i v, V j (l j)⟫ 0 : congr_arg (finset.sum finset.univ) $ funext $ λ j, (hV.eq_ite v (l j)) ... = ⟪v, l i⟫ : by simp only [finset.sum_ite_eq, finset.mem_univ, (V i).inner_map_map, if_true] lemma orthogonal_family.inner_sum (l₁ l₂ : Π i, G i) (s : finset ι) : ⟪∑ i in s, V i (l₁ i), ∑ j in s, V j (l₂ j)⟫ = ∑ i in s, ⟪l₁ i, l₂ i⟫ := by classical; calc ⟪∑ i in s, V i (l₁ i), ∑ j in s, V j (l₂ j)⟫ = ∑ j in s, ∑ i in s, ⟪V i (l₁ i), V j (l₂ j)⟫ : by simp only [sum_inner, inner_sum] ... = ∑ j in s, ∑ i in s, ite (i = j) ⟪V i (l₁ i), V j (l₂ j)⟫ 0 : begin congr' with i, congr' with j, apply hV.eq_ite, end ... = ∑ i in s, ⟪l₁ i, l₂ i⟫ : by simp only [finset.sum_ite_of_true, finset.sum_ite_eq', linear_isometry.inner_map_map, imp_self, implies_true_iff] lemma orthogonal_family.norm_sum (l : Π i, G i) (s : finset ι) : ‖∑ i in s, V i (l i)‖ ^ 2 = ∑ i in s, ‖l i‖ ^ 2 := begin have : (‖∑ i in s, V i (l i)‖ ^ 2 : 𝕜) = ∑ i in s, ‖l i‖ ^ 2, { simp only [← inner_self_eq_norm_sq_to_K, hV.inner_sum] }, exact_mod_cast this, end /-- The composition of an orthogonal family of subspaces with an injective function is also an orthogonal family. -/ lemma orthogonal_family.comp {γ : Type*} {f : γ → ι} (hf : function.injective f) : orthogonal_family 𝕜 (λ g : γ, (V (f g) : G (f g) →ₗᵢ[𝕜] E)) := λ i j hij v w, hV (hf.ne hij) v w lemma orthogonal_family.orthonormal_sigma_orthonormal {α : ι → Type*} {v_family : Π i, (α i) → G i} (hv_family : ∀ i, orthonormal 𝕜 (v_family i)) : orthonormal 𝕜 (λ a : Σ i, α i, V a.1 (v_family a.1 a.2)) := begin split, { rintros ⟨i, v⟩, simpa only [linear_isometry.norm_map] using (hv_family i).left v }, rintros ⟨i, v⟩ ⟨j, w⟩ hvw, by_cases hij : i = j, { subst hij, have : v ≠ w := λ h, by { subst h, exact hvw rfl }, simpa only [linear_isometry.inner_map_map] using (hv_family i).2 this }, { exact hV hij (v_family i v) (v_family j w) } end include dec_ι lemma orthogonal_family.norm_sq_diff_sum (f : Π i, G i) (s₁ s₂ : finset ι) : ‖∑ i in s₁, V i (f i) - ∑ i in s₂, V i (f i)‖ ^ 2 = ∑ i in s₁ \ s₂, ‖f i‖ ^ 2 + ∑ i in s₂ \ s₁, ‖f i‖ ^ 2 := begin rw [← finset.sum_sdiff_sub_sum_sdiff, sub_eq_add_neg, ← finset.sum_neg_distrib], let F : Π i, G i := λ i, if i ∈ s₁ then f i else - (f i), have hF₁ : ∀ i ∈ s₁ \ s₂, F i = f i := λ i hi, if_pos (finset.sdiff_subset _ _ hi), have hF₂ : ∀ i ∈ s₂ \ s₁, F i = - f i := λ i hi, if_neg (finset.mem_sdiff.mp hi).2, have hF : ∀ i, ‖F i‖ = ‖f i‖, { intros i, dsimp only [F], split_ifs; simp only [eq_self_iff_true, norm_neg], }, have : ‖∑ i in s₁ \ s₂, V i (F i) + ∑ i in s₂ \ s₁, V i (F i)‖ ^ 2 = ∑ i in s₁ \ s₂, ‖F i‖ ^ 2 + ∑ i in s₂ \ s₁, ‖F i‖ ^ 2, { have hs : disjoint (s₁ \ s₂) (s₂ \ s₁) := disjoint_sdiff_sdiff, simpa only [finset.sum_union hs] using hV.norm_sum F (s₁ \ s₂ ∪ s₂ \ s₁) }, convert this using 4, { refine finset.sum_congr rfl (λ i hi, _), simp only [hF₁ i hi] }, { refine finset.sum_congr rfl (λ i hi, _), simp only [hF₂ i hi, linear_isometry.map_neg] }, { simp only [hF] }, { simp only [hF] }, end omit dec_ι /-- A family `f` of mutually-orthogonal elements of `E` is summable, if and only if `(λ i, ‖f i‖ ^ 2)` is summable. -/ lemma orthogonal_family.summable_iff_norm_sq_summable [complete_space E] (f : Π i, G i) : summable (λ i, V i (f i)) ↔ summable (λ i, ‖f i‖ ^ 2) := begin classical, simp only [summable_iff_cauchy_seq_finset, normed_add_comm_group.cauchy_seq_iff, real.norm_eq_abs], split, { intros hf ε hε, obtain ⟨a, H⟩ := hf _ (sqrt_pos.mpr hε), use a, intros s₁ hs₁ s₂ hs₂, rw ← finset.sum_sdiff_sub_sum_sdiff, refine (_root_.abs_sub _ _).trans_lt _, have : ∀ i, 0 ≤ ‖f i‖ ^ 2 := λ i : ι, sq_nonneg _, simp only [finset.abs_sum_of_nonneg' this], have : ∑ i in s₁ \ s₂, ‖f i‖ ^ 2 + ∑ i in s₂ \ s₁, ‖f i‖ ^ 2 < (sqrt ε) ^ 2, { rw [← hV.norm_sq_diff_sum, sq_lt_sq, _root_.abs_of_nonneg (sqrt_nonneg _), _root_.abs_of_nonneg (norm_nonneg _)], exact H s₁ hs₁ s₂ hs₂ }, have hη := sq_sqrt (le_of_lt hε), linarith }, { intros hf ε hε, have hε' : 0 < ε ^ 2 / 2 := half_pos (sq_pos_of_pos hε), obtain ⟨a, H⟩ := hf _ hε', use a, intros s₁ hs₁ s₂ hs₂, refine (abs_lt_of_sq_lt_sq' _ (le_of_lt hε)).2, have has : a ≤ s₁ ⊓ s₂ := le_inf hs₁ hs₂, rw hV.norm_sq_diff_sum, have Hs₁ : ∑ (x : ι) in s₁ \ s₂, ‖f x‖ ^ 2 < ε ^ 2 / 2, { convert H _ hs₁ _ has, have : s₁ ⊓ s₂ ⊆ s₁ := finset.inter_subset_left _ _, rw [← finset.sum_sdiff this, add_tsub_cancel_right, finset.abs_sum_of_nonneg'], { simp }, { exact λ i, sq_nonneg _ } }, have Hs₂ : ∑ (x : ι) in s₂ \ s₁, ‖f x‖ ^ 2 < ε ^ 2 /2, { convert H _ hs₂ _ has, have : s₁ ⊓ s₂ ⊆ s₂ := finset.inter_subset_right _ _, rw [← finset.sum_sdiff this, add_tsub_cancel_right, finset.abs_sum_of_nonneg'], { simp }, { exact λ i, sq_nonneg _ } }, linarith }, end omit hV /-- An orthogonal family forms an independent family of subspaces; that is, any collection of elements each from a different subspace in the family is linearly independent. In particular, the pairwise intersections of elements of the family are 0. -/ lemma orthogonal_family.independent {V : ι → submodule 𝕜 E} (hV : @orthogonal_family 𝕜 _ _ _ _ (λ i, V i) _ (λ i, (V i).subtypeₗᵢ)) : complete_lattice.independent V := begin classical, apply complete_lattice.independent_of_dfinsupp_lsum_injective, rw [← @linear_map.ker_eq_bot _ _ _ _ _ _ (direct_sum.add_comm_group (λ i, V i)), submodule.eq_bot_iff], intros v hv, rw linear_map.mem_ker at hv, ext i, suffices : ⟪(v i : E), v i⟫ = 0, { simpa only [inner_self_eq_zero] using this }, calc ⟪(v i : E), v i⟫ = ⟪(v i : E), dfinsupp.lsum ℕ (λ i, (V i).subtype) v⟫ : by simpa only [dfinsupp.sum_add_hom_apply, dfinsupp.lsum_apply_apply] using (hV.inner_right_dfinsupp v i (v i)).symm ... = 0 : by simp only [hv, inner_zero_right], end include dec_ι lemma direct_sum.is_internal.collected_basis_orthonormal {V : ι → submodule 𝕜 E} (hV : @orthogonal_family 𝕜 _ _ _ _ (λ i, V i) _ (λ i, (V i).subtypeₗᵢ)) (hV_sum : direct_sum.is_internal (λ i, V i)) {α : ι → Type*} {v_family : Π i, basis (α i) 𝕜 (V i)} (hv_family : ∀ i, orthonormal 𝕜 (v_family i)) : orthonormal 𝕜 (hV_sum.collected_basis v_family) := by simpa only [hV_sum.collected_basis_coe] using hV.orthonormal_sigma_orthonormal hv_family end orthogonal_family section is_R_or_C_to_real variables {G : Type*} variables (𝕜 E) include 𝕜 /-- A general inner product implies a real inner product. This is not registered as an instance since it creates problems with the case `𝕜 = ℝ`. -/ def has_inner.is_R_or_C_to_real : has_inner ℝ E := { inner := λ x y, re ⟪x, y⟫ } /-- A general inner product space structure implies a real inner product structure. This is not registered as an instance since it creates problems with the case `𝕜 = ℝ`, but in can be used in a proof to obtain a real inner product space structure from a given `𝕜`-inner product space structure. -/ def inner_product_space.is_R_or_C_to_real : inner_product_space ℝ E := { to_normed_add_comm_group := inner_product_space.to_normed_add_comm_group 𝕜, norm_sq_eq_inner := norm_sq_eq_inner, conj_sym := λ x y, inner_re_symm, add_left := λ x y z, by { change re ⟪x + y, z⟫ = re ⟪x, z⟫ + re ⟪y, z⟫, simp only [inner_add_left, map_add] }, smul_left := λ x y r, by { change re ⟪(r : 𝕜) • x, y⟫ = r * re ⟪x, y⟫, simp only [inner_smul_left, conj_of_real, of_real_mul_re] }, ..has_inner.is_R_or_C_to_real 𝕜 E, ..normed_space.restrict_scalars ℝ 𝕜 E } variable {E} lemma real_inner_eq_re_inner (x y : E) : @has_inner.inner ℝ E (has_inner.is_R_or_C_to_real 𝕜 E) x y = re ⟪x, y⟫ := rfl lemma real_inner_I_smul_self (x : E) : @has_inner.inner ℝ E (has_inner.is_R_or_C_to_real 𝕜 E) x ((I : 𝕜) • x) = 0 := by simp [real_inner_eq_re_inner, inner_smul_right] omit 𝕜 /-- A complex inner product implies a real inner product -/ instance inner_product_space.complex_to_real [inner_product_space ℂ G] : inner_product_space ℝ G := inner_product_space.is_R_or_C_to_real ℂ G @[simp] protected lemma complex.inner (w z : ℂ) : ⟪w, z⟫_ℝ = (conj w * z).re := rfl /-- The inner product on an inner product space of dimension 2 can be evaluated in terms of a complex-number representation of the space. -/ lemma inner_map_complex [inner_product_space ℝ G] (f : G ≃ₗᵢ[ℝ] ℂ) (x y : G) : ⟪x, y⟫_ℝ = (conj (f x) * f y).re := by rw [← complex.inner, f.inner_map_map] end is_R_or_C_to_real section continuous /-! ### Continuity of the inner product -/ lemma continuous_inner : continuous (λ p : E × E, ⟪p.1, p.2⟫) := begin letI : inner_product_space ℝ E := inner_product_space.is_R_or_C_to_real 𝕜 E, exact is_bounded_bilinear_map_inner.continuous end variables {α : Type*} lemma filter.tendsto.inner {f g : α → E} {l : filter α} {x y : E} (hf : tendsto f l (𝓝 x)) (hg : tendsto g l (𝓝 y)) : tendsto (λ t, ⟪f t, g t⟫) l (𝓝 ⟪x, y⟫) := (continuous_inner.tendsto _).comp (hf.prod_mk_nhds hg) variables [topological_space α] {f g : α → E} {x : α} {s : set α} include 𝕜 lemma continuous_within_at.inner (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (λ t, ⟪f t, g t⟫) s x := hf.inner hg lemma continuous_at.inner (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λ t, ⟪f t, g t⟫) x := hf.inner hg lemma continuous_on.inner (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λ t, ⟪f t, g t⟫) s := λ x hx, (hf x hx).inner (hg x hx) @[continuity] lemma continuous.inner (hf : continuous f) (hg : continuous g) : continuous (λ t, ⟪f t, g t⟫) := continuous_iff_continuous_at.2 $ λ x, hf.continuous_at.inner hg.continuous_at end continuous section re_apply_inner_self /-- Extract a real bilinear form from an operator `T`, by taking the pairing `λ x, re ⟪T x, x⟫`. -/ def continuous_linear_map.re_apply_inner_self (T : E →L[𝕜] E) (x : E) : ℝ := re ⟪T x, x⟫ lemma continuous_linear_map.re_apply_inner_self_apply (T : E →L[𝕜] E) (x : E) : T.re_apply_inner_self x = re ⟪T x, x⟫ := rfl lemma continuous_linear_map.re_apply_inner_self_continuous (T : E →L[𝕜] E) : continuous T.re_apply_inner_self := re_clm.continuous.comp $ T.continuous.inner continuous_id lemma continuous_linear_map.re_apply_inner_self_smul (T : E →L[𝕜] E) (x : E) {c : 𝕜} : T.re_apply_inner_self (c • x) = ‖c‖ ^ 2 * T.re_apply_inner_self x := by simp only [continuous_linear_map.map_smul, continuous_linear_map.re_apply_inner_self_apply, inner_smul_left, inner_smul_right, ← mul_assoc, mul_conj, norm_sq_eq_def', ← smul_re, algebra.smul_def (‖c‖ ^ 2) ⟪T x, x⟫, algebra_map_eq_of_real] end re_apply_inner_self /-! ### The orthogonal complement -/ section orthogonal variables (K : submodule 𝕜 E) /-- The subspace of vectors orthogonal to a given subspace. -/ def submodule.orthogonal : submodule 𝕜 E := { carrier := {v | ∀ u ∈ K, ⟪u, v⟫ = 0}, zero_mem' := λ _ _, inner_zero_right, add_mem' := λ x y hx hy u hu, by rw [inner_add_right, hx u hu, hy u hu, add_zero], smul_mem' := λ c x hx u hu, by rw [inner_smul_right, hx u hu, mul_zero] } notation K`ᗮ`:1200 := submodule.orthogonal K /-- When a vector is in `Kᗮ`. -/ lemma submodule.mem_orthogonal (v : E) : v ∈ Kᗮ ↔ ∀ u ∈ K, ⟪u, v⟫ = 0 := iff.rfl /-- When a vector is in `Kᗮ`, with the inner product the other way round. -/ lemma submodule.mem_orthogonal' (v : E) : v ∈ Kᗮ ↔ ∀ u ∈ K, ⟪v, u⟫ = 0 := by simp_rw [submodule.mem_orthogonal, inner_eq_zero_sym] variables {K} /-- A vector in `K` is orthogonal to one in `Kᗮ`. -/ lemma submodule.inner_right_of_mem_orthogonal {u v : E} (hu : u ∈ K) (hv : v ∈ Kᗮ) : ⟪u, v⟫ = 0 := (K.mem_orthogonal v).1 hv u hu /-- A vector in `Kᗮ` is orthogonal to one in `K`. -/ lemma submodule.inner_left_of_mem_orthogonal {u v : E} (hu : u ∈ K) (hv : v ∈ Kᗮ) : ⟪v, u⟫ = 0 := by rw [inner_eq_zero_sym]; exact submodule.inner_right_of_mem_orthogonal hu hv /-- A vector is in `(𝕜 ∙ u)ᗮ` iff it is orthogonal to `u`. -/ lemma submodule.mem_orthogonal_singleton_iff_inner_right {u v : E} : v ∈ (𝕜 ∙ u)ᗮ ↔ ⟪u, v⟫ = 0 := begin refine ⟨submodule.inner_right_of_mem_orthogonal (submodule.mem_span_singleton_self u), _⟩, intros hv w hw, rw submodule.mem_span_singleton at hw, obtain ⟨c, rfl⟩ := hw, simp [inner_smul_left, hv], end /-- A vector in `(𝕜 ∙ u)ᗮ` is orthogonal to `u`. -/ lemma submodule.mem_orthogonal_singleton_iff_inner_left {u v : E} : v ∈ (𝕜 ∙ u)ᗮ ↔ ⟪v, u⟫ = 0 := by rw [submodule.mem_orthogonal_singleton_iff_inner_right, inner_eq_zero_sym] lemma submodule.sub_mem_orthogonal_of_inner_left {x y : E} (h : ∀ (v : K), ⟪x, v⟫ = ⟪y, v⟫) : x - y ∈ Kᗮ := begin rw submodule.mem_orthogonal', intros u hu, rw [inner_sub_left, sub_eq_zero], exact h ⟨u, hu⟩, end lemma submodule.sub_mem_orthogonal_of_inner_right {x y : E} (h : ∀ (v : K), ⟪(v : E), x⟫ = ⟪(v : E), y⟫) : x - y ∈ Kᗮ := begin intros u hu, rw [inner_sub_right, sub_eq_zero], exact h ⟨u, hu⟩, end variables (K) /-- `K` and `Kᗮ` have trivial intersection. -/ lemma submodule.inf_orthogonal_eq_bot : K ⊓ Kᗮ = ⊥ := begin rw submodule.eq_bot_iff, intros x, rw submodule.mem_inf, exact λ ⟨hx, ho⟩, inner_self_eq_zero.1 (ho x hx) end /-- `K` and `Kᗮ` have trivial intersection. -/ lemma submodule.orthogonal_disjoint : disjoint K Kᗮ := by simp [disjoint_iff, K.inf_orthogonal_eq_bot] /-- `Kᗮ` can be characterized as the intersection of the kernels of the operations of inner product with each of the elements of `K`. -/ lemma orthogonal_eq_inter : Kᗮ = ⨅ v : K, linear_map.ker (innerSL (v:E) : E →L[𝕜] 𝕜) := begin apply le_antisymm, { rw le_infi_iff, rintros ⟨v, hv⟩ w hw, simpa using hw _ hv }, { intros v hv w hw, simp only [submodule.mem_infi] at hv, exact hv ⟨w, hw⟩ } end /-- The orthogonal complement of any submodule `K` is closed. -/ lemma submodule.is_closed_orthogonal : is_closed (Kᗮ : set E) := begin rw orthogonal_eq_inter K, have := λ v : K, continuous_linear_map.is_closed_ker (innerSL (v:E) : E →L[𝕜] 𝕜), convert is_closed_Inter this, simp only [submodule.infi_coe], end /-- In a complete space, the orthogonal complement of any submodule `K` is complete. -/ instance [complete_space E] : complete_space Kᗮ := K.is_closed_orthogonal.complete_space_coe variables (𝕜 E) /-- `submodule.orthogonal` gives a `galois_connection` between `submodule 𝕜 E` and its `order_dual`. -/ lemma submodule.orthogonal_gc : @galois_connection (submodule 𝕜 E) (submodule 𝕜 E)ᵒᵈ _ _ submodule.orthogonal submodule.orthogonal := λ K₁ K₂, ⟨λ h v hv u hu, submodule.inner_left_of_mem_orthogonal hv (h hu), λ h v hv u hu, submodule.inner_left_of_mem_orthogonal hv (h hu)⟩ variables {𝕜 E} /-- `submodule.orthogonal` reverses the `≤` ordering of two subspaces. -/ lemma submodule.orthogonal_le {K₁ K₂ : submodule 𝕜 E} (h : K₁ ≤ K₂) : K₂ᗮ ≤ K₁ᗮ := (submodule.orthogonal_gc 𝕜 E).monotone_l h /-- `submodule.orthogonal.orthogonal` preserves the `≤` ordering of two subspaces. -/ lemma submodule.orthogonal_orthogonal_monotone {K₁ K₂ : submodule 𝕜 E} (h : K₁ ≤ K₂) : K₁ᗮᗮ ≤ K₂ᗮᗮ := submodule.orthogonal_le (submodule.orthogonal_le h) /-- `K` is contained in `Kᗮᗮ`. -/ lemma submodule.le_orthogonal_orthogonal : K ≤ Kᗮᗮ := (submodule.orthogonal_gc 𝕜 E).le_u_l _ /-- The inf of two orthogonal subspaces equals the subspace orthogonal to the sup. -/ lemma submodule.inf_orthogonal (K₁ K₂ : submodule 𝕜 E) : K₁ᗮ ⊓ K₂ᗮ = (K₁ ⊔ K₂)ᗮ := (submodule.orthogonal_gc 𝕜 E).l_sup.symm /-- The inf of an indexed family of orthogonal subspaces equals the subspace orthogonal to the sup. -/ lemma submodule.infi_orthogonal {ι : Type*} (K : ι → submodule 𝕜 E) : (⨅ i, (K i)ᗮ) = (supr K)ᗮ := (submodule.orthogonal_gc 𝕜 E).l_supr.symm /-- The inf of a set of orthogonal subspaces equals the subspace orthogonal to the sup. -/ lemma submodule.Inf_orthogonal (s : set $ submodule 𝕜 E) : (⨅ K ∈ s, Kᗮ) = (Sup s)ᗮ := (submodule.orthogonal_gc 𝕜 E).l_Sup.symm @[simp] lemma submodule.top_orthogonal_eq_bot : (⊤ : submodule 𝕜 E)ᗮ = ⊥ := begin ext, rw [submodule.mem_bot, submodule.mem_orthogonal], exact ⟨λ h, inner_self_eq_zero.mp (h x submodule.mem_top), by { rintro rfl, simp }⟩ end @[simp] lemma submodule.bot_orthogonal_eq_top : (⊥ : submodule 𝕜 E)ᗮ = ⊤ := begin rw [← submodule.top_orthogonal_eq_bot, eq_top_iff], exact submodule.le_orthogonal_orthogonal ⊤ end @[simp] lemma submodule.orthogonal_eq_top_iff : Kᗮ = ⊤ ↔ K = ⊥ := begin refine ⟨_, by { rintro rfl, exact submodule.bot_orthogonal_eq_top }⟩, intro h, have : K ⊓ Kᗮ = ⊥ := K.orthogonal_disjoint.eq_bot, rwa [h, inf_comm, top_inf_eq] at this end lemma submodule.orthogonal_family_self : @orthogonal_family 𝕜 E _ _ _ (λ b, ((cond b K Kᗮ : submodule 𝕜 E) : Type*)) _ (λ b, (cond b K Kᗮ).subtypeₗᵢ) | tt tt := absurd rfl | tt ff := λ _ x y, submodule.inner_right_of_mem_orthogonal x.prop y.prop | ff tt := λ _ x y, submodule.inner_left_of_mem_orthogonal y.prop x.prop | ff ff := absurd rfl end orthogonal namespace uniform_space.completion open uniform_space function instance {𝕜' E' : Type*} [topological_space 𝕜'] [uniform_space E'] [has_inner 𝕜' E'] : has_inner 𝕜' (completion E') := { inner := curry $ (dense_inducing_coe.prod dense_inducing_coe).extend (uncurry inner) } @[simp] lemma inner_coe (a b : E) : inner (a : completion E) (b : completion E) = (inner a b : 𝕜) := (dense_inducing_coe.prod dense_inducing_coe).extend_eq (continuous_inner : continuous (uncurry inner : E × E → 𝕜)) (a, b) protected lemma continuous_inner : continuous (uncurry inner : completion E × completion E → 𝕜) := begin let inner' : E →+ E →+ 𝕜 := { to_fun := λ x, (innerₛₗ x).to_add_monoid_hom, map_zero' := by ext x; exact inner_zero_left, map_add' := λ x y, by ext z; exact inner_add_left }, have : continuous (λ p : E × E, inner' p.1 p.2) := continuous_inner, rw [completion.has_inner, uncurry_curry _], change continuous (((dense_inducing_to_compl E).prod (dense_inducing_to_compl E)).extend (λ p : E × E, inner' p.1 p.2)), exact (dense_inducing_to_compl E).extend_Z_bilin (dense_inducing_to_compl E) this, end protected lemma continuous.inner {α : Type*} [topological_space α] {f g : α → completion E} (hf : continuous f) (hg : continuous g) : continuous (λ x : α, inner (f x) (g x) : α → 𝕜) := uniform_space.completion.continuous_inner.comp (hf.prod_mk hg : _) instance : inner_product_space 𝕜 (completion E) := { to_normed_add_comm_group := infer_instance, norm_sq_eq_inner := λ x, completion.induction_on x (is_closed_eq (continuous_norm.pow 2) (continuous_re.comp (continuous.inner continuous_id' continuous_id'))) (λ a, by simp only [norm_coe, inner_coe, inner_self_eq_norm_sq]), conj_sym := λ x y, completion.induction_on₂ x y (is_closed_eq (continuous_conj.comp (continuous.inner continuous_snd continuous_fst)) (continuous.inner continuous_fst continuous_snd)) (λ a b, by simp only [inner_coe, inner_conj_sym]), add_left := λ x y z, completion.induction_on₃ x y z (is_closed_eq (continuous.inner (continuous_fst.add (continuous_fst.comp continuous_snd)) (continuous_snd.comp continuous_snd)) ((continuous.inner continuous_fst (continuous_snd.comp continuous_snd)).add (continuous.inner (continuous_fst.comp continuous_snd) (continuous_snd.comp continuous_snd)))) (λ a b c, by simp only [← coe_add, inner_coe, inner_add_left]), smul_left := λ x y c, completion.induction_on₂ x y (is_closed_eq (continuous.inner (continuous_fst.const_smul c) continuous_snd) ((continuous_mul_left _).comp (continuous.inner continuous_fst continuous_snd))) (λ a b, by simp only [← coe_smul c a, inner_coe, inner_smul_left]) } end uniform_space.completion
8dd53aab5eae001e73e844f00166629e2f41f107
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/tactic/omega/find_ees.lean
77427d36fe61b298a9860717cb918514d2454970
[ "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
5,560
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek A tactic for finding a sequence of equality elimination rules for a given set of constraints. -/ import tactic.omega.eq_elim variables {α β : Type} open tactic namespace omega /-- The state of equality elimination proof search. `eqs` is the list of equality constraints, and each `t ∈ eqs` represents the constraint `0 = t`. Similarly, `les` is the list of inequality constraints, and each `t ∈ eqs` represents the constraint `0 < t`. `ees` is the sequence of equality elimination steps that have been used so far to obtain the current set of constraints. The list `ees` grows over time until `eqs` becomes empty. -/ @[derive inhabited] structure ee_state := (eqs : list term) (les : list term) (ees : list ee) @[reducible] meta def eqelim := state_t ee_state tactic meta def abort {α : Type} : eqelim α := ⟨λ x, failed⟩ private meta def mk_eqelim_state (eqs les : list term) : tactic ee_state := return (ee_state.mk eqs les []) /-- Get the current list of equality constraints. -/ meta def get_eqs : eqelim (list term) := ee_state.eqs <$> get /-- Get the current list of inequality constraints. -/ meta def get_les : eqelim (list term) := ee_state.les <$> get /-- Get the current sequence of equality elimiation steps. -/ meta def get_ees : eqelim (list ee) := ee_state.ees <$> get /-- Update the list of equality constraints. -/ meta def set_eqs (eqs : list term) : eqelim unit := modify $ λ s, {eqs := eqs, ..s} /-- Update the list of inequality constraints. -/ meta def set_les (les : list term) : eqelim unit := modify $ λ s, {les := les, ..s} /-- Update the sequence of equality elimiation steps. -/ meta def set_ees (es : list ee) : eqelim unit := modify $ λ s, {ees := es, ..s} /-- Add a new step to the sequence of equality elimination steps. -/ meta def add_ee (e : ee) : eqelim unit := do es ← get_ees, set_ees (es ++ [e]) /-- Return the first equality constraint in the current list of equality constraints. The returned constraint is 'popped' and no longer available in the state. -/ meta def head_eq : eqelim term := do eqs ← get_eqs, match eqs with | [] := abort | (eq::eqs') := set_eqs eqs' >> pure eq end meta def run {α : Type} (eqs les : list term) (r : eqelim α) : tactic α := prod.fst <$> (mk_eqelim_state eqs les >>= r.run) /-- If `t1` succeeds and returns a value, 'commit' to that choice and run `t3` with the returned value as argument. Do not backtrack to try `t2` even if `t3` fails. If `t1` fails outright, run `t2`. -/ meta def ee_commit (t1 : eqelim α) (t2 : eqelim β) (t3 : α → eqelim β) : eqelim β := do x ← ((t1 >>= return ∘ some) <|> return none), match x with | none := t2 | (some a) := t3 a end local notation t1 `!>>=` t2 `;` t3 := ee_commit t1 t2 t3 private meta def of_tactic {α : Type} : tactic α → eqelim α := state_t.lift /-- GCD of all elements of the list. -/ def gcd : list int → nat | [] := 0 | (i::is) := nat.gcd i.nat_abs (gcd is) /-- GCD of all coefficients in a term. -/ meta def get_gcd (t : term) : eqelim int := pure ↑(gcd t.snd) /-- Divide a term by an integer if the integer divides the constant component of the term. It is assumed that the integer also divides all coefficients of the term. -/ meta def factor (i : int) (t : term) : eqelim term := if i ∣ t.fst then add_ee (ee.factor i) >> pure (t.div i) else abort /-- If list has a nonzero element, return the minimum element (by absolute value) with its index. Otherwise, return none. -/ meta def find_min_coeff_core : list int → eqelim (int × nat) | [] := abort | (i::is) := (do (j,n) ← find_min_coeff_core is, if i ≠ 0 ∧ i.nat_abs ≤ j.nat_abs then pure (i,0) else pure (j,n+1)) <|> (if i = (0 : int) then abort else pure (i,0)) /-- Find and return the smallest coefficient (by absolute value) in a term, along with the coefficient's variable index and the term itself. If the coefficient is negative, negate both the coefficient and the term before returning them. -/ meta def find_min_coeff (t : term) : eqelim (int × nat × term) := do (i,n) ← find_min_coeff_core t.snd, if 0 < i then pure (i,n,t) else add_ee (ee.neg) >> pure (-i,n,t.neg) /-- Find an appropriate equality elimination step for the current state and apply it. -/ meta def elim_eq : eqelim unit := do t ← head_eq, i ← get_gcd t, factor i t !>>= (set_eqs [] >> add_ee (ee.nondiv i)) ; λ s, find_min_coeff s !>>= add_ee ee.drop ; λ ⟨i, n, u⟩, if i = 1 then do eqs ← get_eqs, les ← get_les, set_eqs (eqs.map (cancel n u)), set_les (les.map (cancel n u)), add_ee (ee.cancel n) else let v : term := coeffs_reduce n u.fst u.snd in let r : term := rhs n u.fst u.snd in do eqs ← get_eqs, les ← get_les, set_eqs (v::eqs.map (subst n r)), set_les (les.map (subst n r)), add_ee (ee.reduce n), elim_eq /-- Find and return the sequence of steps for eliminating all equality constraints in the current state. -/ meta def elim_eqs : eqelim (list ee) := elim_eq !>>= get_ees ; λ _, elim_eqs /-- Given a linear constrain clause, return a list of steps for eliminating its equality constraints. -/ meta def find_ees : clause → tactic (list ee) | (eqs,les) := run eqs les elim_eqs end omega
fbd98bfd310b168a13dd24db795f6884ea7b77bd
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/algebra/star/chsh.lean
c63dcb4fd56bcec65a1c706e3c7929f1e48e2626
[ "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
11,336
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.star.algebra import algebra.algebra.ordered import analysis.special_functions.pow /-! # The Clauser-Horne-Shimony-Holt inequality and Tsirelson's inequality. We establish a version of the Clauser-Horne-Shimony-Holt (CHSH) inequality (which is a generalization of Bell's inequality). This is a foundational result which implies that quantum mechanics is not a local hidden variable theory. As usually stated the CHSH inequality requires substantial language from physics and probability, but it is possible to give a statement that is purely about ordered `*`-algebras. We do that here, to avoid as many practical and logical dependencies as possible. Since the algebra of observables of any quantum system is an ordered `*`-algebra (in particular a von Neumann algebra) this is a strict generalization of the usual statement. Let `R` be a `*`-ring. A CHSH tuple in `R` consists of * four elements `A₀ A₁ B₀ B₁ : R`, such that * each `Aᵢ` and `Bⱼ` is a self-adjoint involution, and * the `Aᵢ` commute with the `Bⱼ`. The physical interpretation is that the four elements are observables (hence self-adjoint) that take values ±1 (hence involutions), and that the `Aᵢ` are spacelike separated from the `Bⱼ` (and hence commute). The CHSH inequality says that when `R` is an ordered `*`-ring (that is, a `*`-ring which is ordered, and for every `r : R`, `0 ≤ star r * r`), which is moreover *commutative*, we have `A₀ * B₀ + A₀ * B₁ + A₁ * B₀ - A₁ * B₁ ≤ 2` On the other hand, Tsirelson's inequality says that for any ordered `*`-ring we have `A₀ * B₀ + A₀ * B₁ + A₁ * B₀ - A₁ * B₁ ≤ 2√2` (A caveat: in the commutative case we need 2⁻¹ in the ring, and in the noncommutative case we need √2 and √2⁻¹. To keep things simple we just assume our rings are ℝ-algebras.) The proofs I've seen in the literature either assume a significant framework for quantum mechanics, or assume the ring is a `C^*`-algebra. In the `C^*`-algebra case, the order structure is completely determined by the `*`-algebra structure: `0 ≤ A` iff there exists some `B` so `A = star B * B`. There's a nice proof of both bounds in this setting at https://en.wikipedia.org/wiki/Tsirelson%27s_bound The proof given here is purely algebraic. ## Future work One can show that Tsirelson's inequality is tight. In the `*`-ring of n-by-n complex matrices, if `A ≤ λ I` for some `λ : ℝ`, then every eigenvalue has absolute value at most `λ`. There is a CHSH tuple in 4-by-4 matrices such that `A₀ * B₀ + A₀ * B₁ + A₁ * B₀ - A₁ * B₁` has `2√2` as an eigenvalue. ## References * [Clauser, Horne, Shimony, Holt, *Proposed experiment to test local hidden-variable theories*][zbMATH06785026] * [Bell, *On the Einstein Podolsky Rosen Paradox*][MR3790629] * [Tsirelson, *Quantum generalizations of Bell's inequality*][MR577178] -/ universes u /-- A CHSH tuple in a `star_monoid R` consists of 4 self-adjoint involutions `A₀ A₁ B₀ B₁` such that the `Aᵢ` commute with the `Bⱼ`. The physical interpretation is that `A₀` and `A₁` are a pair of boolean observables which are spacelike separated from another pair `B₀` and `B₁` of boolean observables. -/ @[nolint has_inhabited_instance] structure is_CHSH_tuple {R} [monoid R] [star_monoid R] (A₀ A₁ B₀ B₁ : R) := (A₀_inv : A₀^2 = 1) (A₁_inv : A₁^2 = 1) (B₀_inv : B₀^2 = 1) (B₁_inv : B₁^2 = 1) (A₀_sa : star A₀ = A₀) (A₁_sa : star A₁ = A₁) (B₀_sa : star B₀ = B₀) (B₁_sa : star B₁ = B₁) (A₀B₀_commutes : A₀ * B₀ = B₀ * A₀) (A₀B₁_commutes : A₀ * B₁ = B₁ * A₀) (A₁B₀_commutes : A₁ * B₀ = B₀ * A₁) (A₁B₁_commutes : A₁ * B₁ = B₁ * A₁) variables {R : Type u} /-- Given a CHSH tuple (A₀, A₁, B₀, B₁) in a *commutative* ordered `*`-algebra over ℝ, `A₀ * B₀ + A₀ * B₁ + A₁ * B₀ - A₁ * B₁ ≤ 2`. (We could work over ℤ[⅟2] if we wanted to!) -/ lemma CHSH_inequality_of_comm [ordered_comm_ring R] [star_ordered_ring R] [algebra ℝ R] [ordered_smul ℝ R] (A₀ A₁ B₀ B₁ : R) (T : is_CHSH_tuple A₀ A₁ B₀ B₁) : A₀ * B₀ + A₀ * B₁ + A₁ * B₀ - A₁ * B₁ ≤ 2 := begin let P := (2 - A₀ * B₀ - A₀ * B₁ - A₁ * B₀ + A₁ * B₁), have i₁ : 0 ≤ P, { have idem : P * P = 4 * P, { -- If we had a Gröbner basis algorithm, this would be trivial. -- Without one, it is somewhat tedious! dsimp [P], simp only [add_mul, mul_add, sub_mul, mul_sub, mul_comm, mul_assoc, add_assoc], repeat { conv in (B₀ * (A₀ * B₀)) { rw [T.A₀B₀_commutes, ←mul_assoc B₀ B₀ A₀, ←sq, T.B₀_inv, one_mul], } }, repeat { conv in (B₀ * (A₁ * B₀)) { rw [T.A₁B₀_commutes, ←mul_assoc B₀ B₀ A₁, ←sq, T.B₀_inv, one_mul], } }, repeat { conv in (B₁ * (A₀ * B₁)) { rw [T.A₀B₁_commutes, ←mul_assoc B₁ B₁ A₀, ←sq, T.B₁_inv, one_mul], } }, repeat { conv in (B₁ * (A₁ * B₁)) { rw [T.A₁B₁_commutes, ←mul_assoc B₁ B₁ A₁, ←sq, T.B₁_inv, one_mul], } }, conv in (A₀ * (B₀ * (A₀ * B₁))) { rw [←mul_assoc, T.A₀B₀_commutes, mul_assoc, ←mul_assoc A₀, ←sq, T.A₀_inv, one_mul], }, conv in (A₀ * (B₁ * (A₀ * B₀))) { rw [←mul_assoc, T.A₀B₁_commutes, mul_assoc, ←mul_assoc A₀, ←sq, T.A₀_inv, one_mul], }, conv in (A₁ * (B₀ * (A₁ * B₁))) { rw [←mul_assoc, T.A₁B₀_commutes, mul_assoc, ←mul_assoc A₁, ←sq, T.A₁_inv, one_mul], }, conv in (A₁ * (B₁ * (A₁ * B₀))) { rw [←mul_assoc, T.A₁B₁_commutes, mul_assoc, ←mul_assoc A₁, ←sq, T.A₁_inv, one_mul], }, simp only [←sq, T.A₀_inv, T.A₁_inv], simp only [mul_comm A₁ A₀, mul_comm B₁ B₀, mul_left_comm A₁ A₀, mul_left_comm B₁ B₀, mul_left_comm B₀ A₀, mul_left_comm B₀ A₁, mul_left_comm B₁ A₀, mul_left_comm B₁ A₁], norm_num, simp only [mul_comm _ (2 : R), mul_comm _ (4 : R), mul_left_comm _ (2 : R), mul_left_comm _ (4 : R)], abel, simp only [neg_mul_eq_neg_mul_symm, mul_one, int.cast_bit0, one_mul, int.cast_one, gsmul_eq_mul, int.cast_neg], simp only [←mul_assoc, ←add_assoc], norm_num, }, have idem' : P = (1 / 4 : ℝ) • (P * P), { have h : 4 * P = (4 : ℝ) • P := by simp [algebra.smul_def], rw [idem, h, ←mul_smul], norm_num, }, have sa : star P = P, { dsimp [P], simp only [star_add, star_sub, star_mul, star_bit0, star_one, T.A₀_sa, T.A₁_sa, T.B₀_sa, T.B₁_sa, mul_comm B₀, mul_comm B₁], }, rw idem', conv_rhs { congr, skip, congr, rw ←sa, }, convert smul_le_smul_of_nonneg (star_mul_self_nonneg : 0 ≤ star P * P) _, { simp, }, { apply_instance, }, { norm_num, }, }, apply le_of_sub_nonneg, simpa only [sub_add_eq_sub_sub, ←sub_add] using i₁, end /-! We now prove some rather specialized lemmas in preparation for the Tsirelson inequality, which we hide in a namespace as they are unlikely to be useful elsewhere. -/ local notation `√2` := (real.sqrt 2 : ℝ) namespace tsirelson_inequality /-! Before proving Tsirelson's bound, we prepare some easy lemmas about √2. -/ -- This calculation, which we need for Tsirelson's bound, -- defeated me. Thanks for the rescue from Shing Tak Lam! lemma tsirelson_inequality_aux : √2 * √2 ^ 3 = √2 * (2 * √2⁻¹ + 4 * (√2⁻¹ * 2⁻¹)) := begin ring_nf, rw [mul_assoc, inv_mul_cancel, real.sqrt_eq_rpow, ←real.rpow_nat_cast, ←real.rpow_mul], { norm_num, rw show (2 : ℝ) ^ (2 : ℝ) = (2 : ℝ) ^ (2 : ℕ), by { rw ←real.rpow_nat_cast, norm_num }, norm_num }, { norm_num, }, { norm_num, }, end lemma sqrt_two_inv_mul_self : √2⁻¹ * √2⁻¹ = (2⁻¹ : ℝ) := by { rw [←mul_inv₀], norm_num, } end tsirelson_inequality open tsirelson_inequality /-- In a noncommutative ordered `*`-algebra over ℝ, Tsirelson's bound for a CHSH tuple (A₀, A₁, B₀, B₁) is `A₀ * B₀ + A₀ * B₁ + A₁ * B₀ - A₁ * B₁ ≤ 2^(3/2) • 1`. We prove this by providing an explicit sum-of-squares decomposition of the difference. (We could work over `ℤ[2^(1/2), 2^(-1/2)]` if we really wanted to!) -/ lemma tsirelson_inequality [ordered_ring R] [star_ordered_ring R] [algebra ℝ R] [ordered_smul ℝ R] [star_algebra ℝ R] (A₀ A₁ B₀ B₁ : R) (T : is_CHSH_tuple A₀ A₁ B₀ B₁) : A₀ * B₀ + A₀ * B₁ + A₁ * B₀ - A₁ * B₁ ≤ √2^3 • 1 := begin -- abel will create `ℤ` multiplication. We will `simp` them away to `ℝ` multiplication. have M : ∀ (m : ℤ) (a : ℝ) (x : R), m • a • x = ((m : ℝ) * a) • x := λ m a x, by rw [gsmul_eq_smul_cast ℝ, ← mul_smul], let P := √2⁻¹ • (A₁ + A₀) - B₀, let Q := √2⁻¹ • (A₁ - A₀) + B₁, have w : √2^3 • 1 - A₀ * B₀ - A₀ * B₁ - A₁ * B₀ + A₁ * B₁ = √2⁻¹ • (P^2 + Q^2), { dsimp [P, Q], -- distribute out all the powers and products appearing on the RHS simp only [sq, sub_mul, mul_sub, add_mul, mul_add, smul_add, smul_sub], -- pull all coefficients out to the front, and combine `√2`s where possible simp only [algebra.mul_smul_comm, algebra.smul_mul_assoc, ←mul_smul, sqrt_two_inv_mul_self], -- replace Aᵢ * Aᵢ = 1 and Bᵢ * Bᵢ = 1 simp only [←sq, T.A₀_inv, T.A₁_inv, T.B₀_inv, T.B₁_inv], -- move Aᵢ to the left of Bᵢ simp only [←T.A₀B₀_commutes, ←T.A₀B₁_commutes, ←T.A₁B₀_commutes, ←T.A₁B₁_commutes], -- collect terms, simplify coefficients, and collect terms again: abel, -- all terms coincide, but the last one. Simplify all other terms simp only [M], simp only [neg_mul_eq_neg_mul_symm, int.cast_bit0, one_mul, mul_inv_cancel_of_invertible, int.cast_one, one_smul, int.cast_neg, add_right_inj, neg_smul, ← add_smul], -- just look at the coefficients now: congr, exact mul_left_cancel₀ (by norm_num) tsirelson_inequality_aux, }, have pos : 0 ≤ √2⁻¹ • (P^2 + Q^2), { have P_sa : star P = P, { dsimp [P], simp only [star_smul, star_add, star_sub, star_id_of_comm, T.A₀_sa, T.A₁_sa, T.B₀_sa, T.B₁_sa], }, have Q_sa : star Q = Q, { dsimp [Q], simp only [star_smul, star_add, star_sub, star_id_of_comm, T.A₀_sa, T.A₁_sa, T.B₀_sa, T.B₁_sa], }, have P2_nonneg : 0 ≤ P^2, { rw [sq], conv { congr, skip, congr, rw ←P_sa, }, convert (star_mul_self_nonneg : 0 ≤ star P * P), }, have Q2_nonneg : 0 ≤ Q^2, { rw [sq], conv { congr, skip, congr, rw ←Q_sa, }, convert (star_mul_self_nonneg : 0 ≤ star Q * Q), }, convert smul_le_smul_of_nonneg (add_nonneg P2_nonneg Q2_nonneg) (le_of_lt (show 0 < √2⁻¹, by norm_num)), -- `norm_num` can't directly show `0 ≤ √2⁻¹` simp, }, apply le_of_sub_nonneg, simpa only [sub_add_eq_sub_sub, ←sub_add, w] using pos, end
1140c1d661077056a0db0aa97dfce6248b7f58db
82e44445c70db0f03e30d7be725775f122d72f3e
/src/data/polynomial/field_division.lean
55454f694476b85cb9e2bf25b2312df2b73677fa
[ "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
19,811
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.ring_division import data.polynomial.derivative import algebra.gcd_monoid /-! # Theory of univariate polynomials This file starts looking like the ring theory of $ R[X] $ -/ noncomputable theory open_locale classical big_operators namespace polynomial universes u v w y z variables {R : Type u} {S : Type v} {k : Type y} {A : Type z} {a b : R} {n : ℕ} section integral_domain variables [integral_domain R] [normalization_monoid R] instance : normalization_monoid (polynomial R) := { norm_unit := λ p, ⟨C ↑(norm_unit (p.leading_coeff)), C ↑(norm_unit (p.leading_coeff))⁻¹, by rw [← ring_hom.map_mul, units.mul_inv, C_1], by rw [← ring_hom.map_mul, units.inv_mul, C_1]⟩, norm_unit_zero := units.ext (by simp), norm_unit_mul := λ p q hp0 hq0, units.ext (begin dsimp, rw [ne.def, ← leading_coeff_eq_zero] at *, rw [leading_coeff_mul, norm_unit_mul hp0 hq0, units.coe_mul, C_mul], end), norm_unit_coe_units := λ u, units.ext begin rw [← mul_one u⁻¹, units.coe_mul, units.eq_inv_mul_iff_mul_eq], dsimp, rcases polynomial.is_unit_iff.1 ⟨u, rfl⟩ with ⟨_, ⟨w, rfl⟩, h2⟩, rw [← h2, leading_coeff_C, norm_unit_coe_units, ← C_mul, units.mul_inv, C_1], end } @[simp] lemma coe_norm_unit {p : polynomial R} : (norm_unit p : polynomial R) = C ↑(norm_unit p.leading_coeff) := by simp [norm_unit] lemma leading_coeff_normalize (p : polynomial R) : leading_coeff (normalize p) = normalize (leading_coeff p) := by simp end integral_domain section field variables [field R] {p q : polynomial R} lemma is_unit_iff_degree_eq_zero : is_unit p ↔ degree p = 0 := ⟨degree_eq_zero_of_is_unit, λ h, have degree p ≤ 0, by simp [*, le_refl], have hc : coeff p 0 ≠ 0, from λ hc, by rw [eq_C_of_degree_le_zero this, hc] at h; simpa using h, is_unit_iff_dvd_one.2 ⟨C (coeff p 0)⁻¹, begin conv in p { rw eq_C_of_degree_le_zero this }, rw [← C_mul, _root_.mul_inv_cancel hc, C_1] end⟩⟩ lemma degree_pos_of_ne_zero_of_nonunit (hp0 : p ≠ 0) (hp : ¬is_unit p) : 0 < degree p := lt_of_not_ge (λ h, begin rw [eq_C_of_degree_le_zero h] at hp0 hp, exact hp (is_unit.map (C.to_monoid_hom : R →* _) (is_unit.mk0 (coeff p 0) (mt C_inj.2 (by simpa using hp0)))), end) lemma monic_mul_leading_coeff_inv (h : p ≠ 0) : monic (p * C (leading_coeff p)⁻¹) := by rw [monic, leading_coeff_mul, leading_coeff_C, mul_inv_cancel (show leading_coeff p ≠ 0, from mt leading_coeff_eq_zero.1 h)] lemma degree_mul_leading_coeff_inv (p : polynomial R) (h : q ≠ 0) : degree (p * C (leading_coeff q)⁻¹) = degree p := have h₁ : (leading_coeff q)⁻¹ ≠ 0 := inv_ne_zero (mt leading_coeff_eq_zero.1 h), by rw [degree_mul, degree_C h₁, add_zero] theorem irreducible_of_monic {p : polynomial R} (hp1 : p.monic) (hp2 : p ≠ 1) : irreducible p ↔ (∀ f g : polynomial R, f.monic → g.monic → f * g = p → f = 1 ∨ g = 1) := ⟨λ hp3 f g hf hg hfg, or.cases_on (hp3.is_unit_or_is_unit hfg.symm) (assume huf : is_unit f, or.inl $ eq_one_of_is_unit_of_monic hf huf) (assume hug : is_unit g, or.inr $ eq_one_of_is_unit_of_monic hg hug), λ hp3, ⟨mt (eq_one_of_is_unit_of_monic hp1) hp2, λ f g hp, have hf : f ≠ 0, from λ hf, by { rw [hp, hf, zero_mul] at hp1, exact not_monic_zero hp1 }, have hg : g ≠ 0, from λ hg, by { rw [hp, hg, mul_zero] at hp1, exact not_monic_zero hp1 }, or.imp (λ hf, is_unit_of_mul_eq_one _ _ hf) (λ hg, is_unit_of_mul_eq_one _ _ hg) $ hp3 (f * C f.leading_coeff⁻¹) (g * C g.leading_coeff⁻¹) (monic_mul_leading_coeff_inv hf) (monic_mul_leading_coeff_inv hg) $ by rw [mul_assoc, mul_left_comm _ g, ← mul_assoc, ← C_mul, ← mul_inv', ← leading_coeff_mul, ← hp, monic.def.1 hp1, inv_one, C_1, mul_one]⟩⟩ /-- Division of polynomials. See polynomial.div_by_monic for more details.-/ def div (p q : polynomial R) := C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)) /-- Remainder of polynomial division, see the lemma `quotient_mul_add_remainder_eq_aux`. See polynomial.mod_by_monic for more details. -/ def mod (p q : polynomial R) := p %ₘ (q * C (leading_coeff q)⁻¹) private lemma quotient_mul_add_remainder_eq_aux (p q : polynomial R) : q * div p q + mod p q = p := if h : q = 0 then by simp only [h, zero_mul, mod, mod_by_monic_zero, zero_add] else begin conv {to_rhs, rw ← mod_by_monic_add_div p (monic_mul_leading_coeff_inv h)}, rw [div, mod, add_comm, mul_assoc] end private lemma remainder_lt_aux (p : polynomial R) (hq : q ≠ 0) : degree (mod p q) < degree q := by rw ← degree_mul_leading_coeff_inv q hq; exact degree_mod_by_monic_lt p (monic_mul_leading_coeff_inv hq) (mul_ne_zero hq (mt leading_coeff_eq_zero.2 (by rw leading_coeff_C; exact inv_ne_zero (mt leading_coeff_eq_zero.1 hq)))) instance : has_div (polynomial R) := ⟨div⟩ instance : has_mod (polynomial R) := ⟨mod⟩ lemma div_def : p / q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)) := rfl lemma mod_def : p % q = p %ₘ (q * C (leading_coeff q)⁻¹) := rfl lemma mod_by_monic_eq_mod (p : polynomial R) (hq : monic q) : p %ₘ q = p % q := show p %ₘ q = p %ₘ (q * C (leading_coeff q)⁻¹), by simp only [monic.def.1 hq, inv_one, mul_one, C_1] lemma div_by_monic_eq_div (p : polynomial R) (hq : monic q) : p /ₘ q = p / q := show p /ₘ q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)), by simp only [monic.def.1 hq, inv_one, C_1, one_mul, mul_one] lemma mod_X_sub_C_eq_C_eval (p : polynomial R) (a : R) : p % (X - C a) = C (p.eval a) := mod_by_monic_eq_mod p (monic_X_sub_C a) ▸ mod_by_monic_X_sub_C_eq_C_eval _ _ lemma mul_div_eq_iff_is_root : (X - C a) * (p / (X - C a)) = p ↔ is_root p a := div_by_monic_eq_div p (monic_X_sub_C a) ▸ mul_div_by_monic_eq_iff_is_root instance : euclidean_domain (polynomial R) := { quotient := (/), quotient_zero := by simp [div_def], remainder := (%), r := _, r_well_founded := degree_lt_wf, quotient_mul_add_remainder_eq := quotient_mul_add_remainder_eq_aux, remainder_lt := λ p q hq, remainder_lt_aux _ hq, mul_left_not_lt := λ p q hq, not_lt_of_ge (degree_le_mul_left _ hq), .. polynomial.comm_ring, .. polynomial.nontrivial } lemma mod_eq_self_iff (hq0 : q ≠ 0) : p % q = p ↔ degree p < degree q := ⟨λ h, h ▸ euclidean_domain.mod_lt _ hq0, λ h, have ¬degree (q * C (leading_coeff q)⁻¹) ≤ degree p := not_le_of_gt $ by rwa degree_mul_leading_coeff_inv q hq0, begin rw [mod_def, mod_by_monic, dif_pos (monic_mul_leading_coeff_inv hq0)], unfold div_mod_by_monic_aux, simp only [this, false_and, if_false] end⟩ lemma div_eq_zero_iff (hq0 : q ≠ 0) : p / q = 0 ↔ degree p < degree q := ⟨λ h, by have := euclidean_domain.div_add_mod p q; rwa [h, mul_zero, zero_add, mod_eq_self_iff hq0] at this, λ h, have hlt : degree p < degree (q * C (leading_coeff q)⁻¹), by rwa degree_mul_leading_coeff_inv q hq0, have hm : monic (q * C (leading_coeff q)⁻¹) := monic_mul_leading_coeff_inv hq0, by rw [div_def, (div_by_monic_eq_zero_iff hm (ne_zero_of_monic hm)).2 hlt, mul_zero]⟩ lemma degree_add_div (hq0 : q ≠ 0) (hpq : degree q ≤ degree p) : degree q + degree (p / q) = degree p := have degree (p % q) < degree (q * (p / q)) := calc degree (p % q) < degree q : euclidean_domain.mod_lt _ hq0 ... ≤ _ : degree_le_mul_left _ (mt (div_eq_zero_iff hq0).1 (not_lt_of_ge hpq)), by conv_rhs { rw [← euclidean_domain.div_add_mod p q, degree_add_eq_left_of_degree_lt this, degree_mul] } lemma degree_div_le (p q : polynomial R) : degree (p / q) ≤ degree p := if hq : q = 0 then by simp [hq] else by rw [div_def, mul_comm, degree_mul_leading_coeff_inv _ hq]; exact degree_div_by_monic_le _ _ lemma degree_div_lt (hp : p ≠ 0) (hq : 0 < degree q) : degree (p / q) < degree p := have hq0 : q ≠ 0, from λ hq0, by simpa [hq0] using hq, by rw [div_def, mul_comm, degree_mul_leading_coeff_inv _ hq0]; exact degree_div_by_monic_lt _ (monic_mul_leading_coeff_inv hq0) hp (by rw degree_mul_leading_coeff_inv _ hq0; exact hq) @[simp] lemma degree_map [field k] (p : polynomial R) (f : R →+* k) : degree (p.map f) = degree p := p.degree_map_eq_of_injective f.injective @[simp] lemma nat_degree_map [field k] (f : R →+* k) : nat_degree (p.map f) = nat_degree p := nat_degree_eq_of_degree_eq (degree_map _ f) @[simp] lemma leading_coeff_map [field k] (f : R →+* k) : leading_coeff (p.map f) = f (leading_coeff p) := by simp only [← coeff_nat_degree, coeff_map f, nat_degree_map] theorem monic_map_iff [field k] {f : R →+* k} {p : polynomial R} : (p.map f).monic ↔ p.monic := by rw [monic, leading_coeff_map, ← f.map_one, function.injective.eq_iff f.injective, monic] theorem is_unit_map [field k] (f : R →+* k) : is_unit (p.map f) ↔ is_unit p := by simp_rw [is_unit_iff_degree_eq_zero, degree_map] lemma map_div [field k] (f : R →+* k) : (p / q).map f = p.map f / q.map f := if hq0 : q = 0 then by simp [hq0] else by rw [div_def, div_def, map_mul, map_div_by_monic f (monic_mul_leading_coeff_inv hq0)]; simp [f.map_inv, coeff_map f] lemma map_mod [field k] (f : R →+* k) : (p % q).map f = p.map f % q.map f := if hq0 : q = 0 then by simp [hq0] else by rw [mod_def, mod_def, leading_coeff_map f, ← f.map_inv, ← map_C f, ← map_mul f, map_mod_by_monic f (monic_mul_leading_coeff_inv hq0)] section open euclidean_domain theorem gcd_map [field k] (f : R →+* k) : gcd (p.map f) (q.map f) = (gcd p q).map f := gcd.induction p q (λ x, by simp_rw [map_zero, euclidean_domain.gcd_zero_left]) $ λ x y hx ih, by rw [gcd_val, ← map_mod, ih, ← gcd_val] end lemma eval₂_gcd_eq_zero [comm_semiring k] {ϕ : R →+* k} {f g : polynomial R} {α : k} (hf : f.eval₂ ϕ α = 0) (hg : g.eval₂ ϕ α = 0) : (euclidean_domain.gcd f g).eval₂ ϕ α = 0 := by rw [euclidean_domain.gcd_eq_gcd_ab f g, polynomial.eval₂_add, polynomial.eval₂_mul, polynomial.eval₂_mul, hf, hg, zero_mul, zero_mul, zero_add] lemma eval_gcd_eq_zero {f g : polynomial R} {α : R} (hf : f.eval α = 0) (hg : g.eval α = 0) : (euclidean_domain.gcd f g).eval α = 0 := eval₂_gcd_eq_zero hf hg lemma root_left_of_root_gcd [comm_semiring k] {ϕ : R →+* k} {f g : polynomial R} {α : k} (hα : (euclidean_domain.gcd f g).eval₂ ϕ α = 0) : f.eval₂ ϕ α = 0 := by { cases euclidean_domain.gcd_dvd_left f g with p hp, rw [hp, polynomial.eval₂_mul, hα, zero_mul] } lemma root_right_of_root_gcd [comm_semiring k] {ϕ : R →+* k} {f g : polynomial R} {α : k} (hα : (euclidean_domain.gcd f g).eval₂ ϕ α = 0) : g.eval₂ ϕ α = 0 := by { cases euclidean_domain.gcd_dvd_right f g with p hp, rw [hp, polynomial.eval₂_mul, hα, zero_mul] } lemma root_gcd_iff_root_left_right [comm_semiring k] {ϕ : R →+* k} {f g : polynomial R} {α : k} : (euclidean_domain.gcd f g).eval₂ ϕ α = 0 ↔ (f.eval₂ ϕ α = 0) ∧ (g.eval₂ ϕ α = 0) := ⟨λ h, ⟨root_left_of_root_gcd h, root_right_of_root_gcd h⟩, λ h, eval₂_gcd_eq_zero h.1 h.2⟩ lemma is_root_gcd_iff_is_root_left_right {f g : polynomial R} {α : R} : (euclidean_domain.gcd f g).is_root α ↔ f.is_root α ∧ g.is_root α := root_gcd_iff_root_left_right theorem is_coprime_map [field k] (f : R →+* k) : is_coprime (p.map f) (q.map f) ↔ is_coprime p q := by rw [← gcd_is_unit_iff, ← gcd_is_unit_iff, gcd_map, is_unit_map] @[simp] lemma map_eq_zero [semiring S] [nontrivial S] (f : R →+* S) : p.map f = 0 ↔ p = 0 := by simp only [polynomial.ext_iff, f.map_eq_zero, coeff_map, coeff_zero] lemma map_ne_zero [semiring S] [nontrivial S] {f : R →+* S} (hp : p ≠ 0) : p.map f ≠ 0 := mt (map_eq_zero f).1 hp lemma mem_roots_map [field k] {f : R →+* k} {x : k} (hp : p ≠ 0) : x ∈ (p.map f).roots ↔ p.eval₂ f x = 0 := begin rw mem_roots (show p.map f ≠ 0, by exact map_ne_zero hp), dsimp only [is_root], rw polynomial.eval_map, end lemma mem_root_set [field k] [algebra R k] {x : k} (hp : p ≠ 0) : x ∈ p.root_set k ↔ aeval x p = 0 := iff.trans multiset.mem_to_finset (mem_roots_map hp) lemma root_set_C_mul_X_pow {R S : Type*} [field R] [field S] [algebra R S] {n : ℕ} (hn : n ≠ 0) {a : R} (ha : a ≠ 0) : (C a * X ^ n).root_set S = {0} := begin ext x, rw [set.mem_singleton_iff, mem_root_set, aeval_mul, aeval_C, aeval_X_pow, mul_eq_zero], { simp_rw [ring_hom.map_eq_zero, pow_eq_zero_iff (nat.pos_of_ne_zero hn), or_iff_right_iff_imp], exact λ ha', (ha ha').elim }, { exact mul_ne_zero (mt C_eq_zero.mp ha) (pow_ne_zero n X_ne_zero) }, end lemma root_set_monomial {R S : Type*} [field R] [field S] [algebra R S] {n : ℕ} (hn : n ≠ 0) {a : R} (ha : a ≠ 0) : (monomial n a).root_set S = {0} := by rw [←C_mul_X_pow_eq_monomial, root_set_C_mul_X_pow hn ha] lemma root_set_X_pow {R S : Type*} [field R] [field S] [algebra R S] {n : ℕ} (hn : n ≠ 0) : (X ^ n : polynomial R).root_set S = {0} := by { rw [←one_mul (X ^ n : polynomial R), ←C_1, root_set_C_mul_X_pow hn], exact one_ne_zero } lemma exists_root_of_degree_eq_one (h : degree p = 1) : ∃ x, is_root p x := ⟨-(p.coeff 0 / p.coeff 1), have p.coeff 1 ≠ 0, by rw ← nat_degree_eq_of_degree_eq_some h; exact mt leading_coeff_eq_zero.1 (λ h0, by simpa [h0] using h), by conv in p { rw [eq_X_add_C_of_degree_le_one (show degree p ≤ 1, by rw h; exact le_refl _)] }; simp [is_root, mul_div_cancel' _ this]⟩ lemma coeff_inv_units (u : units (polynomial R)) (n : ℕ) : ((↑u : polynomial R).coeff n)⁻¹ = ((↑u⁻¹ : polynomial R).coeff n) := begin rw [eq_C_of_degree_eq_zero (degree_coe_units u), eq_C_of_degree_eq_zero (degree_coe_units u⁻¹), coeff_C, coeff_C, inv_eq_one_div], split_ifs, { rw [div_eq_iff_mul_eq (coeff_coe_units_zero_ne_zero u), coeff_zero_eq_eval_zero, coeff_zero_eq_eval_zero, ← eval_mul, ← units.coe_mul, inv_mul_self]; simp }, { simp } end lemma monic_normalize (hp0 : p ≠ 0) : monic (normalize p) := begin rw [ne.def, ← leading_coeff_eq_zero, ← ne.def, ← is_unit_iff_ne_zero] at hp0, rw [monic, leading_coeff_normalize, normalize_eq_one], apply hp0, end lemma coe_norm_unit_of_ne_zero (hp : p ≠ 0) : (norm_unit p : polynomial R) = C p.leading_coeff⁻¹ := by simp [hp] lemma normalize_monic (h : monic p) : normalize p = p := by simp [h] theorem map_dvd_map' [field k] (f : R →+* k) {x y : polynomial R} : x.map f ∣ y.map f ↔ x ∣ y := if H : x = 0 then by rw [H, map_zero, zero_dvd_iff, zero_dvd_iff, map_eq_zero] else by rw [← normalize_dvd_iff, ← @normalize_dvd_iff (polynomial R), normalize_apply, normalize_apply, coe_norm_unit_of_ne_zero H, coe_norm_unit_of_ne_zero (mt (map_eq_zero f).1 H), leading_coeff_map, ← f.map_inv, ← map_C, ← map_mul, map_dvd_map _ f.injective (monic_mul_leading_coeff_inv H)] lemma degree_normalize : degree (normalize p) = degree p := by simp lemma prime_of_degree_eq_one (hp1 : degree p = 1) : prime p := have prime (normalize p), from prime_of_degree_eq_one_of_monic (hp1 ▸ degree_normalize) (monic_normalize (λ hp0, absurd hp1 (hp0.symm ▸ by simp; exact dec_trivial))), prime_of_associated normalize_associated this lemma irreducible_of_degree_eq_one (hp1 : degree p = 1) : irreducible p := irreducible_of_prime (prime_of_degree_eq_one hp1) theorem not_irreducible_C (x : R) : ¬irreducible (C x) := if H : x = 0 then by { rw [H, C_0], exact not_irreducible_zero } else λ hx, irreducible.not_unit hx $ is_unit_C.2 $ is_unit_iff_ne_zero.2 H theorem degree_pos_of_irreducible (hp : irreducible p) : 0 < p.degree := lt_of_not_ge $ λ hp0, have _ := eq_C_of_degree_le_zero hp0, not_irreducible_C (p.coeff 0) $ this ▸ hp theorem pairwise_coprime_X_sub {α : Type u} [field α] {I : Type v} {s : I → α} (H : function.injective s) : pairwise (is_coprime on (λ i : I, polynomial.X - polynomial.C (s i))) := λ i j hij, have h : s j - s i ≠ 0, from sub_ne_zero_of_ne $ function.injective.ne H hij.symm, ⟨polynomial.C (s j - s i)⁻¹, -polynomial.C (s j - s i)⁻¹, by rw [neg_mul_eq_neg_mul_symm, ← sub_eq_add_neg, ← mul_sub, sub_sub_sub_cancel_left, ← polynomial.C_sub, ← polynomial.C_mul, inv_mul_cancel h, polynomial.C_1]⟩ /-- If `f` is a polynomial over a field, and `a : K` satisfies `f' a ≠ 0`, then `f / (X - a)` is coprime with `X - a`. Note that we do not assume `f a = 0`, because `f / (X - a) = (f - f a) / (X - a)`. -/ lemma is_coprime_of_is_root_of_eval_derivative_ne_zero {K : Type*} [field K] (f : polynomial K) (a : K) (hf' : f.derivative.eval a ≠ 0) : is_coprime (X - C a : polynomial K) (f /ₘ (X - C a)) := begin refine or.resolve_left (dvd_or_coprime (X - C a) (f /ₘ (X - C a)) (irreducible_of_degree_eq_one (polynomial.degree_X_sub_C a))) _, contrapose! hf' with h, have key : (X - C a) * (f /ₘ (X - C a)) = f - (f %ₘ (X - C a)), { rw [eq_sub_iff_add_eq, ← eq_sub_iff_add_eq', mod_by_monic_eq_sub_mul_div], exact monic_X_sub_C a }, replace key := congr_arg derivative key, simp only [derivative_X, derivative_mul, one_mul, sub_zero, derivative_sub, mod_by_monic_X_sub_C_eq_C_eval, derivative_C] at key, have : (X - C a) ∣ derivative f := key ▸ (dvd_add h (dvd_mul_right _ _)), rw [← dvd_iff_mod_by_monic_eq_zero (monic_X_sub_C _), mod_by_monic_X_sub_C_eq_C_eval] at this, rw [← C_inj, this, C_0], end lemma prod_multiset_root_eq_finset_root {p : polynomial R} (hzero : p ≠ 0) : (multiset.map (λ (a : R), X - C a) p.roots).prod = ∏ a in (multiset.to_finset p.roots), (λ (a : R), (X - C a) ^ (root_multiplicity a p)) a := by simp only [count_roots hzero, finset.prod_multiset_map_count] /-- The product `∏ (X - a)` for `a` inside the multiset `p.roots` divides `p`. -/ lemma prod_multiset_X_sub_C_dvd (p : polynomial R) : (multiset.map (λ (a : R), X - C a) p.roots).prod ∣ p := begin by_cases hp0 : p = 0, { simp only [hp0, roots_zero, is_unit_one, multiset.prod_zero, multiset.map_zero, is_unit.dvd] }, rw prod_multiset_root_eq_finset_root hp0, have hcoprime : pairwise (is_coprime on λ (a : R), polynomial.X - C (id a)) := pairwise_coprime_X_sub function.injective_id, have H : pairwise (is_coprime on λ (a : R), (polynomial.X - C (id a)) ^ (root_multiplicity a p)), { intros a b hdiff, exact (hcoprime a b hdiff).pow }, apply finset.prod_dvd_of_coprime (pairwise.pairwise_on H (↑(multiset.to_finset p.roots) : set R)), intros a h, rw multiset.mem_to_finset at h, exact pow_root_multiplicity_dvd p a end lemma roots_C_mul (p : polynomial R) {a : R} (hzero : a ≠ 0) : (C a * p).roots = p.roots := begin by_cases hpzero : p = 0, { simp only [hpzero, mul_zero] }, rw multiset.ext, intro b, have prodzero : C a * p ≠ 0, { simp only [hpzero, or_false, ne.def, mul_eq_zero, C_eq_zero, hzero, not_false_iff] }, rw [count_roots hpzero, count_roots prodzero, root_multiplicity_mul prodzero], have mulzero : root_multiplicity b (C a) = 0, { simp only [hzero, root_multiplicity_eq_zero, eval_C, is_root.def, not_false_iff] }, simp only [mulzero, zero_add] end lemma roots_normalize : (normalize p).roots = p.roots := begin by_cases hzero : p = 0, { rw [hzero, normalize_zero], }, { have hcoeff : p.leading_coeff ≠ 0, { intro h, exact hzero (leading_coeff_eq_zero.1 h) }, rw [normalize_apply, mul_comm, coe_norm_unit_of_ne_zero hzero, roots_C_mul _ (inv_ne_zero hcoeff)], }, end end field end polynomial
b82e7f494752eda33123178cfbb70816a0899204
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/library/logic/wf_k.lean
9c91cc2f65bcad191124c14e1c5ae3912d35f217
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
758
lean
-- Copyright (c) 2014 Microsoft Corporation. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Leonardo de Moura import logic.wf data.nat.basic namespace well_founded -- This is an auxiliary definition that useful for generating a new "proof" for (well_founded R) -- that allows us to use well_founded.fix and execute the definitions up to k nested recursive -- calls without "computing" with the proofs in Hwf. definition intro_k {A : Type} {R : A → A → Prop} (Hwf : well_founded R) (k : nat) : well_founded R := well_founded.intro (nat.rec_on k (λ n : A, well_founded.apply Hwf n) (λ (k' : nat) (f : Πa, acc R a), (λ n : A, acc.intro n (λ y H, f y)))) end well_founded
3a693429ffe0e4a9f5a99fd664c78cae2b0e00cb
e151e9053bfd6d71740066474fc500a087837323
/tests/induction.lean
d3e69a168dc4b7d63bc5b16c7bb80baee4b5eb25
[ "Apache-2.0" ]
permissive
daniel-carranza/hott3
15bac2d90589dbb952ef15e74b2837722491963d
913811e8a1371d3a5751d7d32ff9dec8aa6815d9
refs/heads/master
1,610,091,349,670
1,596,222,336,000
1,596,222,336,000
241,957,822
0
0
Apache-2.0
1,582,222,839,000
1,582,222,838,000
null
UTF-8
Lean
false
false
8,294
lean
import hott.init open expr tactic pexpr hott universes u v noncomputable theory axiom sorry' : Π{α : Sort _}, α /- no warnings are generated when using this axiom -/ @[induction] def foo2 {X Y : Type} {P : X × Y → Type} (x : X × Y) (z : Πa b, P ⟨a, b⟩) : P x := sorry' @[induction] def foo3 {P : ℕ × ℕ → Sort _} (x : ℕ × ℕ) (z : ℕ → P (0,0)) : P x := sorry' @[induction] def foo4 {X Y : Type} {P : Type} (x : X × Y) (z : X → Y → P) : P := sorry' @[induction] def foo5 {X : Type} {P : Type} (x : ℕ × X) (z : X → X → P) : P := sorry' @[induction] def foo6 {P : hott.trunc -2 nat → Type} (x : hott.trunc -2 nat) (z : Π(n : ℕ), P (hott.trunc.tr n)) : P x := sorry' @[induction] def foo7 {P : hott.trunc -2 nat → Type _} (x : hott.trunc -2 nat) (z : Πx, P x → P x) : (ℕ → P (hott.trunc.tr 0)) → P x := sorry' @[induction] def foo8 {P : hott.trunc -2 nat → Type _} (x : hott.trunc -2 nat) : P x := sorry' @[induction] def foo9 (n : ℕ₋₂) (A : Type _) {P : hott.trunc n A → Type _} (x : hott.trunc n A) : (Πx, P x) → P x := sorry' @[induction] def foo10 (n : ℕ₋₂) (A : Type _) {P : Type _} (x : hott.trunc n A) : (ℕ → P) → P := sorry' attribute [induction] trunc.rec attribute [induction] hott.quotient.rec attribute [induction, priority 2000] hott.trunc.rec attribute [induction] hott.eq.idp_rec_on attribute [induction] hott.eq.idp_rec_on attribute [induction] hott.eq.rec attribute [induction] prod.elim def foo11 {X : Type} {P : Type} (x : X) (z : X → X → P) : P := sorry' def foo12 {X : Type} {P : Type} (x : ℕ × X) (z : x = x → P) : P := sorry' def foo13 {X : Type} {P : Type} (x : ℕ) (z : P) : P := sorry' run_cmd success_if_fail $ get_induction_info `foo11 run_cmd success_if_fail $ get_induction_info `foo12 run_cmd success_if_fail $ get_induction_info `foo13 def indfoo {X Y : Type} (x : hott.trunc -2 nat) : hott.eq x x := begin hinduction x using foo7 with x' p n, all_goals { exact sorry' } end def indfoo2 (x : ℕ) (y : ℕ) : x = x := begin hinduction x with n IH, all_goals { exact sorry' } end def indfoo3 {X Y : Type} {P : bool × bool → Type} (x : bool × bool) (z : Πx, P x) : P x := begin hinduction x, exact sorry' end def indfoo4 {X Y : Type} {P : Type} (x : bool × bool) (z : P) : P := begin success_if_fail { hinduction x using foo5 }, hinduction x, exact sorry' end def indfoo5 {X Y : Type} {P : hott.trunc -2 nat → Type} (x : hott.trunc -2 nat) (z : Πx, P x) : P x := begin hinduction x, exact sorry' end def indfoo6 {X Y : Type} (x : hott.trunc -2 nat) : hott.eq x x := begin hinduction x using trunc.rec with x' p n, reflexivity end def indfoo7 {X Y : Type} (x : id (hott.trunc -2 nat)) : hott.eq x x := begin hinduction x using trunc.rec with x' p n, reflexivity end def indfoo8 {X Y : Type} (x : id (hott.trunc -2 nat)) : hott.eq x x := begin hinduction x with x' p n, reflexivity end example {X Y : Type} (x : hott.trunc -2 nat) : hott.eq x x := begin hinduction x using foo8 with x' p n end example {X Y : Type} (x : hott.trunc -2 nat) : hott.eq x x := begin hinduction x using foo9 with x' p n, all_goals { exact sorry' } end example {X Y : Type} (x : hott.trunc -2 nat) : hott.eq x x := begin success_if_fail { hinduction x using foo10 with x' p n }, exact sorry' end example (x : ℕ) (y : ℕ) : x = x := begin hinduction x using nat.rec with n IH generalizing y, all_goals { exact sorry' } end example (x : ℕ) (y : ℕ) : x = x := begin revert y, hinduction x using nat.rec with n IH, all_goals { intro }, all_goals { exact sorry' } end example (x : ℕ) (p : x = 3) : x = x := begin hinduction x using nat.rec with n IH, all_goals { exact sorry' } end example (x : ℕ) : let y := x in Π(p : y = y), x = y := begin intros _ _, hinduction x using nat.rec with n IH generalizing y, all_goals { exact sorry' } end hott_theory -- set_option trace.hinduction true example {A : Type} {a b : A} {f : A → A} (p : f a = b) : unit := begin hinduction p using hott.eq.rec, constructor end example {A : Type} {a : A} {f : A → A} (p : f a = a) : unit := begin success_if_fail { hinduction p using hott.eq.rec }, constructor end example {A : Type} {a : A} {f : A → A} (p : f a = a) : unit := begin success_if_fail { hinduction p }, constructor end example {A : Type} {a : A} {f : A → A} (p : f a = a) : unit := begin success_if_fail { hinduction p using hott.eq.rec }, constructor end example {A : Type} {a b : A} {f : A → A} (p : f a = id b) : unit := begin hinduction p using hott.eq.rec, constructor end example {A : Type} {a b : A} {f : A → A} (p : f a = let u := b in b) : unit := begin hinduction p using hott.eq.rec, constructor end example {A : Type} {a b : A} {f : A → A} (p : f a = let u := b in u) : unit := begin hinduction p using hott.eq.rec, constructor end -- example {A B : Type} {a b : A → B} {f : (A → B) → A → B} (p : f a = λx, b x) : unit := -- begin hinduction p using hott.eq.rec, constructor end example {A : Type} {a b : A} {f : A → A} (p : f a = (λx, x) b) : unit := begin hinduction p using hott.eq.rec, constructor end @[induction] def eqrec1 {A : Type u} {a : A} {C : Π (a' : A), a = a' → Sort v} (H : C a (refl a)) {a' : A} (n : a = a') : C a' n := sorry' @[induction] def eqrec2 {A : Type u} {a : A} {C : a = a → Sort v} (H : C (refl a)) (n : a = a) : C n := sorry' @[induction] def eqrec3 {A : Type u} {C : Π (a' : A), a' = a' → Sort v} (H : Πa, C a (refl a)) {a : A} (n : a = a) : C a n := sorry' @[induction] def eqrec4 {A : Type u} {a : A} {C : A → Sort v} (H : C a) {a' : A} (n : a = a') : C a' := sorry' @[induction] def eqrec5 {A : Type u} {a : A} {C : Sort v} (H : C) {a' : A} (n : a = a') : C := sorry' attribute [induction] pathover.rec idp_rec_on -- #print eqrec1._ind_info -- #print eqrec2._ind_info -- #print eqrec3._ind_info -- #print eqrec4._ind_info -- #print eqrec5._ind_info /- test unfolding of type of induction variable -/ def list2 (α : Type u) : Type u := list (prod α α) def list3 (α : Type u) : Type u := list2 (prod α α) @[induction] def list2rec {α} (P : list2 α → Type) (H1 : P []) (H2 : Πx y l, P l → P ((x,y)::l)) : Πx, P x := by intro x; hinduction x; [exact H1, {induction hd; exact H2 _ _ _ ih}] example {α} (x : list3 α) : x = x := by hinduction x using list2rec; refl open hott.trunc hott.is_trunc @[hott] def trunc_sigma_equiv {n : ℕ₋₂} {A : Type _} {P : A → Type _} : trunc n (Σ x, P x) ≃ trunc n (Σ x, trunc n (P x)) := begin fapply equiv.MK; intro x, { hinduction x with p, exact tr ⟨p.1, tr p.2⟩ }, { hinduction x with p, induction p with a p, hinduction p with p, exact tr ⟨a, p⟩ }, all_goals { exact sorry' } end @[hott] def trunc_sigma_equiv2 {n : ℕ₋₂} {A : Type _} {P : A → Type _} : trunc n (Σ x, P x) ≃ trunc n (Σ x, trunc n (P x)) := begin fapply equiv.MK; intro x, { hinduction x with p, exact tr ⟨p.1, tr p.2⟩ }, { hinduction x with p, have x := p.2, hinduction x with q, exact tr ⟨p.1, q⟩ }, all_goals { exact sorry' } end set_option trace.hinduction true -- attribute [induction] homotopy.rec_on -- #print homotopy.rec_on -- -- #print homotopy.rec_on._ind_info -- @[hott] example {A B : Type _} {f g : A → B} (h : f ~ g) : unit := -- begin hinduction h using homotopy.rec_on, constructor end -- @[hott] example {A : Type _} {B : A → Type _} {f g : Πx, B x} (h : @homotopy A B f g) : unit := -- begin hinduction h using homotopy.rec_on, constructor end def eqrecfail1 {A : Type u} {a : A} {C : Π (a' : A), a = a' → Sort v} (H : C a (refl a)) {a' : A} (n : a = a') : C (id a') n := sorry' def eqrecfail2 {A : Type u} {a : A} {C : Π (a' : A), a = a' → Sort v} (H : C a (refl a)) {a' : A} (n : a = a') : C a' (n ⬝ idp) := sorry' def eqrecfail3 {A : Type u} {a : A} {C : Π (a' : A), a = a' → Sort v} (H : C a (refl a)) {a' : A} (n : a = id a') : C a' n := sorry' run_cmd success_if_fail $ get_induction_info `eqrecfail1 run_cmd success_if_fail $ get_induction_info `eqrecfail2 -- run_cmd success_if_fail $ get_induction_info `eqrecfail3 --run_cmd success_if_fail $ get_induction_info `eqrecfail4 -- #print eqrec1._ind_info -- #print idp_rec_on._ind_info -- #print idp_rec_on
c5588d685ec0d81185cd5cfc349738566029110d
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/blast_ematch_heq1.lean
67df52e1b8ca69750babc7ac48e65685b33dfec0
[ "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
248
lean
import data.nat open algebra nat section open nat set_option blast.strategy "ematch" set_option blast.cc.heq true attribute add.comm [forward] attribute add.assoc [forward] example (a b c : nat) : a + b + b + c = c + b + a + b := by blast end
5dc041c1a9ff4311e0c20636ce520e8a67af1930
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/data/rbtree/min_max.lean
f816bb54e0c0bbf5c6f0b87f70c4a82ac6a2dd5d
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
1,449
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 -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.Lean3Lib.data.rbtree.basic universes u namespace Mathlib namespace rbnode theorem mem_of_min_eq {α : Type u} (lt : α → α → Prop) [is_irrefl α lt] {a : α} {t : rbnode α} : rbnode.min t = some a → mem lt a t := sorry theorem mem_of_max_eq {α : Type u} (lt : α → α → Prop) [is_irrefl α lt] {a : α} {t : rbnode α} : rbnode.max t = some a → mem lt a t := sorry theorem eq_leaf_of_min_eq_none {α : Type u} {t : rbnode α} : rbnode.min t = none → t = leaf := sorry theorem eq_leaf_of_max_eq_none {α : Type u} {t : rbnode α} : rbnode.max t = none → t = leaf := sorry theorem min_is_minimal {α : Type u} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] {a : α} {t : rbnode α} {lo : Option α} {hi : Option α} : is_searchable lt t lo hi → rbnode.min t = some a → ∀ {b : α}, mem lt b t → strict_weak_order.equiv a b ∨ lt a b := sorry theorem max_is_maximal {α : Type u} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] {a : α} {t : rbnode α} {lo : Option α} {hi : Option α} : is_searchable lt t lo hi → rbnode.max t = some a → ∀ {b : α}, mem lt b t → strict_weak_order.equiv a b ∨ lt b a := sorry
bb6c4a6e3f0c778fabd3b69c022c10defed283df
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/topology/homeomorph.lean
20f2d0e48b7016e02975342752bf36a483f04feb
[ "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
20,974
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Patrick Massot, Sébastien Gouëzel, Zhouhang Zhou, Reid Barton -/ import logic.equiv.fin import topology.dense_embedding import topology.support /-! # Homeomorphisms This file defines homeomorphisms between two topological spaces. They are bijections with both directions continuous. We denote homeomorphisms with the notation `≃ₜ`. # Main definitions * `homeomorph α β`: The type of homeomorphisms from `α` to `β`. This type can be denoted using the following notation: `α ≃ₜ β`. # Main results * Pretty much every topological property is preserved under homeomorphisms. * `homeomorph.homeomorph_of_continuous_open`: A continuous bijection that is an open map is a homeomorphism. -/ open set filter open_locale topological_space variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} /-- Homeomorphism between `α` and `β`, also called topological isomorphism -/ @[nolint has_nonempty_instance] -- not all spaces are homeomorphic to each other structure homeomorph (α : Type*) (β : Type*) [topological_space α] [topological_space β] extends α ≃ β := (continuous_to_fun : continuous to_fun . tactic.interactive.continuity') (continuous_inv_fun : continuous inv_fun . tactic.interactive.continuity') infix ` ≃ₜ `:25 := homeomorph namespace homeomorph variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] instance : has_coe_to_fun (α ≃ₜ β) (λ _, α → β) := ⟨λe, e.to_equiv⟩ @[simp] lemma homeomorph_mk_coe (a : equiv α β) (b c) : ((homeomorph.mk a b c) : α → β) = a := rfl /-- Inverse of a homeomorphism. -/ protected def symm (h : α ≃ₜ β) : β ≃ₜ α := { continuous_to_fun := h.continuous_inv_fun, continuous_inv_fun := h.continuous_to_fun, to_equiv := h.to_equiv.symm } /-- See Note [custom simps projection]. We need to specify this projection explicitly in this case, because it is a composition of multiple projections. -/ def simps.apply (h : α ≃ₜ β) : α → β := h /-- See Note [custom simps projection] -/ def simps.symm_apply (h : α ≃ₜ β) : β → α := h.symm initialize_simps_projections homeomorph (to_equiv_to_fun → apply, to_equiv_inv_fun → symm_apply, -to_equiv) @[simp] lemma coe_to_equiv (h : α ≃ₜ β) : ⇑h.to_equiv = h := rfl @[simp] lemma coe_symm_to_equiv (h : α ≃ₜ β) : ⇑h.to_equiv.symm = h.symm := rfl lemma to_equiv_injective : function.injective (to_equiv : α ≃ₜ β → α ≃ β) | ⟨e, h₁, h₂⟩ ⟨e', h₁', h₂'⟩ rfl := rfl @[ext] lemma ext {h h' : α ≃ₜ β} (H : ∀ x, h x = h' x) : h = h' := to_equiv_injective $ equiv.ext H /-- Identity map as a homeomorphism. -/ @[simps apply {fully_applied := ff}] protected def refl (α : Type*) [topological_space α] : α ≃ₜ α := { continuous_to_fun := continuous_id, continuous_inv_fun := continuous_id, to_equiv := equiv.refl α } /-- Composition of two homeomorphisms. -/ protected def trans (h₁ : α ≃ₜ β) (h₂ : β ≃ₜ γ) : α ≃ₜ γ := { continuous_to_fun := h₂.continuous_to_fun.comp h₁.continuous_to_fun, continuous_inv_fun := h₁.continuous_inv_fun.comp h₂.continuous_inv_fun, to_equiv := equiv.trans h₁.to_equiv h₂.to_equiv } @[simp] lemma trans_apply (h₁ : α ≃ₜ β) (h₂ : β ≃ₜ γ) (a : α) : h₁.trans h₂ a = h₂ (h₁ a) := rfl @[simp] lemma homeomorph_mk_coe_symm (a : equiv α β) (b c) : ((homeomorph.mk a b c).symm : β → α) = a.symm := rfl @[simp] lemma refl_symm : (homeomorph.refl α).symm = homeomorph.refl α := rfl @[continuity] protected lemma continuous (h : α ≃ₜ β) : continuous h := h.continuous_to_fun @[continuity] -- otherwise `by continuity` can't prove continuity of `h.to_equiv.symm` protected lemma continuous_symm (h : α ≃ₜ β) : continuous (h.symm) := h.continuous_inv_fun @[simp] lemma apply_symm_apply (h : α ≃ₜ β) (x : β) : h (h.symm x) = x := h.to_equiv.apply_symm_apply x @[simp] lemma symm_apply_apply (h : α ≃ₜ β) (x : α) : h.symm (h x) = x := h.to_equiv.symm_apply_apply x @[simp] lemma self_trans_symm (h : α ≃ₜ β) : h.trans h.symm = homeomorph.refl α := by { ext, apply symm_apply_apply } @[simp] lemma symm_trans_self (h : α ≃ₜ β) : h.symm.trans h = homeomorph.refl β := by { ext, apply apply_symm_apply } protected lemma bijective (h : α ≃ₜ β) : function.bijective h := h.to_equiv.bijective protected lemma injective (h : α ≃ₜ β) : function.injective h := h.to_equiv.injective protected lemma surjective (h : α ≃ₜ β) : function.surjective h := h.to_equiv.surjective /-- Change the homeomorphism `f` to make the inverse function definitionally equal to `g`. -/ def change_inv (f : α ≃ₜ β) (g : β → α) (hg : function.right_inverse g f) : α ≃ₜ β := have g = f.symm, from funext (λ x, calc g x = f.symm (f (g x)) : (f.left_inv (g x)).symm ... = f.symm x : by rw hg x), { to_fun := f, inv_fun := g, left_inv := by convert f.left_inv, right_inv := by convert f.right_inv, continuous_to_fun := f.continuous, continuous_inv_fun := by convert f.symm.continuous } @[simp] lemma symm_comp_self (h : α ≃ₜ β) : ⇑h.symm ∘ ⇑h = id := funext h.symm_apply_apply @[simp] lemma self_comp_symm (h : α ≃ₜ β) : ⇑h ∘ ⇑h.symm = id := funext h.apply_symm_apply @[simp] lemma range_coe (h : α ≃ₜ β) : range h = univ := h.surjective.range_eq lemma image_symm (h : α ≃ₜ β) : image h.symm = preimage h := funext h.symm.to_equiv.image_eq_preimage lemma preimage_symm (h : α ≃ₜ β) : preimage h.symm = image h := (funext h.to_equiv.image_eq_preimage).symm @[simp] lemma image_preimage (h : α ≃ₜ β) (s : set β) : h '' (h ⁻¹' s) = s := h.to_equiv.image_preimage s @[simp] lemma preimage_image (h : α ≃ₜ β) (s : set α) : h ⁻¹' (h '' s) = s := h.to_equiv.preimage_image s protected lemma inducing (h : α ≃ₜ β) : inducing h := inducing_of_inducing_compose h.continuous h.symm.continuous $ by simp only [symm_comp_self, inducing_id] lemma induced_eq (h : α ≃ₜ β) : topological_space.induced h ‹_› = ‹_› := h.inducing.1.symm protected lemma quotient_map (h : α ≃ₜ β) : quotient_map h := quotient_map.of_quotient_map_compose h.symm.continuous h.continuous $ by simp only [self_comp_symm, quotient_map.id] lemma coinduced_eq (h : α ≃ₜ β) : topological_space.coinduced h ‹_› = ‹_› := h.quotient_map.2.symm protected lemma embedding (h : α ≃ₜ β) : embedding h := ⟨h.inducing, h.injective⟩ /-- Homeomorphism given an embedding. -/ noncomputable def of_embedding (f : α → β) (hf : embedding f) : α ≃ₜ (set.range f) := { continuous_to_fun := continuous_subtype_mk _ hf.continuous, continuous_inv_fun := by simp [hf.continuous_iff, continuous_subtype_coe], .. equiv.of_injective f hf.inj } protected lemma second_countable_topology [topological_space.second_countable_topology β] (h : α ≃ₜ β) : topological_space.second_countable_topology α := h.inducing.second_countable_topology lemma compact_image {s : set α} (h : α ≃ₜ β) : is_compact (h '' s) ↔ is_compact s := h.embedding.is_compact_iff_is_compact_image.symm lemma compact_preimage {s : set β} (h : α ≃ₜ β) : is_compact (h ⁻¹' s) ↔ is_compact s := by rw ← image_symm; exact h.symm.compact_image @[simp] lemma comap_cocompact (h : α ≃ₜ β) : comap h (cocompact β) = cocompact α := (comap_cocompact_le h.continuous).antisymm $ (has_basis_cocompact.le_basis_iff (has_basis_cocompact.comap h)).2 $ λ K hK, ⟨h ⁻¹' K, h.compact_preimage.2 hK, subset.rfl⟩ @[simp] lemma map_cocompact (h : α ≃ₜ β) : map h (cocompact α) = cocompact β := by rw [← h.comap_cocompact, map_comap_of_surjective h.surjective] protected lemma compact_space [compact_space α] (h : α ≃ₜ β) : compact_space β := { compact_univ := by { rw [← image_univ_of_surjective h.surjective, h.compact_image], apply compact_space.compact_univ } } protected lemma t0_space [t0_space α] (h : α ≃ₜ β) : t0_space β := h.symm.embedding.t0_space protected lemma t1_space [t1_space α] (h : α ≃ₜ β) : t1_space β := h.symm.embedding.t1_space protected lemma t2_space [t2_space α] (h : α ≃ₜ β) : t2_space β := h.symm.embedding.t2_space protected lemma t3_space [t3_space α] (h : α ≃ₜ β) : t3_space β := h.symm.embedding.t3_space protected lemma dense_embedding (h : α ≃ₜ β) : dense_embedding h := { dense := h.surjective.dense_range, .. h.embedding } @[simp] lemma is_open_preimage (h : α ≃ₜ β) {s : set β} : is_open (h ⁻¹' s) ↔ is_open s := h.quotient_map.is_open_preimage @[simp] lemma is_open_image (h : α ≃ₜ β) {s : set α} : is_open (h '' s) ↔ is_open s := by rw [← preimage_symm, is_open_preimage] protected lemma is_open_map (h : α ≃ₜ β) : is_open_map h := λ s, h.is_open_image.2 @[simp] lemma is_closed_preimage (h : α ≃ₜ β) {s : set β} : is_closed (h ⁻¹' s) ↔ is_closed s := by simp only [← is_open_compl_iff, ← preimage_compl, is_open_preimage] @[simp] lemma is_closed_image (h : α ≃ₜ β) {s : set α} : is_closed (h '' s) ↔ is_closed s := by rw [← preimage_symm, is_closed_preimage] protected lemma is_closed_map (h : α ≃ₜ β) : is_closed_map h := λ s, h.is_closed_image.2 protected lemma open_embedding (h : α ≃ₜ β) : open_embedding h := open_embedding_of_embedding_open h.embedding h.is_open_map protected lemma closed_embedding (h : α ≃ₜ β) : closed_embedding h := closed_embedding_of_embedding_closed h.embedding h.is_closed_map protected lemma normal_space [normal_space α] (h : α ≃ₜ β) : normal_space β := h.symm.closed_embedding.normal_space lemma preimage_closure (h : α ≃ₜ β) (s : set β) : h ⁻¹' (closure s) = closure (h ⁻¹' s) := h.is_open_map.preimage_closure_eq_closure_preimage h.continuous _ lemma image_closure (h : α ≃ₜ β) (s : set α) : h '' (closure s) = closure (h '' s) := by rw [← preimage_symm, preimage_closure] lemma preimage_interior (h : α ≃ₜ β) (s : set β) : h⁻¹' (interior s) = interior (h ⁻¹' s) := h.is_open_map.preimage_interior_eq_interior_preimage h.continuous _ lemma image_interior (h : α ≃ₜ β) (s : set α) : h '' (interior s) = interior (h '' s) := by rw [← preimage_symm, preimage_interior] lemma preimage_frontier (h : α ≃ₜ β) (s : set β) : h ⁻¹' (frontier s) = frontier (h ⁻¹' s) := h.is_open_map.preimage_frontier_eq_frontier_preimage h.continuous _ @[to_additive] lemma _root_.has_compact_mul_support.comp_homeomorph {M} [has_one M] {f : β → M} (hf : has_compact_mul_support f) (φ : α ≃ₜ β) : has_compact_mul_support (f ∘ φ) := hf.comp_closed_embedding φ.closed_embedding @[simp] lemma map_nhds_eq (h : α ≃ₜ β) (x : α) : map h (𝓝 x) = 𝓝 (h x) := h.embedding.map_nhds_of_mem _ (by simp) lemma symm_map_nhds_eq (h : α ≃ₜ β) (x : α) : map h.symm (𝓝 (h x)) = 𝓝 x := by rw [h.symm.map_nhds_eq, h.symm_apply_apply] lemma nhds_eq_comap (h : α ≃ₜ β) (x : α) : 𝓝 x = comap h (𝓝 (h x)) := h.embedding.to_inducing.nhds_eq_comap x @[simp] lemma comap_nhds_eq (h : α ≃ₜ β) (y : β) : comap h (𝓝 y) = 𝓝 (h.symm y) := by rw [h.nhds_eq_comap, h.apply_symm_apply] /-- If an bijective map `e : α ≃ β` is continuous and open, then it is a homeomorphism. -/ def homeomorph_of_continuous_open (e : α ≃ β) (h₁ : continuous e) (h₂ : is_open_map e) : α ≃ₜ β := { continuous_to_fun := h₁, continuous_inv_fun := begin rw continuous_def, intros s hs, convert ← h₂ s hs using 1, apply e.image_eq_preimage end, to_equiv := e } @[simp] lemma comp_continuous_on_iff (h : α ≃ₜ β) (f : γ → α) (s : set γ) : continuous_on (h ∘ f) s ↔ continuous_on f s := h.inducing.continuous_on_iff.symm @[simp] lemma comp_continuous_iff (h : α ≃ₜ β) {f : γ → α} : continuous (h ∘ f) ↔ continuous f := h.inducing.continuous_iff.symm @[simp] lemma comp_continuous_iff' (h : α ≃ₜ β) {f : β → γ} : continuous (f ∘ h) ↔ continuous f := h.quotient_map.continuous_iff.symm lemma comp_continuous_at_iff (h : α ≃ₜ β) (f : γ → α) (x : γ) : continuous_at (h ∘ f) x ↔ continuous_at f x := h.inducing.continuous_at_iff.symm lemma comp_continuous_at_iff' (h : α ≃ₜ β) (f : β → γ) (x : α) : continuous_at (f ∘ h) x ↔ continuous_at f (h x) := h.inducing.continuous_at_iff' (by simp) lemma comp_continuous_within_at_iff (h : α ≃ₜ β) (f : γ → α) (s : set γ) (x : γ) : continuous_within_at f s x ↔ continuous_within_at (h ∘ f) s x := h.inducing.continuous_within_at_iff @[simp] lemma comp_is_open_map_iff (h : α ≃ₜ β) {f : γ → α} : is_open_map (h ∘ f) ↔ is_open_map f := begin refine ⟨_, λ hf, h.is_open_map.comp hf⟩, intros hf, rw [← function.comp.left_id f, ← h.symm_comp_self, function.comp.assoc], exact h.symm.is_open_map.comp hf, end @[simp] lemma comp_is_open_map_iff' (h : α ≃ₜ β) {f : β → γ} : is_open_map (f ∘ h) ↔ is_open_map f := begin refine ⟨_, λ hf, hf.comp h.is_open_map⟩, intros hf, rw [← function.comp.right_id f, ← h.self_comp_symm, ← function.comp.assoc], exact hf.comp h.symm.is_open_map, end /-- If two sets are equal, then they are homeomorphic. -/ def set_congr {s t : set α} (h : s = t) : s ≃ₜ t := { continuous_to_fun := continuous_subtype_mk _ continuous_subtype_val, continuous_inv_fun := continuous_subtype_mk _ continuous_subtype_val, to_equiv := equiv.set_congr h } /-- Sum of two homeomorphisms. -/ def sum_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) : α ⊕ γ ≃ₜ β ⊕ δ := { continuous_to_fun := h₁.continuous.sum_map h₂.continuous, continuous_inv_fun := h₁.symm.continuous.sum_map h₂.symm.continuous, to_equiv := h₁.to_equiv.sum_congr h₂.to_equiv } /-- Product of two homeomorphisms. -/ def prod_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) : α × γ ≃ₜ β × δ := { continuous_to_fun := (h₁.continuous.comp continuous_fst).prod_mk (h₂.continuous.comp continuous_snd), continuous_inv_fun := (h₁.symm.continuous.comp continuous_fst).prod_mk (h₂.symm.continuous.comp continuous_snd), to_equiv := h₁.to_equiv.prod_congr h₂.to_equiv } @[simp] lemma prod_congr_symm (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) : (h₁.prod_congr h₂).symm = h₁.symm.prod_congr h₂.symm := rfl @[simp] lemma coe_prod_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) : ⇑(h₁.prod_congr h₂) = prod.map h₁ h₂ := rfl section variables (α β γ) /-- `α × β` is homeomorphic to `β × α`. -/ def prod_comm : α × β ≃ₜ β × α := { continuous_to_fun := continuous_snd.prod_mk continuous_fst, continuous_inv_fun := continuous_snd.prod_mk continuous_fst, to_equiv := equiv.prod_comm α β } @[simp] lemma prod_comm_symm : (prod_comm α β).symm = prod_comm β α := rfl @[simp] lemma coe_prod_comm : ⇑(prod_comm α β) = prod.swap := rfl /-- `(α × β) × γ` is homeomorphic to `α × (β × γ)`. -/ def prod_assoc : (α × β) × γ ≃ₜ α × (β × γ) := { continuous_to_fun := (continuous_fst.comp continuous_fst).prod_mk ((continuous_snd.comp continuous_fst).prod_mk continuous_snd), continuous_inv_fun := (continuous_fst.prod_mk (continuous_fst.comp continuous_snd)).prod_mk (continuous_snd.comp continuous_snd), to_equiv := equiv.prod_assoc α β γ } /-- `α × {*}` is homeomorphic to `α`. -/ @[simps apply {fully_applied := ff}] def prod_punit : α × punit ≃ₜ α := { to_equiv := equiv.prod_punit α, continuous_to_fun := continuous_fst, continuous_inv_fun := continuous_id.prod_mk continuous_const } /-- `{*} × α` is homeomorphic to `α`. -/ def punit_prod : punit × α ≃ₜ α := (prod_comm _ _).trans (prod_punit _) @[simp] lemma coe_punit_prod : ⇑(punit_prod α) = prod.snd := rfl end /-- `ulift α` is homeomorphic to `α`. -/ def {u v} ulift {α : Type u} [topological_space α] : ulift.{v u} α ≃ₜ α := { continuous_to_fun := continuous_ulift_down, continuous_inv_fun := continuous_ulift_up, to_equiv := equiv.ulift } section distrib /-- `(α ⊕ β) × γ` is homeomorphic to `α × γ ⊕ β × γ`. -/ def sum_prod_distrib : (α ⊕ β) × γ ≃ₜ α × γ ⊕ β × γ := homeomorph.symm $ homeomorph_of_continuous_open (equiv.sum_prod_distrib α β γ).symm ((continuous_inl.prod_map continuous_id).sum_elim (continuous_inr.prod_map continuous_id)) $ is_open_map_sum (open_embedding_inl.is_open_map.prod is_open_map.id) (open_embedding_inr.is_open_map.prod is_open_map.id) /-- `α × (β ⊕ γ)` is homeomorphic to `α × β ⊕ α × γ`. -/ def prod_sum_distrib : α × (β ⊕ γ) ≃ₜ α × β ⊕ α × γ := (prod_comm _ _).trans $ sum_prod_distrib.trans $ sum_congr (prod_comm _ _) (prod_comm _ _) variables {ι : Type*} {σ : ι → Type*} [Π i, topological_space (σ i)] /-- `(Σ i, σ i) × β` is homeomorphic to `Σ i, (σ i × β)`. -/ def sigma_prod_distrib : ((Σ i, σ i) × β) ≃ₜ (Σ i, (σ i × β)) := homeomorph.symm $ homeomorph_of_continuous_open (equiv.sigma_prod_distrib σ β).symm (continuous_sigma $ λ i, (continuous_sigma_mk.comp continuous_fst).prod_mk continuous_snd) (is_open_map_sigma $ λ i, (open_embedding_sigma_mk.prod open_embedding_id).is_open_map) end distrib /-- If `ι` has a unique element, then `ι → α` is homeomorphic to `α`. -/ @[simps { fully_applied := ff }] def fun_unique (ι α : Type*) [unique ι] [topological_space α] : (ι → α) ≃ₜ α := { to_equiv := equiv.fun_unique ι α, continuous_to_fun := continuous_apply _, continuous_inv_fun := continuous_pi (λ _, continuous_id) } /-- Homeomorphism between dependent functions `Π i : fin 2, α i` and `α 0 × α 1`. -/ @[simps { fully_applied := ff }] def {u} pi_fin_two (α : fin 2 → Type u) [Π i, topological_space (α i)] : (Π i, α i) ≃ₜ α 0 × α 1 := { to_equiv := pi_fin_two_equiv α, continuous_to_fun := (continuous_apply 0).prod_mk (continuous_apply 1), continuous_inv_fun := continuous_pi $ fin.forall_fin_two.2 ⟨continuous_fst, continuous_snd⟩ } /-- Homeomorphism between `α² = fin 2 → α` and `α × α`. -/ @[simps { fully_applied := ff }] def fin_two_arrow : (fin 2 → α) ≃ₜ α × α := { to_equiv := fin_two_arrow_equiv α, .. pi_fin_two (λ _, α) } /-- A subset of a topological space is homeomorphic to its image under a homeomorphism. -/ @[simps] def image (e : α ≃ₜ β) (s : set α) : s ≃ₜ e '' s := { continuous_to_fun := by continuity!, continuous_inv_fun := by continuity!, to_equiv := e.to_equiv.image s, } /-- `set.univ α` is homeomorphic to `α`. -/ @[simps { fully_applied := ff }] def set.univ (α : Type*) [topological_space α] : (univ : set α) ≃ₜ α := { to_equiv := equiv.set.univ α, continuous_to_fun := continuous_subtype_coe, continuous_inv_fun := continuous_subtype_mk _ continuous_id } /-- `s ×ˢ t` is homeomorphic to `s × t`. -/ @[simps] def set.prod (s : set α) (t : set β) : ↥(s ×ˢ t) ≃ₜ s × t := { to_equiv := equiv.set.prod s t, continuous_to_fun := continuous.prod_mk (continuous_subtype_mk _ (continuous_fst.comp continuous_induced_dom)) (continuous_subtype_mk _ (continuous_snd.comp continuous_induced_dom)), continuous_inv_fun := continuous_subtype_mk _ (continuous.prod_mk (continuous_induced_dom.comp continuous_fst) (continuous_induced_dom.comp continuous_snd)) } end homeomorph /-- An inducing equiv between topological spaces is a homeomorphism. -/ @[simps] def equiv.to_homeomorph_of_inducing [topological_space α] [topological_space β] (f : α ≃ β) (hf : inducing f) : α ≃ₜ β := { continuous_to_fun := hf.continuous, continuous_inv_fun := hf.continuous_iff.2 $ by simpa using continuous_id, .. f } namespace continuous variables [topological_space α] [topological_space β] lemma continuous_symm_of_equiv_compact_to_t2 [compact_space α] [t2_space β] {f : α ≃ β} (hf : continuous f) : continuous f.symm := begin rw continuous_iff_is_closed, intros C hC, have hC' : is_closed (f '' C) := (hC.is_compact.image hf).is_closed, rwa equiv.image_eq_preimage at hC', end /-- Continuous equivalences from a compact space to a T2 space are homeomorphisms. This is not true when T2 is weakened to T1 (see `continuous.homeo_of_equiv_compact_to_t2.t1_counterexample`). -/ @[simps] def homeo_of_equiv_compact_to_t2 [compact_space α] [t2_space β] {f : α ≃ β} (hf : continuous f) : α ≃ₜ β := { continuous_to_fun := hf, continuous_inv_fun := hf.continuous_symm_of_equiv_compact_to_t2, ..f } end continuous
b075dbfb1707b86f668565c95e2a54e7f260fd78
367134ba5a65885e863bdc4507601606690974c1
/src/set_theory/cardinal.lean
d118b5f321b92cde6f2af55d3f0ec58050d99298
[ "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
51,505
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, Floris van Doorn -/ import data.set.countable import set_theory.schroeder_bernstein import data.fintype.card import data.nat.enat /-! # Cardinal Numbers We define cardinal numbers as a quotient of types under the equivalence relation of equinumerity. ## Main definitions * `cardinal` the type of cardinal numbers (in a given universe). * `cardinal.mk α` or `#α` is the cardinality of `α`. The notation `#` lives in the locale `cardinal`. * There is an instance that `cardinal` forms a `canonically_ordered_comm_semiring`. * Addition `c₁ + c₂` is defined by `cardinal.add_def α β : #α + #β = #(α ⊕ β)`. * Multiplication `c₁ * c₂` is defined by `cardinal.mul_def : #α * #β = #(α * β)`. * The order `c₁ ≤ c₂` is defined by `cardinal.le_def α β : #α ≤ #β ↔ nonempty (α ↪ β)`. * Exponentiation `c₁ ^ c₂` is defined by `cardinal.power_def α β : #α ^ #β = #(β → α)`. * `cardinal.omega` the cardinality of `ℕ`. This definition is universe polymorphic: `cardinal.omega.{u} : cardinal.{u}` (contrast with `ℕ : Type`, which lives in a specific universe). In some cases the universe level has to be given explicitly. * `cardinal.min (I : nonempty ι) (c : ι → cardinal)` is the minimal cardinal in the range of `c`. * `cardinal.succ c` is the successor cardinal, the smallest cardinal larger than `c`. * `cardinal.sum` is the sum of a collection of cardinals. * `cardinal.sup` is the supremum of a collection of cardinals. * `cardinal.powerlt c₁ c₂` or `c₁ ^< c₂` is defined as `sup_{γ < β} α^γ`. ## Main Statements * Cantor's theorem: `cardinal.cantor c : c < 2 ^ c`. * König's theorem: `cardinal.sum_lt_prod` ## Implementation notes * There is a type of cardinal numbers in every universe level: `cardinal.{u} : Type (u + 1)` is the quotient of types in `Type u`. The operation `cardinal.lift` lifts cardinal numbers to a higher level. * Cardinal arithmetic specifically for infinite cardinals (like `κ * κ = κ`) is in the file `set_theory/cardinal_ordinal.lean`. * There is an instance `has_pow cardinal`, but this will only fire if Lean already knows that both the base and the exponent live in the same universe. As a workaround, you can add ``` local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow ``` to a file. This notation will work even if Lean doesn't know yet that the base and the exponent live in the same universe (but no exponents in other types can be used). ## References * <https://en.wikipedia.org/wiki/Cardinal_number> ## Tags cardinal number, cardinal arithmetic, cardinal exponentiation, omega, Cantor's theorem, König's theorem -/ open function set open_locale classical universes u v w x variables {α β : Type u} /-- The equivalence relation on types given by equivalence (bijective correspondence) of types. Quotienting by this equivalence relation gives the cardinal numbers. -/ instance cardinal.is_equivalent : setoid (Type u) := { r := λα β, nonempty (α ≃ β), iseqv := ⟨λα, ⟨equiv.refl α⟩, λα β ⟨e⟩, ⟨e.symm⟩, λα β γ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩⟩ } /-- `cardinal.{u}` is the type of cardinal numbers in `Type u`, defined as the quotient of `Type u` by existence of an equivalence (a bijection with explicit inverse). -/ def cardinal : Type (u + 1) := quotient cardinal.is_equivalent namespace cardinal /-- The cardinal number of a type -/ def mk : Type u → cardinal := quotient.mk localized "notation `#` := cardinal.mk" in cardinal protected lemma eq : mk α = mk β ↔ nonempty (α ≃ β) := quotient.eq @[simp] theorem mk_def (α : Type u) : @eq cardinal ⟦α⟧ (mk α) := rfl @[simp] theorem mk_out (c : cardinal) : mk (c.out) = c := quotient.out_eq _ /-- We define the order on cardinal numbers by `mk α ≤ mk β` if and only if there exists an embedding (injective function) from α to β. -/ instance : has_le cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, nonempty $ α ↪ β) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, propext ⟨assume ⟨e⟩, ⟨e.congr e₁ e₂⟩, assume ⟨e⟩, ⟨e.congr e₁.symm e₂.symm⟩⟩⟩ theorem le_def (α β : Type u) : mk α ≤ mk β ↔ nonempty (α ↪ β) := iff.rfl theorem mk_le_of_injective {α β : Type u} {f : α → β} (hf : injective f) : mk α ≤ mk β := ⟨⟨f, hf⟩⟩ theorem mk_le_of_surjective {α β : Type u} {f : α → β} (hf : surjective f) : mk β ≤ mk α := ⟨embedding.of_surjective f hf⟩ theorem le_mk_iff_exists_set {c : cardinal} {α : Type u} : c ≤ mk α ↔ ∃ p : set α, mk p = c := ⟨quotient.induction_on c $ λ β ⟨⟨f, hf⟩⟩, ⟨set.range f, eq.symm $ quot.sound ⟨equiv.set.range f hf⟩⟩, λ ⟨p, e⟩, e ▸ ⟨⟨subtype.val, λ a b, subtype.eq⟩⟩⟩ theorem out_embedding {c c' : cardinal} : c ≤ c' ↔ nonempty (c.out ↪ c'.out) := by { transitivity _, rw [←quotient.out_eq c, ←quotient.out_eq c'], refl } protected lemma eq_congr : α ≃ β → # α = # β := λ h, quot.sound ⟨h⟩ noncomputable instance : linear_order cardinal.{u} := { le := (≤), le_refl := by rintros ⟨α⟩; exact ⟨embedding.refl _⟩, le_trans := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.trans e₂⟩, le_antisymm := by rintros ⟨α⟩ ⟨β⟩ ⟨e₁⟩ ⟨e₂⟩; exact quotient.sound (e₁.antisymm e₂), le_total := by rintros ⟨α⟩ ⟨β⟩; exact embedding.total, decidable_le := classical.dec_rel _ } noncomputable instance : distrib_lattice cardinal.{u} := by apply_instance -- short-circuit type class inference instance : has_zero cardinal.{u} := ⟨⟦pempty⟧⟩ instance : inhabited cardinal.{u} := ⟨0⟩ theorem ne_zero_iff_nonempty {α : Type u} : mk α ≠ 0 ↔ nonempty α := not_iff_comm.1 ⟨λ h, quotient.sound ⟨(equiv.empty_of_not_nonempty h).trans equiv.empty_equiv_pempty⟩, λ e, let ⟨h⟩ := quotient.exact e in λ ⟨a⟩, (h a).elim⟩ instance : has_one cardinal.{u} := ⟨⟦punit⟧⟩ instance : nontrivial cardinal.{u} := ⟨⟨1, 0, ne_zero_iff_nonempty.2 ⟨punit.star⟩⟩⟩ theorem le_one_iff_subsingleton {α : Type u} : mk α ≤ 1 ↔ subsingleton α := ⟨λ ⟨f⟩, ⟨λ a b, f.injective (subsingleton.elim _ _)⟩, λ ⟨h⟩, ⟨⟨λ a, punit.star, λ a b _, h _ _⟩⟩⟩ theorem one_lt_iff_nontrivial {α : Type u} : 1 < mk α ↔ nontrivial α := by { rw [← not_iff_not, not_nontrivial_iff_subsingleton, ← le_one_iff_subsingleton], simp } instance : has_add cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α ⊕ β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.sum_congr e₁ e₂⟩⟩ @[simp] theorem add_def (α β) : mk α + mk β = mk (α ⊕ β) := rfl instance : has_mul cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α × β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.prod_congr e₁ e₂⟩⟩ @[simp] theorem mul_def (α β : Type u) : mk α * mk β = mk (α × β) := rfl private theorem add_comm (a b : cardinal.{u}) : a + b = b + a := quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.sum_comm α β⟩ private theorem mul_comm (a b : cardinal.{u}) : a * b = b * a := quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.prod_comm α β⟩ private theorem zero_add (a : cardinal.{u}) : 0 + a = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_sum α⟩ private theorem zero_mul (a : cardinal.{u}) : 0 * a = 0 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_prod α⟩ private theorem one_mul (a : cardinal.{u}) : 1 * a = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.punit_prod α⟩ private theorem left_distrib (a b c : cardinal.{u}) : a * (b + c) = a * b + a * c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_sum_distrib α β γ⟩ protected theorem eq_zero_or_eq_zero_of_mul_eq_zero {a b : cardinal.{u}} : a * b = 0 → a = 0 ∨ b = 0 := begin refine quotient.induction_on b _, refine quotient.induction_on a _, intros a b h, contrapose h, simp_rw [not_or_distrib, ← ne.def] at h, have := @prod.nonempty a b (ne_zero_iff_nonempty.mp h.1) (ne_zero_iff_nonempty.mp h.2), exact ne_zero_iff_nonempty.mpr this end instance : comm_semiring cardinal.{u} := { zero := 0, one := 1, add := (+), mul := (*), zero_add := zero_add, add_zero := assume a, by rw [add_comm a 0, zero_add a], add_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.sum_assoc α β γ⟩, add_comm := add_comm, zero_mul := zero_mul, mul_zero := assume a, by rw [mul_comm a 0, zero_mul a], one_mul := one_mul, mul_one := assume a, by rw [mul_comm a 1, one_mul a], mul_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_assoc α β γ⟩, mul_comm := mul_comm, left_distrib := left_distrib, right_distrib := assume a b c, by rw [mul_comm (a + b) c, left_distrib c a b, mul_comm c a, mul_comm c b] } /-- The cardinal exponential. `mk α ^ mk β` is the cardinal of `β → α`. -/ protected def power (a b : cardinal.{u}) : cardinal.{u} := quotient.lift_on₂ a b (λα β, mk (β → α)) $ assume α₁ α₂ β₁ β₂ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.arrow_congr e₂ e₁⟩ instance : has_pow cardinal cardinal := ⟨cardinal.power⟩ local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow @[simp] theorem power_def (α β) : mk α ^ mk β = mk (β → α) := rfl @[simp] theorem power_zero {a : cardinal} : a ^ 0 = 1 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_arrow_equiv_punit α⟩ @[simp] theorem power_one {a : cardinal} : a ^ 1 = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.punit_arrow_equiv α⟩ @[simp] theorem one_power {a : cardinal} : 1 ^ a = 1 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.arrow_punit_equiv_punit α⟩ @[simp] theorem prop_eq_two : mk (ulift Prop) = 2 := quot.sound ⟨equiv.ulift.trans $ equiv.Prop_equiv_bool.trans equiv.bool_equiv_punit_sum_punit⟩ @[simp] theorem zero_power {a : cardinal} : a ≠ 0 → 0 ^ a = 0 := quotient.induction_on a $ assume α heq, nonempty.rec_on (ne_zero_iff_nonempty.1 heq) $ assume a, quotient.sound ⟨equiv.equiv_pempty $ assume f, pempty.rec (λ _, false) (f a)⟩ theorem power_ne_zero {a : cardinal} (b) : a ≠ 0 → a ^ b ≠ 0 := quotient.induction_on₂ a b $ λ α β h, let ⟨a⟩ := ne_zero_iff_nonempty.1 h in ne_zero_iff_nonempty.2 ⟨λ _, a⟩ theorem mul_power {a b c : cardinal} : (a * b) ^ c = a ^ c * b ^ c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.arrow_prod_equiv_prod_arrow α β γ⟩ theorem power_add {a b c : cardinal} : a ^ (b + c) = a ^ b * a ^ c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.sum_arrow_equiv_prod_arrow β γ α⟩ theorem power_mul {a b c : cardinal} : (a ^ b) ^ c = a ^ (b * c) := by rw [_root_.mul_comm b c]; from (quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.arrow_arrow_equiv_prod_arrow γ β α⟩) @[simp] lemma pow_cast_right (κ : cardinal.{u}) : ∀ n : ℕ, (κ ^ (↑n : cardinal.{u})) = @has_pow.pow _ _ monoid.has_pow κ n | 0 := by simp | (_+1) := by rw [nat.cast_succ, power_add, power_one, _root_.mul_comm, pow_succ, pow_cast_right] section order_properties open sum protected theorem zero_le : ∀(a : cardinal), 0 ≤ a := by rintro ⟨α⟩; exact ⟨embedding.of_not_nonempty $ λ ⟨a⟩, a.elim⟩ protected theorem add_le_add : ∀{a b c d : cardinal}, a ≤ b → c ≤ d → a + c ≤ b + d := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.sum_map e₂⟩ protected theorem add_le_add_left (a) {b c : cardinal} : b ≤ c → a + b ≤ a + c := cardinal.add_le_add (le_refl _) protected theorem le_iff_exists_add {a b : cardinal} : a ≤ b ↔ ∃ c, b = a + c := ⟨quotient.induction_on₂ a b $ λ α β ⟨⟨f, hf⟩⟩, have (α ⊕ ((range f)ᶜ : set β)) ≃ β, from (equiv.sum_congr (equiv.set.range f hf) (equiv.refl _)).trans $ (equiv.set.sum_compl (range f)), ⟨⟦↥(range f)ᶜ⟧, quotient.sound ⟨this.symm⟩⟩, λ ⟨c, e⟩, add_zero a ▸ e.symm ▸ cardinal.add_le_add_left _ (cardinal.zero_le _)⟩ instance : order_bot cardinal.{u} := { bot := 0, bot_le := cardinal.zero_le, ..cardinal.linear_order } instance : canonically_ordered_comm_semiring cardinal.{u} := { add_le_add_left := λ a b h c, cardinal.add_le_add_left _ h, lt_of_add_lt_add_left := λ a b c, lt_imp_lt_of_le_imp_le (cardinal.add_le_add_left _), le_iff_exists_add := @cardinal.le_iff_exists_add, eq_zero_or_eq_zero_of_mul_eq_zero := @cardinal.eq_zero_or_eq_zero_of_mul_eq_zero, ..cardinal.order_bot, ..cardinal.comm_semiring, ..cardinal.linear_order } noncomputable instance : canonically_linear_ordered_add_monoid cardinal.{u} := { .. (infer_instance : canonically_ordered_add_monoid cardinal.{u}), .. cardinal.linear_order } @[simp] theorem zero_lt_one : (0 : cardinal) < 1 := lt_of_le_of_ne (zero_le _) zero_ne_one lemma zero_power_le (c : cardinal.{u}) : (0 : cardinal.{u}) ^ c ≤ 1 := by { by_cases h : c = 0, rw [h, power_zero], rw [zero_power h], apply zero_le } theorem power_le_power_left : ∀{a b c : cardinal}, a ≠ 0 → b ≤ c → a ^ b ≤ a ^ c := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ hα ⟨e⟩; exact let ⟨a⟩ := ne_zero_iff_nonempty.1 hα in ⟨@embedding.arrow_congr_right _ _ _ ⟨a⟩ e⟩ theorem power_le_max_power_one {a b c : cardinal} (h : b ≤ c) : a ^ b ≤ max (a ^ c) 1 := begin by_cases ha : a = 0, simp [ha, zero_power_le], exact le_trans (power_le_power_left ha h) (le_max_left _ _) end theorem power_le_power_right {a b c : cardinal} : a ≤ b → a ^ c ≤ b ^ c := quotient.induction_on₃ a b c $ assume α β γ ⟨e⟩, ⟨embedding.arrow_congr_left e⟩ end order_properties theorem cantor : ∀(a : cardinal.{u}), a < 2 ^ a := by rw ← prop_eq_two; rintros ⟨a⟩; exact ⟨ ⟨⟨λ a b, ⟨a = b⟩, λ a b h, cast (ulift.up.inj (@congr_fun _ _ _ _ h b)).symm rfl⟩⟩, λ ⟨⟨f, hf⟩⟩, cantor_injective (λ s, f (λ a, ⟨s a⟩)) $ λ s t h, by funext a; injection congr_fun (hf h) a⟩ instance : no_top_order cardinal.{u} := { no_top := λ a, ⟨_, cantor a⟩, ..cardinal.linear_order } /-- The minimum cardinal in a family of cardinals (the existence of which is provided by `injective_min`). -/ noncomputable def min {ι} (I : nonempty ι) (f : ι → cardinal) : cardinal := f $ classical.some $ @embedding.min_injective _ (λ i, (f i).out) I theorem min_eq {ι} (I) (f : ι → cardinal) : ∃ i, min I f = f i := ⟨_, rfl⟩ theorem min_le {ι I} (f : ι → cardinal) (i) : min I f ≤ f i := by rw [← mk_out (min I f), ← mk_out (f i)]; exact let ⟨g⟩ := classical.some_spec (@embedding.min_injective _ (λ i, (f i).out) I) in ⟨g i⟩ theorem le_min {ι I} {f : ι → cardinal} {a} : a ≤ min I f ↔ ∀ i, a ≤ f i := ⟨λ h i, le_trans h (min_le _ _), λ h, let ⟨i, e⟩ := min_eq I f in e.symm ▸ h i⟩ protected theorem wf : @well_founded cardinal.{u} (<) := ⟨λ a, classical.by_contradiction $ λ h, let ι := {c :cardinal // ¬ acc (<) c}, f : ι → cardinal := subtype.val, ⟨⟨c, hc⟩, hi⟩ := @min_eq ι ⟨⟨_, h⟩⟩ f in hc (acc.intro _ (λ j ⟨_, h'⟩, classical.by_contradiction $ λ hj, h' $ by have := min_le f ⟨j, hj⟩; rwa hi at this))⟩ instance has_wf : @has_well_founded cardinal.{u} := ⟨(<), cardinal.wf⟩ instance wo : @is_well_order cardinal.{u} (<) := ⟨cardinal.wf⟩ /-- The successor cardinal - the smallest cardinal greater than `c`. This is not the same as `c + 1` except in the case of finite `c`. -/ noncomputable def succ (c : cardinal) : cardinal := @min {c' // c < c'} ⟨⟨_, cantor _⟩⟩ subtype.val theorem lt_succ_self (c : cardinal) : c < succ c := by cases min_eq _ _ with s e; rw [succ, e]; exact s.2 theorem succ_le {a b : cardinal} : succ a ≤ b ↔ a < b := ⟨lt_of_lt_of_le (lt_succ_self _), λ h, by exact min_le _ (subtype.mk b h)⟩ theorem lt_succ {a b : cardinal} : a < succ b ↔ a ≤ b := by rw [← not_le, succ_le, not_lt] theorem add_one_le_succ (c : cardinal) : c + 1 ≤ succ c := begin refine quot.induction_on c (λ α, _) (lt_succ_self c), refine quot.induction_on (succ (quot.mk setoid.r α)) (λ β h, _), cases h.left with f, have : ¬ surjective f := λ hn, ne_of_lt h (quotient.sound ⟨equiv.of_bijective f ⟨f.injective, hn⟩⟩), cases not_forall.1 this with b nex, refine ⟨⟨sum.rec (by exact f) _, _⟩⟩, { exact λ _, b }, { intros a b h, rcases a with a|⟨⟨⟨⟩⟩⟩; rcases b with b|⟨⟨⟨⟩⟩⟩, { rw f.injective h }, { exact nex.elim ⟨_, h⟩ }, { exact nex.elim ⟨_, h.symm⟩ }, { refl } } end lemma succ_ne_zero (c : cardinal) : succ c ≠ 0 := by { rw [←pos_iff_ne_zero, lt_succ], apply zero_le } /-- The indexed sum of cardinals is the cardinality of the indexed disjoint union, i.e. sigma type. -/ def sum {ι} (f : ι → cardinal) : cardinal := mk Σ i, (f i).out theorem le_sum {ι} (f : ι → cardinal) (i) : f i ≤ sum f := by rw ← quotient.out_eq (f i); exact ⟨⟨λ a, ⟨i, a⟩, λ a b h, eq_of_heq $ by injection h⟩⟩ @[simp] theorem sum_mk {ι} (f : ι → Type*) : sum (λ i, mk (f i)) = mk (Σ i, f i) := quot.sound ⟨equiv.sigma_congr_right $ λ i, classical.choice $ quotient.exact $ quot.out_eq $ mk (f i)⟩ theorem sum_const (ι : Type u) (a : cardinal.{u}) : sum (λ _:ι, a) = mk ι * a := quotient.induction_on a $ λ α, by simp; exact quotient.sound ⟨equiv.sigma_equiv_prod _ _⟩ theorem sum_le_sum {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sum f ≤ sum g := ⟨(embedding.refl _).sigma_map $ λ i, classical.choice $ by have := H i; rwa [← quot.out_eq (f i), ← quot.out_eq (g i)] at this⟩ /-- The indexed supremum of cardinals is the smallest cardinal above everything in the family. -/ noncomputable def sup {ι} (f : ι → cardinal) : cardinal := @min {c // ∀ i, f i ≤ c} ⟨⟨sum f, le_sum f⟩⟩ (λ a, a.1) theorem le_sup {ι} (f : ι → cardinal) (i) : f i ≤ sup f := by dsimp [sup]; cases min_eq _ _ with c hc; rw hc; exact c.2 i theorem sup_le {ι} {f : ι → cardinal} {a} : sup f ≤ a ↔ ∀ i, f i ≤ a := ⟨λ h i, le_trans (le_sup _ _) h, λ h, by dsimp [sup]; change a with (⟨a, h⟩:subtype _).1; apply min_le⟩ theorem sup_le_sup {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sup f ≤ sup g := sup_le.2 $ λ i, le_trans (H i) (le_sup _ _) theorem sup_le_sum {ι} (f : ι → cardinal) : sup f ≤ sum f := sup_le.2 $ le_sum _ theorem sum_le_sup {ι : Type u} (f : ι → cardinal.{u}) : sum f ≤ mk ι * sup.{u u} f := by rw ← sum_const; exact sum_le_sum _ _ (le_sup _) theorem sup_eq_zero {ι} {f : ι → cardinal} (h : ι → false) : sup f = 0 := by { rw [← nonpos_iff_eq_zero, sup_le], intro x, exfalso, exact h x } /-- The indexed product of cardinals is the cardinality of the Pi type (dependent product). -/ def prod {ι : Type u} (f : ι → cardinal) : cardinal := mk (Π i, (f i).out) @[simp] theorem prod_mk {ι} (f : ι → Type*) : prod (λ i, mk (f i)) = mk (Π i, f i) := quot.sound ⟨equiv.Pi_congr_right $ λ i, classical.choice $ quotient.exact $ mk_out $ mk (f i)⟩ theorem prod_const (ι : Type u) (a : cardinal.{u}) : prod (λ _:ι, a) = a ^ mk ι := quotient.induction_on a $ by simp theorem prod_le_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : prod f ≤ prod g := ⟨embedding.Pi_congr_right $ λ i, classical.choice $ by have := H i; rwa [← mk_out (f i), ← mk_out (g i)] at this⟩ theorem prod_ne_zero {ι} (f : ι → cardinal) : prod f ≠ 0 ↔ ∀ i, f i ≠ 0 := begin suffices : nonempty (Π i, (f i).out) ↔ ∀ i, nonempty (f i).out, { simpa [← ne_zero_iff_nonempty, prod] }, exact classical.nonempty_pi end theorem prod_eq_zero {ι} (f : ι → cardinal) : prod f = 0 ↔ ∃ i, f i = 0 := not_iff_not.1 $ by simpa using prod_ne_zero f /-- The universe lift operation on cardinals. You can specify the universes explicitly with `lift.{u v} : cardinal.{u} → cardinal.{max u v}` -/ def lift (c : cardinal.{u}) : cardinal.{max u v} := quotient.lift_on c (λ α, ⟦ulift α⟧) $ λ α β ⟨e⟩, quotient.sound ⟨equiv.ulift.trans $ e.trans equiv.ulift.symm⟩ theorem lift_mk (α) : lift.{u v} (mk α) = mk (ulift.{v u} α) := rfl theorem lift_umax : lift.{u (max u v)} = lift.{u v} := funext $ λ a, quot.induction_on a $ λ α, quotient.sound ⟨equiv.ulift.trans equiv.ulift.symm⟩ theorem lift_id' (a : cardinal) : lift a = a := quot.induction_on a $ λ α, quot.sound ⟨equiv.ulift⟩ @[simp] theorem lift_id : ∀ a, lift.{u u} a = a := lift_id'.{u u} @[simp] theorem lift_lift (a : cardinal) : lift.{(max u v) w} (lift.{u v} a) = lift.{u (max v w)} a := quot.induction_on a $ λ α, quotient.sound ⟨equiv.ulift.trans $ equiv.ulift.trans equiv.ulift.symm⟩ theorem lift_mk_le {α : Type u} {β : Type v} : lift.{u (max v w)} (mk α) ≤ lift.{v (max u w)} (mk β) ↔ nonempty (α ↪ β) := ⟨λ ⟨f⟩, ⟨embedding.congr equiv.ulift equiv.ulift f⟩, λ ⟨f⟩, ⟨embedding.congr equiv.ulift.symm equiv.ulift.symm f⟩⟩ theorem lift_mk_eq {α : Type u} {β : Type v} : lift.{u (max v w)} (mk α) = lift.{v (max u w)} (mk β) ↔ nonempty (α ≃ β) := quotient.eq.trans ⟨λ ⟨f⟩, ⟨equiv.ulift.symm.trans $ f.trans equiv.ulift⟩, λ ⟨f⟩, ⟨equiv.ulift.trans $ f.trans equiv.ulift.symm⟩⟩ @[simp] theorem lift_le {a b : cardinal} : lift a ≤ lift b ↔ a ≤ b := quotient.induction_on₂ a b $ λ α β, by rw ← lift_umax; exact lift_mk_le @[simp] theorem lift_inj {a b : cardinal} : lift a = lift b ↔ a = b := by simp [le_antisymm_iff] @[simp] theorem lift_lt {a b : cardinal} : lift a < lift b ↔ a < b := by simp [lt_iff_le_not_le, -not_le] @[simp] theorem lift_zero : lift 0 = 0 := quotient.sound ⟨equiv.ulift.trans equiv.pempty_equiv_pempty⟩ @[simp] theorem lift_one : lift 1 = 1 := quotient.sound ⟨equiv.ulift.trans equiv.punit_equiv_punit⟩ @[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.prod_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_power (a b) : lift (a ^ b) = lift a ^ lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.arrow_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_two_power (a) : lift (2 ^ a) = 2 ^ lift a := by simp [bit0] @[simp] theorem lift_min {ι I} (f : ι → cardinal) : lift (min I f) = min I (lift ∘ f) := le_antisymm (le_min.2 $ λ a, lift_le.2 $ min_le _ a) $ let ⟨i, e⟩ := min_eq I (lift ∘ f) in by rw e; exact lift_le.2 (le_min.2 $ λ j, lift_le.1 $ by have := min_le (lift ∘ f) j; rwa e at this) theorem lift_down {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a → ∃ a', lift a' = b := quotient.induction_on₂ a b $ λ α β, by dsimp; rw [← lift_id (mk β), ← lift_umax, ← lift_umax.{u v}, lift_mk_le]; exact λ ⟨f⟩, ⟨mk (set.range f), eq.symm $ lift_mk_eq.2 ⟨embedding.equiv_of_surjective (embedding.cod_restrict _ f set.mem_range_self) $ λ ⟨a, ⟨b, e⟩⟩, ⟨b, subtype.eq e⟩⟩⟩ theorem le_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a ↔ ∃ a', lift a' = b ∧ a' ≤ a := ⟨λ h, let ⟨a', e⟩ := lift_down h in ⟨a', e, lift_le.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_le.2 h⟩ theorem lt_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b < lift a ↔ ∃ a', lift a' = b ∧ a' < a := ⟨λ h, let ⟨a', e⟩ := lift_down (le_of_lt h) in ⟨a', e, lift_lt.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_lt.2 h⟩ @[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) := le_antisymm (le_of_not_gt $ λ h, begin rcases lt_lift_iff.1 h with ⟨b, e, h⟩, rw [lt_succ, ← lift_le, e] at h, exact not_lt_of_le h (lt_succ_self _) end) (succ_le.2 $ lift_lt.2 $ lt_succ_self _) @[simp] theorem lift_max {a : cardinal.{u}} {b : cardinal.{v}} : lift.{u (max v w)} a = lift.{v (max u w)} b ↔ lift.{u v} a = lift.{v u} b := calc lift.{u (max v w)} a = lift.{v (max u w)} b ↔ lift.{(max u v) w} (lift.{u v} a) = lift.{(max u v) w} (lift.{v u} b) : by simp ... ↔ lift.{u v} a = lift.{v u} b : lift_inj theorem mk_prod {α : Type u} {β : Type v} : mk (α × β) = lift.{u v} (mk α) * lift.{v u} (mk β) := quotient.sound ⟨equiv.prod_congr (equiv.ulift).symm (equiv.ulift).symm⟩ theorem sum_const_eq_lift_mul (ι : Type u) (a : cardinal.{v}) : sum (λ _:ι, a) = lift.{u v} (mk ι) * lift.{v u} a := begin apply quotient.induction_on a, intro α, simp only [cardinal.mk_def, cardinal.sum_mk, cardinal.lift_id], convert mk_prod using 1, exact quotient.sound ⟨equiv.sigma_equiv_prod ι α⟩, end /-- `ω` is the smallest infinite cardinal, also known as ℵ₀. -/ def omega : cardinal.{u} := lift (mk ℕ) lemma mk_nat : mk nat = omega := (lift_id _).symm theorem omega_ne_zero : omega ≠ 0 := ne_zero_iff_nonempty.2 ⟨⟨0⟩⟩ theorem omega_pos : 0 < omega := pos_iff_ne_zero.2 omega_ne_zero @[simp] theorem lift_omega : lift omega = omega := lift_lift _ /- properties about the cast from nat -/ @[simp] theorem mk_fin : ∀ (n : ℕ), mk (fin n) = n | 0 := quotient.sound ⟨(equiv.pempty_of_not_nonempty $ λ ⟨h⟩, h.elim0)⟩ | (n+1) := by rw [nat.cast_succ, ← mk_fin]; exact quotient.sound (fintype.card_eq.1 $ by simp) @[simp] theorem lift_nat_cast (n : ℕ) : lift n = n := by induction n; simp * lemma lift_eq_nat_iff {a : cardinal.{u}} {n : ℕ} : lift.{u v} a = n ↔ a = n := by rw [← lift_nat_cast.{u v} n, lift_inj] lemma nat_eq_lift_eq_iff {n : ℕ} {a : cardinal.{u}} : (n : cardinal) = lift.{u v} a ↔ (n : cardinal) = a := by rw [← lift_nat_cast.{u v} n, lift_inj] theorem lift_mk_fin (n : ℕ) : lift (mk (fin n)) = n := by simp theorem fintype_card (α : Type u) [fintype α] : mk α = fintype.card α := by rw [← lift_mk_fin.{u}, ← lift_id (mk α), lift_mk_eq.{u 0 u}]; exact fintype.card_eq.1 (by simp) theorem card_le_of_finset {α} (s : finset α) : (s.card : cardinal) ≤ cardinal.mk α := begin rw (_ : (s.card : cardinal) = cardinal.mk (↑s : set α)), { exact ⟨function.embedding.subtype _⟩ }, rw [cardinal.fintype_card, fintype.card_coe] end @[simp, norm_cast] theorem nat_cast_pow {m n : ℕ} : (↑(pow m n) : cardinal) = m ^ n := by induction n; simp [pow_succ', -_root_.add_comm, power_add, *] @[simp, norm_cast] theorem nat_cast_le {m n : ℕ} : (m : cardinal) ≤ n ↔ m ≤ n := by rw [← lift_mk_fin, ← lift_mk_fin, lift_le]; exact ⟨λ ⟨⟨f, hf⟩⟩, by simpa only [fintype.card_fin] using fintype.card_le_of_injective f hf, λ h, ⟨(fin.cast_le h).to_embedding⟩⟩ @[simp, norm_cast] theorem nat_cast_lt {m n : ℕ} : (m : cardinal) < n ↔ m < n := by simp [lt_iff_le_not_le, -not_le] @[simp, norm_cast] theorem nat_cast_inj {m n : ℕ} : (m : cardinal) = n ↔ m = n := by simp [le_antisymm_iff] @[simp, norm_cast, priority 900] theorem nat_succ (n : ℕ) : (n.succ : cardinal) = succ n := le_antisymm (add_one_le_succ _) (succ_le.2 $ nat_cast_lt.2 $ nat.lt_succ_self _) @[simp] theorem succ_zero : succ 0 = 1 := by norm_cast theorem card_le_of {α : Type u} {n : ℕ} (H : ∀ s : finset α, s.card ≤ n) : # α ≤ n := begin refine lt_succ.1 (lt_of_not_ge $ λ hn, _), rw [← cardinal.nat_succ, ← cardinal.lift_mk_fin n.succ] at hn, cases hn with f, refine not_lt_of_le (H $ finset.univ.map f) _, rw [finset.card_map, ← fintype.card, fintype.card_ulift, fintype.card_fin], exact n.lt_succ_self end theorem cantor' (a) {b : cardinal} (hb : 1 < b) : a < b ^ a := by rw [← succ_le, (by norm_cast : succ 1 = 2)] at hb; exact lt_of_lt_of_le (cantor _) (power_le_power_right hb) theorem one_le_iff_pos {c : cardinal} : 1 ≤ c ↔ 0 < c := by rw [← succ_zero, succ_le] theorem one_le_iff_ne_zero {c : cardinal} : 1 ≤ c ↔ c ≠ 0 := by rw [one_le_iff_pos, pos_iff_ne_zero] theorem nat_lt_omega (n : ℕ) : (n : cardinal.{u}) < omega := succ_le.1 $ by rw [← nat_succ, ← lift_mk_fin, omega, lift_mk_le.{0 0 u}]; exact ⟨⟨coe, λ a b, fin.ext⟩⟩ @[simp] theorem one_lt_omega : 1 < omega := by simpa using nat_lt_omega 1 theorem lt_omega {c : cardinal.{u}} : c < omega ↔ ∃ n : ℕ, c = n := ⟨λ h, begin rcases lt_lift_iff.1 h with ⟨c, rfl, h'⟩, rcases le_mk_iff_exists_set.1 h'.1 with ⟨S, rfl⟩, suffices : finite S, { cases this, resetI, existsi fintype.card S, rw [← lift_nat_cast.{0 u}, lift_inj, fintype_card S] }, by_contra nf, have P : ∀ (n : ℕ) (IH : ∀ i<n, S), ∃ a : S, ¬ ∃ y h, IH y h = a := λ n IH, let g : {i | i < n} → S := λ ⟨i, h⟩, IH i h in not_forall.1 (λ h, nf ⟨fintype.of_surjective g (λ a, subtype.exists.2 (h a))⟩), let F : ℕ → S := nat.lt_wf.fix (λ n IH, classical.some (P n IH)), refine not_le_of_lt h' ⟨⟨F, _⟩⟩, suffices : ∀ (n : ℕ) (m < n), F m ≠ F n, { refine λ m n, not_imp_not.1 (λ ne, _), rcases lt_trichotomy m n with h|h|h, { exact this n m h }, { contradiction }, { exact (this m n h).symm } }, intros n m h, have := classical.some_spec (P n (λ y _, F y)), rw [← show F n = classical.some (P n (λ y _, F y)), from nat.lt_wf.fix_eq (λ n IH, classical.some (P n IH)) n] at this, exact λ e, this ⟨m, h, e⟩, end, λ ⟨n, e⟩, e.symm ▸ nat_lt_omega _⟩ theorem omega_le {c : cardinal.{u}} : omega ≤ c ↔ ∀ n : ℕ, (n:cardinal) ≤ c := ⟨λ h n, le_trans (le_of_lt (nat_lt_omega _)) h, λ h, le_of_not_lt $ λ hn, begin rcases lt_omega.1 hn with ⟨n, rfl⟩, exact not_le_of_lt (nat.lt_succ_self _) (nat_cast_le.1 (h (n+1))) end⟩ theorem lt_omega_iff_fintype {α : Type u} : mk α < omega ↔ nonempty (fintype α) := lt_omega.trans ⟨λ ⟨n, e⟩, begin rw [← lift_mk_fin n] at e, cases quotient.exact e with f, exact ⟨fintype.of_equiv _ f.symm⟩ end, λ ⟨_⟩, by exactI ⟨_, fintype_card _⟩⟩ theorem lt_omega_iff_finite {α} {S : set α} : mk S < omega ↔ finite S := lt_omega_iff_fintype instance can_lift_cardinal_nat : can_lift cardinal ℕ := ⟨ coe, λ x, x < omega, λ x hx, let ⟨n, hn⟩ := lt_omega.mp hx in ⟨n, hn.symm⟩⟩ theorem add_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a + b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_omega end lemma add_lt_omega_iff {a b : cardinal} : a + b < omega ↔ a < omega ∧ b < omega := ⟨λ h, ⟨lt_of_le_of_lt (self_le_add_right _ _) h, lt_of_le_of_lt (self_le_add_left _ _) h⟩, λ⟨h1, h2⟩, add_lt_omega h1 h2⟩ theorem mul_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a * b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_mul]; apply nat_lt_omega end lemma mul_lt_omega_iff {a b : cardinal} : a * b < omega ↔ a = 0 ∨ b = 0 ∨ a < omega ∧ b < omega := begin split, { intro h, by_cases ha : a = 0, { left, exact ha }, right, by_cases hb : b = 0, { left, exact hb }, right, rw [← ne, ← one_le_iff_ne_zero] at ha hb, split, { rw [← mul_one a], refine lt_of_le_of_lt (canonically_ordered_semiring.mul_le_mul (le_refl a) hb) h }, { rw [← _root_.one_mul b], refine lt_of_le_of_lt (canonically_ordered_semiring.mul_le_mul ha (le_refl b)) h }}, rintro (rfl|rfl|⟨ha,hb⟩); simp only [*, mul_lt_omega, omega_pos, _root_.zero_mul, mul_zero] end lemma mul_lt_omega_iff_of_ne_zero {a b : cardinal} (ha : a ≠ 0) (hb : b ≠ 0) : a * b < omega ↔ a < omega ∧ b < omega := by simp [mul_lt_omega_iff, ha, hb] theorem power_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a ^ b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_pow]; apply nat_lt_omega end lemma eq_one_iff_subsingleton_and_nonempty {α : Type*} : mk α = 1 ↔ (subsingleton α ∧ nonempty α) := calc mk α = 1 ↔ mk α ≤ 1 ∧ ¬mk α < 1 : eq_iff_le_not_lt ... ↔ subsingleton α ∧ nonempty α : begin apply and_congr le_one_iff_subsingleton, push_neg, rw [one_le_iff_ne_zero, ne_zero_iff_nonempty] end theorem infinite_iff {α : Type u} : infinite α ↔ omega ≤ mk α := by rw [←not_lt, lt_omega_iff_fintype, not_nonempty_fintype] lemma denumerable_iff {α : Type u} : nonempty (denumerable α) ↔ mk α = omega := ⟨λ⟨h⟩, quotient.sound $ by exactI ⟨ (denumerable.eqv α).trans equiv.ulift.symm ⟩, λ h, by { cases quotient.exact h with f, exact ⟨denumerable.mk' $ f.trans equiv.ulift⟩ }⟩ lemma countable_iff (s : set α) : countable s ↔ mk s ≤ omega := begin rw [countable_iff_exists_injective], split, rintro ⟨f, hf⟩, exact ⟨embedding.trans ⟨f, hf⟩ equiv.ulift.symm.to_embedding⟩, rintro ⟨f'⟩, cases embedding.trans f' equiv.ulift.to_embedding with f hf, exact ⟨f, hf⟩ end /-- This function sends finite cardinals to the corresponding natural, and infinite cardinals to 0. -/ noncomputable def to_nat : zero_hom cardinal ℕ := ⟨λ c, if h : c < omega.{v} then classical.some (lt_omega.1 h) else 0, begin have h : 0 < omega := nat_lt_omega 0, rw [dif_pos h, ← cardinal.nat_cast_inj, ← classical.some_spec (lt_omega.1 h), nat.cast_zero], end⟩ lemma to_nat_apply_of_lt_omega {c : cardinal} (h : c < omega) : c.to_nat = classical.some (lt_omega.1 h) := dif_pos h @[simp] lemma to_nat_apply_of_omega_le {c : cardinal} (h : omega ≤ c) : c.to_nat = 0 := dif_neg (not_lt_of_le h) @[simp] lemma cast_to_nat_of_lt_omega {c : cardinal} (h : c < omega) : ↑c.to_nat = c := by rw [to_nat_apply_of_lt_omega h, ← classical.some_spec (lt_omega.1 h)] @[simp] lemma to_nat_cast (n : ℕ) : cardinal.to_nat n = n := begin rw [to_nat_apply_of_lt_omega (nat_lt_omega n), ← nat_cast_inj], exact (classical.some_spec (lt_omega.1 (nat_lt_omega n))).symm, end /-- `to_nat` has a right-inverse: coercion. -/ lemma to_nat_right_inverse : function.right_inverse (coe : ℕ → cardinal) to_nat := to_nat_cast lemma to_nat_surjective : surjective to_nat := to_nat_right_inverse.surjective @[simp] lemma mk_to_nat_of_infinite [h : infinite α] : (mk α).to_nat = 0 := dif_neg (not_lt_of_le (infinite_iff.1 h)) @[simp] lemma mk_to_nat_eq_card [fintype α] : (mk α).to_nat = fintype.card α := by simp [fintype_card] @[simp] lemma zero_to_nat : cardinal.to_nat 0 = 0 := by rw [← to_nat_cast 0, nat.cast_zero] @[simp] lemma one_to_nat : cardinal.to_nat 1 = 1 := by rw [← to_nat_cast 1, nat.cast_one] /-- This function sends finite cardinals to the corresponding natural, and infinite cardinals to `⊤`. -/ noncomputable def to_enat : cardinal →+ enat := { to_fun := λ c, if c < omega.{v} then c.to_nat else ⊤, map_zero' := by simp [if_pos (lt_trans zero_lt_one one_lt_omega)], map_add' := λ x y, begin by_cases hx : x < omega, { obtain ⟨x0, rfl⟩ := lt_omega.1 hx, by_cases hy : y < omega, { obtain ⟨y0, rfl⟩ := lt_omega.1 hy, simp only [add_lt_omega hx hy, hx, hy, to_nat_cast, if_true], rw [← nat.cast_add, to_nat_cast, enat.coe_add] }, { rw [if_neg hy, if_neg, enat.add_top], contrapose! hy, apply lt_of_le_of_lt (le_add_left (le_refl y)) hy } }, { rw [if_neg hx, if_neg, enat.top_add], contrapose! hx, apply lt_of_le_of_lt (le_add_right (le_refl x)) hx }, end } @[simp] lemma to_enat_apply_of_lt_omega {c : cardinal} (h : c < omega) : c.to_enat = c.to_nat := if_pos h @[simp] lemma to_enat_apply_of_omega_le {c : cardinal} (h : omega ≤ c) : c.to_enat = ⊤ := if_neg (not_lt_of_le h) @[simp] lemma to_enat_cast (n : ℕ) : cardinal.to_enat n = n := by rw [to_enat_apply_of_lt_omega (nat_lt_omega n), to_nat_cast] @[simp] lemma mk_to_enat_of_infinite [h : infinite α] : (mk α).to_enat = ⊤ := to_enat_apply_of_omega_le (infinite_iff.1 h) lemma to_enat_surjective : surjective to_enat := begin intro x, exact enat.cases_on x ⟨omega, to_enat_apply_of_omega_le (le_refl omega)⟩ (λ n, ⟨n, to_enat_cast n⟩), end @[simp] lemma mk_to_enat_eq_coe_card [fintype α] : (mk α).to_enat = fintype.card α := by simp [fintype_card] lemma mk_int : mk ℤ = omega := denumerable_iff.mp ⟨by apply_instance⟩ lemma mk_pnat : mk ℕ+ = omega := denumerable_iff.mp ⟨by apply_instance⟩ lemma two_le_iff : (2 : cardinal) ≤ mk α ↔ ∃x y : α, x ≠ y := begin split, { rintro ⟨f⟩, refine ⟨f $ sum.inl ⟨⟩, f $ sum.inr ⟨⟩, _⟩, intro h, cases f.2 h }, { rintro ⟨x, y, h⟩, by_contra h', rw [not_le, ←nat.cast_two, nat_succ, lt_succ, nat.cast_one, le_one_iff_subsingleton] at h', apply h, exactI subsingleton.elim _ _ } end lemma two_le_iff' (x : α) : (2 : cardinal) ≤ mk α ↔ ∃y : α, x ≠ y := begin rw [two_le_iff], split, { rintro ⟨y, z, h⟩, refine classical.by_cases (λ(h' : x = y), _) (λ h', ⟨y, h'⟩), rw [←h'] at h, exact ⟨z, h⟩ }, { rintro ⟨y, h⟩, exact ⟨x, y, h⟩ } end /-- König's theorem -/ theorem sum_lt_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i < g i) : sum f < prod g := lt_of_not_ge $ λ ⟨F⟩, begin have : inhabited (Π (i : ι), (g i).out), { refine ⟨λ i, classical.choice $ ne_zero_iff_nonempty.1 _⟩, rw mk_out, exact ne_of_gt (lt_of_le_of_lt (zero_le _) (H i)) }, resetI, let G := inv_fun F, have sG : surjective G := inv_fun_surjective F.2, choose C hc using show ∀ i, ∃ b, ∀ a, G ⟨i, a⟩ i ≠ b, { assume i, simp only [- not_exists, not_exists.symm, not_forall.symm], refine λ h, not_le_of_lt (H i) _, rw [← mk_out (f i), ← mk_out (g i)], exact ⟨embedding.of_surjective _ h⟩ }, exact (let ⟨⟨i, a⟩, h⟩ := sG C in hc i a (congr_fun h _)) end @[simp] theorem mk_empty : mk empty = 0 := fintype_card empty @[simp] theorem mk_pempty : mk pempty = 0 := fintype_card pempty @[simp] theorem mk_plift_of_false {p : Prop} (h : ¬ p) : mk (plift p) = 0 := quotient.sound ⟨equiv.plift.trans $ equiv.equiv_pempty h⟩ theorem mk_unit : mk unit = 1 := (fintype_card unit).trans nat.cast_one @[simp] theorem mk_punit : mk punit = 1 := (fintype_card punit).trans nat.cast_one @[simp] theorem mk_singleton {α : Type u} (x : α) : mk ({x} : set α) = 1 := quotient.sound ⟨equiv.set.singleton x⟩ @[simp] theorem mk_plift_of_true {p : Prop} (h : p) : mk (plift p) = 1 := quotient.sound ⟨equiv.plift.trans $ equiv.prop_equiv_punit h⟩ @[simp] theorem mk_bool : mk bool = 2 := quotient.sound ⟨equiv.bool_equiv_punit_sum_punit⟩ @[simp] theorem mk_Prop : mk Prop = 2 := (quotient.sound ⟨equiv.Prop_equiv_bool⟩ : mk Prop = mk bool).trans mk_bool @[simp] theorem mk_set {α : Type u} : mk (set α) = 2 ^ mk α := begin rw [← prop_eq_two, cardinal.power_def (ulift Prop) α, cardinal.eq], exact ⟨equiv.arrow_congr (equiv.refl _) equiv.ulift.symm⟩, end @[simp] theorem mk_option {α : Type u} : mk (option α) = mk α + 1 := quotient.sound ⟨equiv.option_equiv_sum_punit α⟩ theorem mk_list_eq_sum_pow (α : Type u) : mk (list α) = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) := calc mk (list α) = mk (Σ n, vector α n) : quotient.sound ⟨(equiv.sigma_preimage_equiv list.length).symm⟩ ... = mk (Σ n, fin n → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n, ⟨vector.nth, vector.of_fn, vector.of_fn_nth, λ f, funext $ vector.nth_of_fn f⟩⟩ ... = mk (Σ n : ℕ, ulift.{u} (fin n) → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n, equiv.arrow_congr equiv.ulift.symm (equiv.refl α)⟩ ... = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) : by simp only [(lift_mk_fin _).symm, lift_mk, power_def, sum_mk] theorem mk_quot_le {α : Type u} {r : α → α → Prop} : mk (quot r) ≤ mk α := mk_le_of_surjective quot.exists_rep theorem mk_quotient_le {α : Type u} {s : setoid α} : mk (quotient s) ≤ mk α := mk_quot_le theorem mk_subtype_le {α : Type u} (p : α → Prop) : mk (subtype p) ≤ mk α := ⟨embedding.subtype p⟩ theorem mk_subtype_le_of_subset {α : Type u} {p q : α → Prop} (h : ∀ ⦃x⦄, p x → q x) : mk (subtype p) ≤ mk (subtype q) := ⟨embedding.subtype_map (embedding.refl α) h⟩ @[simp] theorem mk_emptyc (α : Type u) : mk (∅ : set α) = 0 := quotient.sound ⟨equiv.set.pempty α⟩ lemma mk_emptyc_iff {α : Type u} {s : set α} : mk s = 0 ↔ s = ∅ := begin split, { intro h, have h2 : cardinal.mk s = cardinal.mk pempty, by simp [h], refine set.eq_empty_iff_forall_not_mem.mpr (λ _ hx, _), rcases cardinal.eq.mp h2 with ⟨f, _⟩, cases f ⟨_, hx⟩ }, { intro, convert mk_emptyc _ } end theorem mk_univ {α : Type u} : mk (@univ α) = mk α := quotient.sound ⟨equiv.set.univ α⟩ theorem mk_image_le {α β : Type u} {f : α → β} {s : set α} : mk (f '' s) ≤ mk s := mk_le_of_surjective surjective_onto_image theorem mk_image_le_lift {α : Type u} {β : Type v} {f : α → β} {s : set α} : lift.{v u} (mk (f '' s)) ≤ lift.{u v} (mk s) := lift_mk_le.{v u 0}.mpr ⟨embedding.of_surjective _ surjective_onto_image⟩ theorem mk_range_le {α β : Type u} {f : α → β} : mk (range f) ≤ mk α := mk_le_of_surjective surjective_onto_range lemma mk_range_eq (f : α → β) (h : injective f) : mk (range f) = mk α := quotient.sound ⟨(equiv.set.range f h).symm⟩ lemma mk_range_eq_of_injective {α : Type u} {β : Type v} {f : α → β} (hf : injective f) : lift.{v u} (mk (range f)) = lift.{u v} (mk α) := begin have := (@lift_mk_eq.{v u max u v} (range f) α).2 ⟨(equiv.set.range f hf).symm⟩, simp only [lift_umax.{u v}, lift_umax.{v u}] at this, exact this end lemma mk_range_eq_lift {α : Type u} {β : Type v} {f : α → β} (hf : injective f) : lift.{v (max u w)} (# (range f)) = lift.{u (max v w)} (# α) := lift_mk_eq.mpr ⟨(equiv.set.range f hf).symm⟩ theorem mk_image_eq {α β : Type u} {f : α → β} {s : set α} (hf : injective f) : mk (f '' s) = mk s := quotient.sound ⟨(equiv.set.image f s hf).symm⟩ theorem mk_Union_le_sum_mk {α ι : Type u} {f : ι → set α} : mk (⋃ i, f i) ≤ sum (λ i, mk (f i)) := calc mk (⋃ i, f i) ≤ mk (Σ i, f i) : mk_le_of_surjective (set.sigma_to_Union_surjective f) ... = sum (λ i, mk (f i)) : (sum_mk _).symm theorem mk_Union_eq_sum_mk {α ι : Type u} {f : ι → set α} (h : ∀i j, i ≠ j → disjoint (f i) (f j)) : mk (⋃ i, f i) = sum (λ i, mk (f i)) := calc mk (⋃ i, f i) = mk (Σi, f i) : quot.sound ⟨set.Union_eq_sigma_of_disjoint h⟩ ... = sum (λi, mk (f i)) : (sum_mk _).symm lemma mk_Union_le {α ι : Type u} (f : ι → set α) : mk (⋃ i, f i) ≤ mk ι * cardinal.sup.{u u} (λ i, mk (f i)) := le_trans mk_Union_le_sum_mk (sum_le_sup _) lemma mk_sUnion_le {α : Type u} (A : set (set α)) : mk (⋃₀ A) ≤ mk A * cardinal.sup.{u u} (λ s : A, mk s) := by { rw [sUnion_eq_Union], apply mk_Union_le } lemma mk_bUnion_le {ι α : Type u} (A : ι → set α) (s : set ι) : mk (⋃(x ∈ s), A x) ≤ mk s * cardinal.sup.{u u} (λ x : s, mk (A x.1)) := by { rw [bUnion_eq_Union], apply mk_Union_le } @[simp] lemma finset_card {α : Type u} {s : finset α} : ↑(finset.card s) = mk (↑s : set α) := by rw [fintype_card, nat_cast_inj, fintype.card_coe] lemma finset_card_lt_omega (s : finset α) : mk (↑s : set α) < omega := by { rw [lt_omega_iff_fintype], exact ⟨finset.subtype.fintype s⟩ } theorem mk_union_add_mk_inter {α : Type u} {S T : set α} : mk (S ∪ T : set α) + mk (S ∩ T : set α) = mk S + mk T := quot.sound ⟨equiv.set.union_sum_inter S T⟩ /-- The cardinality of a union is at most the sum of the cardinalities of the two sets. -/ lemma mk_union_le {α : Type u} (S T : set α) : mk (S ∪ T : set α) ≤ mk S + mk T := @mk_union_add_mk_inter α S T ▸ self_le_add_right (mk (S ∪ T : set α)) (mk (S ∩ T : set α)) theorem mk_union_of_disjoint {α : Type u} {S T : set α} (H : disjoint S T) : mk (S ∪ T : set α) = mk S + mk T := quot.sound ⟨equiv.set.union H⟩ lemma mk_sum_compl {α} (s : set α) : #s + #(sᶜ : set α) = #α := quotient.sound ⟨equiv.set.sum_compl s⟩ lemma mk_le_mk_of_subset {α} {s t : set α} (h : s ⊆ t) : mk s ≤ mk t := ⟨set.embedding_of_subset s t h⟩ lemma mk_subtype_mono {p q : α → Prop} (h : ∀x, p x → q x) : mk {x // p x} ≤ mk {x // q x} := ⟨embedding_of_subset _ _ h⟩ lemma mk_set_le (s : set α) : mk s ≤ mk α := mk_subtype_le s lemma mk_image_eq_lift {α : Type u} {β : Type v} (f : α → β) (s : set α) (h : injective f) : lift.{v u} (mk (f '' s)) = lift.{u v} (mk s) := lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image f s h).symm⟩ lemma mk_image_eq_of_inj_on_lift {α : Type u} {β : Type v} (f : α → β) (s : set α) (h : inj_on f s) : lift.{v u} (mk (f '' s)) = lift.{u v} (mk s) := lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image_of_inj_on f s h).symm⟩ lemma mk_image_eq_of_inj_on {α β : Type u} (f : α → β) (s : set α) (h : inj_on f s) : mk (f '' s) = mk s := quotient.sound ⟨(equiv.set.image_of_inj_on f s h).symm⟩ lemma mk_subtype_of_equiv {α β : Type u} (p : β → Prop) (e : α ≃ β) : mk {a : α // p (e a)} = mk {b : β // p b} := quotient.sound ⟨equiv.subtype_equiv_of_subtype e⟩ lemma mk_sep (s : set α) (t : α → Prop) : mk ({ x ∈ s | t x } : set α) = mk { x : s | t x.1 } := quotient.sound ⟨equiv.set.sep s t⟩ lemma mk_preimage_of_injective_lift {α : Type u} {β : Type v} (f : α → β) (s : set β) (h : injective f) : lift.{u v} (mk (f ⁻¹' s)) ≤ lift.{v u} (mk s) := begin rw lift_mk_le.{u v 0}, use subtype.coind (λ x, f x.1) (λ x, x.2), apply subtype.coind_injective, exact h.comp subtype.val_injective end lemma mk_preimage_of_subset_range_lift {α : Type u} {β : Type v} (f : α → β) (s : set β) (h : s ⊆ range f) : lift.{v u} (mk s) ≤ lift.{u v} (mk (f ⁻¹' s)) := begin rw lift_mk_le.{v u 0}, refine ⟨⟨_, _⟩⟩, { rintro ⟨y, hy⟩, rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩, exact ⟨x, hy⟩ }, rintro ⟨y, hy⟩ ⟨y', hy'⟩, dsimp, rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩, rcases classical.subtype_of_exists (h hy') with ⟨x', rfl⟩, simp, intro hxx', rw hxx' end lemma mk_preimage_of_injective_of_subset_range_lift {β : Type v} (f : α → β) (s : set β) (h : injective f) (h2 : s ⊆ range f) : lift.{u v} (mk (f ⁻¹' s)) = lift.{v u} (mk s) := le_antisymm (mk_preimage_of_injective_lift f s h) (mk_preimage_of_subset_range_lift f s h2) lemma mk_preimage_of_injective (f : α → β) (s : set β) (h : injective f) : mk (f ⁻¹' s) ≤ mk s := by { convert mk_preimage_of_injective_lift.{u u} f s h using 1; rw [lift_id] } lemma mk_preimage_of_subset_range (f : α → β) (s : set β) (h : s ⊆ range f) : mk s ≤ mk (f ⁻¹' s) := by { convert mk_preimage_of_subset_range_lift.{u u} f s h using 1; rw [lift_id] } lemma mk_preimage_of_injective_of_subset_range (f : α → β) (s : set β) (h : injective f) (h2 : s ⊆ range f) : mk (f ⁻¹' s) = mk s := by { convert mk_preimage_of_injective_of_subset_range_lift.{u u} f s h h2 using 1; rw [lift_id] } lemma mk_subset_ge_of_subset_image_lift {α : Type u} {β : Type v} (f : α → β) {s : set α} {t : set β} (h : t ⊆ f '' s) : lift.{v u} (mk t) ≤ lift.{u v} (mk ({ x ∈ s | f x ∈ t } : set α)) := by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range_lift _ _ h using 1, rw [mk_sep], refl } lemma mk_subset_ge_of_subset_image (f : α → β) {s : set α} {t : set β} (h : t ⊆ f '' s) : mk t ≤ mk ({ x ∈ s | f x ∈ t } : set α) := by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range _ _ h using 1, rw [mk_sep], refl } theorem le_mk_iff_exists_subset {c : cardinal} {α : Type u} {s : set α} : c ≤ mk s ↔ ∃ p : set α, p ⊆ s ∧ mk p = c := begin rw [le_mk_iff_exists_set, ←subtype.exists_set_subtype], apply exists_congr, intro t, rw [mk_image_eq], apply subtype.val_injective end /-- The function α^{<β}, defined to be sup_{γ < β} α^γ. We index over {s : set β.out // mk s < β } instead of {γ // γ < β}, because the latter lives in a higher universe -/ noncomputable def powerlt (α β : cardinal.{u}) : cardinal.{u} := sup.{u u} (λ(s : {s : set β.out // mk s < β}), α ^ mk.{u} s) infix ` ^< `:80 := powerlt theorem powerlt_aux {c c' : cardinal} (h : c < c') : ∃(s : {s : set c'.out // mk s < c'}), mk s = c := begin cases out_embedding.mp (le_of_lt h) with f, have : mk ↥(range ⇑f) = c, { rwa [mk_range_eq, mk, quotient.out_eq c], exact f.2 }, exact ⟨⟨range f, by convert h⟩, this⟩ end lemma le_powerlt {c₁ c₂ c₃ : cardinal} (h : c₂ < c₃) : c₁ ^ c₂ ≤ c₁ ^< c₃ := by { rcases powerlt_aux h with ⟨s, rfl⟩, apply le_sup _ s } lemma powerlt_le {c₁ c₂ c₃ : cardinal} : c₁ ^< c₂ ≤ c₃ ↔ ∀(c₄ < c₂), c₁ ^ c₄ ≤ c₃ := begin rw [powerlt, sup_le], split, { intros h c₄ hc₄, rcases powerlt_aux hc₄ with ⟨s, rfl⟩, exact h s }, intros h s, exact h _ s.2 end lemma powerlt_le_powerlt_left {a b c : cardinal} (h : b ≤ c) : a ^< b ≤ a ^< c := by { rw [powerlt, sup_le], rintro ⟨s, hs⟩, apply le_powerlt, exact lt_of_lt_of_le hs h } lemma powerlt_succ {c₁ c₂ : cardinal} (h : c₁ ≠ 0) : c₁ ^< c₂.succ = c₁ ^ c₂ := begin apply le_antisymm, { rw powerlt_le, intros c₃ h2, apply power_le_power_left h, rwa [←lt_succ] }, { apply le_powerlt, apply lt_succ_self } end lemma powerlt_max {c₁ c₂ c₃ : cardinal} : c₁ ^< max c₂ c₃ = max (c₁ ^< c₂) (c₁ ^< c₃) := by { cases le_total c₂ c₃; simp only [max_eq_left, max_eq_right, h, powerlt_le_powerlt_left] } lemma zero_powerlt {a : cardinal} (h : a ≠ 0) : 0 ^< a = 1 := begin apply le_antisymm, { rw [powerlt_le], intros c hc, apply zero_power_le }, convert le_powerlt (pos_iff_ne_zero.2 h), rw [power_zero] end lemma powerlt_zero {a : cardinal} : a ^< 0 = 0 := by { apply sup_eq_zero, rintro ⟨x, hx⟩, rw [←not_le] at hx, apply hx, apply zero_le } end cardinal lemma equiv.cardinal_eq {α β} : α ≃ β → cardinal.mk α = cardinal.mk β := cardinal.eq_congr
599eaf54f4dbb113a9de346f5c9c379472dfafd0
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/stage0/src/Lean/Meta/TransparencyMode.lean
4d07fc9ddb1d585c5db7ff1614f85d84359d56e9
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
816
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 -/ namespace Lean.Meta inductive TransparencyMode where | all | default | reducible | instances deriving Inhabited, BEq, Repr namespace TransparencyMode def hash : TransparencyMode → USize | all => 7 | default => 11 | reducible => 13 | instances => 17 instance : Hashable TransparencyMode := ⟨hash⟩ def lt : TransparencyMode → TransparencyMode → Bool | reducible, default => true | reducible, all => true | reducible, instances => true | instances, default => true | instances, all => true | default, all => true | _, _ => false end TransparencyMode end Lean.Meta
99dbe70383a5d8a4232a64328324c444608dcca7
abd85493667895c57a7507870867b28124b3998f
/src/group_theory/group_action.lean
4b664b7c8df8efacc82536a8505c421839d322d1
[ "Apache-2.0" ]
permissive
pechersky/mathlib
d56eef16bddb0bfc8bc552b05b7270aff5944393
f1df14c2214ee114c9738e733efd5de174deb95d
refs/heads/master
1,666,714,392,571
1,591,747,567,000
1,591,747,567,000
270,557,274
0
0
Apache-2.0
1,591,597,975,000
1,591,597,974,000
null
UTF-8
Lean
false
false
10,581
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 data.set.finite import group_theory.coset universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- Typeclass for types with a scalar multiplication operation, denoted `•` (`\bu`) -/ class has_scalar (α : Type u) (γ : Type v) := (smul : α → γ → γ) infixr ` • `:73 := has_scalar.smul section prio set_option default_priority 100 -- see Note [default priority] /-- Typeclass for multiplicative actions by monoids. This generalizes group actions. -/ @[protect_proj] class mul_action (α : Type u) (β : Type v) [monoid α] extends has_scalar α β := (one_smul : ∀ b : β, (1 : α) • b = b) (mul_smul : ∀ (x y : α) (b : β), (x * y) • b = x • y • b) end prio section variables [monoid α] [mul_action α β] theorem mul_smul (a₁ a₂ : α) (b : β) : (a₁ * a₂) • b = a₁ • a₂ • b := mul_action.mul_smul _ _ _ lemma smul_smul (a₁ a₂ : α) (b : β) : a₁ • a₂ • b = (a₁ * a₂) • b := (mul_smul _ _ _).symm lemma smul_comm {α : Type u} {β : Type v} [comm_monoid α] [mul_action α β] (a₁ a₂ : α) (b : β) : a₁ • a₂ • b = a₂ • a₁ • b := by rw [←mul_smul, ←mul_smul, mul_comm] variable (α) @[simp] theorem one_smul (b : β) : (1 : α) • b = b := mul_action.one_smul _ variables {α} @[simp] lemma units.inv_smul_smul (u : units α) (x : β) : (↑u⁻¹:α) • (u:α) • x = x := by rw [smul_smul, u.inv_mul, one_smul] @[simp] lemma units.smul_inv_smul (u : units α) (x : β) : (u:α) • (↑u⁻¹:α) • x = x := by rw [smul_smul, u.mul_inv, one_smul] section gwz variables {G : Type*} [group_with_zero G] [mul_action G β] lemma inv_smul_smul' {c : G} (hc : c ≠ 0) (x : β) : c⁻¹ • c • x = x := (units.mk0 c hc).inv_smul_smul x lemma smul_inv_smul' {c : G} (hc : c ≠ 0) (x : β) : c • c⁻¹ • x = x := (units.mk0 c hc).smul_inv_smul x end gwz variables (p : Prop) [decidable p] lemma ite_smul (a₁ a₂ : α) (b : β) : (ite p a₁ a₂) • b = ite p (a₁ • b) (a₂ • b) := by split_ifs; refl lemma smul_ite (a : α) (b₁ b₂ : β) : a • (ite p b₁ b₂) = ite p (a • b₁) (a • b₂) := by split_ifs; refl end namespace mul_action variables (α) [monoid α] /-- The regular action of a monoid on itself by left multiplication. -/ def regular : mul_action α α := { smul := λ a₁ a₂, a₁ * a₂, one_smul := λ a, one_mul a, mul_smul := λ a₁ a₂ a₃, mul_assoc _ _ _, } variables [mul_action α β] /-- The orbit of an element under an action. -/ def orbit (b : β) := set.range (λ x : α, x • b) variable {α} lemma mem_orbit_iff {b₁ b₂ : β} : b₂ ∈ orbit α b₁ ↔ ∃ x : α, x • b₁ = b₂ := iff.rfl @[simp] lemma mem_orbit (b : β) (x : α) : x • b ∈ orbit α b := ⟨x, rfl⟩ @[simp] lemma mem_orbit_self (b : β) : b ∈ orbit α b := ⟨1, by simp [mul_action.one_smul]⟩ instance orbit_fintype (b : β) [fintype α] [decidable_eq β] : fintype (orbit α b) := set.fintype_range _ variable (α) /-- The stabilizer of an element under an action, i.e. what sends the element to itself. -/ def stabilizer (b : β) : set α := {x : α | x • b = b} variable {α} @[simp] lemma mem_stabilizer_iff {b : β} {x : α} : x ∈ stabilizer α b ↔ x • b = b := iff.rfl variables (α) (β) /-- The set of elements fixed under the whole action. -/ def fixed_points : set β := {b : β | ∀ x, x ∈ stabilizer α b} variables {α} (β) @[simp] lemma mem_fixed_points {b : β} : b ∈ fixed_points α β ↔ ∀ x : α, x • b = b := iff.rfl lemma mem_fixed_points' {b : β} : b ∈ fixed_points α β ↔ (∀ b', b' ∈ orbit α b → b' = b) := ⟨λ h b h₁, let ⟨x, hx⟩ := mem_orbit_iff.1 h₁ in hx ▸ h x, λ h b, mem_stabilizer_iff.2 (h _ (mem_orbit _ _))⟩ /-- An action of `α` on `β` and a monoid homomorphism `γ → α` induce an action of `γ` on `β`. -/ def comp_hom [monoid γ] (g : γ → α) [is_monoid_hom g] : mul_action γ β := { smul := λ x b, (g x) • b, one_smul := by simp [is_monoid_hom.map_one g, mul_action.one_smul], mul_smul := by simp [is_monoid_hom.map_mul g, mul_action.mul_smul] } instance (b : β) : is_submonoid (stabilizer α b) := { one_mem := one_smul _ b, mul_mem := λ a a' (ha : a • b = b) (hb : a' • b = b), by rw [mem_stabilizer_iff, ←smul_smul, hb, ha] } end mul_action namespace mul_action variables [group α] [mul_action α β] section open mul_action quotient_group @[simp] lemma inv_smul_smul (c : α) (x : β) : c⁻¹ • c • x = x := (to_units α c).inv_smul_smul x @[simp] lemma smul_inv_smul (c : α) (x : β) : c • c⁻¹ • x = x := (to_units α c).smul_inv_smul x variables (α) (β) /-- Given an action of a group `α` on a set `β`, each `g : α` defines a permutation of `β`. -/ def to_perm (g : α) : equiv.perm β := { to_fun := (•) g, inv_fun := (•) g⁻¹, left_inv := inv_smul_smul g, right_inv := smul_inv_smul g } variables {α} {β} instance : is_group_hom (to_perm α β) := { map_mul := λ x y, equiv.ext (λ a, mul_action.mul_smul x y a) } lemma bijective (g : α) : function.bijective (λ b : β, g • b) := (to_perm α β g).bijective lemma orbit_eq_iff {a b : β} : orbit α a = orbit α b ↔ a ∈ orbit α b:= ⟨λ h, h ▸ mem_orbit_self _, λ ⟨x, (hx : x • b = a)⟩, set.ext (λ c, ⟨λ ⟨y, (hy : y • a = c)⟩, ⟨y * x, show (y * x) • b = c, by rwa [mul_action.mul_smul, hx]⟩, λ ⟨y, (hy : y • b = c)⟩, ⟨y * x⁻¹, show (y * x⁻¹) • a = c, by conv {to_rhs, rw [← hy, ← mul_one y, ← inv_mul_self x, ← mul_assoc, mul_action.mul_smul, hx]}⟩⟩)⟩ instance (b : β) : is_subgroup (stabilizer α b) := { one_mem := mul_action.one_smul _, mul_mem := λ x y (hx : x • b = b) (hy : y • b = b), show (x * y) • b = b, by rw mul_action.mul_smul; simp *, inv_mem := λ x (hx : x • b = b), show x⁻¹ • b = b, by rw [← hx, ← mul_action.mul_smul, inv_mul_self, mul_action.one_smul, hx] } @[simp] lemma mem_orbit_smul (g : α) (a : β) : a ∈ orbit α (g • a) := ⟨g⁻¹, by simp⟩ @[simp] lemma smul_mem_orbit_smul (g h : α) (a : β) : g • a ∈ orbit α (h • a) := ⟨g * h⁻¹, by simp [mul_smul]⟩ variables (α) (β) /-- The relation "in the same orbit". -/ def orbit_rel : setoid β := { r := λ a b, a ∈ orbit α b, iseqv := ⟨mem_orbit_self, λ a b, by simp [orbit_eq_iff.symm, eq_comm], λ a b, by simp [orbit_eq_iff.symm, eq_comm] {contextual := tt}⟩ } variables {β} open quotient_group /-- Orbit-stabilizer theorem. -/ noncomputable def orbit_equiv_quotient_stabilizer (b : β) : orbit α b ≃ quotient (stabilizer α b) := equiv.symm (@equiv.of_bijective _ _ (λ x : quotient (stabilizer α b), quotient.lift_on' x (λ x, (⟨x • b, mem_orbit _ _⟩ : orbit α b)) (λ g h (H : _ = _), subtype.eq $ (mul_action.bijective (g⁻¹)).1 $ show g⁻¹ • (g • b) = g⁻¹ • (h • b), by rw [← mul_action.mul_smul, ← mul_action.mul_smul, H, inv_mul_self, mul_action.one_smul])) ⟨λ g h, quotient.induction_on₂' g h (λ g h H, quotient.sound' $ have H : g • b = h • b := subtype.mk.inj H, show (g⁻¹ * h) • b = b, by rw [mul_action.mul_smul, ← H, ← mul_action.mul_smul, inv_mul_self, mul_action.one_smul]), λ ⟨b, ⟨g, hgb⟩⟩, ⟨g, subtype.eq hgb⟩⟩) @[simp] theorem orbit_equiv_quotient_stabilizer_symm_apply (b : β) (a : α) : ((orbit_equiv_quotient_stabilizer α b).symm a : β) = a • b := rfl end open quotient_group mul_action is_subgroup /-- Action on left cosets. -/ def mul_left_cosets (H : set α) [is_subgroup H] (x : α) (y : quotient H) : quotient H := quotient.lift_on' y (λ y, quotient_group.mk ((x : α) * y)) (λ a b (hab : _ ∈ H), quotient_group.eq.2 (by rwa [mul_inv_rev, ← mul_assoc, mul_assoc (a⁻¹), inv_mul_self, mul_one])) instance (H : set α) [is_subgroup H] : mul_action α (quotient H) := { smul := mul_left_cosets H, one_smul := λ a, quotient.induction_on' a (λ a, quotient_group.eq.2 (by simp [is_submonoid.one_mem])), mul_smul := λ x y a, quotient.induction_on' a (λ a, quotient_group.eq.2 (by simp [mul_inv_rev, is_submonoid.one_mem, mul_assoc])) } instance mul_left_cosets_comp_subtype_val (H I : set α) [is_subgroup H] [is_subgroup I] : mul_action I (quotient H) := mul_action.comp_hom (quotient H) (subtype.val : I → α) end mul_action section prio set_option default_priority 100 -- see Note [default priority] /-- Typeclass for multiplicative actions on additive structures. This generalizes group modules. -/ class distrib_mul_action (α : Type u) (β : Type v) [monoid α] [add_monoid β] extends mul_action α β := (smul_add : ∀(r : α) (x y : β), r • (x + y) = r • x + r • y) (smul_zero : ∀(r : α), r • (0 : β) = 0) end prio section variables [monoid α] [add_monoid β] [distrib_mul_action α β] theorem smul_add (a : α) (b₁ b₂ : β) : a • (b₁ + b₂) = a • b₁ + a • b₂ := distrib_mul_action.smul_add _ _ _ @[simp] theorem smul_zero (a : α) : a • (0 : β) = 0 := distrib_mul_action.smul_zero _ theorem units.smul_eq_zero (u : units α) {x : β} : (u : α) • x = 0 ↔ x = 0 := ⟨λ h, by rw [← u.inv_smul_smul x, h, smul_zero], λ h, h.symm ▸ smul_zero _⟩ theorem units.smul_ne_zero (u : units α) {x : β} : (u : α) • x ≠ 0 ↔ x ≠ 0 := not_congr u.smul_eq_zero @[simp] theorem is_unit.smul_eq_zero {u : α} (hu : is_unit u) {x : β} : u • x = 0 ↔ x = 0 := exists.elim hu $ λ u hu, hu ▸ u.smul_eq_zero variable (β) /-- Scalar multiplication by `r` as an `add_monoid_hom`. -/ def const_smul_hom (r : α) : β →+ β := { to_fun := (•) r, map_zero' := smul_zero r, map_add' := smul_add r } variable {β} @[simp] lemma const_smul_hom_apply (r : α) (x : β) : const_smul_hom β r x = r • x := rfl lemma list.smul_sum {r : α} {l : list β} : r • l.sum = (l.map ((•) r)).sum := (const_smul_hom β r).map_list_sum l end section variables [monoid α] [add_comm_monoid β] [distrib_mul_action α β] lemma multiset.smul_sum {r : α} {s : multiset β} : r • s.sum = (s.map ((•) r)).sum := (const_smul_hom β r).map_multiset_sum s lemma finset.smul_sum {r : α} {f : γ → β} {s : finset γ} : r • s.sum f = s.sum (λ x, r • f x) := (const_smul_hom β r).map_sum f s end
e8935c414f5982e7524ab6d3959377c90423cd35
947b78d97130d56365ae2ec264df196ce769371a
/tests/bench/parser.lean
e3457f97262d20ace4a7987aa17db3d961909848
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
236
lean
import Lean.Parser def main : List String → IO Unit | [fname, n] => do env ← Lean.mkEmptyEnvironment; n.toNat!.forM $ fun _ => discard $ Lean.Parser.parseFile env fname; pure () | _ => throw $ IO.userError "give file"
c98094e562b89572fce42b8dfd87f77fdf3704a7
5df84495ec6c281df6d26411cc20aac5c941e745
/src/formal_ml/finite_pi_measure.lean
b51522ecd4b8fa344265dab4b44dcfb8264856b9
[ "Apache-2.0" ]
permissive
eric-wieser/formal-ml
e278df5a8df78aa3947bc8376650419e1b2b0a14
630011d19fdd9539c8d6493a69fe70af5d193590
refs/heads/master
1,681,491,589,256
1,612,642,743,000
1,612,642,743,000
360,114,136
0
0
Apache-2.0
1,618,998,189,000
1,618,998,188,000
null
UTF-8
Lean
false
false
21,412
lean
/- Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -/ import measure_theory.measurable_space import measure_theory.measure_space import measure_theory.outer_measure import measure_theory.lebesgue_measure import measure_theory.integration import measure_theory.borel_space import data.set.countable import formal_ml.nnreal import formal_ml.ennreal import formal_ml.sum import formal_ml.lattice import formal_ml.measurable_space import formal_ml.classical import formal_ml.core import formal_ml.characteristic import formal_ml.measure import data.equiv.list noncomputable def pi.outer_measure {α:Type*} [F:fintype α] [N:nonempty α] {β:α → Type*} [M:∀ a, measurable_space (β a)] (μ:Π a, measure_theory.outer_measure (β a)):measure_theory.outer_measure (Π a, β a) := measure_theory.outer_measure.of_function (λ P:set (Π a, β a), finset.univ.prod (λ (a:α), (μ a) ((λ (p:Π a, β a), p a) '' P))) begin simp, rw finset.card_pos, rw finset.univ_nonempty_iff, apply N, end section pi open_locale classical lemma ennreal.prod_le_prod {α:Type*} {f g:α → ennreal} {s:finset α}:(∀ a∈ s, f a ≤ g a) → s.prod f ≤ s.prod g := begin apply finset.induction_on s, { intros h_le, simp, apply le_refl _ }, { intros a s' h_not_mem h_ind h_le, rw finset.prod_insert h_not_mem, rw finset.prod_insert h_not_mem, apply ennreal.mul_le_mul, apply h_le, simp, apply h_ind, intros a' h_le_a', apply h_le, simp [h_le_a'], }, end lemma finset.insert_erase_univ {α:Type*} [F:fintype α] {d:α}: insert d (finset.univ.erase d) = finset.univ := begin rw finset.insert_erase, apply finset.mem_univ, end noncomputable def pi.measure {α:Type*} [F:fintype α] [N:nonempty α] {β:α → Type*} [M:∀ a, measurable_space (β a)] (μ:Π a, measure_theory.measure (β a)):measure_theory.measure (Π a, β a) := (pi.outer_measure (λ a, (μ a).to_outer_measure)).to_measure begin unfold measurable_space.pi, simp, intros d, intros P A1, unfold measurable_space.comap at A1, simp at A1, cases A1 with s A1, cases A1 with A1 A2, subst P, apply measure_theory.outer_measure.of_function_caratheodory, simp, intros t, have D1:finset.univ = insert d (finset.univ.erase d), { rw finset.insert_erase_univ }, rw D1, rw finset.prod_insert, rw finset.prod_insert, rw finset.prod_insert, have B1:(μ d) ((λ (p : Π (a : α), (λ (a : α), β a) a), p d) '' t∩ s) + (μ d) ((λ (p : Π (a : α), (λ (a : α), β a) a), p d) '' t\ s) = (μ d) ((λ (p : Π (a : α), (λ (a : α), β a) a), p d) '' t), { rw ← measure_theory.measure_eq_inter_diff', apply A1 }, rw ← B1, clear B1, rw right_distrib, apply @add_le_add ennreal _; apply ennreal.mul_le_mul; try {apply measure_theory.measure_mono}; try { simp, apply set.subset.trans, apply set.inter_subset_left, apply set.subset_preimage_image }; try { apply ennreal.prod_le_prod, intros a h_a_mem, apply measure_theory.measure_mono, simp, apply set.subset.trans, apply set.inter_subset_left, apply set.subset_preimage_image }, { simp, apply set.diff_subset_diff_left, apply set.subset_preimage_image }, repeat {simp}, end def cast.pi {α:Type*} {β:α → Type*} {a a':α} (b:β a) (h:a = a'):β a' := cast begin rw h end b def subst.pi {α:Type*} [decidable_eq α] {β:α → Type*} (f:Π (a:α), β a) (a':α) (b:β a'):Π (a:α), β a := λ (a:α), @dite (a' = a) _ (β a) (λ h, cast.pi b h) (λ h, f a) lemma subst.pi_eq {α:Type*} [decidable_eq α] {β:α → Type*} (f:Π (a:α), β a) (a':α) (b:β a'): (subst.pi f a' b) a' = b := begin simp [subst.pi], refl, end lemma subst.pi_ne {α:Type*} [decidable_eq α] {β:α → Type*} (f:Π (a:α), β a) (a a':α) (b:β a') (h:a' ≠ a): (subst.pi f a' b) a = f a := begin simp [subst.pi], rw dif_neg, apply h, end lemma set.project_pi {α:Type*} {β:α → Type*} {f:Π (a:α), set (β a)} (h:∀ a, (f a).nonempty) {a':α}: ((λ (p : Π (a : α), β a), p a') '' (set.pi set.univ f)) = f a' := begin ext x, split;intros A1, simp [set.pi] at A1, { cases A1 with y A1, cases A1 with A1 A2, subst x, apply A1 }, { simp [set.pi], have h2:∀ (a:α), ∃ b:β a, b ∈ (f a), { intros a, rw ← set.nonempty_def, apply h }, rw classical.skolem at h2, cases h2 with g h2, apply exists.intro (subst.pi g a' x), split, intros q, cases (classical.em (a' = q)) with A3 A3, { subst q, rw subst.pi_eq, apply A1 }, { rw subst.pi_ne, apply h2, apply A3, }, rw subst.pi_eq }, end lemma set.pi_empty {α:Type*} {β:α → Type*} {f:Π (a:α), set (β a)} {a':α} (h2:f a' = ∅): (set.pi set.univ f) = ∅ := begin ext x, simp, split, { have h3:x a' ∉ f a', { simp [h2] }, apply h3, }, end lemma pi.outer_measure.Inf_sum {α:Type*} [F:fintype α] [N:nonempty α] {β:α → Type*} [M:∀ a, measurable_space (β a)] (μ:Π a, measure_theory.outer_measure (β a)) {P:set (Π a, β a)}: pi.outer_measure μ P = (⨅ (f:ℕ → (Π (a:α), set (β a))) (h₁:P ⊆ ⋃ (n:ℕ), set.pi set.univ (f n)), ∑' (n:ℕ), finset.univ.prod (λ (m:α), μ m (f n m))) := begin unfold pi.outer_measure measure_theory.outer_measure.of_function, rw ← measure_theory.outer_measure.measure_of_eq_coe, simp, apply le_antisymm, { simp, intros f B1, apply @infi_le_of_le ennreal _ _ _ _ (λ (n:ℕ), set.pi set.univ ((f n))), apply @infi_le_of_le ennreal _ _ _ _ _, apply ennreal.tsum_le_tsum, intros n, cases (classical.em (∀ (a:α), (f n a).nonempty)) with B2 B2, { have D1:(λ (a : α), (μ a) ((λ (p : Π (a : α), β a), p a) '' (λ (n : ℕ), set.pi set.univ (f n)) n)) = (λ (m : α), (μ m) (f n m)), { ext1 a, simp [set.project_pi], rw set.project_pi, apply B2 }, rw D1, apply le_refl _, }, { rw classical.not_forall_iff_exists_not at B2, cases B2 with a B2, rw set.not_nonempty_iff_eq_empty at B2, rw @finset.prod_eq_zero _ _ _ a, rw @finset.prod_eq_zero _ _ _ a, apply le_refl _, apply finset.mem_univ, rw B2, apply measure_theory.outer_measure.empty, apply finset.mem_univ, simp, rw set.pi_empty B2, simp }, apply B1 }, { simp, intros f A1, let f':ℕ → (Π (a:α), set (β a)) := (λ n m, ((λ (p:Π (a:α), β a), p m) '' (f n))), begin apply @infi_le_of_le ennreal (ℕ → (Π (a:α), set (β a))) _ _ _ f', rw infi_prop_def, simp [f'], apply le_refl _, apply @set.subset.trans (Π a, β a) P (set.Union f) (⋃ (n : ℕ), set.pi set.univ (f' n)) A1, apply set.Union_subset_Union, intros i, rw set.subset_def, intros x A1, simp, intros a, apply exists.intro x, simp [A1], end }, end lemma set.pi_subset_pi {α:Type*} {β:α → Type*} {S:Π (a:α), set (β a)} {T:Π (a:α), set (β a)}: (∀ a, S a ⊆ T a) → set.pi set.univ S ⊆ set.pi set.univ T := begin rw set.subset_def, intros A0 x A1, simp, intros a, simp at A1, apply A0, apply A1, end lemma pi.outer_measure.Inf_sum2 {α:Type*} [F:fintype α] [N:nonempty α] {β:α → Type*} [M:∀ (a:α), measurable_space (β a)] (μ:Π (a:α), measure_theory.measure (β a)) {P:set (Π (a:α), β a)}: pi.outer_measure (λ (a:α), (μ a).to_outer_measure) P = (⨅ (f:ℕ → (Π (a:α), set (β a))) (h₁:∀ n m, measurable_set (f n m)) (h₃:P ⊆ ⋃ (n:ℕ), set.pi set.univ (f n)), ∑' (n:ℕ), finset.univ.prod (λ (m:α), μ m (f n m))) := begin rw pi.outer_measure.Inf_sum, apply le_antisymm, { simp, intros f h₁ h₃, apply @infi_le_trans (ℕ→ Π (a:α), set (β a)) ennreal _ f, rw infi_prop_def, apply le_refl _, apply h₃ }, { simp, intros f h₁, have h4_2 := λ (n:ℕ) (m:α), measure_theory.measurable_eq (μ m) (f n m), have h4:∀ n, ∃ (g:Π (a:α), set (β a)), ∀ (a:α), measurable_set (g a) ∧ (μ a) (g a) = (μ a) (f n a) ∧ f n a ⊆ g a, { intros n, have h5_1 := h4_2 n, apply classical.axiom_of_choice h5_1, }, rw classical.skolem at h4, cases h4 with f' h4, apply @infi_le_trans (ℕ→ (Π (a:α), set (β a))) ennreal _ f', rw infi_prop_def, rw infi_prop_def, { apply ennreal.tsum_le_tsum, intro n, apply ennreal.prod_le_prod, intros a h_dummy, rw (h4 n a).right.left, apply le_refl _, }, apply set.subset.trans, apply h₁, apply set.Union_subset_Union, intro n, apply set.pi_subset_pi, intros a, apply (h4 n a).right.right, intros n m, apply (h4 n m).left, }, end /- If we can make this into an equality, we're home free. See https://www.math.ucdavis.edu/~hunter/measure_theory/measure_notes_ch5.pdf Those notes focus on measurable sets. We could theoretically do the same. However, it would make the rest of the analysis much more complex. I wonder if using an "outer measure lower integral" would make this useful. -/ lemma pi.outer_measure.apply_prod_le {α:Type*} [F:fintype α] [N:nonempty α] {β:α → Type*} [M:∀ a, measurable_space (β a)] (μ:Π a, measure_theory.outer_measure (β a)) {P:(Π a, set (β a))}: pi.outer_measure μ (set.pi set.univ P) ≤ finset.univ.prod (λ a, μ a (P a)) := begin rw pi.outer_measure.Inf_sum, { apply @infi_le_of_le ennreal _ _ _ _ (λ (n:ℕ) (a:α), ite (n = 0) (P a) ∅), apply @infi_le_of_le ennreal _ _ _ _ _, rw tsum_eq_single 0, {simp [le_refl]}, intros b' B1, simp [B1], rw finset.card_pos, rw finset.univ_nonempty_iff, apply N, apply ennreal.t2_space, rw set.subset_def, intros p B2, simp, apply exists.intro 0, {simp at B2,simp [B2]}}, end lemma set.characteristic.pi {α:Type*} [F:fintype α] {β:α → Type*} {P:Π a, set (β a)} {x:Π a, β a}:(set.pi set.univ P).characteristic x = finset.univ.prod (λ a, (P a).characteristic (x a)) := begin have A1:∀ S:finset α, (set.pi (↑S) P).characteristic x = S.prod (λ a, (P a).characteristic (x a)), { intros S, apply finset.induction_on S, { simp }, { intros a T h_not_mem h_ind, rw finset.prod_insert h_not_mem, rw ← h_ind, cases classical.em ((x a) ∈ (P a)) with A1 A1, rw set.characteristic.of_mem A1, rw one_mul, cases classical.em (x ∈ (set.pi (↑T) P)) with A2 A2, { rw set.characteristic.of_mem A2, rw set.characteristic.of_mem, simp at A2, simp [A1,A2], apply A2, }, { rw set.characteristic.of_not_mem A2, rw set.characteristic.of_not_mem, simp at A2, simp [A1,A2], }, { rw set.characteristic.of_not_mem A1, rw zero_mul, rw set.characteristic.of_not_mem, simp [A1], } } }, have A2:set.univ = ↑(finset.univ), { ext x, split; intros A1, rw @finset.mem_coe α x, simp, simp }, rw A2, apply A1, end lemma finset.prod_univ_diff_insert {α:Type*} [fintype α] (f:α → ennreal) (A:finset α) (a:α) (h:a∉ A): (finset.univ \ A).prod f = f a * (finset.univ \ (insert a A)).prod f := begin have A1:finset.univ \ A = (insert a (finset.univ \ (insert a A))), { ext x, split;intros A1_1; simp at A1_1; simp [A1_1], apply classical.em (x = a), cases A1_1, subst x, apply h, intros contra, apply A1_1, right, apply contra }, rw A1, rw finset.prod_insert, simp, end lemma pi.outer_measure.le_apply_prod {α:Type*} [F:fintype α] [N:nonempty α] {β:α → Type*} [M:∀ a, measurable_space (β a)] (μ:Π a, measure_theory.measure (β a)) {P:(Π a, set (β a))}:(∀ (a:α), measurable_set (P a)) → finset.univ.prod (λ a, μ a (P a)) ≤ pi.outer_measure (λ a, (μ a).to_outer_measure) (set.pi set.univ P) := begin intro A4, /- Due to an implementation detail, it is best to consider an empty set separately. -/ cases (classical.em (∀ (a:α), (P a).nonempty)) with h_all_nonempty h_exists_empty, rw pi.outer_measure.Inf_sum2, simp, intros f A2 A3, have h2:(set.pi set.univ P).characteristic ≤ ∑' (n : ℕ), (set.pi set.univ (f n)).characteristic, { apply function.le_trans (set.characteristic.subset A3), apply set.characteristic.Union }, have h3:∀ (x:Π (a:α), β a), finset.univ.prod (λ a, (P a).characteristic (x a)) ≤ ∑' (n : ℕ), finset.univ.prod (λ a, (f n a).characteristic (x a)), { intros x, rw ← set.characteristic.pi, have h3a: (λ n, (finset.univ.prod (λ a, (f n a).characteristic (x a)))) = (λ n, (set.pi (set.univ) (f n)).characteristic x), { ext1 n, rw set.characteristic.pi }, rw h3a, have h3b:((∑' (n : ℕ), (set.pi set.univ (f n)).characteristic) x) = (∑' (n : ℕ), (set.pi set.univ (f n)).characteristic x) , { apply ennreal.tsum_apply }, rw ← h3b, apply h2 }, have h4:∀ (A:finset α), ∀ (x:Π (a:α), β a), (A.prod (λ a, μ a (P a))) * ((finset.univ \ A).prod (λ a, (P a).characteristic (x a))) ≤ ∑' (n:ℕ), (A.prod (λ a, μ a (f n a))) * ((finset.univ \ A).prod (λ a, (f n a).characteristic (x a))), { intros A, apply finset.induction_on A, { intros x, simp, apply h3 }, { intros a' s h_not_mem h_ind x, have h4_1:(λ (x':β a'), (P a').characteristic (x') * (s.prod (λ (a : α), (μ a) (P a)) * (finset.univ \ insert a' s).prod (λ (a : α), (P a).characteristic (x a)))) ≤ (λ (x':β a'), ∑' (n : ℕ), (f n a').characteristic (x') * (s.prod (λ (a : α), (μ a) (f n a)) * (finset.univ \ insert a' s).prod (λ (a : α), (f n a).characteristic (x a)))), { rw has_le_fun_def, intros x', have h4_1_1 := h_ind (subst.pi x a' x'), have h4_1_2 :s.prod (λ (a : α), (μ a) (P a)) * (finset.univ \ s).prod (λ (a : α), (P a).characteristic (subst.pi x a' x' a)) = (P a').characteristic (x') * (s.prod (λ (a : α), (μ a) (P a)) * (finset.univ \ insert a' s).prod (λ (a : α), (P a).characteristic (x a))), { have h4_1_2_1: (finset.univ \ (insert a' s)).prod (λ (a : α), (P a).characteristic (subst.pi x a' x' a)) = (finset.univ \ (insert a' s)).prod (λ ⦃a' : α⦄, (P a').characteristic (x a')), { apply finset.prod_congr, refl, intros a'' h4_1_2_1_1, rw subst.pi_ne, simp at h4_1_2_1_1, intros contra, apply h4_1_2_1_1, left, rw contra, }, rw ← h4_1_2_1, clear h4_1_2_1, rw ← mul_assoc, rw mul_comm ((P a').characteristic (x')), rw mul_assoc, have h4_1_2_2:(P a').characteristic x' = (λ a, (P a).characteristic (subst.pi x a' x' a)) a', { simp, rw subst.pi_eq x a' x' }, rw h4_1_2_2, rw finset.prod_univ_diff_insert _ _ a' h_not_mem, }, rw h4_1_2 at h4_1_1, clear h4_1_2, have h4_1_3:(λ (n : ℕ), s.prod (λ (a : α), (μ a) (f n a)) * (finset.univ \ s).prod (λ (a : α), (f n a).characteristic (subst.pi x a' x' a))) = (λ (n:ℕ), (f n a').characteristic x' * (s.prod (λ (a : α), (μ a) (f n a)) * (finset.univ \ insert a' s).prod (λ (a : α), (f n a).characteristic (x a)))), { ext1 n, have h4_1_2_1: (finset.univ \ (insert a' s)).prod (λ (a : α), (f n a).characteristic (subst.pi x a' x' a)) = (finset.univ \ (insert a' s)).prod (λ ⦃a' : α⦄, (f n a').characteristic (x a')), { apply finset.prod_congr, refl, intros a'' h4_1_2_1_1, rw subst.pi_ne, simp at h4_1_2_1_1, intros contra, apply h4_1_2_1_1, left, rw contra, }, rw ← h4_1_2_1, clear h4_1_2_1, rw ← mul_assoc, rw mul_comm ((f n a').characteristic (x')), rw mul_assoc, have h4_1_2_2:(f n a').characteristic x' = (λ a, (f n a).characteristic (subst.pi x a' x' a)) a', { simp, rw subst.pi_eq x a' x' }, rw h4_1_2_2, rw finset.prod_univ_diff_insert _ _ a' h_not_mem, }, rw h4_1_3 at h4_1_1, clear h4_1_3, apply h4_1_1, }, have h4_2:measure_theory.lintegral (μ a') (λ (x':β a'), (P a').characteristic (x') * (s.prod (λ (a : α), (μ a) (P a)) * (finset.univ \ insert a' s).prod (λ (a : α), (P a).characteristic (x a)))) ≤ measure_theory.lintegral (μ a') (λ (x':β a'), ∑' (n : ℕ), (f n a').characteristic (x') * (s.prod (λ (a : α), (μ a) (f n a)) * (finset.univ \ insert a' s).prod (λ (a : α), (f n a).characteristic (x a)))), { apply measure_theory.lintegral_mono, apply h4_1, }, clear h4_1, have h4_3:measure_theory.lintegral (μ a') (λ (x':β a'), (P a').characteristic (x') * (s.prod (λ (a : α), (μ a) (P a)) * (finset.univ \ insert a' s).prod (λ (a : α), (P a).characteristic (x a)))) = (insert a' s).prod (λ (a : α), (μ a) (P a)) * (finset.univ \ insert a' s).prod (λ (a : α), (P a).characteristic (x a)), { rw measure_theory.lintegral_mul_const, rw measure_theory.lintegral_characteristic, rw ← mul_assoc, rw finset.prod_insert h_not_mem, apply A4, apply measurable.characteristic, apply A4 }, rw h4_3 at h4_2, clear h4_3, have h4_4:(∫⁻ (x' : β a'), (∑' (n : ℕ), (f n a').characteristic x' * (s.prod (λ (a : α), (μ a) (f n a)) * (finset.univ \ insert a' s).prod (λ (a : α), (f n a).characteristic (x a)))) ∂μ a') = (∑' (n : ℕ), ∫⁻ (x' : β a'), (f n a').characteristic x' * (s.prod (λ (a : α), (μ a) (f n a)) * (finset.univ \ insert a' s).prod (λ (a : α), (f n a).characteristic (x a))) ∂μ a'), { rw measure_theory.lintegral_tsum, intros n, apply measurable.ennreal_mul, apply measurable.characteristic, apply A2, apply measurable_const }, rw h4_4 at h4_2, clear h4_4, have h4_5:(λ (n : ℕ), ∫⁻ (x' : β a'), (f n a').characteristic x' * (s.prod (λ (a : α), (μ a) (f n a)) * (finset.univ \ insert a' s).prod (λ (a : α), (f n a).characteristic (x a))) ∂μ a') = (λ (n : ℕ), (insert a' s).prod (λ (a : α), (μ a) (f n a)) * (finset.univ \ insert a' s).prod (λ (a : α), (f n a).characteristic (x a))), { ext1 n, rw measure_theory.lintegral_mul_const, rw measure_theory.lintegral_characteristic, rw ← mul_assoc, rw finset.prod_insert h_not_mem, apply A2, apply measurable.characteristic, apply A2, }, rw h4_5 at h4_2, clear h4_5, apply h4_2, } }, have h7:∀ (a:α), ∃ x, x ∈ P a, { intros a, rw ← set.nonempty_def, apply h_all_nonempty }, have h8 := classical.axiom_of_choice h7, cases h8 with g h8, have h6 := h4 finset.univ g, simp at h6, apply h6, rw classical.not_forall_iff_exists_not at h_exists_empty, cases h_exists_empty with a h_empty, rw set.not_nonempty_iff_eq_empty at h_empty, rw @finset.prod_eq_zero _ _ _ a, { simp }, { simp }, simp [h_empty], end lemma pi.measure_apply {α:Type*} [F:fintype α] [N:nonempty α] {β:α → Type*} [M:∀ a, measurable_space (β a)] (μ:Π a, measure_theory.measure (β a)) {P:set (Π a, β a)}:measurable_set P → pi.measure μ P = pi.outer_measure (λ a, (μ a).to_outer_measure) P := begin intro h, simp [pi.measure], rw measure_theory.to_measure_apply, apply h, end lemma measurable_set.pi'' {α:Type*} [F:fintype α] {β:α → Type*} [M:∀ a, measurable_space (β a)] {P:Π a, set (β a)}:(∀ a, measurable_set (P a)) → measurable_set (set.pi set.univ P) := begin intros A0, have A1:(set.pi set.univ P) = ⋂ a, ((λ (p:Π a, β a), p a) ⁻¹' (P a)), { ext x, simp, }, rw A1, have A3:trunc (encodable α) := encodable.trunc_encodable_of_fintype α, trunc_cases A3, haveI:encodable α := A3, apply measurable_set.Inter, intros a', have A2:measurable_space.comap (λ (p:Π a, β a), p a') (M a') ≤ measurable_space.pi, { simp [measurable_space.pi], apply @le_supr (measurable_space (Π a, β a)) _ _ _ (a') }, apply A2, simp [measurable_space.comap], apply exists.intro (P a'), simp, apply A0 a', end lemma pi.measure.apply_prod {α:Type*} [F:fintype α] [N:nonempty α] {β:α → Type*} [M:∀ a, measurable_space (β a)] (μ:Π a, measure_theory.measure (β a)) {P:Π a, set (β a)}:(∀ a, measurable_set (P a)) → pi.measure μ (set.pi set.univ P) = finset.univ.prod (λ a, μ a (P a)) := begin intros A1, rw pi.measure_apply, apply le_antisymm, { apply pi.outer_measure.apply_prod_le }, apply pi.outer_measure.le_apply_prod, apply A1, apply measurable_set.pi'' A1, end end pi
b257dfabd0cf828843683cdd6e423859f441d577
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Init/Prelude.lean
40da57bd6cef2ba08e07c5fe92c4f5310556cc51
[ "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
165,230
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, Mario Carneiro -/ prelude -- Don't import Init, because we're in Init itself set_option linter.missingDocs true -- keep it documented /-! # Init.Prelude This is the first file in the lean import hierarchy. It is responsible for setting up basic definitions, most of which lean already has "built in knowledge" about, so it is important that they be set up in exactly this way. (For example, lean will use `PUnit` in the desugaring of `do` notation, or in the pattern match compiler.) -/ universe u v w /-- The identity function. `id` takes an implicit argument `α : Sort u` (a type in any universe), and an argument `a : α`, and returns `a`. Although this may look like a useless function, one application of the identity function is to explicitly put a type on an expression. If `e` has type `T`, and `T'` is definitionally equal to `T`, then `@id T' e` typechecks, and lean knows that this expression has type `T'` rather than `T`. This can make a difference for typeclass inference, since `T` and `T'` may have different typeclass instances on them. `show T' from e` is sugar for an `@id T' e` expression. -/ @[inline] def id {α : Sort u} (a : α) : α := a /-- Function composition is the act of pipelining the result of one function, to the input of another, creating an entirely new function. Example: ``` #eval Function.comp List.reverse (List.drop 2) [3, 2, 4, 1] -- [1, 4] ``` You can use the notation `f ∘ g` as shorthand for `Function.comp f g`. ``` #eval (List.reverse ∘ List.drop 2) [3, 2, 4, 1] -- [1, 4] ``` A simpler way of thinking about it, is that `List.reverse ∘ List.drop 2` is equivalent to `fun xs => List.reverse (List.drop 2 xs)`, the benefit is that the meaning of composition is obvious, and the representation is compact. -/ @[inline] def Function.comp {α : Sort u} {β : Sort v} {δ : Sort w} (f : β → δ) (g : α → β) : α → δ := fun x => f (g x) /-- The constant function. If `a : α`, then `Function.const β a : β → α` is the "constant function with value `a`", that is, `Function.const β a b = a`. ``` example (b : Bool) : Function.const Bool 10 b = 10 := rfl #check Function.const Bool 10 -- Bool → Nat ``` -/ @[inline] def Function.const {α : Sort u} (β : Sort v) (a : α) : β → α := fun _ => a set_option checkBinderAnnotations false in /-- `inferInstance` synthesizes a value of any target type by typeclass inference. This function has the same type signature as the identity function, but the square brackets on the `[i : α]` argument means that it will attempt to construct this argument by typeclass inference. (This will fail if `α` is not a `class`.) Example: ``` #check (inferInstance : Inhabited Nat) -- Inhabited Nat def foo : Inhabited (Nat × Nat) := inferInstance example : foo.default = (default, default) := rfl ``` -/ @[reducible] def inferInstance {α : Sort u} [i : α] : α := i set_option checkBinderAnnotations false in /-- `inferInstanceAs α` synthesizes a value of any target type by typeclass inference. This is just like `inferInstance` except that `α` is given explicitly instead of being inferred from the target type. It is especially useful when the target type is some `α'` which is definitionally equal to `α`, but the instance we are looking for is only registered for `α` (because typeclass search does not unfold most definitions, but definitional equality does.) Example: ``` #check inferInstanceAs (Inhabited Nat) -- Inhabited Nat ``` -/ @[reducible] def inferInstanceAs (α : Sort u) [i : α] : α := i set_option bootstrap.inductiveCheckResultingUniverse false in /-- The unit type, the canonical type with one element, named `unit` or `()`. This is the universe-polymorphic version of `Unit`; it is preferred to use `Unit` instead where applicable. For more information about universe levels: [Types as objects](https://leanprover.github.io/theorem_proving_in_lean4/dependent_type_theory.html#types-as-objects) -/ inductive PUnit : Sort u where | /-- `PUnit.unit : PUnit` is the canonical element of the unit type. -/ unit : PUnit /-- The unit type, the canonical type with one element, named `unit` or `()`. In other words, it describes only a single value, which consists of said constructor applied to no arguments whatsoever. The `Unit` type is similar to `void` in languages derived from C. `Unit` is actually defined as `PUnit.{0}` where `PUnit` is the universe polymorphic version. The `Unit` should be preferred over `PUnit` where possible to avoid unnecessary universe parameters. In functional programming, `Unit` is the return type of things that "return nothing", since a type with one element conveys no additional information. When programming with monads, the type `m Unit` represents an action that has some side effects but does not return a value, while `m α` would be an action that has side effects and returns a value of type `α`. -/ abbrev Unit : Type := PUnit /-- `Unit.unit : Unit` is the canonical element of the unit type. It can also be written as `()`. -/ @[matchPattern] abbrev Unit.unit : Unit := PUnit.unit /-- Marker for information that has been erased by the code generator. -/ unsafe axiom lcErased : Type /-- "Any" type in the simpler type system used by the code generator. -/ unsafe axiom lcAny : Type /-- Auxiliary unsafe constant used by the Compiler when erasing proofs from code. It may look strange to have an axiom that says "every proposition is true", since this is obviously unsound, but the `unsafe` marker ensures that the kernel will not let this through into regular proofs. The lower levels of the code generator don't need proofs in terms, so this is used to stub the proofs out. -/ unsafe axiom lcProof {α : Prop} : α /-- Auxiliary unsafe constant used by the Compiler when erasing casts. -/ unsafe axiom lcCast {α : Sort u} {β : Sort v} (a : α) : β /-- Auxiliary unsafe constant used by the Compiler to mark unreachable code. Like `lcProof`, this is an `unsafe axiom`, which means that even though it is not sound, the kernel will not let us use it for regular proofs. Executing this expression to actually synthesize a value of type `α` causes **immediate undefined behavior**, and the compiler does take advantage of this to optimize the code assuming that it is not called. If it is not optimized out, it is likely to appear as a print message saying "unreachable code", but this behavior is not guaranteed or stable in any way. -/ unsafe axiom lcUnreachable {α : Sort u} : α /-- `True` is a proposition and has only an introduction rule, `True.intro : True`. In other words, `True` is simply true, and has a canonical proof, `True.intro` For more information: [Propositional Logic](https://leanprover.github.io/theorem_proving_in_lean4/propositions_and_proofs.html#propositional-logic) -/ inductive True : Prop where | /-- `True` is true, and `True.intro` (or more commonly, `trivial`) is the proof. -/ intro : True /-- `False` is the empty proposition. Thus, it has no introduction rules. It represents a contradiction. `False` elimination rule, `False.rec`, expresses the fact that anything follows from a contradiction. This rule is sometimes called ex falso (short for ex falso sequitur quodlibet), or the principle of explosion. For more information: [Propositional Logic](https://leanprover.github.io/theorem_proving_in_lean4/propositions_and_proofs.html#propositional-logic) -/ inductive False : Prop /-- The empty type. It has no constructors. The `Empty.rec` eliminator expresses the fact that anything follows from the empty type. -/ inductive Empty : Type set_option bootstrap.inductiveCheckResultingUniverse false in /-- The universe-polymorphic empty type. Prefer `Empty` or `False` where possible. -/ inductive PEmpty : Sort u where /-- `Not p`, or `¬p`, is the negation of `p`. It is defined to be `p → False`, so if your goal is `¬p` you can use `intro h` to turn the goal into `h : p ⊢ False`, and if you have `hn : ¬p` and `h : p` then `hn h : False` and `(hn h).elim` will prove anything. For more information: [Propositional Logic](https://leanprover.github.io/theorem_proving_in_lean4/propositions_and_proofs.html#propositional-logic) -/ def Not (a : Prop) : Prop := a → False /-- `False.elim : False → C` says that from `False`, any desired proposition `C` holds. Also known as ex falso quodlibet (EFQ) or the principle of explosion. The target type is actually `C : Sort u` which means it works for both propositions and types. When executed, this acts like an "unreachable" instruction: it is **undefined behavior** to run, but it will probably print "unreachable code". (You would need to construct a proof of false to run it anyway, which you can only do using `sorry` or unsound axioms.) -/ @[macroInline] def False.elim {C : Sort u} (h : False) : C := h.rec /-- Anything follows from two contradictory hypotheses. Example: ``` example (hp : p) (hnp : ¬p) : q := absurd hp hnp ``` For more information: [Propositional Logic](https://leanprover.github.io/theorem_proving_in_lean4/propositions_and_proofs.html#propositional-logic) -/ @[macroInline] def absurd {a : Prop} {b : Sort v} (h₁ : a) (h₂ : Not a) : b := (h₂ h₁).rec /-- The equality relation. It has one introduction rule, `Eq.refl`. We use `a = b` as notation for `Eq a b`. A fundamental property of equality is that it is an equivalence relation. ``` variable (α : Type) (a b c d : α) variable (hab : a = b) (hcb : c = b) (hcd : c = d) example : a = d := Eq.trans (Eq.trans hab (Eq.symm hcb)) hcd ``` Equality is much more than an equivalence relation, however. It has the important property that every assertion respects the equivalence, in the sense that we can substitute equal expressions without changing the truth value. That is, given `h1 : a = b` and `h2 : p a`, we can construct a proof for `p b` using substitution: `Eq.subst h1 h2`. Example: ``` example (α : Type) (a b : α) (p : α → Prop) (h1 : a = b) (h2 : p a) : p b := Eq.subst h1 h2 example (α : Type) (a b : α) (p : α → Prop) (h1 : a = b) (h2 : p a) : p b := h1 ▸ h2 ``` The triangle in the second presentation is a macro built on top of `Eq.subst` and `Eq.symm`, and you can enter it by typing `\t`. For more information: [Equality](https://leanprover.github.io/theorem_proving_in_lean4/quantifiers_and_equality.html#equality) -/ inductive Eq : α → α → Prop where | /-- `Eq.refl a : a = a` is reflexivity, the unique constructor of the equality type. See also `rfl`, which is usually used instead. -/ refl (a : α) : Eq a a /-- Non-dependent recursor for the equality type. -/ @[simp] abbrev Eq.ndrec.{u1, u2} {α : Sort u2} {a : α} {motive : α → Sort u1} (m : motive a) {b : α} (h : Eq a b) : motive b := h.rec m /-- `rfl : a = a` is the unique constructor of the equality type. This is the same as `Eq.refl` except that it takes `a` implicitly instead of explicitly. This is a more powerful theorem than it may appear at first, because although the statement of the theorem is `a = a`, lean will allow anything that is definitionally equal to that type. So, for instance, `2 + 2 = 4` is proven in lean by `rfl`, because both sides are the same up to definitional equality. -/ @[matchPattern] def rfl {α : Sort u} {a : α} : Eq a a := Eq.refl a /-- `id x = x`, as a `@[simp]` lemma. -/ @[simp] theorem id_eq (a : α) : Eq (id a) a := rfl /-- The substitution principle for equality. If `a = b ` and `P a` holds, then `P b` also holds. We conventionally use the name `motive` for `P` here, so that you can specify it explicitly using e.g. `Eq.subst (motive := fun x => x < 5)` if it is not otherwise inferred correctly. This theorem is the underlying mechanism behind the `rw` tactic, which is essentially a fancy algorithm for finding good `motive` arguments to usefully apply this theorem to replace occurrences of `a` with `b` in the goal or hypotheses. For more information: [Equality](https://leanprover.github.io/theorem_proving_in_lean4/quantifiers_and_equality.html#equality) -/ theorem Eq.subst {α : Sort u} {motive : α → Prop} {a b : α} (h₁ : Eq a b) (h₂ : motive a) : motive b := Eq.ndrec h₂ h₁ /-- Equality is symmetric: if `a = b` then `b = a`. Because this is in the `Eq` namespace, if you have a variable `h : a = b`, `h.symm` can be used as shorthand for `Eq.symm h` as a proof of `b = a`. For more information: [Equality](https://leanprover.github.io/theorem_proving_in_lean4/quantifiers_and_equality.html#equality) -/ theorem Eq.symm {α : Sort u} {a b : α} (h : Eq a b) : Eq b a := h ▸ rfl /-- Equality is transitive: if `a = b` and `b = c` then `a = c`. Because this is in the `Eq` namespace, if you variables or expressions `h₁ : a = b` and `h₂ : b = c`, you can use `h₁.trans h₂ : a = c` as shorthand for `Eq.trans h₁ h₃`. For more information: [Equality](https://leanprover.github.io/theorem_proving_in_lean4/quantifiers_and_equality.html#equality) -/ theorem Eq.trans {α : Sort u} {a b c : α} (h₁ : Eq a b) (h₂ : Eq b c) : Eq a c := h₂ ▸ h₁ /-- Cast across a type equality. If `h : α = β` is an equality of types, and `a : α`, then `a : β` will usually not typecheck directly, but this function will allow you to work around this and embed `a` in type `β` as `cast h a : β`. It is best to avoid this function if you can, because it is more complicated to reason about terms containing casts, but if the types don't match up definitionally sometimes there isn't anything better you can do. For more information: [Equality](https://leanprover.github.io/theorem_proving_in_lean4/quantifiers_and_equality.html#equality) -/ @[macroInline] def cast {α β : Sort u} (h : Eq α β) (a : α) : β := h.rec a /-- Congruence in the function argument: if `a₁ = a₂` then `f a₁ = f a₂` for any (nondependent) function `f`. This is more powerful than it might look at first, because you can also use a lambda expression for `f` to prove that `<something containing a₁> = <something containing a₂>`. This function is used internally by tactics like `congr` and `simp` to apply equalities inside subterms. For more information: [Equality](https://leanprover.github.io/theorem_proving_in_lean4/quantifiers_and_equality.html#equality) -/ theorem congrArg {α : Sort u} {β : Sort v} {a₁ a₂ : α} (f : α → β) (h : Eq a₁ a₂) : Eq (f a₁) (f a₂) := h ▸ rfl /-- Congruence in both function and argument. If `f₁ = f₂` and `a₁ = a₂` then `f₁ a₁ = f₂ a₂`. This only works for nondependent functions; the theorem statement is more complex in the dependent case. For more information: [Equality](https://leanprover.github.io/theorem_proving_in_lean4/quantifiers_and_equality.html#equality) -/ theorem congr {α : Sort u} {β : Sort v} {f₁ f₂ : α → β} {a₁ a₂ : α} (h₁ : Eq f₁ f₂) (h₂ : Eq a₁ a₂) : Eq (f₁ a₁) (f₂ a₂) := h₁ ▸ h₂ ▸ rfl /-- Congruence in the function part of an application: If `f = g` then `f a = g a`. -/ theorem congrFun {α : Sort u} {β : α → Sort v} {f g : (x : α) → β x} (h : Eq f g) (a : α) : Eq (f a) (g a) := h ▸ rfl /-! Initialize the Quotient Module, which effectively adds the following definitions: ``` opaque Quot {α : Sort u} (r : α → α → Prop) : Sort u opaque Quot.mk {α : Sort u} (r : α → α → Prop) (a : α) : Quot r opaque Quot.lift {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) : (∀ a b : α, r a b → Eq (f a) (f b)) → Quot r → β opaque Quot.ind {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} : (∀ a : α, β (Quot.mk r a)) → ∀ q : Quot r, β q ``` -/ init_quot /-- Let `α` be any type, and let `r` be an equivalence relation on `α`. It is mathematically common to form the "quotient" `α / r`, that is, the type of elements of `α` "modulo" `r`. Set theoretically, one can view `α / r` as the set of equivalence classes of `α` modulo `r`. If `f : α → β` is any function that respects the equivalence relation in the sense that for every `x y : α`, `r x y` implies `f x = f y`, then f "lifts" to a function `f' : α / r → β` defined on each equivalence class `⟦x⟧` by `f' ⟦x⟧ = f x`. Lean extends the Calculus of Constructions with additional constants that perform exactly these constructions, and installs this last equation as a definitional reduction rule. Given a type `α` and any binary relation `r` on `α`, `Quot r` is a type. Note that `r` is not required to be an equivalance relation. `Quot` is the basic building block used to construct later the type `Quotient`. -/ add_decl_doc Quot /-- Given a type `α` and any binary relation `r` on `α`, `Quot.mk` maps `α` to `Quot r`. So that if `r : α → α → Prop` and `a : α`, then `Quot.mk r a` is an element of `Quot r`. See `Quot`. -/ add_decl_doc Quot.mk /-- Given a type `α` and any binary relation `r` on `α`, `Quot.ind` says that every element of `Quot r` is of the form `Quot.mk r a`. See `Quot` and `Quot.lift`. -/ add_decl_doc Quot.ind /-- Given a type `α`, any binary relation `r` on `α`, a function `f : α → β`, and a proof `h` that `f` respects the relation `r`, then `Quot.lift f h` is the corresponding function on `Quot r`. The idea is that for each element `a` in `α`, the function `Quot.lift f h` maps `Quot.mk r a` (the `r`-class containing `a`) to `f a`, wherein `h` shows that this function is well defined. In fact, the computation principle is declared as a reduction rule. -/ add_decl_doc Quot.lift /-- Unsafe auxiliary constant used by the compiler to erase `Quot.lift`. -/ unsafe axiom Quot.lcInv {α : Sort u} {r : α → α → Prop} (q : Quot r) : α /-- Heterogeneous equality. `HEq a b` asserts that `a` and `b` have the same type, and casting `a` across the equality yields `b`, and vice versa. You should avoid using this type if you can. Heterogeneous equality does not have all the same properties as `Eq`, because the assumption that the types of `a` and `b` are equal is often too weak to prove theorems of interest. One important non-theorem is the analogue of `congr`: If `HEq f g` and `HEq x y` and `f x` and `g y` are well typed it does not follow that `HEq (f x) (g y)`. (This does follow if you have `f = g` instead.) However if `a` and `b` have the same type then `a = b` and `HEq a b` ae equivalent. -/ inductive HEq : {α : Sort u} → α → {β : Sort u} → β → Prop where | /-- Reflexivity of heterogeneous equality. -/ refl (a : α) : HEq a a /-- A version of `HEq.refl` with an implicit argument. -/ @[matchPattern] protected def HEq.rfl {α : Sort u} {a : α} : HEq a a := HEq.refl a theorem eq_of_heq {α : Sort u} {a a' : α} (h : HEq a a') : Eq a a' := have : (α β : Sort u) → (a : α) → (b : β) → HEq a b → (h : Eq α β) → Eq (cast h a) b := fun _ _ _ _ h₁ => h₁.rec (fun _ => rfl) this α α a a' h rfl /-- Product type (aka pair). You can use `α × β` as notation for `Prod α β`. Given `a : α` and `b : β`, `Prod.mk a b : Prod α β`. You can use `(a, b)` as notation for `Prod.mk a b`. Moreover, `(a, b, c)` is notation for `Prod.mk a (Prod.mk b c)`. Given `p : Prod α β`, `p.1 : α` and `p.2 : β`. They are short for `Prod.fst p` and `Prod.snd p` respectively. You can also write `p.fst` and `p.snd`. For more information: [Constructors with Arguments](https://leanprover.github.io/theorem_proving_in_lean4/inductive_types.html?highlight=Prod#constructors-with-arguments) -/ structure Prod (α : Type u) (β : Type v) where /-- The first projection out of a pair. if `p : α × β` then `p.1 : α`. -/ fst : α /-- The second projection out of a pair. if `p : α × β` then `p.2 : β`. -/ snd : β attribute [unbox] Prod /-- Similar to `Prod`, but `α` and `β` can be propositions. We use this Type internally to automatically generate the `brecOn` recursor. -/ structure PProd (α : Sort u) (β : Sort v) where /-- The first projection out of a pair. if `p : PProd α β` then `p.1 : α`. -/ fst : α /-- The second projection out of a pair. if `p : PProd α β` then `p.2 : β`. -/ snd : β /-- Similar to `Prod`, but `α` and `β` are in the same universe. We say `MProd` is the universe monomorphic product type. -/ structure MProd (α β : Type u) where /-- The first projection out of a pair. if `p : MProd α β` then `p.1 : α`. -/ fst : α /-- The second projection out of a pair. if `p : MProd α β` then `p.2 : β`. -/ snd : β /-- `And a b`, or `a ∧ b`, is the conjunction of propositions. It can be constructed and destructed like a pair: if `ha : a` and `hb : b` then `⟨ha, hb⟩ : a ∧ b`, and if `h : a ∧ b` then `h.left : a` and `h.right : b`. -/ structure And (a b : Prop) : Prop where /-- `And.intro : a → b → a ∧ b` is the constructor for the And operation. -/ intro :: /-- Extract the left conjunct from a conjunction. `h : a ∧ b` then `h.left`, also notated as `h.1`, is a proof of `a`. -/ left : a /-- Extract the right conjunct from a conjunction. `h : a ∧ b` then `h.right`, also notated as `h.2`, is a proof of `b`. -/ right : b /-- `Or a b`, or `a ∨ b`, is the disjunction of propositions. There are two constructors for `Or`, called `Or.inl : a → a ∨ b` and `Or.inr : b → a ∨ b`, and you can use `match` or `cases` to destruct an `Or` assumption into the two cases. -/ inductive Or (a b : Prop) : Prop where | /-- `Or.inl` is "left injection" into an `Or`. If `h : a` then `Or.inl h : a ∨ b`. -/ inl (h : a) : Or a b | /-- `Or.inr` is "right injection" into an `Or`. If `h : b` then `Or.inr h : a ∨ b`. -/ inr (h : b) : Or a b /-- Alias for `Or.inl`. -/ theorem Or.intro_left (b : Prop) (h : a) : Or a b := Or.inl h /-- Alias for `Or.inr`. -/ theorem Or.intro_right (a : Prop) (h : b) : Or a b := Or.inr h /-- Proof by cases on an `Or`. If `a ∨ b`, and both `a` and `b` imply proposition `c`, then `c` is true. -/ theorem Or.elim {c : Prop} (h : Or a b) (left : a → c) (right : b → c) : c := match h with | Or.inl h => left h | Or.inr h => right h /-- `Bool` is the type of boolean values, `true` and `false`. Classically, this is equivalent to `Prop` (the type of propositions), but the distinction is important for programming, because values of type `Prop` are erased in the code generator, while `Bool` corresponds to the type called `bool` or `boolean` in most programming languages. -/ inductive Bool : Type where | /-- The boolean value `false`, not to be confused with the proposition `False`. -/ false : Bool | /-- The boolean value `true`, not to be confused with the proposition `True`. -/ true : Bool export Bool (false true) /-- `Subtype p`, usually written as `{x : α // p x}`, is a type which represents all the elements `x : α` for which `p x` is true. It is structurally a pair-like type, so if you have `x : α` and `h : p x` then `⟨x, h⟩ : {x // p x}`. An element `s : {x // p x}` will coerce to `α` but you can also make it explicit using `s.1` or `s.val`. -/ structure Subtype {α : Sort u} (p : α → Prop) where /-- If `s : {x // p x}` then `s.val : α` is the underlying element in the base type. You can also write this as `s.1`, or simply as `s` when the type is known from context. -/ val : α /-- If `s : {x // p x}` then `s.2` or `s.property` is the assertion that `p s.1`, that is, that `s` is in fact an element for which `p` holds. -/ property : p val set_option linter.unusedVariables.funArgs false in /-- Gadget for optional parameter support. A binder like `(x : α := default)` in a declaration is syntax sugar for `x : optParam α default`, and triggers the elaborator to attempt to use `default` to supply the argument if it is not supplied. -/ @[reducible] def optParam (α : Sort u) (default : α) : Sort u := α /-- Gadget for marking output parameters in type classes. For example, the `Membership` class is defined as: ``` class Membership (α : outParam (Type u)) (γ : Type v) ``` This means that whenever a typeclass goal of the form `Membership ?α ?γ` comes up, lean will wait to solve it until `?γ` is known, but then it will run typeclass inference, and take the first solution it finds, for any value of `?α`, which thereby determines what `?α` should be. This expresses that in a term like `a ∈ s`, `s` might be a `Set α` or `List α` or some other type with a membership operation, and in each case the "member" type `α` is determined by looking at the container type. -/ @[reducible] def outParam (α : Sort u) : Sort u := α set_option linter.unusedVariables.funArgs false in /-- Auxiliary declaration used to implement named patterns like `x@h:p`. -/ @[reducible] def namedPattern {α : Sort u} (x a : α) (h : Eq x a) : α := a /-- Auxiliary axiom used to implement `sorry`. The `sorry` term/tactic expands to `sorryAx _ (synthetic := false)`. This is a proof of anything, which is intended for stubbing out incomplete parts of a proof while still having a syntactically correct proof skeleton. Lean will give a warning whenever a proof uses `sorry`, so you aren't likely to miss it, but you can double check if a theorem depends on `sorry` by using `#print axioms my_thm` and looking for `sorryAx` in the axiom list. The `synthetic` flag is false when written explicitly by the user, but it is set to `true` when a tactic fails to prove a goal, or if there is a type error in the expression. A synthetic `sorry` acts like a regular one, except that it suppresses follow-up errors in order to prevent one error from causing a cascade of other errors because the desired term was not constructed. -/ @[extern "lean_sorry", neverExtract] axiom sorryAx (α : Sort u) (synthetic := false) : α theorem eq_false_of_ne_true : {b : Bool} → Not (Eq b true) → Eq b false | true, h => False.elim (h rfl) | false, _ => rfl theorem eq_true_of_ne_false : {b : Bool} → Not (Eq b false) → Eq b true | true, _ => rfl | false, h => False.elim (h rfl) theorem ne_false_of_eq_true : {b : Bool} → Eq b true → Not (Eq b false) | true, _ => fun h => Bool.noConfusion h | false, h => Bool.noConfusion h theorem ne_true_of_eq_false : {b : Bool} → Eq b false → Not (Eq b true) | true, h => Bool.noConfusion h | false, _ => fun h => Bool.noConfusion h /-- `Inhabited α` is a typeclass that says that `α` has a designated element, called `(default : α)`. This is sometimes referred to as a "pointed type". This class is used by functions that need to return a value of the type when called "out of domain". For example, `Array.get! arr i : α` returns a value of type `α` when `arr : Array α`, but if `i` is not in range of the array, it reports a panic message, but this does not halt the program, so it must still return a value of type `α` (and in fact this is required for logical consistency), so in this case it returns `default`. -/ class Inhabited (α : Sort u) where /-- `default` is a function that produces a "default" element of any `Inhabited` type. This element does not have any particular specified properties, but it is often an all-zeroes value. -/ default : α export Inhabited (default) /-- `Nonempty α` is a typeclass that says that `α` is not an empty type, that is, there exists an element in the type. It differs from `Inhabited α` in that `Nonempty α` is a `Prop`, which means that it does not actually carry an element of `α`, only a proof that *there exists* such an element. Given `Nonempty α`, you can construct an element of `α` *nonconstructively* using `Classical.choice`. -/ class inductive Nonempty (α : Sort u) : Prop where | /-- If `val : α`, then `α` is nonempty. -/ intro (val : α) : Nonempty α /-- **The axiom of choice**. `Nonempty α` is a proof that `α` has an element, but the element itself is erased. The axiom `choice` supplies a particular element of `α` given only this proof. The textbook axiom of choice normally makes a family of choices all at once, but that is implied from this formulation, because if `α : ι → Type` is a family of types and `h : ∀ i, Nonempty (α i)` is a proof that they are all nonempty, then `fun i => Classical.choice (h i) : ∀ i, α i` is a family of chosen elements. This is actually a bit stronger than the ZFC choice axiom; this is sometimes called "[global choice](https://en.wikipedia.org/wiki/Axiom_of_global_choice)". In lean, we use the axiom of choice to derive the law of excluded middle (see `Classical.em`), so it will often show up in axiom listings where you may not expect. You can use `#print axioms my_thm` to find out if a given theorem depends on this or other axioms. This axiom can be used to construct "data", but obviously there is no algorithm to compute it, so lean will require you to mark any definition that would involve executing `Classical.choice` or other axioms as `noncomputable`, and will not produce any executable code for such definitions. -/ axiom Classical.choice {α : Sort u} : Nonempty α → α /-- The elimination principle for `Nonempty α`. If `Nonempty α`, and we can prove `p` given any element `x : α`, then `p` holds. Note that it is essential that `p` is a `Prop` here; the version with `p` being a `Sort u` is equivalent to `Classical.choice`. -/ protected def Nonempty.elim {α : Sort u} {p : Prop} (h₁ : Nonempty α) (h₂ : α → p) : p := match h₁ with | intro a => h₂ a instance {α : Sort u} [Inhabited α] : Nonempty α := ⟨default⟩ /-- A variation on `Classical.choice` that uses typeclass inference to infer the proof of `Nonempty α`. -/ noncomputable def Classical.ofNonempty {α : Sort u} [Nonempty α] : α := Classical.choice inferInstance instance (α : Sort u) {β : Sort v} [Nonempty β] : Nonempty (α → β) := Nonempty.intro fun _ => Classical.ofNonempty instance (α : Sort u) {β : α → Sort v} [(a : α) → Nonempty (β a)] : Nonempty ((a : α) → β a) := Nonempty.intro fun _ => Classical.ofNonempty instance : Inhabited (Sort u) where default := PUnit instance (α : Sort u) {β : Sort v} [Inhabited β] : Inhabited (α → β) where default := fun _ => default instance (α : Sort u) {β : α → Sort v} [(a : α) → Inhabited (β a)] : Inhabited ((a : α) → β a) where default := fun _ => default deriving instance Inhabited for Bool /-- Universe lifting operation from `Sort u` to `Type u`. -/ structure PLift (α : Sort u) : Type u where /-- Lift a value into `PLift α` -/ up :: /-- Extract a value from `PLift α` -/ down : α /-- Bijection between `α` and `PLift α` -/ theorem PLift.up_down {α : Sort u} (b : PLift α) : Eq (up (down b)) b := rfl /-- Bijection between `α` and `PLift α` -/ theorem PLift.down_up {α : Sort u} (a : α) : Eq (down (up a)) a := rfl /-- `NonemptyType.{u}` is the type of nonempty types in universe `u`. It is mainly used in constant declarations where we wish to introduce a type and simultaneously assert that it is nonempty, but otherwise make the type opaque. -/ def NonemptyType := Subtype fun α : Type u => Nonempty α /-- The underlying type of a `NonemptyType`. -/ abbrev NonemptyType.type (type : NonemptyType.{u}) : Type u := type.val /-- `NonemptyType` is inhabited, because `PUnit` is a nonempty type. -/ instance : Inhabited NonemptyType.{u} where default := ⟨PUnit, ⟨⟨⟩⟩⟩ /-- Universe lifting operation from a lower `Type` universe to a higher one. To express this using level variables, the input is `Type s` and the output is `Type (max s r)`, so if `s ≤ r` then the latter is (definitionally) `Type r`. The universe variable `r` is written first so that `ULift.{r} α` can be used when `s` can be inferred from the type of `α`. -/ structure ULift.{r, s} (α : Type s) : Type (max s r) where /-- Lift a value into `ULift α` -/ up :: /-- Extract a value from `ULift α` -/ down : α /-- Bijection between `α` and `ULift.{v} α` -/ theorem ULift.up_down {α : Type u} (b : ULift.{v} α) : Eq (up (down b)) b := rfl /-- Bijection between `α` and `ULift.{v} α` -/ theorem ULift.down_up {α : Type u} (a : α) : Eq (down (up.{v} a)) a := rfl /-- `Decidable p` is a data-carrying class that supplies a proof that `p` is either `true` or `false`. It is equivalent to `Bool` (and in fact it has the same code generation as `Bool`) together with a proof that the `Bool` is true iff `p` is. `Decidable` instances are used to infer "computation strategies" for propositions, so that you can have the convenience of writing propositions inside `if` statements and executing them (which actually executes the inferred decidability instance instead of the proposition, which has no code). If a proposition `p` is `Decidable`, then `(by decide : p)` will prove it by evaluating the decidability instance to `isTrue h` and returning `h`. -/ class inductive Decidable (p : Prop) where | /-- Prove that `p` is decidable by supplying a proof of `¬p` -/ isFalse (h : Not p) : Decidable p | /-- Prove that `p` is decidable by supplying a proof of `p` -/ isTrue (h : p) : Decidable p /-- Convert a decidable proposition into a boolean value. If `p : Prop` is decidable, then `decide p : Bool` is the boolean value which is `true` if `p` is true and `false` if `p` is false. -/ @[inlineIfReduce, nospecialize] def Decidable.decide (p : Prop) [h : Decidable p] : Bool := h.casesOn (fun _ => false) (fun _ => true) export Decidable (isTrue isFalse decide) /-- A decidable predicate. See `Decidable`. -/ abbrev DecidablePred {α : Sort u} (r : α → Prop) := (a : α) → Decidable (r a) /-- A decidable relation. See `Decidable`. -/ abbrev DecidableRel {α : Sort u} (r : α → α → Prop) := (a b : α) → Decidable (r a b) /-- Asserts that `α` has decidable equality, that is, `a = b` is decidable for all `a b : α`. See `Decidable`. -/ abbrev DecidableEq (α : Sort u) := (a b : α) → Decidable (Eq a b) /-- Proves that `a = b` is decidable given `DecidableEq α`. -/ def decEq {α : Sort u} [inst : DecidableEq α] (a b : α) : Decidable (Eq a b) := inst a b set_option linter.unusedVariables false in theorem decide_eq_true : [inst : Decidable p] → p → Eq (decide p) true | isTrue _, _ => rfl | isFalse h₁, h₂ => absurd h₂ h₁ theorem decide_eq_false : [Decidable p] → Not p → Eq (decide p) false | isTrue h₁, h₂ => absurd h₁ h₂ | isFalse _, _ => rfl theorem of_decide_eq_true [inst : Decidable p] : Eq (decide p) true → p := fun h => match (generalizing := false) inst with | isTrue h₁ => h₁ | isFalse h₁ => absurd h (ne_true_of_eq_false (decide_eq_false h₁)) theorem of_decide_eq_false [inst : Decidable p] : Eq (decide p) false → Not p := fun h => match (generalizing := false) inst with | isTrue h₁ => absurd h (ne_false_of_eq_true (decide_eq_true h₁)) | isFalse h₁ => h₁ theorem of_decide_eq_self_eq_true [inst : DecidableEq α] (a : α) : Eq (decide (Eq a a)) true := match (generalizing := false) inst a a with | isTrue _ => rfl | isFalse h₁ => absurd rfl h₁ @[inline] instance : DecidableEq Bool := fun a b => match a, b with | false, false => isTrue rfl | false, true => isFalse (fun h => Bool.noConfusion h) | true, false => isFalse (fun h => Bool.noConfusion h) | true, true => isTrue rfl /-- `BEq α` is a typeclass for supplying a boolean-valued equality relation on `α`, notated as `a == b`. Unlike `DecidableEq α` (which uses `a = b`), this is `Bool` valued instead of `Prop` valued, and it also does not have any axioms like being reflexive or agreeing with `=`. It is mainly intended for programming applications. See `LawfulBEq` for a version that requires that `==` and `=` coincide. -/ class BEq (α : Type u) where /-- Boolean equality, notated as `a == b`. -/ beq : α → α → Bool open BEq (beq) instance [DecidableEq α] : BEq α where beq a b := decide (Eq a b) /-- "Dependent" if-then-else, normally written via the notation `if h : c then t(h) else e(h)`, is sugar for `dite c (fun h => t(h)) (fun h => e(h))`, and it is the same as `if c then t else e` except that `t` is allowed to depend on a proof `h : c`, and `e` can depend on `h : ¬c`. (Both branches use the same name for the hypothesis, even though it has different types in the two cases.) We use this to be able to communicate the if-then-else condition to the branches. For example, `Array.get arr ⟨i, h⟩` expects a proof `h : i < arr.size` in order to avoid a bounds check, so you can write `if h : i < arr.size then arr.get ⟨i, h⟩ else ...` to avoid the bounds check inside the if branch. (Of course in this case we have only lifted the check into an explicit `if`, but we could also use this proof multiple times or derive `i < arr.size` from some other proposition that we are checking in the `if`.) -/ @[macroInline] def dite {α : Sort u} (c : Prop) [h : Decidable c] (t : c → α) (e : Not c → α) : α := h.casesOn e t /-! # if-then-else -/ /-- `if c then t else e` is notation for `ite c t e`, "if-then-else", which decides to return `t` or `e` depending on whether `c` is true or false. The explicit argument `c : Prop` does not have any actual computational content, but there is an additional `[Decidable c]` argument synthesized by typeclass inference which actually determines how to evaluate `c` to true or false. Because lean uses a strict (call-by-value) evaluation strategy, the signature of this function is problematic in that it would require `t` and `e` to be evaluated before calling the `ite` function, which would cause both sides of the `if` to be evaluated. Even if the result is discarded, this would be a big performance problem, and is undesirable for users in any case. To resolve this, `ite` is marked as `@[macroInline]`, which means that it is unfolded during code generation, and the definition of the function uses `fun _ => t` and `fun _ => e` so this recovers the expected "lazy" behavior of `if`: the `t` and `e` arguments delay evaluation until `c` is known. -/ @[macroInline] def ite {α : Sort u} (c : Prop) [h : Decidable c] (t e : α) : α := h.casesOn (fun _ => e) (fun _ => t) @[macroInline] instance {p q} [dp : Decidable p] [dq : Decidable q] : Decidable (And p q) := match dp with | isTrue hp => match dq with | isTrue hq => isTrue ⟨hp, hq⟩ | isFalse hq => isFalse (fun h => hq (And.right h)) | isFalse hp => isFalse (fun h => hp (And.left h)) @[macroInline] instance [dp : Decidable p] [dq : Decidable q] : Decidable (Or p q) := match dp with | isTrue hp => isTrue (Or.inl hp) | isFalse hp => match dq with | isTrue hq => isTrue (Or.inr hq) | isFalse hq => isFalse fun h => match h with | Or.inl h => hp h | Or.inr h => hq h instance [dp : Decidable p] : Decidable (Not p) := match dp with | isTrue hp => isFalse (absurd hp) | isFalse hp => isTrue hp /-! # Boolean operators -/ /-- `cond b x y` is the same as `if b then x else y`, but optimized for a boolean condition. This is `@[macroInline]` because `x` and `y` should not be eagerly evaluated (see `ite`). -/ @[macroInline] def cond {α : Type u} (c : Bool) (x y : α) : α := match c with | true => x | false => y /-- `or x y`, or `x || y`, is the boolean "or" operation (not to be confused with `Or : Prop → Prop → Prop`, which is the propositional connective). It is `@[macroInline]` because it has C-like short-circuiting behavior: if `x` is true then `y` is not evaluated. -/ @[macroInline] def or (x y : Bool) : Bool := match x with | true => true | false => y /-- `and x y`, or `x && y`, is the boolean "and" operation (not to be confused with `And : Prop → Prop → Prop`, which is the propositional connective). It is `@[macroInline]` because it has C-like short-circuiting behavior: if `x` is false then `y` is not evaluated. -/ @[macroInline] def and (x y : Bool) : Bool := match x with | false => false | true => y /-- `not x`, or `!x`, is the boolean "not" operation (not to be confused with `Not : Prop → Prop`, which is the propositional connective). -/ @[inline] def not : Bool → Bool | true => false | false => true /-- The type of natural numbers, starting at zero. It is defined as an inductive type freely generated by "zero is a natural number" and "the successor of a natural number is a natural number". You can prove a theorem `P n` about `n : Nat` by `induction n`, which will expect a proof of the theorem for `P 0`, and a proof of `P (succ i)` assuming a proof of `P i`. The same method also works to define functions by recursion on natural numbers: induction and recursion are two expressions of the same operation from lean's point of view. ``` open Nat example (n : Nat) : n < succ n := by induction n with | zero => show 0 < 1 decide | succ i ih => -- ih : i < succ i show succ i < succ (succ i) exact Nat.succ_lt_succ ih ``` This type is special-cased by both the kernel and the compiler: * The type of expressions contains "`Nat` literals" as a primitive constructor, and the kernel knows how to reduce zero/succ expressions to nat literals. * If implemented naively, this type would represent a numeral `n` in unary as a linked list with `n` links, which is horribly inefficient. Instead, the runtime itself has a special representation for `Nat` which stores numbers up to 2^63 directly and larger numbers use an arbitrary precision "bignum" library (usually [GMP](https://gmplib.org/)). -/ inductive Nat where | /-- `Nat.zero`, normally written `0 : Nat`, is the smallest natural number. This is one of the two constructors of `Nat`. -/ zero : Nat | /-- The successor function on natural numbers, `succ n = n + 1`. This is one of the two constructors of `Nat`. -/ succ (n : Nat) : Nat instance : Inhabited Nat where default := Nat.zero /-- The class `OfNat α n` powers the numeric literal parser. If you write `37 : α`, lean will attempt to synthesize `OfNat α 37`, and will generate the term `(OfNat.ofNat 37 : α)`. There is a bit of infinite regress here since the desugaring apparently still contains a literal `37` in it. The type of expressions contains a primitive constructor for "raw natural number literals", which you can directly access using the macro `nat_lit 37`. Raw number literals are always of type `Nat`. So it would be more correct to say that lean looks for an instance of `OfNat α (nat_lit 37)`, and it generates the term `(OfNat.ofNat (nat_lit 37) : α)`. -/ class OfNat (α : Type u) (_ : Nat) where /-- The `OfNat.ofNat` function is automatically inserted by the parser when the user writes a numeric literal like `1 : α`. Implementations of this typeclass can therefore customize the behavior of `n : α` based on `n` and `α`. -/ ofNat : α @[defaultInstance 100] /- low prio -/ instance (n : Nat) : OfNat Nat n where ofNat := n /-- `LE α` is the typeclass which supports the notation `x ≤ y` where `x y : α`.-/ class LE (α : Type u) where /-- The less-equal relation: `x ≤ y` -/ le : α → α → Prop /-- `LT α` is the typeclass which supports the notation `x < y` where `x y : α`.-/ class LT (α : Type u) where /-- The less-than relation: `x < y` -/ lt : α → α → Prop /-- `a ≥ b` is an abbreviation for `b ≤ a`. -/ @[reducible] def GE.ge {α : Type u} [LE α] (a b : α) : Prop := LE.le b a /-- `a > b` is an abbreviation for `b < a`. -/ @[reducible] def GT.gt {α : Type u} [LT α] (a b : α) : Prop := LT.lt b a /-- `max a b` is the maximum of `a` and `b`. It is defined simply as `if b < a then a else b`, and works as long as `<` is decidable. -/ @[inline] def max [LT α] [DecidableRel (@LT.lt α _)] (a b : α) : α := ite (LT.lt b a) a b /-- `min a b` is the minimum of `a` and `b`. It is defined simply as `if a ≤ b then a else b`, and works as long as `≤` is decidable. -/ @[inline] def min [LE α] [DecidableRel (@LE.le α _)] (a b : α) : α := ite (LE.le a b) a b /-- Transitive chaining of proofs, used e.g. by `calc`. It takes two relations `r` and `s` as "input", and produces an "output" relation `t`, with the property that `r a b` and `s b c` implies `t a c`. The `calc` tactic uses this so that when it sees a chain with `a ≤ b` and `b < c` it knows that this should be a proof of `a < c` because there is an instance `Trans (·≤·) (·<·) (·<·)`. -/ class Trans (r : α → β → Sort u) (s : β → γ → Sort v) (t : outParam (α → γ → Sort w)) where /-- Compose two proofs by transitivity, generalized over the relations involved. -/ trans : r a b → s b c → t a c export Trans (trans) instance (r : α → γ → Sort u) : Trans Eq r r where trans heq h' := heq ▸ h' instance (r : α → β → Sort u) : Trans r Eq r where trans h' heq := heq ▸ h' /-- The notation typeclass for heterogeneous addition. This enables the notation `a + b : γ` where `a : α`, `b : β`. -/ class HAdd (α : Type u) (β : Type v) (γ : outParam (Type w)) where /-- `a + b` computes the sum of `a` and `b`. The meaning of this notation is type-dependent. -/ hAdd : α → β → γ /-- The notation typeclass for heterogeneous subtraction. This enables the notation `a - b : γ` where `a : α`, `b : β`. -/ class HSub (α : Type u) (β : Type v) (γ : outParam (Type w)) where /-- `a - b` computes the difference of `a` and `b`. The meaning of this notation is type-dependent. * For natural numbers, this operator saturates at 0: `a - b = 0` when `a ≤ b`. -/ hSub : α → β → γ /-- The notation typeclass for heterogeneous multiplication. This enables the notation `a * b : γ` where `a : α`, `b : β`. -/ class HMul (α : Type u) (β : Type v) (γ : outParam (Type w)) where /-- `a * b` computes the product of `a` and `b`. The meaning of this notation is type-dependent. -/ hMul : α → β → γ /-- The notation typeclass for heterogeneous division. This enables the notation `a / b : γ` where `a : α`, `b : β`. -/ class HDiv (α : Type u) (β : Type v) (γ : outParam (Type w)) where /-- `a / b` computes the result of dividing `a` by `b`. The meaning of this notation is type-dependent. * For most types like `Nat`, `Int`, `Rat`, `Real`, `a / 0` is defined to be `0`. * For `Nat` and `Int`, `a / b` rounds toward 0. * For `Float`, `a / 0` follows the IEEE 754 semantics for division, usually resulting in `inf` or `nan`. -/ hDiv : α → β → γ /-- The notation typeclass for heterogeneous modulo / remainder. This enables the notation `a % b : γ` where `a : α`, `b : β`. -/ class HMod (α : Type u) (β : Type v) (γ : outParam (Type w)) where /-- `a % b` computes the remainder upon dividing `a` by `b`. The meaning of this notation is type-dependent. * For `Nat` and `Int`, `a % 0` is defined to be `a`. -/ hMod : α → β → γ /-- The notation typeclass for heterogeneous exponentiation. This enables the notation `a ^ b : γ` where `a : α`, `b : β`. -/ class HPow (α : Type u) (β : Type v) (γ : outParam (Type w)) where /-- `a ^ b` computes `a` to the power of `b`. The meaning of this notation is type-dependent. -/ hPow : α → β → γ /-- The notation typeclass for heterogeneous append. This enables the notation `a ++ b : γ` where `a : α`, `b : β`. -/ class HAppend (α : Type u) (β : Type v) (γ : outParam (Type w)) where /-- `a ++ b` is the result of concatenation of `a` and `b`, usually read "append". The meaning of this notation is type-dependent. -/ hAppend : α → β → γ /-- The typeclass behind the notation `a <|> b : γ` where `a : α`, `b : β`. Because `b` is "lazy" in this notation, it is passed as `Unit → β` to the implementation so it can decide when to evaluate it. -/ class HOrElse (α : Type u) (β : Type v) (γ : outParam (Type w)) where /-- `a <|> b` executes `a` and returns the result, unless it fails in which case it executes and returns `b`. Because `b` is not always executed, it is passed as a thunk so it can be forced only when needed. The meaning of this notation is type-dependent. -/ hOrElse : α → (Unit → β) → γ /-- The typeclass behind the notation `a >> b : γ` where `a : α`, `b : β`. Because `b` is "lazy" in this notation, it is passed as `Unit → β` to the implementation so it can decide when to evaluate it. -/ class HAndThen (α : Type u) (β : Type v) (γ : outParam (Type w)) where /-- `a >> b` executes `a`, ignores the result, and then executes `b`. If `a` fails then `b` is not executed. Because `b` is not always executed, it is passed as a thunk so it can be forced only when needed. The meaning of this notation is type-dependent. -/ hAndThen : α → (Unit → β) → γ /-- The typeclass behind the notation `a &&& b : γ` where `a : α`, `b : β`. -/ class HAnd (α : Type u) (β : Type v) (γ : outParam (Type w)) where /-- `a &&& b` computes the bitwise AND of `a` and `b`. The meaning of this notation is type-dependent. -/ hAnd : α → β → γ /-- The typeclass behind the notation `a ^^^ b : γ` where `a : α`, `b : β`. -/ class HXor (α : Type u) (β : Type v) (γ : outParam (Type w)) where /-- `a ^^^ b` computes the bitwise XOR of `a` and `b`. The meaning of this notation is type-dependent. -/ hXor : α → β → γ /-- The typeclass behind the notation `a ||| b : γ` where `a : α`, `b : β`. -/ class HOr (α : Type u) (β : Type v) (γ : outParam (Type w)) where /-- `a ||| b` computes the bitwise OR of `a` and `b`. The meaning of this notation is type-dependent. -/ hOr : α → β → γ /-- The typeclass behind the notation `a <<< b : γ` where `a : α`, `b : β`. -/ class HShiftLeft (α : Type u) (β : Type v) (γ : outParam (Type w)) where /-- `a <<< b` computes `a` shifted to the left by `b` places. The meaning of this notation is type-dependent. * On `Nat`, this is equivalent to `a * 2 ^ b`. * On `UInt8` and other fixed width unsigned types, this is the same but truncated to the bit width. -/ hShiftLeft : α → β → γ /-- The typeclass behind the notation `a >>> b : γ` where `a : α`, `b : β`. -/ class HShiftRight (α : Type u) (β : Type v) (γ : outParam (Type w)) where /-- `a >>> b` computes `a` shifted to the right by `b` places. The meaning of this notation is type-dependent. * On `Nat` and fixed width unsigned types like `UInt8`, this is equivalent to `a / 2 ^ b`. -/ hShiftRight : α → β → γ /-- The homogeneous version of `HAdd`: `a + b : α` where `a b : α`. -/ class Add (α : Type u) where /-- `a + b` computes the sum of `a` and `b`. See `HAdd`. -/ add : α → α → α /-- The homogeneous version of `HSub`: `a - b : α` where `a b : α`. -/ class Sub (α : Type u) where /-- `a - b` computes the difference of `a` and `b`. See `HSub`. -/ sub : α → α → α /-- The homogeneous version of `HMul`: `a * b : α` where `a b : α`. -/ class Mul (α : Type u) where /-- `a * b` computes the product of `a` and `b`. See `HMul`. -/ mul : α → α → α /-- The notation typeclass for negation. This enables the notation `-a : α` where `a : α`. -/ class Neg (α : Type u) where /-- `-a` computes the negative or opposite of `a`. The meaning of this notation is type-dependent. -/ neg : α → α /-- The homogeneous version of `HDiv`: `a / b : α` where `a b : α`. -/ class Div (α : Type u) where /-- `a / b` computes the result of dividing `a` by `b`. See `HDiv`. -/ div : α → α → α /-- The homogeneous version of `HMod`: `a % b : α` where `a b : α`. -/ class Mod (α : Type u) where /-- `a % b` computes the remainder upon dividing `a` by `b`. See `HMod`. -/ mod : α → α → α /-- The homogeneous version of `HPow`: `a ^ b : α` where `a : α`, `b : β`. (The right argument is not the same as the left since we often want this even in the homogeneous case.) -/ class Pow (α : Type u) (β : Type v) where /-- `a ^ b` computes `a` to the power of `b`. See `HPow`. -/ pow : α → β → α /-- The homogeneous version of `HAppend`: `a ++ b : α` where `a b : α`. -/ class Append (α : Type u) where /-- `a ++ b` is the result of concatenation of `a` and `b`. See `HAppend`. -/ append : α → α → α /-- The homogeneous version of `HOrElse`: `a <|> b : α` where `a b : α`. Because `b` is "lazy" in this notation, it is passed as `Unit → α` to the implementation so it can decide when to evaluate it. -/ class OrElse (α : Type u) where /-- The implementation of `a <|> b : α`. See `HOrElse`. -/ orElse : α → (Unit → α) → α /-- The homogeneous version of `HAndThen`: `a >> b : α` where `a b : α`. Because `b` is "lazy" in this notation, it is passed as `Unit → α` to the implementation so it can decide when to evaluate it. -/ class AndThen (α : Type u) where /-- The implementation of `a >> b : α`. See `HAndThen`. -/ andThen : α → (Unit → α) → α /-- The homogeneous version of `HAnd`: `a &&& b : α` where `a b : α`. (It is called `AndOp` because `And` is taken for the propositional connective.) -/ class AndOp (α : Type u) where /-- The implementation of `a &&& b : α`. See `HAnd`. -/ and : α → α → α /-- The homogeneous version of `HXor`: `a ^^^ b : α` where `a b : α`. -/ class Xor (α : Type u) where /-- The implementation of `a ^^^ b : α`. See `HXor`. -/ xor : α → α → α /-- The homogeneous version of `HOr`: `a ||| b : α` where `a b : α`. (It is called `OrOp` because `Or` is taken for the propositional connective.) -/ class OrOp (α : Type u) where /-- The implementation of `a ||| b : α`. See `HOr`. -/ or : α → α → α /-- The typeclass behind the notation `~~~a : α` where `a : α`. -/ class Complement (α : Type u) where /-- The implementation of `~~~a : α`. -/ complement : α → α /-- The homogeneous version of `HShiftLeft`: `a <<< b : α` where `a b : α`. -/ class ShiftLeft (α : Type u) where /-- The implementation of `a <<< b : α`. See `HShiftLeft`. -/ shiftLeft : α → α → α /-- The homogeneous version of `HShiftRight`: `a >>> b : α` where `a b : α`. -/ class ShiftRight (α : Type u) where /-- The implementation of `a >>> b : α`. See `HShiftRight`. -/ shiftRight : α → α → α @[defaultInstance] instance [Add α] : HAdd α α α where hAdd a b := Add.add a b @[defaultInstance] instance [Sub α] : HSub α α α where hSub a b := Sub.sub a b @[defaultInstance] instance [Mul α] : HMul α α α where hMul a b := Mul.mul a b @[defaultInstance] instance [Div α] : HDiv α α α where hDiv a b := Div.div a b @[defaultInstance] instance [Mod α] : HMod α α α where hMod a b := Mod.mod a b @[defaultInstance] instance [Pow α β] : HPow α β α where hPow a b := Pow.pow a b @[defaultInstance] instance [Append α] : HAppend α α α where hAppend a b := Append.append a b @[defaultInstance] instance [OrElse α] : HOrElse α α α where hOrElse a b := OrElse.orElse a b @[defaultInstance] instance [AndThen α] : HAndThen α α α where hAndThen a b := AndThen.andThen a b @[defaultInstance] instance [AndOp α] : HAnd α α α where hAnd a b := AndOp.and a b @[defaultInstance] instance [Xor α] : HXor α α α where hXor a b := Xor.xor a b @[defaultInstance] instance [OrOp α] : HOr α α α where hOr a b := OrOp.or a b @[defaultInstance] instance [ShiftLeft α] : HShiftLeft α α α where hShiftLeft a b := ShiftLeft.shiftLeft a b @[defaultInstance] instance [ShiftRight α] : HShiftRight α α α where hShiftRight a b := ShiftRight.shiftRight a b open HAdd (hAdd) open HMul (hMul) open HPow (hPow) open HAppend (hAppend) /-- The typeclass behind the notation `a ∈ s : Prop` where `a : α`, `s : γ`. Because `α` is an `outParam`, the "container type" `γ` determines the type of the elements of the container. -/ class Membership (α : outParam (Type u)) (γ : Type v) where /-- The membership relation `a ∈ s : Prop` where `a : α`, `s : γ`. -/ mem : α → γ → Prop set_option bootstrap.genMatcherCode false in /-- Addition of natural numbers. This definition is overridden in both the kernel and the compiler to efficiently evaluate using the "bignum" representation (see `Nat`). The definition provided here is the logical model (and it is soundness-critical that they coincide). -/ @[extern "lean_nat_add"] protected def Nat.add : (@& Nat) → (@& Nat) → Nat | a, Nat.zero => a | a, Nat.succ b => Nat.succ (Nat.add a b) instance : Add Nat where add := Nat.add /- We mark the following definitions as pattern to make sure they can be used in recursive equations, and reduced by the equation Compiler. -/ attribute [matchPattern] Nat.add Add.add HAdd.hAdd Neg.neg set_option bootstrap.genMatcherCode false in /-- Multiplication of natural numbers. This definition is overridden in both the kernel and the compiler to efficiently evaluate using the "bignum" representation (see `Nat`). The definition provided here is the logical model (and it is soundness-critical that they coincide). -/ @[extern "lean_nat_mul"] protected def Nat.mul : (@& Nat) → (@& Nat) → Nat | _, 0 => 0 | a, Nat.succ b => Nat.add (Nat.mul a b) a instance : Mul Nat where mul := Nat.mul set_option bootstrap.genMatcherCode false in /-- The power operation on natural numbers. This definition is overridden in the compiler to efficiently evaluate using the "bignum" representation (see `Nat`). The definition provided here is the logical model. -/ @[extern "lean_nat_pow"] protected def Nat.pow (m : @& Nat) : (@& Nat) → Nat | 0 => 1 | succ n => Nat.mul (Nat.pow m n) m instance : Pow Nat Nat where pow := Nat.pow set_option bootstrap.genMatcherCode false in /-- (Boolean) equality of natural numbers. This definition is overridden in both the kernel and the compiler to efficiently evaluate using the "bignum" representation (see `Nat`). The definition provided here is the logical model (and it is soundness-critical that they coincide). -/ @[extern "lean_nat_dec_eq"] def Nat.beq : (@& Nat) → (@& Nat) → Bool | zero, zero => true | zero, succ _ => false | succ _, zero => false | succ n, succ m => beq n m instance : BEq Nat where beq := Nat.beq theorem Nat.eq_of_beq_eq_true : {n m : Nat} → Eq (beq n m) true → Eq n m | zero, zero, _ => rfl | zero, succ _, h => Bool.noConfusion h | succ _, zero, h => Bool.noConfusion h | succ n, succ m, h => have : Eq (beq n m) true := h have : Eq n m := eq_of_beq_eq_true this this ▸ rfl theorem Nat.ne_of_beq_eq_false : {n m : Nat} → Eq (beq n m) false → Not (Eq n m) | zero, zero, h₁, _ => Bool.noConfusion h₁ | zero, succ _, _, h₂ => Nat.noConfusion h₂ | succ _, zero, _, h₂ => Nat.noConfusion h₂ | succ n, succ m, h₁, h₂ => have : Eq (beq n m) false := h₁ Nat.noConfusion h₂ (fun h₂ => absurd h₂ (ne_of_beq_eq_false this)) /-- A decision procedure for equality of natural numbers. This definition is overridden in the compiler to efficiently evaluate using the "bignum" representation (see `Nat`). The definition provided here is the logical model. -/ @[reducible, extern "lean_nat_dec_eq"] protected def Nat.decEq (n m : @& Nat) : Decidable (Eq n m) := match h:beq n m with | true => isTrue (eq_of_beq_eq_true h) | false => isFalse (ne_of_beq_eq_false h) @[inline] instance : DecidableEq Nat := Nat.decEq set_option bootstrap.genMatcherCode false in /-- The (Boolean) less-equal relation on natural numbers. This definition is overridden in both the kernel and the compiler to efficiently evaluate using the "bignum" representation (see `Nat`). The definition provided here is the logical model (and it is soundness-critical that they coincide). -/ @[extern "lean_nat_dec_le"] def Nat.ble : @& Nat → @& Nat → Bool | zero, zero => true | zero, succ _ => true | succ _, zero => false | succ n, succ m => ble n m /-- An inductive definition of the less-equal relation on natural numbers, characterized as the least relation `≤` such that `n ≤ n` and `n ≤ m → n ≤ m + 1`. -/ protected inductive Nat.le (n : Nat) : Nat → Prop | /-- Less-equal is reflexive: `n ≤ n` -/ refl : Nat.le n n | /-- If `n ≤ m`, then `n ≤ m + 1`. -/ step {m} : Nat.le n m → Nat.le n (succ m) instance : LE Nat where le := Nat.le /-- The strict less than relation on natural numbers is defined as `n < m := n + 1 ≤ m`. -/ protected def Nat.lt (n m : Nat) : Prop := Nat.le (succ n) m instance : LT Nat where lt := Nat.lt theorem Nat.not_succ_le_zero : ∀ (n : Nat), LE.le (succ n) 0 → False | 0, h => nomatch h | succ _, h => nomatch h theorem Nat.not_lt_zero (n : Nat) : Not (LT.lt n 0) := not_succ_le_zero n theorem Nat.zero_le : (n : Nat) → LE.le 0 n | zero => Nat.le.refl | succ n => Nat.le.step (zero_le n) theorem Nat.succ_le_succ : LE.le n m → LE.le (succ n) (succ m) | Nat.le.refl => Nat.le.refl | Nat.le.step h => Nat.le.step (succ_le_succ h) theorem Nat.zero_lt_succ (n : Nat) : LT.lt 0 (succ n) := succ_le_succ (zero_le n) theorem Nat.le_step (h : LE.le n m) : LE.le n (succ m) := Nat.le.step h protected theorem Nat.le_trans {n m k : Nat} : LE.le n m → LE.le m k → LE.le n k | h, Nat.le.refl => h | h₁, Nat.le.step h₂ => Nat.le.step (Nat.le_trans h₁ h₂) protected theorem Nat.lt_trans {n m k : Nat} (h₁ : LT.lt n m) : LT.lt m k → LT.lt n k := Nat.le_trans (le_step h₁) theorem Nat.le_succ (n : Nat) : LE.le n (succ n) := Nat.le.step Nat.le.refl theorem Nat.le_succ_of_le {n m : Nat} (h : LE.le n m) : LE.le n (succ m) := Nat.le_trans h (le_succ m) protected theorem Nat.le_refl (n : Nat) : LE.le n n := Nat.le.refl theorem Nat.succ_pos (n : Nat) : LT.lt 0 (succ n) := zero_lt_succ n set_option bootstrap.genMatcherCode false in /-- The predecessor function on natural numbers. This definition is overridden in the compiler to use `n - 1` instead. The definition provided here is the logical model. -/ @[extern c inline "lean_nat_sub(#1, lean_box(1))"] def Nat.pred : (@& Nat) → Nat | 0 => 0 | succ a => a theorem Nat.pred_le_pred : {n m : Nat} → LE.le n m → LE.le (pred n) (pred m) | _, _, Nat.le.refl => Nat.le.refl | 0, succ _, Nat.le.step h => h | succ _, succ _, Nat.le.step h => Nat.le_trans (le_succ _) h theorem Nat.le_of_succ_le_succ {n m : Nat} : LE.le (succ n) (succ m) → LE.le n m := pred_le_pred theorem Nat.le_of_lt_succ {m n : Nat} : LT.lt m (succ n) → LE.le m n := le_of_succ_le_succ protected theorem Nat.eq_or_lt_of_le : {n m: Nat} → LE.le n m → Or (Eq n m) (LT.lt n m) | zero, zero, _ => Or.inl rfl | zero, succ _, _ => Or.inr (Nat.succ_le_succ (Nat.zero_le _)) | succ _, zero, h => absurd h (not_succ_le_zero _) | succ n, succ m, h => have : LE.le n m := Nat.le_of_succ_le_succ h match Nat.eq_or_lt_of_le this with | Or.inl h => Or.inl (h ▸ rfl) | Or.inr h => Or.inr (succ_le_succ h) protected theorem Nat.lt_or_ge (n m : Nat) : Or (LT.lt n m) (GE.ge n m) := match m with | zero => Or.inr (zero_le n) | succ m => match Nat.lt_or_ge n m with | Or.inl h => Or.inl (le_succ_of_le h) | Or.inr h => match Nat.eq_or_lt_of_le h with | Or.inl h1 => Or.inl (h1 ▸ Nat.le_refl _) | Or.inr h1 => Or.inr h1 theorem Nat.not_succ_le_self : (n : Nat) → Not (LE.le (succ n) n) | 0 => not_succ_le_zero _ | succ n => fun h => absurd (le_of_succ_le_succ h) (not_succ_le_self n) protected theorem Nat.lt_irrefl (n : Nat) : Not (LT.lt n n) := Nat.not_succ_le_self n protected theorem Nat.lt_of_le_of_lt {n m k : Nat} (h₁ : LE.le n m) (h₂ : LT.lt m k) : LT.lt n k := Nat.le_trans (Nat.succ_le_succ h₁) h₂ protected theorem Nat.le_antisymm {n m : Nat} (h₁ : LE.le n m) (h₂ : LE.le m n) : Eq n m := match h₁ with | Nat.le.refl => rfl | Nat.le.step h => absurd (Nat.lt_of_le_of_lt h h₂) (Nat.lt_irrefl n) protected theorem Nat.lt_of_le_of_ne {n m : Nat} (h₁ : LE.le n m) (h₂ : Not (Eq n m)) : LT.lt n m := match Nat.lt_or_ge n m with | Or.inl h₃ => h₃ | Or.inr h₃ => absurd (Nat.le_antisymm h₁ h₃) h₂ theorem Nat.le_of_ble_eq_true (h : Eq (Nat.ble n m) true) : LE.le n m := match n, m with | 0, _ => Nat.zero_le _ | succ _, succ _ => Nat.succ_le_succ (le_of_ble_eq_true h) theorem Nat.ble_self_eq_true : (n : Nat) → Eq (Nat.ble n n) true | 0 => rfl | succ n => ble_self_eq_true n theorem Nat.ble_succ_eq_true : {n m : Nat} → Eq (Nat.ble n m) true → Eq (Nat.ble n (succ m)) true | 0, _, _ => rfl | succ n, succ _, h => ble_succ_eq_true (n := n) h theorem Nat.ble_eq_true_of_le (h : LE.le n m) : Eq (Nat.ble n m) true := match h with | Nat.le.refl => Nat.ble_self_eq_true n | Nat.le.step h => Nat.ble_succ_eq_true (ble_eq_true_of_le h) theorem Nat.not_le_of_not_ble_eq_true (h : Not (Eq (Nat.ble n m) true)) : Not (LE.le n m) := fun h' => absurd (Nat.ble_eq_true_of_le h') h @[extern "lean_nat_dec_le"] instance Nat.decLe (n m : @& Nat) : Decidable (LE.le n m) := dite (Eq (Nat.ble n m) true) (fun h => isTrue (Nat.le_of_ble_eq_true h)) (fun h => isFalse (Nat.not_le_of_not_ble_eq_true h)) @[extern "lean_nat_dec_lt"] instance Nat.decLt (n m : @& Nat) : Decidable (LT.lt n m) := decLe (succ n) m set_option bootstrap.genMatcherCode false in /-- (Truncated) subtraction of natural numbers. Because natural numbers are not closed under subtraction, we define `m - n` to be `0` when `n < m`. This definition is overridden in both the kernel and the compiler to efficiently evaluate using the "bignum" representation (see `Nat`). The definition provided here is the logical model (and it is soundness-critical that they coincide). -/ @[extern "lean_nat_sub"] protected def Nat.sub : (@& Nat) → (@& Nat) → Nat | a, 0 => a | a, succ b => pred (Nat.sub a b) instance : Sub Nat where sub := Nat.sub /-- Gets the word size of the platform. That is, whether the platform is 64 or 32 bits. This function is opaque because we cannot guarantee at compile time that the target will have the same size as the host, and also because we would like to avoid typechecking being architecture-dependent. Nevertheless, lean only works on 64 and 32 bit systems so we can encode this as a fact available for proof purposes. -/ @[extern "lean_system_platform_nbits"] opaque System.Platform.getNumBits : Unit → Subtype fun (n : Nat) => Or (Eq n 32) (Eq n 64) := fun _ => ⟨64, Or.inr rfl⟩ -- inhabitant /-- Gets the word size of the platform. That is, whether the platform is 64 or 32 bits. -/ def System.Platform.numBits : Nat := (getNumBits ()).val theorem System.Platform.numBits_eq : Or (Eq numBits 32) (Eq numBits 64) := (getNumBits ()).property /-- `Fin n` is a natural number `i` with the constraint that `0 ≤ i < n`. It is the "canonical type with `n` elements". -/ structure Fin (n : Nat) where /-- If `i : Fin n`, then `i.val : ℕ` is the described number. It can also be written as `i.1` or just `i` when the target type is known. -/ val : Nat /-- If `i : Fin n`, then `i.2` is a proof that `i.1 < n`. -/ isLt : LT.lt val n theorem Fin.eq_of_val_eq {n} : ∀ {i j : Fin n}, Eq i.val j.val → Eq i j | ⟨_, _⟩, ⟨_, _⟩, rfl => rfl theorem Fin.val_eq_of_eq {n} {i j : Fin n} (h : Eq i j) : Eq i.val j.val := h ▸ rfl theorem Fin.ne_of_val_ne {n} {i j : Fin n} (h : Not (Eq i.val j.val)) : Not (Eq i j) := fun h' => absurd (val_eq_of_eq h') h instance (n : Nat) : DecidableEq (Fin n) := fun i j => match decEq i.val j.val with | isTrue h => isTrue (Fin.eq_of_val_eq h) | isFalse h => isFalse (Fin.ne_of_val_ne h) instance {n} : LT (Fin n) where lt a b := LT.lt a.val b.val instance {n} : LE (Fin n) where le a b := LE.le a.val b.val instance Fin.decLt {n} (a b : Fin n) : Decidable (LT.lt a b) := Nat.decLt .. instance Fin.decLe {n} (a b : Fin n) : Decidable (LE.le a b) := Nat.decLe .. /-- The size of type `UInt8`, that is, `2^8 = 256`. -/ def UInt8.size : Nat := 256 /-- The type of unsigned 8-bit integers. This type has special support in the compiler to make it actually 8 bits rather than wrapping a `Nat`. -/ structure UInt8 where /-- Unpack a `UInt8` as a `Nat` less than `2^8`. This function is overridden with a native implementation. -/ val : Fin UInt8.size attribute [extern "lean_uint8_of_nat_mk"] UInt8.mk attribute [extern "lean_uint8_to_nat"] UInt8.val /-- Pack a `Nat` less than `2^8` into a `UInt8`. This function is overridden with a native implementation. -/ @[extern "lean_uint8_of_nat"] def UInt8.ofNatCore (n : @& Nat) (h : LT.lt n UInt8.size) : UInt8 where val := { val := n, isLt := h } set_option bootstrap.genMatcherCode false in /-- Decides equality on `UInt8`. This function is overridden with a native implementation. -/ @[extern "lean_uint8_dec_eq"] def UInt8.decEq (a b : UInt8) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt8.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt8 := UInt8.decEq instance : Inhabited UInt8 where default := UInt8.ofNatCore 0 (by decide) /-- The size of type `UInt16`, that is, `2^16 = 65536`. -/ def UInt16.size : Nat := 65536 /-- The type of unsigned 16-bit integers. This type has special support in the compiler to make it actually 16 bits rather than wrapping a `Nat`. -/ structure UInt16 where /-- Unpack a `UInt16` as a `Nat` less than `2^16`. This function is overridden with a native implementation. -/ val : Fin UInt16.size attribute [extern "lean_uint16_of_nat_mk"] UInt16.mk attribute [extern "lean_uint16_to_nat"] UInt16.val /-- Pack a `Nat` less than `2^16` into a `UInt16`. This function is overridden with a native implementation. -/ @[extern "lean_uint16_of_nat"] def UInt16.ofNatCore (n : @& Nat) (h : LT.lt n UInt16.size) : UInt16 where val := { val := n, isLt := h } set_option bootstrap.genMatcherCode false in /-- Decides equality on `UInt16`. This function is overridden with a native implementation. -/ @[extern "lean_uint16_dec_eq"] def UInt16.decEq (a b : UInt16) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt16.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt16 := UInt16.decEq instance : Inhabited UInt16 where default := UInt16.ofNatCore 0 (by decide) /-- The size of type `UInt32`, that is, `2^32 = 4294967296`. -/ def UInt32.size : Nat := 4294967296 /-- The type of unsigned 32-bit integers. This type has special support in the compiler to make it actually 32 bits rather than wrapping a `Nat`. -/ structure UInt32 where /-- Unpack a `UInt32` as a `Nat` less than `2^32`. This function is overridden with a native implementation. -/ val : Fin UInt32.size attribute [extern "lean_uint32_of_nat_mk"] UInt32.mk attribute [extern "lean_uint32_to_nat"] UInt32.val /-- Pack a `Nat` less than `2^32` into a `UInt32`. This function is overridden with a native implementation. -/ @[extern "lean_uint32_of_nat"] def UInt32.ofNatCore (n : @& Nat) (h : LT.lt n UInt32.size) : UInt32 where val := { val := n, isLt := h } /-- Unpack a `UInt32` as a `Nat`. This function is overridden with a native implementation. -/ @[extern "lean_uint32_to_nat"] def UInt32.toNat (n : UInt32) : Nat := n.val.val set_option bootstrap.genMatcherCode false in /-- Decides equality on `UInt32`. This function is overridden with a native implementation. -/ @[extern "lean_uint32_dec_eq"] def UInt32.decEq (a b : UInt32) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt32.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt32 := UInt32.decEq instance : Inhabited UInt32 where default := UInt32.ofNatCore 0 (by decide) instance : LT UInt32 where lt a b := LT.lt a.val b.val instance : LE UInt32 where le a b := LE.le a.val b.val set_option bootstrap.genMatcherCode false in /-- Decides less-equal on `UInt32`. This function is overridden with a native implementation. -/ @[extern "lean_uint32_dec_lt"] def UInt32.decLt (a b : UInt32) : Decidable (LT.lt a b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (LT.lt n m)) set_option bootstrap.genMatcherCode false in /-- Decides less-than on `UInt32`. This function is overridden with a native implementation. -/ @[extern "lean_uint32_dec_le"] def UInt32.decLe (a b : UInt32) : Decidable (LE.le a b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (LE.le n m)) instance (a b : UInt32) : Decidable (LT.lt a b) := UInt32.decLt a b instance (a b : UInt32) : Decidable (LE.le a b) := UInt32.decLe a b /-- The size of type `UInt64`, that is, `2^64 = 18446744073709551616`. -/ def UInt64.size : Nat := 18446744073709551616 /-- The type of unsigned 64-bit integers. This type has special support in the compiler to make it actually 64 bits rather than wrapping a `Nat`. -/ structure UInt64 where /-- Unpack a `UInt64` as a `Nat` less than `2^64`. This function is overridden with a native implementation. -/ val : Fin UInt64.size attribute [extern "lean_uint64_of_nat_mk"] UInt64.mk attribute [extern "lean_uint64_to_nat"] UInt64.val /-- Pack a `Nat` less than `2^64` into a `UInt64`. This function is overridden with a native implementation. -/ @[extern "lean_uint64_of_nat"] def UInt64.ofNatCore (n : @& Nat) (h : LT.lt n UInt64.size) : UInt64 where val := { val := n, isLt := h } set_option bootstrap.genMatcherCode false in /-- Decides equality on `UInt64`. This function is overridden with a native implementation. -/ @[extern "lean_uint64_dec_eq"] def UInt64.decEq (a b : UInt64) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt64.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt64 := UInt64.decEq instance : Inhabited UInt64 where default := UInt64.ofNatCore 0 (by decide) /-- The size of type `UInt16`, that is, `2^System.Platform.numBits`, which may be either `2^32` or `2^64` depending on the platform's architecture. -/ def USize.size : Nat := hPow 2 System.Platform.numBits theorem usize_size_eq : Or (Eq USize.size 4294967296) (Eq USize.size 18446744073709551616) := show Or (Eq (hPow 2 System.Platform.numBits) 4294967296) (Eq (hPow 2 System.Platform.numBits) 18446744073709551616) from match System.Platform.numBits, System.Platform.numBits_eq with | _, Or.inl rfl => Or.inl (by decide) | _, Or.inr rfl => Or.inr (by decide) /-- A `USize` is an unsigned integer with the size of a word for the platform's architecture. For example, if running on a 32-bit machine, USize is equivalent to UInt32. Or on a 64-bit machine, UInt64. -/ structure USize where /-- Unpack a `USize` as a `Nat` less than `USize.size`. This function is overridden with a native implementation. -/ val : Fin USize.size attribute [extern "lean_usize_of_nat_mk"] USize.mk attribute [extern "lean_usize_to_nat"] USize.val /-- Pack a `Nat` less than `USize.size` into a `USize`. This function is overridden with a native implementation. -/ @[extern "lean_usize_of_nat"] def USize.ofNatCore (n : @& Nat) (h : LT.lt n USize.size) : USize := { val := { val := n, isLt := h } } set_option bootstrap.genMatcherCode false in /-- Decides equality on `USize`. This function is overridden with a native implementation. -/ @[extern "lean_usize_dec_eq"] def USize.decEq (a b : USize) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h =>isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => USize.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq USize := USize.decEq instance : Inhabited USize where default := USize.ofNatCore 0 (match USize.size, usize_size_eq with | _, Or.inl rfl => by decide | _, Or.inr rfl => by decide) /-- Upcast a `Nat` less than `2^32` to a `USize`. This is lossless because `USize.size` is either `2^32` or `2^64`. This function is overridden with a native implementation. -/ @[extern "lean_usize_of_nat"] def USize.ofNat32 (n : @& Nat) (h : LT.lt n 4294967296) : USize where val := { val := n isLt := match USize.size, usize_size_eq with | _, Or.inl rfl => h | _, Or.inr rfl => Nat.lt_trans h (by decide) } /-- A `Nat` denotes a valid unicode codepoint if it is less than `0x110000`, and it is also not a "surrogate" character (the range `0xd800` to `0xdfff` inclusive). -/ abbrev Nat.isValidChar (n : Nat) : Prop := Or (LT.lt n 0xd800) (And (LT.lt 0xdfff n) (LT.lt n 0x110000)) /-- A `UInt32` denotes a valid unicode codepoint if it is less than `0x110000`, and it is also not a "surrogate" character (the range `0xd800` to `0xdfff` inclusive). -/ abbrev UInt32.isValidChar (n : UInt32) : Prop := n.toNat.isValidChar /-- The `Char` Type represents an unicode scalar value. See http://www.unicode.org/glossary/#unicode_scalar_value). -/ structure Char where /-- The underlying unicode scalar value as a `UInt32`. -/ val : UInt32 /-- The value must be a legal codepoint. -/ valid : val.isValidChar private theorem isValidChar_UInt32 {n : Nat} (h : n.isValidChar) : LT.lt n UInt32.size := match h with | Or.inl h => Nat.lt_trans h (by decide) | Or.inr ⟨_, h⟩ => Nat.lt_trans h (by decide) /-- Pack a `Nat` encoding a valid codepoint into a `Char`. This function is overridden with a native implementation. -/ @[extern "lean_uint32_of_nat"] def Char.ofNatAux (n : @& Nat) (h : n.isValidChar) : Char := { val := ⟨{ val := n, isLt := isValidChar_UInt32 h }⟩, valid := h } /-- Convert a `Nat` into a `Char`. If the `Nat` does not encode a valid unicode scalar value, `'\0'` is returned instead. -/ @[noinline, matchPattern] def Char.ofNat (n : Nat) : Char := dite (n.isValidChar) (fun h => Char.ofNatAux n h) (fun _ => { val := ⟨{ val := 0, isLt := by decide }⟩, valid := Or.inl (by decide) }) theorem Char.eq_of_val_eq : ∀ {c d : Char}, Eq c.val d.val → Eq c d | ⟨_, _⟩, ⟨_, _⟩, rfl => rfl theorem Char.val_eq_of_eq : ∀ {c d : Char}, Eq c d → Eq c.val d.val | _, _, rfl => rfl theorem Char.ne_of_val_ne {c d : Char} (h : Not (Eq c.val d.val)) : Not (Eq c d) := fun h' => absurd (val_eq_of_eq h') h theorem Char.val_ne_of_ne {c d : Char} (h : Not (Eq c d)) : Not (Eq c.val d.val) := fun h' => absurd (eq_of_val_eq h') h instance : DecidableEq Char := fun c d => match decEq c.val d.val with | isTrue h => isTrue (Char.eq_of_val_eq h) | isFalse h => isFalse (Char.ne_of_val_ne h) /-- Returns the number of bytes required to encode this `Char` in UTF-8. -/ def Char.utf8Size (c : Char) : UInt32 := let v := c.val ite (LE.le v (UInt32.ofNatCore 0x7F (by decide))) (UInt32.ofNatCore 1 (by decide)) (ite (LE.le v (UInt32.ofNatCore 0x7FF (by decide))) (UInt32.ofNatCore 2 (by decide)) (ite (LE.le v (UInt32.ofNatCore 0xFFFF (by decide))) (UInt32.ofNatCore 3 (by decide)) (UInt32.ofNatCore 4 (by decide)))) /-- `Option α` is the type of values which are either `some a` for some `a : α`, or `none`. In functional programming languages, this type is used to represent the possibility of failure, or sometimes nullability. For example, the function `HashMap.find? : HashMap α β → α → Option β` looks up a specified key `a : α` inside the map. Because we do not know in advance whether the key is actually in the map, the return type is `Option β`, where `none` means the value was not in the map, and `some b` means that the value was found and `b` is the value retrieved. To extract a value from an `Option α`, we use pattern matching: ``` def map (f : α → β) (x : Option α) : Option β := match x with | some a => some (f a) | none => none ``` We can also use `if let` to pattern match on `Option` and get the value in the branch: ``` def map (f : α → β) (x : Option α) : Option β := if let some a := x then some (f a) else none ``` -/ inductive Option (α : Type u) where | /-- No value. -/ none : Option α | /-- Some value of type `α`. -/ some (val : α) : Option α attribute [unbox] Option export Option (none some) instance {α} : Inhabited (Option α) where default := none /-- Get with default. If `opt : Option α` and `dflt : α`, then `opt.getD dflt` returns `a` if `opt = some a` and `dflt` otherwise. This function is `@[macroInline]`, so `dflt` will not be evaluated unless `opt` turns out to be `none`. -/ @[macroInline] def Option.getD : Option α → α → α | some x, _ => x | none, e => e /-- Map a function over an `Option` by applying the function to the contained value if present. -/ @[inline] protected def Option.map (f : α → β) : Option α → Option β | some x => some (f x) | none => none /-- `List α` is the type of ordered lists with elements of type `α`. It is implemented as a linked list. `List α` is isomorphic to `Array α`, but they are useful for different things: * `List α` is easier for reasoning, and `Array α` is modeled as a wrapper around `List α` * `List α` works well as a persistent data structure, when many copies of the tail are shared. When the value is not shared, `Array α` will have better performance because it can do destructive updates. -/ inductive List (α : Type u) where | /-- `[]` is the empty list. -/ nil : List α | /-- If `a : α` and `l : List α`, then `cons a l`, or `a :: l`, is the list whose first element is `a` and with `l` as the rest of the list. -/ cons (head : α) (tail : List α) : List α instance {α} : Inhabited (List α) where default := List.nil /-- Implements decidable equality for `List α`, assuming `α` has decidable equality. -/ protected def List.hasDecEq {α : Type u} [DecidableEq α] : (a b : List α) → Decidable (Eq a b) | nil, nil => isTrue rfl | cons _ _, nil => isFalse (fun h => List.noConfusion h) | nil, cons _ _ => isFalse (fun h => List.noConfusion h) | cons a as, cons b bs => match decEq a b with | isTrue hab => match List.hasDecEq as bs with | isTrue habs => isTrue (hab ▸ habs ▸ rfl) | isFalse nabs => isFalse (fun h => List.noConfusion h (fun _ habs => absurd habs nabs)) | isFalse nab => isFalse (fun h => List.noConfusion h (fun hab _ => absurd hab nab)) instance {α : Type u} [DecidableEq α] : DecidableEq (List α) := List.hasDecEq /-- Folds a function over a list from the left: `foldl f z [a, b, c] = f (f (f z a) b) c` -/ @[specialize] def List.foldl {α β} (f : α → β → α) : (init : α) → List β → α | a, nil => a | a, cons b l => foldl f (f a b) l /-- `l.set n a` sets the value of list `l` at (zero-based) index `n` to `a`: `[a, b, c, d].set 1 b' = [a, b', c, d]` -/ def List.set : List α → Nat → α → List α | cons _ as, 0, b => cons b as | cons a as, Nat.succ n, b => cons a (set as n b) | nil, _, _ => nil /-- The length of a list: `[].length = 0` and `(a :: l).length = l.length + 1`. This function is overridden in the compiler to `lengthTR`, which uses constant stack space, while leaving this function to use the "naive" recursion which is easier for reasoning. -/ def List.length : List α → Nat | nil => 0 | cons _ as => HAdd.hAdd (length as) 1 /-- Auxiliary function for `List.lengthTR`. -/ def List.lengthTRAux : List α → Nat → Nat | nil, n => n | cons _ as, n => lengthTRAux as (Nat.succ n) /-- A tail-recursive version of `List.length`, used to implement `List.length` without running out of stack space. -/ def List.lengthTR (as : List α) : Nat := lengthTRAux as 0 @[simp] theorem List.length_cons {α} (a : α) (as : List α) : Eq (cons a as).length as.length.succ := rfl /-- `l.concat a` appends `a` at the *end* of `l`, that is, `l ++ [a]`. -/ def List.concat {α : Type u} : List α → α → List α | nil, b => cons b nil | cons a as, b => cons a (concat as b) /-- `as.get i` returns the `i`'th element of the list `as`. This version of the function uses `i : Fin as.length` to ensure that it will not index out of bounds. -/ def List.get {α : Type u} : (as : List α) → Fin as.length → α | cons a _, ⟨0, _⟩ => a | cons _ as, ⟨Nat.succ i, h⟩ => get as ⟨i, Nat.le_of_succ_le_succ h⟩ /-- `String` is the type of (UTF-8 encoded) strings. The compiler overrides the data representation of this type to a byte sequence, and both `String.utf8ByteSize` and `String.length` are cached and O(1). -/ structure String where /-- Pack a `List Char` into a `String`. This function is overridden by the compiler and is O(n) in the length of the list. -/ mk :: /-- Unpack `String` into a `List Char`. This function is overridden by the compiler and is O(n) in the length of the list. -/ data : List Char attribute [extern "lean_string_mk"] String.mk attribute [extern "lean_string_data"] String.data /-- Decides equality on `String`. This function is overridden with a native implementation. -/ @[extern "lean_string_dec_eq"] def String.decEq (s₁ s₂ : @& String) : Decidable (Eq s₁ s₂) := match s₁, s₂ with | ⟨s₁⟩, ⟨s₂⟩ => dite (Eq s₁ s₂) (fun h => isTrue (congrArg _ h)) (fun h => isFalse (fun h' => String.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq String := String.decEq /-- A byte position in a `String`. Internally, `String`s are UTF-8 encoded. Codepoint positions (counting the Unicode codepoints rather than bytes) are represented by plain `Nat`s instead. Indexing a `String` by a byte position is constant-time, while codepoint positions need to be translated internally to byte positions in linear-time. -/ structure String.Pos where /-- Get the underlying byte index of a `String.Pos` -/ byteIdx : Nat := 0 instance : Inhabited String.Pos where default := {} instance : DecidableEq String.Pos := fun ⟨a⟩ ⟨b⟩ => match decEq a b with | isTrue h => isTrue (h ▸ rfl) | isFalse h => isFalse (fun he => String.Pos.noConfusion he fun he => absurd he h) /-- A `Substring` is a view into some subslice of a `String`. The actual string slicing is deferred because this would require copying the string; here we only store a reference to the original string for garbage collection purposes. -/ structure Substring where /-- The underlying string to slice. -/ str : String /-- The byte position of the start of the string slice. -/ startPos : String.Pos /-- The byte position of the end of the string slice. -/ stopPos : String.Pos instance : Inhabited Substring where default := ⟨"", {}, {}⟩ /-- The byte length of the substring. -/ @[inline] def Substring.bsize : Substring → Nat | ⟨_, b, e⟩ => e.byteIdx.sub b.byteIdx /-- Returns the number of bytes required to encode this `Char` in UTF-8. -/ def String.csize (c : Char) : Nat := c.utf8Size.toNat /-- The UTF-8 byte length of this string. This is overridden by the compiler to be cached and O(1). -/ @[extern "lean_string_utf8_byte_size"] def String.utf8ByteSize : (@& String) → Nat | ⟨s⟩ => go s where go : List Char → Nat | .nil => 0 | .cons c cs => hAdd (go cs) (csize c) instance : HAdd String.Pos String.Pos String.Pos where hAdd p₁ p₂ := { byteIdx := hAdd p₁.byteIdx p₂.byteIdx } instance : HSub String.Pos String.Pos String.Pos where hSub p₁ p₂ := { byteIdx := HSub.hSub p₁.byteIdx p₂.byteIdx } instance : HAdd String.Pos Char String.Pos where hAdd p c := { byteIdx := hAdd p.byteIdx (String.csize c) } instance : HAdd String.Pos String String.Pos where hAdd p s := { byteIdx := hAdd p.byteIdx s.utf8ByteSize } instance : LE String.Pos where le p₁ p₂ := LE.le p₁.byteIdx p₂.byteIdx instance : LT String.Pos where lt p₁ p₂ := LT.lt p₁.byteIdx p₂.byteIdx instance (p₁ p₂ : String.Pos) : Decidable (LE.le p₁ p₂) := inferInstanceAs (Decidable (LE.le p₁.byteIdx p₂.byteIdx)) instance (p₁ p₂ : String.Pos) : Decidable (LT.lt p₁ p₂) := inferInstanceAs (Decidable (LT.lt p₁.byteIdx p₂.byteIdx)) /-- A `String.Pos` pointing at the end of this string. -/ @[inline] def String.endPos (s : String) : String.Pos where byteIdx := utf8ByteSize s /-- Convert a `String` into a `Substring` denoting the entire string. -/ @[inline] def String.toSubstring (s : String) : Substring where str := s startPos := {} stopPos := s.endPos /-- This function will cast a value of type `α` to type `β`, and is a no-op in the compiler. This function is **extremely dangerous** because there is no guarantee that types `α` and `β` have the same data representation, and this can lead to memory unsafety. It is also logically unsound, since you could just cast `True` to `False`. For all those reasons this function is marked as `unsafe`. It is implemented by lifting both `α` and `β` into a common universe, and then using `cast (lcProof : ULift (PLift α) = ULift (PLift β))` to actually perform the cast. All these operations are no-ops in the compiler. Using this function correctly requires some knowledge of the data representation of the source and target types. Some general classes of casts which are safe in the current runtime: * `Array α` to `Array β` where `α` and `β` have compatible representations, or more generally for other inductive types. * `Quot α r` and `α`. * `@Subtype α p` and `α`, or generally any structure containing only one non-`Prop` field of type `α`. * Casting `α` to/from `NonScalar` when `α` is a boxed generic type (i.e. a function that accepts an arbitrary type `α` and is not specialized to a scalar type like `UInt8`). -/ unsafe def unsafeCast {α : Sort u} {β : Sort v} (a : α) : β := PLift.down (ULift.down.{max u v} (cast lcProof (ULift.up.{max u v} (PLift.up a)))) /-- Auxiliary definition for `panic`. -/ /- This is a workaround for `panic` occurring in monadic code. See issue #695. The `panicCore` definition cannot be specialized since it is an extern. When `panic` occurs in monadic code, the `Inhabited α` parameter depends on a `[inst : Monad m]` instance. The `inst` parameter will not be eliminated during specialization if it occurs inside of a binder (to avoid work duplication), and will prevent the the actual monad from being "copied" to the code being specialized. When we reimplement the specializer, we may consider copying `inst` if it also occurs outside binders or if it is an instance. -/ @[neverExtract, extern "lean_panic_fn"] opaque panicCore {α : Type u} [Inhabited α] (msg : String) : α /-- `(panic "msg" : α)` has a built-in implementation which prints `msg` to the error buffer. It *does not* terminate execution, and because it is a safe function, it still has to return an element of `α`, so it takes `[Inhabited α]` and returns `default`. It is primarily intended for debugging in pure contexts, and assertion failures. Because this is a pure function with side effects, it is marked as `@[neverExtract]` so that the compiler will not perform common sub-expression elimination and other optimizations that assume that the expression is pure. -/ @[noinline, neverExtract] def panic {α : Type u} [Inhabited α] (msg : String) : α := panicCore msg -- TODO: this be applied directly to `Inhabited`'s definition when we remove the above workaround attribute [nospecialize] Inhabited /-- The class `GetElem cont idx elem dom` implements the `xs[i]` notation. When you write this, given `xs : cont` and `i : idx`, lean looks for an instance of `GetElem cont idx elem dom`. Here `elem` is the type of `xs[i]`, while `dom` is whatever proof side conditions are required to make this applicable. For example, the instance for arrays looks like `GetElem (Array α) Nat α (fun xs i => i < xs.size)`. The proof side-condition `dom xs i` is automatically dispatched by the `get_elem_tactic` tactic, which can be extended by adding more clauses to `get_elem_tactic_trivial`. -/ class GetElem (cont : Type u) (idx : Type v) (elem : outParam (Type w)) (dom : outParam (cont → idx → Prop)) where /-- The implementation of `xs[i]`. `h` is discharged by `get_elem_tactic`. -/ getElem (xs : cont) (i : idx) (h : dom xs i) : elem export GetElem (getElem) /-- `Array α` is the type of [dynamic arrays](https://en.wikipedia.org/wiki/Dynamic_array) with elements from `α`. This type has special support in the runtime. An array has a size and a capacity; the size is `Array.size` but the capacity is not observable from lean code. Arrays perform best when unshared; as long as they are used "linearly" all updates will be performed destructively on the array, so it has comparable performance to mutable arrays in imperative programming languages. -/ structure Array (α : Type u) where /-- Convert a `List α` into an `Array α`. This function is overridden to `List.toArray` and is O(n) in the length of the list. -/ mk :: /-- Convert an `Array α` into a `List α`. This function is overridden to `Array.toList` and is O(n) in the length of the list. -/ data : List α attribute [extern "lean_array_data"] Array.data attribute [extern "lean_array_mk"] Array.mk /-- Construct a new empty array with initial capacity `c`. -/ @[extern "lean_mk_empty_array_with_capacity"] def Array.mkEmpty {α : Type u} (c : @& Nat) : Array α where data := List.nil /-- Construct a new empty array. -/ def Array.empty {α : Type u} : Array α := mkEmpty 0 /-- Get the size of an array. This is a cached value, so it is O(1) to access. -/ @[reducible, extern "lean_array_get_size"] def Array.size {α : Type u} (a : @& Array α) : Nat := a.data.length /-- Access an element from an array without bounds checks, using a `Fin` index. -/ @[extern "lean_array_fget"] def Array.get {α : Type u} (a : @& Array α) (i : @& Fin a.size) : α := a.data.get i /-- Access an element from an array, or return `v₀` if the index is out of bounds. -/ @[inline] abbrev Array.getD (a : Array α) (i : Nat) (v₀ : α) : α := dite (LT.lt i a.size) (fun h => a.get ⟨i, h⟩) (fun _ => v₀) /-- Access an element from an array, or panic if the index is out of bounds. -/ @[extern "lean_array_get"] def Array.get! {α : Type u} [Inhabited α] (a : @& Array α) (i : @& Nat) : α := Array.getD a i default instance : GetElem (Array α) Nat α fun xs i => LT.lt i xs.size where getElem xs i h := xs.get ⟨i, h⟩ /-- Push an element onto the end of an array. This is amortized O(1) because `Array α` is internally a dynamic array. -/ @[extern "lean_array_push"] def Array.push {α : Type u} (a : Array α) (v : α) : Array α where data := List.concat a.data v /-- Set an element in an array without bounds checks, using a `Fin` index. This will perform the update destructively provided that `a` has a reference count of 1 when called. -/ @[extern "lean_array_fset"] def Array.set (a : Array α) (i : @& Fin a.size) (v : α) : Array α where data := a.data.set i.val v /-- Set an element in an array, or do nothing if the index is out of bounds. This will perform the update destructively provided that `a` has a reference count of 1 when called. -/ @[inline] def Array.setD (a : Array α) (i : Nat) (v : α) : Array α := dite (LT.lt i a.size) (fun h => a.set ⟨i, h⟩ v) (fun _ => a) /-- Set an element in an array, or panic if the index is out of bounds. This will perform the update destructively provided that `a` has a reference count of 1 when called. -/ @[extern "lean_array_set"] def Array.set! (a : Array α) (i : @& Nat) (v : α) : Array α := Array.setD a i v /-- Slower `Array.append` used in quotations. -/ protected def Array.appendCore {α : Type u} (as : Array α) (bs : Array α) : Array α := let rec loop (i : Nat) (j : Nat) (as : Array α) : Array α := dite (LT.lt j bs.size) (fun hlt => match i with | 0 => as | Nat.succ i' => loop i' (hAdd j 1) (as.push (bs.get ⟨j, hlt⟩))) (fun _ => as) loop bs.size 0 as /-- Auxiliary definition for `List.toArray`. -/ @[inlineIfReduce] def List.toArrayAux : List α → Array α → Array α | nil, r => r | cons a as, r => toArrayAux as (r.push a) /-- A non-tail-recursive version of `List.length`, used for `List.toArray`. -/ @[inlineIfReduce] def List.redLength : List α → Nat | nil => 0 | cons _ as => as.redLength.succ /-- Convert a `List α` into an `Array α`. This is O(n) in the length of the list. This function is exported to C, where it is called by `Array.mk` (the constructor) to implement this functionality. -/ @[inline, matchPattern, export lean_list_to_array] def List.toArray (as : List α) : Array α := as.toArrayAux (Array.mkEmpty as.redLength) /-- The typeclass which supplies the `>>=` "bind" function. See `Monad`. -/ class Bind (m : Type u → Type v) where /-- If `x : m α` and `f : α → m β`, then `x >>= f : m β` represents the result of executing `x` to get a value of type `α` and then passing it to `f`. -/ bind : {α β : Type u} → m α → (α → m β) → m β export Bind (bind) /-- The typeclass which supplies the `pure` function. See `Monad`. -/ class Pure (f : Type u → Type v) where /-- If `a : α`, then `pure a : f α` represents a monadic action that does nothing and returns `a`. -/ pure {α : Type u} : α → f α export Pure (pure) /-- In functional programming, a "functor" is a function on types `F : Type u → Type v` equipped with an operator called `map` or `<$>` such that if `f : α → β` then `map f : F α → F β`, so `f <$> x : F β` if `x : F α`. This corresponds to the category-theory notion of [functor](https://en.wikipedia.org/wiki/Functor) in the special case where the category is the category of types and functions between them, except that this class supplies only the operations and not the laws (see `LawfulFunctor`). -/ class Functor (f : Type u → Type v) : Type (max (u+1) v) where /-- If `f : α → β` and `x : F α` then `f <$> x : F β`. -/ map : {α β : Type u} → (α → β) → f α → f β /-- The special case `const a <$> x`, which can sometimes be implemented more efficiently. -/ mapConst : {α β : Type u} → α → f β → f α := Function.comp map (Function.const _) /-- The typeclass which supplies the `<*>` "seq" function. See `Applicative`. -/ class Seq (f : Type u → Type v) : Type (max (u+1) v) where /-- If `mf : F (α → β)` and `mx : F α`, then `mf <*> mx : F β`. In a monad this is the same as `do let f ← mf; x ← mx; pure (f x)`: it evaluates first the function, then the argument, and applies one to the other. To avoid surprising evaluation semantics, `mx` is taken "lazily", using a `Unit → f α` function. -/ seq : {α β : Type u} → f (α → β) → (Unit → f α) → f β /-- The typeclass which supplies the `<*` "seqLeft" function. See `Applicative`. -/ class SeqLeft (f : Type u → Type v) : Type (max (u+1) v) where /-- If `x : F α` and `y : F β`, then `x <* y` evaluates `x`, then `y`, and returns the result of `x`. To avoid surprising evaluation semantics, `y` is taken "lazily", using a `Unit → f β` function. -/ seqLeft : {α β : Type u} → f α → (Unit → f β) → f α /-- The typeclass which supplies the `<*` "seqRight" function. See `Applicative`. -/ class SeqRight (f : Type u → Type v) : Type (max (u+1) v) where /-- If `x : F α` and `y : F β`, then `x *> y` evaluates `x`, then `y`, and returns the result of `y`. To avoid surprising evaluation semantics, `y` is taken "lazily", using a `Unit → f β` function. -/ seqRight : {α β : Type u} → f α → (Unit → f β) → f β /-- An [applicative functor](https://en.wikipedia.org/wiki/Applicative_functor) is an intermediate structure between `Functor` and `Monad`. It mainly consists of two operations: * `pure : α → F α` * `seq : F (α → β) → F α → F β` (written as `<*>`) The `seq` operator gives a notion of evaluation order to the effects, where the first argument is executed before the second, but unlike a monad the results of earlier computations cannot be used to define later actions. -/ class Applicative (f : Type u → Type v) extends Functor f, Pure f, Seq f, SeqLeft f, SeqRight f where map := fun x y => Seq.seq (pure x) fun _ => y seqLeft := fun a b => Seq.seq (Functor.map (Function.const _) a) b seqRight := fun a b => Seq.seq (Functor.map (Function.const _ id) a) b /-- A [monad](https://en.wikipedia.org/wiki/Monad_(functional_programming)) is a structure which abstracts the concept of sequential control flow. It mainly consists of two operations: * `pure : α → F α` * `bind : F α → (α → F β) → F β` (written as `>>=`) Like many functional programming languages, Lean makes extensive use of monads for structuring programs. In particular, the `do` notation is a very powerful syntax over monad operations, and it depends on a `Monad` instance. See [the `do` notation](https://leanprover.github.io/lean4/doc/do.html) chapter of the manual for details. -/ class Monad (m : Type u → Type v) extends Applicative m, Bind m : Type (max (u+1) v) where map f x := bind x (Function.comp pure f) seq f x := bind f fun y => Functor.map y (x ()) seqLeft x y := bind x fun a => bind (y ()) (fun _ => pure a) seqRight x y := bind x fun _ => y () instance {α : Type u} {m : Type u → Type v} [Monad m] : Inhabited (α → m α) where default := pure instance {α : Type u} {m : Type u → Type v} [Monad m] [Inhabited α] : Inhabited (m α) where default := pure default /-- A fusion of Haskell's `sequence` and `map`. Used in syntax quotations. -/ def Array.sequenceMap {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (f : α → m β) : m (Array β) := let rec loop (i : Nat) (j : Nat) (bs : Array β) : m (Array β) := dite (LT.lt j as.size) (fun hlt => match i with | 0 => pure bs | Nat.succ i' => Bind.bind (f (as.get ⟨j, hlt⟩)) fun b => loop i' (hAdd j 1) (bs.push b)) (fun _ => pure bs) loop as.size 0 (Array.mkEmpty as.size) /-- A function for lifting a computation from an inner `Monad` to an outer `Monad`. Like Haskell's [`MonadTrans`], but `n` does not have to be a monad transformer. Alternatively, an implementation of [`MonadLayer`] without `layerInvmap` (so far). [`MonadTrans`]: https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Class.html [`MonadLayer`]: https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLayer -/ class MonadLift (m : Type u → Type v) (n : Type u → Type w) where /-- Lifts a value from monad `m` into monad `n`. -/ monadLift : {α : Type u} → m α → n α /-- The reflexive-transitive closure of `MonadLift`. `monadLift` is used to transitively lift monadic computations such as `StateT.get` or `StateT.put s`. Corresponds to Haskell's [`MonadLift`]. [`MonadLift`]: https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLift -/ class MonadLiftT (m : Type u → Type v) (n : Type u → Type w) where /-- Lifts a value from monad `m` into monad `n`. -/ monadLift : {α : Type u} → m α → n α export MonadLiftT (monadLift) /-- Lifts a value from monad `m` into monad `n`. -/ abbrev liftM := @monadLift instance (m n o) [MonadLift n o] [MonadLiftT m n] : MonadLiftT m o where monadLift x := MonadLift.monadLift (m := n) (monadLift x) instance (m) : MonadLiftT m m where monadLift x := x /-- A functor in the category of monads. Can be used to lift monad-transforming functions. Based on [`MFunctor`] from the `pipes` Haskell package, but not restricted to monad transformers. Alternatively, an implementation of [`MonadTransFunctor`]. [`MFunctor`]: https://hackage.haskell.org/package/pipes-2.4.0/docs/Control-MFunctor.html [`MonadTransFunctor`]: http://duairc.netsoc.ie/layers-docs/Control-Monad-Layer.html#t:MonadTransFunctor -/ class MonadFunctor (m : Type u → Type v) (n : Type u → Type w) where /-- Lifts a monad morphism `f : {β : Type u} → m β → m β` to `monadMap f : {α : Type u} → n α → n α`. -/ monadMap {α : Type u} : ({β : Type u} → m β → m β) → n α → n α /-- The reflexive-transitive closure of `MonadFunctor`. `monadMap` is used to transitively lift `Monad` morphisms. -/ class MonadFunctorT (m : Type u → Type v) (n : Type u → Type w) where /-- Lifts a monad morphism `f : {β : Type u} → m β → m β` to `monadMap f : {α : Type u} → n α → n α`. -/ monadMap {α : Type u} : ({β : Type u} → m β → m β) → n α → n α export MonadFunctorT (monadMap) instance (m n o) [MonadFunctor n o] [MonadFunctorT m n] : MonadFunctorT m o where monadMap f := MonadFunctor.monadMap (m := n) (monadMap (m := m) f) instance monadFunctorRefl (m) : MonadFunctorT m m where monadMap f := f /-- `Except ε α` is a type which represents either an error of type `ε`, or an "ok" value of type `α`. The error type is listed first because `Except ε : Type → Type` is a `Monad`: the pure operation is `ok` and the bind operation returns the first encountered `error`. -/ inductive Except (ε : Type u) (α : Type v) where | /-- A failure value of type `ε` -/ error : ε → Except ε α | /-- A success value of type `α` -/ ok : α → Except ε α attribute [unbox] Except instance {ε : Type u} {α : Type v} [Inhabited ε] : Inhabited (Except ε α) where default := Except.error default /-- An implementation of Haskell's [`MonadError`] class. A `MonadError ε m` is a monad `m` with two operations: * `throw : ε → m α` "throws an error" of type `ε` to the nearest enclosing catch block * `tryCatch (body : m α) (handler : ε → m α) : m α` will catch any errors in `body` and pass the resulting error to `handler`. Errors in `handler` will not be caught. The `try ... catch e => ...` syntax inside `do` blocks is sugar for the `tryCatch` operation. [`MonadError`]: https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Except.html#t:MonadError -/ class MonadExceptOf (ε : Type u) (m : Type v → Type w) where /-- `throw : ε → m α` "throws an error" of type `ε` to the nearest enclosing catch block. -/ throw {α : Type v} : ε → m α /-- `tryCatch (body : m α) (handler : ε → m α) : m α` will catch any errors in `body` and pass the resulting error to `handler`. Errors in `handler` will not be caught. -/ tryCatch {α : Type v} (body : m α) (handler : ε → m α) : m α /-- This is the same as `throw`, but allows specifying the particular error type in case the monad supports throwing more than one type of error. -/ abbrev throwThe (ε : Type u) {m : Type v → Type w} [MonadExceptOf ε m] {α : Type v} (e : ε) : m α := MonadExceptOf.throw e /-- This is the same as `tryCatch`, but allows specifying the particular error type in case the monad supports throwing more than one type of error. -/ abbrev tryCatchThe (ε : Type u) {m : Type v → Type w} [MonadExceptOf ε m] {α : Type v} (x : m α) (handle : ε → m α) : m α := MonadExceptOf.tryCatch x handle /-- Similar to `MonadExceptOf`, but `ε` is an `outParam` for convenience. -/ class MonadExcept (ε : outParam (Type u)) (m : Type v → Type w) where /-- `throw : ε → m α` "throws an error" of type `ε` to the nearest enclosing catch block. -/ throw {α : Type v} : ε → m α /-- `tryCatch (body : m α) (handler : ε → m α) : m α` will catch any errors in `body` and pass the resulting error to `handler`. Errors in `handler` will not be caught. -/ tryCatch {α : Type v} : m α → (ε → m α) → m α /-- "Unwraps" an `Except ε α` to get the `α`, or throws the exception otherwise. -/ def MonadExcept.ofExcept [Monad m] [MonadExcept ε m] : Except ε α → m α | .ok a => pure a | .error e => throw e export MonadExcept (throw tryCatch ofExcept) instance (ε : outParam (Type u)) (m : Type v → Type w) [MonadExceptOf ε m] : MonadExcept ε m where throw := throwThe ε tryCatch := tryCatchThe ε namespace MonadExcept variable {ε : Type u} {m : Type v → Type w} /-- A `MonadExcept` can implement `t₁ <|> t₂` as `try t₁ catch _ => t₂`. -/ @[inline] protected def orElse [MonadExcept ε m] {α : Type v} (t₁ : m α) (t₂ : Unit → m α) : m α := tryCatch t₁ fun _ => t₂ () instance [MonadExcept ε m] {α : Type v} : OrElse (m α) where orElse := MonadExcept.orElse end MonadExcept /-- An implementation of Haskell's [`ReaderT`]. This is a monad transformer which equips a monad with additional read-only state, of type `ρ`. [`ReaderT`]: https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Reader.html#t:ReaderT -/ def ReaderT (ρ : Type u) (m : Type u → Type v) (α : Type u) : Type (max u v) := ρ → m α instance (ρ : Type u) (m : Type u → Type v) (α : Type u) [Inhabited (m α)] : Inhabited (ReaderT ρ m α) where default := fun _ => default /-- If `x : ReaderT ρ m α` and `r : ρ`, then `x.run r : ρ` runs the monad with the given reader state. -/ @[inline] def ReaderT.run {ρ : Type u} {m : Type u → Type v} {α : Type u} (x : ReaderT ρ m α) (r : ρ) : m α := x r namespace ReaderT section variable {ρ : Type u} {m : Type u → Type v} {α : Type u} instance : MonadLift m (ReaderT ρ m) where monadLift x := fun _ => x instance (ε) [MonadExceptOf ε m] : MonadExceptOf ε (ReaderT ρ m) where throw e := liftM (m := m) (throw e) tryCatch := fun x c r => tryCatchThe ε (x r) (fun e => (c e) r) end section variable {ρ : Type u} {m : Type u → Type v} /-- `(← read) : ρ` gets the read-only state of a `ReaderT ρ`. -/ @[inline] protected def read [Monad m] : ReaderT ρ m ρ := pure /-- The `pure` operation of the `ReaderT` monad. -/ @[inline] protected def pure [Monad m] {α} (a : α) : ReaderT ρ m α := fun _ => pure a /-- The `bind` operation of the `ReaderT` monad. -/ @[inline] protected def bind [Monad m] {α β} (x : ReaderT ρ m α) (f : α → ReaderT ρ m β) : ReaderT ρ m β := fun r => bind (x r) fun a => f a r instance [Monad m] : Functor (ReaderT ρ m) where map f x r := Functor.map f (x r) mapConst a x r := Functor.mapConst a (x r) instance [Monad m] : Applicative (ReaderT ρ m) where pure := ReaderT.pure seq f x r := Seq.seq (f r) fun _ => x () r seqLeft a b r := SeqLeft.seqLeft (a r) fun _ => b () r seqRight a b r := SeqRight.seqRight (a r) fun _ => b () r instance [Monad m] : Monad (ReaderT ρ m) where bind := ReaderT.bind instance (ρ m) : MonadFunctor m (ReaderT ρ m) where monadMap f x := fun ctx => f (x ctx) /-- `adapt (f : ρ' → ρ)` precomposes function `f` on the reader state of a `ReaderT ρ`, yielding a `ReaderT ρ'`. -/ @[inline] protected def adapt {ρ' α : Type u} (f : ρ' → ρ) : ReaderT ρ m α → ReaderT ρ' m α := fun x r => x (f r) end end ReaderT /-- An implementation of [`MonadReader`]. It does not contain `local` because this function cannot be lifted using `monadLift`. Instead, the `MonadReaderAdapter` class provides the more general `adaptReader` function. Note: This class can be seen as a simplification of the more "principled" definition ``` class MonadReaderOf (ρ : Type u) (n : Type u → Type u) where lift {α : Type u} : ({m : Type u → Type u} → [Monad m] → ReaderT ρ m α) → n α ``` [`MonadReader`]: https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Reader-Class.html#t:MonadReader -/ class MonadReaderOf (ρ : Type u) (m : Type u → Type v) where /-- `(← read) : ρ` reads the state out of monad `m`. -/ read : m ρ /-- Like `read`, but with `ρ` explicit. This is useful if a monad supports `MonadReaderOf` for multiple different types `ρ`. -/ @[inline] def readThe (ρ : Type u) {m : Type u → Type v} [MonadReaderOf ρ m] : m ρ := MonadReaderOf.read /-- Similar to `MonadReaderOf`, but `ρ` is an `outParam` for convenience. -/ class MonadReader (ρ : outParam (Type u)) (m : Type u → Type v) where /-- `(← read) : ρ` reads the state out of monad `m`. -/ read : m ρ export MonadReader (read) instance (ρ : Type u) (m : Type u → Type v) [MonadReaderOf ρ m] : MonadReader ρ m where read := readThe ρ instance {ρ : Type u} {m : Type u → Type v} {n : Type u → Type w} [MonadLift m n] [MonadReaderOf ρ m] : MonadReaderOf ρ n where read := liftM (m := m) read instance {ρ : Type u} {m : Type u → Type v} [Monad m] : MonadReaderOf ρ (ReaderT ρ m) where read := ReaderT.read /-- `MonadWithReaderOf ρ` adds the operation `withReader : (ρ → ρ) → m α → m α`. This runs the inner `x : m α` inside a modified context after applying the function `f : ρ → ρ`. In addition to `ReaderT` itself, this operation lifts over most monad transformers, so it allows us to apply `withReader` to monads deeper in the stack. -/ class MonadWithReaderOf (ρ : Type u) (m : Type u → Type v) where /-- `withReader (f : ρ → ρ) (x : m α) : m α` runs the inner `x : m α` inside a modified context after applying the function `f : ρ → ρ`.-/ withReader {α : Type u} : (ρ → ρ) → m α → m α /-- Like `withReader`, but with `ρ` explicit. This is useful if a monad supports `MonadWithReaderOf` for multiple different types `ρ`. -/ @[inline] def withTheReader (ρ : Type u) {m : Type u → Type v} [MonadWithReaderOf ρ m] {α : Type u} (f : ρ → ρ) (x : m α) : m α := MonadWithReaderOf.withReader f x /-- Similar to `MonadWithReaderOf`, but `ρ` is an `outParam` for convenience. -/ class MonadWithReader (ρ : outParam (Type u)) (m : Type u → Type v) where /-- `withReader (f : ρ → ρ) (x : m α) : m α` runs the inner `x : m α` inside a modified context after applying the function `f : ρ → ρ`.-/ withReader {α : Type u} : (ρ → ρ) → m α → m α export MonadWithReader (withReader) instance (ρ : Type u) (m : Type u → Type v) [MonadWithReaderOf ρ m] : MonadWithReader ρ m where withReader := withTheReader ρ instance {ρ : Type u} {m : Type u → Type v} {n : Type u → Type v} [MonadFunctor m n] [MonadWithReaderOf ρ m] : MonadWithReaderOf ρ n where withReader f := monadMap (m := m) (withTheReader ρ f) instance {ρ : Type u} {m : Type u → Type v} [Monad m] : MonadWithReaderOf ρ (ReaderT ρ m) where withReader f x := fun ctx => x (f ctx) /-- An implementation of [`MonadState`]. In contrast to the Haskell implementation, we use overlapping instances to derive instances automatically from `monadLift`. [`MonadState`]: https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-State-Class.html -/ class MonadStateOf (σ : Type u) (m : Type u → Type v) where /-- `(← get) : σ` gets the state out of a monad `m`. -/ get : m σ /-- `set (s : σ)` replaces the state with value `s`. -/ set : σ → m PUnit /-- `modifyGet (f : σ → α × σ)` applies `f` to the current state, replaces the state with the return value, and returns a computed value. It is equivalent to `do let (a, s) := f (← get); put s; pure a`, but `modifyGet f` may be preferable because the former does not use the state linearly (without sufficient inlining). -/ modifyGet {α : Type u} : (σ → Prod α σ) → m α export MonadStateOf (set) /-- Like `withReader`, but with `ρ` explicit. This is useful if a monad supports `MonadWithReaderOf` for multiple different types `ρ`. -/ abbrev getThe (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] : m σ := MonadStateOf.get /-- Like `modify`, but with `σ` explicit. This is useful if a monad supports `MonadStateOf` for multiple different types `σ`. -/ @[inline] abbrev modifyThe (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] (f : σ → σ) : m PUnit := MonadStateOf.modifyGet fun s => (PUnit.unit, f s) /-- Like `modifyGet`, but with `σ` explicit. This is useful if a monad supports `MonadStateOf` for multiple different types `σ`. -/ @[inline] abbrev modifyGetThe {α : Type u} (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] (f : σ → Prod α σ) : m α := MonadStateOf.modifyGet f /-- Similar to `MonadStateOf`, but `σ` is an `outParam` for convenience. -/ class MonadState (σ : outParam (Type u)) (m : Type u → Type v) where /-- `(← get) : σ` gets the state out of a monad `m`. -/ get : m σ /-- `set (s : σ)` replaces the state with value `s`. -/ set : σ → m PUnit /-- `modifyGet (f : σ → α × σ)` applies `f` to the current state, replaces the state with the return value, and returns a computed value. It is equivalent to `do let (a, s) := f (← get); put s; pure a`, but `modifyGet f` may be preferable because the former does not use the state linearly (without sufficient inlining). -/ modifyGet {α : Type u} : (σ → Prod α σ) → m α export MonadState (get modifyGet) instance (σ : Type u) (m : Type u → Type v) [MonadStateOf σ m] : MonadState σ m where set := MonadStateOf.set get := getThe σ modifyGet f := MonadStateOf.modifyGet f /-- `modify (f : σ → σ)` applies the function `f` to the state. It is equivalent to `do put (f (← get))`, but `modify f` may be preferable because the former does not use the state linearly (without sufficient inlining). -/ @[inline] def modify {σ : Type u} {m : Type u → Type v} [MonadState σ m] (f : σ → σ) : m PUnit := modifyGet fun s => (PUnit.unit, f s) /-- `getModify f` gets the state, applies function `f`, and returns the old value of the state. It is equivalent to `get <* modify f` but may be more efficient. -/ @[inline] def getModify {σ : Type u} {m : Type u → Type v} [MonadState σ m] [Monad m] (f : σ → σ) : m σ := modifyGet fun s => (s, f s) -- NOTE: The Ordering of the following two instances determines that the top-most `StateT` Monad layer -- will be picked first instance {σ : Type u} {m : Type u → Type v} {n : Type u → Type w} [MonadLift m n] [MonadStateOf σ m] : MonadStateOf σ n where get := liftM (m := m) MonadStateOf.get set s := liftM (m := m) (MonadStateOf.set s) modifyGet f := monadLift (m := m) (MonadState.modifyGet f) namespace EStateM /-- `Result ε σ α` is equivalent to `Except ε α × σ`, but using a single combined inductive yields a more efficient data representation. -/ inductive Result (ε σ α : Type u) where | /-- A success value of type `α`, and a new state `σ`. -/ ok : α → σ → Result ε σ α | /-- A failure value of type `ε`, and a new state `σ`. -/ error : ε → σ → Result ε σ α variable {ε σ α : Type u} instance [Inhabited ε] [Inhabited σ] : Inhabited (Result ε σ α) where default := Result.error default default end EStateM open EStateM (Result) in /-- `EStateM ε σ` is a combined error and state monad, equivalent to `ExceptT ε (StateM σ)` but more efficient. -/ def EStateM (ε σ α : Type u) := σ → Result ε σ α namespace EStateM variable {ε σ α β : Type u} instance [Inhabited ε] : Inhabited (EStateM ε σ α) where default := fun s => Result.error default s /-- The `pure` operation of the `EStateM` monad. -/ @[inline] protected def pure (a : α) : EStateM ε σ α := fun s => Result.ok a s /-- The `set` operation of the `EStateM` monad. -/ @[inline] protected def set (s : σ) : EStateM ε σ PUnit := fun _ => Result.ok ⟨⟩ s /-- The `get` operation of the `EStateM` monad. -/ @[inline] protected def get : EStateM ε σ σ := fun s => Result.ok s s /-- The `modifyGet` operation of the `EStateM` monad. -/ @[inline] protected def modifyGet (f : σ → Prod α σ) : EStateM ε σ α := fun s => match f s with | (a, s) => Result.ok a s /-- The `throw` operation of the `EStateM` monad. -/ @[inline] protected def throw (e : ε) : EStateM ε σ α := fun s => Result.error e s /-- Auxiliary instance for saving/restoring the "backtrackable" part of the state. Here `σ` is the state, and `δ` is some subpart of it, and we have a getter and setter for it (a "lens" in the Haskell terminology). -/ class Backtrackable (δ : outParam (Type u)) (σ : Type u) where /-- `save s : δ` retrieves a copy of the backtracking state out of the state. -/ save : σ → δ /-- `restore (s : σ) (x : δ) : σ` applies the old backtracking state `x` to the state `s` to get a backtracked state `s'`. -/ restore : σ → δ → σ /-- Implementation of `tryCatch` for `EStateM` where the state is `Backtrackable`. -/ @[inline] protected def tryCatch {δ} [Backtrackable δ σ] {α} (x : EStateM ε σ α) (handle : ε → EStateM ε σ α) : EStateM ε σ α := fun s => let d := Backtrackable.save s match x s with | Result.error e s => handle e (Backtrackable.restore s d) | ok => ok /-- Implementation of `orElse` for `EStateM` where the state is `Backtrackable`. -/ @[inline] protected def orElse {δ} [Backtrackable δ σ] (x₁ : EStateM ε σ α) (x₂ : Unit → EStateM ε σ α) : EStateM ε σ α := fun s => let d := Backtrackable.save s; match x₁ s with | Result.error _ s => x₂ () (Backtrackable.restore s d) | ok => ok /-- Map the exception type of a `EStateM ε σ α` by a function `f : ε → ε'`. -/ @[inline] def adaptExcept {ε' : Type u} (f : ε → ε') (x : EStateM ε σ α) : EStateM ε' σ α := fun s => match x s with | Result.error e s => Result.error (f e) s | Result.ok a s => Result.ok a s /-- The `bind` operation of the `EStateM` monad. -/ @[inline] protected def bind (x : EStateM ε σ α) (f : α → EStateM ε σ β) : EStateM ε σ β := fun s => match x s with | Result.ok a s => f a s | Result.error e s => Result.error e s /-- The `map` operation of the `EStateM` monad. -/ @[inline] protected def map (f : α → β) (x : EStateM ε σ α) : EStateM ε σ β := fun s => match x s with | Result.ok a s => Result.ok (f a) s | Result.error e s => Result.error e s /-- The `seqRight` operation of the `EStateM` monad. -/ @[inline] protected def seqRight (x : EStateM ε σ α) (y : Unit → EStateM ε σ β) : EStateM ε σ β := fun s => match x s with | Result.ok _ s => y () s | Result.error e s => Result.error e s instance : Monad (EStateM ε σ) where bind := EStateM.bind pure := EStateM.pure map := EStateM.map seqRight := EStateM.seqRight instance {δ} [Backtrackable δ σ] : OrElse (EStateM ε σ α) where orElse := EStateM.orElse instance : MonadStateOf σ (EStateM ε σ) where set := EStateM.set get := EStateM.get modifyGet := EStateM.modifyGet instance {δ} [Backtrackable δ σ] : MonadExceptOf ε (EStateM ε σ) where throw := EStateM.throw tryCatch := EStateM.tryCatch /-- Execute an `EStateM` on initial state `s` to get a `Result`. -/ @[inline] def run (x : EStateM ε σ α) (s : σ) : Result ε σ α := x s /-- Execute an `EStateM` on initial state `s` for the returned value `α`. If the monadic action throws an exception, returns `none` instead. -/ @[inline] def run' (x : EStateM ε σ α) (s : σ) : Option α := match run x s with | Result.ok v _ => some v | Result.error .. => none /-- The `save` implementation for `Backtrackable PUnit σ`. -/ @[inline] def dummySave : σ → PUnit := fun _ => ⟨⟩ /-- The `restore` implementation for `Backtrackable PUnit σ`. -/ @[inline] def dummyRestore : σ → PUnit → σ := fun s _ => s /-- Dummy default instance. This makes every `σ` trivially "backtrackable" by doing nothing on backtrack. Because this is the first declared instance of `Backtrackable _ σ`, it will be picked only if there are no other `Backtrackable _ σ` instances registered. -/ instance nonBacktrackable : Backtrackable PUnit σ where save := dummySave restore := dummyRestore end EStateM /-- A class for types that can be hashed into a `UInt64`. -/ class Hashable (α : Sort u) where /-- Hashes the value `a : α` into a `UInt64`. -/ hash : α → UInt64 export Hashable (hash) /-- Converts a `UInt64` to a `USize` by reducing modulo `USize.size`. -/ @[extern "lean_uint64_to_usize"] opaque UInt64.toUSize (u : UInt64) : USize /-- Upcast a `USize` to a `UInt64`. This is lossless because `USize.size` is either `2^32` or `2^64`. This function is overridden with a native implementation. -/ @[extern "lean_usize_to_uint64"] def USize.toUInt64 (u : USize) : UInt64 where val := { val := u.val.val isLt := let ⟨n, h⟩ := u show LT.lt n _ from match USize.size, usize_size_eq, h with | _, Or.inl rfl, h => Nat.lt_trans h (by decide) | _, Or.inr rfl, h => h } /-- An opaque hash mixing operation, used to implement hashing for tuples. -/ @[extern "lean_uint64_mix_hash"] opaque mixHash (u₁ u₂ : UInt64) : UInt64 /-- A opaque string hash function. -/ @[extern "lean_string_hash"] protected opaque String.hash (s : @& String) : UInt64 instance : Hashable String where hash := String.hash namespace Lean /-- Hierarchical names. We use hierarchical names to name declarations and for creating unique identifiers for free variables and metavariables. You can create hierarchical names using the following quotation notation. ``` `Lean.Meta.whnf ``` It is short for `.str (.str (.str .anonymous "Lean") "Meta") "whnf"` You can use double quotes to request Lean to statically check whether the name corresponds to a Lean declaration in scope. ``` ``Lean.Meta.whnf ``` If the name is not in scope, Lean will report an error. -/ inductive Name where | /-- The "anonymous" name. -/ anonymous : Name | /-- A string name. The name `Lean.Meta.run` is represented at ```lean .str (.str (.str .anonymous "Lean") "Meta") "run" ``` -/ str (pre : Name) (str : String) | /-- A numerical name. This kind of name is used, for example, to create hierarchical names for free variables and metavariables. The identifier `_uniq.231` is represented as ```lean .num (.str .anonymous "_uniq") 231 ``` -/ num (pre : Name) (i : Nat) with /-- A hash function for names, which is stored inside the name itself as a computed field. -/ @[computedField] hash : Name → UInt64 | .anonymous => .ofNatCore 1723 (by decide) | .str p s => mixHash p.hash s.hash | .num p v => mixHash p.hash (dite (LT.lt v UInt64.size) (fun h => UInt64.ofNatCore v h) (fun _ => UInt64.ofNatCore 17 (by decide))) instance : Inhabited Name where default := Name.anonymous instance : Hashable Name where hash := Name.hash namespace Name /-- `.str p s` is now the preferred form. -/ @[export lean_name_mk_string] abbrev mkStr (p : Name) (s : String) : Name := Name.str p s /-- `.num p v` is now the preferred form. -/ @[export lean_name_mk_numeral] abbrev mkNum (p : Name) (v : Nat) : Name := Name.num p v /-- Short for `.str .anonymous s`. -/ abbrev mkSimple (s : String) : Name := mkStr Name.anonymous s /-- (Boolean) equality comparator for names. -/ @[extern "lean_name_eq"] protected def beq : (@& Name) → (@& Name) → Bool | anonymous, anonymous => true | str p₁ s₁, str p₂ s₂ => and (BEq.beq s₁ s₂) (Name.beq p₁ p₂) | num p₁ n₁, num p₂ n₂ => and (BEq.beq n₁ n₂) (Name.beq p₁ p₂) | _, _ => false instance : BEq Name where beq := Name.beq /-- Append two hierarchical names. Example: ```lean `Lean.Meta ++ `Tactic.simp ``` return `Lean.Meta.Tactic.simp` -/ protected def append : Name → Name → Name | n, anonymous => n | n, str p s => Name.mkStr (Name.append n p) s | n, num p d => Name.mkNum (Name.append n p) d instance : Append Name where append := Name.append end Name /-! # Syntax -/ /-- Source information of tokens. -/ inductive SourceInfo where | /-- Token from original input with whitespace and position information. `leading` will be inferred after parsing by `Syntax.updateLeading`. During parsing, it is not at all clear what the preceding token was, especially with backtracking. -/ original (leading : Substring) (pos : String.Pos) (trailing : Substring) (endPos : String.Pos) | /-- Synthesized syntax (e.g. from a quotation) annotated with a span from the original source. In the delaborator, we "misuse" this constructor to store synthetic positions identifying subterms. -/ synthetic (pos : String.Pos) (endPos : String.Pos) | /-- Synthesized token without position information. -/ protected none instance : Inhabited SourceInfo := ⟨SourceInfo.none⟩ namespace SourceInfo /-- Gets the position information from a `SourceInfo`, if available. If `originalOnly` is true, then `.synthetic` syntax will also return `none`. -/ def getPos? (info : SourceInfo) (originalOnly := false) : Option String.Pos := match info, originalOnly with | original (pos := pos) .., _ => some pos | synthetic (pos := pos) .., false => some pos | _, _ => none end SourceInfo /-- A `SyntaxNodeKind` classifies `Syntax.node` values. It is an abbreviation for `Name`, and you can use name literals to construct `SyntaxNodeKind`s, but they need not refer to declarations in the environment. Conventionally, a `SyntaxNodeKind` will correspond to the `Parser` or `ParserDesc` declaration that parses it. -/ abbrev SyntaxNodeKind := Name /-! # Syntax AST -/ /-- Syntax objects used by the parser, macro expander, delaborator, etc. -/ inductive Syntax where | /-- A `missing` syntax corresponds to a portion of the syntax tree that is missing because of a parse error. The indexing operator on Syntax also returns `missing` for indexing out of bounds. -/ missing : Syntax | /-- Node in the syntax tree. The `info` field is used by the delaborator to store the position of the subexpression corresponding to this node. The parser sets the `info` field to `none`. The parser sets the `info` field to `none`, with position retrieval continuing recursively. Nodes created by quotatons use the result from `SourceInfo.fromRef` so that they are marked as synthetic even when the leading/trailing token is not. The delaborator uses the `info` field to store the position of the subexpression corresponding to this node. (Remark: the `node` constructor did not have an `info` field in previous versions. This caused a bug in the interactive widgets, where the popup for `a + b` was the same as for `a`. The delaborator used to associate subexpressions with pretty-printed syntax by setting the (string) position of the first atom/identifier to the (expression) position of the subexpression. For example, both `a` and `a + b` have the same first identifier, and so their infos got mixed up.) -/ node (info : SourceInfo) (kind : SyntaxNodeKind) (args : Array Syntax) : Syntax | /-- An `atom` corresponds to a keyword or piece of literal unquoted syntax. These correspond to quoted strings inside `syntax` declarations. For example, in `(x + y)`, `"("`, `"+"` and `")"` are `atom` and `x` and `y` are `ident`. -/ atom (info : SourceInfo) (val : String) : Syntax | /-- An `ident` corresponds to an identifier as parsed by the `ident` or `rawIdent` parsers. * `rawVal` is the literal substring from the input file * `val` is the parsed identifier (with hygiene) * `preresolved` is the list of possible constants this could refer to -/ ident (info : SourceInfo) (rawVal : Substring) (val : Name) (preresolved : List (Prod Name (List String))) : Syntax /-- `SyntaxNodeKinds` is a set of `SyntaxNodeKind` (implemented as a list). -/ def SyntaxNodeKinds := List SyntaxNodeKind /-- A `Syntax` value of one of the given syntax kinds. Note that while syntax quotations produce/expect `TSyntax` values of the correct kinds, this is not otherwise enforced and can easily be circumvented by direct use of the constructor. The namespace `TSyntax.Compat` can be opened to expose a general coercion from `Syntax` to any `TSyntax ks` for porting older code. -/ structure TSyntax (ks : SyntaxNodeKinds) where /-- The underlying `Syntax` value. -/ raw : Syntax instance : Inhabited Syntax where default := Syntax.missing instance : Inhabited (TSyntax ks) where default := ⟨default⟩ /-! Builtin kinds -/ /-- The `choice` kind is used when a piece of syntax has multiple parses, and the determination of which to use is deferred until typing information is available. -/ abbrev choiceKind : SyntaxNodeKind := `choice /-- The null kind is used for raw list parsers like `many`. -/ abbrev nullKind : SyntaxNodeKind := `null /-- The `group` kind is by the `group` parser, to avoid confusing with the null kind when used inside `optional`. -/ abbrev groupKind : SyntaxNodeKind := `group /-- `ident` is not actually used as a node kind, but it is returned by `getKind` in the `ident` case so that things that handle different node kinds can also handle `ident`. -/ abbrev identKind : SyntaxNodeKind := `ident /-- `str` is the node kind of string literals like `"foo"`. -/ abbrev strLitKind : SyntaxNodeKind := `str /-- `char` is the node kind of character literals like `'A'`. -/ abbrev charLitKind : SyntaxNodeKind := `char /-- `num` is the node kind of number literals like `42`. -/ abbrev numLitKind : SyntaxNodeKind := `num /-- `scientific` is the node kind of floating point literals like `1.23e-3`. -/ abbrev scientificLitKind : SyntaxNodeKind := `scientific /-- `name` is the node kind of name literals like `` `foo ``. -/ abbrev nameLitKind : SyntaxNodeKind := `name /-- `fieldIdx` is the node kind of projection indices like the `2` in `x.2`. -/ abbrev fieldIdxKind : SyntaxNodeKind := `fieldIdx /-- `interpolatedStrLitKind` is the node kind of interpolated string literal fragments like `"value = {` and `}"` in `s!"value = {x}"`. -/ abbrev interpolatedStrLitKind : SyntaxNodeKind := `interpolatedStrLitKind /-- `interpolatedStrKind` is the node kind of an interpolated string literal like `"value = {x}"` in `s!"value = {x}"`. -/ abbrev interpolatedStrKind : SyntaxNodeKind := `interpolatedStrKind namespace Syntax /-- Gets the kind of a `Syntax` node. For non-`node` syntax, we use "pseudo kinds": `identKind` for `ident`, `missing` for `missing`, and the atom's string literal for atoms. -/ def getKind (stx : Syntax) : SyntaxNodeKind := match stx with | Syntax.node _ k _ => k -- We use these "pseudo kinds" for antiquotation kinds. -- For example, an antiquotation `$id:ident` (using Lean.Parser.Term.ident) -- is compiled to ``if stx.isOfKind `ident ...`` | Syntax.missing => `missing | Syntax.atom _ v => Name.mkSimple v | Syntax.ident .. => identKind /-- Changes the kind at the root of a `Syntax` node to `k`. Does nothing for non-`node` nodes. -/ def setKind (stx : Syntax) (k : SyntaxNodeKind) : Syntax := match stx with | Syntax.node info _ args => Syntax.node info k args | _ => stx /-- Is this a syntax with node kind `k`? -/ def isOfKind (stx : Syntax) (k : SyntaxNodeKind) : Bool := beq stx.getKind k /-- Gets the `i`'th argument of the syntax node. This can also be written `stx[i]`. Returns `missing` if `i` is out of range. -/ def getArg (stx : Syntax) (i : Nat) : Syntax := match stx with | Syntax.node _ _ args => args.getD i Syntax.missing | _ => Syntax.missing instance : GetElem Syntax Nat Syntax fun _ _ => True where getElem stx i _ := stx.getArg i /-- Gets the list of arguments of the syntax node, or `#[]` if it's not a `node`. -/ def getArgs (stx : Syntax) : Array Syntax := match stx with | Syntax.node _ _ args => args | _ => Array.empty /-- Gets the number of arguments of the syntax node, or `0` if it's not a `node`. -/ def getNumArgs (stx : Syntax) : Nat := match stx with | Syntax.node _ _ args => args.size | _ => 0 /-- Assuming `stx` was parsed by `optional`, returns the enclosed syntax if it parsed something and `none` otherwise. -/ def getOptional? (stx : Syntax) : Option Syntax := match stx with | Syntax.node _ k args => match and (beq k nullKind) (beq args.size 1) with | true => some (args.get! 0) | false => none | _ => none /-- Is this syntax `.missing`? -/ def isMissing : Syntax → Bool | Syntax.missing => true | _ => false /-- Is this syntax a `node` with kind `k`? -/ def isNodeOf (stx : Syntax) (k : SyntaxNodeKind) (n : Nat) : Bool := and (stx.isOfKind k) (beq stx.getNumArgs n) /-- `stx.isIdent` is `true` iff `stx` is an identifier. -/ def isIdent : Syntax → Bool | ident .. => true | _ => false /-- If this is a `ident`, return the parsed value, else `.anonymous`. -/ def getId : Syntax → Name | ident _ _ val _ => val | _ => Name.anonymous /-- Updates the argument list without changing the node kind. Does nothing for non-`node` nodes. -/ def setArgs (stx : Syntax) (args : Array Syntax) : Syntax := match stx with | node info k _ => node info k args | stx => stx /-- Updates the `i`'th argument of the syntax. Does nothing for non-`node` nodes, or if `i` is out of bounds of the node list. -/ def setArg (stx : Syntax) (i : Nat) (arg : Syntax) : Syntax := match stx with | node info k args => node info k (args.setD i arg) | stx => stx /-- Retrieve the left-most node or leaf's info in the Syntax tree. -/ partial def getHeadInfo? : Syntax → Option SourceInfo | atom info _ => some info | ident info .. => some info | node SourceInfo.none _ args => let rec loop (i : Nat) : Option SourceInfo := match decide (LT.lt i args.size) with | true => match getHeadInfo? (args.get! i) with | some info => some info | none => loop (hAdd i 1) | false => none loop 0 | node info _ _ => some info | _ => none /-- Retrieve the left-most leaf's info in the Syntax tree, or `none` if there is no token. -/ partial def getHeadInfo (stx : Syntax) : SourceInfo := match stx.getHeadInfo? with | some info => info | none => SourceInfo.none /-- Get the starting position of the syntax, if possible. If `originalOnly` is true, `synthetic` nodes are treated as not carrying position information. -/ def getPos? (stx : Syntax) (originalOnly := false) : Option String.Pos := stx.getHeadInfo.getPos? originalOnly /-- Get the ending position of the syntax, if possible. If `originalOnly` is true, `synthetic` nodes are treated as not carrying position information. -/ partial def getTailPos? (stx : Syntax) (originalOnly := false) : Option String.Pos := match stx, originalOnly with | atom (SourceInfo.original (endPos := pos) ..) .., _ => some pos | atom (SourceInfo.synthetic (endPos := pos) ..) _, false => some pos | ident (SourceInfo.original (endPos := pos) ..) .., _ => some pos | ident (SourceInfo.synthetic (endPos := pos) ..) .., false => some pos | node (SourceInfo.original (endPos := pos) ..) .., _ => some pos | node (SourceInfo.synthetic (endPos := pos) ..) .., false => some pos | node _ _ args, _ => let rec loop (i : Nat) : Option String.Pos := match decide (LT.lt i args.size) with | true => match getTailPos? (args.get! ((args.size.sub i).sub 1)) originalOnly with | some info => some info | none => loop (hAdd i 1) | false => none loop 0 | _, _ => none /-- An array of syntax elements interspersed with separators. Can be coerced to/from `Array Syntax` to automatically remove/insert the separators. -/ structure SepArray (sep : String) where /-- The array of elements and separators, ordered like `#[el1, sep1, el2, sep2, el3]`. -/ elemsAndSeps : Array Syntax /-- A typed version of `SepArray`. -/ structure TSepArray (ks : SyntaxNodeKinds) (sep : String) where /-- The array of elements and separators, ordered like `#[el1, sep1, el2, sep2, el3]`. -/ elemsAndSeps : Array Syntax end Syntax /-- An array of syntaxes of kind `ks`. -/ abbrev TSyntaxArray (ks : SyntaxNodeKinds) := Array (TSyntax ks) /-- Implementation of `TSyntaxArray.raw`. -/ unsafe def TSyntaxArray.rawImpl : TSyntaxArray ks → Array Syntax := unsafeCast /-- Converts a `TSyntaxArray` to an `Array Syntax`, without reallocation. -/ @[implementedBy TSyntaxArray.rawImpl] opaque TSyntaxArray.raw (as : TSyntaxArray ks) : Array Syntax := Array.empty /-- Implementation of `TSyntaxArray.mk`. -/ unsafe def TSyntaxArray.mkImpl : Array Syntax → TSyntaxArray ks := unsafeCast /-- Converts an `Array Syntax` to a `TSyntaxArray`, without reallocation. -/ @[implementedBy TSyntaxArray.mkImpl] opaque TSyntaxArray.mk (as : Array Syntax) : TSyntaxArray ks := Array.empty /-- Constructs a synthetic `SourceInfo` using a `ref : Syntax` for the span. -/ def SourceInfo.fromRef (ref : Syntax) : SourceInfo := match ref.getPos?, ref.getTailPos? with | some pos, some tailPos => SourceInfo.synthetic pos tailPos | _, _ => SourceInfo.none /-- Constructs a synthetic `atom` with no source info. -/ def mkAtom (val : String) : Syntax := Syntax.atom SourceInfo.none val /-- Constructs a synthetic `atom` with source info coming from `src`. -/ def mkAtomFrom (src : Syntax) (val : String) : Syntax := Syntax.atom (SourceInfo.fromRef src) val /-! # Parser descriptions -/ /-- A `ParserDescr` is a grammar for parsers. This is used by the `syntax` command to produce parsers without having to `import Lean`. -/ inductive ParserDescr where | /-- A (named) nullary parser, like `ppSpace` -/ const (name : Name) | /-- A (named) unary parser, like `group(p)` -/ unary (name : Name) (p : ParserDescr) | /-- A (named) binary parser, like `orelse` or `andthen` (written as `p1 <|> p2` and `p1 p2` respectively in `syntax`) -/ binary (name : Name) (p₁ p₂ : ParserDescr) | /-- Parses using `p`, then pops the stack to create a new node with kind `kind`. The precedence `prec` is used to determine whether the parser should apply given the current precedence level. -/ node (kind : SyntaxNodeKind) (prec : Nat) (p : ParserDescr) | /-- Like `node` but for trailing parsers (which start with a nonterminal). Assumes the lhs is already on the stack, and parses using `p`, then pops the stack including the lhs to create a new node with kind `kind`. The precedence `prec` and `lhsPrec` are used to determine whether the parser should apply. -/ trailingNode (kind : SyntaxNodeKind) (prec lhsPrec : Nat) (p : ParserDescr) | /-- A literal symbol parser: parses `val` as a literal. This parser does not work on identifiers, so `symbol` arguments are declared as "keywords" and cannot be used as identifiers anywhere in the file. -/ symbol (val : String) | /-- Like `symbol`, but without reserving `val` as a keyword. If `includeIdent` is true then `ident` will be reinterpreted as `atom` if it matches. -/ nonReservedSymbol (val : String) (includeIdent : Bool) | /-- Parses using the category parser `catName` with right binding power (i.e. precedence) `rbp`. -/ cat (catName : Name) (rbp : Nat) | /-- Parses using another parser `declName`, which can be either a `Parser` or `ParserDescr`. -/ parser (declName : Name) | /-- Like `node`, but also declares that the body can be matched using an antiquotation with name `name`. For example, `def $id:declId := 1` uses an antiquotation with name `declId` in the place where a `declId` is expected. -/ nodeWithAntiquot (name : String) (kind : SyntaxNodeKind) (p : ParserDescr) | /-- A `sepBy(p, sep)` parses 0 or more occurrences of `p` separated by `sep`. `psep` is usually the same as `symbol sep`, but it can be overridden. `sep` is only used in the antiquot syntax: `$x;*` would match if `sep` is `";"`. `allowTrailingSep` is true if e.g. `a, b,` is also allowed to match. -/ sepBy (p : ParserDescr) (sep : String) (psep : ParserDescr) (allowTrailingSep : Bool := false) | /-- `sepBy1` is just like `sepBy`, except it takes 1 or more instead of 0 or more occurrences of `p`. -/ sepBy1 (p : ParserDescr) (sep : String) (psep : ParserDescr) (allowTrailingSep : Bool := false) instance : Inhabited ParserDescr where default := ParserDescr.symbol "" /-- Although `TrailingParserDescr` is an abbreviation for `ParserDescr`, Lean will look at the declared type in order to determine whether to add the parser to the leading or trailing parser table. The determination is done automatically by the `syntax` command. -/ abbrev TrailingParserDescr := ParserDescr /-! Runtime support for making quotation terms auto-hygienic, by mangling identifiers introduced by them with a "macro scope" supplied by the context. Details to appear in a paper soon. -/ /-- A macro scope identifier is just a `Nat` that gets bumped every time we enter a new macro scope. Within a macro scope, all occurrences of identifier `x` parse to the same thing, but `x` parsed from different macro scopes will produce different identifiers. -/ abbrev MacroScope := Nat /-- Macro scope used internally. It is not available for our frontend. -/ def reservedMacroScope := 0 /-- First macro scope available for our frontend -/ def firstFrontendMacroScope := hAdd reservedMacroScope 1 /-- A `MonadRef` is a monad that has a `ref : Syntax` in the read-only state. This is used to keep track of the location where we are working; if an exception is thrown, the `ref` gives the location where the error will be reported, assuming no more specific location is provided. -/ class MonadRef (m : Type → Type) where /-- Get the current value of the `ref` -/ getRef : m Syntax /-- Run `x : m α` with a modified value for the `ref` -/ withRef {α} : Syntax → m α → m α export MonadRef (getRef) instance (m n : Type → Type) [MonadLift m n] [MonadFunctor m n] [MonadRef m] : MonadRef n where getRef := liftM (getRef : m _) withRef ref x := monadMap (m := m) (MonadRef.withRef ref) x /-- Replaces `oldRef` with `ref`, unless `ref` has no position info. This biases us to having a valid span to report an error on. -/ def replaceRef (ref : Syntax) (oldRef : Syntax) : Syntax := match ref.getPos? with | some _ => ref | _ => oldRef /-- Run `x : m α` with a modified value for the `ref`. This is not exactly the same as `MonadRef.withRef`, because it uses `replaceRef` to avoid putting syntax with bad spans in the state. -/ @[inline] def withRef {m : Type → Type} [Monad m] [MonadRef m] {α} (ref : Syntax) (x : m α) : m α := bind getRef fun oldRef => let ref := replaceRef ref oldRef MonadRef.withRef ref x /-- A monad that supports syntax quotations. Syntax quotations (in term position) are monadic values that when executed retrieve the current "macro scope" from the monad and apply it to every identifier they introduce (independent of whether this identifier turns out to be a reference to an existing declaration, or an actually fresh binding during further elaboration). We also apply the position of the result of `getRef` to each introduced symbol, which results in better error positions than not applying any position. -/ class MonadQuotation (m : Type → Type) extends MonadRef m where /-- Get the fresh scope of the current macro invocation -/ getCurrMacroScope : m MacroScope /-- Get the module name of the current file. This is used to ensure that hygienic names don't clash across multiple files. -/ getMainModule : m Name /-- Execute action in a new macro invocation context. This transformer should be used at all places that morally qualify as the beginning of a "macro call", e.g. `elabCommand` and `elabTerm` in the case of the elaborator. However, it can also be used internally inside a "macro" if identifiers introduced by e.g. different recursive calls should be independent and not collide. While returning an intermediate syntax tree that will recursively be expanded by the elaborator can be used for the same effect, doing direct recursion inside the macro guarded by this transformer is often easier because one is not restricted to passing a single syntax tree. Modelling this helper as a transformer and not just a monadic action ensures that the current macro scope before the recursive call is restored after it, as expected. -/ withFreshMacroScope {α : Type} : m α → m α export MonadQuotation (getCurrMacroScope getMainModule withFreshMacroScope) /-- Construct a synthetic `SourceInfo` from the `ref` in the monad state. -/ def MonadRef.mkInfoFromRefPos [Monad m] [MonadRef m] : m SourceInfo := return SourceInfo.fromRef (← getRef) instance {m n : Type → Type} [MonadFunctor m n] [MonadLift m n] [MonadQuotation m] : MonadQuotation n where getCurrMacroScope := liftM (m := m) getCurrMacroScope getMainModule := liftM (m := m) getMainModule withFreshMacroScope := monadMap (m := m) withFreshMacroScope /-! We represent a name with macro scopes as ``` <actual name>._@.(<module_name>.<scopes>)*.<module_name>._hyg.<scopes> ``` Example: suppose the module name is `Init.Data.List.Basic`, and name is `foo.bla`, and macroscopes [2, 5] ``` foo.bla._@.Init.Data.List.Basic._hyg.2.5 ``` We may have to combine scopes from different files/modules. The main modules being processed is always the right most one. This situation may happen when we execute a macro generated in an imported file in the current file. ``` foo.bla._@.Init.Data.List.Basic.2.1.Init.Lean.Expr._hyg.4 ``` The delimiter `_hyg` is used just to improve the `hasMacroScopes` performance. -/ /-- Does this name have hygienic macro scopes? -/ def Name.hasMacroScopes : Name → Bool | str _ s => beq s "_hyg" | num p _ => hasMacroScopes p | _ => false private def eraseMacroScopesAux : Name → Name | .str p s => match beq s "_@" with | true => p | false => eraseMacroScopesAux p | .num p _ => eraseMacroScopesAux p | .anonymous => Name.anonymous /-- Remove the macro scopes from the name. -/ @[export lean_erase_macro_scopes] def Name.eraseMacroScopes (n : Name) : Name := match n.hasMacroScopes with | true => eraseMacroScopesAux n | false => n private def simpMacroScopesAux : Name → Name | .num p i => Name.mkNum (simpMacroScopesAux p) i | n => eraseMacroScopesAux n /-- Helper function we use to create binder names that do not need to be unique. -/ @[export lean_simp_macro_scopes] def Name.simpMacroScopes (n : Name) : Name := match n.hasMacroScopes with | true => simpMacroScopesAux n | false => n /-- A `MacroScopesView` represents a parsed hygienic name. `extractMacroScopes` will decode it from a `Name`, and `.review` will re-encode it. The grammar of a hygienic name is: ``` <name>._@.(<module_name>.<scopes>)*.<mainModule>._hyg.<scopes> ``` -/ structure MacroScopesView where /-- The original (unhygienic) name. -/ name : Name /-- All the name components `(<module_name>.<scopes>)*` from the imports concatenated together. -/ imported : Name /-- The main module in which this identifier was parsed. -/ mainModule : Name /-- The list of macro scopes. -/ scopes : List MacroScope instance : Inhabited MacroScopesView where default := ⟨default, default, default, default⟩ /-- Encode a hygienic name from the parsed pieces. -/ def MacroScopesView.review (view : MacroScopesView) : Name := match view.scopes with | List.nil => view.name | List.cons _ _ => let base := (Name.mkStr (hAppend (hAppend (Name.mkStr view.name "_@") view.imported) view.mainModule) "_hyg") view.scopes.foldl Name.mkNum base private def assembleParts : List Name → Name → Name | .nil, acc => acc | .cons (.str _ s) ps, acc => assembleParts ps (Name.mkStr acc s) | .cons (.num _ n) ps, acc => assembleParts ps (Name.mkNum acc n) | _, _ => panic "Error: unreachable @ assembleParts" private def extractImported (scps : List MacroScope) (mainModule : Name) : Name → List Name → MacroScopesView | n@(Name.str p str), parts => match beq str "_@" with | true => { name := p, mainModule := mainModule, imported := assembleParts parts Name.anonymous, scopes := scps } | false => extractImported scps mainModule p (List.cons n parts) | n@(Name.num p _), parts => extractImported scps mainModule p (List.cons n parts) | _, _ => panic "Error: unreachable @ extractImported" private def extractMainModule (scps : List MacroScope) : Name → List Name → MacroScopesView | n@(Name.str p str), parts => match beq str "_@" with | true => { name := p, mainModule := assembleParts parts Name.anonymous, imported := Name.anonymous, scopes := scps } | false => extractMainModule scps p (List.cons n parts) | n@(Name.num _ _), acc => extractImported scps (assembleParts acc Name.anonymous) n List.nil | _, _ => panic "Error: unreachable @ extractMainModule" private def extractMacroScopesAux : Name → List MacroScope → MacroScopesView | Name.num p scp, acc => extractMacroScopesAux p (List.cons scp acc) | Name.str p _ , acc => extractMainModule acc p List.nil -- str must be "_hyg" | _, _ => panic "Error: unreachable @ extractMacroScopesAux" /-- Revert all `addMacroScope` calls. `v = extractMacroScopes n → n = v.review`. This operation is useful for analyzing/transforming the original identifiers, then adding back the scopes (via `MacroScopesView.review`). -/ def extractMacroScopes (n : Name) : MacroScopesView := match n.hasMacroScopes with | true => extractMacroScopesAux n List.nil | false => { name := n, scopes := List.nil, imported := Name.anonymous, mainModule := Name.anonymous } /-- Add a new macro scope onto the name `n`, in the given `mainModule`. -/ def addMacroScope (mainModule : Name) (n : Name) (scp : MacroScope) : Name := match n.hasMacroScopes with | true => let view := extractMacroScopes n match beq view.mainModule mainModule with | true => Name.mkNum n scp | false => { view with imported := view.scopes.foldl Name.mkNum (hAppend view.imported view.mainModule) mainModule := mainModule scopes := List.cons scp List.nil }.review | false => Name.mkNum (Name.mkStr (hAppend (Name.mkStr n "_@") mainModule) "_hyg") scp /-- Add a new macro scope onto the name `n`, using the monad state to supply the main module and current macro scope. -/ @[inline] def MonadQuotation.addMacroScope {m : Type → Type} [MonadQuotation m] [Monad m] (n : Name) : m Name := bind getMainModule fun mainModule => bind getCurrMacroScope fun scp => pure (Lean.addMacroScope mainModule n scp) /-- The default maximum recursion depth. This is adjustable using the `maxRecDepth` option. -/ def defaultMaxRecDepth := 512 /-- The message to display on stack overflow. -/ def maxRecDepthErrorMessage : String := "maximum recursion depth has been reached (use `set_option maxRecDepth <num>` to increase limit)" namespace Syntax /-- Is this syntax a null `node`? -/ def matchesNull (stx : Syntax) (n : Nat) : Bool := stx.isNodeOf nullKind n /-- Function used for determining whether a syntax pattern `` `(id) `` is matched. There are various conceivable notions of when two syntactic identifiers should be regarded as identical, but semantic definitions like whether they refer to the same global name cannot be implemented without context information (i.e. `MonadResolveName`). Thus in patterns we default to the structural solution of comparing the identifiers' `Name` values, though we at least do so modulo macro scopes so that identifiers that "look" the same match. This is particularly useful when dealing with identifiers that do not actually refer to Lean bindings, e.g. in the `stx` pattern `` `(many($p)) ``. -/ def matchesIdent (stx : Syntax) (id : Name) : Bool := and stx.isIdent (beq stx.getId.eraseMacroScopes id.eraseMacroScopes) /-- Is this syntax a node kind `k` wrapping an `atom _ val`? -/ def matchesLit (stx : Syntax) (k : SyntaxNodeKind) (val : String) : Bool := match stx with | Syntax.node _ k' args => and (beq k k') (match args.getD 0 Syntax.missing with | Syntax.atom _ val' => beq val val' | _ => false) | _ => false end Syntax namespace Macro /-- References -/ private opaque MethodsRefPointed : NonemptyType.{0} private def MethodsRef : Type := MethodsRefPointed.type instance : Nonempty MethodsRef := MethodsRefPointed.property /-- The read-only context for the `MacroM` monad. -/ structure Context where /-- An opaque reference to the `Methods` object. This is done to break a dependency cycle: the `Methods` involve `MacroM` which has not been defined yet. -/ methods : MethodsRef /-- The currently parsing module. -/ mainModule : Name /-- The current macro scope. -/ currMacroScope : MacroScope /-- The current recursion depth. -/ currRecDepth : Nat := 0 /-- The maximum recursion depth. -/ maxRecDepth : Nat := defaultMaxRecDepth /-- The syntax which supplies the position of error messages. -/ ref : Syntax /-- An exception in the `MacroM` monad. -/ inductive Exception where | /-- A general error, given a message and a span (expressed as a `Syntax`). -/ error : Syntax → String → Exception | /-- An unsupported syntax exception. We keep this separate because it is used for control flow: if one macro does not support a syntax then we try the next one. -/ unsupportedSyntax : Exception /-- The mutable state for the `MacroM` monad. -/ structure State where /-- The global macro scope counter, used for producing fresh scope names. -/ macroScope : MacroScope /-- The list of trace messages that have been produced, each with a trace class and a message. -/ traceMsgs : List (Prod Name String) := List.nil deriving Inhabited end Macro /-- The `MacroM` monad is the main monad for macro expansion. It has the information needed to handle hygienic name generation, and is the monad that `macro` definitions live in. Notably, this is a (relatively) pure monad: there is no `IO` and no access to the `Environment`. That means that things like declaration lookup are impossible here, as well as `IO.Ref` or other side-effecting operations. For more capabilities, macros can instead be written as `elab` using `adaptExpander`. -/ abbrev MacroM := ReaderT Macro.Context (EStateM Macro.Exception Macro.State) /-- A `macro` has type `Macro`, which is a `Syntax → MacroM Syntax`: it receives an input syntax and is supposed to "expand" it into another piece of syntax. -/ abbrev Macro := Syntax → MacroM Syntax namespace Macro instance : MonadRef MacroM where getRef := bind read fun ctx => pure ctx.ref withRef := fun ref x => withReader (fun ctx => { ctx with ref := ref }) x /-- Add a new macro scope to the name `n`. -/ def addMacroScope (n : Name) : MacroM Name := bind read fun ctx => pure (Lean.addMacroScope ctx.mainModule n ctx.currMacroScope) /-- Throw an `unsupportedSyntax` exception. -/ def throwUnsupported {α} : MacroM α := throw Exception.unsupportedSyntax /-- Throw a error with the given message, using the `ref` for the location information. -/ def throwError {α} (msg : String) : MacroM α := bind getRef fun ref => throw (Exception.error ref msg) /-- Throw a error with the given message and location information. -/ def throwErrorAt {α} (ref : Syntax) (msg : String) : MacroM α := withRef ref (throwError msg) /-- Increments the macro scope counter so that inside the body of `x` the macro scope is fresh. -/ @[inline] protected def withFreshMacroScope {α} (x : MacroM α) : MacroM α := bind (modifyGet (fun s => (s.macroScope, { s with macroScope := hAdd s.macroScope 1 }))) fun fresh => withReader (fun ctx => { ctx with currMacroScope := fresh }) x /-- Run `x` with an incremented recursion depth counter. -/ @[inline] def withIncRecDepth {α} (ref : Syntax) (x : MacroM α) : MacroM α := bind read fun ctx => match beq ctx.currRecDepth ctx.maxRecDepth with | true => throw (Exception.error ref maxRecDepthErrorMessage) | false => withReader (fun ctx => { ctx with currRecDepth := hAdd ctx.currRecDepth 1 }) x instance : MonadQuotation MacroM where getCurrMacroScope ctx := pure ctx.currMacroScope getMainModule ctx := pure ctx.mainModule withFreshMacroScope := Macro.withFreshMacroScope /-- The opaque methods that are available to `MacroM`. -/ structure Methods where /-- Expands macros in the given syntax. A return value of `none` means there was nothing to expand. -/ expandMacro? : Syntax → MacroM (Option Syntax) /-- Get the current namespace in the file. -/ getCurrNamespace : MacroM Name /-- Check if a given name refers to a declaration. -/ hasDecl : Name → MacroM Bool /-- Resolves the given name to an overload list of namespaces. -/ resolveNamespace : Name → MacroM (List Name) /-- Resolves the given name to a overload list of global definitions. The `List String` in each alternative is the deduced list of projections (which are ambiguous with name components). -/ resolveGlobalName : Name → MacroM (List (Prod Name (List String))) deriving Inhabited /-- Implementation of `mkMethods`. -/ unsafe def mkMethodsImp (methods : Methods) : MethodsRef := unsafeCast methods /-- Make an opaque reference to a `Methods`. -/ @[implementedBy mkMethodsImp] opaque mkMethods (methods : Methods) : MethodsRef instance : Inhabited MethodsRef where default := mkMethods default /-- Implementation of `getMethods`. -/ unsafe def getMethodsImp : MacroM Methods := bind read fun ctx => pure (unsafeCast (ctx.methods)) /-- Extract the methods list from the `MacroM` state. -/ @[implementedBy getMethodsImp] opaque getMethods : MacroM Methods /-- `expandMacro? stx` returns `some stxNew` if `stx` is a macro, and `stxNew` is its expansion. -/ def expandMacro? (stx : Syntax) : MacroM (Option Syntax) := do (← getMethods).expandMacro? stx /-- Returns `true` if the environment contains a declaration with name `declName` -/ def hasDecl (declName : Name) : MacroM Bool := do (← getMethods).hasDecl declName /-- Gets the current namespace given the position in the file. -/ def getCurrNamespace : MacroM Name := do (← getMethods).getCurrNamespace /-- Resolves the given name to an overload list of namespaces. -/ def resolveNamespace (n : Name) : MacroM (List Name) := do (← getMethods).resolveNamespace n /-- Resolves the given name to a overload list of global definitions. The `List String` in each alternative is the deduced list of projections (which are ambiguous with name components). -/ def resolveGlobalName (n : Name) : MacroM (List (Prod Name (List String))) := do (← getMethods).resolveGlobalName n /-- Add a new trace message, with the given trace class and message. -/ def trace (clsName : Name) (msg : String) : MacroM Unit := do modify fun s => { s with traceMsgs := List.cons (Prod.mk clsName msg) s.traceMsgs } end Macro export Macro (expandMacro?) namespace PrettyPrinter /-- The unexpander monad, essentially `Syntax → Option α`. The `Syntax` is the `ref`, and it has the possibility of failure without an error message. -/ abbrev UnexpandM := ReaderT Syntax (EStateM Unit Unit) /-- Function that tries to reverse macro expansions as a post-processing step of delaboration. While less general than an arbitrary delaborator, it can be declared without importing `Lean`. Used by the `[appUnexpander]` attribute. -/ -- a `kindUnexpander` could reasonably be added later abbrev Unexpander := Syntax → UnexpandM Syntax instance : MonadQuotation UnexpandM where getRef := read withRef ref x := withReader (fun _ => ref) x -- unexpanders should not need to introduce new names getCurrMacroScope := pure 0 getMainModule := pure `_fakeMod withFreshMacroScope := id end PrettyPrinter end Lean
c9fe8b207a72d08b850d8c68a3e8ee83f897416d
2d041ea7f2e9b29093ffd7c99b11decfaa8b20ca
/ch7.lean
99a84e037b5005a58c96221392d960bb99123c3b
[]
no_license
0xpr/lean_tutorial
1a66577602baa9a52c2b01130b9d70089653ea37
56ef609d8df9e392916012db5354bf182cbbb8d8
refs/heads/master
1,606,955,421,810
1,499,014,388,000
1,499,014,388,000
96,036,899
1
0
null
null
null
null
UTF-8
Lean
false
false
1,531
lean
open nat inductive vector (A : Type) : nat → Type := | nil {} : vector A zero | cons : Π {n}, A → vector A n → vector A (succ n) open vector notation h :: t := cons h t -- defining map with only recursors definition head_aux {A : Type} {m n : nat} (v : vector A m) : (m = succ n) → A := vector.cases_on v (assume H : 0 = succ n, nat.no_confusion H) (λ c a tv, (assume H : succ c = succ n, a)) definition head {A : Type} : Π {n}, vector A (succ n) → A := (λ n v, head_aux v rfl) definition tail_aux {A : Type} {n m : nat} (v : vector A m) : m = succ n → vector A n := vector.cases_on v (assume H : 0 = succ n, nat.no_confusion H) (take m (a : A) w : vector A m, assume H : succ m = succ n, have H1 : m = n, from (nat.no_confusion H) (fun e : m = n, e), eq.rec_on H1 w) definition tail {A : Type} {n : nat} (v : vector A (succ n)) : vector A n := tail_aux v rfl -- defining map without recursors -- we can use head and tail (the tail example is already covered in the book, -- so we only have to worry about head) definition map {A B C : Type} (f : A → B → C) : Π {n : nat}, vector A n → vector B n → vector C n := (λ n : nat, nat.rec (λ vecA vecB, nil) (λ n tf, (λ vecA vecB, have ele_a : A, from head vecA, have ele_b : B, from head vecB, have tl_a : vector A n, from tail vecA, have tl_b : vector B n, from tail vecB, f ele_a ele_b :: tf tl_a tl_b)) n)
c45df07223140e29f2c413d91352f930624adbd9
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/expr.lean
89641583e33bdc49de43ef834762de9e39b5feb8
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
1,852
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 /-! ### Helpers to invoke functions involving algebra at tactic time > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. It's not clear whether using `instance_cache` is a sensible choice here. In particular, we need to use these tactics below when the algebraic instances are local variables that aren't in the "real" instance cache (the one used by `tactic.reset_instance_cache`). -/ namespace expr /-- Produce a `has_one` instance for the type cached by `t`, such that `1 : expr` is the one of that type. -/ meta def has_one (t : tactic.instance_cache) : tactic (tactic.instance_cache × has_one expr) := do (t, one) ← t.mk_app `has_one.one [], pure (t, { one := one }) /-- Produce a `has_zero` instance for the type cached by `t`, such that `0 : expr` is the zero of that type. -/ meta def has_zero (t : tactic.instance_cache) : tactic (tactic.instance_cache × has_zero expr) := do (t, zero) ← t.mk_app `has_zero.zero [], pure (t, { zero := zero }) /-- Produce a `has_mul` instance for the type cached by `t`, such that `(*) : expr → expr → expr` is the multiplication of that type. -/ meta def has_mul (t : tactic.instance_cache) : tactic (tactic.instance_cache × has_mul expr) := do (t, mul) ← t.mk_app `has_mul.mul [], pure (t, { mul := λ a b, mul a b }) /-- Produce a `has_add` instance for the type cached by `t`, such that `(+) : expr → expr → expr` is the addition of that type. -/ meta def has_add (t : tactic.instance_cache) : tactic (tactic.instance_cache × has_add expr) := do (t, add) ← t.mk_app `has_add.add [], pure (t, { add := λ a b, add a b }) end expr
a60056133b13ffc5bc4af634a35407f49307ca4b
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/topology/instances/real.lean
83c48ab7714cd0e24421825eaa04b8adb2360470
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
18,751
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 The real numbers ℝ. They are constructed as the topological completion of ℚ. With the following steps: (1) prove that ℚ forms a uniform space. (2) subtraction and addition are uniform continuous functions in this space (3) for multiplication and inverse this only holds on bounded subsets (4) ℝ is defined as separated Cauchy filters over ℚ (the separation requires a quotient construction) (5) extend the uniform continuous functions along the completion (6) proof field properties using the principle of extension of identities TODO generalizations: * topological groups & rings * order topologies * Archimedean fields -/ import topology.metric_space.basic topology.algebra.uniform_group topology.algebra.ring tactic.linarith noncomputable theory open classical set lattice filter topological_space metric local attribute [instance] prop_decidable universes u v w variables {α : Type u} {β : Type v} {γ : Type w} instance : metric_space ℚ := metric_space.induced coe rat.cast_injective real.metric_space theorem rat.dist_eq (x y : ℚ) : dist x y = abs (x - y) := rfl instance : metric_space ℤ := begin letI M := metric_space.induced coe int.cast_injective real.metric_space, refine @metric_space.replace_uniformity _ int.uniform_space M (le_antisymm refl_le_uniformity $ λ r ru, mem_uniformity_dist.2 ⟨1, zero_lt_one, λ a b h, mem_principal_sets.1 ru $ dist_le_zero.1 (_ : (abs (a - b) : ℝ) ≤ 0)⟩), simpa using (@int.cast_le ℝ _ _ 0).2 (int.lt_add_one_iff.1 $ (@int.cast_lt ℝ _ (abs (a - b)) 1).1 $ by simpa using h) end theorem uniform_continuous_of_rat : uniform_continuous (coe : ℚ → ℝ) := uniform_continuous_comap theorem uniform_embedding_of_rat : uniform_embedding (coe : ℚ → ℝ) := uniform_embedding_comap rat.cast_injective theorem dense_embedding_of_rat : dense_embedding (coe : ℚ → ℝ) := uniform_embedding_of_rat.dense_embedding $ λ x, mem_closure_iff_nhds.2 $ λ t ht, let ⟨ε,ε0, hε⟩ := mem_nhds_iff.1 ht in let ⟨q, h⟩ := exists_rat_near x ε0 in ne_empty_iff_exists_mem.2 ⟨_, hε (mem_ball'.2 h), q, rfl⟩ theorem embedding_of_rat : embedding (coe : ℚ → ℝ) := dense_embedding_of_rat.to_embedding theorem continuous_of_rat : continuous (coe : ℚ → ℝ) := uniform_continuous_of_rat.continuous theorem real.uniform_continuous_add : uniform_continuous (λp : ℝ × ℝ, p.1 + p.2) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_add_continuous_lemma abs ε0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ h₁ h₂⟩ -- TODO(Mario): Find a way to use rat_add_continuous_lemma theorem rat.uniform_continuous_add : uniform_continuous (λp : ℚ × ℚ, p.1 + p.2) := uniform_embedding_of_rat.to_uniform_inducing.uniform_continuous_iff.2 $ by simp [(∘)]; exact real.uniform_continuous_add.comp ((uniform_continuous_of_rat.comp uniform_continuous_fst).prod_mk (uniform_continuous_of_rat.comp uniform_continuous_snd)) theorem real.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℝ _) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [real.dist_eq] using h⟩ theorem rat.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℚ _) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [rat.dist_eq] using h⟩ instance : uniform_add_group ℝ := uniform_add_group.mk' real.uniform_continuous_add real.uniform_continuous_neg instance : uniform_add_group ℚ := uniform_add_group.mk' rat.uniform_continuous_add rat.uniform_continuous_neg instance : topological_add_group ℝ := by apply_instance instance : topological_add_group ℚ := by apply_instance instance : orderable_topology ℚ := induced_orderable_topology _ (λ x y, rat.cast_lt) (@exists_rat_btwn _ _ _) lemma real.is_topological_basis_Ioo_rat : @is_topological_basis ℝ _ (⋃(a b : ℚ) (h : a < b), {Ioo a b}) := is_topological_basis_of_open_of_nhds (by simp [is_open_Ioo] {contextual:=tt}) (assume a v hav hv, let ⟨l, u, hl, hu, h⟩ := (mem_nhds_unbounded (no_top _) (no_bot _)).mp (mem_nhds_sets hv hav), ⟨q, hlq, hqa⟩ := exists_rat_btwn hl, ⟨p, hap, hpu⟩ := exists_rat_btwn hu in ⟨Ioo q p, by simp; exact ⟨q, p, rat.cast_lt.1 $ lt_trans hqa hap, rfl⟩, ⟨hqa, hap⟩, assume a' ⟨hqa', ha'p⟩, h _ (lt_trans hlq hqa') (lt_trans ha'p hpu)⟩) instance : second_countable_topology ℝ := ⟨⟨(⋃(a b : ℚ) (h : a < b), {Ioo a b}), by simp [countable_Union, countable_Union_Prop], real.is_topological_basis_Ioo_rat.2.2⟩⟩ /- TODO(Mario): Prove that these are uniform isomorphisms instead of uniform embeddings lemma uniform_embedding_add_rat {r : ℚ} : uniform_embedding (λp:ℚ, p + r) := _ lemma uniform_embedding_mul_rat {q : ℚ} (hq : q ≠ 0) : uniform_embedding ((*) q) := _ -/ lemma real.uniform_continuous_inv (s : set ℝ) {r : ℝ} (r0 : 0 < r) (H : ∀ x ∈ s, r ≤ abs x) : uniform_continuous (λp:s, p.1⁻¹) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_inv_continuous_lemma abs ε0 r0 in ⟨δ, δ0, λ a b h, Hδ (H _ a.2) (H _ b.2) h⟩ lemma real.uniform_continuous_abs : uniform_continuous (abs : ℝ → ℝ) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨ε, ε0, λ a b, lt_of_le_of_lt (abs_abs_sub_abs_le_abs_sub _ _)⟩ lemma real.continuous_abs : continuous (abs : ℝ → ℝ) := real.uniform_continuous_abs.continuous lemma rat.uniform_continuous_abs : uniform_continuous (abs : ℚ → ℚ) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨ε, ε0, λ a b h, lt_of_le_of_lt (by simpa [rat.dist_eq] using abs_abs_sub_abs_le_abs_sub _ _) h⟩ lemma rat.continuous_abs : continuous (abs : ℚ → ℚ) := rat.uniform_continuous_abs.continuous lemma real.tendsto_inv {r : ℝ} (r0 : r ≠ 0) : tendsto (λq, q⁻¹) (nhds r) (nhds r⁻¹) := by rw ← abs_pos_iff at r0; exact tendsto_of_uniform_continuous_subtype (real.uniform_continuous_inv {x | abs r / 2 < abs x} (half_pos r0) (λ x h, le_of_lt h)) (mem_nhds_sets (real.continuous_abs _ $ is_open_lt' (abs r / 2)) (half_lt_self r0)) lemma real.continuous_inv' : continuous (λa:{r:ℝ // r ≠ 0}, a.val⁻¹) := continuous_iff_continuous_at.mpr $ assume ⟨r, hr⟩, tendsto.comp (real.tendsto_inv hr) (continuous_iff_continuous_at.mp continuous_subtype_val _) lemma real.continuous_inv [topological_space α] {f : α → ℝ} (h : ∀a, f a ≠ 0) (hf : continuous f) : continuous (λa, (f a)⁻¹) := show continuous ((has_inv.inv ∘ @subtype.val ℝ (λr, r ≠ 0)) ∘ λa, ⟨f a, h a⟩), from real.continuous_inv'.comp (continuous_subtype_mk _ hf) lemma real.uniform_continuous_mul_const {x : ℝ} : uniform_continuous ((*) x) := metric.uniform_continuous_iff.2 $ λ ε ε0, begin cases no_top (abs x) with y xy, have y0 := lt_of_le_of_lt (abs_nonneg _) xy, refine ⟨_, div_pos ε0 y0, λ a b h, _⟩, rw [real.dist_eq, ← mul_sub, abs_mul, ← mul_div_cancel' ε (ne_of_gt y0)], exact mul_lt_mul' (le_of_lt xy) h (abs_nonneg _) y0 end lemma real.uniform_continuous_mul (s : set (ℝ × ℝ)) {r₁ r₂ : ℝ} (H : ∀ x ∈ s, abs (x : ℝ × ℝ).1 < r₁ ∧ abs x.2 < r₂) : uniform_continuous (λp:s, p.1.1 * p.1.2) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abs ε0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ (H _ a.2).1 (H _ b.2).2 h₁ h₂⟩ protected lemma real.continuous_mul : continuous (λp : ℝ × ℝ, p.1 * p.2) := continuous_iff_continuous_at.2 $ λ ⟨a₁, a₂⟩, tendsto_of_uniform_continuous_subtype (real.uniform_continuous_mul ({x | abs x < abs a₁ + 1}.prod {x | abs x < abs a₂ + 1}) (λ x, id)) (mem_nhds_sets (is_open_prod (real.continuous_abs _ $ is_open_gt' (abs a₁ + 1)) (real.continuous_abs _ $ is_open_gt' (abs a₂ + 1))) ⟨lt_add_one (abs a₁), lt_add_one (abs a₂)⟩) instance : topological_ring ℝ := { continuous_mul := real.continuous_mul, ..real.topological_add_group } instance : topological_semiring ℝ := by apply_instance lemma rat.continuous_mul : continuous (λp : ℚ × ℚ, p.1 * p.2) := embedding_of_rat.continuous_iff.2 $ by simp [(∘)]; exact real.continuous_mul.comp ((continuous_of_rat.comp continuous_fst).prod_mk (continuous_of_rat.comp continuous_snd)) instance : topological_ring ℚ := { continuous_mul := rat.continuous_mul, ..rat.topological_add_group } theorem real.ball_eq_Ioo (x ε : ℝ) : ball x ε = Ioo (x - ε) (x + ε) := set.ext $ λ y, by rw [mem_ball, real.dist_eq, abs_sub_lt_iff, sub_lt_iff_lt_add', and_comm, sub_lt]; refl theorem real.Ioo_eq_ball (x y : ℝ) : Ioo x y = ball ((x + y) / 2) ((y - x) / 2) := by rw [real.ball_eq_Ioo, ← sub_div, add_comm, ← sub_add, add_sub_cancel', add_self_div_two, ← add_div, add_assoc, add_sub_cancel'_right, add_self_div_two] lemma real.totally_bounded_Ioo (a b : ℝ) : totally_bounded (Ioo a b) := metric.totally_bounded_iff.2 $ λ ε ε0, begin rcases exists_nat_gt ((b - a) / ε) with ⟨n, ba⟩, rw [div_lt_iff' ε0, sub_lt_iff_lt_add'] at ba, let s := (λ i:ℕ, a + ε * i) '' {i:ℕ | i < n}, refine ⟨s, finite_image _ ⟨set.fintype_lt_nat _⟩, λ x h, _⟩, rcases h with ⟨ax, xb⟩, let i : ℕ := ⌊(x - a) / ε⌋.to_nat, have : (i : ℤ) = ⌊(x - a) / ε⌋ := int.to_nat_of_nonneg (floor_nonneg.2 $ le_of_lt (div_pos (sub_pos.2 ax) ε0)), simp, refine ⟨_, ⟨i, _, rfl⟩, _⟩, { rw [← int.coe_nat_lt, this], refine int.cast_lt.1 (lt_of_le_of_lt (floor_le _) _), rw [int.cast_coe_nat, div_lt_iff' ε0, sub_lt_iff_lt_add'], exact lt_trans xb ba }, { rw [real.dist_eq, ← int.cast_coe_nat, this, abs_of_nonneg, ← sub_sub, sub_lt_iff_lt_add'], { have := lt_floor_add_one ((x - a) / ε), rwa [div_lt_iff' ε0, mul_add, mul_one] at this }, { have := floor_le ((x - a) / ε), rwa [ge, sub_nonneg, ← le_sub_iff_add_le', ← le_div_iff' ε0] } } end lemma real.totally_bounded_ball (x ε : ℝ) : totally_bounded (ball x ε) := by rw real.ball_eq_Ioo; apply real.totally_bounded_Ioo lemma real.totally_bounded_Ico (a b : ℝ) : totally_bounded (Ico a b) := let ⟨c, ac⟩ := no_bot a in totally_bounded_subset (by exact λ x ⟨h₁, h₂⟩, ⟨lt_of_lt_of_le ac h₁, h₂⟩) (real.totally_bounded_Ioo c b) lemma real.totally_bounded_Icc (a b : ℝ) : totally_bounded (Icc a b) := let ⟨c, bc⟩ := no_top b in totally_bounded_subset (by exact λ x ⟨h₁, h₂⟩, ⟨h₁, lt_of_le_of_lt h₂ bc⟩) (real.totally_bounded_Ico a c) lemma rat.totally_bounded_Icc (a b : ℚ) : totally_bounded (Icc a b) := begin have := totally_bounded_preimage uniform_embedding_of_rat (real.totally_bounded_Icc a b), rwa (set.ext (λ q, _) : Icc _ _ = _), simp end -- TODO(Mario): Generalize to first-countable uniform spaces? instance : complete_space ℝ := ⟨λ f cf, begin let g : ℕ → {ε:ℝ//ε>0} := λ n, ⟨n.to_pnat'⁻¹, inv_pos (nat.cast_pos.2 n.to_pnat'.pos)⟩, choose S hS hS_dist using show ∀n:ℕ, ∃t ∈ f.sets, ∀ x y ∈ t, dist x y < g n, from assume n, let ⟨t, tf, h⟩ := (metric.cauchy_iff.1 cf).2 (g n).1 (g n).2 in ⟨t, tf, h⟩, let F : ℕ → set ℝ := λn, ⋂i≤n, S i, have hF : ∀n, F n ∈ f.sets := assume n, Inter_mem_sets (finite_le_nat n) (λ i _, hS i), have hF_dist : ∀n, ∀ x y ∈ F n, dist x y < g n := assume n x y hx hy, have F n ⊆ S n := bInter_subset_of_mem (le_refl n), (hS_dist n) _ _ (this hx) (this hy), choose G hG using assume n:ℕ, inhabited_of_mem_sets cf.1 (hF n), have hg : ∀ ε > 0, ∃ n, ∀ j ≥ n, (g j : ℝ) < ε, { intros ε ε0, cases exists_nat_gt ε⁻¹ with n hn, refine ⟨n, λ j nj, _⟩, have hj := lt_of_lt_of_le hn (nat.cast_le.2 nj), have j0 := lt_trans (inv_pos ε0) hj, have jε := (inv_lt j0 ε0).2 hj, rwa ← pnat.to_pnat'_coe (nat.cast_pos.1 j0) at jε }, let c : cau_seq ℝ abs, { refine ⟨λ n, G n, λ ε ε0, _⟩, cases hg _ ε0 with n hn, refine ⟨n, λ j jn, _⟩, have : F j ⊆ F n := bInter_subset_bInter_left (λ i h, @le_trans _ _ i n j h jn), exact lt_trans (hF_dist n _ _ (this (hG j)) (hG n)) (hn _ $ le_refl _) }, refine ⟨cau_seq.lim c, λ s h, _⟩, rcases metric.mem_nhds_iff.1 h with ⟨ε, ε0, hε⟩, cases exists_forall_ge_and (hg _ $ half_pos ε0) (cau_seq.equiv_lim c _ $ half_pos ε0) with n hn, cases hn _ (le_refl _) with h₁ h₂, refine sets_of_superset _ (hF n) (subset.trans _ $ subset.trans (ball_half_subset (G n) h₂) hε), exact λ x h, lt_trans ((hF_dist n) x (G n) h (hG n)) h₁ end⟩ lemma tendsto_coe_nat_real_at_top_iff {f : α → ℕ} {l : filter α} : tendsto (λ n, (f n : ℝ)) l at_top ↔ tendsto f l at_top := tendsto_at_top_embedding (assume a₁ a₂, nat.cast_le) $ assume r, let ⟨n, hn⟩ := exists_nat_gt r in ⟨n, le_of_lt hn⟩ lemma tendsto_coe_nat_real_at_top_at_top : tendsto (coe : ℕ → ℝ) at_top at_top := tendsto_coe_nat_real_at_top_iff.2 tendsto_id lemma tendsto_coe_int_real_at_top_iff {f : α → ℤ} {l : filter α} : tendsto (λ n, (f n : ℝ)) l at_top ↔ tendsto f l at_top := tendsto_at_top_embedding (assume a₁ a₂, int.cast_le) $ assume r, let ⟨n, hn⟩ := exists_nat_gt r in ⟨(n:ℤ), le_of_lt $ by rwa [int.cast_coe_nat]⟩ lemma tendsto_coe_int_real_at_top_at_top : tendsto (coe : ℤ → ℝ) at_top at_top := tendsto_coe_int_real_at_top_iff.2 tendsto_id section lemma closure_of_rat_image_lt {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q < x}) = {r | ↑q ≤ r} := subset.antisymm ((closure_subset_iff_subset_of_is_closed (is_closed_ge' _)).2 (image_subset_iff.2 $ λ p h, le_of_lt $ (@rat.cast_lt ℝ _ _ _).2 h)) $ λ x hx, mem_closure_iff_nhds.2 $ λ t ht, let ⟨ε, ε0, hε⟩ := metric.mem_nhds_iff.1 ht in let ⟨p, h₁, h₂⟩ := exists_rat_btwn ((lt_add_iff_pos_right x).2 ε0) in ne_empty_iff_exists_mem.2 ⟨_, hε (show abs _ < _, by rwa [abs_of_nonneg (le_of_lt $ sub_pos.2 h₁), sub_lt_iff_lt_add']), p, rat.cast_lt.1 (@lt_of_le_of_lt ℝ _ _ _ _ hx h₁), rfl⟩ /- TODO(Mario): Put these back only if needed later lemma closure_of_rat_image_le_eq {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q ≤ x}) = {r | ↑q ≤ r} := _ lemma closure_of_rat_image_le_le_eq {a b : ℚ} (hab : a ≤ b) : closure (of_rat '' {q:ℚ | a ≤ q ∧ q ≤ b}) = {r:ℝ | of_rat a ≤ r ∧ r ≤ of_rat b} := _-/ lemma compact_Icc {a b : ℝ} : compact (Icc a b) := compact_of_totally_bounded_is_closed (real.totally_bounded_Icc a b) (is_closed_inter (is_closed_ge' a) (is_closed_le' b)) instance : proper_space ℝ := { compact_ball := λx r, by rw closed_ball_Icc; apply compact_Icc } open real lemma real.intermediate_value {f : ℝ → ℝ} {a b t : ℝ} (hf : ∀ x, a ≤ x → x ≤ b → tendsto f (nhds x) (nhds (f x))) (ha : f a ≤ t) (hb : t ≤ f b) (hab : a ≤ b) : ∃ x : ℝ, a ≤ x ∧ x ≤ b ∧ f x = t := let x := real.Sup {x | f x ≤ t ∧ a ≤ x ∧ x ≤ b} in have hx₁ : ∃ y, ∀ g ∈ {x | f x ≤ t ∧ a ≤ x ∧ x ≤ b}, g ≤ y := ⟨b, λ _ h, h.2.2⟩, have hx₂ : ∃ y, y ∈ {x | f x ≤ t ∧ a ≤ x ∧ x ≤ b} := ⟨a, ha, le_refl _, hab⟩, have hax : a ≤ x, from le_Sup _ hx₁ ⟨ha, le_refl _, hab⟩, have hxb : x ≤ b, from (Sup_le _ hx₂ hx₁).2 (λ _ h, h.2.2), ⟨x, hax, hxb, eq_of_forall_dist_le $ λ ε ε0, let ⟨δ, hδ0, hδ⟩ := metric.tendsto_nhds_nhds.1 (hf _ hax hxb) ε ε0 in (le_total t (f x)).elim (λ h, le_of_not_gt $ λ hfε, begin rw [dist_eq, abs_of_nonneg (sub_nonneg.2 h)] at hfε, refine mt (Sup_le {x | f x ≤ t ∧ a ≤ x ∧ x ≤ b} hx₂ hx₁).2 (not_le_of_gt (sub_lt_self x (half_pos hδ0))) (λ g hg, le_of_not_gt (λ hgδ, not_lt_of_ge hg.1 (lt_trans (lt_sub.1 hfε) (sub_lt_of_sub_lt (lt_of_le_of_lt (le_abs_self _) _))))), rw abs_sub, exact hδ (abs_sub_lt_iff.2 ⟨lt_of_le_of_lt (sub_nonpos.2 (le_Sup _ hx₁ hg)) hδ0, by simp only [x] at *; linarith⟩) end) (λ h, le_of_not_gt $ λ hfε, begin rw [dist_eq, abs_of_nonpos (sub_nonpos.2 h)] at hfε, exact mt (le_Sup {x | f x ≤ t ∧ a ≤ x ∧ x ≤ b}) (λ h : ∀ k, k ∈ {x | f x ≤ t ∧ a ≤ x ∧ x ≤ b} → k ≤ x, not_le_of_gt ((lt_add_iff_pos_left x).2 (half_pos hδ0)) (h _ ⟨le_trans (le_sub_iff_add_le.2 (le_trans (le_abs_self _) (le_of_lt (hδ $ by rw [dist_eq, add_sub_cancel, abs_of_nonneg (le_of_lt (half_pos hδ0))]; exact half_lt_self hδ0)))) (by linarith), le_trans hax (le_of_lt ((lt_add_iff_pos_left _).2 (half_pos hδ0))), le_of_not_gt (λ hδy, not_lt_of_ge hb (lt_of_le_of_lt (show f b ≤ f b - f x - ε + t, by linarith) (add_lt_of_neg_of_le (sub_neg_of_lt (lt_of_le_of_lt (le_abs_self _) (@hδ b (abs_sub_lt_iff.2 ⟨by simp only [x] at *; linarith, by linarith⟩)))) (le_refl _))))⟩)) hx₁ end)⟩ lemma real.intermediate_value' {f : ℝ → ℝ} {a b t : ℝ} (hf : ∀ x, a ≤ x → x ≤ b → tendsto f (nhds x) (nhds (f x))) (ha : t ≤ f a) (hb : f b ≤ t) (hab : a ≤ b) : ∃ x : ℝ, a ≤ x ∧ x ≤ b ∧ f x = t := let ⟨x, hx₁, hx₂, hx₃⟩ := @real.intermediate_value (λ x, - f x) a b (-t) (λ x hax hxb, tendsto_neg (hf x hax hxb)) (neg_le_neg ha) (neg_le_neg hb) hab in ⟨x, hx₁, hx₂, neg_inj hx₃⟩ lemma real.bounded_iff_bdd_below_bdd_above {s : set ℝ} : bounded s ↔ bdd_below s ∧ bdd_above s := ⟨begin assume bdd, rcases (bounded_iff_subset_ball 0).1 bdd with ⟨r, hr⟩, -- hr : s ⊆ closed_ball 0 r rw closed_ball_Icc at hr, -- hr : s ⊆ Icc (0 - r) (0 + r) exact ⟨⟨-r, λy hy, by simpa using (hr hy).1⟩, ⟨r, λy hy, by simpa using (hr hy).2⟩⟩ end, begin rintros ⟨⟨m, hm⟩, ⟨M, hM⟩⟩, have I : s ⊆ Icc m M := λx hx, ⟨hm x hx, hM x hx⟩, have : Icc m M = closed_ball ((m+M)/2) ((M-m)/2) := by rw closed_ball_Icc; congr; ring, rw this at I, exact bounded.subset I bounded_closed_ball end⟩ end
a5b8d6848f551e29691cc8db67ad86223f6136c4
94e33a31faa76775069b071adea97e86e218a8ee
/src/topology/vector_bundle/hom.lean
ddd1541339077ce674d8514cbd5ca13ae1876824
[ "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
14,407
lean
/- Copyright © 2022 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth, Floris van Doorn -/ import topology.vector_bundle.basic import analysis.normed_space.operator_norm /-! # The topological vector bundle of continuous (semi)linear maps We define the topological vector bundle of continuous (semi)linear maps between two vector bundles over the same base. Given bundles `E₁ E₂ : B → Type*`, we define `bundle.continuous_linear_map 𝕜 E₁ E₂ := λ x, E₁ x →SL[𝕜] E₂ x`. If the `E₁` and `E₂` are topological vector bundles with fibers `F₁` and `F₂`, then this will be a topological vector bundle with fiber `F₁ →SL[𝕜] F₂`. The topology is inherited from the norm-topology on, without the need to define the strong topology on continuous linear maps between general topological vector spaces. ## Main Definitions * `bundle.continuous_linear_map.topological_vector_bundle`: continuous semilinear maps between vector bundles form a vector bundle. -/ noncomputable theory open bundle set continuous_linear_map section defs variables {𝕜₁ 𝕜₂ : Type*} [normed_field 𝕜₁] [normed_field 𝕜₂] variables (σ : 𝕜₁ →+* 𝕜₂) variables {B : Type*} variables (F₁ : Type*) (E₁ : B → Type*) [Π x, add_comm_monoid (E₁ x)] [Π x, module 𝕜₁ (E₁ x)] variables [Π x : B, topological_space (E₁ x)] variables (F₂ : Type*) (E₂ : B → Type*) [Π x, add_comm_monoid (E₂ x)] [Π x, module 𝕜₂ (E₂ x)] variables [Π x : B, topological_space (E₂ x)] include F₁ F₂ -- In this definition we require the scalar rings `𝕜₁` and `𝕜₂` to be normed fields, although -- something much weaker (maybe `comm_semiring`) would suffice mathematically -- this is because of -- a typeclass inference bug with pi-types: -- https://leanprover.zulipchat.com/#narrow/stream/116395-maths/topic/vector.20bundles.20--.20typeclass.20inference.20issue /-- The bundle of continuous `σ`-semilinear maps between the topological vector bundles `E₁` and `E₂`. This is a type synonym for `λ x, E₁ x →SL[σ] E₂ x`. We intentionally add `F₁` and `F₂` as arguments to this type, so that instances on this type (that depend on `F₁` and `F₂`) actually refer to `F₁` and `F₂`. -/ @[derive inhabited, nolint unused_arguments] def bundle.continuous_linear_map (x : B) : Type* := E₁ x →SL[σ] E₂ x instance bundle.continuous_linear_map.add_monoid_hom_class (x : B) : add_monoid_hom_class (bundle.continuous_linear_map σ F₁ E₁ F₂ E₂ x) (E₁ x) (E₂ x) := by delta_instance bundle.continuous_linear_map variables [Π x, has_continuous_add (E₂ x)] instance (x : B) : add_comm_monoid (bundle.continuous_linear_map σ F₁ E₁ F₂ E₂ x) := by delta_instance bundle.continuous_linear_map variables [∀ x, has_continuous_smul 𝕜₂ (E₂ x)] instance (x : B) : module 𝕜₂ (bundle.continuous_linear_map σ F₁ E₁ F₂ E₂ x) := by delta_instance bundle.continuous_linear_map end defs variables {𝕜₁ : Type*} [nondiscrete_normed_field 𝕜₁] {𝕜₂ : Type*} [nondiscrete_normed_field 𝕜₂] (σ : 𝕜₁ →+* 𝕜₂) variables {B : Type*} [topological_space B] variables (F₁ : Type*) [normed_group F₁] [normed_space 𝕜₁ F₁] (E₁ : B → Type*) [Π x, add_comm_monoid (E₁ x)] [Π x, module 𝕜₁ (E₁ x)] [topological_space (total_space E₁)] variables (F₂ : Type*) [normed_group F₂][normed_space 𝕜₂ F₂] (E₂ : B → Type*) [Π x, add_comm_monoid (E₂ x)] [Π x, module 𝕜₂ (E₂ x)] [topological_space (total_space E₂)] namespace topological_vector_bundle variables {F₁ E₁ F₂ E₂} (e₁ e₁' : trivialization 𝕜₁ F₁ E₁) (e₂ e₂' : trivialization 𝕜₂ F₂ E₂) variables [ring_hom_isometric σ] namespace pretrivialization /-- Assume `eᵢ` and `eᵢ'` are trivializations of the bundles `Eᵢ` over base `B` with fiber `Fᵢ` (`i ∈ {1,2}`), then `continuous_linear_map_coord_change σ e₁ e₁' e₂ e₂'` is the coordinate change function between the two induced (pre)trivializations `pretrivialization.continuous_linear_map σ e₁ e₂` and `pretrivialization.continuous_linear_map σ e₁' e₂'` of `bundle.continuous_linear_map`. -/ def continuous_linear_map_coord_change (b : B) : (F₁ →SL[σ] F₂) →L[𝕜₂] F₁ →SL[σ] F₂ := ((e₁'.coord_change e₁ b).symm.arrow_congrSL (e₂.coord_change e₂' b) : (F₁ →SL[σ] F₂) ≃L[𝕜₂] F₁ →SL[σ] F₂) variables {σ e₁ e₁' e₂ e₂'} variables [Π x : B, topological_space (E₁ x)] [topological_vector_bundle 𝕜₁ F₁ E₁] variables [Π x : B, topological_space (E₂ x)] [topological_vector_bundle 𝕜₂ F₂ E₂] lemma continuous_on_continuous_linear_map_coord_change (he₁ : e₁ ∈ trivialization_atlas 𝕜₁ F₁ E₁) (he₁' : e₁' ∈ trivialization_atlas 𝕜₁ F₁ E₁) (he₂ : e₂ ∈ trivialization_atlas 𝕜₂ F₂ E₂) (he₂' : e₂' ∈ trivialization_atlas 𝕜₂ F₂ E₂) : continuous_on (continuous_linear_map_coord_change σ e₁ e₁' e₂ e₂') ((e₁.base_set ∩ e₂.base_set) ∩ (e₁'.base_set ∩ e₂'.base_set)) := begin have h₁ := (compSL F₁ F₂ F₂ σ (ring_hom.id 𝕜₂)).continuous, have h₂ := (continuous_linear_map.flip (compSL F₁ F₁ F₂ (ring_hom.id 𝕜₁) σ)).continuous, have h₃ := (continuous_on_coord_change e₁' he₁' e₁ he₁), have h₄ := (continuous_on_coord_change e₂ he₂ e₂' he₂'), refine ((h₁.comp_continuous_on (h₄.mono _)).clm_comp (h₂.comp_continuous_on (h₃.mono _))).congr _, { mfld_set_tac }, { mfld_set_tac }, { intros b hb, ext L v, simp only [continuous_linear_map_coord_change, continuous_linear_equiv.coe_coe, continuous_linear_equiv.arrow_congrSL_apply, comp_apply, function.comp, compSL_apply, flip_apply, continuous_linear_equiv.symm_symm] }, end variables (σ e₁ e₁' e₂ e₂') variables [Π x, has_continuous_add (E₂ x)] [Π x, has_continuous_smul 𝕜₂ (E₂ x)] /-- Given trivializations `e₁`, `e₂` for vector bundles `E₁`, `E₂` over a base `B`, `pretrivialization.continuous_linear_map σ e₁ e₂` is the induced pretrivialization for the continuous `σ`-semilinear maps from `E₁` to `E₂`. That is, the map which will later become a trivialization, after the bundle of continuous semilinear maps is equipped with the right topological vector bundle structure. -/ def continuous_linear_map : pretrivialization 𝕜₂ (F₁ →SL[σ] F₂) (bundle.continuous_linear_map σ F₁ E₁ F₂ E₂) := { to_fun := λ p, ⟨p.1, (e₂.continuous_linear_map_at p.1).comp $ p.2.comp $ e₁.symmL p.1⟩, inv_fun := λ p, ⟨p.1, (e₂.symmL p.1).comp $ p.2.comp $ e₁.continuous_linear_map_at p.1⟩, source := (bundle.total_space.proj) ⁻¹' (e₁.base_set ∩ e₂.base_set), target := (e₁.base_set ∩ e₂.base_set) ×ˢ (set.univ : set (F₁ →SL[σ] F₂)), map_source' := λ ⟨x, L⟩ h, ⟨h, set.mem_univ _⟩, map_target' := λ ⟨x, f⟩ h, h.1, left_inv' := λ ⟨x, L⟩ ⟨h₁, h₂⟩, begin simp_rw [sigma.mk.inj_iff, eq_self_iff_true, heq_iff_eq, true_and], ext v, simp only [comp_apply, trivialization.symmL_continuous_linear_map_at, h₁, h₂] end, right_inv' := λ ⟨x, f⟩ ⟨⟨h₁, h₂⟩, _⟩, begin simp_rw [prod.mk.inj_iff, eq_self_iff_true, true_and], ext v, simp only [comp_apply, trivialization.continuous_linear_map_at_symmL, h₁, h₂] end, open_target := (e₁.open_base_set.inter e₂.open_base_set).prod is_open_univ, base_set := e₁.base_set ∩ e₂.base_set, open_base_set := e₁.open_base_set.inter e₂.open_base_set, source_eq := rfl, target_eq := rfl, proj_to_fun := λ ⟨x, f⟩ h, rfl, linear' := λ x h, { map_add := λ L L', by simp_rw [add_comp, comp_add], map_smul := λ c L, by simp_rw [smul_comp, comp_smulₛₗ, ring_hom.id_apply] } } lemma continuous_linear_map_apply (p : total_space (bundle.continuous_linear_map σ F₁ E₁ F₂ E₂)) : (continuous_linear_map σ e₁ e₂) p = ⟨p.1, (e₂.continuous_linear_map_at p.1).comp $ p.2.comp $ e₁.symmL p.1⟩ := rfl lemma continuous_linear_map_symm_apply (p : B × (F₁ →SL[σ] F₂)) : (continuous_linear_map σ e₁ e₂).to_local_equiv.symm p = ⟨p.1, (e₂.symmL p.1).comp $ p.2.comp $ e₁.continuous_linear_map_at p.1⟩ := rfl lemma continuous_linear_map_symm_apply' {b : B} (hb : b ∈ e₁.base_set ∩ e₂.base_set) (L : F₁ →SL[σ] F₂) : (continuous_linear_map σ e₁ e₂).symm b L = (e₂.symmL b).comp (L.comp $ e₁.continuous_linear_map_at b) := begin rw [symm_apply], refl, exact hb end lemma continuous_linear_map_coord_change_apply (b : B) (hb : b ∈ (e₁.base_set ∩ e₂.base_set) ∩ (e₁'.base_set ∩ e₂'.base_set)) (L : F₁ →SL[σ] F₂) : continuous_linear_map_coord_change σ e₁ e₁' e₂ e₂' b L = (continuous_linear_map σ e₁' e₂' (total_space_mk b ((continuous_linear_map σ e₁ e₂).symm b L))).2 := begin ext v, simp_rw [continuous_linear_map_coord_change, continuous_linear_equiv.coe_coe, continuous_linear_equiv.arrow_congrSL_apply, continuous_linear_map_apply, continuous_linear_map_symm_apply' σ e₁ e₂ hb.1, comp_apply, continuous_linear_equiv.coe_coe, continuous_linear_equiv.symm_symm, trivialization.continuous_linear_map_at_apply, trivialization.symmL_apply], dsimp only [total_space_mk], rw [e₂.coord_change_apply e₂', e₁'.coord_change_apply e₁, e₁.coe_linear_map_at_of_mem hb.1.1, e₂'.coe_linear_map_at_of_mem hb.2.2], exacts [⟨hb.2.1, hb.1.1⟩, ⟨hb.1.2, hb.2.2⟩] end end pretrivialization open pretrivialization variables (F₁ E₁ F₂ E₂) variables [Π x : B, topological_space (E₁ x)] [topological_vector_bundle 𝕜₁ F₁ E₁] variables [Π x : B, topological_space (E₂ x)] [topological_vector_bundle 𝕜₂ F₂ E₂] variables [Π x, has_continuous_add (E₂ x)] [Π x, has_continuous_smul 𝕜₂ (E₂ x)] /-- The continuous `σ`-semilinear maps between two topological vector bundles form a `topological_vector_prebundle` (this is an auxiliary construction for the `topological_vector_bundle` instance, in which the pretrivializations are collated but no topology on the total space is yet provided). -/ def _root_.bundle.continuous_linear_map.topological_vector_prebundle : topological_vector_prebundle 𝕜₂ (F₁ →SL[σ] F₂) (bundle.continuous_linear_map σ F₁ E₁ F₂ E₂) := { pretrivialization_atlas := image2 (λ e₁ e₂, pretrivialization.continuous_linear_map σ e₁ e₂) (trivialization_atlas 𝕜₁ F₁ E₁) (trivialization_atlas 𝕜₂ F₂ E₂), pretrivialization_at := λ x, pretrivialization.continuous_linear_map σ (trivialization_at 𝕜₁ F₁ E₁ x) (trivialization_at 𝕜₂ F₂ E₂ x), mem_base_pretrivialization_at := λ x, ⟨mem_base_set_trivialization_at 𝕜₁ F₁ E₁ x, mem_base_set_trivialization_at 𝕜₂ F₂ E₂ x⟩, pretrivialization_mem_atlas := λ x, ⟨_, _, trivialization_mem_atlas 𝕜₁ F₁ E₁ x, trivialization_mem_atlas 𝕜₂ F₂ E₂ x, rfl⟩, exists_coord_change := by { rintro _ ⟨e₁, e₂, he₁, he₂, rfl⟩ _ ⟨e₁', e₂', he₁', he₂', rfl⟩, exact ⟨continuous_linear_map_coord_change σ e₁ e₁' e₂ e₂', continuous_on_continuous_linear_map_coord_change he₁ he₁' he₂ he₂', continuous_linear_map_coord_change_apply σ e₁ e₁' e₂ e₂'⟩ } } /-- Topology on the continuous `σ`-semilinear_maps between the respective fibers at a point of two "normable" vector bundles over the same base. Here "normable" means that the bundles have fibers modelled on normed spaces `F₁`, `F₂` respectively. The topology we put on the continuous `σ`-semilinear_maps is the topology coming from the operator norm on maps from `F₁` to `F₂`. -/ instance (x : B) : topological_space (bundle.continuous_linear_map σ F₁ E₁ F₂ E₂ x) := (bundle.continuous_linear_map.topological_vector_prebundle σ F₁ E₁ F₂ E₂).fiber_topology x /-- Topology on the total space of the continuous `σ`-semilinear_maps between two "normable" vector bundles over the same base. -/ instance : topological_space (total_space (bundle.continuous_linear_map σ F₁ E₁ F₂ E₂)) := (bundle.continuous_linear_map.topological_vector_prebundle σ F₁ E₁ F₂ E₂).total_space_topology /-- The continuous `σ`-semilinear_maps between two vector bundles form a vector bundle. -/ instance _root_.bundle.continuous_linear_map.topological_vector_bundle : topological_vector_bundle 𝕜₂ (F₁ →SL[σ] F₂) (bundle.continuous_linear_map σ F₁ E₁ F₂ E₂) := (bundle.continuous_linear_map.topological_vector_prebundle σ F₁ E₁ F₂ E₂).to_topological_vector_bundle variables {F₁ E₁ F₂ E₂} /-- Given trivializations `e₁`, `e₂` in the atlas for vector bundles `E₁`, `E₂` over a base `B`, the induced trivialization for the continuous `σ`-semilinear maps from `E₁` to `E₂`, whose base set is `e₁.base_set ∩ e₂.base_set`. -/ def trivialization.continuous_linear_map (he₁ : e₁ ∈ trivialization_atlas 𝕜₁ F₁ E₁) (he₂ : e₂ ∈ trivialization_atlas 𝕜₂ F₂ E₂) : trivialization 𝕜₂ (F₁ →SL[σ] F₂) (bundle.continuous_linear_map σ F₁ E₁ F₂ E₂) := (bundle.continuous_linear_map.topological_vector_prebundle σ F₁ E₁ F₂ E₂) .trivialization_of_mem_pretrivialization_atlas (mem_image2_of_mem he₁ he₂) variables {e₁ e₂} @[simp] lemma trivialization.base_set_continuous_linear_map (he₁ : e₁ ∈ trivialization_atlas 𝕜₁ F₁ E₁) (he₂ : e₂ ∈ trivialization_atlas 𝕜₂ F₂ E₂) : (e₁.continuous_linear_map σ e₂ he₁ he₂).base_set = e₁.base_set ∩ e₂.base_set := rfl lemma trivialization.continuous_linear_map_apply (he₁ : e₁ ∈ trivialization_atlas 𝕜₁ F₁ E₁) (he₂ : e₂ ∈ trivialization_atlas 𝕜₂ F₂ E₂) (p : total_space (bundle.continuous_linear_map σ F₁ E₁ F₂ E₂)) : e₁.continuous_linear_map σ e₂ he₁ he₂ p = ⟨p.1, (e₂.continuous_linear_map_at p.1).comp $ p.2.comp $ e₁.symmL p.1⟩ := rfl end topological_vector_bundle
903c3c343dde4ead0b44f12bd8af400ffd90eb30
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/src/Lean/Elab/Tactic.lean
fb800b76a577a611d3faa35689de58b1d3121b80
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
533
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Elab.Term import Lean.Elab.Tactic.Basic import Lean.Elab.Tactic.ElabTerm import Lean.Elab.Tactic.Induction import Lean.Elab.Tactic.Generalize import Lean.Elab.Tactic.Injection import Lean.Elab.Tactic.Match import Lean.Elab.Tactic.Rewrite import Lean.Elab.Tactic.Location import Lean.Elab.Tactic.Simp import Lean.Elab.Tactic.BuiltinTactic
98fa650cb3288b6725c3d938e5fc2d7673e07f44
6305b69bc7636a761e1a1947508bb5ebad93cb7e
/library/init/meta/coinductive_predicates.lean
dc1ec9ee1297301e5c1309f601c34f36299300d4
[ "Apache-2.0" ]
permissive
HGldJ1966/lean
e7f0068f8a69fde3593b77d8a44609ae446d7738
049d940167c419cd5935d12b459c0695d8615ae9
refs/heads/master
1,611,340,395,700
1,503,103,829,000
1,503,103,829,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
23,192
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl (CMU) -/ prelude import init.meta.expr init.meta.tactic init.meta.constructor_tactic init.meta.attribute import init.meta.interactive namespace name def last_string : name → string | anonymous := "[anonymous]" | (mk_string s _) := s | (mk_numeral _ n) := last_string n end name namespace expr open expr meta def replace_with (e : expr) (s : expr) (s' : expr) : expr := e.replace $ λc d, if c = s then some (s'.lift_vars 0 d) else none meta def local_binder_info : expr → binder_info | (local_const x n bi t) := bi | e := binder_info.default meta def to_implicit_binder : expr → expr | (local_const n₁ n₂ _ d) := local_const n₁ n₂ binder_info.implicit d | (lam n _ d b) := lam n binder_info.implicit d b | (pi n _ d b) := pi n binder_info.implicit d b | e := e meta def get_app_fn_args_aux : list expr → expr → expr × list expr | r (app f a) := get_app_fn_args_aux (a::r) f | r e := (e, r) meta def get_app_fn_args : expr → expr × list expr := get_app_fn_args_aux [] end expr namespace tactic open level expr tactic meta def mk_local_pisn : expr → nat → tactic (list expr × expr) | (pi n bi d b) (c + 1) := do p ← mk_local' n bi d, (ps, r) ← mk_local_pisn (b.instantiate_var p) c, return ((p :: ps), r) | e 0 := return ([], e) | _ _ := failed meta def drop_pis : list expr → expr → tactic expr | (list.cons v vs) (pi n bi d b) := do t ← infer_type v, guard (t =ₐ d), drop_pis vs (b.instantiate_var v) | [] e := return e | _ _ := failed meta def mk_theorem (n : name) (ls : list name) (t : expr) (e : expr) : declaration := declaration.thm n ls t (task.pure e) meta def add_theorem_by (n : name) (ls : list name) (type : expr) (tac : tactic unit) : tactic expr := do ((), body) ← solve_aux type tac, body ← instantiate_mvars body, add_decl $ mk_theorem n ls type body, return $ const n $ ls.map param meta def mk_exists_lst (args : list expr) (inner : expr) : tactic expr := args.mfoldr (λarg i:expr, do t ← infer_type arg, sort l ← infer_type t, return $ if arg.occurs i ∨ l ≠ level.zero then (const `Exists [l] : expr) t (i.lambdas [arg]) else (const `and [] : expr) t i) inner meta def mk_op_lst (op : expr) (empty : expr) : list expr → expr | [] := empty | [e] := e | (e :: es) := op e $ mk_op_lst es meta def mk_and_lst : list expr → expr := mk_op_lst `(and) `(true) meta def mk_or_lst : list expr → expr := mk_op_lst `(or) `(false) meta def elim_gen_prod : nat → expr → list expr → tactic (list expr × expr) | 0 e hs := return (hs, e) | (n + 1) e hs := do [([h, h'], _)] ← induction e [], elim_gen_prod n h' (hs ++ [h]) private meta def elim_gen_sum_aux : nat → expr → list expr → tactic (list expr × expr) | 0 e hs := return (hs, e) | (n + 1) e hs := do [([h], _), ([h'], _)] ← induction e [], swap, elim_gen_sum_aux n h' (h::hs) meta def elim_gen_sum (n : nat) (e : expr) : tactic (list expr) := do (hs, h') ← elim_gen_sum_aux n e [], gs ← get_goals, set_goals $ (gs.take (n+1)).reverse ++ gs.drop (n+1), return $ hs.reverse ++ [h'] end tactic section universe u @[user_attribute] meta def monotonicity := { user_attribute . name := `monotonicity, descr := "Monotonicity rules for predicates" } lemma monotonicity.pi {α : Sort u} {p q : α → Prop} (h : ∀a, implies (p a) (q a)) : implies (Πa, p a) (Πa, q a) := assume h' a, h a (h' a) lemma monotonicity.imp {p p' q q' : Prop} (h₁ : implies p' q') (h₂ : implies q p) : implies (p → p') (q → q') := assume h, h₁ ∘ h ∘ h₂ @[monotonicity] lemma monotonicity.const (p : Prop) : implies p p := id @[monotonicity] lemma monotonicity.true (p : Prop) : implies p true := assume _, trivial @[monotonicity] lemma monotonicity.false (p : Prop) : implies false p := false.elim @[monotonicity] lemma monotonicity.exists {α : Sort u} {p q : α → Prop} (h : ∀a, implies (p a) (q a)) : implies (∃a, p a) (∃a, q a) := exists_imp_exists h @[monotonicity] lemma monotonicity.and {p p' q q' : Prop} (hp : implies p p') (hq : implies q q') : implies (p ∧ q) (p' ∧ q') := and.imp hp hq @[monotonicity] lemma monotonicity.or {p p' q q' : Prop} (hp : implies p p') (hq : implies q q') : implies (p ∨ q) (p' ∨ q') := or.imp hp hq @[monotonicity] lemma monotonicity.not {p q : Prop} (h : implies p q) : implies (¬ q) (¬ p) := mt h end namespace tactic open expr tactic /- TODO: use backchaining -/ private meta def mono_aux (ns : list name) (hs : list expr) : tactic unit := do intros, (do `(implies %%p %%q) ← target, (do is_def_eq p q, eapplyc `monotone.const) <|> (do (expr.pi pn pbi pd pb) ← return p, (expr.pi qn qbi qd qb) ← return q, sort u ← infer_type pd, (do is_def_eq pd qd, let p' := expr.lam pn pbi pd pb, let q' := expr.lam qn qbi qd qb, eapply $ (const `monotonicity.pi [u] : expr) pd p' q') <|> (do guard $ u = level.zero ∧ is_arrow p ∧ is_arrow q, let p' := pb.lower_vars 0 1, let q' := qb.lower_vars 0 1, eapply $ (const `monotonicity.imp []: expr) pd p' qd q'))) <|> first (hs.map $ λh, apply_core h {md := transparency.none, new_goals := new_goals.non_dep_only} >> skip) <|> first (ns.map $ λn, do c ← mk_const n, apply_core c {md := transparency.none, new_goals := new_goals.non_dep_only}, skip), all_goals mono_aux meta def mono (e : expr) (hs : list expr) : tactic unit := do t ← target, t' ← infer_type e, ns ← attribute.get_instances `monotonicity, ((), p) ← solve_aux `(implies %%t' %%t) (mono_aux ns hs), exact (p e) end tactic /- The coinductive predicate `pred`: coinductive {u} pred (A) : a → Prop | r : ∀A b, pred A p where `u` is a list of universe parameters `A` is a list of global parameters `pred` is a list predicates to be defined `a` are the indices for each `pred` `r` is a list of introduction rules for each `pred` `b` is a list of parameters for each rule in `r` and `pred` `p` is are the instances of `a` using `A` and `b` `pred` is compiled to the following defintions: inductive {u} pred.functional (A) ([pred'] : a → Prop) : a → Prop | r : ∀a [f], b[pred/pred'] → pred.functional a [f] p lemma {u} pred.functional.mono (A) ([pred₁] [pred₂] : a → Prop) [(h : ∀b, pred₁ b → pred₂ b)] : ∀p, pred.functional A pred₁ p → pred.functional A pred₂ p def {u} pred_i (A) (a) : Prop := ∃[pred'], (Λi, ∀a, pred_i a → pred_i.functional A [pred] a) ∧ pred'_i a lemma {u} pred_i.corec_functional (A) [Λi, C_i : a_i → Prop] [Λi, h : ∀a, C_i a → pred_i.functional A C_i a] : ∀a, C_i a → pred_i A a lemma {u} pred_i.destruct (A) (a) : pred A a → pred.functional A [pred A] a lemma {u} pred_i.construct (A) : ∀a, pred_i.functional A [pred A] a → pred_i A a lemma {u} pred_i.cases_on (A) (C : a → Prop) {a} (h : pred_i a) [Λi, ∀a, b → C p] → C a lemma {u} pred_i.corec_on (A) [(C : a → Prop)] (a) (h : C_i a) [Λi, h_i : ∀a, C_i a → [V j ∃b, a = p]] : pred_i A a lemma {u} pred.r (A) (b) : pred_i A p -/ namespace tactic open level expr tactic namespace add_coinductive_predicate /- private -/ meta structure coind_rule : Type := (orig_nm : name) (func_nm : name) (type : expr) (loc_type : expr) (args : list expr) (loc_args : list expr) (concl : expr) (insts : list expr) /- private -/ meta structure coind_pred : Type := (u_names : list name) (params : list expr) (pd_name : name) (type : expr) (intros : list coind_rule) (locals : list expr) (f₁ f₂ : expr) (u_f : level) namespace coind_pred meta def u_params (pd : coind_pred) : list level := pd.u_names.map param meta def f₁_l (pd : coind_pred) : expr := pd.f₁.app_of_list pd.locals meta def f₂_l (pd : coind_pred) : expr := pd.f₂.app_of_list pd.locals meta def pred (pd : coind_pred) : expr := const pd.pd_name pd.u_params meta def func (pd : coind_pred) : expr := const (pd.pd_name ++ "functional") pd.u_params meta def func_g (pd : coind_pred) : expr := pd.func.app_of_list $ pd.params meta def pred_g (pd : coind_pred) : expr := pd.pred.app_of_list $ pd.params meta def impl_locals (pd : coind_pred) : list expr := pd.locals.map to_implicit_binder meta def impl_params (pd : coind_pred) : list expr := pd.params.map to_implicit_binder meta def le (pd : coind_pred) (f₁ f₂ : expr) : expr := (imp (f₁.app_of_list pd.locals) (f₂.app_of_list pd.locals)).pis pd.impl_locals meta def corec_functional (pd : coind_pred) : expr := const (pd.pd_name ++ "corec_functional") pd.u_params meta def mono (pd : coind_pred) : expr := const (pd.func.const_name ++ "mono") pd.u_params meta def rec' (pd : coind_pred) : tactic expr := do let c := pd.func.const_name ++ "rec", env ← get_env, decl ← env.get c, let num := decl.univ_params.length, return (const c $ if num = pd.u_params.length then pd.u_params else level.zero :: pd.u_params) -- ^^ `rec`'s universes are not always `u_params`, e.g. eq, wf, false meta def construct (pd : coind_pred) : expr := const (pd.pd_name ++ "construct") pd.u_params meta def destruct (pd : coind_pred) : expr := const (pd.pd_name ++ "destruct") pd.u_params meta def add_theorem (pd : coind_pred) (n : name) (type : expr) (tac : tactic unit) : tactic expr := add_theorem_by n pd.u_names type tac end coind_pred end add_coinductive_predicate open add_coinductive_predicate /- compact_relation bs as_ps: Product a relation of the form: R := λ as, ∃ bs, Λ_i a_i = p_i[bs] This relation is user visible, so we compact it by removing each `b_j` where a `p_i = b_j`, and hence `a_i = b_j`. We need to take care when there are `p_i` and `p_j` with `p_i = p_j = b_k`. -/ private meta def compact_relation : list expr → list (expr × expr) → list expr × list (expr × expr) | [] ps := ([], ps) | (list.cons b bs) ps := match ps.span (λap:expr × expr, ¬ ap.2 =ₐ b) with | (_, []) := let (bs, ps) := compact_relation bs ps in (b::bs, ps) | (ps₁, list.cons (a, _) ps₂) := let i := a.instantiate_local b.local_uniq_name in compact_relation (bs.map i) ((ps₁ ++ ps₂).map (λ⟨a, p⟩, (a, i p))) end meta def add_coinductive_predicate (u_names : list name) (params : list expr) (preds : list $ expr × list expr) : command := do let params_names := params.map local_pp_name, let u_params := u_names.map param, pre_info ← preds.mmap (λ⟨c, is⟩, do (ls, t) ← mk_local_pis c.local_type, (is_def_eq t `(Prop) <|> fail (format! "Type of {c.local_pp_name} is not Prop. Currently only " ++ "coinductive predicates are supported.")), let n := if preds.length = 1 then "" else "_" ++ c.local_pp_name.last_string, f₁ ← mk_local_def (mk_simple_name $ "C" ++ n) c.local_type, f₂ ← mk_local_def (mk_simple_name $ "C₂" ++ n) c.local_type, return (ls, (f₁, f₂))), let fs := pre_info.map prod.snd, let fs₁ := fs.map prod.fst, let fs₂ := fs.map prod.snd, pds ← (preds.zip pre_info).mmap (λ⟨⟨c, is⟩, ls, f₁, f₂⟩, do sort u_f ← infer_type f₁ >>= infer_type, let pred_g := λc:expr, (const c.local_uniq_name u_params : expr).app_of_list params, intros ← is.mmap (λi, do (args, t') ← mk_local_pis i.local_type, (name.mk_string sub p) ← return i.local_uniq_name, let loc_args := args.map $ λe, (fs₁.zip preds).foldl (λ(e:expr) ⟨f, c, _⟩, e.replace_with (pred_g c) f) e, let t' := t'.replace_with (pred_g c) f₂, return { tactic.add_coinductive_predicate.coind_rule . orig_nm := i.local_uniq_name, func_nm := (p ++ "functional") ++ sub, type := i.local_type, loc_type := t'.pis loc_args, concl := t', loc_args := loc_args, args := args, insts := t'.get_app_args }), return { tactic.add_coinductive_predicate.coind_pred . pd_name := c.local_uniq_name, type := c.local_type, f₁ := f₁, f₂ := f₂, u_f := u_f, intros := intros, locals := ls, params := params, u_names := u_names }), /- Introduce all functionals -/ pds.mmap' (λpd:coind_pred, do let func_f₁ := pd.func_g.app_of_list $ fs₁, let func_f₂ := pd.func_g.app_of_list $ fs₂, /- Define functional for `pd` as inductive predicate -/ func_intros ← pd.intros.mmap (λr:coind_rule, do let t := instantiate_local pd.f₂.local_uniq_name (pd.func_g.app_of_list fs₁) r.loc_type, return (r.func_nm, r.orig_nm, t.pis $ params ++ fs₁)), add_inductive pd.func.const_name u_names (params.length + preds.length) (pd.type.pis $ params ++ fs₁) (func_intros.map $ λ⟨t, _, r⟩, (t, r)), /- Prove monotonicity rule -/ mono_params ← pds.mmap (λpd, do h ← mk_local_def `h $ pd.le pd.f₁ pd.f₂, return [pd.f₁, pd.f₂, h]), pd.add_theorem (pd.func.const_name ++ "mono") ((pd.le func_f₁ func_f₂).pis $ params ++ mono_params.join) (do ps ← intro_lst $ params.map expr.local_pp_name, fs ← pds.mmap (λpd, do [f₁, f₂, h] ← intro_lst [pd.f₁.local_pp_name, pd.f₂.local_pp_name, `h], -- the type of h' reduces to h let h' := local_const h.local_uniq_name h.local_pp_name h.local_binder_info $ (((const `implies [] : expr) (f₁.app_of_list pd.locals) (f₂.app_of_list pd.locals)).pis pd.locals).instantiate_locals $ (ps.zip params).map $ λ⟨lv, p⟩, (p.local_uniq_name, lv), return (f₂, h')), m ← pd.rec', eapply $ m.app_of_list ps, -- somehow `induction` / `cases` doesn't work? func_intros.mmap' (λ⟨n, pp_n, t⟩, solve1 $ do bs ← intros, ms ← apply_core ((const n u_params).app_of_list $ ps ++ fs.map prod.fst) {new_goals := new_goals.all}, params ← (ms.zip bs).enum.mfilter (λ⟨n, m, d⟩, bnot <$> is_assigned m), params.mmap' (λ⟨n, m, d⟩, mono d (fs.map prod.snd) <|> fail format! "failed to prove montonoicity of {n+1}. parameter of intro-rule {pp_n}")))), pds.mmap' (λpd, do let func_f := λpd:coind_pred, pd.func_g.app_of_list $ pds.map coind_pred.f₁, /- define final predicate -/ pred_body ← mk_exists_lst (pds.map coind_pred.f₁) $ mk_and_lst $ (pds.map $ λpd, pd.le pd.f₁ (func_f pd)) ++ [pd.f₁.app_of_list pd.locals], add_decl $ mk_definition pd.pd_name u_names (pd.type.pis $ params) $ pred_body.lambdas $ params ++ pd.locals, /- prove `corec_functional` rule -/ hs ← pds.mmap $ λpd:coind_pred, mk_local_def `hc $ pd.le pd.f₁ (func_f pd), pd.add_theorem (pd.pred.const_name ++ "corec_functional") ((pd.le pd.f₁ pd.pred_g).pis $ params ++ fs₁ ++ hs) (do intro_lst $ params.map local_pp_name, fs ← intro_lst $ fs₁.map local_pp_name, hs ← intro_lst $ hs.map local_pp_name, ls ← intro_lst $ pd.locals.map local_pp_name, h ← intro `h, whnf_target, fs.mmap' existsi, hs.mmap' (λf, econstructor >> exact f), exact h)), let func_f := λpd : coind_pred, pd.func_g.app_of_list $ pds.map coind_pred.pred_g, /- prove `destruct` rules -/ pds.enum.mmap' (λ⟨n, pd⟩, do let destruct := pd.le pd.pred_g (func_f pd), pd.add_theorem (pd.pred.const_name ++ "destruct") (destruct.pis params) (do ps ← intro_lst $ params.map local_pp_name, ls ← intro_lst $ pd.locals.map local_pp_name, h ← intro `h, (fs, h) ← elim_gen_prod pds.length h [], (hs, h) ← elim_gen_prod pds.length h [], eapply $ pd.mono.app_of_list ps, pds.mmap' (λpd:coind_pred, focus1 $ do eapply $ pd.corec_functional, focus $ hs.map exact), some h' ← return $ hs.nth n, eapply h', exact h)), /- prove `construct` rules -/ pds.mmap' (λpd, pd.add_theorem (pd.pred.const_name ++ "construct") ((pd.le (func_f pd) pd.pred_g).pis params) (do ps ← intro_lst $ params.map local_pp_name, let func_pred_g := λpd:coind_pred, pd.func.app_of_list $ ps ++ pds.map (λpd:coind_pred, pd.pred.app_of_list ps), eapply $ pd.corec_functional.app_of_list $ ps ++ pds.map func_pred_g, pds.mmap' (λpd:coind_pred, solve1 $ do eapply $ pd.mono.app_of_list ps, pds.mmap' (λpd, solve1 $ eapply $ pd.destruct.app_of_list ps)))), /- prove `cases_on` rules -/ pds.mmap' (λpd, do let C := pd.f₁.to_implicit_binder, h ← mk_local_def `h $ pd.pred_g.app_of_list pd.locals, rules ← pd.intros.mmap (λr:coind_rule, do mk_local_def (mk_simple_name r.orig_nm.last_string) $ (C.app_of_list r.insts).pis r.args), cases_on ← pd.add_theorem (pd.pred.const_name ++ "cases_on") ((C.app_of_list pd.locals).pis $ params ++ [C] ++ pd.impl_locals ++ [h] ++ rules) (do ps ← intro_lst $ params.map local_pp_name, C ← intro `C, ls ← intro_lst $ pd.locals.map local_pp_name, h ← intro `h, rules ← intro_lst $ rules.map local_pp_name, func_rec ← pd.rec', eapply $ func_rec.app_of_list $ ps ++ pds.map (λpd, pd.pred.app_of_list ps) ++ [C] ++ rules, eapply $ pd.destruct, exact h), set_basic_attribute `elab_as_eliminator cases_on.const_name), /- prove `corec_on` rules -/ pds.mmap' (λpd, do rules ← pds.mmap (λpd, do intros ← pd.intros.mmap (λr, do let (bs, eqs) := compact_relation r.loc_args $ pd.locals.zip r.insts, eqs ← eqs.mmap (λ⟨l, i⟩, do sort u ← infer_type l.local_type, return $ (const `eq [u] : expr) l.local_type i l), match bs, eqs with | [], [] := return ((0, 0), mk_true) | _, [] := prod.mk (bs.length, 0) <$> mk_exists_lst bs.init bs.ilast.local_type | _, _ := prod.mk (bs.length, eqs.length) <$> mk_exists_lst bs (mk_and_lst eqs) end), let shape := intros.map prod.fst, let intros := intros.map prod.snd, prod.mk shape <$> mk_local_def (mk_simple_name $ "h_" ++ pd.pd_name.last_string) (((pd.f₁.app_of_list pd.locals).imp (mk_or_lst intros)).pis pd.locals)), let shape := rules.map prod.fst, let rules := rules.map prod.snd, h ← mk_local_def `h $ pd.f₁.app_of_list pd.locals, pd.add_theorem (pd.pred.const_name ++ "corec_on") ((pd.pred_g.app_of_list $ pd.locals).pis $ params ++ fs₁ ++ pd.impl_locals ++ [h] ++ rules) (do ps ← intro_lst $ params.map local_pp_name, fs ← intro_lst $ fs₁.map local_pp_name, ls ← intro_lst $ pd.locals.map local_pp_name, h ← intro `h, rules ← intro_lst $ rules.map local_pp_name, eapply $ pd.corec_functional.app_of_list $ ps ++ fs, (pds.zip $ rules.zip shape).mmap (λ⟨pd, hr, s⟩, solve1 $ do ls ← intro_lst $ pd.locals.map local_pp_name, h' ← intro `h, h' ← note `h' none $ hr.app_of_list ls h', match s.length with | 0 := induction h' >> skip -- h' : false | (n+1) := do hs ← elim_gen_sum n h', (hs.zip $ pd.intros.zip s).mmap' (λ⟨h, r, n_bs, n_eqs⟩, solve1 $ do (as, h) ← elim_gen_prod (n_bs - (if n_eqs = 0 then 1 else 0)) h [], if n_eqs > 0 then do (eqs, eq') ← elim_gen_prod (n_eqs - 1) h [], (eqs ++ [eq']).mmap' subst else skip, eapply ((const r.func_nm u_params).app_of_list $ ps ++ fs), repeat assumption) end), exact h)), /- prove constructors -/ pds.mmap' (λpd, pd.intros.mmap' (λr, pd.add_theorem r.orig_nm (r.type.pis params) $ do ps ← intro_lst $ params.map local_pp_name, bs ← intros, eapply $ pd.construct, exact $ (const r.func_nm u_params).app_of_list $ ps ++ pds.map (λpd, pd.pred.app_of_list ps) ++ bs)), pds.mmap' (λpd:coind_pred, set_basic_attribute `irreducible pd.pd_name), try triv -- we setup a trivial goal for the tactic framework open lean.parser open interactive @[user_command] meta def coinductive_predicate (meta_info : decl_meta_info) (_ : parse $ tk "coinductive") : lean.parser unit := do decl ← inductive_decl.parse meta_info, add_coinductive_predicate decl.u_names decl.params $ decl.decls.map $ λ d, (d.sig, d.intros), decl.decls.mmap' $ λ d, do { get_env >>= λ env, set_env $ env.add_namespace d.name, meta_info.attrs.apply d.name, d.attrs.apply d.name, some doc_string ← pure meta_info.doc_string | skip, add_doc_string d.name doc_string } /-- Prepares coinduction proofs. This tactic constructs the coinduction invariant from the quantifiers in the current goal. Current version: do not support mutual inductive rules (i.e. only a since C -/ meta def coinduction (rule : expr) : tactic unit := focus1 $ do ctxts' ← intros, -- TODO: why do we need to fix the type here? ctxts ← ctxts'.mmap (λv, local_const v.local_uniq_name v.local_pp_name v.local_binder_info <$> infer_type v), mvars ← apply_core rule {approx := ff, new_goals := new_goals.all}, -- analyse relation g ← list.head <$> get_goals, (list.cons _ m_is) ← return $ mvars.drop_while (λv, v ≠ g), tgt ← target, (is, ty) ← mk_local_pis tgt, -- construct coinduction predicate (bs, eqs) ← compact_relation ctxts <$> ((is.zip m_is).mmap (λ⟨i, m⟩, prod.mk i <$> instantiate_mvars m)), solve1 (do eqs ← mk_and_lst <$> eqs.mmap (λ⟨i, m⟩, mk_app `eq [m, i] >>= instantiate_mvars), rel ← mk_exists_lst bs eqs, exact (rel.lambdas is)), -- prove predicate solve1 (do target >>= instantiate_mvars >>= change, -- TODO: bug in existsi & constructor when mvars in hyptohesis bs.mmap existsi, repeat econstructor), -- clean up remaining coinduction steps all_goals (do ctxts'.reverse.mmap clear, target >>= instantiate_mvars >>= change, -- TODO: bug in subst when mvars in hyptohesis is ← intro_lst $ is.map expr.local_pp_name, h ← intro1, (_, h) ← elim_gen_prod (bs.length - (if eqs.length = 0 then 1 else 0)) h [], (match eqs with | [] := clear h | (e::eqs) := do (hs, h) ← elim_gen_prod eqs.length h [], (h::(hs.reverse)).mmap' subst end)) namespace interactive open interactive interactive.types expr lean.parser local postfix `?`:9001 := optional local postfix *:9001 := many meta def coinduction (corec_name : parse ident) (revert : parse $ (tk "generalizing" *> ident*)?) : tactic unit := do rule ← mk_const corec_name, locals ← mmap tactic.get_local $ revert.get_or_else [], revert_lst locals, tactic.coinduction rule, skip end interactive end tactic
614572061017bb75374953d94ef43ea68e3d068c
64874bd1010548c7f5a6e3e8902efa63baaff785
/tests/lean/run/uni2.lean
625e03a5031f055225a22d19e14e7025a3f125c9
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,363
lean
import logic namespace experiment inductive nat : Type := zero : nat, succ : nat → nat constant f : nat → nat check @nat.rec (* local env = get_env() local nat_rec = Const({"nat", "rec"}, {1}) local nat = Const("nat") local f = Const("f") local n = Local("n", nat) local C = Fun(n, Prop) local p = Local("p", Prop) local ff = Const("false") local tt = Const("true") local t = nat_rec(C, ff, Fun(n, p, tt)) local zero = Const("zero") local succ = Const("succ") local one = succ(zero) local tc = type_checker(env) print(env:whnf(t(one))) print(env:whnf(t(zero))) local m = mk_metavar("m", nat) print(env:whnf(t(m))) function test_unify(env, lhs, rhs, num_s) print(tostring(lhs) .. " =?= " .. tostring(rhs) .. ", expected: " .. tostring(num_s)) local ss = unify(env, lhs, rhs, name_generator(), true, substitution(), options()) local n = 0 for s in ss do print("solution: ") s:for_each_expr(function(n, v, j) print(" " .. tostring(n) .. " := " .. tostring(v)) end) s:for_each_level(function(n, v, j) print(" " .. tostring(n) .. " := " .. tostring(v)) end) n = n + 1 end if num_s ~= n then print("n: " .. n) end assert(num_s == n) end test_unify(env, f(t(m)), f(tt), 1) *) exit