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
5eb6455c4d154e4473df9066630f2e4ee6a811e9
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/tests/lean/run/simp7.lean
0557b6c5bfe3e297a88112901f963e39f25a5ad1
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
1,405
lean
def f (x : α) := x theorem ex1 (a : α) (b : List α) : f (a::b = []) = False := by simp [f] def length : List α → Nat | [] => 0 | a::as => length as + 1 theorem ex2 (a b c : α) (as : List α) : length (a :: b :: as) > length as := by simp [length] apply Nat.lt.step apply Nat.ltSuccSelf def fact : Nat → Nat | 0 => 1 | x+1 => (x+1) * fact x theorem ex3 : fact x > 0 := by induction x with | zero => rfl | succ x ih => simp [fact] apply Nat.mulPos apply Nat.zeroLtSucc apply ih def head [Inhabited α] : List α → α | [] => arbitrary | a::_ => a theorem ex4 [Inhabited α] (a : α) (as : List α) : head (a::as) = a := by simp [head] def foo := 10 theorem ex5 (x : Nat) : foo + x = 10 + x := by simp [foo] done def g (x : Nat) : Nat := do let x ← pure x return x theorem ex6 : g x = x := by simp [g, bind, pure] def f1 : StateM Nat Unit := do modify fun x => g x def f2 : StateM Nat Unit := do let s ← get set <| g s theorem ex7 : f1 = f2 := by simp [f1, f2, bind, StateT.bind, get, getThe, MonadStateOf.get, StateT.get, pure, set, StateT.set, modify, modifyGet, MonadStateOf.modifyGet, StateT.modifyGet] def h (x : Nat) : Sum (Nat × Nat) Nat := Sum.inl (x, x) def bla (x : Nat) := match h x with | Sum.inl (y, z) => y + z | Sum.inr _ => 0 theorem ex8 (x : Nat) : bla x = x + x := by simp [bla, h]
2530ac2b3c71bfe3ee7c093362c25bea51f78ff6
b9dd0f3640eda42cdd8d97060417cb19d5c00eaf
/src/basic.lean
b3bf459f3241461bd1f36eafab1f021e8d23b264
[]
no_license
foxthomson/guessgame
20e3e5854d0a5c1a26335914446c827a711ee53e
96d542b574949a883a9ed216a4f78e195d61878a
refs/heads/master
1,670,822,903,666
1,599,562,332,000
1,599,562,332,000
293,782,243
0
0
null
null
null
null
UTF-8
Lean
false
false
1,829
lean
import system.random.basic import tactic def nat_of_Icc (a : set.Icc 1 100) : ℕ := begin cases a with val, exact val end @[derive has_reflect] structure game := ( target : ℕ ) ( guesses : ℕ ) def game_to_nat := λ g : game, g.target def game.inc_guess : game → game | ⟨ n, m ⟩ := ⟨ n, m.succ ⟩ def game.inc_guess_ex {n m} : (∃ x : game, game.mk n m = x) → (∃ x : game, game.mk n m.succ = x) | ⟨ x, hx ⟩ := ⟨ x.inc_guess, begin rw ← hx, refl end ⟩ def start_game (n) : game := ⟨ n, 7 ⟩ meta def ex (a : game) : tactic expr := tactic.to_expr ``(∃ x, %%a = x) meta def mk_random_game : tactic expr := do start_game <$> nat_of_Icc <$> tactic.random_r 1 100 (by norm_num) >>= ex >>= tactic.assert `target meta def guess (n : ℕ) : tactic unit := do `(∃ x : game, %%a = x) ← tactic.target, do { tactic.to_expr ``(game_to_nat %%a = %%n) >>= tactic.assert `result, tactic.solve1 (tactic.exact_dec_trivial), tactic.trace "Congratulations!!", tactic.tautology } <|> do { ( do { tactic.to_expr ``(game_to_nat %%a < %%n) >>= tactic.assert `result, tactic.solve1 (tactic.exact_dec_trivial) } <|> do { tactic.to_expr ``(game_to_nat %%a > %%n) >>= tactic.assert `result, tactic.solve1 (tactic.exact_dec_trivial) } ), ( do { tactic.interactive.apply ``(game.inc_guess_ex), `(game.mk %%n %%g) ← tactic.to_expr ``(%%a), expr.to_nat <$> tactic.to_expr ``(%%g) >>= λ x, option.cases_on' x (tactic.trace "hello") (λ (guesses : ℕ), tactic.trace $ repr guesses ++ " guesses left") } <|> do { tactic.trace "out of guesses", tactic.failed } ) } notation `*` := game.mk _ _
49e71d896d5f56680431211adda5d6c687ddb7a9
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/fintype/powerset.lean
220c0be08d56588e42122f9319546da0f29208d5
[ "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
2,068
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.fintype.card import data.finset.powerset /-! # fintype instance for `set α`, when `α` is a fintype -/ variables {α : Type*} open finset instance finset.fintype [fintype α] : fintype (finset α) := ⟨univ.powerset, λ x, finset.mem_powerset.2 (finset.subset_univ _)⟩ @[simp] lemma fintype.card_finset [fintype α] : fintype.card (finset α) = 2 ^ (fintype.card α) := finset.card_powerset finset.univ @[simp] lemma finset.powerset_univ [fintype α] : (univ : finset α).powerset = univ := coe_injective $ by simp [-coe_eq_univ] @[simp] lemma finset.powerset_eq_univ [fintype α] {s : finset α} : s.powerset = univ ↔ s = univ := by rw [←finset.powerset_univ, powerset_inj] lemma finset.mem_powerset_len_univ_iff [fintype α] {s : finset α} {k : ℕ} : s ∈ powerset_len k (univ : finset α) ↔ card s = k := mem_powerset_len.trans $ and_iff_right $ subset_univ _ @[simp] lemma finset.univ_filter_card_eq (α : Type*) [fintype α] (k : ℕ) : (finset.univ : finset (finset α)).filter (λ s, s.card = k) = finset.univ.powerset_len k := by { ext, simp [finset.mem_powerset_len] } @[simp] lemma fintype.card_finset_len [fintype α] (k : ℕ) : fintype.card {s : finset α // s.card = k} = nat.choose (fintype.card α) k := by simp [fintype.subtype_card, finset.card_univ] instance set.fintype [fintype α] : fintype (set α) := ⟨(@finset.univ α _).powerset.map ⟨coe, coe_injective⟩, λ s, begin classical, refine mem_map.2 ⟨finset.univ.filter s, mem_powerset.2 (subset_univ _), _⟩, apply (coe_filter _ _).trans, rw [coe_univ, set.sep_univ], refl end⟩ -- Not to be confused with `set.finite`, the predicate instance set.finite' [finite α] : finite (set α) := by { casesI nonempty_fintype α, apply_instance } @[simp] lemma fintype.card_set [fintype α] : fintype.card (set α) = 2 ^ fintype.card α := (finset.card_map _).trans (finset.card_powerset _)
64f7648c05a49c82fe1033639129f1e479f94f81
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/analysis/normed_space/finite_dimension.lean
5d6cd07bd40a27ecf3f347a4acacf79c51df3ea2
[ "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
36,101
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.asymptotics.asymptotic_equivalent import analysis.normed_space.affine_isometry import analysis.normed_space.operator_norm import analysis.normed_space.riesz_lemma import linear_algebra.matrix.to_lin import topology.algebra.module.finite_dimension import topology.instances.matrix /-! # Finite dimensional normed spaces over complete fields Over a complete nontrivially normed field, in finite dimension, all norms are equivalent and all linear maps are continuous. Moreover, a finite-dimensional subspace is always complete and closed. ## Main results: * `finite_dimensional.complete` : a finite-dimensional space over a complete field is complete. This is not registered as an instance, as the field would be an unknown metavariable in typeclass resolution. * `submodule.closed_of_finite_dimensional` : a finite-dimensional subspace over a complete field is closed * `finite_dimensional.proper` : a finite-dimensional space over a proper field is proper. This is not registered as an instance, as the field would be an unknown metavariable in typeclass resolution. It is however registered as an instance for `𝕜 = ℝ` and `𝕜 = ℂ`. As properness implies completeness, there is no need to also register `finite_dimensional.complete` on `ℝ` or `ℂ`. * `finite_dimensional_of_is_compact_closed_ball`: Riesz' theorem: if the closed unit ball is compact, then the space is finite-dimensional. ## Implementation notes The fact that all norms are equivalent is not written explicitly, as it would mean having two norms on a single space, which is not the way type classes work. However, if one has a finite-dimensional vector space `E` with a norm, and a copy `E'` of this type with another norm, then the identities from `E` to `E'` and from `E'`to `E` are continuous thanks to `linear_map.continuous_of_finite_dimensional`. This gives the desired norm equivalence. -/ universes u v w x noncomputable theory open set finite_dimensional topological_space filter asymptotics open_locale classical big_operators filter topological_space asymptotics nnreal namespace linear_isometry open linear_map variables {R : Type*} [semiring R] variables {F E₁ : Type*} [seminormed_add_comm_group F] [normed_add_comm_group E₁] [module R E₁] variables {R₁ : Type*} [field R₁] [module R₁ E₁] [module R₁ F] [finite_dimensional R₁ E₁] [finite_dimensional R₁ F] /-- A linear isometry between finite dimensional spaces of equal dimension can be upgraded to a linear isometry equivalence. -/ def to_linear_isometry_equiv (li : E₁ →ₗᵢ[R₁] F) (h : finrank R₁ E₁ = finrank R₁ F) : E₁ ≃ₗᵢ[R₁] F := { to_linear_equiv := li.to_linear_map.linear_equiv_of_injective li.injective h, norm_map' := li.norm_map' } @[simp] lemma coe_to_linear_isometry_equiv (li : E₁ →ₗᵢ[R₁] F) (h : finrank R₁ E₁ = finrank R₁ F) : (li.to_linear_isometry_equiv h : E₁ → F) = li := rfl @[simp] lemma to_linear_isometry_equiv_apply (li : E₁ →ₗᵢ[R₁] F) (h : finrank R₁ E₁ = finrank R₁ F) (x : E₁) : (li.to_linear_isometry_equiv h) x = li x := rfl end linear_isometry namespace affine_isometry open affine_map variables {𝕜 : Type*} {V₁ V₂ : Type*} {P₁ P₂ : Type*} [normed_field 𝕜] [normed_add_comm_group V₁] [seminormed_add_comm_group V₂] [normed_space 𝕜 V₁] [normed_space 𝕜 V₂] [metric_space P₁] [pseudo_metric_space P₂] [normed_add_torsor V₁ P₁] [normed_add_torsor V₂ P₂] variables [finite_dimensional 𝕜 V₁] [finite_dimensional 𝕜 V₂] /-- An affine isometry between finite dimensional spaces of equal dimension can be upgraded to an affine isometry equivalence. -/ def to_affine_isometry_equiv [inhabited P₁] (li : P₁ →ᵃⁱ[𝕜] P₂) (h : finrank 𝕜 V₁ = finrank 𝕜 V₂) : P₁ ≃ᵃⁱ[𝕜] P₂ := affine_isometry_equiv.mk' li (li.linear_isometry.to_linear_isometry_equiv h) (arbitrary P₁) (λ p, by simp) @[simp] lemma coe_to_affine_isometry_equiv [inhabited P₁] (li : P₁ →ᵃⁱ[𝕜] P₂) (h : finrank 𝕜 V₁ = finrank 𝕜 V₂) : (li.to_affine_isometry_equiv h : P₁ → P₂) = li := rfl @[simp] lemma to_affine_isometry_equiv_apply [inhabited P₁] (li : P₁ →ᵃⁱ[𝕜] P₂) (h : finrank 𝕜 V₁ = finrank 𝕜 V₂) (x : P₁) : (li.to_affine_isometry_equiv h) x = li x := rfl end affine_isometry section complete_field variables {𝕜 : Type u} [nontrivially_normed_field 𝕜] {E : Type v} [normed_add_comm_group E] [normed_space 𝕜 E] {F : Type w} [normed_add_comm_group F] [normed_space 𝕜 F] {F' : Type x} [add_comm_group F'] [module 𝕜 F'] [topological_space F'] [topological_add_group F'] [has_continuous_smul 𝕜 F'] [complete_space 𝕜] section affine variables {PE PF : Type*} [metric_space PE] [normed_add_torsor E PE] [metric_space PF] [normed_add_torsor F PF] [finite_dimensional 𝕜 E] include E F theorem affine_map.continuous_of_finite_dimensional (f : PE →ᵃ[𝕜] PF) : continuous f := affine_map.continuous_linear_iff.1 f.linear.continuous_of_finite_dimensional theorem affine_equiv.continuous_of_finite_dimensional (f : PE ≃ᵃ[𝕜] PF) : continuous f := f.to_affine_map.continuous_of_finite_dimensional /-- Reinterpret an affine equivalence as a homeomorphism. -/ def affine_equiv.to_homeomorph_of_finite_dimensional (f : PE ≃ᵃ[𝕜] PF) : PE ≃ₜ PF := { to_equiv := f.to_equiv, continuous_to_fun := f.continuous_of_finite_dimensional, continuous_inv_fun := begin haveI : finite_dimensional 𝕜 F, from f.linear.finite_dimensional, exact f.symm.continuous_of_finite_dimensional end } @[simp] lemma affine_equiv.coe_to_homeomorph_of_finite_dimensional (f : PE ≃ᵃ[𝕜] PF) : ⇑f.to_homeomorph_of_finite_dimensional = f := rfl @[simp] lemma affine_equiv.coe_to_homeomorph_of_finite_dimensional_symm (f : PE ≃ᵃ[𝕜] PF) : ⇑f.to_homeomorph_of_finite_dimensional.symm = f.symm := rfl end affine lemma continuous_linear_map.continuous_det : continuous (λ (f : E →L[𝕜] E), f.det) := begin change continuous (λ (f : E →L[𝕜] E), (f : E →ₗ[𝕜] E).det), by_cases h : ∃ (s : finset E), nonempty (basis ↥s 𝕜 E), { rcases h with ⟨s, ⟨b⟩⟩, haveI : finite_dimensional 𝕜 E := finite_dimensional.of_finset_basis b, simp_rw linear_map.det_eq_det_to_matrix_of_finset b, refine continuous.matrix_det _, exact ((linear_map.to_matrix b b).to_linear_map.comp (continuous_linear_map.coe_lm 𝕜)).continuous_of_finite_dimensional }, { unfold linear_map.det, simpa only [h, monoid_hom.one_apply, dif_neg, not_false_iff] using continuous_const } end /-- Any `K`-Lipschitz map from a subset `s` of a metric space `α` to a finite-dimensional real vector space `E'` can be extended to a Lipschitz map on the whole space `α`, with a slightly worse constant `C * K` where `C` only depends on `E'`. We record a working value for this constant `C` as `lipschitz_extension_constant E'`. -/ @[irreducible] def lipschitz_extension_constant (E' : Type*) [normed_add_comm_group E'] [normed_space ℝ E'] [finite_dimensional ℝ E'] : ℝ≥0 := let A := (basis.of_vector_space ℝ E').equiv_fun.to_continuous_linear_equiv in max (∥A.symm.to_continuous_linear_map∥₊ * ∥A.to_continuous_linear_map∥₊) 1 lemma lipschitz_extension_constant_pos (E' : Type*) [normed_add_comm_group E'] [normed_space ℝ E'] [finite_dimensional ℝ E'] : 0 < lipschitz_extension_constant E' := by { rw lipschitz_extension_constant, exact zero_lt_one.trans_le (le_max_right _ _) } /-- Any `K`-Lipschitz map from a subset `s` of a metric space `α` to a finite-dimensional real vector space `E'` can be extended to a Lipschitz map on the whole space `α`, with a slightly worse constant `lipschitz_extension_constant E' * K`. -/ theorem lipschitz_on_with.extend_finite_dimension {α : Type*} [pseudo_metric_space α] {E' : Type*} [normed_add_comm_group E'] [normed_space ℝ E'] [finite_dimensional ℝ E'] {s : set α} {f : α → E'} {K : ℝ≥0} (hf : lipschitz_on_with K f s) : ∃ (g : α → E'), lipschitz_with (lipschitz_extension_constant E' * K) g ∧ eq_on f g s := begin /- This result is already known for spaces `ι → ℝ`. We use a continuous linear equiv between `E'` and such a space to transfer the result to `E'`. -/ let ι : Type* := basis.of_vector_space_index ℝ E', let A := (basis.of_vector_space ℝ E').equiv_fun.to_continuous_linear_equiv, have LA : lipschitz_with (∥A.to_continuous_linear_map∥₊) A, by apply A.lipschitz, have L : lipschitz_on_with (∥A.to_continuous_linear_map∥₊ * K) (A ∘ f) s := LA.comp_lipschitz_on_with hf, obtain ⟨g, hg, gs⟩ : ∃ g : α → (ι → ℝ), lipschitz_with (∥A.to_continuous_linear_map∥₊ * K) g ∧ eq_on (A ∘ f) g s := L.extend_pi, refine ⟨A.symm ∘ g, _, _⟩, { have LAsymm : lipschitz_with (∥A.symm.to_continuous_linear_map∥₊) A.symm, by apply A.symm.lipschitz, apply (LAsymm.comp hg).weaken, rw [lipschitz_extension_constant, ← mul_assoc], refine mul_le_mul' (le_max_left _ _) le_rfl }, { assume x hx, have : A (f x) = g x := gs hx, simp only [(∘), ← this, A.symm_apply_apply] } end lemma linear_map.exists_antilipschitz_with [finite_dimensional 𝕜 E] (f : E →ₗ[𝕜] F) (hf : f.ker = ⊥) : ∃ K > 0, antilipschitz_with K f := begin cases subsingleton_or_nontrivial E; resetI, { exact ⟨1, zero_lt_one, antilipschitz_with.of_subsingleton⟩ }, { rw linear_map.ker_eq_bot at hf, let e : E ≃L[𝕜] f.range := (linear_equiv.of_injective f hf).to_continuous_linear_equiv, exact ⟨_, e.nnnorm_symm_pos, e.antilipschitz⟩ } end protected lemma linear_independent.eventually {ι} [fintype ι] {f : ι → E} (hf : linear_independent 𝕜 f) : ∀ᶠ g in 𝓝 f, linear_independent 𝕜 g := begin simp only [fintype.linear_independent_iff'] at hf ⊢, rcases linear_map.exists_antilipschitz_with _ hf with ⟨K, K0, hK⟩, have : tendsto (λ g : ι → E, ∑ i, ∥g i - f i∥) (𝓝 f) (𝓝 $ ∑ i, ∥f i - f i∥), from tendsto_finset_sum _ (λ i hi, tendsto.norm $ ((continuous_apply i).tendsto _).sub tendsto_const_nhds), simp only [sub_self, norm_zero, finset.sum_const_zero] at this, refine (this.eventually (gt_mem_nhds $ inv_pos.2 K0)).mono (λ g hg, _), replace hg : ∑ i, ∥g i - f i∥₊ < K⁻¹, by { rw ← nnreal.coe_lt_coe, push_cast, exact hg }, rw linear_map.ker_eq_bot, refine (hK.add_sub_lipschitz_with (lipschitz_with.of_dist_le_mul $ λ v u, _) hg).injective, simp only [dist_eq_norm, linear_map.lsum_apply, pi.sub_apply, linear_map.sum_apply, linear_map.comp_apply, linear_map.proj_apply, linear_map.smul_right_apply, linear_map.id_apply, ← finset.sum_sub_distrib, ← smul_sub, ← sub_smul, nnreal.coe_sum, coe_nnnorm, finset.sum_mul], refine norm_sum_le_of_le _ (λ i _, _), rw [norm_smul, mul_comm], exact mul_le_mul_of_nonneg_left (norm_le_pi_norm (v - u) i) (norm_nonneg _) end lemma is_open_set_of_linear_independent {ι : Type*} [fintype ι] : is_open {f : ι → E | linear_independent 𝕜 f} := is_open_iff_mem_nhds.2 $ λ f, linear_independent.eventually lemma is_open_set_of_nat_le_rank (n : ℕ) : is_open {f : E →L[𝕜] F | ↑n ≤ rank (f : E →ₗ[𝕜] F)} := begin simp only [le_rank_iff_exists_linear_independent_finset, set_of_exists, ← exists_prop], refine is_open_bUnion (λ t ht, _), have : continuous (λ f : E →L[𝕜] F, (λ x : (t : set E), f x)), from continuous_pi (λ x, (continuous_linear_map.apply 𝕜 F (x : E)).continuous), exact is_open_set_of_linear_independent.preimage this end /-- Two finite-dimensional normed spaces are continuously linearly equivalent if they have the same (finite) dimension. -/ theorem finite_dimensional.nonempty_continuous_linear_equiv_of_finrank_eq [finite_dimensional 𝕜 E] [finite_dimensional 𝕜 F] (cond : finrank 𝕜 E = finrank 𝕜 F) : nonempty (E ≃L[𝕜] F) := (nonempty_linear_equiv_of_finrank_eq cond).map linear_equiv.to_continuous_linear_equiv /-- Two finite-dimensional normed spaces are continuously linearly equivalent if and only if they have the same (finite) dimension. -/ theorem finite_dimensional.nonempty_continuous_linear_equiv_iff_finrank_eq [finite_dimensional 𝕜 E] [finite_dimensional 𝕜 F] : nonempty (E ≃L[𝕜] F) ↔ finrank 𝕜 E = finrank 𝕜 F := ⟨ λ ⟨h⟩, h.to_linear_equiv.finrank_eq, λ h, finite_dimensional.nonempty_continuous_linear_equiv_of_finrank_eq h ⟩ /-- A continuous linear equivalence between two finite-dimensional normed spaces of the same (finite) dimension. -/ def continuous_linear_equiv.of_finrank_eq [finite_dimensional 𝕜 E] [finite_dimensional 𝕜 F] (cond : finrank 𝕜 E = finrank 𝕜 F) : E ≃L[𝕜] F := (linear_equiv.of_finrank_eq E F cond).to_continuous_linear_equiv variables {ι : Type*} [fintype ι] /-- Construct a continuous linear map given the value at a finite basis. -/ def basis.constrL (v : basis ι 𝕜 E) (f : ι → F) : E →L[𝕜] F := by haveI : finite_dimensional 𝕜 E := finite_dimensional.of_fintype_basis v; exact (v.constr 𝕜 f).to_continuous_linear_map @[simp, norm_cast] lemma basis.coe_constrL (v : basis ι 𝕜 E) (f : ι → F) : (v.constrL f : E →ₗ[𝕜] F) = v.constr 𝕜 f := rfl /-- The continuous linear equivalence between a vector space over `𝕜` with a finite basis and functions from its basis indexing type to `𝕜`. -/ def basis.equiv_funL (v : basis ι 𝕜 E) : E ≃L[𝕜] (ι → 𝕜) := { continuous_to_fun := begin haveI : finite_dimensional 𝕜 E := finite_dimensional.of_fintype_basis v, exact v.equiv_fun.to_linear_map.continuous_of_finite_dimensional, end, continuous_inv_fun := begin change continuous v.equiv_fun.symm.to_fun, exact v.equiv_fun.symm.to_linear_map.continuous_of_finite_dimensional, end, ..v.equiv_fun } @[simp] lemma basis.constrL_apply (v : basis ι 𝕜 E) (f : ι → F) (e : E) : (v.constrL f) e = ∑ i, (v.equiv_fun e i) • f i := v.constr_apply_fintype 𝕜 _ _ @[simp] lemma basis.constrL_basis (v : basis ι 𝕜 E) (f : ι → F) (i : ι) : (v.constrL f) (v i) = f i := v.constr_basis 𝕜 _ _ lemma basis.op_nnnorm_le {ι : Type*} [fintype ι] (v : basis ι 𝕜 E) {u : E →L[𝕜] F} (M : ℝ≥0) (hu : ∀ i, ∥u (v i)∥₊ ≤ M) : ∥u∥₊ ≤ fintype.card ι • ∥v.equiv_funL.to_continuous_linear_map∥₊ * M := u.op_nnnorm_le_bound _ $ λ e, begin set φ := v.equiv_funL.to_continuous_linear_map, calc ∥u e∥₊ = ∥u (∑ i, v.equiv_fun e i • v i)∥₊ : by rw [v.sum_equiv_fun] ... = ∥∑ i, (v.equiv_fun e i) • (u $ v i)∥₊ : by simp [u.map_sum, linear_map.map_smul] ... ≤ ∑ i, ∥(v.equiv_fun e i) • (u $ v i)∥₊ : nnnorm_sum_le _ _ ... = ∑ i, ∥v.equiv_fun e i∥₊ * ∥u (v i)∥₊ : by simp only [nnnorm_smul] ... ≤ ∑ i, ∥v.equiv_fun e i∥₊ * M : finset.sum_le_sum (λ i hi, mul_le_mul_of_nonneg_left (hu i) (zero_le _)) ... = (∑ i, ∥v.equiv_fun e i∥₊) * M : finset.sum_mul.symm ... ≤ fintype.card ι • (∥φ∥₊ * ∥e∥₊) * M : (suffices _, from mul_le_mul_of_nonneg_right this (zero_le M), calc ∑ i, ∥v.equiv_fun e i∥₊ ≤ fintype.card ι • ∥φ e∥₊ : pi.sum_nnnorm_apply_le_nnnorm _ ... ≤ fintype.card ι • (∥φ∥₊ * ∥e∥₊) : nsmul_le_nsmul_of_le_right (φ.le_op_nnnorm e) _) ... = fintype.card ι • ∥φ∥₊ * M * ∥e∥₊ : by simp only [smul_mul_assoc, mul_right_comm], end lemma basis.op_norm_le {ι : Type*} [fintype ι] (v : basis ι 𝕜 E) {u : E →L[𝕜] F} {M : ℝ} (hM : 0 ≤ M) (hu : ∀ i, ∥u (v i)∥ ≤ M) : ∥u∥ ≤ fintype.card ι • ∥v.equiv_funL.to_continuous_linear_map∥ * M := by simpa using nnreal.coe_le_coe.mpr (v.op_nnnorm_le ⟨M, hM⟩ hu) /-- A weaker version of `basis.op_nnnorm_le` that abstracts away the value of `C`. -/ lemma basis.exists_op_nnnorm_le {ι : Type*} [fintype ι] (v : basis ι 𝕜 E) : ∃ C > (0 : ℝ≥0), ∀ {u : E →L[𝕜] F} (M : ℝ≥0), (∀ i, ∥u (v i)∥₊ ≤ M) → ∥u∥₊ ≤ C*M := ⟨ max (fintype.card ι • ∥v.equiv_funL.to_continuous_linear_map∥₊) 1, zero_lt_one.trans_le (le_max_right _ _), λ u M hu, (v.op_nnnorm_le M hu).trans $ mul_le_mul_of_nonneg_right (le_max_left _ _) (zero_le M)⟩ /-- A weaker version of `basis.op_norm_le` that abstracts away the value of `C`. -/ lemma basis.exists_op_norm_le {ι : Type*} [fintype ι] (v : basis ι 𝕜 E) : ∃ C > (0 : ℝ), ∀ {u : E →L[𝕜] F} {M : ℝ}, 0 ≤ M → (∀ i, ∥u (v i)∥ ≤ M) → ∥u∥ ≤ C*M := let ⟨C, hC, h⟩ := v.exists_op_nnnorm_le in ⟨C, hC, λ u, subtype.forall'.mpr h⟩ instance [finite_dimensional 𝕜 E] [second_countable_topology F] : second_countable_topology (E →L[𝕜] F) := begin set d := finite_dimensional.finrank 𝕜 E, suffices : ∀ ε > (0 : ℝ), ∃ n : (E →L[𝕜] F) → fin d → ℕ, ∀ (f g : E →L[𝕜] F), n f = n g → dist f g ≤ ε, from metric.second_countable_of_countable_discretization (λ ε ε_pos, ⟨fin d → ℕ, by apply_instance, this ε ε_pos⟩), intros ε ε_pos, obtain ⟨u : ℕ → F, hu : dense_range u⟩ := exists_dense_seq F, let v := finite_dimensional.fin_basis 𝕜 E, obtain ⟨C : ℝ, C_pos : 0 < C, hC : ∀ {φ : E →L[𝕜] F} {M : ℝ}, 0 ≤ M → (∀ i, ∥φ (v i)∥ ≤ M) → ∥φ∥ ≤ C * M⟩ := v.exists_op_norm_le, have h_2C : 0 < 2*C := mul_pos zero_lt_two C_pos, have hε2C : 0 < ε/(2*C) := div_pos ε_pos h_2C, have : ∀ φ : E →L[𝕜] F, ∃ n : fin d → ℕ, ∥φ - (v.constrL $ u ∘ n)∥ ≤ ε/2, { intros φ, have : ∀ i, ∃ n, ∥φ (v i) - u n∥ ≤ ε/(2*C), { simp only [norm_sub_rev], intro i, have : φ (v i) ∈ closure (range u) := hu _, obtain ⟨n, hn⟩ : ∃ n, ∥u n - φ (v i)∥ < ε / (2 * C), { rw mem_closure_iff_nhds_basis metric.nhds_basis_ball at this, specialize this (ε/(2*C)) hε2C, simpa [dist_eq_norm] }, exact ⟨n, le_of_lt hn⟩ }, choose n hn using this, use n, replace hn : ∀ i : fin d, ∥(φ - (v.constrL $ u ∘ n)) (v i)∥ ≤ ε / (2 * C), by simp [hn], have : C * (ε / (2 * C)) = ε/2, { rw [eq_div_iff (two_ne_zero : (2 : ℝ) ≠ 0), mul_comm, ← mul_assoc, mul_div_cancel' _ (ne_of_gt h_2C)] }, specialize hC (le_of_lt hε2C) hn, rwa this at hC }, choose n hn using this, set Φ := λ φ : E →L[𝕜] F, (v.constrL $ u ∘ (n φ)), change ∀ z, dist z (Φ z) ≤ ε/2 at hn, use n, intros x y hxy, calc dist x y ≤ dist x (Φ x) + dist (Φ x) y : dist_triangle _ _ _ ... = dist x (Φ x) + dist y (Φ y) : by simp [Φ, hxy, dist_comm] ... ≤ ε : by linarith [hn x, hn y] end /-- Any finite-dimensional vector space over a complete field is complete. We do not register this as an instance to avoid an instance loop when trying to prove the completeness of `𝕜`, and the search for `𝕜` as an unknown metavariable. Declare the instance explicitly when needed. -/ variables (𝕜 E) lemma finite_dimensional.complete [finite_dimensional 𝕜 E] : complete_space E := begin set e := continuous_linear_equiv.of_finrank_eq (@finrank_fin_fun 𝕜 _ (finrank 𝕜 E)).symm, have : uniform_embedding e.to_linear_equiv.to_equiv.symm := e.symm.uniform_embedding, exact (complete_space_congr this).1 (by apply_instance) end variables {𝕜 E} /-- A finite-dimensional subspace is complete. -/ lemma submodule.complete_of_finite_dimensional (s : submodule 𝕜 E) [finite_dimensional 𝕜 s] : is_complete (s : set E) := complete_space_coe_iff_is_complete.1 (finite_dimensional.complete 𝕜 s) /-- A finite-dimensional subspace is closed. -/ lemma submodule.closed_of_finite_dimensional (s : submodule 𝕜 E) [finite_dimensional 𝕜 s] : is_closed (s : set E) := s.complete_of_finite_dimensional.is_closed lemma affine_subspace.closed_of_finite_dimensional {P : Type*} [metric_space P] [normed_add_torsor E P] (s : affine_subspace 𝕜 P) [finite_dimensional 𝕜 s.direction] : is_closed (s : set P) := s.is_closed_direction_iff.mp s.direction.closed_of_finite_dimensional section riesz /-- In an infinite dimensional space, given a finite number of points, one may find a point with norm at most `R` which is at distance at least `1` of all these points. -/ theorem exists_norm_le_le_norm_sub_of_finset {c : 𝕜} (hc : 1 < ∥c∥) {R : ℝ} (hR : ∥c∥ < R) (h : ¬ (finite_dimensional 𝕜 E)) (s : finset E) : ∃ (x : E), ∥x∥ ≤ R ∧ ∀ y ∈ s, 1 ≤ ∥y - x∥ := begin let F := submodule.span 𝕜 (s : set E), haveI : finite_dimensional 𝕜 F := module.finite_def.2 ((submodule.fg_top _).2 (submodule.fg_def.2 ⟨s, finset.finite_to_set _, rfl⟩)), have Fclosed : is_closed (F : set E) := submodule.closed_of_finite_dimensional _, have : ∃ x, x ∉ F, { contrapose! h, have : (⊤ : submodule 𝕜 E) = F, by { ext x, simp [h] }, have : finite_dimensional 𝕜 (⊤ : submodule 𝕜 E), by rwa this, refine module.finite_def.2 ((submodule.fg_top _).1 (module.finite_def.1 this)) }, obtain ⟨x, xR, hx⟩ : ∃ (x : E), ∥x∥ ≤ R ∧ ∀ (y : E), y ∈ F → 1 ≤ ∥x - y∥ := riesz_lemma_of_norm_lt hc hR Fclosed this, have hx' : ∀ (y : E), y ∈ F → 1 ≤ ∥y - x∥, { assume y hy, rw ← norm_neg, simpa using hx y hy }, exact ⟨x, xR, λ y hy, hx' _ (submodule.subset_span hy)⟩, end /-- In an infinite-dimensional normed space, there exists a sequence of points which are all bounded by `R` and at distance at least `1`. For a version not assuming `c` and `R`, see `exists_seq_norm_le_one_le_norm_sub`. -/ theorem exists_seq_norm_le_one_le_norm_sub' {c : 𝕜} (hc : 1 < ∥c∥) {R : ℝ} (hR : ∥c∥ < R) (h : ¬ (finite_dimensional 𝕜 E)) : ∃ f : ℕ → E, (∀ n, ∥f n∥ ≤ R) ∧ (∀ m n, m ≠ n → 1 ≤ ∥f m - f n∥) := begin haveI : is_symm E (λ (x y : E), 1 ≤ ∥x - y∥), { constructor, assume x y hxy, rw ← norm_neg, simpa }, apply exists_seq_of_forall_finset_exists' (λ (x : E), ∥x∥ ≤ R) (λ (x : E) (y : E), 1 ≤ ∥x - y∥), assume s hs, exact exists_norm_le_le_norm_sub_of_finset hc hR h s, end theorem exists_seq_norm_le_one_le_norm_sub (h : ¬ (finite_dimensional 𝕜 E)) : ∃ (R : ℝ) (f : ℕ → E), (1 < R) ∧ (∀ n, ∥f n∥ ≤ R) ∧ (∀ m n, m ≠ n → 1 ≤ ∥f m - f n∥) := begin obtain ⟨c, hc⟩ : ∃ (c : 𝕜), 1 < ∥c∥ := normed_field.exists_one_lt_norm 𝕜, have A : ∥c∥ < ∥c∥ + 1, by linarith, rcases exists_seq_norm_le_one_le_norm_sub' hc A h with ⟨f, hf⟩, exact ⟨∥c∥ + 1, f, hc.trans A, hf.1, hf.2⟩ end variable (𝕜) /-- **Riesz's theorem**: if a closed ball with center zero of positive radius is compact in a vector space, then the space is finite-dimensional. -/ theorem finite_dimensional_of_is_compact_closed_ball₀ {r : ℝ} (rpos : 0 < r) (h : is_compact (metric.closed_ball (0 : E) r)) : finite_dimensional 𝕜 E := begin by_contra hfin, obtain ⟨R, f, Rgt, fle, lef⟩ : ∃ (R : ℝ) (f : ℕ → E), (1 < R) ∧ (∀ n, ∥f n∥ ≤ R) ∧ (∀ m n, m ≠ n → 1 ≤ ∥f m - f n∥) := exists_seq_norm_le_one_le_norm_sub hfin, have rRpos : 0 < r / R := div_pos rpos (zero_lt_one.trans Rgt), obtain ⟨c, hc⟩ : ∃ (c : 𝕜), 0 < ∥c∥ ∧ ∥c∥ < (r / R) := normed_field.exists_norm_lt _ rRpos, let g := λ (n : ℕ), c • f n, have A : ∀ n, g n ∈ metric.closed_ball (0 : E) r, { assume n, simp only [norm_smul, dist_zero_right, metric.mem_closed_ball], calc ∥c∥ * ∥f n∥ ≤ (r / R) * R : mul_le_mul hc.2.le (fle n) (norm_nonneg _) rRpos.le ... = r : by field_simp [(zero_lt_one.trans Rgt).ne'] }, obtain ⟨x, hx, φ, φmono, φlim⟩ : ∃ (x : E) (H : x ∈ metric.closed_ball (0 : E) r) (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (g ∘ φ) at_top (𝓝 x) := h.tendsto_subseq A, have B : cauchy_seq (g ∘ φ) := φlim.cauchy_seq, obtain ⟨N, hN⟩ : ∃ (N : ℕ), ∀ (n : ℕ), N ≤ n → dist ((g ∘ φ) n) ((g ∘ φ) N) < ∥c∥ := metric.cauchy_seq_iff'.1 B (∥c∥) hc.1, apply lt_irrefl (∥c∥), calc ∥c∥ ≤ dist (g (φ (N+1))) (g (φ N)) : begin conv_lhs { rw [← mul_one (∥c∥)] }, simp only [g, dist_eq_norm, ←smul_sub, norm_smul, -mul_one], apply mul_le_mul_of_nonneg_left (lef _ _ (ne_of_gt _)) (norm_nonneg _), exact φmono (nat.lt_succ_self N) end ... < ∥c∥ : hN (N+1) (nat.le_succ N) end /-- **Riesz's theorem**: if a closed ball of positive radius is compact in a vector space, then the space is finite-dimensional. -/ theorem finite_dimensional_of_is_compact_closed_ball {r : ℝ} (rpos : 0 < r) {c : E} (h : is_compact (metric.closed_ball c r)) : finite_dimensional 𝕜 E := begin apply finite_dimensional_of_is_compact_closed_ball₀ 𝕜 rpos, have : continuous (λ x, -c + x), from continuous_const.add continuous_id, simpa using h.image this, end end riesz /-- An injective linear map with finite-dimensional domain is a closed embedding. -/ lemma linear_equiv.closed_embedding_of_injective {f : E →ₗ[𝕜] F} (hf : f.ker = ⊥) [finite_dimensional 𝕜 E] : closed_embedding ⇑f := let g := linear_equiv.of_injective f (linear_map.ker_eq_bot.mp hf) in { closed_range := begin haveI := f.finite_dimensional_range, simpa [f.range_coe] using f.range.closed_of_finite_dimensional end, .. embedding_subtype_coe.comp g.to_continuous_linear_equiv.to_homeomorph.embedding } lemma continuous_linear_map.exists_right_inverse_of_surjective [finite_dimensional 𝕜 F] (f : E →L[𝕜] F) (hf : f.range = ⊤) : ∃ g : F →L[𝕜] E, f.comp g = continuous_linear_map.id 𝕜 F := let ⟨g, hg⟩ := (f : E →ₗ[𝕜] F).exists_right_inverse_of_surjective hf in ⟨g.to_continuous_linear_map, continuous_linear_map.ext $ linear_map.ext_iff.1 hg⟩ lemma closed_embedding_smul_left {c : E} (hc : c ≠ 0) : closed_embedding (λ x : 𝕜, x • c) := linear_equiv.closed_embedding_of_injective (linear_map.ker_to_span_singleton 𝕜 E hc) /- `smul` is a closed map in the first argument. -/ lemma is_closed_map_smul_left (c : E) : is_closed_map (λ x : 𝕜, x • c) := begin by_cases hc : c = 0, { simp_rw [hc, smul_zero], exact is_closed_map_const }, { exact (closed_embedding_smul_left hc).is_closed_map } end open continuous_linear_map /-- Continuous linear equivalence between continuous linear functions `𝕜ⁿ → E` and `Eⁿ`. The spaces `𝕜ⁿ` and `Eⁿ` are represented as `ι → 𝕜` and `ι → E`, respectively, where `ι` is a finite type. -/ def continuous_linear_equiv.pi_ring (ι : Type*) [fintype ι] [decidable_eq ι] : ((ι → 𝕜) →L[𝕜] E) ≃L[𝕜] (ι → E) := { continuous_to_fun := begin refine continuous_pi (λ i, _), exact (continuous_linear_map.apply 𝕜 E (pi.single i 1)).continuous, end, continuous_inv_fun := begin simp_rw [linear_equiv.inv_fun_eq_symm, linear_equiv.trans_symm, linear_equiv.symm_symm], change continuous (linear_map.to_continuous_linear_map.to_linear_map.comp (linear_equiv.pi_ring 𝕜 E ι 𝕜).symm.to_linear_map), apply add_monoid_hom_class.continuous_of_bound _ (fintype.card ι : ℝ) (λ g, _), rw ← nsmul_eq_mul, apply op_norm_le_bound _ (nsmul_nonneg (norm_nonneg g) (fintype.card ι)) (λ t, _), simp_rw [linear_map.coe_comp, linear_equiv.coe_to_linear_map, function.comp_app, linear_map.coe_to_continuous_linear_map', linear_equiv.pi_ring_symm_apply], apply le_trans (norm_sum_le _ _), rw smul_mul_assoc, refine finset.sum_le_card_nsmul _ _ _ (λ i hi, _), rw [norm_smul, mul_comm], exact mul_le_mul (norm_le_pi_norm g i) (norm_le_pi_norm t i) (norm_nonneg _) (norm_nonneg g), end, .. linear_map.to_continuous_linear_map.symm.trans (linear_equiv.pi_ring 𝕜 E ι 𝕜) } /-- A family of continuous linear maps is continuous on `s` if all its applications are. -/ lemma continuous_on_clm_apply {X : Type*} [topological_space X] [finite_dimensional 𝕜 E] {f : X → E →L[𝕜] F} {s : set X} : continuous_on f s ↔ ∀ y, continuous_on (λ x, f x y) s := begin refine ⟨λ h y, (continuous_linear_map.apply 𝕜 F y).continuous.comp_continuous_on h, λ h, _⟩, let d := finrank 𝕜 E, have hd : d = finrank 𝕜 (fin d → 𝕜) := (finrank_fin_fun 𝕜).symm, let e₁ : E ≃L[𝕜] fin d → 𝕜 := continuous_linear_equiv.of_finrank_eq hd, let e₂ : (E →L[𝕜] F) ≃L[𝕜] fin d → F := (e₁.arrow_congr (1 : F ≃L[𝕜] F)).trans (continuous_linear_equiv.pi_ring (fin d)), rw [← function.comp.left_id f, ← e₂.symm_comp_self], exact e₂.symm.continuous.comp_continuous_on (continuous_on_pi.mpr (λ i, h _)) end lemma continuous_clm_apply {X : Type*} [topological_space X] [finite_dimensional 𝕜 E] {f : X → E →L[𝕜] F} : continuous f ↔ ∀ y, continuous (λ x, f x y) := by simp_rw [continuous_iff_continuous_on_univ, continuous_on_clm_apply] end complete_field section proper_field variables (𝕜 : Type u) [nontrivially_normed_field 𝕜] (E : Type v) [normed_add_comm_group E] [normed_space 𝕜 E] [proper_space 𝕜] /-- Any finite-dimensional vector space over a proper field is proper. We do not register this as an instance to avoid an instance loop when trying to prove the properness of `𝕜`, and the search for `𝕜` as an unknown metavariable. Declare the instance explicitly when needed. -/ lemma finite_dimensional.proper [finite_dimensional 𝕜 E] : proper_space E := begin set e := continuous_linear_equiv.of_finrank_eq (@finrank_fin_fun 𝕜 _ (finrank 𝕜 E)).symm, exact e.symm.antilipschitz.proper_space e.symm.continuous e.symm.surjective end end proper_field /- Over the real numbers, we can register the previous statement as an instance as it will not cause problems in instance resolution since the properness of `ℝ` is already known. -/ @[priority 900] instance finite_dimensional.proper_real (E : Type u) [normed_add_comm_group E] [normed_space ℝ E] [finite_dimensional ℝ E] : proper_space E := finite_dimensional.proper ℝ E /-- If `E` is a finite dimensional normed real vector space, `x : E`, and `s` is a neighborhood of `x` that is not equal to the whole space, then there exists a point `y ∈ frontier s` at distance `metric.inf_dist x sᶜ` from `x`. See also `is_compact.exists_mem_frontier_inf_dist_compl_eq_dist`. -/ lemma exists_mem_frontier_inf_dist_compl_eq_dist {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {x : E} {s : set E} (hx : x ∈ s) (hs : s ≠ univ) : ∃ y ∈ frontier s, metric.inf_dist x sᶜ = dist x y := begin rcases metric.exists_mem_closure_inf_dist_eq_dist (nonempty_compl.2 hs) x with ⟨y, hys, hyd⟩, rw closure_compl at hys, refine ⟨y, ⟨metric.closed_ball_inf_dist_compl_subset_closure hx $ metric.mem_closed_ball.2 $ ge_of_eq _, hys⟩, hyd⟩, rwa dist_comm end /-- If `K` is a compact set in a nontrivial real normed space and `x ∈ K`, then there exists a point `y` of the boundary of `K` at distance `metric.inf_dist x Kᶜ` from `x`. See also `exists_mem_frontier_inf_dist_compl_eq_dist`. -/ lemma is_compact.exists_mem_frontier_inf_dist_compl_eq_dist {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [nontrivial E] {x : E} {K : set E} (hK : is_compact K) (hx : x ∈ K) : ∃ y ∈ frontier K, metric.inf_dist x Kᶜ = dist x y := begin obtain (hx'|hx') : x ∈ interior K ∪ frontier K, { rw ← closure_eq_interior_union_frontier, exact subset_closure hx }, { rw [mem_interior_iff_mem_nhds, metric.nhds_basis_closed_ball.mem_iff] at hx', rcases hx' with ⟨r, hr₀, hrK⟩, haveI : finite_dimensional ℝ E, from finite_dimensional_of_is_compact_closed_ball ℝ hr₀ (compact_of_is_closed_subset hK metric.is_closed_ball hrK), exact exists_mem_frontier_inf_dist_compl_eq_dist hx hK.ne_univ }, { refine ⟨x, hx', _⟩, rw frontier_eq_closure_inter_closure at hx', rw [metric.inf_dist_zero_of_mem_closure hx'.2, dist_self] }, end /-- In a finite dimensional vector space over `ℝ`, the series `∑ x, ∥f x∥` is unconditionally summable if and only if the series `∑ x, f x` is unconditionally summable. One implication holds in any complete normed space, while the other holds only in finite dimensional spaces. -/ lemma summable_norm_iff {α E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {f : α → E} : summable (λ x, ∥f x∥) ↔ summable f := begin refine ⟨summable_of_summable_norm, λ hf, _⟩, -- First we use a finite basis to reduce the problem to the case `E = fin N → ℝ` suffices : ∀ {N : ℕ} {g : α → fin N → ℝ}, summable g → summable (λ x, ∥g x∥), { obtain v := fin_basis ℝ E, set e := v.equiv_funL, have : summable (λ x, ∥e (f x)∥) := this (e.summable.2 hf), refine summable_of_norm_bounded _ (this.mul_left ↑(∥(e.symm : (fin (finrank ℝ E) → ℝ) →L[ℝ] E)∥₊)) (λ i, _), simpa using (e.symm : (fin (finrank ℝ E) → ℝ) →L[ℝ] E).le_op_norm (e $ f i) }, unfreezingI { clear_dependent E }, -- Now we deal with `g : α → fin N → ℝ` intros N g hg, have : ∀ i, summable (λ x, ∥g x i∥) := λ i, (pi.summable.1 hg i).abs, refine summable_of_norm_bounded _ (summable_sum (λ i (hi : i ∈ finset.univ), this i)) (λ x, _), rw [norm_norm, pi_norm_le_iff], { refine λ i, finset.single_le_sum (λ i hi, _) (finset.mem_univ i), exact norm_nonneg (g x i) }, { exact finset.sum_nonneg (λ _ _, norm_nonneg _) } end lemma summable_of_is_O' {ι E F : Type*} [normed_add_comm_group E] [complete_space E] [normed_add_comm_group F] [normed_space ℝ F] [finite_dimensional ℝ F] {f : ι → E} {g : ι → F} (hg : summable g) (h : f =O[cofinite] g) : summable f := summable_of_is_O (summable_norm_iff.mpr hg) h.norm_right lemma summable_of_is_O_nat' {E F : Type*} [normed_add_comm_group E] [complete_space E] [normed_add_comm_group F] [normed_space ℝ F] [finite_dimensional ℝ F] {f : ℕ → E} {g : ℕ → F} (hg : summable g) (h : f =O[at_top] g) : summable f := summable_of_is_O_nat (summable_norm_iff.mpr hg) h.norm_right lemma summable_of_is_equivalent {ι E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {f : ι → E} {g : ι → E} (hg : summable g) (h : f ~[cofinite] g) : summable f := hg.trans_sub (summable_of_is_O' hg h.is_o.is_O) lemma summable_of_is_equivalent_nat {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {f : ℕ → E} {g : ℕ → E} (hg : summable g) (h : f ~[at_top] g) : summable f := hg.trans_sub (summable_of_is_O_nat' hg h.is_o.is_O) lemma is_equivalent.summable_iff {ι E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {f : ι → E} {g : ι → E} (h : f ~[cofinite] g) : summable f ↔ summable g := ⟨λ hf, summable_of_is_equivalent hf h.symm, λ hg, summable_of_is_equivalent hg h⟩ lemma is_equivalent.summable_iff_nat {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {f : ℕ → E} {g : ℕ → E} (h : f ~[at_top] g) : summable f ↔ summable g := ⟨λ hf, summable_of_is_equivalent_nat hf h.symm, λ hg, summable_of_is_equivalent_nat hg h⟩
78d167a52c9bbe1917d2c48c9266b8853bb9a9cd
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/nat/fib.lean
4a82019a0041e61e5182a62ac76d6d6da652b456
[ "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
5,754
lean
/- Copyright (c) 2019 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import data.stream.basic import data.nat.gcd import tactic.ring /-! # The Fibonacci Sequence ## Summary Definition of the Fibonacci sequence `F₀ = 0, F₁ = 1, Fₙ₊₂ = Fₙ + Fₙ₊₁`. ## Main Definitions - `fib` returns the stream of Fibonacci numbers. ## Main Statements - `fib_succ_succ` : shows that `fib` indeed satisfies the Fibonacci recurrence `Fₙ₊₂ = Fₙ + Fₙ₊₁.`. - `fib_gcd` : `fib n` is a strong divisibility sequence. ## Implementation Notes For efficiency purposes, the sequence is defined using `stream.iterate`. ## Tags fib, fibonacci -/ namespace nat /-- Auxiliary function used in the definition of `fib_aux_stream`. -/ private def fib_aux_step : (ℕ × ℕ) → (ℕ × ℕ) := λ p, ⟨p.snd, p.fst + p.snd⟩ /-- Auxiliary stream creating Fibonacci pairs `⟨Fₙ, Fₙ₊₁⟩`. -/ private def fib_aux_stream : stream (ℕ × ℕ) := stream.iterate fib_aux_step ⟨0, 1⟩ /-- Implementation of the fibonacci sequence satisfying `fib 0 = 0, fib 1 = 1, fib (n + 2) = fib n + fib (n + 1)`. *Note:* We use a stream iterator for better performance when compared to the naive recursive implementation. -/ @[pp_nodot] def fib (n : ℕ) : ℕ := (fib_aux_stream n).fst @[simp] lemma fib_zero : fib 0 = 0 := rfl @[simp] lemma fib_one : fib 1 = 1 := rfl @[simp] lemma fib_two : fib 2 = 1 := rfl private lemma fib_aux_stream_succ {n : ℕ} : fib_aux_stream (n + 1) = fib_aux_step (fib_aux_stream n) := begin change (stream.nth (n + 1) $ stream.iterate fib_aux_step ⟨0, 1⟩) = fib_aux_step (stream.nth n $ stream.iterate fib_aux_step ⟨0, 1⟩), rw [stream.nth_succ_iterate, stream.map_iterate, stream.nth_map] end /-- Shows that `fib` indeed satisfies the Fibonacci recurrence `Fₙ₊₂ = Fₙ + Fₙ₊₁.` -/ lemma fib_succ_succ {n : ℕ} : fib (n + 2) = fib n + fib (n + 1) := by simp only [fib, fib_aux_stream_succ, fib_aux_step] lemma fib_pos {n : ℕ} (n_pos : 0 < n) : 0 < fib n := begin induction n with n IH, case nat.zero { norm_num at n_pos }, case nat.succ { cases n, case nat.zero { simp [fib_succ_succ, zero_lt_one] }, case nat.succ { have : 0 ≤ fib n, by simp, exact (lt_add_of_nonneg_of_lt this $ IH n.succ_pos) }} end lemma fib_le_fib_succ {n : ℕ} : fib n ≤ fib (n + 1) := by { cases n; simp [fib_succ_succ] } @[mono] lemma fib_mono : monotone fib := monotone_nat_of_le_succ $ λ _, fib_le_fib_succ /-- `fib (n + 2)` is strictly monotone. -/ lemma fib_add_two_strict_mono : strict_mono (λ n, fib (n + 2)) := strict_mono_nat_of_lt_succ $ λ n, lt_add_of_pos_left _ $ fib_pos succ_pos' lemma le_fib_self {n : ℕ} (five_le_n : 5 ≤ n) : n ≤ fib n := begin induction five_le_n with n five_le_n IH, { have : 5 = fib 5, by refl, -- 5 ≤ fib 5 exact le_of_eq this }, { -- n + 1 ≤ fib (n + 1) for 5 ≤ n cases n with n', -- rewrite n = succ n' to use fib.succ_succ { have : 5 = 0, from nat.le_zero_iff.elim_left five_le_n, contradiction }, rw fib_succ_succ, suffices : 1 + (n' + 1) ≤ fib n' + fib (n' + 1), by rwa [nat.succ_eq_add_one, add_comm], have : n' ≠ 0, by { intro h, have : 5 ≤ 1, by rwa h at five_le_n, norm_num at this }, have : 1 ≤ fib n', from nat.succ_le_of_lt (fib_pos $ pos_iff_ne_zero.mpr this), mono } end /-- Subsequent Fibonacci numbers are coprime, see https://proofwiki.org/wiki/Consecutive_Fibonacci_Numbers_are_Coprime -/ lemma fib_coprime_fib_succ (n : ℕ) : nat.coprime (fib n) (fib (n + 1)) := begin unfold coprime, induction n with n ih, { simp }, { convert ih using 1, rw [fib_succ_succ, succ_eq_add_one, gcd_rec, add_mod_right, gcd_comm (fib n), gcd_rec (fib (n + 1))], } end /-- See https://proofwiki.org/wiki/Fibonacci_Number_in_terms_of_Smaller_Fibonacci_Numbers -/ lemma fib_add (m n : ℕ) : fib m * fib n + fib (m + 1) * fib (n + 1) = fib (m + n + 1) := begin induction n with n ih generalizing m, { simp }, { intros, specialize ih (m + 1), rw [add_assoc m 1 n, add_comm 1 n] at ih, simp only [fib_succ_succ, ← ih], ring, } end lemma gcd_fib_add_self (m n : ℕ) : gcd (fib m) (fib (n + m)) = gcd (fib m) (fib n) := begin cases nat.eq_zero_or_pos n, { rw h, simp }, replace h := nat.succ_pred_eq_of_pos h, rw [← h, succ_eq_add_one], calc gcd (fib m) (fib (n.pred + 1 + m)) = gcd (fib m) (fib (n.pred) * (fib m) + fib (n.pred + 1) * fib (m + 1)) : by { rw fib_add n.pred _, ring_nf } ... = gcd (fib m) (fib (n.pred + 1) * fib (m + 1)) : by rw [add_comm, gcd_add_mul_self (fib m) _ (fib (n.pred))] ... = gcd (fib m) (fib (n.pred + 1)) : coprime.gcd_mul_right_cancel_right (fib (n.pred + 1)) (coprime.symm (fib_coprime_fib_succ m)) end lemma gcd_fib_add_mul_self (m n : ℕ) : ∀ k, gcd (fib m) (fib (n + k * m)) = gcd (fib m) (fib n) | 0 := by simp | (k+1) := by rw [← gcd_fib_add_mul_self k, add_mul, ← add_assoc, one_mul, gcd_fib_add_self _ _] /-- `fib n` is a strong divisibility sequence, see https://proofwiki.org/wiki/GCD_of_Fibonacci_Numbers -/ lemma fib_gcd (m n : ℕ) : fib (gcd m n) = gcd (fib m) (fib n) := begin wlog h : m ≤ n using [n m, m n], exact le_total m n, { apply gcd.induction m n, { simp }, intros m n mpos h, rw ← gcd_rec m n at h, conv_rhs { rw ← mod_add_div' n m }, rwa [gcd_fib_add_mul_self m (n % m) (n / m), gcd_comm (fib m) _] }, rwa [gcd_comm, gcd_comm (fib m)] end lemma fib_dvd (m n : ℕ) (h : m ∣ n) : fib m ∣ fib n := by rwa [gcd_eq_left_iff_dvd, ← fib_gcd, gcd_eq_left_iff_dvd.mp] end nat
e9d39eaeed8cdc5cff97831681ac78efdf2013e9
827a8a5c2041b1d7f55e128581f583dfbd65ecf6
/fin.hlean
20729ef8c7ef0628ba2d411c5680e0663def26dc
[ "Apache-2.0" ]
permissive
fpvandoorn/leansnippets
6af0499f6f3fd2c07e4b580734d77b67574e7c27
601bafbe07e9534af76f60994d6bdf741996ef93
refs/heads/master
1,590,063,910,882
1,545,093,878,000
1,545,093,878,000
36,044,957
2
2
null
1,442,619,708,000
1,432,256,875,000
Lean
UTF-8
Lean
false
false
11,787
hlean
/- Copyright (c) 2016 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Finite types as inductive definition. The definition in types/fin is different, namely as a subtype of the natural numbers. That definition doesn't allow pattern matching. -/ import types.nat.div types.nat.hott types.prod open eq nat bool prod algebra inductive is_succ [class] : ℕ → Type₀ := | mk : Πn, is_succ (succ n) attribute is_succ.mk [instance] definition is_succ_add_right [instance] (n m : ℕ) [H : is_succ m] : is_succ (n+m) := by induction H with m; constructor definition is_succ_add_left (n m : ℕ) [H : is_succ n] : is_succ (n+m) := by induction H with n; cases m with m: constructor definition is_succ_bit0 [instance] (n : ℕ) [H : is_succ n] : is_succ (bit0 n) := by induction H with n; constructor theorem fn_eq_mod {n : ℕ} {f : ℕ → ℕ} (H0 : f 0 = 0) (H1 : Πx, f x < n → f (succ x) = succ (f x)) (H2 : Πx, f x = n → f (succ x) = 0) : Πx, f x = x % (succ n) := begin assert H3 : Πx, x ≤ n → f x = x, { intro x H, induction x with x IH, { exact H0}, { have IH' : f x = x, from IH (le.trans !self_le_succ H), refine H1 x _ ⬝ ap succ IH', rewrite IH', exact lt_of_succ_le H}}, assert H4 : Πx, f x ≤ n, { intro x, induction x using nat.rec_on with x IH , { rewrite [H0], apply zero_le}, { eapply @nat.lt_ge_by_cases (f x) n: intro H, { rewrite [H1 x H], exact succ_le_of_lt H}, { have H5 : f x = n, from le.antisymm IH H, rewrite [H2 x H5], apply zero_le}}}, assert H5 : Πx, f (succ n + x) = f x, { intro x, induction x using nat.rec_on with x IH , { rewrite [add_zero, H0], apply H2, exact H3 n !le.refl}, { eapply @nat.lt_ge_by_cases (f x) n: intro H, { have H' : f (succ n + x) < n, from IH⁻¹ ▸ H, rewrite [H1 x H, add_succ, H1 (succ n + x) H'], exact ap succ IH}, { have H5 : f x = n, from le.antisymm (H4 x) H, rewrite [add_succ, H2 x H5, H2 (succ n + x) (IH ⬝ H5)]}}}, intro x, induction x using nat.case_strong_rec_on with x IH, { exact H0}, { eapply @nat.lt_ge_by_cases x n: intro H, { refine H3 (succ x) (succ_le_of_lt H) ⬝ _, symmetry, exact mod_eq_of_lt (succ_lt_succ H)}, { assert H6 : succ x = succ n + (succ x - succ n), { symmetry, rewrite [add.comm], exact nat.sub_add_cancel (succ_le_succ H)}, assert H7 : succ x - succ n ≤ x, { apply le_of_lt_succ, apply sub_lt: apply !succ_pos}, rewrite [H6, H5, IH _ H7], exact !add_mod_self_left⁻¹}} end inductive ifin : ℕ → Type₀ := -- inductively deinclne incln-type | max : Π n, ifin (succ n) | incl : Π {n}, ifin n → ifin (succ n) namespace ifin /- Intuition behind the following deinclnitions: max n is (n : ifin (succ n)) incl sends (x : ifin n) to (x : ifin (n+1)). zero n is (0 : ifin (succ n)) succ' sends (x : ifin n) to (x+1 : ifin (n+1)) succ' sends (x : ifin n) to (x+1 : ifin (n+1)) succ sends (x : ifin n) to (x+1 : ifin n) (sending n-1 to 0) add sends (x y : ifin n) to (x+y ifin n), where addition is modulo n proj sends (x : ifin (n+2)) to (x : ifin (n+1)) (sending n+1 to n) pred' sends (x : ifin n) to (x+1 : ifin n) (sending 0 to 0) is_zero tests whether (x : ifin n) is n-1 pred sends (x : ifin n) to (x+1 : ifin n) (sending 0 to n-1) -/ definition zero : Π(n : ℕ), ifin (succ n) | 0 := max 0 | (succ n) := incl (zero n) definition succ' : Π{n : ℕ}, ifin n → ifin (succ n) | (succ n) (max n) := max (succ n) | (succ n) (incl x) := incl (succ' x) protected definition succ : Π{n : ℕ}, ifin n → ifin n | (nat.succ n) (max n) := zero n | (nat.succ n) (incl x) := succ' x definition proj : Π{n : ℕ}, ifin (succ (succ n)) → ifin (succ n) | n (max (succ n)) := max n | n (incl x) := x -- definition is_incl [reducible] : Π{n : ℕ} (x : ifin n), Type₀ -- | 1 x := empty -- | (n+2) x := x = incl (proj x) -- definition reverse : Π{n : ℕ}, ifin n → ifin n -- | (nat.succ n) (max n) := zero n -- | (nat.succ n) (incl x) := succ' (reverse x) -- definition pred' : Π{n : ℕ}, ifin n → ifin n -- | 1 (max 0) := max 0 -- | (n+2) (max (n+1)) := incl (max n) -- | (n+2) (incl x) := incl (pred' x) -- definition is_zero : Π{n : ℕ}, ifin n → bool -- | 1 (max 0) := tt -- | (n+2) (max (n+1)) := ff -- | (n+2) (incl x) := is_zero x -- definition pred : Π{n : ℕ}, ifin n → ifin n -- | (succ n) x := cond (is_zero x) (max n) (pred' x) -- definition rev_add {n : ℕ} (x : ifin n): Π{m : ℕ}, ifin m → ifin n -- | (succ m) (max m) := iterate ifin.succ m x -- | (succ m) (incl y) := rev_add y definition add' {n : ℕ} (x : ifin n): Π{m : ℕ}, ifin m → ifin n | (succ m) (max m) := iterate ifin.succ m x | (succ m) (incl y) := add' y definition add [reducible] {n : ℕ} (x y : ifin n) : ifin n := add' x y definition nat_of_ifin : Π{n : ℕ}, ifin n → ℕ | (succ n) (max n) := n | (succ n) (incl x) := nat_of_ifin x definition ifin_of_nat (n : ℕ) : ℕ → ifin (succ n) | 0 := zero n | (succ k) := ifin.succ (ifin_of_nat k) definition has_zero_ifin [instance] (n : ℕ) [H : is_succ n] : has_zero (ifin n) := by induction H with n; exact has_zero.mk (zero n) definition has_one_ifin [instance] (n : ℕ) [H : is_succ n] : has_one (ifin n) := by induction H with n; exact has_one.mk (ifin.succ (zero n)) definition has_add_ifin [instance] (n : ℕ) : has_add (ifin n) := has_add.mk (add) /- some theorems. -/ definition nat_of_ifin_zero (n : ℕ) : nat_of_ifin (zero n) = 0 := begin induction n with n IH, { reflexivity}, { exact IH} end definition nat_of_ifin_succ' : Π{n : ℕ} (x : ifin n), nat_of_ifin (succ' x) = succ (nat_of_ifin x) | (succ n) (max n) := idp | (succ n) (incl x) := nat_of_ifin_succ' x definition nat_of_ifin_lt : Π{n : ℕ} (x : ifin n), nat_of_ifin x < n | (succ n) (max n) := self_lt_succ n | (succ n) (incl x) := lt.trans (nat_of_ifin_lt x) (self_lt_succ n) definition nat_of_ifin_incl_neq {n : ℕ} (x : ifin n) : nat_of_ifin (incl x) ≠ n := begin intro H, refine lt_le_antisymm (nat_of_ifin_lt x) _, apply le_of_eq, symmetry, exact H end definition add'_zero {n : ℕ} (x : ifin n) : Πm, add' x (zero m) = x | 0 := idp | (succ m) := add'_zero m definition add_zero {n : ℕ} (x : ifin (succ n)) : x + 0 = x := add'_zero x n -- definition add'_succ {n : ℕ} (x : ifin n) -- : Π{m} (y : ifin m), add' x (ifin.succ y) = ifin.succ (add' x y) -- | (succ m) (max m) := add'_zero x m ⬝ _ -- | (succ m) (incl y) := sorry --incl (succ' x) -- definition iterate_succ_incl : Π{n : ℕ} (x : ifin n), -- iterate ifin.succ n (incl x) = incl (iterate ifin.succ) -- | 1 (max 0) := idp -- | (succ (n+1)) x := begin esimp [iterate] end definition my_nat_rec {P : ℕ → ℕ → Type} (H0 : P 0 0) (H1 : Πn, P n 0 → P 0 (succ n)) (H1 : Πn k, P n (succ k) → P (succ n) k) (n m : ℕ) : P n m := sorry definition incl_zero (n : ℕ) : incl (0 : ifin (succ n)) = 0 := idp definition succ_incl {n : ℕ} (x : ifin n) : ifin.succ (incl x) = succ' x := idp definition succ_incl_incl {n : ℕ} {x : ifin n} : ifin.succ (incl (incl x)) = incl (ifin.succ (incl x)) := idp -- definition succ_incl_of_is_incl : Π{n : ℕ} {x : ifin n} (H : is_incl x), -- ifin.succ (incl x) = incl (ifin.succ x) -- | 1 x H := by cases H -- | (n+2) (max (n+1)) H := by cases H -- | (n+2) (incl x) H := by reflexivity -- definition is_incl_incl : Π{n : ℕ} (x : ifin n), is_incl (incl x) -- | (succ n) x := idp definition iterate_succ_right {A : Type} (f : A → A) (n : ℕ) (x : A) : iterate f (succ n) x = iterate f n (f x) := begin induction n with n IH, { reflexivity}, { exact ap f IH} end definition iterate_succ_left {A : Type} (f : A → A) (n : ℕ) (x : A) : iterate f (succ n) x = f (iterate f n x) := idp -- set_option pp.notation false -- set_option pp.implicit true -- set_option pp.numerals false -- definition iterate_succ_zero_eq_max_lem_type [reducible] theorem iterate_succ_zero_eq_max_lem (n k : ℕ) : iterate ifin.succ (succ n) (incl (iterate ifin.succ k 0)) = max (succ (n + k)) × Πm, m < n + k → iterate ifin.succ m (0 : ifin (succ (succ (pred (n + k))))) = incl (iterate ifin.succ m (0 : ifin (succ (pred (n + k))))) := begin refine my_nat_rec _ _ _ n k: clear n k, { split, { reflexivity}, { intro m H, cases H}}, { intro n H, rewrite [zero_add (succ n), nat.add_zero n at H], esimp [iterate], cases H with H H2, split, { refine ap ifin.succ (ap incl H)}, { intro m, induction m with m IH: intro H, { reflexivity}, { note IH' := IH (lt.trans !self_lt_succ H), note H3 := H2 m (lt_of_succ_lt_succ H), rewrite [iterate_succ_left, IH'], exact sorry }}}, { intro n k H, cases H with H H2, split, { refine !iterate_succ_right ⬝ _, rewrite [nat.succ_add], refine _ ⬝ H, apply ap (ifin.succ^[nat.succ n]), note H3 := H2 k (lt_of_le_of_lt !le_add_left !self_lt_succ), xrewrite [H3, succ_incl_incl, -H3]}, { rewrite [succ_add], exact H2}} end definition iterate_succ_zero_eq_max (n : ℕ) : iterate ifin.succ (succ n) 0 = max (succ n) := proof pr1 (iterate_succ_zero_eq_max_lem n 0) qed definition iterate_succ_eq_self : Π{n : ℕ} (x : ifin n), iterate ifin.succ n x = x | 1 (max 0) := idp | (succ (n+1)) x := begin exact sorry end -- definition add_succ : Π{n : ℕ} (x y : ifin n), x + (ifin.succ y) = ifin.succ (x + y) -- | (succ n) x (max n) := add_zero x ⬝ _ -- | (succ n) (max n) (incl y) := sorry -- | (succ n) (incl x) (incl y) := sorry -- definition ifin_of_nat_add (n x : ℕ) -- : Πy, ifin_of_nat n (x + y) = ifin_of_nat n x + ifin_of_nat n y -- | 0 := _ -- | (succ k) := _ theorem nat_of_ifin_of_nat (n k : ℕ) : nat_of_ifin (ifin_of_nat n k) = k % (succ n) := begin apply fn_eq_mod: clear k, { apply nat_of_ifin_zero}, { intro k, esimp [ifin_of_nat], cases (ifin_of_nat n k): intro H, { exfalso, exact lt.irrefl n H}, { apply nat_of_ifin_succ'}}, { intro k, esimp [ifin_of_nat], cases (ifin_of_nat n k): intro H, { apply nat_of_ifin_zero}, { exfalso, exact nat_of_ifin_incl_neq _ H}}, end -- theorem ifin_of_nat_of_ifin : Π{n : ℕ} (x : ifin (succ n)), ifin_of_nat n (nat_of_ifin x) = x -- | n (max n) := _ -- | n (incl x) := _ -- TODO: prove theorems about these constructions. example (n : ℕ) : has_zero (ifin (n+6)) := _ definition flatten {n : ℕ} (x : ℕ × ifin n) : ℕ := n * (pr1 x) + nat_of_ifin (pr2 x) definition unflatten (n : ℕ) (x : ℕ) : ℕ × ifin (succ n) := (x / succ n, ifin_of_nat n x) theorem flatten_unflatten {n : ℕ} (x : ℕ) : flatten (unflatten n x) = x := begin unfold [flatten, unflatten], refine _ ⬝ (eq_div_mul_add_mod x (succ n))⁻¹, rewrite [nat_of_ifin_of_nat, mul.comm] end theorem unflatten_flatten {n : ℕ} (x : ℕ × ifin (succ n)) : unflatten n (flatten x) = x := begin cases x with m y, unfold [flatten, unflatten], apply prod_eq: esimp, { rewrite [add.comm, add_mul_div_self_left _ _ (!zero_lt_succ), div_eq_zero_of_lt (nat_of_ifin_lt y), zero_add]}, { exact sorry} end end ifin
b69d8868766c46cd3335dbd04907b2ddcbd1f92d
c8b4b578b2fe61d500fbca7480e506f6603ea698
/src/number_theory/cyclotomic/cyclotomic_units.lean
0d58ff6ef09d2f793541a67528e43904e6c26501
[]
no_license
leanprover-community/flt-regular
aa7e564f2679dfd2e86015a5a9674a6e1197f7cc
67fb3e176584bbc03616c221a7be6fa28c5ccd32
refs/heads/master
1,692,188,905,751
1,691,766,312,000
1,691,766,312,000
421,021,216
19
4
null
1,694,532,115,000
1,635,166,136,000
Lean
UTF-8
Lean
false
false
6,322
lean
/- Copyright (c) 2021 Alex J. Best. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alex J. Best -/ import number_theory.cyclotomic.primitive_roots import ring_theory.polynomial.cyclotomic.eval noncomputable theory open_locale big_operators non_zero_divisors number_field open number_field polynomial finset module units submodule universe variables u v w z variables (n : ℕ+) (K : Type u) (L : Type v) (A : Type w) (B : Type z) variables [comm_ring A] [comm_ring B] [algebra A B] variables [field K] [field L] [algebra K L] namespace is_primitive_root variable {B} variable (B) end is_primitive_root namespace is_cyclotomic_extension variables [is_cyclotomic_extension {n} A B] variables [is_domain A] [algebra A K] [is_fraction_ring A K] open is_cyclotomic_extension open is_cyclotomic_extension section cyclotomic_unit variable {n} namespace cyclotomic_unit -- I don't want to bother Leo, but I wonder if this can be automated in Lean4 -- (if they were 0 < n → 1 < n, it would work already!) lemma _root_.nat.one_lt_of_ne : ∀ n : ℕ, n ≠ 0 → n ≠ 1 → 1 < n | 0 h _ := absurd rfl h | 1 _ h := absurd rfl h | (n+2) _ _ := n.one_lt_succ_succ -- this result holds for all primitive roots; dah. lemma associated_one_sub_pow_primitive_root_of_coprime {n j k : ℕ} {ζ : A} (hζ : is_primitive_root ζ n) (hk : k.coprime n) (hj : j.coprime n) : associated (1 - ζ ^ j) (1 - ζ ^ k) := begin suffices : ∀ {j : ℕ}, j.coprime n → associated (1 - ζ) (1 - ζ ^ j), { exact (this hj).symm.trans (this hk) }, clear' k j hk hj, refine λ j hj, associated_of_dvd_dvd ⟨∑ i in range j, ζ ^ i, by rw [← geom_sum_mul_neg, mul_comm]⟩ _, -- is there an easier way to do this? rcases eq_or_ne n 0 with rfl | hn', { simp [j.coprime_zero_right.mp hj] }, rcases eq_or_ne n 1 with rfl | hn, { simp [is_primitive_root.one_right_iff.mp hζ] }, replace hn := n.one_lt_of_ne hn' hn, obtain ⟨m, hm⟩ := nat.exists_mul_mod_eq_one_of_coprime hj hn, use (∑ i in range m, (ζ ^ j) ^ i), have : ζ = (ζ ^ j) ^ m, { rw [←pow_mul, pow_eq_mod_order_of, ←hζ.eq_order_of, hm, pow_one] }, nth_rewrite 0 this, rw [← geom_sum_mul_neg, mul_comm] end lemma is_primitive_root.sum_pow_unit {n k : ℕ} {ζ : A} (hn : 2 ≤ n) (hk : k.coprime n) (hζ : is_primitive_root ζ n) : is_unit (∑ (i : ℕ) in range k, ζ^(i : ℕ)) := begin have h1 : (1 : ℕ).coprime n, by {exact nat.coprime_one_left n, }, have := associated_one_sub_pow_primitive_root_of_coprime _ hζ hk h1, simp at this, rw associated at this, have h2 := mul_neg_geom_sum ζ k, obtain ⟨u, hu⟩ := this, have := u.is_unit, convert this, rw ←hu at h2, simp at h2, cases h2, exact h2, exfalso, have hn1 : 1 < n, by {linarith}, have hp := is_primitive_root.pow_ne_one_of_pos_of_lt hζ one_pos hn1, simp at *, rw sub_eq_zero at h2, rw ←h2 at hp, simp only [eq_self_iff_true, not_true] at hp, exact hp, end lemma is_primitive_root.zeta_pow_sub_eq_unit_zeta_sub_one {p i j : ℕ} {ζ : A} (hn : 2 ≤ p) (hp : p.prime ) (hi : i < p) (hj : j < p) (hij : i ≠ j) (hζ : is_primitive_root ζ p) : ∃ (u : Aˣ), (ζ^i - ζ^j ) = u * (1- ζ) := begin by_cases hilj : j < i, have h1 : (ζ^i - ζ^j) = ζ^j * (ζ^(i-j)-1), by {ring_exp, rw pow_mul_pow_sub _ hilj.le, rw add_comm,}, rw h1, have h2 := mul_neg_geom_sum ζ (i-j), have hic : (i-j).coprime p, by {rw nat.coprime_comm, apply nat.coprime_of_lt_prime _ _ hp, apply nat.sub_pos_of_lt hilj, by_cases hj : 0 < j, apply lt_trans _ hi, apply nat.sub_lt_of_pos_le _ _ hj hilj.le, simp only [not_lt, _root_.le_zero_iff] at hj, rw hj, simp only [tsub_zero], exact hi,}, have h3 : is_unit (-(ζ^(j))*(∑ (k : ℕ) in range (i-j), ζ^(k : ℕ))), by {apply is_unit.mul _ (is_primitive_root.sum_pow_unit _ hn hic hζ), apply is_unit.neg, apply is_unit.pow, apply hζ.is_unit hp.pos, }, obtain ⟨v, hv⟩ := h3, use v, rw hv, rw mul_comm at h2, rw mul_assoc, rw h2, ring, simp at *, have h1 : (ζ^i - ζ^j) = ζ^i * (1-ζ^(j-i)), by {ring_exp, simp, rw pow_mul_pow_sub _ hilj,}, rw h1, have h2 := mul_neg_geom_sum ζ (j-i), have hjc : (j-i).coprime p, by {rw nat.coprime_comm, apply nat.coprime_of_lt_prime _ _ hp, have hilj' : i < j, by {rw lt_iff_le_and_ne, simp [hij, hilj], }, apply nat.sub_pos_of_lt hilj', by_cases hii : 0 < i, apply lt_trans _ hj, apply nat.sub_lt_of_pos_le _ _ hii hilj, simp only [not_lt, _root_.le_zero_iff] at hii, rw hii, simp only [tsub_zero], exact hj, }, have h3 : is_unit ((ζ^(i))*(∑ (k : ℕ) in range (j-i), ζ^(k : ℕ))), by { apply is_unit.mul _ (is_primitive_root.sum_pow_unit _ hn hjc hζ), apply is_unit.pow, apply hζ.is_unit hp.pos,}, obtain ⟨v, hv⟩ := h3, use v, rw hv, rw mul_comm at h2, rw mul_assoc, rw h2, end /- def unitlem2 {n k : ℕ} {ζ : A} (hk : nat.coprime n k) (hζ : is_primitive_root ζ n) : Aˣ := { val := (∑ (i : finset.range k), ζ^(i : ℕ)), inv := (ζ-1) , val_inv := admit, inv_val := admit, } variable (n) instance : is_localization ((ring_of_integers (cyclotomic_field n K)))⁰ (cyclotomic_field n K) := admit lemma prime_ideal_eq_pow_cyclotomic [hn : fact ((n : ℕ).prime)] : (span_singleton _ n : fractional_ideal RR⁰ L) = (span_singleton _ (1 - (zeta_runity n K L)) ^ ((n : ℕ) - 1) : fractional_ideal RR⁰ L) := --(mk0 (p : cyclotomic_field p) (by norm_num [hn.ne_zero])) begin rw fractional_ideal.span_singleton_pow, apply coe_to_submodule_injective, simp only [coe_span_singleton, coe_coe], -- rw ideal.span_singleton_eq_span_singleton, simp only [submodule.span_singleton_eq_span_singleton], rw ← eval_one_cyclotomic_prime, --rw calc -- eval 1 (cyclotomic n (cyclotomic_field n)) = _ : by simp_rw -- cyclotomic_eq_prod_X_sub_primitive_roots (zeta_primitive_root n _) -- ... = _ : by simp only [polynomial.eval_sub, polynomial.eval_C, -- polynomial.eval_prod, polynomial.eval_X], -- apply span_singleton_eq_span_singleton_, admit, end -/ end cyclotomic_unit end cyclotomic_unit end is_cyclotomic_extension
a036658977b56313edc54d7ab66710180e534dc5
f618aea02cb4104ad34ecf3b9713065cc0d06103
/src/tactic/omega/nat/dnf.lean
b3a49ab3d5bfad3853e501788ff24b2da16cb7ed
[ "Apache-2.0" ]
permissive
joehendrix/mathlib
84b6603f6be88a7e4d62f5b1b0cbb523bb82b9a5
c15eab34ad754f9ecd738525cb8b5a870e834ddc
refs/heads/master
1,589,606,591,630
1,555,946,393,000
1,555,946,393,000
182,813,854
0
0
null
1,555,946,309,000
1,555,946,308,000
null
UTF-8
Lean
false
false
4,898
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek DNF transformation. -/ import tactic.omega.clause import tactic.omega.nat.sub_elim namespace omega namespace nat local notation x ` =* ` y := form.eq x y local notation x ` ≤* ` y := form.le x y local notation `¬* ` p := form.not p local notation p ` ∨* ` q := form.or p q local notation p ` ∧* ` q := form.and p q @[simp] def dnf_core : form → list clause | (p ∨* q) := (dnf_core p) ++ (dnf_core q) | (p ∧* q) := (list.product (dnf_core p) (dnf_core q)).map (λ pq, clause.append pq.fst pq.snd) | (t =* s) := [([term.sub (canonize s) (canonize t)],[])] | (t ≤* s) := [([],[term.sub (canonize s) (canonize t)])] | (¬* _) := [] lemma exists_clause_holds_core {v : nat → nat} : ∀ {p : form}, p.neg_free → p.sub_free → p.holds v → ∃ c ∈ (dnf_core p), clause.holds (λ x, ↑(v x)) c := begin form.induce `[intros h1 h0 h2], { apply list.exists_mem_cons_of, constructor, rw list.forall_mem_singleton, cases h0 with ht hs, simp only [val_canonize ht, val_canonize hs, term.val_sub, form.holds, sub_eq_add_neg] at *, rw [h2, add_neg_self], apply list.forall_mem_nil }, { apply list.exists_mem_cons_of, constructor, apply list.forall_mem_nil, rw list.forall_mem_singleton, simp only [val_canonize (h0.left), val_canonize (h0.right), term.val_sub, form.holds, sub_eq_add_neg] at *, rw [←sub_eq_add_neg, le_sub, sub_zero, int.coe_nat_le], assumption }, { cases h1 }, { cases h2 with h2 h2; [ {cases (ihp h1.left h0.left h2) with c h3}, {cases (ihq h1.right h0.right h2) with c h3}]; cases h3 with h3 h4; refine ⟨c, list.mem_append.elim_right _, h4⟩; [left,right]; assumption }, { rcases (ihp h1.left h0.left h2.left) with ⟨cp, hp1, hp2⟩, rcases (ihq h1.right h0.right h2.right) with ⟨cq, hq1, hq2⟩, refine ⟨clause.append cp cq, ⟨_, clause.holds_append hp2 hq2⟩⟩, simp only [dnf_core, list.mem_map], refine ⟨(cp,cq),⟨_,rfl⟩⟩, rw list.mem_product, constructor; assumption } end def term.vars_core (is : list int) : list bool := is.map (λ i, if i = 0 then ff else tt) def term.vars (t : term) : list bool := term.vars_core t.snd def bools.or : list bool → list bool → list bool | [] bs2 := bs2 | bs1 [] := bs1 | (b1::bs1) (b2::bs2) := (b1 || b2)::(bools.or bs1 bs2) def terms.vars : list term → list bool | [] := [] | (t::ts) := bools.or (term.vars t) (terms.vars ts) local notation as ` {` m ` ↦ ` a `}` := list.func.set a as m def nonneg_consts_core : nat → list bool → list term | _ [] := [] | k (ff::bs) := nonneg_consts_core (k+1) bs | k (tt::bs) := ⟨0, [] {k ↦ 1}⟩::nonneg_consts_core (k+1) bs def nonneg_consts (bs : list bool) : list term := nonneg_consts_core 0 bs def nonnegate : clause → clause | (eqs,les) := let xs := terms.vars eqs in let ys := terms.vars les in let bs := bools.or xs ys in (eqs, nonneg_consts bs ++ les) def dnf (p : form) : list clause := (dnf_core p).map nonnegate lemma holds_nonneg_consts_core {v : nat → int} (h1 : ∀ x, 0 ≤ v x) : ∀ m bs, (∀ t ∈ (nonneg_consts_core m bs), 0 ≤ term.val v t) | _ [] := λ _ h2, by cases h2 | k (ff::bs) := holds_nonneg_consts_core (k+1) bs | k (tt::bs) := begin simp only [nonneg_consts_core], rw list.forall_mem_cons, constructor, { simp only [term.val, one_mul, zero_add, coeffs.val_set], apply h1 }, { apply holds_nonneg_consts_core (k+1) bs } end lemma holds_nonneg_consts {v : nat → int} {bs : list bool} : (∀ x, 0 ≤ v x) → (∀ t ∈ (nonneg_consts bs), 0 ≤ term.val v t) | h1 := by apply holds_nonneg_consts_core h1 lemma exists_clause_holds {v : nat → nat} {p : form} : p.neg_free → p.sub_free → p.holds v → ∃ c ∈ (dnf p), clause.holds (λ x, ↑(v x)) c := begin intros h1 h2 h3, rcases (exists_clause_holds_core h1 h2 h3) with ⟨c,h4,h5⟩, existsi (nonnegate c), have h6 : nonnegate c ∈ dnf p, { simp only [dnf], rw list.mem_map, refine ⟨c,h4,rfl⟩ }, refine ⟨h6,_⟩, cases c with eqs les, simp only [nonnegate, clause.holds], constructor, apply h5.left, rw list.forall_mem_append, apply and.intro (holds_nonneg_consts _) h5.right, apply int.coe_nat_nonneg end lemma exists_clause_sat {p : form} : p.neg_free → p.sub_free → p.sat → ∃ c ∈ (dnf p), clause.sat c := begin intros h1 h2 h3, cases h3 with v h3, rcases (exists_clause_holds h1 h2 h3) with ⟨c,h4,h5⟩, refine ⟨c,h4,_,h5⟩ end lemma unsat_of_unsat_dnf (p : form) : p.neg_free → p.sub_free → clauses.unsat (dnf p) → p.unsat := begin intros hnf hsf h1 h2, apply h1, apply exists_clause_sat hnf hsf h2 end end nat end omega
7c2b5b6d7f0554fca2badd6e804175ca6cc56c6e
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/category_theory/functorial.lean
6cb58ea0f856256365ce26b3f41e74509a100b99
[ "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
2,293
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.functor /-! # Unbundled functors, as a typeclass decorating the object-level function. -/ namespace category_theory universes v v₁ v₂ v₃ u u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {C : Type u₁} [𝒞 : category.{v₁} C] {D : Type u₂} [𝒟 : category.{v₂} D] include 𝒞 𝒟 /-- A unbundled functor. -/ -- Perhaps in the future we could redefine `functor` in terms of this, but that isn't the -- immediate plan. class functorial (F : C → D) : Type (max v₁ v₂ u₁ u₂) := (map : Π {X Y : C}, (X ⟶ Y) → ((F X) ⟶ (F Y))) (map_id' : ∀ (X : C), map (𝟙 X) = 𝟙 (F X) . obviously) (map_comp' : ∀ {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z), map (f ≫ g) = (map f) ≫ (map g) . obviously) restate_axiom functorial.map_id' attribute [simp] functorial.map_id restate_axiom functorial.map_comp' attribute [simp] functorial.map_comp /-- If `F : C → D` (just a function) has `[functorial F]`, we can write `map F f : F X ⟶ F Y` for the action of `F` on a morphism `f : X ⟶ Y`. -/ def map (F : C → D) [functorial.{v₁ v₂} F] {X Y : C} (f : X ⟶ Y) : F X ⟶ F Y := functorial.map.{v₁ v₂} f namespace functor /-- Bundle a functorial function as a functor. -/ def of (F : C → D) [I : functorial.{v₁ v₂} F] : C ⥤ D := { obj := F, ..I } end functor instance (F : C ⥤ D) : functorial.{v₁ v₂} (F.obj) := { .. F } @[simp] lemma map_functorial_obj (F : C ⥤ D) {X Y : C} (f : X ⟶ Y) : map F.obj f = F.map f := rfl section omit 𝒟 instance functorial_id : functorial.{v₁ v₁} (id : C → C) := { map := λ X Y f, f } end section variables {E : Type u₃} [ℰ : category.{v₃} E] include ℰ /-- `G ∘ F` is a functorial if both `F` and `G` are. -/ -- This is no longer viable as an instance in Lean 3.7, -- #lint reports an instance loop -- Will this be a problem? def functorial_comp (F : C → D) [functorial.{v₁ v₂} F] (G : D → E) [functorial.{v₂ v₃} G] : functorial.{v₁ v₃} (G ∘ F) := { ..(functor.of F ⋙ functor.of G) } end end category_theory
4d24585ee5aa19e92e83a37c06d1ca3276ff31f6
08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4
/src/Lean/Widget/UserWidget.lean
f574fe746d8556f0677112022553b41759b72bea
[ "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", "Apache-2.0", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
gebner/lean4
d51c4922640a52a6f7426536ea669ef18a1d9af5
8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f
refs/heads/master
1,685,732,780,391
1,672,962,627,000
1,673,459,398,000
373,307,283
0
0
Apache-2.0
1,691,316,730,000
1,622,669,271,000
Lean
UTF-8
Lean
false
false
6,747
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: E.W.Ayers -/ import Lean.Elab.Eval import Lean.Server.Rpc.RequestHandling open Lean namespace Lean.Widget /-- A custom piece of code that is run on the editor client. The editor can use the `Lean.Widget.getWidgetSource` RPC method to get this object. See the [manual entry](doc/widgets.md) above this declaration for more information on how to use the widgets system. -/ structure WidgetSource where /-- Sourcetext of the code to run.-/ sourcetext : String deriving Inhabited, ToJson, FromJson /-- Use this structure and the `@[widget]` attribute to define your own widgets. ```lean @[widget] def rubiks : UserWidgetDefinition := { name := "Rubiks cube app" javascript := include_str ... } ``` -/ structure UserWidgetDefinition where /-- Pretty name of user widget to display to the user. -/ name : String /-- An ESmodule that exports a react component to render. -/ javascript: String deriving Inhabited, ToJson, FromJson structure UserWidget where id : Name /-- Pretty name of widget to display to the user.-/ name : String javascriptHash: UInt64 deriving Inhabited, ToJson, FromJson private abbrev WidgetSourceRegistry := SimplePersistentEnvExtension (UInt64 × Name) (RBMap UInt64 Name compare) -- Mapping widgetSourceId to hash of sourcetext builtin_initialize userWidgetRegistry : MapDeclarationExtension UserWidget ← mkMapDeclarationExtension builtin_initialize widgetSourceRegistry : WidgetSourceRegistry ← registerSimplePersistentEnvExtension { addImportedFn := fun xss => xss.foldl (Array.foldl (fun s n => s.insert n.1 n.2)) ∅ addEntryFn := fun s n => s.insert n.1 n.2 toArrayFn := fun es => es.toArray } private unsafe def getUserWidgetDefinitionUnsafe (decl : Name) : CoreM UserWidgetDefinition := evalConstCheck UserWidgetDefinition ``UserWidgetDefinition decl @[implemented_by getUserWidgetDefinitionUnsafe] private opaque getUserWidgetDefinition (decl : Name) : CoreM UserWidgetDefinition private def attributeImpl : AttributeImpl where name := `widget descr := "Mark a string as static code that can be loaded by a widget handler." applicationTime := AttributeApplicationTime.afterCompilation add decl _stx _kind := do let env ← getEnv let defn ← getUserWidgetDefinition decl let javascriptHash := hash defn.javascript let env := userWidgetRegistry.insert env decl {id := decl, name := defn.name, javascriptHash} let env := widgetSourceRegistry.addEntry env (javascriptHash, decl) setEnv <| env builtin_initialize registerBuiltinAttribute attributeImpl /-- Input for `getWidgetSource` RPC. -/ structure GetWidgetSourceParams where /-- The hash of the sourcetext to retrieve. -/ hash: UInt64 pos : Lean.Lsp.Position deriving ToJson, FromJson open Server RequestM in @[server_rpc_method] def getWidgetSource (args : GetWidgetSourceParams) : RequestM (RequestTask WidgetSource) := do let doc ← readDoc let pos := doc.meta.text.lspPosToUtf8Pos args.pos let notFound := throwThe RequestError ⟨.invalidParams, s!"No registered user-widget with hash {args.hash}"⟩ withWaitFindSnap doc (notFoundX := notFound) (fun s => s.endPos >= pos || (widgetSourceRegistry.getState s.env).contains args.hash) fun snap => do if let some id := widgetSourceRegistry.getState snap.env |>.find? args.hash then runCoreM snap do return {sourcetext := (← getUserWidgetDefinition id).javascript} else notFound open Lean Elab /-- Try to retrieve the `UserWidgetInfo` at a particular position. -/ def widgetInfosAt? (text : FileMap) (t : InfoTree) (hoverPos : String.Pos) : List UserWidgetInfo := t.deepestNodes fun | _ctx, i@(Info.ofUserWidgetInfo wi), _cs => do if let (some pos, some tailPos) := (i.pos?, i.tailPos?) then let trailSize := i.stx.getTrailingSize -- show info at EOF even if strictly outside token + trail let atEOF := tailPos.byteIdx + trailSize == text.source.endPos.byteIdx guard <| pos ≤ hoverPos ∧ (hoverPos.byteIdx < tailPos.byteIdx + trailSize || atEOF) return wi else failure | _, _, _ => none /-- UserWidget accompanied by component props. -/ structure UserWidgetInstance extends UserWidget where /-- Arguments to be fed to the widget's main component. -/ props : Json /-- The location of the widget instance in the Lean file. -/ range? : Option Lsp.Range deriving ToJson, FromJson /-- Output of `getWidgets` RPC.-/ structure GetWidgetsResponse where widgets : Array UserWidgetInstance deriving ToJson, FromJson open Lean Server RequestM in /-- Get the `UserWidget`s present at a particular position. -/ @[server_rpc_method] def getWidgets (args : Lean.Lsp.Position) : RequestM (RequestTask (GetWidgetsResponse)) := do let doc ← readDoc let filemap := doc.meta.text let pos := filemap.lspPosToUtf8Pos args withWaitFindSnap doc (·.endPos >= pos) (notFoundX := return ⟨∅⟩) fun snap => do let env := snap.env let ws := widgetInfosAt? filemap snap.infoTree pos let ws ← ws.toArray.mapM (fun (w : UserWidgetInfo) => do let some widget := userWidgetRegistry.find? env w.widgetId | throw <| RequestError.mk .invalidParams s!"No registered user-widget with id {w.widgetId}" return { widget with props := w.props range? := String.Range.toLspRange filemap <$> Syntax.getRange? w.stx }) return {widgets := ws} /-- Save a user-widget instance to the infotree. The given `widgetId` should be the declaration name of the widget definition. -/ def saveWidgetInfo [Monad m] [MonadEnv m] [MonadError m] [MonadInfoTree m] (widgetId : Name) (props : Json) (stx : Syntax): m Unit := do let info := Info.ofUserWidgetInfo { widgetId := widgetId props := props stx := stx } pushInfoLeaf info /-! # Widget command -/ /-- Use `#widget <widgetname> <props>` to display a widget. Useful for debugging widgets. -/ syntax (name := widgetCmd) "#widget " ident term : command open Lean Lean.Meta Lean.Elab Lean.Elab.Term in private unsafe def evalJsonUnsafe (stx : Syntax) : TermElabM Json := Lean.Elab.Term.evalTerm Json (mkConst ``Json) stx @[implemented_by evalJsonUnsafe] private opaque evalJson (stx : Syntax) : TermElabM Json open Elab Command in @[command_elab widgetCmd] def elabWidgetCmd : CommandElab := fun | stx@`(#widget $id:ident $props) => do let props : Json ← runTermElabM fun _ => evalJson props saveWidgetInfo id.getId props stx | _ => throwUnsupportedSyntax end Lean.Widget
1ba6760f7c050e7d986ebb81b71558797b4b5d58
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/collectDepsIssue.lean
bea5af6cab90397f2789e487146e75c6f28e551e
[ "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
257
lean
new_frontend variables {α : Type} in def f (a : α) : List α := _ variable (P : List Nat → List Nat → Prop) in theorem foo (xs : List Nat) : (ns : List Nat) → P xs ns | [] => sorry | (n::ns) => by { cases xs; exact sorry; exact sorry }
72ccaec02e90e8080dd543b4a468849f4c13cb85
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/data/padics/hensel.lean
e46fc902f54f49eecc5fe84fe50d3b1109a0f6ca
[ "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
21,445
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import data.padics.padic_integers import topology.metric_space.cau_seq_filter import analysis.specific_limits import data.polynomial.identities import topology.algebra.polynomial /-! # Hensel's lemma on ℤ_p This file proves Hensel's lemma on ℤ_p, roughly following Keith Conrad's writeup: <http://www.math.uconn.edu/~kconrad/blurbs/gradnumthy/hensel.pdf> Hensel's lemma gives a simple condition for the existence of a root of a polynomial. The proof and motivation are described in the paper [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019]. ## References * <http://www.math.uconn.edu/~kconrad/blurbs/gradnumthy/hensel.pdf> * [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019] * <https://en.wikipedia.org/wiki/Hensel%27s_lemma> ## Tags p-adic, p adic, padic, p-adic integer -/ noncomputable theory open_locale classical topological_space -- We begin with some general lemmas that are used below in the computation. lemma padic_polynomial_dist {p : ℕ} [fact p.prime] (F : polynomial ℤ_[p]) (x y : ℤ_[p]) : ∥F.eval x - F.eval y∥ ≤ ∥x - y∥ := let ⟨z, hz⟩ := F.eval_sub_factor x y in calc ∥F.eval x - F.eval y∥ = ∥z∥ * ∥x - y∥ : by simp [hz] ... ≤ 1 * ∥x - y∥ : mul_le_mul_of_nonneg_right (padic_norm_z.le_one _) (norm_nonneg _) ... = ∥x - y∥ : by simp open filter metric private lemma comp_tendsto_lim {p : ℕ} [fact p.prime] {F : polynomial ℤ_[p]} (ncs : cau_seq ℤ_[p] norm) : tendsto (λ i, F.eval (ncs i)) at_top (𝓝 (F.eval ncs.lim)) := (F.continuous_eval.tendsto _).comp ncs.tendsto_limit section parameters {p : ℕ} [fact p.prime] {ncs : cau_seq ℤ_[p] norm} {F : polynomial ℤ_[p]} {a : ℤ_[p]} (ncs_der_val : ∀ n, ∥F.derivative.eval (ncs n)∥ = ∥F.derivative.eval a∥) include ncs_der_val private lemma ncs_tendsto_const : tendsto (λ i, ∥F.derivative.eval (ncs i)∥) at_top (𝓝 ∥F.derivative.eval a∥) := by convert tendsto_const_nhds; ext; rw ncs_der_val private lemma ncs_tendsto_lim : tendsto (λ i, ∥F.derivative.eval (ncs i)∥) at_top (𝓝 (∥F.derivative.eval ncs.lim∥)) := tendsto.comp (continuous_iff_continuous_at.1 continuous_norm _) (comp_tendsto_lim _) private lemma norm_deriv_eq : ∥F.derivative.eval ncs.lim∥ = ∥F.derivative.eval a∥ := tendsto_nhds_unique ncs_tendsto_lim ncs_tendsto_const end section parameters {p : ℕ} [fact p.prime] {ncs : cau_seq ℤ_[p] norm} {F : polynomial ℤ_[p]} (hnorm : tendsto (λ i, ∥F.eval (ncs i)∥) at_top (𝓝 0)) include hnorm private lemma tendsto_zero_of_norm_tendsto_zero : tendsto (λ i, F.eval (ncs i)) at_top (𝓝 0) := tendsto_iff_norm_tendsto_zero.2 (by simpa using hnorm) lemma limit_zero_of_norm_tendsto_zero : F.eval ncs.lim = 0 := tendsto_nhds_unique (comp_tendsto_lim _) tendsto_zero_of_norm_tendsto_zero end section hensel open nat parameters {p : ℕ} [fact p.prime] {F : polynomial ℤ_[p]} {a : ℤ_[p]} (hnorm : ∥F.eval a∥ < ∥F.derivative.eval a∥^2) (hnsol : F.eval a ≠ 0) include hnorm /-- `T` is an auxiliary value that is used to control the behavior of the polynomial `F`. -/ private def T : ℝ := ∥(F.eval a / (F.derivative.eval a)^2 : ℚ_[p])∥ private lemma deriv_sq_norm_pos : 0 < ∥F.derivative.eval a∥ ^ 2 := lt_of_le_of_lt (norm_nonneg _) hnorm private lemma deriv_sq_norm_ne_zero : ∥F.derivative.eval a∥^2 ≠ 0 := ne_of_gt deriv_sq_norm_pos private lemma deriv_norm_ne_zero : ∥F.derivative.eval a∥ ≠ 0 := λ h, deriv_sq_norm_ne_zero (by simp [*, _root_.pow_two]) private lemma deriv_norm_pos : 0 < ∥F.derivative.eval a∥ := lt_of_le_of_ne (norm_nonneg _) (ne.symm deriv_norm_ne_zero) private lemma deriv_ne_zero : F.derivative.eval a ≠ 0 := mt norm_eq_zero.2 deriv_norm_ne_zero private lemma T_def : T = ∥F.eval a∥ / ∥F.derivative.eval a∥^2 := calc T = ∥F.eval a∥ / ∥((F.derivative.eval a)^2 : ℚ_[p])∥ : normed_field.norm_div _ _ ... = ∥F.eval a∥ / ∥(F.derivative.eval a)^2∥ : by simp [norm, padic_norm_z] ... = ∥F.eval a∥ / ∥(F.derivative.eval a)∥^2 : by simp [pow, monoid.pow] private lemma T_lt_one : T < 1 := let h := (div_lt_one_iff_lt deriv_sq_norm_pos).2 hnorm in by rw T_def; apply h private lemma T_pow {n : ℕ} (hn : n > 0) : T ^ n < 1 := have T ^ n ≤ T ^ 1, from pow_le_pow_of_le_one (norm_nonneg _) (le_of_lt T_lt_one) (succ_le_of_lt hn), lt_of_le_of_lt (by simpa) T_lt_one private lemma T_pow' (n : ℕ) : T ^ (2 ^ n) < 1 := (T_pow (nat.pow_pos (by norm_num) _)) private lemma T_pow_nonneg (n : ℕ) : T ^ n ≥ 0 := pow_nonneg (norm_nonneg _) _ /-- We will construct a sequence of elements of ℤ_p satisfying successive values of `ih`. -/ private def ih (n : ℕ) (z : ℤ_[p]) : Prop := ∥F.derivative.eval z∥ = ∥F.derivative.eval a∥ ∧ ∥F.eval z∥ ≤ ∥F.derivative.eval a∥^2 * T ^ (2^n) private lemma ih_0 : ih 0 a := ⟨ rfl, by simp [T_def, mul_div_cancel' _ (ne_of_gt (deriv_sq_norm_pos hnorm))] ⟩ private lemma calc_norm_le_one {n : ℕ} {z : ℤ_[p]} (hz : ih n z) : ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ ≤ 1 := calc ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ = ∥(↑(F.eval z) : ℚ_[p])∥ / ∥(↑(F.derivative.eval z) : ℚ_[p])∥ : normed_field.norm_div _ _ ... = ∥F.eval z∥ / ∥F.derivative.eval a∥ : by simp [hz.1] ... ≤ ∥F.derivative.eval a∥^2 * T^(2^n) / ∥F.derivative.eval a∥ : (div_le_div_right deriv_norm_pos).2 hz.2 ... = ∥F.derivative.eval a∥ * T^(2^n) : div_sq_cancel (ne_of_gt deriv_norm_pos) _ ... ≤ 1 : mul_le_one (padic_norm_z.le_one _) (T_pow_nonneg _) (le_of_lt (T_pow' _)) private lemma calc_deriv_dist {z z' z1 : ℤ_[p]} (hz' : z' = z - z1) (hz1 : ∥z1∥ = ∥F.eval z∥ / ∥F.derivative.eval a∥) {n} (hz : ih n z) : ∥F.derivative.eval z' - F.derivative.eval z∥ < ∥F.derivative.eval a∥ := calc ∥F.derivative.eval z' - F.derivative.eval z∥ ≤ ∥z' - z∥ : padic_polynomial_dist _ _ _ ... = ∥z1∥ : by simp only [sub_eq_add_neg, add_assoc, hz', add_add_neg_cancel'_right, norm_neg] ... = ∥F.eval z∥ / ∥F.derivative.eval a∥ : hz1 ... ≤ ∥F.derivative.eval a∥^2 * T^(2^n) / ∥F.derivative.eval a∥ : (div_le_div_right deriv_norm_pos).2 hz.2 ... = ∥F.derivative.eval a∥ * T^(2^n) : div_sq_cancel deriv_norm_ne_zero _ ... < ∥F.derivative.eval a∥ : (mul_lt_iff_lt_one_right deriv_norm_pos).2 (T_pow (pow_pos (by norm_num) _)) private def calc_eval_z' {z z' z1 : ℤ_[p]} (hz' : z' = z - z1) {n} (hz : ih n z) (h1 : ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ ≤ 1) (hzeq : z1 = ⟨_, h1⟩) : {q : ℤ_[p] // F.eval z' = q * z1^2} := have hdzne' : (↑(F.derivative.eval z) : ℚ_[p]) ≠ 0, from have hdzne : F.derivative.eval z ≠ 0, from mt norm_eq_zero.2 (by rw hz.1; apply deriv_norm_ne_zero; assumption), λ h, hdzne $ subtype.ext_iff_val.2 h, let ⟨q, hq⟩ := F.binom_expansion z (-z1) in have ∥(↑(F.derivative.eval z) * (↑(F.eval z) / ↑(F.derivative.eval z)) : ℚ_[p])∥ ≤ 1, by {rw padic_norm_e.mul, apply mul_le_one, apply padic_norm_z.le_one, apply norm_nonneg, apply h1}, have F.derivative.eval z * (-z1) = -F.eval z, from calc F.derivative.eval z * (-z1) = (F.derivative.eval z) * -⟨↑(F.eval z) / ↑(F.derivative.eval z), h1⟩ : by rw [hzeq] ... = -((F.derivative.eval z) * ⟨↑(F.eval z) / ↑(F.derivative.eval z), h1⟩) : by simp [subtype.ext_iff_val] ... = -(⟨↑(F.derivative.eval z) * (↑(F.eval z) / ↑(F.derivative.eval z)), this⟩) : subtype.ext_iff_val.2 $ by simp ... = -(F.eval z) : by simp [mul_div_cancel' _ hdzne'], have heq : F.eval z' = q * z1^2, by simpa [this, hz'] using hq, ⟨q, heq⟩ private def calc_eval_z'_norm {z z' z1 : ℤ_[p]} {n} (hz : ih n z) {q} (heq : F.eval z' = q * z1^2) (h1 : ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ ≤ 1) (hzeq : z1 = ⟨_, h1⟩) : ∥F.eval z'∥ ≤ ∥F.derivative.eval a∥^2 * T^(2^(n+1)) := calc ∥F.eval z'∥ = ∥q∥ * ∥z1∥^2 : by simp [heq] ... ≤ 1 * ∥z1∥^2 : mul_le_mul_of_nonneg_right (padic_norm_z.le_one _) (pow_nonneg (norm_nonneg _) _) ... = ∥F.eval z∥^2 / ∥F.derivative.eval a∥^2 : by simp [hzeq, hz.1, div_pow] ... ≤ (∥F.derivative.eval a∥^2 * T^(2^n))^2 / ∥F.derivative.eval a∥^2 : (div_le_div_right deriv_sq_norm_pos).2 (pow_le_pow_of_le_left (norm_nonneg _) hz.2 _) ... = (∥F.derivative.eval a∥^2)^2 * (T^(2^n))^2 / ∥F.derivative.eval a∥^2 : by simp only [_root_.mul_pow] ... = ∥F.derivative.eval a∥^2 * (T^(2^n))^2 : div_sq_cancel deriv_sq_norm_ne_zero _ ... = ∥F.derivative.eval a∥^2 * T^(2^(n + 1)) : by rw [←pow_mul]; refl set_option eqn_compiler.zeta true /-- Given `z : ℤ_[p]` satisfying `ih n z`, construct `z' : ℤ_[p]` satisfying `ih (n+1) z'`. We need the hypothesis `ih n z`, since otherwise `z'` is not necessarily an integer. -/ private def ih_n {n : ℕ} {z : ℤ_[p]} (hz : ih n z) : {z' : ℤ_[p] // ih (n+1) z'} := have h1 : ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ ≤ 1, from calc_norm_le_one hz, let z1 : ℤ_[p] := ⟨_, h1⟩, z' : ℤ_[p] := z - z1 in ⟨ z', have hdist : ∥F.derivative.eval z' - F.derivative.eval z∥ < ∥F.derivative.eval a∥, from calc_deriv_dist rfl (by simp [z1, hz.1]) hz, have hfeq : ∥F.derivative.eval z'∥ = ∥F.derivative.eval a∥, begin rw [sub_eq_add_neg, ← hz.1, ←norm_neg (F.derivative.eval z)] at hdist, have := padic_norm_z.eq_of_norm_add_lt_right hdist, rwa [norm_neg, hz.1] at this end, let ⟨q, heq⟩ := calc_eval_z' rfl hz h1 rfl in have hnle : ∥F.eval z'∥ ≤ ∥F.derivative.eval a∥^2 * T^(2^(n+1)), from calc_eval_z'_norm hz heq h1 rfl, ⟨hfeq, hnle⟩⟩ set_option eqn_compiler.zeta false -- why doesn't "noncomputable theory" stick here? private noncomputable def newton_seq_aux : Π n : ℕ, {z : ℤ_[p] // ih n z} | 0 := ⟨a, ih_0⟩ | (k+1) := ih_n (newton_seq_aux k).2 private def newton_seq (n : ℕ) : ℤ_[p] := (newton_seq_aux n).1 private lemma newton_seq_deriv_norm (n : ℕ) : ∥F.derivative.eval (newton_seq n)∥ = ∥F.derivative.eval a∥ := (newton_seq_aux n).2.1 private lemma newton_seq_norm_le (n : ℕ) : ∥F.eval (newton_seq n)∥ ≤ ∥F.derivative.eval a∥^2 * T ^ (2^n) := (newton_seq_aux n).2.2 private lemma newton_seq_norm_eq (n : ℕ) : ∥newton_seq (n+1) - newton_seq n∥ = ∥F.eval (newton_seq n)∥ / ∥F.derivative.eval (newton_seq n)∥ := by simp [newton_seq, newton_seq_aux, ih_n, sub_eq_add_neg, add_comm] private lemma newton_seq_succ_dist (n : ℕ) : ∥newton_seq (n+1) - newton_seq n∥ ≤ ∥F.derivative.eval a∥ * T^(2^n) := calc ∥newton_seq (n+1) - newton_seq n∥ = ∥F.eval (newton_seq n)∥ / ∥F.derivative.eval (newton_seq n)∥ : newton_seq_norm_eq _ ... = ∥F.eval (newton_seq n)∥ / ∥F.derivative.eval a∥ : by rw newton_seq_deriv_norm ... ≤ ∥F.derivative.eval a∥^2 * T ^ (2^n) / ∥F.derivative.eval a∥ : (div_le_div_right deriv_norm_pos).2 (newton_seq_norm_le _) ... = ∥F.derivative.eval a∥ * T^(2^n) : div_sq_cancel (ne_of_gt deriv_norm_pos) _ include hnsol private lemma T_pos : T > 0 := begin rw T_def, exact div_pos_of_pos_of_pos (norm_pos_iff.2 hnsol) (deriv_sq_norm_pos hnorm) end private lemma newton_seq_succ_dist_weak (n : ℕ) : ∥newton_seq (n+2) - newton_seq (n+1)∥ < ∥F.eval a∥ / ∥F.derivative.eval a∥ := have 2 ≤ 2^(n+1), from have _, from pow_le_pow (by norm_num : 1 ≤ 2) (nat.le_add_left _ _ : 1 ≤ n + 1), by simpa using this, calc ∥newton_seq (n+2) - newton_seq (n+1)∥ ≤ ∥F.derivative.eval a∥ * T^(2^(n+1)) : newton_seq_succ_dist _ ... ≤ ∥F.derivative.eval a∥ * T^2 : mul_le_mul_of_nonneg_left (pow_le_pow_of_le_one (norm_nonneg _) (le_of_lt T_lt_one) this) (norm_nonneg _) ... < ∥F.derivative.eval a∥ * T^1 : mul_lt_mul_of_pos_left (pow_lt_pow_of_lt_one T_pos T_lt_one (by norm_num)) deriv_norm_pos ... = ∥F.eval a∥ / ∥F.derivative.eval a∥ : begin rw [T, _root_.pow_two, _root_.pow_one, normed_field.norm_div, ←mul_div_assoc, padic_norm_e.mul], apply mul_div_mul_left, apply deriv_norm_ne_zero; assumption end private lemma newton_seq_dist_aux (n : ℕ) : ∀ k : ℕ, ∥newton_seq (n + k) - newton_seq n∥ ≤ ∥F.derivative.eval a∥ * T^(2^n) | 0 := begin simp, apply mul_nonneg, {apply norm_nonneg}, {apply T_pow_nonneg} end | (k+1) := have 2^n ≤ 2^(n+k), by {rw [←nat.pow_eq_pow, ←nat.pow_eq_pow], apply pow_le_pow, norm_num, apply nat.le_add_right}, calc ∥newton_seq (n + (k + 1)) - newton_seq n∥ = ∥newton_seq ((n + k) + 1) - newton_seq n∥ : by rw add_assoc ... = ∥(newton_seq ((n + k) + 1) - newton_seq (n+k)) + (newton_seq (n+k) - newton_seq n)∥ : by rw ←sub_add_sub_cancel ... ≤ max (∥newton_seq ((n + k) + 1) - newton_seq (n+k)∥) (∥newton_seq (n+k) - newton_seq n∥) : padic_norm_z.nonarchimedean _ _ ... ≤ max (∥F.derivative.eval a∥ * T^(2^((n + k)))) (∥F.derivative.eval a∥ * T^(2^n)) : max_le_max (newton_seq_succ_dist _) (newton_seq_dist_aux _) ... = ∥F.derivative.eval a∥ * T^(2^n) : max_eq_right $ mul_le_mul_of_nonneg_left (pow_le_pow_of_le_one (norm_nonneg _) (le_of_lt T_lt_one) this) (norm_nonneg _) private lemma newton_seq_dist {n k : ℕ} (hnk : n ≤ k) : ∥newton_seq k - newton_seq n∥ ≤ ∥F.derivative.eval a∥ * T^(2^n) := have hex : ∃ m, k = n + m, from exists_eq_add_of_le hnk, let ⟨_, hex'⟩ := hex in by rw hex'; apply newton_seq_dist_aux; assumption private lemma newton_seq_dist_to_a : ∀ n : ℕ, 0 < n → ∥newton_seq n - a∥ = ∥F.eval a∥ / ∥F.derivative.eval a∥ | 1 h := by simp [sub_eq_add_neg, add_assoc, newton_seq, newton_seq_aux, ih_n]; apply normed_field.norm_div | (k+2) h := have hlt : ∥newton_seq (k+2) - newton_seq (k+1)∥ < ∥newton_seq (k+1) - a∥, by rw newton_seq_dist_to_a (k+1) (succ_pos _); apply newton_seq_succ_dist_weak; assumption, have hne' : ∥newton_seq (k + 2) - newton_seq (k+1)∥ ≠ ∥newton_seq (k+1) - a∥, from ne_of_lt hlt, calc ∥newton_seq (k + 2) - a∥ = ∥(newton_seq (k + 2) - newton_seq (k+1)) + (newton_seq (k+1) - a)∥ : by rw ←sub_add_sub_cancel ... = max (∥newton_seq (k + 2) - newton_seq (k+1)∥) (∥newton_seq (k+1) - a∥) : padic_norm_z.add_eq_max_of_ne hne' ... = ∥newton_seq (k+1) - a∥ : max_eq_right_of_lt hlt ... = ∥polynomial.eval a F∥ / ∥polynomial.eval a (polynomial.derivative F)∥ : newton_seq_dist_to_a (k+1) (succ_pos _) private lemma bound' : tendsto (λ n : ℕ, ∥F.derivative.eval a∥ * T^(2^n)) at_top (𝓝 0) := begin rw ←mul_zero (∥F.derivative.eval a∥), exact tendsto_const_nhds.mul (tendsto.comp (tendsto_pow_at_top_nhds_0_of_lt_1 (norm_nonneg _) (T_lt_one hnorm)) (nat.tendsto_pow_at_top_at_top_of_one_lt (by norm_num))) end private lemma bound : ∀ {ε}, ε > 0 → ∃ N : ℕ, ∀ {n}, n ≥ N → ∥F.derivative.eval a∥ * T^(2^n) < ε := have mtn : ∀ n : ℕ, ∥polynomial.eval a (polynomial.derivative F)∥ * T ^ (2 ^ n) ≥ 0, from λ n, mul_nonneg (norm_nonneg _) (T_pow_nonneg _), begin have := bound' hnorm hnsol, simp [tendsto, nhds] at this, intros ε hε, cases this (ball 0 ε) (mem_ball_self hε) (is_open_ball) with N hN, existsi N, intros n hn, simpa [normed_field.norm_mul, real.norm_eq_abs, abs_of_nonneg (mtn n)] using hN _ hn end private lemma bound'_sq : tendsto (λ n : ℕ, ∥F.derivative.eval a∥^2 * T^(2^n)) at_top (𝓝 0) := begin rw [←mul_zero (∥F.derivative.eval a∥), _root_.pow_two], simp only [mul_assoc], apply tendsto.mul, { apply tendsto_const_nhds }, { apply bound', assumption } end private theorem newton_seq_is_cauchy : is_cau_seq norm newton_seq := begin intros ε hε, cases bound hnorm hnsol hε with N hN, existsi N, intros j hj, apply lt_of_le_of_lt, { apply newton_seq_dist _ _ hj, assumption }, { apply hN, apply le_refl } end private def newton_cau_seq : cau_seq ℤ_[p] norm := ⟨_, newton_seq_is_cauchy⟩ private def soln : ℤ_[p] := newton_cau_seq.lim private lemma soln_spec {ε : ℝ} (hε : ε > 0) : ∃ (N : ℕ), ∀ {i : ℕ}, i ≥ N → ∥soln - newton_cau_seq i∥ < ε := setoid.symm (cau_seq.equiv_lim newton_cau_seq) _ hε private lemma soln_deriv_norm : ∥F.derivative.eval soln∥ = ∥F.derivative.eval a∥ := norm_deriv_eq newton_seq_deriv_norm private lemma newton_seq_norm_tendsto_zero : tendsto (λ i, ∥F.eval (newton_cau_seq i)∥) at_top (𝓝 0) := squeeze_zero (λ _, norm_nonneg _) newton_seq_norm_le bound'_sq private lemma newton_seq_dist_tendsto : tendsto (λ n, ∥newton_cau_seq n - a∥) at_top (𝓝 (∥F.eval a∥ / ∥F.derivative.eval a∥)) := tendsto_const_nhds.congr' $ eventually_at_top.2 ⟨1, λ _ hx, (newton_seq_dist_to_a _ hx).symm⟩ private lemma newton_seq_dist_tendsto' : tendsto (λ n, ∥newton_cau_seq n - a∥) at_top (𝓝 ∥soln - a∥) := (continuous_norm.tendsto _).comp (newton_cau_seq.tendsto_limit.sub tendsto_const_nhds) private lemma soln_dist_to_a : ∥soln - a∥ = ∥F.eval a∥ / ∥F.derivative.eval a∥ := tendsto_nhds_unique newton_seq_dist_tendsto' newton_seq_dist_tendsto private lemma soln_dist_to_a_lt_deriv : ∥soln - a∥ < ∥F.derivative.eval a∥ := begin rw soln_dist_to_a, apply div_lt_of_mul_lt_of_pos, { apply deriv_norm_pos; assumption }, { rwa _root_.pow_two at hnorm } end private lemma eval_soln : F.eval soln = 0 := limit_zero_of_norm_tendsto_zero newton_seq_norm_tendsto_zero private lemma soln_unique (z : ℤ_[p]) (hev : F.eval z = 0) (hnlt : ∥z - a∥ < ∥F.derivative.eval a∥) : z = soln := have soln_dist : ∥z - soln∥ < ∥F.derivative.eval a∥, from calc ∥z - soln∥ = ∥(z - a) + (a - soln)∥ : by rw sub_add_sub_cancel ... ≤ max (∥z - a∥) (∥a - soln∥) : padic_norm_z.nonarchimedean _ _ ... < ∥F.derivative.eval a∥ : max_lt hnlt (by rw norm_sub_rev; apply soln_dist_to_a_lt_deriv), let h := z - soln, ⟨q, hq⟩ := F.binom_expansion soln h in have (F.derivative.eval soln + q * h) * h = 0, from eq.symm (calc 0 = F.eval (soln + h) : by simp [hev, h] ... = F.derivative.eval soln * h + q * h^2 : by rw [hq, eval_soln, zero_add] ... = (F.derivative.eval soln + q * h) * h : by rw [_root_.pow_two, right_distrib, mul_assoc]), have h = 0, from by_contradiction $ λ hne, have F.derivative.eval soln + q * h = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right hne, have F.derivative.eval soln = (-q) * h, by simpa using eq_neg_of_add_eq_zero this, lt_irrefl ∥F.derivative.eval soln∥ (calc ∥F.derivative.eval soln∥ = ∥(-q) * h∥ : by rw this ... ≤ 1 * ∥h∥ : by rw [padic_norm_z.mul]; exact mul_le_mul_of_nonneg_right (padic_norm_z.le_one _) (norm_nonneg _) ... = ∥z - soln∥ : by simp [h] ... < ∥F.derivative.eval soln∥ : by rw soln_deriv_norm; apply soln_dist), eq_of_sub_eq_zero (by rw ←this; refl) end hensel variables {p : ℕ} [fact p.prime] {F : polynomial ℤ_[p]} {a : ℤ_[p]} private lemma a_soln_is_unique (ha : F.eval a = 0) (z' : ℤ_[p]) (hz' : F.eval z' = 0) (hnormz' : ∥z' - a∥ < ∥F.derivative.eval a∥) : z' = a := let h := z' - a, ⟨q, hq⟩ := F.binom_expansion a h in have (F.derivative.eval a + q * h) * h = 0, from eq.symm (calc 0 = F.eval (a + h) : show 0 = F.eval (a + (z' - a)), by rw add_comm; simp [hz'] ... = F.derivative.eval a * h + q * h^2 : by rw [hq, ha, zero_add] ... = (F.derivative.eval a + q * h) * h : by rw [_root_.pow_two, right_distrib, mul_assoc]), have h = 0, from by_contradiction $ λ hne, have F.derivative.eval a + q * h = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right hne, have F.derivative.eval a = (-q) * h, by simpa using eq_neg_of_add_eq_zero this, lt_irrefl ∥F.derivative.eval a∥ (calc ∥F.derivative.eval a∥ = ∥q∥*∥h∥ : by simp [this] ... ≤ 1*∥h∥ : mul_le_mul_of_nonneg_right (padic_norm_z.le_one _) (norm_nonneg _) ... < ∥F.derivative.eval a∥ : by simpa [h]), eq_of_sub_eq_zero (by rw ←this; refl) variable (hnorm : ∥F.eval a∥ < ∥F.derivative.eval a∥^2) include hnorm private lemma a_is_soln (ha : F.eval a = 0) : F.eval a = 0 ∧ ∥a - a∥ < ∥F.derivative.eval a∥ ∧ ∥F.derivative.eval a∥ = ∥F.derivative.eval a∥ ∧ ∀ z', F.eval z' = 0 → ∥z' - a∥ < ∥F.derivative.eval a∥ → z' = a := ⟨ha, by simp; apply deriv_norm_pos; apply hnorm, rfl, a_soln_is_unique ha⟩ lemma hensels_lemma : ∃ z : ℤ_[p], F.eval z = 0 ∧ ∥z - a∥ < ∥F.derivative.eval a∥ ∧ ∥F.derivative.eval z∥ = ∥F.derivative.eval a∥ ∧ ∀ z', F.eval z' = 0 → ∥z' - a∥ < ∥F.derivative.eval a∥ → z' = z := if ha : F.eval a = 0 then ⟨a, a_is_soln hnorm ha⟩ else by refine ⟨soln _ _, eval_soln _ _, soln_dist_to_a_lt_deriv _ _, soln_deriv_norm _ _, soln_unique _ _⟩; assumption
afc29da5037b20c282b9c66b24235448fd18d8e6
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Elab/Config.lean
f7ad2d85ca56b07c7759dfadbd96d42489309323
[ "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
1,926
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.Meta.Basic namespace Lean.Elab.Term /-- Set `isDefEq` configuration for the elaborator. Note that we enable all approximations but `quasiPatternApprox` In Lean3 and Lean 4, we used to use the quasi-pattern approximation during elaboration. The example: ``` def ex : StateT δ (StateT σ Id) σ := monadLift (get : StateT σ Id σ) ``` demonstrates why it produces counterintuitive behavior. We have the `Monad-lift` application: ``` @monadLift ?m ?n ?c ?α (get : StateT σ id σ) : ?n ?α ``` It produces the following unification problem when we process the expected type: ``` ?n ?α =?= StateT δ (StateT σ id) σ ==> (approximate using first-order unification) ?n := StateT δ (StateT σ id) ?α := σ ``` Then, we need to solve: ``` ?m ?α =?= StateT σ id σ ==> instantiate metavars ?m σ =?= StateT σ id σ ==> (approximate since it is a quasi-pattern unification constraint) ?m := fun σ => StateT σ id σ ``` Note that the constraint is not a Milner pattern because σ is in the local context of `?m`. We are ignoring the other possible solutions: ``` ?m := fun σ' => StateT σ id σ ?m := fun σ' => StateT σ' id σ ?m := fun σ' => StateT σ id σ' ``` We need the quasi-pattern approximation for elaborating recursor-like expressions (e.g., dependent `match with` expressions). If we had use first-order unification, then we would have produced the right answer: `?m := StateT σ id` Haskell would work on this example since it always uses first-order unification. -/ def setElabConfig (cfg : Meta.Config) : Meta.Config := { cfg with foApprox := true, ctxApprox := true, constApprox := false, quasiPatternApprox := false } end Lean.Elab.Term
a545f99c30e981c16db183c3a4a2da8f9eb33d44
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/386.lean
d8fcfe34f244e3b6583481d11c30ebcaf299d127
[ "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
623
lean
class Fintype (α : Type) where axiom Finset (α : Type) : Type axiom Finset.univ {α : Type} [Fintype α] : Finset α axiom Finset.filter {α : Type} (s : Finset α) (ϕ : α → Bool) : Finset α -- The following should not elaborate, since there are no `Fintype` instances -- Instead it yields: "error: (kernel) declaration has metavariables 'kernelErrorMetavar'" def kernelErrorMetavar1 (n : Nat) : Finset (Fin n) := Finset.univ.filter (fun (i : Fin n) => true) instance : Fintype (Fin n) := ⟨⟩ noncomputable def kernelErrorMetavar2 (n : Nat) : Finset (Fin n) := Finset.univ.filter (fun (i : Fin n) => true)
8ee7aff11dbe031425a37cc3bb0523119bf51a6c
26ac254ecb57ffcb886ff709cf018390161a9225
/src/data/num/lemmas.lean
507436b614c471f15c40196ef06b66051cfe1810
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
48,332
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import data.num.bitwise import data.int.char_zero import data.nat.gcd /-! # Properties of the binary representation of integers -/ local attribute [simp] add_assoc namespace pos_num variables {α : Type*} @[simp, norm_cast] theorem cast_one [has_zero α] [has_one α] [has_add α] : ((1 : pos_num) : α) = 1 := rfl @[simp] theorem cast_one' [has_zero α] [has_one α] [has_add α] : (pos_num.one : α) = 1 := rfl @[simp, norm_cast] theorem cast_bit0 [has_zero α] [has_one α] [has_add α] (n : pos_num) : (n.bit0 : α) = _root_.bit0 n := rfl @[simp, norm_cast] theorem cast_bit1 [has_zero α] [has_one α] [has_add α] (n : pos_num) : (n.bit1 : α) = _root_.bit1 n := rfl @[simp, norm_cast] theorem cast_to_nat [add_monoid α] [has_one α] : ∀ n : pos_num, ((n : ℕ) : α) = n | 1 := nat.cast_one | (bit0 p) := (nat.cast_bit0 _).trans $ congr_arg _root_.bit0 p.cast_to_nat | (bit1 p) := (nat.cast_bit1 _).trans $ congr_arg _root_.bit1 p.cast_to_nat @[simp, norm_cast] theorem to_nat_to_int (n : pos_num) : ((n : ℕ) : ℤ) = n := by rw [← int.nat_cast_eq_coe_nat, cast_to_nat] @[simp, norm_cast] theorem cast_to_int [add_group α] [has_one α] (n : pos_num) : ((n : ℤ) : α) = n := by rw [← to_nat_to_int, int.cast_coe_nat, cast_to_nat] theorem succ_to_nat : ∀ n, (succ n : ℕ) = n + 1 | 1 := rfl | (bit0 p) := rfl | (bit1 p) := (congr_arg _root_.bit0 (succ_to_nat p)).trans $ show ↑p + 1 + ↑p + 1 = ↑p + ↑p + 1 + 1, by simp [add_left_comm] theorem one_add (n : pos_num) : 1 + n = succ n := by cases n; refl theorem add_one (n : pos_num) : n + 1 = succ n := by cases n; refl @[norm_cast] theorem add_to_nat : ∀ m n, ((m + n : pos_num) : ℕ) = m + n | 1 b := by rw [one_add b, succ_to_nat, add_comm]; refl | a 1 := by rw [add_one a, succ_to_nat]; refl | (bit0 a) (bit0 b) := (congr_arg _root_.bit0 (add_to_nat a b)).trans $ show ((a + b) + (a + b) : ℕ) = (a + a) + (b + b), by simp [add_left_comm] | (bit0 a) (bit1 b) := (congr_arg _root_.bit1 (add_to_nat a b)).trans $ show ((a + b) + (a + b) + 1 : ℕ) = (a + a) + (b + b + 1), by simp [add_left_comm] | (bit1 a) (bit0 b) := (congr_arg _root_.bit1 (add_to_nat a b)).trans $ show ((a + b) + (a + b) + 1 : ℕ) = (a + a + 1) + (b + b), by simp [add_comm, add_left_comm] | (bit1 a) (bit1 b) := show (succ (a + b) + succ (a + b) : ℕ) = (a + a + 1) + (b + b + 1), by rw [succ_to_nat, add_to_nat]; simp [add_left_comm] theorem add_succ : ∀ (m n : pos_num), m + succ n = succ (m + n) | 1 b := by simp [one_add] | (bit0 a) 1 := congr_arg bit0 (add_one a) | (bit1 a) 1 := congr_arg bit1 (add_one a) | (bit0 a) (bit0 b) := rfl | (bit0 a) (bit1 b) := congr_arg bit0 (add_succ a b) | (bit1 a) (bit0 b) := rfl | (bit1 a) (bit1 b) := congr_arg bit1 (add_succ a b) theorem bit0_of_bit0 : Π n, _root_.bit0 n = bit0 n | 1 := rfl | (bit0 p) := congr_arg bit0 (bit0_of_bit0 p) | (bit1 p) := show bit0 (succ (_root_.bit0 p)) = _, by rw bit0_of_bit0; refl theorem bit1_of_bit1 (n : pos_num) : _root_.bit1 n = bit1 n := show _root_.bit0 n + 1 = bit1 n, by rw [add_one, bit0_of_bit0]; refl @[norm_cast] theorem mul_to_nat (m) : ∀ n, ((m * n : pos_num) : ℕ) = m * n | 1 := (mul_one _).symm | (bit0 p) := show (↑(m * p) + ↑(m * p) : ℕ) = ↑m * (p + p), by rw [mul_to_nat, left_distrib] | (bit1 p) := (add_to_nat (bit0 (m * p)) m).trans $ show (↑(m * p) + ↑(m * p) + ↑m : ℕ) = ↑m * (p + p) + m, by rw [mul_to_nat, left_distrib] theorem to_nat_pos : ∀ n : pos_num, 0 < (n : ℕ) | 1 := zero_lt_one | (bit0 p) := let h := to_nat_pos p in add_pos h h | (bit1 p) := nat.succ_pos _ theorem cmp_to_nat_lemma {m n : pos_num} : (m:ℕ) < n → (bit1 m : ℕ) < bit0 n := show (m:ℕ) < n → (m + m + 1 + 1 : ℕ) ≤ n + n, by intro h; rw [nat.add_right_comm m m 1, add_assoc]; exact add_le_add h h theorem cmp_swap (m) : ∀n, (cmp m n).swap = cmp n m := by induction m with m IH m IH; intro n; cases n with n n; try {unfold cmp}; try {refl}; rw ←IH; cases cmp m n; refl theorem cmp_to_nat : ∀ (m n), (ordering.cases_on (cmp m n) ((m:ℕ) < n) (m = n) ((m:ℕ) > n) : Prop) | 1 1 := rfl | (bit0 a) 1 := let h : (1:ℕ) ≤ a := to_nat_pos a in add_le_add h h | (bit1 a) 1 := nat.succ_lt_succ $ to_nat_pos $ bit0 a | 1 (bit0 b) := let h : (1:ℕ) ≤ b := to_nat_pos b in add_le_add h h | 1 (bit1 b) := nat.succ_lt_succ $ to_nat_pos $ bit0 b | (bit0 a) (bit0 b) := begin have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro, { exact add_lt_add this this }, { rw this }, { exact add_lt_add this this } end | (bit0 a) (bit1 b) := begin dsimp [cmp], have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro, { exact nat.le_succ_of_le (add_lt_add this this) }, { rw this, apply nat.lt_succ_self }, { exact cmp_to_nat_lemma this } end | (bit1 a) (bit0 b) := begin dsimp [cmp], have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro, { exact cmp_to_nat_lemma this }, { rw this, apply nat.lt_succ_self }, { exact nat.le_succ_of_le (add_lt_add this this) }, end | (bit1 a) (bit1 b) := begin have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro, { exact nat.succ_lt_succ (add_lt_add this this) }, { rw this }, { exact nat.succ_lt_succ (add_lt_add this this) } end @[norm_cast] theorem lt_to_nat {m n : pos_num} : (m:ℕ) < n ↔ m < n := show (m:ℕ) < n ↔ cmp m n = ordering.lt, from match cmp m n, cmp_to_nat m n with | ordering.lt, h := by simp at h; simp [h] | ordering.eq, h := by simp at h; simp [h, lt_irrefl]; exact dec_trivial | ordering.gt, h := by simp [not_lt_of_gt h]; exact dec_trivial end @[norm_cast] theorem le_to_nat {m n : pos_num} : (m:ℕ) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr lt_to_nat end pos_num namespace num variables {α : Type*} open pos_num theorem add_zero (n : num) : n + 0 = n := by cases n; refl theorem zero_add (n : num) : 0 + n = n := by cases n; refl theorem add_one : ∀ n : num, n + 1 = succ n | 0 := rfl | (pos p) := by cases p; refl theorem add_succ : ∀ (m n : num), m + succ n = succ (m + n) | 0 n := by simp [zero_add] | (pos p) 0 := show pos (p + 1) = succ (pos p + 0), by rw [pos_num.add_one, add_zero]; refl | (pos p) (pos q) := congr_arg pos (pos_num.add_succ _ _) @[simp, norm_cast] theorem add_of_nat (m) : ∀ n, ((m + n : ℕ) : num) = m + n | 0 := (add_zero _).symm | (n+1) := show ((m + n : ℕ) + 1 : num) = m + (↑ n + 1), by rw [add_one, add_one, add_succ, add_of_nat] theorem bit0_of_bit0 : ∀ n : num, bit0 n = n.bit0 | 0 := rfl | (pos p) := congr_arg pos p.bit0_of_bit0 theorem bit1_of_bit1 : ∀ n : num, bit1 n = n.bit1 | 0 := rfl | (pos p) := congr_arg pos p.bit1_of_bit1 @[simp, norm_cast] theorem cast_zero [has_zero α] [has_one α] [has_add α] : ((0 : num) : α) = 0 := rfl @[simp] theorem cast_zero' [has_zero α] [has_one α] [has_add α] : (num.zero : α) = 0 := rfl @[simp, norm_cast] theorem cast_one [has_zero α] [has_one α] [has_add α] : ((1 : num) : α) = 1 := rfl @[simp] theorem cast_pos [has_zero α] [has_one α] [has_add α] (n : pos_num) : (num.pos n : α) = n := rfl theorem succ'_to_nat : ∀ n, (succ' n : ℕ) = n + 1 | 0 := (_root_.zero_add _).symm | (pos p) := pos_num.succ_to_nat _ theorem succ_to_nat (n) : (succ n : ℕ) = n + 1 := succ'_to_nat n @[simp, norm_cast] theorem cast_to_nat [add_monoid α] [has_one α] : ∀ n : num, ((n : ℕ) : α) = n | 0 := nat.cast_zero | (pos p) := p.cast_to_nat @[simp, norm_cast] theorem to_nat_to_int (n : num) : ((n : ℕ) : ℤ) = n := by rw [← int.nat_cast_eq_coe_nat, cast_to_nat] @[simp, norm_cast] theorem cast_to_int [add_group α] [has_one α] (n : num) : ((n : ℤ) : α) = n := by rw [← to_nat_to_int, int.cast_coe_nat, cast_to_nat] @[norm_cast] theorem to_of_nat : Π (n : ℕ), ((n : num) : ℕ) = n | 0 := rfl | (n+1) := by rw [nat.cast_add_one, add_one, succ_to_nat, to_of_nat] @[simp, norm_cast] theorem of_nat_cast [add_monoid α] [has_one α] (n : ℕ) : ((n : num) : α) = n := by rw [← cast_to_nat, to_of_nat] @[norm_cast] theorem of_nat_inj {m n : ℕ} : (m : num) = n ↔ m = n := ⟨λ h, function.left_inverse.injective to_of_nat h, congr_arg _⟩ @[norm_cast] theorem add_to_nat : ∀ m n, ((m + n : num) : ℕ) = m + n | 0 0 := rfl | 0 (pos q) := (_root_.zero_add _).symm | (pos p) 0 := rfl | (pos p) (pos q) := pos_num.add_to_nat _ _ @[norm_cast] theorem mul_to_nat : ∀ m n, ((m * n : num) : ℕ) = m * n | 0 0 := rfl | 0 (pos q) := (zero_mul _).symm | (pos p) 0 := rfl | (pos p) (pos q) := pos_num.mul_to_nat _ _ theorem cmp_to_nat : ∀ (m n), (ordering.cases_on (cmp m n) ((m:ℕ) < n) (m = n) ((m:ℕ) > n) : Prop) | 0 0 := rfl | 0 (pos b) := to_nat_pos _ | (pos a) 0 := to_nat_pos _ | (pos a) (pos b) := by { have := pos_num.cmp_to_nat a b; revert this; dsimp [cmp]; cases pos_num.cmp a b, exacts [id, congr_arg pos, id] } @[norm_cast] theorem lt_to_nat {m n : num} : (m:ℕ) < n ↔ m < n := show (m:ℕ) < n ↔ cmp m n = ordering.lt, from match cmp m n, cmp_to_nat m n with | ordering.lt, h := by simp at h; simp [h] | ordering.eq, h := by simp at h; simp [h, lt_irrefl]; exact dec_trivial | ordering.gt, h := by simp [not_lt_of_gt h]; exact dec_trivial end @[norm_cast] theorem le_to_nat {m n : num} : (m:ℕ) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr lt_to_nat end num namespace pos_num @[simp] theorem of_to_nat : Π (n : pos_num), ((n : ℕ) : num) = num.pos n | 1 := rfl | (bit0 p) := show ↑(p + p : ℕ) = num.pos p.bit0, by rw [num.add_of_nat, of_to_nat]; exact congr_arg num.pos p.bit0_of_bit0 | (bit1 p) := show ((p + p : ℕ) : num) + 1 = num.pos p.bit1, by rw [num.add_of_nat, of_to_nat]; exact congr_arg num.pos p.bit1_of_bit1 end pos_num namespace num @[simp, norm_cast] theorem of_to_nat : Π (n : num), ((n : ℕ) : num) = n | 0 := rfl | (pos p) := p.of_to_nat @[norm_cast] theorem to_nat_inj {m n : num} : (m : ℕ) = n ↔ m = n := ⟨λ h, function.left_inverse.injective of_to_nat h, congr_arg _⟩ meta def transfer_rw : tactic unit := `[repeat {rw ← to_nat_inj <|> rw ← lt_to_nat <|> rw ← le_to_nat}, repeat {rw add_to_nat <|> rw mul_to_nat <|> rw cast_one <|> rw cast_zero}] meta def transfer : tactic unit := `[intros, transfer_rw, try {simp}] instance : comm_semiring num := by refine { add := (+), zero := 0, zero_add := zero_add, add_zero := add_zero, mul := (*), one := 1, .. }; try {transfer}; simp [mul_add, mul_left_comm, mul_comm, add_comm] instance : ordered_cancel_add_comm_monoid num := { add_left_cancel := by {intros a b c, transfer_rw, apply add_left_cancel}, add_right_cancel := by {intros a b c, transfer_rw, apply add_right_cancel}, lt := (<), lt_iff_le_not_le := by {intros a b, transfer_rw, apply lt_iff_le_not_le}, le := (≤), le_refl := by transfer, le_trans := by {intros a b c, transfer_rw, apply le_trans}, le_antisymm := by {intros a b, transfer_rw, apply le_antisymm}, add_le_add_left := by {intros a b h c, revert h, transfer_rw, exact λ h, add_le_add_left h c}, le_of_add_le_add_left := by {intros a b c, transfer_rw, apply le_of_add_le_add_left}, ..num.comm_semiring } instance : decidable_linear_ordered_semiring num := { le_total := by {intros a b, transfer_rw, apply le_total}, zero_lt_one := dec_trivial, mul_lt_mul_of_pos_left := by {intros a b c, transfer_rw, apply mul_lt_mul_of_pos_left}, mul_lt_mul_of_pos_right := by {intros a b c, transfer_rw, apply mul_lt_mul_of_pos_right}, decidable_lt := num.decidable_lt, decidable_le := num.decidable_le, decidable_eq := num.decidable_eq, ..num.comm_semiring, ..num.ordered_cancel_add_comm_monoid } @[norm_cast] theorem dvd_to_nat (m n : num) : (m : ℕ) ∣ n ↔ m ∣ n := ⟨λ ⟨k, e⟩, ⟨k, by rw [← of_to_nat n, e]; simp⟩, λ ⟨k, e⟩, ⟨k, by simp [e, mul_to_nat]⟩⟩ end num namespace pos_num variables {α : Type*} open num @[norm_cast] theorem to_nat_inj {m n : pos_num} : (m : ℕ) = n ↔ m = n := ⟨λ h, num.pos.inj $ by rw [← pos_num.of_to_nat, ← pos_num.of_to_nat, h], congr_arg _⟩ theorem pred'_to_nat : ∀ n, (pred' n : ℕ) = nat.pred n | 1 := rfl | (bit0 n) := have nat.succ ↑(pred' n) = ↑n, by rw [pred'_to_nat n, nat.succ_pred_eq_of_pos (to_nat_pos n)], match pred' n, this : ∀ k : num, nat.succ ↑k = ↑n → ↑(num.cases_on k 1 bit1 : pos_num) = nat.pred (_root_.bit0 n) with | 0, (h : ((1:num):ℕ) = n) := by rw ← to_nat_inj.1 h; refl | num.pos p, (h : nat.succ ↑p = n) := by rw ← h; exact (nat.succ_add p p).symm end | (bit1 n) := rfl @[simp] theorem pred'_succ' (n) : pred' (succ' n) = n := num.to_nat_inj.1 $ by rw [pred'_to_nat, succ'_to_nat, nat.add_one, nat.pred_succ] @[simp] theorem succ'_pred' (n) : succ' (pred' n) = n := to_nat_inj.1 $ by rw [succ'_to_nat, pred'_to_nat, nat.add_one, nat.succ_pred_eq_of_pos (to_nat_pos _)] theorem size_to_nat : ∀ n, (size n : ℕ) = nat.size n | 1 := nat.size_one.symm | (bit0 n) := by rw [size, succ_to_nat, size_to_nat, cast_bit0, nat.size_bit0 $ ne_of_gt $ to_nat_pos n] | (bit1 n) := by rw [size, succ_to_nat, size_to_nat, cast_bit1, nat.size_bit1] theorem size_eq_nat_size : ∀ n, (size n : ℕ) = nat_size n | 1 := rfl | (bit0 n) := by rw [size, succ_to_nat, nat_size, size_eq_nat_size] | (bit1 n) := by rw [size, succ_to_nat, nat_size, size_eq_nat_size] theorem nat_size_to_nat (n) : nat_size n = nat.size n := by rw [← size_eq_nat_size, size_to_nat] theorem nat_size_pos (n) : 0 < nat_size n := by cases n; apply nat.succ_pos meta def transfer_rw : tactic unit := `[repeat {rw ← to_nat_inj <|> rw ← lt_to_nat <|> rw ← le_to_nat}, repeat {rw add_to_nat <|> rw mul_to_nat <|> rw cast_one <|> rw cast_zero}] meta def transfer : tactic unit := `[intros, transfer_rw, try {simp [add_comm, add_left_comm, mul_comm, mul_left_comm]}] instance : add_comm_semigroup pos_num := by refine {add := (+), ..}; transfer instance : comm_monoid pos_num := by refine {mul := (*), one := 1, ..}; transfer instance : distrib pos_num := by refine {add := (+), mul := (*), ..}; {transfer, simp [mul_add, mul_comm]} instance : decidable_linear_order pos_num := { lt := (<), lt_iff_le_not_le := by {intros a b, transfer_rw, apply lt_iff_le_not_le}, le := (≤), le_refl := by transfer, le_trans := by {intros a b c, transfer_rw, apply le_trans}, le_antisymm := by {intros a b, transfer_rw, apply le_antisymm}, le_total := by {intros a b, transfer_rw, apply le_total}, decidable_lt := by apply_instance, decidable_le := by apply_instance, decidable_eq := by apply_instance } @[simp] theorem cast_to_num (n : pos_num) : ↑n = num.pos n := by rw [← cast_to_nat, ← of_to_nat n] @[simp, norm_cast] theorem bit_to_nat (b n) : (bit b n : ℕ) = nat.bit b n := by cases b; refl @[simp, norm_cast] theorem cast_add [add_monoid α] [has_one α] (m n) : ((m + n : pos_num) : α) = m + n := by rw [← cast_to_nat, add_to_nat, nat.cast_add, cast_to_nat, cast_to_nat] @[simp, norm_cast, priority 500] theorem cast_succ [add_monoid α] [has_one α] (n : pos_num) : (succ n : α) = n + 1 := by rw [← add_one, cast_add, cast_one] @[simp, norm_cast] theorem cast_inj [add_monoid α] [has_one α] [char_zero α] {m n : pos_num} : (m:α) = n ↔ m = n := by rw [← cast_to_nat m, ← cast_to_nat n, nat.cast_inj, to_nat_inj] @[simp] theorem one_le_cast [linear_ordered_semiring α] (n : pos_num) : (1 : α) ≤ n := by rw [← cast_to_nat, ← nat.cast_one, nat.cast_le]; apply to_nat_pos @[simp] theorem cast_pos [linear_ordered_semiring α] (n : pos_num) : 0 < (n : α) := lt_of_lt_of_le zero_lt_one (one_le_cast n) @[simp, norm_cast] theorem cast_mul [semiring α] (m n) : ((m * n : pos_num) : α) = m * n := by rw [← cast_to_nat, mul_to_nat, nat.cast_mul, cast_to_nat, cast_to_nat] @[simp] theorem cmp_eq (m n) : cmp m n = ordering.eq ↔ m = n := begin have := cmp_to_nat m n, cases cmp m n; simp at this ⊢; try {exact this}; { simp [show m ≠ n, from λ e, by rw e at this; exact lt_irrefl _ this] } end @[simp, norm_cast] theorem cast_lt [linear_ordered_semiring α] {m n : pos_num} : (m:α) < n ↔ m < n := by rw [← cast_to_nat m, ← cast_to_nat n, nat.cast_lt, lt_to_nat] @[simp, norm_cast] theorem cast_le [linear_ordered_semiring α] {m n : pos_num} : (m:α) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr cast_lt end pos_num namespace num variables {α : Type*} open pos_num theorem bit_to_nat (b n) : (bit b n : ℕ) = nat.bit b n := by cases b; cases n; refl theorem cast_succ' [add_monoid α] [has_one α] (n) : (succ' n : α) = n + 1 := by rw [← pos_num.cast_to_nat, succ'_to_nat, nat.cast_add_one, cast_to_nat] theorem cast_succ [add_monoid α] [has_one α] (n) : (succ n : α) = n + 1 := cast_succ' n @[simp, norm_cast] theorem cast_add [semiring α] (m n) : ((m + n : num) : α) = m + n := by rw [← cast_to_nat, add_to_nat, nat.cast_add, cast_to_nat, cast_to_nat] @[simp, norm_cast] theorem cast_bit0 [semiring α] (n : num) : (n.bit0 : α) = _root_.bit0 n := by rw [← bit0_of_bit0, _root_.bit0, cast_add]; refl @[simp, norm_cast] theorem cast_bit1 [semiring α] (n : num) : (n.bit1 : α) = _root_.bit1 n := by rw [← bit1_of_bit1, _root_.bit1, bit0_of_bit0, cast_add, cast_bit0]; refl @[simp, norm_cast] theorem cast_mul [semiring α] : ∀ m n, ((m * n : num) : α) = m * n | 0 0 := (zero_mul _).symm | 0 (pos q) := (zero_mul _).symm | (pos p) 0 := (mul_zero _).symm | (pos p) (pos q) := pos_num.cast_mul _ _ theorem size_to_nat : ∀ n, (size n : ℕ) = nat.size n | 0 := nat.size_zero.symm | (pos p) := p.size_to_nat theorem size_eq_nat_size : ∀ n, (size n : ℕ) = nat_size n | 0 := rfl | (pos p) := p.size_eq_nat_size theorem nat_size_to_nat (n) : nat_size n = nat.size n := by rw [← size_eq_nat_size, size_to_nat] @[simp] theorem of_nat'_eq : ∀ n, num.of_nat' n = n := nat.binary_rec rfl $ λ b n IH, begin rw of_nat' at IH ⊢, rw [nat.binary_rec_eq, IH], { cases b; simp [nat.bit, bit0_of_bit0, bit1_of_bit1] }, { refl } end theorem zneg_to_znum (n : num) : -n.to_znum = n.to_znum_neg := by cases n; refl theorem zneg_to_znum_neg (n : num) : -n.to_znum_neg = n.to_znum := by cases n; refl theorem to_znum_inj {m n : num} : m.to_znum = n.to_znum ↔ m = n := ⟨λ h, by cases m; cases n; cases h; refl, congr_arg _⟩ @[simp, norm_cast squash] theorem cast_to_znum [has_zero α] [has_one α] [has_add α] [has_neg α] : ∀ n : num, (n.to_znum : α) = n | 0 := rfl | (num.pos p) := rfl @[simp] theorem cast_to_znum_neg [add_group α] [has_one α] : ∀ n : num, (n.to_znum_neg : α) = -n | 0 := neg_zero.symm | (num.pos p) := rfl @[simp] theorem add_to_znum (m n : num) : num.to_znum (m + n) = m.to_znum + n.to_znum := by cases m; cases n; refl end num namespace pos_num open num theorem pred_to_nat {n : pos_num} (h : n > 1) : (pred n : ℕ) = nat.pred n := begin unfold pred, have := pred'_to_nat n, cases e : pred' n, { have : (1:ℕ) ≤ nat.pred n := nat.pred_le_pred ((@cast_lt ℕ _ _ _).2 h), rw [← pred'_to_nat, e] at this, exact absurd this dec_trivial }, { rw [← pred'_to_nat, e], refl } end theorem sub'_one (a : pos_num) : sub' a 1 = (pred' a).to_znum := by cases a; refl theorem one_sub' (a : pos_num) : sub' 1 a = (pred' a).to_znum_neg := by cases a; refl theorem lt_iff_cmp {m n} : m < n ↔ cmp m n = ordering.lt := iff.rfl theorem le_iff_cmp {m n} : m ≤ n ↔ cmp m n ≠ ordering.gt := not_congr $ lt_iff_cmp.trans $ by rw ← cmp_swap; cases cmp m n; exact dec_trivial end pos_num namespace num variables {α : Type*} open pos_num theorem pred_to_nat : ∀ (n : num), (pred n : ℕ) = nat.pred n | 0 := rfl | (pos p) := by rw [pred, pos_num.pred'_to_nat]; refl theorem ppred_to_nat : ∀ (n : num), coe <$> ppred n = nat.ppred n | 0 := rfl | (pos p) := by rw [ppred, option.map_some, nat.ppred_eq_some.2]; rw [pos_num.pred'_to_nat, nat.succ_pred_eq_of_pos (pos_num.to_nat_pos _)]; refl theorem cmp_swap (m n) : (cmp m n).swap = cmp n m := by cases m; cases n; try {unfold cmp}; try {refl}; apply pos_num.cmp_swap theorem cmp_eq (m n) : cmp m n = ordering.eq ↔ m = n := begin have := cmp_to_nat m n, cases cmp m n; simp at this ⊢; try {exact this}; { simp [show m ≠ n, from λ e, by rw e at this; exact lt_irrefl _ this] } end @[simp, norm_cast] theorem cast_lt [linear_ordered_semiring α] {m n : num} : (m:α) < n ↔ m < n := by rw [← cast_to_nat m, ← cast_to_nat n, nat.cast_lt, lt_to_nat] @[simp, norm_cast] theorem cast_le [linear_ordered_semiring α] {m n : num} : (m:α) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr cast_lt @[simp, norm_cast] theorem cast_inj [linear_ordered_semiring α] {m n : num} : (m:α) = n ↔ m = n := by rw [← cast_to_nat m, ← cast_to_nat n, nat.cast_inj, to_nat_inj] theorem lt_iff_cmp {m n} : m < n ↔ cmp m n = ordering.lt := iff.rfl theorem le_iff_cmp {m n} : m ≤ n ↔ cmp m n ≠ ordering.gt := not_congr $ lt_iff_cmp.trans $ by rw ← cmp_swap; cases cmp m n; exact dec_trivial theorem bitwise_to_nat {f : num → num → num} {g : bool → bool → bool} (p : pos_num → pos_num → num) (gff : g ff ff = ff) (f00 : f 0 0 = 0) (f0n : ∀ n, f 0 (pos n) = cond (g ff tt) (pos n) 0) (fn0 : ∀ n, f (pos n) 0 = cond (g tt ff) (pos n) 0) (fnn : ∀ m n, f (pos m) (pos n) = p m n) (p11 : p 1 1 = cond (g tt tt) 1 0) (p1b : ∀ b n, p 1 (pos_num.bit b n) = bit (g tt b) (cond (g ff tt) (pos n) 0)) (pb1 : ∀ a m, p (pos_num.bit a m) 1 = bit (g a tt) (cond (g tt ff) (pos m) 0)) (pbb : ∀ a b m n, p (pos_num.bit a m) (pos_num.bit b n) = bit (g a b) (p m n)) : ∀ m n : num, (f m n : ℕ) = nat.bitwise g m n := begin intros, cases m with m; cases n with n; try { change zero with 0 }; try { change ((0:num):ℕ) with 0 }, { rw [f00, nat.bitwise_zero]; refl }, { unfold nat.bitwise, rw [f0n, nat.binary_rec_zero], cases g ff tt; refl }, { unfold nat.bitwise, generalize h : (pos m : ℕ) = m', revert h, apply nat.bit_cases_on m' _, intros b m' h, rw [fn0, nat.binary_rec_eq, nat.binary_rec_zero, ←h], cases g tt ff; refl, apply nat.bitwise_bit_aux gff }, { rw fnn, have : ∀b (n : pos_num), (cond b ↑n 0 : ℕ) = ↑(cond b (pos n) 0 : num) := by intros; cases b; refl, induction m with m IH m IH generalizing n; cases n with n n, any_goals { change one with 1 }, any_goals { change pos 1 with 1 }, any_goals { change pos_num.bit0 with pos_num.bit ff }, any_goals { change pos_num.bit1 with pos_num.bit tt }, any_goals { change ((1:num):ℕ) with nat.bit tt 0 }, all_goals { repeat { rw show ∀ b n, (pos (pos_num.bit b n) : ℕ) = nat.bit b ↑n, by intros; cases b; refl }, rw nat.bitwise_bit }, any_goals { assumption }, any_goals { rw [nat.bitwise_zero, p11], cases g tt tt; refl }, any_goals { rw [nat.bitwise_zero_left, this, ← bit_to_nat, p1b] }, any_goals { rw [nat.bitwise_zero_right _ gff, this, ← bit_to_nat, pb1] }, all_goals { rw [← show ∀ n, ↑(p m n) = nat.bitwise g ↑m ↑n, from IH], rw [← bit_to_nat, pbb] } } end @[simp, norm_cast] theorem lor_to_nat : ∀ m n, (lor m n : ℕ) = nat.lor m n := by apply bitwise_to_nat (λx y, pos (pos_num.lor x y)); intros; try {cases a}; try {cases b}; refl @[simp, norm_cast] theorem land_to_nat : ∀ m n, (land m n : ℕ) = nat.land m n := by apply bitwise_to_nat pos_num.land; intros; try {cases a}; try {cases b}; refl @[simp, norm_cast] theorem ldiff_to_nat : ∀ m n, (ldiff m n : ℕ) = nat.ldiff m n := by apply bitwise_to_nat pos_num.ldiff; intros; try {cases a}; try {cases b}; refl @[simp, norm_cast] theorem lxor_to_nat : ∀ m n, (lxor m n : ℕ) = nat.lxor m n := by apply bitwise_to_nat pos_num.lxor; intros; try {cases a}; try {cases b}; refl @[simp, norm_cast] theorem shiftl_to_nat (m n) : (shiftl m n : ℕ) = nat.shiftl m n := begin cases m; dunfold shiftl, {symmetry, apply nat.zero_shiftl}, simp, induction n with n IH, {refl}, simp [pos_num.shiftl, nat.shiftl_succ], rw ←IH end @[simp, norm_cast] theorem shiftr_to_nat (m n) : (shiftr m n : ℕ) = nat.shiftr m n := begin cases m with m; dunfold shiftr, {symmetry, apply nat.zero_shiftr}, induction n with n IH generalizing m, {cases m; refl}, cases m with m m; dunfold pos_num.shiftr, { rw [nat.shiftr_eq_div_pow], symmetry, apply nat.div_eq_of_lt, exact @nat.pow_lt_pow_of_lt_right 2 dec_trivial 0 (n+1) (nat.succ_pos _) }, { transitivity, apply IH, change nat.shiftr m n = nat.shiftr (bit1 m) (n+1), rw [add_comm n 1, nat.shiftr_add], apply congr_arg (λx, nat.shiftr x n), unfold nat.shiftr, change (bit1 ↑m : ℕ) with nat.bit tt m, rw nat.div2_bit }, { transitivity, apply IH, change nat.shiftr m n = nat.shiftr (bit0 m) (n + 1), rw [add_comm n 1, nat.shiftr_add], apply congr_arg (λx, nat.shiftr x n), unfold nat.shiftr, change (bit0 ↑m : ℕ) with nat.bit ff m, rw nat.div2_bit } end @[simp] theorem test_bit_to_nat (m n) : test_bit m n = nat.test_bit m n := begin cases m with m; unfold test_bit nat.test_bit, { change (zero : nat) with 0, rw nat.zero_shiftr, refl }, induction n with n IH generalizing m; cases m; dunfold pos_num.test_bit, {refl}, { exact (nat.bodd_bit _ _).symm }, { exact (nat.bodd_bit _ _).symm }, { change ff = nat.bodd (nat.shiftr 1 (n + 1)), rw [add_comm, nat.shiftr_add], change nat.shiftr 1 1 with 0, rw nat.zero_shiftr; refl }, { change pos_num.test_bit m n = nat.bodd (nat.shiftr (nat.bit tt m) (n + 1)), rw [add_comm, nat.shiftr_add], unfold nat.shiftr, rw nat.div2_bit, apply IH }, { change pos_num.test_bit m n = nat.bodd (nat.shiftr (nat.bit ff m) (n + 1)), rw [add_comm, nat.shiftr_add], unfold nat.shiftr, rw nat.div2_bit, apply IH }, end end num namespace znum variables {α : Type*} open pos_num @[simp, norm_cast] theorem cast_zero [has_zero α] [has_one α] [has_add α] [has_neg α] : ((0 : znum) : α) = 0 := rfl @[simp] theorem cast_zero' [has_zero α] [has_one α] [has_add α] [has_neg α] : (znum.zero : α) = 0 := rfl @[simp, norm_cast] theorem cast_one [has_zero α] [has_one α] [has_add α] [has_neg α] : ((1 : znum) : α) = 1 := rfl @[simp] theorem cast_pos [has_zero α] [has_one α] [has_add α] [has_neg α] (n : pos_num) : (pos n : α) = n := rfl @[simp] theorem cast_neg [has_zero α] [has_one α] [has_add α] [has_neg α] (n : pos_num) : (neg n : α) = -n := rfl @[simp, norm_cast] theorem cast_zneg [add_group α] [has_one α] : ∀ n, ((-n : znum) : α) = -n | 0 := neg_zero.symm | (pos p) := rfl | (neg p) := (neg_neg _).symm theorem neg_zero : (-0 : znum) = 0 := rfl theorem zneg_pos (n : pos_num) : -pos n = neg n := rfl theorem zneg_neg (n : pos_num) : -neg n = pos n := rfl theorem zneg_zneg (n : znum) : - -n = n := by cases n; refl theorem zneg_bit1 (n : znum) : -n.bit1 = (-n).bitm1 := by cases n; refl theorem zneg_bitm1 (n : znum) : -n.bitm1 = (-n).bit1 := by cases n; refl theorem zneg_succ (n : znum) : -n.succ = (-n).pred := by cases n; try {refl}; rw [succ, num.zneg_to_znum_neg]; refl theorem zneg_pred (n : znum) : -n.pred = (-n).succ := by rw [← zneg_zneg (succ (-n)), zneg_succ, zneg_zneg] @[simp, norm_cast] theorem neg_of_int : ∀ n, ((-n : ℤ) : znum) = -n | (n+1:ℕ) := rfl | 0 := rfl | -[1+n] := (zneg_zneg _).symm @[simp] theorem abs_to_nat : ∀ n, (abs n : ℕ) = int.nat_abs n | 0 := rfl | (pos p) := congr_arg int.nat_abs p.to_nat_to_int | (neg p) := show int.nat_abs ((p:ℕ):ℤ) = int.nat_abs (- p), by rw [p.to_nat_to_int, int.nat_abs_neg] @[simp] theorem abs_to_znum : ∀ n : num, abs n.to_znum = n | 0 := rfl | (num.pos p) := rfl @[simp, norm_cast] theorem cast_to_int [add_group α] [has_one α] : ∀ n : znum, ((n : ℤ) : α) = n | 0 := rfl | (pos p) := by rw [cast_pos, cast_pos, pos_num.cast_to_int] | (neg p) := by rw [cast_neg, cast_neg, int.cast_neg, pos_num.cast_to_int] theorem bit0_of_bit0 : ∀ n : znum, _root_.bit0 n = n.bit0 | 0 := rfl | (pos a) := congr_arg pos a.bit0_of_bit0 | (neg a) := congr_arg neg a.bit0_of_bit0 theorem bit1_of_bit1 : ∀ n : znum, _root_.bit1 n = n.bit1 | 0 := rfl | (pos a) := congr_arg pos a.bit1_of_bit1 | (neg a) := show pos_num.sub' 1 (_root_.bit0 a) = _, by rw [pos_num.one_sub', a.bit0_of_bit0]; refl @[simp, norm_cast] theorem cast_bit0 [add_group α] [has_one α] : ∀ n : znum, (n.bit0 : α) = bit0 n | 0 := (add_zero _).symm | (pos p) := by rw [znum.bit0, cast_pos, cast_pos]; refl | (neg p) := by rw [znum.bit0, cast_neg, cast_neg, pos_num.cast_bit0, _root_.bit0, _root_.bit0, neg_add_rev] @[simp, norm_cast] theorem cast_bit1 [add_group α] [has_one α] : ∀ n : znum, (n.bit1 : α) = bit1 n | 0 := by simp [znum.bit1, _root_.bit1, _root_.bit0] | (pos p) := by rw [znum.bit1, cast_pos, cast_pos]; refl | (neg p) := begin rw [znum.bit1, cast_neg, cast_neg], cases e : pred' p; have : p = _ := (succ'_pred' p).symm.trans (congr_arg num.succ' e), { change p=1 at this, subst p, simp [_root_.bit1, _root_.bit0] }, { rw [num.succ'] at this, subst p, have : (↑(-↑a:ℤ) : α) = -1 + ↑(-↑a + 1 : ℤ), {simp [add_comm]}, simpa [_root_.bit1, _root_.bit0, -add_comm] }, end @[simp] theorem cast_bitm1 [add_group α] [has_one α] (n : znum) : (n.bitm1 : α) = bit0 n - 1 := begin conv { to_lhs, rw ← zneg_zneg n }, rw [← zneg_bit1, cast_zneg, cast_bit1], have : ((-1 + n + n : ℤ) : α) = (n + n + -1 : ℤ), {simp [add_comm, add_left_comm]}, simpa [_root_.bit1, _root_.bit0, sub_eq_add_neg] end theorem add_zero (n : znum) : n + 0 = n := by cases n; refl theorem zero_add (n : znum) : 0 + n = n := by cases n; refl theorem add_one : ∀ n : znum, n + 1 = succ n | 0 := rfl | (pos p) := congr_arg pos p.add_one | (neg p) := by cases p; refl end znum namespace pos_num variables {α : Type*} theorem cast_to_znum : ∀ n : pos_num, (n : znum) = znum.pos n | 1 := rfl | (bit0 p) := (znum.bit0_of_bit0 p).trans $ congr_arg _ (cast_to_znum p) | (bit1 p) := (znum.bit1_of_bit1 p).trans $ congr_arg _ (cast_to_znum p) theorem cast_sub' [add_group α] [has_one α] : ∀ m n : pos_num, (sub' m n : α) = m - n | a 1 := by rw [sub'_one, num.cast_to_znum, ← num.cast_to_nat, pred'_to_nat, ← nat.sub_one]; simp [pos_num.cast_pos] | 1 b := by rw [one_sub', num.cast_to_znum_neg, ← neg_sub, neg_inj, ← num.cast_to_nat, pred'_to_nat, ← nat.sub_one]; simp [pos_num.cast_pos] | (bit0 a) (bit0 b) := begin rw [sub', znum.cast_bit0, cast_sub'], have : ((a + -b + (a + -b) : ℤ) : α) = a + a + (-b + -b), {simp [add_left_comm]}, simpa [_root_.bit0, sub_eq_add_neg] end | (bit0 a) (bit1 b) := begin rw [sub', znum.cast_bitm1, cast_sub'], have : ((-b + (a + (-b + -1)) : ℤ) : α) = (a + -1 + (-b + -b):ℤ), { simp [add_comm, add_left_comm] }, simpa [_root_.bit1, _root_.bit0, sub_eq_add_neg] end | (bit1 a) (bit0 b) := begin rw [sub', znum.cast_bit1, cast_sub'], have : ((-b + (a + (-b + 1)) : ℤ) : α) = (a + 1 + (-b + -b):ℤ), { simp [add_comm, add_left_comm] }, simpa [_root_.bit1, _root_.bit0, sub_eq_add_neg] end | (bit1 a) (bit1 b) := begin rw [sub', znum.cast_bit0, cast_sub'], have : ((-b + (a + -b) : ℤ) : α) = a + (-b + -b), {simp [add_left_comm]}, simpa [_root_.bit1, _root_.bit0, sub_eq_add_neg] end theorem to_nat_eq_succ_pred (n : pos_num) : (n:ℕ) = n.pred' + 1 := by rw [← num.succ'_to_nat, n.succ'_pred'] theorem to_int_eq_succ_pred (n : pos_num) : (n:ℤ) = (n.pred' : ℕ) + 1 := by rw [← n.to_nat_to_int, to_nat_eq_succ_pred]; refl end pos_num namespace num variables {α : Type*} @[simp] theorem cast_sub' [add_group α] [has_one α] : ∀ m n : num, (sub' m n : α) = m - n | 0 0 := (sub_zero _).symm | (pos a) 0 := (sub_zero _).symm | 0 (pos b) := (zero_sub _).symm | (pos a) (pos b) := pos_num.cast_sub' _ _ @[simp] theorem of_nat_to_znum : ∀ n : ℕ, to_znum n = n | 0 := rfl | (n+1) := by rw [nat.cast_add_one, nat.cast_add_one, znum.add_one, add_one, ← of_nat_to_znum]; cases (n:num); refl @[simp] theorem of_nat_to_znum_neg (n : ℕ) : to_znum_neg n = -n := by rw [← of_nat_to_znum, zneg_to_znum] theorem mem_of_znum' : ∀ {m : num} {n : znum}, m ∈ of_znum' n ↔ n = to_znum m | 0 0 := ⟨λ _, rfl, λ _, rfl⟩ | (pos m) 0 := ⟨λ h, by cases h, λ h, by cases h⟩ | m (znum.pos p) := option.some_inj.trans $ by cases m; split; intro h; try {cases h}; refl | m (znum.neg p) := ⟨λ h, by cases h, λ h, by cases m; cases h⟩ theorem of_znum'_to_nat : ∀ (n : znum), coe <$> of_znum' n = int.to_nat' n | 0 := rfl | (znum.pos p) := show _ = int.to_nat' p, by rw [← pos_num.to_nat_to_int p]; refl | (znum.neg p) := congr_arg (λ x, int.to_nat' (-x)) $ show ((p.pred' + 1 : ℕ) : ℤ) = p, by rw ← succ'_to_nat; simp @[simp] theorem of_znum_to_nat : ∀ (n : znum), (of_znum n : ℕ) = int.to_nat n | 0 := rfl | (znum.pos p) := show _ = int.to_nat p, by rw [← pos_num.to_nat_to_int p]; refl | (znum.neg p) := congr_arg (λ x, int.to_nat (-x)) $ show ((p.pred' + 1 : ℕ) : ℤ) = p, by rw ← succ'_to_nat; simp @[simp] theorem cast_of_znum [add_group α] [has_one α] (n : znum) : (of_znum n : α) = int.to_nat n := by rw [← cast_to_nat, of_znum_to_nat] @[simp, norm_cast] theorem sub_to_nat (m n) : ((m - n : num) : ℕ) = m - n := show (of_znum _ : ℕ) = _, by rw [of_znum_to_nat, cast_sub', ← to_nat_to_int, ← to_nat_to_int, int.to_nat_sub] end num namespace znum variables {α : Type*} @[simp, norm_cast] theorem cast_add [add_group α] [has_one α] : ∀ m n, ((m + n : znum) : α) = m + n | 0 a := by cases a; exact (_root_.zero_add _).symm | b 0 := by cases b; exact (_root_.add_zero _).symm | (pos a) (pos b) := pos_num.cast_add _ _ | (pos a) (neg b) := pos_num.cast_sub' _ _ | (neg a) (pos b) := (pos_num.cast_sub' _ _).trans $ show ↑b + -↑a = -↑a + ↑b, by rw [← pos_num.cast_to_int a, ← pos_num.cast_to_int b, ← int.cast_neg, ← int.cast_add (-a)]; simp [add_comm] | (neg a) (neg b) := show -(↑(a + b) : α) = -a + -b, by rw [ pos_num.cast_add, neg_eq_iff_neg_eq, neg_add_rev, neg_neg, neg_neg, ← pos_num.cast_to_int a, ← pos_num.cast_to_int b, ← int.cast_add]; simp [add_comm] @[simp] theorem cast_succ [add_group α] [has_one α] (n) : ((succ n : znum) : α) = n + 1 := by rw [← add_one, cast_add, cast_one] @[simp, norm_cast] theorem mul_to_int : ∀ m n, ((m * n : znum) : ℤ) = m * n | 0 a := by cases a; exact (_root_.zero_mul _).symm | b 0 := by cases b; exact (_root_.mul_zero _).symm | (pos a) (pos b) := pos_num.cast_mul a b | (pos a) (neg b) := show -↑(a * b) = ↑a * -↑b, by rw [pos_num.cast_mul, neg_mul_eq_mul_neg] | (neg a) (pos b) := show -↑(a * b) = -↑a * ↑b, by rw [pos_num.cast_mul, neg_mul_eq_neg_mul] | (neg a) (neg b) := show ↑(a * b) = -↑a * -↑b, by rw [pos_num.cast_mul, neg_mul_neg] theorem cast_mul [ring α] (m n) : ((m * n : znum) : α) = m * n := by rw [← cast_to_int, mul_to_int, int.cast_mul, cast_to_int, cast_to_int] @[simp, norm_cast] theorem of_to_int : Π (n : znum), ((n : ℤ) : znum) = n | 0 := rfl | (pos a) := by rw [cast_pos, ← pos_num.cast_to_nat, int.cast_coe_nat', ← num.of_nat_to_znum, pos_num.of_to_nat]; refl | (neg a) := by rw [cast_neg, neg_of_int, ← pos_num.cast_to_nat, int.cast_coe_nat', ← num.of_nat_to_znum_neg, pos_num.of_to_nat]; refl @[norm_cast] theorem to_of_int : Π (n : ℤ), ((n : znum) : ℤ) = n | (n : ℕ) := by rw [int.cast_coe_nat, ← num.of_nat_to_znum, num.cast_to_znum, ← num.cast_to_nat, int.nat_cast_eq_coe_nat, num.to_of_nat] | -[1+ n] := by rw [int.cast_neg_succ_of_nat, cast_zneg, add_one, cast_succ, int.neg_succ_of_nat_eq, ← num.of_nat_to_znum, num.cast_to_znum, ← num.cast_to_nat, int.nat_cast_eq_coe_nat, num.to_of_nat] theorem to_int_inj {m n : znum} : (m : ℤ) = n ↔ m = n := ⟨λ h, function.left_inverse.injective of_to_int h, congr_arg _⟩ @[simp, norm_cast] theorem of_int_cast [add_group α] [has_one α] (n : ℤ) : ((n : znum) : α) = n := by rw [← cast_to_int, to_of_int] @[simp, norm_cast] theorem of_nat_cast [add_group α] [has_one α] (n : ℕ) : ((n : znum) : α) = n := of_int_cast n @[simp] theorem of_int'_eq : ∀ n, znum.of_int' n = n | (n : ℕ) := to_int_inj.1 $ by simp [znum.of_int'] | -[1+ n] := to_int_inj.1 $ by simp [znum.of_int'] theorem cmp_to_int : ∀ (m n), (ordering.cases_on (cmp m n) ((m:ℤ) < n) (m = n) ((m:ℤ) > n) : Prop) | 0 0 := rfl | (pos a) (pos b) := begin have := pos_num.cmp_to_nat a b; revert this; dsimp [cmp]; cases pos_num.cmp a b; dsimp; [simp, exact congr_arg pos, simp [gt]] end | (neg a) (neg b) := begin have := pos_num.cmp_to_nat b a; revert this; dsimp [cmp]; cases pos_num.cmp b a; dsimp; [simp, simp {contextual := tt}, simp [gt]] end | (pos a) 0 := pos_num.cast_pos _ | (pos a) (neg b) := lt_trans (neg_lt_zero.2 $ pos_num.cast_pos _) (pos_num.cast_pos _) | 0 (neg b) := neg_lt_zero.2 $ pos_num.cast_pos _ | (neg a) 0 := neg_lt_zero.2 $ pos_num.cast_pos _ | (neg a) (pos b) := lt_trans (neg_lt_zero.2 $ pos_num.cast_pos _) (pos_num.cast_pos _) | 0 (pos b) := pos_num.cast_pos _ @[norm_cast] theorem lt_to_int {m n : znum} : (m:ℤ) < n ↔ m < n := show (m:ℤ) < n ↔ cmp m n = ordering.lt, from match cmp m n, cmp_to_int m n with | ordering.lt, h := by simp at h; simp [h] | ordering.eq, h := by simp at h; simp [h, lt_irrefl]; exact dec_trivial | ordering.gt, h := by simp [not_lt_of_gt h]; exact dec_trivial end theorem le_to_int {m n : znum} : (m:ℤ) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr lt_to_int @[simp, norm_cast] theorem cast_lt [linear_ordered_ring α] {m n : znum} : (m:α) < n ↔ m < n := by rw [← cast_to_int m, ← cast_to_int n, int.cast_lt, lt_to_int] @[simp, norm_cast] theorem cast_le [linear_ordered_ring α] {m n : znum} : (m:α) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr cast_lt @[simp, norm_cast] theorem cast_inj [linear_ordered_ring α] {m n : znum} : (m:α) = n ↔ m = n := by rw [← cast_to_int m, ← cast_to_int n, int.cast_inj, to_int_inj] meta def transfer_rw : tactic unit := `[repeat {rw ← to_int_inj <|> rw ← lt_to_int <|> rw ← le_to_int}, repeat {rw cast_add <|> rw mul_to_int <|> rw cast_one <|> rw cast_zero}] meta def transfer : tactic unit := `[intros, transfer_rw, try {simp [add_comm, add_left_comm, mul_comm, mul_left_comm]}] instance : decidable_linear_order znum := { lt := (<), lt_iff_le_not_le := by {intros a b, transfer_rw, apply lt_iff_le_not_le}, le := (≤), le_refl := by transfer, le_trans := by {intros a b c, transfer_rw, apply le_trans}, le_antisymm := by {intros a b, transfer_rw, apply le_antisymm}, le_total := by {intros a b, transfer_rw, apply le_total}, decidable_eq := znum.decidable_eq, decidable_le := znum.decidable_le, decidable_lt := znum.decidable_lt } instance : add_comm_group znum := { add := (+), add_assoc := by transfer, zero := 0, zero_add := zero_add, add_zero := add_zero, add_comm := by transfer, neg := has_neg.neg, add_left_neg := by transfer } instance : decidable_linear_ordered_comm_ring znum := { mul := (*), mul_assoc := by transfer, one := 1, one_mul := by transfer, mul_one := by transfer, left_distrib := by {transfer, simp [mul_add]}, right_distrib := by {transfer, simp [mul_add, mul_comm]}, mul_comm := by transfer, exists_pair_ne := ⟨0, 1, dec_trivial⟩, add_le_add_left := by {intros a b h c, revert h, transfer_rw, exact λ h, add_le_add_left h c}, mul_pos := λ a b, show 0 < a → 0 < b → 0 < a * b, by {transfer_rw, apply mul_pos}, zero_lt_one := dec_trivial, ..znum.decidable_linear_order, ..znum.add_comm_group } @[simp, norm_cast] theorem dvd_to_int (m n : znum) : (m : ℤ) ∣ n ↔ m ∣ n := ⟨λ ⟨k, e⟩, ⟨k, by rw [← of_to_int n, e]; simp⟩, λ ⟨k, e⟩, ⟨k, by simp [e]⟩⟩ end znum namespace pos_num theorem divmod_to_nat_aux {n d : pos_num} {q r : num} (h₁ : (r:ℕ) + d * _root_.bit0 q = n) (h₂ : (r:ℕ) < 2 * d) : ((divmod_aux d q r).2 + d * (divmod_aux d q r).1 : ℕ) = ↑n ∧ ((divmod_aux d q r).2 : ℕ) < d := begin unfold divmod_aux, have : ∀ {r₂}, num.of_znum' (num.sub' r (num.pos d)) = some r₂ ↔ (r : ℕ) = r₂ + d, { intro r₂, apply num.mem_of_znum'.trans, rw [← znum.to_int_inj, num.cast_to_znum, num.cast_sub', sub_eq_iff_eq_add, ← int.coe_nat_inj'], simp }, cases e : num.of_znum' (num.sub' r (num.pos d)) with r₂; simp [divmod_aux], { refine ⟨h₁, lt_of_not_ge (λ h, _)⟩, cases nat.le.dest h with r₂ e', rw [← num.to_of_nat r₂, add_comm] at e', cases e.symm.trans (this.2 e'.symm) }, { have := this.1 e, split, { rwa [_root_.bit1, add_comm _ 1, mul_add, mul_one, ← add_assoc, ← this] }, { rwa [this, two_mul, add_lt_add_iff_right] at h₂ } } end theorem divmod_to_nat (d n : pos_num) : (n / d : ℕ) = (divmod d n).1 ∧ (n % d : ℕ) = (divmod d n).2 := begin rw nat.div_mod_unique (pos_num.cast_pos _), induction n with n IH n IH, { exact divmod_to_nat_aux (by simp; refl) (nat.mul_le_mul_left 2 (pos_num.cast_pos d : (0 : ℕ) < d)) }, { unfold divmod, cases divmod d n with q r, simp only [divmod] at IH ⊢, apply divmod_to_nat_aux; simp, { rw [_root_.bit1, _root_.bit1, add_right_comm, bit0_eq_two_mul ↑n, ← IH.1, mul_add, ← bit0_eq_two_mul, mul_left_comm, ← bit0_eq_two_mul] }, { rw ← bit0_eq_two_mul, exact nat.bit1_lt_bit0 IH.2 } }, { unfold divmod, cases divmod d n with q r, simp only [divmod] at IH ⊢, apply divmod_to_nat_aux; simp, { rw [bit0_eq_two_mul ↑n, ← IH.1, mul_add, ← bit0_eq_two_mul, mul_left_comm, ← bit0_eq_two_mul] }, { rw ← bit0_eq_two_mul, exact nat.bit0_lt IH.2 } } end @[simp] theorem div'_to_nat (n d) : (div' n d : ℕ) = n / d := (divmod_to_nat _ _).1.symm @[simp] theorem mod'_to_nat (n d) : (mod' n d : ℕ) = n % d := (divmod_to_nat _ _).2.symm end pos_num namespace num @[simp, norm_cast] theorem div_to_nat : ∀ n d, ((n / d : num) : ℕ) = n / d | 0 0 := rfl | 0 (pos d) := (nat.zero_div _).symm | (pos n) 0 := (nat.div_zero _).symm | (pos n) (pos d) := pos_num.div'_to_nat _ _ @[simp, norm_cast] theorem mod_to_nat : ∀ n d, ((n % d : num) : ℕ) = n % d | 0 0 := rfl | 0 (pos d) := (nat.zero_mod _).symm | (pos n) 0 := (nat.mod_zero _).symm | (pos n) (pos d) := pos_num.mod'_to_nat _ _ theorem gcd_to_nat_aux : ∀ {n} {a b : num}, a ≤ b → (a * b).nat_size ≤ n → (gcd_aux n a b : ℕ) = nat.gcd a b | 0 0 b ab h := (nat.gcd_zero_left _).symm | 0 (pos a) 0 ab h := (not_lt_of_ge ab).elim rfl | 0 (pos a) (pos b) ab h := (not_lt_of_le h).elim $ pos_num.nat_size_pos _ | (nat.succ n) 0 b ab h := (nat.gcd_zero_left _).symm | (nat.succ n) (pos a) b ab h := begin simp [gcd_aux], rw [nat.gcd_rec, gcd_to_nat_aux, mod_to_nat], {refl}, { rw [← le_to_nat, mod_to_nat], exact le_of_lt (nat.mod_lt _ (pos_num.cast_pos _)) }, rw [nat_size_to_nat, mul_to_nat, nat.size_le] at h ⊢, rw [mod_to_nat, mul_comm], rw [nat.pow_succ, ← nat.mod_add_div b (pos a)] at h, refine lt_of_mul_lt_mul_right (lt_of_le_of_lt _ h) (nat.zero_le 2), rw [mul_two, mul_add], refine add_le_add_left (nat.mul_le_mul_left _ (le_trans (le_of_lt (nat.mod_lt _ (pos_num.cast_pos _))) _)) _, suffices : 1 ≤ _, simpa using nat.mul_le_mul_left (pos a) this, rw [nat.le_div_iff_mul_le _ _ a.cast_pos, one_mul], exact le_to_nat.2 ab end @[simp] theorem gcd_to_nat : ∀ a b, (gcd a b : ℕ) = nat.gcd a b := have ∀ a b : num, (a * b).nat_size ≤ a.nat_size + b.nat_size, begin intros, simp [nat_size_to_nat], rw [nat.size_le, nat.pow_add], exact mul_lt_mul'' (nat.lt_size_self _) (nat.lt_size_self _) (nat.zero_le _) (nat.zero_le _) end, begin intros, unfold gcd, split_ifs, { exact gcd_to_nat_aux h (this _ _) }, { rw nat.gcd_comm, exact gcd_to_nat_aux (le_of_not_le h) (this _ _) } end theorem dvd_iff_mod_eq_zero {m n : num} : m ∣ n ↔ n % m = 0 := by rw [← dvd_to_nat, nat.dvd_iff_mod_eq_zero, ← to_nat_inj, mod_to_nat]; refl instance : decidable_rel ((∣) : num → num → Prop) | a b := decidable_of_iff' _ dvd_iff_mod_eq_zero end num namespace znum @[simp, norm_cast] theorem div_to_int : ∀ n d, ((n / d : znum) : ℤ) = n / d | 0 0 := rfl | 0 (pos d) := (int.zero_div _).symm | 0 (neg d) := (int.zero_div _).symm | (pos n) 0 := (int.div_zero _).symm | (neg n) 0 := (int.div_zero _).symm | (pos n) (pos d) := (num.cast_to_znum _).trans $ by rw ← num.to_nat_to_int; simp | (pos n) (neg d) := (num.cast_to_znum_neg _).trans $ by rw ← num.to_nat_to_int; simp | (neg n) (pos d) := show - _ = (-_/↑d), begin rw [n.to_int_eq_succ_pred, d.to_int_eq_succ_pred, ← pos_num.to_nat_to_int, num.succ'_to_nat, num.div_to_nat], change -[1+ n.pred' / ↑d] = -[1+ n.pred' / (d.pred' + 1)], rw d.to_nat_eq_succ_pred end | (neg n) (neg d) := show ↑(pos_num.pred' n / num.pos d).succ' = (-_ / -↑d), begin rw [n.to_int_eq_succ_pred, d.to_int_eq_succ_pred, ← pos_num.to_nat_to_int, num.succ'_to_nat, num.div_to_nat], change (nat.succ (_/d) : ℤ) = nat.succ (n.pred'/(d.pred' + 1)), rw d.to_nat_eq_succ_pred end @[simp, norm_cast] theorem mod_to_int : ∀ n d, ((n % d : znum) : ℤ) = n % d | 0 d := (int.zero_mod _).symm | (pos n) d := (num.cast_to_znum _).trans $ by rw [← num.to_nat_to_int, cast_pos, num.mod_to_nat, ← pos_num.to_nat_to_int, abs_to_nat]; refl | (neg n) d := (num.cast_sub' _ _).trans $ by rw [← num.to_nat_to_int, cast_neg, ← num.to_nat_to_int, num.succ_to_nat, num.mod_to_nat, abs_to_nat, ← int.sub_nat_nat_eq_coe, n.to_int_eq_succ_pred]; refl @[simp] theorem gcd_to_nat (a b) : (gcd a b : ℕ) = int.gcd a b := (num.gcd_to_nat _ _).trans $ by simpa theorem dvd_iff_mod_eq_zero {m n : znum} : m ∣ n ↔ n % m = 0 := by rw [← dvd_to_int, int.dvd_iff_mod_eq_zero, ← to_int_inj, mod_to_int]; refl instance : decidable_rel ((∣) : znum → znum → Prop) | a b := decidable_of_iff' _ dvd_iff_mod_eq_zero end znum namespace int def of_snum : snum → ℤ := snum.rec' (λ a, cond a (-1) 0) (λa p IH, cond a (bit1 IH) (bit0 IH)) instance snum_coe : has_coe snum ℤ := ⟨of_snum⟩ end int instance : has_lt snum := ⟨λa b, (a : ℤ) < b⟩ instance : has_le snum := ⟨λa b, (a : ℤ) ≤ b⟩
64c5629bfbce84a19de5ae2e5806e6ff6f910367
efa51dd2edbbbbd6c34bd0ce436415eb405832e7
/20161026_ICTAC_Tutorial/ex50.lean
0c6fdadc58fb11463f4e75cf950182e13d055649
[ "Apache-2.0" ]
permissive
leanprover/presentations
dd031a05bcb12c8855676c77e52ed84246bd889a
3ce2d132d299409f1de269fa8e95afa1333d644e
refs/heads/master
1,688,703,388,796
1,686,838,383,000
1,687,465,742,000
29,750,158
12
9
Apache-2.0
1,540,211,670,000
1,422,042,683,000
Lean
UTF-8
Lean
false
false
436
lean
/- And ~ Product/Pair -/ example (p q : Prop) : p ∧ q → q ∧ p := assume ⟨hp, hq⟩, ⟨hq, hp⟩ example (A B : Type) : A × B → B × A := assume ⟨a, b⟩, ⟨b, a⟩ /- Or ~ Sum/Union Type -/ example (p q : Prop) (h : p ∨ q) : q ∨ p := match h with | or.inl h := or.inr h | or.inr h := or.inl h end example (A B : Type) (s : sum A B) : sum B A := match s with | sum.inl h := sum.inr h | sum.inr h := sum.inl h end
43c4ebb2b4099f7b620d118018b9678963a13e09
bae21755a4a03bbe0a5c22e258db8633407711ad
/library/init/meta/tactic.lean
2fa5261f2ff71d831968e05d9933a92a7c588387
[ "Apache-2.0" ]
permissive
nor-code/lean
f437357a8f85db0f06f186fa50fcb1bc75f6b122
aa306af3d7c47de3c7937c98d3aa919eb8da6f34
refs/heads/master
1,662,613,329,886
1,586,696,014,000
1,586,696,014,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
62,654
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.function init.data.option.basic init.util import init.category.combinators init.category.monad init.category.alternative init.category.monad_fail import init.data.nat.div init.meta.exceptional init.meta.format init.meta.environment import init.meta.pexpr init.data.repr init.data.string.basic init.meta.interaction_monad meta constant tactic_state : Type universes u v namespace tactic_state meta constant env : tactic_state → environment /-- Format the given tactic state. If `target_lhs_only` is true and the target is of the form `lhs ~ rhs`, where `~` is a simplification relation, then only the `lhs` is displayed. Remark: the parameter `target_lhs_only` is a temporary hack used to implement the `conv` monad. It will be removed in the future. -/ meta constant to_format (s : tactic_state) (target_lhs_only : bool := ff) : format /-- Format expression with respect to the main goal in the tactic state. If the tactic state does not contain any goals, then format expression using an empty local context. -/ meta constant format_expr : tactic_state → expr → format meta constant get_options : tactic_state → options meta constant set_options : tactic_state → options → tactic_state end tactic_state meta instance : has_to_format tactic_state := ⟨tactic_state.to_format⟩ meta instance : has_to_string tactic_state := ⟨λ s, (to_fmt s).to_string s.get_options⟩ /-- `tactic` is the monad for building tactics. You use this to: - View and modify the local goals and hypotheses in the prover's state. - Invoke type checking and elaboration of terms. - View and modify the environment. - Build new tactics out of existing ones such as `simp` and `rewrite`. -/ @[reducible] meta def tactic := interaction_monad tactic_state @[reducible] meta def tactic_result := interaction_monad.result tactic_state namespace tactic export interaction_monad (hiding failed fail) /-- Cause the tactic to fail with no error message. -/ meta def failed {α : Type} : tactic α := interaction_monad.failed meta def fail {α : Type u} {β : Type v} [has_to_format β] (msg : β) : tactic α := interaction_monad.fail msg end tactic namespace tactic_result export interaction_monad.result end tactic_result open tactic open tactic_result infixl ` >>=[tactic] `:2 := interaction_monad_bind infixl ` >>[tactic] `:2 := interaction_monad_seq meta instance : alternative tactic := { failure := @interaction_monad.failed _, orelse := @interaction_monad_orelse _, ..interaction_monad.monad } meta def {u₁ u₂} tactic.up {α : Type u₂} (t : tactic α) : tactic (ulift.{u₁} α) := λ s, match t s with | success a s' := success (ulift.up a) s' | exception t ref s := exception t ref s end meta def {u₁ u₂} tactic.down {α : Type u₂} (t : tactic (ulift.{u₁} α)) : tactic α := λ s, match t s with | success (ulift.up a) s' := success a s' | exception t ref s := exception t ref s end namespace interactive /-- Typeclass for custom interaction monads, which provides the information required to convert an interactive-mode construction to a `tactic` which can actually be executed. Given a `[monad m]`, `execute_with` explains how to turn a `begin ... end` block, or a `by ...` statement into a `tactic α` which can actually be executed. The `inhabited` first argument facilitates the passing of an optional configuration parameter `config`, using the syntax: ``` begin [custom_monad] with config, ... end ``` -/ meta class executor (m : Type → Type u) [monad m] := (config_type : Type) [inhabited : inhabited config_type] (execute_with : config_type → m unit → tactic unit) attribute [inline] executor.execute_with @[inline] meta def executor.execute_explicit (m : Type → Type u) [monad m] [e : executor m] : m unit → tactic unit := executor.execute_with e.inhabited.default @[inline] meta def executor.execute_with_explicit (m : Type → Type u) [monad m] [executor m] : executor.config_type m → m unit → tactic unit := executor.execute_with /-- Default `executor` instance for `tactic`s themselves -/ meta instance : executor tactic := { config_type := unit, inhabited := ⟨()⟩, execute_with := λ _, id } end interactive namespace tactic variables {α : Type u} meta def try_core (t : tactic α) : tactic (option α) := λ s, result.cases_on (t s) (λ a, success (some a)) (λ e ref s', success none s) /-- Does nothing. -/ meta def skip : tactic unit := success () meta def try (t : tactic α) : tactic unit := try_core t >>[tactic] skip meta def try_lst : list (tactic unit) → tactic unit | [] := failed | (tac :: tacs) := λ s, match tac s with | result.success _ s' := try (try_lst tacs) s' | result.exception e p s' := match try_lst tacs s' with | result.exception _ _ _ := result.exception e p s' | r := r end end meta def fail_if_success {α : Type u} (t : tactic α) : tactic unit := λ s, result.cases_on (t s) (λ a s, mk_exception "fail_if_success combinator failed, given tactic succeeded" none s) (λ e ref s', success () s) meta def success_if_fail {α : Type u} (t : tactic α) : tactic unit := λ s, match t s with | (interaction_monad.result.exception _ _ s') := success () s | (interaction_monad.result.success a s) := mk_exception "success_if_fail combinator failed, given tactic succeeded" none s end open nat /-- (iterate_at_most n t): repeat the given tactic at most n times or until t fails -/ meta def iterate_at_most : nat → tactic unit → tactic unit | 0 t := skip | (succ n) t := (do t, iterate_at_most n t) <|> skip /-- (iterate_exactly n t) : execute t n times -/ meta def iterate_exactly : nat → tactic unit → tactic unit | 0 t := skip | (succ n) t := do t, iterate_exactly n t /-- Repeat the given tactic forever. -/ meta def iterate : tactic unit → tactic unit := iterate_at_most 100000 meta def returnopt (e : option α) : tactic α := λ s, match e with | (some a) := success a s | none := mk_exception "failed" none s end meta instance opt_to_tac : has_coe (option α) (tactic α) := ⟨returnopt⟩ /-- Decorate t's exceptions with msg. -/ meta def decorate_ex (msg : format) (t : tactic α) : tactic α := λ s, result.cases_on (t s) success (λ opt_thunk, match opt_thunk with | some e := exception (some (λ u, msg ++ format.nest 2 (format.line ++ e u))) | none := exception none end) /-- Set the tactic_state. -/ @[inline] meta def write (s' : tactic_state) : tactic unit := λ s, success () s' /-- Get the tactic_state. -/ @[inline] meta def read : tactic tactic_state := λ s, success s s meta def get_options : tactic options := do s ← read, return s.get_options meta def set_options (o : options) : tactic unit := do s ← read, write (s.set_options o) meta def save_options {α : Type} (t : tactic α) : tactic α := do o ← get_options, a ← t, set_options o, return a meta def returnex {α : Type} (e : exceptional α) : tactic α := λ s, match e with | exceptional.success a := success a s | exceptional.exception f := match get_options s with | success opt _ := exception (some (λ u, f opt)) none s | exception _ _ _ := exception (some (λ u, f options.mk)) none s end end meta instance ex_to_tac {α : Type} : has_coe (exceptional α) (tactic α) := ⟨returnex⟩ end tactic meta def tactic_format_expr (e : expr) : tactic format := do s ← tactic.read, return (tactic_state.format_expr s e) meta class has_to_tactic_format (α : Type u) := (to_tactic_format : α → tactic format) meta instance : has_to_tactic_format expr := ⟨tactic_format_expr⟩ meta def tactic.pp {α : Type u} [has_to_tactic_format α] : α → tactic format := has_to_tactic_format.to_tactic_format open tactic format meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (list α) := ⟨λ l, to_fmt <$> l.mmap pp⟩ meta instance (α : Type u) (β : Type v) [has_to_tactic_format α] [has_to_tactic_format β] : has_to_tactic_format (α × β) := ⟨λ ⟨a, b⟩, to_fmt <$> (prod.mk <$> pp a <*> pp b)⟩ meta def option_to_tactic_format {α : Type u} [has_to_tactic_format α] : option α → tactic format | (some a) := do fa ← pp a, return (to_fmt "(some " ++ fa ++ ")") | none := return "none" meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (option α) := ⟨option_to_tactic_format⟩ meta instance {α} (a : α) : has_to_tactic_format (reflected a) := ⟨λ h, pp h.to_expr⟩ @[priority 10] meta instance has_to_format_to_has_to_tactic_format (α : Type) [has_to_format α] : has_to_tactic_format α := ⟨(λ x, return x) ∘ to_fmt⟩ namespace tactic open tactic_state meta def get_env : tactic environment := do s ← read, return $ env s meta def get_decl (n : name) : tactic declaration := do s ← read, (env s).get n meta def trace {α : Type u} [has_to_tactic_format α] (a : α) : tactic unit := do fmt ← pp a, return $ _root_.trace_fmt fmt (λ u, ()) meta def trace_call_stack : tactic unit := assume state, _root_.trace_call_stack (success () state) meta def timetac {α : Type u} (desc : string) (t : thunk (tactic α)) : tactic α := λ s, timeit desc (t () s) meta def trace_state : tactic unit := do s ← read, trace $ to_fmt s /-- A parameter representing how aggressively definitions should be unfolded when trying to decide if two terms match, unify or are definitionally equal. By default, theorem declarations are never unfolded. - `all` will unfold everything, including macros and theorems. Except projection macros. - `semireducible` will unfold everything except theorems and definitions tagged as irreducible. - `instances` will unfold all class instance definitions and definitions tagged with reducible. - `reducible` will only unfold definitions tagged with the `reducible` attribute. - `none` will never unfold anything. [NOTE] You are not allowed to tag a definition with more than one of `reducible`, `irreducible`, `semireducible` attributes. [NOTE] there is a config flag `m_unfold_lemmas`that will make it unfold theorems. -/ inductive transparency | all | semireducible | instances | reducible | none export transparency (reducible semireducible) /-- (eval_expr α e) evaluates 'e' IF 'e' has type 'α'. -/ meta constant eval_expr (α : Type u) [reflected α] : expr → tactic α /-- Return the partial term/proof constructed so far. Note that the resultant expression may contain variables that are not declarate in the current main goal. -/ meta constant result : tactic expr /-- Display the partial term/proof constructed so far. This tactic is *not* equivalent to `do { r ← result, s ← read, return (format_expr s r) }` because this one will format the result with respect to the current goal, and trace_result will do it with respect to the initial goal. -/ meta constant format_result : tactic format /-- Return target type of the main goal. Fail if tactic_state does not have any goal left. -/ meta constant target : tactic expr meta constant intro_core : name → tactic expr meta constant intron : nat → tactic unit /-- Clear the given local constant. The tactic fails if the given expression is not a local constant. -/ meta constant clear : expr → tactic unit /-- `revert_lst : list expr → tactic nat` is the reverse of `intron`. It takes a local constant `c` and puts it back as bound by a `pi` or `elet` of the main target. If there are other local constants that depend on `c`, these are also reverted. Because of this, the `nat` that is returned is the actual number of reverted local constants. Example: with `x : ℕ, h : P(x) ⊢ T(x)`, `revert_lst [x]` returns `2` and produces the state ` ⊢ Π x, P(x) → T(x)`. -/ meta constant revert_lst : list expr → tactic nat /-- Return `e` in weak head normal form with respect to the given transparency setting. If `unfold_ginductive` is `tt`, then nested and/or mutually recursive inductive datatype constructors and types are unfolded. Recall that nested and mutually recursive inductive datatype declarations are compiled into primitive datatypes accepted by the Kernel. -/ meta constant whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic expr /-- (head) eta expand the given expression. `f : α → β` head-eta-expands to `λ a, f a`. If `f` isn't a function then it just returns `f`. -/ meta constant head_eta_expand : expr → tactic expr /-- (head) beta reduction. `(λ x, B) c` reduces to `B[x/c]`. -/ meta constant head_beta : expr → tactic expr /-- (head) zeta reduction. Reduction of let bindings at the head of the expression. `let x : a := b in c` reduces to `c[x/b]`. -/ meta constant head_zeta : expr → tactic expr /-- Zeta reduction. Reduction of let bindings. `let x : a := b in c` reduces to `c[x/b]`. -/ meta constant zeta : expr → tactic expr /-- (head) eta reduction. `(λ x, f x)` reduces to `f`. -/ meta constant head_eta : expr → tactic expr /-- Succeeds if `t` and `s` can be unified using the given transparency setting. -/ meta constant unify (t s : expr) (md := semireducible) (approx := ff) : tactic unit /-- Similar to `unify`, but it treats metavariables as constants. -/ meta constant is_def_eq (t s : expr) (md := semireducible) (approx := ff) : tactic unit /-- Infer the type of the given expression. Remark: transparency does not affect type inference -/ meta constant infer_type : expr → tactic expr /-- Get the `local_const` expr for the given `name`. -/ meta constant get_local : name → tactic expr /-- Resolve a name using the current local context, environment, aliases, etc. -/ meta constant resolve_name : name → tactic pexpr /-- Return the hypothesis in the main goal. Fail if tactic_state does not have any goal left. -/ meta constant local_context : tactic (list expr) /-- Get a fresh name that is guaranteed to not be in use in the local context. If `n` is provided and `n` is not in use, then `n` is returned. Otherwise a number `i` is appended to give `"n_i"`. -/ meta constant get_unused_name (n : name := `_x) (i : option nat := none) : tactic name /-- Helper tactic for creating simple applications where some arguments are inferred using type inference. Example, given ``` rel.{l_1 l_2} : Pi (α : Type.{l_1}) (β : α -> Type.{l_2}), (Pi x : α, β x) -> (Pi x : α, β x) -> , Prop nat : Type real : Type vec.{l} : Pi (α : Type l) (n : nat), Type.{l1} f g : Pi (n : nat), vec real n ``` then ``` mk_app_core semireducible "rel" [f, g] ``` returns the application ``` rel.{1 2} nat (fun n : nat, vec real n) f g ``` The unification constraints due to type inference are solved using the transparency `md`. -/ meta constant mk_app (fn : name) (args : list expr) (md := semireducible) : tactic expr /-- Similar to `mk_app`, but allows to specify which arguments are explicit/implicit. Example, given `(a b : nat)` then ``` mk_mapp "ite" [some (a > b), none, none, some a, some b] ``` returns the application ``` @ite.{1} (a > b) (nat.decidable_gt a b) nat a b ``` -/ meta constant mk_mapp (fn : name) (args : list (option expr)) (md := semireducible) : tactic expr /-- (mk_congr_arg h₁ h₂) is a more efficient version of (mk_app `congr_arg [h₁, h₂]) -/ meta constant mk_congr_arg : expr → expr → tactic expr /-- (mk_congr_fun h₁ h₂) is a more efficient version of (mk_app `congr_fun [h₁, h₂]) -/ meta constant mk_congr_fun : expr → expr → tactic expr /-- (mk_congr h₁ h₂) is a more efficient version of (mk_app `congr [h₁, h₂]) -/ meta constant mk_congr : expr → expr → tactic expr /-- (mk_eq_refl h) is a more efficient version of (mk_app `eq.refl [h]) -/ meta constant mk_eq_refl : expr → tactic expr /-- (mk_eq_symm h) is a more efficient version of (mk_app `eq.symm [h]) -/ meta constant mk_eq_symm : expr → tactic expr /-- (mk_eq_trans h₁ h₂) is a more efficient version of (mk_app `eq.trans [h₁, h₂]) -/ meta constant mk_eq_trans : expr → expr → tactic expr /-- (mk_eq_mp h₁ h₂) is a more efficient version of (mk_app `eq.mp [h₁, h₂]) -/ meta constant mk_eq_mp : expr → expr → tactic expr /-- (mk_eq_mpr h₁ h₂) is a more efficient version of (mk_app `eq.mpr [h₁, h₂]) -/ meta constant mk_eq_mpr : expr → expr → tactic expr /- Given a local constant t, if t has type (lhs = rhs) apply substitution. Otherwise, try to find a local constant that has type of the form (t = t') or (t' = t). The tactic fails if the given expression is not a local constant. -/ meta constant subst_core : expr → tactic unit /-- Close the current goal using `e`. Fail is the type of `e` is not definitionally equal to the target type. -/ meta constant exact (e : expr) (md := semireducible) : tactic unit /-- Elaborate the given quoted expression with respect to the current main goal. Note that this means that any implicit arguments for the given `pexpr` will be applied with fresh metavariables. If `allow_mvars` is tt, then metavariables are tolerated and become new goals if `subgoals` is tt. -/ meta constant to_expr (q : pexpr) (allow_mvars := tt) (subgoals := tt) : tactic expr /-- Return true if the given expression is a type class. -/ meta constant is_class : expr → tactic bool /-- Try to create an instance of the given type class. -/ meta constant mk_instance : expr → tactic expr /-- Change the target of the main goal. The input expression must be definitionally equal to the current target. If `check` is `ff`, then the tactic does not check whether `e` is definitionally equal to the current target. If it is not, then the error will only be detected by the kernel type checker. -/ meta constant change (e : expr) (check : bool := tt): tactic unit /-- `assert_core H T`, adds a new goal for T, and change target to `T -> target`. -/ meta constant assert_core : name → expr → tactic unit /-- `assertv_core H T P`, change target to (T -> target) if P has type T. -/ meta constant assertv_core : name → expr → expr → tactic unit /-- `define_core H T`, adds a new goal for T, and change target to `let H : T := ?M in target` in the current goal. -/ meta constant define_core : name → expr → tactic unit /-- `definev_core H T P`, change target to `let H : T := P in target` if P has type T. -/ meta constant definev_core : name → expr → expr → tactic unit /-- Rotate goals to the left. That is, `rotate_left 1` takes the main goal and puts it to the back of the subgoal list. -/ meta constant rotate_left : nat → tactic unit /-- Gets a list of metavariables, one for each goal. -/ meta constant get_goals : tactic (list expr) /-- Replace the current list of goals with the given one. Each expr in the list should be a metavariable. Any assigned metavariables will be ignored.-/ meta constant set_goals : list expr → tactic unit /-- How to order the new goals made from an `apply` tactic. Supposing we were applying `e : ∀ (a:α) (p : P(a)), Q` - `non_dep_first` would produce goals `⊢ P(?m)`, `⊢ α`. It puts the P goal at the front because none of the arguments after `p` in `e` depend on `p`. It doesn't matter what the result `Q` depends on. - `non_dep_only` would produce goal `⊢ P(?m)`. - `all` would produce goals `⊢ α`, `⊢ P(?m)`. -/ inductive new_goals | non_dep_first | non_dep_only | all /-- Configuration options for the `apply` tactic. - `md` sets how aggressively definitions are unfolded. - `new_goals` is the strategy for ordering new goals. - `instances` if `tt`, then `apply` tries to synthesize unresolved `[...]` arguments using type class resolution. - `auto_param` if `tt`, then `apply` tries to synthesize unresolved `(h : p . tac_id)` arguments using tactic `tac_id`. - `opt_param` if `tt`, then `apply` tries to synthesize unresolved `(a : t := v)` arguments by setting them to `v`. - `unify` if `tt`, then `apply` is free to assign existing metavariables in the goal when solving unification constraints. For example, in the goal `|- ?x < succ 0`, the tactic `apply succ_lt_succ` succeeds with the default configuration, but `apply_with succ_lt_succ {unify := ff}` doesn't since it would require Lean to assign `?x` to `succ ?y` where `?y` is a fresh metavariable. -/ structure apply_cfg := (md := semireducible) (approx := tt) (new_goals := new_goals.non_dep_first) (instances := tt) (auto_param := tt) (opt_param := tt) (unify := tt) /-- Apply the expression `e` to the main goal, the unification is performed using the transparency mode in `cfg`. Supposing `e : Π (a₁:α₁) ... (aₙ:αₙ), P(a₁,...,aₙ)` and the target is `Q`, `apply` will attempt to unify `Q` with `P(?a₁,...?aₙ)`. All of the metavariables that are not assigned are added as new metavariables. If `cfg.approx` is `tt`, then fallback to first-order unification, and approximate context during unification. `cfg.new_goals` specifies which unassigned metavariables become new goals, and their order. If `cfg.instances` is `tt`, then use type class resolution to instantiate unassigned meta-variables. The fields `cfg.auto_param` and `cfg.opt_param` are ignored by this tactic (See `tactic.apply`). It returns a list of all introduced meta variables and the parameter name associated with them, even the assigned ones. -/ meta constant apply_core (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr)) /- Create a fresh meta universe variable. -/ meta constant mk_meta_univ : tactic level /- Create a fresh meta-variable with the given type. The scope of the new meta-variable is the local context of the main goal. -/ meta constant mk_meta_var : expr → tactic expr /-- Return the value assigned to the given universe meta-variable. Fail if argument is not an universe meta-variable or if it is not assigned. -/ meta constant get_univ_assignment : level → tactic level /-- Return the value assigned to the given meta-variable. Fail if argument is not a meta-variable or if it is not assigned. -/ meta constant get_assignment : expr → tactic expr /-- Return true if the given meta-variable is assigned. Fail if argument is not a meta-variable. -/ meta constant is_assigned : expr → tactic bool /-- Make a name that is guaranteed to be unique. Eg `_fresh.1001.4667`. These will be different for each run of the tactic. -/ meta constant mk_fresh_name : tactic name /-- Induction on `h` using recursor `rec`, names for the new hypotheses are retrieved from `ns`. If `ns` does not have sufficient names, then use the internal binder names in the recursor. It returns for each new goal the name of the constructor (if `rec_name` is a builtin recursor), a list of new hypotheses, and a list of substitutions for hypotheses depending on `h`. The substitutions map internal names to their replacement terms. If the replacement is again a hypothesis the user name stays the same. The internal names are only valid in the original goal, not in the type context of the new goal. Remark: if `rec_name` is not a builtin recursor, we use parameter names of `rec_name` instead of constructor names. If `rec` is none, then the type of `h` is inferred, if it is of the form `C ...`, tactic uses `C.rec` -/ meta constant induction (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic (list (name × list expr × list (name × expr))) /-- Apply `cases_on` recursor, names for the new hypotheses are retrieved from `ns`. `h` must be a local constant. It returns for each new goal the name of the constructor, a list of new hypotheses, and a list of substitutions for hypotheses depending on `h`. The number of new goals may be smaller than the number of constructors. Some goals may be discarded when the indices to not match. See `induction` for information on the list of substitutions. The `cases` tactic is implemented using this one, and it relaxes the restriction of `h`. -/ meta constant cases_core (h : expr) (ns : list name := []) (md := semireducible) : tactic (list (name × list expr × list (name × expr))) /-- Similar to cases tactic, but does not revert/intro/clear hypotheses. -/ meta constant destruct (e : expr) (md := semireducible) : tactic unit /-- Generalizes the target with respect to `e`. -/ meta constant generalize (e : expr) (n : name := `_x) (md := semireducible) : tactic unit /-- instantiate assigned metavariables in the given expression -/ meta constant instantiate_mvars : expr → tactic expr /-- Add the given declaration to the environment -/ meta constant add_decl : declaration → tactic unit /-- Changes the environment to the `new_env`. The new environment does not need to be a descendant of the old one. Use with care. -/ meta constant set_env_core : environment → tactic unit /-- Changes the environment to the `new_env`. `new_env` needs to be a descendant from the current environment. -/ meta constant set_env : environment → tactic unit /-- `doc_string env d k` returns the doc string for `d` (if available) -/ meta constant doc_string : name → tactic string /-- Set the docstring for the given declaration. -/ meta constant add_doc_string : name → string → tactic unit /-- Create an auxiliary definition with name `c` where `type` and `value` may contain local constants and meta-variables. This function collects all dependencies (universe parameters, universe metavariables, local constants (aka hypotheses) and metavariables). It updates the environment in the tactic_state, and returns an expression of the form (c.{l_1 ... l_n} a_1 ... a_m) where l_i's and a_j's are the collected dependencies. -/ meta constant add_aux_decl (c : name) (type : expr) (val : expr) (is_lemma : bool) : tactic expr /-- Returns a list of all top-level (`/-! ... -/`) docstrings in the active module and imported ones. The returned object is a list of modules, indexed by `(some filename)` for imported modules and `none` for the active one, where each module in the list is paired with a list of `(position_in_file, docstring)` pairs. -/ meta constant olean_doc_strings : tactic (list (option string × (list (pos × string)))) /-- Returns a list of docstrings in the active module. An entry in the list can be either: - a top-level (`/-! ... -/`) docstring, represented as `(none, docstring)` - a declaration-specific (`/-- ... -/`) docstring, represented as `(some decl_name, docstring)` -/ meta def module_doc_strings : tactic (list (option name × string)) := do /- Obtain a list of top-level docs in current module. -/ mod_docs ← olean_doc_strings, let mod_docs: list (list (option name × string)) := mod_docs.filter_map (λ d, if d.1.is_none then some (d.2.map (λ pos_doc, ⟨none, pos_doc.2⟩)) else none), let mod_docs := mod_docs.join, /- Obtain list of declarations in current module. -/ e ← get_env, let decls := environment.fold e ([]: list name) (λ d acc, let n := d.to_name in if (environment.decl_olean e n).is_none then n::acc else acc), /- Map declarations to those which have docstrings. -/ decls ← decls.mfoldl (λa n, (doc_string n >>= λ doc, pure $ (some n, doc) :: a) <|> pure a) [], pure (mod_docs ++ decls) /-- Set attribute `attr_name` for constant `c_name` with the given priority. If the priority is none, then use default -/ meta constant set_basic_attribute (attr_name : name) (c_name : name) (persistent := ff) (prio : option nat := none) : tactic unit /-- `unset_attribute attr_name c_name` -/ meta constant unset_attribute : name → name → tactic unit /-- `has_attribute attr_name c_name` succeeds if the declaration `decl_name` has the attribute `attr_name`. The result is the priority and whether or not the attribute is persistent. -/ meta constant has_attribute : name → name → tactic (bool × nat) /-- `copy_attribute attr_name c_name p d_name` copy attribute `attr_name` from `src` to `tgt` if it is defined for `src`; make it persistent if `p` is `tt`; if `p` is `none`, the copied attribute is made persistent iff it is persistent on `src` -/ meta def copy_attribute (attr_name : name) (src : name) (tgt : name) (p : option bool := none) : tactic unit := try $ do (p', prio) ← has_attribute attr_name src, let p := p.get_or_else p', set_basic_attribute attr_name tgt p (some prio) /-- Name of the declaration currently being elaborated. -/ meta constant decl_name : tactic name /-- `save_type_info e ref` save (typeof e) at position associated with ref -/ meta constant save_type_info {elab : bool} : expr → expr elab → tactic unit meta constant save_info_thunk : pos → (unit → format) → tactic unit /-- Return list of currently open namespaces -/ meta constant open_namespaces : tactic (list name) /-- Return tt iff `t` "occurs" in `e`. The occurrence checking is performed using keyed matching with the given transparency setting. We say `t` occurs in `e` by keyed matching iff there is a subterm `s` s.t. `t` and `s` have the same head, and `is_def_eq t s md` The main idea is to minimize the number of `is_def_eq` checks performed. -/ meta constant kdepends_on (e t : expr) (md := reducible) : tactic bool /-- Abstracts all occurrences of the term `t` in `e` using keyed matching. If `unify` is `ff`, then matching is used instead of unification. That is, metavariables occurring in `e` are not assigned. -/ meta constant kabstract (e t : expr) (md := reducible) (unify := tt) : tactic expr /-- Blocks the execution of the current thread for at least `msecs` milliseconds. This tactic is used mainly for debugging purposes. -/ meta constant sleep (msecs : nat) : tactic unit /-- Type check `e` with respect to the current goal. Fails if `e` is not type correct. -/ meta constant type_check (e : expr) (md := semireducible) : tactic unit open list nat /-- A `tag` is a list of `names`. These are attached to goals to help tactics track them.-/ def tag : Type := list name /-- Enable/disable goal tagging. -/ meta constant enable_tags (b : bool) : tactic unit /-- Return tt iff goal tagging is enabled. -/ meta constant tags_enabled : tactic bool /-- Tag goal `g` with tag `t`. It does nothing if goal tagging is disabled. Remark: `set_goal g []` removes the tag -/ meta constant set_tag (g : expr) (t : tag) : tactic unit /-- Return tag associated with `g`. Return `[]` if there is no tag. -/ meta constant get_tag (g : expr) : tactic tag /-- By default, Lean only considers local instances in the header of declarations. This has two main benefits. 1- Results produced by the type class resolution procedure can be easily cached. 2- The set of local instances does not have to be recomputed. This approach has the following disadvantages: 1- Frozen local instances cannot be reverted. 2- Local instances defined inside of a declaration are not considered during type class resolution. This tactic resets the set of local instances. After executing this tactic, the set of local instances will be recomputed and the cache will be frequently reset. Note that, the cache is still used when executing a single tactic that may generate many type class resolution problems (e.g., `simp`). -/ meta constant unfreeze_local_instances : tactic unit /- Return the list of frozen local instances. Return `none` if local instances were not frozen. -/ meta constant frozen_local_instances : tactic (option (list expr)) meta def induction' (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic unit := induction h ns rec md >> return () /-- Remark: set_goals will erase any solved goal -/ meta def cleanup : tactic unit := get_goals >>= set_goals /-- Auxiliary definition used to implement begin ... end blocks -/ meta def step {α : Type u} (t : tactic α) : tactic unit := t >>[tactic] cleanup meta def istep {α : Type u} (line0 col0 : ℕ) (line col : ℕ) (t : tactic α) : tactic unit := λ s, (@scope_trace _ line col (λ _, step t s)).clamp_pos line0 line col meta def is_prop (e : expr) : tactic bool := do t ← infer_type e, return (t = `(Prop)) /-- Return true iff n is the name of declaration that is a proposition. -/ meta def is_prop_decl (n : name) : tactic bool := do env ← get_env, d ← env.get n, t ← return $ d.type, is_prop t meta def is_proof (e : expr) : tactic bool := infer_type e >>= is_prop meta def whnf_no_delta (e : expr) : tactic expr := whnf e transparency.none /-- Return `e` in weak head normal form with respect to the given transparency setting, or `e` head is a generalized constructor or inductive datatype. -/ meta def whnf_ginductive (e : expr) (md := semireducible) : tactic expr := whnf e md ff meta def whnf_target : tactic unit := target >>= whnf >>= change /-- Change the target of the main goal. The input expression must be definitionally equal to the current target. The tactic does not check whether `e` is definitionally equal to the current target. The error will only be detected by the kernel type checker. -/ meta def unsafe_change (e : expr) : tactic unit := change e ff /-- Pi or elet introduction. Given the tactic state `⊢ Π x : α, Y`, ``intro `hello`` will produce the state `hello : α ⊢ Y[x/hello]`. Returns the new local constant. Similarly for `elet` expressions. If the target is not a Pi or elet it will try to put it in WHNF. -/ meta def intro (n : name) : tactic expr := do t ← target, if expr.is_pi t ∨ expr.is_let t then intro_core n else whnf_target >> intro_core n /-- Like `intro` except the name is derived from the bound name in the Π. -/ meta def intro1 : tactic expr := intro `_ /-- Repeatedly apply `intro1` and return the list of new local constants in order of introduction.-/ meta def intros : tactic (list expr) := do t ← target, match t with | expr.pi _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs) | expr.elet _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs) | _ := return [] end /-- Same as `intros`, except with the given names for the new hypotheses. Use the name ```_``` to instead use the binder's name.-/ meta def intro_lst : list name → tactic (list expr) | [] := return [] | (n::ns) := do H ← intro n, Hs ← intro_lst ns, return (H :: Hs) /-- Introduces new hypotheses with forward dependencies. -/ meta def intros_dep : tactic (list expr) := do t ← target, let proc (b : expr) := if b.has_var_idx 0 then do h ← intro1, hs ← intros_dep, return (h::hs) else -- body doesn't depend on new hypothesis return [], match t with | expr.pi _ _ _ b := proc b | expr.elet _ _ _ b := proc b | _ := return [] end meta def introv : list name → tactic (list expr) | [] := intros_dep | (n::ns) := do hs ← intros_dep, h ← intro n, hs' ← introv ns, return (hs ++ h :: hs') /-- Returns n fully qualified if it refers to a constant, or else fails. -/ meta def resolve_constant (n : name) : tactic name := do (expr.const n _) ← resolve_name n, pure n meta def to_expr_strict (q : pexpr) : tactic expr := to_expr q /-- Example: with `x : ℕ, h : P(x) ⊢ T(x)`, `revert x` returns `2` and produces the state ` ⊢ Π x, P(x) → T(x)`. -/ meta def revert (l : expr) : tactic nat := revert_lst [l] /- Revert "all" hypotheses. Actually, the tactic only reverts hypotheses occurring after the last frozen local instance. Recall that frozen local instances cannot be reverted. We can use `unfreeze_local_instances` to workaround this limitation. -/ meta def revert_all : tactic nat := do lctx ← local_context, lis ← frozen_local_instances, match lis with | none := revert_lst lctx | some [] := revert_lst lctx /- `hi` is the last local instance. We shoul truncate `lctx` at `hi`. -/ | some (hi::his) := revert_lst $ lctx.foldl (λ r h, if h.local_uniq_name = hi.local_uniq_name then [] else h :: r) [] end meta def clear_lst : list name → tactic unit | [] := skip | (n::ns) := do H ← get_local n, clear H, clear_lst ns meta def match_not (e : expr) : tactic expr := match (expr.is_not e) with | (some a) := return a | none := fail "expression is not a negation" end meta def match_and (e : expr) : tactic (expr × expr) := match (expr.is_and e) with | (some (α, β)) := return (α, β) | none := fail "expression is not a conjunction" end meta def match_or (e : expr) : tactic (expr × expr) := match (expr.is_or e) with | (some (α, β)) := return (α, β) | none := fail "expression is not a disjunction" end meta def match_iff (e : expr) : tactic (expr × expr) := match (expr.is_iff e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not an iff" end meta def match_eq (e : expr) : tactic (expr × expr) := match (expr.is_eq e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not an equality" end meta def match_ne (e : expr) : tactic (expr × expr) := match (expr.is_ne e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not a disequality" end meta def match_heq (e : expr) : tactic (expr × expr × expr × expr) := do match (expr.is_heq e) with | (some (α, lhs, β, rhs)) := return (α, lhs, β, rhs) | none := fail "expression is not a heterogeneous equality" end meta def match_refl_app (e : expr) : tactic (name × expr × expr) := do env ← get_env, match (environment.is_refl_app env e) with | (some (R, lhs, rhs)) := return (R, lhs, rhs) | none := fail "expression is not an application of a reflexive relation" end meta def match_app_of (e : expr) (n : name) : tactic (list expr) := guard (expr.is_app_of e n) >> return e.get_app_args meta def get_local_type (n : name) : tactic expr := get_local n >>= infer_type meta def trace_result : tactic unit := format_result >>= trace meta def rexact (e : expr) : tactic unit := exact e reducible meta def any_hyp_aux {α : Type} (f : expr → tactic α) : list expr → tactic α | [] := failed | (h :: hs) := f h <|> any_hyp_aux hs meta def any_hyp {α : Type} (f : expr → tactic α) : tactic α := local_context >>= any_hyp_aux f /-- `find_same_type t es` tries to find in es an expression with type definitionally equal to t -/ meta def find_same_type : expr → list expr → tactic expr | e [] := failed | e (H :: Hs) := do t ← infer_type H, (unify e t >> return H) <|> find_same_type e Hs meta def find_assumption (e : expr) : tactic expr := do ctx ← local_context, find_same_type e ctx meta def assumption : tactic unit := do { ctx ← local_context, t ← target, H ← find_same_type t ctx, exact H } <|> fail "assumption tactic failed" meta def save_info (p : pos) : tactic unit := do s ← read, tactic.save_info_thunk p (λ _, tactic_state.to_format s) notation `‹` p `›` := (by assumption : p) /-- Swap first two goals, do nothing if tactic state does not have at least two goals. -/ meta def swap : tactic unit := do gs ← get_goals, match gs with | (g₁ :: g₂ :: rs) := set_goals (g₂ :: g₁ :: rs) | e := skip end /-- `assert h t`, adds a new goal for t, and the hypothesis `h : t` in the current goal. -/ meta def assert (h : name) (t : expr) : tactic expr := do assert_core h t, swap, e ← intro h, swap, return e /-- `assertv h t v`, adds the hypothesis `h : t` in the current goal if v has type t. -/ meta def assertv (h : name) (t : expr) (v : expr) : tactic expr := assertv_core h t v >> intro h /-- `define h t`, adds a new goal for t, and the hypothesis `h : t := ?M` in the current goal. -/ meta def define (h : name) (t : expr) : tactic expr := do define_core h t, swap, e ← intro h, swap, return e /-- `definev h t v`, adds the hypothesis (h : t := v) in the current goal if v has type t. -/ meta def definev (h : name) (t : expr) (v : expr) : tactic expr := definev_core h t v >> intro h /-- Add `h : t := pr` to the current goal -/ meta def pose (h : name) (t : option expr := none) (pr : expr) : tactic expr := let dv := λt, definev h t pr in option.cases_on t (infer_type pr >>= dv) dv /-- Add `h : t` to the current goal, given a proof `pr : t` -/ meta def note (h : name) (t : option expr := none) (pr : expr) : tactic expr := let dv := λt, assertv h t pr in option.cases_on t (infer_type pr >>= dv) dv /-- Return the number of goals that need to be solved -/ meta def num_goals : tactic nat := do gs ← get_goals, return (length gs) /-- Rotate the goals to the right by `n`. That is, take the goal at the back and push it to the front `n` times. [NOTE] We have to provide the instance argument `[has_mod nat]` because mod for nat was not defined yet -/ meta def rotate_right (n : nat) [has_mod nat] : tactic unit := do ng ← num_goals, if ng = 0 then skip else rotate_left (ng - n % ng) /-- Rotate the goals to the left by `n`. That is, put the main goal to the back `n` times. -/ meta def rotate : nat → tactic unit := rotate_left private meta def repeat_aux (t : tactic unit) : list expr → list expr → tactic unit | [] r := set_goals r.reverse | (g::gs) r := do ok ← try_core (set_goals [g] >> t), match ok with | none := repeat_aux gs (g::r) | _ := do gs' ← get_goals, repeat_aux (gs' ++ gs) r end /-- This tactic is applied to each goal. If the application succeeds, the tactic is applied recursively to all the generated subgoals until it eventually fails. The recursion stops in a subgoal when the tactic has failed to make progress. The tactic `repeat` never fails. -/ meta def repeat (t : tactic unit) : tactic unit := do gs ← get_goals, repeat_aux t gs [] /-- `first [t_1, ..., t_n]` applies the first tactic that doesn't fail. The tactic fails if all t_i's fail. -/ meta def first {α : Type u} : list (tactic α) → tactic α | [] := fail "first tactic failed, no more alternatives" | (t::ts) := t <|> first ts /-- Applies the given tactic to the main goal and fails if it is not solved. -/ meta def solve1 (tac : tactic unit) : tactic unit := do gs ← get_goals, match gs with | [] := fail "solve1 tactic failed, there isn't any goal left to focus" | (g::rs) := do set_goals [g], tac, gs' ← get_goals, match gs' with | [] := set_goals rs | gs := fail "solve1 tactic failed, focused goal has not been solved" end end /-- `solve [t_1, ... t_n]` applies the first tactic that solves the main goal. -/ meta def solve (ts : list (tactic unit)) : tactic unit := first $ map solve1 ts private meta def focus_aux : list (tactic unit) → list expr → list expr → tactic unit | [] [] rs := set_goals rs | (t::ts) [] rs := fail "focus tactic failed, insufficient number of goals" | tts (g::gs) rs := mcond (is_assigned g) (focus_aux tts gs rs) $ do set_goals [g], t::ts ← pure tts | fail "focus tactic failed, insufficient number of tactics", t, rs' ← get_goals, focus_aux ts gs (rs ++ rs') /-- `focus [t_1, ..., t_n]` applies t_i to the i-th goal. Fails if the number of goals is not n. -/ meta def focus (ts : list (tactic unit)) : tactic unit := do gs ← get_goals, focus_aux ts gs [] meta def focus1 {α} (tac : tactic α) : tactic α := do g::gs ← get_goals, match gs with | [] := tac | _ := do set_goals [g], a ← tac, gs' ← get_goals, set_goals (gs' ++ gs), return a end private meta def all_goals_core (tac : tactic unit) : list expr → list expr → tactic unit | [] ac := set_goals ac | (g :: gs) ac := mcond (is_assigned g) (all_goals_core gs ac) $ do set_goals [g], tac, new_gs ← get_goals, all_goals_core gs (ac ++ new_gs) /-- Apply the given tactic to all goals. -/ meta def all_goals (tac : tactic unit) : tactic unit := do gs ← get_goals, all_goals_core tac gs [] private meta def any_goals_core (tac : tactic unit) : list expr → list expr → bool → tactic unit | [] ac progress := guard progress >> set_goals ac | (g :: gs) ac progress := mcond (is_assigned g) (any_goals_core gs ac progress) $ do set_goals [g], succeeded ← try_core tac, new_gs ← get_goals, any_goals_core gs (ac ++ new_gs) (succeeded.is_some || progress) /-- Apply the given tactic to any goal where it succeeds. The tactic succeeds only if tac succeeds for at least one goal. -/ meta def any_goals (tac : tactic unit) : tactic unit := do gs ← get_goals, any_goals_core tac gs [] ff /-- LCF-style AND_THEN tactic. It applies tac1, and if succeed applies tac2 to each subgoal produced by tac1 -/ meta def seq (tac1 : tactic unit) (tac2 : tactic unit) : tactic unit := do g::gs ← get_goals, set_goals [g], tac1, all_goals tac2, gs' ← get_goals, set_goals (gs' ++ gs) meta def seq_focus (tac1 : tactic unit) (tacs2 : list (tactic unit)) : tactic unit := do g::gs ← get_goals, set_goals [g], tac1, focus tacs2, gs' ← get_goals, set_goals (gs' ++ gs) meta instance andthen_seq : has_andthen (tactic unit) (tactic unit) (tactic unit) := ⟨seq⟩ meta instance andthen_seq_focus : has_andthen (tactic unit) (list (tactic unit)) (tactic unit) := ⟨seq_focus⟩ meta constant is_trace_enabled_for : name → bool /-- Execute tac only if option trace.n is set to true. -/ meta def when_tracing (n : name) (tac : tactic unit) : tactic unit := when (is_trace_enabled_for n = tt) tac /-- Fail if there are no remaining goals. -/ meta def fail_if_no_goals : tactic unit := do n ← num_goals, when (n = 0) (fail "tactic failed, there are no goals to be solved") /-- Fail if there are unsolved goals. -/ meta def done : tactic unit := do n ← num_goals, when (n ≠ 0) (fail "done tactic failed, there are unsolved goals") meta def apply_opt_param : tactic unit := do `(opt_param %%t %%v) ← target, exact v meta def apply_auto_param : tactic unit := do `(auto_param %%type %%tac_name_expr) ← target, change type, tac_name ← eval_expr name tac_name_expr, tac ← eval_expr (tactic unit) (expr.const tac_name []), tac meta def has_opt_auto_param (ms : list expr) : tactic bool := ms.mfoldl (λ r m, do type ← infer_type m, return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2) ff meta def try_apply_opt_auto_param (cfg : apply_cfg) (ms : list expr) : tactic unit := when (cfg.auto_param || cfg.opt_param) $ mwhen (has_opt_auto_param ms) $ do gs ← get_goals, ms.mmap' (λ m, mwhen (bnot <$> is_assigned m) $ set_goals [m] >> when cfg.opt_param (try apply_opt_param) >> when cfg.auto_param (try apply_auto_param)), set_goals gs meta def has_opt_auto_param_for_apply (ms : list (name × expr)) : tactic bool := ms.mfoldl (λ r m, do type ← infer_type m.2, return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2) ff meta def try_apply_opt_auto_param_for_apply (cfg : apply_cfg) (ms : list (name × expr)) : tactic unit := mwhen (has_opt_auto_param_for_apply ms) $ do gs ← get_goals, ms.mmap' (λ m, mwhen (bnot <$> (is_assigned m.2)) $ set_goals [m.2] >> when cfg.opt_param (try apply_opt_param) >> when cfg.auto_param (try apply_auto_param)), set_goals gs meta def apply (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr)) := do r ← apply_core e cfg, try_apply_opt_auto_param_for_apply cfg r, return r /-- Same as `apply` but __all__ arguments that weren't inferred are added to goal list. -/ meta def fapply (e : expr) : tactic (list (name × expr)) := apply e {new_goals := new_goals.all} /-- Same as `apply` but only goals that don't depend on other goals are added to goal list. -/ meta def eapply (e : expr) : tactic (list (name × expr)) := apply e {new_goals := new_goals.non_dep_only} /-- Try to solve the main goal using type class resolution. -/ meta def apply_instance : tactic unit := do tgt ← target >>= instantiate_mvars, b ← is_class tgt, if b then mk_instance tgt >>= exact else fail "apply_instance tactic fail, target is not a type class" /-- Create a list of universe meta-variables of the given size. -/ meta def mk_num_meta_univs : nat → tactic (list level) | 0 := return [] | (succ n) := do l ← mk_meta_univ, ls ← mk_num_meta_univs n, return (l::ls) /-- Return `expr.const c [l_1, ..., l_n]` where l_i's are fresh universe meta-variables. -/ meta def mk_const (c : name) : tactic expr := do env ← get_env, decl ← env.get c, let num := decl.univ_params.length, ls ← mk_num_meta_univs num, return (expr.const c ls) /-- Apply the constant `c` -/ meta def applyc (c : name) (cfg : apply_cfg := {}) : tactic unit := do c ← mk_const c, apply c cfg, skip meta def eapplyc (c : name) : tactic unit := do c ← mk_const c, eapply c, skip meta def save_const_type_info (n : name) {elab : bool} (ref : expr elab) : tactic unit := try (do c ← mk_const n, save_type_info c ref) /-- Create a fresh universe `?u`, a metavariable `?T : Type.{?u}`, and return metavariable `?M : ?T`. This action can be used to create a meta-variable when we don't know its type at creation time -/ meta def mk_mvar : tactic expr := do u ← mk_meta_univ, t ← mk_meta_var (expr.sort u), mk_meta_var t /-- Makes a sorry macro with a meta-variable as its type. -/ meta def mk_sorry : tactic expr := do u ← mk_meta_univ, t ← mk_meta_var (expr.sort u), return $ expr.mk_sorry t /-- Closes the main goal using sorry. -/ meta def admit : tactic unit := target >>= exact ∘ expr.mk_sorry meta def mk_local' (pp_name : name) (bi : binder_info) (type : expr) : tactic expr := do uniq_name ← mk_fresh_name, return $ expr.local_const uniq_name pp_name bi type meta def mk_local_def (pp_name : name) (type : expr) : tactic expr := mk_local' pp_name binder_info.default type meta def mk_local_pis : expr → tactic (list expr × expr) | (expr.pi n bi d b) := do p ← mk_local' n bi d, (ps, r) ← mk_local_pis (expr.instantiate_var b p), return ((p :: ps), r) | e := return ([], e) private meta def get_pi_arity_aux : expr → tactic nat | (expr.pi n bi d b) := do m ← mk_fresh_name, let l := expr.local_const m n bi d, new_b ← whnf (expr.instantiate_var b l), r ← get_pi_arity_aux new_b, return (r + 1) | e := return 0 /-- Compute the arity of the given (Pi-)type -/ meta def get_pi_arity (type : expr) : tactic nat := whnf type >>= get_pi_arity_aux /-- Compute the arity of the given function -/ meta def get_arity (fn : expr) : tactic nat := infer_type fn >>= get_pi_arity meta def triv : tactic unit := mk_const `trivial >>= exact notation `dec_trivial` := of_as_true (by tactic.triv) meta def by_contradiction (H : option name := none) : tactic expr := do tgt : expr ← target, (match_not tgt >> return ()) <|> (mk_mapp `decidable.by_contradiction [some tgt, none] >>= eapply >> skip) <|> fail "tactic by_contradiction failed, target is not a negation nor a decidable proposition (remark: when 'local attribute [instance] classical.prop_decidable' is used, all propositions are decidable)", match H with | some n := intro n | none := intro1 end private meta def generalizes_aux (md : transparency) : list expr → tactic unit | [] := skip | (e::es) := generalize e `x md >> generalizes_aux es meta def generalizes (es : list expr) (md := semireducible) : tactic unit := generalizes_aux md es private meta def kdependencies_core (e : expr) (md : transparency) : list expr → list expr → tactic (list expr) | [] r := return r | (h::hs) r := do type ← infer_type h, d ← kdepends_on type e md, if d then kdependencies_core hs (h::r) else kdependencies_core hs r /-- Return all hypotheses that depends on `e` The dependency test is performed using `kdepends_on` with the given transparency setting. -/ meta def kdependencies (e : expr) (md := reducible) : tactic (list expr) := do ctx ← local_context, kdependencies_core e md ctx [] /-- Revert all hypotheses that depend on `e` -/ meta def revert_kdependencies (e : expr) (md := reducible) : tactic nat := kdependencies e md >>= revert_lst meta def revert_kdeps (e : expr) (md := reducible) := revert_kdependencies e md /-- Similar to `cases_core`, but `e` doesn't need to be a hypothesis. Remark, it reverts dependencies using `revert_kdeps`. Two different transparency modes are used `md` and `dmd`. The mode `md` is used with `cases_core` and `dmd` with `generalize` and `revert_kdeps`. It returns the constructor names associated with each new goal. -/ meta def cases (e : expr) (ids : list name := []) (md := semireducible) (dmd := semireducible) : tactic (list name) := if e.is_local_constant then do r ← cases_core e ids md, return $ r.map (λ t, t.1) else do n ← revert_kdependencies e dmd, x ← get_unused_name, (tactic.generalize e x dmd) <|> (do t ← infer_type e, tactic.assertv x t e, get_local x >>= tactic.revert, return ()), h ← tactic.intro1, focus1 (do r ← cases_core h ids md, all_goals (intron n), return $ r.map (λ t, t.1)) /-- The same as `exact` except you can add proof holes. -/ meta def refine (e : pexpr) : tactic unit := do tgt : expr ← target, to_expr ``(%%e : %%tgt) tt >>= exact meta def by_cases (e : expr) (h : name) : tactic unit := do dec_e ← (mk_app `decidable [e] <|> fail "by_cases tactic failed, type is not a proposition"), inst ← (mk_instance dec_e <|> fail "by_cases tactic failed, type of given expression is not decidable"), t ← target, tm ← mk_mapp `dite [some e, some inst, some t], seq (apply tm >> skip) (intro h >> skip) meta def funext_core : list name → bool → tactic unit | [] tt := return () | ids only_ids := try $ do some (lhs, rhs) ← expr.is_eq <$> (target >>= whnf), applyc `funext, id ← if ids.empty ∨ ids.head = `_ then do (expr.lam n _ _ _) ← whnf lhs | pure `_, return n else return ids.head, intro id, funext_core ids.tail only_ids meta def funext : tactic unit := funext_core [] ff meta def funext_lst (ids : list name) : tactic unit := funext_core ids tt private meta def get_undeclared_const (env : environment) (base : name) : ℕ → name | i := let n := base <.> ("_aux_" ++ repr i) in if ¬env.contains n then n else get_undeclared_const (i+1) meta def new_aux_decl_name : tactic name := do env ← get_env, n ← decl_name, return $ get_undeclared_const env n 1 private meta def mk_aux_decl_name : option name → tactic name | none := new_aux_decl_name | (some suffix) := do p ← decl_name, return $ p ++ suffix meta def abstract (tac : tactic unit) (suffix : option name := none) (zeta_reduce := tt) : tactic unit := do fail_if_no_goals, gs ← get_goals, type ← if zeta_reduce then target >>= zeta else target, is_lemma ← is_prop type, m ← mk_meta_var type, set_goals [m], tac, n ← num_goals, when (n ≠ 0) (fail "abstract tactic failed, there are unsolved goals"), set_goals gs, val ← instantiate_mvars m, val ← if zeta_reduce then zeta val else return val, c ← mk_aux_decl_name suffix, e ← add_aux_decl c type val is_lemma, exact e /-- `solve_aux type tac` synthesize an element of 'type' using tactic 'tac' -/ meta def solve_aux {α : Type} (type : expr) (tac : tactic α) : tactic (α × expr) := do m ← mk_meta_var type, gs ← get_goals, set_goals [m], a ← tac, set_goals gs, return (a, m) /-- Return tt iff 'd' is a declaration in one of the current open namespaces -/ meta def in_open_namespaces (d : name) : tactic bool := do ns ← open_namespaces, env ← get_env, return $ ns.any (λ n, n.is_prefix_of d) && env.contains d /-- Execute tac for 'max' "heartbeats". The heartbeat is approx. the maximum number of memory allocations (in thousands) performed by 'tac'. This is a deterministic way of interrupting long running tactics. -/ meta def try_for {α} (max : nat) (tac : tactic α) : tactic α := λ s, match _root_.try_for max (tac s) with | some r := r | none := mk_exception "try_for tactic failed, timeout" none s end meta def updateex_env (f : environment → exceptional environment) : tactic unit := do env ← get_env, env ← returnex $ f env, set_env env /- Add a new inductive datatype to the environment name, universe parameters, number of parameters, type, constructors (name and type), is_meta -/ meta def add_inductive (n : name) (ls : list name) (p : nat) (ty : expr) (is : list (name × expr)) (is_meta : bool := ff) : tactic unit := updateex_env $ λe, e.add_inductive n ls p ty is is_meta meta def add_meta_definition (n : name) (lvls : list name) (type value : expr) : tactic unit := add_decl (declaration.defn n lvls type value reducibility_hints.abbrev ff) /-- add declaration `d` as a protected declaration -/ meta def add_protected_decl (d : declaration) : tactic unit := updateex_env $ λ e, e.add_protected d /-- check if `n` is the name of a protected declaration -/ meta def is_protected_decl (n : name) : tactic bool := do env ← get_env, return $ env.is_protected n /-- `add_defn_equations` adds a definition specified by a list of equations. The arguments: * `lp`: list of universe parameters * `params`: list of parameters (binders before the colon); * `fn`: a local constant giving the name and type of the declaration (with `params` in the local context); * `eqns`: a list of equations, each of which is a list of patterns (constructors applied to new local constants) and the branch expression; * `is_meta`: is the definition meta? `add_defn_equations` can be used as: do my_add ← mk_local_def `my_add `(ℕ → ℕ), a ← mk_local_def `a ℕ, b ← mk_local_def `b ℕ, add_defn_equations [a] my_add [ ([``(nat.zero)], a), ([``(nat.succ %%b)], my_add b) ]) ff -- non-meta to create the following definition: def my_add (a : ℕ) : ℕ → ℕ | nat.zero := a | (nat.succ b) := my_add b -/ meta def add_defn_equations (lp : list name) (params : list expr) (fn : expr) (eqns : list (list pexpr × expr)) (is_meta : bool) : tactic unit := do opt ← get_options, updateex_env $ λ e, e.add_defn_eqns opt lp params fn eqns is_meta meta def rename (curr : name) (new : name) : tactic unit := do h ← get_local curr, n ← revert h, intro new, intron (n - 1) /-- "Replace" hypothesis `h : type` with `h : new_type` where `eq_pr` is a proof that (type = new_type). The tactic actually creates a new hypothesis with the same user facing name, and (tries to) clear `h`. The `clear` step fails if `h` has forward dependencies. In this case, the old `h` will remain in the local context. The tactic returns the new hypothesis. -/ meta def replace_hyp (h : expr) (new_type : expr) (eq_pr : expr) : tactic expr := do h_type ← infer_type h, new_h ← assert h.local_pp_name new_type, mk_eq_mp eq_pr h >>= exact, try $ clear h, return new_h meta def main_goal : tactic expr := do g::gs ← get_goals, return g /- Goal tagging support -/ meta def with_enable_tags {α : Type} (t : tactic α) (b := tt) : tactic α := do old ← tags_enabled, enable_tags b, r ← t, enable_tags old, return r meta def get_main_tag : tactic tag := main_goal >>= get_tag meta def set_main_tag (t : tag) : tactic unit := do g ← main_goal, set_tag g t meta def subst (h : expr) : tactic unit := (do guard h.is_local_constant, some (α, lhs, β, rhs) ← expr.is_heq <$> infer_type h, is_def_eq α β, new_h_type ← mk_app `eq [lhs, rhs], new_h_pr ← mk_app `eq_of_heq [h], new_h ← assertv h.local_pp_name new_h_type new_h_pr, try (clear h), subst_core new_h) <|> subst_core h end tactic notation [parsing_only] `command`:max := tactic unit open tactic namespace list meta def for_each {α} : list α → (α → tactic unit) → tactic unit | [] fn := skip | (e::es) fn := do fn e, for_each es fn meta def any_of {α β} : list α → (α → tactic β) → tactic β | [] fn := failed | (e::es) fn := do opt_b ← try_core (fn e), match opt_b with | some b := return b | none := any_of es fn end end list /- Install monad laws tactic and use it to prove some instances. -/ /-- Try to prove with `iff.refl`.-/ meta def order_laws_tac := whnf_target >> intros >> to_expr ``(iff.refl _) >>= exact meta def monad_from_pure_bind {m : Type u → Type v} (pure : Π {α : Type u}, α → m α) (bind : Π {α β : Type u}, m α → (α → m β) → m β) : monad m := {pure := @pure, bind := @bind} meta instance : monad task := {map := @task.map, bind := @task.bind, pure := @task.pure} namespace tactic meta def mk_id_proof (prop : expr) (pr : expr) : expr := expr.app (expr.app (expr.const ``id [level.zero]) prop) pr meta def mk_id_eq (lhs : expr) (rhs : expr) (pr : expr) : tactic expr := do prop ← mk_app `eq [lhs, rhs], return $ mk_id_proof prop pr meta def replace_target (new_target : expr) (pr : expr) : tactic unit := do t ← target, assert `htarget new_target, swap, ht ← get_local `htarget, locked_pr ← mk_id_eq t new_target pr, mk_eq_mpr locked_pr ht >>= exact end tactic
66d87b7f65c6ce62324a1f198a5f7383d2d7f813
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/archive/wiedijk_100_theorems/abel_ruffini.lean
16e3595a8dbf854cebc3823821b09484d1cb20e1
[ "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,454
lean
/- Copyright (c) 2021 Thomas Browning. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning -/ import analysis.calculus.local_extr import data.nat.prime_norm_num import field_theory.abel_ruffini import ring_theory.roots_of_unity.minpoly import ring_theory.eisenstein_criterion /-! # Construction of an algebraic number that is not solvable by radicals. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The main ingredients are: * `solvable_by_rad.is_solvable'` in `field_theory/abel_ruffini` : an irreducible polynomial with an `is_solvable_by_rad` root has solvable Galois group * `gal_action_hom_bijective_of_prime_degree'` in `field_theory/polynomial_galois_group` : an irreducible polynomial of prime degree with 1-3 non-real roots has full Galois group * `equiv.perm.not_solvable` in `group_theory/solvable` : the symmetric group is not solvable Then all that remains is the construction of a specific polynomial satisfying the conditions of `gal_action_hom_bijective_of_prime_degree'`, which is done in this file. -/ namespace abel_ruffini open function polynomial polynomial.gal ideal open_locale polynomial local attribute [instance] splits_ℚ_ℂ variables (R : Type*) [comm_ring R] (a b : ℕ) /-- A quintic polynomial that we will show is irreducible -/ noncomputable def Φ : R[X] := X ^ 5 - C ↑a * X + C ↑b variables {R} @[simp] lemma map_Phi {S : Type*} [comm_ring S] (f : R →+* S) : (Φ R a b).map f = Φ S a b := by simp [Φ] @[simp] lemma coeff_zero_Phi : (Φ R a b).coeff 0 = ↑b := by simp [Φ, coeff_X_pow] @[simp] lemma coeff_five_Phi : (Φ R a b).coeff 5 = 1 := by simp [Φ, coeff_X, coeff_C, -C_eq_nat_cast, -map_nat_cast] variables [nontrivial R] lemma degree_Phi : (Φ R a b).degree = ↑5 := begin suffices : degree (X ^ 5 - C ↑a * X) = ↑5, { rwa [Φ, degree_add_eq_left_of_degree_lt], convert degree_C_le.trans_lt (with_bot.coe_lt_coe.mpr (nat.zero_lt_bit1 2)) }, rw degree_sub_eq_left_of_degree_lt; rw degree_X_pow, exact (degree_C_mul_X_le _).trans_lt (with_bot.coe_lt_coe.mpr (nat.one_lt_bit1 two_ne_zero)), end lemma nat_degree_Phi : (Φ R a b).nat_degree = 5 := nat_degree_eq_of_degree_eq_some (degree_Phi a b) lemma leading_coeff_Phi : (Φ R a b).leading_coeff = 1 := by rw [polynomial.leading_coeff, nat_degree_Phi, coeff_five_Phi] lemma monic_Phi : (Φ R a b).monic := leading_coeff_Phi a b lemma irreducible_Phi (p : ℕ) (hp : p.prime) (hpa : p ∣ a) (hpb : p ∣ b) (hp2b : ¬ p ^ 2 ∣ b) : irreducible (Φ ℚ a b) := begin rw [←map_Phi a b (int.cast_ring_hom ℚ), ←is_primitive.int.irreducible_iff_irreducible_map_cast], apply irreducible_of_eisenstein_criterion, { rwa [span_singleton_prime (int.coe_nat_ne_zero.mpr hp.ne_zero), int.prime_iff_nat_abs_prime] }, { rw [leading_coeff_Phi, mem_span_singleton], exact_mod_cast mt nat.dvd_one.mp (hp.ne_one) }, { intros n hn, rw mem_span_singleton, rw [degree_Phi, with_bot.coe_lt_coe] at hn, interval_cases n with hn; simp only [Φ, coeff_X_pow, coeff_C, int.coe_nat_dvd.mpr, hpb, if_true, coeff_C_mul, if_false, nat.zero_ne_bit1, eq_self_iff_true, coeff_X_zero, hpa, coeff_add, zero_add, mul_zero, coeff_sub, sub_self, nat.one_ne_zero, add_zero, coeff_X_one, mul_one, zero_sub, dvd_neg, nat.one_eq_bit1, bit0_eq_zero, neg_zero, nat.bit0_ne_bit1, dvd_mul_of_dvd_left, nat.bit1_eq_bit1, nat.one_ne_bit0, nat.bit1_ne_zero], }, { simp only [degree_Phi, ←with_bot.coe_zero, with_bot.coe_lt_coe, nat.succ_pos'] }, { rw [coeff_zero_Phi, span_singleton_pow, mem_span_singleton], exact mt int.coe_nat_dvd.mp hp2b }, all_goals { exact monic.is_primitive (monic_Phi a b) }, end lemma real_roots_Phi_le : fintype.card ((Φ ℚ a b).root_set ℝ) ≤ 3 := begin rw [←map_Phi a b (algebra_map ℤ ℚ), Φ, ←one_mul (X ^ 5), ←C_1], refine (card_root_set_le_derivative _).trans (nat.succ_le_succ ((card_root_set_le_derivative _).trans (nat.succ_le_succ _))), suffices : ((C ((algebra_map ℤ ℚ) 20) * X ^ 3).root_set ℝ).subsingleton, { norm_num [fintype.card_le_one_iff_subsingleton, ← mul_assoc, *] at * }, rw root_set_C_mul_X_pow; norm_num, end lemma real_roots_Phi_ge_aux (hab : b < a) : ∃ x y : ℝ, x ≠ y ∧ aeval x (Φ ℚ a b) = 0 ∧ aeval y (Φ ℚ a b) = 0 := begin let f := λ x : ℝ, aeval x (Φ ℚ a b), have hf : f = λ x, x ^ 5 - a * x + b := by simp [f, Φ], have hc : ∀ s : set ℝ, continuous_on f s := λ s, (Φ ℚ a b).continuous_on_aeval, have ha : (1 : ℝ) ≤ a := nat.one_le_cast.mpr (nat.one_le_of_lt hab), have hle : (0 : ℝ) ≤ 1 := zero_le_one, have hf0 : 0 ≤ f 0 := by norm_num [hf], by_cases hb : (1 : ℝ) - a + b < 0, { have hf1 : f 1 < 0 := by norm_num [hf, hb], have hfa : 0 ≤ f a, { simp_rw [hf, ←sq], refine add_nonneg (sub_nonneg.mpr (pow_le_pow ha _)) _; norm_num }, obtain ⟨x, ⟨-, hx1⟩, hx2⟩ := intermediate_value_Ico' hle (hc _) (set.mem_Ioc.mpr ⟨hf1, hf0⟩), obtain ⟨y, ⟨hy1, -⟩, hy2⟩ := intermediate_value_Ioc ha (hc _) (set.mem_Ioc.mpr ⟨hf1, hfa⟩), exact ⟨x, y, (hx1.trans hy1).ne, hx2, hy2⟩ }, { replace hb : (b : ℝ) = a - 1 := by linarith [show (b : ℝ) + 1 ≤ a, by exact_mod_cast hab], have hf1 : f 1 = 0 := by norm_num [hf, hb], have hfa := calc f (-a) = a ^ 2 - a ^ 5 + b : by norm_num [hf, ← sq] ... ≤ a ^ 2 - a ^ 3 + (a - 1) : by refine add_le_add (sub_le_sub_left (pow_le_pow ha _) _) _; linarith ... = -(a - 1) ^ 2 * (a + 1) : by ring ... ≤ 0 : by nlinarith, have ha' := neg_nonpos.mpr (hle.trans ha), obtain ⟨x, ⟨-, hx1⟩, hx2⟩ := intermediate_value_Icc ha' (hc _) (set.mem_Icc.mpr ⟨hfa, hf0⟩), exact ⟨x, 1, (hx1.trans_lt zero_lt_one).ne, hx2, hf1⟩ }, end lemma real_roots_Phi_ge (hab : b < a) : 2 ≤ fintype.card ((Φ ℚ a b).root_set ℝ) := begin have q_ne_zero : Φ ℚ a b ≠ 0 := (monic_Phi a b).ne_zero, obtain ⟨x, y, hxy, hx, hy⟩ := real_roots_Phi_ge_aux a b hab, have key : ↑({x, y} : finset ℝ) ⊆ (Φ ℚ a b).root_set ℝ, { simp [set.insert_subset, mem_root_set_of_ne q_ne_zero, hx, hy] }, convert fintype.card_le_of_embedding (set.embedding_of_subset _ _ key), simp only [finset.coe_sort_coe, fintype.card_coe, finset.card_singleton, finset.card_insert_of_not_mem (mt finset.mem_singleton.mp hxy)] end lemma complex_roots_Phi (h : (Φ ℚ a b).separable) : fintype.card ((Φ ℚ a b).root_set ℂ) = 5 := (card_root_set_eq_nat_degree h (is_alg_closed.splits_codomain _)).trans (nat_degree_Phi a b) lemma gal_Phi (hab : b < a) (h_irred : irreducible (Φ ℚ a b)) : bijective (gal_action_hom (Φ ℚ a b) ℂ) := begin apply gal_action_hom_bijective_of_prime_degree' h_irred, { norm_num [nat_degree_Phi] }, { rw [complex_roots_Phi a b h_irred.separable, nat.succ_le_succ_iff], exact (real_roots_Phi_le a b).trans (nat.le_succ 3) }, { simp_rw [complex_roots_Phi a b h_irred.separable, nat.succ_le_succ_iff], exact real_roots_Phi_ge a b hab }, end theorem not_solvable_by_rad (p : ℕ) (x : ℂ) (hx : aeval x (Φ ℚ a b) = 0) (hab : b < a) (hp : p.prime) (hpa : p ∣ a) (hpb : p ∣ b) (hp2b : ¬ p ^ 2 ∣ b) : ¬ is_solvable_by_rad ℚ x := begin have h_irred := irreducible_Phi a b p hp hpa hpb hp2b, apply mt (solvable_by_rad.is_solvable' h_irred hx), introI h, refine equiv.perm.not_solvable _ (le_of_eq _) (solvable_of_surjective (gal_Phi a b hab h_irred).2), rw_mod_cast [cardinal.mk_fintype, complex_roots_Phi a b h_irred.separable], end theorem not_solvable_by_rad' (x : ℂ) (hx : aeval x (Φ ℚ 4 2) = 0) : ¬ is_solvable_by_rad ℚ x := by apply not_solvable_by_rad 4 2 2 x hx; norm_num /-- **Abel-Ruffini Theorem** -/ theorem exists_not_solvable_by_rad : ∃ x : ℂ, is_algebraic ℚ x ∧ ¬ is_solvable_by_rad ℚ x := begin obtain ⟨x, hx⟩ := exists_root_of_splits (algebra_map ℚ ℂ) (is_alg_closed.splits_codomain (Φ ℚ 4 2)) (ne_of_eq_of_ne (degree_Phi 4 2) (mt with_bot.coe_eq_coe.mp (nat.bit1_ne_zero 2))), exact ⟨x, ⟨Φ ℚ 4 2, (monic_Phi 4 2).ne_zero, hx⟩, not_solvable_by_rad' x hx⟩, end end abel_ruffini
17a39cc39a491f11351ecae057fb0c383cc4c628
9028d228ac200bbefe3a711342514dd4e4458bff
/src/order/pilex.lean
9e9076ab15e8ea37a524d0fcf6477adf77006f20
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,318
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import algebra.group.pi import order.well_founded import algebra.order_functions variables {ι : Type*} {β : ι → Type*} (r : ι → ι → Prop) (s : Π {i}, β i → β i → Prop) /-- The lexicographic relation on `Π i : ι, β i`, where `ι` is ordered by `r`, and each `β i` is ordered by `s`. -/ def pi.lex (x y : Π i, β i) : Prop := ∃ i, (∀ j, r j i → x j = y j) ∧ s (x i) (y i) /-- The cartesian product of an indexed family, equipped with the lexicographic order. -/ def pilex (α : Type*) (β : α → Type*) : Type* := Π a, β a instance [has_lt ι] [∀ a, has_lt (β a)] : has_lt (pilex ι β) := { lt := pi.lex (<) (λ _, (<)) } instance [∀ a, inhabited (β a)] : inhabited (pilex ι β) := by unfold pilex; apply_instance set_option eqn_compiler.zeta true instance [linear_order ι] [∀ a, partial_order (β a)] : partial_order (pilex ι β) := let I := classical.DLO ι in have lt_not_symm : ∀ {x y : pilex ι β}, ¬ (x < y ∧ y < x), from λ x y ⟨⟨i, hi⟩, ⟨j, hj⟩⟩, begin rcases lt_trichotomy i j with hij | hij | hji, { exact lt_irrefl (x i) (by simpa [hj.1 _ hij] using hi.2) }, { exact not_le_of_gt hj.2 (hij ▸ le_of_lt hi.2) }, { exact lt_irrefl (x j) (by simpa [hi.1 _ hji] using hj.2) }, end, { le := λ x y, x < y ∨ x = y, le_refl := λ _, or.inr rfl, le_antisymm := λ x y hxy hyx, hxy.elim (λ hxy, hyx.elim (λ hyx, false.elim (lt_not_symm ⟨hxy, hyx⟩)) eq.symm) id, le_trans := λ x y z hxy hyz, hxy.elim (λ ⟨i, hi⟩, hyz.elim (λ ⟨j, hj⟩, or.inl ⟨by exactI min i j, by resetI; exact λ k hk, by rw [hi.1 _ (lt_min_iff.1 hk).1, hj.1 _ (lt_min_iff.1 hk).2], by resetI; exact (le_total i j).elim (λ hij, by rw [min_eq_left hij]; exact lt_of_lt_of_le hi.2 ((lt_or_eq_of_le hij).elim (λ h, le_of_eq (hj.1 _ h)) (λ h, h.symm ▸ le_of_lt hj.2))) (λ hji, by rw [min_eq_right hji]; exact lt_of_le_of_lt ((lt_or_eq_of_le hji).elim (λ h, le_of_eq (hi.1 _ h)) (λ h, h.symm ▸ le_of_lt hi.2)) hj.2)⟩) (λ hyz, hyz ▸ hxy)) (λ hxy, hxy.symm ▸ hyz), lt_iff_le_not_le := λ x y, show x < y ↔ (x < y ∨ x = y) ∧ ¬ (y < x ∨ y = x), from ⟨λ ⟨i, hi⟩, ⟨or.inl ⟨i, hi⟩, λ h, h.elim (λ ⟨j, hj⟩, begin rcases lt_trichotomy i j with hij | hij | hji, { exact lt_irrefl (x i) (by simpa [hj.1 _ hij] using hi.2) }, { exact not_le_of_gt hj.2 (hij ▸ le_of_lt hi.2) }, { exact lt_irrefl (x j) (by simpa [hi.1 _ hji] using hj.2) }, end) (λ hyx, lt_irrefl (x i) (by simpa [hyx] using hi.2))⟩, by tauto⟩, ..pilex.has_lt } /-- `pilex` is a linear order if the original order is well-founded. This cannot be an instance, since it depends on the well-foundedness of `<`. -/ protected def pilex.linear_order [linear_order ι] (wf : well_founded ((<) : ι → ι → Prop)) [∀ a, linear_order (β a)] : linear_order (pilex ι β) := { le_total := λ x y, by classical; exact or_iff_not_imp_left.2 (λ hxy, begin have := not_or_distrib.1 hxy, let i : ι := well_founded.min wf _ (not_forall.1 (this.2 ∘ funext)), have hjiyx : ∀ j < i, y j = x j, { assume j, rw [eq_comm, ← not_imp_not], exact λ h, well_founded.not_lt_min wf _ _ h }, refine or.inl ⟨i, hjiyx, _⟩, { refine lt_of_not_ge (λ hyx, _), exact this.1 ⟨i, (λ j hj, (hjiyx j hj).symm), lt_of_le_of_ne hyx (well_founded.min_mem _ {i | x i ≠ y i} _)⟩ } end), ..pilex.partial_order } instance [linear_order ι] [∀ a, ordered_add_comm_group (β a)] : ordered_add_comm_group (pilex ι β) := { add_le_add_left := λ x y hxy z, hxy.elim (λ ⟨i, hi⟩, or.inl ⟨i, λ j hji, show z j + x j = z j + y j, by rw [hi.1 j hji], add_lt_add_left hi.2 _⟩) (λ hxy, hxy ▸ le_refl _), ..pilex.partial_order, ..pi.add_comm_group }
210731d66087c0e32c94a7e693887194094bba2f
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/data/complex/exponential.lean
f3da3f0bd43019ed353211f51bd21b9aae2fd83e
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
49,859
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir -/ import algebra.geom_sum import data.nat.choose import data.complex.basic /-! # Exponential, trigonometric and hyperbolic trigonometric functions This file containss the definitions of the real and complex exponential, sine, cosine, tangent, hyperbolic sine, hypebolic cosine, and hyperbolic tangent functions. -/ local notation `abs'` := _root_.abs open is_absolute_value open_locale classical big_operators section open real is_absolute_value finset lemma forall_ge_le_of_forall_le_succ {α : Type*} [preorder α] (f : ℕ → α) {m : ℕ} (h : ∀ n ≥ m, f n.succ ≤ f n) : ∀ {l}, ∀ k ≥ m, k ≤ l → f l ≤ f k := begin assume l k hkm hkl, generalize hp : l - k = p, have : l = k + p := add_comm p k ▸ (nat.sub_eq_iff_eq_add hkl).1 hp, subst this, clear hkl hp, induction p with p ih, { simp }, { exact le_trans (h _ (le_trans hkm (nat.le_add_right _ _))) ih } end section variables {α : Type*} {β : Type*} [ring β] [discrete_linear_ordered_field α] [archimedean α] {abv : β → α} [is_absolute_value abv] lemma is_cau_of_decreasing_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, abs (f n) ≤ a) (hnm : ∀ n ≥ m, f n.succ ≤ f n) : is_cau_seq abs f := λ ε ε0, let ⟨k, hk⟩ := archimedean.arch a ε0 in have h : ∃ l, ∀ n ≥ m, a - l •ℕ ε < f n := ⟨k + k + 1, λ n hnm, lt_of_lt_of_le (show a - (k + (k + 1)) •ℕ ε < -abs (f n), from lt_neg.1 $ lt_of_le_of_lt (ham n hnm) (begin rw [neg_sub, lt_sub_iff_add_lt, add_nsmul], exact add_lt_add_of_le_of_lt hk (lt_of_le_of_lt hk (lt_add_of_pos_left _ ε0)), end)) (neg_le.2 $ (abs_neg (f n)) ▸ le_abs_self _)⟩, let l := nat.find h in have hl : ∀ (n : ℕ), n ≥ m → f n > a - l •ℕ ε := nat.find_spec h, have hl0 : l ≠ 0 := λ hl0, not_lt_of_ge (ham m (le_refl _)) (lt_of_lt_of_le (by have := hl m (le_refl m); simpa [hl0] using this) (le_abs_self (f m))), begin cases classical.not_forall.1 (nat.find_min h (nat.pred_lt hl0)) with i hi, rw [not_imp, not_lt] at hi, existsi i, assume j hj, have hfij : f j ≤ f i := forall_ge_le_of_forall_le_succ f hnm _ hi.1 hj, rw [abs_of_nonpos (sub_nonpos.2 hfij), neg_sub, sub_lt_iff_lt_add'], exact calc f i ≤ a - (nat.pred l) •ℕ ε : hi.2 ... = a - l •ℕ ε + ε : by conv {to_rhs, rw [← nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero hl0), succ_nsmul', sub_add, add_sub_cancel] } ... < f j + ε : add_lt_add_right (hl j (le_trans hi.1 hj)) _ end lemma is_cau_of_mono_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, abs (f n) ≤ a) (hnm : ∀ n ≥ m, f n ≤ f n.succ) : is_cau_seq abs f := begin refine @eq.rec_on (ℕ → α) _ (is_cau_seq abs) _ _ (-⟨_, @is_cau_of_decreasing_bounded _ _ _ (λ n, -f n) a m (by simpa) (by simpa)⟩ : cau_seq α abs).2, ext, exact neg_neg _ end end section no_archimedean variables {α : Type*} {β : Type*} [ring β] [discrete_linear_ordered_field α] {abv : β → α} [is_absolute_value abv] lemma is_cau_series_of_abv_le_cau {f : ℕ → β} {g : ℕ → α} (n : ℕ) : (∀ m, n ≤ m → abv (f m) ≤ g m) → is_cau_seq abs (λ n, ∑ i in range n, g i) → is_cau_seq abv (λ n, ∑ i in range n, f i) := begin assume hm hg ε ε0, cases hg (ε / 2) (div_pos ε0 (by norm_num)) with i hi, existsi max n i, assume j ji, have hi₁ := hi j (le_trans (le_max_right n i) ji), have hi₂ := hi (max n i) (le_max_right n i), have sub_le := abs_sub_le (∑ k in range j, g k) (∑ k in range i, g k) (∑ k in range (max n i), g k), have := add_lt_add hi₁ hi₂, rw [abs_sub (∑ k in range (max n i), g k), add_halves ε] at this, refine lt_of_le_of_lt (le_trans (le_trans _ (le_abs_self _)) sub_le) this, generalize hk : j - max n i = k, clear this hi₂ hi₁ hi ε0 ε hg sub_le, rw nat.sub_eq_iff_eq_add ji at hk, rw hk, clear hk ji j, induction k with k' hi, { simp [abv_zero abv] }, { dsimp at *, simp only [nat.succ_add, sum_range_succ, sub_eq_add_neg, add_assoc], refine le_trans (abv_add _ _ _) _, exact add_le_add (hm _ (le_add_of_nonneg_of_le (nat.zero_le _) (le_max_left _ _))) hi }, end lemma is_cau_series_of_abv_cau {f : ℕ → β} : is_cau_seq abs (λ m, ∑ n in range m, abv (f n)) → is_cau_seq abv (λ m, ∑ n in range m, f n) := is_cau_series_of_abv_le_cau 0 (λ n h, le_refl _) end no_archimedean section variables {α : Type*} {β : Type*} [ring β] [discrete_linear_ordered_field α] [archimedean α] {abv : β → α} [is_absolute_value abv] lemma is_cau_geo_series {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] (x : β) (hx1 : abv x < 1) : is_cau_seq abv (λ n, ∑ m in range n, x ^ m) := have hx1' : abv x ≠ 1 := λ h, by simpa [h, lt_irrefl] using hx1, is_cau_series_of_abv_cau begin simp only [abv_pow abv] {eta := ff}, have : (λ (m : ℕ), ∑ n in range m, (abv x) ^ n) = λ m, geom_series (abv x) m := rfl, simp only [this, geom_sum hx1'] {eta := ff}, conv in (_ / _) { rw [← neg_div_neg_eq, neg_sub, neg_sub] }, refine @is_cau_of_mono_bounded _ _ _ _ ((1 : α) / (1 - abv x)) 0 _ _, { assume n hn, rw abs_of_nonneg, refine div_le_div_of_le_of_pos (sub_le_self _ (abv_pow abv x n ▸ abv_nonneg _ _)) (sub_pos.2 hx1), refine div_nonneg (sub_nonneg.2 _) (sub_pos.2 hx1), clear hn, induction n with n ih, { simp }, { rw [pow_succ, ← one_mul (1 : α)], refine mul_le_mul (le_of_lt hx1) ih (abv_pow abv x n ▸ abv_nonneg _ _) (by norm_num) } }, { assume n hn, refine div_le_div_of_le_of_pos (sub_le_sub_left _ _) (sub_pos.2 hx1), rw [← one_mul (_ ^ n), pow_succ], exact mul_le_mul_of_nonneg_right (le_of_lt hx1) (pow_nonneg (abv_nonneg _ _) _) } end lemma is_cau_geo_series_const (a : α) {x : α} (hx1 : abs x < 1) : is_cau_seq abs (λ m, ∑ n in range m, a * x ^ n) := have is_cau_seq abs (λ m, a * ∑ n in range m, x ^ n) := (cau_seq.const abs a * ⟨_, is_cau_geo_series x hx1⟩).2, by simpa only [mul_sum] lemma series_ratio_test {f : ℕ → β} (n : ℕ) (r : α) (hr0 : 0 ≤ r) (hr1 : r < 1) (h : ∀ m, n ≤ m → abv (f m.succ) ≤ r * abv (f m)) : is_cau_seq abv (λ m, ∑ n in range m, f n) := have har1 : abs r < 1, by rwa abs_of_nonneg hr0, begin refine is_cau_series_of_abv_le_cau n.succ _ (is_cau_geo_series_const (abv (f n.succ) * r⁻¹ ^ n.succ) har1), assume m hmn, cases classical.em (r = 0) with r_zero r_ne_zero, { have m_pos := lt_of_lt_of_le (nat.succ_pos n) hmn, have := h m.pred (nat.le_of_succ_le_succ (by rwa [nat.succ_pred_eq_of_pos m_pos])), simpa [r_zero, nat.succ_pred_eq_of_pos m_pos, pow_succ] }, generalize hk : m - n.succ = k, have r_pos : 0 < r := lt_of_le_of_ne hr0 (ne.symm r_ne_zero), replace hk : m = k + n.succ := (nat.sub_eq_iff_eq_add hmn).1 hk, induction k with k ih generalizing m n, { rw [hk, zero_add, mul_right_comm, inv_pow' _ _, ← div_eq_mul_inv, mul_div_cancel], exact (ne_of_lt (pow_pos r_pos _)).symm }, { have kn : k + n.succ ≥ n.succ, by rw ← zero_add n.succ; exact add_le_add (zero_le _) (by simp), rw [hk, nat.succ_add, pow_succ' r, ← mul_assoc], exact le_trans (by rw mul_comm; exact h _ (nat.le_of_succ_le kn)) (mul_le_mul_of_nonneg_right (ih (k + n.succ) n h kn rfl) hr0) } end lemma sum_range_diag_flip {α : Type*} [add_comm_monoid α] (n : ℕ) (f : ℕ → ℕ → α) : ∑ m in range n, ∑ k in range (m + 1), f k (m - k) = ∑ m in range n, ∑ k in range (n - m), f m k := have h₁ : ∑ a in (range n).sigma (range ∘ nat.succ), f (a.2) (a.1 - a.2) = ∑ m in range n, ∑ k in range (m + 1), f k (m - k) := sum_sigma, have h₂ : ∑ a in (range n).sigma (λ m, range (n - m)), f (a.1) (a.2) = ∑ m in range n, ∑ k in range (n - m), f m k := sum_sigma, h₁ ▸ h₂ ▸ sum_bij (λ a _, ⟨a.2, a.1 - a.2⟩) (λ a ha, have h₁ : a.1 < n := mem_range.1 (mem_sigma.1 ha).1, have h₂ : a.2 < nat.succ a.1 := mem_range.1 (mem_sigma.1 ha).2, mem_sigma.2 ⟨mem_range.2 (lt_of_lt_of_le h₂ h₁), mem_range.2 ((nat.sub_lt_sub_right_iff (nat.le_of_lt_succ h₂)).2 h₁)⟩) (λ _ _, rfl) (λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩ ha hb h, have ha : a₁ < n ∧ a₂ ≤ a₁ := ⟨mem_range.1 (mem_sigma.1 ha).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 ha).2)⟩, have hb : b₁ < n ∧ b₂ ≤ b₁ := ⟨mem_range.1 (mem_sigma.1 hb).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 hb).2)⟩, have h : a₂ = b₂ ∧ _ := sigma.mk.inj h, have h' : a₁ = b₁ - b₂ + a₂ := (nat.sub_eq_iff_eq_add ha.2).1 (eq_of_heq h.2), sigma.mk.inj_iff.2 ⟨nat.sub_add_cancel hb.2 ▸ h'.symm ▸ h.1 ▸ rfl, (heq_of_eq h.1)⟩) (λ ⟨a₁, a₂⟩ ha, have ha : a₁ < n ∧ a₂ < n - a₁ := ⟨mem_range.1 (mem_sigma.1 ha).1, (mem_range.1 (mem_sigma.1 ha).2)⟩, ⟨⟨a₂ + a₁, a₁⟩, ⟨mem_sigma.2 ⟨mem_range.2 (nat.lt_sub_right_iff_add_lt.1 ha.2), mem_range.2 (nat.lt_succ_of_le (nat.le_add_left _ _))⟩, sigma.mk.inj_iff.2 ⟨rfl, heq_of_eq (nat.add_sub_cancel _ _).symm⟩⟩⟩) lemma sum_range_sub_sum_range {α : Type*} [add_comm_group α] {f : ℕ → α} {n m : ℕ} (hnm : n ≤ m) : ∑ k in range m, f k - ∑ k in range n, f k = ∑ k in (range m).filter (λ k, n ≤ k), f k := begin rw [← sum_sdiff (@filter_subset _ (λ k, n ≤ k) _ (range m)), sub_eq_iff_eq_add, ← eq_sub_iff_add_eq, add_sub_cancel'], refine finset.sum_congr (finset.ext $ λ a, ⟨λ h, by simp at *; finish, λ h, have ham : a < m := lt_of_lt_of_le (mem_range.1 h) hnm, by simp * at *⟩) (λ _ _, rfl), end end section no_archimedean variables {α : Type*} {β : Type*} [ring β] [discrete_linear_ordered_field α] {abv : β → α} [is_absolute_value abv] lemma abv_sum_le_sum_abv {γ : Type*} (f : γ → β) (s : finset γ) : abv (∑ k in s, f k) ≤ ∑ k in s, abv (f k) := by haveI := classical.dec_eq γ; exact finset.induction_on s (by simp [abv_zero abv]) (λ a s has ih, by rw [sum_insert has, sum_insert has]; exact le_trans (abv_add abv _ _) (add_le_add_left ih _)) @[nolint ge_or_gt] -- see Note [nolint_ge] lemma cauchy_product {a b : ℕ → β} (ha : is_cau_seq abs (λ m, ∑ n in range m, abv (a n))) (hb : is_cau_seq abv (λ m, ∑ n in range m, b n)) (ε : α) (ε0 : 0 < ε) : ∃ i : ℕ, ∀ j ≥ i, abv ((∑ k in range j, a k) * (∑ k in range j, b k) - ∑ n in range j, ∑ m in range (n + 1), a m * b (n - m)) < ε := let ⟨Q, hQ⟩ := cau_seq.bounded ⟨_, hb⟩ in let ⟨P, hP⟩ := cau_seq.bounded ⟨_, ha⟩ in have hP0 : 0 < P, from lt_of_le_of_lt (abs_nonneg _) (hP 0), have hPε0 : 0 < ε / (2 * P), from div_pos ε0 (mul_pos (show (2 : α) > 0, from by norm_num) hP0), let ⟨N, hN⟩ := cau_seq.cauchy₂ ⟨_, hb⟩ hPε0 in have hQε0 : 0 < ε / (4 * Q), from div_pos ε0 (mul_pos (show (0 : α) < 4, by norm_num) (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))), let ⟨M, hM⟩ := cau_seq.cauchy₂ ⟨_, ha⟩ hQε0 in ⟨2 * (max N M + 1), λ K hK, have h₁ : ∑ m in range K, ∑ k in range (m + 1), a k * b (m - k) = ∑ m in range K, ∑ n in range (K - m), a m * b n, by simpa using sum_range_diag_flip K (λ m n, a m * b n), have h₂ : (λ i, ∑ k in range (K - i), a i * b k) = (λ i, a i * ∑ k in range (K - i), b k), by simp [finset.mul_sum], have h₃ : ∑ i in range K, a i * ∑ k in range (K - i), b k = ∑ i in range K, a i * (∑ k in range (K - i), b k - ∑ k in range K, b k) + ∑ i in range K, a i * ∑ k in range K, b k, by rw ← sum_add_distrib; simp [(mul_add _ _ _).symm], have two_mul_two : (4 : α) = 2 * 2, by norm_num, have hQ0 : Q ≠ 0, from λ h, by simpa [h, lt_irrefl] using hQε0, have h2Q0 : 2 * Q ≠ 0, from mul_ne_zero two_ne_zero hQ0, have hε : ε / (2 * P) * P + ε / (4 * Q) * (2 * Q) = ε, by rw [← div_div_eq_div_mul, div_mul_cancel _ (ne.symm (ne_of_lt hP0)), two_mul_two, mul_assoc, ← div_div_eq_div_mul, div_mul_cancel _ h2Q0, add_halves], have hNMK : max N M + 1 < K, from lt_of_lt_of_le (by rw two_mul; exact lt_add_of_pos_left _ (nat.succ_pos _)) hK, have hKN : N < K, from calc N ≤ max N M : le_max_left _ _ ... < max N M + 1 : nat.lt_succ_self _ ... < K : hNMK, have hsumlesum : ∑ i in range (max N M + 1), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) ≤ ∑ i in range (max N M + 1), abv (a i) * (ε / (2 * P)), from sum_le_sum (λ m hmJ, mul_le_mul_of_nonneg_left (le_of_lt (hN (K - m) K (nat.le_sub_left_of_add_le (le_trans (by rw two_mul; exact add_le_add (le_of_lt (mem_range.1 hmJ)) (le_trans (le_max_left _ _) (le_of_lt (lt_add_one _)))) hK)) (le_of_lt hKN))) (abv_nonneg abv _)), have hsumltP : ∑ n in range (max N M + 1), abv (a n) < P := calc ∑ n in range (max N M + 1), abv (a n) = abs (∑ n in range (max N M + 1), abv (a n)) : eq.symm (abs_of_nonneg (sum_nonneg (λ x h, abv_nonneg abv (a x)))) ... < P : hP (max N M + 1), begin rw [h₁, h₂, h₃, sum_mul, ← sub_sub, sub_right_comm, sub_self, zero_sub, abv_neg abv], refine lt_of_le_of_lt (abv_sum_le_sum_abv _ _) _, suffices : ∑ i in range (max N M + 1), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) + (∑ i in range K, abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) - ∑ i in range (max N M + 1), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k)) < ε / (2 * P) * P + ε / (4 * Q) * (2 * Q), { rw hε at this, simpa [abv_mul abv] }, refine add_lt_add (lt_of_le_of_lt hsumlesum (by rw [← sum_mul, mul_comm]; exact (mul_lt_mul_left hPε0).mpr hsumltP)) _, rw sum_range_sub_sum_range (le_of_lt hNMK), exact calc ∑ i in (range K).filter (λ k, max N M + 1 ≤ k), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) ≤ ∑ i in (range K).filter (λ k, max N M + 1 ≤ k), abv (a i) * (2 * Q) : sum_le_sum (λ n hn, begin refine mul_le_mul_of_nonneg_left _ (abv_nonneg _ _), rw sub_eq_add_neg, refine le_trans (abv_add _ _ _) _, rw [two_mul, abv_neg abv], exact add_le_add (le_of_lt (hQ _)) (le_of_lt (hQ _)), end) ... < ε / (4 * Q) * (2 * Q) : by rw [← sum_mul, ← sum_range_sub_sum_range (le_of_lt hNMK)]; refine (mul_lt_mul_right $ by rw two_mul; exact add_pos (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0)) (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))).2 (lt_of_le_of_lt (le_abs_self _) (hM _ _ (le_trans (nat.le_succ_of_le (le_max_right _ _)) (le_of_lt hNMK)) (nat.le_succ_of_le (le_max_right _ _)))) end⟩ end no_archimedean end open finset open cau_seq namespace complex lemma is_cau_abs_exp (z : ℂ) : is_cau_seq _root_.abs (λ n, ∑ m in range n, abs (z ^ m / nat.fact m)) := let ⟨n, hn⟩ := exists_nat_gt (abs z) in have hn0 : (0 : ℝ) < n, from lt_of_le_of_lt (abs_nonneg _) hn, series_ratio_test n (complex.abs z / n) (div_nonneg_of_nonneg_of_pos (complex.abs_nonneg _) hn0) (by rwa [div_lt_iff hn0, one_mul]) (λ m hm, by rw [abs_abs, abs_abs, nat.fact_succ, pow_succ, mul_comm m.succ, nat.cast_mul, ← div_div_eq_div_mul, mul_div_assoc, mul_div_right_comm, abs_mul, abs_div, abs_cast_nat]; exact mul_le_mul_of_nonneg_right (div_le_div_of_le_left (abs_nonneg _) hn0 (nat.cast_le.2 (le_trans hm (nat.le_succ _)))) (abs_nonneg _)) noncomputable theory lemma is_cau_exp (z : ℂ) : is_cau_seq abs (λ n, ∑ m in range n, z ^ m / nat.fact m) := is_cau_series_of_abv_cau (is_cau_abs_exp z) /-- The Cauchy sequence consisting of partial sums of the Taylor series of the complex exponential function -/ @[pp_nodot] def exp' (z : ℂ) : cau_seq ℂ complex.abs := ⟨λ n, ∑ m in range n, z ^ m / nat.fact m, is_cau_exp z⟩ /-- The complex exponential function, defined via its Taylor series -/ @[pp_nodot] def exp (z : ℂ) : ℂ := lim (exp' z) /-- The complex sine function, defined via `exp` -/ @[pp_nodot] def sin (z : ℂ) : ℂ := ((exp (-z * I) - exp (z * I)) * I) / 2 /-- The complex cosine function, defined via `exp` -/ @[pp_nodot] def cos (z : ℂ) : ℂ := (exp (z * I) + exp (-z * I)) / 2 /-- The complex tangent function, defined as `sin z / cos z` -/ @[pp_nodot] def tan (z : ℂ) : ℂ := sin z / cos z /-- The complex hyperbolic sine function, defined via `exp` -/ @[pp_nodot] def sinh (z : ℂ) : ℂ := (exp z - exp (-z)) / 2 /-- The complex hyperbolic cosine function, defined via `exp` -/ @[pp_nodot] def cosh (z : ℂ) : ℂ := (exp z + exp (-z)) / 2 /-- The complex hyperbolic tangent function, defined as `sinh z / cosh z` -/ @[pp_nodot] def tanh (z : ℂ) : ℂ := sinh z / cosh z end complex namespace real open complex /-- The real exponential function, defined as the real part of the complex exponential -/ @[pp_nodot] def exp (x : ℝ) : ℝ := (exp x).re /-- The real sine function, defined as the real part of the complex sine -/ @[pp_nodot] def sin (x : ℝ) : ℝ := (sin x).re /-- The real cosine function, defined as the real part of the complex cosine -/ @[pp_nodot] def cos (x : ℝ) : ℝ := (cos x).re /-- The real tangent function, defined as the real part of the complex tangent -/ @[pp_nodot] def tan (x : ℝ) : ℝ := (tan x).re /-- The real hypebolic sine function, defined as the real part of the complex hyperbolic sine -/ @[pp_nodot] def sinh (x : ℝ) : ℝ := (sinh x).re /-- The real hypebolic cosine function, defined as the real part of the complex hyperbolic cosine -/ @[pp_nodot] def cosh (x : ℝ) : ℝ := (cosh x).re /-- The real hypebolic tangent function, defined as the real part of the complex hyperbolic tangent -/ @[pp_nodot] def tanh (x : ℝ) : ℝ := (tanh x).re end real namespace complex variables (x y : ℂ) @[simp] lemma exp_zero : exp 0 = 1 := lim_eq_of_equiv_const $ λ ε ε0, ⟨1, λ j hj, begin convert ε0, cases j, { exact absurd hj (not_le_of_gt zero_lt_one) }, { dsimp [exp'], induction j with j ih, { dsimp [exp']; simp }, { rw ← ih dec_trivial, simp only [sum_range_succ, pow_succ], simp } } end⟩ lemma exp_add : exp (x + y) = exp x * exp y := show lim (⟨_, is_cau_exp (x + y)⟩ : cau_seq ℂ abs) = lim (show cau_seq ℂ abs, from ⟨_, is_cau_exp x⟩) * lim (show cau_seq ℂ abs, from ⟨_, is_cau_exp y⟩), from have hj : ∀ j : ℕ, ∑ m in range j, (x + y) ^ m / m.fact = ∑ i in range j, ∑ k in range (i + 1), x ^ k / k.fact * (y ^ (i - k) / (i - k).fact), from assume j, finset.sum_congr rfl (λ m hm, begin rw [add_pow, div_eq_mul_inv, sum_mul], refine finset.sum_congr rfl (λ i hi, _), have h₁ : (m.choose i : ℂ) ≠ 0 := nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 (nat.choose_pos (nat.le_of_lt_succ (mem_range.1 hi)))), have h₂ := nat.choose_mul_fact_mul_fact (nat.le_of_lt_succ $ finset.mem_range.1 hi), rw [← h₂, nat.cast_mul, nat.cast_mul, mul_inv', mul_inv'], simp only [mul_left_comm (m.choose i : ℂ), mul_assoc, mul_left_comm (m.choose i : ℂ)⁻¹, mul_comm (m.choose i : ℂ)], rw inv_mul_cancel h₁, simp [div_eq_mul_inv, mul_comm, mul_assoc, mul_left_comm] end), by rw lim_mul_lim; exact eq.symm (lim_eq_lim_of_equiv (by dsimp; simp only [hj]; exact cauchy_product (is_cau_abs_exp x) (is_cau_exp y))) attribute [irreducible] complex.exp lemma exp_list_sum (l : list ℂ) : exp l.sum = (l.map exp).prod := @monoid_hom.map_list_prod (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ l lemma exp_multiset_sum (s : multiset ℂ) : exp s.sum = (s.map exp).prod := @monoid_hom.map_multiset_prod (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ s lemma exp_sum {α : Type*} (s : finset α) (f : α → ℂ) : exp (∑ x in s, f x) = ∏ x in s, exp (f x) := @monoid_hom.map_prod α (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ f s lemma exp_nat_mul (x : ℂ) : ∀ n : ℕ, exp(n*x) = (exp x)^n | 0 := by rw [nat.cast_zero, zero_mul, exp_zero, pow_zero] | (nat.succ n) := by rw [pow_succ', nat.cast_add_one, add_mul, exp_add, ←exp_nat_mul, one_mul] lemma exp_ne_zero : exp x ≠ 0 := λ h, zero_ne_one $ by rw [← exp_zero, ← add_neg_self x, exp_add, h]; simp lemma exp_neg : exp (-x) = (exp x)⁻¹ := by rw [← domain.mul_right_inj (exp_ne_zero x), ← exp_add]; simp [mul_inv_cancel (exp_ne_zero x)] lemma exp_sub : exp (x - y) = exp x / exp y := by simp [sub_eq_add_neg, exp_add, exp_neg, div_eq_mul_inv] @[simp] lemma exp_conj : exp (conj x) = conj (exp x) := begin dsimp [exp], rw [← lim_conj], refine congr_arg lim (cau_seq.ext (λ _, _)), dsimp [exp', function.comp, cau_seq_conj], rw ← sum_hom _ conj, refine sum_congr rfl (λ n hn, _), rw [conj.map_div, conj.map_pow, ← of_real_nat_cast, conj_of_real] end @[simp] lemma of_real_exp_of_real_re (x : ℝ) : ((exp x).re : ℂ) = exp x := eq_conj_iff_re.1 $ by rw [← exp_conj, conj_of_real] @[simp] lemma of_real_exp (x : ℝ) : (real.exp x : ℂ) = exp x := of_real_exp_of_real_re _ @[simp] lemma exp_of_real_im (x : ℝ) : (exp x).im = 0 := by rw [← of_real_exp_of_real_re, of_real_im] lemma exp_of_real_re (x : ℝ) : (exp x).re = real.exp x := rfl lemma two_sinh : 2 * sinh x = exp x - exp (-x) := mul_div_cancel' _ two_ne_zero' lemma two_cosh : 2 * cosh x = exp x + exp (-x) := mul_div_cancel' _ two_ne_zero' @[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh] @[simp] lemma sinh_neg : sinh (-x) = -sinh x := by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul] private lemma sinh_add_aux {a b c d : ℂ} : (a - b) * (c + d) + (a + b) * (c - d) = 2 * (a * c - b * d) := by ring lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y := begin rw [← domain.mul_right_inj (@two_ne_zero' ℂ _ _ _), two_sinh, exp_add, neg_add, exp_add, eq_comm, mul_add, ← mul_assoc, two_sinh, mul_left_comm, two_sinh, ← domain.mul_right_inj (@two_ne_zero' ℂ _ _ _), mul_add, mul_left_comm, two_cosh, ← mul_assoc, two_cosh], exact sinh_add_aux end @[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh] @[simp] lemma cosh_neg : cosh (-x) = cosh x := by simp [add_comm, cosh, exp_neg] private lemma cosh_add_aux {a b c d : ℂ} : (a + b) * (c + d) + (a - b) * (c - d) = 2 * (a * c + b * d) := by ring lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y := begin rw [← domain.mul_right_inj (@two_ne_zero' ℂ _ _ _), two_cosh, exp_add, neg_add, exp_add, eq_comm, mul_add, ← mul_assoc, two_cosh, ← mul_assoc, two_sinh, ← domain.mul_right_inj (@two_ne_zero' ℂ _ _ _), mul_add, mul_left_comm, two_cosh, mul_left_comm, two_sinh], exact cosh_add_aux end lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y := by simp [sub_eq_add_neg, sinh_add, sinh_neg, cosh_neg] lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y := by simp [sub_eq_add_neg, cosh_add, sinh_neg, cosh_neg] lemma sinh_conj : sinh (conj x) = conj (sinh x) := by rw [sinh, ← conj.map_neg, exp_conj, exp_conj, ← conj.map_sub, sinh, conj.map_div, conj_bit0, conj.map_one] @[simp] lemma of_real_sinh_of_real_re (x : ℝ) : ((sinh x).re : ℂ) = sinh x := eq_conj_iff_re.1 $ by rw [← sinh_conj, conj_of_real] @[simp] lemma of_real_sinh (x : ℝ) : (real.sinh x : ℂ) = sinh x := of_real_sinh_of_real_re _ @[simp] lemma sinh_of_real_im (x : ℝ) : (sinh x).im = 0 := by rw [← of_real_sinh_of_real_re, of_real_im] lemma sinh_of_real_re (x : ℝ) : (sinh x).re = real.sinh x := rfl lemma cosh_conj : cosh (conj x) = conj (cosh x) := begin rw [cosh, ← conj.map_neg, exp_conj, exp_conj, ← conj.map_add, cosh, conj.map_div, conj_bit0, conj.map_one] end @[simp] lemma of_real_cosh_of_real_re (x : ℝ) : ((cosh x).re : ℂ) = cosh x := eq_conj_iff_re.1 $ by rw [← cosh_conj, conj_of_real] @[simp] lemma of_real_cosh (x : ℝ) : (real.cosh x : ℂ) = cosh x := of_real_cosh_of_real_re _ @[simp] lemma cosh_of_real_im (x : ℝ) : (cosh x).im = 0 := by rw [← of_real_cosh_of_real_re, of_real_im] lemma cosh_of_real_re (x : ℝ) : (cosh x).re = real.cosh x := rfl lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x := rfl @[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh] @[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div] lemma tanh_conj : tanh (conj x) = conj (tanh x) := by rw [tanh, sinh_conj, cosh_conj, ← conj.map_div, tanh] @[simp] lemma of_real_tanh_of_real_re (x : ℝ) : ((tanh x).re : ℂ) = tanh x := eq_conj_iff_re.1 $ by rw [← tanh_conj, conj_of_real] @[simp] lemma of_real_tanh (x : ℝ) : (real.tanh x : ℂ) = tanh x := of_real_tanh_of_real_re _ @[simp] lemma tanh_of_real_im (x : ℝ) : (tanh x).im = 0 := by rw [← of_real_tanh_of_real_re, of_real_im] lemma tanh_of_real_re (x : ℝ) : (tanh x).re = real.tanh x := rfl lemma cosh_add_sinh : cosh x + sinh x = exp x := by rw [← domain.mul_right_inj (@two_ne_zero' ℂ _ _ _), mul_add, two_cosh, two_sinh, add_add_sub_cancel, two_mul] lemma sinh_add_cosh : sinh x + cosh x = exp x := by rw [add_comm, cosh_add_sinh] lemma cosh_sub_sinh : cosh x - sinh x = exp (-x) := by rw [← domain.mul_right_inj (@two_ne_zero' ℂ _ _ _), mul_sub, two_cosh, two_sinh, add_sub_sub_cancel, two_mul] lemma cosh_sq_sub_sinh_sq : cosh x ^ 2 - sinh x ^ 2 = 1 := by rw [sq_sub_sq, cosh_add_sinh, cosh_sub_sinh, ← exp_add, add_neg_self, exp_zero] @[simp] lemma sin_zero : sin 0 = 0 := by simp [sin] @[simp] lemma sin_neg : sin (-x) = -sin x := by simp [sin, sub_eq_add_neg, exp_neg, (neg_div _ _).symm, add_mul] lemma two_sin : 2 * sin x = (exp (-x * I) - exp (x * I)) * I := mul_div_cancel' _ two_ne_zero' lemma two_cos : 2 * cos x = exp (x * I) + exp (-x * I) := mul_div_cancel' _ two_ne_zero' lemma sinh_mul_I : sinh (x * I) = sin x * I := by rw [← domain.mul_right_inj (@two_ne_zero' ℂ _ _ _), two_sinh, ← mul_assoc, two_sin, mul_assoc, I_mul_I, mul_neg_one, neg_sub, neg_mul_eq_neg_mul] lemma cosh_mul_I : cosh (x * I) = cos x := by rw [← domain.mul_right_inj (@two_ne_zero' ℂ _ _ _), two_cosh, two_cos, neg_mul_eq_neg_mul] lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y := by rw [← domain.mul_left_inj I_ne_zero, ← sinh_mul_I, add_mul, add_mul, mul_right_comm, ← sinh_mul_I, mul_assoc, ← sinh_mul_I, ← cosh_mul_I, ← cosh_mul_I, sinh_add] @[simp] lemma cos_zero : cos 0 = 1 := by simp [cos] @[simp] lemma cos_neg : cos (-x) = cos x := by simp [cos, sub_eq_add_neg, exp_neg, add_comm] private lemma cos_add_aux {a b c d : ℂ} : (a + b) * (c + d) - (b - a) * (d - c) * (-1) = 2 * (a * c + b * d) := by ring lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y := by rw [← cosh_mul_I, add_mul, cosh_add, cosh_mul_I, cosh_mul_I, sinh_mul_I, sinh_mul_I, mul_mul_mul_comm, I_mul_I, mul_neg_one, sub_eq_add_neg] lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y := by simp [sub_eq_add_neg, sin_add, sin_neg, cos_neg] lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y := by simp [sub_eq_add_neg, cos_add, sin_neg, cos_neg] lemma sin_conj : sin (conj x) = conj (sin x) := by rw [← domain.mul_left_inj I_ne_zero, ← sinh_mul_I, ← conj_neg_I, ← conj.map_mul, ← conj.map_mul, sinh_conj, mul_neg_eq_neg_mul_symm, sinh_neg, sinh_mul_I, mul_neg_eq_neg_mul_symm] @[simp] lemma of_real_sin_of_real_re (x : ℝ) : ((sin x).re : ℂ) = sin x := eq_conj_iff_re.1 $ by rw [← sin_conj, conj_of_real] @[simp] lemma of_real_sin (x : ℝ) : (real.sin x : ℂ) = sin x := of_real_sin_of_real_re _ @[simp] lemma sin_of_real_im (x : ℝ) : (sin x).im = 0 := by rw [← of_real_sin_of_real_re, of_real_im] lemma sin_of_real_re (x : ℝ) : (sin x).re = real.sin x := rfl lemma cos_conj : cos (conj x) = conj (cos x) := by rw [← cosh_mul_I, ← conj_neg_I, ← conj.map_mul, ← cosh_mul_I, cosh_conj, mul_neg_eq_neg_mul_symm, cosh_neg] @[simp] lemma of_real_cos_of_real_re (x : ℝ) : ((cos x).re : ℂ) = cos x := eq_conj_iff_re.1 $ by rw [← cos_conj, conj_of_real] @[simp] lemma of_real_cos (x : ℝ) : (real.cos x : ℂ) = cos x := of_real_cos_of_real_re _ @[simp] lemma cos_of_real_im (x : ℝ) : (cos x).im = 0 := by rw [← of_real_cos_of_real_re, of_real_im] lemma cos_of_real_re (x : ℝ) : (cos x).re = real.cos x := rfl @[simp] lemma tan_zero : tan 0 = 0 := by simp [tan] lemma tan_eq_sin_div_cos : tan x = sin x / cos x := rfl @[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div] lemma tan_conj : tan (conj x) = conj (tan x) := by rw [tan, sin_conj, cos_conj, ← conj.map_div, tan] @[simp] lemma of_real_tan_of_real_re (x : ℝ) : ((tan x).re : ℂ) = tan x := eq_conj_iff_re.1 $ by rw [← tan_conj, conj_of_real] @[simp] lemma of_real_tan (x : ℝ) : (real.tan x : ℂ) = tan x := of_real_tan_of_real_re _ @[simp] lemma tan_of_real_im (x : ℝ) : (tan x).im = 0 := by rw [← of_real_tan_of_real_re, of_real_im] lemma tan_of_real_re (x : ℝ) : (tan x).re = real.tan x := rfl lemma cos_add_sin_I : cos x + sin x * I = exp (x * I) := by rw [← cosh_add_sinh, sinh_mul_I, cosh_mul_I] lemma cos_sub_sin_I : cos x - sin x * I = exp (-x * I) := by rw [← neg_mul_eq_neg_mul, ← cosh_sub_sinh, sinh_mul_I, cosh_mul_I] lemma sin_sq_add_cos_sq : sin x ^ 2 + cos x ^ 2 = 1 := eq.trans (by rw [cosh_mul_I, sinh_mul_I, mul_pow, I_sq, mul_neg_one, sub_neg_eq_add, add_comm]) (cosh_sq_sub_sinh_sq (x * I)) lemma cos_two_mul' : cos (2 * x) = cos x ^ 2 - sin x ^ 2 := by rw [two_mul, cos_add, ← pow_two, ← pow_two] lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 := by rw [cos_two_mul', eq_sub_iff_add_eq.2 (sin_sq_add_cos_sq x), ← sub_add, sub_add_eq_add_sub, two_mul] lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x := by rw [two_mul, sin_add, two_mul, add_mul, mul_comm] lemma cos_square : cos x ^ 2 = 1 / 2 + cos (2 * x) / 2 := by simp [cos_two_mul, div_add_div_same, mul_div_cancel_left, two_ne_zero', -one_div_eq_inv] lemma sin_square : sin x ^ 2 = 1 - cos x ^ 2 := by { rw [←sin_sq_add_cos_sq x], simp } lemma exp_mul_I : exp (x * I) = cos x + sin x * I := (cos_add_sin_I _).symm lemma exp_add_mul_I : exp (x + y * I) = exp x * (cos y + sin y * I) := by rw [exp_add, exp_mul_I] lemma exp_eq_exp_re_mul_sin_add_cos : exp x = exp x.re * (cos x.im + sin x.im * I) := by rw [← exp_add_mul_I, re_add_im] theorem cos_add_sin_mul_I_pow (n : ℕ) (z : ℂ) : (cos z + sin z * I) ^ n = cos (↑n * z) + sin (↑n * z) * I := begin rw [← exp_mul_I, ← exp_mul_I], induction n with n ih, { rw [pow_zero, nat.cast_zero, zero_mul, zero_mul, exp_zero] }, { rw [pow_succ', ih, nat.cast_succ, add_mul, add_mul, one_mul, exp_add] } end end complex namespace real open complex variables (x y : ℝ) @[simp] lemma exp_zero : exp 0 = 1 := by simp [real.exp] lemma exp_add : exp (x + y) = exp x * exp y := by simp [exp_add, exp] lemma exp_list_sum (l : list ℝ) : exp l.sum = (l.map exp).prod := @monoid_hom.map_list_prod (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ l lemma exp_multiset_sum (s : multiset ℝ) : exp s.sum = (s.map exp).prod := @monoid_hom.map_multiset_prod (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ s lemma exp_sum {α : Type*} (s : finset α) (f : α → ℝ) : exp (∑ x in s, f x) = ∏ x in s, exp (f x) := @monoid_hom.map_prod α (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ f s lemma exp_nat_mul (x : ℝ) : ∀ n : ℕ, exp(n*x) = (exp x)^n | 0 := by rw [nat.cast_zero, zero_mul, exp_zero, pow_zero] | (nat.succ n) := by rw [pow_succ', nat.cast_add_one, add_mul, exp_add, ←exp_nat_mul, one_mul] lemma exp_ne_zero : exp x ≠ 0 := λ h, exp_ne_zero x $ by rw [exp, ← of_real_inj] at h; simp * at * lemma exp_neg : exp (-x) = (exp x)⁻¹ := by rw [← of_real_inj, exp, of_real_exp_of_real_re, of_real_neg, exp_neg, of_real_inv, of_real_exp] lemma exp_sub : exp (x - y) = exp x / exp y := by simp [sub_eq_add_neg, exp_add, exp_neg, div_eq_mul_inv] @[simp] lemma sin_zero : sin 0 = 0 := by simp [sin] @[simp] lemma sin_neg : sin (-x) = -sin x := by simp [sin, exp_neg, (neg_div _ _).symm, add_mul] lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y := by rw [← of_real_inj]; simp [sin, sin_add] @[simp] lemma cos_zero : cos 0 = 1 := by simp [cos] @[simp] lemma cos_neg : cos (-x) = cos x := by simp [cos, exp_neg] lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y := by rw ← of_real_inj; simp [cos, cos_add] lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y := by simp [sub_eq_add_neg, sin_add, sin_neg, cos_neg] lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y := by simp [sub_eq_add_neg, cos_add, sin_neg, cos_neg] lemma tan_eq_sin_div_cos : tan x = sin x / cos x := if h : complex.cos x = 0 then by simp [sin, cos, tan, *, complex.tan, div_eq_mul_inv] at * else by rw [sin, cos, tan, complex.tan, ← of_real_inj, div_eq_mul_inv, mul_re]; simp [norm_sq, (div_div_eq_div_mul _ _ _).symm, div_self h]; refl @[simp] lemma tan_zero : tan 0 = 0 := by simp [tan] @[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div] lemma sin_sq_add_cos_sq : sin x ^ 2 + cos x ^ 2 = 1 := of_real_inj.1 $ by simpa using sin_sq_add_cos_sq x lemma sin_sq_le_one : sin x ^ 2 ≤ 1 := by rw ← sin_sq_add_cos_sq x; exact le_add_of_nonneg_right' (pow_two_nonneg _) lemma cos_sq_le_one : cos x ^ 2 ≤ 1 := by rw ← sin_sq_add_cos_sq x; exact le_add_of_nonneg_left' (pow_two_nonneg _) lemma abs_sin_le_one : abs' (sin x) ≤ 1 := (mul_self_le_mul_self_iff (_root_.abs_nonneg (sin x)) (by exact zero_le_one)).2 $ by rw [← _root_.abs_mul, abs_mul_self, mul_one, ← pow_two]; apply sin_sq_le_one lemma abs_cos_le_one : abs' (cos x) ≤ 1 := (mul_self_le_mul_self_iff (_root_.abs_nonneg (cos x)) (by exact zero_le_one)).2 $ by rw [← _root_.abs_mul, abs_mul_self, mul_one, ← pow_two]; apply cos_sq_le_one lemma sin_le_one : sin x ≤ 1 := (abs_le.1 (abs_sin_le_one _)).2 lemma cos_le_one : cos x ≤ 1 := (abs_le.1 (abs_cos_le_one _)).2 lemma neg_one_le_sin : -1 ≤ sin x := (abs_le.1 (abs_sin_le_one _)).1 lemma neg_one_le_cos : -1 ≤ cos x := (abs_le.1 (abs_cos_le_one _)).1 lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 := by rw ← of_real_inj; simp [cos_two_mul] lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x := by rw ← of_real_inj; simp [sin_two_mul] lemma cos_square : cos x ^ 2 = 1 / 2 + cos (2 * x) / 2 := of_real_inj.1 $ by simpa using cos_square x lemma sin_square : sin x ^ 2 = 1 - cos x ^ 2 := eq_sub_iff_add_eq.2 $ sin_sq_add_cos_sq _ @[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh] @[simp] lemma sinh_neg : sinh (-x) = -sinh x := by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul] lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y := by rw ← of_real_inj; simp [sinh_add] @[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh] @[simp] lemma cosh_neg : cosh (-x) = cosh x := by simp [cosh, exp_neg] lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y := by rw ← of_real_inj; simp [cosh, cosh_add] lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y := by simp [sub_eq_add_neg, sinh_add, sinh_neg, cosh_neg] lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y := by simp [sub_eq_add_neg, cosh_add, sinh_neg, cosh_neg] lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x := of_real_inj.1 $ by simp [tanh_eq_sinh_div_cosh] @[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh] @[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div] open is_absolute_value /- TODO make this private and prove ∀ x -/ lemma add_one_le_exp_of_nonneg {x : ℝ} (hx : 0 ≤ x) : x + 1 ≤ exp x := calc x + 1 ≤ lim (⟨(λ n : ℕ, ((exp' x) n).re), is_cau_seq_re (exp' x)⟩ : cau_seq ℝ abs') : le_lim (cau_seq.le_of_exists ⟨2, λ j hj, show x + (1 : ℝ) ≤ (∑ m in range j, (x ^ m / m.fact : ℂ)).re, from have h₁ : (((λ m : ℕ, (x ^ m / m.fact : ℂ)) ∘ nat.succ) 0).re = x, by simp, have h₂ : ((x : ℂ) ^ 0 / nat.fact 0).re = 1, by simp, begin rw [← nat.sub_add_cancel hj, sum_range_succ', sum_range_succ', add_re, add_re, h₁, h₂, add_assoc, ← @sum_hom _ _ _ _ _ _ _ complex.re (is_add_group_hom.to_is_add_monoid_hom _)], refine le_add_of_nonneg_of_le (sum_nonneg (λ m hm, _)) (le_refl _), rw [← of_real_pow, ← of_real_nat_cast, ← of_real_div, of_real_re], exact div_nonneg (pow_nonneg hx _) (nat.cast_pos.2 (nat.fact_pos _)), end⟩) ... = exp x : by rw [exp, complex.exp, ← cau_seq_re, lim_re] lemma one_le_exp {x : ℝ} (hx : 0 ≤ x) : 1 ≤ exp x := by linarith [add_one_le_exp_of_nonneg hx] lemma exp_pos (x : ℝ) : 0 < exp x := (le_total 0 x).elim (lt_of_lt_of_le zero_lt_one ∘ one_le_exp) (λ h, by rw [← neg_neg x, real.exp_neg]; exact inv_pos.2 (lt_of_lt_of_le zero_lt_one (one_le_exp (neg_nonneg.2 h)))) @[simp] lemma abs_exp (x : ℝ) : abs' (exp x) = exp x := abs_of_pos (exp_pos _) lemma exp_strict_mono : strict_mono exp := λ x y h, by rw [← sub_add_cancel y x, real.exp_add]; exact (lt_mul_iff_one_lt_left (exp_pos _)).2 (lt_of_lt_of_le (by linarith) (add_one_le_exp_of_nonneg (by linarith))) lemma exp_lt_exp {x y : ℝ} : exp x < exp y ↔ x < y := exp_strict_mono.lt_iff_lt lemma exp_le_exp {x y : ℝ} : exp x ≤ exp y ↔ x ≤ y := exp_strict_mono.le_iff_le lemma exp_injective : function.injective exp := exp_strict_mono.injective @[simp] lemma exp_eq_one_iff : exp x = 1 ↔ x = 0 := by rw [← exp_zero, exp_injective.eq_iff] lemma one_lt_exp_iff {x : ℝ} : 1 < exp x ↔ 0 < x := by rw [← exp_zero, exp_lt_exp] lemma exp_lt_one_iff {x : ℝ} : exp x < 1 ↔ x < 0 := by rw [← exp_zero, exp_lt_exp] end real namespace complex lemma sum_div_fact_le {α : Type*} [discrete_linear_ordered_field α] (n j : ℕ) (hn : 0 < n) : ∑ m in filter (λ k, n ≤ k) (range j), (1 / m.fact : α) ≤ n.succ * (n.fact * n)⁻¹ := calc ∑ m in filter (λ k, n ≤ k) (range j), (1 / m.fact : α) = ∑ m in range (j - n), 1 / (m + n).fact : sum_bij (λ m _, m - n) (λ m hm, mem_range.2 $ (nat.sub_lt_sub_right_iff (by simp at hm; tauto)).2 (by simp at hm; tauto)) (λ m hm, by rw nat.sub_add_cancel; simp at *; tauto) (λ a₁ a₂ ha₁ ha₂ h, by rwa [nat.sub_eq_iff_eq_add, ← nat.sub_add_comm, eq_comm, nat.sub_eq_iff_eq_add, add_left_inj, eq_comm] at h; simp at *; tauto) (λ b hb, ⟨b + n, mem_filter.2 ⟨mem_range.2 $ nat.add_lt_of_lt_sub_right (mem_range.1 hb), nat.le_add_left _ _⟩, by rw nat.add_sub_cancel⟩) ... ≤ ∑ m in range (j - n), (nat.fact n * n.succ ^ m)⁻¹ : begin refine sum_le_sum (assume m n, _), rw [one_div_eq_inv, inv_le_inv], { rw [← nat.cast_pow, ← nat.cast_mul, nat.cast_le, add_comm], exact nat.fact_mul_pow_le_fact }, { exact nat.cast_pos.2 (nat.fact_pos _) }, { exact mul_pos (nat.cast_pos.2 (nat.fact_pos _)) (pow_pos (nat.cast_pos.2 (nat.succ_pos _)) _) }, end ... = (nat.fact n)⁻¹ * ∑ m in range (j - n), n.succ⁻¹ ^ m : by simp [mul_inv', mul_sum.symm, sum_mul.symm, -nat.fact_succ, mul_comm, inv_pow'] ... = (n.succ - n.succ * n.succ⁻¹ ^ (j - n)) / (n.fact * n) : have h₁ : (n.succ : α) ≠ 1, from @nat.cast_one α _ _ ▸ mt nat.cast_inj.1 (mt nat.succ.inj (nat.pos_iff_ne_zero.1 hn)), have h₂ : (n.succ : α) ≠ 0, from nat.cast_ne_zero.2 (nat.succ_ne_zero _), have h₃ : (n.fact * n : α) ≠ 0, from mul_ne_zero (nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 (nat.fact_pos _))) (nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 hn)), have h₄ : (n.succ - 1 : α) = n, by simp, by rw [← geom_series_def, geom_sum_inv h₁ h₂, eq_div_iff_mul_eq _ _ h₃, mul_comm _ (n.fact * n : α), ← mul_assoc (n.fact⁻¹ : α), ← mul_inv', h₄, ← mul_assoc (n.fact * n : α), mul_comm (n : α) n.fact, mul_inv_cancel h₃]; simp [mul_add, add_mul, mul_assoc, mul_comm] ... ≤ n.succ / (n.fact * n) : begin refine iff.mpr (div_le_div_right (mul_pos _ _)) _, exact nat.cast_pos.2 (nat.fact_pos _), exact nat.cast_pos.2 hn, exact sub_le_self _ (mul_nonneg (nat.cast_nonneg _) (pow_nonneg (inv_nonneg.2 (nat.cast_nonneg _)) _)) end lemma exp_bound {x : ℂ} (hx : abs x ≤ 1) {n : ℕ} (hn : 0 < n) : abs (exp x - ∑ m in range n, x ^ m / m.fact) ≤ abs x ^ n * (n.succ * (n.fact * n)⁻¹) := begin rw [← lim_const (∑ m in range n, _), exp, sub_eq_add_neg, ← lim_neg, lim_add, ← lim_abs], refine lim_le (cau_seq.le_of_exists ⟨n, λ j hj, _⟩), show abs (∑ m in range j, x ^ m / m.fact - ∑ m in range n, x ^ m / m.fact) ≤ abs x ^ n * (n.succ * (n.fact * n)⁻¹), rw sum_range_sub_sum_range hj, exact calc abs (∑ m in (range j).filter (λ k, n ≤ k), (x ^ m / m.fact : ℂ)) = abs (∑ m in (range j).filter (λ k, n ≤ k), (x ^ n * (x ^ (m - n) / m.fact) : ℂ)) : congr_arg abs (sum_congr rfl (λ m hm, by rw [← mul_div_assoc, ← pow_add, nat.add_sub_cancel']; simp at hm; tauto)) ... ≤ ∑ m in filter (λ k, n ≤ k) (range j), abs (x ^ n * (_ / m.fact)) : abv_sum_le_sum_abv _ _ ... ≤ ∑ m in filter (λ k, n ≤ k) (range j), abs x ^ n * (1 / m.fact) : begin refine sum_le_sum (λ m hm, _), rw [abs_mul, abv_pow abs, abs_div, abs_cast_nat], refine mul_le_mul_of_nonneg_left ((div_le_div_right _).2 _) _, exact nat.cast_pos.2 (nat.fact_pos _), rw abv_pow abs, exact (pow_le_one _ (abs_nonneg _) hx), exact pow_nonneg (abs_nonneg _) _ end ... = abs x ^ n * (∑ m in (range j).filter (λ k, n ≤ k), (1 / m.fact : ℝ)) : by simp [abs_mul, abv_pow abs, abs_div, mul_sum.symm] ... ≤ abs x ^ n * (n.succ * (n.fact * n)⁻¹) : mul_le_mul_of_nonneg_left (sum_div_fact_le _ _ hn) (pow_nonneg (abs_nonneg _) _) end lemma abs_exp_sub_one_le {x : ℂ} (hx : abs x ≤ 1) : abs (exp x - 1) ≤ 2 * abs x := calc abs (exp x - 1) = abs (exp x - ∑ m in range 1, x ^ m / m.fact) : by simp [sum_range_succ] ... ≤ abs x ^ 1 * ((nat.succ 1) * (nat.fact 1 * (1 : ℕ))⁻¹) : exp_bound hx dec_trivial ... = 2 * abs x : by simp [two_mul, mul_two, mul_add, mul_comm] lemma abs_exp_sub_one_sub_id_le {x : ℂ} (hx : abs x ≤ 1) : abs (exp x - 1 - x) ≤ (abs x)^2 := calc abs (exp x - 1 - x) = abs (exp x - ∑ m in range 2, x ^ m / m.fact) : by simp [sub_eq_add_neg, sum_range_succ, add_assoc] ... ≤ (abs x)^2 * (nat.succ 2 * (nat.fact 2 * (2 : ℕ))⁻¹) : exp_bound hx dec_trivial ... ≤ (abs x)^2 * 1 : mul_le_mul_of_nonneg_left (by norm_num) (pow_two_nonneg (abs x)) ... = (abs x)^2 : by rw [mul_one] end complex namespace real open complex finset lemma cos_bound {x : ℝ} (hx : abs' x ≤ 1) : abs' (cos x - (1 - x ^ 2 / 2)) ≤ abs' x ^ 4 * (5 / 96) := calc abs' (cos x - (1 - x ^ 2 / 2)) = abs (complex.cos x - (1 - x ^ 2 / 2)) : by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv] ... = abs ((complex.exp (x * I) + complex.exp (-x * I) - (2 - x ^ 2)) / 2) : by simp [complex.cos, sub_div, add_div, neg_div, div_self (@two_ne_zero' ℂ _ _ _)] ... = abs (((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m.fact) + ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m.fact))) / 2) : congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin simp only [sum_range_succ], simp [pow_succ], apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring end) ... ≤ abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m.fact) / 2) + abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m.fact) / 2) : by rw add_div; exact abs_add _ _ ... = (abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m.fact)) / 2 + abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m.fact)) / 2) : by simp [complex.abs_div] ... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2 + (complex.abs (-x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2) : add_le_add ((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial)) ((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial)) ... ≤ abs' x ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc] lemma sin_bound {x : ℝ} (hx : abs' x ≤ 1) : abs' (sin x - (x - x ^ 3 / 6)) ≤ abs' x ^ 4 * (5 / 96) := calc abs' (sin x - (x - x ^ 3 / 6)) = abs (complex.sin x - (x - x ^ 3 / 6)) : by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv] ... = abs (((complex.exp (-x * I) - complex.exp (x * I)) * I - (2 * x - x ^ 3 / 3)) / 2) : by simp [complex.sin, sub_div, add_div, neg_div, mul_div_cancel_left _ (@two_ne_zero' ℂ _ _ _), div_div_eq_div_mul, show (3 : ℂ) * 2 = 6, by norm_num] ... = abs ((((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m.fact) - (complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m.fact)) * I) / 2) : congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin simp only [sum_range_succ], simp [pow_succ], apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring end) ... ≤ abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m.fact) * I / 2) + abs (-((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m.fact) * I) / 2) : by rw [sub_mul, sub_eq_add_neg, add_div]; exact abs_add _ _ ... = (abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m.fact)) / 2 + abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m.fact)) / 2) : by simp [add_comm, complex.abs_div, complex.abs_mul] ... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2 + (complex.abs (-x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2) : add_le_add ((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial)) ((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial)) ... ≤ abs' x ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc] lemma cos_pos_of_le_one {x : ℝ} (hx : abs' x ≤ 1) : 0 < cos x := calc 0 < (1 - x ^ 2 / 2) - abs' x ^ 4 * (5 / 96) : sub_pos.2 $ lt_sub_iff_add_lt.2 (calc abs' x ^ 4 * (5 / 96) + x ^ 2 / 2 ≤ 1 * (5 / 96) + 1 / 2 : add_le_add (mul_le_mul_of_nonneg_right (pow_le_one _ (abs_nonneg _) hx) (by norm_num)) ((div_le_div_right (by norm_num)).2 (by rw [pow_two, ← abs_mul_self, _root_.abs_mul]; exact mul_le_one hx (abs_nonneg _) hx)) ... < 1 : by norm_num) ... ≤ cos x : sub_le.1 (abs_sub_le_iff.1 (cos_bound hx)).2 lemma sin_pos_of_pos_of_le_one {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 1) : 0 < sin x := calc 0 < x - x ^ 3 / 6 - abs' x ^ 4 * (5 / 96) : sub_pos.2 $ lt_sub_iff_add_lt.2 (calc abs' x ^ 4 * (5 / 96) + x ^ 3 / 6 ≤ x * (5 / 96) + x / 6 : add_le_add (mul_le_mul_of_nonneg_right (calc abs' x ^ 4 ≤ abs' x ^ 1 : pow_le_pow_of_le_one (abs_nonneg _) (by rwa _root_.abs_of_nonneg (le_of_lt hx0)) dec_trivial ... = x : by simp [_root_.abs_of_nonneg (le_of_lt (hx0))]) (by norm_num)) ((div_le_div_right (by norm_num)).2 (calc x ^ 3 ≤ x ^ 1 : pow_le_pow_of_le_one (le_of_lt hx0) hx dec_trivial ... = x : pow_one _)) ... < x : by linarith) ... ≤ sin x : sub_le.1 (abs_sub_le_iff.1 (sin_bound (by rwa [_root_.abs_of_nonneg (le_of_lt hx0)]))).2 lemma sin_pos_of_pos_of_le_two {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 2) : 0 < sin x := have x / 2 ≤ 1, from div_le_of_le_mul (by norm_num) (by simpa), calc 0 < 2 * sin (x / 2) * cos (x / 2) : mul_pos (mul_pos (by norm_num) (sin_pos_of_pos_of_le_one (half_pos hx0) this)) (cos_pos_of_le_one (by rwa [_root_.abs_of_nonneg (le_of_lt (half_pos hx0))])) ... = sin x : by rw [← sin_two_mul, two_mul, add_halves] lemma cos_one_le : cos 1 ≤ 2 / 3 := calc cos 1 ≤ abs' (1 : ℝ) ^ 4 * (5 / 96) + (1 - 1 ^ 2 / 2) : sub_le_iff_le_add.1 (abs_sub_le_iff.1 (cos_bound (by simp))).1 ... ≤ 2 / 3 : by norm_num lemma cos_one_pos : 0 < cos 1 := cos_pos_of_le_one (by simp) lemma cos_two_neg : cos 2 < 0 := calc cos 2 = cos (2 * 1) : congr_arg cos (mul_one _).symm ... = _ : real.cos_two_mul 1 ... ≤ 2 * (2 / 3) ^ 2 - 1 : sub_le_sub_right (mul_le_mul_of_nonneg_left (by rw [pow_two, pow_two]; exact mul_self_le_mul_self (le_of_lt cos_one_pos) cos_one_le) (by norm_num)) _ ... < 0 : by norm_num end real namespace complex lemma abs_cos_add_sin_mul_I (x : ℝ) : abs (cos x + sin x * I) = 1 := have _ := real.sin_sq_add_cos_sq x, by simp [add_comm, abs, norm_sq, pow_two, *, sin_of_real_re, cos_of_real_re, mul_re] at * lemma abs_exp_eq_iff_re_eq {x y : ℂ} : abs (exp x) = abs (exp y) ↔ x.re = y.re := by rw [exp_eq_exp_re_mul_sin_add_cos, exp_eq_exp_re_mul_sin_add_cos y, abs_mul, abs_mul, abs_cos_add_sin_mul_I, abs_cos_add_sin_mul_I, ← of_real_exp, ← of_real_exp, abs_of_nonneg (le_of_lt (real.exp_pos _)), abs_of_nonneg (le_of_lt (real.exp_pos _)), mul_one, mul_one]; exact ⟨λ h, real.exp_injective h, congr_arg _⟩ @[simp] lemma abs_exp_of_real (x : ℝ) : abs (exp x) = real.exp x := by rw [← of_real_exp]; exact abs_of_nonneg (le_of_lt (real.exp_pos _)) end complex
e090aecb331c659e5aa2f1bc8b28e40e96648ab6
271e26e338b0c14544a889c31c30b39c989f2e0f
/stage0/src/Init/Lean/Meta/Instances.lean
f78ff504004215c190a8ba06cd3969b0be6757e9
[ "Apache-2.0" ]
permissive
dgorokho/lean4
805f99b0b60c545b64ac34ab8237a8504f89d7d4
e949a052bad59b1c7b54a82d24d516a656487d8a
refs/heads/master
1,607,061,363,851
1,578,006,086,000
1,578,006,086,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,187
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Lean.Meta.DiscrTree namespace Lean namespace Meta structure InstanceEntry := (keys : Array DiscrTree.Key) (val : Expr) abbrev Instances := DiscrTree Expr def addInstanceEntry (d : Instances) (e : InstanceEntry) : Instances := d.insertCore e.keys e.val def mkInstanceExtension : IO (SimplePersistentEnvExtension InstanceEntry Instances) := registerSimplePersistentEnvExtension { name := `instanceExt, addEntryFn := addInstanceEntry, addImportedFn := fun es => (mkStateFromImportedEntries addInstanceEntry DiscrTree.empty es) } @[init mkInstanceExtension] constant instanceExtension : SimplePersistentEnvExtension InstanceEntry Instances := arbitrary _ private def mkInstanceKey (e : Expr) : MetaM (Array DiscrTree.Key) := do type ← inferType e; withNewMCtxDepth $ do (_, _, type) ← forallMetaTelescopeReducing type; DiscrTree.mkPath type @[export lean_add_instance] def addGlobalInstance (env : Environment) (constName : Name) : IO Environment := match env.find? constName with | none => throw $ IO.userError "unknown constant" | some cinfo => do let c := mkConst constName (cinfo.lparams.map mkLevelParam); (keys, env) ← IO.runMeta (mkInstanceKey c) env; pure $ instanceExtension.addEntry env { keys := keys, val := c } @[init] def registerInstanceAttr : IO Unit := registerAttribute { name := `instance, descr := "type class instance", add := fun env declName args persistent => do unless args.isMissing $ throw (IO.userError ("invalid attribute 'instance', unexpected argument")); unless persistent $ throw (IO.userError ("invalid attribute 'instance', must be persistent")); env ← IO.ofExcept (addGlobalInstanceOld env declName); -- TODO: delete addGlobalInstance env declName } end Meta def Environment.getGlobalInstances (env : Environment) : Meta.Instances := Meta.instanceExtension.getState env namespace Meta def getGlobalInstances : MetaM Instances := do env ← getEnv; pure env.getGlobalInstances end Meta end Lean
1bc820dd7fa4395a4bad0b5755d1136b658e9fc1
b7f22e51856f4989b970961f794f1c435f9b8f78
/hott/algebra/category/iso.hlean
da2ac740861cb13424595f6d3ec98dde5dfca603
[ "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
19,697
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn, Jakob von Raumer -/ import .precategory types.sigma arity open eq category prod equiv is_equiv sigma sigma.ops is_trunc namespace iso structure split_mono [class] {ob : Type} [C : precategory ob] {a b : ob} (f : a ⟶ b) := {retraction_of : b ⟶ a} (retraction_comp : retraction_of ∘ f = id) structure split_epi [class] {ob : Type} [C : precategory ob] {a b : ob} (f : a ⟶ b) := {section_of : b ⟶ a} (comp_section : f ∘ section_of = id) structure is_iso [class] {ob : Type} [C : precategory ob] {a b : ob} (f : a ⟶ b) := (inverse : b ⟶ a) (left_inverse : inverse ∘ f = id) (right_inverse : f ∘ inverse = id) attribute is_iso.inverse [reducible] open split_mono split_epi is_iso abbreviation retraction_of [unfold 6] := @split_mono.retraction_of abbreviation retraction_comp [unfold 6] := @split_mono.retraction_comp abbreviation section_of [unfold 6] := @split_epi.section_of abbreviation comp_section [unfold 6] := @split_epi.comp_section abbreviation inverse [unfold 6] := @is_iso.inverse abbreviation left_inverse [unfold 6] := @is_iso.left_inverse abbreviation right_inverse [unfold 6] := @is_iso.right_inverse postfix ⁻¹ := inverse --a second notation for the inverse, which is not overloaded postfix [parsing_only] `⁻¹ʰ`:std.prec.max_plus := inverse -- input using \-1h variables {ob : Type} [C : precategory ob] variables {a b c : ob} {g : b ⟶ c} {f : a ⟶ b} {h : b ⟶ a} include C definition split_mono_of_is_iso [constructor] [instance] [priority 300] (f : a ⟶ b) [H : is_iso f] : split_mono f := split_mono.mk !left_inverse definition split_epi_of_is_iso [constructor] [instance] [priority 300] (f : a ⟶ b) [H : is_iso f] : split_epi f := split_epi.mk !right_inverse definition is_iso_id [constructor] [instance] [priority 500] (a : ob) : is_iso (ID a) := is_iso.mk _ !id_id !id_id definition is_iso_inverse [constructor] [instance] [priority 200] (f : a ⟶ b) {H : is_iso f} : is_iso f⁻¹ := is_iso.mk _ !right_inverse !left_inverse theorem left_inverse_eq_right_inverse {f : a ⟶ b} {g g' : hom b a} (Hl : g ∘ f = id) (Hr : f ∘ g' = id) : g = g' := by rewrite [-(id_right g), -Hr, assoc, Hl, id_left] theorem retraction_eq [H : split_mono f] (H2 : f ∘ h = id) : retraction_of f = h := left_inverse_eq_right_inverse !retraction_comp H2 theorem section_eq [H : split_epi f] (H2 : h ∘ f = id) : section_of f = h := (left_inverse_eq_right_inverse H2 !comp_section)⁻¹ theorem inverse_eq_right [H : is_iso f] (H2 : f ∘ h = id) : f⁻¹ = h := left_inverse_eq_right_inverse !left_inverse H2 theorem inverse_eq_left [H : is_iso f] (H2 : h ∘ f = id) : f⁻¹ = h := (left_inverse_eq_right_inverse H2 !right_inverse)⁻¹ theorem retraction_eq_section (f : a ⟶ b) [Hl : split_mono f] [Hr : split_epi f] : retraction_of f = section_of f := retraction_eq !comp_section definition is_iso_of_split_epi_of_split_mono [constructor] (f : a ⟶ b) [Hl : split_mono f] [Hr : split_epi f] : is_iso f := is_iso.mk _ ((retraction_eq_section f) ▸ (retraction_comp f)) (comp_section f) theorem inverse_unique (H H' : is_iso f) : @inverse _ _ _ _ f H = @inverse _ _ _ _ f H' := @inverse_eq_left _ _ _ _ _ _ H !left_inverse theorem inverse_involutive (f : a ⟶ b) [H : is_iso f] [H : is_iso (f⁻¹)] : (f⁻¹)⁻¹ = f := inverse_eq_right !left_inverse theorem inverse_eq_inverse {f g : a ⟶ b} [H : is_iso f] [H : is_iso g] (p : f = g) : f⁻¹ = g⁻¹ := by cases p;apply inverse_unique theorem retraction_id (a : ob) : retraction_of (ID a) = id := retraction_eq !id_id theorem section_id (a : ob) : section_of (ID a) = id := section_eq !id_id theorem id_inverse (a : ob) [H : is_iso (ID a)] : (ID a)⁻¹ = id := inverse_eq_left !id_id definition split_mono_comp [constructor] [instance] [priority 150] (g : b ⟶ c) (f : a ⟶ b) [Hf : split_mono f] [Hg : split_mono g] : split_mono (g ∘ f) := split_mono.mk (show (retraction_of f ∘ retraction_of g) ∘ g ∘ f = id, by rewrite [-assoc, assoc _ g f, retraction_comp, id_left, retraction_comp]) definition split_epi_comp [constructor] [instance] [priority 150] (g : b ⟶ c) (f : a ⟶ b) [Hf : split_epi f] [Hg : split_epi g] : split_epi (g ∘ f) := split_epi.mk (show (g ∘ f) ∘ section_of f ∘ section_of g = id, by rewrite [-assoc, {f ∘ _}assoc, comp_section, id_left, comp_section]) definition is_iso_comp [constructor] [instance] [priority 150] (g : b ⟶ c) (f : a ⟶ b) [Hf : is_iso f] [Hg : is_iso g] : is_iso (g ∘ f) := !is_iso_of_split_epi_of_split_mono theorem is_prop_is_iso [instance] (f : hom a b) : is_prop (is_iso f) := begin apply is_prop.mk, intro H H', cases H with g li ri, cases H' with g' li' ri', fapply (apd0111 (@is_iso.mk ob C a b f)), apply left_inverse_eq_right_inverse, apply li, apply ri', apply is_prop.elimo, apply is_prop.elimo, end end iso open iso /- isomorphic objects -/ structure iso {ob : Type} [C : precategory ob] (a b : ob) := (to_hom : hom a b) (struct : is_iso to_hom) infix ` ≅ `:50 := iso notation c ` ≅[`:50 C:0 `] `:0 c':50 := @iso C _ c c' attribute iso.struct [instance] [priority 2000] namespace iso variables {ob : Type} [C : precategory ob] variables {a b c : ob} {g : b ⟶ c} {f : a ⟶ b} {h : b ⟶ a} include C attribute to_hom [coercion] protected definition MK [constructor] (f : a ⟶ b) (g : b ⟶ a) (H1 : g ∘ f = id) (H2 : f ∘ g = id) := @(mk f) (is_iso.mk _ H1 H2) variable {C} definition to_inv [reducible] [unfold 5] (f : a ≅ b) : b ⟶ a := (to_hom f)⁻¹ definition to_left_inverse [unfold 5] (f : a ≅ b) : (to_hom f)⁻¹ ∘ (to_hom f) = id := left_inverse (to_hom f) definition to_right_inverse [unfold 5] (f : a ≅ b) : (to_hom f) ∘ (to_hom f)⁻¹ = id := right_inverse (to_hom f) variable [C] protected definition refl [constructor] (a : ob) : a ≅ a := mk (ID a) _ protected definition symm [constructor] ⦃a b : ob⦄ (H : a ≅ b) : b ≅ a := mk (to_hom H)⁻¹ _ protected definition trans [constructor] ⦃a b c : ob⦄ (H1 : a ≅ b) (H2 : b ≅ c) : a ≅ c := mk (to_hom H2 ∘ to_hom H1) _ infixl ` ⬝i `:75 := iso.trans postfix `⁻¹ⁱ`:(max + 1) := iso.symm definition change_hom [constructor] (H : a ≅ b) (f : a ⟶ b) (p : to_hom H = f) : a ≅ b := iso.MK f (to_inv H) (p ▸ to_left_inverse H) (p ▸ to_right_inverse H) definition change_inv [constructor] (H : a ≅ b) (g : b ⟶ a) (p : to_inv H = g) : a ≅ b := iso.MK (to_hom H) g (p ▸ to_left_inverse H) (p ▸ to_right_inverse H) definition iso_mk_eq {f f' : a ⟶ b} [H : is_iso f] [H' : is_iso f'] (p : f = f') : iso.mk f _ = iso.mk f' _ := apd011 iso.mk p !is_prop.elimo variable {C} definition iso_eq {f f' : a ≅ b} (p : to_hom f = to_hom f') : f = f' := by (cases f; cases f'; apply (iso_mk_eq p)) definition iso_pathover {X : Type} {x₁ x₂ : X} {p : x₁ = x₂} {a : X → ob} {b : X → ob} {f₁ : a x₁ ≅ b x₁} {f₂ : a x₂ ≅ b x₂} (q : to_hom f₁ =[p] to_hom f₂) : f₁ =[p] f₂ := begin cases f₁, cases f₂, esimp at q, induction q, apply pathover_idp_of_eq, exact ap (iso.mk _) !is_prop.elim end variable [C] -- The structure for isomorphism can be characterized up to equivalence by a sigma type. protected definition sigma_char ⦃a b : ob⦄ : (Σ (f : hom a b), is_iso f) ≃ (a ≅ b) := begin fapply (equiv.mk), {intro S, apply iso.mk, apply (S.2)}, {fapply adjointify, {intro p, cases p with f H, exact sigma.mk f H}, {intro p, cases p, apply idp}, {intro S, cases S, apply idp}}, end -- The type of isomorphisms between two objects is a set definition is_set_iso [instance] : is_set (a ≅ b) := begin apply is_trunc_is_equiv_closed, apply equiv.to_is_equiv (!iso.sigma_char), end definition iso_of_eq [unfold 5] (p : a = b) : a ≅ b := eq.rec_on p (iso.refl a) definition hom_of_eq [reducible] [unfold 5] (p : a = b) : a ⟶ b := iso.to_hom (iso_of_eq p) definition inv_of_eq [reducible] [unfold 5] (p : a = b) : b ⟶ a := iso.to_inv (iso_of_eq p) definition iso_of_eq_inv (p : a = b) : iso_of_eq p⁻¹ = iso.symm (iso_of_eq p) := eq.rec_on p idp theorem hom_of_eq_inv (p : a = b) : hom_of_eq p⁻¹ = inv_of_eq p := eq.rec_on p idp theorem inv_of_eq_inv (p : a = b) : inv_of_eq p⁻¹ = hom_of_eq p := eq.rec_on p idp definition iso_of_eq_con (p : a = b) (q : b = c) : iso_of_eq (p ⬝ q) = iso.trans (iso_of_eq p) (iso_of_eq q) := eq.rec_on q (eq.rec_on p (iso_eq !id_id⁻¹)) definition transport_iso_of_eq (p : a = b) : p ▸ !iso.refl = iso_of_eq p := by cases p; reflexivity definition hom_pathover {X : Type} {x₁ x₂ : X} {p : x₁ = x₂} {a b : X → ob} {f₁ : a x₁ ⟶ b x₁} {f₂ : a x₂ ⟶ b x₂} (q : hom_of_eq (ap b p) ∘ f₁ = f₂ ∘ hom_of_eq (ap a p)) : f₁ =[p] f₂ := begin induction p, apply pathover_idp_of_eq, exact !id_left⁻¹ ⬝ q ⬝ !id_right end definition hom_pathover_constant_left {X : Type} {x₁ x₂ : X} {p : x₁ = x₂} {a : ob} {b : X → ob} {f₁ : a ⟶ b x₁} {f₂ : a ⟶ b x₂} (q : hom_of_eq (ap b p) ∘ f₁ = f₂) : f₁ =[p] f₂ := hom_pathover (q ⬝ !id_right⁻¹ ⬝ ap (λx, _ ∘ hom_of_eq x) !ap_constant⁻¹) definition hom_pathover_constant_right {X : Type} {x₁ x₂ : X} {p : x₁ = x₂} {a : X → ob} {b : ob} {f₁ : a x₁ ⟶ b} {f₂ : a x₂ ⟶ b} (q : f₁ = f₂ ∘ hom_of_eq (ap a p)) : f₁ =[p] f₂ := hom_pathover (ap (λx, hom_of_eq x ∘ _) !ap_constant ⬝ !id_left ⬝ q) definition hom_pathover_id_left {p : a = b} {c : ob → ob} {f₁ : a ⟶ c a} {f₂ : b ⟶ c b} (q : hom_of_eq (ap c p) ∘ f₁ = f₂ ∘ hom_of_eq p) : f₁ =[p] f₂ := hom_pathover (q ⬝ ap (λx, _ ∘ hom_of_eq x) !ap_id⁻¹) definition hom_pathover_id_right {p : a = b} {c : ob → ob} {f₁ : c a ⟶ a} {f₂ : c b ⟶ b} (q : hom_of_eq p ∘ f₁ = f₂ ∘ hom_of_eq (ap c p)) : f₁ =[p] f₂ := hom_pathover (ap (λx, hom_of_eq x ∘ _) !ap_id ⬝ q) definition hom_pathover_id_left_id_right {p : a = b} {f₁ : a ⟶ a} {f₂ : b ⟶ b} (q : hom_of_eq p ∘ f₁ = f₂ ∘ hom_of_eq p) : f₁ =[p] f₂ := hom_pathover_id_left (ap (λx, hom_of_eq x ∘ _) !ap_id ⬝ q) definition hom_pathover_id_left_constant_right {p : a = b} {f₁ : a ⟶ c} {f₂ : b ⟶ c} (q : f₁ = f₂ ∘ hom_of_eq p) : f₁ =[p] f₂ := hom_pathover_constant_right (q ⬝ ap (λx, _ ∘ hom_of_eq x) !ap_id⁻¹) definition hom_pathover_constant_left_id_right {p : a = b} {f₁ : c ⟶ a} {f₂ : c ⟶ b} (q : hom_of_eq p ∘ f₁ = f₂) : f₁ =[p] f₂ := hom_pathover_constant_left (ap (λx, hom_of_eq x ∘ _) !ap_id ⬝ q) section open funext variables {X : Type} {x y : X} {F G : X → ob} definition transport_hom_of_eq (p : F = G) (f : hom (F x) (F y)) : p ▸ f = hom_of_eq (apd10 p y) ∘ f ∘ inv_of_eq (apd10 p x) := by induction p; exact !id_leftright⁻¹ definition transport_hom_of_eq_right (p : x = y) (f : hom c (F x)) : p ▸ f = hom_of_eq (ap F p) ∘ f := by induction p; exact !id_left⁻¹ definition transport_hom_of_eq_left (p : x = y) (f : hom (F x) c) : p ▸ f = f ∘ inv_of_eq (ap F p) := by induction p; exact !id_right⁻¹ definition transport_hom (p : F ~ G) (f : hom (F x) (F y)) : eq_of_homotopy p ▸ f = hom_of_eq (p y) ∘ f ∘ inv_of_eq (p x) := calc eq_of_homotopy p ▸ f = hom_of_eq (apd10 (eq_of_homotopy p) y) ∘ f ∘ inv_of_eq (apd10 (eq_of_homotopy p) x) : transport_hom_of_eq ... = hom_of_eq (p y) ∘ f ∘ inv_of_eq (p x) : {right_inv apd10 p} end structure mono [class] (f : a ⟶ b) := (elim : ∀c (g h : hom c a), f ∘ g = f ∘ h → g = h) structure epi [class] (f : a ⟶ b) := (elim : ∀c (g h : hom b c), g ∘ f = h ∘ f → g = h) definition mono_of_split_mono [instance] (f : a ⟶ b) [H : split_mono f] : mono f := mono.mk (λ c g h H, calc g = id ∘ g : by rewrite id_left ... = (retraction_of f ∘ f) ∘ g : by rewrite retraction_comp ... = (retraction_of f ∘ f) ∘ h : by rewrite [-assoc, H, -assoc] ... = id ∘ h : by rewrite retraction_comp ... = h : by rewrite id_left) definition epi_of_split_epi [instance] (f : a ⟶ b) [H : split_epi f] : epi f := epi.mk (λ c g h H, calc g = g ∘ id : by rewrite id_right ... = g ∘ f ∘ section_of f : by rewrite -(comp_section f) ... = h ∘ f ∘ section_of f : by rewrite [assoc, H, -assoc] ... = h ∘ id : by rewrite comp_section ... = h : by rewrite id_right) definition mono_comp [instance] (g : b ⟶ c) (f : a ⟶ b) [Hf : mono f] [Hg : mono g] : mono (g ∘ f) := mono.mk (λ d h₁ h₂ H, have H2 : g ∘ (f ∘ h₁) = g ∘ (f ∘ h₂), begin rewrite *assoc, exact H end, !mono.elim (!mono.elim H2)) definition epi_comp [instance] (g : b ⟶ c) (f : a ⟶ b) [Hf : epi f] [Hg : epi g] : epi (g ∘ f) := epi.mk (λ d h₁ h₂ H, have H2 : (h₁ ∘ g) ∘ f = (h₂ ∘ g) ∘ f, begin rewrite -*assoc, exact H end, !epi.elim (!epi.elim H2)) end iso attribute iso.refl [refl] attribute iso.symm [symm] attribute iso.trans [trans] namespace iso /- rewrite lemmas for inverses, modified from https://github.com/JasonGross/HoTT-categories/blob/master/theories/Categories/Category/Morphisms.v -/ section variables {ob : Type} [C : precategory ob] include C variables {a b c d : ob} (f : b ⟶ a) (r : c ⟶ d) (q : b ⟶ c) (p : a ⟶ b) (g : d ⟶ c) variable [Hq : is_iso q] include Hq theorem comp.right_inverse : q ∘ q⁻¹ = id := !right_inverse theorem comp.left_inverse : q⁻¹ ∘ q = id := !left_inverse theorem inverse_comp_cancel_left : q⁻¹ ∘ (q ∘ p) = p := by rewrite [assoc, left_inverse, id_left] theorem comp_inverse_cancel_left : q ∘ (q⁻¹ ∘ g) = g := by rewrite [assoc, right_inverse, id_left] theorem comp_inverse_cancel_right : (r ∘ q) ∘ q⁻¹ = r := by rewrite [-assoc, right_inverse, id_right] theorem inverse_comp_cancel_right : (f ∘ q⁻¹) ∘ q = f := by rewrite [-assoc, left_inverse, id_right] theorem comp_inverse [Hp : is_iso p] [Hpq : is_iso (q ∘ p)] : (q ∘ p)⁻¹ʰ = p⁻¹ʰ ∘ q⁻¹ʰ := inverse_eq_left (show (p⁻¹ʰ ∘ q⁻¹ʰ) ∘ q ∘ p = id, from by rewrite [-assoc, inverse_comp_cancel_left, left_inverse]) theorem inverse_comp_inverse_left [H' : is_iso g] : (q⁻¹ ∘ g)⁻¹ = g⁻¹ ∘ q := inverse_involutive q ▸ comp_inverse q⁻¹ g theorem inverse_comp_inverse_right [H' : is_iso f] : (q ∘ f⁻¹)⁻¹ = f ∘ q⁻¹ := inverse_involutive f ▸ comp_inverse q f⁻¹ theorem inverse_comp_inverse_inverse [H' : is_iso r] : (q⁻¹ ∘ r⁻¹)⁻¹ = r ∘ q := inverse_involutive r ▸ inverse_comp_inverse_left q r⁻¹ end section variables {ob : Type} {C : precategory ob} include C variables {d c b a : ob} {r' : c ⟶ d} {i : b ⟶ c} {f : b ⟶ a} {r : c ⟶ d} {q : b ⟶ c} {p : a ⟶ b} {g : d ⟶ c} {h : c ⟶ b} {p' : a ⟶ b} {x : b ⟶ d} {z : a ⟶ c} {y : d ⟶ b} {w : c ⟶ a} variable [Hq : is_iso q] include Hq theorem comp_eq_of_eq_inverse_comp (H : y = q⁻¹ ∘ g) : q ∘ y = g := H⁻¹ ▸ comp_inverse_cancel_left q g theorem comp_eq_of_eq_comp_inverse (H : w = f ∘ q⁻¹) : w ∘ q = f := H⁻¹ ▸ inverse_comp_cancel_right f q theorem eq_comp_of_inverse_comp_eq (H : q⁻¹ ∘ g = y) : g = q ∘ y := (comp_eq_of_eq_inverse_comp H⁻¹)⁻¹ theorem eq_comp_of_comp_inverse_eq (H : f ∘ q⁻¹ = w) : f = w ∘ q := (comp_eq_of_eq_comp_inverse H⁻¹)⁻¹ variable {Hq} theorem inverse_comp_eq_of_eq_comp (H : z = q ∘ p) : q⁻¹ ∘ z = p := H⁻¹ ▸ inverse_comp_cancel_left q p theorem comp_inverse_eq_of_eq_comp (H : x = r ∘ q) : x ∘ q⁻¹ = r := H⁻¹ ▸ comp_inverse_cancel_right r q theorem eq_inverse_comp_of_comp_eq (H : q ∘ p = z) : p = q⁻¹ ∘ z := (inverse_comp_eq_of_eq_comp H⁻¹)⁻¹ theorem eq_comp_inverse_of_comp_eq (H : r ∘ q = x) : r = x ∘ q⁻¹ := (comp_inverse_eq_of_eq_comp H⁻¹)⁻¹ theorem eq_inverse_of_comp_eq_id' (H : h ∘ q = id) : h = q⁻¹ := (inverse_eq_left H)⁻¹ theorem eq_inverse_of_comp_eq_id (H : q ∘ h = id) : h = q⁻¹ := (inverse_eq_right H)⁻¹ theorem inverse_eq_of_id_eq_comp (H : id = h ∘ q) : q⁻¹ = h := (eq_inverse_of_comp_eq_id' H⁻¹)⁻¹ theorem inverse_eq_of_id_eq_comp' (H : id = q ∘ h) : q⁻¹ = h := (eq_inverse_of_comp_eq_id H⁻¹)⁻¹ variable [Hq] theorem eq_of_comp_inverse_eq_id (H : i ∘ q⁻¹ = id) : i = q := eq_inverse_of_comp_eq_id' H ⬝ inverse_involutive q theorem eq_of_inverse_comp_eq_id (H : q⁻¹ ∘ i = id) : i = q := eq_inverse_of_comp_eq_id H ⬝ inverse_involutive q theorem eq_of_id_eq_comp_inverse (H : id = i ∘ q⁻¹) : q = i := (eq_of_comp_inverse_eq_id H⁻¹)⁻¹ theorem eq_of_id_eq_inverse_comp (H : id = q⁻¹ ∘ i) : q = i := (eq_of_inverse_comp_eq_id H⁻¹)⁻¹ theorem inverse_comp_id_comp : q⁻¹ ∘ id ∘ q = id := ap (λ x, _ ∘ x) !id_left ⬝ !comp.left_inverse theorem comp_id_comp_inverse : q ∘ id ∘ q⁻¹ = id := ap (λ x, _ ∘ x) !id_left ⬝ !comp.right_inverse variables (q) theorem comp.cancel_left (H : q ∘ p = q ∘ p') : p = p' := by rewrite [-inverse_comp_cancel_left q p, H, inverse_comp_cancel_left q] theorem comp.cancel_right (H : r ∘ q = r' ∘ q) : r = r' := by rewrite [-comp_inverse_cancel_right r q, H, comp_inverse_cancel_right _ q] end end iso namespace iso /- precomposition and postcomposition by an iso is an equivalence -/ definition is_equiv_postcompose [constructor] {ob : Type} [precategory ob] {a b c : ob} (g : b ⟶ c) [is_iso g] : is_equiv (λ(f : a ⟶ b), g ∘ f) := begin fapply adjointify, { exact λf', g⁻¹ ∘ f'}, { intro f', apply comp_inverse_cancel_left}, { intro f, apply inverse_comp_cancel_left} end definition equiv_postcompose [constructor] {ob : Type} [precategory ob] {a b c : ob} (g : b ⟶ c) [is_iso g] : (a ⟶ b) ≃ (a ⟶ c) := equiv.mk (λ(f : a ⟶ b), g ∘ f) (is_equiv_postcompose g) definition is_equiv_precompose [constructor] {ob : Type} [precategory ob] {a b c : ob} (f : a ⟶ b) [is_iso f] : is_equiv (λ(g : b ⟶ c), g ∘ f) := begin fapply adjointify, { exact λg', g' ∘ f⁻¹}, { intro g', apply comp_inverse_cancel_right}, { intro g, apply inverse_comp_cancel_right} end definition equiv_precompose [constructor] {ob : Type} [precategory ob] {a b c : ob} (f : a ⟶ b) [is_iso f] : (b ⟶ c) ≃ (a ⟶ c) := equiv.mk (λ(g : b ⟶ c), g ∘ f) (is_equiv_precompose f) end iso
ecbb8cebf4a079fcf18cde624a58bb38a7a30d83
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/data/equiv/algebra.lean
a90c8ec2c08f7fe32c17b6a00aeda2c41b4a2056
[ "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
19,428
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import data.equiv.basic algebra.field /-! # equivs in the algebraic hierarchy The role of this file is twofold. In the first part there are theorems of the following form: if α has a group structure and α ≃ β then β has a group structure, and similarly for monoids, semigroups, rings, integral domains, fields and so on. In the second part there are extensions of equiv called add_equiv, mul_equiv, and ring_equiv, which are datatypes representing isomorphisms of add_monoids/add_groups, monoids/groups and rings. ## Notations The extended equivs all have coercions to functions, and the coercions are the canonical notation when treating the isomorphisms as maps. ## Implementation notes Bundling structures means that many things turn into definitions, meaning that to_additive cannot do much work for us, and conversely that we have to do a lot of naming for it. The fields for mul_equiv and add_equiv now avoid the unbundled `is_mul_hom` and `is_add_hom`, as these are deprecated. However ring_equiv still relies on `is_ring_hom`; this should be rewritten in future. ## Tags equiv, mul_equiv, add_equiv, ring_equiv -/ universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} namespace equiv section group variables [group α] protected def mul_left (a : α) : α ≃ α := { to_fun := λx, a * x, inv_fun := λx, a⁻¹ * x, left_inv := assume x, show a⁻¹ * (a * x) = x, from inv_mul_cancel_left a x, right_inv := assume x, show a * (a⁻¹ * x) = x, from mul_inv_cancel_left a x } attribute [to_additive equiv.add_left._proof_1] equiv.mul_left._proof_1 attribute [to_additive equiv.add_left._proof_2] equiv.mul_left._proof_2 attribute [to_additive equiv.add_left] equiv.mul_left protected def mul_right (a : α) : α ≃ α := { to_fun := λx, x * a, inv_fun := λx, x * a⁻¹, left_inv := assume x, show (x * a) * a⁻¹ = x, from mul_inv_cancel_right x a, right_inv := assume x, show (x * a⁻¹) * a = x, from inv_mul_cancel_right x a } attribute [to_additive equiv.add_right._proof_1] equiv.mul_right._proof_1 attribute [to_additive equiv.add_right._proof_2] equiv.mul_right._proof_2 attribute [to_additive equiv.add_right] equiv.mul_right protected def inv (α) [group α] : α ≃ α := { to_fun := λa, a⁻¹, inv_fun := λa, a⁻¹, left_inv := assume a, inv_inv a, right_inv := assume a, inv_inv a } attribute [to_additive equiv.neg._proof_1] equiv.inv._proof_1 attribute [to_additive equiv.neg._proof_2] equiv.inv._proof_2 attribute [to_additive equiv.neg] equiv.inv def units_equiv_ne_zero (α : Type*) [field α] : units α ≃ {a : α | a ≠ 0} := ⟨λ a, ⟨a.1, units.ne_zero _⟩, λ a, units.mk0 _ a.2, λ ⟨_, _, _, _⟩, units.ext rfl, λ ⟨_, _⟩, rfl⟩ @[simp] lemma coe_units_equiv_ne_zero [field α] (a : units α) : ((units_equiv_ne_zero α a) : α) = a := rfl end group section instances variables (e : α ≃ β) protected def has_zero [has_zero β] : has_zero α := ⟨e.symm 0⟩ lemma zero_def [has_zero β] : @has_zero.zero _ (equiv.has_zero e) = e.symm 0 := rfl protected def has_one [has_one β] : has_one α := ⟨e.symm 1⟩ lemma one_def [has_one β] : @has_one.one _ (equiv.has_one e) = e.symm 1 := rfl protected def has_mul [has_mul β] : has_mul α := ⟨λ x y, e.symm (e x * e y)⟩ lemma mul_def [has_mul β] (x y : α) : @has_mul.mul _ (equiv.has_mul e) x y = e.symm (e x * e y) := rfl protected def has_add [has_add β] : has_add α := ⟨λ x y, e.symm (e x + e y)⟩ lemma add_def [has_add β] (x y : α) : @has_add.add _ (equiv.has_add e) x y = e.symm (e x + e y) := rfl protected def has_inv [has_inv β] : has_inv α := ⟨λ x, e.symm (e x)⁻¹⟩ lemma inv_def [has_inv β] (x : α) : @has_inv.inv _ (equiv.has_inv e) x = e.symm (e x)⁻¹ := rfl protected def has_neg [has_neg β] : has_neg α := ⟨λ x, e.symm (-e x)⟩ lemma neg_def [has_neg β] (x : α) : @has_neg.neg _ (equiv.has_neg e) x = e.symm (-e x) := rfl protected def semigroup [semigroup β] : semigroup α := { mul_assoc := by simp [mul_def, mul_assoc], ..equiv.has_mul e } protected def comm_semigroup [comm_semigroup β] : comm_semigroup α := { mul_comm := by simp [mul_def, mul_comm], ..equiv.semigroup e } protected def monoid [monoid β] : monoid α := { one_mul := by simp [mul_def, one_def], mul_one := by simp [mul_def, one_def], ..equiv.semigroup e, ..equiv.has_one e } protected def comm_monoid [comm_monoid β] : comm_monoid α := { ..equiv.comm_semigroup e, ..equiv.monoid e } protected def group [group β] : group α := { mul_left_inv := by simp [mul_def, inv_def, one_def], ..equiv.monoid e, ..equiv.has_inv e } protected def comm_group [comm_group β] : comm_group α := { ..equiv.group e, ..equiv.comm_semigroup e } protected def add_semigroup [add_semigroup β] : add_semigroup α := @additive.add_semigroup _ (@equiv.semigroup _ _ e multiplicative.semigroup) protected def add_comm_semigroup [add_comm_semigroup β] : add_comm_semigroup α := @additive.add_comm_semigroup _ (@equiv.comm_semigroup _ _ e multiplicative.comm_semigroup) protected def add_monoid [add_monoid β] : add_monoid α := @additive.add_monoid _ (@equiv.monoid _ _ e multiplicative.monoid) protected def add_comm_monoid [add_comm_monoid β] : add_comm_monoid α := @additive.add_comm_monoid _ (@equiv.comm_monoid _ _ e multiplicative.comm_monoid) protected def add_group [add_group β] : add_group α := @additive.add_group _ (@equiv.group _ _ e multiplicative.group) protected def add_comm_group [add_comm_group β] : add_comm_group α := @additive.add_comm_group _ (@equiv.comm_group _ _ e multiplicative.comm_group) protected def semiring [semiring β] : semiring α := { right_distrib := by simp [mul_def, add_def, add_mul], left_distrib := by simp [mul_def, add_def, mul_add], zero_mul := by simp [mul_def, zero_def], mul_zero := by simp [mul_def, zero_def], ..equiv.has_zero e, ..equiv.has_mul e, ..equiv.has_add e, ..equiv.monoid e, ..equiv.add_comm_monoid e } protected def comm_semiring [comm_semiring β] : comm_semiring α := { ..equiv.semiring e, ..equiv.comm_monoid e } protected def ring [ring β] : ring α := { ..equiv.semiring e, ..equiv.add_comm_group e } protected def comm_ring [comm_ring β] : comm_ring α := { ..equiv.comm_monoid e, ..equiv.ring e } protected def zero_ne_one_class [zero_ne_one_class β] : zero_ne_one_class α := { zero_ne_one := by simp [zero_def, one_def], ..equiv.has_zero e, ..equiv.has_one e } protected def nonzero_comm_ring [nonzero_comm_ring β] : nonzero_comm_ring α := { ..equiv.zero_ne_one_class e, ..equiv.comm_ring e } protected def domain [domain β] : domain α := { eq_zero_or_eq_zero_of_mul_eq_zero := by simp [mul_def, zero_def, equiv.eq_symm_apply], ..equiv.has_zero e, ..equiv.zero_ne_one_class e, ..equiv.has_mul e, ..equiv.ring e } protected def integral_domain [integral_domain β] : integral_domain α := { ..equiv.domain e, ..equiv.nonzero_comm_ring e } protected def division_ring [division_ring β] : division_ring α := { inv_mul_cancel := λ _, by simp [mul_def, inv_def, zero_def, one_def, (equiv.symm_apply_eq _).symm]; exact inv_mul_cancel, mul_inv_cancel := λ _, by simp [mul_def, inv_def, zero_def, one_def, (equiv.symm_apply_eq _).symm]; exact mul_inv_cancel, ..equiv.has_zero e, ..equiv.has_one e, ..equiv.domain e, ..equiv.has_inv e } protected def field [field β] : field α := { ..equiv.integral_domain e, ..equiv.division_ring e } protected def discrete_field [discrete_field β] : discrete_field α := { has_decidable_eq := equiv.decidable_eq e, inv_zero := by simp [mul_def, inv_def, zero_def], ..equiv.has_mul e, ..equiv.has_inv e, ..equiv.has_zero e, ..equiv.field e } end instances end equiv set_option old_structure_cmd true /-- mul_equiv α β is the type of an equiv α ≃ β which preserves multiplication. -/ structure mul_equiv (α β : Type*) [has_mul α] [has_mul β] extends α ≃ β := (map_mul' : ∀ x y : α, to_fun (x * y) = to_fun x * to_fun y) /-- add_equiv α β is the type of an equiv α ≃ β which preserves addition. -/ structure add_equiv (α β : Type*) [has_add α] [has_add β] extends α ≃ β := (map_add' : ∀ x y : α, to_fun (x + y) = to_fun x + to_fun y) attribute [to_additive add_equiv] mul_equiv attribute [to_additive add_equiv.cases_on] mul_equiv.cases_on attribute [to_additive add_equiv.has_sizeof_inst] mul_equiv.has_sizeof_inst attribute [to_additive add_equiv.inv_fun] mul_equiv.inv_fun attribute [to_additive add_equiv.left_inv] mul_equiv.left_inv attribute [to_additive add_equiv.mk] mul_equiv.mk attribute [to_additive add_equiv.mk.inj] mul_equiv.mk.inj attribute [to_additive add_equiv.mk.inj_arrow] mul_equiv.mk.inj_arrow attribute [to_additive add_equiv.mk.inj_eq] mul_equiv.mk.inj_eq attribute [to_additive add_equiv.mk.sizeof_spec] mul_equiv.mk.sizeof_spec attribute [to_additive add_equiv.map_add'] mul_equiv.map_mul' attribute [to_additive add_equiv.no_confusion] mul_equiv.no_confusion attribute [to_additive add_equiv.no_confusion_type] mul_equiv.no_confusion_type attribute [to_additive add_equiv.rec] mul_equiv.rec attribute [to_additive add_equiv.rec_on] mul_equiv.rec_on attribute [to_additive add_equiv.right_inv] mul_equiv.right_inv attribute [to_additive add_equiv.sizeof] mul_equiv.sizeof attribute [to_additive add_equiv.to_equiv] mul_equiv.to_equiv attribute [to_additive add_equiv.to_fun] mul_equiv.to_fun infix ` ≃* `:25 := mul_equiv infix ` ≃+ `:25 := add_equiv namespace mul_equiv @[to_additive add_equiv.has_coe_to_fun] instance {α β} [has_mul α] [has_mul β] : has_coe_to_fun (α ≃* β) := ⟨_, mul_equiv.to_fun⟩ variables [has_mul α] [has_mul β] [has_mul γ] /-- A multiplicative isomorphism preserves multiplication (canonical form). -/ def map_mul (f : α ≃* β) : ∀ x y : α, f (x * y) = f x * f y := f.map_mul' /-- A multiplicative isomorphism preserves multiplication (deprecated). -/ instance (h : α ≃* β) : is_mul_hom h := ⟨h.map_mul⟩ /-- The identity map is a multiplicative isomorphism. -/ @[refl] def refl (α : Type*) [has_mul α] : α ≃* α := { map_mul' := λ _ _,rfl, ..equiv.refl _} /-- The inverse of an isomorphism is an isomorphism. -/ @[symm] def symm (h : α ≃* β) : β ≃* α := { map_mul' := λ n₁ n₂, function.injective_of_left_inverse h.left_inv begin show h.to_equiv (h.to_equiv.symm (n₁ * n₂)) = h ((h.to_equiv.symm n₁) * (h.to_equiv.symm n₂)), rw h.map_mul, show _ = h.to_equiv (_) * h.to_equiv (_), rw [h.to_equiv.apply_symm_apply, h.to_equiv.apply_symm_apply, h.to_equiv.apply_symm_apply], end, ..h.to_equiv.symm} @[simp] theorem to_equiv_symm (f : α ≃* β) : f.symm.to_equiv = f.to_equiv.symm := rfl /-- Transitivity of multiplication-preserving isomorphisms -/ @[trans] def trans (h1 : α ≃* β) (h2 : β ≃* γ) : (α ≃* γ) := { map_mul' := λ x y, show h2 (h1 (x * y)) = h2 (h1 x) * h2 (h1 y), by rw [h1.map_mul, h2.map_mul], ..h1.to_equiv.trans h2.to_equiv } /-- e.right_inv in canonical form -/ @[simp] def apply_symm_apply (e : α ≃* β) : ∀ (y : β), e (e.symm y) = y := equiv.apply_symm_apply (e.to_equiv) /-- e.left_inv in canonical form -/ @[simp] def symm_apply_apply (e : α ≃* β) : ∀ (x : α), e.symm (e x) = x := equiv.symm_apply_apply (e.to_equiv) /-- a multiplicative equiv of monoids sends 1 to 1 (and is hence a monoid isomorphism) -/ @[simp] def map_one {α β} [monoid α] [monoid β] (h : α ≃* β) : h 1 = 1 := by rw [←mul_one (h 1), ←h.apply_symm_apply 1, ←h.map_mul, one_mul] /-- A multiplicative bijection between two monoids is an isomorphism. -/ def to_monoid_hom {α β} [monoid α] [monoid β] (h : α ≃* β) : (α →* β) := { to_fun := h, map_mul' := h.map_mul, map_one' := h.map_one } /-- A multiplicative bijection between two monoids is a monoid hom (deprecated -- use to_monoid_hom). -/ instance is_monoid_hom {α β} [monoid α] [monoid β] (h : α ≃* β) : is_monoid_hom h := ⟨h.map_one⟩ /-- A multiplicative bijection between two groups is a group hom (deprecated -- use to_monoid_hom). -/ instance is_group_hom {α β} [group α] [group β] (h : α ≃* β) : is_group_hom h := { map_mul := h.map_mul } end mul_equiv namespace add_equiv variables [has_add α] [has_add β] [has_add γ] /-- An additive isomorphism preserves addition (canonical form). -/ def map_add (f : α ≃+ β) : ∀ x y : α, f (x + y) = f x + f y := f.map_add' attribute [to_additive add_equiv.map_add] mul_equiv.map_mul attribute [to_additive add_equiv.map_add.equations._eqn_1] mul_equiv.map_mul.equations._eqn_1 /-- A additive isomorphism preserves multiplication (deprecated). -/ instance (h : α ≃+ β) : is_add_hom h := ⟨h.map_add⟩ /-- The identity map is an additive isomorphism. -/ @[refl] def refl (α : Type*) [has_add α] : α ≃+ α := { map_add' := λ _ _,rfl, ..equiv.refl _} attribute [to_additive add_equiv.refl] mul_equiv.refl attribute [to_additive add_equiv.refl._proof_1] mul_equiv.refl._proof_1 attribute [to_additive add_equiv.refl._proof_2] mul_equiv.refl._proof_2 attribute [to_additive add_equiv.refl._proof_3] mul_equiv.refl._proof_3 attribute [to_additive add_equiv.refl.equations._eqn_1] mul_equiv.refl.equations._eqn_1 /-- The inverse of an isomorphism is an isomorphism. -/ @[symm] def symm (h : α ≃+ β) : β ≃+ α := { map_add' := λ n₁ n₂, function.injective_of_left_inverse h.left_inv begin show h.to_equiv (h.to_equiv.symm (n₁ + n₂)) = h ((h.to_equiv.symm n₁) + (h.to_equiv.symm n₂)), rw h.map_add, show _ = h.to_equiv (_) + h.to_equiv (_), rw [h.to_equiv.apply_symm_apply, h.to_equiv.apply_symm_apply, h.to_equiv.apply_symm_apply], end, ..h.to_equiv.symm} attribute [to_additive add_equiv.symm] mul_equiv.symm attribute [to_additive add_equiv.symm._proof_1] mul_equiv.symm._proof_1 attribute [to_additive add_equiv.symm._proof_2] mul_equiv.symm._proof_2 attribute [to_additive add_equiv.symm._proof_3] mul_equiv.symm._proof_3 attribute [to_additive add_equiv.symm.equations._eqn_1] mul_equiv.symm.equations._eqn_1 @[simp] theorem to_equiv_symm (f : α ≃+ β) : f.symm.to_equiv = f.to_equiv.symm := rfl attribute [to_additive add_equiv.to_equiv_symm] mul_equiv.to_equiv_symm /-- Transitivity of addition-preserving isomorphisms -/ @[trans] def trans (h1 : α ≃+ β) (h2 : β ≃+ γ) : (α ≃+ γ) := { map_add' := λ x y, show h2 (h1 (x + y)) = h2 (h1 x) + h2 (h1 y), by rw [h1.map_add, h2.map_add], ..h1.to_equiv.trans h2.to_equiv } attribute [to_additive add_equiv.trans] mul_equiv.trans attribute [to_additive add_equiv.trans._proof_1] mul_equiv.trans._proof_1 attribute [to_additive add_equiv.trans._proof_2] mul_equiv.trans._proof_2 attribute [to_additive add_equiv.trans._proof_3] mul_equiv.trans._proof_3 attribute [to_additive add_equiv.trans.equations._eqn_1] mul_equiv.trans.equations._eqn_1 /-- e.right_inv in canonical form -/ def apply_symm_apply (e : α ≃+ β) : ∀ (y : β), e (e.symm y) = y := equiv.apply_symm_apply (e.to_equiv) attribute [to_additive add_equiv.apply_symm_apply] mul_equiv.apply_symm_apply attribute [to_additive add_equiv.apply_symm_apply.equations._eqn_1] mul_equiv.apply_symm_apply.equations._eqn_1 /-- e.left_inv in canonical form -/ def symm_apply_apply (e : α ≃+ β) : ∀ (x : α), e.symm (e x) = x := equiv.symm_apply_apply (e.to_equiv) attribute [to_additive add_equiv.symm_apply_apply] mul_equiv.symm_apply_apply attribute [to_additive add_equiv.symm_apply_apply.equations._eqn_1] mul_equiv.symm_apply_apply.equations._eqn_1 /-- an additive equiv of monoids sends 0 to 0 (and is hence an `add_monoid` isomorphism) -/ def map_zero {α β} [add_monoid α] [add_monoid β] (h : α ≃+ β) : h 0 = 0 := by rw [←add_zero (h 0), ←h.apply_symm_apply 0, ←h.map_add, zero_add] attribute [to_additive add_equiv.map_zero] mul_equiv.map_one attribute [to_additive add_equiv.map_zero.equations._eqn_1] mul_equiv.map_one.equations._eqn_1 /-- An additive bijection between two add_monoids is an isomorphism. -/ def to_add_monoid_hom {α β} [add_monoid α] [add_monoid β] (h : α ≃+ β) : (α →+ β) := { to_fun := h, map_add' := h.map_add, map_zero' := h.map_zero } attribute [to_additive add_equiv.to_add_monoid_hom] mul_equiv.to_monoid_hom attribute [to_additive add_equiv.to_add_monoid_hom._proof_1] mul_equiv.to_monoid_hom._proof_1 attribute [to_additive add_equiv.to_add_monoid_hom.equations._eqn_1] mul_equiv.to_monoid_hom.equations._eqn_1 /-- an additive bijection between two add_monoids is an add_monoid hom (deprecated -- use to_add_monoid_hom) -/ instance is_add_monoid_hom {α β} [add_monoid α] [add_monoid β] (h : α ≃+ β) : is_add_monoid_hom h := ⟨h.map_zero⟩ attribute [to_additive add_equiv.is_add_monoid_hom] mul_equiv.is_monoid_hom attribute [to_additive add_equiv.is_add_monoid_hom.equations._eqn_1] mul_equiv.is_monoid_hom.equations._eqn_1 /-- An additive bijection between two add_groups is an add_group hom (deprecated -- use to_monoid_hom). -/ instance is_add_group_hom {α β} [add_group α] [add_group β] (h : α ≃+ β) : is_add_group_hom h := { map_add := h.map_add } attribute [to_additive add_equiv.is_add_group_hom] mul_equiv.is_group_hom attribute [to_additive add_equiv.is_add_group_hom.equations._eqn_1] mul_equiv.is_group_hom.equations._eqn_1 end add_equiv namespace units variables [monoid α] [monoid β] [monoid γ] (f : α → β) (g : β → γ) [is_monoid_hom f] [is_monoid_hom g] def map_equiv (h : α ≃* β) : units α ≃* units β := { to_fun := map h, inv_fun := map h.symm, left_inv := λ u, ext $ h.left_inv u, right_inv := λ u, ext $ h.right_inv u, map_mul' := λ a b, units.ext $ h.map_mul a b} end units structure ring_equiv (α β : Type*) [ring α] [ring β] extends α ≃ β := (hom : is_ring_hom to_fun) infix ` ≃r `:25 := ring_equiv namespace ring_equiv variables [ring α] [ring β] [ring γ] instance (h : α ≃r β) : is_ring_hom h.to_equiv := h.hom instance ring_equiv.is_ring_hom' (h : α ≃r β) : is_ring_hom h.to_fun := h.hom def to_mul_equiv (e : α ≃r β) : α ≃* β := { map_mul' := e.hom.map_mul, .. e.to_equiv } def to_add_equiv (e : α ≃r β) : α ≃+ β := { map_add' := e.hom.map_add, .. e.to_equiv } protected def refl (α : Type*) [ring α] : α ≃r α := { hom := is_ring_hom.id, .. equiv.refl α } protected def symm {α β : Type*} [ring α] [ring β] (e : α ≃r β) : β ≃r α := { hom := { map_one := e.to_mul_equiv.symm.map_one, map_mul := e.to_mul_equiv.symm.map_mul, map_add := e.to_add_equiv.symm.map_add }, .. e.to_equiv.symm } protected def trans {α β γ : Type*} [ring α] [ring β] [ring γ] (e₁ : α ≃r β) (e₂ : β ≃r γ) : α ≃r γ := { hom := is_ring_hom.comp _ _, .. e₁.to_equiv.trans e₂.to_equiv } instance symm.is_ring_hom {e : α ≃r β} : is_ring_hom e.to_equiv.symm := hom e.symm @[simp] lemma to_equiv_symm (e : α ≃r β) : e.symm.to_equiv = e.to_equiv.symm := rfl @[simp] lemma to_equiv_symm_apply (e : α ≃r β) (x : β) : e.symm.to_equiv x = e.to_equiv.symm x := rfl end ring_equiv
dc87b40f5d99bf30720031ade1ec5df59d68c161
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
/order/conditionally_complete_lattice.lean
19c6f7def948e204b85ce7d500da9a63dee68375
[ "Apache-2.0" ]
permissive
kckennylau/mathlib
21fb810b701b10d6606d9002a4004f7672262e83
47b3477e20ffb5a06588dd3abb01fe0fe3205646
refs/heads/master
1,634,976,409,281
1,542,042,832,000
1,542,319,733,000
109,560,458
0
0
Apache-2.0
1,542,369,208,000
1,509,867,494,000
Lean
UTF-8
Lean
false
false
30,239
lean
/- Copyright (c) 2018 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel Adapted from the corresponding theory for complete lattices. Theory of conditionally complete lattices. A conditionally complete lattice is a lattice in which every non-empty bounded subset s has a least upper bound and a greatest lower bound, denoted below by Sup s and Inf s. Typical examples are real, nat, int with their usual orders. The theory is very comparable to the theory of complete lattices, except that suitable boundedness and non-emptyness assumptions have to be added to most statements. We introduce two predicates bdd_above and bdd_below to express this boundedness, prove their basic properties, and then go on to prove most useful properties of Sup and Inf in conditionally complete lattices. To differentiate the statements between complete lattices and conditionally complete lattices, we prefix Inf and Sup in the statements by c, giving cInf and cSup. For instance, Inf_le is a statement in complete lattices ensuring Inf s ≤ x, while cInf_le is the same statement in conditionally complete lattices with an additional assumption that s is bounded below. -/ import order.lattice order.complete_lattice order.bounds tactic.finish data.set.countable set_option old_structure_cmd true open preorder set lattice universes u v variables {α : Type u} {β : Type v} section preorder variables [preorder α] {s t : set α} {a b : α} /-Sets bounded above and bounded below.-/ def bdd_above (s : set α) := ∃x, ∀y∈s, y ≤ x def bdd_below (s : set α) := ∃x, ∀y∈s, x ≤ y /-Introduction rules for boundedness above and below. Most of the time, it is more efficient to use ⟨w, P⟩ where P is a proof that all elements of the set are bounded by w. However, they are sometimes handy.-/ lemma bdd_above.mk (a : α) (H : ∀y∈s, y≤a) : bdd_above s := ⟨a, H⟩ lemma bdd_below.mk (a : α) (H : ∀y∈s, a≤y) : bdd_below s := ⟨a, H⟩ /-Empty sets and singletons are trivially bounded. For finite sets, we need a notion of maximum and minimum, i.e., a lattice structure, see later on.-/ @[simp] lemma bdd_above_empty [inhabited α] : bdd_above (∅ : set α) := ⟨default α, by simp only [set.mem_empty_eq, forall_const, forall_prop_of_false, not_false_iff]⟩ @[simp] lemma bdd_below_empty [inhabited α] : bdd_below (∅ : set α) := ⟨default α, by simp only [set.mem_empty_eq, forall_const, forall_prop_of_false, not_false_iff]⟩ @[simp] lemma bdd_above_singleton : bdd_above ({a} : set α) := ⟨a, by simp only [set.mem_singleton_iff, forall_eq]⟩ @[simp] lemma bdd_below_singleton : bdd_below ({a} : set α) := ⟨a, by simp only [set.mem_singleton_iff, forall_eq]⟩ /-If a set is included in another one, boundedness of the second implies boundedness of the first-/ lemma bdd_above_subset (st : s ⊆ t) : bdd_above t → bdd_above s | ⟨w, hw⟩ := ⟨w, λ y ys, hw _ (st ys)⟩ lemma bdd_below_subset (st : s ⊆ t) : bdd_below t → bdd_below s | ⟨w, hw⟩ := ⟨w, λ y ys, hw _ (st ys)⟩ /- Boundedness of intersections of sets, in different guises, deduced from the monotonicity of boundedness.-/ lemma bdd_above_Int1 (_ : bdd_above s) : bdd_above (s ∩ t) := by apply bdd_above_subset _ ‹bdd_above s›; simp only [set.inter_subset_left] lemma bdd_above_Int2 (_ : bdd_above t) : bdd_above (s ∩ t) := by apply bdd_above_subset _ ‹bdd_above t›; simp only [set.inter_subset_right] lemma bdd_below_Int1 (_ : bdd_below s) : bdd_below (s ∩ t) := by apply bdd_below_subset _ ‹bdd_below s›; simp only [set.inter_subset_left] lemma bdd_below_Int2 (_ : bdd_below t) : bdd_below (s ∩ t) := by apply bdd_below_subset _ ‹bdd_below t›; simp only [set.inter_subset_right] end preorder /--When there is a global maximum, every set is bounded above.-/ @[simp] lemma bdd_above_top [order_top α] (s : set α) : bdd_above s := ⟨⊤, by intros; apply order_top.le_top⟩ /--When there is a global minimum, every set is bounded below.-/ @[simp] lemma bdd_below_bot [order_bot α] (s : set α): bdd_below s := ⟨⊥, by intros; apply order_bot.bot_le⟩ /-When there is a max (i.e., in the class semilattice_sup), then the union of two bounded sets is bounded, by the maximum of the bounds for the two sets. With this, we deduce that finite sets are bounded by induction, and that a finite union of bounded sets is bounded.-/ section semilattice_sup variables [semilattice_sup α] {s t : set α} {a b : α} /--The union of two sets is bounded above if and only if each of the sets is.-/ @[simp] lemma bdd_above_union : bdd_above (s ∪ t) ↔ bdd_above s ∧ bdd_above t := ⟨show bdd_above (s ∪ t) → (bdd_above s ∧ bdd_above t), from assume : bdd_above (s ∪ t), have S : bdd_above s, by apply bdd_above_subset _ ‹bdd_above (s ∪ t)›; simp only [set.subset_union_left], have T : bdd_above t, by apply bdd_above_subset _ ‹bdd_above (s ∪ t)›; simp only [set.subset_union_right], and.intro S T, show (bdd_above s ∧ bdd_above t) → bdd_above (s ∪ t), from assume H : bdd_above s ∧ bdd_above t, let ⟨⟨ws, hs⟩, ⟨wt, ht⟩⟩ := H in /-hs : ∀ (y : α), y ∈ s → y ≤ ws ht : ∀ (y : α), y ∈ s → y ≤ wt-/ have Bs : ∀b∈s, b ≤ ws ⊔ wt, by intros; apply le_trans (hs b ‹b ∈ s›) _; simp only [lattice.le_sup_left], have Bt : ∀b∈t, b ≤ ws ⊔ wt, by intros; apply le_trans (ht b ‹b ∈ t›) _; simp only [lattice.le_sup_right], show bdd_above (s ∪ t), begin apply bdd_above.mk (ws ⊔ wt), intros b H_1, cases H_1, apply Bs _ ‹b ∈ s›, apply Bt _ ‹b ∈ t›, end⟩ /--Adding a point to a set preserves its boundedness above.-/ @[simp] lemma bdd_above_insert : bdd_above (insert a s) ↔ bdd_above s := ⟨bdd_above_subset (by simp only [set.subset_insert]), λ h, by rw [insert_eq, bdd_above_union]; exact ⟨bdd_above_singleton, h⟩⟩ /--A finite set is bounded above.-/ lemma bdd_above_finite [inhabited α] (hs : finite s) : bdd_above s := finite.induction_on hs bdd_above_empty $ λ a s _ _, bdd_above_insert.2 /--A finite union of sets which are all bounded above is still bounded above.-/ lemma bdd_above_finite_union [inhabited α] {β : Type v} {I : set β} {S : β → set α} (H : finite I) : (bdd_above (⋃i∈I, S i)) ↔ (∀i ∈ I, bdd_above (S i)) := ⟨show (bdd_above (⋃i∈I, S i)) → (∀i ∈ I, bdd_above (S i)), by intros; apply bdd_above_subset _ ‹bdd_above (⋃i∈I, S i)›; apply subset_bUnion_of_mem ‹i ∈ I›, show (∀i ∈ I, bdd_above (S i)) → (bdd_above (⋃i∈I, S i)), by apply finite.induction_on ‹finite I›; simp only [set.mem_insert_iff, set.bUnion_insert, bdd_above_union,forall_prop_of_true, set.mem_empty_eq,set.Union_empty,forall_prop_of_false,bdd_above_empty, set.Union_neg,not_false_iff,forall_true_iff]; finish⟩ end semilattice_sup /-When there is a min (i.e., in the class semilattice_inf), then the union of two sets which are bounded from below is bounded from below, by the minimum of the bounds for the two sets. With this, we deduce that finite sets are bounded below by induction, and that a finite union of sets which are bounded below is still bounded below.-/ section semilattice_inf variables [semilattice_inf α] {s t : set α} {a b : α} /--The union of two sets is bounded below if and only if each of the sets is.-/ @[simp] lemma bdd_below_union : bdd_below (s ∪ t) ↔ bdd_below s ∧ bdd_below t := ⟨show bdd_below (s ∪ t) → (bdd_below s ∧ bdd_below t), from assume : bdd_below (s ∪ t), have S : bdd_below s, by apply bdd_below_subset _ ‹bdd_below (s ∪ t)›; simp only [set.subset_union_left], have T : bdd_below t, by apply bdd_below_subset _ ‹bdd_below (s ∪ t)›; simp only [set.subset_union_right], and.intro S T, show (bdd_below s ∧ bdd_below t) → bdd_below (s ∪ t), from assume H : bdd_below s ∧ bdd_below t, let ⟨⟨ws, hs⟩, ⟨wt, ht⟩⟩ := H in /-hs : ∀ (y : α), y ∈ s → ws ≤ y ht : ∀ (y : α), y ∈ s → wt ≤ y-/ have Bs : ∀b∈s, ws ⊓ wt ≤ b, by intros; apply le_trans _ (hs b ‹b ∈ s›); simp only [lattice.inf_le_left], have Bt : ∀b∈t, ws ⊓ wt ≤ b, by intros; apply le_trans _ (ht b ‹b ∈ t›); simp only [lattice.inf_le_right], show bdd_below (s ∪ t), begin apply bdd_below.mk (ws ⊓ wt), intros b H_1, cases H_1, apply Bs _ ‹b ∈ s›, apply Bt _ ‹b ∈ t›, end⟩ /--Adding a point to a set preserves its boundedness below.-/ @[simp] lemma bdd_below_insert : bdd_below (insert a s) ↔ bdd_below s := ⟨show bdd_below (insert a s) → bdd_below s, from bdd_below_subset (by simp only [set.subset_insert]), show bdd_below s → bdd_below (insert a s), by rw[insert_eq]; simp only [bdd_below_singleton, bdd_below_union, and_self, forall_true_iff] {contextual := tt}⟩ /--A finite set is bounded below.-/ lemma bdd_below_finite [inhabited α] (_ : finite s) : bdd_below s := by apply finite.induction_on ‹finite s›; simp only [imp_self, forall_const, bdd_below_insert, forall_true_iff,bdd_below_empty] /--A finite union of sets which are all bounded below is still bounded below.-/ lemma bdd_below_finite_union [inhabited α] {β : Type v} {I : set β} {S : β → set α} (H : finite I) : (bdd_below (⋃i∈I, S i)) ↔ (∀i ∈ I, bdd_below (S i)) := ⟨show (bdd_below (⋃i∈I, S i)) → (∀i ∈ I, bdd_below (S i)), by intros; apply bdd_below_subset _ ‹bdd_below (⋃i∈I, S i)›; apply subset_bUnion_of_mem ‹i ∈ I›, show (∀i ∈ I, bdd_below (S i)) → (bdd_below (⋃i∈I, S i)), by apply finite.induction_on ‹finite I›; simp only [set.mem_insert_iff, set.bUnion_insert, bdd_below_union, forall_prop_of_true,set.mem_empty_eq,set.Union_empty, forall_prop_of_false,bdd_below_empty,set.Union_neg, not_false_iff,forall_true_iff]; finish⟩ end semilattice_inf namespace lattice /-- A conditionally complete lattice is a lattice in which every nonempty subset which is bounded above has a supremum, and every nonempty subset which is bounded below has an infimum. Typical examples are real numbers or natural numbers. To differentiate the statements from the corresponding statements in (unconditional) complete lattices, we prefix Inf and Sup by a c everywhere. The same statements should hold in both worlds, sometimes with additional assumptions of non-emptyness or boundedness.-/ class conditionally_complete_lattice (α : Type u) extends lattice α, has_Sup α, has_Inf α := (le_cSup : ∀s a, bdd_above s → a ∈ s → a ≤ Sup s) (cSup_le : ∀s a, s ≠ ∅ → (∀b∈s, b ≤ a) → Sup s ≤ a) (cInf_le : ∀s a, bdd_below s → a ∈ s → Inf s ≤ a) (le_cInf : ∀s a, s ≠ ∅ → (∀b∈s, a ≤ b) → a ≤ Inf s) class conditionally_complete_linear_order (α : Type u) extends conditionally_complete_lattice α, linear_order α class conditionally_complete_linear_order_bot (α : Type u) extends conditionally_complete_lattice α, linear_order α, order_bot α := (cSup_empty : Sup ∅ = ⊥) /- A complete lattice is a conditionally complete lattice, as there are no restrictions on the properties of Inf and Sup in a complete lattice.-/ instance conditionally_complete_lattice_of_complete_lattice [complete_lattice α]: conditionally_complete_lattice α := { le_cSup := by intros; apply le_Sup; assumption, cSup_le := by intros; apply Sup_le; assumption, cInf_le := by intros; apply Inf_le; assumption, le_cInf := by intros; apply le_Inf; assumption, ..‹complete_lattice α›} instance conditionally_complete_linear_order_of_complete_linear_order [complete_linear_order α]: conditionally_complete_linear_order α := { ..lattice.conditionally_complete_lattice_of_complete_lattice, .. ‹complete_linear_order α› } section conditionally_complete_lattice variables [conditionally_complete_lattice α] {s t : set α} {a b : α} theorem le_cSup (h₁ : bdd_above s) (h₂ : a ∈ s) : a ≤ Sup s := conditionally_complete_lattice.le_cSup s a h₁ h₂ theorem cSup_le (h₁ : s ≠ ∅) (h₂ : ∀b∈s, b ≤ a) : Sup s ≤ a := conditionally_complete_lattice.cSup_le s a h₁ h₂ theorem cInf_le (h₁ : bdd_below s) (h₂ : a ∈ s) : Inf s ≤ a := conditionally_complete_lattice.cInf_le s a h₁ h₂ theorem le_cInf (h₁ : s ≠ ∅) (h₂ : ∀b∈s, a ≤ b) : a ≤ Inf s := conditionally_complete_lattice.le_cInf s a h₁ h₂ theorem le_cSup_of_le (_ : bdd_above s) (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s := le_trans h (le_cSup ‹bdd_above s› hb) theorem cInf_le_of_le (_ : bdd_below s) (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a := le_trans (cInf_le ‹bdd_below s› hb) h theorem cSup_le_cSup (_ : bdd_above t) (_ : s ≠ ∅) (h : s ⊆ t) : Sup s ≤ Sup t := cSup_le ‹s ≠ ∅› (assume (a) (ha : a ∈ s), le_cSup ‹bdd_above t› (h ha)) theorem cInf_le_cInf (_ : bdd_below t) (_ :s ≠ ∅) (h : s ⊆ t) : Inf t ≤ Inf s := le_cInf ‹s ≠ ∅› (assume (a) (ha : a ∈ s), cInf_le ‹bdd_below t› (h ha)) theorem cSup_le_iff (_ : bdd_above s) (_ : s ≠ ∅) : Sup s ≤ a ↔ (∀b ∈ s, b ≤ a) := ⟨assume (_ : Sup s ≤ a) (b) (_ : b ∈ s), le_trans (le_cSup ‹bdd_above s› ‹b ∈ s›) ‹Sup s ≤ a›, cSup_le ‹s ≠ ∅›⟩ theorem le_cInf_iff (_ : bdd_below s) (_ : s ≠ ∅) : a ≤ Inf s ↔ (∀b ∈ s, a ≤ b) := ⟨assume (_ : a ≤ Inf s) (b) (_ : b ∈ s), le_trans ‹a ≤ Inf s› (cInf_le ‹bdd_below s› ‹b ∈ s›), le_cInf ‹s ≠ ∅›⟩ lemma cSup_upper_bounds_eq_cInf {s : set α} (h : bdd_below s) (hs : s ≠ ∅) : Sup {a | ∀x∈s, a ≤ x} = Inf s := let ⟨b, hb⟩ := h, ⟨a, ha⟩ := ne_empty_iff_exists_mem.1 hs in le_antisymm (cSup_le (ne_empty_iff_exists_mem.2 ⟨b, hb⟩) $ assume a ha, le_cInf hs ha) (le_cSup ⟨a, assume y hy, hy a ha⟩ $ assume x hx, cInf_le h hx) lemma cInf_lower_bounds_eq_cSup {s : set α} (h : bdd_above s) (hs : s ≠ ∅) : Inf {a | ∀x∈s, x ≤ a} = Sup s := let ⟨b, hb⟩ := h, ⟨a, ha⟩ := ne_empty_iff_exists_mem.1 hs in le_antisymm (cInf_le ⟨a, assume y hy, hy a ha⟩ $ assume x hx, le_cSup h hx) (le_cInf (ne_empty_iff_exists_mem.2 ⟨b, hb⟩) $ assume a ha, cSup_le hs ha) /--Introduction rule to prove that b is the supremum of s: it suffices to check that b is larger than all elements of s, and that this is not the case of any w<b.-/ theorem cSup_intro (_ : s ≠ ∅) (_ : ∀a∈s, a ≤ b) (H : ∀w, w < b → (∃a∈s, w < a)) : Sup s = b := have bdd_above s := ⟨b, by assumption⟩, have (Sup s < b) ∨ (Sup s = b) := lt_or_eq_of_le (cSup_le ‹s ≠ ∅› ‹∀a∈s, a ≤ b›), have ¬(Sup s < b) := assume: Sup s < b, let ⟨a, _, _⟩ := (H (Sup s) ‹Sup s < b›) in /- a ∈ s, Sup s < a-/ have Sup s < Sup s := lt_of_lt_of_le ‹Sup s < a› (le_cSup ‹bdd_above s› ‹a ∈ s›), show false, by finish [lt_irrefl (Sup s)], show Sup s = b, by finish /--Introduction rule to prove that b is the infimum of s: it suffices to check that b is smaller than all elements of s, and that this is not the case of any w>b.-/ theorem cInf_intro (_ : s ≠ ∅) (_ : ∀a∈s, b ≤ a) (H : ∀w, b < w → (∃a∈s, a < w)) : Inf s = b := have bdd_below s := ⟨b, by assumption⟩, have (b < Inf s) ∨ (b = Inf s) := lt_or_eq_of_le (le_cInf ‹s ≠ ∅› ‹∀a∈s, b ≤ a›), have ¬(b < Inf s) := assume: b < Inf s, let ⟨a, _, _⟩ := (H (Inf s) ‹b < Inf s›) in /- a ∈ s, a < Inf s-/ have Inf s < Inf s := lt_of_le_of_lt (cInf_le ‹bdd_below s› ‹a ∈ s›) ‹a < Inf s› , show false, by finish [lt_irrefl (Inf s)], show Inf s = b, by finish /--When an element a of a set s is larger than all elements of the set, it is Sup s-/ theorem cSup_of_in_of_le (_ : a ∈ s) (_ : ∀w∈s, w ≤ a) : Sup s = a := have bdd_above s := ⟨a, by assumption⟩, have s ≠ ∅ := ne_empty_of_mem ‹a ∈ s›, have A : a ≤ Sup s := le_cSup ‹bdd_above s› ‹a ∈ s›, have B : Sup s ≤ a := cSup_le ‹s ≠ ∅› ‹∀w∈s, w ≤ a›, le_antisymm B A /--When an element a of a set s is smaller than all elements of the set, it is Inf s-/ theorem cInf_of_in_of_le (_ : a ∈ s) (_ : ∀w∈s, a ≤ w) : Inf s = a := have bdd_below s := ⟨a, by assumption⟩, have s ≠ ∅ := ne_empty_of_mem ‹a ∈ s›, have A : Inf s ≤ a := cInf_le ‹bdd_below s› ‹a ∈ s›, have B : a ≤ Inf s := le_cInf ‹s ≠ ∅› ‹∀w∈s, a ≤ w›, le_antisymm A B /--b < Sup s when there is an element a in s with b < a, when s is bounded above. This is essentially an iff, except that the assumptions for the two implications are slightly different (one needs boundedness above for one direction, nonemptyness and linear order for the other one), so we formulate separately the two implications, contrary to the complete_lattice case.-/ lemma lt_cSup_of_lt (_ : bdd_above s) (_ : a ∈ s) (_ : b < a) : b < Sup s := lt_of_lt_of_le ‹b < a› (le_cSup ‹bdd_above s› ‹a ∈ s›) /--Inf s < b s when there is an element a in s with a < b, when s is bounded below. This is essentially an iff, except that the assumptions for the two implications are slightly different (one needs boundedness below for one direction, nonemptyness and linear order for the other one), so we formulate separately the two implications, contrary to the complete_lattice case.-/ lemma cInf_lt_of_lt (_ : bdd_below s) (_ : a ∈ s) (_ : a < b) : Inf s < b := lt_of_le_of_lt (cInf_le ‹bdd_below s› ‹a ∈ s›) ‹a < b› /--The supremum of a singleton is the element of the singleton-/ @[simp] theorem cSup_singleton (a : α) : Sup {a} = a := have A : a ≤ Sup {a} := by apply le_cSup _ _; simp only [set.mem_singleton,bdd_above_singleton], have B : Sup {a} ≤ a := by apply cSup_le _ _; simp only [set.mem_singleton_iff, forall_eq,ne.def, not_false_iff, set.singleton_ne_empty], le_antisymm B A /--The infimum of a singleton is the element of the singleton-/ @[simp] theorem cInf_singleton (a : α) : Inf {a} = a := have A : Inf {a} ≤ a := by apply cInf_le _ _; simp only [set.mem_singleton,bdd_below_singleton], have B : a ≤ Inf {a} := by apply le_cInf _ _; simp only [set.mem_singleton_iff, forall_eq,ne.def, not_false_iff, set.singleton_ne_empty], le_antisymm A B /--If a set is bounded below and above, and nonempty, its infimum is less than or equal to its supremum.-/ theorem cInf_le_cSup (_ : bdd_below s) (_ : bdd_above s) (_ : s ≠ ∅) : Inf s ≤ Sup s := let ⟨w, hw⟩ := exists_mem_of_ne_empty ‹s ≠ ∅› in /-hw : w ∈ s-/ have Inf s ≤ w := cInf_le ‹bdd_below s› ‹w ∈ s›, have w ≤ Sup s := le_cSup ‹bdd_above s› ‹w ∈ s›, le_trans ‹Inf s ≤ w› ‹w ≤ Sup s› /--The sup of a union of sets is the max of the suprema of each subset, under the assumptions that all sets are bounded above and nonempty.-/ theorem cSup_union (_ : bdd_above s) (_ : s ≠ ∅) (_ : bdd_above t) (_ : t ≠ ∅) : Sup (s ∪ t) = Sup s ⊔ Sup t := have A : Sup (s ∪ t) ≤ Sup s ⊔ Sup t := have s ∪ t ≠ ∅ := by simp only [not_and, set.union_empty_iff, ne.def] at *; finish, have F : ∀b∈ s∪t, b ≤ Sup s ⊔ Sup t := begin intros, cases H, apply le_trans (le_cSup ‹bdd_above s› ‹b ∈ s›) _, simp only [lattice.le_sup_left], apply le_trans (le_cSup ‹bdd_above t› ‹b ∈ t›) _, simp only [lattice.le_sup_right] end, cSup_le this F, have B : Sup s ⊔ Sup t ≤ Sup (s ∪ t) := have Sup s ≤ Sup (s ∪ t) := by apply cSup_le_cSup _ ‹s ≠ ∅›; simp only [bdd_above_union,set.subset_union_left]; finish, have Sup t ≤ Sup (s ∪ t) := by apply cSup_le_cSup _ ‹t ≠ ∅›; simp only [bdd_above_union,set.subset_union_right]; finish, by simp only [lattice.sup_le_iff]; split; assumption; assumption, le_antisymm A B /--The inf of a union of sets is the min of the infima of each subset, under the assumptions that all sets are bounded below and nonempty.-/ theorem cInf_union (_ : bdd_below s) (_ : s ≠ ∅) (_ : bdd_below t) (_ : t ≠ ∅) : Inf (s ∪ t) = Inf s ⊓ Inf t := have A : Inf s ⊓ Inf t ≤ Inf (s ∪ t) := have s ∪ t ≠ ∅ := by simp only [not_and, set.union_empty_iff, ne.def] at *; finish, have F : ∀b∈ s∪t, Inf s ⊓ Inf t ≤ b := begin intros, cases H, apply le_trans _ (cInf_le ‹bdd_below s› ‹b ∈ s›), simp only [lattice.inf_le_left], apply le_trans _ (cInf_le ‹bdd_below t› ‹b ∈ t›), simp only [lattice.inf_le_right] end, le_cInf this F, have B : Inf (s ∪ t) ≤ Inf s ⊓ Inf t := have Inf (s ∪ t) ≤ Inf s := by apply cInf_le_cInf _ ‹s ≠ ∅›; simp only [bdd_below_union,set.subset_union_left]; finish, have Inf (s ∪ t) ≤ Inf t := by apply cInf_le_cInf _ ‹t ≠ ∅›; simp only [bdd_below_union,set.subset_union_right]; finish, by simp only [lattice.le_inf_iff]; split; assumption; assumption, le_antisymm B A /--The supremum of an intersection of sets is bounded by the minimum of the suprema of each set, if all sets are bounded above and nonempty.-/ theorem cSup_inter_le (_ : bdd_above s) (_ : bdd_above t) (_ : s ∩ t ≠ ∅) : Sup (s ∩ t) ≤ Sup s ⊓ Sup t := begin apply cSup_le ‹s ∩ t ≠ ∅› _, simp only [lattice.le_inf_iff, and_imp, set.mem_inter_eq], intros b _ _, split, apply le_cSup ‹bdd_above s› ‹b ∈ s›, apply le_cSup ‹bdd_above t› ‹b ∈ t› end /--The infimum of an intersection of sets is bounded below by the maximum of the infima of each set, if all sets are bounded below and nonempty.-/ theorem le_cInf_inter (_ : bdd_below s) (_ : bdd_below t) (_ : s ∩ t ≠ ∅) : Inf s ⊔ Inf t ≤ Inf (s ∩ t) := begin apply le_cInf ‹s ∩ t ≠ ∅› _, simp only [and_imp, set.mem_inter_eq, lattice.sup_le_iff], intros b _ _, split, apply cInf_le ‹bdd_below s› ‹b ∈ s›, apply cInf_le ‹bdd_below t› ‹b ∈ t› end /-- The supremum of insert a s is the maximum of a and the supremum of s, if s is nonempty and bounded above.-/ theorem cSup_insert (_ : bdd_above s) (_ : s ≠ ∅) : Sup (insert a s) = a ⊔ Sup s := calc Sup (insert a s) = Sup ({a} ∪ s) : by rw [insert_eq] ... = Sup {a} ⊔ Sup s : by apply cSup_union _ _ ‹bdd_above s› ‹s ≠ ∅›; simp only [ne.def, not_false_iff, set.singleton_ne_empty,bdd_above_singleton] ... = a ⊔ Sup s : by simp only [eq_self_iff_true, lattice.cSup_singleton] /-- The infimum of insert a s is the minimum of a and the infimum of s, if s is nonempty and bounded below.-/ theorem cInf_insert (_ : bdd_below s) (_ : s ≠ ∅) : Inf (insert a s) = a ⊓ Inf s := calc Inf (insert a s) = Inf ({a} ∪ s) : by rw [insert_eq] ... = Inf {a} ⊓ Inf s : by apply cInf_union _ _ ‹bdd_below s› ‹s ≠ ∅›; simp only [ne.def, not_false_iff, set.singleton_ne_empty,bdd_below_singleton] ... = a ⊓ Inf s : by simp only [eq_self_iff_true, lattice.cInf_singleton] @[simp] lemma cInf_interval [conditionally_complete_lattice α] : Inf {b | a ≤ b} = a := cInf_of_in_of_le (by simp only [set.mem_set_of_eq]) (λw Hw, by simp only [set.mem_set_of_eq] at Hw; apply Hw) @[simp] lemma cSup_interval [conditionally_complete_lattice α] : Sup {b | b ≤ a} = a := cSup_of_in_of_le (by simp only [set.mem_set_of_eq]) (λw Hw, by simp only [set.mem_set_of_eq] at Hw; apply Hw) end conditionally_complete_lattice section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] {s t : set α} {a b : α} /--When b < Sup s, there is an element a in s with b < a, if s is nonempty and the order is a linear order.-/ lemma exists_lt_of_lt_cSup (_ : s ≠ ∅) (_ : b < Sup s) : ∃a∈s, b < a := begin apply classical.by_contradiction, assume : ¬ (∃a∈s, b < a), have : Sup s ≤ b := by apply cSup_le ‹s ≠ ∅› _; finish, apply lt_irrefl b (lt_of_lt_of_le ‹b < Sup s› ‹Sup s ≤ b›) end /--When Inf s < b, there is an element a in s with a < b, if s is nonempty and the order is a linear order.-/ lemma exists_lt_of_cInf_lt (_ : s ≠ ∅) (_ : Inf s < b) : ∃a∈s, a < b := begin apply classical.by_contradiction, assume : ¬ (∃a∈s, a < b), have : b ≤ Inf s := by apply le_cInf ‹s ≠ ∅› _; finish, apply lt_irrefl b (lt_of_le_of_lt ‹b ≤ Inf s› ‹Inf s < b›) end end conditionally_complete_linear_order section conditionally_complete_linear_order_bot variables [conditionally_complete_linear_order_bot α] lemma cSup_empty [conditionally_complete_linear_order_bot α] : (Sup ∅ : α) = ⊥ := conditionally_complete_linear_order_bot.cSup_empty α end conditionally_complete_linear_order_bot section local attribute [instance] classical.prop_decidable noncomputable instance : has_Inf ℕ := ⟨λs, if h : ∃n, n ∈ s then @nat.find (λn, n ∈ s) _ h else 0⟩ noncomputable instance : has_Sup ℕ := ⟨λs, if h : ∃n, ∀a∈s, a ≤ n then @nat.find (λn, ∀a∈s, a ≤ n) _ h else 0⟩ lemma Inf_nat_def {s : set ℕ} (h : ∃n, n ∈ s) : Inf s = @nat.find (λn, n ∈ s) _ h := dif_pos _ lemma Sup_nat_def {s : set ℕ} (h : ∃n, ∀a∈s, a ≤ n) : Sup s = @nat.find (λn, ∀a∈s, a ≤ n) _ h := dif_pos _ /-- This instanec is necessary, otherwise the lattice operations would be derive via conditionally_complete_linear_order_bot and marked as noncomputable. -/ instance : lattice ℕ := infer_instance noncomputable instance : conditionally_complete_linear_order_bot ℕ := { Sup := Sup, Inf := Inf, le_cSup := assume s a hb ha, by rw [Sup_nat_def hb]; revert a ha; exact @nat.find_spec _ _ hb, cSup_le := assume s a hs ha, by rw [Sup_nat_def ⟨a, ha⟩]; exact nat.find_min' _ ha, le_cInf := assume s a hs hb, by rw [Inf_nat_def (ne_empty_iff_exists_mem.1 hs)]; exact hb _ (@nat.find_spec (λn, n ∈ s) _ _), cInf_le := assume s a hb ha, by rw [Inf_nat_def ⟨a, ha⟩]; exact nat.find_min' _ ha, cSup_empty := begin simp only [Sup_nat_def, set.mem_empty_eq, forall_const, forall_prop_of_false, not_false_iff, exists_const], apply bot_unique (nat.find_min' _ _), trivial end, .. (infer_instance : order_bot ℕ), .. (infer_instance : lattice ℕ), .. (infer_instance : linear_order ℕ) } end end lattice /-end of namespace lattice-/ namespace with_top open lattice local attribute [instance] classical.prop_decidable variables [conditionally_complete_linear_order_bot α] lemma has_lub (s : set (with_top α)) : ∃a, is_lub s a := begin by_cases hs : s = ∅, { subst hs, exact ⟨⊥, is_lub_empty⟩, }, rcases ne_empty_iff_exists_mem.1 hs with ⟨x, hxs⟩, by_cases bnd : ∃b:α, ↑b ∈ upper_bounds s, { rcases bnd with ⟨b, hb⟩, have bdd : bdd_above {a : α | ↑a ∈ s}, from ⟨b, assume y hy, coe_le_coe.1 $ hb _ hy⟩, refine ⟨(Sup {a : α | ↑a ∈ s} : α), _, _⟩, { assume a has, rcases (le_coe_iff _ _).1 (hb _ has) with ⟨a, rfl, h⟩, exact (coe_le_coe.2 $ le_cSup bdd has) }, { assume a hs, rcases (le_coe_iff _ _).1 (hb _ hxs) with ⟨x, rfl, h⟩, refine (coe_le_iff _ _).2 (assume c hc, _), subst hc, exact (cSup_le (ne_empty_of_mem hxs) $ assume b (hbs : ↑b ∈ s), coe_le_coe.1 $ hs _ hbs), } }, exact ⟨⊤, assume a _, le_top, assume a, match a with | some a, ha := (bnd ⟨a, ha⟩).elim | none, ha := _root_.le_refl ⊤ end⟩ end lemma has_glb (s : set (with_top α)) : ∃a, is_glb s a := begin by_cases hs : ∃x:α, ↑x ∈ s, { rcases hs with ⟨x, hxs⟩, refine ⟨(Inf {a : α | ↑a ∈ s} : α), _, _⟩, exact (assume a has, (coe_le_iff _ _).2 $ assume x hx, cInf_le (bdd_below_bot _) $ show ↑x ∈ s, from hx ▸ has), { assume a has, rcases (le_coe_iff _ _).1 (has _ hxs) with ⟨x, rfl, h⟩, exact (coe_le_coe.2 $ le_cInf (ne_empty_of_mem hxs) $ assume b hbs, coe_le_coe.1 $ has _ hbs) } }, exact ⟨⊤, assume a, match a with | some a, ha := (hs ⟨a, ha⟩).elim | none, ha := _root_.le_refl _ end, assume a _, le_top⟩ end noncomputable instance : has_Sup (with_top α) := ⟨λs, classical.some $ has_lub s⟩ noncomputable instance : has_Inf (with_top α) := ⟨λs, classical.some $ has_glb s⟩ lemma is_lub_Sup (s : set (with_top α)) : is_lub s (Sup s) := classical.some_spec _ lemma is_glb_Inf (s : set (with_top α)) : is_glb s (Inf s) := classical.some_spec _ noncomputable instance : complete_linear_order (with_top α) := { Sup := Sup, le_Sup := assume s, (is_lub_Sup s).1, Sup_le := assume s, (is_lub_Sup s).2, Inf := Inf, le_Inf := assume s, (is_glb_Inf s).2, Inf_le := assume s, (is_glb_Inf s).1, .. with_top.linear_order, ..with_top.lattice, ..with_top.order_top, ..with_top.order_bot } lemma coe_Sup {s : set α} (hb : bdd_above s) : (↑(Sup s) : with_top α) = (⨆a∈s, ↑a) := begin by_cases hs : s = ∅, { rw [hs, cSup_empty], simp only [set.mem_empty_eq, lattice.supr_bot, lattice.supr_false], refl }, apply le_antisymm, { refine ((coe_le_iff _ _).2 $ assume b hb, cSup_le hs $ assume a has, coe_le_coe.1 $ hb ▸ _), exact (le_supr_of_le a $ le_supr_of_le has $ _root_.le_refl _) }, { exact (supr_le $ assume a, supr_le $ assume ha, coe_le_coe.2 $ le_cSup hb ha) } end lemma coe_Inf {s : set α} (hs : s ≠ ∅) : (↑(Inf s) : with_top α) = (⨅a∈s, ↑a) := let ⟨x, hx⟩ := ne_empty_iff_exists_mem.1 hs in have (⨅a∈s, ↑a : with_top α) ≤ x, from infi_le_of_le x $ infi_le_of_le hx $ _root_.le_refl _, let ⟨r, r_eq, hr⟩ := (le_coe_iff _ _).1 this in le_antisymm (le_infi $ assume a, le_infi $ assume ha, coe_le_coe.2 $ cInf_le (bdd_below_bot s) ha) begin refine (r_eq.symm ▸ coe_le_coe.2 $ le_cInf hs $ assume a has, coe_le_coe.1 $ _), refine (r_eq ▸ infi_le_of_le a _), exact (infi_le_of_le has $ _root_.le_refl _), end end with_top
19453f2777872f463eeb3983e9af0506042b79c8
ff5230333a701471f46c57e8c115a073ebaaa448
/library/init/meta/expr.lean
ff04211f95ff76e70efbc3b6072d053d078849dd
[ "Apache-2.0" ]
permissive
stanford-cs242/lean
f81721d2b5d00bc175f2e58c57b710d465e6c858
7bd861261f4a37326dcf8d7a17f1f1f330e4548c
refs/heads/master
1,600,957,431,849
1,576,465,093,000
1,576,465,093,000
225,779,423
0
3
Apache-2.0
1,575,433,936,000
1,575,433,935,000
null
UTF-8
Lean
false
false
21,646
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.level init.category.monad init.meta.rb_map universes u v open native /-- Column and line position in a Lean source file. -/ structure pos := (line : nat) (column : nat) instance : decidable_eq pos | ⟨l₁, c₁⟩ ⟨l₂, c₂⟩ := if h₁ : l₁ = l₂ then if h₂ : c₁ = c₂ then is_true (eq.rec_on h₁ (eq.rec_on h₂ rfl)) else is_false (λ contra, pos.no_confusion contra (λ e₁ e₂, absurd e₂ h₂)) else is_false (λ contra, pos.no_confusion contra (λ e₁ e₂, absurd e₁ h₁)) meta instance : has_to_format pos := ⟨λ ⟨l, c⟩, "⟨" ++ l ++ ", " ++ c ++ "⟩"⟩ /-- Auxiliary annotation for binders (Lambda and Pi). This information is only used for elaboration. The difference between `{}` and `⦃⦄` is how implicit arguments are treated that are *not* followed by explicit arguments. `{}` arguments are applied eagerly, while `⦃⦄` arguments are left partially applied: ```lean def foo {x : ℕ} : ℕ := x def bar ⦃x : ℕ⦄ : ℕ := x #check foo -- foo : ℕ #check bar -- bar : Π ⦃x : ℕ⦄, ℕ ``` -/ inductive binder_info /- `(x : α)` -/ | default /- `{x : α}` -/ | implicit /- `⦃x:α⦄` -/ | strict_implicit /- `[x : α]`. Should be inferred with typeclass resolution. -/ | inst_implicit /- Auxiliary internal attribute used to mark local constants representing recursive functions in recursive equations and `match` statements. -/ | aux_decl instance : has_repr binder_info := ⟨λ bi, match bi with | binder_info.default := "default" | binder_info.implicit := "implicit" | binder_info.strict_implicit := "strict_implicit" | binder_info.inst_implicit := "inst_implicit" | binder_info.aux_decl := "aux_decl" end⟩ /-- Macros are basically "promises" to build an expr by some C++ code, you can't build them in Lean. You can unfold a macro and force it to evaluate. They are used for - `sorry`. - Term placeholders (`_`) in `pexpr`s. - Expression annotations. See `expr.is_annotation`. - Meta-recursive calls. Eg: ``` meta def Y : (α → α) → α | f := f (Y f) ``` The `Y` that appears in `f (Y f)` is a macro. - Builtin projections: ``` structure foo := (mynat : ℕ) #print foo.mynat -- @[reducible] -- def foo.mynat : foo → ℕ := -- λ (c : foo), [foo.mynat c] ``` The thing in square brackets is a macro. - Ephemeral structures inside certain specialised C++ implemented tactics. -/ meta constant macro_def : Type /-- An expression. eg ```(4+5)```. The `elab` flag is indicates whether the `expr` has been elaborated and doesn't contain any placeholder macros. For example the equality `x = x` is represented in `expr ff` as ``app (app (const `eq _) x) x`` while in `expr tt` it is represented as ``app (app (app (const `eq _) t) x) x`` (one more argument). The VM replaces instances of this datatype with the C++ implementation. -/ meta inductive expr (elaborated : bool := tt) /- A bound variable with a de-Bruijn index. -/ | var {} : nat → expr /- A type universe: `Sort u` -/ | sort {} : level → expr /- A global constant. These include definitions, constants and inductive type stuff present in the environment as well as hard-coded definitions. -/ | const {} : name → list level → expr /- [WARNING] Do not trust the types for `mvar` and `local_const`, they are sometimes dummy values. Use `tactic.infer_type` instead. -/ /- An `mvar` is a 'hole' yet to be filled in by the elaborator or tactic state. -/ | mvar (unique : name) (pretty : name) (type : expr) : expr /- A local constant. For example, if our tactic state was `h : P ⊢ Q`, `h` would be a local constant. -/ | local_const (unique : name) (pretty : name) (bi : binder_info) (type : expr) : expr /- Function application. -/ | app : expr → expr → expr /- Lambda abstraction. eg ```(λ a : α, x)`` -/ | lam (var_name : name) (bi : binder_info) (var_type : expr) (body : expr) : expr /- Pi type constructor. eg ```(Π a : α, x)`` and ```(α → β)`` -/ | pi (var_name : name) (bi : binder_info) (var_type : expr) (body : expr) : expr /- An explicit let binding. -/ | elet (var_name : name) (type : expr) (assignment : expr) (body : expr) : expr /- A macro, see the docstring for `macro_def`. The list of expressions are local constants and metavariables that the macro depends on. -/ | macro : macro_def → list expr → expr variable {elab : bool} meta instance : inhabited expr := ⟨expr.sort level.zero⟩ /-- Get the name of the macro definition. -/ meta constant expr.macro_def_name (d : macro_def) : name meta def expr.mk_var (n : nat) : expr := expr.var n /-- Expressions can be annotated using an annotation macro during compilation. For example, a `have x:X, from p, q` expression will be compiled to `(λ x:X,q)(p)`, but nested in an annotation macro with the name `"have"`. These annotations have no real semantic meaning, but are useful for helping Lean's pretty printer. -/ meta constant expr.is_annotation : expr elab → option (name × expr elab) /-- Remove all macro annotations from the given `expr`. -/ meta def expr.erase_annotations : expr elab → expr elab | e := match e.is_annotation with | some (_, a) := expr.erase_annotations a | none := e end /-- Compares expressions, including binder names. -/ meta constant expr.has_decidable_eq : decidable_eq expr attribute [instance] expr.has_decidable_eq /-- Compares expressions while ignoring binder names. -/ meta constant expr.alpha_eqv : expr → expr → bool notation a ` =ₐ `:50 b:50 := expr.alpha_eqv a b = bool.tt protected meta constant expr.to_string : expr elab → string meta instance : has_to_string (expr elab) := ⟨expr.to_string⟩ meta instance : has_to_format (expr elab) := ⟨λ e, e.to_string⟩ /-- Coercion for letting users write (f a) instead of (expr.app f a) -/ meta instance : has_coe_to_fun (expr elab) := { F := λ e, expr elab → expr elab, coe := λ e, expr.app e } /-- Each expression created by Lean carries a hash. This is calculated upon creation of the expression. Two structurally equal expressions will have the same hash. -/ meta constant expr.hash : expr → nat /-- Compares expressions, ignoring binder names, and sorting by hash. -/ meta constant expr.lt : expr → expr → bool /-- Compares expressions, ignoring binder names. -/ meta constant expr.lex_lt : expr → expr → bool /-- `expr.fold e a f`: Traverses each subexpression of `e`. The `nat` passed to the folder `f` is the binder depth. -/ meta constant expr.fold {α : Type} : expr → α → (expr → nat → α → α) → α /-- `expr.replace e f` Traverse over an expr `e` with a function `f` which can decide to replace subexpressions or not. For each subexpression `s` in the expression tree, `f s n` is called where `n` is how many binders are present above the given subexpression `s`. If `f s n` returns `none`, the children of `s` will be traversed. Otherwise if `some s'` is returned, `s'` will replace `s` and this subexpression will not be traversed further. -/ meta constant expr.replace : expr → (expr → nat → option expr) → expr /-- `abstract_local e n` replaces each instance of the local constant with unique (not pretty) name `n` in `e` with a de-Bruijn variable. -/ meta constant expr.abstract_local : expr → name → expr /-- Multi version of `abstract_local`. Note that the given expression will only be traversed once, so this is not the same as `list.foldl expr.abstract_local`.-/ meta constant expr.abstract_locals : expr → list name → expr /-- `abstract e x` Abstracts the expression `e` over the local constant `x`. -/ meta def expr.abstract : expr → expr → expr | e (expr.local_const n m bi t) := e.abstract_local n | e _ := e /-- Expressions depend on `level`s, and these may depend on universe parameters which have names. `instantiate_univ_params e [(n₁,l₁), ...]` will traverse `e` and replace any universe parameters with name `nᵢ` with the corresponding level `lᵢ`. -/ meta constant expr.instantiate_univ_params : expr → list (name × level) → expr /-- `instantiate_nth_var n a b` takes the `n`th de-Bruijn variable in `a` and replaces each occurrence with `b`. -/ meta constant expr.instantiate_nth_var : nat → expr → expr → expr /-- `instantiate_var a b` takes the 0th de-Bruijn variable in `a` and replaces each occurrence with `b`. -/ meta constant expr.instantiate_var : expr → expr → expr /-- ``instantiate_vars `(#0 #1 #2) [x,y,z] = `(%%x %%y %%z)`` -/ meta constant expr.instantiate_vars : expr → list expr → expr /-- Perform beta-reduction if the left expression is a lambda. Ie: ``expr.subst | `(λ x, %%Y) Z := Y[x/Z] | X Z := X``-/ protected meta constant expr.subst : expr elab → expr elab → expr elab /-- `get_free_var_range e` returns one plus the maximum de-Bruijn value in `e`. Eg `get_free_var_range `(#1 #0)` yields `2` -/ meta constant expr.get_free_var_range : expr → nat /-- `has_var e` returns true iff e has free variables. -/ meta constant expr.has_var : expr → bool /-- `has_var_idx e n` returns true iff `e` has a free variable with de-Bruijn index `n`. -/ meta constant expr.has_var_idx : expr → nat → bool /-- `has_local e` returns true if `e` contains a local constant. -/ meta constant expr.has_local : expr → bool /-- `has_meta_var e` returns true iff `e` contains a metavariable. -/ meta constant expr.has_meta_var : expr → bool /-- `lower_vars e s d` lowers the free variables >= s in `e` by `d`. Note that this can cause variable clashes. examples: - ``lower_vars `(#2 #1 #0) 1 1 = `(#1 #0 #0)`` - ``lower_vars `(λ x, #2 #1 #0) 1 1 = `(λ x, #1 #1 #0 )`` -/ meta constant expr.lower_vars : expr → nat → nat → expr /-- Lifts free variables. `lift_vars e s d` will lift all free variables with index `≥ s` in `e` by `d`. -/ meta constant expr.lift_vars : expr → nat → nat → expr /-- Get the position of the given expression in the Lean source file, if anywhere. -/ protected meta constant expr.pos : expr elab → option pos /-- `copy_pos_info src tgt` copies position information from `src` to `tgt`. -/ meta constant expr.copy_pos_info : expr → expr → expr /-- Returns `some n` when the given expression is a constant with the name `..._cnstr.n` ``` is_internal_cnstr : expr → option unsigned |(const (mk_numeral n (mk_string "_cnstr" _)) _) := some n |_ := none ``` [NOTE] This is not used anywhere in core Lean. -/ meta constant expr.is_internal_cnstr : expr → option unsigned /-- There is a macro called a "nat_value_macro" holding a natural number which are used during compilation. This function extracts that to a natural number. [NOTE] This is not used anywhere in Lean. -/ meta constant expr.get_nat_value : expr → option nat /-- Get a list of all of the universe parameters that the given expression depends on. -/ meta constant expr.collect_univ_params : expr → list name /-- `occurs e t` returns `tt` iff `e` occurs in `t` up to α-equivalence. Purely structural: no unification or definitional equality. -/ meta constant expr.occurs : expr → expr → bool /-- Returns true if any of the names in the given `name_set` are present in the given `expr`. -/ meta constant expr.has_local_in : expr → name_set → bool /-- `mk_delayed_abstraction m ls` creates a delayed abstraction on the metavariable `m` with the unique names of the local constants `ls`. If `m` is not a metavariable then this is equivalent to `abstract_locals`. -/ meta constant expr.mk_delayed_abstraction : expr → list name → expr /-- (reflected a) is a special opaque container for a closed `expr` representing `a`. It can only be obtained via type class inference, which will use the representation of `a` in the calling context. Local constants in the representation are replaced by nested inference of `reflected` instances. The quotation expression `` `(a) `` (outside of patterns) is equivalent to `reflect a` and thus can be used as an explicit way of inferring an instance of `reflected a`. -/ @[class] meta def reflected {α : Sort u} : α → Type := λ _, expr @[inline] meta def reflected.to_expr {α : Sort u} {a : α} : reflected a → expr := id @[inline] meta def reflected.subst {α : Sort v} {β : α → Sort u} {f : Π a : α, β a} {a : α} : reflected f → reflected a → reflected (f a) := λ ef ea, match ef with | (expr.lam _ _ _ _) := expr.subst ef ea | _ := expr.app ef ea end attribute [irreducible] reflected reflected.subst reflected.to_expr @[instance] protected meta constant expr.reflect (e : expr elab) : reflected e @[instance] protected meta constant string.reflect (s : string) : reflected s @[inline] meta instance {α : Sort u} (a : α) : has_coe (reflected a) expr := ⟨reflected.to_expr⟩ protected meta def reflect {α : Sort u} (a : α) [h : reflected a] : reflected a := h meta instance {α} (a : α) : has_to_format (reflected a) := ⟨λ h, to_fmt h.to_expr⟩ namespace expr open decidable meta def expr.lt_prop (a b : expr) : Prop := expr.lt a b = tt meta instance : decidable_rel expr.lt_prop := λ a b, bool.decidable_eq _ _ /-- Compares expressions, ignoring binder names, and sorting by hash. -/ meta instance : has_lt expr := ⟨ expr.lt_prop ⟩ meta def mk_true : expr := const `true [] meta def mk_false : expr := const `false [] /-- Returns the sorry macro with the given type. -/ meta constant mk_sorry (type : expr) : expr /-- Checks whether e is sorry, and returns its type. -/ meta constant is_sorry (e : expr) : option expr /-- Replace each instance of the local constant with name `n` by the expression `s` in `e`. -/ meta def instantiate_local (n : name) (s : expr) (e : expr) : expr := instantiate_var (abstract_local e n) s meta def instantiate_locals (s : list (name × expr)) (e : expr) : expr := instantiate_vars (abstract_locals e (list.reverse (list.map prod.fst s))) (list.map prod.snd s) meta def is_var : expr → bool | (var _) := tt | _ := ff meta def app_of_list : expr → list expr → expr | f [] := f | f (p::ps) := app_of_list (f p) ps meta def is_app : expr → bool | (app f a) := tt | e := ff meta def app_fn : expr → expr | (app f a) := f | a := a meta def app_arg : expr → expr | (app f a) := a | a := a meta def get_app_fn : expr elab → expr elab | (app f a) := get_app_fn f | a := a meta def get_app_num_args : expr → nat | (app f a) := get_app_num_args f + 1 | e := 0 meta def get_app_args_aux : list expr → expr → list expr | r (app f a) := get_app_args_aux (a::r) f | r e := r meta def get_app_args : expr → list expr := get_app_args_aux [] meta def mk_app : expr → list expr → expr | e [] := e | e (x::xs) := mk_app (e x) xs meta def mk_binding (ctor : name → binder_info → expr → expr → expr) (e : expr) : Π (l : expr), expr | (local_const n pp_n bi ty) := ctor pp_n bi ty (e.abstract_local n) | _ := e /-- (bind_pi e l) abstracts and pi-binds the local `l` in `e` -/ meta def bind_pi := mk_binding pi /-- (bind_lambda e l) abstracts and lambda-binds the local `l` in `e` -/ meta def bind_lambda := mk_binding lam meta def ith_arg_aux : expr → nat → expr | (app f a) 0 := a | (app f a) (n+1) := ith_arg_aux f n | e _ := e meta def ith_arg (e : expr) (i : nat) : expr := ith_arg_aux e (get_app_num_args e - i - 1) meta def const_name : expr elab → name | (const n ls) := n | e := name.anonymous meta def is_constant : expr elab → bool | (const n ls) := tt | e := ff meta def is_local_constant : expr → bool | (local_const n m bi t) := tt | e := ff meta def local_uniq_name : expr → name | (local_const n m bi t) := n | e := name.anonymous meta def local_pp_name : expr elab → name | (local_const x n bi t) := n | e := name.anonymous meta def local_type : expr elab → expr elab | (local_const _ _ _ t) := t | e := e meta def is_aux_decl : expr → bool | (local_const _ _ binder_info.aux_decl _) := tt | _ := ff meta def is_constant_of : expr elab → name → bool | (const n₁ ls) n₂ := n₁ = n₂ | e n := ff meta def is_app_of (e : expr) (n : name) : bool := is_constant_of (get_app_fn e) n /-- The same as `is_app_of` but must also have exactly `n` arguments. -/ meta def is_napp_of (e : expr) (c : name) (n : nat) : bool := is_app_of e c ∧ get_app_num_args e = n meta def is_false : expr → bool | `(false) := tt | _ := ff meta def is_not : expr → option expr | `(not %%a) := some a | `(%%a → false) := some a | e := none meta def is_and : expr → option (expr × expr) | `(and %%α %%β) := some (α, β) | _ := none meta def is_or : expr → option (expr × expr) | `(or %%α %%β) := some (α, β) | _ := none meta def is_iff : expr → option (expr × expr) | `((%%a : Prop) ↔ %%b) := some (a, b) | _ := none meta def is_eq : expr → option (expr × expr) | `((%%a : %%_) = %%b) := some (a, b) | _ := none meta def is_ne : expr → option (expr × expr) | `((%%a : %%_) ≠ %%b) := some (a, b) | _ := none meta def is_bin_arith_app (e : expr) (op : name) : option (expr × expr) := if is_napp_of e op 4 then some (app_arg (app_fn e), app_arg e) else none meta def is_lt (e : expr) : option (expr × expr) := is_bin_arith_app e ``has_lt.lt meta def is_gt (e : expr) : option (expr × expr) := is_bin_arith_app e ``gt meta def is_le (e : expr) : option (expr × expr) := is_bin_arith_app e ``has_le.le meta def is_ge (e : expr) : option (expr × expr) := is_bin_arith_app e ``ge meta def is_heq : expr → option (expr × expr × expr × expr) | `(@heq %%α %%a %%β %%b) := some (α, a, β, b) | _ := none meta def is_lambda : expr → bool | (lam _ _ _ _) := tt | e := ff meta def is_pi : expr → bool | (pi _ _ _ _) := tt | e := ff meta def is_arrow : expr → bool | (pi _ _ _ b) := bnot (has_var b) | e := ff meta def is_let : expr → bool | (elet _ _ _ _) := tt | e := ff meta def binding_name : expr → name | (pi n _ _ _) := n | (lam n _ _ _) := n | e := name.anonymous meta def binding_info : expr → binder_info | (pi _ bi _ _) := bi | (lam _ bi _ _) := bi | e := binder_info.default meta def binding_domain : expr → expr | (pi _ _ d _) := d | (lam _ _ d _) := d | e := e meta def binding_body : expr → expr | (pi _ _ _ b) := b | (lam _ _ _ b) := b | e := e meta def is_macro : expr → bool | (macro d a) := tt | e := ff meta def is_numeral : expr → bool | `(@has_zero.zero %%α %%s) := tt | `(@has_one.one %%α %%s) := tt | `(@bit0 %%α %%s %%v) := is_numeral v | `(@bit1 %%α %%s₁ %%s₂ %%v) := is_numeral v | _ := ff meta def imp (a b : expr) : expr := pi `_ binder_info.default a b /-- `lambdas cs e` lambda binds `e` with each of the local constants in `cs`. -/ meta def lambdas : list expr → expr → expr | (local_const uniq pp info t :: es) f := lam pp info t (abstract_local (lambdas es f) uniq) | _ f := f /-- Same as `expr.lambdas` but with `pi`. -/ meta def pis : list expr → expr → expr | (local_const uniq pp info t :: es) f := pi pp info t (abstract_local (pis es f) uniq) | _ f := f meta def extract_opt_auto_param : expr → expr | `(@opt_param %%t _) := extract_opt_auto_param t | `(@auto_param %%t _) := extract_opt_auto_param t | e := e open format private meta def p := λ xs, paren (format.join (list.intersperse " " xs)) meta def to_raw_fmt : expr elab → format | (var n) := p ["var", to_fmt n] | (sort l) := p ["sort", to_fmt l] | (const n ls) := p ["const", to_fmt n, to_fmt ls] | (mvar n m t) := p ["mvar", to_fmt n, to_fmt m, to_raw_fmt t] | (local_const n m bi t) := p ["local_const", to_fmt n, to_fmt m, to_raw_fmt t] | (app e f) := p ["app", to_raw_fmt e, to_raw_fmt f] | (lam n bi e t) := p ["lam", to_fmt n, repr bi, to_raw_fmt e, to_raw_fmt t] | (pi n bi e t) := p ["pi", to_fmt n, repr bi, to_raw_fmt e, to_raw_fmt t] | (elet n g e f) := p ["elet", to_fmt n, to_raw_fmt g, to_raw_fmt e, to_raw_fmt f] | (macro d args) := sbracket (format.join (list.intersperse " " ("macro" :: to_fmt (macro_def_name d) :: args.map to_raw_fmt))) /-- Fold an accumulator `a` over each subexpression in the expression `e`. The `nat` passed to `fn` is the number of binders above the subexpression. -/ meta def mfold {α : Type} {m : Type → Type} [monad m] (e : expr) (a : α) (fn : expr → nat → α → m α) : m α := fold e (return a) (λ e n a, a >>= fn e n) end expr /-- An dictionary from `data` to expressions. -/ @[reducible] meta def expr_map (data : Type) := rb_map expr data namespace expr_map export native.rb_map (hiding mk) meta def mk (data : Type) : expr_map data := rb_map.mk expr data end expr_map meta def mk_expr_map {data : Type} : expr_map data := expr_map.mk data @[reducible] meta def expr_set := rb_set expr meta def mk_expr_set : expr_set := mk_rb_set
67a160481ba62bc304acb91d24ae2c79672068fe
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/polynomial/unit_trinomial.lean
f2148fd2305e40f4a8bcb1dc04f07587654530d5
[ "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,186
lean
/- Copyright (c) 2022 Thomas Browning. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning -/ import analysis.complex.polynomial import data.polynomial.mirror /-! # Unit Trinomials This file defines irreducible trinomials and proves an irreducibility criterion. ## Main definitions - `polynomial.is_unit_trinomial` ## Main results - `polynomial.irreducible_of_coprime`: An irreducibility criterion for unit trinomials. -/ namespace polynomial open_locale polynomial open finset section semiring variables {R : Type*} [semiring R] (k m n : ℕ) (u v w : R) /-- Shorthand for a trinomial -/ noncomputable def trinomial := C u * X ^ k + C v * X ^ m + C w * X ^ n lemma trinomial_def : trinomial k m n u v w = C u * X ^ k + C v * X ^ m + C w * X ^ n := rfl variables {k m n u v w} lemma trinomial_leading_coeff' (hkm : k < m) (hmn : m < n) : (trinomial k m n u v w).coeff n = w := by rw [trinomial_def, coeff_add, coeff_add, coeff_C_mul_X_pow, coeff_C_mul_X_pow, coeff_C_mul_X_pow, if_neg (hkm.trans hmn).ne', if_neg hmn.ne', if_pos rfl, zero_add, zero_add] lemma trinomial_middle_coeff (hkm : k < m) (hmn : m < n) : (trinomial k m n u v w).coeff m = v := by rw [trinomial_def, coeff_add, coeff_add, coeff_C_mul_X_pow, coeff_C_mul_X_pow, coeff_C_mul_X_pow, if_neg hkm.ne', if_pos rfl, if_neg hmn.ne, zero_add, add_zero] lemma trinomial_trailing_coeff' (hkm : k < m) (hmn : m < n) : (trinomial k m n u v w).coeff k = u := by rw [trinomial_def, coeff_add, coeff_add, coeff_C_mul_X_pow, coeff_C_mul_X_pow, coeff_C_mul_X_pow, if_pos rfl, if_neg hkm.ne, if_neg (hkm.trans hmn).ne, add_zero, add_zero] lemma trinomial_nat_degree (hkm : k < m) (hmn : m < n) (hw : w ≠ 0) : (trinomial k m n u v w).nat_degree = n := begin refine nat_degree_eq_of_degree_eq_some (le_antisymm (sup_le (λ i h, _)) (le_degree_of_ne_zero (by rwa trinomial_leading_coeff' hkm hmn))), replace h := support_trinomial' k m n u v w h, rw [mem_insert, mem_insert, mem_singleton] at h, rcases h with rfl | rfl | rfl, { exact with_bot.coe_le_coe.mpr (hkm.trans hmn).le }, { exact with_bot.coe_le_coe.mpr hmn.le }, { exact le_rfl }, end lemma trinomial_nat_trailing_degree (hkm : k < m) (hmn : m < n) (hu : u ≠ 0) : (trinomial k m n u v w).nat_trailing_degree = k := begin refine nat_trailing_degree_eq_of_trailing_degree_eq_some (le_antisymm (le_inf (λ i h, _)) (le_trailing_degree_of_ne_zero (by rwa trinomial_trailing_coeff' hkm hmn))).symm, replace h := support_trinomial' k m n u v w h, rw [mem_insert, mem_insert, mem_singleton] at h, rcases h with rfl | rfl | rfl, { exact le_rfl }, { exact with_top.coe_le_coe.mpr hkm.le }, { exact with_top.coe_le_coe.mpr (hkm.trans hmn).le }, end lemma trinomial_leading_coeff (hkm : k < m) (hmn : m < n) (hw : w ≠ 0) : (trinomial k m n u v w).leading_coeff = w := by rw [leading_coeff, trinomial_nat_degree hkm hmn hw, trinomial_leading_coeff' hkm hmn] lemma trinomial_trailing_coeff (hkm : k < m) (hmn : m < n) (hu : u ≠ 0) : (trinomial k m n u v w).trailing_coeff = u := by rw [trailing_coeff, trinomial_nat_trailing_degree hkm hmn hu, trinomial_trailing_coeff' hkm hmn] lemma trinomial_monic (hkm : k < m) (hmn : m < n) : (trinomial k m n u v 1).monic := begin casesI subsingleton_or_nontrivial R with h h, { apply subsingleton.elim }, { exact trinomial_leading_coeff hkm hmn one_ne_zero }, end lemma trinomial_mirror (hkm : k < m) (hmn : m < n) (hu : u ≠ 0) (hw : w ≠ 0) : (trinomial k m n u v w).mirror = trinomial k (n - m + k) n w v u := by rw [mirror, trinomial_nat_trailing_degree hkm hmn hu, reverse, trinomial_nat_degree hkm hmn hw, trinomial_def, reflect_add, reflect_add, reflect_C_mul_X_pow, reflect_C_mul_X_pow, reflect_C_mul_X_pow, rev_at_le (hkm.trans hmn).le, rev_at_le hmn.le, rev_at_le le_rfl, add_mul, add_mul, mul_assoc, mul_assoc, mul_assoc, ←pow_add, ←pow_add, ←pow_add, nat.sub_add_cancel (hkm.trans hmn).le, nat.sub_self, zero_add, add_comm, add_comm (C u * X ^ n), ←add_assoc, ←trinomial_def] lemma trinomial_support (hkm : k < m) (hmn : m < n) (hu : u ≠ 0) (hv : v ≠ 0) (hw : w ≠ 0) : (trinomial k m n u v w).support = {k, m, n} := support_trinomial hkm hmn hu hv hw end semiring variables (p q : ℤ[X]) /-- A unit trinomial is a trinomial with unit coefficients. -/ def is_unit_trinomial := ∃ {k m n : ℕ} (hkm : k < m) (hmn : m < n) {u v w : units ℤ}, p = trinomial k m n u v w variables {p q} namespace is_unit_trinomial lemma not_is_unit (hp : p.is_unit_trinomial) : ¬ is_unit p := begin obtain ⟨k, m, n, hkm, hmn, u, v, w, rfl⟩ := hp, exact λ h, ne_zero_of_lt hmn ((trinomial_nat_degree hkm hmn w.ne_zero).symm.trans (nat_degree_eq_of_degree_eq_some (degree_eq_zero_of_is_unit h))), end lemma card_support_eq_three (hp : p.is_unit_trinomial) : p.support.card = 3 := begin obtain ⟨k, m, n, hkm, hmn, u, v, w, rfl⟩ := hp, exact card_support_trinomial hkm hmn u.ne_zero v.ne_zero w.ne_zero, end lemma ne_zero (hp : p.is_unit_trinomial) : p ≠ 0 := begin rintro rfl, exact nat.zero_ne_bit1 1 hp.card_support_eq_three, end lemma coeff_is_unit (hp : p.is_unit_trinomial) {k : ℕ} (hk : k ∈ p.support) : is_unit (p.coeff k) := begin obtain ⟨k, m, n, hkm, hmn, u, v, w, rfl⟩ := hp, have := support_trinomial' k m n ↑u ↑v ↑w hk, rw [mem_insert, mem_insert, mem_singleton] at this, rcases this with rfl | rfl | rfl, { refine ⟨u, by rw trinomial_trailing_coeff' hkm hmn⟩ }, { refine ⟨v, by rw trinomial_middle_coeff hkm hmn⟩ }, { refine ⟨w, by rw trinomial_leading_coeff' hkm hmn⟩ }, end lemma leading_coeff_is_unit (hp : p.is_unit_trinomial) : is_unit p.leading_coeff := hp.coeff_is_unit (nat_degree_mem_support_of_nonzero hp.ne_zero) lemma trailing_coeff_is_unit (hp : p.is_unit_trinomial) : is_unit p.trailing_coeff := hp.coeff_is_unit (nat_trailing_degree_mem_support_of_nonzero hp.ne_zero) end is_unit_trinomial lemma is_unit_trinomial_iff : p.is_unit_trinomial ↔ p.support.card = 3 ∧ ∀ k ∈ p.support, is_unit (p.coeff k) := begin refine ⟨λ hp, ⟨hp.card_support_eq_three, λ k, hp.coeff_is_unit⟩, λ hp, _⟩, obtain ⟨k, m, n, hkm, hmn, x, y, z, hx, hy, hz, rfl⟩ := card_support_eq_three.mp hp.1, rw [support_trinomial hkm hmn hx hy hz] at hp, replace hx := hp.2 k (mem_insert_self k {m, n}), replace hy := hp.2 m (mem_insert_of_mem (mem_insert_self m {n})), replace hz := hp.2 n (mem_insert_of_mem (mem_insert_of_mem (mem_singleton_self n))), simp_rw [coeff_add, coeff_C_mul, coeff_X_pow_self, mul_one, coeff_X_pow] at hx hy hz, rw [if_neg hkm.ne, if_neg (hkm.trans hmn).ne] at hx, rw [if_neg hkm.ne', if_neg hmn.ne] at hy, rw [if_neg (hkm.trans hmn).ne', if_neg hmn.ne'] at hz, simp_rw [mul_zero, zero_add, add_zero] at hx hy hz, exact ⟨k, m, n, hkm, hmn, hx.unit, hy.unit, hz.unit, rfl⟩, end lemma is_unit_trinomial_iff' : p.is_unit_trinomial ↔ (p * p.mirror).coeff (((p * p.mirror).nat_degree + (p * p.mirror).nat_trailing_degree) / 2) = 3 := begin rw [nat_degree_mul_mirror, nat_trailing_degree_mul_mirror, ←mul_add, nat.mul_div_right _ zero_lt_two, coeff_mul_mirror], refine ⟨_, λ hp, _⟩, { rintros ⟨k, m, n, hkm, hmn, u, v, w, rfl⟩, rw [sum_def, trinomial_support hkm hmn u.ne_zero v.ne_zero w.ne_zero, sum_insert (mt mem_insert.mp (not_or hkm.ne (mt mem_singleton.mp (hkm.trans hmn).ne))), sum_insert (mt mem_singleton.mp hmn.ne), sum_singleton, trinomial_leading_coeff' hkm hmn, trinomial_middle_coeff hkm hmn, trinomial_trailing_coeff' hkm hmn], simp_rw [←units.coe_pow, int.units_sq, units.coe_one, ←add_assoc, bit1, bit0] }, { have key : ∀ k ∈ p.support, (p.coeff k) ^ 2 = 1 := λ k hk, int.sq_eq_one_of_sq_le_three ((single_le_sum (λ k hk, sq_nonneg (p.coeff k)) hk).trans hp.le) (mem_support_iff.mp hk), refine is_unit_trinomial_iff.mpr ⟨_, λ k hk, is_unit_of_pow_eq_one _ 2 (key k hk) zero_lt_two⟩, rw [sum_def, sum_congr rfl key, sum_const, nat.smul_one_eq_coe] at hp, exact nat.cast_injective hp }, end lemma is_unit_trinomial_iff'' (h : p * p.mirror = q * q.mirror) : p.is_unit_trinomial ↔ q.is_unit_trinomial := by rw [is_unit_trinomial_iff', is_unit_trinomial_iff', h] namespace is_unit_trinomial lemma irreducible_aux1 {k m n : ℕ} (hkm : k < m) (hmn : m < n) (u v w : units ℤ) (hp : p = trinomial k m n u v w) : C ↑v * (C ↑u * X ^ (m + n) + C ↑w * X ^ (n - m + k + n)) = ⟨finsupp.filter (set.Ioo (k + n) (n + n)) (p * p.mirror).to_finsupp⟩ := begin have key : n - m + k < n := by rwa [←lt_tsub_iff_right, tsub_lt_tsub_iff_left_of_le hmn.le], rw [hp, trinomial_mirror hkm hmn u.ne_zero w.ne_zero], simp_rw [trinomial_def, ←monomial_eq_C_mul_X, add_mul, mul_add, monomial_mul_monomial, to_finsupp_add, to_finsupp_monomial, finsupp.filter_add], rw [finsupp.filter_single_of_neg, finsupp.filter_single_of_neg, finsupp.filter_single_of_neg, finsupp.filter_single_of_neg, finsupp.filter_single_of_neg, finsupp.filter_single_of_pos, finsupp.filter_single_of_neg, finsupp.filter_single_of_pos, finsupp.filter_single_of_neg], { simp only [add_zero, zero_add, of_finsupp_add, of_finsupp_single], rw [C_mul_monomial, C_mul_monomial, mul_comm ↑v ↑w, add_comm (n - m + k) n] }, { exact λ h, h.2.ne rfl }, { refine ⟨_, add_lt_add_left key n⟩, rwa [add_comm, add_lt_add_iff_left, lt_add_iff_pos_left, tsub_pos_iff_lt] }, { exact λ h, h.1.ne (add_comm k n) }, { exact ⟨add_lt_add_right hkm n, add_lt_add_right hmn n⟩ }, { rw [←add_assoc, add_tsub_cancel_of_le hmn.le, add_comm], exact λ h, h.1.ne rfl }, { intro h, have := h.1, rw [add_comm, add_lt_add_iff_right] at this, exact asymm this hmn }, { exact λ h, h.1.ne rfl }, { exact λ h, asymm ((add_lt_add_iff_left k).mp h.1) key }, { exact λ h, asymm ((add_lt_add_iff_left k).mp h.1) (hkm.trans hmn) }, end lemma irreducible_aux2 {k m m' n : ℕ} (hkm : k < m) (hmn : m < n) (hkm' : k < m') (hmn' : m' < n) (u v w : units ℤ) (hp : p = trinomial k m n u v w) (hq : q = trinomial k m' n u v w) (h : p * p.mirror = q * q.mirror) : q = p ∨ q = p.mirror := begin let f : ℤ[X] → ℤ[X] := λ p, ⟨finsupp.filter (set.Ioo (k + n) (n + n)) p.to_finsupp⟩, replace h := congr_arg f h, replace h := (irreducible_aux1 hkm hmn u v w hp).trans h, replace h := h.trans (irreducible_aux1 hkm' hmn' u v w hq).symm, rw (is_unit_C.mpr v.is_unit).mul_right_inj at h, rw binomial_eq_binomial u.ne_zero w.ne_zero at h, simp only [add_left_inj, units.eq_iff] at h, rcases h with ⟨rfl, -⟩ | ⟨rfl, rfl, h⟩ | ⟨-, hm, hm'⟩, { exact or.inl (hq.trans hp.symm) }, { refine or.inr _, rw [←trinomial_mirror hkm' hmn' u.ne_zero u.ne_zero, eq_comm, mirror_eq_iff] at hp, exact hq.trans hp }, { suffices : m = m', { rw this at hp, exact or.inl (hq.trans hp.symm) }, rw [tsub_add_eq_add_tsub hmn.le, eq_tsub_iff_add_eq_of_le, ←two_mul] at hm, rw [tsub_add_eq_add_tsub hmn'.le, eq_tsub_iff_add_eq_of_le, ←two_mul] at hm', exact mul_left_cancel₀ two_ne_zero (hm.trans hm'.symm), exact hmn'.le.trans (nat.le_add_right n k), exact hmn.le.trans (nat.le_add_right n k) }, end lemma irreducible_aux3 {k m m' n : ℕ} (hkm : k < m) (hmn : m < n) (hkm' : k < m') (hmn' : m' < n) (u v w x z : units ℤ) (hp : p = trinomial k m n u v w) (hq : q = trinomial k m' n x v z) (h : p * p.mirror = q * q.mirror) : q = p ∨ q = p.mirror := begin have hmul := congr_arg leading_coeff h, rw [leading_coeff_mul, leading_coeff_mul, mirror_leading_coeff, mirror_leading_coeff, hp, hq, trinomial_leading_coeff hkm hmn w.ne_zero, trinomial_leading_coeff hkm' hmn' z.ne_zero, trinomial_trailing_coeff hkm hmn u.ne_zero, trinomial_trailing_coeff hkm' hmn' x.ne_zero] at hmul, have hadd := congr_arg (eval 1) h, rw [eval_mul, eval_mul, mirror_eval_one, mirror_eval_one, ←sq, ←sq, hp, hq] at hadd, simp only [eval_add, eval_C_mul, eval_pow, eval_X, one_pow, mul_one, trinomial_def] at hadd, rw [add_assoc, add_assoc, add_comm ↑u, add_comm ↑x, add_assoc, add_assoc] at hadd, simp only [add_sq', add_assoc, add_right_inj, ←units.coe_pow, int.units_sq] at hadd, rw [mul_assoc, hmul, ←mul_assoc, add_right_inj, mul_right_inj' (show 2 * (v : ℤ) ≠ 0, from mul_ne_zero two_ne_zero v.ne_zero)] at hadd, replace hadd := (int.is_unit_add_is_unit_eq_is_unit_add_is_unit w.is_unit u.is_unit z.is_unit x.is_unit).mp hadd, simp only [units.eq_iff] at hadd, rcases hadd with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, { exact irreducible_aux2 hkm hmn hkm' hmn' u v w hp hq h }, { rw [←mirror_inj, trinomial_mirror hkm' hmn' w.ne_zero u.ne_zero] at hq, rw [mul_comm q, ←q.mirror_mirror, q.mirror.mirror_mirror] at h, rw [←mirror_inj, or_comm, ←mirror_eq_iff], exact irreducible_aux2 hkm hmn (lt_add_of_pos_left k (tsub_pos_of_lt hmn')) ((lt_tsub_iff_right).mp ((tsub_lt_tsub_iff_left_of_le hmn'.le).mpr hkm')) u v w hp hq h }, end lemma irreducible_of_coprime (hp : p.is_unit_trinomial) (h : ∀ q : ℤ[X], q ∣ p → q ∣ p.mirror → is_unit q) : irreducible p := begin refine irreducible_of_mirror hp.not_is_unit (λ q hpq, _) h, have hq : is_unit_trinomial q := (is_unit_trinomial_iff'' hpq).mp hp, obtain ⟨k, m, n, hkm, hmn, u, v, w, hp⟩ := hp, obtain ⟨k', m', n', hkm', hmn', x, y, z, hq⟩ := hq, have hk : k = k', { rw [←mul_right_inj' (show 2 ≠ 0, from two_ne_zero), ←trinomial_nat_trailing_degree hkm hmn u.ne_zero, ←hp, ←nat_trailing_degree_mul_mirror, hpq, nat_trailing_degree_mul_mirror, hq, trinomial_nat_trailing_degree hkm' hmn' x.ne_zero] }, have hn : n = n', { rw [←mul_right_inj' (show 2 ≠ 0, from two_ne_zero), ←trinomial_nat_degree hkm hmn w.ne_zero, ←hp, ←nat_degree_mul_mirror, hpq, nat_degree_mul_mirror, hq, trinomial_nat_degree hkm' hmn' z.ne_zero] }, subst hk, subst hn, rcases eq_or_eq_neg_of_sq_eq_sq ↑y ↑v ((int.is_unit_sq y.is_unit).trans (int.is_unit_sq v.is_unit).symm) with h1 | h1, { rw h1 at *, rcases irreducible_aux3 hkm hmn hkm' hmn' u v w x z hp hq hpq with h2 | h2, { exact or.inl h2 }, { exact or.inr (or.inr (or.inl h2)) } }, { rw h1 at *, rw trinomial_def at hp, rw [←neg_inj, neg_add, neg_add, ←neg_mul, ←neg_mul, ←neg_mul, ←C_neg, ←C_neg, ←C_neg] at hp, rw [←neg_mul_neg, ←mirror_neg] at hpq, rcases irreducible_aux3 hkm hmn hkm' hmn' (-u) (-v) (-w) x z hp hq hpq with rfl | rfl, { exact or.inr (or.inl rfl) }, { exact or.inr (or.inr (or.inr p.mirror_neg)) } }, end /-- A unit trinomial is irreducible if it is coprime with its mirror -/ lemma irreducible_of_is_coprime (hp : p.is_unit_trinomial) (h : is_coprime p p.mirror) : irreducible p := irreducible_of_coprime hp (λ q, h.is_unit_of_dvd') /-- A unit trinomial is irreducible if it has no complex roots in common with its mirror -/ lemma irreducible_of_coprime' (hp : is_unit_trinomial p) (h : ∀ z : ℂ, ¬ (aeval z p = 0 ∧ aeval z (mirror p) = 0)) : irreducible p := begin refine hp.irreducible_of_coprime (λ q hq hq', _), suffices : ¬ (0 < q.nat_degree), { rcases hq with ⟨p, rfl⟩, replace hp := hp.leading_coeff_is_unit, rw leading_coeff_mul at hp, replace hp := is_unit_of_mul_is_unit_left hp, rw [not_lt, le_zero_iff] at this, rwa [eq_C_of_nat_degree_eq_zero this, is_unit_C, ←this] }, intro hq'', rw nat_degree_pos_iff_degree_pos at hq'', rw ← degree_map_eq_of_injective (algebra_map ℤ ℂ).injective_int at hq'', cases complex.exists_root hq'' with z hz, rw [is_root, eval_map, ←aeval_def] at hz, refine h z ⟨_, _⟩, { cases hq with g' hg', rw [hg', aeval_mul, hz, zero_mul] }, { cases hq' with g' hg', rw [hg', aeval_mul, hz, zero_mul] }, end -- TODO: Develop more theory (e.g., it suffices to check that `aeval z p ≠ 0` for `z = 0` -- and `z` a root of unity) end is_unit_trinomial end polynomial
be1d6012d39177111b410b4279115d985f00bba1
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/fin/interval.lean
da6c0ee9eeda9dfe5477cca9280052e11b2c6a7c
[ "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
5,205
lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.nat.interval /-! # Finite intervals in `fin n` This file proves that `fin n` is a `locally_finite_order` and calculates the cardinality of its intervals as finsets and fintypes. -/ open finset fin function open_locale big_operators variables (n : ℕ) instance : locally_finite_order (fin n) := subtype.locally_finite_order _ instance : locally_finite_order_bot (fin n) := subtype.locally_finite_order_bot _ instance : Π n, locally_finite_order_top (fin n) | 0 := is_empty.to_locally_finite_order_top | (n + 1) := infer_instance namespace fin variables {n} (a b : fin n) lemma Icc_eq_finset_subtype : Icc a b = (Icc (a : ℕ) b).subtype (λ x, x < n) := rfl lemma Ico_eq_finset_subtype : Ico a b = (Ico (a : ℕ) b).subtype (λ x, x < n) := rfl lemma Ioc_eq_finset_subtype : Ioc a b = (Ioc (a : ℕ) b).subtype (λ x, x < n) := rfl lemma Ioo_eq_finset_subtype : Ioo a b = (Ioo (a : ℕ) b).subtype (λ x, x < n) := rfl @[simp] lemma map_subtype_embedding_Icc : (Icc a b).map (embedding.subtype _) = Icc a b := map_subtype_embedding_Icc _ _ _ (λ _ c x _ hx _, hx.trans_lt) @[simp] lemma map_subtype_embedding_Ico : (Ico a b).map (embedding.subtype _) = Ico a b := map_subtype_embedding_Ico _ _ _ (λ _ c x _ hx _, hx.trans_lt) @[simp] lemma map_subtype_embedding_Ioc : (Ioc a b).map (embedding.subtype _) = Ioc a b := map_subtype_embedding_Ioc _ _ _ (λ _ c x _ hx _, hx.trans_lt) @[simp] lemma map_subtype_embedding_Ioo : (Ioo a b).map (embedding.subtype _) = Ioo a b := map_subtype_embedding_Ioo _ _ _ (λ _ c x _ hx _, hx.trans_lt) @[simp] lemma card_Icc : (Icc a b).card = b + 1 - a := by rw [←nat.card_Icc, ←map_subtype_embedding_Icc, card_map] @[simp] lemma card_Ico : (Ico a b).card = b - a := by rw [←nat.card_Ico, ←map_subtype_embedding_Ico, card_map] @[simp] lemma card_Ioc : (Ioc a b).card = b - a := by rw [←nat.card_Ioc, ←map_subtype_embedding_Ioc, card_map] @[simp] lemma card_Ioo : (Ioo a b).card = b - a - 1 := by rw [←nat.card_Ioo, ←map_subtype_embedding_Ioo, card_map] @[simp] lemma card_fintype_Icc : fintype.card (set.Icc a b) = b + 1 - a := by rw [←card_Icc, fintype.card_of_finset] @[simp] lemma card_fintype_Ico : fintype.card (set.Ico a b) = b - a := by rw [←card_Ico, fintype.card_of_finset] @[simp] lemma card_fintype_Ioc : fintype.card (set.Ioc a b) = b - a := by rw [←card_Ioc, fintype.card_of_finset] @[simp] lemma card_fintype_Ioo : fintype.card (set.Ioo a b) = b - a - 1 := by rw [←card_Ioo, fintype.card_of_finset] lemma Ici_eq_finset_subtype : Ici a = (Icc (a : ℕ) n).subtype (λ x, x < n) := by { ext x, simp only [mem_subtype, mem_Ici, mem_Icc, coe_fin_le, iff_self_and], exact λ _, x.2.le } lemma Ioi_eq_finset_subtype : Ioi a = (Ioc (a : ℕ) n).subtype (λ x, x < n) := by { ext x, simp only [mem_subtype, mem_Ioi, mem_Ioc, coe_fin_lt, iff_self_and], exact λ _, x.2.le } lemma Iic_eq_finset_subtype : Iic b = (Iic (b : ℕ)).subtype (λ x, x < n) := rfl lemma Iio_eq_finset_subtype : Iio b = (Iio (b : ℕ)).subtype (λ x, x < n) := rfl @[simp] lemma map_subtype_embedding_Ici : (Ici a).map (embedding.subtype _) = Icc a (n - 1) := begin ext x, simp only [exists_prop, embedding.coe_subtype, mem_Ici, mem_map, mem_Icc], split, { rintro ⟨x, hx, rfl⟩, exact ⟨hx, le_tsub_of_add_le_right $ x.2⟩ }, cases n, { exact fin.elim0 a }, { exact λ hx, ⟨⟨x, nat.lt_succ_iff.2 hx.2⟩, hx.1, rfl⟩ } end @[simp] lemma map_subtype_embedding_Ioi : (Ioi a).map (embedding.subtype _) = Ioc a (n - 1) := begin ext x, simp only [exists_prop, embedding.coe_subtype, mem_Ioi, mem_map, mem_Ioc], split, { rintro ⟨x, hx, rfl⟩, exact ⟨hx, le_tsub_of_add_le_right $ x.2⟩ }, cases n, { exact fin.elim0 a }, { exact λ hx, ⟨⟨x, nat.lt_succ_iff.2 hx.2⟩, hx.1, rfl⟩ } end @[simp] lemma map_subtype_embedding_Iic : (Iic b).map (embedding.subtype _) = Iic b := map_subtype_embedding_Iic _ _ $ λ _ _, lt_of_le_of_lt @[simp] lemma map_subtype_embedding_Iio : (Iio b).map (embedding.subtype _) = Iio b := map_subtype_embedding_Iio _ _ $ λ _ _, lt_of_le_of_lt @[simp] lemma card_Ici : (Ici a).card = n - a := by { cases n, { exact fin.elim0 a }, rw [←card_map, map_subtype_embedding_Ici, nat.card_Icc], refl } @[simp] lemma card_Ioi : (Ioi a).card = n - 1 - a := by { rw [←card_map, map_subtype_embedding_Ioi, nat.card_Ioc] } @[simp] lemma card_Iic : (Iic b).card = b + 1 := by rw [←nat.card_Iic b, ←map_subtype_embedding_Iic, card_map] @[simp] lemma card_Iio : (Iio b).card = b := by rw [←nat.card_Iio b, ←map_subtype_embedding_Iio, card_map] @[simp] lemma card_fintype_Ici : fintype.card (set.Ici a) = n - a := by rw [fintype.card_of_finset, card_Ici] @[simp] lemma card_fintype_Ioi : fintype.card (set.Ioi a) = n - 1 - a := by rw [fintype.card_of_finset, card_Ioi] @[simp] lemma card_fintype_Iic : fintype.card (set.Iic b) = b + 1 := by rw [fintype.card_of_finset, card_Iic] @[simp] lemma card_fintype_Iio : fintype.card (set.Iio b) = b := by rw [fintype.card_of_finset, card_Iio] end fin
d7e4a3f560b5cd422220b942e1eed6c4df19e417
9028d228ac200bbefe3a711342514dd4e4458bff
/src/data/equiv/ring.lean
cde792a843b73dca7e81b42ad47d4b06a37eab6e
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,198
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Callum Sutton, Yury Kudryashov -/ import data.equiv.mul_add import algebra.field import algebra.opposites /-! # (Semi)ring equivs In this file we define extension of `equiv` called `ring_equiv`, which is a datatype representing an isomorphism of `semiring`s, `ring`s, `division_ring`s, or `field`s. We also introduce the corresponding group of automorphisms `ring_aut`. ## Notations The extended equiv have coercions to functions, and the coercion is the canonical notation when treating the isomorphism as maps. ## Implementation notes The fields for `ring_equiv` now avoid the unbundled `is_mul_hom` and `is_add_hom`, as these are deprecated. Definition of multiplication in the groups of automorphisms agrees with function composition, multiplication in `equiv.perm`, and multiplication in `category_theory.End`, not with `category_theory.comp`. ## Tags equiv, mul_equiv, add_equiv, ring_equiv, mul_aut, add_aut, ring_aut -/ variables {R : Type*} {S : Type*} {S' : Type*} set_option old_structure_cmd true /-- An equivalence between two (semi)rings that preserves the algebraic structure. -/ structure ring_equiv (R S : Type*) [has_mul R] [has_add R] [has_mul S] [has_add S] extends R ≃ S, R ≃* S, R ≃+ S infix ` ≃+* `:25 := ring_equiv /-- The "plain" equivalence of types underlying an equivalence of (semi)rings. -/ add_decl_doc ring_equiv.to_equiv /-- The equivalence of additive monoids underlying an equivalence of (semi)rings. -/ add_decl_doc ring_equiv.to_add_equiv /-- The equivalence of multiplicative monoids underlying an equivalence of (semi)rings. -/ add_decl_doc ring_equiv.to_mul_equiv namespace ring_equiv section basic variables [has_mul R] [has_add R] [has_mul S] [has_add S] [has_mul S'] [has_add S'] instance : has_coe_to_fun (R ≃+* S) := ⟨_, ring_equiv.to_fun⟩ @[simp] lemma to_fun_eq_coe_fun (f : R ≃+* S) : f.to_fun = f := rfl /-- Two ring isomorphisms agree if they are defined by the same underlying function. -/ @[ext] lemma ext {f g : R ≃+* S} (h : ∀ x, f x = g x) : f = g := begin have h₁ : f.to_equiv = g.to_equiv := equiv.ext h, cases f, cases g, congr, { exact (funext h) }, { exact congr_arg equiv.inv_fun h₁ } end instance has_coe_to_mul_equiv : has_coe (R ≃+* S) (R ≃* S) := ⟨ring_equiv.to_mul_equiv⟩ instance has_coe_to_add_equiv : has_coe (R ≃+* S) (R ≃+ S) := ⟨ring_equiv.to_add_equiv⟩ @[norm_cast] lemma coe_mul_equiv (f : R ≃+* S) (a : R) : (f : R ≃* S) a = f a := rfl @[norm_cast] lemma coe_add_equiv (f : R ≃+* S) (a : R) : (f : R ≃+ S) a = f a := rfl variable (R) /-- The identity map is a ring isomorphism. -/ @[refl] protected def refl : R ≃+* R := { .. mul_equiv.refl R, .. add_equiv.refl R } @[simp] lemma refl_apply (x : R) : ring_equiv.refl R x = x := rfl @[simp] lemma coe_add_equiv_refl : (ring_equiv.refl R : R ≃+ R) = add_equiv.refl R := rfl @[simp] lemma coe_mul_equiv_refl : (ring_equiv.refl R : R ≃* R) = mul_equiv.refl R := rfl instance : inhabited (R ≃+* R) := ⟨ring_equiv.refl R⟩ variables {R} /-- The inverse of a ring isomorphism is a ring isomorphism. -/ @[symm] protected def symm (e : R ≃+* S) : S ≃+* R := { .. e.to_mul_equiv.symm, .. e.to_add_equiv.symm } /-- Transitivity of `ring_equiv`. -/ @[trans] protected def trans (e₁ : R ≃+* S) (e₂ : S ≃+* S') : R ≃+* S' := { .. (e₁.to_mul_equiv.trans e₂.to_mul_equiv), .. (e₁.to_add_equiv.trans e₂.to_add_equiv) } @[simp] lemma trans_apply {A B C : Type*} [semiring A] [semiring B] [semiring C] (e : A ≃+* B) (f : B ≃+* C) (a : A) : e.trans f a = f (e a) := rfl protected lemma bijective (e : R ≃+* S) : function.bijective e := e.to_equiv.bijective protected lemma injective (e : R ≃+* S) : function.injective e := e.to_equiv.injective protected lemma surjective (e : R ≃+* S) : function.surjective e := e.to_equiv.surjective @[simp] lemma apply_symm_apply (e : R ≃+* S) : ∀ x, e (e.symm x) = x := e.to_equiv.apply_symm_apply @[simp] lemma symm_apply_apply (e : R ≃+* S) : ∀ x, e.symm (e x) = x := e.to_equiv.symm_apply_apply lemma image_eq_preimage (e : R ≃+* S) (s : set R) : e '' s = e.symm ⁻¹' s := e.to_equiv.image_eq_preimage s end basic section comm_semiring open opposite variables (R) [comm_semiring R] /-- A commutative ring is isomorphic to its opposite. -/ def to_opposite : R ≃+* Rᵒᵖ := { map_add' := λ x y, rfl, map_mul' := λ x y, mul_comm (op y) (op x), ..equiv_to_opposite } @[simp] lemma to_opposite_apply (r : R) : to_opposite R r = op r := rfl @[simp] lemma to_opposite_symm_apply (r : Rᵒᵖ) : (to_opposite R).symm r = unop r := rfl end comm_semiring section semiring variables [semiring R] [semiring S] (f : R ≃+* S) (x y : R) /-- A ring isomorphism preserves multiplication. -/ @[simp] lemma map_mul : f (x * y) = f x * f y := f.map_mul' x y /-- A ring isomorphism sends one to one. -/ @[simp] lemma map_one : f 1 = 1 := (f : R ≃* S).map_one /-- A ring isomorphism preserves addition. -/ @[simp] lemma map_add : f (x + y) = f x + f y := f.map_add' x y /-- A ring isomorphism sends zero to zero. -/ @[simp] lemma map_zero : f 0 = 0 := (f : R ≃+ S).map_zero variable {x} @[simp] lemma map_eq_one_iff : f x = 1 ↔ x = 1 := (f : R ≃* S).map_eq_one_iff @[simp] lemma map_eq_zero_iff : f x = 0 ↔ x = 0 := (f : R ≃+ S).map_eq_zero_iff lemma map_ne_one_iff : f x ≠ 1 ↔ x ≠ 1 := (f : R ≃* S).map_ne_one_iff lemma map_ne_zero_iff : f x ≠ 0 ↔ x ≠ 0 := (f : R ≃+ S).map_ne_zero_iff /-- Produce a ring isomorphism from a bijective ring homomorphism. -/ noncomputable def of_bijective (f : R →+* S) (hf : function.bijective f) : R ≃+* S := { .. equiv.of_bijective f hf, .. f } end semiring section variables [ring R] [ring S] (f : R ≃+* S) (x y : R) @[simp] lemma map_neg : f (-x) = -f x := (f : R ≃+ S).map_neg x @[simp] lemma map_sub : f (x - y) = f x - f y := (f : R ≃+ S).map_sub x y @[simp] lemma map_neg_one : f (-1) = -1 := f.map_one ▸ f.map_neg 1 end section semiring_hom variables [semiring R] [semiring S] [semiring S'] /-- Reinterpret a ring equivalence as a ring homomorphism. -/ def to_ring_hom (e : R ≃+* S) : R →+* S := { .. e.to_mul_equiv.to_monoid_hom, .. e.to_add_equiv.to_add_monoid_hom } lemma to_ring_hom_injective : function.injective (to_ring_hom : (R ≃+* S) → R →+* S) := λ f g h, ring_equiv.ext (ring_hom.ext_iff.1 h) instance has_coe_to_ring_hom : has_coe (R ≃+* S) (R →+* S) := ⟨ring_equiv.to_ring_hom⟩ @[norm_cast] lemma coe_ring_hom (f : R ≃+* S) (a : R) : (f : R →+* S) a = f a := rfl lemma coe_ring_hom_inj_iff {R S : Type*} [semiring R] [semiring S] (f g : R ≃+* S) : f = g ↔ (f : R →+* S) = g := ⟨congr_arg _, λ h, ext $ ring_hom.ext_iff.mp h⟩ /-- Reinterpret a ring equivalence as a monoid homomorphism. -/ abbreviation to_monoid_hom (e : R ≃+* S) : R →* S := e.to_ring_hom.to_monoid_hom /-- Reinterpret a ring equivalence as an `add_monoid` homomorphism. -/ abbreviation to_add_monoid_hom (e : R ≃+* S) : R →+ S := e.to_ring_hom.to_add_monoid_hom @[simp] lemma to_ring_hom_refl : (ring_equiv.refl R).to_ring_hom = ring_hom.id R := rfl @[simp] lemma to_monoid_hom_refl : (ring_equiv.refl R).to_monoid_hom = monoid_hom.id R := rfl @[simp] lemma to_add_monoid_hom_refl : (ring_equiv.refl R).to_add_monoid_hom = add_monoid_hom.id R := rfl @[simp] lemma to_ring_hom_apply_symm_to_ring_hom_apply (e : R ≃+* S) : ∀ (y : S), e.to_ring_hom (e.symm.to_ring_hom y) = y := e.to_equiv.apply_symm_apply @[simp] lemma symm_to_ring_hom_apply_to_ring_hom_apply (e : R ≃+* S) : ∀ (x : R), e.symm.to_ring_hom (e.to_ring_hom x) = x := equiv.symm_apply_apply (e.to_equiv) @[simp] lemma to_ring_hom_trans (e₁ : R ≃+* S) (e₂ : S ≃+* S') : (e₁.trans e₂).to_ring_hom = e₂.to_ring_hom.comp e₁.to_ring_hom := rfl /-- Construct an equivalence of rings from homomorphisms in both directions, which are inverses. -/ def of_hom_inv (hom : R →+* S) (inv : S →+* R) (hom_inv_id : inv.comp hom = ring_hom.id R) (inv_hom_id : hom.comp inv = ring_hom.id S) : R ≃+* S := { inv_fun := inv, left_inv := λ x, ring_hom.congr_fun hom_inv_id x, right_inv := λ x, ring_hom.congr_fun inv_hom_id x, ..hom } @[simp] lemma of_hom_inv_apply (hom : R →+* S) (inv : S →+* R) (hom_inv_id inv_hom_id) (r : R) : (of_hom_inv hom inv hom_inv_id inv_hom_id) r = hom r := rfl @[simp] lemma of_hom_inv_symm_apply (hom : R →+* S) (inv : S →+* R) (hom_inv_id inv_hom_id) (s : S) : (of_hom_inv hom inv hom_inv_id inv_hom_id).symm s = inv s := rfl end semiring_hom end ring_equiv namespace mul_equiv /-- Gives a `ring_equiv` from a `mul_equiv` preserving addition.-/ def to_ring_equiv {R : Type*} {S : Type*} [has_add R] [has_add S] [has_mul R] [has_mul S] (h : R ≃* S) (H : ∀ x y : R, h (x + y) = h x + h y) : R ≃+* S := {..h.to_equiv, ..h, ..add_equiv.mk' h.to_equiv H } end mul_equiv namespace ring_equiv variables [has_add R] [has_add S] [has_mul R] [has_mul S] @[simp] theorem trans_symm (e : R ≃+* S) : e.trans e.symm = ring_equiv.refl R := ext e.3 @[simp] theorem symm_trans (e : R ≃+* S) : e.symm.trans e = ring_equiv.refl S := ext e.4 /-- If two rings are isomorphic, and the second is an integral domain, then so is the first. -/ protected lemma is_integral_domain {A : Type*} (B : Type*) [ring A] [ring B] (hB : is_integral_domain B) (e : A ≃+* B) : is_integral_domain A := { mul_comm := λ x y, have e.symm (e x * e y) = e.symm (e y * e x), by rw hB.mul_comm, by simpa, eq_zero_or_eq_zero_of_mul_eq_zero := λ x y hxy, have e x * e y = 0, by rw [← e.map_mul, hxy, e.map_zero], (hB.eq_zero_or_eq_zero_of_mul_eq_zero _ _ this).imp (λ hx, by simpa using congr_arg e.symm hx) (λ hy, by simpa using congr_arg e.symm hy), exists_pair_ne := ⟨e.symm 0, e.symm 1, by { haveI : nontrivial B := hB.to_nontrivial, exact e.symm.injective.ne zero_ne_one }⟩ } /-- If two rings are isomorphic, and the second is an integral domain, then so is the first. -/ protected def integral_domain {A : Type*} (B : Type*) [ring A] [integral_domain B] (e : A ≃+* B) : integral_domain A := { .. (‹_› : ring A), .. e.is_integral_domain B (integral_domain.to_is_integral_domain B) } end ring_equiv /-- The group of ring automorphisms. -/ @[reducible] def ring_aut (R : Type*) [has_mul R] [has_add R] := ring_equiv R R namespace ring_aut variables (R) [has_mul R] [has_add R] /-- The group operation on automorphisms of a ring is defined by λ g h, ring_equiv.trans h g. This means that multiplication agrees with composition, (g*h)(x) = g (h x) . -/ instance : group (ring_aut R) := by refine_struct { mul := λ g h, ring_equiv.trans h g, one := ring_equiv.refl R, inv := ring_equiv.symm }; intros; ext; try { refl }; apply equiv.left_inv instance : inhabited (ring_aut R) := ⟨1⟩ /-- Monoid homomorphism from ring automorphisms to additive automorphisms. -/ def to_add_aut : ring_aut R →* add_aut R := by refine_struct { to_fun := ring_equiv.to_add_equiv }; intros; refl /-- Monoid homomorphism from ring automorphisms to multiplicative automorphisms. -/ def to_mul_aut : ring_aut R →* mul_aut R := by refine_struct { to_fun := ring_equiv.to_mul_equiv }; intros; refl /-- Monoid homomorphism from ring automorphisms to permutations. -/ def to_perm : ring_aut R →* equiv.perm R := by refine_struct { to_fun := ring_equiv.to_equiv }; intros; refl end ring_aut namespace equiv variables (K : Type*) [division_ring K] /-- In a division ring `K`, the unit group `units K` is equivalent to the subtype of nonzero elements. -/ -- TODO: this might already exist elsewhere for `group_with_zero` -- deduplicate or generalize def units_equiv_ne_zero : units K ≃ {a : K | a ≠ 0} := ⟨λ a, ⟨a.1, a.ne_zero⟩, λ a, units.mk0 _ a.2, λ ⟨_, _, _, _⟩, units.ext rfl, λ ⟨_, _⟩, rfl⟩ variable {K} @[simp] lemma coe_units_equiv_ne_zero (a : units K) : ((units_equiv_ne_zero K a) : K) = a := rfl end equiv
c1b55adf70b4760b3089ed508c56cb66c7e27dd9
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/stage0/src/Std/Data/HashMap.lean
eb3f573b2363da99e48b214e05691bd9adfefbab
[ "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
7,653
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ import Std.Data.AssocList namespace Std universes u v w def HashMapBucket (α : Type u) (β : Type v) := { b : Array (AssocList α β) // b.size > 0 } def HashMapBucket.update {α : Type u} {β : Type v} (data : HashMapBucket α β) (i : USize) (d : AssocList α β) (h : i.toNat < data.val.size) : HashMapBucket α β := ⟨ data.val.uset i d h, by erw [Array.size_set]; exact data.property ⟩ structure HashMapImp (α : Type u) (β : Type v) where size : Nat buckets : HashMapBucket α β def mkHashMapImp {α : Type u} {β : Type v} (nbuckets := 8) : HashMapImp α β := let n := if nbuckets = 0 then 8 else nbuckets; { size := 0, buckets := ⟨ mkArray n AssocList.nil, by simp; cases nbuckets; decide; apply Nat.zeroLtSucc; done ⟩ } namespace HashMapImp variable {α : Type u} {β : Type v} def mkIdx {n : Nat} (h : n > 0) (u : USize) : { u : USize // u.toNat < n } := ⟨u % n, USize.modn_lt _ h⟩ @[inline] def reinsertAux (hashFn : α → USize) (data : HashMapBucket α β) (a : α) (b : β) : HashMapBucket α β := let ⟨i, h⟩ := mkIdx data.property (hashFn a) data.update i (AssocList.cons a b (data.val.uget i h)) h @[inline] def foldBucketsM {δ : Type w} {m : Type w → Type w} [Monad m] (data : HashMapBucket α β) (d : δ) (f : δ → α → β → m δ) : m δ := data.val.foldlM (init := d) fun d b => b.foldlM f d @[inline] def foldBuckets {δ : Type w} (data : HashMapBucket α β) (d : δ) (f : δ → α → β → δ) : δ := Id.run $ foldBucketsM data d f @[inline] def foldM {δ : Type w} {m : Type w → Type w} [Monad m] (f : δ → α → β → m δ) (d : δ) (h : HashMapImp α β) : m δ := foldBucketsM h.buckets d f @[inline] def fold {δ : Type w} (f : δ → α → β → δ) (d : δ) (m : HashMapImp α β) : δ := foldBuckets m.buckets d f @[inline] def forBucketsM {m : Type w → Type w} [Monad m] (data : HashMapBucket α β) (f : α → β → m PUnit) : m PUnit := data.val.forM fun b => b.forM f @[inline] def forM {m : Type w → Type w} [Monad m] (f : α → β → m PUnit) (h : HashMapImp α β) : m PUnit := forBucketsM h.buckets f def findEntry? [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) : Option (α × β) := match m with | ⟨_, buckets⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a) (buckets.val.uget i h).findEntry? a def find? [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) : Option β := match m with | ⟨_, buckets⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a) (buckets.val.uget i h).find? a def contains [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) : Bool := match m with | ⟨_, buckets⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a) (buckets.val.uget i h).contains a -- TODO: remove `partial` by using well-founded recursion partial def moveEntries [Hashable α] (i : Nat) (source : Array (AssocList α β)) (target : HashMapBucket α β) : HashMapBucket α β := if h : i < source.size then let idx : Fin source.size := ⟨i, h⟩ let es : AssocList α β := source.get idx -- We remove `es` from `source` to make sure we can reuse its memory cells when performing es.foldl let source := source.set idx AssocList.nil let target := es.foldl (reinsertAux hash) target moveEntries (i+1) source target else target def expand [Hashable α] (size : Nat) (buckets : HashMapBucket α β) : HashMapImp α β := let nbuckets := buckets.val.size * 2 have nbuckets > 0 from Nat.mulPos buckets.property (by decide) let new_buckets : HashMapBucket α β := ⟨mkArray nbuckets AssocList.nil, by simp; assumption⟩ { size := size, buckets := moveEntries 0 buckets.val new_buckets } def insert [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) (b : β) : HashMapImp α β := match m with | ⟨size, buckets⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a) let bkt := buckets.val.uget i h if bkt.contains a then ⟨size, buckets.update i (bkt.replace a b) h⟩ else let size' := size + 1 let buckets' := buckets.update i (AssocList.cons a b bkt) h if size' ≤ buckets.val.size then { size := size', buckets := buckets' } else expand size' buckets' def erase [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) : HashMapImp α β := match m with | ⟨ size, buckets ⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a) let bkt := buckets.val.uget i h if bkt.contains a then ⟨size - 1, buckets.update i (bkt.erase a) h⟩ else m inductive WellFormed [BEq α] [Hashable α] : HashMapImp α β → Prop where | mkWff : ∀ n, WellFormed (mkHashMapImp n) | insertWff : ∀ m a b, WellFormed m → WellFormed (insert m a b) | eraseWff : ∀ m a, WellFormed m → WellFormed (erase m a) end HashMapImp def HashMap (α : Type u) (β : Type v) [BEq α] [Hashable α] := { m : HashMapImp α β // m.WellFormed } open Std.HashMapImp def mkHashMap {α : Type u} {β : Type v} [BEq α] [Hashable α] (nbuckets := 8) : HashMap α β := ⟨ mkHashMapImp nbuckets, WellFormed.mkWff nbuckets ⟩ namespace HashMap variable {α : Type u} {β : Type v} [BEq α] [Hashable α] instance : Inhabited (HashMap α β) where default := mkHashMap instance : EmptyCollection (HashMap α β) := ⟨mkHashMap⟩ @[inline] def insert (m : HashMap α β) (a : α) (b : β) : HashMap α β := match m with | ⟨ m, hw ⟩ => ⟨ m.insert a b, WellFormed.insertWff m a b hw ⟩ @[inline] def erase (m : HashMap α β) (a : α) : HashMap α β := match m with | ⟨ m, hw ⟩ => ⟨ m.erase a, WellFormed.eraseWff m a hw ⟩ @[inline] def findEntry? (m : HashMap α β) (a : α) : Option (α × β) := match m with | ⟨ m, _ ⟩ => m.findEntry? a @[inline] def find? (m : HashMap α β) (a : α) : Option β := match m with | ⟨ m, _ ⟩ => m.find? a @[inline] def findD (m : HashMap α β) (a : α) (b₀ : β) : β := (m.find? a).getD b₀ @[inline] def find! [Inhabited β] (m : HashMap α β) (a : α) : β := match m.find? a with | some b => b | none => panic! "key is not in the map" @[inline] def getOp (self : HashMap α β) (idx : α) : Option β := self.find? idx @[inline] def contains (m : HashMap α β) (a : α) : Bool := match m with | ⟨ m, _ ⟩ => m.contains a @[inline] def foldM {δ : Type w} {m : Type w → Type w} [Monad m] (f : δ → α → β → m δ) (init : δ) (h : HashMap α β) : m δ := match h with | ⟨ h, _ ⟩ => h.foldM f init @[inline] def fold {δ : Type w} (f : δ → α → β → δ) (init : δ) (m : HashMap α β) : δ := match m with | ⟨ m, _ ⟩ => m.fold f init @[inline] def forM {m : Type w → Type w} [Monad m] (f : α → β → m PUnit) (h : HashMap α β) : m PUnit := match h with | ⟨ h, _ ⟩ => h.forM f @[inline] def size (m : HashMap α β) : Nat := match m with | ⟨ {size := sz, ..}, _ ⟩ => sz @[inline] def isEmpty (m : HashMap α β) : Bool := m.size = 0 @[inline] def empty : HashMap α β := mkHashMap def toList (m : HashMap α β) : List (α × β) := m.fold (init := []) fun r k v => (k, v)::r def toArray (m : HashMap α β) : Array (α × β) := m.fold (init := #[]) fun r k v => r.push (k, v) def numBuckets (m : HashMap α β) : Nat := m.val.buckets.val.size end HashMap end Std
551c4d8fe2690ec23e77d582f02876b337d973db
63abd62053d479eae5abf4951554e1064a4c45b4
/src/tactic/mk_iff_of_inductive_prop.lean
3434f741529f1fc5bc99d2e3a8b318491d50488c
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
8,147
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl Generation function for iff rules for inductives, like for `list.chain`: ∀{α : Type*} (R : α → α → Prop) (a : α) (l : list α), chain R a l ↔ l = [] ∨ ∃{b : α} {l' : list α}, R a b ∧ chain R b l ∧ l = b :: l' -/ import tactic.core namespace tactic open tactic expr meta def mk_iff (e₀ : expr) (e₁ : expr) : expr := `(%%e₀ ↔ %%e₁) meta def select : ℕ → ℕ → tactic unit | 0 0 := skip | 0 (n + 1) := left >> skip | (m + 1) (n + 1) := right >> select m n | (n + 1) 0 := failure /-- `compact_relation bs as_ps`: Produce 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`. TODO: this is copied from Lean's `coinductive_predicates.lean`, export it there. -/ private meta def compact_relation : list expr → list (expr × expr) → list (option expr) × list (expr × expr) | [] ps := ([], ps) | (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, (bs, ps) := compact_relation (bs.map i) ((ps₁ ++ ps₂).map (λ⟨a, p⟩, (a, i p))) in (none :: bs, ps) end meta def constr_to_prop (univs : list level) (g : list expr) (idxs : list expr) (c : name) : tactic ((list (option expr) × (expr ⊕ ℕ)) × expr) := do e ← get_env, decl ← get_decl c, some type' ← return $ decl.instantiate_type_univ_params univs, type ← drop_pis g type', (args, res) ← open_pis type, let idxs_inst := res.get_app_args.drop g.length, let (bs, eqs) := compact_relation args (idxs.zip idxs_inst), let bs' := bs.filter_map id, eqs ← eqs.mmap (λ⟨idx, inst⟩, do let ty := idx.local_type, inst_ty ← infer_type inst, sort u ← infer_type ty, (is_def_eq ty inst_ty >> return ((const `eq [u] : expr) ty idx inst)) <|> return ((const `heq [u] : expr) ty idx inst_ty inst)), (n, r) ← match bs', eqs with | [], [] := return (sum.inr 0, mk_true) | _, [] := do let t : expr := bs'.ilast.local_type, sort l ← infer_type t, if l = level.zero then do r ← mk_exists_lst bs'.init t, return (sum.inl bs'.ilast, r) else do r ← mk_exists_lst bs' mk_true, return (sum.inr 0, r) | _, _ := do r ← mk_exists_lst bs' (mk_and_lst eqs), return (sum.inr eqs.length, r) end, return ((bs, n), r) private meta def to_cases (s : list $ list (option expr) × (expr ⊕ ℕ)) : tactic unit := do h ← intro1, i ← induction h, focus ((s.zip i).enum.map $ λ⟨p, (shape, t), _, vars, _⟩, do let si := (shape.zip vars).filter_map (λ⟨c, v⟩, c >>= λ _, some v), select p (s.length - 1), match t with | sum.inl e := do si.init.mmap' existsi, some v ← return $ vars.nth (shape.length - 1), exact v | sum.inr n := do si.mmap' existsi, iterate_exactly (n - 1) (split >> constructor >> skip) >> constructor >> skip end, done), done private def list_option_merge {α : Type*} {β : Type*} : list (option α) → list β → list (option β) | [] _ := [] | (none :: xs) ys := none :: list_option_merge xs ys | (some a :: xs) (y :: ys) := some y :: list_option_merge xs ys | (some a :: xs) [] := [] private meta def to_inductive (cs : list name) (gs : list expr) (s : list (list (option expr) × (expr ⊕ ℕ))) (h : expr) : tactic unit := match s.length with | 0 := induction h >> skip | (n + 1) := do r ← elim_gen_sum n h, focus ((cs.zip (r.zip s)).map $ λ⟨constr_name, h, bs, e⟩, do let n := (bs.filter_map id).length, match e with | sum.inl e := elim_gen_prod (n - 1) h [] [] >> skip | sum.inr 0 := do (hs, h, _) ← elim_gen_prod n h [] [], clear h | sum.inr (e + 1) := do (hs, h, _) ← elim_gen_prod n h [] [], (es, eq, _) ← elim_gen_prod e h [] [], let es := es ++ [eq], /- `es.mmap' subst`: fails when we have dependent equalities (heq). `subst will change the dependent hypotheses, so that the uniq local names in `es` are wrong afterwards. Instead we revert them and pull them out one by one -/ revert_lst es, es.mmap' (λ_, intro1 >>= subst) end, ctxt ← local_context, let gs := ctxt.take gs.length, let hs := (ctxt.reverse.take n).reverse, let m := gs.map some ++ list_option_merge bs hs, args ← m.mmap (λa, match a with some v := return v | none := mk_mvar end), c ← mk_const constr_name, exact (c.mk_app args), done), done end /-- `mk_iff_of_inductive_prop i r` makes an iff rule for the inductively defined proposition `i`. The new rule `r` has the shape `∀ps is, i as ↔ ⋁_j, ∃cs, is = cs`, where `ps` are the type parameters, `is` are the indices, `j` ranges over all possible constructors, the `cs` are the parameters for each constructors, the equalities `is = cs` are the instantiations for each constructor for each of the indices to the inductive type `i`. In each case, we remove constructor parameters (i.e. `cs`) when the corresponding equality would be just `c = i` for some index `i`. For example: `mk_iff_of_inductive_prop` on `list.chain` produces: ```lean ∀ {α : Type*} (R : α → α → Prop) (a : α) (l : list α), chain R a l ↔ l = [] ∨ ∃{b : α} {l' : list α}, R a b ∧ chain R b l ∧ l = b :: l' ``` -/ meta def mk_iff_of_inductive_prop (i : name) (r : name) : tactic unit := do e ← get_env, guard (e.is_inductive i), let constrs := e.constructors_of i, let params := e.inductive_num_params i, let indices := e.inductive_num_indices i, let rec := match e.recursor_of i with some rec := rec | none := i.append `rec end, decl ← get_decl i, let type := decl.type, let univ_names := decl.univ_params, let univs := univ_names.map level.param, /- we use these names for our universe parameters, maybe we should construct a copy of them using uniq_name -/ (g, `(Prop)) ← open_pis type | fail "Inductive type is not a proposition", let lhs := (const i univs).mk_app g, shape_rhss ← constrs.mmap (constr_to_prop univs (g.take params) (g.drop params)), let shape := shape_rhss.map prod.fst, let rhss := shape_rhss.map prod.snd, add_theorem_by r univ_names ((mk_iff lhs (mk_or_lst rhss)).pis g) (do gs ← intro_lst (g.map local_pp_name), split, focus' [to_cases shape, intro1 >>= to_inductive constrs (gs.take params) shape]), skip end tactic section setup_tactic_parser /-- `mk_iff_of_inductive_prop i r` makes an iff rule for the inductively defined proposition `i`. The new rule `r` has the shape `∀ps is, i as ↔ ⋁_j, ∃cs, is = cs`, where `ps` are the type parameters, `is` are the indices, `j` ranges over all possible constructors, the `cs` are the parameters for each constructors, the equalities `is = cs` are the instantiations for each constructor for each of the indices to the inductive type `i`. In each case, we remove constructor parameters (i.e. `cs`) when the corresponding equality would be just `c = i` for some index `i`. For example: `mk_iff_of_inductive_prop` on `list.chain` produces: ```lean ∀ {α : Type*} (R : α → α → Prop) (a : α) (l : list α), chain R a l ↔ l = [] ∨ ∃{b : α} {l' : list α}, R a b ∧ chain R b l ∧ l = b :: l' ``` -/ @[user_command] meta def mk_iff_of_inductive_prop_cmd (_ : parse (tk "mk_iff_of_inductive_prop")) : parser unit := do i ← ident, r ← ident, tactic.mk_iff_of_inductive_prop i r add_tactic_doc { name := "mk_iff_of_inductive_prop", category := doc_category.cmd, decl_names := [``mk_iff_of_inductive_prop_cmd], tags := ["logic", "environment"] } end
7e93f100a1f97c373e2907b975c064f4b5b25eba
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/topology/metric_space/closeds.lean
f2c25df81218cf5bc00b13bc0a9a0b3594dee2d0
[ "Apache-2.0" ]
permissive
SAAluthwela/mathlib
62044349d72dd63983a8500214736aa7779634d3
83a4b8b990907291421de54a78988c024dc8a552
refs/heads/master
1,679,433,873,417
1,615,998,031,000
1,615,998,031,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
21,277
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sébastien Gouëzel -/ import topology.metric_space.hausdorff_distance import topology.compacts import analysis.specific_limits /-! # Closed subsets This file defines the metric and emetric space structure on the types of closed subsets and nonempty compact subsets of a metric or emetric space. The Hausdorff distance induces an emetric space structure on the type of closed subsets of an emetric space, called `closeds`. Its completeness, resp. compactness, resp. second-countability, follow from the corresponding properties of the original space. In a metric space, the type of nonempty compact subsets (called `nonempty_compacts`) also inherits a metric space structure from the Hausdorff distance, as the Hausdorff edistance is always finite in this context. -/ noncomputable theory open_locale classical topological_space ennreal universe u open classical set function topological_space filter namespace emetric section variables {α : Type u} [emetric_space α] {s : set α} /-- In emetric spaces, the Hausdorff edistance defines an emetric space structure on the type of closed subsets -/ instance closeds.emetric_space : emetric_space (closeds α) := { edist := λs t, Hausdorff_edist s.val t.val, edist_self := λs, Hausdorff_edist_self, edist_comm := λs t, Hausdorff_edist_comm, edist_triangle := λs t u, Hausdorff_edist_triangle, eq_of_edist_eq_zero := λs t h, subtype.eq ((Hausdorff_edist_zero_iff_eq_of_closed s.property t.property).1 h) } /-- The edistance to a closed set depends continuously on the point and the set -/ lemma continuous_inf_edist_Hausdorff_edist : continuous (λp : α × (closeds α), inf_edist p.1 (p.2).val) := begin refine continuous_of_le_add_edist 2 (by simp) _, rintros ⟨x, s⟩ ⟨y, t⟩, calc inf_edist x (s.val) ≤ inf_edist x (t.val) + Hausdorff_edist (t.val) (s.val) : inf_edist_le_inf_edist_add_Hausdorff_edist ... ≤ (inf_edist y (t.val) + edist x y) + Hausdorff_edist (t.val) (s.val) : add_le_add_right inf_edist_le_inf_edist_add_edist _ ... = inf_edist y (t.val) + (edist x y + Hausdorff_edist (s.val) (t.val)) : by simp [add_comm, add_left_comm, Hausdorff_edist_comm, -subtype.val_eq_coe] ... ≤ inf_edist y (t.val) + (edist (x, s) (y, t) + edist (x, s) (y, t)) : add_le_add_left (add_le_add (le_max_left _ _) (le_max_right _ _)) _ ... = inf_edist y (t.val) + 2 * edist (x, s) (y, t) : by rw [← mul_two, mul_comm] end /-- Subsets of a given closed subset form a closed set -/ lemma is_closed_subsets_of_is_closed (hs : is_closed s) : is_closed {t : closeds α | t.val ⊆ s} := begin refine is_closed_of_closure_subset (λt ht x hx, _), -- t : closeds α, ht : t ∈ closure {t : closeds α | t.val ⊆ s}, -- x : α, hx : x ∈ t.val -- goal : x ∈ s have : x ∈ closure s, { refine mem_closure_iff.2 (λε εpos, _), rcases mem_closure_iff.1 ht ε εpos with ⟨u, hu, Dtu⟩, -- u : closeds α, hu : u ∈ {t : closeds α | t.val ⊆ s}, hu' : edist t u < ε rcases exists_edist_lt_of_Hausdorff_edist_lt hx Dtu with ⟨y, hy, Dxy⟩, -- y : α, hy : y ∈ u.val, Dxy : edist x y < ε exact ⟨y, hu hy, Dxy⟩ }, rwa hs.closure_eq at this, end /-- By definition, the edistance on `closeds α` is given by the Hausdorff edistance -/ lemma closeds.edist_eq {s t : closeds α} : edist s t = Hausdorff_edist s.val t.val := rfl /-- In a complete space, the type of closed subsets is complete for the Hausdorff edistance. -/ instance closeds.complete_space [complete_space α] : complete_space (closeds α) := begin /- We will show that, if a sequence of sets `s n` satisfies `edist (s n) (s (n+1)) < 2^{-n}`, then it converges. This is enough to guarantee completeness, by a standard completeness criterion. We use the shorthand `B n = 2^{-n}` in ennreal. -/ let B : ℕ → ℝ≥0∞ := λ n, (2⁻¹)^n, have B_pos : ∀ n, (0:ℝ≥0∞) < B n, by simp [B, ennreal.pow_pos], have B_ne_top : ∀ n, B n ≠ ⊤, by simp [B, ennreal.pow_ne_top], /- Consider a sequence of closed sets `s n` with `edist (s n) (s (n+1)) < B n`. We will show that it converges. The limit set is t0 = ⋂n, closure (⋃m≥n, s m). We will have to show that a point in `s n` is close to a point in `t0`, and a point in `t0` is close to a point in `s n`. The completeness then follows from a standard criterion. -/ refine complete_of_convergent_controlled_sequences B B_pos (λs hs, _), let t0 := ⋂n, closure (⋃m≥n, (s m).val), let t : closeds α := ⟨t0, is_closed_Inter (λ_, is_closed_closure)⟩, use t, -- The inequality is written this way to agree with `edist_le_of_edist_le_geometric_of_tendsto₀` have I1 : ∀n:ℕ, ∀x ∈ (s n).val, ∃y ∈ t0, edist x y ≤ 2 * B n, { /- This is the main difficulty of the proof. Starting from `x ∈ s n`, we want to find a point in `t0` which is close to `x`. Define inductively a sequence of points `z m` with `z n = x` and `z m ∈ s m` and `edist (z m) (z (m+1)) ≤ B m`. This is possible since the Hausdorff distance between `s m` and `s (m+1)` is at most `B m`. This sequence is a Cauchy sequence, therefore converging as the space is complete, to a limit which satisfies the required properties. -/ assume n x hx, obtain ⟨z, hz₀, hz⟩ : ∃ z : Π l, (s (n+l)).val, (z 0:α) = x ∧ ∀ k, edist (z k:α) (z (k+1):α) ≤ B n / 2^k, { -- We prove existence of the sequence by induction. have : ∀ (l : ℕ) (z : (s (n+l)).val), ∃ z' : (s (n+l+1)).val, edist (z:α) z' ≤ B n / 2^l, { assume l z, obtain ⟨z', z'_mem, hz'⟩ : ∃ z' ∈ (s (n+l+1)).val, edist (z:α) z' < B n / 2^l, { apply exists_edist_lt_of_Hausdorff_edist_lt z.2, simp only [B, ennreal.inv_pow, div_eq_mul_inv], rw [← pow_add], apply hs; simp }, exact ⟨⟨z', z'_mem⟩, le_of_lt hz'⟩ }, use [λ k, nat.rec_on k ⟨x, hx⟩ (λl z, some (this l z)), rfl], exact λ k, some_spec (this k _) }, -- it follows from the previous bound that `z` is a Cauchy sequence have : cauchy_seq (λ k, ((z k):α)), from cauchy_seq_of_edist_le_geometric_two (B n) (B_ne_top n) hz, -- therefore, it converges rcases cauchy_seq_tendsto_of_complete this with ⟨y, y_lim⟩, use y, -- the limit point `y` will be the desired point, in `t0` and close to our initial point `x`. -- First, we check it belongs to `t0`. have : y ∈ t0 := mem_Inter.2 (λk, mem_closure_of_tendsto y_lim begin simp only [exists_prop, set.mem_Union, filter.eventually_at_top, set.mem_preimage, set.preimage_Union], exact ⟨k, λ m hm, ⟨n+m, zero_add k ▸ add_le_add (zero_le n) hm, (z m).2⟩⟩ end), use this, -- Then, we check that `y` is close to `x = z n`. This follows from the fact that `y` -- is the limit of `z k`, and the distance between `z n` and `z k` has already been estimated. rw [← hz₀], exact edist_le_of_edist_le_geometric_two_of_tendsto₀ (B n) hz y_lim }, have I2 : ∀n:ℕ, ∀x ∈ t0, ∃y ∈ (s n).val, edist x y ≤ 2 * B n, { /- For the (much easier) reverse inequality, we start from a point `x ∈ t0` and we want to find a point `y ∈ s n` which is close to `x`. `x` belongs to `t0`, the intersection of the closures. In particular, it is well approximated by a point `z` in `⋃m≥n, s m`, say in `s m`. Since `s m` and `s n` are close, this point is itself well approximated by a point `y` in `s n`, as required. -/ assume n x xt0, have : x ∈ closure (⋃m≥n, (s m).val), by apply mem_Inter.1 xt0 n, rcases mem_closure_iff.1 this (B n) (B_pos n) with ⟨z, hz, Dxz⟩, -- z : α, Dxz : edist x z < B n, simp only [exists_prop, set.mem_Union] at hz, rcases hz with ⟨m, ⟨m_ge_n, hm⟩⟩, -- m : ℕ, m_ge_n : m ≥ n, hm : z ∈ (s m).val have : Hausdorff_edist (s m).val (s n).val < B n := hs n m n m_ge_n (le_refl n), rcases exists_edist_lt_of_Hausdorff_edist_lt hm this with ⟨y, hy, Dzy⟩, -- y : α, hy : y ∈ (s n).val, Dzy : edist z y < B n exact ⟨y, hy, calc edist x y ≤ edist x z + edist z y : edist_triangle _ _ _ ... ≤ B n + B n : add_le_add (le_of_lt Dxz) (le_of_lt Dzy) ... = 2 * B n : (two_mul _).symm ⟩ }, -- Deduce from the above inequalities that the distance between `s n` and `t0` is at most `2 B n`. have main : ∀n:ℕ, edist (s n) t ≤ 2 * B n := λn, Hausdorff_edist_le_of_mem_edist (I1 n) (I2 n), -- from this, the convergence of `s n` to `t0` follows. refine tendsto_at_top.2 (λε εpos, _), have : tendsto (λn, 2 * B n) at_top (𝓝 (2 * 0)), from ennreal.tendsto.const_mul (ennreal.tendsto_pow_at_top_nhds_0_of_lt_1 $ by simp [ennreal.one_lt_two]) (or.inr $ by simp), rw mul_zero at this, obtain ⟨N, hN⟩ : ∃ N, ∀ b ≥ N, ε > 2 * B b, from ((tendsto_order.1 this).2 ε εpos).exists_forall_of_at_top, exact ⟨N, λn hn, lt_of_le_of_lt (main n) (hN n hn)⟩ end /-- In a compact space, the type of closed subsets is compact. -/ instance closeds.compact_space [compact_space α] : compact_space (closeds α) := ⟨begin /- by completeness, it suffices to show that it is totally bounded, i.e., for all ε>0, there is a finite set which is ε-dense. start from a set `s` which is ε-dense in α. Then the subsets of `s` are finitely many, and ε-dense for the Hausdorff distance. -/ refine compact_of_totally_bounded_is_closed (emetric.totally_bounded_iff.2 (λε εpos, _)) is_closed_univ, rcases exists_between εpos with ⟨δ, δpos, δlt⟩, rcases emetric.totally_bounded_iff.1 (compact_iff_totally_bounded_complete.1 (@compact_univ α _ _)).1 δ δpos with ⟨s, fs, hs⟩, -- s : set α, fs : finite s, hs : univ ⊆ ⋃ (y : α) (H : y ∈ s), eball y δ -- we first show that any set is well approximated by a subset of `s`. have main : ∀ u : set α, ∃v ⊆ s, Hausdorff_edist u v ≤ δ, { assume u, let v := {x : α | x ∈ s ∧ ∃y∈u, edist x y < δ}, existsi [v, ((λx hx, hx.1) : v ⊆ s)], refine Hausdorff_edist_le_of_mem_edist _ _, { assume x hx, have : x ∈ ⋃y ∈ s, ball y δ := hs (by simp), rcases mem_bUnion_iff.1 this with ⟨y, ys, dy⟩, have : edist y x < δ := by simp at dy; rwa [edist_comm] at dy, exact ⟨y, ⟨ys, ⟨x, hx, this⟩⟩, le_of_lt dy⟩ }, { rintros x ⟨hx1, ⟨y, yu, hy⟩⟩, exact ⟨y, yu, le_of_lt hy⟩ }}, -- introduce the set F of all subsets of `s` (seen as members of `closeds α`). let F := {f : closeds α | f.val ⊆ s}, use F, split, -- `F` is finite { apply @finite_of_finite_image _ _ F (λf, f.val), { exact subtype.val_injective.inj_on F }, { refine fs.finite_subsets.subset (λb, _), simp only [and_imp, set.mem_image, set.mem_set_of_eq, exists_imp_distrib], assume x hx hx', rwa hx' at hx }}, -- `F` is ε-dense { assume u _, rcases main u.val with ⟨t0, t0s, Dut0⟩, have : is_closed t0 := (fs.subset t0s).is_compact.is_closed, let t : closeds α := ⟨t0, this⟩, have : t ∈ F := t0s, have : edist u t < ε := lt_of_le_of_lt Dut0 δlt, apply mem_bUnion_iff.2, exact ⟨t, ‹t ∈ F›, this⟩ } end⟩ /-- In an emetric space, the type of non-empty compact subsets is an emetric space, where the edistance is the Hausdorff edistance -/ instance nonempty_compacts.emetric_space : emetric_space (nonempty_compacts α) := { edist := λs t, Hausdorff_edist s.val t.val, edist_self := λs, Hausdorff_edist_self, edist_comm := λs t, Hausdorff_edist_comm, edist_triangle := λs t u, Hausdorff_edist_triangle, eq_of_edist_eq_zero := λs t h, subtype.eq $ begin have : closure (s.val) = closure (t.val) := Hausdorff_edist_zero_iff_closure_eq_closure.1 h, rwa [s.property.2.is_closed.closure_eq, t.property.2.is_closed.closure_eq] at this, end } /-- `nonempty_compacts.to_closeds` is a uniform embedding (as it is an isometry) -/ lemma nonempty_compacts.to_closeds.uniform_embedding : uniform_embedding (@nonempty_compacts.to_closeds α _ _) := isometry.uniform_embedding $ λx y, rfl /-- The range of `nonempty_compacts.to_closeds` is closed in a complete space -/ lemma nonempty_compacts.is_closed_in_closeds [complete_space α] : is_closed (range $ @nonempty_compacts.to_closeds α _ _) := begin have : range nonempty_compacts.to_closeds = {s : closeds α | s.val.nonempty ∧ is_compact s.val}, from range_inclusion _, rw this, refine is_closed_of_closure_subset (λs hs, ⟨_, _⟩), { -- take a set set t which is nonempty and at a finite distance of s rcases mem_closure_iff.1 hs ⊤ ennreal.coe_lt_top with ⟨t, ht, Dst⟩, rw edist_comm at Dst, -- since `t` is nonempty, so is `s` exact nonempty_of_Hausdorff_edist_ne_top ht.1 (ne_of_lt Dst) }, { refine compact_iff_totally_bounded_complete.2 ⟨_, s.property.is_complete⟩, refine totally_bounded_iff.2 (λε εpos, _), -- we have to show that s is covered by finitely many eballs of radius ε -- pick a nonempty compact set t at distance at most ε/2 of s rcases mem_closure_iff.1 hs (ε/2) (ennreal.half_pos εpos) with ⟨t, ht, Dst⟩, -- cover this space with finitely many balls of radius ε/2 rcases totally_bounded_iff.1 (compact_iff_totally_bounded_complete.1 ht.2).1 (ε/2) (ennreal.half_pos εpos) with ⟨u, fu, ut⟩, refine ⟨u, ⟨fu, λx hx, _⟩⟩, -- u : set α, fu : finite u, ut : t.val ⊆ ⋃ (y : α) (H : y ∈ u), eball y (ε / 2) -- then s is covered by the union of the balls centered at u of radius ε rcases exists_edist_lt_of_Hausdorff_edist_lt hx Dst with ⟨z, hz, Dxz⟩, rcases mem_bUnion_iff.1 (ut hz) with ⟨y, hy, Dzy⟩, have : edist x y < ε := calc edist x y ≤ edist x z + edist z y : edist_triangle _ _ _ ... < ε/2 + ε/2 : ennreal.add_lt_add Dxz Dzy ... = ε : ennreal.add_halves _, exact mem_bUnion hy this }, end /-- In a complete space, the type of nonempty compact subsets is complete. This follows from the same statement for closed subsets -/ instance nonempty_compacts.complete_space [complete_space α] : complete_space (nonempty_compacts α) := (complete_space_iff_is_complete_range nonempty_compacts.to_closeds.uniform_embedding).2 $ nonempty_compacts.is_closed_in_closeds.is_complete /-- In a compact space, the type of nonempty compact subsets is compact. This follows from the same statement for closed subsets -/ instance nonempty_compacts.compact_space [compact_space α] : compact_space (nonempty_compacts α) := ⟨begin rw embedding.compact_iff_compact_image nonempty_compacts.to_closeds.uniform_embedding.embedding, rw [image_univ], exact nonempty_compacts.is_closed_in_closeds.compact end⟩ /-- In a second countable space, the type of nonempty compact subsets is second countable -/ instance nonempty_compacts.second_countable_topology [second_countable_topology α] : second_countable_topology (nonempty_compacts α) := begin haveI : separable_space (nonempty_compacts α) := begin /- To obtain a countable dense subset of `nonempty_compacts α`, start from a countable dense subset `s` of α, and then consider all its finite nonempty subsets. This set is countable and made of nonempty compact sets. It turns out to be dense: by total boundedness, any compact set `t` can be covered by finitely many small balls, and approximations in `s` of the centers of these balls give the required finite approximation of `t`. -/ rcases exists_countable_dense α with ⟨s, cs, s_dense⟩, let v0 := {t : set α | finite t ∧ t ⊆ s}, let v : set (nonempty_compacts α) := {t : nonempty_compacts α | t.val ∈ v0}, refine ⟨⟨v, ⟨_, _⟩⟩⟩, { have : countable (subtype.val '' v), { refine (countable_set_of_finite_subset cs).mono (λx hx, _), rcases (mem_image _ _ _).1 hx with ⟨y, ⟨hy, yx⟩⟩, rw ← yx, exact hy }, apply countable_of_injective_of_countable_image _ this, apply subtype.val_injective.inj_on }, { refine λt, mem_closure_iff.2 (λε εpos, _), -- t is a compact nonempty set, that we have to approximate uniformly by a a set in `v`. rcases exists_between εpos with ⟨δ, δpos, δlt⟩, -- construct a map F associating to a point in α an approximating point in s, up to δ/2. have Exy : ∀x, ∃y, y ∈ s ∧ edist x y < δ/2, { assume x, rcases mem_closure_iff.1 (s_dense x) (δ/2) (ennreal.half_pos δpos) with ⟨y, ys, hy⟩, exact ⟨y, ⟨ys, hy⟩⟩ }, let F := λx, some (Exy x), have Fspec : ∀x, F x ∈ s ∧ edist x (F x) < δ/2 := λx, some_spec (Exy x), -- cover `t` with finitely many balls. Their centers form a set `a` have : totally_bounded t.val := (compact_iff_totally_bounded_complete.1 t.property.2).1, rcases totally_bounded_iff.1 this (δ/2) (ennreal.half_pos δpos) with ⟨a, af, ta⟩, -- a : set α, af : finite a, ta : t.val ⊆ ⋃ (y : α) (H : y ∈ a), eball y (δ / 2) -- replace each center by a nearby approximation in `s`, giving a new set `b` let b := F '' a, have : finite b := af.image _, have tb : ∀x ∈ t.val, ∃y ∈ b, edist x y < δ, { assume x hx, rcases mem_bUnion_iff.1 (ta hx) with ⟨z, za, Dxz⟩, existsi [F z, mem_image_of_mem _ za], calc edist x (F z) ≤ edist x z + edist z (F z) : edist_triangle _ _ _ ... < δ/2 + δ/2 : ennreal.add_lt_add Dxz (Fspec z).2 ... = δ : ennreal.add_halves _ }, -- keep only the points in `b` that are close to point in `t`, yielding a new set `c` let c := {y ∈ b | ∃x∈t.val, edist x y < δ}, have : finite c := ‹finite b›.subset (λx hx, hx.1), -- points in `t` are well approximated by points in `c` have tc : ∀x ∈ t.val, ∃y ∈ c, edist x y ≤ δ, { assume x hx, rcases tb x hx with ⟨y, yv, Dxy⟩, have : y ∈ c := by simp [c, -mem_image]; exact ⟨yv, ⟨x, hx, Dxy⟩⟩, exact ⟨y, this, le_of_lt Dxy⟩ }, -- points in `c` are well approximated by points in `t` have ct : ∀y ∈ c, ∃x ∈ t.val, edist y x ≤ δ, { rintros y ⟨hy1, ⟨x, xt, Dyx⟩⟩, have : edist y x ≤ δ := calc edist y x = edist x y : edist_comm _ _ ... ≤ δ : le_of_lt Dyx, exact ⟨x, xt, this⟩ }, -- it follows that their Hausdorff distance is small have : Hausdorff_edist t.val c ≤ δ := Hausdorff_edist_le_of_mem_edist tc ct, have Dtc : Hausdorff_edist t.val c < ε := lt_of_le_of_lt this δlt, -- the set `c` is not empty, as it is well approximated by a nonempty set have hc : c.nonempty, from nonempty_of_Hausdorff_edist_ne_top t.property.1 (ne_top_of_lt Dtc), -- let `d` be the version of `c` in the type `nonempty_compacts α` let d : nonempty_compacts α := ⟨c, ⟨hc, ‹finite c›.is_compact⟩⟩, have : c ⊆ s, { assume x hx, rcases (mem_image _ _ _).1 hx.1 with ⟨y, ⟨ya, yx⟩⟩, rw ← yx, exact (Fspec y).1 }, have : d ∈ v := ⟨‹finite c›, this⟩, -- we have proved that `d` is a good approximation of `t` as requested exact ⟨d, ‹d ∈ v›, Dtc⟩ }, end, apply second_countable_of_separable, end end --section end emetric --namespace namespace metric section variables {α : Type u} [metric_space α] /-- `nonempty_compacts α` inherits a metric space structure, as the Hausdorff edistance between two such sets is finite. -/ instance nonempty_compacts.metric_space : metric_space (nonempty_compacts α) := emetric_space.to_metric_space $ λx y, Hausdorff_edist_ne_top_of_nonempty_of_bounded x.2.1 y.2.1 (bounded_of_compact x.2.2) (bounded_of_compact y.2.2) /-- The distance on `nonempty_compacts α` is the Hausdorff distance, by construction -/ lemma nonempty_compacts.dist_eq {x y : nonempty_compacts α} : dist x y = Hausdorff_dist x.val y.val := rfl lemma lipschitz_inf_dist_set (x : α) : lipschitz_with 1 (λ s : nonempty_compacts α, inf_dist x s.val) := lipschitz_with.of_le_add $ assume s t, by { rw dist_comm, exact inf_dist_le_inf_dist_add_Hausdorff_dist (edist_ne_top t s) } lemma lipschitz_inf_dist : lipschitz_with 2 (λ p : α × (nonempty_compacts α), inf_dist p.1 p.2.val) := @lipschitz_with.uncurry _ _ _ _ _ _ (λ (x : α) (s : nonempty_compacts α), inf_dist x s.val) 1 1 (λ s, lipschitz_inf_dist_pt s.val) lipschitz_inf_dist_set lemma uniform_continuous_inf_dist_Hausdorff_dist : uniform_continuous (λp : α × (nonempty_compacts α), inf_dist p.1 (p.2).val) := lipschitz_inf_dist.uniform_continuous end --section end metric --namespace
1de6557e0196dfa4bef69397c397e38373cdd240
a537b538f2bea3181e24409d8a52590603d1ddd9
/src/tidy/rewrite_search/discovery/screening.lean
0906333700e4505897ab70f3f1ad0a2977feaf35
[]
no_license
rwbarton/lean-tidy
6134813ded72b275d19d4d32514dba80c21708e3
fe1125d32adb60decda7a77d0f679614ba9f6fbb
refs/heads/master
1,585,549,718,705
1,538,120,619,000
1,538,120,624,000
150,864,330
0
0
null
1,538,225,790,000
1,538,225,790,000
null
UTF-8
Lean
false
false
1,874
lean
import tidy.lib.env import tidy.lib.tactic import tidy.lib.pretty_print open tactic tactic.interactive open interactive namespace tidy.rewrite_search.discovery -- TODO make sure this didn't break anything meta def is_acceptable_rewrite (t : expr) : bool := is_eq_or_iff_after_binders t meta def is_acceptable_lemma (r : expr) : tactic bool := is_acceptable_rewrite <$> infer_type r meta def is_acceptable_hyp (r : expr) : tactic bool := do t ← infer_type r, return $ is_acceptable_rewrite t ∧ ¬t.has_meta_var meta def assert_acceptable_lemma (r : expr) : tactic unit := do ret ← is_acceptable_lemma r, if ret then return () else do pp ← pretty_print r, fail format!"\"{pp}\" is not a valid rewrite lemma!" meta def load_attr_list : list name → tactic (list name) | [] := return [] | (a :: rest) := do names ← attribute.get_instances a, l ← load_attr_list rest, return $ names ++ l meta def load_names (l : list name) : tactic (list expr) := l.mmap mk_const meta def rewrite_list_from_rw_rules (rws : parse rw_rules) : tactic (list (expr × bool)) := rws.rules.mmap (λ r, do e ← to_expr' r.rule, pure (e, r.symm)) meta def rewrite_list_from_lemma (e : expr) : list (expr × bool) := [(e, ff), (e, tt)] meta def rewrite_list_from_lemmas (l : list expr) : list (expr × bool) := l.map (λ e, (e, ff)) ++ l.map (λ e, (e, tt)) meta def rewrite_list_from_hyps (lems : list expr) : tactic (list (expr × bool)) := do hyps ← local_context, rewrite_list_from_lemmas <$> hyps.mfilter is_acceptable_hyp meta def is_rewrite_lemma (d : declaration) : option (name × expr) := let t := d.type in if is_acceptable_rewrite t then some (d.to_name, t) else none meta def find_all_rewrites : tactic (list (name × expr)) := do e ← get_env, return $ e.decl_omap is_rewrite_lemma end tidy.rewrite_search.discovery
ede574f6c686cec9d53e483d50d4526a7cece70d
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/test/fin_cases.lean
818d1ee2ac360dd0277ceaa46607dbccc29417fc
[ "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
2,324
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import tactic.fin_cases import data.nat.prime import group_theory.perm.sign import data.finset.intervals example (f : ℕ → Prop) (p : fin 3) (h0 : f 0) (h1 : f 1) (h2 : f 2) : f p.val := begin fin_cases *, simp, assumption, simp, assumption, simp, assumption, end example (f : ℕ → Prop) (p : fin 0) : f p.val := by fin_cases * example (f : ℕ → Prop) (p : fin 1) (h : f 0) : f p.val := begin fin_cases p, assumption end example (x2 : fin 2) (x3 : fin 3) (n : nat) (y : fin n) : x2.val * x3.val = x3.val * x2.val := begin fin_cases x2; fin_cases x3, success_if_fail { fin_cases * }, success_if_fail { fin_cases y }, all_goals { refl }, end open finset example (x : ℕ) (h : x ∈ Ico 2 5) : x = 2 ∨ x = 3 ∨ x = 4 := begin fin_cases h, all_goals { simp } end open nat example (x : ℕ) (h : x ∈ [2,3,5,7]) : x = 2 ∨ x = 3 ∨ x = 5 ∨ x = 7 := begin fin_cases h, all_goals { simp } end example (x : ℕ) (h : x ∈ [2,3,5,7]) : true := begin success_if_fail { fin_cases h with [3,3,5,7] }, trivial end example (x : list ℕ) (h : x ∈ [[1],[2]]) : x.length = 1 := begin fin_cases h with [[1],[1+1]], simp, guard_target (list.length [1 + 1] = 1), simp end -- testing that `with` arguments are elaborated with respect to the expected type: example (x : ℤ) (h : x ∈ ([2,3] : list ℤ)) : x = 2 ∨ x = 3 := begin fin_cases h with [2,3], all_goals { simp } end instance (n : ℕ) : decidable (prime n) := decidable_prime_1 n example (x : ℕ) (h : x ∈ (range 10).filter prime) : x = 2 ∨ x = 3 ∨ x = 5 ∨ x = 7 := begin fin_cases h; exact dec_trivial end open equiv.perm example (x : (Σ (a : fin 4), fin 4)) (h : x ∈ fin_pairs_lt 4) : x.1.val < 4 := begin fin_cases h; simp, any_goals { exact dec_trivial }, end example (x : fin 3) : x.val < 5 := begin fin_cases x; exact dec_trivial end example (f : ℕ → Prop) (p : fin 3) (h0 : f 0) (h1 : f 1) (h2 : f 2) : f p.val := begin fin_cases *, all_goals { assumption } end example (n : ℕ) (h : n % 3 ∈ [0,1]) : true := begin fin_cases h, guard_hyp h : n % 3 = 0, trivial, guard_hyp h : n % 3 = 1, trivial, end
d1bae09254485faf4c0dbe663453a82823c571f4
8eeb99d0fdf8125f5d39a0ce8631653f588ee817
/src/data/equiv/mul_add.lean
70027be38133ce24b0b930b28d1204e96f150c88
[ "Apache-2.0" ]
permissive
jesse-michael-han/mathlib
a15c58378846011b003669354cbab7062b893cfe
fa6312e4dc971985e6b7708d99a5bc3062485c89
refs/heads/master
1,625,200,760,912
1,602,081,753,000
1,602,081,753,000
181,787,230
0
0
null
1,555,460,682,000
1,555,460,682,000
null
UTF-8
Lean
false
false
18,862
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Callum Sutton, Yury Kudryashov -/ import data.equiv.basic import deprecated.group /-! # Multiplicative and additive equivs In this file we define two extensions of `equiv` called `add_equiv` and `mul_equiv`, which are datatypes representing isomorphisms of `add_monoid`s/`add_group`s and `monoid`s/`group`s. We also introduce the corresponding groups of automorphisms `add_aut` and `mul_aut`. ## Notations The extended equivs all have coercions to functions, and the coercions are the canonical notation when treating the isomorphisms as maps. ## Implementation notes The fields for `mul_equiv`, `add_equiv` now avoid the unbundled `is_mul_hom` and `is_add_hom`, as these are deprecated. Definition of multiplication in the groups of automorphisms agrees with function composition, multiplication in `equiv.perm`, and multiplication in `category_theory.End`, not with `category_theory.comp`. ## Tags equiv, mul_equiv, add_equiv, mul_aut, add_aut -/ variables {A : Type*} {B : Type*} {M : Type*} {N : Type*} {P : Type*} {G : Type*} {H : Type*} set_option old_structure_cmd true /-- add_equiv α β is the type of an equiv α ≃ β which preserves addition. -/ structure add_equiv (A B : Type*) [has_add A] [has_add B] extends A ≃ B := (map_add' : ∀ x y : A, to_fun (x + y) = to_fun x + to_fun y) /-- The `equiv` underlying an `add_equiv`. -/ add_decl_doc add_equiv.to_equiv /-- `mul_equiv α β` is the type of an equiv `α ≃ β` which preserves multiplication. -/ @[to_additive] structure mul_equiv (M N : Type*) [has_mul M] [has_mul N] extends M ≃ N := (map_mul' : ∀ x y : M, to_fun (x * y) = to_fun x * to_fun y) /-- The `equiv` underlying a `mul_equiv`. -/ add_decl_doc mul_equiv.to_equiv infix ` ≃* `:25 := mul_equiv infix ` ≃+ `:25 := add_equiv namespace mul_equiv @[to_additive] instance [has_mul M] [has_mul N] : has_coe_to_fun (M ≃* N) := ⟨_, mul_equiv.to_fun⟩ variables [has_mul M] [has_mul N] [has_mul P] @[simp, to_additive] lemma to_fun_apply {f : M ≃* N} {m : M} : f.to_fun m = f m := rfl @[simp, to_additive] lemma to_equiv_apply {f : M ≃* N} {m : M} : f.to_equiv m = f m := rfl /-- A multiplicative isomorphism preserves multiplication (canonical form). -/ @[simp, to_additive] lemma map_mul (f : M ≃* N) : ∀ x y, f (x * y) = f x * f y := f.map_mul' /-- A multiplicative isomorphism preserves multiplication (deprecated). -/ @[to_additive] instance (h : M ≃* N) : is_mul_hom h := ⟨h.map_mul⟩ /-- Makes a multiplicative isomorphism from a bijection which preserves multiplication. -/ @[to_additive "Makes an additive isomorphism from a bijection which preserves addition."] def mk' (f : M ≃ N) (h : ∀ x y, f (x * y) = f x * f y) : M ≃* N := ⟨f.1, f.2, f.3, f.4, h⟩ @[to_additive] protected lemma bijective (e : M ≃* N) : function.bijective e := e.to_equiv.bijective @[to_additive] protected lemma injective (e : M ≃* N) : function.injective e := e.to_equiv.injective @[to_additive] protected lemma surjective (e : M ≃* N) : function.surjective e := e.to_equiv.surjective /-- The identity map is a multiplicative isomorphism. -/ @[refl, to_additive "The identity map is an additive isomorphism."] def refl (M : Type*) [has_mul M] : M ≃* M := { map_mul' := λ _ _, rfl, ..equiv.refl _} instance : inhabited (M ≃* M) := ⟨refl M⟩ /-- The inverse of an isomorphism is an isomorphism. -/ @[symm, to_additive "The inverse of an isomorphism is an isomorphism."] def symm (h : M ≃* N) : N ≃* M := { map_mul' := λ n₁ n₂, h.injective $ begin have : ∀ x, h (h.to_equiv.symm.to_fun x) = x := h.to_equiv.apply_symm_apply, simp only [this, h.map_mul] end, .. h.to_equiv.symm} @[simp, to_additive] theorem to_equiv_symm (f : M ≃* N) : f.symm.to_equiv = f.to_equiv.symm := rfl @[simp, to_additive] theorem coe_mk (f : M → N) (g h₁ h₂ h₃) : ⇑(mul_equiv.mk f g h₁ h₂ h₃) = f := rfl @[simp, to_additive] theorem coe_symm_mk (f : M → N) (g h₁ h₂ h₃) : ⇑(mul_equiv.mk f g h₁ h₂ h₃).symm = g := rfl /-- Transitivity of multiplication-preserving isomorphisms -/ @[trans, to_additive "Transitivity of addition-preserving isomorphisms"] def trans (h1 : M ≃* N) (h2 : N ≃* P) : (M ≃* P) := { map_mul' := λ x y, show h2 (h1 (x * y)) = h2 (h1 x) * h2 (h1 y), by rw [h1.map_mul, h2.map_mul], ..h1.to_equiv.trans h2.to_equiv } /-- e.right_inv in canonical form -/ @[simp, to_additive] lemma apply_symm_apply (e : M ≃* N) : ∀ y, e (e.symm y) = y := e.to_equiv.apply_symm_apply /-- e.left_inv in canonical form -/ @[simp, to_additive] lemma symm_apply_apply (e : M ≃* N) : ∀ x, e.symm (e x) = x := e.to_equiv.symm_apply_apply @[simp, to_additive] theorem refl_apply (m : M) : refl M m = m := rfl @[simp, to_additive] theorem trans_apply (e₁ : M ≃* N) (e₂ : N ≃* P) (m : M) : e₁.trans e₂ m = e₂ (e₁ m) := rfl @[simp, to_additive] theorem apply_eq_iff_eq (e : M ≃* N) {x y : M} : e x = e y ↔ x = y := e.injective.eq_iff @[to_additive] lemma apply_eq_iff_symm_apply (e : M ≃* N) {x : M} {y : N} : e x = y ↔ x = e.symm y := e.to_equiv.apply_eq_iff_eq_symm_apply @[to_additive] lemma symm_apply_eq (e : M ≃* N) {x y} : e.symm x = y ↔ x = e y := e.to_equiv.symm_apply_eq @[to_additive] lemma eq_symm_apply (e : M ≃* N) {x y} : y = e.symm x ↔ e y = x := e.to_equiv.eq_symm_apply /-- a multiplicative equiv of monoids sends 1 to 1 (and is hence a monoid isomorphism) -/ @[simp, to_additive] lemma map_one {M N} [monoid M] [monoid N] (h : M ≃* N) : h 1 = 1 := by rw [←mul_one (h 1), ←h.apply_symm_apply 1, ←h.map_mul, one_mul] @[simp, to_additive] lemma map_eq_one_iff {M N} [monoid M] [monoid N] (h : M ≃* N) {x : M} : h x = 1 ↔ x = 1 := h.map_one ▸ h.to_equiv.apply_eq_iff_eq @[to_additive] lemma map_ne_one_iff {M N} [monoid M] [monoid N] (h : M ≃* N) {x : M} : h x ≠ 1 ↔ x ≠ 1 := ⟨mt h.map_eq_one_iff.2, mt h.map_eq_one_iff.1⟩ /-- A bijective `monoid` homomorphism is an isomorphism -/ @[to_additive "A bijective `add_monoid` homomorphism is an isomorphism"] noncomputable def of_bijective {M N} [monoid M] [monoid N] (f : M →* N) (hf : function.bijective f) : M ≃* N := { map_mul' := f.map_mul', ..equiv.of_bijective f hf } /-- Extract the forward direction of a multiplicative equivalence as a multiplication-preserving function. -/ @[to_additive "Extract the forward direction of an additive equivalence as an addition-preserving function."] def to_monoid_hom {M N} [monoid M] [monoid N] (h : M ≃* N) : (M →* N) := { map_one' := h.map_one, .. h } @[simp, to_additive] lemma to_monoid_hom_apply {M N} [monoid M] [monoid N] (e : M ≃* N) (x : M) : e.to_monoid_hom x = e x := rfl /-- A multiplicative equivalence of groups preserves inversion. -/ @[simp, to_additive] lemma map_inv [group G] [group H] (h : G ≃* H) (x : G) : h x⁻¹ = (h x)⁻¹ := h.to_monoid_hom.map_inv x /-- A multiplicative bijection between two monoids is a monoid hom (deprecated -- use to_monoid_hom). -/ @[to_additive] instance is_monoid_hom {M N} [monoid M] [monoid N] (h : M ≃* N) : is_monoid_hom h := ⟨h.map_one⟩ /-- A multiplicative bijection between two groups is a group hom (deprecated -- use to_monoid_hom). -/ @[to_additive] instance is_group_hom {G H} [group G] [group H] (h : G ≃* H) : is_group_hom h := { map_mul := h.map_mul } /-- Two multiplicative isomorphisms agree if they are defined by the same underlying function. -/ @[ext, to_additive "Two additive isomorphisms agree if they are defined by the same underlying function."] lemma ext {f g : mul_equiv M N} (h : ∀ x, f x = g x) : f = g := begin have h₁ : f.to_equiv = g.to_equiv := equiv.ext h, cases f, cases g, congr, { exact (funext h) }, { exact congr_arg equiv.inv_fun h₁ } end attribute [ext] add_equiv.ext end mul_equiv /-- An additive equivalence of additive groups preserves subtraction. -/ lemma add_equiv.map_sub [add_group A] [add_group B] (h : A ≃+ B) (x y : A) : h (x - y) = h x - h y := h.to_add_monoid_hom.map_sub x y instance add_equiv.inhabited {M : Type*} [has_add M] : inhabited (M ≃+ M) := ⟨add_equiv.refl M⟩ /-- The group of multiplicative automorphisms. -/ @[to_additive "The group of additive automorphisms."] def mul_aut (M : Type*) [has_mul M] := M ≃* M attribute [reducible] mul_aut add_aut namespace mul_aut variables (M) [has_mul M] /-- The group operation on multiplicative automorphisms is defined by `λ g h, mul_equiv.trans h g`. This means that multiplication agrees with composition, `(g*h)(x) = g (h x)`. -/ instance : group (mul_aut M) := by refine_struct { mul := λ g h, mul_equiv.trans h g, one := mul_equiv.refl M, inv := mul_equiv.symm }; intros; ext; try { refl }; apply equiv.left_inv instance : inhabited (mul_aut M) := ⟨1⟩ @[simp] lemma coe_mul (e₁ e₂ : mul_aut M) : ⇑(e₁ * e₂) = e₁ ∘ e₂ := rfl @[simp] lemma coe_one : ⇑(1 : mul_aut M) = id := rfl lemma mul_def (e₁ e₂ : mul_aut M) : e₁ * e₂ = e₂.trans e₁ := rfl lemma one_def : (1 : mul_aut M) = mul_equiv.refl _ := rfl lemma inv_def (e₁ : mul_aut M) : e₁⁻¹ = e₁.symm := rfl @[simp] lemma mul_apply (e₁ e₂ : mul_aut M) (m : M) : (e₁ * e₂) m = e₁ (e₂ m) := rfl @[simp] lemma one_apply (m : M) : (1 : mul_aut M) m = m := rfl @[simp] lemma apply_inv_self (e : mul_aut M) (m : M) : e (e⁻¹ m) = m := mul_equiv.apply_symm_apply _ _ @[simp] lemma inv_apply_self (e : mul_aut M) (m : M) : e⁻¹ (e m) = m := mul_equiv.apply_symm_apply _ _ /-- Monoid hom from the group of multiplicative automorphisms to the group of permutations. -/ def to_perm : mul_aut M →* equiv.perm M := by refine_struct { to_fun := mul_equiv.to_equiv }; intros; refl /-- group conjugation as a group homomorphism into the automorphism group. `conj g h = g * h * g⁻¹` -/ def conj [group G] : G →* mul_aut G := { to_fun := λ g, { to_fun := λ h, g * h * g⁻¹, inv_fun := λ h, g⁻¹ * h * g, left_inv := λ _, by simp [mul_assoc], right_inv := λ _, by simp [mul_assoc], map_mul' := by simp [mul_assoc] }, map_mul' := λ _ _, by ext; simp [mul_assoc], map_one' := by ext; simp [mul_assoc] } @[simp] lemma conj_apply [group G] (g h : G) : conj g h = g * h * g⁻¹ := rfl @[simp] lemma conj_symm_apply [group G] (g h : G) : (conj g).symm h = g⁻¹ * h * g := rfl @[simp] lemma conj_inv_apply {G : Type*} [group G] (g h : G) : (conj g)⁻¹ h = g⁻¹ * h * g := rfl end mul_aut namespace add_aut variables (A) [has_add A] /-- The group operation on additive automorphisms is defined by `λ g h, mul_equiv.trans h g`. This means that multiplication agrees with composition, `(g*h)(x) = g (h x)`. -/ instance group : group (add_aut A) := by refine_struct { mul := λ g h, add_equiv.trans h g, one := add_equiv.refl A, inv := add_equiv.symm }; intros; ext; try { refl }; apply equiv.left_inv instance : inhabited (add_aut A) := ⟨1⟩ @[simp] lemma coe_mul (e₁ e₂ : add_aut A) : ⇑(e₁ * e₂) = e₁ ∘ e₂ := rfl @[simp] lemma coe_one : ⇑(1 : add_aut A) = id := rfl lemma mul_def (e₁ e₂ : add_aut A) : e₁ * e₂ = e₂.trans e₁ := rfl lemma one_def : (1 : add_aut A) = add_equiv.refl _ := rfl lemma inv_def (e₁ : add_aut A) : e₁⁻¹ = e₁.symm := rfl @[simp] lemma mul_apply (e₁ e₂ : add_aut A) (a : A) : (e₁ * e₂) a = e₁ (e₂ a) := rfl @[simp] lemma one_apply (a : A) : (1 : add_aut A) a = a := rfl @[simp] lemma apply_inv_self (e : add_aut A) (a : A) : e⁻¹ (e a) = a := add_equiv.apply_symm_apply _ _ @[simp] lemma inv_apply_self (e : add_aut A) (a : A) : e (e⁻¹ a) = a := add_equiv.apply_symm_apply _ _ /-- Monoid hom from the group of multiplicative automorphisms to the group of permutations. -/ def to_perm : add_aut A →* equiv.perm A := by refine_struct { to_fun := add_equiv.to_equiv }; intros; refl end add_aut /-- A group is isomorphic to its group of units. -/ @[to_additive to_add_units "An additive group is isomorphic to its group of additive units"] def to_units {G} [group G] : G ≃* units G := { to_fun := λ x, ⟨x, x⁻¹, mul_inv_self _, inv_mul_self _⟩, inv_fun := coe, left_inv := λ x, rfl, right_inv := λ u, units.ext rfl, map_mul' := λ x y, units.ext rfl } namespace units variables [monoid M] [monoid N] [monoid P] /-- A multiplicative equivalence of monoids defines a multiplicative equivalence of their groups of units. -/ def map_equiv (h : M ≃* N) : units M ≃* units N := { inv_fun := map h.symm.to_monoid_hom, left_inv := λ u, ext $ h.left_inv u, right_inv := λ u, ext $ h.right_inv u, .. map h.to_monoid_hom } /-- Left multiplication by a unit of a monoid is a permutation of the underlying type. -/ @[to_additive "Left addition of an additive unit is a permutation of the underlying type."] def mul_left (u : units M) : equiv.perm M := { to_fun := λx, u * x, inv_fun := λx, ↑u⁻¹ * x, left_inv := u.inv_mul_cancel_left, right_inv := u.mul_inv_cancel_left } @[simp, to_additive] lemma coe_mul_left (u : units M) : ⇑u.mul_left = (*) u := rfl @[simp, to_additive] lemma mul_left_symm (u : units M) : u.mul_left.symm = u⁻¹.mul_left := equiv.ext $ λ x, rfl /-- Right multiplication by a unit of a monoid is a permutation of the underlying type. -/ @[to_additive "Right addition of an additive unit is a permutation of the underlying type."] def mul_right (u : units M) : equiv.perm M := { to_fun := λx, x * u, inv_fun := λx, x * ↑u⁻¹, left_inv := λ x, mul_inv_cancel_right x u, right_inv := λ x, inv_mul_cancel_right x u } @[simp, to_additive] lemma coe_mul_right (u : units M) : ⇑u.mul_right = λ x : M, x * u := rfl @[simp, to_additive] lemma mul_right_symm (u : units M) : u.mul_right.symm = u⁻¹.mul_right := equiv.ext $ λ x, rfl end units namespace equiv section group variables [group G] /-- Left multiplication in a `group` is a permutation of the underlying type. -/ @[to_additive "Left addition in an `add_group` is a permutation of the underlying type."] protected def mul_left (a : G) : perm G := (to_units a).mul_left @[simp, to_additive] lemma coe_mul_left (a : G) : ⇑(equiv.mul_left a) = (*) a := rfl @[simp, to_additive] lemma mul_left_symm (a : G) : (equiv.mul_left a).symm = equiv.mul_left a⁻¹ := ext $ λ x, rfl /-- Right multiplication in a `group` is a permutation of the underlying type. -/ @[to_additive "Right addition in an `add_group` is a permutation of the underlying type."] protected def mul_right (a : G) : perm G := (to_units a).mul_right @[simp, to_additive] lemma coe_mul_right (a : G) : ⇑(equiv.mul_right a) = λ x, x * a := rfl @[simp, to_additive] lemma mul_right_symm (a : G) : (equiv.mul_right a).symm = equiv.mul_right a⁻¹ := ext $ λ x, rfl variable (G) /-- Inversion on a `group` is a permutation of the underlying type. -/ @[to_additive "Negation on an `add_group` is a permutation of the underlying type."] protected def inv : perm G := { to_fun := λa, a⁻¹, inv_fun := λa, a⁻¹, left_inv := assume a, inv_inv a, right_inv := assume a, inv_inv a } variable {G} @[simp, to_additive] lemma coe_inv : ⇑(equiv.inv G) = has_inv.inv := rfl @[simp, to_additive] lemma inv_symm : (equiv.inv G).symm = equiv.inv G := rfl end group section point_reflection variables [add_comm_group A] (x y : A) /-- Point reflection in `x` as a permutation. -/ def point_reflection (x : A) : perm A := (equiv.neg A).trans (equiv.add_left (x + x)) lemma point_reflection_apply : point_reflection x y = x + x - y := rfl @[simp] lemma point_reflection_self : point_reflection x x = x := add_sub_cancel _ _ lemma point_reflection_involutive : function.involutive (point_reflection x : A → A) := λ y, by simp only [point_reflection_apply, sub_sub_cancel] @[simp] lemma point_reflection_symm : (point_reflection x).symm = point_reflection x := by { ext y, rw [symm_apply_eq, point_reflection_involutive x y] } /-- `x` is the only fixed point of `point_reflection x`. This lemma requires `x + x = y + y ↔ x = y`. There is no typeclass to use here, so we add it as an explicit argument. -/ lemma point_reflection_fixed_iff_of_bit0_injective {x y : A} (h : function.injective (bit0 : A → A)) : point_reflection x y = y ↔ y = x := sub_eq_iff_eq_add.trans $ h.eq_iff.trans eq_comm end point_reflection end equiv section type_tags /-- Reinterpret `G ≃+ H` as `multiplicative G ≃* multiplicative H`. -/ def add_equiv.to_multiplicative [add_monoid G] [add_monoid H] : (G ≃+ H) ≃ (multiplicative G ≃* multiplicative H) := { to_fun := λ f, ⟨f.to_add_monoid_hom.to_multiplicative, f.symm.to_add_monoid_hom.to_multiplicative, f.3, f.4, f.5⟩, inv_fun := λ f, ⟨f.to_monoid_hom, f.symm.to_monoid_hom, f.3, f.4, f.5⟩, left_inv := λ x, by { ext, refl, }, right_inv := λ x, by { ext, refl, }, } /-- Reinterpret `G ≃* H` as `additive G ≃+ additive H`. -/ def mul_equiv.to_additive [monoid G] [monoid H] : (G ≃* H) ≃ (additive G ≃+ additive H) := { to_fun := λ f, ⟨f.to_monoid_hom.to_additive, f.symm.to_monoid_hom.to_additive, f.3, f.4, f.5⟩, inv_fun := λ f, ⟨f.to_add_monoid_hom, f.symm.to_add_monoid_hom, f.3, f.4, f.5⟩, left_inv := λ x, by { ext, refl, }, right_inv := λ x, by { ext, refl, }, } /-- Reinterpret `additive G ≃+ H` as `G ≃* multiplicative H`. -/ def add_equiv.to_multiplicative' [monoid G] [add_monoid H] : (additive G ≃+ H) ≃ (G ≃* multiplicative H) := { to_fun := λ f, ⟨f.to_add_monoid_hom.to_multiplicative', f.symm.to_add_monoid_hom.to_multiplicative'', f.3, f.4, f.5⟩, inv_fun := λ f, ⟨f.to_monoid_hom, f.symm.to_monoid_hom, f.3, f.4, f.5⟩, left_inv := λ x, by { ext, refl, }, right_inv := λ x, by { ext, refl, }, } /-- Reinterpret `G ≃* multiplicative H` as `additive G ≃+ H` as. -/ def mul_equiv.to_additive' [monoid G] [add_monoid H] : (G ≃* multiplicative H) ≃ (additive G ≃+ H) := add_equiv.to_multiplicative'.symm /-- Reinterpret `G ≃+ additive H` as `multiplicative G ≃* H`. -/ def add_equiv.to_multiplicative'' [add_monoid G] [monoid H] : (G ≃+ additive H) ≃ (multiplicative G ≃* H) := { to_fun := λ f, ⟨f.to_add_monoid_hom.to_multiplicative'', f.symm.to_add_monoid_hom.to_multiplicative', f.3, f.4, f.5⟩, inv_fun := λ f, ⟨f.to_monoid_hom, f.symm.to_monoid_hom, f.3, f.4, f.5⟩, left_inv := λ x, by { ext, refl, }, right_inv := λ x, by { ext, refl, }, } /-- Reinterpret `multiplicative G ≃* H` as `G ≃+ additive H` as. -/ def mul_equiv.to_additive'' [add_monoid G] [monoid H] : (multiplicative G ≃* H) ≃ (G ≃+ additive H) := add_equiv.to_multiplicative''.symm end type_tags
faf1e21fef6839872e48b6f023f880e8f445b3cd
bb31430994044506fa42fd667e2d556327e18dfe
/src/analysis/special_functions/bernstein.lean
67df5d5c9e1915bcc3940d21ad00215f51aa08f9
[ "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
12,831
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.order.field.basic import ring_theory.polynomial.bernstein import topology.continuous_function.polynomial import topology.continuous_function.compact /-! # Bernstein approximations and Weierstrass' theorem We prove that the Bernstein approximations ``` ∑ k : fin (n+1), f (k/n : ℝ) * n.choose k * x^k * (1-x)^(n-k) ``` for a continuous function `f : C([0,1], ℝ)` converge uniformly to `f` as `n` tends to infinity. Our proof follows [Richard Beals' *Analysis, an introduction*][beals-analysis], §7D. The original proof, due to [Bernstein](bernstein1912) in 1912, is probabilistic, and relies on Bernoulli's theorem, which gives bounds for how quickly the observed frequencies in a Bernoulli trial approach the underlying probability. The proof here does not directly rely on Bernoulli's theorem, but can also be given a probabilistic account. * Consider a weighted coin which with probability `x` produces heads, and with probability `1-x` produces tails. * The value of `bernstein n k x` is the probability that such a coin gives exactly `k` heads in a sequence of `n` tosses. * If such an appearance of `k` heads results in a payoff of `f(k / n)`, the `n`-th Bernstein approximation for `f` evaluated at `x` is the expected payoff. * The main estimate in the proof bounds the probability that the observed frequency of heads differs from `x` by more than some `δ`, obtaining a bound of `(4 * n * δ^2)⁻¹`, irrespective of `x`. * This ensures that for `n` large, the Bernstein approximation is (uniformly) close to the payoff function `f`. (You don't need to think in these terms to follow the proof below: it's a giant `calc` block!) This result proves Weierstrass' theorem that polynomials are dense in `C([0,1], ℝ)`, although we defer an abstract statement of this until later. -/ noncomputable theory open_locale classical open_locale big_operators open_locale bounded_continuous_function open_locale unit_interval /-- The Bernstein polynomials, as continuous functions on `[0,1]`. -/ def bernstein (n ν : ℕ) : C(I, ℝ) := (bernstein_polynomial ℝ n ν).to_continuous_map_on I @[simp] lemma bernstein_apply (n ν : ℕ) (x : I) : bernstein n ν x = n.choose ν * x^ν * (1-x)^(n-ν) := begin dsimp [bernstein, polynomial.to_continuous_map_on, polynomial.to_continuous_map, bernstein_polynomial], simp, end lemma bernstein_nonneg {n ν : ℕ} {x : I} : 0 ≤ bernstein n ν x := begin simp only [bernstein_apply], exact mul_nonneg (mul_nonneg (nat.cast_nonneg _) (pow_nonneg (by unit_interval) _)) (pow_nonneg (by unit_interval) _), end /-! We now give a slight reformulation of `bernstein_polynomial.variance`. -/ namespace bernstein /-- Send `k : fin (n+1)` to the equally spaced points `k/n` in the unit interval. -/ def z {n : ℕ} (k : fin (n+1)) : I := ⟨(k : ℝ) / n, begin cases n, { norm_num }, { have h₁ : 0 < (n.succ : ℝ) := by exact_mod_cast (nat.succ_pos _), have h₂ : ↑k ≤ n.succ := by exact_mod_cast (fin.le_last k), rw [set.mem_Icc, le_div_iff h₁, div_le_iff h₁], norm_cast, simp [h₂], }, end⟩ local postfix `/ₙ`:90 := z lemma probability (n : ℕ) (x : I) : ∑ k : fin (n+1), bernstein n k x = 1 := begin have := bernstein_polynomial.sum ℝ n, apply_fun (λ p, polynomial.aeval (x : ℝ) p) at this, simp [alg_hom.map_sum, finset.sum_range] at this, exact this, end lemma variance {n : ℕ} (h : 0 < (n : ℝ)) (x : I) : ∑ k : fin (n+1), (x - k/ₙ : ℝ)^2 * bernstein n k x = x * (1-x) / n := begin have h' : (n : ℝ) ≠ 0 := ne_of_gt h, apply_fun (λ x : ℝ, x * n) using group_with_zero.mul_right_injective h', apply_fun (λ x : ℝ, x * n) using group_with_zero.mul_right_injective h', dsimp, conv_lhs { simp only [finset.sum_mul, z], }, conv_rhs { rw div_mul_cancel _ h', }, have := bernstein_polynomial.variance ℝ n, apply_fun (λ p, polynomial.aeval (x : ℝ) p) at this, simp [alg_hom.map_sum, finset.sum_range, ←polynomial.nat_cast_mul] at this, convert this using 1, { congr' 1, funext k, rw [mul_comm _ (n : ℝ), mul_comm _ (n : ℝ), ←mul_assoc, ←mul_assoc], congr' 1, field_simp [h], ring, }, { ring, }, end end bernstein open bernstein local postfix `/ₙ`:2000 := z /-- The `n`-th approximation of a continuous function on `[0,1]` by Bernstein polynomials, given by `∑ k, f (k/n) * bernstein n k x`. -/ def bernstein_approximation (n : ℕ) (f : C(I, ℝ)) : C(I, ℝ) := ∑ k : fin (n+1), f k/ₙ • bernstein n k /-! We now set up some of the basic machinery of the proof that the Bernstein approximations converge uniformly. A key player is the set `S f ε h n x`, for some function `f : C(I, ℝ)`, `h : 0 < ε`, `n : ℕ` and `x : I`. This is the set of points `k` in `fin (n+1)` such that `k/n` is within `δ` of `x`, where `δ` is the modulus of uniform continuity for `f`, chosen so `|f x - f y| < ε/2` when `|x - y| < δ`. We show that if `k ∉ S`, then `1 ≤ δ^-2 * (x - k/n)^2`. -/ namespace bernstein_approximation @[simp] lemma apply (n : ℕ) (f : C(I, ℝ)) (x : I) : bernstein_approximation n f x = ∑ k : fin (n+1), f k/ₙ * bernstein n k x := by simp [bernstein_approximation] /-- The modulus of (uniform) continuity for `f`, chosen so `|f x - f y| < ε/2` when `|x - y| < δ`. -/ def δ (f : C(I, ℝ)) (ε : ℝ) (h : 0 < ε) : ℝ := f.modulus (ε/2) (half_pos h) lemma δ_pos {f : C(I, ℝ)} {ε : ℝ} {h : 0 < ε} : 0 < δ f ε h := f.modulus_pos /-- The set of points `k` so `k/n` is within `δ` of `x`. -/ def S (f : C(I, ℝ)) (ε : ℝ) (h : 0 < ε) (n : ℕ) (x : I) : finset (fin (n+1)) := { k : fin (n+1) | dist k/ₙ x < δ f ε h }.to_finset /-- If `k ∈ S`, then `f(k/n)` is close to `f x`. -/ lemma lt_of_mem_S {f : C(I, ℝ)} {ε : ℝ} {h : 0 < ε} {n : ℕ} {x : I} {k : fin (n+1)} (m : k ∈ S f ε h n x) : |f k/ₙ - f x| < ε/2 := begin apply f.dist_lt_of_dist_lt_modulus (ε/2) (half_pos h), simpa [S] using m, end /-- If `k ∉ S`, then as `δ ≤ |x - k/n|`, we have the inequality `1 ≤ δ^-2 * (x - k/n)^2`. This particular formulation will be helpful later. -/ lemma le_of_mem_S_compl {f : C(I, ℝ)} {ε : ℝ} {h : 0 < ε} {n : ℕ} {x : I} {k : fin (n+1)} (m : k ∈ (S f ε h n x)ᶜ) : (1 : ℝ) ≤ (δ f ε h)^(-2 : ℤ) * (x - k/ₙ) ^ 2 := begin simp only [finset.mem_compl, not_lt, set.mem_to_finset, set.mem_set_of_eq, S] at m, rw [zpow_neg, ← div_eq_inv_mul, zpow_two, ←pow_two, one_le_div (pow_pos δ_pos 2), sq_le_sq, abs_of_pos δ_pos], rwa [dist_comm] at m end end bernstein_approximation open bernstein_approximation open bounded_continuous_function open filter open_locale topological_space /-- The Bernstein approximations ``` ∑ k : fin (n+1), f (k/n : ℝ) * n.choose k * x^k * (1-x)^(n-k) ``` for a continuous function `f : C([0,1], ℝ)` converge uniformly to `f` as `n` tends to infinity. This is the proof given in [Richard Beals' *Analysis, an introduction*][beals-analysis], §7D, and reproduced on wikipedia. -/ theorem bernstein_approximation_uniform (f : C(I, ℝ)) : tendsto (λ n : ℕ, bernstein_approximation n f) at_top (𝓝 f) := begin simp only [metric.nhds_basis_ball.tendsto_right_iff, metric.mem_ball, dist_eq_norm], intros ε h, let δ := δ f ε h, have nhds_zero := tendsto_const_div_at_top_nhds_0_nat (2 * ‖f‖ * δ ^ (-2 : ℤ)), filter_upwards [nhds_zero.eventually (gt_mem_nhds (half_pos h)), eventually_gt_at_top 0] with n nh npos', have npos : 0 < (n:ℝ) := by exact_mod_cast npos', -- Two easy inequalities we'll need later: have w₁ : 0 ≤ 2 * ‖f‖ := mul_nonneg (by norm_num) (norm_nonneg f), have w₂ : 0 ≤ 2 * ‖f‖ * δ^(-2 : ℤ) := mul_nonneg w₁ pow_minus_two_nonneg, -- As `[0,1]` is compact, it suffices to check the inequality pointwise. rw (continuous_map.norm_lt_iff _ h), intro x, -- The idea is to split up the sum over `k` into two sets, -- `S`, where `x - k/n < δ`, and its complement. let S := S f ε h n x, calc |(bernstein_approximation n f - f) x| = |bernstein_approximation n f x - f x| : rfl ... = |bernstein_approximation n f x - f x * 1| : by rw mul_one ... = |bernstein_approximation n f x - f x * (∑ k : fin (n+1), bernstein n k x)| : by rw bernstein.probability ... = |∑ k : fin (n+1), (f k/ₙ - f x) * bernstein n k x| : by simp [bernstein_approximation, finset.mul_sum, sub_mul] ... ≤ ∑ k : fin (n+1), |(f k/ₙ - f x) * bernstein n k x| : finset.abs_sum_le_sum_abs _ _ ... = ∑ k : fin (n+1), |f k/ₙ - f x| * bernstein n k x : by simp_rw [abs_mul, abs_eq_self.mpr bernstein_nonneg] ... = ∑ k in S, |f k/ₙ - f x| * bernstein n k x + ∑ k in Sᶜ, |f k/ₙ - f x| * bernstein n k x : (S.sum_add_sum_compl _).symm -- We'll now deal with the terms in `S` and the terms in `Sᶜ` in separate calc blocks. ... < ε/2 + ε/2 : add_lt_add_of_le_of_lt _ _ ... = ε : add_halves ε, { -- We now work on the terms in `S`: uniform continuity and `bernstein.probability` -- quickly give us a bound. calc ∑ k in S, |f k/ₙ - f x| * bernstein n k x ≤ ∑ k in S, ε/2 * bernstein n k x : finset.sum_le_sum (λ k m, (mul_le_mul_of_nonneg_right (le_of_lt (lt_of_mem_S m)) bernstein_nonneg)) ... = ε/2 * ∑ k in S, bernstein n k x : by rw finset.mul_sum -- In this step we increase the sum over `S` back to a sum over all of `fin (n+1)`, -- so that we can use `bernstein.probability`. ... ≤ ε/2 * ∑ k : fin (n+1), bernstein n k x : mul_le_mul_of_nonneg_left (finset.sum_le_univ_sum_of_nonneg (λ k, bernstein_nonneg)) (le_of_lt (half_pos h)) ... = ε/2 : by rw [bernstein.probability, mul_one] }, { -- We now turn to working on `Sᶜ`: we control the difference term just using `‖f‖`, -- and then insert a `δ^(-2) * (x - k/n)^2` factor -- (which is at least one because we are not in `S`). calc ∑ k in Sᶜ, |f k/ₙ - f x| * bernstein n k x ≤ ∑ k in Sᶜ, (2 * ‖f‖) * bernstein n k x : finset.sum_le_sum (λ k m, mul_le_mul_of_nonneg_right (f.dist_le_two_norm _ _) bernstein_nonneg) ... = (2 * ‖f‖) * ∑ k in Sᶜ, bernstein n k x : by rw finset.mul_sum ... ≤ (2 * ‖f‖) * ∑ k in Sᶜ, δ^(-2 : ℤ) * (x - k/ₙ)^2 * bernstein n k x : mul_le_mul_of_nonneg_left (finset.sum_le_sum (λ k m, begin conv_lhs { rw ←one_mul (bernstein _ _ _), }, exact mul_le_mul_of_nonneg_right (le_of_mem_S_compl m) bernstein_nonneg, end)) w₁ -- Again enlarging the sum from `Sᶜ` to all of `fin (n+1)` ... ≤ (2 * ‖f‖) * ∑ k : fin (n+1), δ^(-2 : ℤ) * (x - k/ₙ)^2 * bernstein n k x : mul_le_mul_of_nonneg_left (finset.sum_le_univ_sum_of_nonneg (λ k, mul_nonneg (mul_nonneg pow_minus_two_nonneg (sq_nonneg _)) bernstein_nonneg)) w₁ ... = (2 * ‖f‖) * δ^(-2 : ℤ) * ∑ k : fin (n+1), (x - k/ₙ)^2 * bernstein n k x : by conv_rhs { rw [mul_assoc, finset.mul_sum], simp only [←mul_assoc], } -- `bernstein.variance` and `x ∈ [0,1]` gives the uniform bound ... = (2 * ‖f‖) * δ^(-2 : ℤ) * x * (1-x) / n : by { rw variance npos, ring, } ... ≤ (2 * ‖f‖) * δ^(-2 : ℤ) / n : (div_le_div_right npos).mpr $ by refine mul_le_of_le_of_le_one' (mul_le_of_le_one_right w₂ _) _ _ w₂; unit_interval ... < ε/2 : nh, } end
d9fb01ce90b8daa6c3c895b005d3a73eab579f5f
ea5678cc400c34ff95b661fa26d15024e27ea8cd
/perfect_logician.lean
dcd597dfc6e8329d3c6c01f56c580241ffc821d3
[]
no_license
ChrisHughes24/leanstuff
dca0b5349c3ed893e8792ffbd98cbcadaff20411
9efa85f72efaccd1d540385952a6acc18fce8687
refs/heads/master
1,654,883,241,759
1,652,873,885,000
1,652,873,885,000
134,599,537
1
0
null
null
null
null
UTF-8
Lean
false
false
2,779
lean
import data.nat.basic open nat def island_rules : ℕ → ℕ → (ℕ → Prop) | 0 b := λ bb, (bb = b ∨ bb = b - 1) ∧ bb > 0 | (succ d) b := (λ bb, (island_rules d b) bb ∧ ((∀ c, (island_rules d b) c → c = b) ↔ (∀ c, (island_rules d bb) c → c = bb))) theorem init_island {d b bb} : (island_rules d b) bb → (bb = b ∨ bb = b - 1) ∧ bb > 0 := begin induction d with d hi,unfold island_rules,assume h,exact h, unfold island_rules,assume h,exact hi h.left end theorem blue_eyed_islander : ∀ d b : ℕ, b > 0 → (d + 1 ≥ b ↔ (∀ bb:ℕ, (island_rules d b) bb → bb = b)):=begin assume d,induction d with d hi,assume b, simp[island_rules], cases b,simp[(dec_trivial:¬0>0)], cases b,assume h,simp[(dec_trivial:1≥1)],assume bb hbb,cases hbb,assume hbb1,rw hbb, rw hbb,simp[(dec_trivial:¬0>0)], assume h,simp[(dec_trivial:¬ 1 ≥ succ (succ b))],assume hbb, have h1:=hbb (succ b),simp[(dec_trivial:succ b>0),succ_ne_self (succ b)] at h1, exact (succ_ne_self b).symm h1, assume b hb,apply iff.intro, assume hd,cases lt_or_eq_of_le hd,unfold island_rules,assume bb hbb, have hd1 : succ d ≥ b:=le_of_succ_le_succ (succ_le_of_lt h),rw add_one at hi, exact iff.elim_left (hi b hb) hd1 bb hbb.left, have hi1:= hi b hb,rw succ_add at h,rw h at hi1, have hd1:¬d+1 ≥ succ(d+1) :=not_le_of_gt (lt_succ_self (d+1)), simp[hd1] at hi1,unfold island_rules,assume bb hbb, have hbb1:=init_island hbb.left, cases hbb1.left with hbb2 hbb2,assumption, have hbbd:d + 1 ≥ bb,rw[eq_comm,nat.sub_eq_iff_eq_add (succ_le_of_lt hb)] at hbb2, rw [hbb2,succ_add,add_one bb] at hd,exact le_of_succ_le_succ hd, exact iff.elim_right hbb.right (iff.elim_left (hi bb hbb1.right) hbbd) bb hbb.left, assume hbb,apply by_contradiction,assume hd,have hd1:=lt_of_not_ge hd, rw succ_add at hd1,have hd2:¬d + 1 ≥ b:=not_le_of_gt (lt_of_succ_lt hd1), have hi1:= hi b hb,simp [hd2] at hi1,unfold island_rules at hbb, rw classical.not_forall at hi1,cases hi1 with bb hbb1, rw @not_imp _ _ (classical.prop_decidable _)at hbb1, have hbb2:=hbb bb, have hbb3:= init_island hbb1.left,simp[hbb1.right] at hbb3, have hbb4:=hi bb hbb3.right, rw [eq_comm,nat.sub_eq_iff_eq_add (succ_le_of_lt hb)] at hbb3, rw [hbb3.left,add_one bb] at hd1,have hbbd:¬d + 1 ≥ bb:= not_le_of_gt (lt_of_succ_lt_succ hd1), simp[hbbd] at hbb4, have:¬∀ (c : ℕ), island_rules d b c → c = b,assume hbb4,have:=hbb4 bb hbb1.left, rw [hbb3.left,add_one,eq_comm] at this,exact succ_ne_self bb this, simp[hbb4,hbb1.left,this] at hbb2, rw [hbb3.left,add_one,eq_comm] at hbb2,exact succ_ne_self bb hbb2, end #print blue_eyed_islander
8fdfa1959b358b072d3b26c3c7545aaf8b831324
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/ring_hom/finite.lean
a42d5a5ea96bc35f45d363038fc59a788a1ac83b
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
1,015
lean
/- Copyright (c) 2021 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import ring_theory.ring_hom_properties /-! # The meta properties of finite ring homomorphisms. -/ namespace ring_hom open_locale tensor_product open tensor_product algebra.tensor_product lemma finite_stable_under_composition : stable_under_composition @finite := by { introv R hf hg, exactI hg.comp hf } lemma finite_respects_iso : respects_iso @finite := begin apply finite_stable_under_composition.respects_iso, introsI, exact finite.of_surjective _ e.to_equiv.surjective, end lemma finite_stable_under_base_change : stable_under_base_change @finite := begin classical, introv R h, resetI, replace h : module.finite R T := by { convert h, ext, rw algebra.smul_def, refl }, suffices : module.finite S (S ⊗[R] T), { change module.finite _ _, convert this, ext, rw algebra.smul_def, refl }, exactI infer_instance end end ring_hom
885f7c863c345fbc3e45c07e38f493f327c55a80
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/list/destutter.lean
b6a7de18ec97bb92e34704602949721dcfaaef58
[ "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
4,502
lean
/- Copyright (c) 2022 Eric Rodriguez. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Rodriguez, Eric Wieser -/ import data.list.chain /-! # Destuttering of Lists > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file proves theorems about `list.destutter` (in `data.list.defs`), which greedily removes all non-related items that are adjacent in a list, e.g. `[2, 2, 3, 3, 2].destutter (≠) = [2, 3, 2]`. Note that we make no guarantees of being the longest sublist with this property; e.g., `[123, 1, 2, 5, 543, 1000].destutter (<) = [123, 543, 1000]`, but a longer ascending chain could be `[1, 2, 5, 543, 1000]`. ## Main statements * `list.destutter_sublist`: `l.destutter` is a sublist of `l`. * `list.destutter_is_chain'`: `l.destutter` satisfies `chain' R`. * Analogies of these theorems for `list.destutter'`, which is the `destutter` equivalent of `chain`. ## Tags adjacent, chain, duplicates, remove, list, stutter, destutter -/ variables {α : Type*} (l : list α) (R : α → α → Prop) [decidable_rel R] {a b : α} namespace list @[simp] lemma destutter'_nil : destutter' R a [] = [a] := rfl lemma destutter'_cons : (b :: l).destutter' R a = if R a b then a :: destutter' R b l else destutter' R a l := rfl variables {R} @[simp] lemma destutter'_cons_pos (h : R b a) : (a :: l).destutter' R b = b :: l.destutter' R a := by rw [destutter', if_pos h] @[simp] lemma destutter'_cons_neg (h : ¬ R b a) : (a :: l).destutter' R b = l.destutter' R b := by rw [destutter', if_neg h] variables (R) @[simp] lemma destutter'_singleton : [b].destutter' R a = if R a b then [a, b] else [a] := by split_ifs; simp! [h] lemma destutter'_sublist (a) : l.destutter' R a <+ a :: l := begin induction l with b l hl generalizing a, { simp }, rw destutter', split_ifs, { exact sublist.cons2 _ _ _ (hl b) }, { exact (hl a).trans ((l.sublist_cons b).cons_cons a) } end lemma mem_destutter' (a) : a ∈ l.destutter' R a := begin induction l with b l hl, { simp }, rw destutter', split_ifs, { simp }, { assumption } end lemma destutter'_is_chain : ∀ l : list α, ∀ {a b}, R a b → (l.destutter' R b).chain R a | [] a b h := chain_singleton.mpr h | (c :: l) a b h := begin rw destutter', split_ifs with hbc, { rw chain_cons, exact ⟨h, destutter'_is_chain l hbc⟩ }, { exact destutter'_is_chain l h }, end lemma destutter'_is_chain' (a) : (l.destutter' R a).chain' R := begin induction l with b l hl generalizing a, { simp }, rw destutter', split_ifs, { exact destutter'_is_chain R l h }, { exact hl a }, end lemma destutter'_of_chain (h : l.chain R a) : l.destutter' R a = a :: l := begin induction l with b l hb generalizing a, { simp }, obtain ⟨h, hc⟩ := chain_cons.mp h, rw [l.destutter'_cons_pos h, hb hc] end @[simp] lemma destutter'_eq_self_iff (a) : l.destutter' R a = a :: l ↔ l.chain R a := ⟨λ h, by { rw [←chain', ←h], exact l.destutter'_is_chain' R a }, destutter'_of_chain _ _⟩ lemma destutter'_ne_nil : l.destutter' R a ≠ [] := ne_nil_of_mem $ l.mem_destutter' R a @[simp] lemma destutter_nil : ([] : list α).destutter R = [] := rfl lemma destutter_cons' : (a :: l).destutter R = destutter' R a l := rfl lemma destutter_cons_cons : (a :: b :: l).destutter R = if R a b then a :: destutter' R b l else destutter' R a l := rfl @[simp] lemma destutter_singleton : destutter R [a] = [a] := rfl @[simp] lemma destutter_pair : destutter R [a, b] = if R a b then [a, b] else [a] := destutter_cons_cons _ R lemma destutter_sublist : ∀ (l : list α), l.destutter R <+ l | [] := sublist.slnil | (h :: l) := l.destutter'_sublist R h lemma destutter_is_chain' : ∀ (l : list α), (l.destutter R).chain' R | [] := list.chain'_nil | (h :: l) := l.destutter'_is_chain' R h lemma destutter_of_chain' : ∀ (l : list α), l.chain' R → l.destutter R = l | [] h := rfl | (a :: l) h := l.destutter'_of_chain _ h @[simp] lemma destutter_eq_self_iff : ∀ (l : list α), l.destutter R = l ↔ l.chain' R | [] := by simp | (a :: l) := l.destutter'_eq_self_iff R a lemma destutter_idem : (l.destutter R).destutter R = l.destutter R := destutter_of_chain' R _ $ l.destutter_is_chain' R @[simp] lemma destutter_eq_nil : ∀ {l : list α}, destutter R l = [] ↔ l = [] | [] := iff.rfl | (a :: l) := ⟨λ h, absurd h $ l.destutter'_ne_nil R, λ h, match h with end⟩ end list
6c94123b5443394f68f30a89baae45f89a5d0f72
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/univ2.lean
4ade51cf7c9f2001e662f9b0f987ba26b8e29632
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
217
lean
axiom I : Type definition F (X : Type) : Type := (X → Prop) → Prop axiom unfoldd : I → F I axiom foldd : F I → I axiom iso1 : ∀x, foldd (unfoldd x) = x theorem iso2 : ∀x, foldd (unfoldd x) = x := sorry
e9fb6cf0451f77dbfdc2e9c82d5db2ad204f416c
8b9f17008684d796c8022dab552e42f0cb6fb347
/library/init/logic.lean
f9b7cba8d4cd82e38d273e5eac516e996d757993
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
16,193
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: init.logic Authors: Leonardo de Moura, Jeremy Avigad, Floris van Doorn -/ prelude import init.datatypes init.reserved_notation /- implication -/ definition trivial := true.intro definition not (a : Prop) := a → false prefix `¬` := not definition absurd {a : Prop} {b : Type} (H1 : a) (H2 : ¬a) : b := false.rec b (H2 H1) /- not -/ definition not_false : ¬false := assume H : false, H definition non_contradictory (a : Prop) : Prop := ¬¬a theorem non_contradictory_intro {a : Prop} (Ha : a) : ¬¬a := assume Hna : ¬a, absurd Ha Hna /- eq -/ notation a = b := eq a b definition rfl {A : Type} {a : A} := eq.refl a -- proof irrelevance is built in theorem proof_irrel {a : Prop} (H₁ H₂ : a) : H₁ = H₂ := rfl namespace eq variables {A : Type} variables {a b c a': A} theorem subst {P : A → Prop} (H₁ : a = b) (H₂ : P a) : P b := eq.rec H₂ H₁ theorem trans (H₁ : a = b) (H₂ : b = c) : a = c := subst H₂ H₁ definition symm (H : a = b) : b = a := eq.rec (refl a) H namespace ops notation H `⁻¹` := symm H --input with \sy or \-1 or \inv notation H1 ⬝ H2 := trans H1 H2 notation H1 ▸ H2 := subst H1 H2 end ops end eq section variables {A : Type} {a b c: A} open eq.ops definition trans_rel_left (R : A → A → Prop) (H₁ : R a b) (H₂ : b = c) : R a c := H₂ ▸ H₁ definition trans_rel_right (R : A → A → Prop) (H₁ : a = b) (H₂ : R b c) : R a c := H₁⁻¹ ▸ H₂ end section variable {p : Prop} open eq.ops theorem of_eq_true (H : p = true) : p := H⁻¹ ▸ trivial theorem not_of_eq_false (H : p = false) : ¬p := assume Hp, H ▸ Hp end calc_subst eq.subst calc_refl eq.refl calc_trans eq.trans calc_symm eq.symm /- ne -/ definition ne {A : Type} (a b : A) := ¬(a = b) notation a ≠ b := ne a b namespace ne open eq.ops variable {A : Type} variables {a b : A} theorem intro : (a = b → false) → a ≠ b := assume H, H theorem elim : a ≠ b → a = b → false := assume H₁ H₂, H₁ H₂ theorem irrefl : a ≠ a → false := assume H, H rfl theorem symm : a ≠ b → b ≠ a := assume (H : a ≠ b) (H₁ : b = a), H (H₁⁻¹) end ne section open eq.ops variables {A : Type} {a b c : A} theorem false.of_ne : a ≠ a → false := assume H, H rfl end infixl `==`:50 := heq namespace heq universe variable u variables {A B C : Type.{u}} {a a' : A} {b b' : B} {c : C} definition to_eq (H : a == a') : a = a' := have H₁ : ∀ (Ht : A = A), eq.rec_on Ht a = a, from λ Ht, eq.refl (eq.rec_on Ht a), heq.rec_on H H₁ (eq.refl A) definition elim {A : Type} {a : A} {P : A → Type} {b : A} (H₁ : a == b) (H₂ : P a) : P b := eq.rec_on (to_eq H₁) H₂ theorem subst {P : ∀T : Type, T → Prop} (H₁ : a == b) (H₂ : P A a) : P B b := heq.rec_on H₁ H₂ theorem symm (H : a == b) : b == a := heq.rec_on H (refl a) theorem of_eq (H : a = a') : a == a' := eq.subst H (refl a) theorem trans (H₁ : a == b) (H₂ : b == c) : a == c := subst H₂ H₁ theorem of_heq_of_eq (H₁ : a == b) (H₂ : b = b') : a == b' := trans H₁ (of_eq H₂) theorem of_eq_of_heq (H₁ : a = a') (H₂ : a' == b) : a == b := trans (of_eq H₁) H₂ end heq theorem of_heq_true {a : Prop} (H : a == true) : a := of_eq_true (heq.to_eq H) calc_trans heq.trans calc_trans heq.of_heq_of_eq calc_trans heq.of_eq_of_heq calc_symm heq.symm /- and -/ notation a /\ b := and a b notation a ∧ b := and a b variables {a b c d : Prop} theorem and.elim (H₁ : a ∧ b) (H₂ : a → b → c) : c := and.rec H₂ H₁ /- or -/ notation a `\/` b := or a b notation a ∨ b := or a b namespace or definition elim (H₁ : a ∨ b) (H₂ : a → c) (H₃ : b → c) : c := or.rec H₂ H₃ H₁ end or theorem non_contradictory_em (a : Prop) : ¬¬(a ∨ ¬a) := assume not_em : ¬(a ∨ ¬a), have neg_a : ¬a, from assume pos_a : a, absurd (or.inl pos_a) not_em, absurd (or.inr neg_a) not_em /- iff -/ definition iff (a b : Prop) := (a → b) ∧ (b → a) notation a <-> b := iff a b notation a ↔ b := iff a b namespace iff definition intro (H₁ : a → b) (H₂ : b → a) : a ↔ b := and.intro H₁ H₂ definition elim (H₁ : (a → b) → (b → a) → c) (H₂ : a ↔ b) : c := and.rec H₁ H₂ definition elim_left (H : a ↔ b) : a → b := elim (assume H₁ H₂, H₁) H definition mp := @elim_left definition elim_right (H : a ↔ b) : b → a := elim (assume H₁ H₂, H₂) H definition mp' := @elim_right definition refl (a : Prop) : a ↔ a := intro (assume H, H) (assume H, H) definition rfl {a : Prop} : a ↔ a := refl a theorem trans (H₁ : a ↔ b) (H₂ : b ↔ c) : a ↔ c := intro (assume Ha, elim_left H₂ (elim_left H₁ Ha)) (assume Hc, elim_right H₁ (elim_right H₂ Hc)) theorem symm (H : a ↔ b) : b ↔ a := intro (assume Hb, elim_right H Hb) (assume Ha, elim_left H Ha) open eq.ops theorem of_eq {a b : Prop} (H : a = b) : a ↔ b := iff.intro (λ Ha, H ▸ Ha) (λ Hb, H⁻¹ ▸ Hb) end iff definition not_iff_not_of_iff (H₁ : a ↔ b) : ¬a ↔ ¬b := iff.intro (assume (Hna : ¬ a) (Hb : b), absurd (iff.elim_right H₁ Hb) Hna) (assume (Hnb : ¬ b) (Ha : a), absurd (iff.elim_left H₁ Ha) Hnb) theorem of_iff_true (H : a ↔ true) : a := iff.mp (iff.symm H) trivial theorem not_of_iff_false (H : a ↔ false) : ¬a := assume Ha : a, iff.mp H Ha theorem iff_true_intro (H : a) : a ↔ true := iff.intro (λ Hl, trivial) (λ Hr, H) theorem iff_false_intro (H : ¬a) : a ↔ false := iff.intro (λ Hl, absurd Hl H) (λ Hr, false.rec _ Hr) theorem not_non_contradictory_iff_absurd (a : Prop) : ¬¬¬a ↔ ¬a := iff.intro (assume Hl : ¬¬¬a, assume Ha : a, absurd (non_contradictory_intro Ha) Hl) (assume Hr : ¬a, assume Hnna : ¬¬a, absurd Hr Hnna) calc_refl iff.refl calc_trans iff.trans inductive Exists {A : Type} (P : A → Prop) : Prop := intro : ∀ (a : A), P a → Exists P definition exists.intro := @Exists.intro notation `exists` binders `,` r:(scoped P, Exists P) := r notation `∃` binders `,` r:(scoped P, Exists P) := r definition exists.elim {A : Type} {p : A → Prop} {B : Prop} (H1 : ∃x, p x) (H2 : ∀ (a : A) (H : p a), B) : B := Exists.rec H2 H1 /- decidable -/ inductive decidable [class] (p : Prop) : Type := | inl : p → decidable p | inr : ¬p → decidable p definition decidable_true [instance] : decidable true := decidable.inl trivial definition decidable_false [instance] : decidable false := decidable.inr not_false namespace decidable variables {p q : Prop} definition rec_on_true [H : decidable p] {H1 : p → Type} {H2 : ¬p → Type} (H3 : p) (H4 : H1 H3) : decidable.rec_on H H1 H2 := decidable.rec_on H (λh, H4) (λh, !false.rec (h H3)) definition rec_on_false [H : decidable p] {H1 : p → Type} {H2 : ¬p → Type} (H3 : ¬p) (H4 : H2 H3) : decidable.rec_on H H1 H2 := decidable.rec_on H (λh, false.rec _ (H3 h)) (λh, H4) definition by_cases {q : Type} [C : decidable p] (Hpq : p → q) (Hnpq : ¬p → q) : q := decidable.rec_on C (assume Hp, Hpq Hp) (assume Hnp, Hnpq Hnp) theorem em (p : Prop) [H : decidable p] : p ∨ ¬p := by_cases (λ Hp, or.inl Hp) (λ Hnp, or.inr Hnp) theorem by_contradiction [Hp : decidable p] (H : ¬p → false) : p := by_cases (assume H1 : p, H1) (assume H1 : ¬p, false.rec _ (H H1)) end decidable section variables {p q : Prop} open decidable definition decidable_of_decidable_of_iff (Hp : decidable p) (H : p ↔ q) : decidable q := decidable.rec_on Hp (assume Hp : p, inl (iff.elim_left H Hp)) (assume Hnp : ¬p, inr (iff.elim_left (not_iff_not_of_iff H) Hnp)) definition decidable_of_decidable_of_eq (Hp : decidable p) (H : p = q) : decidable q := decidable_of_decidable_of_iff Hp (iff.of_eq H) end section variables {p q : Prop} open decidable (rec_on inl inr) definition decidable_and [instance] [Hp : decidable p] [Hq : decidable q] : decidable (p ∧ q) := rec_on Hp (assume Hp : p, rec_on Hq (assume Hq : q, inl (and.intro Hp Hq)) (assume Hnq : ¬q, inr (assume H : p ∧ q, and.rec_on H (assume Hp Hq, absurd Hq Hnq)))) (assume Hnp : ¬p, inr (assume H : p ∧ q, and.rec_on H (assume Hp Hq, absurd Hp Hnp))) definition decidable_or [instance] [Hp : decidable p] [Hq : decidable q] : decidable (p ∨ q) := rec_on Hp (assume Hp : p, inl (or.inl Hp)) (assume Hnp : ¬p, rec_on Hq (assume Hq : q, inl (or.inr Hq)) (assume Hnq : ¬q, inr (assume H : p ∨ q, or.elim H (assume Hp, absurd Hp Hnp) (assume Hq, absurd Hq Hnq)))) definition decidable_not [instance] [Hp : decidable p] : decidable (¬p) := rec_on Hp (assume Hp, inr (λ Hnp, absurd Hp Hnp)) (assume Hnp, inl Hnp) definition decidable_implies [instance] [Hp : decidable p] [Hq : decidable q] : decidable (p → q) := rec_on Hp (assume Hp : p, rec_on Hq (assume Hq : q, inl (assume H, Hq)) (assume Hnq : ¬q, inr (assume H : p → q, absurd (H Hp) Hnq))) (assume Hnp : ¬p, inl (assume Hp, absurd Hp Hnp)) definition decidable_iff [instance] [Hp : decidable p] [Hq : decidable q] : decidable (p ↔ q) := show decidable ((p → q) ∧ (q → p)), from _ end definition decidable_pred [reducible] {A : Type} (R : A → Prop) := Π (a : A), decidable (R a) definition decidable_rel [reducible] {A : Type} (R : A → A → Prop) := Π (a b : A), decidable (R a b) definition decidable_eq [reducible] (A : Type) := decidable_rel (@eq A) definition decidable_ne [instance] {A : Type} [H : decidable_eq A] : Π (a b : A), decidable (a ≠ b) := show Π x y : A, decidable (x = y → false), from _ namespace bool definition ff_ne_tt : ff = tt → false | [none] end bool open bool definition is_dec_eq {A : Type} (p : A → A → bool) : Prop := ∀ ⦃x y : A⦄, p x y = tt → x = y definition is_dec_refl {A : Type} (p : A → A → bool) : Prop := ∀x, p x x = tt open decidable protected definition bool.has_decidable_eq [instance] : ∀a b : bool, decidable (a = b) | ff ff := inl rfl | ff tt := inr ff_ne_tt | tt ff := inr (ne.symm ff_ne_tt) | tt tt := inl rfl definition decidable_eq_of_bool_pred {A : Type} {p : A → A → bool} (H₁ : is_dec_eq p) (H₂ : is_dec_refl p) : decidable_eq A := take x y : A, by_cases (assume Hp : p x y = tt, inl (H₁ Hp)) (assume Hn : ¬ p x y = tt, inr (assume Hxy : x = y, absurd (H₂ y) (eq.rec_on Hxy Hn))) theorem decidable_eq_inl_refl {A : Type} [H : decidable_eq A] (a : A) : H a a = inl (eq.refl a) := match H a a with | inl e := rfl | inr n := absurd rfl n end open eq.ops theorem decidable_eq_inr_neg {A : Type} [H : decidable_eq A] {a b : A} : Π n : a ≠ b, H a b = inr n := assume n, match H a b with | inl e := absurd e n | inr n₁ := proof_irrel n n₁ ▸ rfl end /- inhabited -/ inductive inhabited [class] (A : Type) : Type := mk : A → inhabited A protected definition inhabited.value {A : Type} (h : inhabited A) : A := inhabited.rec (λa, a) h protected definition inhabited.destruct {A : Type} {B : Type} (H1 : inhabited A) (H2 : A → B) : B := inhabited.rec H2 H1 definition default (A : Type) [H : inhabited A] : A := inhabited.rec (λa, a) H opaque definition arbitrary (A : Type) [H : inhabited A] : A := inhabited.rec (λa, a) H definition Prop.is_inhabited [instance] : inhabited Prop := inhabited.mk true definition inhabited_fun [instance] (A : Type) {B : Type} [H : inhabited B] : inhabited (A → B) := inhabited.rec_on H (λb, inhabited.mk (λa, b)) definition inhabited_Pi [instance] (A : Type) {B : A → Type} [H : Πx, inhabited (B x)] : inhabited (Πx, B x) := inhabited.mk (λa, inhabited.rec_on (H a) (λb, b)) protected definition bool.is_inhabited [instance] : inhabited bool := inhabited.mk ff inductive nonempty [class] (A : Type) : Prop := intro : A → nonempty A protected definition nonempty.elim {A : Type} {B : Prop} (H1 : nonempty A) (H2 : A → B) : B := nonempty.rec H2 H1 theorem nonempty_of_inhabited [instance] {A : Type} [H : inhabited A] : nonempty A := nonempty.intro (default A) /- subsingleton -/ inductive subsingleton [class] (A : Type) : Prop := intro : (∀ a b : A, a = b) → subsingleton A protected definition subsingleton.elim {A : Type} [H : subsingleton A] : ∀(a b : A), a = b := subsingleton.rec (fun p, p) H definition subsingleton_prop [instance] (p : Prop) : subsingleton p := subsingleton.intro (λa b, !proof_irrel) definition subsingleton_decidable [instance] (p : Prop) : subsingleton (decidable p) := subsingleton.intro (λ d₁, match d₁ with | inl t₁ := (λ d₂, match d₂ with | inl t₂ := eq.rec_on (proof_irrel t₁ t₂) rfl | inr f₂ := absurd t₁ f₂ end) | inr f₁ := (λ d₂, match d₂ with | inl t₂ := absurd t₂ f₁ | inr f₂ := eq.rec_on (proof_irrel f₁ f₂) rfl end) end) protected theorem rec_subsingleton {p : Prop} [H : decidable p] {H1 : p → Type} {H2 : ¬p → Type} [H3 : Π(h : p), subsingleton (H1 h)] [H4 : Π(h : ¬p), subsingleton (H2 h)] : subsingleton (decidable.rec_on H H1 H2) := decidable.rec_on H (λh, H3 h) (λh, H4 h) --this can be proven using dependent version of "by_cases" /- if-then-else -/ definition ite (c : Prop) [H : decidable c] {A : Type} (t e : A) : A := decidable.rec_on H (λ Hc, t) (λ Hnc, e) definition if_pos {c : Prop} [H : decidable c] (Hc : c) {A : Type} {t e : A} : (if c then t else e) = t := decidable.rec (λ Hc : c, eq.refl (@ite c (decidable.inl Hc) A t e)) (λ Hnc : ¬c, absurd Hc Hnc) H definition if_neg {c : Prop} [H : decidable c] (Hnc : ¬c) {A : Type} {t e : A} : (if c then t else e) = e := decidable.rec (λ Hc : c, absurd Hc Hnc) (λ Hnc : ¬c, eq.refl (@ite c (decidable.inr Hnc) A t e)) H definition if_t_t (c : Prop) [H : decidable c] {A : Type} (t : A) : (if c then t else t) = t := decidable.rec (λ Hc : c, eq.refl (@ite c (decidable.inl Hc) A t t)) (λ Hnc : ¬c, eq.refl (@ite c (decidable.inr Hnc) A t t)) H -- We use "dependent" if-then-else to be able to communicate the if-then-else condition -- to the branches definition dite (c : Prop) [H : decidable c] {A : Type} (t : c → A) (e : ¬ c → A) : A := decidable.rec_on H (λ Hc, t Hc) (λ Hnc, e Hnc) definition dif_pos {c : Prop} [H : decidable c] (Hc : c) {A : Type} {t : c → A} {e : ¬ c → A} : (if H : c then t H else e H) = t Hc := decidable.rec (λ Hc : c, eq.refl (@dite c (decidable.inl Hc) A t e)) (λ Hnc : ¬c, absurd Hc Hnc) H definition dif_neg {c : Prop} [H : decidable c] (Hnc : ¬c) {A : Type} {t : c → A} {e : ¬ c → A} : (if H : c then t H else e H) = e Hnc := decidable.rec (λ Hc : c, absurd Hc Hnc) (λ Hnc : ¬c, eq.refl (@dite c (decidable.inr Hnc) A t e)) H -- Remark: dite and ite are "definitionally equal" when we ignore the proofs. theorem dite_ite_eq (c : Prop) [H : decidable c] {A : Type} (t : A) (e : A) : dite c (λh, t) (λh, e) = ite c t e := rfl definition is_true (c : Prop) [H : decidable c] : Prop := if c then true else false definition is_false (c : Prop) [H : decidable c] : Prop := if c then false else true theorem of_is_true {c : Prop} [H₁ : decidable c] (H₂ : is_true c) : c := decidable.rec_on H₁ (λ Hc, Hc) (λ Hnc, !false.rec (if_neg Hnc ▸ H₂)) notation `dec_trivial` := of_is_true trivial theorem not_of_not_is_true {c : Prop} [H₁ : decidable c] (H₂ : ¬ is_true c) : ¬ c := decidable.rec_on H₁ (λ Hc, absurd true.intro (if_pos Hc ▸ H₂)) (λ Hnc, Hnc) theorem not_of_is_false {c : Prop} [H₁ : decidable c] (H₂ : is_false c) : ¬ c := decidable.rec_on H₁ (λ Hc, !false.rec (if_pos Hc ▸ H₂)) (λ Hnc, Hnc) theorem of_not_is_false {c : Prop} [H₁ : decidable c] (H₂ : ¬ is_false c) : c := decidable.rec_on H₁ (λ Hc, Hc) (λ Hnc, absurd true.intro (if_neg Hnc ▸ H₂))
3c004171e118b692bc47a2360b554b0d24ce2f71
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/topology/uniform_space/compact_convergence.lean
aa82d72b0eb98bba92fa7ae6dcfe7d7797244d28
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
21,262
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 topology.compact_open import topology.uniform_space.uniform_convergence /-! # Compact convergence (uniform convergence on compact sets) Given a topological space `α` and a uniform space `β` (e.g., a metric space or a topological group), the space of continuous maps `C(α, β)` carries a natural uniform space structure. We define this uniform space structure in this file and also prove the following properties of the topology it induces on `C(α, β)`: 1. Given a sequence of continuous functions `Fₙ : α → β` together with some continuous `f : α → β`, then `Fₙ` converges to `f` as a sequence in `C(α, β)` iff `Fₙ` converges to `f` uniformly on each compact subset `K` of `α`. 2. Given `Fₙ` and `f` as above and suppose `α` is locally compact, then `Fₙ` converges to `f` iff `Fₙ` converges to `f` locally uniformly. 3. The topology coincides with the compact-open topology. Property 1 is essentially true by definition, 2 follows from basic results about uniform convergence, but 3 requires a little work and uses the Lebesgue number lemma. ## The uniform space structure Given subsets `K ⊆ α` and `V ⊆ β × β`, let `E(K, V) ⊆ C(α, β) × C(α, β)` be the set of pairs of continuous functions `α → β` which are `V`-close on `K`: $$ E(K, V) = \{ (f, g) | ∀ (x ∈ K), (f x, g x) ∈ V \}. $$ Fixing some `f ∈ C(α, β)`, let `N(K, V, f) ⊆ C(α, β)` be the set of continuous functions `α → β` which are `V`-close to `f` on `K`: $$ N(K, V, f) = \{ g | ∀ (x ∈ K), (f x, g x) ∈ V \}. $$ Using this notation we can describe the uniform space structure and the topology it induces. Specifically: * A subset `X ⊆ C(α, β) × C(α, β)` is an entourage for the uniform space structure on `C(α, β)` iff there exists a compact `K` and entourage `V` such that `E(K, V) ⊆ X`. * A subset `Y ⊆ C(α, β)` is a neighbourhood of `f` iff there exists a compact `K` and entourage `V` such that `N(K, V, f) ⊆ Y`. The topology on `C(α, β)` thus has a natural subbasis (the compact-open subbasis) and a natural neighbourhood basis (the compact-convergence neighbourhood basis). ## Main definitions / results * `compact_open_eq_compact_convergence`: the compact-open topology is equal to the compact-convergence topology. * `compact_convergence_uniform_space`: the uniform space structure on `C(α, β)`. * `mem_compact_convergence_entourage_iff`: a characterisation of the entourages of `C(α, β)`. * `tendsto_iff_forall_compact_tendsto_uniformly_on`: a sequence of functions `Fₙ` in `C(α, β)` converges to some `f` iff `Fₙ` converges to `f` uniformly on each compact subset `K` of `α`. * `tendsto_iff_tendsto_locally_uniformly`: on a locally compact space, a sequence of functions `Fₙ` in `C(α, β)` converges to some `f` iff `Fₙ` converges to `f` locally uniformly. * `tendsto_iff_tendsto_uniformly`: on a compact space, a sequence of functions `Fₙ` in `C(α, β)` converges to some `f` iff `Fₙ` converges to `f` uniformly. ## Implementation details We use the forgetful inheritance pattern (see Note [forgetful inheritance]) to make the topology of the uniform space structure on `C(α, β)` definitionally equal to the compact-open topology. ## TODO * When `β` is a metric space, there is natural basis for the compact-convergence topology parameterised by triples `(K, ε, f)` for a real number `ε > 0`. * When `α` is compact and `β` is a metric space, the compact-convergence topology (and thus also the compact-open topology) is metrisable. * Results about uniformly continuous functions `γ → C(α, β)` and uniform limits of sequences `ι → γ → C(α, β)`. -/ universes u₁ u₂ u₃ open_locale filter uniformity topological_space open uniform_space set filter variables {α : Type u₁} {β : Type u₂} [topological_space α] [uniform_space β] variables (K : set α) (V : set (β × β)) (f : C(α, β)) namespace continuous_map /-- Given `K ⊆ α`, `V ⊆ β × β`, and `f : C(α, β)`, we define `compact_conv_nhd K V f` to be the set of `g : C(α, β)` that are `V`-close to `f` on `K`. -/ def compact_conv_nhd : set C(α, β) := { g | ∀ (x ∈ K), (f x, g x) ∈ V } variables {K V} lemma self_mem_compact_conv_nhd (hV : V ∈ 𝓤 β) : f ∈ compact_conv_nhd K V f := λ x hx, refl_mem_uniformity hV @[mono] lemma compact_conv_nhd_mono {V' : set (β × β)} (hV' : V' ⊆ V) : compact_conv_nhd K V' f ⊆ compact_conv_nhd K V f := λ x hx a ha, hV' (hx a ha) lemma compact_conv_nhd_mem_comp {g₁ g₂ : C(α, β)} {V' : set (β × β)} (hg₁ : g₁ ∈ compact_conv_nhd K V f) (hg₂ : g₂ ∈ compact_conv_nhd K V' g₁) : g₂ ∈ compact_conv_nhd K (V ○ V') f := λ x hx, ⟨g₁ x, hg₁ x hx, hg₂ x hx⟩ /-- A key property of `compact_conv_nhd`. It allows us to apply `topological_space.nhds_mk_of_nhds_filter_basis` below. -/ lemma compact_conv_nhd_nhd_basis (hV : V ∈ 𝓤 β) : ∃ (V' ∈ 𝓤 β), V' ⊆ V ∧ ∀ (g ∈ compact_conv_nhd K V' f), compact_conv_nhd K V' g ⊆ compact_conv_nhd K V f := begin obtain ⟨V', h₁, h₂⟩ := comp_mem_uniformity_sets hV, exact ⟨V', h₁, subset.trans (subset_comp_self_of_mem_uniformity h₁) h₂, λ g hg g' hg', compact_conv_nhd_mono f h₂ (compact_conv_nhd_mem_comp f hg hg')⟩, end lemma compact_conv_nhd_subset_inter (K₁ K₂ : set α) (V₁ V₂ : set (β × β)) : compact_conv_nhd (K₁ ∪ K₂) (V₁ ∩ V₂) f ⊆ compact_conv_nhd K₁ V₁ f ∩ compact_conv_nhd K₂ V₂ f := λ g hg, ⟨λ x hx, mem_of_mem_inter_left (hg x (mem_union_left K₂ hx)), λ x hx, mem_of_mem_inter_right (hg x (mem_union_right K₁ hx))⟩ lemma compact_conv_nhd_compact_entourage_nonempty : { KV : set α × set (β × β) | is_compact KV.1 ∧ KV.2 ∈ 𝓤 β }.nonempty := ⟨⟨∅, univ⟩, is_compact_empty, filter.univ_mem⟩ lemma compact_conv_nhd_filter_is_basis : filter.is_basis (λ (KV : set α × set (β × β)), is_compact KV.1 ∧ KV.2 ∈ 𝓤 β) (λ KV, compact_conv_nhd KV.1 KV.2 f) := { nonempty := compact_conv_nhd_compact_entourage_nonempty, inter := begin rintros ⟨K₁, V₁⟩ ⟨K₂, V₂⟩ ⟨hK₁, hV₁⟩ ⟨hK₂, hV₂⟩, exact ⟨⟨K₁ ∪ K₂, V₁ ∩ V₂⟩, ⟨hK₁.union hK₂, filter.inter_mem hV₁ hV₂⟩, compact_conv_nhd_subset_inter f K₁ K₂ V₁ V₂⟩, end, } /-- A filter basis for the neighbourhood filter of a point in the compact-convergence topology. -/ def compact_convergence_filter_basis (f : C(α, β)) : filter_basis C(α, β) := (compact_conv_nhd_filter_is_basis f).filter_basis lemma mem_compact_convergence_nhd_filter (Y : set C(α, β)) : Y ∈ (compact_convergence_filter_basis f).filter ↔ ∃ (K : set α) (V : set (β × β)) (hK : is_compact K) (hV : V ∈ 𝓤 β), compact_conv_nhd K V f ⊆ Y := begin split, { rintros ⟨X, ⟨⟨K, V⟩, ⟨hK, hV⟩, rfl⟩, hY⟩, exact ⟨K, V, hK, hV, hY⟩, }, { rintros ⟨K, V, hK, hV, hY⟩, exact ⟨compact_conv_nhd K V f, ⟨⟨K, V⟩, ⟨hK, hV⟩, rfl⟩, hY⟩, }, end /-- The compact-convergence topology. In fact, see `compact_open_eq_compact_convergence` this is the same as the compact-open topology. This definition is thus an auxiliary convenience definition and is unlikely to be of direct use. -/ def compact_convergence_topology : topological_space C(α, β) := topological_space.mk_of_nhds $ λ f, (compact_convergence_filter_basis f).filter lemma nhds_compact_convergence : @nhds _ compact_convergence_topology f = (compact_convergence_filter_basis f).filter := begin rw topological_space.nhds_mk_of_nhds_filter_basis; rintros g - ⟨⟨K, V⟩, ⟨hK, hV⟩, rfl⟩, { exact self_mem_compact_conv_nhd g hV, }, { obtain ⟨V', hV', h₁, h₂⟩ := compact_conv_nhd_nhd_basis g hV, exact ⟨compact_conv_nhd K V' g, ⟨⟨K, V'⟩, ⟨hK, hV'⟩, rfl⟩, compact_conv_nhd_mono g h₁, λ g' hg', ⟨compact_conv_nhd K V' g', ⟨⟨K, V'⟩, ⟨hK, hV'⟩, rfl⟩, h₂ g' hg'⟩⟩, }, end lemma has_basis_nhds_compact_convergence : has_basis (@nhds _ compact_convergence_topology f) (λ (p : set α × set (β × β)), is_compact p.1 ∧ p.2 ∈ 𝓤 β) (λ p, compact_conv_nhd p.1 p.2 f) := (nhds_compact_convergence f).symm ▸ (compact_conv_nhd_filter_is_basis f).has_basis /-- This is an auxiliary lemma and is unlikely to be of direct use outside of this file. See `tendsto_iff_forall_compact_tendsto_uniformly_on` below for the useful version where the topology is picked up via typeclass inference. -/ lemma tendsto_iff_forall_compact_tendsto_uniformly_on' {ι : Type u₃} {p : filter ι} {F : ι → C(α, β)} : filter.tendsto F p (@nhds _ compact_convergence_topology f) ↔ ∀ K, is_compact K → tendsto_uniformly_on (λ i a, F i a) f p K := begin simp only [(has_basis_nhds_compact_convergence f).tendsto_right_iff, tendsto_uniformly_on, and_imp, prod.forall], refine forall_congr (λ K, _), rw forall_swap, exact forall₃_congr (λ hK V hV, iff.rfl), end /-- Any point of `compact_open.gen K U` is also an interior point wrt the topology of compact convergence. The topology of compact convergence is thus at least as fine as the compact-open topology. -/ lemma compact_conv_nhd_subset_compact_open (hK : is_compact K) {U : set β} (hU : is_open U) (hf : f ∈ compact_open.gen K U) : ∃ (V ∈ 𝓤 β), is_open V ∧ compact_conv_nhd K V f ⊆ compact_open.gen K U := begin obtain ⟨V, hV₁, hV₂, hV₃⟩ := lebesgue_number_of_compact_open (hK.image f.continuous) hU hf, refine ⟨V, hV₁, hV₂, _⟩, rintros g hg - ⟨x, hx, rfl⟩, exact hV₃ (f x) ⟨x, hx, rfl⟩ (hg x hx), end /-- The point `f` in `compact_conv_nhd K V f` is also an interior point wrt the compact-open topology. Since `compact_conv_nhd K V f` are a neighbourhood basis at `f` for each `f`, it follows that the compact-open topology is at least as fine as the topology of compact convergence. -/ lemma Inter_compact_open_gen_subset_compact_conv_nhd (hK : is_compact K) (hV : V ∈ 𝓤 β) : ∃ (ι : Sort (u₁ + 1)) [fintype ι] (C : ι → set α) (hC : ∀ i, is_compact (C i)) (U : ι → set β) (hU : ∀ i, is_open (U i)), (f ∈ ⋂ i, compact_open.gen (C i) (U i)) ∧ (⋂ i, compact_open.gen (C i) (U i)) ⊆ compact_conv_nhd K V f := begin obtain ⟨W, hW₁, hW₄, hW₂, hW₃⟩ := comp_open_symm_mem_uniformity_sets hV, obtain ⟨Z, hZ₁, hZ₄, hZ₂, hZ₃⟩ := comp_open_symm_mem_uniformity_sets hW₁, let U : α → set α := λ x, f⁻¹' (ball (f x) Z), have hU : ∀ x, is_open (U x) := λ x, f.continuous.is_open_preimage _ (is_open_ball _ hZ₄), have hUK : K ⊆ ⋃ (x : K), U (x : K), { intros x hx, simp only [exists_prop, mem_Union, Union_coe_set, mem_preimage], exact ⟨(⟨x, hx⟩ : K), by simp [hx, mem_ball_self (f x) hZ₁]⟩, }, obtain ⟨t, ht⟩ := hK.elim_finite_subcover _ (λ (x : K), hU x.val) hUK, let C : t → set α := λ i, K ∩ closure (U ((i : K) : α)), have hC : K ⊆ ⋃ i, C i, { rw [← K.inter_Union, subset_inter_iff], refine ⟨subset.rfl, ht.trans _⟩, simp only [set_coe.forall, subtype.coe_mk, Union_subset_iff], exact λ x hx₁ hx₂, subset_Union_of_subset (⟨_, hx₂⟩ : t) (by simp [subset_closure]) }, have hfC : ∀ (i : t), C i ⊆ f ⁻¹' ball (f ((i : K) : α)) W, { simp only [← image_subset_iff, ← mem_preimage], rintros ⟨⟨x, hx₁⟩, hx₂⟩, have hZW : closure (ball (f x) Z) ⊆ ball (f x) W, { intros y hy, obtain ⟨z, hz₁, hz₂⟩ := uniform_space.mem_closure_iff_ball.mp hy hZ₁, exact ball_mono hZ₃ _ (mem_ball_comp hz₂ ((mem_ball_symmetry hZ₂).mp hz₁)), }, calc f '' (K ∩ closure (U x)) ⊆ f '' (closure (U x)) : image_subset _ (inter_subset_right _ _) ... ⊆ closure (f '' (U x)) : f.continuous.continuous_on.image_closure ... ⊆ closure (ball (f x) Z) : by { apply closure_mono, simp, } ... ⊆ ball (f x) W : hZW, }, refine ⟨t, t.fintype_coe_sort, C, λ i, hK.inter_right is_closed_closure, λ i, ball (f ((i : K) : α)) W, λ i, is_open_ball _ hW₄, by simp [compact_open.gen, hfC], λ g hg x hx, hW₃ (mem_comp_rel.mpr _)⟩, simp only [mem_Inter, compact_open.gen, mem_set_of_eq, image_subset_iff] at hg, obtain ⟨y, hy⟩ := mem_Union.mp (hC hx), exact ⟨f y, (mem_ball_symmetry hW₂).mp (hfC y hy), mem_preimage.mp (hg y hy)⟩, end /-- The compact-open topology is equal to the compact-convergence topology. -/ lemma compact_open_eq_compact_convergence : continuous_map.compact_open = (compact_convergence_topology : topological_space C(α, β)) := begin rw [compact_convergence_topology, continuous_map.compact_open], refine le_antisymm _ _, { refine λ X hX, is_open_iff_forall_mem_open.mpr (λ f hf, _), have hXf : X ∈ (compact_convergence_filter_basis f).filter, { rw ← nhds_compact_convergence, exact @is_open.mem_nhds C(α, β) compact_convergence_topology _ _ hX hf, }, obtain ⟨-, ⟨⟨K, V⟩, ⟨hK, hV⟩, rfl⟩, hXf⟩ := hXf, obtain ⟨ι, hι, C, hC, U, hU, h₁, h₂⟩ := Inter_compact_open_gen_subset_compact_conv_nhd f hK hV, haveI := hι, exact ⟨⋂ i, compact_open.gen (C i) (U i), h₂.trans hXf, is_open_Inter (λ i, continuous_map.is_open_gen (hC i) (hU i)), h₁⟩, }, { simp only [le_generate_from_iff_subset_is_open, and_imp, exists_prop, forall_exists_index, set_of_subset_set_of], rintros - K hK U hU rfl f hf, obtain ⟨V, hV, hV', hVf⟩ := compact_conv_nhd_subset_compact_open f hK hU hf, exact filter.mem_of_superset (filter_basis.mem_filter_of_mem _ ⟨⟨K, V⟩, ⟨hK, hV⟩, rfl⟩) hVf, }, end /-- The filter on `C(α, β) × C(α, β)` which underlies the uniform space structure on `C(α, β)`. -/ def compact_convergence_uniformity : filter (C(α, β) × C(α, β)) := ⨅ KV ∈ { KV : set α × set (β × β) | is_compact KV.1 ∧ KV.2 ∈ 𝓤 β }, 𝓟 { fg : C(α, β) × C(α, β) | ∀ (x : α), x ∈ KV.1 → (fg.1 x, fg.2 x) ∈ KV.2 } /-- An intermediate lemma. Usually `mem_compact_convergence_entourage_iff` is more useful. -/ lemma mem_compact_convergence_uniformity (X : set (C(α, β) × C(α, β))) : X ∈ @compact_convergence_uniformity α β _ _ ↔ ∃ (K : set α) (V : set (β × β)) (hK : is_compact K) (hV : V ∈ 𝓤 β), { fg : C(α, β) × C(α, β) | ∀ x ∈ K, (fg.1 x, fg.2 x) ∈ V } ⊆ X := begin rw [compact_convergence_uniformity, (filter.has_basis_binfi_principal _ compact_conv_nhd_compact_entourage_nonempty).mem_iff], { simp only [exists_prop, prod.forall, set_of_subset_set_of, mem_set_of_eq, prod.exists], exact exists₂_congr (λ K V, by tauto) }, { rintros ⟨K₁, V₁⟩ ⟨hK₁, hV₁⟩ ⟨K₂, V₂⟩ ⟨hK₂, hV₂⟩, refine ⟨⟨K₁ ∪ K₂, V₁ ∩ V₂⟩, ⟨hK₁.union hK₂, filter.inter_mem hV₁ hV₂⟩, _⟩, simp only [le_eq_subset, prod.forall, set_of_subset_set_of, ge_iff_le, order.preimage, ← forall_and_distrib, mem_inter_eq, mem_union_eq], exact λ f g, forall_imp (λ x, by tauto!), }, end /-- Note that we ensure the induced topology is definitionally the compact-open topology. -/ instance compact_convergence_uniform_space : uniform_space C(α, β) := { uniformity := compact_convergence_uniformity, refl := begin simp only [compact_convergence_uniformity, and_imp, filter.le_principal_iff, prod.forall, filter.mem_principal, mem_set_of_eq, le_infi_iff, id_rel_subset], exact λ K V hK hV f x hx, refl_mem_uniformity hV, end, symm := begin simp only [compact_convergence_uniformity, and_imp, prod.forall, mem_set_of_eq, prod.fst_swap, filter.tendsto_principal, prod.snd_swap, filter.tendsto_infi], intros K V hK hV, obtain ⟨V', hV', hsymm, hsub⟩ := symm_of_uniformity hV, let X := { fg : C(α, β) × C(α, β) | ∀ (x : α), x ∈ K → (fg.1 x, fg.2 x) ∈ V' }, have hX : X ∈ compact_convergence_uniformity := (mem_compact_convergence_uniformity X).mpr ⟨K, V', hK, hV', by simp⟩, exact filter.eventually_of_mem hX (λ fg hfg x hx, hsub (hsymm _ _ (hfg x hx))), end, comp := λ X hX, begin obtain ⟨K, V, hK, hV, hX⟩ := (mem_compact_convergence_uniformity X).mp hX, obtain ⟨V', hV', hcomp⟩ := comp_mem_uniformity_sets hV, let h := λ (s : set (C(α, β) × C(α, β))), s ○ s, suffices : h {fg : C(α, β) × C(α, β) | ∀ (x ∈ K), (fg.1 x, fg.2 x) ∈ V'} ∈ compact_convergence_uniformity.lift' h, { apply filter.mem_of_superset this, rintros ⟨f, g⟩ ⟨z, hz₁, hz₂⟩, refine hX (λ x hx, hcomp _), exact ⟨z x, hz₁ x hx, hz₂ x hx⟩, }, apply filter.mem_lift', exact (mem_compact_convergence_uniformity _).mpr ⟨K, V', hK, hV', subset.refl _⟩, end, is_open_uniformity := begin rw compact_open_eq_compact_convergence, refine λ Y, forall₂_congr (λ f hf, _), simp only [mem_compact_convergence_nhd_filter, mem_compact_convergence_uniformity, prod.forall, set_of_subset_set_of, compact_conv_nhd], refine exists₄_congr (λ K V hK hV, ⟨_, λ hY g hg, hY f g hg rfl⟩), rintros hY g₁ g₂ hg₁ rfl, exact hY hg₁, end } lemma mem_compact_convergence_entourage_iff (X : set (C(α, β) × C(α, β))) : X ∈ 𝓤 C(α, β) ↔ ∃ (K : set α) (V : set (β × β)) (hK : is_compact K) (hV : V ∈ 𝓤 β), { fg : C(α, β) × C(α, β) | ∀ x ∈ K, (fg.1 x, fg.2 x) ∈ V } ⊆ X := mem_compact_convergence_uniformity X lemma has_basis_compact_convergence_uniformity : has_basis (𝓤 C(α, β)) (λ p : set α × set (β × β), is_compact p.1 ∧ p.2 ∈ 𝓤 β) (λ p, { fg : C(α, β) × C(α, β) | ∀ x ∈ p.1, (fg.1 x, fg.2 x) ∈ p.2 }) := ⟨λ t, by { simp only [mem_compact_convergence_entourage_iff, prod.exists], tauto, }⟩ variables {ι : Type u₃} {p : filter ι} {F : ι → C(α, β)} {f} lemma tendsto_iff_forall_compact_tendsto_uniformly_on : tendsto F p (𝓝 f) ↔ ∀ K, is_compact K → tendsto_uniformly_on (λ i a, F i a) f p K := by rw [compact_open_eq_compact_convergence, tendsto_iff_forall_compact_tendsto_uniformly_on'] /-- Locally uniform convergence implies convergence in the compact-open topology. -/ lemma tendsto_of_tendsto_locally_uniformly (h : tendsto_locally_uniformly (λ i a, F i a) f p) : tendsto F p (𝓝 f) := begin rw tendsto_iff_forall_compact_tendsto_uniformly_on, intros K hK, rw ← tendsto_locally_uniformly_on_iff_tendsto_uniformly_on_of_compact hK, exact h.tendsto_locally_uniformly_on, end /-- If every point has a compact neighbourhood, then convergence in the compact-open topology implies locally uniform convergence. See also `tendsto_iff_tendsto_locally_uniformly`, especially for T2 spaces. -/ lemma tendsto_locally_uniformly_of_tendsto (hα : ∀ x : α, ∃ n, is_compact n ∧ n ∈ 𝓝 x) (h : tendsto F p (𝓝 f)) : tendsto_locally_uniformly (λ i a, F i a) f p := begin rw tendsto_iff_forall_compact_tendsto_uniformly_on at h, intros V hV x, obtain ⟨n, hn₁, hn₂⟩ := hα x, exact ⟨n, hn₂, h n hn₁ V hV⟩, end /-- Convergence in the compact-open topology is the same as locally uniform convergence on a locally compact space. For non-T2 spaces, the assumption `locally_compact_space α` is stronger than we need and in fact the `←` direction is true unconditionally. See `tendsto_locally_uniformly_of_tendsto` and `tendsto_of_tendsto_locally_uniformly` for versions requiring weaker hypotheses. -/ lemma tendsto_iff_tendsto_locally_uniformly [locally_compact_space α] : tendsto F p (𝓝 f) ↔ tendsto_locally_uniformly (λ i a, F i a) f p := ⟨tendsto_locally_uniformly_of_tendsto exists_compact_mem_nhds, tendsto_of_tendsto_locally_uniformly⟩ section compact_domain variables [compact_space α] lemma has_basis_compact_convergence_uniformity_of_compact : has_basis (𝓤 C(α, β)) (λ V : set (β × β), V ∈ 𝓤 β) (λ V, { fg : C(α, β) × C(α, β) | ∀ x, (fg.1 x, fg.2 x) ∈ V }) := has_basis_compact_convergence_uniformity.to_has_basis (λ p hp, ⟨p.2, hp.2, λ fg hfg x hx, hfg x⟩) (λ V hV, ⟨⟨univ, V⟩, ⟨compact_univ, hV⟩, λ fg hfg x, hfg x (mem_univ x)⟩) /-- Convergence in the compact-open topology is the same as uniform convergence for sequences of continuous functions on a compact space. -/ lemma tendsto_iff_tendsto_uniformly : tendsto F p (𝓝 f) ↔ tendsto_uniformly (λ i a, F i a) f p := begin rw [tendsto_iff_forall_compact_tendsto_uniformly_on, ← tendsto_uniformly_on_univ], exact ⟨λ h, h univ compact_univ, λ h K hK, h.mono (subset_univ K)⟩, end end compact_domain end continuous_map
71ed7632a1d32fb7b50ef463e549002ef671f927
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/category/Ring/instances.lean
55c663a16477d1baebe1e9a0b7405ca14173a3a4
[ "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
726
lean
/- Copyright (c) 2021 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import algebra.category.Ring.basic import ring_theory.localization.away /-! # Ring-theoretic results in terms of categorical languages -/ open category_theory instance localization_unit_is_iso (R : CommRing) : is_iso (CommRing.of_hom $ algebra_map R (localization.away (1 : R))) := is_iso.of_iso (is_localization.at_one R (localization.away (1 : R))).to_ring_equiv.to_CommRing_iso instance localization_unit_is_iso' (R : CommRing) : @is_iso CommRing _ R _ (CommRing.of_hom $ algebra_map R (localization.away (1 : R))) := by { cases R, exact localization_unit_is_iso _ }
037e7609f60fd050e00e075f1498808a7bc63954
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Meta/Tactic/FVarSubst.lean
757b8bcb27f1fb5a7292531f41483017eb1716b9
[ "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
2,312
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Std.Data.AssocList import Lean.Expr import Lean.LocalContext import Lean.Util.ReplaceExpr namespace Lean.Meta /- Some tactics substitute hypotheses with expressions. We track these substitutions using `FVarSubst`. It is just a mapping from the original FVarId (internal) name to an expression. The free variables occurring in the expression must be defined in the new goal. -/ structure FVarSubst where map : Std.AssocList FVarId Expr := {} deriving Inhabited namespace FVarSubst def empty : FVarSubst := {} def isEmpty (s : FVarSubst) : Bool := s.map.isEmpty def contains (s : FVarSubst) (fvarId : FVarId) : Bool := s.map.contains fvarId /- Add entry `fvarId |-> v` to `s` if `s` does not contain an entry for `fvarId`. -/ def insert (s : FVarSubst) (fvarId : FVarId) (v : Expr) : FVarSubst := if s.contains fvarId then s else let map := s.map.mapVal fun e => e.replaceFVarId fvarId v; { map := map.insert fvarId v } def erase (s : FVarSubst) (fvarId : FVarId) : FVarSubst := { map := s.map.erase fvarId } def find? (s : FVarSubst) (fvarId : FVarId) : Option Expr := s.map.find? fvarId def get (s : FVarSubst) (fvarId : FVarId) : Expr := match s.map.find? fvarId with | none => mkFVar fvarId -- it has not been replaced | some v => v /-- Given `e`, for each `(x => v)` in `s` replace `x` with `v` in `e` -/ def apply (s : FVarSubst) (e : Expr) : Expr := if s.map.isEmpty then e else if !e.hasFVar then e else e.replace fun e => match e with | Expr.fvar fvarId _ => match s.map.find? fvarId with | none => e | some v => v | _ => none def domain (s : FVarSubst) : List FVarId := s.map.foldl (init := []) fun r k v => k :: r def any (p : FVarId → Expr → Bool) (s : FVarSubst) : Bool := s.map.any p end FVarSubst end Meta def LocalDecl.applyFVarSubst (s : Meta.FVarSubst) : LocalDecl → LocalDecl | LocalDecl.cdecl i id n t bi => LocalDecl.cdecl i id n (s.apply t) bi | LocalDecl.ldecl i id n t v nd => LocalDecl.ldecl i id n (s.apply t) (s.apply v) nd abbrev Expr.applyFVarSubst (s : Meta.FVarSubst) (e : Expr) : Expr := s.apply e end Lean
e838315ceb997e1b886a45ccc5fcaa602a502f70
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Parser/Syntax.lean
1c44599a65bcd976a7bfb2c7e2c6626983f931e8
[ "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
6,084
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.Command import Lean.Parser.Tactic namespace Lean namespace Parser builtin_initialize registerBuiltinParserAttribute `builtinSyntaxParser `stx LeadingIdentBehavior.both registerBuiltinDynamicParserAttribute `stxParser `stx builtin_initialize registerBuiltinParserAttribute `builtinPrecParser `prec LeadingIdentBehavior.both registerBuiltinDynamicParserAttribute `precParser `prec @[inline] def precedenceParser (rbp : Nat := 0) : Parser := categoryParser `prec rbp @[inline] def syntaxParser (rbp : Nat := 0) : Parser := categoryParser `stx rbp def «precedence» := leading_parser ":" >> precedenceParser maxPrec def optPrecedence := optional (atomic «precedence») namespace Syntax @[builtinPrecParser] def numPrec := checkPrec maxPrec >> numLit @[builtinSyntaxParser] def paren := leading_parser "(" >> many1 syntaxParser >> ")" @[builtinSyntaxParser] def cat := leading_parser ident >> optPrecedence @[builtinSyntaxParser] def unary := leading_parser ident >> checkNoWsBefore >> "(" >> many1 syntaxParser >> ")" @[builtinSyntaxParser] def binary := leading_parser ident >> checkNoWsBefore >> "(" >> many1 syntaxParser >> ", " >> many1 syntaxParser >> ")" @[builtinSyntaxParser] def sepBy := leading_parser "sepBy(" >> many1 syntaxParser >> ", " >> strLit >> optional (", " >> many1 syntaxParser) >> optional (", " >> nonReservedSymbol "allowTrailingSep") >> ")" @[builtinSyntaxParser] def sepBy1 := leading_parser "sepBy1(" >> many1 syntaxParser >> ", " >> strLit >> optional (", " >> many1 syntaxParser) >> optional (", " >> nonReservedSymbol "allowTrailingSep") >> ")" @[builtinSyntaxParser] def atom := leading_parser strLit @[builtinSyntaxParser] def nonReserved := leading_parser "&" >> strLit end Syntax namespace Term @[builtinTermParser] def stx.quot : Parser := leading_parser "`(stx|" >> incQuotDepth syntaxParser >> ")" @[builtinTermParser] def prec.quot : Parser := leading_parser "`(prec|" >> incQuotDepth precedenceParser >> ")" @[builtinTermParser] def prio.quot : Parser := leading_parser "`(prio|" >> incQuotDepth priorityParser >> ")" end Term namespace Command def namedName := leading_parser (atomic ("(" >> nonReservedSymbol "name") >> " := " >> ident >> ")") def optNamedName := optional namedName def «prefix» := leading_parser "prefix" def «infix» := leading_parser "infix" def «infixl» := leading_parser "infixl" def «infixr» := leading_parser "infixr" def «postfix» := leading_parser "postfix" def mixfixKind := «prefix» <|> «infix» <|> «infixl» <|> «infixr» <|> «postfix» @[builtinCommandParser] def «mixfix» := leading_parser Term.attrKind >> mixfixKind >> precedence >> optNamedName >> optNamedPrio >> ppSpace >> strLit >> darrow >> termParser -- NOTE: We use `suppressInsideQuot` in the following parsers because quotations inside them are evaluated in the same stage and -- thus should be ignored when we use `checkInsideQuot` to prepare the next stage for a builtin syntax change def identPrec := leading_parser ident >> optPrecedence def optKind : Parser := optional ("(" >> nonReservedSymbol "kind" >> ":=" >> ident >> ")") def notationItem := ppSpace >> withAntiquot (mkAntiquot "notationItem" `Lean.Parser.Command.notationItem) (strLit <|> identPrec) @[builtinCommandParser] def «notation» := leading_parser Term.attrKind >> "notation" >> optPrecedence >> optNamedName >> optNamedPrio >> many notationItem >> darrow >> termParser @[builtinCommandParser] def «macro_rules» := suppressInsideQuot (leading_parser optional docComment >> Term.attrKind >> "macro_rules" >> optKind >> Term.matchAlts) @[builtinCommandParser] def «syntax» := leading_parser optional docComment >> Term.attrKind >> "syntax " >> optPrecedence >> optNamedName >> optNamedPrio >> many1 (syntaxParser argPrec) >> " : " >> ident @[builtinCommandParser] def syntaxAbbrev := leading_parser optional docComment >> "syntax " >> ident >> " := " >> many1 syntaxParser def catBehaviorBoth := leading_parser nonReservedSymbol "both" def catBehaviorSymbol := leading_parser nonReservedSymbol "symbol" def catBehavior := optional ("(" >> nonReservedSymbol "behavior" >> " := " >> (catBehaviorBoth <|> catBehaviorSymbol) >> ")") @[builtinCommandParser] def syntaxCat := leading_parser "declare_syntax_cat " >> ident >> catBehavior def macroArg := leading_parser optional (atomic (ident >> checkNoWsBefore "no space before ':'" >> ":")) >> syntaxParser argPrec def macroRhs (quotP : Parser) : Parser := leading_parser "`(" >> incQuotDepth quotP >> ")" <|> withPosition termParser def macroTailTactic : Parser := atomic (" : " >> identEq "tactic") >> darrow >> macroRhs Tactic.seq1 def macroTailCommand : Parser := atomic (" : " >> identEq "command") >> darrow >> macroRhs (many1Unbox commandParser) def macroTailDefault : Parser := atomic (" : " >> ident) >> darrow >> macroRhs (categoryParserOfStack 2) def macroTail := leading_parser macroTailTactic <|> macroTailCommand <|> macroTailDefault @[builtinCommandParser] def «macro» := leading_parser suppressInsideQuot (optional docComment >> Term.attrKind >> "macro " >> optPrecedence >> optNamedName >> optNamedPrio >> many1 macroArg >> macroTail) @[builtinCommandParser] def «elab_rules» := leading_parser suppressInsideQuot (optional docComment >> Term.attrKind >> "elab_rules" >> optKind >> optional (" : " >> ident) >> optional (" <= " >> ident) >> Term.matchAlts) def elabArg := macroArg def elabTail := leading_parser atomic (" : " >> ident >> optional (" <= " >> ident)) >> darrow >> withPosition termParser @[builtinCommandParser] def «elab» := leading_parser suppressInsideQuot (optional docComment >> Term.attrKind >> "elab " >> optPrecedence >> optNamedName >> optNamedPrio >> many1 elabArg >> elabTail) end Command end Parser end Lean
8653cccd85128ac7448fb9e89058434a294b8023
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/hott/types/int/basic.hlean
03e87fc1a0a761ee1c769a434248f7851c517397
[ "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
38,812
hlean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, 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' Ported from standard library -/ import types.nat.sub algebra.relation types.prod open core nat decidable prod relation prod /- the type of integers -/ inductive int : Type := | of_nat : nat → int | neg_succ_of_nat : nat → int notation `ℤ` := int attribute int.of_nat [coercion] definition int.of_num [coercion] [reducible] [constructor] (n : num) : ℤ := int.of_nat (nat.of_num n) namespace int /- definitions of basic functions -/ definition neg_of_nat (m : ℕ) : ℤ := nat.cases_on m 0 (take m', neg_succ_of_nat m') definition sub_nat_nat (m n : ℕ) : ℤ := nat.cases_on (n - m) (of_nat (m - n)) -- m ≥ n (take k, neg_succ_of_nat k) -- m < n, and n - m = succ k definition neg (a : ℤ) : ℤ := int.cases_on a (take m, -- a = of_nat m nat.cases_on m 0 (take m', neg_succ_of_nat m')) (take m, of_nat (succ m)) -- a = neg_succ_of_nat m definition add (a b : ℤ) : ℤ := int.cases_on a (take m, -- a = of_nat m int.cases_on b (take n, of_nat (m + n)) -- b = of_nat n (take n, sub_nat_nat m (succ n))) -- b = neg_succ_of_nat n (take m, -- a = neg_succ_of_nat m int.cases_on b (take n, sub_nat_nat n (succ m)) -- b = of_nat n (take n, neg_of_nat (succ m + succ n))) -- b = neg_succ_of_nat n definition mul (a b : ℤ) : ℤ := int.cases_on a (take m, -- a = of_nat m int.cases_on b (take n, of_nat (m * n)) -- b = of_nat n (take n, neg_of_nat (m * succ n))) -- b = neg_succ_of_nat n (take m, -- a = neg_succ_of_nat m int.cases_on b (take n, neg_of_nat (succ m * n)) -- b = of_nat n (take n, of_nat (succ m * succ n))) -- b = neg_succ_of_nat n /- notation -/ notation `-[`:95 n:0 `+1]`:0 := int.neg_succ_of_nat n -- for pretty-printing output prefix - := int.neg infix + := int.add infix * := int.mul /- some basic functions and properties -/ definition of_nat.inj {m n : ℕ} (H : of_nat m = of_nat n) : m = n := by injection H; assumption definition neg_succ_of_nat.inj {m n : ℕ} (H : neg_succ_of_nat m = neg_succ_of_nat n) : m = n := by injection H; assumption definition neg_succ_of_nat_eq (n : ℕ) : -[n +1] = -(n + 1) := rfl definition has_decidable_eq [instance] : decidable_eq ℤ := take a b, int.cases_on a (take m, int.cases_on b (take n, if H : m = n then inl (ap of_nat H) else inr (take H1, H (of_nat.inj H1))) (take n', inr (by contradiction))) (take m', int.cases_on b (take n, inr (by contradiction)) (take n', (if H : m' = n' then inl (ap neg_succ_of_nat H) else inr (take H1, H (neg_succ_of_nat.inj H1))))) definition of_nat_add_of_nat (n m : nat) : of_nat n + of_nat m = #nat n + m := rfl definition of_nat_succ (n : ℕ) : of_nat (succ n) = of_nat n + 1 := rfl definition of_nat_mul_of_nat (n m : ℕ) : of_nat n * of_nat m = n * m := rfl definition sub_nat_nat_of_ge {m n : ℕ} (H : m ≥ n) : sub_nat_nat m n = of_nat (m - n) := have H1 : n - m = 0, from sub_eq_zero_of_le H, calc sub_nat_nat m n = nat.cases_on 0 (of_nat (m - n)) _ : H1 ▸ rfl ... = of_nat (m - n) : rfl section local attribute sub_nat_nat [reducible] definition sub_nat_nat_of_lt {m n : ℕ} (H : m < n) : sub_nat_nat m n = neg_succ_of_nat (pred (n - m)) := have H1 : n - m = succ (pred (n - m)), from (succ_pred_of_pos (sub_pos_of_lt H))⁻¹, calc sub_nat_nat m n = nat.cases_on (succ (pred (n - m))) (of_nat (m - n)) (take k, neg_succ_of_nat k) : H1 ▸ rfl ... = neg_succ_of_nat (pred (n - m)) : rfl end definition nat_abs (a : ℤ) : ℕ := int.cases_on a (take n, n) (take n', succ n') definition nat_abs_of_nat (n : ℕ) : nat_abs (of_nat n) = n := rfl definition nat_abs_eq_zero {a : ℤ} : nat_abs a = 0 → a = 0 := int.cases_on a (take m, assume H : nat_abs (of_nat m) = 0, ap of_nat H) (take m', assume H : nat_abs (neg_succ_of_nat m') = 0, absurd H (succ_ne_zero _)) /- int is a quotient of ordered pairs of natural numbers -/ definition int_equiv (p q : ℕ × ℕ) : Type₀ := pr1 p + pr2 q = pr2 p + pr1 q local infix `≡` := int_equiv protected theorem int_equiv.refl [refl] {p : ℕ × ℕ} : p ≡ p := !add.comm protected theorem int_equiv.symm [symm] {p q : ℕ × ℕ} (H : p ≡ q) : q ≡ p := calc pr1 q + pr2 p = pr2 p + pr1 q : !add.comm ... = pr1 p + pr2 q : H⁻¹ ... = pr2 q + pr1 p : !add.comm protected theorem int_equiv.trans [trans] {p q r : ℕ × ℕ} (H1 : p ≡ q) (H2 : q ≡ r) : p ≡ r := add.cancel_right (calc pr1 p + pr2 r + pr2 q = pr1 p + pr2 q + pr2 r : add.right_comm ... = pr2 p + pr1 q + pr2 r : {H1} ... = pr2 p + (pr1 q + pr2 r) : add.assoc ... = pr2 p + (pr2 q + pr1 r) : {H2} ... = pr2 p + pr2 q + pr1 r : add.assoc ... = pr2 p + pr1 r + pr2 q : add.right_comm) definition int_equiv_int_equiv : is_equivalence int_equiv := is_equivalence.mk @int_equiv.refl @int_equiv.symm @int_equiv.trans definition int_equiv_cases {p q : ℕ × ℕ} (H : int_equiv p q) : (pr1 p ≥ pr2 p × pr1 q ≥ pr2 q) ⊎ (pr1 p < pr2 p × pr1 q < pr2 q) := sum.rec_on (@le_or_gt (pr2 p) (pr1 p)) (assume H1: pr1 p ≥ pr2 p, have H2 : pr2 p + pr1 q ≥ pr2 p + pr2 q, from H ▸ add_le_add_right H1 (pr2 q), sum.inl (pair H1 (le_of_add_le_add_left H2))) (assume H1: pr1 p < pr2 p, have H2 : pr2 p + pr1 q < pr2 p + pr2 q, from H ▸ add_lt_add_right H1 (pr2 q), sum.inr (pair H1 (lt_of_add_lt_add_left H2))) definition int_equiv_of_eq {p q : ℕ × ℕ} (H : p = q) : p ≡ q := H ▸ int_equiv.refl /- the representation and abstraction functions -/ definition abstr (a : ℕ × ℕ) : ℤ := sub_nat_nat (pr1 a) (pr2 a) definition abstr_of_ge {p : ℕ × ℕ} (H : pr1 p ≥ pr2 p) : abstr p = of_nat (pr1 p - pr2 p) := sub_nat_nat_of_ge H definition abstr_of_lt {p : ℕ × ℕ} (H : pr1 p < pr2 p) : abstr p = neg_succ_of_nat (pred (pr2 p - pr1 p)) := sub_nat_nat_of_lt H definition repr (a : ℤ) : ℕ × ℕ := int.cases_on a (take m, (m, 0)) (take m, (0, succ m)) definition abstr_repr (a : ℤ) : abstr (repr a) = a := int.cases_on a (take m, (sub_nat_nat_of_ge (zero_le m))) (take m, rfl) definition repr_sub_nat_nat (m n : ℕ) : repr (sub_nat_nat m n) ≡ (m, n) := sum.rec_on (@le_or_gt n m) (take H : m ≥ n, have H1 : repr (sub_nat_nat m n) = (m - n, 0), from sub_nat_nat_of_ge H ▸ rfl, H1⁻¹ ▸ (calc m - n + n = m : sub_add_cancel H ... = 0 + m : zero_add)) (take H : m < n, have H1 : repr (sub_nat_nat m n) = (0, succ (pred (n - m))), from sub_nat_nat_of_lt H ▸ rfl, H1⁻¹ ▸ (calc 0 + n = n : zero_add ... = n - m + m : sub_add_cancel (le_of_lt H) ... = succ (pred (n - m)) + m : (succ_pred_of_pos (sub_pos_of_lt H))⁻¹ᵖ)) definition repr_abstr (p : ℕ × ℕ) : repr (abstr p) ≡ p := !prod.eta ▸ !repr_sub_nat_nat definition abstr_eq {p q : ℕ × ℕ} (Hint_equiv : p ≡ q) : abstr p = abstr q := sum.rec_on (int_equiv_cases Hint_equiv) (assume H2, have H3 : pr1 p ≥ pr2 p, from prod.pr1 H2, have H4 : pr1 q ≥ pr2 q, from prod.pr2 H2, have H5 : pr1 p = pr1 q - pr2 q + pr2 p, from calc pr1 p = pr1 p + pr2 q - pr2 q : add_sub_cancel ... = pr2 p + pr1 q - pr2 q : by rewrite [↑int_equiv at Hint_equiv,Hint_equiv] ... = pr2 p + (pr1 q - pr2 q) : add_sub_assoc H4 ... = pr1 q - pr2 q + pr2 p : add.comm, have H6 : pr1 p - pr2 p = pr1 q - pr2 q, from calc pr1 p - pr2 p = pr1 q - pr2 q + pr2 p - pr2 p : H5 ... = pr1 q - pr2 q : add_sub_cancel, abstr_of_ge H3 ⬝ ap of_nat H6 ⬝ (abstr_of_ge H4)⁻¹) (assume H2, have H3 : pr1 p < pr2 p, from prod.pr1 H2, have H4 : pr1 q < pr2 q, from prod.pr2 H2, have H5 : pr2 p = pr2 q - pr1 q + pr1 p, from calc pr2 p = pr2 p + pr1 q - pr1 q : add_sub_cancel ... = pr1 p + pr2 q - pr1 q : by rewrite [↑int_equiv at Hint_equiv,Hint_equiv] ... = pr1 p + (pr2 q - pr1 q) : add_sub_assoc (le_of_lt H4) ... = pr2 q - pr1 q + pr1 p : add.comm, have H6 : pr2 p - pr1 p = pr2 q - pr1 q, from calc pr2 p - pr1 p = pr2 q - pr1 q + pr1 p - pr1 p : H5 ... = pr2 q - pr1 q : add_sub_cancel, abstr_of_lt H3 ⬝ ap neg_succ_of_nat (ap pred H6)⬝ (abstr_of_lt H4)⁻¹) definition int_equiv_iff (p q : ℕ × ℕ) : (p ≡ q) ↔ ((p ≡ p) × (q ≡ q) × (abstr p = abstr q)) := iff.intro (assume H : int_equiv p q, pair !int_equiv.refl (pair !int_equiv.refl (abstr_eq H))) (assume H : int_equiv p p × int_equiv q q × abstr p = abstr q, have H1 : abstr p = abstr q, from prod.pr2 (prod.pr2 H), int_equiv.trans (H1 ▸ int_equiv.symm (repr_abstr p)) (repr_abstr q)) definition eq_abstr_of_int_equiv_repr {a : ℤ} {p : ℕ × ℕ} (Hint_equiv : repr a ≡ p) : a = abstr p := calc a = abstr (repr a) : abstr_repr ... = abstr p : abstr_eq Hint_equiv definition eq_of_repr_int_equiv_repr {a b : ℤ} (H : repr a ≡ repr b) : a = b := calc a = abstr (repr a) : abstr_repr ... = abstr (repr b) : abstr_eq H ... = b : abstr_repr section local attribute abstr [reducible] local attribute dist [reducible] definition nat_abs_abstr (p : ℕ × ℕ) : nat_abs (abstr p) = dist (pr1 p) (pr2 p) := let m := pr1 p, n := pr2 p in sum.rec_on (@le_or_gt n m) (assume H : m ≥ n, calc nat_abs (abstr (m, n)) = nat_abs (of_nat (m - n)) : int.abstr_of_ge H ... = dist m n : dist_eq_sub_of_ge H) (assume H : m < n, calc nat_abs (abstr (m, n)) = nat_abs (neg_succ_of_nat (pred (n - m))) : int.abstr_of_lt H ... = succ (pred (n - m)) : rfl ... = n - m : succ_pred_of_pos (sub_pos_of_lt H) ... = dist m n : dist_eq_sub_of_le (le_of_lt H)) end definition cases_of_nat (a : ℤ) : (Σn : ℕ, a = of_nat n) ⊎ (Σn : ℕ, a = - of_nat n) := int.cases_on a (take n, sum.inl (sigma.mk n rfl)) (take n', sum.inr (sigma.mk (succ n') rfl)) definition cases_of_nat_succ (a : ℤ) : (Σn : ℕ, a = of_nat n) ⊎ (Σn : ℕ, a = - (of_nat (succ n))) := int.cases_on a (take m, sum.inl (sigma.mk _ rfl)) (take m, sum.inr (sigma.mk _ rfl)) definition by_cases_of_nat {P : ℤ → Type} (a : ℤ) (H1 : Πn : ℕ, P (of_nat n)) (H2 : Πn : ℕ, P (- of_nat n)) : P a := sum.rec_on (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) definition by_cases_of_nat_succ {P : ℤ → Type} (a : ℤ) (H1 : Πn : ℕ, P (of_nat n)) (H2 : Πn : ℕ, P (- of_nat (succ n))) : P a := sum.rec_on (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) definition repr_add (a b : ℤ) : repr (add a b) ≡ padd (repr a) (repr b) := int.cases_on a (take m, int.cases_on b (take n, !int_equiv.refl) (take n', have H1 : int_equiv (repr (add (of_nat m) (neg_succ_of_nat n'))) (m, succ n'), from !repr_sub_nat_nat, have H2 : padd (repr (of_nat m)) (repr (neg_succ_of_nat n')) = (m, 0 + succ n'), from rfl, (!zero_add ▸ H2)⁻¹ ▸ H1)) (take m', int.cases_on b (take n, have H1 : int_equiv (repr (add (neg_succ_of_nat m') (of_nat n))) (n, succ m'), from !repr_sub_nat_nat, have H2 : padd (repr (neg_succ_of_nat m')) (repr (of_nat n)) = (0 + n, succ m'), from rfl, (!zero_add ▸ H2)⁻¹ ▸ H1) (take n',!repr_sub_nat_nat)) definition 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 definition padd_comm (p q : ℕ × ℕ) : padd p q = padd q p := calc padd p q = (pr1 p + pr1 q, pr2 p + pr2 q) : rfl ... = (pr1 q + pr1 p, pr2 p + pr2 q) : add.comm ... = (pr1 q + pr1 p, pr2 q + pr2 p) : add.comm ... = padd q p : rfl definition padd_assoc (p q r : ℕ × ℕ) : padd (padd p q) r = padd p (padd q r) := calc padd (padd p q) r = (pr1 p + pr1 q + pr1 r, pr2 p + pr2 q + pr2 r) : rfl ... = (pr1 p + (pr1 q + pr1 r), pr2 p + pr2 q + pr2 r) : add.assoc ... = (pr1 p + (pr1 q + pr1 r), pr2 p + (pr2 q + pr2 r)) : add.assoc ... = padd p (padd q r) : rfl definition add.comm (a b : ℤ) : a + b = b + a := begin apply eq_of_repr_int_equiv_repr, apply int_equiv.trans, apply repr_add, apply int_equiv.symm, apply eq.subst (padd_comm (repr b) (repr a)), apply repr_add end definition add.assoc (a b c : ℤ) : a + b + c = a + (b + c) := assert H1 : repr (a + b + c) ≡ padd (padd (repr a) (repr b)) (repr c), from int_equiv.trans (repr_add (a + b) c) (padd_congr !repr_add !int_equiv.refl), assert H2 : repr (a + (b + c)) ≡ padd (repr a) (padd (repr b) (repr c)), from int_equiv.trans (repr_add a (b + c)) (padd_congr !int_equiv.refl !repr_add), begin apply eq_of_repr_int_equiv_repr, apply int_equiv.trans, apply H1, apply eq.subst (padd_assoc _ _ _)⁻¹, apply int_equiv.symm, apply H2 end definition add_zero (a : ℤ) : a + 0 = a := int.cases_on a (take m, rfl) (take m', rfl) definition zero_add (a : ℤ) : 0 + a = a := add.comm a 0 ▸ add_zero a /- negation -/ definition pneg (p : ℕ × ℕ) : ℕ × ℕ := (pr2 p, pr1 p) -- note: this is =, not just ≡ definition repr_neg (a : ℤ) : repr (- a) = pneg (repr a) := int.cases_on a (take m, nat.cases_on m rfl (take m', rfl)) (take m', rfl) definition pneg_congr {p p' : ℕ × ℕ} (H : p ≡ p') : pneg p ≡ pneg p' := inverse H definition pneg_pneg (p : ℕ × ℕ) : pneg (pneg p) = p := !prod.eta definition 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 definition 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 definition 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 : nat.add.assoc ... = pr1 p + (pr1 q + pr2 q + pr2 p) : nat.add.assoc ... = pr1 p + (pr2 q + pr1 q + pr2 p) : nat.add.comm ... = pr1 p + (pr2 q + pr2 p + pr1 q) : add.right_comm ... = pr1 p + (pr2 p + pr2 q + pr1 q) : nat.add.comm ... = pr2 p + pr2 q + pr1 q + pr1 p : nat.add.comm definition 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_int_equiv_repr H /- nat abs -/ definition pabs (p : ℕ × ℕ) : ℕ := dist (pr1 p) (pr2 p) definition 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 definition 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 definition nat_abs_add_le (a b : ℤ) : nat_abs (a + b) ≤ nat_abs a + nat_abs b := have H : nat_abs (a + b) = pabs (padd (repr a) (repr b)), from calc nat_abs (a + b) = pabs (repr (a + b)) : nat_abs_eq_pabs_repr ... = pabs (padd (repr a) (repr b)) : pabs_congr !repr_add, have H1 : nat_abs a = pabs (repr a), from !nat_abs_eq_pabs_repr, have H2 : nat_abs b = pabs (repr b), from !nat_abs_eq_pabs_repr, have H3 : pabs (padd (repr a) (repr b)) ≤ pabs (repr a) + pabs (repr b), from !dist_add_add_le_add_dist_dist, H⁻¹ ▸ H1⁻¹ ▸ H2⁻¹ ▸ H3 section local attribute nat_abs [reducible] definition mul_nat_abs (a b : ℤ) : nat_abs (a * b) = #nat (nat_abs a) * (nat_abs b) := int.cases_on a (take m, int.cases_on b (take n, rfl) (take n', !nat_abs_neg ▸ rfl)) (take m', int.cases_on b (take n, !nat_abs_neg ▸ rfl) (take n', rfl)) end /- multiplication -/ definition pmul (p q : ℕ × ℕ) : ℕ × ℕ := (pr1 p * pr1 q + pr2 p * pr2 q, pr1 p * pr2 q + pr2 p * pr1 q) definition 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 ≡ definition repr_mul (a b : ℤ) : repr (mul a b) = pmul (repr a) (repr b) := int.cases_on a (take m, int.cases_on b (take n, (calc pmul (repr m) (repr n) = (m * n + 0 * 0, m * 0 + 0 * n) : rfl ... = (m * n + 0 * 0, m * 0 + 0) : zero_mul)⁻¹) (take n', (calc pmul (repr m) (repr (neg_succ_of_nat n')) = (m * 0 + 0 * succ n', m * succ n' + 0 * 0) : rfl ... = (m * 0 + 0, m * succ n' + 0 * 0) : zero_mul ... = repr (mul m (neg_succ_of_nat n')) : repr_neg_of_nat)⁻¹)) (take m', int.cases_on b (take n, (calc pmul (repr (neg_succ_of_nat m')) (repr n) = (0 * n + succ m' * 0, 0 * 0 + succ m' * n) : rfl ... = (0 + succ m' * 0, 0 * 0 + succ m' * n) : zero_mul ... = (0 + succ m' * 0, succ m' * n) : {!nat.zero_add} ... = repr (mul (neg_succ_of_nat m') n) : repr_neg_of_nat)⁻¹) (take n', (calc pmul (repr (neg_succ_of_nat m')) (repr (neg_succ_of_nat n')) = (0 + succ m' * succ n', 0 * succ n') : rfl ... = (succ m' * succ n', 0 * succ n') : nat.zero_add ... = (succ m' * succ n', 0) : zero_mul ... = repr (mul (neg_succ_of_nat m') (neg_succ_of_nat n')) : rfl)⁻¹)) definition int_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.cancel_right (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)) : add.comm4 ... = xa*xn+ya*yn + (yb*xn+xb*yn) + (xb*xn+yb*yn + (xb*ym+yb*xm)) : nat.add.comm ... = xa*xn+yb*xn + (ya*yn+xb*yn) + (xb*xn+xb*ym + (yb*yn+yb*xm)) : !congr_arg2 add.comm4 add.comm4 ... = ya*xn+xb*xn + (xa*yn+yb*yn) + (xb*yn+xb*xm + (yb*xn+yb*ym)) : by rewrite[-+mul.left_distrib,-+mul.right_distrib]; exact H1 ▸ H2 ▸ rfl ... = ya*xn+xa*yn + (xb*xn+yb*yn) + (xb*yn+yb*xn + (xb*xm+yb*ym)) : !congr_arg2 add.comm4 add.comm4 ... = xa*yn+ya*xn + (xb*xn+yb*yn) + (yb*xn+xb*yn + (xb*xm+yb*ym)) : !nat.add.comm ▸ !nat.add.comm ▸ rfl ... = xa*yn+ya*xn + (yb*xn+xb*yn) + (xb*xn+yb*yn + (xb*xm+yb*ym)) : add.comm4 ... = xa*yn+ya*xn + (yb*xn+xb*yn) + (xb*xm+yb*ym + (xb*xn+yb*yn)) : nat.add.comm ... = xa*yn+ya*xn + (xb*xm+yb*ym) + (yb*xn+xb*yn + (xb*xn+yb*yn)) : add.comm4) definition pmul_congr {p p' q q' : ℕ × ℕ} (H1 : p ≡ p') (H2 : q ≡ q') : pmul p q ≡ pmul p' q' := int_equiv_mul_prep H1 H2 definition pmul_comm (p q : ℕ × ℕ) : pmul p q = pmul q p := calc (pr1 p * pr1 q + pr2 p * pr2 q, pr1 p * pr2 q + pr2 p * pr1 q) = (pr1 q * pr1 p + pr2 p * pr2 q, pr1 p * pr2 q + pr2 p * pr1 q) : mul.comm ... = (pr1 q * pr1 p + pr2 q * pr2 p, pr1 p * pr2 q + pr2 p * pr1 q) : mul.comm ... = (pr1 q * pr1 p + pr2 q * pr2 p, pr2 q * pr1 p + pr2 p * pr1 q) : mul.comm ... = (pr1 q * pr1 p + pr2 q * pr2 p, pr2 q * pr1 p + pr1 q * pr2 p) : mul.comm ... = (pr1 q * pr1 p + pr2 q * pr2 p, pr1 q * pr2 p + pr2 q * pr1 p) : nat.add.comm definition mul.comm (a b : ℤ) : a * b = b * a := eq_of_repr_int_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) ▸ !int_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[+mul.left_distrib,+mul.right_distrib,*mul.assoc], rewrite (@add.comm4 (p1 * (q1 * r1)) (p2 * (q2 * r1)) (p1 * (q2 * r2)) (p2 * (q1 * r2))), rewrite (nat.add.comm (p2 * (q2 * r1)) (p2 * (q1 * r2))), rewrite (@add.comm4 (p1 * (q1 * r2)) (p2 * (q2 * r2)) (p1 * (q2 * r1)) (p2 * (q1 * r1))), rewrite (nat.add.comm (p2 * (q2 * r2)) (p2 * (q1 * r1))) end definition pmul_assoc (p q r: ℕ × ℕ) : pmul (pmul p q) r = pmul p (pmul q r) := pmul_assoc_prep definition mul.assoc (a b c : ℤ) : (a * b) * c = a * (b * c) := eq_of_repr_int_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) ▸ !int_equiv.refl) set_option pp.coercions true definition mul_one (a : ℤ) : a * 1 = a := eq_of_repr_int_equiv_repr (int_equiv_of_eq ((calc repr (a * 1) = pmul (repr a) (repr 1) : repr_mul ... = (pr1 (repr a), pr2 (repr a)) : by unfold [pmul, repr]; krewrite [*mul_zero, *mul_one, *nat.add_zero, *nat.zero_add] ... = repr a : prod.eta))) definition one_mul (a : ℤ) : 1 * a = a := mul.comm a 1 ▸ 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)) := by rewrite[+mul.right_distrib] ⬝ (!congr_arg2 !add.comm4 !add.comm4) definition mul.right_distrib (a b c : ℤ) : (a + b) * c = a * c + b * c := eq_of_repr_int_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 int_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 a c)⁻¹} ... = padd (repr (a * c)) (repr (b * c)) : repr_mul ... ≡ repr (a * c + b * c) : int_equiv.symm !repr_add) definition mul.left_distrib (a b c : ℤ) : a * (b + c) = a * b + a * c := calc a * (b + c) = (b + c) * a : mul.comm a (b + c) ... = b * a + c * a : mul.right_distrib b c a ... = a * b + c * a : {mul.comm b a} ... = a * b + a * c : {mul.comm c a} definition zero_ne_one : (0 : int) ≠ 1 := assume H : 0 = 1, show empty, from succ_ne_zero 0 ((of_nat.inj H)⁻¹) definition eq_zero_or_eq_zero_of_mul_eq_zero {a b : ℤ} (H : a * b = 0) : a = 0 ⊎ b = 0 := have H2 : (nat_abs a) * (nat_abs b) = nat.zero, from calc (nat_abs a) * (nat_abs b) = (nat_abs (a * b)) : (mul_nat_abs a b)⁻¹ ... = (nat_abs 0) : {H} ... = nat.zero : nat_abs_of_nat nat.zero, have H3 : (nat_abs a) = nat.zero ⊎ (nat_abs b) = nat.zero, from eq_zero_or_eq_zero_of_mul_eq_zero H2, sum_of_sum_of_imp_of_imp H3 (assume H : (nat_abs a) = nat.zero, nat_abs_eq_zero H) (assume H : (nat_abs b) = nat.zero, nat_abs_eq_zero H) section open [classes] algebra protected definition integral_domain [instance] [reducible] : algebra.integral_domain int := ⦃algebra.integral_domain, add := add, add_assoc := add.assoc, zero := zero, zero_add := zero_add, add_zero := add_zero, neg := neg, add_left_inv := add.left_inv, add_comm := add.comm, mul := mul, mul_assoc := mul.assoc, one := (of_num 1), one_mul := one_mul, mul_one := mul_one, left_distrib := mul.left_distrib, right_distrib := mul.right_distrib, mul_comm := mul.comm, eq_zero_or_eq_zero_of_mul_eq_zero := @eq_zero_or_eq_zero_of_mul_eq_zero, is_hset_carrier := is_hset_of_decidable_eq⦄ end /- instantiate ring theorems to int -/ section port_algebra open [classes] algebra definition mul.left_comm : Πa b c : ℤ, a * (b * c) = b * (a * c) := algebra.mul.left_comm definition mul.right_comm : Πa b c : ℤ, (a * b) * c = (a * c) * b := algebra.mul.right_comm definition add.left_comm : Πa b c : ℤ, a + (b + c) = b + (a + c) := algebra.add.left_comm definition add.right_comm : Πa b c : ℤ, (a + b) + c = (a + c) + b := algebra.add.right_comm definition add.left_cancel : Π{a b c : ℤ}, a + b = a + c → b = c := @algebra.add.left_cancel _ _ definition add.right_cancel : Π{a b c : ℤ}, a + b = c + b → a = c := @algebra.add.right_cancel _ _ definition neg_add_cancel_left : Πa b : ℤ, -a + (a + b) = b := algebra.neg_add_cancel_left definition neg_add_cancel_right : Πa b : ℤ, a + -b + b = a := algebra.neg_add_cancel_right definition neg_eq_of_add_eq_zero : Π{a b : ℤ}, a + b = 0 → -a = b := @algebra.neg_eq_of_add_eq_zero _ _ definition neg_zero : -0 = 0 := algebra.neg_zero definition neg_neg : Πa : ℤ, -(-a) = a := algebra.neg_neg definition neg.inj : Π{a b : ℤ}, -a = -b → a = b := @algebra.neg.inj _ _ definition neg_eq_neg_iff_eq : Πa b : ℤ, -a = -b ↔ a = b := algebra.neg_eq_neg_iff_eq definition neg_eq_zero_iff_eq_zero : Πa : ℤ, -a = 0 ↔ a = 0 := algebra.neg_eq_zero_iff_eq_zero definition eq_neg_of_eq_neg : Π{a b : ℤ}, a = -b → b = -a := @algebra.eq_neg_of_eq_neg _ _ definition eq_neg_iff_eq_neg : Π{a b : ℤ}, a = -b ↔ b = -a := @algebra.eq_neg_iff_eq_neg _ _ definition add.right_inv : Πa : ℤ, a + -a = 0 := algebra.add.right_inv definition add_neg_cancel_left : Πa b : ℤ, a + (-a + b) = b := algebra.add_neg_cancel_left definition add_neg_cancel_right : Πa b : ℤ, a + b + -b = a := algebra.add_neg_cancel_right definition neg_add_rev : Πa b : ℤ, -(a + b) = -b + -a := algebra.neg_add_rev definition eq_add_neg_of_add_eq : Π{a b c : ℤ}, a + c = b → a = b + -c := @algebra.eq_add_neg_of_add_eq _ _ definition eq_neg_add_of_add_eq : Π{a b c : ℤ}, b + a = c → a = -b + c := @algebra.eq_neg_add_of_add_eq _ _ definition neg_add_eq_of_eq_add : Π{a b c : ℤ}, b = a + c → -a + b = c := @algebra.neg_add_eq_of_eq_add _ _ definition add_neg_eq_of_eq_add : Π{a b c : ℤ}, a = c + b → a + -b = c := @algebra.add_neg_eq_of_eq_add _ _ definition eq_add_of_add_neg_eq : Π{a b c : ℤ}, a + -c = b → a = b + c := @algebra.eq_add_of_add_neg_eq _ _ definition eq_add_of_neg_add_eq : Π{a b c : ℤ}, -b + a = c → a = b + c := @algebra.eq_add_of_neg_add_eq _ _ definition add_eq_of_eq_neg_add : Π{a b c : ℤ}, b = -a + c → a + b = c := @algebra.add_eq_of_eq_neg_add _ _ definition add_eq_of_eq_add_neg : Π{a b c : ℤ}, a = c + -b → a + b = c := @algebra.add_eq_of_eq_add_neg _ _ definition add_eq_iff_eq_neg_add : Πa b c : ℤ, a + b = c ↔ b = -a + c := @algebra.add_eq_iff_eq_neg_add _ _ definition add_eq_iff_eq_add_neg : Πa b c : ℤ, a + b = c ↔ a = c + -b := @algebra.add_eq_iff_eq_add_neg _ _ definition sub (a b : ℤ) : ℤ := algebra.sub a b infix - := int.sub definition sub_eq_add_neg : Πa b : ℤ, a - b = a + -b := algebra.sub_eq_add_neg definition sub_self : Πa : ℤ, a - a = 0 := algebra.sub_self definition sub_add_cancel : Πa b : ℤ, a - b + b = a := algebra.sub_add_cancel definition add_sub_cancel : Πa b : ℤ, a + b - b = a := algebra.add_sub_cancel definition eq_of_sub_eq_zero : Π{a b : ℤ}, a - b = 0 → a = b := @algebra.eq_of_sub_eq_zero _ _ definition eq_iff_sub_eq_zero : Πa b : ℤ, a = b ↔ a - b = 0 := algebra.eq_iff_sub_eq_zero definition zero_sub : Πa : ℤ, 0 - a = -a := algebra.zero_sub definition sub_zero : Πa : ℤ, a - 0 = a := algebra.sub_zero definition sub_neg_eq_add : Πa b : ℤ, a - (-b) = a + b := algebra.sub_neg_eq_add definition neg_sub : Πa b : ℤ, -(a - b) = b - a := algebra.neg_sub definition add_sub : Πa b c : ℤ, a + (b - c) = a + b - c := algebra.add_sub definition sub_add_eq_sub_sub_swap : Πa b c : ℤ, a - (b + c) = a - c - b := algebra.sub_add_eq_sub_sub_swap definition sub_eq_iff_eq_add : Πa b c : ℤ, a - b = c ↔ a = c + b := algebra.sub_eq_iff_eq_add definition eq_sub_iff_add_eq : Πa b c : ℤ, a = b - c ↔ a + c = b := algebra.eq_sub_iff_add_eq definition eq_iff_eq_of_sub_eq_sub : Π{a b c d : ℤ}, a - b = c - d → (a = b ↔ c = d) := @algebra.eq_iff_eq_of_sub_eq_sub _ _ definition eq_sub_of_add_eq : Π{a b c : ℤ}, a + c = b → a = b - c := @algebra.eq_sub_of_add_eq _ _ definition sub_eq_of_eq_add : Π{a b c : ℤ}, a = c + b → a - b = c := @algebra.sub_eq_of_eq_add _ _ definition eq_add_of_sub_eq : Π{a b c : ℤ}, a - c = b → a = b + c := @algebra.eq_add_of_sub_eq _ _ definition add_eq_of_eq_sub : Π{a b c : ℤ}, a = c - b → a + b = c := @algebra.add_eq_of_eq_sub _ _ definition sub_add_eq_sub_sub : Πa b c : ℤ, a - (b + c) = a - b - c := algebra.sub_add_eq_sub_sub definition neg_add_eq_sub : Πa b : ℤ, -a + b = b - a := algebra.neg_add_eq_sub definition neg_add : Πa b : ℤ, -(a + b) = -a + -b := algebra.neg_add definition sub_add_eq_add_sub : Πa b c : ℤ, a - b + c = a + c - b := algebra.sub_add_eq_add_sub definition sub_sub_ : Πa b c : ℤ, a - b - c = a - (b + c) := algebra.sub_sub definition add_sub_add_left_eq_sub : Πa b c : ℤ, (c + a) - (c + b) = a - b := algebra.add_sub_add_left_eq_sub definition eq_sub_of_add_eq' : Π{a b c : ℤ}, c + a = b → a = b - c := @algebra.eq_sub_of_add_eq' _ _ definition sub_eq_of_eq_add' : Π{a b c : ℤ}, a = b + c → a - b = c := @algebra.sub_eq_of_eq_add' _ _ definition eq_add_of_sub_eq' : Π{a b c : ℤ}, a - b = c → a = b + c := @algebra.eq_add_of_sub_eq' _ _ definition add_eq_of_eq_sub' : Π{a b c : ℤ}, b = c - a → a + b = c := @algebra.add_eq_of_eq_sub' _ _ definition ne_zero_of_mul_ne_zero_right : Π{a b : ℤ}, a * b ≠ 0 → a ≠ 0 := @algebra.ne_zero_of_mul_ne_zero_right _ _ definition ne_zero_of_mul_ne_zero_left : Π{a b : ℤ}, a * b ≠ 0 → b ≠ 0 := @algebra.ne_zero_of_mul_ne_zero_left _ _ definition dvd (a b : ℤ) : Type₀ := algebra.dvd a b notation a ∣ b := dvd a b definition dvd.intro : Π{a b c : ℤ} (H : a * c = b), a ∣ b := @algebra.dvd.intro _ _ definition dvd.intro_left : Π{a b c : ℤ} (H : c * a = b), a ∣ b := @algebra.dvd.intro_left _ _ definition exists_eq_mul_right_of_dvd : Π{a b : ℤ} (H : a ∣ b), Σc, b = a * c := @algebra.exists_eq_mul_right_of_dvd _ _ definition dvd.elim : Π{P : Type} {a b : ℤ} (H₁ : a ∣ b) (H₂ : Πc, b = a * c → P), P := @algebra.dvd.elim _ _ definition exists_eq_mul_left_of_dvd : Π{a b : ℤ} (H : a ∣ b), Σc, b = c * a := @algebra.exists_eq_mul_left_of_dvd _ _ definition dvd.elim_left : Π{P : Type} {a b : ℤ} (H₁ : a ∣ b) (H₂ : Πc, b = c * a → P), P := @algebra.dvd.elim_left _ _ definition dvd.refl : Πa : ℤ, (a ∣ a) := algebra.dvd.refl definition dvd.trans : Π{a b c : ℤ} (H₁ : a ∣ b) (H₂ : b ∣ c), a ∣ c := @algebra.dvd.trans _ _ definition eq_zero_of_zero_dvd : Π{a : ℤ} (H : 0 ∣ a), a = 0 := @algebra.eq_zero_of_zero_dvd _ _ definition dvd_zero : Πa : ℤ, a ∣ 0 := algebra.dvd_zero definition one_dvd : Πa : ℤ, 1 ∣ a := algebra.one_dvd definition dvd_mul_right : Πa b : ℤ, a ∣ a * b := algebra.dvd_mul_right definition dvd_mul_left : Πa b : ℤ, a ∣ b * a := algebra.dvd_mul_left definition dvd_mul_of_dvd_left : Π{a b : ℤ} (H : a ∣ b) (c : ℤ), a ∣ b * c := @algebra.dvd_mul_of_dvd_left _ _ definition dvd_mul_of_dvd_right : Π{a b : ℤ} (H : a ∣ b) (c : ℤ), a ∣ c * b := @algebra.dvd_mul_of_dvd_right _ _ definition mul_dvd_mul : Π{a b c d : ℤ}, a ∣ b → c ∣ d → a * c ∣ b * d := @algebra.mul_dvd_mul _ _ definition dvd_of_mul_right_dvd : Π{a b c : ℤ}, a * b ∣ c → a ∣ c := @algebra.dvd_of_mul_right_dvd _ _ definition dvd_of_mul_left_dvd : Π{a b c : ℤ}, a * b ∣ c → b ∣ c := @algebra.dvd_of_mul_left_dvd _ _ definition dvd_add : Π{a b c : ℤ}, a ∣ b → a ∣ c → a ∣ b + c := @algebra.dvd_add _ _ definition zero_mul : Πa : ℤ, 0 * a = 0 := algebra.zero_mul definition mul_zero : Πa : ℤ, a * 0 = 0 := algebra.mul_zero definition neg_mul_eq_neg_mul : Πa b : ℤ, -(a * b) = -a * b := algebra.neg_mul_eq_neg_mul definition neg_mul_eq_mul_neg : Πa b : ℤ, -(a * b) = a * -b := algebra.neg_mul_eq_mul_neg definition neg_mul_neg : Πa b : ℤ, -a * -b = a * b := algebra.neg_mul_neg definition neg_mul_comm : Πa b : ℤ, -a * b = a * -b := algebra.neg_mul_comm definition neg_eq_neg_one_mul : Πa : ℤ, -a = -1 * a := algebra.neg_eq_neg_one_mul definition mul_sub_left_distrib : Πa b c : ℤ, a * (b - c) = a * b - a * c := algebra.mul_sub_left_distrib definition mul_sub_right_distrib : Πa b c : ℤ, (a - b) * c = a * c - b * c := algebra.mul_sub_right_distrib definition mul_add_eq_mul_add_iff_sub_mul_add_eq : Πa b c d e : ℤ, a * e + c = b * e + d ↔ (a - b) * e + c = d := algebra.mul_add_eq_mul_add_iff_sub_mul_add_eq definition mul_self_sub_mul_self_eq : Πa b : ℤ, a * a - b * b = (a + b) * (a - b) := algebra.mul_self_sub_mul_self_eq definition mul_self_sub_one_eq : Πa : ℤ, a * a - 1 = (a + 1) * (a - 1) := algebra.mul_self_sub_one_eq definition dvd_neg_iff_dvd : Πa b : ℤ, a ∣ -b ↔ a ∣ b := algebra.dvd_neg_iff_dvd definition neg_dvd_iff_dvd : Πa b : ℤ, -a ∣ b ↔ a ∣ b := algebra.neg_dvd_iff_dvd definition dvd_sub : Πa b c : ℤ, a ∣ b → a ∣ c → a ∣ b - c := algebra.dvd_sub definition mul_ne_zero : Π{a b : ℤ}, a ≠ 0 → b ≠ 0 → a * b ≠ 0 := @algebra.mul_ne_zero _ _ definition eq_of_mul_eq_mul_right : Π{a b c : ℤ}, a ≠ 0 → b * a = c * a → b = c := @algebra.eq_of_mul_eq_mul_right _ _ definition eq_of_mul_eq_mul_left : Π{a b c : ℤ}, a ≠ 0 → a * b = a * c → b = c := @algebra.eq_of_mul_eq_mul_left _ _ definition mul_self_eq_mul_self_iff : Πa b : ℤ, a * a = b * b ↔ a = b ⊎ a = -b := algebra.mul_self_eq_mul_self_iff definition mul_self_eq_one_iff : Πa : ℤ, a * a = 1 ↔ a = 1 ⊎ a = -1 := algebra.mul_self_eq_one_iff definition dvd_of_mul_dvd_mul_left : Π{a b c : ℤ}, a ≠ 0 → a*b ∣ a*c → b ∣ c := @algebra.dvd_of_mul_dvd_mul_left _ _ definition dvd_of_mul_dvd_mul_right : Π{a b c : ℤ}, a ≠ 0 → b*a ∣ c*a → b ∣ c := @algebra.dvd_of_mul_dvd_mul_right _ _ end port_algebra /- additional properties -/ definition of_nat_sub_of_nat {m n : ℕ} (H : #nat m ≥ n) : of_nat m - of_nat n = of_nat (#nat m - n) := have H1 : m = (#nat m - n + n), from (nat.sub_add_cancel H)⁻¹, have H2 : m = (#nat m - n) + n, from ap of_nat H1, sub_eq_of_eq_add H2 definition neg_succ_of_nat_eq' (m : ℕ) : -[m +1] = -m - 1 := by rewrite [neg_succ_of_nat_eq, -of_nat_add_of_nat, neg_add] definition succ (a : ℤ) := a + (nat.succ zero) definition pred (a : ℤ) := a - (nat.succ zero) definition nat_succ_eq_int_succ (n : ℕ) : nat.succ n = int.succ n := idp definition pred_succ (a : ℤ) : pred (succ a) = a := !sub_add_cancel definition succ_pred (a : ℤ) : succ (pred a) = a := !add_sub_cancel definition neg_succ (a : ℤ) : -succ a = pred (-a) := by rewrite [↑succ,neg_add] definition succ_neg_succ (a : ℤ) : succ (-succ a) = -a := by rewrite [neg_succ,succ_pred] definition neg_pred (a : ℤ) : -pred a = succ (-a) := by rewrite [↑pred,neg_sub,sub_eq_add_neg,add.comm] definition pred_neg_pred (a : ℤ) : pred (-pred a) = -a := by rewrite [neg_pred,pred_succ] definition pred_nat_succ (n : ℕ) : pred (nat.succ n) = n := pred_succ n definition neg_nat_succ (n : ℕ) : -nat.succ n = pred (-n) := !neg_succ definition 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 := begin induction z with n n, {exact nat.rec_on n H0 Hsucc}, {induction n with m ih, exact Hpred H0, exact Hpred ih} end --the only computation rule of rec_nat_on which is not definitional definition 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_on n rfl (λn H, rfl) end int
ebff435cf29cee4889cfca85596ca73bb9ed4fcc
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/AdditiveCommutativeSemigroup.lean
7c4011fad126c0210513cb4f9c03e8a9e0e12622
[]
no_license
ysharoda/Deriving-Definitions
3e149e6641fae440badd35ac110a0bd705a49ad2
dfecb27572022de3d4aa702cae8db19957523a59
refs/heads/master
1,679,127,857,700
1,615,939,007,000
1,615,939,007,000
229,785,731
4
0
null
null
null
null
UTF-8
Lean
false
false
7,286
lean
import init.data.nat.basic import init.data.fin.basic import data.vector import .Prelude open Staged open nat open fin open vector section AdditiveCommutativeSemigroup structure AdditiveCommutativeSemigroup (A : Type) : Type := (plus : (A → (A → A))) (commutative_plus : (∀ {x y : A} , (plus x y) = (plus y x))) (associative_plus : (∀ {x y z : A} , (plus (plus x y) z) = (plus x (plus y z)))) open AdditiveCommutativeSemigroup structure Sig (AS : Type) : Type := (plusS : (AS → (AS → AS))) structure Product (A : Type) : Type := (plusP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (commutative_plusP : (∀ {xP yP : (Prod A A)} , (plusP xP yP) = (plusP yP xP))) (associative_plusP : (∀ {xP yP zP : (Prod A A)} , (plusP (plusP xP yP) zP) = (plusP xP (plusP yP zP)))) structure Hom {A1 : Type} {A2 : Type} (Ad1 : (AdditiveCommutativeSemigroup A1)) (Ad2 : (AdditiveCommutativeSemigroup A2)) : Type := (hom : (A1 → A2)) (pres_plus : (∀ {x1 x2 : A1} , (hom ((plus Ad1) x1 x2)) = ((plus Ad2) (hom x1) (hom x2)))) structure RelInterp {A1 : Type} {A2 : Type} (Ad1 : (AdditiveCommutativeSemigroup A1)) (Ad2 : (AdditiveCommutativeSemigroup A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_plus : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((plus Ad1) x1 x2) ((plus Ad2) y1 y2)))))) inductive AdditiveCommutativeSemigroupTerm : Type | plusL : (AdditiveCommutativeSemigroupTerm → (AdditiveCommutativeSemigroupTerm → AdditiveCommutativeSemigroupTerm)) open AdditiveCommutativeSemigroupTerm inductive ClAdditiveCommutativeSemigroupTerm (A : Type) : Type | sing : (A → ClAdditiveCommutativeSemigroupTerm) | plusCl : (ClAdditiveCommutativeSemigroupTerm → (ClAdditiveCommutativeSemigroupTerm → ClAdditiveCommutativeSemigroupTerm)) open ClAdditiveCommutativeSemigroupTerm inductive OpAdditiveCommutativeSemigroupTerm (n : ℕ) : Type | v : ((fin n) → OpAdditiveCommutativeSemigroupTerm) | plusOL : (OpAdditiveCommutativeSemigroupTerm → (OpAdditiveCommutativeSemigroupTerm → OpAdditiveCommutativeSemigroupTerm)) open OpAdditiveCommutativeSemigroupTerm inductive OpAdditiveCommutativeSemigroupTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpAdditiveCommutativeSemigroupTerm2) | sing2 : (A → OpAdditiveCommutativeSemigroupTerm2) | plusOL2 : (OpAdditiveCommutativeSemigroupTerm2 → (OpAdditiveCommutativeSemigroupTerm2 → OpAdditiveCommutativeSemigroupTerm2)) open OpAdditiveCommutativeSemigroupTerm2 def simplifyCl {A : Type} : ((ClAdditiveCommutativeSemigroupTerm A) → (ClAdditiveCommutativeSemigroupTerm A)) | (plusCl x1 x2) := (plusCl (simplifyCl x1) (simplifyCl x2)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpAdditiveCommutativeSemigroupTerm n) → (OpAdditiveCommutativeSemigroupTerm n)) | (plusOL x1 x2) := (plusOL (simplifyOpB x1) (simplifyOpB x2)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpAdditiveCommutativeSemigroupTerm2 n A) → (OpAdditiveCommutativeSemigroupTerm2 n A)) | (plusOL2 x1 x2) := (plusOL2 (simplifyOp x1) (simplifyOp x2)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((AdditiveCommutativeSemigroup A) → (AdditiveCommutativeSemigroupTerm → A)) | Ad (plusL x1 x2) := ((plus Ad) (evalB Ad x1) (evalB Ad x2)) def evalCl {A : Type} : ((AdditiveCommutativeSemigroup A) → ((ClAdditiveCommutativeSemigroupTerm A) → A)) | Ad (sing x1) := x1 | Ad (plusCl x1 x2) := ((plus Ad) (evalCl Ad x1) (evalCl Ad x2)) def evalOpB {A : Type} {n : ℕ} : ((AdditiveCommutativeSemigroup A) → ((vector A n) → ((OpAdditiveCommutativeSemigroupTerm n) → A))) | Ad vars (v x1) := (nth vars x1) | Ad vars (plusOL x1 x2) := ((plus Ad) (evalOpB Ad vars x1) (evalOpB Ad vars x2)) def evalOp {A : Type} {n : ℕ} : ((AdditiveCommutativeSemigroup A) → ((vector A n) → ((OpAdditiveCommutativeSemigroupTerm2 n A) → A))) | Ad vars (v2 x1) := (nth vars x1) | Ad vars (sing2 x1) := x1 | Ad vars (plusOL2 x1 x2) := ((plus Ad) (evalOp Ad vars x1) (evalOp Ad vars x2)) def inductionB {P : (AdditiveCommutativeSemigroupTerm → Type)} : ((∀ (x1 x2 : AdditiveCommutativeSemigroupTerm) , ((P x1) → ((P x2) → (P (plusL x1 x2))))) → (∀ (x : AdditiveCommutativeSemigroupTerm) , (P x))) | pplusl (plusL x1 x2) := (pplusl _ _ (inductionB pplusl x1) (inductionB pplusl x2)) def inductionCl {A : Type} {P : ((ClAdditiveCommutativeSemigroupTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClAdditiveCommutativeSemigroupTerm A)) , ((P x1) → ((P x2) → (P (plusCl x1 x2))))) → (∀ (x : (ClAdditiveCommutativeSemigroupTerm A)) , (P x)))) | psing ppluscl (sing x1) := (psing x1) | psing ppluscl (plusCl x1 x2) := (ppluscl _ _ (inductionCl psing ppluscl x1) (inductionCl psing ppluscl x2)) def inductionOpB {n : ℕ} {P : ((OpAdditiveCommutativeSemigroupTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpAdditiveCommutativeSemigroupTerm n)) , ((P x1) → ((P x2) → (P (plusOL x1 x2))))) → (∀ (x : (OpAdditiveCommutativeSemigroupTerm n)) , (P x)))) | pv pplusol (v x1) := (pv x1) | pv pplusol (plusOL x1 x2) := (pplusol _ _ (inductionOpB pv pplusol x1) (inductionOpB pv pplusol x2)) def inductionOp {n : ℕ} {A : Type} {P : ((OpAdditiveCommutativeSemigroupTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpAdditiveCommutativeSemigroupTerm2 n A)) , ((P x1) → ((P x2) → (P (plusOL2 x1 x2))))) → (∀ (x : (OpAdditiveCommutativeSemigroupTerm2 n A)) , (P x))))) | pv2 psing2 pplusol2 (v2 x1) := (pv2 x1) | pv2 psing2 pplusol2 (sing2 x1) := (psing2 x1) | pv2 psing2 pplusol2 (plusOL2 x1 x2) := (pplusol2 _ _ (inductionOp pv2 psing2 pplusol2 x1) (inductionOp pv2 psing2 pplusol2 x2)) def stageB : (AdditiveCommutativeSemigroupTerm → (Staged AdditiveCommutativeSemigroupTerm)) | (plusL x1 x2) := (stage2 plusL (codeLift2 plusL) (stageB x1) (stageB x2)) def stageCl {A : Type} : ((ClAdditiveCommutativeSemigroupTerm A) → (Staged (ClAdditiveCommutativeSemigroupTerm A))) | (sing x1) := (Now (sing x1)) | (plusCl x1 x2) := (stage2 plusCl (codeLift2 plusCl) (stageCl x1) (stageCl x2)) def stageOpB {n : ℕ} : ((OpAdditiveCommutativeSemigroupTerm n) → (Staged (OpAdditiveCommutativeSemigroupTerm n))) | (v x1) := (const (code (v x1))) | (plusOL x1 x2) := (stage2 plusOL (codeLift2 plusOL) (stageOpB x1) (stageOpB x2)) def stageOp {n : ℕ} {A : Type} : ((OpAdditiveCommutativeSemigroupTerm2 n A) → (Staged (OpAdditiveCommutativeSemigroupTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | (plusOL2 x1 x2) := (stage2 plusOL2 (codeLift2 plusOL2) (stageOp x1) (stageOp x2)) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (plusT : ((Repr A) → ((Repr A) → (Repr A)))) end AdditiveCommutativeSemigroup
dcf0b9a75c0d76b82bc93057b430077424fb275c
367134ba5a65885e863bdc4507601606690974c1
/src/measure_theory/measure_space.lean
730b532c142b7e43074f93555ba1d94390f6b002
[ "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
109,977
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import measure_theory.outer_measure import order.filter.countable_Inter import data.set.accumulate /-! # Measure spaces Given a measurable space `α`, a measure on `α` is a function that sends measurable sets to the extended nonnegative reals that satisfies the following conditions: 1. `μ ∅ = 0`; 2. `μ` is countably additive. This means that the measure of a countable union of pairwise disjoint sets is equal to the measure of the individual sets. Every measure can be canonically extended to an outer measure, so that it assigns values to all subsets, not just the measurable subsets. On the other hand, a measure that is countably additive on measurable sets can be restricted to measurable sets to obtain a measure. In this file a measure is defined to be an outer measure that is countably additive on measurable sets, with the additional assumption that the outer measure is the canonical extension of the restricted measure. Measures on `α` form a complete lattice, and are closed under scalar multiplication with `ℝ≥0∞`. We introduce the following typeclasses for measures: * `probability_measure μ`: `μ univ = 1`; * `finite_measure μ`: `μ univ < ∞`; * `sigma_finite μ`: there exists a countable collection of measurable sets that cover `univ` where `μ` is finite; * `locally_finite_measure μ` : `∀ x, ∃ s ∈ 𝓝 x, μ s < ∞`; * `has_no_atoms μ` : `∀ x, μ {x} = 0`; possibly should be redefined as `∀ s, 0 < μ s → ∃ t ⊆ s, 0 < μ t ∧ μ t < μ s`. Given a measure, the null sets are the sets where `μ s = 0`, where `μ` denotes the corresponding outer measure (so `s` might not be measurable). We can then define the completion of `μ` as the measure on the least `σ`-algebra that also contains all null sets, by defining the measure to be `0` on the null sets. ## Main statements * `completion` is the completion of a measure to all null measurable sets. * `measure.of_measurable` and `outer_measure.to_measure` are two important ways to define a measure. ## Implementation notes Given `μ : measure α`, `μ s` is the value of the *outer measure* applied to `s`. This conveniently allows us to apply the measure to sets without proving that they are measurable. We get countable subadditivity for all sets, but only countable additivity for measurable sets. You often don't want to define a measure via its constructor. Two ways that are sometimes more convenient: * `measure.of_measurable` is a way to define a measure by only giving its value on measurable sets and proving the properties (1) and (2) mentioned above. * `outer_measure.to_measure` is a way of obtaining a measure from an outer measure by showing that all measurable sets in the measurable space are Carathéodory measurable. To prove that two measures are equal, there are multiple options: * `ext`: two measures are equal if they are equal on all measurable sets. * `ext_of_generate_from_of_Union`: two measures are equal if they are equal on a π-system generating the measurable sets, if the π-system contains a spanning increasing sequence of sets where the measures take finite value (in particular the measures are σ-finite). This is a special case of the more general `ext_of_generate_from_of_cover` * `ext_of_generate_finite`: two finite measures are equal if they are equal on a π-system generating the measurable sets. This is a special case of `ext_of_generate_from_of_Union` using `C ∪ {univ}`, but is easier to work with. A `measure_space` is a class that is a measurable space with a canonical measure. The measure is denoted `volume`. ## References * <https://en.wikipedia.org/wiki/Measure_(mathematics)> * <https://en.wikipedia.org/wiki/Complete_measure> * <https://en.wikipedia.org/wiki/Almost_everywhere> ## Tags measure, almost everywhere, measure space, completion, null set, null measurable set -/ noncomputable theory open classical set filter (hiding map) function measurable_space open_locale classical topological_space big_operators filter ennreal variables {α β γ δ ι : Type*} namespace measure_theory /-- A measure is defined to be an outer measure that is countably additive on measurable sets, with the additional assumption that the outer measure is the canonical extension of the restricted measure. -/ structure measure (α : Type*) [measurable_space α] extends outer_measure α := (m_Union ⦃f : ℕ → set α⦄ : (∀ i, measurable_set (f i)) → pairwise (disjoint on f) → measure_of (⋃ i, f i) = ∑' i, measure_of (f i)) (trimmed : to_outer_measure.trim = to_outer_measure) /-- Measure projections for a measure space. For measurable sets this returns the measure assigned by the `measure_of` field in `measure`. But we can extend this to _all_ sets, but using the outer measure. This gives us monotonicity and subadditivity for all sets. -/ instance measure.has_coe_to_fun [measurable_space α] : has_coe_to_fun (measure α) := ⟨λ _, set α → ℝ≥0∞, λ m, m.to_outer_measure⟩ section variables [measurable_space α] {μ μ₁ μ₂ : measure α} {s s₁ s₂ t : set α} namespace measure /-! ### General facts about measures -/ /-- Obtain a measure by giving a countably additive function that sends `∅` to `0`. -/ def of_measurable (m : Π (s : set α), measurable_set s → ℝ≥0∞) (m0 : m ∅ measurable_set.empty = 0) (mU : ∀ {{f : ℕ → set α}} (h : ∀ i, measurable_set (f i)), pairwise (disjoint on f) → m (⋃ i, f i) (measurable_set.Union h) = ∑' i, m (f i) (h i)) : measure α := { m_Union := λ f hf hd, show induced_outer_measure m _ m0 (Union f) = ∑' i, induced_outer_measure m _ m0 (f i), begin rw [induced_outer_measure_eq m0 mU, mU hf hd], congr, funext n, rw induced_outer_measure_eq m0 mU end, trimmed := show (induced_outer_measure m _ m0).trim = induced_outer_measure m _ m0, begin unfold outer_measure.trim, congr, funext s hs, exact induced_outer_measure_eq m0 mU hs end, ..induced_outer_measure m _ m0 } lemma of_measurable_apply {m : Π (s : set α), measurable_set s → ℝ≥0∞} {m0 : m ∅ measurable_set.empty = 0} {mU : ∀ {{f : ℕ → set α}} (h : ∀ i, measurable_set (f i)), pairwise (disjoint on f) → m (⋃ i, f i) (measurable_set.Union h) = ∑' i, m (f i) (h i)} (s : set α) (hs : measurable_set s) : of_measurable m m0 mU s = m s hs := induced_outer_measure_eq m0 mU hs lemma to_outer_measure_injective : injective (to_outer_measure : measure α → outer_measure α) := λ ⟨m₁, u₁, h₁⟩ ⟨m₂, u₂, h₂⟩ h, by { congr, exact h } @[ext] lemma ext (h : ∀ s, measurable_set s → μ₁ s = μ₂ s) : μ₁ = μ₂ := to_outer_measure_injective $ by rw [← trimmed, outer_measure.trim_congr h, trimmed] lemma ext_iff : μ₁ = μ₂ ↔ ∀ s, measurable_set s → μ₁ s = μ₂ s := ⟨by { rintro rfl s hs, refl }, measure.ext⟩ end measure @[simp] lemma coe_to_outer_measure : ⇑μ.to_outer_measure = μ := rfl lemma to_outer_measure_apply (s : set α) : μ.to_outer_measure s = μ s := rfl lemma measure_eq_trim (s : set α) : μ s = μ.to_outer_measure.trim s := by rw μ.trimmed; refl lemma measure_eq_infi (s : set α) : μ s = ⨅ t (st : s ⊆ t) (ht : measurable_set t), μ t := by rw [measure_eq_trim, outer_measure.trim_eq_infi]; refl /-- A variant of `measure_eq_infi` which has a single `infi`. This is useful when applying a lemma next that only works for non-empty infima, in which case you can use `nonempty_measurable_superset`. -/ lemma measure_eq_infi' (μ : measure α) (s : set α) : μ s = ⨅ t : { t // s ⊆ t ∧ measurable_set t}, μ t := by simp_rw [infi_subtype, infi_and, subtype.coe_mk, ← measure_eq_infi] lemma measure_eq_induced_outer_measure : μ s = induced_outer_measure (λ s _, μ s) measurable_set.empty μ.empty s := measure_eq_trim _ lemma to_outer_measure_eq_induced_outer_measure : μ.to_outer_measure = induced_outer_measure (λ s _, μ s) measurable_set.empty μ.empty := μ.trimmed.symm lemma measure_eq_extend (hs : measurable_set s) : μ s = extend (λ t (ht : measurable_set t), μ t) s := by { rw [measure_eq_induced_outer_measure, induced_outer_measure_eq_extend _ _ hs], exact μ.m_Union } @[simp] lemma measure_empty : μ ∅ = 0 := μ.empty lemma nonempty_of_measure_ne_zero (h : μ s ≠ 0) : s.nonempty := ne_empty_iff_nonempty.1 $ λ h', h $ h'.symm ▸ measure_empty lemma measure_mono (h : s₁ ⊆ s₂) : μ s₁ ≤ μ s₂ := μ.mono h lemma measure_mono_null (h : s₁ ⊆ s₂) (h₂ : μ s₂ = 0) : μ s₁ = 0 := nonpos_iff_eq_zero.1 $ h₂ ▸ measure_mono h lemma measure_mono_top (h : s₁ ⊆ s₂) (h₁ : μ s₁ = ∞) : μ s₂ = ∞ := top_unique $ h₁ ▸ measure_mono h lemma exists_measurable_superset (μ : measure α) (s : set α) : ∃ t, s ⊆ t ∧ measurable_set t ∧ μ t = μ s := by simpa only [← measure_eq_trim] using μ.to_outer_measure.exists_measurable_superset_eq_trim s /-- A measurable set `t ⊇ s` such that `μ t = μ s`. -/ def to_measurable (μ : measure α) (s : set α) : set α := classical.some (exists_measurable_superset μ s) lemma subset_to_measurable (μ : measure α) (s : set α) : s ⊆ to_measurable μ s := (classical.some_spec (exists_measurable_superset μ s)).1 @[simp] lemma measurable_set_to_measurable (μ : measure α) (s : set α) : measurable_set (to_measurable μ s) := (classical.some_spec (exists_measurable_superset μ s)).2.1 @[simp] lemma measure_to_measurable (s : set α) : μ (to_measurable μ s) = μ s := (classical.some_spec (exists_measurable_superset μ s)).2.2 lemma exists_measurable_superset_of_null (h : μ s = 0) : ∃ t, s ⊆ t ∧ measurable_set t ∧ μ t = 0 := outer_measure.exists_measurable_superset_of_trim_eq_zero (by rw [← measure_eq_trim, h]) lemma exists_measurable_superset_iff_measure_eq_zero : (∃ t, s ⊆ t ∧ measurable_set t ∧ μ t = 0) ↔ μ s = 0 := ⟨λ ⟨t, hst, _, ht⟩, measure_mono_null hst ht, exists_measurable_superset_of_null⟩ theorem measure_Union_le [encodable β] (s : β → set α) : μ (⋃ i, s i) ≤ ∑' i, μ (s i) := μ.to_outer_measure.Union _ lemma measure_bUnion_le {s : set β} (hs : countable s) (f : β → set α) : μ (⋃ b ∈ s, f b) ≤ ∑' p : s, μ (f p) := begin haveI := hs.to_encodable, rw [bUnion_eq_Union], apply measure_Union_le end lemma measure_bUnion_finset_le (s : finset β) (f : β → set α) : μ (⋃ b ∈ s, f b) ≤ ∑ p in s, μ (f p) := begin rw [← finset.sum_attach, finset.attach_eq_univ, ← tsum_fintype], exact measure_bUnion_le s.countable_to_set f end lemma measure_bUnion_lt_top {s : set β} {f : β → set α} (hs : finite s) (hfin : ∀ i ∈ s, μ (f i) < ∞) : μ (⋃ i ∈ s, f i) < ∞ := begin convert (measure_bUnion_finset_le hs.to_finset f).trans_lt _, { ext, rw [finite.mem_to_finset] }, apply ennreal.sum_lt_top, simpa only [finite.mem_to_finset] end lemma measure_Union_null [encodable β] {s : β → set α} : (∀ i, μ (s i) = 0) → μ (⋃ i, s i) = 0 := μ.to_outer_measure.Union_null lemma measure_Union_null_iff [encodable ι] {s : ι → set α} : μ (⋃ i, s i) = 0 ↔ ∀ i, μ (s i) = 0 := ⟨λ h i, measure_mono_null (subset_Union _ _) h, measure_Union_null⟩ theorem measure_union_le (s₁ s₂ : set α) : μ (s₁ ∪ s₂) ≤ μ s₁ + μ s₂ := μ.to_outer_measure.union _ _ lemma measure_union_null : μ s₁ = 0 → μ s₂ = 0 → μ (s₁ ∪ s₂) = 0 := μ.to_outer_measure.union_null lemma measure_union_null_iff : μ (s₁ ∪ s₂) = 0 ↔ μ s₁ = 0 ∧ μ s₂ = 0:= ⟨λ h, ⟨measure_mono_null (subset_union_left _ _) h, measure_mono_null (subset_union_right _ _) h⟩, λ h, measure_union_null h.1 h.2⟩ /-! ### The almost everywhere filter -/ /-- The “almost everywhere” filter of co-null sets. -/ def measure.ae (μ : measure α) : filter α := { sets := {s | μ sᶜ = 0}, univ_sets := by simp, inter_sets := λ s t hs ht, by simp only [compl_inter, mem_set_of_eq]; exact measure_union_null hs ht, sets_of_superset := λ s t hs hst, measure_mono_null (set.compl_subset_compl.2 hst) hs } notation `∀ᵐ` binders ` ∂` μ `, ` r:(scoped P, filter.eventually P (measure.ae μ)) := r notation f ` =ᵐ[`:50 μ:50 `] `:0 g:50 := f =ᶠ[measure.ae μ] g notation f ` ≤ᵐ[`:50 μ:50 `] `:0 g:50 := f ≤ᶠ[measure.ae μ] g lemma mem_ae_iff {s : set α} : s ∈ μ.ae ↔ μ sᶜ = 0 := iff.rfl lemma ae_iff {p : α → Prop} : (∀ᵐ a ∂ μ, p a) ↔ μ { a | ¬ p a } = 0 := iff.rfl lemma compl_mem_ae_iff {s : set α} : sᶜ ∈ μ.ae ↔ μ s = 0 := by simp only [mem_ae_iff, compl_compl] lemma measure_zero_iff_ae_nmem {s : set α} : μ s = 0 ↔ ∀ᵐ a ∂ μ, a ∉ s := compl_mem_ae_iff.symm lemma ae_of_all {p : α → Prop} (μ : measure α) : (∀ a, p a) → ∀ᵐ a ∂ μ, p a := eventually_of_forall instance ae_is_measurably_generated : is_measurably_generated μ.ae := ⟨λ s hs, let ⟨t, hst, htm, htμ⟩ := exists_measurable_superset_of_null hs in ⟨tᶜ, compl_mem_ae_iff.2 htμ, htm.compl, compl_subset_comm.1 hst⟩⟩ instance : countable_Inter_filter μ.ae := ⟨begin intros S hSc hS, simp only [mem_ae_iff, compl_sInter, sUnion_image, bUnion_eq_Union] at hS ⊢, haveI := hSc.to_encodable, exact measure_Union_null (subtype.forall.2 hS) end⟩ lemma ae_imp_iff {p : α → Prop} {q : Prop} : (∀ᵐ x ∂μ, q → p x) ↔ (q → ∀ᵐ x ∂μ, p x) := filter.eventually_imp_distrib_left lemma ae_all_iff [encodable ι] {p : α → ι → Prop} : (∀ᵐ a ∂ μ, ∀ i, p a i) ↔ (∀ i, ∀ᵐ a ∂ μ, p a i) := eventually_countable_forall lemma ae_ball_iff {S : set ι} (hS : countable S) {p : Π (x : α) (i ∈ S), Prop} : (∀ᵐ x ∂ μ, ∀ i ∈ S, p x i ‹_›) ↔ ∀ i ∈ S, ∀ᵐ x ∂ μ, p x i ‹_› := eventually_countable_ball hS lemma ae_eq_refl (f : α → δ) : f =ᵐ[μ] f := eventually_eq.rfl lemma ae_eq_symm {f g : α → δ} (h : f =ᵐ[μ] g) : g =ᵐ[μ] f := h.symm lemma ae_eq_trans {f g h: α → δ} (h₁ : f =ᵐ[μ] g) (h₂ : g =ᵐ[μ] h) : f =ᵐ[μ] h := h₁.trans h₂ @[simp] lemma ae_eq_empty : s =ᵐ[μ] (∅ : set α) ↔ μ s = 0 := eventually_eq_empty.trans $ by simp [ae_iff] lemma ae_le_set : s ≤ᵐ[μ] t ↔ μ (s \ t) = 0 := calc s ≤ᵐ[μ] t ↔ ∀ᵐ x ∂μ, x ∈ s → x ∈ t : iff.rfl ... ↔ μ (s \ t) = 0 : by simp [ae_iff]; refl @[simp] lemma union_ae_eq_right : (s ∪ t : set α) =ᵐ[μ] t ↔ μ (s \ t) = 0 := by simp [eventually_le_antisymm_iff, ae_le_set, union_diff_right, diff_eq_empty.2 (set.subset_union_right _ _)] lemma diff_ae_eq_self : (s \ t : set α) =ᵐ[μ] s ↔ μ (s ∩ t) = 0 := by simp [eventually_le_antisymm_iff, ae_le_set, diff_diff_right, diff_diff, diff_eq_empty.2 (set.subset_union_right _ _)] lemma ae_eq_set {s t : set α} : s =ᵐ[μ] t ↔ μ (s \ t) = 0 ∧ μ (t \ s) = 0 := by simp [eventually_le_antisymm_iff, ae_le_set] /-- If `s ⊆ t` modulo a set of measure `0`, then `μ s ≤ μ t`. -/ @[mono] lemma measure_mono_ae (H : s ≤ᵐ[μ] t) : μ s ≤ μ t := calc μ s ≤ μ (s ∪ t) : measure_mono $ subset_union_left s t ... = μ (t ∪ s \ t) : by rw [union_diff_self, set.union_comm] ... ≤ μ t + μ (s \ t) : measure_union_le _ _ ... = μ t : by rw [ae_le_set.1 H, add_zero] alias measure_mono_ae ← filter.eventually_le.measure_le /-- If two sets are equal modulo a set of measure zero, then `μ s = μ t`. -/ lemma measure_congr (H : s =ᵐ[μ] t) : μ s = μ t := le_antisymm H.le.measure_le H.symm.le.measure_le lemma measure_Union [encodable β] {f : β → set α} (hn : pairwise (disjoint on f)) (h : ∀ i, measurable_set (f i)) : μ (⋃ i, f i) = ∑' i, μ (f i) := begin rw [measure_eq_extend (measurable_set.Union h), extend_Union measurable_set.empty _ measurable_set.Union _ hn h], { simp [measure_eq_extend, h] }, { exact μ.empty }, { exact μ.m_Union } end lemma measure_union (hd : disjoint s₁ s₂) (h₁ : measurable_set s₁) (h₂ : measurable_set s₂) : μ (s₁ ∪ s₂) = μ s₁ + μ s₂ := begin rw [union_eq_Union, measure_Union, tsum_fintype, fintype.sum_bool, cond, cond], exacts [pairwise_disjoint_on_bool.2 hd, λ b, bool.cases_on b h₂ h₁] end lemma measure_bUnion {s : set β} {f : β → set α} (hs : countable s) (hd : pairwise_on s (disjoint on f)) (h : ∀ b ∈ s, measurable_set (f b)) : μ (⋃ b ∈ s, f b) = ∑' p : s, μ (f p) := begin haveI := hs.to_encodable, rw bUnion_eq_Union, exact measure_Union (hd.on_injective subtype.coe_injective $ λ x, x.2) (λ x, h x x.2) end lemma measure_sUnion {S : set (set α)} (hs : countable S) (hd : pairwise_on S disjoint) (h : ∀ s ∈ S, measurable_set s) : μ (⋃₀ S) = ∑' s : S, μ s := by rw [sUnion_eq_bUnion, measure_bUnion hs hd h] lemma measure_bUnion_finset {s : finset ι} {f : ι → set α} (hd : pairwise_on ↑s (disjoint on f)) (hm : ∀ b ∈ s, measurable_set (f b)) : μ (⋃ b ∈ s, f b) = ∑ p in s, μ (f p) := begin rw [← finset.sum_attach, finset.attach_eq_univ, ← tsum_fintype], exact measure_bUnion s.countable_to_set hd hm end /-- If `s` is a countable set, then the measure of its preimage can be found as the sum of measures of the fibers `f ⁻¹' {y}`. -/ lemma tsum_measure_preimage_singleton {s : set β} (hs : countable s) {f : α → β} (hf : ∀ y ∈ s, measurable_set (f ⁻¹' {y})) : ∑' b : s, μ (f ⁻¹' {↑b}) = μ (f ⁻¹' s) := by rw [← set.bUnion_preimage_singleton, measure_bUnion hs (pairwise_on_disjoint_fiber _ _) hf] /-- If `s` is a `finset`, then the measure of its preimage can be found as the sum of measures of the fibers `f ⁻¹' {y}`. -/ lemma sum_measure_preimage_singleton (s : finset β) {f : α → β} (hf : ∀ y ∈ s, measurable_set (f ⁻¹' {y})) : ∑ b in s, μ (f ⁻¹' {b}) = μ (f ⁻¹' ↑s) := by simp only [← measure_bUnion_finset (pairwise_on_disjoint_fiber _ _) hf, finset.set_bUnion_preimage_singleton] lemma measure_diff (h : s₂ ⊆ s₁) (h₁ : measurable_set s₁) (h₂ : measurable_set s₂) (h_fin : μ s₂ < ∞) : μ (s₁ \ s₂) = μ s₁ - μ s₂ := begin refine (ennreal.add_sub_self' h_fin).symm.trans _, rw [← measure_union disjoint_diff h₂ (h₁.diff h₂), union_diff_cancel h] end lemma measure_compl (h₁ : measurable_set s) (h_fin : μ s < ∞) : μ (sᶜ) = μ univ - μ s := by { rw compl_eq_univ_diff, exact measure_diff (subset_univ s) measurable_set.univ h₁ h_fin } lemma sum_measure_le_measure_univ {s : finset ι} {t : ι → set α} (h : ∀ i ∈ s, measurable_set (t i)) (H : pairwise_on ↑s (disjoint on t)) : ∑ i in s, μ (t i) ≤ μ (univ : set α) := by { rw ← measure_bUnion_finset H h, exact measure_mono (subset_univ _) } lemma tsum_measure_le_measure_univ {s : ι → set α} (hs : ∀ i, measurable_set (s i)) (H : pairwise (disjoint on s)) : ∑' i, μ (s i) ≤ μ (univ : set α) := begin rw [ennreal.tsum_eq_supr_sum], exact supr_le (λ s, sum_measure_le_measure_univ (λ i hi, hs i) (λ i hi j hj hij, H i j hij)) end /-- Pigeonhole principle for measure spaces: if `∑' i, μ (s i) > μ univ`, then one of the intersections `s i ∩ s j` is not empty. -/ lemma exists_nonempty_inter_of_measure_univ_lt_tsum_measure (μ : measure α) {s : ι → set α} (hs : ∀ i, measurable_set (s i)) (H : μ (univ : set α) < ∑' i, μ (s i)) : ∃ i j (h : i ≠ j), (s i ∩ s j).nonempty := begin contrapose! H, apply tsum_measure_le_measure_univ hs, exact λ i j hij x hx, H i j hij ⟨x, hx⟩ end /-- Pigeonhole principle for measure spaces: if `s` is a `finset` and `∑ i in s, μ (t i) > μ univ`, then one of the intersections `t i ∩ t j` is not empty. -/ lemma exists_nonempty_inter_of_measure_univ_lt_sum_measure (μ : measure α) {s : finset ι} {t : ι → set α} (h : ∀ i ∈ s, measurable_set (t i)) (H : μ (univ : set α) < ∑ i in s, μ (t i)) : ∃ (i ∈ s) (j ∈ s) (h : i ≠ j), (t i ∩ t j).nonempty := begin contrapose! H, apply sum_measure_le_measure_univ h, exact λ i hi j hj hij x hx, H i hi j hj hij ⟨x, hx⟩ end /-- Continuity from below: the measure of the union of a directed sequence of measurable sets is the supremum of the measures. -/ lemma measure_Union_eq_supr [encodable ι] {s : ι → set α} (h : ∀ i, measurable_set (s i)) (hd : directed (⊆) s) : μ (⋃ i, s i) = ⨆ i, μ (s i) := begin by_cases hι : nonempty ι, swap, { simp only [supr_of_empty hι, Union], exact measure_empty }, resetI, refine le_antisymm _ (supr_le $ λ i, measure_mono $ subset_Union _ _), have : ∀ n, measurable_set (disjointed (λ n, ⋃ b ∈ encodable.decode2 ι n, s b) n) := measurable_set.disjointed (measurable_set.bUnion_decode2 h), rw [← encodable.Union_decode2, ← Union_disjointed, measure_Union disjoint_disjointed this, ennreal.tsum_eq_supr_nat], simp only [← measure_bUnion_finset (disjoint_disjointed.pairwise_on _) (λ n _, this n)], refine supr_le (λ n, _), refine le_trans (_ : _ ≤ μ (⋃ (k ∈ finset.range n) (i ∈ encodable.decode2 ι k), s i)) _, exact measure_mono (bUnion_subset_bUnion_right (λ k hk, disjointed_subset)), simp only [← finset.set_bUnion_option_to_finset, ← finset.set_bUnion_bUnion], generalize : (finset.range n).bUnion (λ k, (encodable.decode2 ι k).to_finset) = t, rcases hd.finset_le t with ⟨i, hi⟩, exact le_supr_of_le i (measure_mono $ bUnion_subset hi) end lemma measure_bUnion_eq_supr {s : ι → set α} {t : set ι} (ht : countable t) (h : ∀ i ∈ t, measurable_set (s i)) (hd : directed_on ((⊆) on s) t) : μ (⋃ i ∈ t, s i) = ⨆ i ∈ t, μ (s i) := begin haveI := ht.to_encodable, rw [bUnion_eq_Union, measure_Union_eq_supr (set_coe.forall'.1 h) hd.directed_coe, supr_subtype'], refl end /-- Continuity from above: the measure of the intersection of a decreasing sequence of measurable sets is the infimum of the measures. -/ lemma measure_Inter_eq_infi [encodable ι] {s : ι → set α} (h : ∀ i, measurable_set (s i)) (hd : directed (⊇) s) (hfin : ∃ i, μ (s i) < ∞) : μ (⋂ i, s i) = (⨅ i, μ (s i)) := begin rcases hfin with ⟨k, hk⟩, rw [← ennreal.sub_sub_cancel (by exact hk) (infi_le _ k), ennreal.sub_infi, ← ennreal.sub_sub_cancel (by exact hk) (measure_mono (Inter_subset _ k)), ← measure_diff (Inter_subset _ k) (h k) (measurable_set.Inter h) (lt_of_le_of_lt (measure_mono (Inter_subset _ k)) hk), diff_Inter, measure_Union_eq_supr], { congr' 1, refine le_antisymm (supr_le_supr2 $ λ i, _) (supr_le_supr $ λ i, _), { rcases hd i k with ⟨j, hji, hjk⟩, use j, rw [← measure_diff hjk (h _) (h _) ((measure_mono hjk).trans_lt hk)], exact measure_mono (diff_subset_diff_right hji) }, { rw [ennreal.sub_le_iff_le_add, ← measure_union disjoint_diff.symm ((h k).diff (h i)) (h i), set.union_comm], exact measure_mono (diff_subset_iff.1 $ subset.refl _) } }, { exact λ i, (h k).diff (h i) }, { exact hd.mono_comp _ (λ _ _, diff_subset_diff_right) } end lemma measure_eq_inter_diff (hs : measurable_set s) (ht : measurable_set t) : μ s = μ (s ∩ t) + μ (s \ t) := have hd : disjoint (s ∩ t) (s \ t) := assume a ⟨⟨_, hs⟩, _, hns⟩, hns hs , by rw [← measure_union hd (hs.inter ht) (hs.diff ht), inter_union_diff s t] lemma measure_union_add_inter (hs : measurable_set s) (ht : measurable_set t) : μ (s ∪ t) + μ (s ∩ t) = μ s + μ t := by { rw [measure_eq_inter_diff (hs.union ht) ht, set.union_inter_cancel_right, union_diff_right, measure_eq_inter_diff hs ht], ac_refl } /-- Continuity from below: the measure of the union of an increasing sequence of measurable sets is the limit of the measures. -/ lemma tendsto_measure_Union {s : ℕ → set α} (hs : ∀ n, measurable_set (s n)) (hm : monotone s) : tendsto (μ ∘ s) at_top (𝓝 (μ (⋃ n, s n))) := begin rw measure_Union_eq_supr hs (directed_of_sup hm), exact tendsto_at_top_supr (assume n m hnm, measure_mono $ hm hnm) end /-- Continuity from above: the measure of the intersection of a decreasing sequence of measurable sets is the limit of the measures. -/ lemma tendsto_measure_Inter {s : ℕ → set α} (hs : ∀ n, measurable_set (s n)) (hm : ∀ ⦃n m⦄, n ≤ m → s m ⊆ s n) (hf : ∃ i, μ (s i) < ∞) : tendsto (μ ∘ s) at_top (𝓝 (μ (⋂ n, s n))) := begin rw measure_Inter_eq_infi hs (directed_of_sup hm) hf, exact tendsto_at_top_infi (assume n m hnm, measure_mono $ hm hnm), end /-- One direction of the Borel-Cantelli lemma: if (sᵢ) is a sequence of measurable sets such that ∑ μ sᵢ exists, then the limit superior of the sᵢ is a null set. -/ lemma measure_limsup_eq_zero {s : ℕ → set α} (hs : ∀ i, measurable_set (s i)) (hs' : ∑' i, μ (s i) ≠ ∞) : μ (limsup at_top s) = 0 := begin rw limsup_eq_infi_supr_of_nat', -- We will show that both `μ (⨅ n, ⨆ i, s (i + n))` and `0` are the limit of `μ (⊔ i, s (i + n))` -- as `n` tends to infinity. For the former, we use continuity from above. refine tendsto_nhds_unique (tendsto_measure_Inter (λ i, measurable_set.Union (λ b, hs (b + i))) _ ⟨0, lt_of_le_of_lt (measure_Union_le s) (ennreal.lt_top_iff_ne_top.2 hs')⟩) _, { intros n m hnm x, simp only [set.mem_Union], exact λ ⟨i, hi⟩, ⟨i + (m - n), by simpa only [add_assoc, nat.sub_add_cancel hnm] using hi⟩ }, { -- For the latter, notice that, `μ (⨆ i, s (i + n)) ≤ ∑' s (i + n)`. Since the right hand side -- converges to `0` by hypothesis, so does the former and the proof is complete. exact (tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds (ennreal.tendsto_sum_nat_add (μ ∘ s) hs') (eventually_of_forall (by simp only [forall_const, zero_le])) (eventually_of_forall (λ i, measure_Union_le _))) } end lemma measure_if {x : β} {t : set β} {s : set α} {μ : measure α} : μ (if x ∈ t then s else ∅) = indicator t (λ _, μ s) x := by { split_ifs; simp [h] } end section outer_measure variables [ms : measurable_space α] {s t : set α} include ms /-- Obtain a measure by giving an outer measure where all sets in the σ-algebra are Carathéodory measurable. -/ def outer_measure.to_measure (m : outer_measure α) (h : ms ≤ m.caratheodory) : measure α := measure.of_measurable (λ s _, m s) m.empty (λ f hf hd, m.Union_eq_of_caratheodory (λ i, h _ (hf i)) hd) lemma le_to_outer_measure_caratheodory (μ : measure α) : ms ≤ μ.to_outer_measure.caratheodory := begin assume s hs, rw to_outer_measure_eq_induced_outer_measure, refine outer_measure.of_function_caratheodory (λ t, le_infi $ λ ht, _), rw [← measure_eq_extend (ht.inter hs), ← measure_eq_extend (ht.diff hs), ← measure_union _ (ht.inter hs) (ht.diff hs), inter_union_diff], exact le_refl _, exact λ x ⟨⟨_, h₁⟩, _, h₂⟩, h₂ h₁ end @[simp] lemma to_measure_to_outer_measure (m : outer_measure α) (h : ms ≤ m.caratheodory) : (m.to_measure h).to_outer_measure = m.trim := rfl @[simp] lemma to_measure_apply (m : outer_measure α) (h : ms ≤ m.caratheodory) {s : set α} (hs : measurable_set s) : m.to_measure h s = m s := m.trim_eq hs lemma le_to_measure_apply (m : outer_measure α) (h : ms ≤ m.caratheodory) (s : set α) : m s ≤ m.to_measure h s := m.le_trim s @[simp] lemma to_outer_measure_to_measure {μ : measure α} : μ.to_outer_measure.to_measure (le_to_outer_measure_caratheodory _) = μ := measure.ext $ λ s, μ.to_outer_measure.trim_eq end outer_measure variables [measurable_space α] [measurable_space β] [measurable_space γ] variables {μ μ₁ μ₂ μ₃ ν ν' ν₁ ν₂ : measure α} {s s' t : set α} namespace measure protected lemma caratheodory (μ : measure α) (hs : measurable_set s) : μ (t ∩ s) + μ (t \ s) = μ t := (le_to_outer_measure_caratheodory μ s hs t).symm /-! ### The `ℝ≥0∞`-module of measures -/ instance : has_zero (measure α) := ⟨{ to_outer_measure := 0, m_Union := λ f hf hd, tsum_zero.symm, trimmed := outer_measure.trim_zero }⟩ @[simp] theorem zero_to_outer_measure : (0 : measure α).to_outer_measure = 0 := rfl @[simp, norm_cast] theorem coe_zero : ⇑(0 : measure α) = 0 := rfl lemma eq_zero_of_not_nonempty (h : ¬nonempty α) (μ : measure α) : μ = 0 := ext $ λ s hs, by simp only [eq_empty_of_not_nonempty h s, measure_empty] instance : inhabited (measure α) := ⟨0⟩ instance : has_add (measure α) := ⟨λ μ₁ μ₂, { to_outer_measure := μ₁.to_outer_measure + μ₂.to_outer_measure, m_Union := λ s hs hd, show μ₁ (⋃ i, s i) + μ₂ (⋃ i, s i) = ∑' i, (μ₁ (s i) + μ₂ (s i)), by rw [ennreal.tsum_add, measure_Union hd hs, measure_Union hd hs], trimmed := by rw [outer_measure.trim_add, μ₁.trimmed, μ₂.trimmed] }⟩ @[simp] theorem add_to_outer_measure (μ₁ μ₂ : measure α) : (μ₁ + μ₂).to_outer_measure = μ₁.to_outer_measure + μ₂.to_outer_measure := rfl @[simp, norm_cast] theorem coe_add (μ₁ μ₂ : measure α) : ⇑(μ₁ + μ₂) = μ₁ + μ₂ := rfl theorem add_apply (μ₁ μ₂ : measure α) (s : set α) : (μ₁ + μ₂) s = μ₁ s + μ₂ s := rfl instance add_comm_monoid : add_comm_monoid (measure α) := to_outer_measure_injective.add_comm_monoid to_outer_measure zero_to_outer_measure add_to_outer_measure instance : has_scalar ℝ≥0∞ (measure α) := ⟨λ c μ, { to_outer_measure := c • μ.to_outer_measure, m_Union := λ s hs hd, by simp [measure_Union, *, ennreal.tsum_mul_left], trimmed := by rw [outer_measure.trim_smul, μ.trimmed] }⟩ @[simp] theorem smul_to_outer_measure (c : ℝ≥0∞) (μ : measure α) : (c • μ).to_outer_measure = c • μ.to_outer_measure := rfl @[simp, norm_cast] theorem coe_smul (c : ℝ≥0∞) (μ : measure α) : ⇑(c • μ) = c • μ := rfl theorem smul_apply (c : ℝ≥0∞) (μ : measure α) (s : set α) : (c • μ) s = c * μ s := rfl instance : semimodule ℝ≥0∞ (measure α) := injective.semimodule ℝ≥0∞ ⟨to_outer_measure, zero_to_outer_measure, add_to_outer_measure⟩ to_outer_measure_injective smul_to_outer_measure /-! ### The complete lattice of measures -/ instance : partial_order (measure α) := { le := λ m₁ m₂, ∀ s, measurable_set s → m₁ s ≤ m₂ s, le_refl := assume m s hs, le_refl _, le_trans := assume m₁ m₂ m₃ h₁ h₂ s hs, le_trans (h₁ s hs) (h₂ s hs), le_antisymm := assume m₁ m₂ h₁ h₂, ext $ assume s hs, le_antisymm (h₁ s hs) (h₂ s hs) } theorem le_iff : μ₁ ≤ μ₂ ↔ ∀ s, measurable_set s → μ₁ s ≤ μ₂ s := iff.rfl theorem to_outer_measure_le : μ₁.to_outer_measure ≤ μ₂.to_outer_measure ↔ μ₁ ≤ μ₂ := by rw [← μ₂.trimmed, outer_measure.le_trim_iff]; refl theorem le_iff' : μ₁ ≤ μ₂ ↔ ∀ s, μ₁ s ≤ μ₂ s := to_outer_measure_le.symm theorem lt_iff : μ < ν ↔ μ ≤ ν ∧ ∃ s, measurable_set s ∧ μ s < ν s := lt_iff_le_not_le.trans $ and_congr iff.rfl $ by simp only [le_iff, not_forall, not_le, exists_prop] theorem lt_iff' : μ < ν ↔ μ ≤ ν ∧ ∃ s, μ s < ν s := lt_iff_le_not_le.trans $ and_congr iff.rfl $ by simp only [le_iff', not_forall, not_le] -- TODO: add typeclasses for `∀ c, monotone ((*) c)` and `∀ c, monotone ((+) c)` protected lemma add_le_add_left (ν : measure α) (hμ : μ₁ ≤ μ₂) : ν + μ₁ ≤ ν + μ₂ := λ s hs, add_le_add_left (hμ s hs) _ protected lemma add_le_add_right (hμ : μ₁ ≤ μ₂) (ν : measure α) : μ₁ + ν ≤ μ₂ + ν := λ s hs, add_le_add_right (hμ s hs) _ protected lemma add_le_add (hμ : μ₁ ≤ μ₂) (hν : ν₁ ≤ ν₂) : μ₁ + ν₁ ≤ μ₂ + ν₂ := λ s hs, add_le_add (hμ s hs) (hν s hs) protected lemma le_add_left (h : μ ≤ ν) : μ ≤ ν' + ν := λ s hs, le_add_left (h s hs) protected lemma le_add_right (h : μ ≤ ν) : μ ≤ ν + ν' := λ s hs, le_add_right (h s hs) section Inf variables {m : set (measure α)} lemma Inf_caratheodory (s : set α) (hs : measurable_set s) : (Inf (to_outer_measure '' m)).caratheodory.measurable_set' s := begin rw [outer_measure.Inf_eq_bounded_by_Inf_gen], refine outer_measure.bounded_by_caratheodory (λ t, _), simp only [outer_measure.Inf_gen, le_infi_iff, ball_image_iff, coe_to_outer_measure, measure_eq_infi t], intros μ hμ u htu hu, have hm : ∀ {s t}, s ⊆ t → outer_measure.Inf_gen (to_outer_measure '' m) s ≤ μ t, { intros s t hst, rw [outer_measure.Inf_gen_def], refine infi_le_of_le (μ.to_outer_measure) (infi_le_of_le (mem_image_of_mem _ hμ) _), rw [to_outer_measure_apply], refine measure_mono hst }, rw [measure_eq_inter_diff hu hs], refine add_le_add (hm $ inter_subset_inter_left _ htu) (hm $ diff_subset_diff_left htu) end instance : has_Inf (measure α) := ⟨λ m, (Inf (to_outer_measure '' m)).to_measure $ Inf_caratheodory⟩ lemma Inf_apply (hs : measurable_set s) : Inf m s = Inf (to_outer_measure '' m) s := to_measure_apply _ _ hs private lemma measure_Inf_le (h : μ ∈ m) : Inf m ≤ μ := have Inf (to_outer_measure '' m) ≤ μ.to_outer_measure := Inf_le (mem_image_of_mem _ h), assume s hs, by rw [Inf_apply hs, ← to_outer_measure_apply]; exact this s private lemma measure_le_Inf (h : ∀ μ' ∈ m, μ ≤ μ') : μ ≤ Inf m := have μ.to_outer_measure ≤ Inf (to_outer_measure '' m) := le_Inf $ ball_image_of_ball $ assume μ hμ, to_outer_measure_le.2 $ h _ hμ, assume s hs, by rw [Inf_apply hs, ← to_outer_measure_apply]; exact this s instance : complete_lattice (measure α) := { bot := 0, bot_le := assume a s hs, by exact bot_le, /- Adding an explicit `top` makes `leanchecker` fail, see lean#364, disable for now top := (⊤ : outer_measure α).to_measure (by rw [outer_measure.top_caratheodory]; exact le_top), le_top := assume a s hs, by cases s.eq_empty_or_nonempty with h h; simp [h, to_measure_apply ⊤ _ hs, outer_measure.top_apply], -/ .. complete_lattice_of_Inf (measure α) (λ ms, ⟨λ _, measure_Inf_le, λ _, measure_le_Inf⟩) } end Inf protected lemma zero_le (μ : measure α) : 0 ≤ μ := bot_le lemma nonpos_iff_eq_zero' : μ ≤ 0 ↔ μ = 0 := μ.zero_le.le_iff_eq @[simp] lemma measure_univ_eq_zero : μ univ = 0 ↔ μ = 0 := ⟨λ h, bot_unique $ λ s hs, trans_rel_left (≤) (measure_mono (subset_univ s)) h, λ h, h.symm ▸ rfl⟩ /-! ### Pushforward and pullback -/ /-- Lift a linear map between `outer_measure` spaces such that for each measure `μ` every measurable set is caratheodory-measurable w.r.t. `f μ` to a linear map between `measure` spaces. -/ def lift_linear (f : outer_measure α →ₗ[ℝ≥0∞] outer_measure β) (hf : ∀ μ : measure α, ‹_› ≤ (f μ.to_outer_measure).caratheodory) : measure α →ₗ[ℝ≥0∞] measure β := { to_fun := λ μ, (f μ.to_outer_measure).to_measure (hf μ), map_add' := λ μ₁ μ₂, ext $ λ s hs, by simp [hs], map_smul' := λ c μ, ext $ λ s hs, by simp [hs] } @[simp] lemma lift_linear_apply {f : outer_measure α →ₗ[ℝ≥0∞] outer_measure β} (hf) {s : set β} (hs : measurable_set s) : lift_linear f hf μ s = f μ.to_outer_measure s := to_measure_apply _ _ hs lemma le_lift_linear_apply {f : outer_measure α →ₗ[ℝ≥0∞] outer_measure β} (hf) (s : set β) : f μ.to_outer_measure s ≤ lift_linear f hf μ s := le_to_measure_apply _ _ s /-- The pushforward of a measure. It is defined to be `0` if `f` is not a measurable function. -/ def map (f : α → β) : measure α →ₗ[ℝ≥0∞] measure β := if hf : measurable f then lift_linear (outer_measure.map f) $ λ μ s hs t, le_to_outer_measure_caratheodory μ _ (hf hs) (f ⁻¹' t) else 0 /-- We can evaluate the pushforward on measurable sets. For non-measurable sets, see `measure_theory.measure.le_map_apply` and `measurable_equiv.map_apply`. -/ @[simp] theorem map_apply {f : α → β} (hf : measurable f) {s : set β} (hs : measurable_set s) : map f μ s = μ (f ⁻¹' s) := by simp [map, dif_pos hf, hs] @[simp] lemma map_id : map id μ = μ := ext $ λ s, map_apply measurable_id lemma map_map {g : β → γ} {f : α → β} (hg : measurable g) (hf : measurable f) : map g (map f μ) = map (g ∘ f) μ := ext $ λ s hs, by simp [hf, hg, hs, hg hs, hg.comp hf, ← preimage_comp] lemma map_mono {f : α → β} (hf : measurable f) (h : μ ≤ ν) : map f μ ≤ map f ν := λ s hs, by simp [hf, hs, h _ (hf hs)] /-- Even if `s` is not measurable, we can bound `map f μ s` from below. See also `measurable_equiv.map_apply`. -/ theorem le_map_apply {f : α → β} (hf : measurable f) (s : set β) : μ (f ⁻¹' s) ≤ map f μ s := begin rw [measure_eq_infi' (map f μ)], refine le_infi _, rintro ⟨t, hst, ht⟩, convert measure_mono (preimage_mono hst), exact map_apply hf ht end /-- Even if `s` is not measurable, `map f μ s = 0` implies that `μ (f ⁻¹' s) = 0`. -/ lemma preimage_null_of_map_null {f : α → β} (hf : measurable f) {s : set β} (hs : map f μ s = 0) : μ (f ⁻¹' s) = 0 := nonpos_iff_eq_zero.mp $ (le_map_apply hf s).trans_eq hs /-- Pullback of a `measure`. If `f` sends each `measurable` set to a `measurable` set, then for each measurable set `s` we have `comap f μ s = μ (f '' s)`. -/ def comap (f : α → β) : measure β →ₗ[ℝ≥0∞] measure α := if hf : injective f ∧ ∀ s, measurable_set s → measurable_set (f '' s) then lift_linear (outer_measure.comap f) $ λ μ s hs t, begin simp only [coe_to_outer_measure, outer_measure.comap_apply, ← image_inter hf.1, image_diff hf.1], apply le_to_outer_measure_caratheodory, exact hf.2 s hs end else 0 lemma comap_apply (f : α → β) (hfi : injective f) (hf : ∀ s, measurable_set s → measurable_set (f '' s)) (μ : measure β) (hs : measurable_set s) : comap f μ s = μ (f '' s) := begin rw [comap, dif_pos, lift_linear_apply _ hs, outer_measure.comap_apply, coe_to_outer_measure], exact ⟨hfi, hf⟩ end /-! ### Restricting a measure -/ /-- Restrict a measure `μ` to a set `s` as an `ℝ≥0∞`-linear map. -/ def restrictₗ (s : set α) : measure α →ₗ[ℝ≥0∞] measure α := lift_linear (outer_measure.restrict s) $ λ μ s' hs' t, begin suffices : μ (s ∩ t) = μ (s ∩ t ∩ s') + μ (s ∩ t \ s'), { simpa [← set.inter_assoc, set.inter_comm _ s, ← inter_diff_assoc] }, exact le_to_outer_measure_caratheodory _ _ hs' _, end /-- Restrict a measure `μ` to a set `s`. -/ def restrict (μ : measure α) (s : set α) : measure α := restrictₗ s μ @[simp] lemma restrictₗ_apply (s : set α) (μ : measure α) : restrictₗ s μ = μ.restrict s := rfl /-- If `t` is a measurable set, then the measure of `t` with respect to the restriction of the measure to `s` equals the outer measure of `t ∩ s`. An alternate version requiring that `s` be measurable instead of `t` exists as `measure.restrict_apply'`. -/ @[simp] lemma restrict_apply (ht : measurable_set t) : μ.restrict s t = μ (t ∩ s) := by simp [← restrictₗ_apply, restrictₗ, ht] lemma restrict_eq_self (h_meas_t : measurable_set t) (h : t ⊆ s) : μ.restrict s t = μ t := by rw [restrict_apply h_meas_t, subset_iff_inter_eq_left.1 h] lemma restrict_apply_self (μ:measure α) (h_meas_s : measurable_set s) : (μ.restrict s) s = μ s := (restrict_eq_self h_meas_s (set.subset.refl _)) lemma restrict_apply_univ (s : set α) : μ.restrict s univ = μ s := by rw [restrict_apply measurable_set.univ, set.univ_inter] lemma le_restrict_apply (s t : set α) : μ (t ∩ s) ≤ μ.restrict s t := by { rw [restrict, restrictₗ], convert le_lift_linear_apply _ t, simp } @[simp] lemma restrict_add (μ ν : measure α) (s : set α) : (μ + ν).restrict s = μ.restrict s + ν.restrict s := (restrictₗ s).map_add μ ν @[simp] lemma restrict_zero (s : set α) : (0 : measure α).restrict s = 0 := (restrictₗ s).map_zero @[simp] lemma restrict_smul (c : ℝ≥0∞) (μ : measure α) (s : set α) : (c • μ).restrict s = c • μ.restrict s := (restrictₗ s).map_smul c μ @[simp] lemma restrict_restrict (hs : measurable_set s) : (μ.restrict t).restrict s = μ.restrict (s ∩ t) := ext $ λ u hu, by simp [*, set.inter_assoc] lemma restrict_apply_eq_zero (ht : measurable_set t) : μ.restrict s t = 0 ↔ μ (t ∩ s) = 0 := by rw [restrict_apply ht] lemma measure_inter_eq_zero_of_restrict (h : μ.restrict s t = 0) : μ (t ∩ s) = 0 := nonpos_iff_eq_zero.1 (h ▸ le_restrict_apply _ _) lemma restrict_apply_eq_zero' (hs : measurable_set s) : μ.restrict s t = 0 ↔ μ (t ∩ s) = 0 := begin refine ⟨measure_inter_eq_zero_of_restrict, λ h, _⟩, rcases exists_measurable_superset_of_null h with ⟨t', htt', ht', ht'0⟩, apply measure_mono_null ((inter_subset _ _ _).1 htt'), rw [restrict_apply (hs.compl.union ht'), union_inter_distrib_right, compl_inter_self, set.empty_union], exact measure_mono_null (inter_subset_left _ _) ht'0 end @[simp] lemma restrict_eq_zero : μ.restrict s = 0 ↔ μ s = 0 := by rw [← measure_univ_eq_zero, restrict_apply_univ] @[simp] lemma restrict_empty : μ.restrict ∅ = 0 := ext $ λ s hs, by simp [hs] @[simp] lemma restrict_univ : μ.restrict univ = μ := ext $ λ s hs, by simp [hs] lemma restrict_eq_self_of_measurable_subset (ht : measurable_set t) (t_subset : t ⊆ s) : μ.restrict s t = μ t := by rw [measure.restrict_apply ht, set.inter_eq_self_of_subset_left t_subset] lemma restrict_union_apply (h : disjoint (t ∩ s) (t ∩ s')) (hs : measurable_set s) (hs' : measurable_set s') (ht : measurable_set t) : μ.restrict (s ∪ s') t = μ.restrict s t + μ.restrict s' t := begin simp only [restrict_apply, ht, set.inter_union_distrib_left], exact measure_union h (ht.inter hs) (ht.inter hs'), end lemma restrict_union (h : disjoint s t) (hs : measurable_set s) (ht : measurable_set t) : μ.restrict (s ∪ t) = μ.restrict s + μ.restrict t := ext $ λ t' ht', restrict_union_apply (h.mono inf_le_right inf_le_right) hs ht ht' lemma restrict_union_add_inter (hs : measurable_set s) (ht : measurable_set t) : μ.restrict (s ∪ t) + μ.restrict (s ∩ t) = μ.restrict s + μ.restrict t := begin ext1 u hu, simp only [add_apply, restrict_apply hu, inter_union_distrib_left], convert measure_union_add_inter (hu.inter hs) (hu.inter ht) using 3, rw [set.inter_left_comm (u ∩ s), set.inter_assoc, ← set.inter_assoc u u, set.inter_self] end @[simp] lemma restrict_add_restrict_compl (hs : measurable_set s) : μ.restrict s + μ.restrict sᶜ = μ := by rw [← restrict_union disjoint_compl_right hs hs.compl, union_compl_self, restrict_univ] @[simp] lemma restrict_compl_add_restrict (hs : measurable_set s) : μ.restrict sᶜ + μ.restrict s = μ := by rw [add_comm, restrict_add_restrict_compl hs] lemma restrict_union_le (s s' : set α) : μ.restrict (s ∪ s') ≤ μ.restrict s + μ.restrict s' := begin intros t ht, suffices : μ (t ∩ s ∪ t ∩ s') ≤ μ (t ∩ s) + μ (t ∩ s'), by simpa [ht, inter_union_distrib_left], apply measure_union_le end lemma restrict_Union_apply [encodable ι] {s : ι → set α} (hd : pairwise (disjoint on s)) (hm : ∀ i, measurable_set (s i)) {t : set α} (ht : measurable_set t) : μ.restrict (⋃ i, s i) t = ∑' i, μ.restrict (s i) t := begin simp only [restrict_apply, ht, inter_Union], exact measure_Union (λ i j hij, (hd i j hij).mono inf_le_right inf_le_right) (λ i, ht.inter (hm i)) end lemma restrict_Union_apply_eq_supr [encodable ι] {s : ι → set α} (hm : ∀ i, measurable_set (s i)) (hd : directed (⊆) s) {t : set α} (ht : measurable_set t) : μ.restrict (⋃ i, s i) t = ⨆ i, μ.restrict (s i) t := begin simp only [restrict_apply ht, inter_Union], rw [measure_Union_eq_supr], exacts [λ i, ht.inter (hm i), hd.mono_comp _ (λ s₁ s₂, inter_subset_inter_right _)] end lemma restrict_map {f : α → β} (hf : measurable f) {s : set β} (hs : measurable_set s) : (map f μ).restrict s = map f (μ.restrict $ f ⁻¹' s) := ext $ λ t ht, by simp [*, hf ht] lemma map_comap_subtype_coe (hs : measurable_set s) : (map (coe : s → α)).comp (comap coe) = restrictₗ s := linear_map.ext $ λ μ, ext $ λ t ht, by rw [restrictₗ_apply, restrict_apply ht, linear_map.comp_apply, map_apply measurable_subtype_coe ht, comap_apply (coe : s → α) subtype.val_injective (λ _, hs.subtype_image) _ (measurable_subtype_coe ht), subtype.image_preimage_coe] /-- Restriction of a measure to a subset is monotone both in set and in measure. -/ @[mono] lemma restrict_mono ⦃s s' : set α⦄ (hs : s ⊆ s') ⦃μ ν : measure α⦄ (hμν : μ ≤ ν) : μ.restrict s ≤ ν.restrict s' := assume t ht, calc μ.restrict s t = μ (t ∩ s) : restrict_apply ht ... ≤ μ (t ∩ s') : measure_mono $ inter_subset_inter_right _ hs ... ≤ ν (t ∩ s') : le_iff'.1 hμν (t ∩ s') ... = ν.restrict s' t : (restrict_apply ht).symm lemma restrict_le_self : μ.restrict s ≤ μ := assume t ht, calc μ.restrict s t = μ (t ∩ s) : restrict_apply ht ... ≤ μ t : measure_mono $ inter_subset_left t s lemma restrict_congr_meas (hs : measurable_set s) : μ.restrict s = ν.restrict s ↔ ∀ t ⊆ s, measurable_set t → μ t = ν t := ⟨λ H t hts ht, by rw [← inter_eq_self_of_subset_left hts, ← restrict_apply ht, H, restrict_apply ht], λ H, ext $ λ t ht, by rw [restrict_apply ht, restrict_apply ht, H _ (inter_subset_right _ _) (ht.inter hs)]⟩ lemma restrict_congr_mono (hs : s ⊆ t) (hm : measurable_set s) (h : μ.restrict t = ν.restrict t) : μ.restrict s = ν.restrict s := by rw [← inter_eq_self_of_subset_left hs, ← restrict_restrict hm, h, restrict_restrict hm] /-- If two measures agree on all measurable subsets of `s` and `t`, then they agree on all measurable subsets of `s ∪ t`. -/ lemma restrict_union_congr (hsm : measurable_set s) (htm : measurable_set t) : μ.restrict (s ∪ t) = ν.restrict (s ∪ t) ↔ μ.restrict s = ν.restrict s ∧ μ.restrict t = ν.restrict t := begin refine ⟨λ h, ⟨restrict_congr_mono (subset_union_left _ _) hsm h, restrict_congr_mono (subset_union_right _ _) htm h⟩, _⟩, simp only [restrict_congr_meas, hsm, htm, hsm.union htm], rintros ⟨hs, ht⟩ u hu hum, rw [measure_eq_inter_diff hum hsm, measure_eq_inter_diff hum hsm, hs _ (inter_subset_right _ _) (hum.inter hsm), ht _ (diff_subset_iff.2 hu) (hum.diff hsm)] end lemma restrict_finset_bUnion_congr {s : finset ι} {t : ι → set α} (htm : ∀ i ∈ s, measurable_set (t i)) : μ.restrict (⋃ i ∈ s, t i) = ν.restrict (⋃ i ∈ s, t i) ↔ ∀ i ∈ s, μ.restrict (t i) = ν.restrict (t i) := begin induction s using finset.induction_on with i s hi hs, { simp }, simp only [finset.mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at htm ⊢, simp only [finset.set_bUnion_insert, ← hs htm.2], exact restrict_union_congr htm.1 (s.measurable_set_bUnion htm.2) end lemma restrict_Union_congr [encodable ι] {s : ι → set α} (hm : ∀ i, measurable_set (s i)) : μ.restrict (⋃ i, s i) = ν.restrict (⋃ i, s i) ↔ ∀ i, μ.restrict (s i) = ν.restrict (s i) := begin refine ⟨λ h i, restrict_congr_mono (subset_Union _ _) (hm i) h, λ h, _⟩, ext1 t ht, have M : ∀ t : finset ι, measurable_set (⋃ i ∈ t, s i) := λ t, t.measurable_set_bUnion (λ i _, hm i), have D : directed (⊆) (λ t : finset ι, ⋃ i ∈ t, s i) := directed_of_sup (λ t₁ t₂ ht, bUnion_subset_bUnion_left ht), rw [Union_eq_Union_finset], simp only [restrict_Union_apply_eq_supr M D ht, (restrict_finset_bUnion_congr (λ i hi, hm i)).2 (λ i hi, h i)], end lemma restrict_bUnion_congr {s : set ι} {t : ι → set α} (hc : countable s) (htm : ∀ i ∈ s, measurable_set (t i)) : μ.restrict (⋃ i ∈ s, t i) = ν.restrict (⋃ i ∈ s, t i) ↔ ∀ i ∈ s, μ.restrict (t i) = ν.restrict (t i) := begin simp only [bUnion_eq_Union, set_coe.forall'] at htm ⊢, haveI := hc.to_encodable, exact restrict_Union_congr htm end lemma restrict_sUnion_congr {S : set (set α)} (hc : countable S) (hm : ∀ s ∈ S, measurable_set s) : μ.restrict (⋃₀ S) = ν.restrict (⋃₀ S) ↔ ∀ s ∈ S, μ.restrict s = ν.restrict s := by rw [sUnion_eq_bUnion, restrict_bUnion_congr hc hm] /-- This lemma shows that `restrict` and `to_outer_measure` commute. Note that the LHS has a restrict on measures and the RHS has a restrict on outer measures. -/ lemma restrict_to_outer_measure_eq_to_outer_measure_restrict (h : measurable_set s) : (μ.restrict s).to_outer_measure = outer_measure.restrict s μ.to_outer_measure := by simp_rw [restrict, restrictₗ, lift_linear, linear_map.coe_mk, to_measure_to_outer_measure, outer_measure.restrict_trim h, μ.trimmed] /-- This lemma shows that `Inf` and `restrict` commute for measures. -/ lemma restrict_Inf_eq_Inf_restrict {m : set (measure α)} (hm : m.nonempty) (ht : measurable_set t) : (Inf m).restrict t = Inf ((λ μ : measure α, μ.restrict t) '' m) := begin ext1 s hs, simp_rw [Inf_apply hs, restrict_apply hs, Inf_apply (measurable_set.inter hs ht), set.image_image, restrict_to_outer_measure_eq_to_outer_measure_restrict ht, ← set.image_image _ to_outer_measure, ← outer_measure.restrict_Inf_eq_Inf_restrict _ (hm.image _), outer_measure.restrict_apply] end /-- If `s` is a measurable set, then the outer measure of `t` with respect to the restriction of the measure to `s` equals the outer measure of `t ∩ s`. This is an alternate version of `measure.restrict_apply`, requiring that `s` is measurable instead of `t`. -/ lemma restrict_apply' (hs : measurable_set s) : μ.restrict s t = μ (t ∩ s) := by rw [← coe_to_outer_measure, measure.restrict_to_outer_measure_eq_to_outer_measure_restrict hs, outer_measure.restrict_apply s t _, coe_to_outer_measure] lemma restrict_eq_self_of_subset_of_measurable (hs : measurable_set s) (t_subset : t ⊆ s) : μ.restrict s t = μ t := by rw [restrict_apply' hs, set.inter_eq_self_of_subset_left t_subset] /-! ### Extensionality results -/ /-- Two measures are equal if they have equal restrictions on a spanning collection of sets (formulated using `Union`). -/ lemma ext_iff_of_Union_eq_univ [encodable ι] {s : ι → set α} (hm : ∀ i, measurable_set (s i)) (hs : (⋃ i, s i) = univ) : μ = ν ↔ ∀ i, μ.restrict (s i) = ν.restrict (s i) := by rw [← restrict_Union_congr hm, hs, restrict_univ, restrict_univ] alias ext_iff_of_Union_eq_univ ↔ _ measure_theory.measure.ext_of_Union_eq_univ /-- Two measures are equal if they have equal restrictions on a spanning collection of sets (formulated using `bUnion`). -/ lemma ext_iff_of_bUnion_eq_univ {S : set ι} {s : ι → set α} (hc : countable S) (hm : ∀ i ∈ S, measurable_set (s i)) (hs : (⋃ i ∈ S, s i) = univ) : μ = ν ↔ ∀ i ∈ S, μ.restrict (s i) = ν.restrict (s i) := by rw [← restrict_bUnion_congr hc hm, hs, restrict_univ, restrict_univ] alias ext_iff_of_bUnion_eq_univ ↔ _ measure_theory.measure.ext_of_bUnion_eq_univ /-- Two measures are equal if they have equal restrictions on a spanning collection of sets (formulated using `sUnion`). -/ lemma ext_iff_of_sUnion_eq_univ {S : set (set α)} (hc : countable S) (hm : ∀ s ∈ S, measurable_set s) (hs : (⋃₀ S) = univ) : μ = ν ↔ ∀ s ∈ S, μ.restrict s = ν.restrict s := ext_iff_of_bUnion_eq_univ hc hm $ by rwa ← sUnion_eq_bUnion alias ext_iff_of_sUnion_eq_univ ↔ _ measure_theory.measure.ext_of_sUnion_eq_univ lemma ext_of_generate_from_of_cover {S T : set (set α)} (h_gen : ‹_› = generate_from S) (hc : countable T) (h_inter : is_pi_system S) (hm : ∀ t ∈ T, measurable_set t) (hU : ⋃₀ T = univ) (htop : ∀ t ∈ T, μ t < ∞) (ST_eq : ∀ (t ∈ T) (s ∈ S), μ (s ∩ t) = ν (s ∩ t)) (T_eq : ∀ t ∈ T, μ t = ν t) : μ = ν := begin refine ext_of_sUnion_eq_univ hc hm hU (λ t ht, _), ext1 u hu, simp only [restrict_apply hu], refine induction_on_inter h_gen h_inter _ (ST_eq t ht) _ _ hu, { simp only [set.empty_inter, measure_empty] }, { intros v hv hvt, have := T_eq t ht, rw [set.inter_comm] at hvt ⊢, rwa [measure_eq_inter_diff (hm _ ht) hv, measure_eq_inter_diff (hm _ ht) hv, ← hvt, ennreal.add_right_inj] at this, exact (measure_mono $ set.inter_subset_left _ _).trans_lt (htop t ht) }, { intros f hfd hfm h_eq, have : pairwise (disjoint on λ n, f n ∩ t) := λ m n hmn, (hfd m n hmn).mono (inter_subset_left _ _) (inter_subset_left _ _), simp only [Union_inter, measure_Union this (λ n, (hfm n).inter (hm t ht)), h_eq] } end /-- Two measures are equal if they are equal on the π-system generating the σ-algebra, and they are both finite on a increasing spanning sequence of sets in the π-system. This lemma is formulated using `sUnion`. -/ lemma ext_of_generate_from_of_cover_subset {S T : set (set α)} (h_gen : ‹_› = generate_from S) (h_inter : is_pi_system S) (h_sub : T ⊆ S) (hc : countable T) (hU : ⋃₀ T = univ) (htop : ∀ s ∈ T, μ s < ∞) (h_eq : ∀ s ∈ S, μ s = ν s) : μ = ν := begin refine ext_of_generate_from_of_cover h_gen hc h_inter _ hU htop _ (λ t ht, h_eq t (h_sub ht)), { intros t ht, rw [h_gen], exact generate_measurable.basic _ (h_sub ht) }, { intros t ht s hs, cases (s ∩ t).eq_empty_or_nonempty with H H, { simp only [H, measure_empty] }, { exact h_eq _ (h_inter _ _ hs (h_sub ht) H) } } end /-- Two measures are equal if they are equal on the π-system generating the σ-algebra, and they are both finite on a increasing spanning sequence of sets in the π-system. This lemma is formulated using `Union`. `finite_spanning_sets_in.ext` is a reformulation of this lemma. -/ lemma ext_of_generate_from_of_Union (C : set (set α)) (B : ℕ → set α) (hA : ‹_› = generate_from C) (hC : is_pi_system C) (h1B : (⋃ i, B i) = univ) (h2B : ∀ i, B i ∈ C) (hμB : ∀ i, μ (B i) < ∞) (h_eq : ∀ s ∈ C, μ s = ν s) : μ = ν := begin refine ext_of_generate_from_of_cover_subset hA hC _ (countable_range B) h1B _ h_eq, { rintro _ ⟨i, rfl⟩, apply h2B }, { rintro _ ⟨i, rfl⟩, apply hμB } end /-- The dirac measure. -/ def dirac (a : α) : measure α := (outer_measure.dirac a).to_measure (by simp) lemma le_dirac_apply {a} : s.indicator 1 a ≤ dirac a s := outer_measure.dirac_apply a s ▸ le_to_measure_apply _ _ _ @[simp] lemma dirac_apply' (a : α) (hs : measurable_set s) : dirac a s = s.indicator 1 a := to_measure_apply _ _ hs @[simp] lemma dirac_apply_of_mem {a : α} (h : a ∈ s) : dirac a s = 1 := begin have : ∀ t : set α, a ∈ t → t.indicator (1 : α → ℝ≥0∞) a = 1, from λ t ht, indicator_of_mem ht 1, refine le_antisymm (this univ trivial ▸ _) (this s h ▸ le_dirac_apply), rw [← dirac_apply' a measurable_set.univ], exact measure_mono (subset_univ s) end @[simp] lemma dirac_apply [measurable_singleton_class α] (a : α) (s : set α) : dirac a s = s.indicator 1 a := begin by_cases h : a ∈ s, by rw [dirac_apply_of_mem h, indicator_of_mem h, pi.one_apply], rw [indicator_of_not_mem h, ← nonpos_iff_eq_zero], calc dirac a s ≤ dirac a {a}ᶜ : measure_mono (subset_compl_comm.1 $ singleton_subset_iff.2 h) ... = 0 : by simp [dirac_apply' _ (measurable_set_singleton _).compl] end lemma map_dirac {f : α → β} (hf : measurable f) (a : α) : map f (dirac a) = dirac (f a) := ext $ assume s hs, by simp [hs, map_apply hf hs, hf hs, indicator_apply] /-- Sum of an indexed family of measures. -/ def sum (f : ι → measure α) : measure α := (outer_measure.sum (λ i, (f i).to_outer_measure)).to_measure $ le_trans (by exact le_infi (λ i, le_to_outer_measure_caratheodory _)) (outer_measure.le_sum_caratheodory _) lemma le_sum_apply (f : ι → measure α) (s : set α) : (∑' i, f i s) ≤ sum f s := le_to_measure_apply _ _ _ @[simp] lemma sum_apply (f : ι → measure α) {s : set α} (hs : measurable_set s) : sum f s = ∑' i, f i s := to_measure_apply _ _ hs lemma le_sum (μ : ι → measure α) (i : ι) : μ i ≤ sum μ := λ s hs, by simp only [sum_apply μ hs, ennreal.le_tsum i] lemma restrict_Union [encodable ι] {s : ι → set α} (hd : pairwise (disjoint on s)) (hm : ∀ i, measurable_set (s i)) : μ.restrict (⋃ i, s i) = sum (λ i, μ.restrict (s i)) := ext $ λ t ht, by simp only [sum_apply _ ht, restrict_Union_apply hd hm ht] lemma restrict_Union_le [encodable ι] {s : ι → set α} : μ.restrict (⋃ i, s i) ≤ sum (λ i, μ.restrict (s i)) := begin intros t ht, suffices : μ (⋃ i, t ∩ s i) ≤ ∑' i, μ (t ∩ s i), by simpa [ht, inter_Union], apply measure_Union_le end @[simp] lemma sum_bool (f : bool → measure α) : sum f = f tt + f ff := ext $ λ s hs, by simp [hs, tsum_fintype] @[simp] lemma sum_cond (μ ν : measure α) : sum (λ b, cond b μ ν) = μ + ν := sum_bool _ @[simp] lemma restrict_sum (μ : ι → measure α) {s : set α} (hs : measurable_set s) : (sum μ).restrict s = sum (λ i, (μ i).restrict s) := ext $ λ t ht, by simp only [sum_apply, restrict_apply, ht, ht.inter hs] /-- Counting measure on any measurable space. -/ def count : measure α := sum dirac lemma le_count_apply : (∑' i : s, 1 : ℝ≥0∞) ≤ count s := calc (∑' i : s, 1 : ℝ≥0∞) = ∑' i, indicator s 1 i : tsum_subtype s 1 ... ≤ ∑' i, dirac i s : ennreal.tsum_le_tsum $ λ x, le_dirac_apply ... ≤ count s : le_sum_apply _ _ lemma count_apply (hs : measurable_set s) : count s = ∑' i : s, 1 := by simp only [count, sum_apply, hs, dirac_apply', ← tsum_subtype s 1, pi.one_apply] @[simp] lemma count_apply_finset [measurable_singleton_class α] (s : finset α) : count (↑s : set α) = s.card := calc count (↑s : set α) = ∑' i : (↑s : set α), 1 : count_apply s.measurable_set ... = ∑ i in s, 1 : s.tsum_subtype 1 ... = s.card : by simp lemma count_apply_finite [measurable_singleton_class α] (s : set α) (hs : finite s) : count s = hs.to_finset.card := by rw [← count_apply_finset, finite.coe_to_finset] /-- `count` measure evaluates to infinity at infinite sets. -/ lemma count_apply_infinite (hs : s.infinite) : count s = ∞ := begin refine top_unique (le_of_tendsto' ennreal.tendsto_nat_nhds_top $ λ n, _), rcases hs.exists_subset_card_eq n with ⟨t, ht, rfl⟩, calc (t.card : ℝ≥0∞) = ∑ i in t, 1 : by simp ... = ∑' i : (t : set α), 1 : (t.tsum_subtype 1).symm ... ≤ count (t : set α) : le_count_apply ... ≤ count s : measure_mono ht end @[simp] lemma count_apply_eq_top [measurable_singleton_class α] : count s = ∞ ↔ s.infinite := begin by_cases hs : s.finite, { simp [set.infinite, hs, count_apply_finite] }, { change s.infinite at hs, simp [hs, count_apply_infinite] } end @[simp] lemma count_apply_lt_top [measurable_singleton_class α] : count s < ∞ ↔ s.finite := calc count s < ∞ ↔ count s ≠ ∞ : lt_top_iff_ne_top ... ↔ ¬s.infinite : not_congr count_apply_eq_top ... ↔ s.finite : not_not /-! ### Absolute continuity -/ /-- We say that `μ` is absolutely continuous with respect to `ν`, or that `μ` is dominated by `ν`, if `ν(A) = 0` implies that `μ(A) = 0`. -/ def absolutely_continuous (μ ν : measure α) : Prop := ∀ ⦃s : set α⦄, ν s = 0 → μ s = 0 infix ` ≪ `:50 := absolutely_continuous lemma absolutely_continuous.mk (h : ∀ ⦃s : set α⦄, measurable_set s → ν s = 0 → μ s = 0) : μ ≪ ν := begin intros s hs, rcases exists_measurable_superset_of_null hs with ⟨t, h1t, h2t, h3t⟩, exact measure_mono_null h1t (h h2t h3t), end @[refl] lemma absolutely_continuous.refl (μ : measure α) : μ ≪ μ := λ s hs, hs lemma absolutely_continuous.rfl : μ ≪ μ := λ s hs, hs lemma absolutely_continuous_of_eq (h : μ = ν) : μ ≪ ν := by rw h alias absolutely_continuous_of_eq ← eq.absolutely_continuous @[trans] lemma absolutely_continuous.trans (h1 : μ₁ ≪ μ₂) (h2 : μ₂ ≪ μ₃) : μ₁ ≪ μ₃ := λ s hs, h1 $ h2 hs /-- The filter of sets `s` such that `sᶜ` has finite measure. -/ def cofinite (μ : measure α) : filter α := { sets := {s | μ sᶜ < ∞}, univ_sets := by simp, inter_sets := λ s t hs ht, by { simp only [compl_inter, mem_set_of_eq], calc μ (sᶜ ∪ tᶜ) ≤ μ sᶜ + μ tᶜ : measure_union_le _ _ ... < ∞ : ennreal.add_lt_top.2 ⟨hs, ht⟩ }, sets_of_superset := λ s t hs hst, lt_of_le_of_lt (measure_mono $ compl_subset_compl.2 hst) hs } lemma mem_cofinite : s ∈ μ.cofinite ↔ μ sᶜ < ∞ := iff.rfl lemma compl_mem_cofinite : sᶜ ∈ μ.cofinite ↔ μ s < ∞ := by rw [mem_cofinite, compl_compl] lemma eventually_cofinite {p : α → Prop} : (∀ᶠ x in μ.cofinite, p x) ↔ μ {x | ¬p x} < ∞ := iff.rfl end measure open measure @[simp] lemma ae_eq_bot : μ.ae = ⊥ ↔ μ = 0 := by rw [← empty_in_sets_eq_bot, mem_ae_iff, compl_empty, measure_univ_eq_zero] @[simp] lemma ae_zero : (0 : measure α).ae = ⊥ := ae_eq_bot.2 rfl @[mono] lemma ae_mono {μ ν : measure α} (h : μ ≤ ν) : μ.ae ≤ ν.ae := λ s hs, bot_unique $ trans_rel_left (≤) (measure.le_iff'.1 h _) hs lemma mem_ae_map_iff {f : α → β} (hf : measurable f) {s : set β} (hs : measurable_set s) : s ∈ (map f μ).ae ↔ (f ⁻¹' s) ∈ μ.ae := by simp only [mem_ae_iff, map_apply hf hs.compl, preimage_compl] lemma ae_map_iff {f : α → β} (hf : measurable f) {p : β → Prop} (hp : measurable_set {x | p x}) : (∀ᵐ y ∂ (map f μ), p y) ↔ ∀ᵐ x ∂ μ, p (f x) := mem_ae_map_iff hf hp lemma ae_restrict_iff {p : α → Prop} (hp : measurable_set {x | p x}) : (∀ᵐ x ∂(μ.restrict s), p x) ↔ ∀ᵐ x ∂μ, x ∈ s → p x := begin simp only [ae_iff, ← compl_set_of, restrict_apply hp.compl], congr' with x, simp [and_comm] end lemma ae_imp_of_ae_restrict {s : set α} {p : α → Prop} (h : ∀ᵐ x ∂(μ.restrict s), p x) : ∀ᵐ x ∂μ, x ∈ s → p x := begin simp only [ae_iff] at h ⊢, simpa [set_of_and, inter_comm] using measure_inter_eq_zero_of_restrict h end lemma ae_restrict_iff' {s : set α} {p : α → Prop} (hp : measurable_set s) : (∀ᵐ x ∂(μ.restrict s), p x) ↔ ∀ᵐ x ∂μ, x ∈ s → p x := begin simp only [ae_iff, ← compl_set_of, restrict_apply_eq_zero' hp], congr' with x, simp [and_comm] end lemma ae_restrict_of_ae {s : set α} {p : α → Prop} (h : ∀ᵐ x ∂μ, p x) : (∀ᵐ x ∂(μ.restrict s), p x) := eventually.filter_mono (ae_mono measure.restrict_le_self) h lemma ae_restrict_of_ae_restrict_of_subset {s t : set α} {p : α → Prop} (hst : s ⊆ t) (h : ∀ᵐ x ∂(μ.restrict t), p x) : (∀ᵐ x ∂(μ.restrict s), p x) := eventually.filter_mono (ae_mono $ measure.restrict_mono hst (le_refl μ)) h lemma ae_smul_measure {p : α → Prop} (h : ∀ᵐ x ∂μ, p x) (c : ℝ≥0∞) : ∀ᵐ x ∂(c • μ), p x := ae_iff.2 $ by rw [smul_apply, ae_iff.1 h, mul_zero] lemma ae_smul_measure_iff {p : α → Prop} {c : ℝ≥0∞} (hc : c ≠ 0) : (∀ᵐ x ∂(c • μ), p x) ↔ ∀ᵐ x ∂μ, p x := by simp [ae_iff, hc] lemma ae_add_measure_iff {p : α → Prop} {ν} : (∀ᵐ x ∂μ + ν, p x) ↔ (∀ᵐ x ∂μ, p x) ∧ ∀ᵐ x ∂ν, p x := add_eq_zero_iff lemma ae_eq_comp' {ν : measure β} {f : α → β} {g g' : β → δ} (hf : measurable f) (h : g =ᵐ[ν] g') (h2 : map f μ ≪ ν) : g ∘ f =ᵐ[μ] g' ∘ f := preimage_null_of_map_null hf $ h2 h lemma ae_eq_comp {f : α → β} {g g' : β → δ} (hf : measurable f) (h : g =ᵐ[measure.map f μ] g') : g ∘ f =ᵐ[μ] g' ∘ f := ae_eq_comp' hf h absolutely_continuous.rfl lemma le_ae_restrict : μ.ae ⊓ 𝓟 s ≤ (μ.restrict s).ae := λ s hs, eventually_inf_principal.2 (ae_imp_of_ae_restrict hs) @[simp] lemma ae_restrict_eq (hs : measurable_set s) : (μ.restrict s).ae = μ.ae ⊓ 𝓟 s := begin ext t, simp only [mem_inf_principal, mem_ae_iff, restrict_apply_eq_zero' hs, compl_set_of, not_imp, and_comm (_ ∈ s)], refl end @[simp] lemma ae_restrict_eq_bot {s} : (μ.restrict s).ae = ⊥ ↔ μ s = 0 := ae_eq_bot.trans restrict_eq_zero @[simp] lemma ae_restrict_ne_bot {s} : (μ.restrict s).ae.ne_bot ↔ 0 < μ s := ne_bot_iff.trans $ (not_congr ae_restrict_eq_bot).trans pos_iff_ne_zero.symm lemma self_mem_ae_restrict {s} (hs : measurable_set s) : s ∈ (μ.restrict s).ae := by simp only [ae_restrict_eq hs, exists_prop, mem_principal_sets, mem_inf_sets]; exact ⟨_, univ_mem_sets, s, by rw [univ_inter, and_self]⟩ /-- A version of the Borel-Cantelli lemma: if `sᵢ` is a sequence of measurable sets such that `∑ μ sᵢ` exists, then for almost all `x`, `x` does not belong to almost all `sᵢ`. -/ lemma ae_eventually_not_mem {s : ℕ → set α} (hs : ∀ i, measurable_set (s i)) (hs' : ∑' i, μ (s i) ≠ ∞) : ∀ᵐ x ∂ μ, ∀ᶠ n in at_top, x ∉ s n := begin refine measure_mono_null _ (measure_limsup_eq_zero hs hs'), rw ←set.le_eq_subset, refine le_Inf (λ t ht x hx, _), simp only [le_eq_subset, not_exists, eventually_map, exists_prop, ge_iff_le, mem_set_of_eq, eventually_at_top, mem_compl_eq, not_forall, not_not_mem] at hx ht, rcases ht with ⟨i, hi⟩, rcases hx i with ⟨j, ⟨hj, hj'⟩⟩, exact hi j hj hj' end lemma mem_ae_dirac_iff {a : α} (hs : measurable_set s) : s ∈ (dirac a).ae ↔ a ∈ s := by by_cases a ∈ s; simp [mem_ae_iff, dirac_apply', hs.compl, indicator_apply, *] lemma ae_dirac_iff {a : α} {p : α → Prop} (hp : measurable_set {x | p x}) : (∀ᵐ x ∂(dirac a), p x) ↔ p a := mem_ae_dirac_iff hp @[simp] lemma ae_dirac_eq [measurable_singleton_class α] (a : α) : (dirac a).ae = pure a := by { ext s, simp [mem_ae_iff, imp_false] } lemma ae_eq_dirac' [measurable_singleton_class β] {a : α} {f : α → β} (hf : measurable f) : f =ᵐ[dirac a] const α (f a) := (ae_dirac_iff $ show measurable_set (f ⁻¹' {f a}), from hf $ measurable_set_singleton _).2 rfl lemma ae_eq_dirac [measurable_singleton_class α] {a : α} (f : α → δ) : f =ᵐ[dirac a] const α (f a) := by simp [filter.eventually_eq] lemma restrict_mono_ae (h : s ≤ᵐ[μ] t) : μ.restrict s ≤ μ.restrict t := begin intros u hu, simp only [restrict_apply hu], exact measure_mono_ae (h.mono $ λ x hx, and.imp id hx) end lemma restrict_congr_set (H : s =ᵐ[μ] t) : μ.restrict s = μ.restrict t := le_antisymm (restrict_mono_ae H.le) (restrict_mono_ae H.symm.le) /-- A measure `μ` is called a probability measure if `μ univ = 1`. -/ class probability_measure (μ : measure α) : Prop := (measure_univ : μ univ = 1) instance measure.dirac.probability_measure {x : α} : probability_measure (dirac x) := ⟨dirac_apply_of_mem $ mem_univ x⟩ /-- A measure `μ` is called finite if `μ univ < ∞`. -/ class finite_measure (μ : measure α) : Prop := (measure_univ_lt_top : μ univ < ∞) instance restrict.finite_measure (μ : measure α) [hs : fact (μ s < ∞)] : finite_measure (μ.restrict s) := ⟨by simp [hs.elim]⟩ /-- Measure `μ` *has no atoms* if the measure of each singleton is zero. NB: Wikipedia assumes that for any measurable set `s` with positive `μ`-measure, there exists a measurable `t ⊆ s` such that `0 < μ t < μ s`. While this implies `μ {x} = 0`, the converse is not true. -/ class has_no_atoms (μ : measure α) : Prop := (measure_singleton : ∀ x, μ {x} = 0) export probability_measure (measure_univ) has_no_atoms (measure_singleton) attribute [simp] measure_singleton lemma measure_lt_top (μ : measure α) [finite_measure μ] (s : set α) : μ s < ∞ := (measure_mono (subset_univ s)).trans_lt finite_measure.measure_univ_lt_top lemma measure_ne_top (μ : measure α) [finite_measure μ] (s : set α) : μ s ≠ ∞ := ne_of_lt (measure_lt_top μ s) /-- `le_of_add_le_add_left` is normally applicable to `ordered_cancel_add_comm_monoid`, but it holds for measures with the additional assumption that μ is finite. -/ lemma measure.le_of_add_le_add_left {μ ν₁ ν₂ : measure α} [finite_measure μ] (A2 : μ + ν₁ ≤ μ + ν₂) : ν₁ ≤ ν₂ := λ S B1, ennreal.le_of_add_le_add_left (measure_theory.measure_lt_top μ S) (A2 S B1) @[priority 100] instance probability_measure.to_finite_measure (μ : measure α) [probability_measure μ] : finite_measure μ := ⟨by simp only [measure_univ, ennreal.one_lt_top]⟩ lemma probability_measure.ne_zero (μ : measure α) [probability_measure μ] : μ ≠ 0 := mt measure_univ_eq_zero.2 $ by simp [measure_univ] section no_atoms variables [has_no_atoms μ] lemma measure_countable (h : countable s) : μ s = 0 := begin rw [← bUnion_of_singleton s, ← nonpos_iff_eq_zero], refine le_trans (measure_bUnion_le h _) _, simp end lemma measure_finite (h : s.finite) : μ s = 0 := measure_countable h.countable lemma measure_finset (s : finset α) : μ ↑s = 0 := measure_finite s.finite_to_set lemma insert_ae_eq_self (a : α) (s : set α) : (insert a s : set α) =ᵐ[μ] s := union_ae_eq_right.2 $ measure_mono_null (diff_subset _ _) (measure_singleton _) variables [partial_order α] {a b : α} lemma Iio_ae_eq_Iic : Iio a =ᵐ[μ] Iic a := by simp only [← Iic_diff_right, diff_ae_eq_self, measure_mono_null (set.inter_subset_right _ _) (measure_singleton a)] lemma Ioi_ae_eq_Ici : Ioi a =ᵐ[μ] Ici a := @Iio_ae_eq_Iic (order_dual α) ‹_› ‹_› _ _ _ lemma Ioo_ae_eq_Ioc : Ioo a b =ᵐ[μ] Ioc a b := (ae_eq_refl _).inter Iio_ae_eq_Iic lemma Ioc_ae_eq_Icc : Ioc a b =ᵐ[μ] Icc a b := Ioi_ae_eq_Ici.inter (ae_eq_refl _) lemma Ioo_ae_eq_Ico : Ioo a b =ᵐ[μ] Ico a b := Ioi_ae_eq_Ici.inter (ae_eq_refl _) lemma Ioo_ae_eq_Icc : Ioo a b =ᵐ[μ] Icc a b := Ioi_ae_eq_Ici.inter Iio_ae_eq_Iic lemma Ico_ae_eq_Icc : Ico a b =ᵐ[μ] Icc a b := (ae_eq_refl _).inter Iio_ae_eq_Iic lemma Ico_ae_eq_Ioc : Ico a b =ᵐ[μ] Ioc a b := Ioo_ae_eq_Ico.symm.trans Ioo_ae_eq_Ioc end no_atoms lemma ite_ae_eq_of_measure_zero {γ} (f : α → γ) (g : α → γ) (s : set α) (hs_zero : μ s = 0) : (λ x, ite (x ∈ s) (f x) (g x)) =ᵐ[μ] g := begin have h_ss : sᶜ ⊆ {a : α | ite (a ∈ s) (f a) (g a) = g a}, from λ x hx, by simp [(set.mem_compl_iff _ _).mp hx], refine measure_mono_null _ hs_zero, nth_rewrite 0 ←compl_compl s, rwa set.compl_subset_compl, end lemma ite_ae_eq_of_measure_compl_zero {γ} (f : α → γ) (g : α → γ) (s : set α) (hs_zero : μ sᶜ = 0) : (λ x, ite (x ∈ s) (f x) (g x)) =ᵐ[μ] f := by { filter_upwards [hs_zero], intros, split_ifs, refl } namespace measure /-- A measure is called finite at filter `f` if it is finite at some set `s ∈ f`. Equivalently, it is eventually finite at `s` in `f.lift' powerset`. -/ def finite_at_filter (μ : measure α) (f : filter α) : Prop := ∃ s ∈ f, μ s < ∞ lemma finite_at_filter_of_finite (μ : measure α) [finite_measure μ] (f : filter α) : μ.finite_at_filter f := ⟨univ, univ_mem_sets, measure_lt_top μ univ⟩ lemma finite_at_filter.exists_mem_basis {μ : measure α} {f : filter α} (hμ : finite_at_filter μ f) {p : ι → Prop} {s : ι → set α} (hf : f.has_basis p s) : ∃ i (hi : p i), μ (s i) < ∞ := (hf.exists_iff (λ s t hst ht, (measure_mono hst).trans_lt ht)).1 hμ lemma finite_at_bot (μ : measure α) : μ.finite_at_filter ⊥ := ⟨∅, mem_bot_sets, by simp only [measure_empty, with_top.zero_lt_top]⟩ /-- `μ` has finite spanning sets in `C` if there is a countable sequence of sets in `C` that have finite measures. This structure is a type, which is useful if we want to record extra properties about the sets, such as that they are monotone. `sigma_finite` is defined in terms of this: `μ` is σ-finite if there exists a sequence of finite spanning sets in the collection of all measurable sets. -/ @[protect_proj, nolint has_inhabited_instance] structure finite_spanning_sets_in (μ : measure α) (C : set (set α)) := (set : ℕ → set α) (set_mem : ∀ i, set i ∈ C) (finite : ∀ i, μ (set i) < ∞) (spanning : (⋃ i, set i) = univ) end measure open measure /-- A measure `μ` is called σ-finite if there is a countable collection of sets `{ A i | i ∈ ℕ }` such that `μ (A i) < ∞` and `⋃ i, A i = s`. -/ class sigma_finite (μ : measure α) : Prop := (out' : nonempty (μ.finite_spanning_sets_in {s | measurable_set s})) theorem sigma_finite_iff {μ : measure α} : sigma_finite μ ↔ nonempty (μ.finite_spanning_sets_in {s | measurable_set s}) := ⟨λ h, h.1, λ h, ⟨h⟩⟩ theorem sigma_finite.out {μ : measure α} (h : sigma_finite μ) : nonempty (μ.finite_spanning_sets_in {s | measurable_set s}) := h.1 /-- If `μ` is σ-finite it has finite spanning sets in the collection of all measurable sets. -/ def measure.to_finite_spanning_sets_in (μ : measure α) [h : sigma_finite μ] : μ.finite_spanning_sets_in {s | measurable_set s} := classical.choice h.out /-- A noncomputable way to get a monotone collection of sets that span `univ` and have finite measure using `classical.some`. This definition satisfies monotonicity in addition to all other properties in `sigma_finite`. -/ def spanning_sets (μ : measure α) [sigma_finite μ] (i : ℕ) : set α := accumulate μ.to_finite_spanning_sets_in.set i lemma monotone_spanning_sets (μ : measure α) [sigma_finite μ] : monotone (spanning_sets μ) := monotone_accumulate lemma measurable_spanning_sets (μ : measure α) [sigma_finite μ] (i : ℕ) : measurable_set (spanning_sets μ i) := measurable_set.Union $ λ j, measurable_set.Union_Prop $ λ hij, μ.to_finite_spanning_sets_in.set_mem j lemma measure_spanning_sets_lt_top (μ : measure α) [sigma_finite μ] (i : ℕ) : μ (spanning_sets μ i) < ∞ := measure_bUnion_lt_top (finite_le_nat i) $ λ j _, μ.to_finite_spanning_sets_in.finite j lemma Union_spanning_sets (μ : measure α) [sigma_finite μ] : (⋃ i : ℕ, spanning_sets μ i) = univ := by simp_rw [spanning_sets, Union_accumulate, μ.to_finite_spanning_sets_in.spanning] lemma is_countably_spanning_spanning_sets (μ : measure α) [sigma_finite μ] : is_countably_spanning (range (spanning_sets μ)) := ⟨spanning_sets μ, mem_range_self, Union_spanning_sets μ⟩ namespace measure lemma supr_restrict_spanning_sets [sigma_finite μ] (hs : measurable_set s) : (⨆ i, μ.restrict (spanning_sets μ i) s) = μ s := begin convert (restrict_Union_apply_eq_supr (measurable_spanning_sets μ) _ hs).symm, { simp [Union_spanning_sets] }, { exact directed_of_sup (monotone_spanning_sets μ) } end namespace finite_spanning_sets_in variables {C D : set (set α)} /-- If `μ` has finite spanning sets in `C` and `C ⊆ D` then `μ` has finite spanning sets in `D`. -/ protected def mono (h : μ.finite_spanning_sets_in C) (hC : C ⊆ D) : μ.finite_spanning_sets_in D := ⟨h.set, λ i, hC (h.set_mem i), h.finite, h.spanning⟩ /-- If `μ` has finite spanning sets in the collection of measurable sets `C`, then `μ` is σ-finite. -/ protected lemma sigma_finite (h : μ.finite_spanning_sets_in C) (hC : ∀ s ∈ C, measurable_set s) : sigma_finite μ := ⟨⟨h.mono hC⟩⟩ /-- An extensionality for measures. It is `ext_of_generate_from_of_Union` formulated in terms of `finite_spanning_sets_in`. -/ protected lemma ext {ν : measure α} {C : set (set α)} (hA : ‹_› = generate_from C) (hC : is_pi_system C) (h : μ.finite_spanning_sets_in C) (h_eq : ∀ s ∈ C, μ s = ν s) : μ = ν := ext_of_generate_from_of_Union C _ hA hC h.spanning h.set_mem h.finite h_eq protected lemma is_countably_spanning (h : μ.finite_spanning_sets_in C) : is_countably_spanning C := ⟨_, h.set_mem, h.spanning⟩ end finite_spanning_sets_in lemma sigma_finite_of_not_nonempty (μ : measure α) (hα : ¬ nonempty α) : sigma_finite μ := ⟨⟨⟨λ _, ∅, λ n, measurable_set.empty, λ n, by simp, by simp [eq_empty_of_not_nonempty hα univ]⟩⟩⟩ lemma sigma_finite_of_countable {S : set (set α)} (hc : countable S) (hμ : ∀ s ∈ S, μ s < ∞) (hU : ⋃₀ S = univ) : sigma_finite μ := begin obtain ⟨s, hμ, hs⟩ : ∃ s : ℕ → set α, (∀ n, μ (s n) < ∞) ∧ (⋃ n, s n) = univ, from (exists_seq_cover_iff_countable ⟨∅, by simp⟩).2 ⟨S, hc, hμ, hU⟩, refine ⟨⟨⟨λ n, to_measurable μ (s n), λ n, measurable_set_to_measurable _ _, by simpa, _⟩⟩⟩, exact eq_univ_of_subset (Union_subset_Union $ λ n, subset_to_measurable μ (s n)) hs end end measure /-- Every finite measure is σ-finite. -/ @[priority 100] instance finite_measure.to_sigma_finite (μ : measure α) [finite_measure μ] : sigma_finite μ := ⟨⟨⟨λ _, univ, λ _, measurable_set.univ, λ _, measure_lt_top μ _, Union_const _⟩⟩⟩ instance restrict.sigma_finite (μ : measure α) [sigma_finite μ] (s : set α) : sigma_finite (μ.restrict s) := begin refine ⟨⟨⟨spanning_sets μ, measurable_spanning_sets μ, λ i, _, Union_spanning_sets μ⟩⟩⟩, rw [restrict_apply (measurable_spanning_sets μ i)], exact (measure_mono $ inter_subset_left _ _).trans_lt (measure_spanning_sets_lt_top μ i) end instance sum.sigma_finite {ι} [fintype ι] (μ : ι → measure α) [∀ i, sigma_finite (μ i)] : sigma_finite (sum μ) := begin haveI : encodable ι := (encodable.trunc_encodable_of_fintype ι).out, have : ∀ n, measurable_set (⋂ (i : ι), spanning_sets (μ i) n) := λ n, measurable_set.Inter (λ i, measurable_spanning_sets (μ i) n), refine ⟨⟨⟨λ n, ⋂ i, spanning_sets (μ i) n, this, λ n, _, _⟩⟩⟩, { rw [sum_apply _ (this n), tsum_fintype, ennreal.sum_lt_top_iff], rintro i -, exact (measure_mono $ Inter_subset _ i).trans_lt (measure_spanning_sets_lt_top (μ i) n) }, { rw [Union_Inter_of_monotone], simp_rw [Union_spanning_sets, Inter_univ], exact λ i, monotone_spanning_sets (μ i), } end instance add.sigma_finite (μ ν : measure α) [sigma_finite μ] [sigma_finite ν] : sigma_finite (μ + ν) := by { rw [← sum_cond], refine @sum.sigma_finite _ _ _ _ _ (bool.rec _ _); simpa } /-- A measure is called locally finite if it is finite in some neighborhood of each point. -/ class locally_finite_measure [topological_space α] (μ : measure α) : Prop := (finite_at_nhds : ∀ x, μ.finite_at_filter (𝓝 x)) @[priority 100] -- see Note [lower instance priority] instance finite_measure.to_locally_finite_measure [topological_space α] (μ : measure α) [finite_measure μ] : locally_finite_measure μ := ⟨λ x, finite_at_filter_of_finite _ _⟩ lemma measure.finite_at_nhds [topological_space α] (μ : measure α) [locally_finite_measure μ] (x : α) : μ.finite_at_filter (𝓝 x) := locally_finite_measure.finite_at_nhds x lemma measure.smul_finite {α : Type*} [measurable_space α] (μ : measure α) [finite_measure μ] {c : ℝ≥0∞} (hc : c < ∞) : finite_measure (c • μ) := begin refine ⟨_⟩, rw measure.smul_apply, exact ennreal.mul_lt_top hc (measure_lt_top μ set.univ), end lemma measure.exists_is_open_measure_lt_top [topological_space α] (μ : measure α) [locally_finite_measure μ] (x : α) : ∃ s : set α, x ∈ s ∧ is_open s ∧ μ s < ∞ := by simpa only [exists_prop, and.assoc] using (μ.finite_at_nhds x).exists_mem_basis (nhds_basis_opens x) @[priority 100] -- see Note [lower instance priority] instance sigma_finite_of_locally_finite [topological_space α] [topological_space.second_countable_topology α] {μ : measure α} [locally_finite_measure μ] : sigma_finite μ := begin choose s hsx hsμ using μ.finite_at_nhds, rcases topological_space.countable_cover_nhds hsx with ⟨t, htc, htU⟩, refine measure.sigma_finite_of_countable (htc.image s) (ball_image_iff.2 $ λ x hx, hsμ x) _, rwa sUnion_image end /-- If two finite measures give the same mass to the whole space and coincide on a π-system made of measurable sets, then they coincide on all sets in the σ-algebra generated by the π-system. -/ lemma ext_on_measurable_space_of_generate_finite {α} (m₀ : measurable_space α) {μ ν : measure α} [finite_measure μ] (C : set (set α)) (hμν : ∀ s ∈ C, μ s = ν s) {m : measurable_space α} (h : m ≤ m₀) (hA : m = measurable_space.generate_from C) (hC : is_pi_system C) (h_univ : μ set.univ = ν set.univ) {s : set α} (hs : m.measurable_set' s) : μ s = ν s := begin haveI : @finite_measure _ m₀ ν := begin constructor, rw ← h_univ, apply finite_measure.measure_univ_lt_top, end, refine induction_on_inter hA hC (by simp) hμν _ _ hs, { intros t h1t h2t, have h1t_ : @measurable_set α m₀ t, from h _ h1t, rw [@measure_compl α m₀ μ t h1t_ (@measure_lt_top α m₀ μ _ t), @measure_compl α m₀ ν t h1t_ (@measure_lt_top α m₀ ν _ t), h_univ, h2t], }, { intros f h1f h2f h3f, have h2f_ : ∀ (i : ℕ), @measurable_set α m₀ (f i), from (λ i, h _ (h2f i)), have h_Union : @measurable_set α m₀ (⋃ (i : ℕ), f i),from @measurable_set.Union α ℕ m₀ _ f h2f_, simp [measure_Union, h_Union, h1f, h3f, h2f_], }, end /-- Two finite measures are equal if they are equal on the π-system generating the σ-algebra (and `univ`). -/ lemma ext_of_generate_finite (C : set (set α)) (hA : _inst_1 = generate_from C) (hC : is_pi_system C) {μ ν : measure α} [finite_measure μ] (hμν : ∀ s ∈ C, μ s = ν s) (h_univ : μ univ = ν univ) : μ = ν := measure.ext (λ s hs, ext_on_measurable_space_of_generate_finite _inst_1 C hμν (le_refl _inst_1) hA hC h_univ hs) namespace measure namespace finite_at_filter variables {f g : filter α} lemma filter_mono (h : f ≤ g) : μ.finite_at_filter g → μ.finite_at_filter f := λ ⟨s, hs, hμ⟩, ⟨s, h hs, hμ⟩ lemma inf_of_left (h : μ.finite_at_filter f) : μ.finite_at_filter (f ⊓ g) := h.filter_mono inf_le_left lemma inf_of_right (h : μ.finite_at_filter g) : μ.finite_at_filter (f ⊓ g) := h.filter_mono inf_le_right @[simp] lemma inf_ae_iff : μ.finite_at_filter (f ⊓ μ.ae) ↔ μ.finite_at_filter f := begin refine ⟨_, λ h, h.filter_mono inf_le_left⟩, rintros ⟨s, ⟨t, ht, u, hu, hs⟩, hμ⟩, suffices : μ t ≤ μ s, from ⟨t, ht, this.trans_lt hμ⟩, exact measure_mono_ae (mem_sets_of_superset hu (λ x hu ht, hs ⟨ht, hu⟩)) end alias inf_ae_iff ↔ measure_theory.measure.finite_at_filter.of_inf_ae _ lemma filter_mono_ae (h : f ⊓ μ.ae ≤ g) (hg : μ.finite_at_filter g) : μ.finite_at_filter f := inf_ae_iff.1 (hg.filter_mono h) protected lemma measure_mono (h : μ ≤ ν) : ν.finite_at_filter f → μ.finite_at_filter f := λ ⟨s, hs, hν⟩, ⟨s, hs, (measure.le_iff'.1 h s).trans_lt hν⟩ @[mono] protected lemma mono (hf : f ≤ g) (hμ : μ ≤ ν) : ν.finite_at_filter g → μ.finite_at_filter f := λ h, (h.filter_mono hf).measure_mono hμ protected lemma eventually (h : μ.finite_at_filter f) : ∀ᶠ s in f.lift' powerset, μ s < ∞ := (eventually_lift'_powerset' $ λ s t hst ht, (measure_mono hst).trans_lt ht).2 h lemma filter_sup : μ.finite_at_filter f → μ.finite_at_filter g → μ.finite_at_filter (f ⊔ g) := λ ⟨s, hsf, hsμ⟩ ⟨t, htg, htμ⟩, ⟨s ∪ t, union_mem_sup hsf htg, (measure_union_le s t).trans_lt (ennreal.add_lt_top.2 ⟨hsμ, htμ⟩)⟩ end finite_at_filter lemma finite_at_nhds_within [topological_space α] (μ : measure α) [locally_finite_measure μ] (x : α) (s : set α) : μ.finite_at_filter (𝓝[s] x) := (finite_at_nhds μ x).inf_of_left @[simp] lemma finite_at_principal : μ.finite_at_filter (𝓟 s) ↔ μ s < ∞ := ⟨λ ⟨t, ht, hμ⟩, (measure_mono ht).trans_lt hμ, λ h, ⟨s, mem_principal_self s, h⟩⟩ /-! ### Subtraction of measures -/ /-- The measure `μ - ν` is defined to be the least measure `τ` such that `μ ≤ τ + ν`. It is the equivalent of `(μ - ν) ⊔ 0` if `μ` and `ν` were signed measures. Compare with `ennreal.has_sub`. Specifically, note that if you have `α = {1,2}`, and `μ {1} = 2`, `μ {2} = 0`, and `ν {2} = 2`, `ν {1} = 0`, then `(μ - ν) {1, 2} = 2`. However, if `μ ≤ ν`, and `ν univ ≠ ∞`, then `(μ - ν) + ν = μ`. -/ noncomputable instance has_sub {α : Type*} [measurable_space α] : has_sub (measure α) := ⟨λ μ ν, Inf {τ | μ ≤ τ + ν} ⟩ section measure_sub lemma sub_def : μ - ν = Inf {d | μ ≤ d + ν} := rfl lemma sub_eq_zero_of_le (h : μ ≤ ν) : μ - ν = 0 := begin rw [← nonpos_iff_eq_zero', measure.sub_def], apply @Inf_le (measure α) _ _, simp [h], end /-- This application lemma only works in special circumstances. Given knowledge of when `μ ≤ ν` and `ν ≤ μ`, a more general application lemma can be written. -/ lemma sub_apply [finite_measure ν] (h₁ : measurable_set s) (h₂ : ν ≤ μ) : (μ - ν) s = μ s - ν s := begin -- We begin by defining `measure_sub`, which will be equal to `(μ - ν)`. let measure_sub : measure α := @measure_theory.measure.of_measurable α _ (λ (t : set α) (h_t_measurable_set : measurable_set t), (μ t - ν t)) begin simp end begin intros g h_meas h_disj, simp only, rw ennreal.tsum_sub, repeat { rw ← measure_theory.measure_Union h_disj h_meas }, apply measure_theory.measure_lt_top, intro i, apply h₂, apply h_meas end, -- Now, we demonstrate `μ - ν = measure_sub`, and apply it. begin have h_measure_sub_add : (ν + measure_sub = μ), { ext t h_t_measurable_set, simp only [pi.add_apply, coe_add], rw [measure_theory.measure.of_measurable_apply _ h_t_measurable_set, add_comm, ennreal.sub_add_cancel_of_le (h₂ t h_t_measurable_set)] }, have h_measure_sub_eq : (μ - ν) = measure_sub, { rw measure_theory.measure.sub_def, apply le_antisymm, { apply @Inf_le (measure α) (measure.complete_lattice), simp [le_refl, add_comm, h_measure_sub_add] }, apply @le_Inf (measure α) (measure.complete_lattice), intros d h_d, rw [← h_measure_sub_add, mem_set_of_eq, add_comm d] at h_d, apply measure.le_of_add_le_add_left h_d }, rw h_measure_sub_eq, apply measure.of_measurable_apply _ h₁, end end lemma sub_add_cancel_of_le [finite_measure ν] (h₁ : ν ≤ μ) : μ - ν + ν = μ := begin ext s h_s_meas, rw [add_apply, sub_apply h_s_meas h₁, ennreal.sub_add_cancel_of_le (h₁ s h_s_meas)], end end measure_sub lemma restrict_sub_eq_restrict_sub_restrict (h_meas_s : measurable_set s) : (μ - ν).restrict s = (μ.restrict s) - (ν.restrict s) := begin repeat {rw sub_def}, have h_nonempty : {d | μ ≤ d + ν}.nonempty, { apply @set.nonempty_of_mem _ _ μ, rw mem_set_of_eq, intros t h_meas, apply le_add_right (le_refl (μ t)) }, rw restrict_Inf_eq_Inf_restrict h_nonempty h_meas_s, apply le_antisymm, { apply @Inf_le_Inf_of_forall_exists_le (measure α) _, intros ν' h_ν'_in, rw mem_set_of_eq at h_ν'_in, apply exists.intro (ν'.restrict s), split, { rw mem_image, apply exists.intro (ν' + (⊤ : measure_theory.measure α).restrict sᶜ), rw mem_set_of_eq, split, { rw [add_assoc, add_comm _ ν, ← add_assoc, measure_theory.measure.le_iff], intros t h_meas_t, have h_inter_inter_eq_inter : ∀ t' : set α , t ∩ t' ∩ t' = t ∩ t', { intro t', rw set.inter_eq_self_of_subset_left, apply set.inter_subset_right t t' }, have h_meas_t_inter_s : measurable_set (t ∩ s) := h_meas_t.inter h_meas_s, repeat {rw measure_eq_inter_diff h_meas_t h_meas_s, rw set.diff_eq}, apply add_le_add _ _; rw add_apply, { apply le_add_right _, rw add_apply, rw ← @restrict_eq_self _ _ μ s _ h_meas_t_inter_s (set.inter_subset_right _ _), rw ← @restrict_eq_self _ _ ν s _ h_meas_t_inter_s (set.inter_subset_right _ _), apply h_ν'_in _ h_meas_t_inter_s }, cases (@set.eq_empty_or_nonempty _ (t ∩ sᶜ)) with h_inter_empty h_inter_nonempty, { simp [h_inter_empty] }, { have h_meas_inter_compl := h_meas_t.inter (measurable_set.compl h_meas_s), rw [restrict_apply h_meas_inter_compl, h_inter_inter_eq_inter sᶜ], have h_mu_le_add_top : μ ≤ ν' + ν + ⊤, { rw add_comm, have h_le_top : μ ≤ ⊤ := le_top, apply (λ t₂ h_meas, le_add_right (h_le_top t₂ h_meas)) }, apply h_mu_le_add_top _ h_meas_inter_compl } }, { ext1 t h_meas_t, simp [restrict_apply h_meas_t, restrict_apply (h_meas_t.inter h_meas_s), set.inter_assoc] } }, { apply restrict_le_self } }, { apply @Inf_le_Inf_of_forall_exists_le (measure α) _, intros s h_s_in, cases h_s_in with t h_t, cases h_t with h_t_in h_t_eq, subst s, apply exists.intro (t.restrict s), split, { rw [set.mem_set_of_eq, ← restrict_add], apply restrict_mono (set.subset.refl _) h_t_in }, { apply le_refl _ } }, end lemma sub_apply_eq_zero_of_restrict_le_restrict (h_le : μ.restrict s ≤ ν.restrict s) (h_meas_s : measurable_set s) : (μ - ν) s = 0 := begin rw [← restrict_apply_self _ h_meas_s, restrict_sub_eq_restrict_sub_restrict, sub_eq_zero_of_le], repeat {simp [*]}, end end measure end measure_theory open measure_theory measure_theory.measure namespace measurable_equiv /-! Interactions of measurable equivalences and measures -/ open equiv measure_theory.measure variables [measurable_space α] [measurable_space β] {μ : measure α} {ν : measure β} /-- If we map a measure along a measurable equivalence, we can compute the measure on all sets (not just the measurable ones). -/ protected theorem map_apply (f : α ≃ᵐ β) (s : set β) : map f μ s = μ (f ⁻¹' s) := begin refine le_antisymm _ (le_map_apply f.measurable s), rw [measure_eq_infi' μ], refine le_infi _, rintro ⟨t, hst, ht⟩, rw [subtype.coe_mk], have := f.symm.to_equiv.image_eq_preimage, simp only [←coe_eq, symm_symm, symm_to_equiv] at this, rw [← this, image_subset_iff] at hst, convert measure_mono hst, rw [map_apply, preimage_preimage], { refine congr_arg μ (eq.symm _), convert preimage_id, exact funext f.left_inv }, exacts [f.measurable, f.measurable_inv_fun ht] end @[simp] lemma map_symm_map (e : α ≃ᵐ β) : map e.symm (map e μ) = μ := by simp [map_map e.symm.measurable e.measurable] @[simp] lemma map_map_symm (e : α ≃ᵐ β) : map e (map e.symm ν) = ν := by simp [map_map e.measurable e.symm.measurable] lemma map_measurable_equiv_injective (e : α ≃ᵐ β) : injective (map e) := by { intros μ₁ μ₂ hμ, apply_fun map e.symm at hμ, simpa [map_symm_map e] using hμ } lemma map_apply_eq_iff_map_symm_apply_eq (e : α ≃ᵐ β) : map e μ = ν ↔ map e.symm ν = μ := by rw [← (map_measurable_equiv_injective e).eq_iff, map_map_symm, eq_comm] end measurable_equiv section is_complete /-- A measure is complete if every null set is also measurable. A null set is a subset of a measurable set with measure `0`. Since every measure is defined as a special case of an outer measure, we can more simply state that a set `s` is null if `μ s = 0`. -/ class measure_theory.measure.is_complete {_ : measurable_space α} (μ : measure α) : Prop := (out' : ∀ s, μ s = 0 → measurable_set s) theorem measure_theory.measure.is_complete_iff {_ : measurable_space α} {μ : measure α} : μ.is_complete ↔ ∀ s, μ s = 0 → measurable_set s := ⟨λ h, h.1, λ h, ⟨h⟩⟩ theorem measure_theory.measure.is_complete.out {_ : measurable_space α} {μ : measure α} (h : μ.is_complete) : ∀ s, μ s = 0 → measurable_set s := h.1 variables [measurable_space α] {μ : measure α} {s t z : set α} /-- A set is null measurable if it is the union of a null set and a measurable set. -/ def null_measurable_set (μ : measure α) (s : set α) : Prop := ∃ t z, s = t ∪ z ∧ measurable_set t ∧ μ z = 0 theorem null_measurable_set_iff : null_measurable_set μ s ↔ ∃ t, t ⊆ s ∧ measurable_set t ∧ μ (s \ t) = 0 := begin split, { rintro ⟨t, z, rfl, ht, hz⟩, refine ⟨t, set.subset_union_left _ _, ht, measure_mono_null _ hz⟩, simp [union_diff_left, diff_subset] }, { rintro ⟨t, st, ht, hz⟩, exact ⟨t, _, (union_diff_cancel st).symm, ht, hz⟩ } end theorem null_measurable_set_measure_eq (st : t ⊆ s) (hz : μ (s \ t) = 0) : μ s = μ t := begin refine le_antisymm _ (measure_mono st), have := measure_union_le t (s \ t), rw [union_diff_cancel st, hz] at this, simpa end theorem measurable_set.null_measurable_set (μ : measure α) (hs : measurable_set s) : null_measurable_set μ s := ⟨s, ∅, by simp, hs, μ.empty⟩ theorem null_measurable_set_of_complete (μ : measure α) [c : μ.is_complete] : null_measurable_set μ s ↔ measurable_set s := ⟨by rintro ⟨t, z, rfl, ht, hz⟩; exact measurable_set.union ht (c.out _ hz), λ h, h.null_measurable_set _⟩ theorem null_measurable_set.union_null (hs : null_measurable_set μ s) (hz : μ z = 0) : null_measurable_set μ (s ∪ z) := begin rcases hs with ⟨t, z', rfl, ht, hz'⟩, exact ⟨t, z' ∪ z, set.union_assoc _ _ _, ht, nonpos_iff_eq_zero.1 (le_trans (measure_union_le _ _) $ by simp [hz, hz'])⟩ end theorem null_null_measurable_set (hz : μ z = 0) : null_measurable_set μ z := by simpa using (measurable_set.empty.null_measurable_set _).union_null hz theorem null_measurable_set.Union_nat {s : ℕ → set α} (hs : ∀ i, null_measurable_set μ (s i)) : null_measurable_set μ (Union s) := begin choose t ht using assume i, null_measurable_set_iff.1 (hs i), simp [forall_and_distrib] at ht, rcases ht with ⟨st, ht, hz⟩, refine null_measurable_set_iff.2 ⟨Union t, Union_subset_Union st, measurable_set.Union ht, measure_mono_null _ (measure_Union_null hz)⟩, rw [diff_subset_iff, ← Union_union_distrib], exact Union_subset_Union (λ i, by rw ← diff_subset_iff) end theorem measurable_set.diff_null (hs : measurable_set s) (hz : μ z = 0) : null_measurable_set μ (s \ z) := begin rw measure_eq_infi at hz, choose f hf using show ∀ q : {q : ℚ // q > 0}, ∃ t : set α, z ⊆ t ∧ measurable_set t ∧ μ t < (nnreal.of_real q.1 : ℝ≥0∞), { rintro ⟨ε, ε0⟩, have : 0 < (nnreal.of_real ε : ℝ≥0∞), { simpa using ε0 }, rw ← hz at this, simpa [infi_lt_iff] }, refine null_measurable_set_iff.2 ⟨s \ Inter f, diff_subset_diff_right (subset_Inter (λ i, (hf i).1)), hs.diff (measurable_set.Inter (λ i, (hf i).2.1)), measure_mono_null _ (nonpos_iff_eq_zero.1 $ le_of_not_lt $ λ h, _)⟩, { exact Inter f }, { rw [diff_subset_iff, diff_union_self], exact subset.trans (diff_subset _ _) (subset_union_left _ _) }, rcases ennreal.lt_iff_exists_rat_btwn.1 h with ⟨ε, ε0', ε0, h⟩, simp at ε0, apply not_le_of_lt (lt_trans (hf ⟨ε, ε0⟩).2.2 h), exact measure_mono (Inter_subset _ _) end theorem null_measurable_set.diff_null (hs : null_measurable_set μ s) (hz : μ z = 0) : null_measurable_set μ (s \ z) := begin rcases hs with ⟨t, z', rfl, ht, hz'⟩, rw [set.union_diff_distrib], exact (ht.diff_null hz).union_null (measure_mono_null (diff_subset _ _) hz') end theorem null_measurable_set.compl (hs : null_measurable_set μ s) : null_measurable_set μ sᶜ := begin rcases hs with ⟨t, z, rfl, ht, hz⟩, rw compl_union, exact ht.compl.diff_null hz end theorem null_measurable_set_iff_ae {s : set α} : null_measurable_set μ s ↔ ∃ t, measurable_set t ∧ s =ᵐ[μ] t := begin simp only [ae_eq_set], split, { assume h, rcases null_measurable_set_iff.1 h with ⟨t, ts, tmeas, ht⟩, refine ⟨t, tmeas, ht, _⟩, rw [diff_eq_empty.2 ts, measure_empty] }, { rintros ⟨t, tmeas, h₁, h₂⟩, have : null_measurable_set μ (t ∪ (s \ t)) := null_measurable_set.union_null (tmeas.null_measurable_set _) h₁, have A : null_measurable_set μ ((t ∪ (s \ t)) \ (t \ s)) := null_measurable_set.diff_null this h₂, have : (t ∪ (s \ t)) \ (t \ s) = s, { apply subset.antisymm, { assume x hx, simp only [mem_union_eq, not_and, mem_diff, not_not_mem] at hx, cases hx.1, { exact hx.2 h }, { exact h.1 } }, { assume x hx, simp [hx, classical.em (x ∈ t)] } }, rwa this at A } end theorem null_measurable_set_iff_sandwich {s : set α} : null_measurable_set μ s ↔ ∃ (t u : set α), measurable_set t ∧ measurable_set u ∧ t ⊆ s ∧ s ⊆ u ∧ μ (u \ t) = 0 := begin split, { assume h, rcases null_measurable_set_iff.1 h with ⟨t, ts, tmeas, ht⟩, rcases null_measurable_set_iff.1 h.compl with ⟨u', u's, u'meas, hu'⟩, have A : s ⊆ u'ᶜ := subset_compl_comm.mp u's, refine ⟨t, u'ᶜ, tmeas, u'meas.compl, ts, A, _⟩, have : sᶜ \ u' = u'ᶜ \ s, by simp [compl_eq_univ_diff, diff_diff, union_comm], rw this at hu', apply le_antisymm _ bot_le, calc μ (u'ᶜ \ t) ≤ μ ((u'ᶜ \ s) ∪ (s \ t)) : begin apply measure_mono, assume x hx, simp at hx, simp [hx, or_comm, classical.em], end ... ≤ μ (u'ᶜ \ s) + μ (s \ t) : measure_union_le _ _ ... = 0 : by rw [ht, hu', zero_add] }, { rintros ⟨t, u, tmeas, umeas, ts, su, hμ⟩, refine null_measurable_set_iff.2 ⟨t, ts, tmeas, _⟩, apply le_antisymm _ bot_le, calc μ (s \ t) ≤ μ (u \ t) : measure_mono (diff_subset_diff_left su) ... = 0 : hμ } end lemma restrict_apply_of_null_measurable_set {s t : set α} (ht : null_measurable_set (μ.restrict s) t) : μ.restrict s t = μ (t ∩ s) := begin rcases null_measurable_set_iff_sandwich.1 ht with ⟨u, v, umeas, vmeas, ut, tv, huv⟩, apply le_antisymm _ (le_restrict_apply _ _), calc μ.restrict s t ≤ μ.restrict s v : measure_mono tv ... = μ (v ∩ s) : restrict_apply vmeas ... ≤ μ ((u ∩ s) ∪ ((v \ u) ∩ s)) : measure_mono $ by { assume x hx, simp at hx, simp [hx, classical.em] } ... ≤ μ (u ∩ s) + μ ((v \ u) ∩ s) : measure_union_le _ _ ... = μ (u ∩ s) + μ.restrict s (v \ u) : by rw measure.restrict_apply (vmeas.diff umeas) ... = μ (u ∩ s) : by rw [huv, add_zero] ... ≤ μ (t ∩ s) : measure_mono $ inter_subset_inter_left s ut end /-- The measurable space of all null measurable sets. -/ def null_measurable (μ : measure α) : measurable_space α := { measurable_set' := null_measurable_set μ, measurable_set_empty := measurable_set.empty.null_measurable_set _, measurable_set_compl := λ s hs, hs.compl, measurable_set_Union := λ f, null_measurable_set.Union_nat } /-- Given a measure we can complete it to a (complete) measure on all null measurable sets. -/ def completion (μ : measure α) : @measure_theory.measure α (null_measurable μ) := { to_outer_measure := μ.to_outer_measure, m_Union := λ s hs hd, show μ (Union s) = ∑' i, μ (s i), begin choose t ht using assume i, null_measurable_set_iff.1 (hs i), simp [forall_and_distrib] at ht, rcases ht with ⟨st, ht, hz⟩, rw null_measurable_set_measure_eq (Union_subset_Union st), { rw measure_Union _ ht, { congr, funext i, exact (null_measurable_set_measure_eq (st i) (hz i)).symm }, { rintro i j ij x ⟨h₁, h₂⟩, exact hd i j ij ⟨st i h₁, st j h₂⟩ } }, { refine measure_mono_null _ (measure_Union_null hz), rw [diff_subset_iff, ← Union_union_distrib], exact Union_subset_Union (λ i, by rw ← diff_subset_iff) } end, trimmed := begin letI := null_measurable μ, refine le_antisymm (λ s, _) (outer_measure.le_trim _), rw outer_measure.trim_eq_infi, dsimp, clear _inst, resetI, rw measure_eq_infi s, exact infi_le_infi (λ t, infi_le_infi $ λ st, infi_le_infi2 $ λ ht, ⟨ht.null_measurable_set _, le_refl _⟩) end } instance completion.is_complete (μ : measure α) : (completion μ).is_complete := ⟨λ z hz, null_null_measurable_set hz⟩ lemma measurable.ae_eq {α β} [measurable_space α] [measurable_space β] {μ : measure α} [hμ : μ.is_complete] {f g : α → β} (hf : measurable f) (hfg : f =ᵐ[μ] g) : measurable g := begin intros s hs, let t := {x | f x = g x}, have ht_compl : μ tᶜ = 0, by rwa [filter.eventually_eq, ae_iff] at hfg, rw (set.inter_union_compl (g ⁻¹' s) t).symm, refine measurable_set.union _ _, { have h_g_to_f : (g ⁻¹' s) ∩ t = (f ⁻¹' s) ∩ t, { ext, simp only [set.mem_inter_iff, set.mem_preimage, and.congr_left_iff, set.mem_set_of_eq], exact λ hx, by rw hx, }, rw h_g_to_f, exact measurable_set.inter (hf hs) (measurable_set.compl_iff.mp (hμ.out tᶜ ht_compl)), }, { exact hμ.out (g ⁻¹' s ∩ tᶜ) (measure_mono_null (set.inter_subset_right _ _) ht_compl), }, end end is_complete namespace measure_theory /-- A measure space is a measurable space equipped with a measure, referred to as `volume`. -/ class measure_space (α : Type*) extends measurable_space α := (volume : measure α) export measure_space (volume) /-- `volume` is the canonical measure on `α`. -/ add_decl_doc volume section measure_space variables [measure_space α] {s₁ s₂ : set α} notation `∀ᵐ` binders `, ` r:(scoped P, filter.eventually P (measure.ae volume)) := r /-- The tactic `exact volume`, to be used in optional (`auto_param`) arguments. -/ meta def volume_tac : tactic unit := `[exact measure_theory.measure_space.volume] end measure_space end measure_theory /-! # Almost everywhere measurable functions A function is almost everywhere measurable if it coincides almost everywhere with a measurable function. We define this property, called `ae_measurable f μ`, and discuss several of its properties that are analogous to properties of measurable functions. -/ section open measure_theory variables [measurable_space α] [measurable_space β] {f g : α → β} {μ ν : measure α} /-- A function is almost everywhere measurable if it coincides almost everywhere with a measurable function. -/ def ae_measurable (f : α → β) (μ : measure α . measure_theory.volume_tac) : Prop := ∃ g : α → β, measurable g ∧ f =ᵐ[μ] g lemma measurable.ae_measurable (h : measurable f) : ae_measurable f μ := ⟨f, h, ae_eq_refl f⟩ @[nontriviality] lemma subsingleton.ae_measurable [subsingleton α] : ae_measurable f μ := subsingleton.measurable.ae_measurable @[simp] lemma ae_measurable_zero : ae_measurable f 0 := begin nontriviality α, inhabit α, exact ⟨λ x, f (default α), measurable_const, rfl⟩ end lemma ae_measurable_iff_measurable [μ.is_complete] : ae_measurable f μ ↔ measurable f := begin split; intro h, { rcases h with ⟨g, hg_meas, hfg⟩, exact hg_meas.ae_eq hfg.symm, }, { exact h.ae_measurable, }, end namespace ae_measurable /-- Given an almost everywhere measurable function `f`, associate to it a measurable function that coincides with it almost everywhere. `f` is explicit in the definition to make sure that it shows in pretty-printing. -/ def mk (f : α → β) (h : ae_measurable f μ) : α → β := classical.some h lemma measurable_mk (h : ae_measurable f μ) : measurable (h.mk f) := (classical.some_spec h).1 lemma ae_eq_mk (h : ae_measurable f μ) : f =ᵐ[μ] (h.mk f) := (classical.some_spec h).2 lemma congr (hf : ae_measurable f μ) (h : f =ᵐ[μ] g) : ae_measurable g μ := ⟨hf.mk f, hf.measurable_mk, h.symm.trans hf.ae_eq_mk⟩ lemma mono_measure (h : ae_measurable f μ) (h' : ν ≤ μ) : ae_measurable f ν := ⟨h.mk f, h.measurable_mk, eventually.filter_mono (ae_mono h') h.ae_eq_mk⟩ lemma mono_set {s t} (h : s ⊆ t) (ht : ae_measurable f (μ.restrict t)) : ae_measurable f (μ.restrict s) := ht.mono_measure (restrict_mono h le_rfl) protected lemma mono' (h : ae_measurable f μ) (h' : ν ≪ μ) : ae_measurable f ν := ⟨h.mk f, h.measurable_mk, h' h.ae_eq_mk⟩ lemma ae_mem_imp_eq_mk {s} (h : ae_measurable f (μ.restrict s)) : ∀ᵐ x ∂μ, x ∈ s → f x = h.mk f x := ae_imp_of_ae_restrict h.ae_eq_mk lemma ae_inf_principal_eq_mk {s} (h : ae_measurable f (μ.restrict s)) : f =ᶠ[μ.ae ⊓ 𝓟 s] h.mk f := le_ae_restrict h.ae_eq_mk lemma add_measure {f : α → β} (hμ : ae_measurable f μ) (hν : ae_measurable f ν) : ae_measurable f (μ + ν) := begin let s := {x | f x ≠ hμ.mk f x}, have : μ s = 0 := hμ.ae_eq_mk, obtain ⟨t, st, t_meas, μt⟩ : ∃ t, s ⊆ t ∧ measurable_set t ∧ μ t = 0 := exists_measurable_superset_of_null this, let g : α → β := t.piecewise (hν.mk f) (hμ.mk f), refine ⟨g, measurable.piecewise t_meas hν.measurable_mk hμ.measurable_mk, _⟩, change μ {x | f x ≠ g x} + ν {x | f x ≠ g x} = 0, suffices : μ {x | f x ≠ g x} = 0 ∧ ν {x | f x ≠ g x} = 0, by simp [this.1, this.2], have ht : {x | f x ≠ g x} ⊆ t, { assume x hx, by_contra h, simp only [g, h, mem_set_of_eq, ne.def, not_false_iff, piecewise_eq_of_not_mem] at hx, exact h (st hx) }, split, { have : μ {x | f x ≠ g x} ≤ μ t := measure_mono ht, rw μt at this, exact le_antisymm this bot_le }, { have : {x | f x ≠ g x} ⊆ {x | f x ≠ hν.mk f x}, { assume x hx, simpa [ht hx, g] using hx }, apply le_antisymm _ bot_le, calc ν {x | f x ≠ g x} ≤ ν {x | f x ≠ hν.mk f x} : measure_mono this ... = 0 : hν.ae_eq_mk } end lemma smul_measure (h : ae_measurable f μ) (c : ℝ≥0∞) : ae_measurable f (c • μ) := ⟨h.mk f, h.measurable_mk, ae_smul_measure h.ae_eq_mk c⟩ lemma comp_measurable [measurable_space δ] {f : α → δ} {g : δ → β} (hg : ae_measurable g (map f μ)) (hf : measurable f) : ae_measurable (g ∘ f) μ := ⟨hg.mk g ∘ f, hg.measurable_mk.comp hf, ae_eq_comp hf hg.ae_eq_mk⟩ lemma comp_measurable' {δ} [measurable_space δ] {ν : measure δ} {f : α → δ} {g : δ → β} (hg : ae_measurable g ν) (hf : measurable f) (h : map f μ ≪ ν) : ae_measurable (g ∘ f) μ := (hg.mono' h).comp_measurable hf lemma prod_mk {γ : Type*} [measurable_space γ] {f : α → β} {g : α → γ} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ x, (f x, g x)) μ := ⟨λ a, (hf.mk f a, hg.mk g a), hf.measurable_mk.prod_mk hg.measurable_mk, eventually_eq.prod_mk hf.ae_eq_mk hg.ae_eq_mk⟩ lemma null_measurable_set (h : ae_measurable f μ) {s : set β} (hs : measurable_set s) : null_measurable_set μ (f ⁻¹' s) := begin apply null_measurable_set_iff_ae.2, refine ⟨(h.mk f) ⁻¹' s, h.measurable_mk hs, _⟩, filter_upwards [h.ae_eq_mk], assume x hx, change (f x ∈ s) = ((h.mk f) x ∈ s), rwa hx end end ae_measurable lemma ae_measurable_congr (h : f =ᵐ[μ] g) : ae_measurable f μ ↔ ae_measurable g μ := ⟨λ hf, ae_measurable.congr hf h, λ hg, ae_measurable.congr hg h.symm⟩ @[simp] lemma ae_measurable_add_measure_iff : ae_measurable f (μ + ν) ↔ ae_measurable f μ ∧ ae_measurable f ν := ⟨λ h, ⟨h.mono_measure (measure.le_add_right (le_refl _)), h.mono_measure (measure.le_add_left (le_refl _))⟩, λ h, h.1.add_measure h.2⟩ @[simp] lemma ae_measurable_const {b : β} : ae_measurable (λ a : α, b) μ := measurable_const.ae_measurable @[simp] lemma ae_measurable_smul_measure_iff {c : ℝ≥0∞} (hc : c ≠ 0) : ae_measurable f (c • μ) ↔ ae_measurable f μ := ⟨λ h, ⟨h.mk f, h.measurable_mk, (ae_smul_measure_iff hc).1 h.ae_eq_mk⟩, λ h, ⟨h.mk f, h.measurable_mk, (ae_smul_measure_iff hc).2 h.ae_eq_mk⟩⟩ lemma measurable.comp_ae_measurable [measurable_space δ] {f : α → δ} {g : δ → β} (hg : measurable g) (hf : ae_measurable f μ) : ae_measurable (g ∘ f) μ := ⟨g ∘ hf.mk f, hg.comp hf.measurable_mk, eventually_eq.fun_comp hf.ae_eq_mk _⟩ lemma ae_measurable_of_zero_measure {f : α → β} : ae_measurable f 0 := begin by_cases h : nonempty α, { exact (@ae_measurable_const _ _ _ _ _ (f h.some)).congr rfl }, { exact (measurable_of_not_nonempty h f).ae_measurable } end end namespace is_compact variables [topological_space α] [measurable_space α] {μ : measure α} {s : set α} lemma finite_measure_of_nhds_within (hs : is_compact s) : (∀ a ∈ s, μ.finite_at_filter (𝓝[s] a)) → μ s < ∞ := by simpa only [← measure.compl_mem_cofinite, measure.finite_at_filter] using hs.compl_mem_sets_of_nhds_within lemma finite_measure [locally_finite_measure μ] (hs : is_compact s) : μ s < ∞ := hs.finite_measure_of_nhds_within $ λ a ha, μ.finite_at_nhds_within _ _ lemma measure_zero_of_nhds_within (hs : is_compact s) : (∀ a ∈ s, ∃ t ∈ 𝓝[s] a, μ t = 0) → μ s = 0 := by simpa only [← compl_mem_ae_iff] using hs.compl_mem_sets_of_nhds_within end is_compact lemma metric.bounded.finite_measure [metric_space α] [proper_space α] [measurable_space α] {μ : measure α} [locally_finite_measure μ] {s : set α} (hs : metric.bounded s) : μ s < ∞ := (measure_mono subset_closure).trans_lt (metric.compact_iff_closed_bounded.2 ⟨is_closed_closure, metric.bounded_closure_of_bounded hs⟩).finite_measure
8efc94732f5b5d7e050899cff659cdef5ea8c3bd
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/linear_algebra/finsupp.lean
e97cbe551801fea1b02ef544153d96ddd964c69e
[ "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
44,042
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import data.finsupp.defs import linear_algebra.pi import linear_algebra.span /-! # Properties of the module `α →₀ M` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Given an `R`-module `M`, the `R`-module structure on `α →₀ M` is defined in `data.finsupp.basic`. In this file we define `finsupp.supported s` to be the set `{f : α →₀ M | f.support ⊆ s}` interpreted as a submodule of `α →₀ M`. We also define `linear_map` versions of various maps: * `finsupp.lsingle a : M →ₗ[R] ι →₀ M`: `finsupp.single a` as a linear map; * `finsupp.lapply a : (ι →₀ M) →ₗ[R] M`: the map `λ f, f a` as a linear map; * `finsupp.lsubtype_domain (s : set α) : (α →₀ M) →ₗ[R] (s →₀ M)`: restriction to a subtype as a linear map; * `finsupp.restrict_dom`: `finsupp.filter` as a linear map to `finsupp.supported s`; * `finsupp.lsum`: `finsupp.sum` or `finsupp.lift_add_hom` as a `linear_map`; * `finsupp.total α M R (v : ι → M)`: sends `l : ι → R` to the linear combination of `v i` with coefficients `l i`; * `finsupp.total_on`: a restricted version of `finsupp.total` with domain `finsupp.supported R R s` and codomain `submodule.span R (v '' s)`; * `finsupp.supported_equiv_finsupp`: a linear equivalence between the functions `α →₀ M` supported on `s` and the functions `s →₀ M`; * `finsupp.lmap_domain`: a linear map version of `finsupp.map_domain`; * `finsupp.dom_lcongr`: a `linear_equiv` version of `finsupp.dom_congr`; * `finsupp.congr`: if the sets `s` and `t` are equivalent, then `supported M R s` is equivalent to `supported M R t`; * `finsupp.lcongr`: a `linear_equiv`alence between `α →₀ M` and `β →₀ N` constructed using `e : α ≃ β` and `e' : M ≃ₗ[R] N`. ## Tags function with finite support, module, linear algebra -/ noncomputable theory open set linear_map submodule open_locale classical big_operators namespace finsupp variables {α : Type*} {M : Type*} {N : Type*} {P : Type*} {R : Type*} {S : Type*} variables [semiring R] [semiring S] [add_comm_monoid M] [module R M] variables [add_comm_monoid N] [module R N] variables [add_comm_monoid P] [module R P] /-- Interpret `finsupp.single a` as a linear map. -/ def lsingle (a : α) : M →ₗ[R] (α →₀ M) := { map_smul' := assume a b, (smul_single _ _ _).symm, ..finsupp.single_add_hom a } /-- Two `R`-linear maps from `finsupp X M` which agree on each `single x y` agree everywhere. -/ lemma lhom_ext ⦃φ ψ : (α →₀ M) →ₗ[R] N⦄ (h : ∀ a b, φ (single a b) = ψ (single a b)) : φ = ψ := linear_map.to_add_monoid_hom_injective $ add_hom_ext h /-- Two `R`-linear maps from `finsupp X M` which agree on each `single x y` agree everywhere. We formulate this fact using equality of linear maps `φ.comp (lsingle a)` and `ψ.comp (lsingle a)` so that the `ext` tactic can apply a type-specific extensionality lemma to prove equality of these maps. E.g., if `M = R`, then it suffices to verify `φ (single a 1) = ψ (single a 1)`. -/ @[ext] lemma lhom_ext' ⦃φ ψ : (α →₀ M) →ₗ[R] N⦄ (h : ∀ a, φ.comp (lsingle a) = ψ.comp (lsingle a)) : φ = ψ := lhom_ext $ λ a, linear_map.congr_fun (h a) /-- Interpret `λ (f : α →₀ M), f a` as a linear map. -/ def lapply (a : α) : (α →₀ M) →ₗ[R] M := { map_smul' := assume a b, rfl, ..finsupp.apply_add_hom a } /-- Forget that a function is finitely supported. This is the linear version of `finsupp.to_fun`. -/ @[simps] def lcoe_fun : (α →₀ M) →ₗ[R] α → M := { to_fun := coe_fn, map_add' := λ x y, by { ext, simp }, map_smul' := λ x y, by { ext, simp } } section lsubtype_domain variables (s : set α) /-- Interpret `finsupp.subtype_domain s` as a linear map. -/ def lsubtype_domain : (α →₀ M) →ₗ[R] (s →₀ M) := { to_fun := subtype_domain (λx, x ∈ s), map_add' := λ a b, subtype_domain_add, map_smul' := λ c a, ext $ λ a, rfl } lemma lsubtype_domain_apply (f : α →₀ M) : (lsubtype_domain s : (α →₀ M) →ₗ[R] (s →₀ M)) f = subtype_domain (λx, x ∈ s) f := rfl end lsubtype_domain @[simp] lemma lsingle_apply (a : α) (b : M) : (lsingle a : M →ₗ[R] (α →₀ M)) b = single a b := rfl @[simp] lemma lapply_apply (a : α) (f : α →₀ M) : (lapply a : (α →₀ M) →ₗ[R] M) f = f a := rfl @[simp] lemma ker_lsingle (a : α) : (lsingle a : M →ₗ[R] (α →₀ M)).ker = ⊥ := ker_eq_bot_of_injective (single_injective a) lemma lsingle_range_le_ker_lapply (s t : set α) (h : disjoint s t) : (⨆a∈s, (lsingle a : M →ₗ[R] (α →₀ M)).range) ≤ (⨅a∈t, ker (lapply a : (α →₀ M) →ₗ[R] M)) := begin refine supr_le (assume a₁, supr_le $ assume h₁, range_le_iff_comap.2 _), simp only [(ker_comp _ _).symm, eq_top_iff, set_like.le_def, mem_ker, comap_infi, mem_infi], assume b hb a₂ h₂, have : a₁ ≠ a₂ := assume eq, h.le_bot ⟨h₁, eq.symm ▸ h₂⟩, exact single_eq_of_ne this end lemma infi_ker_lapply_le_bot : (⨅a, ker (lapply a : (α →₀ M) →ₗ[R] M)) ≤ ⊥ := begin simp only [set_like.le_def, mem_infi, mem_ker, mem_bot, lapply_apply], exact assume a h, finsupp.ext h end lemma supr_lsingle_range : (⨆a, (lsingle a : M →ₗ[R] (α →₀ M)).range) = ⊤ := begin refine (eq_top_iff.2 $ set_like.le_def.2 $ assume f _, _), rw [← sum_single f], exact sum_mem (assume a ha, submodule.mem_supr_of_mem a ⟨_, rfl⟩), end lemma disjoint_lsingle_lsingle (s t : set α) (hs : disjoint s t) : disjoint (⨆a∈s, (lsingle a : M →ₗ[R] (α →₀ M)).range) (⨆a∈t, (lsingle a : M →ₗ[R] (α →₀ M)).range) := begin refine (disjoint.mono (lsingle_range_le_ker_lapply _ _ $ disjoint_compl_right) (lsingle_range_le_ker_lapply _ _ $ disjoint_compl_right)) _, rw disjoint_iff_inf_le, refine (le_trans (le_infi $ assume i, _) infi_ker_lapply_le_bot), classical, by_cases his : i ∈ s, { by_cases hit : i ∈ t, { exact (hs.le_bot ⟨his, hit⟩).elim }, exact inf_le_of_right_le (infi_le_of_le i $ infi_le _ hit) }, exact inf_le_of_left_le (infi_le_of_le i $ infi_le _ his) end lemma span_single_image (s : set M) (a : α) : submodule.span R (single a '' s) = (submodule.span R s).map (lsingle a : M →ₗ[R] (α →₀ M)) := by rw ← span_image; refl variables (M R) /-- `finsupp.supported M R s` is the `R`-submodule of all `p : α →₀ M` such that `p.support ⊆ s`. -/ def supported (s : set α) : submodule R (α →₀ M) := begin refine ⟨ {p | ↑p.support ⊆ s }, _, _, _ ⟩, { assume p q hp hq, refine subset.trans (subset.trans (finset.coe_subset.2 support_add) _) (union_subset hp hq), rw [finset.coe_union] }, { simp only [subset_def, finset.mem_coe, set.mem_set_of_eq, mem_support_iff, zero_apply], assume h ha, exact (ha rfl).elim }, { assume a p hp, refine subset.trans (finset.coe_subset.2 support_smul) hp } end variables {M} lemma mem_supported {s : set α} (p : α →₀ M) : p ∈ (supported M R s) ↔ ↑p.support ⊆ s := iff.rfl lemma mem_supported' {s : set α} (p : α →₀ M) : p ∈ supported M R s ↔ ∀ x ∉ s, p x = 0 := by haveI := classical.dec_pred (λ (x : α), x ∈ s); simp [mem_supported, set.subset_def, not_imp_comm] lemma mem_supported_support (p : α →₀ M) : p ∈ finsupp.supported M R (p.support : set α) := by rw finsupp.mem_supported lemma single_mem_supported {s : set α} {a : α} (b : M) (h : a ∈ s) : single a b ∈ supported M R s := set.subset.trans support_single_subset (finset.singleton_subset_set_iff.2 h) lemma supported_eq_span_single (s : set α) : supported R R s = span R ((λ i, single i 1) '' s) := begin refine (span_eq_of_le _ _ (set_like.le_def.2 $ λ l hl, _)).symm, { rintro _ ⟨_, hp, rfl ⟩ , exact single_mem_supported R 1 hp }, { rw ← l.sum_single, refine sum_mem (λ i il, _), convert @smul_mem R (α →₀ R) _ _ _ _ (single i 1) (l i) _, { simp }, apply subset_span, apply set.mem_image_of_mem _ (hl il) } end variables (M R) /-- Interpret `finsupp.filter s` as a linear map from `α →₀ M` to `supported M R s`. -/ def restrict_dom (s : set α) : (α →₀ M) →ₗ[R] supported M R s := linear_map.cod_restrict _ { to_fun := filter (∈ s), map_add' := λ l₁ l₂, filter_add, map_smul' := λ a l, filter_smul } (λ l, (mem_supported' _ _).2 $ λ x, filter_apply_neg (∈ s) l) variables {M R} section @[simp] theorem restrict_dom_apply (s : set α) (l : α →₀ M) : ((restrict_dom M R s : (α →₀ M) →ₗ[R] supported M R s) l : α →₀ M) = finsupp.filter (∈ s) l := rfl end theorem restrict_dom_comp_subtype (s : set α) : (restrict_dom M R s).comp (submodule.subtype _) = linear_map.id := begin ext l a, by_cases a ∈ s; simp [h], exact ((mem_supported' R l.1).1 l.2 a h).symm end theorem range_restrict_dom (s : set α) : (restrict_dom M R s).range = ⊤ := range_eq_top.2 $ function.right_inverse.surjective $ linear_map.congr_fun (restrict_dom_comp_subtype s) theorem supported_mono {s t : set α} (st : s ⊆ t) : supported M R s ≤ supported M R t := λ l h, set.subset.trans h st @[simp] theorem supported_empty : supported M R (∅ : set α) = ⊥ := eq_bot_iff.2 $ λ l h, (submodule.mem_bot R).2 $ by ext; simp [*, mem_supported'] at * @[simp] theorem supported_univ : supported M R (set.univ : set α) = ⊤ := eq_top_iff.2 $ λ l _, set.subset_univ _ theorem supported_Union {δ : Type*} (s : δ → set α) : supported M R (⋃ i, s i) = ⨆ i, supported M R (s i) := begin refine le_antisymm _ (supr_le $ λ i, supported_mono $ set.subset_Union _ _), haveI := classical.dec_pred (λ x, x ∈ (⋃ i, s i)), suffices : ((submodule.subtype _).comp (restrict_dom M R (⋃ i, s i))).range ≤ ⨆ i, supported M R (s i), { rwa [linear_map.range_comp, range_restrict_dom, submodule.map_top, range_subtype] at this }, rw [range_le_iff_comap, eq_top_iff], rintro l ⟨⟩, apply finsupp.induction l, { exact zero_mem _ }, refine λ x a l hl a0, add_mem _, by_cases (∃ i, x ∈ s i); simp [h], { cases h with i hi, exact le_supr (λ i, supported M R (s i)) i (single_mem_supported R _ hi) } end theorem supported_union (s t : set α) : supported M R (s ∪ t) = supported M R s ⊔ supported M R t := by erw [set.union_eq_Union, supported_Union, supr_bool_eq]; refl theorem supported_Inter {ι : Type*} (s : ι → set α) : supported M R (⋂ i, s i) = ⨅ i, supported M R (s i) := submodule.ext $ λ x, by simp [mem_supported, subset_Inter_iff] theorem supported_inter (s t : set α) : supported M R (s ∩ t) = supported M R s ⊓ supported M R t := by rw [set.inter_eq_Inter, supported_Inter, infi_bool_eq]; refl theorem disjoint_supported_supported {s t : set α} (h : disjoint s t) : disjoint (supported M R s) (supported M R t) := disjoint_iff.2 $ by rw [← supported_inter, disjoint_iff_inter_eq_empty.1 h, supported_empty] theorem disjoint_supported_supported_iff [nontrivial M] {s t : set α} : disjoint (supported M R s) (supported M R t) ↔ disjoint s t := begin refine ⟨λ h, set.disjoint_left.mpr $ λ x hx1 hx2, _, disjoint_supported_supported⟩, rcases exists_ne (0 : M) with ⟨y, hy⟩, have := h.le_bot ⟨single_mem_supported R y hx1, single_mem_supported R y hx2⟩, rw [mem_bot, single_eq_zero] at this, exact hy this end /-- Interpret `finsupp.restrict_support_equiv` as a linear equivalence between `supported M R s` and `s →₀ M`. -/ def supported_equiv_finsupp (s : set α) : (supported M R s) ≃ₗ[R] (s →₀ M) := begin let F : (supported M R s) ≃ (s →₀ M) := restrict_support_equiv s M, refine F.to_linear_equiv _, have : (F : (supported M R s) → (↥s →₀ M)) = ((lsubtype_domain s : (α →₀ M) →ₗ[R] (s →₀ M)).comp (submodule.subtype (supported M R s))) := rfl, rw this, exact linear_map.is_linear _ end section lsum variables (S) [module S N] [smul_comm_class R S N] /-- Lift a family of linear maps `M →ₗ[R] N` indexed by `x : α` to a linear map from `α →₀ M` to `N` using `finsupp.sum`. This is an upgraded version of `finsupp.lift_add_hom`. See note [bundled maps over different rings] for why separate `R` and `S` semirings are used. -/ def lsum : (α → M →ₗ[R] N) ≃ₗ[S] ((α →₀ M) →ₗ[R] N) := { to_fun := λ F, { to_fun := λ d, d.sum (λ i, F i), map_add' := (lift_add_hom (λ x, (F x).to_add_monoid_hom)).map_add, map_smul' := λ c f, by simp [sum_smul_index', smul_sum] }, inv_fun := λ F x, F.comp (lsingle x), left_inv := λ F, by { ext x y, simp }, right_inv := λ F, by { ext x y, simp }, map_add' := λ F G, by { ext x y, simp }, map_smul' := λ F G, by { ext x y, simp } } @[simp] lemma coe_lsum (f : α → M →ₗ[R] N) : (lsum S f : (α →₀ M) → N) = λ d, d.sum (λ i, f i) := rfl theorem lsum_apply (f : α → M →ₗ[R] N) (l : α →₀ M) : finsupp.lsum S f l = l.sum (λ b, f b) := rfl theorem lsum_single (f : α → M →ₗ[R] N) (i : α) (m : M) : finsupp.lsum S f (finsupp.single i m) = f i m := finsupp.sum_single_index (f i).map_zero theorem lsum_symm_apply (f : (α →₀ M) →ₗ[R] N) (x : α) : (lsum S).symm f x = f.comp (lsingle x) := rfl end lsum section variables (M) (R) (X : Type*) (S) [module S M] [smul_comm_class R S M] /-- A slight rearrangement from `lsum` gives us the bijection underlying the free-forgetful adjunction for R-modules. -/ noncomputable def lift : (X → M) ≃+ ((X →₀ R) →ₗ[R] M) := (add_equiv.arrow_congr (equiv.refl X) (ring_lmap_equiv_self R ℕ M).to_add_equiv.symm).trans (lsum _ : _ ≃ₗ[ℕ] _).to_add_equiv @[simp] lemma lift_symm_apply (f) (x) : ((lift M R X).symm f) x = f (single x 1) := rfl @[simp] lemma lift_apply (f) (g) : ((lift M R X) f) g = g.sum (λ x r, r • f x) := rfl /-- Given compatible `S` and `R`-module structures on `M` and a type `X`, the set of functions `X → M` is `S`-linearly equivalent to the `R`-linear maps from the free `R`-module on `X` to `M`. -/ noncomputable def llift : (X → M) ≃ₗ[S] ((X →₀ R) →ₗ[R] M) := { map_smul' := begin intros, dsimp, ext, simp only [coe_comp, function.comp_app, lsingle_apply, lift_apply, pi.smul_apply, sum_single_index, zero_smul, one_smul, linear_map.smul_apply], end, ..lift M R X } @[simp] lemma llift_apply (f : X → M) (x : X →₀ R) : llift M R S X f x = lift M R X f x := rfl @[simp] lemma llift_symm_apply (f : (X →₀ R) →ₗ[R] M) (x : X) : (llift M R S X).symm f x = f (single x 1) := rfl end section lmap_domain variables {α' : Type*} {α'' : Type*} (M R) /-- Interpret `finsupp.map_domain` as a linear map. -/ def lmap_domain (f : α → α') : (α →₀ M) →ₗ[R] (α' →₀ M) := { to_fun := map_domain f, map_add' := λ a b, map_domain_add, map_smul' := map_domain_smul } @[simp] theorem lmap_domain_apply (f : α → α') (l : α →₀ M) : (lmap_domain M R f : (α →₀ M) →ₗ[R] (α' →₀ M)) l = map_domain f l := rfl @[simp] theorem lmap_domain_id : (lmap_domain M R id : (α →₀ M) →ₗ[R] α →₀ M) = linear_map.id := linear_map.ext $ λ l, map_domain_id theorem lmap_domain_comp (f : α → α') (g : α' → α'') : lmap_domain M R (g ∘ f) = (lmap_domain M R g).comp (lmap_domain M R f) := linear_map.ext $ λ l, map_domain_comp theorem supported_comap_lmap_domain (f : α → α') (s : set α') : supported M R (f ⁻¹' s) ≤ (supported M R s).comap (lmap_domain M R f) := λ l (hl : ↑l.support ⊆ f ⁻¹' s), show ↑(map_domain f l).support ⊆ s, begin rw [← set.image_subset_iff, ← finset.coe_image] at hl, exact set.subset.trans map_domain_support hl end theorem lmap_domain_supported [nonempty α] (f : α → α') (s : set α) : (supported M R s).map (lmap_domain M R f) = supported M R (f '' s) := begin inhabit α, refine le_antisymm (map_le_iff_le_comap.2 $ le_trans (supported_mono $ set.subset_preimage_image _ _) (supported_comap_lmap_domain _ _ _ _)) _, intros l hl, refine ⟨(lmap_domain M R (function.inv_fun_on f s) : (α' →₀ M) →ₗ[R] α →₀ M) l, λ x hx, _, _⟩, { rcases finset.mem_image.1 (map_domain_support hx) with ⟨c, hc, rfl⟩, exact function.inv_fun_on_mem (by simpa using hl hc) }, { rw [← linear_map.comp_apply, ← lmap_domain_comp], refine (map_domain_congr $ λ c hc, _).trans map_domain_id, exact function.inv_fun_on_eq (by simpa using hl hc) } end theorem lmap_domain_disjoint_ker (f : α → α') {s : set α} (H : ∀ a b ∈ s, f a = f b → a = b) : disjoint (supported M R s) (lmap_domain M R f).ker := begin rw disjoint_iff_inf_le, rintro l ⟨h₁, h₂⟩, rw [set_like.mem_coe, mem_ker, lmap_domain_apply, map_domain] at h₂, simp, ext x, haveI := classical.dec_pred (λ x, x ∈ s), by_cases xs : x ∈ s, { have : finsupp.sum l (λ a, finsupp.single (f a)) (f x) = 0, {rw h₂, refl}, rw [finsupp.sum_apply, finsupp.sum, finset.sum_eq_single x] at this, { simpa [finsupp.single_apply] }, { intros y hy xy, simp [mt (H _ (h₁ hy) _ xs) xy] }, { simp {contextual := tt} } }, { by_contra h, exact xs (h₁ $ finsupp.mem_support_iff.2 h) } end end lmap_domain section lcomap_domain variables {β : Type*} {R M} /-- Given `f : α → β` and a proof `hf` that `f` is injective, `lcomap_domain f hf` is the linear map sending `l : β →₀ M` to the finitely supported function from `α` to `M` given by composing `l` with `f`. This is the linear version of `finsupp.comap_domain`. -/ def lcomap_domain (f : α → β) (hf : function.injective f) : (β →₀ M) →ₗ[R] α →₀ M:= { to_fun := λ l, finsupp.comap_domain f l (hf.inj_on _), map_add' := λ x y, by { ext, simp }, map_smul' := λ c x, by { ext, simp } } end lcomap_domain section total variables (α) {α' : Type*} (M) {M' : Type*} (R) [add_comm_monoid M'] [module R M'] (v : α → M) {v' : α' → M'} /-- Interprets (l : α →₀ R) as linear combination of the elements in the family (v : α → M) and evaluates this linear combination. -/ protected def total : (α →₀ R) →ₗ[R] M := finsupp.lsum ℕ (λ i, linear_map.id.smul_right (v i)) variables {α M v} theorem total_apply (l : α →₀ R) : finsupp.total α M R v l = l.sum (λ i a, a • v i) := rfl theorem total_apply_of_mem_supported {l : α →₀ R} {s : finset α} (hs : l ∈ supported R R (↑s : set α)) : finsupp.total α M R v l = s.sum (λ i, l i • v i) := finset.sum_subset hs $ λ x _ hxg, show l x • v x = 0, by rw [not_mem_support_iff.1 hxg, zero_smul] @[simp] theorem total_single (c : R) (a : α) : finsupp.total α M R v (single a c) = c • (v a) := by simp [total_apply, sum_single_index] lemma total_zero_apply (x : α →₀ R) : (finsupp.total α M R 0) x = 0 := by simp [finsupp.total_apply] variables (α M) @[simp] lemma total_zero : finsupp.total α M R 0 = 0 := linear_map.ext (total_zero_apply R) variables {α M} theorem apply_total (f : M →ₗ[R] M') (v) (l : α →₀ R) : f (finsupp.total α M R v l) = finsupp.total α M' R (f ∘ v) l := by apply finsupp.induction_linear l; simp { contextual := tt, } theorem total_unique [unique α] (l : α →₀ R) (v) : finsupp.total α M R v l = l default • v default := by rw [← total_single, ← unique_single l] lemma total_surjective (h : function.surjective v) : function.surjective (finsupp.total α M R v) := begin intro x, obtain ⟨y, hy⟩ := h x, exact ⟨finsupp.single y 1, by simp [hy]⟩ end theorem total_range (h : function.surjective v) : (finsupp.total α M R v).range = ⊤ := range_eq_top.2 $ total_surjective R h /-- Any module is a quotient of a free module. This is stated as surjectivity of `finsupp.total M M R id : (M →₀ R) →ₗ[R] M`. -/ lemma total_id_surjective (M) [add_comm_monoid M] [module R M] : function.surjective (finsupp.total M M R id) := total_surjective R function.surjective_id lemma range_total : (finsupp.total α M R v).range = span R (range v) := begin ext x, split, { intros hx, rw [linear_map.mem_range] at hx, rcases hx with ⟨l, hl⟩, rw ← hl, rw finsupp.total_apply, exact sum_mem (λ i hi, submodule.smul_mem _ _ (subset_span (mem_range_self i))) }, { apply span_le.2, intros x hx, rcases hx with ⟨i, hi⟩, rw [set_like.mem_coe, linear_map.mem_range], use finsupp.single i 1, simp [hi] } end theorem lmap_domain_total (f : α → α') (g : M →ₗ[R] M') (h : ∀ i, g (v i) = v' (f i)) : (finsupp.total α' M' R v').comp (lmap_domain R R f) = g.comp (finsupp.total α M R v) := by ext l; simp [total_apply, finsupp.sum_map_domain_index, add_smul, h] theorem total_comp_lmap_domain (f : α → α') : (finsupp.total α' M' R v').comp (finsupp.lmap_domain R R f) = (finsupp.total α M' R (v' ∘ f)) := by { ext, simp } @[simp] theorem total_emb_domain (f : α ↪ α') (l : α →₀ R) : (finsupp.total α' M' R v') (emb_domain f l) = (finsupp.total α M' R (v' ∘ f)) l := by simp [total_apply, finsupp.sum, support_emb_domain, emb_domain_apply] @[simp] theorem total_map_domain (f : α → α') (l : α →₀ R) : (finsupp.total α' M' R v') (map_domain f l) = (finsupp.total α M' R (v' ∘ f)) l := linear_map.congr_fun (total_comp_lmap_domain _ _) l @[simp] theorem total_equiv_map_domain (f : α ≃ α') (l : α →₀ R) : (finsupp.total α' M' R v') (equiv_map_domain f l) = (finsupp.total α M' R (v' ∘ f)) l := by rw [equiv_map_domain_eq_map_domain, total_map_domain] /-- A version of `finsupp.range_total` which is useful for going in the other direction -/ theorem span_eq_range_total (s : set M) : span R s = (finsupp.total s M R coe).range := by rw [range_total, subtype.range_coe_subtype, set.set_of_mem_eq] theorem mem_span_iff_total (s : set M) (x : M) : x ∈ span R s ↔ ∃ l : s →₀ R, finsupp.total s M R coe l = x := (set_like.ext_iff.1 $ span_eq_range_total _ _) x variables {R} lemma mem_span_range_iff_exists_finsupp {v : α → M} {x : M} : x ∈ span R (range v) ↔ ∃ (c : α →₀ R), c.sum (λ i a, a • v i) = x := by simp only [←finsupp.range_total, linear_map.mem_range, finsupp.total_apply] variables (R) theorem span_image_eq_map_total (s : set α): span R (v '' s) = submodule.map (finsupp.total α M R v) (supported R R s) := begin apply span_eq_of_le, { intros x hx, rw set.mem_image at hx, apply exists.elim hx, intros i hi, exact ⟨_, finsupp.single_mem_supported R 1 hi.1, by simp [hi.2]⟩ }, { refine map_le_iff_le_comap.2 (λ z hz, _), have : ∀i, z i • v i ∈ span R (v '' s), { intro c, haveI := classical.dec_pred (λ x, x ∈ s), by_cases c ∈ s, { exact smul_mem _ _ (subset_span (set.mem_image_of_mem _ h)) }, { simp [(finsupp.mem_supported' R _).1 hz _ h] } }, refine sum_mem _, simp [this] } end theorem mem_span_image_iff_total {s : set α} {x : M} : x ∈ span R (v '' s) ↔ ∃ l ∈ supported R R s, finsupp.total α M R v l = x := by { rw span_image_eq_map_total, simp, } lemma total_option (v : option α → M) (f : option α →₀ R) : finsupp.total (option α) M R v f = f none • v none + finsupp.total α M R (v ∘ option.some) f.some := by rw [total_apply, sum_option_index_smul, total_apply] lemma total_total {α β : Type*} (A : α → M) (B : β → (α →₀ R)) (f : β →₀ R) : finsupp.total α M R A (finsupp.total β (α →₀ R) R B f) = finsupp.total β M R (λ b, finsupp.total α M R A (B b)) f := begin simp only [total_apply], apply induction_linear f, { simp only [sum_zero_index], }, { intros f₁ f₂ h₁ h₂, simp [sum_add_index, h₁, h₂, add_smul], }, { simp [sum_single_index, sum_smul_index, smul_sum, mul_smul], } end @[simp] lemma total_fin_zero (f : fin 0 → M) : finsupp.total (fin 0) M R f = 0 := by { ext i, apply fin_zero_elim i } variables (α) (M) (v) /-- `finsupp.total_on M v s` interprets `p : α →₀ R` as a linear combination of a subset of the vectors in `v`, mapping it to the span of those vectors. The subset is indicated by a set `s : set α` of indices. -/ protected def total_on (s : set α) : supported R R s →ₗ[R] span R (v '' s) := linear_map.cod_restrict _ ((finsupp.total _ _ _ v).comp (submodule.subtype (supported R R s))) $ λ ⟨l, hl⟩, (mem_span_image_iff_total _).2 ⟨l, hl, rfl⟩ variables {α} {M} {v} theorem total_on_range (s : set α) : (finsupp.total_on α M R v s).range = ⊤ := begin rw [finsupp.total_on, linear_map.range_eq_map, linear_map.map_cod_restrict, ← linear_map.range_le_iff_comap, range_subtype, submodule.map_top, linear_map.range_comp, range_subtype], exact (span_image_eq_map_total _ _).le end theorem total_comp (f : α' → α) : (finsupp.total α' M R (v ∘ f)) = (finsupp.total α M R v).comp (lmap_domain R R f) := by { ext, simp [total_apply] } lemma total_comap_domain (f : α → α') (l : α' →₀ R) (hf : set.inj_on f (f ⁻¹' ↑l.support)) : finsupp.total α M R v (finsupp.comap_domain f l hf) = (l.support.preimage f hf).sum (λ i, (l (f i)) • (v i)) := by rw finsupp.total_apply; refl lemma total_on_finset {s : finset α} {f : α → R} (g : α → M) (hf : ∀ a, f a ≠ 0 → a ∈ s): finsupp.total α M R g (finsupp.on_finset s f hf) = finset.sum s (λ (x : α), f x • g x) := begin simp only [finsupp.total_apply, finsupp.sum, finsupp.on_finset_apply, finsupp.support_on_finset], rw finset.sum_filter_of_ne, intros x hx h, contrapose! h, simp [h], end end total /-- An equivalence of domains induces a linear equivalence of finitely supported functions. This is `finsupp.dom_congr` as a `linear_equiv`. See also `linear_map.fun_congr_left` for the case of arbitrary functions. -/ protected def dom_lcongr {α₁ α₂ : Type*} (e : α₁ ≃ α₂) : (α₁ →₀ M) ≃ₗ[R] (α₂ →₀ M) := (finsupp.dom_congr e : (α₁ →₀ M) ≃+ (α₂ →₀ M)).to_linear_equiv $ by simpa only [equiv_map_domain_eq_map_domain, dom_congr_apply] using (lmap_domain M R e).map_smul @[simp] lemma dom_lcongr_apply {α₁ : Type*} {α₂ : Type*} (e : α₁ ≃ α₂) (v : α₁ →₀ M) : (finsupp.dom_lcongr e : _ ≃ₗ[R] _) v = finsupp.dom_congr e v := rfl @[simp] lemma dom_lcongr_refl : finsupp.dom_lcongr (equiv.refl α) = linear_equiv.refl R (α →₀ M) := linear_equiv.ext $ λ _, equiv_map_domain_refl _ lemma dom_lcongr_trans {α₁ α₂ α₃ : Type*} (f : α₁ ≃ α₂) (f₂ : α₂ ≃ α₃) : (finsupp.dom_lcongr f).trans (finsupp.dom_lcongr f₂) = (finsupp.dom_lcongr (f.trans f₂) : (_ →₀ M) ≃ₗ[R] _) := linear_equiv.ext $ λ _, (equiv_map_domain_trans _ _ _).symm @[simp] lemma dom_lcongr_symm {α₁ α₂ : Type*} (f : α₁ ≃ α₂) : ((finsupp.dom_lcongr f).symm : (_ →₀ M) ≃ₗ[R] _) = finsupp.dom_lcongr f.symm := linear_equiv.ext $ λ x, rfl @[simp] theorem dom_lcongr_single {α₁ : Type*} {α₂ : Type*} (e : α₁ ≃ α₂) (i : α₁) (m : M) : (finsupp.dom_lcongr e : _ ≃ₗ[R] _) (finsupp.single i m) = finsupp.single (e i) m := by simp [finsupp.dom_lcongr, finsupp.dom_congr, equiv_map_domain_single] /-- An equivalence of sets induces a linear equivalence of `finsupp`s supported on those sets. -/ noncomputable def congr {α' : Type*} (s : set α) (t : set α') (e : s ≃ t) : supported M R s ≃ₗ[R] supported M R t := begin haveI := classical.dec_pred (λ x, x ∈ s), haveI := classical.dec_pred (λ x, x ∈ t), refine (finsupp.supported_equiv_finsupp s) ≪≫ₗ (_ ≪≫ₗ (finsupp.supported_equiv_finsupp t).symm), exact finsupp.dom_lcongr e end /-- `finsupp.map_range` as a `linear_map`. -/ @[simps] def map_range.linear_map (f : M →ₗ[R] N) : (α →₀ M) →ₗ[R] (α →₀ N) := { to_fun := (map_range f f.map_zero : (α →₀ M) → (α →₀ N)), map_smul' := λ c v, map_range_smul c v (f.map_smul c), ..map_range.add_monoid_hom f.to_add_monoid_hom } @[simp] lemma map_range.linear_map_id : map_range.linear_map linear_map.id = (linear_map.id : (α →₀ M) →ₗ[R] _):= linear_map.ext map_range_id lemma map_range.linear_map_comp (f : N →ₗ[R] P) (f₂ : M →ₗ[R] N) : (map_range.linear_map (f.comp f₂) : (α →₀ _) →ₗ[R] _) = (map_range.linear_map f).comp (map_range.linear_map f₂) := linear_map.ext $ map_range_comp _ _ _ _ _ @[simp] lemma map_range.linear_map_to_add_monoid_hom (f : M →ₗ[R] N) : (map_range.linear_map f).to_add_monoid_hom = (map_range.add_monoid_hom f.to_add_monoid_hom : (α →₀ M) →+ _):= add_monoid_hom.ext $ λ _, rfl /-- `finsupp.map_range` as a `linear_equiv`. -/ @[simps apply] def map_range.linear_equiv (e : M ≃ₗ[R] N) : (α →₀ M) ≃ₗ[R] (α →₀ N) := { to_fun := map_range e e.map_zero, inv_fun := map_range e.symm e.symm.map_zero, ..map_range.linear_map e.to_linear_map, ..map_range.add_equiv e.to_add_equiv} @[simp] lemma map_range.linear_equiv_refl : map_range.linear_equiv (linear_equiv.refl R M) = linear_equiv.refl R (α →₀ M) := linear_equiv.ext map_range_id lemma map_range.linear_equiv_trans (f : M ≃ₗ[R] N) (f₂ : N ≃ₗ[R] P) : (map_range.linear_equiv (f.trans f₂) : (α →₀ _) ≃ₗ[R] _) = (map_range.linear_equiv f).trans (map_range.linear_equiv f₂) := linear_equiv.ext $ map_range_comp _ _ _ _ _ @[simp] lemma map_range.linear_equiv_symm (f : M ≃ₗ[R] N) : ((map_range.linear_equiv f).symm : (α →₀ _) ≃ₗ[R] _) = map_range.linear_equiv f.symm := linear_equiv.ext $ λ x, rfl @[simp] lemma map_range.linear_equiv_to_add_equiv (f : M ≃ₗ[R] N) : (map_range.linear_equiv f).to_add_equiv = (map_range.add_equiv f.to_add_equiv : (α →₀ M) ≃+ _):= add_equiv.ext $ λ _, rfl @[simp] lemma map_range.linear_equiv_to_linear_map (f : M ≃ₗ[R] N) : (map_range.linear_equiv f).to_linear_map = (map_range.linear_map f.to_linear_map : (α →₀ M) →ₗ[R] _):= linear_map.ext $ λ _, rfl /-- An equivalence of domain and a linear equivalence of codomain induce a linear equivalence of the corresponding finitely supported functions. -/ def lcongr {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N) : (ι →₀ M) ≃ₗ[R] (κ →₀ N) := (finsupp.dom_lcongr e₁).trans (map_range.linear_equiv e₂) @[simp] theorem lcongr_single {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N) (i : ι) (m : M) : lcongr e₁ e₂ (finsupp.single i m) = finsupp.single (e₁ i) (e₂ m) := by simp [lcongr] @[simp] lemma lcongr_apply_apply {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N) (f : ι →₀ M) (k : κ) : lcongr e₁ e₂ f k = e₂ (f (e₁.symm k)) := rfl theorem lcongr_symm_single {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N) (k : κ) (n : N) : (lcongr e₁ e₂).symm (finsupp.single k n) = finsupp.single (e₁.symm k) (e₂.symm n) := begin apply_fun lcongr e₁ e₂ using (lcongr e₁ e₂).injective, simp, end @[simp] lemma lcongr_symm {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N) : (lcongr e₁ e₂).symm = lcongr e₁.symm e₂.symm := by { ext, refl } section sum variables (R) /-- The linear equivalence between `(α ⊕ β) →₀ M` and `(α →₀ M) × (β →₀ M)`. This is the `linear_equiv` version of `finsupp.sum_finsupp_equiv_prod_finsupp`. -/ @[simps apply symm_apply] def sum_finsupp_lequiv_prod_finsupp {α β : Type*} : ((α ⊕ β) →₀ M) ≃ₗ[R] (α →₀ M) × (β →₀ M) := { map_smul' := by { intros, ext; simp only [add_equiv.to_fun_eq_coe, prod.smul_fst, prod.smul_snd, smul_apply, snd_sum_finsupp_add_equiv_prod_finsupp, fst_sum_finsupp_add_equiv_prod_finsupp, ring_hom.id_apply] }, .. sum_finsupp_add_equiv_prod_finsupp } lemma fst_sum_finsupp_lequiv_prod_finsupp {α β : Type*} (f : (α ⊕ β) →₀ M) (x : α) : (sum_finsupp_lequiv_prod_finsupp R f).1 x = f (sum.inl x) := rfl lemma snd_sum_finsupp_lequiv_prod_finsupp {α β : Type*} (f : (α ⊕ β) →₀ M) (y : β) : (sum_finsupp_lequiv_prod_finsupp R f).2 y = f (sum.inr y) := rfl lemma sum_finsupp_lequiv_prod_finsupp_symm_inl {α β : Type*} (fg : (α →₀ M) × (β →₀ M)) (x : α) : ((sum_finsupp_lequiv_prod_finsupp R).symm fg) (sum.inl x) = fg.1 x := rfl lemma sum_finsupp_lequiv_prod_finsupp_symm_inr {α β : Type*} (fg : (α →₀ M) × (β →₀ M)) (y : β) : ((sum_finsupp_lequiv_prod_finsupp R).symm fg) (sum.inr y) = fg.2 y := rfl end sum section sigma variables {η : Type*} [fintype η] {ιs : η → Type*} [has_zero α] variables (R) /-- On a `fintype η`, `finsupp.split` is a linear equivalence between `(Σ (j : η), ιs j) →₀ M` and `Π j, (ιs j →₀ M)`. This is the `linear_equiv` version of `finsupp.sigma_finsupp_add_equiv_pi_finsupp`. -/ noncomputable def sigma_finsupp_lequiv_pi_finsupp {M : Type*} {ιs : η → Type*} [add_comm_monoid M] [module R M] : ((Σ j, ιs j) →₀ M) ≃ₗ[R] Π j, (ιs j →₀ M) := { map_smul' := λ c f, by { ext, simp }, .. sigma_finsupp_add_equiv_pi_finsupp } @[simp] lemma sigma_finsupp_lequiv_pi_finsupp_apply {M : Type*} {ιs : η → Type*} [add_comm_monoid M] [module R M] (f : (Σ j, ιs j) →₀ M) (j i) : sigma_finsupp_lequiv_pi_finsupp R f j i = f ⟨j, i⟩ := rfl @[simp] lemma sigma_finsupp_lequiv_pi_finsupp_symm_apply {M : Type*} {ιs : η → Type*} [add_comm_monoid M] [module R M] (f : Π j, (ιs j →₀ M)) (ji) : (finsupp.sigma_finsupp_lequiv_pi_finsupp R).symm f ji = f ji.1 ji.2 := rfl end sigma section prod /-- The linear equivalence between `α × β →₀ M` and `α →₀ β →₀ M`. This is the `linear_equiv` version of `finsupp.finsupp_prod_equiv`. -/ noncomputable def finsupp_prod_lequiv {α β : Type*} (R : Type*) {M : Type*} [semiring R] [add_comm_monoid M] [module R M] : (α × β →₀ M) ≃ₗ[R] (α →₀ β →₀ M) := { map_add' := λ f g, by { ext, simp [finsupp_prod_equiv, curry_apply] }, map_smul' := λ c f, by { ext, simp [finsupp_prod_equiv, curry_apply] }, .. finsupp_prod_equiv } @[simp] lemma finsupp_prod_lequiv_apply {α β R M : Type*} [semiring R] [add_comm_monoid M] [module R M] (f : α × β →₀ M) (x y) : finsupp_prod_lequiv R f x y = f (x, y) := by rw [finsupp_prod_lequiv, linear_equiv.coe_mk, finsupp_prod_equiv, finsupp.curry_apply] @[simp] lemma finsupp_prod_lequiv_symm_apply {α β R M : Type*} [semiring R] [add_comm_monoid M] [module R M] (f : α →₀ β →₀ M) (xy) : (finsupp_prod_lequiv R).symm f xy = f xy.1 xy.2 := by conv_rhs { rw [← (finsupp_prod_lequiv R).apply_symm_apply f, finsupp_prod_lequiv_apply, prod.mk.eta] } end prod end finsupp section fintype variables {α M : Type*} (R : Type*) [fintype α] [semiring R] [add_comm_monoid M] [module R M] variables (S : Type*) [semiring S] [module S M] [smul_comm_class R S M] variable (v : α → M) /-- `fintype.total R S v f` is the linear combination of vectors in `v` with weights in `f`. This variant of `finsupp.total` is defined on fintype indexed vectors. This map is linear in `v` if `R` is commutative, and always linear in `f`. See note [bundled maps over different rings] for why separate `R` and `S` semirings are used. -/ protected def fintype.total : (α → M) →ₗ[S] (α → R) →ₗ[R] M := { to_fun := λ v, { to_fun := λ f, ∑ i, f i • v i, map_add' := λ f g, by { simp_rw [← finset.sum_add_distrib, ← add_smul], refl }, map_smul' := λ r f, by { simp_rw [finset.smul_sum, smul_smul], refl } }, map_add' := λ u v, by { ext, simp [finset.sum_add_distrib, pi.add_apply, smul_add] }, map_smul' := λ r v, by { ext, simp [finset.smul_sum, smul_comm _ r] } } variables {S} lemma fintype.total_apply (f) : fintype.total R S v f = ∑ i, f i • v i := rfl @[simp] lemma fintype.total_apply_single (i : α) (r : R) : fintype.total R S v (pi.single i r) = r • v i := begin simp_rw [fintype.total_apply, pi.single_apply, ite_smul, zero_smul], rw [finset.sum_ite_eq', if_pos (finset.mem_univ _)] end variables (S) lemma finsupp.total_eq_fintype_total_apply (x : α → R) : finsupp.total α M R v ((finsupp.linear_equiv_fun_on_finite R R α).symm x) = fintype.total R S v x := begin apply finset.sum_subset, { exact finset.subset_univ _ }, { intros x _ hx, rw finsupp.not_mem_support_iff.mp hx, exact zero_smul _ _ } end lemma finsupp.total_eq_fintype_total : (finsupp.total α M R v).comp (finsupp.linear_equiv_fun_on_finite R R α).symm.to_linear_map = fintype.total R S v := linear_map.ext $ finsupp.total_eq_fintype_total_apply R S v variables {S} @[simp] lemma fintype.range_total : (fintype.total R S v).range = submodule.span R (set.range v) := by rw [← finsupp.total_eq_fintype_total, linear_map.range_comp, linear_equiv.to_linear_map_eq_coe, linear_equiv.range, submodule.map_top, finsupp.range_total] section span_range variables {v} {x : M} /-- An element `x` lies in the span of `v` iff it can be written as sum `∑ cᵢ • vᵢ = x`. -/ lemma mem_span_range_iff_exists_fun : x ∈ span R (range v) ↔ ∃ (c : α → R), ∑ i, c i • v i = x := begin simp only [finsupp.mem_span_range_iff_exists_finsupp, finsupp.equiv_fun_on_finite.surjective.exists, finsupp.equiv_fun_on_finite_apply], exact exists_congr (λ c, eq.congr_left $ finsupp.sum_fintype _ _ $ λ i, zero_smul _ _) end /-- A family `v : α → V` is generating `V` iff every element `(x : V)` can be written as sum `∑ cᵢ • vᵢ = x`. -/ theorem top_le_span_range_iff_forall_exists_fun : ⊤ ≤ span R (range v) ↔ ∀ x, ∃ (c : α → R), ∑ i, (c i) • (v i) = x := begin simp_rw ←mem_span_range_iff_exists_fun, exact ⟨λ h x, h trivial, λ h x _, h x⟩, end end span_range end fintype variables {R : Type*} {M : Type*} {N : Type*} variables [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid N] [module R N] section variables (R) /-- Pick some representation of `x : span R w` as a linear combination in `w`, using the axiom of choice. -/ @[irreducible] def span.repr (w : set M) (x : span R w) : w →₀ R := ((finsupp.mem_span_iff_total _ _ _).mp x.2).some @[simp] lemma span.finsupp_total_repr {w : set M} (x : span R w) : finsupp.total w M R coe (span.repr R w x) = x := begin rw span.repr, exact ((finsupp.mem_span_iff_total _ _ _).mp x.2).some_spec end end protected lemma submodule.finsupp_sum_mem {ι β : Type*} [has_zero β] (S : submodule R M) (f : ι →₀ β) (g : ι → β → M) (h : ∀ c, f c ≠ 0 → g c (f c) ∈ S) : f.sum g ∈ S := add_submonoid_class.finsupp_sum_mem S f g h lemma linear_map.map_finsupp_total (f : M →ₗ[R] N) {ι : Type*} {g : ι → M} (l : ι →₀ R) : f (finsupp.total ι M R g l) = finsupp.total ι N R (f ∘ g) l := by simp only [finsupp.total_apply, finsupp.total_apply, finsupp.sum, f.map_sum, f.map_smul] lemma submodule.exists_finset_of_mem_supr {ι : Sort*} (p : ι → submodule R M) {m : M} (hm : m ∈ ⨆ i, p i) : ∃ s : finset ι, m ∈ ⨆ i ∈ s, p i := begin have := complete_lattice.is_compact_element.exists_finset_of_le_supr (submodule R M) (submodule.singleton_span_is_compact_element m) p, simp only [submodule.span_singleton_le_iff_mem] at this, exact this hm, end /-- `submodule.exists_finset_of_mem_supr` as an `iff` -/ lemma submodule.mem_supr_iff_exists_finset {ι : Sort*} {p : ι → submodule R M} {m : M} : (m ∈ ⨆ i, p i) ↔ ∃ s : finset ι, m ∈ ⨆ i ∈ s, p i := ⟨submodule.exists_finset_of_mem_supr p, λ ⟨_, hs⟩, supr_mono (λ i, (supr_const_le : _ ≤ p i)) hs⟩ lemma mem_span_finset {s : finset M} {x : M} : x ∈ span R (↑s : set M) ↔ ∃ f : M → R, ∑ i in s, f i • i = x := ⟨λ hx, let ⟨v, hvs, hvx⟩ := (finsupp.mem_span_image_iff_total _).1 (show x ∈ span R (id '' (↑s : set M)), by rwa set.image_id) in ⟨v, hvx ▸ (finsupp.total_apply_of_mem_supported _ hvs).symm⟩, λ ⟨f, hf⟩, hf ▸ sum_mem (λ i hi, smul_mem _ _ $ subset_span hi)⟩ /-- An element `m ∈ M` is contained in the `R`-submodule spanned by a set `s ⊆ M`, if and only if `m` can be written as a finite `R`-linear combination of elements of `s`. The implementation uses `finsupp.sum`. -/ lemma mem_span_set {m : M} {s : set M} : m ∈ submodule.span R s ↔ ∃ c : M →₀ R, (c.support : set M) ⊆ s ∧ c.sum (λ mi r, r • mi) = m := begin conv_lhs { rw ←set.image_id s }, simp_rw ←exists_prop, exact finsupp.mem_span_image_iff_total R, end /-- If `subsingleton R`, then `M ≃ₗ[R] ι →₀ R` for any type `ι`. -/ @[simps] def module.subsingleton_equiv (R M ι: Type*) [semiring R] [subsingleton R] [add_comm_monoid M] [module R M] : M ≃ₗ[R] ι →₀ R := { to_fun := λ m, 0, inv_fun := λ f, 0, left_inv := λ m, by { letI := module.subsingleton R M, simp only [eq_iff_true_of_subsingleton] }, right_inv := λ f, by simp only [eq_iff_true_of_subsingleton], map_add' := λ m n, (add_zero 0).symm, map_smul' := λ r m, (smul_zero r).symm } namespace linear_map variables {R M} {α : Type*} open finsupp function /-- A surjective linear map to finitely supported functions has a splitting. -/ -- See also `linear_map.splitting_of_fun_on_fintype_surjective` def splitting_of_finsupp_surjective (f : M →ₗ[R] (α →₀ R)) (s : surjective f) : (α →₀ R) →ₗ[R] M := finsupp.lift _ _ _ (λ x : α, (s (finsupp.single x 1)).some) lemma splitting_of_finsupp_surjective_splits (f : M →ₗ[R] (α →₀ R)) (s : surjective f) : f.comp (splitting_of_finsupp_surjective f s) = linear_map.id := begin ext x y, dsimp [splitting_of_finsupp_surjective], congr, rw [sum_single_index, one_smul], { exact (s (finsupp.single x 1)).some_spec, }, { rw zero_smul, }, end lemma left_inverse_splitting_of_finsupp_surjective (f : M →ₗ[R] (α →₀ R)) (s : surjective f) : left_inverse f (splitting_of_finsupp_surjective f s) := λ g, linear_map.congr_fun (splitting_of_finsupp_surjective_splits f s) g lemma splitting_of_finsupp_surjective_injective (f : M →ₗ[R] (α →₀ R)) (s : surjective f) : injective (splitting_of_finsupp_surjective f s) := (left_inverse_splitting_of_finsupp_surjective f s).injective /-- A surjective linear map to functions on a finite type has a splitting. -/ -- See also `linear_map.splitting_of_finsupp_surjective` def splitting_of_fun_on_fintype_surjective [fintype α] (f : M →ₗ[R] (α → R)) (s : surjective f) : (α → R) →ₗ[R] M := (finsupp.lift _ _ _ (λ x : α, (s (finsupp.single x 1)).some)).comp (linear_equiv_fun_on_finite R R α).symm.to_linear_map lemma splitting_of_fun_on_fintype_surjective_splits [fintype α] (f : M →ₗ[R] (α → R)) (s : surjective f) : f.comp (splitting_of_fun_on_fintype_surjective f s) = linear_map.id := begin ext x y, dsimp [splitting_of_fun_on_fintype_surjective], rw [linear_equiv_fun_on_finite_symm_single, finsupp.sum_single_index, one_smul, (s (finsupp.single x 1)).some_spec, finsupp.single_eq_pi_single], rw [zero_smul], end lemma left_inverse_splitting_of_fun_on_fintype_surjective [fintype α] (f : M →ₗ[R] (α → R)) (s : surjective f) : left_inverse f (splitting_of_fun_on_fintype_surjective f s) := λ g, linear_map.congr_fun (splitting_of_fun_on_fintype_surjective_splits f s) g lemma splitting_of_fun_on_fintype_surjective_injective [fintype α] (f : M →ₗ[R] (α → R)) (s : surjective f) : injective (splitting_of_fun_on_fintype_surjective f s) := (left_inverse_splitting_of_fun_on_fintype_surjective f s).injective end linear_map
b42298771958618ad5a2ea9d3e502d9fc0cd7e2f
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/src/Lean/Delaborator.lean
a6dd37225ab4330a51cd8db8b4e3618ef41c2275
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
33,682
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. -/ import Lean.KeyedDeclsAttribute import Lean.ProjFns import Lean.Syntax import Lean.Meta.Match import 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|$(quote n):numLit) | none => Unhygienic.run `(level|$(Level.quote l.getLevelOffset) + $(quote l.getOffset):numLit) | max l1 l2 _ => match_syntax Level.quote l2 with | `(level|max $ls*) => Unhygienic.run `(level|max $(Level.quote l1) $ls*) | l2 => Unhygienic.run `(level|max $(Level.quote l1) $l2) | imax l1 l2 _ => match_syntax Level.quote l2 with | `(level|imax $ls*) => Unhygienic.run `(level|imax $(Level.quote l1) $ls*) | l2 => Unhygienic.run `(level|imax $(Level.quote l1) $l2) | param n _ => Unhygienic.run `(level|$(mkIdent n):ident) -- HACK: approximation | mvar n _ => Unhygienic.run `(level|_) instance : Quote 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 getPPNotation (o : Options) : Bool := o.get `pp.notation true def getPPStructureProjections (o : Options) : Bool := o.get `pp.structure_projections true def getPPStructureInstances (o : Options) : Bool := o.get `pp.structure_instances true def getPPStructureInstanceType (o : Options) : Bool := o.get `pp.structure_instance_type false def getPPUniverses (o : Options) : Bool := o.get `pp.universes false def getPPFullNames (o : Options) : Bool := o.get `pp.full_names false def getPPPrivateNames (o : Options) : Bool := o.get `pp.private_names false def getPPUnicode (o : Options) : Bool := o.get `pp.unicode true def getPPAll (o : Options) : Bool := o.get `pp.all false builtin_initialize registerOption `pp.explicit { defValue := false, group := "pp", descr := "(pretty printer) display implicit arguments" } registerOption `pp.structure_instance_type { defValue := false, group := "pp", descr := "(pretty printer) display type of structure instances" } -- TODO: register other options when old pretty printer is removed --registerOption `pp.universes { defValue := false, group := "pp", descr := "(pretty printer) display universes" } /-- Associate pretty printer options to a specific subterm using a synthetic position. -/ abbrev OptionsPerPos := Std.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) (currNamespace : Name) (openDecls : List OpenDecl) -- Exceptions from delaborators are not expected. We use an internal exception to signal whether -- the delaborator was able to produce a Syntax object. builtin_initialize delabFailureId : InternalExceptionId ← registerInternalExceptionId `delabFailure abbrev DelabM := ReaderT Context MetaM abbrev Delab := DelabM Syntax instance {α} : Inhabited (DelabM α) := ⟨throw $ arbitrary _⟩ @[inline] protected def orElse {α} (d₁ d₂ : DelabM α) : DelabM α := do catchInternalId delabFailureId d₁ (fun _ => d₂) protected def failure {α} : DelabM α := throw $ Exception.internal delabFailureId instance : Alternative DelabM := { orElse := Delaborator.orElse, failure := Delaborator.failure } -- HACK: necessary since it would otherwise prefer the instance from MonadExcept instance {α} : OrElse (DelabM α) := ⟨Delaborator.orElse⟩ -- Macro scopes in the delaborator output are ultimately ignored by the pretty printer, -- so give a trivial implementation. instance : 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 @[builtinInit mkDelabAttribute] constant delabAttribute : KeyedDeclsAttribute Delab def getExpr : DelabM Expr := do let ctx ← read pure ctx.expr def getExprKind : DelabM Name := do let 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 /-- 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 let 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 let b ← getPPOption opt if b then d else failure def whenNotPPOption (opt : Options → Bool) (d : Delab) : Delab := do let 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 α := withReader (fun cfg => { cfg with expr := child, pos := cfg.pos * 3 + childIdx }) d def withAppFn {α} (d : DelabM α) : DelabM α := do let Expr.app fn _ _ ← getExpr | unreachable! descend fn 0 d def withAppArg {α} (d : DelabM α) : DelabM α := do let Expr.app _ arg _ ← getExpr | unreachable! descend arg 1 d partial def withAppFnArgs {α} : DelabM α → (α → DelabM α) → DelabM α | fnD, argD => do let Expr.app fn arg _ ← getExpr | fnD let a ← withAppFn (withAppFnArgs fnD argD) withAppArg (argD a) def withBindingDomain {α} (d : DelabM α) : DelabM α := do let e ← getExpr descend e.bindingDomain! 0 d def withBindingBody {α} (n : Name) (d : DelabM α) : DelabM α := do let e ← getExpr withLocalDecl n e.binderInfo e.bindingDomain! fun fvar => let b := e.bindingBody!.instantiate1 fvar descend b 1 d def withProj {α} (d : DelabM α) : DelabM α := do let Expr.proj _ _ e _ ← getExpr | unreachable! descend e 0 d def withMDataExpr {α} (d : DelabM α) : DelabM α := do let Expr.mdata _ e _ ← getExpr | unreachable! -- do not change position so that options on an mdata are automatically forwarded to the child withReader ({ · with expr := e }) d partial def annotatePos (pos : Nat) : Syntax → Syntax | stx@(Syntax.ident _ _ _ _) => stx.setInfo { pos := pos } -- app => annotate function | stx@(Syntax.node `Lean.Parser.Term.app args) => stx.modifyArg 0 (annotatePos pos) -- 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 let ctx ← read pure $ annotatePos ctx.pos stx @[inline] def liftMetaM {α} (x : MetaM α) : DelabM α := liftM x partial def delabFor : Name → Delab | Name.anonymous => failure | k => do let env ← getEnv (match (delabAttribute.ext.getState env).table.find? k with | some delabs => delabs.firstM id >>= annotateCurPos | none => failure) <|> -- have `app.Option.some` fall back to `app` etc. delabFor k.getRoot def delab : Delab := do let k ← getExprKind delabFor k <|> (liftM $ show MetaM Syntax from throwError $ "don't know how to delaborate '" ++ toString k ++ "'") @[builtinDelab fvar] def delabFVar : Delab := do let Expr.fvar id _ ← getExpr | unreachable! try let l ← getLocalDecl id pure $ mkIdent l.userName catch _ => -- loose free variable, use internal name pure $ mkIdent id -- loose bound variable, use pseudo syntax @[builtinDelab bvar] def delabBVar : Delab := do let Expr.bvar idx _ ← getExpr | unreachable! pure $ mkIdent $ Name.mkSimple $ "#" ++ toString idx @[builtinDelab mvar] def delabMVar : Delab := do let Expr.mvar n _ ← getExpr | unreachable! let n := n.replacePrefix `_uniq `m `(?$(mkIdent n)) @[builtinDelab sort] def delabSort : Delab := do let Expr.sort l _ ← getExpr | unreachable! match l with | Level.zero _ => `(Prop) | Level.succ (Level.zero _) _ => `(Type) | _ => match l.dec with | some l' => `(Type $(quote l')) | none => `(Sort $(quote l)) -- find shorter names for constants, in reverse to Lean.Elab.ResolveName private def unresolveQualifiedName (ns : Name) (c : Name) : DelabM Name := do let c' := c.replacePrefix ns Name.anonymous; let env ← getEnv guard $ c' != c && !c'.isAnonymous && (!c'.isAtomic || !isProtected env c) pure c' private def unresolveUsingNamespace (c : Name) : Name → DelabM Name | ns@(Name.str p _ _) => unresolveQualifiedName ns c <|> unresolveUsingNamespace c p | _ => failure private def unresolveOpenDecls (c : Name) : List OpenDecl → DelabM Name | [] => failure | OpenDecl.simple ns exs :: openDecls => let c' := c.replacePrefix ns Name.anonymous if c' != c && exs.elem c' then unresolveOpenDecls c openDecls else unresolveQualifiedName ns c <|> unresolveOpenDecls c openDecls | OpenDecl.explicit openedId resolvedId :: openDecls => guard (c == resolvedId) *> pure openedId <|> unresolveOpenDecls c openDecls -- NOTE: not a registered delaborator, as `const` is never called (see [delab] description) def delabConst : Delab := do let Expr.const c ls _ ← getExpr | unreachable! let c ← if (← getPPOption getPPFullNames) then pure c else let ctx ← read let env ← getEnv let as := getRevAliases env c -- might want to use a more clever heuristic such as selecting the shortest alias... let c := as.headD c unresolveUsingNamespace c ctx.currNamespace <|> unresolveOpenDecls c ctx.openDecls <|> pure c let c ← if (← getPPOption getPPPrivateNames) then pure c else pure $ (privateToUserName? c).getD c let ppUnivs ← getPPOption getPPUniverses if ls.isEmpty || !ppUnivs then pure $ mkIdent c else `($(mkIdent c).{$(mkSepArray (ls.toArray.map quote) (mkAtom ","))*}) inductive ParamKind | explicit -- combines implicit params, optParams, and autoParams | implicit (defVal : Option Expr) /-- Return array with n-th element set to kind of n-th parameter of `e`. -/ def getParamKinds (e : Expr) : MetaM (Array ParamKind) := do let t ← inferType e forallTelescopeReducing t fun params _ => params.mapM fun param => do let l ← getLocalDecl param.fvarId! match l.type.getOptParamDefault? with | some val => pure $ ParamKind.implicit val | _ => if l.type.isAutoParam || !l.binderInfo.isExplicit then pure $ ParamKind.implicit none else pure ParamKind.explicit @[builtinDelab app] def delabAppExplicit : Delab := do let (fnStx, argStxs) ← withAppFnArgs (do let fn ← getExpr let stx ← if fn.isConst then delabConst else delab let paramKinds ← liftM $ getParamKinds fn <|> pure #[] let stx ← if paramKinds.any (fun k => match k with | ParamKind.explicit => false | _ => true) then `(@$stx) else pure stx pure (stx, #[])) (fun ⟨fnStx, argStxs⟩ => do let argStx ← delab pure (fnStx, argStxs.push argStx)) Syntax.mkApp fnStx argStxs @[builtinDelab app] def delabAppImplicit : Delab := whenNotPPOption getPPExplicit do let (fnStx, _, argStxs) ← withAppFnArgs (do let fn ← getExpr let stx ← if fn.isConst then delabConst else delab let paramKinds ← liftM $ getParamKinds fn <|> pure #[] pure (stx, paramKinds.toList, #[])) (fun (fnStx, paramKinds, argStxs) => do let arg ← getExpr; let implicit : Bool := match paramKinds with -- TODO: check why we need `: Bool` here | [ParamKind.implicit (some v)] => !v.hasLooseBVars && v == arg | ParamKind.implicit none :: _ => true | _ => false if implicit then pure (fnStx, paramKinds.tailD [], argStxs) else do let argStx ← delab pure (fnStx, paramKinds.tailD [], argStxs.push argStx)) Syntax.mkApp fnStx argStxs private def getUnusedName (suggestion : Name) : DelabM Name := do -- Use a nicer binder name than `[anonymous]`. We probably shouldn't do this in all LocalContext use cases, so do it here. let suggestion := if suggestion.isAnonymous then `a else suggestion; let lctx ← getLCtx pure $ lctx.getUnusedName suggestion /-- State for `delabAppMatch` and helpers. -/ structure AppMatchState := (info : MatcherInfo) (matcherTy : Expr) (params : Array Expr := #[]) (hasMotive : Bool := false) (discrs : Array Syntax := #[]) (rhss : Array Syntax := #[]) -- additional arguments applied to the result of the `match` expression (moreArgs : Array Syntax := #[]) /-- Skip `numParams` binders. -/ private def skippingBinders {α} : (numParams : Nat) → (x : DelabM α) → DelabM α | 0, x => x | numParams+1, x => do let e ← getExpr let n ← getUnusedName e.bindingName! withBindingBody n $ skippingBinders numParams x /-- Extract arguments of motive applications from the matcher type. For the example below: `#[`([]), `(a::as)]` -/ private def delabPatterns (st : AppMatchState) : DelabM (Array Syntax) := do let ty ← instantiateForall st.matcherTy st.params forallTelescope ty fun params _ => do -- skip motive and discriminators let alts := Array.ofSubarray $ params[1 + st.discrs.size:] alts.mapIdxM fun idx alt => do let ty ← inferType alt withReader ({ · with expr := ty }) $ skippingBinders st.info.altNumParams[idx] do let pats ← withAppFnArgs (pure #[]) (fun pats => do pure $ pats.push (← delab)) Syntax.mkSep pats (mkAtom ",") /-- Delaborate applications of "matchers" such as ``` List.map.match_1 : {α : Type _} → (motive : List α → Sort _) → (x : List α) → (Unit → motive List.nil) → ((a : α) → (as : List α) → motive (a :: as)) → motive x ``` -/ @[builtinDelab app] def delabAppMatch : Delab := whenPPOption getPPNotation do -- incrementally fill `AppMatchState` from arguments let st ← withAppFnArgs (do let (Expr.const c us _) ← getExpr | failure let (some info) ← getMatcherInfo? c | failure { matcherTy := (← getConstInfo c).instantiateTypeLevelParams us, info := info, : AppMatchState }) (fun st => do if st.params.size < st.info.numParams then pure { st with params := st.params.push (← getExpr) } else if !st.hasMotive then -- discard motive argument pure { st with hasMotive := true } else if st.discrs.size < st.info.numDiscrs then pure { st with discrs := st.discrs.push (← delab) } else if st.rhss.size < st.info.altNumParams.size then pure { st with rhss := st.rhss.push (← skippingBinders st.info.altNumParams[st.rhss.size] delab) } else pure { st with moreArgs := st.moreArgs.push (← delab) }) let pats ← delabPatterns st let discrs := st.discrs.map fun discr => mkNode `Lean.Parser.Term.matchDiscr #[mkNullNode, discr] let alts := pats.zipWith st.rhss fun pat rhs => mkNode `Lean.Parser.Term.matchAlt #[pat, mkAtom "=>", rhs] let stx ← `(match $(mkSepArray discrs (mkAtom ",")):matchDiscr* with | $(mkSepArray alts (mkAtom "|")):matchAlt*) Syntax.mkApp stx st.moreArgs @[builtinDelab mdata] def delabMData : Delab := do -- only interpret `pp.` values by default let Expr.mdata m _ _ ← getExpr | unreachable! let mut posOpts := (← read).optionsPerPos let pos := (← read).pos for (k, v) in m do if (`pp).isPrefixOf k then let opts := posOpts.find? pos $.getD {} posOpts := posOpts.insert pos (opts.insert k v) withReader ({ · with optionsPerPos := posOpts }) $ withMDataExpr delab /-- 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 id) | _ => 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 let e ← getExpr let ppEType ← getPPOption getPPBinderTypes; let go (e' : Expr) := do let 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 let e ← getExpr let n ← getUnusedName e.bindingName! let stxN ← annotateCurPos (mkIdent n) let curNames := curNames.push stxN if (← shouldGroupWithNext) then -- group with nested binder => recurse immediately withBindingBody n $ delabBinders delabGroup curNames else -- 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 let e ← getExpr let stxT ← withBindingDomain delab let ppTypes ← getPPOption getPPBinderTypes let 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 let group ← match e.binderInfo, ppTypes with | BinderInfo.default, true => -- "default" binder group is the only one that expects binder names -- as a term, i.e. a single `Syntax.ident` or an application thereof let stxCurNames ← if curNames.size > 1 then `($(curNames.get! 0) $(curNames.eraseIdx 0)*) else pure $ curNames.get! 0; `(funBinder| ($stxCurNames : $stxT)) | BinderInfo.default, false => pure 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 let e ← getExpr let 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 letE] def delabLetE : Delab := do let Expr.letE n t v b _ ← getExpr | unreachable! let n ← getUnusedName n let stxT ← descend t 0 delab let stxV ← descend v 1 delab let stxB ← withLetDecl n t v fun fvar => let b := b.instantiate1 fvar descend b 2 delab `(let $(mkIdent n) : $stxT := $stxV; $stxB) @[builtinDelab lit] def delabLit : Delab := do let 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.OfNat.ofNat] def delabOfNat : Delab := whenPPOption getPPCoercions do let 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 let Expr.proj _ idx _ _ ← getExpr | unreachable! let 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`. let idx := Syntax.mkLit fieldIdxKind (toString (idx + 1)); `($(e).$idx:fieldIdx) /-- Delaborate a call to a projection function such as `Prod.fst`. -/ @[builtinDelab app] def delabProjectionApp : Delab := whenPPOption getPPStructureProjections $ do let e@(Expr.app fn _ _) ← getExpr | failure let Expr.const c@(Name.str _ f _) _ _ ← pure fn.getAppFn | failure let env ← getEnv let 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. let expl ← getPPOption getPPExplicit guard $ !expl || info.nparams == 0 let appStx ← withAppArg delab `($(appStx).$(mkIdent f):ident) @[builtinDelab app] def delabStructureInstance : Delab := whenPPOption getPPStructureInstances do let env ← getEnv let e ← getExpr let some s ← pure $ e.isConstructorApp? env | failure guard $ isStructure env s.induct; /- If implicit arguments should be shown, and the structure has parameters, we should not pretty print using { ... }, because we will not be able to see the parameters. -/ let explicit ← getPPOption getPPExplicit guard !(explicit && s.nparams > 0) let fieldNames := getStructureFields env s.induct let (_, fields) ← withAppFnArgs (pure (0, #[])) fun ⟨idx, fields⟩ => do if idx < s.nparams then pure (idx + 1, fields) else let val ← delab let field := Syntax.node `Lean.Parser.Term.structInstField #[ mkIdent $ fieldNames.get! (idx - s.nparams), mkNullNode, mkAtom ":=", val ] pure (idx + 1, fields.push field) let fields := mkSepArray fields (mkAtom ",") if (← getPPOption getPPStructureInstanceType) then let ty ← inferType e -- `ty` is not actually part of `e`, but since `e` must be an application or constant, we know that -- index 2 is unused. let stxTy ← descend ty 2 delab `({ $fields:structInstField* : $stxTy }) else `({ $fields:structInstField* }) @[builtinDelab app.Prod.mk] def delabTuple : Delab := whenPPOption getPPNotation do let e ← getExpr guard $ e.getAppNumArgs == 4 let a ← withAppFn $ withAppArg delab let b ← withAppArg delab match_syntax b with | `(($b, $bs*)) => let bs := #[b, mkAtom ","] ++ bs; `(($a, $bs*)) | _ => `(($a, $b)) -- abbrev coe {α : Sort u} {β : Sort v} (a : α) [CoeT α a β] : β @[builtinDelab app.coe] def delabCoe : Delab := whenPPOption getPPCoercions do let e ← getExpr guard $ e.getAppNumArgs >= 4 -- delab as application, then discard function let 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 def delabInfixOp (op : Bool → Syntax → Syntax → Delab) : Delab := whenPPOption getPPNotation do let stx ← delabAppImplicit <|> delabAppExplicit guard $ stx.isOfKind `Lean.Parser.Term.app && (stx.getArg 1).getNumArgs == 2 let unicode ← getPPOption getPPUnicode let args := stx.getArg 1 op unicode (args.getArg 0) (args.getArg 1) def delabPrefixOp (op : Bool → Syntax → Delab) : Delab := whenPPOption getPPNotation do let stx ← delabAppImplicit <|> delabAppExplicit guard $ stx.isOfKind `Lean.Parser.Term.app && (stx.getArg 1).getNumArgs == 1 let unicode ← getPPOption getPPUnicode let args := stx.getArg 1 op unicode (args.getArg 0) @[builtinDelab app.Prod] def delabProd : Delab := delabInfixOp fun _ x y => `($x × $y) @[builtinDelab app.Function.comp] def delabFComp : Delab := delabInfixOp fun _ x y => `($x ∘ $y) @[builtinDelab app.Add.add] def delabAdd : Delab := delabInfixOp fun _ x y => `($x + $y) @[builtinDelab app.Sub.sub] def delabSub : Delab := delabInfixOp fun _ x y => `($x - $y) @[builtinDelab app.Mul.mul] def delabMul : Delab := delabInfixOp fun _ x y => `($x * $y) @[builtinDelab app.Div.div] def delabDiv : Delab := delabInfixOp fun _ x y => `($x / $y) @[builtinDelab app.Mod.mod] def delabMod : Delab := delabInfixOp fun _ x y => `($x % $y) @[builtinDelab app.ModN.modn] def delabModN : Delab := delabInfixOp fun _ x y => `($x %ₙ $y) @[builtinDelab app.Pow.pow] def delabPow : Delab := delabInfixOp fun _ x y => `($x ^ $y) @[builtinDelab app.HasLessEq.LessEq] def delabLE : Delab := delabInfixOp fun b x y => cond b `($x ≤ $y) `($x <= $y) @[builtinDelab app.GreaterEq] def delabGE : Delab := delabInfixOp fun b x y => cond b `($x ≥ $y) `($x >= $y) @[builtinDelab app.HasLess.Less] def delabLT : Delab := delabInfixOp fun _ x y => `($x < $y) @[builtinDelab app.Greater] def delabGT : Delab := delabInfixOp fun _ x y => `($x > $y) @[builtinDelab app.Eq] def delabEq : Delab := delabInfixOp fun _ x y => `($x = $y) @[builtinDelab app.Ne] def delabNe : Delab := delabInfixOp fun _ x y => `($x ≠ $y) @[builtinDelab app.BEq.beq] def delabBEq : Delab := delabInfixOp fun _ x y => `($x == $y) @[builtinDelab app.bne] def delabBNe : Delab := delabInfixOp fun _ x y => `($x != $y) @[builtinDelab app.HEq] def delabHEq : Delab := delabInfixOp fun b x y => cond b `($x ≅ $y) `($x ~= $y) @[builtinDelab app.HasEquiv.Equiv] def delabEquiv : Delab := delabInfixOp fun _ x y => `($x ≈ $y) @[builtinDelab app.And] def delabAnd : Delab := delabInfixOp fun b x y => cond b `($x ∧ $y) `($x /\ $y) @[builtinDelab app.Or] def delabOr : Delab := delabInfixOp fun b x y => cond b `($x ∨ $y) `($x || $y) @[builtinDelab app.Iff] def delabIff : Delab := delabInfixOp fun b x y => cond b `($x ↔ $y) `($x <-> $y) @[builtinDelab app.and] def delabBAnd : Delab := delabInfixOp fun _ x y => `($x && $y) @[builtinDelab app.or] def delabBOr : Delab := delabInfixOp fun _ x y => `($x || $y) @[builtinDelab app.Append.append] def delabAppend : Delab := delabInfixOp fun _ x y => `($x ++ $y) @[builtinDelab app.List.cons] def delabCons : Delab := delabInfixOp fun _ x y => `($x :: $y) @[builtinDelab app.AndThen.andthen] def delabAndThen : Delab := delabInfixOp fun _ x y => `($x >> $y) @[builtinDelab app.Bind.bind] def delabBind : Delab := delabInfixOp fun _ x y => `($x >>= $y) @[builtinDelab app.Seq.seq] def delabseq : Delab := delabInfixOp fun _ x y => `($x <*> $y) @[builtinDelab app.SeqLeft.seqLeft] def delabseqLeft : Delab := delabInfixOp fun _ x y => `($x <* $y) @[builtinDelab app.SeqRight.seqRight] def delabseqRight : Delab := delabInfixOp fun _ x y => `($x *> $y) @[builtinDelab app.Functor.map] def delabMap : Delab := delabInfixOp fun _ x y => `($x <$> $y) @[builtinDelab app.Functor.mapRev] def delabMapRev : Delab := delabInfixOp fun _ x y => `($x <&> $y) @[builtinDelab app.OrElse.orelse] def delabOrElse : Delab := delabInfixOp fun _ x y => `($x <|> $y) @[builtinDelab app.orM] def delabOrM : Delab := delabInfixOp fun _ x y => `($x <||> $y) @[builtinDelab app.andM] def delabAndM : Delab := delabInfixOp fun _ x y => `($x <&&> $y) @[builtinDelab app.Not] def delabNot : Delab := delabPrefixOp fun _ x => `(¬ $x) @[builtinDelab app.not] def delabBNot : Delab := delabPrefixOp fun _ x => `(! $x) @[builtinDelab app.List.nil] def delabNil : Delab := whenPPOption getPPNotation do guard $ (← getExpr).getAppNumArgs == 1 `([]) @[builtinDelab app.List.cons] def delabConsList : Delab := whenPPOption getPPNotation do guard $ (← getExpr).getAppNumArgs == 3 let x ← withAppFn (withAppArg delab) match_syntax (← withAppArg delab) with | `([]) => `([$x]) | `([$xs*]) => `([$x, $xs*]) | _ => failure @[builtinDelab app.List.toArray] def delabListToArray : Delab := whenPPOption getPPNotation do guard $ (← getExpr).getAppNumArgs == 2 match_syntax (← withAppArg delab) with | `([$xs*]) => `(#[$xs*]) | _ => failure end Delaborator /-- "Delaborate" the given term into surface-level syntax using the default and given subterm-specific options. -/ def delab (currNamespace : Name) (openDecls : List OpenDecl) (e : Expr) (optionsPerPos : OptionsPerPos := {}) : MetaM Syntax := do let opts ← MonadOptions.getOptions catchInternalId Delaborator.delabFailureId (Delaborator.delab.run { expr := e, defaultOptions := opts, optionsPerPos := optionsPerPos, currNamespace := currNamespace, openDecls := openDecls }) (fun _ => unreachable!) end Lean
92de8bfbcbb09cb2d08e8486d8ef835216ff6f03
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/order/compactly_generated.lean
e59a16befd2308e587ea892a75b4c433847fa172
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
20,349
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 data.set.finite import data.finset.order import order.well_founded import order.order_iso_nat import order.atoms import order.zorn import tactic.tfae /-! # Compactness properties for complete lattices For complete lattices, there are numerous equivalent ways to express the fact that the relation `>` is well-founded. In this file we define three especially-useful characterisations and provide proofs that they are indeed equivalent to well-foundedness. ## Main definitions * `complete_lattice.is_sup_closed_compact` * `complete_lattice.is_Sup_finite_compact` * `complete_lattice.is_compact_element` * `complete_lattice.is_compactly_generated` ## Main results The main result is that the following four conditions are equivalent for a complete lattice: * `well_founded (>)` * `complete_lattice.is_sup_closed_compact` * `complete_lattice.is_Sup_finite_compact` * `∀ k, complete_lattice.is_compact_element k` This is demonstrated by means of the following four lemmas: * `complete_lattice.well_founded.is_Sup_finite_compact` * `complete_lattice.is_Sup_finite_compact.is_sup_closed_compact` * `complete_lattice.is_sup_closed_compact.well_founded` * `complete_lattice.is_Sup_finite_compact_iff_all_elements_compact` We also show well-founded lattices are compactly generated (`complete_lattice.compactly_generated_of_well_founded`). ## References - [G. Călugăreanu, *Lattice Concepts of Module Theory*][calugareanu] ## Tags complete lattice, well-founded, compact -/ variables {α : Type*} [complete_lattice α] namespace complete_lattice variables (α) /-- A compactness property for a complete lattice is that any `sup`-closed non-empty subset contains its `Sup`. -/ def is_sup_closed_compact : Prop := ∀ (s : set α) (h : s.nonempty), (∀ a b, a ∈ s → b ∈ s → a ⊔ b ∈ s) → (Sup s) ∈ s /-- A compactness property for a complete lattice is that any subset has a finite subset with the same `Sup`. -/ def is_Sup_finite_compact : Prop := ∀ (s : set α), ∃ (t : finset α), ↑t ⊆ s ∧ Sup s = t.sup id /-- An element `k` of a complete lattice is said to be compact if any set with `Sup` above `k` has a finite subset with `Sup` above `k`. Such an element is also called "finite" or "S-compact". -/ def is_compact_element {α : Type*} [complete_lattice α] (k : α) := ∀ s : set α, k ≤ Sup s → ∃ t : finset α, ↑t ⊆ s ∧ k ≤ t.sup id /-- An element `k` is compact if and only if any directed set with `Sup` above `k` already got above `k` at some point in the set. -/ theorem is_compact_element_iff_le_of_directed_Sup_le (k : α) : is_compact_element k ↔ ∀ s : set α, s.nonempty → directed_on (≤) s → k ≤ Sup s → ∃ x : α, x ∈ s ∧ k ≤ x := begin classical, split, { by_cases hbot : k = ⊥, -- Any nonempty directed set certainly has sup above ⊥ { rintros _ _ ⟨x, hx⟩ _ _, use x, by simp only [hx, hbot, bot_le, and_self], }, { intros hk s hne hdir hsup, obtain ⟨t, ht⟩ := hk s hsup, -- If t were empty, its sup would be ⊥, which is not above k ≠ ⊥. have tne : t.nonempty, { by_contradiction n, rw [finset.nonempty_iff_ne_empty, not_not] at n, simp only [n, true_and, set.empty_subset, finset.coe_empty, finset.sup_empty, le_bot_iff] at ht, exact absurd ht hbot, }, -- certainly every element of t is below something in s, since ↑t ⊆ s. have t_below_s : ∀ x ∈ t, ∃ y ∈ s, x ≤ y, from λ x hxt, ⟨x, ht.left hxt, by refl⟩, obtain ⟨x, ⟨hxs, hsupx⟩⟩ := finset.sup_le_of_le_directed s hne hdir t t_below_s, exact ⟨x, ⟨hxs, le_trans ht.right hsupx⟩⟩, }, }, { intros hk s hsup, -- Consider the set of finite joins of elements of the (plain) set s. let S : set α := { x | ∃ t : finset α, ↑t ⊆ s ∧ x = t.sup id }, -- S is directed, nonempty, and still has sup above k. have dir_US : directed_on (≤) S, { rintros x ⟨c, hc⟩ y ⟨d, hd⟩, use x ⊔ y, split, { use c ∪ d, split, { simp only [hc.left, hd.left, set.union_subset_iff, finset.coe_union, and_self], }, { simp only [hc.right, hd.right, finset.sup_union], }, }, simp only [and_self, le_sup_left, le_sup_right], }, have sup_S : Sup s ≤ Sup S, { apply Sup_le_Sup, intros x hx, use {x}, simpa only [and_true, id.def, finset.coe_singleton, eq_self_iff_true, finset.sup_singleton, set.singleton_subset_iff], }, have Sne : S.nonempty, { suffices : ⊥ ∈ S, from set.nonempty_of_mem this, use ∅, simp only [set.empty_subset, finset.coe_empty, finset.sup_empty, eq_self_iff_true, and_self], }, -- Now apply the defn of compact and finish. obtain ⟨j, ⟨hjS, hjk⟩⟩ := hk S Sne dir_US (le_trans hsup sup_S), obtain ⟨t, ⟨htS, htsup⟩⟩ := hjS, use t, exact ⟨htS, by rwa ←htsup⟩, }, end /-- A compact element `k` has the property that any directed set lying strictly below `k` has its Sup strictly below `k`. -/ lemma is_compact_element.directed_Sup_lt_of_lt {α : Type*} [complete_lattice α] {k : α} (hk : is_compact_element k) {s : set α} (hemp : s.nonempty) (hdir : directed_on (≤) s) (hbelow : ∀ x ∈ s, x < k) : Sup s < k := begin rw is_compact_element_iff_le_of_directed_Sup_le at hk, by_contradiction, have sSup : Sup s ≤ k, from Sup_le (λ s hs, (hbelow s hs).le), replace sSup : Sup s = k := eq_iff_le_not_lt.mpr ⟨sSup, h⟩, obtain ⟨x, hxs, hkx⟩ := hk s hemp hdir sSup.symm.le, obtain hxk := hbelow x hxs, exact hxk.ne (hxk.le.antisymm hkx), end lemma finset_sup_compact_of_compact {α β : Type*} [complete_lattice α] {f : β → α} (s : finset β) (h : ∀ x ∈ s, is_compact_element (f x)) : is_compact_element (s.sup f) := begin classical, rw is_compact_element_iff_le_of_directed_Sup_le, intros d hemp hdir hsup, change f with id ∘ f, rw finset.sup_finset_image, apply finset.sup_le_of_le_directed d hemp hdir, rintros x hx, obtain ⟨p, ⟨hps, rfl⟩⟩ := finset.mem_image.mp hx, specialize h p hps, rw is_compact_element_iff_le_of_directed_Sup_le at h, specialize h d hemp hdir (le_trans (finset.le_sup hps) hsup), simpa only [exists_prop], end lemma well_founded.is_Sup_finite_compact (h : well_founded ((>) : α → α → Prop)) : is_Sup_finite_compact α := begin intros s, let p : set α := { x | ∃ (t : finset α), ↑t ⊆ s ∧ t.sup id = x }, have hp : p.nonempty, { use [⊥, ∅], simp, }, obtain ⟨m, ⟨t, ⟨ht₁, ht₂⟩⟩, hm⟩ := well_founded.well_founded_iff_has_max'.mp h p hp, use t, simp only [ht₁, ht₂, true_and], apply le_antisymm, { apply Sup_le, intros y hy, classical, have hy' : (insert y t).sup id ∈ p, { use insert y t, simp, rw set.insert_subset, exact ⟨hy, ht₁⟩, }, have hm' : m ≤ (insert y t).sup id, { rw ← ht₂, exact finset.sup_mono (t.subset_insert y), }, rw ← hm _ hy' hm', simp, }, { rw [← ht₂, finset.sup_eq_Sup], exact Sup_le_Sup ht₁, }, end lemma is_Sup_finite_compact.is_sup_closed_compact (h : is_Sup_finite_compact α) : is_sup_closed_compact α := begin intros s hne hsc, obtain ⟨t, ht₁, ht₂⟩ := h s, clear h, cases t.eq_empty_or_nonempty with h h, { subst h, rw finset.sup_empty at ht₂, rw ht₂, simp [eq_singleton_bot_of_Sup_eq_bot_of_nonempty ht₂ hne], }, { rw ht₂, exact t.sup_closed_of_sup_closed h ht₁ hsc, }, end lemma is_sup_closed_compact.well_founded (h : is_sup_closed_compact α) : well_founded ((>) : α → α → Prop) := begin rw rel_embedding.well_founded_iff_no_descending_seq, rintros ⟨a⟩, suffices : Sup (set.range a) ∈ set.range a, { obtain ⟨n, hn⟩ := set.mem_range.mp this, have h' : Sup (set.range a) < a (n+1), { change _ > _, simp [← hn, a.map_rel_iff], }, apply lt_irrefl (a (n+1)), apply lt_of_le_of_lt _ h', apply le_Sup, apply set.mem_range_self, }, apply h (set.range a), { use a 37, apply set.mem_range_self, }, { rintros x y ⟨m, hm⟩ ⟨n, hn⟩, use m ⊔ n, rw [← hm, ← hn], apply a.to_rel_hom.map_sup, }, end lemma is_Sup_finite_compact_iff_all_elements_compact : is_Sup_finite_compact α ↔ (∀ k : α, is_compact_element k) := begin split, { intros h k s hs, obtain ⟨t, ⟨hts, htsup⟩⟩ := h s, use [t, hts], rwa ←htsup, }, { intros h s, obtain ⟨t, ⟨hts, htsup⟩⟩ := h (Sup s) s (by refl), have : Sup s = t.sup id, { suffices : t.sup id ≤ Sup s, by { apply le_antisymm; assumption }, simp only [id.def, finset.sup_le_iff], intros x hx, apply le_Sup, exact hts hx, }, use [t, hts], assumption, }, end lemma well_founded_characterisations : tfae [well_founded ((>) : α → α → Prop), is_Sup_finite_compact α, is_sup_closed_compact α, ∀ k : α, is_compact_element k] := begin tfae_have : 1 → 2, by { exact well_founded.is_Sup_finite_compact α, }, tfae_have : 2 → 3, by { exact is_Sup_finite_compact.is_sup_closed_compact α, }, tfae_have : 3 → 1, by { exact is_sup_closed_compact.well_founded α, }, tfae_have : 2 ↔ 4, by { exact is_Sup_finite_compact_iff_all_elements_compact α }, tfae_finish, end lemma well_founded_iff_is_Sup_finite_compact : well_founded ((>) : α → α → Prop) ↔ is_Sup_finite_compact α := (well_founded_characterisations α).out 0 1 lemma is_Sup_finite_compact_iff_is_sup_closed_compact : is_Sup_finite_compact α ↔ is_sup_closed_compact α := (well_founded_characterisations α).out 1 2 lemma is_sup_closed_compact_iff_well_founded : is_sup_closed_compact α ↔ well_founded ((>) : α → α → Prop) := (well_founded_characterisations α).out 2 0 alias well_founded_iff_is_Sup_finite_compact ↔ _ is_Sup_finite_compact.well_founded alias is_Sup_finite_compact_iff_is_sup_closed_compact ↔ _ is_sup_closed_compact.is_Sup_finite_compact alias is_sup_closed_compact_iff_well_founded ↔ _ well_founded.is_sup_closed_compact end complete_lattice /-- A complete lattice is said to be compactly generated if any element is the `Sup` of compact elements. -/ class is_compactly_generated (α : Type*) [complete_lattice α] : Prop := (exists_Sup_eq : ∀ (x : α), ∃ (s : set α), (∀ x ∈ s, complete_lattice.is_compact_element x) ∧ Sup s = x) section variables {α} [is_compactly_generated α] {a b : α} {s : set α} @[simp] lemma Sup_compact_le_eq (b) : Sup {c : α | complete_lattice.is_compact_element c ∧ c ≤ b} = b := begin rcases is_compactly_generated.exists_Sup_eq b with ⟨s, hs, rfl⟩, exact le_antisymm (Sup_le (λ c hc, hc.2)) (Sup_le_Sup (λ c cs, ⟨hs c cs, le_Sup cs⟩)), end @[simp] theorem Sup_compact_eq_top : Sup {a : α | complete_lattice.is_compact_element a} = ⊤ := begin refine eq.trans (congr rfl (set.ext (λ x, _))) (Sup_compact_le_eq ⊤), exact (and_iff_left le_top).symm, end theorem le_iff_compact_le_imp {a b : α} : a ≤ b ↔ ∀ c : α, complete_lattice.is_compact_element c → c ≤ a → c ≤ b := ⟨λ ab c hc ca, le_trans ca ab, λ h, begin rw [← Sup_compact_le_eq a, ← Sup_compact_le_eq b], exact Sup_le_Sup (λ c hc, ⟨hc.1, h c hc.1 hc.2⟩), end⟩ /-- This property is sometimes referred to as `α` being upper continuous. -/ theorem inf_Sup_eq_of_directed_on (h : directed_on (≤) s): a ⊓ Sup s = ⨆ b ∈ s, a ⊓ b := le_antisymm (begin rw le_iff_compact_le_imp, by_cases hs : s.nonempty, { intros c hc hcinf, rw le_inf_iff at hcinf, rw complete_lattice.is_compact_element_iff_le_of_directed_Sup_le at hc, rcases hc s hs h hcinf.2 with ⟨d, ds, cd⟩, exact (le_inf hcinf.1 cd).trans (le_bsupr d ds) }, { rw set.not_nonempty_iff_eq_empty at hs, simp [hs] } end) supr_inf_le_inf_Sup /-- This property is equivalent to `α` being upper continuous. -/ theorem inf_Sup_eq_supr_inf_sup_finset : a ⊓ Sup s = ⨆ (t : finset α) (H : ↑t ⊆ s), a ⊓ (t.sup id) := le_antisymm (begin rw le_iff_compact_le_imp, intros c hc hcinf, rw le_inf_iff at hcinf, rcases hc s hcinf.2 with ⟨t, ht1, ht2⟩, exact (le_inf hcinf.1 ht2).trans (le_bsupr t ht1), end) (supr_le $ λ t, supr_le $ λ h, inf_le_inf_left _ ((finset.sup_eq_Sup t).symm ▸ (Sup_le_Sup h))) theorem complete_lattice.independent_iff_finite {s : set α} : complete_lattice.independent s ↔ ∀ t : finset α, ↑t ⊆ s → complete_lattice.independent (↑t : set α) := ⟨λ hs t ht, hs.mono ht, λ h a ha, begin rw [disjoint_iff, inf_Sup_eq_supr_inf_sup_finset, supr_eq_bot], intro t, rw [supr_eq_bot, finset.sup_eq_Sup], intro ht, classical, have h' := (h (insert a t) _ (t.mem_insert_self a)).eq_bot, { rwa [finset.coe_insert, set.insert_diff_self_of_not_mem] at h', exact λ con, ((set.mem_diff a).1 (ht con)).2 (set.mem_singleton a) }, { rw [finset.coe_insert, set.insert_subset], exact ⟨ha, set.subset.trans ht (set.diff_subset _ _)⟩ } end⟩ lemma complete_lattice.independent_Union_of_directed {η : Type*} {s : η → set α} (hs : directed (⊆) s) (h : ∀ i, complete_lattice.independent (s i)) : complete_lattice.independent (⋃ i, s i) := begin by_cases hη : nonempty η, { resetI, rw complete_lattice.independent_iff_finite, intros t ht, obtain ⟨I, fi, hI⟩ := set.finite_subset_Union t.finite_to_set ht, obtain ⟨i, hi⟩ := hs.finset_le fi.to_finset, exact (h i).mono (set.subset.trans hI $ set.bUnion_subset $ λ j hj, hi j (set.finite.mem_to_finset.2 hj)) }, { rintros a ⟨_, ⟨i, _⟩, _⟩, exfalso, exact hη ⟨i⟩, }, end lemma complete_lattice.independent_sUnion_of_directed {s : set (set α)} (hs : directed_on (⊆) s) (h : ∀ a ∈ s, complete_lattice.independent a) : complete_lattice.independent (⋃₀ s) := by rw set.sUnion_eq_Union; exact complete_lattice.independent_Union_of_directed hs.directed_coe (by simpa using h) end namespace complete_lattice lemma compactly_generated_of_well_founded (h : well_founded ((>) : α → α → Prop)) : is_compactly_generated α := begin rw [well_founded_iff_is_Sup_finite_compact, is_Sup_finite_compact_iff_all_elements_compact] at h, -- x is the join of the set of compact elements {x} exact ⟨λ x, ⟨{x}, ⟨λ x _, h x, Sup_singleton⟩⟩⟩, end /-- A compact element `k` has the property that any `b < `k lies below a "maximal element below `k`", which is to say `[⊥, k]` is coatomic. -/ theorem Iic_coatomic_of_compact_element {k : α} (h : is_compact_element k) : is_coatomic (set.Iic k) := ⟨λ ⟨b, hbk⟩, begin by_cases htriv : b = k, { left, ext, simp only [htriv, set.Iic.coe_top, subtype.coe_mk], }, right, rcases zorn.zorn_partial_order₀ (set.Iio k) _ b (lt_of_le_of_ne hbk htriv) with ⟨a, a₀, ba, h⟩, { refine ⟨⟨a, le_of_lt a₀⟩, ⟨ne_of_lt a₀, λ c hck, by_contradiction $ λ c₀, _⟩, ba⟩, cases h c.1 (lt_of_le_of_ne c.2 (λ con, c₀ (subtype.ext con))) hck.le, exact lt_irrefl _ hck, }, { intros S SC cC I IS, by_cases hS : S.nonempty, { exact ⟨Sup S, h.directed_Sup_lt_of_lt hS cC.directed_on SC, λ _, le_Sup⟩, }, exact ⟨b, lt_of_le_of_ne hbk htriv, by simp only [set.not_nonempty_iff_eq_empty.mp hS, set.mem_empty_eq, forall_const, forall_prop_of_false, not_false_iff]⟩, }, end⟩ lemma coatomic_of_top_compact (h : is_compact_element (⊤ : α)) : is_coatomic α := (@order_iso.Iic_top α _).is_coatomic_iff.mp (Iic_coatomic_of_compact_element h) end complete_lattice section variables [is_modular_lattice α] [is_compactly_generated α] @[priority 100] instance is_atomic_of_is_complemented [is_complemented α] : is_atomic α := ⟨λ b, begin by_cases h : {c : α | complete_lattice.is_compact_element c ∧ c ≤ b} ⊆ {⊥}, { left, rw [← Sup_compact_le_eq b, Sup_eq_bot], exact h }, { rcases set.not_subset.1 h with ⟨c, ⟨hc, hcb⟩, hcbot⟩, right, have hc' := complete_lattice.Iic_coatomic_of_compact_element hc, rw ← is_atomic_iff_is_coatomic at hc', haveI := hc', obtain con | ⟨a, ha, hac⟩ := eq_bot_or_exists_atom_le (⟨c, le_refl c⟩ : set.Iic c), { exfalso, apply hcbot, simp only [subtype.ext_iff, set.Iic.coe_bot, subtype.coe_mk] at con, exact con }, rw [← subtype.coe_le_coe, subtype.coe_mk] at hac, exact ⟨a, ha.of_is_atom_coe_Iic, hac.trans hcb⟩ }, end⟩ /-- See Lemma 5.1, Călugăreanu -/ @[priority 100] instance is_atomistic_of_is_complemented [is_complemented α] : is_atomistic α := ⟨λ b, ⟨{a | is_atom a ∧ a ≤ b}, begin symmetry, have hle : Sup {a : α | is_atom a ∧ a ≤ b} ≤ b := (Sup_le $ λ _, and.right), apply (lt_or_eq_of_le hle).resolve_left (λ con, _), obtain ⟨c, hc⟩ := exists_is_compl (⟨Sup {a : α | is_atom a ∧ a ≤ b}, hle⟩ : set.Iic b), obtain rfl | ⟨a, ha, hac⟩ := eq_bot_or_exists_atom_le c, { exact ne_of_lt con (subtype.ext_iff.1 (eq_top_of_is_compl_bot hc)) }, { apply ha.1, rw eq_bot_iff, apply le_trans (le_inf _ hac) hc.1, rw [← subtype.coe_le_coe, subtype.coe_mk], exact le_Sup ⟨ha.of_is_atom_coe_Iic, a.2⟩ } end, λ _, and.left⟩⟩ /-- See Theorem 6.6, Călugăreanu -/ theorem is_complemented_of_Sup_atoms_eq_top (h : Sup {a : α | is_atom a} = ⊤) : is_complemented α := ⟨λ b, begin obtain ⟨s, ⟨s_ind, b_inf_Sup_s, s_atoms⟩, s_max⟩ := zorn.zorn_subset {s : set α | complete_lattice.independent s ∧ b ⊓ Sup s = ⊥ ∧ ∀ a ∈ s, is_atom a} _, { refine ⟨Sup s, le_of_eq b_inf_Sup_s, _⟩, rw [← h, Sup_le_iff], intros a ha, rw ← inf_eq_left, refine (eq_bot_or_eq_of_le_atom ha inf_le_left).resolve_left (λ con, ha.1 _), rw [eq_bot_iff, ← con], refine le_inf (le_refl a) ((le_Sup _).trans le_sup_right), rw ← disjoint_iff at *, have a_dis_Sup_s : disjoint a (Sup s) := con.mono_right le_sup_right, rw ← s_max (s ∪ {a}) ⟨λ x hx, _, ⟨_, λ x hx, _⟩⟩ (set.subset_union_left _ _), { exact set.mem_union_right _ (set.mem_singleton _) }, { rw [set.mem_union, set.mem_singleton_iff] at hx, by_cases xa : x = a, { simp only [xa, set.mem_singleton, set.insert_diff_of_mem, set.union_singleton], exact con.mono_right (le_trans (Sup_le_Sup (set.diff_subset s {a})) le_sup_right) }, { have h : (s ∪ {a}) \ {x} = (s \ {x}) ∪ {a}, { simp only [set.union_singleton], rw set.insert_diff_of_not_mem, rw set.mem_singleton_iff, exact ne.symm xa }, rw [h, Sup_union, Sup_singleton], apply (s_ind (hx.resolve_right xa)).disjoint_sup_right_of_disjoint_sup_left (a_dis_Sup_s.mono_right _).symm, rw [← Sup_insert, set.insert_diff_singleton, set.insert_eq_of_mem (hx.resolve_right xa)] } }, { rw [Sup_union, Sup_singleton, ← disjoint_iff], exact b_inf_Sup_s.disjoint_sup_right_of_disjoint_sup_left con.symm }, { rw [set.mem_union, set.mem_singleton_iff] at hx, cases hx, { exact s_atoms x hx }, { rw hx, exact ha } } }, { intros c hc1 hc2, refine ⟨⋃₀ c, ⟨complete_lattice.independent_sUnion_of_directed hc2.directed_on (λ s hs, (hc1 hs).1), _, λ a ha, _⟩, λ _, set.subset_sUnion_of_mem⟩, { rw [Sup_sUnion, ← Sup_image, inf_Sup_eq_of_directed_on, supr_eq_bot], { intro i, rw supr_eq_bot, intro hi, obtain ⟨x, xc, rfl⟩ := (set.mem_image _ _ _).1 hi, exact (hc1 xc).2.1 }, { rw directed_on_image, refine hc2.directed_on.mono (λ s t, Sup_le_Sup) } }, { rcases set.mem_sUnion.1 ha with ⟨s, sc, as⟩, exact (hc1 sc).2.2 a as } } end⟩ /-- See Theorem 6.6, Călugăreanu -/ theorem is_complemented_of_is_atomistic [is_atomistic α] : is_complemented α := is_complemented_of_Sup_atoms_eq_top Sup_atoms_eq_top theorem is_complemented_iff_is_atomistic : is_complemented α ↔ is_atomistic α := begin split; introsI, { exact is_atomistic_of_is_complemented }, { exact is_complemented_of_is_atomistic } end end
3861d1b51e967a7d426a35d151d9e3a423638669
b7f22e51856f4989b970961f794f1c435f9b8f78
/hott/algebra/category/functor/adjoint.hlean
5231bc02e52a126f03a2c390530ba24f578971fb
[ "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
10,165
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Adjoint functors -/ import .attributes .examples open functor nat_trans is_trunc eq iso prod namespace category structure adjoint {C D : Precategory} (F : C ⇒ D) (G : D ⇒ C) := (η : 1 ⟹ G ∘f F) (ε : F ∘f G ⟹ 1) (H : Π(c : C), ε (F c) ∘ F (η c) = ID (F c)) (K : Π(d : D), G (ε d) ∘ η (G d) = ID (G d)) abbreviation to_unit [unfold 5] := @adjoint.η abbreviation to_counit [unfold 5] := @adjoint.ε abbreviation to_counit_unit_eq [unfold 5] := @adjoint.H abbreviation to_unit_counit_eq [unfold 5] := @adjoint.K -- TODO: define is_left_adjoint in terms of adjoint: -- structure is_left_adjoint (F : C ⇒ D) := -- (G : D ⇒ C) -- G -- (is_adjoint : adjoint F G) infix ` ⊣ `:55 := adjoint structure is_left_adjoint [class] {C D : Precategory} (F : C ⇒ D) := (G : D ⇒ C) (η : 1 ⟹ G ∘f F) (ε : F ∘f G ⟹ 1) (H : Π(c : C), ε (F c) ∘ F (η c) = ID (F c)) (K : Π(d : D), G (ε d) ∘ η (G d) = ID (G d)) abbreviation right_adjoint [unfold 4] := @is_left_adjoint.G abbreviation unit [unfold 4] := @is_left_adjoint.η abbreviation counit [unfold 4] := @is_left_adjoint.ε abbreviation counit_unit_eq [unfold 4] := @is_left_adjoint.H abbreviation unit_counit_eq [unfold 4] := @is_left_adjoint.K theorem is_prop_is_left_adjoint [instance] {C : Category} {D : Precategory} (F : C ⇒ D) : is_prop (is_left_adjoint F) := begin apply is_prop.mk, intro G G', cases G with G η ε H K, cases G' with G' η' ε' H' K', have lem₁ : Π(p : G = G'), p ▸ η = η' → p ▸ ε = ε' → is_left_adjoint.mk G η ε H K = is_left_adjoint.mk G' η' ε' H' K', begin intros p q r, induction p, induction q, induction r, esimp, apply apd011 (is_left_adjoint.mk G η ε) !is_prop.elim !is_prop.elimo end, have lem₂ : Π (d : carrier D), (to_fun_hom G (natural_map ε' d) ∘ natural_map η (to_fun_ob G' d)) ∘ to_fun_hom G' (natural_map ε d) ∘ natural_map η' (to_fun_ob G d) = id, begin intro d, esimp, rewrite [assoc], rewrite [-assoc (G (ε' d))], esimp, rewrite [nf_fn_eq_fn_nf_pt' G' ε η d], esimp, rewrite [assoc], esimp, rewrite [-assoc], rewrite [↑functor.compose, -respect_comp G], rewrite [nf_fn_eq_fn_nf_pt ε ε' d,nf_fn_eq_fn_nf_pt η' η (G d),▸*], rewrite [respect_comp G], rewrite [assoc,▸*,-assoc (G (ε d))], rewrite [↑functor.compose, -respect_comp G], rewrite [H' (G d)], rewrite [respect_id,▸*,id_right], apply K end, have lem₃ : Π (d : carrier D), (to_fun_hom G' (natural_map ε d) ∘ natural_map η' (to_fun_ob G d)) ∘ to_fun_hom G (natural_map ε' d) ∘ natural_map η (to_fun_ob G' d) = id, begin intro d, esimp, rewrite [assoc, -assoc (G' (ε d))], esimp, rewrite [nf_fn_eq_fn_nf_pt' G ε' η' d], esimp, rewrite [assoc], esimp, rewrite [-assoc], rewrite [↑functor.compose, -respect_comp G'], rewrite [nf_fn_eq_fn_nf_pt ε' ε d,nf_fn_eq_fn_nf_pt η η' (G' d)], esimp, rewrite [respect_comp G'], rewrite [assoc,▸*,-assoc (G' (ε' d))], rewrite [↑functor.compose, -respect_comp G'], rewrite [H (G' d)], rewrite [respect_id,▸*,id_right], apply K' end, fapply lem₁, { fapply functor.eq_of_pointwise_iso, { fapply change_natural_map, { exact (G' ∘fn1 ε) ∘n !assoc_natural_rev ∘n (η' ∘1nf G)}, { intro d, exact (G' (ε d) ∘ η' (G d))}, { intro d, exact ap (λx, _ ∘ x) !id_left}}, { intro d, fconstructor, { exact (G (ε' d) ∘ η (G' d))}, { exact lem₂ d }, { exact lem₃ d }}}, { clear lem₁, refine transport_hom_of_eq_right _ η ⬝ _, krewrite hom_of_eq_compose_right, rewrite functor.hom_of_eq_eq_of_pointwise_iso, apply nat_trans_eq, intro c, esimp, refine !assoc⁻¹ ⬝ ap (λx, _ ∘ x) (nf_fn_eq_fn_nf_pt η η' c) ⬝ !assoc ⬝ _, esimp, rewrite [-respect_comp G',H c,respect_id G',▸*,id_left]}, { clear lem₁, refine transport_hom_of_eq_left _ ε ⬝ _, krewrite inv_of_eq_compose_left, rewrite functor.inv_of_eq_eq_of_pointwise_iso, apply nat_trans_eq, intro d, esimp, krewrite [respect_comp], rewrite [assoc,nf_fn_eq_fn_nf_pt ε' ε d,-assoc,▸*,H (G' d),id_right]} end section universe variables u v w parameters {C : Precategory.{u v}} {D : Precategory.{w v}} {F : C ⇒ D} {G : D ⇒ C} (θ : hom_functor D ∘f prod_functor_prod Fᵒᵖᶠ 1 ≅ hom_functor C ∘f prod_functor_prod 1 G) include θ definition adj_unit [constructor] : 1 ⟹ G ∘f F := begin fapply nat_trans.mk: esimp, { intro c, exact natural_map (to_hom θ) (c, F c) id}, { intro c c' f, note H := naturality (to_hom θ) (ID c, F f), note K := ap10 H id, rewrite [▸* at K, id_right at K, ▸*, K, respect_id, +id_right], clear H K, note H := naturality (to_hom θ) (f, ID (F c')), note K := ap10 H id, rewrite [▸* at K, respect_id at K,+id_left at K, K]} end definition adj_counit [constructor] : F ∘f G ⟹ 1 := begin fapply nat_trans.mk: esimp, { intro d, exact natural_map (to_inv θ) (G d, d) id, }, { intro d d' g, note H := naturality (to_inv θ) (Gᵒᵖᶠ g, ID d'), note K := ap10 H id, rewrite [▸* at K, id_left at K, ▸*, K, respect_id, +id_left], clear H K, note H := naturality (to_inv θ) (ID (G d), g), note K := ap10 H id, rewrite [▸* at K, respect_id at K,+id_right at K, K]} end theorem adj_eq_unit (c : C) (d : D) (f : F c ⟶ d) : natural_map (to_hom θ) (c, d) f = G f ∘ adj_unit c := begin esimp, note H := naturality (to_hom θ) (ID c, f), note K := ap10 H id, rewrite [▸* at K, id_right at K, K, respect_id, +id_right], end theorem adj_eq_counit (c : C) (d : D) (g : c ⟶ G d) : natural_map (to_inv θ) (c, d) g = adj_counit d ∘ F g := begin esimp, note H := naturality (to_inv θ) (g, ID d), note K := ap10 H id, rewrite [▸* at K, id_left at K, K, respect_id, +id_left], end definition adjoint.mk' [constructor] : F ⊣ G := begin fapply adjoint.mk, { exact adj_unit}, { exact adj_counit}, { intro c, esimp, refine (adj_eq_counit c (F c) (adj_unit c))⁻¹ ⬝ _, apply ap10 (to_left_inverse (componentwise_iso θ (c, F c)))}, { intro d, esimp, refine (adj_eq_unit (G d) d (adj_counit d))⁻¹ ⬝ _, apply ap10 (to_right_inverse (componentwise_iso θ (G d, d)))}, end end /- TODO (below): generalize above definitions to arbitrary categories section universe variables u₁ u₂ v₁ v₂ parameters {C : Precategory.{u₁ v₁}} {D : Precategory.{u₂ v₂}} {F : C ⇒ D} {G : D ⇒ C} (θ : functor_lift.{v₂ v₁} ∘f hom_functor D ∘f prod_functor_prod Fᵒᵖᶠ 1 ≅ functor_lift.{v₁ v₂} ∘f hom_functor C ∘f prod_functor_prod 1 G) include θ open lift definition adj_unit [constructor] : 1 ⟹ G ∘f F := begin fapply nat_trans.mk: esimp, { intro c, exact down (natural_map (to_hom θ) (c, F c) (up id))}, { intro c c' f, let H := naturality (to_hom θ) (ID c, F f), let K := ap10 H (up id), rewrite [▸* at K, id_right at K, ▸*, K, respect_id, +id_right], clear H K, let H := naturality (to_hom θ) (f, ID (F c')), let K := ap10 H id, rewrite [▸* at K, respect_id at K,+id_left at K, K]} end definition adj_counit [constructor] : F ∘f G ⟹ 1 := begin fapply nat_trans.mk: esimp, { intro d, exact natural_map (to_inv θ) (G d, d) id, }, { intro d d' g, let H := naturality (to_inv θ) (Gᵒᵖᶠ g, ID d'), let K := ap10 H id, rewrite [▸* at K, id_left at K, ▸*, K, respect_id, +id_left], clear H K, let H := naturality (to_inv θ) (ID (G d), g), let K := ap10 H id, rewrite [▸* at K, respect_id at K,+id_right at K, K]} end theorem adj_eq_unit (c : C) (d : D) (f : F c ⟶ d) : natural_map (to_hom θ) (c, d) (up f) = G f ∘ adj_unit c := begin esimp, let H := naturality (to_hom θ) (ID c, f), let K := ap10 H id, rewrite [▸* at K, id_right at K, K, respect_id, +id_right], end theorem adj_eq_counit (c : C) (d : D) (g : c ⟶ G d) : natural_map (to_inv θ) (c, d) (up g) = adj_counit d ∘ F g := begin esimp, let H := naturality (to_inv θ) (g, ID d), let K := ap10 H id, rewrite [▸* at K, id_left at K, K, respect_id, +id_left], end definition adjoint.mk' [constructor] : F ⊣ G := begin fapply adjoint.mk, { exact adj_unit}, { exact adj_counit}, { intro c, esimp, refine (adj_eq_counit c (F c) (adj_unit c))⁻¹ ⬝ _, apply ap10 (to_left_inverse (componentwise_iso θ (c, F c)))}, { intro d, esimp, refine (adj_eq_unit (G d) d (adj_counit d))⁻¹ ⬝ _, apply ap10 (to_right_inverse (componentwise_iso θ (G d, d)))}, end end -/ variables {C D : Precategory} {F : C ⇒ D} {G : D ⇒ C} definition adjoint_opposite [constructor] (H : F ⊣ G) : Gᵒᵖᶠ ⊣ Fᵒᵖᶠ := begin fconstructor, { rexact opposite_nat_trans (to_counit H)}, { rexact opposite_nat_trans (to_unit H)}, { rexact to_unit_counit_eq H}, { rexact to_counit_unit_eq H} end definition adjoint_of_opposite [constructor] (H : Fᵒᵖᶠ ⊣ Gᵒᵖᶠ) : G ⊣ F := begin fconstructor, { rexact opposite_rev_nat_trans (to_counit H)}, { rexact opposite_rev_nat_trans (to_unit H)}, { rexact to_unit_counit_eq H}, { rexact to_counit_unit_eq H} end end category
2401cba65c7440cdfe10ac8871269b7f8de6b426
bb31430994044506fa42fd667e2d556327e18dfe
/src/algebra/module/pid.lean
4b3a7fc1c6440216f6018335f6d636f6329d1ffd
[ "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
13,124
lean
/- Copyright (c) 2022 Pierre-Alexandre Bazin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Pierre-Alexandre Bazin -/ import algebra.module.dedekind_domain import linear_algebra.free_module.pid import algebra.module.projective import algebra.category.Module.biproducts /-! # Structure of finitely generated modules over a PID ## Main statements * `module.equiv_direct_sum_of_is_torsion` : A finitely generated torsion module over a PID is isomorphic to a direct sum of some `R ⧸ R ∙ (p i ^ e i)` where the `p i ^ e i` are prime powers. * `module.equiv_free_prod_direct_sum` : A finitely generated module over a PID is isomorphic to the product of a free module (its torsion free part) and a direct sum of the form above (its torsion submodule). ## Notation * `R` is a PID and `M` is a (finitely generated for main statements) `R`-module, with additional torsion hypotheses in the intermediate lemmas. * `N` is a `R`-module lying over a higher type universe than `R`. This assumption is needed on the final statement for technical reasons. * `p` is an irreducible element of `R` or a tuple of these. ## Implementation details We first prove (`submodule.is_internal_prime_power_torsion_of_pid`) that a finitely generated torsion module is the internal direct sum of its `p i ^ e i`-torsion submodules for some (finitely many) prime powers `p i ^ e i`. This is proved in more generality for a Dedekind domain at `submodule.is_internal_prime_power_torsion`. Then we treat the case of a `p ^ ∞`-torsion module (that is, a module where all elements are cancelled by scalar multiplication by some power of `p`) and apply it to the `p i ^ e i`-torsion submodules (that are `p i ^ ∞`-torsion) to get the result for torsion modules. Then we get the general result using that a torsion free module is free (which has been proved at `module.free_of_finite_type_torsion_free'` at `linear_algebra/free_module/pid.lean`.) ## Tags Finitely generated module, principal ideal domain, classification, structure theorem -/ universes u v open_locale big_operators variables {R : Type u} [comm_ring R] [is_domain R] [is_principal_ideal_ring R] variables {M : Type v} [add_comm_group M] [module R M] variables {N : Type (max u v)} [add_comm_group N] [module R N] open_locale direct_sum open submodule /--A finitely generated torsion module over a PID is an internal direct sum of its `p i ^ e i`-torsion submodules for some primes `p i` and numbers `e i`.-/ theorem submodule.is_internal_prime_power_torsion_of_pid [module.finite R M] (hM : module.is_torsion R M) : ∃ (ι : Type u) [fintype ι] [decidable_eq ι] (p : ι → R) (h : ∀ i, irreducible $ p i) (e : ι → ℕ), by exactI direct_sum.is_internal (λ i, torsion_by R M $ p i ^ e i) := begin obtain ⟨P, dec, hP, e, this⟩ := is_internal_prime_power_torsion hM, refine ⟨P, infer_instance, dec, λ p, is_principal.generator (p : ideal R), _, e, _⟩, { rintro ⟨p, hp⟩, haveI := ideal.is_prime_of_prime (hP p hp), exact (is_principal.prime_generator_of_is_prime p (hP p hp).ne_zero).irreducible }, { convert this, ext p : 1, rw [← torsion_by_span_singleton_eq, ideal.submodule_span_eq, ← ideal.span_singleton_pow, ideal.span_singleton_generator] } end namespace module section p_torsion variables {p : R} (hp : irreducible p) (hM : module.is_torsion' M (submonoid.powers p)) variables [dec : Π x : M, decidable (x = 0)] open ideal submodule.is_principal include dec include hp hM lemma _root_.ideal.torsion_of_eq_span_pow_p_order (x : M) : torsion_of R M x = span {p ^ p_order hM x} := begin dunfold p_order, rw [← (torsion_of R M x).span_singleton_generator, ideal.span_singleton_eq_span_singleton, ← associates.mk_eq_mk_iff_associated, associates.mk_pow], have prop : (λ n : ℕ, p ^ n • x = 0) = λ n : ℕ, (associates.mk $ generator $ torsion_of R M x) ∣ associates.mk p ^ n, { ext n, rw [← associates.mk_pow, associates.mk_dvd_mk, ← mem_iff_generator_dvd], refl }, have := (is_torsion'_powers_iff p).mp hM x, rw prop at this, classical, convert associates.eq_pow_find_of_dvd_irreducible_pow ((associates.irreducible_mk p).mpr hp) this.some_spec, end lemma p_pow_smul_lift {x y : M} {k : ℕ} (hM' : module.is_torsion_by R M (p ^ p_order hM y)) (h : p ^ k • x ∈ R ∙ y) : ∃ a : R, p ^ k • x = p ^ k • a • y := begin by_cases hk : k ≤ p_order hM y, { let f := ((R ∙ p ^ (p_order hM y - k) * p ^ k).quot_equiv_of_eq _ _).trans (quot_torsion_of_equiv_span_singleton R M y), have : f.symm ⟨p ^ k • x, h⟩ ∈ R ∙ ideal.quotient.mk (R ∙ p ^ (p_order hM y - k) * p ^ k) (p ^ k), { rw [← quotient.torsion_by_eq_span_singleton, mem_torsion_by_iff, ← f.symm.map_smul], convert f.symm.map_zero, ext, rw [coe_smul_of_tower, coe_mk, coe_zero, smul_smul, ← pow_add, nat.sub_add_cancel hk, @hM' x], { exact mem_non_zero_divisors_of_ne_zero (pow_ne_zero _ hp.ne_zero) } }, rw submodule.mem_span_singleton at this, obtain ⟨a, ha⟩ := this, use a, rw [f.eq_symm_apply, ← ideal.quotient.mk_eq_mk, ← quotient.mk_smul] at ha, dsimp only [smul_eq_mul, f, linear_equiv.trans_apply, submodule.quot_equiv_of_eq_mk, quot_torsion_of_equiv_span_singleton_apply_mk] at ha, rw [smul_smul, mul_comm], exact congr_arg coe ha.symm, { symmetry, convert ideal.torsion_of_eq_span_pow_p_order hp hM y, rw [← pow_add, nat.sub_add_cancel hk] } }, { use 0, rw [zero_smul, smul_zero, ← nat.sub_add_cancel (le_of_not_le hk), pow_add, mul_smul, hM', smul_zero] } end open submodule.quotient lemma exists_smul_eq_zero_and_mk_eq {z : M} (hz : module.is_torsion_by R M (p ^ p_order hM z)) {k : ℕ} (f : (R ⧸ R ∙ p ^ k) →ₗ[R] M ⧸ R ∙ z) : ∃ x : M, p ^ k • x = 0 ∧ submodule.quotient.mk x = f 1 := begin have f1 := mk_surjective (R ∙ z) (f 1), have : p ^ k • f1.some ∈ R ∙ z, { rw [← quotient.mk_eq_zero, mk_smul, f1.some_spec, ← f.map_smul], convert f.map_zero, change _ • submodule.quotient.mk _ = _, rw [← mk_smul, quotient.mk_eq_zero, algebra.id.smul_eq_mul, mul_one], exact submodule.mem_span_singleton_self _ }, obtain ⟨a, ha⟩ := p_pow_smul_lift hp hM hz this, refine ⟨f1.some - a • z, by rw [smul_sub, sub_eq_zero, ha], _⟩, rw [mk_sub, mk_smul, (quotient.mk_eq_zero _).mpr $ submodule.mem_span_singleton_self _, smul_zero, sub_zero, f1.some_spec] end open finset multiset omit dec hM /--A finitely generated `p ^ ∞`-torsion module over a PID is isomorphic to a direct sum of some `R ⧸ R ∙ (p ^ e i)` for some `e i`.-/ theorem torsion_by_prime_power_decomposition (hN : module.is_torsion' N (submonoid.powers p)) [h' : module.finite R N] : ∃ (d : ℕ) (k : fin d → ℕ), nonempty $ N ≃ₗ[R] ⨁ (i : fin d), R ⧸ R ∙ (p ^ (k i : ℕ)) := begin obtain ⟨d, s, hs⟩ := @module.finite.exists_fin _ _ _ _ _ h', use d, clear h', unfreezingI { induction d with d IH generalizing N }, { use λ i, fin_zero_elim i, rw [set.range_eq_empty, submodule.span_empty] at hs, haveI : unique N := ⟨⟨0⟩, λ x, by { rw [← mem_bot _, hs], trivial }⟩, exact ⟨0⟩ }, { haveI : Π x : N, decidable (x = 0), classical, apply_instance, obtain ⟨j, hj⟩ := exists_is_torsion_by hN d.succ d.succ_ne_zero s hs, let s' : fin d → N ⧸ R ∙ s j := submodule.quotient.mk ∘ s ∘ j.succ_above, obtain ⟨k, ⟨f⟩⟩ := IH _ s' _; clear IH, { have : ∀ i : fin d, ∃ x : N, p ^ k i • x = 0 ∧ f (submodule.quotient.mk x) = direct_sum.lof R _ _ i 1, { intro i, let fi := f.symm.to_linear_map.comp (direct_sum.lof _ _ _ i), obtain ⟨x, h0, h1⟩ := exists_smul_eq_zero_and_mk_eq hp hN hj fi, refine ⟨x, h0, _⟩, rw h1, simp only [linear_map.coe_comp, f.symm.coe_to_linear_map, f.apply_symm_apply] }, refine ⟨_, ⟨((( @lequiv_prod_of_right_split_exact _ _ _ _ _ _ _ _ _ _ _ _ ((f.trans ulift.module_equiv.{u u v}.symm).to_linear_map.comp $ mkq _) ((direct_sum.to_module _ _ _ $ λ i, (liftq_span_singleton.{u u} (p ^ k i) (linear_map.to_span_singleton _ _ _) (this i).some_spec.left : R ⧸ _ →ₗ[R] _)).comp ulift.module_equiv.to_linear_map) (R ∙ s j).injective_subtype _ _).symm.trans $ ((quot_torsion_of_equiv_span_singleton _ _ _).symm.trans $ quot_equiv_of_eq _ _ $ ideal.torsion_of_eq_span_pow_p_order hp hN _).prod $ ulift.module_equiv).trans $ (@direct_sum.lequiv_prod_direct_sum R _ _ _ (λ i, R ⧸ R ∙ p ^ @option.rec _ (λ _, ℕ) (p_order hN $ s j) k i) _ _).symm).trans $ direct_sum.lequiv_congr_left R (fin_succ_equiv d).symm⟩⟩, { rw [range_subtype, linear_equiv.to_linear_map_eq_coe, linear_equiv.ker_comp, ker_mkq] }, { rw [linear_equiv.to_linear_map_eq_coe, ← f.comp_coe, linear_map.comp_assoc, linear_map.comp_assoc, ← linear_equiv.to_linear_map_eq_coe, linear_equiv.to_linear_map_symm_comp_eq, linear_map.comp_id, ← linear_map.comp_assoc, ← linear_map.comp_assoc], suffices : (f.to_linear_map.comp (R ∙ s j).mkq).comp _ = linear_map.id, { rw [← f.to_linear_map_eq_coe, this, linear_map.id_comp] }, ext i : 3, simp only [linear_map.coe_comp, function.comp_app, mkq_apply], rw [linear_equiv.coe_to_linear_map, linear_map.id_apply, direct_sum.to_module_lof, liftq_span_singleton_apply, linear_map.to_span_singleton_one, ideal.quotient.mk_eq_mk, map_one, (this i).some_spec.right] } }, { exact (mk_surjective _).forall.mpr (λ x, ⟨(@hN x).some, by rw [← quotient.mk_smul, (@hN x).some_spec, quotient.mk_zero]⟩) }, { have hs' := congr_arg (submodule.map $ mkq $ R ∙ s j) hs, rw [submodule.map_span, submodule.map_top, range_mkq] at hs', simp only [mkq_apply] at hs', simp only [s'], rw [set.range_comp (_ ∘ s), fin.range_succ_above], rw [← set.range_comp, ← set.insert_image_compl_eq_range _ j, function.comp_apply, (quotient.mk_eq_zero _).mpr (submodule.mem_span_singleton_self _), span_insert_zero] at hs', exact hs' } } end end p_torsion /--A finitely generated torsion module over a PID is isomorphic to a direct sum of some `R ⧸ R ∙ (p i ^ e i)` where the `p i ^ e i` are prime powers.-/ theorem equiv_direct_sum_of_is_torsion [h' : module.finite R N] (hN : module.is_torsion R N) : ∃ (ι : Type u) [fintype ι] (p : ι → R) (h : ∀ i, irreducible $ p i) (e : ι → ℕ), nonempty $ N ≃ₗ[R] ⨁ (i : ι), R ⧸ R ∙ (p i ^ e i) := begin obtain ⟨I, fI, _, p, hp, e, h⟩ := submodule.is_internal_prime_power_torsion_of_pid hN, haveI := fI, have : ∀ i, ∃ (d : ℕ) (k : fin d → ℕ), nonempty $ torsion_by R N (p i ^ e i) ≃ₗ[R] ⨁ j, R ⧸ R ∙ (p i ^ k j), { haveI := is_noetherian_of_fg_of_noetherian' (module.finite_def.mp h'), haveI := λ i, is_noetherian_submodule' (torsion_by R N $ p i ^ e i), exact λ i, torsion_by_prime_power_decomposition (hp i) ((is_torsion'_powers_iff $ p i).mpr $ λ x, ⟨e i, smul_torsion_by _ _⟩) }, refine ⟨Σ i, fin (this i).some, infer_instance, λ ⟨i, j⟩, p i, λ ⟨i, j⟩, hp i, λ ⟨i, j⟩, (this i).some_spec.some j, ⟨(linear_equiv.of_bijective (direct_sum.coe_linear_map _) h).symm.trans $ (dfinsupp.map_range.linear_equiv $ λ i, (this i).some_spec.some_spec.some).trans $ (direct_sum.sigma_lcurry_equiv R).symm.trans (dfinsupp.map_range.linear_equiv $ λ i, quot_equiv_of_eq _ _ _)⟩⟩, cases i with i j, simp only end /--**Structure theorem of finitely generated modules over a PID** : A finitely generated module over a PID is isomorphic to the product of a free module and a direct sum of some `R ⧸ R ∙ (p i ^ e i)` where the `p i ^ e i` are prime powers.-/ theorem equiv_free_prod_direct_sum [h' : module.finite R N] : ∃ (n : ℕ) (ι : Type u) [fintype ι] (p : ι → R) (h : ∀ i, irreducible $ p i) (e : ι → ℕ), nonempty $ N ≃ₗ[R] (fin n →₀ R) × ⨁ (i : ι), R ⧸ R ∙ (p i ^ e i) := begin haveI := is_noetherian_of_fg_of_noetherian' (module.finite_def.mp h'), haveI := is_noetherian_submodule' (torsion R N), haveI := module.finite.of_surjective _ (torsion R N).mkq_surjective, obtain ⟨I, fI, p, hp, e, ⟨h⟩⟩ := equiv_direct_sum_of_is_torsion (@torsion_is_torsion R N _ _ _), obtain ⟨n, ⟨g⟩⟩ := @module.free_of_finite_type_torsion_free' R _ _ _ (N ⧸ torsion R N) _ _ _ _, haveI : module.projective R (N ⧸ torsion R N) := module.projective_of_basis ⟨g⟩, obtain ⟨f, hf⟩ := module.projective_lifting_property _ linear_map.id (torsion R N).mkq_surjective, refine ⟨n, I, fI, p, hp, e, ⟨(lequiv_prod_of_right_split_exact (torsion R N).injective_subtype _ hf).symm.trans $ (h.prod g).trans $ linear_equiv.prod_comm R _ _⟩⟩, rw [range_subtype, ker_mkq] end end module
ef3d68c187cdcb80a97a7ce6d9339ab1c86c8df2
6fca17f8d5025f89be1b2d9d15c9e0c4b4900cbf
/src/game/world6/level9.lean
0a9d2a3903e6446fa07a5d12f74619eb46b9ca48
[ "Apache-2.0" ]
permissive
arolihas/natural_number_game
4f0c93feefec93b8824b2b96adff8b702b8b43ce
8e4f7b4b42888a3b77429f90cce16292bd288138
refs/heads/master
1,621,872,426,808
1,586,270,467,000
1,586,270,467,000
253,648,466
0
0
null
1,586,219,694,000
1,586,219,694,000
null
UTF-8
Lean
false
false
1,309
lean
/- # Proposition world. ## Level 9: a big maze. Lean's "congruence closure" tactic `cc` is good at mazes. You might want to try it now. Perhaps I should have mentioned it earlier. -/ /- Lemma : no-side-bar There is a way through the following maze. -/ example (A B C D E F G H I J K L : Prop) (f1 : A → B) (f2 : B → E) (f3 : E → D) (f4 : D → A) (f5 : E → F) (f6 : F → C) (f7 : B → C) (f8 : F → G) (f9 : G → J) (f10 : I → J) (f11 : J → I) (f12 : I → H) (f13 : E → H) (f14 : H → K) (f15 : I → L) : A → L := begin end /- Now move onto advanced proposition world, where you will see how to prove goals such as `P ∧ Q` ($P$ and $Q$), `P ∨ Q` ($P$ or $Q$), `P ↔ Q` ($P\iff Q$). You will need to learn five more tactics: `split`, `cases`, `left`, `right`, and `exfalso`, but they are all straightforward, and furthermore they are essentially the last tactics you need to learn in order to complete all the levels of the Natural Number Game, including all the 17 levels of Inequality World. -/ /- Tactic : cc ## Summary: `cc` will solve certain "logic" goals. ## Details `cc` is a "congruence closure tactic". In practice this means that it is good at solving certain logic goals. It's worth trying if you think that the goal could be solved using truth tables. -/
a74bcee3ea7b1c500a9bc03746c49a42628f93f5
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/equiv/encodable/small.lean
c25cd62ba759e360b62b8adf8517bf17ac4f8bab
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
471
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 data.equiv.encodable.basic import logic.small /-! # All encodable types are small. That is, any encodable type is equivalent to a type in any universe. -/ universes w v @[priority 100] instance small_of_encodable (α : Type v) [encodable α] : small.{w} α := small_of_injective encodable.encode_injective
919ecd83303c2328ec47ae388934d8dcdcf79200
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/group_theory/subgroup.lean
42207619c5f846378b4d1e15b4893f38678355fc
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
56,897
lean
/- Copyright (c) 2020 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import group_theory.submonoid import algebra.group.conj import algebra.pointwise import order.modular_lattice /-! # Subgroups This file defines multiplicative and additive subgroups as an extension of submonoids, in a bundled form (unbundled subgroups are in `deprecated/subgroups.lean`). We prove subgroups of a group form a complete lattice, and results about images and preimages of subgroups under group homomorphisms. The bundled subgroups use bundled monoid homomorphisms. There are also theorems about the subgroups generated by an element or a subset of a group, defined both inductively and as the infimum of the set of subgroups containing a given element/subset. Special thanks goes to Amelia Livingston and Yury Kudryashov for their help and inspiration. ## Main definitions Notation used here: - `G N` are `group`s - `A` is an `add_group` - `H K` are `subgroup`s of `G` or `add_subgroup`s of `A` - `x` is an element of type `G` or type `A` - `f g : N →* G` are group homomorphisms - `s k` are sets of elements of type `G` Definitions in the file: * `subgroup G` : the type of subgroups of a group `G` * `add_subgroup A` : the type of subgroups of an additive group `A` * `complete_lattice (subgroup G)` : the subgroups of `G` form a complete lattice * `subgroup.closure k` : the minimal subgroup that includes the set `k` * `subgroup.subtype` : the natural group homomorphism from a subgroup of group `G` to `G` * `subgroup.gi` : `closure` forms a Galois insertion with the coercion to set * `subgroup.comap H f` : the preimage of a subgroup `H` along the group homomorphism `f` is also a subgroup * `subgroup.map f H` : the image of a subgroup `H` along the group homomorphism `f` is also a subgroup * `subgroup.prod H K` : the product of subgroups `H`, `K` of groups `G`, `N` respectively, `H × K` is a subgroup of `G × N` * `monoid_hom.range f` : the range of the group homomorphism `f` is a subgroup * `monoid_hom.ker f` : the kernel of a group homomorphism `f` is the subgroup of elements `x : G` such that `f x = 1` * `monoid_hom.eq_locus f g` : given group homomorphisms `f`, `g`, the elements of `G` such that `f x = g x` form a subgroup of `G` ## Implementation notes Subgroup inclusion is denoted `≤` rather than `⊆`, although `∈` is defined as membership of a subgroup's underlying set. ## Tags subgroup, subgroups -/ open_locale big_operators variables {G : Type*} [group G] variables {A : Type*} [add_group A] set_option old_structure_cmd true /-- A subgroup of a group `G` is a subset containing 1, closed under multiplication and closed under multiplicative inverse. -/ structure subgroup (G : Type*) [group G] extends submonoid G := (inv_mem' {x} : x ∈ carrier → x⁻¹ ∈ carrier) /-- An additive subgroup of an additive group `G` is a subset containing 0, closed under addition and additive inverse. -/ structure add_subgroup (G : Type*) [add_group G] extends add_submonoid G:= (neg_mem' {x} : x ∈ carrier → -x ∈ carrier) attribute [to_additive] subgroup attribute [to_additive add_subgroup.to_add_submonoid] subgroup.to_submonoid /-- Reinterpret a `subgroup` as a `submonoid`. -/ add_decl_doc subgroup.to_submonoid /-- Reinterpret an `add_subgroup` as an `add_submonoid`. -/ add_decl_doc add_subgroup.to_add_submonoid /-- Map from subgroups of group `G` to `add_subgroup`s of `additive G`. -/ def subgroup.to_add_subgroup {G : Type*} [group G] (H : subgroup G) : add_subgroup (additive G) := { neg_mem' := H.inv_mem', .. submonoid.to_add_submonoid H.to_submonoid} /-- Map from `add_subgroup`s of `additive G` to subgroups of `G`. -/ def subgroup.of_add_subgroup {G : Type*} [group G] (H : add_subgroup (additive G)) : subgroup G := { inv_mem' := H.neg_mem', .. submonoid.of_add_submonoid H.to_add_submonoid} /-- Map from `add_subgroup`s of `add_group G` to subgroups of `multiplicative G`. -/ def add_subgroup.to_subgroup {G : Type*} [add_group G] (H : add_subgroup G) : subgroup (multiplicative G) := { inv_mem' := H.neg_mem', .. add_submonoid.to_submonoid H.to_add_submonoid} /-- Map from subgroups of `multiplicative G` to `add_subgroup`s of `add_group G`. -/ def add_subgroup.of_subgroup {G : Type*} [add_group G] (H : subgroup (multiplicative G)) : add_subgroup G := { neg_mem' := H.inv_mem', .. add_submonoid.of_submonoid H.to_submonoid } /-- Subgroups of group `G` are isomorphic to additive subgroups of `additive G`. -/ def subgroup.add_subgroup_equiv (G : Type*) [group G] : subgroup G ≃ add_subgroup (additive G) := { to_fun := subgroup.to_add_subgroup, inv_fun := subgroup.of_add_subgroup, left_inv := λ x, by cases x; refl, right_inv := λ x, by cases x; refl } namespace subgroup @[to_additive] instance : has_coe (subgroup G) (set G) := { coe := subgroup.carrier } @[simp, to_additive] lemma coe_to_submonoid (K : subgroup G) : (K.to_submonoid : set G) = K := rfl @[to_additive] instance : has_mem G (subgroup G) := ⟨λ m K, m ∈ (K : set G)⟩ @[to_additive] instance : has_coe_to_sort (subgroup G) := ⟨_, λ G, (G : Type*)⟩ @[simp, norm_cast, to_additive] lemma mem_coe {K : subgroup G} {g : G} : g ∈ (K : set G) ↔ g ∈ K := iff.rfl @[simp, norm_cast, to_additive] lemma coe_coe (K : subgroup G) : ↥(K : set G) = K := rfl -- note that `to_additive` transfers the `simp` attribute over but not the `norm_cast` attribute attribute [norm_cast] add_subgroup.mem_coe attribute [norm_cast] add_subgroup.coe_coe @[to_additive] instance (K : subgroup G) [d : decidable_pred K.carrier] [fintype G] : fintype K := show fintype {g : G // g ∈ K.carrier}, from infer_instance end subgroup @[to_additive] protected lemma subgroup.exists {K : subgroup G} {p : K → Prop} : (∃ x : K, p x) ↔ ∃ x ∈ K, p ⟨x, ‹x ∈ K›⟩ := set_coe.exists @[to_additive] protected lemma subgroup.forall {K : subgroup G} {p : K → Prop} : (∀ x : K, p x) ↔ ∀ x ∈ K, p ⟨x, ‹x ∈ K›⟩ := set_coe.forall namespace subgroup variables (H K : subgroup G) /-- Copy of a subgroup with a new `carrier` equal to the old one. Useful to fix definitional equalities.-/ @[to_additive "Copy of an additive subgroup with a new `carrier` equal to the old one. Useful to fix definitional equalities"] protected def copy (K : subgroup G) (s : set G) (hs : s = K) : subgroup G := { carrier := s, one_mem' := hs.symm ▸ K.one_mem', mul_mem' := hs.symm ▸ K.mul_mem', inv_mem' := hs.symm ▸ K.inv_mem' } /- Two subgroups are equal if the underlying set are the same. -/ @[to_additive "Two `add_group`s are equal if the underlying subsets are equal."] theorem ext' {H K : subgroup G} (h : (H : set G) = K) : H = K := by { cases H, cases K, congr, exact h } /- Two subgroups are equal if and only if the underlying subsets are equal. -/ @[to_additive "Two `add_subgroup`s are equal if and only if the underlying subsets are equal."] protected theorem ext'_iff {H K : subgroup G} : H = K ↔ (H : set G) = K := ⟨λ h, h ▸ rfl, ext'⟩ /-- Two subgroups are equal if they have the same elements. -/ @[ext, to_additive "Two `add_subgroup`s are equal if they have the same elements."] theorem ext {H K : subgroup G} (h : ∀ x, x ∈ H ↔ x ∈ K) : H = K := ext' $ set.ext h attribute [ext] add_subgroup.ext /-- A subgroup contains the group's 1. -/ @[to_additive "An `add_subgroup` contains the group's 0."] theorem one_mem : (1 : G) ∈ H := H.one_mem' /-- A subgroup is closed under multiplication. -/ @[to_additive "An `add_subgroup` is closed under addition."] theorem mul_mem {x y : G} : x ∈ H → y ∈ H → x * y ∈ H := λ hx hy, H.mul_mem' hx hy /-- A subgroup is closed under inverse. -/ @[to_additive "An `add_subgroup` is closed under inverse."] theorem inv_mem {x : G} : x ∈ H → x⁻¹ ∈ H := λ hx, H.inv_mem' hx /-- A subgroup is closed under division. -/ @[to_additive "An `add_subgroup` is closed under subtraction."] theorem div_mem {x y : G} (hx : x ∈ H) (hy : y ∈ H) : x / y ∈ H := by simpa only [div_eq_mul_inv] using H.mul_mem' hx (H.inv_mem' hy) @[simp, to_additive] theorem inv_mem_iff {x : G} : x⁻¹ ∈ H ↔ x ∈ H := ⟨λ h, inv_inv x ▸ H.inv_mem h, H.inv_mem⟩ @[to_additive] lemma mul_mem_cancel_right {x y : G} (h : x ∈ H) : y * x ∈ H ↔ y ∈ H := ⟨λ hba, by simpa using H.mul_mem hba (H.inv_mem h), λ hb, H.mul_mem hb h⟩ @[to_additive] lemma mul_mem_cancel_left {x y : G} (h : x ∈ H) : x * y ∈ H ↔ y ∈ H := ⟨λ hab, by simpa using H.mul_mem (H.inv_mem h) hab, H.mul_mem h⟩ /-- Product of a list of elements in a subgroup is in the subgroup. -/ @[to_additive "Sum of a list of elements in an `add_subgroup` is in the `add_subgroup`."] lemma list_prod_mem {l : list G} : (∀ x ∈ l, x ∈ K) → l.prod ∈ K := K.to_submonoid.list_prod_mem /-- Product of a multiset of elements in a subgroup of a `comm_group` is in the subgroup. -/ @[to_additive "Sum of a multiset of elements in an `add_subgroup` of an `add_comm_group` is in the `add_subgroup`."] lemma multiset_prod_mem {G} [comm_group G] (K : subgroup G) (g : multiset G) : (∀ a ∈ g, a ∈ K) → g.prod ∈ K := K.to_submonoid.multiset_prod_mem g /-- Product of elements of a subgroup of a `comm_group` indexed by a `finset` is in the subgroup. -/ @[to_additive "Sum of elements in an `add_subgroup` of an `add_comm_group` indexed by a `finset` is in the `add_subgroup`."] lemma prod_mem {G : Type*} [comm_group G] (K : subgroup G) {ι : Type*} {t : finset ι} {f : ι → G} (h : ∀ c ∈ t, f c ∈ K) : ∏ c in t, f c ∈ K := K.to_submonoid.prod_mem h lemma pow_mem {x : G} (hx : x ∈ K) : ∀ n : ℕ, x ^ n ∈ K := K.to_submonoid.pow_mem hx lemma gpow_mem {x : G} (hx : x ∈ K) : ∀ n : ℤ, x ^ n ∈ K | (int.of_nat n) := pow_mem _ hx n | -[1+ n] := K.inv_mem $ K.pow_mem hx n.succ /-- Construct a subgroup from a nonempty set that is closed under division. -/ @[to_additive "Construct a subgroup from a nonempty set that is closed under subtraction"] def of_div (s : set G) (hsn : s.nonempty) (hs : ∀ x y ∈ s, x * y⁻¹ ∈ s) : subgroup G := have one_mem : (1 : G) ∈ s, from let ⟨x, hx⟩ := hsn in by simpa using hs x x hx hx, have inv_mem : ∀ x, x ∈ s → x⁻¹ ∈ s, from λ x hx, by simpa using hs 1 x one_mem hx, { carrier := s, one_mem' := one_mem, inv_mem' := inv_mem, mul_mem' := λ x y hx hy, by simpa using hs x y⁻¹ hx (inv_mem y hy) } /-- A subgroup of a group inherits a multiplication. -/ @[to_additive "An `add_subgroup` of an `add_group` inherits an addition."] instance has_mul : has_mul H := H.to_submonoid.has_mul /-- A subgroup of a group inherits a 1. -/ @[to_additive "An `add_subgroup` of an `add_group` inherits a zero."] instance has_one : has_one H := H.to_submonoid.has_one /-- A subgroup of a group inherits an inverse. -/ @[to_additive "A `add_subgroup` of a `add_group` inherits an inverse."] instance has_inv : has_inv H := ⟨λ a, ⟨a⁻¹, H.inv_mem a.2⟩⟩ /-- A subgroup of a group inherits a division -/ @[to_additive "An `add_subgroup` of an `add_group` inherits a subtraction."] instance has_div : has_div H := ⟨λ a b, ⟨a / b, H.div_mem a.2 b.2⟩⟩ @[simp, norm_cast, to_additive] lemma coe_mul (x y : H) : (↑(x * y) : G) = ↑x * ↑y := rfl @[simp, norm_cast, to_additive] lemma coe_one : ((1 : H) : G) = 1 := rfl @[simp, norm_cast, to_additive] lemma coe_inv (x : H) : ↑(x⁻¹ : H) = (x⁻¹ : G) := rfl @[simp, norm_cast, to_additive] lemma coe_mk (x : G) (hx : x ∈ H) : ((⟨x, hx⟩ : H) : G) = x := rfl attribute [norm_cast] add_subgroup.coe_add add_subgroup.coe_zero add_subgroup.coe_neg add_subgroup.coe_mk /-- A subgroup of a group inherits a group structure. -/ @[to_additive "An `add_subgroup` of an `add_group` inherits an `add_group` structure."] instance to_group {G : Type*} [group G] (H : subgroup G) : group H := { inv := has_inv.inv, div := (/), div_eq_mul_inv := λ x y, subtype.eq $ div_eq_mul_inv x y, mul_left_inv := λ x, subtype.eq $ mul_left_inv x, .. H.to_submonoid.to_monoid } /-- A subgroup of a `comm_group` is a `comm_group`. -/ @[to_additive "An `add_subgroup` of an `add_comm_group` is an `add_comm_group`."] instance to_comm_group {G : Type*} [comm_group G] (H : subgroup G) : comm_group H := { mul_comm := λ _ _, subtype.eq $ mul_comm _ _, .. H.to_group} /-- The natural group hom from a subgroup of group `G` to `G`. -/ @[to_additive "The natural group hom from an `add_subgroup` of `add_group` `G` to `G`."] def subtype : H →* G := ⟨coe, rfl, λ _ _, rfl⟩ @[simp, to_additive] theorem coe_subtype : ⇑H.subtype = coe := rfl @[simp, norm_cast] lemma coe_pow (x : H) (n : ℕ) : ((x ^ n : H) : G) = x ^ n := coe_subtype H ▸ monoid_hom.map_pow _ _ _ @[simp, norm_cast] lemma coe_gpow (x : H) (n : ℤ) : ((x ^ n : H) : G) = x ^ n := coe_subtype H ▸ monoid_hom.map_gpow _ _ _ @[to_additive] instance : has_le (subgroup G) := ⟨λ H K, ∀ ⦃x⦄, x ∈ H → x ∈ K⟩ @[to_additive] lemma le_def {H K : subgroup G} : H ≤ K ↔ ∀ ⦃x : G⦄, x ∈ H → x ∈ K := iff.rfl @[simp, to_additive] lemma coe_subset_coe {H K : subgroup G} : (H : set G) ⊆ K ↔ H ≤ K := iff.rfl /-- The inclusion homomorphism from a subgroup `H` contained in `K` to `K`. -/ @[to_additive "The inclusion homomorphism from a additive subgroup `H` contained in `K` to `K`."] def inclusion {H K : subgroup G} (h : H ≤ K) : H →* K := monoid_hom.mk' (λ x, ⟨x, h x.prop⟩) (λ ⟨a, ha⟩ ⟨b, hb⟩, rfl) @[simp, to_additive] lemma coe_inclusion {H K : subgroup G} {h : H ≤ K} (a : H) : (inclusion h a : G) = a := by { cases a, simp only [inclusion, coe_mk, monoid_hom.coe_mk'] } @[simp, to_additive] lemma subtype_comp_inclusion {H K : subgroup G} (hH : H ≤ K) : K.subtype.comp (inclusion hH) = H.subtype := by { ext, simp } @[to_additive] instance : partial_order (subgroup G) := { le := (≤), .. partial_order.lift (coe : subgroup G → set G) (λ a b, ext') } /-- The subgroup `G` of the group `G`. -/ @[to_additive "The `add_subgroup G` of the `add_group G`."] instance : has_top (subgroup G) := ⟨{ inv_mem' := λ _ _, set.mem_univ _ , .. (⊤ : submonoid G) }⟩ /-- The trivial subgroup `{1}` of an group `G`. -/ @[to_additive "The trivial `add_subgroup` `{0}` of an `add_group` `G`."] instance : has_bot (subgroup G) := ⟨{ inv_mem' := λ _, by simp *, .. (⊥ : submonoid G) }⟩ @[to_additive] instance : inhabited (subgroup G) := ⟨⊥⟩ @[simp, to_additive] lemma mem_bot {x : G} : x ∈ (⊥ : subgroup G) ↔ x = 1 := iff.rfl @[simp, to_additive] lemma mem_top (x : G) : x ∈ (⊤ : subgroup G) := set.mem_univ x @[simp, to_additive] lemma coe_top : ((⊤ : subgroup G) : set G) = set.univ := rfl @[simp, to_additive] lemma coe_bot : ((⊥ : subgroup G) : set G) = {1} := rfl @[to_additive] lemma eq_bot_iff_forall : H = ⊥ ↔ ∀ x ∈ H, x = (1 : G) := begin split, { intros h x x_in, rwa [h, mem_bot] at x_in }, { intros h, ext x, rw mem_bot, exact ⟨h x, by { rintros rfl, exact H.one_mem }⟩ }, end @[to_additive] lemma eq_top_of_card_eq [fintype H] [fintype G] (h : fintype.card H = fintype.card G) : H = ⊤ := begin classical, rw fintype.card_congr (equiv.refl _) at h, -- this swaps the fintype instance to classical change fintype.card H.carrier = _ at h, unfreezingI { cases H with S hS1 hS2 hS3, }, have : S = set.univ, { suffices : S.to_finset = finset.univ, { rwa [←set.to_finset_univ, set.to_finset_inj] at this, }, apply finset.eq_univ_of_card, rwa set.to_finset_card }, change (⟨_, _, _, _⟩ : subgroup G) = ⟨_, _, _, _⟩, congr', end @[to_additive] lemma nontrivial_iff_exists_ne_one (H : subgroup G) : nontrivial H ↔ ∃ x ∈ H, x ≠ (1:G) := begin split, { introI h, rcases exists_ne (1 : H) with ⟨⟨h, h_in⟩, h_ne⟩, use [h, h_in], intro hyp, apply h_ne, simpa [hyp] }, { rintros ⟨x, x_in, hx⟩, apply nontrivial_of_ne (⟨x, x_in⟩ : H) 1, intro hyp, apply hx, simpa [has_one.one] using hyp }, end /-- A subgroup is either the trivial subgroup or nontrivial. -/ @[to_additive] lemma bot_or_nontrivial (H : subgroup G) : H = ⊥ ∨ nontrivial H := begin classical, by_cases h : ∀ x ∈ H, x = (1 : G), { left, exact H.eq_bot_iff_forall.mpr h }, { right, push_neg at h, simpa [nontrivial_iff_exists_ne_one] using h }, end /-- A subgroup is either the trivial subgroup or contains a nonzero element. -/ @[to_additive] lemma bot_or_exists_ne_one (H : subgroup G) : H = ⊥ ∨ ∃ x ∈ H, x ≠ (1:G) := begin convert H.bot_or_nontrivial, rw nontrivial_iff_exists_ne_one end /-- The inf of two subgroups is their intersection. -/ @[to_additive "The inf of two `add_subgroups`s is their intersection."] instance : has_inf (subgroup G) := ⟨λ H₁ H₂, { inv_mem' := λ _ ⟨hx, hx'⟩, ⟨H₁.inv_mem hx, H₂.inv_mem hx'⟩, .. H₁.to_submonoid ⊓ H₂.to_submonoid }⟩ @[simp, to_additive] lemma coe_inf (p p' : subgroup G) : ((p ⊓ p' : subgroup G) : set G) = p ∩ p' := rfl @[simp, to_additive] lemma mem_inf {p p' : subgroup G} {x : G} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl @[to_additive] instance : has_Inf (subgroup G) := ⟨λ s, { inv_mem' := λ x hx, set.mem_bInter $ λ i h, i.inv_mem (by apply set.mem_bInter_iff.1 hx i h), .. (⨅ S ∈ s, subgroup.to_submonoid S).copy (⋂ S ∈ s, ↑S) (by simp) }⟩ @[simp, to_additive] lemma coe_Inf (H : set (subgroup G)) : ((Inf H : subgroup G) : set G) = ⋂ s ∈ H, ↑s := rfl attribute [norm_cast] coe_Inf add_subgroup.coe_Inf @[simp, to_additive] lemma mem_Inf {S : set (subgroup G)} {x : G} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_bInter_iff @[to_additive] lemma mem_infi {ι : Sort*} {S : ι → subgroup G} {x : G} : (x ∈ ⨅ i, S i) ↔ ∀ i, x ∈ S i := by simp only [infi, mem_Inf, set.forall_range_iff] @[simp, to_additive] lemma coe_infi {ι : Sort*} {S : ι → subgroup G} : (↑(⨅ i, S i) : set G) = ⋂ i, S i := by simp only [infi, coe_Inf, set.bInter_range] attribute [norm_cast] coe_infi add_subgroup.coe_infi /-- Subgroups of a group form a complete lattice. -/ @[to_additive "The `add_subgroup`s of an `add_group` form a complete lattice."] instance : complete_lattice (subgroup G) := { bot := (⊥), bot_le := λ S x hx, (mem_bot.1 hx).symm ▸ S.one_mem, top := (⊤), le_top := λ S x hx, mem_top x, inf := (⊓), le_inf := λ a b c ha hb x hx, ⟨ha hx, hb hx⟩, inf_le_left := λ a b x, and.left, inf_le_right := λ a b x, and.right, .. complete_lattice_of_Inf (subgroup G) $ λ s, is_glb.of_image (λ H K, show (H : set G) ≤ K ↔ H ≤ K, from coe_subset_coe) is_glb_binfi } @[to_additive] lemma mem_sup_left {S T : subgroup G} : ∀ {x : G}, x ∈ S → x ∈ S ⊔ T := show S ≤ S ⊔ T, from le_sup_left @[to_additive] lemma mem_sup_right {S T : subgroup G} : ∀ {x : G}, x ∈ T → x ∈ S ⊔ T := show T ≤ S ⊔ T, from le_sup_right @[to_additive] lemma mem_supr_of_mem {ι : Type*} {S : ι → subgroup G} (i : ι) : ∀ {x : G}, x ∈ S i → x ∈ supr S := show S i ≤ supr S, from le_supr _ _ @[to_additive] lemma mem_Sup_of_mem {S : set (subgroup G)} {s : subgroup G} (hs : s ∈ S) : ∀ {x : G}, x ∈ s → x ∈ Sup S := show s ≤ Sup S, from le_Sup hs @[to_additive] lemma subsingleton_iff : subsingleton G ↔ subsingleton (subgroup G) := ⟨ λ h, by exactI ⟨λ x y, subgroup.ext $ λ i, subsingleton.elim 1 i ▸ by simp [subgroup.one_mem]⟩, λ h, by exactI ⟨λ x y, have ∀ i : G, i = 1 := λ i, mem_bot.mp $ subsingleton.elim (⊤ : subgroup G) ⊥ ▸ mem_top i, (this x).trans (this y).symm⟩⟩ @[to_additive] lemma nontrivial_iff : nontrivial G ↔ nontrivial (subgroup G) := not_iff_not.mp ( (not_nontrivial_iff_subsingleton.trans subsingleton_iff).trans not_nontrivial_iff_subsingleton.symm) @[to_additive] instance [subsingleton G] : unique (subgroup G) := ⟨⟨⊥⟩, λ a, @subsingleton.elim _ (subsingleton_iff.mp ‹_›) a _⟩ @[to_additive] instance [nontrivial G] : nontrivial (subgroup G) := nontrivial_iff.mp ‹_› /-- The `subgroup` generated by a set. -/ @[to_additive "The `add_subgroup` generated by a set"] def closure (k : set G) : subgroup G := Inf {K | k ⊆ K} variable {k : set G} @[to_additive] lemma mem_closure {x : G} : x ∈ closure k ↔ ∀ K : subgroup G, k ⊆ K → x ∈ K := mem_Inf /-- The subgroup generated by a set includes the set. -/ @[simp, to_additive "The `add_subgroup` generated by a set includes the set."] lemma subset_closure : k ⊆ closure k := λ x hx, mem_closure.2 $ λ K hK, hK hx open set /-- A subgroup `K` includes `closure k` if and only if it includes `k`. -/ @[simp, to_additive "An additive subgroup `K` includes `closure k` if and only if it includes `k`"] lemma closure_le : closure k ≤ K ↔ k ⊆ K := ⟨subset.trans subset_closure, λ h, Inf_le h⟩ @[to_additive] lemma closure_eq_of_le (h₁ : k ⊆ K) (h₂ : K ≤ closure k) : closure k = K := le_antisymm ((closure_le $ K).2 h₁) h₂ /-- An induction principle for closure membership. If `p` holds for `1` and all elements of `k`, and is preserved under multiplication and inverse, then `p` holds for all elements of the closure of `k`. -/ @[to_additive "An induction principle for additive closure membership. If `p` holds for `0` and all elements of `k`, and is preserved under addition and isvers, then `p` holds for all elements of the additive closure of `k`."] lemma closure_induction {p : G → Prop} {x} (h : x ∈ closure k) (Hk : ∀ x ∈ k, p x) (H1 : p 1) (Hmul : ∀ x y, p x → p y → p (x * y)) (Hinv : ∀ x, p x → p x⁻¹) : p x := (@closure_le _ _ ⟨p, H1, Hmul, Hinv⟩ _).2 Hk h attribute [elab_as_eliminator] subgroup.closure_induction add_subgroup.closure_induction /-- An induction principle on elements of the subtype `subgroup.closure`. If `p` holds for `1` and all elements of `k`, and is preserved under multiplication and inverse, then `p` holds for all elements `x : closure k`. The difference with `subgroup.closure_induction` is that this acts on the subtype. -/ @[to_additive "An induction principle on elements of the subtype `add_subgroup.closure`. If `p` holds for `0` and all elements of `k`, and is preserved under addition and negation, then `p` holds for all elements `x : closure k`. The difference with `add_subgroup.closure_induction` is that this acts on the subtype."] lemma closure_induction' (k : set G) {p : closure k → Prop} (Hk : ∀ x (h : x ∈ k), p ⟨x, subset_closure h⟩) (H1 : p 1) (Hmul : ∀ x y, p x → p y → p (x * y)) (Hinv : ∀ x, p x → p x⁻¹) (x : closure k) : p x := subtype.rec_on x $ λ x hx, begin refine exists.elim _ (λ (hx : x ∈ closure k) (hc : p ⟨x, hx⟩), hc), exact closure_induction hx (λ x hx, ⟨subset_closure hx, Hk x hx⟩) ⟨one_mem _, H1⟩ (λ x y hx hy, exists.elim hx $ λ hx' hx, exists.elim hy $ λ hy' hy, ⟨mul_mem _ hx' hy', Hmul _ _ hx hy⟩) (λ x hx, exists.elim hx $ λ hx' hx, ⟨inv_mem _ hx', Hinv _ hx⟩), end attribute [elab_as_eliminator] subgroup.closure_induction' add_subgroup.closure_induction' variable (G) /-- `closure` forms a Galois insertion with the coercion to set. -/ @[to_additive "`closure` forms a Galois insertion with the coercion to set."] protected def gi : galois_insertion (@closure G _) coe := { choice := λ s _, closure s, gc := λ s t, @closure_le _ _ t s, le_l_u := λ s, subset_closure, choice_eq := λ s h, rfl } variable {G} /-- Subgroup closure of a set is monotone in its argument: if `h ⊆ k`, then `closure h ≤ closure k`. -/ @[to_additive "Additive subgroup closure of a set is monotone in its argument: if `h ⊆ k`, then `closure h ≤ closure k`"] lemma closure_mono ⦃h k : set G⦄ (h' : h ⊆ k) : closure h ≤ closure k := (subgroup.gi G).gc.monotone_l h' /-- Closure of a subgroup `K` equals `K`. -/ @[simp, to_additive "Additive closure of an additive subgroup `K` equals `K`"] lemma closure_eq : closure (K : set G) = K := (subgroup.gi G).l_u_eq K @[simp, to_additive] lemma closure_empty : closure (∅ : set G) = ⊥ := (subgroup.gi G).gc.l_bot @[simp, to_additive] lemma closure_univ : closure (univ : set G) = ⊤ := @coe_top G _ ▸ closure_eq ⊤ @[to_additive] lemma closure_union (s t : set G) : closure (s ∪ t) = closure s ⊔ closure t := (subgroup.gi G).gc.l_sup @[to_additive] lemma closure_Union {ι} (s : ι → set G) : closure (⋃ i, s i) = ⨆ i, closure (s i) := (subgroup.gi G).gc.l_supr @[to_additive] lemma closure_eq_bot_iff (G : Type*) [group G] (S : set G) : closure S = ⊥ ↔ S ⊆ {1} := by { rw [← le_bot_iff], exact closure_le _} /-- The subgroup generated by an element of a group equals the set of integer number powers of the element. -/ lemma mem_closure_singleton {x y : G} : y ∈ closure ({x} : set G) ↔ ∃ n : ℤ, x ^ n = y := begin refine ⟨λ hy, closure_induction hy _ _ _ _, λ ⟨n, hn⟩, hn ▸ gpow_mem _ (subset_closure $ mem_singleton x) n⟩, { intros y hy, rw [eq_of_mem_singleton hy], exact ⟨1, gpow_one x⟩ }, { exact ⟨0, rfl⟩ }, { rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩, exact ⟨n + m, gpow_add x n m⟩ }, rintros _ ⟨n, rfl⟩, exact ⟨-n, gpow_neg x n⟩ end lemma closure_singleton_one : closure ({1} : set G) = ⊥ := by simp [eq_bot_iff_forall, mem_closure_singleton] @[to_additive] lemma mem_supr_of_directed {ι} [hι : nonempty ι] {K : ι → subgroup G} (hK : directed (≤) K) {x : G} : x ∈ (supr K : subgroup G) ↔ ∃ i, x ∈ K i := begin refine ⟨_, λ ⟨i, hi⟩, (le_def.1 $ le_supr K i) hi⟩, suffices : x ∈ closure (⋃ i, (K i : set G)) → ∃ i, x ∈ K i, by simpa only [closure_Union, closure_eq (K _)] using this, refine (λ hx, closure_induction hx (λ _, mem_Union.1) _ _ _), { exact hι.elim (λ i, ⟨i, (K i).one_mem⟩) }, { rintros x y ⟨i, hi⟩ ⟨j, hj⟩, rcases hK i j with ⟨k, hki, hkj⟩, exact ⟨k, (K k).mul_mem (hki hi) (hkj hj)⟩ }, rintros _ ⟨i, hi⟩, exact ⟨i, inv_mem (K i) hi⟩ end @[to_additive] lemma coe_supr_of_directed {ι} [nonempty ι] {S : ι → subgroup G} (hS : directed (≤) S) : ((⨆ i, S i : subgroup G) : set G) = ⋃ i, ↑(S i) := set.ext $ λ x, by simp [mem_supr_of_directed hS] @[to_additive] lemma mem_Sup_of_directed_on {K : set (subgroup G)} (Kne : K.nonempty) (hK : directed_on (≤) K) {x : G} : x ∈ Sup K ↔ ∃ s ∈ K, x ∈ s := begin haveI : nonempty K := Kne.to_subtype, simp only [Sup_eq_supr', mem_supr_of_directed hK.directed_coe, set_coe.exists, subtype.coe_mk] end variables {N : Type*} [group N] {P : Type*} [group P] /-- The preimage of a subgroup along a monoid homomorphism is a subgroup. -/ @[to_additive "The preimage of an `add_subgroup` along an `add_monoid` homomorphism is an `add_subgroup`."] def comap {N : Type*} [group N] (f : G →* N) (H : subgroup N) : subgroup G := { carrier := (f ⁻¹' H), inv_mem' := λ a ha, show f a⁻¹ ∈ H, by rw f.map_inv; exact H.inv_mem ha, .. H.to_submonoid.comap f } @[simp, to_additive] lemma coe_comap (K : subgroup N) (f : G →* N) : (K.comap f : set G) = f ⁻¹' K := rfl @[simp, to_additive] lemma mem_comap {K : subgroup N} {f : G →* N} {x : G} : x ∈ K.comap f ↔ f x ∈ K := iff.rfl @[to_additive] lemma comap_comap (K : subgroup P) (g : N →* P) (f : G →* N) : (K.comap g).comap f = K.comap (g.comp f) := rfl /-- The image of a subgroup along a monoid homomorphism is a subgroup. -/ @[to_additive "The image of an `add_subgroup` along an `add_monoid` homomorphism is an `add_subgroup`."] def map (f : G →* N) (H : subgroup G) : subgroup N := { carrier := (f '' H), inv_mem' := by { rintros _ ⟨x, hx, rfl⟩, exact ⟨x⁻¹, H.inv_mem hx, f.map_inv x⟩ }, .. H.to_submonoid.map f } @[simp, to_additive] lemma coe_map (f : G →* N) (K : subgroup G) : (K.map f : set N) = f '' K := rfl @[simp, to_additive] lemma mem_map {f : G →* N} {K : subgroup G} {y : N} : y ∈ K.map f ↔ ∃ x ∈ K, f x = y := mem_image_iff_bex @[to_additive] lemma map_map (g : N →* P) (f : G →* N) : (K.map f).map g = K.map (g.comp f) := ext' $ image_image _ _ _ @[to_additive] lemma map_le_iff_le_comap {f : G →* N} {K : subgroup G} {H : subgroup N} : K.map f ≤ H ↔ K ≤ H.comap f := image_subset_iff @[to_additive] lemma gc_map_comap (f : G →* N) : galois_connection (map f) (comap f) := λ _ _, map_le_iff_le_comap @[to_additive] lemma map_sup (H K : subgroup G) (f : G →* N) : (H ⊔ K).map f = H.map f ⊔ K.map f := (gc_map_comap f).l_sup @[to_additive] lemma map_supr {ι : Sort*} (f : G →* N) (s : ι → subgroup G) : (supr s).map f = ⨆ i, (s i).map f := (gc_map_comap f).l_supr @[to_additive] lemma comap_inf (H K : subgroup N) (f : G →* N) : (H ⊓ K).comap f = H.comap f ⊓ K.comap f := (gc_map_comap f).u_inf @[to_additive] lemma comap_infi {ι : Sort*} (f : G →* N) (s : ι → subgroup N) : (infi s).comap f = ⨅ i, (s i).comap f := (gc_map_comap f).u_infi @[simp, to_additive] lemma map_bot (f : G →* N) : (⊥ : subgroup G).map f = ⊥ := (gc_map_comap f).l_bot @[simp, to_additive] lemma comap_top (f : G →* N) : (⊤ : subgroup N).comap f = ⊤ := (gc_map_comap f).u_top @[to_additive] lemma map_eq_bot_iff {G' : Type*} [group G'] {f : G →* G'} (hf : function.injective f) (H : subgroup G) : H.map f = ⊥ ↔ H = ⊥ := begin split, { rw [eq_bot_iff_forall, eq_bot_iff_forall], intros h x hx, have hfx : f x = 1 := h (f x) ⟨x, hx, rfl⟩, exact hf (show f x = f 1, by simp only [hfx, monoid_hom.map_one]), }, { intros h, rw [h, map_bot], }, end @[simp, to_additive] lemma comap_subtype_inf_left {H K : subgroup G} : comap H.subtype (H ⊓ K) = comap H.subtype K := ext $ λ x, and_iff_right_of_imp (λ _, x.prop) @[simp, to_additive] lemma comap_subtype_inf_right {H K : subgroup G} : comap K.subtype (H ⊓ K) = comap K.subtype H := ext $ λ x, and_iff_left_of_imp (λ _, x.prop) /-- Given `subgroup`s `H`, `K` of groups `G`, `N` respectively, `H × K` as a subgroup of `G × N`. -/ @[to_additive prod "Given `add_subgroup`s `H`, `K` of `add_group`s `A`, `B` respectively, `H × K` as an `add_subgroup` of `A × B`."] def prod (H : subgroup G) (K : subgroup N) : subgroup (G × N) := { inv_mem' := λ _ hx, ⟨H.inv_mem' hx.1, K.inv_mem' hx.2⟩, .. submonoid.prod H.to_submonoid K.to_submonoid} @[to_additive coe_prod] lemma coe_prod (H : subgroup G) (K : subgroup N) : (H.prod K : set (G × N)) = (H : set G).prod (K : set N) := rfl @[to_additive mem_prod] lemma mem_prod {H : subgroup G} {K : subgroup N} {p : G × N} : p ∈ H.prod K ↔ p.1 ∈ H ∧ p.2 ∈ K := iff.rfl @[to_additive prod_mono] lemma prod_mono : ((≤) ⇒ (≤) ⇒ (≤)) (@prod G _ N _) (@prod G _ N _) := λ s s' hs t t' ht, set.prod_mono hs ht @[to_additive prod_mono_right] lemma prod_mono_right (K : subgroup G) : monotone (λ t : subgroup N, K.prod t) := prod_mono (le_refl K) @[to_additive prod_mono_left] lemma prod_mono_left (H : subgroup N) : monotone (λ K : subgroup G, K.prod H) := λ s₁ s₂ hs, prod_mono hs (le_refl H) @[to_additive prod_top] lemma prod_top (K : subgroup G) : K.prod (⊤ : subgroup N) = K.comap (monoid_hom.fst G N) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst] @[to_additive top_prod] lemma top_prod (H : subgroup N) : (⊤ : subgroup G).prod H = H.comap (monoid_hom.snd G N) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd] @[simp, to_additive top_prod_top] lemma top_prod_top : (⊤ : subgroup G).prod (⊤ : subgroup N) = ⊤ := (top_prod _).trans $ comap_top _ @[to_additive] lemma bot_prod_bot : (⊥ : subgroup G).prod (⊥ : subgroup N) = ⊥ := ext' $ by simp [coe_prod, prod.one_eq_mk] /-- Product of subgroups is isomorphic to their product as groups. -/ @[to_additive prod_equiv "Product of additive subgroups is isomorphic to their product as additive groups"] def prod_equiv (H : subgroup G) (K : subgroup N) : H.prod K ≃* H × K := { map_mul' := λ x y, rfl, .. equiv.set.prod ↑H ↑K } /-- A subgroup is normal if whenever `n ∈ H`, then `g * n * g⁻¹ ∈ H` for every `g : G` -/ structure normal : Prop := (conj_mem : ∀ n, n ∈ H → ∀ g : G, g * n * g⁻¹ ∈ H) attribute [class] normal end subgroup namespace add_subgroup /-- An add_subgroup is normal if whenever `n ∈ H`, then `g + n - g ∈ H` for every `g : G` -/ structure normal (H : add_subgroup A) : Prop := (conj_mem [] : ∀ n, n ∈ H → ∀ g : A, g + n + -g ∈ H) attribute [to_additive add_subgroup.normal] subgroup.normal attribute [class] normal end add_subgroup namespace subgroup variables {H K : subgroup G} @[priority 100, to_additive] instance normal_of_comm {G : Type*} [comm_group G] (H : subgroup G) : H.normal := ⟨by simp [mul_comm, mul_left_comm]⟩ namespace normal variable (nH : H.normal) @[to_additive] lemma mem_comm {a b : G} (h : a * b ∈ H) : b * a ∈ H := have a⁻¹ * (a * b) * a⁻¹⁻¹ ∈ H, from nH.conj_mem (a * b) h a⁻¹, by simpa @[to_additive] lemma mem_comm_iff {a b : G} : a * b ∈ H ↔ b * a ∈ H := ⟨nH.mem_comm, nH.mem_comm⟩ end normal @[priority 100, to_additive] instance bot_normal : normal (⊥ : subgroup G) := ⟨by simp⟩ @[priority 100, to_additive] instance top_normal : normal (⊤ : subgroup G) := ⟨λ _ _, mem_top⟩ variable (G) /-- The center of a group `G` is the set of elements that commute with everything in `G` -/ @[to_additive "The center of a group `G` is the set of elements that commute with everything in `G`"] def center : subgroup G := { carrier := {z | ∀ g, g * z = z * g}, one_mem' := by simp, mul_mem' := λ a b (ha : ∀ g, g * a = a * g) (hb : ∀ g, g * b = b * g) g, by assoc_rw [ha, hb g], inv_mem' := λ a (ha : ∀ g, g * a = a * g) g, by rw [← inv_inj, mul_inv_rev, inv_inv, ← ha, mul_inv_rev, inv_inv] } variable {G} @[to_additive] lemma mem_center_iff {z : G} : z ∈ center G ↔ ∀ g, g * z = z * g := iff.rfl @[priority 100, to_additive] instance center_normal : (center G).normal := ⟨begin assume n hn g h, assoc_rw [hn (h * g), hn g], simp end⟩ variables {G} (H) /-- The `normalizer` of `H` is the smallest subgroup of `G` inside which `H` is normal. -/ @[to_additive "The `normalizer` of `H` is the smallest subgroup of `G` inside which `H` is normal."] def normalizer : subgroup G := { carrier := {g : G | ∀ n, n ∈ H ↔ g * n * g⁻¹ ∈ H}, one_mem' := by simp, mul_mem' := λ a b (ha : ∀ n, n ∈ H ↔ a * n * a⁻¹ ∈ H) (hb : ∀ n, n ∈ H ↔ b * n * b⁻¹ ∈ H) n, by { rw [hb, ha], simp [mul_assoc] }, inv_mem' := λ a (ha : ∀ n, n ∈ H ↔ a * n * a⁻¹ ∈ H) n, by { rw [ha (a⁻¹ * n * a⁻¹⁻¹)], simp [mul_assoc] } } -- variant for sets. -- TODO should this replace `normalizer`? /-- The `set_normalizer` of `S` is the subgroup of `G` whose elements satisfy `g*S*g⁻¹=S` -/ @[to_additive "The `set_normalizer` of `S` is the subgroup of `G` whose elements satisfy `g+S-g=S`."] def set_normalizer (S : set G) : subgroup G := { carrier := {g : G | ∀ n, n ∈ S ↔ g * n * g⁻¹ ∈ S}, one_mem' := by simp, mul_mem' := λ a b (ha : ∀ n, n ∈ S ↔ a * n * a⁻¹ ∈ S) (hb : ∀ n, n ∈ S ↔ b * n * b⁻¹ ∈ S) n, by { rw [hb, ha], simp [mul_assoc] }, inv_mem' := λ a (ha : ∀ n, n ∈ S ↔ a * n * a⁻¹ ∈ S) n, by { rw [ha (a⁻¹ * n * a⁻¹⁻¹)], simp [mul_assoc] } } variable {H} @[to_additive] lemma mem_normalizer_iff {g : G} : g ∈ normalizer H ↔ ∀ n, n ∈ H ↔ g * n * g⁻¹ ∈ H := iff.rfl @[to_additive] lemma le_normalizer : H ≤ normalizer H := λ x xH n, by rw [H.mul_mem_cancel_right (H.inv_mem xH), H.mul_mem_cancel_left xH] @[priority 100, to_additive] instance normal_in_normalizer : (H.comap H.normalizer.subtype).normal := ⟨λ x xH g, by simpa using (g.2 x).1 xH⟩ open_locale classical @[to_additive] lemma le_normalizer_of_normal [hK : (H.comap K.subtype).normal] (HK : H ≤ K) : K ≤ H.normalizer := λ x hx y, ⟨λ yH, hK.conj_mem ⟨y, HK yH⟩ yH ⟨x, hx⟩, λ yH, by simpa [mem_comap, mul_assoc] using hK.conj_mem ⟨x * y * x⁻¹, HK yH⟩ yH ⟨x⁻¹, K.inv_mem hx⟩⟩ end subgroup namespace group variables {s : set G} /-- Given an element `a`, `conjugates a` is the set of conjugates. -/ def conjugates (a : G) : set G := {b | is_conj a b} lemma mem_conjugates_self {a : G} : a ∈ conjugates a := is_conj_refl _ /-- Given a set `s`, `conjugates_of_set s` is the set of all conjugates of the elements of `s`. -/ def conjugates_of_set (s : set G) : set G := ⋃ a ∈ s, conjugates a lemma mem_conjugates_of_set_iff {x : G} : x ∈ conjugates_of_set s ↔ ∃ a ∈ s, is_conj a x := set.mem_bUnion_iff theorem subset_conjugates_of_set : s ⊆ conjugates_of_set s := λ (x : G) (h : x ∈ s), mem_conjugates_of_set_iff.2 ⟨x, h, is_conj_refl _⟩ theorem conjugates_of_set_mono {s t : set G} (h : s ⊆ t) : conjugates_of_set s ⊆ conjugates_of_set t := set.bUnion_subset_bUnion_left h lemma conjugates_subset_normal {N : subgroup G} [tn : N.normal] {a : G} (h : a ∈ N) : conjugates a ⊆ N := by { rintros a ⟨c, rfl⟩, exact tn.conj_mem a h c } theorem conjugates_of_set_subset {s : set G} {N : subgroup G} [N.normal] (h : s ⊆ N) : conjugates_of_set s ⊆ N := set.bUnion_subset (λ x H, conjugates_subset_normal (h H)) /-- The set of conjugates of `s` is closed under conjugation. -/ lemma conj_mem_conjugates_of_set {x c : G} : x ∈ conjugates_of_set s → (c * x * c⁻¹ ∈ conjugates_of_set s) := λ H, begin rcases (mem_conjugates_of_set_iff.1 H) with ⟨a,h₁,h₂⟩, exact mem_conjugates_of_set_iff.2 ⟨a, h₁, is_conj_trans h₂ ⟨c,rfl⟩⟩, end end group namespace subgroup open group variable {s : set G} /-- The normal closure of a set `s` is the subgroup closure of all the conjugates of elements of `s`. It is the smallest normal subgroup containing `s`. -/ def normal_closure (s : set G) : subgroup G := closure (conjugates_of_set s) theorem conjugates_of_set_subset_normal_closure : conjugates_of_set s ⊆ normal_closure s := subset_closure theorem subset_normal_closure : s ⊆ normal_closure s := set.subset.trans subset_conjugates_of_set conjugates_of_set_subset_normal_closure theorem le_normal_closure {H : subgroup G} : H ≤ normal_closure ↑H := λ _ h, subset_normal_closure h /-- The normal closure of `s` is a normal subgroup. -/ instance normal_closure_normal : (normal_closure s).normal := ⟨λ n h g, begin refine subgroup.closure_induction h (λ x hx, _) _ (λ x y ihx ihy, _) (λ x ihx, _), { exact (conjugates_of_set_subset_normal_closure (conj_mem_conjugates_of_set hx)) }, { simpa using (normal_closure s).one_mem }, { rw ← conj_mul, exact mul_mem _ ihx ihy }, { rw ← conj_inv, exact inv_mem _ ihx } end⟩ /-- The normal closure of `s` is the smallest normal subgroup containing `s`. -/ theorem normal_closure_le_normal {N : subgroup G} [N.normal] (h : s ⊆ N) : normal_closure s ≤ N := begin assume a w, refine closure_induction w (λ x hx, _) _ (λ x y ihx ihy, _) (λ x ihx, _), { exact (conjugates_of_set_subset h hx) }, { exact subgroup.one_mem _ }, { exact subgroup.mul_mem _ ihx ihy }, { exact subgroup.inv_mem _ ihx } end lemma normal_closure_subset_iff {N : subgroup G} [N.normal] : s ⊆ N ↔ normal_closure s ≤ N := ⟨normal_closure_le_normal, set.subset.trans (subset_normal_closure)⟩ theorem normal_closure_mono {s t : set G} (h : s ⊆ t) : normal_closure s ≤ normal_closure t := normal_closure_le_normal (set.subset.trans h subset_normal_closure) theorem normal_closure_eq_infi : normal_closure s = ⨅ (N : subgroup G) [normal N] (hs : s ⊆ N), N := le_antisymm (le_infi (λ N, le_infi (λ hN, by exactI le_infi (normal_closure_le_normal)))) (infi_le_of_le (normal_closure s) (infi_le_of_le (by apply_instance) (infi_le_of_le subset_normal_closure (le_refl _)))) @[simp] theorem normal_closure_eq_self (H : subgroup G) [H.normal] : normal_closure ↑H = H := le_antisymm (normal_closure_le_normal rfl.subset) (le_normal_closure) @[simp] theorem normal_closure_idempotent : normal_closure ↑(normal_closure s) = normal_closure s := normal_closure_eq_self _ theorem closure_le_normal_closure {s : set G} : closure s ≤ normal_closure s := by simp only [subset_normal_closure, closure_le] @[simp] theorem normal_closure_closure_eq_normal_closure {s : set G} : normal_closure ↑(closure s) = normal_closure s := le_antisymm (normal_closure_le_normal closure_le_normal_closure) (normal_closure_mono subset_closure) end subgroup namespace add_subgroup open set lemma gsmul_mem (H : add_subgroup A) {x : A} (hx : x ∈ H) : ∀ n : ℤ, gsmul n x ∈ H | (int.of_nat n) := add_submonoid.nsmul_mem H.to_add_submonoid hx n | -[1+ n] := H.neg_mem' $ H.add_mem hx $ add_submonoid.nsmul_mem H.to_add_submonoid hx n /-- The `add_subgroup` generated by an element of an `add_group` equals the set of natural number multiples of the element. -/ lemma mem_closure_singleton {x y : A} : y ∈ closure ({x} : set A) ↔ ∃ n : ℤ, gsmul n x = y := begin refine ⟨λ hy, closure_induction hy _ _ _ _, λ ⟨n, hn⟩, hn ▸ gsmul_mem _ (subset_closure $ mem_singleton x) n⟩, { intros y hy, rw [eq_of_mem_singleton hy], exact ⟨1, one_gsmul x⟩ }, { exact ⟨0, rfl⟩ }, { rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩, exact ⟨n + m, add_gsmul x n m⟩ }, { rintros _ ⟨n, rfl⟩, refine ⟨-n, neg_gsmul x n⟩ } end lemma closure_singleton_zero : closure ({0} : set A) = ⊥ := by simp [eq_bot_iff_forall, mem_closure_singleton] variable (H : add_subgroup A) @[simp] lemma coe_smul (x : H) (n : ℕ) : ((nsmul n x : H) : A) = nsmul n x := coe_subtype H ▸ add_monoid_hom.map_nsmul _ _ _ @[simp] lemma coe_gsmul (x : H) (n : ℤ) : ((n •ℤ x : H) : A) = n •ℤ x := coe_subtype H ▸ add_monoid_hom.map_gsmul _ _ _ attribute [to_additive add_subgroup.coe_smul] subgroup.coe_pow attribute [to_additive add_subgroup.coe_gsmul] subgroup.coe_gpow end add_subgroup namespace monoid_hom variables {N : Type*} {P : Type*} [group N] [group P] (K : subgroup G) open subgroup /-- The range of a monoid homomorphism from a group is a subgroup. -/ @[to_additive "The range of an `add_monoid_hom` from an `add_group` is an `add_subgroup`."] def range (f : G →* N) : subgroup N := subgroup.copy ((⊤ : subgroup G).map f) (set.range f) (by simp [set.ext_iff]) @[to_additive] instance decidable_mem_range (f : G →* N) [fintype G] [decidable_eq N] : decidable_pred (λ x, x ∈ f.range) := λ x, fintype.decidable_exists_fintype @[simp, to_additive] lemma coe_range (f : G →* N) : (f.range : set N) = set.range f := rfl @[simp, to_additive] lemma mem_range {f : G →* N} {y : N} : y ∈ f.range ↔ ∃ x, f x = y := iff.rfl @[to_additive] lemma range_eq_map (f : G →* N) : f.range = (⊤ : subgroup G).map f := by ext; simp /-- The canonical surjective group homomorphism `G →* f(G)` induced by a group homomorphism `G →* N`. -/ @[to_additive "The canonical surjective `add_group` homomorphism `G →+ f(G)` induced by a group homomorphism `G →+ N`."] def to_range (f : G →* N) : G →* f.range := monoid_hom.mk' (λ g, ⟨f g, ⟨g, rfl⟩⟩) $ λ a b, by {ext, exact f.map_mul' _ _} @[to_additive] lemma map_range (g : N →* P) (f : G →* N) : f.range.map g = (g.comp f).range := by rw [range_eq_map, range_eq_map]; exact (⊤ : subgroup G).map_map g f @[to_additive] lemma range_top_iff_surjective {N} [group N] {f : G →* N} : f.range = (⊤ : subgroup N) ↔ function.surjective f := subgroup.ext'_iff.trans $ iff.trans (by rw [coe_range, coe_top]) set.range_iff_surjective /-- The range of a surjective monoid homomorphism is the whole of the codomain. -/ @[to_additive "The range of a surjective `add_monoid` homomorphism is the whole of the codomain."] lemma range_top_of_surjective {N} [group N] (f : G →* N) (hf : function.surjective f) : f.range = (⊤ : subgroup N) := range_top_iff_surjective.2 hf /-- Restriction of a group hom to a subgroup of the codomain. -/ @[to_additive "Restriction of an `add_group` hom to an `add_subgroup` of the codomain."] def cod_restrict (f : G →* N) (S : subgroup N) (h : ∀ x, f x ∈ S) : G →* S := { to_fun := λ n, ⟨f n, h n⟩, map_one' := subtype.eq f.map_one, map_mul' := λ x y, subtype.eq (f.map_mul x y) } /-- The multiplicative kernel of a monoid homomorphism is the subgroup of elements `x : G` such that `f x = 1` -/ @[to_additive "The additive kernel of an `add_monoid` homomorphism is the `add_subgroup` of elements such that `f x = 0`"] def ker (f : G →* N) := (⊥ : subgroup N).comap f @[to_additive] lemma mem_ker (f : G →* N) {x : G} : x ∈ f.ker ↔ f x = 1 := iff.rfl @[to_additive] lemma comap_ker (g : N →* P) (f : G →* N) : g.ker.comap f = (g.comp f).ker := rfl @[to_additive] lemma to_range_ker (f : G →* N) : ker (to_range f) = ker f := begin ext, change (⟨f x, _⟩ : range f) = ⟨1, _⟩ ↔ f x = 1, simp only [], end /-- The subgroup of elements `x : G` such that `f x = g x` -/ @[to_additive "The additive subgroup of elements `x : G` such that `f x = g x`"] def eq_locus (f g : G →* N) : subgroup G := { inv_mem' := λ x (hx : f x = g x), show f x⁻¹ = g x⁻¹, by rw [f.map_inv, g.map_inv, hx], .. eq_mlocus f g} /-- If two monoid homomorphisms are equal on a set, then they are equal on its subgroup closure. -/ @[to_additive] lemma eq_on_closure {f g : G →* N} {s : set G} (h : set.eq_on f g s) : set.eq_on f g (closure s) := show closure s ≤ f.eq_locus g, from (closure_le _).2 h @[to_additive] lemma eq_of_eq_on_top {f g : G →* N} (h : set.eq_on f g (⊤ : subgroup G)) : f = g := ext $ λ x, h trivial @[to_additive] lemma eq_of_eq_on_dense {s : set G} (hs : closure s = ⊤) {f g : G →* N} (h : s.eq_on f g) : f = g := eq_of_eq_on_top $ hs ▸ eq_on_closure h @[to_additive] lemma gclosure_preimage_le (f : G →* N) (s : set N) : closure (f ⁻¹' s) ≤ (closure s).comap f := (closure_le _).2 $ λ x hx, by rw [mem_coe, mem_comap]; exact subset_closure hx /-- The image under a monoid homomorphism of the subgroup generated by a set equals the subgroup generated by the image of the set. -/ @[to_additive "The image under an `add_monoid` hom of the `add_subgroup` generated by a set equals the `add_subgroup` generated by the image of the set."] lemma map_closure (f : G →* N) (s : set G) : (closure s).map f = closure (f '' s) := le_antisymm (map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image f s) (gclosure_preimage_le _ _)) ((closure_le _).2 $ set.image_subset _ subset_closure) end monoid_hom namespace monoid_hom variables {G₁ G₂ G₃ : Type*} [group G₁] [group G₂] [group G₃] variables (f : G₁ →* G₂) /-- `lift_of_surjective f hf g hg` is the unique group homomorphism `φ` * such that `φ.comp f = g` (`lift_of_surjective_comp`), * where `f : G₁ →+* G₂` is surjective (`hf`), * and `g : G₂ →+* G₃` satisfies `hg : f.ker ≤ g.ker`. See `lift_of_surjective_eq` for the uniqueness lemma. ``` G₁. | \ f | \ g | \ v \⌟ G₂----> G₃ ∃!φ ``` -/ @[to_additive "`lift_of_surjective f hf g hg` is the unique additive group homomorphism `φ` * such that `φ.comp f = g` (`lift_of_surjective_comp`), * where `f : G₁ →+* G₂` is surjective (`hf`), * and `g : G₂ →+* G₃` satisfies `hg : f.ker ≤ g.ker`. See `lift_of_surjective_eq` for the uniqueness lemma. ``` G₁. | \\ f | \\ g | \\ v \\⌟ G₂----> G₃ ∃!φ ```"] noncomputable def lift_of_surjective (hf : function.surjective f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) : G₂ →* G₃ := { to_fun := λ b, g (classical.some (hf b)), map_one' := hg (classical.some_spec (hf 1)), map_mul' := begin intros x y, rw [← g.map_mul, ← mul_inv_eq_one, ← g.map_inv, ← g.map_mul, ← g.mem_ker], apply hg, rw [f.mem_ker, f.map_mul, f.map_inv, mul_inv_eq_one, f.map_mul], simp only [classical.some_spec (hf _)], end } @[simp, to_additive] lemma lift_of_surjective_comp_apply (hf : function.surjective f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) (x : G₁) : (f.lift_of_surjective hf g hg) (f x) = g x := begin dsimp [lift_of_surjective], rw [← mul_inv_eq_one, ← g.map_inv, ← g.map_mul, ← g.mem_ker], apply hg, rw [f.mem_ker, f.map_mul, f.map_inv, mul_inv_eq_one], simp only [classical.some_spec (hf _)], end @[simp, to_additive] lemma lift_of_surjective_comp (hf : function.surjective f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) : (f.lift_of_surjective hf g hg).comp f = g := by { ext, simp only [comp_apply, lift_of_surjective_comp_apply] } @[to_additive] lemma eq_lift_of_surjective (hf : function.surjective f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) (h : G₂ →* G₃) (hh : h.comp f = g) : h = (f.lift_of_surjective hf g hg) := begin ext b, rcases hf b with ⟨a, rfl⟩, simp only [← comp_apply, hh, f.lift_of_surjective_comp], end end monoid_hom variables {N : Type*} [group N] -- Here `H.normal` is an explicit argument so we can use dot notation with `comap`. @[to_additive] lemma subgroup.normal.comap {H : subgroup N} (hH : H.normal) (f : G →* N) : (H.comap f).normal := ⟨λ _, by simp [subgroup.mem_comap, hH.conj_mem] {contextual := tt}⟩ @[priority 100, to_additive] instance subgroup.normal_comap {H : subgroup N} [nH : H.normal] (f : G →* N) : (H.comap f).normal := nH.comap _ @[priority 100, to_additive] instance monoid_hom.normal_ker (f : G →* N) : f.ker.normal := by rw [monoid_hom.ker]; apply_instance @[priority 100, to_additive] instance subgroup.normal_inf (H N : subgroup G) [hN : N.normal] : ((H ⊓ N).comap H.subtype).normal := ⟨λ x hx g, begin simp only [subgroup.mem_inf, coe_subtype, subgroup.mem_comap] at hx, simp only [subgroup.coe_mul, subgroup.mem_inf, coe_subtype, subgroup.coe_inv, subgroup.mem_comap], exact ⟨H.mul_mem (H.mul_mem g.2 hx.1) (H.inv_mem g.2), hN.1 x hx.2 g⟩, end⟩ namespace subgroup /-- The subgroup generated by an element. -/ def gpowers (g : G) : subgroup G := subgroup.copy (gpowers_hom G g).range (set.range ((^) g : ℤ → G)) rfl @[simp] lemma mem_gpowers (g : G) : g ∈ gpowers g := ⟨1, gpow_one _⟩ lemma gpowers_eq_closure (g : G) : gpowers g = closure {g} := by { ext, exact mem_closure_singleton.symm } @[simp] lemma range_gpowers_hom (g : G) : (gpowers_hom G g).range = gpowers g := rfl lemma gpowers_subset {a : G} {K : subgroup G} (h : a ∈ K) : gpowers a ≤ K := λ x hx, match x, hx with _, ⟨i, rfl⟩ := K.gpow_mem h i end end subgroup namespace add_subgroup /-- The subgroup generated by an element. -/ def gmultiples (a : A) : add_subgroup A := add_subgroup.copy (gmultiples_hom A a).range (set.range ((•ℤ a) : ℤ → A)) rfl @[simp] lemma mem_gmultiples (a : A) : a ∈ gmultiples a := ⟨1, one_gsmul _⟩ lemma gmultiples_eq_closure (a : A) : gmultiples a = closure {a} := by { ext, exact mem_closure_singleton.symm } @[simp] lemma range_gmultiples_hom (a : A) : (gmultiples_hom A a).range = gmultiples a := rfl lemma gmultiples_subset {a : A} {B : add_subgroup A} (h : a ∈ B) : gmultiples a ≤ B := @subgroup.gpowers_subset (multiplicative A) _ _ (B.to_subgroup) h attribute [to_additive add_subgroup.gmultiples] subgroup.gpowers attribute [to_additive add_subgroup.mem_gmultiples] subgroup.mem_gpowers attribute [to_additive add_subgroup.gmultiples_eq_closure] subgroup.gpowers_eq_closure attribute [to_additive add_subgroup.range_gmultiples_hom] subgroup.range_gpowers_hom attribute [to_additive add_subgroup.gmultiples_subset] subgroup.gpowers_subset end add_subgroup namespace mul_equiv variables {H K : subgroup G} /-- Makes the identity isomorphism from a proof two subgroups of a multiplicative group are equal. -/ @[to_additive "Makes the identity additive isomorphism from a proof two subgroups of an additive group are equal."] def subgroup_congr (h : H = K) : H ≃* K := { map_mul' := λ _ _, rfl, ..equiv.set_congr $ subgroup.ext'_iff.1 h } end mul_equiv -- TODO : ↥(⊤ : subgroup H) ≃* H ? namespace subgroup variables {C : Type*} [comm_group C] {s t : subgroup C} {x : C} @[to_additive] lemma mem_sup : x ∈ s ⊔ t ↔ ∃ (y ∈ s) (z ∈ t), y * z = x := ⟨λ h, begin rw [← closure_eq s, ← closure_eq t, ← closure_union] at h, apply closure_induction h, { rintro y (h | h), { exact ⟨y, h, 1, t.one_mem, by simp⟩ }, { exact ⟨1, s.one_mem, y, h, by simp⟩ } }, { exact ⟨1, s.one_mem, 1, ⟨t.one_mem, mul_one 1⟩⟩ }, { rintro _ _ ⟨y₁, hy₁, z₁, hz₁, rfl⟩ ⟨y₂, hy₂, z₂, hz₂, rfl⟩, exact ⟨_, mul_mem _ hy₁ hy₂, _, mul_mem _ hz₁ hz₂, by simp [mul_assoc]; cc⟩ }, { rintro _ ⟨y, hy, z, hz, rfl⟩, exact ⟨_, inv_mem _ hy, _, inv_mem _ hz, mul_comm z y ▸ (mul_inv_rev z y).symm⟩ } end, by rintro ⟨y, hy, z, hz, rfl⟩; exact mul_mem _ ((le_sup_left : s ≤ s ⊔ t) hy) ((le_sup_right : t ≤ s ⊔ t) hz)⟩ @[to_additive] lemma mem_sup' : x ∈ s ⊔ t ↔ ∃ (y : s) (z : t), (y:C) * z = x := mem_sup.trans $ by simp only [subgroup.exists, coe_mk] @[to_additive] instance : is_modular_lattice (subgroup C) := ⟨λ x y z xz a ha, begin rw [mem_inf, mem_sup] at ha, rcases ha with ⟨⟨b, hb, c, hc, rfl⟩, haz⟩, rw mem_sup, refine ⟨b, hb, c, mem_inf.2 ⟨hc, _⟩, rfl⟩, rw ← inv_mul_cancel_left b c, apply z.mul_mem (z.inv_mem (xz hb)) haz, end⟩ end subgroup section pointwise namespace subgroup @[to_additive] lemma closure_mul_le (S T : set G) : closure (S * T) ≤ closure S ⊔ closure T := Inf_le $ λ x ⟨s, t, hs, ht, hx⟩, hx ▸ (closure S ⊔ closure T).mul_mem (le_def.mp le_sup_left $ subset_closure hs) (le_def.mp le_sup_right $ subset_closure ht) @[to_additive] lemma sup_eq_closure (H K : subgroup G) : H ⊔ K = closure (H * K) := le_antisymm (sup_le (λ h hh, subset_closure ⟨h, 1, hh, K.one_mem, mul_one h⟩) (λ k hk, subset_closure ⟨1, k, H.one_mem, hk, one_mul k⟩)) (by conv_rhs { rw [← closure_eq H, ← closure_eq K] }; apply closure_mul_le) @[to_additive] private def mul_normal_aux (H N : subgroup G) [hN : N.normal] : subgroup G := { carrier := (H : set G) * N, one_mem' := ⟨1, 1, H.one_mem, N.one_mem, by rw mul_one⟩, mul_mem' := λ a b ⟨h, n, hh, hn, ha⟩ ⟨h', n', hh', hn', hb⟩, ⟨h * h', h'⁻¹ * n * h' * n', H.mul_mem hh hh', N.mul_mem (by simpa using hN.conj_mem _ hn h'⁻¹) hn', by simp [← ha, ← hb, mul_assoc]⟩, inv_mem' := λ x ⟨h, n, hh, hn, hx⟩, ⟨h⁻¹, h * n⁻¹ * h⁻¹, H.inv_mem hh, hN.conj_mem _ (N.inv_mem hn) h, by rw [mul_assoc h, inv_mul_cancel_left, ← hx, mul_inv_rev]⟩ } /-- The carrier of `H ⊔ N` is just `↑H * ↑N` (pointwise set product) when `N` is normal. -/ @[to_additive "The carrier of `H ⊔ N` is just `↑H + ↑N` (pointwise set addition) when `N` is normal."] lemma mul_normal (H N : subgroup G) [N.normal] : (↑(H ⊔ N) : set G) = H * N := set.subset.antisymm (show H ⊔ N ≤ mul_normal_aux H N, by { rw sup_eq_closure, apply Inf_le _, dsimp, refl }) ((sup_eq_closure H N).symm ▸ subset_closure) @[to_additive] private def normal_mul_aux (N H : subgroup G) [hN : N.normal] : subgroup G := { carrier := (N : set G) * H, one_mem' := ⟨1, 1, N.one_mem, H.one_mem, by rw mul_one⟩, mul_mem' := λ a b ⟨n, h, hn, hh, ha⟩ ⟨n', h', hn', hh', hb⟩, ⟨n * (h * n' * h⁻¹), h * h', N.mul_mem hn (hN.conj_mem _ hn' _), H.mul_mem hh hh', by simp [← ha, ← hb, mul_assoc]⟩, inv_mem' := λ x ⟨n, h, hn, hh, hx⟩, ⟨h⁻¹ * n⁻¹ * h, h⁻¹, by simpa using hN.conj_mem _ (N.inv_mem hn) h⁻¹, H.inv_mem hh, by rw [mul_inv_cancel_right, ← mul_inv_rev, hx]⟩ } /-- The carrier of `N ⊔ H` is just `↑N * ↑H` (pointwise set product) when `N` is normal. -/ @[to_additive "The carrier of `N ⊔ H` is just `↑N + ↑H` (pointwise set addition) when `N` is normal."] lemma normal_mul (N H : subgroup G) [N.normal] : (↑(N ⊔ H) : set G) = N * H := set.subset.antisymm (show N ⊔ H ≤ normal_mul_aux N H, by { rw sup_eq_closure, apply Inf_le _, dsimp, refl }) ((sup_eq_closure N H).symm ▸ subset_closure) end subgroup end pointwise
3bd221cfa2a2f2fe37e7da5c2e0324a36891b487
8e381650eb2c1c5361be64ff97e47d956bf2ab9f
/src/sheaves/locally_ringed_space.lean
808168f0db0ac57b49f14cc16472d104fa71c0a5
[]
no_license
alreadydone/lean-scheme
04c51ab08eca7ccf6c21344d45d202780fa667af
52d7624f57415eea27ed4dfa916cd94189221a1c
refs/heads/master
1,599,418,221,423
1,562,248,559,000
1,562,248,559,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,731
lean
import topology.basic import ring_theory.localization import sheaves.presheaf_maps import sheaves.presheaf_of_rings_maps import sheaves.presheaf_of_rings import sheaves.sheaf_of_rings import sheaves.stalk_of_rings universes u v w open topological_space -- Locally ringed spaces. section locally_ringed_spaces structure locally_ringed_space (X : Type u) [topological_space X] := (O : sheaf_of_rings X) (Hstalks : ∀ x, is_local_ring (stalk_of_rings O.F x)) -- Morphism of locally ringed spaces. -- TODO: Work on coercions. structure morphism {X : Type u} {Y : Type v} [topological_space X] [topological_space Y] (OX : locally_ringed_space X) (OY : locally_ringed_space Y) := (f : X → Y) (Hf : continuous f) (fO : presheaf.fmap Hf OX.O.F.to_presheaf OY.O.F.to_presheaf) infix `⟶`:80 := morphism section morphism variables {A : Type u} [topological_space A] variables {B : Type v} [topological_space B] variables {C : Type w} [topological_space C] variable {OA : locally_ringed_space A} variable {OB : locally_ringed_space B} variable {OC : locally_ringed_space C} def comp (F : morphism OA OB) (G : morphism OB OC) : morphism OA OC := { f := G.f ∘ F.f, Hf := continuous.comp F.Hf G.Hf, fO := presheaf.fmap.comp F.fO G.fO, } infixl `⊚`:80 := comp def locally_ringed_space.id (OX : locally_ringed_space A) : morphism OX OX := { f := id, Hf := continuous_id, fO := presheaf.fmap.id OX.O.F.to_presheaf, } structure iso (OX : locally_ringed_space A) (OY : locally_ringed_space B) := (mor : OX ⟶ OY) (inv : OY ⟶ OX) (mor_inv_id : mor ⊚ inv = locally_ringed_space.id OX) (inv_mor_id : inv ⊚ mor = locally_ringed_space.id OY) infix `≅`:80 := iso end morphism end locally_ringed_spaces
b1f33a8b010198f71e970b9c9fffeeda76415d2e
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/data/nat/totient.lean
fb9ddb48d3b4ca18dd2bc77d334e193f01e9eb00
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,718
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 algebra.big_operators.basic open finset open_locale big_operators namespace nat /-- Euler's totient function. This counts the number of positive integers less than `n` which are coprime with `n`. -/ def totient (n : ℕ) : ℕ := ((range n).filter (nat.coprime n)).card localized "notation `φ` := nat.totient" in nat @[simp] theorem totient_zero : φ 0 = 0 := rfl lemma totient_le (n : ℕ) : φ n ≤ n := calc totient n ≤ (range n).card : card_le_of_subset (filter_subset _ _) ... = n : card_range _ lemma totient_pos : ∀ {n : ℕ}, 0 < n → 0 < φ n | 0 := dec_trivial | 1 := dec_trivial | (n+2) := λ h, card_pos.2 ⟨1, mem_filter.2 ⟨mem_range.2 dec_trivial, coprime_one_right _⟩⟩ lemma sum_totient (n : ℕ) : ∑ m in (range n.succ).filter (∣ n), φ m = n := if hn0 : n = 0 then by rw hn0; refl else calc ∑ m in (range n.succ).filter (∣ n), φ m = ∑ d in (range n.succ).filter (∣ n), ((range (n / d)).filter (λ m, gcd (n / d) m = 1)).card : eq.symm $ sum_bij (λ d _, n / d) (λ d hd, mem_filter.2 ⟨mem_range.2 $ lt_succ_of_le $ nat.div_le_self _ _, by conv {to_rhs, rw ← nat.mul_div_cancel' (mem_filter.1 hd).2}; simp⟩) (λ _ _, rfl) (λ a b ha hb h, have ha : a * (n / a) = n, from nat.mul_div_cancel' (mem_filter.1 ha).2, have 0 < (n / a), from nat.pos_of_ne_zero (λ h, by simp [*, lt_irrefl] at *), by rw [← nat.mul_left_inj this, ha, h, nat.mul_div_cancel' (mem_filter.1 hb).2]) (λ b hb, have hb : b < n.succ ∧ b ∣ n, by simpa [-range_succ] using hb, have hbn : (n / b) ∣ n, from ⟨b, by rw nat.div_mul_cancel hb.2⟩, have hnb0 : (n / b) ≠ 0, from λ h, by simpa [h, ne.symm hn0] using nat.div_mul_cancel hbn, ⟨n / b, mem_filter.2 ⟨mem_range.2 $ lt_succ_of_le $ nat.div_le_self _ _, hbn⟩, by rw [← nat.mul_left_inj (nat.pos_of_ne_zero hnb0), nat.mul_div_cancel' hb.2, nat.div_mul_cancel hbn]⟩) ... = ∑ d in (range n.succ).filter (∣ n), ((range n).filter (λ m, gcd n m = d)).card : sum_congr rfl (λ d hd, have hd : d ∣ n, from (mem_filter.1 hd).2, have hd0 : 0 < d, from nat.pos_of_ne_zero (λ h, hn0 (eq_zero_of_zero_dvd $ h ▸ hd)), card_congr (λ m hm, d * m) (λ m hm, have hm : m < n / d ∧ gcd (n / d) m = 1, by simpa using hm, mem_filter.2 ⟨mem_range.2 $ nat.mul_div_cancel' hd ▸ (mul_lt_mul_left hd0).2 hm.1, by rw [← nat.mul_div_cancel' hd, gcd_mul_left, hm.2, mul_one]⟩) (λ a b ha hb h, (nat.mul_right_inj hd0).1 h) (λ b hb, have hb : b < n ∧ gcd n b = d, by simpa using hb, ⟨b / d, mem_filter.2 ⟨mem_range.2 ((mul_lt_mul_left (show 0 < d, from hb.2 ▸ hb.2.symm ▸ hd0)).1 (by rw [← hb.2, nat.mul_div_cancel' (gcd_dvd_left _ _), nat.mul_div_cancel' (gcd_dvd_right _ _)]; exact hb.1)), hb.2 ▸ coprime_div_gcd_div_gcd (hb.2.symm ▸ hd0)⟩, hb.2 ▸ nat.mul_div_cancel' (gcd_dvd_right _ _)⟩)) ... = ((filter (∣ n) (range n.succ)).bUnion (λ d, (range n).filter (λ m, gcd n m = d))).card : (card_bUnion (by intros; apply disjoint_filter.2; cc)).symm ... = (range n).card : congr_arg card (finset.ext (λ m, ⟨by finish, λ hm, have h : m < n, from mem_range.1 hm, mem_bUnion.2 ⟨gcd n m, mem_filter.2 ⟨mem_range.2 (lt_succ_of_le (le_of_dvd (lt_of_le_of_lt (nat.zero_le _) h) (gcd_dvd_left _ _))), gcd_dvd_left _ _⟩, mem_filter.2 ⟨hm, rfl⟩⟩⟩)) ... = n : card_range _ end nat
e3199b7d3eb103d8a0a026cc29c8dac4ecc01ac7
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/topology/metric_space/isometry.lean
50d5e7a46abed08d0a5871a054f513e3382e138b
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,477
lean
/- Copyright (c) 2018 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Isometries of emetric and metric spaces Authors: Sébastien Gouëzel -/ import topology.bounded_continuous_function import topology.compacts /-! # Isometries We define isometries, i.e., maps between emetric spaces that preserve the edistance (on metric spaces, these are exactly the maps that preserve distances), and prove their basic properties. We also introduce isometric bijections. -/ noncomputable theory universes u v w variables {α : Type u} {β : Type v} {γ : Type w} open function set /-- An isometry (also known as isometric embedding) is a map preserving the edistance between emetric spaces, or equivalently the distance between metric space. -/ def isometry [emetric_space α] [emetric_space β] (f : α → β) : Prop := ∀x1 x2 : α, edist (f x1) (f x2) = edist x1 x2 /-- On metric spaces, a map is an isometry if and only if it preserves distances. -/ lemma isometry_emetric_iff_metric [metric_space α] [metric_space β] {f : α → β} : isometry f ↔ (∀x y, dist (f x) (f y) = dist x y) := ⟨assume H x y, by simp [dist_edist, H x y], assume H x y, by simp [edist_dist, H x y]⟩ /-- An isometry preserves edistances. -/ theorem isometry.edist_eq [emetric_space α] [emetric_space β] {f : α → β} (hf : isometry f) (x y : α) : edist (f x) (f y) = edist x y := hf x y /-- An isometry preserves distances. -/ theorem isometry.dist_eq [metric_space α] [metric_space β] {f : α → β} (hf : isometry f) (x y : α) : dist (f x) (f y) = dist x y := by rw [dist_edist, dist_edist, hf] section emetric_isometry variables [emetric_space α] [emetric_space β] [emetric_space γ] variables {f : α → β} {x y z : α} {s : set α} lemma isometry.lipschitz (h : isometry f) : lipschitz_with 1 f := lipschitz_with.of_edist_le $ λ x y, le_of_eq (h x y) lemma isometry.antilipschitz (h : isometry f) : antilipschitz_with 1 f := λ x y, by simp only [h x y, ennreal.coe_one, one_mul, le_refl] /-- An isometry is injective -/ lemma isometry.injective (h : isometry f) : injective f := h.antilipschitz.injective /-- Any map on a subsingleton is an isometry -/ theorem isometry_subsingleton [subsingleton α] : isometry f := λx y, by rw subsingleton.elim x y; simp /-- The identity is an isometry -/ lemma isometry_id : isometry (id : α → α) := λx y, rfl /-- The composition of isometries is an isometry -/ theorem isometry.comp {g : β → γ} {f : α → β} (hg : isometry g) (hf : isometry f) : isometry (g ∘ f) := assume x y, calc edist ((g ∘ f) x) ((g ∘ f) y) = edist (f x) (f y) : hg _ _ ... = edist x y : hf _ _ /-- An isometry is an embedding -/ theorem isometry.uniform_embedding (hf : isometry f) : uniform_embedding f := hf.antilipschitz.uniform_embedding hf.lipschitz.uniform_continuous /-- An isometry is continuous. -/ lemma isometry.continuous (hf : isometry f) : continuous f := hf.lipschitz.continuous /-- The right inverse of an isometry is an isometry. -/ lemma isometry.right_inv {f : α → β} {g : β → α} (h : isometry f) (hg : right_inverse g f) : isometry g := λ x y, by rw [← h, hg _, hg _] /-- Isometries preserve the diameter in emetric spaces. -/ lemma isometry.ediam_image (hf : isometry f) (s : set α) : emetric.diam (f '' s) = emetric.diam s := eq_of_forall_ge_iff $ λ d, by simp only [emetric.diam_le_iff_forall_edist_le, ball_image_iff, hf.edist_eq] lemma isometry.ediam_range (hf : isometry f) : emetric.diam (range f) = emetric.diam (univ : set α) := by { rw ← image_univ, exact hf.ediam_image univ } /-- The injection from a subtype is an isometry -/ lemma isometry_subtype_coe {s : set α} : isometry (coe : s → α) := λx y, rfl end emetric_isometry --section /-- An isometry preserves the diameter in metric spaces. -/ lemma isometry.diam_image [metric_space α] [metric_space β] {f : α → β} (hf : isometry f) (s : set α) : metric.diam (f '' s) = metric.diam s := by rw [metric.diam, metric.diam, hf.ediam_image] lemma isometry.diam_range [metric_space α] [metric_space β] {f : α → β} (hf : isometry f) : metric.diam (range f) = metric.diam (univ : set α) := by { rw ← image_univ, exact hf.diam_image univ } namespace add_monoid_hom variables {E F : Type*} [normed_group E] [normed_group F] lemma isometry_iff_norm (f : E →+ F) : isometry f ↔ ∀ x, ∥f x∥ = ∥x∥ := begin simp only [isometry_emetric_iff_metric, dist_eq_norm, ← f.map_sub], refine ⟨λ h x, _, λ h x y, h _⟩, simpa using h x 0 end lemma isometry_of_norm (f : E →+ F) (hf : ∀ x, ∥f x∥ = ∥x∥) : isometry f := f.isometry_iff_norm.2 hf end add_monoid_hom /-- `α` and `β` are isometric if there is an isometric bijection between them. -/ @[nolint has_inhabited_instance] -- such a bijection need not exist structure isometric (α : Type*) (β : Type*) [emetric_space α] [emetric_space β] extends α ≃ β := (isometry_to_fun : isometry to_fun) infix ` ≃ᵢ `:25 := isometric namespace isometric variables [emetric_space α] [emetric_space β] [emetric_space γ] instance : has_coe_to_fun (α ≃ᵢ β) := ⟨λ_, α → β, λe, e.to_equiv⟩ lemma coe_eq_to_equiv (h : α ≃ᵢ β) (a : α) : h a = h.to_equiv a := rfl @[simp] lemma coe_to_equiv (h : α ≃ᵢ β) : ⇑h.to_equiv = h := rfl protected lemma isometry (h : α ≃ᵢ β) : isometry h := h.isometry_to_fun protected lemma edist_eq (h : α ≃ᵢ β) (x y : α) : edist (h x) (h y) = edist x y := h.isometry.edist_eq x y protected lemma dist_eq {α β : Type*} [metric_space α] [metric_space β] (h : α ≃ᵢ β) (x y : α) : dist (h x) (h y) = dist x y := h.isometry.dist_eq x y protected lemma continuous (h : α ≃ᵢ β) : continuous h := h.isometry.continuous @[simp] lemma ediam_image (h : α ≃ᵢ β) (s : set α) : emetric.diam (h '' s) = emetric.diam s := h.isometry.ediam_image s lemma to_equiv_inj : ∀ ⦃h₁ h₂ : α ≃ᵢ β⦄, (h₁.to_equiv = h₂.to_equiv) → h₁ = h₂ | ⟨e₁, h₁⟩ ⟨e₂, h₂⟩ H := by { dsimp at H, subst e₁ } @[ext] lemma ext ⦃h₁ h₂ : α ≃ᵢ β⦄ (H : ∀ x, h₁ x = h₂ x) : h₁ = h₂ := to_equiv_inj $ equiv.ext H /-- Alternative constructor for isometric bijections, taking as input an isometry, and a right inverse. -/ def mk' (f : α → β) (g : β → α) (hfg : ∀ x, f (g x) = x) (hf : isometry f) : α ≃ᵢ β := { to_fun := f, inv_fun := g, left_inv := λ x, hf.injective $ hfg _, right_inv := hfg, isometry_to_fun := hf } /-- The identity isometry of a space. -/ protected def refl (α : Type*) [emetric_space α] : α ≃ᵢ α := { isometry_to_fun := isometry_id, .. equiv.refl α } /-- The composition of two isometric isomorphisms, as an isometric isomorphism. -/ protected def trans (h₁ : α ≃ᵢ β) (h₂ : β ≃ᵢ γ) : α ≃ᵢ γ := { isometry_to_fun := h₂.isometry_to_fun.comp h₁.isometry_to_fun, .. equiv.trans h₁.to_equiv h₂.to_equiv } @[simp] lemma trans_apply (h₁ : α ≃ᵢ β) (h₂ : β ≃ᵢ γ) (x : α) : h₁.trans h₂ x = h₂ (h₁ x) := rfl /-- The inverse of an isometric isomorphism, as an isometric isomorphism. -/ protected def symm (h : α ≃ᵢ β) : β ≃ᵢ α := { isometry_to_fun := h.isometry.right_inv h.right_inv, to_equiv := h.to_equiv.symm } @[simp] lemma symm_symm (h : α ≃ᵢ β) : h.symm.symm = h := to_equiv_inj h.to_equiv.symm_symm @[simp] lemma apply_symm_apply (h : α ≃ᵢ β) (y : β) : h (h.symm y) = y := h.to_equiv.apply_symm_apply y @[simp] lemma symm_apply_apply (h : α ≃ᵢ β) (x : α) : h.symm (h x) = x := h.to_equiv.symm_apply_apply x lemma symm_apply_eq (h : α ≃ᵢ β) {x : α} {y : β} : h.symm y = x ↔ y = h x := h.to_equiv.symm_apply_eq lemma eq_symm_apply (h : α ≃ᵢ β) {x : α} {y : β} : x = h.symm y ↔ h x = y := h.to_equiv.eq_symm_apply lemma symm_comp_self (h : α ≃ᵢ β) : ⇑h.symm ∘ ⇑h = id := funext $ assume a, h.to_equiv.left_inv a lemma self_comp_symm (h : α ≃ᵢ β) : ⇑h ∘ ⇑h.symm = id := funext $ assume a, h.to_equiv.right_inv a @[simp] lemma range_eq_univ (h : α ≃ᵢ β) : range h = univ := eq_univ_of_forall $ assume b, ⟨h.symm b, congr_fun h.self_comp_symm b⟩ lemma image_symm (h : α ≃ᵢ β) : image h.symm = preimage h := image_eq_preimage_of_inverse h.symm.to_equiv.left_inv h.symm.to_equiv.right_inv lemma preimage_symm (h : α ≃ᵢ β) : preimage h.symm = image h := (image_eq_preimage_of_inverse h.to_equiv.left_inv h.to_equiv.right_inv).symm @[simp] lemma symm_trans_apply (h₁ : α ≃ᵢ β) (h₂ : β ≃ᵢ γ) (x : γ) : (h₁.trans h₂).symm x = h₁.symm (h₂.symm x) := rfl lemma ediam_univ (h : α ≃ᵢ β) : emetric.diam (univ : set α) = emetric.diam (univ : set β) := by rw [← h.range_eq_univ, h.isometry.ediam_range] @[simp] lemma ediam_preimage (h : α ≃ᵢ β) (s : set β) : emetric.diam (h ⁻¹' s) = emetric.diam s := by rw [← image_symm, ediam_image] /-- The (bundled) homeomorphism associated to an isometric isomorphism. -/ protected def to_homeomorph (h : α ≃ᵢ β) : α ≃ₜ β := { continuous_to_fun := h.continuous, continuous_inv_fun := h.symm.continuous, .. h } @[simp] lemma coe_to_homeomorph (h : α ≃ᵢ β) : ⇑(h.to_homeomorph) = h := rfl @[simp] lemma coe_to_homeomorph_symm (h : α ≃ᵢ β) : ⇑(h.to_homeomorph.symm) = h.symm := rfl @[simp] lemma to_homeomorph_to_equiv (h : α ≃ᵢ β) : h.to_homeomorph.to_equiv = h.to_equiv := rfl @[simp] lemma comp_continuous_on_iff {γ} [topological_space γ] (h : α ≃ᵢ β) {f : γ → α} {s : set γ} : continuous_on (h ∘ f) s ↔ continuous_on f s := h.to_homeomorph.comp_continuous_on_iff _ _ @[simp] lemma comp_continuous_iff {γ} [topological_space γ] (h : α ≃ᵢ β) {f : γ → α} : continuous (h ∘ f) ↔ continuous f := h.to_homeomorph.comp_continuous_iff @[simp] lemma comp_continuous_iff' {γ} [topological_space γ] (h : α ≃ᵢ β) {f : β → γ} : continuous (f ∘ h) ↔ continuous f := h.to_homeomorph.comp_continuous_iff' /-- The group of isometries. -/ instance : group (α ≃ᵢ α) := { one := isometric.refl _, mul := λ e₁ e₂, e₂.trans e₁, inv := isometric.symm, mul_assoc := λ e₁ e₂ e₃, rfl, one_mul := λ e, ext $ λ _, rfl, mul_one := λ e, ext $ λ _, rfl, mul_left_inv := λ e, ext e.symm_apply_apply } @[simp] lemma coe_one : ⇑(1 : α ≃ᵢ α) = id := rfl @[simp] lemma coe_mul (e₁ e₂ : α ≃ᵢ α) : ⇑(e₁ * e₂) = e₁ ∘ e₂ := rfl lemma mul_apply (e₁ e₂ : α ≃ᵢ α) (x : α) : (e₁ * e₂) x = e₁ (e₂ x) := rfl @[simp] lemma inv_apply_self (e : α ≃ᵢ α) (x: α) : e⁻¹ (e x) = x := e.symm_apply_apply x @[simp] lemma apply_inv_self (e : α ≃ᵢ α) (x: α) : e (e⁻¹ x) = x := e.apply_symm_apply x section normed_group variables {G : Type*} [normed_group G] /-- Addition `y ↦ y + x` as an `isometry`. -/ protected def add_right (x : G) : G ≃ᵢ G := { isometry_to_fun := isometry_emetric_iff_metric.2 $ λ y z, dist_add_right _ _ _, .. equiv.add_right x } @[simp] lemma add_right_to_equiv (x : G) : (isometric.add_right x).to_equiv = equiv.add_right x := rfl @[simp] lemma coe_add_right (x : G) : (isometric.add_right x : G → G) = λ y, y + x := rfl lemma add_right_apply (x y : G) : (isometric.add_right x : G → G) y = y + x := rfl @[simp] lemma add_right_symm (x : G) : (isometric.add_right x).symm = isometric.add_right (-x) := ext $ λ y, rfl /-- Addition `y ↦ x + y` as an `isometry`. -/ protected def add_left (x : G) : G ≃ᵢ G := { isometry_to_fun := isometry_emetric_iff_metric.2 $ λ y z, dist_add_left _ _ _, to_equiv := equiv.add_left x } @[simp] lemma add_left_to_equiv (x : G) : (isometric.add_left x).to_equiv = equiv.add_left x := rfl @[simp] lemma coe_add_left (x : G) : ⇑(isometric.add_left x) = (+) x := rfl @[simp] lemma add_left_symm (x : G) : (isometric.add_left x).symm = isometric.add_left (-x) := ext $ λ y, rfl variable (G) /-- Negation `x ↦ -x` as an `isometry`. -/ protected def neg : G ≃ᵢ G := { isometry_to_fun := isometry_emetric_iff_metric.2 $ λ x y, dist_neg_neg _ _, to_equiv := equiv.neg G } variable {G} @[simp] lemma neg_symm : (isometric.neg G).symm = isometric.neg G := rfl @[simp] lemma neg_to_equiv : (isometric.neg G).to_equiv = equiv.neg G := rfl @[simp] lemma coe_neg : ⇑(isometric.neg G) = has_neg.neg := rfl end normed_group end isometric namespace isometric variables [metric_space α] [metric_space β] (h : α ≃ᵢ β) @[simp] lemma diam_image (s : set α) : metric.diam (h '' s) = metric.diam s := h.isometry.diam_image s @[simp] lemma diam_preimage (s : set β) : metric.diam (h ⁻¹' s) = metric.diam s := by rw [← image_symm, diam_image] lemma diam_univ : metric.diam (univ : set α) = metric.diam (univ : set β) := congr_arg ennreal.to_real h.ediam_univ end isometric /-- An isometry induces an isometric isomorphism between the source space and the range of the isometry. -/ def isometry.isometric_on_range [emetric_space α] [emetric_space β] {f : α → β} (h : isometry f) : α ≃ᵢ range f := { isometry_to_fun := λx y, by simpa [subtype.edist_eq] using h x y, .. equiv.set.range f h.injective } @[simp] lemma isometry.isometric_on_range_apply [emetric_space α] [emetric_space β] {f : α → β} (h : isometry f) (x : α) : h.isometric_on_range x = ⟨f x, mem_range_self _⟩ := rfl /-- In a normed algebra, the inclusion of the base field in the extended field is an isometry. -/ lemma algebra_map_isometry (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] : isometry (algebra_map 𝕜 𝕜') := begin refine isometry_emetric_iff_metric.2 (λx y, _), rw [dist_eq_norm, dist_eq_norm, ← ring_hom.map_sub, norm_algebra_map_eq], end /-- The space of bounded sequences, with its sup norm -/ @[reducible] def ℓ_infty_ℝ : Type := bounded_continuous_function ℕ ℝ open bounded_continuous_function metric topological_space namespace Kuratowski_embedding /-! ### In this section, we show that any separable metric space can be embedded isometrically in ℓ^∞(ℝ) -/ variables {f g : ℓ_infty_ℝ} {n : ℕ} {C : ℝ} [metric_space α] (x : ℕ → α) (a b : α) /-- A metric space can be embedded in `l^∞(ℝ)` via the distances to points in a fixed countable set, if this set is dense. This map is given in the next definition, without density assumptions. -/ def embedding_of_subset : ℓ_infty_ℝ := of_normed_group_discrete (λn, dist a (x n) - dist (x 0) (x n)) (dist a (x 0)) (λ_, abs_dist_sub_le _ _ _) lemma embedding_of_subset_coe : embedding_of_subset x a n = dist a (x n) - dist (x 0) (x n) := rfl /-- The embedding map is always a semi-contraction. -/ lemma embedding_of_subset_dist_le (a b : α) : dist (embedding_of_subset x a) (embedding_of_subset x b) ≤ dist a b := begin refine (dist_le dist_nonneg).2 (λn, _), simp only [embedding_of_subset_coe, real.dist_eq], convert abs_dist_sub_le a b (x n) using 2, ring end /-- When the reference set is dense, the embedding map is an isometry on its image. -/ lemma embedding_of_subset_isometry (H : dense_range x) : isometry (embedding_of_subset x) := begin refine isometry_emetric_iff_metric.2 (λa b, _), refine (embedding_of_subset_dist_le x a b).antisymm (le_of_forall_pos_le_add (λe epos, _)), /- First step: find n with dist a (x n) < e -/ rcases metric.mem_closure_range_iff.1 (H a) (e/2) (half_pos epos) with ⟨n, hn⟩, /- Second step: use the norm control at index n to conclude -/ have C : dist b (x n) - dist a (x n) = embedding_of_subset x b n - embedding_of_subset x a n := by { simp only [embedding_of_subset_coe, sub_sub_sub_cancel_right] }, have := calc dist a b ≤ dist a (x n) + dist (x n) b : dist_triangle _ _ _ ... = 2 * dist a (x n) + (dist b (x n) - dist a (x n)) : by { simp [dist_comm], ring } ... ≤ 2 * dist a (x n) + abs (dist b (x n) - dist a (x n)) : by apply_rules [add_le_add_left, le_abs_self] ... ≤ 2 * (e/2) + abs (embedding_of_subset x b n - embedding_of_subset x a n) : begin rw C, apply_rules [add_le_add, mul_le_mul_of_nonneg_left, hn.le, le_refl], norm_num end ... ≤ 2 * (e/2) + dist (embedding_of_subset x b) (embedding_of_subset x a) : by simp [← real.dist_eq, dist_coe_le_dist] ... = dist (embedding_of_subset x b) (embedding_of_subset x a) + e : by ring, simpa [dist_comm] using this end /-- Every separable metric space embeds isometrically in ℓ_infty_ℝ. -/ theorem exists_isometric_embedding (α : Type u) [metric_space α] [separable_space α] : ∃(f : α → ℓ_infty_ℝ), isometry f := begin cases (univ : set α).eq_empty_or_nonempty with h h, { use (λ_, 0), assume x, exact absurd h (nonempty.ne_empty ⟨x, mem_univ x⟩) }, { /- We construct a map x : ℕ → α with dense image -/ rcases h with ⟨basepoint⟩, haveI : inhabited α := ⟨basepoint⟩, have : ∃s:set α, countable s ∧ dense s := exists_countable_dense α, rcases this with ⟨S, ⟨S_countable, S_dense⟩⟩, rcases countable_iff_exists_surjective.1 S_countable with ⟨x, x_range⟩, /- Use embedding_of_subset to construct the desired isometry -/ exact ⟨embedding_of_subset x, embedding_of_subset_isometry x (S_dense.mono x_range)⟩ } end end Kuratowski_embedding open topological_space Kuratowski_embedding /-- The Kuratowski embedding is an isometric embedding of a separable metric space in ℓ^∞(ℝ) -/ def Kuratowski_embedding (α : Type u) [metric_space α] [separable_space α] : α → ℓ_infty_ℝ := classical.some (Kuratowski_embedding.exists_isometric_embedding α) /-- The Kuratowski embedding is an isometry -/ protected lemma Kuratowski_embedding.isometry (α : Type u) [metric_space α] [separable_space α] : isometry (Kuratowski_embedding α) := classical.some_spec (exists_isometric_embedding α) /-- Version of the Kuratowski embedding for nonempty compacts -/ def nonempty_compacts.Kuratowski_embedding (α : Type u) [metric_space α] [compact_space α] [nonempty α] : nonempty_compacts ℓ_infty_ℝ := ⟨range (Kuratowski_embedding α), range_nonempty _, compact_range (Kuratowski_embedding.isometry α).continuous⟩
3f4bc40f6793403906c03d470907ec600c4eb53c
4aca55eba10c989f0d58647d3c2f371e7da44355
/src/diagonal_matrix.lean
eb0f355fd72a8349a78ab272c55375d93319f013
[]
no_license
eric-wieser/l534zhan-my_project
f9fc75fb5454405e1a2fa9b56cf96c355f6f2336
febc91e76b7b00fe2517f258ca04d27b7f35fcf3
refs/heads/master
1,689,218,910,420
1,630,439,440,000
1,630,439,440,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,161
lean
/- Copyright (c) 2021 Lu-Ming Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Lu-Ming Zhang. -/ import symmetric_matrix import main1 /-! # Diagonal matrices This file contains the definition and basic results about diagonal matrices. ## Main results - `matrix.has_orthogonal_rows`: `A.has_orthogonal_rows` means `A` has orthogonal (with respect to `dot_product`) rows. - `matrix.has_orthogonal_cols`: `A.has_orthogonal_cols` means `A` has orthogonal (with respect to `dot_product`) columns. - `matrix.is_diagonal`: a proposition that stats a given square matrix `A` is diagonal (i.e. `∀ i j, i ≠ j → A i j = 0`). ## Tags diag, diagonal, matrix -/ namespace matrix variables {α R I J : Type*} [fintype I] [fintype J] open_locale matrix /-- `A.has_orthogonal_rows` means matrix `A` has orthogonal (with respect to `dot_product`) rows. -/ def has_orthogonal_rows [has_mul α] [add_comm_monoid α] (A : matrix I J α) : Prop := ∀ ⦃i₁ i₂⦄, i₁ ≠ i₂ → dot_product (A i₁) (A i₂) = 0 /-- `A.has_orthogonal_cols` means matrix `A` has orthogonal (with respect to `dot_product`) columns. -/ def has_orthogonal_cols [has_mul α] [add_comm_monoid α] (A : matrix I J α) : Prop := ∀ ⦃i₁ i₂⦄, i₁ ≠ i₂ → dot_product (λ j, A j i₁) (λ j, A j i₂) = 0 /-- `Aᵀ` has orthogonal rows iff `A` has orthogonal columns. -/ lemma transpose_has_orthogonal_rows_iff_has_orthogonal_cols [has_mul α] [add_comm_monoid α] (A : matrix I J α) : Aᵀ.has_orthogonal_rows ↔ A.has_orthogonal_cols := by simp [has_orthogonal_rows, has_orthogonal_cols, trans_row_eq_col] /-- `Aᵀ` has orthogonal columns iff `A` has orthogonal rows. -/ lemma transpose_has_orthogonal_cols_iff_has_orthogonal_rows [has_mul α] [add_comm_monoid α] (A : matrix I J α) : Aᵀ.has_orthogonal_cols ↔ A.has_orthogonal_rows := by simp [has_orthogonal_rows, has_orthogonal_cols, trans_row_eq_col] /-- `A.is_diagonal` means square matrix `A` is a dianogal matrix: `∀ i j, i ≠ j → A i j = 0`. -/ def is_diagonal [has_zero α] (A : matrix I I α) : Prop := ∀ i j, i ≠ j → A i j = 0 /-- Non-diagonal entries equal zero. -/ @[simp] lemma is_diagonal.apply_ne [has_zero α] {A : matrix I I α} (ha : A.is_diagonal) {i j : I} (h : ¬ i = j) : A i j = 0 := ha i j h /-- Non-diagonal entries equal zero. -/ @[simp] lemma is_diagonal.apply_ne' [has_zero α] {A : matrix I I α} (ha : A.is_diagonal) {i j : I} (h : ¬ j = i) : A i j = 0 := ha.apply_ne (ne.symm h) /-- Matrix `A` is diagonal iff there is a vector `d` such that A is the diagonal matix generated by `d`. -/ lemma is_diagonal_iff_eq_diagonal [has_zero α] [decidable_eq I] (A : matrix I I α) : A.is_diagonal ↔ (∃ d, A = diagonal d):= begin split, { intros h, use (λ i, A i i), ext, specialize h i j, by_cases i = j; simp * at *, }, { rintros ⟨d, rfl⟩ i j h, simp *} end /-- Every unit matrix is diagonal. -/ @[simp] lemma is_diagonal_of_unit [has_zero α] (A : matrix unit unit α) : A.is_diagonal := by {intros i j h, have h':= @unit.ext i j, simp* at *} /-- Every zero matrix is diagonal. -/ @[simp] lemma is_diagonal_of_zero [has_zero α] : (0 : matrix I I α).is_diagonal := λ i j h, by simp /-- Every identity matrix is diagonal. -/ @[simp] lemma is_diagonal_of_one [decidable_eq I] [has_zero α] [has_one α] : (1 : matrix I I α).is_diagonal := by {intros i j h, simp *} /-- `smul` identity matrix `1` is diagonal. -/ @[simp] lemma is_diagonal_of_smul_one [decidable_eq I] [monoid R] [add_monoid α] [has_one α] [distrib_mul_action R α] (k : R) : (k • (1 : matrix I I α)).is_diagonal := by {intros i j h, simp *} /-- Matrix `k • A` is diagonal if `A` is. -/ @[simp] lemma smul_is_diagonal_of [monoid R] [add_monoid α] [distrib_mul_action R α] {k : R} {A : matrix I I α} (ha : A.is_diagonal): (k • A).is_diagonal := by {intros i j h, simp [ha i j h]} /-- The sum of two diagonal matrices is diagonal. -/ @[simp] lemma is_diagonal_add [add_zero_class α] {A B : matrix I I α} (ha : A.is_diagonal) (hb : B.is_diagonal) : (A + B).is_diagonal := by {intros i j h, simp *, rw [ha i j h, hb i j h], simp} /-- The block matrix `A.from_blocks B C D` is diagonal if `A` and `D` are diagonal and `B` and `C` are `0`. -/ lemma is_diagnoal_of_block_conditions [has_zero α] {A : matrix I I α} {B : matrix I J α} {C : matrix J I α} {D : matrix J J α} : (A.is_diagonal) ∧ (D.is_diagonal) ∧ (B = 0) ∧ (C = 0) → (A.from_blocks B C D).is_diagonal:= begin rintros h (i | i) (j | j) hij, any_goals {rcases h with ⟨ha, hd, hb, hc⟩, simp* at *}, {have h' : i ≠ j, {simp* at *}, exact ha i j h'}, {have h' : i ≠ j, {simp* at *}, exact hd i j h'}, end /-- A symmetric block matrix `A.from_blocks B C D` is diagonal if `A` and `D` are diagonal and `B` is `0`. -/ lemma is_diagnoal_of_sym_block_conditions [has_zero α] {A : matrix I I α} {B : matrix I J α} {C : matrix J I α} {D : matrix J J α} (sym : (A.from_blocks B C D).is_sym) : (A.is_diagonal) ∧ (D.is_diagonal) ∧ (B = 0) → (A.from_blocks B C D).is_diagonal:= begin rintros h, apply is_diagnoal_of_block_conditions, refine ⟨h.1, h.2.1, h.2.2, _⟩, obtain ⟨g1, g2, g3, g4⟩ := block_conditions_of_is_sym sym, simp [← g4, h.2.2] end /-- A different form of `matrix.is_diagnoal_of_sym_block_conditions`. -/ lemma is_diagnoal_of_sym_block_conditions' [has_zero α] {A : matrix I I α} {B : matrix I J α} {C : matrix J I α} {D : matrix J J α} {M : matrix (I ⊕ J) (I ⊕ J) α} (sym : M.is_sym) (h : M = A.from_blocks B C D) : (A.is_diagonal) ∧ (D.is_diagonal) ∧ (B = 0) → M.is_diagonal:= by rw h at *; convert is_diagnoal_of_sym_block_conditions sym /-- `(A ⬝ Aᵀ).is_diagonal` iff `A.has_orthogonal_rows`. -/ lemma mul_tranpose_is_diagonal_iff_has_orthogonal_rows [has_mul α] [add_comm_monoid α] {A : matrix I J α} : (A ⬝ Aᵀ).is_diagonal ↔ A.has_orthogonal_rows := begin split, { rintros h i1 i2 hi, have h' := h i1 i2 hi, simp [dot_product, mul_apply,*] at *, }, { intros ha i j h, have h':= ha h, simp [mul_apply, *, dot_product] at *, } end /-- `(Aᵀ ⬝ A).is_diagonal` iff `A.has_orthogonal_cols`. -/ lemma tranpose_mul_is_diagonal_iff_has_orthogonal_cols [has_mul α] [add_comm_monoid α] {A : matrix I J α} : (Aᵀ ⬝ A).is_diagonal ↔ A.has_orthogonal_cols := begin simp [←transpose_has_orthogonal_rows_iff_has_orthogonal_cols], convert mul_tranpose_is_diagonal_iff_has_orthogonal_rows, simp end /-- `(A ⊗ B).is_diagonal` if both `A` and `B` are diagonal. -/ lemma K_is_diagonal_of [mul_zero_class α] {A : matrix I I α} {B : matrix J J α} (ga: A.is_diagonal) (gb: B.is_diagonal): (A ⊗ B).is_diagonal := begin rintros ⟨a, b⟩ ⟨c, d⟩ h, simp [Kronecker], by_cases ha: a = c, have hb: b ≠ d, {intros hb, rw [ha, hb] at h, apply h rfl}, rw (gb _ _ hb), simp, rw (ga _ _ ha), simp, end end matrix
7db9e63507f75c670ad2bd1e90b2c8f1baf24a20
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/tactic/omega/int/form.lean
808351d3b79de42ffcb8f7fdd74ef2e9cc2c65a7
[ "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
2,950
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek Linear integer arithmetic formulas in pre-normalized form. -/ import tactic.omega.int.preterm namespace omega namespace int @[derive has_reflect] inductive form | eq : preterm → preterm → form | le : preterm → preterm → form | not : form → form | or : form → form → form | and : form → form → form local notation x ` =* ` y := form.eq x y local notation x ` ≤* ` y := form.le x y local notation `¬* ` p := form.not p local notation p ` ∨* ` q := form.or p q local notation p ` ∧* ` q := form.and p q namespace form @[simp] def holds (v : nat → int) : form → 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 form @[simp] def univ_close (p : form) : (nat → int) → nat → Prop | v 0 := p.holds v | v (k+1) := ∀ i : int, univ_close (update_zero i v) k namespace form def fresh_index : form → 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 def valid (p : form) : Prop := ∀ v, holds v p def sat (p : form) : Prop := ∃ v, holds v p def implies (p q : form) : Prop := ∀ v, (holds v p → holds v q) def equiv (p q : form) : Prop := ∀ v, (holds v p ↔ holds v q) lemma sat_of_implies_of_sat {p q : form} : implies p q → sat p → sat q := begin intros h1 h2, apply exists_imp_exists h1 h2 end lemma sat_or {p q : form} : 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 def unsat (p : form) : Prop := ¬ sat p def repr : form → 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 form := ⟨repr⟩ meta instance has_to_format : has_to_format form := ⟨λ x, x.repr⟩ end form lemma univ_close_of_valid {p : form} : ∀ {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 : form} : (¬*p).unsat → p.valid := begin simp only [form.sat, form.unsat, form.valid, form.holds], rw classical.not_exists_not, intro h, assumption end meta def form.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
48aece763347f2774ae4b6f3863dfe0158155aa8
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/library/data/fin.lean
5830042b916f2a215852711fba2e206e744cc81c
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
18,020
lean
/- Copyright (c) 2015 Haitao Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Haitao Zhang, Leonardo de Moura Finite ordinal types. -/ import data.list.basic data.finset.basic data.fintype.card algebra.group data.equiv open eq.ops nat function list finset fintype structure fin (n : nat) := (val : nat) (is_lt : val < n) definition less_than [reducible] := fin namespace fin attribute fin.val [coercion] section def_equal variable {n : nat} lemma eq_of_veq : ∀ {i j : fin n}, (val i) = j → i = j | (mk iv ilt) (mk jv jlt) := assume (veq : iv = jv), begin congruence, assumption end lemma veq_of_eq : ∀ {i j : fin n}, i = j → (val i) = j | (mk iv ilt) (mk jv jlt) := assume Peq, show iv = jv, from fin.no_confusion Peq (λ Pe Pqe, Pe) lemma eq_iff_veq {i j : fin n} : (val i) = j ↔ i = j := iff.intro eq_of_veq veq_of_eq definition val_inj := @eq_of_veq n end def_equal section open decidable protected definition has_decidable_eq [instance] (n : nat) : ∀ (i j : fin n), decidable (i = j) | (mk ival ilt) (mk jval jlt) := decidable_of_decidable_of_iff (nat.has_decidable_eq ival jval) eq_iff_veq end lemma dinj_lt (n : nat) : dinj (λ i, i < n) fin.mk := take a1 a2 Pa1 Pa2 Pmkeq, fin.no_confusion Pmkeq (λ Pe Pqe, Pe) lemma val_mk (n i : nat) (Plt : i < n) : fin.val (fin.mk i Plt) = i := rfl definition upto [reducible] (n : nat) : list (fin n) := dmap (λ i, i < n) fin.mk (list.upto n) lemma nodup_upto (n : nat) : nodup (upto n) := dmap_nodup_of_dinj (dinj_lt n) (list.nodup_upto n) lemma mem_upto (n : nat) : ∀ (i : fin n), i ∈ upto n := take i, fin.destruct i (take ival Piltn, assert ival ∈ list.upto n, from mem_upto_of_lt Piltn, mem_dmap Piltn this) lemma upto_zero : upto 0 = [] := by rewrite [↑upto, list.upto_nil, dmap_nil] lemma map_val_upto (n : nat) : map fin.val (upto n) = list.upto n := map_dmap_of_inv_of_pos (val_mk n) (@lt_of_mem_upto n) lemma length_upto (n : nat) : length (upto n) = n := calc length (upto n) = length (list.upto n) : (map_val_upto n ▸ length_map fin.val (upto n))⁻¹ ... = n : list.length_upto n definition is_fintype [instance] (n : nat) : fintype (fin n) := fintype.mk (upto n) (nodup_upto n) (mem_upto n) section pigeonhole open fintype lemma card_fin (n : nat) : card (fin n) = n := length_upto n theorem pigeonhole {n m : nat} (Pmltn : m < n) : ¬∃ f : fin n → fin m, injective f := assume Pex, absurd Pmltn (not_lt_of_ge (calc n = card (fin n) : card_fin ... ≤ card (fin m) : card_le_of_inj (fin n) (fin m) Pex ... = m : card_fin)) end pigeonhole protected definition zero (n : nat) : fin (succ n) := mk 0 !zero_lt_succ definition fin_has_zero [instance] [reducible] (n : nat) : has_zero (fin (succ n)) := has_zero.mk (fin.zero n) theorem val_zero (n : nat) : val (0 : fin (succ n)) = 0 := rfl definition mk_mod [reducible] (n i : nat) : fin (succ n) := mk (i % (succ n)) (mod_lt _ !zero_lt_succ) theorem mk_mod_zero_eq (n : nat) : mk_mod n 0 = 0 := rfl variable {n : nat} theorem val_lt : ∀ i : fin n, val i < n | (mk v h) := h lemma max_lt (i j : fin n) : max i j < n := max_lt (is_lt i) (is_lt j) definition lift : fin n → Π m : nat, fin (n + m) | (mk v h) m := mk v (lt_add_of_lt_right h m) definition lift_succ (i : fin n) : fin (nat.succ n) := have r : fin (n+1), from lift i 1, r definition maxi [reducible] : fin (succ n) := mk n !lt_succ_self theorem val_lift : ∀ (i : fin n) (m : nat), val i = val (lift i m) | (mk v h) m := rfl lemma mk_succ_ne_zero {i : nat} : ∀ {P}, mk (succ i) P ≠ (0 : fin (succ n)) := assume P Pe, absurd (veq_of_eq Pe) !succ_ne_zero lemma mk_mod_eq {i : fin (succ n)} : i = mk_mod n i := eq_of_veq begin rewrite [↑mk_mod, mod_eq_of_lt !is_lt] end lemma mk_mod_of_lt {i : nat} (Plt : i < succ n) : mk_mod n i = mk i Plt := begin esimp [mk_mod], congruence, exact mod_eq_of_lt Plt end section lift_lower lemma lift_zero : lift_succ (0 : fin (succ n)) = (0 : fin (succ (succ n))) := rfl lemma ne_max_of_lt_max {i : fin (succ n)} : i < n → i ≠ maxi := by intro hlt he; substvars; exact absurd hlt (lt.irrefl n) lemma lt_max_of_ne_max {i : fin (succ n)} : i ≠ maxi → i < n := assume hne : i ≠ maxi, assert vne : val i ≠ n, from assume he, have val (@maxi n) = n, from rfl, have val i = val (@maxi n), from he ⬝ this⁻¹, absurd (eq_of_veq this) hne, have val i < nat.succ n, from val_lt i, lt_of_le_of_ne (le_of_lt_succ this) vne lemma lift_succ_ne_max {i : fin n} : lift_succ i ≠ maxi := begin cases i with v hlt, esimp [lift_succ, lift, max], intro he, injection he, substvars, exact absurd hlt (lt.irrefl v) end lemma lift_succ_inj : injective (@lift_succ n) := take i j, destruct i (destruct j (take iv ilt jv jlt Pmkeq, begin congruence, apply fin.no_confusion Pmkeq, intros, assumption end)) lemma lt_of_inj_of_max (f : fin (succ n) → fin (succ n)) : injective f → (f maxi = maxi) → ∀ i : fin (succ n), i < n → f i < n := assume Pinj Peq, take i, assume Pilt, assert P1 : f i = f maxi → i = maxi, from assume Peq, Pinj i maxi Peq, have f i ≠ maxi, from begin rewrite -Peq, intro P2, apply absurd (P1 P2) (ne_max_of_lt_max Pilt) end, lt_max_of_ne_max this definition lift_fun : (fin n → fin n) → (fin (succ n) → fin (succ n)) := λ f i, dite (i = maxi) (λ Pe, maxi) (λ Pne, lift_succ (f (mk i (lt_max_of_ne_max Pne)))) definition lower_inj (f : fin (succ n) → fin (succ n)) (inj : injective f) : f maxi = maxi → fin n → fin n := assume Peq, take i, mk (f (lift_succ i)) (lt_of_inj_of_max f inj Peq (lift_succ i) (lt_max_of_ne_max lift_succ_ne_max)) lemma lift_fun_max {f : fin n → fin n} : lift_fun f maxi = maxi := begin rewrite [↑lift_fun, dif_pos rfl] end lemma lift_fun_of_ne_max {f : fin n → fin n} {i} (Pne : i ≠ maxi) : lift_fun f i = lift_succ (f (mk i (lt_max_of_ne_max Pne))) := begin rewrite [↑lift_fun, dif_neg Pne] end lemma lift_fun_eq {f : fin n → fin n} {i : fin n} : lift_fun f (lift_succ i) = lift_succ (f i) := begin rewrite [lift_fun_of_ne_max lift_succ_ne_max], congruence, congruence, rewrite [-eq_iff_veq], esimp, rewrite [↑lift_succ, -val_lift] end lemma lift_fun_of_inj {f : fin n → fin n} : injective f → injective (lift_fun f) := assume Pinj, take i j, assert Pdi : decidable (i = maxi), from _, assert Pdj : decidable (j = maxi), from _, begin cases Pdi with Pimax Pinmax, cases Pdj with Pjmax Pjnmax, substvars, intros, exact rfl, substvars, rewrite [lift_fun_max, lift_fun_of_ne_max Pjnmax], intro Plmax, apply absurd Plmax⁻¹ lift_succ_ne_max, cases Pdj with Pjmax Pjnmax, substvars, rewrite [lift_fun_max, lift_fun_of_ne_max Pinmax], intro Plmax, apply absurd Plmax lift_succ_ne_max, rewrite [lift_fun_of_ne_max Pinmax, lift_fun_of_ne_max Pjnmax], intro Peq, rewrite [-eq_iff_veq], exact veq_of_eq (Pinj (lift_succ_inj Peq)) end lemma lift_fun_inj : injective (@lift_fun n) := take f₁ f₂ Peq, funext (λ i, assert lift_fun f₁ (lift_succ i) = lift_fun f₂ (lift_succ i), from congr_fun Peq _, begin revert this, rewrite [*lift_fun_eq], apply lift_succ_inj end) lemma lower_inj_apply {f Pinj Pmax} (i : fin n) : val (lower_inj f Pinj Pmax i) = val (f (lift_succ i)) := by rewrite [↑lower_inj] end lift_lower section madd definition madd (i j : fin (succ n)) : fin (succ n) := mk ((i + j) % (succ n)) (mod_lt _ !zero_lt_succ) definition minv : ∀ i : fin (succ n), fin (succ n) | (mk iv ilt) := mk ((succ n - iv) % succ n) (mod_lt _ !zero_lt_succ) lemma val_madd : ∀ i j : fin (succ n), val (madd i j) = (i + j) % (succ n) | (mk iv ilt) (mk jv jlt) := by esimp lemma madd_inj : ∀ {i : fin (succ n)}, injective (madd i) | (mk iv ilt) := take j₁ j₂, fin.destruct j₁ (fin.destruct j₂ (λ jv₁ jlt₁ jv₂ jlt₂, begin rewrite [↑madd, -eq_iff_veq], intro Peq, congruence, rewrite [-(mod_eq_of_lt jlt₁), -(mod_eq_of_lt jlt₂)], apply mod_eq_mod_of_add_mod_eq_add_mod_left Peq end)) lemma madd_mk_mod {i j : nat} : madd (mk_mod n i) (mk_mod n j) = mk_mod n (i+j) := eq_of_veq begin esimp [madd, mk_mod], rewrite [ mod_add_mod, add_mod_mod ] end lemma val_mod : ∀ i : fin (succ n), (val i) % (succ n) = val i | (mk iv ilt) := by esimp; rewrite [(mod_eq_of_lt ilt)] lemma madd_comm (i j : fin (succ n)) : madd i j = madd j i := by apply eq_of_veq; rewrite [*val_madd, add.comm (val i)] lemma zero_madd (i : fin (succ n)) : madd 0 i = i := have H : madd (fin.zero n) i = i, by apply eq_of_veq; rewrite [val_madd, ↑fin.zero, nat.zero_add, mod_eq_of_lt (is_lt i)], H lemma madd_zero (i : fin (succ n)) : madd i (fin.zero n) = i := !madd_comm ▸ zero_madd i lemma madd_assoc (i j k : fin (succ n)) : madd (madd i j) k = madd i (madd j k) := by apply eq_of_veq; rewrite [*val_madd, mod_add_mod, add_mod_mod, add.assoc (val i)] lemma madd_left_inv : ∀ i : fin (succ n), madd (minv i) i = fin.zero n | (mk iv ilt) := eq_of_veq (by rewrite [val_madd, ↑minv, ↑fin.zero, mod_add_mod, nat.sub_add_cancel (le_of_lt ilt), mod_self]) definition madd_is_comm_group [instance] : add_comm_group (fin (succ n)) := add_comm_group.mk madd madd_assoc (fin.zero n) zero_madd madd_zero minv madd_left_inv madd_comm end madd definition pred : fin n → fin n | (mk v h) := mk (nat.pred v) (pre_lt_of_lt h) lemma val_pred : ∀ (i : fin n), val (pred i) = nat.pred (val i) | (mk v h) := rfl lemma pred_zero : pred (fin.zero n) = fin.zero n := rfl definition mk_pred (i : nat) (h : succ i < succ n) : fin n := mk i (lt_of_succ_lt_succ h) definition succ : fin n → fin (succ n) | (mk v h) := mk (nat.succ v) (succ_lt_succ h) lemma val_succ : ∀ (i : fin n), val (succ i) = nat.succ (val i) | (mk v h) := rfl lemma succ_max : fin.succ maxi = (@maxi (nat.succ n)) := rfl lemma lift_succ.comm : lift_succ ∘ (@succ n) = succ ∘ lift_succ := funext take i, eq_of_veq (begin rewrite [↑lift_succ, -val_lift, *val_succ, -val_lift] end) definition elim0 {C : fin 0 → Type} : Π i : fin 0, C i | (mk v h) := absurd h !not_lt_zero definition zero_succ_cases {C : fin (nat.succ n) → Type} : C (fin.zero n) → (Π j : fin n, C (succ j)) → (Π k : fin (nat.succ n), C k) := begin intros CO CS k, induction k with [vk, pk], induction (nat.decidable_lt 0 vk) with [HT, HF], { show C (mk vk pk), from let vj := nat.pred vk in have vk = vj+1, from eq.symm (succ_pred_of_pos HT), assert vj < n, from lt_of_succ_lt_succ (eq.subst `vk = vj+1` pk), have succ (mk vj `vj < n`) = mk vk pk, from val_inj (eq.symm `vk = vj+1`), eq.rec_on this (CS (mk vj `vj < n`)) }, { show C (mk vk pk), from have vk = 0, from eq_zero_of_le_zero (le_of_not_gt HF), have fin.zero n = mk vk pk, from val_inj (eq.symm this), eq.rec_on this CO } end definition succ_maxi_cases {C : fin (nat.succ n) → Type} : (Π j : fin n, C (lift_succ j)) → C maxi → (Π k : fin (nat.succ n), C k) := begin intros CL CM k, induction k with [vk, pk], induction (nat.decidable_lt vk n) with [HT, HF], { show C (mk vk pk), from have HL : lift_succ (mk vk HT) = mk vk pk, from val_inj rfl, eq.rec_on HL (CL (mk vk HT)) }, { show C (mk vk pk), from have HMv : vk = n, from le.antisymm (le_of_lt_succ pk) (le_of_not_gt HF), have HM : maxi = mk vk pk, from val_inj (eq.symm HMv), eq.rec_on HM CM } end definition foldr {A B : Type} (m : A → B → B) (b : B) : ∀ {n : nat}, (fin n → A) → B := nat.rec (λ f, b) (λ n IH f, m (f (fin.zero n)) (IH (λ i : fin n, f (succ i)))) definition foldl {A B : Type} (m : B → A → B) (b : B) : ∀ {n : nat}, (fin n → A) → B := nat.rec (λ f, b) (λ n IH f, m (IH (λ i : fin n, f (lift_succ i))) (f maxi)) theorem choice {C : fin n → Type} : (∀ i : fin n, nonempty (C i)) → nonempty (Π i : fin n, C i) := begin revert C, induction n with [n, IH], { intros C H, apply nonempty.intro, exact elim0 }, { intros C H, fapply nonempty.elim (H (fin.zero n)), intro CO, fapply nonempty.elim (IH (λ i, C (succ i)) (λ i, H (succ i))), intro CS, apply nonempty.intro, exact zero_succ_cases CO CS } end section open list local postfix `+1`:100 := nat.succ lemma dmap_map_lift {n : nat} : ∀ l : list nat, (∀ i, i ∈ l → i < n) → dmap (λ i, i < n +1) mk l = map lift_succ (dmap (λ i, i < n) mk l) | [] := assume Plt, rfl | (i::l) := assume Plt, begin rewrite [@dmap_cons_of_pos _ _ (λ i, i < n +1) _ _ _ (lt_succ_of_lt (Plt i !mem_cons)), @dmap_cons_of_pos _ _ (λ i, i < n) _ _ _ (Plt i !mem_cons), map_cons], congruence, apply dmap_map_lift, intro j Pjinl, apply Plt, apply mem_cons_of_mem, assumption end lemma upto_succ (n : nat) : upto (n +1) = maxi :: map lift_succ (upto n) := begin rewrite [↑fin.upto, list.upto_succ, @dmap_cons_of_pos _ _ (λ i, i < n +1) _ _ _ (nat.self_lt_succ n)], congruence, apply dmap_map_lift, apply @list.lt_of_mem_upto end definition upto_step : ∀ {n : nat}, fin.upto (n +1) = (map succ (upto n))++[0] | 0 := rfl | (i +1) := begin rewrite [upto_succ i, map_cons, append_cons, succ_max, upto_succ, -lift_zero], congruence, rewrite [map_map, -lift_succ.comm, -map_map, -(map_singleton _ 0), -map_append, -upto_step] end end open sum equiv decidable definition fin_zero_equiv_empty : fin 0 ≃ empty := ⦃ equiv, to_fun := λ f : (fin 0), elim0 f, inv_fun := λ e : empty, empty.rec _ e, left_inv := λ f : (fin 0), elim0 f, right_inv := λ e : empty, empty.rec _ e ⦄ definition fin_one_equiv_unit : fin 1 ≃ unit := ⦃ equiv, to_fun := λ f : (fin 1), unit.star, inv_fun := λ u : unit, fin.zero 0, left_inv := begin intro f, change mk 0 !zero_lt_succ = f, cases f with v h, congruence, have v +1 ≤ 1, from succ_le_of_lt h, have v ≤ 0, from le_of_succ_le_succ this, have v = 0, from eq_zero_of_le_zero this, subst v end, right_inv := begin intro u, cases u, reflexivity end ⦄ definition fin_sum_equiv (n m : nat) : (fin n + fin m) ≃ fin (n+m) := assert aux₁ : ∀ {v}, v < m → (v + n) < (n + m), from take v, suppose v < m, calc v + n < m + n : add_lt_add_of_lt_of_le this !le.refl ... = n + m : add.comm, ⦃ equiv, to_fun := λ s : sum (fin n) (fin m), match s with | sum.inl (mk v hlt) := mk v (lt_add_of_lt_right hlt m) | sum.inr (mk v hlt) := mk (v+n) (aux₁ hlt) end, inv_fun := λ f : fin (n + m), match f with | mk v hlt := if h : v < n then sum.inl (mk v h) else sum.inr (mk (v-n) (nat.sub_lt_of_lt_add hlt (le_of_not_gt h))) end, left_inv := begin intro s, cases s with f₁ f₂, { cases f₁ with v hlt, esimp, rewrite [dif_pos hlt] }, { cases f₂ with v hlt, esimp, have ¬ v + n < n, from suppose v + n < n, assert v < n - n, from nat.lt_sub_of_add_lt this !le.refl, have v < 0, by rewrite [nat.sub_self at this]; exact this, absurd this !not_lt_zero, rewrite [dif_neg this], congruence, congruence, rewrite [nat.add_sub_cancel] } end, right_inv := begin intro f, cases f with v hlt, esimp, apply @by_cases (v < n), { intro h₁, rewrite [dif_pos h₁] }, { intro h₁, rewrite [dif_neg h₁], esimp, congruence, rewrite [nat.sub_add_cancel (le_of_not_gt h₁)] } end ⦄ definition fin_prod_equiv_of_pos (n m : nat) : n > 0 → (fin n × fin m) ≃ fin (n*m) := suppose n > 0, assert aux₁ : ∀ {v₁ v₂}, v₁ < n → v₂ < m → v₁ + v₂ * n < n*m, from take v₁ v₂, assume h₁ h₂, have nat.succ v₂ ≤ m, from succ_le_of_lt h₂, assert nat.succ v₂ * n ≤ m * n, from mul_le_mul_right _ this, have v₂ * n + n ≤ n * m, by rewrite [-add_one at this, right_distrib at this, one_mul at this, mul.comm m n at this]; exact this, assert v₁ + (v₂ * n + n) < n + n * m, from add_lt_add_of_lt_of_le h₁ this, have v₁ + v₂ * n + n < n * m + n, by rewrite [add.assoc, add.comm (n*m) n]; exact this, lt_of_add_lt_add_right this, assert aux₂ : ∀ v, v % n < n, from take v, mod_lt _ `n > 0`, assert aux₃ : ∀ {v}, v < n * m → v / n < m, from take v, assume h, by rewrite mul.comm at h; exact nat.div_lt_of_lt_mul h, ⦃ equiv, to_fun := λ p : (fin n × fin m), match p with (mk v₁ hlt₁, mk v₂ hlt₂) := mk (v₁ + v₂ * n) (aux₁ hlt₁ hlt₂) end, inv_fun := λ f : fin (n*m), match f with (mk v hlt) := (mk (v % n) (aux₂ v), mk (v / n) (aux₃ hlt)) end, left_inv := begin intro p, cases p with f₁ f₂, cases f₁ with v₁ hlt₁, cases f₂ with v₂ hlt₂, esimp, congruence, {congruence, rewrite [add_mul_mod_self, mod_eq_of_lt hlt₁] }, {congruence, rewrite [add_mul_div_self `n > 0`, div_eq_zero_of_lt hlt₁, zero_add]} end, right_inv := begin intro f, cases f with v hlt, esimp, congruence, rewrite [add.comm, -eq_div_mul_add_mod] end ⦄ definition fin_prod_equiv : Π (n m : nat), (fin n × fin m) ≃ fin (n*m) | 0 b := calc (fin 0 × fin b) ≃ (empty × fin b) : prod_congr fin_zero_equiv_empty !equiv.refl ... ≃ empty : prod_empty_left ... ≃ fin 0 : fin_zero_equiv_empty ... ≃ fin (0 * b) : by rewrite zero_mul | (a+1) b := fin_prod_equiv_of_pos (a+1) b dec_trivial definition fin_two_equiv_bool : fin 2 ≃ bool := calc fin 2 ≃ fin (1 + 1) : equiv.refl ... ≃ fin 1 + fin 1 : fin_sum_equiv ... ≃ unit + unit : sum_congr fin_one_equiv_unit fin_one_equiv_unit ... ≃ bool : bool_equiv_unit_sum_unit definition fin_sum_unit_equiv (n : nat) : fin n + unit ≃ fin (n+1) := calc fin n + unit ≃ fin n + fin 1 : sum_congr !equiv.refl (equiv.symm fin_one_equiv_unit) ... ≃ fin (n+1) : fin_sum_equiv end fin
9dbcc4b345c2c089ac2a3f7c8fc066787f656df8
91b8df3b248df89472cc0b753fbe2bac750aefea
/experiments/lean/src/ddl/binary/repr.lean
13d1311f1672f4bc3ba40393d043da87432a93f8
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
yeslogic/fathom
eabe5c4112d3b4d5ec9096a57bb502254ddbdf15
3960a9466150d392c2cb103c5cb5fcffa0200814
refs/heads/main
1,685,349,769,736
1,675,998,621,000
1,675,998,621,000
28,993,871
214
11
Apache-2.0
1,694,044,276,000
1,420,764,938,000
Rust
UTF-8
Lean
false
false
2,130
lean
import ddl.binary.basic import ddl.binary.formation import ddl.host.basic import ddl.host.formation namespace ddl.binary open ddl open ddl.binary namespace type variables {ℓ α : Type} def repr : type ℓ α → host.type ℓ | (union_nil) := host.type.union_nil | (union_cons l t₁ t₂) := host.type.union_cons l t₁.repr t₂.repr | (struct_nil) := host.type.struct_nil | (struct_cons l t₁ t₂) := host.type.struct_cons l t₁.repr t₂.repr | (array t e) := host.type.array (t.repr) | (assert t e) := t.repr | (interp t e ht) := ht | _ := sorry lemma repr_well_formed [decidable_eq ℓ] : Π (t : binary.type ℓ α), well_formed t → host.type.well_formed t.repr := begin intros bt hbtwf, induction hbtwf, case well_formed.bvar i { admit }, case well_formed.fvar x { admit }, case well_formed.bit { admit }, case well_formed.union_nil { exact host.type.well_formed.union_nil }, case well_formed.union_cons l t₁ t₂ hbtwf₁ hbtwf₂ hbts₂ hhtwf₁ hhtwf₂ { exact host.type.well_formed.union_cons hhtwf₁ hhtwf₂ sorry }, case well_formed.struct_nil { exact host.type.well_formed.struct_nil }, case well_formed.struct_cons l t₁ t₂ hbtwf₁ hbtwf₂ hbts₂ hhtwf₁ hhtwf₂ { exact host.type.well_formed.struct_cons hhtwf₁ hhtwf₂ sorry }, case well_formed.array t₁ e hbtwf₁ hhtwf₁ { exact host.type.well_formed.array hhtwf₁, }, case well_formed.assert t₁ e hbtwf₁ hhtwf₁ { exact hhtwf₁, }, case well_formed.interp t₁ e ht hbtwf₁ hhtwf₁ { simp [repr], admit, }, case well_formed.lam t₁ k hbtwf₁ { admit }, case well_formed.app t₁ t₂ hbtwf₁ hbtwf₂ { admit }, end end type end ddl.binary
91eb6a89aa0718a8d888745fe9e8dd8eb957466b
5d166a16ae129621cb54ca9dde86c275d7d2b483
/library/init/relator.lean
540dc801dbbe625fe03cb49615361aab50f66598
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
2,810
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl Relator for functions, pairs, sums, and lists. -/ prelude import init.core init.data.basic namespace relator universe variables u₁ u₂ v₁ v₂ reserve infixr ` ⇒ `:40 /- TODO(johoelzl): * should we introduce relators of datatypes as recursive function or as inductive predicate? For now we stick to the recursor approach. * relation lift for datatypes, Π, Σ, set, and subtype types * proof composition and identity laws * implement method to derive relators from datatype -/ section variables {α : Type u₁} {β : Type u₂} {γ : Type v₁} {δ : Type v₂} variables (R : α → β → Prop) (S : γ → δ → Prop) def lift_fun (f : α → γ) (g : β → δ) : Prop := ∀{a b}, R a b → S (f a) (g b) infixr ⇒ := lift_fun end section variables {α : Type u₁} {β : inout Type u₂} (R : inout α → β → Prop) @[class] def right_total := ∀b, ∃a, R a b @[class] def left_total := ∀a, ∃b, R a b @[class] def bi_total := left_total R ∧ right_total R end section variables {α : Type u₁} {β : Type u₂} (R : α → β → Prop) @[class] def left_unique := ∀{a b c}, R a b → R c b → a = c @[class] def right_unique := ∀{a b c}, R a b → R a c → b = c lemma rel_forall_of_right_total [t : right_total R] : ((R ⇒ implies) ⇒ implies) (λp, ∀i, p i) (λq, ∀i, q i) := take p q Hrel H b, exists.elim (t b) (take a Rab, Hrel Rab (H _)) lemma rel_exists_of_left_total [t : left_total R] : ((R ⇒ implies) ⇒ implies) (λp, ∃i, p i) (λq, ∃i, q i) := take p q Hrel ⟨a, pa⟩, let ⟨b, Rab⟩ := t a in ⟨b, Hrel Rab pa⟩ lemma rel_forall_of_total [t : bi_total R] : ((R ⇒ iff) ⇒ iff) (λp, ∀i, p i) (λq, ∀i, q i) := take p q Hrel, ⟨take H b, exists.elim (t.right b) (take a Rab, (Hrel Rab).mp (H _)), take H a, exists.elim (t.left a) (take b Rab, (Hrel Rab).mpr (H _))⟩ lemma rel_exists_of_total [t : bi_total R] : ((R ⇒ iff) ⇒ iff) (λp, ∃i, p i) (λq, ∃i, q i) := take p q Hrel, ⟨take ⟨a, pa⟩, let ⟨b, Rab⟩ := t.left a in ⟨b, (Hrel Rab).1 pa⟩, take ⟨b, qb⟩, let ⟨a, Rab⟩ := t.right b in ⟨a, (Hrel Rab).2 qb⟩⟩ lemma left_unique_of_rel_eq {eq' : β → β → Prop} (he : (R ⇒ (R ⇒ iff)) eq eq') : left_unique R | a b c (ab : R a b) (cb : R c b) := have eq' b b, from iff.mp (he ab ab) rfl, iff.mpr (he ab cb) this end lemma rel_imp : (iff ⇒ (iff ⇒ iff)) implies implies := take p q h r s l, imp_congr h l lemma rel_not : (iff ⇒ iff) not not := take p q h, not_congr h instance bi_total_eq {α : Type u₁} : relator.bi_total (@eq α) := ⟨take a, ⟨a, rfl⟩, take a, ⟨a, rfl⟩⟩ end relator
ed3fb81c55dc3eb40b1d86d21f07fd6accec4e90
f5f7e6fae601a5fe3cac7cc3ed353ed781d62419
/src/category_theory/instances/monoids.lean
7663933ca11bcd1ff0580ae14f2b99510b720812
[ "Apache-2.0" ]
permissive
EdAyers/mathlib
9ecfb2f14bd6caad748b64c9c131befbff0fb4e0
ca5d4c1f16f9c451cf7170b10105d0051db79e1b
refs/heads/master
1,626,189,395,845
1,555,284,396,000
1,555,284,396,000
144,004,030
0
0
Apache-2.0
1,533,727,664,000
1,533,727,663,000
null
UTF-8
Lean
false
false
1,687
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison Introduce Mon -- the category of monoids. Currently only the basic setup. -/ import category_theory.concrete_category import category_theory.fully_faithful universes u v open category_theory namespace category_theory.instances /-- The category of monoids and monoid morphisms. -/ @[reducible] def Mon : Type (u+1) := bundled monoid instance (x : Mon) : monoid x := x.str instance concrete_is_monoid_hom : concrete_category @is_monoid_hom := ⟨by introsI α ia; apply_instance, by introsI α β γ ia ib ic f g hf hg; apply_instance⟩ instance Mon_hom_is_monoid_hom {R S : Mon} (f : R ⟶ S) : is_monoid_hom (f : R → S) := f.2 /-- The category of commutative monoids and monoid morphisms. -/ @[reducible] def CommMon : Type (u+1) := bundled comm_monoid instance (x : CommMon) : comm_monoid x := x.str @[reducible] def is_comm_monoid_hom {α β} [comm_monoid α] [comm_monoid β] (f : α → β) : Prop := is_monoid_hom f instance concrete_is_comm_monoid_hom : concrete_category @is_comm_monoid_hom := ⟨by introsI α ia; apply_instance, by introsI α β γ ia ib ic f g hf hg; apply_instance⟩ instance CommMon_hom_is_comm_monoid_hom {R S : CommMon} (f : R ⟶ S) : is_comm_monoid_hom (f : R → S) := f.2 namespace CommMon /-- The forgetful functor from commutative monoids to monoids. -/ def forget_to_Mon : CommMon ⥤ Mon := concrete_functor (by intros _ c; exact { ..c }) (by introsI _ _ _ _ f i; exact { ..i }) instance : faithful (forget_to_Mon) := {} end CommMon end category_theory.instances
324a174f6e874135b8b1c250ea4ce03fe2269dd6
c61b91f85121053c627318ad8fcde30dfb8637d2
/Chapter3/3-4.lean
65944f6139e604bd2c83352e450808150b4e26b5
[]
no_license
robkorn/theorem-proving-in-lean-exercises
9e2256360eaf6f8df6cdd8fd656e63dfb04c8cdb
9c51da587105ee047a9db55d52709d881a39be7a
refs/heads/master
1,585,403,341,988
1,540,142,619,000
1,540,142,619,000
148,431,678
2
0
null
null
null
null
UTF-8
Lean
false
false
314
lean
variables p q : Prop -- Equivilant example (h : p ∧ q) : q ∧ p := have hp : p, from and.left h, have hq : q, from and.right h, show q ∧ p, from ⟨hq, hp⟩ example (h : p ∧ q) : q ∧ p := have hp : p, from and.left h, suffices hq: q, from and.intro hq hp, show q, from and.right h --
e7e12e1a1a001d47aad98967e4af9fe556fe3bde
35677d2df3f081738fa6b08138e03ee36bc33cad
/test/simp_rw.lean
14e4ba384896686fbe6c727cab835eb362e66c31
[ "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
1,595
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen A set of test cases for the `simp_rw` tactic. -/ import tactic.simp_rw import data.set.basic -- `simp_rw` can perform rewrites under binders: example : (λ (x y : ℕ), x + y) = (λ x y, y + x) := by simp_rw [add_comm] -- `simp_rw` can apply reverse rules: example (f : ℕ → ℕ) {a b c : ℕ} (ha : f b = a) (hc : f b = c) : a = c := by simp_rw [← ha, hc] -- `simp_rw` performs rewrites in the given order (`simp` fails on this example): example {α β : Type} {f : α → β} {t : set β} : (∀ s, f '' s ⊆ t) = ∀ s : set α, ∀ x ∈ s, x ∈ f ⁻¹' t := by simp_rw [set.image_subset_iff, set.subset_def] -- `simp_rw` applies rewrite rules multiple times: example (a b c d : ℕ) : a + (b + (c + d)) = ((d + c) + b) + a := by simp_rw [add_comm] -- `simp_rw` can also rewrite in assumptions: example (p : ℕ → Prop) (a b : ℕ) (h : p (a + b)) : p (b + a) := by {simp_rw [add_comm a b] at h, exact h} -- or explicitly rewrite at the goal: example (p : ℕ → Prop) (a b : ℕ) (h : p (a + b)) : p (b + a) := by {simp_rw [add_comm b a] at ⊢, exact h} -- or at multiple assumptions: example (p : ℕ → Prop) (a b : ℕ) (h₁ : p (b + a) → p (a + b)) (h₂ : p (a + b)) : p (b + a) := by {simp_rw [add_comm a b] at h₁ h₂, exact h₁ h₂} -- or everywhere: example (p : ℕ → Prop) (a b : ℕ) (h₁ : p (b + a) → p (a + b)) (h₂ : p (a + b)) : p (a + b) := by {simp_rw [add_comm a b] at *, exact h₁ h₂}
1d4e5673511f0b784a065de0ea3787373e07acce
c777c32c8e484e195053731103c5e52af26a25d1
/src/number_theory/number_field/canonical_embedding.lean
bdcc13bebd7ef3bd97aa660e0aff0557a8bdbd07
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
7,178
lean
/- Copyright (c) 2022 Xavier Roblot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Xavier Roblot -/ import number_theory.number_field.embeddings /-! # Canonical embedding of a number field The canonical embedding of a number field `K` of signature `(r₁, r₂)` is the ring homomorphism `K →+* ℝ^r₁ × ℂ^r₂` that sends `x ∈ K` to `(φ_₁(x),...,φ_r₁(x)) × (ψ_₁(x),..., ψ_r₂(x))` where `φ_₁,...,φ_r₁` are its real embeddings and `ψ_₁,..., ψ_r₂` are its complex embeddings (up to complex conjugation). ## Main definitions and results * `number_field.canonical_embedding.ring_of_integers.inter_ball_finite`: the intersection of the image of the ring of integers by the canonical embedding and any ball centered at `0` of finite radius is finite. ## Tags number field, infinite places -/ noncomputable theory open function finite_dimensional finset fintype number_field number_field.infinite_place metric module open_locale classical number_field variables (K : Type*) [field K] namespace number_field.canonical_embedding -- The ambient space `ℝ^r₁ × ℂ^r₂` with `(r₁, r₂)` the signature of `K`. localized "notation `E` := ({w : infinite_place K // is_real w} → ℝ) × ({w : infinite_place K // is_complex w} → ℂ)" in canonical_embedding lemma space_rank [number_field K] : finrank ℝ E = finrank ℚ K := begin haveI : module.free ℝ ℂ := infer_instance, rw [finrank_prod, finrank_pi, finrank_pi_fintype, complex.finrank_real_complex, finset.sum_const, finset.card_univ, ← card_real_embeddings, algebra.id.smul_eq_mul, mul_comm, ← card_complex_embeddings, ← number_field.embeddings.card K ℂ, fintype.card_subtype_compl, nat.add_sub_of_le (fintype.card_subtype_le _)], end lemma non_trivial_space [number_field K] : nontrivial E := begin obtain ⟨w⟩ := infinite_place.nonempty K, obtain hw | hw := w.is_real_or_is_complex, { haveI : nonempty {w : infinite_place K // is_real w} := ⟨⟨w, hw⟩⟩, exact nontrivial_prod_left }, { haveI : nonempty {w : infinite_place K // is_complex w} := ⟨⟨w, hw⟩⟩, exact nontrivial_prod_right } end /-- The canonical embedding of a number field `K` of signature `(r₁, r₂)` into `ℝ^r₁ × ℂ^r₂`. -/ def _root_.number_field.canonical_embedding : K →+* E := ring_hom.prod (pi.ring_hom (λ w, w.prop.embedding)) (pi.ring_hom (λ w, w.val.embedding)) lemma _root_.number_field.canonical_embedding_injective [number_field K] : injective (number_field.canonical_embedding K) := @ring_hom.injective _ _ _ _ (non_trivial_space K) _ open number_field variable {K} @[simp] lemma apply_at_real_infinite_place (w : {w : infinite_place K // is_real w}) (x : K) : (number_field.canonical_embedding K x).1 w = w.prop.embedding x := by simp only [canonical_embedding, ring_hom.prod_apply, pi.ring_hom_apply] @[simp] lemma apply_at_complex_infinite_place (w : { w : infinite_place K // is_complex w}) (x : K) : (number_field.canonical_embedding K x).2 w = embedding w.val x := by simp only [canonical_embedding, ring_hom.prod_apply, pi.ring_hom_apply] lemma nnnorm_eq [number_field K] (x : K) : ‖canonical_embedding K x‖₊ = finset.univ.sup (λ w : infinite_place K, ⟨w x, map_nonneg w x⟩) := begin rw [prod.nnnorm_def', pi.nnnorm_def, pi.nnnorm_def], rw ( _ : finset.univ = {w : infinite_place K | is_real w}.to_finset ∪ {w : infinite_place K | is_complex w}.to_finset), { rw [finset.sup_union, sup_eq_max], refine congr_arg2 _ _ _, { convert (finset.univ.sup_map (function.embedding.subtype (λ w : infinite_place K, is_real w)) (λ w, (⟨w x, map_nonneg w x⟩ : nnreal))).symm using 2, ext w, simp only [apply_at_real_infinite_place, coe_nnnorm, real.norm_eq_abs, function.embedding.coe_subtype, subtype.coe_mk, is_real.abs_embedding_apply], }, { convert (finset.univ.sup_map (function.embedding.subtype (λ w : infinite_place K, is_complex w)) (λ w, (⟨w x, map_nonneg w x⟩ : nnreal))).symm using 2, ext w, simp only [apply_at_complex_infinite_place, subtype.val_eq_coe, coe_nnnorm, complex.norm_eq_abs, function.embedding.coe_subtype, subtype.coe_mk, abs_embedding], }}, { ext w, simp only [w.is_real_or_is_complex, set.mem_set_of_eq, finset.mem_union, set.mem_to_finset, finset.mem_univ], }, end lemma norm_le_iff [number_field K] (x : K) (r : ℝ) : ‖canonical_embedding K x‖ ≤ r ↔ ∀ w : infinite_place K, w x ≤ r := begin obtain hr | hr := lt_or_le r 0, { obtain ⟨w⟩ := infinite_place.nonempty K, exact iff_of_false (hr.trans_le $ norm_nonneg _).not_le (λ h, hr.not_le $ (map_nonneg w _).trans $ h _) }, { lift r to nnreal using hr, simp_rw [← coe_nnnorm, nnnorm_eq, nnreal.coe_le_coe, finset.sup_le_iff, finset.mem_univ, forall_true_left, ←nnreal.coe_le_coe, subtype.coe_mk] } end variables (K) /-- The image of `𝓞 K` as a subring of `ℝ^r₁ × ℂ^r₂`. -/ def integer_lattice : subring E := (ring_hom.range (algebra_map (𝓞 K) K)).map (canonical_embedding K) /-- The linear equiv between `𝓞 K` and the integer lattice. -/ def equiv_integer_lattice [number_field K] : 𝓞 K ≃ₗ[ℤ] integer_lattice K := linear_equiv.of_bijective { to_fun := λ x, ⟨canonical_embedding K (algebra_map (𝓞 K) K x), algebra_map (𝓞 K) K x, by simp only [subring.mem_carrier, ring_hom.mem_range, exists_apply_eq_apply], rfl⟩, map_add' := λ x y, by simpa only [map_add], map_smul' := λ c x, by simpa only [zsmul_eq_mul, map_mul, map_int_cast] } begin refine ⟨λ _ _ h, _, λ ⟨_, _, ⟨a, rfl⟩, rfl⟩, ⟨a, rfl⟩⟩, rw [linear_map.coe_mk, subtype.mk_eq_mk] at h, exact is_fraction_ring.injective (𝓞 K) K (canonical_embedding_injective K h), end lemma integer_lattice.inter_ball_finite [number_field K] (r : ℝ) : ((integer_lattice K : set E) ∩ (closed_ball 0 r)).finite := begin obtain hr | hr := lt_or_le r 0, { simp [closed_ball_eq_empty.2 hr] }, have heq : ∀ x, canonical_embedding K x ∈ closed_ball (0 : E) r ↔ ∀ φ : K →+* ℂ, ‖φ x‖ ≤ r, { simp only [← place_apply, ← infinite_place.coe_mk, mem_closed_ball_zero_iff, norm_le_iff], exact λ x, le_iff_le x r, }, convert (embeddings.finite_of_norm_le K ℂ r).image (canonical_embedding K), ext, split, { rintro ⟨⟨_, ⟨x, rfl⟩, rfl⟩, hx2⟩, exact ⟨x, ⟨set_like.coe_mem x, (heq x).mp hx2⟩, rfl⟩, }, { rintro ⟨x, ⟨hx1, hx2⟩, rfl⟩, exact ⟨⟨x, ⟨⟨x, hx1⟩, rfl⟩, rfl⟩, (heq x).mpr hx2⟩, } end instance [number_field K] : countable (integer_lattice K) := begin have : (⋃ n : ℕ, ((integer_lattice K : set E) ∩ (closed_ball 0 n))).countable, { exact set.countable_Union (λ n, (integer_lattice.inter_ball_finite K n).countable) }, refine (this.mono _).to_subtype, rintro _ ⟨x, hx, rfl⟩, rw set.mem_Union, exact ⟨⌈‖canonical_embedding K x‖⌉₊, ⟨x, hx, rfl⟩, mem_closed_ball_zero_iff.2 (nat.le_ceil _)⟩, end end number_field.canonical_embedding
f42dd1b307932a365c548b8ef283d3a6e0064015
680b0d1592ce164979dab866b232f6fa743f2cc8
/library/theories/analysis/normed_space.lean
c8612cfa4f491c3f48ba2f41b61a76cc512546da
[ "Apache-2.0" ]
permissive
syohex/lean
657428ab520f8277fc18cf04bea2ad200dbae782
081ad1212b686780f3ff8a6d0e5f8a1d29a7d8bc
refs/heads/master
1,611,274,838,635
1,452,668,188,000
1,452,668,188,000
49,562,028
0
0
null
1,452,675,604,000
1,452,675,602,000
null
UTF-8
Lean
false
false
4,284
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad Normed spaces. -/ import algebra.module .real_limit open real noncomputable theory structure has_norm [class] (M : Type) : Type := (norm : M → ℝ) definition norm {M : Type} [has_normM : has_norm M] (v : M) : ℝ := has_norm.norm v notation `∥`v`∥` := norm v -- where is the right place to put this? structure real_vector_space [class] (V : Type) extends vector_space ℝ V structure normed_vector_space [class] (V : Type) extends real_vector_space V, has_norm V := (norm_zero : norm zero = 0) (eq_zero_of_norm_eq_zero : ∀ u : V, norm u = 0 → u = zero) (norm_triangle : ∀ u v, norm (add u v) ≤ norm u + norm v) (norm_smul : ∀ (a : ℝ) (v : V), norm (smul a v) = abs a * norm v) -- what namespace should we put this in? section normed_vector_space variable {V : Type} variable [normed_vector_space V] proposition norm_zero : ∥ (0 : V) ∥ = 0 := !normed_vector_space.norm_zero proposition eq_zero_of_norm_eq_zero {u : V} (H : ∥ u ∥ = 0) : u = 0 := !normed_vector_space.eq_zero_of_norm_eq_zero H proposition norm_triangle (u v : V) : ∥ u + v ∥ ≤ ∥ u ∥ + ∥ v ∥ := !normed_vector_space.norm_triangle proposition norm_smul (a : ℝ) (v : V) : ∥ a • v ∥ = abs a * ∥ v ∥ := !normed_vector_space.norm_smul proposition norm_neg (v : V) : ∥ -v ∥ = ∥ v ∥ := have abs (1 : ℝ) = 1, from abs_of_nonneg zero_le_one, by+ rewrite [-@neg_one_smul ℝ V, norm_smul, abs_neg, this, one_mul] section private definition nvs_dist (u v : V) := ∥ u - v ∥ private lemma nvs_dist_self (u : V) : nvs_dist u u = 0 := by rewrite [↑nvs_dist, sub_self, norm_zero] private lemma eq_of_nvs_dist_eq_zero (u v : V) (H : nvs_dist u v = 0) : u = v := have u - v = 0, from eq_zero_of_norm_eq_zero H, eq_of_sub_eq_zero this private lemma nvs_dist_triangle (u v w : V) : nvs_dist u w ≤ nvs_dist u v + nvs_dist v w := calc nvs_dist u w = ∥ (u - v) + (v - w) ∥ : by rewrite [↑nvs_dist, *sub_eq_add_neg, add.assoc, neg_add_cancel_left] ... ≤ ∥ u - v ∥ + ∥ v - w ∥ : norm_triangle private lemma nvs_dist_comm (u v : V) : nvs_dist u v = nvs_dist v u := by rewrite [↑nvs_dist, -norm_neg, neg_sub] end definition normed_vector_space_to_metric_space [reducible] [trans_instance] : metric_space V := ⦃ metric_space, dist := nvs_dist, dist_self := nvs_dist_self, eq_of_dist_eq_zero := eq_of_nvs_dist_eq_zero, dist_comm := nvs_dist_comm, dist_triangle := nvs_dist_triangle ⦄ end normed_vector_space structure banach_space [class] (V : Type) extends nvsV : normed_vector_space V := (complete : ∀ X, @metric_space.cauchy V (@normed_vector_space_to_metric_space V nvsV) X → @metric_space.converges_seq V (@normed_vector_space_to_metric_space V nvsV) X) definition banach_space_to_metric_space [reducible] [trans_instance] (V : Type) [bsV : banach_space V] : complete_metric_space V := ⦃ complete_metric_space, normed_vector_space_to_metric_space, complete := banach_space.complete ⦄ section open metric_space example (V : Type) (vsV : banach_space V) (X : ℕ → V) (H : cauchy X) : converges_seq X := complete V H end /- the real numbers themselves can be viewed as a banach space -/ definition real_is_real_vector_space [trans_instance] [reducible] : real_vector_space ℝ := ⦃ real_vector_space, real.discrete_linear_ordered_field, smul := mul, smul_left_distrib := left_distrib, smul_right_distrib := right_distrib, smul_mul := mul.assoc, one_smul := one_mul ⦄ definition real_is_banach_space [trans_instance] [reducible] : banach_space ℝ := ⦃ banach_space, real_is_real_vector_space, norm := abs, norm_zero := abs_zero, eq_zero_of_norm_eq_zero := λ a H, eq_zero_of_abs_eq_zero H, norm_triangle := abs_add_le_abs_add_abs, norm_smul := abs_mul, complete := λ X H, complete ℝ H ⦄
0f13e6a6725fe8e2a4d23ae8db1d5ef481719f94
08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4
/src/Lean/Elab/MutualDef.lean
522c15719f7a35fefaa98b6b0e13ab5e2cbf47a9
[ "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", "Apache-2.0", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
gebner/lean4
d51c4922640a52a6f7426536ea669ef18a1d9af5
8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f
refs/heads/master
1,685,732,780,391
1,672,962,627,000
1,673,459,398,000
373,307,283
0
0
Apache-2.0
1,691,316,730,000
1,622,669,271,000
Lean
UTF-8
Lean
false
false
39,451
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Parser.Term import Lean.Meta.Closure import Lean.Meta.Check import Lean.Meta.Transform import Lean.PrettyPrinter.Delaborator.Options import Lean.Elab.Command import Lean.Elab.Match import Lean.Elab.DefView import Lean.Elab.Deriving.Basic import Lean.Elab.PreDefinition.Main import Lean.Elab.DeclarationRange namespace Lean.Elab open Lean.Parser.Term /-- `DefView` after elaborating the header. -/ structure DefViewElabHeader where ref : Syntax modifiers : Modifiers /-- Stores whether this is the header of a definition, theorem, ... -/ kind : DefKind /-- Short name. Recall that all declarations in Lean 4 are potentially recursive. We use `shortDeclName` to refer to them at `valueStx`, and other declarations in the same mutual block. -/ shortDeclName : Name /-- Full name for this declaration. This is the name that will be added to the `Environment`. -/ declName : Name /-- Universe level parameter names explicitly provided by the user. -/ levelNames : List Name /-- Syntax objects for the binders occurring befor `:`, we use them to populate the `InfoTree` when elaborating `valueStx`. -/ binderIds : Array Syntax /-- Number of parameters before `:`, it also includes auto-implicit parameters automatically added by Lean. -/ numParams : Nat /-- Type including parameters. -/ type : Expr /-- `Syntax` object the body/value of the definition. -/ valueStx : Syntax deriving Inhabited namespace Term open Meta private def checkModifiers (m₁ m₂ : Modifiers) : TermElabM Unit := do unless m₁.isUnsafe == m₂.isUnsafe do throwError "cannot mix unsafe and safe definitions" unless m₁.isNoncomputable == m₂.isNoncomputable do throwError "cannot mix computable and non-computable definitions" unless m₁.isPartial == m₂.isPartial do throwError "cannot mix partial and non-partial definitions" private def checkKinds (k₁ k₂ : DefKind) : TermElabM Unit := do unless k₁.isExample == k₂.isExample do throwError "cannot mix examples and definitions" -- Reason: we should discard examples unless k₁.isTheorem == k₂.isTheorem do throwError "cannot mix theorems and definitions" -- Reason: we will eventually elaborate theorems in `Task`s. private def check (prevHeaders : Array DefViewElabHeader) (newHeader : DefViewElabHeader) : TermElabM Unit := do if newHeader.kind.isTheorem && newHeader.modifiers.isUnsafe then throwError "'unsafe' theorems are not allowed" if newHeader.kind.isTheorem && newHeader.modifiers.isPartial then throwError "'partial' theorems are not allowed, 'partial' is a code generation directive" if newHeader.kind.isTheorem && newHeader.modifiers.isNoncomputable then throwError "'theorem' subsumes 'noncomputable', code is not generated for theorems" if newHeader.modifiers.isNoncomputable && newHeader.modifiers.isUnsafe then throwError "'noncomputable unsafe' is not allowed" if newHeader.modifiers.isNoncomputable && newHeader.modifiers.isPartial then throwError "'noncomputable partial' is not allowed" if newHeader.modifiers.isPartial && newHeader.modifiers.isUnsafe then throwError "'unsafe' subsumes 'partial'" if h : 0 < prevHeaders.size then let firstHeader := prevHeaders.get ⟨0, h⟩ try unless newHeader.levelNames == firstHeader.levelNames do throwError "universe parameters mismatch" checkModifiers newHeader.modifiers firstHeader.modifiers checkKinds newHeader.kind firstHeader.kind catch | .error ref msg => throw (.error ref m!"invalid mutually recursive definitions, {msg}") | ex => throw ex else pure () private def registerFailedToInferDefTypeInfo (type : Expr) (ref : Syntax) : TermElabM Unit := registerCustomErrorIfMVar type ref "failed to infer definition type" /-- Return `some [b, c]` if the given `views` are representing a declaration of the form ``` opaque a b c : Nat ``` -/ private def isMultiConstant? (views : Array DefView) : Option (List Name) := if views.size == 1 && views[0]!.kind == .opaque && views[0]!.binders.getArgs.size > 0 && views[0]!.binders.getArgs.all (·.isIdent) then some (views[0]!.binders.getArgs.toList.map (·.getId)) else none private def getPendindMVarErrorMessage (views : Array DefView) : String := match isMultiConstant? views with | some ids => let idsStr := ", ".intercalate <| ids.map fun id => s!"`{id}`" let paramsStr := ", ".intercalate <| ids.map fun id => s!"`({id} : _)`" s!"\nrecall that you cannot declare multiple constants in a single declaration. The identifier(s) {idsStr} are being interpreted as parameters {paramsStr}" | none => "\nwhen the resulting type of a declaration is explicitly provided, all holes (e.g., `_`) in the header are resolved before the declaration body is processed" /-- Convert terms of the form `OfNat <type> (OfNat.ofNat Nat <num> ..)` into `OfNat <type> <num>`. We use this method on instance declaration types. The motivation is to address a recurrent mistake when users forget to use `nat_lit` when declaring `OfNat` instances. See issues #1389 and #875 -/ private def cleanupOfNat (type : Expr) : MetaM Expr := do Meta.transform type fun e => do if !e.isAppOfArity ``OfNat 2 then return .continue let arg ← instantiateMVars e.appArg! if !arg.isAppOfArity ``OfNat.ofNat 3 then return .continue let argArgs := arg.getAppArgs if !argArgs[0]!.isConstOf ``Nat then return .continue let eNew := mkApp e.appFn! argArgs[1]! return .done eNew /-- Elaborate only the declaration headers. We have to elaborate the headers first because we support mutually recursive declarations in Lean 4. -/ private def elabHeaders (views : Array DefView) : TermElabM (Array DefViewElabHeader) := do let expandedDeclIds ← views.mapM fun view => withRef view.ref do Term.expandDeclId (← getCurrNamespace) (← getLevelNames) view.declId view.modifiers withAutoBoundImplicitForbiddenPred (fun n => expandedDeclIds.any (·.shortName == n)) do let mut headers := #[] for view in views, ⟨shortDeclName, declName, levelNames⟩ in expandedDeclIds do let newHeader ← withRef view.ref do addDeclarationRanges declName view.ref applyAttributesAt declName view.modifiers.attrs .beforeElaboration withDeclName declName <| withAutoBoundImplicit <| withLevelNames levelNames <| elabBindersEx view.binders.getArgs fun xs => do let refForElabFunType := view.value let mut type ← match view.type? with | some typeStx => let type ← elabType typeStx registerFailedToInferDefTypeInfo type typeStx pure type | none => let hole := mkHole refForElabFunType let type ← elabType hole trace[Elab.definition] ">> type: {type}\n{type.mvarId!}" registerFailedToInferDefTypeInfo type refForElabFunType pure type Term.synthesizeSyntheticMVarsNoPostponing if view.isInstance then type ← cleanupOfNat type let (binderIds, xs) := xs.unzip -- TODO: add forbidden predicate using `shortDeclName` from `views` let xs ← addAutoBoundImplicits xs type ← mkForallFVars' xs type type ← instantiateMVars type let levelNames ← getLevelNames if view.type?.isSome then let pendingMVarIds ← getMVars type discard <| logUnassignedUsingErrorInfos pendingMVarIds <| getPendindMVarErrorMessage views let newHeader := { ref := view.ref modifiers := view.modifiers kind := view.kind shortDeclName := shortDeclName declName, type, levelNames, binderIds numParams := xs.size valueStx := view.value : DefViewElabHeader } check headers newHeader return newHeader headers := headers.push newHeader return headers /-- Create auxiliary local declarations `fs` for the given hearders using their `shortDeclName` and `type`, given hearders, and execute `k fs`. The new free variables are tagged as `auxDecl`. Remark: `fs.size = headers.size`. -/ private partial def withFunLocalDecls {α} (headers : Array DefViewElabHeader) (k : Array Expr → TermElabM α) : TermElabM α := let rec loop (i : Nat) (fvars : Array Expr) := do if h : i < headers.size then let header := headers.get ⟨i, h⟩ if header.modifiers.isNonrec then loop (i+1) fvars else withAuxDecl header.shortDeclName header.type header.declName fun fvar => loop (i+1) (fvars.push fvar) else k fvars loop 0 #[] private def expandWhereStructInst : Macro | `(Parser.Command.whereStructInst|where $[$decls:letDecl];* $[$whereDecls?:whereDecls]?) => do let letIdDecls ← decls.mapM fun stx => match stx with | `(letDecl|$_decl:letPatDecl) => Macro.throwErrorAt stx "patterns are not allowed here" | `(letDecl|$decl:letEqnsDecl) => expandLetEqnsDecl decl (useExplicit := false) | `(letDecl|$decl:letIdDecl) => pure decl | _ => Macro.throwUnsupported let structInstFields ← letIdDecls.mapM fun | stx@`(letIdDecl|$id:ident $binders* $[: $ty?]? := $val) => withRef stx do let mut val := val if let some ty := ty? then val ← `(($val : $ty)) -- HACK: this produces invalid syntax, but the fun elaborator supports letIdBinders as well have : Coe (TSyntax ``letIdBinder) (TSyntax ``funBinder) := ⟨(⟨·⟩)⟩ val ← if binders.size > 0 then `(fun $binders* => $val) else pure val `(structInstField|$id:ident := $val) | _ => Macro.throwUnsupported let body ← `({ $structInstFields,* }) match whereDecls? with | some whereDecls => expandWhereDecls whereDecls body | none => return body | _ => Macro.throwUnsupported /- Recall that ``` def declValSimple := leading_parser " :=\n" >> termParser >> optional Term.whereDecls def declValEqns := leading_parser Term.matchAltsWhereDecls def declVal := declValSimple <|> declValEqns <|> Term.whereDecls ``` -/ private def declValToTerm (declVal : Syntax) : MacroM Syntax := withRef declVal do if declVal.isOfKind ``Parser.Command.declValSimple then expandWhereDeclsOpt declVal[2] declVal[1] else if declVal.isOfKind ``Parser.Command.declValEqns then expandMatchAltsWhereDecls declVal[0] else if declVal.isOfKind ``Parser.Command.whereStructInst then expandWhereStructInst declVal else if declVal.isMissing then Macro.throwErrorAt declVal "declaration body is missing" else Macro.throwErrorAt declVal "unexpected declaration body" private def elabFunValues (headers : Array DefViewElabHeader) : TermElabM (Array Expr) := headers.mapM fun header => withDeclName header.declName <| withLevelNames header.levelNames do let valStx ← liftMacroM <| declValToTerm header.valueStx forallBoundedTelescope header.type header.numParams fun xs type => do -- Add new info nodes for new fvars. The server will detect all fvars of a binder by the binder's source location. for i in [0:header.binderIds.size] do -- skip auto-bound prefix in `xs` addLocalVarInfo header.binderIds[i]! xs[header.numParams - header.binderIds.size + i]! let val ← elabTermEnsuringType valStx type mkLambdaFVars xs val private def collectUsed (headers : Array DefViewElabHeader) (values : Array Expr) (toLift : List LetRecToLift) : StateRefT CollectFVars.State MetaM Unit := do headers.forM fun header => header.type.collectFVars values.forM fun val => val.collectFVars toLift.forM fun letRecToLift => do letRecToLift.type.collectFVars letRecToLift.val.collectFVars private def removeUnusedVars (vars : Array Expr) (headers : Array DefViewElabHeader) (values : Array Expr) (toLift : List LetRecToLift) : TermElabM (LocalContext × LocalInstances × Array Expr) := do let (_, used) ← (collectUsed headers values toLift).run {} removeUnused vars used private def withUsed {α} (vars : Array Expr) (headers : Array DefViewElabHeader) (values : Array Expr) (toLift : List LetRecToLift) (k : Array Expr → TermElabM α) : TermElabM α := do let (lctx, localInsts, vars) ← removeUnusedVars vars headers values toLift withLCtx lctx localInsts <| k vars private def isExample (views : Array DefView) : Bool := views.any (·.kind.isExample) private def isTheorem (views : Array DefView) : Bool := views.any (·.kind.isTheorem) private def instantiateMVarsAtHeader (header : DefViewElabHeader) : TermElabM DefViewElabHeader := do let type ← instantiateMVars header.type pure { header with type := type } private def instantiateMVarsAtLetRecToLift (toLift : LetRecToLift) : TermElabM LetRecToLift := do let type ← instantiateMVars toLift.type let val ← instantiateMVars toLift.val pure { toLift with type, val } private def typeHasRecFun (type : Expr) (funFVars : Array Expr) (letRecsToLift : List LetRecToLift) : Option FVarId := let occ? := type.find? fun e => match e with | Expr.fvar fvarId => funFVars.contains e || letRecsToLift.any fun toLift => toLift.fvarId == fvarId | _ => false match occ? with | some (Expr.fvar fvarId) => some fvarId | _ => none private def getFunName (fvarId : FVarId) (letRecsToLift : List LetRecToLift) : TermElabM Name := do match (← fvarId.findDecl?) with | some decl => return decl.userName | none => /- Recall that the FVarId of nested let-recs are not in the current local context. -/ match letRecsToLift.findSome? fun toLift => if toLift.fvarId == fvarId then some toLift.shortDeclName else none with | none => throwError "unknown function" | some n => return n /-- Ensures that the of let-rec definition types do not contain functions being defined. In principle, this test can be improved. We could perform it after we separate the set of functions is strongly connected components. However, this extra complication doesn't seem worth it. -/ private def checkLetRecsToLiftTypes (funVars : Array Expr) (letRecsToLift : List LetRecToLift) : TermElabM Unit := letRecsToLift.forM fun toLift => match typeHasRecFun toLift.type funVars letRecsToLift with | none => pure () | some fvarId => do let fnName ← getFunName fvarId letRecsToLift throwErrorAt toLift.ref "invalid type in 'let rec', it uses '{fnName}' which is being defined simultaneously" namespace MutualClosure /-- A mapping from FVarId to Set of FVarIds. -/ abbrev UsedFVarsMap := FVarIdMap FVarIdSet /-- Create the `UsedFVarsMap` mapping that takes the variable id for the mutually recursive functions being defined to the set of free variables in its definition. For `mainFVars`, this is just the set of section variables `sectionVars` used. For nested let-rec functions, we collect their free variables. Recall that a `let rec` expressions are encoded as follows in the elaborator. ```lean let rec f : A := t, g : B := s; body ``` is encoded as ```lean let f : A := ?m₁; let g : B := ?m₂; body ``` where `?m₁` and `?m₂` are synthetic opaque metavariables. That are assigned by this module. We may have nested `let rec`s. ```lean let rec f : A := let rec g : B := t; s; body ``` is encoded as ```lean let f : A := ?m₁; body ``` and the body of `f` is stored the field `val` of a `LetRecToLift`. For the example above, we would have a `LetRecToLift` containing: ``` { mvarId := m₁, val := `(let g : B := ?m₂; body) ... } ``` Note that `g` is not a free variable at `(let g : B := ?m₂; body)`. We recover the fact that `f` depends on `g` because it contains `m₂` -/ private def mkInitialUsedFVarsMap [Monad m] [MonadMCtx m] (sectionVars : Array Expr) (mainFVarIds : Array FVarId) (letRecsToLift : Array LetRecToLift) : m UsedFVarsMap := do let mut sectionVarSet := {} for var in sectionVars do sectionVarSet := sectionVarSet.insert var.fvarId! let mut usedFVarMap := {} for mainFVarId in mainFVarIds do usedFVarMap := usedFVarMap.insert mainFVarId sectionVarSet for toLift in letRecsToLift do let state := Lean.collectFVars {} toLift.val let state := Lean.collectFVars state toLift.type let mut set := state.fvarSet /- toLift.val may contain metavariables that are placeholders for nested let-recs. We should collect the fvarId for the associated let-rec because we need this information to compute the fixpoint later. -/ let mvarIds := (toLift.val.collectMVars {}).result for mvarId in mvarIds do match (← letRecsToLift.findSomeM? fun (toLift : LetRecToLift) => return if toLift.mvarId == (← getDelayedMVarRoot mvarId) then some toLift.fvarId else none) with | some fvarId => set := set.insert fvarId | none => pure () usedFVarMap := usedFVarMap.insert toLift.fvarId set return usedFVarMap /-! The let-recs may invoke each other. Example: ``` let rec f (x : Nat) := g x + y g : Nat → Nat | 0 => 1 | x+1 => f x + z ``` `y` is free variable in `f`, and `z` is a free variable in `g`. To close `f` and `g`, `y` and `z` must be in the closure of both. That is, we need to generate the top-level definitions. ``` def f (y z x : Nat) := g y z x + y def g (y z : Nat) : Nat → Nat | 0 => 1 | x+1 => f y z x + z ``` -/ namespace FixPoint structure State where usedFVarsMap : UsedFVarsMap := {} modified : Bool := false abbrev M := ReaderT (Array FVarId) $ StateM State private def isModified : M Bool := do pure (← get).modified private def resetModified : M Unit := modify fun s => { s with modified := false } private def markModified : M Unit := modify fun s => { s with modified := true } private def getUsedFVarsMap : M UsedFVarsMap := do pure (← get).usedFVarsMap private def modifyUsedFVars (f : UsedFVarsMap → UsedFVarsMap) : M Unit := modify fun s => { s with usedFVarsMap := f s.usedFVarsMap } -- merge s₂ into s₁ private def merge (s₁ s₂ : FVarIdSet) : M FVarIdSet := s₂.foldM (init := s₁) fun s₁ k => do if s₁.contains k then return s₁ else markModified return s₁.insert k private def updateUsedVarsOf (fvarId : FVarId) : M Unit := do let usedFVarsMap ← getUsedFVarsMap match usedFVarsMap.find? fvarId with | none => return () | some fvarIds => let fvarIdsNew ← fvarIds.foldM (init := fvarIds) fun fvarIdsNew fvarId' => do if fvarId == fvarId' then return fvarIdsNew else match usedFVarsMap.find? fvarId' with | none => return fvarIdsNew /- We are being sloppy here `otherFVarIds` may contain free variables that are not in the context of the let-rec associated with fvarId. We filter these out-of-context free variables later. -/ | some otherFVarIds => merge fvarIdsNew otherFVarIds modifyUsedFVars fun usedFVars => usedFVars.insert fvarId fvarIdsNew private partial def fixpoint : Unit → M Unit | _ => do resetModified let letRecFVarIds ← read letRecFVarIds.forM updateUsedVarsOf if (← isModified) then fixpoint () def run (letRecFVarIds : Array FVarId) (usedFVarsMap : UsedFVarsMap) : UsedFVarsMap := let (_, s) := fixpoint () |>.run letRecFVarIds |>.run { usedFVarsMap := usedFVarsMap } s.usedFVarsMap end FixPoint abbrev FreeVarMap := FVarIdMap (Array FVarId) private def mkFreeVarMap [Monad m] [MonadMCtx m] (sectionVars : Array Expr) (mainFVarIds : Array FVarId) (recFVarIds : Array FVarId) (letRecsToLift : Array LetRecToLift) : m FreeVarMap := do let usedFVarsMap ← mkInitialUsedFVarsMap sectionVars mainFVarIds letRecsToLift let letRecFVarIds := letRecsToLift.map fun toLift => toLift.fvarId let usedFVarsMap := FixPoint.run letRecFVarIds usedFVarsMap let mut freeVarMap := {} for toLift in letRecsToLift do let lctx := toLift.lctx let fvarIdsSet := usedFVarsMap.find? toLift.fvarId |>.get! let fvarIds := fvarIdsSet.fold (init := #[]) fun fvarIds fvarId => if lctx.contains fvarId && !recFVarIds.contains fvarId then fvarIds.push fvarId else fvarIds freeVarMap := freeVarMap.insert toLift.fvarId fvarIds return freeVarMap structure ClosureState where newLocalDecls : Array LocalDecl := #[] localDecls : Array LocalDecl := #[] newLetDecls : Array LocalDecl := #[] exprArgs : Array Expr := #[] private def pickMaxFVar? (lctx : LocalContext) (fvarIds : Array FVarId) : Option FVarId := fvarIds.getMax? fun fvarId₁ fvarId₂ => (lctx.get! fvarId₁).index < (lctx.get! fvarId₂).index private def preprocess (e : Expr) : TermElabM Expr := do let e ← instantiateMVars e -- which let-decls are dependent. We say a let-decl is dependent if its lambda abstraction is type incorrect. Meta.check e pure e /-- Push free variables in `s` to `toProcess` if they are not already there. -/ private def pushNewVars (toProcess : Array FVarId) (s : CollectFVars.State) : Array FVarId := s.fvarSet.fold (init := toProcess) fun toProcess fvarId => if toProcess.contains fvarId then toProcess else toProcess.push fvarId private def pushLocalDecl (toProcess : Array FVarId) (fvarId : FVarId) (userName : Name) (type : Expr) (bi : BinderInfo) (kind : LocalDeclKind) : StateRefT ClosureState TermElabM (Array FVarId) := do let type ← preprocess type modify fun s => { s with newLocalDecls := s.newLocalDecls.push <| LocalDecl.cdecl default fvarId userName type bi kind exprArgs := s.exprArgs.push (mkFVar fvarId) } return pushNewVars toProcess (collectFVars {} type) private partial def mkClosureForAux (toProcess : Array FVarId) : StateRefT ClosureState TermElabM Unit := do let lctx ← getLCtx match pickMaxFVar? lctx toProcess with | none => return () | some fvarId => trace[Elab.definition.mkClosure] "toProcess: {toProcess.map mkFVar}, maxVar: {mkFVar fvarId}" let toProcess := toProcess.erase fvarId let localDecl ← fvarId.getDecl match localDecl with | .cdecl _ _ userName type bi k => let toProcess ← pushLocalDecl toProcess fvarId userName type bi k mkClosureForAux toProcess | .ldecl _ _ userName type val _ k => let zetaFVarIds ← getZetaFVarIds if !zetaFVarIds.contains fvarId then /- Non-dependent let-decl. See comment at src/Lean/Meta/Closure.lean -/ let toProcess ← pushLocalDecl toProcess fvarId userName type .default k mkClosureForAux toProcess else /- Dependent let-decl. -/ let type ← preprocess type let val ← preprocess val modify fun s => { s with newLetDecls := s.newLetDecls.push <| .ldecl default fvarId userName type val false k, /- We don't want to interleave let and lambda declarations in our closure. So, we expand any occurrences of fvarId at `newLocalDecls` and `localDecls` -/ newLocalDecls := s.newLocalDecls.map (·.replaceFVarId fvarId val) localDecls := s.localDecls.map (·.replaceFVarId fvarId val) } mkClosureForAux (pushNewVars toProcess (collectFVars (collectFVars {} type) val)) private partial def mkClosureFor (freeVars : Array FVarId) (localDecls : Array LocalDecl) : TermElabM ClosureState := do let (_, s) ← mkClosureForAux freeVars |>.run { localDecls := localDecls } return { s with newLocalDecls := s.newLocalDecls.reverse newLetDecls := s.newLetDecls.reverse exprArgs := s.exprArgs.reverse } structure LetRecClosure where ref : Syntax localDecls : Array LocalDecl /-- Expression used to replace occurrences of the let-rec `FVarId`. -/ closed : Expr toLift : LetRecToLift private def mkLetRecClosureFor (toLift : LetRecToLift) (freeVars : Array FVarId) : TermElabM LetRecClosure := do let lctx := toLift.lctx withLCtx lctx toLift.localInstances do lambdaTelescope toLift.val fun xs val => do /- Recall that `toLift.type` and `toLift.value` may have different binder annotations. See issue #1377 for an example. -/ let userNameAndBinderInfos ← forallBoundedTelescope toLift.type xs.size fun xs _ => xs.mapM fun x => do let localDecl ← x.fvarId!.getDecl return (localDecl.userName, localDecl.binderInfo) /- Auxiliary map for preserving binder user-facing names and `BinderInfo` for types. -/ let mut userNameBinderInfoMap : FVarIdMap (Name × BinderInfo) := {} for x in xs, (userName, bi) in userNameAndBinderInfos do userNameBinderInfoMap := userNameBinderInfoMap.insert x.fvarId! (userName, bi) let type ← instantiateForall toLift.type xs let lctx ← getLCtx let s ← mkClosureFor freeVars <| xs.map fun x => lctx.get! x.fvarId! /- Apply original type binder info and user-facing names to local declarations. -/ let typeLocalDecls := s.localDecls.map fun localDecl => if let some (userName, bi) := userNameBinderInfoMap.find? localDecl.fvarId then localDecl.setBinderInfo bi |>.setUserName userName else localDecl let type := Closure.mkForall typeLocalDecls <| Closure.mkForall s.newLetDecls type let val := Closure.mkLambda s.localDecls <| Closure.mkLambda s.newLetDecls val let c := mkAppN (Lean.mkConst toLift.declName) s.exprArgs toLift.mvarId.assign c return { ref := toLift.ref localDecls := s.newLocalDecls closed := c toLift := { toLift with val, type } } private def mkLetRecClosures (sectionVars : Array Expr) (mainFVarIds : Array FVarId) (recFVarIds : Array FVarId) (letRecsToLift : Array LetRecToLift) : TermElabM (List LetRecClosure) := do -- Compute the set of free variables (excluding `recFVarIds`) for each let-rec. let mut letRecsToLift := letRecsToLift let mut freeVarMap ← mkFreeVarMap sectionVars mainFVarIds recFVarIds letRecsToLift let mut result := #[] for i in [:letRecsToLift.size] do if letRecsToLift[i]!.val.hasExprMVar then -- This can happen when this particular let-rec has nested let-rec that have been resolved in previous iterations. -- This code relies on the fact that nested let-recs occur before the outer most let-recs at `letRecsToLift`. -- Unresolved nested let-recs appear as metavariables before they are resolved. See `assignExprMVar` at `mkLetRecClosureFor` let valNew ← instantiateMVars letRecsToLift[i]!.val letRecsToLift := letRecsToLift.modify i fun t => { t with val := valNew } -- We have to recompute the `freeVarMap` in this case. This overhead should not be an issue in practice. freeVarMap ← mkFreeVarMap sectionVars mainFVarIds recFVarIds letRecsToLift let toLift := letRecsToLift[i]! result := result.push (← mkLetRecClosureFor toLift (freeVarMap.find? toLift.fvarId).get!) return result.toList /-- Mapping from FVarId of mutually recursive functions being defined to "closure" expression. -/ abbrev Replacement := FVarIdMap Expr def insertReplacementForMainFns (r : Replacement) (sectionVars : Array Expr) (mainHeaders : Array DefViewElabHeader) (mainFVars : Array Expr) : Replacement := mainFVars.size.fold (init := r) fun i r => r.insert mainFVars[i]!.fvarId! (mkAppN (Lean.mkConst mainHeaders[i]!.declName) sectionVars) def insertReplacementForLetRecs (r : Replacement) (letRecClosures : List LetRecClosure) : Replacement := letRecClosures.foldl (init := r) fun r c => r.insert c.toLift.fvarId c.closed def Replacement.apply (r : Replacement) (e : Expr) : Expr := e.replace fun e => match e with | .fvar fvarId => match r.find? fvarId with | some c => some c | _ => none | _ => none def pushMain (preDefs : Array PreDefinition) (sectionVars : Array Expr) (mainHeaders : Array DefViewElabHeader) (mainVals : Array Expr) : TermElabM (Array PreDefinition) := mainHeaders.size.foldM (init := preDefs) fun i preDefs => do let header := mainHeaders[i]! let value ← mkLambdaFVars sectionVars mainVals[i]! let type ← mkForallFVars sectionVars header.type return preDefs.push { ref := getDeclarationSelectionRef header.ref kind := header.kind declName := header.declName levelParams := [], -- we set it later modifiers := header.modifiers type, value } def pushLetRecs (preDefs : Array PreDefinition) (letRecClosures : List LetRecClosure) (kind : DefKind) (modifiers : Modifiers) : MetaM (Array PreDefinition) := letRecClosures.foldlM (init := preDefs) fun preDefs c => do let type := Closure.mkForall c.localDecls c.toLift.type let value := Closure.mkLambda c.localDecls c.toLift.val -- Convert any proof let recs inside a `def` to `theorem` kind let kind ← if kind.isDefOrAbbrevOrOpaque then withLCtx c.toLift.lctx c.toLift.localInstances do return if (← inferType c.toLift.type).isProp then .theorem else kind else pure kind return preDefs.push { ref := c.ref declName := c.toLift.declName levelParams := [] -- we set it later modifiers := { modifiers with attrs := c.toLift.attrs } kind, type, value } def getKindForLetRecs (mainHeaders : Array DefViewElabHeader) : DefKind := if mainHeaders.any fun h => h.kind.isTheorem then DefKind.«theorem» else DefKind.«def» def getModifiersForLetRecs (mainHeaders : Array DefViewElabHeader) : Modifiers := { isNoncomputable := mainHeaders.any fun h => h.modifiers.isNoncomputable recKind := if mainHeaders.any fun h => h.modifiers.isPartial then RecKind.partial else RecKind.default isUnsafe := mainHeaders.any fun h => h.modifiers.isUnsafe } /-- - `sectionVars`: The section variables used in the `mutual` block. - `mainHeaders`: The elaborated header of the top-level definitions being defined by the mutual block. - `mainFVars`: The auxiliary variables used to represent the top-level definitions being defined by the mutual block. - `mainVals`: The elaborated value for the top-level definitions - `letRecsToLift`: The let-rec's definitions that need to be lifted -/ def main (sectionVars : Array Expr) (mainHeaders : Array DefViewElabHeader) (mainFVars : Array Expr) (mainVals : Array Expr) (letRecsToLift : List LetRecToLift) : TermElabM (Array PreDefinition) := do -- Store in recFVarIds the fvarId of every function being defined by the mutual block. let letRecsToLift := letRecsToLift.toArray let mainFVarIds := mainFVars.map Expr.fvarId! let recFVarIds := (letRecsToLift.map fun toLift => toLift.fvarId) ++ mainFVarIds resetZetaFVarIds withTrackingZeta do -- By checking `toLift.type` and `toLift.val` we populate `zetaFVarIds`. See comments at `src/Lean/Meta/Closure.lean`. let letRecsToLift ← letRecsToLift.mapM fun toLift => withLCtx toLift.lctx toLift.localInstances do Meta.check toLift.type Meta.check toLift.val return { toLift with val := (← instantiateMVars toLift.val), type := (← instantiateMVars toLift.type) } let letRecClosures ← mkLetRecClosures sectionVars mainFVarIds recFVarIds letRecsToLift -- mkLetRecClosures assign metavariables that were placeholders for the lifted declarations. let mainVals ← mainVals.mapM (instantiateMVars ·) let mainHeaders ← mainHeaders.mapM instantiateMVarsAtHeader let letRecClosures ← letRecClosures.mapM fun closure => do pure { closure with toLift := (← instantiateMVarsAtLetRecToLift closure.toLift) } -- Replace fvarIds for functions being defined with closed terms let r := insertReplacementForMainFns {} sectionVars mainHeaders mainFVars let r := insertReplacementForLetRecs r letRecClosures let mainVals := mainVals.map r.apply let mainHeaders := mainHeaders.map fun h => { h with type := r.apply h.type } let letRecClosures := letRecClosures.map fun c => { c with toLift := { c.toLift with type := r.apply c.toLift.type, val := r.apply c.toLift.val } } let letRecKind := getKindForLetRecs mainHeaders let letRecMods := getModifiersForLetRecs mainHeaders pushMain (← pushLetRecs #[] letRecClosures letRecKind letRecMods) sectionVars mainHeaders mainVals end MutualClosure private def getAllUserLevelNames (headers : Array DefViewElabHeader) : List Name := if h : 0 < headers.size then -- Recall that all top-level functions must have the same levels. See `check` method above (headers.get ⟨0, h⟩).levelNames else [] /-- Eagerly convert universe metavariables occurring in theorem headers to universe parameters. -/ private def levelMVarToParamHeaders (views : Array DefView) (headers : Array DefViewElabHeader) : TermElabM (Array DefViewElabHeader) := do let rec process : StateRefT Nat TermElabM (Array DefViewElabHeader) := do let mut newHeaders := #[] for view in views, header in headers do if view.kind.isTheorem then newHeaders ← withLevelNames header.levelNames do return newHeaders.push { header with type := (← levelMVarToParam header.type), levelNames := (← getLevelNames) } else newHeaders := newHeaders.push header return newHeaders let newHeaders ← (process).run' 1 newHeaders.mapM fun header => return { header with type := (← instantiateMVars header.type) } partial def checkForHiddenUnivLevels (allUserLevelNames : List Name) (preDefs : Array PreDefinition) : TermElabM Unit := unless (← MonadLog.hasErrors) do -- We do not report this kind of error if the declaration already contains errors let mut sTypes : CollectLevelParams.State := {} let mut sValues : CollectLevelParams.State := {} for preDef in preDefs do sTypes := collectLevelParams sTypes preDef.type sValues := collectLevelParams sValues preDef.value if sValues.params.all fun u => sTypes.params.contains u || allUserLevelNames.contains u then -- If all universe level occurring in values also occur in types or explicitly provided universes, then everything is fine -- and we just return return () let checkPreDef (preDef : PreDefinition) : TermElabM Unit := -- Otherwise, we try to produce an error message containing the expression with the offending universe let rec visitLevel (u : Level) : ReaderT Expr TermElabM Unit := do match u with | .succ u => visitLevel u | .imax u v | .max u v => visitLevel u; visitLevel v | .param n => unless sTypes.visitedLevel.contains u || allUserLevelNames.contains n do let parent ← withOptions (fun o => pp.universes.set o true) do addMessageContext m!"{indentExpr (← read)}" let body ← withOptions (fun o => pp.letVarTypes.setIfNotSet (pp.funBinderTypes.setIfNotSet o true) true) do addMessageContext m!"{indentExpr preDef.value}" throwError "invalid occurrence of universe level '{u}' at '{preDef.declName}', it does not occur at the declaration type, nor it is explicit universe level provided by the user, occurring at expression{parent}\nat declaration body{body}" | _ => pure () let rec visit (e : Expr) : ReaderT Expr (MonadCacheT ExprStructEq Unit TermElabM) Unit := do checkCache { val := e : ExprStructEq } fun _ => do match e with | .forallE n d b c | .lam n d b c => visit d e; withLocalDecl n c d fun x => visit (b.instantiate1 x) e | .letE n t v b _ => visit t e; visit v e; withLetDecl n t v fun x => visit (b.instantiate1 x) e | .app .. => e.withApp fun f args => do visit f e; args.forM fun arg => visit arg e | .mdata _ b => visit b e | .proj _ _ b => visit b e | .sort u => visitLevel u (← read) | .const _ us => us.forM (visitLevel · (← read)) | _ => pure () visit preDef.value preDef.value |>.run {} for preDef in preDefs do checkPreDef preDef def elabMutualDef (vars : Array Expr) (views : Array DefView) (hints : TerminationHints) : TermElabM Unit := if isExample views then withoutModifyingEnv do -- save correct environment in info tree withSaveInfoContext do go else go where go := do let scopeLevelNames ← getLevelNames let headers ← elabHeaders views let headers ← levelMVarToParamHeaders views headers let allUserLevelNames := getAllUserLevelNames headers withFunLocalDecls headers fun funFVars => do for view in views, funFVar in funFVars do addLocalVarInfo view.declId funFVar let values ← try let values ← elabFunValues headers Term.synthesizeSyntheticMVarsNoPostponing values.mapM (instantiateMVars ·) catch ex => logException ex headers.mapM fun header => mkSorry header.type (synthetic := true) let headers ← headers.mapM instantiateMVarsAtHeader let letRecsToLift ← getLetRecsToLift let letRecsToLift ← letRecsToLift.mapM instantiateMVarsAtLetRecToLift checkLetRecsToLiftTypes funFVars letRecsToLift withUsed vars headers values letRecsToLift fun vars => do let preDefs ← MutualClosure.main vars headers funFVars values letRecsToLift for preDef in preDefs do trace[Elab.definition] "{preDef.declName} : {preDef.type} :=\n{preDef.value}" let preDefs ← withLevelNames allUserLevelNames <| levelMVarToParamPreDecls preDefs let preDefs ← instantiateMVarsAtPreDecls preDefs let preDefs ← fixLevelParams preDefs scopeLevelNames allUserLevelNames for preDef in preDefs do trace[Elab.definition] "after eraseAuxDiscr, {preDef.declName} : {preDef.type} :=\n{preDef.value}" checkForHiddenUnivLevels allUserLevelNames preDefs addPreDefinitions preDefs hints processDeriving headers processDeriving (headers : Array DefViewElabHeader) := do for header in headers, view in views do if let some classNamesStx := view.deriving? then for classNameStx in classNamesStx do let className ← resolveGlobalConstNoOverload classNameStx withRef classNameStx do unless (← processDefDeriving className header.declName) do throwError "failed to synthesize instance '{className}' for '{header.declName}'" end Term namespace Command def elabMutualDef (ds : Array Syntax) (hints : TerminationHints) : CommandElabM Unit := do let views ← ds.mapM fun d => do let modifiers ← elabModifiers d[0] if ds.size > 1 && modifiers.isNonrec then throwErrorAt d "invalid use of 'nonrec' modifier in 'mutual' block" mkDefView modifiers d[1] runTermElabM fun vars => Term.elabMutualDef vars views hints end Command end Lean.Elab
87da2e163c539e268cd32875b3822bd260e4ef7e
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/topology/sheaves/stalks.lean
12e14e6078de3fd8a705799bff8daf0b682d94fe
[ "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
16,017
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Justus Springer -/ import topology.category.Top.open_nhds import topology.sheaves.presheaf import topology.sheaves.sheaf_condition.unique_gluing import category_theory.limits.types import tactic.elementwise /-! # Stalks For a presheaf `F` on a topological space `X`, valued in some category `C`, the *stalk* of `F` at the point `x : X` is defined as the colimit of the following functor (nhds x)ᵒᵖ ⥤ (opens X)ᵒᵖ ⥤ C where the functor on the left is the inclusion of categories and the functor on the right is `F`. For an open neighborhood `U` of `x`, we define the map `F.germ x : F.obj (op U) ⟶ F.stalk x` as the canonical morphism into this colimit. Taking stalks is functorial: For every point `x : X` we define a functor `stalk_functor C x`, sending presheaves on `X` to objects of `C`. In `is_iso_iff_stalk_functor_map_iso`, we prove that a map `f : F ⟶ G` between `Type`-valued sheaves is an isomorphism if and only if all the maps `F.stalk x ⟶ G.stalk x` (given by the stalk functor on `f`) are isomorphisms. For a map `f : X ⟶ Y` between topological spaces, we define `stalk_pushforward` as the induced map on the stalks `(f _* ℱ).stalk (f x) ⟶ ℱ.stalk x`. -/ noncomputable theory universes v u v' u' open category_theory open Top open category_theory.limits open topological_space open opposite variables {C : Type u} [category.{v} C] variables [has_colimits.{v} C] variables {X Y Z : Top.{v}} namespace Top.presheaf variables (C) /-- Stalks are functorial with respect to morphisms of presheaves over a fixed `X`. -/ def stalk_functor (x : X) : X.presheaf C ⥤ C := ((whiskering_left _ _ C).obj (open_nhds.inclusion x).op) ⋙ colim variables {C} /-- The stalk of a presheaf `F` at a point `x` is calculated as the colimit of the functor nbhds x ⥤ opens F.X ⥤ C -/ def stalk (ℱ : X.presheaf C) (x : X) : C := (stalk_functor C x).obj ℱ -- -- colimit ((open_nhds.inclusion x).op ⋙ ℱ) @[simp] lemma stalk_functor_obj (ℱ : X.presheaf C) (x : X) : (stalk_functor C x).obj ℱ = ℱ.stalk x := rfl /-- The germ of a section of a presheaf over an open at a point of that open. -/ def germ (F : X.presheaf C) {U : opens X} (x : U) : F.obj (op U) ⟶ stalk F x := colimit.ι ((open_nhds.inclusion x.1).op ⋙ F) (op ⟨U, x.2⟩) /-- For a `Type` valued presheaf, every point in a stalk is a germ. -/ lemma germ_exist (F : X.presheaf (Type v)) (x : X) (t : stalk F x) : ∃ (U : opens X) (m : x ∈ U) (s : F.obj (op U)), F.germ ⟨x, m⟩ s = t := begin obtain ⟨U, s, e⟩ := types.jointly_surjective _ (colimit.is_colimit _) t, revert s e, rw [(show U = op (unop U), from rfl)], generalize : unop U = V, clear U, cases V with V m, intros s e, exact ⟨V, m, s, e⟩, end lemma germ_eq (F : X.presheaf (Type v)) {U V : opens X} (x : X) (mU : x ∈ U) (mV : x ∈ V) (s : F.obj (op U)) (t : F.obj (op V)) (h : germ F ⟨x, mU⟩ s = germ F ⟨x, mV⟩ t) : ∃ (W : opens X) (m : x ∈ W) (iU : W ⟶ U) (iV : W ⟶ V), F.map iU.op s = F.map iV.op t := begin erw types.filtered_colimit.colimit_eq_iff at h, rcases h with ⟨W, iU, iV, e⟩, exact ⟨(unop W).1, (unop W).2, iU.unop, iV.unop, e⟩, end @[simp] lemma germ_res (F : X.presheaf C) {U V : opens X} (i : U ⟶ V) (x : U) : F.map i.op ≫ germ F x = germ F (i x : V) := let i' : (⟨U, x.2⟩ : open_nhds x.1) ⟶ ⟨V, (i x : V).2⟩ := i in colimit.w ((open_nhds.inclusion x.1).op ⋙ F) i'.op @[simp] lemma germ_res_apply (F : X.presheaf (Type v)) {U V : opens X} (i : U ⟶ V) (x : U) (f : F.obj (op V)) : germ F x (F.map i.op f) = germ F (i x : V) f := let i' : (⟨U, x.2⟩ : open_nhds x.1) ⟶ ⟨V, (i x : V).2⟩ := i in congr_fun (colimit.w ((open_nhds.inclusion x.1).op ⋙ F) i'.op) f /-- A variant when the open sets are written in `(opens X)ᵒᵖ`. -/ @[simp] lemma germ_res_apply' (F : X.presheaf (Type v)) {U V : (opens X)ᵒᵖ} (i : V ⟶ U) (x : unop U) (f : F.obj V) : germ F x (F.map i f) = germ F (i.unop x : unop V) f := let i' : (⟨unop U, x.2⟩ : open_nhds x.1) ⟶ ⟨unop V, (i.unop x : unop V).2⟩ := i.unop in congr_fun (colimit.w ((open_nhds.inclusion x.1).op ⋙ F) i'.op) f section local attribute [instance] concrete_category.has_coe_to_sort concrete_category.has_coe_to_fun @[ext] lemma germ_ext {D : Type u} [category.{v} D] [concrete_category D] [has_colimits D] (F : X.presheaf D) {U V : opens X} {x : X} {hxU : x ∈ U} {hxV : x ∈ V} (W : opens X) (hxW : x ∈ W) (iWU : W ⟶ U) (iWV : W ⟶ V) {sU : F.obj (op U)} {sV : F.obj (op V)} (ih : F.map iWU.op sU = F.map iWV.op sV) : F.germ ⟨x, hxU⟩ sU = F.germ ⟨x, hxV⟩ sV := by erw [← F.germ_res iWU ⟨x, hxW⟩, ← F.germ_res iWV ⟨x, hxW⟩, comp_apply, comp_apply, ih] end lemma stalk_hom_ext (F : X.presheaf C) {x} {Y : C} {f₁ f₂ : F.stalk x ⟶ Y} (ih : ∀ (U : opens X) (hxU : x ∈ U), F.germ ⟨x, hxU⟩ ≫ f₁ = F.germ ⟨x, hxU⟩ ≫ f₂) : f₁ = f₂ := colimit.hom_ext $ λ U, by { op_induction U, cases U with U hxU, exact ih U hxU } /-- If two sections agree on all stalks, they must be equal -/ lemma section_ext (F : sheaf (Type v) X) (U : opens X) (s t : F.presheaf.obj (op U)) (h : ∀ x : U, F.presheaf.germ x s = F.presheaf.germ x t) : s = t := begin -- We use `germ_eq` and the axiom of choice, to pick for every point `x` a neighbourhood -- `V x`, such that the restrictions of `s` and `t` to `V x` coincide. choose V m i₁ i₂ heq using λ x : U, F.presheaf.germ_eq x.1 x.2 x.2 s t (h x), -- Since `F` is a sheaf, we can prove the equality locally, if we can show that these -- neighborhoods form a cover of `U`. apply F.eq_of_locally_eq' V U i₁, { intros x hxU, rw [subtype.val_eq_coe, opens.mem_coe, opens.mem_supr], exact ⟨⟨x, hxU⟩, m ⟨x, hxU⟩⟩ }, { intro x, rw [heq, subsingleton.elim (i₁ x) (i₂ x)] } end @[simp, reassoc] lemma stalk_functor_map_germ {F G : X.presheaf C} (U : opens X) (x : U) (f : F ⟶ G) : germ F x ≫ (stalk_functor C x.1).map f = f.app (op U) ≫ germ G x := colimit.ι_map (whisker_left ((open_nhds.inclusion x.1).op) f) (op ⟨U, x.2⟩) @[simp] lemma stalk_functor_map_germ_apply (U : opens X) (x : U) {F G : X.presheaf (Type v)} (f : F ⟶ G) (s : F.obj (op U)) : (stalk_functor (Type v) x.1).map f (germ F x s) = germ G x (f.app (op U) s) := congr_fun (stalk_functor_map_germ U x f) s open function lemma stalk_functor_map_injective_of_app_injective {F G : presheaf (Type v) X} (f : F ⟶ G) (h : ∀ U : opens X, injective (f.app (op U))) (x : X) : injective ((stalk_functor (Type v) x).map f) := λ s t hst, begin rcases germ_exist F x s with ⟨U₁, hxU₁, s, rfl⟩, rcases germ_exist F x t with ⟨U₂, hxU₂, t, rfl⟩, simp only [stalk_functor_map_germ_apply _ ⟨x,_⟩] at hst, obtain ⟨W, hxW, iWU₁, iWU₂, heq⟩ := G.germ_eq x hxU₁ hxU₂ _ _ hst, rw [← functor_to_types.naturality, ← functor_to_types.naturality] at heq, replace heq := h W heq, convert congr_arg (F.germ ⟨x,hxW⟩) heq, exacts [(F.germ_res_apply iWU₁ ⟨x,hxW⟩ s).symm, (F.germ_res_apply iWU₂ ⟨x,hxW⟩ t).symm], end /- Note that the analogous statement for surjectivity is false: Surjectivity on stalks does not imply surjectivity of the components of a sheaf morphism. However it does imply that the morphism is an epi, but this fact is not yet formalized. -/ lemma app_injective_of_stalk_functor_map_injective {F : sheaf (Type v) X} {G : presheaf (Type v) X} (f : F.presheaf ⟶ G) (h : ∀ x : X, injective ((stalk_functor (Type v) x).map f)) (U : opens X) : injective (f.app (op U)) := λ s t hst, section_ext F _ _ _ $ λ x, h x.1 $ by rw [stalk_functor_map_germ_apply, stalk_functor_map_germ_apply, hst] lemma app_injective_iff_stalk_functor_map_injective {F : sheaf (Type v) X} {G : presheaf (Type v) X} (f : F.presheaf ⟶ G) : (∀ x : X, injective ((stalk_functor (Type v) x).map f)) ↔ (∀ U : opens X, injective (f.app (op U))) := ⟨app_injective_of_stalk_functor_map_injective f, stalk_functor_map_injective_of_app_injective f⟩ lemma app_surjective_of_stalk_functor_map_bijective {F G : sheaf (Type v) X} (f : F ⟶ G) (h : ∀ x : X, bijective ((stalk_functor (Type v) x).map f)) (U : opens X) : surjective (f.app (op U)) := begin intro t, -- For surjectivity, we are given an arbitrary section `t` and need to find a preimage for it. -- We claim that it suffices to find preimages *locally*. That is, for each `x : U` we construct -- a neighborhood `V ≤ U` and a section `s : F.obj (op V))` such that `f.app (op V) s` and `t` -- agree on `V`. suffices : ∀ x : U, ∃ (V : opens X) (m : x.1 ∈ V) (iVU : V ⟶ U) (s : F.presheaf.obj (op V)), f.app (op V) s = G.presheaf.map iVU.op t, { -- We use the axiom of choice to pick around each point `x` an open neighborhood `V` and a -- preimage under `f` on `V`. choose V mV iVU sf heq using this, -- These neighborhoods clearly cover all of `U`. have V_cover : U ≤ supr V, { intros x hxU, rw [subtype.val_eq_coe, opens.mem_coe, opens.mem_supr], exact ⟨⟨x, hxU⟩, mV ⟨x, hxU⟩⟩ }, -- Since `F` is a sheaf, we can glue all the local preimages together to get a global preimage. obtain ⟨s, s_spec, -⟩ := F.exists_unique_gluing' V U iVU V_cover sf _, { use s, apply G.eq_of_locally_eq' V U iVU V_cover, intro x, rw [← functor_to_types.naturality, s_spec, heq] }, { intros x y, -- What's left to show here is that the secions `sf` are compatible, i.e. they agree on -- the intersections `V x ⊓ V y`. We prove this by showing that all germs are equal. apply section_ext, intro z, -- Here, we need to use injectivity of the stalk maps. apply (h z).1, erw [stalk_functor_map_germ_apply, stalk_functor_map_germ_apply], rw [functor_to_types.naturality, functor_to_types.naturality, heq, heq, ← functor_to_types.map_comp_apply, ← functor_to_types.map_comp_apply], refl } }, intro x, -- Now we need to prove our initial claim: That we can find preimages of `t` locally. -- Since `f` is surjective on stalks, we can find a preimage `s₀` of the germ of `t` at `x` obtain ⟨s₀,hs₀⟩ := (h x).2 (G.presheaf.germ x t), -- ... and this preimage must come from some section `s₁` defined on some open neighborhood `V₁` obtain ⟨V₁,hxV₁,s₁,hs₁⟩ := F.presheaf.germ_exist x.1 s₀, subst hs₁, rename hs₀ hs₁, erw stalk_functor_map_germ_apply V₁ ⟨x.1,hxV₁⟩ f s₁ at hs₁, -- Now, the germ of `f.app (op V₁) s₁` equals the germ of `t`, hence they must coincide on -- some open neighborhood `V₂`. obtain ⟨V₂, hxV₂, iV₂V₁, iV₂U, heq⟩ := G.presheaf.germ_eq x.1 hxV₁ x.2 _ _ hs₁, -- The restriction of `s₁` to that neighborhood is our desired local preimage. use [V₂, hxV₂, iV₂U, F.presheaf.map iV₂V₁.op s₁], rw [functor_to_types.naturality, heq], end lemma app_bijective_of_stalk_functor_map_bijective {F G : sheaf (Type v) X} (f : F ⟶ G) (h : ∀ x : X, bijective ((stalk_functor (Type v) x).map f)) (U : opens X) : bijective (f.app (op U)) := ⟨app_injective_of_stalk_functor_map_injective f (λ x, (h x).1) U, app_surjective_of_stalk_functor_map_bijective f h U⟩ /-- If all the stalk maps of map `f : F ⟶ G` of `Type`-valued sheaves are isomorphisms, then `f` is an isomorphism. -/ -- Making this an instance would cause a loop in typeclass resolution with `functor.map_is_iso` lemma is_iso_of_stalk_functor_map_iso {F G : sheaf (Type v) X} (f : F ⟶ G) [∀ x : X, is_iso ((stalk_functor (Type v) x).map f)] : is_iso f := begin -- Rather annoyingly, an isomorphism of presheaves isn't quite the same as an isomorphism of -- sheaves. We have to use that the induced functor from sheaves to presheaves is fully faithful haveI : is_iso ((induced_functor sheaf.presheaf).map f) := @nat_iso.is_iso_of_is_iso_app _ _ _ _ F.presheaf G.presheaf f (by { intro U, op_induction U, rw is_iso_iff_bijective, exact app_bijective_of_stalk_functor_map_bijective f (λ x, (is_iso_iff_bijective _).mp (_inst_3 x)) U, }), exact is_iso_of_fully_faithful (induced_functor sheaf.presheaf) f, end /-- A morphism of `Type`-valued sheaves `f : F ⟶ G` is an isomorphism if and only if all the stalk maps are isomorphisms -/ lemma is_iso_iff_stalk_functor_map_iso {F G : sheaf (Type v) X} (f : F ⟶ G) : is_iso f ↔ ∀ x : X, is_iso ((stalk_functor (Type v) x).map f) := begin split, { intros h x, resetI, exact @functor.map_is_iso _ _ _ _ _ _ (stalk_functor (Type v) x) f ((induced_functor sheaf.presheaf).map_is_iso f) }, { intro h, resetI, exact is_iso_of_stalk_functor_map_iso f } end variables (C) def stalk_pushforward (f : X ⟶ Y) (ℱ : X.presheaf C) (x : X) : (f _* ℱ).stalk (f x) ⟶ ℱ.stalk x := begin -- This is a hack; Lean doesn't like to elaborate the term written directly. transitivity, swap, exact colimit.pre _ (open_nhds.map f x).op, exact colim.map (whisker_right (nat_trans.op (open_nhds.inclusion_map_iso f x).inv) ℱ), end @[simp, elementwise, reassoc] lemma stalk_pushforward_germ (f : X ⟶ Y) (F : X.presheaf C) (U : opens Y) (x : (opens.map f).obj U) : (f _* F).germ ⟨f x, x.2⟩ ≫ F.stalk_pushforward C f x = F.germ x := begin rw [stalk_pushforward, germ, colimit.ι_map_assoc, colimit.ι_pre, whisker_right_app], erw [category_theory.functor.map_id, category.id_comp], refl, end -- Here are two other potential solutions, suggested by @fpvandoorn at -- <https://github.com/leanprover-community/mathlib/pull/1018#discussion_r283978240> -- However, I can't get the subsequent two proofs to work with either one. -- def stalk_pushforward (f : X ⟶ Y) (ℱ : X.presheaf C) (x : X) : -- (f _* ℱ).stalk (f x) ⟶ ℱ.stalk x := -- colim.map ((functor.associator _ _ _).inv ≫ -- whisker_right (nat_trans.op (open_nhds.inclusion_map_iso f x).inv) ℱ) ≫ -- colimit.pre ((open_nhds.inclusion x).op ⋙ ℱ) (open_nhds.map f x).op -- def stalk_pushforward (f : X ⟶ Y) (ℱ : X.presheaf C) (x : X) : -- (f _* ℱ).stalk (f x) ⟶ ℱ.stalk x := -- (colim.map (whisker_right (nat_trans.op (open_nhds.inclusion_map_iso f x).inv) ℱ) : -- colim.obj ((open_nhds.inclusion (f x) ⋙ opens.map f).op ⋙ ℱ) ⟶ _) ≫ -- colimit.pre ((open_nhds.inclusion x).op ⋙ ℱ) (open_nhds.map f x).op namespace stalk_pushforward local attribute [tidy] tactic.op_induction' @[simp] lemma id (ℱ : X.presheaf C) (x : X) : ℱ.stalk_pushforward C (𝟙 X) x = (stalk_functor C x).map ((pushforward.id ℱ).hom) := begin dsimp [stalk_pushforward, stalk_functor], ext1, tactic.op_induction', cases j, cases j_val, rw [colimit.ι_map_assoc, colimit.ι_map, colimit.ι_pre, whisker_left_app, whisker_right_app, pushforward.id_hom_app, eq_to_hom_map, eq_to_hom_refl], dsimp, -- FIXME A simp lemma which unfortunately doesn't fire: erw [category_theory.functor.map_id], end -- This proof is sadly not at all robust: -- having to use `erw` at all is a bad sign. @[simp] lemma comp (ℱ : X.presheaf C) (f : X ⟶ Y) (g : Y ⟶ Z) (x : X) : ℱ.stalk_pushforward C (f ≫ g) x = ((f _* ℱ).stalk_pushforward C g (f x)) ≫ (ℱ.stalk_pushforward C f x) := begin dsimp [stalk_pushforward, stalk_functor], ext U, op_induction U, cases U, cases U_val, simp only [colimit.ι_map_assoc, colimit.ι_pre_assoc, whisker_right_app, category.assoc], dsimp, -- FIXME: Some of these are simp lemmas, but don't fire successfully: erw [category_theory.functor.map_id, category.id_comp, category.id_comp, category.id_comp, colimit.ι_pre, colimit.ι_pre], refl, end end stalk_pushforward end Top.presheaf
5fb455b90af2258b6dd02178fd69efc78a177c0b
94637389e03c919023691dcd05bd4411b1034aa5
/src/zzz_junk/has_mul/has_mul_bool.lean
34c84227ef127d6b2784cb1c1e2dec97e42b3ba6
[]
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
1,135
lean
import ..has_one.has_one open hidden /- Use a typeclass instance to overload operator symbol for a specific type. Each typeclass instance provides values for "its" associated type. -/ /- Create a single typeclass instance (structure). It gets registered into a database of such instsances. -/ instance has_mul_bool : hidden.has_mul bool := ⟨ band ⟩ /- This code would typically be co-located witht he code that defines the bool type, because this instance defines what the operator returns when applied to the type, bool. Instances implement overloaded operators *for specific types*, and its the type definitions themselves, that should provide define how each overloaded operator is implemented for that type. When needed, this structure can be fetched by means of typeclass inferencing. Here we get back the bool value stored as a identity for bool multiplication (which we take to be performed by band, by the way). -/ def my_band [b : hidden.has_mul bool] := b.mul -- as expected ... #check my_band #eval my_band ff ff #eval my_band ff tt #eval my_band tt ff #eval my_band tt tt -- Yep, that's band alright
6269471247ec172c54285ce3a135c9287b55499c
618003631150032a5676f229d13a079ac875ff77
/src/data/rat/floor.lean
a94f917c196573184a0c3b4d0e005d4609bae1d6
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
1,006
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Kevin Kappelmann -/ import algebra.floor /-! # Floor Function for Rational Numbers ## Summary We define the `floor` function and the `floor_ring` instance on `ℚ`. ## Tags rat, rationals, ℚ, floor -/ namespace rat /-- `floor q` is the largest integer `z` such that `z ≤ q` -/ protected def floor : ℚ → ℤ | ⟨n, d, h, c⟩ := n / d protected theorem le_floor {z : ℤ} : ∀ {r : ℚ}, z ≤ rat.floor r ↔ (z : ℚ) ≤ r | ⟨n, d, h, c⟩ := begin simp [rat.floor], rw [num_denom'], have h' := int.coe_nat_lt.2 h, conv { to_rhs, rw [coe_int_eq_mk, rat.le_def zero_lt_one h', mul_one] }, exact int.le_div_iff_mul_le h' end instance : floor_ring ℚ := { floor := rat.floor, le_floor := @rat.le_floor } protected lemma floor_def {q : ℚ} : ⌊q⌋ = q.num / q.denom := by { cases q, refl } end rat
291d62bae0e0575c2204f71b753a1c487780b164
ba4794a0deca1d2aaa68914cd285d77880907b5c
/experiments/UFD_experiments.lean
521c5d0d0f798c41cbd6a91868146e28f3c7db28
[ "Apache-2.0" ]
permissive
ChrisHughes24/natural_number_game
c7c00aa1f6a95004286fd456ed13cf6e113159ce
9d09925424da9f6275e6cfe427c8bcf12bb0944f
refs/heads/master
1,600,715,773,528
1,573,910,462,000
1,573,910,462,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
728
lean
-- WIP -- this might be awful to do without int. import solutions.world3_le import data.nat.basic #print prefix nat namespace mynat def divides (a b : mynat) := ∃ c, a * c = b instance : has_dvd mynat := ⟨mynat.divides⟩ def is_prime (n : mynat) : Prop := n ≠ 1 ∧ ∀ d, d ∣ n → d = 1 ∨ d = n theorem has_prime_factor (n : mynat) : 1 < n → ∃ p : mynat, is_prime p ∧ p ∣ n := begin [less_leaky] intro h, cases n with n, exfalso, apply @not_lt_zero 1, exact h, cases n with n, exfalso, rw ←one_eq_succ_zero at h, apply lt_irrefl (1 : mynat), assumption, clear h, revert n, apply strong_induction, -- strong induction successfully applied! sorry end end mynat
748a2100787ea9242d929338886f68a4e1bfb30c
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/arrow.lean
97c6eef12cdccc5b3b8eacd20af73ce1daee2e4a
[ "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,270
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import category_theory.comma /-! # The category of arrows The category of arrows, with morphisms commutative squares. We set this up as a specialization of the comma category `comma L R`, where `L` and `R` are both the identity functor. We also define the typeclass `has_lift`, representing a choice of a lift of a commutative square (that is, a diagonal morphism making the two triangles commute). ## Tags comma, arrow -/ namespace category_theory universes v u -- morphism levels before object levels. See note [category_theory universes]. variables {T : Type u} [category.{v} T] section variables (T) /-- The arrow category of `T` has as objects all morphisms in `T` and as morphisms commutative squares in `T`. -/ @[derive category] def arrow := comma.{v v v} (𝟭 T) (𝟭 T) -- Satisfying the inhabited linter instance arrow.inhabited [inhabited T] : inhabited (arrow T) := { default := show comma (𝟭 T) (𝟭 T), from default } end namespace arrow @[simp] lemma id_left (f : arrow T) : comma_morphism.left (𝟙 f) = 𝟙 (f.left) := rfl @[simp] lemma id_right (f : arrow T) : comma_morphism.right (𝟙 f) = 𝟙 (f.right) := rfl /-- An object in the arrow category is simply a morphism in `T`. -/ @[simps] def mk {X Y : T} (f : X ⟶ Y) : arrow T := { left := X, right := Y, hom := f } theorem mk_injective (A B : T) : function.injective (arrow.mk : (A ⟶ B) → arrow T) := λ f g h, by { cases h, refl } theorem mk_inj (A B : T) {f g : A ⟶ B} : arrow.mk f = arrow.mk g ↔ f = g := (mk_injective A B).eq_iff instance {X Y : T} : has_coe (X ⟶ Y) (arrow T) := ⟨mk⟩ /-- A morphism in the arrow category is a commutative square connecting two objects of the arrow category. -/ @[simps] def hom_mk {f g : arrow T} {u : f.left ⟶ g.left} {v : f.right ⟶ g.right} (w : u ≫ g.hom = f.hom ≫ v) : f ⟶ g := { left := u, right := v, w' := w } /-- We can also build a morphism in the arrow category out of any commutative square in `T`. -/ @[simps] def hom_mk' {X Y : T} {f : X ⟶ Y} {P Q : T} {g : P ⟶ Q} {u : X ⟶ P} {v : Y ⟶ Q} (w : u ≫ g = f ≫ v) : arrow.mk f ⟶ arrow.mk g := { left := u, right := v, w' := w } @[simp, reassoc] lemma w {f g : arrow T} (sq : f ⟶ g) : sq.left ≫ g.hom = f.hom ≫ sq.right := sq.w -- `w_mk_left` is not needed, as it is a consequence of `w` and `mk_hom`. @[simp, reassoc] lemma w_mk_right {f : arrow T} {X Y : T} {g : X ⟶ Y} (sq : f ⟶ mk g) : sq.left ≫ g = f.hom ≫ sq.right := sq.w lemma is_iso_of_iso_left_of_is_iso_right {f g : arrow T} (ff : f ⟶ g) [is_iso ff.left] [is_iso ff.right] : is_iso ff := { out := ⟨⟨inv ff.left, inv ff.right⟩, by { ext; dsimp; simp only [is_iso.hom_inv_id] }, by { ext; dsimp; simp only [is_iso.inv_hom_id] }⟩ } /-- Create an isomorphism between arrows, by providing isomorphisms between the domains and codomains, and a proof that the square commutes. -/ @[simps] def iso_mk {f g : arrow T} (l : f.left ≅ g.left) (r : f.right ≅ g.right) (h : l.hom ≫ g.hom = f.hom ≫ r.hom) : f ≅ g := comma.iso_mk l r h section variables {f g : arrow T} (sq : f ⟶ g) instance is_iso_left [is_iso sq] : is_iso sq.left := { out := ⟨(inv sq).left, by simp only [← comma.comp_left, is_iso.hom_inv_id, is_iso.inv_hom_id, arrow.id_left, eq_self_iff_true, and_self]⟩ } instance is_iso_right [is_iso sq] : is_iso sq.right := { out := ⟨(inv sq).right, by simp only [← comma.comp_right, is_iso.hom_inv_id, is_iso.inv_hom_id, arrow.id_right, eq_self_iff_true, and_self]⟩ } @[simp] lemma inv_left [is_iso sq] : (inv sq).left = inv sq.left := is_iso.eq_inv_of_hom_inv_id $ by rw [← comma.comp_left, is_iso.hom_inv_id, id_left] @[simp] lemma inv_right [is_iso sq] : (inv sq).right = inv sq.right := is_iso.eq_inv_of_hom_inv_id $ by rw [← comma.comp_right, is_iso.hom_inv_id, id_right] @[simp] lemma left_hom_inv_right [is_iso sq] : sq.left ≫ g.hom ≫ inv sq.right = f.hom := by simp only [← category.assoc, is_iso.comp_inv_eq, w] -- simp proves this lemma inv_left_hom_right [is_iso sq] : inv sq.left ≫ f.hom ≫ sq.right = g.hom := by simp only [w, is_iso.inv_comp_eq] instance mono_left [mono sq] : mono sq.left := { right_cancellation := λ Z φ ψ h, begin let aux : (Z ⟶ f.left) → (arrow.mk (𝟙 Z) ⟶ f) := λ φ, { left := φ, right := φ ≫ f.hom }, show (aux φ).left = (aux ψ).left, congr' 1, rw ← cancel_mono sq, ext, { exact h }, { simp only [comma.comp_right, category.assoc, ← arrow.w], simp only [← category.assoc, h], }, end } instance epi_right [epi sq] : epi sq.right := { left_cancellation := λ Z φ ψ h, begin let aux : (g.right ⟶ Z) → (g ⟶ arrow.mk (𝟙 Z)) := λ φ, { right := φ, left := g.hom ≫ φ }, show (aux φ).right = (aux ψ).right, congr' 1, rw ← cancel_epi sq, ext, { simp only [comma.comp_left, category.assoc, arrow.w_assoc, h], }, { exact h }, end } end /-- Given a square from an arrow `i` to an isomorphism `p`, express the source part of `sq` in terms of the inverse of `p`. -/ @[simp] lemma square_to_iso_invert (i : arrow T) {X Y : T} (p : X ≅ Y) (sq : i ⟶ arrow.mk p.hom) : i.hom ≫ sq.right ≫ p.inv = sq.left := by simpa only [category.assoc] using (iso.comp_inv_eq p).mpr ((arrow.w_mk_right sq).symm) /-- Given a square from an isomorphism `i` to an arrow `p`, express the target part of `sq` in terms of the inverse of `i`. -/ lemma square_from_iso_invert {X Y : T} (i : X ≅ Y) (p : arrow T) (sq : arrow.mk i.hom ⟶ p) : i.inv ≫ sq.left ≫ p.hom = sq.right := by simp only [iso.inv_hom_id_assoc, arrow.w, arrow.mk_hom] /-- A lift of a commutative square is a diagonal morphism making the two triangles commute. -/ @[ext] structure lift_struct {f g : arrow T} (sq : f ⟶ g) := (lift : f.right ⟶ g.left) (fac_left' : f.hom ≫ lift = sq.left . obviously) (fac_right' : lift ≫ g.hom = sq.right . obviously) restate_axiom lift_struct.fac_left' restate_axiom lift_struct.fac_right' instance lift_struct_inhabited {X : T} : inhabited (lift_struct (𝟙 (arrow.mk (𝟙 X)))) := ⟨⟨𝟙 _, category.id_comp _, category.comp_id _⟩⟩ /-- `has_lift sq` says that there is some `lift_struct sq`, i.e., that it is possible to find a diagonal morphism making the two triangles commute. -/ class has_lift {f g : arrow T} (sq : f ⟶ g) : Prop := mk' :: (exists_lift : nonempty (lift_struct sq)) lemma has_lift.mk {f g : arrow T} {sq : f ⟶ g} (s : lift_struct sq) : has_lift sq := ⟨nonempty.intro s⟩ attribute [simp, reassoc] lift_struct.fac_left lift_struct.fac_right /-- Given `has_lift sq`, obtain a lift. -/ noncomputable def has_lift.struct {f g : arrow T} (sq : f ⟶ g) [has_lift sq] : lift_struct sq := classical.choice has_lift.exists_lift /-- If there is a lift of a commutative square `sq`, we can access it by saying `lift sq`. -/ noncomputable abbreviation lift {f g : arrow T} (sq : f ⟶ g) [has_lift sq] : f.right ⟶ g.left := (has_lift.struct sq).lift lemma lift.fac_left {f g : arrow T} (sq : f ⟶ g) [has_lift sq] : f.hom ≫ lift sq = sq.left := by simp lemma lift.fac_right {f g : arrow T} (sq : f ⟶ g) [has_lift sq] : lift sq ≫ g.hom = sq.right := by simp @[simp, reassoc] lemma lift.fac_right_of_to_mk {X Y : T} {f : arrow T} {g : X ⟶ Y} (sq : f ⟶ mk g) [has_lift sq] : lift sq ≫ g = sq.right := by simp only [←mk_hom g, lift.fac_right] @[simp, reassoc] lemma lift.fac_left_of_from_mk {X Y : T} {f : X ⟶ Y} {g : arrow T} (sq : mk f ⟶ g) [has_lift sq] : f ≫ lift sq = sq.left := by simp only [←mk_hom f, lift.fac_left] @[simp, reassoc] lemma lift_mk'_left {X Y P Q : T} {f : X ⟶ Y} {g : P ⟶ Q} {u : X ⟶ P} {v : Y ⟶ Q} (h : u ≫ g = f ≫ v) [has_lift $ arrow.hom_mk' h] : f ≫ lift (arrow.hom_mk' h) = u := by simp only [←arrow.mk_hom f, lift.fac_left, arrow.hom_mk'_left] @[simp, reassoc] lemma lift_mk'_right {X Y P Q : T} {f : X ⟶ Y} {g : P ⟶ Q} {u : X ⟶ P} {v : Y ⟶ Q} (h : u ≫ g = f ≫ v) [has_lift $ arrow.hom_mk' h] : lift (arrow.hom_mk' h) ≫ g = v := by simp only [←arrow.mk_hom g, lift.fac_right, arrow.hom_mk'_right] section instance subsingleton_lift_struct_of_epi {f g : arrow T} (sq : f ⟶ g) [epi f.hom] : subsingleton (lift_struct sq) := subsingleton.intro $ λ a b, lift_struct.ext a b $ (cancel_epi f.hom).1 $ by simp instance subsingleton_lift_struct_of_mono {f g : arrow T} (sq : f ⟶ g) [mono g.hom] : subsingleton (lift_struct sq) := subsingleton.intro $ λ a b, lift_struct.ext a b $ (cancel_mono g.hom).1 $ by simp end variables {C : Type u} [category.{v} C] /-- A helper construction: given a square between `i` and `f ≫ g`, produce a square between `i` and `g`, whose top leg uses `f`: A → X ↓f ↓i Y --> A → Y ↓g ↓i ↓g B → Z B → Z -/ @[simps] def square_to_snd {X Y Z: C} {i : arrow C} {f : X ⟶ Y} {g : Y ⟶ Z} (sq : i ⟶ arrow.mk (f ≫ g)) : i ⟶ arrow.mk g := { left := sq.left ≫ f, right := sq.right } /-- The functor sending an arrow to its source. -/ @[simps] def left_func : arrow C ⥤ C := comma.fst _ _ /-- The functor sending an arrow to its target. -/ @[simps] def right_func : arrow C ⥤ C := comma.snd _ _ /-- The natural transformation from `left_func` to `right_func`, given by the arrow itself. -/ @[simps] def left_to_right : (left_func : arrow C ⥤ C) ⟶ right_func := { app := λ f, f.hom } end arrow namespace functor universes v₁ v₂ u₁ u₂ variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] /-- A functor `C ⥤ D` induces a functor between the corresponding arrow categories. -/ @[simps] def map_arrow (F : C ⥤ D) : arrow C ⥤ arrow D := { obj := λ a, { left := F.obj a.left, right := F.obj a.right, hom := F.map a.hom, }, map := λ a b f, { left := F.map f.left, right := F.map f.right, w' := by { have w := f.w, simp only [id_map] at w, dsimp, simp only [←F.map_comp, w], } } } end functor end category_theory
d2dee1d0b7764fb360a5331464750aadb7e2e03b
29cc89d6158dd3b90acbdbcab4d2c7eb9a7dbf0f
/4.1/41_lecture.lean
f62d030f62c43832f37fec39190f1451126a6519
[]
no_license
KjellZijlemaker/Logical_Verification_VU
ced0ba95316a30e3c94ba8eebd58ea004fa6f53b
4578b93bf1615466996157bb333c84122b201d99
refs/heads/master
1,585,966,086,108
1,549,187,704,000
1,549,187,704,000
155,690,284
0
0
null
null
null
null
UTF-8
Lean
false
false
3,659
lean
/- Lecture 4.1: Mathematics — Foundation -/ namespace lecture /- Type universes -/ #check (Prop : Type) #check (Type : Type 1) #check (Type 1 : Type 2) #check (Type 2 : Type 3) -- declare universe names universes u v example : Prop = Sort 0 := by refl example : Type = Sort 1 := by refl example : Type = Type 0 := by refl example : Type u = Sort (u + 1) := by refl #check (Type u : Type (u + 1)) -- `ulift α` is isomorphic to `α` #check ulift.{v u} #check @ulift.up.{u v} #check @ulift.down.{u v} #check plift.{1} #check eq.{u} /- `Prop` vs. `Type` -/ -- `Prop` is a subsingleton example {p : Prop} {h₁ h₂ : p} : h₁ = h₂ := by refl namespace hidden class inhabited (α : Type _) := (default : α) -- inductive nonempty (α : Sort u) : Prop -- | intro (val : α) : nonempty -- inductive inhabited (α : Sort u) : Sort (max 1 u) -- | mk (default : α) : inhabited instance Prop_inhabited : inhabited Prop := inhabited.mk true instance bool_inhabited : inhabited bool := inhabited.mk tt instance nat_inhabited : inhabited nat := inhabited.mk 0 instance unit_inhabited : inhabited unit := inhabited.mk () def default (α : Type) [s : inhabited α] : α := @inhabited.default α s instance prod_inhabited {α β : Type} [inhabited α] [inhabited β] : inhabited (prod α β) := ⟨(default α, default β)⟩ #check default (nat × bool) #reduce default (nat × bool) end hidden /- Large elimination -/ #check @false.elim -- in a contradictory context #check @and.rec #check @eq.rec -- substitution in `Prop` and `Type` #check @well_founded.rec -- induction or well-founded recursion /- The axiom of choice -/ #print classical.choice #check classical.some #check classical.some_spec #check classical.em #check classical.prop_decidable /- Quotient types -/ set_option pp.beta true -- `quot` for arbitrary relations #print quot #print quot.mk #print quot.lift #print quot.sound -- `quotient` for equivalence relations #print quotient #print setoid #check quotient.lift_on #check quotient.lift_on₂ #check quotient.exact #check (≈) /- Integers as a quotient -/ /- Basic idea: `(p, n)` represents `p - n` -/ instance int.rel : setoid (ℕ × ℕ) := { r := λa b, a.1 + b.2 = b.1 + a.2, iseqv := ⟨ (assume a, rfl), (assume a b eq, eq.symm), (assume a b c eq_ab eq_bc, have (a.1 + c.2) + b.2 = (c.1 + a.2) + b.2 := calc (a.1 + c.2) + b.2 = (a.1 + b.2) + c.2 : by ac_refl ... = a.2 + (b.1 + c.2) : by rw [eq_ab]; ac_refl ... = (c.1 + a.2) + b.2 : by rw [eq_bc]; ac_refl, calc a.1 + c.2 = c.1 + a.2 : eq_of_add_eq_add_right this) ⟩ } @[simp] lemma rel_iff (a b : ℕ × ℕ) : a ≈ b ↔ a.1 + b.2 = b.1 + a.2 := iff.rfl def int : Type := quotient int.rel def zero : int := ⟦(0, 0)⟧ example (n : ℕ) : zero = ⟦(n, n)⟧ := begin unfold zero, apply quotient.sound, rw [rel_iff], simp end def add (a b : int) : int := quotient.lift_on₂ a b (λa b, ⟦(a.1 + b.1, a.2 + b.2)⟧) begin intros a₁ b₁ a₂ b₂ ha hb, apply quotient.sound, simp only [rel_iff] at ha hb ⊢, calc (a₁.1 + b₁.1) + (a₂.2 + b₂.2) = (a₁.1 + a₂.2) + (b₁.1 + b₂.2) : by ac_refl ... = (a₂.1 + a₁.2) + (b₂.1 + b₁.2) : by rw [ha, hb] ... = (a₂.1 + b₂.1) + (a₁.2 + b₁.2) : by ac_refl end lemma add_mk (ap an bp bn : ℕ) : add ⟦(ap, an)⟧ ⟦(bp, bn)⟧ = ⟦(ap + bp, an + bn)⟧ := by refl lemma add_zero (i : int) : add zero i = i := quotient.induction_on i begin intro p, cases p, simp [zero, add_mk] end end lecture
9ad125488cf26b5560f4967a6951530405e45809
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/algebra/lie_algebra.lean
3c823421efda3a7713227cb9147df4b68c398ac9
[ "Apache-2.0" ]
permissive
DanielFabian/mathlib
efc3a50b5dde303c59eeb6353ef4c35a345d7112
f520d07eba0c852e96fe26da71d85bf6d40fcc2a
refs/heads/master
1,668,739,922,971
1,595,201,756,000
1,595,201,756,000
279,469,476
0
0
null
1,594,696,604,000
1,594,696,604,000
null
UTF-8
Lean
false
false
39,923
lean
/- Copyright (c) 2019 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import ring_theory.algebra import linear_algebra.linear_action import linear_algebra.bilinear_form import tactic.noncomm_ring /-! # Lie algebras This file defines Lie rings, and Lie algebras over a commutative ring. It shows how these arise from associative rings and algebras via the ring commutator. In particular it defines the Lie algebra of endomorphisms of a module as well as of the algebra of square matrices over a commutative ring. It also includes definitions of morphisms of Lie algebras, Lie subalgebras, Lie modules, Lie submodules, and the quotient of a Lie algebra by an ideal. ## Notations We introduce the notation ⁅x, y⁆ for the Lie bracket. Note that these are the Unicode "square with quill" brackets rather than the usual square brackets. We also introduce the notations L →ₗ⁅R⁆ L' for a morphism of Lie algebras over a commutative ring R, and L →ₗ⁅⁆ L' for the same, when the ring is implicit. ## Implementation notes Lie algebras are defined as modules with a compatible Lie ring structure, and thus are partially unbundled. Since they extend Lie rings, these are also partially unbundled. ## References * [N. Bourbaki, *Lie Groups and Lie Algebras, Chapters 1--3*][bourbaki1975] ## Tags lie bracket, ring commutator, jacobi identity, lie ring, lie algebra -/ universes u v w w₁ /-- A binary operation, intended use in Lie algebras and similar structures. -/ class has_bracket (L : Type v) := (bracket : L → L → L) notation `⁅`x`,` y`⁆` := has_bracket.bracket x y /-- An Abelian Lie algebra is one in which all brackets vanish. Arguably this class belongs in the `has_bracket` namespace but it seems much more user-friendly to compromise slightly and put it in the `lie_algebra` namespace. -/ class lie_algebra.is_abelian (L : Type v) [has_bracket L] [has_zero L] : Prop := (abelian : ∀ (x y : L), ⁅x, y⁆ = 0) namespace ring_commutator variables {A : Type v} [ring A] /-- The ring commutator captures the extent to which a ring is commutative. It is identically zero exactly when the ring is commutative. -/ def commutator (x y : A) := x*y - y*x local notation `⁅`x`,` y`⁆` := commutator x y @[simp] lemma add_left (x y z : A) : ⁅x + y, z⁆ = ⁅x, z⁆ + ⁅y, z⁆ := by simp [commutator, right_distrib, left_distrib, sub_eq_add_neg, add_comm, add_left_comm] @[simp] lemma add_right (x y z : A) : ⁅z, x + y⁆ = ⁅z, x⁆ + ⁅z, y⁆ := by simp [commutator, right_distrib, left_distrib, sub_eq_add_neg, add_comm, add_left_comm] @[simp] lemma alternate (x : A) : ⁅x, x⁆ = 0 := by simp [commutator] lemma jacobi (x y z : A) : ⁅x, ⁅y, z⁆⁆ + ⁅y, ⁅z, x⁆⁆ + ⁅z, ⁅x, y⁆⁆ = 0 := by { unfold commutator, noncomm_ring, } end ring_commutator section prio set_option default_priority 100 -- see Note [default priority] /-- A Lie ring is an additive group with compatible product, known as the bracket, satisfying the Jacobi identity. The bracket is not associative unless it is identically zero. -/ @[protect_proj] class lie_ring (L : Type v) extends add_comm_group L, has_bracket L := (add_lie : ∀ (x y z : L), ⁅x + y, z⁆ = ⁅x, z⁆ + ⁅y, z⁆) (lie_add : ∀ (x y z : L), ⁅z, x + y⁆ = ⁅z, x⁆ + ⁅z, y⁆) (lie_self : ∀ (x : L), ⁅x, x⁆ = 0) (jacobi : ∀ (x y z : L), ⁅x, ⁅y, z⁆⁆ + ⁅y, ⁅z, x⁆⁆ + ⁅z, ⁅x, y⁆⁆ = 0) end prio section lie_ring variables {L : Type v} [lie_ring L] @[simp] lemma add_lie (x y z : L) : ⁅x + y, z⁆ = ⁅x, z⁆ + ⁅y, z⁆ := lie_ring.add_lie x y z @[simp] lemma lie_add (x y z : L) : ⁅z, x + y⁆ = ⁅z, x⁆ + ⁅z, y⁆ := lie_ring.lie_add x y z @[simp] lemma lie_self (x : L) : ⁅x, x⁆ = 0 := lie_ring.lie_self x @[simp] lemma lie_skew (x y : L) : -⁅y, x⁆ = ⁅x, y⁆ := begin symmetry, rw [←sub_eq_zero_iff_eq, sub_neg_eq_add], have H : ⁅x + y, x + y⁆ = 0, from lie_self _, rw add_lie at H, simpa using H, end @[simp] lemma lie_zero (x : L) : ⁅x, 0⁆ = 0 := begin have H : ⁅x, 0⁆ + ⁅x, 0⁆ = ⁅x, 0⁆ + 0 := by { rw ←lie_add, simp, }, exact add_left_cancel H, end @[simp] lemma zero_lie (x : L) : ⁅0, x⁆ = 0 := by { rw [←lie_skew, lie_zero], simp, } @[simp] lemma neg_lie (x y : L) : ⁅-x, y⁆ = -⁅x, y⁆ := by { rw [←sub_eq_zero_iff_eq, sub_neg_eq_add, ←add_lie], simp, } @[simp] lemma lie_neg (x y : L) : ⁅x, -y⁆ = -⁅x, y⁆ := by { rw [←lie_skew, ←lie_skew], simp, } @[simp] lemma gsmul_lie (x y : L) (n : ℤ) : ⁅n • x, y⁆ = n • ⁅x, y⁆ := add_monoid_hom.map_gsmul ⟨λ x, ⁅x, y⁆, zero_lie y, λ _ _, add_lie _ _ _⟩ _ _ @[simp] lemma lie_gsmul (x y : L) (n : ℤ) : ⁅x, n • y⁆ = n • ⁅x, y⁆ := begin rw [←lie_skew, ←lie_skew x, gsmul_lie], unfold has_scalar.smul, rw gsmul_neg, end /-- An associative ring gives rise to a Lie ring by taking the bracket to be the ring commutator. -/ def lie_ring.of_associative_ring (A : Type v) [ring A] : lie_ring A := { bracket := ring_commutator.commutator, add_lie := ring_commutator.add_left, lie_add := ring_commutator.add_right, lie_self := ring_commutator.alternate, jacobi := ring_commutator.jacobi } local attribute [instance] lie_ring.of_associative_ring lemma lie_ring.of_associative_ring_bracket (A : Type v) [ring A] (x y : A) : ⁅x, y⁆ = x*y - y*x := rfl lemma commutative_ring_iff_abelian_lie_ring (A : Type v) [ring A] : is_commutative A (*) ↔ lie_algebra.is_abelian A := begin have h₁ : is_commutative A (*) ↔ ∀ (a b : A), a * b = b * a := ⟨λ h, h.1, λ h, ⟨h⟩⟩, have h₂ : lie_algebra.is_abelian A ↔ ∀ (a b : A), ⁅a, b⁆ = 0 := ⟨λ h, h.1, λ h, ⟨h⟩⟩, simp only [h₁, h₂, lie_ring.of_associative_ring_bracket, sub_eq_zero], end end lie_ring section prio set_option default_priority 100 -- see Note [default priority] /-- A Lie algebra is a module with compatible product, known as the bracket, satisfying the Jacobi identity. Forgetting the scalar multiplication, every Lie algebra is a Lie ring. -/ class lie_algebra (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] extends semimodule R L := (lie_smul : ∀ (t : R) (x y : L), ⁅x, t • y⁆ = t • ⁅x, y⁆) end prio @[simp] lemma lie_smul (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L] (t : R) (x y : L) : ⁅x, t • y⁆ = t • ⁅x, y⁆ := lie_algebra.lie_smul t x y @[simp] lemma smul_lie (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L] (t : R) (x y : L) : ⁅t • x, y⁆ = t • ⁅x, y⁆ := by { rw [←lie_skew, ←lie_skew x y], simp [-lie_skew], } namespace lie_algebra set_option old_structure_cmd true /-- A morphism of Lie algebras is a linear map respecting the bracket operations. -/ structure morphism (R : Type u) (L : Type v) (L' : Type w) [comm_ring R] [lie_ring L] [lie_algebra R L] [lie_ring L'] [lie_algebra R L'] extends linear_map R L L' := (map_lie : ∀ {x y : L}, to_fun ⁅x, y⁆ = ⁅to_fun x, to_fun y⁆) attribute [nolint doc_blame] lie_algebra.morphism.to_linear_map infixr ` →ₗ⁅⁆ `:25 := morphism _ notation L ` →ₗ⁅`:25 R:25 `⁆ `:0 L':0 := morphism R L L' section morphism_properties variables {R : Type u} {L₁ : Type v} {L₂ : Type w} {L₃ : Type w₁} variables [comm_ring R] [lie_ring L₁] [lie_ring L₂] [lie_ring L₃] variables [lie_algebra R L₁] [lie_algebra R L₂] [lie_algebra R L₃] instance : has_coe (L₁ →ₗ⁅R⁆ L₂) (L₁ →ₗ[R] L₂) := ⟨morphism.to_linear_map⟩ /-- see Note [function coercion] -/ instance : has_coe_to_fun (L₁ →ₗ⁅R⁆ L₂) := ⟨_, morphism.to_fun⟩ @[simp] lemma map_lie (f : L₁ →ₗ⁅R⁆ L₂) (x y : L₁) : f ⁅x, y⁆ = ⁅f x, f y⁆ := morphism.map_lie f /-- The constant 0 map is a Lie algebra morphism. -/ instance : has_zero (L₁ →ₗ⁅R⁆ L₂) := ⟨{ map_lie := by simp, ..(0 : L₁ →ₗ[R] L₂)}⟩ /-- The identity map is a Lie algebra morphism. -/ instance : has_one (L₁ →ₗ⁅R⁆ L₁) := ⟨{ map_lie := by simp, ..(1 : L₁ →ₗ[R] L₁)}⟩ instance : inhabited (L₁ →ₗ⁅R⁆ L₂) := ⟨0⟩ /-- The composition of morphisms is a morphism. -/ def morphism.comp (f : L₂ →ₗ⁅R⁆ L₃) (g : L₁ →ₗ⁅R⁆ L₂) : L₁ →ₗ⁅R⁆ L₃ := { map_lie := λ x y, by { change f (g ⁅x, y⁆) = ⁅f (g x), f (g y)⁆, rw [map_lie, map_lie], }, ..linear_map.comp f.to_linear_map g.to_linear_map } lemma morphism.comp_apply (f : L₂ →ₗ⁅R⁆ L₃) (g : L₁ →ₗ⁅R⁆ L₂) (x : L₁) : f.comp g x = f (g x) := rfl /-- The inverse of a bijective morphism is a morphism. -/ def morphism.inverse (f : L₁ →ₗ⁅R⁆ L₂) (g : L₂ → L₁) (h₁ : function.left_inverse g f) (h₂ : function.right_inverse g f) : L₂ →ₗ⁅R⁆ L₁ := { map_lie := λ x y, by { calc g ⁅x, y⁆ = g ⁅f (g x), f (g y)⁆ : by { conv_lhs { rw [←h₂ x, ←h₂ y], }, } ... = g (f ⁅g x, g y⁆) : by rw map_lie ... = ⁅g x, g y⁆ : (h₁ _), }, ..linear_map.inverse f.to_linear_map g h₁ h₂ } end morphism_properties /-- An equivalence of Lie algebras is a morphism which is also a linear equivalence. We could instead define an equivalence to be a morphism which is also a (plain) equivalence. However it is more convenient to define via linear equivalence to get `.to_linear_equiv` for free. -/ structure equiv (R : Type u) (L : Type v) (L' : Type w) [comm_ring R] [lie_ring L] [lie_algebra R L] [lie_ring L'] [lie_algebra R L'] extends L →ₗ⁅R⁆ L', L ≃ₗ[R] L' attribute [nolint doc_blame] lie_algebra.equiv.to_morphism attribute [nolint doc_blame] lie_algebra.equiv.to_linear_equiv notation L ` ≃ₗ⁅`:50 R `⁆ ` L' := equiv R L L' namespace equiv variables {R : Type u} {L₁ : Type v} {L₂ : Type w} {L₃ : Type w₁} variables [comm_ring R] [lie_ring L₁] [lie_ring L₂] [lie_ring L₃] variables [lie_algebra R L₁] [lie_algebra R L₂] [lie_algebra R L₃] instance has_coe_to_lie_hom : has_coe (L₁ ≃ₗ⁅R⁆ L₂) (L₁ →ₗ⁅R⁆ L₂) := ⟨to_morphism⟩ instance has_coe_to_linear_equiv : has_coe (L₁ ≃ₗ⁅R⁆ L₂) (L₁ ≃ₗ[R] L₂) := ⟨to_linear_equiv⟩ /-- see Note [function coercion] -/ instance : has_coe_to_fun (L₁ ≃ₗ⁅R⁆ L₂) := ⟨_, to_fun⟩ @[simp, norm_cast] lemma coe_to_lie_equiv (e : L₁ ≃ₗ⁅R⁆ L₂) : ((e : L₁ →ₗ⁅R⁆ L₂) : L₁ → L₂) = e := rfl @[simp, norm_cast] lemma coe_to_linear_equiv (e : L₁ ≃ₗ⁅R⁆ L₂) : ((e : L₁ ≃ₗ[R] L₂) : L₁ → L₂) = e := rfl instance : has_one (L₁ ≃ₗ⁅R⁆ L₁) := ⟨{ map_lie := λ x y, by { change ((1 : L₁→ₗ[R] L₁) ⁅x, y⁆) = ⁅(1 : L₁→ₗ[R] L₁) x, (1 : L₁→ₗ[R] L₁) y⁆, simp, }, ..(1 : L₁ ≃ₗ[R] L₁)}⟩ @[simp] lemma one_apply (x : L₁) : (1 : (L₁ ≃ₗ⁅R⁆ L₁)) x = x := rfl instance : inhabited (L₁ ≃ₗ⁅R⁆ L₁) := ⟨1⟩ /-- Lie algebra equivalences are reflexive. -/ @[refl] def refl : L₁ ≃ₗ⁅R⁆ L₁ := 1 @[simp] lemma refl_apply (x : L₁) : (refl : L₁ ≃ₗ⁅R⁆ L₁) x = x := rfl /-- Lie algebra equivalences are symmetric. -/ @[symm] def symm (e : L₁ ≃ₗ⁅R⁆ L₂) : L₂ ≃ₗ⁅R⁆ L₁ := { ..morphism.inverse e.to_morphism e.inv_fun e.left_inv e.right_inv, ..e.to_linear_equiv.symm } @[simp] lemma symm_symm (e : L₁ ≃ₗ⁅R⁆ L₂) : e.symm.symm = e := by { cases e, refl, } @[simp] lemma apply_symm_apply (e : L₁ ≃ₗ⁅R⁆ L₂) : ∀ x, e (e.symm x) = x := e.to_linear_equiv.apply_symm_apply @[simp] lemma symm_apply_apply (e : L₁ ≃ₗ⁅R⁆ L₂) : ∀ x, e.symm (e x) = x := e.to_linear_equiv.symm_apply_apply /-- Lie algebra equivalences are transitive. -/ @[trans] def trans (e₁ : L₁ ≃ₗ⁅R⁆ L₂) (e₂ : L₂ ≃ₗ⁅R⁆ L₃) : L₁ ≃ₗ⁅R⁆ L₃ := { ..morphism.comp e₂.to_morphism e₁.to_morphism, ..linear_equiv.trans e₁.to_linear_equiv e₂.to_linear_equiv } @[simp] lemma trans_apply (e₁ : L₁ ≃ₗ⁅R⁆ L₂) (e₂ : L₂ ≃ₗ⁅R⁆ L₃) (x : L₁) : (e₁.trans e₂) x = e₂ (e₁ x) := rfl @[simp] lemma symm_trans_apply (e₁ : L₁ ≃ₗ⁅R⁆ L₂) (e₂ : L₂ ≃ₗ⁅R⁆ L₃) (x : L₃) : (e₁.trans e₂).symm x = e₁.symm (e₂.symm x) := rfl end equiv namespace direct_sum open dfinsupp variables {R : Type u} [comm_ring R] variables {ι : Type v} [decidable_eq ι] {L : ι → Type w} variables [Π i, lie_ring (L i)] [Π i, lie_algebra R (L i)] /-- The direct sum of Lie rings carries a natural Lie ring structure. -/ instance : lie_ring (direct_sum ι L) := { bracket := zip_with (λ i, λ x y, ⁅x, y⁆) (λ i, lie_zero 0), add_lie := λ x y z, by { ext, simp only [zip_with_apply, add_apply, add_lie], }, lie_add := λ x y z, by { ext, simp only [zip_with_apply, add_apply, lie_add], }, lie_self := λ x, by { ext, simp only [zip_with_apply, add_apply, lie_self, zero_apply], }, jacobi := λ x y z, by { ext, simp only [zip_with_apply, add_apply, lie_ring.jacobi, zero_apply], }, ..(infer_instance : add_comm_group _) } @[simp] lemma bracket_apply {x y : direct_sum ι L} {i : ι} : ⁅x, y⁆ i = ⁅x i, y i⁆ := zip_with_apply /-- The direct sum of Lie algebras carries a natural Lie algebra structure. -/ instance : lie_algebra R (direct_sum ι L) := { lie_smul := λ c x y, by { ext, simp only [zip_with_apply, smul_apply, bracket_apply, lie_smul], }, ..(infer_instance : module R _) } end direct_sum variables {R : Type u} {L : Type v} [comm_ring R] [lie_ring L] [lie_algebra R L] /-- An associative algebra gives rise to a Lie algebra by taking the bracket to be the ring commutator. -/ def of_associative_algebra (A : Type v) [ring A] [algebra R A] : @lie_algebra R A _ (lie_ring.of_associative_ring _) := { lie_smul := λ t x y, by rw [lie_ring.of_associative_ring_bracket, lie_ring.of_associative_ring_bracket, algebra.mul_smul_comm, algebra.smul_mul_assoc, smul_sub], } instance (M : Type v) [add_comm_group M] [module R M] : lie_ring (module.End R M) := lie_ring.of_associative_ring _ local attribute [instance] lie_ring.of_associative_ring local attribute [instance] lie_algebra.of_associative_algebra /-- The map `of_associative_algebra` associating a Lie algebra to an associative algebra is functorial. -/ def of_associative_algebra_hom {R : Type u} {A : Type v} {B : Type w} [comm_ring R] [ring A] [ring B] [algebra R A] [algebra R B] (f : A →ₐ[R] B) : A →ₗ⁅R⁆ B := { map_lie := λ x y, show f ⁅x,y⁆ = ⁅f x,f y⁆, by simp only [lie_ring.of_associative_ring_bracket, alg_hom.map_sub, alg_hom.map_mul], ..f.to_linear_map, } @[simp] lemma of_associative_algebra_hom_id {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] : of_associative_algebra_hom (alg_hom.id R A) = 1 := rfl @[simp] lemma of_associative_algebra_hom_comp {R : Type u} {A : Type v} {B : Type w} {C : Type w₁} [comm_ring R] [ring A] [ring B] [ring C] [algebra R A] [algebra R B] [algebra R C] (f : A →ₐ[R] B) (g : B →ₐ[R] C) : of_associative_algebra_hom (g.comp f) = (of_associative_algebra_hom g).comp (of_associative_algebra_hom f) := rfl /-- An important class of Lie algebras are those arising from the associative algebra structure on module endomorphisms. -/ instance of_endomorphism_algebra (M : Type v) [add_comm_group M] [module R M] : lie_algebra R (module.End R M) := of_associative_algebra (module.End R M) lemma endo_algebra_bracket (M : Type v) [add_comm_group M] [module R M] (f g : module.End R M) : ⁅f, g⁆ = f.comp g - g.comp f := rfl /-- The adjoint action of a Lie algebra on itself. -/ def Ad : L →ₗ⁅R⁆ module.End R L := { to_fun := λ x, { to_fun := has_bracket.bracket x, map_add' := by { intros, apply lie_add, }, map_smul' := by { intros, apply lie_smul, } }, map_add' := by { intros, ext, simp, }, map_smul' := by { intros, ext, simp, }, map_lie := by { intros x y, ext z, rw endo_algebra_bracket, suffices : ⁅⁅x, y⁆, z⁆ = ⁅x, ⁅y, z⁆⁆ + ⁅⁅x, z⁆, y⁆, by simpa [sub_eq_add_neg], rw [eq_comm, ←lie_skew ⁅x, y⁆ z, ←lie_skew ⁅x, z⁆ y, ←lie_skew x z, lie_neg, neg_neg, ←sub_eq_zero_iff_eq, sub_neg_eq_add, lie_ring.jacobi], } } end lie_algebra section lie_subalgebra variables (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L] set_option old_structure_cmd true /-- A Lie subalgebra of a Lie algebra is submodule that is closed under the Lie bracket. This is a sufficient condition for the subset itself to form a Lie algebra. -/ structure lie_subalgebra extends submodule R L := (lie_mem : ∀ {x y}, x ∈ carrier → y ∈ carrier → ⁅x, y⁆ ∈ carrier) attribute [nolint doc_blame] lie_subalgebra.to_submodule /-- The zero algebra is a subalgebra of any Lie algebra. -/ instance : has_zero (lie_subalgebra R L) := ⟨{ lie_mem := λ x y hx hy, by { rw [((submodule.mem_bot R).1 hx), zero_lie], exact submodule.zero_mem (0 : submodule R L), }, ..(0 : submodule R L) }⟩ instance : inhabited (lie_subalgebra R L) := ⟨0⟩ instance : has_coe (lie_subalgebra R L) (set L) := ⟨lie_subalgebra.carrier⟩ instance : has_mem L (lie_subalgebra R L) := ⟨λ x L', x ∈ (L' : set L)⟩ instance lie_subalgebra_coe_submodule : has_coe (lie_subalgebra R L) (submodule R L) := ⟨lie_subalgebra.to_submodule⟩ /-- A Lie subalgebra forms a new Lie ring. -/ instance lie_subalgebra_lie_ring (L' : lie_subalgebra R L) : lie_ring L' := { bracket := λ x y, ⟨⁅x.val, y.val⁆, L'.lie_mem x.property y.property⟩, lie_add := by { intros, apply set_coe.ext, apply lie_add, }, add_lie := by { intros, apply set_coe.ext, apply add_lie, }, lie_self := by { intros, apply set_coe.ext, apply lie_self, }, jacobi := by { intros, apply set_coe.ext, apply lie_ring.jacobi, } } /-- A Lie subalgebra forms a new Lie algebra. -/ instance lie_subalgebra_lie_algebra (L' : lie_subalgebra R L) : @lie_algebra R L' _ (lie_subalgebra_lie_ring _ _ _) := { lie_smul := by { intros, apply set_coe.ext, apply lie_smul } } @[simp] lemma lie_subalgebra.mem_coe {L' : lie_subalgebra R L} {x : L} : x ∈ (L' : set L) ↔ x ∈ L' := iff.rfl @[simp] lemma lie_subalgebra.mem_coe' {L' : lie_subalgebra R L} {x : L} : x ∈ (L' : submodule R L) ↔ x ∈ L' := iff.rfl @[simp, norm_cast] lemma lie_subalgebra.coe_bracket (L' : lie_subalgebra R L) (x y : L') : (↑⁅x, y⁆ : L) = ⁅↑x, ↑y⁆ := rfl @[ext] lemma lie_subalgebra.ext (L₁' L₂' : lie_subalgebra R L) (h : ∀ x, x ∈ L₁' ↔ x ∈ L₂') : L₁' = L₂' := by { cases L₁', cases L₂', simp only [], ext x, exact h x, } lemma lie_subalgebra.ext_iff (L₁' L₂' : lie_subalgebra R L) : L₁' = L₂' ↔ ∀ x, x ∈ L₁' ↔ x ∈ L₂' := ⟨λ h x, by rw h, lie_subalgebra.ext R L L₁' L₂'⟩ local attribute [instance] lie_ring.of_associative_ring local attribute [instance] lie_algebra.of_associative_algebra /-- A subalgebra of an associative algebra is a Lie subalgebra of the associated Lie algebra. -/ def lie_subalgebra_of_subalgebra (A : Type v) [ring A] [algebra R A] (A' : subalgebra R A) : lie_subalgebra R A := { lie_mem := λ x y hx hy, by { change ⁅x, y⁆ ∈ A', change x ∈ A' at hx, change y ∈ A' at hy, rw lie_ring.of_associative_ring_bracket, have hxy := A'.mul_mem hx hy, have hyx := A'.mul_mem hy hx, exact submodule.sub_mem A'.to_submodule hxy hyx, }, ..A'.to_submodule } variables {R L} {L₂ : Type w} [lie_ring L₂] [lie_algebra R L₂] /-- The embedding of a Lie subalgebra into the ambient space as a Lie morphism. -/ def lie_subalgebra.incl (L' : lie_subalgebra R L) : L' →ₗ⁅R⁆ L := { map_lie := λ x y, by { rw [linear_map.to_fun_eq_coe, submodule.subtype_apply], refl, }, ..L'.to_submodule.subtype } /-- The range of a morphism of Lie algebras is a Lie subalgebra. -/ def lie_algebra.morphism.range (f : L →ₗ⁅R⁆ L₂) : lie_subalgebra R L₂ := { lie_mem := λ x y, show x ∈ f.to_linear_map.range → y ∈ f.to_linear_map.range → ⁅x, y⁆ ∈ f.to_linear_map.range, by { repeat { rw linear_map.mem_range }, rintros ⟨x', hx⟩ ⟨y', hy⟩, refine ⟨⁅x', y'⁆, _⟩, rw [←hx, ←hy], change f ⁅x', y'⁆ = ⁅f x', f y'⁆, rw lie_algebra.map_lie, }, ..f.to_linear_map.range } @[simp] lemma lie_algebra.morphism.range_bracket (f : L →ₗ⁅R⁆ L₂) (x y : f.range) : (↑⁅x, y⁆ : L₂) = ⁅↑x, ↑y⁆ := rfl /-- The image of a Lie subalgebra under a Lie algebra morphism is a Lie subalgebra of the codomain. -/ def lie_subalgebra.map (f : L →ₗ⁅R⁆ L₂) (L' : lie_subalgebra R L) : lie_subalgebra R L₂ := { lie_mem := λ x y hx hy, by { erw submodule.mem_map at hx, rcases hx with ⟨x', hx', hx⟩, rw ←hx, erw submodule.mem_map at hy, rcases hy with ⟨y', hy', hy⟩, rw ←hy, erw submodule.mem_map, exact ⟨⁅x', y'⁆, L'.lie_mem hx' hy', lie_algebra.map_lie f x' y'⟩, }, ..((L' : submodule R L).map (f : L →ₗ[R] L₂))} @[simp] lemma lie_subalgebra.mem_map_submodule (e : L ≃ₗ⁅R⁆ L₂) (L' : lie_subalgebra R L) (x : L₂) : x ∈ L'.map (e : L →ₗ⁅R⁆ L₂) ↔ x ∈ (L' : submodule R L).map (e : L →ₗ[R] L₂) := by refl end lie_subalgebra namespace lie_algebra variables {R : Type u} {L₁ : Type v} {L₂ : Type w} variables [comm_ring R] [lie_ring L₁] [lie_ring L₂] [lie_algebra R L₁] [lie_algebra R L₂] namespace equiv /-- An injective Lie algebra morphism is an equivalence onto its range. -/ noncomputable def of_injective (f : L₁ →ₗ⁅R⁆ L₂) (h : function.injective f) : L₁ ≃ₗ⁅R⁆ f.range := have h' : (f : L₁ →ₗ[R] L₂).ker = ⊥ := linear_map.ker_eq_bot_of_injective h, { map_lie := λ x y, by { apply set_coe.ext, simp only [linear_equiv.of_injective_apply, lie_algebra.morphism.range_bracket], apply f.map_lie, }, ..(linear_equiv.of_injective ↑f h')} @[simp] lemma of_injective_apply (f : L₁ →ₗ⁅R⁆ L₂) (h : function.injective f) (x : L₁) : ↑(of_injective f h x) = f x := rfl variables (L₁' L₁'' : lie_subalgebra R L₁) (L₂' : lie_subalgebra R L₂) /-- Lie subalgebras that are equal as sets are equivalent as Lie algebras. -/ def of_eq (h : (L₁' : set L₁) = L₁'') : L₁' ≃ₗ⁅R⁆ L₁'' := { map_lie := λ x y, by { apply set_coe.ext, simp, }, ..(linear_equiv.of_eq ↑L₁' ↑L₁'' (by {ext x, change x ∈ (L₁' : set L₁) ↔ x ∈ (L₁'' : set L₁), rw h, } )) } @[simp] lemma of_eq_apply (L L' : lie_subalgebra R L₁) (h : (L : set L₁) = L') (x : L) : (↑(of_eq L L' h x) : L₁) = x := rfl variables (e : L₁ ≃ₗ⁅R⁆ L₂) /-- An equivalence of Lie algebras restricts to an equivalence from any Lie subalgebra onto its image. -/ def of_subalgebra : L₁'' ≃ₗ⁅R⁆ (L₁''.map e : lie_subalgebra R L₂) := { map_lie := λ x y, by { apply set_coe.ext, exact lie_algebra.map_lie (↑e : L₁ →ₗ⁅R⁆ L₂) ↑x ↑y, } ..(linear_equiv.of_submodule (e : L₁ ≃ₗ[R] L₂) ↑L₁'') } @[simp] lemma of_subalgebra_apply (x : L₁'') : ↑(e.of_subalgebra _ x) = e x := rfl /-- An equivalence of Lie algebras restricts to an equivalence from any Lie subalgebra onto its image. -/ def of_subalgebras (h : L₁'.map ↑e = L₂') : L₁' ≃ₗ⁅R⁆ L₂' := { map_lie := λ x y, by { apply set_coe.ext, exact lie_algebra.map_lie (↑e : L₁ →ₗ⁅R⁆ L₂) ↑x ↑y, }, ..(linear_equiv.of_submodules (e : L₁ ≃ₗ[R] L₂) ↑L₁' ↑L₂' (by { rw ←h, refl, })) } @[simp] lemma of_subalgebras_apply (h : L₁'.map ↑e = L₂') (x : L₁') : ↑(e.of_subalgebras _ _ h x) = e x := rfl @[simp] lemma of_subalgebras_symm_apply (h : L₁'.map ↑e = L₂') (x : L₂') : ↑((e.of_subalgebras _ _ h).symm x) = e.symm x := rfl end equiv end lie_algebra section lie_module variables (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L] variables (M : Type v) [add_comm_group M] [module R M] section prio set_option default_priority 100 -- see Note [default priority] /-- A Lie module is a module over a commutative ring, together with a linear action of a Lie algebra on this module, such that the Lie bracket acts as the commutator of endomorphisms. -/ class lie_module extends linear_action R L M := (lie_act : ∀ (l l' : L) (m : M), act ⁅l, l'⁆ m = act l (act l' m) - act l' (act l m)) end prio @[simp] lemma lie_act [lie_module R L M] (l l' : L) (m : M) : linear_action.act R ⁅l, l'⁆ m = linear_action.act R l (linear_action.act R l' m) - linear_action.act R l' (linear_action.act R l m) := lie_module.lie_act l l' m protected lemma of_endo_map_action (α : L →ₗ⁅R⁆ module.End R M) (x : L) (m : M) : @linear_action.act R _ _ _ _ _ _ _ (linear_action.of_endo_map R L M α) x m = α x m := rfl /-- A Lie morphism from a Lie algebra to the endomorphism algebra of a module yields a Lie module structure. -/ def lie_module.of_endo_morphism (α : L →ₗ⁅R⁆ module.End R M) : lie_module R L M := { lie_act := by { intros x y m, rw [of_endo_map_action, lie_algebra.map_lie, lie_algebra.endo_algebra_bracket], refl, }, ..(linear_action.of_endo_map R L M α) } /-- Every Lie algebra is a module over itself. -/ instance lie_algebra_self_module : lie_module R L L := lie_module.of_endo_morphism R L L lie_algebra.Ad /-- A Lie submodule of a Lie module is a submodule that is closed under the Lie bracket. This is a sufficient condition for the subset itself to form a Lie module. -/ structure lie_submodule [lie_module R L M] extends submodule R M := (lie_mem : ∀ {x : L} {m : M}, m ∈ carrier → linear_action.act R x m ∈ carrier) /-- The zero module is a Lie submodule of any Lie module. -/ instance [lie_module R L M] : has_zero (lie_submodule R L M) := ⟨{ lie_mem := λ x m h, by { rw [((submodule.mem_bot R).1 h), linear_action_zero], exact submodule.zero_mem (0 : submodule R M), }, ..(0 : submodule R M)}⟩ instance [lie_module R L M] : inhabited (lie_submodule R L M) := ⟨0⟩ instance lie_submodule_coe_submodule [lie_module R L M] : has_coe (lie_submodule R L M) (submodule R M) := ⟨lie_submodule.to_submodule⟩ instance lie_submodule_has_mem [lie_module R L M] : has_mem M (lie_submodule R L M) := ⟨λ x N, x ∈ (N : set M)⟩ instance lie_submodule_lie_module [lie_module R L M] (N : lie_submodule R L M) : lie_module R L N := { act := λ x m, ⟨linear_action.act R x m.val, N.lie_mem m.property⟩, add_act := by { intros x y m, apply set_coe.ext, apply linear_action.add_act, }, act_add := by { intros x m n, apply set_coe.ext, apply linear_action.act_add, }, act_smul := by { intros r x y, apply set_coe.ext, apply linear_action.act_smul, }, smul_act := by { intros r x y, apply set_coe.ext, apply linear_action.smul_act, }, lie_act := by { intros x y m, apply set_coe.ext, apply lie_module.lie_act, } } /-- An ideal of a Lie algebra is a Lie submodule of the Lie algebra as a Lie module over itself. -/ abbreviation lie_ideal := lie_submodule R L L lemma lie_mem_right (I : lie_ideal R L) (x y : L) (h : y ∈ I) : ⁅x, y⁆ ∈ I := I.lie_mem h lemma lie_mem_left (I : lie_ideal R L) (x y : L) (h : x ∈ I) : ⁅x, y⁆ ∈ I := by { rw [←lie_skew, ←neg_lie], apply lie_mem_right, assumption, } /-- An ideal of a Lie algebra is a Lie subalgebra. -/ def lie_ideal_subalgebra (I : lie_ideal R L) : lie_subalgebra R L := { lie_mem := by { intros x y hx hy, apply lie_mem_right, exact hy, }, ..I.to_submodule, } /-- A Lie module is irreducible if its only non-trivial Lie submodule is itself. -/ class lie_module.is_irreducible [lie_module R L M] : Prop := (irreducible : ∀ (M' : lie_submodule R L M), (∃ (m : M'), m ≠ 0) → (∀ (m : M), m ∈ M')) /-- A Lie algebra is simple if it is irreducible as a Lie module over itself via the adjoint action, and it is non-Abelian. -/ class lie_algebra.is_simple : Prop := (simple : lie_module.is_irreducible R L L ∧ ¬lie_algebra.is_abelian L) end lie_module namespace lie_submodule variables {R : Type u} {L : Type v} [comm_ring R] [lie_ring L] [lie_algebra R L] variables {M : Type v} [add_comm_group M] [module R M] [α : lie_module R L M] variables (N : lie_submodule R L M) (I : lie_ideal R L) /-- The quotient of a Lie module by a Lie submodule. It is a Lie module. -/ abbreviation quotient := N.to_submodule.quotient namespace quotient variables {N I} /-- Map sending an element of `M` to the corresponding element of `M/N`, when `N` is a lie_submodule of the lie_module `N`. -/ abbreviation mk : M → N.quotient := submodule.quotient.mk lemma is_quotient_mk (m : M) : quotient.mk' m = (mk m : N.quotient) := rfl /-- Given a Lie module `M` over a Lie algebra `L`, together with a Lie submodule `N ⊆ M`, there is a natural linear map from `L` to the endomorphisms of `M` leaving `N` invariant. -/ def lie_submodule_invariant : L →ₗ[R] submodule.compatible_maps N.to_submodule N.to_submodule := linear_map.cod_restrict _ (α.to_linear_action.to_endo_map _ _ _) N.lie_mem instance lie_quotient_action : linear_action R L N.quotient := linear_action.of_endo_map _ _ _ (linear_map.comp (submodule.mapq_linear N N) lie_submodule_invariant) lemma lie_quotient_action_apply (z : L) (m : M) : linear_action.act R z (mk m : N.quotient) = mk (linear_action.act R z m) := rfl /-- The quotient of a Lie module by a Lie submodule, is a Lie module. -/ instance lie_quotient_lie_module : lie_module R L N.quotient := { lie_act := λ x y m', by { apply quotient.induction_on' m', intros m, rw is_quotient_mk, repeat { rw lie_quotient_action_apply, }, rw lie_act, refl, }, ..quotient.lie_quotient_action, } instance lie_quotient_has_bracket : has_bracket (quotient I) := ⟨by { intros x y, apply quotient.lift_on₂' x y (λ x' y', mk ⁅x', y'⁆), intros x₁ x₂ y₁ y₂ h₁ h₂, apply (submodule.quotient.eq I.to_submodule).2, have h : ⁅x₁, x₂⁆ - ⁅y₁, y₂⁆ = ⁅x₁, x₂ - y₂⁆ + ⁅x₁ - y₁, y₂⁆ := by simp [-lie_skew, sub_eq_add_neg, add_assoc], rw h, apply submodule.add_mem, { apply lie_mem_right R L I x₁ (x₂ - y₂) h₂, }, { apply lie_mem_left R L I (x₁ - y₁) y₂ h₁, }, }⟩ @[simp] lemma mk_bracket (x y : L) : (mk ⁅x, y⁆ : quotient I) = ⁅mk x, mk y⁆ := rfl instance lie_quotient_lie_ring : lie_ring (quotient I) := { add_lie := by { intros x' y' z', apply quotient.induction_on₃' x' y' z', intros x y z, repeat { rw is_quotient_mk <|> rw ←mk_bracket <|> rw ←submodule.quotient.mk_add, }, apply congr_arg, apply add_lie, }, lie_add := by { intros x' y' z', apply quotient.induction_on₃' x' y' z', intros x y z, repeat { rw is_quotient_mk <|> rw ←mk_bracket <|> rw ←submodule.quotient.mk_add, }, apply congr_arg, apply lie_add, }, lie_self := by { intros x', apply quotient.induction_on' x', intros x, rw [is_quotient_mk, ←mk_bracket], apply congr_arg, apply lie_self, }, jacobi := by { intros x' y' z', apply quotient.induction_on₃' x' y' z', intros x y z, repeat { rw is_quotient_mk <|> rw ←mk_bracket <|> rw ←submodule.quotient.mk_add, }, apply congr_arg, apply lie_ring.jacobi, } } instance lie_quotient_lie_algebra : lie_algebra R (quotient I) := { lie_smul := by { intros t x' y', apply quotient.induction_on₂' x' y', intros x y, repeat { rw is_quotient_mk <|> rw ←mk_bracket <|> rw ←submodule.quotient.mk_smul, }, apply congr_arg, apply lie_smul, } } end quotient end lie_submodule namespace linear_equiv variables {R : Type u} {M₁ : Type v} {M₂ : Type w} variables [comm_ring R] [add_comm_group M₁] [module R M₁] [add_comm_group M₂] [module R M₂] variables (e : M₁ ≃ₗ[R] M₂) /-- A linear equivalence of two modules induces a Lie algebra equivalence of their endomorphisms. -/ def lie_conj : module.End R M₁ ≃ₗ⁅R⁆ module.End R M₂ := { map_lie := λ f g, show e.conj ⁅f, g⁆ = ⁅e.conj f, e.conj g⁆, by simp only [lie_algebra.endo_algebra_bracket, e.conj_comp, linear_equiv.map_sub], ..e.conj } @[simp] lemma lie_conj_apply (f : module.End R M₁) : e.lie_conj f = e.conj f := rfl @[simp] lemma lie_conj_symm : e.lie_conj.symm = e.symm.lie_conj := rfl end linear_equiv section matrices open_locale matrix variables {R : Type u} [comm_ring R] variables {n : Type w} [fintype n] [decidable_eq n] /-- An important class of Lie rings are those arising from the associative algebra structure on square matrices over a commutative ring. -/ def matrix.lie_ring : lie_ring (matrix n n R) := lie_ring.of_associative_ring (matrix n n R) local attribute [instance] matrix.lie_ring /-- An important class of Lie algebras are those arising from the associative algebra structure on square matrices over a commutative ring. -/ def matrix.lie_algebra : lie_algebra R (matrix n n R) := lie_algebra.of_associative_algebra (matrix n n R) local attribute [instance] matrix.lie_algebra /-- The natural equivalence between linear endomorphisms of finite free modules and square matrices is compatible with the Lie algebra structures. -/ def lie_equiv_matrix' : module.End R (n → R) ≃ₗ⁅R⁆ matrix n n R := { map_lie := λ T S, begin let f := @linear_map.to_matrixₗ n n _ _ R _ _, change f (T.comp S - S.comp T) = (f T) * (f S) - (f S) * (f T), have h : ∀ (T S : module.End R _), f (T.comp S) = (f T) ⬝ (f S) := matrix.comp_to_matrix_mul, rw [linear_map.map_sub, h, h, matrix.mul_eq_mul, matrix.mul_eq_mul], end, ..linear_equiv_matrix' } @[simp] lemma lie_equiv_matrix'_apply (f : module.End R (n → R)) : lie_equiv_matrix' f = f.to_matrix := rfl @[simp] lemma lie_equiv_matrix'_symm_apply (A : matrix n n R) : (@lie_equiv_matrix' R _ n _ _).symm A = A.to_lin := rfl /-- An invertible matrix induces a Lie algebra equivalence from the space of matrices to itself. -/ noncomputable def matrix.lie_conj (P : matrix n n R) (h : is_unit P) : matrix n n R ≃ₗ⁅R⁆ matrix n n R := ((@lie_equiv_matrix' R _ n _ _).symm.trans (P.to_linear_equiv h).lie_conj).trans lie_equiv_matrix' @[simp] lemma matrix.lie_conj_apply (P A : matrix n n R) (h : is_unit P) : P.lie_conj h A = P ⬝ A ⬝ P⁻¹ := by simp [linear_equiv.conj_apply, matrix.lie_conj, matrix.comp_to_matrix_mul, to_lin_to_matrix] @[simp] lemma matrix.lie_conj_symm_apply (P A : matrix n n R) (h : is_unit P) : (P.lie_conj h).symm A = P⁻¹ ⬝ A ⬝ P := by simp [linear_equiv.symm_conj_apply, matrix.lie_conj, matrix.comp_to_matrix_mul, to_lin_to_matrix] end matrices section skew_adjoint_endomorphisms open bilin_form variables {R : Type u} {M : Type v} [comm_ring R] [add_comm_group M] [module R M] variables (B : bilin_form R M) lemma bilin_form.is_skew_adjoint_bracket (f g : module.End R M) (hf : f ∈ B.skew_adjoint_submodule) (hg : g ∈ B.skew_adjoint_submodule) : ⁅f, g⁆ ∈ B.skew_adjoint_submodule := begin rw mem_skew_adjoint_submodule at *, have hfg : is_adjoint_pair B B (f * g) (g * f), { rw ←neg_mul_neg g f, exact hf.mul hg, }, have hgf : is_adjoint_pair B B (g * f) (f * g), { rw ←neg_mul_neg f g, exact hg.mul hf, }, change bilin_form.is_adjoint_pair B B (f * g - g * f) (-(f * g - g * f)), rw neg_sub, exact hfg.sub hgf, end /-- Given an `R`-module `M`, equipped with a bilinear form, the skew-adjoint endomorphisms form a Lie subalgebra of the Lie algebra of endomorphisms. -/ def skew_adjoint_lie_subalgebra : lie_subalgebra R (module.End R M) := { lie_mem := B.is_skew_adjoint_bracket, ..B.skew_adjoint_submodule } variables {N : Type w} [add_comm_group N] [module R N] (e : N ≃ₗ[R] M) /-- An equivalence of modules with bilinear forms gives equivalence of Lie algebras of skew-adjoint endomorphisms. -/ def skew_adjoint_lie_subalgebra_equiv : skew_adjoint_lie_subalgebra (B.comp (↑e : N →ₗ[R] M) ↑e) ≃ₗ⁅R⁆ skew_adjoint_lie_subalgebra B := begin apply lie_algebra.equiv.of_subalgebras _ _ e.lie_conj, ext f, simp only [lie_subalgebra.mem_coe, submodule.mem_map_equiv, lie_subalgebra.mem_map_submodule, coe_coe], exact (bilin_form.is_pair_self_adjoint_equiv (-B) B e f).symm, end @[simp] lemma skew_adjoint_lie_subalgebra_equiv_apply (f : skew_adjoint_lie_subalgebra (B.comp ↑e ↑e)) : ↑(skew_adjoint_lie_subalgebra_equiv B e f) = e.lie_conj f := by simp [skew_adjoint_lie_subalgebra_equiv] @[simp] lemma skew_adjoint_lie_subalgebra_equiv_symm_apply (f : skew_adjoint_lie_subalgebra B) : ↑((skew_adjoint_lie_subalgebra_equiv B e).symm f) = e.symm.lie_conj f := by simp [skew_adjoint_lie_subalgebra_equiv] end skew_adjoint_endomorphisms section skew_adjoint_matrices open_locale matrix variables {R : Type u} {n : Type w} [comm_ring R] [fintype n] [decidable_eq n] variables (J : matrix n n R) local attribute [instance] matrix.lie_ring local attribute [instance] matrix.lie_algebra lemma matrix.lie_transpose (A B : matrix n n R) : ⁅A, B⁆ᵀ = ⁅Bᵀ, Aᵀ⁆ := show (A * B - B * A)ᵀ = (Bᵀ * Aᵀ - Aᵀ * Bᵀ), by simp lemma matrix.is_skew_adjoint_bracket (A B : matrix n n R) (hA : A ∈ skew_adjoint_matrices_submodule J) (hB : B ∈ skew_adjoint_matrices_submodule J) : ⁅A, B⁆ ∈ skew_adjoint_matrices_submodule J := begin simp only [mem_skew_adjoint_matrices_submodule] at *, change ⁅A, B⁆ᵀ ⬝ J = J ⬝ -⁅A, B⁆, change Aᵀ ⬝ J = J ⬝ -A at hA, change Bᵀ ⬝ J = J ⬝ -B at hB, simp only [←matrix.mul_eq_mul] at *, rw [matrix.lie_transpose, lie_ring.of_associative_ring_bracket, lie_ring.of_associative_ring_bracket, sub_mul, mul_assoc, mul_assoc, hA, hB, ←mul_assoc, ←mul_assoc, hA, hB], noncomm_ring, end /-- The Lie subalgebra of skew-adjoint square matrices corresponding to a square matrix `J`. -/ def skew_adjoint_matrices_lie_subalgebra : lie_subalgebra R (matrix n n R) := { lie_mem := J.is_skew_adjoint_bracket, ..(skew_adjoint_matrices_submodule J) } /-- An invertible matrix `P` gives a Lie algebra equivalence between those endomorphisms that are skew-adjoint with respect to a square matrix `J` and those with respect to `PᵀJP`. -/ noncomputable def skew_adjoint_matrices_lie_subalgebra_equiv (P : matrix n n R) (h : is_unit P) : skew_adjoint_matrices_lie_subalgebra J ≃ₗ⁅R⁆ skew_adjoint_matrices_lie_subalgebra (Pᵀ ⬝ J ⬝ P) := lie_algebra.equiv.of_subalgebras _ _ (P.lie_conj h).symm begin ext A, suffices : P.lie_conj h A ∈ skew_adjoint_matrices_submodule J ↔ A ∈ skew_adjoint_matrices_submodule (Pᵀ ⬝ J ⬝ P), { simp only [lie_subalgebra.mem_coe, submodule.mem_map_equiv, lie_subalgebra.mem_map_submodule, coe_coe], exact this, }, simp [matrix.is_skew_adjoint, J.is_adjoint_pair_equiv _ _ P h], end lemma skew_adjoint_matrices_lie_subalgebra_equiv_apply (P : matrix n n R) (h : is_unit P) (A : skew_adjoint_matrices_lie_subalgebra J) : ↑(skew_adjoint_matrices_lie_subalgebra_equiv J P h A) = P⁻¹ ⬝ ↑A ⬝ P := by simp [skew_adjoint_matrices_lie_subalgebra_equiv] end skew_adjoint_matrices
f0307269661d51cdb7684cd9f2e4d057cf0bbc20
9d2e3d5a2e2342a283affd97eead310c3b528a24
/src/exercises_sources/thursday/afternoon/category_theory/exercise10.lean
8095399e9d7669249a0ed53b5cc2a34e98ed880f
[]
permissive
Vtec234/lftcm2020
ad2610ab614beefe44acc5622bb4a7fff9a5ea46
bbbd4c8162f8c2ef602300ab8fdeca231886375d
refs/heads/master
1,668,808,098,623
1,594,989,081,000
1,594,990,079,000
280,423,039
0
0
MIT
1,594,990,209,000
1,594,990,209,000
null
UTF-8
Lean
false
false
1,547
lean
import category_theory.limits.shapes.zero import category_theory.full_subcategory import algebra.homology.chain_complex import data.int.basic /-! (WARNING: this is an incomplete exercise. It's probably doable from this point, but it's more of a lesson/warning about dependent type theory hell than an enjoyable activity.) Let's give a quirky definition of a cochain complex in a category `C` with zero morphisms, as a functor `F` from `(ℤ, ≤)` to `C`, so that `∀ i, F.map (by tidy : i ≤ i+2) = 0`. Let's think of this as a full subcategory of all functors `(ℤ, ≤) ⥤ C`, and realise that natural transformations are exactly chain maps. Finally let's construct an equivalence of categories with the usual definition of chain cocomplex! -/ open category_theory open category_theory.limits -- Anytime we have a `[preorder α]`, we automatically get a `[category.{v} α]` instance, -- in which the morphisms `X ⟶ Y` are defined to be `ulift (plift X ≤ Y)`. -- (We need those annoying `ulift` and `plift` because `X ≤ Y` is a `Prop`, -- and the morphisms spaces of a category need to be in `Type v` for some `v`.) namespace exercise -- We work in the lowest universe, where `ℤ` lives, for convenience. -- If we wanted to work in higher universes we would need to use `ulift ℤ`. variables (C : Type) [category.{0} C] [has_zero_morphisms C] @[derive category] def complex : Type := { F : ℤ ⥤ C // ∀ i : ℤ, F.map (by tidy : i ⟶ i+2) = 0 } def exercise : complex C ≌ cochain_complex C := sorry end exercise
b72e82394ceb9c4ef6b36c3a4d355f7ba8a11115
abbfc359cee49d3c5258b2bbedc2b4d306ec3bdf
/src/tactic/serial.lean
83d72a8f8d6433882030dbf710622295c3440be1
[]
no_license
cipher1024/serialean
565b17241ba7edc4ee564bf0ae175dd15b06a28c
47881e4a6bc0a62cd68520564610b75f8a4fef2c
refs/heads/master
1,585,117,575,599
1,535,783,976,000
1,535,783,976,000
143,501,396
0
0
null
null
null
null
UTF-8
Lean
false
false
2,603
lean
import data.list.basic import tactic.basic namespace tactic meta def is_type (e : expr) : tactic bool := do (expr.sort _) ← infer_type e | pure ff, pure tt meta def list_macros : expr → list (name × list expr) | e := e.fold [] (λ m i s, match m with | (expr.macro m args) := (expr.macro_def_name m, args) :: s | _ := s end) meta def expand_untrusted (tac : tactic unit) : tactic unit := do tgt ← target, mv ← mk_meta_var tgt, gs ← get_goals, set_goals [mv], tac, env ← get_env, pr ← env.unfold_untrusted_macros <$> instantiate_mvars mv, set_goals gs, exact pr meta def binders : expr → tactic (list expr) | (expr.pi n bi d b) := do v ← mk_local' n bi d, (::) v <$> binders (b.instantiate_var v) | _ := pure [] meta def rec_args_count (t c : name) : tactic ℕ := do ct ← mk_const c >>= infer_type, (list.length ∘ list.filter (λ v : expr, v.local_type.is_app_of t)) <$> binders ct meta def match_induct_hyp (n : name) : list expr → list expr → tactic (list $ expr × option expr) | [] [] := pure [] | [] _ := fail "wrong number of inductive hypotheses" | (x :: xs) [] := (::) (x,none) <$> match_induct_hyp xs [] | (x :: xs) (h :: hs) := do t ← infer_type x, if t.is_app_of n then (::) (x,h) <$> match_induct_hyp xs hs else (::) (x,none) <$> match_induct_hyp xs (h :: hs) meta def is_recursive_type (n : name) : tactic bool := do e ← get_env, let cs := e.constructors_of n, rs ← cs.mmap (rec_args_count n), pure $ rs.any (λ r, r > 0) meta def better_induction (e : expr) : tactic $ list (name × list (expr × option expr) × list (name × expr)) := do t ← infer_type e, let tn := t.get_app_fn.const_name, focus1 $ do vs ← induction e, gs ← get_goals, vs' ← mzip_with (λ g (pat : name × list expr × list (name × expr)), do let ⟨n,args,σ⟩ := pat, set_goals [g], nrec ← rec_args_count tn n, let ⟨args,rec⟩ := args.split_at (args.length - nrec), args ← match_induct_hyp tn args rec, pure ((n,args,σ))) gs vs, set_goals gs, pure vs' meta def extract_def' {α} (n : name) (trusted : bool) (elab_def : tactic α) : tactic α := do cxt ← list.map to_implicit <$> local_context, t ← target, (r,d) ← solve_aux t elab_def, d ← instantiate_mvars d, t' ← pis cxt t, d' ← lambdas cxt d, let univ := t'.collect_univ_params, add_decl $ declaration.defn n univ t' d' (reducibility_hints.regular 1 tt) trusted, r <$ (applyc n; assumption) end tactic
87241a61b23f663de525829de000aaa469f892b9
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/matrix/rank.lean
a803a71acbb7903a644581ca2b68ce4880849ff3
[ "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,686
lean
/- Copyright (c) 2021 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import linear_algebra.free_module.finite.rank /-! # Rank of matrices The rank of a matrix `A` is defined to be the rank of range of the linear map corresponding to `A`. This definition does not depend on the choice of basis, see `matrix.rank_eq_finrank_range_to_lin`. ## Main declarations * `matrix.rank`: the rank of a matrix ## TODO * Show that `matrix.rank` is equal to the row-rank and column-rank * Generalize away from fields -/ open_locale matrix namespace matrix open finite_dimensional variables {m n o K : Type*} [m_fin : fintype m] [fintype n] [fintype o] variables [decidable_eq n] [decidable_eq o] [field K] variables (A : matrix m n K) /-- The rank of a matrix is the rank of its image. -/ noncomputable def rank : ℕ := finrank K A.to_lin'.range @[simp] lemma rank_one : rank (1 : matrix n n K) = fintype.card n := by rw [rank, to_lin'_one, linear_map.range_id, finrank_top, module.free.finrank_pi] @[simp] lemma rank_zero : rank (0 : matrix n n K) = 0 := by rw [rank, linear_equiv.map_zero, linear_map.range_zero, finrank_bot] lemma rank_le_card_width : A.rank ≤ fintype.card n := begin convert le_of_add_le_left (A.to_lin'.finrank_range_add_finrank_ker).le, exact (module.free.finrank_pi K).symm, end lemma rank_le_width {m n : ℕ} (A : matrix (fin m) (fin n) K) : A.rank ≤ n := A.rank_le_card_width.trans $ (fintype.card_fin n).le lemma rank_mul_le (B : matrix n o K) : (A ⬝ B).rank ≤ A.rank := begin refine linear_map.finrank_le_finrank_of_injective (submodule.of_le_injective _), rw [to_lin'_mul], exact linear_map.range_comp_le_range _ _, end lemma rank_unit (A : (matrix n n K)ˣ) : (A : matrix n n K).rank = fintype.card n := begin refine le_antisymm (rank_le_card_width A) _, have := rank_mul_le (A : matrix n n K) (↑A⁻¹ : matrix n n K), rwa [← mul_eq_mul, ← units.coe_mul, mul_inv_self, units.coe_one, rank_one] at this, end lemma rank_of_is_unit (A : matrix n n K) (h : is_unit A) : A.rank = fintype.card n := by { obtain ⟨A, rfl⟩ := h, exact rank_unit A } include m_fin lemma rank_eq_finrank_range_to_lin {M₁ M₂ : Type*} [add_comm_group M₁] [add_comm_group M₂] [module K M₁] [module K M₂] (v₁ : basis m K M₁) (v₂ : basis n K M₂) : A.rank = finrank K (to_lin v₂ v₁ A).range := begin let e₁ := (pi.basis_fun K m).equiv v₁ (equiv.refl _), let e₂ := (pi.basis_fun K n).equiv v₂ (equiv.refl _), have range_e₂ : (e₂ : (n → K) →ₗ[K] M₂).range = ⊤, { rw linear_map.range_eq_top, exact e₂.surjective }, refine linear_equiv.finrank_eq (e₁.of_submodules _ _ _), rw [← linear_map.range_comp, ← linear_map.range_comp_of_range_eq_top (to_lin v₂ v₁ A) range_e₂], congr' 1, apply linear_map.pi_ext', rintro i, apply linear_map.ext_ring, have aux₁ := to_lin_self (pi.basis_fun K n) (pi.basis_fun K m) A i, have aux₂ := basis.equiv_apply (pi.basis_fun K n) i v₂, rw [to_lin_eq_to_lin'] at aux₁, rw [pi.basis_fun_apply, linear_map.coe_std_basis] at aux₁ aux₂, simp only [linear_map.comp_apply, e₁, e₂, linear_equiv.coe_coe, equiv.refl_apply, aux₁, aux₂, linear_map.coe_single, to_lin_self, linear_equiv.map_sum, linear_equiv.map_smul, basis.equiv_apply], end lemma rank_le_card_height : A.rank ≤ fintype.card m := (submodule.finrank_le _).trans (module.free.finrank_pi K).le omit m_fin lemma rank_le_height {m n : ℕ} (A : matrix (fin m) (fin n) K) : A.rank ≤ m := A.rank_le_card_height.trans $ (fintype.card_fin m).le end matrix
bffa1f329956841419ecfad95a52f5a91f51367a
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/280.lean
21fb3ee5301ff99493240b6e0d673033bfc58958
[ "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
403
lean
inductive S where | P | I open S inductive Expr : S → Type where | lit : Int → Expr I | eq : Expr I → Expr I → Expr P def Val : S → Type | P => Prop | I => Int def eval : {s : S} → Expr s → Val s | _, (Expr.lit n) => n | _, (Expr.eq e₁ e₂) => eval e₁ = eval e₂ def eval' : Expr s → Val s | Expr.lit n => n | Expr.eq e₁ e₂ => eval e₁ = eval e₂
447a2a957b28cd965f7321b53f05a2e35a98d224
ba4794a0deca1d2aaa68914cd285d77880907b5c
/src/game/world10/level17.lean
f8a9fdb6cf1e2ff6e81349375bb83736ddc20ff4
[ "Apache-2.0" ]
permissive
ChrisHughes24/natural_number_game
c7c00aa1f6a95004286fd456ed13cf6e113159ce
9d09925424da9f6275e6cfe427c8bcf12bb0944f
refs/heads/master
1,600,715,773,528
1,573,910,462,000
1,573,910,462,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,172
lean
--import mynat.lt -- definition of < import game.world10.level14 -- hide namespace mynat -- hide /- # Inequality world. ## Level 15: introducing `<` To get the remaining collectibles in this world, we need to give a definition of `<`. By default, the definition of `a < b` in Lean, once `≤` is defined, is this: `a < b := a ≤ b ∧ ¬ (b ≤ a)` . But a much more usable definition would be this: `a < b := succ(a) ≤ b` . Let's prove that these two definitions are the same -/ /- Lemma : For all naturals $a$ and $b$, $$a\le b\land\lnot(b\le a)\implies\operatorname{succ}(a)\le b.$$ -/ lemma lt_aux_one (a b : mynat) : a ≤ b ∧ ¬ (b ≤ a) → succ a ≤ b := begin [less_leaky] intro h, cases h with h1 h2, cases h1 with c hc, cases c with d, exfalso, rw add_zero at hc, apply h2, rw hc, refl, use d, rw hc, rw add_succ, rw succ_add, refl, end def lt_of_add_lt_add_left : ∀ (a b c : mynat), a + b < a + c → b < c := sorry def bot := 0 def bot_le := zero_le instance : canonically_ordered_monoid mynat := by structure_helper instance : ordered_comm_monoid mynat := by structure_helper end mynat -- hide
b6a717858ada38318010395419edd0c7209cda17
aa5a655c05e5359a70646b7154e7cac59f0b4132
/stage0/src/Lean/Data/Lsp/Capabilities.lean
85d39c63aaac2ca9dbb5245d06f59ebd5676b9ed
[ "Apache-2.0" ]
permissive
lambdaxymox/lean4
ae943c960a42247e06eff25c35338268d07454cb
278d47c77270664ef29715faab467feac8a0f446
refs/heads/master
1,677,891,867,340
1,612,500,005,000
1,612,500,005,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,064
lean
/- Copyright (c) 2020 Marc Huisinga. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Marc Huisinga, Wojciech Nawrocki -/ import Lean.Data.JsonRpc import Lean.Data.Lsp.TextSync /-! Minimal LSP servers/clients do not have to implement a lot of functionality. Most useful additional behaviour is instead opted into via capabilities. -/ namespace Lean namespace Lsp open Json -- TODO: right now we ignore the client's capabilities inductive ClientCapabilities where | mk instance : FromJson ClientCapabilities := ⟨fun j => ClientCapabilities.mk⟩ instance ClientCapabilities.hasToJson : ToJson ClientCapabilities := ⟨fun o => mkObj []⟩ -- TODO largely unimplemented structure ServerCapabilities where textDocumentSync? : Option TextDocumentSyncOptions := none hoverProvider : Bool := false documentSymbolProvider : Bool := false definitionProvider : Bool := false declarationProvider : Bool := false typeDefinitionProvider : Bool := false deriving ToJson, FromJson end Lsp end Lean
6c7898adeb3286493c790b0cc7f6a116cad25dd1
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/eq2.lean
63b0dbf68925f17b68af686c4d3f938f9698c7c9
[ "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
205
lean
namespace test definition symm {A : Type} : Π {a b : A}, a = b → b = a | a .(a) rfl := rfl definition trans {A : Type} : Π {a b c : A}, a = b → b = c → a = c | a .(a) .(a) rfl rfl := rfl end test
d7b3c7913ba30dc5deb208093b565ed8c61682b8
367134ba5a65885e863bdc4507601606690974c1
/src/data/padics/hensel.lean
b338b90b586971b21f0064b9f12874d6d81d09da
[ "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
21,289
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import data.padics.padic_integers import topology.metric_space.cau_seq_filter import analysis.specific_limits import data.polynomial.identities import topology.algebra.polynomial /-! # Hensel's lemma on ℤ_p This file proves Hensel's lemma on ℤ_p, roughly following Keith Conrad's writeup: <http://www.math.uconn.edu/~kconrad/blurbs/gradnumthy/hensel.pdf> Hensel's lemma gives a simple condition for the existence of a root of a polynomial. The proof and motivation are described in the paper [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019]. ## References * <http://www.math.uconn.edu/~kconrad/blurbs/gradnumthy/hensel.pdf> * [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019] * <https://en.wikipedia.org/wiki/Hensel%27s_lemma> ## Tags p-adic, p adic, padic, p-adic integer -/ noncomputable theory open_locale classical topological_space -- We begin with some general lemmas that are used below in the computation. lemma padic_polynomial_dist {p : ℕ} [fact p.prime] (F : polynomial ℤ_[p]) (x y : ℤ_[p]) : ∥F.eval x - F.eval y∥ ≤ ∥x - y∥ := let ⟨z, hz⟩ := F.eval_sub_factor x y in calc ∥F.eval x - F.eval y∥ = ∥z∥ * ∥x - y∥ : by simp [hz] ... ≤ 1 * ∥x - y∥ : mul_le_mul_of_nonneg_right (padic_int.norm_le_one _) (norm_nonneg _) ... = ∥x - y∥ : by simp open filter metric private lemma comp_tendsto_lim {p : ℕ} [fact p.prime] {F : polynomial ℤ_[p]} (ncs : cau_seq ℤ_[p] norm) : tendsto (λ i, F.eval (ncs i)) at_top (𝓝 (F.eval ncs.lim)) := F.continuous_at.tendsto.comp ncs.tendsto_limit section parameters {p : ℕ} [fact p.prime] {ncs : cau_seq ℤ_[p] norm} {F : polynomial ℤ_[p]} {a : ℤ_[p]} (ncs_der_val : ∀ n, ∥F.derivative.eval (ncs n)∥ = ∥F.derivative.eval a∥) include ncs_der_val private lemma ncs_tendsto_const : tendsto (λ i, ∥F.derivative.eval (ncs i)∥) at_top (𝓝 ∥F.derivative.eval a∥) := by convert tendsto_const_nhds; ext; rw ncs_der_val private lemma ncs_tendsto_lim : tendsto (λ i, ∥F.derivative.eval (ncs i)∥) at_top (𝓝 (∥F.derivative.eval ncs.lim∥)) := tendsto.comp (continuous_iff_continuous_at.1 continuous_norm _) (comp_tendsto_lim _) private lemma norm_deriv_eq : ∥F.derivative.eval ncs.lim∥ = ∥F.derivative.eval a∥ := tendsto_nhds_unique ncs_tendsto_lim ncs_tendsto_const end section parameters {p : ℕ} [fact p.prime] {ncs : cau_seq ℤ_[p] norm} {F : polynomial ℤ_[p]} (hnorm : tendsto (λ i, ∥F.eval (ncs i)∥) at_top (𝓝 0)) include hnorm private lemma tendsto_zero_of_norm_tendsto_zero : tendsto (λ i, F.eval (ncs i)) at_top (𝓝 0) := tendsto_iff_norm_tendsto_zero.2 (by simpa using hnorm) lemma limit_zero_of_norm_tendsto_zero : F.eval ncs.lim = 0 := tendsto_nhds_unique (comp_tendsto_lim _) tendsto_zero_of_norm_tendsto_zero end section hensel open nat parameters {p : ℕ} [fact p.prime] {F : polynomial ℤ_[p]} {a : ℤ_[p]} (hnorm : ∥F.eval a∥ < ∥F.derivative.eval a∥^2) (hnsol : F.eval a ≠ 0) include hnorm /-- `T` is an auxiliary value that is used to control the behavior of the polynomial `F`. -/ private def T : ℝ := ∥(F.eval a / (F.derivative.eval a)^2 : ℚ_[p])∥ private lemma deriv_sq_norm_pos : 0 < ∥F.derivative.eval a∥ ^ 2 := lt_of_le_of_lt (norm_nonneg _) hnorm private lemma deriv_sq_norm_ne_zero : ∥F.derivative.eval a∥^2 ≠ 0 := ne_of_gt deriv_sq_norm_pos private lemma deriv_norm_ne_zero : ∥F.derivative.eval a∥ ≠ 0 := λ h, deriv_sq_norm_ne_zero (by simp [*, pow_two]) private lemma deriv_norm_pos : 0 < ∥F.derivative.eval a∥ := lt_of_le_of_ne (norm_nonneg _) (ne.symm deriv_norm_ne_zero) private lemma deriv_ne_zero : F.derivative.eval a ≠ 0 := mt norm_eq_zero.2 deriv_norm_ne_zero private lemma T_def : T = ∥F.eval a∥ / ∥F.derivative.eval a∥^2 := calc T = ∥F.eval a∥ / ∥((F.derivative.eval a)^2 : ℚ_[p])∥ : normed_field.norm_div _ _ ... = ∥F.eval a∥ / ∥(F.derivative.eval a)^2∥ : by simp [norm, padic_int.norm_def] ... = ∥F.eval a∥ / ∥(F.derivative.eval a)∥^2 : by simp [pow, monoid.pow] private lemma T_lt_one : T < 1 := let h := (div_lt_one deriv_sq_norm_pos).2 hnorm in by rw T_def; apply h private lemma T_pow {n : ℕ} (hn : n > 0) : T ^ n < 1 := have T ^ n ≤ T ^ 1, from pow_le_pow_of_le_one (norm_nonneg _) (le_of_lt T_lt_one) (succ_le_of_lt hn), lt_of_le_of_lt (by simpa) T_lt_one private lemma T_pow' (n : ℕ) : T ^ (2 ^ n) < 1 := (T_pow (pow_pos (by norm_num) _)) private lemma T_pow_nonneg (n : ℕ) : 0 ≤ T ^ n := pow_nonneg (norm_nonneg _) _ /-- We will construct a sequence of elements of ℤ_p satisfying successive values of `ih`. -/ private def ih (n : ℕ) (z : ℤ_[p]) : Prop := ∥F.derivative.eval z∥ = ∥F.derivative.eval a∥ ∧ ∥F.eval z∥ ≤ ∥F.derivative.eval a∥^2 * T ^ (2^n) private lemma ih_0 : ih 0 a := ⟨ rfl, by simp [T_def, mul_div_cancel' _ (ne_of_gt (deriv_sq_norm_pos hnorm))] ⟩ private lemma calc_norm_le_one {n : ℕ} {z : ℤ_[p]} (hz : ih n z) : ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ ≤ 1 := calc ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ = ∥(↑(F.eval z) : ℚ_[p])∥ / ∥(↑(F.derivative.eval z) : ℚ_[p])∥ : normed_field.norm_div _ _ ... = ∥F.eval z∥ / ∥F.derivative.eval a∥ : by simp [hz.1] ... ≤ ∥F.derivative.eval a∥^2 * T^(2^n) / ∥F.derivative.eval a∥ : (div_le_div_right deriv_norm_pos).2 hz.2 ... = ∥F.derivative.eval a∥ * T^(2^n) : div_sq_cancel (ne_of_gt deriv_norm_pos) _ ... ≤ 1 : mul_le_one (padic_int.norm_le_one _) (T_pow_nonneg _) (le_of_lt (T_pow' _)) private lemma calc_deriv_dist {z z' z1 : ℤ_[p]} (hz' : z' = z - z1) (hz1 : ∥z1∥ = ∥F.eval z∥ / ∥F.derivative.eval a∥) {n} (hz : ih n z) : ∥F.derivative.eval z' - F.derivative.eval z∥ < ∥F.derivative.eval a∥ := calc ∥F.derivative.eval z' - F.derivative.eval z∥ ≤ ∥z' - z∥ : padic_polynomial_dist _ _ _ ... = ∥z1∥ : by simp only [sub_eq_add_neg, add_assoc, hz', add_add_neg_cancel'_right, norm_neg] ... = ∥F.eval z∥ / ∥F.derivative.eval a∥ : hz1 ... ≤ ∥F.derivative.eval a∥^2 * T^(2^n) / ∥F.derivative.eval a∥ : (div_le_div_right deriv_norm_pos).2 hz.2 ... = ∥F.derivative.eval a∥ * T^(2^n) : div_sq_cancel deriv_norm_ne_zero _ ... < ∥F.derivative.eval a∥ : (mul_lt_iff_lt_one_right deriv_norm_pos).2 (T_pow (pow_pos (by norm_num) _)) private def calc_eval_z' {z z' z1 : ℤ_[p]} (hz' : z' = z - z1) {n} (hz : ih n z) (h1 : ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ ≤ 1) (hzeq : z1 = ⟨_, h1⟩) : {q : ℤ_[p] // F.eval z' = q * z1^2} := have hdzne' : (↑(F.derivative.eval z) : ℚ_[p]) ≠ 0, from have hdzne : F.derivative.eval z ≠ 0, from mt norm_eq_zero.2 (by rw hz.1; apply deriv_norm_ne_zero; assumption), λ h, hdzne $ subtype.ext_iff_val.2 h, let ⟨q, hq⟩ := F.binom_expansion z (-z1) in have ∥(↑(F.derivative.eval z) * (↑(F.eval z) / ↑(F.derivative.eval z)) : ℚ_[p])∥ ≤ 1, by {rw padic_norm_e.mul, apply mul_le_one, apply padic_int.norm_le_one, apply norm_nonneg, apply h1}, have F.derivative.eval z * (-z1) = -F.eval z, from calc F.derivative.eval z * (-z1) = (F.derivative.eval z) * -⟨↑(F.eval z) / ↑(F.derivative.eval z), h1⟩ : by rw [hzeq] ... = -((F.derivative.eval z) * ⟨↑(F.eval z) / ↑(F.derivative.eval z), h1⟩) : by simp [subtype.ext_iff_val] ... = -(⟨↑(F.derivative.eval z) * (↑(F.eval z) / ↑(F.derivative.eval z)), this⟩) : subtype.ext_iff_val.2 $ by simp ... = -(F.eval z) : by simp [mul_div_cancel' _ hdzne'], have heq : F.eval z' = q * z1^2, by simpa [sub_eq_add_neg, this, hz'] using hq, ⟨q, heq⟩ private def calc_eval_z'_norm {z z' z1 : ℤ_[p]} {n} (hz : ih n z) {q} (heq : F.eval z' = q * z1^2) (h1 : ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ ≤ 1) (hzeq : z1 = ⟨_, h1⟩) : ∥F.eval z'∥ ≤ ∥F.derivative.eval a∥^2 * T^(2^(n+1)) := calc ∥F.eval z'∥ = ∥q∥ * ∥z1∥^2 : by simp [heq] ... ≤ 1 * ∥z1∥^2 : mul_le_mul_of_nonneg_right (padic_int.norm_le_one _) (pow_nonneg (norm_nonneg _) _) ... = ∥F.eval z∥^2 / ∥F.derivative.eval a∥^2 : by simp [hzeq, hz.1, div_pow] ... ≤ (∥F.derivative.eval a∥^2 * T^(2^n))^2 / ∥F.derivative.eval a∥^2 : (div_le_div_right deriv_sq_norm_pos).2 (pow_le_pow_of_le_left (norm_nonneg _) hz.2 _) ... = (∥F.derivative.eval a∥^2)^2 * (T^(2^n))^2 / ∥F.derivative.eval a∥^2 : by simp only [mul_pow] ... = ∥F.derivative.eval a∥^2 * (T^(2^n))^2 : div_sq_cancel deriv_sq_norm_ne_zero _ ... = ∥F.derivative.eval a∥^2 * T^(2^(n + 1)) : by rw [←pow_mul, pow_succ' 2] set_option eqn_compiler.zeta true /-- Given `z : ℤ_[p]` satisfying `ih n z`, construct `z' : ℤ_[p]` satisfying `ih (n+1) z'`. We need the hypothesis `ih n z`, since otherwise `z'` is not necessarily an integer. -/ private def ih_n {n : ℕ} {z : ℤ_[p]} (hz : ih n z) : {z' : ℤ_[p] // ih (n+1) z'} := have h1 : ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ ≤ 1, from calc_norm_le_one hz, let z1 : ℤ_[p] := ⟨_, h1⟩, z' : ℤ_[p] := z - z1 in ⟨ z', have hdist : ∥F.derivative.eval z' - F.derivative.eval z∥ < ∥F.derivative.eval a∥, from calc_deriv_dist rfl (by simp [z1, hz.1]) hz, have hfeq : ∥F.derivative.eval z'∥ = ∥F.derivative.eval a∥, begin rw [sub_eq_add_neg, ← hz.1, ←norm_neg (F.derivative.eval z)] at hdist, have := padic_int.norm_eq_of_norm_add_lt_right hdist, rwa [norm_neg, hz.1] at this end, let ⟨q, heq⟩ := calc_eval_z' rfl hz h1 rfl in have hnle : ∥F.eval z'∥ ≤ ∥F.derivative.eval a∥^2 * T^(2^(n+1)), from calc_eval_z'_norm hz heq h1 rfl, ⟨hfeq, hnle⟩⟩ set_option eqn_compiler.zeta false -- why doesn't "noncomputable theory" stick here? private noncomputable def newton_seq_aux : Π n : ℕ, {z : ℤ_[p] // ih n z} | 0 := ⟨a, ih_0⟩ | (k+1) := ih_n (newton_seq_aux k).2 private def newton_seq (n : ℕ) : ℤ_[p] := (newton_seq_aux n).1 private lemma newton_seq_deriv_norm (n : ℕ) : ∥F.derivative.eval (newton_seq n)∥ = ∥F.derivative.eval a∥ := (newton_seq_aux n).2.1 private lemma newton_seq_norm_le (n : ℕ) : ∥F.eval (newton_seq n)∥ ≤ ∥F.derivative.eval a∥^2 * T ^ (2^n) := (newton_seq_aux n).2.2 private lemma newton_seq_norm_eq (n : ℕ) : ∥newton_seq (n+1) - newton_seq n∥ = ∥F.eval (newton_seq n)∥ / ∥F.derivative.eval (newton_seq n)∥ := by simp [newton_seq, newton_seq_aux, ih_n, sub_eq_add_neg, add_comm] private lemma newton_seq_succ_dist (n : ℕ) : ∥newton_seq (n+1) - newton_seq n∥ ≤ ∥F.derivative.eval a∥ * T^(2^n) := calc ∥newton_seq (n+1) - newton_seq n∥ = ∥F.eval (newton_seq n)∥ / ∥F.derivative.eval (newton_seq n)∥ : newton_seq_norm_eq _ ... = ∥F.eval (newton_seq n)∥ / ∥F.derivative.eval a∥ : by rw newton_seq_deriv_norm ... ≤ ∥F.derivative.eval a∥^2 * T ^ (2^n) / ∥F.derivative.eval a∥ : (div_le_div_right deriv_norm_pos).2 (newton_seq_norm_le _) ... = ∥F.derivative.eval a∥ * T^(2^n) : div_sq_cancel (ne_of_gt deriv_norm_pos) _ include hnsol private lemma T_pos : T > 0 := begin rw T_def, exact div_pos (norm_pos_iff.2 hnsol) (deriv_sq_norm_pos hnorm) end private lemma newton_seq_succ_dist_weak (n : ℕ) : ∥newton_seq (n+2) - newton_seq (n+1)∥ < ∥F.eval a∥ / ∥F.derivative.eval a∥ := have 2 ≤ 2^(n+1), from have _, from pow_le_pow (by norm_num : 1 ≤ 2) (nat.le_add_left _ _ : 1 ≤ n + 1), by simpa using this, calc ∥newton_seq (n+2) - newton_seq (n+1)∥ ≤ ∥F.derivative.eval a∥ * T^(2^(n+1)) : newton_seq_succ_dist _ ... ≤ ∥F.derivative.eval a∥ * T^2 : mul_le_mul_of_nonneg_left (pow_le_pow_of_le_one (norm_nonneg _) (le_of_lt T_lt_one) this) (norm_nonneg _) ... < ∥F.derivative.eval a∥ * T^1 : mul_lt_mul_of_pos_left (pow_lt_pow_of_lt_one T_pos T_lt_one (by norm_num)) deriv_norm_pos ... = ∥F.eval a∥ / ∥F.derivative.eval a∥ : begin rw [T, pow_two, pow_one, normed_field.norm_div, ←mul_div_assoc, padic_norm_e.mul], apply mul_div_mul_left, apply deriv_norm_ne_zero; assumption end private lemma newton_seq_dist_aux (n : ℕ) : ∀ k : ℕ, ∥newton_seq (n + k) - newton_seq n∥ ≤ ∥F.derivative.eval a∥ * T^(2^n) | 0 := by simp [T_pow_nonneg hnorm, mul_nonneg] | (k+1) := have 2^n ≤ 2^(n+k), by {apply pow_le_pow, norm_num, apply nat.le_add_right}, calc ∥newton_seq (n + (k + 1)) - newton_seq n∥ = ∥newton_seq ((n + k) + 1) - newton_seq n∥ : by rw add_assoc ... = ∥(newton_seq ((n + k) + 1) - newton_seq (n+k)) + (newton_seq (n+k) - newton_seq n)∥ : by rw ←sub_add_sub_cancel ... ≤ max (∥newton_seq ((n + k) + 1) - newton_seq (n+k)∥) (∥newton_seq (n+k) - newton_seq n∥) : padic_int.nonarchimedean _ _ ... ≤ max (∥F.derivative.eval a∥ * T^(2^((n + k)))) (∥F.derivative.eval a∥ * T^(2^n)) : max_le_max (newton_seq_succ_dist _) (newton_seq_dist_aux _) ... = ∥F.derivative.eval a∥ * T^(2^n) : max_eq_right $ mul_le_mul_of_nonneg_left (pow_le_pow_of_le_one (norm_nonneg _) (le_of_lt T_lt_one) this) (norm_nonneg _) private lemma newton_seq_dist {n k : ℕ} (hnk : n ≤ k) : ∥newton_seq k - newton_seq n∥ ≤ ∥F.derivative.eval a∥ * T^(2^n) := have hex : ∃ m, k = n + m, from exists_eq_add_of_le hnk, let ⟨_, hex'⟩ := hex in by rw hex'; apply newton_seq_dist_aux; assumption private lemma newton_seq_dist_to_a : ∀ n : ℕ, 0 < n → ∥newton_seq n - a∥ = ∥F.eval a∥ / ∥F.derivative.eval a∥ | 1 h := by simp [sub_eq_add_neg, add_assoc, newton_seq, newton_seq_aux, ih_n]; apply normed_field.norm_div | (k+2) h := have hlt : ∥newton_seq (k+2) - newton_seq (k+1)∥ < ∥newton_seq (k+1) - a∥, by rw newton_seq_dist_to_a (k+1) (succ_pos _); apply newton_seq_succ_dist_weak; assumption, have hne' : ∥newton_seq (k + 2) - newton_seq (k+1)∥ ≠ ∥newton_seq (k+1) - a∥, from ne_of_lt hlt, calc ∥newton_seq (k + 2) - a∥ = ∥(newton_seq (k + 2) - newton_seq (k+1)) + (newton_seq (k+1) - a)∥ : by rw ←sub_add_sub_cancel ... = max (∥newton_seq (k + 2) - newton_seq (k+1)∥) (∥newton_seq (k+1) - a∥) : padic_int.norm_add_eq_max_of_ne hne' ... = ∥newton_seq (k+1) - a∥ : max_eq_right_of_lt hlt ... = ∥polynomial.eval a F∥ / ∥polynomial.eval a (polynomial.derivative F)∥ : newton_seq_dist_to_a (k+1) (succ_pos _) private lemma bound' : tendsto (λ n : ℕ, ∥F.derivative.eval a∥ * T^(2^n)) at_top (𝓝 0) := begin rw ←mul_zero (∥F.derivative.eval a∥), exact tendsto_const_nhds.mul (tendsto.comp (tendsto_pow_at_top_nhds_0_of_lt_1 (norm_nonneg _) (T_lt_one hnorm)) (nat.tendsto_pow_at_top_at_top_of_one_lt (by norm_num))) end private lemma bound : ∀ {ε}, ε > 0 → ∃ N : ℕ, ∀ {n}, n ≥ N → ∥F.derivative.eval a∥ * T^(2^n) < ε := have mtn : ∀ n : ℕ, ∥polynomial.eval a (polynomial.derivative F)∥ * T ^ (2 ^ n) ≥ 0, from λ n, mul_nonneg (norm_nonneg _) (T_pow_nonneg _), begin have := bound' hnorm hnsol, simp [tendsto, nhds] at this, intros ε hε, cases this (ball 0 ε) (mem_ball_self hε) (is_open_ball) with N hN, existsi N, intros n hn, simpa [normed_field.norm_mul, real.norm_eq_abs, abs_of_nonneg (mtn n)] using hN _ hn end private lemma bound'_sq : tendsto (λ n : ℕ, ∥F.derivative.eval a∥^2 * T^(2^n)) at_top (𝓝 0) := begin rw [←mul_zero (∥F.derivative.eval a∥), pow_two], simp only [mul_assoc], apply tendsto.mul, { apply tendsto_const_nhds }, { apply bound', assumption } end private theorem newton_seq_is_cauchy : is_cau_seq norm newton_seq := begin intros ε hε, cases bound hnorm hnsol hε with N hN, existsi N, intros j hj, apply lt_of_le_of_lt, { apply newton_seq_dist _ _ hj, assumption }, { apply hN, apply le_refl } end private def newton_cau_seq : cau_seq ℤ_[p] norm := ⟨_, newton_seq_is_cauchy⟩ private def soln : ℤ_[p] := newton_cau_seq.lim private lemma soln_spec {ε : ℝ} (hε : ε > 0) : ∃ (N : ℕ), ∀ {i : ℕ}, i ≥ N → ∥soln - newton_cau_seq i∥ < ε := setoid.symm (cau_seq.equiv_lim newton_cau_seq) _ hε private lemma soln_deriv_norm : ∥F.derivative.eval soln∥ = ∥F.derivative.eval a∥ := norm_deriv_eq newton_seq_deriv_norm private lemma newton_seq_norm_tendsto_zero : tendsto (λ i, ∥F.eval (newton_cau_seq i)∥) at_top (𝓝 0) := squeeze_zero (λ _, norm_nonneg _) newton_seq_norm_le bound'_sq private lemma newton_seq_dist_tendsto : tendsto (λ n, ∥newton_cau_seq n - a∥) at_top (𝓝 (∥F.eval a∥ / ∥F.derivative.eval a∥)) := tendsto_const_nhds.congr' $ eventually_at_top.2 ⟨1, λ _ hx, (newton_seq_dist_to_a _ hx).symm⟩ private lemma newton_seq_dist_tendsto' : tendsto (λ n, ∥newton_cau_seq n - a∥) at_top (𝓝 ∥soln - a∥) := (continuous_norm.tendsto _).comp (newton_cau_seq.tendsto_limit.sub tendsto_const_nhds) private lemma soln_dist_to_a : ∥soln - a∥ = ∥F.eval a∥ / ∥F.derivative.eval a∥ := tendsto_nhds_unique newton_seq_dist_tendsto' newton_seq_dist_tendsto private lemma soln_dist_to_a_lt_deriv : ∥soln - a∥ < ∥F.derivative.eval a∥ := begin rw [soln_dist_to_a, div_lt_iff], { rwa pow_two at hnorm }, { apply deriv_norm_pos, assumption } end private lemma eval_soln : F.eval soln = 0 := limit_zero_of_norm_tendsto_zero newton_seq_norm_tendsto_zero private lemma soln_unique (z : ℤ_[p]) (hev : F.eval z = 0) (hnlt : ∥z - a∥ < ∥F.derivative.eval a∥) : z = soln := have soln_dist : ∥z - soln∥ < ∥F.derivative.eval a∥, from calc ∥z - soln∥ = ∥(z - a) + (a - soln)∥ : by rw sub_add_sub_cancel ... ≤ max (∥z - a∥) (∥a - soln∥) : padic_int.nonarchimedean _ _ ... < ∥F.derivative.eval a∥ : max_lt hnlt (by rw norm_sub_rev; apply soln_dist_to_a_lt_deriv), let h := z - soln, ⟨q, hq⟩ := F.binom_expansion soln h in have (F.derivative.eval soln + q * h) * h = 0, from eq.symm (calc 0 = F.eval (soln + h) : by simp [hev, h] ... = F.derivative.eval soln * h + q * h^2 : by rw [hq, eval_soln, zero_add] ... = (F.derivative.eval soln + q * h) * h : by rw [pow_two, right_distrib, mul_assoc]), have h = 0, from by_contradiction $ λ hne, have F.derivative.eval soln + q * h = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right hne, have F.derivative.eval soln = (-q) * h, by simpa using eq_neg_of_add_eq_zero this, lt_irrefl ∥F.derivative.eval soln∥ (calc ∥F.derivative.eval soln∥ = ∥(-q) * h∥ : by rw this ... ≤ 1 * ∥h∥ : by rw [padic_int.norm_mul]; exact mul_le_mul_of_nonneg_right (padic_int.norm_le_one _) (norm_nonneg _) ... = ∥z - soln∥ : by simp [h] ... < ∥F.derivative.eval soln∥ : by rw soln_deriv_norm; apply soln_dist), eq_of_sub_eq_zero (by rw ←this; refl) end hensel variables {p : ℕ} [fact p.prime] {F : polynomial ℤ_[p]} {a : ℤ_[p]} private lemma a_soln_is_unique (ha : F.eval a = 0) (z' : ℤ_[p]) (hz' : F.eval z' = 0) (hnormz' : ∥z' - a∥ < ∥F.derivative.eval a∥) : z' = a := let h := z' - a, ⟨q, hq⟩ := F.binom_expansion a h in have (F.derivative.eval a + q * h) * h = 0, from eq.symm (calc 0 = F.eval (a + h) : show 0 = F.eval (a + (z' - a)), by rw add_comm; simp [hz'] ... = F.derivative.eval a * h + q * h^2 : by rw [hq, ha, zero_add] ... = (F.derivative.eval a + q * h) * h : by rw [pow_two, right_distrib, mul_assoc]), have h = 0, from by_contradiction $ λ hne, have F.derivative.eval a + q * h = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right hne, have F.derivative.eval a = (-q) * h, by simpa using eq_neg_of_add_eq_zero this, lt_irrefl ∥F.derivative.eval a∥ (calc ∥F.derivative.eval a∥ = ∥q∥*∥h∥ : by simp [this] ... ≤ 1*∥h∥ : mul_le_mul_of_nonneg_right (padic_int.norm_le_one _) (norm_nonneg _) ... < ∥F.derivative.eval a∥ : by simpa [h]), eq_of_sub_eq_zero (by rw ←this; refl) variable (hnorm : ∥F.eval a∥ < ∥F.derivative.eval a∥^2) include hnorm private lemma a_is_soln (ha : F.eval a = 0) : F.eval a = 0 ∧ ∥a - a∥ < ∥F.derivative.eval a∥ ∧ ∥F.derivative.eval a∥ = ∥F.derivative.eval a∥ ∧ ∀ z', F.eval z' = 0 → ∥z' - a∥ < ∥F.derivative.eval a∥ → z' = a := ⟨ha, by simp [deriv_ne_zero hnorm], rfl, a_soln_is_unique ha⟩ lemma hensels_lemma : ∃ z : ℤ_[p], F.eval z = 0 ∧ ∥z - a∥ < ∥F.derivative.eval a∥ ∧ ∥F.derivative.eval z∥ = ∥F.derivative.eval a∥ ∧ ∀ z', F.eval z' = 0 → ∥z' - a∥ < ∥F.derivative.eval a∥ → z' = z := if ha : F.eval a = 0 then ⟨a, a_is_soln hnorm ha⟩ else by refine ⟨soln _ _, eval_soln _ _, soln_dist_to_a_lt_deriv _ _, soln_deriv_norm _ _, soln_unique _ _⟩; assumption
c24bf6ca83267c9cd7983c17a24de69fd2f00823
94e33a31faa76775069b071adea97e86e218a8ee
/src/algebra/order/floor.lean
78f15aa2d52272000725e410e819008779c249f8
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
30,241
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kevin Kappelmann -/ import tactic.abel import tactic.linarith /-! # Floor and ceil ## Summary We define the natural- and integer-valued floor and ceil functions on linearly ordered rings. ## Main Definitions * `floor_semiring`: An ordered semiring with natural-valued floor and ceil. * `nat.floor a`: Greatest natural `n` such that `n ≤ a`. Equal to `0` if `a < 0`. * `nat.ceil a`: Least natural `n` such that `a ≤ n`. * `floor_ring`: A linearly ordered ring with integer-valued floor and ceil. * `int.floor a`: Greatest integer `z` such that `z ≤ a`. * `int.ceil a`: Least integer `z` such that `a ≤ z`. * `int.fract a`: Fractional part of `a`, defined as `a - floor a`. * `round a`: Nearest integer to `a`. It rounds halves towards infinity. ## Notations * `⌊a⌋₊` is `nat.floor a`. * `⌈a⌉₊` is `nat.ceil a`. * `⌊a⌋` is `int.floor a`. * `⌈a⌉` is `int.ceil a`. The index `₊` in the notations for `nat.floor` and `nat.ceil` is used in analogy to the notation for `nnnorm`. ## TODO Some `nat.floor` and `nat.ceil` lemmas require `linear_ordered_ring α`. Is `has_ordered_sub` enough? `linear_ordered_ring`/`linear_ordered_semiring` can be relaxed to `order_ring`/`order_semiring` in many lemmas. ## Tags rounding, floor, ceil -/ open set variables {α : Type*} /-! ### Floor semiring -/ /-- A `floor_semiring` is an ordered semiring over `α` with a function `floor : α → ℕ` satisfying `∀ (n : ℕ) (x : α), n ≤ ⌊x⌋ ↔ (n : α) ≤ x)`. Note that many lemmas require a `linear_order`. Please see the above `TODO`. -/ class floor_semiring (α) [ordered_semiring α] := (floor : α → ℕ) (ceil : α → ℕ) (floor_of_neg {a : α} (ha : a < 0) : floor a = 0) (gc_floor {a : α} {n : ℕ} (ha : 0 ≤ a) : n ≤ floor a ↔ (n : α) ≤ a) (gc_ceil : galois_connection ceil coe) instance : floor_semiring ℕ := { floor := id, ceil := id, floor_of_neg := λ a ha, (a.not_lt_zero ha).elim, gc_floor := λ n a ha, by { rw nat.cast_id, refl }, gc_ceil := λ n a, by { rw nat.cast_id, refl } } namespace nat section ordered_semiring variables [ordered_semiring α] [floor_semiring α] {a : α} {n : ℕ} /-- `⌊a⌋₊` is the greatest natural `n` such that `n ≤ a`. If `a` is negative, then `⌊a⌋₊ = 0`. -/ def floor : α → ℕ := floor_semiring.floor /-- `⌈a⌉₊` is the least natural `n` such that `a ≤ n` -/ def ceil : α → ℕ := floor_semiring.ceil @[simp] lemma floor_nat : (nat.floor : ℕ → ℕ) = id := rfl @[simp] lemma ceil_nat : (nat.ceil : ℕ → ℕ) = id := rfl notation `⌊` a `⌋₊` := nat.floor a notation `⌈` a `⌉₊` := nat.ceil a end ordered_semiring section linear_ordered_semiring variables [linear_ordered_semiring α] [floor_semiring α] {a : α} {n : ℕ} lemma le_floor_iff (ha : 0 ≤ a) : n ≤ ⌊a⌋₊ ↔ (n : α) ≤ a := floor_semiring.gc_floor ha lemma le_floor (h : (n : α) ≤ a) : n ≤ ⌊a⌋₊ := (le_floor_iff $ n.cast_nonneg.trans h).2 h lemma floor_lt (ha : 0 ≤ a) : ⌊a⌋₊ < n ↔ a < n := lt_iff_lt_of_le_iff_le $ le_floor_iff ha lemma floor_lt_one (ha : 0 ≤ a) : ⌊a⌋₊ < 1 ↔ a < 1 := (floor_lt ha).trans $ by rw nat.cast_one lemma lt_of_floor_lt (h : ⌊a⌋₊ < n) : a < n := lt_of_not_le $ λ h', (le_floor h').not_lt h lemma lt_one_of_floor_lt_one (h : ⌊a⌋₊ < 1) : a < 1 := by exact_mod_cast lt_of_floor_lt h lemma floor_le (ha : 0 ≤ a) : (⌊a⌋₊ : α) ≤ a := (le_floor_iff ha).1 le_rfl lemma lt_succ_floor (a : α) : a < ⌊a⌋₊.succ := lt_of_floor_lt $ nat.lt_succ_self _ lemma lt_floor_add_one (a : α) : a < ⌊a⌋₊ + 1 := by simpa using lt_succ_floor a @[simp] lemma floor_coe (n : ℕ) : ⌊(n : α)⌋₊ = n := eq_of_forall_le_iff $ λ a, by { rw [le_floor_iff, nat.cast_le], exact n.cast_nonneg } @[simp] lemma floor_zero : ⌊(0 : α)⌋₊ = 0 := by rw [← nat.cast_zero, floor_coe] @[simp] lemma floor_one : ⌊(1 : α)⌋₊ = 1 := by rw [←nat.cast_one, floor_coe] lemma floor_of_nonpos (ha : a ≤ 0) : ⌊a⌋₊ = 0 := ha.lt_or_eq.elim floor_semiring.floor_of_neg $ by { rintro rfl, exact floor_zero } lemma floor_mono : monotone (floor : α → ℕ) := λ a b h, begin obtain ha | ha := le_total a 0, { rw floor_of_nonpos ha, exact nat.zero_le _ }, { exact le_floor ((floor_le ha).trans h) } end lemma le_floor_iff' (hn : n ≠ 0) : n ≤ ⌊a⌋₊ ↔ (n : α) ≤ a := begin obtain ha | ha := le_total a 0, { rw floor_of_nonpos ha, exact iff_of_false (nat.pos_of_ne_zero hn).not_le (not_le_of_lt $ ha.trans_lt $ cast_pos.2 $ nat.pos_of_ne_zero hn) }, { exact le_floor_iff ha } end @[simp] lemma one_le_floor_iff (x : α) : 1 ≤ ⌊x⌋₊ ↔ 1 ≤ x := by exact_mod_cast (@le_floor_iff' α _ _ x 1 one_ne_zero) lemma floor_lt' (hn : n ≠ 0) : ⌊a⌋₊ < n ↔ a < n := lt_iff_lt_of_le_iff_le $ le_floor_iff' hn lemma floor_pos : 0 < ⌊a⌋₊ ↔ 1 ≤ a := by { convert le_floor_iff' nat.one_ne_zero, exact cast_one.symm } lemma pos_of_floor_pos (h : 0 < ⌊a⌋₊) : 0 < a := (le_or_lt a 0).resolve_left (λ ha, lt_irrefl 0 $ by rwa floor_of_nonpos ha at h) lemma lt_of_lt_floor (h : n < ⌊a⌋₊) : ↑n < a := (nat.cast_lt.2 h).trans_le $ floor_le (pos_of_floor_pos $ (nat.zero_le n).trans_lt h).le lemma floor_le_of_le (h : a ≤ n) : ⌊a⌋₊ ≤ n := le_imp_le_iff_lt_imp_lt.2 lt_of_lt_floor h lemma floor_le_one_of_le_one (h : a ≤ 1) : ⌊a⌋₊ ≤ 1 := floor_le_of_le $ h.trans_eq $ nat.cast_one.symm @[simp] lemma floor_eq_zero : ⌊a⌋₊ = 0 ↔ a < 1 := by { rw [←lt_one_iff, ←@cast_one α], exact floor_lt' nat.one_ne_zero } lemma floor_eq_iff (ha : 0 ≤ a) : ⌊a⌋₊ = n ↔ ↑n ≤ a ∧ a < ↑n + 1 := by rw [←le_floor_iff ha, ←nat.cast_one, ←nat.cast_add, ←floor_lt ha, nat.lt_add_one_iff, le_antisymm_iff, and.comm] lemma floor_eq_iff' (hn : n ≠ 0) : ⌊a⌋₊ = n ↔ ↑n ≤ a ∧ a < ↑n + 1 := by rw [← le_floor_iff' hn, ← nat.cast_one, ← nat.cast_add, ← floor_lt' (nat.add_one_ne_zero n), nat.lt_add_one_iff, le_antisymm_iff, and.comm] lemma floor_eq_on_Ico (n : ℕ) : ∀ a ∈ (set.Ico n (n+1) : set α), ⌊a⌋₊ = n := λ a ⟨h₀, h₁⟩, (floor_eq_iff $ n.cast_nonneg.trans h₀).mpr ⟨h₀, h₁⟩ lemma floor_eq_on_Ico' (n : ℕ) : ∀ a ∈ (set.Ico n (n+1) : set α), (⌊a⌋₊ : α) = n := λ x hx, by exact_mod_cast floor_eq_on_Ico n x hx @[simp] lemma preimage_floor_zero : (floor : α → ℕ) ⁻¹' {0} = Iio 1 := ext $ λ a, floor_eq_zero lemma preimage_floor_of_ne_zero {n : ℕ} (hn : n ≠ 0) : (floor : α → ℕ) ⁻¹' {n} = Ico n (n + 1) := ext $ λ a, floor_eq_iff' hn /-! #### Ceil -/ lemma gc_ceil_coe : galois_connection (ceil : α → ℕ) coe := floor_semiring.gc_ceil @[simp] lemma ceil_le : ⌈a⌉₊ ≤ n ↔ a ≤ n := gc_ceil_coe _ _ lemma lt_ceil : n < ⌈a⌉₊ ↔ (n : α) < a := lt_iff_lt_of_le_iff_le ceil_le lemma le_ceil (a : α) : a ≤ ⌈a⌉₊ := ceil_le.1 le_rfl lemma ceil_mono : monotone (ceil : α → ℕ) := gc_ceil_coe.monotone_l @[simp] lemma ceil_coe (n : ℕ) : ⌈(n : α)⌉₊ = n := eq_of_forall_ge_iff $ λ a, ceil_le.trans nat.cast_le @[simp] lemma ceil_zero : ⌈(0 : α)⌉₊ = 0 := by rw [← nat.cast_zero, ceil_coe] @[simp] lemma ceil_one : ⌈(1 : α)⌉₊ = 1 := by rw [←nat.cast_one, ceil_coe] @[simp] lemma ceil_eq_zero : ⌈a⌉₊ = 0 ↔ a ≤ 0 := by rw [← le_zero_iff, ceil_le, nat.cast_zero] lemma lt_of_ceil_lt (h : ⌈a⌉₊ < n) : a < n := (le_ceil a).trans_lt (nat.cast_lt.2 h) lemma le_of_ceil_le (h : ⌈a⌉₊ ≤ n) : a ≤ n := (le_ceil a).trans (nat.cast_le.2 h) lemma floor_le_ceil (a : α) : ⌊a⌋₊ ≤ ⌈a⌉₊ := begin obtain ha | ha := le_total a 0, { rw floor_of_nonpos ha, exact nat.zero_le _ }, { exact cast_le.1 ((floor_le ha).trans $ le_ceil _) } end lemma floor_lt_ceil_of_lt_of_pos {a b : α} (h : a < b) (h' : 0 < b) : ⌊a⌋₊ < ⌈b⌉₊ := begin rcases le_or_lt 0 a with ha|ha, { rw floor_lt ha, exact h.trans_le (le_ceil _) }, { rwa [floor_of_nonpos ha.le, lt_ceil, nat.cast_zero] } end lemma ceil_eq_iff (hn : n ≠ 0) : ⌈a⌉₊ = n ↔ ↑(n - 1) < a ∧ a ≤ n := by rw [← ceil_le, ← not_le, ← ceil_le, not_le, tsub_lt_iff_right (nat.add_one_le_iff.2 (pos_iff_ne_zero.2 hn)), nat.lt_add_one_iff, le_antisymm_iff, and.comm] @[simp] lemma preimage_ceil_zero : (nat.ceil : α → ℕ) ⁻¹' {0} = Iic 0 := ext $ λ x, ceil_eq_zero lemma preimage_ceil_of_ne_zero (hn : n ≠ 0) : (nat.ceil : α → ℕ) ⁻¹' {n} = Ioc ↑(n - 1) n := ext $ λ x, ceil_eq_iff hn /-! #### Intervals -/ @[simp] lemma preimage_Ioo {a b : α} (ha : 0 ≤ a) : ((coe : ℕ → α) ⁻¹' (set.Ioo a b)) = set.Ioo ⌊a⌋₊ ⌈b⌉₊ := by { ext, simp [floor_lt, lt_ceil, ha] } @[simp] lemma preimage_Ico {a b : α} : ((coe : ℕ → α) ⁻¹' (set.Ico a b)) = set.Ico ⌈a⌉₊ ⌈b⌉₊ := by { ext, simp [ceil_le, lt_ceil] } @[simp] lemma preimage_Ioc {a b : α} (ha : 0 ≤ a) (hb : 0 ≤ b) : ((coe : ℕ → α) ⁻¹' (set.Ioc a b)) = set.Ioc ⌊a⌋₊ ⌊b⌋₊ := by { ext, simp [floor_lt, le_floor_iff, hb, ha] } @[simp] lemma preimage_Icc {a b : α} (hb : 0 ≤ b) : ((coe : ℕ → α) ⁻¹' (set.Icc a b)) = set.Icc ⌈a⌉₊ ⌊b⌋₊ := by { ext, simp [ceil_le, hb, le_floor_iff] } @[simp] lemma preimage_Ioi {a : α} (ha : 0 ≤ a) : ((coe : ℕ → α) ⁻¹' (set.Ioi a)) = set.Ioi ⌊a⌋₊ := by { ext, simp [floor_lt, ha] } @[simp] lemma preimage_Ici {a : α} : ((coe : ℕ → α) ⁻¹' (set.Ici a)) = set.Ici ⌈a⌉₊ := by { ext, simp [ceil_le] } @[simp] lemma preimage_Iio {a : α} : ((coe : ℕ → α) ⁻¹' (set.Iio a)) = set.Iio ⌈a⌉₊ := by { ext, simp [lt_ceil] } @[simp] lemma preimage_Iic {a : α} (ha : 0 ≤ a) : ((coe : ℕ → α) ⁻¹' (set.Iic a)) = set.Iic ⌊a⌋₊ := by { ext, simp [le_floor_iff, ha] } end linear_ordered_semiring section linear_ordered_ring variables [linear_ordered_ring α] [floor_semiring α] {a : α} {n : ℕ} lemma floor_add_nat (ha : 0 ≤ a) (n : ℕ) : ⌊a + n⌋₊ = ⌊a⌋₊ + n := eq_of_forall_le_iff $ λ b, begin rw [le_floor_iff (add_nonneg ha n.cast_nonneg), ←sub_le_iff_le_add], obtain hb | hb := le_total n b, { rw [←cast_sub hb, ←tsub_le_iff_right], exact (le_floor_iff ha).symm }, { exact iff_of_true ((sub_nonpos_of_le $ cast_le.2 hb).trans ha) (le_add_left hb) } end lemma floor_add_one (ha : 0 ≤ a) : ⌊a + 1⌋₊ = ⌊a⌋₊ + 1 := by { convert floor_add_nat ha 1, exact cast_one.symm } lemma floor_sub_nat (a : α) (n : ℕ) : ⌊a - n⌋₊ = ⌊a⌋₊ - n := begin obtain ha | ha := le_total a 0, { rw [floor_of_nonpos ha, floor_of_nonpos (sub_nonpos_of_le (ha.trans n.cast_nonneg)), zero_tsub] }, cases le_total a n, { rw [floor_of_nonpos (tsub_nonpos_of_le h), eq_comm, tsub_eq_zero_iff_le], exact nat.cast_le.1 ((nat.floor_le ha).trans h) }, { rw [eq_tsub_iff_add_eq_of_le (le_floor h), ←floor_add_nat (sub_nonneg_of_le h), sub_add_cancel] } end lemma sub_one_lt_floor (a : α) : a - 1 < ⌊a⌋₊ := sub_lt_iff_lt_add.2 $ lt_floor_add_one a lemma ceil_add_nat (ha : 0 ≤ a) (n : ℕ) : ⌈a + n⌉₊ = ⌈a⌉₊ + n := eq_of_forall_ge_iff $ λ b, begin rw [←not_lt, ←not_lt, not_iff_not], rw [lt_ceil], obtain hb | hb := le_or_lt n b, { rw [←tsub_lt_iff_right hb, ←sub_lt_iff_lt_add, ←cast_sub hb], exact lt_ceil.symm }, { exact iff_of_true (lt_add_of_nonneg_of_lt ha $ cast_lt.2 hb) (lt_add_left _ _ _ hb) } end lemma ceil_add_one (ha : 0 ≤ a) : ⌈a + 1⌉₊ = ⌈a⌉₊ + 1 := by { convert ceil_add_nat ha 1, exact cast_one.symm } lemma ceil_lt_add_one (ha : 0 ≤ a) : (⌈a⌉₊ : α) < a + 1 := lt_ceil.1 $ (nat.lt_succ_self _).trans_le (ceil_add_one ha).ge end linear_ordered_ring section linear_ordered_semifield variables [linear_ordered_semifield α] [floor_semiring α] lemma floor_div_nat (a : α) (n : ℕ) : ⌊a / n⌋₊ = ⌊a⌋₊ / n := begin cases le_total a 0 with ha ha, { rw [floor_of_nonpos, floor_of_nonpos ha], { simp }, apply div_nonpos_of_nonpos_of_nonneg ha n.cast_nonneg }, obtain rfl | hn := n.eq_zero_or_pos, { rw [cast_zero, div_zero, nat.div_zero, floor_zero] }, refine (floor_eq_iff _).2 _, { exact div_nonneg ha n.cast_nonneg }, split, { exact cast_div_le.trans (div_le_div_of_le_of_nonneg (floor_le ha) n.cast_nonneg) }, rw [div_lt_iff, add_mul, one_mul, ←cast_mul, ←cast_add, ←floor_lt ha], { exact lt_div_mul_add hn }, { exact (cast_pos.2 hn) } end /-- Natural division is the floor of field division. -/ lemma floor_div_eq_div (m n : ℕ) : ⌊(m : α) / n⌋₊ = m / n := by { convert floor_div_nat (m : α) n, rw m.floor_coe } end linear_ordered_semifield end nat /-- There exists at most one `floor_semiring` structure on a linear ordered semiring. -/ lemma subsingleton_floor_semiring {α} [linear_ordered_semiring α] : subsingleton (floor_semiring α) := begin refine ⟨λ H₁ H₂, _⟩, have : H₁.ceil = H₂.ceil, from funext (λ a, H₁.gc_ceil.l_unique H₂.gc_ceil $ λ n, rfl), have : H₁.floor = H₂.floor, { ext a, cases lt_or_le a 0, { rw [H₁.floor_of_neg, H₂.floor_of_neg]; exact h }, { refine eq_of_forall_le_iff (λ n, _), rw [H₁.gc_floor, H₂.gc_floor]; exact h } }, cases H₁, cases H₂, congr; assumption end /-! ### Floor rings -/ /-- A `floor_ring` is a linear ordered ring over `α` with a function `floor : α → ℤ` satisfying `∀ (z : ℤ) (a : α), z ≤ floor a ↔ (z : α) ≤ a)`. -/ class floor_ring (α) [linear_ordered_ring α] := (floor : α → ℤ) (ceil : α → ℤ) (gc_coe_floor : galois_connection coe floor) (gc_ceil_coe : galois_connection ceil coe) instance : floor_ring ℤ := { floor := id, ceil := id, gc_coe_floor := λ a b, by { rw int.cast_id, refl }, gc_ceil_coe := λ a b, by { rw int.cast_id, refl } } /-- A `floor_ring` constructor from the `floor` function alone. -/ def floor_ring.of_floor (α) [linear_ordered_ring α] (floor : α → ℤ) (gc_coe_floor : galois_connection coe floor) : floor_ring α := { floor := floor, ceil := λ a, -floor (-a), gc_coe_floor := gc_coe_floor, gc_ceil_coe := λ a z, by rw [neg_le, ←gc_coe_floor, int.cast_neg, neg_le_neg_iff] } /-- A `floor_ring` constructor from the `ceil` function alone. -/ def floor_ring.of_ceil (α) [linear_ordered_ring α] (ceil : α → ℤ) (gc_ceil_coe : galois_connection ceil coe) : floor_ring α := { floor := λ a, -ceil (-a), ceil := ceil, gc_coe_floor := λ a z, by rw [le_neg, gc_ceil_coe, int.cast_neg, neg_le_neg_iff], gc_ceil_coe := gc_ceil_coe } namespace int variables [linear_ordered_ring α] [floor_ring α] {z : ℤ} {a : α} /-- `int.floor a` is the greatest integer `z` such that `z ≤ a`. It is denoted with `⌊a⌋`. -/ def floor : α → ℤ := floor_ring.floor /-- `int.ceil a` is the smallest integer `z` such that `a ≤ z`. It is denoted with `⌈a⌉`. -/ def ceil : α → ℤ := floor_ring.ceil /-- `int.fract a`, the fractional part of `a`, is `a` minus its floor. -/ def fract (a : α) : α := a - floor a @[simp] lemma floor_int : (int.floor : ℤ → ℤ) = id := rfl @[simp] lemma ceil_int : (int.ceil : ℤ → ℤ) = id := rfl @[simp] lemma fract_int : (int.fract : ℤ → ℤ) = 0 := funext $ λ x, by simp [fract] notation `⌊` a `⌋` := int.floor a notation `⌈` a `⌉` := int.ceil a -- Mathematical notation for `fract a` is usually `{a}`. Let's not even go there. @[simp] lemma floor_ring_floor_eq : @floor_ring.floor = @int.floor := rfl @[simp] lemma floor_ring_ceil_eq : @floor_ring.ceil = @int.ceil := rfl /-! #### Floor -/ lemma gc_coe_floor : galois_connection (coe : ℤ → α) floor := floor_ring.gc_coe_floor lemma le_floor : z ≤ ⌊a⌋ ↔ (z : α) ≤ a := (gc_coe_floor z a).symm lemma floor_lt : ⌊a⌋ < z ↔ a < z := lt_iff_lt_of_le_iff_le le_floor lemma floor_le (a : α) : (⌊a⌋ : α) ≤ a := gc_coe_floor.l_u_le a lemma floor_nonneg : 0 ≤ ⌊a⌋ ↔ 0 ≤ a := by rw [le_floor, int.cast_zero] lemma floor_nonpos (ha : a ≤ 0) : ⌊a⌋ ≤ 0 := begin rw [← @cast_le α, int.cast_zero], exact (floor_le a).trans ha, end lemma lt_succ_floor (a : α) : a < ⌊a⌋.succ := floor_lt.1 $ int.lt_succ_self _ lemma lt_floor_add_one (a : α) : a < ⌊a⌋ + 1 := by simpa only [int.succ, int.cast_add, int.cast_one] using lt_succ_floor a lemma sub_one_lt_floor (a : α) : a - 1 < ⌊a⌋ := sub_lt_iff_lt_add.2 (lt_floor_add_one a) @[simp] lemma floor_coe (z : ℤ) : ⌊(z : α)⌋ = z := eq_of_forall_le_iff $ λ a, by rw [le_floor, int.cast_le] @[simp] lemma floor_zero : ⌊(0 : α)⌋ = 0 := by rw [← int.cast_zero, floor_coe] @[simp] lemma floor_one : ⌊(1 : α)⌋ = 1 := by rw [← int.cast_one, floor_coe] @[mono] lemma floor_mono : monotone (floor : α → ℤ) := gc_coe_floor.monotone_u lemma floor_pos : 0 < ⌊a⌋ ↔ 1 ≤ a := by { convert le_floor, exact cast_one.symm } @[simp] lemma floor_add_int (a : α) (z : ℤ) : ⌊a + z⌋ = ⌊a⌋ + z := eq_of_forall_le_iff $ λ a, by rw [le_floor, ← sub_le_iff_le_add, ← sub_le_iff_le_add, le_floor, int.cast_sub] lemma floor_add_one (a : α) : ⌊a + 1⌋ = ⌊a⌋ + 1 := by { convert floor_add_int a 1, exact cast_one.symm } @[simp] lemma floor_int_add (z : ℤ) (a : α) : ⌊↑z + a⌋ = z + ⌊a⌋ := by simpa only [add_comm] using floor_add_int a z @[simp] lemma floor_add_nat (a : α) (n : ℕ) : ⌊a + n⌋ = ⌊a⌋ + n := by rw [← int.cast_coe_nat, floor_add_int] @[simp] lemma floor_nat_add (n : ℕ) (a : α) : ⌊↑n + a⌋ = n + ⌊a⌋ := by rw [← int.cast_coe_nat, floor_int_add] @[simp] lemma floor_sub_int (a : α) (z : ℤ) : ⌊a - z⌋ = ⌊a⌋ - z := eq.trans (by rw [int.cast_neg, sub_eq_add_neg]) (floor_add_int _ _) @[simp] lemma floor_sub_nat (a : α) (n : ℕ) : ⌊a - n⌋ = ⌊a⌋ - n := by rw [← int.cast_coe_nat, floor_sub_int] lemma abs_sub_lt_one_of_floor_eq_floor {α : Type*} [linear_ordered_comm_ring α] [floor_ring α] {a b : α} (h : ⌊a⌋ = ⌊b⌋) : |a - b| < 1 := begin have : a < ⌊a⌋ + 1 := lt_floor_add_one a, have : b < ⌊b⌋ + 1 := lt_floor_add_one b, have : (⌊a⌋ : α) = ⌊b⌋ := int.cast_inj.2 h, have : (⌊a⌋ : α) ≤ a := floor_le a, have : (⌊b⌋ : α) ≤ b := floor_le b, exact abs_sub_lt_iff.2 ⟨by linarith, by linarith⟩ end lemma floor_eq_iff : ⌊a⌋ = z ↔ ↑z ≤ a ∧ a < z + 1 := by rw [le_antisymm_iff, le_floor, ←int.lt_add_one_iff, floor_lt, int.cast_add, int.cast_one, and.comm] lemma floor_eq_on_Ico (n : ℤ) : ∀ a ∈ set.Ico (n : α) (n + 1), ⌊a⌋ = n := λ a ⟨h₀, h₁⟩, floor_eq_iff.mpr ⟨h₀, h₁⟩ lemma floor_eq_on_Ico' (n : ℤ) : ∀ a ∈ set.Ico (n : α) (n + 1), (⌊a⌋ : α) = n := λ a ha, congr_arg _ $ floor_eq_on_Ico n a ha @[simp] lemma preimage_floor_singleton (m : ℤ) : (floor : α → ℤ) ⁻¹' {m} = Ico m (m + 1) := ext $ λ x, floor_eq_iff /-! #### Fractional part -/ @[simp] lemma self_sub_floor (a : α) : a - ⌊a⌋ = fract a := rfl @[simp] lemma floor_add_fract (a : α) : (⌊a⌋ : α) + fract a = a := add_sub_cancel'_right _ _ @[simp] lemma fract_add_floor (a : α) : fract a + ⌊a⌋ = a := sub_add_cancel _ _ @[simp] lemma fract_add_int (a : α) (m : ℤ) : fract (a + m) = fract a := by { rw fract, simp } @[simp] lemma fract_sub_int (a : α) (m : ℤ) : fract (a - m) = fract a := by { rw fract, simp } @[simp] lemma fract_int_add (m : ℤ) (a : α) : fract (↑m + a) = fract a := by rw [add_comm, fract_add_int] @[simp] lemma self_sub_fract (a : α) : a - fract a = ⌊a⌋ := sub_sub_cancel _ _ @[simp] lemma fract_sub_self (a : α) : fract a - a = -⌊a⌋ := sub_sub_cancel_left _ _ lemma fract_nonneg (a : α) : 0 ≤ fract a := sub_nonneg.2 $ floor_le _ lemma fract_lt_one (a : α) : fract a < 1 := sub_lt.1 $ sub_one_lt_floor _ @[simp] lemma fract_zero : fract (0 : α) = 0 := by rw [fract, floor_zero, cast_zero, sub_self] @[simp] lemma fract_coe (z : ℤ) : fract (z : α) = 0 := by { unfold fract, rw floor_coe, exact sub_self _ } @[simp] lemma fract_floor (a : α) : fract (⌊a⌋ : α) = 0 := fract_coe _ @[simp] lemma floor_fract (a : α) : ⌊fract a⌋ = 0 := by rw [floor_eq_iff, int.cast_zero, zero_add]; exact ⟨fract_nonneg _, fract_lt_one _⟩ lemma fract_eq_iff {a b : α} : fract a = b ↔ 0 ≤ b ∧ b < 1 ∧ ∃ z : ℤ, a - b = z := ⟨λ h, by { rw ←h, exact ⟨fract_nonneg _, fract_lt_one _, ⟨⌊a⌋, sub_sub_cancel _ _⟩⟩}, begin rintro ⟨h₀, h₁, z, hz⟩, show a - ⌊a⌋ = b, apply eq.symm, rw [eq_sub_iff_add_eq, add_comm, ←eq_sub_iff_add_eq], rw [hz, int.cast_inj, floor_eq_iff, ←hz], clear hz, split; simpa [sub_eq_add_neg, add_assoc] end⟩ lemma fract_eq_fract {a b : α} : fract a = fract b ↔ ∃ z : ℤ, a - b = z := ⟨λ h, ⟨⌊a⌋ - ⌊b⌋, begin unfold fract at h, rw [int.cast_sub, sub_eq_sub_iff_sub_eq_sub.1 h], end⟩, begin rintro ⟨z, hz⟩, refine fract_eq_iff.2 ⟨fract_nonneg _, fract_lt_one _, z + ⌊b⌋, _⟩, rw [eq_add_of_sub_eq hz, add_comm, int.cast_add], exact add_sub_sub_cancel _ _ _, end⟩ @[simp] lemma fract_eq_self {a : α} : fract a = a ↔ 0 ≤ a ∧ a < 1 := fract_eq_iff.trans $ and.assoc.symm.trans $ and_iff_left ⟨0, by simp⟩ @[simp] lemma fract_fract (a : α) : fract (fract a) = fract a := fract_eq_self.2 ⟨fract_nonneg _, fract_lt_one _⟩ lemma fract_add (a b : α) : ∃ z : ℤ, fract (a + b) - fract a - fract b = z := ⟨⌊a⌋ + ⌊b⌋ - ⌊a + b⌋, by { unfold fract, simp [sub_eq_add_neg], abel }⟩ lemma fract_mul_nat (a : α) (b : ℕ) : ∃ z : ℤ, fract a * b - fract (a * b) = z := begin induction b with c hc, use 0, simp, rcases hc with ⟨z, hz⟩, rw [nat.succ_eq_add_one, nat.cast_add, mul_add, mul_add, nat.cast_one, mul_one, mul_one], rcases fract_add (a * c) a with ⟨y, hy⟩, use z - y, rw [int.cast_sub, ←hz, ←hy], abel end lemma preimage_fract (s : set α) : fract ⁻¹' s = ⋃ m : ℤ, (λ x, x - m) ⁻¹' (s ∩ Ico (0 : α) 1) := begin ext x, simp only [mem_preimage, mem_Union, mem_inter_eq], refine ⟨λ h, ⟨⌊x⌋, h, fract_nonneg x, fract_lt_one x⟩, _⟩, rintro ⟨m, hms, hm0, hm1⟩, obtain rfl : ⌊x⌋ = m, from floor_eq_iff.2 ⟨sub_nonneg.1 hm0, sub_lt_iff_lt_add'.1 hm1⟩, exact hms end lemma image_fract (s : set α) : fract '' s = ⋃ m : ℤ, (λ x, x - m) '' s ∩ Ico 0 1 := begin ext x, simp only [mem_image, mem_inter_eq, mem_Union], split, { rintro ⟨y, hy, rfl⟩, exact ⟨⌊y⌋, ⟨y, hy, rfl⟩, fract_nonneg y, fract_lt_one y⟩ }, { rintro ⟨m, ⟨y, hys, rfl⟩, h0, h1⟩, obtain rfl : ⌊y⌋ = m, from floor_eq_iff.2 ⟨sub_nonneg.1 h0, sub_lt_iff_lt_add'.1 h1⟩, exact ⟨y, hys, rfl⟩ } end section linear_ordered_field variables {k : Type*} [linear_ordered_field k] [floor_ring k] {b : k} lemma fract_div_mul_self_mem_Ico (a b : k) (ha : 0 < a) : fract (b/a) * a ∈ Ico 0 a := ⟨(zero_le_mul_right ha).2 (fract_nonneg (b/a)), (mul_lt_iff_lt_one_left ha).2 (fract_lt_one (b/a))⟩ lemma fract_div_mul_self_add_zsmul_eq (a b : k) (ha : a ≠ 0) : fract (b/a) * a + ⌊b/a⌋ • a = b := by rw [zsmul_eq_mul, ← add_mul, fract_add_floor, div_mul_cancel b ha] lemma sub_floor_div_mul_nonneg (a : k) (hb : 0 < b) : 0 ≤ a - ⌊a / b⌋ * b := sub_nonneg_of_le $ (le_div_iff hb).1 $ floor_le _ lemma sub_floor_div_mul_lt (a : k) (hb : 0 < b) : a - ⌊a / b⌋ * b < b := sub_lt_iff_lt_add.2 $ by { rw [←one_add_mul, ←div_lt_iff hb, add_comm], exact lt_floor_add_one _ } end linear_ordered_field /-! #### Ceil -/ lemma gc_ceil_coe : galois_connection ceil (coe : ℤ → α) := floor_ring.gc_ceil_coe lemma ceil_le : ⌈a⌉ ≤ z ↔ a ≤ z := gc_ceil_coe a z lemma floor_neg : ⌊-a⌋ = -⌈a⌉ := eq_of_forall_le_iff (λ z, by rw [le_neg, ceil_le, le_floor, int.cast_neg, le_neg]) lemma ceil_neg : ⌈-a⌉ = -⌊a⌋ := eq_of_forall_ge_iff (λ z, by rw [neg_le, ceil_le, le_floor, int.cast_neg, neg_le]) lemma lt_ceil : z < ⌈a⌉ ↔ (z : α) < a := lt_iff_lt_of_le_iff_le ceil_le lemma ceil_le_floor_add_one (a : α) : ⌈a⌉ ≤ ⌊a⌋ + 1 := by { rw [ceil_le, int.cast_add, int.cast_one], exact (lt_floor_add_one a).le } lemma le_ceil (a : α) : a ≤ ⌈a⌉ := gc_ceil_coe.le_u_l a @[simp] lemma ceil_coe (z : ℤ) : ⌈(z : α)⌉ = z := eq_of_forall_ge_iff $ λ a, by rw [ceil_le, int.cast_le] lemma ceil_mono : monotone (ceil : α → ℤ) := gc_ceil_coe.monotone_l @[simp] lemma ceil_add_int (a : α) (z : ℤ) : ⌈a + z⌉ = ⌈a⌉ + z := by rw [←neg_inj, neg_add', ←floor_neg, ←floor_neg, neg_add', floor_sub_int] @[simp] lemma ceil_add_one (a : α) : ⌈a + 1⌉ = ⌈a⌉ + 1 := by { convert ceil_add_int a (1 : ℤ), exact cast_one.symm } @[simp] lemma ceil_sub_int (a : α) (z : ℤ) : ⌈a - z⌉ = ⌈a⌉ - z := eq.trans (by rw [int.cast_neg, sub_eq_add_neg]) (ceil_add_int _ _) @[simp] lemma ceil_sub_one (a : α) : ⌈a - 1⌉ = ⌈a⌉ - 1 := by rw [eq_sub_iff_add_eq, ← ceil_add_one, sub_add_cancel] lemma ceil_lt_add_one (a : α) : (⌈a⌉ : α) < a + 1 := by { rw [← lt_ceil, ← int.cast_one, ceil_add_int], apply lt_add_one } lemma ceil_pos : 0 < ⌈a⌉ ↔ 0 < a := by rw [lt_ceil, int.cast_zero] @[simp] lemma ceil_zero : ⌈(0 : α)⌉ = 0 := by rw [← int.cast_zero, ceil_coe] @[simp] lemma ceil_one : ⌈(1 : α)⌉ = 1 := by rw [←int.cast_one, ceil_coe] lemma ceil_nonneg (ha : 0 ≤ a) : 0 ≤ ⌈a⌉ := by exact_mod_cast ha.trans (le_ceil a) lemma ceil_eq_iff : ⌈a⌉ = z ↔ ↑z - 1 < a ∧ a ≤ z := by rw [←ceil_le, ←int.cast_one, ←int.cast_sub, ←lt_ceil, int.sub_one_lt_iff, le_antisymm_iff, and.comm] lemma ceil_eq_on_Ioc (z : ℤ) : ∀ a ∈ set.Ioc (z - 1 : α) z, ⌈a⌉ = z := λ a ⟨h₀, h₁⟩, ceil_eq_iff.mpr ⟨h₀, h₁⟩ lemma ceil_eq_on_Ioc' (z : ℤ) : ∀ a ∈ set.Ioc (z - 1 : α) z, (⌈a⌉ : α) = z := λ a ha, by exact_mod_cast ceil_eq_on_Ioc z a ha lemma floor_le_ceil (a : α) : ⌊a⌋ ≤ ⌈a⌉ := cast_le.1 $ (floor_le _).trans $ le_ceil _ lemma floor_lt_ceil_of_lt {a b : α} (h : a < b) : ⌊a⌋ < ⌈b⌉ := cast_lt.1 $ (floor_le a).trans_lt $ h.trans_le $ le_ceil b @[simp] lemma preimage_ceil_singleton (m : ℤ) : (ceil : α → ℤ) ⁻¹' {m} = Ioc (m - 1) m := ext $ λ x, ceil_eq_iff /-! #### Intervals -/ @[simp] lemma preimage_Ioo {a b : α} : ((coe : ℤ → α) ⁻¹' (set.Ioo a b)) = set.Ioo ⌊a⌋ ⌈b⌉ := by { ext, simp [floor_lt, lt_ceil] } @[simp] lemma preimage_Ico {a b : α} : ((coe : ℤ → α) ⁻¹' (set.Ico a b)) = set.Ico ⌈a⌉ ⌈b⌉ := by { ext, simp [ceil_le, lt_ceil] } @[simp] lemma preimage_Ioc {a b : α} : ((coe : ℤ → α) ⁻¹' (set.Ioc a b)) = set.Ioc ⌊a⌋ ⌊b⌋ := by { ext, simp [floor_lt, le_floor] } @[simp] lemma preimage_Icc {a b : α} : ((coe : ℤ → α) ⁻¹' (set.Icc a b)) = set.Icc ⌈a⌉ ⌊b⌋ := by { ext, simp [ceil_le, le_floor] } @[simp] lemma preimage_Ioi : ((coe : ℤ → α) ⁻¹' (set.Ioi a)) = set.Ioi ⌊a⌋ := by { ext, simp [floor_lt] } @[simp] lemma preimage_Ici : ((coe : ℤ → α) ⁻¹' (set.Ici a)) = set.Ici ⌈a⌉ := by { ext, simp [ceil_le] } @[simp] lemma preimage_Iio : ((coe : ℤ → α) ⁻¹' (set.Iio a)) = set.Iio ⌈a⌉ := by { ext, simp [lt_ceil] } @[simp] lemma preimage_Iic : ((coe : ℤ → α) ⁻¹' (set.Iic a)) = set.Iic ⌊a⌋ := by { ext, simp [le_floor] } end int open int /-! ### Round -/ section round variables [linear_ordered_field α] [floor_ring α] /-- `round` rounds a number to the nearest integer. `round (1 / 2) = 1` -/ def round (x : α) : ℤ := ⌊x + 1 / 2⌋ @[simp] lemma round_zero : round (0 : α) = 0 := floor_eq_iff.2 (by norm_num) @[simp] lemma round_one : round (1 : α) = 1 := floor_eq_iff.2 (by norm_num) lemma abs_sub_round (x : α) : |x - round x| ≤ 1 / 2 := begin rw [round, abs_sub_le_iff], have := floor_le (x + 1 / 2), have := lt_floor_add_one (x + 1 / 2), split; linarith end end round variables {α} [linear_ordered_ring α] [floor_ring α] /-! #### A floor ring as a floor semiring -/ @[priority 100] -- see Note [lower instance priority] instance _root_.floor_ring.to_floor_semiring : floor_semiring α := { floor := λ a, ⌊a⌋.to_nat, ceil := λ a, ⌈a⌉.to_nat, floor_of_neg := λ a ha, int.to_nat_of_nonpos (int.floor_nonpos ha.le), gc_floor := λ a n ha, by rw [int.le_to_nat_iff (int.floor_nonneg.2 ha), int.le_floor, int.cast_coe_nat], gc_ceil := λ a n, by rw [int.to_nat_le, int.ceil_le, int.cast_coe_nat] } lemma int.floor_to_nat (a : α) : ⌊a⌋.to_nat = ⌊a⌋₊ := rfl lemma int.ceil_to_nat (a : α) : ⌈a⌉.to_nat = ⌈a⌉₊ := rfl @[simp] lemma nat.floor_int : (nat.floor : ℤ → ℕ) = int.to_nat := rfl @[simp] lemma nat.ceil_int : (nat.ceil : ℤ → ℕ) = int.to_nat := rfl variables {a : α} lemma nat.cast_floor_eq_int_floor (ha : 0 ≤ a) : (⌊a⌋₊ : ℤ) = ⌊a⌋ := by rw [←int.floor_to_nat, int.to_nat_of_nonneg (int.floor_nonneg.2 ha)] lemma nat.cast_floor_eq_cast_int_floor (ha : 0 ≤ a) : (⌊a⌋₊ : α) = ⌊a⌋ := by rw [←nat.cast_floor_eq_int_floor ha, int.cast_coe_nat] lemma nat.cast_ceil_eq_int_ceil (ha : 0 ≤ a) : (⌈a⌉₊ : ℤ) = ⌈a⌉ := by { rw [←int.ceil_to_nat, int.to_nat_of_nonneg (int.ceil_nonneg ha)] } lemma nat.cast_ceil_eq_cast_int_ceil (ha : 0 ≤ a) : (⌈a⌉₊ : α) = ⌈a⌉ := by rw [←nat.cast_ceil_eq_int_ceil ha, int.cast_coe_nat] /-- There exists at most one `floor_ring` structure on a given linear ordered ring. -/ lemma subsingleton_floor_ring {α} [linear_ordered_ring α] : subsingleton (floor_ring α) := begin refine ⟨λ H₁ H₂, _⟩, have : H₁.floor = H₂.floor := funext (λ a, H₁.gc_coe_floor.u_unique H₂.gc_coe_floor $ λ _, rfl), have : H₁.ceil = H₂.ceil := funext (λ a, H₁.gc_ceil_coe.l_unique H₂.gc_ceil_coe $ λ _, rfl), cases H₁, cases H₂, congr; assumption end
65a1f247fa002cbed3ad6c0ff45bb1ee4f8245df
cf5965a630b01a84700ca0afa6838e2353e3332b
/src/coffee.lean
9cc12261fae64048e46ec16b7f354782f5ef5515
[ "Apache-2.0" ]
permissive
jesse-michael-han/lean-coffee-can
d337d521b0091774b3a809bd1d2220430a7174e0
86929b4909aa602c867bc5f7fc130c5b7cd84076
refs/heads/master
1,596,514,166,838
1,569,957,883,000
1,569,958,093,000
211,997,928
1
0
null
null
null
null
UTF-8
Lean
false
false
5,691
lean
/- Copyright (c) 2019 Jesse Michael Han. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author(s): Jesse Michael Han A simplified version of the coffee can problem, from David Gries' The Science of Programming Given a coffee can filled with finitely many black and white beans, and an infinite supply of white beans, carry out the following procedure: as long as there is more than one bean in the can, - Draw two beans. - If their colors are different, discard the white one and return the black one to the can. - If their colors are the same, discard both of them and add a white bean to the can. Prove that if the number of black beans in the can is odd, then the process always ends with a black bean, and that if the number of black beans in the can is even, then the process always ends with a white bean. -/ import tactic import data.nat.parity @[derive decidable_eq, derive has_reflect] inductive beans : Type | white : beans | black : beans instance : has_repr beans := { repr := λ b, beans.cases_on b "white" "black" } open beans @[simp]def count_black : list beans → ℕ | [] := 0 | (white::xs) := count_black xs | (black::xs) := count_black xs + 1 @[simp]def count_white : list beans → ℕ | [] := 0 | (white::xs) := count_white xs + 1 | (black::xs) := count_white xs @[simp]lemma count_eq_length (xs : list beans) : count_black xs + count_white xs = xs.length := begin induction xs with x_hd x_tl ih, { refl }, { cases x_hd; simp [ih.symm] } end def coffee : list beans → list beans | [] := [] | [x] := [x] | (black::white::xs) := coffee (black::xs) | (white::black::xs) := coffee (black::xs) | (black::black::xs) := coffee (white::xs) | (white::white::xs) := coffee (white::xs) @[simp]lemma coffee_singleton {x : beans} : coffee [x] = [x] := beans.cases_on x rfl rfl def some_beans : list beans := [black, white, black, black, white, black, white, black, black, white, black] #eval coffee some_beans -- [black] section metaprogramming meta instance : has_to_format beans := { to_format := λ b, beans.cases_on b (format.of_string "white") (format.of_string "black") } meta def coffee_eval : list beans → tactic unit | [] := tactic.trace "[]" | [x] := tactic.trace format!"final state: [{x}]" | arg@(black::white::xs) := do tactic.trace format!"current state: {arg}", tactic.trace "got black + white, discarding white", coffee_eval (black::xs) | arg@(white::black::xs) := do tactic.trace format!"current state: {arg}", tactic.trace "got white + black, discarding white", coffee_eval (black::xs) | arg@(black::black::xs) := do tactic.trace format!"current state: {arg}", tactic.trace "got black + black, discarding both and adding white", coffee_eval (white::xs) | arg@(white::white::xs) := do tactic.trace format!"current state: {arg}", tactic.trace "got white + white, discarding white", coffee_eval (white::xs) @[reducible]meta def my_parser := state_t string tactic meta def beans.of_string : my_parser beans := ⟨ λ ⟨cs⟩, match cs with | [] := tactic.failed | (x::xs) := if x = '0' then return (white, ⟨xs⟩) else if x = '1' then return (black, ⟨xs⟩) else tactic.failed end ⟩ meta def repeat {α} : my_parser α → my_parser (list α) := λ p, (list.cons) <$> p <*> (repeat p <|> return []) meta def my_parser.run {α} [has_to_tactic_format α] (p : my_parser α) (arg : string) : tactic α := do bs <- prod.fst <$> state_t.run p arg, tactic.trace bs, return bs meta def parse_beans (arg : string) : tactic unit := do bs <- my_parser.run (repeat beans.of_string) arg, tactic.exact `(bs).to_expr end metaprogramming section test def some_more_beans : list beans := by {parse_beans "10110001011"} run_cmd coffee_eval some_more_beans end test @[simp]lemma coffee_white {x} {xs} : coffee (white::x::xs) = coffee (x::xs) := begin cases x, { rw coffee }, { simp [coffee] }, end lemma coffee_black_white {x} {xs} : coffee (x::xs) = [black] ∨ coffee (x::xs) = [white] := begin induction xs with y xs ih generalizing x, { cases x; simp }, { cases x; cases y; simp [*,coffee] } end open nat lemma coffee_parity_aux (xs : list beans) (k : ℕ) (H_k : k = xs.length) : even (count_black xs) ↔ even (count_black (coffee xs)) := begin revert xs H_k, apply nat.strong_induction_on k, clear k, intros n IH xs Hn, cases xs with x xs, { simp [coffee] }, { cases xs with y xs, { simp [coffee] }, { cases x; cases y, { simp [coffee] with parity_simps, rw ← IH (xs.length + 1) (by norm_num*), { simp }, { refl }}, { simp [coffee], rw ← IH (xs.length + 1) (by norm_num*), { simp }, { refl }}, { simp [coffee], rw ← IH (xs.length + 1) (by norm_num*), { simp }, { refl }}, { simp [coffee] with parity_simps, rw ← IH (xs.length + 1) (by norm_num*), { simp }, { refl }}}} end lemma coffee_parity {xs : list beans} : even (count_black xs) ↔ even (count_black (coffee xs)) := coffee_parity_aux xs xs.length rfl theorem ends_black_of_count_black_odd {x} {xs : list beans} (H_odd : ¬ (even $ count_black $ x::xs)) : coffee (x::xs) = [black] := by {have := @coffee_parity (x::xs), have := @coffee_black_white x xs, finish} theorem ends_white_of_count_black_even {x} {xs : list beans} (H_even : even $ count_black $ x::xs) : coffee (x::xs) = [white] := by {have := @coffee_parity (x::xs), have := @coffee_black_white x xs, finish}
1dc849b411e534ab2432e6ee5b029ca9d3b44409
b82c5bb4c3b618c23ba67764bc3e93f4999a1a39
/src/formal_ml/with_density_compose_eq_multiply.lean
5a724a901b82bbbb894a6ad8b2abdcf6830282f9
[ "Apache-2.0" ]
permissive
nouretienne/formal-ml
83c4261016955bf9bcb55bd32b4f2621b44163e0
40b6da3b6e875f47412d50c7cd97936cb5091a2b
refs/heads/master
1,671,216,448,724
1,600,472,285,000
1,600,472,285,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
102,835
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.set_integral import measure_theory.borel_space import data.set.countable import formal_ml.nnreal import formal_ml.sum import formal_ml.core import formal_ml.measurable_space import formal_ml.semiring import formal_ml.real_measurable_space import formal_ml.set import formal_ml.filter_util import topology.instances.ennreal import formal_ml.integral import formal_ml.int /- The simple way to think about a continuous random variable is as a continuous function (a density function). Formally, this is the Radon-Nikodym derivative. Using the operation with_density, one can transform this Radon-Nikodym derivative into a measure using measure_theory.with_density, which is provided in measure_theory.integration in mathlib. Specifically, one can write: μ.with_density f where μ is normally the Lebesgue measure on the real number line, and generate a probability measure for a continuous density function. In this file, measure_theory.with_density.compose_eq_multiply connects the integration (or expectation) of a function with respect to the probability measure derived from the density function with the integral using the original base measure. So, if μ is again the base measure, f is the density function, and g is the function we want to take the expectation of, then: (μ.with_density f).integral g = μ.integral (f * g) This is the familiar connection that we use to integrate functions of real random variables on a regular basis. -/ def measure_theory.finite_measure_of_lt_top {Ω:Type*} [M:measurable_space Ω] {μ:measure_theory.measure Ω} (H:μ set.univ < ⊤): measure_theory.finite_measure μ := { measure_univ_lt_top := H, } def measure_theory.finite_measure_of_le {Ω:Type*} [M:measurable_space Ω] (μ ν:measure_theory.measure Ω) [measure_theory.finite_measure ν] (H:μ ≤ ν): measure_theory.finite_measure μ := begin have B1:μ set.univ ≤ ν set.univ, { apply H, simp, }, have B2:μ set.univ < ⊤, { apply lt_of_le_of_lt B1, apply measure_theory.measure_lt_top, }, apply measure_theory.finite_measure_of_lt_top B2, end def measure_theory.finite_measure_restrict {Ω:Type*} [M:measurable_space Ω] (μ:measure_theory.measure Ω) [measure_theory.finite_measure μ] (S:set Ω): measure_theory.finite_measure (μ.restrict S) := begin have A1:= @measure_theory.measure.restrict_le_self Ω M μ S, apply measure_theory.finite_measure_of_le (μ.restrict S) μ A1, end ------------------------Core theorems--------------------------------------- lemma lt_of_not_le {α:Type*} [linear_order α] {a b:α}: ¬(a ≤ b) → (b < a) := begin intros A1, have A2 := lt_trichotomy a b, cases A2, { exfalso, apply A1, apply le_of_lt A2, }, cases A2, { exfalso, apply A1, subst a, }, { apply A2, }, end lemma not_le_iff_lt {α : Type*} [linear_order α] {a b : α}: ¬a ≤ b ↔ b < a := begin split;intro A1, { apply lt_of_not_le A1, }, { apply not_le_of_lt A1, }, end lemma lt_iff_le_not_eq {α:Type*} [linear_order α] {a b:α}: (a < b) ↔ ((a ≤ b) ∧ (a ≠ b)) := begin split;intros A1, { split, { apply le_of_lt A1, }, { apply ne_of_lt A1, }, }, { rw lt_iff_le_not_le, split, { apply A1.left, }, { intro A2, apply A1.right, apply le_antisymm, apply A1.left, apply A2, }, }, end ------------------------Theorems of complete lattices ---------------------- lemma Sup_image_le {α β:Type*} [complete_lattice β] {f:α → β} {S:set α} {x:β}: (∀ s∈ S, f s ≤ x) → (Sup (f '' S)≤ x) := begin intro A1, apply Sup_le, intros b A2, cases A2 with a A2, rw ← A2.right, apply (A1 a A2.left), end lemma le_Sup_image {α β:Type*} [complete_lattice β] {f:α → β} {S:set α} {a:α}: (a∈ S) → (f a) ≤ Sup (f '' S) := begin intro A1, apply le_Sup, simp, apply exists.intro a, split, apply A1, refl, end lemma Sup_Sup_image_image_le {α β γ:Type*} [complete_lattice γ] {f:α → β → γ} {S:set α} {T:set β} {x:γ}: (∀ a∈ S, ∀ b∈T, f a b ≤ x) → (Sup ((λ a:α, Sup ((f a) '' T)) '' S) ≤ x) := begin intro A1, apply Sup_image_le, intros a A2, apply Sup_image_le, intros b A3, apply A1 a A2 b A3, end lemma le_Sup_Sup_image_image {α β γ:Type*} [complete_lattice γ] {f:α → β → γ} {S:set α} {T:set β} {a:α} {b:β}: (a∈ S) → (b∈ T) → (f a b) ≤ (Sup ((λ a:α, Sup ((f a) '' T)) '' S)) := begin intros A1 A2, apply le_trans, apply @le_Sup_image β γ _ (f a) T b A2, apply @le_Sup_image α γ _ ((λ a:α, Sup ((f a) '' T))) S a A1, end lemma Sup_le_Sup_of_monotone {α β:Type*} [complete_lattice α] [complete_lattice β] {f:α → β} {s:set α}: (monotone f) → Sup (f '' s) ≤ f (Sup s) := begin intro A1, apply Sup_le, intros b A2, simp at A2, cases A2 with x A2, cases A2 with A2 A3, subst b, apply A1, apply le_Sup, apply A2, end lemma supr_le_supr_of_monotone {α β γ:Type*} [complete_lattice α] [complete_lattice β] {f:α → β} {g:γ → α}: (monotone f) → supr (f ∘ g) ≤ f (supr g) := begin intro A1, apply Sup_le, intros b A2, simp at A2, cases A2 with x A2, subst b, apply A1, apply le_Sup, simp, end lemma infi_le_infi_of_monotone {α β γ:Type*} [complete_lattice α] [complete_lattice β] {f:α → β} {g:γ → α}: (monotone f) → f (infi g) ≤ infi (f ∘ g) := begin intro A1, apply le_infi, intros b, apply A1, apply infi_le, end lemma Inf_le_Inf_of_monotone {α β:Type*} [complete_lattice α] [complete_lattice β] {f:α → β} {s:set α}: (monotone f) → f (Inf s) ≤ Inf (f '' s) := begin intro A1, apply le_Inf, intros b A2, simp at A2, cases A2 with b' A2, cases A2 with A2 A3, subst b, apply A1, apply Inf_le, apply A2, end lemma supr_prop_def {α:Type*} [complete_lattice α] {v:α} {P:Prop} (H:P):(⨆ (H2:P), v) = v := begin apply le_antisymm, { apply supr_le, intro A1, apply le_refl v, }, { apply @le_supr α P _ (λ H2:P, v), apply H, }, end lemma infi_prop_def {α:Type*} [complete_lattice α] {v:α} {P:Prop} (H:P):(⨅ (H2:P), v) = v := begin apply le_antisymm, { apply infi_le, apply H, }, { apply @le_infi, intro A1, apply le_refl v, }, end lemma supr_prop_false {α:Type*} [complete_lattice α] {v:α} {P:Prop} (H:¬P):(⨆ (H2:P), v) = ⊥ := begin apply le_antisymm, { apply supr_le, intro A1, exfalso, apply H, apply A1, }, { apply bot_le, }, end lemma infi_prop_false {α:Type*} [complete_lattice α] {v:α} {P:Prop} (H:¬P):(⨅ (H2:P), v) = ⊤ := begin apply le_antisymm, { apply le_top, }, { apply le_infi, intro A1, exfalso, apply H, apply A1, }, end ------------------------Theorems of int----------------------------------------------- def monoid_hom_nat_int:monoid_hom nat int := { to_fun := int.of_nat, map_mul' := begin intros x y, simp, end, map_one' := rfl, } def add_monoid_hom_nat_int:add_monoid_hom nat int := { to_fun := int.of_nat, map_add' := begin intros x y, simp, end, map_zero' := rfl, } def ring_hom_nat_int:ring_hom nat int := { ..monoid_hom_nat_int, ..add_monoid_hom_nat_int, } lemma ring_hom_nat_int_to_fun_def {n:ℕ}: ring_hom_nat_int.to_fun n = n := rfl lemma int.coe_nat_eq_coe_nat {a b:ℕ}:(a:ℤ) = (b:ℤ) ↔ a = b := begin split;intros A1, { simp at A1, apply A1, }, { simp, apply A1, }, end lemma ring_hom_nat_int_eq {a b:ℕ}:(ring_hom_nat_int.to_fun a)=(ring_hom_nat_int.to_fun b) ↔ a = b := begin repeat {rw ring_hom_nat_int_to_fun_def}, rw int.coe_nat_eq_coe_nat, end ------------------------Theorems of rat ---------------------------------------------- lemma rat.nonpos_of_num_nonpos {q:ℚ}:q.num ≤ 0 → q ≤ 0 := begin intro A1, have A3:(0:ℤ) < (((0:rat).denom):ℤ), { simp, apply (0:rat).pos, }, rw ← @rat.num_denom q, rw ← @rat.num_denom 0, rw rat.le_def, simp, have A4:(0:ℤ) < (((q:rat).denom):ℤ), { simp, apply (q:rat).pos, }, apply mul_nonpos_of_nonpos_of_nonneg, apply A1, apply le_of_lt, apply A3, { simp, apply q.pos, }, apply A3, end lemma rat.num_nonneg_of_nonneg {q:ℚ}:q≤ 0 → q.num ≤ 0 := begin intro A1, have A3:(0:ℤ) < (((0:rat).denom):ℤ), { simp, apply (0:rat).pos, }, have A4:(0:ℤ) < (((q:rat).denom):ℤ), { simp, apply (q:rat).pos, }, rw ← @rat.num_denom q at A1, rw ← @rat.num_denom 0 at A1, rw rat.le_def at A1, simp at A1, apply nonpos_of_mul_nonpos_right A1 A3, apply A4, apply A3, end lemma rat.nonpos_iff_num_nonpos {q:ℚ}:q.num ≤ 0 ↔ q ≤ 0 := begin have A3:(0:ℤ) < (((0:rat).denom):ℤ), { simp, apply (0:rat).pos, }, have A4:(0:ℤ) < (((q:rat).denom):ℤ), { simp, apply (q:rat).pos, }, rw ← @rat.num_denom q, rw ← @rat.num_denom 0, rw rat.le_def, simp, split;intros A1, { apply mul_nonpos_of_nonpos_of_nonneg, apply A1, apply le_of_lt, apply A3, }, { have B1:(0:ℤ) * ↑((0:ℚ).denom) = (0:ℤ) := zero_mul _, rw ← B1 at A1, apply le_of_mul_le_mul_right, apply A1, apply A3, }, apply A4, apply A3, end lemma rat.num_pos_of_pos {q:ℚ}:0 < q → 0 < q.num := begin intro A1, apply lt_of_not_le, rw ← not_le_iff_lt at A1, intro A2, apply A1, apply rat.nonpos_of_num_nonpos A2, end lemma rat.pos_iff_num_pos {q:ℚ}:0 < q ↔ 0 < q.num := begin split;intro A1, { apply lt_of_not_le, rw ← not_le_iff_lt at A1, intro A2, apply A1, apply rat.nonpos_of_num_nonpos A2, }, { apply lt_of_not_le, rw ← not_le_iff_lt at A1, intro A2, apply A1, apply rat.num_nonneg_of_nonneg A2, }, end def monoid_hom_int_rat:monoid_hom int rat := { to_fun := rat.of_int, map_mul' := begin intros x y, repeat {rw rat.of_int_eq_mk}, rw rat.mul_def one_ne_zero one_ne_zero, simp, end, map_one' := rfl, } def add_monoid_hom_int_rat:add_monoid_hom int rat := { to_fun := rat.of_int, map_add' := begin intros x y, repeat {rw rat.of_int_eq_mk}, rw rat.add_def one_ne_zero one_ne_zero, simp, end, map_zero' := rfl, } def ring_hom_int_rat:ring_hom int rat := { ..monoid_hom_int_rat, ..add_monoid_hom_int_rat, } lemma ring_hom_int_rat_to_fun_def {n:ℤ}: ring_hom_int_rat.to_fun n = rat.of_int n := rfl lemma ring_hom_int_rat_to_fun_def2 {n:ℤ}: ring_hom_int_rat.to_fun n = n := begin rw rat.coe_int_eq_of_int, rw ring_hom_int_rat_to_fun_def, end lemma ring_hom_int_rat_eq {a b:ℤ}:(ring_hom_int_rat.to_fun a)=(ring_hom_int_rat.to_fun b) ↔ (a = b) := begin repeat {rw ring_hom_int_rat_to_fun_def2}, simp, end def ring_hom_nat_rat:= ring_hom.comp ring_hom_int_rat ring_hom_nat_int lemma ring_hom_nat_rat_to_fun_def {n:ℕ}: ring_hom_nat_rat.to_fun n = ring_hom_int_rat.to_fun ( ring_hom_nat_int.to_fun n) := begin refl, end lemma ring_hom_nat_rat_to_fun_def2 {n:ℕ}: ring_hom_nat_rat.to_fun n = n := begin rw ring_hom_nat_rat_to_fun_def, rw ring_hom_nat_int_to_fun_def, rw ring_hom_int_rat_to_fun_def2, simp, end lemma ring_hom_nat_rat_eq {a b:ℕ}:(ring_hom_nat_rat.to_fun a)=(ring_hom_nat_rat.to_fun b) ↔ a = b := begin repeat {rw ring_hom_nat_rat_to_fun_def}, rw ring_hom_int_rat_eq, rw ring_hom_nat_int_eq, end lemma rat.exists_unit_frac_le_pos {q:ℚ}:0 < q → (∃ n:ℕ, (1/((n:rat) + 1)) ≤ q) := begin intro A1, have A3 := @rat.num_denom q, rw ← A3, apply exists.intro (q.denom.pred), have A2:(((nat.pred q.denom):rat) + 1) = q.denom, { have A2A:((@has_one.one ℕ _):ℚ) = 1 := rfl, rw ← A2A, repeat {rw ← ring_hom_nat_rat_to_fun_def2}, rw ← ring_hom_nat_rat.map_add', rw ring_hom_nat_rat_eq, have A2B:nat.pred q.denom + 1 = nat.succ (nat.pred q.denom) := rfl, rw A2B, rw nat.succ_pred_eq_of_pos, apply q.pos, }, rw A2, have A3:(1/(q.denom:rat))= rat.mk 1 q.denom, { have A3A:((1:nat):rat) = 1 := rfl, have A3B:((1:ℤ):rat)/((q.denom:ℤ):rat)=1/(q.denom:rat), { refl, }, rw ← A3B, rw ← rat.mk_eq_div, }, rw A3, rw rat.le_def, { simp, rw le_mul_iff_one_le_left, apply rat.num_pos_of_pos A1, simp, apply q.pos, }, repeat { simp, apply q.pos, }, end lemma rat.mk_pos_denom {p:ℤ} {n:pnat}:(rat.mk p (n:ℤ))= rat.mk_pnat p n := begin cases n, rw rat.mk_pnat_eq, simp, end lemma rat.pos_mk {p q:ℤ}:(0 < p) → (1 ≤ q) → 0 < (rat.mk p q) := begin intros A1 A2, cases q, { cases q, { -- q cannot be zero. exfalso, simp at A2, apply not_lt_of_le A2, apply zero_lt_one, }, let n := q.succ_pnat, begin have B1:(n:ℤ) = int.of_nat q.succ := rfl, rw ← B1, rw rat.mk_pos_denom, rw ← rat.num_pos_iff_pos, rw rat.mk_pnat_num, simp, cases p, { simp, rw ← int.coe_nat_div, have B2:((0:ℕ):ℤ) = (0:ℤ) := rfl, rw ← B2, rw int.coe_nat_lt, apply nat.div_pos, apply nat.gcd_le_left, simp at A1, apply A1, apply nat.gcd_pos_of_pos_right, simp, }, { -- p cannot be negative. exfalso, apply not_le_of_lt A1, apply le_of_lt, apply int.neg_succ_of_nat_lt_zero p, }, end }, -- q cannot be negative. rw ← rat.num_pos_iff_pos, unfold rat.mk, { exfalso, apply not_le_of_lt (int.neg_succ_of_nat_lt_zero q), apply le_of_lt, apply lt_of_lt_of_le, apply zero_lt_one, apply A2, }, end lemma rat.coe_int_div {p q:ℤ}:rat.mk p q = (p:ℚ) / (q:ℚ) := begin --rw rat.coe_int_eq_mk, --rw rat.coe_int_eq_mk, rw rat.div_num_denom, repeat {rw rat.coe_int_num}, repeat {rw rat.coe_int_denom}, have A1:((1:ℕ):ℤ)=1 := rfl, rw A1, simp, end ------------------------Theorems of real --------------------------------------------- lemma real.add_sub_add_eq_sub_add_sub {a b c d:real}: a + b - (c + d) = (a - c) + (b - d) := begin rw add_sub_assoc, rw sub_add_eq_sub_sub_swap, rw sub_add_eq_add_sub, rw add_sub_assoc, end lemma real.unit_frac_pos (n:ℕ):0 < (1/((n:real) + 1)) := begin simp, -- ⊢ 0 < ↑n + 1 rw add_comm, apply add_pos_of_pos_of_nonneg, { apply zero_lt_one, }, { simp, }, end lemma real.sub_lt_sub_of_lt {a b c:real}:a < b → a - c < b - c := begin intros A1, simp, apply A1, end lemma real.rat_le_rat_iff {q r:ℚ}:q ≤ r ↔ (q:ℝ) ≤ (r:ℝ) := begin rw ← real.of_rat_eq_cast, rw ← real.of_rat_eq_cast, rw le_iff_lt_or_eq, rw le_iff_lt_or_eq, split;intros A3;cases A3, { left, rw real.of_rat_lt, apply A3, }, { right, simp, apply A3, }, { left, rw ← real.of_rat_lt, apply A3, }, { right, simp at A3, apply A3, }, end lemma real.eq_add_of_sub_eq {a b c:real}: a - b = c → a = b + c := begin intros A1, have A2:((a:ℝ)-(b:ℝ))+(b:ℝ)=(c:ℝ)+(b:ℝ), { rw A1, }, simp at A2, rw add_comm at A2, apply A2, end lemma real.sub_add_sub {a b c:real}:(a - b) + (b - c) = a - c := begin rw ← add_sub_assoc, simp, end ------------------------Theorems of nnreal -------------------------------------------- lemma nnreal.not_add_le_of_lt {a b:nnreal}: (0 < b) → ¬(a + b) ≤ a := begin intros A1 A2, simp at A2, subst A2, apply lt_irrefl _ A1, end lemma nnreal.sub_lt_of_pos_of_pos {a b:nnreal}:(0 < a) → (0 < b) → (a - b) < a := begin intros A1 A2, cases (le_total a b) with A3 A3, { rw nnreal.sub_eq_zero A3, apply A1, }, { rw ← nnreal.coe_lt_coe, rw nnreal.coe_sub A3, rw ← nnreal.coe_lt_coe at A2, rw sub_lt_self_iff, apply A2, } end lemma nnreal.add_sub_add_eq_sub_add_sub {a b c d:nnreal}:c ≤ a → d ≤ b → a + b - (c + d) = (a - c) + (b - d) := begin intros A1 A2, have A3:c + d ≤ a + b, { apply add_le_add A1 A2, }, rw ← nnreal.eq_iff, rw nnreal.coe_sub A3, rw nnreal.coe_add, rw nnreal.coe_add, rw nnreal.coe_add, rw nnreal.coe_sub A1, rw nnreal.coe_sub A2, apply real.add_sub_add_eq_sub_add_sub, end lemma nnreal.sub_eq_of_add_of_le {a b c:nnreal}:a = b + c → c ≤ a → a - c = b := begin intros A1 A2, have A3:a - c + c = b + c, { rw nnreal.sub_add_cancel_of_le A2, apply A1, }, apply add_right_cancel A3, end lemma nnreal.inverse_le_of_le {a b:nnreal}: 0 < a → a ≤ b → b⁻¹ ≤ a⁻¹ := begin intros A1 A2, have B1: (a⁻¹ * b⁻¹) * a ≤ (a⁻¹ * b⁻¹) * b, { apply mul_le_mul, apply le_refl _, apply A2, simp, simp, }, rw mul_comm a⁻¹ b⁻¹ at B1, rw mul_assoc at B1, rw inv_mul_cancel at B1, rw mul_comm b⁻¹ a⁻¹ at B1, rw mul_assoc at B1, rw mul_one at B1, rw inv_mul_cancel at B1, rw mul_one at B1, apply B1, { have B1A := lt_of_lt_of_le A1 A2, intro B1B, subst b, simp at B1A, apply B1A, }, { intro C1, subst a, simp at A1, apply A1, }, end lemma nnreal.unit_frac_pos (n:ℕ):0 < (1/((n:nnreal) + 1)) := begin apply nnreal.div_pos, apply zero_lt_one, have A1:(0:nnreal) < (0:nnreal) + (1:nnreal), { simp, apply zero_lt_one, }, apply lt_of_lt_of_le A1, rw add_comm (0:nnreal) 1, rw add_comm _ (1:nnreal), apply add_le_add_left, simp, end lemma nnreal.real_le_real {q r:ℝ}:q ≤ r → (nnreal.of_real q ≤ nnreal.of_real r) := begin intro A1, cases (le_total 0 q) with A2 A2, { have A3 := le_trans A2 A1, rw ← @nnreal.coe_le_coe, rw nnreal.coe_of_real q A2, rw nnreal.coe_of_real r A3, apply A1, }, { have B1 := nnreal.of_real_of_nonpos A2, rw B1, simp, }, end lemma nnreal.rat_le_rat {q r:ℚ}:q ≤ r → (nnreal.of_real q ≤ nnreal.of_real r) := begin rw real.rat_le_rat_iff, apply nnreal.real_le_real, end lemma nnreal.real_lt_nnreal_of_real_le_real_of_real_lt_nnreal {q r:real} {s:nnreal}: q ≤ r → (nnreal.of_real r) < s → (nnreal.of_real q) < s := begin intros A1 A2, apply lt_of_le_of_lt _ A2, apply nnreal.real_le_real, apply A1, end lemma nnreal.rat_lt_nnreal_of_rat_le_rat_of_rat_lt_nnreal {q r:ℚ} {s:nnreal}: q ≤ r → (nnreal.of_real r) < s → (nnreal.of_real q) < s := begin intros A1 A2, rw real.rat_le_rat_iff at A1, apply nnreal.real_lt_nnreal_of_real_le_real_of_real_lt_nnreal A1 A2, end lemma nnreal.of_real_inv_eq_inv_of_real {x:real}:(0 ≤ x) → nnreal.of_real x⁻¹ = (nnreal.of_real x)⁻¹ := begin intro A1, rw ← nnreal.eq_iff, simp, have A2:0 ≤ x⁻¹, { apply inv_nonneg.2 A1, }, rw nnreal.coe_of_real x A1, rw nnreal.coe_of_real _ A2, end lemma nnreal.one_div_eq_inv {x:nnreal}:1/x = x⁻¹ := begin rw nnreal.div_def, rw one_mul, end lemma nnreal.exists_unit_frac_lt_pos {ε:nnreal}:0 < ε → (∃ n:ℕ, (1/((n:nnreal) + 1)) < ε) := begin intro A1, have A2 := A1, rw nnreal.lt_iff_exists_rat_btwn at A2, cases A2 with q A2, cases A2 with A2 A3, cases A3 with A3 A4, simp at A3, have A5 := rat.exists_unit_frac_le_pos A3, cases A5 with n A5, apply exists.intro n, simp at A5, rw nnreal.one_div_eq_inv, have B2:(0:ℝ) ≤ 1, { apply le_of_lt, apply zero_lt_one, }, have A7:nnreal.of_real 1 = (1:nnreal), { rw ← nnreal.coe_eq, rw nnreal.coe_of_real, rw nnreal.coe_one, apply B2, }, rw ← A7, have A8:nnreal.of_real n = n, { rw ← nnreal.coe_eq, rw nnreal.coe_of_real, simp, simp, }, rw ← A8, have B1:(0:ℝ) ≤ n, { simp, }, have B3:(0:ℝ) ≤ n + (1:ℝ), { apply le_trans B1, simp, apply B2 }, rw ← nnreal.of_real_add B1 B2, rw ← nnreal.of_real_inv_eq_inv_of_real B3, have A9 := nnreal.rat_le_rat A5, have A10:((n:ℝ) + 1)⁻¹ = (↑((n:ℚ) + 1)⁻¹:ℝ), { simp, }, rw A10, apply lt_of_le_of_lt A9 A4, end lemma nnreal.of_real_div {x y:real}:0 ≤ x → 0 ≤ y → nnreal.of_real (x / y) = nnreal.of_real x / nnreal.of_real y := begin intros A1 A2, rw ← nnreal.coe_eq, rw nnreal.coe_of_real, simp, repeat {rw nnreal.coe_of_real}, apply A2, apply A1, apply div_nonneg A1 A2, end lemma nnreal.of_real_eq_coe_nat {n:ℕ}:nnreal.of_real n = n := begin rw ← nnreal.coe_eq, rw nnreal.coe_of_real, repeat {simp}, end lemma nnreal.sub_le_sub_of_le {a b c:nnreal}:b ≤ a → c - a ≤ c - b := begin intro A1, cases (classical.em (a ≤ c)) with B1 B1, { rw ← nnreal.coe_le_coe, rw nnreal.coe_sub B1, have B2:=le_trans A1 B1, rw nnreal.coe_sub B2, simp, rw nnreal.coe_le_coe, apply A1, }, { simp at B1, have C1:= le_of_lt B1, rw nnreal.sub_eq_zero C1, simp }, end --Replace c < b with c ≤ a. lemma nnreal.sub_lt_sub_of_lt_of_lt {a b c:nnreal}:a < b → c ≤ a → a - c < b - c := begin intros A1 A2, rw ← nnreal.coe_lt_coe, rw nnreal.coe_sub A2, have B1:=lt_of_le_of_lt A2 A1, have B2 := le_of_lt B1, rw nnreal.coe_sub B2, apply real.sub_lt_sub_of_lt, rw nnreal.coe_lt_coe, apply A1, end lemma nnreal.sub_lt_sub_of_lt_of_le {a b c d:nnreal}:a < b → c ≤ d → d ≤ a → a - d < b - c := begin intros A1 A2 A3, have A3:a - d < b - d, { apply nnreal.sub_lt_sub_of_lt_of_lt A1 A3, }, apply lt_of_lt_of_le A3, apply nnreal.sub_le_sub_of_le A2, end lemma nnreal.eq_add_of_sub_eq {a b c:nnreal}:b ≤ a → a - b = c → a = b + c := begin intros A1 A2, apply nnreal.eq, rw nnreal.coe_add, rw ← nnreal.eq_iff at A2, rw nnreal.coe_sub A1 at A2, apply real.eq_add_of_sub_eq A2, end lemma nnreal.sub_add_sub {a b c:nnreal}:c ≤ b → b ≤ a → (a - b) + (b - c) = a - c := begin intros A1 A2, rw ← nnreal.coe_eq, rw nnreal.coe_add, repeat {rw nnreal.coe_sub}, apply real.sub_add_sub, apply le_trans A1 A2, apply A1, apply A2, end ------------------------Theorems of ennreal ------------------------------------------- lemma le_coe_ne_top {x:nnreal} {y:ennreal}:y≤(x:ennreal) → y≠ ⊤ := begin intro A1, have A2:(x:ennreal)< ⊤, { apply with_top.coe_lt_top, }, have A3:y < ⊤, { apply lt_of_le_of_lt, apply A1, apply A2, }, rw ← lt_top_iff_ne_top, apply A3, end --Unnecessary lemma upper_bounds_nnreal (s : set ennreal) {x:nnreal} {y:ennreal}: (x:ennreal) ∈ upper_bounds s → (y∈ s) → y≠ ⊤:= begin intros A1 A2, rw mem_upper_bounds at A1, have A3 := A1 y A2, apply le_coe_ne_top A3, end --Unnecessary lemma upper_bounds_nnreal_fn {α:Type*} {f:α → ennreal} {x:nnreal}: (x:ennreal) ∈ upper_bounds (set.range f) → (∃ g:α → nnreal, f = (λ a:α, (g a:ennreal))) := begin intro A1, let g:α → nnreal := λ a:α, ((f a).to_nnreal), begin have A2:g = λ a:α, ((f a).to_nnreal) := rfl, apply exists.intro g, rw A2, ext a, split;intro A3, { simp, simp at A3, rw A3, rw ennreal.to_nnreal_coe, }, { simp, simp at A3, rw ← A3, symmetry, apply ennreal.coe_to_nnreal, apply upper_bounds_nnreal, apply A1, simp, }, end end lemma ennreal.infi_le {α:Type*} {f:α → ennreal} {b : ennreal}: (∀ (ε : nnreal), 0 < ε → b < ⊤ → (∃a, f a ≤ b + ↑ε)) → infi f ≤ b := begin intro A1, apply @ennreal.le_of_forall_epsilon_le, intros ε A2 A3, have A4 := A1 ε A2 A3, cases A4 with a A4, apply le_trans _ A4, apply @infi_le ennreal _ _, end lemma ennreal.le_supr {α:Type*} {f:α → ennreal} {b : ennreal}:(∀ (ε : nnreal), 0 < ε → (supr f < ⊤) → (∃a, b ≤ f a + ε)) → b ≤ supr f := begin intro A1, apply @ennreal.le_of_forall_epsilon_le, intros ε A2 A3, have A4 := A1 ε A2 A3, cases A4 with a A4, apply le_trans A4, have A5:=@le_supr ennreal _ _ f a, apply add_le_add A5, apply le_refl _, end lemma ennreal.not_add_le_of_lt_of_lt_top {a b:ennreal}: (0 < b) → (a < ⊤) → ¬(a + b) ≤ a := begin intros A1 A2 A3, have A4:(⊤:ennreal) = none := rfl, cases a, { simp at A2, apply A2, }, cases b, { rw ←A4 at A3, rw with_top.add_top at A3, rw top_le_iff at A3, simp at A3, apply A3, }, simp at A3, rw ← ennreal.coe_add at A3, rw ennreal.coe_le_coe at A3, simp at A1, apply nnreal.not_add_le_of_lt A1, apply A3, end lemma ennreal.lt_add_of_pos_of_lt_top {a b:ennreal}: (0 < b) → (a < ⊤) → a < a + b := begin intros A1 A2, apply lt_of_not_le, apply ennreal.not_add_le_of_lt_of_lt_top A1 A2, end lemma ennreal.infi_elim {α:Sort*} {f:α → ennreal} {ε:nnreal}: (0 < ε) → (infi f < ⊤) → (∃a, f a ≤ infi f + ↑ε) := begin intros A1 A2, have A3:¬(infi f+(ε:ennreal)≤ infi f), { apply ennreal.not_add_le_of_lt_of_lt_top _ A2, simp, apply A1, }, apply (@classical.exists_of_not_forall_not α (λ (a : α), f a ≤ infi f + ↑ε)), intro A4, apply A3, apply @le_infi ennreal α _, intro a, cases (le_total (infi f + ↑ε) (f a)) with A5 A5, apply A5, have A6 := A4 a, exfalso, apply A6, apply A5, end lemma ennreal.zero_le {a:ennreal}:0 ≤ a := begin simp, end lemma ennreal.sub_top {a:ennreal}:a - ⊤ = 0 := begin simp, end lemma ennreal.sub_lt_of_pos_of_pos {a b:ennreal}:(0 < a) → (0 < b) → (a ≠ ⊤) → (a - b) < a := begin intros A1 A2 A3, cases a, { exfalso, simp at A3, apply A3, }, cases b, { rw ennreal.none_eq_top, rw ennreal.sub_top, apply A1, }, simp, rw ← ennreal.coe_sub, rw ennreal.coe_lt_coe, apply nnreal.sub_lt_of_pos_of_pos, { simp at A1, apply A1, }, { simp at A2, apply A2, }, end lemma ennreal.Sup_elim {S:set ennreal} {ε:nnreal}: (0 < ε) → (S.nonempty) → (Sup S ≠ ⊤) → (∃s∈S, (Sup S) - ε ≤ s) := begin intros A1 A2 A3, cases classical.em (Sup S = 0) with A4 A4, { rw A4, have A5:= set.nonempty_def.mp A2, cases A5 with s A5, apply exists.intro s, apply exists.intro A5, simp, }, have A5:(0:ennreal) = ⊥ := rfl, have B1:(Sup S) - ε < (Sup S), { apply ennreal.sub_lt_of_pos_of_pos, rw A5, rw bot_lt_iff_ne_bot, rw ← A5, apply A4, simp, apply A1, apply A3, }, rw lt_Sup_iff at B1, cases B1 with a B1, cases B1 with B2 B3, apply exists.intro a, apply exists.intro B2, apply le_of_lt B3, end lemma ennreal.top_of_infi_top {α:Type*} {g:α → ennreal} {a:α}:((⨅ a', g a') = ⊤) → (g a = ⊤) := begin intro A1, rw ← top_le_iff, rw ← A1, apply @infi_le ennreal α _, end lemma of_infi_lt_top {P:Prop} {H:P→ ennreal}:infi H < ⊤ → P := begin intro A1, cases (classical.em P) with A2 A2, { apply A2, }, { exfalso, unfold infi at A1, unfold set.range at A1, have A2:{x : ennreal | ∃ (y : P), H y = x}=∅, { ext;split;intro A2A, simp at A2A, exfalso, cases A2A with y A2A, apply A2, apply y, exfalso, apply A2A, }, rw A2 at A1, simp at A1, apply A1, }, end lemma ennreal.add_le_add_left {a b c:ennreal}: b ≤ c → a + b ≤ a + c := begin intro A1, cases a, { simp, }, cases b, { simp at A1, subst c, simp, }, cases c, { simp, }, simp, simp at A1, repeat {rw ← ennreal.coe_add}, rw ennreal.coe_le_coe, apply @add_le_add_left nnreal _, apply A1, end lemma ennreal.le_of_add_le_add_left {a b c:ennreal}:a < ⊤ → a + b ≤ a + c → b ≤ c := begin intros A1 A2, cases a, { exfalso, simp at A1, apply A1, }, cases c, { simp, }, cases b, { exfalso, simp at A2, rw ← ennreal.coe_add at A2, apply ennreal.coe_ne_top A2, }, simp, simp at A2, repeat {rw ← ennreal.coe_add at A2}, rw ennreal.coe_le_coe at A2, apply le_of_add_le_add_left A2, end lemma ennreal.le_of_add_le_add_right {a b c:ennreal}:(c < ⊤)→ (a + c ≤ b + c) → (a ≤ b) := begin intros A1 A2, rw add_comm a c at A2, rw add_comm b c at A2, apply ennreal.le_of_add_le_add_left A1 A2, end lemma ennreal.top_sub_some {a:nnreal}:(⊤:ennreal) - a = ⊤ := begin simp, end lemma ennreal.add_sub_add_eq_sub_add_sub {a b c d:ennreal}:c < ⊤ → d < ⊤ → c ≤ a → d ≤ b → a + b - (c + d) = (a - c) + (b - d) := begin intros A1 A2 A3 A4, cases c, { simp at A1, exfalso, apply A1, }, cases d, { simp at A2, exfalso, apply A2, }, cases a, { simp, rw ← ennreal.coe_add, apply ennreal.top_sub_some, }, cases b, { simp, rw ← ennreal.coe_add, apply ennreal.top_sub_some, }, simp, rw ← ennreal.coe_add, rw ← ennreal.coe_add, rw ← ennreal.coe_sub, rw ← ennreal.coe_sub, rw ← ennreal.coe_sub, rw ← ennreal.coe_add, rw ennreal.coe_eq_coe, simp at A3, simp at A4, apply nnreal.add_sub_add_eq_sub_add_sub A3 A4, end lemma ennreal.le_add {a b c:ennreal}:a ≤ b → a ≤ b + c := begin intro A1, apply @le_add_of_le_of_nonneg ennreal _, apply A1, simp, end lemma ennreal.add_lt_add_of_lt_of_le_of_lt_top {a b c d:ennreal}:d < ⊤ → c ≤ d → a < b → a + c < b + d := begin intros A1 A2 A3, rw le_iff_lt_or_eq at A2, cases A2 with A2 A2, { apply ennreal.add_lt_add A3 A2, }, subst d, rw with_top.add_lt_add_iff_right, apply A3, apply A1, end lemma ennreal.le_of_sub_eq_zero {a b:ennreal}: a - b = 0 → a ≤ b := begin intros A1, simp at A1, apply A1, end lemma ennreal.le_zero_iff {a:ennreal}:a ≤ 0 ↔ a=0 := begin simp end lemma ennreal.sub_le {a b:ennreal}:a - b ≤ a := begin simp, apply ennreal.le_add, apply le_refl _, end lemma ennreal.multiply_mono {α β:Type*} [preorder α] {f g:α → β → ennreal}: monotone f → monotone g → monotone (f * g) := begin intros A1 A2 a1 a2 A3, rw le_func_def2, intro b, simp, apply @ennreal.mul_le_mul (f a1 b) (f a2 b) (g a1 b) (g a2 b), { apply A1, apply A3, }, { apply A2, apply A3, }, end lemma ennreal.supr_zero_iff_zero {α:Type*} {f:α → ennreal}: supr f = 0 ↔ f = 0 := begin have A0:(0:ennreal) = ⊥ := rfl, rw A0, have A1:f = 0 ↔ (∀ a:α, f a = 0), { split; intro A1, { intro a, rw A1, simp, }, apply funext, intro a, simp, apply A1, }, rw A1, split;intros A2, { intro a, rw A0, rw ← @le_bot_iff ennreal _ (f a), rw ← A2, apply le_supr f, }, { rw ← @le_bot_iff ennreal _ (supr f), apply @supr_le ennreal α _ f, intro a, rw @le_bot_iff ennreal _ (f a), rw ← A0, apply A2, }, end lemma le_supr_mul_of_supr_zero {α:Type*} {f g:α → ennreal}:supr f = 0 → (supr f) * (supr g) ≤ supr (f * g) := begin intro A1, rw A1, rw zero_mul, apply @bot_le ennreal _, end lemma ennreal.zero_of_mul_top_lt {a b:ennreal}:a * ⊤ < b → a = 0 := begin intro A1, have A2:a=0 ∨ a≠ 0 := eq_or_ne, cases A2, { apply A2, }, { exfalso, rw with_top.mul_top A2 at A1, apply @not_top_lt ennreal _ b, apply A1, }, end lemma ennreal.sub_add_sub {a b c:ennreal}:c ≤ b → b ≤ a → (a - b) + (b - c) = a - c := begin intros A1 A2, cases c, { rw ennreal.none_eq_top at A1, rw top_le_iff at A1, subst b, rw top_le_iff at A2, subst a, simp, }, rw ennreal.some_eq_coe at A1, rw ennreal.some_eq_coe, cases b, { rw ennreal.none_eq_top at A2, rw top_le_iff at A2, subst a, simp, }, rw ennreal.some_eq_coe at A1, rw ennreal.some_eq_coe at A2, rw ennreal.some_eq_coe, cases a, { simp, }, rw ennreal.some_eq_coe at A2, rw ennreal.some_eq_coe, repeat {rw ← ennreal.coe_sub}, repeat {rw ← ennreal.coe_add}, rw ennreal.coe_eq_coe, rw ennreal.coe_le_coe at A1, rw ennreal.coe_le_coe at A2, apply nnreal.sub_add_sub A1 A2, end lemma ennreal.lt_div_iff_mul_lt {a b c : ennreal}: (b ≠ 0) → (b ≠ ⊤) → (a < c / b ↔ a * b < c) := begin intros A1 A2, cases b, { exfalso, simp at A2, apply A2, }, cases a, { simp, rw mul_comm, rw with_top.mul_top, apply @le_top ennreal _, apply A1, }, simp at A2, cases c, { simp, rw ennreal.div_def, rw mul_comm, rw with_top.mul_top, split;intros A3, { rw ← ennreal.coe_mul, apply with_top.coe_lt_top, }, { simp, }, { simp, }, }, simp, split;intros A3, { rw lt_iff_le_not_eq, split, { rw ← ennreal.le_div_iff_mul_le, apply @le_of_lt ennreal _ (↑a) ((↑c)/(↑b)), apply A3, apply or.inl A1, left, simp, }, { intro A4, rw ← A4 at A3, rw ennreal.mul_div_assoc at A3, rw @ennreal.div_self at A3, simp at A3, have A5 := ne_of_lt A3, simp at A5, apply A5, apply A1, have A6 := @with_top.none_lt_some nnreal _ b, apply ne_of_lt A6, }, }, { rw lt_iff_le_not_eq, split, { rw ennreal.le_div_iff_mul_le, apply @le_of_lt ennreal _, apply A3, apply or.inl A1, left, simp, }, { intro A4, rw A4 at A3, rw ennreal.mul_div_cancel at A3, simp at A3, have A5 := ne_of_lt A3, simp at A5, apply A5, apply A1, have A6 := @with_top.none_lt_some nnreal _ b, apply ne_of_lt A6, }, }, end lemma ennreal.lt_of_mul_lt_mul {a b c:ennreal}: (b ≠ 0) → (b ≠ ⊤) → (a < c) → (a * b < c * b) := begin intros A1 A2 A3, apply ennreal.mul_lt_of_lt_div, rw ennreal.mul_div_assoc, have A4:(b/b)=1, { apply ennreal.div_self, apply A1, apply A2, }, rw A4, simp, apply A3, end ---------------------- Theorems of topology ------------------------------------------------------ lemma Pi.topological_space_def {α:Type*} {β : α → Type*} [t₂ : Πa, topological_space (β a)] : @Pi.topological_space α β t₂ = ⨅a, topological_space.induced (λf, f a) (t₂ a) := rfl lemma Pi.topological_space_le_induced {α:Type*} {β : α → Type*} [t₂ : Πa, topological_space (β a)] {a:α}:@Pi.topological_space α β t₂ ≤ topological_space.induced (λf, f a) (t₂ a) := begin rw Pi.topological_space_def, have A1:(λ a2:α, topological_space.induced (λf:(Π a:α, β a) , f a2) (t₂ a2)) a = topological_space.induced (λf, f a) (t₂ a) := rfl, rw ← A1, apply infi_le (λ a2:α, topological_space.induced (λf:(Π a:α, β a) , f a2) (t₂ a2)), end lemma is_open_iff_is_open {α:Type*} {T:topological_space α} {U:set α}: is_open U = topological_space.is_open T U := rfl lemma topological_space_le_is_open {α:Type*} {T1 T2:topological_space α}: ((topological_space.is_open T1)≤ (topological_space.is_open T2)) = (T2 ≤ T1) := rfl lemma topological_space_le_is_open_2 {α:Type*} {T1 T2:topological_space α}: (T1 ≤ T2) ↔ (∀ S:set α, topological_space.is_open T2 S → topological_space.is_open T1 S) := begin rw ← topological_space_le_is_open, rw set.le_eq_subset, rw set.subset_def, refl, end --These are the most basic open sets: don't even form a basis. lemma Pi.topological_space_is_open {α:Type*} {β : α → Type*} [t₂ : Πa, topological_space (β a)] {a:α} (S:set (Π a:α, β a)): topological_space.is_open (topological_space.induced (λf:(Π a:α, β a), f a) (t₂ a)) S → topological_space.is_open (@Pi.topological_space α β t₂) S := begin have A1:=@Pi.topological_space_le_induced α β t₂ a, rw topological_space_le_is_open_2 at A1, apply A1 S, end lemma topological_space_infi {α β:Type*} {T:β → topological_space α}: (⨅ b:β, T b) = topological_space.generate_from ( (⋃ b:β, (T b).is_open)) := begin apply le_antisymm, { rw le_generate_from_iff_subset_is_open, rw set.subset_def, intros U A1, simp at A1, simp, cases A1 with b A1, have A2:infi T ≤ T b, { have A3:T b ≤ T b, { apply le_refl (T b), }, apply (infi_le_of_le b) A3, }, rw topological_space_le_is_open_2 at A2, apply A2, apply A1, }, { apply @le_infi (topological_space α) _ _, intro b, rw topological_space_le_is_open_2, intros S A1, unfold topological_space.generate_from, simp, apply topological_space.generate_open.basic, simp, apply exists.intro b, apply A1, }, end lemma is_open_infi_elim {α β:Type*} [decidable_eq β] {T:β → topological_space α} {U:set α} {x:α}: (x∈ U) → topological_space.is_open (⨅ b:β, T b) U → (∃ S:finset β, ∃ f:β →set α, (∀ s∈ S, topological_space.is_open (T s) (f s)) ∧ (∀ s∈ S, x ∈ f s) ∧ (⋂s∈ S, f s)⊆ U) := begin intros A1 A2, rw @topological_space_infi α β T at A2, unfold topological_space.generate_from at A2, simp at A2, induction A2, { simp at A2_H, cases A2_H with b A2, apply exists.intro ({b}), { apply exists.intro (λ b:β, A2_s), split, { intros b2 A3, simp, rw @finset.mem_singleton β b b2 at A3, rw A3, apply A2, }, split, { intros b2 A3, simp, apply A1, }, { rw set.subset_def, intros x2 A3, simp at A3, apply A3, }, }, }, { apply exists.intro ∅, apply exists.intro (λ b:β, set.univ), split, { intros b A2, simp, apply topological_space.is_open_univ, }, split, { intros b A2, simp, }, { apply set.subset_univ, }, { apply finset.has_emptyc, }, }, { simp at A1, cases A1 with A3 A4, have A5 := A2_ih_a A3, cases A5 with S A5, cases A5 with f A5, have A6 := A2_ih_a_1 A4, cases A6 with S2 A6, cases A6 with f2 A6, let z:β → set α := λ b:β, if (b∈ S) then (if (b∈ S2) then ((f b) ∩ (f2 b)) else f b) else (f2 b), begin have B1:z = λ b:β, if (b∈ S) then (if (b∈ S2) then ((f b) ∩ (f2 b)) else f b) else (f2 b) := rfl, apply exists.intro (S ∪ S2), apply exists.intro z, split, { intros s B2, rw union_trichotomy at B2, rw B1, simp, cases B2, { rw if_pos B2.left, rw if_neg B2.right, apply A5.left s B2.left, }, cases B2, { rw if_pos B2.left, rw if_pos B2.right, apply topological_space.is_open_inter, apply A5.left s B2.left, apply A6.left s B2.right, }, { rw if_neg B2.left, apply A6.left s B2.right, }, }, split, { intros s B2, rw B1, simp, rw union_trichotomy at B2, cases B2, { rw if_pos B2.left, rw if_neg B2.right, apply A5.right.left s B2.left, }, cases B2, { rw if_pos B2.left, rw if_pos B2.right, simp, split, apply A5.right.left s B2.left, apply A6.right.left s B2.right, }, { rw if_neg B2.left, apply A6.right.left s B2.right, }, }, { rw set.subset_def, rw B1, intros a B2, simp at B2, split, { have B3 := A5.right.right, rw set.subset_def at B3, apply B3, simp, intros b B4, have B5 := B2 b (or.inl B4), rw if_pos B4 at B5, have B6:(b ∈ S2) ∨ (b ∉ S2), { apply classical.em, }, cases B6, { rw if_pos B6 at B5, simp at B5, apply B5.left, }, { rw if_neg B6 at B5, apply B5, }, }, { have B3 := A6.right.right, rw set.subset_def at B3, apply B3, simp, intros b B4, have B5 := B2 b (or.inr B4), rw if_pos B4 at B5, have B6:(b ∈ S) ∨ (b ∉ S), { apply classical.em, }, cases B6, { rw if_pos B6 at B5, simp at B5, apply B5.right, }, { rw if_neg B6 at B5, apply B5, }, }, }, end }, { simp at A1, cases A1 with S A1, cases A1 with A3 A4, have A5 := A2_ih S A3 A4, cases A5 with S2 A5, cases A5 with f A5, apply exists.intro S2, apply exists.intro f, cases A5 with A5 A6, cases A6 with A6 A7, split, { apply A5, }, split, { apply A6, }, { apply set.subset.trans, apply A7, apply set.subset_sUnion_of_mem, apply A3, }, }, end def product_basis {α:Type*} {β : α → Type*} (S:finset α) (f:Π a:α, set (β a)):set (Πa, β a) := {x:Πa, β a|∀ a∈ S, x a ∈ f a} lemma product_basis_def {α:Type*} {β : α → Type*} {S:finset α} {f:Π a:α, set (β a)}: product_basis S f = {x:Πa, β a|∀ a∈ S, x a ∈ f a} := rfl lemma finite_inter_insert {α:Type*} [decidable_eq α] {β : Type*} {S:finset α} {a:α} {f:Π a:α, set (β)}:(⋂ (a2:α) (H:a2∈ (insert a S)), f a2) = (⋂ (a2:α) (H:a2∈ (S)), f a2) ∩ (f a) := begin ext b, split;intro A1, { simp, simp at A1, split, { intros i A2, apply A1.right i, apply A2, }, { apply A1.left, }, }, { simp, simp at A1, apply and.intro A1.right A1.left, }, end lemma is_open_finite_inter {α:Type*} [decidable_eq α] {β : Type*} [topological_space β] {S:finset α} {f:Π a:α, set (β)}: (∀ a∈ S, is_open (f a)) → is_open (⋂ (a:α) (H:a∈ S), f a) := begin apply finset.induction_on S, intro A1, { simp, }, { intros a S A2 A3 A4, rw finite_inter_insert, apply is_open_inter, { apply A3, simp at A4, intros a2 A5, apply A4, apply or.inr A5, }, { apply A4, simp, }, }, end --This is missing that f b is open. lemma Pi.is_open_topological_space {α:Type*} {β : α → Type*} [decidable_eq α] [t₂ : Πa, topological_space (β a)] {U:set (Π a, β a)} {x:(Π a, β a)}: (x∈ U) → (@is_open _ (@Pi.topological_space α β t₂) U) → (∃ S:finset α, ∃ (f:Π a:α, set (β a)), x∈ product_basis S f ∧ (∀ a∈ S, (is_open (f a))) ∧ product_basis S f ⊆ U) := begin intros AX A1, rw Pi.topological_space_def at A1, have A2 := is_open_infi_elim AX A1, cases A2 with S A2, cases A2 with f A2, cases A2 with A2 A3, cases A3 with A3A A3B, apply exists.intro S, unfold product_basis, have A4:∀ s∈ S, ∃ t:set (β s), @is_open (β s) (t₂ s) t ∧ (λ (f : Π (a : α), β a), f s) ⁻¹' t = f s, { intros s A4A, have A4B := A2 s A4A, simp at A4B, rw ← is_open_iff_is_open at A4B, rw @is_open_induced_iff (Π (a: α), β a) (β s) (t₂ s) (f s) (λ (f : Π (a : α), β a), f s) at A4B, cases A4B with t A4B, apply exists.intro t, apply A4B, }, let z:(Π (a:α), set (β a)) := λ (a:α), (@dite (a∈ S) _ (set (β a)) (λ h:(a∈ S), @classical.some _ _ (A4 a h)) (λ h, ∅)), begin have A5:z= λ (a:α), (@dite (a∈ S) _ (set (β a)) (λ h:(a∈ S), @classical.some _ _ (A4 a h)) (λ h, ∅)) := rfl, have AY:∀ s∈ S, is_open (z s) ∧ ( λ (f : Π (a : α), β a), f s) ⁻¹' (z s) = f s, { intros i A8, have A10 := A4 i A8, have A11:(λ q:set (β i), @is_open (β i) (t₂ i) q ∧ (λ (f : Π (a : α), β a), f i) ⁻¹' q = f i) ((@classical.some (set (β i)) (λ (t : set (β i)), @is_open (β i) (t₂ i) t ∧ (λ (f : Π (a : α), β a), f i) ⁻¹' t = f i)) A10), { apply @classical.some_spec (set (β i)) (λ q:set (β i), @is_open (β i) (t₂ i) q ∧ (λ (f : Π (a : α), β a), f i) ⁻¹' q = f i), }, have A12:z i = (classical.some A10), { rw A5, simp, rw dif_pos A8, }, rw ← A12 at A11, apply A11, }, apply exists.intro z, have A6:{x : Π (a : α), β a | ∀ (a : α), a ∈ S → x a ∈ z a} = (⋂ (s : α) (H : s ∈ S), f s) , { ext k, split;intros A7, { simp, simp at A7, intros i A8, have A9 := A7 i A8, cases (AY i A8) with A11 A12, rw ← A12, simp, apply A9, }, { simp, simp at A7, intros i A8, have A9 := AY i A8, cases A9 with A10 A11, have A12 := A7 i A8, rw ← A11 at A12, simp at A12, apply A12, }, }, rw A6, split, { simp, apply A3A, }, split, { intros a A7, apply (AY a A7).left, }, { apply A3B, }, end end ------ Measure theory -------------------------------------------------------------------------- lemma simple_func_to_fun {Ω:Type*} {M:measurable_space Ω} (g:measure_theory.simple_func Ω ennreal):⇑g = g.to_fun := rfl def is_absolutely_continuous_wrt {Ω:Type*} {M:measurable_space Ω} (μ ν:measure_theory.measure Ω):Prop := ∀ A:set Ω, is_measurable A → (ν A = 0) → (μ A = 0) lemma measure_zero_of_is_absolutely_continuous_wrt {Ω:Type*} {M:measurable_space Ω} (μ ν:measure_theory.measure Ω) (A:set Ω): is_absolutely_continuous_wrt μ ν → is_measurable A → (ν A = 0) → (μ A = 0) := begin intros A1 A2 A3, unfold is_absolutely_continuous_wrt at A1, apply A1 A A2 A3, end noncomputable def lebesgue_measure_on_borel := measure_theory.real.measure_space.volume lemma lebesgue_measure_on_borel_def: lebesgue_measure_on_borel = measure_theory.real.measure_space.volume := rfl lemma lebesgue_measure_on_borel_apply {S:set ℝ}: lebesgue_measure_on_borel S = measure_theory.lebesgue_outer S := rfl def is_absolutely_continuous_wrt_lebesgue (μ:measure_theory.measure ℝ):Prop := is_absolutely_continuous_wrt μ lebesgue_measure_on_borel lemma prob_zero_of_is_absolute_continuous_wrt_lebesgue (μ:measure_theory.measure ℝ) (E:set ℝ):is_absolutely_continuous_wrt_lebesgue μ → is_measurable E → measure_theory.lebesgue_outer E = 0 → μ E=0 := begin intros A1 A2 A3, apply measure_zero_of_is_absolutely_continuous_wrt μ lebesgue_measure_on_borel _ A1 A2, rw lebesgue_measure_on_borel_apply, apply A3, end lemma outer_measure.has_coe_to_fun_def {Ω:Type*} (O:measure_theory.outer_measure Ω): ⇑O = O.measure_of := rfl lemma outer_measure.ext2 {Ω:Type*} (O1 O2:measure_theory.outer_measure Ω): (O1.measure_of = O2.measure_of) → (O1 = O2) := begin intro A1, apply measure_theory.outer_measure.ext, intro s, repeat {rw outer_measure.has_coe_to_fun_def}, rw A1, end lemma measurable_set_indicator {Ω:Type*} {M:measurable_space Ω} (s:set Ω) (f:Ω → ennreal): (is_measurable s) → (measurable f) → measurable (set.indicator s f) := begin intros A1 A2, unfold set.indicator, apply measurable.if, apply A1, apply A2, apply measurable_const, end lemma filter.has_mem_def {α : Type*} (S:set α) (F:filter α): S ∈ F = (S∈ F.sets) := rfl def finset.Union {α:Type*} [decidable_eq α] (S:finset (finset α)):finset α := @finset.fold (finset α) (finset α) (@has_union.union (finset α) _) _ _ ∅ id S lemma finset.Union_insert {α:Type*} [decidable_eq α] (S:finset (finset α)) {T:finset α}:(T∉ S) → finset.Union (insert T S) = T ∪ (finset.Union S) := begin intro A1, unfold finset.Union, rw finset.fold_insert A1, simp, end lemma finset.subset_Union {α:Type*} [decidable_eq α] {S:finset (finset α)} {T:finset α}:T ∈ S → T ⊆ (finset.Union S) := begin apply finset.induction_on S, { intros A1, exfalso, simp at A1, apply A1, }, { intros T2 S2 A1 A2 A3, simp at A3, rw finset.Union_insert, cases A3, { subst T2, apply finset.subset_union_left, }, { apply finset.subset.trans (A2 A3), apply finset.subset_union_right, }, apply A1, }, end lemma has_sum_product {α β:Type*} [Dα:decidable_eq α] [Dβ:decidable_eq β] {γ:β → Type*} [Π b:β,add_comm_monoid (γ b)] [T:Π b:β,topological_space (γ b)] {f:α → (Π b:β, γ b)} {g:Π b:β, γ b}: (∀ b:β, has_sum (λ n, f n b) (g b)) → has_sum f g := begin intro A1, unfold has_sum filter.tendsto filter.map, rw le_nhds_iff, intros S A1A A2, rw Pi.topological_space_def at A2, rw ← filter.has_mem_def, simp, --At some point, we want to apply filter_at_top_intro3, but --only after we better understand the set S. have A3:= @Pi.is_open_topological_space β γ Dβ T S g A1A A2, cases A3 with S2 A3, cases A3 with f2 A3, have A4:∀ b∈ S2, ∃ S3:finset α, ∀S4⊇ S3, S4.sum (λ a:α, f a b) ∈ f2 b, { intros b A4A, have A4B := A1 b, unfold has_sum filter.tendsto filter.map at A4B, have A4C:f2 b ∈ nhds (g b), { apply mem_nhds_sets, { have D1 := A3.right.left, apply D1 b A4A, }, { have C1:= A3.left, unfold product_basis at C1, simp at C1, apply C1 b A4A, }, }, have A4D := filter_le_elim A4B A4C, simp at A4D, cases A4D with S3 A4D, apply exists.intro S3, intros S4 A4E, have A4F := A4D S4 A4E, apply A4F, }, let z:β → (finset α) := λ b:β, @dite (b∈ S2) _ (finset α) (λ H:b∈ S2, classical.some (A4 b H)) (λ H, ∅), let S3 := finset.Union (finset.image z S2), begin have A5:z= λ b:β, @dite (b∈ S2) _ (finset α) (λ H:b∈ S2, classical.some (A4 b H)) (λ H, ∅) := rfl, have A6:S3 = finset.Union (finset.image z S2) := rfl, apply exists.intro S3, intros S4 A7, have A8:S4.sum f ∈ product_basis S2 f2, { unfold product_basis, simp, intros b A8A, have A8X:z b ⊆ S3, { have A8BA:z b ∈ finset.image z S2, { apply (@finset.mem_image_of_mem β (finset α) _ z b S2 A8A), }, apply @finset.subset_Union α Dα (finset.image z S2) (z b) A8BA, }, have A8B:z b ⊆ S4, { apply finset.subset.trans, apply A8X, apply A7, }, have A9C:(λ (S3 : finset α), ∀ (S4 : finset α), S4 ⊇ S3 → finset.sum S4 (λ (a : α), f a b) ∈ f2 b) (classical.some (A4 b A8A)), { apply @classical.some_spec (finset α) (λ (S3 : finset α), ∀ (S4 : finset α), S4 ⊇ S3 → finset.sum S4 (λ (a : α), f a b) ∈ f2 b) , }, have A9D:z b = classical.some (A4 b A8A), { rw A5, simp, rw dif_pos A8A, }, rw ← A9D at A9C, have A9E := A9C S4 A8B, apply A9E, }, apply set.mem_of_mem_of_subset A8 A3.right.right, end end /- This is true, but for an odd reason. Note that the product topology has the finite product of bases as a basis. So, we can take the finite product of elements to get the neighborhood. For each of these elements in the finite product, there is some finite set such that it is within the limit. So, the union of N finite sets will give us a finite set. QED. -/ lemma has_sum_fn {α Ω γ:Type*} [Dα:decidable_eq α] [DΩ:decidable_eq Ω] [C:add_comm_monoid γ] [T:topological_space γ] {f:α → Ω → γ} {g:Ω → γ}: (∀ ω:Ω, has_sum (λ n, f n ω) (g ω)) → has_sum f g := begin intro A1, apply (@has_sum_product α Ω Dα DΩ _ (λ ω:Ω, C) (λ ω:Ω, T) f g A1), end lemma has_sum_fn_ennreal_2 {α β:Type*} [decidable_eq α] [decidable_eq β] (f:α → β → ennreal): has_sum f (λ b:β, ∑' a:α, f a b) := begin apply has_sum_fn, intro ω, rw summable.has_sum_iff, apply ennreal.summable, end lemma summable_fn_ennreal {α β:Type*} [decidable_eq α] [decidable_eq β] {f:α → β → ennreal}:summable f := begin have A1 := has_sum_fn_ennreal_2 f, apply has_sum.summable A1, end lemma tsum_fn {α Ω:Type*} [decidable_eq α] [decidable_eq Ω] {f:α → Ω → ennreal}: (∑' n, f n) = (λ ω, ∑' n, (f n ω)) := begin apply has_sum.tsum_eq, apply has_sum_fn_ennreal_2, end lemma set_indicator_le_sum {Ω:Type*} [decidable_eq Ω] (f:Ω → ennreal) (s: ℕ → set Ω): (set.indicator (⋃ (i : ℕ), s i) f) ≤ ∑' i:ℕ, set.indicator (s i) f := begin rw has_le_fun_def, intro ω, have A1:ω ∈ (⋃ (i : ℕ), s i) ∨ ω ∉ (⋃ (i : ℕ), s i), { apply classical.em, }, cases A1, { rw set.indicator_apply, rw if_pos, { cases A1 with S A1, cases A1 with A1 A2, simp at A1, cases A1 with y A1, subst S, have A3:f ω = set.indicator (s y) f ω, { rw set.indicator_apply, rw if_pos, apply A2, }, rw A3, have A4 := @ennreal.le_tsum _ (λ i, set.indicator (s i) f ω) y, simp at A4, rw tsum_fn, apply A4, }, { apply A1, }, }, { rw set.indicator_apply, rw if_neg, { simp, }, { apply A1, }, }, end lemma lintegral_tsum2 {α β:Type*} [M:measure_theory.measure_space α] [E:encodable β] [Dα:decidable_eq α] {f : β → α → ennreal} (hf : ∀i, measurable (f i)) : (measure_theory.lintegral M.volume ∑' i, f i ) = (∑' i, measure_theory.lintegral M.volume (f i)) := begin begin have A0:(∑' i, f i) = λ a:α, ∑' (i:β), f i a, { have A0A:decidable_eq β, { apply encodable.decidable_eq_of_encodable, }, apply @tsum_fn β α A0A, }, have A1:(∫⁻ (a : α), ∑' (i : β), f i a) = (measure_theory.lintegral M.volume ∑' i, f i ), { rw A0, }, rw ← A1, apply @measure_theory.lintegral_tsum α β (M.to_measurable_space) (M.volume) E f, apply hf, end end lemma integral_tsum {α β:Type*} [measurable_space α] {μ:measure_theory.measure α} [E:encodable β] {f : β → α → ennreal} (hf : ∀i, measurable (f i)) : (μ.integral ∑' i, f i ) = (∑' i, μ.integral (f i)) := begin let M:measure_theory.measure_space α := {volume := μ}, begin unfold measure_theory.measure.integral, have A1:decidable_eq α := classical.decidable_eq α, apply @lintegral_tsum2 α β M E A1 f, apply hf, end end lemma monotone_convergence_for_series {Ω:Type*} {M:measurable_space Ω} (μ:measure_theory.measure Ω) (f:ℕ → Ω → ennreal):(∀ n, measurable (f n)) → μ.integral (∑' n:ℕ, f n) = ∑' n:ℕ, μ.integral (f n) := begin intro A1, apply integral_tsum, apply A1, end lemma set.indicator_tsum {Ω:Type*} (f:Ω → ennreal) (g:ℕ → set Ω): pairwise (disjoint on g) → set.indicator (⋃ (i : ℕ), g i) f = ∑' (i : ℕ), set.indicator (g i) f := begin intro A1, apply funext, intro ω, have A2:decidable_eq Ω := classical.decidable_eq Ω, rw @tsum_fn ℕ Ω nat.decidable_eq A2 (λ i:ℕ, set.indicator (g i) f), simp, have A3:ω ∈ (set.Union g) ∨ (ω ∉ (set.Union g)) := classical.em (ω ∈ (set.Union g) ), cases A3, { rw set.indicator_of_mem A3, simp at A3, cases A3 with i A3, rw tsum_eq_single i, rw set.indicator_of_mem A3, intros b' A4, rw set.indicator_of_not_mem, have A5:disjoint (g b') (g i), { apply A1, apply A4, }, rw set.disjoint_right at A5, apply A5, apply A3, apply ennreal.t2_space, }, { rw set.indicator_of_not_mem A3, have A6:(λ i:ℕ, set.indicator (g i) f ω)=0, { apply funext, intro i, simp at A3, rw set.indicator_of_not_mem (A3 i), simp, }, rw A6, symmetry, apply has_sum.tsum_eq, apply has_sum_zero, }, end lemma set_indicator_def {Ω:Type*} {S:set Ω} {f:Ω → ennreal}: (λ (a : Ω), ⨆ (h : a ∈ S), f a) = set.indicator S f := begin apply funext, intro ω, cases (classical.em (ω ∈ S)) with A1 A1, { simp [A1], }, { simp [A1], }, end lemma measure.apply {Ω:Type*} {M:measurable_space Ω} (μ:measure_theory.measure Ω) (S:set Ω): μ S = μ.to_outer_measure.measure_of S := begin refl end lemma measure_theory.lintegral_supr2 {α : Type*} [M : measure_theory.measure_space α] {f : ℕ → α → ennreal}: (∀ (n : ℕ), measurable (f n)) → monotone f → ((measure_theory.lintegral (M.volume) (⨆ (n : ℕ), f n)) = ⨆ (n : ℕ), measure_theory.lintegral (M.volume) (f n)) := begin intros A1 A2, have A3:(λ a, (⨆ (n : ℕ), f n a)) = (⨆ (n : ℕ), f n), { apply funext, intro a, rw supr_apply, }, rw ← A3, apply measure_theory.lintegral_supr, apply A1, apply A2, end lemma measure_theory.integral_supr {Ω : Type*} {M:measurable_space Ω} {μ:measure_theory.measure Ω} {f : ℕ → Ω → ennreal}: (∀ (n : ℕ), measurable (f n)) → monotone f → ((μ.integral (⨆ (n : ℕ), f n)) = ⨆ (n : ℕ), μ.integral (f n)) := begin intros A1 A2, unfold measure_theory.measure.integral, rw @measure_theory.lintegral_supr2 Ω {volume := μ} f, apply A1, apply A2, end lemma supr_indicator {Ω:Type*} (g:ℕ → Ω → ennreal) (S:set Ω): (set.indicator S (supr g)) = (⨆ (n : ℕ), (set.indicator S (g n))) := begin apply funext, intro ω, rw (@supr_apply Ω (λ ω:Ω, ennreal) ℕ _ (λ n:ℕ, set.indicator S (g n)) ), have A0:(λ (i : ℕ), (λ (n : ℕ), set.indicator S (g n)) i ω) = (λ (i : ℕ), set.indicator S (g i) ω), { apply funext, intro i, simp, }, rw A0, have A1:ω ∈ S ∨ ω ∉ S , { apply classical.em, }, cases A1, { rw set.indicator_of_mem A1, have B1A:(λ (i : ℕ), set.indicator S (g i) ω) = (λ (i : ℕ), g i ω), { apply funext, intro i, rw set.indicator_of_mem A1, }, rw B1A, rw supr_apply, }, { rw set.indicator_of_not_mem A1, have B1A:(λ (i : ℕ), set.indicator S (g i) ω) = (λ (i:ℕ), 0), { apply funext, intro i, rw set.indicator_of_not_mem A1, }, rw B1A, rw @supr_const ennreal ℕ _ _ 0, }, end lemma supr_eapprox {α:Type*} {M:measurable_space α} (f : α → ennreal) (hf : measurable f): (⨆ n:ℕ, (measure_theory.simple_func.eapprox f n).to_fun) = f := begin apply funext, intro a, rw supr_apply, rw ← @measure_theory.simple_func.supr_eapprox_apply α M f hf a, refl, end lemma supr_eapprox' {α:Type*} {M:measurable_space α} (f : α → ennreal) (hf : measurable f): (⨆ (n : ℕ), (⇑(measure_theory.simple_func.eapprox f n)): (α → ennreal))=(f:α → ennreal) := begin have A1:(λ (n : ℕ), (⇑(measure_theory.simple_func.eapprox f n)))= (λ (n : ℕ), ((measure_theory.simple_func.eapprox f n).to_fun)), { apply funext, intro n, rw simple_func_to_fun, }, rw A1, rw supr_eapprox, apply hf, end lemma set_indicator_monotone {Ω:Type*} {g:ℕ → Ω → ennreal} {S:set Ω}: monotone g → monotone (λ n:ℕ, set.indicator S (g n)) := begin intro A1, intros n1 n2 A2, simp, rw has_le_fun_def, intro ω, have A3:ω ∈ S ∨ ω ∉ S := classical.em (ω ∈ S), cases A3, { repeat {rw @set.indicator_of_mem Ω _ _ S ω A3}, apply A1, apply A2, }, { repeat {rw @set.indicator_of_not_mem Ω _ _ S ω A3}, apply le_refl (0:ennreal), }, end lemma integral_simple_func_def {Ω:Type*} {M:measurable_space Ω} (μ:measure_theory.measure Ω) (g:measure_theory.simple_func Ω ennreal): μ.integral g = @measure_theory.simple_func.lintegral _ M g μ := begin unfold measure_theory.measure.integral, rw measure_theory.simple_func.lintegral_eq_lintegral, end lemma measure_of_measure_space {Ω:Type*} {M:measurable_space Ω} (μ:measure_theory.measure Ω):({volume := μ}:measure_theory.measure_space Ω).volume = μ := rfl def finset.filter_nonzero {α: Type*} [decidable_eq α] [has_zero α] (S:finset α):finset α := S.filter (λ a:α, a ≠ 0) def finset.mem_filter_nonzero {α: Type*} [decidable_eq α] [has_zero α] (S:finset α) (x:α): (x ∈ S.filter_nonzero) ↔ (x∈ S) ∧ (x ≠ 0) := begin unfold finset.filter_nonzero, rw finset.mem_filter, end lemma finset.sum_eq_sum_of_filter_nonzero {α : Type*} {β : Type*} [canonically_ordered_add_monoid β] {s₁ s₂: finset α} {f : α → β}: (∀ (x : α), (x ∈ s₁ ∧ f x ≠ 0) → x ∈ s₂) → s₂ ⊆ s₁ → finset.sum s₁ f = finset.sum s₂ f := begin intros A1 A2, apply le_antisymm, { apply finset.sum_le_sum_of_ne_zero, intros x B1 B2, apply A1, apply and.intro B1 B2, }, { apply finset.sum_le_sum_of_subset, apply A2, }, end lemma integral_simple_func_def2 {Ω:Type*} {M:measurable_space Ω} (μ:measure_theory.measure Ω) (g:measure_theory.simple_func Ω ennreal): μ.integral g = finset.sum (measure_theory.simple_func.range g) (λ x:ennreal, x * μ.to_outer_measure.measure_of (g.to_fun ⁻¹' {x})) := begin rw integral_simple_func_def, unfold measure_theory.simple_func.lintegral, have A2:(λ (x : ennreal), x * (μ (⇑g ⁻¹' {x})))= (λ x:ennreal, x * μ.to_outer_measure.measure_of (g.to_fun ⁻¹' {x})), { apply funext, intro x, rw measure.apply, rw simple_func_to_fun, }, rw A2, end lemma integral_simple_func_def3 {Ω:Type*} {M:measurable_space Ω} (μ:measure_theory.measure Ω) (g:measure_theory.simple_func Ω ennreal): μ.integral g = finset.sum (measure_theory.simple_func.range g).filter_nonzero (λ x:ennreal, x * μ.to_outer_measure.measure_of (g.to_fun ⁻¹' {x})) := begin rw ← @finset.sum_eq_sum_of_filter_nonzero ennreal ennreal _ (measure_theory.simple_func.range g), rw integral_simple_func_def2, { intros x A1, rw finset.mem_filter_nonzero, split, apply A1.left, intro contra, apply A1.right, rw contra, simp, }, { unfold finset.filter_nonzero, apply finset.filter_subset, }, end lemma filter_nonzero_congr {S:finset ennreal} {f g:ennreal → ennreal}: (∀ x ≠ 0, f x = g x) → (S.filter_nonzero.sum f = S.filter_nonzero.sum g) := begin intro A1, rw finset.sum_congr, refl, intros x A2, apply A1, rw finset.mem_filter_nonzero at A2, apply A2.right, end lemma set_indicator_inter {Ω:Type*} (f:Ω → ennreal) {g:Ω → ennreal} {x y:ennreal}: (y ≠ 0) → (set.indicator (g ⁻¹' {x}) (f))⁻¹' {y} = (g⁻¹' {x}) ∩ (f⁻¹' {y}) := begin intro A1, ext ω, split;intros B1;simp at B1;simp, { have C1:g ω = x ∨ g ω ≠ x := eq_or_ne, cases C1, { rw set.indicator_of_mem at B1, apply and.intro C1 B1, simp [C1], }, { exfalso, apply A1, rw set.indicator_of_not_mem at B1, symmetry, apply B1, simp [C1], }, }, { rw set.indicator_of_mem, apply B1.right, simp [B1.left], }, end lemma set_indicator_inter2 {Ω:Type*} {M:measurable_space Ω} (f:measure_theory.simple_func Ω ennreal) {g:measure_theory.simple_func Ω ennreal} {x y:ennreal}: (y ≠ 0) → (set.indicator (⇑g ⁻¹' {x}) (⇑f))⁻¹' {y} = (g⁻¹' {x}) ∩ (f⁻¹' {y}) := begin apply set_indicator_inter, end noncomputable def measure_theory.simple_func.piece {Ω:Type*} [measurable_space Ω] (g:measure_theory.simple_func Ω ennreal) (x:ennreal): measure_theory.simple_func Ω ennreal := (measure_theory.simple_func.const Ω x).restrict (g.to_fun ⁻¹' {x}) lemma measure_theory.simple_func.piece_def {Ω:Type*} [measurable_space Ω] (g:measure_theory.simple_func Ω ennreal) (x:ennreal): g.piece x = (measure_theory.simple_func.const Ω x).restrict (g.to_fun ⁻¹' {x}) := rfl lemma measure_theory.simple_func.piece_apply_of_eq {Ω:Type*} [measurable_space Ω] (g:measure_theory.simple_func Ω ennreal) (x:ennreal) (ω:Ω): (g ω = x) → g.piece x ω = x := begin intro A1, rw measure_theory.simple_func.piece_def, rw measure_theory.simple_func.restrict_apply, rw if_pos, rw measure_theory.simple_func.const_apply, { rw simple_func_to_fun at A1, simp [A1], }, apply g.is_measurable_fiber', end lemma measure_theory.simple_func.piece_apply_of_ne {Ω:Type*} [measurable_space Ω] (g:measure_theory.simple_func Ω ennreal) (x:ennreal) (ω:Ω): (g ω ≠ x) → g.piece x ω = 0 := begin intro A1, rw measure_theory.simple_func.piece_def, rw measure_theory.simple_func.restrict_apply, rw if_neg, simp, rw simple_func_to_fun at A1, apply A1, apply g.is_measurable_fiber', end noncomputable def simple_func_to_fun_add_monoid_hom (Ω:Type*) [measurable_space Ω]: add_monoid_hom (measure_theory.simple_func Ω ennreal) (Ω → ennreal) := { to_fun := measure_theory.simple_func.to_fun, map_add' := begin intros x y, refl, end, map_zero' := rfl, } lemma simple_func_to_fun_add_monoid_hom_to_fun_def' {Ω:Type*} [M:measurable_space Ω] {g:measure_theory.simple_func Ω ennreal}: (simple_func_to_fun_add_monoid_hom Ω) g = g.to_fun := rfl lemma measure_theory.simple_func.finset_sum_to_fun {β:Type*} {Ω:Type*} [measurable_space Ω] (g:β → (measure_theory.simple_func Ω ennreal)) (S:finset β): ⇑(S.sum g) = (S.sum (λ b:β, (g b).to_fun)) := begin have A1:(λ b:β, (g b).to_fun) = ((λ b:β, (simple_func_to_fun_add_monoid_hom Ω) (g b))), { apply funext, intro b, rw simple_func_to_fun_add_monoid_hom_to_fun_def', }, rw A1, clear A1, rw simple_func_to_fun, rw ← simple_func_to_fun_add_monoid_hom_to_fun_def', rw add_monoid_hom.map_sum, end def apply_add_monoid_hom {α:Type*} (β:Type*) [add_monoid β] (a:α): add_monoid_hom (α → β) β := { to_fun := (λ f:α → β, f a), map_add' := begin intros x y, refl, end, map_zero' := rfl, } lemma apply_add_monoid_hom_to_fun_def' {α β:Type*} [add_monoid β] {f:α → β} {a:α}: (apply_add_monoid_hom β a) f = f a := rfl noncomputable def simple_func_apply_add_monoid_hom {Ω:Type*} [measurable_space Ω] (ω:Ω): add_monoid_hom (measure_theory.simple_func Ω ennreal) (ennreal) := { to_fun := (λ (g:measure_theory.simple_func Ω ennreal), g ω), map_add' := begin intros x y, refl, end, map_zero' := rfl, } lemma simple_func_apply_add_monoid_hom_apply_def {Ω:Type*} [M:measurable_space Ω] {g:measure_theory.simple_func Ω ennreal} {ω:Ω}: (@simple_func_apply_add_monoid_hom Ω M ω) g = g ω := rfl lemma measure_theory.simple_func.finset_sum_apply {β:Type*} {Ω:Type*} [measurable_space Ω] (g:β → (measure_theory.simple_func Ω ennreal)) (S:finset β) (ω:Ω): (S.sum g) ω = (S.sum (λ b:β, (g b ω))) := begin rw ← simple_func_apply_add_monoid_hom_apply_def, have A1:(λ (b : β), (⇑(simple_func_apply_add_monoid_hom ω):((measure_theory.simple_func Ω ennreal) → ennreal)) (g b)) = (λ (b : β), g b ω), { apply funext, intro b, rw ← simple_func_apply_add_monoid_hom_apply_def, }, rw ← A1, rw add_monoid_hom.map_sum, end lemma measure_theory.simple_func.sum_piece {Ω:Type*} [measurable_space Ω] (g:measure_theory.simple_func Ω ennreal): g = g.range.sum (λ x:ennreal, g.piece x) := begin apply measure_theory.simple_func.ext, intro ω, rw @measure_theory.simple_func.finset_sum_apply, rw finset.sum_eq_single (g ω), { rw measure_theory.simple_func.piece_apply_of_eq, refl, }, { intros ω2 A1 A2, rw measure_theory.simple_func.piece_apply_of_ne, symmetry, apply A2, }, { intro A1, exfalso, apply A1, rw measure_theory.simple_func.mem_range, apply exists.intro ω, refl, }, end lemma measure_theory.simple_func.const_preimage {Ω:Type*} [measurable_space Ω] (x:ennreal): (measure_theory.simple_func.const Ω x) ⁻¹' {x} = set.univ := begin ext, split;intro B1;simp, end lemma measure_theory.simple_func.const_preimage_of_ne {Ω:Type*} [measurable_space Ω] (x y:ennreal):x ≠ y → (measure_theory.simple_func.const Ω x) ⁻¹' {y} = ∅ := begin intro A1, ext, split;intro B1;simp;simp at B1, { apply A1, apply B1, }, { exfalso, apply B1, }, end lemma emptyset_of_not_nonempty {Ω:Type*} (S:set Ω):(¬(nonempty Ω)) → S = ∅ := begin intro A1, ext ω,split;intros A2;exfalso, { apply A1, apply nonempty.intro ω, }, { apply A2, }, end lemma integral_const_restrict_def {Ω:Type*} {M:measurable_space Ω} (μ:measure_theory.measure Ω) (S:set Ω) (x:ennreal):(is_measurable S) → μ.integral ((measure_theory.simple_func.const Ω x).restrict S) = x * (μ.to_outer_measure.measure_of S) := begin intro A1, rw integral_simple_func_def, rw measure_theory.simple_func.restrict_const_lintegral, rw measure.apply, apply A1, end lemma mul_restrict_def {Ω:Type*} {M:measurable_space Ω} (f:Ω → ennreal) (S:set Ω) (x:ennreal):(is_measurable S) → ((f * ⇑((measure_theory.simple_func.const Ω x).restrict S))) = (λ ω:Ω, (x * (set.indicator S f ω))) := begin intro A1, apply funext, intro ω, simp, rw measure_theory.simple_func.restrict_apply, rw measure_theory.simple_func.const_apply, simp, rw mul_comm, apply A1, end lemma measure_theory.integral_mul_const {Ω:Type*} {M:measurable_space Ω} (μ:measure_theory.measure Ω) (f:Ω → ennreal) (H:measurable f) (x:ennreal): x * μ.integral f = μ.integral (λ ω:Ω, x * (f ω)) := begin unfold measure_theory.measure.integral, rw measure_theory.lintegral_const_mul, simp [H], end lemma function_support_le_subset {Ω:Type*} {f g:Ω → ennreal}: f ≤ g → (function.support f) ⊆ (function.support g) := begin intro A1, rw set.subset_def, intros x B1, unfold function.support, unfold function.support at B1, simp at B1, simp, intro B2, apply B1, have B3 := A1 x, rw B2 at B3, have C1:⊥ = (0:ennreal) := rfl, rw ← C1 at B3, rw ← C1, rw ← le_bot_iff, apply B3, end lemma function_support_indicator_subset {Ω:Type*} {f:Ω → ennreal} {S:set Ω}: (function.support (S.indicator f)) ⊆ S := begin rw set.subset_def, intros x A1, unfold function.support at A1, simp at A1, unfold set.indicator at A1, cases (classical.em (x ∈ S)) with B1 B1, { apply B1, }, { exfalso, apply A1, apply if_neg, apply B1, }, end lemma indicator_le {Ω:Type*} {f:Ω → ennreal} {S:set Ω}: (S.indicator f) ≤ f := begin intro x, cases (classical.em (x ∈ S)) with A1 A1, { rw set.indicator_of_mem A1, apply le_refl _, }, { rw set.indicator_of_not_mem A1, have B1:(0:ennreal) = ⊥ := rfl, rw B1, apply @bot_le ennreal _, }, end lemma simple_func_restrict_of_is_measurable {Ω:Type*} {M:measurable_space Ω} (μ:measure_theory.measure Ω) (g:measure_theory.simple_func Ω ennreal) (S:set Ω) (H:is_measurable S): (g.restrict S)=measure_theory.simple_func.piecewise S H g 0 := begin unfold measure_theory.simple_func.restrict, rw dif_pos, end lemma simple_func_piecewise_range_subset {Ω:Type*} {M:measurable_space Ω} (f g:measure_theory.simple_func Ω ennreal) (S:set Ω) (H:is_measurable S): (measure_theory.simple_func.piecewise S H f g).range ⊆ (f.range ∪ g.range) := begin rw finset.subset_iff, intros x B1, rw measure_theory.simple_func.mem_range at B1, rw finset.mem_union, rw measure_theory.simple_func.mem_range, rw measure_theory.simple_func.mem_range, rw measure_theory.simple_func.coe_piecewise at B1, rw set.mem_range at B1, cases B1 with ω B1, cases (classical.em (ω ∈ S)) with B2 B2, { left, rw set.piecewise_eq_of_mem at B1, rw set.mem_range, apply exists.intro ω B1, apply B2, }, { right, rw set.piecewise_eq_of_not_mem at B1, rw set.mem_range, apply exists.intro ω B1, apply B2, }, end lemma measure_theory.simple_func.lintegral_eq_of_range_subset {Ω:Type*} {M:measurable_space Ω} {f:measure_theory.simple_func Ω ennreal} {μ:measure_theory.measure Ω} {S:finset ennreal}: f.range ⊆ S → f.lintegral μ = S.sum (λ x:ennreal, x * μ (f ⁻¹' {x})) := begin intros A1, apply @measure_theory.simple_func.lintegral_eq_of_subset Ω M, intros x B1 B2, rw finset.subset_iff at A1, apply A1, apply @measure_theory.simple_func.mem_range_of_measure_ne_zero Ω ennreal M f _ μ, apply B2, end lemma simple_func_piecewise_preimage {Ω:Type*} {M:measurable_space Ω} (f g:measure_theory.simple_func Ω ennreal) (S:set Ω) (H:is_measurable S) (T:set ennreal): (measure_theory.simple_func.piecewise S H f g) ⁻¹' T = (S ∩ (f ⁻¹' T)) ∪ ((Sᶜ) ∩ (g ⁻¹' T)) := begin rw measure_theory.simple_func.coe_piecewise, rw set.piecewise_preimage, end lemma simple_func_piecewise_integral {Ω:Type*} {M:measurable_space Ω} (μ:measure_theory.measure Ω) (f g:measure_theory.simple_func Ω ennreal) (S:set Ω) (H:is_measurable S): (measure_theory.simple_func.piecewise S H f g).lintegral μ = f.lintegral (μ.restrict S) + g.lintegral (μ.restrict Sᶜ) := begin let Z := (f.range ∪ g.range), begin have B1:Z = (f.range ∪ g.range) := rfl, have C1:f.range ⊆ Z, { rw B1, apply finset.subset_union_left, }, have C2:g.range ⊆ Z, { rw B1, apply finset.subset_union_right, }, have C3:(measure_theory.simple_func.piecewise S H f g).range ⊆ Z, { rw B1, apply simple_func_piecewise_range_subset, }, rw measure_theory.simple_func.lintegral_eq_of_range_subset C1, rw measure_theory.simple_func.lintegral_eq_of_range_subset C2, rw measure_theory.simple_func.lintegral_eq_of_range_subset C3, rw ← finset.sum_add_distrib, have D1:(λ (x : ennreal), x * μ (⇑(measure_theory.simple_func.piecewise S H f g) ⁻¹' {x})) = (λ (x : ennreal), x * (μ.restrict S) (⇑f ⁻¹' {x}) + x * (μ.restrict Sᶜ) (⇑g ⁻¹' {x})), { apply funext, intros x, rw simple_func_piecewise_preimage, have D1A:μ (⇑f ⁻¹' {x} ∩ S ∪ ⇑g ⁻¹' {x} ∩ Sᶜ) = μ (⇑f ⁻¹' {x} ∩ S) + μ (⇑g ⁻¹' {x} ∩ Sᶜ), { apply measure_theory.measure_union, apply set.disjoint_inter_compl, apply is_measurable.inter, apply f.is_measurable_fiber', apply H, apply is_measurable.inter, apply g.is_measurable_fiber', apply is_measurable.compl, apply H, }, rw set.inter_comm, rw set.inter_comm Sᶜ, rw D1A, rw measure_theory.measure.restrict_apply, rw measure_theory.measure.restrict_apply, rw left_distrib, apply g.is_measurable_fiber', apply f.is_measurable_fiber', }, rw D1, end end lemma simple_func_integral_restrict {Ω:Type*} {M:measurable_space Ω} (μ:measure_theory.measure Ω) (g:measure_theory.simple_func Ω ennreal) (S:set Ω): (is_measurable S) → (g.restrict S).lintegral μ = g.lintegral (μ.restrict S) := begin intro A1, rw simple_func_restrict_of_is_measurable μ g S A1, rw simple_func_piecewise_integral, rw measure_theory.simple_func.zero_lintegral, rw add_zero, end lemma simple_func_integral_restrict' {Ω:Type*} {M:measurable_space Ω} (μ:measure_theory.measure Ω) (g:measure_theory.simple_func Ω ennreal) (S:set Ω): (is_measurable S) → (function.support g⊆ S) → g.lintegral μ = g.lintegral (μ.restrict S) := begin intros A1 A2, rw ← simple_func_integral_restrict, have B1:g.restrict S = g, { apply measure_theory.simple_func.ext, intro ω, rw measure_theory.simple_func.restrict_apply, cases (classical.em (ω ∈ S)) with B1A B1A, { rw if_pos, apply B1A, }, { rw if_neg, unfold function.support at A2, rw set.subset_def at A2, have B1B := A2 ω, apply classical.by_contradiction, intro B1C, apply B1A, apply B1B, simp, intro B1D, apply B1C, rw B1D, apply B1A, }, apply A1, }, rw B1, apply A1, end --This just lifts measure_theory.lintegral_indicator. lemma integral_set_indicator {Ω:Type*} {M:measurable_space Ω} (μ:measure_theory.measure Ω) (f:Ω → ennreal) (S:set Ω):(is_measurable S) → (μ.integral (set.indicator S f)) = (μ.restrict S).integral f := begin intro A1, unfold measure_theory.measure.integral, rw measure_theory.lintegral_indicator, apply A1, end lemma measure_theory.with_density_apply2 {Ω:Type*} {M:measurable_space Ω} (μ:measure_theory.measure Ω) (f:Ω → ennreal) (S:set Ω):(is_measurable S) → (μ.with_density f) S = (μ.integral (set.indicator S f)) := begin intro A1, rw measure_theory.with_density_apply f A1, rw integral_set_indicator, unfold measure_theory.measure.integral, --apply H, apply A1, end lemma measure_theory.with_density_apply3 {Ω:Type*} {M:measurable_space Ω} (μ:measure_theory.measure Ω) (f:Ω → ennreal) (S:set Ω):(is_measurable S) → (μ.with_density f).to_outer_measure.measure_of S = (μ.integral (set.indicator S f)) := begin intro A1, rw ← measure_theory.with_density_apply2, refl, --apply H, apply A1, end lemma integral_measure.apply3 {Ω:Type*} {M:measurable_space Ω} (μ:measure_theory.measure Ω) (f:Ω → ennreal) (H:measurable f) (S:set Ω):(is_measurable S) → (μ.with_density f).to_outer_measure.measure_of S = supr (λ n, (μ.integral (set.indicator S (measure_theory.simple_func.eapprox f n)))) := begin intro A1, rw measure_theory.with_density_apply3, rw ← @measure_theory.integral_supr Ω M μ, rw ← supr_indicator, have C1:(λ (n : ℕ), ⇑(measure_theory.simple_func.eapprox f n))= (λ (n : ℕ), (measure_theory.simple_func.eapprox f n).to_fun), { ext, rw simple_func_to_fun, }, rw C1, clear C1, rw supr_eapprox, apply H, { intro n, apply measurable_set_indicator, apply A1, apply measure_theory.simple_func.measurable, }, { apply set_indicator_monotone, apply measure_theory.simple_func.monotone_eapprox, }, --apply H, apply A1, end lemma integral_measure_restrict_def {Ω:Type*} {M:measurable_space Ω} (μ:measure_theory.measure Ω) (f:Ω → ennreal) (H:measurable f) (S:set Ω) (x:ennreal): is_measurable S → (μ.with_density f).integral ((measure_theory.simple_func.const Ω x).restrict S) = μ.integral (f * ⇑((measure_theory.simple_func.const Ω x).restrict S)) := begin intro A1, rw integral_const_restrict_def, rw measure_theory.with_density_apply3, rw mul_restrict_def, rw measure_theory.integral_mul_const, apply measurable_set_indicator, apply A1, apply H, apply A1, repeat {apply A1}, end lemma integral_measure_piece_def {Ω:Type*} {M:measurable_space Ω} (μ:measure_theory.measure Ω) (f:Ω → ennreal) (H:measurable f) {g:measure_theory.simple_func Ω ennreal} (x:ennreal): (μ.with_density f).integral (g.piece x) = μ.integral (f * ⇑(g.piece x)) := begin rw measure_theory.simple_func.piece_def, rw integral_measure_restrict_def, apply H, apply g.is_measurable_fiber', end lemma integral_zero {Ω:Type*} {M:measurable_space Ω} (μ:measure_theory.measure Ω): μ.integral 0 = 0 := begin have A1:μ.integral (0:Ω → ennreal) = μ.integral (λ ω:Ω, 0), { have A1A:(λ ω:Ω, (0:ennreal)) = 0 := rfl, rw ← A1A, }, rw A1, unfold measure_theory.measure.integral, rw measure_theory.lintegral_zero, end lemma with_density.zero {Ω:Type*} {M:measurable_space Ω} (μ:measure_theory.measure Ω): (μ.with_density 0) = 0 := begin apply measure_theory.measure.ext, intros S A1, rw measure_theory.with_density_apply2, { simp, rw integral_zero, }, { apply A1, } end lemma measure_theory.measure.integral_def {Ω:Type*} [M:measurable_space Ω] (μ:measure_theory.measure Ω) {x:Ω → ennreal}: μ.integral x = ∫⁻ (a : Ω), x a ∂μ := rfl lemma measure_theory.measure.integral_add {Ω:Type*} [M:measurable_space Ω] (μ:measure_theory.measure Ω) {x y:Ω → ennreal}:measurable x → measurable y → μ.integral (x + y) = μ.integral x + μ.integral y := begin intros A1 A2, repeat {rw measure_theory.measure.integral_def}, simp, rw @measure_theory.lintegral_add Ω M μ x y, apply A1, apply A2, end lemma finset.sum_measurable {β:Type*} {Ω:Type*} {M:measurable_space Ω} (f:β → Ω → ennreal) (S:finset β):(∀ b∈ S, measurable (f b)) → measurable (S.sum f) := begin have A1:decidable_eq β := classical.decidable_eq β, apply @finset.induction_on β _ A1 S, { intro A2, rw finset.sum_empty, have A3:(λ ω:Ω, (0:ennreal)) = (0:Ω → ennreal) := rfl, rw ← A3, apply measurable_const, }, { intros b S2 B1 B2 B3, rw finset.sum_insert, apply measurable.ennreal_add, apply B3, simp, apply B2, intros b2 B4, apply B3, simp, right, apply B4, apply B1, }, end -- Because we need an additional constraint, this cannot be handled with -- add_monoid_hom. lemma finset.sum_integral {β:Type*} {Ω:Type*} {M:measurable_space Ω} (μ:measure_theory.measure Ω) (f:β → Ω → ennreal) (S:finset β): (∀ b∈S, measurable (f b)) → S.sum (λ b, (μ.integral (f b))) = (μ.integral (S.sum f)) := begin have A1:decidable_eq β := classical.decidable_eq β, apply @finset.induction_on β _ A1 S, { rw finset.sum_empty, rw finset.sum_empty, rw integral_zero, intro A1, refl, }, { intros b S2 A2 A3 A4, rw finset.sum_insert, rw A3, rw finset.sum_insert, rw measure_theory.measure.integral_add, { apply A4, simp, }, { apply finset.sum_measurable, intros b2 A5, apply A4, simp [A5], }, { apply A2, }, { intros b A5, apply A4, simp [A5], }, { apply A2, }, }, end lemma finset.sum_integral_simple_func {β:Type*} {Ω:Type*} {M:measurable_space Ω} (μ:measure_theory.measure Ω) (f:β → (measure_theory.simple_func Ω ennreal)) (S:finset β): S.sum (λ b, (μ.integral (f b))) = (μ.integral (⇑(S.sum f))) := begin rw measure_theory.simple_func.finset_sum_to_fun, rw finset.sum_integral, have A1:(λ (b : β), ⇑(f b)) = (λ (b : β), (f b).to_fun), { apply funext, intro b, rw simple_func_to_fun, }, rw A1, intros b A2, apply measure_theory.simple_func.measurable, end lemma finset.sum_distrib {α:Type*} {β:Type*} [comm_semiring β] {f:β} {g:α → β} {S:finset α}:S.sum (λ a:α, f * (g a))=f * (S.sum g) := begin have A1:(λ a:α, f * (g a)) = (λ a:α, (add_monoid_hom.mul_left f).to_fun (g a)), { unfold add_monoid_hom.mul_left, }, rw A1, have A2:f * (S.sum g) = (add_monoid_hom.mul_left f).to_fun (S.sum g), { unfold add_monoid_hom.mul_left, }, rw A2, symmetry, apply @add_monoid_hom.map_sum α β β _ _ (add_monoid_hom.mul_left f) g S, end lemma simple_func.compose_eq_multiply {Ω:Type*} {M:measurable_space Ω} (μ:measure_theory.measure Ω) (f:Ω → ennreal) (H:measurable f) {g:measure_theory.simple_func Ω ennreal}: (μ.with_density f).integral g = μ.integral (f * ⇑g) := begin have A1:∀ g2 g3:measure_theory.simple_func Ω ennreal, g2 = g3 → (μ.with_density f).integral g2 = (μ.with_density f).integral g3, { intros g2 g3 A1A, rw A1A, }, rw A1 g (finset.sum (measure_theory.simple_func.range g) (λ (x : ennreal), measure_theory.simple_func.piece g x)) (measure_theory.simple_func.sum_piece g), rw ← finset.sum_integral_simple_func, have A1A:(λ (b : ennreal), measure_theory.measure.integral (μ.with_density f) ⇑(measure_theory.simple_func.piece g b))=λ b, μ.integral (f * ⇑(measure_theory.simple_func.piece g b)), { apply funext, intro x, rw integral_measure_piece_def, apply H, }, rw A1A, clear A1A, rw finset.sum_integral, rw @finset.sum_distrib ennreal (Ω → ennreal), have A3: (@finset.sum ennreal (Ω → ennreal) _ g.range (λ (a : ennreal), (⇑(measure_theory.simple_func.piece g a):Ω → ennreal))) = (⇑g:Ω → ennreal), { have A3A:(λ (a:ennreal), ⇑(measure_theory.simple_func.piece g a)) = (λ (a:ennreal), (measure_theory.simple_func.piece g a).to_fun), { apply funext, intro x, rw simple_func_to_fun, }, rw A3A, rw ← @measure_theory.simple_func.finset_sum_to_fun ennreal Ω M g.piece g.range, symmetry, have A3B:∀ g2 g3:measure_theory.simple_func Ω ennreal, g2 = g3 → (g2:Ω → ennreal) = (g3:Ω → ennreal), { intros g2 g3 A1, rw A1, }, rw A3B, apply @measure_theory.simple_func.sum_piece Ω M g, }, rw A3, intros b B1, apply measurable.ennreal_mul, apply H, apply (g.piece b).measurable, end lemma integral_le {Ω:Type*} {M:measurable_space Ω} (μ:measure_theory.measure Ω) (f:Ω → ennreal) (H:measurable f) (x:ennreal):(∀ g:measure_theory.simple_func Ω ennreal, (⇑g ≤ f) → μ.integral g ≤ x) → (μ.integral f ≤ x) := begin intros A1, unfold measure_theory.measure.integral, unfold measure_theory.lintegral, unfold supr, apply @Sup_le ennreal _, intros b A2, simp at A2, cases A2 with g A2, subst b, simp, intros b A3 A4, subst b, rw ← integral_simple_func_def, apply A1 g A3, end lemma integral.monotone {Ω:Type*} {M:measurable_space Ω} (μ:measure_theory.measure Ω) (f g:Ω → ennreal): (f ≤ g) → (μ.integral f ≤ μ.integral g) := begin intros A3, apply measure_theory.lintegral_mono, apply A3, end --This seems like a specific example of integrals being monotone. lemma le_integral {Ω:Type*} {M:measurable_space Ω} (μ:measure_theory.measure Ω) (f:Ω → ennreal) (g:measure_theory.simple_func Ω ennreal): (⇑g ≤ f) → (μ.integral g ≤ μ.integral f) := begin intros A1, apply integral.monotone, apply A1, end lemma integral_eq_Sup {Ω:Type*} {M:measurable_space Ω} (μ:measure_theory.measure Ω) (f:Ω → ennreal): (measurable f) → μ.integral f = Sup ((λ g:measure_theory.simple_func Ω ennreal, μ.integral g) '' {g:measure_theory.simple_func Ω ennreal|(⇑g ≤ f)}) := begin intro A1, apply le_antisymm, { apply integral_le, apply A1, intros g A2, apply @le_Sup_image (measure_theory.simple_func Ω ennreal) ennreal _, simp, apply A2, }, { apply @Sup_image_le (measure_theory.simple_func Ω ennreal) ennreal _, intros g A2, apply le_integral, simp at A2, apply A2, }, end -- In general, given two monotone functions, the supremum of the product -- equals the product of the supremum. Here, we prove a part of that, -- when one function has a supremum of infinity. lemma supr_mul_top {α:Type*} [linear_order α] {f g:α → ennreal}: monotone f → monotone g → supr f = ⊤ → supr g ≠ 0 → supr (f * g) = ⊤ := begin intros A1 A2 A3 A4, rw supr_eq_top, intros b A5, have C0F1:(0:ennreal) = ⊥ := rfl, rw supr_eq_top at A3, have C0:(∃ a:α, g a = ⊤) ∨ ¬ (∃ a:α, g a = ⊤) := classical.em _, cases C0, { cases C0 with j C0, have C0B := (@ennreal.coe_lt_top 1), have C0C := A3 1 C0B, cases C0C with i C0C, have C0D :(i ≤ j) ∨ (j ≤ i) := le_total i j, cases C0D, { apply exists.intro j, have C0E:(f * g) j = f j * g j := rfl, rw C0E, have C0F:(f j) * (g j)=⊤, { rw C0, rw with_top.mul_top, rw C0F1, rw ← bot_lt_iff_ne_bot, rw ← C0F1, apply lt_trans, apply ennreal.zero_lt_one, apply lt_of_lt_of_le, apply C0C, apply A1, apply C0D, }, rw C0F, apply A5, }, { apply exists.intro i, simp, have C0G:g i = ⊤, { apply top_unique, rw ← C0, apply A2, apply C0D, }, have C0H:f i * g i = ⊤, { rw C0G, simp, left, rw C0F1, have C0H1:(¬f i = ⊥) = (f i ≠ ⊥) := rfl, rw C0H1, rw ← @bot_lt_iff_ne_bot ennreal _ (f i), apply lt_of_le_of_lt, apply @bot_le ennreal _ 1, apply C0C, }, rw C0H, apply A5, }, }, have C1:∀ a:α, g a ≠ ⊤, { apply forall_not_of_not_exists, apply C0, }, have A6:∃ j, g j ≠ 0, { have A6A: g ≠ 0, { intro A6A1, apply A4, rw ennreal.supr_zero_iff_zero, apply A6A1, }, rw ← classical.not_forall_iff_exists_not, intro A6B, apply A6A, apply funext, intro a, apply A6B, }, cases A6 with j A6, let c := b / (g j), begin have B1 : c = b / (g j) := rfl, have B2 : c < ⊤, { rw B1, rw lt_top_iff_ne_top, intro B2A, rw ennreal.div_eq_top at B2A, cases B2A, { apply A6, apply B2A.right, }, { rw lt_top_iff_ne_top at A5, apply A5, apply B2A.left, }, }, have B3 := A3 c B2, cases B3 with i B3, have B7 :c * (g j) = b, { have B7A:c * (g j) = (b / (g j)) * (g j), { rw B1, }, rw B7A, rw ennreal.mul_div_cancel, apply A6, apply C1, }, rw ← B7, have B4: i ≤ j ∨ j ≤ i := le_total i j, cases B4, { apply exists.intro j, have B5:c < f j, { apply lt_of_lt_of_le, apply B3, apply A1, apply B4, }, have B6:(f * g) j = f j * g j := rfl, rw B6, apply ennreal.lt_of_mul_lt_mul, apply A6, apply C1, apply B5, }, { apply exists.intro i, have B6:(f * g) i = f i * g i := rfl, rw B6, have B8:c * g j < f i * g j, { rw lt_iff_le_and_ne, split, { apply ennreal.mul_le_mul, apply le_of_lt B3, apply le_refl (g j), }, { intro B8A, rw ennreal.mul_eq_mul_right at B8A, rw ← B8A at B3, have B8B := ne_of_lt B3, apply B8B, refl, apply A6, apply C1, }, }, have B9:f i * g j ≤ f i * g i, { apply ennreal.mul_le_mul, apply le_refl (f i), apply A2 B4, }, apply lt_of_lt_of_le B8 B9, }, end end lemma supr_mul_of_supr_top {α:Type*} [linear_order α] {f g:α → ennreal}: monotone f → monotone g → supr f = ⊤ → supr g ≠ 0 → supr f * supr g ≤ supr (f * g) := begin intros A1 A2 A3 A4, rw supr_mul_top A1 A2 A3 A4, apply @le_top ennreal _ ((supr f) * (supr g)), end lemma ne_top_of_supr_ne_top {α:Type*} {f:α → ennreal} {a:α}: supr f ≠ ⊤ → f a ≠ ⊤ := begin intro A1, intro A2, apply A1, rw ← top_le_iff, rw ← A2, apply le_supr f a, end lemma multiply_supr {α:Type*} [linear_order α] {f g:α → ennreal}: monotone f → monotone g → supr (f * g) = (supr f) * (supr g) := begin intros A1 A2, apply le_antisymm, { apply supr_le _, intro x, simp, apply ennreal.mul_le_mul, apply le_supr f x, apply le_supr g x, }, { /- If for all x and all y, (f x) * (f y) ≤ z, then (supr x) * (supr y) ≤ z. Consider a particular x, y. If x < y, then f x ≤ f y. Thus (f x) * (g y) ≤ (f y) * (g y) ≤ supr (f * g) However, I don't know how to prove the first part. -/ have A3:supr f = 0 ∨ supr f ≠ 0 := eq_or_ne, cases A3, { apply le_supr_mul_of_supr_zero, apply A3, }, have A4:supr g = 0 ∨ supr g ≠ 0 := eq_or_ne, cases A4, { rw mul_comm, rw mul_comm f g, apply le_supr_mul_of_supr_zero, apply A4, }, have A3A:supr f = ⊤ ∨ supr f ≠ ⊤ := eq_or_ne, cases A3A, { apply supr_mul_of_supr_top A1 A2 A3A A4, }, have A5:supr g = ⊤ ∨ supr g ≠ ⊤ := eq_or_ne, cases A5, { rw mul_comm, rw mul_comm f g, apply supr_mul_of_supr_top A2 A1 A5 A3, }, rw ← ennreal.le_div_iff_mul_le (or.inl A4) (or.inl A5), apply @supr_le ennreal α _, intro i, have B4:f i ≠ ⊤, { apply ne_top_of_supr_ne_top A3A, }, have A6:f i = 0 ∨ f i ≠ 0 := eq_or_ne, cases A6, { rw A6, simp, }, rw ennreal.le_div_iff_mul_le (or.inl A4) (or.inl A5), rw mul_comm, rw ← ennreal.le_div_iff_mul_le (or.inl A6) (or.inl B4), apply @supr_le ennreal α _, { intro j, rw ennreal.le_div_iff_mul_le (or.inl A6) (or.inl B4), have A7:i ≤ j ∨ j ≤ i := le_total i j, cases A7, { have B1:f i ≤ f j, { apply A1, apply A7, }, rw mul_comm, have B2:f i * g j ≤ f j * g j, { apply ennreal.mul_le_mul B1, apply le_refl (g j), }, apply le_trans B2, have B3:f j * g j = (f * g) j := rfl, rw B3, apply @le_supr ennreal α _ (f * g), }, { have B1:g j ≤ g i, { apply A2, apply A7, }, rw mul_comm, have B2:f i * g j ≤ f i * g i, { apply ennreal.mul_le_mul _ B1, apply le_refl (f i), }, apply le_trans B2, have B3:f i * g i = (f * g) i := rfl, rw B3, apply @le_supr ennreal α _ (f * g), }, }, }, end lemma pointwise_monotone {α β γ:Type*} [preorder α] [preorder γ] {f:α → β → γ}:monotone f ↔ (∀ b:β, monotone (λ a:α, f a b)) := begin split;intros A1, { intro b, let g:β → α → γ := (λ (b:β) (a:α), f a b), begin have A2:g = (λ (b:β) (a:α), f a b) := rfl, have A3:(λ (a:α), f a b)=g b, { rw A2, }, rw A3, apply @monotone_app α β γ _ _, have A4:(λ (a : α) (b : β), g b a) = f, { ext a b2, rw A2, }, rw A4, apply A1, end }, { apply @monotone_lam α β γ _ _, apply A1, }, end lemma pointwise_supr {α β:Type*} [preorder α] {f:α → β → ennreal} {g:β → ennreal}:supr f = g ↔ (∀ b:β, supr (λ a:α, f a b)=g b) := begin split;intros A1, { intro b, rw ← A1, rw supr_apply, }, { apply funext, intro b, rw ← (A1 b), rw supr_apply, }, end lemma multiply_supr2 {α β:Type*} [linear_order α] {f g:α → β → ennreal}: monotone f → monotone g → supr (f * g) = (supr f) * (supr g) := begin intro A1, intro A2, rw pointwise_supr, intro b, have A3:(⨆ (a : α), (f * g) a b) = (supr ((λ (a : α), f a b) * (λ a:α, g a b))), { have A3A:(λ (a:α), f a b) * (λ (a:α), g a b)=(λ a:α, (f * g) a b), { apply funext, intro a, simp, }, rw A3A, }, rw A3, rw multiply_supr, { simp, rw supr_apply, rw supr_apply, }, rw pointwise_monotone at A1, apply A1, rw pointwise_monotone at A2, apply A2, end lemma eapprox.mul_mono {α β:Type*} [preorder α] [encodable α] [measurable_space β] (f g:β → ennreal): monotone ((measure_theory.simple_func.eapprox f) * (measure_theory.simple_func.eapprox g)) := begin apply ennreal.multiply_mono, apply measure_theory.simple_func.monotone_eapprox, apply measure_theory.simple_func.monotone_eapprox, end /- This theorem leaves us in an interesting position. We now have a sequence of functions that is separable, and yet the limit is f * g. -/ lemma eapprox.mul_supr {β:Type*} [measurable_space β] (f g:β → ennreal): (measurable f) → (measurable g) → supr ((λ n:ℕ, (measure_theory.simple_func.eapprox f n).to_fun) * (λ n:ℕ, ⇑(measure_theory.simple_func.eapprox g n))) = (f * g) := begin intros A1 A2, rw multiply_supr2, apply funext, intro a, simp, rw supr_apply, rw supr_apply, rw measure_theory.simple_func.supr_eapprox_apply g A2 a, have A3:(⨆ (a_1 : ℕ), (measure_theory.simple_func.eapprox f a_1).to_fun a) = (⨆ n:ℕ, (⇑(measure_theory.simple_func.eapprox f n):β → ennreal) a) := rfl, rw A3, rw measure_theory.simple_func.supr_eapprox_apply f A1 a, apply measure_theory.simple_func.monotone_eapprox, apply measure_theory.simple_func.monotone_eapprox, end lemma supr_const_mul {Ω:Type*} {k:ennreal} {g:Ω → ennreal}: supr (λ n:Ω, k * (g n)) = k * (supr g) := begin apply le_antisymm, { simp, intro ω, apply ennreal.mul_le_mul, apply le_refl k, apply le_supr g, }, { have A1:k = 0 ∨ k ≠ 0 := eq_or_ne, cases A1, { subst k, simp, }, have A3:supr g = 0 ∨ supr g ≠ 0 := eq_or_ne, cases A3, { rw A3, rw ennreal.supr_zero_iff_zero at A3, rw A3, simp, }, have A4:(∃ ω:Ω, g ω ≠ 0), { apply classical.exists_not_of_not_forall, intro contra, apply A3, rw ennreal.supr_zero_iff_zero, apply funext, intro ω, simp, apply contra, }, cases A4 with ω A4, have A5:k = ⊤ ∨ k ≠ ⊤ := eq_or_ne, cases A5, { subst k, rw with_top.top_mul A3, have A3A:⊤ * (g ω) ≤ ⨆ (n : Ω), ⊤ * g n, { apply le_supr (λ ω:Ω, ⊤ * g ω), }, rw with_top.top_mul A4 at A3A, apply A3A, }, rw mul_comm, rw ← ennreal.le_div_iff_mul_le, simp, intro ω, rw ennreal.le_div_iff_mul_le, rw mul_comm, apply le_supr (λ (ω:Ω), k * g ω), apply (or.inl A1), apply (or.inl A5), apply (or.inl A1), apply (or.inl A5), }, end lemma supr_fn_const_mul {α Ω:Type*} {f:Ω → ennreal} {g:α → Ω → ennreal}: supr (λ n:α, f * (g n)) = f * (supr g) := begin apply funext, intro ω, rw supr_apply, simp, rw supr_apply, apply @supr_const_mul α (f ω) (λ i:α, g i ω), end lemma monotone_fn_const_mul {α Ω:Type*} [preorder α] {f:Ω → ennreal} {g:α → Ω → ennreal}: monotone g → monotone (λ n:α, f * (g n)) := begin intros A1 α1 α2 A2, rw le_func_def2, intro ω, simp, apply ennreal.mul_le_mul, apply le_refl (f ω), apply A1, apply A2, end lemma measure_theory.with_density.compose_eq_multiply {Ω:Type*} {M:measurable_space Ω} (μ:measure_theory.measure Ω) (f g:Ω → ennreal) (H:measurable f) (H2:measurable g): (μ.with_density f).integral g = μ.integral (f * g) := begin have A1:(μ.with_density f).integral g = supr (λ n:ℕ, (μ.with_density f).integral (measure_theory.simple_func.eapprox g n)), { rw ← measure_theory.integral_supr, rw supr_eapprox', apply H2, intro n, apply (measure_theory.simple_func.eapprox g n).measurable, apply measure_theory.simple_func.monotone_eapprox, }, rw A1, clear A1, have A2:(λ n:ℕ, (μ.with_density f).integral (measure_theory.simple_func.eapprox g n)) = (λ n:ℕ, μ.integral (f * (measure_theory.simple_func.eapprox g n))), { apply funext, intro n, rw simple_func.compose_eq_multiply, apply H, }, rw A2, clear A2, rw ← measure_theory.integral_supr, have A3:(⨆ (n : ℕ), f * ⇑(measure_theory.simple_func.eapprox g n)) = (f * g), { rw supr_fn_const_mul, rw supr_eapprox', apply H2, }, rw A3, intro n, apply measurable.ennreal_mul, apply H, apply measure_theory.simple_func.measurable, apply monotone_fn_const_mul, apply measure_theory.simple_func.monotone_eapprox, end
c808274bfd87daa9aef7d6b9e1678f740fa0bb3c
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/PointedMagma.lean
62078467a512505f8793461753d4828563333b77
[]
no_license
ysharoda/Deriving-Definitions
3e149e6641fae440badd35ac110a0bd705a49ad2
dfecb27572022de3d4aa702cae8db19957523a59
refs/heads/master
1,679,127,857,700
1,615,939,007,000
1,615,939,007,000
229,785,731
4
0
null
null
null
null
UTF-8
Lean
false
false
6,552
lean
import init.data.nat.basic import init.data.fin.basic import data.vector import .Prelude open Staged open nat open fin open vector section PointedMagma structure PointedMagma (A : Type) : Type := (e : A) (op : (A → (A → A))) open PointedMagma structure Sig (AS : Type) : Type := (eS : AS) (opS : (AS → (AS → AS))) structure Product (A : Type) : Type := (eP : (Prod A A)) (opP : ((Prod A A) → ((Prod A A) → (Prod A A)))) structure Hom {A1 : Type} {A2 : Type} (Po1 : (PointedMagma A1)) (Po2 : (PointedMagma A2)) : Type := (hom : (A1 → A2)) (pres_e : (hom (e Po1)) = (e Po2)) (pres_op : (∀ {x1 x2 : A1} , (hom ((op Po1) x1 x2)) = ((op Po2) (hom x1) (hom x2)))) structure RelInterp {A1 : Type} {A2 : Type} (Po1 : (PointedMagma A1)) (Po2 : (PointedMagma A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_e : (interp (e Po1) (e Po2))) (interp_op : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((op Po1) x1 x2) ((op Po2) y1 y2)))))) inductive PointedMagmaTerm : Type | eL : PointedMagmaTerm | opL : (PointedMagmaTerm → (PointedMagmaTerm → PointedMagmaTerm)) open PointedMagmaTerm inductive ClPointedMagmaTerm (A : Type) : Type | sing : (A → ClPointedMagmaTerm) | eCl : ClPointedMagmaTerm | opCl : (ClPointedMagmaTerm → (ClPointedMagmaTerm → ClPointedMagmaTerm)) open ClPointedMagmaTerm inductive OpPointedMagmaTerm (n : ℕ) : Type | v : ((fin n) → OpPointedMagmaTerm) | eOL : OpPointedMagmaTerm | opOL : (OpPointedMagmaTerm → (OpPointedMagmaTerm → OpPointedMagmaTerm)) open OpPointedMagmaTerm inductive OpPointedMagmaTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpPointedMagmaTerm2) | sing2 : (A → OpPointedMagmaTerm2) | eOL2 : OpPointedMagmaTerm2 | opOL2 : (OpPointedMagmaTerm2 → (OpPointedMagmaTerm2 → OpPointedMagmaTerm2)) open OpPointedMagmaTerm2 def simplifyCl {A : Type} : ((ClPointedMagmaTerm A) → (ClPointedMagmaTerm A)) | eCl := eCl | (opCl x1 x2) := (opCl (simplifyCl x1) (simplifyCl x2)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpPointedMagmaTerm n) → (OpPointedMagmaTerm n)) | eOL := eOL | (opOL x1 x2) := (opOL (simplifyOpB x1) (simplifyOpB x2)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpPointedMagmaTerm2 n A) → (OpPointedMagmaTerm2 n A)) | eOL2 := eOL2 | (opOL2 x1 x2) := (opOL2 (simplifyOp x1) (simplifyOp x2)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((PointedMagma A) → (PointedMagmaTerm → A)) | Po eL := (e Po) | Po (opL x1 x2) := ((op Po) (evalB Po x1) (evalB Po x2)) def evalCl {A : Type} : ((PointedMagma A) → ((ClPointedMagmaTerm A) → A)) | Po (sing x1) := x1 | Po eCl := (e Po) | Po (opCl x1 x2) := ((op Po) (evalCl Po x1) (evalCl Po x2)) def evalOpB {A : Type} {n : ℕ} : ((PointedMagma A) → ((vector A n) → ((OpPointedMagmaTerm n) → A))) | Po vars (v x1) := (nth vars x1) | Po vars eOL := (e Po) | Po vars (opOL x1 x2) := ((op Po) (evalOpB Po vars x1) (evalOpB Po vars x2)) def evalOp {A : Type} {n : ℕ} : ((PointedMagma A) → ((vector A n) → ((OpPointedMagmaTerm2 n A) → A))) | Po vars (v2 x1) := (nth vars x1) | Po vars (sing2 x1) := x1 | Po vars eOL2 := (e Po) | Po vars (opOL2 x1 x2) := ((op Po) (evalOp Po vars x1) (evalOp Po vars x2)) def inductionB {P : (PointedMagmaTerm → Type)} : ((P eL) → ((∀ (x1 x2 : PointedMagmaTerm) , ((P x1) → ((P x2) → (P (opL x1 x2))))) → (∀ (x : PointedMagmaTerm) , (P x)))) | pel popl eL := pel | pel popl (opL x1 x2) := (popl _ _ (inductionB pel popl x1) (inductionB pel popl x2)) def inductionCl {A : Type} {P : ((ClPointedMagmaTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((P eCl) → ((∀ (x1 x2 : (ClPointedMagmaTerm A)) , ((P x1) → ((P x2) → (P (opCl x1 x2))))) → (∀ (x : (ClPointedMagmaTerm A)) , (P x))))) | psing pecl popcl (sing x1) := (psing x1) | psing pecl popcl eCl := pecl | psing pecl popcl (opCl x1 x2) := (popcl _ _ (inductionCl psing pecl popcl x1) (inductionCl psing pecl popcl x2)) def inductionOpB {n : ℕ} {P : ((OpPointedMagmaTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((P eOL) → ((∀ (x1 x2 : (OpPointedMagmaTerm n)) , ((P x1) → ((P x2) → (P (opOL x1 x2))))) → (∀ (x : (OpPointedMagmaTerm n)) , (P x))))) | pv peol popol (v x1) := (pv x1) | pv peol popol eOL := peol | pv peol popol (opOL x1 x2) := (popol _ _ (inductionOpB pv peol popol x1) (inductionOpB pv peol popol x2)) def inductionOp {n : ℕ} {A : Type} {P : ((OpPointedMagmaTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((P eOL2) → ((∀ (x1 x2 : (OpPointedMagmaTerm2 n A)) , ((P x1) → ((P x2) → (P (opOL2 x1 x2))))) → (∀ (x : (OpPointedMagmaTerm2 n A)) , (P x)))))) | pv2 psing2 peol2 popol2 (v2 x1) := (pv2 x1) | pv2 psing2 peol2 popol2 (sing2 x1) := (psing2 x1) | pv2 psing2 peol2 popol2 eOL2 := peol2 | pv2 psing2 peol2 popol2 (opOL2 x1 x2) := (popol2 _ _ (inductionOp pv2 psing2 peol2 popol2 x1) (inductionOp pv2 psing2 peol2 popol2 x2)) def stageB : (PointedMagmaTerm → (Staged PointedMagmaTerm)) | eL := (Now eL) | (opL x1 x2) := (stage2 opL (codeLift2 opL) (stageB x1) (stageB x2)) def stageCl {A : Type} : ((ClPointedMagmaTerm A) → (Staged (ClPointedMagmaTerm A))) | (sing x1) := (Now (sing x1)) | eCl := (Now eCl) | (opCl x1 x2) := (stage2 opCl (codeLift2 opCl) (stageCl x1) (stageCl x2)) def stageOpB {n : ℕ} : ((OpPointedMagmaTerm n) → (Staged (OpPointedMagmaTerm n))) | (v x1) := (const (code (v x1))) | eOL := (Now eOL) | (opOL x1 x2) := (stage2 opOL (codeLift2 opOL) (stageOpB x1) (stageOpB x2)) def stageOp {n : ℕ} {A : Type} : ((OpPointedMagmaTerm2 n A) → (Staged (OpPointedMagmaTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | eOL2 := (Now eOL2) | (opOL2 x1 x2) := (stage2 opOL2 (codeLift2 opOL2) (stageOp x1) (stageOp x2)) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (eT : (Repr A)) (opT : ((Repr A) → ((Repr A) → (Repr A)))) end PointedMagma
1f0320caed5428cec07d7034bd9bf4238db305bc
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/playground/forthelean/ForTheLean.lean
9af054101def9dc47be37b7607a8e81f508e54a0
[ "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
23
lean
import ForTheLean.Demo
bb6c871f46d6862657888276a7e8fb01c20a122e
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/1016.lean
cb57cda9f99d51638222e3238ea06edebf9fcb4c
[ "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
90
lean
inductive t | one | two example (h : False) : t.one = t.two := by simp contradiction
20972dda65a2073db55ee1c0ff64777bc55fdd34
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/analysis/normed_space/compact_operator.lean
6bb435f5e3d1b8a245745c44f4d8ad3d1f3d5393
[ "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
22,010
lean
/- Copyright (c) 2022 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker -/ import analysis.normed_space.operator_norm import analysis.locally_convex.bounded /-! # Compact operators In this file we define compact linear operators between two topological vector spaces (TVS). ## Main definitions * `is_compact_operator` : predicate for compact operators ## Main statements * `is_compact_operator_iff_is_compact_closure_image_closed_ball` : the usual characterization of compact operators from a normed space to a T2 TVS. * `is_compact_operator.comp_clm` : precomposing a compact operator by a continuous linear map gives a compact operator * `is_compact_operator.clm_comp` : postcomposing a compact operator by a continuous linear map gives a compact operator * `is_compact_operator.continuous` : compact operators are automatically continuous * `is_closed_set_of_is_compact_operator` : the set of compact operators is closed for the operator norm ## Implementation details We define `is_compact_operator` as a predicate, because the space of compact operators inherits all of its structure from the space of continuous linear maps (e.g we want to have the usual operator norm on compact operators). The two natural options then would be to make it a predicate over linear maps or continuous linear maps. Instead we define it as a predicate over bare functions, although it really only makes sense for linear functions, because Lean is really good at finding coercions to bare functions (whereas coercing from continuous linear maps to linear maps often needs type ascriptions). ## TODO Once we have the strong operator topology on spaces of linear maps between two TVSs, `is_closed_set_of_is_compact_operator` should be generalized to this setup. ## References * Bourbaki, *Spectral Theory*, chapters 3 to 5, to be published (2022) ## Tags Compact operator -/ open function set filter bornology metric open_locale pointwise big_operators topological_space /-- A compact operator between two topological vector spaces. This definition is usually given as "there exists a neighborhood of zero whose image is contained in a compact set", but we choose a definition which involves fewer existential quantifiers and replaces images with preimages. We prove the equivalence in `is_compact_operator_iff_exists_mem_nhds_image_subset_compact`. -/ def is_compact_operator {M₁ M₂ : Type*} [has_zero M₁] [topological_space M₁] [topological_space M₂] (f : M₁ → M₂) : Prop := ∃ K, is_compact K ∧ f ⁻¹' K ∈ (𝓝 0 : filter M₁) lemma is_compact_operator_zero {M₁ M₂ : Type*} [has_zero M₁] [topological_space M₁] [topological_space M₂] [has_zero M₂] : is_compact_operator (0 : M₁ → M₂) := ⟨{0}, is_compact_singleton, mem_of_superset univ_mem (λ x _, rfl)⟩ section characterizations section variables {R₁ R₂ : Type*} [semiring R₁] [semiring R₂] {σ₁₂ : R₁ →+* R₂} {M₁ M₂ : Type*} [topological_space M₁] [add_comm_monoid M₁] [topological_space M₂] lemma is_compact_operator_iff_exists_mem_nhds_image_subset_compact (f : M₁ → M₂) : is_compact_operator f ↔ ∃ V ∈ (𝓝 0 : filter M₁), ∃ (K : set M₂), is_compact K ∧ f '' V ⊆ K := ⟨λ ⟨K, hK, hKf⟩, ⟨f ⁻¹' K, hKf, K, hK, image_preimage_subset _ _⟩, λ ⟨V, hV, K, hK, hVK⟩, ⟨K, hK, mem_of_superset hV (image_subset_iff.mp hVK)⟩⟩ lemma is_compact_operator_iff_exists_mem_nhds_is_compact_closure_image [t2_space M₂] (f : M₁ → M₂) : is_compact_operator f ↔ ∃ V ∈ (𝓝 0 : filter M₁), is_compact (closure $ f '' V) := begin rw is_compact_operator_iff_exists_mem_nhds_image_subset_compact, exact ⟨λ ⟨V, hV, K, hK, hKV⟩, ⟨V, hV, compact_closure_of_subset_compact hK hKV⟩, λ ⟨V, hV, hVc⟩, ⟨V, hV, closure (f '' V), hVc, subset_closure⟩⟩, end end section bounded variables {𝕜₁ 𝕜₂ : Type*} [nontrivially_normed_field 𝕜₁] [semi_normed_ring 𝕜₂] {σ₁₂ : 𝕜₁ →+* 𝕜₂} {M₁ M₂ : Type*} [topological_space M₁] [add_comm_monoid M₁] [topological_space M₂] [add_comm_monoid M₂] [module 𝕜₁ M₁] [module 𝕜₂ M₂] [has_continuous_const_smul 𝕜₂ M₂] lemma is_compact_operator.image_subset_compact_of_vonN_bounded {f : M₁ →ₛₗ[σ₁₂] M₂} (hf : is_compact_operator f) {S : set M₁} (hS : is_vonN_bounded 𝕜₁ S) : ∃ (K : set M₂), is_compact K ∧ f '' S ⊆ K := let ⟨K, hK, hKf⟩ := hf, ⟨r, hr, hrS⟩ := hS hKf, ⟨c, hc⟩ := normed_field.exists_lt_norm 𝕜₁ r, this := ne_zero_of_norm_ne_zero (hr.trans hc).ne.symm in ⟨σ₁₂ c • K, hK.image $ continuous_id.const_smul (σ₁₂ c), by rw [image_subset_iff, preimage_smul_setₛₗ _ _ _ f this.is_unit]; exact hrS c hc.le⟩ lemma is_compact_operator.is_compact_closure_image_of_vonN_bounded [t2_space M₂] {f : M₁ →ₛₗ[σ₁₂] M₂} (hf : is_compact_operator f) {S : set M₁} (hS : is_vonN_bounded 𝕜₁ S) : is_compact (closure $ f '' S) := let ⟨K, hK, hKf⟩ := hf.image_subset_compact_of_vonN_bounded hS in compact_closure_of_subset_compact hK hKf end bounded section normed_space variables {𝕜₁ 𝕜₂ : Type*} [nontrivially_normed_field 𝕜₁] [semi_normed_ring 𝕜₂] {σ₁₂ : 𝕜₁ →+* 𝕜₂} {M₁ M₂ M₃ : Type*} [seminormed_add_comm_group M₁] [topological_space M₂] [add_comm_monoid M₂] [normed_space 𝕜₁ M₁] [module 𝕜₂ M₂] lemma is_compact_operator.image_subset_compact_of_bounded [has_continuous_const_smul 𝕜₂ M₂] {f : M₁ →ₛₗ[σ₁₂] M₂} (hf : is_compact_operator f) {S : set M₁} (hS : metric.bounded S) : ∃ (K : set M₂), is_compact K ∧ f '' S ⊆ K := hf.image_subset_compact_of_vonN_bounded (by rwa [normed_space.is_vonN_bounded_iff, ← metric.bounded_iff_is_bounded]) lemma is_compact_operator.is_compact_closure_image_of_bounded [has_continuous_const_smul 𝕜₂ M₂] [t2_space M₂] {f : M₁ →ₛₗ[σ₁₂] M₂} (hf : is_compact_operator f) {S : set M₁} (hS : metric.bounded S) : is_compact (closure $ f '' S) := hf.is_compact_closure_image_of_vonN_bounded (by rwa [normed_space.is_vonN_bounded_iff, ← metric.bounded_iff_is_bounded]) lemma is_compact_operator.image_ball_subset_compact [has_continuous_const_smul 𝕜₂ M₂] {f : M₁ →ₛₗ[σ₁₂] M₂} (hf : is_compact_operator f) (r : ℝ) : ∃ (K : set M₂), is_compact K ∧ f '' metric.ball 0 r ⊆ K := hf.image_subset_compact_of_vonN_bounded (normed_space.is_vonN_bounded_ball 𝕜₁ M₁ r) lemma is_compact_operator.image_closed_ball_subset_compact [has_continuous_const_smul 𝕜₂ M₂] {f : M₁ →ₛₗ[σ₁₂] M₂} (hf : is_compact_operator f) (r : ℝ) : ∃ (K : set M₂), is_compact K ∧ f '' metric.closed_ball 0 r ⊆ K := hf.image_subset_compact_of_vonN_bounded (normed_space.is_vonN_bounded_closed_ball 𝕜₁ M₁ r) lemma is_compact_operator.is_compact_closure_image_ball [has_continuous_const_smul 𝕜₂ M₂] [t2_space M₂] {f : M₁ →ₛₗ[σ₁₂] M₂} (hf : is_compact_operator f) (r : ℝ) : is_compact (closure $ f '' metric.ball 0 r) := hf.is_compact_closure_image_of_vonN_bounded (normed_space.is_vonN_bounded_ball 𝕜₁ M₁ r) lemma is_compact_operator.is_compact_closure_image_closed_ball [has_continuous_const_smul 𝕜₂ M₂] [t2_space M₂] {f : M₁ →ₛₗ[σ₁₂] M₂} (hf : is_compact_operator f) (r : ℝ) : is_compact (closure $ f '' metric.closed_ball 0 r) := hf.is_compact_closure_image_of_vonN_bounded (normed_space.is_vonN_bounded_closed_ball 𝕜₁ M₁ r) lemma is_compact_operator_iff_image_ball_subset_compact [has_continuous_const_smul 𝕜₂ M₂] (f : M₁ →ₛₗ[σ₁₂] M₂) {r : ℝ} (hr : 0 < r) : is_compact_operator f ↔ ∃ (K : set M₂), is_compact K ∧ f '' metric.ball 0 r ⊆ K := ⟨λ hf, hf.image_ball_subset_compact r, λ ⟨K, hK, hKr⟩, (is_compact_operator_iff_exists_mem_nhds_image_subset_compact f).mpr ⟨metric.ball 0 r, ball_mem_nhds _ hr, K, hK, hKr⟩⟩ lemma is_compact_operator_iff_image_closed_ball_subset_compact [has_continuous_const_smul 𝕜₂ M₂] (f : M₁ →ₛₗ[σ₁₂] M₂) {r : ℝ} (hr : 0 < r) : is_compact_operator f ↔ ∃ (K : set M₂), is_compact K ∧ f '' metric.closed_ball 0 r ⊆ K := ⟨λ hf, hf.image_closed_ball_subset_compact r, λ ⟨K, hK, hKr⟩, (is_compact_operator_iff_exists_mem_nhds_image_subset_compact f).mpr ⟨metric.closed_ball 0 r, closed_ball_mem_nhds _ hr, K, hK, hKr⟩⟩ lemma is_compact_operator_iff_is_compact_closure_image_ball [has_continuous_const_smul 𝕜₂ M₂] [t2_space M₂] (f : M₁ →ₛₗ[σ₁₂] M₂) {r : ℝ} (hr : 0 < r) : is_compact_operator f ↔ is_compact (closure $ f '' metric.ball 0 r) := ⟨λ hf, hf.is_compact_closure_image_ball r, λ hf, (is_compact_operator_iff_exists_mem_nhds_is_compact_closure_image f).mpr ⟨metric.ball 0 r, ball_mem_nhds _ hr, hf⟩⟩ lemma is_compact_operator_iff_is_compact_closure_image_closed_ball [has_continuous_const_smul 𝕜₂ M₂] [t2_space M₂] (f : M₁ →ₛₗ[σ₁₂] M₂) {r : ℝ} (hr : 0 < r) : is_compact_operator f ↔ is_compact (closure $ f '' metric.closed_ball 0 r) := ⟨λ hf, hf.is_compact_closure_image_closed_ball r, λ hf, (is_compact_operator_iff_exists_mem_nhds_is_compact_closure_image f).mpr ⟨metric.closed_ball 0 r, closed_ball_mem_nhds _ hr, hf⟩⟩ end normed_space end characterizations section operations variables {R₁ R₂ R₃ R₄ : Type*} [semiring R₁] [semiring R₂] [comm_semiring R₃] [comm_semiring R₄] {σ₁₂ : R₁ →+* R₂} {σ₁₄ : R₁ →+* R₄} {σ₃₄ : R₃ →+* R₄} {M₁ M₂ M₃ M₄ : Type*} [topological_space M₁] [add_comm_monoid M₁] [topological_space M₂] [add_comm_monoid M₂] [topological_space M₃] [add_comm_group M₃] [topological_space M₄] [add_comm_group M₄] lemma is_compact_operator.smul {S : Type*} [monoid S] [distrib_mul_action S M₂] [has_continuous_const_smul S M₂] {f : M₁ → M₂} (hf : is_compact_operator f) (c : S) : is_compact_operator (c • f) := let ⟨K, hK, hKf⟩ := hf in ⟨c • K, hK.image $ continuous_id.const_smul c, mem_of_superset hKf (λ x hx, smul_mem_smul_set hx)⟩ lemma is_compact_operator.add [has_continuous_add M₂] {f g : M₁ → M₂} (hf : is_compact_operator f) (hg : is_compact_operator g) : is_compact_operator (f + g) := let ⟨A, hA, hAf⟩ := hf, ⟨B, hB, hBg⟩ := hg in ⟨A + B, hA.add hB, mem_of_superset (inter_mem hAf hBg) (λ x ⟨hxA, hxB⟩, set.add_mem_add hxA hxB)⟩ lemma is_compact_operator.neg [has_continuous_neg M₄] {f : M₁ → M₄} (hf : is_compact_operator f) : is_compact_operator (-f) := let ⟨K, hK, hKf⟩ := hf in ⟨-K, hK.neg, mem_of_superset hKf $ λ x (hx : f x ∈ K), set.neg_mem_neg.mpr hx⟩ lemma is_compact_operator.sub [topological_add_group M₄] {f g : M₁ → M₄} (hf : is_compact_operator f) (hg : is_compact_operator g) : is_compact_operator (f - g) := by rw sub_eq_add_neg; exact hf.add hg.neg variables (σ₁₄ M₁ M₄) /-- The submodule of compact continuous linear maps. -/ def compact_operator [module R₁ M₁] [module R₄ M₄] [has_continuous_const_smul R₄ M₄] [topological_add_group M₄] : submodule R₄ (M₁ →SL[σ₁₄] M₄) := { carrier := {f | is_compact_operator f}, add_mem' := λ f g hf hg, hf.add hg, zero_mem' := is_compact_operator_zero, smul_mem' := λ c f hf, hf.smul c } end operations section comp variables {R₁ R₂ R₃ : Type*} [semiring R₁] [semiring R₂] [semiring R₃] {σ₁₂ : R₁ →+* R₂} {σ₂₃ : R₂ →+* R₃} {M₁ M₂ M₃ : Type*} [topological_space M₁] [topological_space M₂] [topological_space M₃] [add_comm_monoid M₁] [module R₁ M₁] lemma is_compact_operator.comp_clm [add_comm_monoid M₂] [module R₂ M₂] {f : M₂ → M₃} (hf : is_compact_operator f) (g : M₁ →SL[σ₁₂] M₂) : is_compact_operator (f ∘ g) := begin have := g.continuous.tendsto 0, rw map_zero at this, rcases hf with ⟨K, hK, hKf⟩, exact ⟨K, hK, this hKf⟩ end lemma is_compact_operator.continuous_comp {f : M₁ → M₂} (hf : is_compact_operator f) {g : M₂ → M₃} (hg : continuous g) : is_compact_operator (g ∘ f) := begin rcases hf with ⟨K, hK, hKf⟩, refine ⟨g '' K, hK.image hg, mem_of_superset hKf _⟩, nth_rewrite 1 preimage_comp, exact preimage_mono (subset_preimage_image _ _) end lemma is_compact_operator.clm_comp [add_comm_monoid M₂] [module R₂ M₂] [add_comm_monoid M₃] [module R₃ M₃] {f : M₁ → M₂} (hf : is_compact_operator f) (g : M₂ →SL[σ₂₃] M₃) : is_compact_operator (g ∘ f) := hf.continuous_comp g.continuous end comp section cod_restrict variables {R₁ R₂ : Type*} [semiring R₁] [semiring R₂] {σ₁₂ : R₁ →+* R₂} {M₁ M₂ : Type*} [topological_space M₁] [topological_space M₂] [add_comm_monoid M₁] [add_comm_monoid M₂] [module R₁ M₁] [module R₂ M₂] lemma is_compact_operator.cod_restrict {f : M₁ → M₂} (hf : is_compact_operator f) {V : submodule R₂ M₂} (hV : ∀ x, f x ∈ V) (h_closed : is_closed (V : set M₂)): is_compact_operator (set.cod_restrict f V hV) := let ⟨K, hK, hKf⟩ := hf in ⟨coe ⁻¹' K, (closed_embedding_subtype_coe h_closed).is_compact_preimage hK, hKf⟩ end cod_restrict section restrict variables {R₁ R₂ R₃ : Type*} [semiring R₁] [semiring R₂] [semiring R₃] {σ₁₂ : R₁ →+* R₂} {σ₂₃ : R₂ →+* R₃} {M₁ M₂ M₃ : Type*} [topological_space M₁] [uniform_space M₂] [topological_space M₃] [add_comm_monoid M₁] [add_comm_monoid M₂] [add_comm_monoid M₃] [module R₁ M₁] [module R₂ M₂] [module R₃ M₃] /-- If a compact operator preserves a closed submodule, its restriction to that submodule is compact. Note that, following mathlib's convention in linear algebra, `restrict` designates the restriction of an endomorphism `f : E →ₗ E` to an endomorphism `f' : ↥V →ₗ ↥V`. To prove that the restriction `f' : ↥U →ₛₗ ↥V` of a compact operator `f : E →ₛₗ F` is compact, apply `is_compact_operator.cod_restrict` to `f ∘ U.subtypeL`, which is compact by `is_compact_operator.comp_clm`. -/ lemma is_compact_operator.restrict {f : M₁ →ₗ[R₁] M₁} (hf : is_compact_operator f) {V : submodule R₁ M₁} (hV : ∀ v ∈ V, f v ∈ V) (h_closed : is_closed (V : set M₁)): is_compact_operator (f.restrict hV) := (hf.comp_clm V.subtypeL).cod_restrict (set_like.forall.2 hV) h_closed /-- If a compact operator preserves a complete submodule, its restriction to that submodule is compact. Note that, following mathlib's convention in linear algebra, `restrict` designates the restriction of an endomorphism `f : E →ₗ E` to an endomorphism `f' : ↥V →ₗ ↥V`. To prove that the restriction `f' : ↥U →ₛₗ ↥V` of a compact operator `f : E →ₛₗ F` is compact, apply `is_compact_operator.cod_restrict` to `f ∘ U.subtypeL`, which is compact by `is_compact_operator.comp_clm`. -/ lemma is_compact_operator.restrict' [separated_space M₂] {f : M₂ →ₗ[R₂] M₂} (hf : is_compact_operator f) {V : submodule R₂ M₂} (hV : ∀ v ∈ V, f v ∈ V) [hcomplete : complete_space V] : is_compact_operator (f.restrict hV) := hf.restrict hV (complete_space_coe_iff_is_complete.mp hcomplete).is_closed end restrict section continuous variables {𝕜₁ 𝕜₂ : Type*} [nontrivially_normed_field 𝕜₁] [nontrivially_normed_field 𝕜₂] {σ₁₂ : 𝕜₁ →+* 𝕜₂} [ring_hom_isometric σ₁₂] {M₁ M₂ : Type*} [topological_space M₁] [add_comm_group M₁] [topological_space M₂] [add_comm_group M₂] [module 𝕜₁ M₁] [module 𝕜₂ M₂] [topological_add_group M₁] [has_continuous_const_smul 𝕜₁ M₁] [topological_add_group M₂] [has_continuous_smul 𝕜₂ M₂] @[continuity] lemma is_compact_operator.continuous {f : M₁ →ₛₗ[σ₁₂] M₂} (hf : is_compact_operator f) : continuous f := begin letI : uniform_space M₂ := topological_add_group.to_uniform_space _, haveI : uniform_add_group M₂ := topological_add_comm_group_is_uniform, -- Since `f` is linear, we only need to show that it is continuous at zero. -- Let `U` be a neighborhood of `0` in `M₂`. refine continuous_of_continuous_at_zero f (λ U hU, _), rw map_zero at hU, -- The compactness of `f` gives us a compact set `K : set M₂` such that `f ⁻¹' K` is a -- neighborhood of `0` in `M₁`. rcases hf with ⟨K, hK, hKf⟩, -- But any compact set is totally bounded, hence Von-Neumann bounded. Thus, `K` absorbs `U`. -- This gives `r > 0` such that `∀ a : 𝕜₂, r ≤ ∥a∥ → K ⊆ a • U`. rcases hK.totally_bounded.is_vonN_bounded 𝕜₂ hU with ⟨r, hr, hrU⟩, -- Choose `c : 𝕜₂` with `r < ∥c∥`. rcases normed_field.exists_lt_norm 𝕜₁ r with ⟨c, hc⟩, have hcnz : c ≠ 0 := ne_zero_of_norm_ne_zero (hr.trans hc).ne.symm, -- We have `f ⁻¹' ((σ₁₂ c⁻¹) • K) = c⁻¹ • f ⁻¹' K ∈ 𝓝 0`. Thus, showing that -- `(σ₁₂ c⁻¹) • K ⊆ U` is enough to deduce that `f ⁻¹' U ∈ 𝓝 0`. suffices : (σ₁₂ $ c⁻¹) • K ⊆ U, { refine mem_of_superset _ this, have : is_unit c⁻¹ := hcnz.is_unit.inv, rwa [mem_map, preimage_smul_setₛₗ _ _ _ f this, set_smul_mem_nhds_zero_iff (inv_ne_zero hcnz)], apply_instance }, -- Since `σ₁₂ c⁻¹` = `(σ₁₂ c)⁻¹`, we have to prove that `K ⊆ σ₁₂ c • U`. rw [map_inv₀, ← subset_set_smul_iff₀ (σ₁₂.map_ne_zero.mpr hcnz)], -- But `σ₁₂` is isometric, so `∥σ₁₂ c∥ = ∥c∥ > r`, which concludes the argument since -- `∀ a : 𝕜₂, r ≤ ∥a∥ → K ⊆ a • U`. refine hrU (σ₁₂ c) _, rw ring_hom_isometric.is_iso, exact hc.le end /-- Upgrade a compact `linear_map` to a `continuous_linear_map`. -/ def continuous_linear_map.mk_of_is_compact_operator {f : M₁ →ₛₗ[σ₁₂] M₂} (hf : is_compact_operator f) : M₁ →SL[σ₁₂] M₂ := ⟨f, hf.continuous⟩ @[simp] lemma continuous_linear_map.mk_of_is_compact_operator_to_linear_map {f : M₁ →ₛₗ[σ₁₂] M₂} (hf : is_compact_operator f) : (continuous_linear_map.mk_of_is_compact_operator hf : M₁ →ₛₗ[σ₁₂] M₂) = f := rfl @[simp] lemma continuous_linear_map.coe_mk_of_is_compact_operator {f : M₁ →ₛₗ[σ₁₂] M₂} (hf : is_compact_operator f) : (continuous_linear_map.mk_of_is_compact_operator hf : M₁ → M₂) = f := rfl lemma continuous_linear_map.mk_of_is_compact_operator_mem_compact_operator {f : M₁ →ₛₗ[σ₁₂] M₂} (hf : is_compact_operator f) : continuous_linear_map.mk_of_is_compact_operator hf ∈ compact_operator σ₁₂ M₁ M₂ := hf end continuous lemma is_closed_set_of_is_compact_operator {𝕜₁ 𝕜₂ : Type*} [nontrivially_normed_field 𝕜₁] [nontrivially_normed_field 𝕜₂] {σ₁₂ : 𝕜₁ →+* 𝕜₂} [ring_hom_isometric σ₁₂] {M₁ M₂ : Type*} [seminormed_add_comm_group M₁] [normed_add_comm_group M₂] [normed_space 𝕜₁ M₁] [normed_space 𝕜₂ M₂] [complete_space M₂] : is_closed {f : M₁ →SL[σ₁₂] M₂ | is_compact_operator f} := begin refine is_closed_of_closure_subset _, rintros u hu, rw metric.mem_closure_iff at hu, suffices : totally_bounded (u '' metric.closed_ball 0 1), { change is_compact_operator (u : M₁ →ₛₗ[σ₁₂] M₂), rw is_compact_operator_iff_is_compact_closure_image_closed_ball (u : M₁ →ₛₗ[σ₁₂] M₂) zero_lt_one, exact compact_of_totally_bounded_is_closed this.closure is_closed_closure }, rw metric.totally_bounded_iff, intros ε hε, rcases hu (ε/2) (by linarith) with ⟨v, hv, huv⟩, rcases (hv.is_compact_closure_image_closed_ball 1).finite_cover_balls (show 0 < ε/2, by linarith) with ⟨T, -, hT, hTv⟩, have hTv : v '' closed_ball 0 1 ⊆ _ := subset_closure.trans hTv, refine ⟨T, hT, _⟩, rw image_subset_iff at ⊢ hTv, intros x hx, specialize hTv hx, rw [mem_preimage, mem_Union₂] at ⊢ hTv, rcases hTv with ⟨t, ht, htx⟩, refine ⟨t, ht, _⟩, suffices : dist (u x) (v x) < ε/2, { rw mem_ball at *, linarith [dist_triangle (u x) (v x) t] }, rw mem_closed_ball_zero_iff at hx, calc dist (u x) (v x) = ∥u x - v x∥ : dist_eq_norm _ _ ... = ∥(u - v) x∥ : by rw continuous_linear_map.sub_apply; refl ... ≤ ∥u - v∥ : (u - v).unit_le_op_norm x hx ... = dist u v : (dist_eq_norm _ _).symm ... < ε/2 : huv end lemma compact_operator_topological_closure {𝕜₁ 𝕜₂ : Type*} [nontrivially_normed_field 𝕜₁] [nontrivially_normed_field 𝕜₂] {σ₁₂ : 𝕜₁ →+* 𝕜₂} [ring_hom_isometric σ₁₂] {M₁ M₂ : Type*} [seminormed_add_comm_group M₁] [normed_add_comm_group M₂] [normed_space 𝕜₁ M₁] [normed_space 𝕜₂ M₂] [complete_space M₂] : (compact_operator σ₁₂ M₁ M₂).topological_closure = compact_operator σ₁₂ M₁ M₂ := set_like.ext' (is_closed_set_of_is_compact_operator.closure_eq) lemma is_compact_operator_of_tendsto {ι 𝕜₁ 𝕜₂ : Type*} [nontrivially_normed_field 𝕜₁] [nontrivially_normed_field 𝕜₂] {σ₁₂ : 𝕜₁ →+* 𝕜₂} [ring_hom_isometric σ₁₂] {M₁ M₂ : Type*} [seminormed_add_comm_group M₁] [normed_add_comm_group M₂] [normed_space 𝕜₁ M₁] [normed_space 𝕜₂ M₂] [complete_space M₂] {l : filter ι} [l.ne_bot] {F : ι → M₁ →SL[σ₁₂] M₂} {f : M₁ →SL[σ₁₂] M₂} (hf : tendsto F l (𝓝 f)) (hF : ∀ᶠ i in l, is_compact_operator (F i)) : is_compact_operator f := is_closed_set_of_is_compact_operator.mem_of_tendsto hf hF
cbb21331cea1833aafec78913cad37aa84277de3
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/derive_fintype.lean
d7689c7101080b89e0b7b0ded0975c0364285c99
[ "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,293
lean
/- Copyright (c) 2020 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import tactic.derive_fintype import data.fintype.pi import data.fintype.prod import data.fintype.sigma @[derive fintype] inductive alphabet | a | b | c | d | e | f | g | h | i | j | k | l | m | n | o | p | q | r | s | t | u | v | w | x | y | z | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z @[derive fintype] inductive foo | A (x : bool) | B (y : unit) | C (z : fin 37) @[derive fintype] inductive foo2 (α : Type) | A : α → foo2 | B : α → α → foo2 | C : α × α → foo2 | D : foo2 -- @[derive fintype] -- won't work because missing decidable instance inductive foo3 (α β : Type) (n : ℕ) | A : (α → β) → foo3 | B : fin n → foo3 instance (α β : Type) [decidable_eq α] [fintype α] [fintype β] (n : ℕ) : fintype (foo3 α β n) := by tactic.mk_fintype_instance @[derive fintype] structure foo4 {m n : Type} (b : m → ℕ) := (x : m × n) (y : m × n) (h : b x.1 = b y.1) class my_class (M : Type*) := (one : M) (eq_one : ∀ x : M, x = one) instance {M : Type*} [fintype M] [decidable_eq M] : fintype (my_class M) := by tactic.mk_fintype_instance
7c00e33da07f8e98b141ed52ee80bbe2780af7a6
dac4e6671410f506c880986cbb2212dd7f5b3dfd
/folklore/complex.lean
0e0d734e1dd1685574fff359b99b3e7baf02dc20
[ "CC-BY-4.0" ]
permissive
thalesant/formalabstracts-2018
e6ddfe8b3ce5c6f055ddcccf345bf55c41f850c1
d206dfa32a6b4a84aacc3a5500a144757e6d3454
refs/heads/master
1,642,678,879,231
1,561,648,713,000
1,561,648,713,000
97,608,420
1
0
null
1,564,063,995,000
1,500,388,250,000
Lean
UTF-8
Lean
false
false
6,360
lean
-- basic development of complex numbers and -- transcendental functions following HOL-Light, -- up to the statement of the Riemann hypothesis. import data.set meta_data data.list data.vector topology.real algebra.group_power topology.infinite_sum noncomputable theory open classical local attribute [instance] prop_decidable namespace nat def fact : ℕ → ℕ | 0 := 1 | (succ n) := (n+1) * fact n postfix `!`:9001 := fact def odd (m : ℕ) : Prop := (∃ k, m = 2*k+1) end nat open set classical nat int list monoid vector real namespace real unfinished sup : (set ℝ) → ℝ := { description := "the supremum of a subset of real numbers. It is undefined on the empty set and on sets unbounded above." } def inf (S : set ℝ) : ℝ := - sup { x | S(-x) } def sqrt (x : ℝ) : ℝ := sup { t | (t = 0) ∨ t*t = x } def abs (x : ℝ) : ℝ := sup { t | t = x ∨ t = -x } def max (x y : ℝ) : ℝ := sup { t | t = x ∨ t = y } def min (x y : ℝ) := inf { t | t = x ∨ t = y } end real namespace complex open set classical nat int list vector real local attribute [instance] prop_decidable structure ℂ : Type := (re : ℝ) (im : ℝ) @[instance] constant complex_field : field ℂ attribute [instance] complex_field def re (c : ℂ) := c.re def im (c : ℂ) := c.im def cx (a : ℝ) : ℂ := { re := a, im := 0 } def cx2 (a : ℝ × ℝ) : ℂ := { re := prod.fst a, im := prod.snd a } def i : ℂ := { re := 0, im := 1 } instance coe_real_complex : has_coe ℝ ℂ := ⟨ cx ⟩ -- complex conjugation def cnj (z : ℂ) : ℂ := { re := z.re, im := - z.im } def abs (z : ℂ) : ℝ := real.sqrt (z.re ^ 2 + z.im ^ 2) -- complex square root with branch along the negative real axis -- following HOL-Light def sqrt (z : ℂ) : ℂ := if z.im = 0 then if 0 ≤ z.re then cx(real.sqrt(z.re)) else cx2(0,real.sqrt(- z.re)) else cx2(real.sqrt((abs z + z.re) / 2),(z.im/real.abs(z.im))*real.sqrt((abs z - z.re)/2)) def is_real (z: ℂ) := (z.im = 0) instance : has_div ℂ := ⟨ λ x y, x * y⁻¹⟩ instance : has_zero ℂ := ⟨ (of_rat 0) ⟩ instance : has_one ℂ := ⟨of_rat 1⟩ instance inhabited_ℂ : inhabited ℂ := ⟨0⟩ open nat complex constant complex_topology : topological_space ℂ instance : topological_space ℂ := complex_topology constant tam : topological_add_monoid ℂ instance : topological_add_monoid ℂ := tam def complex_sum (f : ℕ → ℂ) : ℂ := @tsum ℂ ℕ _ complex_topology _ f notation `Σ` := complex_sum instance real_of_nat_coe : has_coe ℚ ℝ := ⟨ of_rat ⟩ def exp (z : ℂ) : ℂ := Σ (λ n, z^n / (n!) ) def cos (z : ℂ) : ℂ := (exp(i*z) + exp(-i*z))/2 def sin (z : ℂ) : ℂ := (exp(i*z) - exp(-i*z))/(2*i) def tan (z : ℂ) := sin z / cos z end complex open complex classical def real.exp (x : ℝ) : ℝ := re (complex.exp x) def real.sin (x : ℝ) : ℝ := re (complex.sin x) def real.cos (x : ℝ) : ℝ := re (complex.cos x) def real.tan (x : ℝ) : ℝ := re (complex.tan x) open real -- log extended by 0 on non-positive reals def real.log (y : ℝ) : ℝ := sup { x | (real.exp x = y) ∨ (x = 0 ∧ y ≤ 0) } -- π is the smallest positive root of sin def real.π : ℝ := real.inf { pi | 0 < pi ∧ real.sin pi = 0 } open real axiom log_exists (z : complex.ℂ) : (∃! w, (z = 0 ∧ w = 0) ∨ ((z ≠ 0) ∧ complex.exp w = z ∧ -π < im w ∧ im w ≤ π)) def complex.arg (z : ℂ) : ℂ := real.inf { t | 0 ≤ t ∧ t < 2*π ∧ z = complex.abs(z)* exp(i*t) } def complex.log (z : ℂ) : ℂ := classical.some (log_exists z) -- w^z def complex.pow (w : ℂ) (z : ℂ) : ℂ := if (w = 0) then 0 else exp (z * complex.log w) def complex.atn (z : ℂ) : ℂ := (i / 2) * complex.log ( (1 - i * z) / (1 + i * z)) def complex.asn (z : ℂ) : ℂ := -i * complex.log(i * z + sqrt(1 - z^2)) def complex.acs (z : ℂ) : ℂ := -i * complex.log(z + i* sqrt(1 - z^2)) def real.asn (x : ℝ) : ℝ := re (complex.asn x) def real.acs (x : ℝ) : ℝ := re (complex.acs x) def real.sgn (x : ℝ) : ℝ := if (x > 0) then 1 else (if x = 0 then 0 else -1) open real -- nth root, extended to be an odd function: def real.root (n : ℕ) (x : ℝ) : ℝ := sgn(x) * real.exp (real.log(real.abs x) / n) -- HOL-Light's definition: def real.pow (x : ℝ) (y : ℝ) : ℝ := let exlog y x := real.exp(y * real.log x) in if (x > 0) then exlog y x else if (x = 0) then (if y = 0 then 1 else 0) else if (∃ (m n : ℕ), real.abs y = m / n ∧ odd m ∧ odd n) then - exlog y (-x) else exlog y (-x) open filter /- 1-dimensional complex case of Frechet derivative. We take f here to be total, but the derivative depends only on its germ at z0. -/ def has_complex_derivative_at (f : ℂ → ℂ) (f'z : ℂ) (z : ℂ) : Prop := let error_term (h : ℂ) : ℝ := abs((f (z + h) - (f z + f'z * h))/h) in (tendsto error_term (nhds 0) (nhds 0)) -- This must be already defined somewhere. But where? def to_subtype {α : Type*} (p : α → Prop) (x : α) (h : p x) : subtype p := { val := x, property := h } def extend_by_zero (domain : set ℂ) (f : subtype domain → ℂ) (z : ℂ) : ℂ := if h: domain z then f (to_subtype domain z h) else 0 def holomorphic_on (domain : set ℂ) (f : subtype domain → ℂ) := (∀ z : subtype domain, ∃ f'z, has_complex_derivative_at (extend_by_zero domain f) f'z z) class holomorphic_function := (domain : set ℂ) (f : subtype domain → ℂ) (open_domain : is_open domain) (has_derivative : holomorphic_on domain f) -- notation f(z), for holomorphic functions instance : has_coe_to_fun holomorphic_function := { F := λ h, subtype h.domain → ℂ, coe := λ h, h.f } -- converges for Re(s) > 1 def riemann_zeta_sum (s : ℂ) : ℂ := Σ (λ n, complex.pow n (-s) ) -- trivial zeros at -2, -4, -6,... def riemann_zeta_trivial_zero (s : ℂ) : Prop := (∃ n : ℕ, n > 0 ∧ s = (-2)*n) -- analytic continuation of Riemann zeta function. axiom riemann_zeta_exists : (∃! ζ : holomorphic_function, ζ.domain = (set.univ \ {1}) ∧ ∀ s : subtype ζ.domain, re(s) > 1 → ζ(s) = riemann_zeta_sum s) def ζ := classical.some riemann_zeta_exists -- (s ≠ 1) implicit in the domain constraints: def riemann_hypothesis := (∀ s, ζ(s) = 0 ∧ ¬(riemann_zeta_trivial_zero s) → re (s) = 1/2)
6e221b6cb07556b27c2968edbbb1df4d8f8e18da
4fa161becb8ce7378a709f5992a594764699e268
/src/algebra/category/Mon/basic.lean
d7fce7392d489da562f32d085e3287e629b82da4
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
8,180
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.concrete_category import algebra.punit_instances /-! # Category instances for monoid, add_monoid, comm_monoid, and add_comm_monoid. We introduce the bundled categories: * `Mon` * `AddMon` * `CommMon` * `AddCommMon` along with the relevant forgetful functors between them. ## Implementation notes See the note [locally reducible category instances]. -/ /-- We make SemiRing (and the other categories) locally reducible in order to define its instances. This is because writing, for example, ``` instance : concrete_category SemiRing := by { delta SemiRing, apply_instance } ``` results in an instance of the form `id (bundled_hom.concrete_category _)` and this `id`, not being [reducible], prevents a later instance search (once SemiRing is no longer reducible) from seeing that the morphisms of SemiRing are really semiring morphisms (`→+*`), and therefore have a coercion to functions, for example. It's especially important that the `has_coe_to_sort` instance not contain an extra `id` as we want the `semiring ↥R` instance to also apply to `semiring R.α` (it seems to be impractical to guarantee that we always access `R.α` through the coercion rather than directly). TODO: Probably @[derive] should be able to create instances of the required form (without `id`), and then we could use that instead of this obscure `local attribute [reducible]` method. -/ library_note "locally reducible category instances" universes u v open category_theory /-- The category of monoids and monoid morphisms. -/ @[to_additive AddMon] def Mon : Type (u+1) := bundled monoid /-- The category of additive monoids and monoid morphisms. -/ add_decl_doc AddMon namespace Mon /-- Construct a bundled `Mon` from the underlying type and typeclass. -/ @[to_additive] def of (M : Type u) [monoid M] : Mon := bundled.of M /-- Construct a bundled Mon from the underlying type and typeclass. -/ add_decl_doc AddMon.of @[to_additive] instance : inhabited Mon := -- The default instance for `monoid punit` is derived via `punit.comm_ring`, -- which breaks to_additive. ⟨@of punit $ @group.to_monoid _ $ @comm_group.to_group _ punit.comm_group⟩ local attribute [reducible] Mon @[to_additive] instance : has_coe_to_sort Mon := infer_instance -- short-circuit type class inference @[to_additive add_monoid] instance (M : Mon) : monoid M := M.str @[to_additive] instance bundled_hom : bundled_hom @monoid_hom := ⟨@monoid_hom.to_fun, @monoid_hom.id, @monoid_hom.comp, @monoid_hom.coe_inj⟩ @[to_additive] instance : category Mon := infer_instance -- short-circuit type class inference @[to_additive] instance : concrete_category Mon := infer_instance -- short-circuit type class inference end Mon /-- The category of commutative monoids and monoid morphisms. -/ @[to_additive AddCommMon] def CommMon : Type (u+1) := bundled comm_monoid /-- The category of additive commutative monoids and monoid morphisms. -/ add_decl_doc AddCommMon namespace CommMon @[to_additive] instance : bundled_hom.parent_projection comm_monoid.to_monoid := ⟨⟩ /-- Construct a bundled `CommMon` from the underlying type and typeclass. -/ @[to_additive] def of (M : Type u) [comm_monoid M] : CommMon := bundled.of M /-- Construct a bundled `AddCommMon` from the underlying type and typeclass. -/ add_decl_doc AddCommMon.of @[to_additive] instance : inhabited CommMon := -- The default instance for `comm_monoid punit` is derived via `punit.comm_ring`, -- which breaks to_additive. ⟨@of punit $ @comm_group.to_comm_monoid _ punit.comm_group⟩ local attribute [reducible] CommMon @[to_additive] instance : has_coe_to_sort CommMon := infer_instance -- short-circuit type class inference @[to_additive add_comm_monoid] instance (M : CommMon) : comm_monoid M := M.str @[to_additive] instance : category CommMon := infer_instance -- short-circuit type class inference @[to_additive] instance : concrete_category CommMon := infer_instance -- short-circuit type class inference @[to_additive has_forget_to_AddMon] instance has_forget_to_Mon : has_forget₂ CommMon Mon := bundled_hom.forget₂ _ _ end CommMon -- We verify that the coercions of morphisms to functions work correctly: example {R S : Mon} (f : R ⟶ S) : (R : Type) → (S : Type) := f example {R S : CommMon} (f : R ⟶ S) : (R : Type) → (S : Type) := f -- We verify that when constructing a morphism in `CommMon`, -- when we construct the `to_fun` field, the types are presented as `↥R`, -- rather than `R.α` or (as we used to have) `↥(bundled.map comm_monoid.to_monoid R)`. example (R : CommMon.{u}) : R ⟶ R := { to_fun := λ x, begin match_target (R : Type u), match_hyp x := (R : Type u), exact x * x end , map_one' := by simp, map_mul' := λ x y, begin rw [mul_assoc x y (x * y), ←mul_assoc y x y, mul_comm y x, mul_assoc, mul_assoc], end, } variables {X Y : Type u} section variables [monoid X] [monoid Y] /-- Build an isomorphism in the category `Mon` from a `mul_equiv` between `monoid`s. -/ @[to_additive add_equiv.to_AddMon_iso "Build an isomorphism in the category `AddMon` from an `add_equiv` between `add_monoid`s."] def mul_equiv.to_Mon_iso (e : X ≃* Y) : Mon.of X ≅ Mon.of Y := { hom := e.to_monoid_hom, inv := e.symm.to_monoid_hom } @[simp, to_additive add_equiv.to_AddMon_iso_hom] lemma mul_equiv.to_Mon_iso_hom {e : X ≃* Y} : e.to_Mon_iso.hom = e.to_monoid_hom := rfl @[simp, to_additive add_equiv.to_AddMon_iso_inv] lemma mul_equiv.to_Mon_iso_inv {e : X ≃* Y} : e.to_Mon_iso.inv = e.symm.to_monoid_hom := rfl end section variables [comm_monoid X] [comm_monoid Y] /-- Build an isomorphism in the category `CommMon` from a `mul_equiv` between `comm_monoid`s. -/ @[to_additive add_equiv.to_AddCommMon_iso "Build an isomorphism in the category `AddCommMon` from an `add_equiv` between `add_comm_monoid`s."] def mul_equiv.to_CommMon_iso (e : X ≃* Y) : CommMon.of X ≅ CommMon.of Y := { hom := e.to_monoid_hom, inv := e.symm.to_monoid_hom } @[simp, to_additive add_equiv.to_AddCommMon_iso_hom] lemma mul_equiv.to_CommMon_iso_hom {e : X ≃* Y} : e.to_CommMon_iso.hom = e.to_monoid_hom := rfl @[simp, to_additive add_equiv.to_AddCommMon_iso_inv] lemma mul_equiv.to_CommMon_iso_inv {e : X ≃* Y} : e.to_CommMon_iso.inv = e.symm.to_monoid_hom := rfl end namespace category_theory.iso /-- Build a `mul_equiv` from an isomorphism in the category `Mon`. -/ @[to_additive AddMond_iso_to_add_equiv "Build an `add_equiv` from an isomorphism in the category `AddMon`."] def Mon_iso_to_mul_equiv {X Y : Mon.{u}} (i : X ≅ Y) : X ≃* Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := by tidy, right_inv := by tidy, map_mul' := by tidy }. /-- Build a `mul_equiv` from an isomorphism in the category `CommMon`. -/ @[to_additive AddCommMon_iso_to_add_equiv "Build an `add_equiv` from an isomorphism in the category `AddCommMon`."] def CommMon_iso_to_mul_equiv {X Y : CommMon.{u}} (i : X ≅ Y) : X ≃* Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := by tidy, right_inv := by tidy, map_mul' := by tidy }. end category_theory.iso /-- multiplicative equivalences between `monoid`s are the same as (isomorphic to) isomorphisms in `Mon` -/ @[to_additive add_equiv_iso_AddMon_iso "additive equivalences between `add_monoid`s are the same as (isomorphic to) isomorphisms in `AddMon`"] def mul_equiv_iso_Mon_iso {X Y : Type u} [monoid X] [monoid Y] : (X ≃* Y) ≅ (Mon.of X ≅ Mon.of Y) := { hom := λ e, e.to_Mon_iso, inv := λ i, i.Mon_iso_to_mul_equiv, } /-- multiplicative equivalences between `comm_monoid`s are the same as (isomorphic to) isomorphisms in `CommMon` -/ @[to_additive add_equiv_iso_AddCommMon_iso "additive equivalences between `add_comm_monoid`s are the same as (isomorphic to) isomorphisms in `AddCommMon`"] def mul_equiv_iso_CommMon_iso {X Y : Type u} [comm_monoid X] [comm_monoid Y] : (X ≃* Y) ≅ (CommMon.of X ≅ CommMon.of Y) := { hom := λ e, e.to_CommMon_iso, inv := λ i, i.CommMon_iso_to_mul_equiv, }
8a3e1797df6656d4073e373429eae35a180b85a5
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/tactic/omega/int/preterm.lean
12373415538f49ec7bd4bf3886e72d5900ab701b
[ "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
1,851
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek Linear integer arithmetic terms in pre-normalized form. -/ import tactic.split_ifs tactic.omega.term namespace omega namespace int @[derive has_reflect] inductive preterm : Type | cst : int → preterm | var : int → nat → preterm | add : preterm → preterm → preterm local notation `&` k := preterm.cst k local infix ` ** ` : 300 := preterm.var local notation t `+*` s := preterm.add t s namespace preterm @[simp] def val (v : nat → int) : preterm → int | (& i) := i | (i ** n) := if i = 1 then v n else if i = -1 then -(v n) else (v n) * i | (t1 +* t2) := t1.val + t2.val def fresh_index : preterm → nat | (& _) := 0 | (i ** n) := n + 1 | (t1 +* t2) := max t1.fresh_index t2.fresh_index @[simp] def add_one (t : preterm) : preterm := t +* (&1) def repr : preterm → string | (& i) := i.repr | (i ** n) := i.repr ++ "*x" ++ n.repr | (t1 +* t2) := "(" ++ t1.repr ++ " + " ++ t2.repr ++ ")" end preterm local notation as ` {` m ` ↦ ` a `}` := list.func.set a as m @[simp] def canonize : preterm → term | (& i) := ⟨i, []⟩ | (i ** n) := ⟨0, [] {n ↦ i}⟩ | (t1 +* t2) := term.add (canonize t1) (canonize t2) @[simp] lemma val_canonize {v : nat → int} : ∀ {t : preterm}, (canonize t).val v = t.val v | (& i) := by simp only [preterm.val, add_zero, term.val, canonize, coeffs.val_nil] | (i ** n) := begin simp only [coeffs.val_set, canonize, preterm.val, zero_add, term.val], split_ifs with h1 h2, { simp only [one_mul, h1] }, { simp only [neg_mul_eq_neg_mul_symm, one_mul, h2] }, { rw mul_comm } end | (t +* s) := by simp only [canonize, val_canonize, term.val_add, preterm.val] end int end omega
7a81592b89690edd16298bc42f767c1c8807a7f7
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/ring_theory/unique_factorization_domain.lean
24b0cc01d52ee1599aa34b76346fd1c73ace02c8
[ "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
19,784
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jens Wagemaker Theory of unique factorization domains. @TODO: setup the complete lattice structure on `factor_set`. -/ import algebra.gcd_domain variables {α : Type*} local infix ` ~ᵤ ` : 50 := associated /-- Unique factorization domains. In a unique factorization domain each element (except zero) is uniquely represented as a multiset of irreducible factors. Uniqueness is only up to associated elements. This is equivalent to defining a unique factorization domain as a domain in which each element (except zero) is non-uniquely represented as a multiset of prime factors. This definition is used. To define a UFD using the traditional definition in terms of multisets of irreducible factors, use the definition `of_unique_irreducible_factorization` -/ class unique_factorization_domain (α : Type*) [integral_domain α] := (factors : α → multiset α) (factors_prod : ∀{a : α}, a ≠ 0 → (factors a).prod ~ᵤ a) (prime_factors : ∀{a : α}, a ≠ 0 → ∀x∈factors a, prime x) namespace unique_factorization_domain variables [integral_domain α] [unique_factorization_domain α] @[elab_as_eliminator] lemma induction_on_prime {P : α → Prop} (a : α) (h₁ : P 0) (h₂ : ∀ x : α, is_unit x → P x) (h₃ : ∀ a p : α, a ≠ 0 → prime p → P a → P (p * a)) : P a := by haveI := classical.dec_eq α; exact if ha0 : a = 0 then ha0.symm ▸ h₁ else @multiset.induction_on _ (λ s : multiset α, ∀ (a : α), a ≠ 0 → s.prod ~ᵤ a → (∀ p ∈ s, prime p) → P a) (factors a) (λ _ _ h _, h₂ _ ((is_unit_iff_of_associated h.symm).2 is_unit_one)) (λ p s ih a ha0 ⟨u, hu⟩ hsp, have ha : a = (p * u) * s.prod, by simp [hu.symm, mul_comm, mul_assoc], have hs0 : s.prod ≠ 0, from λ _ : s.prod = 0, by simp * at *, ha.symm ▸ h₃ _ _ hs0 (prime_of_associated ⟨u, rfl⟩ (hsp p (multiset.mem_cons_self _ _))) (ih _ hs0 (by refl) (λ p hp, hsp p (multiset.mem_cons.2 (or.inr hp))))) _ ha0 (factors_prod ha0) (prime_factors ha0) lemma factors_irreducible {a : α} (ha : irreducible a) : ∃ p, a ~ᵤ p ∧ factors a = p :: 0 := by haveI := classical.dec_eq α; exact multiset.induction_on (factors a) (λ h, (ha.1 (associated_one_iff_is_unit.1 h.symm)).elim) (λ p s _ hp hs, let ⟨u, hu⟩ := hp in ⟨p, have hs0 : s = 0, from classical.by_contradiction (λ hs0, let ⟨q, hq⟩ := multiset.exists_mem_of_ne_zero hs0 in (hs q (by simp [hq])).2.1 $ (ha.2 ((p * u) * (s.erase q).prod) _ (by rw [mul_right_comm _ _ q, mul_assoc, ← multiset.prod_cons, multiset.cons_erase hq]; simp [hu.symm, mul_comm, mul_assoc])).resolve_left $ mt is_unit_of_mul_is_unit_left $ mt is_unit_of_mul_is_unit_left (hs p (multiset.mem_cons_self _ _)).2.1), ⟨associated.symm (by clear _let_match; simp * at *), hs0 ▸ rfl⟩⟩) (factors_prod ha.ne_zero) (prime_factors ha.ne_zero) lemma irreducible_iff_prime {p : α} : irreducible p ↔ prime p := by letI := classical.dec_eq α; exact if hp0 : p = 0 then by simp [hp0] else ⟨λ h, let ⟨q, hq⟩ := factors_irreducible h in have prime q, from hq.2 ▸ prime_factors hp0 _ (by simp [hq.2]), suffices prime (factors p).prod, from prime_of_associated (factors_prod hp0) this, hq.2.symm ▸ by simp [this], irreducible_of_prime⟩ lemma irreducible_factors : ∀{a : α}, a ≠ 0 → ∀x∈factors a, irreducible x := by simp only [irreducible_iff_prime]; exact @prime_factors _ _ _ lemma unique : ∀{f g : multiset α}, (∀x∈f, irreducible x) → (∀x∈g, irreducible x) → f.prod ~ᵤ g.prod → multiset.rel associated f g := by haveI := classical.dec_eq α; exact λ f, multiset.induction_on f (λ g _ hg h, multiset.rel_zero_left.2 $ multiset.eq_zero_of_forall_not_mem (λ x hx, have is_unit g.prod, by simpa [associated_one_iff_is_unit] using h.symm, (hg x hx).1 (is_unit_iff_dvd_one.2 (dvd.trans (multiset.dvd_prod hx) (is_unit_iff_dvd_one.1 this))))) (λ p f ih g hf hg hfg, let ⟨b, hbg, hb⟩ := exists_associated_mem_of_dvd_prod (irreducible_iff_prime.1 (hf p (by simp))) (λ q hq, irreducible_iff_prime.1 (hg _ hq)) $ (dvd_iff_dvd_of_rel_right hfg).1 (show p ∣ (p :: f).prod, by simp) in begin rw ← multiset.cons_erase hbg, exact multiset.rel.cons hb (ih (λ q hq, hf _ (by simp [hq])) (λ q (hq : q ∈ g.erase b), hg q (multiset.mem_of_mem_erase hq)) (associated_mul_left_cancel (by rwa [← multiset.prod_cons, ← multiset.prod_cons, multiset.cons_erase hbg]) hb (hf p (by simp)).ne_zero)) end) end unique_factorization_domain structure unique_irreducible_factorization (α : Type*) [integral_domain α] := (factors : α → multiset α) (factors_prod : ∀{a : α}, a ≠ 0 → (factors a).prod ~ᵤ a) (irreducible_factors : ∀{a : α}, a ≠ 0 → ∀x∈factors a, irreducible x) (unique : ∀{f g : multiset α}, (∀x∈f, irreducible x) → (∀x∈g, irreducible x) → f.prod ~ᵤ g.prod → multiset.rel associated f g) namespace unique_factorization_domain open unique_factorization_domain associated variables [integral_domain α] [unique_factorization_domain α] lemma exists_mem_factors_of_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) : p ∣ a → ∃ q ∈ factors a, p ~ᵤ q := λ ⟨b, hb⟩, have hb0 : b ≠ 0, from λ hb0, by simp * at *, have multiset.rel associated (p :: factors b) (factors a), from unique (λ x hx, (multiset.mem_cons.1 hx).elim (λ h, h.symm ▸ hp) (irreducible_factors hb0 _)) (irreducible_factors ha0) (associated.symm $ calc multiset.prod (factors a) ~ᵤ a : factors_prod ha0 ... = p * b : hb ... ~ᵤ multiset.prod (p :: factors b) : by rw multiset.prod_cons; exact associated_mul_mul (associated.refl _) (associated.symm (factors_prod hb0))), multiset.exists_mem_of_rel_of_mem this (by simp) def of_unique_irreducible_factorization {α : Type*} [integral_domain α] (o : unique_irreducible_factorization α) : unique_factorization_domain α := by letI := classical.dec_eq α; exact { prime_factors := λ a h p (hpa : p ∈ o.factors a), have hpi : irreducible p, from o.irreducible_factors h _ hpa, ⟨hpi.ne_zero, hpi.1, λ a b ⟨x, hx⟩, if hab0 : a * b = 0 then (eq_zero_or_eq_zero_of_mul_eq_zero hab0).elim (λ ha0, by simp [ha0]) (λ hb0, by simp [hb0]) else have hx0 : x ≠ 0, from λ hx0, by simp * at *, have ha0 : a ≠ 0, from ne_zero_of_mul_ne_zero_right hab0, have hb0 : b ≠ 0, from ne_zero_of_mul_ne_zero_left hab0, have multiset.rel associated (p :: o.factors x) (o.factors a + o.factors b), from o.unique (λ i hi, (multiset.mem_cons.1 hi).elim (λ hip, hip.symm ▸ hpi) (o.irreducible_factors hx0 _)) (show ∀ x ∈ o.factors a + o.factors b, irreducible x, from λ x hx, (multiset.mem_add.1 hx).elim (o.irreducible_factors (ne_zero_of_mul_ne_zero_right hab0) _) (o.irreducible_factors (ne_zero_of_mul_ne_zero_left hab0) _)) $ calc multiset.prod (p :: o.factors x) ~ᵤ a * b : by rw [hx, multiset.prod_cons]; exact associated_mul_mul (by refl) (o.factors_prod hx0) ... ~ᵤ (o.factors a).prod * (o.factors b).prod : associated_mul_mul (o.factors_prod ha0).symm (o.factors_prod hb0).symm ... = _ : by rw multiset.prod_add, let ⟨q, hqf, hq⟩ := multiset.exists_mem_of_rel_of_mem this (multiset.mem_cons_self p _) in (multiset.mem_add.1 hqf).elim (λ hqa, or.inl $ (dvd_iff_dvd_of_rel_left hq).2 $ (dvd_iff_dvd_of_rel_right (o.factors_prod ha0)).1 (multiset.dvd_prod hqa)) (λ hqb, or.inr $ (dvd_iff_dvd_of_rel_left hq).2 $ (dvd_iff_dvd_of_rel_right (o.factors_prod hb0)).1 (multiset.dvd_prod hqb))⟩, ..o } end unique_factorization_domain namespace associates open unique_factorization_domain associated variables [integral_domain α] /-- `factor_set α` representation elements of unique factorization domain as multisets. `multiset α` produced by `factors` are only unique up to associated elements, while the multisets in `factor_set α` are unqiue by equality and restricted to irreducible elements. This gives us a representation of each element as a unique multisets (or the added ⊤ for 0), which has a complete lattice struture. Infimum is the greatest common divisor and supremum is the least common multiple. -/ @[reducible] def {u} factor_set (α : Type u) [integral_domain α] : Type u := with_top (multiset { a : associates α // irreducible a }) local attribute [instance] associated.setoid @[simp, nolint simp_nf] -- takes a crazy amount of time to simplify lhs theorem factor_set.coe_add {a b : multiset { a : associates α // irreducible a }} : (↑a + ↑b : factor_set α) = ↑(a + b) := with_top.coe_add lemma factor_set.sup_add_inf_eq_add [decidable_eq (associates α)] : ∀(a b : factor_set α), a ⊔ b + a ⊓ b = a + b | none b := show ⊤ ⊔ b + ⊤ ⊓ b = ⊤ + b, by simp | a none := show a ⊔ ⊤ + a ⊓ ⊤ = a + ⊤, by simp | (some a) (some b) := show (a : factor_set α) ⊔ b + a ⊓ b = a + b, from begin rw [← with_top.coe_sup, ← with_top.coe_inf, ← with_top.coe_add, ← with_top.coe_add, with_top.coe_eq_coe], exact multiset.union_add_inter _ _ end def factor_set.prod : factor_set α → associates α | none := 0 | (some s) := (s.map subtype.val).prod @[simp] theorem prod_top : (⊤ : factor_set α).prod = 0 := rfl @[simp] theorem prod_coe {s : multiset { a : associates α // irreducible a }} : (s : factor_set α).prod = (s.map subtype.val).prod := rfl @[simp] theorem prod_add : ∀(a b : factor_set α), (a + b).prod = a.prod * b.prod | none b := show (⊤ + b).prod = (⊤:factor_set α).prod * b.prod, by simp | a none := show (a + ⊤).prod = a.prod * (⊤:factor_set α).prod, by simp | (some a) (some b) := show (↑a + ↑b:factor_set α).prod = (↑a:factor_set α).prod * (↑b:factor_set α).prod, by rw [factor_set.coe_add, prod_coe, prod_coe, prod_coe, multiset.map_add, multiset.prod_add] theorem prod_mono : ∀{a b : factor_set α}, a ≤ b → a.prod ≤ b.prod | none b h := have b = ⊤, from top_unique h, by rw [this, prod_top]; exact le_refl _ | a none h := show a.prod ≤ (⊤ : factor_set α).prod, by simp; exact le_top | (some a) (some b) h := prod_le_prod $ multiset.map_le_map $ with_top.coe_le_coe.1 $ h variable [unique_factorization_domain α] theorem unique' {p q : multiset (associates α)} : (∀a∈p, irreducible a) → (∀a∈q, irreducible a) → p.prod = q.prod → p = q := begin apply multiset.induction_on_multiset_quot p, apply multiset.induction_on_multiset_quot q, assume s t hs ht eq, refine multiset.map_mk_eq_map_mk_of_rel (unique_factorization_domain.unique _ _ _), { exact assume a ha, ((irreducible_mk_iff _).1 $ hs _ $ multiset.mem_map_of_mem _ ha) }, { exact assume a ha, ((irreducible_mk_iff _).1 $ ht _ $ multiset.mem_map_of_mem _ ha) }, simpa [quot_mk_eq_mk, prod_mk, mk_eq_mk_iff_associated] using eq end private theorem forall_map_mk_factors_irreducible (x : α) (hx : x ≠ 0) : ∀(a : associates α), a ∈ multiset.map associates.mk (factors x) → irreducible a := begin assume a ha, rcases multiset.mem_map.1 ha with ⟨c, hc, rfl⟩, exact (irreducible_mk_iff c).2 (irreducible_factors hx _ hc) end theorem prod_le_prod_iff_le {p q : multiset (associates α)} (hp : ∀a∈p, irreducible a) (hq : ∀a∈q, irreducible a) : p.prod ≤ q.prod ↔ p ≤ q := iff.intro begin rintros ⟨⟨c⟩, eq⟩, have : c ≠ 0, from (mt mk_eq_zero_iff_eq_zero.2 $ assume (hc : quot.mk setoid.r c = 0), have (0 : associates α) ∈ q, from prod_eq_zero_iff.1 $ eq ▸ hc.symm ▸ mul_zero _, not_irreducible_zero ((irreducible_mk_iff 0).1 $ hq _ this)), have : associates.mk (factors c).prod = quot.mk setoid.r c, from mk_eq_mk_iff_associated.2 (factors_prod this), refine le_iff_exists_add.2 ⟨(factors c).map associates.mk, unique' hq _ _⟩, { assume x hx, rcases multiset.mem_add.1 hx with h | h, exact hp x h, exact forall_map_mk_factors_irreducible c ‹c ≠ 0› _ h }, { simp [multiset.prod_add, prod_mk, *] at * } end prod_le_prod def factors' (a : α) (ha : a ≠ 0) : multiset { a : associates α // irreducible a } := (factors a).pmap (λa ha, ⟨associates.mk a, (irreducible_mk_iff _).2 ha⟩) (irreducible_factors $ ha) @[simp] theorem map_subtype_val_factors' {a : α} (ha : a ≠ 0) : (factors' a ha).map subtype.val = (factors a).map associates.mk := by simp [factors', multiset.map_pmap, multiset.pmap_eq_map] theorem factors'_cong {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) (h : a ~ᵤ b) : factors' a ha = factors' b hb := have multiset.rel associated (factors a) (factors b), from unique (irreducible_factors ha) (irreducible_factors hb) ((factors_prod ha).trans $ h.trans $ (factors_prod hb).symm), by simpa [(multiset.map_eq_map subtype.val_injective).symm, rel_associated_iff_map_eq_map.symm] variable [dec : decidable_eq (associates α)] include dec def factors (a : associates α) : factor_set α := begin refine (if h : a = 0 then ⊤ else quotient.hrec_on a (λx h, some $ factors' x (mt mk_eq_zero_iff_eq_zero.2 h)) _ h), assume a b hab, apply function.hfunext, { have : a ~ᵤ 0 ↔ b ~ᵤ 0, from iff.intro (assume ha0, hab.symm.trans ha0) (assume hb0, hab.trans hb0), simp [quotient_mk_eq_mk, mk_eq_zero_iff_eq_zero, (associated_zero_iff_eq_zero _).symm, this] }, exact (assume ha hb eq, heq_of_eq $ congr_arg some $ factors'_cong _ _ hab) end @[simp] theorem factors_0 : (0 : associates α).factors = ⊤ := dif_pos rfl @[simp] theorem factors_mk (a : α) (h : a ≠ 0) : (associates.mk a).factors = factors' a h := dif_neg (mt mk_eq_zero_iff_eq_zero.1 h) theorem prod_factors : ∀(s : factor_set α), s.prod.factors = s | none := by simp [factor_set.prod]; refl | (some s) := begin unfold factor_set.prod, generalize eq_a : (s.map subtype.val).prod = a, rcases a with ⟨a⟩, rw quot_mk_eq_mk at *, have : (s.map subtype.val).prod ≠ 0, from assume ha, let ⟨⟨a, ha⟩, h, eq⟩ := multiset.mem_map.1 (prod_eq_zero_iff.1 ha) in have irreducible (0 : associates α), from eq ▸ ha, not_irreducible_zero ((irreducible_mk_iff _).1 this), have ha : a ≠ 0, by simp [*] at *, suffices : (unique_factorization_domain.factors a).map associates.mk = s.map subtype.val, { rw [factors_mk a ha], apply congr_arg some _, simpa [(multiset.map_eq_map subtype.val_injective).symm] }, refine unique' (forall_map_mk_factors_irreducible _ ha) (assume a ha, let ⟨⟨x, hx⟩, ha, eq⟩ := multiset.mem_map.1 ha in eq ▸ hx) _, rw [prod_mk, eq_a, mk_eq_mk_iff_associated], exact factors_prod ha end theorem factors_prod (a : associates α) : a.factors.prod = a := quotient.induction_on a $ assume a, decidable.by_cases (assume : associates.mk a = 0, by simp [quotient_mk_eq_mk, this]) (assume : associates.mk a ≠ 0, have a ≠ 0, by simp * at *, by simp [this, quotient_mk_eq_mk, prod_mk, mk_eq_mk_iff_associated.2 (factors_prod this)]) theorem eq_of_factors_eq_factors {a b : associates α} (h : a.factors = b.factors) : a = b := have a.factors.prod = b.factors.prod, by rw h, by rwa [factors_prod, factors_prod] at this omit dec theorem eq_of_prod_eq_prod {a b : factor_set α} (h : a.prod = b.prod) : a = b := begin classical, have : a.prod.factors = b.prod.factors, by rw h, rwa [prod_factors, prod_factors] at this end include dec @[simp] theorem factors_mul (a b : associates α) : (a * b).factors = a.factors + b.factors := eq_of_prod_eq_prod $ eq_of_factors_eq_factors $ by rw [prod_add, factors_prod, factors_prod, factors_prod] theorem factors_mono : ∀{a b : associates α}, a ≤ b → a.factors ≤ b.factors | s t ⟨d, rfl⟩ := by rw [factors_mul] ; exact le_add_of_nonneg_right' bot_le theorem factors_le {a b : associates α} : a.factors ≤ b.factors ↔ a ≤ b := iff.intro (assume h, have a.factors.prod ≤ b.factors.prod, from prod_mono h, by rwa [factors_prod, factors_prod] at this) factors_mono omit dec theorem prod_le {a b : factor_set α} : a.prod ≤ b.prod ↔ a ≤ b := begin classical, exact iff.intro (assume h, have a.prod.factors ≤ b.prod.factors, from factors_mono h, by rwa [prod_factors, prod_factors] at this) prod_mono end include dec instance : has_sup (associates α) := ⟨λa b, (a.factors ⊔ b.factors).prod⟩ instance : has_inf (associates α) := ⟨λa b, (a.factors ⊓ b.factors).prod⟩ instance : bounded_lattice (associates α) := { sup := (⊔), inf := (⊓), sup_le := assume a b c hac hbc, factors_prod c ▸ prod_mono (sup_le (factors_mono hac) (factors_mono hbc)), le_sup_left := assume a b, le_trans (le_of_eq (factors_prod a).symm) $ prod_mono $ le_sup_left, le_sup_right := assume a b, le_trans (le_of_eq (factors_prod b).symm) $ prod_mono $ le_sup_right, le_inf := assume a b c hac hbc, factors_prod a ▸ prod_mono (le_inf (factors_mono hac) (factors_mono hbc)), inf_le_left := assume a b, le_trans (prod_mono inf_le_left) (le_of_eq (factors_prod a)), inf_le_right := assume a b, le_trans (prod_mono inf_le_right) (le_of_eq (factors_prod b)), .. associates.partial_order, .. associates.order_top, .. associates.order_bot } lemma sup_mul_inf (a b : associates α) : (a ⊔ b) * (a ⊓ b) = a * b := show (a.factors ⊔ b.factors).prod * (a.factors ⊓ b.factors).prod = a * b, begin refine eq_of_factors_eq_factors _, rw [← prod_add, prod_factors, factors_mul, factor_set.sup_add_inf_eq_add] end end associates section open associates unique_factorization_domain /-- `to_gcd_domain` constructs a GCD domain out of a unique factorization domain over a normalization domain. -/ def unique_factorization_domain.to_gcd_domain (α : Type*) [normalization_domain α] [unique_factorization_domain α] [decidable_eq (associates α)] : gcd_domain α := { gcd := λa b, (associates.mk a ⊓ associates.mk b).out, lcm := λa b, (associates.mk a ⊔ associates.mk b).out, gcd_dvd_left := assume a b, (out_dvd_iff a (associates.mk a ⊓ associates.mk b)).2 $ inf_le_left, gcd_dvd_right := assume a b, (out_dvd_iff b (associates.mk a ⊓ associates.mk b)).2 $ inf_le_right, dvd_gcd := assume a b c hac hab, show a ∣ (associates.mk c ⊓ associates.mk b).out, by rw [dvd_out_iff, le_inf_iff, mk_le_mk_iff_dvd_iff, mk_le_mk_iff_dvd_iff]; exact ⟨hac, hab⟩, lcm_zero_left := assume a, show (⊤ ⊔ associates.mk a).out = 0, by simp, lcm_zero_right := assume a, show (associates.mk a ⊔ ⊤).out = 0, by simp, gcd_mul_lcm := assume a b, show (associates.mk a ⊓ associates.mk b).out * (associates.mk a ⊔ associates.mk b).out = normalize (a * b), by rw [← out_mk, ← out_mul, mul_comm, sup_mul_inf]; refl, normalize_gcd := assume a b, by convert normalize_out _, .. ‹normalization_domain α› } end
9af0039b588dca942dda45e307439d4aeace1fad
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/category_theory/adjunction/limits.lean
08a8087b05020d4381d2281017a971c8ebbd8c0f
[ "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
8,528
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) def functoriality_right_adjoint : cocone (K ⋙ F) ⥤ cocone K := (cocones.functoriality _ G) ⋙ (cocones.precompose (K.right_unitor.inv ≫ (whisker_left K adj.unit) ≫ (associator _ _ _).inv)) local attribute [reducible] functoriality_right_adjoint @[simps] def functoriality_unit : 𝟭 (cocone K) ⟶ cocones.functoriality _ F ⋙ functoriality_right_adjoint adj K := { app := λ c, { hom := adj.unit.app c.X } } @[simps] def functoriality_counit : functoriality_right_adjoint adj K ⋙ cocones.functoriality _ F ⟶ 𝟭 (cocone (K ⋙ F)) := { app := λ c, { hom := adj.counit.app c.X } } def functoriality_is_left_adjoint : is_left_adjoint (cocones.functoriality K F) := { right := functoriality_right_adjoint adj K, adj := mk_of_unit_counit { unit := functoriality_unit adj K, counit := functoriality_counit adj K } } /-- A left adjoint preserves colimits. -/ def left_adjoint_preserves_colimits : preserves_colimits F := { preserves_colimits_of_shape := λ J 𝒥, { preserves_colimit := λ F, by exactI { preserves := λ c hc, is_colimit.iso_unique_cocone_morphism.inv (λ s, @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 -- 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) := { cocone := E.map_cocone (colimit.cocone K), is_colimit := preserves_colimit.preserves (colimit.is_colimit K) } def has_colimit_of_comp_equivalence (E : C ⥤ D) [is_equivalence E] [has_colimit (K ⋙ E)] : has_colimit K := @has_colimit_of_iso _ _ _ _ (K ⋙ E ⋙ inv E) K (@adjunction.has_colimit_comp_equivalence _ _ _ _ _ _ (K ⋙ E) (inv E) _ _) ((functor.right_unitor _).symm ≪≫ (iso_whisker_left K (fun_inv_id E)).symm) end preservation_colimits section preservation_limits variables {J : Type v} [small_category J] (K : J ⥤ D) def functoriality_left_adjoint : cone (K ⋙ G) ⥤ cone K := (cones.functoriality _ F) ⋙ (cones.postcompose ((associator _ _ _).hom ≫ (whisker_left K adj.counit) ≫ K.right_unitor.hom)) local attribute [reducible] functoriality_left_adjoint @[simps] def functoriality_unit' : 𝟭 (cone (K ⋙ G)) ⟶ functoriality_left_adjoint adj K ⋙ cones.functoriality _ G := { app := λ c, { hom := adj.unit.app c.X, } } @[simps] def functoriality_counit' : cones.functoriality _ G ⋙ functoriality_left_adjoint adj K ⟶ 𝟭 (cone K) := { app := λ c, { hom := adj.counit.app c.X, } } def functoriality_is_right_adjoint : is_right_adjoint (cones.functoriality K G) := { left := functoriality_left_adjoint adj K, adj := mk_of_unit_counit { unit := functoriality_unit' adj K, counit := functoriality_counit' adj K } } /-- A right adjoint preserves limits. -/ def right_adjoint_preserves_limits : preserves_limits G := { preserves_limits_of_shape := λ J 𝒥, { preserves_limit := λ K, by exactI { preserves := λ c hc, is_limit.iso_unique_cone_morphism.inv (λ s, @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 l: is_limit (E.inv.map_cone (E.map_cone c)) := preserves_limit.preserves t, convert is_limit.map_cone_equiv E.fun_inv_id l, { rw functor.comp_id }, { cases c, cases c_π, congr; rw functor.comp_id } 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) := { cone := E.map_cone (limit.cone K), is_limit := preserves_limit.preserves (limit.is_limit K) } def has_limit_of_comp_equivalence (E : D ⥤ C) [is_equivalence E] [has_limit (K ⋙ E)] : has_limit K := @has_limit_of_iso _ _ _ _ (K ⋙ E ⋙ inv E) K (@adjunction.has_limit_comp_equivalence _ _ _ _ _ _ (K ⋙ E) (inv E) _ _) ((iso_whisker_left K (fun_inv_id E)) ≪≫ (functor.right_unitor _)) end preservation_limits /-- 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 } -- 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. 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
e8ee2f6805c4c9f2bccfd92532b7f172f5457e4f
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/suffices.lean
4d9b4338eba376f6b3b1cf6d96bb957b93e70cf5
[ "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
726
lean
variable {a b c : Prop} theorem ex1 (Ha : a) (Hab : a → b) (Hbc : b → c) : c := suffices b from Hbc this suffices a from Hab this Ha theorem ex2 (Ha : a) (Hab : a → b) (Hbc : b → c) : c := suffices b by apply Hbc; assumption suffices a by apply Hab; exact this Ha theorem ex3 (Ha : a) (Hab : a → b) (Hbc : b → c) : c := by suffices b by apply Hbc; assumption suffices a by apply Hab; assumption assumption theorem ex4 (Ha : a) (Hab : a → b) (Hbc : b → c) : c := suffices h1 : b from Hbc h1 suffices h2 : a from Hab h2 Ha theorem ex5 (Ha : a) (Hab : a → b) (Hbc : b → c) : c := by suffices h1 : b by apply Hbc; assumption suffices h2 : a by apply Hab; exact h2 assumption
81f7ca086d38e5c2fc70b3bcb14478788b94c6ee
4b846d8dabdc64e7ea03552bad8f7fa74763fc67
/tests/lean/run/dsimp_test.lean
749d12ce3b0d8118339c3e3c7c748bd46e222a83
[ "Apache-2.0" ]
permissive
pacchiano/lean
9324b33f3ac3b5c5647285160f9f6ea8d0d767dc
fdadada3a970377a6df8afcd629a6f2eab6e84e8
refs/heads/master
1,611,357,380,399
1,489,870,101,000
1,489,870,101,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,626
lean
def f : nat → nat | 0 := 10 | (n+1) := 20 + n open list tactic meta def check_expr (p : pexpr) (t : expr) : tactic unit := do e ← to_expr p, guard (t = e) meta def check_target (p : pexpr) : tactic unit := do t ← target, check_expr p t local attribute [-simp] map head example (a b c : nat) : head (map f [1, 2, 3]) = 20 := begin dsimp [map], check_target `(head [f 1, f 2, f 3] = 20), dsimp [f], check_target `(head [20 + 0, 20 + 1, 20 + 2] = 20), dsimp [head], check_target `(20 + 0 = 20), reflexivity end example (a b c : nat) : head (map f [1, 2, 3]) = 20 := begin dsimp [map, f, head], check_target `(20 + 0 = 20), reflexivity end @[simp] lemma succ_zero_eq_one : nat.succ 0 = 1 := rfl def g : nat × nat → nat | (a, b) := a + b lemma gax (x y) : g (x, y) = x + y := rfl attribute [simp] gax example (a b c : nat) : g (f 1, f 2) = 41 := begin dsimp, check_target `(f 1 + f 2 = 41), dsimp [f], reflexivity end example (a b c : nat) : g (f 1, f 2) = 41 := begin dsimp [f], check_target `(20 + 0 + (20 + 1) = 41), reflexivity end example (a b c : nat) : g (f 1, f 2) = 41 := begin dsimp [f] without gax, check_target `(g (20 + 0, 20 + 1) = 41), dsimp [g], check_target `(20 + 0 + (20 + 1) = 41), reflexivity end local attribute [-simp] gax example (a b c : nat) : g (f 1, f 2) = 41 := begin dsimp [f], check_target `(g (20 + 0, 20 + 1) = 41), dsimp [gax], check_target `(20 + 0 + (20 + 1) = 41), reflexivity end example (a b c : nat) : g (f 1, f 2) = 41 := begin dsimp [f, gax], check_target `(20 + 0 + (20 + 1) = 41), reflexivity end
2836551a07fa1c3c719f85e7aa286d494cbe7a3a
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/cdotTuple.lean
e73f13308725945269eb2e54d376a3da3cfab06c
[ "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
188
lean
#eval [1, 2, 3].map (·, 1) #eval (·, ·) 1 2 #eval (., ., .) 1 2 3 theorem ex1 : [1, 2, 3].map (·, 1) = [(1, 1), (2, 1), (3, 1)] := rfl theorem ex2 : (., .) 1 2 = (1, 2) := rfl