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
543382abb093978a71229a5a71f319ab4f076183
3dd1b66af77106badae6edb1c4dea91a146ead30
/tests/lean/run/tactic23.lean
7608169ddd341098dc1b49899de3bb078c8d0be5
[ "Apache-2.0" ]
permissive
silky/lean
79c20c15c93feef47bb659a2cc139b26f3614642
df8b88dca2f8da1a422cb618cd476ef5be730546
refs/heads/master
1,610,737,587,697
1,406,574,534,000
1,406,574,534,000
22,362,176
1
0
null
null
null
null
UTF-8
Lean
false
false
1,023
lean
import standard using num (num pos_num num_rec pos_num_rec) using tactic inductive nat : Type := | zero : nat | succ : nat → nat definition add [inline] (a b : nat) : nat := nat_rec a (λ n r, succ r) b infixl `+`:65 := add definition one [inline] := succ zero -- Define coercion from num -> nat -- By default the parser converts numerals into a binary representation num definition pos_num_to_nat [inline] (n : pos_num) : nat := pos_num_rec one (λ n r, r + r) (λ n r, r + r + one) n definition num_to_nat [inline] (n : num) : nat := num_rec zero (λ n, pos_num_to_nat n) n coercion num_to_nat -- Now we can write 2 + 3, the coercion will be applied check 2 + 3 -- Define an assump as an alias for the eassumption tactic definition assump : tactic := eassumption theorem T1 {p : nat → Prop} {a : nat } (H : p (a+2)) : ∃ x, p (succ x) := by apply exists_intro; assump definition is_zero (n : nat) := nat_rec true (λ n r, false) n theorem T2 : ∃ a, (is_zero a) = true := by apply exists_intro; apply refl
bff2a6b90e52ba59604904fef0e0ceb3eb455744
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/measure_theory/integral/bochner.lean
8ffb917e5355573ac34544d53059b30ed2ad378b
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
67,152
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Yury Kudryashov, Sébastien Gouëzel, Rémy Degenne -/ import measure_theory.integral.set_to_l1 import measure_theory.group.basic import analysis.normed_space.bounded_linear_maps import topology.sequences /-! # Bochner integral The Bochner integral extends the definition of the Lebesgue integral to functions that map from a measure space into a Banach space (complete normed vector space). It is constructed here by extending the integral on simple functions. ## Main definitions The Bochner integral is defined through the extension process described in the file `set_to_L1`, which follows these steps: 1. Define the integral of the indicator of a set. This is `weighted_smul μ s x = (μ s).to_real * x`. `weighted_smul μ` is shown to be linear in the value `x` and `dominated_fin_meas_additive` (defined in the file `set_to_L1`) with respect to the set `s`. 2. Define the integral on simple functions of the type `simple_func α E` (notation : `α →ₛ E`) where `E` is a real normed space. (See `simple_func.integral` for details.) 3. Transfer this definition to define the integral on `L1.simple_func α E` (notation : `α →₁ₛ[μ] E`), see `L1.simple_func.integral`. Show that this integral is a continuous linear map from `α →₁ₛ[μ] E` to `E`. 4. Define the Bochner integral on L1 functions by extending the integral on integrable simple functions `α →₁ₛ[μ] E` using `continuous_linear_map.extend` and the fact that the embedding of `α →₁ₛ[μ] E` into `α →₁[μ] E` is dense. 5. Define the Bochner integral on functions as the Bochner integral of its equivalence class in L1 space, if it is in L1, and 0 otherwise. The result of that construction is `∫ a, f a ∂μ`, which is definitionally equal to `set_to_fun (dominated_fin_meas_additive_weighted_smul μ) f`. Some basic properties of the integral (like linearity) are particular cases of the properties of `set_to_fun` (which are described in the file `set_to_L1`). ## Main statements 1. Basic properties of the Bochner integral on functions of type `α → E`, where `α` is a measure space and `E` is a real normed space. * `integral_zero` : `∫ 0 ∂μ = 0` * `integral_add` : `∫ x, f x + g x ∂μ = ∫ x, f ∂μ + ∫ x, g x ∂μ` * `integral_neg` : `∫ x, - f x ∂μ = - ∫ x, f x ∂μ` * `integral_sub` : `∫ x, f x - g x ∂μ = ∫ x, f x ∂μ - ∫ x, g x ∂μ` * `integral_smul` : `∫ x, r • f x ∂μ = r • ∫ x, f x ∂μ` * `integral_congr_ae` : `f =ᵐ[μ] g → ∫ x, f x ∂μ = ∫ x, g x ∂μ` * `norm_integral_le_integral_norm` : `∥∫ x, f x ∂μ∥ ≤ ∫ x, ∥f x∥ ∂μ` 2. Basic properties of the Bochner integral on functions of type `α → ℝ`, where `α` is a measure space. * `integral_nonneg_of_ae` : `0 ≤ᵐ[μ] f → 0 ≤ ∫ x, f x ∂μ` * `integral_nonpos_of_ae` : `f ≤ᵐ[μ] 0 → ∫ x, f x ∂μ ≤ 0` * `integral_mono_ae` : `f ≤ᵐ[μ] g → ∫ x, f x ∂μ ≤ ∫ x, g x ∂μ` * `integral_nonneg` : `0 ≤ f → 0 ≤ ∫ x, f x ∂μ` * `integral_nonpos` : `f ≤ 0 → ∫ x, f x ∂μ ≤ 0` * `integral_mono` : `f ≤ᵐ[μ] g → ∫ x, f x ∂μ ≤ ∫ x, g x ∂μ` 3. Propositions connecting the Bochner integral with the integral on `ℝ≥0∞`-valued functions, which is called `lintegral` and has the notation `∫⁻`. * `integral_eq_lintegral_max_sub_lintegral_min` : `∫ x, f x ∂μ = ∫⁻ x, f⁺ x ∂μ - ∫⁻ x, f⁻ x ∂μ`, where `f⁺` is the positive part of `f` and `f⁻` is the negative part of `f`. * `integral_eq_lintegral_of_nonneg_ae` : `0 ≤ᵐ[μ] f → ∫ x, f x ∂μ = ∫⁻ x, f x ∂μ` 4. `tendsto_integral_of_dominated_convergence` : the Lebesgue dominated convergence theorem 5. (In the file `set_integral`) integration commutes with continuous linear maps. * `continuous_linear_map.integral_comp_comm` * `linear_isometry.integral_comp_comm` ## Notes Some tips on how to prove a proposition if the API for the Bochner integral is not enough so that you need to unfold the definition of the Bochner integral and go back to simple functions. One method is to use the theorem `integrable.induction` in the file `simple_func_dense` (or one of the related results, like `Lp.induction` for functions in `Lp`), which allows you to prove something for an arbitrary measurable + integrable function. Another method is using the following steps. See `integral_eq_lintegral_max_sub_lintegral_min` for a complicated example, which proves that `∫ f = ∫⁻ f⁺ - ∫⁻ f⁻`, with the first integral sign being the Bochner integral of a real-valued function `f : α → ℝ`, and second and third integral sign being the integral on `ℝ≥0∞`-valued functions (called `lintegral`). The proof of `integral_eq_lintegral_max_sub_lintegral_min` is scattered in sections with the name `pos_part`. Here are the usual steps of proving that a property `p`, say `∫ f = ∫⁻ f⁺ - ∫⁻ f⁻`, holds for all functions : 1. First go to the `L¹` space. For example, if you see `ennreal.to_real (∫⁻ a, ennreal.of_real $ ∥f a∥)`, that is the norm of `f` in `L¹` space. Rewrite using `L1.norm_of_fun_eq_lintegral_norm`. 2. Show that the set `{f ∈ L¹ | ∫ f = ∫⁻ f⁺ - ∫⁻ f⁻}` is closed in `L¹` using `is_closed_eq`. 3. Show that the property holds for all simple functions `s` in `L¹` space. Typically, you need to convert various notions to their `simple_func` counterpart, using lemmas like `L1.integral_coe_eq_integral`. 4. Since simple functions are dense in `L¹`, ``` univ = closure {s simple} = closure {s simple | ∫ s = ∫⁻ s⁺ - ∫⁻ s⁻} : the property holds for all simple functions ⊆ closure {f | ∫ f = ∫⁻ f⁺ - ∫⁻ f⁻} = {f | ∫ f = ∫⁻ f⁺ - ∫⁻ f⁻} : closure of a closed set is itself ``` Use `is_closed_property` or `dense_range.induction_on` for this argument. ## Notations * `α →ₛ E` : simple functions (defined in `measure_theory/integration`) * `α →₁[μ] E` : functions in L1 space, i.e., equivalence classes of integrable functions (defined in `measure_theory/lp_space`) * `α →₁ₛ[μ] E` : simple functions in L1 space, i.e., equivalence classes of integrable simple functions (defined in `measure_theory/simple_func_dense`) * `∫ a, f a ∂μ` : integral of `f` with respect to a measure `μ` * `∫ a, f a` : integral of `f` with respect to `volume`, the default measure on the ambient type We also define notations for integral on a set, which are described in the file `measure_theory/set_integral`. Note : `ₛ` is typed using `\_s`. Sometimes it shows as a box if the font is missing. ## Tags Bochner integral, simple function, function space, Lebesgue dominated convergence theorem -/ noncomputable theory open_locale classical topological_space big_operators nnreal ennreal measure_theory open set filter topological_space ennreal emetric local attribute [instance] fact_one_le_one_ennreal namespace measure_theory variables {α E F 𝕜 : Type*} section weighted_smul open continuous_linear_map variables [normed_group F] [normed_space ℝ F] {m : measurable_space α} {μ : measure α} /-- Given a set `s`, return the continuous linear map `λ x, (μ s).to_real • x`. The extension of that set function through `set_to_L1` gives the Bochner integral of L1 functions. -/ def weighted_smul {m : measurable_space α} (μ : measure α) (s : set α) : F →L[ℝ] F := (μ s).to_real • (continuous_linear_map.id ℝ F) lemma weighted_smul_apply {m : measurable_space α} (μ : measure α) (s : set α) (x : F) : weighted_smul μ s x = (μ s).to_real • x := by simp [weighted_smul] @[simp] lemma weighted_smul_zero_measure {m : measurable_space α} : weighted_smul (0 : measure α) = (0 : set α → F →L[ℝ] F) := by { ext1, simp [weighted_smul], } @[simp] lemma weighted_smul_empty {m : measurable_space α} (μ : measure α) : weighted_smul μ ∅ = (0 : F →L[ℝ] F) := by { ext1 x, rw [weighted_smul_apply], simp, } lemma weighted_smul_add_measure {m : measurable_space α} (μ ν : measure α) {s : set α} (hμs : μ s ≠ ∞) (hνs : ν s ≠ ∞) : (weighted_smul (μ + ν) s : F →L[ℝ] F) = weighted_smul μ s + weighted_smul ν s := begin ext1 x, push_cast, simp_rw [pi.add_apply, weighted_smul_apply], push_cast, rw [pi.add_apply, ennreal.to_real_add hμs hνs, add_smul], end lemma weighted_smul_congr (s t : set α) (hst : μ s = μ t) : (weighted_smul μ s : F →L[ℝ] F) = weighted_smul μ t := by { ext1 x, simp_rw weighted_smul_apply, congr' 2, } lemma weighted_smul_null {s : set α} (h_zero : μ s = 0) : (weighted_smul μ s : F →L[ℝ] F) = 0 := by { ext1 x, rw [weighted_smul_apply, h_zero], simp, } lemma weighted_smul_union (s t : set α) (hs : measurable_set s) (ht : measurable_set t) (hs_finite : μ s ≠ ∞) (ht_finite : μ t ≠ ∞) (h_inter : s ∩ t = ∅) : (weighted_smul μ (s ∪ t) : F →L[ℝ] F) = weighted_smul μ s + weighted_smul μ t := begin ext1 x, simp_rw [add_apply, weighted_smul_apply, measure_union (set.disjoint_iff_inter_eq_empty.mpr h_inter) hs ht, ennreal.to_real_add hs_finite ht_finite, add_smul], end lemma weighted_smul_smul [normed_field 𝕜] [normed_space 𝕜 F] [smul_comm_class ℝ 𝕜 F] (c : 𝕜) (s : set α) (x : F) : weighted_smul μ s (c • x) = c • weighted_smul μ s x := by { simp_rw [weighted_smul_apply, smul_comm], } lemma norm_weighted_smul_le (s : set α) : ∥(weighted_smul μ s : F →L[ℝ] F)∥ ≤ (μ s).to_real := calc ∥(weighted_smul μ s : F →L[ℝ] F)∥ = ∥(μ s).to_real∥ * ∥continuous_linear_map.id ℝ F∥ : norm_smul _ _ ... ≤ ∥(μ s).to_real∥ : (mul_le_mul_of_nonneg_left norm_id_le (norm_nonneg _)).trans (mul_one _).le ... = abs (μ s).to_real : real.norm_eq_abs _ ... = (μ s).to_real : abs_eq_self.mpr ennreal.to_real_nonneg lemma dominated_fin_meas_additive_weighted_smul {m : measurable_space α} (μ : measure α) : dominated_fin_meas_additive μ (weighted_smul μ : set α → F →L[ℝ] F) 1 := ⟨weighted_smul_union, λ s, (norm_weighted_smul_le s).trans (one_mul _).symm.le⟩ end weighted_smul local infixr ` →ₛ `:25 := simple_func namespace simple_func section pos_part variables [linear_order E] [has_zero E] [measurable_space α] /-- Positive part of a simple function. -/ def pos_part (f : α →ₛ E) : α →ₛ E := f.map (λ b, max b 0) /-- Negative part of a simple function. -/ def neg_part [has_neg E] (f : α →ₛ E) : α →ₛ E := pos_part (-f) lemma pos_part_map_norm (f : α →ₛ ℝ) : (pos_part f).map norm = pos_part f := by { ext, rw [map_apply, real.norm_eq_abs, abs_of_nonneg], exact le_max_right _ _ } lemma neg_part_map_norm (f : α →ₛ ℝ) : (neg_part f).map norm = neg_part f := by { rw neg_part, exact pos_part_map_norm _ } lemma pos_part_sub_neg_part (f : α →ₛ ℝ) : f.pos_part - f.neg_part = f := begin simp only [pos_part, neg_part], ext a, rw coe_sub, exact max_zero_sub_eq_self (f a) end end pos_part section integral /-! ### The Bochner integral of simple functions Define the Bochner integral of simple functions of the type `α →ₛ β` where `β` is a normed group, and prove basic property of this integral. -/ open finset variables [normed_group E] [measurable_space E] [normed_group F] [normed_space ℝ F] {p : ℝ≥0∞} {G F' : Type*} [normed_group G] [normed_group F'] [normed_space ℝ F'] {m : measurable_space α} {μ : measure α} /-- Bochner integral of simple functions whose codomain is a real `normed_space`. This is equal to `∑ x in f.range, (μ (f ⁻¹' {x})).to_real • x` (see `integral_eq`). -/ def integral {m : measurable_space α} (μ : measure α) (f : α →ₛ F) : F := f.set_to_simple_func (weighted_smul μ) lemma integral_def {m : measurable_space α} (μ : measure α) (f : α →ₛ F) : f.integral μ = f.set_to_simple_func (weighted_smul μ) := rfl lemma integral_eq {m : measurable_space α} (μ : measure α) (f : α →ₛ F) : f.integral μ = ∑ x in f.range, (μ (f ⁻¹' {x})).to_real • x := by simp [integral, set_to_simple_func, weighted_smul_apply] lemma integral_eq_sum_filter {m : measurable_space α} (f : α →ₛ F) (μ : measure α) : f.integral μ = ∑ x in f.range.filter (λ x, x ≠ 0), (μ (f ⁻¹' {x})).to_real • x := by { rw [integral_def, set_to_simple_func_eq_sum_filter], simp_rw weighted_smul_apply, } /-- The Bochner integral is equal to a sum over any set that includes `f.range` (except `0`). -/ lemma integral_eq_sum_of_subset {f : α →ₛ F} {s : finset F} (hs : f.range.filter (λ x, x ≠ 0) ⊆ s) : f.integral μ = ∑ x in s, (μ (f ⁻¹' {x})).to_real • x := begin rw [simple_func.integral_eq_sum_filter, finset.sum_subset hs], rintro x - hx, rw [finset.mem_filter, not_and_distrib, ne.def, not_not] at hx, rcases hx with hx|rfl; [skip, simp], rw [simple_func.mem_range] at hx, rw [preimage_eq_empty]; simp [set.disjoint_singleton_left, hx] end @[simp] lemma integral_const {m : measurable_space α} (μ : measure α) (y : F) : (const α y).integral μ = (μ univ).to_real • y := calc (const α y).integral μ = ∑ z in {y}, (μ ((const α y) ⁻¹' {z})).to_real • z : integral_eq_sum_of_subset $ (filter_subset _ _).trans (range_const_subset _ _) ... = (μ univ).to_real • y : by simp @[simp] lemma integral_piecewise_zero {m : measurable_space α} (f : α →ₛ F) (μ : measure α) {s : set α} (hs : measurable_set s) : (piecewise s hs f 0).integral μ = f.integral (μ.restrict s) := begin refine (integral_eq_sum_of_subset _).trans ((sum_congr rfl $ λ y hy, _).trans (integral_eq_sum_filter _ _).symm), { intros y hy, simp only [mem_filter, mem_range, coe_piecewise, coe_zero, piecewise_eq_indicator, mem_range_indicator] at *, rcases hy with ⟨⟨rfl, -⟩|⟨x, hxs, rfl⟩, h₀⟩, exacts [(h₀ rfl).elim, ⟨set.mem_range_self _, h₀⟩] }, { dsimp, rw [indicator_preimage_of_not_mem, measure.restrict_apply (f.measurable_set_preimage _)], exact λ h₀, (mem_filter.1 hy).2 (eq.symm h₀) } end /-- Calculate the integral of `g ∘ f : α →ₛ F`, where `f` is an integrable function from `α` to `E` and `g` is a function from `E` to `F`. We require `g 0 = 0` so that `g ∘ f` is integrable. -/ lemma map_integral (f : α →ₛ E) (g : E → F) (hf : integrable f μ) (hg : g 0 = 0) : (f.map g).integral μ = ∑ x in f.range, (ennreal.to_real (μ (f ⁻¹' {x}))) • (g x) := map_set_to_simple_func _ weighted_smul_union hf hg /-- `simple_func.integral` and `simple_func.lintegral` agree when the integrand has type `α →ₛ ℝ≥0∞`. But since `ℝ≥0∞` is not a `normed_space`, we need some form of coercion. See `integral_eq_lintegral` for a simpler version. -/ lemma integral_eq_lintegral' {f : α →ₛ E} {g : E → ℝ≥0∞} (hf : integrable f μ) (hg0 : g 0 = 0) (ht : ∀ b, g b ≠ ∞) : (f.map (ennreal.to_real ∘ g)).integral μ = ennreal.to_real (∫⁻ a, g (f a) ∂μ) := begin have hf' : f.fin_meas_supp μ := integrable_iff_fin_meas_supp.1 hf, simp only [← map_apply g f, lintegral_eq_lintegral], rw [map_integral f _ hf, map_lintegral, ennreal.to_real_sum], { refine finset.sum_congr rfl (λb hb, _), rw [smul_eq_mul, to_real_mul, mul_comm] }, { assume a ha, by_cases a0 : a = 0, { rw [a0, hg0, zero_mul], exact with_top.zero_ne_top }, { apply mul_ne_top (ht a) (hf'.meas_preimage_singleton_ne_zero a0).ne } }, { simp [hg0] } end variables [normed_field 𝕜] [normed_space 𝕜 E] [normed_space ℝ E] [smul_comm_class ℝ 𝕜 E] lemma integral_congr {f g : α →ₛ E} (hf : integrable f μ) (h : f =ᵐ[μ] g) : f.integral μ = g.integral μ := set_to_simple_func_congr (weighted_smul μ) (λ s hs, weighted_smul_null) weighted_smul_union hf h /-- `simple_func.bintegral` and `simple_func.integral` agree when the integrand has type `α →ₛ ℝ≥0∞`. But since `ℝ≥0∞` is not a `normed_space`, we need some form of coercion. -/ lemma integral_eq_lintegral {f : α →ₛ ℝ} (hf : integrable f μ) (h_pos : 0 ≤ᵐ[μ] f) : f.integral μ = ennreal.to_real (∫⁻ a, ennreal.of_real (f a) ∂μ) := begin have : f =ᵐ[μ] f.map (ennreal.to_real ∘ ennreal.of_real) := h_pos.mono (λ a h, (ennreal.to_real_of_real h).symm), rw [← integral_eq_lintegral' hf], exacts [integral_congr hf this, ennreal.of_real_zero, λ b, ennreal.of_real_ne_top] end lemma integral_add {f g : α →ₛ E} (hf : integrable f μ) (hg : integrable g μ) : integral μ (f + g) = integral μ f + integral μ g := set_to_simple_func_add _ weighted_smul_union hf hg lemma integral_neg {f : α →ₛ E} (hf : integrable f μ) : integral μ (-f) = - integral μ f := set_to_simple_func_neg _ weighted_smul_union hf lemma integral_sub {f g : α →ₛ E} (hf : integrable f μ) (hg : integrable g μ) : integral μ (f - g) = integral μ f - integral μ g := set_to_simple_func_sub _ weighted_smul_union hf hg lemma integral_smul (c : 𝕜) {f : α →ₛ E} (hf : integrable f μ) : integral μ (c • f) = c • integral μ f := set_to_simple_func_smul _ weighted_smul_union weighted_smul_smul c hf lemma norm_set_to_simple_func_le_integral_norm (T : set α → E →L[ℝ] F) {C : ℝ} (hT_norm : ∀ s, ∥T s∥ ≤ C * (μ s).to_real) {f : α →ₛ E} (hf : integrable f μ) : ∥f.set_to_simple_func T∥ ≤ C * (f.map norm).integral μ := calc ∥f.set_to_simple_func T∥ ≤ C * ∑ x in f.range, ennreal.to_real (μ (f ⁻¹' {x})) * ∥x∥ : norm_set_to_simple_func_le_sum_mul_norm T hT_norm f ... = C * (f.map norm).integral μ : by { rw map_integral f norm hf norm_zero, simp_rw smul_eq_mul, } lemma norm_integral_le_integral_norm (f : α →ₛ E) (hf : integrable f μ) : ∥f.integral μ∥ ≤ (f.map norm).integral μ := begin refine (norm_set_to_simple_func_le_integral_norm _ (λ s, _) hf).trans (one_mul _).le, exact (norm_weighted_smul_le s).trans (one_mul _).symm.le, end lemma integral_add_measure {ν} (f : α →ₛ E) (hf : integrable f (μ + ν)) : f.integral (μ + ν) = f.integral μ + f.integral ν := begin simp_rw [integral_def], refine set_to_simple_func_add_left' (weighted_smul μ) (weighted_smul ν) (weighted_smul (μ + ν)) (λ s hs hμνs, _) hf, rw [measure.coe_add, pi.add_apply, ennreal.add_ne_top] at hμνs, rw weighted_smul_add_measure _ _ hμνs.1 hμνs.2, end end integral end simple_func namespace L1 open ae_eq_fun Lp.simple_func Lp variables [normed_group E] [second_countable_topology E] [measurable_space E] [borel_space E] [normed_group F] [second_countable_topology F] [measurable_space F] [borel_space F] {m : measurable_space α} {μ : measure α} variables {α E μ} namespace simple_func lemma norm_eq_integral (f : α →₁ₛ[μ] E) : ∥f∥ = ((to_simple_func f).map norm).integral μ := begin rw [norm_eq_sum_mul f, (to_simple_func f).map_integral norm (simple_func.integrable f) norm_zero], simp_rw smul_eq_mul, end section pos_part /-- Positive part of a simple function in L1 space. -/ def pos_part (f : α →₁ₛ[μ] ℝ) : α →₁ₛ[μ] ℝ := ⟨Lp.pos_part (f : α →₁[μ] ℝ), begin rcases f with ⟨f, s, hsf⟩, use s.pos_part, simp only [subtype.coe_mk, Lp.coe_pos_part, ← hsf, ae_eq_fun.pos_part_mk, simple_func.pos_part, simple_func.coe_map] end ⟩ /-- Negative part of a simple function in L1 space. -/ def neg_part (f : α →₁ₛ[μ] ℝ) : α →₁ₛ[μ] ℝ := pos_part (-f) @[norm_cast] lemma coe_pos_part (f : α →₁ₛ[μ] ℝ) : (pos_part f : α →₁[μ] ℝ) = Lp.pos_part (f : α →₁[μ] ℝ) := rfl @[norm_cast] lemma coe_neg_part (f : α →₁ₛ[μ] ℝ) : (neg_part f : α →₁[μ] ℝ) = Lp.neg_part (f : α →₁[μ] ℝ) := rfl end pos_part section simple_func_integral /-! ### The Bochner integral of `L1` Define the Bochner integral on `α →₁ₛ[μ] E` by extension from the simple functions `α →₁ₛ[μ] E`, and prove basic properties of this integral. -/ variables [normed_field 𝕜] [normed_space 𝕜 E] [normed_space ℝ E] [smul_comm_class ℝ 𝕜 E] {F' : Type*} [normed_group F'] [normed_space ℝ F'] local attribute [instance] simple_func.normed_space /-- The Bochner integral over simple functions in L1 space. -/ def integral (f : α →₁ₛ[μ] E) : E := ((to_simple_func f)).integral μ lemma integral_eq_integral (f : α →₁ₛ[μ] E) : integral f = ((to_simple_func f)).integral μ := rfl lemma integral_eq_lintegral {f : α →₁ₛ[μ] ℝ} (h_pos : 0 ≤ᵐ[μ] (to_simple_func f)) : integral f = ennreal.to_real (∫⁻ a, ennreal.of_real ((to_simple_func f) a) ∂μ) := by rw [integral, simple_func.integral_eq_lintegral (simple_func.integrable f) h_pos] lemma integral_eq_set_to_L1s (f : α →₁ₛ[μ] E) : integral f = set_to_L1s (weighted_smul μ) f := rfl lemma integral_congr {f g : α →₁ₛ[μ] E} (h : to_simple_func f =ᵐ[μ] to_simple_func g) : integral f = integral g := simple_func.integral_congr (simple_func.integrable f) h lemma integral_add (f g : α →₁ₛ[μ] E) : integral (f + g) = integral f + integral g := set_to_L1s_add _ (λ _ _, weighted_smul_null) weighted_smul_union _ _ lemma integral_smul [measurable_space 𝕜] [opens_measurable_space 𝕜] (c : 𝕜) (f : α →₁ₛ[μ] E) : integral (c • f) = c • integral f := set_to_L1s_smul _ (λ _ _, weighted_smul_null) weighted_smul_union weighted_smul_smul c f lemma norm_integral_le_norm (f : α →₁ₛ[μ] E) : ∥integral f∥ ≤ ∥f∥ := begin rw [integral, norm_eq_integral], exact (to_simple_func f).norm_integral_le_integral_norm (simple_func.integrable f) end variables {E' : Type*} [normed_group E'] [second_countable_topology E'] [measurable_space E'] [borel_space E'] [normed_space ℝ E'] [normed_space 𝕜 E'] [measurable_space 𝕜] [opens_measurable_space 𝕜] variables (α E μ 𝕜) /-- The Bochner integral over simple functions in L1 space as a continuous linear map. -/ def integral_clm' : (α →₁ₛ[μ] E) →L[𝕜] E := linear_map.mk_continuous ⟨integral, integral_add, integral_smul⟩ 1 (λf, le_trans (norm_integral_le_norm _) $ by rw one_mul) /-- The Bochner integral over simple functions in L1 space as a continuous linear map over ℝ. -/ def integral_clm : (α →₁ₛ[μ] E) →L[ℝ] E := integral_clm' α E ℝ μ variables {α E μ 𝕜} local notation `Integral` := integral_clm α E μ open continuous_linear_map lemma norm_Integral_le_one : ∥Integral∥ ≤ 1 := linear_map.mk_continuous_norm_le _ (zero_le_one) _ section pos_part lemma pos_part_to_simple_func (f : α →₁ₛ[μ] ℝ) : to_simple_func (pos_part f) =ᵐ[μ] (to_simple_func f).pos_part := begin have eq : ∀ a, (to_simple_func f).pos_part a = max ((to_simple_func f) a) 0 := λa, rfl, have ae_eq : ∀ᵐ a ∂μ, to_simple_func (pos_part f) a = max ((to_simple_func f) a) 0, { filter_upwards [to_simple_func_eq_to_fun (pos_part f), Lp.coe_fn_pos_part (f : α →₁[μ] ℝ), to_simple_func_eq_to_fun f], assume a h₁ h₂ h₃, convert h₂ }, refine ae_eq.mono (assume a h, _), rw [h, eq] end lemma neg_part_to_simple_func (f : α →₁ₛ[μ] ℝ) : to_simple_func (neg_part f) =ᵐ[μ] (to_simple_func f).neg_part := begin rw [simple_func.neg_part, measure_theory.simple_func.neg_part], filter_upwards [pos_part_to_simple_func (-f), neg_to_simple_func f], assume a h₁ h₂, rw h₁, show max _ _ = max _ _, rw h₂, refl end lemma integral_eq_norm_pos_part_sub (f : α →₁ₛ[μ] ℝ) : integral f = ∥pos_part f∥ - ∥neg_part f∥ := begin -- Convert things in `L¹` to their `simple_func` counterpart have ae_eq₁ : (to_simple_func f).pos_part =ᵐ[μ] (to_simple_func (pos_part f)).map norm, { filter_upwards [pos_part_to_simple_func f], assume a h, rw [simple_func.map_apply, h], conv_lhs { rw [← simple_func.pos_part_map_norm, simple_func.map_apply] } }, -- Convert things in `L¹` to their `simple_func` counterpart have ae_eq₂ : (to_simple_func f).neg_part =ᵐ[μ] (to_simple_func (neg_part f)).map norm, { filter_upwards [neg_part_to_simple_func f], assume a h, rw [simple_func.map_apply, h], conv_lhs { rw [← simple_func.neg_part_map_norm, simple_func.map_apply] } }, -- Convert things in `L¹` to their `simple_func` counterpart have ae_eq : ∀ᵐ a ∂μ, (to_simple_func f).pos_part a - (to_simple_func f).neg_part a = (to_simple_func (pos_part f)).map norm a - (to_simple_func (neg_part f)).map norm a, { filter_upwards [ae_eq₁, ae_eq₂], assume a h₁ h₂, rw [h₁, h₂] }, rw [integral, norm_eq_integral, norm_eq_integral, ← simple_func.integral_sub], { show (to_simple_func f).integral μ = ((to_simple_func (pos_part f)).map norm - (to_simple_func (neg_part f)).map norm).integral μ, apply measure_theory.simple_func.integral_congr (simple_func.integrable f), filter_upwards [ae_eq₁, ae_eq₂], assume a h₁ h₂, show _ = _ - _, rw [← h₁, ← h₂], have := (to_simple_func f).pos_part_sub_neg_part, conv_lhs {rw ← this}, refl }, { exact (simple_func.integrable f).max_zero.congr ae_eq₁ }, { exact (simple_func.integrable f).neg.max_zero.congr ae_eq₂ } end end pos_part end simple_func_integral end simple_func open simple_func local notation `Integral` := @integral_clm α E _ _ _ _ _ μ _ variables [normed_space ℝ E] [nondiscrete_normed_field 𝕜] [normed_space 𝕜 E] [smul_comm_class ℝ 𝕜 E] [normed_space ℝ F] [complete_space E] section integration_in_L1 local attribute [instance] simple_func.normed_space open continuous_linear_map variables (𝕜) [measurable_space 𝕜] [opens_measurable_space 𝕜] /-- The Bochner integral in L1 space as a continuous linear map. -/ def integral_clm' : (α →₁[μ] E) →L[𝕜] E := (integral_clm' α E 𝕜 μ).extend (coe_to_Lp α E 𝕜) (simple_func.dense_range one_ne_top) simple_func.uniform_inducing variables {𝕜} /-- The Bochner integral in L1 space as a continuous linear map over ℝ. -/ def integral_clm : (α →₁[μ] E) →L[ℝ] E := integral_clm' ℝ /-- The Bochner integral in L1 space -/ def integral (f : α →₁[μ] E) : E := integral_clm f lemma integral_eq (f : α →₁[μ] E) : integral f = integral_clm f := rfl lemma integral_eq_set_to_L1 (f : α →₁[μ] E) : integral f = set_to_L1 (dominated_fin_meas_additive_weighted_smul μ) f := rfl @[norm_cast] lemma simple_func.integral_L1_eq_integral (f : α →₁ₛ[μ] E) : integral (f : α →₁[μ] E) = (simple_func.integral f) := set_to_L1_eq_set_to_L1s_clm (dominated_fin_meas_additive_weighted_smul μ) f variables (α E) @[simp] lemma integral_zero : integral (0 : α →₁[μ] E) = 0 := map_zero integral_clm variables {α E} lemma integral_add (f g : α →₁[μ] E) : integral (f + g) = integral f + integral g := map_add integral_clm f g lemma integral_neg (f : α →₁[μ] E) : integral (-f) = - integral f := map_neg integral_clm f lemma integral_sub (f g : α →₁[μ] E) : integral (f - g) = integral f - integral g := map_sub integral_clm f g lemma integral_smul (c : 𝕜) (f : α →₁[μ] E) : integral (c • f) = c • integral f := map_smul (integral_clm' 𝕜) c f local notation `Integral` := @integral_clm α E _ _ _ _ _ μ _ _ local notation `sIntegral` := @simple_func.integral_clm α E _ _ _ _ _ μ _ lemma norm_Integral_le_one : ∥Integral∥ ≤ 1 := calc ∥Integral∥ ≤ (1 : ℝ≥0) * ∥sIntegral∥ : op_norm_extend_le _ _ _ $ λs, by {rw [nnreal.coe_one, one_mul], refl} ... = ∥sIntegral∥ : one_mul _ ... ≤ 1 : norm_Integral_le_one lemma norm_integral_le (f : α →₁[μ] E) : ∥integral f∥ ≤ ∥f∥ := calc ∥integral f∥ = ∥Integral f∥ : rfl ... ≤ ∥Integral∥ * ∥f∥ : le_op_norm _ _ ... ≤ 1 * ∥f∥ : mul_le_mul_of_nonneg_right norm_Integral_le_one $ norm_nonneg _ ... = ∥f∥ : one_mul _ @[continuity] lemma continuous_integral : continuous (λ (f : α →₁[μ] E), integral f) := L1.integral_clm.continuous section pos_part local attribute [instance] fact_one_le_one_ennreal lemma integral_eq_norm_pos_part_sub (f : α →₁[μ] ℝ) : integral f = ∥Lp.pos_part f∥ - ∥Lp.neg_part f∥ := begin -- Use `is_closed_property` and `is_closed_eq` refine @is_closed_property _ _ _ (coe : (α →₁ₛ[μ] ℝ) → (α →₁[μ] ℝ)) (λ f : α →₁[μ] ℝ, integral f = ∥Lp.pos_part f∥ - ∥Lp.neg_part f∥) (simple_func.dense_range one_ne_top) (is_closed_eq _ _) _ f, { exact cont _ }, { refine continuous.sub (continuous_norm.comp Lp.continuous_pos_part) (continuous_norm.comp Lp.continuous_neg_part) }, -- Show that the property holds for all simple functions in the `L¹` space. { assume s, norm_cast, exact simple_func.integral_eq_norm_pos_part_sub _ } end end pos_part end integration_in_L1 end L1 /-! ### The Bochner integral on functions Define the Bochner integral on functions generally to be the `L1` Bochner integral, for integrable functions, and 0 otherwise; prove its basic properties. -/ variables [normed_group E] [second_countable_topology E] [normed_space ℝ E] [complete_space E] [measurable_space E] [borel_space E] [nondiscrete_normed_field 𝕜] [normed_space 𝕜 E] [smul_comm_class ℝ 𝕜 E] [normed_group F] [second_countable_topology F] [normed_space ℝ F] [complete_space F] [measurable_space F] [borel_space F] /-- The Bochner integral -/ def integral {m : measurable_space α} (μ : measure α) (f : α → E) : E := if hf : integrable f μ then L1.integral (hf.to_L1 f) else 0 /-! In the notation for integrals, an expression like `∫ x, g ∥x∥ ∂μ` will not be parsed correctly, and needs parentheses. We do not set the binding power of `r` to `0`, because then `∫ x, f x = 0` will be parsed incorrectly. -/ notation `∫` binders `, ` r:(scoped:60 f, f) ` ∂` μ:70 := integral μ r notation `∫` binders `, ` r:(scoped:60 f, integral volume f) := r notation `∫` binders ` in ` s `, ` r:(scoped:60 f, f) ` ∂` μ:70 := integral (measure.restrict μ s) r notation `∫` binders ` in ` s `, ` r:(scoped:60 f, integral (measure.restrict volume s) f) := r section properties open continuous_linear_map measure_theory.simple_func variables {f g : α → E} {m : measurable_space α} {μ : measure α} lemma integral_eq (f : α → E) (hf : integrable f μ) : ∫ a, f a ∂μ = L1.integral (hf.to_L1 f) := dif_pos hf lemma integral_eq_set_to_fun (f : α → E) : ∫ a, f a ∂μ = set_to_fun (dominated_fin_meas_additive_weighted_smul μ) f := rfl lemma L1.integral_eq_integral (f : α →₁[μ] E) : L1.integral f = ∫ a, f a ∂μ := (L1.set_to_fun_eq_set_to_L1 (dominated_fin_meas_additive_weighted_smul μ) f).symm lemma integral_undef (h : ¬ integrable f μ) : ∫ a, f a ∂μ = 0 := dif_neg h lemma integral_non_ae_measurable (h : ¬ ae_measurable f μ) : ∫ a, f a ∂μ = 0 := integral_undef $ not_and_of_not_left _ h variables (α E) lemma integral_zero : ∫ a : α, (0:E) ∂μ = 0 := set_to_fun_zero (dominated_fin_meas_additive_weighted_smul μ) @[simp] lemma integral_zero' : integral μ (0 : α → E) = 0 := integral_zero α E variables {α E} lemma integral_add (hf : integrable f μ) (hg : integrable g μ) : ∫ a, f a + g a ∂μ = ∫ a, f a ∂μ + ∫ a, g a ∂μ := set_to_fun_add (dominated_fin_meas_additive_weighted_smul μ) hf hg lemma integral_add' (hf : integrable f μ) (hg : integrable g μ) : ∫ a, (f + g) a ∂μ = ∫ a, f a ∂μ + ∫ a, g a ∂μ := integral_add hf hg lemma integral_neg (f : α → E) : ∫ a, -f a ∂μ = - ∫ a, f a ∂μ := set_to_fun_neg (dominated_fin_meas_additive_weighted_smul μ) f lemma integral_neg' (f : α → E) : ∫ a, (-f) a ∂μ = - ∫ a, f a ∂μ := integral_neg f lemma integral_sub (hf : integrable f μ) (hg : integrable g μ) : ∫ a, f a - g a ∂μ = ∫ a, f a ∂μ - ∫ a, g a ∂μ := set_to_fun_sub (dominated_fin_meas_additive_weighted_smul μ) hf hg lemma integral_sub' (hf : integrable f μ) (hg : integrable g μ) : ∫ a, (f - g) a ∂μ = ∫ a, f a ∂μ - ∫ a, g a ∂μ := integral_sub hf hg lemma integral_smul [measurable_space 𝕜] [opens_measurable_space 𝕜] (c : 𝕜) (f : α → E) : ∫ a, c • (f a) ∂μ = c • ∫ a, f a ∂μ := set_to_fun_smul (dominated_fin_meas_additive_weighted_smul μ) weighted_smul_smul c f lemma integral_mul_left (r : ℝ) (f : α → ℝ) : ∫ a, r * (f a) ∂μ = r * ∫ a, f a ∂μ := integral_smul r f lemma integral_mul_right (r : ℝ) (f : α → ℝ) : ∫ a, (f a) * r ∂μ = ∫ a, f a ∂μ * r := by { simp only [mul_comm], exact integral_mul_left r f } lemma integral_div (r : ℝ) (f : α → ℝ) : ∫ a, (f a) / r ∂μ = ∫ a, f a ∂μ / r := integral_mul_right r⁻¹ f lemma integral_congr_ae (h : f =ᵐ[μ] g) : ∫ a, f a ∂μ = ∫ a, g a ∂μ := set_to_fun_congr_ae (dominated_fin_meas_additive_weighted_smul μ) h @[simp] lemma L1.integral_of_fun_eq_integral {f : α → E} (hf : integrable f μ) : ∫ a, (hf.to_L1 f) a ∂μ = ∫ a, f a ∂μ := integral_congr_ae $ by simp [integrable.coe_fn_to_L1] @[continuity] lemma continuous_integral : continuous (λ (f : α →₁[μ] E), ∫ a, f a ∂μ) := by { simp only [← L1.integral_eq_integral], exact L1.continuous_integral } lemma norm_integral_le_lintegral_norm (f : α → E) : ∥∫ a, f a ∂μ∥ ≤ ennreal.to_real (∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ) := begin by_cases hf : integrable f μ, { rw [integral_eq f hf, ← integrable.norm_to_L1_eq_lintegral_norm f hf], exact L1.norm_integral_le _ }, { rw [integral_undef hf, norm_zero], exact to_real_nonneg } end lemma ennnorm_integral_le_lintegral_ennnorm (f : α → E) : (nnnorm (∫ a, f a ∂μ) : ℝ≥0∞) ≤ ∫⁻ a, (nnnorm (f a)) ∂μ := by { simp_rw [← of_real_norm_eq_coe_nnnorm], apply ennreal.of_real_le_of_le_to_real, exact norm_integral_le_lintegral_norm f } lemma integral_eq_zero_of_ae {f : α → E} (hf : f =ᵐ[μ] 0) : ∫ a, f a ∂μ = 0 := by simp [integral_congr_ae hf, integral_zero] /-- If `f` has finite integral, then `∫ x in s, f x ∂μ` is absolutely continuous in `s`: it tends to zero as `μ s` tends to zero. -/ lemma has_finite_integral.tendsto_set_integral_nhds_zero {ι} {f : α → E} (hf : has_finite_integral f μ) {l : filter ι} {s : ι → set α} (hs : tendsto (μ ∘ s) l (𝓝 0)) : tendsto (λ i, ∫ x in s i, f x ∂μ) l (𝓝 0) := begin rw [tendsto_zero_iff_norm_tendsto_zero], simp_rw [← coe_nnnorm, ← nnreal.coe_zero, nnreal.tendsto_coe, ← ennreal.tendsto_coe, ennreal.coe_zero], exact tendsto_of_tendsto_of_tendsto_of_le_of_le tendsto_const_nhds (tendsto_set_lintegral_zero (ne_of_lt hf) hs) (λ i, zero_le _) (λ i, ennnorm_integral_le_lintegral_ennnorm _) end /-- If `f` is integrable, then `∫ x in s, f x ∂μ` is absolutely continuous in `s`: it tends to zero as `μ s` tends to zero. -/ lemma integrable.tendsto_set_integral_nhds_zero {ι} {f : α → E} (hf : integrable f μ) {l : filter ι} {s : ι → set α} (hs : tendsto (μ ∘ s) l (𝓝 0)) : tendsto (λ i, ∫ x in s i, f x ∂μ) l (𝓝 0) := hf.2.tendsto_set_integral_nhds_zero hs /-- If `F i → f` in `L1`, then `∫ x, F i x ∂μ → ∫ x, f x∂μ`. -/ lemma tendsto_integral_of_L1 {ι} (f : α → E) (hfi : integrable f μ) {F : ι → α → E} {l : filter ι} (hFi : ∀ᶠ i in l, integrable (F i) μ) (hF : tendsto (λ i, ∫⁻ x, ∥F i x - f x∥₊ ∂μ) l (𝓝 0)) : tendsto (λ i, ∫ x, F i x ∂μ) l (𝓝 $ ∫ x, f x ∂μ) := begin rw [tendsto_iff_norm_tendsto_zero], replace hF : tendsto (λ i, ennreal.to_real $ ∫⁻ x, ∥F i x - f x∥₊ ∂μ) l (𝓝 0) := (ennreal.tendsto_to_real zero_ne_top).comp hF, refine squeeze_zero_norm' (hFi.mp $ hFi.mono $ λ i hFi hFm, _) hF, simp only [norm_norm, ← integral_sub hFi hfi], convert norm_integral_le_lintegral_norm (λ x, F i x - f x), ext1 x, exact coe_nnreal_eq _ end /-- Lebesgue dominated convergence theorem provides sufficient conditions under which almost everywhere convergence of a sequence of functions implies the convergence of their integrals. -/ theorem tendsto_integral_of_dominated_convergence {F : ℕ → α → E} {f : α → E} (bound : α → ℝ) (F_measurable : ∀ n, ae_measurable (F n) μ) (bound_integrable : integrable bound μ) (h_bound : ∀ n, ∀ᵐ a ∂μ, ∥F n a∥ ≤ bound a) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) : tendsto (λn, ∫ a, F n a ∂μ) at_top (𝓝 $ ∫ a, f a ∂μ) := begin /- `f` is a.e.-measurable, since it is the a.e.-pointwise limit of a.e.-measurable functions. -/ have f_measurable : ae_measurable f μ := ae_measurable_of_tendsto_metric_ae F_measurable h_lim, /- To show `(∫ a, F n a) --> (∫ f)`, suffices to show `∥∫ a, F n a - ∫ f∥ --> 0` -/ rw tendsto_iff_norm_tendsto_zero, /- But `0 ≤ ∥∫ a, F n a - ∫ f∥ = ∥∫ a, (F n a - f a) ∥ ≤ ∫ a, ∥F n a - f a∥, and thus we apply the sandwich theorem and prove that `∫ a, ∥F n a - f a∥ --> 0` -/ have lintegral_norm_tendsto_zero : tendsto (λn, ennreal.to_real $ ∫⁻ a, (ennreal.of_real ∥F n a - f a∥) ∂μ) at_top (𝓝 0) := (tendsto_to_real zero_ne_top).comp (tendsto_lintegral_norm_of_dominated_convergence F_measurable f_measurable bound_integrable.has_finite_integral h_bound h_lim), -- Use the sandwich theorem refine squeeze_zero (λ n, norm_nonneg _) _ lintegral_norm_tendsto_zero, -- Show `∥∫ a, F n a - ∫ f∥ ≤ ∫ a, ∥F n a - f a∥` for all `n` { assume n, have h₁ : integrable (F n) μ := bound_integrable.mono' (F_measurable n) (h_bound _), have h₂ : integrable f μ := ⟨f_measurable, has_finite_integral_of_dominated_convergence bound_integrable.has_finite_integral h_bound h_lim⟩, rw ← integral_sub h₁ h₂, exact norm_integral_le_lintegral_norm _ } end /-- Lebesgue dominated convergence theorem for filters with a countable basis -/ lemma tendsto_integral_filter_of_dominated_convergence {ι} {l : filter ι} [l.is_countably_generated] {F : ι → α → E} {f : α → E} (bound : α → ℝ) (hF_meas : ∀ᶠ n in l, ae_measurable (F n) μ) (h_bound : ∀ᶠ n in l, ∀ᵐ a ∂μ, ∥F n a∥ ≤ bound a) (bound_integrable : integrable bound μ) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) l (𝓝 (f a))) : tendsto (λn, ∫ a, F n a ∂μ) l (𝓝 $ ∫ a, f a ∂μ) := begin rw tendsto_iff_seq_tendsto, intros x xl, have hxl, { rw tendsto_at_top' at xl, exact xl }, have h := inter_mem hF_meas h_bound, replace h := hxl _ h, rcases h with ⟨k, h⟩, rw ← tendsto_add_at_top_iff_nat k, refine tendsto_integral_of_dominated_convergence bound _ bound_integrable _ _, { intro, refine (h _ _).1, apply self_le_add_left }, { intro, refine (h _ _).2, apply self_le_add_left }, { filter_upwards [h_lim], assume a h_lim, apply @tendsto.comp _ _ _ (λn, x (n + k)) (λn, F n a), { assumption }, rw tendsto_add_at_top_iff_nat, assumption } end variables {X : Type*} [topological_space X] [first_countable_topology X] lemma continuous_at_of_dominated {F : X → α → E} {x₀ : X} {bound : α → ℝ} (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_measurable (F x) μ) (h_bound : ∀ᶠ x in 𝓝 x₀, ∀ᵐ a ∂μ, ∥F x a∥ ≤ bound a) (bound_integrable : integrable bound μ) (h_cont : ∀ᵐ a ∂μ, continuous_at (λ x, F x a) x₀) : continuous_at (λ x, ∫ a, F x a ∂μ) x₀ := tendsto_integral_filter_of_dominated_convergence bound ‹_› ‹_› ‹_› ‹_› lemma continuous_of_dominated {F : X → α → E} {bound : α → ℝ} (hF_meas : ∀ x, ae_measurable (F x) μ) (h_bound : ∀ x, ∀ᵐ a ∂μ, ∥F x a∥ ≤ bound a) (bound_integrable : integrable bound μ) (h_cont : ∀ᵐ a ∂μ, continuous (λ x, F x a)) : continuous (λ x, ∫ a, F x a ∂μ) := continuous_iff_continuous_at.mpr (λ x₀, continuous_at_of_dominated (eventually_of_forall hF_meas) (eventually_of_forall h_bound) ‹_› $ h_cont.mono $ λ _, continuous.continuous_at) /-- The Bochner integral of a real-valued function `f : α → ℝ` is the difference between the integral of the positive part of `f` and the integral of the negative part of `f`. -/ lemma integral_eq_lintegral_pos_part_sub_lintegral_neg_part {f : α → ℝ} (hf : integrable f μ) : ∫ a, f a ∂μ = ennreal.to_real (∫⁻ a, (ennreal.of_real $ f a) ∂μ) - ennreal.to_real (∫⁻ a, (ennreal.of_real $ - f a) ∂μ) := let f₁ := hf.to_L1 f in -- Go to the `L¹` space have eq₁ : ennreal.to_real (∫⁻ a, (ennreal.of_real $ f a) ∂μ) = ∥Lp.pos_part f₁∥ := begin rw L1.norm_def, congr' 1, apply lintegral_congr_ae, filter_upwards [Lp.coe_fn_pos_part f₁, hf.coe_fn_to_L1], assume a h₁ h₂, rw [h₁, h₂, ennreal.of_real], congr' 1, apply nnreal.eq, simp [real.norm_of_nonneg, le_max_right, real.coe_to_nnreal] end, -- Go to the `L¹` space have eq₂ : ennreal.to_real (∫⁻ a, (ennreal.of_real $ - f a) ∂μ) = ∥Lp.neg_part f₁∥ := begin rw L1.norm_def, congr' 1, apply lintegral_congr_ae, filter_upwards [Lp.coe_fn_neg_part f₁, hf.coe_fn_to_L1], assume a h₁ h₂, rw [h₁, h₂, ennreal.of_real], congr' 1, apply nnreal.eq, simp only [real.norm_of_nonneg, min_le_right, neg_nonneg, real.coe_to_nnreal', subtype.coe_mk], rw [← max_neg_neg, coe_nnnorm, neg_zero, real.norm_of_nonneg (le_max_right (-f a) 0)] end, begin rw [eq₁, eq₂, integral, dif_pos], exact L1.integral_eq_norm_pos_part_sub _ end lemma integral_eq_lintegral_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ] f) (hfm : ae_measurable f μ) : ∫ a, f a ∂μ = ennreal.to_real (∫⁻ a, (ennreal.of_real $ f a) ∂μ) := begin by_cases hfi : integrable f μ, { rw integral_eq_lintegral_pos_part_sub_lintegral_neg_part hfi, have h_min : ∫⁻ a, ennreal.of_real (-f a) ∂μ = 0, { rw lintegral_eq_zero_iff', { refine hf.mono _, simp only [pi.zero_apply], assume a h, simp only [h, neg_nonpos, of_real_eq_zero], }, { exact measurable_of_real.comp_ae_measurable hfm.neg } }, rw [h_min, zero_to_real, _root_.sub_zero] }, { rw integral_undef hfi, simp_rw [integrable, hfm, has_finite_integral_iff_norm, lt_top_iff_ne_top, ne.def, true_and, not_not] at hfi, have : ∫⁻ (a : α), ennreal.of_real (f a) ∂μ = ∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ, { refine lintegral_congr_ae (hf.mono $ assume a h, _), rw [real.norm_eq_abs, abs_of_nonneg h] }, rw [this, hfi], refl } end lemma of_real_integral_norm_eq_lintegral_nnnorm {G} [normed_group G] [measurable_space G] [opens_measurable_space G] {f : α → G} (hf : integrable f μ) : ennreal.of_real ∫ x, ∥f x∥ ∂μ = ∫⁻ x, ∥f x∥₊ ∂μ := begin rw integral_eq_lintegral_of_nonneg_ae _ hf.1.norm, { simp_rw [of_real_norm_eq_coe_nnnorm, ennreal.of_real_to_real (lt_top_iff_ne_top.mp hf.2)], }, { refine ae_of_all _ _, simp, }, end lemma integral_eq_integral_pos_part_sub_integral_neg_part {f : α → ℝ} (hf : integrable f μ) : ∫ a, f a ∂μ = (∫ a, real.to_nnreal (f a) ∂μ) - (∫ a, real.to_nnreal (-f a) ∂μ) := begin rw [← integral_sub hf.real_to_nnreal], { simp }, { exact hf.neg.real_to_nnreal } end lemma integral_nonneg_of_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ] f) : 0 ≤ ∫ a, f a ∂μ := begin by_cases hfm : ae_measurable f μ, { rw integral_eq_lintegral_of_nonneg_ae hf hfm, exact to_real_nonneg }, { rw integral_non_ae_measurable hfm } end lemma lintegral_coe_eq_integral (f : α → ℝ≥0) (hfi : integrable (λ x, (f x : ℝ)) μ) : ∫⁻ a, f a ∂μ = ennreal.of_real ∫ a, f a ∂μ := begin simp_rw [integral_eq_lintegral_of_nonneg_ae (eventually_of_forall (λ x, (f x).coe_nonneg)) hfi.ae_measurable, ← ennreal.coe_nnreal_eq], rw [ennreal.of_real_to_real], rw [← lt_top_iff_ne_top], convert hfi.has_finite_integral, ext1 x, rw [nnreal.nnnorm_eq] end lemma integral_to_real {f : α → ℝ≥0∞} (hfm : ae_measurable f μ) (hf : ∀ᵐ x ∂μ, f x < ∞) : ∫ a, (f a).to_real ∂μ = (∫⁻ a, f a ∂μ).to_real := begin rw [integral_eq_lintegral_of_nonneg_ae _ hfm.ennreal_to_real], { rw lintegral_congr_ae, refine hf.mp (eventually_of_forall _), intros x hx, rw [lt_top_iff_ne_top] at hx, simp [hx] }, { exact (eventually_of_forall $ λ x, ennreal.to_real_nonneg) } end lemma lintegral_coe_le_coe_iff_integral_le {f : α → ℝ≥0} (hfi : integrable (λ x, (f x : ℝ)) μ) {b : ℝ≥0} : ∫⁻ a, f a ∂μ ≤ b ↔ ∫ a, (f a : ℝ) ∂μ ≤ b := by rw [lintegral_coe_eq_integral f hfi, ennreal.of_real, ennreal.coe_le_coe, real.to_nnreal_le_iff_le_coe] lemma integral_coe_le_of_lintegral_coe_le {f : α → ℝ≥0} {b : ℝ≥0} (h : ∫⁻ a, f a ∂μ ≤ b) : ∫ a, (f a : ℝ) ∂μ ≤ b := begin by_cases hf : integrable (λ a, (f a : ℝ)) μ, { exact (lintegral_coe_le_coe_iff_integral_le hf).1 h }, { rw integral_undef hf, exact b.2 } end lemma integral_nonneg {f : α → ℝ} (hf : 0 ≤ f) : 0 ≤ ∫ a, f a ∂μ := integral_nonneg_of_ae $ eventually_of_forall hf lemma integral_nonpos_of_ae {f : α → ℝ} (hf : f ≤ᵐ[μ] 0) : ∫ a, f a ∂μ ≤ 0 := begin have hf : 0 ≤ᵐ[μ] (-f) := hf.mono (assume a h, by rwa [pi.neg_apply, pi.zero_apply, neg_nonneg]), have : 0 ≤ ∫ a, -f a ∂μ := integral_nonneg_of_ae hf, rwa [integral_neg, neg_nonneg] at this, end lemma integral_nonpos {f : α → ℝ} (hf : f ≤ 0) : ∫ a, f a ∂μ ≤ 0 := integral_nonpos_of_ae $ eventually_of_forall hf lemma integral_eq_zero_iff_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ] f) (hfi : integrable f μ) : ∫ x, f x ∂μ = 0 ↔ f =ᵐ[μ] 0 := by simp_rw [integral_eq_lintegral_of_nonneg_ae hf hfi.1, ennreal.to_real_eq_zero_iff, lintegral_eq_zero_iff' (ennreal.measurable_of_real.comp_ae_measurable hfi.1), ← ennreal.not_lt_top, ← has_finite_integral_iff_of_real hf, hfi.2, not_true, or_false, ← hf.le_iff_eq, filter.eventually_eq, filter.eventually_le, (∘), pi.zero_apply, ennreal.of_real_eq_zero] lemma integral_eq_zero_iff_of_nonneg {f : α → ℝ} (hf : 0 ≤ f) (hfi : integrable f μ) : ∫ x, f x ∂μ = 0 ↔ f =ᵐ[μ] 0 := integral_eq_zero_iff_of_nonneg_ae (eventually_of_forall hf) hfi lemma integral_pos_iff_support_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ] f) (hfi : integrable f μ) : (0 < ∫ x, f x ∂μ) ↔ 0 < μ (function.support f) := by simp_rw [(integral_nonneg_of_ae hf).lt_iff_ne, pos_iff_ne_zero, ne.def, @eq_comm ℝ 0, integral_eq_zero_iff_of_nonneg_ae hf hfi, filter.eventually_eq, ae_iff, pi.zero_apply, function.support] lemma integral_pos_iff_support_of_nonneg {f : α → ℝ} (hf : 0 ≤ f) (hfi : integrable f μ) : (0 < ∫ x, f x ∂μ) ↔ 0 < μ (function.support f) := integral_pos_iff_support_of_nonneg_ae (eventually_of_forall hf) hfi section normed_group variables {H : Type*} [normed_group H] [second_countable_topology H] [measurable_space H] [borel_space H] lemma L1.norm_eq_integral_norm (f : α →₁[μ] H) : ∥f∥ = ∫ a, ∥f a∥ ∂μ := begin simp only [snorm, snorm', ennreal.one_to_real, ennreal.rpow_one, Lp.norm_def, if_false, ennreal.one_ne_top, one_ne_zero, _root_.div_one], rw integral_eq_lintegral_of_nonneg_ae (eventually_of_forall (by simp [norm_nonneg])) (continuous_norm.measurable.comp_ae_measurable (Lp.ae_measurable f)), simp [of_real_norm_eq_coe_nnnorm] end lemma L1.norm_of_fun_eq_integral_norm {f : α → H} (hf : integrable f μ) : ∥hf.to_L1 f∥ = ∫ a, ∥f a∥ ∂μ := begin rw L1.norm_eq_integral_norm, refine integral_congr_ae _, apply hf.coe_fn_to_L1.mono, intros a ha, simp [ha] end end normed_group lemma integral_mono_ae {f g : α → ℝ} (hf : integrable f μ) (hg : integrable g μ) (h : f ≤ᵐ[μ] g) : ∫ a, f a ∂μ ≤ ∫ a, g a ∂μ := le_of_sub_nonneg $ integral_sub hg hf ▸ integral_nonneg_of_ae $ h.mono (λ a, sub_nonneg_of_le) @[mono] lemma integral_mono {f g : α → ℝ} (hf : integrable f μ) (hg : integrable g μ) (h : f ≤ g) : ∫ a, f a ∂μ ≤ ∫ a, g a ∂μ := integral_mono_ae hf hg $ eventually_of_forall h lemma integral_mono_of_nonneg {f g : α → ℝ} (hf : 0 ≤ᵐ[μ] f) (hgi : integrable g μ) (h : f ≤ᵐ[μ] g) : ∫ a, f a ∂μ ≤ ∫ a, g a ∂μ := begin by_cases hfm : ae_measurable f μ, { refine integral_mono_ae ⟨hfm, _⟩ hgi h, refine (hgi.has_finite_integral.mono $ h.mp $ hf.mono $ λ x hf hfg, _), simpa [real.norm_eq_abs, abs_of_nonneg hf, abs_of_nonneg (le_trans hf hfg)] }, { rw [integral_non_ae_measurable hfm], exact integral_nonneg_of_ae (hf.trans h) } end lemma norm_integral_le_integral_norm (f : α → E) : ∥(∫ a, f a ∂μ)∥ ≤ ∫ a, ∥f a∥ ∂μ := have le_ae : ∀ᵐ a ∂μ, 0 ≤ ∥f a∥ := eventually_of_forall (λa, norm_nonneg _), classical.by_cases ( λh : ae_measurable f μ, calc ∥∫ a, f a ∂μ∥ ≤ ennreal.to_real (∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ) : norm_integral_le_lintegral_norm _ ... = ∫ a, ∥f a∥ ∂μ : (integral_eq_lintegral_of_nonneg_ae le_ae $ ae_measurable.norm h).symm ) ( λh : ¬ae_measurable f μ, begin rw [integral_non_ae_measurable h, norm_zero], exact integral_nonneg_of_ae le_ae end ) lemma norm_integral_le_of_norm_le {f : α → E} {g : α → ℝ} (hg : integrable g μ) (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ g x) : ∥∫ x, f x ∂μ∥ ≤ ∫ x, g x ∂μ := calc ∥∫ x, f x ∂μ∥ ≤ ∫ x, ∥f x∥ ∂μ : norm_integral_le_integral_norm f ... ≤ ∫ x, g x ∂μ : integral_mono_of_nonneg (eventually_of_forall $ λ x, norm_nonneg _) hg h lemma integral_finset_sum {ι} (s : finset ι) {f : ι → α → E} (hf : ∀ i, integrable (f i) μ) : ∫ a, ∑ i in s, f i a ∂μ = ∑ i in s, ∫ a, f i a ∂μ := begin refine finset.induction_on s _ _, { simp only [integral_zero, finset.sum_empty] }, { assume i s his ih, simp only [his, finset.sum_insert, not_false_iff], rw [integral_add (hf _) (integrable_finset_sum s hf), ih] } end lemma simple_func.integral_eq_integral (f : α →ₛ E) (hfi : integrable f μ) : f.integral μ = ∫ x, f x ∂μ := begin rw [integral_eq f hfi, ← L1.simple_func.to_Lp_one_eq_to_L1, L1.simple_func.integral_L1_eq_integral, L1.simple_func.integral_eq_integral], exact simple_func.integral_congr hfi (Lp.simple_func.to_simple_func_to_Lp _ _).symm end lemma simple_func.integral_eq_sum (f : α →ₛ E) (hfi : integrable f μ) : ∫ x, f x ∂μ = ∑ x in f.range, (ennreal.to_real (μ (f ⁻¹' {x}))) • x := by { rw [← f.integral_eq_integral hfi, simple_func.integral, ← simple_func.integral_eq], refl, } @[simp] lemma integral_const (c : E) : ∫ x : α, c ∂μ = (μ univ).to_real • c := begin cases (@le_top _ _ (μ univ)).lt_or_eq with hμ hμ, { haveI : is_finite_measure μ := ⟨hμ⟩, calc ∫ x : α, c ∂μ = (simple_func.const α c).integral μ : ((simple_func.const α c).integral_eq_integral (integrable_const _)).symm ... = _ : simple_func.integral_const _ _ }, { by_cases hc : c = 0, { simp [hc, integral_zero] }, { have : ¬integrable (λ x : α, c) μ, { simp only [integrable_const_iff, not_or_distrib], exact ⟨hc, hμ.not_lt⟩ }, simp [integral_undef, *] } } end lemma norm_integral_le_of_norm_le_const [is_finite_measure μ] {f : α → E} {C : ℝ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ C) : ∥∫ x, f x ∂μ∥ ≤ C * (μ univ).to_real := calc ∥∫ x, f x ∂μ∥ ≤ ∫ x, C ∂μ : norm_integral_le_of_norm_le (integrable_const C) h ... = C * (μ univ).to_real : by rw [integral_const, smul_eq_mul, mul_comm] lemma tendsto_integral_approx_on_univ_of_measurable {f : α → E} (fmeas : measurable f) (hf : integrable f μ) : tendsto (λ n, (simple_func.approx_on f fmeas univ 0 trivial n).integral μ) at_top (𝓝 $ ∫ x, f x ∂μ) := begin have : tendsto (λ n, ∫ x, simple_func.approx_on f fmeas univ 0 trivial n x ∂μ) at_top (𝓝 $ ∫ x, f x ∂μ) := tendsto_integral_of_L1 _ hf (eventually_of_forall $ simple_func.integrable_approx_on_univ fmeas hf) (simple_func.tendsto_approx_on_univ_L1_nnnorm fmeas hf), simpa only [simple_func.integral_eq_integral, simple_func.integrable_approx_on_univ fmeas hf] end variable {ν : measure α} private lemma integral_add_measure_of_measurable {f : α → E} (fmeas : measurable f) (hμ : integrable f μ) (hν : integrable f ν) : ∫ x, f x ∂(μ + ν) = ∫ x, f x ∂μ + ∫ x, f x ∂ν := begin have hfi := hμ.add_measure hν, refine tendsto_nhds_unique (tendsto_integral_approx_on_univ_of_measurable fmeas hfi) _, simpa only [simple_func.integral_add_measure _ (simple_func.integrable_approx_on_univ fmeas hfi _)] using (tendsto_integral_approx_on_univ_of_measurable fmeas hμ).add (tendsto_integral_approx_on_univ_of_measurable fmeas hν) end lemma integral_add_measure {f : α → E} (hμ : integrable f μ) (hν : integrable f ν) : ∫ x, f x ∂(μ + ν) = ∫ x, f x ∂μ + ∫ x, f x ∂ν := begin have h : ae_measurable f (μ + ν) := hμ.ae_measurable.add_measure hν.ae_measurable, let g := h.mk f, have A : f =ᵐ[μ + ν] g := h.ae_eq_mk, have B : f =ᵐ[μ] g := A.filter_mono (ae_mono (measure.le_add_right (le_refl μ))), have C : f =ᵐ[ν] g := A.filter_mono (ae_mono (measure.le_add_left (le_refl ν))), calc ∫ x, f x ∂(μ + ν) = ∫ x, g x ∂(μ + ν) : integral_congr_ae A ... = ∫ x, g x ∂μ + ∫ x, g x ∂ν : integral_add_measure_of_measurable h.measurable_mk ((integrable_congr B).1 hμ) ((integrable_congr C).1 hν) ... = ∫ x, f x ∂μ + ∫ x, f x ∂ν : by { congr' 1, { exact integral_congr_ae B.symm }, { exact integral_congr_ae C.symm } } end @[simp] lemma integral_zero_measure {m : measurable_space α} (f : α → E) : ∫ x, f x ∂(0 : measure α) = 0 := norm_le_zero_iff.1 $ le_trans (norm_integral_le_lintegral_norm f) $ by simp private lemma integral_smul_measure_aux {f : α → E} {c : ℝ≥0∞} (h0 : c ≠ 0) (hc : c ≠ ∞) (fmeas : measurable f) (hfi : integrable f μ) : ∫ x, f x ∂(c • μ) = c.to_real • ∫ x, f x ∂μ := begin refine tendsto_nhds_unique _ (tendsto_const_nhds.smul (tendsto_integral_approx_on_univ_of_measurable fmeas hfi)), convert tendsto_integral_approx_on_univ_of_measurable fmeas (hfi.smul_measure hc), simp only [simple_func.integral_eq, measure.smul_apply, finset.smul_sum, smul_smul, ennreal.to_real_mul] end @[simp] lemma integral_smul_measure (f : α → E) (c : ℝ≥0∞) : ∫ x, f x ∂(c • μ) = c.to_real • ∫ x, f x ∂μ := begin -- First we consider “degenerate” cases: -- `c = 0` rcases eq_or_ne c 0 with rfl|h0, { simp }, -- `f` is not almost everywhere measurable by_cases hfm : ae_measurable f μ, swap, { have : ¬ (ae_measurable f (c • μ)), by simpa [h0] using hfm, simp [integral_non_ae_measurable, hfm, this] }, -- `c = ∞` rcases eq_or_ne c ∞ with rfl|hc, { rw [ennreal.top_to_real, zero_smul], by_cases hf : f =ᵐ[μ] 0, { have : f =ᵐ[∞ • μ] 0 := ae_smul_measure hf ∞, exact integral_eq_zero_of_ae this }, { apply integral_undef, rw [integrable, has_finite_integral, iff_true_intro (hfm.smul_measure ∞), true_and, lintegral_smul_measure, top_mul, if_neg], { apply lt_irrefl }, { rw [lintegral_eq_zero_iff' hfm.ennnorm], refine λ h, hf (h.mono $ λ x, _), simp } } }, -- `f` is not integrable and `0 < c < ∞` by_cases hfi : integrable f μ, swap, { rw [integral_undef hfi, smul_zero], refine integral_undef (mt (λ h, _) hfi), convert h.smul_measure (ennreal.inv_ne_top.2 h0), rw [smul_smul, ennreal.inv_mul_cancel h0 hc, one_smul] }, -- Main case: `0 < c < ∞`, `f` is almost everywhere measurable and integrable let g := hfm.mk f, calc ∫ x, f x ∂(c • μ) = ∫ x, g x ∂(c • μ) : integral_congr_ae $ ae_smul_measure hfm.ae_eq_mk c ... = c.to_real • ∫ x, g x ∂μ : integral_smul_measure_aux h0 hc hfm.measurable_mk $ hfi.congr hfm.ae_eq_mk ... = c.to_real • ∫ x, f x ∂μ : by { congr' 1, exact integral_congr_ae (hfm.ae_eq_mk.symm) } end lemma integral_map_of_measurable {β} [measurable_space β] {φ : α → β} (hφ : measurable φ) {f : β → E} (hfm : measurable f) : ∫ y, f y ∂(measure.map φ μ) = ∫ x, f (φ x) ∂μ := begin by_cases hfi : integrable f (measure.map φ μ), swap, { rw [integral_undef hfi, integral_undef], rwa [← integrable_map_measure hfm.ae_measurable hφ] }, refine tendsto_nhds_unique (tendsto_integral_approx_on_univ_of_measurable hfm hfi) _, convert tendsto_integral_approx_on_univ_of_measurable (hfm.comp hφ) ((integrable_map_measure hfm.ae_measurable hφ).1 hfi), ext1 i, simp only [simple_func.approx_on_comp, simple_func.integral_eq, measure.map_apply, hφ, simple_func.measurable_set_preimage, ← preimage_comp, simple_func.coe_comp], refine (finset.sum_subset (simple_func.range_comp_subset_range _ hφ) (λ y _ hy, _)).symm, rw [simple_func.mem_range, ← set.preimage_singleton_eq_empty, simple_func.coe_comp] at hy, simp [hy] end lemma integral_map {β} [measurable_space β] {φ : α → β} (hφ : measurable φ) {f : β → E} (hfm : ae_measurable f (measure.map φ μ)) : ∫ y, f y ∂(measure.map φ μ) = ∫ x, f (φ x) ∂μ := let g := hfm.mk f in calc ∫ y, f y ∂(measure.map φ μ) = ∫ y, g y ∂(measure.map φ μ) : integral_congr_ae hfm.ae_eq_mk ... = ∫ x, g (φ x) ∂μ : integral_map_of_measurable hφ hfm.measurable_mk ... = ∫ x, f (φ x) ∂μ : integral_congr_ae $ ae_eq_comp hφ (hfm.ae_eq_mk).symm lemma integral_map_of_closed_embedding {β} [topological_space α] [borel_space α] [topological_space β] [measurable_space β] [borel_space β] {φ : α → β} (hφ : closed_embedding φ) (f : β → E) : ∫ y, f y ∂(measure.map φ μ) = ∫ x, f (φ x) ∂μ := begin by_cases hfm : ae_measurable f (measure.map φ μ), { exact integral_map hφ.continuous.measurable hfm }, { rw [integral_non_ae_measurable hfm, integral_non_ae_measurable], rwa ae_measurable_comp_right_iff_of_closed_embedding hφ } end lemma integral_map_equiv {β} [measurable_space β] (e : α ≃ᵐ β) (f : β → E) : ∫ y, f y ∂(measure.map e μ) = ∫ x, f (e x) ∂μ := begin by_cases hfm : ae_measurable f (measure.map e μ), { exact integral_map e.measurable hfm }, { rw [integral_non_ae_measurable hfm, integral_non_ae_measurable], rwa ← ae_measurable_map_equiv_iff } end @[simp] lemma integral_dirac' [measurable_space α] (f : α → E) (a : α) (hfm : measurable f) : ∫ x, f x ∂(measure.dirac a) = f a := calc ∫ x, f x ∂(measure.dirac a) = ∫ x, f a ∂(measure.dirac a) : integral_congr_ae $ ae_eq_dirac' hfm ... = f a : by simp [measure.dirac_apply_of_mem] @[simp] lemma integral_dirac [measurable_space α] [measurable_singleton_class α] (f : α → E) (a : α) : ∫ x, f x ∂(measure.dirac a) = f a := calc ∫ x, f x ∂(measure.dirac a) = ∫ x, f a ∂(measure.dirac a) : integral_congr_ae $ ae_eq_dirac f ... = f a : by simp [measure.dirac_apply_of_mem] end properties section group variables {G : Type*} [measurable_space G] [topological_space G] [group G] [has_continuous_mul G] [borel_space G] variables {μ : measure G} open measure /-- Translating a function by left-multiplication does not change its integral with respect to a left-invariant measure. -/ @[to_additive] lemma integral_mul_left_eq_self (hμ : is_mul_left_invariant μ) {f : G → E} (g : G) : ∫ x, f (g * x) ∂μ = ∫ x, f x ∂μ := begin have hgμ : measure.map (has_mul.mul g) μ = μ, { rw ← map_mul_left_eq_self at hμ, exact hμ g }, have h_mul : closed_embedding (λ x, g * x) := (homeomorph.mul_left g).closed_embedding, rw [← integral_map_of_closed_embedding h_mul, hgμ], apply_instance, end /-- Translating a function by right-multiplication does not change its integral with respect to a right-invariant measure. -/ @[to_additive] lemma integral_mul_right_eq_self (hμ : is_mul_right_invariant μ) {f : G → E} (g : G) : ∫ x, f (x * g) ∂μ = ∫ x, f x ∂μ := begin have hgμ : measure.map (λ x, x * g) μ = μ, { rw ← map_mul_right_eq_self at hμ, exact hμ g }, have h_mul : closed_embedding (λ x, x * g) := (homeomorph.mul_right g).closed_embedding, rw [← integral_map_of_closed_embedding h_mul, hgμ], apply_instance, end /-- If some left-translate of a function negates it, then the integral of the function with respect to a left-invariant measure is 0. -/ @[to_additive] lemma integral_zero_of_mul_left_eq_neg (hμ : is_mul_left_invariant μ) {f : G → E} {g : G} (hf' : ∀ x, f (g * x) = - f x) : ∫ x, f x ∂μ = 0 := begin refine eq_zero_of_eq_neg ℝ (eq.symm _), have : ∫ x, f (g * x) ∂μ = ∫ x, - f x ∂μ, { congr, ext x, exact hf' x }, convert integral_mul_left_eq_self hμ g using 1, rw [this, integral_neg] end /-- If some right-translate of a function negates it, then the integral of the function with respect to a right-invariant measure is 0. -/ @[to_additive] lemma integral_zero_of_mul_right_eq_neg (hμ : is_mul_right_invariant μ) {f : G → E} {g : G} (hf' : ∀ x, f (x * g) = - f x) : ∫ x, f x ∂μ = 0 := begin refine eq_zero_of_eq_neg ℝ (eq.symm _), have : ∫ x, f (x * g) ∂μ = ∫ x, - f x ∂μ, { congr, ext x, exact hf' x }, convert integral_mul_right_eq_self hμ g using 1, rw [this, integral_neg] end end group mk_simp_attribute integral_simps "Simp set for integral rules." attribute [integral_simps] integral_neg integral_smul L1.integral_add L1.integral_sub L1.integral_smul L1.integral_neg attribute [irreducible] integral L1.integral section integral_trim variables {H β γ : Type*} [normed_group H] [measurable_space H] {m m0 : measurable_space β} {μ : measure β} /-- Simple function seen as simple function of a larger `measurable_space`. -/ def simple_func.to_larger_space (hm : m ≤ m0) (f : @simple_func β m γ) : simple_func β γ := ⟨@simple_func.to_fun β m γ f, λ x, hm _ (@simple_func.measurable_set_fiber β γ m f x), @simple_func.finite_range β γ m f⟩ lemma simple_func.coe_to_larger_space_eq (hm : m ≤ m0) (f : @simple_func β m γ) : ⇑(f.to_larger_space hm) = f := rfl lemma integral_simple_func_larger_space (hm : m ≤ m0) (f : @simple_func β m F) (hf_int : integrable f μ) : ∫ x, f x ∂μ = ∑ x in (@simple_func.range β F m f), (ennreal.to_real (μ (f ⁻¹' {x}))) • x := begin simp_rw ← f.coe_to_larger_space_eq hm, have hf_int : integrable (f.to_larger_space hm) μ, by rwa simple_func.coe_to_larger_space_eq, rw simple_func.integral_eq_sum _ hf_int, congr, end lemma integral_trim_simple_func (hm : m ≤ m0) (f : @simple_func β m F) (hf_int : integrable f μ) : ∫ x, f x ∂μ = ∫ x, f x ∂(μ.trim hm) := begin have hf : @measurable _ _ m _ f, from @simple_func.measurable β F m _ f, have hf_int_m := hf_int.trim hm hf, rw [integral_simple_func_larger_space le_rfl f hf_int_m, integral_simple_func_larger_space hm f hf_int], congr, ext1 x, congr, exact (trim_measurable_set_eq hm (@simple_func.measurable_set_fiber β F m f x)).symm, end lemma integral_trim (hm : m ≤ m0) {f : β → F} (hf : @measurable β F m _ f) : ∫ x, f x ∂μ = ∫ x, f x ∂(μ.trim hm) := begin by_cases hf_int : integrable f μ, swap, { have hf_int_m : ¬ integrable f (μ.trim hm), from λ hf_int_m, hf_int (integrable_of_integrable_trim hm hf_int_m), rw [integral_undef hf_int, integral_undef hf_int_m], }, let f_seq := @simple_func.approx_on F β _ _ _ m _ hf set.univ 0 (set.mem_univ 0) _, have hf_seq_meas : ∀ n, @measurable _ _ m _ (f_seq n), from λ n, @simple_func.measurable β F m _ (f_seq n), have hf_seq_int : ∀ n, integrable (f_seq n) μ, from simple_func.integrable_approx_on_univ (hf.mono hm le_rfl) hf_int, have hf_seq_int_m : ∀ n, integrable (f_seq n) (μ.trim hm), from λ n, (hf_seq_int n).trim hm (hf_seq_meas n) , have hf_seq_eq : ∀ n, ∫ x, f_seq n x ∂μ = ∫ x, f_seq n x ∂(μ.trim hm), from λ n, integral_trim_simple_func hm (f_seq n) (hf_seq_int n), have h_lim_1 : at_top.tendsto (λ n, ∫ x, f_seq n x ∂μ) (𝓝 (∫ x, f x ∂μ)), { refine tendsto_integral_of_L1 f hf_int (eventually_of_forall hf_seq_int) _, exact simple_func.tendsto_approx_on_univ_L1_nnnorm (hf.mono hm le_rfl) hf_int, }, have h_lim_2 : at_top.tendsto (λ n, ∫ x, f_seq n x ∂μ) (𝓝 (∫ x, f x ∂(μ.trim hm))), { simp_rw hf_seq_eq, refine @tendsto_integral_of_L1 β F _ _ _ _ _ _ m (μ.trim hm) _ f (hf_int.trim hm hf) _ _ (eventually_of_forall hf_seq_int_m) _, exact @simple_func.tendsto_approx_on_univ_L1_nnnorm β F m _ _ _ _ f _ hf (hf_int.trim hm hf), }, exact tendsto_nhds_unique h_lim_1 h_lim_2, end lemma integral_trim_ae (hm : m ≤ m0) {f : β → F} (hf : ae_measurable f (μ.trim hm)) : ∫ x, f x ∂μ = ∫ x, f x ∂(μ.trim hm) := begin rw [integral_congr_ae (ae_eq_of_ae_eq_trim hf.ae_eq_mk), integral_congr_ae hf.ae_eq_mk], exact integral_trim hm hf.measurable_mk, end lemma ae_eq_trim_of_measurable [measurable_space γ] [add_group γ] [measurable_singleton_class γ] [has_measurable_sub₂ γ] (hm : m ≤ m0) {f g : β → γ} (hf : @measurable _ _ m _ f) (hg : @measurable _ _ m _ g) (hfg : f =ᵐ[μ] g) : f =ᵐ[μ.trim hm] g := begin rwa [eventually_eq, ae_iff, trim_measurable_set_eq hm _], exact (@measurable_set.compl β _ m (@measurable_set_eq_fun β m γ _ _ _ _ _ _ hf hg)), end lemma ae_eq_trim_iff [measurable_space γ] [add_group γ] [measurable_singleton_class γ] [has_measurable_sub₂ γ] (hm : m ≤ m0) {f g : β → γ} (hf : @measurable _ _ m _ f) (hg : @measurable _ _ m _ g) : f =ᵐ[μ.trim hm] g ↔ f =ᵐ[μ] g := ⟨ae_eq_of_ae_eq_trim, ae_eq_trim_of_measurable hm hf hg⟩ end integral_trim end measure_theory
c99feceb71dab765c791615bea1f80802900c9b8
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/model_theory/basic.lean
2c3df278de426b3ae386813d459ee837baf4e6c9
[ "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
29,882
lean
/- Copyright (c) 2021 Aaron Anderson, Jesse Michael Han, Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Jesse Michael Han, Floris van Doorn -/ import category_theory.concrete_category.bundled import data.fin.tuple.basic import data.fin.vec_notation import logic.encodable.basic import logic.small import set_theory.cardinal.basic /-! # Basics on First-Order Structures This file defines first-order languages and structures in the style of the [Flypitch project](https://flypitch.github.io/), as well as several important maps between structures. ## Main Definitions * A `first_order.language` defines a language as a pair of functions from the natural numbers to `Type l`. One sends `n` to the type of `n`-ary functions, and the other sends `n` to the type of `n`-ary relations. * A `first_order.language.Structure` interprets the symbols of a given `first_order.language` in the context of a given type. * A `first_order.language.hom`, denoted `M →[L] N`, is a map from the `L`-structure `M` to the `L`-structure `N` that commutes with the interpretations of functions, and which preserves the interpretations of relations (although only in the forward direction). * A `first_order.language.embedding`, denoted `M ↪[L] N`, is an embedding from the `L`-structure `M` to the `L`-structure `N` that commutes with the interpretations of functions, and which preserves the interpretations of relations in both directions. * A `first_order.language.elementary_embedding`, denoted `M ↪ₑ[L] N`, is an embedding from the `L`-structure `M` to the `L`-structure `N` that commutes with the realizations of all formulas. * A `first_order.language.equiv`, denoted `M ≃[L] N`, is an equivalence from the `L`-structure `M` to the `L`-structure `N` that commutes with the interpretations of functions, and which preserves the interpretations of relations in both directions. ## References For the Flypitch project: - [J. Han, F. van Doorn, *A formal proof of the independence of the continuum hypothesis*] [flypitch_cpp] - [J. Han, F. van Doorn, *A formalization of forcing and the unprovability of the continuum hypothesis*][flypitch_itp] -/ universes u v u' v' w w' open_locale cardinal open cardinal namespace first_order /-! ### Languages and Structures -/ /-- A first-order language consists of a type of functions of every natural-number arity and a type of relations of every natural-number arity. -/ @[nolint check_univs] -- intended to be used with explicit universe parameters structure language := (functions : ℕ → Type u) (relations : ℕ → Type v) /-- Used to define `first_order.language₂`. -/ @[simp] def sequence₂ (a₀ a₁ a₂ : Type u) : ℕ → Type u | 0 := a₀ | 1 := a₁ | 2 := a₂ | _ := pempty namespace sequence₂ variables (a₀ a₁ a₂ : Type u) instance inhabited₀ [h : inhabited a₀] : inhabited (sequence₂ a₀ a₁ a₂ 0) := h instance inhabited₁ [h : inhabited a₁] : inhabited (sequence₂ a₀ a₁ a₂ 1) := h instance inhabited₂ [h : inhabited a₂] : inhabited (sequence₂ a₀ a₁ a₂ 2) := h instance {n : ℕ} : is_empty (sequence₂ a₀ a₁ a₂ (n + 3)) := pempty.is_empty @[simp] lemma lift_mk {i : ℕ} : cardinal.lift (# (sequence₂ a₀ a₁ a₂ i)) = # (sequence₂ (ulift a₀) (ulift a₁) (ulift a₂) i) := begin rcases i with (_ | _ | _ | i); simp only [sequence₂, mk_ulift, mk_fintype, fintype.card_of_is_empty, nat.cast_zero, lift_zero], end @[simp] lemma sum_card : cardinal.sum (λ i, # (sequence₂ a₀ a₁ a₂ i)) = # a₀ + # a₁ + # a₂ := begin rw [sum_nat_eq_add_sum_succ, sum_nat_eq_add_sum_succ, sum_nat_eq_add_sum_succ], simp [add_assoc], end end sequence₂ namespace language /-- A constructor for languages with only constants, unary and binary functions, and unary and binary relations. -/ @[simps] protected def mk₂ (c f₁ f₂ : Type u) (r₁ r₂ : Type v) : language := ⟨sequence₂ c f₁ f₂, sequence₂ pempty r₁ r₂⟩ /-- The empty language has no symbols. -/ protected def empty : language := ⟨λ _, empty, λ _, empty⟩ instance : inhabited language := ⟨language.empty⟩ /-- The sum of two languages consists of the disjoint union of their symbols. -/ protected def sum (L : language.{u v}) (L' : language.{u' v'}) : language := ⟨λn, L.functions n ⊕ L'.functions n, λ n, L.relations n ⊕ L'.relations n⟩ variable (L : language.{u v}) /-- The type of constants in a given language. -/ @[nolint has_nonempty_instance] protected def «constants» := L.functions 0 @[simp] lemma constants_mk₂ (c f₁ f₂ : Type u) (r₁ r₂ : Type v) : (language.mk₂ c f₁ f₂ r₁ r₂).constants = c := rfl /-- The type of symbols in a given language. -/ @[nolint has_nonempty_instance] def symbols := (Σl, L.functions l) ⊕ (Σl, L.relations l) /-- The cardinality of a language is the cardinality of its type of symbols. -/ def card : cardinal := # L.symbols /-- A language is countable when it has countably many symbols. -/ class countable : Prop := (card_le_aleph_0' : L.card ≤ ℵ₀) lemma card_le_aleph_0 [L.countable] : L.card ≤ ℵ₀ := countable.card_le_aleph_0' /-- A language is relational when it has no function symbols. -/ class is_relational : Prop := (empty_functions : ∀ n, is_empty (L.functions n)) /-- A language is algebraic when it has no relation symbols. -/ class is_algebraic : Prop := (empty_relations : ∀ n, is_empty (L.relations n)) /-- A language is countable when it has countably many symbols. -/ class countable_functions : Prop := (card_functions_le_aleph_0' : # (Σ l, L.functions l) ≤ ℵ₀) lemma card_functions_le_aleph_0 [L.countable_functions] : #(Σ l, L.functions l) ≤ ℵ₀ := countable_functions.card_functions_le_aleph_0' variables {L} {L' : language.{u' v'}} lemma card_eq_card_functions_add_card_relations : L.card = cardinal.sum (λ l, (cardinal.lift.{v} (#(L.functions l)))) + cardinal.sum (λ l, cardinal.lift.{u} (#(L.relations l))) := by simp [card, symbols] instance [L.is_relational] {n : ℕ} : is_empty (L.functions n) := is_relational.empty_functions n instance [L.is_algebraic] {n : ℕ} : is_empty (L.relations n) := is_algebraic.empty_relations n instance is_relational_of_empty_functions {symb : ℕ → Type*} : is_relational ⟨λ _, empty, symb⟩ := ⟨λ _, empty.is_empty⟩ instance is_algebraic_of_empty_relations {symb : ℕ → Type*} : is_algebraic ⟨symb, λ _, empty⟩ := ⟨λ _, empty.is_empty⟩ instance is_relational_empty : is_relational language.empty := language.is_relational_of_empty_functions instance is_algebraic_empty : is_algebraic language.empty := language.is_algebraic_of_empty_relations instance is_relational_sum [L.is_relational] [L'.is_relational] : is_relational (L.sum L') := ⟨λ n, sum.is_empty⟩ instance is_algebraic_sum [L.is_algebraic] [L'.is_algebraic] : is_algebraic (L.sum L') := ⟨λ n, sum.is_empty⟩ instance is_relational_mk₂ {c f₁ f₂ : Type u} {r₁ r₂ : Type v} [h0 : is_empty c] [h1 : is_empty f₁] [h2 : is_empty f₂] : is_relational (language.mk₂ c f₁ f₂ r₁ r₂) := ⟨λ n, nat.cases_on n h0 (λ n, nat.cases_on n h1 (λ n, nat.cases_on n h2 (λ _, pempty.is_empty)))⟩ instance is_algebraic_mk₂ {c f₁ f₂ : Type u} {r₁ r₂ : Type v} [h1 : is_empty r₁] [h2 : is_empty r₂] : is_algebraic (language.mk₂ c f₁ f₂ r₁ r₂) := ⟨λ n, nat.cases_on n pempty.is_empty (λ n, nat.cases_on n h1 (λ n, nat.cases_on n h2 (λ _, pempty.is_empty)))⟩ instance subsingleton_mk₂_functions {c f₁ f₂ : Type u} {r₁ r₂ : Type v} [h0 : subsingleton c] [h1 : subsingleton f₁] [h2 : subsingleton f₂] {n : ℕ} : subsingleton ((language.mk₂ c f₁ f₂ r₁ r₂).functions n) := nat.cases_on n h0 (λ n, nat.cases_on n h1 (λ n, nat.cases_on n h2 (λ n, ⟨λ x, pempty.elim x⟩))) instance subsingleton_mk₂_relations {c f₁ f₂ : Type u} {r₁ r₂ : Type v} [h1 : subsingleton r₁] [h2 : subsingleton r₂] {n : ℕ} : subsingleton ((language.mk₂ c f₁ f₂ r₁ r₂).relations n) := nat.cases_on n ⟨λ x, pempty.elim x⟩ (λ n, nat.cases_on n h1 (λ n, nat.cases_on n h2 (λ n, ⟨λ x, pempty.elim x⟩))) lemma encodable.countable [h : encodable L.symbols] : L.countable := ⟨cardinal.encodable_iff.1 ⟨h⟩⟩ @[simp] lemma empty_card : language.empty.card = 0 := by simp [card_eq_card_functions_add_card_relations] instance countable_empty : language.empty.countable := ⟨by simp⟩ @[priority 100] instance countable.countable_functions [L.countable] : L.countable_functions := ⟨begin refine lift_le_aleph_0.1 (trans _ L.card_le_aleph_0), rw [card, symbols, mk_sum], exact le_self_add end⟩ lemma encodable.countable_functions [h : encodable (Σl, L.functions l)] : L.countable_functions := ⟨cardinal.encodable_iff.1 ⟨h⟩⟩ @[priority 100] instance is_relational.countable_functions [L.is_relational] : L.countable_functions := encodable.countable_functions @[simp] lemma card_functions_sum (i : ℕ) : #((L.sum L').functions i) = (#(L.functions i)).lift + cardinal.lift.{u} (#(L'.functions i)) := by simp [language.sum] @[simp] lemma card_relations_sum (i : ℕ) : #((L.sum L').relations i) = (#(L.relations i)).lift + cardinal.lift.{v} (#(L'.relations i)) := by simp [language.sum] @[simp] lemma card_sum : (L.sum L').card = cardinal.lift.{max u' v'} L.card + cardinal.lift.{max u v} L'.card := begin simp only [card_eq_card_functions_add_card_relations, card_functions_sum, card_relations_sum, sum_add_distrib', lift_add, lift_sum, lift_lift], rw [add_assoc, ←add_assoc (cardinal.sum (λ i, (# (L'.functions i)).lift)), add_comm (cardinal.sum (λ i, (# (L'.functions i)).lift)), add_assoc, add_assoc] end @[simp] lemma card_mk₂ (c f₁ f₂ : Type u) (r₁ r₂ : Type v) : (language.mk₂ c f₁ f₂ r₁ r₂).card = cardinal.lift.{v} (# c) + cardinal.lift.{v} (# f₁) + cardinal.lift.{v} (# f₂) + cardinal.lift.{u} (# r₁) + cardinal.lift.{u} (# r₂) := by simp [card_eq_card_functions_add_card_relations, add_assoc] variables (L) (M : Type w) /-- A first-order structure on a type `M` consists of interpretations of all the symbols in a given language. Each function of arity `n` is interpreted as a function sending tuples of length `n` (modeled as `(fin n → M)`) to `M`, and a relation of arity `n` is a function from tuples of length `n` to `Prop`. -/ @[ext] class Structure := (fun_map : ∀{n}, L.functions n → (fin n → M) → M) (rel_map : ∀{n}, L.relations n → (fin n → M) → Prop) variables (N : Type w') [L.Structure M] [L.Structure N] open Structure /-- Used for defining `first_order.language.Theory.Model.inhabited`. -/ def trivial_unit_structure : L.Structure unit := ⟨default, default⟩ /-! ### Maps -/ /-- A homomorphism between first-order structures is a function that commutes with the interpretations of functions and maps tuples in one structure where a given relation is true to tuples in the second structure where that relation is still true. -/ structure hom := (to_fun : M → N) (map_fun' : ∀{n} (f : L.functions n) x, to_fun (fun_map f x) = fun_map f (to_fun ∘ x) . obviously) (map_rel' : ∀{n} (r : L.relations n) x, rel_map r x → rel_map r (to_fun ∘ x) . obviously) localized "notation A ` →[`:25 L `] ` B := first_order.language.hom L A B" in first_order /-- An embedding of first-order structures is an embedding that commutes with the interpretations of functions and relations. -/ @[ancestor function.embedding] structure embedding extends M ↪ N := (map_fun' : ∀{n} (f : L.functions n) x, to_fun (fun_map f x) = fun_map f (to_fun ∘ x) . obviously) (map_rel' : ∀{n} (r : L.relations n) x, rel_map r (to_fun ∘ x) ↔ rel_map r x . obviously) localized "notation A ` ↪[`:25 L `] ` B := first_order.language.embedding L A B" in first_order /-- An equivalence of first-order structures is an equivalence that commutes with the interpretations of functions and relations. -/ structure equiv extends M ≃ N := (map_fun' : ∀{n} (f : L.functions n) x, to_fun (fun_map f x) = fun_map f (to_fun ∘ x) . obviously) (map_rel' : ∀{n} (r : L.relations n) x, rel_map r (to_fun ∘ x) ↔ rel_map r x . obviously) localized "notation A ` ≃[`:25 L `] ` B := first_order.language.equiv L A B" in first_order variables {L M N} {P : Type*} [L.Structure P] {Q : Type*} [L.Structure Q] instance : has_coe_t L.constants M := ⟨λ c, fun_map c default⟩ lemma fun_map_eq_coe_constants {c : L.constants} {x : fin 0 → M} : fun_map c x = c := congr rfl (funext fin.elim0) /-- Given a language with a nonempty type of constants, any structure will be nonempty. This cannot be a global instance, because `L` becomes a metavariable. -/ lemma nonempty_of_nonempty_constants [h : nonempty L.constants] : nonempty M := h.map coe /-- The function map for `first_order.language.Structure₂`. -/ def fun_map₂ {c f₁ f₂ : Type u} {r₁ r₂ : Type v} (c' : c → M) (f₁' : f₁ → M → M) (f₂' : f₂ → M → M → M) : ∀{n}, (language.mk₂ c f₁ f₂ r₁ r₂).functions n → (fin n → M) → M | 0 f _ := c' f | 1 f x := f₁' f (x 0) | 2 f x := f₂' f (x 0) (x 1) | (n + 3) f _ := pempty.elim f /-- The relation map for `first_order.language.Structure₂`. -/ def rel_map₂ {c f₁ f₂ : Type u} {r₁ r₂ : Type v} (r₁' : r₁ → set M) (r₂' : r₂ → M → M → Prop) : ∀{n}, (language.mk₂ c f₁ f₂ r₁ r₂).relations n → (fin n → M) → Prop | 0 r _ := pempty.elim r | 1 r x := (x 0) ∈ r₁' r | 2 r x := r₂' r (x 0) (x 1) | (n + 3) r _ := pempty.elim r /-- A structure constructor to match `first_order.language₂`. -/ protected def Structure.mk₂ {c f₁ f₂ : Type u} {r₁ r₂ : Type v} (c' : c → M) (f₁' : f₁ → M → M) (f₂' : f₂ → M → M → M) (r₁' : r₁ → set M) (r₂' : r₂ → M → M → Prop) : (language.mk₂ c f₁ f₂ r₁ r₂).Structure M := ⟨λ _, fun_map₂ c' f₁' f₂', λ _, rel_map₂ r₁' r₂'⟩ namespace Structure variables {c f₁ f₂ : Type u} {r₁ r₂ : Type v} variables {c' : c → M} {f₁' : f₁ → M → M} {f₂' : f₂ → M → M → M} variables {r₁' : r₁ → set M} {r₂' : r₂ → M → M → Prop} @[simp] lemma fun_map_apply₀ (c₀ : c) {x : fin 0 → M} : @Structure.fun_map _ M (Structure.mk₂ c' f₁' f₂' r₁' r₂') 0 c₀ x = c' c₀ := rfl @[simp] lemma fun_map_apply₁ (f : f₁) (x : M) : @Structure.fun_map _ M (Structure.mk₂ c' f₁' f₂' r₁' r₂') 1 f (![x]) = f₁' f x := rfl @[simp] lemma fun_map_apply₂ (f : f₂) (x y : M) : @Structure.fun_map _ M (Structure.mk₂ c' f₁' f₂' r₁' r₂') 2 f (![x,y]) = f₂' f x y := rfl @[simp] lemma rel_map_apply₁ (r : r₁) (x : M) : @Structure.rel_map _ M (Structure.mk₂ c' f₁' f₂' r₁' r₂') 1 r (![x]) = (x ∈ r₁' r) := rfl @[simp] lemma rel_map_apply₂ (r : r₂) (x y : M) : @Structure.rel_map _ M (Structure.mk₂ c' f₁' f₂' r₁' r₂') 2 r (![x,y]) = r₂' r x y := rfl end Structure /-- `hom_class L F M N` states that `F` is a type of `L`-homomorphisms. You should extend this typeclass when you extend `first_order.language.hom`. -/ class hom_class (L : out_param language) (F : Type*) (M N : out_param $ Type*) [fun_like F M (λ _, N)] [L.Structure M] [L.Structure N] := (map_fun : ∀ (φ : F) {n} (f : L.functions n) x, φ (fun_map f x) = fun_map f (φ ∘ x)) (map_rel : ∀ (φ : F) {n} (r : L.relations n) x, rel_map r x → rel_map r (φ ∘ x)) /-- `strong_hom_class L F M N` states that `F` is a type of `L`-homomorphisms which preserve relations in both directions. -/ class strong_hom_class (L : out_param language) (F : Type*) (M N : out_param $ Type*) [fun_like F M (λ _, N)] [L.Structure M] [L.Structure N] := (map_fun : ∀ (φ : F) {n} (f : L.functions n) x, φ (fun_map f x) = fun_map f (φ ∘ x)) (map_rel : ∀ (φ : F) {n} (r : L.relations n) x, rel_map r (φ ∘ x) ↔ rel_map r x) @[priority 100] instance strong_hom_class.hom_class {F M N} [L.Structure M] [L.Structure N] [fun_like F M (λ _, N)] [strong_hom_class L F M N] : hom_class L F M N := { map_fun := strong_hom_class.map_fun, map_rel := λ φ n R x, (strong_hom_class.map_rel φ R x).2 } /-- Not an instance to avoid a loop. -/ def hom_class.strong_hom_class_of_is_algebraic [L.is_algebraic] {F M N} [L.Structure M] [L.Structure N] [fun_like F M (λ _, N)] [hom_class L F M N] : strong_hom_class L F M N := { map_fun := hom_class.map_fun, map_rel := λ φ n R x, (is_algebraic.empty_relations n).elim R } lemma hom_class.map_constants {F M N} [L.Structure M] [L.Structure N] [fun_like F M (λ _, N)] [hom_class L F M N] (φ : F) (c : L.constants) : φ (c) = c := (hom_class.map_fun φ c default).trans (congr rfl (funext default)) namespace hom instance fun_like : fun_like (M →[L] N) M (λ _, N) := { coe := hom.to_fun, coe_injective' := λ f g h, by {cases f, cases g, cases h, refl} } instance hom_class : hom_class L (M →[L] N) M N := { map_fun := map_fun', map_rel := map_rel' } instance [L.is_algebraic] : strong_hom_class L (M →[L] N) M N := hom_class.strong_hom_class_of_is_algebraic instance has_coe_to_fun : has_coe_to_fun (M →[L] N) (λ _, M → N) := fun_like.has_coe_to_fun @[simp] lemma to_fun_eq_coe {f : M →[L] N} : f.to_fun = (f : M → N) := rfl @[ext] lemma ext ⦃f g : M →[L] N⦄ (h : ∀ x, f x = g x) : f = g := fun_like.ext f g h lemma ext_iff {f g : M →[L] N} : f = g ↔ ∀ x, f x = g x := fun_like.ext_iff @[simp] lemma map_fun (φ : M →[L] N) {n : ℕ} (f : L.functions n) (x : fin n → M) : φ (fun_map f x) = fun_map f (φ ∘ x) := hom_class.map_fun φ f x @[simp] lemma map_constants (φ : M →[L] N) (c : L.constants) : φ c = c := hom_class.map_constants φ c @[simp] lemma map_rel (φ : M →[L] N) {n : ℕ} (r : L.relations n) (x : fin n → M) : rel_map r x → rel_map r (φ ∘ x) := hom_class.map_rel φ r x variables (L) (M) /-- The identity map from a structure to itself -/ @[refl] def id : M →[L] M := { to_fun := id } variables {L} {M} instance : inhabited (M →[L] M) := ⟨id L M⟩ @[simp] lemma id_apply (x : M) : id L M x = x := rfl /-- Composition of first-order homomorphisms -/ @[trans] def comp (hnp : N →[L] P) (hmn : M →[L] N) : M →[L] P := { to_fun := hnp ∘ hmn, map_rel' := λ _ _ _ h, by simp [h] } @[simp] lemma comp_apply (g : N →[L] P) (f : M →[L] N) (x : M) : g.comp f x = g (f x) := rfl /-- Composition of first-order homomorphisms is associative. -/ lemma comp_assoc (f : M →[L] N) (g : N →[L] P) (h : P →[L] Q) : (h.comp g).comp f = h.comp (g.comp f) := rfl end hom /-- Any element of a `hom_class` can be realized as a first_order homomorphism. -/ def hom_class.to_hom {F M N} [L.Structure M] [L.Structure N] [fun_like F M (λ _, N)] [hom_class L F M N] : F → (M →[L] N) := λ φ, ⟨φ, λ _, hom_class.map_fun φ, λ _, hom_class.map_rel φ⟩ namespace embedding instance embedding_like : embedding_like (M ↪[L] N) M N := { coe := λ f, f.to_fun, injective' := λ f, f.to_embedding.injective, coe_injective' := λ f g h, begin cases f, cases g, simp only, ext x, exact function.funext_iff.1 h x end } instance strong_hom_class : strong_hom_class L (M ↪[L] N) M N := { map_fun := map_fun', map_rel := map_rel' } instance has_coe_to_fun : has_coe_to_fun (M ↪[L] N) (λ _, M → N) := fun_like.has_coe_to_fun @[simp] lemma map_fun (φ : M ↪[L] N) {n : ℕ} (f : L.functions n) (x : fin n → M) : φ (fun_map f x) = fun_map f (φ ∘ x) := hom_class.map_fun φ f x @[simp] lemma map_constants (φ : M ↪[L] N) (c : L.constants) : φ c = c := hom_class.map_constants φ c @[simp] lemma map_rel (φ : M ↪[L] N) {n : ℕ} (r : L.relations n) (x : fin n → M) : rel_map r (φ ∘ x) ↔ rel_map r x := strong_hom_class.map_rel φ r x /-- A first-order embedding is also a first-order homomorphism. -/ def to_hom : (M ↪[L] N) → M →[L] N := hom_class.to_hom @[simp] lemma coe_to_hom {f : M ↪[L] N} : (f.to_hom : M → N) = f := rfl lemma coe_injective : @function.injective (M ↪[L] N) (M → N) coe_fn | f g h := begin cases f, cases g, simp only, ext x, exact function.funext_iff.1 h x, end @[ext] lemma ext ⦃f g : M ↪[L] N⦄ (h : ∀ x, f x = g x) : f = g := coe_injective (funext h) lemma ext_iff {f g : M ↪[L] N} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ lemma injective (f : M ↪[L] N) : function.injective f := f.to_embedding.injective /-- In an algebraic language, any injective homomorphism is an embedding. -/ @[simps] def of_injective [L.is_algebraic] {f : M →[L] N} (hf : function.injective f) : M ↪[L] N := { inj' := hf, map_rel' := λ n r x, strong_hom_class.map_rel f r x, .. f } @[simp] lemma coe_fn_of_injective [L.is_algebraic] {f : M →[L] N} (hf : function.injective f) : (of_injective hf : M → N) = f := rfl @[simp] lemma of_injective_to_hom [L.is_algebraic] {f : M →[L] N} (hf : function.injective f) : (of_injective hf).to_hom = f := by { ext, simp } variables (L) (M) /-- The identity embedding from a structure to itself -/ @[refl] def refl : M ↪[L] M := { to_embedding := function.embedding.refl M } variables {L} {M} instance : inhabited (M ↪[L] M) := ⟨refl L M⟩ @[simp] lemma refl_apply (x : M) : refl L M x = x := rfl /-- Composition of first-order embeddings -/ @[trans] def comp (hnp : N ↪[L] P) (hmn : M ↪[L] N) : M ↪[L] P := { to_fun := hnp ∘ hmn, inj' := hnp.injective.comp hmn.injective } @[simp] lemma comp_apply (g : N ↪[L] P) (f : M ↪[L] N) (x : M) : g.comp f x = g (f x) := rfl /-- Composition of first-order embeddings is associative. -/ lemma comp_assoc (f : M ↪[L] N) (g : N ↪[L] P) (h : P ↪[L] Q) : (h.comp g).comp f = h.comp (g.comp f) := rfl @[simp] lemma comp_to_hom (hnp : N ↪[L] P) (hmn : M ↪[L] N) : (hnp.comp hmn).to_hom = hnp.to_hom.comp hmn.to_hom := by { ext, simp only [coe_to_hom, comp_apply, hom.comp_apply] } end embedding /-- Any element of an injective `strong_hom_class` can be realized as a first_order embedding. -/ def strong_hom_class.to_embedding {F M N} [L.Structure M] [L.Structure N] [embedding_like F M N] [strong_hom_class L F M N] : F → (M ↪[L] N) := λ φ, ⟨⟨φ, embedding_like.injective φ⟩, λ _, strong_hom_class.map_fun φ, λ _, strong_hom_class.map_rel φ⟩ namespace equiv instance : equiv_like (M ≃[L] N) M N := { coe := λ f, f.to_fun, inv := λ f, f.inv_fun, left_inv := λ f, f.left_inv, right_inv := λ f, f.right_inv, coe_injective' := λ f g h₁ h₂, begin cases f, cases g, simp only, ext x, exact function.funext_iff.1 h₁ x, end, } instance : strong_hom_class L (M ≃[L] N) M N := { map_fun := map_fun', map_rel := map_rel', } /-- The inverse of a first-order equivalence is a first-order equivalence. -/ @[symm] def symm (f : M ≃[L] N) : N ≃[L] M := { map_fun' := λ n f' x, begin simp only [equiv.to_fun_as_coe], rw [equiv.symm_apply_eq], refine eq.trans _ (f.map_fun' f' (f.to_equiv.symm ∘ x)).symm, rw [← function.comp.assoc, equiv.to_fun_as_coe, equiv.self_comp_symm, function.comp.left_id] end, map_rel' := λ n r x, begin simp only [equiv.to_fun_as_coe], refine (f.map_rel' r (f.to_equiv.symm ∘ x)).symm.trans _, rw [← function.comp.assoc, equiv.to_fun_as_coe, equiv.self_comp_symm, function.comp.left_id] end, .. f.to_equiv.symm } instance has_coe_to_fun : has_coe_to_fun (M ≃[L] N) (λ _, M → N) := fun_like.has_coe_to_fun @[simp] lemma apply_symm_apply (f : M ≃[L] N) (a : N) : f (f.symm a) = a := f.to_equiv.apply_symm_apply a @[simp] lemma symm_apply_apply (f : M ≃[L] N) (a : M) : f.symm (f a) = a := f.to_equiv.symm_apply_apply a @[simp] lemma map_fun (φ : M ≃[L] N) {n : ℕ} (f : L.functions n) (x : fin n → M) : φ (fun_map f x) = fun_map f (φ ∘ x) := hom_class.map_fun φ f x @[simp] lemma map_constants (φ : M ≃[L] N) (c : L.constants) : φ c = c := hom_class.map_constants φ c @[simp] lemma map_rel (φ : M ≃[L] N) {n : ℕ} (r : L.relations n) (x : fin n → M) : rel_map r (φ ∘ x) ↔ rel_map r x := strong_hom_class.map_rel φ r x /-- A first-order equivalence is also a first-order embedding. -/ def to_embedding : (M ≃[L] N) → M ↪[L] N := strong_hom_class.to_embedding /-- A first-order equivalence is also a first-order homomorphism. -/ def to_hom : (M ≃[L] N) → M →[L] N := hom_class.to_hom @[simp] lemma to_embedding_to_hom (f : M ≃[L] N) : f.to_embedding.to_hom = f.to_hom := rfl @[simp] lemma coe_to_hom {f : M ≃[L] N} : (f.to_hom : M → N) = (f : M → N) := rfl @[simp] lemma coe_to_embedding (f : M ≃[L] N) : (f.to_embedding : M → N) = (f : M → N) := rfl lemma coe_injective : @function.injective (M ≃[L] N) (M → N) coe_fn := fun_like.coe_injective @[ext] lemma ext ⦃f g : M ≃[L] N⦄ (h : ∀ x, f x = g x) : f = g := coe_injective (funext h) lemma ext_iff {f g : M ≃[L] N} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ lemma bijective (f : M ≃[L] N) : function.bijective f := equiv_like.bijective f lemma injective (f : M ≃[L] N) : function.injective f := equiv_like.injective f lemma surjective (f : M ≃[L] N) : function.surjective f := equiv_like.surjective f variables (L) (M) /-- The identity equivalence from a structure to itself -/ @[refl] def refl : M ≃[L] M := { to_equiv := equiv.refl M } variables {L} {M} instance : inhabited (M ≃[L] M) := ⟨refl L M⟩ @[simp] lemma refl_apply (x : M) : refl L M x = x := rfl /-- Composition of first-order equivalences -/ @[trans] def comp (hnp : N ≃[L] P) (hmn : M ≃[L] N) : M ≃[L] P := { to_fun := hnp ∘ hmn, .. (hmn.to_equiv.trans hnp.to_equiv) } @[simp] lemma comp_apply (g : N ≃[L] P) (f : M ≃[L] N) (x : M) : g.comp f x = g (f x) := rfl /-- Composition of first-order homomorphisms is associative. -/ lemma comp_assoc (f : M ≃[L] N) (g : N ≃[L] P) (h : P ≃[L] Q) : (h.comp g).comp f = h.comp (g.comp f) := rfl end equiv /-- Any element of a bijective `strong_hom_class` can be realized as a first_order isomorphism. -/ def strong_hom_class.to_equiv {F M N} [L.Structure M] [L.Structure N] [equiv_like F M N] [strong_hom_class L F M N] : F → (M ≃[L] N) := λ φ, ⟨⟨φ, equiv_like.inv φ, equiv_like.left_inv φ, equiv_like.right_inv φ⟩, λ _, hom_class.map_fun φ, λ _, strong_hom_class.map_rel φ⟩ section sum_Structure variables (L₁ L₂ : language) (S : Type*) [L₁.Structure S] [L₂.Structure S] instance sum_Structure : (L₁.sum L₂).Structure S := { fun_map := λ n, sum.elim fun_map fun_map, rel_map := λ n, sum.elim rel_map rel_map, } variables {L₁ L₂ S} @[simp] lemma fun_map_sum_inl {n : ℕ} (f : L₁.functions n) : @fun_map (L₁.sum L₂) S _ n (sum.inl f) = fun_map f := rfl @[simp] lemma fun_map_sum_inr {n : ℕ} (f : L₂.functions n) : @fun_map (L₁.sum L₂) S _ n (sum.inr f) = fun_map f := rfl @[simp] lemma rel_map_sum_inl {n : ℕ} (R : L₁.relations n) : @rel_map (L₁.sum L₂) S _ n (sum.inl R) = rel_map R := rfl @[simp] lemma rel_map_sum_inr {n : ℕ} (R : L₂.relations n) : @rel_map (L₁.sum L₂) S _ n (sum.inr R) = rel_map R := rfl end sum_Structure section empty section variables [language.empty.Structure M] [language.empty.Structure N] @[simp] lemma empty.nonempty_embedding_iff : nonempty (M ↪[language.empty] N) ↔ cardinal.lift.{w'} (# M) ≤ cardinal.lift.{w} (# N) := trans ⟨nonempty.map (λ f, f.to_embedding), nonempty.map (λ f, {to_embedding := f})⟩ cardinal.lift_mk_le'.symm @[simp] lemma empty.nonempty_equiv_iff : nonempty (M ≃[language.empty] N) ↔ cardinal.lift.{w'} (# M) = cardinal.lift.{w} (# N) := trans ⟨nonempty.map (λ f, f.to_equiv), nonempty.map (λ f, {to_equiv := f})⟩ cardinal.lift_mk_eq'.symm end instance empty_Structure : language.empty.Structure M := ⟨λ _, empty.elim, λ _, empty.elim⟩ instance : unique (language.empty.Structure M) := ⟨⟨language.empty_Structure⟩, λ a, begin ext n f, { exact empty.elim f }, { exact subsingleton.elim _ _ }, end⟩ @[priority 100] instance strong_hom_class_empty {F M N} [fun_like F M (λ _, N)] : strong_hom_class language.empty F M N := ⟨λ _ _ f, empty.elim f, λ _ _ r, empty.elim r⟩ /-- Makes a `language.empty.hom` out of any function. -/ @[simps] def _root_.function.empty_hom (f : M → N) : (M →[language.empty] N) := { to_fun := f } /-- Makes a `language.empty.embedding` out of any function. -/ @[simps] def _root_.embedding.empty (f : M ↪ N) : (M ↪[language.empty] N) := { to_embedding := f } /-- Makes a `language.empty.equiv` out of any function. -/ @[simps] def _root_.equiv.empty (f : M ≃ N) : (M ≃[language.empty] N) := { to_equiv := f } end empty end language end first_order namespace equiv open first_order first_order.language first_order.language.Structure open_locale first_order variables {L : language} {M : Type*} {N : Type*} [L.Structure M] /-- A structure induced by a bijection. -/ @[simps] def induced_Structure (e : M ≃ N) : L.Structure N := ⟨λ n f x, e (fun_map f (e.symm ∘ x)), λ n r x, rel_map r (e.symm ∘ x)⟩ /-- A bijection as a first-order isomorphism with the induced structure on the codomain. -/ @[simps] def induced_Structure_equiv (e : M ≃ N) : @language.equiv L M N _ (induced_Structure e) := { map_fun' := λ n f x, by simp [← function.comp.assoc e.symm e x], map_rel' := λ n r x, by simp [← function.comp.assoc e.symm e x], .. e } end equiv
3d3b3e9f78d433ca45f600366cc0c03f90ad1399
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/src/Init/Control/Functor.lean
46235c3bcf044df7fab6a5df7089eed80d094eb8
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
881
lean
/- Copyright (c) Luke Nelson and Jared Roesch. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Luke Nelson, Jared Roesch, Sebastian Ullrich, Leonardo de Moura -/ prelude import Init.Core open Function universes u v class Functor (f : Type u → Type v) : Type (max (u+1) v) := (map : ∀ {α β : Type u}, (α → β) → f α → f β) (mapConst : ∀ {α β : Type u}, α → f β → f α := fun α β => map ∘ const β) infixr `<$>` := Functor.map infixr `<$` := Functor.mapConst @[reducible] def Functor.mapConstRev {f : Type u → Type v} [Functor f] {α β : Type u} : f β → α → f α := fun a b => b <$ a infixr `$>` := Functor.mapConstRev @[reducible] def Functor.mapRev {f : Type u → Type v} [Functor f] {α β : Type u} : f α → (α → β) → f β := fun a f => f <$> a infixl `<&>` := Functor.mapRev
202353ea5aa362c9cadbbbaa374e6b664f4665f0
9c1ad797ec8a5eddb37d34806c543602d9a6bf70
/monoidal_categories/internal_objects/semigroups.lean
e9d7b3931fc7c704dd2839d855c6aacfede31967
[]
no_license
timjb/lean-category-theory
816eefc3a0582c22c05f4ee1c57ed04e57c0982f
12916cce261d08bb8740bc85e0175b75fb2a60f4
refs/heads/master
1,611,078,926,765
1,492,080,000,000
1,492,080,000,000
88,348,246
0
0
null
1,492,262,499,000
1,492,262,498,000
null
UTF-8
Lean
false
false
952
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan, Scott Morrison import ..monoidal_category open tqft.categories open tqft.categories.monoidal_category namespace tqft.categories.internal_objects structure SemigroupObject { C : Category } ( m : MonoidalStructure C ) := ( object : C.Obj ) ( multiplication : C.Hom (m (object, object)) object) ( associativity : C.compose (m.tensorMorphisms multiplication (C.identity object)) multiplication = C.compose (m.associator object object object) (C.compose (m.tensorMorphisms (C.identity object) multiplication) multiplication) ) attribute [ematch] SemigroupObject.associativity instance SemigroupObject_coercion_to_object { C : Category } { m : MonoidalStructure C } : has_coe (SemigroupObject m) (C.Obj) := { coe := SemigroupObject.object } end tqft.categories.internal_objects
35038a4ab59232cf62a16d9f60f7392d066308ac
41ebf3cb010344adfa84907b3304db00e02db0a6
/uexp/tactic_paper_supplemental_material/lazy_tactic.lean
12748fc576da664251da1726f545b9f5d72d5248
[ "BSD-2-Clause" ]
permissive
ReinierKoops/Cosette
e061b2ba58b26f4eddf4cd052dcf7abd16dfe8fb
eb8dadd06ee05fe7b6b99de431dd7c4faef5cb29
refs/heads/master
1,686,483,953,198
1,624,293,498,000
1,624,293,498,000
378,997,885
0
0
BSD-2-Clause
1,624,293,485,000
1,624,293,484,000
null
UTF-8
Lean
false
false
2,289
lean
import data.lazy_list universe variables u meta def lazy_tactic (α : Type u) := tactic_state → lazy_list (α × tactic_state) namespace lazy_tactic open lazy_list meta def of_tactic {α : Type u} (t : tactic α) : lazy_tactic α := λ s, match t s with | result.success a new_s := lazy_list.singleton (a, new_s) | result.exception f e s := lazy_list.nil end meta instance {α : Type} : has_coe (tactic α) (lazy_tactic α) := ⟨of_tactic⟩ protected meta def return {α} (a : α) : lazy_tactic α := λ s, lazy_list.singleton (a, s) protected meta def map {α β} (f : α → β) : lazy_tactic α → lazy_tactic β | t s := (t s).for (λ ⟨a, new_s⟩, (f a, new_s)) protected meta def bind {α β} : lazy_tactic α → (α → lazy_tactic β) → lazy_tactic β := λ t₁ t₂ s, join (for (t₁ s) (λ ⟨a, new_s⟩, t₂ a new_s)) protected meta def orelse {α} (t₁ t₂ : lazy_tactic α) : lazy_tactic α := λ s, append (t₁ s) (t₂ s) protected meta def failure {α} : lazy_tactic α := λ s, nil meta instance : monad lazy_tactic := unsafe_monad_from_pure_bind @lazy_tactic.return @lazy_tactic.bind meta instance : alternative lazy_tactic := { lazy_tactic.monad with failure := @lazy_tactic.failure, orelse := @lazy_tactic.orelse } meta def choose {α} (xs : list α) : lazy_tactic α := λ s, of_list $ xs.for (λ a, (a, s)) meta def run {α} (t : lazy_tactic α) : tactic α := λ s, match t s with | nil := tactic.failed s | cons (a, new_s) ss := result.success a new_s end open tactic private meta def try_constructors : list name → lazy_tactic unit | [] := failure | (c::cs) := (mk_const c >>= apply : tactic unit) <|> try_constructors cs /- Backtracking version of constructor -/ meta def constructor : lazy_tactic unit := do t ← target, cs ← get_constructors_for t, try_constructors cs end lazy_tactic open lazy_tactic example (p q : Prop) : q → p ∨ q := by run $ do tactic.intros, constructor, tactic.trace_state, tactic.assumption meta def naive_instantiation : lazy_tactic unit := let vals := [``(1),``(2),``(3)] in do x ← choose vals, y ← choose vals, e ← tactic.to_expr ``(nat.add_comm %%x %%y), tactic.trace e, tactic.exact e lemma ex : 1 + 3 = 3 + 1 := by naive_instantiation.run
3a758d076396dfd750f7c7e1b5edda26b01dc3db
4727251e0cd73359b15b664c3170e5d754078599
/src/number_theory/legendre_symbol/quadratic_char.lean
6c8dd16b5e06f495ca184db7e939d829a4ce95d3
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
13,406
lean
/- Copyright (c) 2022 Michael Stoll. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Stoll -/ import tactic.basic import number_theory.legendre_symbol.auxiliary import data.int.range /-! # Quadratic characters of finite fields This file defines the quadratic character on a finite field `F` and proves some basic statements about it. ## Tags quadratic character -/ namespace char /-! ### Definition of the quadratic character We define the quadratic character of a finite field `F` with values in ℤ. -/ section define /-- Define the quadratic character with values in ℤ on a monoid with zero `α`. It takes the value zero at zero; for non-zero argument `a : α`, it is `1` if `a` is a square, otherwise it is `-1`. This only deserves the name "character" when it is multiplicative, e.g., when `α` is a finite field. See `quadratic_char_mul`. -/ def quadratic_char (α : Type*) [monoid_with_zero α] [decidable_eq α] [decidable_pred (is_square : α → Prop)] (a : α) : ℤ := if a = 0 then 0 else if is_square a then 1 else -1 end define /-! ### Basic properties of the quadratic character We prove some properties of the quadratic character. We work with a finite field `F` here. The interesting case is when the characteristic of `F` is odd. -/ section quadratic_char variables {F : Type*} [field F] [fintype F] [decidable_eq F] /-- Some basic API lemmas -/ lemma quadratic_char_eq_zero_iff (a : F) : quadratic_char F a = 0 ↔ a = 0 := begin simp only [quadratic_char], by_cases ha : a = 0, { simp only [ha, eq_self_iff_true, if_true], }, { simp only [ha, if_false, iff_false], split_ifs; simp only [neg_eq_zero, one_ne_zero, not_false_iff], }, end @[simp] lemma quadratic_char_zero : quadratic_char F 0 = 0 := by simp only [quadratic_char, eq_self_iff_true, if_true, id.def] @[simp] lemma quadratic_char_one : quadratic_char F 1 = 1 := by simp only [quadratic_char, one_ne_zero, is_square_one, if_true, if_false, id.def] /-- For nonzero `a : F`, `quadratic_char F a = 1 ↔ is_square a`. -/ lemma quadratic_char_one_iff_is_square {a : F} (ha : a ≠ 0) : quadratic_char F a = 1 ↔ is_square a := by { simp only [quadratic_char, ha, (dec_trivial : (-1 : ℤ) ≠ 1), if_false, ite_eq_left_iff], tauto, } /-- The quadratic character takes the value `1` on nonzero squares. -/ lemma quadratic_char_sq_one' {a : F} (ha : a ≠ 0) : quadratic_char F (a ^ 2) = 1 := by simp only [quadratic_char, ha, pow_eq_zero_iff, nat.succ_pos', is_square_sq, if_true, if_false] /-- If `ring_char F = 2`, then `quadratic_char F` takes the value `1` on nonzero elements. -/ lemma quadratic_char_eq_one_of_char_two (hF : ring_char F = 2) {a : F} (ha : a ≠ 0) : quadratic_char F a = 1 := begin simp only [quadratic_char, ha, if_false, ite_eq_left_iff], intro h, exfalso, exact h (finite_field.is_square_of_char_two hF a), end /-- If `ring_char F` is odd, then `quadratic_char F a` can be computed in terms of `a ^ (fintype.card F / 2)`. -/ lemma quadratic_char_eq_pow_of_char_ne_two (hF : ring_char F ≠ 2) {a : F} (ha : a ≠ 0) : quadratic_char F a = if a ^ (fintype.card F / 2) = 1 then 1 else -1 := begin simp only [quadratic_char, ha, if_false], simp_rw finite_field.is_square_iff hF ha, end /-- The quadratic character is multiplicative. -/ lemma quadratic_char_mul (a b : F) : quadratic_char F (a * b) = quadratic_char F a * quadratic_char F b := begin by_cases ha : a = 0, { rw [ha, zero_mul, quadratic_char_zero, zero_mul], }, -- now `a ≠ 0` by_cases hb : b = 0, { rw [hb, mul_zero, quadratic_char_zero, mul_zero], }, -- now `a ≠ 0` and `b ≠ 0` have hab := mul_ne_zero ha hb, by_cases hF : ring_char F = 2, { -- case `ring_char F = 2` rw [quadratic_char_eq_one_of_char_two hF ha, quadratic_char_eq_one_of_char_two hF hb, quadratic_char_eq_one_of_char_two hF hab, mul_one], }, { -- case of odd characteristic rw [quadratic_char_eq_pow_of_char_ne_two hF ha, quadratic_char_eq_pow_of_char_ne_two hF hb, quadratic_char_eq_pow_of_char_ne_two hF hab, mul_pow], cases finite_field.pow_dichotomy hF hb with hb' hb', { simp only [hb', mul_one, eq_self_iff_true, if_true], }, { have h := finite_field.neg_one_ne_one_of_char_ne_two hF, -- `-1 ≠ 1` simp only [hb', h, mul_neg, mul_one, if_false, ite_mul, neg_mul], cases finite_field.pow_dichotomy hF ha with ha' ha'; simp only [ha', h, neg_neg, eq_self_iff_true, if_true, if_false], }, }, end /-- The quadratic character is a homomorphism of monoids with zero. -/ @[simps] def quadratic_char_hom : F →*₀ ℤ := { to_fun := quadratic_char F, map_zero' := quadratic_char_zero, map_one' := quadratic_char_one, map_mul' := quadratic_char_mul } /-- The square of the quadratic character on nonzero arguments is `1`. -/ lemma quadratic_char_sq_one {a : F} (ha : a ≠ 0) : (quadratic_char F a) ^ 2 = 1 := by rwa [pow_two, ← quadratic_char_mul, ← pow_two, quadratic_char_sq_one'] /-- The quadratic character is `1` or `-1` on nonzero arguments. -/ lemma quadratic_char_dichotomy {a : F} (ha : a ≠ 0) : quadratic_char F a = 1 ∨ quadratic_char F a = -1 := (sq_eq_one_iff (quadratic_char F a)).mp (quadratic_char_sq_one ha) /-- A variant -/ lemma quadratic_char_eq_neg_one_iff_not_one {a : F} (ha : a ≠ 0) : quadratic_char F a = -1 ↔ ¬ quadratic_char F a = 1 := begin refine ⟨λ h, _, λ h₂, (or_iff_right h₂).mp (quadratic_char_dichotomy ha)⟩, rw h, norm_num, end /-- For `a : F`, `quadratic_char F a = -1 ↔ ¬ is_square a`. -/ lemma quadratic_char_neg_one_iff_not_is_square {a : F} : quadratic_char F a = -1 ↔ ¬ is_square a := begin by_cases ha : a = 0, { simp only [ha, is_square_zero, quadratic_char_zero, zero_eq_neg, one_ne_zero, not_true], }, { rw [quadratic_char_eq_neg_one_iff_not_one ha, quadratic_char_one_iff_is_square ha] }, end /-- If `F` has odd characteristic, then `quadratic_char F` takes the value `-1`. -/ lemma quadratic_char_exists_neg_one (hF : ring_char F ≠ 2) : ∃ a, quadratic_char F a = -1 := (finite_field.exists_nonsquare hF).imp (λ b h₁, quadratic_char_neg_one_iff_not_is_square.mpr h₁) /-- The number of solutions to `x^2 = a` is determined by the quadratic character. -/ lemma quadratic_char_card_sqrts (hF : ring_char F ≠ 2) (a : F) : ↑{x : F | x^2 = a}.to_finset.card = quadratic_char F a + 1 := begin -- we consider the cases `a = 0`, `a` is a nonzero square and `a` is a nonsquare in turn by_cases h₀ : a = 0, { simp only [h₀, pow_eq_zero_iff, nat.succ_pos', int.coe_nat_succ, int.coe_nat_zero, zero_add, quadratic_char_zero, add_zero, set.set_of_eq_eq_singleton, set.to_finset_card, set.card_singleton], }, { set s := {x : F | x^2 = a}.to_finset with hs, by_cases h : is_square a, { rw (quadratic_char_one_iff_is_square h₀).mpr h, rcases h with ⟨b, h⟩, rw [h, mul_self_eq_zero] at h₀, have h₁ : s = [b, -b].to_finset := by { ext x, simp only [finset.mem_filter, finset.mem_univ, true_and, list.to_finset_cons, list.to_finset_nil, insert_emptyc_eq, finset.mem_insert, finset.mem_singleton], rw ← pow_two at h, simp only [hs, set.mem_to_finset, set.mem_set_of_eq, h], split, { exact eq_or_eq_neg_of_sq_eq_sq _ _, }, { rintro (h₂ | h₂); rw h₂, simp only [neg_sq], }, }, simp only [h₁, finset.card_doubleton (finite_field.neg_ne_self_of_char_ne_two hF h₀), list.to_finset_cons, list.to_finset_nil, insert_emptyc_eq, int.coe_nat_succ, int.coe_nat_zero, zero_add], }, { rw quadratic_char_neg_one_iff_not_is_square.mpr h, simp only [int.coe_nat_eq_zero, finset.card_eq_zero, set.to_finset_card, fintype.card_of_finset, set.mem_set_of_eq, add_left_neg], ext x, simp only [iff_false, finset.mem_filter, finset.mem_univ, true_and, finset.not_mem_empty], rw is_square_iff_exists_sq at h, exact λ h', h ⟨_, h'.symm⟩, }, }, end open_locale big_operators /-- The sum over the values of the quadratic character is zero when the characteristic is odd. -/ lemma quadratic_char_sum_zero (hF : ring_char F ≠ 2) : ∑ (a : F), quadratic_char F a = 0 := begin cases (quadratic_char_exists_neg_one hF) with b hb, have h₀ : b ≠ 0 := by { intro hf, rw [hf, quadratic_char_zero, zero_eq_neg] at hb, exact one_ne_zero hb, }, have h₁ : ∑ (a : F), quadratic_char F (b * a) = ∑ (a : F), quadratic_char F a := fintype.sum_bijective _ (mul_left_bijective₀ b h₀) _ _ (λ x, rfl), simp only [quadratic_char_mul] at h₁, rw [← finset.mul_sum, hb, neg_mul, one_mul] at h₁, exact eq_zero_of_neg_eq h₁, end end quadratic_char end char /-! ### Quadratic characters mod 4 and 8 We define the primitive quadratic characters `χ₄`on `zmod 4` and `χ₈`, `χ₈'` on `zmod 8`. -/ namespace zmod section quad_char_mod_p /-- Define the nontrivial quadratic character on `zmod 4`, `χ₄`. It corresponds to the extension `ℚ(√-1)/ℚ`. -/ @[simps] def χ₄ : (zmod 4) →*₀ ℤ := { to_fun := (![0,1,0,-1] : (zmod 4 → ℤ)), map_zero' := rfl, map_one' := rfl, map_mul' := dec_trivial } /-- An explicit description of `χ₄` on integers / naturals -/ lemma χ₄_int_eq_if_mod_four (n : ℤ) : χ₄ n = if n % 2 = 0 then 0 else if n % 4 = 1 then 1 else -1 := begin have help : ∀ (m : ℤ), 0 ≤ m → m < 4 → χ₄ m = if m % 2 = 0 then 0 else if m = 1 then 1 else -1 := dec_trivial, rw [← int.mod_mod_of_dvd n (by norm_num : (2 : ℤ) ∣ 4), ← zmod.int_cast_mod n 4], exact help (n % 4) (int.mod_nonneg n (by norm_num)) (int.mod_lt n (by norm_num)), end lemma χ₄_nat_eq_if_mod_four (n : ℕ) : χ₄ n = if n % 2 = 0 then 0 else if n % 4 = 1 then 1 else -1 := by exact_mod_cast χ₄_int_eq_if_mod_four n /-- Alternative description for odd `n : ℕ` in terms of powers of `-1` -/ lemma χ₄_eq_neg_one_pow {n : ℕ} (hn : n % 2 = 1) : χ₄ n = (-1)^(n / 2) := begin rw χ₄_nat_eq_if_mod_four, simp only [hn, nat.one_ne_zero, if_false], have h := (nat.div_add_mod n 4).symm, cases (nat.odd_mod_four_iff.mp hn) with h4 h4, { split_ifs, rw h4 at h, rw [h], nth_rewrite 0 (by norm_num : 4 = 2 * 2), rw [mul_assoc, add_comm, nat.add_mul_div_left _ _ (by norm_num : 0 < 2), pow_add, pow_mul], norm_num, }, { split_ifs, { exfalso, rw h4 at h_1, norm_num at h_1, }, { rw h4 at h, rw [h], nth_rewrite 0 (by norm_num : 4 = 2 * 2), rw [mul_assoc, add_comm, nat.add_mul_div_left _ _ (by norm_num : 0 < 2), pow_add, pow_mul], norm_num, }, }, end /-- Define the first primitive quadratic character on `zmod 8`, `χ₈`. It corresponds to the extension `ℚ(√2)/ℚ`. -/ @[simps] def χ₈ : (zmod 8) →*₀ ℤ := { to_fun := (![0,1,0,-1,0,-1,0,1] : (zmod 8 → ℤ)), map_zero' := rfl, map_one' := rfl, map_mul' := by dec_trivial } /-- Define the second primitive quadratic character on `zmod 8`, `χ₈'`. It corresponds to the extension `ℚ(√-2)/ℚ`. -/ @[simps] def χ₈' : (zmod 8) →*₀ ℤ := { to_fun := (![0,1,0,1,0,-1,0,-1] : (zmod 8 → ℤ)), map_zero' := rfl, map_one' := rfl, map_mul' := by dec_trivial } end quad_char_mod_p end zmod /-! ### Special values of the quadratic character We express `quadratic_char F (-1)` in terms of `χ₄`. -/ section special_values namespace char open zmod variables {F : Type*} [field F] [fintype F] /-- The value of the quadratic character at `-1` -/ lemma quadratic_char_neg_one [decidable_eq F] (hF : ring_char F ≠ 2) : quadratic_char F (-1) = χ₄ (fintype.card F) := begin have h₁ : (-1 : F) ≠ 0 := by { rw neg_ne_zero, exact one_ne_zero }, have h := quadratic_char_eq_pow_of_char_ne_two hF h₁, rw [h, χ₄_eq_neg_one_pow (finite_field.odd_card_of_char_ne_two hF)], set n := fintype.card F / 2, cases (nat.even_or_odd n) with h₂ h₂, { simp only [even.neg_one_pow h₂, eq_self_iff_true, if_true], }, { simp only [odd.neg_one_pow h₂, ite_eq_right_iff], exact λ (hf : -1 = 1), false.rec (1 = -1) (finite_field.neg_one_ne_one_of_char_ne_two hF hf), }, end /-- The interpretation in terms of whether `-1` is a square in `F` -/ lemma is_square_neg_one_iff : is_square (-1 : F) ↔ fintype.card F % 4 ≠ 3 := begin classical, -- suggested by the linter (instead of `[decidable_eq F]`) by_cases hF : (ring_char F = 2), { simp only [finite_field.is_square_of_char_two hF, ne.def, true_iff], exact (λ hf, one_ne_zero ((nat.odd_of_mod_four_eq_three hf).symm.trans (finite_field.even_card_of_char_two hF)))}, { have h₁ : (-1 : F) ≠ 0 := by { rw neg_ne_zero, exact one_ne_zero }, have h₂ := finite_field.odd_card_of_char_ne_two hF, rw [← quadratic_char_one_iff_is_square h₁, quadratic_char_neg_one hF, χ₄_nat_eq_if_mod_four, h₂], have h₃ := nat.odd_mod_four_iff.mp h₂, simp only [nat.one_ne_zero, if_false, ite_eq_left_iff, ne.def], norm_num, split, { intros h h', have t := (of_not_not h).symm.trans h', norm_num at t, }, exact λ h h', h' ((or_iff_left h).mp h₃), }, end end char end special_values
fed365f5c0ea07668c8832c5183efc3cd741eff9
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/finite/card.lean
bda3efd6479ac68523ade58867331bc872a5e60e
[ "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
7,784
lean
/- Copyright (c) 2022 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import set_theory.cardinal.finite /-! # Cardinality of finite types > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The cardinality of a finite type `α` is given by `nat.card α`. This function has the "junk value" of `0` for infinite types, but to ensure the function has valid output, one just needs to know that it's possible to produce a `finite` instance for the type. (Note: we could have defined a `finite.card` that required you to supply a `finite` instance, but (a) the function would be `noncomputable` anyway so there is no need to supply the instance and (b) the function would have a more complicated dependent type that easily leads to "motive not type correct" errors.) ## Implementation notes Theorems about `nat.card` are sometimes incidentally true for both finite and infinite types. If removing a finiteness constraint results in no loss in legibility, we remove it. We generally put such theorems into the `set_theory.cardinal.finite` module. -/ noncomputable theory open_locale classical variables {α β γ : Type*} /-- There is (noncomputably) an equivalence between a finite type `α` and `fin (nat.card α)`. -/ def finite.equiv_fin (α : Type*) [finite α] : α ≃ fin (nat.card α) := begin have := (finite.exists_equiv_fin α).some_spec.some, rwa nat.card_eq_of_equiv_fin this, end /-- Similar to `finite.equiv_fin` but with control over the term used for the cardinality. -/ def finite.equiv_fin_of_card_eq [finite α] {n : ℕ} (h : nat.card α = n) : α ≃ fin n := by { subst h, apply finite.equiv_fin } lemma nat.card_eq (α : Type*) : nat.card α = if h : finite α then by exactI @fintype.card α (fintype.of_finite α) else 0 := begin casesI finite_or_infinite α, { letI := fintype.of_finite α, simp only [*, nat.card_eq_fintype_card, dif_pos] }, { simp [*, not_finite_iff_infinite.mpr h] }, end lemma finite.card_pos_iff [finite α] : 0 < nat.card α ↔ nonempty α := begin haveI := fintype.of_finite α, rw [nat.card_eq_fintype_card, fintype.card_pos_iff], end lemma finite.card_pos [finite α] [h : nonempty α] : 0 < nat.card α := finite.card_pos_iff.mpr h namespace finite lemma cast_card_eq_mk {α : Type*} [finite α] : ↑(nat.card α) = cardinal.mk α := cardinal.cast_to_nat_of_lt_aleph_0 (cardinal.lt_aleph_0_of_finite α) lemma card_eq [finite α] [finite β] : nat.card α = nat.card β ↔ nonempty (α ≃ β) := by { haveI := fintype.of_finite α, haveI := fintype.of_finite β, simp [fintype.card_eq] } lemma card_le_one_iff_subsingleton [finite α] : nat.card α ≤ 1 ↔ subsingleton α := by { haveI := fintype.of_finite α, simp [fintype.card_le_one_iff_subsingleton] } lemma one_lt_card_iff_nontrivial [finite α] : 1 < nat.card α ↔ nontrivial α := by { haveI := fintype.of_finite α, simp [fintype.one_lt_card_iff_nontrivial] } lemma one_lt_card [finite α] [h : nontrivial α] : 1 < nat.card α := one_lt_card_iff_nontrivial.mpr h @[simp] lemma card_option [finite α] : nat.card (option α) = nat.card α + 1 := by { haveI := fintype.of_finite α, simp } lemma card_le_of_injective [finite β] (f : α → β) (hf : function.injective f) : nat.card α ≤ nat.card β := by { haveI := fintype.of_finite β, haveI := fintype.of_injective f hf, simpa using fintype.card_le_of_injective f hf } lemma card_le_of_embedding [finite β] (f : α ↪ β) : nat.card α ≤ nat.card β := card_le_of_injective _ f.injective lemma card_le_of_surjective [finite α] (f : α → β) (hf : function.surjective f) : nat.card β ≤ nat.card α := by { haveI := fintype.of_finite α, haveI := fintype.of_surjective f hf, simpa using fintype.card_le_of_surjective f hf } lemma card_eq_zero_iff [finite α] : nat.card α = 0 ↔ is_empty α := by { haveI := fintype.of_finite α, simp [fintype.card_eq_zero_iff] } /-- If `f` is injective, then `nat.card α ≤ nat.card β`. We must also assume `nat.card β = 0 → nat.card α = 0` since `nat.card` is defined to be `0` for infinite types. -/ lemma card_le_of_injective' {f : α → β} (hf : function.injective f) (h : nat.card β = 0 → nat.card α = 0) : nat.card α ≤ nat.card β := (or_not_of_imp h).cases_on (λ h, le_of_eq_of_le h zero_le') (λ h, @card_le_of_injective α β (nat.finite_of_card_ne_zero h) f hf) /-- If `f` is an embedding, then `nat.card α ≤ nat.card β`. We must also assume `nat.card β = 0 → nat.card α = 0` since `nat.card` is defined to be `0` for infinite types. -/ lemma card_le_of_embedding' (f : α ↪ β) (h : nat.card β = 0 → nat.card α = 0) : nat.card α ≤ nat.card β := card_le_of_injective' f.2 h /-- If `f` is surjective, then `nat.card β ≤ nat.card α`. We must also assume `nat.card α = 0 → nat.card β = 0` since `nat.card` is defined to be `0` for infinite types. -/ lemma card_le_of_surjective' {f : α → β} (hf : function.surjective f) (h : nat.card α = 0 → nat.card β = 0) : nat.card β ≤ nat.card α := (or_not_of_imp h).cases_on (λ h, le_of_eq_of_le h zero_le') (λ h, @card_le_of_surjective α β (nat.finite_of_card_ne_zero h) f hf) /-- NB: `nat.card` is defined to be `0` for infinite types. -/ lemma card_eq_zero_of_surjective {f : α → β} (hf : function.surjective f) (h : nat.card β = 0) : nat.card α = 0 := begin casesI finite_or_infinite β, { haveI := card_eq_zero_iff.mp h, haveI := function.is_empty f, exact nat.card_of_is_empty }, { haveI := infinite.of_surjective f hf, exact nat.card_eq_zero_of_infinite }, end /-- NB: `nat.card` is defined to be `0` for infinite types. -/ lemma card_eq_zero_of_injective [nonempty α] {f : α → β} (hf : function.injective f) (h : nat.card α = 0) : nat.card β = 0 := card_eq_zero_of_surjective (function.inv_fun_surjective hf) h /-- NB: `nat.card` is defined to be `0` for infinite types. -/ lemma card_eq_zero_of_embedding [nonempty α] (f : α ↪ β) (h : nat.card α = 0) : nat.card β = 0 := card_eq_zero_of_injective f.2 h lemma card_sum [finite α] [finite β] : nat.card (α ⊕ β) = nat.card α + nat.card β := by { haveI := fintype.of_finite α, haveI := fintype.of_finite β, simp } lemma card_image_le {s : set α} [finite s] (f : α → β) : nat.card (f '' s) ≤ nat.card s := card_le_of_surjective _ set.surjective_onto_image lemma card_range_le [finite α] (f : α → β) : nat.card (set.range f) ≤ nat.card α := card_le_of_surjective _ set.surjective_onto_range theorem card_subtype_le [finite α] (p : α → Prop) : nat.card {x // p x} ≤ nat.card α := by { haveI := fintype.of_finite α, simpa using fintype.card_subtype_le p } theorem card_subtype_lt [finite α] {p : α → Prop} {x : α} (hx : ¬ p x) : nat.card {x // p x} < nat.card α := by { haveI := fintype.of_finite α, simpa using fintype.card_subtype_lt hx } end finite namespace part_enat lemma card_eq_coe_nat_card (α : Type*) [finite α] : card α = nat.card α := begin unfold part_enat.card, apply symm, rw cardinal.coe_nat_eq_to_part_enat_iff, exact finite.cast_card_eq_mk , end end part_enat namespace set lemma card_union_le (s t : set α) : nat.card ↥(s ∪ t) ≤ nat.card s + nat.card t := begin casesI _root_.finite_or_infinite ↥(s ∪ t) with h h, { rw [finite_coe_iff, finite_union, ←finite_coe_iff, ←finite_coe_iff] at h, casesI h, rw [←cardinal.nat_cast_le, nat.cast_add, finite.cast_card_eq_mk, finite.cast_card_eq_mk, finite.cast_card_eq_mk], exact cardinal.mk_union_le s t }, { exact nat.card_eq_zero_of_infinite.trans_le (zero_le _) }, end end set
c424a72ff3d3df21782b65e7c6d9749d80ff4635
ac60dab17014edd769c9618cc1569ce8c960a6a5
/src/ant.lean
375799e8aa3345eeaa45ed29d54710e32ff8cd42
[ "MIT" ]
permissive
frankSil/CAExtensions
20e1f856b3ad775d5e8dc8877614dbcd58c77901
f5c74fd9a806696c73497d9abd45b7315f45379f
refs/heads/master
1,608,706,941,607
1,586,193,337,000
1,586,193,337,000
237,077,434
0
0
null
null
null
null
UTF-8
Lean
false
false
2,389
lean
import cautomaton utils open utils namespace la section la inductive cellT | B | W | BN | BE | BS | BW | WN | WE | WS | WW inductive antCardinal | AN | AW | AE | AS | A open cellT antCardinal def cellT_str : cellT → string | B := "X" | W := " " | BN := "^" | BE := ">" | BS := "v" | BW := "<" | WN := "^" | WE := ">" | WS := "v" | WW := "<" instance cellT_to_str : has_to_string cellT := ⟨cellT_str⟩ instance cellT_repr : has_repr cellT := ⟨cellT_str⟩ instance cellT_deceq : decidable_eq cellT := λl r, begin cases l; cases r; try {exact is_true rfl}; apply is_false; trivial end attribute [reducible] def ant := cautomaton cellT def step : cellT → antCardinal → cellT | W AS := WS | B AS := BS | W AE := WE | B AE := BE | W AW := WW | B AW := BW | W AN := WN | B AN := BN | BN _ := W | BW _ := W | BE _ := W | BS _ := W | WN _ := B | WW _ := B | WE _ := B | WS _ := B | x A := x def la_step (cell : cellT) (neigh : list cellT) := let north := list.nth neigh 0 in match north with | none := W | (some c) := if c = WE ∨ c = BW then step cell AS else let west := list.nth neigh 1 in match west with | none := W | (some c) := if c = WN ∨ c = BS then step cell AE else let east := list.nth neigh 2 in match east with | none := W | (some c) := if c = WS ∨ c = BN then step cell AW else let south := list.nth neigh 3 in match south with | none := W | (some c) := if c = WW ∨ c = BE then step cell AN else step cell A end end end end def mk_ant (g : vec_grid₀ cellT) : ant := ⟨g, W, cautomatons.neumann, sum.inr (@bound_periodic (vec_grid₀ cellT) _), la_step⟩ def ant_g := vec_grid₀.mk ⟨11, 11, dec_trivial, ⟨[W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, WW, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W, W], rfl⟩⟩ ⟨0, 1⟩ def simple : ant := mk_ant ant_g end la end la
911fef13e51e4ea56c594f941f904baeec2bb989
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/uniform_space/pi_auto.lean
573ebafa5fc7479feba093b801e14a40cc5a9b02
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
2,176
lean
/- Copyright (c) 2019 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.uniform_space.cauchy import Mathlib.topology.uniform_space.separation import Mathlib.PostPort universes u u_1 namespace Mathlib /-! # Indexed product of uniform spaces -/ protected instance Pi.uniform_space {ι : Type u_1} (α : ι → Type u) [U : (i : ι) → uniform_space (α i)] : uniform_space ((i : ι) → α i) := uniform_space.of_core_eq uniform_space.to_core Pi.topological_space sorry theorem Pi.uniformity {ι : Type u_1} (α : ι → Type u) [U : (i : ι) → uniform_space (α i)] : uniformity ((i : ι) → α i) = infi fun (i : ι) => filter.comap (fun (a : ((i : ι) → α i) × ((i : ι) → α i)) => (prod.fst a i, prod.snd a i)) (uniformity (α i)) := infi_uniformity theorem Pi.uniform_continuous_proj {ι : Type u_1} (α : ι → Type u) [U : (i : ι) → uniform_space (α i)] (i : ι) : uniform_continuous fun (a : (i : ι) → α i) => a i := eq.mpr (id (Eq._oldrec (Eq.refl (uniform_continuous fun (a : (i : ι) → α i) => a i)) (propext uniform_continuous_iff))) (infi_le (fun (j : ι) => uniform_space.comap (fun (a : (i : ι) → α i) => a j) (U j)) i) protected instance Pi.complete {ι : Type u_1} (α : ι → Type u) [U : (i : ι) → uniform_space (α i)] [∀ (i : ι), complete_space (α i)] : complete_space ((i : ι) → α i) := sorry protected instance Pi.separated {ι : Type u_1} (α : ι → Type u) [U : (i : ι) → uniform_space (α i)] [∀ (i : ι), separated_space (α i)] : separated_space ((i : ι) → α i) := iff.mpr separated_def fun (x y : (i : ι) → α i) (H : ∀ (r : set (((i : ι) → α i) × ((i : ι) → α i))), r ∈ uniformity ((i : ι) → α i) → (x, y) ∈ r) => funext fun (i : ι) => uniform_space.eq_of_separated_of_uniform_continuous (Pi.uniform_continuous_proj α i) H end Mathlib
1c24f65f2777f58fc69003b09ef8c6302c6372f9
94e33a31faa76775069b071adea97e86e218a8ee
/src/analysis/convex/topology.lean
5381e8564c8c4895622d36f63533593f9c48aaca
[ "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
19,331
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp, Yury Kudryashov -/ import analysis.convex.jensen import analysis.normed.group.pointwise import analysis.normed_space.finite_dimension import analysis.normed_space.ray import topology.path_connected import topology.algebra.affine /-! # Topological and metric properties of convex sets We prove the following facts: * `convex.interior` : interior of a convex set is convex; * `convex.closure` : closure of a convex set is convex; * `set.finite.compact_convex_hull` : convex hull of a finite set is compact; * `set.finite.is_closed_convex_hull` : convex hull of a finite set is closed; * `convex_on_norm`, `convex_on_dist` : norm and distance to a fixed point is convex on any convex set; * `convex_on_univ_norm`, `convex_on_univ_dist` : norm and distance to a fixed point is convex on the whole space; * `convex_hull_ediam`, `convex_hull_diam` : convex hull of a set has the same (e)metric diameter as the original set; * `bounded_convex_hull` : convex hull of a set is bounded if and only if the original set is bounded. * `bounded_std_simplex`, `is_closed_std_simplex`, `compact_std_simplex`: topological properties of the standard simplex; -/ variables {ι : Type*} {E : Type*} open metric set open_locale pointwise convex lemma real.convex_iff_is_preconnected {s : set ℝ} : convex ℝ s ↔ is_preconnected s := convex_iff_ord_connected.trans is_preconnected_iff_ord_connected.symm alias real.convex_iff_is_preconnected ↔ _ is_preconnected.convex /-! ### Standard simplex -/ section std_simplex variables [fintype ι] /-- Every vector in `std_simplex 𝕜 ι` has `max`-norm at most `1`. -/ lemma std_simplex_subset_closed_ball : std_simplex ℝ ι ⊆ metric.closed_ball 0 1 := begin assume f hf, rw [metric.mem_closed_ball, dist_zero_right], refine (nnreal.coe_one ▸ nnreal.coe_le_coe.2 $ finset.sup_le $ λ x hx, _), change |f x| ≤ 1, rw [abs_of_nonneg $ hf.1 x], exact (mem_Icc_of_mem_std_simplex hf x).2 end variable (ι) /-- `std_simplex ℝ ι` is bounded. -/ lemma bounded_std_simplex : metric.bounded (std_simplex ℝ ι) := (metric.bounded_iff_subset_ball 0).2 ⟨1, std_simplex_subset_closed_ball⟩ /-- `std_simplex ℝ ι` is closed. -/ lemma is_closed_std_simplex : is_closed (std_simplex ℝ ι) := (std_simplex_eq_inter ℝ ι).symm ▸ is_closed.inter (is_closed_Inter $ λ i, is_closed_le continuous_const (continuous_apply i)) (is_closed_eq (continuous_finset_sum _ $ λ x _, continuous_apply x) continuous_const) /-- `std_simplex ℝ ι` is compact. -/ lemma compact_std_simplex : is_compact (std_simplex ℝ ι) := metric.compact_iff_closed_bounded.2 ⟨is_closed_std_simplex ι, bounded_std_simplex ι⟩ end std_simplex /-! ### Topological vector space -/ section has_continuous_const_smul variables {𝕜 : Type*} [linear_ordered_field 𝕜] [add_comm_group E] [module 𝕜 E] [topological_space E] [topological_add_group E] [has_continuous_const_smul 𝕜 E] /-- If `s` is a convex set, then `a • interior s + b • closure s ⊆ interior s` for all `0 < a`, `0 ≤ b`, `a + b = 1`. See also `convex.combo_interior_self_subset_interior` for a weaker version. -/ lemma convex.combo_interior_closure_subset_interior {s : set E} (hs : convex 𝕜 s) {a b : 𝕜} (ha : 0 < a) (hb : 0 ≤ b) (hab : a + b = 1) : a • interior s + b • closure s ⊆ interior s := interior_smul₀ ha.ne' s ▸ calc interior (a • s) + b • closure s ⊆ interior (a • s) + closure (b • s) : add_subset_add subset.rfl (smul_closure_subset b s) ... = interior (a • s) + b • s : by rw is_open_interior.add_closure (b • s) ... ⊆ interior (a • s + b • s) : subset_interior_add_left ... ⊆ interior s : interior_mono $ hs.set_combo_subset ha.le hb hab /-- If `s` is a convex set, then `a • interior s + b • s ⊆ interior s` for all `0 < a`, `0 ≤ b`, `a + b = 1`. See also `convex.combo_interior_closure_subset_interior` for a stronger version. -/ lemma convex.combo_interior_self_subset_interior {s : set E} (hs : convex 𝕜 s) {a b : 𝕜} (ha : 0 < a) (hb : 0 ≤ b) (hab : a + b = 1) : a • interior s + b • s ⊆ interior s := calc a • interior s + b • s ⊆ a • interior s + b • closure s : add_subset_add subset.rfl $ image_subset _ subset_closure ... ⊆ interior s : hs.combo_interior_closure_subset_interior ha hb hab /-- If `s` is a convex set, then `a • closure s + b • interior s ⊆ interior s` for all `0 ≤ a`, `0 < b`, `a + b = 1`. See also `convex.combo_self_interior_subset_interior` for a weaker version. -/ lemma convex.combo_closure_interior_subset_interior {s : set E} (hs : convex 𝕜 s) {a b : 𝕜} (ha : 0 ≤ a) (hb : 0 < b) (hab : a + b = 1) : a • closure s + b • interior s ⊆ interior s := by { rw add_comm, exact hs.combo_interior_closure_subset_interior hb ha (add_comm a b ▸ hab) } /-- If `s` is a convex set, then `a • s + b • interior s ⊆ interior s` for all `0 ≤ a`, `0 < b`, `a + b = 1`. See also `convex.combo_closure_interior_subset_interior` for a stronger version. -/ lemma convex.combo_self_interior_subset_interior {s : set E} (hs : convex 𝕜 s) {a b : 𝕜} (ha : 0 ≤ a) (hb : 0 < b) (hab : a + b = 1) : a • s + b • interior s ⊆ interior s := by { rw add_comm, exact hs.combo_interior_self_subset_interior hb ha (add_comm a b ▸ hab) } lemma convex.combo_interior_closure_mem_interior {s : set E} (hs : convex 𝕜 s) {x y : E} (hx : x ∈ interior s) (hy : y ∈ closure s) {a b : 𝕜} (ha : 0 < a) (hb : 0 ≤ b) (hab : a + b = 1) : a • x + b • y ∈ interior s := hs.combo_interior_closure_subset_interior ha hb hab $ add_mem_add (smul_mem_smul_set hx) (smul_mem_smul_set hy) lemma convex.combo_interior_self_mem_interior {s : set E} (hs : convex 𝕜 s) {x y : E} (hx : x ∈ interior s) (hy : y ∈ s) {a b : 𝕜} (ha : 0 < a) (hb : 0 ≤ b) (hab : a + b = 1) : a • x + b • y ∈ interior s := hs.combo_interior_closure_mem_interior hx (subset_closure hy) ha hb hab lemma convex.combo_closure_interior_mem_interior {s : set E} (hs : convex 𝕜 s) {x y : E} (hx : x ∈ closure s) (hy : y ∈ interior s) {a b : 𝕜} (ha : 0 ≤ a) (hb : 0 < b) (hab : a + b = 1) : a • x + b • y ∈ interior s := hs.combo_closure_interior_subset_interior ha hb hab $ add_mem_add (smul_mem_smul_set hx) (smul_mem_smul_set hy) lemma convex.combo_self_interior_mem_interior {s : set E} (hs : convex 𝕜 s) {x y : E} (hx : x ∈ s) (hy : y ∈ interior s) {a b : 𝕜} (ha : 0 ≤ a) (hb : 0 < b) (hab : a + b = 1) : a • x + b • y ∈ interior s := hs.combo_closure_interior_mem_interior (subset_closure hx) hy ha hb hab lemma convex.open_segment_interior_closure_subset_interior {s : set E} (hs : convex 𝕜 s) {x y : E} (hx : x ∈ interior s) (hy : y ∈ closure s) : open_segment 𝕜 x y ⊆ interior s := begin rintro _ ⟨a, b, ha, hb, hab, rfl⟩, exact hs.combo_interior_closure_mem_interior hx hy ha hb.le hab end lemma convex.open_segment_interior_self_subset_interior {s : set E} (hs : convex 𝕜 s) {x y : E} (hx : x ∈ interior s) (hy : y ∈ s) : open_segment 𝕜 x y ⊆ interior s := hs.open_segment_interior_closure_subset_interior hx (subset_closure hy) lemma convex.open_segment_closure_interior_subset_interior {s : set E} (hs : convex 𝕜 s) {x y : E} (hx : x ∈ closure s) (hy : y ∈ interior s) : open_segment 𝕜 x y ⊆ interior s := begin rintro _ ⟨a, b, ha, hb, hab, rfl⟩, exact hs.combo_closure_interior_mem_interior hx hy ha.le hb hab end lemma convex.open_segment_self_interior_subset_interior {s : set E} (hs : convex 𝕜 s) {x y : E} (hx : x ∈ s) (hy : y ∈ interior s) : open_segment 𝕜 x y ⊆ interior s := hs.open_segment_closure_interior_subset_interior (subset_closure hx) hy /-- If `x ∈ closure s` and `y ∈ interior s`, then the segment `(x, y]` is included in `interior s`. -/ lemma convex.add_smul_sub_mem_interior' {s : set E} (hs : convex 𝕜 s) {x y : E} (hx : x ∈ closure s) (hy : y ∈ interior s) {t : 𝕜} (ht : t ∈ Ioc (0 : 𝕜) 1) : x + t • (y - x) ∈ interior s := by simpa only [sub_smul, smul_sub, one_smul, add_sub, add_comm] using hs.combo_interior_closure_mem_interior hy hx ht.1 (sub_nonneg.mpr ht.2) (add_sub_cancel'_right _ _) /-- If `x ∈ s` and `y ∈ interior s`, then the segment `(x, y]` is included in `interior s`. -/ lemma convex.add_smul_sub_mem_interior {s : set E} (hs : convex 𝕜 s) {x y : E} (hx : x ∈ s) (hy : y ∈ interior s) {t : 𝕜} (ht : t ∈ Ioc (0 : 𝕜) 1) : x + t • (y - x) ∈ interior s := hs.add_smul_sub_mem_interior' (subset_closure hx) hy ht /-- If `x ∈ closure s` and `x + y ∈ interior s`, then `x + t y ∈ interior s` for `t ∈ (0, 1]`. -/ lemma convex.add_smul_mem_interior' {s : set E} (hs : convex 𝕜 s) {x y : E} (hx : x ∈ closure s) (hy : x + y ∈ interior s) {t : 𝕜} (ht : t ∈ Ioc (0 : 𝕜) 1) : x + t • y ∈ interior s := by simpa only [add_sub_cancel'] using hs.add_smul_sub_mem_interior' hx hy ht /-- If `x ∈ s` and `x + y ∈ interior s`, then `x + t y ∈ interior s` for `t ∈ (0, 1]`. -/ lemma convex.add_smul_mem_interior {s : set E} (hs : convex 𝕜 s) {x y : E} (hx : x ∈ s) (hy : x + y ∈ interior s) {t : 𝕜} (ht : t ∈ Ioc (0 : 𝕜) 1) : x + t • y ∈ interior s := hs.add_smul_mem_interior' (subset_closure hx) hy ht /-- In a topological vector space, the interior of a convex set is convex. -/ protected lemma convex.interior {s : set E} (hs : convex 𝕜 s) : convex 𝕜 (interior s) := convex_iff_open_segment_subset.mpr $ λ x y hx hy, hs.open_segment_closure_interior_subset_interior (interior_subset_closure hx) hy /-- In a topological vector space, the closure of a convex set is convex. -/ protected lemma convex.closure {s : set E} (hs : convex 𝕜 s) : convex 𝕜 (closure s) := λ x y hx hy a b ha hb hab, let f : E → E → E := λ x' y', a • x' + b • y' in have hf : continuous (λ p : E × E, f p.1 p.2), from (continuous_fst.const_smul _).add (continuous_snd.const_smul _), show f x y ∈ closure s, from mem_closure_of_continuous2 hf hx hy (λ x' hx' y' hy', subset_closure (hs hx' hy' ha hb hab)) end has_continuous_const_smul section has_continuous_smul variables [add_comm_group E] [module ℝ E] [topological_space E] [topological_add_group E] [has_continuous_smul ℝ E] /-- Convex hull of a finite set is compact. -/ lemma set.finite.compact_convex_hull {s : set E} (hs : s.finite) : is_compact (convex_hull ℝ s) := begin rw [hs.convex_hull_eq_image], apply (compact_std_simplex _).image, haveI := hs.fintype, apply linear_map.continuous_on_pi end /-- Convex hull of a finite set is closed. -/ lemma set.finite.is_closed_convex_hull [t2_space E] {s : set E} (hs : s.finite) : is_closed (convex_hull ℝ s) := hs.compact_convex_hull.is_closed open affine_map /-- If we dilate the interior of a convex set about a point in its interior by a scale `t > 1`, the result includes the closure of the original set. TODO Generalise this from convex sets to sets that are balanced / star-shaped about `x`. -/ lemma convex.closure_subset_image_homothety_interior_of_one_lt {s : set E} (hs : convex ℝ s) {x : E} (hx : x ∈ interior s) (t : ℝ) (ht : 1 < t) : closure s ⊆ homothety x t '' interior s := begin intros y hy, have hne : t ≠ 0, from (one_pos.trans ht).ne', refine ⟨homothety x t⁻¹ y, hs.open_segment_interior_closure_subset_interior hx hy _, (affine_equiv.homothety_units_mul_hom x (units.mk0 t hne)).apply_symm_apply y⟩, rw [open_segment_eq_image_line_map, ← inv_one, ← inv_Ioi (@one_pos ℝ _ _), ← image_inv, image_image, homothety_eq_line_map], exact mem_image_of_mem _ ht end /-- If we dilate a convex set about a point in its interior by a scale `t > 1`, the interior of the result includes the closure of the original set. TODO Generalise this from convex sets to sets that are balanced / star-shaped about `x`. -/ lemma convex.closure_subset_interior_image_homothety_of_one_lt {s : set E} (hs : convex ℝ s) {x : E} (hx : x ∈ interior s) (t : ℝ) (ht : 1 < t) : closure s ⊆ interior (homothety x t '' s) := (hs.closure_subset_image_homothety_interior_of_one_lt hx t ht).trans $ (homothety_is_open_map x t (one_pos.trans ht).ne').image_interior_subset _ /-- If we dilate a convex set about a point in its interior by a scale `t > 1`, the interior of the result includes the closure of the original set. TODO Generalise this from convex sets to sets that are balanced / star-shaped about `x`. -/ lemma convex.subset_interior_image_homothety_of_one_lt {s : set E} (hs : convex ℝ s) {x : E} (hx : x ∈ interior s) (t : ℝ) (ht : 1 < t) : s ⊆ interior (homothety x t '' s) := subset_closure.trans $ hs.closure_subset_interior_image_homothety_of_one_lt hx t ht /-- A nonempty convex set is path connected. -/ protected lemma convex.is_path_connected {s : set E} (hconv : convex ℝ s) (hne : s.nonempty) : is_path_connected s := begin refine is_path_connected_iff.mpr ⟨hne, _⟩, intros x x_in y y_in, have H := hconv.segment_subset x_in y_in, rw segment_eq_image_line_map at H, exact joined_in.of_line affine_map.line_map_continuous.continuous_on (line_map_apply_zero _ _) (line_map_apply_one _ _) H end /-- A nonempty convex set is connected. -/ protected lemma convex.is_connected {s : set E} (h : convex ℝ s) (hne : s.nonempty) : is_connected s := (h.is_path_connected hne).is_connected /-- A convex set is preconnected. -/ protected lemma convex.is_preconnected {s : set E} (h : convex ℝ s) : is_preconnected s := s.eq_empty_or_nonempty.elim (λ h, h.symm ▸ is_preconnected_empty) (λ hne, (h.is_connected hne).is_preconnected) /-- Every topological vector space over ℝ is path connected. Not an instance, because it creates enormous TC subproblems (turn on `pp.all`). -/ protected lemma topological_add_group.path_connected : path_connected_space E := path_connected_space_iff_univ.mpr $ convex_univ.is_path_connected ⟨(0 : E), trivial⟩ end has_continuous_smul /-! ### Normed vector space -/ section normed_space variables [semi_normed_group E] [normed_space ℝ E] {s t : set E} /-- The norm on a real normed space is convex on any convex set. See also `seminorm.convex_on` and `convex_on_univ_norm`. -/ lemma convex_on_norm (hs : convex ℝ s) : convex_on ℝ s norm := ⟨hs, λ x y hx hy a b ha hb hab, calc ∥a • x + b • y∥ ≤ ∥a • x∥ + ∥b • y∥ : norm_add_le _ _ ... = a * ∥x∥ + b * ∥y∥ : by rw [norm_smul, norm_smul, real.norm_of_nonneg ha, real.norm_of_nonneg hb]⟩ /-- The norm on a real normed space is convex on the whole space. See also `seminorm.convex_on` and `convex_on_norm`. -/ lemma convex_on_univ_norm : convex_on ℝ univ (norm : E → ℝ) := convex_on_norm convex_univ lemma convex_on_dist (z : E) (hs : convex ℝ s) : convex_on ℝ s (λ z', dist z' z) := by simpa [dist_eq_norm, preimage_preimage] using (convex_on_norm (hs.translate (-z))).comp_affine_map (affine_map.id ℝ E - affine_map.const ℝ E z) lemma convex_on_univ_dist (z : E) : convex_on ℝ univ (λz', dist z' z) := convex_on_dist z convex_univ lemma convex_ball (a : E) (r : ℝ) : convex ℝ (metric.ball a r) := by simpa only [metric.ball, sep_univ] using (convex_on_univ_dist a).convex_lt r lemma convex_closed_ball (a : E) (r : ℝ) : convex ℝ (metric.closed_ball a r) := by simpa only [metric.closed_ball, sep_univ] using (convex_on_univ_dist a).convex_le r lemma convex.thickening (hs : convex ℝ s) (δ : ℝ) : convex ℝ (thickening δ s) := by { rw ←add_ball_zero, exact hs.add (convex_ball 0 _) } lemma convex.cthickening (hs : convex ℝ s) (δ : ℝ) : convex ℝ (cthickening δ s) := begin obtain hδ | hδ := le_total 0 δ, { rw cthickening_eq_Inter_thickening hδ, exact convex_Inter₂ (λ _ _, hs.thickening _) }, { rw cthickening_of_nonpos hδ, exact hs.closure } end /-- If `s`, `t` are disjoint convex sets, `s` is compact and `t` is closed then we can find open disjoint convex sets containing them. -/ lemma disjoint.exists_open_convexes (disj : disjoint s t) (hs₁ : convex ℝ s) (hs₂ : is_compact s) (ht₁ : convex ℝ t) (ht₂ : is_closed t) : ∃ u v, is_open u ∧ is_open v ∧ convex ℝ u ∧ convex ℝ v ∧ s ⊆ u ∧ t ⊆ v ∧ disjoint u v := let ⟨δ, hδ, hst⟩ := disj.exists_thickenings hs₂ ht₂ in ⟨_, _, is_open_thickening, is_open_thickening, hs₁.thickening _, ht₁.thickening _, self_subset_thickening hδ _, self_subset_thickening hδ _, hst⟩ /-- Given a point `x` in the convex hull of `s` and a point `y`, there exists a point of `s` at distance at least `dist x y` from `y`. -/ lemma convex_hull_exists_dist_ge {s : set E} {x : E} (hx : x ∈ convex_hull ℝ s) (y : E) : ∃ x' ∈ s, dist x y ≤ dist x' y := (convex_on_dist y (convex_convex_hull ℝ _)).exists_ge_of_mem_convex_hull hx /-- Given a point `x` in the convex hull of `s` and a point `y` in the convex hull of `t`, there exist points `x' ∈ s` and `y' ∈ t` at distance at least `dist x y`. -/ lemma convex_hull_exists_dist_ge2 {s t : set E} {x y : E} (hx : x ∈ convex_hull ℝ s) (hy : y ∈ convex_hull ℝ t) : ∃ (x' ∈ s) (y' ∈ t), dist x y ≤ dist x' y' := begin rcases convex_hull_exists_dist_ge hx y with ⟨x', hx', Hx'⟩, rcases convex_hull_exists_dist_ge hy x' with ⟨y', hy', Hy'⟩, use [x', hx', y', hy'], exact le_trans Hx' (dist_comm y x' ▸ dist_comm y' x' ▸ Hy') end /-- Emetric diameter of the convex hull of a set `s` equals the emetric diameter of `s. -/ @[simp] lemma convex_hull_ediam (s : set E) : emetric.diam (convex_hull ℝ s) = emetric.diam s := begin refine (emetric.diam_le $ λ x hx y hy, _).antisymm (emetric.diam_mono $ subset_convex_hull ℝ s), rcases convex_hull_exists_dist_ge2 hx hy with ⟨x', hx', y', hy', H⟩, rw edist_dist, apply le_trans (ennreal.of_real_le_of_real H), rw ← edist_dist, exact emetric.edist_le_diam_of_mem hx' hy' end /-- Diameter of the convex hull of a set `s` equals the emetric diameter of `s. -/ @[simp] lemma convex_hull_diam (s : set E) : metric.diam (convex_hull ℝ s) = metric.diam s := by simp only [metric.diam, convex_hull_ediam] /-- Convex hull of `s` is bounded if and only if `s` is bounded. -/ @[simp] lemma bounded_convex_hull {s : set E} : metric.bounded (convex_hull ℝ s) ↔ metric.bounded s := by simp only [metric.bounded_iff_ediam_ne_top, convex_hull_ediam] @[priority 100] instance normed_space.path_connected : path_connected_space E := topological_add_group.path_connected @[priority 100] instance normed_space.loc_path_connected : loc_path_connected_space E := loc_path_connected_of_bases (λ x, metric.nhds_basis_ball) (λ x r r_pos, (convex_ball x r).is_path_connected $ by simp [r_pos]) lemma dist_add_dist_of_mem_segment {x y z : E} (h : y ∈ [x -[ℝ] z]) : dist x y + dist y z = dist x z := begin simp only [dist_eq_norm, mem_segment_iff_same_ray] at *, simpa only [sub_add_sub_cancel', norm_sub_rev] using h.norm_add.symm end end normed_space
441370683d726fdbbce137cb9c0aa3fde0a97514
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/src/Init/Lean/Meta/RecursorInfo.lean
297e1192163cbd5eecbf1671ddd4810e9de6ee69
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
14,863
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.Nat.Control import Init.Lean.AuxRecursor import Init.Lean.Util.FindExpr import Init.Lean.Meta.ExprDefEq import Init.Lean.Meta.Message namespace Lean namespace Meta def casesOnSuffix := "casesOn" def recOnSuffix := "recOn" def brecOnSuffix := "brecOn" def mkCasesOnFor (indDeclName : Name) : Name := mkNameStr indDeclName casesOnSuffix def mkRecOnFor (indDeclName : Name) : Name := mkNameStr indDeclName recOnSuffix def mkBRecOnFor (indDeclName : Name) : Name := mkNameStr indDeclName brecOnSuffix inductive RecursorUnivLevelPos | motive -- marks where the universe of the motive should go | majorType (idx : Nat) -- marks where the #idx universe of the major premise type goes instance RecursorUnivLevelPos.hasToString : HasToString RecursorUnivLevelPos := ⟨fun pos => match pos with | RecursorUnivLevelPos.motive => "<motive-univ>" | RecursorUnivLevelPos.majorType idx => toString idx⟩ structure RecursorInfo := (recursorName : Name) (typeName : Name) (univLevelPos : List RecursorUnivLevelPos) (depElim : Bool) (recursive : Bool) (numArgs : Nat) -- Total number of arguments (majorPos : Nat) (paramsPos : List (Option Nat)) -- Position of the recursor parameters in the major premise, instance implicit arguments are `none` (indicesPos : List Nat) -- Position of the recursor indices in the major premise (produceMotive : List Bool) -- If the i-th element is true then i-th minor premise produces the motive namespace RecursorInfo def numParams (info : RecursorInfo) : Nat := info.paramsPos.length def numIndices (info : RecursorInfo) : Nat := info.indicesPos.length def motivePos (info : RecursorInfo) : Nat := info.numParams def firstIndexPos (info : RecursorInfo) : Nat := info.majorPos - info.numIndices def isMinor (info : RecursorInfo) (pos : Nat) : Bool := if pos ≤ info.motivePos then false else if info.firstIndexPos ≤ pos && pos ≤ info.majorPos then false else true def numMinors (info : RecursorInfo) : Nat := let r := info.numArgs; let r := r - info.motivePos - 1; r - (info.majorPos + 1 - info.firstIndexPos) instance : HasToString RecursorInfo := ⟨fun info => "{\n" ++ " name := " ++ toString info.recursorName ++ "\n" ++ " type := " ++ toString info.typeName ++ "\n" ++ " univs := " ++ toString info.univLevelPos ++ "\n" ++ " depElim := " ++ toString info.depElim ++ "\n" ++ " recursive := " ++ toString info.recursive ++ "\n" ++ " numArgs := " ++ toString info.numArgs ++ "\n" ++ " numParams := " ++ toString info.numParams ++ "\n" ++ " numIndices := " ++ toString info.numIndices ++ "\n" ++ " numMinors := " ++ toString info.numMinors ++ "\n" ++ " major := " ++ toString info.majorPos ++ "\n" ++ " motive := " ++ toString info.motivePos ++ "\n" ++ " paramsAtMajor := " ++ toString info.paramsPos ++ "\n" ++ " indicesAtMajor := " ++ toString info.indicesPos ++ "\n" ++ " produceMotive := " ++ toString info.produceMotive ++ "\n" ++ "}"⟩ end RecursorInfo private def mkRecursorInfoForKernelRec (declName : Name) (val : RecursorVal) : MetaM RecursorInfo := do indInfo ← getConstInfo val.getInduct; match indInfo with | ConstantInfo.inductInfo ival => let numLParams := ival.lparams.length; let univLevelPos := (List.range numLParams).map RecursorUnivLevelPos.majorType; let univLevelPos := if val.lparams.length == numLParams then univLevelPos else RecursorUnivLevelPos.motive :: univLevelPos; let produceMotive := List.replicate val.nminors true; let paramsPos := (List.range val.nparams).map some; let indicesPos := (List.range val.nindices).map (fun pos => val.nparams + pos); let numArgs := val.nindices + val.nparams + val.nminors + val.nmotives + 1; pure { recursorName := declName, typeName := val.getInduct, univLevelPos := univLevelPos, majorPos := val.getMajorIdx, depElim := true, recursive := ival.isRec, produceMotive := produceMotive, paramsPos := paramsPos, indicesPos := indicesPos, numArgs := numArgs } | _ => throw $ Exception.other "ill-formed builtin recursor" private def getMajorPosIfAuxRecursor? (declName : Name) (majorPos? : Option Nat) : MetaM (Option Nat) := if majorPos?.isSome then pure majorPos? else do env ← getEnv; if !isAuxRecursor env declName then pure none else match declName with | Name.str p s _ => if s != recOnSuffix && s != casesOnSuffix && s != brecOnSuffix then pure none else do recInfo ← getConstInfo (mkRecFor p); match recInfo with | ConstantInfo.recInfo val => pure (some (val.nparams + val.nindices + (if s == casesOnSuffix then 1 else val.nmotives))) | _ => throw $ Exception.other "unexpected recursor information" | _ => pure none private def checkMotive (declName : Name) (motive : Expr) (motiveArgs : Array Expr) : MetaM Unit := unless (motive.isFVar && motiveArgs.all Expr.isFVar) $ throw $ Exception.other ("invalid user defined recursor '" ++ toString declName ++ "', result type must be of the form (C t), " ++ "where C is a bound variable, and t is a (possibly empty) sequence of bound variables") /- Compute number of parameters for (user-defined) recursor. We assume a parameter is anything that occurs before the motive -/ private partial def getNumParams (xs : Array Expr) (motive : Expr) : Nat → Nat | i => if h : i < xs.size then let x := xs.get ⟨i, h⟩; if motive == x then i else getNumParams (i+1) else i private def getMajorPosDepElim (declName : Name) (majorPos? : Option Nat) (xs : Array Expr) (motive : Expr) (motiveArgs : Array Expr) : MetaM (Expr × Nat × Bool) := do match majorPos? with | some majorPos => if h : majorPos < xs.size then let major := xs.get ⟨majorPos, h⟩; let depElim := motiveArgs.contains major; pure (major, majorPos, depElim) else throw $ Exception.other ("invalid major premise position for user defined recursor, recursor has only " ++ toString xs.size ++ " arguments") | none => do when motiveArgs.isEmpty $ throw $ Exception.other ("invalid user defined recursor, '" ++ toString declName ++ "' does not support dependent elimination, " ++ "and position of the major premise was not specified " ++ "(solution: set attribute '[recursor <pos>]', where <pos> is the position of the major premise)"); let major := motiveArgs.back; match xs.getIdx? major with | some majorPos => pure (major, majorPos, true) | none => throw $ Exception.other ("ill-formed recursor '" ++ toString declName ++ "'") private def getParamsPos (declName : Name) (xs : Array Expr) (numParams : Nat) (Iargs : Array Expr) : MetaM (List (Option Nat)) := do paramsPos ← numParams.foldM (fun i (paramsPos : Array (Option Nat)) => do let x := xs.get! i; j? ← Iargs.findIdxM? $ fun Iarg => isDefEq Iarg x; match j? with | some j => pure $ paramsPos.push (some j) | none => do localDecl ← getLocalDecl x.fvarId!; if localDecl.binderInfo.isInstImplicit then pure $ paramsPos.push none else throw $ Exception.other ("invalid user defined recursor '" ++ toString declName ++ "' , type of the major premise does not contain the recursor parameter")) #[]; pure paramsPos.toList private def getIndicesPos (declName : Name) (xs : Array Expr) (majorPos numIndices : Nat) (Iargs : Array Expr) : MetaM (List Nat) := do indicesPos ← numIndices.foldM (fun i (indicesPos : Array Nat) => do let i := majorPos - numIndices + i; let x := xs.get! i; -- trace! `Meta ("getIndicesPos " ++ toString i ++ ": " ++ x); j? ← Iargs.findIdxM? $ fun Iarg => isDefEq Iarg x; match j? with | some j => pure $ indicesPos.push j | none => throw $ Exception.other ("invalid user defined recursor '" ++ toString declName ++ "' , type of the major premise does not contain the recursor index")) #[]; pure indicesPos.toList private def getMotiveLevel (declName : Name) (motiveResultType : Expr) : MetaM Level := match motiveResultType with | Expr.sort u@(Level.zero _) _ => pure u | Expr.sort u@(Level.param _ _) _ => pure u | _ => throw $ Exception.other ("invalid user defined recursor '" ++ toString declName ++ "' , motive result sort must be Prop or (Sort u) where u is a universe level parameter") private def getUnivLevelPos (declName : Name) (lparams : List Name) (motiveLvl : Level) (Ilevels : List Level) : MetaM (List RecursorUnivLevelPos) := do let Ilevels := Ilevels.toArray; univLevelPos ← lparams.foldlM (fun (univLevelPos : Array RecursorUnivLevelPos) p => if motiveLvl == mkLevelParam p then pure $ univLevelPos.push RecursorUnivLevelPos.motive else match Ilevels.findIdx? $ fun u => u == mkLevelParam p with | some i => pure $ univLevelPos.push $ RecursorUnivLevelPos.majorType i | none => throw $ Exception.other ("invalid user defined recursor '" ++ toString declName ++ "' , major premise type does not contain universe level parameter '" ++ toString p ++ "'")) #[]; pure univLevelPos.toList private def getProduceMotiveAndRecursive (xs : Array Expr) (numParams numIndices majorPos : Nat) (motive : Expr) : MetaM (List Bool × Bool) := do (produceMotive, rec) ← xs.size.foldM (fun i (p : Array Bool × Bool) => if i < numParams + 1 then pure p -- skip parameters and motive else if majorPos - numIndices ≤ i && i ≤ majorPos then pure p -- skip indices and major premise else do -- process minor premise let (produceMotive, rec) := p; let x := xs.get! i; xType ← inferType x; forallTelescopeReducing xType $ fun minorArgs minorResultType => minorResultType.withApp $ fun res _ => do -- trace! `Meta ("xType: " ++ xType ++ ", motive: " ++ motive ++ ", " ++ minorArgs ++ ", " ++ res); let produceMotive := produceMotive.push (res == motive); rec ← if rec then pure rec else minorArgs.anyM $ fun minorArg => do { minorArgType ← inferType minorArg; pure $ (minorArgType.find? $ fun e => e == motive).isSome }; pure (produceMotive, rec)) (#[], false); pure (produceMotive.toList, rec) private def checkMotiveResultType (declName : Name) (motiveArgs : Array Expr) (motiveResultType : Expr) (motiveTypeParams : Array Expr) : MetaM Unit := when (!motiveResultType.isSort || motiveArgs.size != motiveTypeParams.size) $ throw $ Exception.other ("invalid user defined recursor '" ++ toString declName ++ "', motive must have a type of the form " ++ "(C : Pi (i : B A), I A i -> Type), where A is (possibly empty) sequence of variables (aka parameters), " ++ "(i : B A) is a (possibly empty) telescope (aka indices), and I is a constant") private def mkRecursorInfoAux (cinfo : ConstantInfo) (majorPos? : Option Nat) : MetaM RecursorInfo := do let declName := cinfo.name; majorPos? ← getMajorPosIfAuxRecursor? declName majorPos?; forallTelescopeReducing cinfo.type $ fun xs type => type.withApp $ fun motive motiveArgs => do checkMotive declName motive motiveArgs; let numParams := getNumParams xs motive 0; (major, majorPos, depElim) ← getMajorPosDepElim declName majorPos? xs motive motiveArgs; let numIndices := if depElim then motiveArgs.size - 1 else motiveArgs.size; when (majorPos < numIndices) $ throw $ Exception.other ("invalid user defined recursor '" ++ toString declName ++ "', indices must occur before major premise"); majorType ← inferType major; majorType.withApp $ fun I Iargs => match I with | Expr.const Iname Ilevels _ => do paramsPos ← getParamsPos declName xs numParams Iargs; indicesPos ← getIndicesPos declName xs majorPos numIndices Iargs; motiveType ← inferType motive; forallTelescopeReducing motiveType $ fun motiveTypeParams motiveResultType => do checkMotiveResultType declName motiveArgs motiveResultType motiveTypeParams; motiveLvl ← getMotiveLevel declName motiveResultType; univLevelPos ← getUnivLevelPos declName cinfo.lparams motiveLvl Ilevels; (produceMotive, recursive) ← getProduceMotiveAndRecursive xs numParams numIndices majorPos motive; pure { recursorName := declName, typeName := Iname, univLevelPos := univLevelPos, majorPos := majorPos, depElim := depElim, recursive := recursive, produceMotive := produceMotive, paramsPos := paramsPos, indicesPos := indicesPos, numArgs := xs.size } | _ => throw $ Exception.other ("invalid user defined recursor '" ++ toString declName ++ "', type of the major premise must be of the form (I ...), where I is a constant") private def syntaxToMajorPos (stx : Syntax) : Except String Nat := match stx with | Syntax.node _ args => if args.size == 0 then Except.error "unexpected kind of argument" else match (args.get! 0).isNatLit? with | some idx => if idx == 0 then Except.error "major premise position must be greater than 0" else pure (idx - 1) | none => Except.error "unexpected kind of argument" | _ => Except.error "unexpected kind of argument" private def mkRecursorInfoCore (declName : Name) (majorPos? : Option Nat := none) : MetaM RecursorInfo := do cinfo ← getConstInfo declName; match cinfo with | ConstantInfo.recInfo val => mkRecursorInfoForKernelRec declName val | _ => mkRecursorInfoAux cinfo majorPos? def mkRecursorAttr : IO (ParametricAttribute Nat) := registerParametricAttribute `recursor "user defined recursor, numerical parameter specifies position of the major premise" (fun _ _ => syntaxToMajorPos) (fun env declName majorPos => match Meta.run env (mkRecursorInfoCore declName (some majorPos)) with | Except.ok _ => pure env | Except.error ex => Except.error $ toString ex) @[init mkRecursorAttr] constant recursorAttribute : ParametricAttribute Nat := arbitrary _ def getMajorPos? (env : Environment) (declName : Name) : Option Nat := recursorAttribute.getParam env declName def mkRecursorInfo (declName : Name) (majorPos? : Option Nat := none) : MetaM RecursorInfo := do cinfo ← getConstInfo declName; match cinfo with | ConstantInfo.recInfo val => mkRecursorInfoForKernelRec declName val | _ => match majorPos? with | none => do env ← getEnv; mkRecursorInfoAux cinfo (getMajorPos? env declName) | _ => mkRecursorInfoAux cinfo majorPos? end Meta end Lean
a2b43cee0b3745b52ebb3c39e6f06529e71ddb86
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/algebra/group/opposite.lean
c468905404733e1e0ca29e9b83621adfc102f1bd
[ "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
16,282
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.group.inj_surj import algebra.group.commute import algebra.opposites import data.equiv.mul_add /-! # Group structures on the multiplicative and additive opposites -/ universes u v variables (α : Type u) namespace mul_opposite /-! ### Additive structures on `αᵐᵒᵖ` -/ instance [add_semigroup α] : add_semigroup (αᵐᵒᵖ) := unop_injective.add_semigroup _ (λ x y, rfl) instance [add_left_cancel_semigroup α] : add_left_cancel_semigroup αᵐᵒᵖ := unop_injective.add_left_cancel_semigroup _ (λ x y, rfl) instance [add_right_cancel_semigroup α] : add_right_cancel_semigroup αᵐᵒᵖ := unop_injective.add_right_cancel_semigroup _ (λ x y, rfl) instance [add_comm_semigroup α] : add_comm_semigroup αᵐᵒᵖ := { add_comm := λ x y, unop_injective $ add_comm (unop x) (unop y), .. mul_opposite.add_semigroup α } instance [add_zero_class α] : add_zero_class αᵐᵒᵖ := unop_injective.add_zero_class _ rfl (λ x y, rfl) instance [add_monoid α] : add_monoid αᵐᵒᵖ := unop_injective.add_monoid_smul _ rfl (λ _ _, rfl) (λ _ _, rfl) instance [add_comm_monoid α] : add_comm_monoid αᵐᵒᵖ := { .. mul_opposite.add_monoid α, .. mul_opposite.add_comm_semigroup α } instance [sub_neg_monoid α] : sub_neg_monoid αᵐᵒᵖ := unop_injective.sub_neg_monoid_smul _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) instance [add_group α] : add_group αᵐᵒᵖ := unop_injective.add_group_smul _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) instance [add_comm_group α] : add_comm_group αᵐᵒᵖ := { .. mul_opposite.add_group α, .. mul_opposite.add_comm_monoid α } /-! ### Multiplicative structures on `αᵐᵒᵖ` We also generate additive structures on `αᵃᵒᵖ` using `to_additive` -/ @[to_additive] instance [semigroup α] : semigroup αᵐᵒᵖ := { mul_assoc := λ x y z, unop_injective $ eq.symm $ mul_assoc (unop z) (unop y) (unop x), .. mul_opposite.has_mul α } @[to_additive] instance [right_cancel_semigroup α] : left_cancel_semigroup αᵐᵒᵖ := { mul_left_cancel := λ x y z H, unop_injective $ mul_right_cancel $ op_injective H, .. mul_opposite.semigroup α } @[to_additive] instance [left_cancel_semigroup α] : right_cancel_semigroup αᵐᵒᵖ := { mul_right_cancel := λ x y z H, unop_injective $ mul_left_cancel $ op_injective H, .. mul_opposite.semigroup α } @[to_additive] instance [comm_semigroup α] : comm_semigroup αᵐᵒᵖ := { mul_comm := λ x y, unop_injective $ mul_comm (unop y) (unop x), .. mul_opposite.semigroup α } @[to_additive] instance [mul_one_class α] : mul_one_class αᵐᵒᵖ := { one_mul := λ x, unop_injective $ mul_one $ unop x, mul_one := λ x, unop_injective $ one_mul $ unop x, .. mul_opposite.has_mul α, .. mul_opposite.has_one α } @[to_additive] instance [monoid α] : monoid αᵐᵒᵖ := { npow := λ n x, op $ x.unop ^ n, npow_zero' := λ x, unop_injective $ monoid.npow_zero' x.unop, npow_succ' := λ n x, unop_injective $ pow_succ' x.unop n, .. mul_opposite.semigroup α, .. mul_opposite.mul_one_class α } @[to_additive] instance [right_cancel_monoid α] : left_cancel_monoid αᵐᵒᵖ := { .. mul_opposite.left_cancel_semigroup α, .. mul_opposite.monoid α } @[to_additive] instance [left_cancel_monoid α] : right_cancel_monoid αᵐᵒᵖ := { .. mul_opposite.right_cancel_semigroup α, .. mul_opposite.monoid α } @[to_additive] instance [cancel_monoid α] : cancel_monoid αᵐᵒᵖ := { .. mul_opposite.right_cancel_monoid α, .. mul_opposite.left_cancel_monoid α } @[to_additive] instance [comm_monoid α] : comm_monoid αᵐᵒᵖ := { .. mul_opposite.monoid α, .. mul_opposite.comm_semigroup α } @[to_additive] instance [cancel_comm_monoid α] : cancel_comm_monoid αᵐᵒᵖ := { .. mul_opposite.cancel_monoid α, .. mul_opposite.comm_monoid α } @[to_additive] instance [div_inv_monoid α] : div_inv_monoid αᵐᵒᵖ := { zpow := λ n x, op $ x.unop ^ n, zpow_zero' := λ x, unop_injective $ div_inv_monoid.zpow_zero' x.unop, zpow_succ' := λ n x, unop_injective $ by rw [unop_op, zpow_of_nat, zpow_of_nat, pow_succ', unop_mul, unop_op], zpow_neg' := λ z x, unop_injective $ div_inv_monoid.zpow_neg' z x.unop, .. mul_opposite.monoid α, .. mul_opposite.has_inv α } @[to_additive] instance [group α] : group αᵐᵒᵖ := { mul_left_inv := λ x, unop_injective $ mul_inv_self $ unop x, .. mul_opposite.div_inv_monoid α, } @[to_additive] instance [comm_group α] : comm_group αᵐᵒᵖ := { .. mul_opposite.group α, .. mul_opposite.comm_monoid α } variable {α} @[simp, to_additive] lemma semiconj_by_op [has_mul α] {a x y : α} : semiconj_by (op a) (op y) (op x) ↔ semiconj_by a x y := by simp only [semiconj_by, ← op_mul, op_inj, eq_comm] @[simp, to_additive] lemma semiconj_by_unop [has_mul α] {a x y : αᵐᵒᵖ} : semiconj_by (unop a) (unop y) (unop x) ↔ semiconj_by a x y := by conv_rhs { rw [← op_unop a, ← op_unop x, ← op_unop y, semiconj_by_op] } @[to_additive] lemma _root_.semiconj_by.op [has_mul α] {a x y : α} (h : semiconj_by a x y) : semiconj_by (op a) (op y) (op x) := semiconj_by_op.2 h @[to_additive] lemma _root_.semiconj_by.unop [has_mul α] {a x y : αᵐᵒᵖ} (h : semiconj_by a x y) : semiconj_by (unop a) (unop y) (unop x) := semiconj_by_unop.2 h @[to_additive] lemma _root_.commute.op [has_mul α] {x y : α} (h : commute x y) : commute (op x) (op y) := h.op @[to_additive] lemma commute.unop [has_mul α] {x y : αᵐᵒᵖ} (h : commute x y) : commute (unop x) (unop y) := h.unop @[simp, to_additive] lemma commute_op [has_mul α] {x y : α} : commute (op x) (op y) ↔ commute x y := semiconj_by_op @[simp, to_additive] lemma commute_unop [has_mul α] {x y : αᵐᵒᵖ} : commute (unop x) (unop y) ↔ commute x y := semiconj_by_unop /-- The function `mul_opposite.op` is an additive equivalence. -/ @[simps { fully_applied := ff, simp_rhs := tt }] def op_add_equiv [has_add α] : α ≃+ αᵐᵒᵖ := { map_add' := λ a b, rfl, .. op_equiv } @[simp] lemma op_add_equiv_to_equiv [has_add α] : (op_add_equiv : α ≃+ αᵐᵒᵖ).to_equiv = op_equiv := rfl end mul_opposite /-! ### Multiplicative structures on `αᵃᵒᵖ` -/ namespace add_opposite instance [semigroup α] : semigroup (αᵃᵒᵖ) := unop_injective.semigroup _ (λ x y, rfl) instance [left_cancel_semigroup α] : left_cancel_semigroup αᵃᵒᵖ := unop_injective.left_cancel_semigroup _ (λ x y, rfl) instance [right_cancel_semigroup α] : right_cancel_semigroup αᵃᵒᵖ := unop_injective.right_cancel_semigroup _ (λ x y, rfl) instance [comm_semigroup α] : comm_semigroup αᵃᵒᵖ := { mul_comm := λ x y, unop_injective $ mul_comm (unop x) (unop y), .. add_opposite.semigroup α } instance [mul_one_class α] : mul_one_class αᵃᵒᵖ := unop_injective.mul_one_class _ rfl (λ x y, rfl) instance {β} [has_pow α β] : has_pow αᵃᵒᵖ β := { pow := λ a b, op (unop a ^ b) } @[simp] lemma op_pow {β} [has_pow α β] (a : α) (b : β) : op (a ^ b) = op a ^ b := rfl @[simp] lemma unop_pow {β} [has_pow α β] (a : αᵃᵒᵖ) (b : β) : unop (a ^ b) = unop a ^ b := rfl instance [monoid α] : monoid αᵃᵒᵖ := unop_injective.monoid_pow _ rfl (λ _ _, rfl) (λ _ _, rfl) instance [comm_monoid α] : comm_monoid αᵃᵒᵖ := { .. add_opposite.monoid α, .. add_opposite.comm_semigroup α } instance [div_inv_monoid α] : div_inv_monoid αᵃᵒᵖ := unop_injective.div_inv_monoid_pow _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) instance [group α] : group αᵃᵒᵖ := unop_injective.group_pow _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) instance [comm_group α] : comm_group αᵃᵒᵖ := { .. add_opposite.group α, .. add_opposite.comm_monoid α } variable {α} /-- The function `add_opposite.op` is a multiplicative equivalence. -/ @[simps { fully_applied := ff, simp_rhs := tt }] def op_mul_equiv [has_mul α] : α ≃* αᵃᵒᵖ := { map_mul' := λ a b, rfl, .. op_equiv } @[simp] lemma op_mul_equiv_to_equiv [has_mul α] : (op_mul_equiv : α ≃* αᵃᵒᵖ).to_equiv = op_equiv := rfl end add_opposite open mul_opposite /-- Inversion on a group is a `mul_equiv` to the opposite group. When `G` is commutative, there is `mul_equiv.inv`. -/ @[to_additive "Negation on an additive group is an `add_equiv` to the opposite group. When `G` is commutative, there is `add_equiv.inv`.", simps { fully_applied := ff, simp_rhs := tt }] def mul_equiv.inv' (G : Type*) [group G] : G ≃* Gᵐᵒᵖ := { map_mul' := λ x y, unop_injective $ mul_inv_rev x y, .. (equiv.inv G).trans op_equiv } /-- A monoid homomorphism `f : M →* N` such that `f x` commutes with `f y` for all `x, y` defines a monoid homomorphism to `Nᵐᵒᵖ`. -/ @[to_additive "An additive monoid homomorphism `f : M →+ N` such that `f x` additively commutes with `f y` for all `x, y` defines an additive monoid homomorphism to `Sᵃᵒᵖ`.", simps {fully_applied := ff}] def monoid_hom.to_opposite {M N : Type*} [mul_one_class M] [mul_one_class N] (f : M →* N) (hf : ∀ x y, commute (f x) (f y)) : M →* Nᵐᵒᵖ := { to_fun := mul_opposite.op ∘ f, map_one' := congr_arg op f.map_one, map_mul' := λ x y, by simp [(hf x y).eq] } /-- A monoid homomorphism `f : M →* N` such that `f x` commutes with `f y` for all `x, y` defines a monoid homomorphism from `Mᵐᵒᵖ`. -/ @[to_additive "An additive monoid homomorphism `f : M →+ N` such that `f x` additively commutes with `f y` for all `x`, `y` defines an additive monoid homomorphism from `Mᵃᵒᵖ`.", simps {fully_applied := ff}] def monoid_hom.from_opposite {M N : Type*} [mul_one_class M] [mul_one_class N] (f : M →* N) (hf : ∀ x y, commute (f x) (f y)) : Mᵐᵒᵖ →* N := { to_fun := f ∘ mul_opposite.unop, map_one' := f.map_one, map_mul' := λ x y, (f.map_mul _ _).trans (hf _ _).eq } /-- The units of the opposites are equivalent to the opposites of the units. -/ @[to_additive "The additive units of the additive opposites are equivalent to the additive opposites of the additive units."] def units.op_equiv {M} [monoid M] : (Mᵐᵒᵖ)ˣ ≃* (Mˣ)ᵐᵒᵖ := { to_fun := λ u, op ⟨unop u, unop ↑(u⁻¹), op_injective u.4, op_injective u.3⟩, inv_fun := mul_opposite.rec $ λ u, ⟨op ↑(u), op ↑(u⁻¹), unop_injective $ u.4, unop_injective u.3⟩, map_mul' := λ x y, unop_injective $ units.ext $ rfl, left_inv := λ x, units.ext $ by simp, right_inv := λ x, unop_injective $ units.ext $ rfl } @[simp, to_additive] lemma units.coe_unop_op_equiv {M} [monoid M] (u : (Mᵐᵒᵖ)ˣ) : ((units.op_equiv u).unop : M) = unop (u : Mᵐᵒᵖ) := rfl @[simp, to_additive] lemma units.coe_op_equiv_symm {M} [monoid M] (u : (Mˣ)ᵐᵒᵖ) : (units.op_equiv.symm u : Mᵐᵒᵖ) = op (u.unop : M) := rfl /-- A monoid homomorphism `M →* N` can equivalently be viewed as a monoid homomorphism `Mᵐᵒᵖ →* Nᵐᵒᵖ`. This is the action of the (fully faithful) `ᵐᵒᵖ`-functor on morphisms. -/ @[to_additive "An additive monoid homomorphism `M →+ N` can equivalently be viewed as an additive monoid homomorphism `Mᵃᵒᵖ →+ Nᵃᵒᵖ`. This is the action of the (fully faithful) `ᵃᵒᵖ`-functor on morphisms.", simps] def monoid_hom.op {M N} [mul_one_class M] [mul_one_class N] : (M →* N) ≃ (Mᵐᵒᵖ →* Nᵐᵒᵖ) := { to_fun := λ f, { to_fun := op ∘ f ∘ unop, map_one' := congr_arg op f.map_one, map_mul' := λ x y, unop_injective (f.map_mul y.unop x.unop) }, inv_fun := λ f, { to_fun := unop ∘ f ∘ op, map_one' := congr_arg unop f.map_one, map_mul' := λ x y, congr_arg unop (f.map_mul (op y) (op x)) }, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext x, simp } } /-- The 'unopposite' of a monoid homomorphism `Mᵐᵒᵖ →* Nᵐᵒᵖ`. Inverse to `monoid_hom.op`. -/ @[simp, to_additive "The 'unopposite' of an additive monoid homomorphism `Mᵃᵒᵖ →+ Nᵃᵒᵖ`. Inverse to `add_monoid_hom.op`."] def monoid_hom.unop {M N} [mul_one_class M] [mul_one_class N] : (Mᵐᵒᵖ →* Nᵐᵒᵖ) ≃ (M →* N) := monoid_hom.op.symm /-- An additive homomorphism `M →+ N` can equivalently be viewed as an additive homomorphism `Mᵐᵒᵖ →+ Nᵐᵒᵖ`. This is the action of the (fully faithful) `ᵐᵒᵖ`-functor on morphisms. -/ @[simps] def add_monoid_hom.mul_op {M N} [add_zero_class M] [add_zero_class N] : (M →+ N) ≃ (Mᵐᵒᵖ →+ Nᵐᵒᵖ) := { to_fun := λ f, { to_fun := op ∘ f ∘ unop, map_zero' := unop_injective f.map_zero, map_add' := λ x y, unop_injective (f.map_add x.unop y.unop) }, inv_fun := λ f, { to_fun := unop ∘ f ∘ op, map_zero' := congr_arg unop f.map_zero, map_add' := λ x y, congr_arg unop (f.map_add (op x) (op y)) }, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, simp } } /-- The 'unopposite' of an additive monoid hom `αᵐᵒᵖ →+ βᵐᵒᵖ`. Inverse to `add_monoid_hom.mul_op`. -/ @[simp] def add_monoid_hom.mul_unop {α β} [add_zero_class α] [add_zero_class β] : (αᵐᵒᵖ →+ βᵐᵒᵖ) ≃ (α →+ β) := add_monoid_hom.mul_op.symm /-- A iso `α ≃+ β` can equivalently be viewed as an iso `αᵐᵒᵖ ≃+ βᵐᵒᵖ`. -/ @[simps] def add_equiv.mul_op {α β} [has_add α] [has_add β] : (α ≃+ β) ≃ (αᵐᵒᵖ ≃+ βᵐᵒᵖ) := { to_fun := λ f, op_add_equiv.symm.trans (f.trans op_add_equiv), inv_fun := λ f, op_add_equiv.trans (f.trans op_add_equiv.symm), left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, simp } } /-- The 'unopposite' of an iso `αᵐᵒᵖ ≃+ βᵐᵒᵖ`. Inverse to `add_equiv.mul_op`. -/ @[simp] def add_equiv.mul_unop {α β} [has_add α] [has_add β] : (αᵐᵒᵖ ≃+ βᵐᵒᵖ) ≃ (α ≃+ β) := add_equiv.mul_op.symm /-- A iso `α ≃* β` can equivalently be viewed as an iso `αᵐᵒᵖ ≃* βᵐᵒᵖ`. -/ @[to_additive "A iso `α ≃+ β` can equivalently be viewed as an iso `αᵃᵒᵖ ≃+ βᵃᵒᵖ`.", simps] def mul_equiv.op {α β} [has_mul α] [has_mul β] : (α ≃* β) ≃ (αᵐᵒᵖ ≃* βᵐᵒᵖ) := { to_fun := λ f, { to_fun := op ∘ f ∘ unop, inv_fun := op ∘ f.symm ∘ unop, left_inv := λ x, unop_injective (f.symm_apply_apply x.unop), right_inv := λ x, unop_injective (f.apply_symm_apply x.unop), map_mul' := λ x y, unop_injective (f.map_mul y.unop x.unop) }, inv_fun := λ f, { to_fun := unop ∘ f ∘ op, inv_fun := unop ∘ f.symm ∘ op, left_inv := λ x, by simp, right_inv := λ x, by simp, map_mul' := λ x y, congr_arg unop (f.map_mul (op y) (op x)) }, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, simp } } /-- The 'unopposite' of an iso `αᵐᵒᵖ ≃* βᵐᵒᵖ`. Inverse to `mul_equiv.op`. -/ @[simp, to_additive "The 'unopposite' of an iso `αᵃᵒᵖ ≃+ βᵃᵒᵖ`. Inverse to `add_equiv.op`."] def mul_equiv.unop {α β} [has_mul α] [has_mul β] : (αᵐᵒᵖ ≃* βᵐᵒᵖ) ≃ (α ≃* β) := mul_equiv.op.symm section ext /-- This ext lemma change equalities on `αᵐᵒᵖ →+ β` to equalities on `α →+ β`. This is useful because there are often ext lemmas for specific `α`s that will apply to an equality of `α →+ β` such as `finsupp.add_hom_ext'`. -/ @[ext] lemma add_monoid_hom.mul_op_ext {α β} [add_zero_class α] [add_zero_class β] (f g : αᵐᵒᵖ →+ β) (h : f.comp (op_add_equiv : α ≃+ αᵐᵒᵖ).to_add_monoid_hom = g.comp (op_add_equiv : α ≃+ αᵐᵒᵖ).to_add_monoid_hom) : f = g := add_monoid_hom.ext $ mul_opposite.rec $ λ x, (add_monoid_hom.congr_fun h : _) x end ext
b9180eda40b336ddaef2b09c4edb770b0a6691bc
eb9357a70318e50e095b58730bebfe0cffee457f
/lean/love06_monads_exercise_sheet.lean
1c137b44c4f31346f7057137ac5a7053551e3a50
[]
no_license
Vierkantor/logical_verification_2021
7485dd916953131d501760f023d5b30fbb74d36a
9500b9c194e22a9ab4067321cfed7a1f445afcfc
refs/heads/main
1,692,560,845,086
1,624,721,275,000
1,624,721,275,000
416,354,079
0
0
null
null
null
null
UTF-8
Lean
false
false
6,334
lean
import .love06_monads_demo /-! # LoVe Exercise 6: Monads -/ set_option pp.beta true set_option pp.generalized_field_notation false namespace LoVe /-! ## Question 1: A State Monad with Failure We introduce a richer notion of lawful monad that provides an `orelse` operator `<|>` satisfying some laws, given below. `emp` denotes failure. `x <|> y` tries `x` first, falling back on `y` on failure. -/ @[class] structure lawful_monad_with_orelse (m : Type → Type) extends lawful_monad m, has_orelse m : Type 1 := (emp {} {α : Type} : m α) (emp_orelse {α : Type} (a : m α) : (emp <|> a) = a) (orelse_emp {α : Type} (a : m α) : (a <|> emp) = a) (orelse_assoc {α : Type} (a b c : m α) : ((a <|> b) <|> c) = (a <|> (b <|> c))) (emp_bind {α β : Type} (f : α → m β) : (emp >>= f) = emp) (bind_emp {α β : Type} (f : m α) : (f >>= (λa, emp : α → m β)) = emp) /-! 1.1. We set up the `option` type constructor to be a `lawful_monad_with_orelse`. Complete the proofs. Hint: Use `simp [(>>=)]` if you want to unfold the definition of the bind operator. -/ def option.orelse {α : Type} : option α → option α → option α | option.none ma' := ma' | (option.some a) _ := option.some a @[instance] def lawful_monad_with_orelse_option : lawful_monad_with_orelse option := { emp := λα, option.none, orelse := @option.orelse, emp_orelse := sorry, orelse_emp := begin intros α a, cases' a, { refl }, { refl } end, orelse_assoc := sorry, emp_bind := begin intros α β f, refl end, bind_emp := sorry, .. option.lawful_monad } @[simp] lemma option.some_bind {α β : Type} (a : α) (g : α → option β) : (option.some a >>= g) = g a := sorry /-! Let us enable some convenient pattern matching syntax, by instantiating Lean's `monad_fail` type class. (Do not worry if you do not understand what we are referring to.) -/ @[instance] def lawful_monad_with_orelse.monad_fail {m : Type → Type} [lawful_monad_with_orelse m] : monad_fail m := { fail := λα msg, lawful_monad_with_orelse.emp } /-! Now we can write definitions such as the following: -/ def first_of_three {m : Type → Type} [lawful_monad_with_orelse m] (c : m (list ℕ)) : m ℕ := do [n, _, _] ← c, pure n #eval first_of_three (option.some [1]) #eval first_of_three (option.some [1, 2, 3]) #eval first_of_three (option.some [1, 2, 3, 4]) /-! Using `lawful_monad_with_orelse` and the `monad_fail` syntax, we can give a concise definition for the `sum_2_5_7` function seen in the lecture. -/ def sum_2_5_7₇ {m : Type → Type} [lawful_monad_with_orelse m] (c : m (list ℕ)) : m ℕ := do (_ :: n2 :: _ :: _ :: n5 :: _ :: n7 :: _) ← c, pure (n2 + n5 + n7) /-! 1.2. Now we are ready to define `faction σ` ("eff action"): a monad with an internal state of type `σ` that can fail (unlike `action σ`). We start with defining `faction σ α`, where `σ` is the type of the internal state, and `α` is the type of the value stored in the monad. We use `option` to model failure. This means we can also use the monad operations of `option` when defining the monad operations on `faction`. Hints: * Remember that `faction σ α` is an alias for a function type, so you can use pattern matching and `λs, …` to define values of type `faction σ α`. * `faction` is very similar to `action` from the lecture's demo. You can look there for inspiration. -/ def faction (σ : Type) (α : Type) : Type := σ → option (α × σ) /-! 1.3. Define the `get` and `set` function for `faction`, where `get` returns the state passed along the state monad and `set s` changes the state to `s`. -/ def get {σ : Type} : faction σ σ := sorry def set {σ : Type} (s : σ) : faction σ unit := sorry /-! We set up the `>>=` syntax on `faction`: -/ def faction.bind {σ α β : Type} (f : faction σ α) (g : α → faction σ β) : faction σ β | s := f s >>= (λas, g (prod.fst as) (prod.snd as)) @[instance] def faction.has_bind {σ : Type} : has_bind (faction σ) := { bind := @faction.bind σ } lemma faction.bind_apply {σ α β : Type} (f : faction σ α) (g : α → faction σ β) (s : σ) : (f >>= g) s = (f s >>= (λas, g (prod.fst as) (prod.snd as))) := by refl /-! 1.4. Define the operator `pure` for `faction`, in such a way that it will satisfy the three laws. -/ def faction.pure {σ α : Type} (a : α) : faction σ α := sorry /-! We set up the syntax for `pure` on `faction`: -/ @[instance] def faction.has_pure {σ : Type} : has_pure (faction σ) := { pure := @faction.pure σ } lemma faction.pure_apply {σ α : Type} (a : α) (s : σ) : (pure a : faction σ α) s = option.some (a, s) := by refl /-! 1.3. Register `faction` as a monad. Hints: * The `funext` lemma is useful when you need to prove equality between two functions. * `cases' f s` only works when `f s` appears in your goal, so you may need to unfold some constants before you can invoke `cases'`. -/ @[instance] def faction.lawful_monad {σ : Type} : lawful_monad (faction σ) := { pure_bind := begin intros α β a f, apply funext, intro s, refl end, bind_pure := sorry, bind_assoc := sorry, .. faction.has_bind, .. faction.has_pure } /-! ## Question 2: Kleisli Operator The Kleisli operator `>=>` (not to be confused with `>>=`) is useful for pipelining effectful functions. Note that `λa, f a >>= g` is to be parsed as `λa, (f a >>= g)`, not as `(λa, f a) >>= g`. -/ def kleisli {m : Type → Type} [lawful_monad m] {α β γ : Type} (f : α → m β) (g : β → m γ) : α → m γ := λa, f a >>= g infixr ` >=> ` : 90 := kleisli /-! 2.1. Prove that `pure` is a left and right unit for the Kleisli operator. -/ lemma pure_kleisli {m : Type → Type} [lawful_monad m] {α β : Type} (f : α → m β) : (pure >=> f) = f := sorry lemma kleisli_pure {m : Type → Type} [lawful_monad m] {α β : Type} (f : α → m β) : (f >=> pure) = f := sorry /-! 2.2. Prove that the Kleisli operator is associative. -/ lemma kleisli_assoc {m : Type → Type} [lawful_monad m] {α β γ δ : Type} (f : α → m β) (g : β → m γ) (h : γ → m δ) : ((f >=> g) >=> h) = (f >=> (g >=> h)) := sorry end LoVe
faf280c6cf9123c0b1009638fbcdeb8b28c6eafd
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/stage0/src/Init/System/Platform.lean
379b97e1420217995c31b5c3f44fa327dd7091b0
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
641
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.Nat.Basic namespace System namespace Platform @[extern "lean_system_platform_nbits"] constant getNumBits : Unit → Nat := arbitrary _ @[extern "lean_system_platform_windows"] constant getIsWindows : Unit → Bool := arbitrary _ @[extern "lean_system_platform_osx"] constant getIsOSX : Unit → Bool := arbitrary _ def numBits : Nat := getNumBits () def isWindows : Bool := getIsWindows () def isOSX : Bool := getIsOSX () end Platform end System
6ca47df8a3716f3c3aeac84aa398f6b31fd1e7e0
bb31430994044506fa42fd667e2d556327e18dfe
/src/algebraic_geometry/projective_spectrum/topology.lean
dfd2ee4a7847e4f6270b159f71afedbd5c21b891
[ "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
18,511
lean
/- Copyright (c) 2020 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jujian Zhang, Johan Commelin -/ import ring_theory.graded_algebra.homogeneous_ideal import topology.category.Top.basic import topology.sets.opens /-! # Projective spectrum of a graded ring The projective spectrum of a graded commutative ring is the subtype of all homogenous ideals that are prime and do not contain the irrelevant ideal. It is naturally endowed with a topology: the Zariski topology. ## Notation - `R` is a commutative semiring; - `A` is a commutative ring and an `R`-algebra; - `𝒜 : ℕ → submodule R A` is the grading of `A`; ## Main definitions * `projective_spectrum 𝒜`: The projective spectrum of a graded ring `A`, or equivalently, the set of all homogeneous ideals of `A` that is both prime and relevant i.e. not containing irrelevant ideal. Henceforth, we call elements of projective spectrum *relevant homogeneous prime ideals*. * `projective_spectrum.zero_locus 𝒜 s`: The zero locus of a subset `s` of `A` is the subset of `projective_spectrum 𝒜` consisting of all relevant homogeneous prime ideals that contain `s`. * `projective_spectrum.vanishing_ideal t`: The vanishing ideal of a subset `t` of `projective_spectrum 𝒜` is the intersection of points in `t` (viewed as relevant homogeneous prime ideals). * `projective_spectrum.Top`: the topological space of `projective_spectrum 𝒜` endowed with the Zariski topology. -/ noncomputable theory open_locale direct_sum big_operators pointwise open direct_sum set_like Top topological_space category_theory opposite variables {R A: Type*} variables [comm_semiring R] [comm_ring A] [algebra R A] variables (𝒜 : ℕ → submodule R A) [graded_algebra 𝒜] /-- The projective spectrum of a graded commutative ring is the subtype of all homogenous ideals that are prime and do not contain the irrelevant ideal. -/ @[ext, nolint has_nonempty_instance] structure projective_spectrum := (as_homogeneous_ideal : homogeneous_ideal 𝒜) (is_prime : as_homogeneous_ideal.to_ideal.is_prime) (not_irrelevant_le : ¬(homogeneous_ideal.irrelevant 𝒜 ≤ as_homogeneous_ideal)) attribute [instance] projective_spectrum.is_prime namespace projective_spectrum /-- The zero locus of a set `s` of elements of a commutative ring `A` is the set of all relevant homogeneous prime ideals of the ring that contain the set `s`. An element `f` of `A` can be thought of as a dependent function on the projective spectrum of `𝒜`. At a point `x` (a homogeneous prime ideal) the function (i.e., element) `f` takes values in the quotient ring `A` modulo the prime ideal `x`. In this manner, `zero_locus s` is exactly the subset of `projective_spectrum 𝒜` where all "functions" in `s` vanish simultaneously. -/ def zero_locus (s : set A) : set (projective_spectrum 𝒜) := {x | s ⊆ x.as_homogeneous_ideal} @[simp] lemma mem_zero_locus (x : projective_spectrum 𝒜) (s : set A) : x ∈ zero_locus 𝒜 s ↔ s ⊆ x.as_homogeneous_ideal := iff.rfl @[simp] lemma zero_locus_span (s : set A) : zero_locus 𝒜 (ideal.span s) = zero_locus 𝒜 s := by { ext x, exact (submodule.gi _ _).gc s x.as_homogeneous_ideal.to_ideal } variable {𝒜} /-- The vanishing ideal of a set `t` of points of the projective spectrum of a commutative ring `R` is the intersection of all the relevant homogeneous prime ideals in the set `t`. An element `f` of `A` can be thought of as a dependent function on the projective spectrum of `𝒜`. At a point `x` (a homogeneous prime ideal) the function (i.e., element) `f` takes values in the quotient ring `A` modulo the prime ideal `x`. In this manner, `vanishing_ideal t` is exactly the ideal of `A` consisting of all "functions" that vanish on all of `t`. -/ def vanishing_ideal (t : set (projective_spectrum 𝒜)) : homogeneous_ideal 𝒜 := ⨅ (x : projective_spectrum 𝒜) (h : x ∈ t), x.as_homogeneous_ideal lemma coe_vanishing_ideal (t : set (projective_spectrum 𝒜)) : (vanishing_ideal t : set A) = {f | ∀ x : projective_spectrum 𝒜, x ∈ t → f ∈ x.as_homogeneous_ideal} := begin ext f, rw [vanishing_ideal, set_like.mem_coe, ← homogeneous_ideal.mem_iff, homogeneous_ideal.to_ideal_infi, submodule.mem_infi], apply forall_congr (λ x, _), rw [homogeneous_ideal.to_ideal_infi, submodule.mem_infi, homogeneous_ideal.mem_iff], end lemma mem_vanishing_ideal (t : set (projective_spectrum 𝒜)) (f : A) : f ∈ vanishing_ideal t ↔ ∀ x : projective_spectrum 𝒜, x ∈ t → f ∈ x.as_homogeneous_ideal := by rw [← set_like.mem_coe, coe_vanishing_ideal, set.mem_set_of_eq] @[simp] lemma vanishing_ideal_singleton (x : projective_spectrum 𝒜) : vanishing_ideal ({x} : set (projective_spectrum 𝒜)) = x.as_homogeneous_ideal := by simp [vanishing_ideal] lemma subset_zero_locus_iff_le_vanishing_ideal (t : set (projective_spectrum 𝒜)) (I : ideal A) : t ⊆ zero_locus 𝒜 I ↔ I ≤ (vanishing_ideal t).to_ideal := ⟨λ h f k, (mem_vanishing_ideal _ _).mpr (λ x j, (mem_zero_locus _ _ _).mpr (h j) k), λ h, λ x j, (mem_zero_locus _ _ _).mpr (le_trans h (λ f h, ((mem_vanishing_ideal _ _).mp h) x j))⟩ variable (𝒜) /-- `zero_locus` and `vanishing_ideal` form a galois connection. -/ lemma gc_ideal : @galois_connection (ideal A) (set (projective_spectrum 𝒜))ᵒᵈ _ _ (λ I, zero_locus 𝒜 I) (λ t, (vanishing_ideal t).to_ideal) := λ I t, subset_zero_locus_iff_le_vanishing_ideal t I /-- `zero_locus` and `vanishing_ideal` form a galois connection. -/ lemma gc_set : @galois_connection (set A) (set (projective_spectrum 𝒜))ᵒᵈ _ _ (λ s, zero_locus 𝒜 s) (λ t, vanishing_ideal t) := have ideal_gc : galois_connection (ideal.span) coe := (submodule.gi A _).gc, by simpa [zero_locus_span, function.comp] using galois_connection.compose ideal_gc (gc_ideal 𝒜) lemma gc_homogeneous_ideal : @galois_connection (homogeneous_ideal 𝒜) (set (projective_spectrum 𝒜))ᵒᵈ _ _ (λ I, zero_locus 𝒜 I) (λ t, (vanishing_ideal t)) := λ I t, by simpa [show I.to_ideal ≤ (vanishing_ideal t).to_ideal ↔ I ≤ (vanishing_ideal t), from iff.rfl] using subset_zero_locus_iff_le_vanishing_ideal t I.to_ideal lemma subset_zero_locus_iff_subset_vanishing_ideal (t : set (projective_spectrum 𝒜)) (s : set A) : t ⊆ zero_locus 𝒜 s ↔ s ⊆ vanishing_ideal t := (gc_set _) s t lemma subset_vanishing_ideal_zero_locus (s : set A) : s ⊆ vanishing_ideal (zero_locus 𝒜 s) := (gc_set _).le_u_l s lemma ideal_le_vanishing_ideal_zero_locus (I : ideal A) : I ≤ (vanishing_ideal (zero_locus 𝒜 I)).to_ideal := (gc_ideal _).le_u_l I lemma homogeneous_ideal_le_vanishing_ideal_zero_locus (I : homogeneous_ideal 𝒜) : I ≤ vanishing_ideal (zero_locus 𝒜 I) := (gc_homogeneous_ideal _).le_u_l I lemma subset_zero_locus_vanishing_ideal (t : set (projective_spectrum 𝒜)) : t ⊆ zero_locus 𝒜 (vanishing_ideal t) := (gc_ideal _).l_u_le t lemma zero_locus_anti_mono {s t : set A} (h : s ⊆ t) : zero_locus 𝒜 t ⊆ zero_locus 𝒜 s := (gc_set _).monotone_l h lemma zero_locus_anti_mono_ideal {s t : ideal A} (h : s ≤ t) : zero_locus 𝒜 (t : set A) ⊆ zero_locus 𝒜 (s : set A) := (gc_ideal _).monotone_l h lemma zero_locus_anti_mono_homogeneous_ideal {s t : homogeneous_ideal 𝒜} (h : s ≤ t) : zero_locus 𝒜 (t : set A) ⊆ zero_locus 𝒜 (s : set A) := (gc_homogeneous_ideal _).monotone_l h lemma vanishing_ideal_anti_mono {s t : set (projective_spectrum 𝒜)} (h : s ⊆ t) : vanishing_ideal t ≤ vanishing_ideal s := (gc_ideal _).monotone_u h lemma zero_locus_bot : zero_locus 𝒜 ((⊥ : ideal A) : set A) = set.univ := (gc_ideal 𝒜).l_bot @[simp] lemma zero_locus_singleton_zero : zero_locus 𝒜 ({0} : set A) = set.univ := zero_locus_bot _ @[simp] lemma zero_locus_empty : zero_locus 𝒜 (∅ : set A) = set.univ := (gc_set 𝒜).l_bot @[simp] lemma vanishing_ideal_univ : vanishing_ideal (∅ : set (projective_spectrum 𝒜)) = ⊤ := by simpa using (gc_ideal _).u_top lemma zero_locus_empty_of_one_mem {s : set A} (h : (1:A) ∈ s) : zero_locus 𝒜 s = ∅ := set.eq_empty_iff_forall_not_mem.mpr $ λ x hx, (infer_instance : x.as_homogeneous_ideal.to_ideal.is_prime).ne_top $ x.as_homogeneous_ideal.to_ideal.eq_top_iff_one.mpr $ hx h @[simp] lemma zero_locus_singleton_one : zero_locus 𝒜 ({1} : set A) = ∅ := zero_locus_empty_of_one_mem 𝒜 (set.mem_singleton (1 : A)) @[simp] lemma zero_locus_univ : zero_locus 𝒜 (set.univ : set A) = ∅ := zero_locus_empty_of_one_mem _ (set.mem_univ 1) lemma zero_locus_sup_ideal (I J : ideal A) : zero_locus 𝒜 ((I ⊔ J : ideal A) : set A) = zero_locus _ I ∩ zero_locus _ J := (gc_ideal 𝒜).l_sup lemma zero_locus_sup_homogeneous_ideal (I J : homogeneous_ideal 𝒜) : zero_locus 𝒜 ((I ⊔ J : homogeneous_ideal 𝒜) : set A) = zero_locus _ I ∩ zero_locus _ J := (gc_homogeneous_ideal 𝒜).l_sup lemma zero_locus_union (s s' : set A) : zero_locus 𝒜 (s ∪ s') = zero_locus _ s ∩ zero_locus _ s' := (gc_set 𝒜).l_sup lemma vanishing_ideal_union (t t' : set (projective_spectrum 𝒜)) : vanishing_ideal (t ∪ t') = vanishing_ideal t ⊓ vanishing_ideal t' := by ext1; convert (gc_ideal 𝒜).u_inf lemma zero_locus_supr_ideal {γ : Sort*} (I : γ → ideal A) : zero_locus _ ((⨆ i, I i : ideal A) : set A) = (⋂ i, zero_locus 𝒜 (I i)) := (gc_ideal 𝒜).l_supr lemma zero_locus_supr_homogeneous_ideal {γ : Sort*} (I : γ → homogeneous_ideal 𝒜) : zero_locus _ ((⨆ i, I i : homogeneous_ideal 𝒜) : set A) = (⋂ i, zero_locus 𝒜 (I i)) := (gc_homogeneous_ideal 𝒜).l_supr lemma zero_locus_Union {γ : Sort*} (s : γ → set A) : zero_locus 𝒜 (⋃ i, s i) = (⋂ i, zero_locus 𝒜 (s i)) := (gc_set 𝒜).l_supr lemma zero_locus_bUnion (s : set (set A)) : zero_locus 𝒜 (⋃ s' ∈ s, s' : set A) = ⋂ s' ∈ s, zero_locus 𝒜 s' := by simp only [zero_locus_Union] lemma vanishing_ideal_Union {γ : Sort*} (t : γ → set (projective_spectrum 𝒜)) : vanishing_ideal (⋃ i, t i) = (⨅ i, vanishing_ideal (t i)) := homogeneous_ideal.to_ideal_injective $ by convert (gc_ideal 𝒜).u_infi; exact homogeneous_ideal.to_ideal_infi _ lemma zero_locus_inf (I J : ideal A) : zero_locus 𝒜 ((I ⊓ J : ideal A) : set A) = zero_locus 𝒜 I ∪ zero_locus 𝒜 J := set.ext $ λ x, x.is_prime.inf_le lemma union_zero_locus (s s' : set A) : zero_locus 𝒜 s ∪ zero_locus 𝒜 s' = zero_locus 𝒜 ((ideal.span s) ⊓ (ideal.span s'): ideal A) := by { rw zero_locus_inf, simp } lemma zero_locus_mul_ideal (I J : ideal A) : zero_locus 𝒜 ((I * J : ideal A) : set A) = zero_locus 𝒜 I ∪ zero_locus 𝒜 J := set.ext $ λ x, x.is_prime.mul_le lemma zero_locus_mul_homogeneous_ideal (I J : homogeneous_ideal 𝒜) : zero_locus 𝒜 ((I * J : homogeneous_ideal 𝒜) : set A) = zero_locus 𝒜 I ∪ zero_locus 𝒜 J := set.ext $ λ x, x.is_prime.mul_le lemma zero_locus_singleton_mul (f g : A) : zero_locus 𝒜 ({f * g} : set A) = zero_locus 𝒜 {f} ∪ zero_locus 𝒜 {g} := set.ext $ λ x, by simpa using x.is_prime.mul_mem_iff_mem_or_mem @[simp] lemma zero_locus_singleton_pow (f : A) (n : ℕ) (hn : 0 < n) : zero_locus 𝒜 ({f ^ n} : set A) = zero_locus 𝒜 {f} := set.ext $ λ x, by simpa using x.is_prime.pow_mem_iff_mem n hn lemma sup_vanishing_ideal_le (t t' : set (projective_spectrum 𝒜)) : vanishing_ideal t ⊔ vanishing_ideal t' ≤ vanishing_ideal (t ∩ t') := begin intros r, rw [← homogeneous_ideal.mem_iff, homogeneous_ideal.to_ideal_sup, mem_vanishing_ideal, submodule.mem_sup], rintro ⟨f, hf, g, hg, rfl⟩ x ⟨hxt, hxt'⟩, erw mem_vanishing_ideal at hf hg, apply submodule.add_mem; solve_by_elim end lemma mem_compl_zero_locus_iff_not_mem {f : A} {I : projective_spectrum 𝒜} : I ∈ (zero_locus 𝒜 {f} : set (projective_spectrum 𝒜))ᶜ ↔ f ∉ I.as_homogeneous_ideal := by rw [set.mem_compl_iff, mem_zero_locus, set.singleton_subset_iff]; refl /-- The Zariski topology on the prime spectrum of a commutative ring is defined via the closed sets of the topology: they are exactly those sets that are the zero locus of a subset of the ring. -/ instance zariski_topology : topological_space (projective_spectrum 𝒜) := topological_space.of_closed (set.range (projective_spectrum.zero_locus 𝒜)) (⟨set.univ, by simp⟩) begin intros Zs h, rw set.sInter_eq_Inter, let f : Zs → set _ := λ i, classical.some (h i.2), have hf : ∀ i : Zs, ↑i = zero_locus 𝒜 (f i) := λ i, (classical.some_spec (h i.2)).symm, simp only [hf], exact ⟨_, zero_locus_Union 𝒜 _⟩ end (by { rintros _ ⟨s, rfl⟩ _ ⟨t, rfl⟩, exact ⟨_, (union_zero_locus 𝒜 s t).symm⟩ }) /-- The underlying topology of `Proj` is the projective spectrum of graded ring `A`. -/ def Top : Top := Top.of (projective_spectrum 𝒜) lemma is_open_iff (U : set (projective_spectrum 𝒜)) : is_open U ↔ ∃ s, Uᶜ = zero_locus 𝒜 s := by simp only [@eq_comm _ Uᶜ]; refl lemma is_closed_iff_zero_locus (Z : set (projective_spectrum 𝒜)) : is_closed Z ↔ ∃ s, Z = zero_locus 𝒜 s := by rw [← is_open_compl_iff, is_open_iff, compl_compl] lemma is_closed_zero_locus (s : set A) : is_closed (zero_locus 𝒜 s) := by { rw [is_closed_iff_zero_locus], exact ⟨s, rfl⟩ } lemma zero_locus_vanishing_ideal_eq_closure (t : set (projective_spectrum 𝒜)) : zero_locus 𝒜 (vanishing_ideal t : set A) = closure t := begin apply set.subset.antisymm, { rintro x hx t' ⟨ht', ht⟩, obtain ⟨fs, rfl⟩ : ∃ s, t' = zero_locus 𝒜 s, by rwa [is_closed_iff_zero_locus] at ht', rw [subset_zero_locus_iff_subset_vanishing_ideal] at ht, exact set.subset.trans ht hx }, { rw (is_closed_zero_locus _ _).closure_subset_iff, exact subset_zero_locus_vanishing_ideal 𝒜 t } end lemma vanishing_ideal_closure (t : set (projective_spectrum 𝒜)) : vanishing_ideal (closure t) = vanishing_ideal t := begin have := (gc_ideal 𝒜).u_l_u_eq_u t, dsimp only at this, ext1, erw zero_locus_vanishing_ideal_eq_closure 𝒜 t at this, exact this, end section basic_open /-- `basic_open r` is the open subset containing all prime ideals not containing `r`. -/ def basic_open (r : A) : topological_space.opens (projective_spectrum 𝒜) := { val := { x | r ∉ x.as_homogeneous_ideal }, property := ⟨{r}, set.ext $ λ x, set.singleton_subset_iff.trans $ not_not.symm⟩ } @[simp] lemma mem_basic_open (f : A) (x : projective_spectrum 𝒜) : x ∈ basic_open 𝒜 f ↔ f ∉ x.as_homogeneous_ideal := iff.rfl lemma mem_coe_basic_open (f : A) (x : projective_spectrum 𝒜) : x ∈ (↑(basic_open 𝒜 f): set (projective_spectrum 𝒜)) ↔ f ∉ x.as_homogeneous_ideal := iff.rfl lemma is_open_basic_open {a : A} : is_open ((basic_open 𝒜 a) : set (projective_spectrum 𝒜)) := (basic_open 𝒜 a).property @[simp] lemma basic_open_eq_zero_locus_compl (r : A) : (basic_open 𝒜 r : set (projective_spectrum 𝒜)) = (zero_locus 𝒜 {r})ᶜ := set.ext $ λ x, by simpa only [set.mem_compl_iff, mem_zero_locus, set.singleton_subset_iff] @[simp] lemma basic_open_one : basic_open 𝒜 (1 : A) = ⊤ := topological_space.opens.ext $ by simp @[simp] lemma basic_open_zero : basic_open 𝒜 (0 : A) = ⊥ := topological_space.opens.ext $ by simp lemma basic_open_mul (f g : A) : basic_open 𝒜 (f * g) = basic_open 𝒜 f ⊓ basic_open 𝒜 g := topological_space.opens.ext $ by {simp [zero_locus_singleton_mul]} lemma basic_open_mul_le_left (f g : A) : basic_open 𝒜 (f * g) ≤ basic_open 𝒜 f := by { rw basic_open_mul 𝒜 f g, exact inf_le_left } lemma basic_open_mul_le_right (f g : A) : basic_open 𝒜 (f * g) ≤ basic_open 𝒜 g := by { rw basic_open_mul 𝒜 f g, exact inf_le_right } @[simp] lemma basic_open_pow (f : A) (n : ℕ) (hn : 0 < n) : basic_open 𝒜 (f ^ n) = basic_open 𝒜 f := topological_space.opens.ext $ by simpa using zero_locus_singleton_pow 𝒜 f n hn lemma basic_open_eq_union_of_projection (f : A) : basic_open 𝒜 f = ⨆ (i : ℕ), basic_open 𝒜 (graded_algebra.proj 𝒜 i f) := topological_space.opens.ext $ set.ext $ λ z, begin erw [mem_coe_basic_open, topological_space.opens.mem_Sup], split; intros hz, { rcases show ∃ i, graded_algebra.proj 𝒜 i f ∉ z.as_homogeneous_ideal, begin contrapose! hz with H, classical, rw ←direct_sum.sum_support_decompose 𝒜 f, apply ideal.sum_mem _ (λ i hi, H i) end with ⟨i, hi⟩, exact ⟨basic_open 𝒜 (graded_algebra.proj 𝒜 i f), ⟨i, rfl⟩, by rwa mem_basic_open⟩ }, { obtain ⟨_, ⟨i, rfl⟩, hz⟩ := hz, exact λ rid, hz (z.1.2 i rid) }, end lemma is_topological_basis_basic_opens : topological_space.is_topological_basis (set.range (λ (r : A), (basic_open 𝒜 r : set (projective_spectrum 𝒜)))) := begin apply topological_space.is_topological_basis_of_open_of_nhds, { rintros _ ⟨r, rfl⟩, exact is_open_basic_open 𝒜 }, { rintros p U hp ⟨s, hs⟩, rw [← compl_compl U, set.mem_compl_iff, ← hs, mem_zero_locus, set.not_subset] at hp, obtain ⟨f, hfs, hfp⟩ := hp, refine ⟨basic_open 𝒜 f, ⟨f, rfl⟩, hfp, _⟩, rw [← set.compl_subset_compl, ← hs, basic_open_eq_zero_locus_compl, compl_compl], exact zero_locus_anti_mono 𝒜 (set.singleton_subset_iff.mpr hfs) } end end basic_open section order /-! ## The specialization order We endow `projective_spectrum 𝒜` with a partial order, where `x ≤ y` if and only if `y ∈ closure {x}`. -/ instance : partial_order (projective_spectrum 𝒜) := partial_order.lift as_homogeneous_ideal $ λ ⟨_, _, _⟩ ⟨_, _, _⟩, mk.inj_eq.mpr @[simp] lemma as_ideal_le_as_ideal (x y : projective_spectrum 𝒜) : x.as_homogeneous_ideal ≤ y.as_homogeneous_ideal ↔ x ≤ y := iff.rfl @[simp] lemma as_ideal_lt_as_ideal (x y : projective_spectrum 𝒜) : x.as_homogeneous_ideal < y.as_homogeneous_ideal ↔ x < y := iff.rfl lemma le_iff_mem_closure (x y : projective_spectrum 𝒜) : x ≤ y ↔ y ∈ closure ({x} : set (projective_spectrum 𝒜)) := begin rw [← as_ideal_le_as_ideal, ← zero_locus_vanishing_ideal_eq_closure, mem_zero_locus, vanishing_ideal_singleton], simp only [coe_subset_coe, subtype.coe_le_coe, coe_coe], end end order end projective_spectrum
58b7aef8dd964f862abb3bc3448e3d31bd70f7a2
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/computability/tm_computable.lean
a9870bd83a0600c6625b0c426e6abcf721468207
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
14,136
lean
/- Copyright (c) 2020 Pim Spelier, Daan van Gent. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Pim Spelier, Daan van Gent. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.computability.encoding import Mathlib.computability.turing_machine import Mathlib.data.polynomial.basic import Mathlib.data.polynomial.eval import Mathlib.PostPort universes l u_1 namespace Mathlib /-! # Computable functions This file contains the definition of a Turing machine with some finiteness conditions (bundling the definition of TM2 in turing_machine.lean), a definition of when a TM gives a certain output (in a certain time), and the definition of computability (in polytime or any time function) of a function between two types that have an encoding (as in encoding.lean). ## Main theorems - `id_computable_in_poly_time` : a TM + a proof it computes the identity on a type in polytime. - `id_computable` : a TM + a proof it computes the identity on a type. ## Implementation notes To count the execution time of a Turing machine, we have decided to count the number of times the `step` function is used. Each step executes a statement (of type stmt); this is a function, and generally contains multiple "fundamental" steps (pushing, popping, so on). However, as functions only contain a finite number of executions and each one is executed at most once, this execution time is up to multiplication by a constant the amount of fundamental steps. -/ namespace turing /-- A bundled TM2 (an equivalent of the classical Turing machine, defined starting from the namespace `turing.TM2` in `turing_machine.lean`), with an input and output stack, a main function, an initial state and some finiteness guarantees. -/ structure fin_tm2 where K : Type K_decidable_eq : DecidableEq K K_fin : fintype K k₀ : K k₁ : K Γ : K → Type Λ : Type main : Λ Λ_fin : fintype Λ σ : Type initial_state : σ σ_fin : fintype σ Γk₀_fin : fintype (Γ k₀) M : Λ → TM2.stmt Γ Λ σ namespace fin_tm2 protected instance K.decidable_eq (tm : fin_tm2) : DecidableEq (K tm) := K_decidable_eq tm protected instance σ.inhabited (tm : fin_tm2) : Inhabited (σ tm) := { default := initial_state tm } /-- The type of statements (functions) corresponding to this TM. -/ def stmt (tm : fin_tm2) := TM2.stmt (Γ tm) (Λ tm) (σ tm) /-- The type of configurations (functions) corresponding to this TM. -/ def cfg (tm : fin_tm2) := TM2.cfg (Γ tm) (Λ tm) (σ tm) protected instance inhabited_cfg (tm : fin_tm2) : Inhabited (cfg tm) := TM2.cfg.inhabited (Γ tm) (Λ tm) (σ tm) /-- The step function corresponding to this TM. -/ @[simp] def step (tm : fin_tm2) : cfg tm → Option (cfg tm) := TM2.step (M tm) end fin_tm2 /-- The initial configuration corresponding to a list in the input alphabet. -/ def init_list (tm : fin_tm2) (s : List (fin_tm2.Γ tm (fin_tm2.k₀ tm))) : fin_tm2.cfg tm := TM2.cfg.mk (some (fin_tm2.main tm)) (fin_tm2.initial_state tm) fun (k : fin_tm2.K tm) => dite (k = fin_tm2.k₀ tm) (fun (h : k = fin_tm2.k₀ tm) => eq.mpr sorry s) fun (_x : ¬k = fin_tm2.k₀ tm) => [] /-- The final configuration corresponding to a list in the output alphabet. -/ def halt_list (tm : fin_tm2) (s : List (fin_tm2.Γ tm (fin_tm2.k₁ tm))) : fin_tm2.cfg tm := TM2.cfg.mk none (fin_tm2.initial_state tm) fun (k : fin_tm2.K tm) => dite (k = fin_tm2.k₁ tm) (fun (h : k = fin_tm2.k₁ tm) => eq.mpr sorry s) fun (_x : ¬k = fin_tm2.k₁ tm) => [] /-- A "proof" of the fact that f eventually reaches b when repeatedly evaluated on a, remembering the number of steps it takes. -/ structure evals_to {σ : Type u_1} (f : σ → Option σ) (a : σ) (b : Option σ) where steps : ℕ evals_in_steps : nat.iterate (flip bind f) steps ↑a = b /-- A "proof" of the fact that `f` eventually reaches `b` in at most `m` steps when repeatedly evaluated on `a`, remembering the number of steps it takes. -/ structure evals_to_in_time {σ : Type u_1} (f : σ → Option σ) (a : σ) (b : Option σ) (m : ℕ) extends evals_to f a b where steps_le_m : evals_to.steps _to_evals_to ≤ m /-- Reflexivity of `evals_to` in 0 steps. -/ def evals_to.refl {σ : Type u_1} (f : σ → Option σ) (a : σ) : evals_to f a ↑a := evals_to.mk 0 sorry /-- Transitivity of `evals_to` in the sum of the numbers of steps. -/ def evals_to.trans {σ : Type u_1} (f : σ → Option σ) (a : σ) (b : σ) (c : Option σ) (h₁ : evals_to f a ↑b) (h₂ : evals_to f b c) : evals_to f a c := evals_to.mk (evals_to.steps h₂ + evals_to.steps h₁) sorry /-- Reflexivity of `evals_to_in_time` in 0 steps. -/ def evals_to_in_time.refl {σ : Type u_1} (f : σ → Option σ) (a : σ) : evals_to_in_time f a (↑a) 0 := evals_to_in_time.mk (evals_to.refl f a) sorry /-- Transitivity of `evals_to_in_time` in the sum of the numbers of steps. -/ def evals_to_in_time.trans {σ : Type u_1} (f : σ → Option σ) (a : σ) (b : σ) (c : Option σ) (m₁ : ℕ) (m₂ : ℕ) (h₁ : evals_to_in_time f a (↑b) m₁) (h₂ : evals_to_in_time f b c m₂) : evals_to_in_time f a c (m₂ + m₁) := evals_to_in_time.mk (evals_to.trans f a b c (evals_to_in_time.to_evals_to h₁) (evals_to_in_time.to_evals_to h₂)) sorry /-- A proof of tm outputting l' when given l. -/ def tm2_outputs (tm : fin_tm2) (l : List (fin_tm2.Γ tm (fin_tm2.k₀ tm))) (l' : Option (List (fin_tm2.Γ tm (fin_tm2.k₁ tm)))) := evals_to (fin_tm2.step tm) (init_list tm l) (option.map (halt_list tm) l') /-- A proof of tm outputting l' when given l in at most m steps. -/ def tm2_outputs_in_time (tm : fin_tm2) (l : List (fin_tm2.Γ tm (fin_tm2.k₀ tm))) (l' : Option (List (fin_tm2.Γ tm (fin_tm2.k₁ tm)))) (m : ℕ) := evals_to_in_time (fin_tm2.step tm) (init_list tm l) (option.map (halt_list tm) l') m /-- The forgetful map, forgetting the upper bound on the number of steps. -/ def tm2_outputs_in_time.to_tm2_outputs {tm : fin_tm2} {l : List (fin_tm2.Γ tm (fin_tm2.k₀ tm))} {l' : Option (List (fin_tm2.Γ tm (fin_tm2.k₁ tm)))} {m : ℕ} (h : tm2_outputs_in_time tm l l' m) : tm2_outputs tm l l' := evals_to_in_time.to_evals_to h /-- A Turing machine with input alphabet equivalent to Γ₀ and output alphabet equivalent to Γ₁. -/ structure tm2_computable_aux (Γ₀ : Type) (Γ₁ : Type) where tm : fin_tm2 input_alphabet : fin_tm2.Γ tm (fin_tm2.k₀ tm) ≃ Γ₀ output_alphabet : fin_tm2.Γ tm (fin_tm2.k₁ tm) ≃ Γ₁ /-- A Turing machine + a proof it outputs f. -/ structure tm2_computable {α : Type} {β : Type} (ea : computability.fin_encoding α) (eb : computability.fin_encoding β) (f : α → β) extends tm2_computable_aux (computability.encoding.Γ (computability.fin_encoding.to_encoding ea)) (computability.encoding.Γ (computability.fin_encoding.to_encoding eb)) where outputs_fun : (a : α) → tm2_outputs (tm2_computable_aux.tm _to_tm2_computable_aux) (list.map (equiv.inv_fun (tm2_computable_aux.input_alphabet _to_tm2_computable_aux)) (computability.encoding.encode (computability.fin_encoding.to_encoding ea) a)) (some (list.map (equiv.inv_fun (tm2_computable_aux.output_alphabet _to_tm2_computable_aux)) (computability.encoding.encode (computability.fin_encoding.to_encoding eb) (f a)))) /-- A Turing machine + a time function + a proof it outputs f in at most time(len(input)) steps. -/ structure tm2_computable_in_time {α : Type} {β : Type} (ea : computability.fin_encoding α) (eb : computability.fin_encoding β) (f : α → β) extends tm2_computable_aux (computability.encoding.Γ (computability.fin_encoding.to_encoding ea)) (computability.encoding.Γ (computability.fin_encoding.to_encoding eb)) where time : ℕ → ℕ outputs_fun : (a : α) → tm2_outputs_in_time (tm2_computable_aux.tm _to_tm2_computable_aux) (list.map (equiv.inv_fun (tm2_computable_aux.input_alphabet _to_tm2_computable_aux)) (computability.encoding.encode (computability.fin_encoding.to_encoding ea) a)) (some (list.map (equiv.inv_fun (tm2_computable_aux.output_alphabet _to_tm2_computable_aux)) (computability.encoding.encode (computability.fin_encoding.to_encoding eb) (f a)))) (time (list.length (computability.encoding.encode (computability.fin_encoding.to_encoding ea) a))) /-- A Turing machine + a polynomial time function + a proof it outputs f in at most time(len(input)) steps. -/ structure tm2_computable_in_poly_time {α : Type} {β : Type} (ea : computability.fin_encoding α) (eb : computability.fin_encoding β) (f : α → β) extends tm2_computable_aux (computability.encoding.Γ (computability.fin_encoding.to_encoding ea)) (computability.encoding.Γ (computability.fin_encoding.to_encoding eb)) where time : polynomial ℕ outputs_fun : (a : α) → tm2_outputs_in_time (tm2_computable_aux.tm _to_tm2_computable_aux) (list.map (equiv.inv_fun (tm2_computable_aux.input_alphabet _to_tm2_computable_aux)) (computability.encoding.encode (computability.fin_encoding.to_encoding ea) a)) (some (list.map (equiv.inv_fun (tm2_computable_aux.output_alphabet _to_tm2_computable_aux)) (computability.encoding.encode (computability.fin_encoding.to_encoding eb) (f a)))) (polynomial.eval (list.length (computability.encoding.encode (computability.fin_encoding.to_encoding ea) a)) time) /-- A forgetful map, forgetting the time bound on the number of steps. -/ def tm2_computable_in_time.to_tm2_computable {α : Type} {β : Type} {ea : computability.fin_encoding α} {eb : computability.fin_encoding β} {f : α → β} (h : tm2_computable_in_time ea eb f) : tm2_computable ea eb f := tm2_computable.mk (tm2_computable_in_time.to_tm2_computable_aux h) fun (a : α) => tm2_outputs_in_time.to_tm2_outputs (tm2_computable_in_time.outputs_fun h a) /-- A forgetful map, forgetting that the time function is polynomial. -/ def tm2_computable_in_poly_time.to_tm2_computable_in_time {α : Type} {β : Type} {ea : computability.fin_encoding α} {eb : computability.fin_encoding β} {f : α → β} (h : tm2_computable_in_poly_time ea eb f) : tm2_computable_in_time ea eb f := tm2_computable_in_time.mk (tm2_computable_in_poly_time.to_tm2_computable_aux h) (fun (n : ℕ) => polynomial.eval n (tm2_computable_in_poly_time.time h)) (tm2_computable_in_poly_time.outputs_fun h) /-- A Turing machine computing the identity on α. -/ def id_computer {α : Type} (ea : computability.fin_encoding α) : fin_tm2 := fin_tm2.mk PUnit.unit PUnit.unit (fun (_x : Unit) => computability.encoding.Γ (computability.fin_encoding.to_encoding ea)) Unit PUnit.unit Unit PUnit.unit fun (_x : Unit) => TM2.stmt.halt protected instance inhabited_fin_tm2 : Inhabited fin_tm2 := { default := id_computer Inhabited.default } /-- A proof that the identity map on α is computable in polytime. -/ def id_computable_in_poly_time {α : Type} (ea : computability.fin_encoding α) : tm2_computable_in_poly_time ea ea id := tm2_computable_in_poly_time.mk (tm2_computable_aux.mk (id_computer ea) (equiv.cast sorry) (equiv.cast sorry)) 1 fun (_x : α) => evals_to_in_time.mk (evals_to.mk 1 sorry) sorry protected instance inhabited_tm2_computable_in_poly_time : Inhabited (tm2_computable_in_poly_time Inhabited.default Inhabited.default id) := { default := id_computable_in_poly_time Inhabited.default } protected instance inhabited_tm2_outputs_in_time : Inhabited (tm2_outputs_in_time (id_computer computability.fin_encoding_bool_bool) (list.map (equiv.inv_fun (equiv.cast inhabited_tm2_outputs_in_time._proof_1)) [false]) (some (list.map (equiv.inv_fun (equiv.cast inhabited_tm2_outputs_in_time._proof_2)) [false])) (polynomial.eval (list.length (computability.encoding.encode (computability.fin_encoding.to_encoding computability.fin_encoding_bool_bool) false)) (tm2_computable_in_poly_time.time (id_computable_in_poly_time computability.fin_encoding_bool_bool)))) := { default := tm2_computable_in_poly_time.outputs_fun (id_computable_in_poly_time computability.fin_encoding_bool_bool) false } protected instance inhabited_tm2_outputs : Inhabited (tm2_outputs (id_computer computability.fin_encoding_bool_bool) (list.map (equiv.inv_fun (equiv.cast inhabited_tm2_outputs._proof_1)) [false]) (some (list.map (equiv.inv_fun (equiv.cast inhabited_tm2_outputs._proof_2)) [false]))) := { default := tm2_outputs_in_time.to_tm2_outputs Inhabited.default } protected instance inhabited_evals_to_in_time : Inhabited (evals_to_in_time (fun (_x : Unit) => some PUnit.unit) PUnit.unit (some PUnit.unit) 0) := { default := evals_to_in_time.refl (fun (_x : Unit) => some PUnit.unit) PUnit.unit } protected instance inhabited_tm2_evals_to : Inhabited (evals_to (fun (_x : Unit) => some PUnit.unit) PUnit.unit (some PUnit.unit)) := { default := evals_to.refl (fun (_x : Unit) => some PUnit.unit) PUnit.unit } /-- A proof that the identity map on α is computable in time. -/ def id_computable_in_time {α : Type} (ea : computability.fin_encoding α) : tm2_computable_in_time ea ea id := tm2_computable_in_poly_time.to_tm2_computable_in_time (id_computable_in_poly_time ea) protected instance inhabited_tm2_computable_in_time : Inhabited (tm2_computable_in_time computability.fin_encoding_bool_bool computability.fin_encoding_bool_bool id) := { default := id_computable_in_time Inhabited.default } /-- A proof that the identity map on α is computable. -/ def id_computable {α : Type} (ea : computability.fin_encoding α) : tm2_computable ea ea id := tm2_computable_in_time.to_tm2_computable (id_computable_in_time ea) protected instance inhabited_tm2_computable : Inhabited (tm2_computable computability.fin_encoding_bool_bool computability.fin_encoding_bool_bool id) := { default := id_computable Inhabited.default } protected instance inhabited_tm2_computable_aux : Inhabited (tm2_computable_aux Bool Bool) := { default := tm2_computable.to_tm2_computable_aux Inhabited.default }
ac1990f95e80d98ac396a45f93ec7f8c6388ae94
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/dfinsupp/ne_locus.lean
772d04af470e8684827d99efae12689a5c498b5d
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
5,951
lean
/- Copyright (c) 2022 Junyan Xu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa, Junyan Xu -/ import data.dfinsupp.basic /-! # Locus of unequal values of finitely supported dependent functions > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Let `N : α → Type*` be a type family, assume that `N a` has a `0` for all `a : α` and let `f g : Π₀ a, N a` be finitely supported dependent functions. ## Main definition * `dfinsupp.ne_locus f g : finset α`, the finite subset of `α` where `f` and `g` differ. In the case in which `N a` is an additive group for all `a`, `dfinsupp.ne_locus f g` coincides with `dfinsupp.support (f - g)`. -/ variables {α : Type*} {N : α → Type*} namespace dfinsupp variable [decidable_eq α] section N_has_zero variables [Π a, decidable_eq (N a)] [Π a, has_zero (N a)] (f g : Π₀ a, N a) /-- Given two finitely supported functions `f g : α →₀ N`, `finsupp.ne_locus f g` is the `finset` where `f` and `g` differ. This generalizes `(f - g).support` to situations without subtraction. -/ def ne_locus (f g : Π₀ a, N a) : finset α := (f.support ∪ g.support).filter (λ x, f x ≠ g x) @[simp] lemma mem_ne_locus {f g : Π₀ a, N a} {a : α} : a ∈ f.ne_locus g ↔ f a ≠ g a := by simpa only [ne_locus, finset.mem_filter, finset.mem_union, mem_support_iff, and_iff_right_iff_imp] using ne.ne_or_ne _ lemma not_mem_ne_locus {f g : Π₀ a, N a} {a : α} : a ∉ f.ne_locus g ↔ f a = g a := mem_ne_locus.not.trans not_ne_iff @[simp] lemma coe_ne_locus : ↑(f.ne_locus g) = {x | f x ≠ g x} := set.ext $ λ x, mem_ne_locus @[simp] lemma ne_locus_eq_empty {f g : Π₀ a, N a} : f.ne_locus g = ∅ ↔ f = g := ⟨λ h, ext (λ a, not_not.mp (mem_ne_locus.not.mp (finset.eq_empty_iff_forall_not_mem.mp h a))), λ h, h ▸ by simp only [ne_locus, ne.def, eq_self_iff_true, not_true, finset.filter_false]⟩ @[simp] lemma nonempty_ne_locus_iff {f g : Π₀ a, N a} : (f.ne_locus g).nonempty ↔ f ≠ g := finset.nonempty_iff_ne_empty.trans ne_locus_eq_empty.not lemma ne_locus_comm : f.ne_locus g = g.ne_locus f := by simp_rw [ne_locus, finset.union_comm, ne_comm] @[simp] lemma ne_locus_zero_right : f.ne_locus 0 = f.support := by { ext, rw [mem_ne_locus, mem_support_iff, coe_zero, pi.zero_apply] } @[simp] lemma ne_locus_zero_left : (0 : Π₀ a, N a).ne_locus f = f.support := (ne_locus_comm _ _).trans (ne_locus_zero_right _) end N_has_zero section ne_locus_and_maps variables {M P : α → Type*} [Π a, has_zero (N a)] [Π a, has_zero (M a)] [Π a, has_zero (P a)] lemma subset_map_range_ne_locus [Π a, decidable_eq (N a)] [Π a, decidable_eq (M a)] (f g : Π₀ a, N a) {F : Π a, N a → M a} (F0 : ∀ a, F a 0 = 0) : (f.map_range F F0).ne_locus (g.map_range F F0) ⊆ f.ne_locus g := λ a, by simpa only [mem_ne_locus, map_range_apply, not_imp_not] using congr_arg (F a) lemma zip_with_ne_locus_eq_left [Π a, decidable_eq (N a)] [Π a, decidable_eq (P a)] {F : Π a, M a → N a → P a} (F0 : ∀ a, F a 0 0 = 0) (f : Π₀ a, M a) (g₁ g₂ : Π₀ a, N a) (hF : ∀ a f, function.injective (λ g, F a f g)) : (zip_with F F0 f g₁).ne_locus (zip_with F F0 f g₂) = g₁.ne_locus g₂ := by { ext, simpa only [mem_ne_locus] using (hF a _).ne_iff } lemma zip_with_ne_locus_eq_right [Π a, decidable_eq (M a)] [Π a, decidable_eq (P a)] {F : Π a, M a → N a → P a} (F0 : ∀ a, F a 0 0 = 0) (f₁ f₂ : Π₀ a, M a) (g : Π₀ a, N a) (hF : ∀ a g, function.injective (λ f, F a f g)) : (zip_with F F0 f₁ g).ne_locus (zip_with F F0 f₂ g) = f₁.ne_locus f₂ := by { ext, simpa only [mem_ne_locus] using (hF a _).ne_iff } lemma map_range_ne_locus_eq [Π a, decidable_eq (N a)] [Π a, decidable_eq (M a)] (f g : Π₀ a, N a) {F : Π a, N a → M a} (F0 : ∀ a, F a 0 = 0) (hF : ∀ a, function.injective (F a)) : (f.map_range F F0).ne_locus (g.map_range F F0) = f.ne_locus g := by { ext, simpa only [mem_ne_locus] using (hF a).ne_iff } end ne_locus_and_maps variables [Π a, decidable_eq (N a)] @[simp] lemma ne_locus_add_left [Π a, add_left_cancel_monoid (N a)] (f g h : Π₀ a, N a) : (f + g).ne_locus (f + h) = g.ne_locus h := zip_with_ne_locus_eq_left _ _ _ _ $ λ a, add_right_injective @[simp] lemma ne_locus_add_right [Π a, add_right_cancel_monoid (N a)] (f g h : Π₀ a, N a) : (f + h).ne_locus (g + h) = f.ne_locus g := zip_with_ne_locus_eq_right _ _ _ _ $ λ a, add_left_injective section add_group variables [Π a, add_group (N a)] (f f₁ f₂ g g₁ g₂ : Π₀ a, N a) @[simp] lemma ne_locus_neg_neg : ne_locus (-f) (-g) = f.ne_locus g := map_range_ne_locus_eq _ _ (λ a, neg_zero) (λ a, neg_injective) lemma ne_locus_neg : ne_locus (-f) g = f.ne_locus (-g) := by rw [←ne_locus_neg_neg, neg_neg] lemma ne_locus_eq_support_sub : f.ne_locus g = (f - g).support := by rw [←@ne_locus_add_right α N _ _ _ _ _ (-g), add_right_neg, ne_locus_zero_right, sub_eq_add_neg] @[simp] lemma ne_locus_sub_left : ne_locus (f - g₁) (f - g₂) = ne_locus g₁ g₂ := by simp only [sub_eq_add_neg, @ne_locus_add_left α N _ _ _, ne_locus_neg_neg] @[simp] lemma ne_locus_sub_right : ne_locus (f₁ - g) (f₂ - g) = ne_locus f₁ f₂ := by simpa only [sub_eq_add_neg] using @ne_locus_add_right α N _ _ _ _ _ _ @[simp] lemma ne_locus_self_add_right : ne_locus f (f + g) = g.support := by rw [←ne_locus_zero_left, ←@ne_locus_add_left α N _ _ _ f 0 g, add_zero] @[simp] lemma ne_locus_self_add_left : ne_locus (f + g) f = g.support := by rw [ne_locus_comm, ne_locus_self_add_right] @[simp] lemma ne_locus_self_sub_right : ne_locus f (f - g) = g.support := by rw [sub_eq_add_neg, ne_locus_self_add_right, support_neg] @[simp] lemma ne_locus_self_sub_left : ne_locus (f - g) f = g.support := by rw [ne_locus_comm, ne_locus_self_sub_right] end add_group end dfinsupp
675df4deb003bbdf9b08f31b2b0bb4cc72dfe972
4727251e0cd73359b15b664c3170e5d754078599
/src/measure_theory/measure/ae_measurable.lean
13816f0ef631aad2ce211a9a76cfecc8f286cbee
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
13,783
lean
/- Copyright (c) 2021 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import measure_theory.measure.measure_space /-! # Almost everywhere measurable functions A function is almost everywhere measurable if it coincides almost everywhere with a measurable function. This property, called `ae_measurable f μ`, is defined in the file `measure_space_def`. We discuss several of its properties that are analogous to properties of measurable functions. -/ open measure_theory measure_theory.measure filter set function open_locale measure_theory filter classical ennreal interval variables {ι α β γ δ R : Type*} {m0 : measurable_space α} [measurable_space β] [measurable_space γ] [measurable_space δ] {f g : α → β} {μ ν : measure α} include m0 section @[nontriviality, measurability] lemma subsingleton.ae_measurable [subsingleton α] : ae_measurable f μ := subsingleton.measurable.ae_measurable @[nontriviality, measurability] lemma ae_measurable_of_subsingleton_codomain [subsingleton β] : ae_measurable f μ := (measurable_of_subsingleton_codomain f).ae_measurable @[simp, measurability] lemma ae_measurable_zero_measure : ae_measurable f (0 : measure α) := begin nontriviality α, inhabit α, exact ⟨λ x, f default, measurable_const, rfl⟩ end namespace ae_measurable 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 @[measurability] lemma sum_measure [encodable ι] {μ : ι → measure α} (h : ∀ i, ae_measurable f (μ i)) : ae_measurable f (sum μ) := begin nontriviality β, inhabit β, set s : ι → set α := λ i, to_measurable (μ i) {x | f x ≠ (h i).mk f x}, have hsμ : ∀ i, μ i (s i) = 0, { intro i, rw measure_to_measurable, exact (h i).ae_eq_mk }, have hsm : measurable_set (⋂ i, s i), from measurable_set.Inter (λ i, measurable_set_to_measurable _ _), have hs : ∀ i x, x ∉ s i → f x = (h i).mk f x, { intros i x hx, contrapose! hx, exact subset_to_measurable _ _ hx }, set g : α → β := (⋂ i, s i).piecewise (const α default) f, refine ⟨g, measurable_of_restrict_of_restrict_compl hsm _ _, ae_sum_iff.mpr $ λ i, _⟩, { rw [restrict_piecewise], simp only [set.restrict, const], exact measurable_const }, { rw [restrict_piecewise_compl, compl_Inter], intros t ht, refine ⟨⋃ i, ((h i).mk f ⁻¹' t) ∩ (s i)ᶜ, measurable_set.Union $ λ i, (measurable_mk _ ht).inter (measurable_set_to_measurable _ _).compl, _⟩, ext ⟨x, hx⟩, simp only [mem_preimage, mem_Union, subtype.coe_mk, set.restrict, mem_inter_eq, mem_compl_iff] at hx ⊢, split, { rintro ⟨i, hxt, hxs⟩, rwa hs _ _ hxs }, { rcases hx with ⟨i, hi⟩, rw hs _ _ hi, exact λ h, ⟨i, h, hi⟩ } }, { refine measure_mono_null (λ x (hx : f x ≠ g x), _) (hsμ i), contrapose! hx, refine (piecewise_eq_of_not_mem _ _ _ _).symm, exact λ h, hx (mem_Inter.1 h i) } end @[simp] lemma _root_.ae_measurable_sum_measure_iff [encodable ι] {μ : ι → measure α} : ae_measurable f (sum μ) ↔ ∀ i, ae_measurable f (μ i) := ⟨λ h i, h.mono_measure (le_sum _ _), sum_measure⟩ @[simp] lemma _root_.ae_measurable_add_measure_iff : ae_measurable f (μ + ν) ↔ ae_measurable f μ ∧ ae_measurable f ν := by { rw [← sum_cond, ae_measurable_sum_measure_iff, bool.forall_bool, and.comm], refl } @[measurability] lemma add_measure {f : α → β} (hμ : ae_measurable f μ) (hν : ae_measurable f ν) : ae_measurable f (μ + ν) := ae_measurable_add_measure_iff.2 ⟨hμ, hν⟩ @[measurability] protected lemma Union [encodable ι] {s : ι → set α} (h : ∀ i, ae_measurable f (μ.restrict (s i))) : ae_measurable f (μ.restrict (⋃ i, s i)) := (sum_measure h).mono_measure $ restrict_Union_le @[simp] lemma _root_.ae_measurable_Union_iff [encodable ι] {s : ι → set α} : ae_measurable f (μ.restrict (⋃ i, s i)) ↔ ∀ i, ae_measurable f (μ.restrict (s i)) := ⟨λ h i, h.mono_measure $ restrict_mono (subset_Union _ _) le_rfl, ae_measurable.Union⟩ @[simp] lemma _root_.ae_measurable_union_iff {s t : set α} : ae_measurable f (μ.restrict (s ∪ t)) ↔ ae_measurable f (μ.restrict s) ∧ ae_measurable f (μ.restrict t) := by simp only [union_eq_Union, ae_measurable_Union_iff, bool.forall_bool, cond, and.comm] @[measurability] lemma smul_measure [monoid R] [distrib_mul_action R ℝ≥0∞] [is_scalar_tower R ℝ≥0∞ ℝ≥0∞] (h : ae_measurable f μ) (c : R) : ae_measurable f (c • μ) := ⟨h.mk f, h.measurable_mk, ae_smul_measure h.ae_eq_mk c⟩ lemma comp_ae_measurable {f : α → δ} {g : δ → β} (hg : ae_measurable g (μ.map f)) (hf : ae_measurable f μ) : ae_measurable (g ∘ f) μ := ⟨hg.mk g ∘ hf.mk f, hg.measurable_mk.comp hf.measurable_mk, (ae_eq_comp hf hg.ae_eq_mk).trans ((hf.ae_eq_mk).fun_comp (mk g hg))⟩ lemma comp_measurable {f : α → δ} {g : δ → β} (hg : ae_measurable g (μ.map f)) (hf : measurable f) : ae_measurable (g ∘ f) μ := hg.comp_ae_measurable hf.ae_measurable lemma comp_measurable' {ν : measure δ} {f : α → δ} {g : δ → β} (hg : ae_measurable g ν) (hf : measurable f) (h : μ.map f ≪ ν) : ae_measurable (g ∘ f) μ := (hg.mono' h).comp_measurable hf lemma map_map_of_ae_measurable {g : β → γ} {f : α → β} (hg : ae_measurable g (measure.map f μ)) (hf : ae_measurable f μ) : (μ.map f).map g = μ.map (g ∘ f) := begin ext1 s hs, let g' := hg.mk g, have A : map g (map f μ) = map g' (map f μ), { apply measure_theory.measure.map_congr, exact hg.ae_eq_mk }, have B : map (g ∘ f) μ = map (g' ∘ f) μ, { apply measure_theory.measure.map_congr, exact ae_of_ae_map hf hg.ae_eq_mk }, simp only [A, B, hs, hg.measurable_mk.ae_measurable.comp_ae_measurable hf, hg.measurable_mk, hg.measurable_mk hs, hf, map_apply, map_apply_of_ae_measurable], refl, end @[measurability] lemma prod_mk {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 exists_ae_eq_range_subset (H : ae_measurable f μ) {t : set β} (ht : ∀ᵐ x ∂μ, f x ∈ t) (h₀ : t.nonempty) : ∃ g, measurable g ∧ range g ⊆ t ∧ f =ᵐ[μ] g := begin let s : set α := to_measurable μ {x | f x = H.mk f x ∧ f x ∈ t}ᶜ, let g : α → β := piecewise s (λ x, h₀.some) (H.mk f), refine ⟨g, _, _, _⟩, { exact measurable.piecewise (measurable_set_to_measurable _ _) measurable_const H.measurable_mk }, { rintros - ⟨x, rfl⟩, by_cases hx : x ∈ s, { simpa [g, hx] using h₀.some_mem }, { simp only [g, hx, piecewise_eq_of_not_mem, not_false_iff], contrapose! hx, apply subset_to_measurable, simp only [hx, mem_compl_eq, mem_set_of_eq, not_and, not_false_iff, implies_true_iff] {contextual := tt} } }, { have A : μ (to_measurable μ {x | f x = H.mk f x ∧ f x ∈ t}ᶜ) = 0, { rw [measure_to_measurable, ← compl_mem_ae_iff, compl_compl], exact H.ae_eq_mk.and ht }, filter_upwards [compl_mem_ae_iff.2 A] with x hx, rw mem_compl_iff at hx, simp only [g, hx, piecewise_eq_of_not_mem, not_false_iff], contrapose! hx, apply subset_to_measurable, simp only [hx, mem_compl_eq, mem_set_of_eq, false_and, not_false_iff] } end lemma subtype_mk (h : ae_measurable f μ) {s : set β} {hfs : ∀ x, f x ∈ s} : ae_measurable (cod_restrict f s hfs) μ := begin nontriviality α, inhabit α, obtain ⟨g, g_meas, hg, fg⟩ : ∃ (g : α → β), measurable g ∧ range g ⊆ s ∧ f =ᵐ[μ] g := h.exists_ae_eq_range_subset (eventually_of_forall hfs) ⟨_, hfs default⟩, refine ⟨cod_restrict g s (λ x, hg (mem_range_self _)), measurable.subtype_mk g_meas, _⟩, filter_upwards [fg] with x hx, simpa [subtype.ext_iff], end protected lemma null_measurable (h : ae_measurable f μ) : null_measurable f μ := let ⟨g, hgm, hg⟩ := h in hgm.null_measurable.congr hg.symm end ae_measurable lemma ae_measurable_interval_oc_iff [linear_order α] {f : α → β} {a b : α} : (ae_measurable f $ μ.restrict $ Ι a b) ↔ (ae_measurable f $ μ.restrict $ Ioc a b) ∧ (ae_measurable f $ μ.restrict $ Ioc b a) := by rw [interval_oc_eq_union, ae_measurable_union_iff] lemma ae_measurable_iff_measurable [μ.is_complete] : ae_measurable f μ ↔ measurable f := ⟨λ h, h.null_measurable.measurable_of_complete, λ h, h.ae_measurable⟩ lemma measurable_embedding.ae_measurable_map_iff {g : β → γ} (hf : measurable_embedding f) : ae_measurable g (μ.map f) ↔ ae_measurable (g ∘ f) μ := begin refine ⟨λ H, H.comp_measurable hf.measurable, _⟩, rintro ⟨g₁, hgm₁, heq⟩, rcases hf.exists_measurable_extend hgm₁ (λ x, ⟨g x⟩) with ⟨g₂, hgm₂, rfl⟩, exact ⟨g₂, hgm₂, hf.ae_map_iff.2 heq⟩ end lemma measurable_embedding.ae_measurable_comp_iff {g : β → γ} (hg : measurable_embedding g) {μ : measure α} : ae_measurable (g ∘ f) μ ↔ ae_measurable f μ := begin refine ⟨λ H, _, hg.measurable.comp_ae_measurable⟩, suffices : ae_measurable ((range_splitting g ∘ range_factorization g) ∘ f) μ, by rwa [(right_inverse_range_splitting hg.injective).comp_eq_id] at this, exact hg.measurable_range_splitting.comp_ae_measurable H.subtype_mk end lemma ae_measurable_restrict_iff_comap_subtype {s : set α} (hs : measurable_set s) {μ : measure α} {f : α → β} : ae_measurable f (μ.restrict s) ↔ ae_measurable (f ∘ coe : s → β) (comap coe μ) := by rw [← map_comap_subtype_coe hs, (measurable_embedding.subtype_coe hs).ae_measurable_map_iff] @[simp, to_additive] lemma ae_measurable_one [has_one β] : ae_measurable (λ a : α, (1 : β)) μ := measurable_one.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 ae_measurable_of_ae_measurable_trim {α} {m m0 : measurable_space α} {μ : measure α} (hm : m ≤ m0) {f : α → β} (hf : ae_measurable f (μ.trim hm)) : ae_measurable f μ := ⟨hf.mk f, measurable.mono hf.measurable_mk hm le_rfl, ae_eq_of_ae_eq_trim hf.ae_eq_mk⟩ lemma ae_measurable_restrict_of_measurable_subtype {s : set α} (hs : measurable_set s) (hf : measurable (λ x : s, f x)) : ae_measurable f (μ.restrict s) := (ae_measurable_restrict_iff_comap_subtype hs).2 hf.ae_measurable lemma ae_measurable_map_equiv_iff (e : α ≃ᵐ β) {f : β → γ} : ae_measurable f (μ.map e) ↔ ae_measurable (f ∘ e) μ := e.measurable_embedding.ae_measurable_map_iff end lemma ae_measurable.restrict (hfm : ae_measurable f μ) {s} : ae_measurable f (μ.restrict s) := ⟨ae_measurable.mk f hfm, hfm.measurable_mk, ae_restrict_of_ae hfm.ae_eq_mk⟩ variables [has_zero β] lemma ae_measurable_indicator_iff {s} (hs : measurable_set s) : ae_measurable (indicator s f) μ ↔ ae_measurable f (μ.restrict s) := begin split, { intro h, exact (h.mono_measure measure.restrict_le_self).congr (indicator_ae_eq_restrict hs) }, { intro h, refine ⟨indicator s (h.mk f), h.measurable_mk.indicator hs, _⟩, have A : s.indicator f =ᵐ[μ.restrict s] s.indicator (ae_measurable.mk f h) := (indicator_ae_eq_restrict hs).trans (h.ae_eq_mk.trans $ (indicator_ae_eq_restrict hs).symm), have B : s.indicator f =ᵐ[μ.restrict sᶜ] s.indicator (ae_measurable.mk f h) := (indicator_ae_eq_restrict_compl hs).trans (indicator_ae_eq_restrict_compl hs).symm, exact ae_of_ae_restrict_of_ae_restrict_compl _ A B }, end @[measurability] lemma ae_measurable.indicator (hfm : ae_measurable f μ) {s} (hs : measurable_set s) : ae_measurable (s.indicator f) μ := (ae_measurable_indicator_iff hs).mpr hfm.restrict lemma measure_theory.measure.restrict_map_of_ae_measurable {f : α → δ} (hf : ae_measurable f μ) {s : set δ} (hs : measurable_set s) : (μ.map f).restrict s = (μ.restrict $ f ⁻¹' s).map f := calc (μ.map f).restrict s = (μ.map (hf.mk f)).restrict s : by { congr' 1, apply measure.map_congr hf.ae_eq_mk } ... = (μ.restrict $ (hf.mk f) ⁻¹' s).map (hf.mk f) : measure.restrict_map hf.measurable_mk hs ... = (μ.restrict $ (hf.mk f) ⁻¹' s).map f : measure.map_congr (ae_restrict_of_ae (hf.ae_eq_mk.symm)) ... = (μ.restrict $ f ⁻¹' s).map f : begin apply congr_arg, ext1 t ht, simp only [ht, measure.restrict_apply], apply measure_congr, apply (eventually_eq.refl _ _).inter (hf.ae_eq_mk.symm.preimage s) end lemma measure_theory.measure.map_mono_of_ae_measurable {f : α → δ} (h : μ ≤ ν) (hf : ae_measurable f ν) : μ.map f ≤ ν.map f := λ s hs, by simpa [hf, hs, hf.mono_measure h] using measure.le_iff'.1 h (f ⁻¹' s)
22ba4cc412118d5bbbc6dc5b9837dfe07e810434
c777c32c8e484e195053731103c5e52af26a25d1
/src/data/set/intervals/unordered_interval.lean
1e795686afe08e359962e8ad0dd662cd6cc44123
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
10,359
lean
/- Copyright (c) 2020 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou -/ import order.bounds.basic import data.set.intervals.basic /-! # Intervals without endpoints ordering > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In any lattice `α`, we define `uIcc a b` to be `Icc (a ⊓ b) (a ⊔ b)`, which in a linear order is the set of elements lying between `a` and `b`. `Icc a b` requires the assumption `a ≤ b` to be meaningful, which is sometimes inconvenient. The interval as defined in this file is always the set of things lying between `a` and `b`, regardless of the relative order of `a` and `b`. For real numbers, `uIcc a b` is the same as `segment ℝ a b`. In a product or pi type, `uIcc a b` is the smallest box containing `a` and `b`. For example, `uIcc (1, -1) (-1, 1) = Icc (-1, -1) (1, 1)` is the square of vertices `(1, -1)`, `(-1, -1)`, `(-1, 1)`, `(1, 1)`. In `finset α` (seen as a hypercube of dimension `fintype.card α`), `uIcc a b` is the smallest subcube containing both `a` and `b`. ## Notation We use the localized notation `[a, b]` for `uIcc a b`. One can open the locale `interval` to make the notation available. -/ open function order_dual (to_dual of_dual) variables {α β : Type*} namespace set section lattice variables [lattice α] [lattice β] {a a₁ a₂ b b₁ b₂ c x : α} /-- `uIcc a b` is the set of elements lying between `a` and `b`, with `a` and `b` included. Note that we define it more generally in a lattice as `set.Icc (a ⊓ b) (a ⊔ b)`. In a product type, `uIcc` corresponds to the bounding box of the two elements. -/ def uIcc (a b : α) : set α := Icc (a ⊓ b) (a ⊔ b) localized "notation (name := set.uIcc) `[`a `, ` b `]` := set.uIcc a b" in interval @[simp] lemma dual_uIcc (a b : α) : [to_dual a, to_dual b] = of_dual ⁻¹' [a, b] := dual_Icc @[simp] lemma uIcc_of_le (h : a ≤ b) : [a, b] = Icc a b := by rw [uIcc, inf_eq_left.2 h, sup_eq_right.2 h] @[simp] lemma uIcc_of_ge (h : b ≤ a) : [a, b] = Icc b a := by rw [uIcc, inf_eq_right.2 h, sup_eq_left.2 h] lemma uIcc_comm (a b : α) : [a, b] = [b, a] := by simp_rw [uIcc, inf_comm, sup_comm] lemma uIcc_of_lt (h : a < b) : [a, b] = Icc a b := uIcc_of_le h.le lemma uIcc_of_gt (h : b < a) : [a, b] = Icc b a := uIcc_of_ge h.le @[simp] lemma uIcc_self : [a, a] = {a} := by simp [uIcc] @[simp] lemma nonempty_uIcc : [a, b].nonempty := nonempty_Icc.2 inf_le_sup lemma Icc_subset_uIcc : Icc a b ⊆ [a, b] := Icc_subset_Icc inf_le_left le_sup_right lemma Icc_subset_uIcc' : Icc b a ⊆ [a, b] := Icc_subset_Icc inf_le_right le_sup_left @[simp] lemma left_mem_uIcc : a ∈ [a, b] := ⟨inf_le_left, le_sup_left⟩ @[simp] lemma right_mem_uIcc : b ∈ [a, b] := ⟨inf_le_right, le_sup_right⟩ lemma mem_uIcc_of_le (ha : a ≤ x) (hb : x ≤ b) : x ∈ [a, b] := Icc_subset_uIcc ⟨ha, hb⟩ lemma mem_uIcc_of_ge (hb : b ≤ x) (ha : x ≤ a) : x ∈ [a, b] := Icc_subset_uIcc' ⟨hb, ha⟩ lemma uIcc_subset_uIcc (h₁ : a₁ ∈ [a₂, b₂]) (h₂ : b₁ ∈ [a₂, b₂]) : [a₁, b₁] ⊆ [a₂, b₂] := Icc_subset_Icc (le_inf h₁.1 h₂.1) (sup_le h₁.2 h₂.2) lemma uIcc_subset_Icc (ha : a₁ ∈ Icc a₂ b₂) (hb : b₁ ∈ Icc a₂ b₂) : [a₁, b₁] ⊆ Icc a₂ b₂ := Icc_subset_Icc (le_inf ha.1 hb.1) (sup_le ha.2 hb.2) lemma uIcc_subset_uIcc_iff_mem : [a₁, b₁] ⊆ [a₂, b₂] ↔ a₁ ∈ [a₂, b₂] ∧ b₁ ∈ [a₂, b₂] := iff.intro (λh, ⟨h left_mem_uIcc, h right_mem_uIcc⟩) (λ h, uIcc_subset_uIcc h.1 h.2) lemma uIcc_subset_uIcc_iff_le' : [a₁, b₁] ⊆ [a₂, b₂] ↔ a₂ ⊓ b₂ ≤ a₁ ⊓ b₁ ∧ a₁ ⊔ b₁ ≤ a₂ ⊔ b₂ := Icc_subset_Icc_iff inf_le_sup lemma uIcc_subset_uIcc_right (h : x ∈ [a, b]) : [x, b] ⊆ [a, b] := uIcc_subset_uIcc h right_mem_uIcc lemma uIcc_subset_uIcc_left (h : x ∈ [a, b]) : [a, x] ⊆ [a, b] := uIcc_subset_uIcc left_mem_uIcc h lemma bdd_below_bdd_above_iff_subset_uIcc (s : set α) : bdd_below s ∧ bdd_above s ↔ ∃ a b, s ⊆ [a, b] := bdd_below_bdd_above_iff_subset_Icc.trans ⟨λ ⟨a, b, h⟩, ⟨a, b, λ x hx, Icc_subset_uIcc (h hx)⟩, λ ⟨a, b, h⟩, ⟨_, _, h⟩⟩ section prod @[simp] lemma uIcc_prod_uIcc (a₁ a₂ : α) (b₁ b₂ : β) : [a₁, a₂] ×ˢ [b₁, b₂] = [(a₁, b₁), (a₂, b₂)] := Icc_prod_Icc _ _ _ _ lemma uIcc_prod_eq (a b : α × β) : [a, b] = [a.1, b.1] ×ˢ [a.2, b.2] := by simp end prod end lattice open_locale interval section distrib_lattice variables [distrib_lattice α] {a a₁ a₂ b b₁ b₂ c x : α} lemma eq_of_mem_uIcc_of_mem_uIcc (ha : a ∈ [b, c]) (hb : b ∈ [a, c]) : a = b := eq_of_inf_eq_sup_eq (inf_congr_right ha.1 hb.1) $ sup_congr_right ha.2 hb.2 lemma eq_of_mem_uIcc_of_mem_uIcc' : b ∈ [a, c] → c ∈ [a, b] → b = c := by simpa only [uIcc_comm a] using eq_of_mem_uIcc_of_mem_uIcc lemma uIcc_injective_right (a : α) : injective (λ b, uIcc b a) := λ b c h, by { rw ext_iff at h, exact eq_of_mem_uIcc_of_mem_uIcc ((h _).1 left_mem_uIcc) ((h _).2 left_mem_uIcc) } lemma uIcc_injective_left (a : α) : injective (uIcc a) := by simpa only [uIcc_comm] using uIcc_injective_right a end distrib_lattice section linear_order variables [linear_order α] [linear_order β] {f : α → β} {s : set α} {a a₁ a₂ b b₁ b₂ c d x : α} lemma Icc_min_max : Icc (min a b) (max a b) = [a, b] := rfl lemma uIcc_of_not_le (h : ¬ a ≤ b) : [a, b] = Icc b a := uIcc_of_gt $ lt_of_not_ge h lemma uIcc_of_not_ge (h : ¬ b ≤ a) : [a, b] = Icc a b := uIcc_of_lt $ lt_of_not_ge h lemma uIcc_eq_union : [a, b] = Icc a b ∪ Icc b a := by rw [Icc_union_Icc', max_comm]; refl lemma mem_uIcc : a ∈ [b, c] ↔ b ≤ a ∧ a ≤ c ∨ c ≤ a ∧ a ≤ b := by simp [uIcc_eq_union] lemma not_mem_uIcc_of_lt (ha : c < a) (hb : c < b) : c ∉ [a, b] := not_mem_Icc_of_lt $ lt_min_iff.mpr ⟨ha, hb⟩ lemma not_mem_uIcc_of_gt (ha : a < c) (hb : b < c) : c ∉ [a, b] := not_mem_Icc_of_gt $ max_lt_iff.mpr ⟨ha, hb⟩ lemma uIcc_subset_uIcc_iff_le : [a₁, b₁] ⊆ [a₂, b₂] ↔ min a₂ b₂ ≤ min a₁ b₁ ∧ max a₁ b₁ ≤ max a₂ b₂ := uIcc_subset_uIcc_iff_le' /-- A sort of triangle inequality. -/ lemma uIcc_subset_uIcc_union_uIcc : [a, c] ⊆ [a, b] ∪ [b, c] := λ x, by simp only [mem_uIcc, mem_union]; cases le_total a c; cases le_total x b; tauto lemma monotone_or_antitone_iff_uIcc : monotone f ∨ antitone f ↔ ∀ a b c, c ∈ [a, b] → f c ∈ [f a, f b] := begin split, { rintro (hf | hf) a b c; simp_rw [←Icc_min_max, ←hf.map_min, ←hf.map_max], exacts [λ hc, ⟨hf hc.1, hf hc.2⟩, λ hc, ⟨hf hc.2, hf hc.1⟩] }, contrapose!, rw not_monotone_not_antitone_iff_exists_le_le, rintro ⟨a, b, c, hab, hbc, ⟨hfab, hfcb⟩ | ⟨hfba, hfbc⟩⟩, { exact ⟨a, c, b, Icc_subset_uIcc ⟨hab, hbc⟩, λ h, h.2.not_lt $ max_lt hfab hfcb⟩ }, { exact ⟨a, c, b, Icc_subset_uIcc ⟨hab, hbc⟩, λ h, h.1.not_lt $ lt_min hfba hfbc⟩ } end lemma monotone_on_or_antitone_on_iff_uIcc : monotone_on f s ∨ antitone_on f s ↔ ∀ a b c ∈ s, c ∈ [a, b] → f c ∈ [f a, f b] := by simp [monotone_on_iff_monotone, antitone_on_iff_antitone, monotone_or_antitone_iff_uIcc, mem_uIcc] /-- The open-closed interval with unordered bounds. -/ def uIoc : α → α → set α := λ a b, Ioc (min a b) (max a b) -- Below is a capital iota localized "notation `Ι` := set.uIoc" in interval @[simp] lemma uIoc_of_le (h : a ≤ b) : Ι a b = Ioc a b := by simp [uIoc, h] @[simp] lemma uIoc_of_lt (h : b < a) : Ι a b = Ioc b a := by simp [uIoc, h.le] lemma uIoc_eq_union : Ι a b = Ioc a b ∪ Ioc b a := by cases le_total a b; simp [uIoc, *] lemma mem_uIoc : a ∈ Ι b c ↔ b < a ∧ a ≤ c ∨ c < a ∧ a ≤ b := by simp only [uIoc_eq_union, mem_union, mem_Ioc] lemma not_mem_uIoc : a ∉ Ι b c ↔ a ≤ b ∧ a ≤ c ∨ c < a ∧ b < a := by { simp only [uIoc_eq_union, mem_union, mem_Ioc, not_lt, ←not_le], tauto } @[simp] lemma left_mem_uIoc : a ∈ Ι a b ↔ b < a := by simp [mem_uIoc] @[simp] lemma right_mem_uIoc : b ∈ Ι a b ↔ a < b := by simp [mem_uIoc] lemma forall_uIoc_iff {P : α → Prop} : (∀ x ∈ Ι a b, P x) ↔ (∀ x ∈ Ioc a b, P x) ∧ (∀ x ∈ Ioc b a, P x) := by simp only [uIoc_eq_union, mem_union, or_imp_distrib, forall_and_distrib] lemma uIoc_subset_uIoc_of_uIcc_subset_uIcc (h : [a, b] ⊆ [c, d]) : Ι a b ⊆ Ι c d := Ioc_subset_Ioc (uIcc_subset_uIcc_iff_le.1 h).1 (uIcc_subset_uIcc_iff_le.1 h).2 lemma uIoc_swap (a b : α) : Ι a b = Ι b a := by simp only [uIoc, min_comm a b, max_comm a b] lemma Ioc_subset_uIoc : Ioc a b ⊆ Ι a b := Ioc_subset_Ioc (min_le_left _ _) (le_max_right _ _) lemma Ioc_subset_uIoc' : Ioc a b ⊆ Ι b a := Ioc_subset_Ioc (min_le_right _ _) (le_max_left _ _) lemma eq_of_mem_uIoc_of_mem_uIoc : a ∈ Ι b c → b ∈ Ι a c → a = b := by simp_rw mem_uIoc; rintro (⟨_, _⟩ | ⟨_, _⟩) (⟨_, _⟩ | ⟨_, _⟩); apply le_antisymm; assumption <|> exact le_of_lt ‹_› <|> exact le_trans ‹_› (le_of_lt ‹_›) lemma eq_of_mem_uIoc_of_mem_uIoc' : b ∈ Ι a c → c ∈ Ι a b → b = c := by simpa only [uIoc_swap a] using eq_of_mem_uIoc_of_mem_uIoc lemma eq_of_not_mem_uIoc_of_not_mem_uIoc (ha : a ≤ c) (hb : b ≤ c) : a ∉ Ι b c → b ∉ Ι a c → a = b := by simp_rw not_mem_uIoc; rintro (⟨_, _⟩ | ⟨_, _⟩) (⟨_, _⟩ | ⟨_, _⟩); apply le_antisymm; assumption <|> exact le_of_lt ‹_› <|> cases not_le_of_lt ‹_› ‹_› lemma uIoc_injective_right (a : α) : injective (λ b, Ι b a) := begin rintro b c h, rw ext_iff at h, obtain ha | ha := le_or_lt b a, { have hb := (h b).not, simp only [ha, left_mem_uIoc, not_lt, true_iff, not_mem_uIoc, ←not_le, and_true, not_true, false_and, not_false_iff, true_iff, or_false] at hb, refine hb.eq_of_not_lt (λ hc, _), simpa [ha, and_iff_right hc, ←@not_le _ _ _ a, -not_le] using h c }, { refine eq_of_mem_uIoc_of_mem_uIoc ((h _).1 $ left_mem_uIoc.2 ha) ((h _).2 $ left_mem_uIoc.2 $ ha.trans_le _), simpa [ha, ha.not_le, mem_uIoc] using h b } end lemma uIoc_injective_left (a : α) : injective (Ι a) := by simpa only [uIoc_swap] using uIoc_injective_right a end linear_order end set
714d736c68b784c4d4ca01566360634ed3e90a33
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/measure_theory/interval_integral.lean
aa28f339e65d074d4cc21682eab0e9935812d17c
[ "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
77,100
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Yury G. Kudryashov -/ import measure_theory.set_integral import measure_theory.lebesgue_measure import analysis.calculus.fderiv_measurable import analysis.calculus.extend_deriv /-! # Integral over an interval In this file we define `∫ x in a..b, f x ∂μ` to be `∫ x in Ioc a b, f x ∂μ` if `a ≤ b` and `-∫ x in Ioc b a, f x ∂μ` if `b ≤ a`. We prove a few simple properties and many versions of the first part of the [fundamental theorem of calculus](https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus). Recall that it states that the function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(δu, δv) ↦ δv • f b - δu • f a` at `(a, b)` provided that `f` is continuous at `a` and `b`. ## Main statements ### FTC-1 for Lebesgue measure We prove several versions of FTC-1, all in the `interval_integral` namespace. Many of them follow the naming scheme `integral_has(_strict?)_(f?)deriv(_within?)_at(_of_tendsto_ae?)(_right|_left?)`. They formulate FTC in terms of `has(_strict?)_(f?)deriv(_within?)_at`. Let us explain the meaning of each part of the name: * `_strict` means that the theorem is about strict differentiability; * `f` means that the theorem is about differentiability in both endpoints; incompatible with `_right|_left`; * `_within` means that the theorem is about one-sided derivatives, see below for details; * `_of_tendsto_ae` means that instead of continuity the theorem assumes that `f` has a finite limit almost surely as `x` tends to `a` and/or `b`; * `_right` or `_left` mean that the theorem is about differentiability in the right (resp., left) endpoint. We also reformulate these theorems in terms of `(f?)deriv(_within?)`. These theorems are named `(f?)deriv(_within?)_integral(_of_tendsto_ae?)(_right|_left?)` with the same meaning of parts of the name. ### One-sided derivatives Theorem `integral_has_fderiv_within_at_of_tendsto_ae` states that `(u, v) ↦ ∫ x in u..v, f x` has a derivative `(δu, δv) ↦ δv • cb - δu • ca` within the set `s × t` at `(a, b)` provided that `f` tends to `ca` (resp., `cb`) almost surely at `la` (resp., `lb`), where possible values of `s`, `t`, and corresponding filters `la`, `lb` are given in the following table. | `s` | `la` | `t` | `lb` | | ------- | ---- | --- | ---- | | `Iic a` | `𝓝[Iic a] a` | `Iic b` | `𝓝[Iic b] b` | | `Ici a` | `𝓝[Ioi a] a` | `Ici b` | `𝓝[Ioi b] b` | | `{a}` | `⊥` | `{b}` | `⊥` | | `univ` | `𝓝 a` | `univ` | `𝓝 b` | We use a typeclass `FTC_filter` to make Lean automatically find `la`/`lb` based on `s`/`t`. This way we can formulate one theorem instead of `16` (or `8` if we leave only non-trivial ones not covered by `integral_has_deriv_within_at_of_tendsto_ae_(left|right)` and `integral_has_fderiv_at_of_tendsto_ae`). Similarly, `integral_has_deriv_within_at_of_tendsto_ae_right` works for both one-sided derivatives using the same typeclass to find an appropriate filter. ### FTC for a locally finite measure Before proving FTC for the Lebesgue measure, we prove a few statements that can be seen as FTC for any measure. The most general of them, `measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae`, states the following. Let `(la, la')` be an `FTC_filter` pair of filters around `a` (i.e., `FTC_filter a la la'`) and let `(lb, lb')` be an `FTC_filter` pair of filters around `b`. If `f` has finite limits `ca` and `cb` almost surely at `la'` and `lb'`, respectively, then `∫ x in va..vb, f x ∂μ - ∫ x in ua..ub, f x ∂μ = ∫ x in ub..vb, cb ∂μ - ∫ x in ua..va, ca ∂μ + o(∥∫ x in ua..va, (1:ℝ) ∂μ∥ + ∥∫ x in ub..vb, (1:ℝ) ∂μ∥)` as `ua` and `va` tend to `la` while `ub` and `vb` tend to `lb`. ## Implementation notes ### Avoiding `if`, `min`, and `max` In order to avoid `if`s in the definition, we define `interval_integrable f μ a b` as `integrable_on f (Ioc a b) μ ∧ integrable_on f (Ioc b a) μ`. For any `a`, `b` one of these intervals is empty and the other coincides with `Ioc (min a b) (max a b)`. Similarly, we define `∫ x in a..b, f x ∂μ` to be `∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ`. Again, for any `a`, `b` one of these integrals is zero, and the other gives the expected result. This way some properties can be translated from integrals over sets without dealing with the cases `a ≤ b` and `b ≤ a` separately. ### Choice of the interval We use integral over `Ioc (min a b) (max a b)` instead of one of the other three possible intervals with the same endpoints for two reasons: * this way `∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ = ∫ x in a..c, f x ∂μ` holds whenever `f` is integrable on each interval; in particular, it works even if the measure `μ` has an atom at `b`; this rules out `Ioo` and `Icc` intervals; * with this definition for a probability measure `μ`, the integral `∫ x in a..b, 1 ∂μ` equals the difference $F_μ(b)-F_μ(a)$, where $F_μ(a)=μ(-∞, a]$ is the [cumulative distribution function](https://en.wikipedia.org/wiki/Cumulative_distribution_function) of `μ`. ### `FTC_filter` class As explained above, many theorems in this file rely on the typeclass `FTC_filter (a : α) (l l' : filter α)` to avoid code duplication. This typeclass combines four assumptions: - `pure a ≤ l`; - `l' ≤ 𝓝 a`; - `l'` has a basis of measurable sets; - if `u n` and `v n` tend to `l`, then for any `s ∈ l'`, `Ioc (u n) (v n)` is eventually included in `s`. This typeclass has exactly four “real” instances: `(a, pure a, ⊥)`, `(a, 𝓝[Ici a] a, 𝓝[Ioi a] a)`, `(a, 𝓝[Iic a] a, 𝓝[Iic a] a)`, `(a, 𝓝 a, 𝓝 a)`, and two instances that are equal to the first and last “real” instances: `(a, 𝓝[{a}] a, ⊥)` and `(a, 𝓝[univ] a, 𝓝[univ] a)`. While the difference between `Ici a` and `Ioi a` doesn't matter for theorems about Lebesgue measure, it becomes important in the versions of FTC about any locally finite measure if this measure has an atom at one of the endpoints. ## Tags integral, fundamental theorem of calculus -/ noncomputable theory open topological_space (second_countable_topology) open measure_theory set classical filter open_locale classical topological_space filter variables {α β 𝕜 E F : Type*} [linear_order α] [measurable_space α] [measurable_space E] [normed_group E] /-! ### Integrability at an interval -/ /-- A function `f` is called *interval integrable* with respect to a measure `μ` on an unordered interval `a..b` if it is integrable on both intervals `(a, b]` and `(b, a]`. One of these intervals is always empty, so this property is equivalent to `f` being integrable on `(min a b, max a b]`. -/ def interval_integrable (f : α → E) (μ : measure α) (a b : α) := integrable_on f (Ioc a b) μ ∧ integrable_on f (Ioc b a) μ lemma measure_theory.integrable.interval_integrable {f : α → E} {μ : measure α} (hf : integrable f μ) {a b : α} : interval_integrable f μ a b := ⟨hf.integrable_on, hf.integrable_on⟩ namespace interval_integrable section variables {f : α → E} {a b c : α} {μ : measure α} @[symm] lemma symm (h : interval_integrable f μ a b) : interval_integrable f μ b a := h.symm @[refl] lemma refl : interval_integrable f μ a a := by split; simp @[trans] lemma trans (hab : interval_integrable f μ a b) (hbc : interval_integrable f μ b c) : interval_integrable f μ a c := ⟨(hab.1.union hbc.1).mono_set Ioc_subset_Ioc_union_Ioc, (hbc.2.union hab.2).mono_set Ioc_subset_Ioc_union_Ioc⟩ lemma neg [borel_space E] (h : interval_integrable f μ a b) : interval_integrable (-f) μ a b := ⟨h.1.neg, h.2.neg⟩ protected lemma ae_measurable (h : interval_integrable f μ a b) : ae_measurable f (μ.restrict (Ioc a b)):= h.1.ae_measurable protected lemma ae_measurable' (h : interval_integrable f μ a b) : ae_measurable f (μ.restrict (Ioc b a)):= h.2.ae_measurable end variables [borel_space E] {f g : α → E} {a b : α} {μ : measure α} lemma smul [normed_field 𝕜] [normed_space 𝕜 E] {f : α → E} {a b : α} {μ : measure α} (h : interval_integrable f μ a b) (r : 𝕜) : interval_integrable (r • f) μ a b := ⟨h.1.smul r, h.2.smul r⟩ lemma add [second_countable_topology E] (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) : interval_integrable (f + g) μ a b := ⟨hf.1.add hg.1, hf.2.add hg.2⟩ lemma sub [second_countable_topology E] (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) : interval_integrable (f - g) μ a b := ⟨hf.1.sub hg.1, hf.2.sub hg.2⟩ end interval_integrable section variables {μ : measure ℝ} [locally_finite_measure μ] lemma continuous_on.interval_integrable [borel_space E] {u : ℝ → E} {a b : ℝ} (hu : continuous_on u (interval a b)) : interval_integrable u μ a b := begin split, all_goals { refine measure_theory.integrable_on.mono_set _ Ioc_subset_Icc_self, refine continuous_on.integrable_on_compact compact_Icc (hu.mono _) }, exacts [Icc_subset_interval, Icc_subset_interval'] end lemma continuous_on.interval_integrable_of_Icc [borel_space E] {u : ℝ → E} {a b : ℝ} (h : a ≤ b) (hu : continuous_on u (Icc a b)) : interval_integrable u μ a b := continuous_on.interval_integrable ((interval_of_le h).symm ▸ hu) /-- A continuous function on `ℝ` is `interval_integrable` with respect to any locally finite measure `ν` on ℝ. -/ lemma continuous.interval_integrable [borel_space E] {u : ℝ → E} (hu : continuous u) (a b : ℝ) : interval_integrable u μ a b := hu.continuous_on.interval_integrable end /-- Let `l'` be a measurably generated filter; let `l` be a of filter such that each `s ∈ l'` eventually includes `Ioc u v` as both `u` and `v` tend to `l`. Let `μ` be a measure finite at `l'`. Suppose that `f : α → E` has a finite limit at `l' ⊓ μ.ae`. Then `f` is interval integrable on `u..v` provided that both `u` and `v` tend to `l`. Typeclass instances allow Lean to find `l'` based on `l` but not vice versa, so `apply tendsto.eventually_interval_integrable_ae` will generate goals `filter α` and `tendsto_Ixx_class Ioc ?m_1 l'`. -/ lemma filter.tendsto.eventually_interval_integrable_ae {f : α → E} {μ : measure α} {l l' : filter α} (hfm : measurable_at_filter f l' μ) [tendsto_Ixx_class Ioc l l'] [is_measurably_generated l'] (hμ : μ.finite_at_filter l') {c : E} (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) {u v : β → α} {lt : filter β} (hu : tendsto u lt l) (hv : tendsto v lt l) : ∀ᶠ t in lt, interval_integrable f μ (u t) (v t) := have _ := (hf.integrable_at_filter_ae hfm hμ).eventually, ((hu.Ioc hv).eventually this).and $ (hv.Ioc hu).eventually this /-- Let `l'` be a measurably generated filter; let `l` be a of filter such that each `s ∈ l'` eventually includes `Ioc u v` as both `u` and `v` tend to `l`. Let `μ` be a measure finite at `l'`. Suppose that `f : α → E` has a finite limit at `l`. Then `f` is interval integrable on `u..v` provided that both `u` and `v` tend to `l`. Typeclass instances allow Lean to find `l'` based on `l` but not vice versa, so `apply tendsto.eventually_interval_integrable_ae` will generate goals `filter α` and `tendsto_Ixx_class Ioc ?m_1 l'`. -/ lemma filter.tendsto.eventually_interval_integrable {f : α → E} {μ : measure α} {l l' : filter α} (hfm : measurable_at_filter f l' μ) [tendsto_Ixx_class Ioc l l'] [is_measurably_generated l'] (hμ : μ.finite_at_filter l') {c : E} (hf : tendsto f l' (𝓝 c)) {u v : β → α} {lt : filter β} (hu : tendsto u lt l) (hv : tendsto v lt l) : ∀ᶠ t in lt, interval_integrable f μ (u t) (v t) := (hf.mono_left inf_le_left).eventually_interval_integrable_ae hfm hμ hu hv /-! ### Interval integral: definition and basic properties In this section we define `∫ x in a..b, f x ∂μ` as `∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ` and prove some basic properties. -/ variables [second_countable_topology E] [complete_space E] [normed_space ℝ E] [borel_space E] /-- The interval integral `∫ x in a..b, f x ∂μ` is defined as `∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ`. If `a ≤ b`, then it equals `∫ x in Ioc a b, f x ∂μ`, otherwise it equals `-∫ x in Ioc b a, f x ∂μ`. -/ def interval_integral (f : α → E) (a b : α) (μ : measure α) := ∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ notation `∫` binders ` in ` a `..` b `, ` r:(scoped:60 f, f) ` ∂` μ:70 := interval_integral r a b μ notation `∫` binders ` in ` a `..` b `, ` r:(scoped:60 f, interval_integral f a b volume) := r namespace interval_integral section variables {a b c d : α} {f g : α → E} {μ : measure α} @[simp] lemma integral_zero : ∫ x in a..b, (0 : E) ∂μ = 0 := by simp [interval_integral] lemma integral_of_le (h : a ≤ b) : ∫ x in a..b, f x ∂μ = ∫ x in Ioc a b, f x ∂μ := by simp [interval_integral, h] @[simp] lemma integral_same : ∫ x in a..a, f x ∂μ = 0 := sub_self _ lemma integral_symm (a b) : ∫ x in b..a, f x ∂μ = -∫ x in a..b, f x ∂μ := by simp only [interval_integral, neg_sub] lemma integral_of_ge (h : b ≤ a) : ∫ x in a..b, f x ∂μ = -∫ x in Ioc b a, f x ∂μ := by simp only [integral_symm b, integral_of_le h] lemma integral_cases (f : α → E) (a b) : ∫ x in a..b, f x ∂μ ∈ ({∫ x in Ioc (min a b) (max a b), f x ∂μ, -∫ x in Ioc (min a b) (max a b), f x ∂μ} : set E) := (le_total a b).imp (λ h, by simp [h, integral_of_le]) (λ h, by simp [h, integral_of_ge]) lemma integral_non_ae_measurable {f : α → E} {a b} (h : a < b) (hf : ¬ ae_measurable f (μ.restrict (Ioc a b))) : ∫ x in a..b, f x ∂μ = 0 := by rw [integral_of_le h.le, integral_non_ae_measurable hf] lemma norm_integral_eq_norm_integral_Ioc : ∥∫ x in a..b, f x ∂μ∥ = ∥∫ x in Ioc (min a b) (max a b), f x ∂μ∥ := (integral_cases f a b).elim (congr_arg _) (λ h, (congr_arg _ h).trans (norm_neg _)) lemma norm_integral_le_integral_norm_Ioc : ∥∫ x in a..b, f x ∂μ∥ ≤ ∫ x in Ioc (min a b) (max a b), ∥f x∥ ∂μ := calc ∥∫ x in a..b, f x ∂μ∥ = ∥∫ x in Ioc (min a b) (max a b), f x ∂μ∥ : norm_integral_eq_norm_integral_Ioc ... ≤ ∫ x in Ioc (min a b) (max a b), ∥f x∥ ∂μ : norm_integral_le_integral_norm f lemma norm_integral_le_abs_integral_norm : ∥∫ x in a..b, f x ∂μ∥ ≤ abs (∫ x in a..b, ∥f x∥ ∂μ) := begin simp only [← real.norm_eq_abs, norm_integral_eq_norm_integral_Ioc], exact le_trans (norm_integral_le_integral_norm _) (le_abs_self _) end lemma norm_integral_le_of_norm_le_const_ae {a b C : ℝ} {f : ℝ → E} (h : ∀ᵐ x, x ∈ Ioc (min a b) (max a b) → ∥f x∥ ≤ C) : ∥∫ x in a..b, f x∥ ≤ C * abs (b - a) := begin rw [norm_integral_eq_norm_integral_Ioc], convert norm_set_integral_le_of_norm_le_const_ae'' _ is_measurable_Ioc h, { rw [real.volume_Ioc, max_sub_min_eq_abs, ennreal.to_real_of_real (abs_nonneg _)] }, { simp only [real.volume_Ioc, ennreal.of_real_lt_top] }, end lemma norm_integral_le_of_norm_le_const {a b C : ℝ} {f : ℝ → E} (h : ∀ x ∈ Ioc (min a b) (max a b), ∥f x∥ ≤ C) : ∥∫ x in a..b, f x∥ ≤ C * abs (b - a) := norm_integral_le_of_norm_le_const_ae $ eventually_of_forall h lemma integral_add (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) : ∫ x in a..b, f x + g x ∂μ = ∫ x in a..b, f x ∂μ + ∫ x in a..b, g x ∂μ := by { simp only [interval_integral, integral_add hf.1 hg.1, integral_add hf.2 hg.2], abel } @[simp] lemma integral_neg : ∫ x in a..b, -f x ∂μ = -∫ x in a..b, f x ∂μ := by { simp only [interval_integral, integral_neg], abel } lemma integral_sub (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) : ∫ x in a..b, f x - g x ∂μ = ∫ x in a..b, f x ∂μ - ∫ x in a..b, g x ∂μ := by simpa only [sub_eq_add_neg] using (integral_add hf hg.neg).trans (congr_arg _ integral_neg) lemma integral_smul (r : ℝ) : ∫ x in a..b, r • f x ∂μ = r • ∫ x in a..b, f x ∂μ := by simp only [interval_integral, integral_smul, smul_sub] lemma integral_const' (c : E) : ∫ x in a..b, c ∂μ = ((μ $ Ioc a b).to_real - (μ $ Ioc b a).to_real) • c := by simp only [interval_integral, set_integral_const, sub_smul] lemma integral_const {a b : ℝ} (c : E) : (∫ (x : ℝ) in a..b, c) = (b - a) • c := by simp only [integral_const', real.volume_Ioc, ennreal.to_real_of_real', ← neg_sub b, max_zero_sub_eq_self] lemma integral_smul_measure (c : ennreal) : ∫ x in a..b, f x ∂(c • μ) = c.to_real • ∫ x in a..b, f x ∂μ := by simp only [interval_integral, measure.restrict_smul, integral_smul_measure, smul_sub] lemma integral_comp_add_right (a b c : ℝ) (f : ℝ → E) (hfm : ae_measurable f) : ∫ x in a..b, f (x + c) = ∫ x in a+c..b+c, f x := have A : ae_measurable f (measure.map (λ x, x + c) volume), by rwa [real.map_volume_add_right], calc ∫ x in a..b, f (x + c) = ∫ x in a+c..b+c, f x ∂(measure.map (λ x, x + c) volume) : by simp only [interval_integral, set_integral_map is_measurable_Ioc A (measurable_add_right _), preimage_add_const_Ioc, add_sub_cancel] ... = ∫ x in a+c..b+c, f x : by rw [real.map_volume_add_right] lemma integral_comp_mul_right {c : ℝ} (hc : 0 < c) (a b : ℝ) (f : ℝ → E) (hfm : ae_measurable f) : ∫ x in a..b, f (x * c) = c⁻¹ • ∫ x in a*c..b*c, f x := begin have A : ae_measurable f (measure.map (λ (x : ℝ), x*c) volume), by { rw real.map_volume_mul_right (ne_of_gt hc), exact hfm.smul_measure _ }, conv_rhs { rw [← real.smul_map_volume_mul_right (ne_of_gt hc)] }, rw [integral_smul_measure], simp only [interval_integral, set_integral_map is_measurable_Ioc A (measurable_mul_right _), hc, preimage_mul_const_Ioc, mul_div_cancel _ (ne_of_gt hc), abs_of_pos, ennreal.to_real_of_real (le_of_lt hc), inv_smul_smul' (ne_of_gt hc)], end lemma integral_comp_neg (a b : ℝ) (f : ℝ → E) (hfm : ae_measurable f) : ∫ x in a..b, f (-x) = ∫ x in -b..-a, f x := begin have A : ae_measurable f (measure.map (λ (x : ℝ), -x) volume), by rwa real.map_volume_neg, conv_rhs { rw ← real.map_volume_neg }, simp only [interval_integral, set_integral_map is_measurable_Ioc A measurable_neg, neg_preimage, preimage_neg_Ioc, neg_neg, restrict_congr_set Ico_ae_eq_Ioc] end /-! ### Integral is an additive function of the interval In this section we prove that `∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ = ∫ x in a..c, f x ∂μ` as well as a few other identities trivially equivalent to this one. We also prove that `∫ x in a..b, f x ∂μ = ∫ x, f x ∂μ` provided that `support f ⊆ Ioc a b`. -/ variables [topological_space α] [opens_measurable_space α] section order_closed_topology variables [order_closed_topology α] /-- If two functions are equal in the relevant interval, their interval integrals are also equal. -/ lemma integral_congr {a b : α} {f g : α → E} (h : eq_on f g (interval a b)) : ∫ x in a..b, f x ∂μ = ∫ x in a..b, g x ∂μ := by cases le_total a b with hab hab; simpa [hab, integral_of_le, integral_of_ge] using set_integral_congr is_measurable_Ioc (h.mono Ioc_subset_Icc_self) lemma integral_add_adjacent_intervals_cancel (hab : interval_integrable f μ a b) (hbc : interval_integrable f μ b c) : ∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ + ∫ x in c..a, f x ∂μ = 0 := begin have hac := hab.trans hbc, simp only [interval_integral, ← add_sub_comm, sub_eq_zero], iterate 4 { rw ← integral_union }, { suffices : Ioc a b ∪ Ioc b c ∪ Ioc c a = Ioc b a ∪ Ioc c b ∪ Ioc a c, by rw this, rw [Ioc_union_Ioc_union_Ioc_cycle, union_right_comm, Ioc_union_Ioc_union_Ioc_cycle, min_left_comm, max_left_comm] }, all_goals { simp [*, is_measurable.union, is_measurable_Ioc, Ioc_disjoint_Ioc_same, Ioc_disjoint_Ioc_same.symm, hab.1, hab.2, hbc.1, hbc.2, hac.1, hac.2] } end lemma integral_add_adjacent_intervals (hab : interval_integrable f μ a b) (hbc : interval_integrable f μ b c) : ∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ = ∫ x in a..c, f x ∂μ := by rw [← add_neg_eq_zero, ← integral_symm, integral_add_adjacent_intervals_cancel hab hbc] lemma integral_interval_sub_left (hab : interval_integrable f μ a b) (hac : interval_integrable f μ a c) : ∫ x in a..b, f x ∂μ - ∫ x in a..c, f x ∂μ = ∫ x in c..b, f x ∂μ := sub_eq_of_eq_add' $ eq.symm $ integral_add_adjacent_intervals hac (hac.symm.trans hab) lemma integral_interval_add_interval_comm (hab : interval_integrable f μ a b) (hcd : interval_integrable f μ c d) (hac : interval_integrable f μ a c) : ∫ x in a..b, f x ∂μ + ∫ x in c..d, f x ∂μ = ∫ x in a..d, f x ∂μ + ∫ x in c..b, f x ∂μ := by rw [← integral_add_adjacent_intervals hac hcd, add_assoc, add_left_comm, integral_add_adjacent_intervals hac (hac.symm.trans hab), add_comm] lemma integral_interval_sub_interval_comm (hab : interval_integrable f μ a b) (hcd : interval_integrable f μ c d) (hac : interval_integrable f μ a c) : ∫ x in a..b, f x ∂μ - ∫ x in c..d, f x ∂μ = ∫ x in a..c, f x ∂μ - ∫ x in b..d, f x ∂μ := by simp only [sub_eq_add_neg, ← integral_symm, integral_interval_add_interval_comm hab hcd.symm (hac.trans hcd)] lemma integral_interval_sub_interval_comm' (hab : interval_integrable f μ a b) (hcd : interval_integrable f μ c d) (hac : interval_integrable f μ a c) : ∫ x in a..b, f x ∂μ - ∫ x in c..d, f x ∂μ = ∫ x in d..b, f x ∂μ - ∫ x in c..a, f x ∂μ := by { rw [integral_interval_sub_interval_comm hab hcd hac, integral_symm b d, integral_symm a c, sub_neg_eq_add, sub_eq_neg_add], } lemma integral_Iic_sub_Iic (ha : integrable_on f (Iic a) μ) (hb : integrable_on f (Iic b) μ) : ∫ x in Iic b, f x ∂μ - ∫ x in Iic a, f x ∂μ = ∫ x in a..b, f x ∂μ := begin wlog hab : a ≤ b using [a b] tactic.skip, { rw [sub_eq_iff_eq_add', integral_of_le hab, ← integral_union (Iic_disjoint_Ioc (le_refl _)), Iic_union_Ioc_eq_Iic hab], exacts [is_measurable_Iic, is_measurable_Ioc, ha, hb.mono_set (λ _, and.right)] }, { intros ha hb, rw [integral_symm, ← this hb ha, neg_sub] } end /-- If `μ` is a finite measure then `∫ x in a..b, c ∂μ = (μ (Iic b) - μ (Iic a)) • c`. -/ lemma integral_const_of_cdf [finite_measure μ] (c : E) : ∫ x in a..b, c ∂μ = ((μ (Iic b)).to_real - (μ (Iic a)).to_real) • c := begin simp only [sub_smul, ← set_integral_const], refine (integral_Iic_sub_Iic _ _).symm; simp only [integrable_on_const, measure_lt_top, or_true] end lemma integral_eq_integral_of_support_subset {f : α → E} {a b} (h : function.support f ⊆ Ioc a b) : ∫ x in a..b, f x ∂μ = ∫ x, f x ∂μ := begin cases le_total a b with hab hab, { rw [integral_of_le hab, ← integral_indicator is_measurable_Ioc, indicator_eq_self.2 h]; apply_instance }, { rw [Ioc_eq_empty hab, subset_empty_iff, function.support_eq_empty_iff] at h, simp [h] } end end order_closed_topology end lemma integral_eq_zero_iff_of_le_of_nonneg_ae {f : ℝ → ℝ} {a b : ℝ} (hab : a ≤ b) (hf : 0 ≤ᵐ[volume.restrict (Ioc a b)] f) (hfi : interval_integrable f volume a b) : ∫ x in a..b, f x = 0 ↔ f =ᵐ[volume.restrict (Ioc a b)] 0 := by rw [integral_of_le hab, integral_eq_zero_iff_of_nonneg_ae hf hfi.1] lemma integral_eq_zero_iff_of_nonneg_ae {f : ℝ → ℝ} {a b : ℝ} (hf : 0 ≤ᵐ[volume.restrict (Ioc a b ∪ Ioc b a)] f) (hfi : interval_integrable f volume a b) : ∫ x in a..b, f x = 0 ↔ f =ᵐ[volume.restrict (Ioc a b ∪ Ioc b a)] 0 := begin cases le_total a b with hab hab; simp only [Ioc_eq_empty hab, empty_union, union_empty] at *, { exact integral_eq_zero_iff_of_le_of_nonneg_ae hab hf hfi }, { rw [integral_symm, neg_eq_zero], exact integral_eq_zero_iff_of_le_of_nonneg_ae hab hf hfi.symm } end lemma integral_pos_iff_support_of_nonneg_ae' {f : ℝ → ℝ} {a b : ℝ} (hf : 0 ≤ᵐ[volume.restrict (Ioc a b ∪ Ioc b a)] f) (hfi : interval_integrable f volume a b) : 0 < ∫ x in a..b, f x ↔ a < b ∧ 0 < volume (function.support f ∩ Ioc a b) := begin cases le_total a b with hab hab, { simp only [integral_of_le hab, Ioc_eq_empty hab, union_empty] at hf ⊢, symmetry, rw [set_integral_pos_iff_support_of_nonneg_ae hf hfi.1, and_iff_right_iff_imp], contrapose!, intro h, simp [Ioc_eq_empty h] }, { rw [Ioc_eq_empty hab, empty_union] at hf, simp [integral_of_ge hab, Ioc_eq_empty hab, integral_nonneg_of_ae hf] } end lemma integral_pos_iff_support_of_nonneg_ae {f : ℝ → ℝ} {a b : ℝ} (hf : 0 ≤ᵐ[volume] f) (hfi : interval_integrable f volume a b) : 0 < ∫ x in a..b, f x ↔ a < b ∧ 0 < volume (function.support f ∩ Ioc a b) := integral_pos_iff_support_of_nonneg_ae' (ae_mono measure.restrict_le_self hf) hfi /-! ### Fundamental theorem of calculus, part 1, for any measure In this section we prove a few lemmas that can be seen as versions of FTC-1 for interval integrals w.r.t. any measure. Many theorems are formulated for one or two pairs of filters related by `FTC_filter a l l'`. This typeclass has exactly four “real” instances: `(a, pure a, ⊥)`, `(a, 𝓝[Ici a] a, 𝓝[Ioi a] a)`, `(a, 𝓝[Iic a] a, 𝓝[Iic a] a)`, `(a, 𝓝 a, 𝓝 a)`, and two instances that are equal to the first and last “real” instances: `(a, 𝓝[{a}] a, ⊥)` and `(a, 𝓝[univ] a, 𝓝[univ] a)`. We use this approach to avoid repeating arguments in many very similar cases. Lean can automatically find both `a` and `l'` based on `l`. The most general theorem `measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae` can be seen as a generalization of lemma `integral_has_strict_fderiv_at` below which states strict differentiability of `∫ x in u..v, f x` in `(u, v)` at `(a, b)` for a measurable function `f` that is integrable on `a..b` and is continuous at `a` and `b`. The lemma is generalized in three directions: first, `measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae` deals with any locally finite measure `μ`; second, it works for one-sided limits/derivatives; third, it assumes only that `f` has finite limits almost surely at `a` and `b`. Namely, let `f` be a measurable function integrable on `a..b`. Let `(la, la')` be a pair of `FTC_filter`s around `a`; let `(lb, lb')` be a pair of `FTC_filter`s around `b`. Suppose that `f` has finite limits `ca` and `cb` at `la' ⊓ μ.ae` and `lb' ⊓ μ.ae`, respectively. Then `∫ x in va..vb, f x ∂μ - ∫ x in ua..ub, f x ∂μ = ∫ x in ub..vb, cb ∂μ - ∫ x in ua..va, ca ∂μ + o(∥∫ x in ua..va, (1:ℝ) ∂μ∥ + ∥∫ x in ub..vb, (1:ℝ) ∂μ∥)` as `ua` and `va` tend to `la` while `ub` and `vb` tend to `lb`. This theorem is formulated with integral of constants instead of measures in the right hand sides for two reasons: first, this way we avoid `min`/`max` in the statements; second, often it is possible to write better `simp` lemmas for these integrals, see `integral_const` and `integral_const_of_cdf`. In the next subsection we apply this theorem to prove various theorems about differentiability of the integral w.r.t. Lebesgue measure. -/ /-- An auxiliary typeclass for the Fundamental theorem of calculus, part 1. It is used to formulate theorems that work simultaneously for left and right one-sided derivatives of `∫ x in u..v, f x`. There are four instances: `(a, pure a, ⊥)`, `(a, 𝓝[Ici a], 𝓝[Ioi a])`, `(a, 𝓝[Iic a], 𝓝[Iic a])`, and `(a, 𝓝 a, 𝓝 a)`. -/ class FTC_filter {β : Type*} [linear_order β] [measurable_space β] [topological_space β] (a : out_param β) (outer : filter β) (inner : out_param $ filter β) extends tendsto_Ixx_class Ioc outer inner : Prop := (pure_le : pure a ≤ outer) (le_nhds : inner ≤ 𝓝 a) [meas_gen : is_measurably_generated inner] /- The `dangerous_instance` linter doesn't take `out_param`s into account, so it thinks that `FTC_filter.to_tendsto_Ixx_class` is dangerous. Disable this linter using `nolint`. -/ attribute [nolint dangerous_instance] FTC_filter.to_tendsto_Ixx_class namespace FTC_filter variables [linear_order β] [measurable_space β] [topological_space β] instance pure (a : β) : FTC_filter a (pure a) ⊥ := { pure_le := le_refl _, le_nhds := bot_le } instance nhds_within_singleton (a : β) : FTC_filter a (𝓝[{a}] a) ⊥ := by { rw [nhds_within, principal_singleton, inf_eq_right.2 (pure_le_nhds a)], apply_instance } lemma finite_at_inner {a : β} (l : filter β) {l'} [h : FTC_filter a l l'] {μ : measure β} [locally_finite_measure μ] : μ.finite_at_filter l' := (μ.finite_at_nhds a).filter_mono h.le_nhds variables [opens_measurable_space β] [order_topology β] instance nhds (a : β) : FTC_filter a (𝓝 a) (𝓝 a) := { pure_le := pure_le_nhds a, le_nhds := le_refl _ } instance nhds_univ (a : β) : FTC_filter a (𝓝[univ] a) (𝓝 a) := by { rw nhds_within_univ, apply_instance } instance nhds_left (a : β) : FTC_filter a (𝓝[Iic a] a) (𝓝[Iic a] a) := { pure_le := pure_le_nhds_within right_mem_Iic, le_nhds := inf_le_left } instance nhds_right (a : β) : FTC_filter a (𝓝[Ici a] a) (𝓝[Ioi a] a) := { pure_le := pure_le_nhds_within left_mem_Ici, le_nhds := inf_le_left } end FTC_filter open asymptotics section variables {f : α → E} {a b : α} {c ca cb : E} {l l' la la' lb lb' : filter α} {lt : filter β} {μ : measure α} {u v ua va ub vb : β → α} /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `tendsto_Ixx_class Ioc`. If `f` has a finite limit `c` at `l' ⊓ μ.ae`, where `μ` is a measure finite at `l'`, then `∫ x in u..v, f x ∂μ = ∫ x in u..v, c ∂μ + o(∫ x in u..v, 1 ∂μ)` as both `u` and `v` tend to `l`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae` for a version assuming `[FTC_filter a l l']` and `[locally_finite_measure μ]`. If `l` is one of `𝓝[Ici a] a`, `𝓝[Iic a] a`, `𝓝 a`, then it's easier to apply the non-primed version. The primed version also works, e.g., for `l = l' = at_top`. We use integrals of constants instead of measures because this way it is easier to formulate a statement that works in both cases `u ≤ v` and `v ≤ u`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae' [is_measurably_generated l'] [tendsto_Ixx_class Ioc l l'] (hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hl : μ.finite_at_filter l') (hu : tendsto u lt l) (hv : tendsto v lt l) : is_o (λ t, ∫ x in u t..v t, f x ∂μ - ∫ x in u t..v t, c ∂μ) (λ t, ∫ x in u t..v t, (1:ℝ) ∂μ) lt := begin have A := hf.integral_sub_linear_is_o_ae hfm hl (hu.Ioc hv), have B := hf.integral_sub_linear_is_o_ae hfm hl (hv.Ioc hu), simp only [integral_const'], convert (A.trans_le _).sub (B.trans_le _), { ext t, simp_rw [(∘), interval_integral, sub_smul], abel }, all_goals { intro t, cases le_total (u t) (v t) with huv huv; simp [huv] } end /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `tendsto_Ixx_class Ioc`. If `f` has a finite limit `c` at `l ⊓ μ.ae`, where `μ` is a measure finite at `l`, then `∫ x in u..v, f x ∂μ = μ (Ioc u v) • c + o(μ(Ioc u v))` as both `u` and `v` tend to `l` so that `u ≤ v`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae_of_le` for a version assuming `[FTC_filter a l l']` and `[locally_finite_measure μ]`. If `l` is one of `𝓝[Ici a] a`, `𝓝[Iic a] a`, `𝓝 a`, then it's easier to apply the non-primed version. The primed version also works, e.g., for `l = l' = at_top`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae_of_le' [is_measurably_generated l'] [tendsto_Ixx_class Ioc l l'] (hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hl : μ.finite_at_filter l') (hu : tendsto u lt l) (hv : tendsto v lt l) (huv : u ≤ᶠ[lt] v) : is_o (λ t, ∫ x in u t..v t, f x ∂μ - (μ (Ioc (u t) (v t))).to_real • c) (λ t, (μ $ Ioc (u t) (v t)).to_real) lt := (measure_integral_sub_linear_is_o_of_tendsto_ae' hfm hf hl hu hv).congr' (huv.mono $ λ x hx, by simp [integral_const', hx]) (huv.mono $ λ x hx, by simp [integral_const', hx]) /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `tendsto_Ixx_class Ioc`. If `f` has a finite limit `c` at `l ⊓ μ.ae`, where `μ` is a measure finite at `l`, then `∫ x in u..v, f x ∂μ = -μ (Ioc v u) • c + o(μ(Ioc v u))` as both `u` and `v` tend to `l` so that `v ≤ u`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge` for a version assuming `[FTC_filter a l l']` and `[locally_finite_measure μ]`. If `l` is one of `𝓝[Ici a] a`, `𝓝[Iic a] a`, `𝓝 a`, then it's easier to apply the non-primed version. The primed version also works, e.g., for `l = l' = at_top`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge' [is_measurably_generated l'] [tendsto_Ixx_class Ioc l l'] (hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hl : μ.finite_at_filter l') (hu : tendsto u lt l) (hv : tendsto v lt l) (huv : v ≤ᶠ[lt] u) : is_o (λ t, ∫ x in u t..v t, f x ∂μ + (μ (Ioc (v t) (u t))).to_real • c) (λ t, (μ $ Ioc (v t) (u t)).to_real) lt := (measure_integral_sub_linear_is_o_of_tendsto_ae_of_le' hfm hf hl hv hu huv).neg_left.congr_left $ λ t, by simp [integral_symm (u t), add_comm] variables [topological_space α] section variables [locally_finite_measure μ] [FTC_filter a l l'] include a local attribute [instance] FTC_filter.meas_gen /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `[FTC_filter a l l']`; let `μ` be a locally finite measure. If `f` has a finite limit `c` at `l' ⊓ μ.ae`, then `∫ x in u..v, f x ∂μ = ∫ x in u..v, c ∂μ + o(∫ x in u..v, 1 ∂μ)` as both `u` and `v` tend to `l`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae'` for a version that also works, e.g., for `l = l' = at_top`. We use integrals of constants instead of measures because this way it is easier to formulate a statement that works in both cases `u ≤ v` and `v ≤ u`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae (hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt l) (hv : tendsto v lt l) : is_o (λ t, ∫ x in u t..v t, f x ∂μ - ∫ x in u t..v t, c ∂μ) (λ t, ∫ x in u t..v t, (1:ℝ) ∂μ) lt := measure_integral_sub_linear_is_o_of_tendsto_ae' hfm hf (FTC_filter.finite_at_inner l) hu hv /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `[FTC_filter a l l']`; let `μ` be a locally finite measure. If `f` has a finite limit `c` at `l' ⊓ μ.ae`, then `∫ x in u..v, f x ∂μ = μ (Ioc u v) • c + o(μ(Ioc u v))` as both `u` and `v` tend to `l`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae_of_le'` for a version that also works, e.g., for `l = l' = at_top`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae_of_le (hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt l) (hv : tendsto v lt l) (huv : u ≤ᶠ[lt] v) : is_o (λ t, ∫ x in u t..v t, f x ∂μ - (μ (Ioc (u t) (v t))).to_real • c) (λ t, (μ $ Ioc (u t) (v t)).to_real) lt := measure_integral_sub_linear_is_o_of_tendsto_ae_of_le' hfm hf (FTC_filter.finite_at_inner l) hu hv huv /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `[FTC_filter a l l']`; let `μ` be a locally finite measure. If `f` has a finite limit `c` at `l' ⊓ μ.ae`, then `∫ x in u..v, f x ∂μ = -μ (Ioc v u) • c + o(μ(Ioc v u))` as both `u` and `v` tend to `l`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge'` for a version that also works, e.g., for `l = l' = at_top`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge (hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt l) (hv : tendsto v lt l) (huv : v ≤ᶠ[lt] u) : is_o (λ t, ∫ x in u t..v t, f x ∂μ + (μ (Ioc (v t) (u t))).to_real • c) (λ t, (μ $ Ioc (v t) (u t)).to_real) lt := measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge' hfm hf (FTC_filter.finite_at_inner l) hu hv huv end variables [order_topology α] [borel_space α] local attribute [instance] FTC_filter.meas_gen variables [FTC_filter a la la'] [FTC_filter b lb lb'] [locally_finite_measure μ] /-- Fundamental theorem of calculus-1, strict derivative in both limits for a locally finite measure. Let `f` be a measurable function integrable on `a..b`. Let `(la, la')` be a pair of `FTC_filter`s around `a`; let `(lb, lb')` be a pair of `FTC_filter`s around `b`. Suppose that `f` has finite limits `ca` and `cb` at `la' ⊓ μ.ae` and `lb' ⊓ μ.ae`, respectively. Then `∫ x in va..vb, f x ∂μ - ∫ x in ua..ub, f x ∂μ = ∫ x in ub..vb, cb ∂μ - ∫ x in ua..va, ca ∂μ + o(∥∫ x in ua..va, (1:ℝ) ∂μ∥ + ∥∫ x in ub..vb, (1:ℝ) ∂μ∥)` as `ua` and `va` tend to `la` while `ub` and `vb` tend to `lb`. -/ lemma measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae (hab : interval_integrable f μ a b) (hmeas_a : measurable_at_filter f la' μ) (hmeas_b : measurable_at_filter f lb' μ) (ha_lim : tendsto f (la' ⊓ μ.ae) (𝓝 ca)) (hb_lim : tendsto f (lb' ⊓ μ.ae) (𝓝 cb)) (hua : tendsto ua lt la) (hva : tendsto va lt la) (hub : tendsto ub lt lb) (hvb : tendsto vb lt lb) : is_o (λ t, (∫ x in va t..vb t, f x ∂μ) - (∫ x in ua t..ub t, f x ∂μ) - (∫ x in ub t..vb t, cb ∂μ - ∫ x in ua t..va t, ca ∂μ)) (λ t, ∥∫ x in ua t..va t, (1:ℝ) ∂μ∥ + ∥∫ x in ub t..vb t, (1:ℝ) ∂μ∥) lt := begin refine ((measure_integral_sub_linear_is_o_of_tendsto_ae hmeas_a ha_lim hua hva).neg_left.add_add (measure_integral_sub_linear_is_o_of_tendsto_ae hmeas_b hb_lim hub hvb)).congr' _ eventually_eq.rfl, have A : ∀ᶠ t in lt, interval_integrable f μ (ua t) (va t) := ha_lim.eventually_interval_integrable_ae hmeas_a (FTC_filter.finite_at_inner la) hua hva, have A' : ∀ᶠ t in lt, interval_integrable f μ a (ua t) := ha_lim.eventually_interval_integrable_ae hmeas_a (FTC_filter.finite_at_inner la) (tendsto_const_pure.mono_right FTC_filter.pure_le) hua, have B : ∀ᶠ t in lt, interval_integrable f μ (ub t) (vb t) := hb_lim.eventually_interval_integrable_ae hmeas_b (FTC_filter.finite_at_inner lb) hub hvb, have B' : ∀ᶠ t in lt, interval_integrable f μ b (ub t) := hb_lim.eventually_interval_integrable_ae hmeas_b (FTC_filter.finite_at_inner lb) (tendsto_const_pure.mono_right FTC_filter.pure_le) hub, filter_upwards [A, A', B, B'], intros t ua_va a_ua ub_vb b_ub, rw [← integral_interval_sub_interval_comm'], { dsimp only [], abel }, exacts [ub_vb, ua_va, b_ub.symm.trans $ hab.symm.trans a_ua] end /-- Fundamental theorem of calculus-1, strict derivative in right endpoint for a locally finite measure. Let `f` be a measurable function integrable on `a..b`. Let `(lb, lb')` be a pair of `FTC_filter`s around `b`. Suppose that `f` has a finite limit `c` at `lb' ⊓ μ.ae`. Then `∫ x in a..v, f x ∂μ - ∫ x in a..u, f x ∂μ = ∫ x in u..v, c ∂μ + o(∫ x in u..v, (1:ℝ) ∂μ)` as `u` and `v` tend to `lb`. -/ lemma measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right (hab : interval_integrable f μ a b) (hmeas : measurable_at_filter f lb' μ) (hf : tendsto f (lb' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt lb) (hv : tendsto v lt lb) : is_o (λ t, ∫ x in a..v t, f x ∂μ - ∫ x in a..u t, f x ∂μ - ∫ x in u t..v t, c ∂μ) (λ t, ∫ x in u t..v t, (1:ℝ) ∂μ) lt := by simpa using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae hab measurable_at_bot hmeas ((tendsto_bot : tendsto _ ⊥ (𝓝 0)).mono_left inf_le_left) hf (tendsto_const_pure : tendsto _ _ (pure a)) tendsto_const_pure hu hv /-- Fundamental theorem of calculus-1, strict derivative in left endpoint for a locally finite measure. Let `f` be a measurable function integrable on `a..b`. Let `(la, la')` be a pair of `FTC_filter`s around `a`. Suppose that `f` has a finite limit `c` at `la' ⊓ μ.ae`. Then `∫ x in v..b, f x ∂μ - ∫ x in u..b, f x ∂μ = -∫ x in u..v, c ∂μ + o(∫ x in u..v, (1:ℝ) ∂μ)` as `u` and `v` tend to `la`. -/ lemma measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae_left (hab : interval_integrable f μ a b) (hmeas : measurable_at_filter f la' μ) (hf : tendsto f (la' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt la) (hv : tendsto v lt la) : is_o (λ t, ∫ x in v t..b, f x ∂μ - ∫ x in u t..b, f x ∂μ + ∫ x in u t..v t, c ∂μ) (λ t, ∫ x in u t..v t, (1:ℝ) ∂μ) lt := by simpa using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae hab hmeas measurable_at_bot hf ((tendsto_bot : tendsto _ ⊥ (𝓝 0)).mono_left inf_le_left) hu hv (tendsto_const_pure : tendsto _ _ (pure b)) tendsto_const_pure end /-! ### Fundamental theorem of calculus-1 for Lebesgue measure In this section we restate theorems from the previous section for Lebesgue measure. In particular, we prove that `∫ x in u..v, f x` is strictly differentiable in `(u, v)` at `(a, b)` provided that `f` is integrable on `a..b` and is continuous at `a` and `b`. -/ variables {f : ℝ → E} {c ca cb : E} {l l' la la' lb lb' : filter ℝ} {lt : filter β} {a b z : ℝ} {u v ua ub va vb : β → ℝ} [FTC_filter a la la'] [FTC_filter b lb lb'] /-! #### Auxiliary `is_o` statements In this section we prove several lemmas that can be interpreted as strict differentiability of `(u, v) ↦ ∫ x in u..v, f x ∂μ` in `u` and/or `v` at a filter. The statements use `is_o` because we have no definition of `has_strict_(f)deriv_at_filter` in the library. -/ /-- Fundamental theorem of calculus-1, local version. If `f` has a finite limit `c` almost surely at `l'`, where `(l, l')` is an `FTC_filter` pair around `a`, then `∫ x in u..v, f x ∂μ = (v - u) • c + o (v - u)` as both `u` and `v` tend to `l`. -/ lemma integral_sub_linear_is_o_of_tendsto_ae [FTC_filter a l l'] (hfm : measurable_at_filter f l') (hf : tendsto f (l' ⊓ volume.ae) (𝓝 c)) {u v : β → ℝ} (hu : tendsto u lt l) (hv : tendsto v lt l) : is_o (λ t, (∫ x in u t..v t, f x) - (v t - u t) • c) (v - u) lt := by simpa [integral_const] using measure_integral_sub_linear_is_o_of_tendsto_ae hfm hf hu hv /-- Fundamental theorem of calculus-1, strict differentiability at filter in both endpoints. If `f` is a measurable function integrable on `a..b`, `(la, la')` is an `FTC_filter` pair around `a`, and `(lb, lb')` is an `FTC_filter` pair around `b`, and `f` has finite limits `ca` and `cb` almost surely at `la'` and `lb'`, respectively, then `(∫ x in va..vb, f x) - ∫ x in ua..ub, f x = (vb - ub) • cb - (va - ua) • ca + o(∥va - ua∥ + ∥vb - ub∥)` as `ua` and `va` tend to `la` while `ub` and `vb` tend to `lb`. This lemma could've been formulated using `has_strict_fderiv_at_filter` if we had this definition. -/ lemma integral_sub_integral_sub_linear_is_o_of_tendsto_ae (hab : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f la') (hmeas_b : measurable_at_filter f lb') (ha_lim : tendsto f (la' ⊓ volume.ae) (𝓝 ca)) (hb_lim : tendsto f (lb' ⊓ volume.ae) (𝓝 cb)) (hua : tendsto ua lt la) (hva : tendsto va lt la) (hub : tendsto ub lt lb) (hvb : tendsto vb lt lb) : is_o (λ t, (∫ x in va t..vb t, f x) - (∫ x in ua t..ub t, f x) - ((vb t - ub t) • cb - (va t - ua t) • ca)) (λ t, ∥va t - ua t∥ + ∥vb t - ub t∥) lt := by simpa [integral_const] using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae hab hmeas_a hmeas_b ha_lim hb_lim hua hva hub hvb /-- Fundamental theorem of calculus-1, strict differentiability at filter in both endpoints. If `f` is a measurable function integrable on `a..b`, `(lb, lb')` is an `FTC_filter` pair around `b`, and `f` has a finite limit `c` almost surely at `lb'`, then `(∫ x in a..v, f x) - ∫ x in a..u, f x = (v - u) • c + o(∥v - u∥)` as `u` and `v` tend to `lb`. This lemma could've been formulated using `has_strict_deriv_at_filter` if we had this definition. -/ lemma integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right (hab : interval_integrable f volume a b) (hmeas : measurable_at_filter f lb') (hf : tendsto f (lb' ⊓ volume.ae) (𝓝 c)) (hu : tendsto u lt lb) (hv : tendsto v lt lb) : is_o (λ t, (∫ x in a..v t, f x) - (∫ x in a..u t, f x) - (v t - u t) • c) (v - u) lt := by simpa only [integral_const, smul_eq_mul, mul_one] using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right hab hmeas hf hu hv /-- Fundamental theorem of calculus-1, strict differentiability at filter in both endpoints. If `f` is a measurable function integrable on `a..b`, `(la, la')` is an `FTC_filter` pair around `a`, and `f` has a finite limit `c` almost surely at `la'`, then `(∫ x in v..b, f x) - ∫ x in u..b, f x = -(v - u) • c + o(∥v - u∥)` as `u` and `v` tend to `la`. This lemma could've been formulated using `has_strict_deriv_at_filter` if we had this definition. -/ lemma integral_sub_integral_sub_linear_is_o_of_tendsto_ae_left (hab : interval_integrable f volume a b) (hmeas : measurable_at_filter f la') (hf : tendsto f (la' ⊓ volume.ae) (𝓝 c)) (hu : tendsto u lt la) (hv : tendsto v lt la) : is_o (λ t, (∫ x in v t..b, f x) - (∫ x in u t..b, f x) + (v t - u t) • c) (v - u) lt := by simpa only [integral_const, smul_eq_mul, mul_one] using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae_left hab hmeas hf hu hv open continuous_linear_map (fst snd smul_right sub_apply smul_right_apply coe_fst' coe_snd' map_sub) /-! #### Strict differentiability In this section we prove that for a measurable function `f` integrable on `a..b`, * `integral_has_strict_fderiv_at_of_tendsto_ae`: the function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)` in the sense of strict differentiability provided that `f` tends to `ca` and `cb` almost surely as `x` tendsto to `a` and `b`, respectively; * `integral_has_strict_fderiv_at`: the function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • f b - u • f a` at `(a, b)` in the sense of strict differentiability provided that `f` is continuous at `a` and `b`; * `integral_has_strict_deriv_at_of_tendsto_ae_right`: the function `u ↦ ∫ x in a..u, f x` has derivative `c` at `b` in the sense of strict differentiability provided that `f` tends to `c` almost surely as `x` tends to `b`; * `integral_has_strict_deriv_at_right`: the function `u ↦ ∫ x in a..u, f x` has derivative `f b` at `b` in the sense of strict differentiability provided that `f` is continuous at `b`; * `integral_has_strict_deriv_at_of_tendsto_ae_left`: the function `u ↦ ∫ x in u..b, f x` has derivative `-c` at `a` in the sense of strict differentiability provided that `f` tends to `c` almost surely as `x` tends to `a`; * `integral_has_strict_deriv_at_left`: the function `u ↦ ∫ x in u..b, f x` has derivative `-f a` at `a` in the sense of strict differentiability provided that `f` is continuous at `a`. -/ /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has finite limits `ca` and `cb` almost surely as `x` tends to `a` and `b`, respectively, then `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)` in the sense of strict differentiability. -/ lemma integral_has_strict_fderiv_at_of_tendsto_ae (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b)) (ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 cb)) : has_strict_fderiv_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca) (a, b) := begin have := integral_sub_integral_sub_linear_is_o_of_tendsto_ae hf hmeas_a hmeas_b ha hb ((continuous_fst.comp continuous_snd).tendsto ((a, b), (a, b))) ((continuous_fst.comp continuous_fst).tendsto ((a, b), (a, b))) ((continuous_snd.comp continuous_snd).tendsto ((a, b), (a, b))) ((continuous_snd.comp continuous_fst).tendsto ((a, b), (a, b))), refine (this.congr_left _).trans_is_O _, { intro x, simp [sub_smul] }, { exact is_O_fst_prod.norm_left.add is_O_snd_prod.norm_left } end /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a` and `b`, then `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)` in the sense of strict differentiability. -/ lemma integral_has_strict_fderiv_at (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b)) (ha : continuous_at f a) (hb : continuous_at f b) : has_strict_fderiv_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right (f b) - (fst ℝ ℝ ℝ).smul_right (f a)) (a, b) := integral_has_strict_fderiv_at_of_tendsto_ae hf hmeas_a hmeas_b (ha.mono_left inf_le_left) (hb.mono_left inf_le_left) /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely at `b`, then `u ↦ ∫ x in a..u, f x` has derivative `c` at `b` in the sense of strict differentiability. -/ lemma integral_has_strict_deriv_at_of_tendsto_ae_right (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 c)) : has_strict_deriv_at (λ u, ∫ x in a..u, f x) c b := integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right hf hmeas hb continuous_at_snd continuous_at_fst /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `b`, then `u ↦ ∫ x in a..u, f x` has derivative `f b` at `b` in the sense of strict differentiability. -/ lemma integral_has_strict_deriv_at_right (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b)) (hb : continuous_at f b) : has_strict_deriv_at (λ u, ∫ x in a..u, f x) (f b) b := integral_has_strict_deriv_at_of_tendsto_ae_right hf hmeas (hb.mono_left inf_le_left) /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely at `a`, then `u ↦ ∫ x in u..b, f x` has derivative `-c` at `a` in the sense of strict differentiability. -/ lemma integral_has_strict_deriv_at_of_tendsto_ae_left (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a)) (ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 c)) : has_strict_deriv_at (λ u, ∫ x in u..b, f x) (-c) a := by simpa only [← integral_symm] using (integral_has_strict_deriv_at_of_tendsto_ae_right hf.symm hmeas ha).neg /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a`, then `u ↦ ∫ x in u..b, f x` has derivative `-f a` at `a` in the sense of strict differentiability. -/ lemma integral_has_strict_deriv_at_left (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a)) (ha : continuous_at f a) : has_strict_deriv_at (λ u, ∫ x in u..b, f x) (-f a) a := by simpa only [← integral_symm] using (integral_has_strict_deriv_at_right hf.symm hmeas ha).neg /-! #### Fréchet differentiability In this subsection we restate results from the previous subsection in terms of `has_fderiv_at`, `has_deriv_at`, `fderiv`, and `deriv`. -/ /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has finite limits `ca` and `cb` almost surely as `x` tends to `a` and `b`, respectively, then `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)`. -/ lemma integral_has_fderiv_at_of_tendsto_ae (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b)) (ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 cb)) : has_fderiv_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca) (a, b) := (integral_has_strict_fderiv_at_of_tendsto_ae hf hmeas_a hmeas_b ha hb).has_fderiv_at /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a` and `b`, then `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)`. -/ lemma integral_has_fderiv_at (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b)) (ha : continuous_at f a) (hb : continuous_at f b) : has_fderiv_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right (f b) - (fst ℝ ℝ ℝ).smul_right (f a)) (a, b) := (integral_has_strict_fderiv_at hf hmeas_a hmeas_b ha hb).has_fderiv_at /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has finite limits `ca` and `cb` almost surely as `x` tends to `a` and `b`, respectively, then `fderiv` derivative of `(u, v) ↦ ∫ x in u..v, f x` at `(a, b)` equals `(u, v) ↦ v • cb - u • ca`. -/ lemma fderiv_integral_of_tendsto_ae (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b)) (ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 cb)) : fderiv ℝ (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) (a, b) = (snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca := (integral_has_fderiv_at_of_tendsto_ae hf hmeas_a hmeas_b ha hb).fderiv /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a` and `b`, then `fderiv` derivative of `(u, v) ↦ ∫ x in u..v, f x` at `(a, b)` equals `(u, v) ↦ v • cb - u • ca`. -/ lemma fderiv_integral (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b)) (ha : continuous_at f a) (hb : continuous_at f b) : fderiv ℝ (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) (a, b) = (snd ℝ ℝ ℝ).smul_right (f b) - (fst ℝ ℝ ℝ).smul_right (f a) := (integral_has_fderiv_at hf hmeas_a hmeas_b ha hb).fderiv /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely at `b`, then `u ↦ ∫ x in a..u, f x` has derivative `c` at `b`. -/ lemma integral_has_deriv_at_of_tendsto_ae_right (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 c)) : has_deriv_at (λ u, ∫ x in a..u, f x) c b := (integral_has_strict_deriv_at_of_tendsto_ae_right hf hmeas hb).has_deriv_at /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `b`, then `u ↦ ∫ x in a..u, f x` has derivative `f b` at `b`. -/ lemma integral_has_deriv_at_right (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b)) (hb : continuous_at f b) : has_deriv_at (λ u, ∫ x in a..u, f x) (f b) b := (integral_has_strict_deriv_at_right hf hmeas hb).has_deriv_at /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f` has a finite limit `c` almost surely at `b`, then the derivative of `u ↦ ∫ x in a..u, f x` at `b` equals `c`. -/ lemma deriv_integral_of_tendsto_ae_right (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 c)) : deriv (λ u, ∫ x in a..u, f x) b = c := (integral_has_deriv_at_of_tendsto_ae_right hf hmeas hb).deriv /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `b`, then the derivative of `u ↦ ∫ x in a..u, f x` at `b` equals `f b`. -/ lemma deriv_integral_right (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b)) (hb : continuous_at f b) : deriv (λ u, ∫ x in a..u, f x) b = f b := (integral_has_deriv_at_right hf hmeas hb).deriv /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely at `a`, then `u ↦ ∫ x in u..b, f x` has derivative `-c` at `a`. -/ lemma integral_has_deriv_at_of_tendsto_ae_left (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a)) (ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 c)) : has_deriv_at (λ u, ∫ x in u..b, f x) (-c) a := (integral_has_strict_deriv_at_of_tendsto_ae_left hf hmeas ha).has_deriv_at /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a`, then `u ↦ ∫ x in u..b, f x` has derivative `-f a` at `a`. -/ lemma integral_has_deriv_at_left (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a)) (ha : continuous_at f a) : has_deriv_at (λ u, ∫ x in u..b, f x) (-f a) a := (integral_has_strict_deriv_at_left hf hmeas ha).has_deriv_at /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f` has a finite limit `c` almost surely at `a`, then the derivative of `u ↦ ∫ x in u..b, f x` at `a` equals `-c`. -/ lemma deriv_integral_of_tendsto_ae_left (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a)) (hb : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 c)) : deriv (λ u, ∫ x in u..b, f x) a = -c := (integral_has_deriv_at_of_tendsto_ae_left hf hmeas hb).deriv /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a`, then the derivative of `u ↦ ∫ x in u..b, f x` at `a` equals `-f a`. -/ lemma deriv_integral_left (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a)) (hb : continuous_at f a) : deriv (λ u, ∫ x in u..b, f x) a = -f a := (integral_has_deriv_at_left hf hmeas hb).deriv /-! #### One-sided derivatives -/ /-- Let `f` be a measurable function integrable on `a..b`. The function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` within `s × t` at `(a, b)`, where `s ∈ {Iic a, {a}, Ici a, univ}` and `t ∈ {Iic b, {b}, Ici b, univ}` provided that `f` tends to `ca` and `cb` almost surely at the filters `la` and `lb` from the following table. | `s` | `la` | `t` | `lb` | | ------- | ---- | --- | ---- | | `Iic a` | `𝓝[Iic a] a` | `Iic b` | `𝓝[Iic b] b` | | `Ici a` | `𝓝[Ioi a] a` | `Ici b` | `𝓝[Ioi b] b` | | `{a}` | `⊥` | `{b}` | `⊥` | | `univ` | `𝓝 a` | `univ` | `𝓝 b` | -/ lemma integral_has_fderiv_within_at_of_tendsto_ae (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) la] [FTC_filter b (𝓝[t] b) lb] (hmeas_a : measurable_at_filter f la) (hmeas_b : measurable_at_filter f lb) (ha : tendsto f (la ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (lb ⊓ volume.ae) (𝓝 cb)) : has_fderiv_within_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca) (s.prod t) (a, b) := begin rw [has_fderiv_within_at, nhds_within_prod_eq], have := integral_sub_integral_sub_linear_is_o_of_tendsto_ae hf hmeas_a hmeas_b ha hb (tendsto_const_pure.mono_right FTC_filter.pure_le : tendsto _ _ (𝓝[s] a)) tendsto_fst (tendsto_const_pure.mono_right FTC_filter.pure_le : tendsto _ _ (𝓝[t] b)) tendsto_snd, refine (this.congr_left _).trans_is_O _, { intro x, simp [sub_smul] }, { exact is_O_fst_prod.norm_left.add is_O_snd_prod.norm_left } end /-- Let `f` be a measurable function integrable on `a..b`. The function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • f b - u • f a` within `s × t` at `(a, b)`, where `s ∈ {Iic a, {a}, Ici a, univ}` and `t ∈ {Iic b, {b}, Ici b, univ}` provided that `f` tends to `f a` and `f b` at the filters `la` and `lb` from the following table. In most cases this assumption is definitionally equal `continuous_at f _` or `continuous_within_at f _ _`. | `s` | `la` | `t` | `lb` | | ------- | ---- | --- | ---- | | `Iic a` | `𝓝[Iic a] a` | `Iic b` | `𝓝[Iic b] b` | | `Ici a` | `𝓝[Ioi a] a` | `Ici b` | `𝓝[Ioi b] b` | | `{a}` | `⊥` | `{b}` | `⊥` | | `univ` | `𝓝 a` | `univ` | `𝓝 b` | -/ lemma integral_has_fderiv_within_at (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f la) (hmeas_b : measurable_at_filter f lb) {s t : set ℝ} [FTC_filter a (𝓝[s] a) la] [FTC_filter b (𝓝[t] b) lb] (ha : tendsto f la (𝓝 $ f a)) (hb : tendsto f lb (𝓝 $ f b)) : has_fderiv_within_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right (f b) - (fst ℝ ℝ ℝ).smul_right (f a)) (s.prod t) (a, b) := integral_has_fderiv_within_at_of_tendsto_ae hf hmeas_a hmeas_b (ha.mono_left inf_le_left) (hb.mono_left inf_le_left) /-- An auxiliary tactic closing goals `unique_diff_within_at ℝ s a` where `s ∈ {Iic a, Ici a, univ}`. -/ meta def unique_diff_within_at_Ici_Iic_univ : tactic unit := `[apply_rules [unique_diff_on.unique_diff_within_at, unique_diff_on_Ici, unique_diff_on_Iic, left_mem_Ici, right_mem_Iic, unique_diff_within_at_univ]] /-- Let `f` be a measurable function integrable on `a..b`. Choose `s ∈ {Iic a, Ici a, univ}` and `t ∈ {Iic b, Ici b, univ}`. Suppose that `f` tends to `ca` and `cb` almost surely at the filters `la` and `lb` from the table below. Then `fderiv_within ℝ (λ p, ∫ x in p.1..p.2, f x) (s.prod t)` is equal to `(u, v) ↦ u • cb - v • ca`. | `s` | `la` | `t` | `lb` | | ------- | ---- | --- | ---- | | `Iic a` | `𝓝[Iic a] a` | `Iic b` | `𝓝[Iic b] b` | | `Ici a` | `𝓝[Ioi a] a` | `Ici b` | `𝓝[Ioi b] b` | | `univ` | `𝓝 a` | `univ` | `𝓝 b` | -/ lemma fderiv_within_integral_of_tendsto_ae (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f la) (hmeas_b : measurable_at_filter f lb) {s t : set ℝ} [FTC_filter a (𝓝[s] a) la] [FTC_filter b (𝓝[t] b) lb] (ha : tendsto f (la ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (lb ⊓ volume.ae) (𝓝 cb)) (hs : unique_diff_within_at ℝ s a . unique_diff_within_at_Ici_Iic_univ) (ht : unique_diff_within_at ℝ t b . unique_diff_within_at_Ici_Iic_univ) : fderiv_within ℝ (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) (s.prod t) (a, b) = ((snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca) := (integral_has_fderiv_within_at_of_tendsto_ae hf hmeas_a hmeas_b ha hb).fderiv_within $ hs.prod ht /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely as `x` tends to `b` from the right or from the left, then `u ↦ ∫ x in a..u, f x` has right (resp., left) derivative `c` at `b`. -/ lemma integral_has_deriv_within_at_of_tendsto_ae_right (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter b (𝓝[s] b) (𝓝[t] b)] (hmeas : measurable_at_filter f (𝓝[t] b)) (hb : tendsto f (𝓝[t] b ⊓ volume.ae) (𝓝 c)) : has_deriv_within_at (λ u, ∫ x in a..u, f x) c s b := integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right hf hmeas hb (tendsto_const_pure.mono_right FTC_filter.pure_le) tendsto_id /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` is continuous from the left or from the right at `b`, then `u ↦ ∫ x in a..u, f x` has left (resp., right) derivative `f b` at `b`. -/ lemma integral_has_deriv_within_at_right (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter b (𝓝[s] b) (𝓝[t] b)] (hmeas : measurable_at_filter f (𝓝[t] b)) (hb : continuous_within_at f t b) : has_deriv_within_at (λ u, ∫ x in a..u, f x) (f b) s b := integral_has_deriv_within_at_of_tendsto_ae_right hf hmeas (hb.mono_left inf_le_left) /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely as `x` tends to `b` from the right or from the left, then the right (resp., left) derivative of `u ↦ ∫ x in a..u, f x` at `b` equals `c`. -/ lemma deriv_within_integral_of_tendsto_ae_right (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter b (𝓝[s] b) (𝓝[t] b)] (hmeas: measurable_at_filter f (𝓝[t] b)) (hb : tendsto f (𝓝[t] b ⊓ volume.ae) (𝓝 c)) (hs : unique_diff_within_at ℝ s b . unique_diff_within_at_Ici_Iic_univ) : deriv_within (λ u, ∫ x in a..u, f x) s b = c := (integral_has_deriv_within_at_of_tendsto_ae_right hf hmeas hb).deriv_within hs /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` is continuous on the right or on the left at `b`, then the right (resp., left) derivative of `u ↦ ∫ x in a..u, f x` at `b` equals `f b`. -/ lemma deriv_within_integral_right (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter b (𝓝[s] b) (𝓝[t] b)] (hmeas : measurable_at_filter f (𝓝[t] b)) (hb : continuous_within_at f t b) (hs : unique_diff_within_at ℝ s b . unique_diff_within_at_Ici_Iic_univ) : deriv_within (λ u, ∫ x in a..u, f x) s b = f b := (integral_has_deriv_within_at_right hf hmeas hb).deriv_within hs /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely as `x` tends to `a` from the right or from the left, then `u ↦ ∫ x in u..b, f x` has right (resp., left) derivative `-c` at `a`. -/ lemma integral_has_deriv_within_at_of_tendsto_ae_left (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) (𝓝[t] a)] (hmeas : measurable_at_filter f (𝓝[t] a)) (ha : tendsto f (𝓝[t] a ⊓ volume.ae) (𝓝 c)) : has_deriv_within_at (λ u, ∫ x in u..b, f x) (-c) s a := by { simp only [integral_symm b], exact (integral_has_deriv_within_at_of_tendsto_ae_right hf.symm hmeas ha).neg } /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` is continuous from the left or from the right at `a`, then `u ↦ ∫ x in u..b, f x` has left (resp., right) derivative `-f a` at `a`. -/ lemma integral_has_deriv_within_at_left (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) (𝓝[t] a)] (hmeas : measurable_at_filter f (𝓝[t] a)) (ha : continuous_within_at f t a) : has_deriv_within_at (λ u, ∫ x in u..b, f x) (-f a) s a := integral_has_deriv_within_at_of_tendsto_ae_left hf hmeas (ha.mono_left inf_le_left) /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely as `x` tends to `a` from the right or from the left, then the right (resp., left) derivative of `u ↦ ∫ x in u..b, f x` at `a` equals `-c`. -/ lemma deriv_within_integral_of_tendsto_ae_left (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) (𝓝[t] a)] (hmeas : measurable_at_filter f (𝓝[t] a)) (ha : tendsto f (𝓝[t] a ⊓ volume.ae) (𝓝 c)) (hs : unique_diff_within_at ℝ s a . unique_diff_within_at_Ici_Iic_univ) : deriv_within (λ u, ∫ x in u..b, f x) s a = -c := (integral_has_deriv_within_at_of_tendsto_ae_left hf hmeas ha).deriv_within hs /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` is continuous on the right or on the left at `a`, then the right (resp., left) derivative of `u ↦ ∫ x in u..b, f x` at `a` equals `-f a`. -/ lemma deriv_within_integral_left (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) (𝓝[t] a)] (hmeas : measurable_at_filter f (𝓝[t] a)) (ha : continuous_within_at f t a) (hs : unique_diff_within_at ℝ s a . unique_diff_within_at_Ici_Iic_univ) : deriv_within (λ u, ∫ x in u..b, f x) s a = -f a := (integral_has_deriv_within_at_left hf hmeas ha).deriv_within hs /-! ### Fundamental theorem of calculus, part 2 This section contains theorems pertaining to FTC-2 for interval integrals. -/ variable {f' : ℝ → E} /-- The integral of a continuous function is differentiable on a real set `s`. -/ theorem differentiable_on_integral_of_continuous {s : set ℝ} (hintg : ∀ x ∈ s, interval_integrable f volume a x) (hcont : continuous f) : differentiable_on ℝ (λ u, ∫ x in a..u, f x) s := λ y hy, (integral_has_deriv_at_right (hintg y hy) hcont.measurable.ae_measurable.measurable_at_filter hcont.continuous_at) .differentiable_at.differentiable_within_at /-- The integral of a continuous function is continuous on a real set `s`. This is true even without the assumption of continuity, but a proof of that fact does not yet exist in mathlib. -/ theorem continuous_on_integral_of_continuous {s : set ℝ} (hintg : ∀ x ∈ s, interval_integrable f volume a x) (hcont : continuous f) : continuous_on (λ u, ∫ x in a..u, f x) s := (differentiable_on_integral_of_continuous hintg hcont).continuous_on /-- Fundamental theorem of calculus-2: If `f : ℝ → E` is continuous on `[a, b]` and has a right derivative at `f' x` for all `x` in `[a, b)`, and `f'` is continuous on `[a, b]`, then `∫ y in a..b, f' y` equals `f b - f a`. -/ theorem integral_eq_sub_of_has_deriv_right_of_le (hab : a ≤ b) (hcont : continuous_on f (Icc a b)) (hderiv : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) (hcont' : continuous_on f' (Icc a b)) : ∫ y in a..b, f' y = f b - f a := begin have hmeas' : ae_measurable f' (volume.restrict (Icc a b)), from hcont'.ae_measurable is_measurable_Icc, refine eq_sub_of_add_eq (eq_of_has_deriv_right_eq (λ y hy, _) hderiv (λ y hy, _) hcont (by simp) _ (right_mem_Icc.2 hab)), { refine (integral_has_deriv_within_at_right _ _ _).add_const _, { refine (hcont'.mono _).interval_integrable, simp only [hy.left, Icc_subset_Icc_right hy.right.le, interval_of_le] }, { exact ⟨_, Icc_mem_nhds_within_Ioi hy, hmeas'⟩, }, { exact (hcont' _ (mem_Icc_of_Ico hy)).mono_of_mem (Icc_mem_nhds_within_Ioi hy) } }, { -- TODO: prove that integral of any integrable function is continuous, and use here letI : tendsto_Ixx_class Ioc (𝓟 (Icc a b)) (𝓟 (Ioc a b)) := tendsto_Ixx_class_principal.2 (λ x hx y hy, Ioc_subset_Ioc hx.1 hy.2), haveI : is_measurably_generated (𝓝[Ioc a b] y) := is_measurable_Ioc.nhds_within_is_measurably_generated y, letI : FTC_filter y (𝓝[Icc a b] y) (𝓝[Ioc a b] y) := ⟨pure_le_nhds_within hy, inf_le_left⟩, refine (integral_has_deriv_within_at_right _ _ _).continuous_within_at.add continuous_within_at_const, { exact (hcont'.mono $ Icc_subset_Icc_right hy.2).interval_integrable_of_Icc hy.1 }, { exact ⟨_, mem_sets_of_superset self_mem_nhds_within Ioc_subset_Icc_self, hmeas'⟩ }, { exact (hcont' y hy).mono Ioc_subset_Icc_self } } end /-- Fundamental theorem of calculus-2: If `f : ℝ → E` is continuous on `[a, b]` (where `a ≤ b`) and has a right derivative at `f' x` for all `x` in `[a, b)`, and `f'` is continuous on `[a, b]` then `∫ y in a..b, f' y` equals `f b - f a`. -/ theorem integral_eq_sub_of_has_deriv_right (hcont : continuous_on f (interval a b)) (hderiv : ∀ x ∈ Ico (min a b) (max a b), has_deriv_within_at f (f' x) (Ici x) x) (hcont' : continuous_on f' (interval a b)) : ∫ y in a..b, f' y = f b - f a := begin cases le_total a b with hab hab, { simp only [interval_of_le, min_eq_left, max_eq_right, hab] at hcont hcont' hderiv, exact integral_eq_sub_of_has_deriv_right_of_le hab hcont hderiv hcont' }, { simp only [interval_of_ge, min_eq_right, max_eq_left, hab] at hcont hcont' hderiv, rw [integral_symm, integral_eq_sub_of_has_deriv_right_of_le hab hcont hderiv hcont', neg_sub] } end /-- Fundamental theorem of calculus-2: If `f : ℝ → E` is continuous on `[a, b]` and has a derivative at `f' x` for all `x` in `(a, b)`, and `f'` is continuous on `[a, b]`, then `∫ y in a..b, f' y` equals `f b - f a`. -/ theorem integral_eq_sub_of_has_deriv_at' (hcont : continuous_on f (interval a b)) (hderiv : ∀ x ∈ Ioo (min a b) (max a b), has_deriv_at f (f' x) x) (hcont' : continuous_on f' (interval a b)) : ∫ y in a..b, f' y = f b - f a := begin refine integral_eq_sub_of_has_deriv_right hcont _ hcont', intros y hy', obtain (hy | hy) : y ∈ Ioo (min a b) (max a b) ∨ min a b = y ∧ y < max a b, { simpa only [le_iff_lt_or_eq, or_and_distrib_right, mem_Ioo, mem_Ico] using hy' }, { exact (hderiv y hy).has_deriv_within_at }, { refine has_deriv_at_interval_left_endpoint_of_tendsto_deriv (λ x hx, (hderiv x hx).has_deriv_within_at.differentiable_within_at) _ _ _, { exact (hcont y (Ico_subset_Icc_self hy')).mono Ioo_subset_Icc_self }, { exact Ioo_mem_nhds_within_Ioi hy' }, { have : tendsto f' (𝓝[Ioi y] y) (𝓝 (f' y)), { refine tendsto.mono_left _ (nhds_within_mono y Ioi_subset_Ici_self), have h := hcont'.continuous_within_at (left_mem_Icc.mpr min_le_max), simpa only [← nhds_within_Icc_eq_nhds_within_Ici hy.2, interval, hy.1] using h }, have h := eventually_of_mem (Ioo_mem_nhds_within_Ioi hy') (λ x hx, (hderiv x hx).deriv), rwa tendsto_congr' h } }, end /-- Fundamental theorem of calculus-2: If `f : ℝ → E` has a derivative at `f' x` for all `x` in `[a, b]` and `f'` is continuous on `[a, b]`, then `∫ y in a..b, f' y` equals `f b - f a`. -/ theorem integral_eq_sub_of_has_deriv_at (hderiv : ∀ x ∈ interval a b, has_deriv_at f (f' x) x) (hcont' : continuous_on f' (interval a b)) : ∫ y in a..b, f' y = f b - f a := integral_eq_sub_of_has_deriv_at' (λ x hx, (hderiv x hx).continuous_at.continuous_within_at) (λ x hx, hderiv _ (mem_Icc_of_Ioo hx)) hcont' /-- Fundamental theorem of calculus-2: If `f : ℝ → E` is differentiable at every `x` in `[a, b]` and its derivative is continuous on `[a, b]`, then `∫ y in a..b, deriv f y` equals `f b - f a`. -/ theorem integral_deriv_eq_sub (hderiv : ∀ x ∈ interval a b, differentiable_at ℝ f x) (hcont' : continuous_on (deriv f) (interval a b)) : ∫ y in a..b, deriv f y = f b - f a := integral_eq_sub_of_has_deriv_at (λ x hx, (hderiv x hx).has_deriv_at) hcont' /-! ### Integration by parts -/ lemma integral_deriv_mul_eq_sub {u v u' v' : ℝ → ℝ} (hu : ∀ x ∈ interval a b, has_deriv_at u (u' x) x) (hv : ∀ x ∈ interval a b, has_deriv_at v (v' x) x) (hcu' : continuous_on u' (interval a b)) (hcv' : continuous_on v' (interval a b)) : ∫ x in a..b, u' x * v x + u x * v' x = u b * v b - u a * v a := begin have hcu : continuous_on u _ := λ x hx, (hu x hx).continuous_at.continuous_within_at, have hcv : continuous_on v _ := λ x hx, (hv x hx).continuous_at.continuous_within_at, rw integral_eq_sub_of_has_deriv_at, intros x hx; { exact (hu x hx).mul (hv x hx) }, { exact (hcu'.mul hcv).add (hcu.mul hcv') } end theorem integral_mul_deriv_eq_deriv_mul {u v u' v' : ℝ → ℝ} (hu : ∀ x ∈ interval a b, has_deriv_at u (u' x) x) (hv : ∀ x ∈ interval a b, has_deriv_at v (v' x) x) (hcu' : continuous_on u' (interval a b)) (hcv' : continuous_on v' (interval a b)) : ∫ x in a..b, u x * v' x = u b * v b - u a * v a - ∫ x in a..b, v x * u' x := begin have hcu : continuous_on u _ := λ x hx, (hu x hx).continuous_at.continuous_within_at, have hcv : continuous_on v _ := λ x hx, (hv x hx).continuous_at.continuous_within_at, rw [← integral_deriv_mul_eq_sub hu hv hcu' hcv', ← integral_sub], { apply integral_congr, exact λ x hx, by simp [mul_comm] }, { exact ((hcu'.mul hcv).add (hcu.mul hcv')).interval_integrable }, { exact (hcv.mul hcu').interval_integrable }, end end interval_integral
3546d369f2b47ce754cdf62609bc81631b1bf208
8b9f17008684d796c8022dab552e42f0cb6fb347
/hott/algebra/precategory/nat_trans.hlean
c1310ccde4c40f27796130b3e0d66b1f2497eaa4
[ "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
5,452
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: algebra.precategory.nat_trans Author: Floris van Doorn, Jakob von Raumer -/ import .functor .iso open eq category functor is_trunc equiv sigma.ops sigma is_equiv function pi funext iso structure nat_trans {C D : Precategory} (F G : C ⇒ D) := (natural_map : Π (a : C), hom (F a) (G a)) (naturality : Π {a b : C} (f : hom a b), G f ∘ natural_map a = natural_map b ∘ F f) namespace nat_trans infixl `⟹`:25 := nat_trans -- \==> variables {B C D E : Precategory} {F G H I : C ⇒ D} {F' G' : D ⇒ E} attribute natural_map [coercion] protected definition compose [reducible] (η : G ⟹ H) (θ : F ⟹ G) : F ⟹ H := nat_trans.mk (λ a, η a ∘ θ a) (λ a b f, calc H f ∘ (η a ∘ θ a) = (H f ∘ η a) ∘ θ a : by rewrite assoc ... = (η b ∘ G f) ∘ θ a : by rewrite naturality ... = η b ∘ (G f ∘ θ a) : by rewrite assoc ... = η b ∘ (θ b ∘ F f) : by rewrite naturality ... = (η b ∘ θ b) ∘ F f : by rewrite assoc) infixr `∘n`:60 := compose protected definition id [reducible] {C D : Precategory} {F : functor C D} : nat_trans F F := mk (λa, id) (λa b f, !id_right ⬝ !id_left⁻¹) protected definition ID [reducible] {C D : Precategory} (F : functor C D) : nat_trans F F := id definition nat_trans_eq_mk' {η₁ η₂ : Π (a : C), hom (F a) (G a)} (nat₁ : Π (a b : C) (f : hom a b), G f ∘ η₁ a = η₁ b ∘ F f) (nat₂ : Π (a b : C) (f : hom a b), G f ∘ η₂ a = η₂ b ∘ F f) (p : η₁ ∼ η₂) : nat_trans.mk η₁ nat₁ = nat_trans.mk η₂ nat₂ := apD011 nat_trans.mk (eq_of_homotopy p) !is_hprop.elim definition nat_trans_eq_mk {η₁ η₂ : F ⟹ G} : natural_map η₁ ∼ natural_map η₂ → η₁ = η₂ := nat_trans.rec_on η₁ (λf₁ nat₁, nat_trans.rec_on η₂ (λf₂ nat₂ p, !nat_trans_eq_mk' p)) protected definition assoc (η₃ : H ⟹ I) (η₂ : G ⟹ H) (η₁ : F ⟹ G) : η₃ ∘n (η₂ ∘n η₁) = (η₃ ∘n η₂) ∘n η₁ := nat_trans_eq_mk (λa, !assoc) protected definition id_left (η : F ⟹ G) : id ∘n η = η := nat_trans_eq_mk (λa, !id_left) protected definition id_right (η : F ⟹ G) : η ∘n id = η := nat_trans_eq_mk (λa, !id_right) protected definition sigma_char (F G : C ⇒ D) : (Σ (η : Π (a : C), hom (F a) (G a)), Π (a b : C) (f : hom a b), G f ∘ η a = η b ∘ F f) ≃ (F ⟹ G) := begin fapply equiv.mk, -- TODO(Leo): investigate why we need to use rexact in the following line {intro S, apply nat_trans.mk, rexact (S.2)}, fapply adjointify, intro H, fapply sigma.mk, intro a, exact (H a), intros [a, b, f], exact (naturality H f), intro η, apply nat_trans_eq_mk, intro a, apply idp, intro S, fapply sigma_eq, apply eq_of_homotopy, intro a, apply idp, apply is_hprop.elim, end set_option apply.class_instance false definition is_hset_nat_trans : is_hset (F ⟹ G) := begin apply is_trunc_is_equiv_closed, apply (equiv.to_is_equiv !sigma_char), apply is_trunc_sigma, apply is_trunc_pi, intro a, exact (@homH (Precategory.carrier D) _ (F a) (G a)), intro η, apply is_trunc_pi, intro a, apply is_trunc_pi, intro b, apply is_trunc_pi, intro f, apply is_trunc_eq, apply is_trunc_succ, exact (@homH (Precategory.carrier D) _ (F a) (G b)), end definition nat_trans_functor_compose [reducible] (η : G ⟹ H) (F : E ⇒ C) : G ∘f F ⟹ H ∘f F := nat_trans.mk (λ a, η (F a)) (λ a b f, naturality η (F f)) definition functor_nat_trans_compose [reducible] (F : D ⇒ E) (η : G ⟹ H) : F ∘f G ⟹ F ∘f H := nat_trans.mk (λ a, F (η a)) (λ a b f, calc F (H f) ∘ F (η a) = F (H f ∘ η a) : by rewrite respect_comp ... = F (η b ∘ G f) : by rewrite (naturality η f) ... = F (η b) ∘ F (G f) : by rewrite respect_comp) infixr `∘nf`:60 := nat_trans_functor_compose infixr `∘fn`:60 := functor_nat_trans_compose definition functor_nat_trans_compose_commute (η : F ⟹ G) (θ : F' ⟹ G') : (θ ∘nf G) ∘n (F' ∘fn η) = (G' ∘fn η) ∘n (θ ∘nf F) := nat_trans_eq_mk (λc, (naturality θ (η c))⁻¹) definition fn_n_distrib (F' : D ⇒ E) (η : G ⟹ H) (θ : F ⟹ G) : F' ∘fn (η ∘n θ) = (F' ∘fn η) ∘n (F' ∘fn θ) := nat_trans_eq_mk (λc, !respect_comp) definition n_nf_distrib (η : G ⟹ H) (θ : F ⟹ G) (F' : B ⇒ C) : (η ∘n θ) ∘nf F' = (η ∘nf F') ∘n (θ ∘nf F') := nat_trans_eq_mk (λc, idp) definition fn_id (F' : D ⇒ E) : F' ∘fn nat_trans.ID F = nat_trans.id := nat_trans_eq_mk (λc, !respect_id) definition id_nf (F' : B ⇒ C) : nat_trans.ID F ∘nf F' = nat_trans.id := nat_trans_eq_mk (λc, idp) definition id_fn (η : G ⟹ H) (c : C) : (functor.id ∘fn η) c = η c := idp definition nf_id (η : G ⟹ H) (c : C) : (η ∘nf functor.id) c = η c := idp definition nat_trans_of_eq [reducible] (p : F = G) : F ⟹ G := nat_trans.mk (λc, hom_of_eq (ap010 to_fun_ob p c)) (λa b f, eq.rec_on p (!id_right ⬝ !id_left⁻¹)) end nat_trans
85a1824b4af3cf3aa90106f921adde2a16c6630e
43390109ab88557e6090f3245c47479c123ee500
/src/M1F/problem_bank/0203/Q0203.lean
262b4804fd653d287bd21546f87447670a7bc848
[ "Apache-2.0" ]
permissive
Ja1941/xena-UROP-2018
41f0956519f94d56b8bf6834a8d39473f4923200
b111fb87f343cf79eca3b886f99ee15c1dd9884b
refs/heads/master
1,662,355,955,139
1,590,577,325,000
1,590,577,325,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
521
lean
import algebra.group_power theorem Q3a (n : int) : (3:ℤ) ∣ n ^ 2 → (3:ℤ) ∣ n := sorry def exists_sqrt_3 := square_root.exists_unique_square_root 3 (by norm_num) noncomputable def sqrt3 := classical.some (exists_sqrt_3) def sqrt3_proof := classical.some_spec (exists_sqrt_3) example : sqrt3 ** 2 = 3 := sqrt3_proof.right.left noncomputable example : monoid ℝ := by apply_instance theorem no_rational_squared_is_three : ¬ (∃ (q:ℚ),q**2=3) := sorry theorem Q3b : M1F.is_irrational (sqrt3) := sorry
da3124e103b42e5c8d3579569d149b26f11c9a91
ebf7140a9ea507409ff4c994124fa36e79b4ae35
/src/exercises_sources/thursday/category_theory/exercise2.lean
3a5337ee06ed423632620290c3a8193f3f604271
[]
no_license
fundou/lftcm2020
3e88d58a92755ea5dd49f19c36239c35286ecf5e
99d11bf3bcd71ffeaef0250caa08ecc46e69b55b
refs/heads/master
1,685,610,799,304
1,624,070,416,000
1,624,070,416,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
959
lean
import algebra.category.CommRing.basic import data.polynomial /-! Let's show that taking polynomials over a ring is functor `Ring ⥤ Ring`. -/ noncomputable theory -- the default implementation of polynomials is noncomputable -- Just ignore this for now: it's a hack that prevents an annoying problem, -- and a cleaner fix is on its way to mathlib. local attribute [irreducible] polynomial.eval₂ /-! Hints: * use `polynomial.map_ring_hom` -/ def Ring.polynomial : Ring ⥤ Ring := sorry def CommRing.polynomial : CommRing ⥤ CommRing := sorry open category_theory def commutes : (forget₂ CommRing Ring) ⋙ Ring.polynomial ≅ CommRing.polynomial ⋙ (forget₂ CommRing Ring) := -- Hint: You can do this in two lines, ≤ 33 columns! sorry /-! There are some further hints in `hints/category_theory/exercise2/` -/ /-! Bonus problem: Why did we set `local attribute [irreducible] polynomial.eval₂`? What goes wrong without it? Why? -/
704eb65fae6b44d66f6ed20149aa4ef909214dd1
5749d8999a76f3a8fddceca1f6941981e33aaa96
/src/topology/uniform_space/uniform_embedding.lean
c7e167154dbabb2e5b146a9b77a77f45e4f6c3e0
[ "Apache-2.0" ]
permissive
jdsalchow/mathlib
13ab43ef0d0515a17e550b16d09bd14b76125276
497e692b946d93906900bb33a51fd243e7649406
refs/heads/master
1,585,819,143,348
1,580,072,892,000
1,580,072,892,000
154,287,128
0
0
Apache-2.0
1,540,281,610,000
1,540,281,609,000
null
UTF-8
Lean
false
false
19,046
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, Sébastien Gouëzel, Patrick Massot Uniform embeddings of uniform spaces. Extension of uniform continuous functions. -/ import topology.uniform_space.cauchy topology.uniform_space.separation import topology.dense_embedding open filter topological_space lattice set classical open_locale classical open_locale uniformity topological_space section variables {α : Type*} {β : Type*} {γ : Type*} [uniform_space α] [uniform_space β] [uniform_space γ] universe u structure uniform_inducing (f : α → β) : Prop := (comap_uniformity : comap (λx:α×α, (f x.1, f x.2)) (𝓤 β) = 𝓤 α) lemma uniform_inducing.mk' {f : α → β} (h : ∀ s, s ∈ 𝓤 α ↔ ∃ t ∈ 𝓤 β, ∀ x y : α, (f x, f y) ∈ t → (x, y) ∈ s) : uniform_inducing f := ⟨by simp [eq_comm, filter.ext_iff, subset_def, h]⟩ lemma uniform_inducing.comp {g : β → γ} (hg : uniform_inducing g) {f : α → β} (hf : uniform_inducing f) : uniform_inducing (g ∘ f) := ⟨ by rw [show (λ (x : α × α), ((g ∘ f) x.1, (g ∘ f) x.2)) = (λ y : β × β, (g y.1, g y.2)) ∘ (λ x : α × α, (f x.1, f x.2)), by ext ; simp, ← filter.comap_comap_comp, hg.1, hf.1]⟩ structure uniform_embedding (f : α → β) extends uniform_inducing f : Prop := (inj : function.injective f) lemma uniform_embedding.comp {g : β → γ} (hg : uniform_embedding g) {f : α → β} (hf : uniform_embedding f) : uniform_embedding (g ∘ f) := { inj := function.injective_comp hg.inj hf.inj, ..hg.to_uniform_inducing.comp hf.to_uniform_inducing } theorem uniform_embedding_def {f : α → β} : uniform_embedding f ↔ function.injective f ∧ ∀ s, s ∈ 𝓤 α ↔ ∃ t ∈ 𝓤 β, ∀ x y : α, (f x, f y) ∈ t → (x, y) ∈ s := begin split, { rintro ⟨⟨h⟩, h'⟩, rw [eq_comm, filter.ext_iff] at h, simp [*, subset_def] }, { rintro ⟨h, h'⟩, refine uniform_embedding.mk ⟨_⟩ h, rw [eq_comm, filter.ext_iff], simp [*, subset_def] } end theorem uniform_embedding_def' {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ s, s ∈ 𝓤 α → ∃ t ∈ 𝓤 β, ∀ x y : α, (f x, f y) ∈ t → (x, y) ∈ s := by simp [uniform_embedding_def, uniform_continuous_def]; exact ⟨λ ⟨I, H⟩, ⟨I, λ s su, (H _).2 ⟨s, su, λ x y, id⟩, λ s, (H s).1⟩, λ ⟨I, H₁, H₂⟩, ⟨I, λ s, ⟨H₂ s, λ ⟨t, tu, h⟩, sets_of_superset _ (H₁ t tu) (λ ⟨a, b⟩, h a b)⟩⟩⟩ lemma uniform_inducing.uniform_continuous {f : α → β} (hf : uniform_inducing f) : uniform_continuous f := by simp [uniform_continuous, hf.comap_uniformity.symm, tendsto_comap] lemma uniform_inducing.uniform_continuous_iff {f : α → β} {g : β → γ} (hg : uniform_inducing g) : uniform_continuous f ↔ uniform_continuous (g ∘ f) := by simp [uniform_continuous, tendsto]; rw [← hg.comap_uniformity, ← map_le_iff_le_comap, filter.map_map] lemma uniform_inducing.inducing {f : α → β} (h : uniform_inducing f) : inducing f := begin refine ⟨eq_of_nhds_eq_nhds $ assume a, _ ⟩, rw [nhds_induced, nhds_eq_uniformity, nhds_eq_uniformity, ← h.comap_uniformity, comap_lift'_eq, comap_lift'_eq2]; { refl <|> exact monotone_preimage } end lemma uniform_inducing.prod {α' : Type*} {β' : Type*} [uniform_space α'] [uniform_space β'] {e₁ : α → α'} {e₂ : β → β'} (h₁ : uniform_inducing e₁) (h₂ : uniform_inducing e₂) : uniform_inducing (λp:α×β, (e₁ p.1, e₂ p.2)) := ⟨by simp [(∘), uniformity_prod, h₁.comap_uniformity.symm, h₂.comap_uniformity.symm, comap_inf, comap_comap_comp]⟩ lemma uniform_inducing.dense_inducing {f : α → β} (h : uniform_inducing f) (hd : dense_range f) : dense_inducing f := { dense := hd, induced := h.inducing.induced } lemma uniform_embedding.embedding {f : α → β} (h : uniform_embedding f) : embedding f := { induced := h.to_uniform_inducing.inducing.induced, inj := h.inj } lemma uniform_embedding.dense_embedding {f : α → β} (h : uniform_embedding f) (hd : dense_range f) : dense_embedding f := { dense := hd, inj := h.inj, induced := h.embedding.induced } lemma closure_image_mem_nhds_of_uniform_inducing {s : set (α×α)} {e : α → β} (b : β) (he₁ : uniform_inducing e) (he₂ : dense_inducing e) (hs : s ∈ 𝓤 α) : ∃a, closure (e '' {a' | (a, a') ∈ s}) ∈ 𝓝 b := have s ∈ comap (λp:α×α, (e p.1, e p.2)) (𝓤 β), from he₁.comap_uniformity.symm ▸ hs, let ⟨t₁, ht₁u, ht₁⟩ := this in have ht₁ : ∀p:α×α, (e p.1, e p.2) ∈ t₁ → p ∈ s, from ht₁, let ⟨t₂, ht₂u, ht₂s, ht₂c⟩ := comp_symm_of_uniformity ht₁u in let ⟨t, htu, hts, htc⟩ := comp_symm_of_uniformity ht₂u in have preimage e {b' | (b, b') ∈ t₂} ∈ comap e (𝓝 b), from preimage_mem_comap $ mem_nhds_left b ht₂u, let ⟨a, (ha : (b, e a) ∈ t₂)⟩ := inhabited_of_mem_sets (he₂.comap_nhds_ne_bot) this in have ∀b' (s' : set (β × β)), (b, b') ∈ t → s' ∈ 𝓤 β → {y : β | (b', y) ∈ s'} ∩ e '' {a' : α | (a, a') ∈ s} ≠ ∅, from assume b' s' hb' hs', have preimage e {b'' | (b', b'') ∈ s' ∩ t} ∈ comap e (𝓝 b'), from preimage_mem_comap $ mem_nhds_left b' $ inter_mem_sets hs' htu, let ⟨a₂, ha₂s', ha₂t⟩ := inhabited_of_mem_sets (he₂.comap_nhds_ne_bot) this in have (e a, e a₂) ∈ t₁, from ht₂c $ prod_mk_mem_comp_rel (ht₂s ha) $ htc $ prod_mk_mem_comp_rel hb' ha₂t, have e a₂ ∈ {b'':β | (b', b'') ∈ s'} ∩ e '' {a' | (a, a') ∈ s}, from ⟨ha₂s', mem_image_of_mem _ $ ht₁ (a, a₂) this⟩, ne_empty_of_mem this, have ∀b', (b, b') ∈ t → 𝓝 b' ⊓ principal (e '' {a' | (a, a') ∈ s}) ≠ ⊥, begin intros b' hb', rw [nhds_eq_uniformity, lift'_inf_principal_eq, lift'_ne_bot_iff], exact assume s, this b' s hb', exact monotone_inter monotone_preimage monotone_const end, have ∀b', (b, b') ∈ t → b' ∈ closure (e '' {a' | (a, a') ∈ s}), from assume b' hb', by rw [closure_eq_nhds]; exact this b' hb', ⟨a, (𝓝 b).sets_of_superset (mem_nhds_left b htu) this⟩ lemma uniform_embedding_subtype_emb (p : α → Prop) {e : α → β} (ue : uniform_embedding e) (de : dense_embedding e) : uniform_embedding (dense_embedding.subtype_emb p e) := { comap_uniformity := by simp [comap_comap_comp, (∘), dense_embedding.subtype_emb, uniformity_subtype, ue.comap_uniformity.symm], inj := (de.subtype p).inj } lemma uniform_embedding.prod {α' : Type*} {β' : Type*} [uniform_space α'] [uniform_space β'] {e₁ : α → α'} {e₂ : β → β'} (h₁ : uniform_embedding e₁) (h₂ : uniform_embedding e₂) : uniform_embedding (λp:α×β, (e₁ p.1, e₂ p.2)) := { inj := function.injective_prod h₁.inj h₂.inj, ..h₁.to_uniform_inducing.prod h₂.to_uniform_inducing } /-- A set is complete iff its image under a uniform embedding is complete. -/ lemma is_complete_image_iff {m : α → β} {s : set α} (hm : uniform_embedding m) : is_complete (m '' s) ↔ is_complete s := begin refine ⟨λ c f hf fs, _, λ c f hf fs, _⟩, { let f' := map m f, have cf' : cauchy f' := cauchy_map hm.to_uniform_inducing.uniform_continuous hf, have f's : f' ≤ principal (m '' s), { simp only [filter.le_principal_iff, set.mem_image, filter.mem_map], exact mem_sets_of_superset (filter.le_principal_iff.1 fs) (λx hx, ⟨x, hx, rfl⟩) }, rcases c f' cf' f's with ⟨y, yms, hy⟩, rcases mem_image_iff_bex.1 yms with ⟨x, xs, rfl⟩, rw [map_le_iff_le_comap, ← nhds_induced, ← (uniform_embedding.embedding hm).induced] at hy, exact ⟨x, xs, hy⟩ }, { rw filter.le_principal_iff at fs, let f' := comap m f, have cf' : cauchy f', { have : comap m f ≠ ⊥, { refine comap_ne_bot (λt ht, _), have A : t ∩ m '' s ∈ f := filter.inter_mem_sets ht fs, have : t ∩ m '' s ≠ ∅, { by_contradiction h, simp only [not_not, ne.def] at h, simpa [h, empty_in_sets_eq_bot, hf.1] using A }, rcases ne_empty_iff_exists_mem.1 this with ⟨x, ⟨xt, xms⟩⟩, rcases mem_image_iff_bex.1 xms with ⟨y, ys, yx⟩, rw ← yx at xt, exact ⟨y, xt⟩ }, apply cauchy_comap _ hf this, simp only [hm.comap_uniformity, le_refl] }, have : f' ≤ principal s := by simp [f']; exact ⟨m '' s, by simpa using fs, by simp [preimage_image_eq s hm.inj]⟩, rcases c f' cf' this with ⟨x, xs, hx⟩, existsi [m x, mem_image_of_mem m xs], rw [(uniform_embedding.embedding hm).induced, nhds_induced] at hx, calc f = map m f' : (map_comap $ filter.mem_sets_of_superset fs $ image_subset_range _ _).symm ... ≤ map m (comap m (𝓝 (m x))) : map_mono hx ... ≤ 𝓝 (m x) : map_comap_le } end lemma complete_space_extension {m : β → α} (hm : uniform_inducing m) (dense : dense_range m) (h : ∀f:filter β, cauchy f → ∃x:α, map m f ≤ 𝓝 x) : complete_space α := ⟨assume (f : filter α), assume hf : cauchy f, let p : set (α × α) → set α → set α := λs t, {y : α| ∃x:α, x ∈ t ∧ (x, y) ∈ s}, g := (𝓤 α).lift (λs, f.lift' (p s)) in have mp₀ : monotone p, from assume a b h t s ⟨x, xs, xa⟩, ⟨x, xs, h xa⟩, have mp₁ : ∀{s}, monotone (p s), from assume s a b h x ⟨y, ya, yxs⟩, ⟨y, h ya, yxs⟩, have f ≤ g, from le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht, le_principal_iff.mpr $ mem_sets_of_superset ht $ assume x hx, ⟨x, hx, refl_mem_uniformity hs⟩, have g ≠ ⊥, from ne_bot_of_le_ne_bot hf.left this, have comap m g ≠ ⊥, from comap_ne_bot $ assume t ht, let ⟨t', ht', ht_mem⟩ := (mem_lift_sets $ monotone_lift' monotone_const mp₀).mp ht in let ⟨t'', ht'', ht'_sub⟩ := (mem_lift'_sets mp₁).mp ht_mem in let ⟨x, (hx : x ∈ t'')⟩ := inhabited_of_mem_sets hf.left ht'' in have h₀ : 𝓝 x ⊓ principal (range m) ≠ ⊥, by simpa [dense_range, closure_eq_nhds] using dense x, have h₁ : {y | (x, y) ∈ t'} ∈ 𝓝 x ⊓ principal (range m), from @mem_inf_sets_of_left α (𝓝 x) (principal (range m)) _ $ mem_nhds_left x ht', have h₂ : range m ∈ 𝓝 x ⊓ principal (range m), from @mem_inf_sets_of_right α (𝓝 x) (principal (range m)) _ $ subset.refl _, have {y | (x, y) ∈ t'} ∩ range m ∈ 𝓝 x ⊓ principal (range m), from @inter_mem_sets α (𝓝 x ⊓ principal (range m)) _ _ h₁ h₂, let ⟨y, xyt', b, b_eq⟩ := inhabited_of_mem_sets h₀ this in ⟨b, b_eq.symm ▸ ht'_sub ⟨x, hx, xyt'⟩⟩, have cauchy g, from ⟨‹g ≠ ⊥›, assume s hs, let ⟨s₁, hs₁, (comp_s₁ : comp_rel s₁ s₁ ⊆ s)⟩ := comp_mem_uniformity_sets hs, ⟨s₂, hs₂, (comp_s₂ : comp_rel s₂ s₂ ⊆ s₁)⟩ := comp_mem_uniformity_sets hs₁, ⟨t, ht, (prod_t : set.prod t t ⊆ s₂)⟩ := mem_prod_same_iff.mp (hf.right hs₂) in have hg₁ : p (preimage prod.swap s₁) t ∈ g, from mem_lift (symm_le_uniformity hs₁) $ @mem_lift' α α f _ t ht, have hg₂ : p s₂ t ∈ g, from mem_lift hs₂ $ @mem_lift' α α f _ t ht, have hg : set.prod (p (preimage prod.swap s₁) t) (p s₂ t) ∈ filter.prod g g, from @prod_mem_prod α α _ _ g g hg₁ hg₂, (filter.prod g g).sets_of_superset hg (assume ⟨a, b⟩ ⟨⟨c₁, c₁t, hc₁⟩, ⟨c₂, c₂t, hc₂⟩⟩, have (c₁, c₂) ∈ set.prod t t, from ⟨c₁t, c₂t⟩, comp_s₁ $ prod_mk_mem_comp_rel hc₁ $ comp_s₂ $ prod_mk_mem_comp_rel (prod_t this) hc₂)⟩, have cauchy (filter.comap m g), from cauchy_comap (le_of_eq hm.comap_uniformity) ‹cauchy g› (by assumption), let ⟨x, (hx : map m (filter.comap m g) ≤ 𝓝 x)⟩ := h _ this in have map m (filter.comap m g) ⊓ 𝓝 x ≠ ⊥, from (le_nhds_iff_adhp_of_cauchy (cauchy_map hm.uniform_continuous this)).mp hx, have g ⊓ 𝓝 x ≠ ⊥, from ne_bot_of_le_ne_bot this (inf_le_inf (assume s hs, ⟨s, hs, subset.refl _⟩) (le_refl _)), ⟨x, calc f ≤ g : by assumption ... ≤ 𝓝 x : le_nhds_of_cauchy_adhp ‹cauchy g› this⟩⟩ lemma totally_bounded_preimage {f : α → β} {s : set β} (hf : uniform_embedding f) (hs : totally_bounded s) : totally_bounded (f ⁻¹' s) := λ t ht, begin rw ← hf.comap_uniformity at ht, rcases mem_comap_sets.2 ht with ⟨t', ht', ts⟩, rcases totally_bounded_iff_subset.1 (totally_bounded_subset (image_preimage_subset f s) hs) _ ht' with ⟨c, cs, hfc, hct⟩, refine ⟨f ⁻¹' c, finite_preimage (inj_on_of_injective _ hf.inj) hfc, λ x h, _⟩, have := hct (mem_image_of_mem f h), simp at this ⊢, rcases this with ⟨z, zc, zt⟩, rcases cs zc with ⟨y, yc, rfl⟩, exact ⟨y, zc, ts (by exact zt)⟩ end end lemma uniform_embedding_comap {α : Type*} {β : Type*} {f : α → β} [u : uniform_space β] (hf : function.injective f) : @uniform_embedding α β (uniform_space.comap f u) u f := @uniform_embedding.mk _ _ (uniform_space.comap f u) _ _ (@uniform_inducing.mk _ _ (uniform_space.comap f u) _ _ rfl) hf section uniform_extension variables {α : Type*} {β : Type*} {γ : Type*} [uniform_space α] [uniform_space β] [uniform_space γ] {e : β → α} (h_e : uniform_inducing e) (h_dense : dense_range e) {f : β → γ} (h_f : uniform_continuous f) local notation `ψ` := (h_e.dense_inducing h_dense).extend f lemma uniformly_extend_exists [complete_space γ] (a : α) : ∃c, tendsto f (comap e (𝓝 a)) (𝓝 c) := let de := (h_e.dense_inducing h_dense) in have cauchy (𝓝 a), from cauchy_nhds, have cauchy (comap e (𝓝 a)), from cauchy_comap (le_of_eq h_e.comap_uniformity) this de.comap_nhds_ne_bot, have cauchy (map f (comap e (𝓝 a))), from cauchy_map h_f this, complete_space.complete this lemma uniform_extend_subtype [complete_space γ] {p : α → Prop} {e : α → β} {f : α → γ} {b : β} {s : set α} (hf : uniform_continuous (λx:subtype p, f x.val)) (he : uniform_embedding e) (hd : ∀x:β, x ∈ closure (range e)) (hb : closure (e '' s) ∈ 𝓝 b) (hs : is_closed s) (hp : ∀x∈s, p x) : ∃c, tendsto f (comap e (𝓝 b)) (𝓝 c) := have de : dense_embedding e, from he.dense_embedding hd, have de' : dense_embedding (dense_embedding.subtype_emb p e), by exact de.subtype p, have ue' : uniform_embedding (dense_embedding.subtype_emb p e), from uniform_embedding_subtype_emb _ he de, have b ∈ closure (e '' {x | p x}), from (closure_mono $ mono_image $ hp) (mem_of_nhds hb), let ⟨c, (hc : tendsto (f ∘ subtype.val) (comap (dense_embedding.subtype_emb p e) (𝓝 ⟨b, this⟩)) (𝓝 c))⟩ := uniformly_extend_exists ue'.to_uniform_inducing de'.dense hf _ in begin rw [nhds_subtype_eq_comap] at hc, simp [comap_comap_comp] at hc, change (tendsto (f ∘ @subtype.val α p) (comap (e ∘ @subtype.val α p) (𝓝 b)) (𝓝 c)) at hc, rw [←comap_comap_comp, tendsto_comap'_iff] at hc, exact ⟨c, hc⟩, exact ⟨_, hb, assume x, begin change e x ∈ (closure (e '' s)) → x ∈ range subtype.val, rw [←closure_induced, closure_eq_nhds, mem_set_of_eq, (≠), nhds_induced, ← de.to_dense_inducing.nhds_eq_comap], change x ∈ {x | 𝓝 x ⊓ principal s ≠ ⊥} → x ∈ range subtype.val, rw [←closure_eq_nhds, closure_eq_of_is_closed hs], exact assume hxs, ⟨⟨x, hp x hxs⟩, rfl⟩, exact de.inj end⟩ end variables [separated γ] lemma uniformly_extend_of_ind (b : β) : ψ (e b) = f b := dense_inducing.extend_e_eq _ b (continuous_iff_continuous_at.1 h_f.continuous b) include h_f lemma uniformly_extend_spec [complete_space γ] (a : α) : tendsto f (comap e (𝓝 a)) (𝓝 (ψ a)) := let de := (h_e.dense_inducing h_dense) in begin by_cases ha : a ∈ range e, { rcases ha with ⟨b, rfl⟩, rw [uniformly_extend_of_ind _ _ h_f, ← de.nhds_eq_comap], exact h_f.continuous.tendsto _ }, { simp only [dense_inducing.extend, dif_neg ha], exact (@lim_spec _ _ (id _) _ $ uniformly_extend_exists h_e h_dense h_f _) } end lemma uniform_continuous_uniformly_extend [cγ : complete_space γ] : uniform_continuous ψ := assume d hd, let ⟨s, hs, hs_comp⟩ := (mem_lift'_sets $ monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp (comp_le_uniformity3 hd) in have h_pnt : ∀{a m}, m ∈ 𝓝 a → ∃c, c ∈ f '' preimage e m ∧ (c, ψ a) ∈ s ∧ (ψ a, c) ∈ s, from assume a m hm, have nb : map f (comap e (𝓝 a)) ≠ ⊥, from map_ne_bot (h_e.dense_inducing h_dense).comap_nhds_ne_bot, have (f '' preimage e m) ∩ ({c | (c, ψ a) ∈ s } ∩ {c | (ψ a, c) ∈ s }) ∈ map f (comap e (𝓝 a)), from inter_mem_sets (image_mem_map $ preimage_mem_comap $ hm) (uniformly_extend_spec h_e h_dense h_f _ (inter_mem_sets (mem_nhds_right _ hs) (mem_nhds_left _ hs))), inhabited_of_mem_sets nb this, have preimage (λp:β×β, (f p.1, f p.2)) s ∈ 𝓤 β, from h_f hs, have preimage (λp:β×β, (f p.1, f p.2)) s ∈ comap (λx:β×β, (e x.1, e x.2)) (𝓤 α), by rwa [h_e.comap_uniformity.symm] at this, let ⟨t, ht, ts⟩ := this in show preimage (λp:(α×α), (ψ p.1, ψ p.2)) d ∈ 𝓤 α, from (𝓤 α).sets_of_superset (interior_mem_uniformity ht) $ assume ⟨x₁, x₂⟩ hx_t, have 𝓝 (x₁, x₂) ≤ principal (interior t), from is_open_iff_nhds.mp is_open_interior (x₁, x₂) hx_t, have interior t ∈ filter.prod (𝓝 x₁) (𝓝 x₂), by rwa [nhds_prod_eq, le_principal_iff] at this, let ⟨m₁, hm₁, m₂, hm₂, (hm : set.prod m₁ m₂ ⊆ interior t)⟩ := mem_prod_iff.mp this in let ⟨a, ha₁, _, ha₂⟩ := h_pnt hm₁ in let ⟨b, hb₁, hb₂, _⟩ := h_pnt hm₂ in have set.prod (preimage e m₁) (preimage e m₂) ⊆ preimage (λp:(β×β), (f p.1, f p.2)) s, from calc _ ⊆ preimage (λp:(β×β), (e p.1, e p.2)) (interior t) : preimage_mono hm ... ⊆ preimage (λp:(β×β), (e p.1, e p.2)) t : preimage_mono interior_subset ... ⊆ preimage (λp:(β×β), (f p.1, f p.2)) s : ts, have set.prod (f '' preimage e m₁) (f '' preimage e m₂) ⊆ s, from calc set.prod (f '' preimage e m₁) (f '' preimage e m₂) = (λp:(β×β), (f p.1, f p.2)) '' (set.prod (preimage e m₁) (preimage e m₂)) : prod_image_image_eq ... ⊆ (λp:(β×β), (f p.1, f p.2)) '' preimage (λp:(β×β), (f p.1, f p.2)) s : mono_image this ... ⊆ s : image_subset_iff.mpr $ subset.refl _, have (a, b) ∈ s, from @this (a, b) ⟨ha₁, hb₁⟩, hs_comp $ show (ψ x₁, ψ x₂) ∈ comp_rel s (comp_rel s s), from ⟨a, ha₂, ⟨b, this, hb₂⟩⟩ end uniform_extension
f83815ce1ca3f31a1e25c45a7658430751f41d97
3d2a7f1582fe5bae4d0bdc2fe86e997521239a65
/spatial-reasoning/spatial-reasoning-problem-07.lean
e26a5475aa52e2f053f58caaca646c4777fc3ee4
[]
no_license
own-pt/common-sense-lean
e4fa643ae010459de3d1bf673be7cbc7062563c9
f672210aecb4172f5bae265e43e6867397e13b1c
refs/heads/master
1,622,065,660,261
1,589,487,533,000
1,589,487,533,000
254,167,782
3
2
null
1,589,487,535,000
1,586,370,214,000
Lean
UTF-8
Lean
false
false
1,247
lean
/- Spatial Reasoning Problem 07 -/ /- It can be found at: SpatialQs.txt -/ /- (7) Pittsburgh is north of Washington, DC. New York City is north of Pittsburgh. Is New York City north of Washington, DC? -/ constant U : Type constants North South Pittsburgh Washington_DC New_York TransitivePositionalAttribute PositionalAttribute : U constant ins : U → U → Prop constant located : U → U → Prop constant subclass : U → U → Prop constant orientation: U → U → U → Prop /- axioms from problem -/ axiom a1 : orientation Pittsburgh Washington_DC North axiom a2 : orientation New_York Pittsburgh North /- axioms to be added -/ -- (subclass TransitivePositionalAttribute PositionalAttribute) axiom a3 : subclass TransitivePositionalAttribute PositionalAttribute -- (instance North TransitivePositionalAttribute) axiom a4 : ∀ A B C P, (orientation A B P) ∧ (orientation B C P) ∧ (ins P TransitivePositionalAttribute) → (orientation A C P) -- (instance North TransitivePositionalAttribute) axiom a5 : ins North TransitivePositionalAttribute /- demonstration start -/ theorem new_york_city_north_of_washington_dc: orientation New_York Washington_DC North := by exact (a4 _ _ _ _) ⟨a2 ,⟨a1, a5⟩⟩
fe4cd49170c599870246883cb3f26c3ab63b7c1f
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/omega/main.lean
5a0802130d59f726fef939cc2dd35397fb16053b
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
1,328
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.omega.int.main import Mathlib.tactic.omega.nat.main import Mathlib.PostPort namespace Mathlib /- A tactic for discharging linear integer & natural number arithmetic goals using the Omega test. -/ namespace omega /-- Detects domain of a formula from its expr. * Returns none, if domain can be either ℤ or ℕ * Returns some tt, if domain is exclusively ℤ * Returns some ff, if domain is exclusively ℕ * Fails, if domain is neither ℤ nor ℕ -/ /-- Use the current goal to determine. Return tt if the domain is ℤ, and return ff if it is ℕ -/ /-- Return tt if the domain is ℤ, and return ff if it is ℕ -/ end omega /-- Attempts to discharge goals in the quantifier-free fragment of linear integer and natural number arithmetic using the Omega test. Guesses the correct domain by looking at the goal and hypotheses, and then reverts all relevant hypotheses and variables. Use `omega manual` to disable automatic reverts, and `omega int` or `omega nat` to specify the domain. -/ /-- `omega` attempts to discharge goals in the quantifier-free fragment of linear integer and natural
8871cafcf6a94c4b5ec321cca30a0e0f0022a781
626e312b5c1cb2d88fca108f5933076012633192
/src/linear_algebra/dimension.lean
8ec3395d7bb8f2a14bbdaab61e9f9f7f37d4e780
[ "Apache-2.0" ]
permissive
Bioye97/mathlib
9db2f9ee54418d29dd06996279ba9dc874fd6beb
782a20a27ee83b523f801ff34efb1a9557085019
refs/heads/master
1,690,305,956,488
1,631,067,774,000
1,631,067,774,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
48,778
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johannes Hölzl, Sander Dahmen, Scott Morrison -/ import linear_algebra.basis import linear_algebra.std_basis import set_theory.cofinality import linear_algebra.invariant_basis_number /-! # Dimension of modules and vector spaces ## Main definitions * The rank of a module is defined as `module.rank : cardinal`. This is defined as the supremum of the cardinalities of linearly independent subsets. * The rank of a linear map is defined as the rank of its range. ## Main statements * `linear_map.dim_le_of_injective`: the source of an injective linear map has dimension at most that of the target. * `linear_map.dim_le_of_surjective`: the target of a surjective linear map has dimension at most that of that source. * `basis_fintype_of_finite_spans`: the existence of a finite spanning set implies that any basis is finite. * `infinite_basis_le_maximal_linear_independent`: if `b` is an infinite basis for a module `M`, and `s` is a maximal linearly independent set, then the cardinality of `b` is bounded by the cardinality of `s`. For modules over rings satisfying the rank condition * `basis.le_span`: the cardinality of a basis is bounded by the cardinality of any spanning set For modules over rings satisfying the strong rank condition * `linear_independent_le_span`: For any linearly independent family `v : ι → M` and any finite spanning set `w : set M`, the cardinality of `ι` is bounded by the cardinality of `w`. * `linear_independent_le_basis`: If `b` is a basis for a module `M`, and `s` is a linearly independent set, then the cardinality of `s` is bounded by the cardinality of `b`. For modules over rings with invariant basis number (including all commutative rings and all noetherian rings) * `mk_eq_mk_of_basis`: the dimension theorem, any two bases of the same vector space have the same cardinality. For vector spaces (i.e. modules over a field), we have * `dim_quotient_add_dim`: if `V₁` is a submodule of `V`, then `module.rank (V/V₁) + module.rank V₁ = module.rank V`. * `dim_range_add_dim_ker`: the rank-nullity theorem. ## Implementation notes There is a naming discrepancy: most of the theorem names refer to `dim`, even though the definition is of `module.rank`. This reflects that `module.rank` was originally called `dim`, and only defined for vector spaces. Many theorems in this file are not universe-generic when they relate dimensions in different universes. They should be as general as they can be without inserting `lift`s. The types `V`, `V'`, ... all live in different universes, and `V₁`, `V₂`, ... all live in the same universe. -/ noncomputable theory universes u v v' v'' u₁' w w' variables {K : Type u} {V V₁ V₂ V₃ : Type v} {V' V'₁ : Type v'} {V'' : Type v''} variables {ι : Type w} {ι' : Type w'} {η : Type u₁'} {φ : η → Type*} open_locale classical big_operators open basis submodule function set section module section variables [semiring K] [add_comm_monoid V] [module K V] include K variables (K V) /-- The rank of a module, defined as a term of type `cardinal`. We define this as the supremum of the cardinalities of linearly independent subsets. For a free module over any ring satisfying the strong rank condition (e.g. left-noetherian rings, commutative rings, and in particular division rings and fields), this is the same as the dimension of the space (i.e. the cardinality of any basis). In particular this agrees with the usual notion of the dimension of a vector space. The definition is marked as protected to avoid conflicts with `_root_.rank`, the rank of a linear map. -/ protected def module.rank : cardinal := cardinal.sup.{v v} (λ ι : {s : set V // linear_independent K (coe : s → V)}, cardinal.mk ι.1) end section variables {R : Type u} [ring R] variables {M : Type v} [add_comm_group M] [module R M] variables {M' : Type v'} [add_comm_group M'] [module R M'] variables {M₁ : Type v} [add_comm_group M₁] [module R M₁] theorem linear_map.lift_dim_le_of_injective (f : M →ₗ[R] M') (i : injective f) : cardinal.lift.{v v'} (module.rank R M) ≤ cardinal.lift.{v' v} (module.rank R M') := begin dsimp [module.rank], fapply cardinal.lift_sup_le_lift_sup', { rintro ⟨s, li⟩, use f '' s, convert (li.map' f (linear_map.ker_eq_bot.mpr i)).comp (equiv.set.image ⇑f s i).symm (equiv.injective _), ext ⟨-, ⟨x, ⟨h, rfl⟩⟩⟩, simp, }, { rintro ⟨s, li⟩, exact cardinal.lift_mk_le'.mpr ⟨(equiv.set.image f s i).to_embedding⟩, } end theorem linear_map.dim_le_of_injective (f : M →ₗ[R] M₁) (i : injective f) : module.rank R M ≤ module.rank R M₁ := cardinal.lift_le.1 (f.lift_dim_le_of_injective i) theorem dim_le {n : ℕ} (H : ∀ s : finset M, linear_independent R (λ i : s, (i : M)) → s.card ≤ n) : module.rank R M ≤ n := begin apply cardinal.sup_le.mpr, rintro ⟨s, li⟩, exact linear_independent_bounded_of_finset_linear_independent_bounded H _ li, end lemma lift_dim_range_le (f : M →ₗ[R] M') : cardinal.lift.{v' v} (module.rank R f.range) ≤ cardinal.lift.{v v'} (module.rank R M) := begin dsimp [module.rank], apply cardinal.lift_sup_le, rintro ⟨s, li⟩, apply le_trans, swap 2, apply cardinal.lift_le.mpr, refine (cardinal.le_sup _ ⟨range_splitting f '' s, _⟩), { apply linear_independent.of_comp f.range_restrict, convert li.comp (equiv.set.range_splitting_image_equiv f s) (equiv.injective _) using 1, }, { exact (cardinal.lift_mk_eq'.mpr ⟨equiv.set.range_splitting_image_equiv f s⟩).ge, }, end lemma dim_range_le (f : M →ₗ[R] M₁) : module.rank R f.range ≤ module.rank R M := by simpa using lift_dim_range_le f lemma lift_dim_map_le (f : M →ₗ[R] M') (p : submodule R M) : cardinal.lift.{v' v} (module.rank R (p.map f)) ≤ cardinal.lift.{v v'} (module.rank R p) := begin have h := lift_dim_range_le (f.comp (submodule.subtype p)), rwa [linear_map.range_comp, range_subtype] at h, end lemma dim_map_le (f : M →ₗ[R] M₁) (p : submodule R M) : module.rank R (p.map f) ≤ module.rank R p := by simpa using lift_dim_map_le f p lemma dim_le_of_submodule (s t : submodule R M) (h : s ≤ t) : module.rank R s ≤ module.rank R t := (of_le h).dim_le_of_injective $ assume ⟨x, hx⟩ ⟨y, hy⟩ eq, subtype.eq $ show x = y, from subtype.ext_iff_val.1 eq /-- Two linearly equivalent vector spaces have the same dimension, a version with different universes. -/ theorem linear_equiv.lift_dim_eq (f : M ≃ₗ[R] M') : cardinal.lift.{v v'} (module.rank R M) = cardinal.lift.{v' v} (module.rank R M') := begin apply le_antisymm, { exact f.to_linear_map.lift_dim_le_of_injective f.injective, }, { exact f.symm.to_linear_map.lift_dim_le_of_injective f.symm.injective, }, end /-- Two linearly equivalent vector spaces have the same dimension. -/ theorem linear_equiv.dim_eq (f : M ≃ₗ[R] M₁) : module.rank R M = module.rank R M₁ := cardinal.lift_inj.1 f.lift_dim_eq lemma dim_eq_of_injective (f : M →ₗ[R] M₁) (h : injective f) : module.rank R M = module.rank R f.range := (linear_equiv.of_injective f (linear_map.ker_eq_bot.mpr h)).dim_eq /-- Pushforwards of submodules along a `linear_equiv` have the same dimension. -/ lemma linear_equiv.dim_map_eq (f : M ≃ₗ[R] M₁) (p : submodule R M) : module.rank R (p.map (f : M →ₗ[R] M₁)) = module.rank R p := (f.of_submodule p).dim_eq.symm variables (R M) @[simp] lemma dim_top : module.rank R (⊤ : submodule R M) = module.rank R M := begin have : (⊤ : submodule R M) ≃ₗ[R] M := linear_equiv.of_top ⊤ rfl, rw this.dim_eq, end variables {R M} lemma dim_range_of_surjective (f : M →ₗ[R] M') (h : surjective f) : module.rank R f.range = module.rank R M' := by rw [linear_map.range_eq_top.2 h, dim_top] lemma dim_submodule_le (s : submodule R M) : module.rank R s ≤ module.rank R M := begin rw ←dim_top R M, exact dim_le_of_submodule _ _ le_top, end lemma linear_map.dim_le_of_surjective (f : M →ₗ[R] M₁) (h : surjective f) : module.rank R M₁ ≤ module.rank R M := begin rw ←dim_range_of_surjective f h, apply dim_range_le, end theorem dim_quotient_le (p : submodule R M) : module.rank R p.quotient ≤ module.rank R M := (mkq p).dim_le_of_surjective (surjective_quot_mk _) variables [nontrivial R] lemma {m} cardinal_lift_le_dim_of_linear_independent {ι : Type w} {v : ι → M} (hv : linear_independent R v) : cardinal.lift.{w (max v m)} (cardinal.mk ι) ≤ cardinal.lift.{v (max w m)} (module.rank R M) := begin apply le_trans, { exact cardinal.lift_mk_le.mpr ⟨(equiv.of_injective _ hv.injective).to_embedding⟩, }, { simp only [cardinal.lift_le], apply le_trans, swap, exact cardinal.le_sup _ ⟨range v, hv.coe_range⟩, exact le_refl _, }, end lemma cardinal_le_dim_of_linear_independent {ι : Type v} {v : ι → M} (hv : linear_independent R v) : cardinal.mk ι ≤ module.rank R M := by simpa using cardinal_lift_le_dim_of_linear_independent hv lemma cardinal_le_dim_of_linear_independent' {s : set M} (hs : linear_independent R (λ x, x : s → M)) : cardinal.mk s ≤ module.rank R M := cardinal_le_dim_of_linear_independent hs variables (R M) @[simp] lemma dim_punit : module.rank R punit = 0 := begin apply le_bot_iff.mp, apply cardinal.sup_le.mpr, rintro ⟨s, li⟩, apply le_bot_iff.mpr, apply cardinal.mk_emptyc_iff.mpr, simp only [subtype.coe_mk], by_contradiction h, have ne : s.nonempty := ne_empty_iff_nonempty.mp h, simpa using linear_independent.ne_zero (⟨_, ne.some_mem⟩ : s) li, end @[simp] lemma dim_bot : module.rank R (⊥ : submodule R M) = 0 := begin have : (⊥ : submodule R M) ≃ₗ[R] punit := bot_equiv_punit, rw [this.dim_eq, dim_punit], end variables {R M} /-- Over any nontrivial ring, the existence of a finite spanning set implies that any basis is finite. -/ -- One might hope that a finite spanning set implies that any linearly independent set is finite. -- While this is true over a division ring -- (simply because any linearly independent set can be extended to a basis), -- I'm not certain what more general statements are possible. def basis_fintype_of_finite_spans (w : set M) [fintype w] (s : span R w = ⊤) {ι : Type w} (b : basis ι R M) : fintype ι := begin -- We'll work by contradiction, assuming `ι` is infinite. apply fintype_of_not_infinite _, introI i, -- Let `S` be the union of the supports of `x ∈ w` expressed as linear combinations of `b`. -- This is a finite set since `w` is finite. let S : finset ι := finset.univ.sup (λ x : w, (b.repr x).support), let bS : set M := b '' S, have h : ∀ x ∈ w, x ∈ span R bS, { intros x m, rw [←b.total_repr x, finsupp.span_image_eq_map_total, submodule.mem_map], use b.repr x, simp only [and_true, eq_self_iff_true, finsupp.mem_supported], change (b.repr x).support ≤ S, convert (finset.le_sup (by simp : (⟨x, m⟩ : w) ∈ finset.univ)), refl, }, -- Thus this finite subset of the basis elements spans the entire module. have k : span R bS = ⊤ := eq_top_iff.2 (le_trans s.ge (span_le.2 h)), -- Now there is some `x : ι` not in `S`, since `ι` is infinite. obtain ⟨x, nm⟩ := infinite.exists_not_mem_finset S, -- However it must be in the span of the finite subset, have k' : b x ∈ span R bS, { rw k, exact mem_top, }, -- giving the desire contradiction. refine b.linear_independent.not_mem_span_image _ k', exact nm, end /-- Over any ring `R`, if `b` is a basis for a module `M`, and `s` is a maximal linearly independent set, then the union of the supports of `x ∈ s` (when written out in the basis `b`) is all of `b`. -/ -- From [Les familles libres maximales d'un module ont-elles le meme cardinal?][lazarus1973] lemma union_support_maximal_linear_independent_eq_range_basis {ι : Type w} (b : basis ι R M) {κ : Type w'} (v : κ → M) (i : linear_independent R v) (m : i.maximal) : (⋃ k, ((b.repr (v k)).support : set ι)) = univ := begin -- If that's not the case, by_contradiction h, simp only [←ne.def, ne_univ_iff_exists_not_mem, mem_Union, not_exists_not, finsupp.mem_support_iff, finset.mem_coe] at h, -- We have some basis element `b b'` which is not in the support of any of the `v i`. obtain ⟨b', w⟩ := h, -- Using this, we'll construct a linearly independent family strictly larger than `v`, -- by also using this `b b'`. let v' : option κ → M := λ o, o.elim (b b') v, have r : range v ⊆ range v', { rintro - ⟨k, rfl⟩, use some k, refl, }, have r' : b b' ∉ range v, { rintro ⟨k, p⟩, simpa [w] using congr_arg (λ m, (b.repr m) b') p, }, have r'' : range v ≠ range v', { intro e, have p : b b' ∈ range v', { use none, refl, }, rw ←e at p, exact r' p, }, have inj' : injective v', { rintros (_|k) (_|k) z, { refl, }, { exfalso, exact r' ⟨k, z.symm⟩, }, { exfalso, exact r' ⟨k, z⟩, }, { congr, exact i.injective z, }, }, -- The key step in the proof is checking that this strictly larger family is linearly independent. have i' : linear_independent R (coe : range v' → M), { rw [linear_independent_subtype_range inj', linear_independent_iff], intros l z, rw [finsupp.total_option] at z, simp only [v', option.elim] at z, change _ + finsupp.total κ M R v l.some = 0 at z, -- We have some linear combination of `b b'` and the `v i`, which we want to show is trivial. -- We'll first show the coefficient of `b b'` is zero, -- by expressing the `v i` in the basis `b`, and using that the `v i` have no `b b'` term. have l₀ : l none = 0, { rw ←eq_neg_iff_add_eq_zero at z, replace z := eq_neg_of_eq_neg z, apply_fun (λ x, b.repr x b') at z, simp only [repr_self, linear_equiv.map_smul, mul_one, finsupp.single_eq_same, pi.neg_apply, finsupp.smul_single', linear_equiv.map_neg, finsupp.coe_neg] at z, erw finsupp.congr_fun (finsupp.apply_total R (b.repr : M →ₗ[R] ι →₀ R) v l.some) b' at z, simpa [finsupp.total_apply, w] using z, }, -- Then all the other coefficients are zero, because `v` is linear independent. have l₁ : l.some = 0, { rw [l₀, zero_smul, zero_add] at z, exact linear_independent_iff.mp i _ z, }, -- Finally we put those facts together to show the linear combination is trivial. ext (_|a), { simp only [l₀, finsupp.coe_zero, pi.zero_apply], }, { erw finsupp.congr_fun l₁ a, simp only [finsupp.coe_zero, pi.zero_apply], }, }, dsimp [linear_independent.maximal] at m, specialize m (range v') i' r, exact r'' m, end /-- Over any ring `R`, if `b` is an infinite basis for a module `M`, and `s` is a maximal linearly independent set, then the cardinality of `b` is bounded by the cardinality of `s`. -/ lemma infinite_basis_le_maximal_linear_independent' {ι : Type w} (b : basis ι R M) [infinite ι] {κ : Type w'} (v : κ → M) (i : linear_independent R v) (m : i.maximal) : cardinal.lift.{w w'} (cardinal.mk ι) ≤ cardinal.lift.{w' w} (cardinal.mk κ) := begin let Φ := λ k : κ, (b.repr (v k)).support, have w₁ : cardinal.mk ι ≤ cardinal.mk (set.range Φ), { apply cardinal.le_range_of_union_finset_eq_top, exact union_support_maximal_linear_independent_eq_range_basis b v i m, }, have w₂ : cardinal.lift.{w w'} (cardinal.mk (set.range Φ)) ≤ cardinal.lift.{w' w} (cardinal.mk κ) := cardinal.mk_range_le_lift, exact (cardinal.lift_le.mpr w₁).trans w₂, end /-- Over any ring `R`, if `b` is an infinite basis for a module `M`, and `s` is a maximal linearly independent set, then the cardinality of `b` is bounded by the cardinality of `s`. -/ -- (See `infinite_basis_le_maximal_linear_independent'` for the more general version -- where the index types can live in different universes.) lemma infinite_basis_le_maximal_linear_independent {ι : Type w} (b : basis ι R M) [infinite ι] {κ : Type w} (v : κ → M) (i : linear_independent R v) (m : i.maximal) : cardinal.mk ι ≤ cardinal.mk κ := cardinal.lift_le.mp (infinite_basis_le_maximal_linear_independent' b v i m) end section invariant_basis_number variables {R : Type u} [ring R] [nontrivial R] [invariant_basis_number R] variables {M : Type v} [add_comm_group M] [module R M] /-- The dimension theorem: if `v` and `v'` are two bases, their index types have the same cardinalities. -/ theorem mk_eq_mk_of_basis (v : basis ι R M) (v' : basis ι' R M) : cardinal.lift.{w w'} (cardinal.mk ι) = cardinal.lift.{w' w} (cardinal.mk ι') := begin by_cases h : cardinal.mk ι < cardinal.omega, { -- `v` is a finite basis, so by `basis_fintype_of_finite_spans` so is `v'`. haveI : fintype ι := (cardinal.lt_omega_iff_fintype.mp h).some, haveI : fintype (range v) := set.fintype_range ⇑v, haveI := basis_fintype_of_finite_spans _ v.span_eq v', -- We clean up a little: rw [cardinal.fintype_card, cardinal.fintype_card], simp only [cardinal.lift_nat_cast, cardinal.nat_cast_inj], -- Now we can use invariant basis number to show they have the same cardinality. apply card_eq_of_lequiv R, exact (((finsupp.linear_equiv_fun_on_fintype R R ι).symm.trans v.repr.symm) ≪≫ₗ v'.repr) ≪≫ₗ (finsupp.linear_equiv_fun_on_fintype R R ι'), }, { -- `v` is an infinite basis, -- so by `infinite_basis_le_maximal_linear_independent`, `v'` is at least as big, -- and then applying `infinite_basis_le_maximal_linear_independent` again -- we see they have the same cardinality. simp only [not_lt] at h, haveI : infinite ι := cardinal.infinite_iff.mpr h, have w₁ := infinite_basis_le_maximal_linear_independent' v _ v'.linear_independent v'.maximal, haveI : infinite ι' := cardinal.infinite_iff.mpr (begin apply cardinal.lift_le.{w' w}.mp, have p := (cardinal.lift_le.mpr h).trans w₁, rw cardinal.lift_omega at ⊢ p, exact p, end), have w₂ := infinite_basis_le_maximal_linear_independent' v' _ v.linear_independent v.maximal, exact le_antisymm w₁ w₂, } end theorem mk_eq_mk_of_basis' {ι' : Type w} (v : basis ι R M) (v' : basis ι' R M) : cardinal.mk ι = cardinal.mk ι' := cardinal.lift_inj.1 $ mk_eq_mk_of_basis v v' end invariant_basis_number section rank_condition variables {R : Type u} [ring R] [rank_condition R] variables {M : Type v} [add_comm_group M] [module R M] /-- An auxiliary lemma for `basis.le_span`. If `R` satisfies the rank condition, then for any finite basis `b : basis ι R M`, and any finite spanning set `w : set M`, the cardinality of `ι` is bounded by the cardinality of `w`. -/ lemma basis.le_span'' {ι : Type*} [fintype ι] (b : basis ι R M) {w : set M} [fintype w] (s : span R w = ⊤) : fintype.card ι ≤ fintype.card w := begin -- We construct an surjective linear map `(w → R) →ₗ[R] (ι → R)`, -- by expressing a linear combination in `w` as a linear combination in `ι`. fapply card_le_of_surjective' R, { exact b.repr.to_linear_map.comp (finsupp.total w M R coe), }, { apply surjective.comp, apply linear_equiv.surjective, rw [←linear_map.range_eq_top, finsupp.range_total], simpa using s, }, end variables [nontrivial R] /-- Another auxiliary lemma for `basis.le_span`, which does not require assuming the basis is finite, but still assumes we have a finite spanning set. -/ lemma basis_le_span' {ι : Type*} (b : basis ι R M) {w : set M} [fintype w] (s : span R w = ⊤) : cardinal.mk ι ≤ fintype.card w := begin haveI := basis_fintype_of_finite_spans w s b, rw cardinal.fintype_card ι, simp only [cardinal.nat_cast_le], exact basis.le_span'' b s, end /-- If `R` satisfies the rank condition, then the cardinality of any basis is bounded by the cardinality of any spanning set. -/ -- Note that if `R` satisfies the strong rank condition, -- this also follows from `linear_independent_le_span` below. theorem basis.le_span {J : set M} (v : basis ι R M) (hJ : span R J = ⊤) : cardinal.mk (range v) ≤ cardinal.mk J := begin cases le_or_lt cardinal.omega (cardinal.mk J) with oJ oJ, { have := cardinal.mk_range_eq_of_injective v.injective, let S : J → set ι := λ j, ↑(v.repr j).support, let S' : J → set M := λ j, v '' S j, have hs : range v ⊆ ⋃ j, S' j, { intros b hb, rcases mem_range.1 hb with ⟨i, hi⟩, have : span R J ≤ comap v.repr.to_linear_map (finsupp.supported R R (⋃ j, S j)) := span_le.2 (λ j hj x hx, ⟨_, ⟨⟨j, hj⟩, rfl⟩, hx⟩), rw hJ at this, replace : v.repr (v i) ∈ (finsupp.supported R R (⋃ j, S j)) := this trivial, rw [v.repr_self, finsupp.mem_supported, finsupp.support_single_ne_zero one_ne_zero] at this, { subst b, rcases mem_Union.1 (this (finset.mem_singleton_self _)) with ⟨j, hj⟩, exact mem_Union.2 ⟨j, (mem_image _ _ _).2 ⟨i, hj, rfl⟩⟩ }, { apply_instance } }, refine le_of_not_lt (λ IJ, _), suffices : cardinal.mk (⋃ j, S' j) < cardinal.mk (range v), { exact not_le_of_lt this ⟨set.embedding_of_subset _ _ hs⟩ }, refine lt_of_le_of_lt (le_trans cardinal.mk_Union_le_sum_mk (cardinal.sum_le_sum _ (λ _, cardinal.omega) _)) _, { exact λ j, le_of_lt (cardinal.lt_omega_iff_finite.2 $ (finset.finite_to_set _).image _) }, { rwa [cardinal.sum_const, cardinal.mul_eq_max oJ (le_refl _), max_eq_left oJ] } }, { haveI : fintype J := (cardinal.lt_omega_iff_fintype.mp oJ).some, rw [←cardinal.lift_le, cardinal.mk_range_eq_of_injective v.injective, cardinal.fintype_card J], convert cardinal.lift_le.{w v}.2 (basis_le_span' v hJ), simp, }, end end rank_condition section strong_rank_condition variables {R : Type u} [ring R] [strong_rank_condition R] variables {M : Type v} [add_comm_group M] [module R M] open submodule -- An auxiliary lemma for `linear_independent_le_span'`, -- with the additional assumption that the linearly independent family is finite. lemma linear_independent_le_span_aux' {ι : Type*} [fintype ι] (v : ι → M) (i : linear_independent R v) (w : set M) [fintype w] (s : range v ≤ span R w) : fintype.card ι ≤ fintype.card w := begin -- We construct an injective linear map `(ι → R) →ₗ[R] (w → R)`, -- by thinking of `f : ι → R` as a linear combination of the finite family `v`, -- and expressing that (using the axiom of choice) as a linear combination over `w`. -- We can do this linearly by constructing the map on a basis. fapply card_le_of_injective' R, { apply finsupp.total, exact λ i, span.repr R w ⟨v i, s (mem_range_self i)⟩, }, { intros f g h, apply_fun finsupp.total w M R coe at h, simp only [finsupp.total_total, submodule.coe_mk, span.finsupp_total_repr] at h, rw [←sub_eq_zero, ←linear_map.map_sub] at h, exact sub_eq_zero.mp (linear_independent_iff.mp i _ h), }, end /-- If `R` satisfies the strong rank condition, then any linearly independent family `v : ι → M` contained in the span of some finite `w : set M`, is itself finite. -/ def linear_independent_fintype_of_le_span_fintype {ι : Type*} (v : ι → M) (i : linear_independent R v) (w : set M) [fintype w] (s : range v ≤ span R w) : fintype ι := fintype_of_finset_card_le (fintype.card w) (λ t, begin let v' := λ x : (t : set ι), v x, have i' : linear_independent R v' := i.comp _ subtype.val_injective, have s' : range v' ≤ span R w := (range_comp_subset_range _ _).trans s, simpa using linear_independent_le_span_aux' v' i' w s', end) /-- If `R` satisfies the strong rank condition, then for any linearly independent family `v : ι → M` contained in the span of some finite `w : set M`, the cardinality of `ι` is bounded by the cardinality of `w`. -/ lemma linear_independent_le_span' {ι : Type*} (v : ι → M) (i : linear_independent R v) (w : set M) [fintype w] (s : range v ≤ span R w) : cardinal.mk ι ≤ fintype.card w := begin haveI : fintype ι := linear_independent_fintype_of_le_span_fintype v i w s, rw cardinal.fintype_card, simp only [cardinal.nat_cast_le], exact linear_independent_le_span_aux' v i w s, end /-- If `R` satisfies the strong rank condition, then for any linearly independent family `v : ι → M` and any finite spanning set `w : set M`, the cardinality of `ι` is bounded by the cardinality of `w`. -/ lemma linear_independent_le_span {ι : Type*} (v : ι → M) (i : linear_independent R v) (w : set M) [fintype w] (s : span R w = ⊤) : cardinal.mk ι ≤ fintype.card w := begin apply linear_independent_le_span' v i w, rw s, exact le_top, end /-- An auxiliary lemma for `linear_independent_le_basis`: we handle the case where the basis `b` is infinite. -/ lemma linear_independent_le_infinite_basis {ι : Type*} (b : basis ι R M) [infinite ι] {κ : Type*} (v : κ → M) (i : linear_independent R v) : cardinal.mk κ ≤ cardinal.mk ι := begin by_contradiction, simp only [not_le] at h, have w : cardinal.mk (finset ι) = cardinal.mk ι := cardinal.mk_finset_eq_mk (cardinal.infinite_iff.mp ‹infinite ι›), rw ←w at h, let Φ := λ k : κ, (b.repr (v k)).support, obtain ⟨s, w : infinite ↥(Φ ⁻¹' {s})⟩ := cardinal.exists_infinite_fiber Φ h (by { rw [cardinal.infinite_iff, w], exact (cardinal.infinite_iff.mp ‹infinite ι›), }), let v' := λ k : Φ ⁻¹' {s}, v k, have i' : linear_independent R v' := i.comp _ subtype.val_injective, have w' : fintype (Φ ⁻¹' {s}), { apply linear_independent_fintype_of_le_span_fintype v' i' (s.image b), rintros m ⟨⟨p,⟨rfl⟩⟩,rfl⟩, simp only [set_like.mem_coe, subtype.coe_mk, finset.coe_image], apply basis.mem_span_repr_support, }, exactI w.false, end /-- Over any ring `R` satisfying the strong rank condition, if `b` is a basis for a module `M`, and `s` is a linearly independent set, then the cardinality of `s` is bounded by the cardinality of `b`. -/ lemma linear_independent_le_basis {ι : Type*} (b : basis ι R M) {κ : Type*} (v : κ → M) (i : linear_independent R v) : cardinal.mk κ ≤ cardinal.mk ι := begin -- We split into cases depending on whether `ι` is infinite. cases fintype_or_infinite ι; resetI, { -- When `ι` is finite, we have `linear_independent_le_span`, rw cardinal.fintype_card ι, haveI : nontrivial R := nontrivial_of_invariant_basis_number R, rw fintype.card_congr (equiv.of_injective b b.injective), exact linear_independent_le_span v i (range b) b.span_eq, }, { -- and otherwise we have `linear_indepedent_le_infinite_basis`. exact linear_independent_le_infinite_basis b v i, }, end /-- Over any ring `R` satisfying the strong rank condition, if `b` is an infinite basis for a module `M`, then every maximal linearly independent set has the same cardinality as `b`. This proof (along with some of the lemmas above) comes from [Les familles libres maximales d'un module ont-elles le meme cardinal?][lazarus1973] -/ -- When the basis is not infinite this need not be true! lemma maximal_linear_independent_eq_infinite_basis {ι : Type*} (b : basis ι R M) [infinite ι] {κ : Type*} (v : κ → M) (i : linear_independent R v) (m : i.maximal) : cardinal.mk κ = cardinal.mk ι := begin apply le_antisymm, { exact linear_independent_le_basis b v i, }, { haveI : nontrivial R := nontrivial_of_invariant_basis_number R, exact infinite_basis_le_maximal_linear_independent b v i m, } end variables [nontrivial R] theorem basis.mk_eq_dim'' {ι : Type v} (v : basis ι R M) : cardinal.mk ι = module.rank R M := begin apply le_antisymm, { transitivity, swap, apply cardinal.le_sup, exact ⟨set.range v, by { convert v.reindex_range.linear_independent, ext, simp }⟩, exact (cardinal.eq_congr (equiv.of_injective v v.injective)).le, }, { apply cardinal.sup_le.mpr, rintro ⟨s, li⟩, apply linear_independent_le_basis v _ li, }, end -- By this stage we want to have a complete API for `module.rank`, -- so we set it `irreducible` here, to keep ourselves honest. attribute [irreducible] module.rank theorem basis.mk_range_eq_dim (v : basis ι R M) : cardinal.mk (range v) = module.rank R M := v.reindex_range.mk_eq_dim'' /-- If a vector space has a finite basis, then its dimension (seen as a cardinal) is equal to the cardinality of the basis. -/ lemma dim_eq_card_basis {ι : Type w} [fintype ι] (h : basis ι R M) : module.rank R M = fintype.card ι := by rw [←h.mk_range_eq_dim, cardinal.fintype_card, set.card_range_of_injective h.injective] theorem basis.mk_eq_dim (v : basis ι R M) : cardinal.lift.{w v} (cardinal.mk ι) = cardinal.lift.{v w} (module.rank R M) := by rw [←v.mk_range_eq_dim, cardinal.mk_range_eq_of_injective v.injective] theorem {m} basis.mk_eq_dim' (v : basis ι R M) : cardinal.lift.{w (max v m)} (cardinal.mk ι) = cardinal.lift.{v (max w m)} (module.rank R M) := by simpa using v.mk_eq_dim /-- If a module has a finite dimension, all bases are indexed by a finite type. -/ lemma basis.nonempty_fintype_index_of_dim_lt_omega {ι : Type*} (b : basis ι R M) (h : module.rank R M < cardinal.omega) : nonempty (fintype ι) := by rwa [← cardinal.lift_lt, ← b.mk_eq_dim, -- ensure `omega` has the correct universe cardinal.lift_omega, ← cardinal.lift_omega.{u_1 v}, cardinal.lift_lt, cardinal.lt_omega_iff_fintype] at h /-- If a module has a finite dimension, all bases are indexed by a finite type. -/ noncomputable def basis.fintype_index_of_dim_lt_omega {ι : Type*} (b : basis ι R M) (h : module.rank R M < cardinal.omega) : fintype ι := classical.choice (b.nonempty_fintype_index_of_dim_lt_omega h) /-- If a module has a finite dimension, all bases are indexed by a finite set. -/ lemma basis.finite_index_of_dim_lt_omega {ι : Type*} {s : set ι} (b : basis s R M) (h : module.rank R M < cardinal.omega) : s.finite := b.nonempty_fintype_index_of_dim_lt_omega h lemma dim_span {v : ι → M} (hv : linear_independent R v) : module.rank R ↥(span R (range v)) = cardinal.mk (range v) := by rw [←cardinal.lift_inj, ← (basis.span hv).mk_eq_dim, cardinal.mk_range_eq_of_injective (@linear_independent.injective ι R M v _ _ _ _ hv)] lemma dim_span_set {s : set M} (hs : linear_independent R (λ x, x : s → M)) : module.rank R ↥(span R s) = cardinal.mk s := by { rw [← @set_of_mem_eq _ s, ← subtype.range_coe_subtype], exact dim_span hs } variables (R) lemma dim_self : module.rank R R = 1 := by rw [←cardinal.lift_inj, ← (basis.singleton punit R).mk_eq_dim, cardinal.mk_punit] end strong_rank_condition section division_ring variables [division_ring K] [add_comm_group V] [module K V] [add_comm_group V₁] [module K V₁] variables {K V} /-- If a vector space has a finite dimension, the index set of `basis.of_vector_space` is finite. -/ lemma basis.finite_of_vector_space_index_of_dim_lt_omega (h : module.rank K V < cardinal.omega) : (basis.of_vector_space_index K V).finite := (basis.of_vector_space K V).nonempty_fintype_index_of_dim_lt_omega h variables [add_comm_group V'] [module K V'] /-- Two vector spaces are isomorphic if they have the same dimension. -/ theorem nonempty_linear_equiv_of_lift_dim_eq (cond : cardinal.lift.{v v'} (module.rank K V) = cardinal.lift.{v' v} (module.rank K V')) : nonempty (V ≃ₗ[K] V') := begin let B := basis.of_vector_space K V, let B' := basis.of_vector_space K V', have : cardinal.lift.{v v'} (cardinal.mk _) = cardinal.lift.{v' v} (cardinal.mk _), by rw [B.mk_eq_dim'', cond, B'.mk_eq_dim''], exact (cardinal.lift_mk_eq.{v v' 0}.1 this).map (B.equiv B') end /-- Two vector spaces are isomorphic if they have the same dimension. -/ theorem nonempty_linear_equiv_of_dim_eq (cond : module.rank K V = module.rank K V₁) : nonempty (V ≃ₗ[K] V₁) := nonempty_linear_equiv_of_lift_dim_eq $ congr_arg _ cond section variables (V V' V₁) /-- Two vector spaces are isomorphic if they have the same dimension. -/ def linear_equiv.of_lift_dim_eq (cond : cardinal.lift.{v v'} (module.rank K V) = cardinal.lift.{v' v} (module.rank K V')) : V ≃ₗ[K] V' := classical.choice (nonempty_linear_equiv_of_lift_dim_eq cond) /-- Two vector spaces are isomorphic if they have the same dimension. -/ def linear_equiv.of_dim_eq (cond : module.rank K V = module.rank K V₁) : V ≃ₗ[K] V₁ := classical.choice (nonempty_linear_equiv_of_dim_eq cond) end /-- Two vector spaces are isomorphic if and only if they have the same dimension. -/ theorem linear_equiv.nonempty_equiv_iff_lift_dim_eq : nonempty (V ≃ₗ[K] V') ↔ cardinal.lift.{v v'} (module.rank K V) = cardinal.lift.{v' v} (module.rank K V') := ⟨λ ⟨h⟩, linear_equiv.lift_dim_eq h, λ h, nonempty_linear_equiv_of_lift_dim_eq h⟩ /-- Two vector spaces are isomorphic if and only if they have the same dimension. -/ theorem linear_equiv.nonempty_equiv_iff_dim_eq : nonempty (V ≃ₗ[K] V₁) ↔ module.rank K V = module.rank K V₁ := ⟨λ ⟨h⟩, linear_equiv.dim_eq h, λ h, nonempty_linear_equiv_of_dim_eq h⟩ -- TODO how far can we generalise this? -- When `s` is finite, we could prove this for any ring satisfying the strong rank condition -- using `linear_independent_le_span'` lemma dim_span_le (s : set V) : module.rank K (span K s) ≤ cardinal.mk s := begin classical, rcases exists_linear_independent (linear_independent_empty K V) (set.empty_subset s) with ⟨b, hb, _, hsb, hlib⟩, have hsab : span K s = span K b, from span_eq_of_le _ hsb (span_le.2 (λ x hx, subset_span (hb hx))), convert cardinal.mk_le_mk_of_subset hb, rw [hsab, dim_span_set hlib] end lemma dim_span_of_finset (s : finset V) : module.rank K (span K (↑s : set V)) < cardinal.omega := calc module.rank K (span K (↑s : set V)) ≤ cardinal.mk (↑s : set V) : dim_span_le ↑s ... = s.card : by rw [cardinal.finset_card, finset.coe_sort_coe] ... < cardinal.omega : cardinal.nat_lt_omega _ theorem dim_prod : module.rank K (V × V₁) = module.rank K V + module.rank K V₁ := begin let b := basis.of_vector_space K V, let c := basis.of_vector_space K V₁, rw [← cardinal.lift_inj, ← (basis.prod b c).mk_eq_dim, cardinal.lift_add, cardinal.lift_mk, ← b.mk_eq_dim, ← c.mk_eq_dim, cardinal.lift_mk, cardinal.lift_mk, cardinal.add_def (ulift _)], exact cardinal.lift_inj.1 (cardinal.lift_mk_eq.2 ⟨equiv.ulift.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm ⟩), end -- TODO the remainder of this section should generalize beyond division rings. lemma dim_zero_iff_forall_zero : module.rank K V = 0 ↔ ∀ x : V, x = 0 := begin split, { intros h x, have card_mk_range := (basis.of_vector_space K V).mk_range_eq_dim, rw [h, cardinal.mk_emptyc_iff, coe_of_vector_space, subtype.range_coe] at card_mk_range, simpa [card_mk_range] using (of_vector_space K V).mem_span x }, { intro h, have : (⊤ : submodule K V) = ⊥, { ext x, simp [h x] }, rw [←dim_top, this, dim_bot] } end lemma dim_zero_iff : module.rank K V = 0 ↔ subsingleton V := dim_zero_iff_forall_zero.trans (subsingleton_iff_forall_eq 0).symm lemma dim_pos_iff_exists_ne_zero : 0 < module.rank K V ↔ ∃ x : V, x ≠ 0 := begin rw ←not_iff_not, simpa using dim_zero_iff_forall_zero end lemma dim_pos_iff_nontrivial : 0 < module.rank K V ↔ nontrivial V := dim_pos_iff_exists_ne_zero.trans (nontrivial_iff_exists_ne 0).symm lemma dim_pos [h : nontrivial V] : 0 < module.rank K V := dim_pos_iff_nontrivial.2 h section fintype variable [fintype η] variables [∀i, add_comm_group (φ i)] [∀i, module K (φ i)] open linear_map lemma dim_pi : module.rank K (Πi, φ i) = cardinal.sum (λi, module.rank K (φ i)) := begin let b := assume i, basis.of_vector_space K (φ i), let this : basis (Σ j, _) K (Π j, φ j) := pi.basis b, rw [←cardinal.lift_inj, ← this.mk_eq_dim], simp [λ i, (b i).mk_range_eq_dim.symm, cardinal.sum_mk] end lemma dim_fun {V η : Type u} [fintype η] [add_comm_group V] [module K V] : module.rank K (η → V) = fintype.card η * module.rank K V := by rw [dim_pi, cardinal.sum_const, cardinal.fintype_card] lemma dim_fun_eq_lift_mul : module.rank K (η → V) = (fintype.card η : cardinal.{max u₁' v}) * cardinal.lift.{v u₁'} (module.rank K V) := by rw [dim_pi, cardinal.sum_const_eq_lift_mul, cardinal.fintype_card, cardinal.lift_nat_cast] lemma dim_fun' : module.rank K (η → K) = fintype.card η := by rw [dim_fun_eq_lift_mul, dim_self, cardinal.lift_one, mul_one, cardinal.nat_cast_inj] lemma dim_fin_fun (n : ℕ) : module.rank K (fin n → K) = n := by simp [dim_fun'] end fintype end division_ring section field variables [field K] [add_comm_group V] [module K V] [add_comm_group V₁] [module K V₁] variables [add_comm_group V'] [module K V'] variables {K V} theorem dim_quotient_add_dim (p : submodule K V) : module.rank K p.quotient + module.rank K p = module.rank K V := by classical; exact let ⟨f⟩ := quotient_prod_linear_equiv p in dim_prod.symm.trans f.dim_eq /-- rank-nullity theorem -/ theorem dim_range_add_dim_ker (f : V →ₗ[K] V₁) : module.rank K f.range + module.rank K f.ker = module.rank K V := begin haveI := λ (p : submodule K V), classical.dec_eq p.quotient, rw [← f.quot_ker_equiv_range.dim_eq, dim_quotient_add_dim] end lemma dim_eq_of_surjective (f : V →ₗ[K] V₁) (h : surjective f) : module.rank K V = module.rank K V₁ + module.rank K f.ker := by rw [← dim_range_add_dim_ker f, ← dim_range_of_surjective f h] section variables [add_comm_group V₂] [module K V₂] variables [add_comm_group V₃] [module K V₃] open linear_map /-- This is mostly an auxiliary lemma for `dim_sup_add_dim_inf_eq`. -/ lemma dim_add_dim_split (db : V₂ →ₗ[K] V) (eb : V₃ →ₗ[K] V) (cd : V₁ →ₗ[K] V₂) (ce : V₁ →ₗ[K] V₃) (hde : ⊤ ≤ db.range ⊔ eb.range) (hgd : ker cd = ⊥) (eq : db.comp cd = eb.comp ce) (eq₂ : ∀d e, db d = eb e → (∃c, cd c = d ∧ ce c = e)) : module.rank K V + module.rank K V₁ = module.rank K V₂ + module.rank K V₃ := have hf : surjective (coprod db eb), begin refine (range_eq_top.1 $ top_unique $ _), rwa [← map_top, ← prod_top, map_coprod_prod, ←range_eq_map, ←range_eq_map] end, begin conv {to_rhs, rw [← dim_prod, dim_eq_of_surjective _ hf] }, congr' 1, apply linear_equiv.dim_eq, refine linear_equiv.of_bijective _ _ _, { refine cod_restrict _ (prod cd (- ce)) _, { assume c, simp only [add_eq_zero_iff_eq_neg, linear_map.prod_apply, mem_ker, coprod_apply, neg_neg, map_neg, neg_apply], exact linear_map.ext_iff.1 eq c } }, { rw [ker_cod_restrict, ker_prod, hgd, bot_inf_eq] }, { rw [eq_top_iff, range_cod_restrict, ← map_le_iff_le_comap, map_top, range_subtype], rintros ⟨d, e⟩, have h := eq₂ d (-e), simp only [add_eq_zero_iff_eq_neg, linear_map.prod_apply, mem_ker, set_like.mem_coe, prod.mk.inj_iff, coprod_apply, map_neg, neg_apply, linear_map.mem_range] at ⊢ h, assume hde, rcases h hde with ⟨c, h₁, h₂⟩, refine ⟨c, h₁, _⟩, rw [h₂, _root_.neg_neg] } end lemma dim_sup_add_dim_inf_eq (s t : submodule K V) : module.rank K (s ⊔ t : submodule K V) + module.rank K (s ⊓ t : submodule K V) = module.rank K s + module.rank K t := dim_add_dim_split (of_le le_sup_left) (of_le le_sup_right) (of_le inf_le_left) (of_le inf_le_right) begin rw [← map_le_map_iff' (ker_subtype $ s ⊔ t), map_sup, map_top, ← linear_map.range_comp, ← linear_map.range_comp, subtype_comp_of_le, subtype_comp_of_le, range_subtype, range_subtype, range_subtype], exact le_refl _ end (ker_of_le _ _ _) begin ext ⟨x, hx⟩, refl end begin rintros ⟨b₁, hb₁⟩ ⟨b₂, hb₂⟩ eq, have : b₁ = b₂ := congr_arg subtype.val eq, subst this, exact ⟨⟨b₁, hb₁, hb₂⟩, rfl, rfl⟩ end lemma dim_add_le_dim_add_dim (s t : submodule K V) : module.rank K (s ⊔ t : submodule K V) ≤ module.rank K s + module.rank K t := by { rw [← dim_sup_add_dim_inf_eq], exact self_le_add_right _ _ } end lemma exists_mem_ne_zero_of_ne_bot {s : submodule K V} (h : s ≠ ⊥) : ∃ b : V, b ∈ s ∧ b ≠ 0 := begin classical, by_contradiction hex, have : ∀x∈s, (x:V) = 0, { simpa only [not_exists, not_and, not_not, ne.def] using hex }, exact (h $ bot_unique $ assume s hs, (submodule.mem_bot K).2 $ this s hs) end lemma exists_mem_ne_zero_of_dim_pos {s : submodule K V} (h : 0 < module.rank K s) : ∃ b : V, b ∈ s ∧ b ≠ 0 := exists_mem_ne_zero_of_ne_bot $ assume eq, by rw [eq, dim_bot] at h; exact lt_irrefl _ h section rank -- TODO This definition, and some of the results about it, could be generalized to arbitrary rings. /-- `rank f` is the rank of a `linear_map f`, defined as the dimension of `f.range`. -/ def rank (f : V →ₗ[K] V') : cardinal := module.rank K f.range lemma rank_le_domain (f : V →ₗ[K] V₁) : rank f ≤ module.rank K V := by { rw [← dim_range_add_dim_ker f], exact self_le_add_right _ _ } lemma rank_le_range (f : V →ₗ[K] V₁) : rank f ≤ module.rank K V₁ := dim_submodule_le _ lemma rank_add_le (f g : V →ₗ[K] V') : rank (f + g) ≤ rank f + rank g := calc rank (f + g) ≤ module.rank K (f.range ⊔ g.range : submodule K V') : begin refine dim_le_of_submodule _ _ _, exact (linear_map.range_le_iff_comap.2 $ eq_top_iff'.2 $ assume x, show f x + g x ∈ (f.range ⊔ g.range : submodule K V'), from mem_sup.2 ⟨_, ⟨x, rfl⟩, _, ⟨x, rfl⟩, rfl⟩) end ... ≤ rank f + rank g : dim_add_le_dim_add_dim _ _ @[simp] lemma rank_zero : rank (0 : V →ₗ[K] V') = 0 := by rw [rank, linear_map.range_zero, dim_bot] lemma rank_finset_sum_le {η} (s : finset η) (f : η → V →ₗ[K] V') : rank (∑ d in s, f d) ≤ ∑ d in s, rank (f d) := @finset.sum_hom_rel _ _ _ _ _ (λa b, rank a ≤ b) f (λ d, rank (f d)) s (le_of_eq rank_zero) (λ i g c h, le_trans (rank_add_le _ _) (add_le_add_left h _)) variables [add_comm_group V''] [module K V''] lemma rank_comp_le1 (g : V →ₗ[K] V') (f : V' →ₗ[K] V'') : rank (f.comp g) ≤ rank f := begin refine dim_le_of_submodule _ _ _, rw [linear_map.range_comp], exact linear_map.map_le_range, end variables [add_comm_group V'₁] [module K V'₁] lemma rank_comp_le2 (g : V →ₗ[K] V') (f : V' →ₗ[K] V'₁) : rank (f.comp g) ≤ rank g := by rw [rank, rank, linear_map.range_comp]; exact dim_map_le _ _ end rank -- TODO The remainder of this file could be generalized to arbitrary rings. /-- The `ι` indexed basis on `V`, where `ι` is an empty type and `V` is zero-dimensional. See also `finite_dimensional.fin_basis`. -/ def basis.of_dim_eq_zero {ι : Type*} [is_empty ι] (hV : module.rank K V = 0) : basis ι K V := begin haveI : subsingleton V := dim_zero_iff.1 hV, exact basis.empty _ end @[simp] lemma basis.of_dim_eq_zero_apply {ι : Type*} [is_empty ι] (hV : module.rank K V = 0) (i : ι) : basis.of_dim_eq_zero hV i = 0 := rfl lemma le_dim_iff_exists_linear_independent {c : cardinal} : c ≤ module.rank K V ↔ ∃ s : set V, cardinal.mk s = c ∧ linear_independent K (coe : s → V) := begin split, { intro h, let t := basis.of_vector_space K V, rw [← t.mk_eq_dim'', cardinal.le_mk_iff_exists_subset] at h, rcases h with ⟨s, hst, hsc⟩, exact ⟨s, hsc, (of_vector_space_index.linear_independent K V).mono hst⟩ }, { rintro ⟨s, rfl, si⟩, exact cardinal_le_dim_of_linear_independent si } end lemma le_dim_iff_exists_linear_independent_finset {n : ℕ} : ↑n ≤ module.rank K V ↔ ∃ s : finset V, s.card = n ∧ linear_independent K (coe : (s : set V) → V) := begin simp only [le_dim_iff_exists_linear_independent, cardinal.mk_eq_nat_iff_finset], split, { rintro ⟨s, ⟨t, rfl, rfl⟩, si⟩, exact ⟨t, rfl, si⟩ }, { rintro ⟨s, rfl, si⟩, exact ⟨s, ⟨s, rfl, rfl⟩, si⟩ } end lemma le_rank_iff_exists_linear_independent {c : cardinal} {f : V →ₗ[K] V'} : c ≤ rank f ↔ ∃ s : set V, cardinal.lift.{v v'} (cardinal.mk s) = cardinal.lift.{v' v} c ∧ linear_independent K (λ x : s, f x) := begin rcases f.range_restrict.exists_right_inverse_of_surjective f.range_range_restrict with ⟨g, hg⟩, have fg : left_inverse f.range_restrict g, from linear_map.congr_fun hg, refine ⟨λ h, _, _⟩, { rcases le_dim_iff_exists_linear_independent.1 h with ⟨s, rfl, si⟩, refine ⟨g '' s, cardinal.mk_image_eq_lift _ _ fg.injective, _⟩, replace fg : ∀ x, f (g x) = x, by { intro x, convert congr_arg subtype.val (fg x) }, replace si : linear_independent K (λ x : s, f (g x)), by simpa only [fg] using si.map' _ (ker_subtype _), exact si.image_of_comp s g f }, { rintro ⟨s, hsc, si⟩, have : linear_independent K (λ x : s, f.range_restrict x), from linear_independent.of_comp (f.range.subtype) (by convert si), convert cardinal_le_dim_of_linear_independent this.image, rw [← cardinal.lift_inj, ← hsc, cardinal.mk_image_eq_of_inj_on_lift], exact inj_on_iff_injective.2 this.injective } end lemma le_rank_iff_exists_linear_independent_finset {n : ℕ} {f : V →ₗ[K] V'} : ↑n ≤ rank f ↔ ∃ s : finset V, s.card = n ∧ linear_independent K (λ x : (s : set V), f x) := begin simp only [le_rank_iff_exists_linear_independent, cardinal.lift_nat_cast, cardinal.lift_eq_nat_iff, cardinal.mk_eq_nat_iff_finset], split, { rintro ⟨s, ⟨t, rfl, rfl⟩, si⟩, exact ⟨t, rfl, si⟩ }, { rintro ⟨s, rfl, si⟩, exact ⟨s, ⟨s, rfl, rfl⟩, si⟩ } end /-- A vector space has dimension at most `1` if and only if there is a single vector of which all vectors are multiples. -/ lemma dim_le_one_iff : module.rank K V ≤ 1 ↔ ∃ v₀ : V, ∀ v, ∃ r : K, r • v₀ = v := begin let b := basis.of_vector_space K V, split, { intro hd, rw [← b.mk_eq_dim'', cardinal.le_one_iff_subsingleton, subsingleton_coe] at hd, rcases eq_empty_or_nonempty (of_vector_space_index K V) with hb | ⟨⟨v₀, hv₀⟩⟩, { use 0, have h' : ∀ v : V, v = 0, { simpa [hb, submodule.eq_bot_iff] using b.span_eq.symm }, intro v, simp [h' v] }, { use v₀, have h' : (K ∙ v₀) = ⊤, { simpa [hd.eq_singleton_of_mem hv₀] using b.span_eq }, intro v, have hv : v ∈ (⊤ : submodule K V) := mem_top, rwa [←h', mem_span_singleton] at hv } }, { rintros ⟨v₀, hv₀⟩, have h : (K ∙ v₀) = ⊤, { ext, simp [mem_span_singleton, hv₀] }, rw [←dim_top, ←h], convert dim_span_le _, simp } end /-- A submodule has dimension at most `1` if and only if there is a single vector in the submodule such that the submodule is contained in its span. -/ lemma dim_submodule_le_one_iff (s : submodule K V) : module.rank K s ≤ 1 ↔ ∃ v₀ ∈ s, s ≤ K ∙ v₀ := begin simp_rw [dim_le_one_iff, le_span_singleton_iff], split, { rintro ⟨⟨v₀, hv₀⟩, h⟩, use [v₀, hv₀], intros v hv, obtain ⟨r, hr⟩ := h ⟨v, hv⟩, use r, simp_rw [subtype.ext_iff, coe_smul, submodule.coe_mk] at hr, exact hr }, { rintro ⟨v₀, hv₀, h⟩, use ⟨v₀, hv₀⟩, rintro ⟨v, hv⟩, obtain ⟨r, hr⟩ := h v hv, use r, simp_rw [subtype.ext_iff, coe_smul, submodule.coe_mk], exact hr } end /-- A submodule has dimension at most `1` if and only if there is a single vector, not necessarily in the submodule, such that the submodule is contained in its span. -/ lemma dim_submodule_le_one_iff' (s : submodule K V) : module.rank K s ≤ 1 ↔ ∃ v₀, s ≤ K ∙ v₀ := begin rw dim_submodule_le_one_iff, split, { rintros ⟨v₀, hv₀, h⟩, exact ⟨v₀, h⟩ }, { rintros ⟨v₀, h⟩, by_cases hw : ∃ w : V, w ∈ s ∧ w ≠ 0, { rcases hw with ⟨w, hw, hw0⟩, use [w, hw], rcases mem_span_singleton.1 (h hw) with ⟨r', rfl⟩, have h0 : r' ≠ 0, { rintro rfl, simpa using hw0 }, rwa span_singleton_smul_eq _ h0 }, { push_neg at hw, rw ←submodule.eq_bot_iff at hw, simp [hw] } } end end field end module
fd4430e8ca2bad21d2acaa6a4c2398dba8a3f5c9
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/even_perf.lean
04a5f9a3d10e6dd6c31f8b1b10b891af110712fa
[ "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
184
lean
open nat def even : nat → bool | 0 := tt | (succ 0) := ff | (succ (succ n)) := even n #eval even 0 #eval even 1 #eval even 2 #eval even 10000 #eval even 10001
5fd97fff1c2b098d47b510eb3de6ddfb0bff1834
4727251e0cd73359b15b664c3170e5d754078599
/src/ring_theory/discriminant.lean
cb55318b03c988eff09b803bed8c0e127c117732
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
16,639
lean
/- Copyright (c) 2021 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import ring_theory.trace import ring_theory.norm import number_theory.number_field /-! # Discriminant of a family of vectors Given an `A`-algebra `B` and `b`, an `ι`-indexed family of elements of `B`, we define the *discriminant* of `b` as the determinant of the matrix whose `(i j)`-th element is the trace of `b i * b j`. ## Main definition * `algebra.discr A b` : the discriminant of `b : ι → B`. ## Main results * `algebra.discr_zero_of_not_linear_independent` : if `b` is not linear independent, then `algebra.discr A b = 0`. * `algebra.discr_of_matrix_vec_mul` and `discr_of_matrix_mul_vec` : formulas relating `algebra.discr A ι b` with `algebra.discr A ((P.map (algebra_map A B)).vec_mul b)` and `algebra.discr A ((P.map (algebra_map A B)).mul_vec b)`. * `algebra.discr_not_zero_of_basis` : over a field, if `b` is a basis, then `algebra.discr K b ≠ 0`. * `algebra.discr_eq_det_embeddings_matrix_reindex_pow_two` : if `L/K` is a field extension and `b : ι → L`, then `discr K b` is the square of the determinant of the matrix whose `(i, j)` coefficient is `σⱼ (b i)`, where `σⱼ : L →ₐ[K] E` is the embedding in an algebraically closed field `E` corresponding to `j : ι` via a bijection `e : ι ≃ (L →ₐ[K] E)`. * `algebra.discr_of_power_basis_eq_prod` : the discriminant of a power basis. * `discr_is_integral` : if `K` and `L` are fields and `is_scalar_tower R K L`, is `b : ι → L` satisfies ` ∀ i, is_integral R (b i)`, then `is_integral R (discr K b)`. * `discr_mul_is_integral_mem_adjoin` : let `K` be the fraction field of an integrally closed domain `R` and let `L` be a finite separable extension of `K`. Let `B : power_basis K L` be such that `is_integral R B.gen`. Then for all, `z : L` we have `(discr K B.basis) • z ∈ adjoin R ({B.gen} : set L)`. ## Implementation details Our definition works for any `A`-algebra `B`, but note that if `B` is not free as an `A`-module, then `trace A B = 0` by definition, so `discr A b = 0` for any `b`. -/ universes u v w z open_locale matrix big_operators open matrix finite_dimensional fintype polynomial finset intermediate_field namespace algebra variables (A : Type u) {B : Type v} (C : Type z) {ι : Type w} variables [comm_ring A] [comm_ring B] [algebra A B] [comm_ring C] [algebra A C] section discr /-- Given an `A`-algebra `B` and `b`, an `ι`-indexed family of elements of `B`, we define `discr A ι b` as the determinant of `trace_matrix A ι b`. -/ noncomputable def discr (A : Type u) {B : Type v} [comm_ring A] [comm_ring B] [algebra A B] [fintype ι] (b : ι → B) := by { classical, exact (trace_matrix A b).det } lemma discr_def [decidable_eq ι] [fintype ι] (b : ι → B) : discr A b = (trace_matrix A b).det := by convert rfl variables {ι' : Type*} [fintype ι'] [fintype ι] section basic @[simp] lemma discr_reindex (b : basis ι A B) (f : ι ≃ ι') : discr A (b ∘ ⇑(f.symm)) = discr A b := begin classical, rw [← basis.coe_reindex, discr_def, trace_matrix_reindex, det_reindex_self, ← discr_def] end /-- If `b` is not linear independent, then `algebra.discr A b = 0`. -/ lemma discr_zero_of_not_linear_independent [is_domain A] {b : ι → B} (hli : ¬linear_independent A b) : discr A b = 0 := begin classical, obtain ⟨g, hg, i, hi⟩ := fintype.not_linear_independent_iff.1 hli, have : (trace_matrix A b).mul_vec g = 0, { ext i, have : ∀ j, (trace A B) (b i * b j) * g j = (trace A B) (((g j) • (b j)) * b i), { intro j, simp [mul_comm], }, simp only [mul_vec, dot_product, trace_matrix, pi.zero_apply, trace_form_apply, λ j, this j, ← linear_map.map_sum, ← sum_mul, hg, zero_mul, linear_map.map_zero] }, by_contra h, rw discr_def at h, simpa [matrix.eq_zero_of_mul_vec_eq_zero h this] using hi, end variable {A} /-- Relation between `algebra.discr A ι b` and `algebra.discr A ((P.map (algebra_map A B)).vec_mul b)`. -/ lemma discr_of_matrix_vec_mul [decidable_eq ι] (b : ι → B) (P : matrix ι ι A) : discr A ((P.map (algebra_map A B)).vec_mul b) = P.det ^ 2 * discr A b := by rw [discr_def, trace_matrix_of_matrix_vec_mul, det_mul, det_mul, det_transpose, mul_comm, ← mul_assoc, discr_def, pow_two] /-- Relation between `algebra.discr A ι b` and `algebra.discr A ((P.map (algebra_map A B)).mul_vec b)`. -/ lemma discr_of_matrix_mul_vec [decidable_eq ι] (b : ι → B) (P : matrix ι ι A) : discr A ((P.map (algebra_map A B)).mul_vec b) = P.det ^ 2 * discr A b := by rw [discr_def, trace_matrix_of_matrix_mul_vec, det_mul, det_mul, det_transpose, mul_comm, ← mul_assoc, discr_def, pow_two] end basic section field variables (K : Type u) {L : Type v} (E : Type z) [field K] [field L] [field E] variables [algebra K L] [algebra K E] variables [module.finite K L] [is_alg_closed E] /-- Over a field, if `b` is a basis, then `algebra.discr K b ≠ 0`. -/ lemma discr_not_zero_of_basis [is_separable K L] (b : basis ι K L) : discr K b ≠ 0 := begin by_cases h : nonempty ι, { classical, have := span_eq_top_of_linear_independent_of_card_eq_finrank b.linear_independent (finrank_eq_card_basis b).symm, rw [discr_def, trace_matrix_def], simp_rw [← basis.mk_apply b.linear_independent this], rw [← trace_matrix_def, trace_matrix_of_basis, ← bilin_form.nondegenerate_iff_det_ne_zero], exact trace_form_nondegenerate _ _ }, letI := not_nonempty_iff.1 h, simp [discr], end /-- Over a field, if `b` is a basis, then `algebra.discr K b` is a unit. -/ lemma discr_is_unit_of_basis [is_separable K L] (b : basis ι K L) : is_unit (discr K b) := is_unit.mk0 _ (discr_not_zero_of_basis _ _) variables (b : ι → L) (pb : power_basis K L) /-- If `L/K` is a field extension and `b : ι → L`, then `discr K b` is the square of the determinant of the matrix whose `(i, j)` coefficient is `σⱼ (b i)`, where `σⱼ : L →ₐ[K] E` is the embedding in an algebraically closed field `E` corresponding to `j : ι` via a bijection `e : ι ≃ (L →ₐ[K] E)`. -/ lemma discr_eq_det_embeddings_matrix_reindex_pow_two [decidable_eq ι] [is_separable K L] (e : ι ≃ (L →ₐ[K] E)) : algebra_map K E (discr K b) = (embeddings_matrix_reindex K E b e).det ^ 2 := by rw [discr_def, ring_hom.map_det, ring_hom.map_matrix_apply, trace_matrix_eq_embeddings_matrix_reindex_mul_trans, det_mul, det_transpose, pow_two] /-- The discriminant of a power basis. -/ lemma discr_power_basis_eq_prod (e : fin pb.dim ≃ (L →ₐ[K] E)) [is_separable K L] : algebra_map K E (discr K pb.basis) = ∏ i : fin pb.dim, ∏ j in finset.univ.filter (λ j, i < j), (e j pb.gen- (e i pb.gen)) ^ 2 := begin rw [discr_eq_det_embeddings_matrix_reindex_pow_two K E pb.basis e, embeddings_matrix_reindex_eq_vandermonde, det_transpose, det_vandermonde, ← prod_pow], congr, ext i, rw [← prod_pow] end /-- A variation of `of_power_basis_eq_prod`. -/ lemma discr_power_basis_eq_prod' [is_separable K L] (e : fin pb.dim ≃ (L →ₐ[K] E)) : algebra_map K E (discr K pb.basis) = ∏ i : fin pb.dim, ∏ j in finset.univ.filter (λ j, i < j), -((e j pb.gen- (e i pb.gen)) * (e i pb.gen- (e j pb.gen))) := begin rw [discr_power_basis_eq_prod _ _ _ e], congr, ext i, congr, ext j, ring end local notation `n` := finrank K L /-- A variation of `of_power_basis_eq_prod`. -/ lemma discr_power_basis_eq_prod'' [is_separable K L] (e : fin pb.dim ≃ (L →ₐ[K] E)) : algebra_map K E (discr K pb.basis) = (-1) ^ (n * (n - 1) / 2) * ∏ i : fin pb.dim, ∏ j in finset.univ.filter (λ j, i < j), ((e j pb.gen- (e i pb.gen)) * (e i pb.gen- (e j pb.gen))) := begin rw [discr_power_basis_eq_prod' _ _ _ e], simp_rw [λ i j, neg_eq_neg_one_mul ((e j pb.gen- (e i pb.gen)) * (e i pb.gen- (e j pb.gen))), prod_mul_distrib], congr, simp only [prod_pow_eq_pow_sum, prod_const], congr, simp_rw [fin.card_filter_lt], apply (@nat.cast_inj ℚ _ _ _ _ _).1, rw [nat.cast_sum], have : ∀ (x : fin pb.dim), (↑x + 1) ≤ pb.dim := by simp [nat.succ_le_iff, fin.is_lt], simp_rw [nat.sub_sub], simp only [nat.cast_sub, this, finset.card_fin, nsmul_eq_mul, sum_const, sum_sub_distrib, nat.cast_add, nat.cast_one, sum_add_distrib, mul_one], rw [← nat.cast_sum, ← @finset.sum_range ℕ _ pb.dim (λ i, i), sum_range_id ], have hn : n = pb.dim, { rw [← alg_hom.card K L E, ← fintype.card_fin pb.dim], exact card_congr (equiv.symm e) }, have h₂ : 2 ∣ (pb.dim * (pb.dim - 1)) := even_iff_two_dvd.1 (nat.even_mul_self_pred _), have hne : ((2 : ℕ) : ℚ) ≠ 0 := by simp, have hle : 1 ≤ pb.dim, { rw [← hn, nat.one_le_iff_ne_zero, ← zero_lt_iff, finite_dimensional.finrank_pos_iff], apply_instance }, rw [hn, nat.cast_div h₂ hne, nat.cast_mul, nat.cast_sub hle], field_simp, ring, end /-- Formula for the discriminant of a power basis using the norm of the field extension. -/ lemma discr_power_basis_eq_norm [is_separable K L] : discr K pb.basis = (-1) ^ (n * (n - 1) / 2) * (norm K (aeval pb.gen (minpoly K pb.gen).derivative)) := begin let E := algebraic_closure L, letI := λ (a b : E), classical.prop_decidable (eq a b), have e : fin pb.dim ≃ (L →ₐ[K] E), { refine equiv_of_card_eq _, rw [fintype.card_fin, alg_hom.card], exact (power_basis.finrank pb).symm }, have hnodup : (map (algebra_map K E) (minpoly K pb.gen)).roots.nodup := nodup_roots (separable.map (is_separable.separable K pb.gen)), have hroots : ∀ σ : L →ₐ[K] E, σ pb.gen ∈ (map (algebra_map K E) (minpoly K pb.gen)).roots, { intro σ, rw [mem_roots, is_root.def, eval_map, ← aeval_def, aeval_alg_hom_apply], repeat { simp [minpoly.ne_zero (is_separable.is_integral K pb.gen)] } }, apply (algebra_map K E).injective, rw [ring_hom.map_mul, ring_hom.map_pow, ring_hom.map_neg, ring_hom.map_one, discr_power_basis_eq_prod'' _ _ _ e], congr, rw [norm_eq_prod_embeddings, fin.prod_filter_lt_mul_neg_eq_prod_off_diag], conv_rhs { congr, skip, funext, rw [← aeval_alg_hom_apply, aeval_root_derivative_of_splits (minpoly.monic (is_separable.is_integral K pb.gen)) (is_alg_closed.splits_codomain _) (hroots σ), ← finset.prod_mk _ (hnodup.erase _)] }, rw [prod_sigma', prod_sigma'], refine prod_bij (λ i hi, ⟨e i.2, e i.1 pb.gen⟩) (λ i hi, _) (λ i hi, by simp at hi) (λ i j hi hj hij, _) (λ σ hσ, _), { simp only [true_and, finset.mem_mk, mem_univ, mem_sigma], rw [multiset.mem_erase_of_ne (λ h, _)], { exact hroots _ }, { simp only [true_and, mem_filter, mem_univ, ne.def, mem_sigma] at hi, refine hi (equiv.injective e (equiv.injective (power_basis.lift_equiv pb) _)), rw [← power_basis.lift_equiv_apply_coe, ← power_basis.lift_equiv_apply_coe] at h, exact subtype.eq h } }, { simp only [equiv.apply_eq_iff_eq, heq_iff_eq] at hij, have h := hij.2, rw [← power_basis.lift_equiv_apply_coe, ← power_basis.lift_equiv_apply_coe] at h, refine sigma.eq (equiv.injective e (equiv.injective _ (subtype.eq h))) (by simp [hij.1]) }, { simp only [true_and, finset.mem_mk, mem_univ, mem_sigma] at hσ, simp only [sigma.exists, true_and, exists_prop, mem_filter, mem_univ, ne.def, mem_sigma], refine ⟨e.symm (power_basis.lift pb σ.2 _), e.symm σ.1, ⟨λ h, _, sigma.eq _ _⟩⟩, { rw [aeval_def, eval₂_eq_eval_map, ← is_root.def, ← mem_roots], { exact multiset.erase_subset _ _ hσ }, { simp [minpoly.ne_zero (is_separable.is_integral K pb.gen)] } }, { replace h := alg_hom.congr_fun (equiv.injective _ h) pb.gen, rw [power_basis.lift_gen] at h, rw [← h] at hσ, exact hnodup.not_mem_erase hσ }, all_goals { simp } } end section integral variables {R : Type z} [comm_ring R] [algebra R K] [algebra R L] [is_scalar_tower R K L] local notation `is_integral` := _root_.is_integral /-- If `K` and `L` are fields and `is_scalar_tower R K L`, and `b : ι → L` satisfies ` ∀ i, is_integral R (b i)`, then `is_integral R (discr K b)`. -/ lemma discr_is_integral {b : ι → L} (h : ∀ i, is_integral R (b i)) : is_integral R (discr K b) := begin classical, rw [discr_def], exact is_integral.det (λ i j, is_integral_trace (is_integral_mul (h i) (h j))) end /-- If `b` and `b'` are `ℚ`-bases of a number field `K` such that `∀ i j, is_integral ℤ (b.to_matrix b' i j)` and `∀ i j, is_integral ℤ (b'.to_matrix b i j)` then `discr ℚ b = discr ℚ b'`. -/ lemma discr_eq_discr_of_to_matrix_coeff_is_integral [number_field K] {b : basis ι ℚ K} {b' : basis ι' ℚ K} (h : ∀ i j, is_integral ℤ (b.to_matrix b' i j)) (h' : ∀ i j, is_integral ℤ (b'.to_matrix b i j)) : discr ℚ b = discr ℚ b' := begin replace h' : ∀ i j, is_integral ℤ (b'.to_matrix ((b.reindex (b.index_equiv b'))) i j), { intros i j, convert h' i ((b.index_equiv b').symm j), simpa }, classical, rw [← (b.reindex (b.index_equiv b')).to_matrix_map_vec_mul b', discr_of_matrix_vec_mul, ← one_mul (discr ℚ b), basis.coe_reindex, discr_reindex], congr, have hint : is_integral ℤ (((b.reindex (b.index_equiv b')).to_matrix b').det) := is_integral.det (λ i j, h _ _), obtain ⟨r, hr⟩ := is_integrally_closed.is_integral_iff.1 hint, have hunit : is_unit r, { have : is_integral ℤ ((b'.to_matrix (b.reindex (b.index_equiv b'))).det) := is_integral.det (λ i j, h' _ _), obtain ⟨r', hr'⟩ := is_integrally_closed.is_integral_iff.1 this, refine is_unit_iff_exists_inv.2 ⟨r', _⟩, suffices : algebra_map ℤ ℚ (r * r') = 1, { rw [← ring_hom.map_one (algebra_map ℤ ℚ)] at this, exact (is_fraction_ring.injective ℤ ℚ) this }, rw [ring_hom.map_mul, hr, hr', ← det_mul, basis.to_matrix_mul_to_matrix_flip, det_one] }, rw [← ring_hom.map_one (algebra_map ℤ ℚ), ← hr], cases int.is_unit_iff.1 hunit with hp hm, { simp [hp] }, { simp [hm] } end /-- Let `K` be the fraction field of an integrally closed domain `R` and let `L` be a finite separable extension of `K`. Let `B : power_basis K L` be such that `is_integral R B.gen`. Then for all, `z : L` that are integral over `R`, we have `(discr K B.basis) • z ∈ adjoin R ({B.gen} : set L)`. -/ lemma discr_mul_is_integral_mem_adjoin [is_domain R] [is_separable K L] [is_integrally_closed R] [is_fraction_ring R K] {B : power_basis K L} (hint : is_integral R B.gen) {z : L} (hz : is_integral R z) : (discr K B.basis) • z ∈ adjoin R ({B.gen} : set L) := begin have hinv : is_unit (trace_matrix K B.basis).det := by simpa [← discr_def] using discr_is_unit_of_basis _ B.basis, have H : (trace_matrix K B.basis).det • (trace_matrix K B.basis).mul_vec (B.basis.equiv_fun z) = (trace_matrix K B.basis).det • (λ i, trace K L (z * B.basis i)), { congr, exact trace_matrix_of_basis_mul_vec _ _ }, have cramer := mul_vec_cramer (trace_matrix K B.basis) (λ i, trace K L (z * B.basis i)), suffices : ∀ i, ((trace_matrix K B.basis).det • (B.basis.equiv_fun z)) i ∈ (⊥ : subalgebra R K), { rw [← B.basis.sum_repr z, finset.smul_sum], refine subalgebra.sum_mem _ (λ i hi, _), replace this := this i, rw [← discr_def, pi.smul_apply, mem_bot] at this, obtain ⟨r, hr⟩ := this, rw [basis.equiv_fun_apply] at hr, rw [← smul_assoc, ← hr, algebra_map_smul], refine subalgebra.smul_mem _ _ _, rw [B.basis_eq_pow i], refine subalgebra.pow_mem _ (subset_adjoin (set.mem_singleton _)) _}, intro i, rw [← H, ← mul_vec_smul] at cramer, replace cramer := congr_arg (mul_vec (trace_matrix K B.basis)⁻¹) cramer, rw [mul_vec_mul_vec, nonsing_inv_mul _ hinv, mul_vec_mul_vec, nonsing_inv_mul _ hinv, one_mul_vec, one_mul_vec] at cramer, rw [← congr_fun cramer i, cramer_apply, det_apply], refine subalgebra.sum_mem _ (λ σ _, subalgebra.zsmul_mem _ (subalgebra.prod_mem _ (λ j _, _)) _), by_cases hji : j = i, { simp only [update_column_apply, hji, eq_self_iff_true, power_basis.coe_basis], exact mem_bot.2 (is_integrally_closed.is_integral_iff.1 $ is_integral_trace $ is_integral_mul hz $ is_integral.pow hint _) }, { simp only [update_column_apply, hji, power_basis.coe_basis], exact mem_bot.2 (is_integrally_closed.is_integral_iff.1 $ is_integral_trace $ is_integral_mul (is_integral.pow hint _) (is_integral.pow hint _)) } end end integral end field end discr end algebra
f453ee853124287e62177c27baf87fd82500417c
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch5/ex0606.lean
326f945996a20fd801c8f98806ab1112b9f45ee6
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
110
lean
variables (f : ℕ → ℕ) (a : ℕ) example (h : a + 0 = 0) : f a = f 0 := by { rw add_zero at h, rw h }
ee8e381a86832024a4354b19487d4e9becae894d
80746c6dba6a866de5431094bf9f8f841b043d77
/src/set_theory/cardinal.lean
fc843d5d7254685c2ce44b85b4f8e65b8171ac92
[ "Apache-2.0" ]
permissive
leanprover-fork/mathlib-backup
8b5c95c535b148fca858f7e8db75a76252e32987
0eb9db6a1a8a605f0cf9e33873d0450f9f0ae9b0
refs/heads/master
1,585,156,056,139
1,548,864,430,000
1,548,864,438,000
143,964,213
0
0
Apache-2.0
1,550,795,966,000
1,533,705,322,000
Lean
UTF-8
Lean
false
false
30,668
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl, Mario Carneiro Cardinal arithmetic. Cardinals are represented as quotient over equinumerous types. -/ import data.set.finite data.quot logic.function set_theory.schroeder_bernstein open function lattice set local attribute [instance] classical.prop_decidable universes u v w x instance cardinal.is_equivalent : setoid (Type u) := { r := λα β, nonempty (α ≃ β), iseqv := ⟨λα, ⟨equiv.refl α⟩, λα β ⟨e⟩, ⟨e.symm⟩, λα β γ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩⟩ } /-- `cardinal.{u}` is the type of cardinal numbers in `Type u`, defined as the quotient of `Type u` by existence of an equivalence (a bijection with explicit inverse). -/ def cardinal : Type (u + 1) := quotient cardinal.is_equivalent namespace cardinal /-- The cardinal of a type -/ def mk : Type u → cardinal := quotient.mk @[simp] theorem mk_def (α : Type u) : @eq cardinal ⟦α⟧ (mk α) := rfl @[simp] theorem mk_out (c : cardinal) : mk (c.out) = c := quotient.out_eq _ instance : has_le cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, nonempty $ α ↪ β) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, propext ⟨assume ⟨e⟩, ⟨e.congr e₁ e₂⟩, assume ⟨e⟩, ⟨e.congr e₁.symm e₂.symm⟩⟩⟩ theorem mk_le_of_injective {α β : Type u} {f : α → β} (hf : injective f) : mk α ≤ mk β := ⟨⟨f, hf⟩⟩ theorem mk_le_of_surjective {α β : Type u} {f : α → β} (hf : surjective f) : mk β ≤ mk α := ⟨embedding.of_surjective hf⟩ theorem le_mk_iff_exists_set {c : cardinal} {α : Type u} : c ≤ mk α ↔ ∃ p : set α, mk p = c := ⟨quotient.induction_on c $ λ β ⟨⟨f, hf⟩⟩, ⟨set.range f, eq.symm $ quot.sound ⟨equiv.set.range f hf⟩⟩, λ ⟨p, e⟩, e ▸ ⟨⟨subtype.val, λ a b, subtype.eq⟩⟩⟩ instance : linear_order cardinal.{u} := { le := (≤), le_refl := by rintros ⟨α⟩; exact ⟨embedding.refl _⟩, le_trans := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.trans e₂⟩, le_antisymm := by rintros ⟨α⟩ ⟨β⟩ ⟨e₁⟩ ⟨e₂⟩; exact quotient.sound (e₁.antisymm e₂), le_total := by rintros ⟨α⟩ ⟨β⟩; exact embedding.total } noncomputable instance : decidable_linear_order cardinal.{u} := classical.DLO _ noncomputable instance : distrib_lattice cardinal.{u} := by apply_instance instance : has_zero cardinal.{u} := ⟨⟦pempty⟧⟩ instance : inhabited cardinal.{u} := ⟨0⟩ theorem ne_zero_iff_nonempty {α : Type u} : mk α ≠ 0 ↔ nonempty α := not_iff_comm.1 ⟨λ h, quotient.sound ⟨(equiv.empty_of_not_nonempty h).trans equiv.empty_equiv_pempty⟩, λ e, let ⟨h⟩ := quotient.exact e in λ ⟨a⟩, (h a).elim⟩ instance : has_one cardinal.{u} := ⟨⟦punit⟧⟩ instance : zero_ne_one_class cardinal.{u} := { zero := 0, one := 1, zero_ne_one := ne.symm $ ne_zero_iff_nonempty.2 ⟨punit.star⟩ } theorem le_one_iff_subsingleton {α : Type u} : mk α ≤ 1 ↔ subsingleton α := ⟨λ ⟨f⟩, ⟨λ a b, f.inj (subsingleton.elim _ _)⟩, λ ⟨h⟩, ⟨⟨λ a, punit.star, λ a b _, h _ _⟩⟩⟩ instance : has_add cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α ⊕ β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.sum_congr e₁ e₂⟩⟩ @[simp] theorem add_def (α β) : mk α + mk β = mk (α ⊕ β) := rfl instance : has_mul cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α × β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.prod_congr e₁ e₂⟩⟩ @[simp] theorem mul_def (α β) : mk α * mk β = mk (α × β) := rfl private theorem add_comm (a b : cardinal.{u}) : a + b = b + a := quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.sum_comm α β⟩ private theorem mul_comm (a b : cardinal.{u}) : a * b = b * a := quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.prod_comm α β⟩ private theorem zero_add (a : cardinal.{u}) : 0 + a = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_sum α⟩ private theorem zero_mul (a : cardinal.{u}) : 0 * a = 0 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_prod α⟩ private theorem one_mul (a : cardinal.{u}) : 1 * a = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.punit_prod α⟩ private theorem left_distrib (a b c : cardinal.{u}) : a * (b + c) = a * b + a * c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_sum_distrib α β γ⟩ instance : comm_semiring cardinal.{u} := { zero := 0, one := 1, add := (+), mul := (*), zero_add := zero_add, add_zero := assume a, by rw [add_comm a 0, zero_add a], add_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.sum_assoc α β γ⟩, add_comm := add_comm, zero_mul := zero_mul, mul_zero := assume a, by rw [mul_comm a 0, zero_mul a], one_mul := one_mul, mul_one := assume a, by rw [mul_comm a 1, one_mul a], mul_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_assoc α β γ⟩, mul_comm := mul_comm, left_distrib := left_distrib, right_distrib := assume a b c, by rw [mul_comm (a + b) c, left_distrib c a b, mul_comm c a, mul_comm c b] } /-- The cardinal exponential. `mk α ^ mk β` is the cardinal of `β → α`. -/ protected def power (a b : cardinal.{u}) : cardinal.{u} := quotient.lift_on₂ a b (λα β, mk (β → α)) $ assume α₁ α₂ β₁ β₂ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.arrow_congr e₂ e₁⟩ instance : has_pow cardinal cardinal := ⟨cardinal.power⟩ local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow @[simp] theorem power_def (α β) : mk α ^ mk β = mk (β → α) := rfl @[simp] theorem power_zero {a : cardinal} : a ^ 0 = 1 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_arrow_equiv_punit α⟩ @[simp] theorem power_one {a : cardinal} : a ^ 1 = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.punit_arrow_equiv α⟩ @[simp] theorem one_power {a : cardinal} : 1 ^ a = 1 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.arrow_punit_equiv_punit α⟩ @[simp] theorem prop_eq_two : mk (ulift Prop) = 2 := quot.sound ⟨equiv.ulift.trans $ equiv.Prop_equiv_bool.trans equiv.bool_equiv_punit_sum_punit⟩ @[simp] theorem zero_power {a : cardinal} : a ≠ 0 → 0 ^ a = 0 := quotient.induction_on a $ assume α heq, nonempty.rec_on (ne_zero_iff_nonempty.1 heq) $ assume a, quotient.sound ⟨equiv.equiv_pempty $ assume f, pempty.rec (λ _, false) (f a)⟩ theorem power_ne_zero {a : cardinal} (b) : a ≠ 0 → a ^ b ≠ 0 := quotient.induction_on₂ a b $ λ α β h, let ⟨a⟩ := ne_zero_iff_nonempty.1 h in ne_zero_iff_nonempty.2 ⟨λ _, a⟩ theorem mul_power {a b c : cardinal} : (a * b) ^ c = a ^ c * b ^ c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.arrow_prod_equiv_prod_arrow α β γ⟩ theorem power_add {a b c : cardinal} : a ^ (b + c) = a ^ b * a ^ c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.sum_arrow_equiv_prod_arrow β γ α⟩ theorem power_mul {a b c : cardinal} : (a ^ b) ^ c = a ^ (b * c) := by rw [_root_.mul_comm b c]; from (quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.arrow_arrow_equiv_prod_arrow γ β α⟩) section order_properties open sum theorem zero_le : ∀(a : cardinal), 0 ≤ a := by rintro ⟨α⟩; exact ⟨embedding.of_not_nonempty $ λ ⟨a⟩, a.elim⟩ theorem le_zero (a : cardinal) : a ≤ 0 ↔ a = 0 := by simp [le_antisymm_iff, zero_le] theorem pos_iff_ne_zero {o : cardinal} : 0 < o ↔ o ≠ 0 := by simp [lt_iff_le_and_ne, eq_comm, zero_le] theorem zero_lt_one : (0 : cardinal) < 1 := lt_of_le_of_ne (zero_le _) zero_ne_one theorem add_le_add : ∀{a b c d : cardinal}, a ≤ b → c ≤ d → a + c ≤ b + d := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨embedding.sum_congr e₁ e₂⟩ theorem add_le_add_left (a) {b c : cardinal} : b ≤ c → a + b ≤ a + c := add_le_add (le_refl _) theorem add_le_add_right {a b : cardinal} (c) (h : a ≤ b) : a + c ≤ b + c := add_le_add h (le_refl _) theorem le_add_right (a b : cardinal) : a ≤ a + b := by simpa using add_le_add_left a (zero_le b) theorem le_add_left (a b : cardinal) : a ≤ b + a := by simpa using add_le_add_right a (zero_le b) theorem mul_le_mul : ∀{a b c d : cardinal}, a ≤ b → c ≤ d → a * c ≤ b * d := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨embedding.prod_congr e₁ e₂⟩ theorem mul_le_mul_left (a) {b c : cardinal} : b ≤ c → a * b ≤ a * c := mul_le_mul (le_refl _) theorem mul_le_mul_right {a b : cardinal} (c) (h : a ≤ b) : a * c ≤ b * c := mul_le_mul h (le_refl _) theorem power_le_power_left : ∀{a b c : cardinal}, a ≠ 0 → b ≤ c → a ^ b ≤ a ^ c := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ hα ⟨e⟩; exact let ⟨a⟩ := ne_zero_iff_nonempty.1 hα in ⟨@embedding.arrow_congr_right _ _ _ ⟨a⟩ e⟩ theorem power_le_power_right {a b c : cardinal} : a ≤ b → a ^ c ≤ b ^ c := quotient.induction_on₃ a b c $ assume α β γ ⟨e⟩, ⟨embedding.arrow_congr_left e⟩ theorem le_iff_exists_add {a b : cardinal} : a ≤ b ↔ ∃ c, b = a + c := ⟨quotient.induction_on₂ a b $ λ α β ⟨⟨f, hf⟩⟩, have (α ⊕ ↥-range f) ≃ β, from (equiv.sum_congr (equiv.set.range f hf) (equiv.refl _)).trans $ (equiv.set.sum_compl (range f)), ⟨⟦(-range f : set β)⟧, quotient.sound ⟨this.symm⟩⟩, λ ⟨c, e⟩, add_zero a ▸ e.symm ▸ add_le_add_left _ (zero_le _)⟩ end order_properties instance : canonically_ordered_monoid cardinal.{u} := { add_le_add_left := λ a b h c, add_le_add_left _ h, lt_of_add_lt_add_left := λ a b c, lt_imp_lt_of_le_imp_le (add_le_add_left _), le_iff_exists_add := @le_iff_exists_add, ..cardinal.comm_semiring, ..cardinal.linear_order } instance : order_bot cardinal.{u} := { bot := 0, bot_le := zero_le, ..cardinal.linear_order } theorem cantor : ∀(a : cardinal.{u}), a < 2 ^ a := by rw ← prop_eq_two; rintros ⟨a⟩; exact ⟨ ⟨⟨λ a b, ⟨a = b⟩, λ a b h, cast (ulift.up.inj (@congr_fun _ _ _ _ h b)).symm rfl⟩⟩, λ ⟨⟨f, hf⟩⟩, cantor_injective (λ s, f (λ a, ⟨s a⟩)) $ λ s t h, by funext a; injection congr_fun (hf h) a⟩ instance : no_top_order cardinal.{u} := { no_top := λ a, ⟨_, cantor a⟩, ..cardinal.linear_order } /-- The minimum cardinal in a family of cardinals (the existence of which is provided by `injective_min`). -/ noncomputable def min {ι} (I : nonempty ι) (f : ι → cardinal) : cardinal := f $ classical.some $ @embedding.injective_min _ (λ i, (f i).out) I theorem min_eq {ι} (I) (f : ι → cardinal) : ∃ i, min I f = f i := ⟨_, rfl⟩ theorem min_le {ι I} (f : ι → cardinal) (i) : min I f ≤ f i := by rw [← mk_out (min I f), ← mk_out (f i)]; exact let ⟨g⟩ := classical.some_spec (@embedding.injective_min _ (λ i, (f i).out) I) in ⟨g i⟩ theorem le_min {ι I} {f : ι → cardinal} {a} : a ≤ min I f ↔ ∀ i, a ≤ f i := ⟨λ h i, le_trans h (min_le _ _), λ h, let ⟨i, e⟩ := min_eq I f in e.symm ▸ h i⟩ protected theorem wf : @well_founded cardinal.{u} (<) := ⟨λ a, classical.by_contradiction $ λ h, let ι := {c :cardinal // ¬ acc (<) c}, f : ι → cardinal := subtype.val, ⟨⟨c, hc⟩, hi⟩ := @min_eq ι ⟨⟨_, h⟩⟩ f in hc (acc.intro _ (λ j ⟨_, h'⟩, classical.by_contradiction $ λ hj, h' $ by have := min_le f ⟨j, hj⟩; rwa hi at this))⟩ instance has_wf : @has_well_founded cardinal.{u} := ⟨(<), cardinal.wf⟩ instance wo : @is_well_order cardinal.{u} (<) := ⟨cardinal.wf⟩ /-- The successor cardinal - the smallest cardinal greater than `c`. This is not the same as `c + 1` except in the case of finite `c`. -/ noncomputable def succ (c : cardinal) : cardinal := @min {c' // c < c'} ⟨⟨_, cantor _⟩⟩ subtype.val theorem lt_succ_self (c : cardinal) : c < succ c := by cases min_eq _ _ with s e; rw [succ, e]; exact s.2 theorem succ_le {a b : cardinal} : succ a ≤ b ↔ a < b := ⟨lt_of_lt_of_le (lt_succ_self _), λ h, by exact min_le _ (subtype.mk b h)⟩ theorem lt_succ {a b : cardinal} : a < succ b ↔ a ≤ b := by rw [← not_le, succ_le, not_lt] theorem add_one_le_succ (c : cardinal) : c + 1 ≤ succ c := begin refine quot.induction_on c (λ α, _) (lt_succ_self c), refine quot.induction_on (succ (quot.mk setoid.r α)) (λ β h, _), cases h.left with f, have : ¬ surjective f := λ hn, ne_of_lt h (quotient.sound ⟨equiv.of_bijective ⟨f.inj, hn⟩⟩), cases classical.not_forall.1 this with b nex, refine ⟨⟨sum.rec (by exact f) _, _⟩⟩, { exact λ _, b }, { intros a b h, rcases a with a|⟨⟨⟨⟩⟩⟩; rcases b with b|⟨⟨⟨⟩⟩⟩, { rw f.inj h }, { exact nex.elim ⟨_, h⟩ }, { exact nex.elim ⟨_, h.symm⟩ }, { refl } } end /-- The indexed sum of cardinals is the cardinality of the indexed disjoint union, i.e. sigma type. -/ def sum {ι} (f : ι → cardinal) : cardinal := mk Σ i, (f i).out theorem le_sum {ι} (f : ι → cardinal) (i) : f i ≤ sum f := by rw ← quotient.out_eq (f i); exact ⟨⟨λ a, ⟨i, a⟩, λ a b h, eq_of_heq $ by injection h⟩⟩ @[simp] theorem sum_mk {ι} (f : ι → Type*) : sum (λ i, mk (f i)) = mk (Σ i, f i) := quot.sound ⟨equiv.sigma_congr_right $ λ i, classical.choice $ quotient.exact $ quot.out_eq $ mk (f i)⟩ theorem sum_const (ι : Type u) (a : cardinal.{u}) : sum (λ _:ι, a) = mk ι * a := quotient.induction_on a $ λ α, by simp; exact quotient.sound ⟨equiv.sigma_equiv_prod _ _⟩ theorem sum_le_sum {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sum f ≤ sum g := ⟨embedding.sigma_congr_right $ λ i, classical.choice $ by have := H i; rwa [← quot.out_eq (f i), ← quot.out_eq (g i)] at this⟩ /-- The indexed supremum of cardinals is the smallest cardinal above everything in the family. -/ noncomputable def sup {ι} (f : ι → cardinal) : cardinal := @min {c // ∀ i, f i ≤ c} ⟨⟨sum f, le_sum f⟩⟩ (λ a, a.1) theorem le_sup {ι} (f : ι → cardinal) (i) : f i ≤ sup f := by dsimp [sup]; cases min_eq _ _ with c hc; rw hc; exact c.2 i theorem sup_le {ι} {f : ι → cardinal} {a} : sup f ≤ a ↔ ∀ i, f i ≤ a := ⟨λ h i, le_trans (le_sup _ _) h, λ h, by dsimp [sup]; change a with (⟨a, h⟩:subtype _).1; apply min_le⟩ theorem sup_le_sup {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sup f ≤ sup g := sup_le.2 $ λ i, le_trans (H i) (le_sup _ _) theorem sup_le_sum {ι} (f : ι → cardinal) : sup f ≤ sum f := sup_le.2 $ le_sum _ theorem sum_le_sup {ι : Type u} (f : ι → cardinal.{u}) : sum f ≤ mk ι * sup.{u u} f := by rw ← sum_const; exact sum_le_sum _ _ (le_sup _) /-- The indexed product of cardinals is the cardinality of the Pi type (dependent product). -/ def prod {ι : Type u} (f : ι → cardinal) : cardinal := mk (Π i, (f i).out) @[simp] theorem prod_mk {ι} (f : ι → Type*) : prod (λ i, mk (f i)) = mk (Π i, f i) := quot.sound ⟨equiv.Pi_congr_right $ λ i, classical.choice $ quotient.exact $ mk_out $ mk (f i)⟩ theorem prod_const (ι : Type u) (a : cardinal.{u}) : prod (λ _:ι, a) = a ^ mk ι := quotient.induction_on a $ by simp theorem prod_le_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : prod f ≤ prod g := ⟨embedding.Pi_congr_right $ λ i, classical.choice $ by have := H i; rwa [← mk_out (f i), ← mk_out (g i)] at this⟩ theorem prod_ne_zero {ι} (f : ι → cardinal) : prod f ≠ 0 ↔ ∀ i, f i ≠ 0 := begin conv in (f _) {rw ← mk_out (f i)}, simp [prod, ne_zero_iff_nonempty, -mk_out, -ne.def], exact ⟨λ ⟨F⟩ i, ⟨F i⟩, λ h, ⟨λ i, classical.choice (h i)⟩⟩, end theorem prod_eq_zero {ι} (f : ι → cardinal) : prod f = 0 ↔ ∃ i, f i = 0 := not_iff_not.1 $ by simpa using prod_ne_zero f /-- The universe lift operation on cardinals -/ def lift (c : cardinal.{u}) : cardinal.{max u v} := quotient.lift_on c (λ α, ⟦ulift α⟧) $ λ α β ⟨e⟩, quotient.sound ⟨equiv.ulift.trans $ e.trans equiv.ulift.symm⟩ theorem lift_mk (α) : lift.{u v} (mk α) = mk (ulift.{v u} α) := rfl theorem lift_umax : lift.{u (max u v)} = lift.{u v} := funext $ λ a, quot.induction_on a $ λ α, quotient.sound ⟨equiv.ulift.trans equiv.ulift.symm⟩ theorem lift_id' (a : cardinal) : lift a = a := quot.induction_on a $ λ α, quot.sound ⟨equiv.ulift⟩ @[simp] theorem lift_id : ∀ a, lift.{u u} a = a := lift_id'.{u u} @[simp] theorem lift_lift (a : cardinal) : lift.{(max u v) w} (lift.{u v} a) = lift.{u (max v w)} a := quot.induction_on a $ λ α, quotient.sound ⟨equiv.ulift.trans $ equiv.ulift.trans equiv.ulift.symm⟩ theorem lift_mk_le {α : Type u} {β : Type v} : lift.{u (max v w)} (mk α) ≤ lift.{v (max u w)} (mk β) ↔ nonempty (α ↪ β) := ⟨λ ⟨f⟩, ⟨embedding.congr equiv.ulift equiv.ulift f⟩, λ ⟨f⟩, ⟨embedding.congr equiv.ulift.symm equiv.ulift.symm f⟩⟩ theorem lift_mk_eq {α : Type u} {β : Type v} : lift.{u (max v w)} (mk α) = lift.{v (max u w)} (mk β) ↔ nonempty (α ≃ β) := quotient.eq.trans ⟨λ ⟨f⟩, ⟨equiv.ulift.symm.trans $ f.trans equiv.ulift⟩, λ ⟨f⟩, ⟨equiv.ulift.trans $ f.trans equiv.ulift.symm⟩⟩ @[simp] theorem lift_le {a b : cardinal} : lift a ≤ lift b ↔ a ≤ b := quotient.induction_on₂ a b $ λ α β, by rw ← lift_umax; exact lift_mk_le @[simp] theorem lift_inj {a b : cardinal} : lift a = lift b ↔ a = b := by simp [le_antisymm_iff] @[simp] theorem lift_lt {a b : cardinal} : lift a < lift b ↔ a < b := by simp [lt_iff_le_not_le, -not_le] @[simp] theorem lift_zero : lift 0 = 0 := quotient.sound ⟨equiv.ulift.trans equiv.pempty_equiv_pempty⟩ @[simp] theorem lift_one : lift 1 = 1 := quotient.sound ⟨equiv.ulift.trans equiv.punit_equiv_punit⟩ @[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.prod_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_power (a b) : lift (a ^ b) = lift a ^ lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.arrow_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_two_power (a) : lift (2 ^ a) = 2 ^ lift a := by simp [bit0] @[simp] theorem lift_min {ι I} (f : ι → cardinal) : lift (min I f) = min I (lift ∘ f) := le_antisymm (le_min.2 $ λ a, lift_le.2 $ min_le _ a) $ let ⟨i, e⟩ := min_eq I (lift ∘ f) in by rw e; exact lift_le.2 (le_min.2 $ λ j, lift_le.1 $ by have := min_le (lift ∘ f) j; rwa e at this) theorem lift_down {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a → ∃ a', lift a' = b := quotient.induction_on₂ a b $ λ α β, by dsimp; rw [← lift_id (mk β), ← lift_umax, ← lift_umax.{u v}, lift_mk_le]; exact λ ⟨f⟩, ⟨mk (set.range f), eq.symm $ lift_mk_eq.2 ⟨embedding.equiv_of_surjective (embedding.cod_restrict _ f set.mem_range_self) $ λ ⟨a, ⟨b, e⟩⟩, ⟨b, subtype.eq e⟩⟩⟩ theorem le_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a ↔ ∃ a', lift a' = b ∧ a' ≤ a := ⟨λ h, let ⟨a', e⟩ := lift_down h in ⟨a', e, lift_le.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_le.2 h⟩ theorem lt_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b < lift a ↔ ∃ a', lift a' = b ∧ a' < a := ⟨λ h, let ⟨a', e⟩ := lift_down (le_of_lt h) in ⟨a', e, lift_lt.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_lt.2 h⟩ @[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) := le_antisymm (le_of_not_gt $ λ h, begin rcases lt_lift_iff.1 h with ⟨b, e, h⟩, rw [lt_succ, ← lift_le, e] at h, exact not_lt_of_le h (lt_succ_self _) end) (succ_le.2 $ lift_lt.2 $ lt_succ_self _) /-- `ω` is the smallest infinite cardinal, also known as ℵ₀. -/ def omega : cardinal.{u} := lift (mk ℕ) theorem omega_ne_zero : omega ≠ 0 := ne_zero_iff_nonempty.2 ⟨⟨0⟩⟩ theorem omega_pos : 0 < omega := pos_iff_ne_zero.2 omega_ne_zero @[simp] theorem lift_omega : lift omega = omega := lift_lift _ @[simp] theorem mk_fin : ∀ (n : ℕ), mk (fin n) = n | 0 := quotient.sound ⟨(equiv.pempty_of_not_nonempty $ λ ⟨h⟩, h.elim0)⟩ | (n+1) := by rw [nat.cast_succ, ← mk_fin]; exact quotient.sound (fintype.card_eq.1 $ by simp) @[simp] theorem lift_nat_cast (n : ℕ) : lift n = n := by induction n; simp * theorem lift_mk_fin (n : ℕ) : lift (mk (fin n)) = n := by simp theorem fintype_card (α : Type u) [fintype α] : mk α = fintype.card α := by rw [← lift_mk_fin.{u}, ← lift_id (mk α), lift_mk_eq.{u 0 u}]; exact fintype.card_eq.1 (by simp) theorem card_le_of_finset {α} (s : finset α) : (s.card : cardinal) ≤ cardinal.mk α := begin rw (_ : (s.card : cardinal) = cardinal.mk (↑s : set α)), { exact ⟨function.embedding.subtype _⟩ }, rw [cardinal.fintype_card, fintype.card_coe] end @[simp] theorem nat_cast_pow {m n : ℕ} : (↑(pow m n) : cardinal) = m ^ n := by induction n; simp [nat.pow_succ, -_root_.add_comm, power_add, *] @[simp] theorem nat_cast_le {m n : ℕ} : (m : cardinal) ≤ n ↔ m ≤ n := by rw [← lift_mk_fin, ← lift_mk_fin, lift_le]; exact ⟨λ ⟨⟨f, hf⟩⟩, begin have : _ = fintype.card _ := finset.card_image_of_injective finset.univ hf, simp at this, rw [← fintype.card_fin n, ← this], exact finset.card_le_of_subset (finset.subset_univ _) end, λ h, ⟨⟨λ i, ⟨i.1, lt_of_lt_of_le i.2 h⟩, λ a b h, have _, from fin.veq_of_eq h, fin.eq_of_veq this⟩⟩⟩ @[simp] theorem nat_cast_lt {m n : ℕ} : (m : cardinal) < n ↔ m < n := by simp [lt_iff_le_not_le, -not_le] @[simp] theorem nat_cast_inj {m n : ℕ} : (m : cardinal) = n ↔ m = n := by simp [le_antisymm_iff] @[simp] theorem nat_succ (n : ℕ) : succ n = n.succ := le_antisymm (succ_le.2 $ nat_cast_lt.2 $ nat.lt_succ_self _) (add_one_le_succ _) @[simp] theorem succ_zero : succ 0 = 1 := by simpa using nat_succ 0 theorem cantor' (a) {b : cardinal} (hb : 1 < b) : a < b ^ a := by rw [← succ_le, (by simpa using nat_succ 1 : succ 1 = 2)] at hb; exact lt_of_lt_of_le (cantor _) (power_le_power_right hb) theorem one_le_iff_pos {c : cardinal} : 1 ≤ c ↔ 0 < c := by rw [← succ_zero, succ_le] theorem one_le_iff_ne_zero {c : cardinal} : 1 ≤ c ↔ c ≠ 0 := by rw [one_le_iff_pos, pos_iff_ne_zero] theorem nat_lt_omega (n : ℕ) : (n : cardinal.{u}) < omega := succ_le.1 $ by rw [nat_succ, ← lift_mk_fin, omega, lift_mk_le.{0 0 u}]; exact ⟨⟨fin.val, λ a b, fin.eq_of_veq⟩⟩ theorem one_lt_omega : 1 < omega := by simpa using nat_lt_omega 1 theorem lt_omega {c : cardinal.{u}} : c < omega ↔ ∃ n : ℕ, c = n := ⟨λ h, begin rcases lt_lift_iff.1 h with ⟨c, rfl, h'⟩, rcases le_mk_iff_exists_set.1 h'.1 with ⟨S, rfl⟩, suffices : finite S, { cases this, resetI, existsi fintype.card S, rw [← lift_nat_cast.{0 u}, lift_inj, fintype_card S] }, by_contra nf, have P : ∀ (n : ℕ) (IH : ∀ i<n, S), ∃ a : S, ¬ ∃ y h, IH y h = a := λ n IH, let g : {i | i < n} → S := λ ⟨i, h⟩, IH i h in classical.not_forall.1 (λ h, nf ⟨fintype.of_surjective g (λ a, subtype.exists.2 (h a))⟩), let F : ℕ → S := nat.lt_wf.fix (λ n IH, classical.some (P n IH)), refine not_le_of_lt h' ⟨⟨F, _⟩⟩, suffices : ∀ (n : ℕ) (m < n), F m ≠ F n, { refine λ m n, not_imp_not.1 (λ ne, _), rcases lt_trichotomy m n with h|h|h, { exact this n m h }, { contradiction }, { exact (this m n h).symm } }, intros n m h, have := classical.some_spec (P n (λ y _, F y)), rw [← show F n = classical.some (P n (λ y _, F y)), from nat.lt_wf.fix_eq (λ n IH, classical.some (P n IH)) n] at this, exact λ e, this ⟨m, h, e⟩, end, λ ⟨n, e⟩, e.symm ▸ nat_lt_omega _⟩ theorem omega_le {c : cardinal.{u}} : omega ≤ c ↔ ∀ n : ℕ, (n:cardinal) ≤ c := ⟨λ h n, le_trans (le_of_lt (nat_lt_omega _)) h, λ h, le_of_not_lt $ λ hn, begin rcases lt_omega.1 hn with ⟨n, rfl⟩, exact not_le_of_lt (nat.lt_succ_self _) (nat_cast_le.1 (h (n+1))) end⟩ theorem lt_omega_iff_fintype {α : Type u} : mk α < omega ↔ nonempty (fintype α) := lt_omega.trans ⟨λ ⟨n, e⟩, begin rw [← lift_mk_fin n] at e, cases quotient.exact e with f, exact ⟨fintype.of_equiv _ f.symm⟩ end, λ ⟨_⟩, by exactI ⟨_, fintype_card _⟩⟩ theorem lt_omega_iff_finite {α} {S : set α} : mk S < omega ↔ finite S := lt_omega_iff_fintype theorem add_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a + b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_omega end theorem mul_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a * b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_mul]; apply nat_lt_omega end theorem power_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a ^ b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_pow]; apply nat_lt_omega end /-- König's theorem -/ theorem sum_lt_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i < g i) : sum f < prod g := lt_of_not_ge $ λ ⟨F⟩, begin have : inhabited (Π (i : ι), (g i).out), { refine ⟨λ i, classical.choice $ ne_zero_iff_nonempty.1 _⟩, rw mk_out, exact ne_of_gt (lt_of_le_of_lt (zero_le _) (H i)) }, resetI, let G := inv_fun F, have sG : surjective G := inv_fun_surjective F.2, choose C hc using show ∀ i, ∃ b, ∀ a, G ⟨i, a⟩ i ≠ b, { assume i, simp only [- not_exists, not_exists.symm, classical.not_forall.symm], refine λ h, not_le_of_lt (H i) _, rw [← mk_out (f i), ← mk_out (g i)], exact ⟨embedding.of_surjective h⟩ }, exact (let ⟨⟨i, a⟩, h⟩ := sG C in hc i a (congr_fun h _)) end @[simp] theorem mk_empty : mk empty = 0 := fintype_card empty @[simp] theorem mk_pempty : mk pempty = 0 := fintype_card pempty @[simp] theorem mk_plift_of_false {p : Prop} (h : ¬ p) : mk (plift p) = 0 := quotient.sound ⟨equiv.plift.trans $ equiv.equiv_pempty h⟩ @[simp] theorem mk_unit : mk unit = 1 := (fintype_card unit).trans nat.cast_one @[simp] theorem mk_punit : mk punit = 1 := (fintype_card punit).trans nat.cast_one @[simp] theorem mk_singleton {α : Type u} (x : α) : mk ({x} : set α) = 1 := quotient.sound ⟨equiv.set.singleton x⟩ @[simp] theorem mk_plift_of_true {p : Prop} (h : p) : mk (plift p) = 1 := quotient.sound ⟨equiv.plift.trans $ equiv.prop_equiv_punit h⟩ @[simp] theorem mk_bool : mk bool = 2 := quotient.sound ⟨equiv.bool_equiv_punit_sum_punit⟩ @[simp] theorem mk_Prop : mk Prop = 2 := (quotient.sound ⟨equiv.Prop_equiv_bool⟩ : mk Prop = mk bool).trans mk_bool @[simp] theorem mk_option {α : Type u} : mk (option α) = mk α + 1 := quotient.sound ⟨equiv.option_equiv_sum_punit α⟩ theorem mk_list_eq_sum_pow (α : Type u) : mk (list α) = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) := calc mk (list α) = mk (Σ n, vector α n) : quotient.sound ⟨equiv.equiv_sigma_subtype list.length⟩ ... = mk (Σ n, fin n → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n, ⟨vector.nth, vector.of_fn, vector.of_fn_nth, λ f, funext $ vector.nth_of_fn f⟩⟩ ... = mk (Σ n : ℕ, ulift.{u} (fin n) → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n, equiv.arrow_congr equiv.ulift.symm (equiv.refl α)⟩ ... = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) : by simp only [(lift_mk_fin _).symm, lift_mk, power_def, sum_mk] theorem mk_quot_le {α : Type u} {r : α → α → Prop} : mk (quot r) ≤ mk α := mk_le_of_surjective quot.exists_rep theorem mk_quotient_le {α : Type u} {s : setoid α} : mk (quotient s) ≤ mk α := mk_quot_le theorem mk_subtype_le {α : Type u} {s : set α} : mk s ≤ mk α := mk_le_of_injective subtype.val_injective @[simp] theorem mk_emptyc (α : Type u) : mk (∅ : set α) = 0 := quotient.sound ⟨equiv.set.pempty α⟩ theorem mk_univ {α : Type u} : mk (@univ α) = mk α := quotient.sound ⟨equiv.set.univ α⟩ theorem mk_image_le {α β : Type u} {f : α → β} {s : set α} : mk (f '' s) ≤ mk s := mk_le_of_surjective surjective_onto_image theorem mk_range_le {α β : Type u} {f : α → β} {s : set α} : mk (range f) ≤ mk α := mk_le_of_surjective surjective_onto_range theorem mk_eq_of_injective {α β : Type u} {f : α → β} {s : set α} (hf : injective f) : mk (f '' s) = mk s := quotient.sound ⟨(equiv.set.image f s hf).symm⟩ theorem mk_Union_le_sum_mk {α ι : Type u} {f : ι → set α} : mk (⋃ i, f i) ≤ sum (λ i, mk (f i)) := calc mk (⋃ i, f i) ≤ mk (Σ i, f i) : let f : (Σ i, f i) → (⋃ i, f i) := λ ⟨i, x, hx⟩, ⟨x, mem_Union.2 ⟨i, hx⟩⟩ in have surjective f := λ ⟨x, hx⟩, let ⟨i, hi⟩ := mem_Union.1 hx in ⟨⟨i, x, hi⟩, rfl⟩, mk_le_of_surjective this ... = sum (λ i, mk (f i)) : (sum_mk _).symm @[simp] lemma finset_card {α : Type u} {s : finset α} : ↑(finset.card s) = mk (↑s : set α) := by rw [fintype_card, nat_cast_inj, fintype.card_coe] theorem mk_union_add_mk_inter {α : Type u} {S T : set α} : mk (S ∪ T : set α) + mk (S ∩ T : set α) = mk S + mk T := quot.sound ⟨equiv.set.union_sum_inter S T⟩ theorem mk_union_of_disjoint {α : Type u} {S T : set α} (H : disjoint S T) : mk (S ∪ T : set α) = mk S + mk T := quot.sound ⟨equiv.set.union (disjoint_iff.1 H)⟩ lemma mk_le_mk_of_subset {α} {s t : set α} (h : s ⊆ t) : mk s ≤ mk t := ⟨ set.embedding_of_subset h ⟩ end cardinal
89de004841e9be1724af8a11f5e181f3890c7f49
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/src/builtin/subtype.lean
505b92b69e53b37fe9b566eaf79bb5f47d7ed239
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
2,196
lean
-- Copyright (c) 2014 Microsoft Corporation. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Leonardo de Moura import macros -- Simulate "subtypes" using Sigma types and proof irrelevance definition subtype (A : (Type U)) (P : A → Bool) := sig x, P x namespace subtype definition rep {A : (Type U)} {P : A → Bool} (a : subtype A P) : A := proj1 a definition abst {A : (Type U)} {P : A → Bool} (r : A) (H : inhabited (subtype A P)) : subtype A P := ε H (λ a, rep a = r) theorem subtype_inhabited {A : (Type U)} {P : A → Bool} (H : ∃ x, P x) : inhabited (subtype A P) := obtain (w : A) (Hw : P w), from H, inhabited_intro (pair w Hw) theorem P_rep {A : (Type U)} {P : A → Bool} (a : subtype A P) : P (rep a) := proj2 a theorem rep_inj {A : (Type U)} {P : A → Bool} {a b : subtype A P} (H : rep a = rep b) : a = b := pairext _ _ H (hproof_irrel (proj2 a) (proj2 b)) theorem ex_abst {A : (Type U)} {P : A → Bool} {r : A} (H : P r) : ∃ a, rep a = r := exists_intro (pair r H) (refl r) theorem abst_rep {A : (Type U)} {P : A → Bool} (H : inhabited (subtype A P)) (a : subtype A P) : abst (rep a) H = a := let s1 : rep (abst (rep a) H) = rep a := @eps_ax (subtype A P) H (λ x, rep x = rep a) a (refl (rep a)) in rep_inj s1 theorem rep_abst {A : (Type U)} {P : A → Bool} (H : inhabited (subtype A P)) : ∀ r, P r → rep (abst r H) = r := take r, assume Hl : P r, @eps_ax (subtype A P) H (λ x, rep x = r) (pair r Hl) (refl r) theorem abst_inj {A : (Type U)} {P : A → Bool} (H : inhabited (subtype A P)) {r r' : A} : P r → P r' → abst r H = abst r' H → r = r' := assume Hr Hr' Heq, calc r = rep (abst r H) : symm (rep_abst H r Hr) ... = rep (abst r' H) : { Heq } ... = r' : rep_abst H r' Hr' theorem ex_rep {A : (Type U)} {P : A → Bool} (H : inhabited (subtype A P)) : ∀ a, ∃ r, abst r H = a ∧ P r := take a, exists_intro (rep a) (and_intro (abst_rep H a) (proj2 a)) set_opaque rep true set_opaque abst true end -- namespace subtype set_opaque subtype true
61f449c1b76bf55f064a756713dbd1013782bf27
4727251e0cd73359b15b664c3170e5d754078599
/src/field_theory/perfect_closure.lean
e361fc583710104de050007b338ea9fc8102cae1
[ "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
17,836
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Yury Kudryashov -/ import algebra.char_p.basic import algebra.group_with_zero.power import algebra.hom.iterate import algebra.ring.equiv /-! # The perfect closure of a field -/ universes u v open function section defs variables (R : Type u) [comm_semiring R] (p : ℕ) [fact p.prime] [char_p R p] /-- A perfect ring is a ring of characteristic p that has p-th root. -/ class perfect_ring : Type u := (pth_root' : R → R) (frobenius_pth_root' : ∀ x, frobenius R p (pth_root' x) = x) (pth_root_frobenius' : ∀ x, pth_root' (frobenius R p x) = x) /-- Frobenius automorphism of a perfect ring. -/ def frobenius_equiv [perfect_ring R p] : R ≃+* R := { inv_fun := perfect_ring.pth_root' p, left_inv := perfect_ring.pth_root_frobenius', right_inv := perfect_ring.frobenius_pth_root', .. frobenius R p } /-- `p`-th root of an element in a `perfect_ring` as a `ring_hom`. -/ def pth_root [perfect_ring R p] : R →+* R := (frobenius_equiv R p).symm end defs section variables {R : Type u} [comm_semiring R] {S : Type v} [comm_semiring S] (f : R →* S) (g : R →+* S) {p : ℕ} [fact p.prime] [char_p R p] [perfect_ring R p] [char_p S p] [perfect_ring S p] @[simp] lemma coe_frobenius_equiv : ⇑(frobenius_equiv R p) = frobenius R p := rfl @[simp] lemma coe_frobenius_equiv_symm : ⇑(frobenius_equiv R p).symm = pth_root R p := rfl @[simp] theorem frobenius_pth_root (x : R) : frobenius R p (pth_root R p x) = x := (frobenius_equiv R p).apply_symm_apply x @[simp] theorem pth_root_pow_p (x : R) : pth_root R p x ^ p = x := frobenius_pth_root x @[simp] theorem pth_root_frobenius (x : R) : pth_root R p (frobenius R p x) = x := (frobenius_equiv R p).symm_apply_apply x @[simp] theorem pth_root_pow_p' (x : R) : pth_root R p (x ^ p) = x := pth_root_frobenius x theorem left_inverse_pth_root_frobenius : left_inverse (pth_root R p) (frobenius R p) := pth_root_frobenius theorem right_inverse_pth_root_frobenius : function.right_inverse (pth_root R p) (frobenius R p) := frobenius_pth_root theorem commute_frobenius_pth_root : function.commute (frobenius R p) (pth_root R p) := λ x, (frobenius_pth_root x).trans (pth_root_frobenius x).symm theorem eq_pth_root_iff {x y : R} : x = pth_root R p y ↔ frobenius R p x = y := (frobenius_equiv R p).to_equiv.eq_symm_apply theorem pth_root_eq_iff {x y : R} : pth_root R p x = y ↔ x = frobenius R p y := (frobenius_equiv R p).to_equiv.symm_apply_eq theorem monoid_hom.map_pth_root (x : R) : f (pth_root R p x) = pth_root S p (f x) := eq_pth_root_iff.2 $ by rw [← f.map_frobenius, frobenius_pth_root] theorem monoid_hom.map_iterate_pth_root (x : R) (n : ℕ) : f (pth_root R p^[n] x) = (pth_root S p^[n] (f x)) := semiconj.iterate_right f.map_pth_root n x theorem ring_hom.map_pth_root (x : R) : g (pth_root R p x) = pth_root S p (g x) := g.to_monoid_hom.map_pth_root x theorem ring_hom.map_iterate_pth_root (x : R) (n : ℕ) : g (pth_root R p^[n] x) = (pth_root S p^[n] (g x)) := g.to_monoid_hom.map_iterate_pth_root x n variables (p) lemma injective_pow_p {x y : R} (hxy : x ^ p = y ^ p) : x = y := left_inverse_pth_root_frobenius.injective hxy end section variables (K : Type u) [comm_ring K] (p : ℕ) [fact p.prime] [char_p K p] /-- `perfect_closure K p` is the quotient by this relation. -/ @[mk_iff] inductive perfect_closure.r : (ℕ × K) → (ℕ × K) → Prop | intro : ∀ n x, perfect_closure.r (n, x) (n+1, frobenius K p x) /-- The perfect closure is the smallest extension that makes frobenius surjective. -/ def perfect_closure : Type u := quot (perfect_closure.r K p) end namespace perfect_closure variables (K : Type u) section ring variables [comm_ring K] (p : ℕ) [fact p.prime] [char_p K p] /-- Constructor for `perfect_closure`. -/ def mk (x : ℕ × K) : perfect_closure K p := quot.mk (r K p) x @[simp] lemma quot_mk_eq_mk (x : ℕ × K) : (quot.mk (r K p) x : perfect_closure K p) = mk K p x := rfl variables {K p} /-- Lift a function `ℕ × K → L` to a function on `perfect_closure K p`. -/ @[elab_as_eliminator] def lift_on {L : Type*} (x : perfect_closure K p) (f : ℕ × K → L) (hf : ∀ x y, r K p x y → f x = f y) : L := quot.lift_on x f hf @[simp] lemma lift_on_mk {L : Sort*} (f : ℕ × K → L) (hf : ∀ x y, r K p x y → f x = f y) (x : ℕ × K) : (mk K p x).lift_on f hf = f x := rfl @[elab_as_eliminator] lemma induction_on (x : perfect_closure K p) {q : perfect_closure K p → Prop} (h : ∀ x, q (mk K p x)) : q x := quot.induction_on x h variables (K p) private lemma mul_aux_left (x1 x2 y : ℕ × K) (H : r K p x1 x2) : mk K p (x1.1 + y.1, ((frobenius K p)^[y.1] x1.2) * ((frobenius K p)^[x1.1] y.2)) = mk K p (x2.1 + y.1, ((frobenius K p)^[y.1] x2.2) * ((frobenius K p)^[x2.1] y.2)) := match x1, x2, H with | _, _, r.intro n x := quot.sound $ by rw [← iterate_succ_apply, iterate_succ', iterate_succ', ← frobenius_mul, nat.succ_add]; apply r.intro end private lemma mul_aux_right (x y1 y2 : ℕ × K) (H : r K p y1 y2) : mk K p (x.1 + y1.1, ((frobenius K p)^[y1.1] x.2) * ((frobenius K p)^[x.1] y1.2)) = mk K p (x.1 + y2.1, ((frobenius K p)^[y2.1] x.2) * ((frobenius K p)^[x.1] y2.2)) := match y1, y2, H with | _, _, r.intro n y := quot.sound $ by rw [← iterate_succ_apply, iterate_succ', iterate_succ', ← frobenius_mul]; apply r.intro end instance : has_mul (perfect_closure K p) := ⟨quot.lift (λ x:ℕ×K, quot.lift (λ y:ℕ×K, mk K p (x.1 + y.1, ((frobenius K p)^[y.1] x.2) * ((frobenius K p)^[x.1] y.2))) (mul_aux_right K p x)) (λ x1 x2 (H : r K p x1 x2), funext $ λ e, quot.induction_on e $ λ y, mul_aux_left K p x1 x2 y H)⟩ @[simp] lemma mk_mul_mk (x y : ℕ × K) : mk K p x * mk K p y = mk K p (x.1 + y.1, ((frobenius K p)^[y.1] x.2) * ((frobenius K p)^[x.1] y.2)) := rfl instance : comm_monoid (perfect_closure K p) := { mul_assoc := λ e f g, quot.induction_on e $ λ ⟨m, x⟩, quot.induction_on f $ λ ⟨n, y⟩, quot.induction_on g $ λ ⟨s, z⟩, congr_arg (quot.mk _) $ by simp only [add_assoc, mul_assoc, ring_hom.iterate_map_mul, ← iterate_add_apply, add_comm, add_left_comm], one := mk K p (0, 1), one_mul := λ e, quot.induction_on e (λ ⟨n, x⟩, congr_arg (quot.mk _) $ by simp only [ring_hom.iterate_map_one, iterate_zero_apply, one_mul, zero_add]), mul_one := λ e, quot.induction_on e (λ ⟨n, x⟩, congr_arg (quot.mk _) $ by simp only [ring_hom.iterate_map_one, iterate_zero_apply, mul_one, add_zero]), mul_comm := λ e f, quot.induction_on e (λ ⟨m, x⟩, quot.induction_on f (λ ⟨n, y⟩, congr_arg (quot.mk _) $ by simp only [add_comm, mul_comm])), .. (infer_instance : has_mul (perfect_closure K p)) } lemma one_def : (1 : perfect_closure K p) = mk K p (0, 1) := rfl instance : inhabited (perfect_closure K p) := ⟨1⟩ private lemma add_aux_left (x1 x2 y : ℕ × K) (H : r K p x1 x2) : mk K p (x1.1 + y.1, ((frobenius K p)^[y.1] x1.2) + ((frobenius K p)^[x1.1] y.2)) = mk K p (x2.1 + y.1, ((frobenius K p)^[y.1] x2.2) + ((frobenius K p)^[x2.1] y.2)) := match x1, x2, H with | _, _, r.intro n x := quot.sound $ by rw [← iterate_succ_apply, iterate_succ', iterate_succ', ← frobenius_add, nat.succ_add]; apply r.intro end private lemma add_aux_right (x y1 y2 : ℕ × K) (H : r K p y1 y2) : mk K p (x.1 + y1.1, ((frobenius K p)^[y1.1] x.2) + ((frobenius K p)^[x.1] y1.2)) = mk K p (x.1 + y2.1, ((frobenius K p)^[y2.1] x.2) + ((frobenius K p)^[x.1] y2.2)) := match y1, y2, H with | _, _, r.intro n y := quot.sound $ by rw [← iterate_succ_apply, iterate_succ', iterate_succ', ← frobenius_add]; apply r.intro end instance : has_add (perfect_closure K p) := ⟨quot.lift (λ x:ℕ×K, quot.lift (λ y:ℕ×K, mk K p (x.1 + y.1, ((frobenius K p)^[y.1] x.2) + ((frobenius K p)^[x.1] y.2))) (add_aux_right K p x)) (λ x1 x2 (H : r K p x1 x2), funext $ λ e, quot.induction_on e $ λ y, add_aux_left K p x1 x2 y H)⟩ @[simp] lemma mk_add_mk (x y : ℕ × K) : mk K p x + mk K p y = mk K p (x.1 + y.1, ((frobenius K p)^[y.1] x.2) + ((frobenius K p)^[x.1] y.2)) := rfl instance : has_neg (perfect_closure K p) := ⟨quot.lift (λ x:ℕ×K, mk K p (x.1, -x.2)) (λ x y (H : r K p x y), match x, y, H with | _, _, r.intro n x := quot.sound $ by rw ← frobenius_neg; apply r.intro end)⟩ @[simp] lemma neg_mk (x : ℕ × K) : - mk K p x = mk K p (x.1, -x.2) := rfl instance : has_zero (perfect_closure K p) := ⟨mk K p (0, 0)⟩ lemma zero_def : (0 : perfect_closure K p) = mk K p (0, 0) := rfl theorem mk_zero (n : ℕ) : mk K p (n, 0) = 0 := by induction n with n ih; [refl, rw ← ih]; symmetry; apply quot.sound; have := r.intro n (0:K); rwa [frobenius_zero K p] at this theorem r.sound (m n : ℕ) (x y : K) (H : frobenius K p^[m] x = y) : mk K p (n, x) = mk K p (m + n, y) := by subst H; induction m with m ih; [simp only [zero_add, iterate_zero_apply], rw [ih, nat.succ_add, iterate_succ']]; apply quot.sound; apply r.intro instance : comm_ring (perfect_closure K p) := { add_assoc := λ e f g, quot.induction_on e $ λ ⟨m, x⟩, quot.induction_on f $ λ ⟨n, y⟩, quot.induction_on g $ λ ⟨s, z⟩, congr_arg (quot.mk _) $ by simp only [ring_hom.iterate_map_add, ← iterate_add_apply, add_assoc, add_comm s _], zero := 0, zero_add := λ e, quot.induction_on e (λ ⟨n, x⟩, congr_arg (quot.mk _) $ by simp only [ring_hom.iterate_map_zero, iterate_zero_apply, zero_add]), add_zero := λ e, quot.induction_on e (λ ⟨n, x⟩, congr_arg (quot.mk _) $ by simp only [ring_hom.iterate_map_zero, iterate_zero_apply, add_zero]), sub_eq_add_neg := λ a b, rfl, add_left_neg := λ e, by exact quot.induction_on e (λ ⟨n, x⟩, by simp only [quot_mk_eq_mk, neg_mk, mk_add_mk, ring_hom.iterate_map_neg, add_left_neg, mk_zero]), add_comm := λ e f, quot.induction_on e (λ ⟨m, x⟩, quot.induction_on f (λ ⟨n, y⟩, congr_arg (quot.mk _) $ by simp only [add_comm])), left_distrib := λ e f g, quot.induction_on e $ λ ⟨m, x⟩, quot.induction_on f $ λ ⟨n, y⟩, quot.induction_on g $ λ ⟨s, z⟩, show quot.mk _ _ = quot.mk _ _, by simp only [add_assoc, add_comm, add_left_comm]; apply r.sound; simp only [ring_hom.iterate_map_mul, ring_hom.iterate_map_add, ← iterate_add_apply, mul_add, add_comm, add_left_comm], right_distrib := λ e f g, quot.induction_on e $ λ ⟨m, x⟩, quot.induction_on f $ λ ⟨n, y⟩, quot.induction_on g $ λ ⟨s, z⟩, show quot.mk _ _ = quot.mk _ _, by simp only [add_assoc, add_comm _ s, add_left_comm _ s]; apply r.sound; simp only [ring_hom.iterate_map_mul, ring_hom.iterate_map_add, ← iterate_add_apply, add_mul, add_comm, add_left_comm], .. (infer_instance : has_add (perfect_closure K p)), .. (infer_instance : has_neg (perfect_closure K p)), .. (infer_instance : comm_monoid (perfect_closure K p)) } theorem eq_iff' (x y : ℕ × K) : mk K p x = mk K p y ↔ ∃ z, (frobenius K p^[y.1 + z] x.2) = (frobenius K p^[x.1 + z] y.2) := begin split, { intro H, replace H := quot.exact _ H, induction H, case eqv_gen.rel : x y H { cases H with n x, exact ⟨0, rfl⟩ }, case eqv_gen.refl : H { exact ⟨0, rfl⟩ }, case eqv_gen.symm : x y H ih { cases ih with w ih, exact ⟨w, ih.symm⟩ }, case eqv_gen.trans : x y z H1 H2 ih1 ih2 { cases ih1 with z1 ih1, cases ih2 with z2 ih2, existsi z2+(y.1+z1), rw [← add_assoc, iterate_add_apply, ih1], rw [← iterate_add_apply, add_comm, iterate_add_apply, ih2], rw [← iterate_add_apply], simp only [add_comm, add_left_comm] } }, intro H, cases x with m x, cases y with n y, cases H with z H, dsimp only at H, rw [r.sound K p (n+z) m x _ rfl, r.sound K p (m+z) n y _ rfl, H], rw [add_assoc, add_comm, add_comm z] end theorem nat_cast (n x : ℕ) : (x : perfect_closure K p) = mk K p (n, x) := begin induction n with n ih, { induction x with x ih, {refl}, rw [nat.cast_succ, nat.cast_succ, ih], refl }, rw ih, apply quot.sound, conv {congr, skip, skip, rw ← frobenius_nat_cast K p x}, apply r.intro end theorem int_cast (x : ℤ) : (x : perfect_closure K p) = mk K p (0, x) := by induction x; simp only [int.cast_of_nat, int.cast_neg_succ_of_nat, nat_cast K p 0]; refl theorem nat_cast_eq_iff (x y : ℕ) : (x : perfect_closure K p) = y ↔ (x : K) = y := begin split; intro H, { rw [nat_cast K p 0, nat_cast K p 0, eq_iff'] at H, cases H with z H, simpa only [zero_add, iterate_fixed (frobenius_nat_cast K p _)] using H }, rw [nat_cast K p 0, nat_cast K p 0, H] end instance : char_p (perfect_closure K p) p := begin constructor, intro x, rw ← char_p.cast_eq_zero_iff K, rw [← nat.cast_zero, nat_cast_eq_iff, nat.cast_zero] end theorem frobenius_mk (x : ℕ × K) : (frobenius (perfect_closure K p) p : perfect_closure K p → perfect_closure K p) (mk K p x) = mk _ _ (x.1, x.2^p) := begin simp only [frobenius_def], cases x with n x, dsimp only, suffices : ∀ p':ℕ, mk K p (n, x) ^ p' = mk K p (n, x ^ p'), { apply this }, intro p, induction p with p ih, case nat.zero { apply r.sound, rw [(frobenius _ _).iterate_map_one, pow_zero] }, case nat.succ { rw [pow_succ, ih], symmetry, apply r.sound, simp only [pow_succ, (frobenius _ _).iterate_map_mul] } end /-- Embedding of `K` into `perfect_closure K p` -/ def of : K →+* perfect_closure K p := { to_fun := λ x, mk _ _ (0, x), map_one' := rfl, map_mul' := λ x y, rfl, map_zero' := rfl, map_add' := λ x y, rfl } lemma of_apply (x : K) : of K p x = mk _ _ (0, x) := rfl end ring theorem eq_iff [comm_ring K] [is_domain K] (p : ℕ) [fact p.prime] [char_p K p] (x y : ℕ × K) : quot.mk (r K p) x = quot.mk (r K p) y ↔ (frobenius K p^[y.1] x.2) = (frobenius K p^[x.1] y.2) := (eq_iff' K p x y).trans ⟨λ ⟨z, H⟩, (frobenius_inj K p).iterate z $ by simpa only [add_comm, iterate_add] using H, λ H, ⟨0, H⟩⟩ section field variables [field K] (p : ℕ) [fact p.prime] [char_p K p] instance : has_inv (perfect_closure K p) := ⟨quot.lift (λ x:ℕ×K, quot.mk (r K p) (x.1, x.2⁻¹)) (λ x y (H : r K p x y), match x, y, H with | _, _, r.intro n x := quot.sound $ by { simp only [frobenius_def], rw ← inv_pow₀, apply r.intro } end)⟩ instance : field (perfect_closure K p) := { exists_pair_ne := ⟨0, 1, λ H, zero_ne_one ((eq_iff _ _ _ _).1 H)⟩, mul_inv_cancel := λ e, induction_on e $ λ ⟨m, x⟩ H, have _ := mt (eq_iff _ _ _ _).2 H, (eq_iff _ _ _ _).2 (by simp only [(frobenius _ _).iterate_map_one, (frobenius K p).iterate_map_zero, iterate_zero_apply, ← (frobenius _ p).iterate_map_mul] at this ⊢; rw [mul_inv_cancel this, (frobenius _ _).iterate_map_one]), inv_zero := congr_arg (quot.mk (r K p)) (by rw [inv_zero]), .. (infer_instance : has_inv (perfect_closure K p)), .. (infer_instance : comm_ring (perfect_closure K p)) } instance : perfect_ring (perfect_closure K p) p := { pth_root' := λ e, lift_on e (λ x, mk K p (x.1 + 1, x.2)) (λ x y H, match x, y, H with | _, _, r.intro n x := quot.sound (r.intro _ _) end), frobenius_pth_root' := λ e, induction_on e (λ ⟨n, x⟩, by { simp only [lift_on_mk, frobenius_mk], exact (quot.sound $ r.intro _ _).symm }), pth_root_frobenius' := λ e, induction_on e (λ ⟨n, x⟩, by { simp only [lift_on_mk, frobenius_mk], exact (quot.sound $ r.intro _ _).symm }) } theorem eq_pth_root (x : ℕ × K) : mk K p x = (pth_root (perfect_closure K p) p^[x.1] (of K p x.2)) := begin rcases x with ⟨m, x⟩, induction m with m ih, {refl}, rw [iterate_succ_apply', ← ih]; refl end /-- Given a field `K` of characteristic `p` and a perfect ring `L` of the same characteristic, any homomorphism `K →+* L` can be lifted to `perfect_closure K p`. -/ def lift (L : Type v) [comm_semiring L] [char_p L p] [perfect_ring L p] : (K →+* L) ≃ (perfect_closure K p →+* L) := begin have := left_inverse_pth_root_frobenius.iterate, refine_struct { .. }, field to_fun { intro f, refine_struct { .. }, field to_fun { refine λ e, lift_on e (λ x, pth_root L p^[x.1] (f x.2)) _, rintro a b ⟨n⟩, simp only [f.map_frobenius, iterate_succ_apply, pth_root_frobenius] }, field map_one' { exact f.map_one }, field map_zero' { exact f.map_zero }, field map_mul' { rintro ⟨x⟩ ⟨y⟩, simp only [quot_mk_eq_mk, lift_on_mk, mk_mul_mk, ring_hom.map_iterate_frobenius, ring_hom.iterate_map_mul, ring_hom.map_mul], rw [iterate_add_apply, this _ _, add_comm, iterate_add_apply, this _ _] }, field map_add' { rintro ⟨x⟩ ⟨y⟩, simp only [quot_mk_eq_mk, lift_on_mk, mk_add_mk, ring_hom.map_iterate_frobenius, ring_hom.iterate_map_add, ring_hom.map_add], rw [iterate_add_apply, this _ _, add_comm x.1, iterate_add_apply, this _ _] } }, field inv_fun { exact λ f, f.comp (of K p) }, field left_inv { intro f, ext x, refl }, field right_inv { intro f, ext ⟨x⟩, simp only [ring_hom.coe_mk, quot_mk_eq_mk, ring_hom.comp_apply, lift_on_mk], rw [eq_pth_root, ring_hom.map_iterate_pth_root] } end end field end perfect_closure /-- A reduced ring with prime characteristic and surjective frobenius map is perfect. -/ noncomputable def perfect_ring.of_surjective (k : Type*) [comm_ring k] [is_reduced k] (p : ℕ) [fact p.prime] [char_p k p] (h : function.surjective $ frobenius k p) : perfect_ring k p := { pth_root' := function.surj_inv h, frobenius_pth_root' := function.surj_inv_eq h, pth_root_frobenius' := λ x, frobenius_inj _ _ $ function.surj_inv_eq h _ }
88cd3d38e50780c78fa1cefe59fda8b602f7efd9
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/dep_coe_to_fn3.lean
46c39be0e35265d526072dcb4d44c597644c6e65
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
723
lean
universe variables u v structure Func := (A : Type u) (B : A → Type v) (fn : Π a, B a → B a) instance F_to_fn : has_coe_to_fun Func := { F := λ f, Π a, f^.B a → f^.B a, coe := λ f a b, f^.fn a (f^.fn a b) } variables (f : Func) (a : f^.A) (b : f^.B a) #check (f a b) def f1 : Func := { A := nat, B := λ a, nat, fn := (+) } -- set_option trace.type_context.is_def_eq_detail true /- We need to mark 10 as a nat. Reason: f1 is not reducible, then type class resolution cannot find an instance for `has_one (Func.A f1)` -/ example : f1 (10:nat) (30:nat) = (50:nat) := rfl /- #exit attribute [reducible] f1 example : f1 10 30 = 50 := rfl example (n m : nat) : f1 n m = n + (n + m) := rfl -/
7ded622df488cee874f9291f3ebd2dc49c4e423e
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/logic/nonempty.lean
cc3a00fc6312e0868fcec3ac574a38cb82488624
[ "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
5,445
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import logic.basic /-! # Nonempty types This file proves a few extra facts about `nonempty`, which is defined in core Lean. ## Main declarations * `nonempty.some`: Extracts a witness of nonemptiness using choice. Takes `nonempty α` explicitly. * `classical.arbitrary`: Extracts a witness of nonemptiness using choice. Takes `nonempty α` as an instance. -/ variables {α β : Type*} {γ : α → Type*} attribute [simp] nonempty_of_inhabited @[priority 20] instance has_zero.nonempty [has_zero α] : nonempty α := ⟨0⟩ @[priority 20] instance has_one.nonempty [has_one α] : nonempty α := ⟨1⟩ lemma exists_true_iff_nonempty {α : Sort*} : (∃a:α, true) ↔ nonempty α := iff.intro (λ⟨a, _⟩, ⟨a⟩) (λ⟨a⟩, ⟨a, trivial⟩) @[simp] lemma nonempty_Prop {p : Prop} : nonempty p ↔ p := iff.intro (assume ⟨h⟩, h) (assume h, ⟨h⟩) lemma not_nonempty_iff_imp_false {α : Sort*} : ¬ nonempty α ↔ α → false := ⟨λ h a, h ⟨a⟩, λ h ⟨a⟩, h a⟩ @[simp] lemma nonempty_sigma : nonempty (Σa:α, γ a) ↔ (∃a:α, nonempty (γ a)) := iff.intro (assume ⟨⟨a, c⟩⟩, ⟨a, ⟨c⟩⟩) (assume ⟨a, ⟨c⟩⟩, ⟨⟨a, c⟩⟩) @[simp] lemma nonempty_subtype {α} {p : α → Prop} : nonempty (subtype p) ↔ (∃a:α, p a) := iff.intro (assume ⟨⟨a, h⟩⟩, ⟨a, h⟩) (assume ⟨a, h⟩, ⟨⟨a, h⟩⟩) @[simp] lemma nonempty_prod : nonempty (α × β) ↔ (nonempty α ∧ nonempty β) := iff.intro (assume ⟨⟨a, b⟩⟩, ⟨⟨a⟩, ⟨b⟩⟩) (assume ⟨⟨a⟩, ⟨b⟩⟩, ⟨⟨a, b⟩⟩) @[simp] lemma nonempty_pprod {α β} : nonempty (pprod α β) ↔ (nonempty α ∧ nonempty β) := iff.intro (assume ⟨⟨a, b⟩⟩, ⟨⟨a⟩, ⟨b⟩⟩) (assume ⟨⟨a⟩, ⟨b⟩⟩, ⟨⟨a, b⟩⟩) @[simp] lemma nonempty_sum : nonempty (α ⊕ β) ↔ (nonempty α ∨ nonempty β) := iff.intro (assume ⟨h⟩, match h with sum.inl a := or.inl ⟨a⟩ | sum.inr b := or.inr ⟨b⟩ end) (assume h, match h with or.inl ⟨a⟩ := ⟨sum.inl a⟩ | or.inr ⟨b⟩ := ⟨sum.inr b⟩ end) @[simp] lemma nonempty_psum {α β} : nonempty (psum α β) ↔ (nonempty α ∨ nonempty β) := iff.intro (assume ⟨h⟩, match h with psum.inl a := or.inl ⟨a⟩ | psum.inr b := or.inr ⟨b⟩ end) (assume h, match h with or.inl ⟨a⟩ := ⟨psum.inl a⟩ | or.inr ⟨b⟩ := ⟨psum.inr b⟩ end) @[simp] lemma nonempty_psigma {α} {β : α → Sort*} : nonempty (psigma β) ↔ (∃a:α, nonempty (β a)) := iff.intro (assume ⟨⟨a, c⟩⟩, ⟨a, ⟨c⟩⟩) (assume ⟨a, ⟨c⟩⟩, ⟨⟨a, c⟩⟩) @[simp] lemma nonempty_empty : ¬ nonempty empty := assume ⟨h⟩, h.elim @[simp] lemma nonempty_ulift : nonempty (ulift α) ↔ nonempty α := iff.intro (assume ⟨⟨a⟩⟩, ⟨a⟩) (assume ⟨a⟩, ⟨⟨a⟩⟩) @[simp] lemma nonempty_plift {α} : nonempty (plift α) ↔ nonempty α := iff.intro (assume ⟨⟨a⟩⟩, ⟨a⟩) (assume ⟨a⟩, ⟨⟨a⟩⟩) @[simp] lemma nonempty.forall {α} {p : nonempty α → Prop} : (∀h:nonempty α, p h) ↔ (∀a, p ⟨a⟩) := iff.intro (assume h a, h _) (assume h ⟨a⟩, h _) @[simp] lemma nonempty.exists {α} {p : nonempty α → Prop} : (∃h:nonempty α, p h) ↔ (∃a, p ⟨a⟩) := iff.intro (assume ⟨⟨a⟩, h⟩, ⟨a, h⟩) (assume ⟨a, h⟩, ⟨⟨a⟩, h⟩) lemma classical.nonempty_pi {α} {β : α → Sort*} : nonempty (Πa:α, β a) ↔ (∀a:α, nonempty (β a)) := iff.intro (assume ⟨f⟩ a, ⟨f a⟩) (assume f, ⟨assume a, classical.choice $ f a⟩) /-- Using `classical.choice`, lifts a (`Prop`-valued) `nonempty` instance to a (`Type`-valued) `inhabited` instance. `classical.inhabited_of_nonempty` already exists, in `core/init/classical.lean`, but the assumption is not a type class argument, which makes it unsuitable for some applications. -/ noncomputable def classical.inhabited_of_nonempty' {α} [h : nonempty α] : inhabited α := ⟨classical.choice h⟩ /-- Using `classical.choice`, extracts a term from a `nonempty` type. -/ @[reducible] protected noncomputable def nonempty.some {α} (h : nonempty α) : α := classical.choice h /-- Using `classical.choice`, extracts a term from a `nonempty` type. -/ @[reducible] protected noncomputable def classical.arbitrary (α) [h : nonempty α] : α := classical.choice h /-- Given `f : α → β`, if `α` is nonempty then `β` is also nonempty. `nonempty` cannot be a `functor`, because `functor` is restricted to `Type`. -/ lemma nonempty.map {α β} (f : α → β) : nonempty α → nonempty β | ⟨h⟩ := ⟨f h⟩ protected lemma nonempty.map2 {α β γ : Sort*} (f : α → β → γ) : nonempty α → nonempty β → nonempty γ | ⟨x⟩ ⟨y⟩ := ⟨f x y⟩ protected lemma nonempty.congr {α β} (f : α → β) (g : β → α) : nonempty α ↔ nonempty β := ⟨nonempty.map f, nonempty.map g⟩ lemma nonempty.elim_to_inhabited {α : Sort*} [h : nonempty α] {p : Prop} (f : inhabited α → p) : p := h.elim $ f ∘ inhabited.mk instance {α β} [h : nonempty α] [h2 : nonempty β] : nonempty (α × β) := h.elim $ λ g, h2.elim $ λ g2, ⟨⟨g, g2⟩⟩ lemma subsingleton_of_not_nonempty {α : Sort*} (h : ¬ nonempty α) : subsingleton α := ⟨λ x, false.elim $ not_nonempty_iff_imp_false.mp h x⟩
a0a8f884bb3c5765f571330dc2766a583077356c
c777c32c8e484e195053731103c5e52af26a25d1
/archive/100-theorems-list/57_herons_formula.lean
7d288df537ac0a1edc58a69893206ee25f5f3443
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
2,813
lean
/- Copyright (c) 2021 Matt Kempster. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Matt Kempster -/ import geometry.euclidean.triangle /-! # Freek № 57: Heron's Formula This file proves Theorem 57 from the [100 Theorems List](https://www.cs.ru.nl/~freek/100/), also known as Heron's formula, which gives the area of a triangle based only on its three sides' lengths. ## References * https://en.wikipedia.org/wiki/Herons_formula -/ open real euclidean_geometry open_locale real euclidean_geometry local notation `√` := real.sqrt variables {V : Type*} {P : Type*} [normed_add_comm_group V] [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] include V /-- **Heron's formula**: The area of a triangle with side lengths `a`, `b`, and `c` is `√(s * (s - a) * (s - b) * (s - c))` where `s = (a + b + c) / 2` is the semiperimeter. We show this by equating this formula to `a * b * sin γ`, where `γ` is the angle opposite the side `c`. -/ theorem heron {p1 p2 p3 : P} (h1 : p1 ≠ p2) (h2 : p3 ≠ p2) : let a := dist p1 p2, b := dist p3 p2, c := dist p1 p3, s := (a + b + c) / 2 in 1/2 * a * b * sin (∠ p1 p2 p3) = √(s * (s - a) * (s - b) * (s - c)) := begin intros a b c s, let γ := ∠ p1 p2 p3, obtain := ⟨(dist_pos.mpr h1).ne', (dist_pos.mpr h2).ne'⟩, have cos_rule : cos γ = (a * a + b * b - c * c) / (2 * a * b) := by field_simp [mul_comm, a, dist_sq_eq_dist_sq_add_dist_sq_sub_two_mul_dist_mul_dist_mul_cos_angle p1 p2 p3], let numerator := (2*a*b)^2 - (a*a + b*b - c*c)^2, let denominator := (2*a*b)^2, have split_to_frac : 1 - cos γ ^ 2 = numerator / denominator := by field_simp [cos_rule], have numerator_nonneg : 0 ≤ numerator, { have frac_nonneg: 0 ≤ numerator / denominator := by linarith [split_to_frac, cos_sq_le_one γ], cases div_nonneg_iff.mp frac_nonneg, { exact h.left }, { simpa [h1, h2] using le_antisymm h.right (sq_nonneg _) } }, have ab2_nonneg : 0 ≤ (2 * a * b) := by norm_num [mul_nonneg, dist_nonneg], calc 1/2 * a * b * sin γ = 1/2 * a * b * (√numerator / √denominator) : by rw [sin_eq_sqrt_one_sub_cos_sq, split_to_frac, sqrt_div numerator_nonneg]; simp [angle_nonneg, angle_le_pi] ... = 1/4 * √((2*a*b)^2 - (a*a + b*b - c*c)^2) : by { field_simp [ab2_nonneg], ring } ... = 1/4 * √(s * (s-a) * (s-b) * (s-c) * 4^2) : by { simp only [s], ring_nf } ... = √(s * (s-a) * (s-b) * (s-c)) : by rw [sqrt_mul', sqrt_sq, div_mul_eq_mul_div, one_mul, mul_div_cancel]; norm_num, end
3ef1076944ea6e930bf13465e240a540d22d4e68
f68c8823d8ddc719de8a4513815174aa7408ac4a
/lean_resolutions/PUZ135_2.lean
ad2bccc8c5e808029b549072d9ea594cefa42312
[]
no_license
FredsoNerd/tptp-lean-puzzles
e7ea66a0de9aa3cb7cc7480299f01adf885440a6
43d4d77524e797a4ac7a62b2cfaf8df08b409815
refs/heads/master
1,606,359,611,765
1,576,824,274,000
1,576,824,274,000
228,945,807
4
0
null
null
null
null
UTF-8
Lean
false
false
5,055
lean
------------------------------------------------------------------------------ -- File : PUZ135_2 : TPTP v7.3.0. Released v5.1.0. -- Domain : Puzzles -- Problem : The Knowheyan Art Fair Puzzle - Order -- Version : Especial. -- English : Knowheyans are not negative by nature; it is just that their way -- of expressing themselves, using negative sentences, makes it -- appear that way. Several fortunate visitors have an opportunity -- to attend the Midseason Art Fair, in which they are able to -- observe a variety of Knowheyans art forms. An artists' competition -- was held as part of the fair and awards were given for the top -- four entries, which were collage painting, holography, laser -- etchings, and reconstituted materials sculpture. The interpreter -- is explaining the results of the competition to the visitors: -- 1. A, who was not the first-place winner, did not enter a -- holograph. -- 2. The fourth-place winner did not enter a sculpture or a -- holograph. -- 3. The one who entered the collage painting, who was neither A -- nor C, did not win first or second place. -- 4. Neither B, nor the one who entered the laser etching, was the -- fourth-place winner. -- 5. The third-place winner was neither B nor C. -- 6. The one who entered the laser etching, who was not A, was not -- the second place winner. -- In what order did they finish? -- Refs : [WS+06] Willis et al. (2006), The World's Biggest Book of Brai -- Source : [TPTP] -------------------------------------------------------------------------------- variable knowheyan: Type variable place: Type variable entry: Type variable entry_of: knowheyan → entry variable place_of: knowheyan → place variable a: knowheyan variable b: knowheyan variable c: knowheyan variable d: knowheyan variable a_not_b: a ≠ b variable a_not_c: a ≠ c variable a_not_d: a ≠ d variable b_not_c: b ≠ c variable b_not_d: b ≠ d variable c_not_d: c ≠ d variable collage_painting: entry variable holography: entry variable laser_etching: entry variable reconstituted_materials_sculpture: entry -- axioms variable collage_painting_not_holography: collage_painting ≠ holography variable collage_painting_not_laser_etching: collage_painting ≠ laser_etching variable collage_painting_not_reconstituted_materials_sculpture: collage_painting ≠ reconstituted_materials_sculpture variable holography_not_laser_etching: holography ≠ laser_etching variable holography_not_reconstituted_materials_sculpture: holography ≠ reconstituted_materials_sculpture variable laser_etching_not_reconstituted_materials_sculpture: laser_etching ≠ reconstituted_materials_sculpture variable first: place variable second: place variable third: place variable fourth: place variable first_not_second: first ≠ second variable first_not_third: first ≠ third variable first_not_fourth: first ≠ fourth variable second_not_third: second ≠ third variable second_not_fourth: second ≠ fourth variable third_not_fourth: third ≠ fourth variable only_knowheyans: ∀ (X: knowheyan) , ( X = a ∨ X = b ∨ X = c ∨ X = d ) variable only_entries: ∀ (X: entry) , ( X = collage_painting ∨ X = holography ∨ X = laser_etching ∨ X = reconstituted_materials_sculpture ) variable only_places: ∀ (X: place) , ( X = first ∨ X = second ∨ X = third ∨ X = fourth ) variable unique_entrys: ∀ (X: knowheyan)(Y: knowheyan) , ( X ≠ Y → entry_of(X) ≠ entry_of(Y) ) variable unique_places: ∀ (X: knowheyan)(Y: knowheyan) , ( X ≠ Y → place_of(X) ≠ place_of(Y) ) variable a_info: ( place_of(a) ≠ first ∧ entry_of(a) ≠ holography ) variable fourth_info: ∀ (X: knowheyan) , ( place_of(X) = fourth → ( entry_of(X) ≠ reconstituted_materials_sculpture ∧ entry_of(X) ≠ holography )) variable collage_info: ∀ (X: knowheyan) , ( entry_of(X) = collage_painting → ( X ≠ a ∧ X ≠ c ∧ place_of(X) ≠ first ∧ place_of(X) ≠ second ) ) variable fourth_info2: ( place_of(b) ≠ fourth ∧ ∀ (X: knowheyan) , ( entry_of(X) = laser_etching → place_of(X) ≠ fourth ) ) variable third_info: ( place_of(b) ≠ third ∧ place_of(c) ≠ third ) variable laser_etching_info: ( entry_of(b) ≠ laser_etching ∧ ∀ (X: knowheyan) , ( entry_of(X) = laser_etching → ( X ≠ a ∧ place_of(X) ≠ second ) ) ) -- conjecture : places theorem places : ( place_of(a) = third ∧ place_of(b) = second ∧ place_of(c) = first ∧ place_of(d) = fourth ) := sorry
ad8b51696ffd905cae1fa67aae02fd323c719fa2
fecda8e6b848337561d6467a1e30cf23176d6ad0
/src/data/num/lemmas.lean
80eac51e7aa28d731da7c16712ac8138c2f0e3b4
[ "Apache-2.0" ]
permissive
spolu/mathlib
bacf18c3d2a561d00ecdc9413187729dd1f705ed
480c92cdfe1cf3c2d083abded87e82162e8814f4
refs/heads/master
1,671,684,094,325
1,600,736,045,000
1,600,736,045,000
297,564,749
1
0
null
1,600,758,368,000
1,600,758,367,000
null
UTF-8
Lean
false
false
48,656
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 import data.nat.psub /-! # 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) ((n:ℕ) < m) : 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) ((n:ℕ) < m) : 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 _)] instance : has_dvd pos_num := ⟨λ m n, pos m ∣ pos n⟩ @[norm_cast] theorem dvd_to_nat {m n : pos_num} : (m:ℕ) ∣ n ↔ m ∣ n := num.dvd_to_nat (pos m) (pos n) 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 : 1 < n) : (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) ((n:ℤ) < m) : 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_dvd : decidable_rel ((∣) : num → num → Prop) | a b := decidable_of_iff' _ dvd_iff_mod_eq_zero end num instance pos_num.decidable_dvd : decidable_rel ((∣) : pos_num → pos_num → Prop) | a b := num.decidable_dvd _ _ 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⟩
825b88936b5cf5a4745b9e5dd096dc8c19bf3563
94e33a31faa76775069b071adea97e86e218a8ee
/src/analysis/complex/abs_max.lean
9f82194df62d3172dbd299952bb11e813337222b
[ "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
22,001
lean
/- Copyright (c) 2022 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import analysis.complex.cauchy_integral import analysis.convex.integral import analysis.normed_space.completion import analysis.normed_space.extr import topology.algebra.order.extr_closure /-! # Maximum modulus principle In this file we prove several versions of the maximum modulus principle. There are several statements that can be called "the maximum modulus principle" for maps between normed complex spaces. They differ by assumptions on the domain (any space, a nontrivial space, a finite dimensional space), assumptions on the codomain (any space, a strictly convex space), and by conclusion (either equality of norms or of the values of the function). ## Main results ### Theorems for any codomain Consider a function `f : E → F` that is complex differentiable on a set `s`, is continuous on its closure, and `∥f x∥` has a maximum on `s` at `c`. We prove the following theorems. - `complex.norm_eq_on_closed_ball_of_is_max_on`: if `s = metric.ball c r`, then `∥f x∥ = ∥f c∥` for any `x` from the corresponding closed ball; - `complex.norm_eq_norm_of_is_max_on_of_ball_subset`: if `metric.ball c (dist w c) ⊆ s`, then `∥f w∥ = ∥f c∥`; - `complex.norm_eq_on_of_is_preconnected_of_is_max_on`: if `U` is an open (pre)connected set, `f` is complex differentiable on `U`, and `∥f x∥` has a maximum on `U` at `c ∈ U`, then `∥f x∥ = ∥f c∥` for all `x ∈ U`; - `complex.norm_eq_on_closure_of_is_preconnected_of_is_max_on`: if `s` is open and (pre)connected and `c ∈ s`, then `∥f x∥ = ∥f c∥` for all `x ∈ closure s`; - `complex.norm_eventually_eq_of_is_local_max`: if `f` is complex differentiable in a neighborhood of `c` and `∥f x∥` has a local maximum at `c`, then `∥f x∥` is locally a constant in a neighborhood of `c`. ### Theorems for a strictly convex codomain If the codomain `F` is a strictly convex space, then in the lemmas from the previous section we can prove `f w = f c` instead of `∥f w∥ = ∥f c∥`, see `complex.eq_on_of_is_preconnected_of_is_max_on_norm`, `complex.eq_on_closure_of_is_preconnected_of_is_max_on_norm`, `complex.eq_of_is_max_on_of_ball_subset`, `complex.eq_on_closed_ball_of_is_max_on_norm`, and `complex.eventually_eq_of_is_local_max_norm`. ### Values on the frontier Finally, we prove some corollaries that relate the (norm of the) values of a function on a set to its values on the frontier of the set. All these lemmas assume that `E` is a nontrivial space. In this section `f g : E → F` are functions that are complex differentiable on a bounded set `s` and are continuous on its closure. We prove the following theorems. - `complex.exists_mem_frontier_is_max_on_norm`: If `E` is a finite dimensional space and `s` is a nonempty bounded set, then there exists a point `z ∈ frontier s` such that `λ z, ∥f z∥` takes it maximum value on `closure s` at `z`. - `complex.norm_le_of_forall_mem_frontier_norm_le`: if `∥f z∥ ≤ C` for all `z ∈ frontier s`, then `∥f z∥ ≤ C` for all `z ∈ s`; note that this theorem does not require `E` to be a finite dimensional space. - `complex.eq_on_closure_of_eq_on_frontier`: if `f x = g x` on the frontier of `s`, then `f x = g x` on `closure s`; - `complex.eq_on_of_eq_on_frontier`: if `f x = g x` on the frontier of `s`, then `f x = g x` on `s`. ## Tags maximum modulus principle, complex analysis -/ open topological_space metric set filter asymptotics function measure_theory affine_map open_locale topological_space filter nnreal real universes u v w variables {E : Type u} [normed_group E] [normed_space ℂ E] {F : Type v} [normed_group F] [normed_space ℂ F] local postfix `̂`:100 := uniform_space.completion namespace complex /-! ### Auxiliary lemmas We split the proof into a series of lemmas. First we prove the principle for a function `f : ℂ → F` with an additional assumption that `F` is a complete space, then drop unneeded assumptions one by one. The lemmas with names `*_auxₙ` are considered to be private and should not be used outside of this file. -/ lemma norm_max_aux₁ [complete_space F] {f : ℂ → F} {z w : ℂ} (hd : diff_cont_on_cl ℂ f (ball z (dist w z))) (hz : is_max_on (norm ∘ f) (closed_ball z (dist w z)) z) : ∥f w∥ = ∥f z∥ := begin /- Consider a circle of radius `r = dist w z`. -/ set r : ℝ := dist w z, have hw : w ∈ closed_ball z r, from mem_closed_ball.2 le_rfl, /- Assume the converse. Since `∥f w∥ ≤ ∥f z∥`, we have `∥f w∥ < ∥f z∥`. -/ refine (is_max_on_iff.1 hz _ hw).antisymm (not_lt.1 _), rintro hw_lt : ∥f w∥ < ∥f z∥, have hr : 0 < r, from dist_pos.2 (ne_of_apply_ne (norm ∘ f) hw_lt.ne), /- Due to Cauchy integral formula, it suffices to prove the following inequality. -/ suffices : ∥∮ ζ in C(z, r), (ζ - z)⁻¹ • f ζ∥ < 2 * π * ∥f z∥, { refine this.ne _, have A : ∮ ζ in C(z, r), (ζ - z)⁻¹ • f ζ = (2 * π * I : ℂ) • f z := hd.circle_integral_sub_inv_smul (mem_ball_self hr), simp [A, norm_smul, real.pi_pos.le] }, suffices : ∥∮ ζ in C(z, r), (ζ - z)⁻¹ • f ζ∥ < 2 * π * r * (∥f z∥ / r), by rwa [mul_assoc, mul_div_cancel' _ hr.ne'] at this, /- This inequality is true because `∥(ζ - z)⁻¹ • f ζ∥ ≤ ∥f z∥ / r` for all `ζ` on the circle and this inequality is strict at `ζ = w`. -/ have hsub : sphere z r ⊆ closed_ball z r, from sphere_subset_closed_ball, refine circle_integral.norm_integral_lt_of_norm_le_const_of_lt hr _ _ ⟨w, rfl, _⟩, show continuous_on (λ (ζ : ℂ), (ζ - z)⁻¹ • f ζ) (sphere z r), { refine ((continuous_on_id.sub continuous_on_const).inv₀ _).smul (hd.continuous_on_ball.mono hsub), exact λ ζ hζ, sub_ne_zero.2 (ne_of_mem_sphere hζ hr.ne') }, show ∀ ζ ∈ sphere z r, ∥(ζ - z)⁻¹ • f ζ∥ ≤ ∥f z∥ / r, { rintros ζ (hζ : abs (ζ - z) = r), rw [le_div_iff hr, norm_smul, norm_inv, norm_eq_abs, hζ, mul_comm, mul_inv_cancel_left₀ hr.ne'], exact hz (hsub hζ) }, show ∥(w - z)⁻¹ • f w∥ < ∥f z∥ / r, { rw [norm_smul, norm_inv, norm_eq_abs, ← div_eq_inv_mul], exact (div_lt_div_right hr).2 hw_lt } end /-! Now we drop the assumption `complete_space F` by embedding `F` into its completion. -/ lemma norm_max_aux₂ {f : ℂ → F} {z w : ℂ} (hd : diff_cont_on_cl ℂ f (ball z (dist w z))) (hz : is_max_on (norm ∘ f) (closed_ball z (dist w z)) z) : ∥f w∥ = ∥f z∥ := begin set e : F →L[ℂ] F̂ := uniform_space.completion.to_complL, have he : ∀ x, ∥e x∥ = ∥x∥, from uniform_space.completion.norm_coe, replace hz : is_max_on (norm ∘ (e ∘ f)) (closed_ball z (dist w z)) z, by simpa only [is_max_on, (∘), he] using hz, simpa only [he] using norm_max_aux₁ (e.differentiable.comp_diff_cont_on_cl hd) hz end /-! Then we replace the assumption `is_max_on (norm ∘ f) (closed_ball z r) z` with a seemingly weaker assumption `is_max_on (norm ∘ f) (ball z r) z`. -/ lemma norm_max_aux₃ {f : ℂ → F} {z w : ℂ} {r : ℝ} (hr : dist w z = r) (hd : diff_cont_on_cl ℂ f (ball z r)) (hz : is_max_on (norm ∘ f) (ball z r) z) : ∥f w∥ = ∥f z∥ := begin subst r, rcases eq_or_ne w z with rfl|hne, { refl }, rw ← dist_ne_zero at hne, exact norm_max_aux₂ hd (closure_ball z hne ▸ hz.closure hd.continuous_on.norm) end /-! ### Maximum modulus principle for any codomain If we do not assume that the codomain is a strictly convex space, then we can only claim that the **norm** `∥f x∥` is locally constant. -/ /-! Finally, we generalize the theorem from a disk in `ℂ` to a closed ball in any normed space. -/ /-- **Maximum modulus principle** on a closed ball: if `f : E → F` is continuous on a closed ball, is complex differentiable on the corresponding open ball, and the norm `∥f w∥` takes its maximum value on the open ball at its center, then the norm `∥f w∥` is constant on the closed ball. -/ lemma norm_eq_on_closed_ball_of_is_max_on {f : E → F} {z : E} {r : ℝ} (hd : diff_cont_on_cl ℂ f (ball z r)) (hz : is_max_on (norm ∘ f) (ball z r) z) : eq_on (norm ∘ f) (const E ∥f z∥) (closed_ball z r) := begin intros w hw, rw [mem_closed_ball, dist_comm] at hw, rcases eq_or_ne z w with rfl|hne, { refl }, set e : ℂ → E := line_map z w, have hde : differentiable ℂ e := (differentiable_id.smul_const (w - z)).add_const z, suffices : ∥(f ∘ e) (1 : ℂ)∥ = ∥(f ∘ e) (0 : ℂ)∥, by simpa [e], have hr : dist (1 : ℂ) 0 = 1, by simp, have hball : maps_to e (ball 0 1) (ball z r), { refine ((lipschitz_with_line_map z w).maps_to_ball (mt nndist_eq_zero.1 hne) 0 1).mono subset.rfl _, simpa only [line_map_apply_zero, mul_one, coe_nndist] using ball_subset_ball hw }, exact norm_max_aux₃ hr (hd.comp hde.diff_cont_on_cl hball) (hz.comp_maps_to hball (line_map_apply_zero z w)) end /-- **Maximum modulus principle**: if `f : E → F` is complex differentiable on a set `s`, the norm of `f` takes it maximum on `s` at `z`, and `w` is a point such that the closed ball with center `z` and radius `dist w z` is included in `s`, then `∥f w∥ = ∥f z∥`. -/ lemma norm_eq_norm_of_is_max_on_of_ball_subset {f : E → F} {s : set E} {z w : E} (hd : diff_cont_on_cl ℂ f s) (hz : is_max_on (norm ∘ f) s z) (hsub : ball z (dist w z) ⊆ s) : ∥f w∥ = ∥f z∥ := norm_eq_on_closed_ball_of_is_max_on (hd.mono hsub) (hz.on_subset hsub) (mem_closed_ball.2 le_rfl) /-- **Maximum modulus principle**: if `f : E → F` is complex differentiable in a neighborhood of `c` and the norm `∥f z∥` has a local maximum at `c`, then `∥f z∥` is locally constant in a neighborhood of `c`. -/ lemma norm_eventually_eq_of_is_local_max {f : E → F} {c : E} (hd : ∀ᶠ z in 𝓝 c, differentiable_at ℂ f z) (hc : is_local_max (norm ∘ f) c) : ∀ᶠ y in 𝓝 c, ∥f y∥ = ∥f c∥ := begin rcases nhds_basis_closed_ball.eventually_iff.1 (hd.and hc) with ⟨r, hr₀, hr⟩, exact nhds_basis_closed_ball.eventually_iff.2 ⟨r, hr₀, norm_eq_on_closed_ball_of_is_max_on (differentiable_on.diff_cont_on_cl $ λ x hx, (hr $ closure_ball_subset_closed_ball hx).1.differentiable_within_at) (λ x hx, (hr $ ball_subset_closed_ball hx).2)⟩ end lemma is_open_set_of_mem_nhds_and_is_max_on_norm {f : E → F} {s : set E} (hd : differentiable_on ℂ f s) : is_open {z | s ∈ 𝓝 z ∧ is_max_on (norm ∘ f) s z} := begin refine is_open_iff_mem_nhds.2 (λ z hz, (eventually_eventually_nhds.2 hz.1).and _), replace hd : ∀ᶠ w in 𝓝 z, differentiable_at ℂ f w, from hd.eventually_differentiable_at hz.1, exact (norm_eventually_eq_of_is_local_max hd $ (hz.2.is_local_max hz.1)).mono (λ x hx y hy, le_trans (hz.2 hy) hx.ge) end /-- **Maximum modulus principle** on a connected set. Let `U` be a (pre)connected open set in a complex normed space. Let `f : E → F` be a function that is complex differentiable on `U`. Suppose that `∥f x∥` takes its maximum value on `U` at `c ∈ U`. Then `∥f x∥ = ∥f c∥` for all `x ∈ U`. -/ lemma norm_eq_on_of_is_preconnected_of_is_max_on {f : E → F} {U : set E} {c : E} (hc : is_preconnected U) (ho : is_open U) (hd : differentiable_on ℂ f U) (hcU : c ∈ U) (hm : is_max_on (norm ∘ f) U c) : eq_on (norm ∘ f) (const E ∥f c∥) U := begin set V := U ∩ {z | is_max_on (norm ∘ f) U z}, have hV : ∀ x ∈ V, ∥f x∥ = ∥f c∥, from λ x hx, le_antisymm (hm hx.1) (hx.2 hcU), suffices : U ⊆ V, from λ x hx, hV x (this hx), have hVo : is_open V, { simpa only [ho.mem_nhds_iff, set_of_and, set_of_mem_eq] using is_open_set_of_mem_nhds_and_is_max_on_norm hd }, have hVne : (U ∩ V).nonempty := ⟨c, hcU, hcU, hm⟩, set W := U ∩ {z | ∥f z∥ ≠ ∥f c∥}, have hWo : is_open W, from hd.continuous_on.norm.preimage_open_of_open ho is_open_ne, have hdVW : disjoint V W, from λ x ⟨hxV, hxW⟩, hxW.2 (hV x hxV), have hUVW : U ⊆ V ∪ W, from λ x hx, (eq_or_ne (∥f x∥) (∥f c∥)).imp (λ h, ⟨hx, λ y hy, (hm hy).out.trans_eq h.symm⟩) (and.intro hx), exact hc.subset_left_of_subset_union hVo hWo hdVW hUVW hVne, end /-- **Maximum modulus principle** on a connected set. Let `U` be a (pre)connected open set in a complex normed space. Let `f : E → F` be a function that is complex differentiable on `U` and is continuous on its closure. Suppose that `∥f x∥` takes its maximum value on `U` at `c ∈ U`. Then `∥f x∥ = ∥f c∥` for all `x ∈ closure U`. -/ lemma norm_eq_on_closure_of_is_preconnected_of_is_max_on {f : E → F} {U : set E} {c : E} (hc : is_preconnected U) (ho : is_open U) (hd : diff_cont_on_cl ℂ f U) (hcU : c ∈ U) (hm : is_max_on (norm ∘ f) U c) : eq_on (norm ∘ f) (const E ∥f c∥) (closure U) := (norm_eq_on_of_is_preconnected_of_is_max_on hc ho hd.differentiable_on hcU hm).of_subset_closure hd.continuous_on.norm continuous_on_const subset_closure subset.rfl section strict_convex /-! ### The case of a strictly convex codomain If the codomain `F` is a strictly convex space, then we can claim equalities like `f w = f z` instead of `∥f w∥ = ∥f z∥`. Instead of repeating the proof starting with lemmas about integrals, we apply a corresponding lemma above twice: for `f` and for `λ x, f x + f c`. Then we have `∥f w∥ = ∥f z∥` and `∥f w + f z∥ = ∥f z + f z∥`, thus `∥f w + f z∥ = ∥f w∥ + ∥f z∥`. This is only possible if `f w = f z`, see `eq_of_norm_eq_of_norm_add_eq`. -/ variables [strict_convex_space ℝ F] /-- **Maximum modulus principle** on a connected set. Let `U` be a (pre)connected open set in a complex normed space. Let `f : E → F` be a function that is complex differentiable on `U`. Suppose that `∥f x∥` takes its maximum value on `U` at `c ∈ U`. Then `f x = f c` for all `x ∈ U`. TODO: change assumption from `is_max_on` to `is_local_max`. -/ lemma eq_on_of_is_preconnected_of_is_max_on_norm {f : E → F} {U : set E} {c : E} (hc : is_preconnected U) (ho : is_open U) (hd : differentiable_on ℂ f U) (hcU : c ∈ U) (hm : is_max_on (norm ∘ f) U c) : eq_on f (const E (f c)) U := λ x hx, have H₁ : ∥f x∥ = ∥f c∥, from norm_eq_on_of_is_preconnected_of_is_max_on hc ho hd hcU hm hx, have H₂ : ∥f x + f c∥ = ∥f c + f c∥, from norm_eq_on_of_is_preconnected_of_is_max_on hc ho (hd.add_const _) hcU hm.norm_add_self hx, eq_of_norm_eq_of_norm_add_eq H₁ $ by simp only [H₂, same_ray.rfl.norm_add, H₁] /-- **Maximum modulus principle** on a connected set. Let `U` be a (pre)connected open set in a complex normed space. Let `f : E → F` be a function that is complex differentiable on `U` and is continuous on its closure. Suppose that `∥f x∥` takes its maximum value on `U` at `c ∈ U`. Then `f x = f c` for all `x ∈ closure U`. -/ lemma eq_on_closure_of_is_preconnected_of_is_max_on_norm {f : E → F} {U : set E} {c : E} (hc : is_preconnected U) (ho : is_open U) (hd : diff_cont_on_cl ℂ f U) (hcU : c ∈ U) (hm : is_max_on (norm ∘ f) U c) : eq_on f (const E (f c)) (closure U) := (eq_on_of_is_preconnected_of_is_max_on_norm hc ho hd.differentiable_on hcU hm).of_subset_closure hd.continuous_on continuous_on_const subset_closure subset.rfl /-- **Maximum modulus principle**. Let `f : E → F` be a function between complex normed spaces. Suppose that the codomain `F` is a strictly convex space, `f` is complex differentiable on a set `s`, `f` is continuous on the closure of `s`, the norm of `f` takes it maximum on `s` at `z`, and `w` is a point such that the closed ball with center `z` and radius `dist w z` is included in `s`, then `f w = f z`. -/ lemma eq_of_is_max_on_of_ball_subset {f : E → F} {s : set E} {z w : E} (hd : diff_cont_on_cl ℂ f s) (hz : is_max_on (norm ∘ f) s z) (hsub : ball z (dist w z) ⊆ s) : f w = f z := have H₁ : ∥f w∥ = ∥f z∥, from norm_eq_norm_of_is_max_on_of_ball_subset hd hz hsub, have H₂ : ∥f w + f z∥ = ∥f z + f z∥, from norm_eq_norm_of_is_max_on_of_ball_subset (hd.add_const _) hz.norm_add_self hsub, eq_of_norm_eq_of_norm_add_eq H₁ $ by simp only [H₂, same_ray.rfl.norm_add, H₁] /-- **Maximum modulus principle** on a closed ball. Suppose that a function `f : E → F` from a normed complex space to a strictly convex normed complex space has the following properties: - it is continuous on a closed ball `metric.closed_ball z r`, - it is complex differentiable on the corresponding open ball; - the norm `∥f w∥` takes its maximum value on the open ball at its center. Then `f` is a constant on the closed ball. -/ lemma eq_on_closed_ball_of_is_max_on_norm {f : E → F} {z : E} {r : ℝ} (hd : diff_cont_on_cl ℂ f (ball z r)) (hz : is_max_on (norm ∘ f) (ball z r) z) : eq_on f (const E (f z)) (closed_ball z r) := λ x hx, eq_of_is_max_on_of_ball_subset hd hz $ ball_subset_ball hx /-- **Maximum modulus principle**: if `f : E → F` is complex differentiable in a neighborhood of `c` and the norm `∥f z∥` has a local maximum at `c`, then `f` is locally constant in a neighborhood of `c`. -/ lemma eventually_eq_of_is_local_max_norm {f : E → F} {c : E} (hd : ∀ᶠ z in 𝓝 c, differentiable_at ℂ f z) (hc : is_local_max (norm ∘ f) c) : ∀ᶠ y in 𝓝 c, f y = f c := begin rcases nhds_basis_closed_ball.eventually_iff.1 (hd.and hc) with ⟨r, hr₀, hr⟩, exact nhds_basis_closed_ball.eventually_iff.2 ⟨r, hr₀, eq_on_closed_ball_of_is_max_on_norm (differentiable_on.diff_cont_on_cl $ λ x hx, (hr $ closure_ball_subset_closed_ball hx).1.differentiable_within_at) (λ x hx, (hr $ ball_subset_closed_ball hx).2)⟩ end end strict_convex /-! ### Maximum on a set vs maximum on its frontier In this section we prove corollaries of the maximum modulus principle that relate the values of a function on a set to its values on the frontier of this set. -/ variable [nontrivial E] /-- **Maximum modulus principle**: if `f : E → F` is complex differentiable on a nonempty bounded set `U` and is continuous on its closure, then there exists a point `z ∈ frontier U` such that `λ z, ∥f z∥` takes it maximum value on `closure U` at `z`. -/ lemma exists_mem_frontier_is_max_on_norm [finite_dimensional ℂ E] {f : E → F} {U : set E} (hb : bounded U) (hne : U.nonempty) (hd : diff_cont_on_cl ℂ f U) : ∃ z ∈ frontier U, is_max_on (norm ∘ f) (closure U) z := begin have hc : is_compact (closure U), from hb.is_compact_closure, obtain ⟨w, hwU, hle⟩ : ∃ w ∈ closure U, is_max_on (norm ∘ f) (closure U) w, from hc.exists_forall_ge hne.closure hd.continuous_on.norm, rw [closure_eq_interior_union_frontier, mem_union_eq] at hwU, cases hwU, rotate, { exact ⟨w, hwU, hle⟩ }, have : interior U ≠ univ, from ne_top_of_le_ne_top hc.ne_univ interior_subset_closure, rcases exists_mem_frontier_inf_dist_compl_eq_dist hwU this with ⟨z, hzU, hzw⟩, refine ⟨z, frontier_interior_subset hzU, λ x hx, (mem_set_of_eq.mp $ hle hx).trans_eq _⟩, refine (norm_eq_norm_of_is_max_on_of_ball_subset hd (hle.on_subset subset_closure) _).symm, rw [dist_comm, ← hzw], exact ball_inf_dist_compl_subset.trans interior_subset end /-- **Maximum modulus principle**: if `f : E → F` is complex differentiable on a bounded set `U` and `∥f z∥ ≤ C` for any `z ∈ frontier U`, then the same is true for any `z ∈ closure U`. -/ lemma norm_le_of_forall_mem_frontier_norm_le {f : E → F} {U : set E} (hU : bounded U) (hd : diff_cont_on_cl ℂ f U) {C : ℝ} (hC : ∀ z ∈ frontier U, ∥f z∥ ≤ C) {z : E} (hz : z ∈ closure U) : ∥f z∥ ≤ C := begin rw [closure_eq_self_union_frontier, union_comm, mem_union_eq] at hz, cases hz, { exact hC z hz }, /- In case of a finite dimensional domain, one can just apply `complex.exists_mem_frontier_is_max_on_norm`. To make it work in any Banach space, we restrict the function to a line first. -/ rcases exists_ne z with ⟨w, hne⟩, set e : ℂ → E := line_map z w, have hde : differentiable ℂ e := (differentiable_id.smul_const (w - z)).add_const z, have hL : antilipschitz_with (nndist z w)⁻¹ e, from antilipschitz_with_line_map hne.symm, replace hd : diff_cont_on_cl ℂ (f ∘ e) (e ⁻¹' U), from hd.comp hde.diff_cont_on_cl (maps_to_preimage _ _), have h₀ : (0 : ℂ) ∈ e ⁻¹' U, by simpa only [e, mem_preimage, line_map_apply_zero], rcases exists_mem_frontier_is_max_on_norm (hL.bounded_preimage hU) ⟨0, h₀⟩ hd with ⟨ζ, hζU, hζ⟩, calc ∥f z∥ = ∥f (e 0)∥ : by simp only [e, line_map_apply_zero] ... ≤ ∥f (e ζ)∥ : hζ (subset_closure h₀) ... ≤ C : hC _ (hde.continuous.frontier_preimage_subset _ hζU) end /-- If two complex differentiable functions `f g : E → F` are equal on the boundary of a bounded set `U`, then they are equal on `closure U`. -/ lemma eq_on_closure_of_eq_on_frontier {f g : E → F} {U : set E} (hU : bounded U) (hf : diff_cont_on_cl ℂ f U) (hg : diff_cont_on_cl ℂ g U) (hfg : eq_on f g (frontier U)) : eq_on f g (closure U) := begin suffices H : ∀ z ∈ closure U, ∥(f - g) z∥ ≤ 0, by simpa [sub_eq_zero] using H, refine λ z hz, norm_le_of_forall_mem_frontier_norm_le hU (hf.sub hg) (λ w hw, _) hz, simp [hfg hw] end /-- If two complex differentiable functions `f g : E → F` are equal on the boundary of a bounded set `U`, then they are equal on `U`. -/ lemma eq_on_of_eq_on_frontier {f g : E → F} {U : set E} (hU : bounded U) (hf : diff_cont_on_cl ℂ f U) (hg : diff_cont_on_cl ℂ g U) (hfg : eq_on f g (frontier U)) : eq_on f g U := (eq_on_closure_of_eq_on_frontier hU hf hg hfg).mono subset_closure end complex
09582855ce4c2af7123023c442d5d3b74db360b3
ee8cdbabf07f77e7be63a449b8483ce308d37218
/lean/src/test/mathd-algebra-188.lean
2c496151ca37a2416dbe21709fcbbdc670471263
[ "MIT", "Apache-2.0" ]
permissive
zeta1999/miniF2F
6d66c75d1c18152e224d07d5eed57624f731d4b7
c1ba9629559c5273c92ec226894baa0c1ce27861
refs/heads/main
1,681,897,460,642
1,620,646,361,000
1,620,646,361,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
424
lean
/- Copyright (c) 2021 OpenAI. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kunhao Zheng -/ import tactic.gptf import data.real.basic import data.real.nnreal import data.real.sqrt import data.equiv.basic example (σ : equiv ℝ ℝ) (h : σ.1 2 = σ.2 2) : σ.1 (σ.1 2) = 2 := begin simp only [*, equiv.to_fun_as_coe, equiv.apply_symm_apply, equiv.inv_fun_as_coe] end
db2b46da5ea2eaeb08ca25886c1c4190b280659a
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/11_Tactic-Style_Proofs.org.25.lean
902f3ab6ab0f2787a51b57fe8c16e337c0a6bb5e
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
599
lean
import standard example (p q r : Prop) : p ∧ (q ∨ r) ↔ (p ∧ q) ∨ (p ∧ r) := begin apply iff.intro, begin intro H, apply (or.elim (and.elim_right H)), intro Hq, show (p ∧ q) ∨ (p ∧ r), from or.inl (and.intro (and.elim_left H) Hq), intro Hr, show (p ∧ q) ∨ (p ∧ r), from or.inr (and.intro (and.elim_left H) Hr), end, begin intro H, apply (or.elim H), begin intro Hpq, show p ∧ (q ∨ r), from and.intro (and.elim_left Hpq) (or.inl (and.elim_right Hpq)), end, begin intro Hpr, show p ∧ (q ∨ r), from and.intro (and.elim_left Hpr) (or.inr (and.elim_right Hpr)) end end end
8d0119d15538fa85d92e2deda895a487308fc7ad
037dba89703a79cd4a4aec5e959818147f97635d
/src/2020/problem_sheets/sheet2.lean
1889ffa72f14ebb87f21edac1bfd27b86922a603
[]
no_license
ImperialCollegeLondon/M40001_lean
3a6a09298da395ab51bc220a535035d45bbe919b
62a76fa92654c855af2b2fc2bef8e60acd16ccec
refs/heads/master
1,666,750,403,259
1,665,771,117,000
1,665,771,117,000
209,141,835
115
12
null
1,640,270,596,000
1,568,749,174,000
Lean
UTF-8
Lean
false
false
3,097
lean
/- Math40001 : Introduction to university mathematics. Problem Sheet 2, October 2020. This is a Lean file. It can be read with the Lean theorem prover. You can work on this file online via the link at https://github.com/ImperialCollegeLondon/M40001_lean/blob/master/README.md or you can install Lean and its maths library following the instructions at https://leanprover-community.github.io/get_started.html and then just clone the project onto your own computer with `leanproject get ImperialCollegeLondon/M40001_lean`. There are advantages to installing Lean on your own computer (for example it's faster), but it's more hassle than just using it online. In the below, delete "sorry" and replace it with some tactics which prove the result. -/ import data.real.basic -- need real numbers for Q5 -- Q1 prove that ∩ is symmetric lemma question1 (α : Type) (X Y : set α) : X ∩ Y = Y ∩ X := begin sorry end -- question 2 defs def A := {x : ℝ | x ^ 2 < 3} def B := {x : ℝ | ∃ n : ℤ, x = n ∧ x ^ 2 < 3} def C := {x : ℝ | x ^ 3 < 3} -- Change _true to _false and put a ¬ in front -- of the goal if you think it's false. -- e.g. if you think 2c is false then don't -- try to prove it's true, try proving -- lemma question2c_false : ¬ (A ⊆ C) := ... -- Some of these are tricky for Lean beginners. lemma question2a_true : (1 : ℝ)/2 ∈ A ∩ B := begin sorry end lemma question2b_true : (1 : ℝ)/2 ∈ A ∪ B := begin sorry end lemma question2c_true : A ⊆ C := begin sorry end lemma question2d_true : B ⊆ C := begin sorry end lemma question2e_true : C ⊆ A ∪ B := begin sorry end lemma question2f_true : (A ∩ B) ∪ C = (A ∪ B) ∩ C := begin sorry end -- Q3 set-up variables (X Y : Type) variable (P : X → Prop) variable (Q : X → Prop) variable (R : X → Y → Prop) -- for Q3 you're going to have to change the right hand -- side of the ↔ in the statement -- of the lemma to the answer you think is correct. lemma question3a : ¬ (∀ x : X, P x ∧ ¬ Q x) ↔ true := -- change `true`! begin sorry end lemma question3b : ¬ (∃ x : X, (¬ P x) ∧ Q x) ↔ true := -- change `true`! begin sorry end lemma question3c : ¬ (∀ x : X, ∃ y : Y, R x y) ↔ true := -- change `true`! begin sorry end example (f : ℝ → ℝ) (x : ℝ) : ¬ (∀ ε : ℝ, ε > 0 → ∃ δ : ℝ, δ > 0 ∧ ∀ y : ℝ, abs (y - x) < δ → abs (f y -f x) < ε ) ↔ -- change next line to what you think the answer is true := begin sorry end -- change _true to _false in 4a, 4b if you think the opposite is true -- and stick a `¬` in front of it lemma question4a_true : ∀ x : ℝ, ∃ y : ℝ, x + y = 2 := begin sorry end lemma question4b_true : ∃ y : ℝ, ∀ x : ℝ, x + y = 2 := begin sorry end -- similarly for Q5 -- change _true to _false and add in a negation if you -- want to prove that the proposition in the question is false. lemma question5a_true : ∃ x ∈ (∅ : set ℕ), 2 + 2 = 5 := begin sorry end lemma question5b_true : ∀ x ∈ (∅ : set ℕ), 2 + 2 = 5 := begin sorry end
e50ee1e2392bbe1efb71ff7f628af2382de8f231
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/analysis/special_functions/trigonometric/deriv.lean
ee156b48855ae8a6d517e4a4e214b8a290cea836
[ "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
36,332
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Benjamin Davidson -/ import analysis.special_functions.exp_deriv /-! # Differentiability of trigonometric functions ## Main statements The differentiability of the usual trigonometric functions is proved, and their derivatives are computed. ## Tags sin, cos, tan, angle -/ noncomputable theory open_locale classical topological_space filter open set filter namespace complex /-- The complex sine function is everywhere strictly differentiable, with the derivative `cos x`. -/ lemma has_strict_deriv_at_sin (x : ℂ) : has_strict_deriv_at sin (cos x) x := begin simp only [cos, div_eq_mul_inv], convert ((((has_strict_deriv_at_id x).neg.mul_const I).cexp.sub ((has_strict_deriv_at_id x).mul_const I).cexp).mul_const I).mul_const (2:ℂ)⁻¹, simp only [function.comp, id], rw [sub_mul, mul_assoc, mul_assoc, I_mul_I, neg_one_mul, neg_neg, mul_one, one_mul, mul_assoc, I_mul_I, mul_neg_one, sub_neg_eq_add, add_comm] end /-- The complex sine function is everywhere differentiable, with the derivative `cos x`. -/ lemma has_deriv_at_sin (x : ℂ) : has_deriv_at sin (cos x) x := (has_strict_deriv_at_sin x).has_deriv_at lemma times_cont_diff_sin {n} : times_cont_diff ℂ n sin := (((times_cont_diff_neg.mul times_cont_diff_const).cexp.sub (times_cont_diff_id.mul times_cont_diff_const).cexp).mul times_cont_diff_const).div_const lemma differentiable_sin : differentiable ℂ sin := λx, (has_deriv_at_sin x).differentiable_at lemma differentiable_at_sin {x : ℂ} : differentiable_at ℂ sin x := differentiable_sin x @[simp] lemma deriv_sin : deriv sin = cos := funext $ λ x, (has_deriv_at_sin x).deriv /-- The complex cosine function is everywhere strictly differentiable, with the derivative `-sin x`. -/ lemma has_strict_deriv_at_cos (x : ℂ) : has_strict_deriv_at cos (-sin x) x := begin simp only [sin, div_eq_mul_inv, neg_mul_eq_neg_mul], convert (((has_strict_deriv_at_id x).mul_const I).cexp.add ((has_strict_deriv_at_id x).neg.mul_const I).cexp).mul_const (2:ℂ)⁻¹, simp only [function.comp, id], ring end /-- The complex cosine function is everywhere differentiable, with the derivative `-sin x`. -/ lemma has_deriv_at_cos (x : ℂ) : has_deriv_at cos (-sin x) x := (has_strict_deriv_at_cos x).has_deriv_at lemma times_cont_diff_cos {n} : times_cont_diff ℂ n cos := ((times_cont_diff_id.mul times_cont_diff_const).cexp.add (times_cont_diff_neg.mul times_cont_diff_const).cexp).div_const lemma differentiable_cos : differentiable ℂ cos := λx, (has_deriv_at_cos x).differentiable_at lemma differentiable_at_cos {x : ℂ} : differentiable_at ℂ cos x := differentiable_cos x lemma deriv_cos {x : ℂ} : deriv cos x = -sin x := (has_deriv_at_cos x).deriv @[simp] lemma deriv_cos' : deriv cos = (λ x, -sin x) := funext $ λ x, deriv_cos /-- The complex hyperbolic sine function is everywhere strictly differentiable, with the derivative `cosh x`. -/ lemma has_strict_deriv_at_sinh (x : ℂ) : has_strict_deriv_at sinh (cosh x) x := begin simp only [cosh, div_eq_mul_inv], convert ((has_strict_deriv_at_exp x).sub (has_strict_deriv_at_id x).neg.cexp).mul_const (2:ℂ)⁻¹, rw [id, mul_neg_one, sub_eq_add_neg, neg_neg] end /-- The complex hyperbolic sine function is everywhere differentiable, with the derivative `cosh x`. -/ lemma has_deriv_at_sinh (x : ℂ) : has_deriv_at sinh (cosh x) x := (has_strict_deriv_at_sinh x).has_deriv_at lemma times_cont_diff_sinh {n} : times_cont_diff ℂ n sinh := (times_cont_diff_exp.sub times_cont_diff_neg.cexp).div_const lemma differentiable_sinh : differentiable ℂ sinh := λx, (has_deriv_at_sinh x).differentiable_at lemma differentiable_at_sinh {x : ℂ} : differentiable_at ℂ sinh x := differentiable_sinh x @[simp] lemma deriv_sinh : deriv sinh = cosh := funext $ λ x, (has_deriv_at_sinh x).deriv /-- The complex hyperbolic cosine function is everywhere strictly differentiable, with the derivative `sinh x`. -/ lemma has_strict_deriv_at_cosh (x : ℂ) : has_strict_deriv_at cosh (sinh x) x := begin simp only [sinh, div_eq_mul_inv], convert ((has_strict_deriv_at_exp x).add (has_strict_deriv_at_id x).neg.cexp).mul_const (2:ℂ)⁻¹, rw [id, mul_neg_one, sub_eq_add_neg] end /-- The complex hyperbolic cosine function is everywhere differentiable, with the derivative `sinh x`. -/ lemma has_deriv_at_cosh (x : ℂ) : has_deriv_at cosh (sinh x) x := (has_strict_deriv_at_cosh x).has_deriv_at lemma times_cont_diff_cosh {n} : times_cont_diff ℂ n cosh := (times_cont_diff_exp.add times_cont_diff_neg.cexp).div_const lemma differentiable_cosh : differentiable ℂ cosh := λx, (has_deriv_at_cosh x).differentiable_at lemma differentiable_at_cosh {x : ℂ} : differentiable_at ℂ cosh x := differentiable_cosh x @[simp] lemma deriv_cosh : deriv cosh = sinh := funext $ λ x, (has_deriv_at_cosh x).deriv end complex section /-! ### Simp lemmas for derivatives of `λ x, complex.cos (f x)` etc., `f : ℂ → ℂ` -/ variables {f : ℂ → ℂ} {f' x : ℂ} {s : set ℂ} /-! #### `complex.cos` -/ lemma has_strict_deriv_at.ccos (hf : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ x, complex.cos (f x)) (- complex.sin (f x) * f') x := (complex.has_strict_deriv_at_cos (f x)).comp x hf lemma has_deriv_at.ccos (hf : has_deriv_at f f' x) : has_deriv_at (λ x, complex.cos (f x)) (- complex.sin (f x) * f') x := (complex.has_deriv_at_cos (f x)).comp x hf lemma has_deriv_within_at.ccos (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, complex.cos (f x)) (- complex.sin (f x) * f') s x := (complex.has_deriv_at_cos (f x)).comp_has_deriv_within_at x hf lemma deriv_within_ccos (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : deriv_within (λx, complex.cos (f x)) s x = - complex.sin (f x) * (deriv_within f s x) := hf.has_deriv_within_at.ccos.deriv_within hxs @[simp] lemma deriv_ccos (hc : differentiable_at ℂ f x) : deriv (λx, complex.cos (f x)) x = - complex.sin (f x) * (deriv f x) := hc.has_deriv_at.ccos.deriv /-! #### `complex.sin` -/ lemma has_strict_deriv_at.csin (hf : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ x, complex.sin (f x)) (complex.cos (f x) * f') x := (complex.has_strict_deriv_at_sin (f x)).comp x hf lemma has_deriv_at.csin (hf : has_deriv_at f f' x) : has_deriv_at (λ x, complex.sin (f x)) (complex.cos (f x) * f') x := (complex.has_deriv_at_sin (f x)).comp x hf lemma has_deriv_within_at.csin (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, complex.sin (f x)) (complex.cos (f x) * f') s x := (complex.has_deriv_at_sin (f x)).comp_has_deriv_within_at x hf lemma deriv_within_csin (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : deriv_within (λx, complex.sin (f x)) s x = complex.cos (f x) * (deriv_within f s x) := hf.has_deriv_within_at.csin.deriv_within hxs @[simp] lemma deriv_csin (hc : differentiable_at ℂ f x) : deriv (λx, complex.sin (f x)) x = complex.cos (f x) * (deriv f x) := hc.has_deriv_at.csin.deriv /-! #### `complex.cosh` -/ lemma has_strict_deriv_at.ccosh (hf : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ x, complex.cosh (f x)) (complex.sinh (f x) * f') x := (complex.has_strict_deriv_at_cosh (f x)).comp x hf lemma has_deriv_at.ccosh (hf : has_deriv_at f f' x) : has_deriv_at (λ x, complex.cosh (f x)) (complex.sinh (f x) * f') x := (complex.has_deriv_at_cosh (f x)).comp x hf lemma has_deriv_within_at.ccosh (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, complex.cosh (f x)) (complex.sinh (f x) * f') s x := (complex.has_deriv_at_cosh (f x)).comp_has_deriv_within_at x hf lemma deriv_within_ccosh (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : deriv_within (λx, complex.cosh (f x)) s x = complex.sinh (f x) * (deriv_within f s x) := hf.has_deriv_within_at.ccosh.deriv_within hxs @[simp] lemma deriv_ccosh (hc : differentiable_at ℂ f x) : deriv (λx, complex.cosh (f x)) x = complex.sinh (f x) * (deriv f x) := hc.has_deriv_at.ccosh.deriv /-! #### `complex.sinh` -/ lemma has_strict_deriv_at.csinh (hf : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ x, complex.sinh (f x)) (complex.cosh (f x) * f') x := (complex.has_strict_deriv_at_sinh (f x)).comp x hf lemma has_deriv_at.csinh (hf : has_deriv_at f f' x) : has_deriv_at (λ x, complex.sinh (f x)) (complex.cosh (f x) * f') x := (complex.has_deriv_at_sinh (f x)).comp x hf lemma has_deriv_within_at.csinh (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, complex.sinh (f x)) (complex.cosh (f x) * f') s x := (complex.has_deriv_at_sinh (f x)).comp_has_deriv_within_at x hf lemma deriv_within_csinh (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : deriv_within (λx, complex.sinh (f x)) s x = complex.cosh (f x) * (deriv_within f s x) := hf.has_deriv_within_at.csinh.deriv_within hxs @[simp] lemma deriv_csinh (hc : differentiable_at ℂ f x) : deriv (λx, complex.sinh (f x)) x = complex.cosh (f x) * (deriv f x) := hc.has_deriv_at.csinh.deriv end section /-! ### Simp lemmas for derivatives of `λ x, complex.cos (f x)` etc., `f : E → ℂ` -/ variables {E : Type*} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {f' : E →L[ℂ] ℂ} {x : E} {s : set E} /-! #### `complex.cos` -/ lemma has_strict_fderiv_at.ccos (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, complex.cos (f x)) (- complex.sin (f x) • f') x := (complex.has_strict_deriv_at_cos (f x)).comp_has_strict_fderiv_at x hf lemma has_fderiv_at.ccos (hf : has_fderiv_at f f' x) : has_fderiv_at (λ x, complex.cos (f x)) (- complex.sin (f x) • f') x := (complex.has_deriv_at_cos (f x)).comp_has_fderiv_at x hf lemma has_fderiv_within_at.ccos (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, complex.cos (f x)) (- complex.sin (f x) • f') s x := (complex.has_deriv_at_cos (f x)).comp_has_fderiv_within_at x hf lemma differentiable_within_at.ccos (hf : differentiable_within_at ℂ f s x) : differentiable_within_at ℂ (λ x, complex.cos (f x)) s x := hf.has_fderiv_within_at.ccos.differentiable_within_at @[simp] lemma differentiable_at.ccos (hc : differentiable_at ℂ f x) : differentiable_at ℂ (λx, complex.cos (f x)) x := hc.has_fderiv_at.ccos.differentiable_at lemma differentiable_on.ccos (hc : differentiable_on ℂ f s) : differentiable_on ℂ (λx, complex.cos (f x)) s := λx h, (hc x h).ccos @[simp] lemma differentiable.ccos (hc : differentiable ℂ f) : differentiable ℂ (λx, complex.cos (f x)) := λx, (hc x).ccos lemma fderiv_within_ccos (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : fderiv_within ℂ (λx, complex.cos (f x)) s x = - complex.sin (f x) • (fderiv_within ℂ f s x) := hf.has_fderiv_within_at.ccos.fderiv_within hxs @[simp] lemma fderiv_ccos (hc : differentiable_at ℂ f x) : fderiv ℂ (λx, complex.cos (f x)) x = - complex.sin (f x) • (fderiv ℂ f x) := hc.has_fderiv_at.ccos.fderiv lemma times_cont_diff.ccos {n} (h : times_cont_diff ℂ n f) : times_cont_diff ℂ n (λ x, complex.cos (f x)) := complex.times_cont_diff_cos.comp h lemma times_cont_diff_at.ccos {n} (hf : times_cont_diff_at ℂ n f x) : times_cont_diff_at ℂ n (λ x, complex.cos (f x)) x := complex.times_cont_diff_cos.times_cont_diff_at.comp x hf lemma times_cont_diff_on.ccos {n} (hf : times_cont_diff_on ℂ n f s) : times_cont_diff_on ℂ n (λ x, complex.cos (f x)) s := complex.times_cont_diff_cos.comp_times_cont_diff_on hf lemma times_cont_diff_within_at.ccos {n} (hf : times_cont_diff_within_at ℂ n f s x) : times_cont_diff_within_at ℂ n (λ x, complex.cos (f x)) s x := complex.times_cont_diff_cos.times_cont_diff_at.comp_times_cont_diff_within_at x hf /-! #### `complex.sin` -/ lemma has_strict_fderiv_at.csin (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, complex.sin (f x)) (complex.cos (f x) • f') x := (complex.has_strict_deriv_at_sin (f x)).comp_has_strict_fderiv_at x hf lemma has_fderiv_at.csin (hf : has_fderiv_at f f' x) : has_fderiv_at (λ x, complex.sin (f x)) (complex.cos (f x) • f') x := (complex.has_deriv_at_sin (f x)).comp_has_fderiv_at x hf lemma has_fderiv_within_at.csin (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, complex.sin (f x)) (complex.cos (f x) • f') s x := (complex.has_deriv_at_sin (f x)).comp_has_fderiv_within_at x hf lemma differentiable_within_at.csin (hf : differentiable_within_at ℂ f s x) : differentiable_within_at ℂ (λ x, complex.sin (f x)) s x := hf.has_fderiv_within_at.csin.differentiable_within_at @[simp] lemma differentiable_at.csin (hc : differentiable_at ℂ f x) : differentiable_at ℂ (λx, complex.sin (f x)) x := hc.has_fderiv_at.csin.differentiable_at lemma differentiable_on.csin (hc : differentiable_on ℂ f s) : differentiable_on ℂ (λx, complex.sin (f x)) s := λx h, (hc x h).csin @[simp] lemma differentiable.csin (hc : differentiable ℂ f) : differentiable ℂ (λx, complex.sin (f x)) := λx, (hc x).csin lemma fderiv_within_csin (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : fderiv_within ℂ (λx, complex.sin (f x)) s x = complex.cos (f x) • (fderiv_within ℂ f s x) := hf.has_fderiv_within_at.csin.fderiv_within hxs @[simp] lemma fderiv_csin (hc : differentiable_at ℂ f x) : fderiv ℂ (λx, complex.sin (f x)) x = complex.cos (f x) • (fderiv ℂ f x) := hc.has_fderiv_at.csin.fderiv lemma times_cont_diff.csin {n} (h : times_cont_diff ℂ n f) : times_cont_diff ℂ n (λ x, complex.sin (f x)) := complex.times_cont_diff_sin.comp h lemma times_cont_diff_at.csin {n} (hf : times_cont_diff_at ℂ n f x) : times_cont_diff_at ℂ n (λ x, complex.sin (f x)) x := complex.times_cont_diff_sin.times_cont_diff_at.comp x hf lemma times_cont_diff_on.csin {n} (hf : times_cont_diff_on ℂ n f s) : times_cont_diff_on ℂ n (λ x, complex.sin (f x)) s := complex.times_cont_diff_sin.comp_times_cont_diff_on hf lemma times_cont_diff_within_at.csin {n} (hf : times_cont_diff_within_at ℂ n f s x) : times_cont_diff_within_at ℂ n (λ x, complex.sin (f x)) s x := complex.times_cont_diff_sin.times_cont_diff_at.comp_times_cont_diff_within_at x hf /-! #### `complex.cosh` -/ lemma has_strict_fderiv_at.ccosh (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, complex.cosh (f x)) (complex.sinh (f x) • f') x := (complex.has_strict_deriv_at_cosh (f x)).comp_has_strict_fderiv_at x hf lemma has_fderiv_at.ccosh (hf : has_fderiv_at f f' x) : has_fderiv_at (λ x, complex.cosh (f x)) (complex.sinh (f x) • f') x := (complex.has_deriv_at_cosh (f x)).comp_has_fderiv_at x hf lemma has_fderiv_within_at.ccosh (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, complex.cosh (f x)) (complex.sinh (f x) • f') s x := (complex.has_deriv_at_cosh (f x)).comp_has_fderiv_within_at x hf lemma differentiable_within_at.ccosh (hf : differentiable_within_at ℂ f s x) : differentiable_within_at ℂ (λ x, complex.cosh (f x)) s x := hf.has_fderiv_within_at.ccosh.differentiable_within_at @[simp] lemma differentiable_at.ccosh (hc : differentiable_at ℂ f x) : differentiable_at ℂ (λx, complex.cosh (f x)) x := hc.has_fderiv_at.ccosh.differentiable_at lemma differentiable_on.ccosh (hc : differentiable_on ℂ f s) : differentiable_on ℂ (λx, complex.cosh (f x)) s := λx h, (hc x h).ccosh @[simp] lemma differentiable.ccosh (hc : differentiable ℂ f) : differentiable ℂ (λx, complex.cosh (f x)) := λx, (hc x).ccosh lemma fderiv_within_ccosh (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : fderiv_within ℂ (λx, complex.cosh (f x)) s x = complex.sinh (f x) • (fderiv_within ℂ f s x) := hf.has_fderiv_within_at.ccosh.fderiv_within hxs @[simp] lemma fderiv_ccosh (hc : differentiable_at ℂ f x) : fderiv ℂ (λx, complex.cosh (f x)) x = complex.sinh (f x) • (fderiv ℂ f x) := hc.has_fderiv_at.ccosh.fderiv lemma times_cont_diff.ccosh {n} (h : times_cont_diff ℂ n f) : times_cont_diff ℂ n (λ x, complex.cosh (f x)) := complex.times_cont_diff_cosh.comp h lemma times_cont_diff_at.ccosh {n} (hf : times_cont_diff_at ℂ n f x) : times_cont_diff_at ℂ n (λ x, complex.cosh (f x)) x := complex.times_cont_diff_cosh.times_cont_diff_at.comp x hf lemma times_cont_diff_on.ccosh {n} (hf : times_cont_diff_on ℂ n f s) : times_cont_diff_on ℂ n (λ x, complex.cosh (f x)) s := complex.times_cont_diff_cosh.comp_times_cont_diff_on hf lemma times_cont_diff_within_at.ccosh {n} (hf : times_cont_diff_within_at ℂ n f s x) : times_cont_diff_within_at ℂ n (λ x, complex.cosh (f x)) s x := complex.times_cont_diff_cosh.times_cont_diff_at.comp_times_cont_diff_within_at x hf /-! #### `complex.sinh` -/ lemma has_strict_fderiv_at.csinh (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, complex.sinh (f x)) (complex.cosh (f x) • f') x := (complex.has_strict_deriv_at_sinh (f x)).comp_has_strict_fderiv_at x hf lemma has_fderiv_at.csinh (hf : has_fderiv_at f f' x) : has_fderiv_at (λ x, complex.sinh (f x)) (complex.cosh (f x) • f') x := (complex.has_deriv_at_sinh (f x)).comp_has_fderiv_at x hf lemma has_fderiv_within_at.csinh (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, complex.sinh (f x)) (complex.cosh (f x) • f') s x := (complex.has_deriv_at_sinh (f x)).comp_has_fderiv_within_at x hf lemma differentiable_within_at.csinh (hf : differentiable_within_at ℂ f s x) : differentiable_within_at ℂ (λ x, complex.sinh (f x)) s x := hf.has_fderiv_within_at.csinh.differentiable_within_at @[simp] lemma differentiable_at.csinh (hc : differentiable_at ℂ f x) : differentiable_at ℂ (λx, complex.sinh (f x)) x := hc.has_fderiv_at.csinh.differentiable_at lemma differentiable_on.csinh (hc : differentiable_on ℂ f s) : differentiable_on ℂ (λx, complex.sinh (f x)) s := λx h, (hc x h).csinh @[simp] lemma differentiable.csinh (hc : differentiable ℂ f) : differentiable ℂ (λx, complex.sinh (f x)) := λx, (hc x).csinh lemma fderiv_within_csinh (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : fderiv_within ℂ (λx, complex.sinh (f x)) s x = complex.cosh (f x) • (fderiv_within ℂ f s x) := hf.has_fderiv_within_at.csinh.fderiv_within hxs @[simp] lemma fderiv_csinh (hc : differentiable_at ℂ f x) : fderiv ℂ (λx, complex.sinh (f x)) x = complex.cosh (f x) • (fderiv ℂ f x) := hc.has_fderiv_at.csinh.fderiv lemma times_cont_diff.csinh {n} (h : times_cont_diff ℂ n f) : times_cont_diff ℂ n (λ x, complex.sinh (f x)) := complex.times_cont_diff_sinh.comp h lemma times_cont_diff_at.csinh {n} (hf : times_cont_diff_at ℂ n f x) : times_cont_diff_at ℂ n (λ x, complex.sinh (f x)) x := complex.times_cont_diff_sinh.times_cont_diff_at.comp x hf lemma times_cont_diff_on.csinh {n} (hf : times_cont_diff_on ℂ n f s) : times_cont_diff_on ℂ n (λ x, complex.sinh (f x)) s := complex.times_cont_diff_sinh.comp_times_cont_diff_on hf lemma times_cont_diff_within_at.csinh {n} (hf : times_cont_diff_within_at ℂ n f s x) : times_cont_diff_within_at ℂ n (λ x, complex.sinh (f x)) s x := complex.times_cont_diff_sinh.times_cont_diff_at.comp_times_cont_diff_within_at x hf end namespace real variables {x y z : ℝ} lemma has_strict_deriv_at_sin (x : ℝ) : has_strict_deriv_at sin (cos x) x := (complex.has_strict_deriv_at_sin x).real_of_complex lemma has_deriv_at_sin (x : ℝ) : has_deriv_at sin (cos x) x := (has_strict_deriv_at_sin x).has_deriv_at lemma times_cont_diff_sin {n} : times_cont_diff ℝ n sin := complex.times_cont_diff_sin.real_of_complex lemma differentiable_sin : differentiable ℝ sin := λx, (has_deriv_at_sin x).differentiable_at lemma differentiable_at_sin : differentiable_at ℝ sin x := differentiable_sin x @[simp] lemma deriv_sin : deriv sin = cos := funext $ λ x, (has_deriv_at_sin x).deriv lemma has_strict_deriv_at_cos (x : ℝ) : has_strict_deriv_at cos (-sin x) x := (complex.has_strict_deriv_at_cos x).real_of_complex lemma has_deriv_at_cos (x : ℝ) : has_deriv_at cos (-sin x) x := (complex.has_deriv_at_cos x).real_of_complex lemma times_cont_diff_cos {n} : times_cont_diff ℝ n cos := complex.times_cont_diff_cos.real_of_complex lemma differentiable_cos : differentiable ℝ cos := λx, (has_deriv_at_cos x).differentiable_at lemma differentiable_at_cos : differentiable_at ℝ cos x := differentiable_cos x lemma deriv_cos : deriv cos x = - sin x := (has_deriv_at_cos x).deriv @[simp] lemma deriv_cos' : deriv cos = (λ x, - sin x) := funext $ λ _, deriv_cos lemma has_strict_deriv_at_sinh (x : ℝ) : has_strict_deriv_at sinh (cosh x) x := (complex.has_strict_deriv_at_sinh x).real_of_complex lemma has_deriv_at_sinh (x : ℝ) : has_deriv_at sinh (cosh x) x := (complex.has_deriv_at_sinh x).real_of_complex lemma times_cont_diff_sinh {n} : times_cont_diff ℝ n sinh := complex.times_cont_diff_sinh.real_of_complex lemma differentiable_sinh : differentiable ℝ sinh := λx, (has_deriv_at_sinh x).differentiable_at lemma differentiable_at_sinh : differentiable_at ℝ sinh x := differentiable_sinh x @[simp] lemma deriv_sinh : deriv sinh = cosh := funext $ λ x, (has_deriv_at_sinh x).deriv lemma has_strict_deriv_at_cosh (x : ℝ) : has_strict_deriv_at cosh (sinh x) x := (complex.has_strict_deriv_at_cosh x).real_of_complex lemma has_deriv_at_cosh (x : ℝ) : has_deriv_at cosh (sinh x) x := (complex.has_deriv_at_cosh x).real_of_complex lemma times_cont_diff_cosh {n} : times_cont_diff ℝ n cosh := complex.times_cont_diff_cosh.real_of_complex lemma differentiable_cosh : differentiable ℝ cosh := λx, (has_deriv_at_cosh x).differentiable_at lemma differentiable_at_cosh : differentiable_at ℝ cosh x := differentiable_cosh x @[simp] lemma deriv_cosh : deriv cosh = sinh := funext $ λ x, (has_deriv_at_cosh x).deriv /-- `sinh` is strictly monotone. -/ lemma sinh_strict_mono : strict_mono sinh := strict_mono_of_deriv_pos $ by { rw real.deriv_sinh, exact cosh_pos } end real section /-! ### Simp lemmas for derivatives of `λ x, real.cos (f x)` etc., `f : ℝ → ℝ` -/ variables {f : ℝ → ℝ} {f' x : ℝ} {s : set ℝ} /-! #### `real.cos` -/ lemma has_strict_deriv_at.cos (hf : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ x, real.cos (f x)) (- real.sin (f x) * f') x := (real.has_strict_deriv_at_cos (f x)).comp x hf lemma has_deriv_at.cos (hf : has_deriv_at f f' x) : has_deriv_at (λ x, real.cos (f x)) (- real.sin (f x) * f') x := (real.has_deriv_at_cos (f x)).comp x hf lemma has_deriv_within_at.cos (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, real.cos (f x)) (- real.sin (f x) * f') s x := (real.has_deriv_at_cos (f x)).comp_has_deriv_within_at x hf lemma deriv_within_cos (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, real.cos (f x)) s x = - real.sin (f x) * (deriv_within f s x) := hf.has_deriv_within_at.cos.deriv_within hxs @[simp] lemma deriv_cos (hc : differentiable_at ℝ f x) : deriv (λx, real.cos (f x)) x = - real.sin (f x) * (deriv f x) := hc.has_deriv_at.cos.deriv /-! #### `real.sin` -/ lemma has_strict_deriv_at.sin (hf : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ x, real.sin (f x)) (real.cos (f x) * f') x := (real.has_strict_deriv_at_sin (f x)).comp x hf lemma has_deriv_at.sin (hf : has_deriv_at f f' x) : has_deriv_at (λ x, real.sin (f x)) (real.cos (f x) * f') x := (real.has_deriv_at_sin (f x)).comp x hf lemma has_deriv_within_at.sin (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, real.sin (f x)) (real.cos (f x) * f') s x := (real.has_deriv_at_sin (f x)).comp_has_deriv_within_at x hf lemma deriv_within_sin (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, real.sin (f x)) s x = real.cos (f x) * (deriv_within f s x) := hf.has_deriv_within_at.sin.deriv_within hxs @[simp] lemma deriv_sin (hc : differentiable_at ℝ f x) : deriv (λx, real.sin (f x)) x = real.cos (f x) * (deriv f x) := hc.has_deriv_at.sin.deriv /-! #### `real.cosh` -/ lemma has_strict_deriv_at.cosh (hf : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ x, real.cosh (f x)) (real.sinh (f x) * f') x := (real.has_strict_deriv_at_cosh (f x)).comp x hf lemma has_deriv_at.cosh (hf : has_deriv_at f f' x) : has_deriv_at (λ x, real.cosh (f x)) (real.sinh (f x) * f') x := (real.has_deriv_at_cosh (f x)).comp x hf lemma has_deriv_within_at.cosh (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, real.cosh (f x)) (real.sinh (f x) * f') s x := (real.has_deriv_at_cosh (f x)).comp_has_deriv_within_at x hf lemma deriv_within_cosh (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, real.cosh (f x)) s x = real.sinh (f x) * (deriv_within f s x) := hf.has_deriv_within_at.cosh.deriv_within hxs @[simp] lemma deriv_cosh (hc : differentiable_at ℝ f x) : deriv (λx, real.cosh (f x)) x = real.sinh (f x) * (deriv f x) := hc.has_deriv_at.cosh.deriv /-! #### `real.sinh` -/ lemma has_strict_deriv_at.sinh (hf : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ x, real.sinh (f x)) (real.cosh (f x) * f') x := (real.has_strict_deriv_at_sinh (f x)).comp x hf lemma has_deriv_at.sinh (hf : has_deriv_at f f' x) : has_deriv_at (λ x, real.sinh (f x)) (real.cosh (f x) * f') x := (real.has_deriv_at_sinh (f x)).comp x hf lemma has_deriv_within_at.sinh (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, real.sinh (f x)) (real.cosh (f x) * f') s x := (real.has_deriv_at_sinh (f x)).comp_has_deriv_within_at x hf lemma deriv_within_sinh (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, real.sinh (f x)) s x = real.cosh (f x) * (deriv_within f s x) := hf.has_deriv_within_at.sinh.deriv_within hxs @[simp] lemma deriv_sinh (hc : differentiable_at ℝ f x) : deriv (λx, real.sinh (f x)) x = real.cosh (f x) * (deriv f x) := hc.has_deriv_at.sinh.deriv end section /-! ### Simp lemmas for derivatives of `λ x, real.cos (f x)` etc., `f : E → ℝ` -/ variables {E : Type*} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {f' : E →L[ℝ] ℝ} {x : E} {s : set E} /-! #### `real.cos` -/ lemma has_strict_fderiv_at.cos (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, real.cos (f x)) (- real.sin (f x) • f') x := (real.has_strict_deriv_at_cos (f x)).comp_has_strict_fderiv_at x hf lemma has_fderiv_at.cos (hf : has_fderiv_at f f' x) : has_fderiv_at (λ x, real.cos (f x)) (- real.sin (f x) • f') x := (real.has_deriv_at_cos (f x)).comp_has_fderiv_at x hf lemma has_fderiv_within_at.cos (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, real.cos (f x)) (- real.sin (f x) • f') s x := (real.has_deriv_at_cos (f x)).comp_has_fderiv_within_at x hf lemma differentiable_within_at.cos (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (λ x, real.cos (f x)) s x := hf.has_fderiv_within_at.cos.differentiable_within_at @[simp] lemma differentiable_at.cos (hc : differentiable_at ℝ f x) : differentiable_at ℝ (λx, real.cos (f x)) x := hc.has_fderiv_at.cos.differentiable_at lemma differentiable_on.cos (hc : differentiable_on ℝ f s) : differentiable_on ℝ (λx, real.cos (f x)) s := λx h, (hc x h).cos @[simp] lemma differentiable.cos (hc : differentiable ℝ f) : differentiable ℝ (λx, real.cos (f x)) := λx, (hc x).cos lemma fderiv_within_cos (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : fderiv_within ℝ (λx, real.cos (f x)) s x = - real.sin (f x) • (fderiv_within ℝ f s x) := hf.has_fderiv_within_at.cos.fderiv_within hxs @[simp] lemma fderiv_cos (hc : differentiable_at ℝ f x) : fderiv ℝ (λx, real.cos (f x)) x = - real.sin (f x) • (fderiv ℝ f x) := hc.has_fderiv_at.cos.fderiv lemma times_cont_diff.cos {n} (h : times_cont_diff ℝ n f) : times_cont_diff ℝ n (λ x, real.cos (f x)) := real.times_cont_diff_cos.comp h lemma times_cont_diff_at.cos {n} (hf : times_cont_diff_at ℝ n f x) : times_cont_diff_at ℝ n (λ x, real.cos (f x)) x := real.times_cont_diff_cos.times_cont_diff_at.comp x hf lemma times_cont_diff_on.cos {n} (hf : times_cont_diff_on ℝ n f s) : times_cont_diff_on ℝ n (λ x, real.cos (f x)) s := real.times_cont_diff_cos.comp_times_cont_diff_on hf lemma times_cont_diff_within_at.cos {n} (hf : times_cont_diff_within_at ℝ n f s x) : times_cont_diff_within_at ℝ n (λ x, real.cos (f x)) s x := real.times_cont_diff_cos.times_cont_diff_at.comp_times_cont_diff_within_at x hf /-! #### `real.sin` -/ lemma has_strict_fderiv_at.sin (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, real.sin (f x)) (real.cos (f x) • f') x := (real.has_strict_deriv_at_sin (f x)).comp_has_strict_fderiv_at x hf lemma has_fderiv_at.sin (hf : has_fderiv_at f f' x) : has_fderiv_at (λ x, real.sin (f x)) (real.cos (f x) • f') x := (real.has_deriv_at_sin (f x)).comp_has_fderiv_at x hf lemma has_fderiv_within_at.sin (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, real.sin (f x)) (real.cos (f x) • f') s x := (real.has_deriv_at_sin (f x)).comp_has_fderiv_within_at x hf lemma differentiable_within_at.sin (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (λ x, real.sin (f x)) s x := hf.has_fderiv_within_at.sin.differentiable_within_at @[simp] lemma differentiable_at.sin (hc : differentiable_at ℝ f x) : differentiable_at ℝ (λx, real.sin (f x)) x := hc.has_fderiv_at.sin.differentiable_at lemma differentiable_on.sin (hc : differentiable_on ℝ f s) : differentiable_on ℝ (λx, real.sin (f x)) s := λx h, (hc x h).sin @[simp] lemma differentiable.sin (hc : differentiable ℝ f) : differentiable ℝ (λx, real.sin (f x)) := λx, (hc x).sin lemma fderiv_within_sin (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : fderiv_within ℝ (λx, real.sin (f x)) s x = real.cos (f x) • (fderiv_within ℝ f s x) := hf.has_fderiv_within_at.sin.fderiv_within hxs @[simp] lemma fderiv_sin (hc : differentiable_at ℝ f x) : fderiv ℝ (λx, real.sin (f x)) x = real.cos (f x) • (fderiv ℝ f x) := hc.has_fderiv_at.sin.fderiv lemma times_cont_diff.sin {n} (h : times_cont_diff ℝ n f) : times_cont_diff ℝ n (λ x, real.sin (f x)) := real.times_cont_diff_sin.comp h lemma times_cont_diff_at.sin {n} (hf : times_cont_diff_at ℝ n f x) : times_cont_diff_at ℝ n (λ x, real.sin (f x)) x := real.times_cont_diff_sin.times_cont_diff_at.comp x hf lemma times_cont_diff_on.sin {n} (hf : times_cont_diff_on ℝ n f s) : times_cont_diff_on ℝ n (λ x, real.sin (f x)) s := real.times_cont_diff_sin.comp_times_cont_diff_on hf lemma times_cont_diff_within_at.sin {n} (hf : times_cont_diff_within_at ℝ n f s x) : times_cont_diff_within_at ℝ n (λ x, real.sin (f x)) s x := real.times_cont_diff_sin.times_cont_diff_at.comp_times_cont_diff_within_at x hf /-! #### `real.cosh` -/ lemma has_strict_fderiv_at.cosh (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, real.cosh (f x)) (real.sinh (f x) • f') x := (real.has_strict_deriv_at_cosh (f x)).comp_has_strict_fderiv_at x hf lemma has_fderiv_at.cosh (hf : has_fderiv_at f f' x) : has_fderiv_at (λ x, real.cosh (f x)) (real.sinh (f x) • f') x := (real.has_deriv_at_cosh (f x)).comp_has_fderiv_at x hf lemma has_fderiv_within_at.cosh (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, real.cosh (f x)) (real.sinh (f x) • f') s x := (real.has_deriv_at_cosh (f x)).comp_has_fderiv_within_at x hf lemma differentiable_within_at.cosh (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (λ x, real.cosh (f x)) s x := hf.has_fderiv_within_at.cosh.differentiable_within_at @[simp] lemma differentiable_at.cosh (hc : differentiable_at ℝ f x) : differentiable_at ℝ (λx, real.cosh (f x)) x := hc.has_fderiv_at.cosh.differentiable_at lemma differentiable_on.cosh (hc : differentiable_on ℝ f s) : differentiable_on ℝ (λx, real.cosh (f x)) s := λx h, (hc x h).cosh @[simp] lemma differentiable.cosh (hc : differentiable ℝ f) : differentiable ℝ (λx, real.cosh (f x)) := λx, (hc x).cosh lemma fderiv_within_cosh (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : fderiv_within ℝ (λx, real.cosh (f x)) s x = real.sinh (f x) • (fderiv_within ℝ f s x) := hf.has_fderiv_within_at.cosh.fderiv_within hxs @[simp] lemma fderiv_cosh (hc : differentiable_at ℝ f x) : fderiv ℝ (λx, real.cosh (f x)) x = real.sinh (f x) • (fderiv ℝ f x) := hc.has_fderiv_at.cosh.fderiv lemma times_cont_diff.cosh {n} (h : times_cont_diff ℝ n f) : times_cont_diff ℝ n (λ x, real.cosh (f x)) := real.times_cont_diff_cosh.comp h lemma times_cont_diff_at.cosh {n} (hf : times_cont_diff_at ℝ n f x) : times_cont_diff_at ℝ n (λ x, real.cosh (f x)) x := real.times_cont_diff_cosh.times_cont_diff_at.comp x hf lemma times_cont_diff_on.cosh {n} (hf : times_cont_diff_on ℝ n f s) : times_cont_diff_on ℝ n (λ x, real.cosh (f x)) s := real.times_cont_diff_cosh.comp_times_cont_diff_on hf lemma times_cont_diff_within_at.cosh {n} (hf : times_cont_diff_within_at ℝ n f s x) : times_cont_diff_within_at ℝ n (λ x, real.cosh (f x)) s x := real.times_cont_diff_cosh.times_cont_diff_at.comp_times_cont_diff_within_at x hf /-! #### `real.sinh` -/ lemma has_strict_fderiv_at.sinh (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, real.sinh (f x)) (real.cosh (f x) • f') x := (real.has_strict_deriv_at_sinh (f x)).comp_has_strict_fderiv_at x hf lemma has_fderiv_at.sinh (hf : has_fderiv_at f f' x) : has_fderiv_at (λ x, real.sinh (f x)) (real.cosh (f x) • f') x := (real.has_deriv_at_sinh (f x)).comp_has_fderiv_at x hf lemma has_fderiv_within_at.sinh (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, real.sinh (f x)) (real.cosh (f x) • f') s x := (real.has_deriv_at_sinh (f x)).comp_has_fderiv_within_at x hf lemma differentiable_within_at.sinh (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (λ x, real.sinh (f x)) s x := hf.has_fderiv_within_at.sinh.differentiable_within_at @[simp] lemma differentiable_at.sinh (hc : differentiable_at ℝ f x) : differentiable_at ℝ (λx, real.sinh (f x)) x := hc.has_fderiv_at.sinh.differentiable_at lemma differentiable_on.sinh (hc : differentiable_on ℝ f s) : differentiable_on ℝ (λx, real.sinh (f x)) s := λx h, (hc x h).sinh @[simp] lemma differentiable.sinh (hc : differentiable ℝ f) : differentiable ℝ (λx, real.sinh (f x)) := λx, (hc x).sinh lemma fderiv_within_sinh (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : fderiv_within ℝ (λx, real.sinh (f x)) s x = real.cosh (f x) • (fderiv_within ℝ f s x) := hf.has_fderiv_within_at.sinh.fderiv_within hxs @[simp] lemma fderiv_sinh (hc : differentiable_at ℝ f x) : fderiv ℝ (λx, real.sinh (f x)) x = real.cosh (f x) • (fderiv ℝ f x) := hc.has_fderiv_at.sinh.fderiv lemma times_cont_diff.sinh {n} (h : times_cont_diff ℝ n f) : times_cont_diff ℝ n (λ x, real.sinh (f x)) := real.times_cont_diff_sinh.comp h lemma times_cont_diff_at.sinh {n} (hf : times_cont_diff_at ℝ n f x) : times_cont_diff_at ℝ n (λ x, real.sinh (f x)) x := real.times_cont_diff_sinh.times_cont_diff_at.comp x hf lemma times_cont_diff_on.sinh {n} (hf : times_cont_diff_on ℝ n f s) : times_cont_diff_on ℝ n (λ x, real.sinh (f x)) s := real.times_cont_diff_sinh.comp_times_cont_diff_on hf lemma times_cont_diff_within_at.sinh {n} (hf : times_cont_diff_within_at ℝ n f s x) : times_cont_diff_within_at ℝ n (λ x, real.sinh (f x)) s x := real.times_cont_diff_sinh.times_cont_diff_at.comp_times_cont_diff_within_at x hf end
33f1789f873f9c1fb15b1108e223ad285b32cb52
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/topology/metric_space/isometry.lean
3feae31cee4bfe4c3a01a1d02cfeaace2277cbb0
[ "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
17,203
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.metric_space.antilipschitz /-! # 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. Since a lot of elementary properties don't require `eq_of_dist_eq_zero` we start setting up the theory for `pseudo_metric_space` and we specialize to `metric_space` when needed. -/ noncomputable theory universes u v w variables {α : Type u} {β : Type v} {γ : Type w} open function set open_locale topological_space ennreal /-- An isometry (also known as isometric embedding) is a map preserving the edistance between pseudoemetric spaces, or equivalently the distance between pseudometric space. -/ def isometry [pseudo_emetric_space α] [pseudo_emetric_space β] (f : α → β) : Prop := ∀x1 x2 : α, edist (f x1) (f x2) = edist x1 x2 /-- On pseudometric spaces, a map is an isometry if and only if it preserves distances. -/ lemma isometry_emetric_iff_metric [pseudo_metric_space α] [pseudo_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 [pseudo_emetric_space α] [pseudo_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 [pseudo_metric_space α] [pseudo_metric_space β] {f : α → β} (hf : isometry f) (x y : α) : dist (f x) (f y) = dist x y := by rw [dist_edist, dist_edist, hf] section pseudo_emetric_isometry variables [pseudo_emetric_space α] [pseudo_emetric_space β] [pseudo_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 from an emetric space is injective -/ lemma isometry.injective {α : Type u} [emetric_space α] {f : α → β} (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 from a metric space is a uniform inducing map -/ theorem isometry.uniform_inducing (hf : isometry f) : uniform_inducing f := hf.antilipschitz.uniform_inducing hf.lipschitz.uniform_continuous lemma isometry.tendsto_nhds_iff {ι : Type*} {f : α → β} {g : ι → α} {a : filter ι} {b : α} (hf : isometry f) : filter.tendsto g a (𝓝 b) ↔ filter.tendsto (f ∘ g) a (𝓝 (f b)) := hf.uniform_inducing.inducing.tendsto_nhds_iff /-- 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 pseudoemetric 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, 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 } lemma isometry.maps_to_emetric_ball (hf : isometry f) (x : α) (r : ℝ≥0∞) : maps_to f (emetric.ball x r) (emetric.ball (f x) r) := λ y hy, by rwa [emetric.mem_ball, hf] lemma isometry.maps_to_emetric_closed_ball (hf : isometry f) (x : α) (r : ℝ≥0∞) : maps_to f (emetric.closed_ball x r) (emetric.closed_ball (f x) r) := λ y hy, by rwa [emetric.mem_closed_ball, hf] /-- The injection from a subtype is an isometry -/ lemma isometry_subtype_coe {s : set α} : isometry (coe : s → α) := λx y, rfl lemma isometry.comp_continuous_on_iff {γ} [topological_space γ] (hf : isometry f) {g : γ → α} {s : set γ} : continuous_on (f ∘ g) s ↔ continuous_on g s := hf.uniform_inducing.inducing.continuous_on_iff.symm lemma isometry.comp_continuous_iff {γ} [topological_space γ] (hf : isometry f) {g : γ → α} : continuous (f ∘ g) ↔ continuous g := hf.uniform_inducing.inducing.continuous_iff.symm end pseudo_emetric_isometry --section section emetric_isometry variables [emetric_space α] /-- An isometry from a metric space is a uniform embedding -/ theorem isometry.uniform_embedding [pseudo_emetric_space β] {f : α → β} (hf : isometry f) : uniform_embedding f := hf.antilipschitz.uniform_embedding hf.lipschitz.uniform_continuous /-- An isometry from a metric space is an embedding -/ theorem isometry.embedding [pseudo_emetric_space β] {f : α → β} (hf : isometry f) : embedding f := hf.uniform_embedding.embedding /-- An isometry from a complete emetric space is a closed embedding -/ theorem isometry.closed_embedding [complete_space α] [emetric_space β] {f : α → β} (hf : isometry f) : closed_embedding f := hf.antilipschitz.closed_embedding hf.lipschitz.uniform_continuous end emetric_isometry --section namespace isometry variables [pseudo_metric_space α] [pseudo_metric_space β] {f : α → β} /-- An isometry preserves the diameter in pseudometric spaces. -/ lemma diam_image (hf : isometry f) (s : set α) : metric.diam (f '' s) = metric.diam s := by rw [metric.diam, metric.diam, hf.ediam_image] lemma diam_range (hf : isometry f) : metric.diam (range f) = metric.diam (univ : set α) := by { rw ← image_univ, exact hf.diam_image univ } lemma maps_to_ball (hf : isometry f) (x : α) (r : ℝ) : maps_to f (metric.ball x r) (metric.ball (f x) r) := λ y hy, by rwa [metric.mem_ball, hf.dist_eq] lemma maps_to_sphere (hf : isometry f) (x : α) (r : ℝ) : maps_to f (metric.sphere x r) (metric.sphere (f x) r) := λ y hy, by rwa [metric.mem_sphere, hf.dist_eq] lemma maps_to_closed_ball (hf : isometry f) (x : α) (r : ℝ) : maps_to f (metric.closed_ball x r) (metric.closed_ball (f x) r) := λ y hy, by rwa [metric.mem_closed_ball, hf.dist_eq] end isometry /-- `α` 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*) [pseudo_emetric_space α] [pseudo_emetric_space β] extends α ≃ β := (isometry_to_fun : isometry to_fun) infix ` ≃ᵢ `:25 := isometric namespace isometric section pseudo_emetric_space variables [pseudo_emetric_space α] [pseudo_emetric_space β] [pseudo_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 bijective (h : α ≃ᵢ β) : bijective h := h.to_equiv.bijective protected lemma injective (h : α ≃ᵢ β) : injective h := h.to_equiv.injective protected lemma surjective (h : α ≃ᵢ β) : surjective h := h.to_equiv.surjective 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*} [pseudo_metric_space α] [pseudo_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' {α : Type u} [emetric_space α] (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*) [pseudo_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 } /-- See Note [custom simps projection]. We need to specify this projection explicitly in this case, because it is a composition of multiple projections. -/ def simps.apply (h : α ≃ᵢ β) : α → β := h /-- See Note [custom simps projection] -/ def simps.symm_apply (h : α ≃ᵢ β) : β → α := h.symm initialize_simps_projections isometric (to_equiv_to_fun → apply, to_equiv_inv_fun → symm_apply) @[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 := h.to_equiv.range_eq_univ 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] @[simp] lemma preimage_emetric_ball (h : α ≃ᵢ β) (x : β) (r : ℝ≥0∞) : h ⁻¹' (emetric.ball x r) = emetric.ball (h.symm x) r := by { ext y, simp [← h.edist_eq] } @[simp] lemma preimage_emetric_closed_ball (h : α ≃ᵢ β) (x : β) (r : ℝ≥0∞) : h ⁻¹' (emetric.closed_ball x r) = emetric.closed_ball (h.symm x) r := by { ext y, simp [← h.edist_eq] } @[simp] lemma image_emetric_ball (h : α ≃ᵢ β) (x : α) (r : ℝ≥0∞) : h '' (emetric.ball x r) = emetric.ball (h x) r := by rw [← h.preimage_symm, h.symm.preimage_emetric_ball, symm_symm] @[simp] lemma image_emetric_closed_ball (h : α ≃ᵢ β) (x : α) (r : ℝ≥0∞) : h '' (emetric.closed_ball x r) = emetric.closed_ball (h x) r := by rw [← h.preimage_symm, h.symm.preimage_emetric_closed_ball, symm_symm] /-- The (bundled) homeomorphism associated to an isometric isomorphism. -/ @[simps to_equiv] protected def to_homeomorph (h : α ≃ᵢ β) : α ≃ₜ β := { continuous_to_fun := h.continuous, continuous_inv_fun := h.symm.continuous, to_equiv := h.to_equiv } @[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 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 protected lemma complete_space [complete_space β] (e : α ≃ᵢ β) : complete_space α := complete_space_of_is_complete_univ $ is_complete_of_complete_image e.isometry.uniform_inducing $ by rwa [set.image_univ, isometric.range_eq_univ, ← complete_space_iff_is_complete_univ] lemma complete_space_iff (e : α ≃ᵢ β) : complete_space α ↔ complete_space β := by { split; introI H, exacts [e.symm.complete_space, e.complete_space] } end pseudo_emetric_space section pseudo_metric_space variables [pseudo_metric_space α] [pseudo_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 @[simp] lemma preimage_ball (h : α ≃ᵢ β) (x : β) (r : ℝ) : h ⁻¹' (metric.ball x r) = metric.ball (h.symm x) r := by { ext y, simp [← h.dist_eq] } @[simp] lemma preimage_sphere (h : α ≃ᵢ β) (x : β) (r : ℝ) : h ⁻¹' (metric.sphere x r) = metric.sphere (h.symm x) r := by { ext y, simp [← h.dist_eq] } @[simp] lemma preimage_closed_ball (h : α ≃ᵢ β) (x : β) (r : ℝ) : h ⁻¹' (metric.closed_ball x r) = metric.closed_ball (h.symm x) r := by { ext y, simp [← h.dist_eq] } @[simp] lemma image_ball (h : α ≃ᵢ β) (x : α) (r : ℝ) : h '' (metric.ball x r) = metric.ball (h x) r := by rw [← h.preimage_symm, h.symm.preimage_ball, symm_symm] @[simp] lemma image_sphere (h : α ≃ᵢ β) (x : α) (r : ℝ) : h '' (metric.sphere x r) = metric.sphere (h x) r := by rw [← h.preimage_symm, h.symm.preimage_sphere, symm_symm] @[simp] lemma image_closed_ball (h : α ≃ᵢ β) (x : α) (r : ℝ) : h '' (metric.closed_ball x r) = metric.closed_ball (h x) r := by rw [← h.preimage_symm, h.symm.preimage_closed_ball, symm_symm] end pseudo_metric_space end isometric /-- An isometry induces an isometric isomorphism between the source space and the range of the isometry. -/ @[simps to_equiv apply { simp_rhs := tt }] def isometry.isometric_on_range [emetric_space α] [pseudo_emetric_space β] {f : α → β} (h : isometry f) : α ≃ᵢ range f := { isometry_to_fun := λx y, by simpa [subtype.edist_eq] using h x y, to_equiv := equiv.of_injective f h.injective }
2747eec4128b26591d0d6904d3b947431c096a6e
bb31430994044506fa42fd667e2d556327e18dfe
/src/algebraic_geometry/prime_spectrum/basic.lean
ba43a6c38d108940fb3b0afc6467d50ba7cf8ee6
[ "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
35,511
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import algebra.punit_instances import linear_algebra.finsupp import ring_theory.ideal.over import ring_theory.ideal.prod import ring_theory.localization.away import ring_theory.nilpotent import topology.sets.closeds import topology.sober /-! # Prime spectrum of a commutative ring The prime spectrum of a commutative ring is the type of all prime ideals. It is naturally endowed with a topology: the Zariski topology. (It is also naturally endowed with a sheaf of rings, which is constructed in `algebraic_geometry.structure_sheaf`.) ## Main definitions * `prime_spectrum R`: The prime spectrum of a commutative ring `R`, i.e., the set of all prime ideals of `R`. * `zero_locus s`: The zero locus of a subset `s` of `R` is the subset of `prime_spectrum R` consisting of all prime ideals that contain `s`. * `vanishing_ideal t`: The vanishing ideal of a subset `t` of `prime_spectrum R` is the intersection of points in `t` (viewed as prime ideals). ## Conventions We denote subsets of rings with `s`, `s'`, etc... whereas we denote subsets of prime spectra with `t`, `t'`, etc... ## Inspiration/contributors The contents of this file draw inspiration from <https://github.com/ramonfmir/lean-scheme> which has contributions from Ramon Fernandez Mir, Kevin Buzzard, Kenny Lau, and Chris Hughes (on an earlier repository). -/ noncomputable theory open_locale classical universes u v variables (R : Type u) (S : Type v) [comm_ring R] [comm_ring S] /-- The prime spectrum of a commutative ring `R` is the type of all prime ideals of `R`. It is naturally endowed with a topology (the Zariski topology), and a sheaf of commutative rings (see `algebraic_geometry.structure_sheaf`). It is a fundamental building block in algebraic geometry. -/ @[ext] structure prime_spectrum := (as_ideal : ideal R) (is_prime : as_ideal.is_prime) attribute [instance] prime_spectrum.is_prime namespace prime_spectrum variables {R S} instance [nontrivial R] : nonempty $ prime_spectrum R := let ⟨I, hI⟩ := ideal.exists_maximal R in ⟨⟨I, hI.is_prime⟩⟩ /-- The prime spectrum of the zero ring is empty. -/ lemma punit (x : prime_spectrum punit) : false := x.1.ne_top_iff_one.1 x.2.1 $ subsingleton.elim (0 : punit) 1 ▸ x.1.zero_mem variables (R S) /-- The map from the direct sum of prime spectra to the prime spectrum of a direct product. -/ @[simp] def prime_spectrum_prod_of_sum : prime_spectrum R ⊕ prime_spectrum S → prime_spectrum (R × S) | (sum.inl ⟨I, hI⟩) := ⟨ideal.prod I ⊤, by exactI ideal.is_prime_ideal_prod_top⟩ | (sum.inr ⟨J, hJ⟩) := ⟨ideal.prod ⊤ J, by exactI ideal.is_prime_ideal_prod_top'⟩ /-- The prime spectrum of `R × S` is in bijection with the disjoint unions of the prime spectrum of `R` and the prime spectrum of `S`. -/ noncomputable def prime_spectrum_prod : prime_spectrum (R × S) ≃ prime_spectrum R ⊕ prime_spectrum S := equiv.symm $ equiv.of_bijective (prime_spectrum_prod_of_sum R S) begin split, { rintro (⟨I, hI⟩|⟨J, hJ⟩) (⟨I', hI'⟩|⟨J', hJ'⟩) h; simp only [ideal.prod.ext_iff, prime_spectrum_prod_of_sum] at h, { simp only [h] }, { exact false.elim (hI.ne_top h.left) }, { exact false.elim (hJ.ne_top h.right) }, { simp only [h] } }, { rintro ⟨I, hI⟩, rcases (ideal.ideal_prod_prime I).mp hI with (⟨p, ⟨hp, rfl⟩⟩|⟨p, ⟨hp, rfl⟩⟩), { exact ⟨sum.inl ⟨p, hp⟩, rfl⟩ }, { exact ⟨sum.inr ⟨p, hp⟩, rfl⟩ } } end variables {R S} @[simp] lemma prime_spectrum_prod_symm_inl_as_ideal (x : prime_spectrum R) : ((prime_spectrum_prod R S).symm $ sum.inl x).as_ideal = ideal.prod x.as_ideal ⊤ := by { cases x, refl } @[simp] lemma prime_spectrum_prod_symm_inr_as_ideal (x : prime_spectrum S) : ((prime_spectrum_prod R S).symm $ sum.inr x).as_ideal = ideal.prod ⊤ x.as_ideal := by { cases x, refl } /-- The zero locus of a set `s` of elements of a commutative ring `R` is the set of all prime ideals of the ring that contain the set `s`. An element `f` of `R` can be thought of as a dependent function on the prime spectrum of `R`. At a point `x` (a prime ideal) the function (i.e., element) `f` takes values in the quotient ring `R` modulo the prime ideal `x`. In this manner, `zero_locus s` is exactly the subset of `prime_spectrum R` where all "functions" in `s` vanish simultaneously. -/ def zero_locus (s : set R) : set (prime_spectrum R) := {x | s ⊆ x.as_ideal} @[simp] lemma mem_zero_locus (x : prime_spectrum R) (s : set R) : x ∈ zero_locus s ↔ s ⊆ x.as_ideal := iff.rfl @[simp] lemma zero_locus_span (s : set R) : zero_locus (ideal.span s : set R) = zero_locus s := by { ext x, exact (submodule.gi R R).gc s x.as_ideal } /-- The vanishing ideal of a set `t` of points of the prime spectrum of a commutative ring `R` is the intersection of all the prime ideals in the set `t`. An element `f` of `R` can be thought of as a dependent function on the prime spectrum of `R`. At a point `x` (a prime ideal) the function (i.e., element) `f` takes values in the quotient ring `R` modulo the prime ideal `x`. In this manner, `vanishing_ideal t` is exactly the ideal of `R` consisting of all "functions" that vanish on all of `t`. -/ def vanishing_ideal (t : set (prime_spectrum R)) : ideal R := ⨅ (x : prime_spectrum R) (h : x ∈ t), x.as_ideal lemma coe_vanishing_ideal (t : set (prime_spectrum R)) : (vanishing_ideal t : set R) = {f : R | ∀ x : prime_spectrum R, x ∈ t → f ∈ x.as_ideal} := begin ext f, rw [vanishing_ideal, set_like.mem_coe, submodule.mem_infi], apply forall_congr, intro x, rw [submodule.mem_infi], end lemma mem_vanishing_ideal (t : set (prime_spectrum R)) (f : R) : f ∈ vanishing_ideal t ↔ ∀ x : prime_spectrum R, x ∈ t → f ∈ x.as_ideal := by rw [← set_like.mem_coe, coe_vanishing_ideal, set.mem_set_of_eq] @[simp] lemma vanishing_ideal_singleton (x : prime_spectrum R) : vanishing_ideal ({x} : set (prime_spectrum R)) = x.as_ideal := by simp [vanishing_ideal] lemma subset_zero_locus_iff_le_vanishing_ideal (t : set (prime_spectrum R)) (I : ideal R) : t ⊆ zero_locus I ↔ I ≤ vanishing_ideal t := ⟨λ h f k, (mem_vanishing_ideal _ _).mpr (λ x j, (mem_zero_locus _ _).mpr (h j) k), λ h, λ x j, (mem_zero_locus _ _).mpr (le_trans h (λ f h, ((mem_vanishing_ideal _ _).mp h) x j))⟩ section gc variable (R) /-- `zero_locus` and `vanishing_ideal` form a galois connection. -/ lemma gc : @galois_connection (ideal R) (set (prime_spectrum R))ᵒᵈ _ _ (λ I, zero_locus I) (λ t, vanishing_ideal t) := λ I t, subset_zero_locus_iff_le_vanishing_ideal t I /-- `zero_locus` and `vanishing_ideal` form a galois connection. -/ lemma gc_set : @galois_connection (set R) (set (prime_spectrum R))ᵒᵈ _ _ (λ s, zero_locus s) (λ t, vanishing_ideal t) := have ideal_gc : galois_connection (ideal.span) coe := (submodule.gi R R).gc, by simpa [zero_locus_span, function.comp] using ideal_gc.compose (gc R) lemma subset_zero_locus_iff_subset_vanishing_ideal (t : set (prime_spectrum R)) (s : set R) : t ⊆ zero_locus s ↔ s ⊆ vanishing_ideal t := (gc_set R) s t end gc lemma subset_vanishing_ideal_zero_locus (s : set R) : s ⊆ vanishing_ideal (zero_locus s) := (gc_set R).le_u_l s lemma le_vanishing_ideal_zero_locus (I : ideal R) : I ≤ vanishing_ideal (zero_locus I) := (gc R).le_u_l I @[simp] lemma vanishing_ideal_zero_locus_eq_radical (I : ideal R) : vanishing_ideal (zero_locus (I : set R)) = I.radical := ideal.ext $ λ f, begin rw [mem_vanishing_ideal, ideal.radical_eq_Inf, submodule.mem_Inf], exact ⟨(λ h x hx, h ⟨x, hx.2⟩ hx.1), (λ h x hx, h x.1 ⟨hx, x.2⟩)⟩ end @[simp] lemma zero_locus_radical (I : ideal R) : zero_locus (I.radical : set R) = zero_locus I := vanishing_ideal_zero_locus_eq_radical I ▸ (gc R).l_u_l_eq_l I lemma subset_zero_locus_vanishing_ideal (t : set (prime_spectrum R)) : t ⊆ zero_locus (vanishing_ideal t) := (gc R).l_u_le t lemma zero_locus_anti_mono {s t : set R} (h : s ⊆ t) : zero_locus t ⊆ zero_locus s := (gc_set R).monotone_l h lemma zero_locus_anti_mono_ideal {s t : ideal R} (h : s ≤ t) : zero_locus (t : set R) ⊆ zero_locus (s : set R) := (gc R).monotone_l h lemma vanishing_ideal_anti_mono {s t : set (prime_spectrum R)} (h : s ⊆ t) : vanishing_ideal t ≤ vanishing_ideal s := (gc R).monotone_u h lemma zero_locus_subset_zero_locus_iff (I J : ideal R) : zero_locus (I : set R) ⊆ zero_locus (J : set R) ↔ J ≤ I.radical := ⟨λ h, ideal.radical_le_radical_iff.mp (vanishing_ideal_zero_locus_eq_radical I ▸ vanishing_ideal_zero_locus_eq_radical J ▸ vanishing_ideal_anti_mono h), λ h, zero_locus_radical I ▸ zero_locus_anti_mono_ideal h⟩ lemma zero_locus_subset_zero_locus_singleton_iff (f g : R) : zero_locus ({f} : set R) ⊆ zero_locus {g} ↔ g ∈ (ideal.span ({f} : set R)).radical := by rw [← zero_locus_span {f}, ← zero_locus_span {g}, zero_locus_subset_zero_locus_iff, ideal.span_le, set.singleton_subset_iff, set_like.mem_coe] lemma zero_locus_bot : zero_locus ((⊥ : ideal R) : set R) = set.univ := (gc R).l_bot @[simp] lemma zero_locus_singleton_zero : zero_locus ({0} : set R) = set.univ := zero_locus_bot @[simp] lemma zero_locus_empty : zero_locus (∅ : set R) = set.univ := (gc_set R).l_bot @[simp] lemma vanishing_ideal_univ : vanishing_ideal (∅ : set (prime_spectrum R)) = ⊤ := by simpa using (gc R).u_top lemma zero_locus_empty_of_one_mem {s : set R} (h : (1:R) ∈ s) : zero_locus s = ∅ := begin rw set.eq_empty_iff_forall_not_mem, intros x hx, rw mem_zero_locus at hx, have x_prime : x.as_ideal.is_prime := by apply_instance, have eq_top : x.as_ideal = ⊤, { rw ideal.eq_top_iff_one, exact hx h }, apply x_prime.ne_top eq_top, end @[simp] lemma zero_locus_singleton_one : zero_locus ({1} : set R) = ∅ := zero_locus_empty_of_one_mem (set.mem_singleton (1 : R)) lemma zero_locus_empty_iff_eq_top {I : ideal R} : zero_locus (I : set R) = ∅ ↔ I = ⊤ := begin split, { contrapose!, intro h, rcases ideal.exists_le_maximal I h with ⟨M, hM, hIM⟩, exact set.nonempty.ne_empty ⟨⟨M, hM.is_prime⟩, hIM⟩ }, { rintro rfl, apply zero_locus_empty_of_one_mem, trivial } end @[simp] lemma zero_locus_univ : zero_locus (set.univ : set R) = ∅ := zero_locus_empty_of_one_mem (set.mem_univ 1) lemma vanishing_ideal_eq_top_iff {s : set (prime_spectrum R)} : vanishing_ideal s = ⊤ ↔ s = ∅ := by rw [← top_le_iff, ← subset_zero_locus_iff_le_vanishing_ideal, submodule.top_coe, zero_locus_univ, set.subset_empty_iff] lemma zero_locus_sup (I J : ideal R) : zero_locus ((I ⊔ J : ideal R) : set R) = zero_locus I ∩ zero_locus J := (gc R).l_sup lemma zero_locus_union (s s' : set R) : zero_locus (s ∪ s') = zero_locus s ∩ zero_locus s' := (gc_set R).l_sup lemma vanishing_ideal_union (t t' : set (prime_spectrum R)) : vanishing_ideal (t ∪ t') = vanishing_ideal t ⊓ vanishing_ideal t' := (gc R).u_inf lemma zero_locus_supr {ι : Sort*} (I : ι → ideal R) : zero_locus ((⨆ i, I i : ideal R) : set R) = (⋂ i, zero_locus (I i)) := (gc R).l_supr lemma zero_locus_Union {ι : Sort*} (s : ι → set R) : zero_locus (⋃ i, s i) = (⋂ i, zero_locus (s i)) := (gc_set R).l_supr lemma zero_locus_bUnion (s : set (set R)) : zero_locus (⋃ s' ∈ s, s' : set R) = ⋂ s' ∈ s, zero_locus s' := by simp only [zero_locus_Union] lemma vanishing_ideal_Union {ι : Sort*} (t : ι → set (prime_spectrum R)) : vanishing_ideal (⋃ i, t i) = (⨅ i, vanishing_ideal (t i)) := (gc R).u_infi lemma zero_locus_inf (I J : ideal R) : zero_locus ((I ⊓ J : ideal R) : set R) = zero_locus I ∪ zero_locus J := set.ext $ λ x, x.2.inf_le lemma union_zero_locus (s s' : set R) : zero_locus s ∪ zero_locus s' = zero_locus ((ideal.span s) ⊓ (ideal.span s') : ideal R) := by { rw zero_locus_inf, simp } lemma zero_locus_mul (I J : ideal R) : zero_locus ((I * J : ideal R) : set R) = zero_locus I ∪ zero_locus J := set.ext $ λ x, x.2.mul_le lemma zero_locus_singleton_mul (f g : R) : zero_locus ({f * g} : set R) = zero_locus {f} ∪ zero_locus {g} := set.ext $ λ x, by simpa using x.2.mul_mem_iff_mem_or_mem @[simp] lemma zero_locus_pow (I : ideal R) {n : ℕ} (hn : 0 < n) : zero_locus ((I ^ n : ideal R) : set R) = zero_locus I := zero_locus_radical (I ^ n) ▸ (I.radical_pow n hn).symm ▸ zero_locus_radical I @[simp] lemma zero_locus_singleton_pow (f : R) (n : ℕ) (hn : 0 < n) : zero_locus ({f ^ n} : set R) = zero_locus {f} := set.ext $ λ x, by simpa using x.2.pow_mem_iff_mem n hn lemma sup_vanishing_ideal_le (t t' : set (prime_spectrum R)) : vanishing_ideal t ⊔ vanishing_ideal t' ≤ vanishing_ideal (t ∩ t') := begin intros r, rw [submodule.mem_sup, mem_vanishing_ideal], rintro ⟨f, hf, g, hg, rfl⟩ x ⟨hxt, hxt'⟩, rw mem_vanishing_ideal at hf hg, apply submodule.add_mem; solve_by_elim end lemma mem_compl_zero_locus_iff_not_mem {f : R} {I : prime_spectrum R} : I ∈ (zero_locus {f} : set (prime_spectrum R))ᶜ ↔ f ∉ I.as_ideal := by rw [set.mem_compl_iff, mem_zero_locus, set.singleton_subset_iff]; refl /-- The Zariski topology on the prime spectrum of a commutative ring is defined via the closed sets of the topology: they are exactly those sets that are the zero locus of a subset of the ring. -/ instance zariski_topology : topological_space (prime_spectrum R) := topological_space.of_closed (set.range prime_spectrum.zero_locus) (⟨set.univ, by simp⟩) begin intros Zs h, rw set.sInter_eq_Inter, choose f hf using λ i : Zs, h i.prop, simp only [← hf], exact ⟨_, zero_locus_Union _⟩ end (by { rintro _ ⟨s, rfl⟩ _ ⟨t, rfl⟩, exact ⟨_, (union_zero_locus s t).symm⟩ }) lemma is_open_iff (U : set (prime_spectrum R)) : is_open U ↔ ∃ s, Uᶜ = zero_locus s := by simp only [@eq_comm _ Uᶜ]; refl lemma is_closed_iff_zero_locus (Z : set (prime_spectrum R)) : is_closed Z ↔ ∃ s, Z = zero_locus s := by rw [← is_open_compl_iff, is_open_iff, compl_compl] lemma is_closed_iff_zero_locus_ideal (Z : set (prime_spectrum R)) : is_closed Z ↔ ∃ (I : ideal R), Z = zero_locus I := (is_closed_iff_zero_locus _).trans ⟨λ ⟨s, hs⟩, ⟨_, (zero_locus_span s).substr hs⟩, λ ⟨I, hI⟩, ⟨I, hI⟩⟩ lemma is_closed_iff_zero_locus_radical_ideal (Z : set (prime_spectrum R)) : is_closed Z ↔ ∃ (I : ideal R), I.is_radical ∧ Z = zero_locus I := (is_closed_iff_zero_locus_ideal _).trans ⟨λ ⟨I, hI⟩, ⟨_, I.radical_is_radical, (zero_locus_radical I).substr hI⟩, λ ⟨I, _, hI⟩, ⟨I, hI⟩⟩ lemma is_closed_zero_locus (s : set R) : is_closed (zero_locus s) := by { rw [is_closed_iff_zero_locus], exact ⟨s, rfl⟩ } lemma is_closed_singleton_iff_is_maximal (x : prime_spectrum R) : is_closed ({x} : set (prime_spectrum R)) ↔ x.as_ideal.is_maximal := begin refine (is_closed_iff_zero_locus _).trans ⟨λ h, _, λ h, _⟩, { obtain ⟨s, hs⟩ := h, rw [eq_comm, set.eq_singleton_iff_unique_mem] at hs, refine ⟨⟨x.2.1, λ I hI, not_not.1 (mt (ideal.exists_le_maximal I) $ not_exists.2 (λ J, not_and.2 $ λ hJ hIJ,_))⟩⟩, exact ne_of_lt (lt_of_lt_of_le hI hIJ) (symm $ congr_arg prime_spectrum.as_ideal (hs.2 ⟨J, hJ.is_prime⟩ (λ r hr, hIJ (le_of_lt hI $ hs.1 hr)))) }, { refine ⟨x.as_ideal.1, _⟩, rw [eq_comm, set.eq_singleton_iff_unique_mem], refine ⟨λ _ h, h, λ y hy, prime_spectrum.ext _ _ (h.eq_of_le y.2.ne_top hy).symm⟩ } end lemma zero_locus_vanishing_ideal_eq_closure (t : set (prime_spectrum R)) : zero_locus (vanishing_ideal t : set R) = closure t := begin apply set.subset.antisymm, { rintro x hx t' ⟨ht', ht⟩, obtain ⟨fs, rfl⟩ : ∃ s, t' = zero_locus s, by rwa [is_closed_iff_zero_locus] at ht', rw [subset_zero_locus_iff_subset_vanishing_ideal] at ht, exact set.subset.trans ht hx }, { rw (is_closed_zero_locus _).closure_subset_iff, exact subset_zero_locus_vanishing_ideal t } end lemma vanishing_ideal_closure (t : set (prime_spectrum R)) : vanishing_ideal (closure t) = vanishing_ideal t := zero_locus_vanishing_ideal_eq_closure t ▸ (gc R).u_l_u_eq_u t lemma closure_singleton (x) : closure ({x} : set (prime_spectrum R)) = zero_locus x.as_ideal := by rw [← zero_locus_vanishing_ideal_eq_closure, vanishing_ideal_singleton] lemma is_radical_vanishing_ideal (s : set (prime_spectrum R)) : (vanishing_ideal s).is_radical := by { rw [← vanishing_ideal_closure, ← zero_locus_vanishing_ideal_eq_closure, vanishing_ideal_zero_locus_eq_radical], apply ideal.radical_is_radical } lemma vanishing_ideal_anti_mono_iff {s t : set (prime_spectrum R)} (ht : is_closed t) : s ⊆ t ↔ vanishing_ideal t ≤ vanishing_ideal s := ⟨vanishing_ideal_anti_mono, λ h, begin rw [← ht.closure_subset_iff, ← ht.closure_eq], convert ← zero_locus_anti_mono_ideal h; apply zero_locus_vanishing_ideal_eq_closure, end⟩ lemma vanishing_ideal_strict_anti_mono_iff {s t : set (prime_spectrum R)} (hs : is_closed s) (ht : is_closed t) : s ⊂ t ↔ vanishing_ideal t < vanishing_ideal s := by rw [set.ssubset_def, vanishing_ideal_anti_mono_iff hs, vanishing_ideal_anti_mono_iff ht, lt_iff_le_not_le] /-- The antitone order embedding of closed subsets of `Spec R` into ideals of `R`. -/ def closeds_embedding (R : Type*) [comm_ring R] : (topological_space.closeds $ prime_spectrum R)ᵒᵈ ↪o ideal R := order_embedding.of_map_le_iff (λ s, vanishing_ideal s.of_dual) (λ s t, (vanishing_ideal_anti_mono_iff s.2).symm) lemma t1_space_iff_is_field [is_domain R] : t1_space (prime_spectrum R) ↔ is_field R := begin refine ⟨_, λ h, _⟩, { introI h, have hbot : ideal.is_prime (⊥ : ideal R) := ideal.bot_prime, exact not_not.1 (mt (ring.ne_bot_of_is_maximal_of_not_is_field $ (is_closed_singleton_iff_is_maximal _).1 (t1_space.t1 ⟨⊥, hbot⟩)) (not_not.2 rfl)) }, { refine ⟨λ x, (is_closed_singleton_iff_is_maximal x).2 _⟩, by_cases hx : x.as_ideal = ⊥, { exact hx.symm ▸ @ideal.bot_is_maximal R (@field.to_division_ring _ h.to_field) }, { exact absurd h (ring.not_is_field_iff_exists_prime.2 ⟨x.as_ideal, ⟨hx, x.2⟩⟩) } } end local notation `Z(` a `)` := zero_locus (a : set R) lemma is_irreducible_zero_locus_iff_of_radical (I : ideal R) (hI : I.is_radical) : is_irreducible (zero_locus (I : set R)) ↔ I.is_prime := begin rw [ideal.is_prime_iff, is_irreducible], apply and_congr, { rw [set.nonempty_iff_ne_empty, ne.def, zero_locus_empty_iff_eq_top] }, { transitivity ∀ (x y : ideal R), Z(I) ⊆ Z(x) ∪ Z(y) → Z(I) ⊆ Z(x) ∨ Z(I) ⊆ Z(y), { simp_rw [is_preirreducible_iff_closed_union_closed, is_closed_iff_zero_locus_ideal], split, { rintros h x y, exact h _ _ ⟨x, rfl⟩ ⟨y, rfl⟩ }, { rintros h _ _ ⟨x, rfl⟩ ⟨y, rfl⟩, exact h x y } }, { simp_rw [← zero_locus_inf, subset_zero_locus_iff_le_vanishing_ideal, vanishing_ideal_zero_locus_eq_radical, hI.radical], split, { simp_rw [← set_like.mem_coe, ← set.singleton_subset_iff, ← ideal.span_le, ← ideal.span_singleton_mul_span_singleton], refine λ h x y h', h _ _ _, rw [← hI.radical_le_iff] at h' ⊢, simpa only [ideal.radical_inf, ideal.radical_mul] using h' }, { simp_rw [or_iff_not_imp_left, set_like.not_le_iff_exists], rintros h s t h' ⟨x, hx, hx'⟩ y hy, exact h (h' ⟨ideal.mul_mem_right _ _ hx, ideal.mul_mem_left _ _ hy⟩) hx' } } } end lemma is_irreducible_zero_locus_iff (I : ideal R) : is_irreducible (zero_locus (I : set R)) ↔ I.radical.is_prime := zero_locus_radical I ▸ is_irreducible_zero_locus_iff_of_radical _ I.radical_is_radical lemma is_irreducible_iff_vanishing_ideal_is_prime {s : set (prime_spectrum R)} : is_irreducible s ↔ (vanishing_ideal s).is_prime := by rw [← is_irreducible_iff_closure, ← zero_locus_vanishing_ideal_eq_closure, is_irreducible_zero_locus_iff_of_radical _ (is_radical_vanishing_ideal s)] instance [is_domain R] : irreducible_space (prime_spectrum R) := begin rw [irreducible_space_def, set.top_eq_univ, ← zero_locus_bot, is_irreducible_zero_locus_iff], simpa using ideal.bot_prime end instance : quasi_sober (prime_spectrum R) := ⟨λ S h₁ h₂, ⟨⟨_, is_irreducible_iff_vanishing_ideal_is_prime.1 h₁⟩, by rw [is_generic_point, closure_singleton, zero_locus_vanishing_ideal_eq_closure, h₂.closure_eq]⟩⟩ section comap variables {S' : Type*} [comm_ring S'] lemma preimage_comap_zero_locus_aux (f : R →+* S) (s : set R) : (λ y, ⟨ideal.comap f y.as_ideal, infer_instance⟩ : prime_spectrum S → prime_spectrum R) ⁻¹' (zero_locus s) = zero_locus (f '' s) := begin ext x, simp only [mem_zero_locus, set.image_subset_iff], refl end /-- The function between prime spectra of commutative rings induced by a ring homomorphism. This function is continuous. -/ def comap (f : R →+* S) : C(prime_spectrum S, prime_spectrum R) := { to_fun := λ y, ⟨ideal.comap f y.as_ideal, infer_instance⟩, continuous_to_fun := begin simp only [continuous_iff_is_closed, is_closed_iff_zero_locus], rintro _ ⟨s, rfl⟩, exact ⟨_, preimage_comap_zero_locus_aux f s⟩ end } variables (f : R →+* S) @[simp] lemma comap_as_ideal (y : prime_spectrum S) : (comap f y).as_ideal = ideal.comap f y.as_ideal := rfl @[simp] lemma comap_id : comap (ring_hom.id R) = continuous_map.id _ := by { ext, refl } @[simp] lemma comap_comp (f : R →+* S) (g : S →+* S') : comap (g.comp f) = (comap f).comp (comap g) := rfl lemma comap_comp_apply (f : R →+* S) (g : S →+* S') (x : prime_spectrum S') : prime_spectrum.comap (g.comp f) x = (prime_spectrum.comap f) (prime_spectrum.comap g x) := rfl @[simp] lemma preimage_comap_zero_locus (s : set R) : (comap f) ⁻¹' (zero_locus s) = zero_locus (f '' s) := preimage_comap_zero_locus_aux f s lemma comap_injective_of_surjective (f : R →+* S) (hf : function.surjective f) : function.injective (comap f) := λ x y h, prime_spectrum.ext _ _ (ideal.comap_injective_of_surjective f hf (congr_arg prime_spectrum.as_ideal h : (comap f x).as_ideal = (comap f y).as_ideal)) lemma comap_singleton_is_closed_of_surjective (f : R →+* S) (hf : function.surjective f) (x : prime_spectrum S) (hx : is_closed ({x} : set (prime_spectrum S))) : is_closed ({comap f x} : set (prime_spectrum R)) := begin haveI : x.as_ideal.is_maximal := (is_closed_singleton_iff_is_maximal x).1 hx, exact (is_closed_singleton_iff_is_maximal _).2 (ideal.comap_is_maximal_of_surjective f hf) end lemma comap_singleton_is_closed_of_is_integral (f : R →+* S) (hf : f.is_integral) (x : prime_spectrum S) (hx : is_closed ({x} : set (prime_spectrum S))) : is_closed ({comap f x} : set (prime_spectrum R)) := (is_closed_singleton_iff_is_maximal _).2 (ideal.is_maximal_comap_of_is_integral_of_is_maximal' f hf x.as_ideal $ (is_closed_singleton_iff_is_maximal x).1 hx) variable S lemma localization_comap_inducing [algebra R S] (M : submonoid R) [is_localization M S] : inducing (comap (algebra_map R S)) := begin constructor, rw topological_space_eq_iff, intro U, simp_rw ← is_closed_compl_iff, generalize : Uᶜ = Z, simp_rw [is_closed_induced_iff, is_closed_iff_zero_locus], split, { rintro ⟨s, rfl⟩, refine ⟨_,⟨(algebra_map R S) ⁻¹' (ideal.span s),rfl⟩,_⟩, rw [preimage_comap_zero_locus, ← zero_locus_span, ← zero_locus_span s], congr' 1, exact congr_arg submodule.carrier (is_localization.map_comap M S (ideal.span s)) }, { rintro ⟨_, ⟨t, rfl⟩, rfl⟩, simp } end lemma localization_comap_injective [algebra R S] (M : submonoid R) [is_localization M S] : function.injective (comap (algebra_map R S)) := begin intros p q h, replace h := congr_arg (λ (x : prime_spectrum R), ideal.map (algebra_map R S) x.as_ideal) h, dsimp only at h, erw [is_localization.map_comap M S, is_localization.map_comap M S] at h, ext1, exact h end lemma localization_comap_embedding [algebra R S] (M : submonoid R) [is_localization M S] : embedding (comap (algebra_map R S)) := ⟨localization_comap_inducing S M, localization_comap_injective S M⟩ lemma localization_comap_range [algebra R S] (M : submonoid R) [is_localization M S] : set.range (comap (algebra_map R S)) = { p | disjoint (M : set R) p.as_ideal } := begin ext x, split, { simp_rw disjoint_iff_inf_le, rintro ⟨p, rfl⟩ x ⟨hx₁, hx₂⟩, exact (p.2.1 : ¬ _) (p.as_ideal.eq_top_of_is_unit_mem hx₂ (is_localization.map_units S ⟨x, hx₁⟩)) }, { intro h, use ⟨x.as_ideal.map (algebra_map R S), is_localization.is_prime_of_is_prime_disjoint M S _ x.2 h⟩, ext1, exact is_localization.comap_map_of_is_prime_disjoint M S _ x.2 h } end section spec_of_surjective /-! The comap of a surjective ring homomorphism is a closed embedding between the prime spectra. -/ open function ring_hom lemma comap_inducing_of_surjective (hf : surjective f) : inducing (comap f) := { induced := begin simp_rw [topological_space_eq_iff, ←is_closed_compl_iff, is_closed_induced_iff, is_closed_iff_zero_locus], refine λ s, ⟨λ ⟨F, hF⟩, ⟨zero_locus (f ⁻¹' F), ⟨f ⁻¹' F, rfl⟩, by rw [preimage_comap_zero_locus, surjective.image_preimage hf, hF]⟩, _⟩, rintros ⟨-, ⟨F, rfl⟩, hF⟩, exact ⟨f '' F, hF.symm.trans (preimage_comap_zero_locus f F)⟩, end } lemma image_comap_zero_locus_eq_zero_locus_comap (hf : surjective f) (I : ideal S) : comap f '' zero_locus I = zero_locus (I.comap f) := begin simp only [set.ext_iff, set.mem_image, mem_zero_locus, set_like.coe_subset_coe], refine λ p, ⟨_, λ h_I_p, _⟩, { rintro ⟨p, hp, rfl⟩ a ha, exact hp ha }, { have hp : ker f ≤ p.as_ideal := (ideal.comap_mono bot_le).trans h_I_p, refine ⟨⟨p.as_ideal.map f, ideal.map_is_prime_of_surjective hf hp⟩, λ x hx, _, _⟩, { obtain ⟨x', rfl⟩ := hf x, exact ideal.mem_map_of_mem f (h_I_p hx) }, { ext x, change f x ∈ p.as_ideal.map f ↔ _, rw ideal.mem_map_iff_of_surjective f hf, refine ⟨_, λ hx, ⟨x, hx, rfl⟩⟩, rintros ⟨x', hx', heq⟩, rw ← sub_sub_cancel x' x, refine p.as_ideal.sub_mem hx' (hp _), rwa [mem_ker, map_sub, sub_eq_zero] } }, end lemma range_comap_of_surjective (hf : surjective f) : set.range (comap f) = zero_locus (ker f) := begin rw ← set.image_univ, convert image_comap_zero_locus_eq_zero_locus_comap _ _ hf _, rw zero_locus_bot, end lemma is_closed_range_comap_of_surjective (hf : surjective f) : is_closed (set.range (comap f)) := begin rw range_comap_of_surjective _ f hf, exact is_closed_zero_locus ↑(ker f), end lemma closed_embedding_comap_of_surjective (hf : surjective f) : closed_embedding (comap f) := { induced := (comap_inducing_of_surjective S f hf).induced, inj := comap_injective_of_surjective f hf, closed_range := is_closed_range_comap_of_surjective S f hf } end spec_of_surjective end comap section basic_open /-- `basic_open r` is the open subset containing all prime ideals not containing `r`. -/ def basic_open (r : R) : topological_space.opens (prime_spectrum R) := { val := { x | r ∉ x.as_ideal }, property := ⟨{r}, set.ext $ λ x, set.singleton_subset_iff.trans $ not_not.symm⟩ } @[simp] lemma mem_basic_open (f : R) (x : prime_spectrum R) : x ∈ basic_open f ↔ f ∉ x.as_ideal := iff.rfl lemma is_open_basic_open {a : R} : is_open ((basic_open a) : set (prime_spectrum R)) := (basic_open a).property @[simp] lemma basic_open_eq_zero_locus_compl (r : R) : (basic_open r : set (prime_spectrum R)) = (zero_locus {r})ᶜ := set.ext $ λ x, by simpa only [set.mem_compl_iff, mem_zero_locus, set.singleton_subset_iff] @[simp] lemma basic_open_one : basic_open (1 : R) = ⊤ := topological_space.opens.ext $ by simp @[simp] lemma basic_open_zero : basic_open (0 : R) = ⊥ := topological_space.opens.ext $ by simp lemma basic_open_le_basic_open_iff (f g : R) : basic_open f ≤ basic_open g ↔ f ∈ (ideal.span ({g} : set R)).radical := by rw [topological_space.opens.le_def, basic_open_eq_zero_locus_compl, basic_open_eq_zero_locus_compl, set.le_eq_subset, set.compl_subset_compl, zero_locus_subset_zero_locus_singleton_iff] lemma basic_open_mul (f g : R) : basic_open (f * g) = basic_open f ⊓ basic_open g := topological_space.opens.ext $ by {simp [zero_locus_singleton_mul]} lemma basic_open_mul_le_left (f g : R) : basic_open (f * g) ≤ basic_open f := by { rw basic_open_mul f g, exact inf_le_left } lemma basic_open_mul_le_right (f g : R) : basic_open (f * g) ≤ basic_open g := by { rw basic_open_mul f g, exact inf_le_right } @[simp] lemma basic_open_pow (f : R) (n : ℕ) (hn : 0 < n) : basic_open (f ^ n) = basic_open f := topological_space.opens.ext $ by simpa using zero_locus_singleton_pow f n hn lemma is_topological_basis_basic_opens : topological_space.is_topological_basis (set.range (λ (r : R), (basic_open r : set (prime_spectrum R)))) := begin apply topological_space.is_topological_basis_of_open_of_nhds, { rintros _ ⟨r, rfl⟩, exact is_open_basic_open }, { rintros p U hp ⟨s, hs⟩, rw [← compl_compl U, set.mem_compl_iff, ← hs, mem_zero_locus, set.not_subset] at hp, obtain ⟨f, hfs, hfp⟩ := hp, refine ⟨basic_open f, ⟨f, rfl⟩, hfp, _⟩, rw [← set.compl_subset_compl, ← hs, basic_open_eq_zero_locus_compl, compl_compl], exact zero_locus_anti_mono (set.singleton_subset_iff.mpr hfs) } end lemma is_basis_basic_opens : topological_space.opens.is_basis (set.range (@basic_open R _)) := begin unfold topological_space.opens.is_basis, convert is_topological_basis_basic_opens, rw ← set.range_comp, end lemma is_compact_basic_open (f : R) : is_compact (basic_open f : set (prime_spectrum R)) := is_compact_of_finite_subfamily_closed $ λ ι Z hZc hZ, begin let I : ι → ideal R := λ i, vanishing_ideal (Z i), have hI : ∀ i, Z i = zero_locus (I i) := λ i, by simpa only [zero_locus_vanishing_ideal_eq_closure] using (hZc i).closure_eq.symm, rw [basic_open_eq_zero_locus_compl f, set.inter_comm, ← set.diff_eq, set.diff_eq_empty, funext hI, ← zero_locus_supr] at hZ, obtain ⟨n, hn⟩ : f ∈ (⨆ (i : ι), I i).radical, { rw ← vanishing_ideal_zero_locus_eq_radical, apply vanishing_ideal_anti_mono hZ, exact (subset_vanishing_ideal_zero_locus {f} (set.mem_singleton f)) }, rcases submodule.exists_finset_of_mem_supr I hn with ⟨s, hs⟩, use s, -- Using simp_rw here, because `hI` and `zero_locus_supr` need to be applied underneath binders simp_rw [basic_open_eq_zero_locus_compl f, set.inter_comm (zero_locus {f})ᶜ, ← set.diff_eq, set.diff_eq_empty, hI, ← zero_locus_supr], rw ← zero_locus_radical, -- this one can't be in `simp_rw` because it would loop apply zero_locus_anti_mono, rw set.singleton_subset_iff, exact ⟨n, hs⟩ end @[simp] lemma basic_open_eq_bot_iff (f : R) : basic_open f = ⊥ ↔ is_nilpotent f := begin rw [← subtype.coe_injective.eq_iff, basic_open_eq_zero_locus_compl], simp only [set.eq_univ_iff_forall, set.singleton_subset_iff, topological_space.opens.coe_bot, nilpotent_iff_mem_prime, set.compl_empty_iff, mem_zero_locus, set_like.mem_coe], exact ⟨λ h I hI, h ⟨I, hI⟩, λ h ⟨I, hI⟩, h I hI⟩ end lemma localization_away_comap_range (S : Type v) [comm_ring S] [algebra R S] (r : R) [is_localization.away r S] : set.range (comap (algebra_map R S)) = basic_open r := begin rw localization_comap_range S (submonoid.powers r), ext, simp only [mem_zero_locus, basic_open_eq_zero_locus_compl, set_like.mem_coe, set.mem_set_of_eq, set.singleton_subset_iff, set.mem_compl_iff, disjoint_iff_inf_le], split, { intros h₁ h₂, exact h₁ ⟨submonoid.mem_powers r, h₂⟩ }, { rintros h₁ _ ⟨⟨n, rfl⟩, h₃⟩, exact h₁ (x.2.mem_of_pow_mem _ h₃) }, end lemma localization_away_open_embedding (S : Type v) [comm_ring S] [algebra R S] (r : R) [is_localization.away r S] : open_embedding (comap (algebra_map R S)) := { to_embedding := localization_comap_embedding S (submonoid.powers r), open_range := by { rw localization_away_comap_range S r, exact is_open_basic_open } } end basic_open /-- The prime spectrum of a commutative ring is a compact topological space. -/ instance : compact_space (prime_spectrum R) := { is_compact_univ := by { convert is_compact_basic_open (1 : R), rw basic_open_one, refl } } section order /-! ## The specialization order We endow `prime_spectrum R` with a partial order, where `x ≤ y` if and only if `y ∈ closure {x}`. -/ instance : partial_order (prime_spectrum R) := partial_order.lift as_ideal ext @[simp] lemma as_ideal_le_as_ideal (x y : prime_spectrum R) : x.as_ideal ≤ y.as_ideal ↔ x ≤ y := iff.rfl @[simp] lemma as_ideal_lt_as_ideal (x y : prime_spectrum R) : x.as_ideal < y.as_ideal ↔ x < y := iff.rfl lemma le_iff_mem_closure (x y : prime_spectrum R) : x ≤ y ↔ y ∈ closure ({x} : set (prime_spectrum R)) := by rw [← as_ideal_le_as_ideal, ← zero_locus_vanishing_ideal_eq_closure, mem_zero_locus, vanishing_ideal_singleton, set_like.coe_subset_coe] lemma le_iff_specializes (x y : prime_spectrum R) : x ≤ y ↔ x ⤳ y := (le_iff_mem_closure x y).trans specializes_iff_mem_closure.symm /-- `nhds` as an order embedding. -/ @[simps { fully_applied := tt }] def nhds_order_embedding : prime_spectrum R ↪o filter (prime_spectrum R) := order_embedding.of_map_le_iff nhds $ λ a b, (le_iff_specializes a b).symm instance : t0_space (prime_spectrum R) := ⟨nhds_order_embedding.injective⟩ end order /-- If `x` specializes to `y`, then there is a natural map from the localization of `y` to the localization of `x`. -/ def localization_map_of_specializes {x y : prime_spectrum R} (h : x ⤳ y) : localization.at_prime y.as_ideal →+* localization.at_prime x.as_ideal := @is_localization.lift _ _ _ _ _ _ _ _ localization.is_localization (algebra_map R (localization.at_prime x.as_ideal)) begin rintro ⟨a, ha⟩, rw [← prime_spectrum.le_iff_specializes, ← as_ideal_le_as_ideal, ← set_like.coe_subset_coe, ← set.compl_subset_compl] at h, exact (is_localization.map_units _ ⟨a, (show a ∈ x.as_ideal.prime_compl, from h ha)⟩ : _) end end prime_spectrum namespace local_ring variables [local_ring R] /-- The closed point in the prime spectrum of a local ring. -/ def closed_point : prime_spectrum R := ⟨maximal_ideal R, (maximal_ideal.is_maximal R).is_prime⟩ variable {R} lemma is_local_ring_hom_iff_comap_closed_point {S : Type v} [comm_ring S] [local_ring S] (f : R →+* S) : is_local_ring_hom f ↔ prime_spectrum.comap f (closed_point S) = closed_point R := by { rw [(local_hom_tfae f).out 0 4, prime_spectrum.ext_iff], refl } @[simp] lemma comap_closed_point {S : Type v} [comm_ring S] [local_ring S] (f : R →+* S) [is_local_ring_hom f] : prime_spectrum.comap f (closed_point S) = closed_point R := (is_local_ring_hom_iff_comap_closed_point f).mp infer_instance end local_ring
8bb571a116b45107d4ab4a4c9a9e4504ed8289b2
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/topology/metric_space/emetric_space.lean
8ead13e8373dccc27d0b80fe7543741d005f018a
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
38,202
lean
/- Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel -/ import data.real.nnreal data.real.ennreal import topology.uniform_space.separation topology.uniform_space.uniform_embedding topology.uniform_space.pi import topology.bases /-! # Extended metric spaces This file is devoted to the definition and study of `emetric_spaces`, i.e., metric spaces in which the distance is allowed to take the value ∞. This extended distance is called `edist`, and takes values in `ennreal`. Many definitions and theorems expected on emetric spaces are already introduced on uniform spaces and topological spaces. For example: open and closed sets, compactness, completeness, continuity and uniform continuity The class `emetric_space` therefore extends `uniform_space` (and `topological_space`). -/ open set filter classical noncomputable theory open_locale uniformity topological_space universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- Characterizing uniformities associated to a (generalized) distance function `D` in terms of the elements of the uniformity. -/ theorem uniformity_dist_of_mem_uniformity [linear_order β] {U : filter (α × α)} (z : β) (D : α → α → β) (H : ∀ s, s ∈ U ↔ ∃ε>z, ∀{a b:α}, D a b < ε → (a, b) ∈ s) : U = ⨅ ε>z, principal {p:α×α | D p.1 p.2 < ε} := le_antisymm (le_infi $ λ ε, le_infi $ λ ε0, le_principal_iff.2 $ (H _).2 ⟨ε, ε0, λ a b, id⟩) (λ r ur, let ⟨ε, ε0, h⟩ := (H _).1 ur in mem_infi_sets ε $ mem_infi_sets ε0 $ mem_principal_sets.2 $ λ ⟨a, b⟩, h) class has_edist (α : Type*) := (edist : α → α → ennreal) export has_edist (edist) /- Design note: one could define an `emetric_space` just by giving `edist`, and then derive an instance of `uniform_space` by taking the natural uniform structure associated to the distance. This creates diamonds problem for products, as the uniform structure on the product of two emetric spaces could be obtained first by obtaining two uniform spaces and then taking their products, or by taking the product of the emetric spaces and then the associated uniform structure. The two uniform structure we have just described are equal, but not defeq, which creates a lot of problem. The idea is to add, in the very definition of an `emetric_space`, a uniform structure with a uniformity which equal to the one given by the distance, but maybe not defeq. And the instance from `emetric_space` to `uniform_space` uses this uniformity. In this way, when we create the product of emetric spaces, we put in the product the uniformity corresponding to the product of the uniformities. There is one more proof obligation, that this product uniformity is equal to the uniformity corresponding to the product metric. But the diamond problem disappears. The same trick is used in the definition of a metric space, where one stores as well a uniform structure and an edistance. -/ /-- Creating a uniform space from an extended distance. -/ def uniform_space_of_edist (edist : α → α → ennreal) (edist_self : ∀ x : α, edist x x = 0) (edist_comm : ∀ x y : α, edist x y = edist y x) (edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) : uniform_space α := uniform_space.of_core { uniformity := (⨅ ε>0, principal {p:α×α | edist p.1 p.2 < ε}), refl := le_infi $ assume ε, le_infi $ by simp [set.subset_def, id_rel, edist_self, (>)] {contextual := tt}, comp := le_infi $ assume ε, le_infi $ assume h, have (2 : ennreal) = (2 : ℕ) := by simp, have A : 0 < ε / 2 := ennreal.div_pos_iff.2 ⟨ne_of_gt h, this ▸ ennreal.nat_ne_top 2⟩, lift'_le (mem_infi_sets (ε / 2) $ mem_infi_sets A (subset.refl _)) $ have ∀ (a b c : α), edist a c < ε / 2 → edist c b < ε / 2 → edist a b < ε, from assume a b c hac hcb, calc edist a b ≤ edist a c + edist c b : edist_triangle _ _ _ ... < ε / 2 + ε / 2 : ennreal.add_lt_add hac hcb ... = ε : by rw [ennreal.add_halves], by simpa [comp_rel], symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h, tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [edist_comm] } section prio set_option default_priority 100 -- see Note [default priority] /-- Extended metric spaces, with an extended distance `edist` possibly taking the value ∞ Each emetric space induces a canonical `uniform_space` and hence a canonical `topological_space`. This is enforced in the type class definition, by extending the `uniform_space` structure. When instantiating an `emetric_space` structure, the uniformity fields are not necessary, they will be filled in by default. There is a default value for the uniformity, that can be substituted in cases of interest, for instance when instantiating an `emetric_space` structure on a product. Continuity of `edist` is finally proving in `topology.instances.ennreal` -/ class emetric_space (α : Type u) extends has_edist α : Type u := (edist_self : ∀ x : α, edist x x = 0) (eq_of_edist_eq_zero : ∀ {x y : α}, edist x y = 0 → x = y) (edist_comm : ∀ x y : α, edist x y = edist y x) (edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) (to_uniform_space : uniform_space α := uniform_space_of_edist edist edist_self edist_comm edist_triangle) (uniformity_edist : 𝓤 α = ⨅ ε>0, principal {p:α×α | edist p.1 p.2 < ε} . control_laws_tac) end prio /- emetric spaces are less common than metric spaces. Therefore, we work in a dedicated namespace, while notions associated to metric spaces are mostly in the root namespace. -/ variables [emetric_space α] @[priority 100] -- see Note [lower instance priority] instance emetric_space.to_uniform_space' : uniform_space α := emetric_space.to_uniform_space α export emetric_space (edist_self eq_of_edist_eq_zero edist_comm edist_triangle) attribute [simp] edist_self /-- Characterize the equality of points by the vanishing of their extended distance -/ @[simp] theorem edist_eq_zero {x y : α} : edist x y = 0 ↔ x = y := iff.intro eq_of_edist_eq_zero (assume : x = y, this ▸ edist_self _) @[simp] theorem zero_eq_edist {x y : α} : 0 = edist x y ↔ x = y := iff.intro (assume h, eq_of_edist_eq_zero (h.symm)) (assume : x = y, this ▸ (edist_self _).symm) theorem edist_le_zero {x y : α} : (edist x y ≤ 0) ↔ x = y := le_zero_iff_eq.trans edist_eq_zero /-- Triangle inequality for the extended distance -/ theorem edist_triangle_left (x y z : α) : edist x y ≤ edist z x + edist z y := by rw edist_comm z; apply edist_triangle theorem edist_triangle_right (x y z : α) : edist x y ≤ edist x z + edist y z := by rw edist_comm y; apply edist_triangle lemma edist_triangle4 (x y z t : α) : edist x t ≤ edist x y + edist y z + edist z t := calc edist x t ≤ edist x z + edist z t : edist_triangle x z t ... ≤ (edist x y + edist y z) + edist z t : add_le_add_right' (edist_triangle x y z) /-- The triangle (polygon) inequality for sequences of points; `finset.Ico` version. -/ lemma edist_le_Ico_sum_edist (f : ℕ → α) {m n} (h : m ≤ n) : edist (f m) (f n) ≤ (finset.Ico m n).sum (λ i, edist (f i) (f (i + 1))) := begin revert n, refine nat.le_induction _ _, { simp only [finset.sum_empty, finset.Ico.self_eq_empty, edist_self], -- TODO: Why doesn't Lean close this goal automatically? `apply le_refl` fails too. exact le_refl (0:ennreal) }, { assume n hn hrec, calc edist (f m) (f (n+1)) ≤ edist (f m) (f n) + edist (f n) (f (n+1)) : edist_triangle _ _ _ ... ≤ (finset.Ico m n).sum _ + _ : add_le_add' hrec (le_refl _) ... = (finset.Ico m (n+1)).sum _ : by rw [finset.Ico.succ_top hn, finset.sum_insert, add_comm]; simp } end /-- The triangle (polygon) inequality for sequences of points; `finset.range` version. -/ lemma edist_le_range_sum_edist (f : ℕ → α) (n : ℕ) : edist (f 0) (f n) ≤ (finset.range n).sum (λ i, edist (f i) (f (i + 1))) := finset.Ico.zero_bot n ▸ edist_le_Ico_sum_edist f (nat.zero_le n) /-- A version of `edist_le_Ico_sum_edist` with each intermediate distance replaced with an upper estimate. -/ lemma edist_le_Ico_sum_of_edist_le {f : ℕ → α} {m n} (hmn : m ≤ n) {d : ℕ → ennreal} (hd : ∀ {k}, m ≤ k → k < n → edist (f k) (f (k + 1)) ≤ d k) : edist (f m) (f n) ≤ (finset.Ico m n).sum d := le_trans (edist_le_Ico_sum_edist f hmn) $ finset.sum_le_sum $ λ k hk, hd (finset.Ico.mem.1 hk).1 (finset.Ico.mem.1 hk).2 /-- A version of `edist_le_range_sum_edist` with each intermediate distance replaced with an upper estimate. -/ lemma edist_le_range_sum_of_edist_le {f : ℕ → α} (n : ℕ) {d : ℕ → ennreal} (hd : ∀ {k}, k < n → edist (f k) (f (k + 1)) ≤ d k) : edist (f 0) (f n) ≤ (finset.range n).sum d := finset.Ico.zero_bot n ▸ edist_le_Ico_sum_of_edist_le (zero_le n) (λ _ _, hd) /-- Two points coincide if their distance is `< ε` for all positive ε -/ theorem eq_of_forall_edist_le {x y : α} (h : ∀ε, ε > 0 → edist x y ≤ ε) : x = y := eq_of_edist_eq_zero (eq_of_le_of_forall_le_of_dense bot_le h) /-- Reformulation of the uniform structure in terms of the extended distance -/ theorem uniformity_edist : 𝓤 α = ⨅ ε>0, principal {p:α×α | edist p.1 p.2 < ε} := emetric_space.uniformity_edist α theorem uniformity_basis_edist : (𝓤 α).has_basis (λ ε : ennreal, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 < ε}) := (@uniformity_edist α _).symm ▸ has_basis_binfi_principal (λ r hr p hp, ⟨min r p, lt_min hr hp, λ x hx, lt_of_lt_of_le hx (min_le_left _ _), λ x hx, lt_of_lt_of_le hx (min_le_right _ _)⟩) ⟨1, ennreal.zero_lt_one⟩ /-- Characterization of the elements of the uniformity in terms of the extended distance -/ theorem mem_uniformity_edist {s : set (α×α)} : s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, edist a b < ε → (a, b) ∈ s) := uniformity_basis_edist.mem_uniformity_iff /-- Given `f : β → ennreal`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`. For specific bases see `uniformity_basis_edist`, `uniformity_basis_edist'`, `uniformity_basis_edist_nnreal`, and `uniformity_basis_edist_inv_nat`. -/ protected theorem emetric.mk_uniformity_basis {β : Type*} {p : β → Prop} {f : β → ennreal} (hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) : (𝓤 α).has_basis p (λ x, {p:α×α | edist p.1 p.2 < f x}) := begin refine λ s, uniformity_basis_edist.mem_iff.trans _, split, { rintros ⟨ε, ε₀, hε⟩, rcases hf ε ε₀ with ⟨i, hi, H⟩, exact ⟨i, hi, λ x hx, hε $ lt_of_lt_of_le hx H⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, H⟩ } end /-- Given `f : β → ennreal`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then closed `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`. For specific bases see `uniformity_basis_edist_le` and `uniformity_basis_edist_le'`. -/ protected theorem emetric.mk_uniformity_basis_le {β : Type*} {p : β → Prop} {f : β → ennreal} (hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) : (𝓤 α).has_basis p (λ x, {p:α×α | edist p.1 p.2 ≤ f x}) := begin refine λ s, uniformity_basis_edist.mem_iff.trans _, split, { rintros ⟨ε, ε₀, hε⟩, rcases dense ε₀ with ⟨ε', hε'⟩, rcases hf ε' hε'.1 with ⟨i, hi, H⟩, exact ⟨i, hi, λ x hx, hε $ lt_of_le_of_lt (le_trans hx H) hε'.2⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, λ x hx, H (le_of_lt hx)⟩ } end theorem uniformity_basis_edist_le : (𝓤 α).has_basis (λ ε : ennreal, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 ≤ ε}) := emetric.mk_uniformity_basis_le (λ _, id) (λ ε ε₀, ⟨ε, ε₀, le_refl ε⟩) theorem uniformity_basis_edist' (ε' : ennreal) (hε' : 0 < ε') : (𝓤 α).has_basis (λ ε : ennreal, ε ∈ Ioo 0 ε') (λ ε, {p:α×α | edist p.1 p.2 < ε}) := emetric.mk_uniformity_basis (λ _, and.left) (λ ε ε₀, let ⟨δ, hδ⟩ := dense hε' in ⟨min ε δ, ⟨lt_min ε₀ hδ.1, lt_of_le_of_lt (min_le_right _ _) hδ.2⟩, min_le_left _ _⟩) theorem uniformity_basis_edist_le' (ε' : ennreal) (hε' : 0 < ε') : (𝓤 α).has_basis (λ ε : ennreal, ε ∈ Ioo 0 ε') (λ ε, {p:α×α | edist p.1 p.2 ≤ ε}) := emetric.mk_uniformity_basis_le (λ _, and.left) (λ ε ε₀, let ⟨δ, hδ⟩ := dense hε' in ⟨min ε δ, ⟨lt_min ε₀ hδ.1, lt_of_le_of_lt (min_le_right _ _) hδ.2⟩, min_le_left _ _⟩) theorem uniformity_basis_edist_nnreal : (𝓤 α).has_basis (λ ε : nnreal, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 < ε}) := emetric.mk_uniformity_basis (λ _, ennreal.coe_pos.2) (λ ε ε₀, let ⟨δ, hδ⟩ := with_top.dense_coe ε₀ in ⟨δ, ennreal.coe_pos.1 hδ.1, le_of_lt hδ.2⟩) theorem uniformity_basis_edist_inv_nat : (𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | edist p.1 p.2 < (↑n)⁻¹}) := emetric.mk_uniformity_basis (λ n _, ennreal.inv_pos.2 $ ennreal.nat_ne_top n) (λ ε ε₀, let ⟨n, hn⟩ := ennreal.exists_inv_nat_lt (ne_of_gt ε₀) in ⟨n, trivial, le_of_lt hn⟩) /-- Fixed size neighborhoods of the diagonal belong to the uniform structure -/ theorem edist_mem_uniformity {ε:ennreal} (ε0 : 0 < ε) : {p:α×α | edist p.1 p.2 < ε} ∈ 𝓤 α := mem_uniformity_edist.2 ⟨ε, ε0, λ a b, id⟩ namespace emetric theorem uniformity_has_countable_basis : has_countable_basis (𝓤 α) := has_countable_basis_of_seq _ _ uniformity_basis_edist_inv_nat.eq_infi /-- ε-δ characterization of uniform continuity on emetric spaces -/ theorem uniform_continuous_iff [emetric_space β] {f : α → β} : uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0, ∀{a b:α}, edist a b < δ → edist (f a) (f b) < ε := uniformity_basis_edist.uniform_continuous_iff uniformity_basis_edist /-- ε-δ characterization of uniform embeddings on emetric spaces -/ theorem uniform_embedding_iff [emetric_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ := uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl ⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (edist_mem_uniformity δ0), ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 tu in ⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩, λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_edist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in ⟨_, edist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩ /-- A map between emetric spaces is a uniform embedding if and only if the edistance between `f x` and `f y` is controlled in terms of the distance between `x` and `y` and conversely. -/ theorem uniform_embedding_iff' [emetric_space β] {f : α → β} : uniform_embedding f ↔ (∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, edist a b < δ → edist (f a) (f b) < ε) ∧ (∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ) := begin split, { assume h, exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1, (uniform_embedding_iff.1 h).2.2⟩ }, { rintros ⟨h₁, h₂⟩, refine uniform_embedding_iff.2 ⟨_, uniform_continuous_iff.2 h₁, h₂⟩, assume x y hxy, have : edist x y ≤ 0, { refine le_of_forall_lt' (λδ δpos, _), rcases h₂ δ δpos with ⟨ε, εpos, hε⟩, have : edist (f x) (f y) < ε, by simpa [hxy], exact hε this }, simpa using this } end /-- ε-δ characterization of Cauchy sequences on emetric spaces -/ protected lemma cauchy_iff {f : filter α} : cauchy f ↔ f ≠ ⊥ ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, edist x y < ε := uniformity_basis_edist.cauchy_iff /-- A very useful criterion to show that a space is complete is to show that all sequences which satisfy a bound of the form `edist (u n) (u m) < B N` for all `n m ≥ N` are converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to `0`, which makes it possible to use arguments of converging series, while this is impossible to do in general for arbitrary Cauchy sequences. -/ theorem complete_of_convergent_controlled_sequences (B : ℕ → ennreal) (hB : ∀n, 0 < B n) (H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → edist (u n) (u m) < B N) → ∃x, tendsto u at_top (𝓝 x)) : complete_space α := uniform_space.complete_of_convergent_controlled_sequences uniformity_has_countable_basis (λ n, {p:α×α | edist p.1 p.2 < B n}) (λ n, edist_mem_uniformity $ hB n) H /-- A sequentially complete emetric space is complete. -/ theorem complete_of_cauchy_seq_tendsto : (∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) → complete_space α := uniform_space.complete_of_cauchy_seq_tendsto uniformity_has_countable_basis end emetric open emetric /-- An emetric space is separated -/ @[priority 100] -- see Note [lower instance priority] instance to_separated : separated α := separated_def.2 $ λ x y h, eq_of_forall_edist_le $ λ ε ε0, le_of_lt (h _ (edist_mem_uniformity ε0)) /-- Auxiliary function to replace the uniformity on an emetric space with a uniformity which is equal to the original one, but maybe not defeq. This is useful if one wants to construct an emetric space with a specified uniformity. -/ def emetric_space.replace_uniformity {α} [U : uniform_space α] (m : emetric_space α) (H : @uniformity _ U = @uniformity _ (emetric_space.to_uniform_space α)) : emetric_space α := { edist := @edist _ m.to_has_edist, edist_self := edist_self, eq_of_edist_eq_zero := @eq_of_edist_eq_zero _ _, edist_comm := edist_comm, edist_triangle := edist_triangle, to_uniform_space := U, uniformity_edist := H.trans (@emetric_space.uniformity_edist α _) } /-- The extended metric induced by an injective function taking values in an emetric space. -/ def emetric_space.induced {α β} (f : α → β) (hf : function.injective f) (m : emetric_space β) : emetric_space α := { edist := λ x y, edist (f x) (f y), edist_self := λ x, edist_self _, eq_of_edist_eq_zero := λ x y h, hf (edist_eq_zero.1 h), edist_comm := λ x y, edist_comm _ _, edist_triangle := λ x y z, edist_triangle _ _ _, to_uniform_space := uniform_space.comap f m.to_uniform_space, uniformity_edist := begin apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, edist (f x) (f y)), refine λ s, mem_comap_sets.trans _, split; intro H, { rcases H with ⟨r, ru, rs⟩, rcases mem_uniformity_edist.1 ru with ⟨ε, ε0, hε⟩, refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h }, { rcases H with ⟨ε, ε0, hε⟩, exact ⟨_, edist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ } end } /-- Emetric space instance on subsets of emetric spaces -/ instance {α : Type*} {p : α → Prop} [t : emetric_space α] : emetric_space (subtype p) := t.induced coe (λ x y, subtype.coe_ext.2) /-- The extended distance on a subset of an emetric space is the restriction of the original distance, by definition -/ theorem subtype.edist_eq {p : α → Prop} (x y : subtype p) : edist x y = edist (x : α) y := rfl /-- The product of two emetric spaces, with the max distance, is an extended metric spaces. We make sure that the uniform structure thus constructed is the one corresponding to the product of uniform spaces, to avoid diamond problems. -/ instance prod.emetric_space_max [emetric_space β] : emetric_space (α × β) := { edist := λ x y, max (edist x.1 y.1) (edist x.2 y.2), edist_self := λ x, by simp, eq_of_edist_eq_zero := λ x y h, begin cases max_le_iff.1 (le_of_eq h) with h₁ h₂, have A : x.fst = y.fst := edist_le_zero.1 h₁, have B : x.snd = y.snd := edist_le_zero.1 h₂, exact prod.ext_iff.2 ⟨A, B⟩ end, edist_comm := λ x y, by simp [edist_comm], edist_triangle := λ x y z, max_le (le_trans (edist_triangle _ _ _) (add_le_add' (le_max_left _ _) (le_max_left _ _))) (le_trans (edist_triangle _ _ _) (add_le_add' (le_max_right _ _) (le_max_right _ _))), uniformity_edist := begin refine uniformity_prod.trans _, simp [emetric_space.uniformity_edist, comap_infi], rw ← infi_inf_eq, congr, funext, rw ← infi_inf_eq, congr, funext, simp [inf_principal, ext_iff, max_lt_iff] end, to_uniform_space := prod.uniform_space } lemma prod.edist_eq [emetric_space β] (x y : α × β) : edist x y = max (edist x.1 y.1) (edist x.2 y.2) := rfl section pi open finset variables {π : β → Type*} [fintype β] /-- The product of a finite number of emetric spaces, with the max distance, is still an emetric space. This construction would also work for infinite products, but it would not give rise to the product topology. Hence, we only formalize it in the good situation of finitely many spaces. -/ instance emetric_space_pi [∀b, emetric_space (π b)] : emetric_space (Πb, π b) := { edist := λ f g, finset.sup univ (λb, edist (f b) (g b)), edist_self := assume f, bot_unique $ finset.sup_le $ by simp, edist_comm := assume f g, by unfold edist; congr; funext a; exact edist_comm _ _, edist_triangle := assume f g h, begin simp only [finset.sup_le_iff], assume b hb, exact le_trans (edist_triangle _ (g b) _) (add_le_add' (le_sup hb) (le_sup hb)) end, eq_of_edist_eq_zero := assume f g eq0, begin have eq1 : sup univ (λ (b : β), edist (f b) (g b)) ≤ 0 := le_of_eq eq0, simp only [finset.sup_le_iff] at eq1, exact (funext $ assume b, edist_le_zero.1 $ eq1 b $ mem_univ b), end, to_uniform_space := Pi.uniform_space _, uniformity_edist := begin simp only [Pi.uniformity, emetric_space.uniformity_edist, comap_infi, gt_iff_lt, preimage_set_of_eq, comap_principal], rw infi_comm, congr, funext ε, rw infi_comm, congr, funext εpos, change 0 < ε at εpos, simp [ext_iff, εpos] end } end pi namespace emetric variables {x y z : α} {ε ε₁ ε₂ : ennreal} {s : set α} /-- `emetric.ball x ε` is the set of all points `y` with `edist y x < ε` -/ def ball (x : α) (ε : ennreal) : set α := {y | edist y x < ε} @[simp] theorem mem_ball : y ∈ ball x ε ↔ edist y x < ε := iff.rfl theorem mem_ball' : y ∈ ball x ε ↔ edist x y < ε := by rw edist_comm; refl /-- `emetric.closed_ball x ε` is the set of all points `y` with `edist y x ≤ ε` -/ def closed_ball (x : α) (ε : ennreal) := {y | edist y x ≤ ε} @[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ edist y x ≤ ε := iff.rfl theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε := assume y, by simp; intros h; apply le_of_lt h theorem pos_of_mem_ball (hy : y ∈ ball x ε) : 0 < ε := lt_of_le_of_lt (zero_le _) hy theorem mem_ball_self (h : 0 < ε) : x ∈ ball x ε := show edist x x < ε, by rw edist_self; assumption theorem mem_closed_ball_self : x ∈ closed_ball x ε := show edist x x ≤ ε, by rw edist_self; exact bot_le theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε := by simp [edist_comm] theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ := λ y (yx : _ < ε₁), lt_of_lt_of_le yx h theorem closed_ball_subset_closed_ball (h : ε₁ ≤ ε₂) : closed_ball x ε₁ ⊆ closed_ball x ε₂ := λ y (yx : _ ≤ ε₁), le_trans yx h theorem ball_disjoint (h : ε₁ + ε₂ ≤ edist x y) : ball x ε₁ ∩ ball y ε₂ = ∅ := eq_empty_iff_forall_not_mem.2 $ λ z ⟨h₁, h₂⟩, not_lt_of_le (edist_triangle_left x y z) (lt_of_lt_of_le (ennreal.add_lt_add h₁ h₂) h) theorem ball_subset (h : edist x y + ε₁ ≤ ε₂) (h' : edist x y < ⊤) : ball x ε₁ ⊆ ball y ε₂ := λ z zx, calc edist z y ≤ edist z x + edist x y : edist_triangle _ _ _ ... = edist x y + edist z x : add_comm _ _ ... < edist x y + ε₁ : (ennreal.add_lt_add_iff_left h').2 zx ... ≤ ε₂ : h theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε := begin have : 0 < ε - edist y x := by simpa using h, refine ⟨ε - edist y x, this, ball_subset _ _⟩, { rw ennreal.add_sub_cancel_of_le (le_of_lt h), apply le_refl _}, { have : edist y x ≠ ⊤ := ne_top_of_lt h, apply lt_top_iff_ne_top.2 this } end theorem ball_eq_empty_iff : ball x ε = ∅ ↔ ε = 0 := eq_empty_iff_forall_not_mem.trans ⟨λh, le_bot_iff.1 (le_of_not_gt (λ ε0, h _ (mem_ball_self ε0))), λε0 y h, not_lt_of_le (le_of_eq ε0) (pos_of_mem_ball h)⟩ /-- Relation “two points are at a finite edistance” is an equivalence relation. -/ def edist_lt_top_setoid : setoid α := { r := λ x y, edist x y < ⊤, iseqv := ⟨λ x, by { rw edist_self, exact ennreal.coe_lt_top }, λ x y h, by rwa edist_comm, λ x y z hxy hyz, lt_of_le_of_lt (edist_triangle x y z) (ennreal.add_lt_top.2 ⟨hxy, hyz⟩)⟩ } @[simp] lemma ball_zero : ball x 0 = ∅ := by rw [emetric.ball_eq_empty_iff] theorem nhds_basis_eball : (𝓝 x).has_basis (λ ε:ennreal, 0 < ε) (ball x) := nhds_basis_uniformity uniformity_basis_edist theorem nhds_eq : 𝓝 x = (⨅ε>0, principal (ball x ε)) := nhds_basis_eball.eq_binfi theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ε>0, ball x ε ⊆ s := nhds_basis_eball s theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s := by simp [is_open_iff_nhds, mem_nhds_iff] theorem is_open_ball : is_open (ball x ε) := is_open_iff.2 $ λ y, exists_ball_subset_ball theorem is_closed_ball_top : is_closed (ball x ⊤) := is_open_iff.2 $ λ y hy, ⟨⊤, ennreal.coe_lt_top, subset_compl_iff_disjoint.2 $ ball_disjoint $ by { rw ennreal.top_add, exact le_of_not_lt hy }⟩ theorem ball_mem_nhds (x : α) {ε : ennreal} (ε0 : 0 < ε) : ball x ε ∈ 𝓝 x := mem_nhds_sets is_open_ball (mem_ball_self ε0) /-- ε-characterization of the closure in emetric spaces -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem mem_closure_iff : x ∈ closure s ↔ ∀ε>0, ∃y ∈ s, edist x y < ε := (mem_closure_iff_nhds_basis nhds_basis_eball).trans $ by simp only [mem_ball, edist_comm x] theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, edist (u x) a < ε := nhds_basis_eball.tendsto_right_iff theorem tendsto_at_top [nonempty β] [semilattice_sup β] (u : β → α) {a : α} : tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, edist (u n) a < ε := (at_top_basis.tendsto_iff nhds_basis_eball).trans $ by simp only [exists_prop, true_and, mem_Ici, mem_ball] /-- In an emetric space, Cauchy sequences are characterized by the fact that, eventually, the edistance between its elements is arbitrarily small -/ theorem cauchy_seq_iff [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, edist (u m) (u n) < ε := uniformity_basis_edist.cauchy_seq_iff /-- A variation around the emetric characterization of Cauchy sequences -/ theorem cauchy_seq_iff' [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ε>(0 : ennreal), ∃N, ∀n≥N, edist (u n) (u N) < ε := uniformity_basis_edist.cauchy_seq_iff' /-- A variation of the emetric characterization of Cauchy sequences that deals with `nnreal` upper bounds. -/ theorem cauchy_seq_iff_nnreal [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ ε : nnreal, 0 < ε → ∃ N, ∀ n, N ≤ n → edist (u n) (u N) < ε := uniformity_basis_edist_nnreal.cauchy_seq_iff' theorem totally_bounded_iff {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t : set α, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, H _ (edist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨t, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ theorem totally_bounded_iff' {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t⊆s, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, (totally_bounded_iff_subset.1 H) _ (edist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨t, _, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ section compact /-- A compact set in an emetric space is separable, i.e., it is the closure of a countable set -/ lemma countable_closure_of_compact {α : Type u} [emetric_space α] {s : set α} (hs : compact s) : ∃ t ⊆ s, (countable t ∧ s = closure t) := begin have A : ∀ (e:ennreal), e > 0 → ∃ t ⊆ s, (finite t ∧ s ⊆ (⋃x∈t, ball x e)) := totally_bounded_iff'.1 (compact_iff_totally_bounded_complete.1 hs).1, -- assume e, finite_cover_balls_of_compact hs, have B : ∀ (e:ennreal), ∃ t ⊆ s, finite t ∧ (e > 0 → s ⊆ (⋃x∈t, ball x e)), { intro e, cases le_or_gt e 0 with h, { exact ⟨∅, by finish⟩ }, { rcases A e h with ⟨s, ⟨finite_s, closure_s⟩⟩, existsi s, finish }}, /-The desired countable set is obtained by taking for each `n` the centers of a finite cover by balls of radius `1/n`, and then the union over `n`. -/ choose T T_in_s finite_T using B, let t := ⋃n:ℕ, T n⁻¹, have T₁ : t ⊆ s := begin apply Union_subset, assume n, apply T_in_s end, have T₂ : countable t := by finish [countable_Union, countable_finite], have T₃ : s ⊆ closure t, { intros x x_in_s, apply mem_closure_iff.2, intros ε εpos, rcases ennreal.exists_inv_nat_lt (bot_lt_iff_ne_bot.1 εpos) with ⟨n, hn⟩, have inv_n_pos : (0 : ennreal) < (n : ℕ)⁻¹ := by simp [ennreal.bot_lt_iff_ne_bot], have C : x ∈ (⋃y∈ T (n : ℕ)⁻¹, ball y (n : ℕ)⁻¹) := mem_of_mem_of_subset x_in_s ((finite_T (n : ℕ)⁻¹).2 inv_n_pos), rcases mem_Union.1 C with ⟨y, _, ⟨y_in_T, rfl⟩, Dxy⟩, simp at Dxy, -- Dxy : edist x y < 1 / ↑n have : y ∈ t := mem_of_mem_of_subset y_in_T (by apply subset_Union (λ (n:ℕ), T (n : ℕ)⁻¹)), have : edist x y < ε := lt_trans Dxy hn, exact ⟨y, ‹y ∈ t›, ‹edist x y < ε›⟩ }, have T₄ : closure t ⊆ s := calc closure t ⊆ closure s : closure_mono T₁ ... = s : closure_eq_of_is_closed (closed_of_compact _ hs), exact ⟨t, ⟨T₁, T₂, subset.antisymm T₃ T₄⟩⟩ end end compact section first_countable @[priority 100] -- see Note [lower instance priority] instance (α : Type u) [emetric_space α] : topological_space.first_countable_topology α := uniform_space.first_countable_topology uniformity_has_countable_basis end first_countable section second_countable open topological_space /-- A separable emetric space is second countable: one obtains a countable basis by taking the balls centered at points in a dense subset, and with rational radii. We do not register this as an instance, as there is already an instance going in the other direction from second countable spaces to separable spaces, and we want to avoid loops. -/ lemma second_countable_of_separable (α : Type u) [emetric_space α] [separable_space α] : second_countable_topology α := let ⟨S, ⟨S_countable, S_dense⟩⟩ := separable_space.exists_countable_closure_eq_univ α in ⟨⟨⋃x ∈ S, ⋃ (n : nat), {ball x (n⁻¹)}, ⟨show countable ⋃x ∈ S, ⋃ (n : nat), {ball x (n⁻¹)}, { apply countable_bUnion S_countable, intros a aS, apply countable_Union, simp }, show uniform_space.to_topological_space α = generate_from (⋃x ∈ S, ⋃ (n : nat), {ball x (n⁻¹)}), { have A : ∀ (u : set α), (u ∈ ⋃x ∈ S, ⋃ (n : nat), ({ball x ((n : ennreal)⁻¹)} : set (set α))) → is_open u, { simp only [and_imp, exists_prop, set.mem_Union, set.mem_singleton_iff, exists_imp_distrib], intros u x hx i u_ball, rw [u_ball], exact is_open_ball }, have B : is_topological_basis (⋃x ∈ S, ⋃ (n : nat), ({ball x (n⁻¹)} : set (set α))), { refine is_topological_basis_of_open_of_nhds A (λa u au open_u, _), rcases is_open_iff.1 open_u a au with ⟨ε, εpos, εball⟩, have : ε / 2 > 0 := ennreal.half_pos εpos, /- The ball `ball a ε` is included in `u`. We need to find one of our balls `ball x (n⁻¹)` containing `a` and contained in `ball a ε`. For this, we take `n` larger than `2/ε`, and then `x` in `S` at distance at most `n⁻¹` of `a` -/ rcases ennreal.exists_inv_nat_lt (bot_lt_iff_ne_bot.1 (ennreal.half_pos εpos)) with ⟨n, εn⟩, have : (0 : ennreal) < n⁻¹ := by simp [ennreal.bot_lt_iff_ne_bot], have : (a : α) ∈ closure (S : set α) := by rw [S_dense]; simp, rcases mem_closure_iff.1 this _ ‹(0 : ennreal) < n⁻¹› with ⟨x, xS, xdist⟩, existsi ball x (↑n)⁻¹, have I : ball x (n⁻¹) ⊆ ball a ε := λy ydist, calc edist y a = edist a y : edist_comm _ _ ... ≤ edist a x + edist y x : edist_triangle_right _ _ _ ... < n⁻¹ + n⁻¹ : ennreal.add_lt_add xdist ydist ... < ε/2 + ε/2 : ennreal.add_lt_add εn εn ... = ε : ennreal.add_halves _, simp only [emetric.mem_ball, exists_prop, set.mem_Union, set.mem_singleton_iff], exact ⟨⟨x, ⟨xS, ⟨n, rfl⟩⟩⟩, ⟨by simpa, subset.trans I εball⟩⟩ }, exact B.2.2 }⟩⟩⟩ end second_countable section diam /-- The diameter of a set in an emetric space, named `emetric.diam` -/ def diam (s : set α) := ⨆ (x ∈ s) (y ∈ s), edist x y lemma diam_le_iff_forall_edist_le {d : ennreal} : diam s ≤ d ↔ ∀ (x ∈ s) (y ∈ s), edist x y ≤ d := by simp only [diam, supr_le_iff] /-- If two points belong to some set, their edistance is bounded by the diameter of the set -/ lemma edist_le_diam_of_mem (hx : x ∈ s) (hy : y ∈ s) : edist x y ≤ diam s := diam_le_iff_forall_edist_le.1 (le_refl _) x hx y hy /-- If the distance between any two points in a set is bounded by some constant, this constant bounds the diameter. -/ lemma diam_le_of_forall_edist_le {d : ennreal} (h : ∀ (x ∈ s) (y ∈ s), edist x y ≤ d) : diam s ≤ d := diam_le_iff_forall_edist_le.2 h /-- The diameter of a subsingleton vanishes. -/ lemma diam_subsingleton (hs : s.subsingleton) : diam s = 0 := le_zero_iff_eq.1 $ diam_le_of_forall_edist_le $ λ x hx y hy, (hs hx hy).symm ▸ edist_self y ▸ le_refl _ /-- The diameter of the empty set vanishes -/ @[simp] lemma diam_empty : diam (∅ : set α) = 0 := diam_subsingleton subsingleton_empty /-- The diameter of a singleton vanishes -/ @[simp] lemma diam_singleton : diam ({x} : set α) = 0 := diam_subsingleton subsingleton_singleton lemma diam_eq_zero_iff : diam s = 0 ↔ s.subsingleton := ⟨λ h x hx y hy, edist_le_zero.1 $ h ▸ edist_le_diam_of_mem hx hy, diam_subsingleton⟩ lemma diam_pos_iff : 0 < diam s ↔ ∃ (x ∈ s) (y ∈ s), x ≠ y := begin have := not_congr (@diam_eq_zero_iff _ _ s), dunfold set.subsingleton at this, push_neg at this, simpa only [zero_lt_iff_ne_zero, exists_prop] using this end lemma diam_insert : diam (insert x s) = max (diam s) (⨆ y ∈ s, edist y x) := eq_of_forall_ge_iff $ λ d, by simp only [diam_le_iff_forall_edist_le, ball_insert_iff, max_le_iff, edist_self, zero_le, true_and, supr_le_iff, forall_and_distrib, edist_comm x, and_self, (and_assoc _ _).symm, max_comm (diam s)] lemma diam_pair : diam ({x, y} : set α) = edist x y := by simp only [supr_singleton, diam_insert, diam_singleton, ennreal.max_zero_left] lemma diam_triple : diam ({x, y, z} : set α) = max (edist x y) (max (edist y z) (edist x z)) := by simp only [diam_insert, supr_insert, supr_singleton, diam_singleton, ennreal.max_zero_left, ennreal.sup_eq_max] /-- The diameter is monotonous with respect to inclusion -/ lemma diam_mono {s t : set α} (h : s ⊆ t) : diam s ≤ diam t := diam_le_of_forall_edist_le $ λ x hx y hy, edist_le_diam_of_mem (h hx) (h hy) /-- The diameter of a union is controlled by the diameter of the sets, and the edistance between two points in the sets. -/ lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) : diam (s ∪ t) ≤ diam s + edist x y + diam t := begin have A : ∀a ∈ s, ∀b ∈ t, edist a b ≤ diam s + edist x y + diam t := λa ha b hb, calc edist a b ≤ edist a x + edist x y + edist y b : edist_triangle4 _ _ _ _ ... ≤ diam s + edist x y + diam t : add_le_add' (add_le_add' (edist_le_diam_of_mem ha xs) (le_refl _)) (edist_le_diam_of_mem yt hb), refine diam_le_of_forall_edist_le (λa ha b hb, _), cases (mem_union _ _ _).1 ha with h'a h'a; cases (mem_union _ _ _).1 hb with h'b h'b, { calc edist a b ≤ diam s : edist_le_diam_of_mem h'a h'b ... ≤ diam s + (edist x y + diam t) : le_add_right (le_refl _) ... = diam s + edist x y + diam t : by simp only [add_comm, eq_self_iff_true, add_left_comm] }, { exact A a h'a b h'b }, { have Z := A b h'b a h'a, rwa [edist_comm] at Z }, { calc edist a b ≤ diam t : edist_le_diam_of_mem h'a h'b ... ≤ (diam s + edist x y) + diam t : le_add_left (le_refl _) } end lemma diam_union' {t : set α} (h : (s ∩ t).nonempty) : diam (s ∪ t) ≤ diam s + diam t := let ⟨x, ⟨xs, xt⟩⟩ := h in by simpa using diam_union xs xt lemma diam_closed_ball {r : ennreal} : diam (closed_ball x r) ≤ 2 * r := diam_le_of_forall_edist_le $ λa ha b hb, calc edist a b ≤ edist a x + edist b x : edist_triangle_right _ _ _ ... ≤ r + r : add_le_add' ha hb ... = 2 * r : by simp [mul_two, mul_comm] lemma diam_ball {r : ennreal} : diam (ball x r) ≤ 2 * r := le_trans (diam_mono ball_subset_closed_ball) diam_closed_ball end diam end emetric --namespace
148cebbb627c9ab86a8ffb9c8f7b825b6047c869
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/order/fixed_points_auto.lean
a6a178aba2feb88648800e9be88c7a9f0a076a3b
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
7,106
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, Kenny Lau -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.order.complete_lattice import Mathlib.dynamics.fixed_points.basic import Mathlib.PostPort universes u v namespace Mathlib /-! # Fixed point construction on complete lattices -/ /-- Least fixed point of a monotone function -/ /-- Greatest fixed point of a monotone function -/ def lfp {α : Type u} [complete_lattice α] (f : α → α) : α := Inf (set_of fun (a : α) => f a ≤ a) def gfp {α : Type u} [complete_lattice α] (f : α → α) : α := Sup (set_of fun (a : α) => a ≤ f a) theorem lfp_le {α : Type u} [complete_lattice α] {f : α → α} {a : α} (h : f a ≤ a) : lfp f ≤ a := Inf_le h theorem le_lfp {α : Type u} [complete_lattice α] {f : α → α} {a : α} (h : ∀ (b : α), f b ≤ b → a ≤ b) : a ≤ lfp f := le_Inf h theorem lfp_eq {α : Type u} [complete_lattice α] {f : α → α} (m : monotone f) : lfp f = f (lfp f) := (fun (this : f (lfp f) ≤ lfp f) => le_antisymm (lfp_le (m this)) this) (le_lfp fun (b : α) (h : f b ≤ b) => le_trans (m (lfp_le h)) h) theorem lfp_induct {α : Type u} [complete_lattice α] {f : α → α} {p : α → Prop} (m : monotone f) (step : ∀ (a : α), p a → a ≤ lfp f → p (f a)) (sup : ∀ (s : set α), (∀ (a : α), a ∈ s → p a) → p (Sup s)) : p (lfp f) := sorry theorem monotone_lfp {α : Type u} [complete_lattice α] : monotone lfp := fun (f g : α → α) (this : f ≤ g) => le_lfp fun (a : α) (this_1 : g a ≤ a) => lfp_le (le_trans (this a) this_1) theorem le_gfp {α : Type u} [complete_lattice α] {f : α → α} {a : α} (h : a ≤ f a) : a ≤ gfp f := le_Sup h theorem gfp_le {α : Type u} [complete_lattice α] {f : α → α} {a : α} (h : ∀ (b : α), b ≤ f b → b ≤ a) : gfp f ≤ a := Sup_le h theorem gfp_eq {α : Type u} [complete_lattice α] {f : α → α} (m : monotone f) : gfp f = f (gfp f) := (fun (this : gfp f ≤ f (gfp f)) => le_antisymm this (le_gfp (m this))) (gfp_le fun (b : α) (h : b ≤ f b) => le_trans h (m (le_gfp h))) theorem gfp_induct {α : Type u} [complete_lattice α] {f : α → α} {p : α → Prop} (m : monotone f) (step : ∀ (a : α), p a → gfp f ≤ a → p (f a)) (inf : ∀ (s : set α), (∀ (a : α), a ∈ s → p a) → p (Inf s)) : p (gfp f) := sorry theorem monotone_gfp {α : Type u} [complete_lattice α] : monotone gfp := fun (f g : α → α) (this : f ≤ g) => gfp_le fun (a : α) (this_1 : a ≤ f a) => le_gfp (le_trans this_1 (this a)) -- Rolling rule theorem lfp_comp {α : Type u} {β : Type v} [complete_lattice α] [complete_lattice β] {f : β → α} {g : α → β} (m_f : monotone f) (m_g : monotone g) : lfp (f ∘ g) = f (lfp (g ∘ f)) := sorry theorem gfp_comp {α : Type u} {β : Type v} [complete_lattice α] [complete_lattice β] {f : β → α} {g : α → β} (m_f : monotone f) (m_g : monotone g) : gfp (f ∘ g) = f (gfp (g ∘ f)) := sorry -- Diagonal rule theorem lfp_lfp {α : Type u} [complete_lattice α] {h : α → α → α} (m : ∀ {a b c d : α}, a ≤ b → c ≤ d → h a c ≤ h b d) : lfp (lfp ∘ h) = lfp fun (x : α) => h x x := sorry theorem gfp_gfp {α : Type u} [complete_lattice α] {h : α → α → α} (m : ∀ {a b c d : α}, a ≤ b → c ≤ d → h a c ≤ h b d) : gfp (gfp ∘ h) = gfp fun (x : α) => h x x := sorry /- The complete lattice of fixed points of a function f -/ namespace fixed_points def prev {α : Type u} [complete_lattice α] (f : α → α) (x : α) : α := gfp fun (z : α) => x ⊓ f z def next {α : Type u} [complete_lattice α] (f : α → α) (x : α) : α := lfp fun (z : α) => x ⊔ f z theorem prev_le {α : Type u} [complete_lattice α] {f : α → α} {x : α} : prev f x ≤ x := gfp_le fun (z : α) (hz : z ≤ x ⊓ f z) => le_trans hz inf_le_left theorem prev_eq {α : Type u} [complete_lattice α] {f : α → α} (hf : monotone f) {a : α} (h : f a ≤ a) : prev f a = f (prev f a) := sorry def prev_fixed {α : Type u} [complete_lattice α] {f : α → α} (hf : monotone f) (a : α) (h : f a ≤ a) : ↥(function.fixed_points f) := { val := prev f a, property := sorry } theorem next_le {α : Type u} [complete_lattice α] {f : α → α} {x : α} : x ≤ next f x := le_lfp fun (z : α) (hz : x ⊔ f z ≤ z) => le_trans le_sup_left hz theorem next_eq {α : Type u} [complete_lattice α] {f : α → α} (hf : monotone f) {a : α} (h : a ≤ f a) : next f a = f (next f a) := sorry def next_fixed {α : Type u} [complete_lattice α] {f : α → α} (hf : monotone f) (a : α) (h : a ≤ f a) : ↥(function.fixed_points f) := { val := next f a, property := sorry } theorem sup_le_f_of_fixed_points {α : Type u} [complete_lattice α] (f : α → α) (hf : monotone f) (x : ↥(function.fixed_points f)) (y : ↥(function.fixed_points f)) : subtype.val x ⊔ subtype.val y ≤ f (subtype.val x ⊔ subtype.val y) := sorry theorem f_le_inf_of_fixed_points {α : Type u} [complete_lattice α] (f : α → α) (hf : monotone f) (x : ↥(function.fixed_points f)) (y : ↥(function.fixed_points f)) : f (subtype.val x ⊓ subtype.val y) ≤ subtype.val x ⊓ subtype.val y := sorry theorem Sup_le_f_of_fixed_points {α : Type u} [complete_lattice α] (f : α → α) (hf : monotone f) (A : set α) (HA : A ⊆ function.fixed_points f) : Sup A ≤ f (Sup A) := Sup_le fun (x : α) (hxA : x ∈ A) => HA hxA ▸ hf (le_Sup hxA) theorem f_le_Inf_of_fixed_points {α : Type u} [complete_lattice α] (f : α → α) (hf : monotone f) (A : set α) (HA : A ⊆ function.fixed_points f) : f (Inf A) ≤ Inf A := le_Inf fun (x : α) (hxA : x ∈ A) => HA hxA ▸ hf (Inf_le hxA) /-- The fixed points of `f` form a complete lattice. This cannot be an instance, since it depends on the monotonicity of `f`. -/ protected def complete_lattice {α : Type u} [complete_lattice α] (f : α → α) (hf : monotone f) : complete_lattice ↥(function.fixed_points f) := complete_lattice.mk (fun (x y : ↥(function.fixed_points f)) => next_fixed hf (subtype.val x ⊔ subtype.val y) (sup_le_f_of_fixed_points f hf x y)) (fun (x y : ↥(function.fixed_points f)) => subtype.val x ≤ subtype.val y) (bounded_lattice.lt._default fun (x y : ↥(function.fixed_points f)) => subtype.val x ≤ subtype.val y) sorry sorry sorry sorry sorry sorry (fun (x y : ↥(function.fixed_points f)) => prev_fixed hf (subtype.val x ⊓ subtype.val y) (f_le_inf_of_fixed_points f hf x y)) sorry sorry sorry (prev_fixed hf ⊤ sorry) sorry (next_fixed hf ⊥ sorry) sorry (fun (A : set ↥(function.fixed_points f)) => next_fixed hf (Sup (subtype.val '' A)) sorry) (fun (A : set ↥(function.fixed_points f)) => prev_fixed hf (Inf (subtype.val '' A)) sorry) sorry sorry sorry sorry end Mathlib
bf8dbdde00428b261235d9e8464744aac5a77115
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/tests/lean/run/362.lean
c84fa8bfccaedb5f2942cdc8edf6fa78c4a915ec
[ "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
202
lean
variables {a : Type} definition foo (A : Type) : A → A := begin intro a, assumption end (* local d = get_env():find("foo") assert(#d:univ_params() == 1) *) set_option pp.universes true check foo
23c79c413cae72aa4616ad379c7579b46833cc3f
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/archive/wiedijk_100_theorems/area_of_a_circle.lean
e22a6274e698f1bb2ffadfe06eb5e434e86618d8
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
6,704
lean
/- Copyright (c) 2021 James Arthur, Benjamin Davidson, Andrew Souther. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: James Arthur, Benjamin Davidson, Andrew Souther -/ import analysis.special_functions.sqrt import analysis.special_functions.trigonometric.inverse_deriv import measure_theory.integral.fund_thm_calculus import measure_theory.measure.lebesgue.integral /-! # Freek № 9: The Area of a Circle > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we show that the area of a disc with nonnegative radius `r` is `π * r^2`. The main tools our proof uses are `volume_region_between_eq_integral`, which allows us to represent the area of the disc as an integral, and `interval_integral.integral_eq_sub_of_has_deriv_at'_of_le`, the second fundamental theorem of calculus. We begin by defining `disc` in `ℝ × ℝ`, then show that `disc` can be represented as the `region_between` two functions. Though not necessary for the main proof, we nonetheless choose to include a proof of the measurability of the disc in order to convince the reader that the set whose volume we will be calculating is indeed measurable and our result is therefore meaningful. In the main proof, `area_disc`, we use `volume_region_between_eq_integral` followed by `interval_integral.integral_of_le` to reduce our goal to a single `interval_integral`: `∫ (x : ℝ) in -r..r, 2 * sqrt (r ^ 2 - x ^ 2) = π * r ^ 2`. After disposing of the trivial case `r = 0`, we show that `λ x, 2 * sqrt (r ^ 2 - x ^ 2)` is equal to the derivative of `λ x, r ^ 2 * arcsin (x / r) + x * sqrt (r ^ 2 - x ^ 2)` everywhere on `Ioo (-r) r` and that those two functions are continuous, then apply the second fundamental theorem of calculus with those facts. Some simple algebra then completes the proof. Note that we choose to define `disc` as a set of points in `ℝ × ℝ`. This is admittedly not ideal; it would be more natural to define `disc` as a `metric.ball` in `euclidean_space ℝ (fin 2)` (as well as to provide a more general proof in higher dimensions). However, our proof indirectly relies on a number of theorems (particularly `measure_theory.measure.prod_apply`) which do not yet exist for Euclidean space, thus forcing us to use this less-preferable definition. As `measure_theory.pi` continues to develop, it should eventually become possible to redefine `disc` and extend our proof to the n-ball. -/ open set real measure_theory interval_integral open_locale real nnreal namespace theorems_100 /-- A disc of radius `r` is defined as the collection of points `(p.1, p.2)` in `ℝ × ℝ` such that `p.1 ^ 2 + p.2 ^ 2 < r ^ 2`. Note that this definition is not equivalent to `metric.ball (0 : ℝ × ℝ) r`. This was done intentionally because `dist` in `ℝ × ℝ` is defined as the uniform norm, making the `metric.ball` in `ℝ × ℝ` a square, not a disc. See the module docstring for an explanation of why we don't define the disc in Euclidean space. -/ def disc (r : ℝ) := {p : ℝ × ℝ | p.1 ^ 2 + p.2 ^ 2 < r ^ 2} variable (r : ℝ≥0) /-- A disc of radius `r` can be represented as the region between the two curves `λ x, - sqrt (r ^ 2 - x ^ 2)` and `λ x, sqrt (r ^ 2 - x ^ 2)`. -/ lemma disc_eq_region_between : disc r = region_between (λ x, -sqrt (r^2 - x^2)) (λ x, sqrt (r^2 - x^2)) (Ioc (-r) r) := begin ext p, simp only [disc, region_between, mem_set_of_eq, mem_Ioo, mem_Ioc, pi.neg_apply], split; intro h, { cases abs_lt_of_sq_lt_sq' (lt_of_add_lt_of_nonneg_left h (sq_nonneg p.2)) r.2, rw [add_comm, ← lt_sub_iff_add_lt] at h, exact ⟨⟨left, right.le⟩, sq_lt.mp h⟩ }, { rw [add_comm, ← lt_sub_iff_add_lt], exact sq_lt.mpr h.2 }, end /-- The disc is a `measurable_set`. -/ theorem measurable_set_disc : measurable_set (disc r) := by apply measurable_set_lt; apply continuous.measurable; continuity /-- **Area of a Circle**: The area of a disc with radius `r` is `π * r ^ 2`. -/ theorem area_disc : volume (disc r) = nnreal.pi * r ^ 2 := begin let f := λ x, sqrt (r ^ 2 - x ^ 2), let F := λ x, (r:ℝ) ^ 2 * arcsin (r⁻¹ * x) + x * sqrt (r ^ 2 - x ^ 2), have hf : continuous f := by continuity, suffices : ∫ x in -r..r, 2 * f x = nnreal.pi * r ^ 2, { have h : integrable_on f (Ioc (-r) r) := hf.integrable_on_Icc.mono_set Ioc_subset_Icc_self, calc volume (disc r) = volume (region_between (λ x, -f x) f (Ioc (-r) r)) : by rw disc_eq_region_between ... = ennreal.of_real (∫ x in Ioc (-r:ℝ) r, (f - has_neg.neg ∘ f) x) : volume_region_between_eq_integral h.neg h measurable_set_Ioc (λ x hx, neg_le_self (sqrt_nonneg _)) ... = ennreal.of_real (∫ x in (-r:ℝ)..r, 2 * f x) : by simp [two_mul, integral_of_le] ... = nnreal.pi * r ^ 2 : by rw_mod_cast [this, ← ennreal.coe_nnreal_eq], }, obtain ⟨hle, (heq | hlt)⟩ := ⟨nnreal.coe_nonneg r, hle.eq_or_lt⟩, { simp [← heq] }, have hderiv : ∀ x ∈ Ioo (-r:ℝ) r, has_deriv_at F (2 * f x) x, { rintros x ⟨hx1, hx2⟩, convert ((has_deriv_at_const x ((r:ℝ)^2)).mul ((has_deriv_at_arcsin _ _).comp x ((has_deriv_at_const x (r:ℝ)⁻¹).mul (has_deriv_at_id' x)))).add ((has_deriv_at_id' x).mul ((((has_deriv_at_id' x).pow 2).const_sub ((r:ℝ)^2)).sqrt _)), { have h : sqrt (1 - x ^ 2 / r ^ 2) * r = sqrt (r ^ 2 - x ^ 2), { rw [← sqrt_sq hle, ← sqrt_mul, sub_mul, sqrt_sq hle, mul_comm_div, div_self (pow_ne_zero 2 hlt.ne'), one_mul, mul_one], simpa [sqrt_sq hle, div_le_one (pow_pos hlt 2)] using sq_le_sq' hx1.le hx2.le }, field_simp, rw [h, mul_left_comm, ← sq, neg_mul_eq_mul_neg, mul_div_mul_left (-x^2) _ two_ne_zero, add_left_comm, div_add_div_same, tactic.ring.add_neg_eq_sub, div_sqrt, two_mul] }, { suffices : -(1:ℝ) < r⁻¹ * x, by exact this.ne', calc -(1:ℝ) = r⁻¹ * -r : by simp [hlt.ne'] ... < r⁻¹ * x : by nlinarith [inv_pos.mpr hlt] }, { suffices : (r:ℝ)⁻¹ * x < 1, by exact this.ne, calc (r:ℝ)⁻¹ * x < r⁻¹ * r : by nlinarith [inv_pos.mpr hlt] ... = 1 : inv_mul_cancel hlt.ne' }, { nlinarith } }, have hcont := (by continuity : continuous F).continuous_on, calc ∫ x in -r..r, 2 * f x = F r - F (-r) : integral_eq_sub_of_has_deriv_at_of_le (neg_le_self r.2) hcont hderiv (continuous_const.mul hf).continuous_on.interval_integrable ... = nnreal.pi * r ^ 2 : by norm_num [F, inv_mul_cancel hlt.ne', ← mul_div_assoc, mul_comm π], end end theorems_100
bb32fb8d81181c7573c6d32ab3dffdfa8746dd23
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/group_theory/index.lean
aa4c84281ab89ab03194bfec02e614bffd64e08c
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,858
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 group_theory.quotient_group import set_theory.fincard /-! # Index of a Subgroup In this file we define the index of a subgroup, and prove several divisibility properties. ## Main definitions - `H.index` : the index of `H : subgroup G` as a natural number, and returns 0 if the index is infinite. - `H.relindex K` : the relative index of `H : subgroup G` in `K : subgroup G` as a natural number, and returns 0 if the relative index is infinite. # Main results - `index_mul_card` : `H.index * fintype.card H = fintype.card G` - `index_dvd_card` : `H.index ∣ fintype.card G` - `index_eq_mul_of_le` : If `H ≤ K`, then `H.index = K.index * (H.subgroup_of K).index` - `index_dvd_of_le` : If `H ≤ K`, then `K.index ∣ H.index` - `relindex_mul_relindex` : `relindex` is multiplicative in towers -/ namespace subgroup open_locale cardinal variables {G : Type*} [group G] (H K L : subgroup G) /-- The index of a subgroup as a natural number, and returns 0 if the index is infinite. -/ @[to_additive "The index of a subgroup as a natural number, and returns 0 if the index is infinite."] noncomputable def index : ℕ := nat.card (quotient_group.quotient H) /-- The relative index of a subgroup as a natural number, and returns 0 if the relative index is infinite. -/ @[to_additive "The relative index of a subgroup as a natural number, and returns 0 if the relative index is infinite."] noncomputable def relindex : ℕ := (H.subgroup_of K).index @[to_additive] lemma index_comap_of_surjective {G' : Type*} [group G'] {f : G' →* G} (hf : function.surjective f) : (H.comap f).index = H.index := begin letI := quotient_group.left_rel H, letI := quotient_group.left_rel (H.comap f), have key : ∀ x y : G', setoid.r x y ↔ setoid.r (f x) (f y) := λ x y, iff_of_eq (congr_arg (∈ H) (by rw [f.map_mul, f.map_inv])), refine cardinal.to_nat_congr (equiv.of_bijective (quotient.map' f (λ x y, (key x y).mp)) ⟨_, _⟩), { simp_rw [←quotient.eq'] at key, refine quotient.ind' (λ x, _), refine quotient.ind' (λ y, _), exact (key x y).mpr }, { refine quotient.ind' (λ x, _), obtain ⟨y, hy⟩ := hf x, exact ⟨y, (quotient.map'_mk' f _ y).trans (congr_arg quotient.mk' hy)⟩ }, end @[to_additive] lemma index_comap {G' : Type*} [group G'] (f : G' →* G) : (H.comap f).index = H.relindex f.range := eq.trans (congr_arg index (by refl)) ((H.subgroup_of f.range).index_comap_of_surjective f.range_restrict_surjective) variables {H K L} @[to_additive] lemma relindex_mul_index (h : H ≤ K) : H.relindex K * K.index = H.index := ((mul_comm _ _).trans (cardinal.to_nat_mul _ _).symm).trans (congr_arg cardinal.to_nat (equiv.cardinal_eq (quotient_equiv_prod_of_le h))).symm @[to_additive] lemma index_dvd_of_le (h : H ≤ K) : K.index ∣ H.index := dvd_of_mul_left_eq (H.relindex K) (relindex_mul_index h) @[to_additive] lemma relindex_subgroup_of (hKL : K ≤ L) : (H.subgroup_of L).relindex (K.subgroup_of L) = H.relindex K := ((index_comap (H.subgroup_of L) (inclusion hKL)).trans (congr_arg _ (inclusion_range hKL))).symm @[to_additive] lemma relindex_mul_relindex (hHK : H ≤ K) (hKL : K ≤ L) : H.relindex K * K.relindex L = H.relindex L := begin rw [←relindex_subgroup_of hKL], exact relindex_mul_index (λ x hx, hHK hx), end variables (H K L) lemma inf_relindex_right : (H ⊓ K).relindex K = H.relindex K := begin rw [←subgroup_of_map_subtype, relindex, relindex, subgroup_of, comap_map_eq_self_of_injective], exact subtype.coe_injective, end lemma inf_relindex_left : (H ⊓ K).relindex H = K.relindex H := by rw [inf_comm, inf_relindex_right] lemma inf_relindex_eq_relindex_sup [K.normal] : (H ⊓ K).relindex H = K.relindex (H ⊔ K) := cardinal.to_nat_congr (quotient_group.quotient_inf_equiv_prod_normal_quotient H K).to_equiv lemma relindex_eq_relindex_sup [K.normal] : K.relindex H = K.relindex (H ⊔ K) := by rw [←inf_relindex_left, inf_relindex_eq_relindex_sup] variables {H K} lemma relindex_dvd_of_le_left (hHK : H ≤ K) : K.relindex L ∣ H.relindex L := begin apply dvd_of_mul_left_eq ((H ⊓ L).relindex (K ⊓ L)), rw [←inf_relindex_right H L, ←inf_relindex_right K L], exact relindex_mul_relindex (inf_le_inf_right L hHK) inf_le_right, end variables (H K) @[simp, to_additive] lemma index_top : (⊤ : subgroup G).index = 1 := cardinal.to_nat_eq_one_iff_unique.mpr ⟨quotient_group.subsingleton_quotient_top, ⟨1⟩⟩ @[simp, to_additive] lemma index_bot : (⊥ : subgroup G).index = nat.card G := cardinal.to_nat_congr (quotient_group.quotient_bot.to_equiv) @[to_additive] lemma index_bot_eq_card [fintype G] : (⊥ : subgroup G).index = fintype.card G := index_bot.trans nat.card_eq_fintype_card @[simp, to_additive] lemma relindex_top_left : (⊤ : subgroup G).relindex H = 1 := index_top @[simp, to_additive] lemma relindex_top_right : H.relindex ⊤ = H.index := by rw [←relindex_mul_index (show H ≤ ⊤, from le_top), index_top, mul_one] @[simp, to_additive] lemma relindex_bot_left : (⊥ : subgroup G).relindex H = nat.card H := by rw [relindex, bot_subgroup_of, index_bot] @[to_additive] lemma relindex_bot_left_eq_card [fintype H] : (⊥ : subgroup G).relindex H = fintype.card H := H.relindex_bot_left.trans nat.card_eq_fintype_card @[simp, to_additive] lemma relindex_bot_right : H.relindex ⊥ = 1 := by rw [relindex, subgroup_of_bot_eq_top, index_top] @[simp, to_additive] lemma relindex_self : H.relindex H = 1 := by rw [relindex, subgroup_of_self, index_top] @[simp, to_additive card_mul_index] lemma card_mul_index : nat.card H * H.index = nat.card G := by { rw [←relindex_bot_left, ←index_bot], exact relindex_mul_index bot_le } @[to_additive] lemma index_map {G' : Type*} [group G'] (f : G →* G') : (H.map f).index = (H ⊔ f.ker).index * f.range.index := by rw [←comap_map_eq, index_comap, relindex_mul_index (H.map_le_range f)] @[to_additive] lemma index_map_dvd {G' : Type*} [group G'] {f : G →* G'} (hf : function.surjective f) : (H.map f).index ∣ H.index := begin rw [index_map, f.range_top_of_surjective hf, index_top, mul_one], exact index_dvd_of_le le_sup_left, end @[to_additive] lemma dvd_index_map {G' : Type*} [group G'] {f : G →* G'} (hf : f.ker ≤ H) : H.index ∣ (H.map f).index := begin rw [index_map, sup_of_le_left hf], apply dvd_mul_right, end @[to_additive] lemma index_map_eq {G' : Type*} [group G'] {f : G →* G'} (hf1 : function.surjective f) (hf2 : f.ker ≤ H) : (H.map f).index = H.index := nat.dvd_antisymm (H.index_map_dvd hf1) (H.dvd_index_map hf2) @[to_additive] lemma index_eq_card [fintype (quotient_group.quotient H)] : H.index = fintype.card (quotient_group.quotient H) := nat.card_eq_fintype_card @[to_additive] lemma index_mul_card [fintype G] [hH : fintype H] : H.index * fintype.card H = fintype.card G := by rw [←relindex_bot_left_eq_card, ←index_bot_eq_card, mul_comm]; exact relindex_mul_index bot_le @[to_additive] lemma index_dvd_card [fintype G] : H.index ∣ fintype.card G := begin classical, exact ⟨fintype.card H, H.index_mul_card.symm⟩, end variables {H} @[simp] lemma index_eq_one : H.index = 1 ↔ H = ⊤ := ⟨λ h, quotient_group.subgroup_eq_top_of_subsingleton H (cardinal.to_nat_eq_one_iff_unique.mp h).1, λ h, (congr_arg index h).trans index_top⟩ lemma index_ne_zero_of_fintype [hH : fintype (quotient_group.quotient H)] : H.index ≠ 0 := by { rw index_eq_card, exact fintype.card_ne_zero } lemma one_lt_index_of_ne_top [fintype (quotient_group.quotient H)] (hH : H ≠ ⊤) : 1 < H.index := nat.one_lt_iff_ne_zero_and_ne_one.mpr ⟨index_ne_zero_of_fintype, mt index_eq_one.mp hH⟩ end subgroup
b6c6553a66447f0034818036fb5d461f56faefd0
5aaed23ab7202c675981a8ecc309d1f3ea53fa63
/src/2012_q4.lean
c9c6978da95f364498af8bfae720df6664b7de22
[]
no_license
jalex-stark/mathcamp-QQuiz-lean
d1cedba0ae1ff078022c6b9f6e5090b97ee4cc27
fd17c0cfe6c7a0b2f283cf33bed1403279c8e04a
refs/heads/master
1,668,476,432,896
1,594,602,972,000
1,594,602,972,000
279,175,371
0
0
null
null
null
null
UTF-8
Lean
false
false
880
lean
import tactic import data.real.basic noncomputable theory open_locale classical open real -- Let a be a rational number with 0 < a < 1. -- A lollipop in the xy-plane with base (a,0) consists of ---- a line segment from (a,0) to some point (a,b) with b > 0, ---- together with a filled in disc of radius less than b, centered at (a,b). def lollipop (a b r : ℝ) (hb : 0 < b) (hr : r < b) : set (ℝ × ℝ) := {p : ℝ × ℝ | dist p ⟨a, b⟩ ≤ r} ∪ {p : ℝ × ℝ | p.1 = a ∧ p.2 ∈ Icc 0 b} -- Determine whether or not it is possible to have a set of lollipops in the xy-plane satisfying both of the following conditions: -- for every rational number a with 0 < a < 1, there is a lollipop whose base is the point (a,0), -- no two lollipops touch or overlap each other. -- If such a set of lollipops exists, explain how to construct it. If not, justify why not.
26063dee3d1fa3f1c5f3b3aa9d1d7e620c129cb5
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/analysis/calculus/fderiv.lean
5080bb4af69738c6ef4836c00f19c80b0224cf50
[ "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
102,654
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Sébastien Gouëzel, Yury Kudryashov -/ import analysis.calculus.tangent_cone /-! # The Fréchet derivative Let `E` and `F` be normed spaces, `f : E → F`, and `f' : E →L[𝕜] F` a continuous 𝕜-linear map, where `𝕜` is a non-discrete normed field. Then `has_fderiv_within_at f f' s x` says that `f` has derivative `f'` at `x`, where the domain of interest is restricted to `s`. We also have `has_fderiv_at f f' x := has_fderiv_within_at f f' x univ` Finally, `has_strict_fderiv_at f f' x` means that `f : E → F` has derivative `f' : E →L[𝕜] F` in the sense of strict differentiability, i.e., `f y - f z - f'(y - z) = o(y - z)` as `y, z → x`. This notion is used in the inverse function theorem, and is defined here only to avoid proving theorems like `is_bounded_bilinear_map.has_fderiv_at` twice: first for `has_fderiv_at`, then for `has_strict_fderiv_at`. ## Main results In addition to the definition and basic properties of the derivative, this file contains the usual formulas (and existence assertions) for the derivative of * constants * the identity * bounded linear maps * bounded bilinear maps * sum of two functions * sum of finitely many functions * multiplication of a function by a scalar constant * negative of a function * subtraction of two functions * multiplication of a function by a scalar function * multiplication of two scalar functions * composition of functions (the chain rule) * inverse function (assuming that it exists; the inverse function theorem is in `inverse.lean`) For most binary operations we also define `const_op` and `op_const` theorems for the cases when the first or second argument is a constant. This makes writing chains of `has_deriv_at`'s easier, and they more frequently lead to the desired result. One can also interpret the derivative of a function `f : 𝕜 → E` as an element of `E` (by identifying a linear function from `𝕜` to `E` with its value at `1`). Results on the Fréchet derivative are translated to this more elementary point of view on the derivative in the file `deriv.lean`. The derivative of polynomials is handled there, as it is naturally one-dimensional. The simplifier is set up to prove automatically that some functions are differentiable, or differentiable at a point (but not differentiable on a set or within a set at a point, as checking automatically that the good domains are mapped one to the other when using composition is not something the simplifier can easily do). This means that one can write `example (x : ℝ) : differentiable ℝ (λ x, sin (exp (3 + x^2)) - 5 * cos x) := by simp`. If there are divisions, one needs to supply to the simplifier proofs that the denominators do not vanish, as in ```lean example (x : ℝ) (h : 1 + sin x ≠ 0) : differentiable_at ℝ (λ x, exp x / (1 + sin x)) x := by simp [h] ``` Of course, these examples only work once `exp`, `cos` and `sin` have been shown to be differentiable, in `analysis.special_functions.trigonometric`. The simplifier is not set up to compute the Fréchet derivative of maps (as these are in general complicated multidimensional linear maps), but it will compute one-dimensional derivatives, see `deriv.lean`. ## Implementation details The derivative is defined in terms of the `is_o` relation, but also characterized in terms of the `tendsto` relation. We also introduce predicates `differentiable_within_at 𝕜 f s x` (where `𝕜` is the base field, `f` the function to be differentiated, `x` the point at which the derivative is asserted to exist, and `s` the set along which the derivative is defined), as well as `differentiable_at 𝕜 f x`, `differentiable_on 𝕜 f s` and `differentiable 𝕜 f` to express the existence of a derivative. To be able to compute with derivatives, we write `fderiv_within 𝕜 f s x` and `fderiv 𝕜 f x` for some choice of a derivative if it exists, and the zero function otherwise. This choice only behaves well along sets for which the derivative is unique, i.e., those for which the tangent directions span a dense subset of the whole space. The predicates `unique_diff_within_at s x` and `unique_diff_on s`, defined in `tangent_cone.lean` express this property. We prove that indeed they imply the uniqueness of the derivative. This is satisfied for open subsets, and in particular for `univ`. This uniqueness only holds when the field is non-discrete, which we request at the very beginning: otherwise, a derivative can be defined, but it has no interesting properties whatsoever. To make sure that the simplifier can prove automatically that functions are differentiable, we tag many lemmas with the `simp` attribute, for instance those saying that the sum of differentiable functions is differentiable, as well as their product, their cartesian product, and so on. A notable exception is the chain rule: we do not mark as a simp lemma the fact that, if `f` and `g` are differentiable, then their composition also is: `simp` would always be able to match this lemma, by taking `f` or `g` to be the identity. Instead, for every reasonable function (say, `exp`), we add a lemma that if `f` is differentiable then so is `(λ x, exp (f x))`. This means adding some boilerplate lemmas, but these can also be useful in their own right. Tests for this ability of the simplifier (with more examples) are provided in `tests/differentiable.lean`. ## Tags derivative, differentiable, Fréchet, calculus -/ open filter asymptotics continuous_linear_map set open_locale topological_space classical noncomputable theory section variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] variables {G : Type*} [normed_group G] [normed_space 𝕜 G] variables {G' : Type*} [normed_group G'] [normed_space 𝕜 G'] /-- A function `f` has the continuous linear map `f'` as derivative along the filter `L` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` converges along the filter `L`. This definition is designed to be specialized for `L = 𝓝 x` (in `has_fderiv_at`), giving rise to the usual notion of Fréchet derivative, and for `L = nhds_within x s` (in `has_fderiv_within_at`), giving rise to the notion of Fréchet derivative along the set `s`. -/ def has_fderiv_at_filter (f : E → F) (f' : E →L[𝕜] F) (x : E) (L : filter E) := is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L /-- A function `f` has the continuous linear map `f'` as derivative at `x` within a set `s` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` tends to `x` inside `s`. -/ def has_fderiv_within_at (f : E → F) (f' : E →L[𝕜] F) (s : set E) (x : E) := has_fderiv_at_filter f f' x (nhds_within x s) /-- A function `f` has the continuous linear map `f'` as derivative at `x` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` tends to `x`. -/ def has_fderiv_at (f : E → F) (f' : E →L[𝕜] F) (x : E) := has_fderiv_at_filter f f' x (𝓝 x) /-- A function `f` has derivative `f'` at `a` in the sense of *strict differentiability* if `f x - f y - f' (x - y) = o(x - y)` as `x, y → a`. This form of differentiability is required, e.g., by the inverse function theorem. Any `C^1` function on a vector space over `ℝ` is strictly differentiable but this definition works, e.g., for vector spaces over `p`-adic numbers. -/ def has_strict_fderiv_at (f : E → F) (f' : E →L[𝕜] F) (x : E) := is_o (λ p : E × E, f p.1 - f p.2 - f' (p.1 - p.2)) (λ p : E × E, p.1 - p.2) (𝓝 (x, x)) variables (𝕜) /-- A function `f` is differentiable at a point `x` within a set `s` if it admits a derivative there (possibly non-unique). -/ def differentiable_within_at (f : E → F) (s : set E) (x : E) := ∃f' : E →L[𝕜] F, has_fderiv_within_at f f' s x /-- A function `f` is differentiable at a point `x` if it admits a derivative there (possibly non-unique). -/ def differentiable_at (f : E → F) (x : E) := ∃f' : E →L[𝕜] F, has_fderiv_at f f' x /-- If `f` has a derivative at `x` within `s`, then `fderiv_within 𝕜 f s x` is such a derivative. Otherwise, it is set to `0`. -/ def fderiv_within (f : E → F) (s : set E) (x : E) : E →L[𝕜] F := if h : ∃f', has_fderiv_within_at f f' s x then classical.some h else 0 /-- If `f` has a derivative at `x`, then `fderiv 𝕜 f x` is such a derivative. Otherwise, it is set to `0`. -/ def fderiv (f : E → F) (x : E) : E →L[𝕜] F := if h : ∃f', has_fderiv_at f f' x then classical.some h else 0 /-- `differentiable_on 𝕜 f s` means that `f` is differentiable within `s` at any point of `s`. -/ def differentiable_on (f : E → F) (s : set E) := ∀x ∈ s, differentiable_within_at 𝕜 f s x /-- `differentiable 𝕜 f` means that `f` is differentiable at any point. -/ def differentiable (f : E → F) := ∀x, differentiable_at 𝕜 f x variables {𝕜} variables {f f₀ f₁ g : E → F} variables {f' f₀' f₁' g' : E →L[𝕜] F} variables (e : E →L[𝕜] F) variables {x : E} variables {s t : set E} variables {L L₁ L₂ : filter E} lemma fderiv_within_zero_of_not_differentiable_within_at (h : ¬ differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 f s x = 0 := have ¬ ∃ f', has_fderiv_within_at f f' s x, from h, by simp [fderiv_within, this] lemma fderiv_zero_of_not_differentiable_at (h : ¬ differentiable_at 𝕜 f x) : fderiv 𝕜 f x = 0 := have ¬ ∃ f', has_fderiv_at f f' x, from h, by simp [fderiv, this] section derivative_uniqueness /- In this section, we discuss the uniqueness of the derivative. We prove that the definitions `unique_diff_within_at` and `unique_diff_on` indeed imply the uniqueness of the derivative. -/ /-- If a function f has a derivative f' at x, a rescaled version of f around x converges to f', i.e., `n (f (x + (1/n) v) - f x)` converges to `f' v`. More generally, if `c n` tends to infinity and `c n * d n` tends to `v`, then `c n * (f (x + d n) - f x)` tends to `f' v`. This lemma expresses this fact, for functions having a derivative within a set. Its specific formulation is useful for tangent cone related discussions. -/ theorem has_fderiv_within_at.lim (h : has_fderiv_within_at f f' s x) {α : Type*} (l : filter α) {c : α → 𝕜} {d : α → E} {v : E} (dtop : ∀ᶠ n in l, x + d n ∈ s) (clim : tendsto (λ n, ∥c n∥) l at_top) (cdlim : tendsto (λ n, c n • d n) l (𝓝 v)) : tendsto (λn, c n • (f (x + d n) - f x)) l (𝓝 (f' v)) := begin have tendsto_arg : tendsto (λ n, x + d n) l (nhds_within x s), { conv in (nhds_within x s) { rw ← add_zero x }, rw [nhds_within, tendsto_inf], split, { apply tendsto_const_nhds.add (tangent_cone_at.lim_zero l clim cdlim) }, { rwa tendsto_principal } }, have : is_o (λ y, f y - f x - f' (y - x)) (λ y, y - x) (nhds_within x s) := h, have : is_o (λ n, f (x + d n) - f x - f' ((x + d n) - x)) (λ n, (x + d n) - x) l := this.comp_tendsto tendsto_arg, have : is_o (λ n, f (x + d n) - f x - f' (d n)) d l := by simpa only [add_sub_cancel'], have : is_o (λn, c n • (f (x + d n) - f x - f' (d n))) (λn, c n • d n) l := (is_O_refl c l).smul_is_o this, have : is_o (λn, c n • (f (x + d n) - f x - f' (d n))) (λn, (1:ℝ)) l := this.trans_is_O (is_O_one_of_tendsto ℝ cdlim), have L1 : tendsto (λn, c n • (f (x + d n) - f x - f' (d n))) l (𝓝 0) := (is_o_one_iff ℝ).1 this, have L2 : tendsto (λn, f' (c n • d n)) l (𝓝 (f' v)) := tendsto.comp f'.cont.continuous_at cdlim, have L3 : tendsto (λn, (c n • (f (x + d n) - f x - f' (d n)) + f' (c n • d n))) l (𝓝 (0 + f' v)) := L1.add L2, have : (λn, (c n • (f (x + d n) - f x - f' (d n)) + f' (c n • d n))) = (λn, c n • (f (x + d n) - f x)), by { ext n, simp [smul_add, smul_sub] }, rwa [this, zero_add] at L3 end /-- `unique_diff_within_at` achieves its goal: it implies the uniqueness of the derivative. -/ theorem unique_diff_within_at.eq (H : unique_diff_within_at 𝕜 s x) (h : has_fderiv_within_at f f' s x) (h₁ : has_fderiv_within_at f f₁' s x) : f' = f₁' := begin have A : ∀y ∈ tangent_cone_at 𝕜 s x, f' y = f₁' y, { rintros y ⟨c, d, dtop, clim, cdlim⟩, exact tendsto_nhds_unique (by simp) (h.lim at_top dtop clim cdlim) (h₁.lim at_top dtop clim cdlim) }, have B : ∀y ∈ submodule.span 𝕜 (tangent_cone_at 𝕜 s x), f' y = f₁' y, { assume y hy, apply submodule.span_induction hy, { exact λy hy, A y hy }, { simp only [continuous_linear_map.map_zero] }, { simp {contextual := tt} }, { simp {contextual := tt} } }, have C : ∀y ∈ closure ((submodule.span 𝕜 (tangent_cone_at 𝕜 s x)) : set E), f' y = f₁' y, { assume y hy, let K := {y | f' y = f₁' y}, have : (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E) ⊆ K := B, have : closure (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E) ⊆ closure K := closure_mono this, have : y ∈ closure K := this hy, rwa (is_closed_eq f'.continuous f₁'.continuous).closure_eq at this }, rw H.1 at C, ext y, exact C y (mem_univ _) end theorem unique_diff_on.eq (H : unique_diff_on 𝕜 s) (hx : x ∈ s) (h : has_fderiv_within_at f f' s x) (h₁ : has_fderiv_within_at f f₁' s x) : f' = f₁' := unique_diff_within_at.eq (H x hx) h h₁ end derivative_uniqueness section fderiv_properties /-! ### Basic properties of the derivative -/ theorem has_fderiv_at_filter_iff_tendsto : has_fderiv_at_filter f f' x L ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (𝓝 0) := have h : ∀ x', ∥x' - x∥ = 0 → ∥f x' - f x - f' (x' - x)∥ = 0, from λ x' hx', by { rw [sub_eq_zero.1 (norm_eq_zero.1 hx')], simp }, begin unfold has_fderiv_at_filter, rw [←is_o_norm_left, ←is_o_norm_right, is_o_iff_tendsto h], exact tendsto_congr (λ _, div_eq_inv_mul), end theorem has_fderiv_within_at_iff_tendsto : has_fderiv_within_at f f' s x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) (nhds_within x s) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_fderiv_at_iff_tendsto : has_fderiv_at f f' x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) (𝓝 x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_fderiv_at_iff_is_o_nhds_zero : has_fderiv_at f f' x ↔ is_o (λh, f (x + h) - f x - f' h) (λh, h) (𝓝 0) := begin split, { assume H, have : tendsto (λ (z : E), z + x) (𝓝 0) (𝓝 (0 + x)), from tendsto_id.add tendsto_const_nhds, rw [zero_add] at this, refine (H.comp_tendsto this).congr _ _; intro z; simp only [function.comp, add_sub_cancel', add_comm z] }, { assume H, have : tendsto (λ (z : E), z - x) (𝓝 x) (𝓝 (x - x)), from tendsto_id.sub tendsto_const_nhds, rw [sub_self] at this, refine (H.comp_tendsto this).congr _ _; intro z; simp only [function.comp, add_sub_cancel'_right] } end theorem has_fderiv_at_filter.mono (h : has_fderiv_at_filter f f' x L₂) (hst : L₁ ≤ L₂) : has_fderiv_at_filter f f' x L₁ := h.mono hst theorem has_fderiv_within_at.mono (h : has_fderiv_within_at f f' t x) (hst : s ⊆ t) : has_fderiv_within_at f f' s x := h.mono (nhds_within_mono _ hst) theorem has_fderiv_at.has_fderiv_at_filter (h : has_fderiv_at f f' x) (hL : L ≤ 𝓝 x) : has_fderiv_at_filter f f' x L := h.mono hL theorem has_fderiv_at.has_fderiv_within_at (h : has_fderiv_at f f' x) : has_fderiv_within_at f f' s x := h.has_fderiv_at_filter inf_le_left lemma has_fderiv_within_at.differentiable_within_at (h : has_fderiv_within_at f f' s x) : differentiable_within_at 𝕜 f s x := ⟨f', h⟩ lemma has_fderiv_at.differentiable_at (h : has_fderiv_at f f' x) : differentiable_at 𝕜 f x := ⟨f', h⟩ @[simp] lemma has_fderiv_within_at_univ : has_fderiv_within_at f f' univ x ↔ has_fderiv_at f f' x := by { simp only [has_fderiv_within_at, nhds_within_univ], refl } lemma has_strict_fderiv_at.is_O_sub (hf : has_strict_fderiv_at f f' x) : is_O (λ p : E × E, f p.1 - f p.2) (λ p : E × E, p.1 - p.2) (𝓝 (x, x)) := hf.is_O.congr_of_sub.2 (f'.is_O_comp _ _) lemma has_fderiv_at_filter.is_O_sub (h : has_fderiv_at_filter f f' x L) : is_O (λ x', f x' - f x) (λ x', x' - x) L := h.is_O.congr_of_sub.2 (f'.is_O_sub _ _) protected lemma has_strict_fderiv_at.has_fderiv_at (hf : has_strict_fderiv_at f f' x) : has_fderiv_at f f' x := begin rw [has_fderiv_at, has_fderiv_at_filter, is_o_iff], exact (λ c hc, tendsto_id.prod_mk_nhds tendsto_const_nhds (is_o_iff.1 hf hc)) end protected lemma has_strict_fderiv_at.differentiable_at (hf : has_strict_fderiv_at f f' x) : differentiable_at 𝕜 f x := hf.has_fderiv_at.differentiable_at /-- Directional derivative agrees with `has_fderiv`. -/ lemma has_fderiv_at.lim (hf : has_fderiv_at f f' x) (v : E) {α : Type*} {c : α → 𝕜} {l : filter α} (hc : tendsto (λ n, ∥c n∥) l at_top) : tendsto (λ n, (c n) • (f (x + (c n)⁻¹ • v) - f x)) l (𝓝 (f' v)) := begin refine (has_fderiv_within_at_univ.2 hf).lim _ (univ_mem_sets' (λ _, trivial)) hc _, assume U hU, refine (eventually_ne_of_tendsto_norm_at_top hc (0:𝕜)).mono (λ y hy, _), convert mem_of_nhds hU, dsimp only, rw [← mul_smul, mul_inv_cancel hy, one_smul] end theorem has_fderiv_at_unique (h₀ : has_fderiv_at f f₀' x) (h₁ : has_fderiv_at f f₁' x) : f₀' = f₁' := begin rw ← has_fderiv_within_at_univ at h₀ h₁, exact unique_diff_within_at_univ.eq h₀ h₁ end lemma has_fderiv_within_at_inter' (h : t ∈ nhds_within x s) : has_fderiv_within_at f f' (s ∩ t) x ↔ has_fderiv_within_at f f' s x := by simp [has_fderiv_within_at, nhds_within_restrict'' s h] lemma has_fderiv_within_at_inter (h : t ∈ 𝓝 x) : has_fderiv_within_at f f' (s ∩ t) x ↔ has_fderiv_within_at f f' s x := by simp [has_fderiv_within_at, nhds_within_restrict' s h] lemma has_fderiv_within_at.union (hs : has_fderiv_within_at f f' s x) (ht : has_fderiv_within_at f f' t x) : has_fderiv_within_at f f' (s ∪ t) x := begin simp only [has_fderiv_within_at, nhds_within_union], exact hs.join ht, end lemma has_fderiv_within_at.nhds_within (h : has_fderiv_within_at f f' s x) (ht : s ∈ nhds_within x t) : has_fderiv_within_at f f' t x := (has_fderiv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _)) lemma has_fderiv_within_at.has_fderiv_at (h : has_fderiv_within_at f f' s x) (hs : s ∈ 𝓝 x) : has_fderiv_at f f' x := by rwa [← univ_inter s, has_fderiv_within_at_inter hs, has_fderiv_within_at_univ] at h lemma differentiable_within_at.has_fderiv_within_at (h : differentiable_within_at 𝕜 f s x) : has_fderiv_within_at f (fderiv_within 𝕜 f s x) s x := begin dunfold fderiv_within, dunfold differentiable_within_at at h, rw dif_pos h, exact classical.some_spec h end lemma differentiable_at.has_fderiv_at (h : differentiable_at 𝕜 f x) : has_fderiv_at f (fderiv 𝕜 f x) x := begin dunfold fderiv, dunfold differentiable_at at h, rw dif_pos h, exact classical.some_spec h end lemma has_fderiv_at.fderiv (h : has_fderiv_at f f' x) : fderiv 𝕜 f x = f' := by { ext, rw has_fderiv_at_unique h h.differentiable_at.has_fderiv_at } lemma has_fderiv_within_at.fderiv_within (h : has_fderiv_within_at f f' s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = f' := (hxs.eq h h.differentiable_within_at.has_fderiv_within_at).symm /-- If `x` is not in the closure of `s`, then `f` has any derivative at `x` within `s`, as this statement is empty. -/ lemma has_fderiv_within_at_of_not_mem_closure (h : x ∉ closure s) : has_fderiv_within_at f f' s x := begin simp [mem_closure_iff_nhds_within_ne_bot] at h, simp [has_fderiv_within_at, has_fderiv_at_filter, h, is_o, is_O_with], end lemma differentiable_within_at.mono (h : differentiable_within_at 𝕜 f t x) (st : s ⊆ t) : differentiable_within_at 𝕜 f s x := begin rcases h with ⟨f', hf'⟩, exact ⟨f', hf'.mono st⟩ end lemma differentiable_within_at_univ : differentiable_within_at 𝕜 f univ x ↔ differentiable_at 𝕜 f x := by simp only [differentiable_within_at, has_fderiv_within_at_univ, differentiable_at] lemma differentiable_within_at_inter (ht : t ∈ 𝓝 x) : differentiable_within_at 𝕜 f (s ∩ t) x ↔ differentiable_within_at 𝕜 f s x := by simp only [differentiable_within_at, has_fderiv_within_at, has_fderiv_at_filter, nhds_within_restrict' s ht] lemma differentiable_within_at_inter' (ht : t ∈ nhds_within x s) : differentiable_within_at 𝕜 f (s ∩ t) x ↔ differentiable_within_at 𝕜 f s x := by simp only [differentiable_within_at, has_fderiv_within_at, has_fderiv_at_filter, nhds_within_restrict'' s ht] lemma differentiable_at.differentiable_within_at (h : differentiable_at 𝕜 f x) : differentiable_within_at 𝕜 f s x := (differentiable_within_at_univ.2 h).mono (subset_univ _) lemma differentiable.differentiable_at (h : differentiable 𝕜 f) : differentiable_at 𝕜 f x := h x lemma differentiable_within_at.differentiable_at (h : differentiable_within_at 𝕜 f s x) (hs : s ∈ 𝓝 x) : differentiable_at 𝕜 f x := h.imp (λ f' hf', hf'.has_fderiv_at hs) lemma differentiable_at.fderiv_within (h : differentiable_at 𝕜 f x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = fderiv 𝕜 f x := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact h.has_fderiv_at.has_fderiv_within_at end lemma differentiable_on.mono (h : differentiable_on 𝕜 f t) (st : s ⊆ t) : differentiable_on 𝕜 f s := λx hx, (h x (st hx)).mono st lemma differentiable_on_univ : differentiable_on 𝕜 f univ ↔ differentiable 𝕜 f := by { simp [differentiable_on, differentiable_within_at_univ], refl } lemma differentiable.differentiable_on (h : differentiable 𝕜 f) : differentiable_on 𝕜 f s := (differentiable_on_univ.2 h).mono (subset_univ _) lemma differentiable_on_of_locally_differentiable_on (h : ∀x∈s, ∃u, is_open u ∧ x ∈ u ∧ differentiable_on 𝕜 f (s ∩ u)) : differentiable_on 𝕜 f s := begin assume x xs, rcases h x xs with ⟨t, t_open, xt, ht⟩, exact (differentiable_within_at_inter (mem_nhds_sets t_open xt)).1 (ht x ⟨xs, xt⟩) end lemma fderiv_within_subset (st : s ⊆ t) (ht : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f t x) : fderiv_within 𝕜 f s x = fderiv_within 𝕜 f t x := ((differentiable_within_at.has_fderiv_within_at h).mono st).fderiv_within ht @[simp] lemma fderiv_within_univ : fderiv_within 𝕜 f univ = fderiv 𝕜 f := begin ext x : 1, by_cases h : differentiable_at 𝕜 f x, { apply has_fderiv_within_at.fderiv_within _ unique_diff_within_at_univ, rw has_fderiv_within_at_univ, apply h.has_fderiv_at }, { have : ¬ differentiable_within_at 𝕜 f univ x, by contrapose! h; rwa ← differentiable_within_at_univ, rw [fderiv_zero_of_not_differentiable_at h, fderiv_within_zero_of_not_differentiable_within_at this] } end lemma fderiv_within_inter (ht : t ∈ 𝓝 x) (hs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f (s ∩ t) x = fderiv_within 𝕜 f s x := begin by_cases h : differentiable_within_at 𝕜 f (s ∩ t) x, { apply fderiv_within_subset (inter_subset_left _ _) _ ((differentiable_within_at_inter ht).1 h), apply hs.inter ht }, { have : ¬ differentiable_within_at 𝕜 f s x, by contrapose! h; rw differentiable_within_at_inter; assumption, rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at this] } end end fderiv_properties section continuous /-! ### Deducing continuity from differentiability -/ theorem has_fderiv_at_filter.tendsto_nhds (hL : L ≤ 𝓝 x) (h : has_fderiv_at_filter f f' x L) : tendsto f L (𝓝 (f x)) := begin have : tendsto (λ x', f x' - f x) L (𝓝 0), { refine h.is_O_sub.trans_tendsto (tendsto_le_left hL _), rw ← sub_self x, exact tendsto_id.sub tendsto_const_nhds }, have := tendsto.add this tendsto_const_nhds, rw zero_add (f x) at this, exact this.congr (by simp) end theorem has_fderiv_within_at.continuous_within_at (h : has_fderiv_within_at f f' s x) : continuous_within_at f s x := has_fderiv_at_filter.tendsto_nhds inf_le_left h theorem has_fderiv_at.continuous_at (h : has_fderiv_at f f' x) : continuous_at f x := has_fderiv_at_filter.tendsto_nhds (le_refl _) h lemma differentiable_within_at.continuous_within_at (h : differentiable_within_at 𝕜 f s x) : continuous_within_at f s x := let ⟨f', hf'⟩ := h in hf'.continuous_within_at lemma differentiable_at.continuous_at (h : differentiable_at 𝕜 f x) : continuous_at f x := let ⟨f', hf'⟩ := h in hf'.continuous_at lemma differentiable_on.continuous_on (h : differentiable_on 𝕜 f s) : continuous_on f s := λx hx, (h x hx).continuous_within_at lemma differentiable.continuous (h : differentiable 𝕜 f) : continuous f := continuous_iff_continuous_at.2 $ λx, (h x).continuous_at protected lemma has_strict_fderiv_at.continuous_at (hf : has_strict_fderiv_at f f' x) : continuous_at f x := hf.has_fderiv_at.continuous_at lemma has_strict_fderiv_at.is_O_sub_rev {f' : E ≃L[𝕜] F} (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) x) : is_O (λ p : E × E, p.1 - p.2) (λ p : E × E, f p.1 - f p.2) (𝓝 (x, x)) := ((f'.is_O_comp_rev _ _).trans (hf.trans_is_O (f'.is_O_comp_rev _ _)).right_is_O_add).congr (λ _, rfl) (λ _, sub_add_cancel _ _) lemma has_fderiv_at_filter.is_O_sub_rev {f' : E ≃L[𝕜] F} (hf : has_fderiv_at_filter f (f' : E →L[𝕜] F) x L) : is_O (λ x', x' - x) (λ x', f x' - f x) L := ((f'.is_O_sub_rev _ _).trans (hf.trans_is_O (f'.is_O_sub_rev _ _)).right_is_O_add).congr (λ _, rfl) (λ _, sub_add_cancel _ _) end continuous section congr /-! ### congr properties of the derivative -/ theorem filter.eventually_eq.has_strict_fderiv_at_iff (h : f₀ =ᶠ[𝓝 x] f₁) (h' : ∀ y, f₀' y = f₁' y) : has_strict_fderiv_at f₀ f₀' x ↔ has_strict_fderiv_at f₁ f₁' x := begin refine is_o_congr ((h.prod_mk_nhds h).mono _) (eventually_of_forall $ λ _, rfl), rintros p ⟨hp₁, hp₂⟩, simp only [*] end theorem has_strict_fderiv_at.congr_of_eventually_eq (h : has_strict_fderiv_at f f' x) (h₁ : f =ᶠ[𝓝 x] f₁) : has_strict_fderiv_at f₁ f' x := (h₁.has_strict_fderiv_at_iff (λ _, rfl)).1 h theorem filter.eventually_eq.has_fderiv_at_filter_iff (h₀ : f₀ =ᶠ[L] f₁) (hx : f₀ x = f₁ x) (h₁ : ∀ x, f₀' x = f₁' x) : has_fderiv_at_filter f₀ f₀' x L ↔ has_fderiv_at_filter f₁ f₁' x L := is_o_congr (h₀.mono $ λ y hy, by simp only [hy, h₁, hx]) (eventually_of_forall $ λ _, rfl) lemma has_fderiv_at_filter.congr_of_eventually_eq (h : has_fderiv_at_filter f f' x L) (hL : f₁ =ᶠ[L] f) (hx : f₁ x = f x) : has_fderiv_at_filter f₁ f' x L := (hL.has_fderiv_at_filter_iff hx $ λ _, rfl).2 h lemma has_fderiv_within_at.congr_mono (h : has_fderiv_within_at f f' s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : has_fderiv_within_at f₁ f' t x := has_fderiv_at_filter.congr_of_eventually_eq (h.mono h₁) (filter.mem_inf_sets_of_right ht) hx lemma has_fderiv_within_at.congr (h : has_fderiv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : has_fderiv_within_at f₁ f' s x := h.congr_mono hs hx (subset.refl _) lemma has_fderiv_within_at.congr_of_eventually_eq (h : has_fderiv_within_at f f' s x) (h₁ : f₁ =ᶠ[nhds_within x s] f) (hx : f₁ x = f x) : has_fderiv_within_at f₁ f' s x := has_fderiv_at_filter.congr_of_eventually_eq h h₁ hx lemma has_fderiv_at.congr_of_eventually_eq (h : has_fderiv_at f f' x) (h₁ : f₁ =ᶠ[𝓝 x] f) : has_fderiv_at f₁ f' x := has_fderiv_at_filter.congr_of_eventually_eq h h₁ (mem_of_nhds h₁ : _) lemma differentiable_within_at.congr_mono (h : differentiable_within_at 𝕜 f s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : differentiable_within_at 𝕜 f₁ t x := (has_fderiv_within_at.congr_mono h.has_fderiv_within_at ht hx h₁).differentiable_within_at lemma differentiable_within_at.congr (h : differentiable_within_at 𝕜 f s x) (ht : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : differentiable_within_at 𝕜 f₁ s x := differentiable_within_at.congr_mono h ht hx (subset.refl _) lemma differentiable_within_at.congr_of_eventually_eq (h : differentiable_within_at 𝕜 f s x) (h₁ : f₁ =ᶠ[nhds_within x s] f) (hx : f₁ x = f x) : differentiable_within_at 𝕜 f₁ s x := (h.has_fderiv_within_at.congr_of_eventually_eq h₁ hx).differentiable_within_at lemma differentiable_on.congr_mono (h : differentiable_on 𝕜 f s) (h' : ∀x ∈ t, f₁ x = f x) (h₁ : t ⊆ s) : differentiable_on 𝕜 f₁ t := λ x hx, (h x (h₁ hx)).congr_mono h' (h' x hx) h₁ lemma differentiable_on.congr (h : differentiable_on 𝕜 f s) (h' : ∀x ∈ s, f₁ x = f x) : differentiable_on 𝕜 f₁ s := λ x hx, (h x hx).congr h' (h' x hx) lemma differentiable_on_congr (h' : ∀x ∈ s, f₁ x = f x) : differentiable_on 𝕜 f₁ s ↔ differentiable_on 𝕜 f s := ⟨λ h, differentiable_on.congr h (λy hy, (h' y hy).symm), λ h, differentiable_on.congr h h'⟩ lemma differentiable_at.congr_of_eventually_eq (h : differentiable_at 𝕜 f x) (hL : f₁ =ᶠ[𝓝 x] f) : differentiable_at 𝕜 f₁ x := has_fderiv_at.differentiable_at (has_fderiv_at_filter.congr_of_eventually_eq h.has_fderiv_at hL (mem_of_nhds hL : _)) lemma differentiable_within_at.fderiv_within_congr_mono (h : differentiable_within_at 𝕜 f s x) (hs : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (hxt : unique_diff_within_at 𝕜 t x) (h₁ : t ⊆ s) : fderiv_within 𝕜 f₁ t x = fderiv_within 𝕜 f s x := (has_fderiv_within_at.congr_mono h.has_fderiv_within_at hs hx h₁).fderiv_within hxt lemma filter.eventually_eq.fderiv_within_eq (hs : unique_diff_within_at 𝕜 s x) (hL : f₁ =ᶠ[nhds_within x s] f) (hx : f₁ x = f x) : fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x := if h : differentiable_within_at 𝕜 f s x then has_fderiv_within_at.fderiv_within (h.has_fderiv_within_at.congr_of_eventually_eq hL hx) hs else have h' : ¬ differentiable_within_at 𝕜 f₁ s x, from mt (λ h, h.congr_of_eventually_eq (hL.mono $ λ x, eq.symm) hx.symm) h, by rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at h'] lemma fderiv_within_congr (hs : unique_diff_within_at 𝕜 s x) (hL : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) : fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x := begin apply filter.eventually_eq.fderiv_within_eq hs _ hx, apply mem_sets_of_superset self_mem_nhds_within, exact hL end lemma filter.eventually_eq.fderiv_eq (hL : f₁ =ᶠ[𝓝 x] f) : fderiv 𝕜 f₁ x = fderiv 𝕜 f x := begin have A : f₁ x = f x := (mem_of_nhds hL : _), rw [← fderiv_within_univ, ← fderiv_within_univ], rw ← nhds_within_univ at hL, exact hL.fderiv_within_eq unique_diff_within_at_univ A end end congr section id /-! ### Derivative of the identity -/ theorem has_strict_fderiv_at_id (x : E) : has_strict_fderiv_at id (id 𝕜 E) x := (is_o_zero _ _).congr_left $ by simp theorem has_fderiv_at_filter_id (x : E) (L : filter E) : has_fderiv_at_filter id (id 𝕜 E) x L := (is_o_zero _ _).congr_left $ by simp theorem has_fderiv_within_at_id (x : E) (s : set E) : has_fderiv_within_at id (id 𝕜 E) s x := has_fderiv_at_filter_id _ _ theorem has_fderiv_at_id (x : E) : has_fderiv_at id (id 𝕜 E) x := has_fderiv_at_filter_id _ _ @[simp] lemma differentiable_at_id : differentiable_at 𝕜 id x := (has_fderiv_at_id x).differentiable_at @[simp] lemma differentiable_at_id' : differentiable_at 𝕜 (λ x, x) x := (has_fderiv_at_id x).differentiable_at lemma differentiable_within_at_id : differentiable_within_at 𝕜 id s x := differentiable_at_id.differentiable_within_at @[simp] lemma differentiable_id : differentiable 𝕜 (id : E → E) := λx, differentiable_at_id @[simp] lemma differentiable_id' : differentiable 𝕜 (λ (x : E), x) := λx, differentiable_at_id lemma differentiable_on_id : differentiable_on 𝕜 id s := differentiable_id.differentiable_on lemma fderiv_id : fderiv 𝕜 id x = id 𝕜 E := has_fderiv_at.fderiv (has_fderiv_at_id x) lemma fderiv_within_id (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 id s x = id 𝕜 E := begin rw differentiable_at.fderiv_within (differentiable_at_id) hxs, exact fderiv_id end end id section const /-! ### derivative of a constant function -/ theorem has_strict_fderiv_at_const (c : F) (x : E) : has_strict_fderiv_at (λ _, c) (0 : E →L[𝕜] F) x := (is_o_zero _ _).congr_left $ λ _, by simp only [zero_apply, sub_self] theorem has_fderiv_at_filter_const (c : F) (x : E) (L : filter E) : has_fderiv_at_filter (λ x, c) (0 : E →L[𝕜] F) x L := (is_o_zero _ _).congr_left $ λ _, by simp only [zero_apply, sub_self] theorem has_fderiv_within_at_const (c : F) (x : E) (s : set E) : has_fderiv_within_at (λ x, c) (0 : E →L[𝕜] F) s x := has_fderiv_at_filter_const _ _ _ theorem has_fderiv_at_const (c : F) (x : E) : has_fderiv_at (λ x, c) (0 : E →L[𝕜] F) x := has_fderiv_at_filter_const _ _ _ @[simp] lemma differentiable_at_const (c : F) : differentiable_at 𝕜 (λx, c) x := ⟨0, has_fderiv_at_const c x⟩ lemma differentiable_within_at_const (c : F) : differentiable_within_at 𝕜 (λx, c) s x := differentiable_at.differentiable_within_at (differentiable_at_const _) lemma fderiv_const_apply (c : F) : fderiv 𝕜 (λy, c) x = 0 := has_fderiv_at.fderiv (has_fderiv_at_const c x) lemma fderiv_const (c : F) : fderiv 𝕜 (λ (y : E), c) = 0 := by { ext m, rw fderiv_const_apply, refl } lemma fderiv_within_const_apply (c : F) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λy, c) s x = 0 := begin rw differentiable_at.fderiv_within (differentiable_at_const _) hxs, exact fderiv_const_apply _ end @[simp] lemma differentiable_const (c : F) : differentiable 𝕜 (λx : E, c) := λx, differentiable_at_const _ lemma differentiable_on_const (c : F) : differentiable_on 𝕜 (λx, c) s := (differentiable_const _).differentiable_on end const section continuous_linear_map /-! ### Continuous linear maps There are currently two variants of these in mathlib, the bundled version (named `continuous_linear_map`, and denoted `E →L[𝕜] F`), and the unbundled version (with a predicate `is_bounded_linear_map`). We give statements for both versions. -/ protected theorem continuous_linear_map.has_strict_fderiv_at {x : E} : has_strict_fderiv_at e e x := (is_o_zero _ _).congr_left $ λ x, by simp only [e.map_sub, sub_self] protected lemma continuous_linear_map.has_fderiv_at_filter : has_fderiv_at_filter e e x L := (is_o_zero _ _).congr_left $ λ x, by simp only [e.map_sub, sub_self] protected lemma continuous_linear_map.has_fderiv_within_at : has_fderiv_within_at e e s x := e.has_fderiv_at_filter protected lemma continuous_linear_map.has_fderiv_at : has_fderiv_at e e x := e.has_fderiv_at_filter @[simp] protected lemma continuous_linear_map.differentiable_at : differentiable_at 𝕜 e x := e.has_fderiv_at.differentiable_at protected lemma continuous_linear_map.differentiable_within_at : differentiable_within_at 𝕜 e s x := e.differentiable_at.differentiable_within_at protected lemma continuous_linear_map.fderiv : fderiv 𝕜 e x = e := e.has_fderiv_at.fderiv protected lemma continuous_linear_map.fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 e s x = e := begin rw differentiable_at.fderiv_within e.differentiable_at hxs, exact e.fderiv end @[simp]protected lemma continuous_linear_map.differentiable : differentiable 𝕜 e := λx, e.differentiable_at protected lemma continuous_linear_map.differentiable_on : differentiable_on 𝕜 e s := e.differentiable.differentiable_on lemma is_bounded_linear_map.has_fderiv_at_filter (h : is_bounded_linear_map 𝕜 f) : has_fderiv_at_filter f h.to_continuous_linear_map x L := h.to_continuous_linear_map.has_fderiv_at_filter lemma is_bounded_linear_map.has_fderiv_within_at (h : is_bounded_linear_map 𝕜 f) : has_fderiv_within_at f h.to_continuous_linear_map s x := h.has_fderiv_at_filter lemma is_bounded_linear_map.has_fderiv_at (h : is_bounded_linear_map 𝕜 f) : has_fderiv_at f h.to_continuous_linear_map x := h.has_fderiv_at_filter lemma is_bounded_linear_map.differentiable_at (h : is_bounded_linear_map 𝕜 f) : differentiable_at 𝕜 f x := h.has_fderiv_at.differentiable_at lemma is_bounded_linear_map.differentiable_within_at (h : is_bounded_linear_map 𝕜 f) : differentiable_within_at 𝕜 f s x := h.differentiable_at.differentiable_within_at lemma is_bounded_linear_map.fderiv (h : is_bounded_linear_map 𝕜 f) : fderiv 𝕜 f x = h.to_continuous_linear_map := has_fderiv_at.fderiv (h.has_fderiv_at) lemma is_bounded_linear_map.fderiv_within (h : is_bounded_linear_map 𝕜 f) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = h.to_continuous_linear_map := begin rw differentiable_at.fderiv_within h.differentiable_at hxs, exact h.fderiv end lemma is_bounded_linear_map.differentiable (h : is_bounded_linear_map 𝕜 f) : differentiable 𝕜 f := λx, h.differentiable_at lemma is_bounded_linear_map.differentiable_on (h : is_bounded_linear_map 𝕜 f) : differentiable_on 𝕜 f s := h.differentiable.differentiable_on end continuous_linear_map section composition /-! ### Derivative of the composition of two functions For composition lemmas, we put x explicit to help the elaborator, as otherwise Lean tends to get confused since there are too many possibilities for composition -/ variable (x) theorem has_fderiv_at_filter.comp {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at_filter g g' (f x) (L.map f)) (hf : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (g ∘ f) (g'.comp f') x L := let eq₁ := (g'.is_O_comp _ _).trans_is_o hf in let eq₂ := (hg.comp_tendsto tendsto_map).trans_is_O hf.is_O_sub in by { refine eq₂.triangle (eq₁.congr_left (λ x', _)), simp } /- A readable version of the previous theorem, a general form of the chain rule. -/ example {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at_filter g g' (f x) (L.map f)) (hf : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (g ∘ f) (g'.comp f') x L := begin unfold has_fderiv_at_filter at hg, have : is_o (λ x', g (f x') - g (f x) - g' (f x' - f x)) (λ x', f x' - f x) L, from hg.comp_tendsto (le_refl _), have eq₁ : is_o (λ x', g (f x') - g (f x) - g' (f x' - f x)) (λ x', x' - x) L, from this.trans_is_O hf.is_O_sub, have eq₂ : is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L, from hf, have : is_O (λ x', g' (f x' - f x - f' (x' - x))) (λ x', f x' - f x - f' (x' - x)) L, from g'.is_O_comp _ _, have : is_o (λ x', g' (f x' - f x - f' (x' - x))) (λ x', x' - x) L, from this.trans_is_o eq₂, have eq₃ : is_o (λ x', g' (f x' - f x) - (g' (f' (x' - x)))) (λ x', x' - x) L, by { refine this.congr_left _, simp}, exact eq₁.triangle eq₃ end theorem has_fderiv_within_at.comp {g : F → G} {g' : F →L[𝕜] G} {t : set F} (hg : has_fderiv_within_at g g' t (f x)) (hf : has_fderiv_within_at f f' s x) (hst : s ⊆ f ⁻¹' t) : has_fderiv_within_at (g ∘ f) (g'.comp f') s x := begin apply has_fderiv_at_filter.comp _ (has_fderiv_at_filter.mono hg _) hf, calc map f (nhds_within x s) ≤ nhds_within (f x) (f '' s) : hf.continuous_within_at.tendsto_nhds_within_image ... ≤ nhds_within (f x) t : nhds_within_mono _ (image_subset_iff.mpr hst) end /-- The chain rule. -/ theorem has_fderiv_at.comp {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at g g' (f x)) (hf : has_fderiv_at f f' x) : has_fderiv_at (g ∘ f) (g'.comp f') x := (hg.mono hf.continuous_at).comp x hf theorem has_fderiv_at.comp_has_fderiv_within_at {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at g g' (f x)) (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (g ∘ f) (g'.comp f') s x := begin rw ← has_fderiv_within_at_univ at hg, exact has_fderiv_within_at.comp x hg hf subset_preimage_univ end lemma differentiable_within_at.comp {g : F → G} {t : set F} (hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) (h : s ⊆ f ⁻¹' t) : differentiable_within_at 𝕜 (g ∘ f) s x := begin rcases hf with ⟨f', hf'⟩, rcases hg with ⟨g', hg'⟩, exact ⟨continuous_linear_map.comp g' f', hg'.comp x hf' h⟩ end lemma differentiable_within_at.comp' {g : F → G} {t : set F} (hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (g ∘ f) (s ∩ f⁻¹' t) x := hg.comp x (hf.mono (inter_subset_left _ _)) (inter_subset_right _ _) lemma differentiable_at.comp {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (g ∘ f) x := (hg.has_fderiv_at.comp x hf.has_fderiv_at).differentiable_at lemma differentiable_at.comp_differentiable_within_at {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (g ∘ f) s x := (differentiable_within_at_univ.2 hg).comp x hf (by simp) lemma fderiv_within.comp {g : F → G} {t : set F} (hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) (h : maps_to f s t) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (g ∘ f) s x = (fderiv_within 𝕜 g t (f x)).comp (fderiv_within 𝕜 f s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_within_at.comp x (hg.has_fderiv_within_at) (hf.has_fderiv_within_at) h end lemma fderiv.comp {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_at 𝕜 f x) : fderiv 𝕜 (g ∘ f) x = (fderiv 𝕜 g (f x)).comp (fderiv 𝕜 f x) := begin apply has_fderiv_at.fderiv, exact has_fderiv_at.comp x hg.has_fderiv_at hf.has_fderiv_at end lemma fderiv.comp_fderiv_within {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_within_at 𝕜 f s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (g ∘ f) s x = (fderiv 𝕜 g (f x)).comp (fderiv_within 𝕜 f s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_at.comp_has_fderiv_within_at x (hg.has_fderiv_at) (hf.has_fderiv_within_at) end lemma differentiable_on.comp {g : F → G} {t : set F} (hg : differentiable_on 𝕜 g t) (hf : differentiable_on 𝕜 f s) (st : s ⊆ f ⁻¹' t) : differentiable_on 𝕜 (g ∘ f) s := λx hx, differentiable_within_at.comp x (hg (f x) (st hx)) (hf x hx) st lemma differentiable.comp {g : F → G} (hg : differentiable 𝕜 g) (hf : differentiable 𝕜 f) : differentiable 𝕜 (g ∘ f) := λx, differentiable_at.comp x (hg (f x)) (hf x) lemma differentiable.comp_differentiable_on {g : F → G} (hg : differentiable 𝕜 g) (hf : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (g ∘ f) s := (differentiable_on_univ.2 hg).comp hf (by simp) /-- The chain rule for derivatives in the sense of strict differentiability. -/ protected lemma has_strict_fderiv_at.comp {g : F → G} {g' : F →L[𝕜] G} (hg : has_strict_fderiv_at g g' (f x)) (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, g (f x)) (g'.comp f') x := ((hg.comp_tendsto (hf.continuous_at.prod_map' hf.continuous_at)).trans_is_O hf.is_O_sub).triangle $ by simpa only [g'.map_sub, f'.coe_comp'] using (g'.is_O_comp _ _).trans_is_o hf protected lemma differentiable.iterate {f : E → E} (hf : differentiable 𝕜 f) (n : ℕ) : differentiable 𝕜 (f^[n]) := nat.rec_on n differentiable_id (λ n ihn, ihn.comp hf) protected lemma differentiable_on.iterate {f : E → E} (hf : differentiable_on 𝕜 f s) (hs : maps_to f s s) (n : ℕ) : differentiable_on 𝕜 (f^[n]) s := nat.rec_on n differentiable_on_id (λ n ihn, ihn.comp hf hs) variable {x} protected lemma has_fderiv_at_filter.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_fderiv_at_filter f f' x L) (hL : tendsto f L L) (hx : f x = x) (n : ℕ) : has_fderiv_at_filter (f^[n]) (f'^n) x L := begin induction n with n ihn, { exact has_fderiv_at_filter_id x L }, { change has_fderiv_at_filter (f^[n] ∘ f) (f'^(n+1)) x L, rw [pow_succ'], refine has_fderiv_at_filter.comp x _ hf, rw hx, exact ihn.mono hL } end protected lemma has_fderiv_at.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_fderiv_at f f' x) (hx : f x = x) (n : ℕ) : has_fderiv_at (f^[n]) (f'^n) x := begin refine hf.iterate _ hx n, convert hf.continuous_at, exact hx.symm end protected lemma has_fderiv_within_at.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_fderiv_within_at f f' s x) (hx : f x = x) (hs : maps_to f s s) (n : ℕ) : has_fderiv_within_at (f^[n]) (f'^n) s x := begin refine hf.iterate _ hx n, convert tendsto_inf.2 ⟨hf.continuous_within_at, _⟩, exacts [hx.symm, tendsto_le_left inf_le_right (tendsto_principal_principal.2 hs)] end protected lemma has_strict_fderiv_at.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_strict_fderiv_at f f' x) (hx : f x = x) (n : ℕ) : has_strict_fderiv_at (f^[n]) (f'^n) x := begin induction n with n ihn, { exact has_strict_fderiv_at_id x }, { change has_strict_fderiv_at (f^[n] ∘ f) (f'^(n+1)) x, rw [pow_succ'], refine has_strict_fderiv_at.comp x _ hf, rwa hx } end protected lemma differentiable_at.iterate {f : E → E} (hf : differentiable_at 𝕜 f x) (hx : f x = x) (n : ℕ) : differentiable_at 𝕜 (f^[n]) x := exists.elim hf $ λ f' hf, (hf.iterate hx n).differentiable_at protected lemma differentiable_within_at.iterate {f : E → E} (hf : differentiable_within_at 𝕜 f s x) (hx : f x = x) (hs : maps_to f s s) (n : ℕ) : differentiable_within_at 𝕜 (f^[n]) s x := exists.elim hf $ λ f' hf, (hf.iterate hx hs n).differentiable_within_at end composition section cartesian_product /-! ### Derivative of the cartesian product of two functions -/ section prod variables {f₂ : E → G} {f₂' : E →L[𝕜] G} protected lemma has_strict_fderiv_at.prod (hf₁ : has_strict_fderiv_at f₁ f₁' x) (hf₂ : has_strict_fderiv_at f₂ f₂' x) : has_strict_fderiv_at (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') x := hf₁.prod_left hf₂ lemma has_fderiv_at_filter.prod (hf₁ : has_fderiv_at_filter f₁ f₁' x L) (hf₂ : has_fderiv_at_filter f₂ f₂' x L) : has_fderiv_at_filter (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') x L := hf₁.prod_left hf₂ lemma has_fderiv_within_at.prod (hf₁ : has_fderiv_within_at f₁ f₁' s x) (hf₂ : has_fderiv_within_at f₂ f₂' s x) : has_fderiv_within_at (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') s x := hf₁.prod hf₂ lemma has_fderiv_at.prod (hf₁ : has_fderiv_at f₁ f₁' x) (hf₂ : has_fderiv_at f₂ f₂' x) : has_fderiv_at (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') x := hf₁.prod hf₂ lemma differentiable_within_at.prod (hf₁ : differentiable_within_at 𝕜 f₁ s x) (hf₂ : differentiable_within_at 𝕜 f₂ s x) : differentiable_within_at 𝕜 (λx:E, (f₁ x, f₂ x)) s x := (hf₁.has_fderiv_within_at.prod hf₂.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.prod (hf₁ : differentiable_at 𝕜 f₁ x) (hf₂ : differentiable_at 𝕜 f₂ x) : differentiable_at 𝕜 (λx:E, (f₁ x, f₂ x)) x := (hf₁.has_fderiv_at.prod hf₂.has_fderiv_at).differentiable_at lemma differentiable_on.prod (hf₁ : differentiable_on 𝕜 f₁ s) (hf₂ : differentiable_on 𝕜 f₂ s) : differentiable_on 𝕜 (λx:E, (f₁ x, f₂ x)) s := λx hx, differentiable_within_at.prod (hf₁ x hx) (hf₂ x hx) @[simp] lemma differentiable.prod (hf₁ : differentiable 𝕜 f₁) (hf₂ : differentiable 𝕜 f₂) : differentiable 𝕜 (λx:E, (f₁ x, f₂ x)) := λ x, differentiable_at.prod (hf₁ x) (hf₂ x) lemma differentiable_at.fderiv_prod (hf₁ : differentiable_at 𝕜 f₁ x) (hf₂ : differentiable_at 𝕜 f₂ x) : fderiv 𝕜 (λx:E, (f₁ x, f₂ x)) x = continuous_linear_map.prod (fderiv 𝕜 f₁ x) (fderiv 𝕜 f₂ x) := has_fderiv_at.fderiv (has_fderiv_at.prod hf₁.has_fderiv_at hf₂.has_fderiv_at) lemma differentiable_at.fderiv_within_prod (hf₁ : differentiable_within_at 𝕜 f₁ s x) (hf₂ : differentiable_within_at 𝕜 f₂ s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx:E, (f₁ x, f₂ x)) s x = continuous_linear_map.prod (fderiv_within 𝕜 f₁ s x) (fderiv_within 𝕜 f₂ s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_within_at.prod hf₁.has_fderiv_within_at hf₂.has_fderiv_within_at end end prod section fst variables {f₂ : E → F × G} {f₂' : E →L[𝕜] F × G} {p : E × F} lemma has_strict_fderiv_at_fst : has_strict_fderiv_at prod.fst (fst 𝕜 E F) p := (fst 𝕜 E F).has_strict_fderiv_at protected lemma has_strict_fderiv_at.fst (h : has_strict_fderiv_at f₂ f₂' x) : has_strict_fderiv_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x := has_strict_fderiv_at_fst.comp x h lemma has_fderiv_at_filter_fst {L : filter (E × F)} : has_fderiv_at_filter prod.fst (fst 𝕜 E F) p L := (fst 𝕜 E F).has_fderiv_at_filter protected lemma has_fderiv_at_filter.fst (h : has_fderiv_at_filter f₂ f₂' x L) : has_fderiv_at_filter (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x L := has_fderiv_at_filter_fst.comp x h lemma has_fderiv_at_fst : has_fderiv_at prod.fst (fst 𝕜 E F) p := has_fderiv_at_filter_fst protected lemma has_fderiv_at.fst (h : has_fderiv_at f₂ f₂' x) : has_fderiv_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x := h.fst lemma has_fderiv_within_at_fst {s : set (E × F)} : has_fderiv_within_at prod.fst (fst 𝕜 E F) s p := has_fderiv_at_filter_fst protected lemma has_fderiv_within_at.fst (h : has_fderiv_within_at f₂ f₂' s x) : has_fderiv_within_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') s x := h.fst lemma differentiable_at_fst : differentiable_at 𝕜 prod.fst p := has_fderiv_at_fst.differentiable_at @[simp] protected lemma differentiable_at.fst (h : differentiable_at 𝕜 f₂ x) : differentiable_at 𝕜 (λ x, (f₂ x).1) x := differentiable_at_fst.comp x h lemma differentiable_fst : differentiable 𝕜 (prod.fst : E × F → E) := λ x, differentiable_at_fst @[simp] protected lemma differentiable.fst (h : differentiable 𝕜 f₂) : differentiable 𝕜 (λ x, (f₂ x).1) := differentiable_fst.comp h lemma differentiable_within_at_fst {s : set (E × F)} : differentiable_within_at 𝕜 prod.fst s p := differentiable_at_fst.differentiable_within_at protected lemma differentiable_within_at.fst (h : differentiable_within_at 𝕜 f₂ s x) : differentiable_within_at 𝕜 (λ x, (f₂ x).1) s x := differentiable_at_fst.comp_differentiable_within_at x h lemma differentiable_on_fst {s : set (E × F)} : differentiable_on 𝕜 prod.fst s := differentiable_fst.differentiable_on protected lemma differentiable_on.fst (h : differentiable_on 𝕜 f₂ s) : differentiable_on 𝕜 (λ x, (f₂ x).1) s := differentiable_fst.comp_differentiable_on h lemma fderiv_fst : fderiv 𝕜 prod.fst p = fst 𝕜 E F := has_fderiv_at_fst.fderiv lemma fderiv.fst (h : differentiable_at 𝕜 f₂ x) : fderiv 𝕜 (λ x, (f₂ x).1) x = (fst 𝕜 F G).comp (fderiv 𝕜 f₂ x) := h.has_fderiv_at.fst.fderiv lemma fderiv_within_fst {s : set (E × F)} (hs : unique_diff_within_at 𝕜 s p) : fderiv_within 𝕜 prod.fst s p = fst 𝕜 E F := has_fderiv_within_at_fst.fderiv_within hs lemma fderiv_within.fst (hs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f₂ s x) : fderiv_within 𝕜 (λ x, (f₂ x).1) s x = (fst 𝕜 F G).comp (fderiv_within 𝕜 f₂ s x) := h.has_fderiv_within_at.fst.fderiv_within hs end fst section snd variables {f₂ : E → F × G} {f₂' : E →L[𝕜] F × G} {p : E × F} lemma has_strict_fderiv_at_snd : has_strict_fderiv_at prod.snd (snd 𝕜 E F) p := (snd 𝕜 E F).has_strict_fderiv_at protected lemma has_strict_fderiv_at.snd (h : has_strict_fderiv_at f₂ f₂' x) : has_strict_fderiv_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x := has_strict_fderiv_at_snd.comp x h lemma has_fderiv_at_filter_snd {L : filter (E × F)} : has_fderiv_at_filter prod.snd (snd 𝕜 E F) p L := (snd 𝕜 E F).has_fderiv_at_filter protected lemma has_fderiv_at_filter.snd (h : has_fderiv_at_filter f₂ f₂' x L) : has_fderiv_at_filter (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x L := has_fderiv_at_filter_snd.comp x h lemma has_fderiv_at_snd : has_fderiv_at prod.snd (snd 𝕜 E F) p := has_fderiv_at_filter_snd protected lemma has_fderiv_at.snd (h : has_fderiv_at f₂ f₂' x) : has_fderiv_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x := h.snd lemma has_fderiv_within_at_snd {s : set (E × F)} : has_fderiv_within_at prod.snd (snd 𝕜 E F) s p := has_fderiv_at_filter_snd protected lemma has_fderiv_within_at.snd (h : has_fderiv_within_at f₂ f₂' s x) : has_fderiv_within_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') s x := h.snd lemma differentiable_at_snd : differentiable_at 𝕜 prod.snd p := has_fderiv_at_snd.differentiable_at @[simp] protected lemma differentiable_at.snd (h : differentiable_at 𝕜 f₂ x) : differentiable_at 𝕜 (λ x, (f₂ x).2) x := differentiable_at_snd.comp x h lemma differentiable_snd : differentiable 𝕜 (prod.snd : E × F → F) := λ x, differentiable_at_snd @[simp] protected lemma differentiable.snd (h : differentiable 𝕜 f₂) : differentiable 𝕜 (λ x, (f₂ x).2) := differentiable_snd.comp h lemma differentiable_within_at_snd {s : set (E × F)} : differentiable_within_at 𝕜 prod.snd s p := differentiable_at_snd.differentiable_within_at protected lemma differentiable_within_at.snd (h : differentiable_within_at 𝕜 f₂ s x) : differentiable_within_at 𝕜 (λ x, (f₂ x).2) s x := differentiable_at_snd.comp_differentiable_within_at x h lemma differentiable_on_snd {s : set (E × F)} : differentiable_on 𝕜 prod.snd s := differentiable_snd.differentiable_on protected lemma differentiable_on.snd (h : differentiable_on 𝕜 f₂ s) : differentiable_on 𝕜 (λ x, (f₂ x).2) s := differentiable_snd.comp_differentiable_on h lemma fderiv_snd : fderiv 𝕜 prod.snd p = snd 𝕜 E F := has_fderiv_at_snd.fderiv lemma fderiv.snd (h : differentiable_at 𝕜 f₂ x) : fderiv 𝕜 (λ x, (f₂ x).2) x = (snd 𝕜 F G).comp (fderiv 𝕜 f₂ x) := h.has_fderiv_at.snd.fderiv lemma fderiv_within_snd {s : set (E × F)} (hs : unique_diff_within_at 𝕜 s p) : fderiv_within 𝕜 prod.snd s p = snd 𝕜 E F := has_fderiv_within_at_snd.fderiv_within hs lemma fderiv_within.snd (hs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f₂ s x) : fderiv_within 𝕜 (λ x, (f₂ x).2) s x = (snd 𝕜 F G).comp (fderiv_within 𝕜 f₂ s x) := h.has_fderiv_within_at.snd.fderiv_within hs end snd section prod_map variables {f₂ : G → G'} {f₂' : G →L[𝕜] G'} {y : G} (p : E × G) -- TODO (Lean 3.8): use `prod.map f f₂`` protected theorem has_strict_fderiv_at.prod_map (hf : has_strict_fderiv_at f f' p.1) (hf₂ : has_strict_fderiv_at f₂ f₂' p.2) : has_strict_fderiv_at (λ p : E × G, (f p.1, f₂ p.2)) (f'.prod_map f₂') p := (hf.comp p has_strict_fderiv_at_fst).prod (hf₂.comp p has_strict_fderiv_at_snd) protected theorem has_fderiv_at.prod_map (hf : has_fderiv_at f f' p.1) (hf₂ : has_fderiv_at f₂ f₂' p.2) : has_fderiv_at (λ p : E × G, (f p.1, f₂ p.2)) (f'.prod_map f₂') p := (hf.comp p has_fderiv_at_fst).prod (hf₂.comp p has_fderiv_at_snd) @[simp] protected theorem differentiable_at.prod_map (hf : differentiable_at 𝕜 f p.1) (hf₂ : differentiable_at 𝕜 f₂ p.2) : differentiable_at 𝕜 (λ p : E × G, (f p.1, f₂ p.2)) p := (hf.comp p differentiable_at_fst).prod (hf₂.comp p differentiable_at_snd) end prod_map end cartesian_product section const_smul /-! ### Derivative of a function multiplied by a constant -/ theorem has_strict_fderiv_at.const_smul (h : has_strict_fderiv_at f f' x) (c : 𝕜) : has_strict_fderiv_at (λ x, c • f x) (c • f') x := (c • (1 : F →L[𝕜] F)).has_strict_fderiv_at.comp x h theorem has_fderiv_at_filter.const_smul (h : has_fderiv_at_filter f f' x L) (c : 𝕜) : has_fderiv_at_filter (λ x, c • f x) (c • f') x L := (c • (1 : F →L[𝕜] F)).has_fderiv_at_filter.comp x h theorem has_fderiv_within_at.const_smul (h : has_fderiv_within_at f f' s x) (c : 𝕜) : has_fderiv_within_at (λ x, c • f x) (c • f') s x := h.const_smul c theorem has_fderiv_at.const_smul (h : has_fderiv_at f f' x) (c : 𝕜) : has_fderiv_at (λ x, c • f x) (c • f') x := h.const_smul c lemma differentiable_within_at.const_smul (h : differentiable_within_at 𝕜 f s x) (c : 𝕜) : differentiable_within_at 𝕜 (λy, c • f y) s x := (h.has_fderiv_within_at.const_smul c).differentiable_within_at lemma differentiable_at.const_smul (h : differentiable_at 𝕜 f x) (c : 𝕜) : differentiable_at 𝕜 (λy, c • f y) x := (h.has_fderiv_at.const_smul c).differentiable_at lemma differentiable_on.const_smul (h : differentiable_on 𝕜 f s) (c : 𝕜) : differentiable_on 𝕜 (λy, c • f y) s := λx hx, (h x hx).const_smul c lemma differentiable.const_smul (h : differentiable 𝕜 f) (c : 𝕜) : differentiable 𝕜 (λy, c • f y) := λx, (h x).const_smul c lemma fderiv_within_const_smul (hxs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f s x) (c : 𝕜) : fderiv_within 𝕜 (λy, c • f y) s x = c • fderiv_within 𝕜 f s x := (h.has_fderiv_within_at.const_smul c).fderiv_within hxs lemma fderiv_const_smul (h : differentiable_at 𝕜 f x) (c : 𝕜) : fderiv 𝕜 (λy, c • f y) x = c • fderiv 𝕜 f x := (h.has_fderiv_at.const_smul c).fderiv end const_smul section add /-! ### Derivative of the sum of two functions -/ theorem has_strict_fderiv_at.add (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) : has_strict_fderiv_at (λ y, f y + g y) (f' + g') x := (hf.add hg).congr_left $ λ y, by simp; abel theorem has_fderiv_at_filter.add (hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) : has_fderiv_at_filter (λ y, f y + g y) (f' + g') x L := (hf.add hg).congr_left $ λ _, by simp; abel theorem has_fderiv_within_at.add (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) : has_fderiv_within_at (λ y, f y + g y) (f' + g') s x := hf.add hg theorem has_fderiv_at.add (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) : has_fderiv_at (λ x, f x + g x) (f' + g') x := hf.add hg lemma differentiable_within_at.add (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : differentiable_within_at 𝕜 (λ y, f y + g y) s x := (hf.has_fderiv_within_at.add hg.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : differentiable_at 𝕜 (λ y, f y + g y) x := (hf.has_fderiv_at.add hg.has_fderiv_at).differentiable_at lemma differentiable_on.add (hf : differentiable_on 𝕜 f s) (hg : differentiable_on 𝕜 g s) : differentiable_on 𝕜 (λy, f y + g y) s := λx hx, (hf x hx).add (hg x hx) @[simp] lemma differentiable.add (hf : differentiable 𝕜 f) (hg : differentiable 𝕜 g) : differentiable 𝕜 (λy, f y + g y) := λx, (hf x).add (hg x) lemma fderiv_within_add (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : fderiv_within 𝕜 (λy, f y + g y) s x = fderiv_within 𝕜 f s x + fderiv_within 𝕜 g s x := (hf.has_fderiv_within_at.add hg.has_fderiv_within_at).fderiv_within hxs lemma fderiv_add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : fderiv 𝕜 (λy, f y + g y) x = fderiv 𝕜 f x + fderiv 𝕜 g x := (hf.has_fderiv_at.add hg.has_fderiv_at).fderiv theorem has_strict_fderiv_at.add_const (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ y, f y + c) f' x := add_zero f' ▸ hf.add (has_strict_fderiv_at_const _ _) theorem has_fderiv_at_filter.add_const (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ y, f y + c) f' x L := add_zero f' ▸ hf.add (has_fderiv_at_filter_const _ _ _) theorem has_fderiv_within_at.add_const (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ y, f y + c) f' s x := hf.add_const c theorem has_fderiv_at.add_const (hf : has_fderiv_at f f' x) (c : F): has_fderiv_at (λ x, f x + c) f' x := hf.add_const c lemma differentiable_within_at.add_const (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, f y + c) s x := (hf.has_fderiv_within_at.add_const c).differentiable_within_at lemma differentiable_at.add_const (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, f y + c) x := (hf.has_fderiv_at.add_const c).differentiable_at lemma differentiable_on.add_const (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, f y + c) s := λx hx, (hf x hx).add_const c lemma differentiable.add_const (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, f y + c) := λx, (hf x).add_const c lemma fderiv_within_add_const (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : fderiv_within 𝕜 (λy, f y + c) s x = fderiv_within 𝕜 f s x := (hf.has_fderiv_within_at.add_const c).fderiv_within hxs lemma fderiv_add_const (hf : differentiable_at 𝕜 f x) (c : F) : fderiv 𝕜 (λy, f y + c) x = fderiv 𝕜 f x := (hf.has_fderiv_at.add_const c).fderiv theorem has_strict_fderiv_at.const_add (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ y, c + f y) f' x := zero_add f' ▸ (has_strict_fderiv_at_const _ _).add hf theorem has_fderiv_at_filter.const_add (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ y, c + f y) f' x L := zero_add f' ▸ (has_fderiv_at_filter_const _ _ _).add hf theorem has_fderiv_within_at.const_add (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ y, c + f y) f' s x := hf.const_add c theorem has_fderiv_at.const_add (hf : has_fderiv_at f f' x) (c : F): has_fderiv_at (λ x, c + f x) f' x := hf.const_add c lemma differentiable_within_at.const_add (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, c + f y) s x := (hf.has_fderiv_within_at.const_add c).differentiable_within_at lemma differentiable_at.const_add (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, c + f y) x := (hf.has_fderiv_at.const_add c).differentiable_at lemma differentiable_on.const_add (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, c + f y) s := λx hx, (hf x hx).const_add c lemma differentiable.const_add (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, c + f y) := λx, (hf x).const_add c lemma fderiv_within_const_add (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : fderiv_within 𝕜 (λy, c + f y) s x = fderiv_within 𝕜 f s x := (hf.has_fderiv_within_at.const_add c).fderiv_within hxs lemma fderiv_const_add (hf : differentiable_at 𝕜 f x) (c : F) : fderiv 𝕜 (λy, c + f y) x = fderiv 𝕜 f x := (hf.has_fderiv_at.const_add c).fderiv end add section sum /-! ### Derivative of a finite sum of functions -/ open_locale big_operators variables {ι : Type*} {u : finset ι} {A : ι → (E → F)} {A' : ι → (E →L[𝕜] F)} theorem has_strict_fderiv_at.sum (h : ∀ i ∈ u, has_strict_fderiv_at (A i) (A' i) x) : has_strict_fderiv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x := begin dsimp [has_strict_fderiv_at] at *, convert is_o.sum h, simp [finset.sum_sub_distrib, continuous_linear_map.sum_apply] end theorem has_fderiv_at_filter.sum (h : ∀ i ∈ u, has_fderiv_at_filter (A i) (A' i) x L) : has_fderiv_at_filter (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x L := begin dsimp [has_fderiv_at_filter] at *, convert is_o.sum h, simp [continuous_linear_map.sum_apply] end theorem has_fderiv_within_at.sum (h : ∀ i ∈ u, has_fderiv_within_at (A i) (A' i) s x) : has_fderiv_within_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) s x := has_fderiv_at_filter.sum h theorem has_fderiv_at.sum (h : ∀ i ∈ u, has_fderiv_at (A i) (A' i) x) : has_fderiv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x := has_fderiv_at_filter.sum h theorem differentiable_within_at.sum (h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) : differentiable_within_at 𝕜 (λ y, ∑ i in u, A i y) s x := has_fderiv_within_at.differentiable_within_at $ has_fderiv_within_at.sum $ λ i hi, (h i hi).has_fderiv_within_at @[simp] theorem differentiable_at.sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) : differentiable_at 𝕜 (λ y, ∑ i in u, A i y) x := has_fderiv_at.differentiable_at $ has_fderiv_at.sum $ λ i hi, (h i hi).has_fderiv_at theorem differentiable_on.sum (h : ∀ i ∈ u, differentiable_on 𝕜 (A i) s) : differentiable_on 𝕜 (λ y, ∑ i in u, A i y) s := λ x hx, differentiable_within_at.sum $ λ i hi, h i hi x hx @[simp] theorem differentiable.sum (h : ∀ i ∈ u, differentiable 𝕜 (A i)) : differentiable 𝕜 (λ y, ∑ i in u, A i y) := λ x, differentiable_at.sum $ λ i hi, h i hi x theorem fderiv_within_sum (hxs : unique_diff_within_at 𝕜 s x) (h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) : fderiv_within 𝕜 (λ y, ∑ i in u, A i y) s x = (∑ i in u, fderiv_within 𝕜 (A i) s x) := (has_fderiv_within_at.sum (λ i hi, (h i hi).has_fderiv_within_at)).fderiv_within hxs theorem fderiv_sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) : fderiv 𝕜 (λ y, ∑ i in u, A i y) x = (∑ i in u, fderiv 𝕜 (A i) x) := (has_fderiv_at.sum (λ i hi, (h i hi).has_fderiv_at)).fderiv end sum section neg /-! ### Derivative of the negative of a function -/ theorem has_strict_fderiv_at.neg (h : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, -f x) (-f') x := (-1 : F →L[𝕜] F).has_strict_fderiv_at.comp x h theorem has_fderiv_at_filter.neg (h : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (λ x, -f x) (-f') x L := (-1 : F →L[𝕜] F).has_fderiv_at_filter.comp x h theorem has_fderiv_within_at.neg (h : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, -f x) (-f') s x := h.neg theorem has_fderiv_at.neg (h : has_fderiv_at f f' x) : has_fderiv_at (λ x, -f x) (-f') x := h.neg lemma differentiable_within_at.neg (h : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (λy, -f y) s x := h.has_fderiv_within_at.neg.differentiable_within_at @[simp] lemma differentiable_at.neg (h : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (λy, -f y) x := h.has_fderiv_at.neg.differentiable_at lemma differentiable_on.neg (h : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (λy, -f y) s := λx hx, (h x hx).neg @[simp] lemma differentiable.neg (h : differentiable 𝕜 f) : differentiable 𝕜 (λy, -f y) := λx, (h x).neg lemma fderiv_within_neg (hxs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 (λy, -f y) s x = - fderiv_within 𝕜 f s x := h.has_fderiv_within_at.neg.fderiv_within hxs lemma fderiv_neg (h : differentiable_at 𝕜 f x) : fderiv 𝕜 (λy, -f y) x = - fderiv 𝕜 f x := h.has_fderiv_at.neg.fderiv end neg section sub /-! ### Derivative of the difference of two functions -/ theorem has_strict_fderiv_at.sub (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) : has_strict_fderiv_at (λ x, f x - g x) (f' - g') x := hf.add hg.neg theorem has_fderiv_at_filter.sub (hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) : has_fderiv_at_filter (λ x, f x - g x) (f' - g') x L := hf.add hg.neg theorem has_fderiv_within_at.sub (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) : has_fderiv_within_at (λ x, f x - g x) (f' - g') s x := hf.sub hg theorem has_fderiv_at.sub (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) : has_fderiv_at (λ x, f x - g x) (f' - g') x := hf.sub hg lemma differentiable_within_at.sub (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : differentiable_within_at 𝕜 (λ y, f y - g y) s x := (hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : differentiable_at 𝕜 (λ y, f y - g y) x := (hf.has_fderiv_at.sub hg.has_fderiv_at).differentiable_at lemma differentiable_on.sub (hf : differentiable_on 𝕜 f s) (hg : differentiable_on 𝕜 g s) : differentiable_on 𝕜 (λy, f y - g y) s := λx hx, (hf x hx).sub (hg x hx) @[simp] lemma differentiable.sub (hf : differentiable 𝕜 f) (hg : differentiable 𝕜 g) : differentiable 𝕜 (λy, f y - g y) := λx, (hf x).sub (hg x) lemma fderiv_within_sub (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : fderiv_within 𝕜 (λy, f y - g y) s x = fderiv_within 𝕜 f s x - fderiv_within 𝕜 g s x := (hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).fderiv_within hxs lemma fderiv_sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : fderiv 𝕜 (λy, f y - g y) x = fderiv 𝕜 f x - fderiv 𝕜 g x := (hf.has_fderiv_at.sub hg.has_fderiv_at).fderiv theorem has_strict_fderiv_at.sub_const (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ x, f x - c) f' x := hf.add_const (-c) theorem has_fderiv_at_filter.sub_const (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ x, f x - c) f' x L := hf.add_const (-c) theorem has_fderiv_within_at.sub_const (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ x, f x - c) f' s x := hf.sub_const c theorem has_fderiv_at.sub_const (hf : has_fderiv_at f f' x) (c : F) : has_fderiv_at (λ x, f x - c) f' x := hf.sub_const c lemma differentiable_within_at.sub_const (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, f y - c) s x := (hf.has_fderiv_within_at.sub_const c).differentiable_within_at lemma differentiable_at.sub_const (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, f y - c) x := (hf.has_fderiv_at.sub_const c).differentiable_at lemma differentiable_on.sub_const (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, f y - c) s := λx hx, (hf x hx).sub_const c lemma differentiable.sub_const (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, f y - c) := λx, (hf x).sub_const c lemma fderiv_within_sub_const (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : fderiv_within 𝕜 (λy, f y - c) s x = fderiv_within 𝕜 f s x := (hf.has_fderiv_within_at.sub_const c).fderiv_within hxs lemma fderiv_sub_const (hf : differentiable_at 𝕜 f x) (c : F) : fderiv 𝕜 (λy, f y - c) x = fderiv 𝕜 f x := (hf.has_fderiv_at.sub_const c).fderiv theorem has_strict_fderiv_at.const_sub (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ x, c - f x) (-f') x := hf.neg.const_add c theorem has_fderiv_at_filter.const_sub (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ x, c - f x) (-f') x L := hf.neg.const_add c theorem has_fderiv_within_at.const_sub (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ x, c - f x) (-f') s x := hf.const_sub c theorem has_fderiv_at.const_sub (hf : has_fderiv_at f f' x) (c : F) : has_fderiv_at (λ x, c - f x) (-f') x := hf.const_sub c lemma differentiable_within_at.const_sub (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, c - f y) s x := (hf.has_fderiv_within_at.const_sub c).differentiable_within_at lemma differentiable_at.const_sub (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, c - f y) x := (hf.has_fderiv_at.const_sub c).differentiable_at lemma differentiable_on.const_sub (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, c - f y) s := λx hx, (hf x hx).const_sub c lemma differentiable.const_sub (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, c - f y) := λx, (hf x).const_sub c lemma fderiv_within_const_sub (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : fderiv_within 𝕜 (λy, c - f y) s x = -fderiv_within 𝕜 f s x := (hf.has_fderiv_within_at.const_sub c).fderiv_within hxs lemma fderiv_const_sub (hf : differentiable_at 𝕜 f x) (c : F) : fderiv 𝕜 (λy, c - f y) x = -fderiv 𝕜 f x := (hf.has_fderiv_at.const_sub c).fderiv end sub section bilinear_map /-! ### Derivative of a bounded bilinear map -/ variables {b : E × F → G} {u : set (E × F) } open normed_field lemma is_bounded_bilinear_map.has_strict_fderiv_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_strict_fderiv_at b (h.deriv p) p := begin rw has_strict_fderiv_at, set T := (E × F) × (E × F), have : is_o (λ q : T, b (q.1 - q.2)) (λ q : T, ∥q.1 - q.2∥ * 1) (𝓝 (p, p)), { refine (h.is_O'.comp_tendsto le_top).trans_is_o _, simp only [(∘)], refine (is_O_refl (λ q : T, ∥q.1 - q.2∥) _).mul_is_o (is_o.norm_left $ (is_o_one_iff _).2 _), rw [← sub_self p], exact continuous_at_fst.sub continuous_at_snd }, simp only [mul_one, is_o_norm_right] at this, refine (is_o.congr_of_sub _).1 this, clear this, convert_to is_o (λ q : T, h.deriv (p - q.2) (q.1 - q.2)) (λ q : T, q.1 - q.2) (𝓝 (p, p)), { ext ⟨⟨x₁, y₁⟩, ⟨x₂, y₂⟩⟩, rcases p with ⟨x, y⟩, simp only [is_bounded_bilinear_map_deriv_coe, prod.mk_sub_mk, h.map_sub_left, h.map_sub_right], abel }, have : is_o (λ q : T, p - q.2) (λ q, (1:ℝ)) (𝓝 (p, p)), from (is_o_one_iff _).2 (sub_self p ▸ tendsto_const_nhds.sub continuous_at_snd), apply is_bounded_bilinear_map_apply.is_O_comp.trans_is_o, refine is_o.trans_is_O _ (is_O_const_mul_self 1 _ _).of_norm_right, refine is_o.mul_is_O _ (is_O_refl _ _), exact (((h.is_bounded_linear_map_deriv.is_O_id ⊤).comp_tendsto le_top : _).trans_is_o this).norm_left end lemma is_bounded_bilinear_map.has_fderiv_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_fderiv_at b (h.deriv p) p := (h.has_strict_fderiv_at p).has_fderiv_at lemma is_bounded_bilinear_map.has_fderiv_within_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_fderiv_within_at b (h.deriv p) u p := (h.has_fderiv_at p).has_fderiv_within_at lemma is_bounded_bilinear_map.differentiable_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : differentiable_at 𝕜 b p := (h.has_fderiv_at p).differentiable_at lemma is_bounded_bilinear_map.differentiable_within_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : differentiable_within_at 𝕜 b u p := (h.differentiable_at p).differentiable_within_at lemma is_bounded_bilinear_map.fderiv (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : fderiv 𝕜 b p = h.deriv p := has_fderiv_at.fderiv (h.has_fderiv_at p) lemma is_bounded_bilinear_map.fderiv_within (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) (hxs : unique_diff_within_at 𝕜 u p) : fderiv_within 𝕜 b u p = h.deriv p := begin rw differentiable_at.fderiv_within (h.differentiable_at p) hxs, exact h.fderiv p end lemma is_bounded_bilinear_map.differentiable (h : is_bounded_bilinear_map 𝕜 b) : differentiable 𝕜 b := λx, h.differentiable_at x lemma is_bounded_bilinear_map.differentiable_on (h : is_bounded_bilinear_map 𝕜 b) : differentiable_on 𝕜 b u := h.differentiable.differentiable_on lemma is_bounded_bilinear_map.continuous (h : is_bounded_bilinear_map 𝕜 b) : continuous b := h.differentiable.continuous lemma is_bounded_bilinear_map.continuous_left (h : is_bounded_bilinear_map 𝕜 b) {f : F} : continuous (λe, b (e, f)) := h.continuous.comp (continuous_id.prod_mk continuous_const) lemma is_bounded_bilinear_map.continuous_right (h : is_bounded_bilinear_map 𝕜 b) {e : E} : continuous (λf, b (e, f)) := h.continuous.comp (continuous_const.prod_mk continuous_id) end bilinear_map section smul /-! ### Derivative of the product of a scalar-valued function and a vector-valued function -/ variables {c : E → 𝕜} {c' : E →L[𝕜] 𝕜} theorem has_strict_fderiv_at.smul (hc : has_strict_fderiv_at c c' x) (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) x := (is_bounded_bilinear_map_smul.has_strict_fderiv_at (c x, f x)).comp x $ hc.prod hf theorem has_fderiv_within_at.smul (hc : has_fderiv_within_at c c' s x) (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) s x := (is_bounded_bilinear_map_smul.has_fderiv_at (c x, f x)).comp_has_fderiv_within_at x $ hc.prod hf theorem has_fderiv_at.smul (hc : has_fderiv_at c c' x) (hf : has_fderiv_at f f' x) : has_fderiv_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) x := (is_bounded_bilinear_map_smul.has_fderiv_at (c x, f x)).comp x $ hc.prod hf lemma differentiable_within_at.smul (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (λ y, c y • f y) s x := (hc.has_fderiv_within_at.smul hf.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (λ y, c y • f y) x := (hc.has_fderiv_at.smul hf.has_fderiv_at).differentiable_at lemma differentiable_on.smul (hc : differentiable_on 𝕜 c s) (hf : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (λ y, c y • f y) s := λx hx, (hc x hx).smul (hf x hx) @[simp] lemma differentiable.smul (hc : differentiable 𝕜 c) (hf : differentiable 𝕜 f) : differentiable 𝕜 (λ y, c y • f y) := λx, (hc x).smul (hf x) lemma fderiv_within_smul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 (λ y, c y • f y) s x = c x • fderiv_within 𝕜 f s x + (fderiv_within 𝕜 c s x).smul_right (f x) := (hc.has_fderiv_within_at.smul hf.has_fderiv_within_at).fderiv_within hxs lemma fderiv_smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : fderiv 𝕜 (λ y, c y • f y) x = c x • fderiv 𝕜 f x + (fderiv 𝕜 c x).smul_right (f x) := (hc.has_fderiv_at.smul hf.has_fderiv_at).fderiv theorem has_strict_fderiv_at.smul_const (hc : has_strict_fderiv_at c c' x) (f : F) : has_strict_fderiv_at (λ y, c y • f) (c'.smul_right f) x := by simpa only [smul_zero, zero_add] using hc.smul (has_strict_fderiv_at_const f x) theorem has_fderiv_within_at.smul_const (hc : has_fderiv_within_at c c' s x) (f : F) : has_fderiv_within_at (λ y, c y • f) (c'.smul_right f) s x := by simpa only [smul_zero, zero_add] using hc.smul (has_fderiv_within_at_const f x s) theorem has_fderiv_at.smul_const (hc : has_fderiv_at c c' x) (f : F) : has_fderiv_at (λ y, c y • f) (c'.smul_right f) x := by simpa only [smul_zero, zero_add] using hc.smul (has_fderiv_at_const f x) lemma differentiable_within_at.smul_const (hc : differentiable_within_at 𝕜 c s x) (f : F) : differentiable_within_at 𝕜 (λ y, c y • f) s x := (hc.has_fderiv_within_at.smul_const f).differentiable_within_at lemma differentiable_at.smul_const (hc : differentiable_at 𝕜 c x) (f : F) : differentiable_at 𝕜 (λ y, c y • f) x := (hc.has_fderiv_at.smul_const f).differentiable_at lemma differentiable_on.smul_const (hc : differentiable_on 𝕜 c s) (f : F) : differentiable_on 𝕜 (λ y, c y • f) s := λx hx, (hc x hx).smul_const f lemma differentiable.smul_const (hc : differentiable 𝕜 c) (f : F) : differentiable 𝕜 (λ y, c y • f) := λx, (hc x).smul_const f lemma fderiv_within_smul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (f : F) : fderiv_within 𝕜 (λ y, c y • f) s x = (fderiv_within 𝕜 c s x).smul_right f := (hc.has_fderiv_within_at.smul_const f).fderiv_within hxs lemma fderiv_smul_const (hc : differentiable_at 𝕜 c x) (f : F) : fderiv 𝕜 (λ y, c y • f) x = (fderiv 𝕜 c x).smul_right f := (hc.has_fderiv_at.smul_const f).fderiv end smul section mul /-! ### Derivative of the product of two scalar-valued functions -/ variables {c d : E → 𝕜} {c' d' : E →L[𝕜] 𝕜} theorem has_strict_fderiv_at.mul (hc : has_strict_fderiv_at c c' x) (hd : has_strict_fderiv_at d d' x) : has_strict_fderiv_at (λ y, c y * d y) (c x • d' + d x • c') x := by { convert hc.smul hd, ext z, apply mul_comm } theorem has_fderiv_within_at.mul (hc : has_fderiv_within_at c c' s x) (hd : has_fderiv_within_at d d' s x) : has_fderiv_within_at (λ y, c y * d y) (c x • d' + d x • c') s x := by { convert hc.smul hd, ext z, apply mul_comm } theorem has_fderiv_at.mul (hc : has_fderiv_at c c' x) (hd : has_fderiv_at d d' x) : has_fderiv_at (λ y, c y * d y) (c x • d' + d x • c') x := by { convert hc.smul hd, ext z, apply mul_comm } lemma differentiable_within_at.mul (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : differentiable_within_at 𝕜 (λ y, c y * d y) s x := (hc.has_fderiv_within_at.mul hd.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : differentiable_at 𝕜 (λ y, c y * d y) x := (hc.has_fderiv_at.mul hd.has_fderiv_at).differentiable_at lemma differentiable_on.mul (hc : differentiable_on 𝕜 c s) (hd : differentiable_on 𝕜 d s) : differentiable_on 𝕜 (λ y, c y * d y) s := λx hx, (hc x hx).mul (hd x hx) @[simp] lemma differentiable.mul (hc : differentiable 𝕜 c) (hd : differentiable 𝕜 d) : differentiable 𝕜 (λ y, c y * d y) := λx, (hc x).mul (hd x) lemma fderiv_within_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : fderiv_within 𝕜 (λ y, c y * d y) s x = c x • fderiv_within 𝕜 d s x + d x • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.mul hd.has_fderiv_within_at).fderiv_within hxs lemma fderiv_mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : fderiv 𝕜 (λ y, c y * d y) x = c x • fderiv 𝕜 d x + d x • fderiv 𝕜 c x := (hc.has_fderiv_at.mul hd.has_fderiv_at).fderiv theorem has_strict_fderiv_at.mul_const (hc : has_strict_fderiv_at c c' x) (d : 𝕜) : has_strict_fderiv_at (λ y, c y * d) (d • c') x := by simpa only [smul_zero, zero_add] using hc.mul (has_strict_fderiv_at_const d x) theorem has_fderiv_within_at.mul_const (hc : has_fderiv_within_at c c' s x) (d : 𝕜) : has_fderiv_within_at (λ y, c y * d) (d • c') s x := by simpa only [smul_zero, zero_add] using hc.mul (has_fderiv_within_at_const d x s) theorem has_fderiv_at.mul_const (hc : has_fderiv_at c c' x) (d : 𝕜) : has_fderiv_at (λ y, c y * d) (d • c') x := begin rw [← has_fderiv_within_at_univ] at *, exact hc.mul_const d end lemma differentiable_within_at.mul_const (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : differentiable_within_at 𝕜 (λ y, c y * d) s x := (hc.has_fderiv_within_at.mul_const d).differentiable_within_at lemma differentiable_at.mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) : differentiable_at 𝕜 (λ y, c y * d) x := (hc.has_fderiv_at.mul_const d).differentiable_at lemma differentiable_on.mul_const (hc : differentiable_on 𝕜 c s) (d : 𝕜) : differentiable_on 𝕜 (λ y, c y * d) s := λx hx, (hc x hx).mul_const d lemma differentiable.mul_const (hc : differentiable 𝕜 c) (d : 𝕜) : differentiable 𝕜 (λ y, c y * d) := λx, (hc x).mul_const d lemma fderiv_within_mul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : fderiv_within 𝕜 (λ y, c y * d) s x = d • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.mul_const d).fderiv_within hxs lemma fderiv_mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) : fderiv 𝕜 (λ y, c y * d) x = d • fderiv 𝕜 c x := (hc.has_fderiv_at.mul_const d).fderiv theorem has_strict_fderiv_at.const_mul (hc : has_strict_fderiv_at c c' x) (d : 𝕜) : has_strict_fderiv_at (λ y, d * c y) (d • c') x := begin simp only [mul_comm d], exact hc.mul_const d, end theorem has_fderiv_within_at.const_mul (hc : has_fderiv_within_at c c' s x) (d : 𝕜) : has_fderiv_within_at (λ y, d * c y) (d • c') s x := begin simp only [mul_comm d], exact hc.mul_const d, end theorem has_fderiv_at.const_mul (hc : has_fderiv_at c c' x) (d : 𝕜) : has_fderiv_at (λ y, d * c y) (d • c') x := begin simp only [mul_comm d], exact hc.mul_const d, end lemma differentiable_within_at.const_mul (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : differentiable_within_at 𝕜 (λ y, d * c y) s x := (hc.has_fderiv_within_at.const_mul d).differentiable_within_at lemma differentiable_at.const_mul (hc : differentiable_at 𝕜 c x) (d : 𝕜) : differentiable_at 𝕜 (λ y, d * c y) x := (hc.has_fderiv_at.const_mul d).differentiable_at lemma differentiable_on.const_mul (hc : differentiable_on 𝕜 c s) (d : 𝕜) : differentiable_on 𝕜 (λ y, d * c y) s := λx hx, (hc x hx).const_mul d lemma differentiable.const_mul (hc : differentiable 𝕜 c) (d : 𝕜) : differentiable 𝕜 (λ y, d * c y) := λx, (hc x).const_mul d lemma fderiv_within_const_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : fderiv_within 𝕜 (λ y, d * c y) s x = d • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.const_mul d).fderiv_within hxs lemma fderiv_const_mul (hc : differentiable_at 𝕜 c x) (d : 𝕜) : fderiv 𝕜 (λ y, d * c y) x = d • fderiv 𝕜 c x := (hc.has_fderiv_at.const_mul d).fderiv end mul section continuous_linear_equiv /-! ### Differentiability of linear equivs, and invariance of differentiability -/ variable (iso : E ≃L[𝕜] F) protected lemma continuous_linear_equiv.has_strict_fderiv_at : has_strict_fderiv_at iso (iso : E →L[𝕜] F) x := iso.to_continuous_linear_map.has_strict_fderiv_at protected lemma continuous_linear_equiv.has_fderiv_within_at : has_fderiv_within_at iso (iso : E →L[𝕜] F) s x := iso.to_continuous_linear_map.has_fderiv_within_at protected lemma continuous_linear_equiv.has_fderiv_at : has_fderiv_at iso (iso : E →L[𝕜] F) x := iso.to_continuous_linear_map.has_fderiv_at_filter protected lemma continuous_linear_equiv.differentiable_at : differentiable_at 𝕜 iso x := iso.has_fderiv_at.differentiable_at protected lemma continuous_linear_equiv.differentiable_within_at : differentiable_within_at 𝕜 iso s x := iso.differentiable_at.differentiable_within_at protected lemma continuous_linear_equiv.fderiv : fderiv 𝕜 iso x = iso := iso.has_fderiv_at.fderiv protected lemma continuous_linear_equiv.fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 iso s x = iso := iso.to_continuous_linear_map.fderiv_within hxs protected lemma continuous_linear_equiv.differentiable : differentiable 𝕜 iso := λx, iso.differentiable_at protected lemma continuous_linear_equiv.differentiable_on : differentiable_on 𝕜 iso s := iso.differentiable.differentiable_on lemma continuous_linear_equiv.comp_differentiable_within_at_iff {f : G → E} {s : set G} {x : G} : differentiable_within_at 𝕜 (iso ∘ f) s x ↔ differentiable_within_at 𝕜 f s x := begin refine ⟨λ H, _, λ H, iso.differentiable.differentiable_at.comp_differentiable_within_at x H⟩, have : differentiable_within_at 𝕜 (iso.symm ∘ (iso ∘ f)) s x := iso.symm.differentiable.differentiable_at.comp_differentiable_within_at x H, rwa [← function.comp.assoc iso.symm iso f, iso.symm_comp_self] at this, end lemma continuous_linear_equiv.comp_differentiable_at_iff {f : G → E} {x : G} : differentiable_at 𝕜 (iso ∘ f) x ↔ differentiable_at 𝕜 f x := by rw [← differentiable_within_at_univ, ← differentiable_within_at_univ, iso.comp_differentiable_within_at_iff] lemma continuous_linear_equiv.comp_differentiable_on_iff {f : G → E} {s : set G} : differentiable_on 𝕜 (iso ∘ f) s ↔ differentiable_on 𝕜 f s := begin rw [differentiable_on, differentiable_on], simp only [iso.comp_differentiable_within_at_iff], end lemma continuous_linear_equiv.comp_differentiable_iff {f : G → E} : differentiable 𝕜 (iso ∘ f) ↔ differentiable 𝕜 f := begin rw [← differentiable_on_univ, ← differentiable_on_univ], exact iso.comp_differentiable_on_iff end lemma continuous_linear_equiv.comp_has_fderiv_within_at_iff {f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] E} : has_fderiv_within_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') s x ↔ has_fderiv_within_at f f' s x := begin refine ⟨λ H, _, λ H, iso.has_fderiv_at.comp_has_fderiv_within_at x H⟩, have A : f = iso.symm ∘ (iso ∘ f), by { rw [← function.comp.assoc, iso.symm_comp_self], refl }, have B : f' = (iso.symm : F →L[𝕜] E).comp ((iso : E →L[𝕜] F).comp f'), by rw [← continuous_linear_map.comp_assoc, iso.coe_symm_comp_coe, continuous_linear_map.id_comp], rw [A, B], exact iso.symm.has_fderiv_at.comp_has_fderiv_within_at x H end lemma continuous_linear_equiv.comp_has_strict_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} : has_strict_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_strict_fderiv_at f f' x := begin refine ⟨λ H, _, λ H, iso.has_strict_fderiv_at.comp x H⟩, convert iso.symm.has_strict_fderiv_at.comp x H; ext z; apply (iso.symm_apply_apply _).symm end lemma continuous_linear_equiv.comp_has_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} : has_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_fderiv_at f f' x := by rw [← has_fderiv_within_at_univ, ← has_fderiv_within_at_univ, iso.comp_has_fderiv_within_at_iff] lemma continuous_linear_equiv.comp_has_fderiv_within_at_iff' {f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] F} : has_fderiv_within_at (iso ∘ f) f' s x ↔ has_fderiv_within_at f ((iso.symm : F →L[𝕜] E).comp f') s x := by rw [← iso.comp_has_fderiv_within_at_iff, ← continuous_linear_map.comp_assoc, iso.coe_comp_coe_symm, continuous_linear_map.id_comp] lemma continuous_linear_equiv.comp_has_fderiv_at_iff' {f : G → E} {x : G} {f' : G →L[𝕜] F} : has_fderiv_at (iso ∘ f) f' x ↔ has_fderiv_at f ((iso.symm : F →L[𝕜] E).comp f') x := by rw [← has_fderiv_within_at_univ, ← has_fderiv_within_at_univ, iso.comp_has_fderiv_within_at_iff'] lemma continuous_linear_equiv.comp_fderiv_within {f : G → E} {s : set G} {x : G} (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (iso ∘ f) s x = (iso : E →L[𝕜] F).comp (fderiv_within 𝕜 f s x) := begin by_cases h : differentiable_within_at 𝕜 f s x, { rw [fderiv.comp_fderiv_within x iso.differentiable_at h hxs, iso.fderiv] }, { have : ¬differentiable_within_at 𝕜 (iso ∘ f) s x, from mt iso.comp_differentiable_within_at_iff.1 h, rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at this, continuous_linear_map.comp_zero] } end lemma continuous_linear_equiv.comp_fderiv {f : G → E} {x : G} : fderiv 𝕜 (iso ∘ f) x = (iso : E →L[𝕜] F).comp (fderiv 𝕜 f x) := begin rw [← fderiv_within_univ, ← fderiv_within_univ], exact iso.comp_fderiv_within unique_diff_within_at_univ, end end continuous_linear_equiv /-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an invertible derivative `f'` at `g a` in the strict sense, then `g` has the derivative `f'⁻¹` at `a` in the strict sense. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem has_strict_fderiv_at.of_local_left_inverse {f : E → F} {f' : E ≃L[𝕜] F} {g : F → E} {a : F} (hg : continuous_at g a) (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) (g a)) (hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) : has_strict_fderiv_at g (f'.symm : F →L[𝕜] E) a := begin replace hg := hg.prod_map' hg, replace hfg := hfg.prod_mk_nhds hfg, have : is_O (λ p : F × F, g p.1 - g p.2 - f'.symm (p.1 - p.2)) (λ p : F × F, f' (g p.1 - g p.2) - (p.1 - p.2)) (𝓝 (a, a)), { refine ((f'.symm : F →L[𝕜] E).is_O_comp _ _).congr (λ x, _) (λ _, rfl), simp }, refine this.trans_is_o _, clear this, refine ((hf.comp_tendsto hg).symm.congr' (hfg.mono _) (eventually_of_forall $ λ _, rfl)).trans_is_O _, { rintros p ⟨hp1, hp2⟩, simp [hp1, hp2] }, { refine (hf.is_O_sub_rev.comp_tendsto hg).congr' (eventually_of_forall $ λ _, rfl) (hfg.mono _), rintros p ⟨hp1, hp2⟩, simp only [(∘), hp1, hp2] } end /-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an invertible derivative `f'` at `g a`, then `g` has the derivative `f'⁻¹` at `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem has_fderiv_at.of_local_left_inverse {f : E → F} {f' : E ≃L[𝕜] F} {g : F → E} {a : F} (hg : continuous_at g a) (hf : has_fderiv_at f (f' : E →L[𝕜] F) (g a)) (hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) : has_fderiv_at g (f'.symm : F →L[𝕜] E) a := begin have : is_O (λ x : F, g x - g a - f'.symm (x - a)) (λ x : F, f' (g x - g a) - (x - a)) (𝓝 a), { refine ((f'.symm : F →L[𝕜] E).is_O_comp _ _).congr (λ x, _) (λ _, rfl), simp }, refine this.trans_is_o _, clear this, refine ((hf.comp_tendsto hg).symm.congr' (hfg.mono _) (eventually_of_forall $ λ _, rfl)).trans_is_O _, { rintros p hp, simp [hp, hfg.self_of_nhds] }, { refine (hf.is_O_sub_rev.comp_tendsto hg).congr' (eventually_of_forall $ λ _, rfl) (hfg.mono _), rintros p hp, simp only [(∘), hp, hfg.self_of_nhds] } end end section /- In the special case of a normed space over the reals, we can use scalar multiplication in the `tendsto` characterization of the Fréchet derivative. -/ variables {E : Type*} [normed_group E] [normed_space ℝ E] variables {F : Type*} [normed_group F] [normed_space ℝ F] variables {f : E → F} {f' : E →L[ℝ] F} {x : E} theorem has_fderiv_at_filter_real_equiv {L : filter E} : tendsto (λ x' : E, ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (𝓝 0) ↔ tendsto (λ x' : E, ∥x' - x∥⁻¹ • (f x' - f x - f' (x' - x))) L (𝓝 0) := begin symmetry, rw [tendsto_iff_norm_tendsto_zero], refine tendsto_congr (λ x', _), have : ∥x' - x∥⁻¹ ≥ 0, from inv_nonneg.mpr (norm_nonneg _), simp [norm_smul, real.norm_eq_abs, abs_of_nonneg this] end lemma has_fderiv_at.lim_real (hf : has_fderiv_at f f' x) (v : E) : tendsto (λ (c:ℝ), c • (f (x + c⁻¹ • v) - f x)) at_top (𝓝 (f' v)) := begin apply hf.lim v, rw tendsto_at_top_at_top, exact λ b, ⟨b, λ a ha, le_trans ha (le_abs_self _)⟩ end end section tangent_cone variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {f : E → F} {s : set E} {f' : E →L[𝕜] F} /-- The image of a tangent cone under the differential of a map is included in the tangent cone to the image. -/ lemma has_fderiv_within_at.maps_to_tangent_cone {x : E} (h : has_fderiv_within_at f f' s x) : maps_to f' (tangent_cone_at 𝕜 s x) (tangent_cone_at 𝕜 (f '' s) (f x)) := begin rintros v ⟨c, d, dtop, clim, cdlim⟩, refine ⟨c, (λn, f (x + d n) - f x), mem_sets_of_superset dtop _, clim, h.lim at_top dtop clim cdlim⟩, simp [-mem_image, mem_image_of_mem] {contextual := tt} end /-- If a set has the unique differentiability property at a point x, then the image of this set under a map with onto derivative has also the unique differentiability property at the image point. -/ lemma has_fderiv_within_at.unique_diff_within_at {x : E} (h : has_fderiv_within_at f f' s x) (hs : unique_diff_within_at 𝕜 s x) (h' : closure (range f') = univ) : unique_diff_within_at 𝕜 (f '' s) (f x) := begin have B : ∀v ∈ (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E), f' v ∈ (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x)) : set F), { assume v hv, apply submodule.span_induction hv, { exact λ w hw, submodule.subset_span (h.maps_to_tangent_cone hw) }, { simp }, { assume w₁ w₂ hw₁ hw₂, rw continuous_linear_map.map_add, exact submodule.add_mem (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x))) hw₁ hw₂ }, { assume a w hw, rw continuous_linear_map.map_smul, exact submodule.smul_mem (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x))) _ hw } }, rw [unique_diff_within_at, ← univ_subset_iff], split, show f x ∈ closure (f '' s), from h.continuous_within_at.mem_closure_image hs.2, show univ ⊆ closure ↑(submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x))), from calc univ ⊆ closure (range f') : univ_subset_iff.2 h' ... = closure (f' '' univ) : by rw image_univ ... = closure (f' '' (closure (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E))) : by rw hs.1 ... ⊆ closure (closure (f' '' (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E))) : closure_mono (image_closure_subset_closure_image f'.cont) ... = closure (f' '' (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E)) : closure_closure ... ⊆ closure (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x)) : set F) : closure_mono (image_subset_iff.mpr B) end lemma has_fderiv_within_at.unique_diff_within_at_of_continuous_linear_equiv {x : E} (e' : E ≃L[𝕜] F) (h : has_fderiv_within_at f (e' : E →L[𝕜] F) s x) (hs : unique_diff_within_at 𝕜 s x) : unique_diff_within_at 𝕜 (f '' s) (f x) := begin apply h.unique_diff_within_at hs, have : set.range (e' : E →L[𝕜] F) = univ := e'.to_linear_equiv.to_equiv.range_eq_univ, rw [this, closure_univ] end lemma continuous_linear_equiv.unique_diff_on_preimage_iff (e : F ≃L[𝕜] E) : unique_diff_on 𝕜 (e ⁻¹' s) ↔ unique_diff_on 𝕜 s := begin split, { assume hs x hx, have A : s = e '' (e.symm '' s) := (equiv.symm_image_image (e.symm.to_linear_equiv.to_equiv) s).symm, have B : e.symm '' s = e⁻¹' s := equiv.image_eq_preimage e.symm.to_linear_equiv.to_equiv s, rw [A, B, (e.apply_symm_apply x).symm], refine has_fderiv_within_at.unique_diff_within_at_of_continuous_linear_equiv e e.has_fderiv_within_at (hs _ _), rwa [mem_preimage, e.apply_symm_apply x] }, { assume hs x hx, have : e ⁻¹' s = e.symm '' s := (equiv.image_eq_preimage e.symm.to_linear_equiv.to_equiv s).symm, rw [this, (e.symm_apply_apply x).symm], exact has_fderiv_within_at.unique_diff_within_at_of_continuous_linear_equiv e.symm e.symm.has_fderiv_within_at (hs _ hx) }, end end tangent_cone section restrict_scalars /-! ### Restricting from `ℂ` to `ℝ`, or generally from `𝕜'` to `𝕜` If a function is differentiable over `ℂ`, then it is differentiable over `ℝ`. In this paragraph, we give variants of this statement, in the general situation where `ℂ` and `ℝ` are replaced respectively by `𝕜'` and `𝕜` where `𝕜'` is a normed algebra over `𝕜`. -/ variables (𝕜 : Type*) [nondiscrete_normed_field 𝕜] {𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] {E : Type*} [normed_group E] [normed_space 𝕜' E] {F : Type*} [normed_group F] [normed_space 𝕜' F] {f : E → F} {f' : E →L[𝕜'] F} {s : set E} {x : E} local attribute [instance] normed_space.restrict_scalars lemma has_strict_fderiv_at.restrict_scalars (h : has_strict_fderiv_at f f' x) : has_strict_fderiv_at f (f'.restrict_scalars 𝕜) x := h lemma has_fderiv_at.restrict_scalars (h : has_fderiv_at f f' x) : has_fderiv_at f (f'.restrict_scalars 𝕜) x := h lemma has_fderiv_within_at.restrict_scalars (h : has_fderiv_within_at f f' s x) : has_fderiv_within_at f (f'.restrict_scalars 𝕜) s x := h lemma differentiable_at.restrict_scalars (h : differentiable_at 𝕜' f x) : differentiable_at 𝕜 f x := (h.has_fderiv_at.restrict_scalars 𝕜).differentiable_at lemma differentiable_within_at.restrict_scalars (h : differentiable_within_at 𝕜' f s x) : differentiable_within_at 𝕜 f s x := (h.has_fderiv_within_at.restrict_scalars 𝕜).differentiable_within_at lemma differentiable_on.restrict_scalars (h : differentiable_on 𝕜' f s) : differentiable_on 𝕜 f s := λx hx, (h x hx).restrict_scalars 𝕜 lemma differentiable.restrict_scalars (h : differentiable 𝕜' f) : differentiable 𝕜 f := λx, (h x).restrict_scalars 𝕜 end restrict_scalars
4086bdf15db44bba7b0ad475e981afe3a40b3da9
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/order/ideal.lean
2df691ebcecde288019a7bb5370e65c13ac0fbe4
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
19,379
lean
/- Copyright (c) 2020 David Wärn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Wärn -/ import data.equiv.encodable.basic import order.atoms /-! # Order ideals, cofinal sets, and the Rasiowa–Sikorski lemma ## Main definitions Throughout this file, `P` is at least a preorder, but some sections require more structure, such as a bottom element, a top element, or a join-semilattice structure. - `order.ideal P`: the type of nonempty, upward directed, and downward closed subsets of `P`. Dual to the notion of a filter on a preorder. - `order.is_ideal P`: a predicate for when a `set P` is an ideal. - `order.ideal.principal p`: the principal ideal generated by `p : P`. - `order.ideal.is_proper P`: a predicate for proper ideals. Dual to the notion of a proper filter. - `order.ideal.is_maximal`: a predicate for maximal ideals. Dual to the notion of an ultrafilter. - `ideal_inter_nonempty P`: a predicate for when the intersection of any two ideals of `P` is nonempty. - `ideal_Inter_nonempty P`: a predicate for when the intersection of all ideals of `P` is nonempty. - `order.cofinal P`: the type of subsets of `P` containing arbitrarily large elements. Dual to the notion of 'dense set' used in forcing. - `order.ideal_of_cofinals p 𝒟`, where `p : P`, and `𝒟` is a countable family of cofinal subsets of P: an ideal in `P` which contains `p` and intersects every set in `𝒟`. (This a form of the Rasiowa–Sikorski lemma.) ## References - <https://en.wikipedia.org/wiki/Ideal_(order_theory)> - <https://en.wikipedia.org/wiki/Cofinal_(mathematics)> - <https://en.wikipedia.org/wiki/Rasiowa%E2%80%93Sikorski_lemma> Note that for the Rasiowa–Sikorski lemma, Wikipedia uses the opposite ordering on `P`, in line with most presentations of forcing. ## Tags ideal, cofinal, dense, countable, generic -/ namespace order variables {P : Type*} /-- An ideal on a preorder `P` is a subset of `P` that is - nonempty - upward directed (any pair of elements in the ideal has an upper bound in the ideal) - downward closed (any element less than an element of the ideal is in the ideal). -/ structure ideal (P) [preorder P] := (carrier : set P) (nonempty : carrier.nonempty) (directed : directed_on (≤) carrier) (mem_of_le : ∀ {x y : P}, x ≤ y → y ∈ carrier → x ∈ carrier) /-- A subset of a preorder `P` is an ideal if it is - nonempty - upward directed (any pair of elements in the ideal has an upper bound in the ideal) - downward closed (any element less than an element of the ideal is in the ideal). -/ @[mk_iff] structure is_ideal {P} [preorder P] (I : set P) : Prop := (nonempty : I.nonempty) (directed : directed_on (≤) I) (mem_of_le : ∀ {x y : P}, x ≤ y → y ∈ I → x ∈ I) /-- Create an element of type `order.ideal` from a set satisfying the predicate `order.is_ideal`. -/ def is_ideal.to_ideal [preorder P] {I : set P} (h : is_ideal I) : ideal P := ⟨I, h.1, h.2, h.3⟩ namespace ideal section preorder variables [preorder P] {x y : P} {I J : ideal P} /-- The smallest ideal containing a given element. -/ def principal (p : P) : ideal P := { carrier := { x | x ≤ p }, nonempty := ⟨p, le_refl _⟩, directed := λ x hx y hy, ⟨p, le_refl _, hx, hy⟩, mem_of_le := λ x y hxy hy, le_trans hxy hy, } instance [inhabited P] : inhabited (ideal P) := ⟨ideal.principal $ default P⟩ /-- An ideal of `P` can be viewed as a subset of `P`. -/ instance : has_coe (ideal P) (set P) := ⟨carrier⟩ /-- For the notation `x ∈ I`. -/ instance : has_mem P (ideal P) := ⟨λ x I, x ∈ (I : set P)⟩ @[simp] lemma mem_coe : x ∈ (I : set P) ↔ x ∈ I := iff_of_eq rfl @[simp] lemma mem_principal : x ∈ principal y ↔ x ≤ y := by refl /-- Two ideals are equal when their underlying sets are equal. -/ @[ext] lemma ext : ∀ (I J : ideal P), (I : set P) = J → I = J | ⟨_, _, _, _⟩ ⟨_, _, _, _⟩ rfl := rfl @[simp, norm_cast] lemma ext_set_eq {I J : ideal P} : (I : set P) = J ↔ I = J := ⟨by ext, congr_arg _⟩ lemma ext'_iff {I J : ideal P} : I = J ↔ (I : set P) = J := ext_set_eq.symm lemma is_ideal (I : ideal P) : is_ideal (I : set P) := ⟨I.2, I.3, I.4⟩ /-- The partial ordering by subset inclusion, inherited from `set P`. -/ instance : partial_order (ideal P) := partial_order.lift coe ext @[trans] lemma mem_of_mem_of_le : x ∈ I → I ≤ J → x ∈ J := @set.mem_of_mem_of_subset P x I J @[simp] lemma principal_le_iff : principal x ≤ I ↔ x ∈ I := ⟨λ (h : ∀ {y}, y ≤ x → y ∈ I), h (le_refl x), λ h_mem y (h_le : y ≤ x), I.mem_of_le h_le h_mem⟩ lemma mem_compl_of_ge {x y : P} : x ≤ y → x ∈ (I : set P)ᶜ → y ∈ (I : set P)ᶜ := λ h, mt (I.mem_of_le h) /-- A proper ideal is one that is not the whole set. Note that the whole set might not be an ideal. -/ @[mk_iff] class is_proper (I : ideal P) : Prop := (ne_univ : (I : set P) ≠ set.univ) lemma is_proper_of_not_mem {I : ideal P} {p : P} (nmem : p ∉ I) : is_proper I := ⟨λ hp, begin change p ∉ ↑I at nmem, rw hp at nmem, exact nmem (set.mem_univ p), end⟩ /-- An ideal is maximal if it is maximal in the collection of proper ideals. Note that we cannot use the `is_coatom` class because `P` might not have a `top` element. -/ @[mk_iff] class is_maximal (I : ideal P) extends is_proper I : Prop := (maximal_proper : ∀ ⦃J : ideal P⦄, I < J → (J : set P) = set.univ) variable (P) /-- A preorder `P` has the `ideal_inter_nonempty` property if the intersection of any two ideals is nonempty. Most importantly, a `semilattice_sup` preorder with this property satisfies that its ideal poset is a lattice. -/ class ideal_inter_nonempty : Prop := (inter_nonempty : ∀ (I J : ideal P), ((I : set P) ∩ (J : set P)).nonempty) /-- A preorder `P` has the `ideal_Inter_nonempty` property if the intersection of all ideals is nonempty. Most importantly, a `semilattice_sup` preorder with this property satisfies that its ideal poset is a complete lattice. -/ class ideal_Inter_nonempty : Prop := (Inter_nonempty : (⋂ (I : ideal P), (I : set P)).nonempty) variable {P} lemma inter_nonempty [ideal_inter_nonempty P] : ∀ (I J : ideal P), ((I : set P) ∩ (J : set P)).nonempty := ideal_inter_nonempty.inter_nonempty lemma Inter_nonempty [ideal_Inter_nonempty P] : (⋂ (I : ideal P), (I : set P)).nonempty := ideal_Inter_nonempty.Inter_nonempty lemma ideal_Inter_nonempty.exists_all_mem [ideal_Inter_nonempty P] : ∃ a : P, ∀ I : ideal P, a ∈ I := begin change ∃ (a : P), ∀ (I : ideal P), a ∈ (I : set P), rw ← set.nonempty_Inter, exact Inter_nonempty, end lemma ideal_Inter_nonempty_of_exists_all_mem (h : ∃ a : P, ∀ I : ideal P, a ∈ I) : ideal_Inter_nonempty P := { Inter_nonempty := by rwa set.nonempty_Inter } lemma ideal_Inter_nonempty_iff : ideal_Inter_nonempty P ↔ ∃ a : P, ∀ I : ideal P, a ∈ I := ⟨λ _, by exactI ideal_Inter_nonempty.exists_all_mem, ideal_Inter_nonempty_of_exists_all_mem⟩ end preorder section order_bot variables [order_bot P] {I : ideal P} /-- A specific witness of `I.nonempty` when `P` has a bottom element. -/ @[simp] lemma bot_mem : ⊥ ∈ I := I.mem_of_le bot_le I.nonempty.some_mem /-- There is a bottom ideal when `P` has a bottom element. -/ instance : order_bot (ideal P) := { bot := principal ⊥, bot_le := by simp, .. ideal.partial_order } @[priority 100] instance order_bot.ideal_Inter_nonempty : ideal_Inter_nonempty P := by { rw ideal_Inter_nonempty_iff, exact ⟨⊥, λ I, bot_mem⟩ } end order_bot section order_top variables [order_top P] /-- There is a top ideal when `P` has a top element. -/ instance : order_top (ideal P) := { top := principal ⊤, le_top := λ I x h, le_top, .. ideal.partial_order } @[simp] lemma coe_top : ((⊤ : ideal P) : set P) = set.univ := set.univ_subset_iff.1 (λ p _, le_top) lemma top_of_mem_top {I : ideal P} (mem_top : ⊤ ∈ I) : I = ⊤ := begin ext, change x ∈ I ↔ x ∈ ((⊤ : ideal P) : set P), split, { simp [coe_top] }, { exact λ _, I.mem_of_le le_top mem_top } end lemma is_proper_of_ne_top {I : ideal P} (ne_top : I ≠ ⊤) : is_proper I := is_proper_of_not_mem (λ h, ne_top (top_of_mem_top h)) lemma is_proper.ne_top {I : ideal P} (hI : is_proper I) : I ≠ ⊤ := begin intro h, rw [ext'_iff, coe_top] at h, apply hI.ne_univ, assumption, end lemma is_proper.top_not_mem {I : ideal P} (hI : is_proper I) : ⊤ ∉ I := by { by_contra, exact hI.ne_top (top_of_mem_top h) } lemma _root_.is_coatom.is_proper {I : ideal P} (hI : is_coatom I) : is_proper I := is_proper_of_ne_top hI.1 lemma is_proper_iff_ne_top {I : ideal P} : is_proper I ↔ I ≠ ⊤ := ⟨λ h, h.ne_top, λ h, is_proper_of_ne_top h⟩ lemma is_maximal.is_coatom {I : ideal P} (h : is_maximal I) : is_coatom I := ⟨is_maximal.to_is_proper.ne_top, λ _ _, by { rw [ext'_iff, coe_top], exact is_maximal.maximal_proper ‹_› }⟩ lemma is_maximal.is_coatom' {I : ideal P} [is_maximal I] : is_coatom I := is_maximal.is_coatom ‹_› lemma _root_.is_coatom.is_maximal {I : ideal P} (hI : is_coatom I) : is_maximal I := { maximal_proper := λ _ _, by simp [hI.2 _ ‹_›], ..is_coatom.is_proper ‹_› } lemma is_maximal_iff_is_coatom {I : ideal P} : is_maximal I ↔ is_coatom I := ⟨λ h, h.is_coatom, λ h, h.is_maximal⟩ end order_top section semilattice_sup variables [semilattice_sup P] {x y : P} {I : ideal P} /-- A specific witness of `I.directed` when `P` has joins. -/ lemma sup_mem (x y ∈ I) : x ⊔ y ∈ I := let ⟨z, h_mem, hx, hy⟩ := I.directed x ‹_› y ‹_› in I.mem_of_le (sup_le hx hy) h_mem @[simp] lemma sup_mem_iff : x ⊔ y ∈ I ↔ x ∈ I ∧ y ∈ I := ⟨λ h, ⟨I.mem_of_le le_sup_left h, I.mem_of_le le_sup_right h⟩, λ h, sup_mem x y h.left h.right⟩ end semilattice_sup section semilattice_sup_ideal_inter_nonempty variables [semilattice_sup P] [ideal_inter_nonempty P] {x : P} {I J K : ideal P} /-- The intersection of two ideals is an ideal, when it is nonempty and `P` has joins. -/ def inf (I J : ideal P) : ideal P := { carrier := I ∩ J, nonempty := inter_nonempty I J, directed := λ x ⟨_, _⟩ y ⟨_, _⟩, ⟨x ⊔ y, ⟨sup_mem x y ‹_› ‹_›, sup_mem x y ‹_› ‹_›⟩, by simp⟩, mem_of_le := λ x y h ⟨_, _⟩, ⟨mem_of_le I h ‹_›, mem_of_le J h ‹_›⟩ } /-- There is a smallest ideal containing two ideals, when their intersection is nonempty and `P` has joins. -/ def sup (I J : ideal P) : ideal P := { carrier := {x | ∃ (i ∈ I) (j ∈ J), x ≤ i ⊔ j}, nonempty := by { cases inter_nonempty I J, exact ⟨w, w, h.1, w, h.2, le_sup_left⟩ }, directed := λ x ⟨xi, _, xj, _, _⟩ y ⟨yi, _, yj, _, _⟩, ⟨x ⊔ y, ⟨xi ⊔ yi, sup_mem xi yi ‹_› ‹_›, xj ⊔ yj, sup_mem xj yj ‹_› ‹_›, sup_le (calc x ≤ xi ⊔ xj : ‹_› ... ≤ (xi ⊔ yi) ⊔ (xj ⊔ yj) : sup_le_sup le_sup_left le_sup_left) (calc y ≤ yi ⊔ yj : ‹_› ... ≤ (xi ⊔ yi) ⊔ (xj ⊔ yj) : sup_le_sup le_sup_right le_sup_right)⟩, le_sup_left, le_sup_right⟩, mem_of_le := λ x y _ ⟨yi, _, yj, _, _⟩, ⟨yi, ‹_›, yj, ‹_›, le_trans ‹x ≤ y› ‹_›⟩ } lemma sup_le : I ≤ K → J ≤ K → sup I J ≤ K := λ hIK hJK x ⟨i, hiI, j, hjJ, hxij⟩, K.mem_of_le hxij $ sup_mem i j (mem_of_mem_of_le hiI hIK) (mem_of_mem_of_le hjJ hJK) instance : lattice (ideal P) := { sup := sup, le_sup_left := λ I J (i ∈ I), by { cases nonempty J, exact ⟨i, ‹_›, w, ‹_›, le_sup_left⟩ }, le_sup_right := λ I J (j ∈ J), by { cases nonempty I, exact ⟨w, ‹_›, j, ‹_›, le_sup_right⟩ }, sup_le := @sup_le _ _ _, inf := inf, inf_le_left := λ I J, set.inter_subset_left I J, inf_le_right := λ I J, set.inter_subset_right I J, le_inf := λ I J K, set.subset_inter, .. ideal.partial_order } @[simp] lemma mem_inf : x ∈ I ⊓ J ↔ x ∈ I ∧ x ∈ J := iff_of_eq rfl @[simp] lemma mem_sup : x ∈ I ⊔ J ↔ ∃ (i ∈ I) (j ∈ J), x ≤ i ⊔ j := iff_of_eq rfl lemma lt_sup_principal_of_not_mem (hx : x ∉ I) : I < I ⊔ principal x := begin apply lt_of_le_of_ne le_sup_left, intro h, simp at h, exact hx h end end semilattice_sup_ideal_inter_nonempty section ideal_Inter_nonempty variables [preorder P] [ideal_Inter_nonempty P] @[priority 100] instance ideal_Inter_nonempty.ideal_inter_nonempty : ideal_inter_nonempty P := { inter_nonempty := λ _ _, begin obtain ⟨a, ha⟩ : ∃ a : P, ∀ I : ideal P, a ∈ I := ideal_Inter_nonempty.exists_all_mem, exact ⟨a, ha _, ha _⟩ end } variables {α β γ : Type*} {ι : Sort*} lemma ideal_Inter_nonempty.all_Inter_nonempty {f : ι → ideal P} : (⋂ x, (f x : set P)).nonempty := begin obtain ⟨a, ha⟩ : ∃ a : P, ∀ I : ideal P, a ∈ I := ideal_Inter_nonempty.exists_all_mem, exact ⟨a, by simp [ha]⟩ end lemma ideal_Inter_nonempty.all_bInter_nonempty {f : α → ideal P} {s : set α} : (⋂ x ∈ s, (f x : set P)).nonempty := begin obtain ⟨a, ha⟩ : ∃ a : P, ∀ I : ideal P, a ∈ I := ideal_Inter_nonempty.exists_all_mem, exact ⟨a, by simp [ha]⟩ end end ideal_Inter_nonempty section semilattice_sup_ideal_Inter_nonempty variables [semilattice_sup P] [ideal_Inter_nonempty P] {x : P} {I J K : ideal P} instance : has_Inf (ideal P) := { Inf := λ s, { carrier := ⋂ (I ∈ s), (I : set P), nonempty := ideal_Inter_nonempty.all_bInter_nonempty, directed := λ x hx y hy, ⟨x ⊔ y, ⟨λ S ⟨I, hS⟩, begin simp only [←hS, sup_mem_iff, mem_coe, set.mem_Inter], intro hI, rw set.mem_bInter_iff at *, exact ⟨hx _ hI, hy _ hI⟩ end, le_sup_left, le_sup_right⟩⟩, mem_of_le := λ x y hxy hy, begin rw set.mem_bInter_iff at *, exact λ I hI, mem_of_le I ‹_› (hy I hI) end } } variables {s : set (ideal P)} @[simp] lemma mem_Inf : x ∈ Inf s ↔ ∀ I ∈ s, x ∈ I := by { change x ∈ (⋂ (I ∈ s), (I : set P)) ↔ ∀ I ∈ s, x ∈ I, simp } @[simp] lemma coe_Inf : ↑(Inf s) = ⋂ (I ∈ s), (I : set P) := rfl lemma Inf_le (hI : I ∈ s) : Inf s ≤ I := λ _ hx, hx I ⟨I, by simp [hI]⟩ lemma le_Inf (h : ∀ J ∈ s, I ≤ J) : I ≤ Inf s := λ _ _, by { simp only [mem_coe, coe_Inf, set.mem_Inter], tauto } lemma is_glb_Inf : is_glb s (Inf s) := ⟨λ _, Inf_le, λ _, le_Inf⟩ instance : complete_lattice (ideal P) := { ..ideal.lattice, ..complete_lattice_of_Inf (ideal P) (λ _, @is_glb_Inf _ _ _ _) } end semilattice_sup_ideal_Inter_nonempty section semilattice_inf variable [semilattice_inf P] @[priority 100] instance semilattice_inf.ideal_inter_nonempty : ideal_inter_nonempty P := { inter_nonempty := λ I J, begin cases I.nonempty with i _, cases J.nonempty with j _, exact ⟨i ⊓ j, I.mem_of_le inf_le_left ‹_›, J.mem_of_le inf_le_right ‹_›⟩ end } end semilattice_inf section distrib_lattice variables [distrib_lattice P] variables {I J : ideal P} lemma eq_sup_of_le_sup {x i j: P} (hi : i ∈ I) (hj : j ∈ J) (hx : x ≤ i ⊔ j): ∃ (i' ∈ I) (j' ∈ J), x = i' ⊔ j' := begin refine ⟨x ⊓ i, I.mem_of_le inf_le_right hi, x ⊓ j, J.mem_of_le inf_le_right hj, _⟩, calc x = x ⊓ (i ⊔ j) : left_eq_inf.mpr hx ... = (x ⊓ i) ⊔ (x ⊓ j) : inf_sup_left, end lemma coe_sup_eq : ↑(I ⊔ J) = {x | ∃ i ∈ I, ∃ j ∈ J, x = i ⊔ j} := begin ext, rw [mem_coe, mem_sup], exact ⟨λ ⟨_, _, _, _, _⟩, eq_sup_of_le_sup ‹_› ‹_› ‹_›, λ ⟨i, _, j, _, _⟩, ⟨i, ‹_›, j, ‹_›, le_of_eq ‹_›⟩⟩ end end distrib_lattice section boolean_algebra variables [boolean_algebra P] {x : P} {I : ideal P} lemma is_proper.not_mem_of_compl_mem (hI : is_proper I) (hxc : xᶜ ∈ I) : x ∉ I := begin intro hx, apply hI.top_not_mem, have ht : x ⊔ xᶜ ∈ I := sup_mem _ _ ‹_› ‹_›, rwa sup_compl_eq_top at ht, end lemma is_proper.not_mem_or_compl_not_mem (hI : is_proper I) : x ∉ I ∨ xᶜ ∉ I := have h : xᶜ ∈ I → x ∉ I := hI.not_mem_of_compl_mem, by tauto end boolean_algebra end ideal /-- For a preorder `P`, `cofinal P` is the type of subsets of `P` containing arbitrarily large elements. They are the dense sets in the topology whose open sets are terminal segments. -/ structure cofinal (P) [preorder P] := (carrier : set P) (mem_gt : ∀ x : P, ∃ y ∈ carrier, x ≤ y) namespace cofinal variables [preorder P] instance : inhabited (cofinal P) := ⟨{ carrier := set.univ, mem_gt := λ x, ⟨x, trivial, le_refl _⟩ }⟩ instance : has_mem P (cofinal P) := ⟨λ x D, x ∈ D.carrier⟩ variables (D : cofinal P) (x : P) /-- A (noncomputable) element of a cofinal set lying above a given element. -/ noncomputable def above : P := classical.some $ D.mem_gt x lemma above_mem : D.above x ∈ D := exists.elim (classical.some_spec $ D.mem_gt x) $ λ a _, a lemma le_above : x ≤ D.above x := exists.elim (classical.some_spec $ D.mem_gt x) $ λ _ b, b end cofinal section ideal_of_cofinals variables [preorder P] (p : P) {ι : Type*} [encodable ι] (𝒟 : ι → cofinal P) /-- Given a starting point, and a countable family of cofinal sets, this is an increasing sequence that intersects each cofinal set. -/ noncomputable def sequence_of_cofinals : ℕ → P | 0 := p | (n+1) := match encodable.decode ι n with | none := sequence_of_cofinals n | some i := (𝒟 i).above (sequence_of_cofinals n) end lemma sequence_of_cofinals.monotone : monotone (sequence_of_cofinals p 𝒟) := by { apply monotone_nat_of_le_succ, intros n, dunfold sequence_of_cofinals, cases encodable.decode ι n, { refl }, { apply cofinal.le_above }, } lemma sequence_of_cofinals.encode_mem (i : ι) : sequence_of_cofinals p 𝒟 (encodable.encode i + 1) ∈ 𝒟 i := by { dunfold sequence_of_cofinals, rw encodable.encodek, apply cofinal.above_mem, } /-- Given an element `p : P` and a family `𝒟` of cofinal subsets of a preorder `P`, indexed by a countable type, `ideal_of_cofinals p 𝒟` is an ideal in `P` which - contains `p`, according to `mem_ideal_of_cofinals p 𝒟`, and - intersects every set in `𝒟`, according to `cofinal_meets_ideal_of_cofinals p 𝒟`. This proves the Rasiowa–Sikorski lemma. -/ def ideal_of_cofinals : ideal P := { carrier := { x : P | ∃ n, x ≤ sequence_of_cofinals p 𝒟 n }, nonempty := ⟨p, 0, le_refl _⟩, directed := λ x ⟨n, hn⟩ y ⟨m, hm⟩, ⟨_, ⟨max n m, le_refl _⟩, le_trans hn $ sequence_of_cofinals.monotone p 𝒟 (le_max_left _ _), le_trans hm $ sequence_of_cofinals.monotone p 𝒟 (le_max_right _ _) ⟩, mem_of_le := λ x y hxy ⟨n, hn⟩, ⟨n, le_trans hxy hn⟩, } lemma mem_ideal_of_cofinals : p ∈ ideal_of_cofinals p 𝒟 := ⟨0, le_refl _⟩ /-- `ideal_of_cofinals p 𝒟` is `𝒟`-generic. -/ lemma cofinal_meets_ideal_of_cofinals (i : ι) : ∃ x : P, x ∈ 𝒟 i ∧ x ∈ ideal_of_cofinals p 𝒟 := ⟨_, sequence_of_cofinals.encode_mem p 𝒟 i, _, le_refl _⟩ end ideal_of_cofinals end order
ced9a345d9731f9b6a287c22225b217bb1fb308a
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/PrettyPrinter/Delaborator/TopDownAnalyze.lean
ee89be8e3080bbeff9c6a5a8f23c39f00af23a71
[ "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
27,095
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Selsam -/ import Lean.Data.RBMap import Lean.Meta.SynthInstance import Lean.Util.FindMVar import Lean.Util.FindLevelMVar import Lean.Util.CollectLevelParams import Lean.Util.ReplaceLevel import Lean.PrettyPrinter.Delaborator.Options import Lean.PrettyPrinter.Delaborator.SubExpr import Lean.Elab.Config /-! The top-down analyzer is an optional preprocessor to the delaborator that aims to determine the minimal annotations necessary to ensure that the delaborated expression can be re-elaborated correctly. Currently, the top-down analyzer is neither sound nor complete: there may be edge-cases in which the expression can still not be re-elaborated correctly, and it may also add many annotations that are not strictly necessary. -/ namespace Lean open Meta SubExpr register_builtin_option pp.analyze : Bool := { defValue := false group := "pp.analyze" descr := "(pretty printer analyzer) determine annotations sufficient to ensure round-tripping" } register_builtin_option pp.analyze.checkInstances : Bool := { -- TODO: It would be great to make this default to `true`, but currently, `MessageData` does not -- include the `LocalInstances`, so this will be very over-aggressive in inserting instances -- that would otherwise be easy to synthesize. We may consider threading the instances in the future, -- or at least tracking a bool for whether the instances have been lost. defValue := false group := "pp.analyze" descr := "(pretty printer analyzer) confirm that instances can be re-synthesized" } register_builtin_option pp.analyze.typeAscriptions : Bool := { defValue := true group := "pp.analyze" descr := "(pretty printer analyzer) add type ascriptions when deemed necessary" } register_builtin_option pp.analyze.trustSubst : Bool := { defValue := false group := "pp.analyze" descr := "(pretty printer analyzer) always 'pretend' applications that can delab to ▸ are 'regular'" } register_builtin_option pp.analyze.trustOfNat : Bool := { defValue := true group := "pp.analyze" descr := "(pretty printer analyzer) always 'pretend' `OfNat.ofNat` applications can elab bottom-up" } register_builtin_option pp.analyze.trustOfScientific : Bool := { defValue := true group := "pp.analyze" descr := "(pretty printer analyzer) always 'pretend' `OfScientific.ofScientific` applications can elab bottom-up" } -- TODO: this is an arbitrary special case of a more general principle. register_builtin_option pp.analyze.trustSubtypeMk : Bool := { defValue := true group := "pp.analyze" descr := "(pretty printer analyzer) assume the implicit arguments of Subtype.mk can be inferred" } register_builtin_option pp.analyze.trustId : Bool := { defValue := true group := "pp.analyze" descr := "(pretty printer analyzer) always assume an implicit `fun x => x` can be inferred" } register_builtin_option pp.analyze.trustKnownFOType2TypeHOFuns : Bool := { defValue := true group := "pp.analyze" descr := "(pretty printer analyzer) omit higher-order functions whose values seem to be knownType2Type" } register_builtin_option pp.analyze.omitMax : Bool := { defValue := true group := "pp.analyze" descr := "(pretty printer analyzer) omit universe `max` annotations (these constraints can actually hurt)" } register_builtin_option pp.analyze.knowsType : Bool := { defValue := true group := "pp.analyze" descr := "(pretty printer analyzer) assume the type of the original expression is known" } register_builtin_option pp.analyze.explicitHoles : Bool := { defValue := false group := "pp.analyze" descr := "(pretty printer analyzer) use `_` for explicit arguments that can be inferred" } def getPPAnalyze (o : Options) : Bool := o.get pp.analyze.name pp.analyze.defValue def getPPAnalyzeCheckInstances (o : Options) : Bool := o.get pp.analyze.checkInstances.name pp.analyze.checkInstances.defValue def getPPAnalyzeTypeAscriptions (o : Options) : Bool := o.get pp.analyze.typeAscriptions.name pp.analyze.typeAscriptions.defValue def getPPAnalyzeTrustSubst (o : Options) : Bool := o.get pp.analyze.trustSubst.name pp.analyze.trustSubst.defValue def getPPAnalyzeTrustOfNat (o : Options) : Bool := o.get pp.analyze.trustOfNat.name pp.analyze.trustOfNat.defValue def getPPAnalyzeTrustOfScientific (o : Options) : Bool := o.get pp.analyze.trustOfScientific.name pp.analyze.trustOfScientific.defValue def getPPAnalyzeTrustId (o : Options) : Bool := o.get pp.analyze.trustId.name pp.analyze.trustId.defValue def getPPAnalyzeTrustSubtypeMk (o : Options) : Bool := o.get pp.analyze.trustSubtypeMk.name pp.analyze.trustSubtypeMk.defValue def getPPAnalyzeTrustKnownFOType2TypeHOFuns (o : Options) : Bool := o.get pp.analyze.trustKnownFOType2TypeHOFuns.name pp.analyze.trustKnownFOType2TypeHOFuns.defValue def getPPAnalyzeOmitMax (o : Options) : Bool := o.get pp.analyze.omitMax.name pp.analyze.omitMax.defValue def getPPAnalyzeKnowsType (o : Options) : Bool := o.get pp.analyze.knowsType.name pp.analyze.knowsType.defValue def getPPAnalyzeExplicitHoles (o : Options) : Bool := o.get pp.analyze.explicitHoles.name pp.analyze.explicitHoles.defValue def getPPAnalysisSkip (o : Options) : Bool := o.get `pp.analysis.skip false def getPPAnalysisHole (o : Options) : Bool := o.get `pp.analysis.hole false def getPPAnalysisNamedArg (o : Options) : Bool := o.get `pp.analysis.namedArg false def getPPAnalysisLetVarType (o : Options) : Bool := o.get `pp.analysis.letVarType false def getPPAnalysisNeedsType (o : Options) : Bool := o.get `pp.analysis.needsType false def getPPAnalysisBlockImplicit (o : Options) : Bool := o.get `pp.analysis.blockImplicit false namespace PrettyPrinter.Delaborator def returnsPi (motive : Expr) : MetaM Bool := do lambdaTelescope motive fun _ b => return b.isForall def isNonConstFun (motive : Expr) : MetaM Bool := do match motive with | Expr.lam _ _ b _ => isNonConstFun b | _ => return motive.hasLooseBVars def isSimpleHOFun (motive : Expr) : MetaM Bool := return not (← returnsPi motive) && not (← isNonConstFun motive) def isType2Type (motive : Expr) : MetaM Bool := do match ← inferType motive with | Expr.forallE _ (Expr.sort ..) (Expr.sort ..) .. => return true | _ => return false def isFOLike (motive : Expr) : MetaM Bool := do let f := motive.getAppFn return f.isFVar || f.isConst def isIdLike (arg : Expr) : Bool := -- TODO: allow `id` constant as well? match arg with | Expr.lam _ _ (Expr.bvar ..) .. => true | _ => false def isStructureInstance (e : Expr) : MetaM Bool := do match e.isConstructorApp? (← getEnv) with | some s => return isStructure (← getEnv) s.induct | none => return false namespace TopDownAnalyze partial def hasMVarAtCurrDepth (e : Expr) : MetaM Bool := do let mctx ← getMCtx return Option.isSome <| e.findMVar? fun mvarId => match mctx.findDecl? mvarId with | some mdecl => mdecl.depth == mctx.depth | _ => false partial def hasLevelMVarAtCurrDepth (e : Expr) : MetaM Bool := do let mctx ← getMCtx return Option.isSome <| e.findLevelMVar? fun mvarId => mctx.findLevelDepth? mvarId == some mctx.depth private def valUnknown (e : Expr) : MetaM Bool := do hasMVarAtCurrDepth (← instantiateMVars e) private def typeUnknown (e : Expr) : MetaM Bool := do valUnknown (← inferType e) def isHBinOp (e : Expr) : Bool := Id.run do -- TODO: instead of tracking these explicitly, -- consider a more general solution that checks for defaultInstances if e.getAppNumArgs != 6 then return false let f := e.getAppFn if !f.isConst then return false -- Note: we leave out `HPow.hPow because we expect its homogeneous -- version will change soon let ops := #[ `HOr.hOr, `HXor.hXor, `HAnd.hAnd, `HAppend.hAppend, `HOrElse.hOrElse, `HAndThen.hAndThen, `HAdd.hAdd, `HSub.hSub, `HMul.hMul, `HDiv.hDiv, `HMod.hMod, `HShiftLeft.hShiftLeft, `HShiftRight] ops.any fun op => op == f.constName! def replaceLPsWithVars (e : Expr) : MetaM Expr := do if !e.hasLevelParam then return e let lps := collectLevelParams {} e |>.params let mut replaceMap : HashMap Name Level := {} for lp in lps do replaceMap := replaceMap.insert lp (← mkFreshLevelMVar) return e.replaceLevel fun | Level.param n .. => replaceMap.find! n | l => if !l.hasParam then some l else none def isDefEqAssigning (t s : Expr) : MetaM Bool := do withReader (fun ctx => { ctx with config := { ctx.config with assignSyntheticOpaque := true }}) $ Meta.isDefEq t s def checkpointDefEq (t s : Expr) : MetaM Bool := do Meta.checkpointDefEq (mayPostpone := false) do isDefEqAssigning t s def isHigherOrder (type : Expr) : MetaM Bool := do forallTelescopeReducing type fun xs b => return xs.size > 0 && b.isSort def isFunLike (e : Expr) : MetaM Bool := do forallTelescopeReducing (← inferType e) fun xs _ => return xs.size > 0 def isSubstLike (e : Expr) : Bool := e.isAppOfArity ``Eq.ndrec 6 || e.isAppOfArity ``Eq.rec 6 def nameNotRoundtrippable (n : Name) : Bool := n.hasMacroScopes || isPrivateName n || containsNum n where containsNum | Name.str p .. => containsNum p | Name.num .. => true | Name.anonymous => false def mvarName (mvar : Expr) : MetaM Name := return (← mvar.mvarId!.getDecl).userName def containsBadMax : Level → Bool | Level.succ u .. => containsBadMax u | Level.max u v .. => (u.hasParam && v.hasParam) || containsBadMax u || containsBadMax v | Level.imax u v .. => (u.hasParam && v.hasParam) || containsBadMax u || containsBadMax v | _ => false open SubExpr structure Context where knowsType : Bool knowsLevel : Bool -- only constants look at this inBottomUp : Bool := false parentIsApp : Bool := false subExpr : SubExpr deriving Inhabited structure State where annotations : OptionsPerPos := {} postponed : Array (Expr × Expr) := #[] -- not currently used abbrev AnalyzeM := ReaderT Context (StateRefT State MetaM) instance (priority := low) : MonadReaderOf SubExpr AnalyzeM where read := Context.subExpr <$> read instance (priority := low) : MonadWithReaderOf SubExpr AnalyzeM where withReader f x := fun ctx => x { ctx with subExpr := f ctx.subExpr } def tryUnify (e₁ e₂ : Expr) : AnalyzeM Unit := do try let r ← isDefEqAssigning e₁ e₂ if !r then modify fun s => { s with postponed := s.postponed.push (e₁, e₂) } pure () catch _ => modify fun s => { s with postponed := s.postponed.push (e₁, e₂) } partial def inspectOutParams (arg mvar : Expr) : AnalyzeM Unit := do let argType ← inferType arg -- HAdd α α α let mvarType ← inferType mvar let fType ← inferType argType.getAppFn -- Type → Type → outParam Type let mType ← inferType mvarType.getAppFn inspectAux fType mType 0 argType.getAppArgs mvarType.getAppArgs where inspectAux (fType mType : Expr) (i : Nat) (args mvars : Array Expr) := do let fType ← whnf fType let mType ← whnf mType if not (i < args.size) then return () match fType, mType with | Expr.forallE _ fd fb _, Expr.forallE _ _ mb _ => do -- TODO: do I need to check (← okBottomUp? args[i] mvars[i] fuel).isSafe here? -- if so, I'll need to take a callback if fd.isOutParam then tryUnify (args[i]!) (mvars[i]!) inspectAux (fb.instantiate1 args[i]!) (mb.instantiate1 mvars[i]!) (i+1) args mvars | _, _ => return () partial def isTrivialBottomUp (e : Expr) : AnalyzeM Bool := do let opts ← getOptions return e.isFVar || e.isConst || e.isMVar || e.isNatLit || e.isStringLit || e.isSort || (getPPAnalyzeTrustOfNat opts && e.isAppOfArity ``OfNat.ofNat 3) || (getPPAnalyzeTrustOfScientific opts && e.isAppOfArity ``OfScientific.ofScientific 5) partial def canBottomUp (e : Expr) (mvar? : Option Expr := none) (fuel : Nat := 10) : AnalyzeM Bool := do -- Here we check if `e` can be safely elaborated without its expected type. -- These are incomplete (and possibly unsound) heuristics. -- TODO: do I need to snapshot the state before calling this? match fuel with | 0 => return false | fuel + 1 => if ← isTrivialBottomUp e then return true let f := e.getAppFn if !f.isConst && !f.isFVar then return false let args := e.getAppArgs let fType ← replaceLPsWithVars (← inferType e.getAppFn) let (mvars, bInfos, resultType) ← forallMetaBoundedTelescope fType e.getAppArgs.size for i in [:mvars.size] do if bInfos[i]! == BinderInfo.instImplicit then inspectOutParams args[i]! mvars[i]! else if bInfos[i]! == BinderInfo.default then if ← isTrivialBottomUp args[i]! then tryUnify args[i]! mvars[i]! else if ← typeUnknown mvars[i]! <&&> canBottomUp args[i]! (some mvars[i]!) fuel then tryUnify args[i]! mvars[i]! if ← (pure (isHBinOp e) <&&> (valUnknown mvars[0]! <||> valUnknown mvars[1]!)) then tryUnify mvars[0]! mvars[1]! if mvar?.isSome then tryUnify resultType (← inferType mvar?.get!) return !(← valUnknown resultType) def withKnowing (knowsType knowsLevel : Bool) (x : AnalyzeM α) : AnalyzeM α := do withReader (fun ctx => { ctx with knowsType := knowsType, knowsLevel := knowsLevel }) x builtin_initialize analyzeFailureId : InternalExceptionId ← registerInternalExceptionId `analyzeFailure def checkKnowsType : AnalyzeM Unit := do if not (← read).knowsType then throw $ Exception.internal analyzeFailureId def annotateBoolAt (n : Name) (pos : Pos) : AnalyzeM Unit := do let opts := (← get).annotations.findD pos {} |>.setBool n true trace[pp.analyze.annotate] "{pos} {n}" modify fun s => { s with annotations := s.annotations.insert pos opts } def annotateBool (n : Name) : AnalyzeM Unit := do annotateBoolAt n (← getPos) structure App.Context where f : Expr fType : Expr args : Array Expr mvars : Array Expr bInfos : Array BinderInfo forceRegularApp : Bool structure App.State where bottomUps : Array Bool higherOrders : Array Bool funBinders : Array Bool provideds : Array Bool namedArgs : Array Name := #[] abbrev AnalyzeAppM := ReaderT App.Context (StateT App.State AnalyzeM) mutual partial def analyze (parentIsApp : Bool := false) : AnalyzeM Unit := do checkMaxHeartbeats "Delaborator.topDownAnalyze" trace[pp.analyze] "{(← read).knowsType}.{(← read).knowsLevel}" let e ← getExpr let opts ← getOptions if ← (pure !e.isAtomic) <&&> pure !(getPPProofs opts) <&&> (try Meta.isProof e catch _ => pure false) then if getPPProofsWithType opts then withType $ withKnowing true true $ analyze return () else withReader (fun ctx => { ctx with parentIsApp := parentIsApp }) do match (← getExpr) with | Expr.app .. => analyzeApp | Expr.forallE .. => analyzePi | Expr.lam .. => analyzeLam | Expr.const .. => analyzeConst | Expr.sort .. => analyzeSort | Expr.proj .. => analyzeProj | Expr.fvar .. => analyzeFVar | Expr.mdata .. => analyzeMData | Expr.letE .. => analyzeLet | Expr.lit .. => pure () | Expr.mvar .. => pure () | Expr.bvar .. => pure () where analyzeApp := do let mut willKnowType := (← read).knowsType if !(← read).knowsType && !(← canBottomUp (← getExpr)) then annotateBool `pp.analysis.needsType withType $ withKnowing true false $ analyze willKnowType := true else if ← (pure !(← read).knowsType <||> pure (← read).inBottomUp) <&&> isStructureInstance (← getExpr) then withType do annotateBool `pp.structureInstanceTypes withKnowing true false $ analyze willKnowType := true withKnowing willKnowType true $ analyzeAppStaged (← getExpr).getAppFn (← getExpr).getAppArgs analyzeAppStaged (f : Expr) (args : Array Expr) : AnalyzeM Unit := do let fType ← replaceLPsWithVars (← inferType f) let (mvars, bInfos, resultType) ← forallMetaBoundedTelescope fType args.size let rest := args.extract mvars.size args.size let args := args.shrink mvars.size -- Unify with the expected type if (← read).knowsType then tryUnify (← inferType (mkAppN f args)) resultType let forceRegularApp : Bool := (getPPAnalyzeTrustSubst (← getOptions) && isSubstLike (← getExpr)) || (getPPAnalyzeTrustSubtypeMk (← getOptions) && (← getExpr).isAppOfArity ``Subtype.mk 4) analyzeAppStagedCore { f, fType, args, mvars, bInfos, forceRegularApp } |>.run' { bottomUps := mkArray args.size false, higherOrders := mkArray args.size false, provideds := mkArray args.size false, funBinders := mkArray args.size false } if not rest.isEmpty then -- Note: this shouldn't happen for type-correct terms if !args.isEmpty then analyzeAppStaged (mkAppN f args) rest maybeAddBlockImplicit : AnalyzeM Unit := do -- See `MonadLift.noConfusion for an example where this is necessary. if !(← read).parentIsApp then let type ← inferType (← getExpr) if type.isForall && type.bindingInfo! == BinderInfo.implicit then annotateBool `pp.analysis.blockImplicit analyzeConst : AnalyzeM Unit := do let Expr.const _ ls .. ← getExpr | unreachable! if !(← read).knowsLevel && !ls.isEmpty then -- TODO: this is a very crude heuristic, motivated by https://github.com/leanprover/lean4/issues/590 unless getPPAnalyzeOmitMax (← getOptions) && ls.any containsBadMax do annotateBool `pp.universes maybeAddBlockImplicit analyzePi : AnalyzeM Unit := do withBindingDomain $ withKnowing true false analyze withBindingBody Name.anonymous analyze analyzeLam : AnalyzeM Unit := do if !(← read).knowsType then annotateBool `pp.funBinderTypes withBindingDomain $ withKnowing true false analyze withBindingBody Name.anonymous analyze analyzeLet : AnalyzeM Unit := do let Expr.letE _ _ v _ .. ← getExpr | unreachable! if !(← canBottomUp v) then annotateBool `pp.analysis.letVarType withLetVarType $ withKnowing true false analyze withLetValue $ withKnowing true true analyze else withReader (fun ctx => { ctx with inBottomUp := true }) do withLetValue $ withKnowing true true analyze withLetBody analyze analyzeSort : AnalyzeM Unit := pure () analyzeProj : AnalyzeM Unit := withProj analyze analyzeFVar : AnalyzeM Unit := maybeAddBlockImplicit analyzeMData : AnalyzeM Unit := withMDataExpr analyze partial def analyzeAppStagedCore : AnalyzeAppM Unit := do collectBottomUps checkOutParams collectHigherOrders hBinOpHeuristic collectTrivialBottomUps discard <| processPostponed (mayPostpone := true) applyFunBinderHeuristic analyzeFn for i in [:(← read).args.size] do analyzeArg i maybeSetExplicit where collectBottomUps := do let { args, mvars, bInfos, ..} ← read for target in [fun _ => none, fun i => some mvars[i]!] do for i in [:args.size] do if bInfos[i]! == BinderInfo.default then if ← typeUnknown mvars[i]! <&&> canBottomUp args[i]! (target i) then tryUnify args[i]! mvars[i]! modify fun s => { s with bottomUps := s.bottomUps.set! i true } checkOutParams := do let { args, mvars, bInfos, ..} ← read for i in [:args.size] do if bInfos[i]! == BinderInfo.instImplicit then inspectOutParams args[i]! mvars[i]! collectHigherOrders := do let { args, mvars, bInfos, ..} ← read for i in [:args.size] do if not (bInfos[i]! == BinderInfo.implicit || bInfos[i]! == BinderInfo.strictImplicit) then continue if not (← isHigherOrder (← inferType args[i]!)) then continue if getPPAnalyzeTrustId (← getOptions) && isIdLike args[i]! then continue if getPPAnalyzeTrustKnownFOType2TypeHOFuns (← getOptions) && not (← valUnknown mvars[i]!) && (← isType2Type (args[i]!)) && (← isFOLike (args[i]!)) then continue tryUnify args[i]! mvars[i]! modify fun s => { s with higherOrders := s.higherOrders.set! i true } hBinOpHeuristic := do let { mvars, ..} ← read if ← (pure (isHBinOp (← getExpr)) <&&> (valUnknown mvars[0]! <||> valUnknown mvars[1]!)) then tryUnify mvars[0]! mvars[1]! collectTrivialBottomUps := do -- motivation: prevent levels from printing in -- Boo.mk : {α : Type u_1} → {β : Type u_2} → α → β → Boo.{u_1, u_2} α β let { args, mvars, bInfos, ..} ← read for i in [:args.size] do if bInfos[i]! == BinderInfo.default then if ← valUnknown mvars[i]! <&&> isTrivialBottomUp args[i]! then tryUnify args[i]! mvars[i]! modify fun s => { s with bottomUps := s.bottomUps.set! i true } applyFunBinderHeuristic := do let { args, mvars, bInfos, .. } ← read let rec core (argIdx : Nat) (mvarType : Expr) : AnalyzeAppM Bool := do match ← getExpr, mvarType with | Expr.lam .., Expr.forallE _ t b .. => let mut annotated := false for i in [:argIdx] do if ← pure (bInfos[i]! == BinderInfo.implicit) <&&> valUnknown mvars[i]! <&&> withNewMCtxDepth (checkpointDefEq t mvars[i]!) then annotateBool `pp.funBinderTypes tryUnify args[i]! mvars[i]! -- Note: currently we always analyze the lambda binding domains in `analyzeLam` -- (so we don't need to analyze it again here) annotated := true break let annotatedBody ← withBindingBody Name.anonymous (core argIdx b) return annotated || annotatedBody | _, _ => return false for i in [:args.size] do if bInfos[i]! == BinderInfo.default then let b ← withNaryArg i (core i (← inferType mvars[i]!)) if b then modify fun s => { s with funBinders := s.funBinders.set! i true } analyzeFn := do -- Now, if this is the first staging, analyze the n-ary function without expected type let {f, fType, forceRegularApp ..} ← read if !f.isApp then withKnowing false (forceRegularApp || !(← hasLevelMVarAtCurrDepth (← instantiateMVars fType))) $ withNaryFn (analyze (parentIsApp := true)) annotateNamedArg (n : Name) : AnalyzeAppM Unit := do annotateBool `pp.analysis.namedArg modify fun s => { s with namedArgs := s.namedArgs.push n } analyzeArg (i : Nat) := do let { f, args, mvars, bInfos, forceRegularApp ..} ← read let { bottomUps, higherOrders, funBinders, ..} ← get let arg := args[i]! let argType ← inferType arg let processNaturalImplicit : AnalyzeAppM Unit := do if (← valUnknown mvars[i]! <||> pure higherOrders[i]!) && !forceRegularApp then annotateNamedArg (← mvarName mvars[i]!) modify fun s => { s with provideds := s.provideds.set! i true } else annotateBool `pp.analysis.skip withNaryArg (f.getAppNumArgs + i) do withTheReader Context (fun ctx => { ctx with inBottomUp := ctx.inBottomUp || bottomUps[i]! }) do match bInfos[i]! with | BinderInfo.default => if ← pure (getPPAnalyzeExplicitHoles (← getOptions)) <&&> pure !(← valUnknown mvars[i]!) <&&> pure !(← readThe Context).inBottomUp <&&> pure !(← isFunLike arg) <&&> pure !funBinders[i]! <&&> checkpointDefEq mvars[i]! arg then annotateBool `pp.analysis.hole else modify fun s => { s with provideds := s.provideds.set! i true } | BinderInfo.implicit => processNaturalImplicit | BinderInfo.strictImplicit => processNaturalImplicit | BinderInfo.instImplicit => -- Note: apparently checking valUnknown here is not sound, because the elaborator -- will not happily assign instImplicits that it cannot synthesize let mut provided := true if !getPPInstances (← getOptions) then annotateBool `pp.analysis.skip provided := false else if getPPAnalyzeCheckInstances (← getOptions) then let instResult ← try trySynthInstance argType catch _ => pure LOption.undef match instResult with | LOption.some inst => if ← checkpointDefEq inst arg then annotateBool `pp.analysis.skip; provided := false else annotateNamedArg (← mvarName mvars[i]!) | _ => annotateNamedArg (← mvarName mvars[i]!) else annotateBool `pp.analysis.skip; provided := false modify fun s => { s with provideds := s.provideds.set! i provided } if (← get).provideds[i]! then withKnowing (not (← typeUnknown mvars[i]!)) true analyze tryUnify mvars[i]! args[i]! maybeSetExplicit := do let { f, args, bInfos, ..} ← read if (← get).namedArgs.any nameNotRoundtrippable then annotateBool `pp.explicit for i in [:args.size] do if !(← get).provideds[i]! then withNaryArg (f.getAppNumArgs + i) do annotateBool `pp.analysis.hole if bInfos[i]! == BinderInfo.instImplicit && getPPInstanceTypes (← getOptions) then withType (withKnowing true false analyze) end end TopDownAnalyze open TopDownAnalyze SubExpr def topDownAnalyze (e : Expr) : MetaM OptionsPerPos := do let s₀ ← get withTraceNode `pp.analyze (fun _ => return e) do withReader (fun ctx => { ctx with config := Elab.Term.setElabConfig ctx.config }) do let ϕ : AnalyzeM OptionsPerPos := do withNewMCtxDepth analyze; pure (← get).annotations try let knowsType := getPPAnalyzeKnowsType (← getOptions) ϕ { knowsType := knowsType, knowsLevel := knowsType, subExpr := mkRoot e } |>.run' { : TopDownAnalyze.State } catch e => trace[pp.analyze.error] "failed {e.toMessageData}" pure {} finally set s₀ builtin_initialize registerTraceClass `pp.analyze registerTraceClass `pp.analyze.annotate (inherited := true) registerTraceClass `pp.analyze.tryUnify (inherited := true) registerTraceClass `pp.analyze.error (inherited := true) end Lean.PrettyPrinter.Delaborator
813ec40548f9e88562618166de94efbb47ea56df
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/linear_algebra/finsupp.lean
4a852b5c12bedb99e99d5e890dbe4971c38f6803
[ "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
39,491
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.basic import linear_algebra.pi /-! # Properties of the module `α →₀ M` 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 } 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)) := 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 ⟨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).range) := begin refine disjoint.mono (lsingle_range_le_ker_lapply _ _ $ disjoint_compl_right) (lsingle_range_le_ker_lapply _ _ $ disjoint_compl_right) (le_trans (le_infi $ assume i, _) infi_ker_lapply_le_bot), classical, by_cases his : i ∈ s, { by_cases hit : i ∈ t, { exact (hs ⟨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) := 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 }, _, _, _ ⟩, { 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 p q hp hq, refine subset.trans (subset.trans (finset.coe_subset.2 support_add) _) (union_subset hp hq), rw [finset.coe_union] }, { 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, 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 x hx, _, disjoint_supported_supported⟩, rcases exists_ne (0 : M) with ⟨y, hy⟩, have := h ⟨single_mem_supported R y hx.1, single_mem_supported R y hx.2⟩, 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*) /-- 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 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 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 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] 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, unfold finsupp.sum, apply sum_mem (span R (range v)), exact λ 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] @[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] theorem total_map_domain (f : α → α') (hf : function.injective f) (l : α →₀ R) : (finsupp.total α' M' R v') (map_domain f l) = (finsupp.total α M' R (v' ∘ f)) l := begin have : map_domain f l = emb_domain ⟨f, hf⟩ l, { rw emb_domain_eq_map_domain ⟨f, hf⟩, refl }, rw this, apply total_emb_domain R ⟨f, hf⟩ l end @[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 _ _ f.injective] /-- 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 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, 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 := begin ext f i, simp only [equiv.symm_symm, finsupp.lcongr_apply_apply], apply finsupp.induction_linear f, { simp, }, { intros f g hf hg, simp [map_add, hf, hg], }, { intros k m, simp only [finsupp.lcongr_symm_single], simp only [finsupp.single, equiv.symm_apply_eq, finsupp.coe_mk], split_ifs; simp, }, end 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 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. -/ 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 := ((finsupp.mem_span_iff_total _ _ _).mp x.2).some_spec attribute [irreducible] span.repr end 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 := S.to_add_submonoid.finsupp_sum_mem 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 obtain ⟨f, hf, rfl⟩ : ∃ f ∈ finsupp.supported R R (⋃ i, ↑(p i)), finsupp.total M M R id f = m, { have aux : (id : M → M) '' (⋃ (i : ι), ↑(p i)) = (⋃ (i : ι), ↑(p i)) := set.image_id _, rwa [supr_eq_span, ← aux, finsupp.mem_span_image_iff_total R] at hm }, let t : finset M := f.support, have ht : ∀ x : {x // x ∈ t}, ∃ i, ↑x ∈ p i, { intros x, rw finsupp.mem_supported at hf, specialize hf x.2, rwa set.mem_Union at hf }, choose g hg using ht, let s : finset ι := finset.univ.image g, use s, simp only [mem_supr, supr_le_iff], assume N hN, rw [finsupp.total_apply, finsupp.sum, ← set_like.mem_coe], apply N.sum_mem, assume x hx, apply submodule.smul_mem, let i : ι := g ⟨x, hx⟩, have hi : i ∈ s, { rw finset.mem_image, exact ⟨⟨x, hx⟩, finset.mem_univ _, rfl⟩ }, exact hN i hi (hg _), 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_le_supr (λ 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_fintype 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_fintype_symm_single, finsupp.sum_single_index, one_smul, linear_map.id_coe, id_def, (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
3219e19627727ae733cd4b2488cd154878219b1e
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/measure_theory/category/Meas.lean
1b9f1dfec5e9f660113d43c3ffe107b0f31a1cbc
[ "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
4,155
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 topology.category.Top.basic import measure_theory.giry_monad import category_theory.monad.algebra /- * Meas, the category of measurable spaces Measurable spaces and measurable functions form a (concrete) category Meas. Measure : Meas ⥤ Meas is the functor which sends a measurable space X to the space of measures on X; it is a monad (the "Giry monad"). Borel : Top ⥤ Meas sends a topological space X to X equipped with the σ-algebra of Borel sets (the σ-algebra generated by the open subsets of X). ## Tags measurable space, giry monad, borel -/ noncomputable theory open category_theory measure_theory universes u v @[derive has_coe_to_sort] def Meas : Type (u+1) := bundled measurable_space namespace Meas instance (X : Meas) : measurable_space X := X.str /-- Construct a bundled `Meas` from the underlying type and the typeclass. -/ def of (α : Type u) [measurable_space α] : Meas := ⟨α⟩ instance unbundled_hom : unbundled_hom @measurable := ⟨@measurable_id, @measurable.comp⟩ attribute [derive [large_category, concrete_category]] Meas instance : inhabited Meas := ⟨Meas.of empty⟩ /-- `Measure X` is the measurable space of measures over the measurable space `X`. It is the weakest measurable space, s.t. λμ, μ s is measurable for all measurable sets `s` in `X`. An important purpose is to assign a monadic structure on it, the Giry monad. In the Giry monad, the pure values are the Dirac measure, and the bind operation maps to the integral: `(μ >>= ν) s = ∫ x. (ν x) s dμ`. In probability theory, the `Meas`-morphisms `X → Prob X` are (sub-)Markov kernels (here `Prob` is the restriction of `Measure` to (sub-)probability space.) -/ def Measure : Meas ⥤ Meas := { obj := λX, ⟨@measure_theory.measure X.1 X.2⟩, map := λX Y f, ⟨measure.map f, measure.measurable_map f f.2⟩, map_id' := assume ⟨α, I⟩, subtype.eq $ funext $ assume μ, @measure.map_id α I μ, map_comp':= assume X Y Z ⟨f, hf⟩ ⟨g, hg⟩, subtype.eq $ funext $ assume μ, (measure.map_map hg hf).symm } /-- The Giry monad, i.e. the monadic structure associated with `Measure`. -/ instance : category_theory.monad Measure.{u} := { η := { app := λX, ⟨@measure.dirac X.1 X.2, measure.measurable_dirac⟩, naturality' := assume X Y ⟨f, hf⟩, subtype.eq $ funext $ assume a, (measure.map_dirac hf a).symm }, μ := { app := λX, ⟨@measure.join X.1 X.2, measure.measurable_join⟩, naturality' := assume X Y ⟨f, hf⟩, subtype.eq $ funext $ assume μ, measure.join_map_map hf μ }, assoc' := assume ⟨α, I⟩, subtype.eq $ funext $ assume μ, @measure.join_map_join α I μ, left_unit' := assume ⟨α, I⟩, subtype.eq $ funext $ assume μ, @measure.join_dirac α I μ, right_unit' := assume ⟨α, I⟩, subtype.eq $ funext $ assume μ, @measure.join_map_dirac α I μ } /-- An example for an algebra on `Measure`: the nonnegative Lebesgue integral is a hom, behaving nicely under the monad operations. -/ def Integral : monad.algebra Measure := { A := Meas.of ennreal , a := ⟨ λm:measure ennreal, m.integral id, measure.measurable_integral _ measurable_id ⟩, unit' := subtype.eq $ funext $ assume r:ennreal, measure.integral_dirac _ measurable_id, assoc' := subtype.eq $ funext $ assume μ : measure (measure ennreal), show μ.join.integral id = measure.integral (μ.map (λm:measure ennreal, m.integral id)) id, from begin rw [measure.integral_join measurable_id, measure.integral_map measurable_id], refl, exact measure.measurable_integral _ measurable_id end } end Meas instance Top.has_forget_to_Meas : has_forget₂ Top.{u} Meas.{u} := bundled_hom.mk_has_forget₂ borel (λ X Y f, ⟨f.1, f.2.borel_measurable⟩) (by intros; refl) /-- The Borel functor, the canonical embedding of topological spaces into measurable spaces. -/ @[reducible] def Borel : Top.{u} ⥤ Meas.{u} := forget₂ Top.{u} Meas.{u}
cf7ddc02643fcca426a4aafc36f92a66533f9c80
ad0c7d243dc1bd563419e2767ed42fb323d7beea
/order/lattice.lean
c79a3c074940a3dc6e27a0dc328b848ad8aefb1a
[ "Apache-2.0" ]
permissive
sebzim4500/mathlib
e0b5a63b1655f910dee30badf09bd7e191d3cf30
6997cafbd3a7325af5cb318561768c316ceb7757
refs/heads/master
1,585,549,958,618
1,538,221,723,000
1,538,221,723,000
150,869,076
0
0
Apache-2.0
1,538,229,323,000
1,538,229,323,000
null
UTF-8
Lean
false
false
12,494
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 Defines the inf/sup (semi)-lattice with optionally top/bot type class hierarchy. -/ import order.basic set_option old_structure_cmd true universes u v w -- TODO: move this eventually, if we decide to use them attribute [ematch] le_trans lt_of_le_of_lt lt_of_lt_of_le lt_trans section variable {α : Type u} -- TODO: this seems crazy, but it also seems to work reasonably well @[ematch] theorem le_antisymm' [partial_order α] : ∀ {a b : α}, (: a ≤ b :) → b ≤ a → a = b := @le_antisymm _ _ end /- TODO: automatic construction of dual definitions / theorems -/ namespace lattice reserve infixl ` ⊓ `:70 reserve infixl ` ⊔ `:65 /-- Typeclass for the `⊔` (`\lub`) notation -/ class has_sup (α : Type u) := (sup : α → α → α) /-- Typeclass for the `⊓` (`\glb`) notation -/ class has_inf (α : Type u) := (inf : α → α → α) infix ⊔ := has_sup.sup infix ⊓ := has_inf.inf /-- A `semilattice_sup` is a join-semilattice, that is, a partial order with a join (a.k.a. lub / least upper bound, sup / supremum) operation `⊔` which is the least element larger than both factors. -/ class semilattice_sup (α : Type u) extends has_sup α, partial_order α := (le_sup_left : ∀ a b : α, a ≤ a ⊔ b) (le_sup_right : ∀ a b : α, b ≤ a ⊔ b) (sup_le : ∀ a b c : α, a ≤ c → b ≤ c → a ⊔ b ≤ c) section semilattice_sup variables {α : Type u} [semilattice_sup α] {a b c d : α} @[simp] theorem le_sup_left : a ≤ a ⊔ b := semilattice_sup.le_sup_left a b @[ematch] theorem le_sup_left' : a ≤ (: a ⊔ b :) := semilattice_sup.le_sup_left a b @[simp] theorem le_sup_right : b ≤ a ⊔ b := semilattice_sup.le_sup_right a b @[ematch] theorem le_sup_right' : b ≤ (: a ⊔ b :) := semilattice_sup.le_sup_right a b theorem le_sup_left_of_le (h : c ≤ a) : c ≤ a ⊔ b := by finish theorem le_sup_right_of_le (h : c ≤ b) : c ≤ a ⊔ b := by finish theorem sup_le : a ≤ c → b ≤ c → a ⊔ b ≤ c := semilattice_sup.sup_le a b c @[simp] theorem sup_le_iff : a ⊔ b ≤ c ↔ a ≤ c ∧ b ≤ c := ⟨assume h : a ⊔ b ≤ c, ⟨le_trans le_sup_left h, le_trans le_sup_right h⟩, assume ⟨h₁, h₂⟩, sup_le h₁ h₂⟩ -- TODO: if we just write le_antisymm, Lean doesn't know which ≤ we want to use -- Can we do anything about that? theorem sup_of_le_left (h : b ≤ a) : a ⊔ b = a := by apply le_antisymm; finish theorem sup_of_le_right (h : a ≤ b) : a ⊔ b = b := by apply le_antisymm; finish theorem sup_le_sup (h₁ : a ≤ b) (h₂ : c ≤ d) : a ⊔ c ≤ b ⊔ d := by finish theorem sup_le_sup_left (h₁ : a ≤ b) (c) : c ⊔ a ≤ c ⊔ b := by finish theorem sup_le_sup_right (h₁ : a ≤ b) (c) : a ⊔ c ≤ b ⊔ c := by finish theorem le_of_sup_eq (h : a ⊔ b = b) : a ≤ b := by finish @[simp] theorem sup_idem : a ⊔ a = a := by apply le_antisymm; finish instance sup_is_idempotent : is_idempotent α (⊔) := ⟨@sup_idem _ _⟩ theorem sup_comm : a ⊔ b = b ⊔ a := by apply le_antisymm; finish instance sup_is_commutative : is_commutative α (⊔) := ⟨@sup_comm _ _⟩ theorem sup_assoc : a ⊔ b ⊔ c = a ⊔ (b ⊔ c) := by apply le_antisymm; finish instance sup_is_associative : is_associative α (⊔) := ⟨@sup_assoc _ _⟩ lemma forall_le_or_exists_lt_sup (a : α) : (∀b, b ≤ a) ∨ (∃b, a < b) := suffices (∃b, ¬b ≤ a) → (∃b, a < b), by rwa [classical.or_iff_not_imp_left, classical.not_forall], assume ⟨b, hb⟩, have a ≠ a ⊔ b, from assume eq, hb $ eq.symm ▸ le_sup_right, ⟨a ⊔ b, lt_of_le_of_ne le_sup_left ‹a ≠ a ⊔ b›⟩ theorem semilattice_sup.ext_sup {α} {A B : semilattice_sup α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) (x y : α) : (by haveI := A; exact (x ⊔ y)) = x ⊔ y := eq_of_forall_ge_iff $ λ c, by simp; rw [← H, @sup_le_iff α A, H, H] theorem semilattice_sup.ext {α} {A B : semilattice_sup α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin haveI this := partial_order.ext H, have ss := funext (λ x, funext $ semilattice_sup.ext_sup H x), cases A; cases B; injection this; congr' end end semilattice_sup /-- A `semilattice_inf` is a meet-semilattice, that is, a partial order with a meet (a.k.a. glb / greatest lower bound, inf / infimum) operation `⊓` which is the greatest element smaller than both factors. -/ class semilattice_inf (α : Type u) extends has_inf α, partial_order α := (inf_le_left : ∀ a b : α, a ⊓ b ≤ a) (inf_le_right : ∀ a b : α, a ⊓ b ≤ b) (le_inf : ∀ a b c : α, a ≤ b → a ≤ c → a ≤ b ⊓ c) section semilattice_inf variables {α : Type u} [semilattice_inf α] {a b c d : α} @[simp] theorem inf_le_left : a ⊓ b ≤ a := semilattice_inf.inf_le_left a b @[ematch] theorem inf_le_left' : (: a ⊓ b :) ≤ a := semilattice_inf.inf_le_left a b @[simp] theorem inf_le_right : a ⊓ b ≤ b := semilattice_inf.inf_le_right a b @[ematch] theorem inf_le_right' : (: a ⊓ b :) ≤ b := semilattice_inf.inf_le_right a b theorem le_inf : a ≤ b → a ≤ c → a ≤ b ⊓ c := semilattice_inf.le_inf a b c theorem inf_le_left_of_le (h : a ≤ c) : a ⊓ b ≤ c := le_trans inf_le_left h theorem inf_le_right_of_le (h : b ≤ c) : a ⊓ b ≤ c := le_trans inf_le_right h @[simp] theorem le_inf_iff : a ≤ b ⊓ c ↔ a ≤ b ∧ a ≤ c := ⟨assume h : a ≤ b ⊓ c, ⟨le_trans h inf_le_left, le_trans h inf_le_right⟩, assume ⟨h₁, h₂⟩, le_inf h₁ h₂⟩ theorem inf_of_le_left (h : a ≤ b) : a ⊓ b = a := by apply le_antisymm; finish theorem inf_of_le_right (h : b ≤ a) : a ⊓ b = b := by apply le_antisymm; finish theorem inf_le_inf (h₁ : a ≤ b) (h₂ : c ≤ d) : a ⊓ c ≤ b ⊓ d := by finish theorem le_of_inf_eq (h : a ⊓ b = a) : a ≤ b := by finish @[simp] theorem inf_idem : a ⊓ a = a := by apply le_antisymm; finish instance inf_is_idempotent : is_idempotent α (⊓) := ⟨@inf_idem _ _⟩ theorem inf_comm : a ⊓ b = b ⊓ a := by apply le_antisymm; finish instance inf_is_commutative : is_commutative α (⊓) := ⟨@inf_comm _ _⟩ theorem inf_assoc : a ⊓ b ⊓ c = a ⊓ (b ⊓ c) := by apply le_antisymm; finish instance inf_is_associative : is_associative α (⊓) := ⟨@inf_assoc _ _⟩ lemma forall_le_or_exists_lt_inf (a : α) : (∀b, a ≤ b) ∨ (∃b, b < a) := suffices (∃b, ¬a ≤ b) → (∃b, b < a), by rwa [classical.or_iff_not_imp_left, classical.not_forall], assume ⟨b, hb⟩, have a ⊓ b ≠ a, from assume eq, hb $ eq ▸ inf_le_right, ⟨a ⊓ b, lt_of_le_of_ne inf_le_left ‹a ⊓ b ≠ a›⟩ theorem semilattice_inf.ext_inf {α} {A B : semilattice_inf α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) (x y : α) : (by haveI := A; exact (x ⊓ y)) = x ⊓ y := eq_of_forall_le_iff $ λ c, by simp; rw [← H, @le_inf_iff α A, H, H] theorem semilattice_inf.ext {α} {A B : semilattice_inf α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin haveI this := partial_order.ext H, have ss := funext (λ x, funext $ semilattice_inf.ext_inf H x), cases A; cases B; injection this; congr' end end semilattice_inf /- Lattices -/ /-- A lattice is a join-semilattice which is also a meet-semilattice. -/ class lattice (α : Type u) extends semilattice_sup α, semilattice_inf α section lattice variables {α : Type u} [lattice α] {a b c d : α} /- Distributivity laws -/ /- TODO: better names? -/ theorem sup_inf_le : a ⊔ (b ⊓ c) ≤ (a ⊔ b) ⊓ (a ⊔ c) := by finish theorem le_inf_sup : (a ⊓ b) ⊔ (a ⊓ c) ≤ a ⊓ (b ⊔ c) := by finish theorem inf_sup_self : a ⊓ (a ⊔ b) = a := le_antisymm (by finish) (by finish) theorem sup_inf_self : a ⊔ (a ⊓ b) = a := le_antisymm (by finish) (by finish) theorem lattice.ext {α} {A B : lattice α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have SS : @lattice.to_semilattice_sup α A = @lattice.to_semilattice_sup α B := semilattice_sup.ext H, have II := semilattice_inf.ext H, resetI, cases A; cases B; injection SS; injection II; congr' end end lattice variables {α : Type u} {x y z w : α} /-- A distributive lattice is a lattice that satisfies any of four equivalent distribution properties (of sup over inf or inf over sup, on the left or right). A classic example of a distributive lattice is the lattice of subsets of a set, and in fact this example is generic in the sense that every distributive lattice is realizable as a sublattice of a powerset lattice. -/ class distrib_lattice α extends lattice α := (le_sup_inf : ∀x y z : α, (x ⊔ y) ⊓ (x ⊔ z) ≤ x ⊔ (y ⊓ z)) section distrib_lattice variables [distrib_lattice α] theorem le_sup_inf : ∀{x y z : α}, (x ⊔ y) ⊓ (x ⊔ z) ≤ x ⊔ (y ⊓ z) := distrib_lattice.le_sup_inf theorem sup_inf_left : x ⊔ (y ⊓ z) = (x ⊔ y) ⊓ (x ⊔ z) := le_antisymm sup_inf_le le_sup_inf theorem sup_inf_right : (y ⊓ z) ⊔ x = (y ⊔ x) ⊓ (z ⊔ x) := by simp [sup_inf_left, λy:α, @sup_comm α _ y x] theorem inf_sup_left : x ⊓ (y ⊔ z) = (x ⊓ y) ⊔ (x ⊓ z) := calc x ⊓ (y ⊔ z) = (x ⊓ (x ⊔ z)) ⊓ (y ⊔ z) : by rw [inf_sup_self] ... = x ⊓ ((x ⊓ y) ⊔ z) : by simp [inf_assoc, sup_inf_right] ... = (x ⊔ (x ⊓ y)) ⊓ ((x ⊓ y) ⊔ z) : by rw [sup_inf_self] ... = ((x ⊓ y) ⊔ x) ⊓ ((x ⊓ y) ⊔ z) : by rw [sup_comm] ... = (x ⊓ y) ⊔ (x ⊓ z) : by rw [sup_inf_left] theorem inf_sup_right : (y ⊔ z) ⊓ x = (y ⊓ x) ⊔ (z ⊓ x) := by simp [inf_sup_left, λy:α, @inf_comm α _ y x] lemma eq_of_sup_eq_inf_eq {α : Type u} [distrib_lattice α] {a b c : α} (h₁ : b ⊓ a = c ⊓ a) (h₂ : b ⊔ a = c ⊔ a) : b = c := le_antisymm (calc b ≤ (c ⊓ a) ⊔ b : le_sup_right ... = (c ⊔ b) ⊓ (a ⊔ b) : sup_inf_right ... = c ⊔ (c ⊓ a) : by rw [←h₁, sup_inf_left, ←h₂]; simp [sup_comm] ... = c : sup_inf_self) (calc c ≤ (b ⊓ a) ⊔ c : le_sup_right ... = (b ⊔ c) ⊓ (a ⊔ c) : sup_inf_right ... = b ⊔ (b ⊓ a) : by rw [h₁, sup_inf_left, h₂]; simp [sup_comm] ... = b : sup_inf_self) end distrib_lattice /- Lattices derived from linear orders -/ instance lattice_of_decidable_linear_order {α : Type u} [o : decidable_linear_order α] : lattice α := { sup := max, le_sup_left := le_max_left, le_sup_right := le_max_right, sup_le := assume a b c, max_le, inf := min, inf_le_left := min_le_left, inf_le_right := min_le_right, le_inf := assume a b c, le_min, ..o } theorem sup_eq_max [decidable_linear_order α] : x ⊔ y = max x y := rfl theorem inf_eq_min [decidable_linear_order α] : x ⊓ y = min x y := rfl instance distrib_lattice_of_decidable_linear_order {α : Type u} [o : decidable_linear_order α] : distrib_lattice α := { le_sup_inf := assume a b c, match le_total b c with | or.inl h := inf_le_left_of_le $ sup_le_sup_left (le_inf (le_refl b) h) _ | or.inr h := inf_le_right_of_le $ sup_le_sup_left (le_inf h (le_refl c)) _ end, ..lattice.lattice_of_decidable_linear_order } instance nat.distrib_lattice : distrib_lattice ℕ := by apply_instance end lattice namespace order_dual open lattice variable (α : Type*) instance [has_inf α] : has_sup (order_dual α) := ⟨((⊓) : α → α → α)⟩ instance [has_sup α] : has_inf (order_dual α) := ⟨((⊔) : α → α → α)⟩ instance [semilattice_inf α] : semilattice_sup (order_dual α) := { le_sup_left := @inf_le_left α _, le_sup_right := @inf_le_right α _, sup_le := assume a b c hca hcb, @le_inf α _ _ _ _ hca hcb, .. order_dual.partial_order α, .. order_dual.lattice.has_sup α } instance [semilattice_sup α] : semilattice_inf (order_dual α) := { inf_le_left := @le_sup_left α _, inf_le_right := @le_sup_right α _, le_inf := assume a b c hca hcb, @sup_le α _ _ _ _ hca hcb, .. order_dual.partial_order α, .. order_dual.lattice.has_inf α } instance [lattice α] : lattice (order_dual α) := { .. order_dual.lattice.semilattice_sup α, .. order_dual.lattice.semilattice_inf α } end order_dual
5bed367b1ee5bd4bb5a02ac3a1f0b679ab310b99
63abd62053d479eae5abf4951554e1064a4c45b4
/src/topology/topological_fiber_bundle.lean
58ea46990a155aefb0daa15a4dc24805370607a4
[ "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
25,513
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 topology.local_homeomorph /-! # Fiber bundles A topological fiber bundle with fiber `F` over a base `B` is a space projecting on `B` for which the fibers are all homeomorphic to `F`, such that the local situation around each point is a direct product. We define a predicate `is_topological_fiber_bundle F p` saying that `p : Z → B` is a topological fiber bundle with fiber `F`. It is in general nontrivial to construct a fiber bundle. A way is to start from the knowledge of how changes of local trivializations act on the fiber. From this, one can construct the total space of the bundle and its topology by a suitable gluing construction. The main content of this file is an implementation of this construction: starting from an object of type `topological_fiber_bundle_core` registering the trivialization changes, one gets the corresponding fiber bundle and projection. ## Main definitions * `bundle_trivialization F p` : structure extending local homeomorphisms, defining a local trivialization of a topological space `Z` with projection `p` and fiber `F`. * `is_topological_fiber_bundle F p` : Prop saying that the map `p` between topological spaces is a fiber bundle with fiber `F`. * `topological_fiber_bundle_core ι B F` : structure registering how changes of coordinates act on the fiber `F` above open subsets of `B`, where local trivializations are indexed by `ι`. Let `Z : topological_fiber_bundle_core ι B F`. Then we define * `Z.total_space` : the total space of `Z`, defined as a `Type` as `Σ (b : B), F`, but with a twisted topology coming from the fiber bundle structure * `Z.proj` : projection from `Z.total_space` to `B`. It is continuous. * `Z.fiber x` : the fiber above `x`, homeomorphic to `F` (and defeq to `F` as a type). * `Z.local_triv i`: for `i : ι`, a local homeomorphism from `Z.total_space` to `B × F`, that realizes a trivialization above the set `Z.base_set i`, which is an open set in `B`. ## Implementation notes A topological fiber bundle with fiber `F` over a base `B` is a family of spaces isomorphic to `F`, indexed by `B`, which is locally trivial in the following sense: there is a covering of `B` by open sets such that, on each such open set `s`, the bundle is isomorphic to `s × F`. To construct a fiber bundle formally, the main data is what happens when one changes trivializations from `s × F` to `s' × F` on `s ∩ s'`: one should get a family of homeomorphisms of `F`, depending continuously on the base point, satisfying basic compatibility conditions (cocycle property). Useful classes of bundles can then be specified by requiring that these homeomorphisms of `F` belong to some subgroup, preserving some structure (the "structure group of the bundle"): then these structures are inherited by the fibers of the bundle. Given such trivialization change data (encoded below in a structure called `topological_fiber_bundle_core`), one can construct the fiber bundle. The intrinsic canonical mathematical construction is the following. The fiber above `x` is the disjoint union of `F` over all trivializations, modulo the gluing identifications: one gets a fiber which is isomorphic to `F`, but non-canonically (each choice of one of the trivializations around `x` gives such an isomorphism). Given a trivialization over a set `s`, one gets an isomorphism between `s × F` and `proj^{-1} s`, by using the identification corresponding to this trivialization. One chooses the topology on the bundle that makes all of these into homeomorphisms. For the practical implementation, it turns out to be more convenient to avoid completely the gluing and quotienting construction above, and to declare above each `x` that the fiber is `F`, but thinking that it corresponds to the `F` coming from the choice of one trivialization around `x`. This has several practical advantages: * without any work, one gets a topological space structure on the fiber. And if `F` has more structure it is inherited for free by the fiber. * In the case of the tangent bundle of manifolds, this implies that on vector spaces the derivative (from `F` to `F`) and the manifold derivative (from `tangent_space I x` to `tangent_space I' (f x)`) are equal. A drawback is that some silly constructions will typecheck: in the case of the tangent bundle, one can add two vectors in different tangent spaces (as they both are elements of `F` from the point of view of Lean). To solve this, one could mark the tangent space as irreducible, but then one would lose the identification of the tangent space to `F` with `F`. There is however a big advantage of this situation: even if Lean can not check that two basepoints are defeq, it will accept the fact that the tangent spaces are the same. For instance, if two maps `f` and `g` are locally inverse to each other, one can express that the composition of their derivatives is the identity of `tangent_space I x`. One could fear issues as this composition goes from `tangent_space I x` to `tangent_space I (g (f x))` (which should be the same, but should not be obvious to Lean as it does not know that `g (f x) = x`). As these types are the same to Lean (equal to `F`), there are in fact no dependent type difficulties here! For this construction of a fiber bundle from a `topological_fiber_bundle_core`, we should thus choose for each `x` one specific trivialization around it. We include this choice in the definition of the `topological_fiber_bundle_core`, as it makes some constructions more functorial and it is a nice way to say that the trivializations cover the whole space `B`. With this definition, the type of the fiber bundle space constructed from the core data is just `Σ (b : B), F `, but the topology is not the product one, in general. We also take the indexing type (indexing all the trivializations) as a parameter to the fiber bundle core: it could always be taken as a subtype of all the maps from open subsets of `B` to continuous maps of `F`, but in practice it will sometimes be something else. For instance, on a manifold, one will use the set of charts as a good parameterization for the trivializations of the tangent bundle. Or for the pullback of a `topological_fiber_bundle_core`, the indexing type will be the same as for the initial bundle. ## Tags Fiber bundle, topological bundle, vector bundle, local trivialization, structure group -/ variables {ι : Type*} {B : Type*} {F : Type*} open topological_space set open_locale topological_space section topological_fiber_bundle variables {Z : Type*} [topological_space B] [topological_space Z] [topological_space F] (proj : Z → B) variable (F) /-- A structure extending local homeomorphisms, defining a local trivialization of a projection `proj : Z → B` with fiber `F`, as a local homeomorphism between `Z` and `B × F` defined between two sets of the form `proj ⁻¹' base_set` and `base_set × F`, acting trivially on the first coordinate. -/ structure bundle_trivialization extends local_homeomorph Z (B × F) := (base_set : set B) (open_base_set : is_open base_set) (source_eq : source = proj ⁻¹' base_set) (target_eq : target = set.prod base_set univ) (proj_to_fun : ∀ p ∈ source, (to_fun p).1 = proj p) instance : has_coe_to_fun (bundle_trivialization F proj) := ⟨_, λ e, e.to_fun⟩ @[simp, mfld_simps] lemma bundle_trivialization.coe_coe (e : bundle_trivialization F proj) (x : Z) : e.to_local_homeomorph x = e x := rfl @[simp, mfld_simps] lemma bundle_trivialization.coe_mk (e : local_homeomorph Z (B × F)) (i j k l m) (x : Z) : (bundle_trivialization.mk e i j k l m : bundle_trivialization F proj) x = e x := rfl /-- A topological fiber bundle with fiber F over a base B is a space projecting on B for which the fibers are all homeomorphic to F, such that the local situation around each point is a direct product. -/ def is_topological_fiber_bundle : Prop := ∀ x : Z, ∃e : bundle_trivialization F proj, x ∈ e.source variables {F} {proj} @[simp, mfld_simps] lemma bundle_trivialization.coe_fst (e : bundle_trivialization F proj) {x : Z} (ex : x ∈ e.source) : (e x).1 = proj x := e.proj_to_fun x ex /-- In the domain of a bundle trivialization, the projection is continuous-/ lemma bundle_trivialization.continuous_at_proj (e : bundle_trivialization F proj) {x : Z} (ex : x ∈ e.source) : continuous_at proj x := begin assume s hs, obtain ⟨t, st, t_open, xt⟩ : ∃ t ⊆ s, is_open t ∧ proj x ∈ t, from mem_nhds_sets_iff.1 hs, rw e.source_eq at ex, let u := e.base_set ∩ t, have u_open : is_open u := is_open_inter e.open_base_set t_open, have xu : proj x ∈ u := ⟨ex, xt⟩, /- Take a small enough open neighborhood u of `proj x`, contained in a trivialization domain o. One should show that its preimage is open. -/ suffices : is_open (proj ⁻¹' u), { have : proj ⁻¹' u ∈ 𝓝 x := mem_nhds_sets this xu, apply filter.mem_sets_of_superset this, exact preimage_mono (subset.trans (inter_subset_right _ _) st) }, -- to do this, rewrite `proj ⁻¹' u` in terms of the trivialization, and use its continuity. have : proj ⁻¹' u = e ⁻¹' (set.prod u univ) ∩ e.source, { ext p, split, { assume h, have : p ∈ e.source, { rw e.source_eq, have : u ⊆ e.base_set := inter_subset_left _ _, exact preimage_mono this h }, simp [this, h.1, h.2], }, { rintros ⟨h, h_source⟩, simpa [h_source] using h } }, rw [this, inter_comm], exact continuous_on.preimage_open_of_open e.continuous_to_fun e.open_source (u_open.prod is_open_univ) end /-- The projection from a topological fiber bundle to its base is continuous. -/ lemma is_topological_fiber_bundle.continuous_proj (h : is_topological_fiber_bundle F proj) : continuous proj := begin rw continuous_iff_continuous_at, assume x, rcases h x with ⟨e, ex⟩, exact e.continuous_at_proj ex end /-- The projection from a topological fiber bundle to its base is an open map. -/ lemma is_topological_fiber_bundle.is_open_map_proj (h : is_topological_fiber_bundle F proj) : is_open_map proj := begin assume s hs, rw is_open_iff_forall_mem_open, assume x xs, obtain ⟨y, ys, yx⟩ : ∃ y, y ∈ s ∧ proj y = x, from (mem_image _ _ _).1 xs, obtain ⟨e, he⟩ : ∃ (e : bundle_trivialization F proj), y ∈ e.source, from h y, refine ⟨proj '' (s ∩ e.source), image_subset _ (inter_subset_left _ _), _, ⟨y, ⟨ys, he⟩, yx⟩⟩, have : ∀z ∈ s ∩ e.source, prod.fst (e z) = proj z := λz hz, e.proj_to_fun z hz.2, rw [← image_congr this, image_comp], have : is_open (e '' (s ∩ e.source)) := e.to_local_homeomorph.image_open_of_open (is_open_inter hs e.to_local_homeomorph.open_source) (inter_subset_right _ _), exact is_open_map_fst _ this end /-- The first projection in a product is a topological fiber bundle. -/ lemma is_topological_fiber_bundle_fst : is_topological_fiber_bundle F (prod.fst : B × F → B) := begin let F : bundle_trivialization F (prod.fst : B × F → B) := { base_set := univ, open_base_set := is_open_univ, source_eq := rfl, target_eq := by simp, proj_to_fun := by simp, ..local_homeomorph.refl _ }, exact λx, ⟨F, by simp⟩ end /-- The second projection in a product is a topological fiber bundle. -/ lemma is_topological_fiber_bundle_snd : is_topological_fiber_bundle F (prod.snd : F × B → B) := begin let F : bundle_trivialization F (prod.snd : F × B → B) := { base_set := univ, open_base_set := is_open_univ, source_eq := rfl, target_eq := by simp, proj_to_fun := λp, by { simp, refl }, ..(homeomorph.prod_comm F B).to_local_homeomorph }, exact λx, ⟨F, by simp⟩ end end topological_fiber_bundle /-- Core data defining a locally trivial topological bundle with fiber `F` over a topological space `B`. Note that "bundle" is used in its mathematical sense. This is the (computer science) bundled version, i.e., all the relevant data is contained in the following structure. A family of local trivializations is indexed by a type ι, on open subsets `base_set i` for each `i : ι`. Trivialization changes from `i` to `j` are given by continuous maps `coord_change i j` from `base_set i ∩ base_set j` to the set of homeomorphisms of `F`, but we express them as maps `B → F → F` and require continuity on `(base_set i ∩ base_set j) × F` to avoid the topology on the space of continuous maps on `F`. -/ structure topological_fiber_bundle_core (ι : Type*) (B : Type*) [topological_space B] (F : Type*) [topological_space F] := (base_set : ι → set B) (is_open_base_set : ∀i, is_open (base_set i)) (index_at : B → ι) (mem_base_set_at : ∀x, x ∈ base_set (index_at x)) (coord_change : ι → ι → B → F → F) (coord_change_self : ∀i, ∀ x ∈ base_set i, ∀v, coord_change i i x v = v) (coord_change_continuous : ∀i j, continuous_on (λp : B × F, coord_change i j p.1 p.2) (set.prod ((base_set i) ∩ (base_set j)) univ)) (coord_change_comp : ∀i j k, ∀x ∈ (base_set i) ∩ (base_set j) ∩ (base_set k), ∀v, (coord_change j k x) (coord_change i j x v) = coord_change i k x v) attribute [simp, mfld_simps] topological_fiber_bundle_core.mem_base_set_at namespace topological_fiber_bundle_core variables [topological_space B] [topological_space F] (Z : topological_fiber_bundle_core ι B F) include Z /-- The index set of a topological fiber bundle core, as a convenience function for dot notation -/ @[nolint unused_arguments] def index := ι /-- The base space of a topological fiber bundle core, as a convenience function for dot notation -/ @[nolint unused_arguments] def base := B /-- The fiber of a topological fiber bundle core, as a convenience function for dot notation and typeclass inference -/ @[nolint unused_arguments] def fiber (x : B) := F instance topological_space_fiber (x : B) : topological_space (Z.fiber x) := by { dsimp [fiber], apply_instance } /-- Total space of a topological bundle created from core. It is equal to `Σ (x : B), F` as a type, but the fiber above `x` is registered as `Z.fiber x` to make sure that it is possible to register additional type classes on these fibers. -/ @[nolint unused_arguments] def total_space := Σ (x : B), Z.fiber x /-- The projection from the total space of a topological fiber bundle core, on its base. -/ @[simp, mfld_simps] def proj : Z.total_space → B := λp, p.1 /-- Local homeomorphism version of the trivialization change. -/ def triv_change (i j : ι) : local_homeomorph (B × F) (B × F) := { source := set.prod (Z.base_set i ∩ Z.base_set j) univ, target := set.prod (Z.base_set i ∩ Z.base_set j) univ, to_fun := λp, ⟨p.1, Z.coord_change i j p.1 p.2⟩, inv_fun := λp, ⟨p.1, Z.coord_change j i p.1 p.2⟩, map_source' := λp hp, by simpa using hp, map_target' := λp hp, by simpa using hp, left_inv' := begin rintros ⟨x, v⟩ hx, simp only [prod_mk_mem_set_prod_eq, mem_inter_eq, and_true, mem_univ] at hx, rw [Z.coord_change_comp, Z.coord_change_self], { exact hx.1 }, { simp [hx] } end, right_inv' := begin rintros ⟨x, v⟩ hx, simp only [prod_mk_mem_set_prod_eq, mem_inter_eq, and_true, mem_univ] at hx, rw [Z.coord_change_comp, Z.coord_change_self], { exact hx.2 }, { simp [hx] }, end, open_source := (is_open_inter (Z.is_open_base_set i) (Z.is_open_base_set j)).prod is_open_univ, open_target := (is_open_inter (Z.is_open_base_set i) (Z.is_open_base_set j)).prod is_open_univ, continuous_to_fun := continuous_on.prod continuous_fst.continuous_on (Z.coord_change_continuous i j), continuous_inv_fun := by simpa [inter_comm] using continuous_on.prod continuous_fst.continuous_on (Z.coord_change_continuous j i) } @[simp, mfld_simps] lemma mem_triv_change_source (i j : ι) (p : B × F) : p ∈ (Z.triv_change i j).source ↔ p.1 ∈ Z.base_set i ∩ Z.base_set j := by { erw [mem_prod], simp } /-- Associate to a trivialization index `i : ι` the corresponding trivialization, i.e., a bijection between `proj ⁻¹ (base_set i)` and `base_set i × F`. As the fiber above `x` is `F` but read in the chart with index `index_at x`, the trivialization in the fiber above x is by definition the coordinate change from i to `index_at x`, so it depends on `x`. The local trivialization will ultimately be a local homeomorphism. For now, we only introduce the local equiv version, denoted with a prime. In further developments, avoid this auxiliary version, and use Z.local_triv instead. -/ def local_triv' (i : ι) : local_equiv Z.total_space (B × F) := { source := Z.proj ⁻¹' (Z.base_set i), target := set.prod (Z.base_set i) univ, inv_fun := λp, ⟨p.1, Z.coord_change i (Z.index_at p.1) p.1 p.2⟩, to_fun := λp, ⟨p.1, Z.coord_change (Z.index_at p.1) i p.1 p.2⟩, map_source' := λp hp, by simpa only [set.mem_preimage, and_true, set.mem_univ, set.prod_mk_mem_set_prod_eq] using hp, map_target' := λp hp, by simpa only [set.mem_preimage, and_true, set.mem_univ, set.mem_prod] using hp, left_inv' := begin rintros ⟨x, v⟩ hx, change x ∈ Z.base_set i at hx, dsimp, rw [Z.coord_change_comp, Z.coord_change_self], { exact Z.mem_base_set_at _ }, { simp [hx] } end, right_inv' := begin rintros ⟨x, v⟩ hx, simp only [prod_mk_mem_set_prod_eq, and_true, mem_univ] at hx, rw [Z.coord_change_comp, Z.coord_change_self], { exact hx }, { simp [hx] } end } @[simp, mfld_simps] lemma mem_local_triv'_source (i : ι) (p : Z.total_space) : p ∈ (Z.local_triv' i).source ↔ p.1 ∈ Z.base_set i := by refl @[simp, mfld_simps] lemma mem_local_triv'_target (i : ι) (p : B × F) : p ∈ (Z.local_triv' i).target ↔ p.1 ∈ Z.base_set i := by { erw [mem_prod], simp } @[simp, mfld_simps] lemma local_triv'_apply (i : ι) (p : Z.total_space) : (Z.local_triv' i) p = ⟨p.1, Z.coord_change (Z.index_at p.1) i p.1 p.2⟩ := rfl @[simp, mfld_simps] lemma local_triv'_symm_apply (i : ι) (p : B × F) : (Z.local_triv' i).symm p = ⟨p.1, Z.coord_change i (Z.index_at p.1) p.1 p.2⟩ := rfl /-- The composition of two local trivializations is the trivialization change Z.triv_change i j. -/ lemma local_triv'_trans (i j : ι) : (Z.local_triv' i).symm.trans (Z.local_triv' j) ≈ (Z.triv_change i j).to_local_equiv := begin split, { ext x, erw [mem_prod], simp [local_equiv.trans_source] }, { rintros ⟨x, v⟩ hx, simp only [triv_change, local_triv', local_equiv.symm, true_and, prod_mk_mem_set_prod_eq, local_equiv.trans_source, mem_inter_eq, and_true, mem_univ, prod.mk.inj_iff, mem_preimage, proj, local_equiv.coe_mk, eq_self_iff_true, local_equiv.coe_trans] at hx ⊢, simp [Z.coord_change_comp, hx] } end /-- Topological structure on the total space of a topological bundle created from core, designed so that all the local trivialization are continuous. -/ instance to_topological_space : topological_space Z.total_space := topological_space.generate_from $ ⋃ (i : ι) (s : set (B × F)) (s_open : is_open s), {(Z.local_triv' i).source ∩ (Z.local_triv' i) ⁻¹' s} lemma open_source' (i : ι) : is_open (Z.local_triv' i).source := begin apply topological_space.generate_open.basic, simp only [exists_prop, mem_Union, mem_singleton_iff], refine ⟨i, set.prod (Z.base_set i) univ, (Z.is_open_base_set i).prod is_open_univ, _⟩, ext p, simp only with mfld_simps end lemma open_target' (i : ι) : is_open (Z.local_triv' i).target := (Z.is_open_base_set i).prod is_open_univ /-- Local trivialization of a topological bundle created from core, as a local homeomorphism. -/ def local_triv (i : ι) : local_homeomorph Z.total_space (B × F) := { open_source := Z.open_source' i, open_target := Z.open_target' i, continuous_to_fun := begin rw continuous_on_open_iff (Z.open_source' i), assume s s_open, apply topological_space.generate_open.basic, simp only [exists_prop, mem_Union, mem_singleton_iff], exact ⟨i, s, s_open, rfl⟩ end, continuous_inv_fun := begin apply continuous_on_open_of_generate_from (Z.open_target' i), assume t ht, simp only [exists_prop, mem_Union, mem_singleton_iff] at ht, obtain ⟨j, s, s_open, ts⟩ : ∃ j s, is_open s ∧ t = (local_triv' Z j).source ∩ (local_triv' Z j) ⁻¹' s := ht, rw ts, simp only [local_equiv.right_inv, preimage_inter, local_equiv.left_inv], let e := Z.local_triv' i, let e' := Z.local_triv' j, let f := e.symm.trans e', have : is_open (f.source ∩ f ⁻¹' s), { rw [(Z.local_triv'_trans i j).source_inter_preimage_eq], exact (continuous_on_open_iff (Z.triv_change i j).open_source).1 ((Z.triv_change i j).continuous_on) _ s_open }, convert this using 1, dsimp [local_equiv.trans_source], rw [← preimage_comp, inter_assoc] end, ..Z.local_triv' i } /- We will now state again the basic properties of the local trivializations, but without primes, i.e., for the local homeomorphism instead of the local equiv. -/ @[simp, mfld_simps] lemma mem_local_triv_source (i : ι) (p : Z.total_space) : p ∈ (Z.local_triv i).source ↔ p.1 ∈ Z.base_set i := by refl @[simp, mfld_simps] lemma mem_local_triv_target (i : ι) (p : B × F) : p ∈ (Z.local_triv i).target ↔ p.1 ∈ Z.base_set i := by { erw [mem_prod], simp } @[simp, mfld_simps] lemma local_triv_apply (i : ι) (p : Z.total_space) : (Z.local_triv i) p = ⟨p.1, Z.coord_change (Z.index_at p.1) i p.1 p.2⟩ := rfl @[simp, mfld_simps] lemma local_triv_symm_fst (i : ι) (p : B × F) : (Z.local_triv i).symm p = ⟨p.1, Z.coord_change i (Z.index_at p.1) p.1 p.2⟩ := rfl /-- The composition of two local trivializations is the trivialization change Z.triv_change i j. -/ lemma local_triv_trans (i j : ι) : (Z.local_triv i).symm.trans (Z.local_triv j) ≈ Z.triv_change i j := Z.local_triv'_trans i j /-- Extended version of the local trivialization of a fiber bundle constructed from core, registering additionally in its type that it is a local bundle trivialization. -/ def local_triv_ext (i : ι) : bundle_trivialization F Z.proj := { base_set := Z.base_set i, open_base_set := Z.is_open_base_set i, source_eq := rfl, target_eq := rfl, proj_to_fun := λp hp, by simp, ..Z.local_triv i } /-- A topological fiber bundle constructed from core is indeed a topological fiber bundle. -/ theorem is_topological_fiber_bundle : is_topological_fiber_bundle F Z.proj := λx, ⟨Z.local_triv_ext (Z.index_at (Z.proj x)), by simp [local_triv_ext]⟩ /-- The projection on the base of a topological bundle created from core is continuous -/ lemma continuous_proj : continuous Z.proj := Z.is_topological_fiber_bundle.continuous_proj /-- The projection on the base of a topological bundle created from core is an open map -/ lemma is_open_map_proj : is_open_map Z.proj := Z.is_topological_fiber_bundle.is_open_map_proj /-- Preferred local trivialization of a fiber bundle constructed from core, at a given point, as a local homeomorphism -/ def local_triv_at (p : Z.total_space) : local_homeomorph Z.total_space (B × F) := Z.local_triv (Z.index_at (Z.proj p)) @[simp, mfld_simps] lemma mem_local_triv_at_source (p : Z.total_space) : p ∈ (Z.local_triv_at p).source := by simp [local_triv_at] @[simp, mfld_simps] lemma local_triv_at_fst (p q : Z.total_space) : ((Z.local_triv_at p) q).1 = q.1 := rfl @[simp, mfld_simps] lemma local_triv_at_symm_fst (p : Z.total_space) (q : B × F) : ((Z.local_triv_at p).symm q).1 = q.1 := rfl /-- Preferred local trivialization of a fiber bundle constructed from core, at a given point, as a bundle trivialization -/ def local_triv_at_ext (p : Z.total_space) : bundle_trivialization F Z.proj := Z.local_triv_ext (Z.index_at (Z.proj p)) @[simp, mfld_simps] lemma local_triv_at_ext_to_local_homeomorph (p : Z.total_space) : (Z.local_triv_at_ext p).to_local_homeomorph = Z.local_triv_at p := rfl /-- If an element of `F` is invariant under all coordinate changes, then one can define a corresponding section of the fiber bundle, which is continuous. This applies in particular to the zero section of a vector bundle. Another example (not yet defined) would be the identity section of the endomorphism bundle of a vector bundle. -/ lemma continuous_const_section (v : F) (h : ∀ i j, ∀ x ∈ (Z.base_set i) ∩ (Z.base_set j), Z.coord_change i j x v = v) : continuous (show B → Z.total_space, from λ x, ⟨x, v⟩) := begin apply continuous_iff_continuous_at.2 (λ x, _), have A : Z.base_set (Z.index_at x) ∈ 𝓝 x := mem_nhds_sets (Z.is_open_base_set (Z.index_at x)) (Z.mem_base_set_at x), apply ((Z.local_triv (Z.index_at x)).continuous_at_iff_continuous_at_comp_left _).2, { simp only [(∘)] with mfld_simps, apply continuous_at_id.prod, have : continuous_on (λ (y : B), v) (Z.base_set (Z.index_at x)) := continuous_on_const, apply (this.congr _).continuous_at A, assume y hy, simp only [h, hy] with mfld_simps }, { exact A } end end topological_fiber_bundle_core
1dec050a37e7afe686e20897f29c75bc55bbe5d1
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/mk_byte.lean
b0c261434f6c72d1436cfe935e6fbb48b3f31004
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
1,260
lean
import data.vector namespace Ex universe u -- def vector (α : Type u) (n : ℕ) := { l : list α // l.length = n } namespace vector variables {α : Type u} {n : ℕ} @[pattern] def cons : α → vector α n → vector α (nat.succ n) | a ⟨ v, h ⟩ := ⟨ a::v, congr_arg nat.succ h ⟩ def to_list' (v : vector α n) : list α := v.1 def drop (i : ℕ) : vector α n → vector α (n - i) | ⟨l, p⟩ := ⟨ list.drop i l, by simp * ⟩ protected axiom eq {n : ℕ} : ∀ (a1 a2 : vector α n), to_list' a1 = to_list' a2 → a1 = a2 @[simp] axiom to_list'_cons (a : α) (v : vector α n) : to_list' (cons a v) = list.cons a (to_list' v) @[simp] axiom to_list'_drop {n m : ℕ} (v : vector α m) : to_list' (drop n v) = list.drop n (to_list' v) end vector open Ex.vector @[reducible] def bitvec (n : ℕ) := vector bool n def byte_type := bitvec 8 -- A byte is formed from concatenating two bits and a 6-bit field. def mk_byte (a b : bool) (l : bitvec 6) : byte_type := cons a (cons b l) -- Get the third component def get_data (byte : byte_type) : bitvec 6 := vector.drop 2 byte lemma get_data_mk_byte {a b : bool} {l : bitvec 6} : get_data (mk_byte a b l) = l := begin apply vector.eq, unfold mk_byte, unfold get_data, simp end end Ex
a920bcf8a814a1e7478e58cc338a0e2aab15fbbf
4efff1f47634ff19e2f786deadd394270a59ecd2
/test/lint_simp_var_head.lean
b4028849224462cafeb9c23ce2f3a23b1aaf79ab
[ "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
591
lean
import tactic.lint -- The following simp lemma has the variable `f` as head symbol of the left-hand side: @[simp] axiom const_zero_eq_zero (f : ℕ → ℕ) (x) : f x = 0 example (f : ℕ → ℕ) : f 42 = 0 := begin -- Hence it doesn't work: success_if_fail {simp}, -- BTW, rw doesn't work either: success_if_fail {rw const_zero_eq_zero}, -- It only works if explicitly instantiate with `f`: simp only [const_zero_eq_zero f] end open tactic run_cmd do decl ← get_decl ``const_zero_eq_zero, res ← linter.simp_var_head.test decl, -- linter complains guard $ res.is_some
e4872e9c9315c13d8790e3f3654317d332685fad
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/congrThmIssue.lean
a8c0f4874a6b351e45a3569ba4d32368dab02e20
[ "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
719
lean
theorem Nat.lt_of_lt_le {x y z : Nat} : x < y → y ≤ z → x < z := by intro h h' induction h' assumption apply Nat.le_step assumption structure ArrayBuffer (α) where cap : Nat backing : Fin cap → Option α size : Nat h_size : size ≤ cap h_full : ∀ i, (h:i < size) → (backing ⟨i, Nat.lt_of_lt_le h h_size⟩).isSome namespace ArrayBuffer def grow : ArrayBuffer α → ArrayBuffer α := λ ⟨cap, backing, size, h_size, h_full⟩ => ⟨cap + cap, λ i => if h:i < cap then backing ⟨i,h⟩ else none, size, Nat.le_trans h_size (Nat.le_add_left _ _), by intro i h simp trace_state have : i < cap := Nat.lt_of_lt_le h h_size simp [*]⟩
079d6c2c1994b031f83426a4f9b249b90a8560a5
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/hott/types/W.hlean
7ea30fdb72901f919b4fc313a194a57789211d9a
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
4,740
hlean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Theorems about W-types (well-founded trees) -/ import .sigma .pi open eq equiv is_equiv sigma sigma.ops inductive Wtype.{l k} {A : Type.{l}} (B : A → Type.{k}) : Type.{max l k} := sup : Π (a : A), (B a → Wtype.{l k} B) → Wtype.{l k} B namespace Wtype notation `W` binders `, ` r:(scoped B, Wtype B) := r universe variables u v variables {A A' : Type.{u}} {B B' : A → Type.{v}} {C : Π(a : A), B a → Type} {a a' : A} {f : B a → W a, B a} {f' : B a' → W a, B a} {w w' : W(a : A), B a} protected definition pr1 [unfold 3] (w : W(a : A), B a) : A := by cases w with a f; exact a protected definition pr2 [unfold 3] (w : W(a : A), B a) : B (Wtype.pr1 w) → W(a : A), B a := by cases w with a f; exact f namespace ops postfix `.1`:(max+1) := Wtype.pr1 postfix `.2`:(max+1) := Wtype.pr2 notation `⟨` a `, ` f `⟩`:0 := Wtype.sup a f --input ⟨ ⟩ as \< \> end ops open ops protected definition eta [unfold 3] (w : W a, B a) : ⟨w.1 , w.2⟩ = w := by cases w; exact idp definition sup_eq_sup [unfold 8] (p : a = a') (q : f =[p] f') : ⟨a, f⟩ = ⟨a', f'⟩ := by cases q; exact idp definition Wtype_eq [unfold 3 4] (p : w.1 = w'.1) (q : w.2 =[p] w'.2) : w = w' := by cases w; cases w';exact (sup_eq_sup p q) definition Wtype_eq_pr1 [unfold 5] (p : w = w') : w.1 = w'.1 := by cases p;exact idp definition Wtype_eq_pr2 [unfold 5] (p : w = w') : w.2 =[Wtype_eq_pr1 p] w'.2 := by cases p;exact idpo namespace ops postfix `..1`:(max+1) := Wtype_eq_pr1 postfix `..2`:(max+1) := Wtype_eq_pr2 end ops open ops open sigma definition sup_path_W (p : w.1 = w'.1) (q : w.2 =[p] w'.2) : ⟨(Wtype_eq p q)..1, (Wtype_eq p q)..2⟩ = ⟨p, q⟩ := by cases w; cases w'; cases q; exact idp definition pr1_path_W (p : w.1 = w'.1) (q : w.2 =[p] w'.2) : (Wtype_eq p q)..1 = p := !sup_path_W..1 definition pr2_path_W (p : w.1 = w'.1) (q : w.2 =[p] w'.2) : (Wtype_eq p q)..2 =[pr1_path_W p q] q := !sup_path_W..2 definition eta_path_W (p : w = w') : Wtype_eq (p..1) (p..2) = p := by cases p; cases w; exact idp definition transport_pr1_path_W {B' : A → Type} (p : w.1 = w'.1) (q : w.2 =[p] w'.2) : transport (λx, B' x.1) (Wtype_eq p q) = transport B' p := by cases w; cases w'; cases q; exact idp definition path_W_uncurried (pq : Σ(p : w.1 = w'.1), w.2 =[p] w'.2) : w = w' := by cases pq with p q; exact (Wtype_eq p q) definition sup_path_W_uncurried (pq : Σ(p : w.1 = w'.1), w.2 =[p] w'.2) : ⟨(path_W_uncurried pq)..1, (path_W_uncurried pq)..2⟩ = pq := by cases pq with p q; exact (sup_path_W p q) definition pr1_path_W_uncurried (pq : Σ(p : w.1 = w'.1), w.2 =[p] w'.2) : (path_W_uncurried pq)..1 = pq.1 := !sup_path_W_uncurried..1 definition pr2_path_W_uncurried (pq : Σ(p : w.1 = w'.1), w.2 =[p] w'.2) : (path_W_uncurried pq)..2 =[pr1_path_W_uncurried pq] pq.2 := !sup_path_W_uncurried..2 definition eta_path_W_uncurried (p : w = w') : path_W_uncurried ⟨p..1, p..2⟩ = p := !eta_path_W definition transport_pr1_path_W_uncurried {B' : A → Type} (pq : Σ(p : w.1 = w'.1), w.2 =[p] w'.2) : transport (λx, B' x.1) (@path_W_uncurried A B w w' pq) = transport B' pq.1 := by cases pq with p q; exact (transport_pr1_path_W p q) definition isequiv_path_W /-[instance]-/ (w w' : W a, B a) : is_equiv (path_W_uncurried : (Σ(p : w.1 = w'.1), w.2 =[p] w'.2) → w = w') := adjointify path_W_uncurried (λp, ⟨p..1, p..2⟩) eta_path_W_uncurried sup_path_W_uncurried definition equiv_path_W (w w' : W a, B a) : (Σ(p : w.1 = w'.1), w.2 =[p] w'.2) ≃ (w = w') := equiv.mk path_W_uncurried !isequiv_path_W definition double_induction_on {P : (W a, B a) → (W a, B a) → Type} (w w' : W a, B a) (H : ∀ (a a' : A) (f : B a → W a, B a) (f' : B a' → W a, B a), (∀ (b : B a) (b' : B a'), P (f b) (f' b')) → P (sup a f) (sup a' f')) : P w w' := begin revert w', induction w with a f IH, intro w', cases w' with a' f', apply H, intro b b', apply IH end /- truncatedness -/ open is_trunc pi definition is_trunc_W [instance] (n : trunc_index) [HA : is_trunc (n.+1) A] : is_trunc (n.+1) (W a, B a) := begin fapply is_trunc_succ_intro, intro w w', eapply (double_induction_on w w'), intro a a' f f' IH, fapply is_trunc_equiv_closed, { apply equiv_path_W}, { apply is_trunc_sigma, intro p, cases p, esimp, apply is_trunc_equiv_closed_rev, apply pathover_idp} end end Wtype
54dfba4341ea49badb04f903ba602baffd22f099
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/fingerprint.lean
5f0e9c41f3a99bd8014de6d29d736b8e028f7dec
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
710
lean
open tactic run_command attribute.fingerprint `reducible >>= trace definition ex0 : nat := by attribute.fingerprint `reducible >>= expr_of_nat >>= exact attribute [reducible] definition f : nat := 10 run_command attribute.fingerprint `reducible >>= trace definition ex1 : nat := by attribute.fingerprint `reducible >>= expr_of_nat >>= exact vm_eval ex1 definition g : nat := 20 run_command attribute.fingerprint `reducible >>= trace definition ex2 : nat := by attribute.fingerprint `reducible >>= expr_of_nat >>= exact vm_eval ex2 example : ex1 = ex2 := rfl definition h : nat := 20 definition ex3 : nat := by attribute.fingerprint `reducible >>= expr_of_nat >>= exact example : ex1 = ex3 := rfl
9b2c8fd54b8247a413456d3cb32dd3d460a5568f
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/tests/lean/ppExpr.lean
edf393c0ddb1d0541ca1e5093d1c5808cc5a9196
[ "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
652
lean
import Lean /-! Pretty printing tests for `Expr`s that cannot be generated by parsing+elaborating. -/ open Lean def test (e : Expr) : MetaM Unit := PrettyPrinter.ppExpr Name.anonymous [] e >>= IO.println -- loose bound variable #eval test (mkBVar 0) -- anonymous binder #eval test (mkLambda Name.anonymous BinderInfo.default (mkSort levelZero) (mkBVar 0)) -- pp annotations #eval test $ mkAppN (mkConst `id [levelZero]) #[ mkConst `Nat, mkMData (KVMap.empty.set `pp.explicit true) $ mkAppN (mkConst `id [levelZero]) #[ mkConst `Nat, mkAppN (mkConst `id [levelZero]) #[ mkConst `Nat, mkConst `Nat.zero ]]]
0d6c4a66ad8c3e6e4870aa1b2822b8d6141ca2e6
e030b0259b777fedcdf73dd966f3f1556d392178
/tests/lean/run/using_smt3.lean
bd16f183cac625aeb4883b609941adf982e7f09a
[ "Apache-2.0" ]
permissive
fgdorais/lean
17b46a095b70b21fa0790ce74876658dc5faca06
c3b7c54d7cca7aaa25328f0a5660b6b75fe26055
refs/heads/master
1,611,523,590,686
1,484,412,902,000
1,484,412,902,000
38,489,734
0
0
null
1,435,923,380,000
1,435,923,379,000
null
UTF-8
Lean
false
false
700
lean
open tactic lemma ex1 : let x := 1 in ∀ y, x = y → y = 1 := by using_smt $ smt_tactic.intros >> get_local `x >>= (fun a, trace a) open tactic_result meta def fail_if_success {α : Type} (t : smt_tactic α) : smt_tactic unit := λ ss ts, match t ss ts with | success _ _ := failed ts | exception .(α × smt_state) _ _ _ := success ((), ss) ts end def my_pre_config : smt_pre_config := { default_smt_pre_config with zeta := tt } def my_smt_config : smt_config := { default_smt_config with pre_cfg := my_pre_config } lemma ex2 : let x := 1 in ∀ y, x = y → y = 1 := by using_smt_core my_smt_config $ smt_tactic.intros >> fail_if_success (get_local `x) >> return ()
54bac4282083a170af246e352bbed1d53bb1d4f9
a19a4fce1e5677f4d20cbfdf60c04b6386ab8210
/hott/types/pointed.hlean
6438ce6955427cac5b9f728dbb00b98b822d743a
[ "Apache-2.0" ]
permissive
nthomas103/lean
9c341a316e7d9faa00546462f90a8aa402e17eac
04eaf184a92606a56e54d0d6c8d59437557263fc
refs/heads/master
1,586,061,106,806
1,454,640,115,000
1,454,641,279,000
51,127,143
0
0
null
1,454,648,683,000
1,454,648,683,000
null
UTF-8
Lean
false
false
12,681
hlean
/- Copyright (c) 2014 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jakob von Raumer, Floris van Doorn Ported from Coq HoTT -/ import arity .eq .bool .unit .sigma .nat.basic open is_trunc eq prod sigma nat equiv option is_equiv bool unit algebra structure pointed [class] (A : Type) := (point : A) structure Pointed := {carrier : Type} (Point : carrier) open Pointed notation `Type*` := Pointed namespace pointed attribute Pointed.carrier [coercion] variables {A B : Type} definition pt [unfold 2] [H : pointed A] := point A protected definition Mk [constructor] := @Pointed.mk protected definition MK [constructor] (A : Type) (a : A) := Pointed.mk a protected definition mk' [constructor] (A : Type) [H : pointed A] : Type* := Pointed.mk (point A) definition pointed_carrier [instance] [constructor] (A : Type*) : pointed A := pointed.mk (Point A) -- Any contractible type is pointed definition pointed_of_is_contr [instance] [priority 800] [constructor] (A : Type) [H : is_contr A] : pointed A := pointed.mk !center -- A pi type with a pointed target is pointed definition pointed_pi [instance] [constructor] (P : A → Type) [H : Πx, pointed (P x)] : pointed (Πx, P x) := pointed.mk (λx, pt) -- A sigma type of pointed components is pointed definition pointed_sigma [instance] [constructor] (P : A → Type) [G : pointed A] [H : pointed (P pt)] : pointed (Σx, P x) := pointed.mk ⟨pt,pt⟩ definition pointed_prod [instance] [constructor] (A B : Type) [H1 : pointed A] [H2 : pointed B] : pointed (A × B) := pointed.mk (pt,pt) definition pointed_loop [instance] [constructor] (a : A) : pointed (a = a) := pointed.mk idp definition pointed_bool [instance] [constructor] : pointed bool := pointed.mk ff definition Bool [constructor] : Type* := pointed.mk' bool definition Unit [constructor] : Type* := Pointed.mk unit.star definition pointed_fun_closed [constructor] (f : A → B) [H : pointed A] : pointed B := pointed.mk (f pt) definition Loop_space [reducible] [constructor] (A : Type*) : Type* := pointed.mk' (point A = point A) definition Iterated_loop_space [unfold 1] [reducible] : ℕ → Type* → Type* | Iterated_loop_space 0 X := X | Iterated_loop_space (n+1) X := Loop_space (Iterated_loop_space n X) prefix `Ω`:(max+5) := Loop_space notation `Ω[`:95 n:0 `] `:0 A:95 := Iterated_loop_space n A definition rfln [constructor] [reducible] {A : Type*} {n : ℕ} : Ω[n] A := pt definition refln [constructor] [reducible] (A : Type*) (n : ℕ) : Ω[n] A := pt definition refln_eq_refl (A : Type*) (n : ℕ) : rfln = rfl :> Ω[succ n] A := rfl definition iterated_loop_space [unfold 3] (A : Type) [H : pointed A] (n : ℕ) : Type := Ω[n] (pointed.mk' A) open equiv.ops definition Pointed_eq {A B : Type*} (f : A ≃ B) (p : f pt = pt) : A = B := begin cases A with A a, cases B with B b, esimp at *, fapply apd011 @Pointed.mk, { apply ua f}, { rewrite [cast_ua,p]}, end protected definition Pointed.sigma_char.{u} : Pointed.{u} ≃ Σ(X : Type.{u}), X := begin fapply equiv.MK, { intro x, induction x with X x, exact ⟨X, x⟩}, { intro x, induction x with X x, exact pointed.MK X x}, { intro x, induction x with X x, reflexivity}, { intro x, induction x with X x, reflexivity}, end definition add_point [constructor] (A : Type) : Type* := Pointed.mk (none : option A) postfix `₊`:(max+1) := add_point -- the inclusion A → A₊ is called "some", the extra point "pt" or "none" ("@none A") end pointed open pointed structure pmap (A B : Type*) := (map : A → B) (resp_pt : map (Point A) = Point B) open pmap namespace pointed abbreviation respect_pt [unfold 3] := @pmap.resp_pt notation `map₊` := pmap infix ` →* `:30 := pmap attribute pmap.map [coercion] variables {A B C D : Type*} {f g h : A →* B} definition pmap_eq (r : Πa, f a = g a) (s : respect_pt f = (r pt) ⬝ respect_pt g) : f = g := begin cases f with f p, cases g with g q, esimp at *, fapply apo011 pmap.mk, { exact eq_of_homotopy r}, { apply concato_eq, apply pathover_eq_Fl, apply inv_con_eq_of_eq_con, rewrite [ap_eq_ap10,↑ap10,apd10_eq_of_homotopy,s]} end definition pid [constructor] (A : Type*) : A →* A := pmap.mk id idp definition pcompose [constructor] (g : B →* C) (f : A →* B) : A →* C := pmap.mk (λa, g (f a)) (ap g (respect_pt f) ⬝ respect_pt g) infixr ` ∘* `:60 := pcompose -- The constant pointed map between any two types definition pconst [constructor] (A B : Type*) : A →* B := pmap.mk (λ a, Point B) idp structure phomotopy (f g : A →* B) := (homotopy : f ~ g) (homotopy_pt : homotopy pt ⬝ respect_pt g = respect_pt f) infix ` ~* `:50 := phomotopy abbreviation to_homotopy_pt [unfold 5] := @phomotopy.homotopy_pt abbreviation to_homotopy [coercion] [unfold 5] (p : f ~* g) : Πa, f a = g a := phomotopy.homotopy p definition passoc (h : C →* D) (g : B →* C) (f : A →* B) : (h ∘* g) ∘* f ~* h ∘* (g ∘* f) := begin fconstructor, intro a, reflexivity, cases A, cases B, cases C, cases D, cases f with f pf, cases g with g pg, cases h with h ph, esimp at *, induction pf, induction pg, induction ph, reflexivity end definition pid_comp (f : A →* B) : pid B ∘* f ~* f := begin fconstructor, { intro a, reflexivity}, { esimp, exact !idp_con ⬝ !ap_id⁻¹} end definition comp_pid (f : A →* B) : f ∘* pid A ~* f := begin fconstructor, { intro a, reflexivity}, { reflexivity} end definition pmap_equiv_left (A : Type) (B : Type*) : A₊ →* B ≃ (A → B) := begin fapply equiv.MK, { intro f a, cases f with f p, exact f (some a)}, { intro f, fconstructor, intro a, cases a, exact pt, exact f a, reflexivity}, { intro f, reflexivity}, { intro f, cases f with f p, esimp, fapply pmap_eq, { intro a, cases a; all_goals (esimp at *), exact p⁻¹}, { esimp, exact !con.left_inv⁻¹}}, end -- set_option pp.notation false -- definition pmap_equiv_right (A : Type*) (B : Type) -- : (Σ(b : B), map₊ A (pointed.Mk b)) ≃ (A → B) := -- begin -- fapply equiv.MK, -- { intro u a, cases u with b f, cases f with f p, esimp at f, exact f a}, -- { intro f, refine ⟨f pt, _⟩, fapply pmap.mk, -- intro a, esimp, exact f a, -- reflexivity}, -- { intro f, reflexivity}, -- { intro u, cases u with b f, cases f with f p, esimp at *, apply sigma_eq p, -- esimp, apply sorry -- } -- end definition pmap_bool_equiv (B : Type*) : map₊ Bool B ≃ B := begin fapply equiv.MK, { intro f, cases f with f p, exact f tt}, { intro b, fconstructor, intro u, cases u, exact pt, exact b, reflexivity}, { intro b, reflexivity}, { intro f, cases f with f p, esimp, fapply pmap_eq, { intro a, cases a; all_goals (esimp at *), exact p⁻¹}, { esimp, exact !con.left_inv⁻¹}}, end definition ap1 [constructor] (f : A →* B) : Ω A →* Ω B := begin fconstructor, { intro p, exact !respect_pt⁻¹ ⬝ ap f p ⬝ !respect_pt}, { esimp, apply con.left_inv} end definition apn [unfold 3] (n : ℕ) (f : map₊ A B) : Ω[n] A →* Ω[n] B := begin induction n with n IH, { exact f}, { esimp [Iterated_loop_space], exact ap1 IH} end variable (A) definition loop_space_succ_eq_in (n : ℕ) : Ω[succ n] A = Ω[n] (Ω A) := begin induction n with n IH, { reflexivity}, { exact ap Loop_space IH} end definition loop_space_add (n m : ℕ) : Ω[n] (Ω[m] A) = Ω[m+n] (A) := begin induction n with n IH, { reflexivity}, { exact ap Loop_space IH} end definition loop_space_succ_eq_out (n : ℕ) : Ω[succ n] A = Ω(Ω[n] A) := idp variable {A} /- the equality [loop_space_succ_eq_in] preserves concatenation -/ theorem loop_space_succ_eq_in_concat {n : ℕ} (p q : Ω[succ (succ n)] A) : transport carrier (ap Loop_space (loop_space_succ_eq_in A n)) (p ⬝ q) = transport carrier (ap Loop_space (loop_space_succ_eq_in A n)) p ⬝ transport carrier (ap Loop_space (loop_space_succ_eq_in A n)) q := begin rewrite [-+tr_compose, ↑function.compose], rewrite [+@transport_eq_FlFr_D _ _ _ _ Point Point, +con.assoc], apply whisker_left, rewrite [-+con.assoc], apply whisker_right, rewrite [con_inv_cancel_right, ▸*, -ap_con] end definition loop_space_loop_irrel (p : point A = point A) : Ω(Pointed.mk p) = Ω[2] A := begin intros, fapply Pointed_eq, { esimp, transitivity _, apply eq_equiv_fn_eq_of_equiv (equiv_eq_closed_right _ p⁻¹), esimp, apply eq_equiv_eq_closed, apply con.right_inv, apply con.right_inv}, { esimp, apply con.left_inv} end definition iterated_loop_space_loop_irrel (n : ℕ) (p : point A = point A) : Ω[succ n](Pointed.mk p) = Ω[succ (succ n)] A :> Pointed := calc Ω[succ n](Pointed.mk p) = Ω[n](Ω (Pointed.mk p)) : loop_space_succ_eq_in ... = Ω[n] (Ω[2] A) : loop_space_loop_irrel ... = Ω[2+n] A : loop_space_add ... = Ω[n+2] A : by rewrite [algebra.add.comm] -- TODO: -- definition apn_compose (n : ℕ) (g : B →* C) (f : A →* B) : apn n (g ∘* f) ~* apn n g ∘* apn n f := -- _ definition ap1_compose (g : B →* C) (f : A →* B) : ap1 (g ∘* f) ~* ap1 g ∘* ap1 f := begin induction B, induction C, induction g with g pg, induction f with f pf, esimp at *, induction pg, induction pf, fconstructor, { intro p, esimp, apply whisker_left, exact ap_compose g f p ⬝ ap (ap g) !idp_con⁻¹}, { reflexivity} end protected definition phomotopy.refl [refl] (f : A →* B) : f ~* f := begin fconstructor, { intro a, exact idp}, { apply idp_con} end protected definition phomotopy.trans [trans] (p : f ~* g) (q : g ~* h) : f ~* h := begin fconstructor, { intro a, exact p a ⬝ q a}, { induction f, induction g, induction p with p p', induction q with q q', esimp at *, induction p', induction q', esimp, apply con.assoc} end protected definition phomotopy.symm [symm] (p : f ~* g) : g ~* f := begin fconstructor, { intro a, exact (p a)⁻¹}, { induction f, induction p with p p', esimp at *, induction p', esimp, apply inv_con_cancel_left} end infix ` ⬝* `:75 := phomotopy.trans postfix `⁻¹*`:(max+1) := phomotopy.symm definition eq_of_phomotopy (p : f ~* g) : f = g := begin fapply pmap_eq, { intro a, exact p a}, { exact !to_homotopy_pt⁻¹} end definition pwhisker_left (h : B →* C) (p : f ~* g) : h ∘* f ~* h ∘* g := begin fconstructor, { intro a, exact ap h (p a)}, { induction A, induction B, induction C, induction f with f pf, induction g with g pg, induction h with h ph, induction p with p p', esimp at *, induction ph, induction pg, induction p', reflexivity} end definition pwhisker_right (h : C →* A) (p : f ~* g) : f ∘* h ~* g ∘* h := begin fconstructor, { intro a, exact p (h a)}, { induction A, induction B, induction C, induction f with f pf, induction g with g pg, induction h with h ph, induction p with p p', esimp at *, induction ph, induction pg, induction p', esimp, exact !idp_con⁻¹} end structure pequiv (A B : Type*) := (to_pmap : A →* B) (is_equiv_to_pmap : is_equiv to_pmap) infix ` ≃* `:25 := pequiv attribute pequiv.to_pmap [coercion] attribute pequiv.is_equiv_to_pmap [instance] definition pequiv.mk' (to_pmap : A →* B) [is_equiv_to_pmap : is_equiv to_pmap] : pequiv A B := pequiv.mk to_pmap is_equiv_to_pmap definition equiv_of_pequiv [constructor] (f : A ≃* B) : A ≃ B := equiv.mk f _ definition to_pinv [constructor] (f : A ≃* B) : B →* A := pmap.mk f⁻¹ (ap f⁻¹ (respect_pt f)⁻¹ ⬝ !left_inv) definition pua {A B : Type*} (f : A ≃* B) : A = B := Pointed_eq (equiv_of_pequiv f) !respect_pt definition pequiv_refl [refl] [constructor] : A ≃* A := pequiv.mk !pid !is_equiv_id definition pequiv_symm [symm] (f : A ≃* B) : B ≃* A := pequiv.mk (to_pinv f) !is_equiv_inv definition pequiv_trans [trans] (f : A ≃* B) (g : B ≃*C) : A ≃* C := pequiv.mk (pcompose g f) !is_equiv_compose end pointed
fdb2f6600400fc1dcdc3e9b868d85140616a8969
5d95c8513fa8592ce314d1f40c23ad5eecfe1e34
/src/util/meta/expr_ctx.lean
d2d91256cfed4fe956bad8b2cdcd1d05f23f2225
[ "Apache-2.0" ]
permissive
solovay/lean-universal
6b792513ced2fe82218e7828400743375dd59e24
417ed5e1b030e547912cbfefe34df9d3d01c2b65
refs/heads/master
1,598,052,603,315
1,565,981,123,000
1,565,981,123,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,276
lean
-- Copyright © 2019 François G. Dorais. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. import .expr import .format meta abbreviation expr_ctx : Type := list (name × expr × binder_info) namespace expr_ctx open exceptional meta def nil : expr_ctx := list.nil meta def add (ctx : expr_ctx) (n : name) (e : expr) (b : binder_info := binder_info.default) : expr_ctx := (n, e, b) :: ctx meta def pop : expr_ctx → exceptional (expr_ctx × name × expr × binder_info) | ((n,e,b)::ctx) := success (ctx,n,e,b) | [] := fail "empty expr_ctx" meta def get : expr_ctx → exceptional (name × expr × binder_info) := λ ctx, ctx.pop >>= λ r, success r.snd meta def nth : expr_ctx → nat → exceptional (name × expr × binder_info) | (_ :: ctx) (n+1) := nth ctx n | (c :: _) 0 := success c | [] _ := fail "empty expr_ctx" meta def del : expr_ctx → exceptional expr_ctx := λ ctx, ctx.pop >>= λ r, success r.fst meta def drop : expr_ctx → nat → exceptional expr_ctx | ctx 0 := success ctx | ctx (k+1) := del ctx >>= λ ctx, drop ctx k meta def take : expr_ctx → nat → exceptional expr_ctx | _ 0 := success nil | ctx (k+1) := ctx.pop >>= λ ⟨ctx, c⟩, ctx.take k >>= λ ctx, success $ c :: ctx meta def app (ctx : expr_ctx) : expr → expr := λ e, e.mk_app (expr.mk_num_vars ctx.length).reverse meta def app_beta (ctx : expr_ctx) : expr → expr := λ e, e.mk_app_beta (expr.mk_num_vars ctx.length).reverse meta def insert_aux : expr_ctx → nat → name × expr × binder_info → exceptional expr_ctx | ctx (k+1) := λ c, ctx.pop >>= λ ⟨ctx, n, t, b⟩, insert_aux ctx k c >>= λ ctx, success $ ctx.add n (t.lift_vars k 1) b | ctx 0 := λ ⟨n, t, b⟩, success $ ctx.add n t b meta def insert (ctx : expr_ctx) (i : nat) (n : name) (t : expr) (b : binder_info := binder_info.default) : exceptional expr_ctx := insert_aux ctx i (n, t.lower_vars 0 i, b) meta def delete : expr_ctx → nat → exceptional expr_ctx | ctx (k+1) := ctx.pop >>= λ ⟨ctx, n, t, b⟩, delete ctx k >>= λ ctx, success $ ctx.add n (t.lower_vars k 1) b | ctx 0 := ctx.del meta def collect_univ_params (ctx : expr_ctx) : list name := ctx.foldl (λ us ⟨_,e,_⟩, e.collect_univ_params.foldr list.insert us) [] meta def implicitize : expr_ctx → expr_ctx | [] := [] | ((n,t,binder_info.default)::ctx) := (n,t,binder_info.implicit) :: implicitize ctx | (c::ctx) := c :: implicitize ctx meta def lam : expr_ctx → expr → expr | [] e := e | ((n,t,_)::ctx) e := lam ctx (expr.lam n binder_info.default t e) meta def mk_lam : expr_ctx → nat → expr → exceptional expr := λ ctx k e, ctx.take k >>= λ ctx, success $ ctx.lam e meta def pi : expr_ctx → expr → expr | [] e := e | ((n,t,b)::ctx) e := pi ctx (expr.pi n b t e) meta def mk_pi : expr_ctx → nat → expr → exceptional expr := λ ctx k e, ctx.take k >>= λ ctx, success $ ctx.pi e meta def get_ctx_lam_aux : expr → expr_ctx → expr × expr_ctx | (expr.lam n b t e) ctx := get_ctx_lam_aux e ((n, t, b) :: ctx) | e ctx := (e, ctx) meta def get_ctx_lam : expr → expr × expr_ctx := λ e, get_ctx_lam_aux e nil meta def get_ctx_pi_aux : expr → expr_ctx → expr × expr_ctx | (expr.pi n b t e) ctx := get_ctx_pi_aux e ((n, t, b) :: ctx) | e ctx := (e, ctx) meta def get_ctx_pi : expr → expr × expr_ctx := λ e, get_ctx_pi_aux e nil meta def lift_vars : expr_ctx → nat → nat → expr_ctx | [] _ _ := [] | ((n,e,b)::ctx) s i := (n, e.lift_vars s i, b) :: lift_vars ctx (s+1) i meta def lower_vars : expr_ctx → nat → nat → expr_ctx | [] _ _ := [] | ((n,e,b)::ctx) s d := (n, e.lower_vars s d, b) :: lower_vars ctx (s+1) d meta def mk_local (upfx : name) : expr_ctx → list expr | [] := [] | ((n,t,b)::ctx) := let loc := mk_local ctx in let t := t.instantiate_vars loc in expr.local_const (mk_num_name upfx ctx.length) n b t :: loc meta def ref_aux : expr_ctx → name → nat → exceptional nat | [] n _ := fail $ "name " ++ n.to_string ++ " not found in expr_ctx" | (c::ctx) n k := if c.fst = n then success k else ref_aux ctx n (k+1) meta def ref : expr_ctx → name → exceptional nat := λ ctx n, ctx.ref_aux n 0 meta def ref_var : expr_ctx → name → exceptional expr := λ ctx n, ctx.ref n >>= λ k, success $ expr.var k meta def refs (ctx : expr_ctx) : list name → exceptional (list nat) | [] := success [] | (n::ns) := ctx.ref n >>= λ k, refs ns >>= λ ks, success $ k :: ks meta def ref_vars : expr_ctx → list name → exceptional (list expr) := λ ctx ns, ctx.refs ns >>= λ ks, success $ ks.map expr.var meta def expr_to_fmt (ctx : expr_ctx) : expr → format | (expr.var i) := match ctx.nth i with | success ⟨n,_⟩ := to_fmt n | exception _ _ := "#" ++ to_fmt (i - ctx.length) end | (expr.sort l) := "Sort " ++ format.paren (to_fmt l) | (expr.app a b) := expr_to_fmt a ++ " " ++ format.paren (expr_to_fmt b) | (expr.pi n b t e) := "Π " ++ b.to_fmt (to_fmt n ++ " : " ++ expr_to_fmt t) ++ ", " ++ expr_to_fmt e | (expr.lam n b t e) := "λ " ++ b.to_fmt (to_fmt n ++ " : " ++ expr_to_fmt t) ++ ", " ++ expr_to_fmt e | (expr.local_const _ n b t) := b.to_fmt (to_fmt n ++ " : " ++ expr_to_fmt t) | (expr.elet n t v e) := "let " ++ to_fmt n ++ " : " ++ expr_to_fmt t ++ " := " ++ expr_to_fmt v ++ " in " ++ expr_to_fmt e | (expr.mvar n _ t) := format.paren (to_fmt n ++ " : " ++ expr_to_fmt t) | (expr.const n l) := "@" ++ to_fmt n ++ "." ++ format.cbrace (format.join (list.intersperse format.space (l.map to_fmt))) | (expr.macro m e) := to_fmt (expr.macro_def_name m) ++ format.sbracket (format.join $ list.intersperse ", " $ e.map expr_to_fmt) meta def expr_to_string (ctx : expr_ctx) (e : expr) : string := to_string $ ctx.expr_to_fmt e meta def to_format : expr_ctx → format | (⟨n, t, b⟩ :: ctx) := to_format ctx ++ format.space ++ b.to_fmt (to_fmt n ++ " : " ++ expr_to_fmt ctx t) | [] := "" meta def to_format_num : expr_ctx → nat → format | (⟨n, t, b⟩ :: ctx) (p+1) := to_format_num ctx p ++ format.space ++ b.to_fmt (to_fmt n ++ " : " ++ expr_to_fmt ctx t) | _ 0 := "" | [] _ := "" end expr_ctx meta def tactic.mk_local_ctx : expr_ctx → tactic (list expr) := λ ctx, tactic.mk_fresh_name >>= λ upfx, return $ expr_ctx.mk_local upfx ctx
91a7e56970afe1cdda97a6fb1b8d2b39551a86a3
4727251e0cd73359b15b664c3170e5d754078599
/src/measure_theory/decomposition/radon_nikodym.lean
ce7f41201fe0e8874a4501108d249bf37242cc10
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
4,902
lean
/- Copyright (c) 2021 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import measure_theory.decomposition.lebesgue /-! # Radon-Nikodym theorem This file proves the Radon-Nikodym theorem. The Radon-Nikodym theorem states that, given measures `μ, ν`, if `have_lebesgue_decomposition μ ν`, then `μ` is absolutely continuous with respect to `ν` if and only if there exists a measurable function `f : α → ℝ≥0∞` such that `μ = fν`. In particular, we have `f = rn_deriv μ ν`. The Radon-Nikodym theorem will allow us to define many important concepts in probability theory, most notably probability cumulative functions. It could also be used to define the conditional expectation of a real function, but we take a different approach (see the file `measure_theory/function/conditional_expectation`). ## Main results * `measure_theory.measure.absolutely_continuous_iff_with_density_rn_deriv_eq` : the Radon-Nikodym theorem * `measure_theory.signed_measure.absolutely_continuous_iff_with_density_rn_deriv_eq` : the Radon-Nikodym theorem for signed measures ## Tags Radon-Nikodym theorem -/ noncomputable theory open_locale classical measure_theory nnreal ennreal variables {α β : Type*} {m : measurable_space α} namespace measure_theory namespace measure include m lemma with_density_rn_deriv_eq (μ ν : measure α) [have_lebesgue_decomposition μ ν] (h : μ ≪ ν) : ν.with_density (rn_deriv μ ν) = μ := begin obtain ⟨hf₁, ⟨E, hE₁, hE₂, hE₃⟩, hadd⟩:= have_lebesgue_decomposition_spec μ ν, have : singular_part μ ν = 0, { refine le_antisymm (λ A hA, _) (measure.zero_le _), suffices : singular_part μ ν set.univ = 0, { rw [measure.coe_zero, pi.zero_apply, ← this], exact measure_mono (set.subset_univ _) }, rw [← measure_add_measure_compl hE₁, hE₂, zero_add], have : (singular_part μ ν + ν.with_density (rn_deriv μ ν)) Eᶜ = μ Eᶜ, { rw ← hadd }, rw [measure.coe_add, pi.add_apply, h hE₃] at this, exact (add_eq_zero_iff.1 this).1 }, rw [this, zero_add] at hadd, exact hadd.symm end /-- **The Radon-Nikodym theorem**: Given two measures `μ` and `ν`, if `have_lebesgue_decomposition μ ν`, then `μ` is absolutely continuous to `ν` if and only if `ν.with_density (rn_deriv μ ν) = μ`. -/ theorem absolutely_continuous_iff_with_density_rn_deriv_eq {μ ν : measure α} [have_lebesgue_decomposition μ ν] : μ ≪ ν ↔ ν.with_density (rn_deriv μ ν) = μ := ⟨with_density_rn_deriv_eq μ ν, λ h, h ▸ with_density_absolutely_continuous _ _⟩ lemma with_density_rn_deriv_to_real_eq {μ ν : measure α} [is_finite_measure μ] [have_lebesgue_decomposition μ ν] (h : μ ≪ ν) {i : set α} (hi : measurable_set i) : ∫ x in i, (μ.rn_deriv ν x).to_real ∂ν = (μ i).to_real := begin rw [integral_to_real, ← with_density_apply _ hi, with_density_rn_deriv_eq μ ν h], { measurability }, { refine ae_lt_top (μ.measurable_rn_deriv ν) (lt_of_le_of_lt (lintegral_mono_set i.subset_univ) _).ne, rw [← with_density_apply _ measurable_set.univ, with_density_rn_deriv_eq μ ν h], exact measure_lt_top _ _ }, end end measure namespace signed_measure include m open measure vector_measure theorem with_densityᵥ_rn_deriv_eq (s : signed_measure α) (μ : measure α) [sigma_finite μ] (h : s ≪ᵥ μ.to_ennreal_vector_measure) : μ.with_densityᵥ (s.rn_deriv μ) = s := begin rw [absolutely_continuous_ennreal_iff, (_ : μ.to_ennreal_vector_measure.ennreal_to_measure = μ), total_variation_absolutely_continuous_iff] at h, { ext1 i hi, rw [with_densityᵥ_apply (integrable_rn_deriv _ _) hi, rn_deriv, integral_sub, with_density_rn_deriv_to_real_eq h.1 hi, with_density_rn_deriv_to_real_eq h.2 hi], { conv_rhs { rw ← s.to_signed_measure_to_jordan_decomposition }, erw vector_measure.sub_apply, rw [to_signed_measure_apply_measurable hi, to_signed_measure_apply_measurable hi] }, all_goals { rw ← integrable_on_univ, refine integrable_on.restrict _ measurable_set.univ, refine ⟨_, has_finite_integral_to_real_of_lintegral_ne_top _⟩, { apply measurable.ae_strongly_measurable, measurability }, { rw set_lintegral_univ, exact (lintegral_rn_deriv_lt_top _ _).ne } } }, { exact equiv_measure.right_inv μ } end /-- The Radon-Nikodym theorem for signed measures. -/ theorem absolutely_continuous_iff_with_densityᵥ_rn_deriv_eq (s : signed_measure α) (μ : measure α) [sigma_finite μ] : s ≪ᵥ μ.to_ennreal_vector_measure ↔ μ.with_densityᵥ (s.rn_deriv μ) = s := ⟨with_densityᵥ_rn_deriv_eq s μ, λ h, h ▸ with_densityᵥ_absolutely_continuous _ _⟩ end signed_measure end measure_theory
6fb18df90936682457ce3f052c6ec23b59b0f7e6
c86b74188c4b7a462728b1abd659ab4e5828dd61
/stage0/src/Lean/Elab/Frontend.lean
53ff7919be3ef0f0e35160195cfaa283ae222fce
[ "Apache-2.0" ]
permissive
cwb96/lean4
75e1f92f1ba98bbaa6b34da644b3dfab2ce7bf89
b48831cda76e64f13dd1c0edde7ba5fb172ed57a
refs/heads/master
1,686,347,881,407
1,624,483,842,000
1,624,483,842,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,710
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.Elab.Import import Lean.Elab.Command import Lean.Util.Profile namespace Lean.Elab.Frontend structure State where commandState : Command.State parserState : Parser.ModuleParserState cmdPos : String.Pos commands : Array Syntax := #[] structure Context where inputCtx : Parser.InputContext abbrev FrontendM := ReaderT Context $ StateRefT State IO def setCommandState (commandState : Command.State) : FrontendM Unit := modify fun s => { s with commandState := commandState } @[inline] def runCommandElabM (x : Command.CommandElabM α) : FrontendM α := do let ctx ← read let s ← get let cmdCtx : Command.Context := { cmdPos := s.cmdPos, fileName := ctx.inputCtx.fileName, fileMap := ctx.inputCtx.fileMap } match (← liftM <| EIO.toIO' <| (x cmdCtx).run s.commandState) with | Except.error e => throw <| IO.Error.userError s!"unexpected internal error: {← e.toMessageData.toString}" | Except.ok (a, sNew) => setCommandState sNew; return a def elabCommandAtFrontend (stx : Syntax) : FrontendM Unit := do runCommandElabM do let infoTreeEnabled := (← getInfoState).enabled if checkTraceOption (← getOptions) `Elab.info then enableInfoTree Command.elabCommand stx enableInfoTree infoTreeEnabled def updateCmdPos : FrontendM Unit := do modify fun s => { s with cmdPos := s.parserState.pos } def getParserState : FrontendM Parser.ModuleParserState := do pure (← get).parserState def getCommandState : FrontendM Command.State := do pure (← get).commandState def setParserState (ps : Parser.ModuleParserState) : FrontendM Unit := modify fun s => { s with parserState := ps } def setMessages (msgs : MessageLog) : FrontendM Unit := modify fun s => { s with commandState := { s.commandState with messages := msgs } } def getInputContext : FrontendM Parser.InputContext := do pure (← read).inputCtx def processCommand : FrontendM Bool := do updateCmdPos let cmdState ← getCommandState let ictx ← getInputContext let pstate ← getParserState let scope := cmdState.scopes.head! let pmctx := { env := cmdState.env, options := scope.opts, currNamespace := scope.currNamespace, openDecls := scope.openDecls } let pos := ictx.fileMap.toPosition pstate.pos match profileit "parsing" scope.opts fun _ => Parser.parseCommand ictx pmctx pstate cmdState.messages with | (cmd, ps, messages) => modify fun s => { s with commands := s.commands.push cmd } setParserState ps setMessages messages if Parser.isEOI cmd || Parser.isExitCommand cmd then pure true -- Done else profileitM IO.Error "elaboration" scope.opts <| elabCommandAtFrontend cmd pure false partial def processCommands : FrontendM Unit := do let done ← processCommand unless done do processCommands end Frontend open Frontend def IO.processCommands (inputCtx : Parser.InputContext) (parserState : Parser.ModuleParserState) (commandState : Command.State) : IO State := do let (_, s) ← (Frontend.processCommands.run { inputCtx := inputCtx }).run { commandState := commandState, parserState := parserState, cmdPos := parserState.pos } pure s def process (input : String) (env : Environment) (opts : Options) (fileName : Option String := none) : IO (Environment × MessageLog) := do let fileName := fileName.getD "<input>" let inputCtx := Parser.mkInputContext input fileName let s ← IO.processCommands inputCtx { : Parser.ModuleParserState } (Command.mkState env {} opts) pure (s.commandState.env, s.commandState.messages) builtin_initialize registerOption `printMessageEndPos { defValue := false, descr := "print end position of each message in addition to start position" } registerTraceClass `Elab.info def getPrintMessageEndPos (opts : Options) : Bool := opts.getBool `printMessageEndPos false @[export lean_run_frontend] def runFrontend (input : String) (opts : Options) (fileName : String) (mainModuleName : Name) : IO (Environment × Bool) := do let inputCtx := Parser.mkInputContext input fileName let (header, parserState, messages) ← Parser.parseHeader inputCtx let (env, messages) ← processHeader header opts messages inputCtx let env := env.setMainModule mainModuleName let s ← IO.processCommands inputCtx parserState (Command.mkState env messages opts) for msg in s.commandState.messages.toList do IO.print (← msg.toString (includeEndPos := getPrintMessageEndPos opts)) pure (s.commandState.env, !s.commandState.messages.hasErrors) end Lean.Elab
522d7457e0849293a7fb2fcc7a5ca106df7c5c32
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/mutualWithNamespaceMacro.lean
dead5d0623cfe152baa47b6c1101cb9d60ed5a59
[ "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
205
lean
mutual inductive Foo.Lst (α : Type) | nil : Foo.Lst α | cons : Boo.Tree α → Foo.Lst α → Foo.Lst α inductive Boo.Tree (α : Type) | leaf : Boo.Tree α | node : Foo.Lst α → Boo.Tree α end
df6eda9a376d95af7054aaa79cb869ce6abc70dc
63abd62053d479eae5abf4951554e1064a4c45b4
/src/group_theory/perm/sign.lean
901d46eca6e03ecf4a4a75a0a443c3d267e68200
[ "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
38,006
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.fintype.basic import data.finset.sort import algebra.group.conj import algebra.big_operators.basic universes u v open equiv function fintype finset open_locale big_operators variables {α : Type u} {β : Type v} namespace equiv.perm /-- If the permutation `f` fixes the subtype `{x // p x}`, then this returns the permutation on `{x // p x}` induced by `f`. -/ def subtype_perm (f : perm α) {p : α → Prop} (h : ∀ x, p x ↔ p (f x)) : perm {x // p x} := ⟨λ x, ⟨f x, (h _).1 x.2⟩, λ x, ⟨f⁻¹ x, (h (f⁻¹ x)).2 $ by simpa using x.2⟩, λ _, by simp only [perm.inv_apply_self, subtype.coe_eta, subtype.coe_mk], λ _, by simp only [perm.apply_inv_self, subtype.coe_eta, subtype.coe_mk]⟩ @[simp] lemma subtype_perm_one (p : α → Prop) (h : ∀ x, p x ↔ p ((1 : perm α) x)) : @subtype_perm α 1 p h = 1 := equiv.ext $ λ ⟨_, _⟩, rfl /-- The inclusion map of permutations on a subtype of `α` into permutations of `α`, fixing the other points. -/ def of_subtype {p : α → Prop} [decidable_pred p] : perm (subtype p) →* perm α := { to_fun := λ f, ⟨λ x, if h : p x then f ⟨x, h⟩ else x, λ x, if h : p x then f⁻¹ ⟨x, h⟩ else x, λ x, have h : ∀ h : p x, p (f ⟨x, h⟩), from λ h, (f ⟨x, h⟩).2, by { simp only [], split_ifs at *; simp only [perm.inv_apply_self, subtype.coe_eta, subtype.coe_mk, not_true, *] at * }, λ x, have h : ∀ h : p x, p (f⁻¹ ⟨x, h⟩), from λ h, (f⁻¹ ⟨x, h⟩).2, by { simp only [], split_ifs at *; simp only [perm.apply_inv_self, subtype.coe_eta, subtype.coe_mk, not_true, *] at *}⟩, map_one' := begin ext, dsimp, split_ifs; refl, end, map_mul' := λ f g, equiv.ext $ λ x, begin by_cases h : p x, { have h₁ : p (f (g ⟨x, h⟩)), from (f (g ⟨x, h⟩)).2, have h₂ : p (g ⟨x, h⟩), from (g ⟨x, h⟩).2, simp only [h, h₂, coe_fn_mk, perm.mul_apply, dif_pos, subtype.coe_eta] }, { simp only [h, coe_fn_mk, perm.mul_apply, dif_neg, not_false_iff] } end } lemma eq_inv_iff_eq {f : perm α} {x y : α} : x = f⁻¹ y ↔ f x = y := by conv {to_lhs, rw [← injective.eq_iff f.injective, apply_inv_self]} lemma inv_eq_iff_eq {f : perm α} {x y : α} : f⁻¹ x = y ↔ x = f y := by rw [eq_comm, eq_inv_iff_eq, eq_comm] /-- Two permutations `f` and `g` are `disjoint` if their supports are disjoint, i.e., every element is fixed either by `f`, or by `g`. -/ def disjoint (f g : perm α) := ∀ x, f x = x ∨ g x = x @[symm] lemma disjoint.symm {f g : perm α} : disjoint f g → disjoint g f := by simp only [disjoint, or.comm, imp_self] lemma disjoint_comm {f g : perm α} : disjoint f g ↔ disjoint g f := ⟨disjoint.symm, disjoint.symm⟩ lemma disjoint_mul_comm {f g : perm α} (h : disjoint f g) : f * g = g * f := equiv.ext $ λ x, (h x).elim (λ hf, (h (g x)).elim (λ hg, by simp [mul_apply, hf, hg]) (λ hg, by simp [mul_apply, hf, g.injective hg])) (λ hg, (h (f x)).elim (λ hf, by simp [mul_apply, f.injective hf, hg]) (λ hf, by simp [mul_apply, hf, hg])) @[simp] lemma disjoint_one_left (f : perm α) : disjoint 1 f := λ _, or.inl rfl @[simp] lemma disjoint_one_right (f : perm α) : disjoint f 1 := λ _, or.inr rfl lemma disjoint_mul_left {f g h : perm α} (H1 : disjoint f h) (H2 : disjoint g h) : disjoint (f * g) h := λ x, by cases H1 x; cases H2 x; simp * lemma disjoint_mul_right {f g h : perm α} (H1 : disjoint f g) (H2 : disjoint f h) : disjoint f (g * h) := by rw disjoint_comm; exact disjoint_mul_left H1.symm H2.symm lemma disjoint_prod_right {f : perm α} (l : list (perm α)) (h : ∀ g ∈ l, disjoint f g) : disjoint f l.prod := begin induction l with g l ih, { exact disjoint_one_right _ }, { rw list.prod_cons; exact disjoint_mul_right (h _ (list.mem_cons_self _ _)) (ih (λ g hg, h g (list.mem_cons_of_mem _ hg))) } end lemma disjoint_prod_perm {l₁ l₂ : list (perm α)} (hl : l₁.pairwise disjoint) (hp : l₁ ~ l₂) : l₁.prod = l₂.prod := hp.prod_eq' $ hl.imp $ λ f g, disjoint_mul_comm lemma of_subtype_subtype_perm {f : perm α} {p : α → Prop} [decidable_pred p] (h₁ : ∀ x, p x ↔ p (f x)) (h₂ : ∀ x, f x ≠ x → p x) : of_subtype (subtype_perm f h₁) = f := equiv.ext $ λ x, begin rw [of_subtype, subtype_perm], by_cases hx : p x, { simp only [hx, coe_fn_mk, dif_pos, monoid_hom.coe_mk, subtype.coe_mk]}, { haveI := classical.prop_decidable, simp only [hx, not_not.mp (mt (h₂ x) hx), coe_fn_mk, dif_neg, not_false_iff, monoid_hom.coe_mk] } end lemma of_subtype_apply_of_not_mem {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) {x : α} (hx : ¬ p x) : of_subtype f x = x := dif_neg hx lemma mem_iff_of_subtype_apply_mem {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) (x : α) : p x ↔ p ((of_subtype f : α → α) x) := if h : p x then by dsimp [of_subtype]; simpa [h] using (f ⟨x, h⟩).2 else by simp [h, of_subtype_apply_of_not_mem f h] @[simp] lemma subtype_perm_of_subtype {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) : subtype_perm (of_subtype f) (mem_iff_of_subtype_apply_mem f) = f := equiv.ext $ λ ⟨x, hx⟩, by dsimp [subtype_perm, of_subtype]; simp [show p x, from hx] lemma pow_apply_eq_self_of_apply_eq_self {f : perm α} {x : α} (hfx : f x = x) : ∀ n : ℕ, (f ^ n) x = x | 0 := rfl | (n+1) := by rw [pow_succ', mul_apply, hfx, pow_apply_eq_self_of_apply_eq_self] lemma gpow_apply_eq_self_of_apply_eq_self {f : perm α} {x : α} (hfx : f x = x) : ∀ n : ℤ, (f ^ n) x = x | (n : ℕ) := pow_apply_eq_self_of_apply_eq_self hfx n | -[1+ n] := by rw [gpow_neg_succ_of_nat, inv_eq_iff_eq, pow_apply_eq_self_of_apply_eq_self hfx] lemma pow_apply_eq_of_apply_apply_eq_self {f : perm α} {x : α} (hffx : f (f x) = x) : ∀ n : ℕ, (f ^ n) x = x ∨ (f ^ n) x = f x | 0 := or.inl rfl | (n+1) := (pow_apply_eq_of_apply_apply_eq_self n).elim (λ h, or.inr (by rw [pow_succ, mul_apply, h])) (λ h, or.inl (by rw [pow_succ, mul_apply, h, hffx])) lemma gpow_apply_eq_of_apply_apply_eq_self {f : perm α} {x : α} (hffx : f (f x) = x) : ∀ i : ℤ, (f ^ i) x = x ∨ (f ^ i) x = f x | (n : ℕ) := pow_apply_eq_of_apply_apply_eq_self hffx n | -[1+ n] := by rw [gpow_neg_succ_of_nat, inv_eq_iff_eq, ← injective.eq_iff f.injective, ← mul_apply, ← pow_succ, eq_comm, inv_eq_iff_eq, ← mul_apply, ← pow_succ', @eq_comm _ x, or.comm]; exact pow_apply_eq_of_apply_apply_eq_self hffx _ variable [decidable_eq α] /-- The `finset` of nonfixed points of a permutation. -/ def support [fintype α] (f : perm α) := univ.filter (λ x, f x ≠ x) @[simp] lemma mem_support [fintype α] {f : perm α} {x : α} : x ∈ f.support ↔ f x ≠ x := by simp only [support, true_and, mem_filter, mem_univ] /-- `f.is_swap` indicates that the permutation `f` is a transposition of two elements. -/ def is_swap (f : perm α) := ∃ x y, x ≠ y ∧ f = swap x y lemma swap_mul_eq_mul_swap (f : perm α) (x y : α) : swap x y * f = f * swap (f⁻¹ x) (f⁻¹ y) := equiv.ext $ λ z, begin simp only [perm.mul_apply, swap_apply_def], split_ifs; simp only [perm.apply_inv_self, *, eq_inv_iff_eq,eq_self_iff_true, not_true] at * end lemma mul_swap_eq_swap_mul (f : perm α) (x y : α) : f * swap x y = swap (f x) (f y) * f := by rw [swap_mul_eq_mul_swap, inv_apply_self, inv_apply_self] /-- Multiplying a permutation with `swap i j` twice gives the original permutation. This specialization of `swap_mul_self` is useful when using cosets of permutations. -/ @[simp] lemma swap_mul_self_mul (i j : α) (σ : perm α) : equiv.swap i j * (equiv.swap i j * σ) = σ := by rw [←mul_assoc (swap i j) (swap i j) σ, equiv.swap_mul_self, one_mul] lemma swap_mul_eq_iff {i j : α} {σ : perm α} : swap i j * σ = σ ↔ i = j := ⟨(assume h, have swap_id : swap i j = 1 := mul_right_cancel (trans h (one_mul σ).symm), by {rw [←swap_apply_right i j, swap_id], refl}), (assume h, by erw [h, swap_self, one_mul])⟩ lemma is_swap_of_subtype {p : α → Prop} [decidable_pred p] {f : perm (subtype p)} (h : is_swap f) : is_swap (of_subtype f) := let ⟨⟨x, hx⟩, ⟨y, hy⟩, hxy⟩ := h in ⟨x, y, by simp only [ne.def] at hxy; tauto, equiv.ext $ λ z, begin rw [hxy.2, of_subtype], simp only [swap_apply_def, coe_fn_mk, swap_inv, subtype.mk_eq_mk, monoid_hom.coe_mk], split_ifs; rw subtype.coe_mk <|> cc, end⟩ lemma ne_and_ne_of_swap_mul_apply_ne_self {f : perm α} {x y : α} (hy : (swap x (f x) * f) y ≠ y) : f y ≠ y ∧ y ≠ x := begin simp only [swap_apply_def, mul_apply, injective.eq_iff f.injective] at *, by_cases h : f y = x, { split; intro; simp only [*, if_true, eq_self_iff_true, not_true, ne.def] at *}, { split_ifs at hy; cc } end lemma support_swap_mul_eq [fintype α] {f : perm α} {x : α} (hffx : f (f x) ≠ x) : (swap x (f x) * f).support = f.support.erase x := have hfx : f x ≠ x, from λ hfx, by simpa [hfx] using hffx, finset.ext $ λ y, ⟨λ hy, have hy' : (swap x (f x) * f) y ≠ y, from mem_support.1 hy, mem_erase.2 ⟨λ hyx, by simp [hyx, mul_apply, *] at *, mem_support.2 $ λ hfy, by simp only [mul_apply, swap_apply_def, hfy] at hy'; split_ifs at hy'; simp only [*, eq_self_iff_true, not_true, ne.def, apply_eq_iff_eq] at *⟩, λ hy, by simp only [mem_erase, mem_support, swap_apply_def, mul_apply] at *; intro; split_ifs at *; simp only [*, eq_self_iff_true, not_true, ne.def] at *⟩ lemma card_support_swap_mul [fintype α] {f : perm α} {x : α} (hx : f x ≠ x) : (swap x (f x) * f).support.card < f.support.card := finset.card_lt_card ⟨λ z hz, mem_support.2 (ne_and_ne_of_swap_mul_apply_ne_self (mem_support.1 hz)).1, λ h, absurd (h (mem_support.2 hx)) (mt mem_support.1 (by simp))⟩ /-- Given a list `l : list α` and a permutation `f : perm α` such that the nonfixed points of `f` are in `l`, recursively factors `f` as a product of transpositions. -/ def swap_factors_aux : Π (l : list α) (f : perm α), (∀ {x}, f x ≠ x → x ∈ l) → {l : list (perm α) // l.prod = f ∧ ∀ g ∈ l, is_swap g} | [] := λ f h, ⟨[], equiv.ext $ λ x, by rw [list.prod_nil]; exact eq.symm (not_not.1 (mt h (list.not_mem_nil _))), by simp⟩ | (x :: l) := λ f h, if hfx : x = f x then swap_factors_aux l f (λ y hy, list.mem_of_ne_of_mem (λ h : y = x, by simpa [h, hfx.symm] using hy) (h hy)) else let m := swap_factors_aux l (swap x (f x) * f) (λ y hy, have f y ≠ y ∧ y ≠ x, from ne_and_ne_of_swap_mul_apply_ne_self hy, list.mem_of_ne_of_mem this.2 (h this.1)) in ⟨swap x (f x) :: m.1, by rw [list.prod_cons, m.2.1, ← mul_assoc, mul_def (swap x (f x)), swap_swap, ← one_def, one_mul], λ g hg, ((list.mem_cons_iff _ _ _).1 hg).elim (λ h, ⟨x, f x, hfx, h⟩) (m.2.2 _)⟩ /-- `swap_factors` represents a permutation as a product of a list of transpositions. The representation is non unique and depends on the linear order structure. For types without linear order `trunc_swap_factors` can be used -/ def swap_factors [fintype α] [linear_order α] (f : perm α) : {l : list (perm α) // l.prod = f ∧ ∀ g ∈ l, is_swap g} := swap_factors_aux ((@univ α _).sort (≤)) f (λ _ _, (mem_sort _).2 (mem_univ _)) /-- This computably represents the fact that any permutation can be represented as the product of a list of transpositions. -/ def trunc_swap_factors [fintype α] (f : perm α) : trunc {l : list (perm α) // l.prod = f ∧ ∀ g ∈ l, is_swap g} := quotient.rec_on_subsingleton (@univ α _).1 (λ l h, trunc.mk (swap_factors_aux l f h)) (show ∀ x, f x ≠ x → x ∈ (@univ α _).1, from λ _ _, mem_univ _) @[elab_as_eliminator] lemma swap_induction_on [fintype α] {P : perm α → Prop} (f : perm α) : P 1 → (∀ f x y, x ≠ y → P f → P (swap x y * f)) → P f := begin cases trunc.out (trunc_swap_factors f) with l hl, induction l with g l ih generalizing f, { simp only [hl.left.symm, list.prod_nil, forall_true_iff] {contextual := tt}}, { assume h1 hmul_swap, rcases hl.2 g (by simp) with ⟨x, y, hxy⟩, rw [← hl.1, list.prod_cons, hxy.2], exact hmul_swap _ _ _ hxy.1 (ih _ ⟨rfl, λ v hv, hl.2 _ (list.mem_cons_of_mem _ hv)⟩ h1 hmul_swap) } end lemma swap_mul_swap_mul_swap {x y z : α} (hwz: x ≠ y) (hxz : x ≠ z) : swap y z * swap x y * swap y z = swap z x := equiv.ext $ λ n, by simp only [swap_apply_def, mul_apply]; split_ifs; cc lemma is_conj_swap {w x y z : α} (hwx : w ≠ x) (hyz : y ≠ z) : is_conj (swap w x) (swap y z) := have h : ∀ {y z : α}, y ≠ z → w ≠ z → (swap w y * swap x z) * swap w x * (swap w y * swap x z)⁻¹ = swap y z := λ y z hyz hwz, by rw [mul_inv_rev, swap_inv, swap_inv, mul_assoc (swap w y), mul_assoc (swap w y), ← mul_assoc _ (swap x z), swap_mul_swap_mul_swap hwx hwz, ← mul_assoc, swap_mul_swap_mul_swap hwz.symm hyz.symm], if hwz : w = z then have hwy : w ≠ y, by cc, ⟨swap w z * swap x y, by rw [swap_comm y z, h hyz.symm hwy]⟩ else ⟨swap w y * swap x z, h hyz hwz⟩ /-- set of all pairs (⟨a, b⟩ : Σ a : fin n, fin n) such that b < a -/ def fin_pairs_lt (n : ℕ) : finset (Σ a : fin n, fin n) := (univ : finset (fin n)).sigma (λ a, (range a).attach_fin (λ m hm, lt_trans (mem_range.1 hm) a.2)) lemma mem_fin_pairs_lt {n : ℕ} {a : Σ a : fin n, fin n} : a ∈ fin_pairs_lt n ↔ a.2 < a.1 := by simp only [fin_pairs_lt, fin.lt_iff_coe_lt_coe, true_and, mem_attach_fin, mem_range, mem_univ, mem_sigma] /-- `sign_aux σ` is the sign of a permutation on `fin n`, defined as the parity of the number of pairs `(x₁, x₂)` such that `x₂ < x₁` but `σ x₁ ≤ σ x₂` -/ def sign_aux {n : ℕ} (a : perm (fin n)) : units ℤ := ∏ x in fin_pairs_lt n, if a x.1 ≤ a x.2 then -1 else 1 @[simp] lemma sign_aux_one (n : ℕ) : sign_aux (1 : perm (fin n)) = 1 := begin unfold sign_aux, conv { to_rhs, rw ← @finset.prod_const_one _ (units ℤ) (fin_pairs_lt n) }, exact finset.prod_congr rfl (λ a ha, if_neg (not_le_of_gt (mem_fin_pairs_lt.1 ha))) end /-- `sign_bij_aux f ⟨a, b⟩` returns the pair consisting of `f a` and `f b` in decreasing order. -/ def sign_bij_aux {n : ℕ} (f : perm (fin n)) (a : Σ a : fin n, fin n) : Σ a : fin n, fin n := if hxa : f a.2 < f a.1 then ⟨f a.1, f a.2⟩ else ⟨f a.2, f a.1⟩ lemma sign_bij_aux_inj {n : ℕ} {f : perm (fin n)} : ∀ a b : Σ a : fin n, fin n, a ∈ fin_pairs_lt n → b ∈ fin_pairs_lt n → sign_bij_aux f a = sign_bij_aux f b → a = b := λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩ ha hb h, begin unfold sign_bij_aux at h, rw mem_fin_pairs_lt at *, have : ¬b₁ < b₂ := not_lt_of_ge (le_of_lt hb), split_ifs at h; simp only [*, (equiv.injective f).eq_iff, eq_self_iff_true, and_self, heq_iff_eq] at *, end lemma sign_bij_aux_surj {n : ℕ} {f : perm (fin n)} : ∀ a ∈ fin_pairs_lt n, ∃ b ∈ fin_pairs_lt n, a = sign_bij_aux f b := λ ⟨a₁, a₂⟩ ha, if hxa : f⁻¹ a₂ < f⁻¹ a₁ then ⟨⟨f⁻¹ a₁, f⁻¹ a₂⟩, mem_fin_pairs_lt.2 hxa, by dsimp [sign_bij_aux]; rw [apply_inv_self, apply_inv_self, dif_pos (mem_fin_pairs_lt.1 ha)]⟩ else ⟨⟨f⁻¹ a₂, f⁻¹ a₁⟩, mem_fin_pairs_lt.2 $ lt_of_le_of_ne (le_of_not_gt hxa) $ λ h, by simpa [mem_fin_pairs_lt, (f⁻¹).injective h, lt_irrefl] using ha, by dsimp [sign_bij_aux]; rw [apply_inv_self, apply_inv_self, dif_neg (not_lt_of_ge (le_of_lt (mem_fin_pairs_lt.1 ha)))]⟩ lemma sign_bij_aux_mem {n : ℕ} {f : perm (fin n)}: ∀ a : Σ a : fin n, fin n, a ∈ fin_pairs_lt n → sign_bij_aux f a ∈ fin_pairs_lt n := λ ⟨a₁, a₂⟩ ha, begin unfold sign_bij_aux, split_ifs with h, { exact mem_fin_pairs_lt.2 h }, { exact mem_fin_pairs_lt.2 (lt_of_le_of_ne (le_of_not_gt h) (λ h, ne_of_lt (mem_fin_pairs_lt.1 ha) (f.injective h.symm))) } end @[simp] lemma sign_aux_inv {n : ℕ} (f : perm (fin n)) : sign_aux f⁻¹ = sign_aux f := prod_bij (λ a ha, sign_bij_aux f⁻¹ a) sign_bij_aux_mem (λ ⟨a, b⟩ hab, if h : f⁻¹ b < f⁻¹ a then by rw [sign_bij_aux, dif_pos h, if_neg (not_le_of_gt h), apply_inv_self, apply_inv_self, if_neg (not_le_of_gt $ mem_fin_pairs_lt.1 hab)] else by rw [sign_bij_aux, if_pos (le_of_not_gt h), dif_neg h, apply_inv_self, apply_inv_self, if_pos (le_of_lt $ mem_fin_pairs_lt.1 hab)]) sign_bij_aux_inj sign_bij_aux_surj lemma sign_aux_mul {n : ℕ} (f g : perm (fin n)) : sign_aux (f * g) = sign_aux f * sign_aux g := begin rw ← sign_aux_inv g, unfold sign_aux, rw ← prod_mul_distrib, refine prod_bij (λ a ha, sign_bij_aux g a) sign_bij_aux_mem _ sign_bij_aux_inj sign_bij_aux_surj, rintros ⟨a, b⟩ hab, rw [sign_bij_aux, mul_apply, mul_apply], rw mem_fin_pairs_lt at hab, by_cases h : g b < g a, { rw dif_pos h, simp only [not_le_of_gt hab, mul_one, perm.inv_apply_self, if_false] }, { rw [dif_neg h, inv_apply_self, inv_apply_self, if_pos (le_of_lt hab)], by_cases h₁ : f (g b) ≤ f (g a), { have : f (g b) ≠ f (g a), { rw [ne.def, injective.eq_iff f.injective, injective.eq_iff g.injective]; exact ne_of_lt hab }, rw [if_pos h₁, if_neg (not_le_of_gt (lt_of_le_of_ne h₁ this))], refl }, { rw [if_neg h₁, if_pos (le_of_lt (lt_of_not_ge h₁))], refl } } end private lemma sign_aux_swap_zero_one {n : ℕ} (hn : 2 ≤ n) : sign_aux (swap (⟨0, lt_of_lt_of_le dec_trivial hn⟩ : fin n) ⟨1, lt_of_lt_of_le dec_trivial hn⟩) = -1 := let zero : fin n := ⟨0, lt_of_lt_of_le dec_trivial hn⟩ in let one : fin n := ⟨1, lt_of_lt_of_le dec_trivial hn⟩ in have hzo : zero < one := dec_trivial, show _ = ∏ x : Σ a : fin n, fin n in {(⟨one, zero⟩ : Σ a : fin n, fin n)}, if (equiv.swap zero one) x.1 ≤ swap zero one x.2 then (-1 : units ℤ) else 1, begin refine eq.symm (prod_subset (λ ⟨x₁, x₂⟩, by simp [mem_fin_pairs_lt, hzo] {contextual := tt}) (λ a ha₁ ha₂, _)), rcases a with ⟨⟨a₁, ha₁⟩, ⟨a₂, ha₂⟩⟩, replace ha₁ : a₂ < a₁ := mem_fin_pairs_lt.1 ha₁, simp only [swap_apply_def], have : ¬ 1 ≤ a₂ → a₂ = 0, from λ h, nat.le_zero_iff.1 (nat.le_of_lt_succ (lt_of_not_ge h)), have : a₁ ≤ 1 → a₁ = 0 ∨ a₁ = 1, from nat.cases_on a₁ (λ _, or.inl rfl) (λ a₁, nat.cases_on a₁ (λ _, or.inr rfl) (λ _ h, absurd h dec_trivial)), split_ifs; simp only [*, not_le.symm, iff.intro fin.veq_of_eq fin.eq_of_veq, nat.le_zero_iff, eq_self_iff_true, not_true, fin.le_def, one, nat.zero_le, and_self, heq_iff_eq, mem_singleton, forall_prop_of_true, or_self, le_refl] at *, end lemma sign_aux_swap : ∀ {n : ℕ} {x y : fin n} (hxy : x ≠ y), sign_aux (swap x y) = -1 | 0 := dec_trivial | 1 := dec_trivial | (n+2) := λ x y hxy, have h2n : 2 ≤ n + 2 := dec_trivial, by rw [← is_conj_iff_eq, ← sign_aux_swap_zero_one h2n]; exact (monoid_hom.mk' sign_aux sign_aux_mul).map_is_conj (is_conj_swap hxy dec_trivial) /-- When the list `l : list α` contains all nonfixed points of the permutation `f : perm α`, `sign_aux2 l f` recursively calculates the sign of `f`. -/ def sign_aux2 : list α → perm α → units ℤ | [] f := 1 | (x::l) f := if x = f x then sign_aux2 l f else -sign_aux2 l (swap x (f x) * f) lemma sign_aux_eq_sign_aux2 {n : ℕ} : ∀ (l : list α) (f : perm α) (e : α ≃ fin n) (h : ∀ x, f x ≠ x → x ∈ l), sign_aux ((e.symm.trans f).trans e) = sign_aux2 l f | [] f e h := have f = 1, from equiv.ext $ λ y, not_not.1 (mt (h y) (list.not_mem_nil _)), by rw [this, one_def, equiv.trans_refl, equiv.symm_trans, ← one_def, sign_aux_one, sign_aux2] | (x::l) f e h := begin rw sign_aux2, by_cases hfx : x = f x, { rw if_pos hfx, exact sign_aux_eq_sign_aux2 l f _ (λ y (hy : f y ≠ y), list.mem_of_ne_of_mem (λ h : y = x, by simpa [h, hfx.symm] using hy) (h y hy) ) }, { have hy : ∀ y : α, (swap x (f x) * f) y ≠ y → y ∈ l, from λ y hy, have f y ≠ y ∧ y ≠ x, from ne_and_ne_of_swap_mul_apply_ne_self hy, list.mem_of_ne_of_mem this.2 (h _ this.1), have : (e.symm.trans (swap x (f x) * f)).trans e = (swap (e x) (e (f x))) * (e.symm.trans f).trans e, by ext; simp [← equiv.symm_trans_swap_trans, mul_def], have hefx : e x ≠ e (f x), from mt (injective.eq_iff e.injective).1 hfx, rw [if_neg hfx, ← sign_aux_eq_sign_aux2 _ _ e hy, this, sign_aux_mul, sign_aux_swap hefx], simp only [units.neg_neg, one_mul, units.neg_mul]} end /-- When the multiset `s : multiset α` contains all nonfixed points of the permutation `f : perm α`, `sign_aux2 f _` recursively calculates the sign of `f`. -/ def sign_aux3 [fintype α] (f : perm α) {s : multiset α} : (∀ x, x ∈ s) → units ℤ := quotient.hrec_on s (λ l h, sign_aux2 l f) (trunc.induction_on (equiv_fin α) (λ e l₁ l₂ h, function.hfunext (show (∀ x, x ∈ l₁) = ∀ x, x ∈ l₂, by simp only [h.mem_iff]) (λ h₁ h₂ _, by rw [← sign_aux_eq_sign_aux2 _ _ e (λ _ _, h₁ _), ← sign_aux_eq_sign_aux2 _ _ e (λ _ _, h₂ _)]))) lemma sign_aux3_mul_and_swap [fintype α] (f g : perm α) (s : multiset α) (hs : ∀ x, x ∈ s) : sign_aux3 (f * g) hs = sign_aux3 f hs * sign_aux3 g hs ∧ ∀ x y, x ≠ y → sign_aux3 (swap x y) hs = -1 := let ⟨l, hl⟩ := quotient.exists_rep s in let ⟨e, _⟩ := trunc.exists_rep (equiv_fin α) in begin clear _let_match _let_match, subst hl, show sign_aux2 l (f * g) = sign_aux2 l f * sign_aux2 l g ∧ ∀ x y, x ≠ y → sign_aux2 l (swap x y) = -1, have hfg : (e.symm.trans (f * g)).trans e = (e.symm.trans f).trans e * (e.symm.trans g).trans e, from equiv.ext (λ h, by simp [mul_apply]), split, { rw [← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), ← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), ← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), hfg, sign_aux_mul] }, { assume x y hxy, have hexy : e x ≠ e y, from mt (injective.eq_iff e.injective).1 hxy, rw [← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), equiv.symm_trans_swap_trans, sign_aux_swap hexy] } end /-- `sign` of a permutation returns the signature or parity of a permutation, `1` for even permutations, `-1` for odd permutations. It is the unique surjective group homomorphism from `perm α` to the group with two elements.-/ def sign [fintype α] : perm α →* units ℤ := monoid_hom.mk' (λ f, sign_aux3 f mem_univ) (λ f g, (sign_aux3_mul_and_swap f g _ mem_univ).1) section sign variable [fintype α] @[simp] lemma sign_mul (f g : perm α) : sign (f * g) = sign f * sign g := monoid_hom.map_mul sign f g @[simp] lemma sign_one : (sign (1 : perm α)) = 1 := monoid_hom.map_one sign @[simp] lemma sign_refl : sign (equiv.refl α) = 1 := monoid_hom.map_one sign @[simp] lemma sign_inv (f : perm α) : sign f⁻¹ = sign f := by rw [monoid_hom.map_inv sign f, int.units_inv_eq_self] lemma sign_swap {x y : α} (h : x ≠ y) : sign (swap x y) = -1 := (sign_aux3_mul_and_swap 1 1 _ mem_univ).2 x y h @[simp] lemma sign_swap' {x y : α} : (swap x y).sign = if x = y then 1 else -1 := if H : x = y then by simp [H, swap_self] else by simp [sign_swap H, H] lemma sign_eq_of_is_swap {f : perm α} (h : is_swap f) : sign f = -1 := let ⟨x, y, hxy⟩ := h in hxy.2.symm ▸ sign_swap hxy.1 lemma sign_aux3_symm_trans_trans [decidable_eq β] [fintype β] (f : perm α) (e : α ≃ β) {s : multiset α} {t : multiset β} (hs : ∀ x, x ∈ s) (ht : ∀ x, x ∈ t) : sign_aux3 ((e.symm.trans f).trans e) ht = sign_aux3 f hs := quotient.induction_on₂ t s (λ l₁ l₂ h₁ h₂, show sign_aux2 _ _ = sign_aux2 _ _, from let n := trunc.out (equiv_fin β) in by rw [← sign_aux_eq_sign_aux2 _ _ n (λ _ _, h₁ _), ← sign_aux_eq_sign_aux2 _ _ (e.trans n) (λ _ _, h₂ _)]; exact congr_arg sign_aux (equiv.ext (λ x, by simp only [equiv.coe_trans, apply_eq_iff_eq, symm_trans_apply]))) ht hs lemma sign_symm_trans_trans [decidable_eq β] [fintype β] (f : perm α) (e : α ≃ β) : sign ((e.symm.trans f).trans e) = sign f := sign_aux3_symm_trans_trans f e mem_univ mem_univ lemma sign_prod_list_swap {l : list (perm α)} (hl : ∀ g ∈ l, is_swap g) : sign l.prod = (-1) ^ l.length := have h₁ : l.map sign = list.repeat (-1) l.length := list.eq_repeat.2 ⟨by simp, λ u hu, let ⟨g, hg⟩ := list.mem_map.1 hu in hg.2 ▸ sign_eq_of_is_swap (hl _ hg.1)⟩, by rw [← list.prod_repeat, ← h₁, list.prod_hom _ (@sign α _ _)] lemma sign_surjective (hα : 1 < fintype.card α) : function.surjective (sign : perm α → units ℤ) := λ a, (int.units_eq_one_or a).elim (λ h, ⟨1, by simp [h]⟩) (λ h, let ⟨x⟩ := fintype.card_pos_iff.1 (lt_trans zero_lt_one hα) in let ⟨y, hxy⟩ := fintype.exists_ne_of_one_lt_card hα x in ⟨swap y x, by rw [sign_swap hxy, h]⟩ ) lemma eq_sign_of_surjective_hom {s : perm α →* units ℤ} (hs : surjective s) : s = sign := have ∀ {f}, is_swap f → s f = -1 := λ f ⟨x, y, hxy, hxy'⟩, hxy'.symm ▸ by_contradiction (λ h, have ∀ f, is_swap f → s f = 1 := λ f ⟨a, b, hab, hab'⟩, by rw [← is_conj_iff_eq, ← or.resolve_right (int.units_eq_one_or _) h, hab']; exact (monoid_hom.of s).map_is_conj (is_conj_swap hab hxy), let ⟨g, hg⟩ := hs (-1) in let ⟨l, hl⟩ := trunc.out (trunc_swap_factors g) in have ∀ a ∈ l.map s, a = (1 : units ℤ) := λ a ha, let ⟨g, hg⟩ := list.mem_map.1 ha in hg.2 ▸ this _ (hl.2 _ hg.1), have s l.prod = 1, by rw [← l.prod_hom s, list.eq_repeat'.2 this, list.prod_repeat, one_pow], by rw [hl.1, hg] at this; exact absurd this dec_trivial), monoid_hom.ext $ λ f, let ⟨l, hl₁, hl₂⟩ := trunc.out (trunc_swap_factors f) in have hsl : ∀ a ∈ l.map s, a = (-1 : units ℤ) := λ a ha, let ⟨g, hg⟩ := list.mem_map.1 ha in hg.2 ▸ this (hl₂ _ hg.1), by rw [← hl₁, ← l.prod_hom s, list.eq_repeat'.2 hsl, list.length_map, list.prod_repeat, sign_prod_list_swap hl₂] lemma sign_subtype_perm (f : perm α) {p : α → Prop} [decidable_pred p] (h₁ : ∀ x, p x ↔ p (f x)) (h₂ : ∀ x, f x ≠ x → p x) : sign (subtype_perm f h₁) = sign f := let l := trunc.out (trunc_swap_factors (subtype_perm f h₁)) in have hl' : ∀ g' ∈ l.1.map of_subtype, is_swap g' := λ g' hg', let ⟨g, hg⟩ := list.mem_map.1 hg' in hg.2 ▸ is_swap_of_subtype (l.2.2 _ hg.1), have hl'₂ : (l.1.map of_subtype).prod = f, by rw [l.1.prod_hom of_subtype, l.2.1, of_subtype_subtype_perm _ h₂], by conv {congr, rw ← l.2.1, skip, rw ← hl'₂}; rw [sign_prod_list_swap l.2.2, sign_prod_list_swap hl', list.length_map] @[simp] lemma sign_of_subtype {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) : sign (of_subtype f) = sign f := have ∀ x, of_subtype f x ≠ x → p x, from λ x, not_imp_comm.1 (of_subtype_apply_of_not_mem f), by conv {to_rhs, rw [← subtype_perm_of_subtype f, sign_subtype_perm _ _ this]} lemma sign_eq_sign_of_equiv [decidable_eq β] [fintype β] (f : perm α) (g : perm β) (e : α ≃ β) (h : ∀ x, e (f x) = g (e x)) : sign f = sign g := have hg : g = (e.symm.trans f).trans e, from equiv.ext $ by simp [h], by rw [hg, sign_symm_trans_trans] lemma sign_bij [decidable_eq β] [fintype β] {f : perm α} {g : perm β} (i : Π x : α, f x ≠ x → β) (h : ∀ x hx hx', i (f x) hx' = g (i x hx)) (hi : ∀ x₁ x₂ hx₁ hx₂, i x₁ hx₁ = i x₂ hx₂ → x₁ = x₂) (hg : ∀ y, g y ≠ y → ∃ x hx, i x hx = y) : sign f = sign g := calc sign f = sign (@subtype_perm _ f (λ x, f x ≠ x) (by simp)) : eq.symm (sign_subtype_perm _ _ (λ _, id)) ... = sign (@subtype_perm _ g (λ x, g x ≠ x) (by simp)) : sign_eq_sign_of_equiv _ _ (equiv.of_bijective (λ x : {x // f x ≠ x}, (⟨i x.1 x.2, have f (f x) ≠ f x, from mt (λ h, f.injective h) x.2, by rw [← h _ x.2 this]; exact mt (hi _ _ this x.2) x.2⟩ : {y // g y ≠ y})) ⟨λ ⟨x, hx⟩ ⟨y, hy⟩ h, subtype.eq (hi _ _ _ _ (subtype.mk.inj h)), λ ⟨y, hy⟩, let ⟨x, hfx, hx⟩ := hg y hy in ⟨⟨x, hfx⟩, subtype.eq hx⟩⟩) (λ ⟨x, _⟩, subtype.eq (h x _ _)) ... = sign g : sign_subtype_perm _ _ (λ _, id) /-- A permutation is a cycle when any two nonfixed points of the permutation are related by repeated application of the permutation. -/ def is_cycle (f : perm β) := ∃ x, f x ≠ x ∧ ∀ y, f y ≠ y → ∃ i : ℤ, (f ^ i) x = y lemma is_cycle_swap {α : Type*} [decidable_eq α] {x y : α} (hxy : x ≠ y) : is_cycle (swap x y) := ⟨y, by rwa swap_apply_right, λ a (ha : ite (a = x) y (ite (a = y) x a) ≠ a), if hya : y = a then ⟨0, hya⟩ else ⟨1, by rw [gpow_one, swap_apply_def]; split_ifs at *; cc⟩⟩ lemma is_cycle_inv {f : perm β} (hf : is_cycle f) : is_cycle (f⁻¹) := let ⟨x, hx⟩ := hf in ⟨x, by simp only [inv_eq_iff_eq, *, forall_prop_of_true, ne.def] at *; cc, λ y hy, let ⟨i, hi⟩ := hx.2 y (by simp only [inv_eq_iff_eq, *, forall_prop_of_true, ne.def] at *; cc) in ⟨-i, by rwa [gpow_neg, inv_gpow, inv_inv]⟩⟩ lemma exists_gpow_eq_of_is_cycle {f : perm β} (hf : is_cycle f) {x y : β} (hx : f x ≠ x) (hy : f y ≠ y) : ∃ i : ℤ, (f ^ i) x = y := let ⟨g, hg⟩ := hf in let ⟨a, ha⟩ := hg.2 x hx in let ⟨b, hb⟩ := hg.2 y hy in ⟨b - a, by rw [← ha, ← mul_apply, ← gpow_add, sub_add_cancel, hb]⟩ lemma is_cycle_swap_mul_aux₁ {α : Type*} [decidable_eq α] : ∀ (n : ℕ) {b x : α} {f : perm α} (hb : (swap x (f x) * f) b ≠ b) (h : (f ^ n) (f x) = b), ∃ i : ℤ, ((swap x (f x) * f) ^ i) (f x) = b | 0 := λ b x f hb h, ⟨0, h⟩ | (n+1 : ℕ) := λ b x f hb h, if hfbx : f x = b then ⟨0, hfbx⟩ else have f b ≠ b ∧ b ≠ x, from ne_and_ne_of_swap_mul_apply_ne_self hb, have hb' : (swap x (f x) * f) (f⁻¹ b) ≠ f⁻¹ b, by rw [mul_apply, apply_inv_self, swap_apply_of_ne_of_ne this.2 (ne.symm hfbx), ne.def, ← injective.eq_iff f.injective, apply_inv_self]; exact this.1, let ⟨i, hi⟩ := is_cycle_swap_mul_aux₁ n hb' (f.injective $ by rw [apply_inv_self]; rwa [pow_succ, mul_apply] at h) in ⟨i + 1, by rw [add_comm, gpow_add, mul_apply, hi, gpow_one, mul_apply, apply_inv_self, swap_apply_of_ne_of_ne (ne_and_ne_of_swap_mul_apply_ne_self hb).2 (ne.symm hfbx)]⟩ lemma is_cycle_swap_mul_aux₂ {α : Type*} [decidable_eq α] : ∀ (n : ℤ) {b x : α} {f : perm α} (hb : (swap x (f x) * f) b ≠ b) (h : (f ^ n) (f x) = b), ∃ i : ℤ, ((swap x (f x) * f) ^ i) (f x) = b | (n : ℕ) := λ b x f, is_cycle_swap_mul_aux₁ n | -[1+ n] := λ b x f hb h, if hfbx : f⁻¹ x = b then ⟨-1, by rwa [gpow_neg, gpow_one, mul_inv_rev, mul_apply, swap_inv, swap_apply_right]⟩ else if hfbx' : f x = b then ⟨0, hfbx'⟩ else have f b ≠ b ∧ b ≠ x := ne_and_ne_of_swap_mul_apply_ne_self hb, have hb : (swap x (f⁻¹ x) * f⁻¹) (f⁻¹ b) ≠ f⁻¹ b, by rw [mul_apply, swap_apply_def]; split_ifs; simp only [inv_eq_iff_eq, perm.mul_apply, gpow_neg_succ_of_nat, ne.def, perm.apply_inv_self] at *; cc, let ⟨i, hi⟩ := is_cycle_swap_mul_aux₁ n hb (show (f⁻¹ ^ n) (f⁻¹ x) = f⁻¹ b, by rw [← gpow_coe_nat, ← h, ← mul_apply, ← mul_apply, ← mul_apply, gpow_neg_succ_of_nat, ← inv_pow, pow_succ', mul_assoc, mul_assoc, inv_mul_self, mul_one, gpow_coe_nat, ← pow_succ', ← pow_succ]) in have h : (swap x (f⁻¹ x) * f⁻¹) (f x) = f⁻¹ x, by rw [mul_apply, inv_apply_self, swap_apply_left], ⟨-i, by rw [← add_sub_cancel i 1, neg_sub, sub_eq_add_neg, gpow_add, gpow_one, gpow_neg, ← inv_gpow, mul_inv_rev, swap_inv, mul_swap_eq_swap_mul, inv_apply_self, swap_comm _ x, gpow_add, gpow_one, mul_apply, mul_apply (_ ^ i), h, hi, mul_apply, apply_inv_self, swap_apply_of_ne_of_ne this.2 (ne.symm hfbx')]⟩ lemma eq_swap_of_is_cycle_of_apply_apply_eq_self {α : Type*} [decidable_eq α] {f : perm α} (hf : is_cycle f) {x : α} (hfx : f x ≠ x) (hffx : f (f x) = x) : f = swap x (f x) := equiv.ext $ λ y, let ⟨z, hz⟩ := hf in let ⟨i, hi⟩ := hz.2 x hfx in if hyx : y = x then by simp [hyx] else if hfyx : y = f x then by simp [hfyx, hffx] else begin rw [swap_apply_of_ne_of_ne hyx hfyx], refine by_contradiction (λ hy, _), cases hz.2 y hy with j hj, rw [← sub_add_cancel j i, gpow_add, mul_apply, hi] at hj, cases gpow_apply_eq_of_apply_apply_eq_self hffx (j - i) with hji hji, { rw [← hj, hji] at hyx, cc }, { rw [← hj, hji] at hfyx, cc } end lemma is_cycle_swap_mul {α : Type*} [decidable_eq α] {f : perm α} (hf : is_cycle f) {x : α} (hx : f x ≠ x) (hffx : f (f x) ≠ x) : is_cycle (swap x (f x) * f) := ⟨f x, by simp only [swap_apply_def, mul_apply]; split_ifs; simp [injective.eq_iff f.injective] at *; cc, λ y hy, let ⟨i, hi⟩ := exists_gpow_eq_of_is_cycle hf hx (ne_and_ne_of_swap_mul_apply_ne_self hy).1 in have hi : (f ^ (i - 1)) (f x) = y, from calc (f ^ (i - 1)) (f x) = (f ^ (i - 1) * f ^ (1 : ℤ)) x : by rw [gpow_one, mul_apply] ... = y : by rwa [← gpow_add, sub_add_cancel], is_cycle_swap_mul_aux₂ (i - 1) hy hi⟩ @[simp] lemma support_swap {x y : α} (hxy : x ≠ y) : (swap x y).support = {x, y} := finset.ext $ λ a, by simp [swap_apply_def]; split_ifs; cc lemma card_support_swap {x y : α} (hxy : x ≠ y) : (swap x y).support.card = 2 := show (swap x y).support.card = finset.card ⟨x ::ₘ y ::ₘ 0, by simp [hxy]⟩, from congr_arg card $ by rw [support_swap hxy]; simp [*, finset.ext_iff]; cc lemma sign_cycle : ∀ {f : perm α} (hf : is_cycle f), sign f = -(-1) ^ f.support.card | f := λ hf, let ⟨x, hx⟩ := hf in calc sign f = sign (swap x (f x) * (swap x (f x) * f)) : by rw [← mul_assoc, mul_def, mul_def, swap_swap, trans_refl] ... = -(-1) ^ f.support.card : if h1 : f (f x) = x then have h : swap x (f x) * f = 1, begin rw eq_swap_of_is_cycle_of_apply_apply_eq_self hf hx.1 h1, simp only [perm.mul_def, perm.one_def, swap_apply_left, swap_swap] end, by rw [sign_mul, sign_swap hx.1.symm, h, sign_one, eq_swap_of_is_cycle_of_apply_apply_eq_self hf hx.1 h1, card_support_swap hx.1.symm]; refl else have h : card (support (swap x (f x) * f)) + 1 = card (support f), by rw [← insert_erase (mem_support.2 hx.1), support_swap_mul_eq h1, card_insert_of_not_mem (not_mem_erase _ _)], have wf : card (support (swap x (f x) * f)) < card (support f), from card_support_swap_mul hx.1, by rw [sign_mul, sign_swap hx.1.symm, sign_cycle (is_cycle_swap_mul hf hx.1 h1), ← h]; simp only [pow_add, mul_one, units.neg_neg, one_mul, units.mul_neg, eq_self_iff_true, pow_one, units.neg_mul_neg] using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ f, f.support.card)⟩]} /-- If we apply `prod_extend_right a (σ a)` for all `a : α` in turn, we get `prod_congr_right σ`. -/ lemma prod_prod_extend_right {α : Type*} [decidable_eq α] (σ : α → perm β) {l : list α} (hl : l.nodup) (mem_l : ∀ a, a ∈ l) : (l.map (λ a, prod_extend_right a (σ a))).prod = prod_congr_right σ := begin ext ⟨a, b⟩ : 1, -- We'll use induction on the list of elements, -- but we have to keep track of whether we already passed `a` in the list. suffices : (a ∈ l ∧ (l.map (λ a, prod_extend_right a (σ a))).prod (a, b) = (a, σ a b)) ∨ (a ∉ l ∧ (l.map (λ a, prod_extend_right a (σ a))).prod (a, b) = (a, b)), { obtain ⟨_, prod_eq⟩ := or.resolve_right this (not_and.mpr (λ h _, h (mem_l a))), rw [prod_eq, prod_congr_right_apply] }, clear mem_l, induction l with a' l ih, { refine or.inr ⟨list.not_mem_nil _, _⟩, rw [list.map_nil, list.prod_nil, one_apply] }, rw [list.map_cons, list.prod_cons, mul_apply], rcases ih (list.nodup_cons.mp hl).2 with ⟨mem_l, prod_eq⟩ | ⟨not_mem_l, prod_eq⟩; rw prod_eq, { refine or.inl ⟨list.mem_cons_of_mem _ mem_l, _⟩, rw prod_extend_right_apply_ne _ (λ (h : a = a'), (list.nodup_cons.mp hl).1 (h ▸ mem_l)) }, by_cases ha' : a = a', { rw ← ha' at *, refine or.inl ⟨l.mem_cons_self a, _⟩, rw prod_extend_right_apply_eq }, { refine or.inr ⟨λ h, not_or ha' not_mem_l ((list.mem_cons_iff _ _ _).mp h), _⟩, rw prod_extend_right_apply_ne _ ha' }, end section open_locale classical lemma sign_prod_extend_right [fintype β] (a : α) (σ : perm β) : (prod_extend_right a σ).sign = σ.sign := sign_bij (λ (ab : α × β) _, ab.snd) (λ ⟨a', b⟩ hab hab', by simp [eq_of_prod_extend_right_ne hab]) (λ ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ hab₁ hab₂ h, by simpa [eq_of_prod_extend_right_ne hab₁, eq_of_prod_extend_right_ne hab₂] using h) (λ y hy, ⟨(a, y), by simpa, by simp⟩) lemma sign_prod_congr_right [fintype β] (σ : α → perm β) : sign (prod_congr_right σ) = ∏ k, (σ k).sign := begin obtain ⟨l, hl, mem_l⟩ := fintype.exists_univ_list α, have l_to_finset : l.to_finset = finset.univ, { apply eq_top_iff.mpr, intros b _, exact list.mem_to_finset.mpr (mem_l b) }, rw [← prod_prod_extend_right σ hl mem_l, sign.map_list_prod, list.map_map, ← l_to_finset, list.prod_to_finset _ hl], simp_rw ← λ a, sign_prod_extend_right a (σ a) end lemma sign_prod_congr_left [fintype β] (σ : α → perm β) : sign (prod_congr_left σ) = ∏ k, (σ k).sign := begin refine (sign_eq_sign_of_equiv _ _ (prod_comm β α) _).trans (sign_prod_congr_right σ), rintro ⟨b, α⟩, refl end end end sign end equiv.perm
1c4d4d727d4bf4af0e69155d9fec0cb160316ae0
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/linear_algebra/smodeq.lean
a2b42c9dd7e2d6e2567ee6edf3575256388e75bb
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,927
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import ring_theory.ideal.basic import data.polynomial.eval /-! # modular equivalence for submodule -/ open submodule variables {R : Type*} [ring R] variables {M : Type*} [add_comm_group M] [module R M] (U U₁ U₂ : submodule R M) variables {x x₁ x₂ y y₁ y₂ z z₁ z₂ : M} variables {N : Type*} [add_comm_group N] [module R N] (V V₁ V₂ : submodule R N) /-- A predicate saying two elements of a module are equivalent modulo a submodule. -/ def smodeq (x y : M) : Prop := (submodule.quotient.mk x : U.quotient) = submodule.quotient.mk y notation x ` ≡ `:50 y ` [SMOD `:50 N `]`:0 := smodeq N x y variables {U U₁ U₂} protected lemma smodeq.def : x ≡ y [SMOD U] ↔ (submodule.quotient.mk x : U.quotient) = submodule.quotient.mk y := iff.rfl namespace smodeq lemma sub_mem : x ≡ y [SMOD U] ↔ x - y ∈ U := by rw [smodeq.def, submodule.quotient.eq] @[simp] theorem top : x ≡ y [SMOD (⊤ : submodule R M)] := (submodule.quotient.eq ⊤).2 mem_top @[simp] theorem bot : x ≡ y [SMOD (⊥ : submodule R M)] ↔ x = y := by rw [smodeq.def, submodule.quotient.eq, mem_bot, sub_eq_zero] @[mono] theorem mono (HU : U₁ ≤ U₂) (hxy : x ≡ y [SMOD U₁]) : x ≡ y [SMOD U₂] := (submodule.quotient.eq U₂).2 $ HU $ (submodule.quotient.eq U₁).1 hxy @[refl] theorem refl : x ≡ x [SMOD U] := eq.refl _ @[symm] theorem symm (hxy : x ≡ y [SMOD U]) : y ≡ x [SMOD U] := hxy.symm @[trans] theorem trans (hxy : x ≡ y [SMOD U]) (hyz : y ≡ z [SMOD U]) : x ≡ z [SMOD U] := hxy.trans hyz theorem add (hxy₁ : x₁ ≡ y₁ [SMOD U]) (hxy₂ : x₂ ≡ y₂ [SMOD U]) : x₁ + x₂ ≡ y₁ + y₂ [SMOD U] := by { rw smodeq.def at hxy₁ hxy₂ ⊢, simp_rw [quotient.mk_add, hxy₁, hxy₂] } theorem smul (hxy : x ≡ y [SMOD U]) (c : R) : c • x ≡ c • y [SMOD U] := by { rw smodeq.def at hxy ⊢, simp_rw [quotient.mk_smul, hxy] } theorem zero : x ≡ 0 [SMOD U] ↔ x ∈ U := by rw [smodeq.def, submodule.quotient.eq, sub_zero] theorem map (hxy : x ≡ y [SMOD U]) (f : M →ₗ[R] N) : f x ≡ f y [SMOD U.map f] := (submodule.quotient.eq _).2 $ f.map_sub x y ▸ mem_map_of_mem $ (submodule.quotient.eq _).1 hxy theorem comap {f : M →ₗ[R] N} (hxy : f x ≡ f y [SMOD V]) : x ≡ y [SMOD V.comap f] := (submodule.quotient.eq _).2 $ show f (x - y) ∈ V, from (f.map_sub x y).symm ▸ (submodule.quotient.eq _).1 hxy lemma eval {R : Type*} [comm_ring R] {I : ideal R} {x y : R} (h : x ≡ y [SMOD I]) (f : polynomial R) : f.eval x ≡ f.eval y [SMOD I] := begin rw [smodeq.def] at h ⊢, show ideal.quotient.mk I (f.eval x) = ideal.quotient.mk I (f.eval y), change ideal.quotient.mk I x = ideal.quotient.mk I y at h, rw [← polynomial.eval₂_at_apply, ← polynomial.eval₂_at_apply, h], end end smodeq
b0b44001e5c58c8e8e176134d7aedae00ccc5a9d
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/interactive_auto.lean
519ebed454f8edb7dd5be380661b8852490a1fe7
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
13,978
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Sebastien Gouezel, Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.lint.default import Mathlib.tactic.dependencies import Mathlib.PostPort universes u namespace Mathlib namespace tactic namespace interactive /-- Similar to `constructor`, but does not reorder goals. -/ /-- `try_for n { tac }` executes `tac` for `n` ticks, otherwise uses `sorry` to close the goal. Never fails. Useful for debugging. -/ /-- Multiple `subst`. `substs x y z` is the same as `subst x, subst y, subst z`. -/ /-- Unfold coercion-related definitions -/ /-- Unfold `has_well_founded.r`, `sizeof` and other such definitions. -/ /-- Unfold auxiliary definitions associated with the current declaration. -/ /-- For debugging only. This tactic checks the current state for any missing dropped goals and restores them. Useful when there are no goals to solve but "result contains meta-variables". -/ /-- Like `try { tac }`, but in the case of failure it continues from the failure state instead of reverting to the original state. -/ /-- `id { tac }` is the same as `tac`, but it is useful for creating a block scope without requiring the goal to be solved at the end like `{ tac }`. It can also be used to enclose a non-interactive tactic for patterns like `tac1; id {tac2}` where `tac2` is non-interactive. -/ /-- `work_on_goal n { tac }` creates a block scope for the `n`-goal (indexed from zero), and does not require that the goal be solved at the end (any remaining subgoals are inserted back into the list of goals). Typically usage might look like: ```` intros, simp, apply lemma_1, work_on_goal 2 { dsimp, simp }, refl ```` See also `id { tac }`, which is equivalent to `work_on_goal 0 { tac }`. -/ /-- `swap n` will move the `n`th goal to the front. `swap` defaults to `swap 2`, and so interchanges the first and second goals. -/ /-- `rotate` moves the first goal to the back. `rotate n` will do this `n` times. -/ /-- Clear all hypotheses starting with `_`, like `_match` and `_let_match`. -/ /-- Acts like `have`, but removes a hypothesis with the same name as this one. For example if the state is `h : p ⊢ goal` and `f : p → q`, then after `replace h := f h` the goal will be `h : q ⊢ goal`, where `have h := f h` would result in the state `h : p, h : q ⊢ goal`. This can be used to simulate the `specialize` and `apply at` tactics of Coq. -/ /-- Make every proposition in the context decidable. -/ theorem generalize_a_aux {α : Sort u} (h : (x : Sort u) → (α → x) → x) : α := h α id /-- Like `generalize` but also considers assumptions specified by the user. The user can also specify to omit the goal. -/ /-- go from (x₀ : t₀) (x₁ : t₀) (x₂ : t₀) to (x₀ x₁ x₂ : t₀) -/ /-- Remove identity functions from a term. These are normally automatically generated with terms like `show t, from p` or `(p : t)` which translate to some variant on `@id t p` in order to retain the type. -/ /-- `refine_struct { .. }` acts like `refine` but works only with structure instance literals. It creates a goal for each missing field and tags it with the name of the field so that `have_field` can be used to generically refer to the field currently being refined. As an example, we can use `refine_struct` to automate the construction semigroup instances: ```lean refine_struct ( { .. } : semigroup α ), -- case semigroup, mul -- case semigroup, mul -- α : Type u, -- α : Type u, -- ⊢ α → α → α -- ⊢ α → α → α -- case semigroup, mul_assoc -- case semigroup, mul_assoc -- α : Type u, -- α : Type u, -- ⊢ ∀ (a b c : α), a * b * c = a * (b * c) -- ⊢ ∀ (a b c : α), a * b * c = a * (b * c) ``` `have_field`, used after `refine_struct _`, poses `field` as a local constant with the type of the field of the current goal: ```lean refine_struct ({ .. } : semigroup α), { have_field, ... }, { have_field, ... }, ``` behaves like ```lean refine_struct ({ .. } : semigroup α), { have field := @semigroup.mul, ... }, { have field := @semigroup.mul_assoc, ... }, ``` -/ /-- `guard_hyp' h : t` fails if the hypothesis `h` does not have type `t`. We use this tactic for writing tests. Fixes `guard_hyp` by instantiating meta variables -/ /-- `match_hyp h : t` fails if the hypothesis `h` does not match the type `t` (which may be a pattern). We use this tactic for writing tests. -/ /-- `guard_expr_strict t := e` fails if the expr `t` is not equal to `e`. By contrast to `guard_expr`, this tests strict (syntactic) equality. We use this tactic for writing tests. -/ /-- `guard_target_strict t` fails if the target of the main goal is not syntactically `t`. We use this tactic for writing tests. -/ /-- `guard_hyp_strict h : t` fails if the hypothesis `h` does not have type syntactically equal to `t`. We use this tactic for writing tests. -/ /-- Tests that there are `n` hypotheses in the current context. -/ /-- Test that `t` is the tag of the main goal. -/ /-- `guard_proof_term { t } e` applies tactic `t` and tests whether the resulting proof term unifies with `p`. -/ /-- `success_if_fail_with_msg { tac } msg` succeeds if the interactive tactic `tac` fails with error message `msg` (for test writing purposes). -/ /-- Get the field of the current goal. -/ /-- `have_field`, used after `refine_struct _` poses `field` as a local constant with the type of the field of the current goal: ```lean refine_struct ({ .. } : semigroup α), { have_field, ... }, { have_field, ... }, ``` behaves like ```lean refine_struct ({ .. } : semigroup α), { have field := @semigroup.mul, ... }, { have field := @semigroup.mul_assoc, ... }, ``` -/ /-- `apply_field` functions as `have_field, apply field, clear field` -/ /-- `apply_rules hs n` applies the list of lemmas `hs` and `assumption` on the first goal and the resulting subgoals, iteratively, at most `n` times. `n` is optional, equal to 50 by default. You can pass an `apply_cfg` option argument as `apply_rules hs n opt`. (A typical usage would be with `apply_rules hs n { md := reducible })`, which asks `apply_rules` to not unfold `semireducible` definitions (i.e. most) when checking if a lemma matches the goal.) `hs` can contain user attributes: in this case all theorems with this attribute are added to the list of rules. For instance: ```lean @[user_attribute] meta def mono_rules : user_attribute := { name := `mono_rules, descr := "lemmas usable to prove monotonicity" } attribute [mono_rules] add_le_add mul_le_mul_of_nonneg_right lemma my_test {a b c d e : real} (h1 : a ≤ b) (h2 : c ≤ d) (h3 : 0 ≤ e) : a + c * e + a + c + 0 ≤ b + d * e + b + d + e := -- any of the following lines solve the goal: -- any of the following lines solve the goal: add_le_add (add_le_add (add_le_add (add_le_add h1 (mul_le_mul_of_nonneg_right h2 h3)) h1 ) h2) h3 by apply_rules [add_le_add, mul_le_mul_of_nonneg_right] by apply_rules [mono_rules] by apply_rules mono_rules ``` -/ /-- `h_generalize Hx : e == x` matches on `cast _ e` in the goal and replaces it with `x`. It also adds `Hx : e == x` as an assumption. If `cast _ e` appears multiple times (not necessarily with the same proof), they are all replaced by `x`. `cast` `eq.mp`, `eq.mpr`, `eq.subst`, `eq.substr`, `eq.rec` and `eq.rec_on` are all treated as casts. - `h_generalize Hx : e == x with h` adds hypothesis `α = β` with `e : α, x : β`; - `h_generalize Hx : e == x with _` chooses automatically chooses the name of assumption `α = β`; - `h_generalize! Hx : e == x` reverts `Hx`; - when `Hx` is omitted, assumption `Hx : e == x` is not added. -/ /-- Tests whether `t` is definitionally equal to `p`. The difference with `guard_expr_eq` is that this uses definitional equality instead of alpha-equivalence. -/ /-- `guard_target' t` fails if the target of the main goal is not definitionally equal to `t`. We use this tactic for writing tests. The difference with `guard_target` is that this uses definitional equality instead of alpha-equivalence. -/ /-- a weaker version of `trivial` that tries to solve the goal by reflexivity or by reducing it to true, unfolding only `reducible` constants. -/ /-- Similar to `existsi`. `use x` will instantiate the first term of an `∃` or `Σ` goal with `x`. It will then try to close the new goal using `triv`, or try to simplify it by applying `exists_prop`. Unlike `existsi`, `x` is elaborated with respect to the expected type. `use` will alternatively take a list of terms `[x0, ..., xn]`. `use` will work with constructors of arbitrary inductive types. Examples: ```lean example (α : Type) : ∃ S : set α, S = S := by use ∅ example : ∃ x : ℤ, x = x := by use 42 example : ∃ n > 0, n = n := begin use 1, -- goal is now 1 > 0 ∧ 1 = 1, whereas it would be ∃ (H : 1 > 0), 1 = 1 after existsi 1. exact ⟨zero_lt_one, rfl⟩, end example : ∃ a b c : ℤ, a + b + c = 6 := by use [1, 2, 3] example : ∃ p : ℤ × ℤ, p.1 = 1 := by use ⟨1, 42⟩ example : Σ x y : ℤ, (ℤ × ℤ) × ℤ := by use [1, 2, 3, 4, 5] inductive foo | mk : ℕ → bool × ℕ → ℕ → foo example : foo := by use [100, tt, 4, 3] ``` -/ /-- `clear_aux_decl` clears every `aux_decl` in the local context for the current goal. This includes the induction hypothesis when using the equation compiler and `_let_match` and `_fun_match`. It is useful when using a tactic such as `finish`, `simp *` or `subst` that may use these auxiliary declarations, and produce an error saying the recursion is not well founded. ```lean example (n m : ℕ) (h₁ : n = m) (h₂ : ∃ a : ℕ, a = n ∧ a = m) : 2 * m = 2 * n := let ⟨a, ha⟩ := h₂ in begin clear_aux_decl, -- subst will fail without this line subst h₁ end example (x y : ℕ) (h₁ : ∃ n : ℕ, n * 1 = 2) (h₂ : 1 + 1 = 2 → x * 1 = y) : x = y := let ⟨n, hn⟩ := h₁ in begin clear_aux_decl, -- finish produces an error without this line finish end ``` -/ /-- The logic of `change x with y at l` fails when there are dependencies. `change'` mimics the behavior of `change`, except in the case of `change x with y at l`. In this case, it will correctly replace occurences of `x` with `y` at all possible hypotheses in `l`. As long as `x` and `y` are defeq, it should never fail. -/ /-- `set a := t with h` is a variant of `let a := t`. It adds the hypothesis `h : a = t` to the local context and replaces `t` with `a` everywhere it can. `set a := t with ←h` will add `h : t = a` instead. `set! a := t with h` does not do any replacing. ```lean example (x : ℕ) (h : x = 3) : x + x + x = 9 := begin set y := x with ←h_xy, /- x : ℕ, y : ℕ := x, h_xy : x = y, h : y = 3 ⊢ y + y + y = 9 -/ /-- `clear_except h₀ h₁` deletes all the assumptions it can except for `h₀` and `h₁`. -/ /-- Format the current goal as a stand-alone example. Useful for testing tactics or creating [minimal working examples](https://leanprover-community.github.io/mwe.html). * `extract_goal`: formats the statement as an `example` declaration * `extract_goal my_decl`: formats the statement as a `lemma` or `def` declaration called `my_decl` * `extract_goal with i j k:` only use local constants `i`, `j`, `k` in the declaration Examples: ```lean example (i j k : ℕ) (h₀ : i ≤ j) (h₁ : j ≤ k) : i ≤ k := begin extract_goal, -- prints: -- example (i j k : ℕ) (h₀ : i ≤ j) (h₁ : j ≤ k) : i ≤ k := -- begin -- admit, -- end extract_goal my_lemma -- prints: -- lemma my_lemma (i j k : ℕ) (h₀ : i ≤ j) (h₁ : j ≤ k) : i ≤ k := -- begin -- admit, -- end end example {i j k x y z w p q r m n : ℕ} (h₀ : i ≤ j) (h₁ : j ≤ k) (h₁ : k ≤ p) (h₁ : p ≤ q) : i ≤ k := begin extract_goal my_lemma, -- prints: -- lemma my_lemma {i j k x y z w p q r m n : ℕ} -- (h₀ : i ≤ j) -- (h₁ : j ≤ k) -- (h₁ : k ≤ p) -- (h₁ : p ≤ q) : -- i ≤ k := -- begin -- admit, -- end extract_goal my_lemma with i j k -- prints: -- lemma my_lemma {p i j k : ℕ} -- (h₀ : i ≤ j) -- (h₁ : j ≤ k) -- (h₁ : k ≤ p) : -- i ≤ k := -- begin -- admit, -- end end example : true := begin let n := 0, have m : ℕ, admit, have k : fin n, admit, have : n + m + k.1 = 0, extract_goal, -- prints: -- example (m : ℕ) : let n : ℕ := 0 in ∀ (k : fin n), n + m + k.val = 0 := -- begin -- intros n k, -- admit, -- end end ``` -/ /-- `inhabit α` tries to derive a `nonempty α` instance and then upgrades this to an `inhabited α` instance. If the target is a `Prop`, this is done constructively; otherwise, it uses `classical.choice`. ```lean example (α) [nonempty α] : ∃ a : α, true := begin inhabit α, existsi default α, trivial end ``` -/ /-- `revert_deps n₁ n₂ ...` reverts all the hypotheses that depend on one of `n₁, n₂, ...` It does not revert `n₁, n₂, ...` themselves (unless they depend on another `nᵢ`). -/ /-- `revert_after n` reverts all the hypotheses after `n`. -/ /-- Reverts all local constants on which the target depends (recursively). -/ /-- `clear_value n₁ n₂ ...` clears the bodies of the local definitions `n₁, n₂ ...`, changing them into regular hypotheses. A hypothesis `n : α := t` is changed to `n : α`. -/ /-- `generalize' : e = x` replaces all occurrences of `e` in the target with a new hypothesis `x` of the same type. `generalize' h : e = x` in addition registers the hypothesis `h : e = x`. `generalize'` is similar to `generalize`. The difference is that `generalize' : e = x` also succeeds when `e` does not occur in the goal. It is similar to `set`, but the resulting hypothesis `x` is not a local definition. -/ end Mathlib
2ce1b89ce3fe80e969323a96025521cd3e69b46f
0dc59d2b959c9b11a672f655b104d7d7d3e37660
/other_peoples_work/jason_set.lean
77c8b376f7f00b4d778ba495fcbe739a3c3af6ca
[]
no_license
kbuzzard/lean4-filters
5aa17d95079ceb906622543209064151fa645e71
29f90055b7a2341c86d924954463c439bd128fb7
refs/heads/master
1,679,762,259,673
1,616,701,300,000
1,616,701,300,000
350,784,493
5
1
null
1,625,691,081,000
1,616,517,435,000
Lean
UTF-8
Lean
false
false
6,965
lean
theorem impNot {p q : Prop} : p → ¬ q ↔ ¬ (p ∧ q) := ⟨ λ hpq h => hpq h.1 h.2, λ h hp hq => h <| And.intro hp hq ⟩ theorem Exists.impNot {p q : α → Prop} : (∃ x, p x → ¬ q x) ↔ ∃ x, ¬ (p x ∧ q x) := by apply Iff.intro intro h cases h with | intro x hx => { exact ⟨ x, λ hs => hx hs.1 hs.2 ⟩ } intro h cases h with | intro x hx => { exact ⟨ x, λ hpx hqx => hx <| And.intro hpx hqx ⟩ } namespace Classical theorem contrapositive {p q : Prop} : (¬ q → ¬ p) → p → q := λ hqp hp => match em q with | Or.inl h => h | Or.inr h => False.elim <| hqp h hp theorem notNot {p : Prop} : ¬ ¬ p ↔ p := by apply Iff.intro { intro hp; cases em p with | inl => assumption | inr h => exact False.elim <| hp h } { exact λ hp hnp => False.elim <| hnp hp } theorem notForall {p : α → Prop} : (¬ ∀ x, p x) → ∃ x, ¬ p x := by { apply contrapositive; intro hx; rw notNot; intro x; cases em (p x); { assumption } { apply False.elim <| hx <| Exists.intro x _; assumption } } theorem notAnd {p q : Prop} : p ∧ ¬ q ↔ ¬ (p → q) := by apply Iff.intro { exact λ h himp => h.2 <| himp h.1 } { intro h; apply And.intro; { revert h; apply contrapositive; rw notNot; exact λ hnp hp => False.elim <| hnp hp } { exact λ hq => h <| λ _ => hq } } theorem Exists.notAnd {p q : α → Prop} : (∃ x, p x ∧ ¬ q x) ↔ ∃ x, ¬ (p x → q x) := by apply Iff.intro { intro h; let ⟨ x, ⟨ hp, hnq ⟩ ⟩ := h; exact Exists.intro x λ h => hnq <| h hp } { intro h; let ⟨ x, hx ⟩ := h; apply Exists.intro x; apply And.intro; { revert hx; apply contrapositive; exact λ hpx hpq => hpq λ hp => False.elim <| hpx hp } { intro foo; apply hx; intro bar; assumption; } } end Classical def Set (α : Type u) := α → Prop def setOf (p : α → Prop) : Set α := p namespace Set instance : EmptyCollection (Set α) := ⟨ λ x => False ⟩ variable {zzz : Type u} variable {α : Type u} variable {s : Set α} def mem (a : α) (s : Set α) := s a infix:55 "∈" => Set.mem notation:55 x "∉" s => ¬ x ∈ s instance : CoeSort (Set α) (Type u) where coe s := Subtype s theorem ext {s t : Set α} (h : ∀ x, x ∈ s ↔ x ∈ t) : s = t := funext <| λ x => propext <| h x -- Declaring the index category declare_syntax_cat index syntax ident : index syntax ident ":" term : index syntax ident "∈" term : index -- Notation for sets syntax "{" index "|" term "}" : term macro_rules | `({ $x:ident : $t | $p }) => `(setOf (λ ($x:ident : $t) => $p)) | `({ $x:ident | $p }) => `(setOf (λ ($x:ident) => $p)) | `({ $x:ident ∈ $s | $p }) => `(setOf (λ $x => $x ∈ $s → $p)) def union (s t : Set α) : Set α := { x : α | x ∈ s ∨ x ∈ t } def inter (s t : Set α) : Set α := { x : α | x ∈ s ∧ x ∈ t } theorem unionDef (s t : Set α) : union s t = λ x => s x ∨ t x := rfl theorem interDef (s t : Set α) : inter s t = λ x => s x ∧ t x := rfl infix:60 "∪" => Set.union infix:60 "∩" => Set.inter def Union (s : Set (Set α)) : Set α := { x : α | ∃ t : Set α, t ∈ s → t x } def Inter (s : Set (Set α)) : Set α := { x : α | ∀ t : Set α, t ∈ s → t x } def UnionDef (s : Set (Set α)) : Union s = λ x => ∃ t : Set α, t ∈ s → t x := rfl def InterDef (s : Set (Set α)) : Inter s = λ x => ∀ t : Set α, t ∈ s → t x := rfl syntax "⋃" index "," term : term syntax "⋂" index "," term : term macro_rules | `(⋃ $s:ident ∈ $c, $s) => `(Union $c) | `(⋂ $s:ident ∈ $c, $s) => `(Inter $c) -- variables {s : Set (Set α)} -- #check ⋂ t ∈ s, t -- Notation for ∀ x ∈ s, p and ∃ x ∈ s, p syntax "∀" index "," term : term syntax "∃" index "," term : term macro_rules | `(∀ $x:ident ∈ $s, $p) => `(∀ $x:ident, $x ∈ $s → $p) | `(∃ $x:ident ∈ $s, $p) => `(∃ $x:ident, $x ∈ $s ∧ $p) def Subset (s t : Set α) := ∀ x ∈ s, x ∈ t infix:50 "⊆" => Subset theorem Subset.def {s t : Set α} : s ⊆ t ↔ ∀ x ∈ s, x ∈ t := Iff.rfl namespace Subset theorem refl {s : Set α} : s ⊆ s := λ _ hx => hx theorem trans {s t v : Set α} (hst : s ⊆ t) (htv : t ⊆ v) : s ⊆ t := λ x hx => hst x hx theorem antisymm {s t : Set α} (hst : s ⊆ t) (hts : t ⊆ s) : s = t := Set.ext λ x => ⟨ λ hx => hst x hx, λ hx => hts x hx ⟩ theorem antisymmIff {s t : Set α} : s = t ↔ s ⊆ t ∧ t ⊆ s := ⟨ by { intro hst; subst hst; exact ⟨ refl, refl ⟩ }, λ ⟨ hst, hts ⟩ => antisymm hst hts ⟩ -- ↓ Uses classical logic theorem notSubset : ¬ s ⊆ t ↔ ∃ x ∈ s, x ∉ t := by apply Iff.intro; { intro hst; rw Classical.Exists.notAnd; apply Classical.notForall; exact λ h => hst λ x hx => h x hx } { intro h hst; let ⟨ x, ⟨ hxs, hxt ⟩ ⟩ := h; exact hxt <| hst x hxs } end Subset theorem memEmptySet {x : α} (h : x ∈ ∅) : False := h @[simp] theorem memEmptySetIff : (∃ (x : α), x ∈ ∅) ↔ False := Iff.intro (λ h => h.2) False.elim @[simp] theorem setOfFalse : { a : α | False } = ∅ := rfl def univ : Set α := { x | True } @[simp] theorem memUniv (x : α) : x ∈ univ := True.intro theorem Subset.subsetUniv {s : Set α} : s ⊆ univ := λ x _ => memUniv x theorem Subset.univSubsetIff {s : Set α} : univ ⊆ s ↔ univ = s := by apply Iff.intro λ hs => Subset.antisymm hs Subset.subsetUniv { intro h; subst h; exact Subset.refl } theorem eqUnivIff {s : Set α} : s = univ ↔ ∀ x, x ∈ s := by apply Iff.intro { intro h x; subst h; exact memUniv x } { exact λ h => ext λ x => Iff.intro (λ _ => memUniv _) λ _ => h x } /-! ### Unions and Intersections -/ macro "extia" x:term : tactic => `(tactic| apply ext; intro $x; apply Iff.intro) theorem unionSelf {s : Set α} : s ∪ s = s := by extia x { intro hx; cases hx; assumption; assumption } { exact Or.inl } theorem unionEmpty {s : Set α} : s ∪ ∅ = s := by extia x { intro hx; cases hx with | inl => assumption | inr h => exact False.elim <| memEmptySet h } { exact Or.inl } theorem unionSymm {s t : Set α} : s ∪ t = t ∪ s := by extia x allGoals { intro hx; cases hx with | inl hx => exact Or.inr hx | inr hx => exact Or.inl hx } theorem emptyUnion {s : Set α} : ∅ ∪ s = s := by rw unionSymm; exact unionEmpty theorem unionAssoc {s t w : Set α} : s ∪ t ∪ w = s ∪ (t ∪ w) := by extia x { intro hx; cases hx with | inr hx => exact Or.inr <| Or.inr hx | inl hx => cases hx with | inr hx => exact Or.inr <| Or.inl hx | inl hx => exact Or.inl hx } { intro hx; cases hx with | inl hx => exact Or.inl <| Or.inl hx | inr hx => cases hx with | inr hx => exact Or.inr hx | inl hx => exact Or.inl <| Or.inr hx } end Set
cea70a2d157fc679244b42b58d6dcd2a7cbc7b78
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/module/submodule.lean
30390329d7d7b5b7e5bc8b7e61d485fc54396ccd
[ "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
11,250
lean
/- Copyright (c) 2015 Nathaniel Thomas. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro -/ import algebra.module.linear_map import group_theory.group_action.sub_mul_action /-! # Submodules of a module In this file we define * `submodule R M` : a subset of a `module` `M` that contains zero and is closed with respect to addition and scalar multiplication. * `subspace k M` : an abbreviation for `submodule` assuming that `k` is a `field`. ## Tags submodule, subspace, linear map -/ open function open_locale big_operators universes u' u v w variables {S : Type u'} {R : Type u} {M : Type v} {ι : Type w} set_option old_structure_cmd true /-- A submodule of a module is one which is closed under vector operations. This is a sufficient condition for the subset of vectors in the submodule to themselves form a module. -/ structure submodule (R : Type u) (M : Type v) [semiring R] [add_comm_monoid M] [module R M] extends add_submonoid M, sub_mul_action R M : Type v. /-- Reinterpret a `submodule` as an `add_submonoid`. -/ add_decl_doc submodule.to_add_submonoid /-- Reinterpret a `submodule` as an `sub_mul_action`. -/ add_decl_doc submodule.to_sub_mul_action namespace submodule variables [semiring R] [add_comm_monoid M] [module R M] instance : set_like (submodule R M) M := ⟨submodule.carrier, λ p q h, by cases p; cases q; congr'⟩ @[simp] theorem mem_to_add_submonoid (p : submodule R M) (x : M) : x ∈ p.to_add_submonoid ↔ x ∈ p := iff.rfl variables {p q : submodule R M} @[simp] lemma mk_coe (S : set M) (h₁ h₂ h₃) : ((⟨S, h₁, h₂, h₃⟩ : submodule R M) : set M) = S := rfl @[ext] theorem ext (h : ∀ x, x ∈ p ↔ x ∈ q) : p = q := set_like.ext h /-- Copy of a submodule with a new `carrier` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (p : submodule R M) (s : set M) (hs : s = ↑p) : submodule R M := { carrier := s, zero_mem' := hs.symm ▸ p.zero_mem', add_mem' := hs.symm ▸ p.add_mem', smul_mem' := hs.symm ▸ p.smul_mem' } theorem to_add_submonoid_injective : injective (to_add_submonoid : submodule R M → add_submonoid M) := λ p q h, set_like.ext'_iff.2 (show _, from set_like.ext'_iff.1 h) @[simp] theorem to_add_submonoid_eq : p.to_add_submonoid = q.to_add_submonoid ↔ p = q := to_add_submonoid_injective.eq_iff @[mono] lemma to_add_submonoid_strict_mono : strict_mono (to_add_submonoid : submodule R M → add_submonoid M) := λ _ _, id @[mono] lemma to_add_submonoid_mono : monotone (to_add_submonoid : submodule R M → add_submonoid M) := to_add_submonoid_strict_mono.monotone @[simp] theorem coe_to_add_submonoid (p : submodule R M) : (p.to_add_submonoid : set M) = p := rfl theorem to_sub_mul_action_injective : injective (to_sub_mul_action : submodule R M → sub_mul_action R M) := λ p q h, set_like.ext'_iff.2 (show _, from set_like.ext'_iff.1 h) @[simp] theorem to_sub_mul_action_eq : p.to_sub_mul_action = q.to_sub_mul_action ↔ p = q := to_sub_mul_action_injective.eq_iff @[mono] lemma to_sub_mul_action_strict_mono : strict_mono (to_sub_mul_action : submodule R M → sub_mul_action R M) := λ _ _, id @[mono] lemma to_sub_mul_action_mono : monotone (to_sub_mul_action : submodule R M → sub_mul_action R M) := to_sub_mul_action_strict_mono.monotone @[simp] theorem coe_to_sub_mul_action (p : submodule R M) : (p.to_sub_mul_action : set M) = p := rfl end submodule namespace submodule section add_comm_monoid variables [semiring S] [semiring R] [add_comm_monoid M] -- We can infer the module structure implicitly from the bundled submodule, -- rather than via typeclass resolution. variables {module_M : module R M} variables {p q : submodule R M} variables {r : R} {x y : M} variables [has_scalar S R] [module S M] [is_scalar_tower S R M] variables (p) @[simp] lemma mem_carrier : x ∈ p.carrier ↔ x ∈ (p : set M) := iff.rfl @[simp] lemma zero_mem : (0 : M) ∈ p := p.zero_mem' lemma add_mem (h₁ : x ∈ p) (h₂ : y ∈ p) : x + y ∈ p := p.add_mem' h₁ h₂ lemma smul_mem (r : R) (h : x ∈ p) : r • x ∈ p := p.smul_mem' r h lemma smul_of_tower_mem (r : S) (h : x ∈ p) : r • x ∈ p := p.to_sub_mul_action.smul_of_tower_mem r h lemma sum_mem {t : finset ι} {f : ι → M} : (∀c∈t, f c ∈ p) → (∑ i in t, f i) ∈ p := p.to_add_submonoid.sum_mem lemma sum_smul_mem {t : finset ι} {f : ι → M} (r : ι → R) (hyp : ∀ c ∈ t, f c ∈ p) : (∑ i in t, r i • f i) ∈ p := submodule.sum_mem _ (λ i hi, submodule.smul_mem _ _ (hyp i hi)) @[simp] lemma smul_mem_iff' (u : units S) : (u:S) • x ∈ p ↔ x ∈ p := p.to_sub_mul_action.smul_mem_iff' u instance : has_add p := ⟨λx y, ⟨x.1 + y.1, add_mem _ x.2 y.2⟩⟩ instance : has_zero p := ⟨⟨0, zero_mem _⟩⟩ instance : inhabited p := ⟨0⟩ instance : has_scalar S p := ⟨λ c x, ⟨c • x.1, smul_of_tower_mem _ c x.2⟩⟩ protected lemma nonempty : (p : set M).nonempty := ⟨0, p.zero_mem⟩ @[simp] lemma mk_eq_zero {x} (h : x ∈ p) : (⟨x, h⟩ : p) = 0 ↔ x = 0 := subtype.ext_iff_val variables {p} @[simp, norm_cast] lemma coe_eq_zero {x : p} : (x : M) = 0 ↔ x = 0 := (set_like.coe_eq_coe : (x : M) = (0 : p) ↔ x = 0) @[simp, norm_cast] lemma coe_add (x y : p) : (↑(x + y) : M) = ↑x + ↑y := rfl @[simp, norm_cast] lemma coe_zero : ((0 : p) : M) = 0 := rfl @[norm_cast] lemma coe_smul (r : R) (x : p) : ((r • x : p) : M) = r • ↑x := rfl @[simp, norm_cast] lemma coe_smul_of_tower (r : S) (x : p) : ((r • x : p) : M) = r • ↑x := rfl @[simp, norm_cast] lemma coe_mk (x : M) (hx : x ∈ p) : ((⟨x, hx⟩ : p) : M) = x := rfl @[simp] lemma coe_mem (x : p) : (x : M) ∈ p := x.2 variables (p) instance : add_comm_monoid p := { add := (+), zero := 0, .. p.to_add_submonoid.to_add_comm_monoid } instance module' : module S p := by refine {smul := (•), ..p.to_sub_mul_action.mul_action', ..}; { intros, apply set_coe.ext, simp [smul_add, add_smul, mul_smul] } instance : module R p := p.module' instance : is_scalar_tower S R p := p.to_sub_mul_action.is_scalar_tower instance no_zero_smul_divisors [no_zero_smul_divisors R M] : no_zero_smul_divisors R p := ⟨λ c x h, have c = 0 ∨ (x : M) = 0, from eq_zero_or_eq_zero_of_smul_eq_zero (congr_arg coe h), this.imp_right (@subtype.ext_iff _ _ x 0).mpr⟩ /-- Embedding of a submodule `p` to the ambient space `M`. -/ protected def subtype : p →ₗ[R] M := by refine {to_fun := coe, ..}; simp [coe_smul] @[simp] theorem subtype_apply (x : p) : p.subtype x = x := rfl lemma subtype_eq_val : ((submodule.subtype p) : p → M) = subtype.val := rfl end add_comm_monoid section add_comm_group variables [ring R] [add_comm_group M] variables {module_M : module R M} variables (p p' : submodule R M) variables {r : R} {x y : M} lemma neg_mem (hx : x ∈ p) : -x ∈ p := p.to_sub_mul_action.neg_mem hx /-- Reinterpret a submodule as an additive subgroup. -/ def to_add_subgroup : add_subgroup M := { neg_mem' := λ _, p.neg_mem , .. p.to_add_submonoid } @[simp] lemma coe_to_add_subgroup : (p.to_add_subgroup : set M) = p := rfl @[simp] lemma mem_to_add_subgroup : x ∈ p.to_add_subgroup ↔ x ∈ p := iff.rfl include module_M theorem to_add_subgroup_injective : injective (to_add_subgroup : submodule R M → add_subgroup M) | p q h := set_like.ext (set_like.ext_iff.1 h : _) @[simp] theorem to_add_subgroup_eq : p.to_add_subgroup = p'.to_add_subgroup ↔ p = p' := to_add_subgroup_injective.eq_iff @[mono] lemma to_add_subgroup_strict_mono : strict_mono (to_add_subgroup : submodule R M → add_subgroup M) := λ _ _, id @[mono] lemma to_add_subgroup_mono : monotone (to_add_subgroup : submodule R M → add_subgroup M) := to_add_subgroup_strict_mono.monotone omit module_M lemma sub_mem : x ∈ p → y ∈ p → x - y ∈ p := p.to_add_subgroup.sub_mem @[simp] lemma neg_mem_iff : -x ∈ p ↔ x ∈ p := p.to_add_subgroup.neg_mem_iff lemma add_mem_iff_left : y ∈ p → (x + y ∈ p ↔ x ∈ p) := p.to_add_subgroup.add_mem_cancel_right lemma add_mem_iff_right : x ∈ p → (x + y ∈ p ↔ y ∈ p) := p.to_add_subgroup.add_mem_cancel_left instance : has_neg p := ⟨λx, ⟨-x.1, neg_mem _ x.2⟩⟩ @[simp, norm_cast] lemma coe_neg (x : p) : ((-x : p) : M) = -x := rfl instance : add_comm_group p := { add := (+), zero := 0, neg := has_neg.neg, ..p.to_add_subgroup.to_add_comm_group } @[simp, norm_cast] lemma coe_sub (x y : p) : (↑(x - y) : M) = ↑x - ↑y := rfl end add_comm_group section ordered_monoid variables [semiring R] /-- A submodule of an `ordered_add_comm_monoid` is an `ordered_add_comm_monoid`. -/ instance to_ordered_add_comm_monoid {M} [ordered_add_comm_monoid M] [module R M] (S : submodule R M) : ordered_add_comm_monoid S := subtype.coe_injective.ordered_add_comm_monoid coe rfl (λ _ _, rfl) /-- A submodule of a `linear_ordered_add_comm_monoid` is a `linear_ordered_add_comm_monoid`. -/ instance to_linear_ordered_add_comm_monoid {M} [linear_ordered_add_comm_monoid M] [module R M] (S : submodule R M) : linear_ordered_add_comm_monoid S := subtype.coe_injective.linear_ordered_add_comm_monoid coe rfl (λ _ _, rfl) /-- A submodule of an `ordered_cancel_add_comm_monoid` is an `ordered_cancel_add_comm_monoid`. -/ instance to_ordered_cancel_add_comm_monoid {M} [ordered_cancel_add_comm_monoid M] [module R M] (S : submodule R M) : ordered_cancel_add_comm_monoid S := subtype.coe_injective.ordered_cancel_add_comm_monoid coe rfl (λ _ _, rfl) /-- A submodule of a `linear_ordered_cancel_add_comm_monoid` is a `linear_ordered_cancel_add_comm_monoid`. -/ instance to_linear_ordered_cancel_add_comm_monoid {M} [linear_ordered_cancel_add_comm_monoid M] [module R M] (S : submodule R M) : linear_ordered_cancel_add_comm_monoid S := subtype.coe_injective.linear_ordered_cancel_add_comm_monoid coe rfl (λ _ _, rfl) end ordered_monoid section ordered_group variables [ring R] /-- A submodule of an `ordered_add_comm_group` is an `ordered_add_comm_group`. -/ instance to_ordered_add_comm_group {M} [ordered_add_comm_group M] [module R M] (S : submodule R M) : ordered_add_comm_group S := subtype.coe_injective.ordered_add_comm_group coe rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) /-- A submodule of a `linear_ordered_add_comm_group` is a `linear_ordered_add_comm_group`. -/ instance to_linear_ordered_add_comm_group {M} [linear_ordered_add_comm_group M] [module R M] (S : submodule R M) : linear_ordered_add_comm_group S := subtype.coe_injective.linear_ordered_add_comm_group coe rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) end ordered_group end submodule namespace submodule variables [division_ring S] [semiring R] [add_comm_monoid M] [module R M] variables [has_scalar S R] [module S M] [is_scalar_tower S R M] variables (p : submodule R M) {s : S} {x y : M} theorem smul_mem_iff (s0 : s ≠ 0) : s • x ∈ p ↔ x ∈ p := p.to_sub_mul_action.smul_mem_iff s0 end submodule /-- Subspace of a vector space. Defined to equal `submodule`. -/ abbreviation subspace (R : Type u) (M : Type v) [field R] [add_comm_group M] [module R M] := submodule R M
2cfa1155734c68154370dd3ee6f7f47f1b17a6d3
ac1c2a2f522b0fdf854095ba00f882ca849669e7
/library/tools/debugger/util.lean
ddb3a99d4ef8e53ecc9ec71b15de73c337bf7356
[ "Apache-2.0" ]
permissive
abliss/lean
b8b336abc8d50dbb0726dcff9dd16793c23bfbe1
fb24cc99573c153f97a1951ee94bbbdda300b6be
refs/heads/master
1,611,536,584,520
1,497,811,981,000
1,497,811,981,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,961
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 -/ namespace debugger def is_space (c : char) : bool := if c = ' ' ∨ c = char.of_nat 11 ∨ c = '\n' then tt else ff private def split_core : list char → option string → list string | (c::cs) none := if is_space c then split_core cs none else split_core cs (some $ string.singleton c) | (c::cs) (some s) := if is_space c then s :: split_core cs none else split_core cs (s.str c) | [] none := [] | [] (some s) := [s] def split (s : string) : list string := split_core s.to_list none def to_qualified_name_core : list char → name → string → name | [] r s := if s.is_empty then r else r <.> s | (c::cs) r s := if is_space c then to_qualified_name_core cs r s else if c = '.' then if s.is_empty then to_qualified_name_core cs r "" else to_qualified_name_core cs (r <.> s) "" else to_qualified_name_core cs r (s.str c) def to_qualified_name (s : string) : name := to_qualified_name_core s.to_list name.anonymous "" def olean_to_lean (s : string) := s.popn_back 5 ++ "lean" meta def get_file (fn : name) : vm string := do { d ← vm.get_decl fn, some n ← return (vm_decl.olean d) | failure, return (olean_to_lean n) } <|> return "[current file]" meta def pos_info (fn : name) : vm string := do { d ← vm.get_decl fn, some p ← return (vm_decl.pos d) | failure, file ← get_file fn, return sformat!"{file}:{p.line}:{p.column}" } <|> return "<position not available>" meta def show_fn (header : string) (fn : name) (frame : nat) : vm unit := do pos ← pos_info fn, vm.put_str sformat!"[{frame}] {header}", if header = "" then return () else vm.put_str " ", vm.put_str sformat!"{fn} at {pos}\n" meta def show_curr_fn (header : string) : vm unit := do fn ← vm.curr_fn, sz ← vm.call_stack_size, show_fn header fn (sz-1) meta def is_valid_fn_prefix (p : name) : vm bool := do env ← vm.get_env, return $ env.fold ff (λ d r, r || let n := d.to_name in p.is_prefix_of n) meta def show_frame (frame_idx : nat) : vm unit := do sz ← vm.call_stack_size, fn ← if frame_idx >= sz then vm.curr_fn else vm.call_stack_fn frame_idx, show_fn "" fn frame_idx meta def type_to_string : option expr → nat → vm string | none i := do o ← vm.stack_obj i, match o.kind with | vm_obj_kind.simple := return "[tagged value]" | vm_obj_kind.constructor := return "[constructor]" | vm_obj_kind.closure := return "[closure]" | vm_obj_kind.native_closure := return "[native closure]" | vm_obj_kind.mpz := return "[big num]" | vm_obj_kind.name := return "name" | vm_obj_kind.level := return "level" | vm_obj_kind.expr := return "expr" | vm_obj_kind.declaration := return "declaration" | vm_obj_kind.environment := return "environment" | vm_obj_kind.tactic_state := return "tactic_state" | vm_obj_kind.format := return "format" | vm_obj_kind.options := return "options" | vm_obj_kind.other := return "[other]" end | (some type) i := do fmt ← vm.pp_expr type, opts ← vm.get_options, return (fmt.to_string opts) meta def show_vars_core : nat → nat → nat → vm unit | c i e := if i = e then return () else do (n, type) ← vm.stack_obj_info i, type_str ← type_to_string type i, vm.put_str sformat!"#{c} {n} : {type_str}\n", show_vars_core (c+1) (i+1) e meta def show_vars (frame : nat) : vm unit := do (s, e) ← vm.call_stack_var_range frame, show_vars_core 0 s e meta def show_stack_core : nat → vm unit | 0 := return () | (i+1) := do fn ← vm.call_stack_fn i, show_fn "" fn i, show_stack_core i meta def show_stack : vm unit := do sz ← vm.call_stack_size, show_stack_core sz end debugger
0d06b28ebcb458db6ab0d81a750778e7582da2e7
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/limits/shapes/terminal_auto.lean
51168b0848a1b94d82c06832974e2b0167344a8a
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
10,919
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.pempty import Mathlib.category_theory.limits.limits import Mathlib.PostPort universes u v u₂ namespace Mathlib /-! # Initial and terminal objects in a category. ## References * [Stacks: Initial and final objects](https://stacks.math.columbia.edu/tag/002B) -/ namespace category_theory.limits /-- Construct a cone for the empty diagram given an object. -/ /-- Construct a cocone for the empty diagram given an object. -/ @[simp] theorem as_empty_cone_π_app {C : Type u} [category C] (X : C) : ∀ (X_1 : discrete pempty), nat_trans.app (cone.π (as_empty_cone X)) X_1 = as_empty_cone._aux_1 X X_1 := fun (X_1 : discrete pempty) => Eq.refl (nat_trans.app (cone.π (as_empty_cone X)) X_1) @[simp] theorem as_empty_cocone_ι_app {C : Type u} [category C] (X : C) : ∀ (X_1 : discrete pempty), nat_trans.app (cocone.ι (as_empty_cocone X)) X_1 = as_empty_cocone._aux_1 X X_1 := fun (X_1 : discrete pempty) => Eq.refl (nat_trans.app (cocone.ι (as_empty_cocone X)) X_1) /-- `X` is terminal if the cone it induces on the empty diagram is limiting. -/ /-- `X` is initial if the cocone it induces on the empty diagram is colimiting. -/ def is_terminal {C : Type u} [category C] (X : C) := is_limit (as_empty_cone X) def is_initial {C : Type u} [category C] (X : C) := is_colimit (as_empty_cocone X) /-- Give the morphism to a terminal object from any other. -/ def is_terminal.from {C : Type u} [category C] {X : C} (t : is_terminal X) (Y : C) : Y ⟶ X := is_limit.lift t (as_empty_cone Y) /-- Any two morphisms to a terminal object are equal. -/ theorem is_terminal.hom_ext {C : Type u} [category C] {X : C} {Y : C} (t : is_terminal X) (f : Y ⟶ X) (g : Y ⟶ X) : f = g := sorry /-- Give the morphism from an initial object to any other. -/ def is_initial.to {C : Type u} [category C] {X : C} (t : is_initial X) (Y : C) : X ⟶ Y := is_colimit.desc t (as_empty_cocone Y) /-- Any two morphisms from an initial object are equal. -/ theorem is_initial.hom_ext {C : Type u} [category C] {X : C} {Y : C} (t : is_initial X) (f : X ⟶ Y) (g : X ⟶ Y) : f = g := sorry /-- Any morphism from a terminal object is mono. -/ theorem is_terminal.mono_from {C : Type u} [category C] {X : C} {Y : C} (t : is_terminal X) (f : X ⟶ Y) : mono f := mono.mk fun (Z : C) (g h : Z ⟶ X) (eq : g ≫ f = h ≫ f) => is_terminal.hom_ext t g h /-- Any morphism to an initial object is epi. -/ theorem is_initial.epi_to {C : Type u} [category C] {X : C} {Y : C} (t : is_initial X) (f : Y ⟶ X) : epi f := epi.mk fun (Z : C) (g h : X ⟶ Z) (eq : f ≫ g = f ≫ h) => is_initial.hom_ext t g h /-- A category has a terminal object if it has a limit over the empty diagram. Use `has_terminal_of_unique` to construct instances. -/ /-- def has_terminal (C : Type u) [category C] := has_limits_of_shape (discrete pempty) C A category has an initial object if it has a colimit over the empty diagram. Use `has_initial_of_unique` to construct instances. -/ def has_initial (C : Type u) [category C] := has_colimits_of_shape (discrete pempty) C /-- An arbitrary choice of terminal object, if one exists. You can use the notation `⊤_ C`. This object is characterized by having a unique morphism from any object. -/ /-- def terminal (C : Type u) [category C] [has_terminal C] : C := limit (functor.empty C) An arbitrary choice of initial object, if one exists. You can use the notation `⊥_ C`. This object is characterized by having a unique morphism to any object. -/ def initial (C : Type u) [category C] [has_initial C] : C := colimit (functor.empty C) prefix:20 "⊤_" => Mathlib.category_theory.limits.terminal prefix:20 "⊥_" => Mathlib.category_theory.limits.initial /-- We can more explicitly show that a category has a terminal object by specifying the object, and showing there is a unique morphism to it from any other object. -/ theorem has_terminal_of_unique {C : Type u} [category C] (X : C) [h : (Y : C) → unique (Y ⟶ X)] : has_terminal C := sorry /-- We can more explicitly show that a category has an initial object by specifying the object, and showing there is a unique morphism from it to any other object. -/ theorem has_initial_of_unique {C : Type u} [category C] (X : C) [h : (Y : C) → unique (X ⟶ Y)] : has_initial C := sorry /-- The map from an object to the terminal object. -/ def terminal.from {C : Type u} [category C] [has_terminal C] (P : C) : P ⟶ ⊤_C := limit.lift (functor.empty C) (as_empty_cone P) /-- The map to an object from the initial object. -/ def initial.to {C : Type u} [category C] [has_initial C] (P : C) : ⊥_C ⟶ P := colimit.desc (functor.empty C) (as_empty_cocone P) protected instance unique_to_terminal {C : Type u} [category C] [has_terminal C] (P : C) : unique (P ⟶ ⊤_C) := unique.mk { default := terminal.from P } sorry protected instance unique_from_initial {C : Type u} [category C] [has_initial C] (P : C) : unique (⊥_C ⟶ P) := unique.mk { default := initial.to P } sorry /-- A terminal object is terminal. -/ def terminal_is_terminal {C : Type u} [category C] [has_terminal C] : is_terminal (⊤_C) := is_limit.mk fun (s : cone (functor.empty C)) => terminal.from (cone.X s) /-- An initial object is initial. -/ def initial_is_initial {C : Type u} [category C] [has_initial C] : is_initial (⊥_C) := is_colimit.mk fun (s : cocone (functor.empty C)) => initial.to (cocone.X s) /-- Any morphism from a terminal object is mono. -/ protected instance terminal.mono_from {C : Type u} [category C] {Y : C} [has_terminal C] (f : ⊤_C ⟶ Y) : mono f := is_terminal.mono_from terminal_is_terminal f /-- Any morphism to an initial object is epi. -/ protected instance initial.epi_to {C : Type u} [category C] {Y : C} [has_initial C] (f : Y ⟶ ⊥_C) : epi f := is_initial.epi_to initial_is_initial f /-- An initial object is terminal in the opposite category. -/ def terminal_op_of_initial {C : Type u} [category C] {X : C} (t : is_initial X) : is_terminal (opposite.op X) := is_limit.mk fun (s : cone (functor.empty (Cᵒᵖ))) => has_hom.hom.op (is_initial.to t (opposite.unop (cone.X s))) /-- An initial object in the opposite category is terminal in the original category. -/ def terminal_unop_of_initial {C : Type u} [category C] {X : Cᵒᵖ} (t : is_initial X) : is_terminal (opposite.unop X) := is_limit.mk fun (s : cone (functor.empty C)) => has_hom.hom.unop (is_initial.to t (opposite.op (cone.X s))) /-- A terminal object is initial in the opposite category. -/ def initial_op_of_terminal {C : Type u} [category C] {X : C} (t : is_terminal X) : is_initial (opposite.op X) := is_colimit.mk fun (s : cocone (functor.empty (Cᵒᵖ))) => has_hom.hom.op (is_terminal.from t (opposite.unop (cocone.X s))) /-- A terminal object in the opposite category is initial in the original category. -/ def initial_unop_of_terminal {C : Type u} [category C] {X : Cᵒᵖ} (t : is_terminal X) : is_initial (opposite.unop X) := is_colimit.mk fun (s : cocone (functor.empty C)) => has_hom.hom.unop (is_terminal.from t (opposite.op (cocone.X s))) /-- From a functor `F : J ⥤ C`, given an initial object of `J`, construct a cone for `J`. In `limit_of_diagram_initial` we show it is a limit cone. -/ @[simp] theorem cone_of_diagram_initial_π_app {C : Type u} [category C] {J : Type v} [small_category J] {X : J} (tX : is_initial X) (F : J ⥤ C) (j : J) : nat_trans.app (cone.π (cone_of_diagram_initial tX F)) j = functor.map F (is_initial.to tX j) := Eq.refl (nat_trans.app (cone.π (cone_of_diagram_initial tX F)) j) /-- From a functor `F : J ⥤ C`, given an initial object of `J`, show the cone `cone_of_diagram_initial` is a limit. -/ def limit_of_diagram_initial {C : Type u} [category C] {J : Type v} [small_category J] {X : J} (tX : is_initial X) (F : J ⥤ C) : is_limit (cone_of_diagram_initial tX F) := is_limit.mk fun (s : cone F) => nat_trans.app (cone.π s) X -- This is reducible to allow usage of lemmas about `cone_point_unique_up_to_iso`. /-- For a functor `F : J ⥤ C`, if `J` has an initial object then the image of it is isomorphic to the limit of `F`. -/ def limit_of_initial {C : Type u} [category C] {J : Type v} [small_category J] (F : J ⥤ C) [has_initial J] [has_limit F] : limit F ≅ functor.obj F (⊥_J) := is_limit.cone_point_unique_up_to_iso (limit.is_limit F) (limit_of_diagram_initial initial_is_initial F) /-- From a functor `F : J ⥤ C`, given a terminal object of `J`, construct a cocone for `J`. In `colimit_of_diagram_terminal` we show it is a colimit cocone. -/ @[simp] theorem cocone_of_diagram_terminal_X {C : Type u} [category C] {J : Type v} [small_category J] {X : J} (tX : is_terminal X) (F : J ⥤ C) : cocone.X (cocone_of_diagram_terminal tX F) = functor.obj F X := Eq.refl (cocone.X (cocone_of_diagram_terminal tX F)) /-- From a functor `F : J ⥤ C`, given a terminal object of `J`, show the cocone `cocone_of_diagram_terminal` is a colimit. -/ def colimit_of_diagram_terminal {C : Type u} [category C] {J : Type v} [small_category J] {X : J} (tX : is_terminal X) (F : J ⥤ C) : is_colimit (cocone_of_diagram_terminal tX F) := is_colimit.mk fun (s : cocone F) => nat_trans.app (cocone.ι s) X -- This is reducible to allow usage of lemmas about `cocone_point_unique_up_to_iso`. /-- For a functor `F : J ⥤ C`, if `J` has a terminal object then the image of it is isomorphic to the colimit of `F`. -/ def colimit_of_terminal {C : Type u} [category C] {J : Type v} [small_category J] (F : J ⥤ C) [has_terminal J] [has_colimit F] : colimit F ≅ functor.obj F (⊤_J) := is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit F) (colimit_of_diagram_terminal terminal_is_terminal F) /-- The comparison morphism from the image of a terminal object to the terminal object in the target category. -/ -- TODO: Show this is an isomorphism if and only if `G` preserves terminal objects. def terminal_comparison {C : Type u} [category C] {D : Type u₂} [category D] (G : C ⥤ D) [has_terminal C] [has_terminal D] : functor.obj G (⊤_C) ⟶ ⊤_D := terminal.from (functor.obj G (⊤_C)) /-- The comparison morphism from the initial object in the target category to the image of the initial object. -/ -- TODO: Show this is an isomorphism if and only if `G` preserves initial objects. def initial_comparison {C : Type u} [category C] {D : Type u₂} [category D] (G : C ⥤ D) [has_initial C] [has_initial D] : ⊥_D ⟶ functor.obj G (⊥_C) := initial.to (functor.obj G (⊥_C)) end Mathlib
09a68ccfcc08da68897dadae4a52a6e1b78df189
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/logic/equiv/fintype.lean
97b99b7ec5ff2abe457a83276278a6b116651cbe
[ "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
5,408
lean
/- Copyright (c) 2021 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import data.fintype.basic import group_theory.perm.sign import logic.equiv.defs /-! # Equivalence between fintypes This file contains some basic results on equivalences where one or both sides of the equivalence are `fintype`s. # Main definitions - `function.embedding.to_equiv_range`: computably turn an embedding of a fintype into an `equiv` of the domain to its range - `equiv.perm.via_fintype_embedding : perm α → (α ↪ β) → perm β` extends the domain of a permutation, fixing everything outside the range of the embedding # Implementation details - `function.embedding.to_equiv_range` uses a computable inverse, but one that has poor computational performance, since it operates by exhaustive search over the input `fintype`s. -/ variables {α β : Type*} [fintype α] [decidable_eq β] (e : equiv.perm α) (f : α ↪ β) /-- Computably turn an embedding `f : α ↪ β` into an equiv `α ≃ set.range f`, if `α` is a `fintype`. Has poor computational performance, due to exhaustive searching in constructed inverse. When a better inverse is known, use `equiv.of_left_inverse'` or `equiv.of_left_inverse` instead. This is the computable version of `equiv.of_injective`. -/ def function.embedding.to_equiv_range : α ≃ set.range f := ⟨λ a, ⟨f a, set.mem_range_self a⟩, f.inv_of_mem_range, λ _, by simp, λ _, by simp⟩ @[simp] lemma function.embedding.to_equiv_range_apply (a : α) : f.to_equiv_range a = ⟨f a, set.mem_range_self a⟩ := rfl @[simp] lemma function.embedding.to_equiv_range_symm_apply_self (a : α) : f.to_equiv_range.symm ⟨f a, set.mem_range_self a⟩ = a := by simp [equiv.symm_apply_eq] lemma function.embedding.to_equiv_range_eq_of_injective : f.to_equiv_range = equiv.of_injective f f.injective := by { ext, simp } /-- Extend the domain of `e : equiv.perm α`, mapping it through `f : α ↪ β`. Everything outside of `set.range f` is kept fixed. Has poor computational performance, due to exhaustive searching in constructed inverse due to using `function.embedding.to_equiv_range`. When a better `α ≃ set.range f` is known, use `equiv.perm.via_set_range`. When `[fintype α]` is not available, a noncomputable version is available as `equiv.perm.via_embedding`. -/ def equiv.perm.via_fintype_embedding : equiv.perm β := e.extend_domain f.to_equiv_range @[simp] lemma equiv.perm.via_fintype_embedding_apply_image (a : α) : e.via_fintype_embedding f (f a) = f (e a) := begin rw equiv.perm.via_fintype_embedding, convert equiv.perm.extend_domain_apply_image e _ _ end lemma equiv.perm.via_fintype_embedding_apply_mem_range {b : β} (h : b ∈ set.range f) : e.via_fintype_embedding f b = f (e (f.inv_of_mem_range ⟨b, h⟩)) := by simpa [equiv.perm.via_fintype_embedding, equiv.perm.extend_domain_apply_subtype, h] lemma equiv.perm.via_fintype_embedding_apply_not_mem_range {b : β} (h : b ∉ set.range f) : e.via_fintype_embedding f b = b := by rwa [equiv.perm.via_fintype_embedding, equiv.perm.extend_domain_apply_not_subtype] @[simp] lemma equiv.perm.via_fintype_embedding_sign [decidable_eq α] [fintype β] : equiv.perm.sign (e.via_fintype_embedding f) = equiv.perm.sign e := by simp [equiv.perm.via_fintype_embedding] namespace equiv variables {p q : α → Prop} [decidable_pred p] [decidable_pred q] /-- If `e` is an equivalence between two subtypes of a fintype `α`, `e.to_compl` is an equivalence between the complement of those subtypes. See also `equiv.compl`, for a computable version when a term of type `{e' : α ≃ α // ∀ x : {x // p x}, e' x = e x}` is known. -/ noncomputable def to_compl (e : {x // p x} ≃ {x // q x}) : {x // ¬ p x} ≃ {x // ¬ q x} := classical.choice (fintype.card_eq.mp (fintype.card_compl_eq_card_compl _ _ (fintype.card_congr e))) /-- If `e` is an equivalence between two subtypes of a fintype `α`, `e.extend_subtype` is a permutation of `α` acting like `e` on the subtypes and doing something arbitrary outside. Note that when `p = q`, `equiv.perm.subtype_congr e (equiv.refl _)` can be used instead. -/ noncomputable abbreviation extend_subtype (e : {x // p x} ≃ {x // q x}) : perm α := subtype_congr e e.to_compl lemma extend_subtype_apply_of_mem (e : {x // p x} ≃ {x // q x}) (x) (hx : p x) : e.extend_subtype x = e ⟨x, hx⟩ := by { dunfold extend_subtype, simp only [subtype_congr, equiv.trans_apply, equiv.sum_congr_apply], rw [sum_compl_apply_symm_of_pos _ _ hx, sum.map_inl, sum_compl_apply_inl] } lemma extend_subtype_mem (e : {x // p x} ≃ {x // q x}) (x) (hx : p x) : q (e.extend_subtype x) := by { convert (e ⟨x, hx⟩).2, rw [e.extend_subtype_apply_of_mem _ hx, subtype.val_eq_coe] } lemma extend_subtype_apply_of_not_mem (e : {x // p x} ≃ {x // q x}) (x) (hx : ¬ p x) : e.extend_subtype x = e.to_compl ⟨x, hx⟩ := by { dunfold extend_subtype, simp only [subtype_congr, equiv.trans_apply, equiv.sum_congr_apply], rw [sum_compl_apply_symm_of_neg _ _ hx, sum.map_inr, sum_compl_apply_inr] } lemma extend_subtype_not_mem (e : {x // p x} ≃ {x // q x}) (x) (hx : ¬ p x) : ¬ q (e.extend_subtype x) := by { convert (e.to_compl ⟨x, hx⟩).2, rw [e.extend_subtype_apply_of_not_mem _ hx, subtype.val_eq_coe] } end equiv
f7bc110e8d8c35dd2bb1b69dab1e27ef5dcb8aa0
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/tactic/default.lean
96dc6b3dcbe6bd1c79a3f2f82023114023a7dceb
[ "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
1,139
lean
/- This file imports many useful tactics ("the kitchen sink"). You can use `import tactic` at the beginning of your file to get everything. (Although you may want to strip things down when you're polishing.) Because this file imports some complicated tactics, it has many transitive dependencies (which of course may not use `import tactic`, and must import selectively). As (non-exhaustive) examples, these includes things like: * algebra.group_power * algebra.ordered_ring * data.rat * data.nat.prime * data.list.perm * data.set.lattice * data.equiv.encodable.basic * order.complete_lattice -/ import tactic.basic -- ensure basic tactics are available import tactic.abel import tactic.ring_exp import tactic.noncomm_ring import tactic.linarith import tactic.omega import tactic.tfae import tactic.apply_fun import tactic.interval_cases import tactic.reassoc_axiom -- most likely useful only for category_theory import tactic.slice import tactic.subtype_instance import tactic.derive_fintype import tactic.group import tactic.cancel_denoms import tactic.zify import tactic.transport import tactic.unfold_cases import tactic.field_simp
746e42a5bd441a4d111e343fa0c01aaffa605fa0
618003631150032a5676f229d13a079ac875ff77
/src/topology/bases.lean
deeedb305ce0ff0ecefe04eebae3f6ad87a12fa0
[ "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
12,078
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro Bases of topologies. Countability axioms. -/ import topology.constructions open set filter classical open_locale topological_space namespace topological_space /- countability axioms For our applications we are interested that there exists a countable basis, but we do not need the concrete basis itself. This allows us to declare these type classes as `Prop` to use them as mixins. -/ universe u variables {α : Type u} [t : topological_space α] include t /-- A topological basis is one that satisfies the necessary conditions so that it suffices to take unions of the basis sets to get a topology (without taking finite intersections as well). -/ def is_topological_basis (s : set (set α)) : Prop := (∀t₁∈s, ∀t₂∈s, ∀ x ∈ t₁ ∩ t₂, ∃ t₃∈s, x ∈ t₃ ∧ t₃ ⊆ t₁ ∩ t₂) ∧ (⋃₀ s) = univ ∧ t = generate_from s lemma is_topological_basis_of_subbasis {s : set (set α)} (hs : t = generate_from s) : is_topological_basis ((λf, ⋂₀ f) '' {f:set (set α) | finite f ∧ f ⊆ s ∧ (⋂₀ f).nonempty}) := let b' := (λf, ⋂₀ f) '' {f:set (set α) | finite f ∧ f ⊆ s ∧ (⋂₀ f).nonempty} in ⟨assume s₁ ⟨t₁, ⟨hft₁, ht₁b, ht₁⟩, eq₁⟩ s₂ ⟨t₂, ⟨hft₂, ht₂b, ht₂⟩, eq₂⟩, have ie : ⋂₀(t₁ ∪ t₂) = ⋂₀ t₁ ∩ ⋂₀ t₂, from Inf_union, eq₁ ▸ eq₂ ▸ assume x h, ⟨_, ⟨t₁ ∪ t₂, ⟨finite_union hft₁ hft₂, union_subset ht₁b ht₂b, ie.symm ▸ ⟨_, h⟩⟩, ie⟩, h, subset.refl _⟩, eq_univ_iff_forall.2 $ assume a, ⟨univ, ⟨∅, ⟨finite_empty, empty_subset _, by rw sInter_empty; exact ⟨a, mem_univ a⟩⟩, sInter_empty⟩, mem_univ _⟩, have generate_from s = generate_from b', from le_antisymm (le_generate_from $ assume u ⟨t, ⟨hft, htb, ne⟩, eq⟩, eq ▸ @is_open_sInter _ (generate_from s) _ hft (assume s hs, generate_open.basic _ $ htb hs)) (le_generate_from $ assume s hs, s.eq_empty_or_nonempty.elim (assume : s = ∅, by rw [this]; apply @is_open_empty _ _) (assume : s.nonempty, generate_open.basic _ ⟨{s}, ⟨finite_singleton s, singleton_subset_iff.2 hs, by rwa sInter_singleton⟩, sInter_singleton s⟩)), this ▸ hs⟩ lemma is_topological_basis_of_open_of_nhds {s : set (set α)} (h_open : ∀ u ∈ s, is_open u) (h_nhds : ∀(a:α) (u : set α), a ∈ u → is_open u → ∃v ∈ s, a ∈ v ∧ v ⊆ u) : is_topological_basis s := ⟨assume t₁ ht₁ t₂ ht₂ x ⟨xt₁, xt₂⟩, h_nhds x (t₁ ∩ t₂) ⟨xt₁, xt₂⟩ (is_open_inter (h_open _ ht₁) (h_open _ ht₂)), eq_univ_iff_forall.2 $ assume a, let ⟨u, h₁, h₂, _⟩ := h_nhds a univ trivial is_open_univ in ⟨u, h₁, h₂⟩, le_antisymm (le_generate_from h_open) (assume u hu, (@is_open_iff_nhds α (generate_from _) _).mpr $ assume a hau, let ⟨v, hvs, hav, hvu⟩ := h_nhds a u hau hu in by rw nhds_generate_from; exact infi_le_of_le v (infi_le_of_le ⟨hav, hvs⟩ $ le_principal_iff.2 hvu))⟩ lemma mem_nhds_of_is_topological_basis {a : α} {s : set α} {b : set (set α)} (hb : is_topological_basis b) : s ∈ 𝓝 a ↔ ∃t∈b, a ∈ t ∧ t ⊆ s := begin change s ∈ (𝓝 a).sets ↔ ∃t∈b, a ∈ t ∧ t ⊆ s, rw [hb.2.2, nhds_generate_from, binfi_sets_eq], { simp only [mem_bUnion_iff, exists_prop, mem_set_of_eq, and_assoc, and.left_comm], refl }, { exact assume s ⟨hs₁, hs₂⟩ t ⟨ht₁, ht₂⟩, have a ∈ s ∩ t, from ⟨hs₁, ht₁⟩, let ⟨u, hu₁, hu₂, hu₃⟩ := hb.1 _ hs₂ _ ht₂ _ this in ⟨u, ⟨hu₂, hu₁⟩, le_principal_iff.2 (subset.trans hu₃ (inter_subset_left _ _)), le_principal_iff.2 (subset.trans hu₃ (inter_subset_right _ _))⟩ }, { rcases eq_univ_iff_forall.1 hb.2.1 a with ⟨i, h1, h2⟩, exact ⟨i, h2, h1⟩ } end lemma is_open_of_is_topological_basis {s : set α} {b : set (set α)} (hb : is_topological_basis b) (hs : s ∈ b) : is_open s := is_open_iff_mem_nhds.2 $ λ a as, (mem_nhds_of_is_topological_basis hb).2 ⟨s, hs, as, subset.refl _⟩ lemma mem_basis_subset_of_mem_open {b : set (set α)} (hb : is_topological_basis b) {a:α} {u : set α} (au : a ∈ u) (ou : is_open u) : ∃v ∈ b, a ∈ v ∧ v ⊆ u := (mem_nhds_of_is_topological_basis hb).1 $ mem_nhds_sets ou au lemma sUnion_basis_of_is_open {B : set (set α)} (hB : is_topological_basis B) {u : set α} (ou : is_open u) : ∃ S ⊆ B, u = ⋃₀ S := ⟨{s ∈ B | s ⊆ u}, λ s h, h.1, set.ext $ λ a, ⟨λ ha, let ⟨b, hb, ab, bu⟩ := mem_basis_subset_of_mem_open hB ha ou in ⟨b, ⟨hb, bu⟩, ab⟩, λ ⟨b, ⟨hb, bu⟩, ab⟩, bu ab⟩⟩ lemma Union_basis_of_is_open {B : set (set α)} (hB : is_topological_basis B) {u : set α} (ou : is_open u) : ∃ (β : Type u) (f : β → set α), u = (⋃ i, f i) ∧ ∀ i, f i ∈ B := let ⟨S, sb, su⟩ := sUnion_basis_of_is_open hB ou in ⟨S, subtype.val, su.trans set.sUnion_eq_Union, λ ⟨b, h⟩, sb h⟩ variables (α) /-- A separable space is one with a countable dense subset. -/ class separable_space : Prop := (exists_countable_closure_eq_univ : ∃s:set α, countable s ∧ closure s = univ) /-- A first-countable space is one in which every point has a countable neighborhood basis. -/ class first_countable_topology : Prop := (nhds_generated_countable : ∀a:α, (𝓝 a).is_countably_generated) /-- A second-countable space is one with a countable basis. -/ class second_countable_topology : Prop := (is_open_generated_countable [] : ∃b:set (set α), countable b ∧ t = topological_space.generate_from b) @[priority 100] -- see Note [lower instance priority] instance second_countable_topology.to_first_countable_topology [second_countable_topology α] : first_countable_topology α := let ⟨b, hb, eq⟩ := second_countable_topology.is_open_generated_countable α in ⟨begin intros, rw [eq, nhds_generate_from], exact is_countably_generated_binfi_principal (hb.mono (assume x, and.right)), end⟩ lemma second_countable_topology_induced (β) [t : topological_space β] [second_countable_topology β] (f : α → β) : @second_countable_topology α (t.induced f) := begin rcases second_countable_topology.is_open_generated_countable β with ⟨b, hb, eq⟩, refine { is_open_generated_countable := ⟨preimage f '' b, hb.image _, _⟩ }, rw [eq, induced_generate_from_eq] end instance subtype.second_countable_topology (s : set α) [second_countable_topology α] : second_countable_topology s := second_countable_topology_induced s α coe lemma is_open_generated_countable_inter [second_countable_topology α] : ∃b:set (set α), countable b ∧ ∅ ∉ b ∧ is_topological_basis b := let ⟨b, hb₁, hb₂⟩ := second_countable_topology.is_open_generated_countable α in let b' := (λs, ⋂₀ s) '' {s:set (set α) | finite s ∧ s ⊆ b ∧ (⋂₀ s).nonempty} in ⟨b', ((countable_set_of_finite_subset hb₁).mono (by { simp only [← and_assoc], apply inter_subset_left })).image _, assume ⟨s, ⟨_, _, hn⟩, hp⟩, absurd hn (not_nonempty_iff_eq_empty.2 hp), is_topological_basis_of_subbasis hb₂⟩ /- TODO: more fine grained instances for first_countable_topology, separable_space, t2_space, ... -/ instance {β : Type*} [topological_space β] [second_countable_topology α] [second_countable_topology β] : second_countable_topology (α × β) := ⟨let ⟨a, ha₁, ha₂, ha₃, ha₄, ha₅⟩ := is_open_generated_countable_inter α in let ⟨b, hb₁, hb₂, hb₃, hb₄, hb₅⟩ := is_open_generated_countable_inter β in ⟨{g | ∃u∈a, ∃v∈b, g = set.prod u v}, have {g | ∃u∈a, ∃v∈b, g = set.prod u v} = (⋃u∈a, ⋃v∈b, {set.prod u v}), by apply set.ext; simp, by rw [this]; exact (ha₁.bUnion $ assume u hu, hb₁.bUnion $ by simp), by rw [ha₅, hb₅, prod_generate_from_generate_from_eq ha₄ hb₄]⟩⟩ instance second_countable_topology_fintype {ι : Type*} {π : ι → Type*} [fintype ι] [t : ∀a, topological_space (π a)] [sc : ∀a, second_countable_topology (π a)] : second_countable_topology (∀a, π a) := have ∀i, ∃b : set (set (π i)), countable b ∧ ∅ ∉ b ∧ is_topological_basis b, from assume a, @is_open_generated_countable_inter (π a) _ (sc a), let ⟨g, hg⟩ := classical.axiom_of_choice this in have t = (λa, generate_from (g a)), from funext $ assume a, (hg a).2.2.2.2, begin constructor, refine ⟨pi univ '' pi univ g, countable.image _ _, _⟩, { suffices : countable {f : Πa, set (π a) | ∀a, f a ∈ g a}, { simpa [pi] }, exact countable_pi (assume i, (hg i).1), }, rw [this, pi_generate_from_eq_fintype], { congr' 1, ext f, simp [pi, eq_comm] }, exact assume a, (hg a).2.2.2.1 end @[priority 100] -- see Note [lower instance priority] instance second_countable_topology.to_separable_space [second_countable_topology α] : separable_space α := let ⟨b, hb₁, hb₂, hb₃, hb₄, eq⟩ := is_open_generated_countable_inter α in have nhds_eq : ∀a, 𝓝 a = (⨅ s : {s : set α // a ∈ s ∧ s ∈ b}, principal s.val), by intro a; rw [eq, nhds_generate_from, infi_subtype]; refl, have ∀s∈b, set.nonempty s, from assume s hs, ne_empty_iff_nonempty.1 $ λ eq, absurd hs (eq.symm ▸ hb₂), have ∃f:∀s∈b, α, ∀s h, f s h ∈ s, by simpa only [skolem, set.nonempty] using this, let ⟨f, hf⟩ := this in ⟨⟨(⋃s∈b, ⋃h:s∈b, {f s h}), hb₁.bUnion (λ _ _, countable_Union_Prop $ λ _, countable_singleton _), set.ext $ assume a, have a ∈ (⋃₀ b), by rw [hb₄]; exact trivial, let ⟨t, ht₁, ht₂⟩ := this in have w : {s : set α // a ∈ s ∧ s ∈ b}, from ⟨t, ht₂, ht₁⟩, suffices (⨅ (x : {s // a ∈ s ∧ s ∈ b}), principal (x.val ∩ ⋃s (h₁ h₂ : s ∈ b), {f s h₂})) ≠ ⊥, by simpa only [closure_eq_nhds, nhds_eq, infi_inf w, inf_principal, mem_set_of_eq, mem_univ, iff_true], infi_ne_bot_of_directed ⟨a⟩ (assume ⟨s₁, has₁, hs₁⟩ ⟨s₂, has₂, hs₂⟩, have a ∈ s₁ ∩ s₂, from ⟨has₁, has₂⟩, let ⟨s₃, hs₃, has₃, hs⟩ := hb₃ _ hs₁ _ hs₂ _ this in ⟨⟨s₃, has₃, hs₃⟩, begin simp only [le_principal_iff, mem_principal_sets, (≥)], simp only [subset_inter_iff] at hs, split; apply inter_subset_inter_left; simp only [hs] end⟩) (assume ⟨s, has, hs⟩, have (s ∩ (⋃ (s : set α) (H h : s ∈ b), {f s h})).nonempty, from ⟨_, hf _ hs, mem_bUnion hs $ mem_Union.mpr ⟨hs, mem_singleton _⟩⟩, principal_ne_bot_iff.2 this) ⟩⟩ variables {α} lemma is_open_Union_countable [second_countable_topology α] {ι} (s : ι → set α) (H : ∀ i, is_open (s i)) : ∃ T : set ι, countable T ∧ (⋃ i ∈ T, s i) = ⋃ i, s i := let ⟨B, cB, _, bB⟩ := is_open_generated_countable_inter α in begin let B' := {b ∈ B | ∃ i, b ⊆ s i}, choose f hf using λ b:B', b.2.2, haveI : encodable B' := (cB.mono (sep_subset _ _)).to_encodable, refine ⟨_, countable_range f, subset.antisymm (bUnion_subset_Union _ _) (sUnion_subset _)⟩, rintro _ ⟨i, rfl⟩ x xs, rcases mem_basis_subset_of_mem_open bB xs (H _) with ⟨b, hb, xb, bs⟩, exact ⟨_, ⟨_, rfl⟩, _, ⟨⟨⟨_, hb, _, bs⟩, rfl⟩, rfl⟩, hf _ (by exact xb)⟩ end lemma is_open_sUnion_countable [second_countable_topology α] (S : set (set α)) (H : ∀ s ∈ S, is_open s) : ∃ T : set (set α), countable T ∧ T ⊆ S ∧ ⋃₀ T = ⋃₀ S := let ⟨T, cT, hT⟩ := is_open_Union_countable (λ s:S, s.1) (λ s, H s.1 s.2) in ⟨subtype.val '' T, cT.image _, image_subset_iff.2 $ λ ⟨x, xs⟩ xt, xs, by rwa [sUnion_image, sUnion_eq_Union]⟩ end topological_space
d3e6560acb19d27e37d791307443555f3deb9f07
44023683920a51f2416cf51eeab3fc51c3ff0765
/tests/lean/char_lits.lean
7e3d1b377e54286f2af7190192aa08b047d0500c
[ "Apache-2.0" ]
permissive
pirocks/lean
e6e3e3fd20c5e7877f7efc3b50e5e20271e8d0cf
368f17d0b1392a5a72c9eb974f15b14462cc1475
refs/heads/master
1,620,671,385,768
1,516,152,564,000
1,516,152,564,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
392
lean
import system.io open io #check 'a' #check '\\' #check 'α' #eval 'a' #eval '\n' #eval '\\' variable [io.interface] #eval put_str ("aaa".str '\\') #eval put_str $ repr '\n' #eval put_str $ string.singleton '\n' #eval put_str ("aaa".str '\'') #check ['\x7f', '\x00', '\x11'] -- ^^ all characters should be pretty-printed using \x escapes #eval 'α' #eval 'β' #eval '\u03B1' #eval '\u03B2'
5c9b39ed278394849f62f9d217172400cade51bd
367134ba5a65885e863bdc4507601606690974c1
/src/data/num/lemmas.lean
c5b5ad37fcdadae1b2649a016751a1ae3de506f7
[ "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
50,149
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 import data.nat.psub /-! # Properties of the binary representation of integers -/ local attribute [simp] add_assoc namespace pos_num variables {α : Type*} @[simp, norm_cast] theorem cast_one [has_one α] [has_add α] : ((1 : pos_num) : α) = 1 := rfl @[simp] theorem cast_one' [has_one α] [has_add α] : (pos_num.one : α) = 1 := rfl @[simp, norm_cast] theorem cast_bit0 [has_one α] [has_add α] (n : pos_num) : (n.bit0 : α) = _root_.bit0 n := rfl @[simp, norm_cast] theorem cast_bit1 [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) ((n:ℕ) < m) : 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) ((n:ℕ) < m) : 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 _⟩ /-- This tactic tries to turn an (in)equality about `num`s to one about `nat`s by rewriting. ```lean example (n : num) (m : num) : n ≤ n + m := begin num.transfer_rw, exact nat.le_add_right _ _ end ``` -/ 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}] /-- This tactic tries to prove (in)equalities about `num`s by transfering them to the `nat` world and then trying to call `simp`. ```lean example (n : num) (m : num) : n ≤ n + m := by num.transfer ``` -/ 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 : linear_ordered_semiring num := { le_total := by {intros a b, transfer_rw, apply le_total}, zero_le_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, exists_pair_ne := ⟨0, 1, dec_trivial⟩, ..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 _)] instance : has_dvd pos_num := ⟨λ m n, pos m ∣ pos n⟩ @[norm_cast] theorem dvd_to_nat {m n : pos_num} : (m:ℕ) ∣ n ↔ m ∣ n := num.dvd_to_nat (pos m) (pos n) 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 /-- This tactic tries to turn an (in)equality about `pos_num`s to one about `nat`s by rewriting. ```lean example (n : pos_num) (m : pos_num) : n ≤ n + m := begin pos_num.transfer_rw, exact nat.le_add_right _ _ end ``` -/ 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}] /-- This tactic tries to prove (in)equalities about `pos_num`s by transferring them to the `nat` world and then trying to call `simp`. ```lean example (n : pos_num) (m : pos_num) : n ≤ n + m := by pos_num.transfer ``` -/ 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 : 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 : 1 < n) : (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 with a; 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, -int.add_neg_one] 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) local attribute [-simp] int.add_neg_one 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) := by simpa only [sub_eq_add_neg] using pos_num.cast_sub' _ _ | (neg a) (pos b) := have (↑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], (pos_num.cast_sub' _ _).trans $ (sub_eq_add_neg _ _).trans this | (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) ((n:ℤ) < m) : 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] /-- This tactic tries to turn an (in)equality about `znum`s to one about `int`s by rewriting. ```lean example (n : znum) (m : znum) : n ≤ n + m * m := begin znum.transfer_rw, exact le_add_of_nonneg_right (mul_self_nonneg _) end ``` -/ 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}] /-- This tactic tries to prove (in)equalities about `znum`s by transfering them to the `int` world and then trying to call `simp`. ```lean example (n : znum) (m : znum) : n ≤ n + m * m := begin znum.transfer, exact mul_self_nonneg _ end ``` -/ meta def transfer : tactic unit := `[intros, transfer_rw, try {simp [add_comm, add_left_comm, mul_comm, mul_left_comm]}] instance : 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 : 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_le_one := dec_trivial, ..znum.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 [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, 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_dvd : decidable_rel ((∣) : num → num → Prop) | a b := decidable_of_iff' _ dvd_iff_mod_eq_zero end num instance pos_num.decidable_dvd : decidable_rel ((∣) : pos_num → pos_num → Prop) | a b := num.decidable_dvd _ _ 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 /-- Cast a `snum` to the corresponding integer. -/ 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⟩
84428cb947ef8c73a911fc98a78d0e9a8c449491
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/data/option/basic.lean
923b80122383bc441effc10bba80e91e9180deb3
[ "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
2,241
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.logic init.control.monad init.control.alternative open decidable universes u v namespace option def to_monad {m : Type → Type} [monad m] [alternative m] {A} : option A → m A | none := failure | (some a) := return a def get_or_else {α : Type u} : option α → α → α | (some x) _ := x | none e := e def is_some {α : Type u} : option α → bool | (some _) := tt | none := ff def is_none {α : Type u} : option α → bool | (some _) := ff | none := tt def get {α : Type u} : Π {o : option α}, is_some o → α | (some x) h := x | none h := false.rec _ $ bool.ff_ne_tt h def rhoare {α : Type u} : bool → α → option α | tt a := none | ff a := some a def lhoare {α : Type u} : α → option α → α | a none := a | _ (some b) := b infixr `|>`:1 := rhoare infixr `<|`:1 := lhoare @[inline] protected def bind {α : Type u} {β : Type v} : option α → (α → option β) → option β | none b := none | (some a) b := b a protected def map {α β} (f : α → β) (o : option α) : option β := option.bind o (some ∘ f) theorem map_id {α} : (option.map id : option α → option α) = id := funext (λo, match o with | none := rfl | some x := rfl end) instance : monad option := {pure := @some, bind := @option.bind, map := @option.map} protected def orelse {α : Type u} : option α → option α → option α | (some a) o := some a | none (some a) := some a | none none := none instance : alternative option := { failure := @none, orelse := @option.orelse } end option instance (α : Type u) : inhabited (option α) := ⟨none⟩ instance {α : Type u} [d : decidable_eq α] : decidable_eq (option α) | none none := is_true rfl | none (some v₂) := is_false (λ h, option.no_confusion h) | (some v₁) none := is_false (λ h, option.no_confusion h) | (some v₁) (some v₂) := match (d v₁ v₂) with | (is_true e) := is_true (congr_arg (@some α) e) | (is_false n) := is_false (λ h, option.no_confusion h (λ e, absurd e n)) end
e6c13eaa2ff796dfbb68b0342d86b86c32619852
6afa22d5eee6e9a56b6a2f1210eca8f7a1067466
/library/init/meta/tactic.lean
54c29358ebdb021672363f64ed3e05ab35d7590e
[ "Apache-2.0" ]
permissive
giordano/lean
72a1fabfeb2f1ccfd38673e2719a719cd6ffbb40
56f8877f1efa22215aca0b82f1c0ce2ff975b9c3
refs/heads/master
1,663,091,511,168
1,590,688,082,000
1,590,688,082,000
268,183,678
0
0
Apache-2.0
1,590,885,425,000
1,590,885,424,000
null
UTF-8
Lean
false
false
71,308
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.control.combinators init.control.monad init.control.alternative init.control.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 open native 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 open interaction_monad.result variables {α : Type u} /-- Does nothing. -/ meta def skip : tactic unit := success () /-- `try_core t` acts like `t`, but succeeds even if `t` fails. It returns the result of `t` if `t` succeeded and `none` otherwise. -/ meta def try_core (t : tactic α) : tactic (option α) := λ s, match t s with | (exception _ _ _) := success none s | (success a s') := success (some a) s' end /-- `try t` acts like `t`, but succeeds even if `t` fails. -/ meta def try (t : tactic α) : tactic unit := λ s, match t s with | (exception _ _ _) := success () s | (success _ s') := success () s' end meta def try_lst : list (tactic unit) → tactic unit | [] := failed | (tac :: tacs) := λ s, match tac s with | success _ s' := try (try_lst tacs) s' | exception e p s' := match try_lst tacs s' with | exception _ _ _ := exception e p s' | r := r end end /-- `fail_if_success t` acts like `t`, but succeeds if `t` fails and fails if `t` succeeds. Changes made by `t` to the `tactic_state` are preserved only if `t` succeeds. -/ meta def fail_if_success {α : Type u} (t : tactic α) : tactic unit := λ s, match (t s) with | (success a s) := mk_exception "fail_if_success combinator failed, given tactic succeeded" none s | (exception _ _ _) := success () s end /-- `success_if_fail t` acts like `t`, but succeeds if `t` fails and fails if `t` succeeds. Changes made by `t` to the `tactic_state` are preserved only if `t` succeeds. -/ meta def success_if_fail {α : Type u} (t : tactic α) : tactic unit := λ s, match t s with | (success a s) := mk_exception "success_if_fail combinator failed, given tactic succeeded" none s | (exception _ _ _) := success () s end open nat /-- `iterate_at_most n t` iterates `t` `n` times or until `t` fails, returning the result of each successful iteration. -/ meta def iterate_at_most : nat → tactic α → tactic (list α) | 0 t := pure [] | (n + 1) t := do (some a) ← try_core t | pure [], as ← iterate_at_most n t, pure $ a :: as /-- `iterate_at_most' n t` repeats `t` `n` times or until `t` fails. -/ meta def iterate_at_most' : nat → tactic unit → tactic unit | 0 t := skip | (succ n) t := do (some _) ← try_core t | skip, iterate_at_most' n t /-- `iterate_exactly n t` iterates `t` `n` times, returning the result of each iteration. If any iteration fails, the whole tactic fails. -/ meta def iterate_exactly : nat → tactic α → tactic (list α) | 0 t := pure [] | (n + 1) t := do a ← t, as ← iterate_exactly n t, pure $ a ::as /-- `iterate_exactly' n t` executes `t` `n` times. If any iteration fails, the whole tactic fails. -/ meta def iterate_exactly' : nat → tactic unit → tactic unit | 0 t := skip | (n + 1) t := t *> iterate_exactly' n t /-- `iterate t` repeats `t` 100.000 times or until `t` fails, returning the result of each iteration. -/ meta def iterate : tactic α → tactic (list α) := iterate_at_most 100000 /-- `iterate' t` repeats `t` 100.000 times or until `t` fails. -/ 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 /-- Freeze the current set of local instances. -/ meta constant freeze_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') /-- `intron' n` introduces `n` hypotheses and returns the resulting local constants. Fails if there are not at least `n` arguments to introduce. If you do not need the return value, use `intron`. -/ meta def intron' : ℕ → tactic (list expr) | 0 := pure [] | (n + 1) := do h ← intro1, hs ← intron' n, pure $ 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 α) : tactic α := 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], a ← tac, gs' ← get_goals, match gs' with | [] := set_goals rs >> pure a | 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 α)) : tactic α := first $ map solve1 ts private meta def focus_aux {α} : list (tactic α) → list expr → list expr → tactic (list α) | [] [] rs := set_goals rs *> pure [] | (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", a ← t, rs' ← get_goals, as ← focus_aux ts gs (rs ++ rs'), pure $ a :: as /-- `focus [t_1, ..., t_n]` applies t_i to the i-th goal. Fails if the number of goals is not n. Returns the results of t_i (one per goal). -/ meta def focus {α} (ts : list (tactic α)) : tactic (list α) := do gs ← get_goals, focus_aux ts gs [] 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 α) : list expr → list expr → tactic (list α) | [] ac := set_goals ac *> pure [] | (g :: gs) ac := mcond (is_assigned g) (all_goals_core gs ac) $ do set_goals [g], a ← tac, new_gs ← get_goals, as ← all_goals_core gs (ac ++ new_gs), pure $ a :: as /-- Apply the given tactic to all goals. Return one result per goal. -/ meta def all_goals {α} (tac : tactic α) : tactic (list α) := do gs ← get_goals, all_goals_core tac gs [] 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 α) : list expr → list expr → bool → tactic (list (option α)) | [] ac progress := guard progress *> set_goals ac *> pure [] | (g :: gs) ac progress := mcond (is_assigned g) (any_goals_core gs ac progress) $ do set_goals [g], res ← try_core tac, new_gs ← get_goals, ress ← any_goals_core gs (ac ++ new_gs) (res.is_some || progress), pure $ res :: ress /-- Apply `tac` to any goal where it succeeds. The tactic succeeds if `tac` succeeds for at least one goal. The returned list contains the result of `tac` for each goal: `some a` if tac succeeded, or `none` if it did not. -/ meta def any_goals {α} (tac : tactic α) : tactic (list (option α)) := do gs ← get_goals, any_goals_core tac gs [] ff 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` to the main goal, then applies `tac2` to each goal produced by `tac1`. -/ meta def seq {α β} (tac1 : tactic α) (tac2 : α → tactic β) : tactic (list β) := do g::gs ← get_goals, set_goals [g], a ← tac1, bs ← all_goals $ tac2 a, gs' ← get_goals, set_goals (gs' ++ gs), pure bs /-- 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) /-- Applies `tac1` to the main goal, then applies each of the tactics in `tacs2` to one of the produced subgoals (like `focus'`). -/ meta def seq_focus {α β} (tac1 : tactic α) (tacs2 : α → list (tactic β)) : tactic (list β) := do g::gs ← get_goals, set_goals [g], a ← tac1, bs ← focus $ tacs2 a, gs' ← get_goals, set_goals (gs' ++ gs), pure bs /-- Applies `tac1` to the main goal, then applies each of the tactics in `tacs2` to one of the produced subgoals (like `focus`). -/ 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 and the newly introduced hypotheses. -/ meta def cases (e : expr) (ids : list name := []) (md := semireducible) (dmd := semireducible) : tactic (list (name × list expr)) := if e.is_local_constant then do r ← cases_core e ids md, return $ r.map (λ ⟨n, hs, _⟩, ⟨n, hs⟩) 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, hs' ← all_goals (intron' n), return $ r.map₂ (λ ⟨n, hs, _⟩ hs', ⟨n, hs ++ hs'⟩) hs' /-- 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 /-- Get the revertible part of the local context. These are the hypotheses that appear after the last frozen local instance in the local context. We call them revertible because `revert` can revert them, unlike those hypotheses which occur before a frozen instance. -/ meta def revertible_local_context : tactic (list expr) := do ctx ← local_context, frozen ← frozen_local_instances, pure $ match frozen with | none := ctx | some [] := ctx | some (h :: _) := ctx.after (eq h) end /-- Rename local hypotheses according to the given `name_map`. The `name_map` contains as keys those hypotheses that should be renamed; the associated values are the new names. This tactic can only rename hypotheses which occur after the last frozen local instance. If you need to rename earlier hypotheses, try `unfreeze_local_instances`. If `strict` is true, we fail if `name_map` refers to hypotheses that do not appear in the local context or that appear before a frozen local instance. Conversely, if `strict` is false, some entries of `name_map` may be silently ignored. If `use_unique_names` is true, the keys of `name_map` should be the unique names of hypotheses to be renamed. Otherwise, the keys should be display names. Note that we allow shadowing, so renamed hypotheses may have the same name as other hypotheses in the context. If `use_unique_names` is false and there are multiple hypotheses with the same display name in the context, they are all renamed. -/ meta def rename_many (renames : name_map name) (strict := tt) (use_unique_names := ff) : tactic unit := do let hyp_name : expr → name := if use_unique_names then expr.local_uniq_name else expr.local_pp_name, ctx ← revertible_local_context, -- The part of the context after (but including) the first hypthesis that -- must be renamed. let ctx_suffix := ctx.drop_while (λ h, (renames.find $ hyp_name h).is_none), when strict $ do { let ctx_names := rb_map.set_of_list (ctx_suffix.map hyp_name), let invalid_renames := (renames.to_list.map prod.fst).filter (λ h, ¬ ctx_names.contains h), when ¬ invalid_renames.empty $ fail $ format.join [ "Cannot rename these hypotheses:\n" , format.join $ (invalid_renames.map to_fmt).intersperse ", " , format.line , "This is because these hypotheses either do not occur in the\n" , "context or they occur before a frozen local instance.\n" , "In the latter case, try `tactic.unfreeze_local_instances`." ] }, -- The new names for all hypotheses in ctx_suffix. let new_names := ctx_suffix.map $ λ h, (renames.find $ hyp_name h).get_or_else h.local_pp_name, revert_lst ctx_suffix, intro_lst new_names, pure () /-- Rename a local hypothesis. This is a special case of `rename_many`; see there for caveats. -/ meta def rename (curr : name) (new : name) : tactic unit := rename_many (rb_map.of_list [⟨curr, new⟩]) /-- Rename a local hypothesis. Unlike `rename` and `rename_many`, this tactic does not preserve the order of hypotheses. Its implementation is simpler (and therefore probably faster) than that of `rename`. -/ meta def rename_unstable (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 meta def eval_pexpr (α) [reflected α] (e : pexpr) : tactic α := to_expr ``(%%e : %%(reflect α)) ff ff >>= eval_expr α meta def tactic.run_simple {α} : tactic_state → tactic α → option α | ts t := match t ts with | (interaction_monad.result.success a ts') := some a | (interaction_monad.result.exception _ _ _) := none end end tactic
be3bd7c976f66bdaa964e97d12395f5612cda05f
7cef822f3b952965621309e88eadf618da0c8ae9
/src/algebra/module.lean
78580a59c3bd7ced888bd8a0766cdf7f072fe7f0
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
17,381
lean
/- Copyright (c) 2015 Nathaniel Thomas. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro Modules over a ring. ## Implementation notes Throughout the `linear_map` section implicit `{}` brackets are often used instead of type class `[]` brackets. This is done when the instances can be inferred because they are implicit arguments to the type `linear_map`. When they can be inferred from the type it is faster to use this method than to use type class inference -/ import algebra.ring algebra.big_operators group_theory.subgroup group_theory.group_action open function universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} -- /-- Typeclass for types with a scalar multiplication operation, denoted `•` (`\bu`) -/ -- class has_scalar (α : Type u) (γ : Type v) := (smul : α → γ → γ) -- infixr ` • `:73 := has_scalar.smul section prio set_option default_priority 100 -- see Note [default priority] /-- A semimodule is a generalization of vector spaces to a scalar semiring. It consists of a scalar semiring `α` and an additive monoid of "vectors" `β`, connected by a "scalar multiplication" operation `r • x : β` (where `r : α` and `x : β`) with some natural associativity and distributivity axioms similar to those on a ring. -/ class semimodule (α : Type u) (β : Type v) [semiring α] [add_comm_monoid β] extends distrib_mul_action α β := (add_smul : ∀(r s : α) (x : β), (r + s) • x = r • x + s • x) (zero_smul : ∀x : β, (0 : α) • x = 0) end prio section semimodule variables [R:semiring α] [add_comm_monoid β] [semimodule α β] (r s : α) (x y : β) include R theorem add_smul : (r + s) • x = r • x + s • x := semimodule.add_smul r s x variables (α) @[simp] theorem zero_smul : (0 : α) • x = 0 := semimodule.zero_smul α x lemma smul_smul : r • s • x = (r * s) • x := (mul_smul _ _ _).symm instance smul.is_add_monoid_hom {r : α} : is_add_monoid_hom (λ x : β, r • x) := { map_add := smul_add _, map_zero := smul_zero _ } lemma semimodule.eq_zero_of_zero_eq_one (zero_eq_one : (0 : α) = 1) : x = 0 := by rw [←one_smul α x, ←zero_eq_one, zero_smul] /-- R-linearity of finite sums of elements of an R-semimodule. -/ lemma finset.sum_smul {α : Type*} {R : Type*} [semiring R] {M : Type*} [add_comm_monoid M] [semimodule R M] (s : finset α) (r : R) (f : α → M) : finset.sum s (λ (x : α), (r • (f x))) = r • (finset.sum s f) := by classical; exact finset.induction_on s (by simp) (by simp [_root_.smul_add] {contextual := tt}) end semimodule section prio set_option default_priority 100 -- see Note [default priority] /-- A module is a generalization of vector spaces to a scalar ring. It consists of a scalar ring `α` and an additive group of "vectors" `β`, connected by a "scalar multiplication" operation `r • x : β` (where `r : α` and `x : β`) with some natural associativity and distributivity axioms similar to those on a ring. -/ class module (α : Type u) (β : Type v) [ring α] [add_comm_group β] extends semimodule α β end prio structure module.core (α β) [ring α] [add_comm_group β] extends has_scalar α β := (smul_add : ∀(r : α) (x y : β), r • (x + y) = r • x + r • y) (add_smul : ∀(r s : α) (x : β), (r + s) • x = r • x + s • x) (mul_smul : ∀(r s : α) (x : β), (r * s) • x = r • s • x) (one_smul : ∀x : β, (1 : α) • x = x) def module.of_core {α β} [ring α] [add_comm_group β] (M : module.core α β) : module α β := by letI := M.to_has_scalar; exact { zero_smul := λ x, have (0 : α) • x + (0 : α) • x = (0 : α) • x + 0, by rw ← M.add_smul; simp, add_left_cancel this, smul_zero := λ r, have r • (0:β) + r • 0 = r • 0 + 0, by rw ← M.smul_add; simp, add_left_cancel this, ..M } section module variables [ring α] [add_comm_group β] [module α β] (r s : α) (x y : β) @[simp] theorem neg_smul : -r • x = - (r • x) := eq_neg_of_add_eq_zero (by rw [← add_smul, add_left_neg, zero_smul]) variables (α) theorem neg_one_smul (x : β) : (-1 : α) • x = -x := by simp variables {α} @[simp] theorem smul_neg : r • (-x) = -(r • x) := by rw [← neg_one_smul α, ← mul_smul, mul_neg_one, neg_smul] theorem smul_sub (r : α) (x y : β) : r • (x - y) = r • x - r • y := by simp [smul_add]; rw smul_neg theorem sub_smul (r s : α) (y : β) : (r - s) • y = r • y - s • y := by simp [add_smul] end module instance semiring.to_semimodule [r : semiring α] : semimodule α α := { smul := (*), smul_add := mul_add, add_smul := add_mul, mul_smul := mul_assoc, one_smul := one_mul, zero_smul := zero_mul, smul_zero := mul_zero, ..r } @[simp] lemma smul_eq_mul [semiring α] {a a' : α} : a • a' = a * a' := rfl instance ring.to_module [r : ring α] : module α α := { ..semiring.to_semimodule } def is_ring_hom.to_module [ring α] [ring β] (f : α → β) [h : is_ring_hom f] : module α β := module.of_core { smul := λ r x, f r * x, smul_add := λ r x y, by unfold has_scalar.smul; rw [mul_add], add_smul := λ r s x, by unfold has_scalar.smul; rw [h.map_add, add_mul], mul_smul := λ r s x, by unfold has_scalar.smul; rw [h.map_mul, mul_assoc], one_smul := λ x, show f 1 * x = _, by rw [h.map_one, one_mul] } class is_linear_map (α : Type u) {β : Type v} {γ : Type w} [ring α] [add_comm_group β] [add_comm_group γ] [module α β] [module α γ] (f : β → γ) : Prop := (add : ∀x y, f (x + y) = f x + f y) (smul : ∀(c : α) x, f (c • x) = c • f x) structure linear_map (α : Type u) (β : Type v) (γ : Type w) [ring α] [add_comm_group β] [add_comm_group γ] [module α β] [module α γ] := (to_fun : β → γ) (add : ∀x y, to_fun (x + y) = to_fun x + to_fun y) (smul : ∀(c : α) x, to_fun (c • x) = c • to_fun x) infixr ` →ₗ `:25 := linear_map _ notation β ` →ₗ[`:25 α:25 `] `:0 γ:0 := linear_map α β γ namespace linear_map variables {rα : ring α} {gβ : add_comm_group β} {gγ : add_comm_group γ} {gδ : add_comm_group δ} variables {mβ : module α β} {mγ : module α γ} {mδ : module α δ} variables (f g : β →ₗ[α] γ) include α mβ mγ instance : has_coe_to_fun (β →ₗ[α] γ) := ⟨_, to_fun⟩ @[simp] lemma coe_mk (f : β → γ) (h₁ h₂) : ((linear_map.mk f h₁ h₂ : β →ₗ[α] γ) : β → γ) = f := rfl theorem is_linear : is_linear_map α f := {..f} @[ext] theorem ext {f g : β →ₗ[α] γ} (H : ∀ x, f x = g x) : f = g := by cases f; cases g; congr'; exact funext H theorem ext_iff {f g : β →ₗ[α] γ} : f = g ↔ ∀ x, f x = g x := ⟨by rintro rfl; simp, ext⟩ @[simp] lemma map_add (x y : β) : f (x + y) = f x + f y := f.add x y @[simp] lemma map_smul (c : α) (x : β) : f (c • x) = c • f x := f.smul c x @[simp] lemma map_zero : f 0 = 0 := by rw [← zero_smul α, map_smul f 0 0, zero_smul] instance : is_add_group_hom f := { map_add := map_add f } @[simp] lemma map_neg (x : β) : f (- x) = - f x := by rw [← neg_one_smul α, map_smul, neg_one_smul] @[simp] lemma map_sub (x y : β) : f (x - y) = f x - f y := by simp [map_neg, map_add] @[simp] lemma map_sum {ι} {t : finset ι} {g : ι → β} : f (t.sum g) = t.sum (λi, f (g i)) := (finset.sum_hom f).symm include mδ def comp (f : γ →ₗ[α] δ) (g : β →ₗ[α] γ) : β →ₗ[α] δ := ⟨f ∘ g, by simp, by simp⟩ @[simp] lemma comp_apply (f : γ →ₗ[α] δ) (g : β →ₗ[α] γ) (x : β) : f.comp g x = f (g x) := rfl omit mγ mδ variables [rα] [gβ] [mβ] def id : β →ₗ[α] β := ⟨id, by simp, by simp⟩ @[simp] lemma id_apply (x : β) : @id α β _ _ _ x = x := rfl end linear_map namespace is_linear_map variables [ring α] [add_comm_group β] [add_comm_group γ] variables [module α β] [module α γ] include α def mk' (f : β → γ) (H : is_linear_map α f) : β →ₗ γ := {to_fun := f, ..H} @[simp] theorem mk'_apply {f : β → γ} (H : is_linear_map α f) (x : β) : mk' f H x = f x := rfl lemma is_linear_map_neg : is_linear_map α (λ (z : β), -z) := is_linear_map.mk neg_add (λ x y, (smul_neg x y).symm) lemma is_linear_map_smul {α R : Type*} [add_comm_group α] [comm_ring R] [module R α] (c : R) : is_linear_map R (λ (z : α), c • z) := begin refine is_linear_map.mk (smul_add c) _, intros _ _, simp [smul_smul], ac_refl end --TODO: move lemma is_linear_map_smul' {α R : Type*} [add_comm_group α] [ring R] [module R α] (a : α) : is_linear_map R (λ (c : R), c • a) := begin refine is_linear_map.mk (λ x y, add_smul x y a) _, intros _ _, simp [smul_smul] end variables {f : β → γ} (lin : is_linear_map α f) include β γ lin @[simp] lemma map_zero : f (0 : β) = (0 : γ) := by rw [← zero_smul α (0 : β), lin.smul, zero_smul] @[simp] lemma map_add (x y : β) : f (x + y) = f x + f y := by rw [lin.add] @[simp] lemma map_neg (x : β) : f (- x) = - f x := by rw [← neg_one_smul α, lin.smul, neg_one_smul] @[simp] lemma map_sub (x y : β) : f (x - y) = f x - f y := by simp [lin.map_neg, lin.map_add] end is_linear_map abbreviation module.End (R : Type u) (M : Type v) [comm_ring R] [add_comm_group M] [module R M] := M →ₗ[R] M /-- A submodule of a module is one which is closed under vector operations. This is a sufficient condition for the subset of vectors in the submodule to themselves form a module. -/ structure submodule (α : Type u) (β : Type v) [ring α] [add_comm_group β] [module α β] : Type v := (carrier : set β) (zero : (0:β) ∈ carrier) (add : ∀ {x y}, x ∈ carrier → y ∈ carrier → x + y ∈ carrier) (smul : ∀ (c:α) {x}, x ∈ carrier → c • x ∈ carrier) namespace submodule variables [ring α] [add_comm_group β] [add_comm_group γ] variables [module α β] [module α γ] variables (p p' : submodule α β) variables {r : α} {x y : β} instance : has_coe (submodule α β) (set β) := ⟨submodule.carrier⟩ instance : has_mem β (submodule α β) := ⟨λ x p, x ∈ (p : set β)⟩ @[simp] theorem mem_coe : x ∈ (p : set β) ↔ x ∈ p := iff.rfl theorem ext' {s t : submodule α β} (h : (s : set β) = t) : s = t := by cases s; cases t; congr' protected theorem ext'_iff {s t : submodule α β} : (s : set β) = t ↔ s = t := ⟨ext', λ h, h ▸ rfl⟩ @[ext] theorem ext {s t : submodule α β} (h : ∀ x, x ∈ s ↔ x ∈ t) : s = t := ext' $ set.ext h @[simp] lemma zero_mem : (0 : β) ∈ p := p.zero lemma add_mem (h₁ : x ∈ p) (h₂ : y ∈ p) : x + y ∈ p := p.add h₁ h₂ lemma smul_mem (r : α) (h : x ∈ p) : r • x ∈ p := p.smul r h lemma neg_mem (hx : x ∈ p) : -x ∈ p := by rw ← neg_one_smul α; exact p.smul_mem _ hx lemma sub_mem (hx : x ∈ p) (hy : y ∈ p) : x - y ∈ p := p.add_mem hx (p.neg_mem hy) lemma neg_mem_iff : -x ∈ p ↔ x ∈ p := ⟨λ h, by simpa using neg_mem p h, neg_mem p⟩ lemma add_mem_iff_left (h₁ : y ∈ p) : x + y ∈ p ↔ x ∈ p := ⟨λ h₂, by simpa using sub_mem _ h₂ h₁, λ h₂, add_mem _ h₂ h₁⟩ lemma add_mem_iff_right (h₁ : x ∈ p) : x + y ∈ p ↔ y ∈ p := ⟨λ h₂, by simpa using sub_mem _ h₂ h₁, add_mem _ h₁⟩ lemma sum_mem {ι : Type w} [decidable_eq ι] {t : finset ι} {f : ι → β} : (∀c∈t, f c ∈ p) → t.sum f ∈ p := finset.induction_on t (by simp [p.zero_mem]) (by simp [p.add_mem] {contextual := tt}) instance : has_add p := ⟨λx y, ⟨x.1 + y.1, add_mem _ x.2 y.2⟩⟩ instance : has_zero p := ⟨⟨0, zero_mem _⟩⟩ instance : has_neg p := ⟨λx, ⟨-x.1, neg_mem _ x.2⟩⟩ instance : has_scalar α p := ⟨λ c x, ⟨c • x.1, smul_mem _ c x.2⟩⟩ @[simp] lemma coe_add (x y : p) : (↑(x + y) : β) = ↑x + ↑y := rfl @[simp] lemma coe_zero : ((0 : p) : β) = 0 := rfl @[simp] lemma coe_neg (x : p) : ((-x : p) : β) = -x := rfl @[simp] lemma coe_smul (r : α) (x : p) : ((r • x : p) : β) = r • ↑x := rfl instance : add_comm_group p := by refine {add := (+), zero := 0, neg := has_neg.neg, ..}; { intros, apply set_coe.ext, simp } instance submodule_is_add_subgroup : is_add_subgroup (p : set β) := { zero_mem := p.zero, add_mem := p.add, neg_mem := λ _, p.neg_mem } lemma coe_sub (x y : p) : (↑(x - y) : β) = ↑x - ↑y := by simp instance : module α p := by refine {smul := (•), ..}; { intros, apply set_coe.ext, simp [smul_add, add_smul, mul_smul] } protected def subtype : p →ₗ[α] β := by refine {to_fun := coe, ..}; simp [coe_smul] @[simp] theorem subtype_apply (x : p) : p.subtype x = x := rfl lemma subtype_eq_val (p : submodule α β) : ((submodule.subtype p) : p → β) = subtype.val := rfl end submodule @[reducible] def ideal (α : Type u) [comm_ring α] := submodule α α namespace ideal variables [comm_ring α] (I : ideal α) {a b : α} protected lemma zero_mem : (0 : α) ∈ I := I.zero_mem protected lemma add_mem : a ∈ I → b ∈ I → a + b ∈ I := I.add_mem lemma neg_mem_iff : -a ∈ I ↔ a ∈ I := I.neg_mem_iff lemma add_mem_iff_left : b ∈ I → (a + b ∈ I ↔ a ∈ I) := I.add_mem_iff_left lemma add_mem_iff_right : a ∈ I → (a + b ∈ I ↔ b ∈ I) := I.add_mem_iff_right protected lemma sub_mem : a ∈ I → b ∈ I → a - b ∈ I := I.sub_mem lemma mul_mem_left : b ∈ I → a * b ∈ I := I.smul_mem _ lemma mul_mem_right (h : a ∈ I) : a * b ∈ I := mul_comm b a ▸ I.mul_mem_left h end ideal library_note "vector space definition" "Vector spaces are defined as an `abbreviation` for modules, if the base ring is a field. (A previous definition made `vector_space` a structure defined to be `module`.) This has as advantage that vector spaces are completely transparant for type class inference, which means that all instances for modules are immediately picked up for vector spaces as well. A cosmetic disadvantage is that one can not extend vector spaces an sich, in definitions such as `normed_space`. The solution is to extend `module` instead." /-- A vector space is the same as a module, except the scalar ring is actually a field. (This adds commutativity of the multiplication and existence of inverses.) This is the traditional generalization of spaces like `ℝ^n`, which have a natural addition operation and a way to multiply them by real numbers, but no multiplication operation between vectors. -/ abbreviation vector_space (α : Type u) (β : Type v) [discrete_field α] [add_comm_group β] := module α β instance discrete_field.to_vector_space {α : Type*} [discrete_field α] : vector_space α α := { .. ring.to_module } /-- Subspace of a vector space. Defined to equal `submodule`. -/ @[reducible] def subspace (α : Type u) (β : Type v) [discrete_field α] [add_comm_group β] [vector_space α β] : Type v := submodule α β instance subspace.vector_space {α β} {f : discrete_field α} [add_comm_group β] [vector_space α β] (p : subspace α β) : vector_space α p := {..submodule.module p} namespace submodule variables {R:discrete_field α} [add_comm_group β] [add_comm_group γ] variables [vector_space α β] [vector_space α γ] variables (p p' : submodule α β) variables {r : α} {x y : β} include R set_option class.instance_max_depth 36 theorem smul_mem_iff (r0 : r ≠ 0) : r • x ∈ p ↔ x ∈ p := ⟨λ h, by simpa [smul_smul, inv_mul_cancel r0] using p.smul_mem (r⁻¹) h, p.smul_mem r⟩ end submodule namespace add_comm_monoid open add_monoid variables {M : Type*} [add_comm_monoid M] instance : semimodule ℕ M := { smul := smul, smul_add := λ _ _ _, smul_add _ _ _, add_smul := λ _ _ _, add_smul _ _ _, mul_smul := λ _ _ _, mul_smul _ _ _, one_smul := one_smul, zero_smul := zero_smul, smul_zero := smul_zero } end add_comm_monoid namespace add_comm_group variables {M : Type*} [add_comm_group M] instance : module ℤ M := { smul := gsmul, smul_add := λ _ _ _, gsmul_add _ _ _, add_smul := λ _ _ _, add_gsmul _ _ _, mul_smul := λ _ _ _, gsmul_mul _ _ _, one_smul := one_gsmul, zero_smul := zero_gsmul, smul_zero := gsmul_zero } end add_comm_group lemma gsmul_eq_smul {M : Type*} [add_comm_group M] (n : ℤ) (x : M) : gsmul n x = n • x := rfl def is_add_group_hom.to_linear_map [add_comm_group α] [add_comm_group β] (f : α → β) [is_add_group_hom f] : α →ₗ[ℤ] β := { to_fun := f, add := is_add_hom.map_add f, smul := λ i x, int.induction_on i (by rw [zero_smul, zero_smul, is_add_group_hom.map_zero f]) (λ i ih, by rw [add_smul, add_smul, is_add_hom.map_add f, ih, one_smul, one_smul]) (λ i ih, by rw [sub_smul, sub_smul, is_add_group_hom.map_sub f, ih, one_smul, one_smul]) } lemma module.smul_eq_smul {R : Type*} [ring R] {β : Type*} [add_comm_group β] [module R β] (n : ℕ) (b : β) : n • b = (n : R) • b := begin induction n with n ih, { rw [nat.cast_zero, zero_smul, zero_smul] }, { change (n + 1) • b = (n + 1 : R) • b, rw [add_smul, add_smul, one_smul, ih, one_smul] } end lemma finset.sum_const' {α : Type*} (R : Type*) [ring R] {β : Type*} [add_comm_group β] [module R β] {s : finset α} (b : β) : finset.sum s (λ (a : α), b) = (finset.card s : R) • b := by rw [finset.sum_const, ← module.smul_eq_smul]; refl
2be814c288405a4ea26a8da60cb57c720a36bb29
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/data/pnat/xgcd.lean
79bb62ca5602fbeeaa625db1f51a263c46c40da6
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
13,319
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland This file sets up a version of the Euclidean algorithm that works only with natural numbers. Given a, b > 0, it computes the unique system (w, x, y, z, d) such that the following identities hold: w * z = x * y + 1 a = (w + x) d b = (y + z) d These equations force w, z, d > 0. They also imply that the integers a' = w + x = a / d and b' = y + z = b / d are coprime, and that d is the gcd of a and b. This story is closely related to the structure of SL₂(ℕ) (as a free monoid on two generators) and the theory of continued fractions. -/ import tactic.ring import tactic.abel import data.pnat.prime namespace pnat open nat pnat /-- A term of xgcd_type is a system of six naturals. They should be thought of as representing the matrix [[w, x], [y, z]] = [[wp + 1, x], [y, zp + 1]] together with the vector [a, b] = [ap + 1, bp + 1]. -/ @[derive inhabited] structure xgcd_type := (wp x y zp ap bp : ℕ) namespace xgcd_type variable (u : xgcd_type) instance : has_sizeof xgcd_type := ⟨λ u, u.bp⟩ /-- The has_repr instance converts terms to strings in a way that reflects the matrix/vector interpretation as above. -/ instance : has_repr xgcd_type := ⟨λ u, "[[[" ++ (repr (u.wp + 1)) ++ ", " ++ (repr u.x) ++ "], [" ++ (repr u.y) ++ ", " ++ (repr (u.zp + 1)) ++ "]], [" ++ (repr (u.ap + 1)) ++ ", " ++ (repr (u.bp + 1)) ++ "]]"⟩ def mk' (w : ℕ+) (x : ℕ) (y : ℕ) (z : ℕ+) (a : ℕ+) (b : ℕ+) : xgcd_type := mk w.val.pred x y z.val.pred a.val.pred b.val.pred def w : ℕ+ := succ_pnat u.wp def z : ℕ+ := succ_pnat u.zp def a : ℕ+ := succ_pnat u.ap def b : ℕ+ := succ_pnat u.bp def r : ℕ := (u.ap + 1) % (u.bp + 1) def q : ℕ := (u.ap + 1) / (u.bp + 1) def qp : ℕ := u.q - 1 /-- The map v gives the product of the matrix [[w, x], [y, z]] = [[wp + 1, x], [y, zp + 1]] and the vector [a, b] = [ap + 1, bp + 1]. The map vp gives [sp, tp] such that v = [sp + 1, tp + 1]. -/ def vp : ℕ × ℕ := ⟨ u.wp + u.x + u.ap + u.wp * u.ap + u.x * u.bp, u.y + u.zp + u.bp + u.y * u.ap + u.zp * u.bp ⟩ def v : ℕ × ℕ := ⟨u.w * u.a + u.x * u.b, u.y * u.a + u.z * u.b⟩ def succ₂ (t : ℕ × ℕ) : ℕ × ℕ := ⟨t.1.succ, t.2.succ⟩ theorem v_eq_succ_vp : u.v = succ₂ u.vp := by { ext; dsimp [v, vp, w, z, a, b, succ₂]; repeat { rw [nat.succ_eq_add_one] }; ring } /-- is_special holds if the matrix has determinant one. -/ def is_special : Prop := u.wp + u.zp + u.wp * u.zp = u.x * u.y def is_special' : Prop := u.w * u.z = succ_pnat (u.x * u.y) theorem is_special_iff : u.is_special ↔ u.is_special' := begin dsimp [is_special, is_special'], split; intro h, { apply eq, dsimp [w, z, succ_pnat], rw [← h], repeat { rw [nat.succ_eq_add_one] }, ring }, { apply nat.succ.inj, replace h := congr_arg (coe : ℕ+ → ℕ) h, rw [mul_coe, w, z] at h, repeat { rw [succ_pnat_coe, nat.succ_eq_add_one] at h }, repeat { rw [nat.succ_eq_add_one] }, rw [← h], ring } end /-- is_reduced holds if the two entries in the vector are the same. The reduction algorithm will produce a system with this property, whose product vector is the same as for the original system. -/ def is_reduced : Prop := u.ap = u.bp def is_reduced' : Prop := u.a = u.b theorem is_reduced_iff : u.is_reduced ↔ u.is_reduced' := ⟨ congr_arg succ_pnat, succ_pnat_inj ⟩ def flip : xgcd_type := { wp := u.zp, x := u.y, y := u.x, zp := u.wp, ap := u.bp, bp := u.ap } @[simp] theorem flip_w : (flip u).w = u.z := rfl @[simp] theorem flip_x : (flip u).x = u.y := rfl @[simp] theorem flip_y : (flip u).y = u.x := rfl @[simp] theorem flip_z : (flip u).z = u.w := rfl @[simp] theorem flip_a : (flip u).a = u.b := rfl @[simp] theorem flip_b : (flip u).b = u.a := rfl theorem flip_is_reduced : (flip u).is_reduced ↔ u.is_reduced := by { dsimp [is_reduced, flip], split; intro h; exact h.symm } theorem flip_is_special : (flip u).is_special ↔ u.is_special := by { dsimp [is_special, flip], rw[mul_comm u.x, mul_comm u.zp, add_comm u.zp] } theorem flip_v : (flip u).v = (u.v).swap := by { dsimp [v], ext, { simp only, ring }, { simp only, ring } } /-- Properties of division with remainder for a / b. -/ theorem rq_eq : u.r + (u.bp + 1) * u.q = u.ap + 1 := nat.mod_add_div (u.ap + 1) (u.bp + 1) theorem qp_eq (hr : u.r = 0) : u.q = u.qp + 1 := begin by_cases hq : u.q = 0, { let h := u.rq_eq, rw [hr, hq, mul_zero, add_zero] at h, cases h }, { exact (nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero hq)).symm } end /-- The following function provides the starting point for our algorithm. We will apply an iterative reduction process to it, which will produce a system satisfying is_reduced. The gcd can be read off from this final system. -/ def start (a b : ℕ+) : xgcd_type := ⟨0, 0, 0, 0, a - 1, b - 1⟩ theorem start_is_special (a b : ℕ+) : (start a b).is_special := by { dsimp [start, is_special], refl } theorem start_v (a b : ℕ+) : (start a b).v = ⟨a, b⟩ := begin dsimp [start, v, xgcd_type.a, xgcd_type.b, w, z], rw [one_mul, one_mul, zero_mul, zero_mul, zero_add, add_zero], rw [← nat.pred_eq_sub_one, ← nat.pred_eq_sub_one], rw [nat.succ_pred_eq_of_pos a.pos, nat.succ_pred_eq_of_pos b.pos] end def finish : xgcd_type := xgcd_type.mk u.wp ((u.wp + 1) * u.qp + u.x) u.y (u.y * u.qp + u.zp) u.bp u.bp theorem finish_is_reduced : u.finish.is_reduced := by { dsimp [is_reduced], refl } theorem finish_is_special (hs : u.is_special) : u.finish.is_special := begin dsimp [is_special, finish] at hs ⊢, rw [add_mul _ _ u.y, add_comm _ (u.x * u.y), ← hs], ring end theorem finish_v (hr : u.r = 0) : u.finish.v = u.v := begin let ha : u.r + u.b * u.q = u.a := u.rq_eq, rw [hr, zero_add] at ha, ext, { change (u.wp + 1) * u.b + ((u.wp + 1) * u.qp + u.x) * u.b = u.w * u.a + u.x * u.b, have : u.wp + 1 = u.w := rfl, rw [this, ← ha, u.qp_eq hr], ring }, { change u.y * u.b + (u.y * u.qp + u.z) * u.b = u.y * u.a + u.z * u.b, rw [← ha, u.qp_eq hr], ring } end /-- This is the main reduction step, which is used when u.r ≠ 0, or equivalently b does not divide a. -/ def step : xgcd_type := xgcd_type.mk (u.y * u.q + u.zp) u.y ((u.wp + 1) * u.q + u.x) u.wp u.bp (u.r - 1) /-- We will apply the above step recursively. The following result is used to ensure that the process terminates. -/ theorem step_wf (hr : u.r ≠ 0) : sizeof u.step < sizeof u := begin change u.r - 1 < u.bp, have h₀ : (u.r - 1) + 1 = u.r := nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero hr), have h₁ : u.r < u.bp + 1 := nat.mod_lt (u.ap + 1) u.bp.succ_pos, rw[← h₀] at h₁, exact lt_of_succ_lt_succ h₁, end theorem step_is_special (hs : u.is_special) : u.step.is_special := begin dsimp [is_special, step] at hs ⊢, rw [mul_add, mul_comm u.y u.x, ← hs], ring end /-- The reduction step does not change the product vector. -/ theorem step_v (hr : u.r ≠ 0) : u.step.v = (u.v).swap := begin let ha : u.r + u.b * u.q = u.a := u.rq_eq, let hr : (u.r - 1) + 1 = u.r := (add_comm _ 1).trans (nat.add_sub_of_le (nat.pos_of_ne_zero hr)), ext, { change ((u.y * u.q + u.z) * u.b + u.y * (u.r - 1 + 1) : ℕ) = u.y * u.a + u.z * u.b, rw [← ha, hr], ring }, { change ((u.w * u.q + u.x) * u.b + u.w * (u.r - 1 + 1) : ℕ) = u.w * u.a + u.x * u.b, rw [← ha, hr], ring } end /-- We can now define the full reduction function, which applies step as long as possible, and then applies finish. Note that the "have" statement puts a fact in the local context, and the equation compiler uses this fact to help construct the full definition in terms of well-founded recursion. The same fact needs to be introduced in all the inductive proofs of properties given below. -/ def reduce : xgcd_type → xgcd_type | u := dite (u.r = 0) (λ h, u.finish) (λ h, have sizeof u.step < sizeof u, from u.step_wf h, flip (reduce u.step)) theorem reduce_a {u : xgcd_type} (h : u.r = 0) : u.reduce = u.finish := by { rw [reduce], simp only, rw [if_pos h] } theorem reduce_b {u : xgcd_type} (h : u.r ≠ 0) : u.reduce = u.step.reduce.flip := by { rw [reduce], simp only, rw [if_neg h, step] } theorem reduce_reduced : ∀ (u : xgcd_type), u.reduce.is_reduced | u := dite (u.r = 0) (λ h, by { rw [reduce_a h], exact u.finish_is_reduced }) (λ h, have sizeof u.step < sizeof u, from u.step_wf h, by { rw [reduce_b h, flip_is_reduced], apply reduce_reduced }) theorem reduce_reduced' (u : xgcd_type) : u.reduce.is_reduced' := (is_reduced_iff _).mp u.reduce_reduced theorem reduce_special : ∀ (u : xgcd_type), u.is_special → u.reduce.is_special | u := dite (u.r = 0) (λ h hs, by { rw [reduce_a h], exact u.finish_is_special hs }) (λ h hs, have sizeof u.step < sizeof u, from u.step_wf h, by { rw [reduce_b h], exact (flip_is_special _).mpr (reduce_special _ (u.step_is_special hs)) }) theorem reduce_special' (u : xgcd_type) (hs : u.is_special) : u.reduce.is_special' := (is_special_iff _).mp (u.reduce_special hs) theorem reduce_v : ∀ (u : xgcd_type), u.reduce.v = u.v | u := dite (u.r = 0) (λ h, by {rw[reduce_a h, finish_v u h]}) (λ h, have sizeof u.step < sizeof u, from u.step_wf h, by { rw[reduce_b h, flip_v, reduce_v (step u), step_v u h, prod.swap_swap] }) end xgcd_type section gcd variables (a b : ℕ+) def xgcd: xgcd_type := (xgcd_type.start a b).reduce def gcd_d : ℕ+ := (xgcd a b).a def gcd_w : ℕ+ := (xgcd a b).w def gcd_x : ℕ := (xgcd a b).x def gcd_y : ℕ := (xgcd a b).y def gcd_z : ℕ+ := (xgcd a b).z def gcd_a' : ℕ+ := succ_pnat ((xgcd a b).wp + (xgcd a b).x) def gcd_b' : ℕ+ := succ_pnat ((xgcd a b).y + (xgcd a b).zp) theorem gcd_a'_coe : ((gcd_a' a b) : ℕ) = (gcd_w a b) + (gcd_x a b) := by { dsimp [gcd_a', gcd_x, gcd_w, xgcd_type.w], rw [nat.succ_eq_add_one, nat.succ_eq_add_one, add_right_comm] } theorem gcd_b'_coe : ((gcd_b' a b) : ℕ) = (gcd_y a b) + (gcd_z a b) := by { dsimp [gcd_b', gcd_y, gcd_z, xgcd_type.z], rw [nat.succ_eq_add_one, nat.succ_eq_add_one, add_assoc] } theorem gcd_props : let d := gcd_d a b, w := gcd_w a b, x := gcd_x a b, y := gcd_y a b, z := gcd_z a b, a' := gcd_a' a b, b' := gcd_b' a b in (w * z = succ_pnat (x * y) ∧ (a = a' * d) ∧ (b = b' * d) ∧ z * a' = succ_pnat (x * b') ∧ w * b' = succ_pnat (y * a') ∧ (z * a : ℕ) = x * b + d ∧ (w * b : ℕ) = y * a + d ) := begin intros, let u := (xgcd_type.start a b), let ur := u.reduce, have ha : d = ur.a := rfl, have hb : d = ur.b := u.reduce_reduced', have ha' : (a' : ℕ) = w + x := gcd_a'_coe a b, have hb' : (b' : ℕ) = y + z := gcd_b'_coe a b, have hdet : w * z = succ_pnat (x * y) := u.reduce_special' rfl, split, exact hdet, have hdet' : ((w * z) : ℕ) = x * y + 1 := by { rw [← mul_coe, hdet, succ_pnat_coe] }, have huv : u.v = ⟨a, b⟩ := (xgcd_type.start_v a b), let hv : prod.mk (w * d + x * ur.b : ℕ) (y * d + z * ur.b : ℕ) = ⟨a, b⟩ := u.reduce_v.trans (xgcd_type.start_v a b), rw [← hb, ← add_mul, ← add_mul, ← ha', ← hb'] at hv, have ha'' : (a : ℕ) = a' * d := (congr_arg prod.fst hv).symm, have hb'' : (b : ℕ) = b' * d := (congr_arg prod.snd hv).symm, split, exact eq ha'', split, exact eq hb'', have hza' : (z * a' : ℕ) = x * b' + 1, by { rw [ha', hb', mul_add, mul_add, mul_comm (z : ℕ), hdet'], ring }, have hwb' : (w * b' : ℕ) = y * a' + 1, by { rw [ha', hb', mul_add, mul_add, hdet'], ring }, split, { apply eq, rw [succ_pnat_coe, nat.succ_eq_add_one, mul_coe, hza'] }, split, { apply eq, rw [succ_pnat_coe, nat.succ_eq_add_one, mul_coe, hwb'] }, rw [ha'', hb''], repeat { rw [← mul_assoc] }, rw [hza', hwb'], split; ring, end theorem gcd_eq : gcd_d a b = gcd a b := begin rcases gcd_props a b with ⟨h₀, h₁, h₂, h₃, h₄, h₅, h₆⟩, apply dvd_antisymm, { apply dvd_gcd, exact dvd.intro (gcd_a' a b) (h₁.trans (mul_comm _ _)).symm, exact dvd.intro (gcd_b' a b) (h₂.trans (mul_comm _ _)).symm}, { have h₇ : (gcd a b : ℕ) ∣ (gcd_z a b) * a := dvd_trans (nat.gcd_dvd_left a b) (dvd_mul_left _ _), have h₈ : (gcd a b : ℕ) ∣ (gcd_x a b) * b := dvd_trans (nat.gcd_dvd_right a b) (dvd_mul_left _ _), rw[h₅] at h₇, rw dvd_iff, exact (nat.dvd_add_iff_right h₈).mpr h₇,} end theorem gcd_det_eq : (gcd_w a b) * (gcd_z a b) = succ_pnat ((gcd_x a b) * (gcd_y a b)) := (gcd_props a b).1 theorem gcd_a_eq : a = (gcd_a' a b) * (gcd a b) := (gcd_eq a b) ▸ (gcd_props a b).2.1 theorem gcd_b_eq : b = (gcd_b' a b) * (gcd a b) := (gcd_eq a b) ▸ (gcd_props a b).2.2.1 theorem gcd_rel_left' : (gcd_z a b) * (gcd_a' a b) = succ_pnat ((gcd_x a b) * (gcd_b' a b)) := (gcd_props a b).2.2.2.1 theorem gcd_rel_right' : (gcd_w a b) * (gcd_b' a b) = succ_pnat ((gcd_y a b) * (gcd_a' a b)) := (gcd_props a b).2.2.2.2.1 theorem gcd_rel_left : ((gcd_z a b) * a : ℕ) = (gcd_x a b) * b + (gcd a b) := (gcd_eq a b) ▸ (gcd_props a b).2.2.2.2.2.1 theorem gcd_rel_right : ((gcd_w a b) * b : ℕ) = (gcd_y a b) * a + (gcd a b) := (gcd_eq a b) ▸ (gcd_props a b).2.2.2.2.2.2 end gcd end pnat
db0bdeeaea8915ed2dccba91c3e7cb95d8bac44e
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/analysis/normed_space/mazur_ulam_auto.lean
697e9fce19d7a7af9cc82ed5f75bdf00713be7dc
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
5,824
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Yury Kudryashov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.instances.real_vector_space import Mathlib.analysis.normed_space.add_torsor import Mathlib.linear_algebra.affine_space.midpoint import Mathlib.analysis.normed_space.linear_isometry import Mathlib.PostPort universes u_1 u_2 u_3 u_4 namespace Mathlib /-! # Mazur-Ulam Theorem Mazur-Ulam theorem states that an isometric bijection between two normed affine spaces over `ℝ` is affine. We formalize it in three definitions: * `isometric.to_real_linear_isometry_equiv_of_map_zero` : given `E ≃ᵢ F` sending `0` to `0`, returns `E ≃ₗᵢ[ℝ] F` with the same `to_fun` and `inv_fun`; * `isometric.to_real_linear_isometry_equiv` : given `f : E ≃ᵢ F`, returns `g : E ≃ₗᵢ[ℝ] F` with `g x = f x - f 0`. * `isometric.to_affine_equiv` : given `PE ≃ᵢ PF`, returns `g : PE ≃ᵃ[ℝ] PF` with the same `to_equiv`. The formalization is based on [Jussi Väisälä, *A Proof of the Mazur-Ulam Theorem*][Vaisala_2003]. ## Tags isometry, affine map, linear map -/ namespace isometric /-- If an isometric self-homeomorphism of a normed vector space over `ℝ` fixes `x` and `y`, then it fixes the midpoint of `[x, y]`. This is a lemma for a more general Mazur-Ulam theorem, see below. -/ theorem midpoint_fixed {E : Type u_1} {PE : Type u_2} [normed_group E] [normed_space ℝ E] [metric_space PE] [normed_add_torsor E PE] {x : PE} {y : PE} (e : PE ≃ᵢ PE) : coe_fn e x = x → coe_fn e y = y → coe_fn e (midpoint ℝ x y) = midpoint ℝ x y := sorry /-- A bijective isometry sends midpoints to midpoints. -/ theorem map_midpoint {E : Type u_1} {PE : Type u_2} [normed_group E] [normed_space ℝ E] [metric_space PE] [normed_add_torsor E PE] {F : Type u_3} {PF : Type u_4} [normed_group F] [normed_space ℝ F] [metric_space PF] [normed_add_torsor F PF] (f : PE ≃ᵢ PF) (x : PE) (y : PE) : coe_fn f (midpoint ℝ x y) = midpoint ℝ (coe_fn f x) (coe_fn f y) := sorry /-! Since `f : PE ≃ᵢ PF` sends midpoints to midpoints, it is an affine map. We define a conversion to a `continuous_linear_equiv` first, then a conversion to an `affine_map`. -/ /-- Mazur-Ulam Theorem: if `f` is an isometric bijection between two normed vector spaces over `ℝ` and `f 0 = 0`, then `f` is a linear equivalence. -/ def to_real_linear_isometry_equiv_of_map_zero {E : Type u_1} [normed_group E] [normed_space ℝ E] {F : Type u_3} [normed_group F] [normed_space ℝ F] (f : E ≃ᵢ F) (h0 : coe_fn f 0 = 0) : linear_isometry_equiv ℝ E F := linear_isometry_equiv.mk (linear_equiv.mk (linear_map.to_fun (continuous_linear_map.to_linear_map (add_monoid_hom.to_real_linear_map (add_monoid_hom.of_map_midpoint ℝ ℝ (⇑f) h0 sorry) sorry))) sorry sorry (equiv.inv_fun (to_equiv f)) sorry sorry) sorry @[simp] theorem coe_to_real_linear_equiv_of_map_zero {E : Type u_1} [normed_group E] [normed_space ℝ E] {F : Type u_3} [normed_group F] [normed_space ℝ F] (f : E ≃ᵢ F) (h0 : coe_fn f 0 = 0) : ⇑(to_real_linear_isometry_equiv_of_map_zero f h0) = ⇑f := rfl @[simp] theorem coe_to_real_linear_equiv_of_map_zero_symm {E : Type u_1} [normed_group E] [normed_space ℝ E] {F : Type u_3} [normed_group F] [normed_space ℝ F] (f : E ≃ᵢ F) (h0 : coe_fn f 0 = 0) : ⇑(linear_isometry_equiv.symm (to_real_linear_isometry_equiv_of_map_zero f h0)) = ⇑(isometric.symm f) := rfl /-- Mazur-Ulam Theorem: if `f` is an isometric bijection between two normed vector spaces over `ℝ`, then `x ↦ f x - f 0` is a linear equivalence. -/ def to_real_linear_isometry_equiv {E : Type u_1} [normed_group E] [normed_space ℝ E] {F : Type u_3} [normed_group F] [normed_space ℝ F] (f : E ≃ᵢ F) : linear_isometry_equiv ℝ E F := to_real_linear_isometry_equiv_of_map_zero (isometric.trans f (isometric.symm (isometric.add_right (coe_fn f 0)))) sorry @[simp] theorem to_real_linear_equiv_apply {E : Type u_1} [normed_group E] [normed_space ℝ E] {F : Type u_3} [normed_group F] [normed_space ℝ F] (f : E ≃ᵢ F) (x : E) : coe_fn (to_real_linear_isometry_equiv f) x = coe_fn f x - coe_fn f 0 := Eq.symm (sub_eq_add_neg (coe_fn f x) (coe_fn f 0)) @[simp] theorem to_real_linear_isometry_equiv_symm_apply {E : Type u_1} [normed_group E] [normed_space ℝ E] {F : Type u_3} [normed_group F] [normed_space ℝ F] (f : E ≃ᵢ F) (y : F) : coe_fn (linear_isometry_equiv.symm (to_real_linear_isometry_equiv f)) y = coe_fn (isometric.symm f) (y + coe_fn f 0) := rfl /-- Convert an isometric equivalence between two affine spaces to an `affine_map`. -/ def to_affine_equiv {E : Type u_1} {PE : Type u_2} [normed_group E] [normed_space ℝ E] [metric_space PE] [normed_add_torsor E PE] {F : Type u_3} {PF : Type u_4} [normed_group F] [normed_space ℝ F] [metric_space PF] [normed_add_torsor F PF] (f : PE ≃ᵢ PF) : affine_equiv ℝ PE PF := affine_equiv.mk' (to_equiv f) (linear_isometry_equiv.to_linear_equiv (to_real_linear_isometry_equiv (isometric.trans (vadd_const (classical.arbitrary PE)) (isometric.trans f (isometric.symm (vadd_const (coe_fn f (classical.arbitrary PE)))))))) (classical.arbitrary PE) sorry @[simp] theorem coe_to_affine_equiv {E : Type u_1} {PE : Type u_2} [normed_group E] [normed_space ℝ E] [metric_space PE] [normed_add_torsor E PE] {F : Type u_3} {PF : Type u_4} [normed_group F] [normed_space ℝ F] [metric_space PF] [normed_add_torsor F PF] (f : PE ≃ᵢ PF) : ⇑(to_affine_equiv f) = ⇑f := rfl end Mathlib
10eea230792c8491a1a9367f9efc0a696169caf1
a4673261e60b025e2c8c825dfa4ab9108246c32e
/stage0/src/Lean/Meta/Tactic/Cases.lean
236953879355607059bc4e47a476b02022a5ea1d
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,612
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.AppBuilder import Lean.Meta.Tactic.Induction import Lean.Meta.Tactic.Injection import Lean.Meta.Tactic.Assert import Lean.Meta.Tactic.Subst namespace Lean.Meta private def throwInductiveTypeExpected {α} (type : Expr) : MetaM α := do throwError! "failed to compile pattern matching, inductive type expected{indentExpr type}" def getInductiveUniverseAndParams (type : Expr) : MetaM (List Level × Array Expr) := do let type ← whnfD type matchConstInduct type.getAppFn (fun _ => throwInductiveTypeExpected type) fun val us => let I := type.getAppFn let Iargs := type.getAppArgs let params := Iargs.extract 0 val.nparams pure (us, params) private def mkEqAndProof (lhs rhs : Expr) : MetaM (Expr × Expr) := do let lhsType ← inferType lhs let rhsType ← inferType rhs let u ← getLevel lhsType if (← isDefEq lhsType rhsType) then pure (mkApp3 (mkConst `Eq [u]) lhsType lhs rhs, mkApp2 (mkConst `Eq.refl [u]) lhsType lhs) else pure (mkApp4 (mkConst `HEq [u]) lhsType lhs rhsType rhs, mkApp2 (mkConst `HEq.refl [u]) lhsType lhs) private partial def withNewEqs {α} (targets targetsNew : Array Expr) (k : Array Expr → Array Expr → MetaM α) : MetaM α := let rec loop (i : Nat) (newEqs : Array Expr) (newRefls : Array Expr) := do if h : i < targets.size then let (newEqType, newRefl) ← mkEqAndProof targets[i] targetsNew[i] withLocalDeclD `h newEqType fun newEq => do loop (i+1) (newEqs.push newEq) (newRefls.push newRefl) else k newEqs newRefls loop 0 #[] #[] def generalizeTargets (mvarId : MVarId) (motiveType : Expr) (targets : Array Expr) : MetaM MVarId := withMVarContext mvarId do checkNotAssigned mvarId `generalizeTargets let (typeNew, eqRefls) ← forallTelescopeReducing motiveType fun targetsNew _ => do unless targetsNew.size == targets.size do throwError! "invalid number of targets #{targets.size}, motive expects #{targetsNew.size}" withNewEqs targets targetsNew fun eqs eqRefls => do let type ← getMVarType mvarId let typeNew ← mkForallFVars eqs type let typeNew ← mkForallFVars targetsNew typeNew pure (typeNew, eqRefls) let mvarNew ← mkFreshExprSyntheticOpaqueMVar typeNew (← getMVarTag mvarId) assignExprMVar mvarId (mkAppN (mkAppN mvarNew targets) eqRefls) pure mvarNew.mvarId! structure GeneralizeIndicesSubgoal := (mvarId : MVarId) (indicesFVarIds : Array FVarId) (fvarId : FVarId) (numEqs : Nat) /-- Similar to `generalizeTargets` but customized for the `casesOn` motive. Given a metavariable `mvarId` representing the ``` Ctx, h : I A j, D |- T ``` where `fvarId` is `h`s id, and the type `I A j` is an inductive datatype where `A` are parameters, and `j` the indices. Generate the goal ``` Ctx, h : I A j, D, j' : J, h' : I A j' |- j == j' -> h == h' -> T ``` Remark: `(j == j' -> h == h')` is a "telescopic" equality. Remark: `j` is sequence of terms, and `j'` a sequence of free variables. The result contains the fields - `mvarId`: the new goal - `indicesFVarIds`: `j'` ids - `fvarId`: `h'` id - `numEqs`: number of equations in the target -/ def generalizeIndices (mvarId : MVarId) (fvarId : FVarId) : MetaM GeneralizeIndicesSubgoal := withMVarContext mvarId do let lctx ← getLCtx let localInsts ← getLocalInstances checkNotAssigned mvarId `generalizeIndices let fvarDecl ← getLocalDecl fvarId let type ← whnf fvarDecl.type type.withApp fun f args => matchConstInduct f (fun _ => throwTacticEx `generalizeIndices mvarId "inductive type expected") fun val _ => do unless val.nindices > 0 do throwTacticEx `generalizeIndices mvarId "indexed inductive type expected" unless args.size == val.nindices + val.nparams do throwTacticEx `generalizeIndices mvarId "ill-formed inductive datatype" let indices := args.extract (args.size - val.nindices) args.size let IA := mkAppN f (args.extract 0 val.nparams) -- `I A` let IAType ← inferType IA forallTelescopeReducing IAType fun newIndices _ => do let newType := mkAppN IA newIndices withLocalDeclD fvarDecl.userName newType fun h' => withNewEqs indices newIndices fun newEqs newRefls => do let (newEqType, newRefl) ← mkEqAndProof fvarDecl.toExpr h' let newRefls := newRefls.push newRefl withLocalDeclD `h newEqType fun newEq => do let newEqs := newEqs.push newEq /- auxType `forall (j' : J) (h' : I A j'), j == j' -> h == h' -> target -/ let target ← getMVarType mvarId let tag ← getMVarTag mvarId let auxType ← mkForallFVars newEqs target let auxType ← mkForallFVars #[h'] auxType let auxType ← mkForallFVars newIndices auxType let newMVar ← mkFreshExprMVarAt lctx localInsts auxType MetavarKind.syntheticOpaque tag /- assign mvarId := newMVar indices h refls -/ assignExprMVar mvarId (mkAppN (mkApp (mkAppN newMVar indices) fvarDecl.toExpr) newRefls) let (indicesFVarIds, newMVarId) ← introNP newMVar.mvarId! newIndices.size let (fvarId, newMVarId) ← intro1P newMVarId pure { mvarId := newMVarId, indicesFVarIds := indicesFVarIds, fvarId := fvarId, numEqs := newEqs.size } structure CasesSubgoal extends InductionSubgoal := (ctorName : Name) namespace Cases structure Context := (inductiveVal : InductiveVal) (casesOnVal : DefinitionVal) (nminors : Nat := inductiveVal.ctors.length) (majorDecl : LocalDecl) (majorTypeFn : Expr) (majorTypeArgs : Array Expr) (majorTypeIndices : Array Expr := majorTypeArgs.extract (majorTypeArgs.size - inductiveVal.nindices) majorTypeArgs.size) private def mkCasesContext? (majorFVarId : FVarId) : MetaM (Option Context) := do let env ← getEnv if !env.contains `Eq || !env.contains `HEq then pure none else let majorDecl ← getLocalDecl majorFVarId let majorType ← whnf majorDecl.type majorType.withApp fun f args => matchConstInduct f (fun _ => pure none) fun ival _ => if args.size != ival.nindices + ival.nparams then pure none else match env.find? (Name.mkStr ival.name "casesOn") with | ConstantInfo.defnInfo cval => pure $ some { inductiveVal := ival, casesOnVal := cval, majorDecl := majorDecl, majorTypeFn := f, majorTypeArgs := args } | _ => pure none /- We say the major premise has independent indices IF 1- its type is *not* an indexed inductive family, OR 2- its type is an indexed inductive family, but all indices are distinct free variables, and all local declarations different from the major and its indices do not depend on the indices. -/ private def hasIndepIndices (ctx : Context) : MetaM Bool := do if ctx.majorTypeIndices.isEmpty then pure true else if ctx.majorTypeIndices.any $ fun idx => !idx.isFVar then /- One of the indices is not a free variable. -/ pure false else if ctx.majorTypeIndices.size.any fun i => i.any fun j => ctx.majorTypeIndices[i] == ctx.majorTypeIndices[j] then /- An index ocurrs more than once -/ pure false else let lctx ← getLCtx let mctx ← getMCtx pure $ lctx.all fun decl => decl.fvarId == ctx.majorDecl.fvarId || -- decl is the major ctx.majorTypeIndices.any (fun index => decl.fvarId == index.fvarId!) || -- decl is one of the indices mctx.findLocalDeclDependsOn decl (fun fvarId => ctx.majorTypeIndices.all $ fun idx => idx.fvarId! != fvarId) -- or does not depend on any index private def elimAuxIndices (s₁ : GeneralizeIndicesSubgoal) (s₂ : Array CasesSubgoal) : MetaM (Array CasesSubgoal) := let indicesFVarIds := s₁.indicesFVarIds s₂.mapM fun s => do indicesFVarIds.foldlM (init := s) fun s indexFVarId => match s.subst.get indexFVarId with | Expr.fvar indexFVarId' _ => (do let mvarId ← clear s.mvarId indexFVarId'; pure { s with mvarId := mvarId, subst := s.subst.erase indexFVarId }) <|> (pure s) | _ => pure s /- Convert `s` into an array of `CasesSubgoal`, by attaching the corresponding constructor name, and adding the substitution `majorFVarId -> ctor_i us params fields` into each subgoal. -/ private def toCasesSubgoals (s : Array InductionSubgoal) (ctorNames : Array Name) (majorFVarId : FVarId) (us : List Level) (params : Array Expr) : Array CasesSubgoal := s.mapIdx fun i s => let ctorName := ctorNames[i] let ctorApp := mkAppN (mkAppN (mkConst ctorName us) params) s.fields let s := { s with subst := s.subst.insert majorFVarId ctorApp } { ctorName := ctorName, toInductionSubgoal := s } /- Convert heterogeneous equality into a homegeneous one -/ private def heqToEq (mvarId : MVarId) (eqDecl : LocalDecl) : MetaM MVarId := do /- Convert heterogeneous equality into a homegeneous one -/ let prf ← mkEqOfHEq (mkFVar eqDecl.fvarId) let aEqb ← whnf (← inferType prf) let mvarId ← assert mvarId eqDecl.userName aEqb prf clear mvarId eqDecl.fvarId partial def unifyEqs (numEqs : Nat) (mvarId : MVarId) (subst : FVarSubst) : MetaM (Option (MVarId × FVarSubst)) := do if numEqs == 0 then pure (some (mvarId, subst)) else let (eqFVarId, mvarId) ← intro1 mvarId withMVarContext mvarId do let eqDecl ← getLocalDecl eqFVarId if eqDecl.type.isHEq then let mvarId ← heqToEq mvarId eqDecl unifyEqs numEqs mvarId subst else match eqDecl.type.eq? with | none => throwError! "equality expected{indentExpr eqDecl.type}" | some (α, a, b) => if (← isDefEq a b) then /- Skip equality -/ unifyEqs (numEqs - 1) (← clear mvarId eqFVarId) subst else -- Remark: we use `let rec` here because otherwise the compiler would generate an insane amount of code. -- We can remove the `rec` after we fix the eagerly inlining issue in the compiler. let rec substEq (symm : Bool) := do /- TODO: support for acyclicity (e.g., `xs ≠ x :: xs`) -/ let (substNew, mvarId) ← substCore mvarId eqFVarId symm subst unifyEqs (numEqs - 1) mvarId substNew let rec injection (a b : Expr) := do let env ← getEnv if a.isConstructorApp env && b.isConstructorApp env then /- ctor_i ... = ctor_j ... -/ match (← injectionCore mvarId eqFVarId) with | InjectionResultCore.solved => pure none -- this alternative has been solved | InjectionResultCore.subgoal mvarId numEqsNew => unifyEqs (numEqs - 1 + numEqsNew) mvarId subst else let a' ← whnf a let b' ← whnf b if a' != a || b' != b then /- Reduced lhs/rhs of current equality -/ let prf := mkFVar eqFVarId let aEqb' ← mkEq a' b' let mvarId ← assert mvarId eqDecl.userName aEqb' prf let mvarId ← clear mvarId eqFVarId unifyEqs numEqs mvarId subst else throwError! "dependent elimination failed, stuck at auxiliary equation{indentExpr eqDecl.type}" match a, b with | Expr.fvar aFVarId _, Expr.fvar bFVarId _ => /- x = y -/ let aDecl ← getLocalDecl aFVarId let bDecl ← getLocalDecl bFVarId substEq (aDecl.index < bDecl.index) | Expr.fvar .., _ => /- x = t -/ substEq (symm := false) | _, Expr.fvar .. => /- t = x -/ substEq (symm := true) | a, b => injection a b private def unifyCasesEqs (numEqs : Nat) (subgoals : Array CasesSubgoal) : MetaM (Array CasesSubgoal) := subgoals.foldlM (init := #[]) fun subgoals s => do match (← unifyEqs numEqs s.mvarId s.subst) with | none => pure subgoals | some (mvarId, subst) => pure $ subgoals.push { s with mvarId := mvarId, subst := subst, fields := s.fields.map (subst.apply ·) } private def inductionCasesOn (mvarId : MVarId) (majorFVarId : FVarId) (givenNames : Array (List Name)) (useUnusedNames : Bool) (ctx : Context) : MetaM (Array CasesSubgoal) := do withMVarContext mvarId do let majorType ← inferType (mkFVar majorFVarId) let (us, params) ← getInductiveUniverseAndParams majorType let casesOn := mkCasesOnName ctx.inductiveVal.name let ctors := ctx.inductiveVal.ctors.toArray let s ← induction mvarId majorFVarId casesOn givenNames useUnusedNames pure $ toCasesSubgoals s ctors majorFVarId us params def cases (mvarId : MVarId) (majorFVarId : FVarId) (givenNames : Array (List Name) := #[]) (useUnusedNames := false) : MetaM (Array CasesSubgoal) := withMVarContext mvarId do checkNotAssigned mvarId `cases let context? ← mkCasesContext? majorFVarId match context? with | none => throwTacticEx `cases mvarId "not applicable to the given hypothesis" | some ctx => /- Remark: if caller does not need a `FVarSubst` (variable substitution), and `hasIndepIndices ctx` is true, then we can also use the simple case. This is a minor optimization, and we currently do not even allow callers to specify whether they want the `FVarSubst` or not. -/ if ctx.inductiveVal.nindices == 0 then -- Simple case inductionCasesOn mvarId majorFVarId givenNames useUnusedNames ctx else let s₁ ← generalizeIndices mvarId majorFVarId trace[Meta.Tactic.cases]! "after generalizeIndices\n{MessageData.ofGoal s₁.mvarId}" let s₂ ← inductionCasesOn s₁.mvarId s₁.fvarId givenNames useUnusedNames ctx let s₂ ← elimAuxIndices s₁ s₂ unifyCasesEqs s₁.numEqs s₂ end Cases def cases (mvarId : MVarId) (majorFVarId : FVarId) (givenNames : Array (List Name) := #[]) (useUnusedNames := false) : MetaM (Array CasesSubgoal) := Cases.cases mvarId majorFVarId givenNames useUnusedNames builtin_initialize registerTraceClass `Meta.Tactic.cases end Lean.Meta
a22335cc6c7171e2c35dfa0aa7ab76dcc26db9ef
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/sec3.lean
e378680522552bb46a9487581756463eb23f3225
[ "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
111
lean
section parameter A : Type definition tst (a : A) := a set_option pp.universes true #check tst.{1} end
f700da02b68cdf0ac9d5e1e964dc7c8d543f96ec
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/09_Type_Classes.org.16.lean
1e6fe8cfda1b290e5a1c9ed2d52f3324d2694301
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
166
lean
import standard import standard open nat definition step (a b x : ℕ) : ℕ := if x < a ∨ x > b then 0 else 1 set_option pp.implicit true print definition step
21b0c4f81ce1850f12e93db135e672c569c9174e
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/ordmap/ordnode.lean
a12102699cc808c6ca3088add123248a1b988620
[ "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
42,071
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.list.defs import data.nat.psub /-! # Ordered sets This file defines a data structure for ordered sets, supporting a variety of useful operations including insertion and deletion, logarithmic time lookup, set operations, folds, and conversion from lists. The `ordnode α` operations all assume that `α` has the structure of a total preorder, meaning a `≤` operation that is * Transitive: `x ≤ y → y ≤ z → x ≤ z` * Reflexive: `x ≤ x` * Total: `x ≤ y ∨ y ≤ x` For example, in order to use this data structure as a map type, one can store pairs `(k, v)` where `(k, v) ≤ (k', v')` is defined to mean `k ≤ k'` (assuming that the key values are linearly ordered). Two values `x,y` are equivalent if `x ≤ y` and `y ≤ x`. An `ordnode α` maintains the invariant that it never stores two equivalent nodes; the insertion operation comes with two variants depending on whether you want to keep the old value or the new value in case you insert a value that is equivalent to one in the set. The operations in this file are not verified, in the sense that they provide "raw operations" that work for programming purposes but the invariants are not explicitly in the structure. See `ordset` for a verified version of this data structure. ## Main definitions * `ordnode α`: A set of values of type `α` ## Implementation notes Based on weight balanced trees: * Stephen Adams, "Efficient sets: a balancing act", Journal of Functional Programming 3(4):553-562, October 1993, <http://www.swiss.ai.mit.edu/~adams/BB/>. * J. Nievergelt and E.M. Reingold, "Binary search trees of bounded balance", SIAM journal of computing 2(1), March 1973. Ported from Haskell's `Data.Set`. ## Tags ordered map, ordered set, data structure -/ universes u /-- An `ordnode α` is a finite set of values, represented as a tree. The operations on this type maintain that the tree is balanced and correctly stores subtree sizes at each level. -/ inductive ordnode (α : Type u) : Type u | nil {} : ordnode | node (size : ℕ) (l : ordnode) (x : α) (r : ordnode) : ordnode namespace ordnode variable {α : Type u} instance : has_emptyc (ordnode α) := ⟨nil⟩ instance : inhabited (ordnode α) := ⟨nil⟩ /-- **Internal use only** The maximal relative difference between the sizes of two trees, it corresponds with the `w` in Adams' paper. According to the Haskell comment, only `(delta, ratio)` settings of `(3, 2)` and `(4, 2)` will work, and the proofs in `ordset.lean` assume `delta := 3` and `ratio := 2`. -/ @[inline] def delta := 3 /-- **Internal use only** The ratio between an outer and inner sibling of the heavier subtree in an unbalanced setting. It determines whether a double or single rotation should be performed to restore balance. It is corresponds with the inverse of `α` in Adam's article. -/ @[inline] def ratio := 2 /-- O(1). Construct a singleton set containing value `a`. singleton 3 = {3} -/ @[inline] protected def singleton (a : α) : ordnode α := node 1 nil a nil local prefix `ι`:max := ordnode.singleton instance : has_singleton α (ordnode α) := ⟨ordnode.singleton⟩ /-- O(1). Get the size of the set. size {2, 1, 1, 4} = 3 -/ @[inline, simp] def size : ordnode α → ℕ | nil := 0 | (node sz _ _ _) := sz /-- O(1). Is the set empty? empty ∅ = tt empty {1, 2, 3} = ff -/ @[inline] def empty : ordnode α → bool | nil := tt | (node _ _ _ _) := ff /-- **Internal use only**, because it violates the BST property on the original order. O(n). The dual of a tree is a tree with its left and right sides reversed throughout. The dual of a valid BST is valid under the dual order. This is convenient for exploiting symmetries in the algorithms. -/ @[simp] def dual : ordnode α → ordnode α | nil := nil | (node s l x r) := node s (dual r) x (dual l) /-- **Internal use only** O(1). Construct a node with the correct size information, without rebalancing. -/ @[inline, reducible] def node' (l : ordnode α) (x : α) (r : ordnode α) : ordnode α := node (size l + size r + 1) l x r /-- Basic pretty printing for `ordnode α` that shows the structure of the tree. repr {3, 1, 2, 4} = ((∅ 1 ∅) 2 ((∅ 3 ∅) 4 ∅)) -/ def repr {α} [has_repr α] : ordnode α → string | nil := "∅" | (node _ l x r) := "(" ++ repr l ++ " " ++ _root_.repr x ++ " " ++ repr r ++ ")" instance {α} [has_repr α] : has_repr (ordnode α) := ⟨repr⟩ /-- **Internal use only** O(1). Rebalance a tree which was previously balanced but has had its left side grow by 1, or its right side shrink by 1. -/ -- Note: The function has been written with tactics to avoid extra junk def balance_l (l : ordnode α) (x : α) (r : ordnode α) : ordnode α := by clean begin cases id r with rs, { cases id l with ls ll lx lr, { exact ι x }, { cases id ll with lls, { cases lr with _ _ lrx, { exact node 2 l x nil }, { exact node 3 (ι lx) lrx (ι x) } }, { cases id lr with lrs lrl lrx lrr, { exact node 3 ll lx (ι x) }, { exact if lrs < ratio * lls then node (ls+1) ll lx (node (lrs+1) lr x nil) else node (ls+1) (node (lls + size lrl + 1) ll lx lrl) lrx (node (size lrr + 1) lrr x nil) } } } }, { cases id l with ls ll lx lr, { exact node (rs+1) nil x r }, { refine if ls > delta * rs then _ else node (ls + rs + 1) l x r, cases id ll with lls, {exact nil /-should not happen-/}, cases id lr with lrs lrl lrx lrr, {exact nil /-should not happen-/}, exact if lrs < ratio * lls then node (ls + rs + 1) ll lx (node (rs + lrs + 1) lr x r) else node (ls + rs + 1) (node (lls + size lrl + 1) ll lx lrl) lrx (node (size lrr + rs + 1) lrr x r) } } end /-- **Internal use only** O(1). Rebalance a tree which was previously balanced but has had its right side grow by 1, or its left side shrink by 1. -/ def balance_r (l : ordnode α) (x : α) (r : ordnode α) : ordnode α := by clean begin cases id l with ls, { cases id r with rs rl rx rr, { exact ι x }, { cases id rr with rrs, { cases rl with _ _ rlx, { exact node 2 nil x r }, { exact node 3 (ι x) rlx (ι rx) } }, { cases id rl with rls rll rlx rlr, { exact node 3 (ι x) rx rr }, { exact if rls < ratio * rrs then node (rs+1) (node (rls+1) nil x rl) rx rr else node (rs+1) (node (size rll + 1) nil x rll) rlx (node (size rlr + rrs + 1) rlr rx rr) } } } }, { cases id r with rs rl rx rr, { exact node (ls+1) l x nil }, { refine if rs > delta * ls then _ else node (ls + rs + 1) l x r, cases id rr with rrs, {exact nil /-should not happen-/}, cases id rl with rls rll rlx rlr, {exact nil /-should not happen-/}, exact if rls < ratio * rrs then node (ls + rs + 1) (node (ls + rls + 1) l x rl) rx rr else node (ls + rs + 1) (node (ls + size rll + 1) l x rll) rlx (node (size rlr + rrs + 1) rlr rx rr) } } end /-- **Internal use only** O(1). Rebalance a tree which was previously balanced but has had one side change by at most 1. -/ def balance (l : ordnode α) (x : α) (r : ordnode α) : ordnode α := by clean begin cases id l with ls ll lx lr, { cases id r with rs rl rx rr, { exact ι x }, { cases id rl with rls rll rlx rlr, { cases id rr, { exact node 2 nil x r }, { exact node 3 (ι x) rx rr } }, { cases id rr with rrs, { exact node 3 (ι x) rlx (ι rx) }, { exact if rls < ratio * rrs then node (rs+1) (node (rls+1) nil x rl) rx rr else node (rs+1) (node (size rll + 1) nil x rll) rlx (node (size rlr + rrs + 1) rlr rx rr) } } } }, { cases id r with rs rl rx rr, { cases id ll with lls, { cases lr with _ _ lrx, { exact node 2 l x nil }, { exact node 3 (ι lx) lrx (ι x) } }, { cases id lr with lrs lrl lrx lrr, { exact node 3 ll lx (ι x) }, { exact if lrs < ratio * lls then node (ls+1) ll lx (node (lrs+1) lr x nil) else node (ls+1) (node (lls + size lrl + 1) ll lx lrl) lrx (node (size lrr + 1) lrr x nil) } } }, { refine if delta * ls < rs then _ else if delta * rs < ls then _ else node (ls+rs+1) l x r, { cases id rl with rls rll rlx rlr, {exact nil /-should not happen-/}, cases id rr with rrs, {exact nil /-should not happen-/}, exact if rls < ratio * rrs then node (ls+rs+1) (node (ls+rls+1) l x rl) rx rr else node (ls+rs+1) (node (ls + size rll + 1) l x rll) rlx (node (size rlr + rrs + 1) rlr rx rr) }, { cases id ll with lls, {exact nil /-should not happen-/}, cases id lr with lrs lrl lrx lrr, {exact nil /-should not happen-/}, exact if lrs < ratio * lls then node (ls+rs+1) ll lx (node (lrs+rs+1) lr x r) else node (ls+rs+1) (node (lls + size lrl + 1) ll lx lrl) lrx (node (size lrr + rs + 1) lrr x r) } } } end /-- O(n). Does every element of the map satisfy property `P`? all (λ x, x < 5) {1, 2, 3} = true all (λ x, x < 5) {1, 2, 3, 5} = false -/ def all (P : α → Prop) : ordnode α → Prop | nil := true | (node _ l x r) := all l ∧ P x ∧ all r instance all.decidable {P : α → Prop} [decidable_pred P] (t) : decidable (all P t) := by induction t; dunfold all; resetI; apply_instance /-- O(n). Does any element of the map satisfy property `P`? any (λ x, x < 2) {1, 2, 3} = true any (λ x, x < 2) {2, 3, 5} = false -/ def any (P : α → Prop) : ordnode α → Prop | nil := false | (node _ l x r) := any l ∨ P x ∨ any r instance any.decidable {P : α → Prop} [decidable_pred P] (t) : decidable (any P t) := by induction t; dunfold any; resetI; apply_instance /-- O(n). Exact membership in the set. This is useful primarily for stating correctness properties; use `∈` for a version that actually uses the BST property of the tree. emem 2 {1, 2, 3} = true emem 4 {1, 2, 3} = false -/ def emem (x : α) : ordnode α → Prop := any (eq x) instance emem.decidable [decidable_eq α] (x : α) : ∀ t, decidable (emem x t) := any.decidable /-- O(n). Approximate membership in the set, that is, whether some element in the set is equivalent to this one in the preorder. This is useful primarily for stating correctness properties; use `∈` for a version that actually uses the BST property of the tree. amem 2 {1, 2, 3} = true amem 4 {1, 2, 3} = false To see the difference with `emem`, we need a preorder that is not a partial order. For example, suppose we compare pairs of numbers using only their first coordinate. Then: emem (0, 1) {(0, 0), (1, 2)} = false amem (0, 1) {(0, 0), (1, 2)} = true (0, 1) ∈ {(0, 0), (1, 2)} = true The `∈` relation is equivalent to `amem` as long as the `ordnode` is well formed, and should always be used instead of `amem`. -/ def amem [has_le α] (x : α) : ordnode α → Prop := any (λ y, x ≤ y ∧ y ≤ x) instance amem.decidable [has_le α] [@decidable_rel α (≤)] (x : α) : ∀ t, decidable (amem x t) := any.decidable /-- O(log n). Return the minimum element of the tree, or the provided default value. find_min' 37 {1, 2, 3} = 1 find_min' 37 ∅ = 37 -/ def find_min' : ordnode α → α → α | nil x := x | (node _ l x r) _ := find_min' l x /-- O(log n). Return the minimum element of the tree, if it exists. find_min {1, 2, 3} = some 1 find_min ∅ = none -/ def find_min : ordnode α → option α | nil := none | (node _ l x r) := some (find_min' l x) /-- O(log n). Return the maximum element of the tree, or the provided default value. find_max' 37 {1, 2, 3} = 3 find_max' 37 ∅ = 37 -/ def find_max' : α → ordnode α → α | x nil := x | _ (node _ l x r) := find_max' x r /-- O(log n). Return the maximum element of the tree, if it exists. find_max {1, 2, 3} = some 3 find_max ∅ = none -/ def find_max : ordnode α → option α | nil := none | (node _ l x r) := some (find_max' x r) /-- O(log n). Remove the minimum element from the tree, or do nothing if it is already empty. erase_min {1, 2, 3} = {2, 3} erase_min ∅ = ∅ -/ def erase_min : ordnode α → ordnode α | nil := nil | (node _ nil x r) := r | (node _ l x r) := balance_r (erase_min l) x r /-- O(log n). Remove the maximum element from the tree, or do nothing if it is already empty. erase_max {1, 2, 3} = {1, 2} erase_max ∅ = ∅ -/ def erase_max : ordnode α → ordnode α | nil := nil | (node _ l x nil) := l | (node _ l x r) := balance_l l x (erase_max r) /-- **Internal use only**, because it requires a balancing constraint on the inputs. O(log n). Extract and remove the minimum element from a nonempty tree. -/ def split_min' : ordnode α → α → ordnode α → α × ordnode α | nil x r := (x, r) | (node _ ll lx lr) x r := let (xm, l') := split_min' ll lx lr in (xm, balance_r l' x r) /-- O(log n). Extract and remove the minimum element from the tree, if it exists. split_min {1, 2, 3} = some (1, {2, 3}) split_min ∅ = none -/ def split_min : ordnode α → option (α × ordnode α) | nil := none | (node _ l x r) := split_min' l x r /-- **Internal use only**, because it requires a balancing constraint on the inputs. O(log n). Extract and remove the maximum element from a nonempty tree. -/ def split_max' : ordnode α → α → ordnode α → ordnode α × α | l x nil := (l, x) | l x (node _ rl rx rr) := let (r', xm) := split_max' rl rx rr in (balance_l l x r', xm) /-- O(log n). Extract and remove the maximum element from the tree, if it exists. split_max {1, 2, 3} = some ({1, 2}, 3) split_max ∅ = none -/ def split_max : ordnode α → option (ordnode α × α) | nil := none | (node _ x l r) := split_max' x l r /-- **Internal use only** O(log(m+n)). Concatenate two trees that are balanced and ordered with respect to each other. -/ def glue : ordnode α → ordnode α → ordnode α | nil r := r | l@(node _ _ _ _) nil := l | l@(node sl ll lx lr) r@(node sr rl rx rr) := if sl > sr then let (l', m) := split_max' ll lx lr in balance_r l' m r else let (m, r') := split_min' rl rx rr in balance_l l m r' /-- O(log(m+n)). Concatenate two trees that are ordered with respect to each other. merge {1, 2} {3, 4} = {1, 2, 3, 4} merge {3, 4} {1, 2} = precondition violation -/ def merge (l : ordnode α) : ordnode α → ordnode α := ordnode.rec_on l (λ r, r) $ λ ls ll lx lr IHll IHlr r, ordnode.rec_on r (node ls ll lx lr) $ λ rs rl rx rr IHrl IHrr, if delta * ls < rs then balance_l IHrl rx rr else if delta * rs < ls then balance_r ll lx (IHlr $ node rs rl rx rr) else glue (node ls ll lx lr) (node rs rl rx rr) /-- O(log n). Insert an element above all the others, without any comparisons. (Assumes that the element is in fact above all the others). insert_max {1, 2} 4 = {1, 2, 4} insert_max {1, 2} 0 = precondition violation -/ def insert_max : ordnode α → α → ordnode α | nil x := ι x | (node _ l y r) x := balance_r l y (insert_max r x) /-- O(log n). Insert an element below all the others, without any comparisons. (Assumes that the element is in fact below all the others). insert_min {1, 2} 0 = {0, 1, 2} insert_min {1, 2} 4 = precondition violation -/ def insert_min (x : α) : ordnode α → ordnode α | nil := ι x | (node _ l y r) := balance_r (insert_min l) y r /-- O(log(m+n)). Build a tree from an element between two trees, without any assumption on the relative sizes. link {1, 2} 4 {5, 6} = {1, 2, 4, 5, 6} link {1, 3} 2 {5} = precondition violation -/ def link (l : ordnode α) (x : α) : ordnode α → ordnode α := ordnode.rec_on l (insert_min x) $ λ ls ll lx lr IHll IHlr r, ordnode.rec_on r (insert_max l x) $ λ rs rl rx rr IHrl IHrr, if delta * ls < rs then balance_l IHrl rx rr else if delta * rs < ls then balance_r ll lx (IHlr r) else node' l x r /-- O(n). Filter the elements of a tree satisfying a predicate. filter (λ x, x < 3) {1, 2, 4} = {1, 2} filter (λ x, x > 5) {1, 2, 4} = ∅ -/ def filter (p : α → Prop) [decidable_pred p] : ordnode α → ordnode α | nil := nil | (node _ l x r) := if p x then link (filter l) x (filter r) else merge (filter l) (filter r) /-- O(n). Split the elements of a tree into those satisfying, and not satisfying, a predicate. partition (λ x, x < 3) {1, 2, 4} = ({1, 2}, {3}) -/ def partition (p : α → Prop) [decidable_pred p] : ordnode α → ordnode α × ordnode α | nil := (nil, nil) | (node _ l x r) := let (l₁, l₂) := partition l, (r₁, r₂) := partition r in if p x then (link l₁ x r₁, merge l₂ r₂) else (merge l₁ r₁, link l₂ x r₂) /-- O(n). Map a function across a tree, without changing the structure. Only valid when the function is strictly monotonic, i.e. `x < y → f x < f y`. partition (λ x, x + 2) {1, 2, 4} = {2, 3, 6} partition (λ x : ℕ, x - 2) {1, 2, 4} = precondition violation -/ def map {β} (f : α → β) : ordnode α → ordnode β | nil := nil | (node s l x r) := node s (map l) (f x) (map r) /-- O(n). Fold a function across the structure of a tree. fold z f {1, 2, 4} = f (f z 1 z) 2 (f z 4 z) The exact structure of function applications depends on the tree and so is unspecified. -/ def fold {β} (z : β) (f : β → α → β → β) : ordnode α → β | nil := z | (node _ l x r) := f (fold l) x (fold r) /-- O(n). Fold a function from left to right (in increasing order) across the tree. foldl f z {1, 2, 4} = f (f (f z 1) 2) 4 -/ def foldl {β} (f : β → α → β) : β → ordnode α → β | z nil := z | z (node _ l x r) := foldl (f (foldl z l) x) r /-- O(n). Fold a function from right to left (in decreasing order) across the tree. foldl f {1, 2, 4} z = f 1 (f 2 (f 4 z)) -/ def foldr {β} (f : α → β → β) : ordnode α → β → β | nil z := z | (node _ l x r) z := foldr l (f x (foldr r z)) /-- O(n). Build a list of elements in ascending order from the tree. to_list {1, 2, 4} = [1, 2, 4] to_list {2, 1, 1, 4} = [1, 2, 4] -/ def to_list (t : ordnode α) : list α := foldr list.cons t [] /-- O(n). Build a list of elements in descending order from the tree. to_rev_list {1, 2, 4} = [4, 2, 1] to_rev_list {2, 1, 1, 4} = [4, 2, 1] -/ def to_rev_list (t : ordnode α) : list α := foldl (flip list.cons) [] t instance [has_to_string α] : has_to_string (ordnode α) := ⟨λ t, "{" ++ string.intercalate ", " (t.to_list.map to_string) ++ "}"⟩ meta instance [has_to_format α] : has_to_format (ordnode α) := ⟨λ t, "{" ++ format.intercalate ", " (t.to_list.map to_fmt) ++ "}"⟩ /-- O(n). True if the trees have the same elements, ignoring structural differences. equiv {1, 2, 4} {2, 1, 1, 4} = true equiv {1, 2, 4} {1, 2, 3} = false -/ def equiv (t₁ t₂ : ordnode α) : Prop := t₁.size = t₂.size ∧ t₁.to_list = t₂.to_list instance [decidable_eq α] : decidable_rel (@equiv α) := λ t₁ t₂, and.decidable /-- O(2^n). Constructs the powerset of a given set, that is, the set of all subsets. powerset {1, 2, 3} = {∅, {1}, {2}, {3}, {1,2}, {1,3}, {2,3}, {1,2,3}} -/ def powerset (t : ordnode α) : ordnode (ordnode α) := insert_min nil $ foldr (λ x ts, glue (insert_min (ι x) (map (insert_min x) ts)) ts) t nil /-- O(m*n). The cartesian product of two sets: `(a, b) ∈ s.prod t` iff `a ∈ s` and `b ∈ t`. prod {1, 2} {2, 3} = {(1, 2), (1, 3), (2, 2), (2, 3)} -/ protected def prod {β} (t₁ : ordnode α) (t₂ : ordnode β) : ordnode (α × β) := fold nil (λ s₁ a s₂, merge s₁ $ merge (map (prod.mk a) t₂) s₂) t₁ /-- O(m+n). Build a set on the disjoint union by combining sets on the factors. `inl a ∈ s.copair t` iff `a ∈ s`, and `inr b ∈ s.copair t` iff `b ∈ t`. copair {1, 2} {2, 3} = {inl 1, inl 2, inr 2, inr 3} -/ protected def copair {β} (t₁ : ordnode α) (t₂ : ordnode β) : ordnode (α ⊕ β) := merge (map sum.inl t₁) (map sum.inr t₂) /-- O(n). Map a partial function across a set. The result depends on a proof that the function is defined on all members of the set. pmap (fin.mk : ∀ n, n < 4 → fin 4) {1, 2} H = {(1 : fin 4), (2 : fin 4)} -/ def pmap {P : α → Prop} {β} (f : ∀ a, P a → β) : ∀ t : ordnode α, all P t → ordnode β | nil _ := nil | (node s l x r) ⟨hl, hx, hr⟩ := node s (pmap l hl) (f x hx) (pmap r hr) /-- O(n). "Attach" the information that every element of `t` satisfies property P to these elements inside the set, producing a set in the subtype. attach' (λ x, x < 4) {1, 2} H = ({1, 2} : ordnode {x // x<4}) -/ def attach' {P : α → Prop} : ∀ t, all P t → ordnode {a // P a} := pmap subtype.mk /-- O(log n). Get the `i`th element of the set, by its index from left to right. nth {a, b, c, d} 2 = some c nth {a, b, c, d} 5 = none -/ def nth : ordnode α → ℕ → option α | nil i := none | (node _ l x r) i := match nat.psub' i (size l) with | none := nth l i | some 0 := some x | some (j + 1) := nth r j end /-- O(log n). Remove the `i`th element of the set, by its index from left to right. remove_nth {a, b, c, d} 2 = {a, b, d} remove_nth {a, b, c, d} 5 = {a, b, c, d} -/ def remove_nth : ordnode α → ℕ → ordnode α | nil i := nil | (node _ l x r) i := match nat.psub' i (size l) with | none := balance_r (remove_nth l i) x r | some 0 := glue l r | some (j + 1) := balance_l l x (remove_nth r j) end /-- Auxiliary definition for `take`. (Can also be used in lieu of `take` if you know the index is within the range of the data structure.) take_aux {a, b, c, d} 2 = {a, b} take_aux {a, b, c, d} 5 = {a, b, c, d} -/ def take_aux : ordnode α → ℕ → ordnode α | nil i := nil | (node _ l x r) i := if i = 0 then nil else match nat.psub' i (size l) with | none := take_aux l i | some 0 := l | some (j + 1) := link l x (take_aux r j) end /-- O(log n). Get the first `i` elements of the set, counted from the left. take 2 {a, b, c, d} = {a, b} take 5 {a, b, c, d} = {a, b, c, d} -/ def take (i : ℕ) (t : ordnode α) : ordnode α := if size t ≤ i then t else take_aux t i /-- Auxiliary definition for `drop`. (Can also be used in lieu of `drop` if you know the index is within the range of the data structure.) drop_aux {a, b, c, d} 2 = {c, d} drop_aux {a, b, c, d} 5 = ∅ -/ def drop_aux : ordnode α → ℕ → ordnode α | nil i := nil | t@(node _ l x r) i := if i = 0 then t else match nat.psub' i (size l) with | none := link (drop_aux l i) x r | some 0 := insert_min x r | some (j + 1) := drop_aux r j end /-- O(log n). Remove the first `i` elements of the set, counted from the left. drop 2 {a, b, c, d} = {c, d} drop 5 {a, b, c, d} = ∅ -/ def drop (i : ℕ) (t : ordnode α) : ordnode α := if size t ≤ i then nil else drop_aux t i /-- Auxiliary definition for `split_at`. (Can also be used in lieu of `split_at` if you know the index is within the range of the data structure.) split_at_aux {a, b, c, d} 2 = ({a, b}, {c, d}) split_at_aux {a, b, c, d} 5 = ({a, b, c, d}, ∅) -/ def split_at_aux : ordnode α → ℕ → ordnode α × ordnode α | nil i := (nil, nil) | t@(node _ l x r) i := if i = 0 then (nil, t) else match nat.psub' i (size l) with | none := let (l₁, l₂) := split_at_aux l i in (l₁, link l₂ x r) | some 0 := (glue l r, insert_min x r) | some (j + 1) := let (r₁, r₂) := split_at_aux r j in (link l x r₁, r₂) end /-- O(log n). Split a set at the `i`th element, getting the first `i` and everything else. split_at 2 {a, b, c, d} = ({a, b}, {c, d}) split_at 5 {a, b, c, d} = ({a, b, c, d}, ∅) -/ def split_at (i : ℕ) (t : ordnode α) : ordnode α × ordnode α := if size t ≤ i then (t, nil) else split_at_aux t i /-- O(log n). Get an initial segment of the set that satisfies the predicate `p`. `p` is required to be antitone, that is, `x < y → p y → p x`. take_while (λ x, x < 4) {1, 2, 3, 4, 5} = {1, 2, 3} take_while (λ x, x > 4) {1, 2, 3, 4, 5} = precondition violation -/ def take_while (p : α → Prop) [decidable_pred p] : ordnode α → ordnode α | nil := nil | (node _ l x r) := if p x then link l x (take_while r) else take_while l /-- O(log n). Remove an initial segment of the set that satisfies the predicate `p`. `p` is required to be antitone, that is, `x < y → p y → p x`. drop_while (λ x, x < 4) {1, 2, 3, 4, 5} = {4, 5} drop_while (λ x, x > 4) {1, 2, 3, 4, 5} = precondition violation -/ def drop_while (p : α → Prop) [decidable_pred p] : ordnode α → ordnode α | nil := nil | (node _ l x r) := if p x then drop_while r else link (drop_while l) x r /-- O(log n). Split the set into those satisfying and not satisfying the predicate `p`. `p` is required to be antitone, that is, `x < y → p y → p x`. span (λ x, x < 4) {1, 2, 3, 4, 5} = ({1, 2, 3}, {4, 5}) span (λ x, x > 4) {1, 2, 3, 4, 5} = precondition violation -/ def span (p : α → Prop) [decidable_pred p] : ordnode α → ordnode α × ordnode α | nil := (nil, nil) | (node _ l x r) := if p x then let (r₁, r₂) := span r in (link l x r₁, r₂) else let (l₁, l₂) := span l in (l₁, link l₂ x r) /-- Auxiliary definition for `of_asc_list`. **Note:** This function is defined by well founded recursion, so it will probably not compute in the kernel, meaning that you probably can't prove things like `of_asc_list [1, 2, 3] = {1, 2, 3}` by `rfl`. This implementation is optimized for VM evaluation. -/ def of_asc_list_aux₁ : ∀ l : list α, ℕ → ordnode α × {l' : list α // l'.length ≤ l.length} | [] := λ s, (nil, ⟨[], le_refl _⟩) | (x :: xs) := λ s, if s = 1 then (ι x, ⟨xs, nat.le_succ _⟩) else have _, from nat.lt_succ_self xs.length, match of_asc_list_aux₁ xs (s.shiftl 1) with | (t, ⟨[], h⟩) := (t, ⟨[], nat.zero_le _⟩) | (l, ⟨y :: ys, h⟩) := have _, from nat.le_succ_of_le h, let (r, ⟨zs, h'⟩) := of_asc_list_aux₁ ys (s.shiftl 1) in (link l y r, ⟨zs, le_trans h' (le_of_lt this)⟩) end using_well_founded { rel_tac := λ _ _, `[exact ⟨_, measure_wf list.length⟩], dec_tac := `[assumption] } /-- Auxiliary definition for `of_asc_list`. -/ def of_asc_list_aux₂ : list α → ordnode α → ℕ → ordnode α | [] := λ t s, t | (x :: xs) := λ l s, have _, from nat.lt_succ_self xs.length, match of_asc_list_aux₁ xs s with | (r, ⟨ys, h⟩) := have _, from nat.lt_succ_of_le h, of_asc_list_aux₂ ys (link l x r) (s.shiftl 1) end using_well_founded { rel_tac := λ _ _, `[exact ⟨_, measure_wf list.length⟩], dec_tac := `[assumption] } /-- O(n). Build a set from a list which is already sorted. Performs no comparisons. of_asc_list [1, 2, 3] = {1, 2, 3} of_asc_list [3, 2, 1] = precondition violation -/ def of_asc_list : list α → ordnode α | [] := nil | (x :: xs) := of_asc_list_aux₂ xs (ι x) 1 section variables [has_le α] [@decidable_rel α (≤)] /-- O(log n). Does the set (approximately) contain the element `x`? That is, is there an element that is equivalent to `x` in the order? 1 ∈ {1, 2, 3} = true 4 ∈ {1, 2, 3} = false Using a preorder on `ℕ × ℕ` that only compares the first coordinate: (1, 1) ∈ {(0, 1), (1, 2)} = true (3, 1) ∈ {(0, 1), (1, 2)} = false -/ def mem (x : α) : ordnode α → bool | nil := ff | (node _ l y r) := match cmp_le x y with | ordering.lt := mem l | ordering.eq := tt | ordering.gt := mem r end /-- O(log n). Retrieve an element in the set that is equivalent to `x` in the order, if it exists. find 1 {1, 2, 3} = some 1 find 4 {1, 2, 3} = none Using a preorder on `ℕ × ℕ` that only compares the first coordinate: find (1, 1) {(0, 1), (1, 2)} = some (1, 2) find (3, 1) {(0, 1), (1, 2)} = none -/ def find (x : α) : ordnode α → option α | nil := none | (node _ l y r) := match cmp_le x y with | ordering.lt := find l | ordering.eq := some y | ordering.gt := find r end instance : has_mem α (ordnode α) := ⟨λ x t, t.mem x⟩ instance mem.decidable (x : α) (t : ordnode α) : decidable (x ∈ t) := bool.decidable_eq _ _ /-- O(log n). Insert an element into the set, preserving balance and the BST property. If an equivalent element is already in the set, the function `f` is used to generate the element to insert (being passed the current value in the set). insert_with f 0 {1, 2, 3} = {0, 1, 2, 3} insert_with f 1 {1, 2, 3} = {f 1, 2, 3} Using a preorder on `ℕ × ℕ` that only compares the first coordinate: insert_with f (1, 1) {(0, 1), (1, 2)} = {(0, 1), f (1, 2)} insert_with f (3, 1) {(0, 1), (1, 2)} = {(0, 1), (1, 2), (3, 1)} -/ def insert_with (f : α → α) (x : α) : ordnode α → ordnode α | nil := ι x | t@(node sz l y r) := match cmp_le x y with | ordering.lt := balance_l (insert_with l) y r | ordering.eq := node sz l (f y) r | ordering.gt := balance_r l y (insert_with r) end /-- O(log n). Modify an element in the set with the given function, doing nothing if the key is not found. Note that the element returned by `f` must be equivalent to `x`. adjust_with f 0 {1, 2, 3} = {1, 2, 3} adjust_with f 1 {1, 2, 3} = {f 1, 2, 3} Using a preorder on `ℕ × ℕ` that only compares the first coordinate: adjust_with f (1, 1) {(0, 1), (1, 2)} = {(0, 1), f (1, 2)} adjust_with f (3, 1) {(0, 1), (1, 2)} = {(0, 1), (1, 2)} -/ def adjust_with (f : α → α) (x : α) : ordnode α → ordnode α | nil := nil | t@(node sz l y r) := match cmp_le x y with | ordering.lt := node sz (adjust_with l) y r | ordering.eq := node sz l (f y) r | ordering.gt := node sz l y (adjust_with r) end /-- O(log n). Modify an element in the set with the given function, doing nothing if the key is not found. Note that the element returned by `f` must be equivalent to `x`. update_with f 0 {1, 2, 3} = {1, 2, 3} update_with f 1 {1, 2, 3} = {2, 3} if f 1 = none = {a, 2, 3} if f 1 = some a -/ def update_with (f : α → option α) (x : α) : ordnode α → ordnode α | nil := nil | t@(node sz l y r) := match cmp_le x y with | ordering.lt := balance_r (update_with l) y r | ordering.eq := match f y with | none := glue l r | some a := node sz l a r end | ordering.gt := balance_l l y (update_with r) end /-- O(log n). Modify an element in the set with the given function, doing nothing if the key is not found. Note that the element returned by `f` must be equivalent to `x`. alter f 0 {1, 2, 3} = {1, 2, 3} if f none = none = {a, 1, 2, 3} if f none = some a alter f 1 {1, 2, 3} = {2, 3} if f 1 = none = {a, 2, 3} if f 1 = some a -/ def alter (f : option α → option α) (x : α) : ordnode α → ordnode α | nil := option.rec_on (f none) nil ordnode.singleton | t@(node sz l y r) := match cmp_le x y with | ordering.lt := balance (alter l) y r | ordering.eq := match f (some y) with | none := glue l r | some a := node sz l a r end | ordering.gt := balance l y (alter r) end /-- O(log n). Insert an element into the set, preserving balance and the BST property. If an equivalent element is already in the set, this replaces it. insert 1 {1, 2, 3} = {1, 2, 3} insert 4 {1, 2, 3} = {1, 2, 3, 4} Using a preorder on `ℕ × ℕ` that only compares the first coordinate: insert (1, 1) {(0, 1), (1, 2)} = {(0, 1), (1, 1)} insert (3, 1) {(0, 1), (1, 2)} = {(0, 1), (1, 2), (3, 1)} -/ protected def insert (x : α) : ordnode α → ordnode α | nil := ι x | (node sz l y r) := match cmp_le x y with | ordering.lt := balance_l (insert l) y r | ordering.eq := node sz l x r | ordering.gt := balance_r l y (insert r) end instance : has_insert α (ordnode α) := ⟨ordnode.insert⟩ /-- O(log n). Insert an element into the set, preserving balance and the BST property. If an equivalent element is already in the set, the set is returned as is. insert' 1 {1, 2, 3} = {1, 2, 3} insert' 4 {1, 2, 3} = {1, 2, 3, 4} Using a preorder on `ℕ × ℕ` that only compares the first coordinate: insert' (1, 1) {(0, 1), (1, 2)} = {(0, 1), (1, 2)} insert' (3, 1) {(0, 1), (1, 2)} = {(0, 1), (1, 2), (3, 1)} -/ def insert' (x : α) : ordnode α → ordnode α | nil := ι x | t@(node sz l y r) := match cmp_le x y with | ordering.lt := balance_l (insert' l) y r | ordering.eq := t | ordering.gt := balance_r l y (insert' r) end /-- O(log n). Split the tree into those smaller than `x` and those greater than it. If an element equivalent to `x` is in the set, it is discarded. split 2 {1, 2, 4} = ({1}, {4}) split 3 {1, 2, 4} = ({1, 2}, {4}) split 4 {1, 2, 4} = ({1, 2}, ∅) Using a preorder on `ℕ × ℕ` that only compares the first coordinate: split (1, 1) {(0, 1), (1, 2)} = ({(0, 1)}, ∅) split (3, 1) {(0, 1), (1, 2)} = ({(0, 1), (1, 2)}, ∅) -/ def split (x : α) : ordnode α → ordnode α × ordnode α | nil := (nil, nil) | (node sz l y r) := match cmp_le x y with | ordering.lt := let (lt, gt) := split l in (lt, link gt y r) | ordering.eq := (l, r) | ordering.gt := let (lt, gt) := split r in (link l y lt, gt) end /-- O(log n). Split the tree into those smaller than `x` and those greater than it, plus an element equivalent to `x`, if it exists. split 2 {1, 2, 4} = ({1}, some 2, {4}) split 3 {1, 2, 4} = ({1, 2}, none, {4}) split 4 {1, 2, 4} = ({1, 2}, some 4, ∅) Using a preorder on `ℕ × ℕ` that only compares the first coordinate: split (1, 1) {(0, 1), (1, 2)} = ({(0, 1)}, some (1, 2), ∅) split (3, 1) {(0, 1), (1, 2)} = ({(0, 1), (1, 2)}, none, ∅) -/ def split3 (x : α) : ordnode α → ordnode α × option α × ordnode α | nil := (nil, none, nil) | (node sz l y r) := match cmp_le x y with | ordering.lt := let (lt, f, gt) := split3 l in (lt, f, link gt y r) | ordering.eq := (l, some y, r) | ordering.gt := let (lt, f, gt) := split3 r in (link l y lt, f, gt) end /-- O(log n). Remove an element from the set equivalent to `x`. Does nothing if there is no such element. erase 1 {1, 2, 3} = {2, 3} erase 4 {1, 2, 3} = {1, 2, 3} Using a preorder on `ℕ × ℕ` that only compares the first coordinate: erase (1, 1) {(0, 1), (1, 2)} = {(0, 1)} erase (3, 1) {(0, 1), (1, 2)} = {(0, 1), (1, 2)} -/ def erase (x : α) : ordnode α → ordnode α | nil := nil | t@(node sz l y r) := match cmp_le x y with | ordering.lt := balance_r (erase l) y r | ordering.eq := glue l r | ordering.gt := balance_l l y (erase r) end /-- Auxiliary definition for `find_lt`. -/ def find_lt_aux (x : α) : ordnode α → α → α | nil best := best | (node _ l y r) best := if x ≤ y then find_lt_aux l best else find_lt_aux r y /-- O(log n). Get the largest element in the tree that is `< x`. find_lt 2 {1, 2, 4} = some 1 find_lt 3 {1, 2, 4} = some 2 find_lt 0 {1, 2, 4} = none -/ def find_lt (x : α) : ordnode α → option α | nil := none | (node _ l y r) := if x ≤ y then find_lt l else some (find_lt_aux x r y) /-- Auxiliary definition for `find_gt`. -/ def find_gt_aux (x : α) : ordnode α → α → α | nil best := best | (node _ l y r) best := if y ≤ x then find_gt_aux r best else find_gt_aux l y /-- O(log n). Get the smallest element in the tree that is `> x`. find_lt 2 {1, 2, 4} = some 4 find_lt 3 {1, 2, 4} = some 4 find_lt 4 {1, 2, 4} = none -/ def find_gt (x : α) : ordnode α → option α | nil := none | (node _ l y r) := if y ≤ x then find_gt r else some (find_gt_aux x l y) /-- Auxiliary definition for `find_le`. -/ def find_le_aux (x : α) : ordnode α → α → α | nil best := best | (node _ l y r) best := match cmp_le x y with | ordering.lt := find_le_aux l best | ordering.eq := y | ordering.gt := find_le_aux r y end /-- O(log n). Get the largest element in the tree that is `≤ x`. find_le 2 {1, 2, 4} = some 2 find_le 3 {1, 2, 4} = some 2 find_le 0 {1, 2, 4} = none -/ def find_le (x : α) : ordnode α → option α | nil := none | (node _ l y r) := match cmp_le x y with | ordering.lt := find_le l | ordering.eq := some y | ordering.gt := some (find_le_aux x r y) end /-- Auxiliary definition for `find_ge`. -/ def find_ge_aux (x : α) : ordnode α → α → α | nil best := best | (node _ l y r) best := match cmp_le x y with | ordering.lt := find_ge_aux l y | ordering.eq := y | ordering.gt := find_ge_aux r best end /-- O(log n). Get the smallest element in the tree that is `≥ x`. find_le 2 {1, 2, 4} = some 2 find_le 3 {1, 2, 4} = some 4 find_le 5 {1, 2, 4} = none -/ def find_ge (x : α) : ordnode α → option α | nil := none | (node _ l y r) := match cmp_le x y with | ordering.lt := some (find_ge_aux x l y) | ordering.eq := some y | ordering.gt := find_ge r end /-- Auxiliary definition for `find_index`. -/ def find_index_aux (x : α) : ordnode α → ℕ → option ℕ | nil i := none | (node _ l y r) i := match cmp_le x y with | ordering.lt := find_index_aux l i | ordering.eq := some (i + size l) | ordering.gt := find_index_aux r (i + size l + 1) end /-- O(log n). Get the index, counting from the left, of an element equivalent to `x` if it exists. find_index 2 {1, 2, 4} = some 1 find_index 4 {1, 2, 4} = some 2 find_index 5 {1, 2, 4} = none -/ def find_index (x : α) (t : ordnode α) : option ℕ := find_index_aux x t 0 /-- Auxiliary definition for `is_subset`. -/ def is_subset_aux : ordnode α → ordnode α → bool | nil _ := tt | _ nil := ff | (node _ l x r) t := let (lt, found, gt) := split3 x t in found.is_some && is_subset_aux l lt && is_subset_aux r gt /-- O(m+n). Is every element of `t₁` equivalent to some element of `t₂`? is_subset {1, 4} {1, 2, 4} = tt is_subset {1, 3} {1, 2, 4} = ff -/ def is_subset (t₁ t₂ : ordnode α) : bool := to_bool (size t₁ ≤ size t₂) && is_subset_aux t₁ t₂ /-- O(m+n). Is every element of `t₁` not equivalent to any element of `t₂`? disjoint {1, 3} {2, 4} = tt disjoint {1, 2} {2, 4} = ff -/ def disjoint : ordnode α → ordnode α → bool | nil _ := tt | _ nil := tt | (node _ l x r) t := let (lt, found, gt) := split3 x t in found.is_none && disjoint l lt && disjoint r gt /-- O(m * log(|m ∪ n| + 1)), m ≤ n. The union of two sets, preferring members of `t₁` over those of `t₂` when equivalent elements are encountered. union {1, 2} {2, 3} = {1, 2, 3} union {1, 3} {2} = {1, 2, 3} Using a preorder on `ℕ × ℕ` that only compares the first coordinate: union {(1, 1)} {(0, 1), (1, 2)} = {(0, 1), (1, 1)} -/ def union : ordnode α → ordnode α → ordnode α | t₁ nil := t₁ | nil t₂ := t₂ | t₁@(node s₁ l₁ x₁ r₁) t₂@(node s₂ l₂ x₂ r₂) := if s₂ = 1 then insert' x₂ t₁ else if s₁ = 1 then insert x₁ t₂ else let (l₂', r₂') := split x₁ t₂ in link (union l₁ l₂') x₁ (union r₁ r₂') /-- O(m * log(|m ∪ n| + 1)), m ≤ n. Difference of two sets. diff {1, 2} {2, 3} = {1} diff {1, 2, 3} {2} = {1, 3} -/ def diff : ordnode α → ordnode α → ordnode α | t₁ nil := t₁ | t₁ t₂@(node _ l₂ x r₂) := cond t₁.empty t₂ $ let (l₁, r₁) := split x t₁, l₁₂ := diff l₁ l₂, r₁₂ := diff r₁ r₂ in if size l₁₂ + size r₁₂ = size t₁ then t₁ else merge l₁₂ r₁₂ /-- O(m * log(|m ∪ n| + 1)), m ≤ n. Intersection of two sets, preferring members of `t₁` over those of `t₂` when equivalent elements are encountered. inter {1, 2} {2, 3} = {2} inter {1, 3} {2} = ∅ -/ def inter : ordnode α → ordnode α → ordnode α | nil t₂ := nil | t₁@(node _ l₁ x r₁) t₂ := cond t₂.empty t₁ $ let (l₂, y, r₂) := split3 x t₂, l₁₂ := inter l₁ l₂, r₁₂ := inter r₁ r₂ in cond y.is_some (link l₁₂ x r₁₂) (merge l₁₂ r₁₂) /-- O(n * log n). Build a set from a list, preferring elements that appear earlier in the list in the case of equivalent elements. of_list [1, 2, 3] = {1, 2, 3} of_list [2, 1, 1, 3] = {1, 2, 3} Using a preorder on `ℕ × ℕ` that only compares the first coordinate: of_list [(1, 1), (0, 1), (1, 2)] = {(0, 1), (1, 1)} -/ def of_list (l : list α) : ordnode α := l.foldr insert nil /-- O(n * log n). Adaptively chooses between the linear and log-linear algorithm depending on whether the input list is already sorted. of_list' [1, 2, 3] = {1, 2, 3} of_list' [2, 1, 1, 3] = {1, 2, 3} -/ def of_list' : list α → ordnode α | [] := nil | (x :: xs) := if list.chain (λ a b, ¬ b ≤ a) x xs then of_asc_list (x :: xs) else of_list (x :: xs) /-- O(n * log n). Map a function on a set. Unlike `map` this has no requirements on `f`, and the resulting set may be smaller than the input if `f` is noninjective. Equivalent elements are selected with a preference for smaller source elements. image (λ x, x + 2) {1, 2, 4} = {3, 4, 6} image (λ x : ℕ, x - 2) {1, 2, 4} = {0, 2} -/ def image {α β} [has_le β] [@decidable_rel β (≤)] (f : α → β) (t : ordnode α) : ordnode β := of_list (t.to_list.map f) end end ordnode
1ff9d9780d717b0c378a402de926f60dd065ce45
66a6486e19b71391cc438afee5f081a4257564ec
/algebra/exactness.hlean
9fdec90808ea82233b6fe4c91c002f3e2a878470
[ "Apache-2.0" ]
permissive
spiceghello/Spectral
c8ccd1e32d4b6a9132ccee20fcba44b477cd0331
20023aa3de27c22ab9f9b4a177f5a1efdec2b19f
refs/heads/master
1,611,263,374,078
1,523,349,717,000
1,523,349,717,000
92,312,239
0
0
null
1,495,642,470,000
1,495,642,470,000
null
UTF-8
Lean
false
false
11,964
hlean
/- Copyright (c) 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad Short exact sequences -/ import homotopy.chain_complex eq2 .quotient_group open pointed is_trunc equiv is_equiv eq algebra group trunc function fiber sigma property structure is_exact_t {A B : Type} {C : Type*} (f : A → B) (g : B → C) := ( im_in_ker : Π(a:A), g (f a) = pt) ( ker_in_im : Π(b:B), (g b = pt) → fiber f b) structure is_exact {A B : Type} {C : Type*} (f : A → B) (g : B → C) := ( im_in_ker : Π(a:A), g (f a) = pt) ( ker_in_im : Π(b:B), (g b = pt) → image f b) namespace algebra definition is_exact_g {A B C : Group} (f : A →g B) (g : B →g C) := is_exact f g definition is_exact_ag {A B C : AbGroup} (f : A →g B) (g : B →g C) := is_exact f g definition is_exact_g.mk {A B C : Group} {f : A →g B} {g : B →g C} (H₁ : Πa, g (f a) = 1) (H₂ : Πb, g b = 1 → image f b) : is_exact_g f g := is_exact.mk H₁ H₂ definition is_exact.im_in_ker2 {A B : Type} {C : Set*} {f : A → B} {g : B → C} (H : is_exact f g) {b : B} (h : image f b) : g b = pt := begin induction h with a p, exact ap g p⁻¹ ⬝ is_exact.im_in_ker H a end definition is_exact_homotopy {A B : Type} {C : Type*} {f f' : A → B} {g g' : B → C} (p : f ~ f') (q : g ~ g') (H : is_exact f g) : is_exact f' g' := begin induction p using homotopy.rec_on_idp, induction q using homotopy.rec_on_idp, exact H end definition is_exact_trunc_functor {A B : Type} {C : Type*} {f : A → B} {g : B → C} (H : is_exact_t f g) : @is_exact _ _ (ptrunc 0 C) (trunc_functor 0 f) (trunc_functor 0 g) := begin constructor, { intro a, esimp, induction a with a, exact ap tr (is_exact_t.im_in_ker H a) }, { intro b p, induction b with b, note q := !tr_eq_tr_equiv p, induction q with q, induction is_exact_t.ker_in_im H b q with a r, exact image.mk (tr a) (ap tr r) } end definition is_contr_middle_of_is_exact {A B : Type} {C : Type*} {f : A → B} {g : B → C} (H : is_exact f g) [is_contr A] [is_set B] [is_contr C] : is_contr B := begin apply is_contr.mk (f pt), intro b, induction is_exact.ker_in_im H b !is_prop.elim, exact ap f !is_prop.elim ⬝ p end definition is_surjective_of_is_exact_of_is_contr {A B : Type} {C : Type*} {f : A → B} {g : B → C} (H : is_exact f g) [is_contr C] : is_surjective f := λb, is_exact.ker_in_im H b !is_prop.elim definition is_embedding_of_is_exact_g {A B C : Group} {g : B →g C} {f : A →g B} (gf : is_exact_g f g) [is_contr A] : is_embedding g := begin apply to_is_embedding_homomorphism, intro a p, induction is_exact.ker_in_im gf a p with x q, exact q⁻¹ ⬝ ap f !is_prop.elim ⬝ to_respect_one f end definition map_left_of_is_exact {G₃' G₃ G₂ : Type} {G₁ : Type*} {g : G₃ → G₂} {g' : G₃' → G₂} {f : G₂ → G₁} (H1 : is_exact g f) (H2 : is_exact g' f) (Hg' : is_embedding g') : G₃ → G₃' := begin intro a, have fiber g' (g a), begin have is_prop (fiber g' (g a)), from !is_prop_fiber_of_is_embedding, induction is_exact.ker_in_im H2 (g a) (is_exact.im_in_ker H1 a) with a' p, exact fiber.mk a' p end, exact point this end definition map_left_of_is_exact_compute {G₃' G₃ G₂ : Type} {G₁ : Type*} {g : G₃ → G₂} {g' : G₃' → G₂} {f : G₂ → G₁} (H1 : is_exact g f) (H2 : is_exact g' f) (Hg' : is_embedding g') (a : G₃) : g' (map_left_of_is_exact H1 H2 Hg' a) = g a := @point_eq _ _ g' _ _ definition map_left_of_is_exact_compose {G₃'' G₃' G₃ G₂ : Type} {G₁ : Type*} {g : G₃ → G₂} {g' : G₃' → G₂} {g'' : G₃'' → G₂} {f : G₂ → G₁} (H1 : is_exact g f) (H2 : is_exact g' f) (H3 : is_exact g'' f) (Hg' : is_embedding g') (Hg'' : is_embedding g'') (a : G₃) : map_left_of_is_exact H2 H3 Hg'' (map_left_of_is_exact H1 H2 Hg' a) = map_left_of_is_exact H1 H3 Hg'' a := begin refine @is_injective_of_is_embedding _ _ g'' _ _ _ _, refine !map_left_of_is_exact_compute ⬝ _ ⬝ !map_left_of_is_exact_compute⁻¹, exact map_left_of_is_exact_compute H1 H2 Hg' a end definition map_left_of_is_exact_id {G₃ G₂ : Type} {G₁ : Type*} {g : G₃ → G₂} {f : G₂ → G₁} (H1 : is_exact g f) (Hg : is_embedding g) (a : G₃) : map_left_of_is_exact H1 H1 Hg a = a := begin refine @is_injective_of_is_embedding _ _ g _ _ _ _, exact map_left_of_is_exact_compute H1 H1 Hg a end definition map_left_of_is_exact_homotopy {G₃' G₃ G₂ : Type} {G₁ : Type*} {g : G₃ → G₂} {g' g'' : G₃' → G₂} {f : G₂ → G₁} (H1 : is_exact g f) (H2 : is_exact g' f) (H3 : is_exact g'' f) (Hg' : is_embedding g') (Hg'' : is_embedding g'') (p : g' ~ g'') : map_left_of_is_exact H1 H2 Hg' ~ map_left_of_is_exact H1 H3 Hg'' := begin intro a, refine @is_injective_of_is_embedding _ _ g' _ _ _ _, exact !map_left_of_is_exact_compute ⬝ (!p ⬝ !map_left_of_is_exact_compute)⁻¹, end definition homomorphism_left_of_is_exact_g {G₃' G₃ G₂ G₁ : Group} {g : G₃ →g G₂} {g' : G₃' →g G₂} {f : G₂ →g G₁} (H1 : is_exact_g g f) (H2 : is_exact_g g' f) (Hg' : is_embedding g') : G₃ →g G₃' := begin apply homomorphism.mk (map_left_of_is_exact H1 H2 Hg'), { intro a a', refine @is_injective_of_is_embedding _ _ g' _ _ _ _, exact !point_eq ⬝ to_respect_mul g a a' ⬝ (to_respect_mul g' _ _ ⬝ ap011 mul !point_eq !point_eq)⁻¹ } end definition isomorphism_left_of_is_exact_g {G₃' G₃ G₂ G₁ : Group} {g : G₃ →g G₂} {g' : G₃' →g G₂} {f : G₂ →g G₁} (H1 : is_exact g f) (H2 : is_exact g' f) (Hg : is_embedding g) (Hg' : is_embedding g') : G₃ ≃g G₃' := begin fapply isomorphism.mk, exact homomorphism_left_of_is_exact_g H1 H2 Hg', fapply adjointify, exact homomorphism_left_of_is_exact_g H2 H1 Hg, { intro a, refine @is_injective_of_is_embedding _ _ g' _ _ _ _, refine map_left_of_is_exact_compute H1 H2 Hg' _ ⬝ map_left_of_is_exact_compute H2 H1 Hg a }, { intro a, refine @is_injective_of_is_embedding _ _ g _ _ _ _, refine map_left_of_is_exact_compute H2 H1 Hg _ ⬝ map_left_of_is_exact_compute H1 H2 Hg' a }, end definition is_exact_incl_of_subgroup {G H : Group} (f : G →g H) : is_exact (incl_of_subgroup (kernel f)) f := begin apply is_exact.mk, { intro x, cases x with x p, exact p }, { intro x p, exact image.mk ⟨x, p⟩ idp } end definition isomorphism_kernel_of_is_exact {G₄ G₃ G₂ G₁ : Group} {h : G₄ →g G₃} {g : G₃ →g G₂} {f : G₂ →g G₁} (H1 : is_exact h g) (H2 : is_exact g f) (HG : is_contr G₄) : G₃ ≃g Kernel f := isomorphism_left_of_is_exact_g H2 (is_exact_incl_of_subgroup f) (is_embedding_of_is_exact_g H1) (is_embedding_incl_of_subgroup _) section chain_complex open succ_str chain_complex definition is_exact_of_is_exact_at {N : succ_str} {A : chain_complex N} {n : N} (H : is_exact_at A n) : is_exact (cc_to_fn A (S n)) (cc_to_fn A n) := is_exact.mk (cc_is_chain_complex A n) H end chain_complex structure is_short_exact {A B : Type} {C : Type*} (f : A → B) (g : B → C) := (is_emb : is_embedding f) (im_in_ker : Π(a:A), g (f a) = pt) (ker_in_im : Π(b:B), (g b = pt) → image f b) (is_surj : is_surjective g) structure is_short_exact_t {A B : Type} {C : Type*} (f : A → B) (g : B → C) := (is_emb : is_embedding f) (im_in_ker : Π(a:A), g (f a) = pt) (ker_in_im : Π(b:B), (g b = pt) → fiber f b) (is_surj : is_split_surjective g) lemma is_short_exact_of_is_exact {X A B C Y : Group} (k : X →g A) (f : A →g B) (g : B →g C) (l : C →g Y) (hX : is_contr X) (hY : is_contr Y) (kf : is_exact_g k f) (fg : is_exact_g f g) (gl : is_exact_g g l) : is_short_exact f g := begin constructor, { exact is_embedding_of_is_exact_g kf }, { exact is_exact.im_in_ker fg }, { exact is_exact.ker_in_im fg }, { intro c, exact is_exact.ker_in_im gl c !is_prop.elim }, end lemma is_short_exact_equiv {A B A' B' : Type} {C C' : Type*} {f' : A' → B'} {g' : B' → C'} (f : A → B) (g : B → C) (eA : A ≃ A') (eB : B ≃ B') (eC : C ≃* C') (h₁ : hsquare f f' eA eB) (h₂ : hsquare g g' eB eC) (H : is_short_exact f' g') : is_short_exact f g := begin constructor, { apply is_embedding_homotopy_closed_rev (homotopy_top_of_hsquare h₁), apply is_embedding_compose, apply is_embedding_of_is_equiv, apply is_embedding_compose, apply is_short_exact.is_emb H, apply is_embedding_of_is_equiv }, { intro a, refine homotopy_top_of_hsquare' (hhconcat h₁ h₂) a ⬝ _, refine ap eC⁻¹ _ ⬝ respect_pt eC⁻¹ᵉ*, exact is_short_exact.im_in_ker H (eA a) }, { intro b p, note q := eq_of_inv_eq ((homotopy_top_of_hsquare' h₂ b)⁻¹ ⬝ p) ⬝ respect_pt eC, induction is_short_exact.ker_in_im H (eB b) q with a' r, apply image.mk (eA⁻¹ a'), exact eq_of_fn_eq_fn eB ((homotopy_top_of_hsquare h₁⁻¹ʰᵗʸᵛ a')⁻¹ ⬝ r) }, { apply is_surjective_homotopy_closed_rev (homotopy_top_of_hsquare' h₂), apply is_surjective_compose, apply is_surjective_of_is_equiv, apply is_surjective_compose, apply is_short_exact.is_surj H, apply is_surjective_of_is_equiv } end lemma is_exact_of_is_short_exact {A B : Type} {C : Type*} {f : A → B} {g : B → C} (H : is_short_exact f g) : is_exact f g := begin constructor, { exact is_short_exact.im_in_ker H }, { exact is_short_exact.ker_in_im H } end lemma is_equiv_left_of_is_short_exact {A B C : Group} {f : A →g B} {g : B →g C} (H : is_short_exact f g) (HC : is_contr C) : is_equiv f := begin apply is_equiv_of_is_surjective_of_is_embedding, exact is_short_exact.is_emb H, apply is_surjective_of_is_exact_of_is_contr, exact is_exact_of_is_short_exact H end lemma is_equiv_right_of_is_short_exact {A B C : Group} {f : A →g B} {g : B →g C} (H : is_short_exact f g) (HA : is_contr A) : is_equiv g := begin apply is_equiv_of_is_surjective_of_is_embedding, apply is_embedding_of_is_exact_g, exact is_exact_of_is_short_exact H, exact is_short_exact.is_surj H end definition is_contr_right_of_is_short_exact {A B : Type} {C : Type*} {f : A → B} {g : B → C} (H : is_short_exact f g) (HB : is_contr B) (HC : is_set C) : is_contr C := is_contr_of_is_surjective g (is_short_exact.is_surj H) HB HC definition is_contr_left_of_is_short_exact {A B : Type} {C : Type*} {f : A → B} {g : B → C} (H : is_short_exact f g) (HB : is_contr B) (a₀ : A) : is_contr A := is_contr_of_is_embedding f (is_short_exact.is_emb H) _ a₀ /- TODO: move and remove other versions -/ definition is_surjective_qg_map {A : Group} (N : property A) [is_normal_subgroup A N] : is_surjective (qg_map N) := begin intro x, induction x, fapply image.mk, exact a, reflexivity, apply is_prop.elimo end definition is_surjective_ab_qg_map {A : AbGroup} (N : property A) [is_normal_subgroup A N] : is_surjective (ab_qg_map N) := is_surjective_ab_qg_map _ definition qg_map_eq_one {A : Group} {K : property A} [is_normal_subgroup A K] (g : A) (H : g ∈ K) : qg_map K g = 1 := begin apply set_quotient.eq_of_rel, have e : g * 1⁻¹ = g, from calc g * 1⁻¹ = g * 1 : one_inv ... = g : mul_one, exact transport (λx, K x) e⁻¹ H end definition ab_qg_map_eq_one {A : AbGroup} {K : property A} [is_subgroup A K] (g : A) (H : g ∈ K) : ab_qg_map K g = 1 := ab_qg_map_eq_one g H definition is_short_exact_normal_subgroup {G : Group} (S : property G) [is_normal_subgroup G S] : is_short_exact (incl_of_subgroup S) (qg_map S) := begin fconstructor, { exact is_embedding_incl_of_subgroup S }, { intro a, fapply qg_map_eq_one, induction a with b p, exact p }, { intro b p, fapply image.mk, { apply sigma.mk b, fapply rel_of_qg_map_eq_one, exact p }, reflexivity }, { exact is_surjective_qg_map S }, end end algebra
77540991dd08d149095a556bfee8a0ce49a7185d
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Meta/Tactic/Generalize.lean
c972bc9db920d00045193f73162c2a793dbb5955
[ "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,737
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.KAbstract import Lean.Meta.Tactic.Util import Lean.Meta.Tactic.Intro namespace Lean.Meta /-- The `generalize` tactic takes arguments of the form `h : e = x` -/ structure GeneralizeArg where expr : Expr xName? : Option Name := none hName? : Option Name := none deriving Inhabited partial def generalize (mvarId : MVarId) (args : Array GeneralizeArg) : MetaM (Array FVarId × MVarId) := withMVarContext mvarId do checkNotAssigned mvarId `generalize let tag ← getMVarTag mvarId let target ← instantiateMVars (← getMVarType mvarId) let rec go (i : Nat) : MetaM Expr := do if i < args.size then let arg := args[i] let e ← instantiateMVars arg.expr let eType ← instantiateMVars (← inferType e) let type ← go (i+1) let xName ← if let some xName := arg.xName? then pure xName else mkFreshUserName `x return Lean.mkForall xName BinderInfo.default eType (← kabstract type e) else return target let targetNew ← go 0 unless (← isTypeCorrect targetNew) do throwTacticEx `generalize mvarId m!"result is not type correct{indentExpr targetNew}" let es := args.map (·.expr) if !args.any fun arg => arg.hName?.isSome then let mvarNew ← mkFreshExprSyntheticOpaqueMVar targetNew tag assignExprMVar mvarId (mkAppN mvarNew es) introNP mvarNew.mvarId! args.size else let (rfls, targetNew) ← forallBoundedTelescope targetNew args.size fun xs type => do let rec go' (i : Nat) : MetaM (List Expr × Expr) := do if i < xs.size then let arg := args[i] if let some hName := arg.hName? then let xType ← inferType xs[i] let e ← instantiateMVars arg.expr let eType ← instantiateMVars (← inferType e) let (hType, r) ← if (← isDefEq xType eType) then pure (← mkEq e xs[i], ← mkEqRefl e) else pure (← mkHEq e xs[i], ← mkHEqRefl e) let (rs, type) ← go' (i+1) return (r :: rs, mkForall hName BinderInfo.default hType type) else go' (i+1) else return ([], type) let (rfls, type) ← go' 0 return (rfls, ← mkForallFVars xs type) let mvarNew ← mkFreshExprSyntheticOpaqueMVar targetNew tag assignExprMVar mvarId (mkAppN (mkAppN mvarNew es) rfls.toArray) introNP mvarNew.mvarId! (args.size + rfls.length) end Lean.Meta
b65d74e767cf417fe0917b0e90e530a86a1cc038
aa5a655c05e5359a70646b7154e7cac59f0b4132
/src/Lean/Server/FileWorker.lean
adaa46aaeae2390ffc8afc1efa0b7410f5444d03
[ "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
29,297
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 Init.System.IO import Std.Data.RBMap import Lean.Environment import Lean.PrettyPrinter import Lean.DeclarationRange import Lean.Data.Lsp import Lean.Data.Json.FromToJson import Lean.Server.Snapshots import Lean.Server.Utils import Lean.Server.AsyncList import Lean.Server.InfoUtils /-! For general server architecture, see `README.md`. For details of IPC communication, see `Watchdog.lean`. This module implements per-file worker processes. File processing and requests+notifications against a file should be concurrent for two reasons: - By the LSP standard, requests should be cancellable. - Since Lean allows arbitrary user code to be executed during elaboration via the tactic framework, elaboration can be extremely slow and even not halt in some cases. Users should be able to work with the file while this is happening, e.g. make new changes to the file or send requests. To achieve these goals, elaboration is executed in a chain of tasks, where each task corresponds to the elaboration of one command. When the elaboration of one command is done, the next task is spawned. On didChange notifications, we search for the task in which the change occured. If we stumble across a task that has not yet finished before finding the task we're looking for, we terminate it and start the elaboration there, otherwise we start the elaboration at the task where the change occured. Requests iterate over tasks until they find the command that they need to answer the request. In order to not block the main thread, this is done in a request task. If a task that the request task waits for is terminated, a change occured somewhere before the command that the request is looking for and the request sends a "content changed" error. -/ namespace Lean.Server.FileWorker open Lsp open IO open Snapshots open Lean.Parser.Command open Std (RBMap RBMap.empty) open JsonRpc section Utils private def logSnapContent (s : Snapshot) (text : FileMap) : IO Unit := IO.eprintln s!"[{s.beginPos}, {s.endPos}]: `{text.source.extract s.beginPos (s.endPos-1)}`" inductive ElabTaskError where | aborted | eof | ioError (e : IO.Error) instance : Coe IO.Error ElabTaskError := ⟨ElabTaskError.ioError⟩ structure CancelToken where ref : IO.Ref Bool deriving Inhabited namespace CancelToken def new : IO CancelToken := CancelToken.mk <$> IO.mkRef false def check [MonadExceptOf ElabTaskError m] [MonadLiftT (ST RealWorld) m] [Monad m] (tk : CancelToken) : m Unit := do let c ← tk.ref.get if c = true then throw ElabTaskError.aborted def set (tk : CancelToken) : IO Unit := tk.ref.set true end CancelToken /-- A document editable in the sense that we track the environment and parser state after each command so that edits can be applied without recompiling code appearing earlier in the file. -/ structure EditableDocument where meta : DocumentMeta /- The first snapshot is that after the header. -/ headerSnap : Snapshot /- Subsequent snapshots occur after each command. -/ cmdSnaps : AsyncList ElabTaskError Snapshot cancelTk : CancelToken deriving Inhabited end Utils /- Asynchronous snapshot elaboration. -/ section Elab /-- Elaborates the next command after `parentSnap` and emits diagnostics into `hOut`. -/ private def nextCmdSnap (m : DocumentMeta) (parentSnap : Snapshot) (cancelTk : CancelToken) (hOut : FS.Stream) : ExceptT ElabTaskError IO Snapshot := do cancelTk.check let maybeSnap ← compileNextCmd m.text.source parentSnap -- TODO(MH): check for interrupt with increased precision cancelTk.check let sendDiagnostics (msgLog : MessageLog) : IO Unit := do let diagnostics ← msgLog.msgs.mapM (msgToDiagnostic m.text) hOut.writeLspNotification { method := "textDocument/publishDiagnostics" param := { uri := m.uri version? := m.version diagnostics := diagnostics.toArray : PublishDiagnosticsParams } } match maybeSnap with | Sum.inl snap => /- NOTE(MH): This relies on the client discarding old diagnostics upon receiving new ones while prefering newer versions over old ones. The former is necessary because we do not explicitly clear older diagnostics, while the latter is necessary because we do not guarantee that diagnostics are emitted in order. Specifically, it may happen that we interrupted this elaboration task right at this point and a newer elaboration task emits diagnostics, after which we emit old diagnostics because we did not yet detect the interrupt. Explicitly clearing diagnostics is difficult for a similar reason, because we cannot guarantee that no further diagnostics are emitted after clearing them. -/ sendDiagnostics <| snap.msgLog.add { fileName := "<ignored>" pos := m.text.toPosition snap.endPos severity := MessageSeverity.information data := "processing..." } snap | Sum.inr msgLog => sendDiagnostics msgLog throw ElabTaskError.eof /-- Elaborates all commands after `initSnap`, emitting the diagnostics into `hOut`. -/ def unfoldCmdSnaps (m : DocumentMeta) (initSnap : Snapshot) (cancelTk : CancelToken) (hOut : FS.Stream) : IO (AsyncList ElabTaskError Snapshot) := do AsyncList.unfoldAsync (nextCmdSnap m . cancelTk hOut) initSnap end Elab -- Pending requests are tracked so they can be cancelled abbrev PendingRequestMap := RBMap RequestID (Task (Except IO.Error Unit)) (fun a b => Decidable.decide (a < b)) structure ServerContext where hIn : FS.Stream hOut : FS.Stream hLog : FS.Stream srcSearchPath : SearchPath docRef : IO.Ref EditableDocument pendingRequestsRef : IO.Ref PendingRequestMap abbrev ServerM := ReaderT ServerContext IO /- Worker initialization sequence. -/ section Initialization /-- Use `leanpkg print-paths` to compile dependencies on the fly and add them to `LEAN_PATH`. Compilation progress is reported to `hOut` via LSP notifications. Return the search path for source files. -/ partial def leanpkgSetupSearchPath (leanpkgPath : String) (m : DocumentMeta) (imports : Array Import) (hOut : FS.Stream) : IO SearchPath := do let leanpkgProc ← Process.spawn { stdin := Process.Stdio.null stdout := Process.Stdio.piped stderr := Process.Stdio.piped cmd := leanpkgPath args := #["print-paths"] ++ imports.map (toString ·.module) } -- progress notification: report latest stderr line let rec processStderr (acc : String) : IO String := do let line ← leanpkgProc.stderr.getLine if line == "" then return acc else hOut.writeLspNotification { method := "textDocument/publishDiagnostics" param := { uri := m.uri version? := m.version diagnostics := #[{ range := ⟨⟨0, 0⟩, ⟨0, 0⟩⟩, severity? := DiagnosticSeverity.information, message := line }] : PublishDiagnosticsParams } } processStderr (acc ++ line) let stderr ← IO.asTask (processStderr "") Task.Priority.dedicated let stdout := String.trim (← leanpkgProc.stdout.readToEnd) let stderr ← IO.ofExcept stderr.get if (← leanpkgProc.wait) == 0 then match stdout.split (· == '\n') with | [""] => pure [] -- e.g. no leanpkg.toml | [leanPath, leanSrcPath] => let sp ← getBuiltinSearchPath let sp ← addSearchPathFromEnv sp let sp ← parseSearchPath leanPath sp searchPathRef.set sp let srcPath := parseSearchPath leanSrcPath srcPath.mapM realPathNormalized | _ => throw <| IO.userError s!"unexpected output from `leanpkg print-paths`:\n{stdout}\nstderr:\n{stderr}" else -- HACK(WN): `leanpkg` currently runs in the current directory, most likely the directory where the editor -- was ran, which can lead to unexpected failures. We need to support workspace folders and execute it there. -- For now though, just log the failure and press onwards. IO.eprintln s!"`leanpkg print-paths` failed:\n{stdout}\nstderr:\n{stderr}" return [] def compileHeader (m : DocumentMeta) (hOut : FS.Stream) : IO (Snapshot × SearchPath) := do let opts := {} -- TODO let inputCtx := Parser.mkInputContext m.text.source "<input>" let (headerStx, headerParserState, msgLog) ← Parser.parseHeader inputCtx let leanpkgPath ← match ← IO.getEnv "LEAN_SYSROOT" with | some path => s!"{path}/bin/leanpkg{System.FilePath.exeSuffix}" | _ => s!"{← appDir}/leanpkg{System.FilePath.exeSuffix}" let mut srcSearchPath := [s!"{← appDir}/../lib/lean/src"] if let some p := (← IO.getEnv "LEAN_SRC_PATH") then srcSearchPath := srcSearchPath ++ parseSearchPath p -- NOTE: leanpkg does not exist in stage 0 (yet?) if (← fileExists leanpkgPath) then let pkgSearchPath ← leanpkgSetupSearchPath leanpkgPath m (Lean.Elab.headerToImports headerStx).toArray hOut srcSearchPath := srcSearchPath ++ pkgSearchPath let (headerEnv, msgLog) ← Elab.processHeader headerStx opts msgLog inputCtx let cmdState := Elab.Command.mkState headerEnv msgLog opts let opts := opts.setBool `interpreter.prefer_native false let cmdState := { cmdState with infoState.enabled := true, scopes := [{ header := "", opts := opts }] } let headerSnap := { beginPos := 0 stx := headerStx mpState := headerParserState data := SnapshotData.headerData cmdState } return (headerSnap, srcSearchPath) def initializeWorker (p : DidOpenTextDocumentParams) (i o e : FS.Stream) : IO ServerContext := do let doc := p.textDocument /- NOTE(WN): `toFileMap` marks line beginnings as immediately following "\n", which should be enough to handle both LF and CRLF correctly. This is because LSP always refers to characters by (line, column), so if we get the line number correct it shouldn't matter that there is a CR there. -/ let meta : DocumentMeta := ⟨doc.uri, doc.version, doc.text.toFileMap⟩ let (headerSnap, srcSearchPath) ← compileHeader meta o let cancelTk ← CancelToken.new let cmdSnaps ← unfoldCmdSnaps meta headerSnap cancelTk o let doc : EditableDocument := ⟨meta, headerSnap, cmdSnaps, cancelTk⟩ return { hIn := i hOut := o hLog := e srcSearchPath := srcSearchPath docRef := ←IO.mkRef doc pendingRequestsRef := ←IO.mkRef RBMap.empty } end Initialization section Updates def updatePendingRequests (map : PendingRequestMap → PendingRequestMap) : ServerM Unit := do (←read).pendingRequestsRef.modify map /-- Given the new document and `changePos`, the UTF-8 offset of a change into the pre-change source, updates editable doc state. -/ def updateDocument (newMeta : DocumentMeta) (changePos : String.Pos) : ServerM Unit := do -- The watchdog only restarts the file worker when the syntax tree of the header changes. -- If e.g. a newline is deleted, it will not restart this file worker, but we still -- need to reparse the header so that the offsets are correct. let st ← read let oldDoc ← st.docRef.get let newHeaderSnap ← reparseHeader newMeta.text.source oldDoc.headerSnap if newHeaderSnap.stx != oldDoc.headerSnap.stx then throwServerError "Internal server error: header changed but worker wasn't restarted." let ⟨cmdSnaps, e?⟩ ← oldDoc.cmdSnaps.updateFinishedPrefix match e? with -- This case should not be possible. only the main task aborts tasks and ensures that aborted tasks -- do not show up in `snapshots` of an EditableDocument. | some ElabTaskError.aborted => throwServerError "Internal server error: elab task was aborted while still in use." | some (ElabTaskError.ioError ioError) => throw ioError | _ => -- No error or EOF oldDoc.cancelTk.set -- NOTE(WN): we invalidate eagerly as `endPos` consumes input greedily. To re-elaborate only -- when really necessary, we could do a whitespace-aware `Syntax` comparison instead. let mut validSnaps := cmdSnaps.finishedPrefix.takeWhile (fun s => s.endPos < changePos) if validSnaps.length = 0 then let cancelTk ← CancelToken.new let newCmdSnaps ← unfoldCmdSnaps newMeta newHeaderSnap cancelTk st.hOut st.docRef.set ⟨newMeta, newHeaderSnap, newCmdSnaps, cancelTk⟩ else /- When at least one valid non-header snap exists, it may happen that a change does not fall within the syntactic range of that last snap but still modifies it by appending tokens. We check for this here. We do not currently handle crazy grammars in which an appended token can merge two or more previous commands into one. To do so would require reparsing the entire file. -/ let mut lastSnap := validSnaps.getLast! let preLastSnap := if validSnaps.length ≥ 2 then validSnaps.get! (validSnaps.length - 2) else newHeaderSnap let newLastStx ← parseNextCmd newMeta.text.source preLastSnap if newLastStx != lastSnap.stx then validSnaps ← validSnaps.dropLast lastSnap ← preLastSnap let cancelTk ← CancelToken.new let newSnaps ← unfoldCmdSnaps newMeta lastSnap cancelTk st.hOut let newCmdSnaps := AsyncList.ofList validSnaps ++ newSnaps st.docRef.set ⟨newMeta, newHeaderSnap, newCmdSnaps, cancelTk⟩ end Updates /- Notifications are handled in the main thread. They may change global worker state such as the current file contents. -/ section NotificationHandling def handleDidChange (p : DidChangeTextDocumentParams) : ServerM Unit := do let docId := p.textDocument let changes := p.contentChanges let oldDoc ← (←read).docRef.get let some newVersion ← pure docId.version? | throwServerError "Expected version number" if newVersion ≤ oldDoc.meta.version then -- TODO(WN): This happens on restart sometimes. IO.eprintln s!"Got outdated version number: {newVersion} ≤ {oldDoc.meta.version}" else if ¬ changes.isEmpty then let (newDocText, minStartOff) := foldDocumentChanges changes oldDoc.meta.text updateDocument ⟨docId.uri, newVersion, newDocText⟩ minStartOff def handleCancelRequest (p : CancelParams) : ServerM Unit := do updatePendingRequests (fun pendingRequests => pendingRequests.erase p.id) end NotificationHandling /- Request handlers are given by `Task`s executed asynchronously. They may be cancelled at any time, so they should check the cancellation token when possible to handle this cooperatively. Any exceptions thrown in a handler will be reported to the client as LSP error responses. -/ section RequestHandling structure RequestError where code : ErrorCode message : String namespace RequestError def fileChanged : RequestError := { code := ErrorCode.contentModified message := "File changed." } end RequestError -- TODO(WN): the type is too complicated abbrev RequestM α := ServerM $ Task $ Except IO.Error $ Except RequestError α def mapTask (t : Task α) (f : α → ExceptT RequestError ServerM β) : RequestM β := fun st => (IO.mapTask · t) fun a => f a st /-- Create a task which waits for a snapshot matching `p`, handles various errors, and if a matching snapshot was found executes `x` with it. If not found, the task executes `notFoundX`. -/ def withWaitFindSnap (doc : EditableDocument) (p : Snapshot → Bool) (notFoundX : ExceptT RequestError ServerM β) (x : Snapshot → ExceptT RequestError ServerM β) : ServerM (Task (Except IO.Error (Except RequestError β))) := do let findTask ← doc.cmdSnaps.waitFind? p mapTask findTask fun | Except.error ElabTaskError.aborted => throwThe RequestError RequestError.fileChanged | Except.error (ElabTaskError.ioError e) => throwThe IO.Error e | Except.error ElabTaskError.eof => notFoundX | Except.ok none => notFoundX | Except.ok (some snap) => x snap /- Requests that need data from a certain command should traverse the snapshots by successively getting the next task, meaning that we might need to wait for elaboration. When that happens, the request should send a "content changed" error to the user (this way, the server doesn't get bogged down in requests for an old state of the document). Requests need to manually check for whether their task has been cancelled, so that they can reply with a RequestCancelled error. -/ open Elab in partial def handleHover (id : RequestID) (p : HoverParams) : ServerM (Task (Except IO.Error (Except RequestError (Option Hover)))) := do let st ← read let doc ← st.docRef.get let text := doc.meta.text let mkHover (s : String) (f : String.Pos) (t : String.Pos) : Hover := { contents := { kind := MarkupKind.markdown value := s } range? := some { start := text.utf8PosToLspPos f «end» := text.utf8PosToLspPos t } } let hoverPos := text.lspPosToUtf8Pos p.position withWaitFindSnap doc (fun s => s.endPos > hoverPos) (notFoundX := pure none) fun snap => do for t in snap.toCmdState.infoState.trees do if let some (ci, i) := t.hoverableTermAt? hoverPos then let tFmt ← ci.runMetaM i.lctx do return f!"{← Meta.ppExpr i.expr} : {← Meta.ppExpr (← Meta.inferType i.expr)}" let mut hoverFmt := f!"```lean {tFmt} ```" if let some n := i.expr.constName? then if let some doc ← ci.runMetaM i.lctx <| findDocString? n then hoverFmt := f!"{hoverFmt}\n***\n{doc}" return some <| mkHover (toString hoverFmt) i.pos?.get! i.tailPos?.get! pure () return none open Elab in partial def handleDefinition (goToType? : Bool) (id : RequestID) (p : TextDocumentPositionParams) : ServerM (Task (Except IO.Error (Except RequestError (Array LocationLink)))) := do let st ← read let doc ← st.docRef.get let text := doc.meta.text let hoverPos := text.lspPosToUtf8Pos p.position withWaitFindSnap doc (fun s => s.endPos > hoverPos) (notFoundX := pure #[]) fun snap => do for t in snap.toCmdState.infoState.trees do if let some (ci, i) := t.hoverableTermAt? hoverPos then let expr ← if goToType? then ci.runMetaM i.lctx <| Meta.inferType i.expr else i.expr if let some n := expr.constName? then let mod? ← ci.runMetaM i.lctx <| findModuleOf? n let modUri? ← match mod? with | some modName => let modFname? ← st.srcSearchPath.findWithExt ".lean" modName pure <| modFname?.map toFileUri | none => pure <| some doc.meta.uri let ranges? ← ci.runMetaM i.lctx <| findDeclarationRanges? n if let (some ranges, some modUri) := (ranges?, modUri?) then let declRangeToLspRange (r : DeclarationRange) : Lsp.Range := { start := ⟨r.pos.line - 1, r.charUtf16⟩ «end» := ⟨r.endPos.line - 1, r.endCharUtf16⟩ } let ll : LocationLink := { originSelectionRange? := some ⟨text.utf8PosToLspPos i.pos?.get!, text.utf8PosToLspPos i.tailPos?.get!⟩ targetUri := modUri targetRange := declRangeToLspRange ranges.range targetSelectionRange := declRangeToLspRange ranges.selectionRange } return #[ll] return #[] def rangeOfSyntax (text : FileMap) (stx : Syntax) : Range := ⟨text.utf8PosToLspPos <| stx.getPos?.get!, text.utf8PosToLspPos <| stx.getTailPos?.get!⟩ partial def handleDocumentSymbol (id : RequestID) (p : DocumentSymbolParams) : ServerM (Task (Except IO.Error (Except RequestError DocumentSymbolResult))) := do let st ← read asTask do let doc ← st.docRef.get let ⟨cmdSnaps, e?⟩ ← doc.cmdSnaps.updateFinishedPrefix let mut stxs := cmdSnaps.finishedPrefix.map Snapshot.stx match e? with | some ElabTaskError.aborted => return Except.error RequestError.fileChanged | some _ => pure () -- TODO(WN): what to do on ioError? | none => let lastSnap := cmdSnaps.finishedPrefix.getLastD doc.headerSnap stxs := stxs ++ (← parseAhead doc.meta.text.source lastSnap).toList let (syms, _) := toDocumentSymbols doc.meta.text stxs return Except.ok { syms := syms.toArray } where toDocumentSymbols (text : FileMap) | [] => ([], []) | stx::stxs => match stx with | `(namespace $id) => sectionLikeToDocumentSymbols text stx stxs (id.getId.toString) SymbolKind.namespace id | `(section $(id)?) => sectionLikeToDocumentSymbols text stx stxs ((·.getId.toString) <$> id |>.getD "<section>") SymbolKind.namespace (id.getD stx) | `(end $(id)?) => ([], stx::stxs) | _ => let (syms, stxs') := toDocumentSymbols text stxs if stx.isOfKind ``Lean.Parser.Command.declaration then let (name, selection) := match stx with | `($dm:declModifiers $ak:attrKind instance $[$np:namedPrio]? $[$id:ident$[.{$ls,*}]?]? $sig:declSig $val) => ((·.getId.toString) <$> id |>.getD s!"instance {sig.reprint.getD ""}", id.getD sig) | _ => match stx[1][1] with | `(declId|$id:ident$[.{$ls,*}]?) => (id.getId.toString, id) | _ => (stx[1][0].isIdOrAtom?.getD "<unknown>", stx[1][0]) (DocumentSymbol.mk { name := name kind := SymbolKind.method range := rangeOfSyntax text stx selectionRange := rangeOfSyntax text selection } :: syms, stxs') else (syms, stxs') sectionLikeToDocumentSymbols (text : FileMap) (stx : Syntax) (stxs : List Syntax) (name : String) (kind : SymbolKind) (selection : Syntax) := let (syms, stxs') := toDocumentSymbols text stxs -- discard `end` let (syms', stxs'') := toDocumentSymbols text (stxs'.drop 1) let endStx := match stxs' with | endStx::_ => endStx | [] => (stx::stxs').getLast! (DocumentSymbol.mk { name := name kind := kind range := ⟨(rangeOfSyntax text stx).start, (rangeOfSyntax text endStx).«end»⟩ selectionRange := rangeOfSyntax text selection children? := syms.toArray } :: syms', stxs'') partial def handleWaitForDiagnostics (id : RequestID) (p : WaitForDiagnosticsParams) : ServerM (Task (Except IO.Error (Except RequestError WaitForDiagnostics))) := do let st ← read let rec waitLoop : IO EditableDocument := do let doc ← st.docRef.get if p.version ≤ doc.meta.version then return doc else IO.sleep 50 waitLoop let t ← IO.asTask waitLoop let t ← IO.bindTask t fun | Except.error e => unreachable! | Except.ok doc => do let t₁ ← doc.cmdSnaps.waitAll return t₁.map fun _ => Except.ok WaitForDiagnostics.mk return t.map fun _ => Except.ok <| Except.ok WaitForDiagnostics.mk end RequestHandling section MessageHandling def parseParams (paramType : Type) [FromJson paramType] (params : Json) : ServerM paramType := match fromJson? params with | some parsed => pure parsed | none => throwServerError s!"Got param with wrong structure: {params.compress}" def handleNotification (method : String) (params : Json) : ServerM Unit := do let handle := fun paramType [FromJson paramType] (handler : paramType → ServerM Unit) => parseParams paramType params >>= handler match method with | "textDocument/didChange" => handle DidChangeTextDocumentParams handleDidChange | "$/cancelRequest" => handle CancelParams handleCancelRequest | _ => throwServerError s!"Got unsupported notification method: {method}" def queueRequest (id : RequestID) (requestTask : Task (Except IO.Error Unit)) : ServerM Unit := do updatePendingRequests (fun pendingRequests => pendingRequests.insert id requestTask) def handleRequest (id : RequestID) (method : String) (params : Json) : ServerM Unit := do let handle := fun paramType [FromJson paramType] respType [ToJson respType] (handler : RequestID → paramType → RequestM respType) => do let st ← read let p ← parseParams paramType params let t ← handler id p let t₁ ← (IO.mapTask · t) fun | Except.ok (Except.ok resp) => st.hOut.writeLspResponse ⟨id, resp⟩ | Except.ok (Except.error e) => st.hOut.writeLspResponseError { id := id, code := e.code, message := e.message } | Except.error e => st.hOut.writeLspResponseError { id := id, code := ErrorCode.internalError, message := toString e } queueRequest id t₁ match method with | "textDocument/waitForDiagnostics" => handle WaitForDiagnosticsParams WaitForDiagnostics handleWaitForDiagnostics | "textDocument/hover" => handle HoverParams (Option Hover) handleHover | "textDocument/declaration" => handle TextDocumentPositionParams (Array LocationLink) <| handleDefinition (goToType? := false) | "textDocument/definition" => handle TextDocumentPositionParams (Array LocationLink) <| handleDefinition (goToType? := false) | "textDocument/typeDefinition" => handle TextDocumentPositionParams (Array LocationLink) <| handleDefinition (goToType? := true) | "textDocument/documentSymbol" => handle DocumentSymbolParams DocumentSymbolResult handleDocumentSymbol | _ => throwServerError s!"Got unsupported request: {method}" end MessageHandling section MainLoop partial def mainLoop : ServerM Unit := do let st ← read let msg ← st.hIn.readLspMessage let pendingRequests ← st.pendingRequestsRef.get let filterFinishedTasks (acc : PendingRequestMap) (id : RequestID) (task : Task (Except IO.Error Unit)) : ServerM PendingRequestMap := do if (←hasFinished task) then /- Handler tasks are constructed so that the only possible errors here are failures of writing a response into the stream. -/ if let Except.error e := task.get then throwServerError s!"Failed responding to request {id}: {e}" acc.erase id else acc let pendingRequests ← pendingRequests.foldM filterFinishedTasks pendingRequests st.pendingRequestsRef.set pendingRequests match msg with | Message.request id method (some params) => handleRequest id method (toJson params) mainLoop | Message.notification "exit" none => let doc ← st.docRef.get doc.cancelTk.set return () | Message.notification method (some params) => handleNotification method (toJson params) mainLoop | _ => throwServerError "Got invalid JSON-RPC message" end MainLoop def initAndRunWorker (i o e : FS.Stream) : IO UInt32 := do let i ← maybeTee "fwIn.txt" false i let o ← maybeTee "fwOut.txt" true o -- TODO(WN): act in accordance with InitializeParams let _ ← i.readLspRequestAs "initialize" InitializeParams let ⟨_, param⟩ ← i.readLspNotificationAs "textDocument/didOpen" DidOpenTextDocumentParams let e ← e.withPrefix s!"[{param.textDocument.uri}] " let _ ← IO.setStderr e try let ctx ← initializeWorker param i o e ReaderT.run (r := ctx) mainLoop return 0 catch e => o.writeLspNotification { method := "textDocument/publishDiagnostics" param := { uri := param.textDocument.uri version? := param.textDocument.version diagnostics := #[{ range := ⟨⟨0, 0⟩, ⟨0, 0⟩⟩, severity? := DiagnosticSeverity.error, message := e.toString }] : PublishDiagnosticsParams } } return 1 @[export lean_server_worker_main] def workerMain : IO UInt32 := do let i ← IO.getStdin let o ← IO.getStdout let e ← IO.getStderr try initAndRunWorker i o e catch err => e.putStrLn s!"worker initialization error: {err}" return (1 : UInt32) end Lean.Server.FileWorker
c131f14d7fe5ad5aa94ff4cf6b14d053fc0dd2ba
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/1098.lean
c689743222b48b4e0b5f09898e6a81acf93942aa
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
718
lean
structure FoldImpl (α β : Type u) where γ : Type u x₀ : γ f : γ → α → γ out : γ → β inductive R : FoldImpl α β → FoldImpl α β → Prop where | intro {γ γ' x₀ y₀ f g out out'} : R ⟨γ, x₀, f, out⟩ ⟨γ', y₀, g, out'⟩ #print R #check @R.intro -- @R.intro : ∀ {α β γ γ' : Type u_1} {x₀ : γ} {y₀ : γ'} {f : γ → α → γ} {g : γ' → α → γ'} {out : γ → β} {out' : γ' → β}, -- R { γ := γ, x₀ := x₀, f := f, out := out } { γ := γ', x₀ := y₀, f := g, out := out' } namespace Ex2 inductive R : FoldImpl α β → FoldImpl α β → Prop where | intro : R ⟨γ, x₀, f, out⟩ ⟨γ', y₀, g, out'⟩ #print R end Ex2
2642ea10aa6ceb42626a9f603fdb505a8e9110d3
42c01158c2730cc6ac3e058c1339c18cb90366e2
/M1F/2017-18/Example_Sheet_01/Question_07/M1F_sheet01_solution07.lean
0a89a7010c3f2b899f1a65cd9c1b2b2282405335
[]
no_license
ChrisHughes24/xena
c80d94355d0c2ae8deddda9d01e6d31bc21c30ae
337a0d7c9f0e255e08d6d0a383e303c080c6ec0c
refs/heads/master
1,631,059,898,392
1,511,200,551,000
1,511,200,551,000
111,468,589
1
0
null
null
null
null
UTF-8
Lean
false
false
8,103
lean
import analysis.real xenalib.M1Fstuff -- real numbers live in here in Lean mathlib -- NB you need mathlib installed to get this working. -- of_rat is the injection from the rationals to the reals. -- This question was absurdly difficult for me -- because we need to prove that 1/2 isn't an integer ;-) -- I did it in the end, and called it real_half_not_an_integer -- I put it in the M1Fstuff library. -- #check M1F.real_half_not_an_integer def A : set ℝ := { x | x^2 < 3} def B : set ℝ := {x | (∃ y : ℤ, x = ↑y) ∧ x^2 < 3} def C : set ℝ := {x | x^3 < 3} -- set_option pp.notation false theorem part_a : ¬ (((1/2):ℝ) ∈ A ∩ B) := begin assume H : ((1/2):ℝ) ∈ A ∩ B, have H2: ((1/2):ℝ) ∈ B, exact and.right H, have H3: ∃ y : ℤ, ((1/2):ℝ) = ↑y, exact and.left H2, exact M1F.real_half_not_an_integer H3, end -- set_option pp.all true -- #check @of_rat_mul set_option pp.notation false theorem part_b : of_rat (1/2) ∈ A ∪ B := begin left, -- this now says -- of_rat (1 / 2) ^ 2 < (3:real) -- (after a huge amount of unfolding) unfold has_mem.mem set.mem A set_of, have J : (3:real) = of_rat(3), simp with real_simps, rewrite J,clear J, unfold pow_nat has_pow_nat.pow_nat monoid.pow, have J : (1:real) = of_rat(1), apply of_rat_one, rewrite J,clear J, rewrite (@of_rat_mul (1/2) 1), rewrite (of_rat_mul), apply of_rat_lt_of_rat.mpr, exact dec_trivial end set_option pp.notation true -- set_option pp.all true theorem part_c : ¬ (A ⊆ C) := begin assume H : A ⊆ C, let x := of_rat (3/2), -- strat is to prove x is in A but not C have H2 : x ∈ A, unfold A, unfold has_mem.mem set.mem set_of has_lt.lt preorder.lt,change x with of_rat (3/2), unfold partial_order.lt ordered_comm_monoid.lt discrete_linear_ordered_field.lt has_lt.lt, unfold preorder.lt partial_order.lt lattice.semilattice_inf.lt lattice.lattice.lt, unfold decidable_linear_order.lt decidable_linear_ordered_comm_group.lt, unfold pow_nat has_pow_nat.pow_nat monoid.pow, have J : (3:real) = of_rat(3), simp with real_simps, rewrite J,clear J, have J : (1:real) = of_rat(1), apply of_rat_one, rewrite J,clear J, rewrite (of_rat_mul), rewrite (of_rat_mul), apply of_rat_lt_of_rat.mpr, simp, exact dec_trivial, have H3 : ¬ (x ∈ C), unfold C, unfold has_mem.mem set.mem set_of has_lt.lt preorder.lt,change x with of_rat (3/2), unfold partial_order.lt ordered_comm_monoid.lt discrete_linear_ordered_field.lt has_lt.lt, unfold preorder.lt partial_order.lt lattice.semilattice_inf.lt lattice.lattice.lt, unfold decidable_linear_order.lt decidable_linear_ordered_comm_group.lt, unfold pow_nat has_pow_nat.pow_nat monoid.pow, have J : (3:real) = of_rat(3), simp with real_simps, rewrite J,clear J, have J : (1:real) = of_rat(1), apply of_rat_one, rewrite J,clear J, rewrite (of_rat_mul), rewrite (of_rat_mul), rewrite (of_rat_mul), simp, -- apply of_rat_le_of_rat.mpr, -- exact dec_trivial, -- now have 3/2 in A not C -- trivial, have J : x ∈ C, exact H H2, -- contradiction exact H3 J, -- simp with real_simps, -- unfold pow_nat, -- apply of_rat_lt_of_rat.mpr, -- simp [M1F.of_rat_inj] with real_simps, end -- To do part (d) it's helpful to evaluate B completely. -- def B : set ℝ := {x | (∃ y : ℤ, x = of_rat y) ∧ x^2 < 3} -- #check @eq.subst -- #check rat.coe_int_mul -- #check rat.coe_int_lt -- set_option pp.notation false lemma B_is_minus_one_zero_one (x:ℝ): x ∈ B → (x=((-1):ℝ)) ∨ (x=(0:ℝ)) ∨ (x=(1:ℝ)) := begin assume H : x ∈ B, have H2 : exists y : ℤ, x = (y:ℝ), exact H.left, have H3 : x^2 < 3, exact H.right, cases H2 with y H4, unfold pow_nat has_pow_nat.pow_nat monoid.pow at H3, simp at H3, have H5 : ((y:ℚ):ℝ) * ((y:ℚ):ℝ) < 3, exact (@eq.subst ℝ (λ z, z*z<(3:real)) x (y:ℚ) (by simp [H4]) H3), rw [←rat.cast_mul] at H5, have J : (3:real) = (((3:ℤ):ℚ):ℝ), simp, rw [J,rat.cast_lt,←int.cast_mul,int.cast_lt] at H5, /- rw ←coe_rat_eq_of_rat 3,exact have H6 : of_rat (↑ y * ↑ y) < of_rat 3, exact eq.subst J H5, rewrite of_rat_lt_of_rat at H6, clear H3 H5 J, rewrite eq.symm (rat.coe_int_mul y y) at H6, change (3:rat) with ↑(3:int) at H6, rewrite rat.coe_int_lt at H6, -- Situation now: -- y is an integer, H6 is y*y<3 -- H4 is x=of_rat(y)=y:real, -- and we want to prove x=-1 or 0 or 1. -/ have H6 : y*y<3, exact H5, clear H5, cases y with y m1my, rewrite eq.symm (int.of_nat_mul y y) at H6, have H1:y*y < 3, exact @int.lt_of_coe_nat_lt_coe_nat (y*y) 3 H6, cases y with ys, right,left, exact H4, cases ys with yss, right,right,simp [H4], have H : 4<3, exact calc 4 = 2*2 : dec_trivial ... ≤ 2*(yss+2) : nat.mul_le_mul_left 2 (nat.le_add_left 2 yss) ... ≤ (yss+2)*(yss+2) : nat.mul_le_mul_right (yss+2) (nat.le_add_left 2 yss) ... < 3 : H1, have H2 : ¬ (4<3), exact dec_trivial, exfalso, contradiction, cases m1my with y2, left,simp [H4], exfalso, have H1 : int.nat_abs (int.neg_succ_of_nat (nat.succ y2)) = y2+2, refl, have H2:↑((y2+2)*(y2+2))=(int.neg_succ_of_nat (nat.succ y2))*(int.neg_succ_of_nat (nat.succ y2)), apply @int.nat_abs_mul_self (int.neg_succ_of_nat (nat.succ y2)), have H3: ↑((y2+2)*(y2+2)) < (↑3:int), exact H2 ▸ H6, have H5 : (y2+2)*(y2+2) < 3, exact @int.lt_of_coe_nat_lt_coe_nat ((y2+2)*(y2+2)) 3 H3, have H : 4<3, exact calc 4 = 2*2 : dec_trivial ... ≤ 2*(y2+2) : nat.mul_le_mul_left 2 (nat.le_add_left 2 y2) ... ≤ (y2+2)*(y2+2) : nat.mul_le_mul_right (y2+2) (nat.le_add_left 2 y2) ... < 3 : H5, have H2 : ¬ (4<3), exact dec_trivial, exfalso, contradiction, -- have H3:(y2+2)*(y2+2)<3, -- simp [H1,H6,int.lt_of_coe_nat_lt_coe_nat,int.nat_abs_mul_self] end -- set_option pp.notation false theorem part_d : B ⊆ C := -- B={-1,0,1} so this is true begin intro x, intro H, have H2 : (x=-1) ∨ (x=0) ∨ (x=1), exact B_is_minus_one_zero_one x H, unfold has_mem.mem set.mem C set_of, cases H2 with xm1 xrest, -- need to prove of_rat(-1)^3<3 have H2 : ((-1):ℝ)^3 < 3, unfold pow_nat has_pow_nat.pow_nat monoid.pow, simp with real_simps,exact dec_trivial, -- apply (@eq.subst ℝ (λ x,x^3<3) x (of_rat(-1)) xm1), exact @eq.subst ℝ (λ t, t^3<3) (-1) x (eq.symm xm1) H2, cases xrest with x0 x1, have H2 : of_rat(0)^3 < 3, unfold pow_nat has_pow_nat.pow_nat monoid.pow, simp with real_simps,exact dec_trivial, -- apply (@eq.subst ℝ (λ x,x^3<3) x (of_rat(-1)) xm1), exact @eq.subst ℝ (λ t, t^3<3) (of_rat(0)) x (eq.symm x0) H2, have H2 : of_rat(1)^3 < 3, unfold pow_nat has_pow_nat.pow_nat monoid.pow, simp with real_simps,exact dec_trivial, -- apply (@eq.subst ℝ (λ x,x^3<3) x (of_rat(-1)) xm1), exact @eq.subst ℝ (λ t, t^3<3) (of_rat(1)) x (eq.symm x1) H2, -- simp with real_simps, end -- To do parts e and f it's useful to note that -2 is in C but not A or B. lemma two_in_C : (-2:real) ∈ C := begin unfold has_mem.mem set.mem C pow_nat has_pow_nat.pow_nat monoid.pow set_of, simp with real_simps, repeat {rewrite of_rat_mul}, exact dec_trivial end lemma two_not_in_A : (-2:real) ∉ A := begin unfold has_mem.mem set.mem A pow_nat has_pow_nat.pow_nat monoid.pow set_of, simp with real_simps, end lemma two_not_in_B : (-2:real) ∉ B := begin unfold has_mem.mem set.mem B pow_nat has_pow_nat.pow_nat monoid.pow set_of, simp with real_simps, intros y J, exact dec_trivial, end theorem part_e : ¬ (C ⊆ A ∪ B) := -- not true as C contains -2 begin let x:=(-2:real), have HC : x ∈ C, exact two_in_C, have HnA : x ∉ A, exact two_not_in_A, have HnB : x ∉ B, exact two_not_in_B, intro J, have J2 : x ∈ (A ∪ B), exact (@J x HC), cases J2 with HA HB, contradiction, contradiction, end theorem part_f : ¬ ((A ∩ B) ∪ C = (A ∪ B) ∩ C) := begin let x:=(-2:real), have HC : x ∈ C, exact two_in_C, have HnA : x ∉ A, exact two_not_in_A, have HnB : x ∉ B, exact two_not_in_B, intro H, have H1 : x ∈ (A ∩ B ∪ C), right,exact HC, have H2 : x ∈ (A ∪ B) ∩ C, exact eq.subst H H1, have H3 : x ∈ (A ∪ B), exact H2.left, cases H3 with HA HB, exact HnA HA, exact HnB HB end
b3f537bd98f3b6b7395a49fe34a5a6b315e95b71
fe208a542cea7b2d6d7ff79f94d535f6d11d814a
/src/Dedekind_cuts/framework.lean
790d1605d19111f37775bfc6e5b332a2bf90d7e6
[]
no_license
ImperialCollegeLondon/M1F_room_342_questions
c4b98b14113fe900a7f388762269305faff73e63
63de9a6ab9c27a433039dd5530bc9b10b1d227f7
refs/heads/master
1,585,807,312,561
1,545,232,972,000
1,545,232,972,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
717
lean
import data.rat structure Dedekind_real := (carrier : set ℚ) (nonemp : ∃ a, a ∈ carrier) (nonrat : ∃ a, a ∉ carrier) (down : ∀ p ∈ carrier, ∀ q, q < p → q ∈ carrier) (nomax : ∀ p ∈ carrier, ∃ q ∈ carrier, p < q) notation `ℝ` := Dedekind_real instance : has_coe ℝ (set ℚ) := ⟨λ r, r.carrier⟩ namespace Dedekind_real protected def lt (α β : ℝ) : Prop := (α : set ℚ) ⊂ β -- notation typeclass instance : has_lt ℝ := ⟨Dedekind_real.lt⟩ #check λ a b : ℝ, a < b -- I can use "<" notation now. -- more definitions of stuff like addition go here in the namespace end Dedekind_real open Dedekind_real -- questions about reals go here, outside the namespace
4c1b2a563c7c2742d24b7a5c3d2af52fc0d69176
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/field_theory/finiteness.lean
55746cd353899fa4a3e78536b71c6e030eac282c
[ "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,133
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 ring_theory.finiteness import linear_algebra.dimension /-! # A module over a division ring is noetherian if and only if it is finite. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ universes u v open_locale classical cardinal open cardinal submodule module function namespace is_noetherian variables {K : Type u} {V : Type v} [division_ring K] [add_comm_group V] [module K V] /-- A module over a division ring is noetherian if and only if its dimension (as a cardinal) is strictly less than the first infinite cardinal `ℵ₀`. -/ lemma iff_rank_lt_aleph_0 : is_noetherian K V ↔ module.rank K V < ℵ₀ := begin let b := basis.of_vector_space K V, rw [← b.mk_eq_rank'', lt_aleph_0_iff_set_finite], split, { introI, exact finite_of_linear_independent (basis.of_vector_space_index.linear_independent K V) }, { assume hbfinite, refine @is_noetherian_of_linear_equiv K (⊤ : submodule K V) V _ _ _ _ _ (linear_equiv.of_top _ rfl) (id _), refine is_noetherian_of_fg_of_noetherian _ ⟨set.finite.to_finset hbfinite, _⟩, rw [set.finite.coe_to_finset, ← b.span_eq, basis.coe_of_vector_space, subtype.range_coe] } end variables (K V) /-- The dimension of a noetherian module over a division ring, as a cardinal, is strictly less than the first infinite cardinal `ℵ₀`. -/ lemma rank_lt_aleph_0 : ∀ [is_noetherian K V], module.rank K V < ℵ₀ := is_noetherian.iff_rank_lt_aleph_0.1 variables {K V} /-- In a noetherian module over a division ring, all bases are indexed by a finite type. -/ noncomputable def fintype_basis_index {ι : Type*} [is_noetherian K V] (b : basis ι K V) : fintype ι := b.fintype_index_of_rank_lt_aleph_0 (rank_lt_aleph_0 K V) /-- In a noetherian module over a division ring, `basis.of_vector_space` is indexed by a finite type. -/ noncomputable instance [is_noetherian K V] : fintype (basis.of_vector_space_index K V) := fintype_basis_index (basis.of_vector_space K V) /-- In a noetherian module over a division ring, if a basis is indexed by a set, that set is finite. -/ lemma finite_basis_index {ι : Type*} {s : set ι} [is_noetherian K V] (b : basis s K V) : s.finite := b.finite_index_of_rank_lt_aleph_0 (rank_lt_aleph_0 K V) variables (K V) /-- In a noetherian module over a division ring, there exists a finite basis. This is the indexing `finset`. -/ noncomputable def finset_basis_index [is_noetherian K V] : finset V := (finite_basis_index (basis.of_vector_space K V)).to_finset @[simp] lemma coe_finset_basis_index [is_noetherian K V] : (↑(finset_basis_index K V) : set V) = basis.of_vector_space_index K V := set.finite.coe_to_finset _ @[simp] lemma coe_sort_finset_basis_index [is_noetherian K V] : ((finset_basis_index K V) : Type*) = basis.of_vector_space_index K V := set.finite.coe_sort_to_finset _ /-- In a noetherian module over a division ring, there exists a finite basis. This is indexed by the `finset` `finite_dimensional.finset_basis_index`. This is in contrast to the result `finite_basis_index (basis.of_vector_space K V)`, which provides a set and a `set.finite`. -/ noncomputable def finset_basis [is_noetherian K V] : basis (finset_basis_index K V) K V := (basis.of_vector_space K V).reindex (by simp) @[simp] lemma range_finset_basis [is_noetherian K V] : set.range (finset_basis K V) = basis.of_vector_space_index K V := by rw [finset_basis, basis.range_reindex, basis.range_of_vector_space] variables {K V} /-- A module over a division ring is noetherian if and only if it is finitely generated. -/ lemma iff_fg : is_noetherian K V ↔ module.finite K V := begin split, { introI h, exact ⟨⟨finset_basis_index K V, by { convert (finset_basis K V).span_eq, simp }⟩⟩ }, { rintros ⟨s, hs⟩, rw [is_noetherian.iff_rank_lt_aleph_0, ← rank_top, ← hs], exact lt_of_le_of_lt (rank_span_le _) s.finite_to_set.lt_aleph_0 } end end is_noetherian
daedef25cef80e19151ec6bcc907a0dfc2141bd9
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/tactic/norm_num.lean
ba2a63259a9c07a0bcd75a264f531a329cf16c22
[ "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
59,428
lean
/- Copyright (c) 2017 Simon Hudon All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Mario Carneiro -/ import data.rat.cast import data.rat.meta_defs /-! # `norm_num` Evaluating arithmetic expressions including `*`, `+`, `-`, `^`, `≤`. -/ universes u v w namespace tactic /-- Reflexivity conversion: given `e` returns `(e, ⊢ e = e)` -/ meta def refl_conv (e : expr) : tactic (expr × expr) := do p ← mk_eq_refl e, return (e, p) /-- Transitivity conversion: given two conversions (which take an expression `e` and returns `(e', ⊢ e = e')`), produces another conversion that combines them with transitivity, treating failures as reflexivity conversions. -/ meta def trans_conv (t₁ t₂ : expr → tactic (expr × expr)) (e : expr) : tactic (expr × expr) := (do (e₁, p₁) ← t₁ e, (do (e₂, p₂) ← t₂ e₁, p ← mk_eq_trans p₁ p₂, return (e₂, p)) <|> return (e₁, p₁)) <|> t₂ e namespace instance_cache /-- Faster version of `mk_app ``bit0 [e]`. -/ meta def mk_bit0 (c : instance_cache) (e : expr) : tactic (instance_cache × expr) := do (c, ai) ← c.get ``has_add, return (c, (expr.const ``bit0 [c.univ]).mk_app [c.α, ai, e]) /-- Faster version of `mk_app ``bit1 [e]`. -/ meta def mk_bit1 (c : instance_cache) (e : expr) : tactic (instance_cache × expr) := do (c, ai) ← c.get ``has_add, (c, oi) ← c.get ``has_one, return (c, (expr.const ``bit1 [c.univ]).mk_app [c.α, oi, ai, e]) end instance_cache end tactic open tactic namespace norm_num variable {α : Type u} lemma subst_into_add {α} [has_add α] (l r tl tr t) (prl : (l : α) = tl) (prr : r = tr) (prt : tl + tr = t) : l + r = t := by rw [prl, prr, prt] lemma subst_into_mul {α} [has_mul α] (l r tl tr t) (prl : (l : α) = tl) (prr : r = tr) (prt : tl * tr = t) : l * r = t := by rw [prl, prr, prt] lemma subst_into_neg {α} [has_neg α] (a ta t : α) (pra : a = ta) (prt : -ta = t) : -a = t := by simp [pra, prt] /-- The result type of `match_numeral`, either `0`, `1`, or a top level decomposition of `bit0 e` or `bit1 e`. The `other` case means it is not a numeral. -/ meta inductive match_numeral_result | zero | one | bit0 (e : expr) | bit1 (e : expr) | other /-- Unfold the top level constructor of the numeral expression. -/ meta def match_numeral : expr → match_numeral_result | `(bit0 %%e) := match_numeral_result.bit0 e | `(bit1 %%e) := match_numeral_result.bit1 e | `(@has_zero.zero _ _) := match_numeral_result.zero | `(@has_one.one _ _) := match_numeral_result.one | _ := match_numeral_result.other theorem zero_succ {α} [semiring α] : (0 + 1 : α) = 1 := zero_add _ theorem one_succ {α} [semiring α] : (1 + 1 : α) = 2 := rfl theorem bit0_succ {α} [semiring α] (a : α) : bit0 a + 1 = bit1 a := rfl theorem bit1_succ {α} [semiring α] (a b : α) (h : a + 1 = b) : bit1 a + 1 = bit0 b := h ▸ by simp [bit1, bit0, add_left_comm, add_assoc] section open match_numeral_result /-- Given `a`, `b` natural numerals, proves `⊢ a + 1 = b`, assuming that this is provable. (It may prove garbage instead of failing if `a + 1 = b` is false.) -/ meta def prove_succ : instance_cache → expr → expr → tactic (instance_cache × expr) | c e r := match match_numeral e with | zero := c.mk_app ``zero_succ [] | one := c.mk_app ``one_succ [] | bit0 e := c.mk_app ``bit0_succ [e] | bit1 e := do let r := r.app_arg, (c, p) ← prove_succ c e r, c.mk_app ``bit1_succ [e, r, p] | _ := failed end end theorem zero_adc {α} [semiring α] (a b : α) (h : a + 1 = b) : 0 + a + 1 = b := by rwa zero_add theorem adc_zero {α} [semiring α] (a b : α) (h : a + 1 = b) : a + 0 + 1 = b := by rwa add_zero theorem one_add {α} [semiring α] (a b : α) (h : a + 1 = b) : 1 + a = b := by rwa add_comm theorem add_bit0_bit0 {α} [semiring α] (a b c : α) (h : a + b = c) : bit0 a + bit0 b = bit0 c := h ▸ by simp [bit0, add_left_comm, add_assoc] theorem add_bit0_bit1 {α} [semiring α] (a b c : α) (h : a + b = c) : bit0 a + bit1 b = bit1 c := h ▸ by simp [bit0, bit1, add_left_comm, add_assoc] theorem add_bit1_bit0 {α} [semiring α] (a b c : α) (h : a + b = c) : bit1 a + bit0 b = bit1 c := h ▸ by simp [bit0, bit1, add_left_comm, add_comm] theorem add_bit1_bit1 {α} [semiring α] (a b c : α) (h : a + b + 1 = c) : bit1 a + bit1 b = bit0 c := h ▸ by simp [bit0, bit1, add_left_comm, add_comm] theorem adc_one_one {α} [semiring α] : (1 + 1 + 1 : α) = 3 := rfl theorem adc_bit0_one {α} [semiring α] (a b : α) (h : a + 1 = b) : bit0 a + 1 + 1 = bit0 b := h ▸ by simp [bit0, add_left_comm, add_assoc] theorem adc_one_bit0 {α} [semiring α] (a b : α) (h : a + 1 = b) : 1 + bit0 a + 1 = bit0 b := h ▸ by simp [bit0, add_left_comm, add_assoc] theorem adc_bit1_one {α} [semiring α] (a b : α) (h : a + 1 = b) : bit1 a + 1 + 1 = bit1 b := h ▸ by simp [bit1, bit0, add_left_comm, add_assoc] theorem adc_one_bit1 {α} [semiring α] (a b : α) (h : a + 1 = b) : 1 + bit1 a + 1 = bit1 b := h ▸ by simp [bit1, bit0, add_left_comm, add_assoc] theorem adc_bit0_bit0 {α} [semiring α] (a b c : α) (h : a + b = c) : bit0 a + bit0 b + 1 = bit1 c := h ▸ by simp [bit1, bit0, add_left_comm, add_assoc] theorem adc_bit1_bit0 {α} [semiring α] (a b c : α) (h : a + b + 1 = c) : bit1 a + bit0 b + 1 = bit0 c := h ▸ by simp [bit1, bit0, add_left_comm, add_assoc] theorem adc_bit0_bit1 {α} [semiring α] (a b c : α) (h : a + b + 1 = c) : bit0 a + bit1 b + 1 = bit0 c := h ▸ by simp [bit1, bit0, add_left_comm, add_assoc] theorem adc_bit1_bit1 {α} [semiring α] (a b c : α) (h : a + b + 1 = c) : bit1 a + bit1 b + 1 = bit1 c := h ▸ by simp [bit1, bit0, add_left_comm, add_assoc] section open match_numeral_result meta mutual def prove_add_nat, prove_adc_nat with prove_add_nat : instance_cache → expr → expr → expr → tactic (instance_cache × expr) | c a b r := do match match_numeral a, match_numeral b with | zero, _ := c.mk_app ``zero_add [b] | _, zero := c.mk_app ``add_zero [a] | _, one := prove_succ c a r | one, _ := do (c, p) ← prove_succ c b r, c.mk_app ``one_add [b, r, p] | bit0 a, bit0 b := do let r := r.app_arg, (c, p) ← prove_add_nat c a b r, c.mk_app ``add_bit0_bit0 [a, b, r, p] | bit0 a, bit1 b := do let r := r.app_arg, (c, p) ← prove_add_nat c a b r, c.mk_app ``add_bit0_bit1 [a, b, r, p] | bit1 a, bit0 b := do let r := r.app_arg, (c, p) ← prove_add_nat c a b r, c.mk_app ``add_bit1_bit0 [a, b, r, p] | bit1 a, bit1 b := do let r := r.app_arg, (c, p) ← prove_adc_nat c a b r, c.mk_app ``add_bit1_bit1 [a, b, r, p] | _, _ := failed end with prove_adc_nat : instance_cache → expr → expr → expr → tactic (instance_cache × expr) | c a b r := do match match_numeral a, match_numeral b with | zero, _ := do (c, p) ← prove_succ c b r, c.mk_app ``zero_adc [b, r, p] | _, zero := do (c, p) ← prove_succ c b r, c.mk_app ``adc_zero [b, r, p] | one, one := c.mk_app ``adc_one_one [] | bit0 a, one := do let r := r.app_arg, (c, p) ← prove_succ c a r, c.mk_app ``adc_bit0_one [a, r, p] | one, bit0 b := do let r := r.app_arg, (c, p) ← prove_succ c b r, c.mk_app ``adc_one_bit0 [b, r, p] | bit1 a, one := do let r := r.app_arg, (c, p) ← prove_succ c a r, c.mk_app ``adc_bit1_one [a, r, p] | one, bit1 b := do let r := r.app_arg, (c, p) ← prove_succ c b r, c.mk_app ``adc_one_bit1 [b, r, p] | bit0 a, bit0 b := do let r := r.app_arg, (c, p) ← prove_add_nat c a b r, c.mk_app ``adc_bit0_bit0 [a, b, r, p] | bit0 a, bit1 b := do let r := r.app_arg, (c, p) ← prove_adc_nat c a b r, c.mk_app ``adc_bit0_bit1 [a, b, r, p] | bit1 a, bit0 b := do let r := r.app_arg, (c, p) ← prove_adc_nat c a b r, c.mk_app ``adc_bit1_bit0 [a, b, r, p] | bit1 a, bit1 b := do let r := r.app_arg, (c, p) ← prove_adc_nat c a b r, c.mk_app ``adc_bit1_bit1 [a, b, r, p] | _, _ := failed end /-- Given `a`,`b`,`r` natural numerals, proves `⊢ a + b = r`. -/ add_decl_doc prove_add_nat /-- Given `a`,`b`,`r` natural numerals, proves `⊢ a + b + 1 = r`. -/ add_decl_doc prove_adc_nat /-- Given `a`,`b` natural numerals, returns `(r, ⊢ a + b = r)`. -/ meta def prove_add_nat' (c : instance_cache) (a b : expr) : tactic (instance_cache × expr × expr) := do na ← a.to_nat, nb ← b.to_nat, (c, r) ← c.of_nat (na + nb), (c, p) ← prove_add_nat c a b r, return (c, r, p) end theorem bit0_mul {α} [semiring α] (a b c : α) (h : a * b = c) : bit0 a * b = bit0 c := h ▸ by simp [bit0, add_mul] theorem mul_bit0' {α} [semiring α] (a b c : α) (h : a * b = c) : a * bit0 b = bit0 c := h ▸ by simp [bit0, mul_add] theorem mul_bit0_bit0 {α} [semiring α] (a b c : α) (h : a * b = c) : bit0 a * bit0 b = bit0 (bit0 c) := bit0_mul _ _ _ (mul_bit0' _ _ _ h) theorem mul_bit1_bit1 {α} [semiring α] (a b c d e : α) (hc : a * b = c) (hd : a + b = d) (he : bit0 c + d = e) : bit1 a * bit1 b = bit1 e := by rw [← he, ← hd, ← hc]; simp [bit1, bit0, mul_add, add_mul, add_left_comm, add_assoc] section open match_numeral_result /-- Given `a`,`b` natural numerals, returns `(r, ⊢ a * b = r)`. -/ meta def prove_mul_nat : instance_cache → expr → expr → tactic (instance_cache × expr × expr) | ic a b := match match_numeral a, match_numeral b with | zero, _ := do (ic, z) ← ic.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``zero_mul [b], return (ic, z, p) | _, zero := do (ic, z) ← ic.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``mul_zero [a], return (ic, z, p) | one, _ := do (ic, p) ← ic.mk_app ``one_mul [b], return (ic, b, p) | _, one := do (ic, p) ← ic.mk_app ``mul_one [a], return (ic, a, p) | bit0 a, bit0 b := do (ic, c, p) ← prove_mul_nat ic a b, (ic, p) ← ic.mk_app ``mul_bit0_bit0 [a, b, c, p], (ic, c') ← ic.mk_bit0 c, (ic, c') ← ic.mk_bit0 c', return (ic, c', p) | bit0 a, _ := do (ic, c, p) ← prove_mul_nat ic a b, (ic, p) ← ic.mk_app ``bit0_mul [a, b, c, p], (ic, c') ← ic.mk_bit0 c, return (ic, c', p) | _, bit0 b := do (ic, c, p) ← prove_mul_nat ic a b, (ic, p) ← ic.mk_app ``mul_bit0' [a, b, c, p], (ic, c') ← ic.mk_bit0 c, return (ic, c', p) | bit1 a, bit1 b := do (ic, c, pc) ← prove_mul_nat ic a b, (ic, d, pd) ← prove_add_nat' ic a b, (ic, c') ← ic.mk_bit0 c, (ic, e, pe) ← prove_add_nat' ic c' d, (ic, p) ← ic.mk_app ``mul_bit1_bit1 [a, b, c, d, e, pc, pd, pe], (ic, e') ← ic.mk_bit1 e, return (ic, e', p) | _, _ := failed end end section open match_numeral_result /-- Given `a` a positive natural numeral, returns `⊢ 0 < a`. -/ meta def prove_pos_nat (c : instance_cache) : expr → tactic (instance_cache × expr) | e := match match_numeral e with | one := c.mk_app ``zero_lt_one' [] | bit0 e := do (c, p) ← prove_pos_nat e, c.mk_app ``bit0_pos [e, p] | bit1 e := do (c, p) ← prove_pos_nat e, c.mk_app ``bit1_pos' [e, p] | _ := failed end end /-- Given `a` a rational numeral, returns `⊢ 0 < a`. -/ meta def prove_pos (c : instance_cache) : expr → tactic (instance_cache × expr) | `(%%e₁ / %%e₂) := do (c, p₁) ← prove_pos_nat c e₁, (c, p₂) ← prove_pos_nat c e₂, c.mk_app ``div_pos [e₁, e₂, p₁, p₂] | e := prove_pos_nat c e /-- `match_neg (- e) = some e`, otherwise `none` -/ meta def match_neg : expr → option expr | `(- %%e) := some e | _ := none /-- `match_sign (- e) = inl e`, `match_sign 0 = inr ff`, otherwise `inr tt` -/ meta def match_sign : expr → expr ⊕ bool | `(- %%e) := sum.inl e | `(has_zero.zero) := sum.inr ff | _ := sum.inr tt theorem ne_zero_of_pos {α} [ordered_add_comm_group α] (a : α) : 0 < a → a ≠ 0 := ne_of_gt theorem ne_zero_neg {α} [add_group α] (a : α) : a ≠ 0 → -a ≠ 0 := mt neg_eq_zero.1 /-- Given `a` a rational numeral, returns `⊢ a ≠ 0`. -/ meta def prove_ne_zero' (c : instance_cache) : expr → tactic (instance_cache × expr) | a := match match_neg a with | some a := do (c, p) ← prove_ne_zero' a, c.mk_app ``ne_zero_neg [a, p] | none := do (c, p) ← prove_pos c a, c.mk_app ``ne_zero_of_pos [a, p] end theorem clear_denom_div {α} [division_ring α] (a b b' c d : α) (h₀ : b ≠ 0) (h₁ : b * b' = d) (h₂ : a * b' = c) : (a / b) * d = c := by rwa [← h₁, ← mul_assoc, div_mul_cancel _ h₀] /-- Given `a` nonnegative rational and `d` a natural number, returns `(b, ⊢ a * d = b)`. (`d` should be a multiple of the denominator of `a`, so that `b` is a natural number.) -/ meta def prove_clear_denom' (prove_ne_zero : instance_cache → expr → ℚ → tactic (instance_cache × expr)) (c : instance_cache) (a d : expr) (na : ℚ) (nd : ℕ) : tactic (instance_cache × expr × expr) := if na.denom = 1 then prove_mul_nat c a d else do [_, _, a, b] ← return a.get_app_args, (c, b') ← c.of_nat (nd / na.denom), (c, p₀) ← prove_ne_zero c b (rat.of_int na.denom), (c, _, p₁) ← prove_mul_nat c b b', (c, r, p₂) ← prove_mul_nat c a b', (c, p) ← c.mk_app ``clear_denom_div [a, b, b', r, d, p₀, p₁, p₂], return (c, r, p) theorem nonneg_pos {α} [ordered_cancel_add_comm_monoid α] (a : α) : 0 < a → 0 ≤ a := le_of_lt theorem lt_one_bit0 {α} [linear_ordered_semiring α] (a : α) (h : 1 ≤ a) : 1 < bit0 a := lt_of_lt_of_le one_lt_two (bit0_le_bit0.2 h) theorem lt_one_bit1 {α} [linear_ordered_semiring α] (a : α) (h : 0 < a) : 1 < bit1 a := one_lt_bit1.2 h theorem lt_bit0_bit0 {α} [linear_ordered_semiring α] (a b : α) : a < b → bit0 a < bit0 b := bit0_lt_bit0.2 theorem lt_bit0_bit1 {α} [linear_ordered_semiring α] (a b : α) (h : a ≤ b) : bit0 a < bit1 b := lt_of_le_of_lt (bit0_le_bit0.2 h) (lt_add_one _) theorem lt_bit1_bit0 {α} [linear_ordered_semiring α] (a b : α) (h : a + 1 ≤ b) : bit1 a < bit0 b := lt_of_lt_of_le (by simp [bit0, bit1, zero_lt_one, add_assoc]) (bit0_le_bit0.2 h) theorem lt_bit1_bit1 {α} [linear_ordered_semiring α] (a b : α) : a < b → bit1 a < bit1 b := bit1_lt_bit1.2 theorem le_one_bit0 {α} [linear_ordered_semiring α] (a : α) (h : 1 ≤ a) : 1 ≤ bit0 a := le_of_lt (lt_one_bit0 _ h) -- deliberately strong hypothesis because bit1 0 is not a numeral theorem le_one_bit1 {α} [linear_ordered_semiring α] (a : α) (h : 0 < a) : 1 ≤ bit1 a := le_of_lt (lt_one_bit1 _ h) theorem le_bit0_bit0 {α} [linear_ordered_semiring α] (a b : α) : a ≤ b → bit0 a ≤ bit0 b := bit0_le_bit0.2 theorem le_bit0_bit1 {α} [linear_ordered_semiring α] (a b : α) (h : a ≤ b) : bit0 a ≤ bit1 b := le_of_lt (lt_bit0_bit1 _ _ h) theorem le_bit1_bit0 {α} [linear_ordered_semiring α] (a b : α) (h : a + 1 ≤ b) : bit1 a ≤ bit0 b := le_of_lt (lt_bit1_bit0 _ _ h) theorem le_bit1_bit1 {α} [linear_ordered_semiring α] (a b : α) : a ≤ b → bit1 a ≤ bit1 b := bit1_le_bit1.2 theorem sle_one_bit0 {α} [linear_ordered_semiring α] (a : α) : 1 ≤ a → 1 + 1 ≤ bit0 a := bit0_le_bit0.2 theorem sle_one_bit1 {α} [linear_ordered_semiring α] (a : α) : 1 ≤ a → 1 + 1 ≤ bit1 a := le_bit0_bit1 _ _ theorem sle_bit0_bit0 {α} [linear_ordered_semiring α] (a b : α) : a + 1 ≤ b → bit0 a + 1 ≤ bit0 b := le_bit1_bit0 _ _ theorem sle_bit0_bit1 {α} [linear_ordered_semiring α] (a b : α) (h : a ≤ b) : bit0 a + 1 ≤ bit1 b := bit1_le_bit1.2 h theorem sle_bit1_bit0 {α} [linear_ordered_semiring α] (a b : α) (h : a + 1 ≤ b) : bit1 a + 1 ≤ bit0 b := (bit1_succ a _ rfl).symm ▸ bit0_le_bit0.2 h theorem sle_bit1_bit1 {α} [linear_ordered_semiring α] (a b : α) (h : a + 1 ≤ b) : bit1 a + 1 ≤ bit1 b := (bit1_succ a _ rfl).symm ▸ le_bit0_bit1 _ _ h /-- Given `a` a rational numeral, returns `⊢ 0 ≤ a`. -/ meta def prove_nonneg (ic : instance_cache) : expr → tactic (instance_cache × expr) | e@`(has_zero.zero) := ic.mk_app ``le_refl [e] | e := if ic.α = `(ℕ) then return (ic, `(nat.zero_le).mk_app [e]) else do (ic, p) ← prove_pos ic e, ic.mk_app ``nonneg_pos [e, p] section open match_numeral_result /-- Given `a` a rational numeral, returns `⊢ 1 ≤ a`. -/ meta def prove_one_le_nat (ic : instance_cache) : expr → tactic (instance_cache × expr) | a := match match_numeral a with | one := ic.mk_app ``le_refl [a] | bit0 a := do (ic, p) ← prove_one_le_nat a, ic.mk_app ``le_one_bit0 [a, p] | bit1 a := do (ic, p) ← prove_pos_nat ic a, ic.mk_app ``le_one_bit1 [a, p] | _ := failed end meta mutual def prove_le_nat, prove_sle_nat (ic : instance_cache) with prove_le_nat : expr → expr → tactic (instance_cache × expr) | a b := if a = b then ic.mk_app ``le_refl [a] else match match_numeral a, match_numeral b with | zero, _ := prove_nonneg ic b | one, bit0 b := do (ic, p) ← prove_one_le_nat ic b, ic.mk_app ``le_one_bit0 [b, p] | one, bit1 b := do (ic, p) ← prove_pos_nat ic b, ic.mk_app ``le_one_bit1 [b, p] | bit0 a, bit0 b := do (ic, p) ← prove_le_nat a b, ic.mk_app ``le_bit0_bit0 [a, b, p] | bit0 a, bit1 b := do (ic, p) ← prove_le_nat a b, ic.mk_app ``le_bit0_bit1 [a, b, p] | bit1 a, bit0 b := do (ic, p) ← prove_sle_nat a b, ic.mk_app ``le_bit1_bit0 [a, b, p] | bit1 a, bit1 b := do (ic, p) ← prove_le_nat a b, ic.mk_app ``le_bit1_bit1 [a, b, p] | _, _ := failed end with prove_sle_nat : expr → expr → tactic (instance_cache × expr) | a b := match match_numeral a, match_numeral b with | zero, _ := prove_nonneg ic b | one, bit0 b := do (ic, p) ← prove_one_le_nat ic b, ic.mk_app ``sle_one_bit0 [b, p] | one, bit1 b := do (ic, p) ← prove_one_le_nat ic b, ic.mk_app ``sle_one_bit1 [b, p] | bit0 a, bit0 b := do (ic, p) ← prove_sle_nat a b, ic.mk_app ``sle_bit0_bit0 [a, b, p] | bit0 a, bit1 b := do (ic, p) ← prove_le_nat a b, ic.mk_app ``sle_bit0_bit1 [a, b, p] | bit1 a, bit0 b := do (ic, p) ← prove_sle_nat a b, ic.mk_app ``sle_bit1_bit0 [a, b, p] | bit1 a, bit1 b := do (ic, p) ← prove_sle_nat a b, ic.mk_app ``sle_bit1_bit1 [a, b, p] | _, _ := failed end /-- Given `a`,`b` natural numerals, proves `⊢ a ≤ b`. -/ add_decl_doc prove_le_nat /-- Given `a`,`b` natural numerals, proves `⊢ a + 1 ≤ b`. -/ add_decl_doc prove_sle_nat /-- Given `a`,`b` natural numerals, proves `⊢ a < b`. -/ meta def prove_lt_nat (ic : instance_cache) : expr → expr → tactic (instance_cache × expr) | a b := match match_numeral a, match_numeral b with | zero, _ := prove_pos ic b | one, bit0 b := do (ic, p) ← prove_one_le_nat ic b, ic.mk_app ``lt_one_bit0 [b, p] | one, bit1 b := do (ic, p) ← prove_pos_nat ic b, ic.mk_app ``lt_one_bit1 [b, p] | bit0 a, bit0 b := do (ic, p) ← prove_lt_nat a b, ic.mk_app ``lt_bit0_bit0 [a, b, p] | bit0 a, bit1 b := do (ic, p) ← prove_le_nat ic a b, ic.mk_app ``lt_bit0_bit1 [a, b, p] | bit1 a, bit0 b := do (ic, p) ← prove_sle_nat ic a b, ic.mk_app ``lt_bit1_bit0 [a, b, p] | bit1 a, bit1 b := do (ic, p) ← prove_lt_nat a b, ic.mk_app ``lt_bit1_bit1 [a, b, p] | _, _ := failed end end theorem clear_denom_lt {α} [linear_ordered_semiring α] (a a' b b' d : α) (h₀ : 0 < d) (ha : a * d = a') (hb : b * d = b') (h : a' < b') : a < b := lt_of_mul_lt_mul_right (by rwa [ha, hb]) (le_of_lt h₀) /-- Given `a`,`b` nonnegative rational numerals, proves `⊢ a < b`. -/ meta def prove_lt_nonneg_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr) := if na.denom = 1 ∧ nb.denom = 1 then prove_lt_nat ic a b else do let nd := na.denom.lcm nb.denom, (ic, d) ← ic.of_nat nd, (ic, p₀) ← prove_pos ic d, (ic, a', pa) ← prove_clear_denom' (λ ic e _, prove_ne_zero' ic e) ic a d na nd, (ic, b', pb) ← prove_clear_denom' (λ ic e _, prove_ne_zero' ic e) ic b d nb nd, (ic, p) ← prove_lt_nat ic a' b', ic.mk_app ``clear_denom_lt [a, a', b, b', d, p₀, pa, pb, p] lemma lt_neg_pos {α} [ordered_add_comm_group α] (a b : α) (ha : 0 < a) (hb : 0 < b) : -a < b := lt_trans (neg_neg_of_pos ha) hb /-- Given `a`,`b` rational numerals, proves `⊢ a < b`. -/ meta def prove_lt_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr) := match match_sign a, match_sign b with | sum.inl a, sum.inl b := do (ic, p) ← prove_lt_nonneg_rat ic a b (-na) (-nb), ic.mk_app ``neg_lt_neg [a, b, p] | sum.inl a, sum.inr ff := do (ic, p) ← prove_pos ic a, ic.mk_app ``neg_neg_of_pos [a, p] | sum.inl a, sum.inr tt := do (ic, pa) ← prove_pos ic a, (ic, pb) ← prove_pos ic b, ic.mk_app ``lt_neg_pos [a, b, pa, pb] | sum.inr ff, _ := prove_pos ic b | sum.inr tt, _ := prove_lt_nonneg_rat ic a b na nb end theorem clear_denom_le {α} [linear_ordered_semiring α] (a a' b b' d : α) (h₀ : 0 < d) (ha : a * d = a') (hb : b * d = b') (h : a' ≤ b') : a ≤ b := le_of_mul_le_mul_right (by rwa [ha, hb]) h₀ /-- Given `a`,`b` nonnegative rational numerals, proves `⊢ a ≤ b`. -/ meta def prove_le_nonneg_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr) := if na.denom = 1 ∧ nb.denom = 1 then prove_le_nat ic a b else do let nd := na.denom.lcm nb.denom, (ic, d) ← ic.of_nat nd, (ic, p₀) ← prove_pos ic d, (ic, a', pa) ← prove_clear_denom' (λ ic e _, prove_ne_zero' ic e) ic a d na nd, (ic, b', pb) ← prove_clear_denom' (λ ic e _, prove_ne_zero' ic e) ic b d nb nd, (ic, p) ← prove_le_nat ic a' b', ic.mk_app ``clear_denom_le [a, a', b, b', d, p₀, pa, pb, p] lemma le_neg_pos {α} [ordered_add_comm_group α] (a b : α) (ha : 0 ≤ a) (hb : 0 ≤ b) : -a ≤ b := le_trans (neg_nonpos_of_nonneg ha) hb /-- Given `a`,`b` rational numerals, proves `⊢ a ≤ b`. -/ meta def prove_le_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr) := match match_sign a, match_sign b with | sum.inl a, sum.inl b := do (ic, p) ← prove_le_nonneg_rat ic a b (-na) (-nb), ic.mk_app ``neg_le_neg [a, b, p] | sum.inl a, sum.inr ff := do (ic, p) ← prove_nonneg ic a, ic.mk_app ``neg_nonpos_of_nonneg [a, p] | sum.inl a, sum.inr tt := do (ic, pa) ← prove_nonneg ic a, (ic, pb) ← prove_nonneg ic b, ic.mk_app ``le_neg_pos [a, b, pa, pb] | sum.inr ff, _ := prove_nonneg ic b | sum.inr tt, _ := prove_le_nonneg_rat ic a b na nb end /-- Given `a`,`b` rational numerals, proves `⊢ a ≠ b`. This version tries to prove `⊢ a < b` or `⊢ b < a`, and so is not appropriate for types without an order relation. -/ meta def prove_ne_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr) := if na < nb then do (ic, p) ← prove_lt_rat ic a b na nb, ic.mk_app ``ne_of_lt [a, b, p] else do (ic, p) ← prove_lt_rat ic b a nb na, ic.mk_app ``ne_of_gt [a, b, p] theorem nat_cast_zero {α} [semiring α] : ↑(0 : ℕ) = (0 : α) := nat.cast_zero theorem nat_cast_one {α} [semiring α] : ↑(1 : ℕ) = (1 : α) := nat.cast_one theorem nat_cast_bit0 {α} [semiring α] (a : ℕ) (a' : α) (h : ↑a = a') : ↑(bit0 a) = bit0 a' := h ▸ nat.cast_bit0 _ theorem nat_cast_bit1 {α} [semiring α] (a : ℕ) (a' : α) (h : ↑a = a') : ↑(bit1 a) = bit1 a' := h ▸ nat.cast_bit1 _ theorem int_cast_zero {α} [ring α] : ↑(0 : ℤ) = (0 : α) := int.cast_zero theorem int_cast_one {α} [ring α] : ↑(1 : ℤ) = (1 : α) := int.cast_one theorem int_cast_bit0 {α} [ring α] (a : ℤ) (a' : α) (h : ↑a = a') : ↑(bit0 a) = bit0 a' := h ▸ int.cast_bit0 _ theorem int_cast_bit1 {α} [ring α] (a : ℤ) (a' : α) (h : ↑a = a') : ↑(bit1 a) = bit1 a' := h ▸ int.cast_bit1 _ theorem rat_cast_bit0 {α} [division_ring α] [char_zero α] (a : ℚ) (a' : α) (h : ↑a = a') : ↑(bit0 a) = bit0 a' := h ▸ rat.cast_bit0 _ theorem rat_cast_bit1 {α} [division_ring α] [char_zero α] (a : ℚ) (a' : α) (h : ↑a = a') : ↑(bit1 a) = bit1 a' := h ▸ rat.cast_bit1 _ /-- Given `a' : α` a natural numeral, returns `(a : ℕ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ meta def prove_nat_uncast (ic nc : instance_cache) : ∀ (a' : expr), tactic (instance_cache × instance_cache × expr × expr) | a' := match match_numeral a' with | match_numeral_result.zero := do (nc, e) ← nc.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``nat_cast_zero [], return (ic, nc, e, p) | match_numeral_result.one := do (nc, e) ← nc.mk_app ``has_one.one [], (ic, p) ← ic.mk_app ``nat_cast_one [], return (ic, nc, e, p) | match_numeral_result.bit0 a' := do (ic, nc, a, p) ← prove_nat_uncast a', (nc, a0) ← nc.mk_bit0 a, (ic, p) ← ic.mk_app ``nat_cast_bit0 [a, a', p], return (ic, nc, a0, p) | match_numeral_result.bit1 a' := do (ic, nc, a, p) ← prove_nat_uncast a', (nc, a1) ← nc.mk_bit1 a, (ic, p) ← ic.mk_app ``nat_cast_bit1 [a, a', p], return (ic, nc, a1, p) | _ := failed end /-- Given `a' : α` a natural numeral, returns `(a : ℤ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ meta def prove_int_uncast_nat (ic zc : instance_cache) : ∀ (a' : expr), tactic (instance_cache × instance_cache × expr × expr) | a' := match match_numeral a' with | match_numeral_result.zero := do (zc, e) ← zc.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``int_cast_zero [], return (ic, zc, e, p) | match_numeral_result.one := do (zc, e) ← zc.mk_app ``has_one.one [], (ic, p) ← ic.mk_app ``int_cast_one [], return (ic, zc, e, p) | match_numeral_result.bit0 a' := do (ic, zc, a, p) ← prove_int_uncast_nat a', (zc, a0) ← zc.mk_bit0 a, (ic, p) ← ic.mk_app ``int_cast_bit0 [a, a', p], return (ic, zc, a0, p) | match_numeral_result.bit1 a' := do (ic, zc, a, p) ← prove_int_uncast_nat a', (zc, a1) ← zc.mk_bit1 a, (ic, p) ← ic.mk_app ``int_cast_bit1 [a, a', p], return (ic, zc, a1, p) | _ := failed end /-- Given `a' : α` a natural numeral, returns `(a : ℚ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ meta def prove_rat_uncast_nat (ic qc : instance_cache) (cz_inst : expr) : ∀ (a' : expr), tactic (instance_cache × instance_cache × expr × expr) | a' := match match_numeral a' with | match_numeral_result.zero := do (qc, e) ← qc.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``rat.cast_zero [], return (ic, qc, e, p) | match_numeral_result.one := do (qc, e) ← qc.mk_app ``has_one.one [], (ic, p) ← ic.mk_app ``rat.cast_one [], return (ic, qc, e, p) | match_numeral_result.bit0 a' := do (ic, qc, a, p) ← prove_rat_uncast_nat a', (qc, a0) ← qc.mk_bit0 a, (ic, p) ← ic.mk_app ``rat_cast_bit0 [cz_inst, a, a', p], return (ic, qc, a0, p) | match_numeral_result.bit1 a' := do (ic, qc, a, p) ← prove_rat_uncast_nat a', (qc, a1) ← qc.mk_bit1 a, (ic, p) ← ic.mk_app ``rat_cast_bit1 [cz_inst, a, a', p], return (ic, qc, a1, p) | _ := failed end theorem rat_cast_div {α} [division_ring α] [char_zero α] (a b : ℚ) (a' b' : α) (ha : ↑a = a') (hb : ↑b = b') : ↑(a / b) = a' / b' := ha ▸ hb ▸ rat.cast_div _ _ /-- Given `a' : α` a nonnegative rational numeral, returns `(a : ℚ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ meta def prove_rat_uncast_nonneg (ic qc : instance_cache) (cz_inst a' : expr) (na' : ℚ) : tactic (instance_cache × instance_cache × expr × expr) := if na'.denom = 1 then prove_rat_uncast_nat ic qc cz_inst a' else do [_, _, a', b'] ← return a'.get_app_args, (ic, qc, a, pa) ← prove_rat_uncast_nat ic qc cz_inst a', (ic, qc, b, pb) ← prove_rat_uncast_nat ic qc cz_inst b', (qc, e) ← qc.mk_app ``has_div.div [a, b], (ic, p) ← ic.mk_app ``rat_cast_div [cz_inst, a, b, a', b', pa, pb], return (ic, qc, e, p) theorem int_cast_neg {α} [ring α] (a : ℤ) (a' : α) (h : ↑a = a') : ↑-a = -a' := h ▸ int.cast_neg _ theorem rat_cast_neg {α} [division_ring α] (a : ℚ) (a' : α) (h : ↑a = a') : ↑-a = -a' := h ▸ rat.cast_neg _ /-- Given `a' : α` an integer numeral, returns `(a : ℤ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ meta def prove_int_uncast (ic zc : instance_cache) (a' : expr) : tactic (instance_cache × instance_cache × expr × expr) := match match_neg a' with | some a' := do (ic, zc, a, p) ← prove_int_uncast_nat ic zc a', (zc, e) ← zc.mk_app ``has_neg.neg [a], (ic, p) ← ic.mk_app ``int_cast_neg [a, a', p], return (ic, zc, e, p) | none := prove_int_uncast_nat ic zc a' end /-- Given `a' : α` a rational numeral, returns `(a : ℚ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ meta def prove_rat_uncast (ic qc : instance_cache) (cz_inst a' : expr) (na' : ℚ) : tactic (instance_cache × instance_cache × expr × expr) := match match_neg a' with | some a' := do (ic, qc, a, p) ← prove_rat_uncast_nonneg ic qc cz_inst a' (-na'), (qc, e) ← qc.mk_app ``has_neg.neg [a], (ic, p) ← ic.mk_app ``rat_cast_neg [a, a', p], return (ic, qc, e, p) | none := prove_rat_uncast_nonneg ic qc cz_inst a' na' end theorem nat_cast_ne {α} [semiring α] [char_zero α] (a b : ℕ) (a' b' : α) (ha : ↑a = a') (hb : ↑b = b') (h : a ≠ b) : a' ≠ b' := ha ▸ hb ▸ mt nat.cast_inj.1 h theorem int_cast_ne {α} [ring α] [char_zero α] (a b : ℤ) (a' b' : α) (ha : ↑a = a') (hb : ↑b = b') (h : a ≠ b) : a' ≠ b' := ha ▸ hb ▸ mt int.cast_inj.1 h theorem rat_cast_ne {α} [division_ring α] [char_zero α] (a b : ℚ) (a' b' : α) (ha : ↑a = a') (hb : ↑b = b') (h : a ≠ b) : a' ≠ b' := ha ▸ hb ▸ mt rat.cast_inj.1 h /-- Given `a`,`b` rational numerals, proves `⊢ a ≠ b`. Currently it tries two methods: * Prove `⊢ a < b` or `⊢ b < a`, if the base type has an order * Embed `↑(a':ℚ) = a` and `↑(b':ℚ) = b`, and then prove `a' ≠ b'`. This requires that the base type be `char_zero`, and also that it be a `division_ring` so that the coercion from `ℚ` is well defined. We may also add coercions to `ℤ` and `ℕ` as well in order to support `char_zero` rings and semirings. -/ meta def prove_ne : instance_cache → expr → expr → ℚ → ℚ → tactic (instance_cache × expr) | ic a b na nb := prove_ne_rat ic a b na nb <|> do cz_inst ← mk_mapp ``char_zero [ic.α, none, none] >>= mk_instance, if na.denom = 1 ∧ nb.denom = 1 then if na ≥ 0 ∧ nb ≥ 0 then do guard (ic.α ≠ `(ℕ)), nc ← mk_instance_cache `(ℕ), (ic, nc, a', pa) ← prove_nat_uncast ic nc a, (ic, nc, b', pb) ← prove_nat_uncast ic nc b, (nc, p) ← prove_ne_rat nc a' b' na nb, ic.mk_app ``nat_cast_ne [cz_inst, a', b', a, b, pa, pb, p] else do guard (ic.α ≠ `(ℤ)), zc ← mk_instance_cache `(ℤ), (ic, zc, a', pa) ← prove_int_uncast ic zc a, (ic, zc, b', pb) ← prove_int_uncast ic zc b, (zc, p) ← prove_ne_rat zc a' b' na nb, ic.mk_app ``int_cast_ne [cz_inst, a', b', a, b, pa, pb, p] else do guard (ic.α ≠ `(ℚ)), qc ← mk_instance_cache `(ℚ), (ic, qc, a', pa) ← prove_rat_uncast ic qc cz_inst a na, (ic, qc, b', pb) ← prove_rat_uncast ic qc cz_inst b nb, (qc, p) ← prove_ne_rat qc a' b' na nb, ic.mk_app ``rat_cast_ne [cz_inst, a', b', a, b, pa, pb, p] /-- Given `a` a rational numeral, returns `⊢ a ≠ 0`. -/ meta def prove_ne_zero (ic : instance_cache) : expr → ℚ → tactic (instance_cache × expr) | a na := do (ic, z) ← ic.mk_app ``has_zero.zero [], prove_ne ic a z na 0 /-- Given `a` nonnegative rational and `d` a natural number, returns `(b, ⊢ a * d = b)`. (`d` should be a multiple of the denominator of `a`, so that `b` is a natural number.) -/ meta def prove_clear_denom : instance_cache → expr → expr → ℚ → ℕ → tactic (instance_cache × expr × expr) := prove_clear_denom' prove_ne_zero theorem clear_denom_add {α} [division_ring α] (a a' b b' c c' d : α) (h₀ : d ≠ 0) (ha : a * d = a') (hb : b * d = b') (hc : c * d = c') (h : a' + b' = c') : a + b = c := mul_right_cancel' h₀ $ by rwa [add_mul, ha, hb, hc] /-- Given `a`,`b`,`c` nonnegative rational numerals, returns `⊢ a + b = c`. -/ meta def prove_add_nonneg_rat (ic : instance_cache) (a b c : expr) (na nb nc : ℚ) : tactic (instance_cache × expr) := if na.denom = 1 ∧ nb.denom = 1 then prove_add_nat ic a b c else do let nd := na.denom.lcm nb.denom, (ic, d) ← ic.of_nat nd, (ic, p₀) ← prove_ne_zero ic d (rat.of_int nd), (ic, a', pa) ← prove_clear_denom ic a d na nd, (ic, b', pb) ← prove_clear_denom ic b d nb nd, (ic, c', pc) ← prove_clear_denom ic c d nc nd, (ic, p) ← prove_add_nat ic a' b' c', ic.mk_app ``clear_denom_add [a, a', b, b', c, c', d, p₀, pa, pb, pc, p] theorem add_pos_neg_pos {α} [add_group α] (a b c : α) (h : c + b = a) : a + -b = c := h ▸ by simp theorem add_pos_neg_neg {α} [add_group α] (a b c : α) (h : c + a = b) : a + -b = -c := h ▸ by simp theorem add_neg_pos_pos {α} [add_group α] (a b c : α) (h : a + c = b) : -a + b = c := h ▸ by simp theorem add_neg_pos_neg {α} [add_group α] (a b c : α) (h : b + c = a) : -a + b = -c := h ▸ by simp theorem add_neg_neg {α} [add_group α] (a b c : α) (h : b + a = c) : -a + -b = -c := h ▸ by simp /-- Given `a`,`b`,`c` rational numerals, returns `⊢ a + b = c`. -/ meta def prove_add_rat (ic : instance_cache) (ea eb ec : expr) (a b c : ℚ) : tactic (instance_cache × expr) := match match_neg ea, match_neg eb, match_neg ec with | some ea, some eb, some ec := do (ic, p) ← prove_add_nonneg_rat ic eb ea ec (-b) (-a) (-c), ic.mk_app ``add_neg_neg [ea, eb, ec, p] | some ea, none, some ec := do (ic, p) ← prove_add_nonneg_rat ic eb ec ea b (-c) (-a), ic.mk_app ``add_neg_pos_neg [ea, eb, ec, p] | some ea, none, none := do (ic, p) ← prove_add_nonneg_rat ic ea ec eb (-a) c b, ic.mk_app ``add_neg_pos_pos [ea, eb, ec, p] | none, some eb, some ec := do (ic, p) ← prove_add_nonneg_rat ic ec ea eb (-c) a (-b), ic.mk_app ``add_pos_neg_neg [ea, eb, ec, p] | none, some eb, none := do (ic, p) ← prove_add_nonneg_rat ic ec eb ea c (-b) a, ic.mk_app ``add_pos_neg_pos [ea, eb, ec, p] | _, _, _ := prove_add_nonneg_rat ic ea eb ec a b c end /-- Given `a`,`b` rational numerals, returns `(c, ⊢ a + b = c)`. -/ meta def prove_add_rat' (ic : instance_cache) (a b : expr) : tactic (instance_cache × expr × expr) := do na ← a.to_rat, nb ← b.to_rat, let nc := na + nb, (ic, c) ← ic.of_rat nc, (ic, p) ← prove_add_rat ic a b c na nb nc, return (ic, c, p) theorem clear_denom_simple_nat {α} [division_ring α] (a : α) : (1:α) ≠ 0 ∧ a * 1 = a := ⟨one_ne_zero, mul_one _⟩ theorem clear_denom_simple_div {α} [division_ring α] (a b : α) (h : b ≠ 0) : b ≠ 0 ∧ a / b * b = a := ⟨h, div_mul_cancel _ h⟩ /-- Given `a` a nonnegative rational numeral, returns `(b, c, ⊢ a * b = c)` where `b` and `c` are natural numerals. (`b` will be the denominator of `a`.) -/ meta def prove_clear_denom_simple (c : instance_cache) (a : expr) (na : ℚ) : tactic (instance_cache × expr × expr × expr) := if na.denom = 1 then do (c, d) ← c.mk_app ``has_one.one [], (c, p) ← c.mk_app ``clear_denom_simple_nat [a], return (c, d, a, p) else do [α, _, a, b] ← return a.get_app_args, (c, p₀) ← prove_ne_zero c b (rat.of_int na.denom), (c, p) ← c.mk_app ``clear_denom_simple_div [a, b, p₀], return (c, b, a, p) theorem clear_denom_mul {α} [field α] (a a' b b' c c' d₁ d₂ d : α) (ha : d₁ ≠ 0 ∧ a * d₁ = a') (hb : d₂ ≠ 0 ∧ b * d₂ = b') (hc : c * d = c') (hd : d₁ * d₂ = d) (h : a' * b' = c') : a * b = c := mul_right_cancel' ha.1 $ mul_right_cancel' hb.1 $ by rw [mul_assoc c, hd, hc, ← h, ← ha.2, ← hb.2, ← mul_assoc, mul_right_comm a] /-- Given `a`,`b` nonnegative rational numerals, returns `(c, ⊢ a * b = c)`. -/ meta def prove_mul_nonneg_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr × expr) := if na.denom = 1 ∧ nb.denom = 1 then prove_mul_nat ic a b else do let nc := na * nb, (ic, c) ← ic.of_rat nc, (ic, d₁, a', pa) ← prove_clear_denom_simple ic a na, (ic, d₂, b', pb) ← prove_clear_denom_simple ic b nb, (ic, d, pd) ← prove_mul_nat ic d₁ d₂, nd ← d.to_nat, (ic, c', pc) ← prove_clear_denom ic c d nc nd, (ic, _, p) ← prove_mul_nat ic a' b', (ic, p) ← ic.mk_app ``clear_denom_mul [a, a', b, b', c, c', d₁, d₂, d, pa, pb, pc, pd, p], return (ic, c, p) theorem mul_neg_pos {α} [ring α] (a b c : α) (h : a * b = c) : -a * b = -c := h ▸ by simp theorem mul_pos_neg {α} [ring α] (a b c : α) (h : a * b = c) : a * -b = -c := h ▸ by simp theorem mul_neg_neg {α} [ring α] (a b c : α) (h : a * b = c) : -a * -b = c := h ▸ by simp /-- Given `a`,`b` rational numerals, returns `(c, ⊢ a * b = c)`. -/ meta def prove_mul_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr × expr) := match match_sign a, match_sign b with | sum.inl a, sum.inl b := do (ic, c, p) ← prove_mul_nonneg_rat ic a b (-na) (-nb), (ic, p) ← ic.mk_app ``mul_neg_neg [a, b, c, p], return (ic, c, p) | sum.inr ff, _ := do (ic, z) ← ic.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``zero_mul [b], return (ic, z, p) | _, sum.inr ff := do (ic, z) ← ic.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``mul_zero [a], return (ic, z, p) | sum.inl a, sum.inr tt := do (ic, c, p) ← prove_mul_nonneg_rat ic a b (-na) nb, (ic, p) ← ic.mk_app ``mul_neg_pos [a, b, c, p], (ic, c') ← ic.mk_app ``has_neg.neg [c], return (ic, c', p) | sum.inr tt, sum.inl b := do (ic, c, p) ← prove_mul_nonneg_rat ic a b na (-nb), (ic, p) ← ic.mk_app ``mul_pos_neg [a, b, c, p], (ic, c') ← ic.mk_app ``has_neg.neg [c], return (ic, c', p) | sum.inr tt, sum.inr tt := prove_mul_nonneg_rat ic a b na nb end theorem inv_neg {α} [division_ring α] (a b : α) (h : a⁻¹ = b) : (-a)⁻¹ = -b := h ▸ by simp only [inv_eq_one_div, one_div_neg_eq_neg_one_div] theorem inv_one {α} [division_ring α] : (1 : α)⁻¹ = 1 := inv_one theorem inv_one_div {α} [division_ring α] (a : α) : (1 / a)⁻¹ = a := by rw [one_div, inv_inv'] theorem inv_div_one {α} [division_ring α] (a : α) : a⁻¹ = 1 / a := inv_eq_one_div _ theorem inv_div {α} [division_ring α] (a b : α) : (a / b)⁻¹ = b / a := by simp only [inv_eq_one_div, one_div_div] /-- Given `a` a rational numeral, returns `(b, ⊢ a⁻¹ = b)`. -/ meta def prove_inv : instance_cache → expr → ℚ → tactic (instance_cache × expr × expr) | ic e n := match match_sign e with | sum.inl e := do (ic, e', p) ← prove_inv ic e (-n), (ic, r) ← ic.mk_app ``has_neg.neg [e'], (ic, p) ← ic.mk_app ``inv_neg [e, e', p], return (ic, r, p) | sum.inr ff := do (ic, p) ← ic.mk_app ``inv_zero [], return (ic, e, p) | sum.inr tt := if n.num = 1 then if n.denom = 1 then do (ic, p) ← ic.mk_app ``inv_one [], return (ic, e, p) else do let e := e.app_arg, (ic, p) ← ic.mk_app ``inv_one_div [e], return (ic, e, p) else if n.denom = 1 then do (ic, p) ← ic.mk_app ``inv_div_one [e], e ← infer_type p, return (ic, e.app_arg, p) else do [_, _, a, b] ← return e.get_app_args, (ic, e') ← ic.mk_app ``has_div.div [b, a], (ic, p) ← ic.mk_app ``inv_div [a, b], return (ic, e', p) end theorem div_eq {α} [division_ring α] (a b b' c : α) (hb : b⁻¹ = b') (h : a * b' = c) : a / b = c := by rwa [ ← hb, ← div_eq_mul_inv] at h /-- Given `a`,`b` rational numerals, returns `(c, ⊢ a / b = c)`. -/ meta def prove_div (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr × expr) := do (ic, b', pb) ← prove_inv ic b nb, (ic, c, p) ← prove_mul_rat ic a b' na nb⁻¹, (ic, p) ← ic.mk_app ``div_eq [a, b, b', c, pb, p], return (ic, c, p) /-- Given `a` a rational numeral, returns `(b, ⊢ -a = b)`. -/ meta def prove_neg (ic : instance_cache) (a : expr) : tactic (instance_cache × expr × expr) := match match_sign a with | sum.inl a := do (ic, p) ← ic.mk_app ``neg_neg [a], return (ic, a, p) | sum.inr ff := do (ic, p) ← ic.mk_app ``neg_zero [], return (ic, a, p) | sum.inr tt := do (ic, a') ← ic.mk_app ``has_neg.neg [a], p ← mk_eq_refl a', return (ic, a', p) end theorem sub_pos {α} [add_group α] (a b b' c : α) (hb : -b = b') (h : a + b' = c) : a - b = c := by rwa [← hb, ← sub_eq_add_neg] at h theorem sub_neg {α} [add_group α] (a b c : α) (h : a + b = c) : a - -b = c := by rwa sub_neg_eq_add /-- Given `a`,`b` rational numerals, returns `(c, ⊢ a - b = c)`. -/ meta def prove_sub (ic : instance_cache) (a b : expr) : tactic (instance_cache × expr × expr) := match match_sign b with | sum.inl b := do (ic, c, p) ← prove_add_rat' ic a b, (ic, p) ← ic.mk_app ``sub_neg [a, b, c, p], return (ic, c, p) | sum.inr ff := do (ic, p) ← ic.mk_app ``sub_zero [a], return (ic, a, p) | sum.inr tt := do (ic, b', pb) ← prove_neg ic b, (ic, c, p) ← prove_add_rat' ic a b', (ic, p) ← ic.mk_app ``sub_pos [a, b, b', c, pb, p], return (ic, c, p) end theorem sub_nat_pos (a b c : ℕ) (h : b + c = a) : a - b = c := h ▸ nat.add_sub_cancel_left _ _ theorem sub_nat_neg (a b c : ℕ) (h : a + c = b) : a - b = 0 := nat.sub_eq_zero_of_le $ h ▸ nat.le_add_right _ _ /-- Given `a : nat`,`b : nat` natural numerals, returns `(c, ⊢ a - b = c)`. -/ meta def prove_sub_nat (ic : instance_cache) (a b : expr) : tactic (expr × expr) := do na ← a.to_nat, nb ← b.to_nat, if nb ≤ na then do (ic, c) ← ic.of_nat (na - nb), (ic, p) ← prove_add_nat ic b c a, return (c, `(sub_nat_pos).mk_app [a, b, c, p]) else do (ic, c) ← ic.of_nat (nb - na), (ic, p) ← prove_add_nat ic a c b, return (`(0 : ℕ), `(sub_nat_neg).mk_app [a, b, c, p]) /-- Evaluates the basic field operations `+`,`neg`,`-`,`*`,`inv`,`/` on numerals. Also handles nat subtraction. Does not do recursive simplification; that is, `1 + 1 + 1` will not simplify but `2 + 1` will. This is handled by the top level `simp` call in `norm_num.derive`. -/ meta def eval_field : expr → tactic (expr × expr) | `(%%e₁ + %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, let n₃ := n₁ + n₂, (c, e₃) ← c.of_rat n₃, (_, p) ← prove_add_rat c e₁ e₂ e₃ n₁ n₂ n₃, return (e₃, p) | `(%%e₁ * %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, prod.snd <$> prove_mul_rat c e₁ e₂ n₁ n₂ | `(- %%e) := do c ← infer_type e >>= mk_instance_cache, prod.snd <$> prove_neg c e | `(@has_sub.sub %%α %%inst %%a %%b) := do c ← mk_instance_cache α, if α = `(nat) then prove_sub_nat c a b else prod.snd <$> prove_sub c a b | `(has_inv.inv %%e) := do n ← e.to_rat, c ← infer_type e >>= mk_instance_cache, prod.snd <$> prove_inv c e n | `(%%e₁ / %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, prod.snd <$> prove_div c e₁ e₂ n₁ n₂ | _ := failed lemma pow_bit0 [monoid α] (a c' c : α) (b : ℕ) (h : a ^ b = c') (h₂ : c' * c' = c) : a ^ bit0 b = c := h₂ ▸ by simp [pow_bit0, h] lemma pow_bit1 [monoid α] (a c₁ c₂ c : α) (b : ℕ) (h : a ^ b = c₁) (h₂ : c₁ * c₁ = c₂) (h₃ : c₂ * a = c) : a ^ bit1 b = c := by rw [← h₃, ← h₂]; simp [pow_bit1, h] section open match_numeral_result /-- Given `a` a rational numeral and `b : nat`, returns `(c, ⊢ a ^ b = c)`. -/ meta def prove_pow (a : expr) (na : ℚ) : instance_cache → expr → tactic (instance_cache × expr × expr) | ic b := match match_numeral b with | zero := do (ic, p) ← ic.mk_app ``pow_zero [a], (ic, o) ← ic.mk_app ``has_one.one [], return (ic, o, p) | one := do (ic, p) ← ic.mk_app ``pow_one [a], return (ic, a, p) | bit0 b := do (ic, c', p) ← prove_pow ic b, nc' ← expr.to_rat c', (ic, c, p₂) ← prove_mul_rat ic c' c' nc' nc', (ic, p) ← ic.mk_app ``pow_bit0 [a, c', c, b, p, p₂], return (ic, c, p) | bit1 b := do (ic, c₁, p) ← prove_pow ic b, nc₁ ← expr.to_rat c₁, (ic, c₂, p₂) ← prove_mul_rat ic c₁ c₁ nc₁ nc₁, (ic, c, p₃) ← prove_mul_rat ic c₂ a (nc₁ * nc₁) na, (ic, p) ← ic.mk_app ``pow_bit1 [a, c₁, c₂, c, b, p, p₂, p₃], return (ic, c, p) | _ := failed end end /-- Evaluates expressions of the form `a ^ b`, `monoid.pow a b` or `nat.pow a b`. -/ meta def eval_pow : expr → tactic (expr × expr) | `(@has_pow.pow %%α _ %%m %%e₁ %%e₂) := do n₁ ← e₁.to_rat, c ← infer_type e₁ >>= mk_instance_cache, match m with | `(@monoid.has_pow %%_ %%_) := prod.snd <$> prove_pow e₁ n₁ c e₂ | _ := failed end | `(monoid.pow %%e₁ %%e₂) := do n₁ ← e₁.to_rat, c ← infer_type e₁ >>= mk_instance_cache, prod.snd <$> prove_pow e₁ n₁ c e₂ | _ := failed /-- Given `⊢ p`, returns `(true, ⊢ p = true)`. -/ meta def true_intro (p : expr) : tactic (expr × expr) := prod.mk `(true) <$> mk_app ``eq_true_intro [p] /-- Given `⊢ ¬ p`, returns `(false, ⊢ p = false)`. -/ meta def false_intro (p : expr) : tactic (expr × expr) := prod.mk `(false) <$> mk_app ``eq_false_intro [p] theorem not_refl_false_intro {α} (a : α) : (a ≠ a) = false := eq_false_intro $ not_not_intro rfl /-- Evaluates the inequality operations `=`,`<`,`>`,`≤`,`≥`,`≠` on numerals. -/ meta def eval_ineq : expr → tactic (expr × expr) | `(%%e₁ < %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, if n₁ < n₂ then do (_, p) ← prove_lt_rat c e₁ e₂ n₁ n₂, true_intro p else if n₁ = n₂ then do (_, p) ← c.mk_app ``lt_irrefl [e₁], false_intro p else do (c, p') ← prove_lt_rat c e₂ e₁ n₂ n₁, (_, p) ← c.mk_app ``not_lt_of_gt [e₁, e₂, p'], false_intro p | `(%%e₁ ≤ %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, if n₁ ≤ n₂ then do (_, p) ← if n₁ = n₂ then c.mk_app ``le_refl [e₁] else prove_le_rat c e₁ e₂ n₁ n₂, true_intro p else do (c, p) ← prove_lt_rat c e₂ e₁ n₂ n₁, (_, p) ← c.mk_app ``not_le_of_gt [e₁, e₂, p], false_intro p | `(%%e₁ = %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, if n₁ = n₂ then mk_eq_refl e₁ >>= true_intro else do (_, p) ← prove_ne c e₁ e₂ n₁ n₂, false_intro p | `(%%e₁ > %%e₂) := mk_app ``has_lt.lt [e₂, e₁] >>= eval_ineq | `(%%e₁ ≥ %%e₂) := mk_app ``has_le.le [e₂, e₁] >>= eval_ineq | `(%%e₁ ≠ %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, if n₁ = n₂ then prod.mk `(false) <$> mk_app ``not_refl_false_intro [e₁] else do (_, p) ← prove_ne c e₁ e₂ n₁ n₂, true_intro p | _ := failed theorem nat_succ_eq (a b c : ℕ) (h₁ : a = b) (h₂ : b + 1 = c) : nat.succ a = c := by rwa h₁ /-- Evaluates the expression `nat.succ ... (nat.succ n)` where `n` is a natural numeral. (We could also just handle `nat.succ n` here and rely on `simp` to work bottom up, but we figure that towers of successors coming from e.g. `induction` are a common case.) -/ meta def prove_nat_succ (ic : instance_cache) : expr → tactic (instance_cache × ℕ × expr × expr) | `(nat.succ %%a) := do (ic, n, b, p₁) ← prove_nat_succ a, let n' := n + 1, (ic, c) ← ic.of_nat n', (ic, p₂) ← prove_add_nat ic b `(1) c, return (ic, n', c, `(nat_succ_eq).mk_app [a, b, c, p₁, p₂]) | e := do n ← e.to_nat, p ← mk_eq_refl e, return (ic, n, e, p) lemma nat_div (a b q r m : ℕ) (hm : q * b = m) (h : r + m = a) (h₂ : r < b) : a / b = q := by rw [← h, ← hm, nat.add_mul_div_right _ _ (lt_of_le_of_lt (nat.zero_le _) h₂), nat.div_eq_of_lt h₂, zero_add] lemma int_div (a b q r m : ℤ) (hm : q * b = m) (h : r + m = a) (h₁ : 0 ≤ r) (h₂ : r < b) : a / b = q := by rw [← h, ← hm, int.add_mul_div_right _ _ (ne_of_gt (lt_of_le_of_lt h₁ h₂)), int.div_eq_zero_of_lt h₁ h₂, zero_add] lemma nat_mod (a b q r m : ℕ) (hm : q * b = m) (h : r + m = a) (h₂ : r < b) : a % b = r := by rw [← h, ← hm, nat.add_mul_mod_self_right, nat.mod_eq_of_lt h₂] lemma int_mod (a b q r m : ℤ) (hm : q * b = m) (h : r + m = a) (h₁ : 0 ≤ r) (h₂ : r < b) : a % b = r := by rw [← h, ← hm, int.add_mul_mod_self, int.mod_eq_of_lt h₁ h₂] lemma int_div_neg (a b c' c : ℤ) (h : a / b = c') (h₂ : -c' = c) : a / -b = c := h₂ ▸ h ▸ int.div_neg _ _ lemma int_mod_neg (a b c : ℤ) (h : a % b = c) : a % -b = c := (int.mod_neg _ _).trans h /-- Given `a`,`b` numerals in `nat` or `int`, * `prove_div_mod ic a b ff` returns `(c, ⊢ a / b = c)` * `prove_div_mod ic a b tt` returns `(c, ⊢ a % b = c)` -/ meta def prove_div_mod (ic : instance_cache) : expr → expr → bool → tactic (instance_cache × expr × expr) | a b mod := match match_neg b with | some b := do (ic, c', p) ← prove_div_mod a b mod, if mod then return (ic, c', `(int_mod_neg).mk_app [a, b, c', p]) else do (ic, c, p₂) ← prove_neg ic c', return (ic, c, `(int_div_neg).mk_app [a, b, c', c, p, p₂]) | none := do nb ← b.to_nat, na ← a.to_int, let nq := na / nb, let nr := na % nb, let nm := nq * nr, (ic, q) ← ic.of_int nq, (ic, r) ← ic.of_int nr, (ic, m, pm) ← prove_mul_rat ic q b (rat.of_int nq) (rat.of_int nb), (ic, p) ← prove_add_rat ic r m a (rat.of_int nr) (rat.of_int nm) (rat.of_int na), (ic, p') ← prove_lt_nat ic r b, if ic.α = `(nat) then if mod then return (ic, r, `(nat_mod).mk_app [a, b, q, r, m, pm, p, p']) else return (ic, q, `(nat_div).mk_app [a, b, q, r, m, pm, p, p']) else if ic.α = `(int) then do (ic, p₀) ← prove_nonneg ic r, if mod then return (ic, r, `(int_mod).mk_app [a, b, q, r, m, pm, p, p₀, p']) else return (ic, q, `(int_div).mk_app [a, b, q, r, m, pm, p, p₀, p']) else failed end theorem dvd_eq_nat (a b c : ℕ) (p) (h₁ : b % a = c) (h₂ : (c = 0) = p) : (a ∣ b) = p := (propext $ by rw [← h₁, nat.dvd_iff_mod_eq_zero]).trans h₂ theorem dvd_eq_int (a b c : ℤ) (p) (h₁ : b % a = c) (h₂ : (c = 0) = p) : (a ∣ b) = p := (propext $ by rw [← h₁, int.dvd_iff_mod_eq_zero]).trans h₂ /-- Evaluates some extra numeric operations on `nat` and `int`, specifically `nat.succ`, `/` and `%`, and `∣` (divisibility). -/ meta def eval_nat_int_ext : expr → tactic (expr × expr) | e@`(nat.succ _) := do ic ← mk_instance_cache `(ℕ), (_, _, ep) ← prove_nat_succ ic e, return ep | `(%%a / %%b) := do c ← infer_type a >>= mk_instance_cache, prod.snd <$> prove_div_mod c a b ff | `(%%a % %%b) := do c ← infer_type a >>= mk_instance_cache, prod.snd <$> prove_div_mod c a b tt | `(%%a ∣ %%b) := do α ← infer_type a, ic ← mk_instance_cache α, th ← if α = `(nat) then return (`(dvd_eq_nat):expr) else if α = `(int) then return `(dvd_eq_int) else failed, (ic, c, p₁) ← prove_div_mod ic b a tt, (ic, z) ← ic.mk_app ``has_zero.zero [], (e', p₂) ← mk_app ``eq [c, z] >>= eval_ineq, return (e', th.mk_app [a, b, c, e', p₁, p₂]) | _ := failed /-- This version of `derive` does not fail when the input is already a numeral -/ meta def derive.step (e : expr) : tactic (expr × expr) := eval_field e <|> eval_nat_int_ext e <|> eval_pow e <|> eval_ineq e /-- An attribute for adding additional extensions to `norm_num`. To use this attribute, put `@[norm_num]` on a tactic of type `expr → tactic (expr × expr)`; the tactic will be called on subterms by `norm_num`, and it is responsible for identifying that the expression is a numerical function applied to numerals, for example `nat.fib 17`, and should return the reduced numerical expression (which must be in `norm_num`-normal form: a natural or rational numeral, i.e. `37`, `12 / 7` or `-(2 / 3)`, although this can be an expression in any type), and the proof that the original expression is equal to the rewritten expression. Failure is used to indicate that this tactic does not apply to the term. For performance reasons, it is best to detect non-applicability as soon as possible so that the next tactic can have a go, so generally it will start with a pattern match and then checking that the arguments to the term are numerals or of the appropriate form, followed by proof construction, which should not fail. Propositions are treated like any other term. The normal form for propositions is `true` or `false`, so it should produce a proof of the form `p = true` or `p = false`. `eq_true_intro` can be used to help here. -/ @[user_attribute] protected meta def attr : user_attribute (expr → tactic (expr × expr)) unit := { name := `norm_num, descr := "Add norm_num derivers", cache_cfg := { mk_cache := λ ns, do { t ← ns.mfoldl (λ (t : expr → tactic (expr × expr)) n, do t' ← eval_expr (expr → tactic (expr × expr)) (expr.const n []), pure (λ e, t' e <|> t e)) (λ _, failed), pure (λ e, derive.step e <|> t e) }, dependencies := [] } } add_tactic_doc { name := "norm_num", category := doc_category.attr, decl_names := [`norm_num.attr], tags := ["arithmetic", "decision_procedure"] } /-- Look up the `norm_num` extensions in the cache and return a tactic extending `derive.step` with additional reduction procedures. -/ meta def get_step : tactic (expr → tactic (expr × expr)) := norm_num.attr.get_cache /-- Simplify an expression bottom-up using `step` to simplify the subexpressions. -/ meta def derive' (step : expr → tactic (expr × expr)) : expr → tactic (expr × expr) | e := do e ← instantiate_mvars e, (_, e', pr) ← ext_simplify_core () {} simp_lemmas.mk (λ _, failed) (λ _ _ _ _ _, failed) (λ _ _ _ _ e, do (new_e, pr) ← step e, guard (¬ new_e =ₐ e), return ((), new_e, some pr, tt)) `eq e, return (e', pr) /-- Simplify an expression bottom-up using the default `norm_num` set to simplify the subexpressions. -/ meta def derive (e : expr) : tactic (expr × expr) := do f ← get_step, derive' f e end norm_num /-- Basic version of `norm_num` that does not call `simp`. It uses the provided `step` tactic to simplify the expression; use `get_step` to get the default `norm_num` set and `derive.step` for the basic builtin set of simplifications. -/ meta def tactic.norm_num1 (step : expr → tactic (expr × expr)) (loc : interactive.loc) : tactic unit := do ns ← loc.get_locals, tt ← tactic.replace_at (norm_num.derive' step) ns loc.include_goal | fail "norm_num failed to simplify", when loc.include_goal $ try tactic.triv, when (¬ ns.empty) $ try tactic.contradiction /-- Normalize numerical expressions. It uses the provided `step` tactic to simplify the expression; use `get_step` to get the default `norm_num` set and `derive.step` for the basic builtin set of simplifications. -/ meta def tactic.norm_num (step : expr → tactic (expr × expr)) (hs : list simp_arg_type) (l : interactive.loc) : tactic unit := repeat1 $ orelse' (tactic.norm_num1 step l) $ interactive.simp_core {} (tactic.norm_num1 step (interactive.loc.ns [none])) ff (simp_arg_type.except ``one_div :: hs) [] l >> skip namespace tactic.interactive open norm_num interactive interactive.types /-- Basic version of `norm_num` that does not call `simp`. -/ meta def norm_num1 (loc : parse location) : tactic unit := do f ← get_step, tactic.norm_num1 f loc /-- Normalize numerical expressions. Supports the operations `+` `-` `*` `/` `^` and `%` over numerical types such as `ℕ`, `ℤ`, `ℚ`, `ℝ`, `ℂ` and some general algebraic types, and can prove goals of the form `A = B`, `A ≠ B`, `A < B` and `A ≤ B`, where `A` and `B` are numerical expressions. It also has a relatively simple primality prover. -/ meta def norm_num (hs : parse simp_arg_list) (l : parse location) : tactic unit := do f ← get_step, tactic.norm_num f hs l add_hint_tactic "norm_num" /-- Normalizes a numerical expression and tries to close the goal with the result. -/ meta def apply_normed (x : parse texpr) : tactic unit := do x₁ ← to_expr x, (x₂,_) ← derive x₁, tactic.exact x₂ /-- Normalises numerical expressions. It supports the operations `+` `-` `*` `/` `^` and `%` over numerical types such as `ℕ`, `ℤ`, `ℚ`, `ℝ`, `ℂ`, and can prove goals of the form `A = B`, `A ≠ B`, `A < B` and `A ≤ B`, where `A` and `B` are numerical expressions. It also has a relatively simple primality prover. ```lean import data.real.basic example : (2 : ℝ) + 2 = 4 := by norm_num example : (12345.2 : ℝ) ≠ 12345.3 := by norm_num example : (73 : ℝ) < 789/2 := by norm_num example : 123456789 + 987654321 = 1111111110 := by norm_num example (R : Type*) [ring R] : (2 : R) + 2 = 4 := by norm_num example (F : Type*) [linear_ordered_field F] : (2 : F) + 2 < 5 := by norm_num example : nat.prime (2^13 - 1) := by norm_num example : ¬ nat.prime (2^11 - 1) := by norm_num example (x : ℝ) (h : x = 123 + 456) : x = 579 := by norm_num at h; assumption ``` The variant `norm_num1` does not call `simp`. Both `norm_num` and `norm_num1` can be called inside the `conv` tactic. The tactic `apply_normed` normalises a numerical expression and tries to close the goal with the result. Compare: ```lean def a : ℕ := 2^100 #print a -- 2 ^ 100 def normed_a : ℕ := by apply_normed 2^100 #print normed_a -- 1267650600228229401496703205376 ``` -/ add_tactic_doc { name := "norm_num", category := doc_category.tactic, decl_names := [`tactic.interactive.norm_num1, `tactic.interactive.norm_num, `tactic.interactive.apply_normed], tags := ["arithmetic", "decision procedure"] } end tactic.interactive namespace conv.interactive open conv interactive tactic.interactive open norm_num (derive) /-- Basic version of `norm_num` that does not call `simp`. -/ meta def norm_num1 : conv unit := replace_lhs derive /-- Normalize numerical expressions. Supports the operations `+` `-` `*` `/` `^` and `%` over numerical types such as `ℕ`, `ℤ`, `ℚ`, `ℝ`, `ℂ` and some general algebraic types, and can prove goals of the form `A = B`, `A ≠ B`, `A < B` and `A ≤ B`, where `A` and `B` are numerical expressions. It also has a relatively simple primality prover. -/ meta def norm_num (hs : parse simp_arg_list) : conv unit := repeat1 $ orelse' norm_num1 $ conv.interactive.simp ff (simp_arg_type.except ``one_div :: hs) [] { discharger := tactic.interactive.norm_num1 (loc.ns [none]) } end conv.interactive