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
c0d57a18f014d0dd51c8857c82bd23f5d7ec241c
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/src/Init/Data/Format/Macro.lean
72910a493a0459eabf8307453ca3634d957298e8
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
404
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import Init.Data.Format.Basic import Init.Data.ToString.Macro namespace Std syntax:max "f!" interpolatedStr(term) : term macro_rules | `(f! $interpStr) => do interpStr.expandInterpolatedStr (← `(Format)) (← `(fmt)) end Std
21055987513bb22b64c0403134592482f63bbb04
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/linear_algebra/affine_space/affine_map.lean
8993df84d9187aa0c203e4887aced85ec71079b6
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
19,250
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import linear_algebra.affine_space.basic import linear_algebra.tensor_product import linear_algebra.prod import linear_algebra.pi import data.set.intervals.unordered_interval /-! # Affine maps This file defines affine maps. ## Main definitions * `affine_map` is the type of affine maps between two affine spaces with the same ring `k`. Various basic examples of affine maps are defined, including `const`, `id`, `line_map` and `homothety`. ## Notations * `P1 →ᵃ[k] P2` is a notation for `affine_map k P1 P2`; * `affine_space V P`: a localized notation for `add_torsor V P` defined in `linear_algebra.affine_space.basic`. ## Implementation notes `out_param` is used in the definition of `[add_torsor V P]` to make `V` an implicit argument (deduced from `P`) in most cases; `include V` is needed in many cases for `V`, and type classes using it, to be added as implicit arguments to individual lemmas. As for modules, `k` is an explicit argument rather than implied by `P` or `V`. This file only provides purely algebraic definitions and results. Those depending on analysis or topology are defined elsewhere; see `analysis.normed_space.add_torsor` and `topology.algebra.affine`. ## References * https://en.wikipedia.org/wiki/Affine_space * https://en.wikipedia.org/wiki/Principal_homogeneous_space -/ open_locale affine /-- An `affine_map k P1 P2` (notation: `P1 →ᵃ[k] P2`) is a map from `P1` to `P2` that induces a corresponding linear map from `V1` to `V2`. -/ structure affine_map (k : Type*) {V1 : Type*} (P1 : Type*) {V2 : Type*} (P2 : Type*) [ring k] [add_comm_group V1] [module k V1] [affine_space V1 P1] [add_comm_group V2] [module k V2] [affine_space V2 P2] := (to_fun : P1 → P2) (linear : linear_map k V1 V2) (map_vadd' : ∀ (p : P1) (v : V1), to_fun (v +ᵥ p) = linear v +ᵥ to_fun p) notation P1 ` →ᵃ[`:25 k:25 `] `:0 P2:0 := affine_map k P1 P2 instance (k : Type*) {V1 : Type*} (P1 : Type*) {V2 : Type*} (P2 : Type*) [ring k] [add_comm_group V1] [module k V1] [affine_space V1 P1] [add_comm_group V2] [module k V2] [affine_space V2 P2]: has_coe_to_fun (P1 →ᵃ[k] P2) := ⟨_, affine_map.to_fun⟩ namespace linear_map variables {k : Type*} {V₁ : Type*} {V₂ : Type*} [ring k] [add_comm_group V₁] [module k V₁] [add_comm_group V₂] [module k V₂] (f : V₁ →ₗ[k] V₂) /-- Reinterpret a linear map as an affine map. -/ def to_affine_map : V₁ →ᵃ[k] V₂ := { to_fun := f, linear := f, map_vadd' := λ p v, f.map_add v p } @[simp] lemma coe_to_affine_map : ⇑f.to_affine_map = f := rfl @[simp] lemma to_affine_map_linear : f.to_affine_map.linear = f := rfl end linear_map namespace affine_map variables {k : Type*} {V1 : Type*} {P1 : Type*} {V2 : Type*} {P2 : Type*} {V3 : Type*} {P3 : Type*} {V4 : Type*} {P4 : Type*} [ring k] [add_comm_group V1] [module k V1] [affine_space V1 P1] [add_comm_group V2] [module k V2] [affine_space V2 P2] [add_comm_group V3] [module k V3] [affine_space V3 P3] [add_comm_group V4] [module k V4] [affine_space V4 P4] include V1 V2 /-- Constructing an affine map and coercing back to a function produces the same map. -/ @[simp] lemma coe_mk (f : P1 → P2) (linear add) : ((mk f linear add : P1 →ᵃ[k] P2) : P1 → P2) = f := rfl /-- `to_fun` is the same as the result of coercing to a function. -/ @[simp] lemma to_fun_eq_coe (f : P1 →ᵃ[k] P2) : f.to_fun = ⇑f := rfl /-- An affine map on the result of adding a vector to a point produces the same result as the linear map applied to that vector, added to the affine map applied to that point. -/ @[simp] lemma map_vadd (f : P1 →ᵃ[k] P2) (p : P1) (v : V1) : f (v +ᵥ p) = f.linear v +ᵥ f p := f.map_vadd' p v /-- The linear map on the result of subtracting two points is the result of subtracting the result of the affine map on those two points. -/ @[simp] lemma linear_map_vsub (f : P1 →ᵃ[k] P2) (p1 p2 : P1) : f.linear (p1 -ᵥ p2) = f p1 -ᵥ f p2 := by conv_rhs { rw [←vsub_vadd p1 p2, map_vadd, vadd_vsub] } /-- Two affine maps are equal if they coerce to the same function. -/ @[ext] lemma ext {f g : P1 →ᵃ[k] P2} (h : ∀ p, f p = g p) : f = g := begin rcases f with ⟨f, f_linear, f_add⟩, rcases g with ⟨g, g_linear, g_add⟩, have : f = g := funext h, subst g, congr' with v, cases (add_torsor.nonempty : nonempty P1) with p, apply vadd_right_cancel (f p), erw [← f_add, ← g_add] end lemma ext_iff {f g : P1 →ᵃ[k] P2} : f = g ↔ ∀ p, f p = g p := ⟨λ h p, h ▸ rfl, ext⟩ lemma coe_fn_injective : function.injective (λ (f : P1 →ᵃ[k] P2) (x : P1), f x) := λ f g H, ext $ congr_fun H protected lemma congr_arg (f : P1 →ᵃ[k] P2) {x y : P1} (h : x = y) : f x = f y := congr_arg _ h protected lemma congr_fun {f g : P1 →ᵃ[k] P2} (h : f = g) (x : P1) : f x = g x := h ▸ rfl variables (k P1) /-- Constant function as an `affine_map`. -/ def const (p : P2) : P1 →ᵃ[k] P2 := { to_fun := function.const P1 p, linear := 0, map_vadd' := λ p v, by simp } @[simp] lemma coe_const (p : P2) : ⇑(const k P1 p) = function.const P1 p := rfl @[simp] lemma const_linear (p : P2) : (const k P1 p).linear = 0 := rfl variables {k P1} instance nonempty : nonempty (P1 →ᵃ[k] P2) := (add_torsor.nonempty : nonempty P2).elim $ λ p, ⟨const k P1 p⟩ /-- Construct an affine map by verifying the relation between the map and its linear part at one base point. Namely, this function takes a map `f : P₁ → P₂`, a linear map `f' : V₁ →ₗ[k] V₂`, and a point `p` such that for any other point `p'` we have `f p' = f' (p' -ᵥ p) +ᵥ f p`. -/ def mk' (f : P1 → P2) (f' : V1 →ₗ[k] V2) (p : P1) (h : ∀ p' : P1, f p' = f' (p' -ᵥ p) +ᵥ f p) : P1 →ᵃ[k] P2 := { to_fun := f, linear := f', map_vadd' := λ p' v, by rw [h, h p', vadd_vsub_assoc, f'.map_add, vadd_vadd] } @[simp] lemma coe_mk' (f : P1 → P2) (f' : V1 →ₗ[k] V2) (p h) : ⇑(mk' f f' p h) = f := rfl @[simp] lemma mk'_linear (f : P1 → P2) (f' : V1 →ₗ[k] V2) (p h) : (mk' f f' p h).linear = f' := rfl /-- The set of affine maps to a vector space is an additive commutative group. -/ instance : add_comm_group (P1 →ᵃ[k] V2) := { zero := ⟨0, 0, λ p v, (zero_vadd _ _).symm⟩, add := λ f g, ⟨f + g, f.linear + g.linear, λ p v, by simp [add_add_add_comm]⟩, neg := λ f, ⟨-f, -f.linear, λ p v, by simp [add_comm]⟩, add_assoc := λ f₁ f₂ f₃, ext $ λ p, add_assoc _ _ _, zero_add := λ f, ext $ λ p, zero_add (f p), add_zero := λ f, ext $ λ p, add_zero (f p), add_comm := λ f g, ext $ λ p, add_comm (f p) (g p), add_left_neg := λ f, ext $ λ p, add_left_neg (f p) } @[simp, norm_cast] lemma coe_zero : ⇑(0 : P1 →ᵃ[k] V2) = 0 := rfl @[simp] lemma zero_linear : (0 : P1 →ᵃ[k] V2).linear = 0 := rfl @[simp, norm_cast] lemma coe_add (f g : P1 →ᵃ[k] V2) : ⇑(f + g) = f + g := rfl @[simp] lemma add_linear (f g : P1 →ᵃ[k] V2) : (f + g).linear = f.linear + g.linear := rfl /-- The space of affine maps from `P1` to `P2` is an affine space over the space of affine maps from `P1` to the vector space `V2` corresponding to `P2`. -/ instance : affine_space (P1 →ᵃ[k] V2) (P1 →ᵃ[k] P2) := { vadd := λ f g, ⟨λ p, f p +ᵥ g p, f.linear + g.linear, λ p v, by simp [vadd_vadd, add_right_comm]⟩, zero_vadd := λ f, ext $ λ p, zero_vadd _ (f p), add_vadd := λ f₁ f₂ f₃, ext $ λ p, add_vadd (f₁ p) (f₂ p) (f₃ p), vsub := λ f g, ⟨λ p, f p -ᵥ g p, f.linear - g.linear, λ p v, by simp [vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_sub, sub_add_eq_add_sub]⟩, vsub_vadd' := λ f g, ext $ λ p, vsub_vadd (f p) (g p), vadd_vsub' := λ f g, ext $ λ p, vadd_vsub (f p) (g p) } @[simp] lemma vadd_apply (f : P1 →ᵃ[k] V2) (g : P1 →ᵃ[k] P2) (p : P1) : (f +ᵥ g) p = f p +ᵥ g p := rfl @[simp] lemma vsub_apply (f g : P1 →ᵃ[k] P2) (p : P1) : (f -ᵥ g : P1 →ᵃ[k] V2) p = f p -ᵥ g p := rfl /-- `prod.fst` as an `affine_map`. -/ def fst : (P1 × P2) →ᵃ[k] P1 := { to_fun := prod.fst, linear := linear_map.fst k V1 V2, map_vadd' := λ _ _, rfl } @[simp] lemma coe_fst : ⇑(fst : (P1 × P2) →ᵃ[k] P1) = prod.fst := rfl @[simp] lemma fst_linear : (fst : (P1 × P2) →ᵃ[k] P1).linear = linear_map.fst k V1 V2 := rfl /-- `prod.snd` as an `affine_map`. -/ def snd : (P1 × P2) →ᵃ[k] P2 := { to_fun := prod.snd, linear := linear_map.snd k V1 V2, map_vadd' := λ _ _, rfl } @[simp] lemma coe_snd : ⇑(snd : (P1 × P2) →ᵃ[k] P2) = prod.snd := rfl @[simp] lemma snd_linear : (snd : (P1 × P2) →ᵃ[k] P2).linear = linear_map.snd k V1 V2 := rfl variables (k P1) omit V2 /-- Identity map as an affine map. -/ def id : P1 →ᵃ[k] P1 := { to_fun := id, linear := linear_map.id, map_vadd' := λ p v, rfl } /-- The identity affine map acts as the identity. -/ @[simp] lemma coe_id : ⇑(id k P1) = _root_.id := rfl @[simp] lemma id_linear : (id k P1).linear = linear_map.id := rfl variable {P1} /-- The identity affine map acts as the identity. -/ lemma id_apply (p : P1) : id k P1 p = p := rfl variables {k P1} instance : inhabited (P1 →ᵃ[k] P1) := ⟨id k P1⟩ include V2 V3 /-- Composition of affine maps. -/ def comp (f : P2 →ᵃ[k] P3) (g : P1 →ᵃ[k] P2) : P1 →ᵃ[k] P3 := { to_fun := f ∘ g, linear := f.linear.comp g.linear, map_vadd' := begin intros p v, rw [function.comp_app, g.map_vadd, f.map_vadd], refl end } /-- Composition of affine maps acts as applying the two functions. -/ @[simp] lemma coe_comp (f : P2 →ᵃ[k] P3) (g : P1 →ᵃ[k] P2) : ⇑(f.comp g) = f ∘ g := rfl /-- Composition of affine maps acts as applying the two functions. -/ lemma comp_apply (f : P2 →ᵃ[k] P3) (g : P1 →ᵃ[k] P2) (p : P1) : f.comp g p = f (g p) := rfl omit V3 @[simp] lemma comp_id (f : P1 →ᵃ[k] P2) : f.comp (id k P1) = f := ext $ λ p, rfl @[simp] lemma id_comp (f : P1 →ᵃ[k] P2) : (id k P2).comp f = f := ext $ λ p, rfl include V3 V4 lemma comp_assoc (f₃₄ : P3 →ᵃ[k] P4) (f₂₃ : P2 →ᵃ[k] P3) (f₁₂ : P1 →ᵃ[k] P2) : (f₃₄.comp f₂₃).comp f₁₂ = f₃₄.comp (f₂₃.comp f₁₂) := rfl omit V2 V3 V4 instance : monoid (P1 →ᵃ[k] P1) := { one := id k P1, mul := comp, one_mul := id_comp, mul_one := comp_id, mul_assoc := comp_assoc } @[simp] lemma coe_mul (f g : P1 →ᵃ[k] P1) : ⇑(f * g) = f ∘ g := rfl @[simp] lemma coe_one : ⇑(1 : P1 →ᵃ[k] P1) = _root_.id := rfl /-! ### Definition of `affine_map.line_map` and lemmas about it -/ /-- The affine map from `k` to `P1` sending `0` to `p₀` and `1` to `p₁`. -/ def line_map (p₀ p₁ : P1) : k →ᵃ[k] P1 := ((linear_map.id : k →ₗ[k] k).smul_right (p₁ -ᵥ p₀)).to_affine_map +ᵥ const k k p₀ lemma coe_line_map (p₀ p₁ : P1) : (line_map p₀ p₁ : k → P1) = λ c, c • (p₁ -ᵥ p₀) +ᵥ p₀ := rfl lemma line_map_apply (p₀ p₁ : P1) (c : k) : line_map p₀ p₁ c = c • (p₁ -ᵥ p₀) +ᵥ p₀ := rfl lemma line_map_apply_module' (p₀ p₁ : V1) (c : k) : line_map p₀ p₁ c = c • (p₁ - p₀) + p₀ := rfl lemma line_map_apply_module (p₀ p₁ : V1) (c : k) : line_map p₀ p₁ c = (1 - c) • p₀ + c • p₁ := by simp [line_map_apply_module', smul_sub, sub_smul]; abel omit V1 lemma line_map_apply_ring' (a b c : k) : line_map a b c = c * (b - a) + a := rfl lemma line_map_apply_ring (a b c : k) : line_map a b c = (1 - c) * a + c * b := line_map_apply_module a b c include V1 lemma line_map_vadd_apply (p : P1) (v : V1) (c : k) : line_map p (v +ᵥ p) c = c • v +ᵥ p := by rw [line_map_apply, vadd_vsub] @[simp] lemma line_map_linear (p₀ p₁ : P1) : (line_map p₀ p₁ : k →ᵃ[k] P1).linear = linear_map.id.smul_right (p₁ -ᵥ p₀) := add_zero _ lemma line_map_same_apply (p : P1) (c : k) : line_map p p c = p := by simp [line_map_apply] @[simp] lemma line_map_same (p : P1) : line_map p p = const k k p := ext $ line_map_same_apply p @[simp] lemma line_map_apply_zero (p₀ p₁ : P1) : line_map p₀ p₁ (0:k) = p₀ := by simp [line_map_apply] @[simp] lemma line_map_apply_one (p₀ p₁ : P1) : line_map p₀ p₁ (1:k) = p₁ := by simp [line_map_apply] include V2 @[simp] lemma apply_line_map (f : P1 →ᵃ[k] P2) (p₀ p₁ : P1) (c : k) : f (line_map p₀ p₁ c) = line_map (f p₀) (f p₁) c := by simp [line_map_apply] @[simp] lemma comp_line_map (f : P1 →ᵃ[k] P2) (p₀ p₁ : P1) : f.comp (line_map p₀ p₁) = line_map (f p₀) (f p₁) := ext $ f.apply_line_map p₀ p₁ @[simp] lemma fst_line_map (p₀ p₁ : P1 × P2) (c : k) : (line_map p₀ p₁ c).1 = line_map p₀.1 p₁.1 c := fst.apply_line_map p₀ p₁ c @[simp] lemma snd_line_map (p₀ p₁ : P1 × P2) (c : k) : (line_map p₀ p₁ c).2 = line_map p₀.2 p₁.2 c := snd.apply_line_map p₀ p₁ c omit V2 lemma line_map_symm (p₀ p₁ : P1) : line_map p₀ p₁ = (line_map p₁ p₀).comp (line_map (1:k) (0:k)) := by { rw [comp_line_map], simp } lemma line_map_apply_one_sub (p₀ p₁ : P1) (c : k) : line_map p₀ p₁ (1 - c) = line_map p₁ p₀ c := by { rw [line_map_symm p₀, comp_apply], congr, simp [line_map_apply] } @[simp] lemma line_map_vsub_left (p₀ p₁ : P1) (c : k) : line_map p₀ p₁ c -ᵥ p₀ = c • (p₁ -ᵥ p₀) := vadd_vsub _ _ @[simp] lemma left_vsub_line_map (p₀ p₁ : P1) (c : k) : p₀ -ᵥ line_map p₀ p₁ c = c • (p₀ -ᵥ p₁) := by rw [← neg_vsub_eq_vsub_rev, line_map_vsub_left, ← smul_neg, neg_vsub_eq_vsub_rev] @[simp] lemma line_map_vsub_right (p₀ p₁ : P1) (c : k) : line_map p₀ p₁ c -ᵥ p₁ = (1 - c) • (p₀ -ᵥ p₁) := by rw [← line_map_apply_one_sub, line_map_vsub_left] @[simp] lemma right_vsub_line_map (p₀ p₁ : P1) (c : k) : p₁ -ᵥ line_map p₀ p₁ c = (1 - c) • (p₁ -ᵥ p₀) := by rw [← line_map_apply_one_sub, left_vsub_line_map] lemma line_map_vadd_line_map (v₁ v₂ : V1) (p₁ p₂ : P1) (c : k) : line_map v₁ v₂ c +ᵥ line_map p₁ p₂ c = line_map (v₁ +ᵥ p₁) (v₂ +ᵥ p₂) c := ((fst : V1 × P1 →ᵃ[k] V1) +ᵥ snd).apply_line_map (v₁, p₁) (v₂, p₂) c lemma line_map_vsub_line_map (p₁ p₂ p₃ p₄ : P1) (c : k) : line_map p₁ p₂ c -ᵥ line_map p₃ p₄ c = line_map (p₁ -ᵥ p₃) (p₂ -ᵥ p₄) c := -- Why Lean fails to find this instance without a hint? by letI : affine_space (V1 × V1) (P1 × P1) := prod.add_torsor; exact ((fst : P1 × P1 →ᵃ[k] P1) -ᵥ (snd : P1 × P1 →ᵃ[k] P1)).apply_line_map (_, _) (_, _) c /-- Decomposition of an affine map in the special case when the point space and vector space are the same. -/ lemma decomp (f : V1 →ᵃ[k] V2) : (f : V1 → V2) = f.linear + (λ z, f 0) := begin ext x, calc f x = f.linear x +ᵥ f 0 : by simp [← f.map_vadd] ... = (f.linear.to_fun + λ (z : V1), f 0) x : by simp end /-- Decomposition of an affine map in the special case when the point space and vector space are the same. -/ lemma decomp' (f : V1 →ᵃ[k] V2) : (f.linear : V1 → V2) = f - (λ z, f 0) := by rw decomp ; simp only [linear_map.map_zero, pi.add_apply, add_sub_cancel, zero_add] omit V1 lemma image_interval {k : Type*} [linear_ordered_field k] (f : k →ᵃ[k] k) (a b : k) : f '' set.interval a b = set.interval (f a) (f b) := begin have : ⇑f = (λ x, x + f 0) ∘ λ x, x * (f 1 - f 0), { ext x, change f x = x • (f 1 -ᵥ f 0) +ᵥ f 0, rw [← f.linear_map_vsub, ← f.linear.map_smul, ← f.map_vadd], simp only [vsub_eq_sub, add_zero, mul_one, vadd_eq_add, sub_zero, smul_eq_mul] }, rw [this, set.image_comp], simp only [set.image_add_const_interval, set.image_mul_const_interval] end section variables {ι : Type*} {V : Π i : ι, Type*} {P : Π i : ι, Type*} [Π i, add_comm_group (V i)] [Π i, semimodule k (V i)] [Π i, add_torsor (V i) (P i)] include V /-- Evaluation at a point as an affine map. -/ def proj (i : ι) : (Π i : ι, P i) →ᵃ[k] P i := { to_fun := λ f, f i, linear := @linear_map.proj k ι _ V _ _ i, map_vadd' := λ p v, rfl } @[simp] lemma proj_apply (i : ι) (f : Π i, P i) : @proj k _ ι V P _ _ _ i f = f i := rfl @[simp] lemma proj_linear (i : ι) : (@proj k _ ι V P _ _ _ i).linear = @linear_map.proj k ι _ V _ _ i := rfl lemma pi_line_map_apply (f g : Π i, P i) (c : k) (i : ι) : line_map f g c i = line_map (f i) (g i) c := (proj i : (Π i, P i) →ᵃ[k] P i).apply_line_map f g c end end affine_map namespace affine_map variables {k : Type*} {V1 : Type*} {P1 : Type*} {V2 : Type*} [comm_ring k] [add_comm_group V1] [module k V1] [affine_space V1 P1] [add_comm_group V2] [module k V2] include V1 /-- If `k` is a commutative ring, then the set of affine maps with codomain in a `k`-module is a `k`-module. -/ instance : module k (P1 →ᵃ[k] V2) := { smul := λ c f, ⟨c • f, c • f.linear, λ p v, by simp [smul_add]⟩, one_smul := λ f, ext $ λ p, one_smul _ _, mul_smul := λ c₁ c₂ f, ext $ λ p, mul_smul _ _ _, smul_add := λ c f g, ext $ λ p, smul_add _ _ _, smul_zero := λ c, ext $ λ p, smul_zero _, add_smul := λ c₁ c₂ f, ext $ λ p, add_smul _ _ _, zero_smul := λ f, ext $ λ p, zero_smul _ _ } @[simp] lemma coe_smul (c : k) (f : P1 →ᵃ[k] V2) : ⇑(c • f) = c • f := rfl /-- `homothety c r` is the homothety about `c` with scale factor `r`. -/ def homothety (c : P1) (r : k) : P1 →ᵃ[k] P1 := r • (id k P1 -ᵥ const k P1 c) +ᵥ const k P1 c lemma homothety_def (c : P1) (r : k) : homothety c r = r • (id k P1 -ᵥ const k P1 c) +ᵥ const k P1 c := rfl lemma homothety_apply (c : P1) (r : k) (p : P1) : homothety c r p = r • (p -ᵥ c : V1) +ᵥ c := rfl lemma homothety_eq_line_map (c : P1) (r : k) (p : P1) : homothety c r p = line_map c p r := rfl @[simp] lemma homothety_one (c : P1) : homothety c (1:k) = id k P1 := by { ext p, simp [homothety_apply] } lemma homothety_mul (c : P1) (r₁ r₂ : k) : homothety c (r₁ * r₂) = (homothety c r₁).comp (homothety c r₂) := by { ext p, simp [homothety_apply, mul_smul] } @[simp] lemma homothety_zero (c : P1) : homothety c (0:k) = const k P1 c := by { ext p, simp [homothety_apply] } @[simp] lemma homothety_add (c : P1) (r₁ r₂ : k) : homothety c (r₁ + r₂) = r₁ • (id k P1 -ᵥ const k P1 c) +ᵥ homothety c r₂ := by simp only [homothety_def, add_smul, vadd_vadd] /-- `homothety` as a multiplicative monoid homomorphism. -/ def homothety_hom (c : P1) : k →* P1 →ᵃ[k] P1 := ⟨homothety c, homothety_one c, homothety_mul c⟩ @[simp] lemma coe_homothety_hom (c : P1) : ⇑(homothety_hom c : k →* _) = homothety c := rfl /-- `homothety` as an affine map. -/ def homothety_affine (c : P1) : k →ᵃ[k] (P1 →ᵃ[k] P1) := ⟨homothety c, (linear_map.lsmul k _).flip (id k P1 -ᵥ const k P1 c), function.swap (homothety_add c)⟩ @[simp] lemma coe_homothety_affine (c : P1) : ⇑(homothety_affine c : k →ᵃ[k] _) = homothety c := rfl end affine_map
5d19cf0649e0d3e17cfb8b574ed20c86ad33a508
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/tactic/linarith/frontend.lean
5ea2c37df8738cc3956997502048709c37747808
[ "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
18,580
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import tactic.linarith.verification import tactic.linarith.preprocessing /-! # `linarith`: solving linear arithmetic goals `linarith` is a tactic for solving goals with linear arithmetic. Suppose we have a set of hypotheses in `n` variables `S = {a₁x₁ + a₂x₂ + ... + aₙxₙ R b₁x₁ + b₂x₂ + ... + bₙxₙ}`, where `R ∈ {<, ≤, =, ≥, >}`. Our goal is to determine if the inequalities in `S` are jointly satisfiable, that is, if there is an assignment of values to `x₁, ..., xₙ` such that every inequality in `S` is true. Specifically, we aim to show that they are *not* satisfiable. This amounts to proving a contradiction. If our goal is also a linear inequality, we negate it and move it to a hypothesis before trying to prove `false`. When the inequalities are over a dense linear order, `linarith` is a decision procedure: it will prove `false` if and only if the inequalities are unsatisfiable. `linarith` will also run on some types like `ℤ` that are not dense orders, but it will fail to prove `false` on some unsatisfiable problems. It will run over concrete types like `ℕ`, `ℚ`, and `ℝ`, as well as abstract types that are instances of `linear_ordered_comm_ring`. ## Algorithm sketch First, the inequalities in the set `S` are rearranged into the form `tᵢ Rᵢ 0`, where `Rᵢ ∈ {<, ≤, =}` and each `tᵢ` is of the form `∑ cⱼxⱼ`. `linarith` uses an untrusted oracle to search for a certificate of unsatisfiability. The oracle searches for a list of natural number coefficients `kᵢ` such that `∑ kᵢtᵢ = 0`, where for at least one `i`, `kᵢ > 0` and `Rᵢ = <`. Given a list of such coefficients, `linarith` verifies that `∑ kᵢtᵢ = 0` using a normalization tactic such as `ring`. It proves that `∑ kᵢtᵢ < 0` by transitivity, since each component of the sum is either equal to, less than or equal to, or less than zero by hypothesis. This produces a contradiction. ## Preprocessing `linarith` does some basic preprocessing before running. Most relevantly, inequalities over natural numbers are cast into inequalities about integers, and rational division by numerals is canceled into multiplication. We do this so that we can guarantee the coefficients in the certificate are natural numbers, which allows the tactic to solve goals over types that are not fields. Preprocessors are allowed to branch, that is, to case split on disjunctions. `linarith` will succeed overall if it succeeds in all cases. This leads to exponential blowup in the number of `linarith` calls, and should be used sparingly. The default preprocessor set does not include case splits. ## Fourier-Motzkin elimination The oracle implemented to search for certificates uses Fourier-Motzkin variable elimination. This technique transorms a set of inequalities in `n` variables to an equisatisfiable set in `n - 1` variables. Once all variables have been eliminated, we conclude that the original set was unsatisfiable iff the comparison `0 < 0` is in the resulting set. While performing this elimination, we track the history of each derived comparison. This allows us to represent any comparison at any step as a positive combination of comparisons from the original set. In particular, if we derive `0 < 0`, we can find our desired list of coefficients by counting how many copies of each original comparison appear in the history. ## Implementation details `linarith` homogenizes numerical constants: the expression `1` is treated as a variable `t₀`. Often `linarith` is called on goals that have comparison hypotheses over multiple types. This creates multiple `linarith` problems, each of which is handled separately; the goal is solved as soon as one problem is found to be contradictory. Disequality hypotheses `t ≠ 0` do not fit in this pattern. `linarith` will attempt to prove equality goals by splitting them into two weak inequalities and running twice. But it does not split disequality hypotheses, since this would lead to a number of runs exponential in the number of disequalities in the context. The Fourier-Motzkin oracle is very modular. It can easily be replaced with another function of type `certificate_oracle := list comp → ℕ → tactic (rb_map ℕ ℕ)`, which takes a list of comparisons and the largest variable index appearing in those comparisons, and returns a map from comparison indices to coefficients. An alternate oracle can be specified in the `linarith_config` object. A variant, `nlinarith`, adds an extra preprocessing step to handle some basic nonlinear goals. There is a hook in the `linarith_config` configuration object to add custom preprocessing routines. The certificate checking step is *not* by reflection. `linarith` converts the certificate into a proof term of type `false`. Some of the behavior of `linarith` can be inspected with the option `set_option trace.linarith true`. Because the variable elimination happens outside the tactic monad, we cannot trace intermediate steps there. ## File structure The components of `linarith` are spread between a number of files for the sake of organization. * `lemmas.lean` contains proofs of some arithmetic lemmas that are used in preprocessing and in verification. * `datatypes.lean` contains data structures that are used across multiple files, along with some useful auxiliary functions. * `preprocessing.lean` contains functions used at the beginning of the tactic to transform hypotheses into a shape suitable for the main routine. * `parsing.lean` contains functions used to compute the linear structure of an expression. * `elimination.lean` contains the Fourier-Motzkin elimination routine. * `verification.lean` contains the certificate checking functions that produce a proof of `false`. * `frontend.lean` contains the control methods and user-facing components of the tactic. ## Tags linarith, nlinarith, lra, nra, Fourier Motzkin, linear arithmetic, linear programming -/ open tactic native namespace linarith /-! ### Control -/ /-- If `e` is a comparison `a R b` or the negation of a comparison `¬ a R b`, found in the target, `get_contr_lemma_name_and_type e` returns the name of a lemma that will change the goal to an implication, along with the type of `a` and `b`. For example, if `e` is `(a : ℕ) < b`, returns ``(`lt_of_not_ge, ℕ)``. -/ meta def get_contr_lemma_name_and_type : expr → option (name × expr) | `(@has_lt.lt %%tp %%_ _ _) := return (`lt_of_not_ge, tp) | `(@has_le.le %%tp %%_ _ _) := return (`le_of_not_gt, tp) | `(@eq %%tp _ _) := return (``eq_of_not_lt_of_not_gt, tp) | `(@ne %%tp _ _) := return (`not.intro, tp) | `(@ge %%tp %%_ _ _) := return (`le_of_not_gt, tp) | `(@gt %%tp %%_ _ _) := return (`lt_of_not_ge, tp) | `(¬ @has_lt.lt %%tp %%_ _ _) := return (`not.intro, tp) | `(¬ @has_le.le %%tp %%_ _ _) := return (`not.intro, tp) | `(¬ @eq %%tp _ _) := return (``not.intro, tp) | `(¬ @ge %%tp %%_ _ _) := return (`not.intro, tp) | `(¬ @gt %%tp %%_ _ _) := return (`not.intro, tp) | _ := none /-- `apply_contr_lemma` inspects the target to see if it can be moved to a hypothesis by negation. For example, a goal `⊢ a ≤ b` can become `a > b ⊢ false`. If this is the case, it applies the appropriate lemma and introduces the new hypothesis. It returns the type of the terms in the comparison (e.g. the type of `a` and `b` above) and the newly introduced local constant. Otherwise returns `none`. -/ meta def apply_contr_lemma : tactic (option (expr × expr)) := do t ← target, match get_contr_lemma_name_and_type t with | some (nm, tp) := do refine ((expr.const nm []) pexpr.mk_placeholder), v ← intro1, return $ some (tp, v) | none := return none end /-- `partition_by_type l` takes a list `l` of proofs of comparisons. It sorts these proofs by the type of the variables in the comparison, e.g. `(a : ℚ) < 1` and `(b : ℤ) > c` will be separated. Returns a map from a type to a list of comparisons over that type. -/ meta def partition_by_type (l : list expr) : tactic (rb_lmap expr expr) := l.mfoldl (λ m h, do tp ← ineq_prf_tp h, return $ m.insert tp h) mk_rb_map /-- Given a list `ls` of lists of proofs of comparisons, `try_linarith_on_lists cfg ls` will try to prove `false` by calling `linarith` on each list in succession. It will stop at the first proof of `false`, and fail if no contradiction is found with any list. -/ meta def try_linarith_on_lists (cfg : linarith_config) (ls : list (list expr)) : tactic expr := (first $ ls.map $ prove_false_by_linarith cfg) <|> fail "linarith failed to find a contradiction" /-- Given a list `hyps` of proofs of comparisons, `run_linarith_on_pfs cfg hyps pref_type` preprocesses `hyps` according to the list of preprocessors in `cfg`. This results in a list of branches (typically only one), each of which must succeed in order to close the goal. In each branch, we partition the list of hypotheses by type, and run `linarith` on each class in the partition; one of these must succeed in order for `linarith` to succeed on this branch. If `pref_type` is given, it will first use the class of proofs of comparisons over that type. -/ meta def run_linarith_on_pfs (cfg : linarith_config) (hyps : list expr) (pref_type : option expr) : tactic unit := let single_process := λ hyps : list expr, do linarith_trace_proofs ("after preprocessing, linarith has " ++ to_string hyps.length ++ " facts:") hyps, hyp_set ← partition_by_type hyps, linarith_trace format!"hypotheses appear in {hyp_set.size} different types", match pref_type with | some t := prove_false_by_linarith cfg (hyp_set.ifind t) <|> try_linarith_on_lists cfg (rb_map.values (hyp_set.erase t)) | none := try_linarith_on_lists cfg (rb_map.values hyp_set) end in let preprocessors := cfg.preprocessors.get_or_else default_preprocessors, preprocessors := if cfg.split_ne then linarith.remove_ne::preprocessors else preprocessors in do hyps ← preprocess preprocessors hyps, hyps.mmap' $ λ hs, do set_goals [hs.1], single_process hs.2 >>= exact /-- `filter_hyps_to_type restr_type hyps` takes a list of proofs of comparisons `hyps`, and filters it to only those that are comparisons over the type `restr_type`. -/ meta def filter_hyps_to_type (restr_type : expr) (hyps : list expr) : tactic (list expr) := hyps.mfilter $ λ h, do ht ← infer_type h, match get_contr_lemma_name_and_type ht with | some (_, htype) := succeeds $ unify htype restr_type | none := return ff end /-- A hack to allow users to write `{restr_type := ℚ}` in configuration structures. -/ meta def get_restrict_type (e : expr) : tactic expr := do m ← mk_mvar, unify `(some %%m : option Type) e, instantiate_mvars m end linarith /-! ### User facing functions -/ open linarith /-- `linarith reduce_semi only_on hyps cfg` tries to close the goal using linear arithmetic. It fails if it does not succeed at doing this. * If `reduce_semi` is true, it will unfold semireducible definitions when trying to match atomic expressions. * `hyps` is a list of proofs of comparisons to include in the search. * If `only_on` is true, the search will be restricted to `hyps`. Otherwise it will use all comparisons in the local context. -/ meta def tactic.linarith (reduce_semi : bool) (only_on : bool) (hyps : list pexpr) (cfg : linarith_config := {}) : tactic unit := focus1 $ do t ← target, -- if the target is an equality, we run `linarith` twice, to prove ≤ and ≥. if t.is_eq.is_some then linarith_trace "target is an equality: splitting" >> seq' (applyc ``eq_of_not_lt_of_not_gt) tactic.linarith else do hyps ← hyps.mmap $ λ e, i_to_expr e >>= note_anon none, when cfg.split_hypotheses (linarith_trace "trying to split hypotheses" >> try auto.split_hyps), /- If we are proving a comparison goal (and not just `false`), we consider the type of the elements in the comparison to be the "preferred" type. That is, if we find comparison hypotheses in multiple types, we will run `linarith` on the goal type first. In this case we also recieve a new variable from moving the goal to a hypothesis. Otherwise, there is no preferred type and no new variable; we simply change the goal to `false`. -/ pref_type_and_new_var_from_tgt ← apply_contr_lemma, when pref_type_and_new_var_from_tgt.is_none $ if cfg.exfalso then linarith_trace "using exfalso" >> exfalso else fail "linarith failed: target is not a valid comparison", let cfg := cfg.update_reducibility reduce_semi, let (pref_type, new_var) := pref_type_and_new_var_from_tgt.elim (none, none) (prod.map some some), -- set up the list of hypotheses, considering the `only_on` and `restrict_type` options hyps ← if only_on then return (new_var.elim [] singleton ++ hyps) else (++ hyps) <$> local_context, hyps ← (do t ← get_restrict_type cfg.restrict_type_reflect, filter_hyps_to_type t hyps) <|> return hyps, linarith_trace_proofs "linarith is running on the following hypotheses:" hyps, run_linarith_on_pfs cfg hyps pref_type setup_tactic_parser /-- Tries to prove a goal of `false` by linear arithmetic on hypotheses. If the goal is a linear (in)equality, tries to prove it by contradiction. If the goal is not `false` or an inequality, applies `exfalso` and tries linarith on the hypotheses. * `linarith` will use all relevant hypotheses in the local context. * `linarith [t1, t2, t3]` will add proof terms t1, t2, t3 to the local context. * `linarith only [h1, h2, h3, t1, t2, t3]` will use only the goal (if relevant), local hypotheses `h1`, `h2`, `h3`, and proofs `t1`, `t2`, `t3`. It will ignore the rest of the local context. * `linarith!` will use a stronger reducibility setting to identify atoms. Config options: * `linarith {exfalso := ff}` will fail on a goal that is neither an inequality nor `false` * `linarith {restrict_type := T}` will run only on hypotheses that are inequalities over `T` * `linarith {discharger := tac}` will use `tac` instead of `ring` for normalization. Options: `ring2`, `ring SOP`, `simp` * `linarith {split_hypotheses := ff}` will not destruct conjunctions in the context. -/ meta def tactic.interactive.linarith (red : parse ((tk "!")?)) (restr : parse ((tk "only")?)) (hyps : parse pexpr_list?) (cfg : linarith_config := {}) : tactic unit := tactic.linarith red.is_some restr.is_some (hyps.get_or_else []) cfg add_hint_tactic "linarith" /-- `linarith` attempts to find a contradiction between hypotheses that are linear (in)equalities. Equivalently, it can prove a linear inequality by assuming its negation and proving `false`. In theory, `linarith` should prove any goal that is true in the theory of linear arithmetic over the rationals. While there is some special handling for non-dense orders like `nat` and `int`, this tactic is not complete for these theories and will not prove every true goal. It will solve goals over arbitrary types that instantiate `linear_ordered_comm_ring`. An example: ```lean example (x y z : ℚ) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0) (h3 : 12*y - 4* z < 0) : false := by linarith ``` `linarith` will use all appropriate hypotheses and the negation of the goal, if applicable. `linarith [t1, t2, t3]` will additionally use proof terms `t1, t2, t3`. `linarith only [h1, h2, h3, t1, t2, t3]` will use only the goal (if relevant), local hypotheses `h1`, `h2`, `h3`, and proofs `t1`, `t2`, `t3`. It will ignore the rest of the local context. `linarith!` will use a stronger reducibility setting to try to identify atoms. For example, ```lean example (x : ℚ) : id x ≥ x := by linarith ``` will fail, because `linarith` will not identify `x` and `id x`. `linarith!` will. This can sometimes be expensive. `linarith {discharger := tac, restrict_type := tp, exfalso := ff}` takes a config object with five optional arguments: * `discharger` specifies a tactic to be used for reducing an algebraic equation in the proof stage. The default is `ring`. Other options currently include `ring SOP` or `simp` for basic problems. * `restrict_type` will only use hypotheses that are inequalities over `tp`. This is useful if you have e.g. both integer and rational valued inequalities in the local context, which can sometimes confuse the tactic. * `transparency` controls how hard `linarith` will try to match atoms to each other. By default it will only unfold `reducible` definitions. * If `split_hypotheses` is true, `linarith` will split conjunctions in the context into separate hypotheses. * If `exfalso` is false, `linarith` will fail when the goal is neither an inequality nor `false`. (True by default.) A variant, `nlinarith`, does some basic preprocessing to handle some nonlinear goals. The option `set_option trace.linarith true` will trace certain intermediate stages of the `linarith` routine. -/ add_tactic_doc { name := "linarith", category := doc_category.tactic, decl_names := [`tactic.interactive.linarith], tags := ["arithmetic", "decision procedure", "finishing"] } /-- An extension of `linarith` with some preprocessing to allow it to solve some nonlinear arithmetic problems. (Based on Coq's `nra` tactic.) See `linarith` for the available syntax of options, which are inherited by `nlinarith`; that is, `nlinarith!` and `nlinarith only [h1, h2]` all work as in `linarith`. The preprocessing is as follows: * For every subterm `a ^ 2` or `a * a` in a hypothesis or the goal, the assumption `0 ≤ a ^ 2` or `0 ≤ a * a` is added to the context. * For every pair of hypotheses `a1 R1 b1`, `a2 R2 b2` in the context, `R1, R2 ∈ {<, ≤, =}`, the assumption `0 R' (b1 - a1) * (b2 - a2)` is added to the context (non-recursively), where `R ∈ {<, ≤, =}` is the appropriate comparison derived from `R1, R2`. -/ meta def tactic.interactive.nlinarith (red : parse ((tk "!")?)) (restr : parse ((tk "only")?)) (hyps : parse pexpr_list?) (cfg : linarith_config := {}) : tactic unit := tactic.linarith red.is_some restr.is_some (hyps.get_or_else []) { cfg with preprocessors := some $ cfg.preprocessors.get_or_else default_preprocessors ++ [nlinarith_extras] } add_hint_tactic "nlinarith" add_tactic_doc { name := "nlinarith", category := doc_category.tactic, decl_names := [`tactic.interactive.nlinarith], tags := ["arithmetic", "decision procedure", "finishing"] }
2f486308c6ce727cd52cdcfa40dce4de860d5dd1
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/coe1.lean
55ff6dfa6ee0f46c470202744d850c775eb5a4d8
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
603
lean
prelude constant A : Type.{1} constant B : Type.{1} constant f : A → B attribute f [coercion] constant g : B → B → B constants a1 a2 a3 : A constants b1 b2 b3 : B check g a1 b1 set_option pp.coercions true check g a1 b1 constant eq {A : Type} : A → A → Type.{0} check eq a1 a2 check eq a1 b1 set_option pp.implicit true check eq a1 b1 set_option pp.universes true check eq a1 b1 inductive pair (A : Type) (B: Type) : Type := mk : A → B → pair A B check pair.mk a1 b2 check B check pair.mk set_option pp.unicode false check pair.mk set_option pp.implicit false check pair.mk check pair
e8b3e7d2db4468c130868cd2962f8584483ea0ad
3ed5a65c1ab3ce5d1a094edce8fa3287980f197b
/src/herstein/ex1_1/Q_02.lean
577b7b5d693da61f51b41f5aceea7ea91cf36358
[]
no_license
group-study-group/herstein
35d32e77158efa2cc303c84e1ee5e3bc80831137
f5a1a72eb56fa19c19ece0cb3ab6cf7ffd161f66
refs/heads/master
1,586,202,191,519
1,548,969,759,000
1,548,969,759,000
157,746,953
0
0
null
1,542,412,901,000
1,542,302,366,000
Lean
UTF-8
Lean
false
false
370
lean
import data.set.basic variable α: Type* variables A B C: set α open set theorem Q2a: A ∩ B = B ∩ A := ext $ λ x, ⟨λ ⟨ha, hb⟩, ⟨hb, ha⟩, λ ⟨hb, ha⟩, ⟨ha, hb⟩⟩ theorem Q2b: (A ∩ B) ∩ C = A ∩ (B ∩ C) := ext $ λ x, ⟨λ ⟨⟨ha, hb⟩, hc⟩, ⟨ha, ⟨hb, hc⟩⟩, λ ⟨ha, ⟨hb, hc⟩⟩, ⟨⟨ha, hb⟩, hc⟩⟩
00ed31d4f54bcca79e7a945c6126a3fed91157c8
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/hott/algebra/bundled.hlean
12026213545ad369bde9575a2fe7a329a63eb092
[ "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
2,080
hlean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad Bundled structures -/ import algebra.group open algebra namespace algebra structure Semigroup := (carrier : Type) (struct : semigroup carrier) attribute Semigroup.carrier [coercion] attribute Semigroup.struct [instance] structure CommSemigroup := (carrier : Type) (struct : comm_semigroup carrier) attribute CommSemigroup.carrier [coercion] attribute CommSemigroup.struct [instance] structure Monoid := (carrier : Type) (struct : monoid carrier) attribute Monoid.carrier [coercion] attribute Monoid.struct [instance] structure CommMonoid := (carrier : Type) (struct : comm_monoid carrier) attribute CommMonoid.carrier [coercion] attribute CommMonoid.struct [instance] structure Group := (carrier : Type) (struct : group carrier) attribute Group.carrier [coercion] attribute Group.struct [instance] structure CommGroup := (carrier : Type) (struct : comm_group carrier) attribute CommGroup.carrier [coercion] attribute CommGroup.struct [instance] structure AddSemigroup := (carrier : Type) (struct : add_semigroup carrier) attribute AddSemigroup.carrier [coercion] attribute AddSemigroup.struct [instance] structure AddCommSemigroup := (carrier : Type) (struct : add_comm_semigroup carrier) attribute AddCommSemigroup.carrier [coercion] attribute AddCommSemigroup.struct [instance] structure AddMonoid := (carrier : Type) (struct : add_monoid carrier) attribute AddMonoid.carrier [coercion] attribute AddMonoid.struct [instance] structure AddCommMonoid := (carrier : Type) (struct : add_comm_monoid carrier) attribute AddCommMonoid.carrier [coercion] attribute AddCommMonoid.struct [instance] structure AddGroup := (carrier : Type) (struct : add_group carrier) attribute AddGroup.carrier [coercion] attribute AddGroup.struct [instance] structure AddCommGroup := (carrier : Type) (struct : add_comm_group carrier) attribute AddCommGroup.carrier [coercion] attribute AddCommGroup.struct [instance] end algebra
25359049dab08e33ab1a03d0be77f12d595e0ec4
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/elabissues/ProjNotation.lean
4296395f791c0836aafec9315bf0c07dbcdc6519
[ "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
411
lean
/- Underapplying a projection notation applies the 'this' argument to the wrong parameter. It should either fail or (preferably) construct an explicit lambda. -/ -- Char → Bool #check fun c => ['a', 'b'].elem c -- List (List Char) → Bool #check ['a', 'b'].elem -- works #check fun (s : String) => s.split (fun c => ['a', 'b'].elem c) -- doesn't work #check fun (s : String) => s.split (['a', 'b'].elem)
f5b4c61c9f8ce55c7bd680f257d1e76e3b3759d1
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/data/zmod/basic.lean
1bb56443545f3023eb61bd08aef5d9850a21f84a
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
29,403
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Chris Hughes -/ import data.int.modeq import algebra.char_p.basic import data.nat.totient import ring_theory.ideal.operations /-! # Integers mod `n` Definition of the integers mod n, and the field structure on the integers mod p. ## Definitions * `zmod n`, which is for integers modulo a nat `n : ℕ` * `val a` is defined as a natural number: - for `a : zmod 0` it is the absolute value of `a` - for `a : zmod n` with `0 < n` it is the least natural number in the equivalence class * `val_min_abs` returns the integer closest to zero in the equivalence class. * A coercion `cast` is defined from `zmod n` into any ring. This is a ring hom if the ring has characteristic dividing `n` -/ namespace fin /-! ## Ring structure on `fin n` We define a commutative ring structure on `fin n`, but we do not register it as instance. Afterwords, when we define `zmod n` in terms of `fin n`, we use these definitions to register the ring structure on `zmod n` as type class instance. -/ open nat nat.modeq int /-- Negation on `fin n` -/ def has_neg (n : ℕ) : has_neg (fin n) := ⟨λ a, ⟨nat_mod (-(a.1 : ℤ)) n, begin have npos : 0 < n := lt_of_le_of_lt (nat.zero_le _) a.2, have h : (n : ℤ) ≠ 0 := int.coe_nat_ne_zero_iff_pos.2 npos, have := int.mod_lt (-(a.1 : ℤ)) h, rw [(abs_of_nonneg (int.coe_nat_nonneg n))] at this, rwa [← int.coe_nat_lt, nat_mod, to_nat_of_nonneg (int.mod_nonneg _ h)] end⟩⟩ /-- Multiplicative commutative semigroup structure on `fin (n+1)`. -/ def comm_semigroup (n : ℕ) : comm_semigroup (fin (n+1)) := { mul_assoc := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq (calc ((a * b) % (n+1) * c) ≡ a * b * c [MOD (n+1)] : modeq_mul (nat.mod_mod _ _) rfl ... ≡ a * (b * c) [MOD (n+1)] : by rw mul_assoc ... ≡ a * (b * c % (n+1)) [MOD (n+1)] : modeq_mul rfl (nat.mod_mod _ _).symm), mul_comm := λ ⟨a, _⟩ ⟨b, _⟩, fin.eq_of_veq (show (a * b) % (n+1) = (b * a) % (n+1), by rw mul_comm), ..fin.has_mul } local attribute [instance] fin.comm_semigroup private lemma one_mul_aux (n : ℕ) (a : fin (n+1)) : (1 : fin (n+1)) * a = a := begin cases n with n, { exact subsingleton.elim _ _ }, { have h₁ : (a : ℕ) % n.succ.succ = a := nat.mod_eq_of_lt a.2, apply fin.ext, simp only [coe_mul, coe_one, h₁, one_mul], } end private lemma left_distrib_aux (n : ℕ) : ∀ a b c : fin (n+1), a * (b + c) = a * b + a * c := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq (calc a * ((b + c) % (n+1)) ≡ a * (b + c) [MOD (n+1)] : modeq_mul rfl (nat.mod_mod _ _) ... ≡ a * b + a * c [MOD (n+1)] : by rw mul_add ... ≡ (a * b) % (n+1) + (a * c) % (n+1) [MOD (n+1)] : modeq_add (nat.mod_mod _ _).symm (nat.mod_mod _ _).symm) /-- Commutative ring structure on `fin (n+1)`. -/ def comm_ring (n : ℕ) : comm_ring (fin (n+1)) := { add_left_neg := λ ⟨a, ha⟩, fin.eq_of_veq (show (((-a : ℤ) % (n+1)).to_nat + a) % (n+1) = 0, from int.coe_nat_inj begin have npos : 0 < n+1 := lt_of_le_of_lt (nat.zero_le _) ha, have hn : ((n+1) : ℤ) ≠ 0 := (ne_of_lt (int.coe_nat_lt.2 npos)).symm, rw [int.coe_nat_mod, int.coe_nat_add, to_nat_of_nonneg (int.mod_nonneg _ hn), add_comm], simp, end), one_mul := fin.one_mul, mul_one := fin.mul_one, left_distrib := left_distrib_aux n, right_distrib := λ a b c, by rw [mul_comm, left_distrib_aux, mul_comm _ b, mul_comm]; refl, ..fin.has_one, ..fin.has_neg (n+1), ..fin.add_comm_monoid n, ..fin.comm_semigroup n } end fin /-- The integers modulo `n : ℕ`. -/ def zmod : ℕ → Type | 0 := ℤ | (n+1) := fin (n+1) namespace zmod instance fintype : Π (n : ℕ) [fact (0 < n)], fintype (zmod n) | 0 _ := false.elim $ nat.not_lt_zero 0 ‹0 < 0› | (n+1) _ := fin.fintype (n+1) lemma card (n : ℕ) [fact (0 < n)] : fintype.card (zmod n) = n := begin casesI n, { exfalso, exact nat.not_lt_zero 0 ‹0 < 0› }, { exact fintype.card_fin (n+1) } end instance decidable_eq : Π (n : ℕ), decidable_eq (zmod n) | 0 := int.decidable_eq | (n+1) := fin.decidable_eq _ instance has_repr : Π (n : ℕ), has_repr (zmod n) | 0 := int.has_repr | (n+1) := fin.has_repr _ instance comm_ring : Π (n : ℕ), comm_ring (zmod n) | 0 := int.comm_ring | (n+1) := fin.comm_ring n instance inhabited (n : ℕ) : inhabited (zmod n) := ⟨0⟩ /-- `val a` is a natural number defined as: - for `a : zmod 0` it is the absolute value of `a` - for `a : zmod n` with `0 < n` it is the least natural number in the equivalence class See `zmod.val_min_abs` for a variant that takes values in the integers. -/ def val : Π {n : ℕ}, zmod n → ℕ | 0 := int.nat_abs | (n+1) := (coe : fin (n + 1) → ℕ) lemma val_lt {n : ℕ} [fact (0 < n)] (a : zmod n) : a.val < n := begin casesI n, { exfalso, exact nat.not_lt_zero 0 ‹0 < 0› }, exact fin.is_lt a end @[simp] lemma val_zero : ∀ {n}, (0 : zmod n).val = 0 | 0 := rfl | (n+1) := rfl lemma val_nat_cast {n : ℕ} (a : ℕ) : (a : zmod n).val = a % n := begin casesI n, { rw [nat.mod_zero, int.nat_cast_eq_coe_nat], exact int.nat_abs_of_nat a, }, rw ← fin.of_nat_eq_coe, refl end instance (n : ℕ) : char_p (zmod n) n := { cast_eq_zero_iff := begin intro k, cases n, { simp only [int.nat_cast_eq_coe_nat, zero_dvd_iff, int.coe_nat_eq_zero], }, rw [fin.eq_iff_veq], show (k : zmod (n+1)).val = (0 : zmod (n+1)).val ↔ _, rw [val_nat_cast, val_zero, nat.dvd_iff_mod_eq_zero], end } @[simp] lemma nat_cast_self (n : ℕ) : (n : zmod n) = 0 := char_p.cast_eq_zero (zmod n) n @[simp] lemma nat_cast_self' (n : ℕ) : (n + 1 : zmod (n + 1)) = 0 := by rw [← nat.cast_add_one, nat_cast_self (n + 1)] section universal_property variables {n : ℕ} {R : Type*} section variables [has_zero R] [has_one R] [has_add R] [has_neg R] /-- Cast an integer modulo `n` to another semiring. This function is a morphism if the characteristic of `R` divides `n`. See `zmod.cast_hom` for a bundled version. -/ def cast : Π {n : ℕ}, zmod n → R | 0 := int.cast | (n+1) := λ i, i.val -- see Note [coercion into rings] @[priority 900] instance (n : ℕ) : has_coe_t (zmod n) R := ⟨cast⟩ @[simp] lemma cast_zero : ((0 : zmod n) : R) = 0 := by { cases n; refl } end /-- So-named because the coercion is `nat.cast` into `zmod`. For `nat.cast` into an arbitrary ring, see `zmod.nat_cast_val`. -/ lemma nat_cast_zmod_val {n : ℕ} [fact (0 < n)] (a : zmod n) : (a.val : zmod n) = a := begin casesI n, { exfalso, exact nat.not_lt_zero 0 ‹0 < 0› }, { change fin (n + 1) at a, rw [val, fin.ext_iff, fin.coe_coe_eq_self] } end lemma nat_cast_right_inverse [fact (0 < n)] : function.right_inverse val (coe : ℕ → zmod n) := nat_cast_zmod_val lemma nat_cast_zmod_surjective [fact (0 < n)] : function.surjective (coe : ℕ → zmod n) := nat_cast_right_inverse.surjective /-- So-named because the outer coercion is `int.cast` into `zmod`. For `int.cast` into an arbitrary ring, see `zmod.int_cast_cast`. -/ lemma int_cast_zmod_cast (a : zmod n) : ((a : ℤ) : zmod n) = a := begin cases n, { rw [int.cast_id a, int.cast_id a], }, { rw [coe_coe, int.nat_cast_eq_coe_nat, int.cast_coe_nat, fin.coe_coe_eq_self] } end lemma int_cast_right_inverse : function.right_inverse (coe : zmod n → ℤ) (coe : ℤ → zmod n) := int_cast_zmod_cast lemma int_cast_surjective : function.surjective (coe : ℤ → zmod n) := int_cast_right_inverse.surjective @[norm_cast] lemma cast_id : ∀ n (i : zmod n), ↑i = i | 0 i := int.cast_id i | (n+1) i := nat_cast_zmod_val i @[simp] lemma cast_id' : (coe : zmod n → zmod n) = id := funext (cast_id n) variables (R) [ring R] /-- The coercions are respectively `nat.cast` and `zmod.cast`. -/ @[simp] lemma nat_cast_comp_val [fact (0 < n)] : (coe : ℕ → R) ∘ (val : zmod n → ℕ) = coe := begin casesI n, { exfalso, exact nat.not_lt_zero 0 ‹0 < 0› }, refl end /-- The coercions are respectively `int.cast`, `zmod.cast`, and `zmod.cast`. -/ @[simp] lemma int_cast_comp_cast : (coe : ℤ → R) ∘ (coe : zmod n → ℤ) = coe := begin cases n, { exact congr_arg ((∘) int.cast) zmod.cast_id', }, { ext, simp } end variables {R} @[simp] lemma nat_cast_val [fact (0 < n)] (i : zmod n) : (i.val : R) = i := congr_fun (nat_cast_comp_val R) i @[simp] lemma int_cast_cast (i : zmod n) : ((i : ℤ) : R) = i := congr_fun (int_cast_comp_cast R) i section char_dvd /-! If the characteristic of `R` divides `n`, then `cast` is a homomorphism. -/ variables {n} {m : ℕ} [char_p R m] @[simp] lemma cast_one (h : m ∣ n) : ((1 : zmod n) : R) = 1 := begin casesI n, { exact int.cast_one }, show ((1 % (n+1) : ℕ) : R) = 1, cases n, { rw [nat.dvd_one] at h, substI m, apply subsingleton.elim }, rw nat.mod_eq_of_lt, { exact nat.cast_one }, exact nat.lt_of_sub_eq_succ rfl end lemma cast_add (h : m ∣ n) (a b : zmod n) : ((a + b : zmod n) : R) = a + b := begin casesI n, { apply int.cast_add }, simp only [coe_coe], symmetry, erw [fin.coe_add, ← nat.cast_add, ← sub_eq_zero, ← nat.cast_sub (nat.mod_le _ _), @char_p.cast_eq_zero_iff R _ m], exact dvd_trans h (nat.dvd_sub_mod _), end lemma cast_mul (h : m ∣ n) (a b : zmod n) : ((a * b : zmod n) : R) = a * b := begin casesI n, { apply int.cast_mul }, simp only [coe_coe], symmetry, erw [fin.coe_mul, ← nat.cast_mul, ← sub_eq_zero, ← nat.cast_sub (nat.mod_le _ _), @char_p.cast_eq_zero_iff R _ m], exact dvd_trans h (nat.dvd_sub_mod _), end /-- The canonical ring homomorphism from `zmod n` to a ring of characteristic `n`. -/ def cast_hom (h : m ∣ n) (R : Type*) [ring R] [char_p R m] : zmod n →+* R := { to_fun := coe, map_zero' := cast_zero, map_one' := cast_one h, map_add' := cast_add h, map_mul' := cast_mul h } @[simp] lemma cast_hom_apply {h : m ∣ n} (i : zmod n) : cast_hom h R i = i := rfl @[simp, norm_cast] lemma cast_sub (h : m ∣ n) (a b : zmod n) : ((a - b : zmod n) : R) = a - b := (cast_hom h R).map_sub a b @[simp, norm_cast] lemma cast_neg (h : m ∣ n) (a : zmod n) : ((-a : zmod n) : R) = -a := (cast_hom h R).map_neg a @[simp, norm_cast] lemma cast_pow (h : m ∣ n) (a : zmod n) (k : ℕ) : ((a ^ k : zmod n) : R) = a ^ k := (cast_hom h R).map_pow a k @[simp, norm_cast] lemma cast_nat_cast (h : m ∣ n) (k : ℕ) : ((k : zmod n) : R) = k := (cast_hom h R).map_nat_cast k @[simp, norm_cast] lemma cast_int_cast (h : m ∣ n) (k : ℤ) : ((k : zmod n) : R) = k := (cast_hom h R).map_int_cast k end char_dvd section char_eq /-! Some specialised simp lemmas which apply when `R` has characteristic `n`. -/ variable [char_p R n] @[simp] lemma cast_one' : ((1 : zmod n) : R) = 1 := cast_one (dvd_refl _) @[simp] lemma cast_add' (a b : zmod n) : ((a + b : zmod n) : R) = a + b := cast_add (dvd_refl _) a b @[simp] lemma cast_mul' (a b : zmod n) : ((a * b : zmod n) : R) = a * b := cast_mul (dvd_refl _) a b @[simp] lemma cast_sub' (a b : zmod n) : ((a - b : zmod n) : R) = a - b := cast_sub (dvd_refl _) a b @[simp] lemma cast_pow' (a : zmod n) (k : ℕ) : ((a ^ k : zmod n) : R) = a ^ k := cast_pow (dvd_refl _) a k @[simp, norm_cast] lemma cast_nat_cast' (k : ℕ) : ((k : zmod n) : R) = k := cast_nat_cast (dvd_refl _) k @[simp, norm_cast] lemma cast_int_cast' (k : ℤ) : ((k : zmod n) : R) = k := cast_int_cast (dvd_refl _) k instance (R : Type*) [comm_ring R] [char_p R n] : algebra (zmod n) R := (zmod.cast_hom (dvd_refl n) R).to_algebra variables (R) lemma cast_hom_injective : function.injective (zmod.cast_hom (dvd_refl n) R) := begin rw ring_hom.injective_iff, intro x, obtain ⟨k, rfl⟩ := zmod.int_cast_surjective x, rw [ring_hom.map_int_cast, char_p.int_cast_eq_zero_iff R n, char_p.int_cast_eq_zero_iff (zmod n) n], exact id end lemma cast_hom_bijective [fintype R] (h : fintype.card R = n) : function.bijective (zmod.cast_hom (dvd_refl n) R) := begin haveI : fact (0 < n) := begin rw [pos_iff_ne_zero], unfreezingI { rintro rfl }, exact fintype.card_eq_zero_iff.mp h 0 end, rw [fintype.bijective_iff_injective_and_card, zmod.card, h, eq_self_iff_true, and_true], apply zmod.cast_hom_injective end /-- The unique ring isomorphism between `zmod n` and a ring `R` of characteristic `n` and cardinality `n`. -/ noncomputable def ring_equiv [fintype R] (h : fintype.card R = n) : zmod n ≃+* R := ring_equiv.of_bijective _ (zmod.cast_hom_bijective R h) end char_eq end universal_property lemma int_coe_eq_int_coe_iff (a b : ℤ) (c : ℕ) : (a : zmod c) = (b : zmod c) ↔ a ≡ b [ZMOD c] := char_p.int_coe_eq_int_coe_iff (zmod c) c a b lemma nat_coe_eq_nat_coe_iff (a b c : ℕ) : (a : zmod c) = (b : zmod c) ↔ a ≡ b [MOD c] := begin convert zmod.int_coe_eq_int_coe_iff a b c, simp [nat.modeq.modeq_iff_dvd, int.modeq.modeq_iff_dvd], end lemma int_coe_zmod_eq_zero_iff_dvd (a : ℤ) (b : ℕ) : (a : zmod b) = 0 ↔ (b : ℤ) ∣ a := begin change (a : zmod b) = ((0 : ℤ) : zmod b) ↔ (b : ℤ) ∣ a, rw [zmod.int_coe_eq_int_coe_iff, int.modeq.modeq_zero_iff], end lemma nat_coe_zmod_eq_zero_iff_dvd (a b : ℕ) : (a : zmod b) = 0 ↔ b ∣ a := begin change (a : zmod b) = ((0 : ℕ) : zmod b) ↔ b ∣ a, rw [zmod.nat_coe_eq_nat_coe_iff, nat.modeq.modeq_zero_iff], end @[push_cast, simp] lemma int_cast_mod (a : ℤ) (b : ℕ) : ((a % b : ℤ) : zmod b) = (a : zmod b) := begin rw zmod.int_coe_eq_int_coe_iff, apply int.modeq.mod_modeq, end local attribute [semireducible] int.nonneg @[simp] lemma nat_cast_to_nat (p : ℕ) : ∀ {z : ℤ} (h : 0 ≤ z), (z.to_nat : zmod p) = z | (n : ℕ) h := by simp only [int.cast_coe_nat, int.to_nat_coe_nat] | -[1+n] h := false.elim h lemma val_injective (n : ℕ) [fact (0 < n)] : function.injective (zmod.val : zmod n → ℕ) := begin casesI n, { exfalso, exact nat.not_lt_zero 0 ‹_› }, assume a b h, ext, exact h end lemma val_one_eq_one_mod (n : ℕ) : (1 : zmod n).val = 1 % n := by rw [← nat.cast_one, val_nat_cast] lemma val_one (n : ℕ) [fact (1 < n)] : (1 : zmod n).val = 1 := by { rw val_one_eq_one_mod, exact nat.mod_eq_of_lt ‹1 < n› } lemma val_add {n : ℕ} [fact (0 < n)] (a b : zmod n) : (a + b).val = (a.val + b.val) % n := begin casesI n, { exfalso, exact nat.not_lt_zero 0 ‹0 < 0› }, { apply fin.val_add } end lemma val_mul {n : ℕ} (a b : zmod n) : (a * b).val = (a.val * b.val) % n := begin cases n, { rw nat.mod_zero, apply int.nat_abs_mul }, { apply fin.val_mul } end instance nontrivial (n : ℕ) [fact (1 < n)] : nontrivial (zmod n) := ⟨⟨0, 1, assume h, zero_ne_one $ calc 0 = (0 : zmod n).val : by rw val_zero ... = (1 : zmod n).val : congr_arg zmod.val h ... = 1 : val_one n ⟩⟩ /-- The inversion on `zmod n`. It is setup in such a way that `a * a⁻¹` is equal to `gcd a.val n`. In particular, if `a` is coprime to `n`, and hence a unit, `a * a⁻¹ = 1`. -/ def inv : Π (n : ℕ), zmod n → zmod n | 0 i := int.sign i | (n+1) i := nat.gcd_a i.val (n+1) instance (n : ℕ) : has_inv (zmod n) := ⟨inv n⟩ lemma inv_zero : ∀ (n : ℕ), (0 : zmod n)⁻¹ = 0 | 0 := int.sign_zero | (n+1) := show (nat.gcd_a _ (n+1) : zmod (n+1)) = 0, by { rw val_zero, unfold nat.gcd_a nat.xgcd nat.xgcd_aux, refl } lemma mul_inv_eq_gcd {n : ℕ} (a : zmod n) : a * a⁻¹ = nat.gcd a.val n := begin cases n, { calc a * a⁻¹ = a * int.sign a : rfl ... = a.nat_abs : by rw [int.mul_sign, int.nat_cast_eq_coe_nat] ... = a.val.gcd 0 : by rw nat.gcd_zero_right; refl }, { set k := n.succ, calc a * a⁻¹ = a * a⁻¹ + k * nat.gcd_b (val a) k : by rw [nat_cast_self, zero_mul, add_zero] ... = ↑(↑a.val * nat.gcd_a (val a) k + k * nat.gcd_b (val a) k) : by { push_cast, rw nat_cast_zmod_val, refl } ... = nat.gcd a.val k : (congr_arg coe (nat.gcd_eq_gcd_ab a.val k)).symm, } end @[simp] lemma nat_cast_mod (n : ℕ) (a : ℕ) : ((a % n : ℕ) : zmod n) = a := by conv {to_rhs, rw ← nat.mod_add_div a n}; simp lemma eq_iff_modeq_nat (n : ℕ) {a b : ℕ} : (a : zmod n) = b ↔ a ≡ b [MOD n] := begin cases n, { simp only [nat.modeq, int.coe_nat_inj', nat.mod_zero, int.nat_cast_eq_coe_nat], }, { rw [fin.ext_iff, nat.modeq, ← val_nat_cast, ← val_nat_cast], exact iff.rfl, } end lemma coe_mul_inv_eq_one {n : ℕ} (x : ℕ) (h : nat.coprime x n) : (x * x⁻¹ : zmod n) = 1 := begin rw [nat.coprime, nat.gcd_comm, nat.gcd_rec] at h, rw [mul_inv_eq_gcd, val_nat_cast, h, nat.cast_one], end /-- `unit_of_coprime` makes an element of `units (zmod n)` given a natural number `x` and a proof that `x` is coprime to `n` -/ def unit_of_coprime {n : ℕ} (x : ℕ) (h : nat.coprime x n) : units (zmod n) := ⟨x, x⁻¹, coe_mul_inv_eq_one x h, by rw [mul_comm, coe_mul_inv_eq_one x h]⟩ @[simp] lemma coe_unit_of_coprime {n : ℕ} (x : ℕ) (h : nat.coprime x n) : (unit_of_coprime x h : zmod n) = x := rfl lemma val_coe_unit_coprime {n : ℕ} (u : units (zmod n)) : nat.coprime (u : zmod n).val n := begin cases n, { rcases int.units_eq_one_or u with rfl|rfl; exact dec_trivial }, apply nat.modeq.coprime_of_mul_modeq_one ((u⁻¹ : units (zmod (n+1))) : zmod (n+1)).val, have := units.ext_iff.1 (mul_right_inv u), rw [units.coe_one] at this, rw [← eq_iff_modeq_nat, nat.cast_one, ← this], clear this, rw [← nat_cast_zmod_val ((u * u⁻¹ : units (zmod (n+1))) : zmod (n+1))], rw [units.coe_mul, val_mul, nat_cast_mod], end @[simp] lemma inv_coe_unit {n : ℕ} (u : units (zmod n)) : (u : zmod n)⁻¹ = (u⁻¹ : units (zmod n)) := begin have := congr_arg (coe : ℕ → zmod n) (val_coe_unit_coprime u), rw [← mul_inv_eq_gcd, nat.cast_one] at this, let u' : units (zmod n) := ⟨u, (u : zmod n)⁻¹, this, by rwa mul_comm⟩, have h : u = u', { apply units.ext, refl }, rw h, refl end lemma mul_inv_of_unit {n : ℕ} (a : zmod n) (h : is_unit a) : a * a⁻¹ = 1 := begin rcases h with ⟨u, rfl⟩, rw [inv_coe_unit, u.mul_inv], end lemma inv_mul_of_unit {n : ℕ} (a : zmod n) (h : is_unit a) : a⁻¹ * a = 1 := by rw [mul_comm, mul_inv_of_unit a h] /-- Equivalence between the units of `zmod n` and the subtype of terms `x : zmod n` for which `x.val` is comprime to `n` -/ def units_equiv_coprime {n : ℕ} [fact (0 < n)] : units (zmod n) ≃ {x : zmod n // nat.coprime x.val n} := { to_fun := λ x, ⟨x, val_coe_unit_coprime x⟩, inv_fun := λ x, unit_of_coprime x.1.val x.2, left_inv := λ ⟨_, _, _, _⟩, units.ext (nat_cast_zmod_val _), right_inv := λ ⟨_, _⟩, by simp } section totient open_locale nat @[simp] lemma card_units_eq_totient (n : ℕ) [fact (0 < n)] : fintype.card (units (zmod n)) = φ n := calc fintype.card (units (zmod n)) = fintype.card {x : zmod n // x.val.coprime n} : fintype.card_congr zmod.units_equiv_coprime ... = φ n : begin apply finset.card_congr (λ (a : {x : zmod n // x.val.coprime n}) _, a.1.val), { intro a, simp [(a : zmod n).val_lt, a.prop.symm] {contextual := tt} }, { intros _ _ _ _ h, rw subtype.ext_iff_val, apply val_injective, exact h, }, { intros b hb, rw [finset.mem_filter, finset.mem_range] at hb, refine ⟨⟨b, _⟩, finset.mem_univ _, _⟩, { let u := unit_of_coprime b hb.2.symm, exact val_coe_unit_coprime u }, { show zmod.val (b : zmod n) = b, rw [val_nat_cast, nat.mod_eq_of_lt hb.1], } } end end totient instance subsingleton_units : subsingleton (units (zmod 2)) := ⟨λ x y, begin cases x with x xi, cases y with y yi, revert x y xi yi, exact dec_trivial end⟩ lemma le_div_two_iff_lt_neg (n : ℕ) [hn : fact ((n : ℕ) % 2 = 1)] {x : zmod n} (hx0 : x ≠ 0) : x.val ≤ (n / 2 : ℕ) ↔ (n / 2 : ℕ) < (-x).val := begin haveI npos : fact (0 < n) := by { apply (nat.eq_zero_or_pos n).resolve_left, unfreezingI { rintro rfl }, simpa [fact] using hn, }, have hn2 : (n : ℕ) / 2 < n := nat.div_lt_of_lt_mul ((lt_mul_iff_one_lt_left npos).2 dec_trivial), have hn2' : (n : ℕ) - n / 2 = n / 2 + 1, { conv {to_lhs, congr, rw [← nat.succ_sub_one n, nat.succ_sub npos]}, rw [← nat.two_mul_odd_div_two hn, two_mul, ← nat.succ_add, nat.add_sub_cancel], }, have hxn : (n : ℕ) - x.val < n, { rw [nat.sub_lt_iff (le_of_lt x.val_lt) (le_refl _), nat.sub_self], rw ← zmod.nat_cast_zmod_val x at hx0, exact nat.pos_of_ne_zero (λ h, by simpa [h] using hx0) }, by conv {to_rhs, rw [← nat.succ_le_iff, nat.succ_eq_add_one, ← hn2', ← zero_add (- x), ← zmod.nat_cast_self, ← sub_eq_add_neg, ← zmod.nat_cast_zmod_val x, ← nat.cast_sub (le_of_lt x.val_lt), zmod.val_nat_cast, nat.mod_eq_of_lt hxn, nat.sub_le_sub_left_iff (le_of_lt x.val_lt)] } end lemma ne_neg_self (n : ℕ) [hn : fact ((n : ℕ) % 2 = 1)] {a : zmod n} (ha : a ≠ 0) : a ≠ -a := λ h, have a.val ≤ n / 2 ↔ (n : ℕ) / 2 < (-a).val := le_div_two_iff_lt_neg n ha, by rwa [← h, ← not_lt, not_iff_self] at this lemma neg_one_ne_one {n : ℕ} [fact (2 < n)] : (-1 : zmod n) ≠ 1 := char_p.neg_one_ne_one (zmod n) n @[simp] lemma neg_eq_self_mod_two : ∀ (a : zmod 2), -a = a := dec_trivial @[simp] lemma nat_abs_mod_two (a : ℤ) : (a.nat_abs : zmod 2) = a := begin cases a, { simp only [int.nat_abs_of_nat, int.cast_coe_nat, int.of_nat_eq_coe] }, { simp only [neg_eq_self_mod_two, nat.cast_succ, int.nat_abs, int.cast_neg_succ_of_nat] } end @[simp] lemma val_eq_zero : ∀ {n : ℕ} (a : zmod n), a.val = 0 ↔ a = 0 | 0 a := int.nat_abs_eq_zero | (n+1) a := by { rw fin.ext_iff, exact iff.rfl } lemma val_cast_of_lt {n : ℕ} {a : ℕ} (h : a < n) : (a : zmod n).val = a := by rw [val_nat_cast, nat.mod_eq_of_lt h] lemma neg_val' {n : ℕ} [fact (0 < n)] (a : zmod n) : (-a).val = (n - a.val) % n := begin have : ((-a).val + a.val) % n = (n - a.val + a.val) % n, { rw [←val_add, add_left_neg, nat.sub_add_cancel (le_of_lt a.val_lt), nat.mod_self, val_zero], }, calc (-a).val = val (-a) % n : by rw nat.mod_eq_of_lt ((-a).val_lt) ... = (n - val a) % n : nat.modeq.modeq_add_cancel_right rfl this end lemma neg_val {n : ℕ} [fact (0 < n)] (a : zmod n) : (-a).val = if a = 0 then 0 else n - a.val := begin rw neg_val', by_cases h : a = 0, { rw [if_pos h, h, val_zero, nat.sub_zero, nat.mod_self] }, rw if_neg h, apply nat.mod_eq_of_lt, apply nat.sub_lt ‹0 < n›, contrapose! h, rwa [nat.le_zero_iff, val_eq_zero] at h, end /-- `val_min_abs x` returns the integer in the same equivalence class as `x` that is closest to `0`, The result will be in the interval `(-n/2, n/2]`. -/ def val_min_abs : Π {n : ℕ}, zmod n → ℤ | 0 x := x | n@(_+1) x := if x.val ≤ n / 2 then x.val else (x.val : ℤ) - n @[simp] lemma val_min_abs_def_zero (x : zmod 0) : val_min_abs x = x := rfl lemma val_min_abs_def_pos {n : ℕ} [fact (0 < n)] (x : zmod n) : val_min_abs x = if x.val ≤ n / 2 then x.val else x.val - n := begin casesI n, { exfalso, exact nat.not_lt_zero 0 ‹0 < 0› }, { refl } end @[simp] lemma coe_val_min_abs : ∀ {n : ℕ} (x : zmod n), (x.val_min_abs : zmod n) = x | 0 x := int.cast_id x | k@(n+1) x := begin rw val_min_abs_def_pos, split_ifs, { rw [int.cast_coe_nat, nat_cast_zmod_val] }, { rw [int.cast_sub, int.cast_coe_nat, nat_cast_zmod_val, int.cast_coe_nat, nat_cast_self, sub_zero] } end lemma nat_abs_val_min_abs_le {n : ℕ} [fact (0 < n)] (x : zmod n) : x.val_min_abs.nat_abs ≤ n / 2 := begin rw zmod.val_min_abs_def_pos, split_ifs with h, { exact h }, have : (x.val - n : ℤ) ≤ 0, { rw [sub_nonpos, int.coe_nat_le], exact le_of_lt x.val_lt, }, rw [← int.coe_nat_le, int.of_nat_nat_abs_of_nonpos this, neg_sub], conv_lhs { congr, rw [← nat.mod_add_div n 2, int.coe_nat_add, int.coe_nat_mul, int.coe_nat_bit0, int.coe_nat_one] }, suffices : ((n % 2 : ℕ) + (n / 2) : ℤ) ≤ (val x), { rw ← sub_nonneg at this ⊢, apply le_trans this (le_of_eq _), ring }, norm_cast, calc (n : ℕ) % 2 + n / 2 ≤ 1 + n / 2 : nat.add_le_add_right (nat.le_of_lt_succ (nat.mod_lt _ dec_trivial)) _ ... ≤ x.val : by { rw add_comm, exact nat.succ_le_of_lt (lt_of_not_ge h) } end @[simp] lemma val_min_abs_zero : ∀ n, (0 : zmod n).val_min_abs = 0 | 0 := by simp only [val_min_abs_def_zero] | (n+1) := by simp only [val_min_abs_def_pos, if_true, int.coe_nat_zero, zero_le, val_zero] @[simp] lemma val_min_abs_eq_zero {n : ℕ} (x : zmod n) : x.val_min_abs = 0 ↔ x = 0 := begin cases n, { simp }, split, { simp only [val_min_abs_def_pos, int.coe_nat_succ], split_ifs with h h; assume h0, { apply val_injective, rwa [int.coe_nat_eq_zero] at h0, }, { apply absurd h0, rw sub_eq_zero, apply ne_of_lt, exact_mod_cast x.val_lt } }, { rintro rfl, rw val_min_abs_zero } end lemma nat_cast_nat_abs_val_min_abs {n : ℕ} [fact (0 < n)] (a : zmod n) : (a.val_min_abs.nat_abs : zmod n) = if a.val ≤ (n : ℕ) / 2 then a else -a := begin have : (a.val : ℤ) - n ≤ 0, by { erw [sub_nonpos, int.coe_nat_le], exact le_of_lt a.val_lt, }, rw [zmod.val_min_abs_def_pos], split_ifs, { rw [int.nat_abs_of_nat, nat_cast_zmod_val] }, { rw [← int.cast_coe_nat, int.of_nat_nat_abs_of_nonpos this, int.cast_neg, int.cast_sub], rw [int.cast_coe_nat, int.cast_coe_nat, nat_cast_self, sub_zero, nat_cast_zmod_val], } end @[simp] lemma nat_abs_val_min_abs_neg {n : ℕ} (a : zmod n) : (-a).val_min_abs.nat_abs = a.val_min_abs.nat_abs := begin cases n, { simp only [int.nat_abs_neg, val_min_abs_def_zero], }, by_cases ha0 : a = 0, { rw [ha0, neg_zero] }, by_cases haa : -a = a, { rw [haa] }, suffices hpa : (n+1 : ℕ) - a.val ≤ (n+1) / 2 ↔ (n+1 : ℕ) / 2 < a.val, { rw [val_min_abs_def_pos, val_min_abs_def_pos], rw ← not_le at hpa, simp only [if_neg ha0, neg_val, hpa, int.coe_nat_sub (le_of_lt a.val_lt)], split_ifs, all_goals { rw [← int.nat_abs_neg], congr' 1, ring } }, suffices : (((n+1 : ℕ) % 2) + 2 * ((n + 1) / 2)) - a.val ≤ (n+1) / 2 ↔ (n+1 : ℕ) / 2 < a.val, by rwa [nat.mod_add_div] at this, suffices : (n + 1) % 2 + (n + 1) / 2 ≤ val a ↔ (n + 1) / 2 < val a, by rw [nat.sub_le_iff, two_mul, ← add_assoc, nat.add_sub_cancel, this], cases (n + 1 : ℕ).mod_two_eq_zero_or_one with hn0 hn1, { split, { assume h, apply lt_of_le_of_ne (le_trans (nat.le_add_left _ _) h), contrapose! haa, rw [← zmod.nat_cast_zmod_val a, ← haa, neg_eq_iff_add_eq_zero, ← nat.cast_add], rw [char_p.cast_eq_zero_iff (zmod (n+1)) (n+1)], rw [← two_mul, ← zero_add (2 * _), ← hn0, nat.mod_add_div] }, { rw [hn0, zero_add], exact le_of_lt } }, { rw [hn1, add_comm, nat.succ_le_iff] } end lemma val_eq_ite_val_min_abs {n : ℕ} [fact (0 < n)] (a : zmod n) : (a.val : ℤ) = a.val_min_abs + if a.val ≤ n / 2 then 0 else n := by { rw [zmod.val_min_abs_def_pos], split_ifs; simp only [add_zero, sub_add_cancel] } lemma prime_ne_zero (p q : ℕ) [hp : fact p.prime] [hq : fact q.prime] (hpq : p ≠ q) : (q : zmod p) ≠ 0 := by rwa [← nat.cast_zero, ne.def, eq_iff_modeq_nat, nat.modeq.modeq_zero_iff, ← hp.coprime_iff_not_dvd, nat.coprime_primes hp hq] end zmod namespace zmod variables (p : ℕ) [fact p.prime] private lemma mul_inv_cancel_aux (a : zmod p) (h : a ≠ 0) : a * a⁻¹ = 1 := begin obtain ⟨k, rfl⟩ := nat_cast_zmod_surjective a, apply coe_mul_inv_eq_one, apply nat.coprime.symm, rwa [nat.prime.coprime_iff_not_dvd ‹p.prime›, ← char_p.cast_eq_zero_iff (zmod p)] end /-- Field structure on `zmod p` if `p` is prime. -/ instance : field (zmod p) := { mul_inv_cancel := mul_inv_cancel_aux p, inv_zero := inv_zero p, .. zmod.comm_ring p, .. zmod.has_inv p, .. zmod.nontrivial p } end zmod lemma ring_hom.ext_zmod {n : ℕ} {R : Type*} [semiring R] (f g : (zmod n) →+* R) : f = g := begin ext a, obtain ⟨k, rfl⟩ := zmod.int_cast_surjective a, let φ : ℤ →+* R := f.comp (int.cast_ring_hom (zmod n)), let ψ : ℤ →+* R := g.comp (int.cast_ring_hom (zmod n)), show φ k = ψ k, rw φ.ext_int ψ, end namespace zmod variables {n : ℕ} {R : Type*} instance subsingleton_ring_hom [semiring R] : subsingleton ((zmod n) →+* R) := ⟨ring_hom.ext_zmod⟩ instance subsingleton_ring_equiv [semiring R] : subsingleton (zmod n ≃+* R) := ⟨λ f g, by { rw ring_equiv.coe_ring_hom_inj_iff, apply ring_hom.ext_zmod _ _ }⟩ @[simp] lemma ring_hom_map_cast [ring R] (f : R →+* (zmod n)) (k : zmod n) : f k = k := by { cases n; simp } lemma ring_hom_right_inverse [ring R] (f : R →+* (zmod n)) : function.right_inverse (coe : zmod n → R) f := ring_hom_map_cast f lemma ring_hom_surjective [ring R] (f : R →+* (zmod n)) : function.surjective f := (ring_hom_right_inverse f).surjective lemma ring_hom_eq_of_ker_eq [comm_ring R] (f g : R →+* (zmod n)) (h : f.ker = g.ker) : f = g := by rw [← f.lift_of_surjective_comp (zmod.ring_hom_surjective f) g (le_of_eq h), ring_hom.ext_zmod (f.lift_of_surjective _ _ _) (ring_hom.id _), ring_hom.id_comp] end zmod
b7799c1219673a9ab4d53de8a76fb890b083122b
07c6143268cfb72beccd1cc35735d424ebcb187b
/src/category_theory/graded_object.lean
51941a7a58c00467310fdbc01a8739c191197a36
[ "Apache-2.0" ]
permissive
khoek/mathlib
bc49a842910af13a3c372748310e86467d1dc766
aa55f8b50354b3e11ba64792dcb06cccb2d8ee28
refs/heads/master
1,588,232,063,837
1,587,304,803,000
1,587,304,803,000
176,688,517
0
0
Apache-2.0
1,553,070,585,000
1,553,070,585,000
null
UTF-8
Lean
false
false
6,912
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.shift import category_theory.limits.shapes.zero import category_theory.concrete_category /-! # The category of graded objects For any type `β`, a `β`-graded object over some category `C` is just a function `β → C` into the objects of `C`. We define the category structure on these. We describe the `comap` functors obtained by precomposing with functions `β → γ`. As a consequence a fixed element (e.g. `1`) in an additive group `β` provides a shift functor on `β`-graded objects When `C` has coproducts we construct the `total` functor `graded_object β C ⥤ C`, show that it is faithful, and deduce that when `C` is concrete so is `graded_object β C`. -/ open category_theory.limits namespace category_theory universes w v u /-- A type synonym for `β → C`, used for `β`-graded objects in a category `C`. -/ def graded_object (β : Type w) (C : Type u) : Type (max w u) := β → C -- Satisfying the inhabited linter... instance inhabited_graded_object (β : Type w) (C : Type u) [inhabited C] : inhabited (graded_object β C) := ⟨λ b, inhabited.default C⟩ /-- A type synonym for `β → C`, used for `β`-graded objects in a category `C` with a shift functor given by translation by `s`. -/ @[nolint unused_arguments] -- `s` is here to distinguish type synonyms asking for different shifts abbreviation graded_object_with_shift {β : Type w} [add_comm_group β] (s : β) (C : Type u) : Type (max w u) := graded_object β C namespace graded_object variables {C : Type u} [𝒞 : category.{v} C] include 𝒞 instance category_of_graded_objects (β : Type w) : category.{(max w v)} (graded_object β C) := { hom := λ X Y, Π b : β, X b ⟶ Y b, id := λ X b, 𝟙 (X b), comp := λ X Y Z f g b, f b ≫ g b, } @[simp] lemma id_apply {β : Type w} (X : graded_object β C) (b : β) : ((𝟙 X) : Π b, X b ⟶ X b) b = 𝟙 (X b) := rfl @[simp] lemma comp_apply {β : Type w} {X Y Z : graded_object β C} (f : X ⟶ Y) (g : Y ⟶ Z) (b : β) : ((f ≫ g) : Π b, X b ⟶ Z b) b = f b ≫ g b := rfl section variable (C) /-- Pull back a graded object along a change-of-grading function. -/ @[simps] def comap {β γ : Type w} (f : β → γ) : (graded_object γ C) ⥤ (graded_object β C) := { obj := λ X, X ∘ f, map := λ X Y g b, g (f b) } /-- The natural isomorphism between pulling back a grading along the identity function, and the identity functor. -/ @[simps] def comap_id (β : Type w) : comap C (id : β → β) ≅ 𝟭 (graded_object β C) := { hom := { app := λ X, 𝟙 X }, inv := { app := λ X, 𝟙 X } }. /-- The natural isomorphism comparing between pulling back along two successive functions, and pulling back along their composition -/ @[simps] def comap_comp {β γ δ : Type w} (f : β → γ) (g : γ → δ) : comap C g ⋙ comap C f ≅ comap C (g ∘ f) := { hom := { app := λ X b, 𝟙 (X (g (f b))) }, inv := { app := λ X b, 𝟙 (X (g (f b))) } } /-- The natural isomorphism comparing between pulling back along two propositionally equal functions. -/ @[simps] def comap_eq {β γ : Type w} {f g : β → γ} (h : f = g) : comap C f ≅ comap C g := { hom := { app := λ X b, eq_to_hom begin dsimp [comap], subst h, end }, inv := { app := λ X b, eq_to_hom begin dsimp [comap], subst h, end }, } @[simp] lemma comap_eq_symm {β γ : Type w} {f g : β → γ} (h : f = g) : comap_eq C h.symm = (comap_eq C h).symm := by tidy @[simp] lemma comap_eq_trans {β γ : Type w} {f g h : β → γ} (k : f = g) (l : g = h) : comap_eq C (k.trans l) = comap_eq C k ≪≫ comap_eq C l := begin ext X b, simp, end /-- The equivalence between β-graded objects and γ-graded objects, given an equivalence between β and γ. -/ @[simps] def comap_equiv {β γ : Type w} (e : β ≃ γ) : (graded_object β C) ≌ (graded_object γ C) := { functor := comap C (e.symm : γ → β), inverse := comap C (e : β → γ), counit_iso := (comap_comp C _ _).trans (comap_eq C (by { ext, simp } )), unit_iso := (comap_eq C (by { ext, simp} )).trans (comap_comp _ _ _).symm, functor_unit_iso_comp' := λ X, begin ext b, dsimp, simp, end, } end instance has_shift {β : Type} [add_comm_group β] (s : β) : has_shift.{v} (graded_object_with_shift s C) := { shift := comap_equiv C { to_fun := λ b, b-s, inv_fun := λ b, b+s, left_inv := λ x, (by simp), right_inv := λ x, (by simp), } } instance has_zero_morphisms [has_zero_morphisms.{v} C] (β : Type w) : has_zero_morphisms.{(max w v)} (graded_object β C) := { has_zero := λ X Y, { zero := λ b, 0 } } @[simp] lemma zero_apply [has_zero_morphisms.{v} C] (β : Type w) (X Y : graded_object β C) (b : β) : (0 : X ⟶ Y) b = 0 := rfl section local attribute [instance] has_zero_object.has_zero instance has_zero_object [has_zero_object.{v} C] [has_zero_morphisms.{v} C] (β : Type w) : has_zero_object.{(max w v)} (graded_object β C) := { zero := λ b, (0 : C), unique_to := λ X, ⟨⟨λ b, 0⟩, λ f, (by ext)⟩, unique_from := λ X, ⟨⟨λ b, 0⟩, λ f, (by ext)⟩, } end end graded_object namespace graded_object -- The universes get a little hairy here, so we restrict the universe level for the grading to 0. -- Since we're typically interested in grading by ℤ or a finite group, this should be okay. -- If you're grading by things in higher universes, have fun! variables (β : Type) variables (C : Type u) [𝒞 : category.{v} C] include 𝒞 variables [has_coproducts.{v} C] /-- The total object of a graded object is the coproduct of the graded components. -/ def total : graded_object β C ⥤ C := { obj := λ X, ∐ (λ i : ulift.{v} β, X i.down), map := λ X Y f, limits.sigma.map (λ i, f i.down) }. variables [has_zero_morphisms.{v} C] /-- The `total` functor taking a graded object to the coproduct of its graded components is faithful. To prove this, we need to know that the coprojections into the coproduct are monomorphisms, which follows from the fact we have zero morphisms and decidable equality for the grading. -/ instance : faithful.{v} (total.{v u} β C) := { injectivity' := λ X Y f g w, begin classical, ext i, replace w := sigma.ι (λ i : ulift β, X i.down) ⟨i⟩ ≫= w, erw [colimit.ι_map, colimit.ι_map] at w, exact mono.right_cancellation _ _ w, end } end graded_object namespace graded_object variables (β : Type) variables (C : Type (u+1)) [large_category C] [𝒞 : concrete_category C] [has_coproducts.{u} C] [has_zero_morphisms.{u} C] include 𝒞 instance : concrete_category (graded_object β C) := { forget := total β C ⋙ forget C } instance : has_forget₂ (graded_object β C) C := { forget₂ := total β C } end graded_object end category_theory
2f13ac3c6d89fa07fde4b13e3d54d757452bca89
7a468d7c7c0949ab8b191bb62ff6d4d2af9f3917
/test/p_implies_p.lean
b4a7a81cbf31625a8faa939388ee9f34dd897ab2
[ "Apache-2.0" ]
permissive
seanpm2001/LeanProver_SMT2_Interface
c15b2fba021c406d965655b182eef54a14121b82
7ff0ce248b68ea4db2a2d4966a97b5786da05ed7
refs/heads/master
1,688,599,220,366
1,547,825,187,000
1,547,825,187,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
84
lean
import smt2 lemma p_implies_p (P : Prop) : P → P := begin intros, z3 end
952cc2b082b478a4fe46cd18cdf55432966c9c0a
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/user_recursor.lean
ef6dab08f5f0530b53ec82bf1cab8b18d7f8ef25
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
402
lean
import data.finset check @and.rec definition and.rec2 [recursor 4] {p r : Prop} (H₁ : p → r) (H₂ : p ∧ p) : r := and.rec_on H₂ (λ h₁ h₁, H₁ h₁) set_option pp.all true check ∃ x : nat, x = x print [recursor] and.rec2 print [recursor] or.rec print [recursor] and.rec print [recursor] nat.rec print [recursor] finset.induction print [recursor] list.rec print [recursor] Exists.rec
56c2431fa5e136f3c2a708fdf46e77165d8d4330
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/stage0/src/Init/Lean/Data/Format.lean
e0ae98b510ab623ad9a75b95e66ac54d0dd6802e
[ "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
7,801
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import Init.Data.Array import Init.Lean.Data.Options universes u v namespace Lean inductive Format | nil : Format | line : Format | text : String → Format | nest : Nat → Format → Format | compose : Bool → Format → Format → Format | choice : Format → Format → Format namespace Format @[export lean_format_append] protected def append (a b : Format) : Format := compose false a b instance : HasAppend Format := ⟨Format.append⟩ instance : HasCoe String Format := ⟨text⟩ instance : Inhabited Format := ⟨nil⟩ def join (xs : List Format) : Format := xs.foldl HasAppend.append "" def isNil : Format → Bool | nil => true | _ => false def flatten : Format → Format | nil => nil | line => text " " | f@(text _) => f | nest _ f => flatten f | choice f _ => flatten f | f@(compose true _ _) => f | f@(compose false f₁ f₂) => compose true (flatten f₁) (flatten f₂) @[export lean_format_group] def group : Format → Format | nil => nil | f@(text _) => f | f@(compose true _ _) => f | f => choice (flatten f) f structure SpaceResult := (found := false) (exceeded := false) (space := 0) @[inline] private def merge (w : Nat) (r₁ : SpaceResult) (r₂ : Thunk SpaceResult) : SpaceResult := if r₁.exceeded || r₁.found then r₁ else let y := r₂.get; if y.exceeded || y.found then y else let newSpace := r₁.space + y.space; { space := newSpace, exceeded := newSpace > w } def spaceUptoLine : Format → Nat → SpaceResult | nil, w => {} | line, w => { found := true } | text s, w => { space := s.length, exceeded := s.length > w } | compose _ f₁ f₂, w => merge w (spaceUptoLine f₁ w) (spaceUptoLine f₂ w) | nest _ f, w => spaceUptoLine f w | choice f₁ f₂, w => spaceUptoLine f₂ w def spaceUptoLine' : List (Nat × Format) → Nat → SpaceResult | [], w => {} | p::ps, w => merge w (spaceUptoLine p.2 w) (spaceUptoLine' ps w) partial def be : Nat → Nat → String → List (Nat × Format) → String | w, k, out, [] => out | w, k, out, (i, nil)::z => be w k out z | w, k, out, (i, (compose _ f₁ f₂))::z => be w k out ((i, f₁)::(i, f₂)::z) | w, k, out, (i, (nest n f))::z => be w k out ((i+n, f)::z) | w, k, out, (i, text s)::z => be w (k + s.length) (out ++ s) z | w, k, out, (i, line)::z => be w i ((out ++ "\n").pushn ' ' i) z | w, k, out, (i, choice f₁ f₂)::z => let r := merge w (spaceUptoLine f₁ w) (spaceUptoLine' z w); if r.exceeded then be w k out ((i, f₂)::z) else be w k out ((i, f₁)::z) @[inline] def bracket (l : String) (f : Format) (r : String) : Format := group (nest l.length $ l ++ f ++ r) @[inline] def paren (f : Format) : Format := bracket "(" f ")" @[inline] def sbracket (f : Format) : Format := bracket "[" f "]" def defIndent := 4 def defUnicode := true def defWidth := 120 def getWidth (o : Options) : Nat := o.get `format.width defWidth def getIndent (o : Options) : Nat := o.get `format.indent defIndent def getUnicode (o : Options) : Bool := o.get `format.unicode defUnicode @[init] def indentOption : IO Unit := registerOption `format.indent { defValue := defIndent, group := "format", descr := "indentation" } @[init] def unicodeOption : IO Unit := registerOption `format.unicode { defValue := defUnicode, group := "format", descr := "unicode characters" } @[init] def widthOption : IO Unit := registerOption `format.width { defValue := defWidth, group := "format", descr := "line width" } @[export lean_format_pretty] def prettyAux (f : Format) (w : Nat := defWidth) : String := be w 0 "" [(0, f)] def pretty (f : Format) (o : Options := {}) : String := prettyAux f (getWidth o) end Format open Lean.Format class HasFormat (α : Type u) := (format : α → Format) export Lean.HasFormat (format) def fmt {α : Type u} [HasFormat α] : α → Format := format instance toStringToFormat {α : Type u} [HasToString α] : HasFormat α := ⟨text ∘ toString⟩ -- note: must take precendence over the above instance to avoid premature formatting instance formatHasFormat : HasFormat Format := ⟨id⟩ instance stringHasFormat : HasFormat String := ⟨Format.text⟩ def Format.joinSep {α : Type u} [HasFormat α] : List α → Format → Format | [], sep => nil | [a], sep => format a | a::as, sep => format a ++ sep ++ Format.joinSep as sep def Format.prefixJoin {α : Type u} [HasFormat α] (pre : Format) : List α → Format | [] => nil | a::as => pre ++ format a ++ Format.prefixJoin as def Format.joinSuffix {α : Type u} [HasFormat α] : List α → Format → Format | [], suffix => nil | a::as, suffix => format a ++ suffix ++ Format.joinSuffix as suffix def List.format {α : Type u} [HasFormat α] : List α → Format | [] => "[]" | xs => sbracket $ Format.joinSep xs ("," ++ line) instance listHasFormat {α : Type u} [HasFormat α] : HasFormat (List α) := ⟨List.format⟩ instance arrayHasFormat {α : Type u} [HasFormat α] : HasFormat (Array α) := ⟨fun a => "#" ++ fmt a.toList⟩ def Option.format {α : Type u} [HasFormat α] : Option α → Format | none => "none" | some a => "some " ++ fmt a instance optionHasFormat {α : Type u} [HasFormat α] : HasFormat (Option α) := ⟨Option.format⟩ instance prodHasFormat {α : Type u} {β : Type v} [HasFormat α] [HasFormat β] : HasFormat (Prod α β) := ⟨fun ⟨a, b⟩ => paren $ format a ++ "," ++ line ++ format b⟩ def Format.joinArraySep {α : Type u} [HasFormat α] (a : Array α) (sep : Format) : Format := a.iterate nil (fun i a r => if i.val > 0 then r ++ sep ++ format a else r ++ format a) instance natHasFormat : HasFormat Nat := ⟨fun n => toString n⟩ instance uint16HasFormat : HasFormat UInt16 := ⟨fun n => toString n⟩ instance uint32HasFormat : HasFormat UInt32 := ⟨fun n => toString n⟩ instance uint64HasFormat : HasFormat UInt64 := ⟨fun n => toString n⟩ instance usizeHasFormat : HasFormat USize := ⟨fun n => toString n⟩ instance nameHasFormat : HasFormat Name := ⟨fun n => n.toString⟩ protected def Format.repr : Format → Format | nil => "Format.nil" | line => "Format.line" | text s => paren $ "Format.text" ++ line ++ repr s | nest n f => paren $ "Format.nest" ++ line ++ repr n ++ line ++ Format.repr f | compose b f₁ f₂ => paren $ "Format.compose " ++ repr b ++ line ++ Format.repr f₁ ++ line ++ Format.repr f₂ | choice f₁ f₂ => paren $ "Format.choice" ++ line ++ Format.repr f₁ ++ line ++ Format.repr f₂ instance formatHasToString : HasToString Format := ⟨Format.pretty⟩ instance : HasRepr Format := ⟨Format.pretty ∘ Format.repr⟩ def formatDataValue : DataValue → Format | DataValue.ofString v => format (repr v) | DataValue.ofBool v => format v | DataValue.ofName v => "`" ++ format v | DataValue.ofNat v => format v | DataValue.ofInt v => format v instance dataValueHasFormat : HasFormat DataValue := ⟨formatDataValue⟩ def formatEntry : Name × DataValue → Format | (n, v) => format n ++ " := " ++ format v instance entryHasFormat : HasFormat (Name × DataValue) := ⟨formatEntry⟩ def formatKVMap (m : KVMap) : Format := sbracket (Format.joinSep m.entries ", ") instance kvMapHasFormat : HasFormat KVMap := ⟨formatKVMap⟩ end Lean def String.toFormat (s : String) : Lean.Format := Lean.Format.joinSep (s.splitOn "\n") Lean.Format.line
96b1cdb58e71a3b04add2dbe9e4e1e4659672af2
4727251e0cd73359b15b664c3170e5d754078599
/src/data/list/default.lean
aeda587b9cf86f349a076b8a3ffca4c6098cbf24
[ "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
712
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad -/ import data.list.alist import data.list.basic import data.list.chain import data.list.defs import data.list.dedup import data.list.forall2 import data.list.func import data.list.intervals import data.list.lattice import data.list.min_max import data.list.indexes import data.list.nat_antidiagonal import data.list.nodup import data.list.of_fn import data.list.pairwise import data.list.perm import data.list.range import data.list.rotate import data.list.sections import data.list.sigma import data.list.sort import data.list.tfae import data.list.zip
0a297037c8aaaf89fa9a33fb3036e5ec19216553
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/algebra/valuation.lean
a89243493d4c3b1fa7f783da7bb08667dc9e14fe
[ "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,320
lean
/- Copyright (c) 2021 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import topology.algebra.nonarchimedean.bases import topology.algebra.uniform_filter_basis import ring_theory.valuation.basic /-! # The topology on a valued ring > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file, we define the non archimedean topology induced by a valuation on a ring. The main definition is a `valued` type class which equips a ring with a valuation taking values in a group with zero. Other instances are then deduced from this. -/ open_locale classical topology uniformity open set valuation noncomputable theory universes v u variables {R : Type u} [ring R] {Γ₀ : Type v} [linear_ordered_comm_group_with_zero Γ₀] namespace valuation variables (v : valuation R Γ₀) /-- The basis of open subgroups for the topology on a ring determined by a valuation. -/ lemma subgroups_basis : ring_subgroups_basis (λ γ : Γ₀ˣ, (v.lt_add_subgroup γ : add_subgroup R)) := { inter := begin rintros γ₀ γ₁, use min γ₀ γ₁, simp [valuation.lt_add_subgroup] ; tauto end, mul := begin rintros γ, cases exists_square_le γ with γ₀ h, use γ₀, rintro - ⟨r, s, r_in, s_in, rfl⟩, calc (v (r*s) : Γ₀) = v r * v s : valuation.map_mul _ _ _ ... < γ₀*γ₀ : mul_lt_mul₀ r_in s_in ... ≤ γ : by exact_mod_cast h end, left_mul := begin rintros x γ, rcases group_with_zero.eq_zero_or_unit (v x) with Hx | ⟨γx, Hx⟩, { use (1 : Γ₀ˣ), rintros y (y_in : (v y : Γ₀) < 1), change v (x * y) < _, rw [valuation.map_mul, Hx, zero_mul], exact units.zero_lt γ }, { simp only [image_subset_iff, set_of_subset_set_of, preimage_set_of_eq, valuation.map_mul], use γx⁻¹*γ, rintros y (vy_lt : v y < ↑(γx⁻¹ * γ)), change (v (x * y) : Γ₀) < γ, rw [valuation.map_mul, Hx, mul_comm], rw [units.coe_mul, mul_comm] at vy_lt, simpa using mul_inv_lt_of_lt_mul₀ vy_lt } end, right_mul := begin rintros x γ, rcases group_with_zero.eq_zero_or_unit (v x) with Hx | ⟨γx, Hx⟩, { use 1, rintros y (y_in : (v y : Γ₀) < 1), change v (y * x) < _, rw [valuation.map_mul, Hx, mul_zero], exact units.zero_lt γ }, { use γx⁻¹*γ, rintros y (vy_lt : v y < ↑(γx⁻¹ * γ)), change (v (y * x) : Γ₀) < γ, rw [valuation.map_mul, Hx], rw [units.coe_mul, mul_comm] at vy_lt, simpa using mul_inv_lt_of_lt_mul₀ vy_lt } end } end valuation /-- A valued ring is a ring that comes equipped with a distinguished valuation. The class `valued` is designed for the situation that there is a canonical valuation on the ring. TODO: show that there always exists an equivalent valuation taking values in a type belonging to the same universe as the ring. See Note [forgetful inheritance] for why we extend `uniform_space`, `uniform_add_group`. -/ class valued (R : Type u) [ring R] (Γ₀ : out_param (Type v)) [linear_ordered_comm_group_with_zero Γ₀] extends uniform_space R, uniform_add_group R := (v : valuation R Γ₀) (is_topological_valuation : ∀ s, s ∈ 𝓝 (0 : R) ↔ ∃ (γ : Γ₀ˣ), { x : R | v x < γ } ⊆ s) /-- The `dangerous_instance` linter does not check whether the metavariables only occur in arguments marked with `out_param`, so in this instance it gives a false positive. -/ attribute [nolint dangerous_instance] valued.to_uniform_space namespace valued /-- Alternative `valued` constructor for use when there is no preferred `uniform_space` structure. -/ def mk' (v : valuation R Γ₀) : valued R Γ₀ := { v := v, to_uniform_space := @topological_add_group.to_uniform_space R _ v.subgroups_basis.topology _, to_uniform_add_group := @topological_add_comm_group_is_uniform _ _ v.subgroups_basis.topology _, is_topological_valuation := begin letI := @topological_add_group.to_uniform_space R _ v.subgroups_basis.topology _, intros s, rw filter.has_basis_iff.mp v.subgroups_basis.has_basis_nhds_zero s, exact exists_congr (λ γ, by simpa), end } variables (R Γ₀) [_i : valued R Γ₀] include _i lemma has_basis_nhds_zero : (𝓝 (0 : R)).has_basis (λ _, true) (λ (γ : Γ₀ˣ), { x | v x < (γ : Γ₀) }) := by simp [filter.has_basis_iff, is_topological_valuation] lemma has_basis_uniformity : (𝓤 R).has_basis (λ _, true) (λ (γ : Γ₀ˣ), { p : R × R | v (p.2 - p.1) < (γ : Γ₀) }) := begin rw uniformity_eq_comap_nhds_zero, exact (has_basis_nhds_zero R Γ₀).comap _, end lemma to_uniform_space_eq : to_uniform_space = @topological_add_group.to_uniform_space R _ v.subgroups_basis.topology _ := uniform_space_eq ((has_basis_uniformity R Γ₀).eq_of_same_basis $ v.subgroups_basis.has_basis_nhds_zero.comap _) variables {R Γ₀} lemma mem_nhds {s : set R} {x : R} : (s ∈ 𝓝 x) ↔ ∃ (γ : Γ₀ˣ), {y | (v (y - x) : Γ₀) < γ } ⊆ s := by simp only [← nhds_translation_add_neg x, ← sub_eq_add_neg, preimage_set_of_eq, exists_true_left, ((has_basis_nhds_zero R Γ₀).comap (λ y, y - x)).mem_iff] lemma mem_nhds_zero {s : set R} : (s ∈ 𝓝 (0 : R)) ↔ ∃ γ : Γ₀ˣ, {x | v x < (γ : Γ₀) } ⊆ s := by simp only [mem_nhds, sub_zero] lemma loc_const {x : R} (h : (v x : Γ₀) ≠ 0) : {y : R | v y = v x} ∈ 𝓝 x := begin rw mem_nhds, rcases units.exists_iff_ne_zero.mpr h with ⟨γ, hx⟩, use γ, rw hx, intros y y_in, exact valuation.map_eq_of_sub_lt _ y_in end @[priority 100] instance : topological_ring R := (to_uniform_space_eq R Γ₀).symm ▸ v.subgroups_basis.to_ring_filter_basis.is_topological_ring lemma cauchy_iff {F : filter R} : cauchy F ↔ F.ne_bot ∧ ∀ γ : Γ₀ˣ, ∃ M ∈ F, ∀ x y ∈ M, (v (y - x) : Γ₀) < γ := begin rw [to_uniform_space_eq, add_group_filter_basis.cauchy_iff], apply and_congr iff.rfl, simp_rw valued.v.subgroups_basis.mem_add_group_filter_basis_iff, split, { intros h γ, exact h _ (valued.v.subgroups_basis.mem_add_group_filter_basis _) }, { rintros h - ⟨γ, rfl⟩, exact h γ } end end valued
03aadefd3b6be7a4a384bd88a1339176b967dbd8
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/tactic/tfae.lean
cf491060b42fce10569690c3e8afee052c24015e
[ "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
5,001
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Reid Barton, Simon Hudon "The Following Are Equivalent" (tfae) : Tactic for proving the equivalence of a set of proposition using various implications between them. -/ import tactic.interactive data.list.basic tactic.doc_commands import tactic.scc open expr tactic lean lean.parser namespace tactic open interactive interactive.types expr export list (tfae) namespace tfae @[derive has_reflect, derive inhabited] inductive arrow : Type | right : arrow | left_right : arrow | left : arrow meta def mk_implication : Π (re : arrow) (e₁ e₂ : expr), pexpr | arrow.right e₁ e₂ := ``(%%e₁ → %%e₂) | arrow.left_right e₁ e₂ := ``(%%e₁ ↔ %%e₂) | arrow.left e₁ e₂ := ``(%%e₂ → %%e₁) meta def mk_name : Π (re : arrow) (i₁ i₂ : nat), name | arrow.right i₁ i₂ := ("tfae_" ++ to_string i₁ ++ "_to_" ++ to_string i₂ : string) | arrow.left_right i₁ i₂ := ("tfae_" ++ to_string i₁ ++ "_iff_" ++ to_string i₂ : string) | arrow.left i₁ i₂ := ("tfae_" ++ to_string i₂ ++ "_to_" ++ to_string i₁ : string) end tfae namespace interactive open tactic.tfae list meta def parse_list : expr → option (list expr) | `([]) := pure [] | `(%%e :: %%es) := (::) e <$> parse_list es | _ := none /-- In a goal of the form `tfae [a₀, a₁, a₂]`, `tfae_have : i → j` creates the assertion `aᵢ → aⱼ`. The other possible notations are `tfae_have : i ← j` and `tfae_have : i ↔ j`. The user can also provide a label for the assertion, as with `have`: `tfae_have h : i ↔ j`. -/ meta def tfae_have (h : parse $ optional ident <* tk ":") (i₁ : parse (with_desc "i" small_nat)) (re : parse (((tk "→" <|> tk "->") *> return arrow.right) <|> ((tk "↔" <|> tk "<->") *> return arrow.left_right) <|> ((tk "←" <|> tk "<-") *> return arrow.left))) (i₂ : parse (with_desc "j" small_nat)) (discharger : tactic unit := tactic.solve_by_elim) : tactic unit := do `(tfae %%l) <- target, l ← parse_list l, e₁ ← list.nth l (i₁ - 1) <|> fail format!"index {i₁} is not between 1 and {l.length}", e₂ ← list.nth l (i₂ - 1) <|> fail format!"index {i₂} is not between 1 and {l.length}", type ← to_expr (tfae.mk_implication re e₁ e₂), let h := h.get_or_else (mk_name re i₁ i₂), tactic.assert h type, return () /-- Finds all implications and equivalences in the context to prove a goal of the form `tfae [...]`. --- The `tfae` tactic suite is a set of tactics that help with proving that certain propositions are equivalent. In `data/list/basic.lean` there is a section devoted to propositions of the form ```lean tfae [p1, p2, ..., pn] ``` where `p1`, `p2`, through, `pn` are terms of type `Prop`. This proposition asserts that all the `pi` are pairwise equivalent. There are results that allow to extract the equivalence of two propositions `pi` and `pj`. To prove a goal of the form `tfae [p1, p2, ..., pn]`, there are two tactics. The first tactic is `tfae_have`. As an argument it takes an expression of the form `i arrow j`, where `i` and `j` are two positive natural numbers, and `arrow` is an arrow such as `→`, `->`, `←`, `<-`, `↔`, or `<->`. The tactic `tfae_have : i arrow j` sets up a subgoal in which the user has to prove the equivalence (or implication) of `pi` and `pj`. The remaining tactic, `tfae_finish`, is a finishing tactic. It collects all implications and equivalences from the local context and computes their transitive closure to close the main goal. `tfae_have` and `tfae_finish` can be used together in a proof as follows: ```lean example (a b c d : Prop) : tfae [a,b,c,d] := begin tfae_have : 3 → 1, { /- prove c → a -/ }, tfae_have : 2 → 3, { /- prove b → c -/ }, tfae_have : 2 ← 1, { /- prove a → b -/ }, tfae_have : 4 ↔ 2, { /- prove d ↔ b -/ }, -- a b c d : Prop, -- tfae_3_to_1 : c → a, -- tfae_2_to_3 : b → c, -- tfae_1_to_2 : a → b, -- tfae_4_iff_2 : d ↔ b -- ⊢ tfae [a, b, c, d] tfae_finish, end ``` -/ meta def tfae_finish : tactic unit := applyc ``tfae_nil <|> closure.with_new_closure (λ cl, do impl_graph.mk_scc cl, `(tfae %%l) ← target, l ← parse_list l, (_,r,_) ← cl.root l.head, refine ``(tfae_of_forall %%r _ _), thm ← mk_const ``forall_mem_cons, l.mmap' (λ e, do rewrite_target thm, split, (_,r',p) ← cl.root e, tactic.exact p ), applyc ``forall_mem_nil, pure ()) end interactive end tactic add_tactic_doc { name := "tfae", category := doc_category.tactic, decl_names := [`tactic.interactive.tfae_have, `tactic.interactive.tfae_finish], tags := ["logic"], inherit_description_from := `tactic.interactive.tfae_finish }
15b3474309d3f7021fc4393640fbdb757b38e1cb
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/witt_vector/mul_p.lean
750ab4c8d9e65b1495722e9cc98b86f9148a7307
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
2,882
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import ring_theory.witt_vector.is_poly /-! ## Multiplication by `n` in the ring of Witt vectors > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we show that multiplication by `n` in the ring of Witt vectors is a polynomial function. We then use this fact to show that the composition of Frobenius and Verschiebung is equal to multiplication by `p`. ### Main declarations * `mul_n_is_poly`: multiplication by `n` is a polynomial function ## References * [Hazewinkel, *Witt Vectors*][Haze09] * [Commelin and Lewis, *Formalizing the Ring of Witt Vectors*][CL21] -/ namespace witt_vector variables {p : ℕ} {R : Type*} [hp : fact p.prime] [comm_ring R] local notation `𝕎` := witt_vector p -- type as `\bbW` open mv_polynomial noncomputable theory include hp variable (p) /-- `witt_mul_n p n` is the family of polynomials that computes the coefficients of `x * n` in terms of the coefficients of the Witt vector `x`. -/ noncomputable def witt_mul_n : ℕ → ℕ → mv_polynomial ℕ ℤ | 0 := 0 | (n+1) := λ k, bind₁ (function.uncurry $ ![(witt_mul_n n), X]) (witt_add p k) variable {p} lemma mul_n_coeff (n : ℕ) (x : 𝕎 R) (k : ℕ) : (x * n).coeff k = aeval x.coeff (witt_mul_n p n k) := begin induction n with n ih generalizing k, { simp only [nat.nat_zero_eq_zero, nat.cast_zero, mul_zero, zero_coeff, witt_mul_n, alg_hom.map_zero, pi.zero_apply], }, { rw [witt_mul_n, nat.succ_eq_add_one, nat.cast_add, nat.cast_one, mul_add, mul_one, aeval_bind₁, add_coeff], apply eval₂_hom_congr (ring_hom.ext_int _ _) _ rfl, ext1 ⟨b, i⟩, fin_cases b, { simp only [function.uncurry, matrix.cons_val_zero, ih] }, { simp only [function.uncurry, matrix.cons_val_one, matrix.head_cons, aeval_X] } } end variables (p) /-- Multiplication by `n` is a polynomial function. -/ @[is_poly] lemma mul_n_is_poly (n : ℕ) : is_poly p (λ R _Rcr x, by exactI x * n) := ⟨⟨witt_mul_n p n, λ R _Rcr x, by { funext k, exactI mul_n_coeff n x k }⟩⟩ @[simp] lemma bind₁_witt_mul_n_witt_polynomial (n k : ℕ) : bind₁ (witt_mul_n p n) (witt_polynomial p ℤ k) = n * witt_polynomial p ℤ k := begin induction n with n ih, { simp only [witt_mul_n, nat.cast_zero, zero_mul, bind₁_zero_witt_polynomial] }, { rw [witt_mul_n, ← bind₁_bind₁, witt_add, witt_structure_int_prop], simp only [alg_hom.map_add, nat.cast_succ, bind₁_X_right], rw [add_mul, one_mul, bind₁_rename, bind₁_rename], simp only [ih, function.uncurry, function.comp, bind₁_X_left, alg_hom.id_apply, matrix.cons_val_zero, matrix.head_cons, matrix.cons_val_one], } end end witt_vector
bdf06e380c7728642d653a0d350bf339880ca4e9
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/linear_algebra/affine_space/finite_dimensional.lean
15ae7242e0116752479161ff024e3208bf1dee01
[ "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
4,692
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Joseph Myers. -/ import linear_algebra.affine_space.independent import linear_algebra.finite_dimensional noncomputable theory open_locale big_operators open_locale classical /-! # Finite-dimensional subspaces of affine spaces. This file provides a few results relating to finite-dimensional subspaces of affine spaces. -/ section affine_space' variables (k : Type*) {V : Type*} {P : Type*} [field k] [add_comm_group V] [module k V] [affine_space V P] variables {ι : Type*} include V open finite_dimensional /-- The `vector_span` of a finite set is finite-dimensional. -/ lemma finite_dimensional_vector_span_of_finite {s : set P} (h : set.finite s) : finite_dimensional k (vector_span k s) := span_of_finite k $ vsub_set_finite_of_finite h /-- The direction of the affine span of a finite set is finite-dimensional. -/ lemma finite_dimensional_direction_affine_span_of_finite {s : set P} (h : set.finite s) : finite_dimensional k (affine_span k s).direction := (direction_affine_span k s).symm ▸ finite_dimensional_vector_span_of_finite k h /-- The direction of the affine span of a family indexed by a `fintype` is finite-dimensional. -/ instance finite_dimensional_direction_affine_span_of_fintype [fintype ι] (p : ι → P) : finite_dimensional k (affine_span k (set.range p)).direction := finite_dimensional_direction_affine_span_of_finite k (set.finite_range _) /-- The direction of the affine span of a subset of a family indexed by a `fintype` is finite-dimensional. -/ instance finite_dimensional_direction_affine_span_image_of_fintype [fintype ι] (p : ι → P) (s : set ι) : finite_dimensional k (affine_span k (p '' s)).direction := finite_dimensional_direction_affine_span_of_finite k ((set.finite.of_fintype _).image _) variables {k} /-- The `vector_span` of a finite affinely independent family has dimension one less than its cardinality. -/ lemma findim_vector_span_of_affine_independent [fintype ι] {p : ι → P} (hi : affine_independent k p) {n : ℕ} (hc : fintype.card ι = n + 1) : findim k (vector_span k (set.range p)) = n := begin have hi' := affine_independent_set_of_affine_independent hi, have hc' : fintype.card (set.range p) = n + 1, by rwa set.card_range_of_injective (injective_of_affine_independent hi), have hn : (set.range p).nonempty, { refine set.range_nonempty_iff_nonempty.2 (fintype.card_pos_iff.1 _), simp [hc] }, rcases hn with ⟨p₁, hp₁⟩, rw affine_independent_set_iff_linear_independent_vsub k hp₁ at hi', have hfr : (set.range p \ {p₁}).finite := (set.finite_range _).subset (set.diff_subset _ _), haveI := hfr.fintype, have hf : set.finite ((λ (p : P), p -ᵥ p₁) '' (set.range p \ {p₁})) := hfr.image _, haveI := hf.fintype, have hc : hf.to_finset.card = n, { rw [hf.card_to_finset, set.card_image_of_injective (set.range p \ {p₁}) (vsub_left_injective _)], have hd : insert p₁ (set.range p \ {p₁}) = set.range p, { rw [set.insert_diff_singleton, set.insert_eq_of_mem hp₁] }, have hc'' : fintype.card ↥(insert p₁ (set.range p \ {p₁})) = n + 1, { convert hc' }, rw set.card_insert (set.range p \ {p₁}) (λ h, ((set.mem_diff p₁).2 h).2 rfl) at hc'', simpa using hc'' }, rw [vector_span_eq_span_vsub_set_right_ne k hp₁, findim_span_set_eq_card _ hi', ←hc], congr end /-- The `vector_span` of a finite affinely independent family whose cardinality is one more than that of the finite-dimensional space is `⊤`. -/ lemma vector_span_eq_top_of_affine_independent_of_card_eq_findim_add_one [finite_dimensional k V] [fintype ι] {p : ι → P} (hi : affine_independent k p) (hc : fintype.card ι = findim k V + 1) : vector_span k (set.range p) = ⊤ := eq_top_of_findim_eq $ findim_vector_span_of_affine_independent hi hc /-- The `affine_span` of a finite affinely independent family whose cardinality is one more than that of the finite-dimensional space is `⊤`. -/ lemma affine_span_eq_top_of_affine_independent_of_card_eq_findim_add_one [finite_dimensional k V] [fintype ι] {p : ι → P} (hi : affine_independent k p) (hc : fintype.card ι = findim k V + 1) : affine_span k (set.range p) = ⊤ := begin have hn : (set.range p).nonempty, { refine set.range_nonempty_iff_nonempty.2 (fintype.card_pos_iff.1 _), simp [hc] }, rw [←affine_subspace.direction_eq_top_iff_of_nonempty ((affine_span_nonempty k _).2 hn), direction_affine_span], exact vector_span_eq_top_of_affine_independent_of_card_eq_findim_add_one hi hc end end affine_space'
bda55bf96ad46d74c0b3d671b415f038a4a2b913
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/analysis/normed_space/is_R_or_C.lean
8bb5398339dde1753ced80eb2f14b1ad50a51248
[ "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
3,294
lean
/- Copyright (c) 2021 Kalle Kytölä. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kalle Kytölä -/ import analysis.normed_space.operator_norm import analysis.complex.basic /-! # Normed spaces over R or C This file is about results on normed spaces over the fields `ℝ` and `ℂ`. ## Main definitions None. ## Main theorems * `continuous_linear_map.op_norm_bound_of_ball_bound`: A bound on the norms of values of a linear map in a ball yields a bound on the operator norm. ## Notes This file exists mainly to avoid importing `is_R_or_C` in the main normed space theory files. -/ open metric @[simp] lemma is_R_or_C.norm_coe_norm {𝕜 : Type*} [is_R_or_C 𝕜] {E : Type*} [normed_group E] {z : E} : ∥(∥ z ∥ : 𝕜)∥ = ∥ z ∥ := by { unfold_coes, simp only [norm_algebra_map_eq, ring_hom.to_fun_eq_coe, norm_norm], } variables {𝕜 : Type*} [is_R_or_C 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] lemma linear_map.bound_of_sphere_bound {r : ℝ} (r_pos : 0 < r) (c : ℝ) (f : E →ₗ[𝕜] 𝕜) (h : ∀ z ∈ sphere (0 : E) r, ∥ f z ∥ ≤ c) (z : E) : ∥ f z ∥ ≤ c / r * ∥ z ∥ := begin by_cases z_zero : z = 0, { rw z_zero, simp only [linear_map.map_zero, norm_zero, mul_zero], }, set z₁ := (r * ∥ z ∥⁻¹ : 𝕜) • z with hz₁, have norm_f_z₁ : ∥ f z₁ ∥ ≤ c, { apply h z₁, rw [mem_sphere_zero_iff_norm, hz₁, norm_smul, normed_field.norm_mul], simp only [normed_field.norm_inv, is_R_or_C.norm_coe_norm], rw [mul_assoc, inv_mul_cancel (norm_pos_iff.mpr z_zero).ne.symm, mul_one], unfold_coes, simp only [norm_algebra_map_eq, ring_hom.to_fun_eq_coe], exact abs_of_pos r_pos, }, have r_ne_zero : (r : 𝕜) ≠ 0 := (algebra_map ℝ 𝕜).map_ne_zero.mpr r_pos.ne.symm, have eq : f z = ∥ z ∥ / r * (f z₁), { rw [hz₁, linear_map.map_smul, smul_eq_mul], rw [← mul_assoc, ← mul_assoc, div_mul_cancel _ r_ne_zero, mul_inv_cancel, one_mul], simp only [z_zero, is_R_or_C.of_real_eq_zero, norm_eq_zero, ne.def, not_false_iff], }, rw [eq, normed_field.norm_mul, normed_field.norm_div, is_R_or_C.norm_coe_norm, is_R_or_C.norm_of_nonneg r_pos.le, div_mul_eq_mul_div, div_mul_eq_mul_div, mul_comm], apply div_le_div _ _ r_pos rfl.ge, { exact mul_nonneg ((norm_nonneg _).trans norm_f_z₁) (norm_nonneg z), }, apply mul_le_mul norm_f_z₁ rfl.le (norm_nonneg z) ((norm_nonneg _).trans norm_f_z₁), end lemma linear_map.bound_of_ball_bound {r : ℝ} (r_pos : 0 < r) (c : ℝ) (f : E →ₗ[𝕜] 𝕜) (h : ∀ z ∈ closed_ball (0 : E) r, ∥ f z ∥ ≤ c) : ∀ (z : E), ∥ f z ∥ ≤ c / r * ∥ z ∥ := begin apply linear_map.bound_of_sphere_bound r_pos c f, exact λ z hz, h z hz.le, end lemma continuous_linear_map.op_norm_bound_of_ball_bound {r : ℝ} (r_pos : 0 < r) (c : ℝ) (f : E →L[𝕜] 𝕜) (h : ∀ z ∈ closed_ball (0 : E) r, ∥ f z ∥ ≤ c) : ∥ f ∥ ≤ c / r := begin apply continuous_linear_map.op_norm_le_bound, { apply div_nonneg _ r_pos.le, exact (norm_nonneg _).trans (h 0 (by simp only [norm_zero, mem_closed_ball, dist_zero_left, r_pos.le])), }, apply linear_map.bound_of_ball_bound r_pos, exact λ z hz, h z hz, end
aefeaf51a32deb8b63ae3b0432e0cd12ea87e51d
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/order/galois_connection.lean
9f179810090f82fbd82da264ca5e58c2880b0185
[ "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
30,292
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 order.complete_lattice import order.order_dual /-! # Galois connections, insertions and coinsertions Galois connections are order theoretic adjoints, i.e. a pair of functions `u` and `l`, such that `∀ a b, l a ≤ b ↔ a ≤ u b`. ## Main definitions * `galois_connection`: A Galois connection is a pair of functions `l` and `u` satisfying `l a ≤ b ↔ a ≤ u b`. They are special cases of adjoint functors in category theory, but do not depend on the category theory library in mathlib. * `galois_insertion`: A Galois insertion is a Galois connection where `l ∘ u = id` * `galois_coinsertion`: A Galois coinsertion is a Galois connection where `u ∘ l = id` ## Implementation details Galois insertions can be used to lift order structures from one type to another. For example if `α` is a complete lattice, and `l : α → β`, and `u : β → α` form a Galois insertion, then `β` is also a complete lattice. `l` is the lower adjoint and `u` is the upper adjoint. An example of a Galois insertion is in group theory. If `G` is a group, then there is a Galois insertion between the set of subsets of `G`, `set G`, and the set of subgroups of `G`, `subgroup G`. The lower adjoint is `subgroup.closure`, taking the `subgroup` generated by a `set`, and the upper adjoint is the coercion from `subgroup G` to `set G`, taking the underlying set of a subgroup. Naively lifting a lattice structure along this Galois insertion would mean that the definition of `inf` on subgroups would be `subgroup.closure (↑S ∩ ↑T)`. This is an undesirable definition because the intersection of subgroups is already a subgroup, so there is no need to take the closure. For this reason a `choice` function is added as a field to the `galois_insertion` structure. It has type `Π S : set G, ↑(closure S) ≤ S → subgroup G`. When `↑(closure S) ≤ S`, then `S` is already a subgroup, so this function can be defined using `subgroup.mk` and not `closure`. This means the infimum of subgroups will be defined to be the intersection of sets, paired with a proof that intersection of subgroups is a subgroup, rather than the closure of the intersection. -/ open function set universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {a a₁ a₂ : α} {b b₁ b₂ : β} /-- A Galois connection is a pair of functions `l` and `u` satisfying `l a ≤ b ↔ a ≤ u b`. They are special cases of adjoint functors in category theory, but do not depend on the category theory library in mathlib. -/ def galois_connection [preorder α] [preorder β] (l : α → β) (u : β → α) := ∀ a b, l a ≤ b ↔ a ≤ u b /-- Makes a Galois connection from an order-preserving bijection. -/ theorem order_iso.to_galois_connection [preorder α] [preorder β] (oi : α ≃o β) : galois_connection oi oi.symm := λ b g, oi.rel_symm_apply.symm namespace galois_connection section variables [preorder α] [preorder β] {l : α → β} {u : β → α} (gc : galois_connection l u) lemma monotone_intro (hu : monotone u) (hl : monotone l) (hul : ∀ a, a ≤ u (l a)) (hlu : ∀ a, l (u a) ≤ a) : galois_connection l u := λ a b, ⟨λ h, (hul _).trans (hu h), λ h, (hl h).trans (hlu _)⟩ include gc protected lemma dual {l : α → β} {u : β → α} (gc : galois_connection l u) : galois_connection (order_dual.to_dual ∘ u ∘ order_dual.of_dual) (order_dual.to_dual ∘ l ∘ order_dual.of_dual) := λ a b, (gc b a).symm lemma l_le {a : α} {b : β} : a ≤ u b → l a ≤ b := (gc _ _).mpr lemma le_u {a : α} {b : β} : l a ≤ b → a ≤ u b := (gc _ _).mp lemma le_u_l (a) : a ≤ u (l a) := gc.le_u $ le_rfl lemma l_u_le (a) : l (u a) ≤ a := gc.l_le $ le_rfl lemma monotone_u : monotone u := λ a b H, gc.le_u ((gc.l_u_le a).trans H) lemma monotone_l : monotone l := gc.dual.monotone_u.dual lemma upper_bounds_l_image (s : set α) : upper_bounds (l '' s) = u ⁻¹' upper_bounds s := set.ext $ λ b, by simp [upper_bounds, gc _ _] lemma lower_bounds_u_image (s : set β) : lower_bounds (u '' s) = l ⁻¹' lower_bounds s := gc.dual.upper_bounds_l_image s lemma bdd_above_l_image {s : set α} : bdd_above (l '' s) ↔ bdd_above s := ⟨λ ⟨x, hx⟩, ⟨u x, by rwa [gc.upper_bounds_l_image] at hx⟩, gc.monotone_l.map_bdd_above⟩ lemma bdd_below_u_image {s : set β} : bdd_below (u '' s) ↔ bdd_below s := gc.dual.bdd_above_l_image lemma is_lub_l_image {s : set α} {a : α} (h : is_lub s a) : is_lub (l '' s) (l a) := ⟨gc.monotone_l.mem_upper_bounds_image h.left, λ b hb, gc.l_le $ h.right $ by rwa [gc.upper_bounds_l_image] at hb⟩ lemma is_glb_u_image {s : set β} {b : β} (h : is_glb s b) : is_glb (u '' s) (u b) := gc.dual.is_lub_l_image h lemma is_least_l {a : α} : is_least {b | a ≤ u b} (l a) := ⟨gc.le_u_l _, λ b hb, gc.l_le hb⟩ lemma is_greatest_u {b : β} : is_greatest {a | l a ≤ b} (u b) := gc.dual.is_least_l lemma is_glb_l {a : α} : is_glb {b | a ≤ u b} (l a) := gc.is_least_l.is_glb lemma is_lub_u {b : β} : is_lub { a | l a ≤ b } (u b) := gc.is_greatest_u.is_lub /-- If `(l, u)` is a Galois connection, then the relation `x ≤ u (l y)` is a transitive relation. If `l` is a closure operator (`submodule.span`, `subgroup.closure`, ...) and `u` is the coercion to `set`, this reads as "if `U` is in the closure of `V` and `V` is in the closure of `W` then `U` is in the closure of `W`". -/ lemma le_u_l_trans {x y z : α} (hxy : x ≤ u (l y)) (hyz : y ≤ u (l z)) : x ≤ u (l z) := hxy.trans (gc.monotone_u $ gc.l_le hyz) lemma l_u_le_trans {x y z : β} (hxy : l (u x) ≤ y) (hyz : l (u y) ≤ z) : l (u x) ≤ z := (gc.monotone_l $ gc.le_u hxy).trans hyz end section partial_order variables [partial_order α] [preorder β] {l : α → β} {u : β → α} (gc : galois_connection l u) include gc lemma u_l_u_eq_u (b : β) : u (l (u b)) = u b := (gc.monotone_u (gc.l_u_le _)).antisymm (gc.le_u_l _) lemma u_l_u_eq_u' : u ∘ l ∘ u = u := funext gc.u_l_u_eq_u lemma u_unique {l' : α → β} {u' : β → α} (gc' : galois_connection l' u') (hl : ∀ a, l a = l' a) {b : β} : u b = u' b := le_antisymm (gc'.le_u $ hl (u b) ▸ gc.l_u_le _) (gc.le_u $ (hl (u' b)).symm ▸ gc'.l_u_le _) /-- If there exists a `b` such that `a = u a`, then `b = l a` is one such element. -/ lemma exists_eq_u (a : α) : (∃ b : β, a = u b) ↔ a = u (l a) := ⟨λ ⟨S, hS⟩, hS.symm ▸ (gc.u_l_u_eq_u _).symm, λ HI, ⟨_, HI⟩ ⟩ lemma u_eq {z : α} {y : β} : u y = z ↔ ∀ x, x ≤ z ↔ l x ≤ y := begin split, { rintros rfl x, exact (gc x y).symm }, { intros H, exact ((H $ u y).mpr (gc.l_u_le y)).antisymm ((gc _ _).mp $ (H z).mp le_rfl) } end end partial_order section partial_order variables [preorder α] [partial_order β] {l : α → β} {u : β → α} (gc : galois_connection l u) include gc lemma l_u_l_eq_l (a : α) : l (u (l a)) = l a := (gc.l_u_le _).antisymm (gc.monotone_l (gc.le_u_l _)) lemma l_u_l_eq_l' : l ∘ u ∘ l = l := funext gc.l_u_l_eq_l lemma l_unique {l' : α → β} {u' : β → α} (gc' : galois_connection l' u') (hu : ∀ b, u b = u' b) {a : α} : l a = l' a := le_antisymm (gc.l_le $ (hu (l' a)).symm ▸ gc'.le_u_l _) (gc'.l_le $ hu (l a) ▸ gc.le_u_l _) /-- If there exists an `a` such that `b = l a`, then `a = u b` is one such element. -/ lemma exists_eq_l (b : β) : (∃ a : α, b = l a) ↔ b = l (u b) := ⟨λ ⟨S, hS⟩, hS.symm ▸ (gc.l_u_l_eq_l _).symm, λ HI, ⟨_, HI⟩ ⟩ lemma l_eq {x : α} {z : β} : l x = z ↔ ∀ y, z ≤ y ↔ x ≤ u y := begin split, { rintros rfl y, exact gc x y }, { intros H, exact ((gc _ _).mpr $ (H z).mp le_rfl).antisymm ((H $ l x).mpr (gc.le_u_l x)) } end end partial_order section order_top variables [partial_order α] [preorder β] [order_top α] [order_top β] {l : α → β} {u : β → α} (gc : galois_connection l u) include gc lemma u_top : u ⊤ = ⊤ := top_unique $ gc.le_u le_top end order_top section order_bot variables [preorder α] [partial_order β] [order_bot α] [order_bot β] {l : α → β} {u : β → α} (gc : galois_connection l u) include gc lemma l_bot : l ⊥ = ⊥ := gc.dual.u_top end order_bot section semilattice_sup variables [semilattice_sup α] [semilattice_sup β] {l : α → β} {u : β → α} (gc : galois_connection l u) include gc lemma l_sup : l (a₁ ⊔ a₂) = l a₁ ⊔ l a₂ := (gc.is_lub_l_image is_lub_pair).unique $ by simp only [image_pair, is_lub_pair] end semilattice_sup section semilattice_inf variables [semilattice_inf α] [semilattice_inf β] {l : α → β} {u : β → α} (gc : galois_connection l u) include gc lemma u_inf : u (b₁ ⊓ b₂) = u b₁ ⊓ u b₂ := gc.dual.l_sup end semilattice_inf section complete_lattice variables [complete_lattice α] [complete_lattice β] {l : α → β} {u : β → α} (gc : galois_connection l u) include gc lemma l_supr {f : ι → α} : l (supr f) = (⨆i, l (f i)) := eq.symm $ is_lub.supr_eq $ show is_lub (range (l ∘ f)) (l (supr f)), by rw [range_comp, ← Sup_range]; exact gc.is_lub_l_image (is_lub_Sup _) lemma u_infi {f : ι → β} : u (infi f) = (⨅i, u (f i)) := gc.dual.l_supr lemma l_Sup {s : set α} : l (Sup s) = (⨆a ∈ s, l a) := by simp only [Sup_eq_supr, gc.l_supr] lemma u_Inf {s : set β} : u (Inf s) = (⨅a ∈ s, u a) := gc.dual.l_Sup end complete_lattice section linear_order variables [linear_order α] [linear_order β] {l : α → β} {u : β → α} (gc : galois_connection l u) lemma lt_iff_lt {a : α} {b : β} : b < l a ↔ u b < a := lt_iff_lt_of_le_iff_le (gc a b) end linear_order /- Constructing Galois connections -/ section constructions protected lemma id [pα : preorder α] : @galois_connection α α pα pα id id := λ a b, iff.intro (λ x, x) (λ x, x) protected lemma compose [preorder α] [preorder β] [preorder γ] {l1 : α → β} {u1 : β → α} {l2 : β → γ} {u2 : γ → β} (gc1 : galois_connection l1 u1) (gc2 : galois_connection l2 u2) : galois_connection (l2 ∘ l1) (u1 ∘ u2) := by intros a b; rw [gc2, gc1] protected lemma dfun {ι : Type u} {α : ι → Type v} {β : ι → Type w} [∀ i, preorder (α i)] [∀ i, preorder (β i)] (l : Πi, α i → β i) (u : Πi, β i → α i) (gc : ∀ i, galois_connection (l i) (u i)) : galois_connection (λ (a : Π i, α i) i, l i (a i)) (λ b i, u i (b i)) := λ a b, forall_congr $ λ i, gc i (a i) (b i) end constructions lemma l_comm_of_u_comm {X : Type*} [preorder X] {Y : Type*} [partial_order Y] {Z : Type*} [preorder Z] {W : Type*} [partial_order W] {lYX : X → Y} {uXY : Y → X} (hXY : galois_connection lYX uXY) {lWZ : Z → W} {uZW : W → Z} (hZW : galois_connection lWZ uZW) {lWY : Y → W} {uYW : W → Y} (hWY : galois_connection lWY uYW) {lZX : X → Z} {uXZ : Z → X} (hXZ : galois_connection lZX uXZ) (h : ∀ w, uXZ (uZW w) = uXY (uYW w)) {x : X} : lWZ (lZX x) = lWY (lYX x) := (hXZ.compose hZW).l_unique (hXY.compose hWY) h lemma u_comm_of_l_comm {X : Type*} [partial_order X] {Y : Type*} [preorder Y] {Z : Type*} [partial_order Z] {W : Type*} [preorder W] {lYX : X → Y} {uXY : Y → X} (hXY : galois_connection lYX uXY) {lWZ : Z → W} {uZW : W → Z} (hZW : galois_connection lWZ uZW) {lWY : Y → W} {uYW : W → Y} (hWY : galois_connection lWY uYW) {lZX : X → Z} {uXZ : Z → X} (hXZ : galois_connection lZX uXZ) (h : ∀ x, lWZ (lZX x) = lWY (lYX x)) {w : W} : uXZ (uZW w) = uXY (uYW w) := (hXZ.compose hZW).u_unique (hXY.compose hWY) h lemma l_comm_iff_u_comm {X : Type*} [partial_order X] {Y : Type*} [partial_order Y] {Z : Type*} [partial_order Z] {W : Type*} [partial_order W] {lYX : X → Y} {uXY : Y → X} (hXY : galois_connection lYX uXY) {lWZ : Z → W} {uZW : W → Z} (hZW : galois_connection lWZ uZW) {lWY : Y → W} {uYW : W → Y} (hWY : galois_connection lWY uYW) {lZX : X → Z} {uXZ : Z → X} (hXZ : galois_connection lZX uXZ) : (∀ w : W, uXZ (uZW w) = uXY (uYW w)) ↔ ∀ x : X, lWZ (lZX x) = lWY (lYX x) := ⟨hXY.l_comm_of_u_comm hZW hWY hXZ, hXY.u_comm_of_l_comm hZW hWY hXZ⟩ end galois_connection namespace order_iso variables [preorder α] [preorder β] @[simp] lemma bdd_above_image (e : α ≃o β) {s : set α} : bdd_above (e '' s) ↔ bdd_above s := e.to_galois_connection.bdd_above_l_image @[simp] lemma bdd_below_image (e : α ≃o β) {s : set α} : bdd_below (e '' s) ↔ bdd_below s := e.dual.bdd_above_image @[simp] lemma bdd_above_preimage (e : α ≃o β) {s : set β} : bdd_above (e ⁻¹' s) ↔ bdd_above s := by rw [← e.bdd_above_image, e.image_preimage] @[simp] lemma bdd_below_preimage (e : α ≃o β) {s : set β} : bdd_below (e ⁻¹' s) ↔ bdd_below s := by rw [← e.bdd_below_image, e.image_preimage] end order_iso namespace nat lemma galois_connection_mul_div {k : ℕ} (h : 0 < k) : galois_connection (λ n, n * k) (λ n, n / k) := λ x y, (le_div_iff_mul_le x y h).symm end nat /-- A Galois insertion is a Galois connection where `l ∘ u = id`. It also contains a constructive choice function, to give better definitional equalities when lifting order structures. Dual to `galois_coinsertion` -/ @[nolint has_inhabited_instance] structure galois_insertion {α β : Type*} [preorder α] [preorder β] (l : α → β) (u : β → α) := (choice : Πx : α, u (l x) ≤ x → β) (gc : galois_connection l u) (le_l_u : ∀ x, x ≤ l (u x)) (choice_eq : ∀ a h, choice a h = l a) /-- A constructor for a Galois insertion with the trivial `choice` function. -/ def galois_insertion.monotone_intro {α β : Type*} [preorder α] [preorder β] {l : α → β} {u : β → α} (hu : monotone u) (hl : monotone l) (hul : ∀ a, a ≤ u (l a)) (hlu : ∀ b, l (u b) = b) : galois_insertion l u := { choice := λ x _, l x, gc := galois_connection.monotone_intro hu hl hul (λ b, le_of_eq (hlu b)), le_l_u := λ b, le_of_eq $ (hlu b).symm, choice_eq := λ _ _, rfl } /-- Makes a Galois insertion from an order-preserving bijection. -/ protected def order_iso.to_galois_insertion [preorder α] [preorder β] (oi : α ≃o β) : @galois_insertion α β _ _ (oi) (oi.symm) := { choice := λ b h, oi b, gc := oi.to_galois_connection, le_l_u := λ g, le_of_eq (oi.right_inv g).symm, choice_eq := λ b h, rfl } /-- Make a `galois_insertion l u` from a `galois_connection l u` such that `∀ b, b ≤ l (u b)` -/ def galois_connection.to_galois_insertion {α β : Type*} [preorder α] [preorder β] {l : α → β} {u : β → α} (gc : galois_connection l u) (h : ∀ b, b ≤ l (u b)) : galois_insertion l u := { choice := λ x _, l x, gc := gc, le_l_u := h, choice_eq := λ _ _, rfl } /-- Lift the bottom along a Galois connection -/ def galois_connection.lift_order_bot {α β : Type*} [preorder α] [order_bot α] [partial_order β] {l : α → β} {u : β → α} (gc : galois_connection l u) : order_bot β := { bot := l ⊥, bot_le := λ b, gc.l_le $ bot_le } namespace galois_insertion variables {l : α → β} {u : β → α} lemma l_u_eq [preorder α] [partial_order β] (gi : galois_insertion l u) (b : β) : l (u b) = b := (gi.gc.l_u_le _).antisymm (gi.le_l_u _) lemma left_inverse_l_u [preorder α] [partial_order β] (gi : galois_insertion l u) : left_inverse l u := gi.l_u_eq lemma l_surjective [preorder α] [partial_order β] (gi : galois_insertion l u) : surjective l := gi.left_inverse_l_u.surjective lemma u_injective [preorder α] [partial_order β] (gi : galois_insertion l u) : injective u := gi.left_inverse_l_u.injective lemma l_sup_u [semilattice_sup α] [semilattice_sup β] (gi : galois_insertion l u) (a b : β) : l (u a ⊔ u b) = a ⊔ b := calc l (u a ⊔ u b) = l (u a) ⊔ l (u b) : gi.gc.l_sup ... = a ⊔ b : by simp only [gi.l_u_eq] lemma l_supr_u [complete_lattice α] [complete_lattice β] (gi : galois_insertion l u) {ι : Sort x} (f : ι → β) : l (⨆ i, u (f i)) = ⨆ i, (f i) := calc l (⨆ (i : ι), u (f i)) = ⨆ (i : ι), l (u (f i)) : gi.gc.l_supr ... = ⨆ (i : ι), f i : congr_arg _ $ funext $ λ i, gi.l_u_eq (f i) lemma l_bsupr_u [complete_lattice α] [complete_lattice β] (gi : galois_insertion l u) {ι : Sort x} {p : ι → Prop} (f : Π i (hi : p i), β) : l (⨆ i hi, u (f i hi)) = ⨆ i hi, f i hi := by simp only [supr_subtype', gi.l_supr_u] lemma l_Sup_u_image [complete_lattice α] [complete_lattice β] (gi : galois_insertion l u) (s : set β) : l (Sup (u '' s)) = Sup s := by rw [Sup_image, gi.l_bsupr_u, Sup_eq_supr] lemma l_inf_u [semilattice_inf α] [semilattice_inf β] (gi : galois_insertion l u) (a b : β) : l (u a ⊓ u b) = a ⊓ b := calc l (u a ⊓ u b) = l (u (a ⊓ b)) : congr_arg l gi.gc.u_inf.symm ... = a ⊓ b : by simp only [gi.l_u_eq] lemma l_infi_u [complete_lattice α] [complete_lattice β] (gi : galois_insertion l u) {ι : Sort x} (f : ι → β) : l (⨅ i, u (f i)) = ⨅ i, f i := calc l (⨅ (i : ι), u (f i)) = l (u (⨅ (i : ι), (f i))) : congr_arg l gi.gc.u_infi.symm ... = ⨅ (i : ι), f i : gi.l_u_eq _ lemma l_binfi_u [complete_lattice α] [complete_lattice β] (gi : galois_insertion l u) {ι : Sort x} {p : ι → Prop} (f : Π i (hi : p i), β) : l (⨅ i hi, u (f i hi)) = ⨅ i hi, f i hi := by simp only [infi_subtype', gi.l_infi_u] lemma l_Inf_u_image [complete_lattice α] [complete_lattice β] (gi : galois_insertion l u) (s : set β) : l (Inf (u '' s)) = Inf s := by rw [Inf_image, gi.l_binfi_u, Inf_eq_infi] lemma l_infi_of_ul_eq_self [complete_lattice α] [complete_lattice β] (gi : galois_insertion l u) {ι : Sort x} (f : ι → α) (hf : ∀ i, u (l (f i)) = f i) : l (⨅ i, f i) = ⨅ i, l (f i) := calc l (⨅ i, (f i)) = l ⨅ (i : ι), (u (l (f i))) : by simp [hf] ... = ⨅ i, l (f i) : gi.l_infi_u _ lemma l_binfi_of_ul_eq_self [complete_lattice α] [complete_lattice β] (gi : galois_insertion l u) {ι : Sort x} {p : ι → Prop} (f : Π i (hi : p i), α) (hf : ∀ i hi, u (l (f i hi)) = f i hi) : l (⨅ i hi, f i hi) = ⨅ i hi, l (f i hi) := by { rw [infi_subtype', infi_subtype'], exact gi.l_infi_of_ul_eq_self _ (λ _, hf _ _) } lemma u_le_u_iff [preorder α] [preorder β] (gi : galois_insertion l u) {a b} : u a ≤ u b ↔ a ≤ b := ⟨λ h, (gi.le_l_u _).trans (gi.gc.l_le h), λ h, gi.gc.monotone_u h⟩ lemma strict_mono_u [preorder α] [preorder β] (gi : galois_insertion l u) : strict_mono u := strict_mono_of_le_iff_le $ λ _ _, gi.u_le_u_iff.symm lemma is_lub_of_u_image [preorder α] [preorder β] (gi : galois_insertion l u) {s : set β} {a : α} (hs : is_lub (u '' s) a) : is_lub s (l a) := ⟨λ x hx, (gi.le_l_u x).trans $ gi.gc.monotone_l $ hs.1 $ mem_image_of_mem _ hx, λ x hx, gi.gc.l_le $ hs.2 $ gi.gc.monotone_u.mem_upper_bounds_image hx⟩ lemma is_glb_of_u_image [preorder α] [preorder β] (gi : galois_insertion l u) {s : set β} {a : α} (hs : is_glb (u '' s) a) : is_glb s (l a) := ⟨λ x hx, gi.gc.l_le $ hs.1 $ mem_image_of_mem _ hx, λ x hx, (gi.le_l_u x).trans $ gi.gc.monotone_l $ hs.2 $ gi.gc.monotone_u.mem_lower_bounds_image hx⟩ section lift variables [partial_order β] /-- Lift the suprema along a Galois insertion -/ def lift_semilattice_sup [semilattice_sup α] (gi : galois_insertion l u) : semilattice_sup β := { sup := λ a b, l (u a ⊔ u b), le_sup_left := λ a b, (gi.le_l_u a).trans $ gi.gc.monotone_l $ le_sup_left, le_sup_right := λ a b, (gi.le_l_u b).trans $ gi.gc.monotone_l $ le_sup_right, sup_le := λ a b c hac hbc, gi.gc.l_le $ sup_le (gi.gc.monotone_u hac) (gi.gc.monotone_u hbc), .. ‹partial_order β› } /-- Lift the infima along a Galois insertion -/ def lift_semilattice_inf [semilattice_inf α] (gi : galois_insertion l u) : semilattice_inf β := { inf := λ a b, gi.choice (u a ⊓ u b) $ (le_inf (gi.gc.monotone_u $ gi.gc.l_le $ inf_le_left) (gi.gc.monotone_u $ gi.gc.l_le $ inf_le_right)), inf_le_left := by simp only [gi.choice_eq]; exact λ a b, gi.gc.l_le inf_le_left, inf_le_right := by simp only [gi.choice_eq]; exact λ a b, gi.gc.l_le inf_le_right, le_inf := by simp only [gi.choice_eq]; exact λ a b c hac hbc, (gi.le_l_u a).trans $ gi.gc.monotone_l $ le_inf (gi.gc.monotone_u hac) (gi.gc.monotone_u hbc), .. ‹partial_order β› } /-- Lift the suprema and infima along a Galois insertion -/ def lift_lattice [lattice α] (gi : galois_insertion l u) : lattice β := { .. gi.lift_semilattice_sup, .. gi.lift_semilattice_inf } /-- Lift the top along a Galois insertion -/ def lift_order_top [preorder α] [order_top α] (gi : galois_insertion l u) : order_top β := { top := gi.choice ⊤ $ le_top, le_top := by simp only [gi.choice_eq]; exact λ b, (gi.le_l_u b).trans (gi.gc.monotone_l le_top) } /-- Lift the top, bottom, suprema, and infima along a Galois insertion -/ def lift_bounded_order [preorder α] [bounded_order α] (gi : galois_insertion l u) : bounded_order β := { .. gi.lift_order_top, .. gi.gc.lift_order_bot } /-- Lift all suprema and infima along a Galois insertion -/ def lift_complete_lattice [complete_lattice α] (gi : galois_insertion l u) : complete_lattice β := { Sup := λ s, l (Sup (u '' s)), Sup_le := λ s, (gi.is_lub_of_u_image (is_lub_Sup _)).2, le_Sup := λ s, (gi.is_lub_of_u_image (is_lub_Sup _)).1, Inf := λ s, gi.choice (Inf (u '' s)) $ gi.gc.monotone_u.le_is_glb_image (gi.is_glb_of_u_image $ is_glb_Inf _) (is_glb_Inf _), Inf_le := λ s, by { rw gi.choice_eq, exact (gi.is_glb_of_u_image (is_glb_Inf _)).1 }, le_Inf := λ s, by { rw gi.choice_eq, exact (gi.is_glb_of_u_image (is_glb_Inf _)).2 }, .. gi.lift_bounded_order, .. gi.lift_lattice } end lift end galois_insertion /-- A Galois coinsertion is a Galois connection where `u ∘ l = id`. It also contains a constructive choice function, to give better definitional equalities when lifting order structures. Dual to `galois_insertion` -/ @[nolint has_inhabited_instance] structure galois_coinsertion {α β : Type*} [preorder α] [preorder β] (l : α → β) (u : β → α) := (choice : Πx : β, x ≤ l (u x) → α) (gc : galois_connection l u) (u_l_le : ∀ x, u (l x) ≤ x) (choice_eq : ∀ a h, choice a h = u a) /-- Make a `galois_insertion u l` in the `order_dual`, from a `galois_coinsertion l u` -/ def galois_coinsertion.dual {α β : Type*} [preorder α] [preorder β] {l : α → β} {u : β → α} : galois_coinsertion l u → @galois_insertion (order_dual β) (order_dual α) _ _ u l := λ x, ⟨x.1, x.2.dual, x.3, x.4⟩ /-- Make a `galois_coinsertion u l` in the `order_dual`, from a `galois_insertion l u` -/ def galois_insertion.dual {α β : Type*} [preorder α] [preorder β] {l : α → β} {u : β → α} : galois_insertion l u → @galois_coinsertion (order_dual β) (order_dual α) _ _ u l := λ x, ⟨x.1, x.2.dual, x.3, x.4⟩ /-- Make a `galois_coinsertion l u` from a `galois_insertion l u` in the `order_dual` -/ def galois_coinsertion.of_dual {α β : Type*} [preorder α] [preorder β] {l : α → β} {u : β → α} : @galois_insertion (order_dual β) (order_dual α) _ _ u l → galois_coinsertion l u := λ x, ⟨x.1, x.2.dual, x.3, x.4⟩ /-- Make a `galois_insertion l u` from a `galois_coinsertion l u` in the `order_dual` -/ def galois_insertion.of_dual {α β : Type*} [preorder α] [preorder β] {l : α → β} {u : β → α} : @galois_coinsertion (order_dual β) (order_dual α) _ _ u l → galois_insertion l u := λ x, ⟨x.1, x.2.dual, x.3, x.4⟩ /-- Makes a Galois coinsertion from an order-preserving bijection. -/ protected def rel_iso.to_galois_coinsertion [preorder α] [preorder β] (oi : α ≃o β) : @galois_coinsertion α β _ _ (oi) (oi.symm) := { choice := λ b h, oi.symm b, gc := oi.to_galois_connection, u_l_le := λ g, le_of_eq (oi.left_inv g), choice_eq := λ b h, rfl } /-- A constructor for a Galois coinsertion with the trivial `choice` function. -/ def galois_coinsertion.monotone_intro [preorder α] [preorder β] {l : α → β} {u : β → α} (hu : monotone u) (hl : monotone l) (hlu : ∀ b, l (u b) ≤ b) (hul : ∀ a, u (l a) = a) : galois_coinsertion l u := galois_coinsertion.of_dual (galois_insertion.monotone_intro hl.dual hu.dual hlu hul) /-- Make a `galois_coinsertion l u` from a `galois_connection l u` such that `∀ b, b ≤ l (u b)` -/ def galois_connection.to_galois_coinsertion {α β : Type*} [preorder α] [preorder β] {l : α → β} {u : β → α} (gc : galois_connection l u) (h : ∀ a, u (l a) ≤ a) : galois_coinsertion l u := { choice := λ x _, u x, gc := gc, u_l_le := h, choice_eq := λ _ _, rfl } /-- Lift the top along a Galois connection -/ def galois_connection.lift_order_top {α β : Type*} [partial_order α] [preorder β] [order_top β] {l : α → β} {u : β → α} (gc : galois_connection l u) : order_top α := { top := u ⊤, le_top := λ b, gc.le_u $ le_top } namespace galois_coinsertion variables {l : α → β} {u : β → α} lemma u_l_eq [partial_order α] [preorder β] (gi : galois_coinsertion l u) (a : α) : u (l a) = a := gi.dual.l_u_eq a lemma u_l_left_inverse [partial_order α] [preorder β] (gi : galois_coinsertion l u) : left_inverse u l := gi.u_l_eq lemma u_surjective [partial_order α] [preorder β] (gi : galois_coinsertion l u) : surjective u := gi.dual.l_surjective lemma l_injective [partial_order α] [preorder β] (gi : galois_coinsertion l u) : injective l := gi.dual.u_injective lemma u_inf_l [semilattice_inf α] [semilattice_inf β] (gi : galois_coinsertion l u) (a b : α) : u (l a ⊓ l b) = a ⊓ b := gi.dual.l_sup_u a b lemma u_infi_l [complete_lattice α] [complete_lattice β] (gi : galois_coinsertion l u) {ι : Sort x} (f : ι → α) : u (⨅ i, l (f i)) = ⨅ i, (f i) := gi.dual.l_supr_u _ lemma u_Inf_l_image [complete_lattice α] [complete_lattice β] (gi : galois_coinsertion l u) (s : set α) : u (Inf (l '' s)) = Inf s := gi.dual.l_Sup_u_image _ lemma u_sup_l [semilattice_sup α] [semilattice_sup β] (gi : galois_coinsertion l u) (a b : α) : u (l a ⊔ l b) = a ⊔ b := gi.dual.l_inf_u _ _ lemma u_supr_l [complete_lattice α] [complete_lattice β] (gi : galois_coinsertion l u) {ι : Sort x} (f : ι → α) : u (⨆ i, l (f i)) = ⨆ i, (f i) := gi.dual.l_infi_u _ lemma u_bsupr_l [complete_lattice α] [complete_lattice β] (gi : galois_coinsertion l u) {ι : Sort x} {p : ι → Prop} (f : Π i (hi : p i), α) : u (⨆ i hi, l (f i hi)) = ⨆ i hi, f i hi := gi.dual.l_binfi_u _ lemma u_Sup_l_image [complete_lattice α] [complete_lattice β] (gi : galois_coinsertion l u) (s : set α) : u (Sup (l '' s)) = Sup s := gi.dual.l_Inf_u_image _ lemma u_supr_of_lu_eq_self [complete_lattice α] [complete_lattice β] (gi : galois_coinsertion l u) {ι : Sort x} (f : ι → β) (hf : ∀ i, l (u (f i)) = f i) : u (⨆ i, (f i)) = ⨆ i, u (f i) := gi.dual.l_infi_of_ul_eq_self _ hf lemma u_bsupr_of_lu_eq_self [complete_lattice α] [complete_lattice β] (gi : galois_coinsertion l u) {ι : Sort x} {p : ι → Prop} (f : Π i (hi : p i), β) (hf : ∀ i hi, l (u (f i hi)) = f i hi) : u (⨆ i hi, f i hi) = ⨆ i hi, u (f i hi) := gi.dual.l_binfi_of_ul_eq_self _ hf lemma l_le_l_iff [preorder α] [preorder β] (gi : galois_coinsertion l u) {a b} : l a ≤ l b ↔ a ≤ b := gi.dual.u_le_u_iff lemma strict_mono_l [partial_order α] [preorder β] (gi : galois_coinsertion l u) : strict_mono l := λ a b h, gi.dual.strict_mono_u h lemma is_glb_of_l_image [preorder α] [preorder β] (gi : galois_coinsertion l u) {s : set α} {a : β} (hs : is_glb (l '' s) a) : is_glb s (u a) := gi.dual.is_lub_of_u_image hs lemma is_lub_of_l_image [preorder α] [preorder β] (gi : galois_coinsertion l u) {s : set α} {a : β} (hs : is_lub (l '' s) a) : is_lub s (u a) := gi.dual.is_glb_of_u_image hs section lift variables [partial_order α] /-- Lift the infima along a Galois coinsertion -/ def lift_semilattice_inf [semilattice_inf β] (gi : galois_coinsertion l u) : semilattice_inf α := { inf := λ a b, u (l a ⊓ l b), .. ‹partial_order α›, .. @order_dual.semilattice_inf _ gi.dual.lift_semilattice_sup } /-- Lift the suprema along a Galois coinsertion -/ def lift_semilattice_sup [semilattice_sup β] (gi : galois_coinsertion l u) : semilattice_sup α := { sup := λ a b, gi.choice (l a ⊔ l b) $ (sup_le (gi.gc.monotone_l $ gi.gc.le_u $ le_sup_left) (gi.gc.monotone_l $ gi.gc.le_u $ le_sup_right)), .. ‹partial_order α›, .. @order_dual.semilattice_sup _ gi.dual.lift_semilattice_inf } /-- Lift the suprema and infima along a Galois coinsertion -/ def lift_lattice [lattice β] (gi : galois_coinsertion l u) : lattice α := { .. gi.lift_semilattice_sup, .. gi.lift_semilattice_inf } /-- Lift the bot along a Galois coinsertion -/ def lift_order_bot [preorder β] [order_bot β] (gi : galois_coinsertion l u) : order_bot α := { bot := gi.choice ⊥ $ bot_le, .. @order_dual.order_bot _ _ gi.dual.lift_order_top } /-- Lift the top, bottom, suprema, and infima along a Galois coinsertion -/ def lift_bounded_order [preorder β] [bounded_order β] (gi : galois_coinsertion l u) : bounded_order α := { .. gi.lift_order_bot, .. gi.gc.lift_order_top } /-- Lift all suprema and infima along a Galois coinsertion -/ def lift_complete_lattice [complete_lattice β] (gi : galois_coinsertion l u) : complete_lattice α := { Inf := λ s, u (Inf (l '' s)), Sup := λ s, gi.choice (Sup (l '' s)) _, .. @order_dual.complete_lattice _ gi.dual.lift_complete_lattice } end lift end galois_coinsertion /-- If `α` is a partial order with bottom element (e.g., `ℕ`, `ℝ≥0`), then `λ o : with_bot α, o.get_or_else ⊥` and coercion form a Galois insertion. -/ def with_bot.gi_get_or_else_bot [preorder α] [order_bot α] : galois_insertion (λ o : with_bot α, o.get_or_else ⊥) coe := { gc := λ a b, with_bot.get_or_else_bot_le_iff, le_l_u := λ a, le_rfl, choice := λ o ho, _, choice_eq := λ _ _, rfl }
50a6a41e2e0c6074de28c35312a191cfcc1d3f3c
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/category_theory/limits/shapes/finite_limits.lean
6519a88c978ff052eee062529fa92ba3acc554bf
[ "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
7,361
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import data.fintype.basic import category_theory.limits.shapes.products import category_theory.limits.shapes.equalizers import category_theory.limits.shapes.pullbacks universes v u namespace category_theory instance discrete_fintype {α : Type*} [fintype α] : fintype (discrete α) := by { dsimp [discrete], apply_instance } instance discrete_hom_fintype {α : Type*} [decidable_eq α] (X Y : discrete α) : fintype (X ⟶ Y) := by { apply ulift.fintype } /-- A category with a `fintype` of objects, and a `fintype` for each morphism space. -/ class fin_category (J : Type v) [small_category J] := (decidable_eq_obj : decidable_eq J . tactic.apply_instance) (fintype_obj : fintype J . tactic.apply_instance) (decidable_eq_hom : Π (j j' : J), decidable_eq (j ⟶ j') . tactic.apply_instance) (fintype_hom : Π (j j' : J), fintype (j ⟶ j') . tactic.apply_instance) attribute [instance] fin_category.decidable_eq_obj fin_category.fintype_obj fin_category.decidable_eq_hom fin_category.fintype_hom -- We need a `decidable_eq` instance here to construct `fintype` on the morphism spaces. instance fin_category_discrete_of_decidable_fintype (J : Type v) [decidable_eq J] [fintype J] : fin_category (discrete J) := { } end category_theory open category_theory namespace category_theory.limits variables (C : Type u) [category.{v} C] def has_finite_limits : Type (max (v+1) u) := Π (J : Type v) [𝒥 : small_category J] [@fin_category J 𝒥], @has_limits_of_shape J 𝒥 C _ attribute [class] has_finite_limits @[priority 100] instance has_limits_of_shape_of_has_finite_limits (J : Type v) [small_category J] [fin_category J] [has_finite_limits C] : has_limits_of_shape J C := ‹has_finite_limits C› J /-- If `C` has all limits, it has finite limits. -/ def has_finite_limits_of_has_limits [has_limits C] : has_finite_limits C := λ J 𝒥₁ 𝒥₂, infer_instance def has_finite_colimits : Type (max (v+1) u) := Π (J : Type v) [𝒥 : small_category J] [@fin_category J 𝒥], @has_colimits_of_shape J 𝒥 C _ attribute [class] has_finite_colimits @[priority 100] instance has_colimits_of_shape_of_has_finite_colimits (J : Type v) [small_category J] [fin_category J] [has_finite_colimits C] : has_colimits_of_shape J C := ‹has_finite_colimits C› J /-- If `C` has all colimits, it has finite colimits. -/ def has_finite_colimits_of_has_colimits [has_colimits C] : has_finite_colimits C := λ J 𝒥₁ 𝒥₂, infer_instance section open walking_parallel_pair walking_parallel_pair_hom instance fintype_walking_parallel_pair : fintype walking_parallel_pair := { elems := [walking_parallel_pair.zero, walking_parallel_pair.one].to_finset, complete := λ x, by { cases x; simp } } local attribute [tidy] tactic.case_bash instance (j j' : walking_parallel_pair) : fintype (walking_parallel_pair_hom j j') := { elems := walking_parallel_pair.rec_on j (walking_parallel_pair.rec_on j' [walking_parallel_pair_hom.id zero].to_finset [left, right].to_finset) (walking_parallel_pair.rec_on j' ∅ [walking_parallel_pair_hom.id one].to_finset), complete := by tidy } end instance : fin_category walking_parallel_pair := { } /-- Equalizers are finite limits, so if `C` has all finite limits, it also has all equalizers -/ example [has_finite_limits C] : has_equalizers C := infer_instance /-- Coequalizers are finite colimits, of if `C` has all finite colimits, it also has all coequalizers -/ example [has_finite_colimits C] : has_coequalizers C := infer_instance variables {J : Type v} local attribute [tidy] tactic.case_bash namespace wide_pullback_shape instance fintype_obj [fintype J] : fintype (wide_pullback_shape J) := by { rw wide_pullback_shape, apply_instance } instance fintype_hom [decidable_eq J] (j j' : wide_pullback_shape J) : fintype (j ⟶ j') := { elems := begin cases j', { cases j, { exact {hom.id none} }, { exact {hom.term j} } }, { by_cases some j' = j, { rw h, exact {hom.id j} }, { exact ∅ } } end, complete := by tidy } end wide_pullback_shape namespace wide_pushout_shape instance fintype_obj [fintype J] : fintype (wide_pushout_shape J) := by { rw wide_pushout_shape, apply_instance } instance fintype_hom [decidable_eq J] (j j' : wide_pushout_shape J) : fintype (j ⟶ j') := { elems := begin cases j, { cases j', { exact {hom.id none} }, { exact {hom.init j'} } }, { by_cases some j = j', { rw h, exact {hom.id j'} }, { exact ∅ } } end, complete := by tidy } end wide_pushout_shape instance fin_category_wide_pullback [decidable_eq J] [fintype J] : fin_category (wide_pullback_shape J) := { fintype_hom := wide_pullback_shape.fintype_hom } instance fin_category_wide_pushout [decidable_eq J] [fintype J] : fin_category (wide_pushout_shape J) := { fintype_hom := wide_pushout_shape.fintype_hom } /-- `has_finite_wide_pullbacks` represents a choice of wide pullback for every finite collection of morphisms -/ -- We can't use the same design as for `has_wide_pullbacks`, -- because of https://github.com/leanprover-community/lean/issues/429 def has_finite_wide_pullbacks : Type (max (v+1) u) := Π (J : Type v) [decidable_eq J] [fintype J], has_limits_of_shape (wide_pullback_shape J) C attribute [class] has_finite_wide_pullbacks instance has_limits_of_shape_wide_pullback_shape (J : Type v) [decidable_eq J] [fintype J] [has_finite_wide_pullbacks C] : has_limits_of_shape (wide_pullback_shape J) C := ‹has_finite_wide_pullbacks C› J /-- `has_finite_wide_pushouts` represents a choice of wide pushout for every finite collection of morphisms -/ def has_finite_wide_pushouts : Type (max (v+1) u) := Π (J : Type v) [decidable_eq J] [fintype J], has_colimits_of_shape (wide_pushout_shape J) C attribute [class] has_finite_wide_pushouts instance has_colimits_of_shape_wide_pushout_shape (J : Type v) [decidable_eq J] [fintype J] [has_finite_wide_pushouts C] : has_colimits_of_shape (wide_pushout_shape J) C := ‹has_finite_wide_pushouts C› J /-- Finite wide pullbacks are finite limits, so if `C` has all finite limits, it also has finite wide pullbacks -/ def has_finite_wide_pullbacks_of_has_finite_limits [has_finite_limits C] : has_finite_wide_pullbacks C := λ J _ _, by exactI limits.has_limits_of_shape_of_has_finite_limits _ _ /-- Finite wide pushouts are finite colimits, so if `C` has all finite colimits, it also has finite wide pushouts -/ def has_finite_wide_pushouts_of_has_finite_limits [has_finite_colimits C] : has_finite_wide_pushouts C := λ J _ _, by exactI limits.has_colimits_of_shape_of_has_finite_colimits _ _ instance fintype_walking_pair : fintype walking_pair := { elems := {walking_pair.left, walking_pair.right}, complete := λ x, by { cases x; simp } } /-- Pullbacks are finite limits, so if `C` has all finite limits, it also has all pullbacks -/ example [has_finite_wide_pullbacks C] : has_pullbacks C := infer_instance /-- Pushouts are finite colimits, so if `C` has all finite colimits, it also has all pushouts -/ example [has_finite_wide_pushouts C] : has_pushouts C := infer_instance end category_theory.limits
2b60bdc3ebdc30acdaac38bb1e8e4317130604fe
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/tactic/tauto.lean
29f6139de87508de9b112dcb4b9fbfda8464b8de
[ "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
9,793
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import logic.basic tactic.solve_by_elim tactic.hint namespace tactic open expr open tactic.interactive ( casesm constructor_matching ) /-- find all assumptions of the shape `¬ (p ∧ q)` or `¬ (p ∨ q)` and replace them using de Morgan's law. -/ meta def distrib_not : tactic unit := do hs ← local_context, hs.for_each $ λ h, all_goals $ iterate_at_most 3 $ do h ← get_local h.local_pp_name, e ← infer_type h, match e with | `(¬ _ = _) := replace h.local_pp_name ``(mt iff.to_eq %%h) | `(_ ≠ _) := replace h.local_pp_name ``(mt iff.to_eq %%h) | `(_ = _) := replace h.local_pp_name ``(eq.to_iff %%h) | `(¬ (_ ∧ _)) := replace h.local_pp_name ``(not_and_distrib'.mp %%h) <|> replace h.local_pp_name ``(not_and_distrib.mp %%h) | `(¬ (_ ∨ _)) := replace h.local_pp_name ``(not_or_distrib.mp %%h) | `(¬ ¬ _) := replace h.local_pp_name ``(of_not_not %%h) | `(¬ (_ → (_ : Prop))) := replace h.local_pp_name ``(not_imp.mp %%h) | `(¬ (_ ↔ _)) := replace h.local_pp_name ``(not_iff.mp %%h) | `(_ ↔ _) := replace h.local_pp_name ``(iff_iff_and_or_not_and_not.mp %%h) <|> replace h.local_pp_name ``(iff_iff_and_or_not_and_not.mp (%%h).symm) <|> () <$ tactic.cases h | `(_ → _) := replace h.local_pp_name ``(not_or_of_imp %%h) | _ := failed end meta def tauto_state := ref $ expr_map (option (expr × expr)) meta def modify_ref {α : Type} (r : ref α) (f : α → α) := read_ref r >>= write_ref r ∘ f meta def add_refl (r : tauto_state) (e : expr) : tactic (expr × expr) := do m ← read_ref r, p ← mk_mapp `rfl [none,e], write_ref r $ m.insert e none, return (e,p) meta def add_symm_proof (r : tauto_state) (e : expr) : tactic (expr × expr) := do env ← get_env, let rel := e.get_app_fn.const_name, some symm ← pure $ environment.symm_for env rel | add_refl r e, (do e' ← mk_meta_var `(Prop), iff_t ← to_expr ``(%%e = %%e'), (_,p) ← solve_aux iff_t (applyc `iff.to_eq ; () <$ split ; applyc symm), e' ← instantiate_mvars e', m ← read_ref r, write_ref r $ (m.insert e (e',p)).insert e' none, return (e',p) ) <|> add_refl r e meta def add_edge (r : tauto_state) (x y p : expr) : tactic unit := modify_ref r $ λ m, m.insert x (y,p) meta def root (r : tauto_state) : expr → tactic (expr × expr) | e := do m ← read_ref r, let record_e : tactic (expr × expr) := match e with | v@(expr.mvar _ _ _) := (do (e,p) ← get_assignment v >>= root, add_edge r v e p, return (e,p)) <|> add_refl r e | _ := add_refl r e end, some e' ← pure $ m.find e | record_e, match e' with | (some (e',p')) := do (e'',p'') ← root e', p'' ← mk_app `eq.trans [p',p''], add_edge r e e'' p'', pure (e'',p'') | none := prod.mk e <$> mk_mapp `rfl [none,some e] end meta def symm_eq (r : tauto_state) : expr → expr → tactic expr | a b := do m ← read_ref r, (a',pa) ← root r a, (b',pb) ← root r b, (unify a' b' >> add_refl r a' *> mk_mapp `rfl [none,a]) <|> do p ← match (a', b') with | (`(¬ %%a₀), `(¬ %%b₀)) := do p ← symm_eq a₀ b₀, p' ← mk_app `congr_arg [`(not),p], add_edge r a' b' p', return p' | (`(%%a₀ ∧ %%a₁), `(%%b₀ ∧ %%b₁)) := do p₀ ← symm_eq a₀ b₀, p₁ ← symm_eq a₁ b₁, p' ← to_expr ``(congr (congr_arg and %%p₀) %%p₁), add_edge r a' b' p', return p' | (`(%%a₀ ∨ %%a₁), `(%%b₀ ∨ %%b₁)) := do p₀ ← symm_eq a₀ b₀, p₁ ← symm_eq a₁ b₁, p' ← to_expr ``(congr (congr_arg or %%p₀) %%p₁), add_edge r a' b' p', return p' | (`(%%a₀ ↔ %%a₁), `(%%b₀ ↔ %%b₁)) := (do p₀ ← symm_eq a₀ b₀, p₁ ← symm_eq a₁ b₁, p' ← to_expr ``(congr (congr_arg iff %%p₀) %%p₁), add_edge r a' b' p', return p') <|> do p₀ ← symm_eq a₀ b₁, p₁ ← symm_eq a₁ b₀, p' ← to_expr ``(eq.trans (congr (congr_arg iff %%p₀) %%p₁) (iff.to_eq iff.comm ) ), add_edge r a' b' p', return p' | (`(%%a₀ → %%a₁), `(%%b₀ → %%b₁)) := if ¬ a₁.has_var ∧ ¬ b₁.has_var then do p₀ ← symm_eq a₀ b₀, p₁ ← symm_eq a₁ b₁, p' ← mk_app `congr_arg [`(implies),p₀,p₁], add_edge r a' b' p', return p' else unify a' b' >> add_refl r a' *> mk_mapp `rfl [none,a] | (_, _) := (do guard $ a'.get_app_fn.is_constant ∧ a'.get_app_fn.const_name = b'.get_app_fn.const_name, (a'',pa') ← add_symm_proof r a', guard $ a'' =ₐ b', pure pa' ) end, p' ← mk_eq_trans pa p, add_edge r a' b' p', mk_eq_symm pb >>= mk_eq_trans p' meta def find_eq_type (r : tauto_state) : expr → list expr → tactic (expr × expr) | e [] := failed | e (H :: Hs) := do t ← infer_type H, t' ← infer_type e, (prod.mk H <$> symm_eq r e t) <|> find_eq_type e Hs private meta def contra_p_not_p (r : tauto_state) : list expr → list expr → tactic unit | [] Hs := failed | (H1 :: Rs) Hs := do t ← (extract_opt_auto_param <$> infer_type H1) >>= whnf, (do a ← match_not t, (H2,p) ← find_eq_type r a Hs, H2 ← to_expr ``( (%%p).mpr %%H2 ), tgt ← target, pr ← mk_app `absurd [tgt, H2, H1], tactic.exact pr) <|> contra_p_not_p Rs Hs meta def contradiction_with (r : tauto_state) : tactic unit := contradiction <|> do tactic.try intro1, ctx ← local_context, contra_p_not_p r ctx ctx meta def contradiction_symm := using_new_ref (native.rb_map.mk _ _) contradiction_with meta def assumption_with (r : tauto_state) : tactic unit := do { ctx ← local_context, t ← target, (H,p) ← find_eq_type r t ctx, mk_eq_mpr p H >>= tactic.exact } <|> fail "assumption tactic failed" meta def assumption_symm := using_new_ref (native.rb_map.mk _ _) assumption_with meta def tautology (c : bool := ff) : tactic unit := do when c classical, using_new_ref (expr_map.mk _) $ λ r, do try (contradiction_with r); try (assumption_with r); repeat (do gs ← get_goals, repeat (() <$ tactic.intro1); distrib_not; casesm (some ()) [``(_ ∧ _),``(_ ∨ _),``(Exists _),``(false)]; try (contradiction_with r); try (target >>= match_or >> refine ``( or_iff_not_imp_left.mpr _)); try (target >>= match_or >> refine ``( or_iff_not_imp_right.mpr _)); repeat (() <$ tactic.intro1); constructor_matching (some ()) [``(_ ∧ _),``(_ ↔ _),``(true)]; try (assumption_with r), gs' ← get_goals, guard (gs ≠ gs') ) ; repeat (reflexivity <|> solve_by_elim <|> constructor_matching none [``(_ ∧ _),``(_ ↔ _),``(Exists _),``(true)] ) ; done open interactive lean.parser namespace interactive local postfix `?`:9001 := optional /-- `tautology` breaks down assumptions of the form `_ ∧ _`, `_ ∨ _`, `_ ↔ _` and `∃ _, _` and splits a goal of the form `_ ∧ _`, `_ ↔ _` or `∃ _, _` until it can be discharged using `reflexivity` or `solve_by_elim`. This is a finishing tactic: it either closes the goal or raises an error. The variant `tautology!` uses the law of excluded middle. --- This tactic (with shorthand `tauto`) breaks down assumptions of the form `_ ∧ _`, `_ ∨ _`, `_ ↔ _` and `∃ _, _` and splits a goal of the form `_ ∧ _`, `_ ↔ _` or `∃ _, _` until it can be discharged using `reflexivity` or `solve_by_elim`. This is a finishing tactic: it either closes the goal or raises an error. The variants `tautology!` and `tauto!` use the law of excluded middle. For instance, one can write: ```lean example (p q r : Prop) [decidable p] [decidable r] : p ∨ (q ∧ r) ↔ (p ∨ q) ∧ (r ∨ p ∨ r) := by tauto ``` and the decidability assumptions can be dropped if `tauto!` is used instead of `tauto`. -/ meta def tautology (c : parse $ (tk "!")?) := tactic.tautology c.is_some -- Now define a shorter name for the tactic `tautology`. /-- `tauto` breaks down assumptions of the form `_ ∧ _`, `_ ∨ _`, `_ ↔ _` and `∃ _, _` and splits a goal of the form `_ ∧ _`, `_ ↔ _` or `∃ _, _` until it can be discharged using `reflexivity` or `solve_by_elim`. This is a finishing tactic: it either closes the goal or raises an error. The variant `tauto!` uses the law of excluded middle. -/ meta def tauto (c : parse $ (tk "!")?) := tautology c add_hint_tactic "tauto" add_tactic_doc { name := "tautology", category := doc_category.tactic, decl_names := [`tactic.interactive.tautology, `tactic.interactive.tauto], tags := ["logic", "decision procedure"], inherit_description_from := `tactic.interactive.tautology } end interactive end tactic
5455fdbbb94496b6900fe7d9b7ff84c314aa32d5
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/library/theories/number_theory/bezout.lean
dd7cf7385e4ecd1c9eb1aafda194991d3a013b05
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,988
lean
/- Copyright (c) 2015 William Peterson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: William Peterson, Jeremy Avigad Extended gcd, Bezout's theorem, chinese remainder theorem. -/ import data.nat.div data.int .primes /- Bezout's theorem -/ section Bezout open nat int open eq.ops well_founded decidable prod open algebra private definition pair_nat.lt : ℕ × ℕ → ℕ × ℕ → Prop := measure pr₂ private definition pair_nat.lt.wf : well_founded pair_nat.lt := intro_k (measure.wf pr₂) 20 local attribute pair_nat.lt.wf [instance] local infixl `≺`:50 := pair_nat.lt private definition gcd.lt.dec (x y₁ : ℕ) : (succ y₁, x % succ y₁) ≺ (x, succ y₁) := !nat.mod_lt (succ_pos y₁) private definition egcd_rec_f (z : ℤ) : ℤ → ℤ → ℤ × ℤ := λ s t, (t, s - t * z) definition egcd.F : Π (p₁ : ℕ × ℕ), (Π p₂ : ℕ × ℕ, p₂ ≺ p₁ → ℤ × ℤ) → ℤ × ℤ | (x, y) := nat.cases_on y (λ f, (1, 0) ) (λ y₁ (f : Π p₂, p₂ ≺ (x, succ y₁) → ℤ × ℤ), let bz := f (succ y₁, x % succ y₁) !gcd.lt.dec in prod.cases_on bz (egcd_rec_f (x / succ y₁))) definition egcd (x y : ℕ) := fix egcd.F (pair x y) theorem egcd_zero (x : ℕ) : egcd x 0 = (1, 0) := well_founded.fix_eq egcd.F (x, 0) theorem egcd_succ (x y : ℕ) : egcd x (succ y) = prod.cases_on (egcd (succ y) (x % succ y)) (egcd_rec_f (x / succ y)) := well_founded.fix_eq egcd.F (x, succ y) theorem egcd_of_pos (x : ℕ) {y : ℕ} (ypos : y > 0) : let erec := egcd y (x % y), u := pr₁ erec, v := pr₂ erec in egcd x y = (v, u - v * (x / y)) := obtain (y' : nat) (yeq : y = succ y'), from exists_eq_succ_of_pos ypos, begin rewrite [yeq, egcd_succ, -prod.eta (egcd _ _)], esimp, unfold egcd_rec_f, rewrite [of_nat_div] end theorem egcd_prop (x y : ℕ) : (pr₁ (egcd x y)) * x + (pr₂ (egcd x y)) * y = gcd x y := gcd.induction x y (take m, by krewrite [egcd_zero, algebra.mul_zero, algebra.one_mul]) (take m n, assume npos : 0 < n, assume IH, begin let H := egcd_of_pos m npos, esimp at H, rewrite H, esimp, rewrite [gcd_rec, -IH], rewrite [algebra.add.comm], rewrite [-of_nat_mod], rewrite [int.mod_def], rewrite [+algebra.mul_sub_right_distrib], rewrite [+algebra.mul_sub_left_distrib, *left_distrib], rewrite [*sub_eq_add_neg, {pr₂ (egcd n (m % n)) * of_nat m + - _}algebra.add.comm], rewrite [-algebra.add.assoc ,algebra.mul.assoc] end) theorem Bezout_aux (x y : ℕ) : ∃ a b : ℤ, a * x + b * y = gcd x y := exists.intro _ (exists.intro _ (egcd_prop x y)) theorem Bezout (x y : ℤ) : ∃ a b : ℤ, a * x + b * y = gcd x y := obtain a' b' (H : a' * nat_abs x + b' * nat_abs y = gcd x y), from !Bezout_aux, begin existsi (a' * sign x), existsi (b' * sign y), rewrite [*mul.assoc, -*abs_eq_sign_mul, -*of_nat_nat_abs], apply H end end Bezout /- A sample application of Bezout's theorem, namely, an alternative proof that irreducible implies prime (dvd_or_dvd_of_prime_of_dvd_mul). -/ namespace nat open int algebra example {p x y : ℕ} (pp : prime p) (H : p ∣ x * y) : p ∣ x ∨ p ∣ y := decidable.by_cases (suppose p ∣ x, or.inl this) (suppose ¬ p ∣ x, have cpx : coprime p x, from coprime_of_prime_of_not_dvd pp this, obtain (a b : ℤ) (Hab : a * p + b * x = gcd p x), from Bezout_aux p x, assert a * p * y + b * x * y = y, by rewrite [-right_distrib, Hab, ↑coprime at cpx, cpx, int.one_mul], have p ∣ y, begin apply dvd_of_of_nat_dvd_of_nat, rewrite [-this], apply @dvd_add, {apply dvd_mul_of_dvd_left, apply dvd_mul_of_dvd_right, apply dvd.refl}, {rewrite mul.assoc, apply dvd_mul_of_dvd_right, apply of_nat_dvd_of_nat_of_dvd H} end, or.inr this) end nat
452fc68b2ed22d4863981846b99f4e5a507100c2
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/simp1.lean
29372b2590112d18562ed0ba15193bdf91f13493
[ "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
255
lean
constants (A : Type.{1}) (f : A → A → A) (x y z : A) (g : A → A) attribute [simp] lemma foo : f x y = y := sorry attribute [simp] lemma bar : g y = z := sorry open tactic example : g (f x y) = z := by simp example : g (f x (f x y)) = z := by simp
1c70f5c848188daf7ed568a918a7f1c918ee77ae
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/algebra/ordered_monoid_lemmas.lean
876cc74b5aa0a7aa1859dbc5e8335946fe54d94f
[ "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
20,638
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl, Damiano Testa -/ import algebra.group.defs import order.basic /-! This file begins the splitting of the ordering assumptions from the algebraic assumptions on the operations in the `ordered_[...]` hierarchy. The strategy is to introduce two more flexible typeclasses, covariant_class and contravariant_class. * covariant_class models the implication a ≤ b → c * a ≤ c * b (multiplication is monotone), * contravariant_class models the implication a * b < a * c → b < c. Since `co(ntra)variant_class` takes as input the operation (typically `(+)` or `(*)`) and the order relation (typically `(≤)` or `(<)`), these are the only two typeclasses that I have used. The general approach is to formulate the lemma that you are interested and prove it, with the `ordered_[...]` typeclass of your liking. After that, you convert the single typeclass, say `[ordered_cancel_monoid M]`, with three typeclasses, e.g. `[partial_order M] [left_cancel_semigroup M] [covariant_class M M (function.swap (*)) (≤)]` and have a go at seeing if the proof still works! Note that it is possible to combine several co(ntra)variant_class assumptions together. Indeed, the usual ordered typeclasses arise from assuming the pair `[covariant_class M M (*) (≤)] [contravariant_class M M (*) (<)]` on top of order/algebraic assumptions. A formal remark is that normally covariant_class uses the `(≤)`-relation, while contravariant_class uses the `(<)`-relation. This need not be the case in general, but seems to be the most common usage. In the opposite direction, the implication ```lean [semigroup α] [partial_order α] [contravariant_class α α (*) (≤)] => left_cancel_semigroup α ``` holds (note the `co*ntra*` assumption and the `(≤)`-relation). -/ -- TODO: convert `has_exists_mul_of_le`, `has_exists_add_of_le`? -- TODO: relationship with add_con -- include equivalence of `left_cancel_semigroup` with -- `semigroup partial_order contravariant_class α α (*) (≤)`? -- use ⇒, as per Eric's suggestion? section variants variables {M N : Type*} (μ : M → N → N) (r s : N → N → Prop) (m : M) {a b c : N} variables (M N) /-- `covariant` is useful to formulate succintly statements about the interactions between an action of a Type on another one and a relation on the acted-upon Type. See the `covariant_class` doc-string for its meaning. -/ def covariant : Prop := ∀ (m) {n₁ n₂}, r n₁ n₂ → r (μ m n₁) (μ m n₂) /-- `contravariant` is useful to formulate succintly statements about the interactions between an action of a Type on another one and a relation on the acted-upon Type. See the `contravariant_class` doc-string for its meaning. -/ def contravariant : Prop := ∀ (m) {n₁ n₂}, s (μ m n₁) (μ m n₂) → s n₁ n₂ /-- Given an action `μ` of a Type `M` on a Type `N` and a relation `r` on `N`, informally, the `covariant_class` says that "the action `μ` preserves the relation `r`. More precisely, the `covariant_class` is a class taking two Types `M N`, together with an "action" `μ : M → N → N` and a relation `r : N → N`. Its unique field `covc` is the assertion that for all `m ∈ M` and all elements `n₁, n₂ ∈ N`, if the relation `r` holds for the pair `(n₁, n₂)`, then, the relation `r` also holds for the pair `(μ m n₁, μ m n₂)`, obtained from `(n₁, n₂)` by "acting upon it by `m`". If `m : M` and `h : r n₁ n₂`, then `covariant_class.covc m h : r (μ m n₁) (μ m n₂)`. -/ class covariant_class := (covc : covariant M N μ r) /-- Given an action `μ` of a Type `M` on a Type `N` and a relation `r` on `N`, informally, the `contravariant_class` says that "if the result of the action `μ` on a pair satisfies the relation `r`, then the initial pair satisfied the relation `r`. More precisely, the `contravariant_class` is a class taking two Types `M N`, together with an "action" `μ : M → N → N` and a relation `r : N → N`. Its unique field `covtc` is the assertion that for all `m ∈ M` and all elements `n₁, n₂ ∈ N`, if the relation `r` holds for the pair `(μ m n₁, μ m n₂)` obtained from `(n₁, n₂)` by "acting upon it by `m`"", then, the relation `r` also holds for the pair `(n₁, n₂)`. If `m : M` and `h : r (μ m n₁) (μ m n₂)`, then `covariant_class.covc m h : r n₁ n₂`. -/ class contravariant_class := (covtc : contravariant M N μ s) end variants variables {α : Type*} {a b c d : α} section left variables [preorder α] section has_mul variables [has_mul α] @[to_additive lt_of_add_lt_add_left] lemma lt_of_mul_lt_mul_left' [contravariant_class α α (*) (<)] : a * b < a * c → b < c := contravariant_class.covtc a variable [covariant_class α α (*) (≤)] @[to_additive add_le_add_left] lemma mul_le_mul_left' (h : a ≤ b) (c) : c * a ≤ c * b := covariant_class.covc c h @[to_additive] lemma mul_lt_of_mul_lt_left (h : a * b < c) (hle : d ≤ b) : a * d < c := (mul_le_mul_left' hle a).trans_lt h @[to_additive] lemma mul_le_of_mul_le_left (h : a * b ≤ c) (hle : d ≤ b) : a * d ≤ c := (mul_le_mul_left' hle a).trans h @[to_additive] lemma lt_mul_of_lt_mul_left (h : a < b * c) (hle : c ≤ d) : a < b * d := h.trans_le (mul_le_mul_left' hle b) @[to_additive] lemma le_mul_of_le_mul_left (h : a ≤ b * c) (hle : c ≤ d) : a ≤ b * d := h.trans (mul_le_mul_left' hle b) end has_mul -- here we start using properties of one. section mul_one_class variables [mul_one_class α] [covariant_class α α (*) (≤)] @[to_additive le_add_of_nonneg_right] lemma le_mul_of_one_le_right' (h : 1 ≤ b) : a ≤ a * b := by simpa only [mul_one] using mul_le_mul_left' h a @[to_additive add_le_of_nonpos_right] lemma mul_le_of_le_one_right' (h : b ≤ 1) : a * b ≤ a := by simpa only [mul_one] using mul_le_mul_left' h a @[to_additive] lemma lt_of_mul_lt_of_one_le_left (h : a * b < c) (hle : 1 ≤ b) : a < c := (le_mul_of_one_le_right' hle).trans_lt h @[to_additive] lemma le_of_mul_le_of_one_le_left (h : a * b ≤ c) (hle : 1 ≤ b) : a ≤ c := (le_mul_of_one_le_right' hle).trans h @[to_additive] lemma lt_of_lt_mul_of_le_one_left (h : a < b * c) (hle : c ≤ 1) : a < b := h.trans_le (mul_le_of_le_one_right' hle) @[to_additive] lemma le_of_le_mul_of_le_one_left (h : a ≤ b * c) (hle : c ≤ 1) : a ≤ b := h.trans (mul_le_of_le_one_right' hle) end mul_one_class end left section right section preorder variables [preorder α] section has_mul variables [has_mul α] @[to_additive lt_of_add_lt_add_right] lemma lt_of_mul_lt_mul_right' [contravariant_class α α (function.swap (*)) (<)] (h : a * b < c * b) : a < c := contravariant_class.covtc b h variable [covariant_class α α (function.swap (*)) (≤)] @[to_additive add_le_add_right] lemma mul_le_mul_right' (h : a ≤ b) (c) : a * c ≤ b * c := covariant_class.covc c h @[to_additive] lemma mul_lt_of_mul_lt_right (h : a * b < c) (hle : d ≤ a) : d * b < c := (mul_le_mul_right' hle b).trans_lt h @[to_additive] lemma mul_le_of_mul_le_right (h : a * b ≤ c) (hle : d ≤ a) : d * b ≤ c := (mul_le_mul_right' hle b).trans h @[to_additive] lemma lt_mul_of_lt_mul_right (h : a < b * c) (hle : b ≤ d) : a < d * c := h.trans_le (mul_le_mul_right' hle c) @[to_additive] lemma le_mul_of_le_mul_right (h : a ≤ b * c) (hle : b ≤ d) : a ≤ d * c := h.trans (mul_le_mul_right' hle c) end has_mul -- here we start using properties of one. section mul_one_class variables [mul_one_class α] [covariant_class α α (function.swap (*)) (≤)] @[to_additive le_add_of_nonneg_left] lemma le_mul_of_one_le_left' (h : 1 ≤ b) : a ≤ b * a := by simpa only [one_mul] using mul_le_mul_right' h a @[to_additive add_le_of_nonpos_left] lemma mul_le_of_le_one_left' (h : b ≤ 1) : b * a ≤ a := by simpa only [one_mul] using mul_le_mul_right' h a @[to_additive] lemma lt_of_mul_lt_of_one_le_right (h : a * b < c) (hle : 1 ≤ a) : b < c := (le_mul_of_one_le_left' hle).trans_lt h @[to_additive] lemma le_of_mul_le_of_one_le_right (h : a * b ≤ c) (hle : 1 ≤ a) : b ≤ c := (le_mul_of_one_le_left' hle).trans h @[to_additive] lemma lt_of_lt_mul_of_le_one_right (h : a < b * c) (hle : b ≤ 1) : a < c := h.trans_le (mul_le_of_le_one_left' hle) @[to_additive] lemma le_of_le_mul_of_le_one_right (h : a ≤ b * c) (hle : b ≤ 1) : a ≤ c := h.trans (mul_le_of_le_one_left' hle) end mul_one_class end preorder end right section preorder variables [preorder α] section has_mul_left_right variables [has_mul α] [covariant_class α α (*) (≤)] [covariant_class α α (function.swap (*)) (≤)] @[to_additive add_le_add] lemma mul_le_mul' (h₁ : a ≤ b) (h₂ : c ≤ d) : a * c ≤ b * d := (mul_le_mul_left' h₂ _).trans (mul_le_mul_right' h₁ d) @[to_additive] lemma mul_le_mul_three {e f : α} (h₁ : a ≤ d) (h₂ : b ≤ e) (h₃ : c ≤ f) : a * b * c ≤ d * e * f := mul_le_mul' (mul_le_mul' h₁ h₂) h₃ end has_mul_left_right -- here we start using properties of one. section mul_one_class_left_right variables [mul_one_class α] section covariant variable [covariant_class α α (*) (≤)] @[to_additive add_pos_of_pos_of_nonneg] lemma one_lt_mul_of_lt_of_le' (ha : 1 < a) (hb : 1 ≤ b) : 1 < a * b := lt_of_lt_of_le ha $ le_mul_of_one_le_right' hb @[to_additive add_pos] lemma one_lt_mul' (ha : 1 < a) (hb : 1 < b) : 1 < a * b := one_lt_mul_of_lt_of_le' ha hb.le @[to_additive] lemma lt_mul_of_lt_of_one_le' (hbc : b < c) (ha : 1 ≤ a) : b < c * a := hbc.trans_le $ le_mul_of_one_le_right' ha @[to_additive] lemma lt_mul_of_lt_of_one_lt' (hbc : b < c) (ha : 1 < a) : b < c * a := lt_mul_of_lt_of_one_le' hbc ha.le end covariant section contravariant variable [covariant_class α α (function.swap (*)) (≤)] @[to_additive add_pos_of_nonneg_of_pos] lemma one_lt_mul_of_le_of_lt' (ha : 1 ≤ a) (hb : 1 < b) : 1 < a * b := lt_of_lt_of_le hb $ le_mul_of_one_le_left' ha @[to_additive] lemma lt_mul_of_one_le_of_lt' (ha : 1 ≤ a) (hbc : b < c) : b < a * c := hbc.trans_le $ le_mul_of_one_le_left' ha @[to_additive] lemma lt_mul_of_one_lt_of_lt' (ha : 1 < a) (hbc : b < c) : b < a * c := lt_mul_of_one_le_of_lt' ha.le hbc end contravariant variables [covariant_class α α (*) (≤)] [covariant_class α α (function.swap (*)) (≤)] @[to_additive] lemma le_mul_of_one_le_of_le (ha : 1 ≤ a) (hbc : b ≤ c) : b ≤ a * c := one_mul b ▸ mul_le_mul' ha hbc @[to_additive] lemma le_mul_of_le_of_one_le (hbc : b ≤ c) (ha : 1 ≤ a) : b ≤ c * a := mul_one b ▸ mul_le_mul' hbc ha @[to_additive add_nonneg] lemma one_le_mul (ha : 1 ≤ a) (hb : 1 ≤ b) : 1 ≤ a * b := le_mul_of_one_le_of_le ha hb @[to_additive add_nonpos] lemma mul_le_one' (ha : a ≤ 1) (hb : b ≤ 1) : a * b ≤ 1 := one_mul (1:α) ▸ (mul_le_mul' ha hb) @[to_additive] lemma mul_le_of_le_one_of_le' (ha : a ≤ 1) (hbc : b ≤ c) : a * b ≤ c := one_mul c ▸ mul_le_mul' ha hbc @[to_additive] lemma mul_le_of_le_of_le_one' (hbc : b ≤ c) (ha : a ≤ 1) : b * a ≤ c := mul_one c ▸ mul_le_mul' hbc ha @[to_additive] lemma mul_lt_one_of_lt_one_of_le_one' (ha : a < 1) (hb : b ≤ 1) : a * b < 1 := (mul_le_of_le_of_le_one' le_rfl hb).trans_lt ha @[to_additive] lemma mul_lt_one_of_le_one_of_lt_one' (ha : a ≤ 1) (hb : b < 1) : a * b < 1 := (mul_le_of_le_one_of_le' ha le_rfl).trans_lt hb @[to_additive] lemma mul_lt_one' (ha : a < 1) (hb : b < 1) : a * b < 1 := mul_lt_one_of_le_one_of_lt_one' ha.le hb @[to_additive] lemma mul_lt_of_le_one_of_lt' (ha : a ≤ 1) (hbc : b < c) : a * b < c := lt_of_le_of_lt (mul_le_of_le_one_of_le' ha le_rfl) hbc @[to_additive] lemma mul_lt_of_lt_of_le_one' (hbc : b < c) (ha : a ≤ 1) : b * a < c := lt_of_le_of_lt (mul_le_of_le_of_le_one' le_rfl ha) hbc @[to_additive] lemma mul_lt_of_lt_one_of_lt' (ha : a < 1) (hbc : b < c) : a * b < c := mul_lt_of_le_one_of_lt' ha.le hbc @[to_additive] lemma mul_lt_of_lt_of_lt_one' (hbc : b < c) (ha : a < 1) : b * a < c := mul_lt_of_lt_of_le_one' hbc ha.le end mul_one_class_left_right end preorder section partial_order variables [mul_one_class α] [partial_order α] [covariant_class α α (*) (≤)] [covariant_class α α (function.swap (*)) (≤)] @[to_additive] lemma mul_eq_one_iff' (ha : 1 ≤ a) (hb : 1 ≤ b) : a * b = 1 ↔ a = 1 ∧ b = 1 := iff.intro (assume hab : a * b = 1, have a ≤ 1, from hab ▸ le_mul_of_le_of_one_le le_rfl hb, have a = 1, from le_antisymm this ha, have b ≤ 1, from hab ▸ le_mul_of_one_le_of_le ha le_rfl, have b = 1, from le_antisymm this hb, and.intro ‹a = 1› ‹b = 1›) (assume ⟨ha', hb'⟩, by rw [ha', hb', mul_one]) section mono variables {β : Type*} [preorder β] {f g : β → α} @[to_additive monotone.add] lemma monotone.mul' (hf : monotone f) (hg : monotone g) : monotone (λ x, f x * g x) := λ x y h, mul_le_mul' (hf h) (hg h) @[to_additive monotone.add_const] lemma monotone.mul_const' (hf : monotone f) (a : α) : monotone (λ x, f x * a) := hf.mul' monotone_const @[to_additive monotone.const_add] lemma monotone.const_mul' (hf : monotone f) (a : α) : monotone (λ x, a * f x) := monotone_const.mul' hf end mono end partial_order @[to_additive le_of_add_le_add_left] lemma le_of_mul_le_mul_left' [partial_order α] [left_cancel_semigroup α] [contravariant_class α α (*) (<)] {a b c : α} (bc : a * b ≤ a * c) : b ≤ c := begin cases le_iff_eq_or_lt.mp bc, { exact le_iff_eq_or_lt.mpr (or.inl ((mul_right_inj a).mp h)) }, { exact (lt_of_mul_lt_mul_left' h).le } end @[to_additive le_of_add_le_add_right] lemma le_of_mul_le_mul_right' [partial_order α] [right_cancel_semigroup α] [contravariant_class α α (function.swap (*)) (<)] {a b c : α} (bc : b * a ≤ c * a) : b ≤ c := begin cases le_iff_eq_or_lt.mp bc, { exact le_iff_eq_or_lt.mpr (or.inl ((mul_left_inj a).mp h)) }, { exact (lt_of_mul_lt_mul_right' h).le } end variable [partial_order α] section left_co_co variables [left_cancel_monoid α] [covariant_class α α (*) (≤)] [contravariant_class α α (*) (<)] @[to_additive add_lt_add_left] lemma mul_lt_mul_left' (h : a < b) (c : α) : c * a < c * b := lt_of_le_not_le (mul_le_mul_left' h.le _) (λ j, not_le_of_gt h (le_of_mul_le_mul_left' j)) @[to_additive lt_add_of_pos_right] lemma lt_mul_of_one_lt_right' (a : α) {b : α} (h : 1 < b) : a < a * b := have a * 1 < a * b, from mul_lt_mul_left' h a, by rwa [mul_one] at this @[simp, to_additive] lemma mul_le_mul_iff_left (a : α) {b c : α} : a * b ≤ a * c ↔ b ≤ c := ⟨le_of_mul_le_mul_left', λ h, mul_le_mul_left' h _⟩ @[simp, to_additive] lemma mul_lt_mul_iff_left (a : α) {b c : α} : a * b < a * c ↔ b < c := ⟨lt_of_mul_lt_mul_left', λ h, mul_lt_mul_left' h _⟩ @[simp, to_additive le_add_iff_nonneg_right] lemma le_mul_iff_one_le_right' (a : α) {b : α} : a ≤ a * b ↔ 1 ≤ b := have a * 1 ≤ a * b ↔ 1 ≤ b, from mul_le_mul_iff_left a, by rwa mul_one at this @[simp, to_additive lt_add_iff_pos_right] lemma lt_mul_iff_one_lt_right' (a : α) {b : α} : a < a * b ↔ 1 < b := have a * 1 < a * b ↔ 1 < b, from mul_lt_mul_iff_left a, by rwa mul_one at this @[simp, to_additive add_le_iff_nonpos_right] lemma mul_le_iff_le_one_right' : a * b ≤ a ↔ b ≤ 1 := by { convert mul_le_mul_iff_left a, rw [mul_one] } @[simp, to_additive add_lt_iff_neg_left] lemma mul_lt_iff_lt_one_left' : a * b < a ↔ b < 1 := by { convert mul_lt_mul_iff_left a, rw [mul_one] } end left_co_co section right_cos_cos variables [right_cancel_monoid α] [covariant_class α α (function.swap (*)) (≤)] [contravariant_class α α (function.swap (*)) (<)] @[to_additive add_lt_add_right] lemma mul_lt_mul_right' (h : a < b) (c : α) : a * c < b * c := (mul_le_mul_right' h.le _).lt_of_not_le (λ j, not_le_of_gt h (le_of_mul_le_mul_right' j)) @[to_additive lt_add_of_pos_left] lemma lt_mul_of_one_lt_left' (a : α) {b : α} (h : 1 < b) : a < b * a := have 1 * a < b * a, from mul_lt_mul_right' h a, by rwa [one_mul] at this @[simp, to_additive] lemma mul_le_mul_iff_right (c : α) : a * c ≤ b * c ↔ a ≤ b := ⟨le_of_mul_le_mul_right', λ h, mul_le_mul_right' h _⟩ @[simp, to_additive] lemma mul_lt_mul_iff_right (c : α) : a * c < b * c ↔ a < b := ⟨lt_of_mul_lt_mul_right', λ h, mul_lt_mul_right' h _⟩ @[simp, to_additive le_add_iff_nonneg_left] lemma le_mul_iff_one_le_left' (a : α) {b : α} : a ≤ b * a ↔ 1 ≤ b := have 1 * a ≤ b * a ↔ 1 ≤ b, from mul_le_mul_iff_right a, by rwa one_mul at this @[simp, to_additive lt_add_iff_pos_left] lemma lt_mul_iff_one_lt_left' (a : α) {b : α} : a < b * a ↔ 1 < b := have 1 * a < b * a ↔ 1 < b, from mul_lt_mul_iff_right a, by rwa one_mul at this @[simp, to_additive add_le_iff_nonpos_left] lemma mul_le_iff_le_one_left' : a * b ≤ b ↔ a ≤ 1 := by { convert mul_le_mul_iff_right b, rw [one_mul] } @[simp, to_additive add_lt_iff_neg_right] lemma mul_lt_iff_lt_one_right' : a * b < b ↔ a < 1 := by { convert mul_lt_mul_iff_right b, rw [one_mul] } end right_cos_cos section right_co_cos variables [right_cancel_monoid α] [covariant_class α α (*) (≤)] [covariant_class α α (function.swap (*)) (≤)] @[to_additive] lemma mul_lt_mul_of_lt_of_le (h₁ : a < b) (h₂ : c ≤ d) : a * c < b * d := lt_of_lt_of_le ((covariant_class.covc c h₁.le).lt_of_ne (λ h, h₁.ne ((mul_left_inj c).mp h))) (mul_le_mul_left' h₂ b) @[to_additive] lemma mul_lt_one_of_lt_one_of_le_one (ha : a < 1) (hb : b ≤ 1) : a * b < 1 := one_mul (1:α) ▸ (mul_lt_mul_of_lt_of_le ha hb) @[to_additive] lemma lt_mul_of_one_lt_of_le (ha : 1 < a) (hbc : b ≤ c) : b < a * c := one_mul b ▸ mul_lt_mul_of_lt_of_le ha hbc @[to_additive] lemma mul_le_of_le_one_of_le (ha : a ≤ 1) (hbc : b ≤ c) : a * b ≤ c := one_mul c ▸ mul_le_mul' ha hbc @[to_additive] lemma mul_le_of_le_of_le_one (hbc : b ≤ c) (ha : a ≤ 1) : b * a ≤ c := mul_one c ▸ mul_le_mul' hbc ha @[to_additive] lemma mul_lt_of_lt_one_of_le (ha : a < 1) (hbc : b ≤ c) : a * b < c := one_mul c ▸ mul_lt_mul_of_lt_of_le ha hbc @[to_additive] lemma lt_mul_of_lt_of_one_le (hbc : b < c) (ha : 1 ≤ a) : b < c * a := mul_one b ▸ mul_lt_mul_of_lt_of_le hbc ha @[to_additive] lemma mul_lt_of_lt_of_le_one (hbc : b < c) (ha : a ≤ 1) : b * a < c := mul_one c ▸ mul_lt_mul_of_lt_of_le hbc ha end right_co_cos variables [cancel_monoid α] [covariant_class α α (*) (≤)] [contravariant_class α α (*) (<)] [covariant_class α α (function.swap (*)) (≤)] section special @[to_additive] lemma mul_lt_mul_of_le_of_lt (h₁ : a ≤ b) (h₂ : c < d) : a * c < b * d := (mul_le_mul_right' h₁ _).trans_lt (mul_lt_mul_left' h₂ b) @[to_additive] lemma mul_lt_one_of_le_one_of_lt_one (ha : a ≤ 1) (hb : b < 1) : a * b < 1 := one_mul (1:α) ▸ (mul_lt_mul_of_le_of_lt ha hb) @[to_additive] lemma lt_mul_of_le_of_one_lt (hbc : b ≤ c) (ha : 1 < a) : b < c * a := mul_one b ▸ mul_lt_mul_of_le_of_lt hbc ha @[to_additive] lemma mul_lt_of_le_of_lt_one (hbc : b ≤ c) (ha : a < 1) : b * a < c := mul_one c ▸ mul_lt_mul_of_le_of_lt hbc ha @[to_additive] lemma lt_mul_of_one_le_of_lt (ha : 1 ≤ a) (hbc : b < c) : b < a * c := one_mul b ▸ mul_lt_mul_of_le_of_lt ha hbc @[to_additive] lemma mul_lt_of_le_one_of_lt (ha : a ≤ 1) (hbc : b < c) : a * b < c := one_mul c ▸ mul_lt_mul_of_le_of_lt ha hbc end special variables [contravariant_class α α (function.swap (*)) (<)] @[to_additive add_lt_add] lemma mul_lt_mul''' (h₁ : a < b) (h₂ : c < d) : a * c < b * d := (mul_lt_mul_right' h₁ c).trans (mul_lt_mul_left' h₂ b) @[to_additive] lemma mul_eq_one_iff_eq_one_of_one_le (ha : 1 ≤ a) (hb : 1 ≤ b) : a * b = 1 ↔ a = 1 ∧ b = 1 := ⟨λ hab : a * b = 1, by split; apply le_antisymm; try {assumption}; rw ← hab; simp [ha, hb], λ ⟨ha', hb'⟩, by rw [ha', hb', mul_one]⟩ @[to_additive] lemma mul_lt_one (ha : a < 1) (hb : b < 1) : a * b < 1 := one_mul (1:α) ▸ (mul_lt_mul''' ha hb) @[to_additive] lemma lt_mul_of_one_lt_of_lt (ha : 1 < a) (hbc : b < c) : b < a * c := one_mul b ▸ mul_lt_mul''' ha hbc @[to_additive] lemma lt_mul_of_lt_of_one_lt (hbc : b < c) (ha : 1 < a) : b < c * a := mul_one b ▸ mul_lt_mul''' hbc ha @[to_additive] lemma mul_lt_of_lt_one_of_lt (ha : a < 1) (hbc : b < c) : a * b < c := one_mul c ▸ mul_lt_mul''' ha hbc @[to_additive] lemma mul_lt_of_lt_of_lt_one (hbc : b < c) (ha : a < 1) : b * a < c := mul_one c ▸ mul_lt_mul''' hbc ha
d73f45cb2ca8d5899114a8630ad4fe321ab99362
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/coercion2.lean
634b019cb379125ce78f02acbc751ff2b43f4a30
[ "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
626
lean
variable T : Type variable R : Type variable t2r : T -> R coercion t2r variable g : R -> R -> R variable a : T print g a a variable b : R print g a b print g b a set_option lean::pp::coercion true print g a a print g a b print g b a set_option lean::pp::coercion false variable S : Type variable s : S variable r : S variable h : S -> S -> S infixl 10 ++ : g infixl 10 ++ : h set_option lean::pp::notation false print a ++ b ++ a print r ++ s ++ r check a ++ b ++ a check r ++ s ++ r set_option lean::pp::coercion true print a ++ b ++ a print r ++ s ++ r set_option lean::pp::notation true print a ++ b ++ a print r ++ s ++ r
b16ecf9381a3c5e275e095807365bbb5d3ea3e30
7cef822f3b952965621309e88eadf618da0c8ae9
/src/data/semiquot.lean
b5666916f7657e4cd0db6872a80c4a81641b815c
[ "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
6,943
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro A data type for semiquotients, which are classically equivalent to nonempty sets, but are useful for programming; the idea is that a semiquotient set `S` represents some (particular but unknown) element of `S`. This can be used to model nondeterministic functions, which return something in a range of values (represented by the predicate `S`) but are not completely determined. -/ import data.set.lattice data.quot /-- A member of `semiquot α` is classically a nonempty `set α`, and in the VM is represented by an element of `α`; the relation between these is that the VM element is required to be a member of the set `s`. The specific element of `s` that the VM computes is hidden by a quotient construction, allowing for the representation of nondeterministic functions. -/ structure {u} semiquot (α : Type*) := mk' :: (s : set α) (val : trunc ↥s) namespace semiquot variables {α : Type*} {β : Type*} instance : has_mem α (semiquot α) := ⟨λ a q, a ∈ q.s⟩ def mk {a : α} {s : set α} (h : a ∈ s) : semiquot α := ⟨s, trunc.mk ⟨a, h⟩⟩ theorem ext_s {q₁ q₂ : semiquot α} : q₁ = q₂ ↔ q₁.s = q₂.s := ⟨congr_arg _, λ h, by cases q₁; cases q₂; congr; exact h⟩ theorem ext {q₁ q₂ : semiquot α} : q₁ = q₂ ↔ ∀ a, a ∈ q₁ ↔ a ∈ q₂ := ext_s.trans (set.ext_iff _ _) theorem exists_mem (q : semiquot α) : ∃ a, a ∈ q := let ⟨⟨a, h⟩, h₂⟩ := q.2.exists_rep in ⟨a, h⟩ theorem eq_mk_of_mem {q : semiquot α} {a : α} (h : a ∈ q) : q = @mk _ a q.1 h := ext_s.2 rfl theorem ne_empty (q : semiquot α) : q.s ≠ ∅ := let ⟨a, h⟩ := q.exists_mem in set.ne_empty_of_mem h protected def pure (a : α) : semiquot α := mk (set.mem_singleton a) @[simp] theorem mem_pure' {a b : α} : a ∈ semiquot.pure b ↔ a = b := set.mem_singleton_iff def blur' (q : semiquot α) {s : set α} (h : q.s ⊆ s) : semiquot α := ⟨s, trunc.lift (λ a : q.s, trunc.mk ⟨a.1, h a.2⟩) (λ _ _, trunc.eq _ _) q.2⟩ def blur (s : set α) (q : semiquot α) : semiquot α := blur' q (set.subset_union_right s q.s) theorem blur_eq_blur' (q : semiquot α) (s : set α) (h : q.s ⊆ s) : blur s q = blur' q h := by unfold blur; congr; exact set.union_eq_self_of_subset_right h @[simp] theorem mem_blur' (q : semiquot α) {s : set α} (h : q.s ⊆ s) {a : α} : a ∈ blur' q h ↔ a ∈ s := iff.rfl def of_trunc (q : trunc α) : semiquot α := ⟨set.univ, q.map (λ a, ⟨a, trivial⟩)⟩ def to_trunc (q : semiquot α) : trunc α := q.2.map subtype.val def lift_on (q : semiquot α) (f : α → β) (h : ∀ a b ∈ q, f a = f b) : β := trunc.lift_on q.2 (λ x, f x.1) (λ x y, h _ _ x.2 y.2) theorem lift_on_of_mem (q : semiquot α) (f : α → β) (h : ∀ a b ∈ q, f a = f b) (a : α) (aq : a ∈ q) : lift_on q f h = f a := by revert h; rw eq_mk_of_mem aq; intro; refl def map (f : α → β) (q : semiquot α) : semiquot β := ⟨f '' q.1, q.2.map (λ x, ⟨f x.1, set.mem_image_of_mem _ x.2⟩)⟩ @[simp] theorem mem_map (f : α → β) (q : semiquot α) (b : β) : b ∈ map f q ↔ ∃ a, a ∈ q ∧ f a = b := set.mem_image _ _ _ def bind (q : semiquot α) (f : α → semiquot β) : semiquot β := ⟨⋃ a ∈ q.1, (f a).1, q.2.bind (λ a, (f a.1).2.map (λ b, ⟨b.1, set.mem_bUnion a.2 b.2⟩))⟩ @[simp] theorem mem_bind (q : semiquot α) (f : α → semiquot β) (b : β) : b ∈ bind q f ↔ ∃ a, a ∈ q ∧ b ∈ f a := set.mem_bUnion_iff instance : monad semiquot := { pure := @semiquot.pure, map := @semiquot.map, bind := @semiquot.bind } @[simp] theorem mem_pure {a b : α} : a ∈ (pure b : semiquot α) ↔ a = b := set.mem_singleton_iff theorem mem_pure_self (a : α) : a ∈ (pure a : semiquot α) := set.mem_singleton a @[simp] theorem pure_inj {a b : α} : (pure a : semiquot α) = pure b ↔ a = b := ext_s.trans set.singleton_eq_singleton_iff instance : is_lawful_monad semiquot := { pure_bind := λ α β x f, ext.2 $ by simp, bind_assoc := λ α β γ s f g, ext.2 $ by simp; exact λ c, ⟨λ ⟨b, ⟨a, as, bf⟩, cg⟩, ⟨a, as, b, bf, cg⟩, λ ⟨a, as, b, bf, cg⟩, ⟨b, ⟨a, as, bf⟩, cg⟩⟩, id_map := λ α q, ext.2 $ by simp, bind_pure_comp_eq_map := λ α β f s, ext.2 $ by simp [eq_comm] } instance : has_le (semiquot α) := ⟨λ s t, s.s ⊆ t.s⟩ instance : partial_order (semiquot α) := { le := λ s t, ∀ ⦃x⦄, x ∈ s → x ∈ t, le_refl := λ s, set.subset.refl _, le_trans := λ s t u, set.subset.trans, le_antisymm := λ s t h₁ h₂, ext_s.2 (set.subset.antisymm h₁ h₂) } instance : lattice.semilattice_sup (semiquot α) := { sup := λ s, blur s.s, le_sup_left := λ s t, set.subset_union_left _ _, le_sup_right := λ s t, set.subset_union_right _ _, sup_le := λ s t u, set.union_subset, ..semiquot.partial_order } @[simp] theorem pure_le {a : α} {s : semiquot α} : pure a ≤ s ↔ a ∈ s := set.singleton_subset_iff def is_pure (q : semiquot α) := ∀ a b ∈ q, a = b def get (q) (h : @is_pure α q) : α := lift_on q id h theorem get_mem {q : semiquot α} (p) : get q p ∈ q := let ⟨a, h⟩ := exists_mem q in by unfold get; rw lift_on_of_mem q _ _ a h; exact h theorem eq_pure {q : semiquot α} (p) : q = pure (get q p) := ext.2 $ λ a, by simp; exact ⟨λ h, p _ _ h (get_mem _), λ e, e.symm ▸ get_mem _⟩ @[simp] theorem pure_is_pure (a : α) : is_pure (pure a) | b c ab ac := by { simp at ab ac, cc } theorem is_pure_iff {s : semiquot α} : is_pure s ↔ ∃ a, s = pure a := ⟨λ h, ⟨_, eq_pure h⟩, λ ⟨a, e⟩, e.symm ▸ pure_is_pure _⟩ theorem is_pure.mono {s t : semiquot α} (st : s ≤ t) (h : is_pure t) : is_pure s | a b as bs := h _ _ (st as) (st bs) theorem is_pure.min {s t : semiquot α} (h : is_pure t) : s ≤ t ↔ s = t := ⟨λ st, le_antisymm st $ by rw [eq_pure h, eq_pure (h.mono st)]; simp; exact h _ _ (get_mem _) (st $ get_mem _), le_of_eq⟩ theorem is_pure_of_subsingleton [subsingleton α] (q : semiquot α) : is_pure q | a b aq bq := subsingleton.elim _ _ def univ [inhabited α] : semiquot α := mk $ set.mem_univ (default _) @[simp] theorem mem_univ [inhabited α] : ∀ a, a ∈ @univ α _ := @set.mem_univ α @[congr] theorem univ_unique (I J : inhabited α) : @univ _ I = @univ _ J := ext.2 $ by simp @[simp] theorem is_pure_univ [inhabited α] : @is_pure α univ ↔ subsingleton α := ⟨λ h, ⟨λ a b, h a b trivial trivial⟩, λ ⟨h⟩ a b _ _, h a b⟩ instance [inhabited α] : lattice.order_top (semiquot α) := { top := univ, le_top := λ s, set.subset_univ _, ..semiquot.partial_order } instance [inhabited α] : lattice.semilattice_sup_top (semiquot α) := { ..semiquot.lattice.order_top, ..semiquot.lattice.semilattice_sup } end semiquot
e161ad3ac5aede1fe6b5c33830dff63f0d7d46f4
5e3548e65f2c037cb94cd5524c90c623fbd6d46a
/src_icannos_totilas/topologie-espaces-normés/cpge_ten_06.lean
680e89cd0ca14df61edefa5a0f38a36d74a1a37f
[]
no_license
ahayat16/lean_exos
d4f08c30adb601a06511a71b5ffb4d22d12ef77f
682f2552d5b04a8c8eb9e4ab15f875a91b03845c
refs/heads/main
1,693,101,073,585
1,636,479,336,000
1,636,479,336,000
415,000,441
0
0
null
null
null
null
UTF-8
Lean
false
false
985
lean
import data.set.basic import topology.basic import algebra.module.basic import algebra.module.submodule import order.complete_lattice import analysis.normed_space.basic -- Soient A, B deux parties non vides d'un espace vectoriel normé E telles que -- d(A, B) = inf_xy d(x, y) > 0 -- Montrer qu'il existe deux ouverts disjoints U et V tels que A ⊂ U et B ⊂ V . -- F ⊂ U, G ⊂ V et U ∩ V = ∅ . theorem exo {R E: Type*} [normed_field R] [normed_group E] [normed_space R E] : forall (A B: set E), (set.nonempty A) -> (set.nonempty B) -> -- typing error here. -- type mismatch at application -- dist p.fst p.snd -- term -- p.snd -- has type -- ↥B -- but is expected to have type -- ↥A (infi (λ (p: A × B), dist p.fst p.snd) > 0) -> -- sparable exists (U V: set E), (is_open U) /\ (is_open V) /\ set.subset A U /\ set.subset B V /\ set.inter A B = ∅ := sorry
3c319ee17ff2c42a4c6dd37169636e5f5cf7688c
200b12985a863d01fbbde6abfc9326bb82424a8b
/src/propLogic/Ex006.lean
0f23034a3da5d0a40f440383121b12c860af5a79
[]
no_license
SvenWille/LeanLogicExercises
38eacd36733ac48e5a7aacf863c681c9a9a48271
2dbc920feadd63bbc50f87e69646c0081db26eba
refs/heads/master
1,629,676,667,365
1,512,161,459,000
1,512,161,459,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
533
lean
theorem Ex006(a b c : Prop): a ∨ b → a ∨ c → a ∨ (b ∧ c) := assume H1:a ∨ b, assume H2:a ∨ c, show a ∨ (b ∧ c), from or.elim H1 ( assume H :a, show a ∨ (b ∧ c), from or.inl H ) ( assume H: b, show a ∨ (b ∧ c), from or.elim H2 ( assume HH:a, show a ∨ (b ∧ c), from or.inl HH ) ( assume HH:c, have H3:b ∧ c, from and.intro H HH, show a ∨ (b ∧ c), from or.inr H3 ) )
5c9c000568338f7cbaa3de7420522ed0f6d61238
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/tests/lean/run/macro2.lean
2d22f99498805174cfde054bb5e3d7449802205e
[ "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
340
lean
notation:50 a "**" b:50 => b * a * b notation "~" a => a+a namespace Foo notation "~~" a => a+a end Foo syntax:60 term "+++" term:59 : term syntax "<|" term "|>" : term macro_rules | `($a +++ $b) => `($a + $b + $b) macro_rules | `(<| $x |>) => `($x +++ 1 ** 2) #check <| 2 |> #check <| ~2 |> #check <| ~~2 |> #check <| <| 3 |> |>
ac39c217d84a1306350edacf9e77768d764f194b
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/MonadEnv.lean
6e3b4011e642f42b6e0920820f98dc904c9679e5
[ "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
6,393
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.Environment import Lean.Exception import Lean.Declaration import Lean.Log import Lean.AuxRecursor import Lean.Compiler.Old namespace Lean def setEnv [MonadEnv m] (env : Environment) : m Unit := modifyEnv fun _ => env def withEnv [Monad m] [MonadFinally m] [MonadEnv m] (env : Environment) (x : m α) : m α := do let saved ← getEnv try setEnv env x finally setEnv saved def isInductive [Monad m] [MonadEnv m] (declName : Name) : m Bool := do match (← getEnv).find? declName with | some (ConstantInfo.inductInfo ..) => return true | _ => return false def isRecCore (env : Environment) (declName : Name) : Bool := match env.find? declName with | some (ConstantInfo.recInfo ..) => true | _ => false def isRec [Monad m] [MonadEnv m] (declName : Name) : m Bool := return isRecCore (← getEnv) declName @[inline] def withoutModifyingEnv [Monad m] [MonadEnv m] [MonadFinally m] {α : Type} (x : m α) : m α := do let env ← getEnv try x finally setEnv env /-- Similar to `withoutModifyingEnv`, but also returns the updated environment -/ @[inline] def withoutModifyingEnv' [Monad m] [MonadEnv m] [MonadFinally m] {α : Type} (x : m α) : m (α × Environment) := do let env ← getEnv try let a ← x return (a, ← getEnv) finally setEnv env @[inline] def matchConst [Monad m] [MonadEnv m] (e : Expr) (failK : Unit → m α) (k : ConstantInfo → List Level → m α) : m α := do match e with | Expr.const constName us => do match (← getEnv).find? constName with | some cinfo => k cinfo us | none => failK () | _ => failK () @[inline] def matchConstInduct [Monad m] [MonadEnv m] (e : Expr) (failK : Unit → m α) (k : InductiveVal → List Level → m α) : m α := matchConst e failK fun cinfo us => match cinfo with | ConstantInfo.inductInfo val => k val us | _ => failK () @[inline] def matchConstCtor [Monad m] [MonadEnv m] (e : Expr) (failK : Unit → m α) (k : ConstructorVal → List Level → m α) : m α := matchConst e failK fun cinfo us => match cinfo with | ConstantInfo.ctorInfo val => k val us | _ => failK () @[inline] def matchConstRec [Monad m] [MonadEnv m] (e : Expr) (failK : Unit → m α) (k : RecursorVal → List Level → m α) : m α := matchConst e failK fun cinfo us => match cinfo with | ConstantInfo.recInfo val => k val us | _ => failK () def hasConst [Monad m] [MonadEnv m] (constName : Name) : m Bool := do return (← getEnv).contains constName private partial def mkAuxNameAux (env : Environment) (base : Name) (i : Nat) : Name := let candidate := base.appendIndexAfter i if env.contains candidate then mkAuxNameAux env base (i+1) else candidate def mkAuxName [Monad m] [MonadEnv m] (baseName : Name) (idx : Nat) : m Name := do return mkAuxNameAux (← getEnv) baseName idx def getConstInfo [Monad m] [MonadEnv m] [MonadError m] (constName : Name) : m ConstantInfo := do match (← getEnv).find? constName with | some info => pure info | none => throwError "unknown constant '{mkConst constName}'" def mkConstWithLevelParams [Monad m] [MonadEnv m] [MonadError m] (constName : Name) : m Expr := do let info ← getConstInfo constName return mkConst constName (info.levelParams.map mkLevelParam) def getConstInfoDefn [Monad m] [MonadEnv m] [MonadError m] (constName : Name) : m DefinitionVal := do match (← getConstInfo constName) with | ConstantInfo.defnInfo v => pure v | _ => throwError "'{mkConst constName}' is not a definition" def getConstInfoInduct [Monad m] [MonadEnv m] [MonadError m] (constName : Name) : m InductiveVal := do match (← getConstInfo constName) with | ConstantInfo.inductInfo v => pure v | _ => throwError "'{mkConst constName}' is not a inductive type" def getConstInfoCtor [Monad m] [MonadEnv m] [MonadError m] (constName : Name) : m ConstructorVal := do match (← getConstInfo constName) with | ConstantInfo.ctorInfo v => pure v | _ => throwError "'{mkConst constName}' is not a constructor" def getConstInfoRec [Monad m] [MonadEnv m] [MonadError m] (constName : Name) : m RecursorVal := do match (← getConstInfo constName) with | ConstantInfo.recInfo v => pure v | _ => throwError "'{mkConst constName}' is not a recursor" @[inline] def matchConstStruct [Monad m] [MonadEnv m] [MonadError m] (e : Expr) (failK : Unit → m α) (k : InductiveVal → List Level → ConstructorVal → m α) : m α := matchConstInduct e failK fun ival us => do if ival.isRec || ival.numIndices != 0 then failK () else match ival.ctors with | [ctor] => match (← getConstInfo ctor) with | ConstantInfo.ctorInfo cval => k ival us cval | _ => failK () | _ => failK () unsafe def evalConst [Monad m] [MonadEnv m] [MonadError m] [MonadOptions m] (α) (constName : Name) : m α := do ofExcept <| (← getEnv).evalConst α (← getOptions) constName unsafe def evalConstCheck [Monad m] [MonadEnv m] [MonadError m] [MonadOptions m] (α) (typeName : Name) (constName : Name) : m α := do ofExcept <| (← getEnv).evalConstCheck α (← getOptions) typeName constName def findModuleOf? [Monad m] [MonadEnv m] [MonadError m] (declName : Name) : m (Option Name) := do discard <| getConstInfo declName -- ensure declaration exists match (← getEnv).getModuleIdxFor? declName with | none => return none | some modIdx => return some ((← getEnv).allImportedModuleNames[modIdx.toNat]!) def isEnumType [Monad m] [MonadEnv m] [MonadError m] (declName : Name) : m Bool := do if let ConstantInfo.inductInfo info ← getConstInfo declName then if !info.type.isProp && info.all.length == 1 && info.numIndices == 0 && info.numParams == 0 && !info.ctors.isEmpty && !info.isRec && !info.isNested && !info.isUnsafe then info.ctors.allM fun ctorName => do let ConstantInfo.ctorInfo info ← getConstInfo ctorName | return false return info.numFields == 0 else return false else return false end Lean
ac96e66c896beac3d281e601ee57c7cf98e0c57c
4727251e0cd73359b15b664c3170e5d754078599
/src/group_theory/group_action/prod.lean
dc845b81552d2e9cea3c7b0684b24490e472575a
[ "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,482
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot, Eric Wieser -/ import algebra.group.prod import group_theory.group_action.defs /-! # Prod instances for additive and multiplicative actions This file defines instances for binary product of additive and multiplicative actions and provides scalar multiplication as a homomorphism from `α × β` to `β`. ## Main declarations * `smul_mul_hom`/`smul_monoid_hom`: Scalar multiplication bundled as a multiplicative/monoid homomorphism. -/ variables {M N P α β : Type*} namespace prod section variables [has_scalar M α] [has_scalar M β] [has_scalar N α] [has_scalar N β] (a : M) (x : α × β) @[to_additive prod.has_vadd] instance : has_scalar M (α × β) := ⟨λa p, (a • p.1, a • p.2)⟩ @[simp, to_additive] theorem smul_fst : (a • x).1 = a • x.1 := rfl @[simp, to_additive] theorem smul_snd : (a • x).2 = a • x.2 := rfl @[simp, to_additive] theorem smul_mk (a : M) (b : α) (c : β) : a • (b, c) = (a • b, a • c) := rfl @[to_additive] theorem smul_def (a : M) (x : α × β) : a • x = (a • x.1, a • x.2) := rfl @[simp, to_additive] theorem smul_swap : (a • x).swap = a • x.swap := rfl instance [has_scalar M N] [is_scalar_tower M N α] [is_scalar_tower M N β] : is_scalar_tower M N (α × β) := ⟨λ x y z, mk.inj_iff.mpr ⟨smul_assoc _ _ _, smul_assoc _ _ _⟩⟩ @[to_additive] instance [smul_comm_class M N α] [smul_comm_class M N β] : smul_comm_class M N (α × β) := { smul_comm := λ r s x, mk.inj_iff.mpr ⟨smul_comm _ _ _, smul_comm _ _ _⟩ } instance [has_scalar Mᵐᵒᵖ α] [has_scalar Mᵐᵒᵖ β] [is_central_scalar M α] [is_central_scalar M β] : is_central_scalar M (α × β) := ⟨λ r m, prod.ext (op_smul_eq_smul _ _) (op_smul_eq_smul _ _)⟩ @[to_additive has_faithful_vadd_left] instance has_faithful_scalar_left [has_faithful_scalar M α] [nonempty β] : has_faithful_scalar M (α × β) := ⟨λ x y h, let ⟨b⟩ := ‹nonempty β› in eq_of_smul_eq_smul $ λ a : α, by injection h (a, b)⟩ @[to_additive has_faithful_vadd_right] instance has_faithful_scalar_right [nonempty α] [has_faithful_scalar M β] : has_faithful_scalar M (α × β) := ⟨λ x y h, let ⟨a⟩ := ‹nonempty α› in eq_of_smul_eq_smul $ λ b : β, by injection h (a, b)⟩ end @[to_additive] instance smul_comm_class_both [has_mul N] [has_mul P] [has_scalar M N] [has_scalar M P] [smul_comm_class M N N] [smul_comm_class M P P] : smul_comm_class M (N × P) (N × P) := ⟨λ c x y, by simp [smul_def, mul_def, mul_smul_comm]⟩ instance is_scalar_tower_both [has_mul N] [has_mul P] [has_scalar M N] [has_scalar M P] [is_scalar_tower M N N] [is_scalar_tower M P P] : is_scalar_tower M (N × P) (N × P) := ⟨λ c x y, by simp [smul_def, mul_def, smul_mul_assoc]⟩ @[to_additive] instance {m : monoid M} [mul_action M α] [mul_action M β] : mul_action M (α × β) := { mul_smul := λ a₁ a₂ p, mk.inj_iff.mpr ⟨mul_smul _ _ _, mul_smul _ _ _⟩, one_smul := λ ⟨b, c⟩, mk.inj_iff.mpr ⟨one_smul _ _, one_smul _ _⟩ } instance {R M N : Type*} {r : monoid R} [add_monoid M] [add_monoid N] [distrib_mul_action R M] [distrib_mul_action R N] : distrib_mul_action R (M × N) := { smul_add := λ a p₁ p₂, mk.inj_iff.mpr ⟨smul_add _ _ _, smul_add _ _ _⟩, smul_zero := λ a, mk.inj_iff.mpr ⟨smul_zero _, smul_zero _⟩ } instance {R M N : Type*} {r : monoid R} [monoid M] [monoid N] [mul_distrib_mul_action R M] [mul_distrib_mul_action R N] : mul_distrib_mul_action R (M × N) := { smul_mul := λ a p₁ p₂, mk.inj_iff.mpr ⟨smul_mul' _ _ _, smul_mul' _ _ _⟩, smul_one := λ a, mk.inj_iff.mpr ⟨smul_one _, smul_one _⟩ } end prod /-! ### Scalar multiplication as a homomorphism -/ section bundled_smul /-- Scalar multiplication as a multiplicative homomorphism. -/ @[simps] def smul_mul_hom [monoid α] [has_mul β] [mul_action α β] [is_scalar_tower α β β] [smul_comm_class α β β] : (α × β) →ₙ* β := { to_fun := λ a, a.1 • a.2, map_mul' := λ a b, (smul_mul_smul _ _ _ _).symm } /-- Scalar multiplication as a monoid homomorphism. -/ @[simps] def smul_monoid_hom [monoid α] [mul_one_class β] [mul_action α β] [is_scalar_tower α β β] [smul_comm_class α β β] : α × β →* β := { map_one' := one_smul _ _, .. smul_mul_hom } end bundled_smul
52536e8b280a73ec64a449fd68c5b4e57cc35936
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/pnat/intervals.lean
ee8b1488dbf75cd8e0465ad6c60f45e350a9657d
[ "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
815
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import data.pnat.basic import data.finset.intervals namespace pnat /-- `Ico l u` is the set of positive natural numbers `l ≤ k < u`. -/ def Ico (l u : ℕ+) : finset ℕ+ := (finset.Ico l u).attach.map { to_fun := λ n, ⟨(n : ℕ), lt_of_lt_of_le l.2 (finset.Ico.mem.1 n.2).1⟩, -- why can't we do this directly? inj' := λ n m h, subtype.eq (by { replace h := congr_arg subtype.val h, exact h }) } @[simp] lemma Ico.mem : ∀ {n m l : ℕ+}, l ∈ Ico n m ↔ n ≤ l ∧ l < m := by { rintro ⟨n, hn⟩ ⟨m, hm⟩ ⟨l, hl⟩, simp [pnat.Ico] } @[simp] lemma Ico.card (l u : ℕ+) : (Ico l u).card = u - l := by simp [pnat.Ico] end pnat
d6b54452f095c32e89012c2af561b7bfba8b31e2
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/stage0/src/Init/Meta.lean
827504d16c584d88539310e149c8a6ab91796371
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
31,992
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 and Sebastian Ullrich Additional goodies for writing macros -/ prelude import Init.Data.Array.Basic namespace Lean @[extern c inline "lean_box(LEAN_VERSION_MAJOR)"] private constant version.getMajor (u : Unit) : Nat def version.major : Nat := version.getMajor () @[extern c inline "lean_box(LEAN_VERSION_MINOR)"] private constant version.getMinor (u : Unit) : Nat def version.minor : Nat := version.getMinor () @[extern c inline "lean_box(LEAN_VERSION_PATCH)"] private constant version.getPatch (u : Unit) : Nat def version.patch : Nat := version.getPatch () -- @[extern c inline "lean_mk_string(LEAN_GITHASH)"] -- constant getGithash (u : Unit) : String -- def githash : String := getGithash () @[extern c inline "LEAN_VERSION_IS_RELEASE"] constant version.getIsRelease (u : Unit) : Bool def version.isRelease : Bool := version.getIsRelease () /-- Additional version description like "nightly-2018-03-11" -/ @[extern c inline "lean_mk_string(LEAN_SPECIAL_VERSION_DESC)"] constant version.getSpecialDesc (u : Unit) : String def version.specialDesc : String := version.getSpecialDesc () /- Valid identifier names -/ def isGreek (c : Char) : Bool := 0x391 ≤ c.val && c.val ≤ 0x3dd def isLetterLike (c : Char) : Bool := (0x3b1 ≤ c.val && c.val ≤ 0x3c9 && c.val ≠ 0x3bb) || -- Lower greek, but lambda (0x391 ≤ c.val && c.val ≤ 0x3A9 && c.val ≠ 0x3A0 && c.val ≠ 0x3A3) || -- Upper greek, but Pi and Sigma (0x3ca ≤ c.val && c.val ≤ 0x3fb) || -- Coptic letters (0x1f00 ≤ c.val && c.val ≤ 0x1ffe) || -- Polytonic Greek Extended Character Set (0x2100 ≤ c.val && c.val ≤ 0x214f) || -- Letter like block (0x1d49c ≤ c.val && c.val ≤ 0x1d59f) -- Latin letters, Script, Double-struck, Fractur def isNumericSubscript (c : Char) : Bool := 0x2080 ≤ c.val && c.val ≤ 0x2089 def isSubScriptAlnum (c : Char) : Bool := isNumericSubscript c || (0x2090 ≤ c.val && c.val ≤ 0x209c) || (0x1d62 ≤ c.val && c.val ≤ 0x1d6a) def isIdFirst (c : Char) : Bool := c.isAlpha || c = '_' || isLetterLike c def isIdRest (c : Char) : Bool := c.isAlphanum || c = '_' || c = '\'' || c == '!' || c == '?' || isLetterLike c || isSubScriptAlnum c def idBeginEscape := '«' def idEndEscape := '»' def isIdBeginEscape (c : Char) : Bool := c = idBeginEscape def isIdEndEscape (c : Char) : Bool := c = idEndEscape namespace Name def getRoot : Name → Name | anonymous => anonymous | n@(str anonymous _ _) => n | n@(num anonymous _ _) => n | str n _ _ => getRoot n | num n _ _ => getRoot n @[export lean_is_inaccessible_user_name] def isInaccessibleUserName : Name → Bool | Name.str _ s _ => s.contains '✝' || s == "_inaccessible" | Name.num p idx _ => isInaccessibleUserName p | _ => false def escapePart (s : String) : Option String := if s.length > 0 && isIdFirst s[0] && (s.toSubstring.drop 1).all isIdRest then s else if s.any isIdEndEscape then none else some <| idBeginEscape.toString ++ s ++ idEndEscape.toString -- NOTE: does not roundtrip even with `escape = true` if name is anonymous or contains numeric part or `idEndEscape` variable (sep : String) (escape : Bool) def toStringWithSep : Name → String | anonymous => "[anonymous]" | str anonymous s _ => maybeEscape s | num anonymous v _ => toString v | str n s _ => toStringWithSep n ++ sep ++ maybeEscape s | num n v _ => toStringWithSep n ++ sep ++ Nat.repr v where maybeEscape s := if escape then escapePart s |>.getD s else s protected def toString (n : Name) (escape := true) : String := -- never escape "prettified" inaccessible names or macro scopes or pseudo-syntax introduced by the delaborator toStringWithSep "." (escape && !n.isInaccessibleUserName && !n.hasMacroScopes && !maybePseudoSyntax) n where maybePseudoSyntax := if let Name.str _ s _ := n.getRoot then -- could be pseudo-syntax for loose bvar or universe mvar, output as is "#".isPrefixOf s || "?".isPrefixOf s else false instance : ToString Name where toString n := n.toString instance : Repr Name where reprPrec n _ := Std.Format.text "`" ++ n.toString def capitalize : Name → Name | Name.str p s _ => Name.mkStr p s.capitalize | n => n def replacePrefix : Name → Name → Name → Name | anonymous, anonymous, newP => newP | anonymous, _, _ => anonymous | n@(str p s _), queryP, newP => if n == queryP then newP else Name.mkStr (p.replacePrefix queryP newP) s | n@(num p s _), queryP, newP => if n == queryP then newP else Name.mkNum (p.replacePrefix queryP newP) s /-- Remove macros scopes, apply `f`, and put them back -/ @[inline] def modifyBase (n : Name) (f : Name → Name) : Name := if n.hasMacroScopes then let view := extractMacroScopes n { view with name := f view.name }.review else f n @[export lean_name_append_after] def appendAfter (n : Name) (suffix : String) : Name := n.modifyBase fun | str p s _ => Name.mkStr p (s ++ suffix) | n => Name.mkStr n suffix @[export lean_name_append_index_after] def appendIndexAfter (n : Name) (idx : Nat) : Name := n.modifyBase fun | str p s _ => Name.mkStr p (s ++ "_" ++ toString idx) | n => Name.mkStr n ("_" ++ toString idx) @[export lean_name_append_before] def appendBefore (n : Name) (pre : String) : Name := n.modifyBase fun | anonymous => Name.mkStr anonymous pre | str p s _ => Name.mkStr p (pre ++ s) | num p n _ => Name.mkNum (Name.mkStr p pre) n end Name structure NameGenerator where namePrefix : Name := `_uniq idx : Nat := 1 deriving Inhabited namespace NameGenerator @[inline] def curr (g : NameGenerator) : Name := Name.mkNum g.namePrefix g.idx @[inline] def next (g : NameGenerator) : NameGenerator := { g with idx := g.idx + 1 } @[inline] def mkChild (g : NameGenerator) : NameGenerator × NameGenerator := ({ namePrefix := Name.mkNum g.namePrefix g.idx, idx := 1 }, { g with idx := g.idx + 1 }) end NameGenerator class MonadNameGenerator (m : Type → Type) where getNGen : m NameGenerator setNGen : NameGenerator → m Unit export MonadNameGenerator (getNGen setNGen) def mkFreshId {m : Type → Type} [Monad m] [MonadNameGenerator m] : m Name := do let ngen ← getNGen let r := ngen.curr setNGen ngen.next pure r instance monadNameGeneratorLift (m n : Type → Type) [MonadLift m n] [MonadNameGenerator m] : MonadNameGenerator n := { getNGen := liftM (getNGen : m _), setNGen := fun ngen => liftM (setNGen ngen : m _) } namespace Syntax partial def structEq : Syntax → Syntax → Bool | Syntax.missing, Syntax.missing => true | Syntax.node k args, Syntax.node k' args' => k == k' && args.isEqv args' structEq | Syntax.atom _ val, Syntax.atom _ val' => val == val' | Syntax.ident _ rawVal val preresolved, Syntax.ident _ rawVal' val' preresolved' => rawVal == rawVal' && val == val' && preresolved == preresolved' | _, _ => false instance : BEq Lean.Syntax := ⟨structEq⟩ partial def getTailInfo? : Syntax → Option SourceInfo | atom info _ => info | ident info .. => info | node _ args => args.findSomeRev? getTailInfo? | _ => none def getTailInfo (stx : Syntax) : SourceInfo := stx.getTailInfo?.getD SourceInfo.none def getTrailingSize (stx : Syntax) : Nat := match stx.getTailInfo? with | some (SourceInfo.original (trailing := trailing) ..) => trailing.bsize | _ => 0 @[specialize] private partial def updateLast {α} [Inhabited α] (a : Array α) (f : α → Option α) (i : Nat) : Option (Array α) := if i == 0 then none else let i := i - 1 let v := a[i] match f v with | some v => some <| a.set! i v | none => updateLast a f i partial def setTailInfoAux (info : SourceInfo) : Syntax → Option Syntax | atom _ val => some <| atom info val | ident _ rawVal val pre => some <| ident info rawVal val pre | node k args => match updateLast args (setTailInfoAux info) args.size with | some args => some <| node k args | none => none | stx => none def setTailInfo (stx : Syntax) (info : SourceInfo) : Syntax := match setTailInfoAux info stx with | some stx => stx | none => stx def unsetTrailing (stx : Syntax) : Syntax := match stx.getTailInfo with | SourceInfo.original lead pos trail endPos => stx.setTailInfo (SourceInfo.original lead pos "".toSubstring endPos) | _ => stx @[specialize] private partial def updateFirst {α} [Inhabited α] (a : Array α) (f : α → Option α) (i : Nat) : Option (Array α) := if h : i < a.size then let v := a.get ⟨i, h⟩; match f v with | some v => some <| a.set ⟨i, h⟩ v | none => updateFirst a f (i+1) else none partial def setHeadInfoAux (info : SourceInfo) : Syntax → Option Syntax | atom _ val => some <| atom info val | ident _ rawVal val pre => some <| ident info rawVal val pre | node k args => match updateFirst args (setHeadInfoAux info) 0 with | some args => some <| node k args | noxne => none | stx => none def setHeadInfo (stx : Syntax) (info : SourceInfo) : Syntax := match setHeadInfoAux info stx with | some stx => stx | none => stx def setInfo (info : SourceInfo) : Syntax → Syntax | atom _ val => atom info val | ident _ rawVal val pre => ident info rawVal val pre | stx => stx /-- Return the first atom/identifier that has position information -/ partial def getHead? : Syntax → Option Syntax | stx@(atom info ..) => info.getPos?.map fun _ => stx | stx@(ident info ..) => info.getPos?.map fun _ => stx | node _ args => args.findSome? getHead? | _ => none def copyHeadTailInfoFrom (target source : Syntax) : Syntax := target.setHeadInfo source.getHeadInfo |>.setTailInfo source.getTailInfo end Syntax /-- Use the head atom/identifier of the current `ref` as the `ref` -/ @[inline] def withHeadRefOnly {m : Type → Type} [Monad m] [MonadRef m] {α} (x : m α) : m α := do match (← getRef).getHead? with | none => x | some ref => withRef ref x @[inline] def mkNode (k : SyntaxNodeKind) (args : Array Syntax) : Syntax := Syntax.node k args /- Syntax objects for a Lean module. -/ structure Module where header : Syntax commands : Array Syntax /-- Expand all macros in the given syntax -/ partial def expandMacros : Syntax → MacroM Syntax | stx@(Syntax.node k args) => do match (← expandMacro? stx) with | some stxNew => expandMacros stxNew | none => do let args ← Macro.withIncRecDepth stx <| args.mapM expandMacros pure <| Syntax.node k args | stx => pure stx /- Helper functions for processing Syntax programmatically -/ /-- Create an identifier copying the position from `src`. To refer to a specific constant, use `mkCIdentFrom` instead. -/ def mkIdentFrom (src : Syntax) (val : Name) : Syntax := Syntax.ident (SourceInfo.fromRef src) (toString val).toSubstring val [] def mkIdentFromRef [Monad m] [MonadRef m] (val : Name) : m Syntax := do return mkIdentFrom (← getRef) val /-- Create an identifier referring to a constant `c` copying the position from `src`. This variant of `mkIdentFrom` makes sure that the identifier cannot accidentally be captured. -/ def mkCIdentFrom (src : Syntax) (c : Name) : Syntax := -- Remark: We use the reserved macro scope to make sure there are no accidental collision with our frontend let id := addMacroScope `_internal c reservedMacroScope Syntax.ident (SourceInfo.fromRef src) (toString id).toSubstring id [(c, [])] def mkCIdentFromRef [Monad m] [MonadRef m] (c : Name) : m Syntax := do return mkCIdentFrom (← getRef) c def mkCIdent (c : Name) : Syntax := mkCIdentFrom Syntax.missing c @[export lean_mk_syntax_ident] def mkIdent (val : Name) : Syntax := Syntax.ident SourceInfo.none (toString val).toSubstring val [] @[inline] def mkNullNode (args : Array Syntax := #[]) : Syntax := Syntax.node nullKind args @[inline] def mkGroupNode (args : Array Syntax := #[]) : Syntax := Syntax.node groupKind args def mkSepArray (as : Array Syntax) (sep : Syntax) : Array Syntax := do let mut i := 0 let mut r := #[] for a in as do if i > 0 then r := r.push sep |>.push a else r := r.push a i := i + 1 return r def mkOptionalNode (arg : Option Syntax) : Syntax := match arg with | some arg => Syntax.node nullKind #[arg] | none => Syntax.node nullKind #[] def mkHole (ref : Syntax) : Syntax := Syntax.node `Lean.Parser.Term.hole #[mkAtomFrom ref "_"] namespace Syntax def mkSep (a : Array Syntax) (sep : Syntax) : Syntax := mkNullNode <| mkSepArray a sep def SepArray.ofElems {sep} (elems : Array Syntax) : SepArray sep := ⟨mkSepArray elems (mkAtom sep)⟩ def SepArray.ofElemsUsingRef [Monad m] [MonadRef m] {sep} (elems : Array Syntax) : m (SepArray sep) := do let ref ← getRef; return ⟨mkSepArray elems (mkAtomFrom ref sep)⟩ instance (sep) : Coe (Array Syntax) (SepArray sep) where coe := SepArray.ofElems /-- Create syntax representing a Lean term application, but avoid degenerate empty applications. -/ def mkApp (fn : Syntax) : (args : Array Syntax) → Syntax | #[] => fn | args => Syntax.node `Lean.Parser.Term.app #[fn, mkNullNode args] def mkCApp (fn : Name) (args : Array Syntax) : Syntax := mkApp (mkCIdent fn) args def mkLit (kind : SyntaxNodeKind) (val : String) (info := SourceInfo.none) : Syntax := let atom : Syntax := Syntax.atom info val Syntax.node kind #[atom] def mkStrLit (val : String) (info := SourceInfo.none) : Syntax := mkLit strLitKind (String.quote val) info def mkNumLit (val : String) (info := SourceInfo.none) : Syntax := mkLit numLitKind val info def mkScientificLit (val : String) (info := SourceInfo.none) : Syntax := mkLit scientificLitKind val info def mkNameLit (val : String) (info := SourceInfo.none) : Syntax := mkLit nameLitKind val info /- Recall that we don't have special Syntax constructors for storing numeric and string atoms. The idea is to have an extensible approach where embedded DSLs may have new kind of atoms and/or different ways of representing them. So, our atoms contain just the parsed string. The main Lean parser uses the kind `numLitKind` for storing natural numbers that can be encoded in binary, octal, decimal and hexadecimal format. `isNatLit` implements a "decoder" for Syntax objects representing these numerals. -/ private partial def decodeBinLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else let c := s.get i if c == '0' then decodeBinLitAux s (s.next i) (2*val) else if c == '1' then decodeBinLitAux s (s.next i) (2*val + 1) else none private partial def decodeOctalLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else let c := s.get i if '0' ≤ c && c ≤ '7' then decodeOctalLitAux s (s.next i) (8*val + c.toNat - '0'.toNat) else none private def decodeHexDigit (s : String) (i : String.Pos) : Option (Nat × String.Pos) := let c := s.get i let i := s.next i if '0' ≤ c && c ≤ '9' then some (c.toNat - '0'.toNat, i) else if 'a' ≤ c && c ≤ 'f' then some (10 + c.toNat - 'a'.toNat, i) else if 'A' ≤ c && c ≤ 'F' then some (10 + c.toNat - 'A'.toNat, i) else none private partial def decodeHexLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else match decodeHexDigit s i with | some (d, i) => decodeHexLitAux s i (16*val + d) | none => none private partial def decodeDecimalLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else let c := s.get i if '0' ≤ c && c ≤ '9' then decodeDecimalLitAux s (s.next i) (10*val + c.toNat - '0'.toNat) else none def decodeNatLitVal? (s : String) : Option Nat := let len := s.length if len == 0 then none else let c := s.get 0 if c == '0' then if len == 1 then some 0 else let c := s.get 1 if c == 'x' || c == 'X' then decodeHexLitAux s 2 0 else if c == 'b' || c == 'B' then decodeBinLitAux s 2 0 else if c == 'o' || c == 'O' then decodeOctalLitAux s 2 0 else if c.isDigit then decodeDecimalLitAux s 0 0 else none else if c.isDigit then decodeDecimalLitAux s 0 0 else none def isLit? (litKind : SyntaxNodeKind) (stx : Syntax) : Option String := match stx with | Syntax.node k args => if k == litKind && args.size == 1 then match args.get! 0 with | (Syntax.atom _ val) => some val | _ => none else none | _ => none private def isNatLitAux (litKind : SyntaxNodeKind) (stx : Syntax) : Option Nat := match isLit? litKind stx with | some val => decodeNatLitVal? val | _ => none def isNatLit? (s : Syntax) : Option Nat := isNatLitAux numLitKind s def isFieldIdx? (s : Syntax) : Option Nat := isNatLitAux fieldIdxKind s partial def decodeScientificLitVal? (s : String) : Option (Nat × Bool × Nat) := let len := s.length if len == 0 then none else let c := s.get 0 if c.isDigit then decode 0 0 else none where decodeAfterExp (i : String.Pos) (val : Nat) (e : Nat) (sign : Bool) (exp : Nat) : Option (Nat × Bool × Nat) := if s.atEnd i then if sign then some (val, sign, exp + e) else if exp >= e then some (val, sign, exp - e) else some (val, true, e - exp) else let c := s.get i if '0' ≤ c && c ≤ '9' then decodeAfterExp (s.next i) val e sign (10*exp + c.toNat - '0'.toNat) else none decodeExp (i : String.Pos) (val : Nat) (e : Nat) : Option (Nat × Bool × Nat) := let c := s.get i if c == '-' then decodeAfterExp (s.next i) val e true 0 else decodeAfterExp i val e false 0 decodeAfterDot (i : String.Pos) (val : Nat) (e : Nat) : Option (Nat × Bool × Nat) := if s.atEnd i then some (val, true, e) else let c := s.get i if '0' ≤ c && c ≤ '9' then decodeAfterDot (s.next i) (10*val + c.toNat - '0'.toNat) (e+1) else if c == 'e' || c == 'E' then decodeExp (s.next i) val e else none decode (i : String.Pos) (val : Nat) : Option (Nat × Bool × Nat) := if s.atEnd i then none else let c := s.get i if '0' ≤ c && c ≤ '9' then decode (s.next i) (10*val + c.toNat - '0'.toNat) else if c == '.' then decodeAfterDot (s.next i) val 0 else if c == 'e' || c == 'E' then decodeExp (s.next i) val 0 else none def isScientificLit? (stx : Syntax) : Option (Nat × Bool × Nat) := match isLit? scientificLitKind stx with | some val => decodeScientificLitVal? val | _ => none def isIdOrAtom? : Syntax → Option String | Syntax.atom _ val => some val | Syntax.ident _ rawVal _ _ => some rawVal.toString | _ => none def toNat (stx : Syntax) : Nat := match stx.isNatLit? with | some val => val | none => 0 def decodeQuotedChar (s : String) (i : String.Pos) : Option (Char × String.Pos) := OptionM.run do let c := s.get i let i := s.next i if c == '\\' then pure ('\\', i) else if c = '\"' then pure ('\"', i) else if c = '\'' then pure ('\'', i) else if c = 'r' then pure ('\r', i) else if c = 'n' then pure ('\n', i) else if c = 't' then pure ('\t', i) else if c = 'x' then let (d₁, i) ← decodeHexDigit s i let (d₂, i) ← decodeHexDigit s i pure (Char.ofNat (16*d₁ + d₂), i) else if c = 'u' then do let (d₁, i) ← decodeHexDigit s i let (d₂, i) ← decodeHexDigit s i let (d₃, i) ← decodeHexDigit s i let (d₄, i) ← decodeHexDigit s i pure (Char.ofNat (16*(16*(16*d₁ + d₂) + d₃) + d₄), i) else none partial def decodeStrLitAux (s : String) (i : String.Pos) (acc : String) : Option String := OptionM.run do let c := s.get i let i := s.next i if c == '\"' then pure acc else if s.atEnd i then none else if c == '\\' then do let (c, i) ← decodeQuotedChar s i decodeStrLitAux s i (acc.push c) else decodeStrLitAux s i (acc.push c) def decodeStrLit (s : String) : Option String := decodeStrLitAux s 1 "" def isStrLit? (stx : Syntax) : Option String := match isLit? strLitKind stx with | some val => decodeStrLit val | _ => none def decodeCharLit (s : String) : Option Char := OptionM.run do let c := s.get 1 if c == '\\' then do let (c, _) ← decodeQuotedChar s 2 pure c else pure c def isCharLit? (stx : Syntax) : Option Char := match isLit? charLitKind stx with | some val => decodeCharLit val | _ => none private partial def decodeNameLitAux (s : String) (i : Nat) (r : Name) : Option Name := OptionM.run do let continue? (i : Nat) (r : Name) : OptionM Name := if s.get i == '.' then decodeNameLitAux s (s.next i) r else if s.atEnd i then pure r else none let curr := s.get i if isIdBeginEscape curr then let startPart := s.next i let stopPart := s.nextUntil isIdEndEscape startPart if !isIdEndEscape (s.get stopPart) then none else continue? (s.next stopPart) (Name.mkStr r (s.extract startPart stopPart)) else if isIdFirst curr then let startPart := i let stopPart := s.nextWhile isIdRest startPart continue? stopPart (Name.mkStr r (s.extract startPart stopPart)) else none def decodeNameLit (s : String) : Option Name := if s.get 0 == '`' then decodeNameLitAux s 1 Name.anonymous else none def isNameLit? (stx : Syntax) : Option Name := match isLit? nameLitKind stx with | some val => decodeNameLit val | _ => none def hasArgs : Syntax → Bool | Syntax.node _ args => args.size > 0 | _ => false def isAtom : Syntax → Bool | atom _ _ => true | _ => false def isToken (token : String) : Syntax → Bool | atom _ val => val.trim == token.trim | _ => false def isNone (stx : Syntax) : Bool := match stx with | Syntax.node k args => k == nullKind && args.size == 0 -- when elaborating partial syntax trees, it's reasonable to interpret missing parts as `none` | Syntax.missing => true | _ => false def getOptional? (stx : Syntax) : Option Syntax := match stx with | Syntax.node k args => if k == nullKind && args.size == 1 then some (args.get! 0) else none | _ => none def getOptionalIdent? (stx : Syntax) : Option Name := match stx.getOptional? with | some stx => some stx.getId | none => none partial def findAux (p : Syntax → Bool) : Syntax → Option Syntax | stx@(Syntax.node _ args) => if p stx then some stx else args.findSome? (findAux p) | stx => if p stx then some stx else none def find? (stx : Syntax) (p : Syntax → Bool) : Option Syntax := findAux p stx end Syntax /-- Reflect a runtime datum back to surface syntax (best-effort). -/ class Quote (α : Type) where quote : α → Syntax export Quote (quote) instance : Quote Syntax := ⟨id⟩ instance : Quote Bool := ⟨fun | true => mkCIdent `Bool.true | false => mkCIdent `Bool.false⟩ instance : Quote String := ⟨Syntax.mkStrLit⟩ instance : Quote Nat := ⟨fun n => Syntax.mkNumLit <| toString n⟩ instance : Quote Substring := ⟨fun s => Syntax.mkCApp `String.toSubstring #[quote s.toString]⟩ -- in contrast to `Name.toString`, we can, and want to be, precise here private def getEscapedNameParts? (acc : List String) : Name → OptionM (List String) | Name.anonymous => acc | Name.str n s _ => do let s ← Name.escapePart s getEscapedNameParts? (s::acc) n | Name.num n i _ => none private def quoteNameMk : Name → Syntax | Name.anonymous => mkCIdent ``Name.anonymous | Name.str n s _ => Syntax.mkCApp ``Name.mkStr #[quoteNameMk n, quote s] | Name.num n i _ => Syntax.mkCApp ``Name.mkNum #[quoteNameMk n, quote i] instance : Quote Name where quote n := match getEscapedNameParts? [] n with | some ss => mkNode `Lean.Parser.Term.quotedName #[Syntax.mkNameLit ("`" ++ ".".intercalate ss)] | none => quoteNameMk n instance {α β : Type} [Quote α] [Quote β] : Quote (α × β) where quote | ⟨a, b⟩ => Syntax.mkCApp ``Prod.mk #[quote a, quote b] private def quoteList {α : Type} [Quote α] : List α → Syntax | [] => mkCIdent ``List.nil | (x::xs) => Syntax.mkCApp ``List.cons #[quote x, quoteList xs] instance {α : Type} [Quote α] : Quote (List α) where quote := quoteList instance {α : Type} [Quote α] : Quote (Array α) where quote xs := Syntax.mkCApp ``List.toArray #[quote xs.toList] private def quoteOption {α : Type} [Quote α] : Option α → Syntax | none => mkIdent ``none | (some x) => Syntax.mkCApp ``some #[quote x] instance Option.hasQuote {α : Type} [Quote α] : Quote (Option α) where quote := quoteOption /- Evaluator for `prec` DSL -/ def evalPrec (stx : Syntax) : MacroM Nat := Macro.withIncRecDepth stx do let stx ← expandMacros stx match stx with | `(prec| $num:numLit) => return num.isNatLit?.getD 0 | _ => Macro.throwErrorAt stx "unexpected precedence" macro_rules | `(prec| $a + $b) => do `(prec| $(quote <| (← evalPrec a) + (← evalPrec b)):numLit) macro_rules | `(prec| $a - $b) => do `(prec| $(quote <| (← evalPrec a) - (← evalPrec b)):numLit) macro "eval_prec " p:prec:max : term => return quote (← evalPrec p) def evalOptPrec : Option Syntax → MacroM Nat | some prec => evalPrec prec | none => return 0 /- Evaluator for `prio` DSL -/ def evalPrio (stx : Syntax) : MacroM Nat := Macro.withIncRecDepth stx do let stx ← expandMacros stx match stx with | `(prio| $num:numLit) => return num.isNatLit?.getD 0 | _ => Macro.throwErrorAt stx "unexpected priority" macro_rules | `(prio| $a + $b) => do `(prio| $(quote <| (← evalPrio a) + (← evalPrio b)):numLit) macro_rules | `(prio| $a - $b) => do `(prio| $(quote <| (← evalPrio a) - (← evalPrio b)):numLit) macro "eval_prio " p:prio:max : term => return quote (← evalPrio p) def evalOptPrio : Option Syntax → MacroM Nat | some prio => evalPrio prio | none => return eval_prio default end Lean namespace Array abbrev getSepElems := @getEvenElems open Lean private partial def filterSepElemsMAux {m : Type → Type} [Monad m] (a : Array Syntax) (p : Syntax → m Bool) (i : Nat) (acc : Array Syntax) : m (Array Syntax) := do if h : i < a.size then let stx := a.get ⟨i, h⟩ if (← p stx) then if acc.isEmpty then filterSepElemsMAux a p (i+2) (acc.push stx) else if hz : i ≠ 0 then have : i.pred < i := Nat.predLt hz let sepStx := a.get ⟨i.pred, Nat.ltTrans this h⟩ filterSepElemsMAux a p (i+2) ((acc.push sepStx).push stx) else filterSepElemsMAux a p (i+2) (acc.push stx) else filterSepElemsMAux a p (i+2) acc else pure acc def filterSepElemsM {m : Type → Type} [Monad m] (a : Array Syntax) (p : Syntax → m Bool) : m (Array Syntax) := filterSepElemsMAux a p 0 #[] def filterSepElems (a : Array Syntax) (p : Syntax → Bool) : Array Syntax := Id.run <| a.filterSepElemsM p private partial def mapSepElemsMAux {m : Type → Type} [Monad m] (a : Array Syntax) (f : Syntax → m Syntax) (i : Nat) (acc : Array Syntax) : m (Array Syntax) := do if h : i < a.size then let stx := a.get ⟨i, h⟩ if i % 2 == 0 then do let stx ← f stx mapSepElemsMAux a f (i+1) (acc.push stx) else mapSepElemsMAux a f (i+1) (acc.push stx) else pure acc def mapSepElemsM {m : Type → Type} [Monad m] (a : Array Syntax) (f : Syntax → m Syntax) : m (Array Syntax) := mapSepElemsMAux a f 0 #[] def mapSepElems (a : Array Syntax) (f : Syntax → Syntax) : Array Syntax := Id.run <| a.mapSepElemsM f end Array namespace Lean.Syntax.SepArray def getElems {sep} (sa : SepArray sep) : Array Syntax := sa.elemsAndSeps.getSepElems /- We use `CoeTail` here instead of `Coe` to avoid a "loop" when computing `CoeTC`. The "loop" is interrupted using the maximum instance size threshold, but it is a performance bottleneck. The loop occurs because the predicate `isNewAnswer` is too imprecise. -/ instance (sep) : CoeTail (SepArray sep) (Array Syntax) where coe := getElems end Lean.Syntax.SepArray /-- Gadget for automatic parameter support. This is similar to the `optParam` gadget, but it uses the given tactic. Like `optParam`, this gadget only affects elaboration. For example, the tactic will *not* be invoked during type class resolution. -/ abbrev autoParam.{u} (α : Sort u) (tactic : Lean.Syntax) : Sort u := α /- Helper functions for manipulating interpolated strings -/ namespace Lean.Syntax private def decodeInterpStrQuotedChar (s : String) (i : String.Pos) : Option (Char × String.Pos) := OptionM.run do match decodeQuotedChar s i with | some r => some r | none => let c := s.get i let i := s.next i if c == '{' then pure ('{', i) else none private partial def decodeInterpStrLit (s : String) : Option String := let rec loop (i : String.Pos) (acc : String) : OptionM String := let c := s.get i let i := s.next i if c == '\"' || c == '{' then pure acc else if s.atEnd i then none else if c == '\\' then do let (c, i) ← decodeInterpStrQuotedChar s i loop i (acc.push c) else loop i (acc.push c) loop 1 "" partial def isInterpolatedStrLit? (stx : Syntax) : Option String := match isLit? interpolatedStrLitKind stx with | none => none | some val => decodeInterpStrLit val def expandInterpolatedStrChunks (chunks : Array Syntax) (mkAppend : Syntax → Syntax → MacroM Syntax) (mkElem : Syntax → MacroM Syntax) : MacroM Syntax := do let mut i := 0 let mut result := Syntax.missing for elem in chunks do let elem ← match elem.isInterpolatedStrLit? with | none => mkElem elem | some str => mkElem (Syntax.mkStrLit str) if i == 0 then result := elem else result ← mkAppend result elem i := i+1 return result def expandInterpolatedStr (interpStr : Syntax) (type : Syntax) (toTypeFn : Syntax) : MacroM Syntax := do let ref := interpStr let r ← expandInterpolatedStrChunks interpStr.getArgs (fun a b => `($a ++ $b)) (fun a => `($toTypeFn $a)) `(($r : $type)) def getSepArgs (stx : Syntax) : Array Syntax := stx.getArgs.getSepElems end Syntax namespace Meta.Simp def defaultMaxSteps := 100000 structure Config where maxSteps : Nat := defaultMaxSteps maxDischargeDepth : Nat := 2 contextual : Bool := false memoize : Bool := true singlePass : Bool := false zeta : Bool := true beta : Bool := true eta : Bool := true iota : Bool := true proj : Bool := true ctorEq : Bool := true decide : Bool := true deriving Inhabited, BEq, Repr -- Configuration object for `simp_all` structure ConfigCtx extends Config where contextual := true end Meta.Simp end Lean
41a62bae4f6ee768eb618e2d19b547b7d23721e0
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/deprecated/subfield.lean
8f7c3cd5207f9fb5471749c184c30d4bd875524d
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,470
lean
/- Copyright (c) 2018 Andreas Swerdlow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andreas Swerdlow -/ import deprecated.subring import algebra.group_with_zero.power variables {F : Type*} [field F] (S : set F) class is_subfield extends is_subring S : Prop := (inv_mem : ∀ {x : F}, x ∈ S → x⁻¹ ∈ S) lemma is_subfield.div_mem {S : set F} [is_subfield S] {x y : F} (hx : x ∈ S) (hy : y ∈ S) : x / y ∈ S := by { rw div_eq_mul_inv, exact is_submonoid.mul_mem hx (is_subfield.inv_mem hy) } instance is_subfield.field [is_subfield S] : field S := by letI cr_inst : comm_ring S := subset.comm_ring; exact { inv := λ x, ⟨x⁻¹, is_subfield.inv_mem x.2⟩, div := λ x y, ⟨x / y, is_subfield.div_mem x.2 y.2⟩, div_eq_mul_inv := λ x y, subtype.ext $ div_eq_mul_inv (x : F) y, exists_pair_ne := ⟨0, 1, λ h, zero_ne_one (subtype.ext_iff_val.1 h)⟩, mul_inv_cancel := λ a ha, subtype.ext_iff_val.2 (mul_inv_cancel (λ h, ha $ subtype.ext_iff_val.2 h)), inv_zero := subtype.ext_iff_val.2 inv_zero, .. cr_inst } lemma is_subfield.pow_mem {a : F} {n : ℤ} {s : set F} [is_subfield s] (h : a ∈ s) : a ^ n ∈ s := begin cases n, { exact is_submonoid.pow_mem h }, { exact is_subfield.inv_mem (is_submonoid.pow_mem h) }, end instance univ.is_subfield : is_subfield (@set.univ F) := { inv_mem := by intros; trivial } /- note: in the next two declarations, if we let type-class inference figure out the instance `ring_hom.is_subring_preimage` then that instance only applies when particular instances of `is_add_subgroup _` and `is_submonoid _` are chosen (which are not the default ones). If we specify it explicitly, then it doesn't complain. -/ instance preimage.is_subfield {K : Type*} [field K] (f : F →+* K) (s : set K) [is_subfield s] : is_subfield (f ⁻¹' s) := { inv_mem := λ a (ha : f a ∈ s), show f a⁻¹ ∈ s, by { rw [f.map_inv], exact is_subfield.inv_mem ha }, ..f.is_subring_preimage s } instance image.is_subfield {K : Type*} [field K] (f : F →+* K) (s : set F) [is_subfield s] : is_subfield (f '' s) := { inv_mem := λ a ⟨x, xmem, ha⟩, ⟨x⁻¹, is_subfield.inv_mem xmem, ha ▸ f.map_inv _⟩, ..f.is_subring_image s } instance range.is_subfield {K : Type*} [field K] (f : F →+* K) : is_subfield (set.range f) := by { rw ← set.image_univ, apply_instance } namespace field /-- `field.closure s` is the minimal subfield that includes `s`. -/ def closure : set F := { x | ∃ y ∈ ring.closure S, ∃ z ∈ ring.closure S, y / z = x } variables {S} theorem ring_closure_subset : ring.closure S ⊆ closure S := λ x hx, ⟨x, hx, 1, is_submonoid.one_mem, div_one x⟩ instance closure.is_submonoid : is_submonoid (closure S) := { mul_mem := by rintros _ _ ⟨p, hp, q, hq, hq0, rfl⟩ ⟨r, hr, s, hs, hs0, rfl⟩; exact ⟨p * r, is_submonoid.mul_mem hp hr, q * s, is_submonoid.mul_mem hq hs, (div_mul_div _ _ _ _).symm⟩, one_mem := ring_closure_subset $ is_submonoid.one_mem } instance closure.is_subfield : is_subfield (closure S) := have h0 : (0:F) ∈ closure S, from ring_closure_subset $ is_add_submonoid.zero_mem, { add_mem := begin intros a b ha hb, rcases (id ha) with ⟨p, hp, q, hq, rfl⟩, rcases (id hb) with ⟨r, hr, s, hs, rfl⟩, classical, by_cases hq0 : q = 0, by simp [hb, hq0], by_cases hs0 : s = 0, by simp [ha, hs0], exact ⟨p * s + q * r, is_add_submonoid.add_mem (is_submonoid.mul_mem hp hs) (is_submonoid.mul_mem hq hr), q * s, is_submonoid.mul_mem hq hs, (div_add_div p r hq0 hs0).symm⟩ end, zero_mem := h0, neg_mem := begin rintros _ ⟨p, hp, q, hq, rfl⟩, exact ⟨-p, is_add_subgroup.neg_mem hp, q, hq, neg_div q p⟩ end, inv_mem := begin rintros _ ⟨p, hp, q, hq, rfl⟩, classical, by_cases hp0 : p = 0, by simp [hp0, h0], exact ⟨q, hq, p, hp, inv_div.symm⟩ end } theorem mem_closure {a : F} (ha : a ∈ S) : a ∈ closure S := ring_closure_subset $ ring.mem_closure ha theorem subset_closure : S ⊆ closure S := λ _, mem_closure theorem closure_subset {T : set F} [is_subfield T] (H : S ⊆ T) : closure S ⊆ T := by rintros _ ⟨p, hp, q, hq, hq0, rfl⟩; exact is_subfield.div_mem (ring.closure_subset H hp) (ring.closure_subset H hq) theorem closure_subset_iff (s t : set F) [is_subfield t] : closure s ⊆ t ↔ s ⊆ t := ⟨set.subset.trans subset_closure, closure_subset⟩ theorem closure_mono {s t : set F} (H : s ⊆ t) : closure s ⊆ closure t := closure_subset $ set.subset.trans H subset_closure end field lemma is_subfield_Union_of_directed {ι : Type*} [hι : nonempty ι] (s : ι → set F) [∀ i, is_subfield (s i)] (directed : ∀ i j, ∃ k, s i ⊆ s k ∧ s j ⊆ s k) : is_subfield (⋃i, s i) := { inv_mem := λ x hx, let ⟨i, hi⟩ := set.mem_Union.1 hx in set.mem_Union.2 ⟨i, is_subfield.inv_mem hi⟩, to_is_subring := is_subring_Union_of_directed s directed } instance is_subfield.inter (S₁ S₂ : set F) [is_subfield S₁] [is_subfield S₂] : is_subfield (S₁ ∩ S₂) := { inv_mem := λ x hx, ⟨is_subfield.inv_mem hx.1, is_subfield.inv_mem hx.2⟩ } instance is_subfield.Inter {ι : Sort*} (S : ι → set F) [h : ∀ y : ι, is_subfield (S y)] : is_subfield (set.Inter S) := { inv_mem := λ x hx, set.mem_Inter.2 $ λ y, is_subfield.inv_mem $ set.mem_Inter.1 hx y }
7a0eb3ed5487736f092f7fa7c699a689d99997c2
c777c32c8e484e195053731103c5e52af26a25d1
/src/topology/covering.lean
58f758a2ee4edd9811f162b82920a100092357a5
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
7,175
lean
/- Copyright (c) 2022 Thomas Browning. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning -/ import topology.is_locally_homeomorph import topology.fiber_bundle.basic /-! # Covering Maps > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines covering maps. ## Main definitions * `is_evenly_covered f x I`: A point `x` is evenly coverd by `f : E → X` with fiber `I` if `I` is discrete and there is a `trivialization` of `f` at `x` with fiber `I`. * `is_covering_map f`: A function `f : E → X` is a covering map if every point `x` is evenly covered by `f` with fiber `f ⁻¹' {x}`. The fibers `f ⁻¹' {x}` must be discrete, but if `X` is not connected, then the fibers `f ⁻¹' {x}` are not necessarily isomorphic. Also, `f` is not assumed to be surjective, so the fibers are even allowed to be empty. -/ open_locale bundle variables {E X : Type*} [topological_space E] [topological_space X] (f : E → X) (s : set X) /-- A point `x : X` is evenly covered by `f : E → X` if `x` has an evenly covered neighborhood. -/ def is_evenly_covered (x : X) (I : Type*) [topological_space I] := discrete_topology I ∧ ∃ t : trivialization I f, x ∈ t.base_set namespace is_evenly_covered variables {f} /-- If `x` is evenly covered by `f`, then we can construct a trivialization of `f` at `x`. -/ noncomputable def to_trivialization {x : X} {I : Type*} [topological_space I] (h : is_evenly_covered f x I) : trivialization (f ⁻¹' {x}) f := (classical.some h.2).trans_fiber_homeomorph ((classical.some h.2).preimage_singleton_homeomorph (classical.some_spec h.2)).symm lemma mem_to_trivialization_base_set {x : X} {I : Type*} [topological_space I] (h : is_evenly_covered f x I) : x ∈ h.to_trivialization.base_set := classical.some_spec h.2 lemma to_trivialization_apply {x : E} {I : Type*} [topological_space I] (h : is_evenly_covered f (f x) I) : (h.to_trivialization x).2 = ⟨x, rfl⟩ := let e := classical.some h.2, h := classical.some_spec h.2, he := e.mk_proj_snd' h in subtype.ext ((e.to_local_equiv.eq_symm_apply (e.mem_source.mpr h) (by rwa [he, e.mem_target, e.coe_fst (e.mem_source.mpr h)])).mpr he.symm).symm protected lemma continuous_at {x : E} {I : Type*} [topological_space I] (h : is_evenly_covered f (f x) I) : continuous_at f x := let e := h.to_trivialization in e.continuous_at_proj (e.mem_source.mpr (mem_to_trivialization_base_set h)) lemma to_is_evenly_covered_preimage {x : X} {I : Type*} [topological_space I] (h : is_evenly_covered f x I) : is_evenly_covered f x (f ⁻¹' {x}) := let ⟨h1, h2⟩ := h in by exactI ⟨((classical.some h2).preimage_singleton_homeomorph (classical.some_spec h2)).embedding.discrete_topology, _, h.mem_to_trivialization_base_set⟩ end is_evenly_covered /-- A covering map is a continuous function `f : E → X` with discrete fibers such that each point of `X` has an evenly covered neighborhood. -/ def is_covering_map_on := ∀ x ∈ s, is_evenly_covered f x (f ⁻¹' {x}) namespace is_covering_map_on lemma mk (F : X → Type*) [Π x, topological_space (F x)] [hF : Π x, discrete_topology (F x)] (e : Π x ∈ s, trivialization (F x) f) (h : ∀ (x : X) (hx : x ∈ s), x ∈ (e x hx).base_set) : is_covering_map_on f s := λ x hx, is_evenly_covered.to_is_evenly_covered_preimage ⟨hF x, e x hx, h x hx⟩ variables {f} {s} protected lemma continuous_at (hf : is_covering_map_on f s) {x : E} (hx : f x ∈ s) : continuous_at f x := (hf (f x) hx).continuous_at protected lemma continuous_on (hf : is_covering_map_on f s) : continuous_on f (f ⁻¹' s) := continuous_at.continuous_on (λ x, hf.continuous_at) protected lemma is_locally_homeomorph_on (hf : is_covering_map_on f s) : is_locally_homeomorph_on f (f ⁻¹' s) := begin refine is_locally_homeomorph_on.mk f (f ⁻¹' s) (λ x hx, _), let e := (hf (f x) hx).to_trivialization, have h := (hf (f x) hx).mem_to_trivialization_base_set, let he := e.mem_source.2 h, refine ⟨e.to_local_homeomorph.trans { to_fun := λ p, p.1, inv_fun := λ p, ⟨p, x, rfl⟩, source := e.base_set ×ˢ ({⟨x, rfl⟩} : set (f ⁻¹' {f x})), target := e.base_set, open_source := e.open_base_set.prod (singletons_open_iff_discrete.2 (hf (f x) hx).1 ⟨x, rfl⟩), open_target := e.open_base_set, map_source' := λ p, and.left, map_target' := λ p hp, ⟨hp, rfl⟩, left_inv' := λ p hp, prod.ext rfl hp.2.symm, right_inv' := λ p hp, rfl, continuous_to_fun := continuous_fst.continuous_on, continuous_inv_fun := (continuous_id'.prod_mk continuous_const).continuous_on }, ⟨he, by rwa [e.to_local_homeomorph.symm_symm, e.proj_to_fun x he], (hf (f x) hx).to_trivialization_apply⟩, λ p h, (e.proj_to_fun p h.1).symm⟩, end end is_covering_map_on /-- A covering map is a continuous function `f : E → X` with discrete fibers such that each point of `X` has an evenly covered neighborhood. -/ def is_covering_map := ∀ x, is_evenly_covered f x (f ⁻¹' {x}) variables {f} lemma is_covering_map_iff_is_covering_map_on_univ : is_covering_map f ↔ is_covering_map_on f set.univ := by simp only [is_covering_map, is_covering_map_on, set.mem_univ, forall_true_left] protected lemma is_covering_map.is_covering_map_on (hf : is_covering_map f) : is_covering_map_on f set.univ := is_covering_map_iff_is_covering_map_on_univ.mp hf variables (f) namespace is_covering_map lemma mk (F : X → Type*) [Π x, topological_space (F x)] [hF : Π x, discrete_topology (F x)] (e : Π x, trivialization (F x) f) (h : ∀ x, x ∈ (e x).base_set) : is_covering_map f := is_covering_map_iff_is_covering_map_on_univ.mpr (is_covering_map_on.mk f set.univ F (λ x hx, e x) (λ x hx, h x)) variables {f} protected lemma continuous (hf : is_covering_map f) : continuous f := continuous_iff_continuous_on_univ.mpr hf.is_covering_map_on.continuous_on protected lemma is_locally_homeomorph (hf : is_covering_map f) : is_locally_homeomorph f := is_locally_homeomorph_iff_is_locally_homeomorph_on_univ.mpr hf.is_covering_map_on.is_locally_homeomorph_on protected lemma is_open_map (hf : is_covering_map f) : is_open_map f := hf.is_locally_homeomorph.is_open_map protected lemma quotient_map (hf : is_covering_map f) (hf' : function.surjective f) : quotient_map f := hf.is_open_map.to_quotient_map hf.continuous hf' end is_covering_map variables {f} protected lemma is_fiber_bundle.is_covering_map {F : Type*} [topological_space F] [discrete_topology F] (hf : ∀ x : X, ∃ e : trivialization F f, x ∈ e.base_set) : is_covering_map f := is_covering_map.mk f (λ x, F) (λ x, classical.some (hf x)) (λ x, classical.some_spec (hf x)) protected lemma fiber_bundle.is_covering_map {F : Type*} {E : X → Type*} [topological_space F] [discrete_topology F] [topological_space (bundle.total_space E)] [Π x, topological_space (E x)] [hf : fiber_bundle F E] : is_covering_map (π E) := is_fiber_bundle.is_covering_map (λ x, ⟨trivialization_at F E x, mem_base_set_trivialization_at F E x ⟩)
d53e00c848b70e89d8b375a9ab20f6e9b2237ca1
2bafba05c98c1107866b39609d15e849a4ca2bb8
/src/week_8/Part_B_H0.lean
a6638a05bffcd247188145ca253cd8d0e4f7dd94
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/formalising-mathematics
b54c83c94b5c315024ff09997fcd6b303892a749
7cf1d51c27e2038d2804561d63c74711924044a1
refs/heads/master
1,651,267,046,302
1,638,888,459,000
1,638,888,459,000
331,592,375
284
24
Apache-2.0
1,669,593,705,000
1,611,224,849,000
Lean
UTF-8
Lean
false
false
9,700
lean
import week_8.Part_A_G_modules /- # Making the API for H⁰(G,M) If G is a group and M is a G-module then H⁰(G,M), or `H0 G M`, is the abelian group of G-invariant elements of `M`. We make the definition so we have to make the interface too. We show that `H0 G M` is an abelian group, define a coercion to `M` sending `m` to `↑m`, and define `m.spec` to be the statement that `↑m` is G-invariant. Let's start by giving a preliminary definition of H⁰ as an additive subgroup of `M`. -/ open set /-- `H0 G M` is the type of G-invariant elements of M. -/ def H0_subgroup (G M : Type) [monoid G] [add_comm_group M] [distrib_mul_action G M] : add_subgroup M := { carrier := {m | ∀ g : G, g • m = m }, -- Need to check it's a subgroup. -- Axiom 1: zero in ("closed under `0`") zero_mem' := begin -- you can start with this rw mem_set_of_eq, -- says that `a ∈ { x | p x}` is the same as `p a`. -- can you take it from there? sorry end, -- Axiom 2 : closed under `+` add_mem' := begin intros a b ha hb g, rw mem_set_of_eq at *, -- that's how I'd start sorry, end, -- Axiom 3 : closed under `-` neg_mem' := begin sorry end } /- This makes `H0_subgroup G M`, a term (an additive subgroup of `M`, and hence a term of type `add_subgroup M`). But this is no good -- we want to consider functions `H⁰(G,M) → H⁰(G,N)` so we need a *type* `H0 G M`. We need to promote the term to a type. We do this by using Lean's theory of subtypes, with notation `{ x // P x }` (a type) as oppposed to the set-theoretic `{ x | P x }` (a term) -/ /-- Group cohomology `H⁰(G,M)` as a type. -/ def H0 (G M : Type) [monoid G] [add_comm_group M] [distrib_mul_action G M] : Type := {m : M // ∀ g : G, g • m = m } -- let's make an API and prove stuff about `H0 G M` in the `H0` namespace. namespace H0 -- let `G` be a group (or a monoid) and let `M` be a `G`-module. variables {G M : Type} [monoid G] [add_comm_group M] [distrib_mul_action G M] /- We have defined `H0 G M` to be a type, a so-called subtype of `M`, but a type in its own right. It has terms of its own (unlike `S : set M` or `A : sub_distrib_mul_action M`) So how does this work? A term `m` of type `H0 G M` is a *package* consisting of a term `m.1 : M` and a proof `m.2 : ∀ g, g • m.1 = m.1`. We do not want to use these internal computer science terms for this package of information, we want a nice interface. Below we use coercion, to turn a term `m : H0 G M` into a term `↑m : M`. -/ /-- set up coercion from `H⁰(G,M) to M`, sending `m` to `↑m` -/ instance : has_coe (H0 G M) M := -- this is the last time we see `m.1` ⟨λ m, m.1⟩ -- That's a definition, so we need to make a little API. /-- If `a : M` then `↑⟨a, ha⟩ = a` -/ @[simp] lemma coe_def (a : M) (ha : ∀(g : G), g • a = a) : ((⟨a, ha⟩ : H0 G M) : M) = a := rfl -- this is our nice interface lemma spec (m : H0 G M) : ∀ (g : G), g • (m : M) = m := -- this is the last time we see `m.2` m.2 /- The idea now is that we should avoid `m.1` and `m.2` completely, and use `m : M` or `↑m` for the element of the module, and `m.spec` for the proof that it is `G`-invariant. ## Basic Infrastructure We have made a new definition, `H0`, and now we need to make it easier to use. Things we do here: * We want to get (for free) that `H0 G M` is a group (so we need to put this fact into the type class mechanism). * We want to know that two terms of type `H0 G M` are equal if and only if the corresponding terms of type `M` are equal (so we want to prove an extensionality lemma). * We want to know that things like 0 and addition coincide in `M` and `H0 G M` (the coercion is a group homomorphism) Let's start by making H⁰(G, M) a.k.a. `H0 G M` into a group. This is easy because `H0 G M` is the type corresponding to the term `H0_subgroup G M` which is a subgroup, hence a group. -/ -- tell type class inference that `H0 G M` is a group instance : add_comm_group (H0 G M) := add_subgroup.to_add_comm_group (H0_subgroup G M) -- Let's now prove an ext_iff lemma (useful for rewriting) lemma ext_iff (m₁ m₂ : H0 G M) : m₁ = m₂ ↔ (m₁ : M) = (m₂ : M) := begin split, { -- one way uses a rewrite rintro rfl, refl }, { -- the other way is just set extensionality ext } end -- Let's tell the simplifier how the group structure (addition, 0, negation -- and subtraction) works with respect to the coercion. All the proofs -- are true by definition @[simp] lemma coe_add (a b : H0 G M) : ((a + b : H0 G M) : M) = a + b := begin -- true by definition refl end @[simp] lemma coe_zero : ((0 : H0 G M) : M) = 0 := rfl -- true by definition @[simp] lemma coe_neg (a : H0 G M) : ((-a : H0 G M) : M) = -a := rfl @[simp] lemma coe_sub (a b : H0 G M) : ((a - b : H0 G M) : M) = a - b := rfl -- try these example (m₁ m₂ m₃ : H0 G M) : m₁ + (m₂ - m₁ + m₃) = m₃ + m₂ := begin -- which tactic? sorry end example (g : G) (m : H0 G M) : g • (m + m : M) = m + m := begin -- can you help the simplifier? sorry end end H0 /- ## Definition of `φ.H0 : H0 G M →+ H0 G N` Now let's prove that a G-module map `φ : M →+[G] N` induces a natural abelian group hom `φ.H0 : H⁰(G,M) →+ H⁰(G,N)`. I would rather do this in `φ`'s namespace, which is `distrib_mul_action_hom`, because then I can write `φ.H0` directly. This is definitions so it's a bit messy. I left you one sorry -- prove that if `m ∈ H⁰(G,M)` then `φ(m)` is actually `G`-invariant. -/ namespace distrib_mul_action_hom variables {G M N : Type} [monoid G] [add_comm_group M] [add_comm_group N] [distrib_mul_action G M] [distrib_mul_action G N] (a : M) (b : N) -- Let's first define the group homomorphism `H0 G M →+ H0 G N` induced by `φ`. -- Recall that the constructor of `H0 G N` needs as input a pair consisting -- of `b : N` and `hb : ∀ g, g • b = b`, and we make the element of `H0 G N` -- using the `⟨b, hb⟩` notation. I am playing with the idea of -- distinguishing `n : H0 G N` and `b = ↑n` when we're taking these -- things apart explicitly. /- The function underlying the group homomorphism `H⁰(G,M) → H⁰(G,N)` induced by a `G`-equivariant group homomorphism `φ : M →+[G] N` -/ def H0_underlying_function (φ : M →+[G] N) (a : H0 G M) : H0 G N := ⟨φ a, begin -- use φ.map_smul and a.spec to prove that this map is well-defined. -- Remember that `rw` doesn't work under binders, and ∀ is a binder, so start -- with `intros`. sorry end⟩ /-- The group homomorphism `H⁰(G,M) →+ H⁰(G,N)` induced by a `G`-equivariant group homomorphism `φ : M →+[G] N` -/ def H0 (φ : M →+[G] N) : H0 G M →+ H0 G N := -- to make a group homomorphism we need apply a constructor add_monoid_hom.mk' -- to the function we just made (H0_underlying_function φ) -- and then prove that this function preserves addition. begin -- this is a bit of a mess, I'll do it. intros a b, simp only [H0_underlying_function], ext, simp, end end distrib_mul_action_hom -- The API for `φ.H0` starts here namespace H0 variables {G M N : Type} [monoid G] [add_comm_group M] [add_comm_group N] [distrib_mul_action G M] [distrib_mul_action G N] (a : M) (b : N) /- ## An API for `φ.H0` So now if `φ : M →+[G] N` is a G-module homomorphism, we can talk about `φ.H0 : H0 G M →+ H0 G N`, an abelian group homomorphism from H⁰(G,M) to H⁰(G,N). As ever, this is a definition so we need to make a little API. We start with the following handy fact: Given a G-module map `φ : M →+[G] N`, The following diagram commutes: φ M ----------------> N /\ /\ | coercion ↑ | coercion ↑ | | | | H⁰(G,M) ---------> H⁰(G,N) -/ @[simp] lemma coe_apply (m : H0 G M) (φ : M →+[G] N) : ((φ.H0 m) : N) = φ m := begin -- Look at the goal the way I have written it. -- Unfold the definitions. It's true by definition. -- Look at the goal the way Lean is displaying it -- right now. It's just coercions everywhere. Ignore them. sorry end open distrib_mul_action_hom -- If you're in to that sort of thing, you can prove that `φ.H0` -- is functorial. That's it and comp. def id_apply (m : H0 G M) : (distrib_mul_action_hom.id G).H0 m = m := begin -- remember extensionality. sorry, end variables {P : Type} [add_comm_group P] [distrib_mul_action G P] def comp (φ : M →+[G] N) (ψ : N →+[G] P) : (ψ ∘ᵍ φ).H0 = ψ.H0.comp φ.H0 := begin -- be sure to check out the proof in the solutions. sorry end end H0 /- ## First exactness result If 0 → M → N → P → 0 is a short exact sequence, then there is a long exact sequence 0 → H⁰(G,M) → H⁰(G,N) → H⁰(G,P) and we can't go any further because we haven't defined H¹! This boils down to two theorems; let's prove them. -/ open function open distrib_mul_action_hom variables {G M N P : Type} [monoid G] [add_comm_group M] [add_comm_group N] [add_comm_group P] [distrib_mul_action G M] [distrib_mul_action G N] [distrib_mul_action G P] (a : M) (b : N) -- 0 → H⁰(G,M) → H⁰(G,N) is exact, i.e. φ.H0 is injective theorem H0_hom.left_exact (φ : M →+[G] N) (hφ : injective φ) : injective φ.H0 := begin sorry end -- H⁰(G,M) → H⁰(G,N) → H⁰(G,P) is exact, i.e. an image equals a kernel. theorem H0_hom.middle_exact (φ : M →+[G] N) (ψ : N →+[G] P) (h : is_short_exact φ ψ) : φ.H0.range = ψ.H0.ker := begin sorry, end -- Do you think we should prove something weaker? I quite -- like the API we have for short exact sequences.
d726ea6cd8f75dbcad7de31774092a97687229de
c777c32c8e484e195053731103c5e52af26a25d1
/src/data/pi/interval.lean
c77e21f3ce2bd3f172af61b33df583940db44388
[ "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,629
lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.finset.locally_finite import data.fintype.big_operators /-! # Intervals in a pi type > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file shows that (dependent) functions to locally finite orders equipped with the pointwise order are locally finite and calculates the cardinality of their intervals. -/ open finset fintype open_locale big_operators variables {ι : Type*} {α : ι → Type*} namespace pi section locally_finite variables [decidable_eq ι] [fintype ι] [Π i, decidable_eq (α i)] [Π i, partial_order (α i)] [Π i, locally_finite_order (α i)] instance : locally_finite_order (Π i, α i) := locally_finite_order.of_Icc _ (λ a b, pi_finset $ λ i, Icc (a i) (b i)) (λ a b x, by simp_rw [mem_pi_finset, mem_Icc, le_def, forall_and_distrib]) variables (a b : Π i, α i) lemma Icc_eq : Icc a b = pi_finset (λ i, Icc (a i) (b i)) := rfl lemma card_Icc : (Icc a b).card = ∏ i, (Icc (a i) (b i)).card := card_pi_finset _ lemma card_Ico : (Ico a b).card = (∏ i, (Icc (a i) (b i)).card) - 1 := by rw [card_Ico_eq_card_Icc_sub_one, card_Icc] lemma card_Ioc : (Ioc a b).card = (∏ i, (Icc (a i) (b i)).card) - 1 := by rw [card_Ioc_eq_card_Icc_sub_one, card_Icc] lemma card_Ioo : (Ioo a b).card = (∏ i, (Icc (a i) (b i)).card) - 2 := by rw [card_Ioo_eq_card_Icc_sub_two, card_Icc] end locally_finite section bounded variables [decidable_eq ι] [fintype ι] [Π i, decidable_eq (α i)] [Π i, partial_order (α i)] section bot variables [Π i, locally_finite_order_bot (α i)] (b : Π i, α i) instance : locally_finite_order_bot (Π i, α i) := locally_finite_order_top.of_Iic _ (λ b, pi_finset $ λ i, Iic (b i)) (λ b x, by simp_rw [mem_pi_finset, mem_Iic, le_def]) lemma card_Iic : (Iic b).card = ∏ i, (Iic (b i)).card := card_pi_finset _ lemma card_Iio : (Iio b).card = (∏ i, (Iic (b i)).card) - 1 := by rw [card_Iio_eq_card_Iic_sub_one, card_Iic] end bot section top variables [Π i, locally_finite_order_top (α i)] (a : Π i, α i) instance : locally_finite_order_top (Π i, α i) := locally_finite_order_top.of_Ici _ (λ a, pi_finset $ λ i, Ici (a i)) (λ a x, by simp_rw [mem_pi_finset, mem_Ici, le_def]) lemma card_Ici : (Ici a).card = (∏ i, (Ici (a i)).card) := card_pi_finset _ lemma card_Ioi : (Ioi a).card = (∏ i, (Ici (a i)).card) - 1 := by rw [card_Ioi_eq_card_Ici_sub_one, card_Ici] end top end bounded end pi
76c31b58c39f224dfc3326fc67b015dc61226c4a
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/data/fintype/basic.lean
00a4340293b348238e471a738e1f5efe0f198ee5
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
75,683
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.array.lemmas import data.finset.pi import data.finset.powerset import data.sym.basic import group_theory.perm.basic import order.well_founded import tactic.wlog /-! # Finite types This file defines a typeclass to state that a type is finite. ## Main declarations * `fintype α`: Typeclass saying that a type is finite. It takes as fields a `finset` and a proof that all terms of type `α` are in it. * `finset.univ`: The finset of all elements of a fintype. * `fintype.card α`: Cardinality of a fintype. Equal to `finset.univ.card`. * `perms_of_finset s`: The finset of permutations of the finset `s`. * `fintype.trunc_equiv_fin`: A fintype `α` is computably equivalent to `fin (card α)`. The `trunc`-free, noncomputable version is `fintype.equiv_fin`. * `fintype.trunc_equiv_of_card_eq` `fintype.equiv_of_card_eq`: Two fintypes of same cardinality are equivalent. See above. * `fin.equiv_iff_eq`: `fin m ≃ fin n` iff `m = n`. * `infinite α`: Typeclass saying that a type is infinite. Defined as `fintype α → false`. * `not_fintype`: No `fintype` has an `infinite` instance. * `infinite.nat_embedding`: An embedding of `ℕ` into an infinite type. We also provide the following versions of the pigeonholes principle. * `fintype.exists_ne_map_eq_of_card_lt` and `is_empty_of_card_lt`: Finitely many pigeons and pigeonholes. Weak formulation. * `fintype.exists_ne_map_eq_of_infinite`: Infinitely many pigeons in finitely many pigeonholes. Weak formulation. * `fintype.exists_infinite_fiber`: Infinitely many pigeons in finitely many pigeonholes. Strong formulation. Some more pigeonhole-like statements can be found in `data.fintype.card_embedding`. ## Instances Among others, we provide `fintype` instances for * A `subtype` of a fintype. See `fintype.subtype`. * The `option` of a fintype. * The product of two fintypes. * The sum of two fintypes. * `Prop`. and `infinite` instances for * `ℕ` * `ℤ` along with some machinery * Types which have a surjection from/an injection to a `fintype` are themselves fintypes. See `fintype.of_injective` and `fintype.of_surjective`. * Types which have an injection from/a surjection to an `infinite` type are themselves `infinite`. See `infinite.of_injective` and `infinite.of_surjective`. -/ open_locale nat universes u v variables {α β γ : Type*} /-- `fintype α` means that `α` is finite, i.e. there are only finitely many distinct elements of type `α`. The evidence of this is a finset `elems` (a list up to permutation without duplicates), together with a proof that everything of type `α` is in the list. -/ class fintype (α : Type*) := (elems [] : finset α) (complete : ∀ x : α, x ∈ elems) namespace finset variable [fintype α] /-- `univ` is the universal finite set of type `finset α` implied from the assumption `fintype α`. -/ def univ : finset α := fintype.elems α @[simp] theorem mem_univ (x : α) : x ∈ (univ : finset α) := fintype.complete x @[simp] theorem mem_univ_val : ∀ x, x ∈ (univ : finset α).1 := mem_univ @[simp] lemma coe_univ : ↑(univ : finset α) = (set.univ : set α) := by ext; simp lemma univ_nonempty_iff : (univ : finset α).nonempty ↔ nonempty α := by rw [← coe_nonempty, coe_univ, set.nonempty_iff_univ_nonempty] lemma univ_nonempty [nonempty α] : (univ : finset α).nonempty := univ_nonempty_iff.2 ‹_› lemma univ_eq_empty : (univ : finset α) = ∅ ↔ ¬nonempty α := by rw [← univ_nonempty_iff, nonempty_iff_ne_empty, ne.def, not_not] lemma univ_eq_empty' : (univ : finset α) = ∅ ↔ is_empty α := univ_eq_empty.trans (not_nonempty_iff) @[simp] theorem subset_univ (s : finset α) : s ⊆ univ := λ a _, mem_univ a instance : order_top (finset α) := { top := univ, le_top := subset_univ, .. finset.partial_order } instance [decidable_eq α] : boolean_algebra (finset α) := { compl := λ s, univ \ s, inf_compl_le_bot := λ s x hx, by simpa using hx, top_le_sup_compl := λ s x hx, by simp, sdiff_eq := λ s t, by simp [ext_iff, compl], ..finset.order_top, ..finset.generalized_boolean_algebra } lemma compl_eq_univ_sdiff [decidable_eq α] (s : finset α) : sᶜ = univ \ s := rfl @[simp] lemma mem_compl [decidable_eq α] {s : finset α} {x : α} : x ∈ sᶜ ↔ x ∉ s := by simp [compl_eq_univ_sdiff] @[simp, norm_cast] lemma coe_compl [decidable_eq α] (s : finset α) : ↑(sᶜ) = (↑s : set α)ᶜ := set.ext $ λ x, mem_compl @[simp] theorem union_compl [decidable_eq α] (s : finset α) : s ∪ sᶜ = finset.univ := sup_compl_eq_top @[simp] lemma compl_filter [decidable_eq α] (p : α → Prop) [decidable_pred p] [Π x, decidable (¬p x)] : (univ.filter p)ᶜ = univ.filter (λ x, ¬p x) := (filter_not _ _).symm theorem eq_univ_iff_forall {s : finset α} : s = univ ↔ ∀ x, x ∈ s := by simp [ext_iff] lemma compl_ne_univ_iff_nonempty [decidable_eq α] (s : finset α) : sᶜ ≠ univ ↔ s.nonempty := by simp [eq_univ_iff_forall, finset.nonempty] @[simp] lemma univ_inter [decidable_eq α] (s : finset α) : univ ∩ s = s := ext $ λ a, by simp @[simp] lemma inter_univ [decidable_eq α] (s : finset α) : s ∩ univ = s := by rw [inter_comm, univ_inter] @[simp] lemma piecewise_univ [Π i : α, decidable (i ∈ (univ : finset α))] {δ : α → Sort*} (f g : Π i, δ i) : univ.piecewise f g = f := by { ext i, simp [piecewise] } lemma piecewise_compl [decidable_eq α] (s : finset α) [Π i : α, decidable (i ∈ s)] [Π i : α, decidable (i ∈ sᶜ)] {δ : α → Sort*} (f g : Π i, δ i) : sᶜ.piecewise f g = s.piecewise g f := by { ext i, simp [piecewise] } lemma univ_map_equiv_to_embedding {α β : Type*} [fintype α] [fintype β] (e : α ≃ β) : univ.map e.to_embedding = univ := eq_univ_iff_forall.mpr (λ b, mem_map.mpr ⟨e.symm b, mem_univ _, by simp⟩) @[simp] lemma univ_filter_exists (f : α → β) [fintype β] [decidable_pred (λ y, ∃ x, f x = y)] [decidable_eq β] : finset.univ.filter (λ y, ∃ x, f x = y) = finset.univ.image f := by { ext, simp } /-- Note this is a special case of `(finset.image_preimage f univ _).symm`. -/ lemma univ_filter_mem_range (f : α → β) [fintype β] [decidable_pred (λ y, y ∈ set.range f)] [decidable_eq β] : finset.univ.filter (λ y, y ∈ set.range f) = finset.univ.image f := univ_filter_exists f /-- A special case of `finset.sup_eq_supr` that omits the useless `x ∈ univ` binder. -/ lemma sup_univ_eq_supr [complete_lattice β] (f : α → β) : finset.univ.sup f = supr f := (sup_eq_supr _ f).trans $ congr_arg _ $ funext $ λ a, supr_pos (mem_univ _) /-- A special case of `finset.inf_eq_infi` that omits the useless `x ∈ univ` binder. -/ lemma inf_univ_eq_infi [complete_lattice β] (f : α → β) : finset.univ.inf f = infi f := sup_univ_eq_supr (by exact f : α → order_dual β) end finset open finset function namespace fintype instance decidable_pi_fintype {α} {β : α → Type*} [∀ a, decidable_eq (β a)] [fintype α] : decidable_eq (Π a, β a) := λ f g, decidable_of_iff (∀ a ∈ fintype.elems α, f a = g a) (by simp [function.funext_iff, fintype.complete]) instance decidable_forall_fintype {p : α → Prop} [decidable_pred p] [fintype α] : decidable (∀ a, p a) := decidable_of_iff (∀ a ∈ @univ α _, p a) (by simp) instance decidable_exists_fintype {p : α → Prop} [decidable_pred p] [fintype α] : decidable (∃ a, p a) := decidable_of_iff (∃ a ∈ @univ α _, p a) (by simp) instance decidable_mem_range_fintype [fintype α] [decidable_eq β] (f : α → β) : decidable_pred (∈ set.range f) := λ x, fintype.decidable_exists_fintype section bundled_homs instance decidable_eq_equiv_fintype [decidable_eq β] [fintype α] : decidable_eq (α ≃ β) := λ a b, decidable_of_iff (a.1 = b.1) equiv.coe_fn_injective.eq_iff instance decidable_eq_embedding_fintype [decidable_eq β] [fintype α] : decidable_eq (α ↪ β) := λ a b, decidable_of_iff (⇑a = b) function.embedding.coe_injective.eq_iff @[to_additive] instance decidable_eq_one_hom_fintype [decidable_eq β] [fintype α] [has_one α] [has_one β]: decidable_eq (one_hom α β) := λ a b, decidable_of_iff (⇑a = b) (injective.eq_iff one_hom.coe_inj) @[to_additive] instance decidable_eq_mul_hom_fintype [decidable_eq β] [fintype α] [has_mul α] [has_mul β]: decidable_eq (mul_hom α β) := λ a b, decidable_of_iff (⇑a = b) (injective.eq_iff mul_hom.coe_inj) @[to_additive] instance decidable_eq_monoid_hom_fintype [decidable_eq β] [fintype α] [mul_one_class α] [mul_one_class β]: decidable_eq (α →* β) := λ a b, decidable_of_iff (⇑a = b) (injective.eq_iff monoid_hom.coe_inj) instance decidable_eq_monoid_with_zero_hom_fintype [decidable_eq β] [fintype α] [mul_zero_one_class α] [mul_zero_one_class β]: decidable_eq (monoid_with_zero_hom α β) := λ a b, decidable_of_iff (⇑a = b) (injective.eq_iff monoid_with_zero_hom.coe_inj) instance decidable_eq_ring_hom_fintype [decidable_eq β] [fintype α] [semiring α] [semiring β]: decidable_eq (α →+* β) := λ a b, decidable_of_iff (⇑a = b) (injective.eq_iff ring_hom.coe_inj) end bundled_homs instance decidable_injective_fintype [decidable_eq α] [decidable_eq β] [fintype α] : decidable_pred (injective : (α → β) → Prop) := λ x, by unfold injective; apply_instance instance decidable_surjective_fintype [decidable_eq β] [fintype α] [fintype β] : decidable_pred (surjective : (α → β) → Prop) := λ x, by unfold surjective; apply_instance instance decidable_bijective_fintype [decidable_eq α] [decidable_eq β] [fintype α] [fintype β] : decidable_pred (bijective : (α → β) → Prop) := λ x, by unfold bijective; apply_instance instance decidable_right_inverse_fintype [decidable_eq α] [fintype α] (f : α → β) (g : β → α) : decidable (function.right_inverse f g) := show decidable (∀ x, g (f x) = x), by apply_instance instance decidable_left_inverse_fintype [decidable_eq β] [fintype β] (f : α → β) (g : β → α) : decidable (function.left_inverse f g) := show decidable (∀ x, f (g x) = x), by apply_instance lemma exists_max [fintype α] [nonempty α] {β : Type*} [linear_order β] (f : α → β) : ∃ x₀ : α, ∀ x, f x ≤ f x₀ := by simpa using exists_max_image univ f univ_nonempty lemma exists_min [fintype α] [nonempty α] {β : Type*} [linear_order β] (f : α → β) : ∃ x₀ : α, ∀ x, f x₀ ≤ f x := by simpa using exists_min_image univ f univ_nonempty /-- Construct a proof of `fintype α` from a universal multiset -/ def of_multiset [decidable_eq α] (s : multiset α) (H : ∀ x : α, x ∈ s) : fintype α := ⟨s.to_finset, by simpa using H⟩ /-- Construct a proof of `fintype α` from a universal list -/ def of_list [decidable_eq α] (l : list α) (H : ∀ x : α, x ∈ l) : fintype α := ⟨l.to_finset, by simpa using H⟩ theorem exists_univ_list (α) [fintype α] : ∃ l : list α, l.nodup ∧ ∀ x : α, x ∈ l := let ⟨l, e⟩ := quotient.exists_rep (@univ α _).1 in by have := and.intro univ.2 mem_univ_val; exact ⟨_, by rwa ←e at this⟩ /-- `card α` is the number of elements in `α`, defined when `α` is a fintype. -/ def card (α) [fintype α] : ℕ := (@univ α _).card /-- If `l` lists all the elements of `α` without duplicates, then `α ≃ fin (l.length)`. -/ def equiv_fin_of_forall_mem_list {α} [decidable_eq α] {l : list α} (h : ∀ x : α, x ∈ l) (nd : l.nodup) : α ≃ fin (l.length) := ⟨λ a, ⟨_, list.index_of_lt_length.2 (h a)⟩, λ i, l.nth_le i.1 i.2, λ a, by simp, λ ⟨i, h⟩, fin.eq_of_veq $ list.nodup_iff_nth_le_inj.1 nd _ _ (list.index_of_lt_length.2 (list.nth_le_mem _ _ _)) h $ by simp⟩ /-- There is (computably) a bijection between `α` and `fin (card α)`. Since it is not unique, and depends on which permutation of the universe list is used, the bijection is wrapped in `trunc` to preserve computability. See `fintype.equiv_fin` for the noncomputable version, and `fintype.trunc_equiv_fin_of_card_eq` and `fintype.equiv_fin_of_card_eq` for an equiv `α ≃ fin n` given `fintype.card α = n`. -/ def trunc_equiv_fin (α) [decidable_eq α] [fintype α] : trunc (α ≃ fin (card α)) := by unfold card finset.card; exact quot.rec_on_subsingleton (@univ α _).1 (λ l (h : ∀ x : α, x ∈ l) (nd : l.nodup), trunc.mk (equiv_fin_of_forall_mem_list h nd)) mem_univ_val univ.2 /-- There is a (noncomputable) bijection between `α` and `fin (card α)`. See `fintype.trunc_equiv_fin` for the computable version, and `fintype.trunc_equiv_fin_of_card_eq` and `fintype.equiv_fin_of_card_eq` for an equiv `α ≃ fin n` given `fintype.card α = n`. -/ noncomputable def equiv_fin (α) [fintype α] : α ≃ fin (card α) := by { letI := classical.dec_eq α, exact (trunc_equiv_fin α).out } instance (α : Type*) : subsingleton (fintype α) := ⟨λ ⟨s₁, h₁⟩ ⟨s₂, h₂⟩, by congr; simp [finset.ext_iff, h₁, h₂]⟩ /-- Given a predicate that can be represented by a finset, the subtype associated to the predicate is a fintype. -/ protected def subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : fintype {x // p x} := ⟨⟨multiset.pmap subtype.mk s.1 (λ x, (H x).1), multiset.nodup_pmap (λ a _ b _, congr_arg subtype.val) s.2⟩, λ ⟨x, px⟩, multiset.mem_pmap.2 ⟨x, (H x).2 px, rfl⟩⟩ theorem subtype_card {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : @card {x // p x} (fintype.subtype s H) = s.card := multiset.card_pmap _ _ _ theorem card_of_subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) [fintype {x // p x}] : card {x // p x} = s.card := by { rw ← subtype_card s H, congr } /-- Construct a fintype from a finset with the same elements. -/ def of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : fintype p := fintype.subtype s H @[simp] theorem card_of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : @fintype.card p (of_finset s H) = s.card := fintype.subtype_card s H theorem card_of_finset' {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) [fintype p] : fintype.card p = s.card := by rw ←card_of_finset s H; congr /-- If `f : α → β` is a bijection and `α` is a fintype, then `β` is also a fintype. -/ def of_bijective [fintype α] (f : α → β) (H : function.bijective f) : fintype β := ⟨univ.map ⟨f, H.1⟩, λ b, let ⟨a, e⟩ := H.2 b in e ▸ mem_map_of_mem _ (mem_univ _)⟩ /-- If `f : α → β` is a surjection and `α` is a fintype, then `β` is also a fintype. -/ def of_surjective [decidable_eq β] [fintype α] (f : α → β) (H : function.surjective f) : fintype β := ⟨univ.image f, λ b, let ⟨a, e⟩ := H b in e ▸ mem_image_of_mem _ (mem_univ _)⟩ end fintype section inv namespace function variables [fintype α] [decidable_eq β] namespace injective variables {f : α → β} (hf : function.injective f) /-- The inverse of an `hf : injective` function `f : α → β`, of the type `↥(set.range f) → α`. This is the computable version of `function.inv_fun` that requires `fintype α` and `decidable_eq β`, or the function version of applying `(equiv.of_injective f hf).symm`. This function should not usually be used for actual computation because for most cases, an explicit inverse can be stated that has better computational properties. This function computes by checking all terms `a : α` to find the `f a = b`, so it is O(N) where `N = fintype.card α`. -/ def inv_of_mem_range : set.range f → α := λ b, finset.choose (λ a, f a = b) finset.univ ((exists_unique_congr (by simp)).mp (hf.exists_unique_of_mem_range b.property)) lemma left_inv_of_inv_of_mem_range (b : set.range f) : f (hf.inv_of_mem_range b) = b := (finset.choose_spec (λ a, f a = b) _ _).right @[simp] lemma right_inv_of_inv_of_mem_range (a : α) : hf.inv_of_mem_range (⟨f a, set.mem_range_self a⟩) = a := hf (finset.choose_spec (λ a', f a' = f a) _ _).right lemma inv_fun_restrict [nonempty α] : (set.range f).restrict (inv_fun f) = hf.inv_of_mem_range := begin ext ⟨b, h⟩, apply hf, simp [hf.left_inv_of_inv_of_mem_range, @inv_fun_eq _ _ _ f b (set.mem_range.mp h)] end lemma inv_of_mem_range_surjective : function.surjective hf.inv_of_mem_range := λ a, ⟨⟨f a, set.mem_range_self a⟩, by simp⟩ end injective namespace embedding variables (f : α ↪ β) (b : set.range f) /-- The inverse of an embedding `f : α ↪ β`, of the type `↥(set.range f) → α`. This is the computable version of `function.inv_fun` that requires `fintype α` and `decidable_eq β`, or the function version of applying `(equiv.of_injective f f.injective).symm`. This function should not usually be used for actual computation because for most cases, an explicit inverse can be stated that has better computational properties. This function computes by checking all terms `a : α` to find the `f a = b`, so it is O(N) where `N = fintype.card α`. -/ def inv_of_mem_range : α := f.injective.inv_of_mem_range b @[simp] lemma left_inv_of_inv_of_mem_range : f (f.inv_of_mem_range b) = b := f.injective.left_inv_of_inv_of_mem_range b @[simp] lemma right_inv_of_inv_of_mem_range (a : α) : f.inv_of_mem_range ⟨f a, set.mem_range_self a⟩ = a := f.injective.right_inv_of_inv_of_mem_range a lemma inv_fun_restrict [nonempty α] : (set.range f).restrict (inv_fun f) = f.inv_of_mem_range := begin ext ⟨b, h⟩, apply f.injective, simp [f.left_inv_of_inv_of_mem_range, @inv_fun_eq _ _ _ f b (set.mem_range.mp h)] end lemma inv_of_mem_range_surjective : function.surjective f.inv_of_mem_range := λ a, ⟨⟨f a, set.mem_range_self a⟩, by simp⟩ end embedding end function end inv namespace fintype /-- Given an injective function to a fintype, the domain is also a fintype. This is noncomputable because injectivity alone cannot be used to construct preimages. -/ noncomputable def of_injective [fintype β] (f : α → β) (H : function.injective f) : fintype α := by letI := classical.dec; exact if hα : nonempty α then by letI := classical.inhabited_of_nonempty hα; exact of_surjective (inv_fun f) (inv_fun_surjective H) else ⟨∅, λ x, (hα ⟨x⟩).elim⟩ /-- If `f : α ≃ β` and `α` is a fintype, then `β` is also a fintype. -/ def of_equiv (α : Type*) [fintype α] (f : α ≃ β) : fintype β := of_bijective _ f.bijective theorem of_equiv_card [fintype α] (f : α ≃ β) : @card β (of_equiv α f) = card α := multiset.card_map _ _ theorem card_congr {α β} [fintype α] [fintype β] (f : α ≃ β) : card α = card β := by rw ← of_equiv_card f; congr section variables [fintype α] [fintype β] /-- If the cardinality of `α` is `n`, there is computably a bijection between `α` and `fin n`. See `fintype.equiv_fin_of_card_eq` for the noncomputable definition, and `fintype.trunc_equiv_fin` and `fintype.equiv_fin` for the bijection `α ≃ fin (card α)`. -/ def trunc_equiv_fin_of_card_eq [decidable_eq α] {n : ℕ} (h : fintype.card α = n) : trunc (α ≃ fin n) := (trunc_equiv_fin α).map (λ e, e.trans (fin.cast h).to_equiv) /-- If the cardinality of `α` is `n`, there is noncomputably a bijection between `α` and `fin n`. See `fintype.trunc_equiv_fin_of_card_eq` for the computable definition, and `fintype.trunc_equiv_fin` and `fintype.equiv_fin` for the bijection `α ≃ fin (card α)`. -/ noncomputable def equiv_fin_of_card_eq {n : ℕ} (h : fintype.card α = n) : α ≃ fin n := by { letI := classical.dec_eq α, exact (trunc_equiv_fin_of_card_eq h).out } /-- Two `fintype`s with the same cardinality are (computably) in bijection. See `fintype.equiv_of_card_eq` for the noncomputable version, and `fintype.trunc_equiv_fin_of_card_eq` and `fintype.equiv_fin_of_card_eq` for the specialization to `fin`. -/ def trunc_equiv_of_card_eq [decidable_eq α] [decidable_eq β] (h : card α = card β) : trunc (α ≃ β) := (trunc_equiv_fin_of_card_eq h).bind (λ e, (trunc_equiv_fin β).map (λ e', e.trans e'.symm)) /-- Two `fintype`s with the same cardinality are (noncomputably) in bijection. See `fintype.trunc_equiv_of_card_eq` for the computable version, and `fintype.trunc_equiv_fin_of_card_eq` and `fintype.equiv_fin_of_card_eq` for the specialization to `fin`. -/ noncomputable def equiv_of_card_eq (h : card α = card β) : α ≃ β := by { letI := classical.dec_eq α, letI := classical.dec_eq β, exact (trunc_equiv_of_card_eq h).out } end theorem card_eq {α β} [F : fintype α] [G : fintype β] : card α = card β ↔ nonempty (α ≃ β) := ⟨λ h, by { haveI := classical.prop_decidable, exact (trunc_equiv_of_card_eq h).nonempty }, λ ⟨f⟩, card_congr f⟩ /-- Any subsingleton type with a witness is a fintype (with one term). -/ def of_subsingleton (a : α) [subsingleton α] : fintype α := ⟨{a}, λ b, finset.mem_singleton.2 (subsingleton.elim _ _)⟩ @[simp] theorem univ_of_subsingleton (a : α) [subsingleton α] : @univ _ (of_subsingleton a) = {a} := rfl /-- Note: this lemma is specifically about `fintype.of_subsingleton`. For a statement about arbitrary `fintype` instances, use either `fintype.card_le_one_iff_subsingleton` or `fintype.card_unique`. -/ @[simp] theorem card_of_subsingleton (a : α) [subsingleton α] : @fintype.card _ (of_subsingleton a) = 1 := rfl @[simp] theorem card_unique [unique α] [h : fintype α] : fintype.card α = 1 := subsingleton.elim (of_subsingleton $ default α) h ▸ card_of_subsingleton _ @[priority 100] -- see Note [lower instance priority] instance of_is_empty [is_empty α] : fintype α := ⟨∅, is_empty_elim⟩ /-- Note: this lemma is specifically about `fintype.of_is_empty`. For a statement about arbitrary `fintype` instances, use `fintype.univ_is_empty`. -/ -- no-lint since while `fintype.of_is_empty` can prove this, it isn't applicable for `dsimp`. @[simp, nolint simp_nf] theorem univ_of_is_empty [is_empty α] : @univ α _ = ∅ := rfl /-- Note: this lemma is specifically about `fintype.of_is_empty`. For a statement about arbitrary `fintype` instances, use `fintype.card_eq_zero_iff`. -/ @[simp] theorem card_of_is_empty [is_empty α] : fintype.card α = 0 := rfl open_locale classical variables (α) /-- Any subsingleton type is (noncomputably) a fintype (with zero or one term). -/ @[priority 5] -- see Note [lower instance priority] noncomputable instance of_subsingleton' [subsingleton α] : fintype α := if h : nonempty α then of_subsingleton (nonempty.some h) else @fintype.of_is_empty _ $ not_nonempty_iff.mp h end fintype namespace set /-- Construct a finset enumerating a set `s`, given a `fintype` instance. -/ def to_finset (s : set α) [fintype s] : finset α := ⟨(@finset.univ s _).1.map subtype.val, multiset.nodup_map (λ a b, subtype.eq) finset.univ.2⟩ @[simp] theorem mem_to_finset {s : set α} [fintype s] {a : α} : a ∈ s.to_finset ↔ a ∈ s := by simp [to_finset] @[simp] theorem mem_to_finset_val {s : set α} [fintype s] {a : α} : a ∈ s.to_finset.1 ↔ a ∈ s := mem_to_finset -- We use an arbitrary `[fintype s]` instance here, -- not necessarily coming from a `[fintype α]`. @[simp] lemma to_finset_card {α : Type*} (s : set α) [fintype s] : s.to_finset.card = fintype.card s := multiset.card_map subtype.val finset.univ.val @[simp] theorem coe_to_finset (s : set α) [fintype s] : (↑s.to_finset : set α) = s := set.ext $ λ _, mem_to_finset @[simp] theorem to_finset_inj {s t : set α} [fintype s] [fintype t] : s.to_finset = t.to_finset ↔ s = t := ⟨λ h, by rw [←s.coe_to_finset, h, t.coe_to_finset], λ h, by simp [h]; congr⟩ @[simp, mono] theorem to_finset_mono {s t : set α} [fintype s] [fintype t] : s.to_finset ⊆ t.to_finset ↔ s ⊆ t := by simp [finset.subset_iff, set.subset_def] @[simp, mono] theorem to_finset_strict_mono {s t : set α} [fintype s] [fintype t] : s.to_finset ⊂ t.to_finset ↔ s ⊂ t := begin rw [←lt_eq_ssubset, ←finset.lt_iff_ssubset, lt_iff_le_and_ne, lt_iff_le_and_ne], simp end @[simp] theorem to_finset_disjoint_iff [decidable_eq α] {s t : set α} [fintype s] [fintype t] : disjoint s.to_finset t.to_finset ↔ disjoint s t := ⟨λ h x hx, h (by simpa using hx), λ h x hx, h (by simpa using hx)⟩ end set lemma finset.card_univ [fintype α] : (finset.univ : finset α).card = fintype.card α := rfl lemma finset.eq_univ_of_card [fintype α] (s : finset α) (hs : s.card = fintype.card α) : s = univ := eq_of_subset_of_card_le (subset_univ _) $ by rw [hs, finset.card_univ] lemma finset.card_eq_iff_eq_univ [fintype α] (s : finset α) : s.card = fintype.card α ↔ s = finset.univ := ⟨s.eq_univ_of_card, by { rintro rfl, exact finset.card_univ, }⟩ lemma finset.card_le_univ [fintype α] (s : finset α) : s.card ≤ fintype.card α := card_le_of_subset (subset_univ s) lemma finset.card_lt_univ_of_not_mem [fintype α] {s : finset α} {x : α} (hx : x ∉ s) : s.card < fintype.card α := card_lt_card ⟨subset_univ s, not_forall.2 ⟨x, λ hx', hx (hx' $ mem_univ x)⟩⟩ lemma finset.card_lt_iff_ne_univ [fintype α] (s : finset α) : s.card < fintype.card α ↔ s ≠ finset.univ := s.card_le_univ.lt_iff_ne.trans (not_iff_not_of_iff s.card_eq_iff_eq_univ) lemma finset.card_compl_lt_iff_nonempty [fintype α] [decidable_eq α] (s : finset α) : sᶜ.card < fintype.card α ↔ s.nonempty := sᶜ.card_lt_iff_ne_univ.trans s.compl_ne_univ_iff_nonempty lemma finset.card_univ_diff [decidable_eq α] [fintype α] (s : finset α) : (finset.univ \ s).card = fintype.card α - s.card := finset.card_sdiff (subset_univ s) lemma finset.card_compl [decidable_eq α] [fintype α] (s : finset α) : sᶜ.card = fintype.card α - s.card := finset.card_univ_diff s instance (n : ℕ) : fintype (fin n) := ⟨finset.fin_range n, finset.mem_fin_range⟩ lemma fin.univ_def (n : ℕ) : (univ : finset (fin n)) = finset.fin_range n := rfl @[simp] theorem fintype.card_fin (n : ℕ) : fintype.card (fin n) = n := list.length_fin_range n @[simp] lemma finset.card_fin (n : ℕ) : finset.card (finset.univ : finset (fin n)) = n := by rw [finset.card_univ, fintype.card_fin] lemma card_finset_fin_le {n : ℕ} (s : finset (fin n)) : s.card ≤ n := by simpa only [fintype.card_fin] using s.card_le_univ lemma fin.equiv_iff_eq {m n : ℕ} : nonempty (fin m ≃ fin n) ↔ m = n := ⟨λ ⟨h⟩, by simpa using fintype.card_congr h, λ h, ⟨equiv.cast $ h ▸ rfl ⟩ ⟩ /-- Embed `fin n` into `fin (n + 1)` by prepending zero to the `univ` -/ lemma fin.univ_succ (n : ℕ) : (univ : finset (fin (n + 1))) = insert 0 (univ.image fin.succ) := begin ext m, simp only [mem_univ, mem_insert, true_iff, mem_image, exists_prop], exact fin.cases (or.inl rfl) (λ i, or.inr ⟨i, trivial, rfl⟩) m end /-- Embed `fin n` into `fin (n + 1)` by appending a new `fin.last n` to the `univ` -/ lemma fin.univ_cast_succ (n : ℕ) : (univ : finset (fin (n + 1))) = insert (fin.last n) (univ.image fin.cast_succ) := begin ext m, simp only [mem_univ, mem_insert, true_iff, mem_image, exists_prop, true_and], by_cases h : m.val < n, { right, use fin.cast_lt m h, rw fin.cast_succ_cast_lt }, { left, exact fin.eq_last_of_not_lt h } end /-- Embed `fin n` into `fin (n + 1)` by inserting around a specified pivot `p : fin (n + 1)` into the `univ` -/ lemma fin.univ_succ_above (n : ℕ) (p : fin (n + 1)) : (univ : finset (fin (n + 1))) = insert p (univ.image (fin.succ_above p)) := begin obtain hl | rfl := (fin.le_last p).lt_or_eq, { ext m, simp only [finset.mem_univ, finset.mem_insert, true_iff, finset.mem_image, exists_prop], refine or_iff_not_imp_left.mpr (λ h, _), cases n, { have : m = p := by simp, exact absurd this h }, use p.cast_pred.pred_above m, rw fin.pred_above, split_ifs with H, { simp only [fin.coe_cast_succ, true_and, fin.coe_coe_eq_self, coe_coe], rw fin.lt_last_iff_coe_cast_pred at hl, rw fin.succ_above_above, { simp }, { simp only [fin.lt_iff_coe_lt_coe, fin.coe_cast_succ] at H, simpa [fin.le_iff_coe_le_coe, ←hl] using nat.le_pred_of_lt H } }, { rw fin.succ_above_below, { simp }, { simp only [fin.cast_succ_cast_pred hl, not_lt] at H, simpa using lt_of_le_of_ne H h } } }, { rw fin.succ_above_last, exact fin.univ_cast_succ n } end @[instance, priority 10] def unique.fintype {α : Type*} [unique α] : fintype α := fintype.of_subsingleton (default α) /-- Short-circuit instance to decrease search for `unique.fintype`, since that relies on a subsingleton elimination for `unique`. -/ instance fintype.subtype_eq (y : α) : fintype {x // x = y} := fintype.subtype {y} (by simp) /-- Short-circuit instance to decrease search for `unique.fintype`, since that relies on a subsingleton elimination for `unique`. -/ instance fintype.subtype_eq' (y : α) : fintype {x // y = x} := fintype.subtype {y} (by simp [eq_comm]) @[simp] lemma univ_unique {α : Type*} [unique α] [f : fintype α] : @finset.univ α _ = {default α} := by rw [subsingleton.elim f (@unique.fintype α _)]; refl @[simp] lemma univ_is_empty {α : Type*} [is_empty α] [fintype α] : @finset.univ α _ = ∅ := finset.ext is_empty_elim @[simp] lemma fintype.card_subtype_eq (y : α) : fintype.card {x // x = y} = 1 := begin convert fintype.card_unique, exact unique.subtype_eq _ end @[simp] lemma fintype.card_subtype_eq' (y : α) : fintype.card {x // y = x} = 1 := begin convert fintype.card_unique, exact unique.subtype_eq' _ end @[simp] theorem fintype.univ_empty : @univ empty _ = ∅ := rfl @[simp] theorem fintype.card_empty : fintype.card empty = 0 := rfl @[simp] theorem fintype.univ_pempty : @univ pempty _ = ∅ := rfl @[simp] theorem fintype.card_pempty : fintype.card pempty = 0 := rfl instance : fintype unit := fintype.of_subsingleton () theorem fintype.univ_unit : @univ unit _ = {()} := rfl theorem fintype.card_unit : fintype.card unit = 1 := rfl instance : fintype punit := fintype.of_subsingleton punit.star @[simp] theorem fintype.univ_punit : @univ punit _ = {punit.star} := rfl @[simp] theorem fintype.card_punit : fintype.card punit = 1 := rfl instance : fintype bool := ⟨⟨tt ::ₘ ff ::ₘ 0, by simp⟩, λ x, by cases x; simp⟩ @[simp] theorem fintype.univ_bool : @univ bool _ = {tt, ff} := rfl instance units_int.fintype : fintype (units ℤ) := ⟨{1, -1}, λ x, by cases int.units_eq_one_or x; simp *⟩ @[simp] lemma units_int.univ : (finset.univ : finset (units ℤ)) = {1, -1} := rfl instance additive.fintype : Π [fintype α], fintype (additive α) := id instance multiplicative.fintype : Π [fintype α], fintype (multiplicative α) := id @[simp] theorem fintype.card_units_int : fintype.card (units ℤ) = 2 := rfl noncomputable instance [monoid α] [fintype α] : fintype (units α) := by classical; exact fintype.of_injective units.val units.ext @[simp] theorem fintype.card_bool : fintype.card bool = 2 := rfl /-- Given a finset on `α`, lift it to being a finset on `option α` using `option.some` and then insert `option.none`. -/ def finset.insert_none (s : finset α) : finset (option α) := ⟨none ::ₘ s.1.map some, multiset.nodup_cons.2 ⟨by simp, multiset.nodup_map (λ a b, option.some.inj) s.2⟩⟩ @[simp] theorem finset.mem_insert_none {s : finset α} : ∀ {o : option α}, o ∈ s.insert_none ↔ ∀ a ∈ o, a ∈ s | none := iff_of_true (multiset.mem_cons_self _ _) (λ a h, by cases h) | (some a) := multiset.mem_cons.trans $ by simp; refl theorem finset.some_mem_insert_none {s : finset α} {a : α} : some a ∈ s.insert_none ↔ a ∈ s := by simp instance {α : Type*} [fintype α] : fintype (option α) := ⟨univ.insert_none, λ a, by simp⟩ @[simp] theorem fintype.card_option {α : Type*} [fintype α] : fintype.card (option α) = fintype.card α + 1 := (multiset.card_cons _ _).trans (by rw multiset.card_map; refl) instance {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype (sigma β) := ⟨univ.sigma (λ _, univ), λ ⟨a, b⟩, by simp⟩ @[simp] lemma finset.univ_sigma_univ {α : Type*} {β : α → Type*} [fintype α] [∀ a, fintype (β a)] : (univ : finset α).sigma (λ a, (univ : finset (β a))) = univ := rfl instance (α β : Type*) [fintype α] [fintype β] : fintype (α × β) := ⟨univ.product univ, λ ⟨a, b⟩, by simp⟩ @[simp] lemma finset.univ_product_univ {α β : Type*} [fintype α] [fintype β] : (univ : finset α).product (univ : finset β) = univ := rfl @[simp] theorem fintype.card_prod (α β : Type*) [fintype α] [fintype β] : fintype.card (α × β) = fintype.card α * fintype.card β := card_product _ _ /-- Given that `α × β` is a fintype, `α` is also a fintype. -/ def fintype.prod_left {α β} [decidable_eq α] [fintype (α × β)] [nonempty β] : fintype α := ⟨(fintype.elems (α × β)).image prod.fst, λ a, let ⟨b⟩ := ‹nonempty β› in by simp; exact ⟨b, fintype.complete _⟩⟩ /-- Given that `α × β` is a fintype, `β` is also a fintype. -/ def fintype.prod_right {α β} [decidable_eq β] [fintype (α × β)] [nonempty α] : fintype β := ⟨(fintype.elems (α × β)).image prod.snd, λ b, let ⟨a⟩ := ‹nonempty α› in by simp; exact ⟨a, fintype.complete _⟩⟩ instance (α : Type*) [fintype α] : fintype (ulift α) := fintype.of_equiv _ equiv.ulift.symm @[simp] theorem fintype.card_ulift (α : Type*) [fintype α] : fintype.card (ulift α) = fintype.card α := fintype.of_equiv_card _ lemma univ_sum_type {α β : Type*} [fintype α] [fintype β] [fintype (α ⊕ β)] [decidable_eq (α ⊕ β)] : (univ : finset (α ⊕ β)) = map function.embedding.inl univ ∪ map function.embedding.inr univ := begin rw [eq_comm, eq_univ_iff_forall], simp only [mem_union, mem_map, exists_prop, mem_univ, true_and], rintro (x|y), exacts [or.inl ⟨x, rfl⟩, or.inr ⟨y, rfl⟩] end instance (α : Type u) (β : Type v) [fintype α] [fintype β] : fintype (α ⊕ β) := @fintype.of_equiv _ _ (@sigma.fintype _ (λ b, cond b (ulift α) (ulift.{(max u v) v} β)) _ (λ b, by cases b; apply ulift.fintype)) ((equiv.sum_equiv_sigma_bool _ _).symm.trans (equiv.sum_congr equiv.ulift equiv.ulift)) /-- Given that `α ⊕ β` is a fintype, `α` is also a fintype. This is non-computable as it uses that `sum.inl` is an injection, but there's no clear inverse if `α` is empty. -/ noncomputable def fintype.sum_left {α β} [fintype (α ⊕ β)] : fintype α := fintype.of_injective (sum.inl : α → α ⊕ β) sum.inl_injective /-- Given that `α ⊕ β` is a fintype, `β` is also a fintype. This is non-computable as it uses that `sum.inr` is an injection, but there's no clear inverse if `β` is empty. -/ noncomputable def fintype.sum_right {α β} [fintype (α ⊕ β)] : fintype β := fintype.of_injective (sum.inr : β → α ⊕ β) sum.inr_injective @[simp] theorem fintype.card_sum [fintype α] [fintype β] : fintype.card (α ⊕ β) = fintype.card α + fintype.card β := begin classical, rw [←finset.card_univ, univ_sum_type, finset.card_union_eq], { simp [finset.card_univ] }, { intros x hx, suffices : (∃ (a : α), sum.inl a = x) ∧ ∃ (b : β), sum.inr b = x, { obtain ⟨⟨a, rfl⟩, ⟨b, hb⟩⟩ := this, simpa using hb }, simpa using hx } end section finset /-! ### `fintype (s : finset α)` -/ instance finset.fintype_coe_sort {α : Type u} (s : finset α) : fintype s := ⟨s.attach, s.mem_attach⟩ @[simp] lemma finset.univ_eq_attach {α : Type u} (s : finset α) : (univ : finset s) = s.attach := rfl end finset namespace fintype variables [fintype α] [fintype β] lemma card_le_of_injective (f : α → β) (hf : function.injective f) : card α ≤ card β := finset.card_le_card_of_inj_on f (λ _ _, finset.mem_univ _) (λ _ _ _ _ h, hf h) lemma card_le_of_embedding (f : α ↪ β) : card α ≤ card β := card_le_of_injective f f.2 lemma card_lt_of_injective_of_not_mem (f : α → β) (h : function.injective f) {b : β} (w : b ∉ set.range f) : card α < card β := calc card α = (univ.map ⟨f, h⟩).card : (card_map _).symm ... < card β : finset.card_lt_univ_of_not_mem $ by rwa [← mem_coe, coe_map, coe_univ, set.image_univ] lemma card_lt_of_injective_not_surjective (f : α → β) (h : function.injective f) (h' : ¬function.surjective f) : card α < card β := let ⟨y, hy⟩ := not_forall.1 h' in card_lt_of_injective_of_not_mem f h hy lemma card_le_of_surjective (f : α → β) (h : function.surjective f) : card β ≤ card α := card_le_of_injective _ (function.injective_surj_inv h) /-- The pigeonhole principle for finitely many pigeons and pigeonholes. This is the `fintype` version of `finset.exists_ne_map_eq_of_card_lt_of_maps_to`. -/ lemma exists_ne_map_eq_of_card_lt (f : α → β) (h : fintype.card β < fintype.card α) : ∃ x y, x ≠ y ∧ f x = f y := let ⟨x, _, y, _, h⟩ := finset.exists_ne_map_eq_of_card_lt_of_maps_to h (λ x _, mem_univ (f x)) in ⟨x, y, h⟩ lemma card_eq_one_iff : card α = 1 ↔ (∃ x : α, ∀ y, y = x) := by rw [←card_unit, card_eq]; exact ⟨λ ⟨a⟩, ⟨a.symm (), λ y, a.injective (subsingleton.elim _ _)⟩, λ ⟨x, hx⟩, ⟨⟨λ _, (), λ _, x, λ _, (hx _).trans (hx _).symm, λ _, subsingleton.elim _ _⟩⟩⟩ lemma card_eq_zero_iff : card α = 0 ↔ is_empty α := ⟨λ h, ⟨λ a, have e : α ≃ empty := classical.choice (card_eq.1 (by simp [h])), (e a).elim⟩, λ h, by { have e : α ≃ empty, exactI equiv.equiv_empty α, simp [card_congr e] }⟩ lemma card_eq_one_iff_nonempty_unique : card α = 1 ↔ nonempty (unique α) := ⟨λ h, let ⟨d, h⟩ := fintype.card_eq_one_iff.mp h in ⟨{ default := d, uniq := h}⟩, λ ⟨h⟩, by exactI fintype.card_unique⟩ /-- A `fintype` with cardinality zero is equivalent to `empty`. -/ def card_eq_zero_equiv_equiv_empty : card α = 0 ≃ (α ≃ empty) := (equiv.of_iff card_eq_zero_iff).trans (equiv.equiv_empty_equiv α).symm lemma card_pos_iff : 0 < card α ↔ nonempty α := pos_iff_ne_zero.trans $ not_iff_comm.mp $ not_nonempty_iff.trans card_eq_zero_iff.symm lemma card_le_one_iff : card α ≤ 1 ↔ (∀ a b : α, a = b) := let n := card α in have hn : n = card α := rfl, match n, hn with | 0 := λ ha, ⟨λ h, λ a, (card_eq_zero_iff.1 ha.symm).elim a, λ _, ha ▸ nat.le_succ _⟩ | 1 := λ ha, ⟨λ h, λ a b, let ⟨x, hx⟩ := card_eq_one_iff.1 ha.symm in by rw [hx a, hx b], λ _, ha ▸ le_refl _⟩ | (n+2) := λ ha, ⟨λ h, by rw ← ha at h; exact absurd h dec_trivial, (λ h, card_unit ▸ card_le_of_injective (λ _, ()) (λ _ _ _, h _ _))⟩ end lemma card_le_one_iff_subsingleton : card α ≤ 1 ↔ subsingleton α := card_le_one_iff.trans subsingleton_iff.symm lemma one_lt_card_iff_nontrivial : 1 < card α ↔ nontrivial α := begin classical, rw ←not_iff_not, push_neg, rw [not_nontrivial_iff_subsingleton, card_le_one_iff_subsingleton] end lemma exists_ne_of_one_lt_card (h : 1 < card α) (a : α) : ∃ b : α, b ≠ a := by { haveI : nontrivial α := one_lt_card_iff_nontrivial.1 h, exact exists_ne a } lemma exists_pair_of_one_lt_card (h : 1 < card α) : ∃ (a b : α), a ≠ b := by { haveI : nontrivial α := one_lt_card_iff_nontrivial.1 h, exact exists_pair_ne α } lemma card_eq_one_of_forall_eq {i : α} (h : ∀ j, j = i) : card α = 1 := fintype.card_eq_one_iff.2 ⟨i,h⟩ lemma injective_iff_surjective {f : α → α} : injective f ↔ surjective f := by haveI := classical.prop_decidable; exact have ∀ {f : α → α}, injective f → surjective f, from λ f hinj x, have h₁ : image f univ = univ := eq_of_subset_of_card_le (subset_univ _) ((card_image_of_injective univ hinj).symm ▸ le_refl _), have h₂ : x ∈ image f univ := h₁.symm ▸ mem_univ _, exists_of_bex (mem_image.1 h₂), ⟨this, λ hsurj, has_left_inverse.injective ⟨surj_inv hsurj, left_inverse_of_surjective_of_right_inverse (this (injective_surj_inv _)) (right_inverse_surj_inv _)⟩⟩ lemma injective_iff_bijective {f : α → α} : injective f ↔ bijective f := by simp [bijective, injective_iff_surjective] lemma surjective_iff_bijective {f : α → α} : surjective f ↔ bijective f := by simp [bijective, injective_iff_surjective] lemma injective_iff_surjective_of_equiv {β : Type*} {f : α → β} (e : α ≃ β) : injective f ↔ surjective f := have injective (e.symm ∘ f) ↔ surjective (e.symm ∘ f), from injective_iff_surjective, ⟨λ hinj, by simpa [function.comp] using e.surjective.comp (this.1 (e.symm.injective.comp hinj)), λ hsurj, by simpa [function.comp] using e.injective.comp (this.2 (e.symm.surjective.comp hsurj))⟩ lemma bijective_iff_injective_and_card (f : α → β) : bijective f ↔ injective f ∧ card α = card β := begin split, { intro h, exact ⟨h.1, card_congr (equiv.of_bijective f h)⟩ }, { rintro ⟨hf, h⟩, refine ⟨hf, _⟩, rwa ←injective_iff_surjective_of_equiv (equiv_of_card_eq h) } end lemma bijective_iff_surjective_and_card (f : α → β) : bijective f ↔ surjective f ∧ card α = card β := begin split, { intro h, exact ⟨h.2, card_congr (equiv.of_bijective f h)⟩, }, { rintro ⟨hf, h⟩, refine ⟨_, hf⟩, rwa injective_iff_surjective_of_equiv (equiv_of_card_eq h) } end lemma right_inverse_of_left_inverse_of_card_le {f : α → β} {g : β → α} (hfg : left_inverse f g) (hcard : card α ≤ card β) : right_inverse f g := have hsurj : surjective f, from surjective_iff_has_right_inverse.2 ⟨g, hfg⟩, right_inverse_of_injective_of_left_inverse ((bijective_iff_surjective_and_card _).2 ⟨hsurj, le_antisymm hcard (card_le_of_surjective f hsurj)⟩ ).1 hfg lemma left_inverse_of_right_inverse_of_card_le {f : α → β} {g : β → α} (hfg : right_inverse f g) (hcard : card β ≤ card α) : left_inverse f g := right_inverse_of_left_inverse_of_card_le hfg hcard end fintype lemma fintype.coe_image_univ [fintype α] [decidable_eq β] {f : α → β} : ↑(finset.image f finset.univ) = set.range f := by { ext x, simp } instance list.subtype.fintype [decidable_eq α] (l : list α) : fintype {x // x ∈ l} := fintype.of_list l.attach l.mem_attach instance multiset.subtype.fintype [decidable_eq α] (s : multiset α) : fintype {x // x ∈ s} := fintype.of_multiset s.attach s.mem_attach instance finset.subtype.fintype (s : finset α) : fintype {x // x ∈ s} := ⟨s.attach, s.mem_attach⟩ instance finset_coe.fintype (s : finset α) : fintype (↑s : set α) := finset.subtype.fintype s @[simp] lemma fintype.card_coe (s : finset α) : fintype.card s = s.card := card_attach lemma finset.attach_eq_univ {s : finset α} : s.attach = finset.univ := rfl instance plift.fintype (p : Prop) [decidable p] : fintype (plift p) := ⟨if h : p then {⟨h⟩} else ∅, λ ⟨h⟩, by simp [h]⟩ instance Prop.fintype : fintype Prop := ⟨⟨true ::ₘ false ::ₘ 0, by simp [true_ne_false]⟩, classical.cases (by simp) (by simp)⟩ instance subtype.fintype (p : α → Prop) [decidable_pred p] [fintype α] : fintype {x // p x} := fintype.subtype (univ.filter p) (by simp) /-- A set on a fintype, when coerced to a type, is a fintype. -/ def set_fintype {α} [fintype α] (s : set α) [decidable_pred (∈ s)] : fintype s := subtype.fintype (λ x, x ∈ s) lemma set_fintype_card_le_univ {α : Type*} [fintype α] (s : set α) [fintype ↥s] : fintype.card ↥s ≤ fintype.card α := fintype.card_le_of_embedding (function.embedding.subtype s) namespace function.embedding /-- An embedding from a `fintype` to itself can be promoted to an equivalence. -/ noncomputable def equiv_of_fintype_self_embedding {α : Type*} [fintype α] (e : α ↪ α) : α ≃ α := equiv.of_bijective e (fintype.injective_iff_bijective.1 e.2) @[simp] lemma equiv_of_fintype_self_embedding_to_embedding {α : Type*} [fintype α] (e : α ↪ α) : e.equiv_of_fintype_self_embedding.to_embedding = e := by { ext, refl, } /-- If `‖β‖ < ‖α‖` there are no embeddings `α ↪ β`. This is a formulation of the pigeonhole principle. Note this cannot be an instance as it needs `h`. -/ @[simp] lemma is_empty_of_card_lt {α β} [fintype α] [fintype β] (h : fintype.card β < fintype.card α) : is_empty (α ↪ β) := ⟨λ f, let ⟨x, y, ne, feq⟩ := fintype.exists_ne_map_eq_of_card_lt f h in ne $ f.injective feq⟩ end function.embedding @[simp] lemma finset.univ_map_embedding {α : Type*} [fintype α] (e : α ↪ α) : univ.map e = univ := by rw [←e.equiv_of_fintype_self_embedding_to_embedding, univ_map_equiv_to_embedding] namespace fintype lemma card_lt_of_surjective_not_injective [fintype α] [fintype β] (f : α → β) (h : function.surjective f) (h' : ¬function.injective f) : card β < card α := card_lt_of_injective_not_surjective _ (function.injective_surj_inv h) $ λ hg, have w : function.bijective (function.surj_inv h) := ⟨function.injective_surj_inv h, hg⟩, h' $ (injective_iff_surjective_of_equiv (equiv.of_bijective _ w).symm).mpr h variables [decidable_eq α] [fintype α] {δ : α → Type*} /-- Given for all `a : α` a finset `t a` of `δ a`, then one can define the finset `fintype.pi_finset t` of all functions taking values in `t a` for all `a`. This is the analogue of `finset.pi` where the base finset is `univ` (but formally they are not the same, as there is an additional condition `i ∈ finset.univ` in the `finset.pi` definition). -/ def pi_finset (t : Π a, finset (δ a)) : finset (Π a, δ a) := (finset.univ.pi t).map ⟨λ f a, f a (mem_univ a), λ _ _, by simp [function.funext_iff]⟩ @[simp] lemma mem_pi_finset {t : Π a, finset (δ a)} {f : Π a, δ a} : f ∈ pi_finset t ↔ (∀ a, f a ∈ t a) := begin split, { simp only [pi_finset, mem_map, and_imp, forall_prop_of_true, exists_prop, mem_univ, exists_imp_distrib, mem_pi], rintro g hg hgf a, rw ← hgf, exact hg a }, { simp only [pi_finset, mem_map, forall_prop_of_true, exists_prop, mem_univ, mem_pi], exact λ hf, ⟨λ a ha, f a, hf, rfl⟩ } end lemma pi_finset_subset (t₁ t₂ : Π a, finset (δ a)) (h : ∀ a, t₁ a ⊆ t₂ a) : pi_finset t₁ ⊆ pi_finset t₂ := λ g hg, mem_pi_finset.2 $ λ a, h a $ mem_pi_finset.1 hg a lemma pi_finset_disjoint_of_disjoint [∀ a, decidable_eq (δ a)] (t₁ t₂ : Π a, finset (δ a)) {a : α} (h : disjoint (t₁ a) (t₂ a)) : disjoint (pi_finset t₁) (pi_finset t₂) := disjoint_iff_ne.2 $ λ f₁ hf₁ f₂ hf₂ eq₁₂, disjoint_iff_ne.1 h (f₁ a) (mem_pi_finset.1 hf₁ a) (f₂ a) (mem_pi_finset.1 hf₂ a) (congr_fun eq₁₂ a) end fintype /-! ### pi -/ /-- A dependent product of fintypes, indexed by a fintype, is a fintype. -/ instance pi.fintype {α : Type*} {β : α → Type*} [decidable_eq α] [fintype α] [∀ a, fintype (β a)] : fintype (Π a, β a) := ⟨fintype.pi_finset (λ _, univ), by simp⟩ @[simp] lemma fintype.pi_finset_univ {α : Type*} {β : α → Type*} [decidable_eq α] [fintype α] [∀ a, fintype (β a)] : fintype.pi_finset (λ a : α, (finset.univ : finset (β a))) = (finset.univ : finset (Π a, β a)) := rfl instance d_array.fintype {n : ℕ} {α : fin n → Type*} [∀ n, fintype (α n)] : fintype (d_array n α) := fintype.of_equiv _ (equiv.d_array_equiv_fin _).symm instance array.fintype {n : ℕ} {α : Type*} [fintype α] : fintype (array n α) := d_array.fintype instance vector.fintype {α : Type*} [fintype α] {n : ℕ} : fintype (vector α n) := fintype.of_equiv _ (equiv.vector_equiv_fin _ _).symm instance quotient.fintype [fintype α] (s : setoid α) [decidable_rel ((≈) : α → α → Prop)] : fintype (quotient s) := fintype.of_surjective quotient.mk (λ x, quotient.induction_on x (λ x, ⟨x, rfl⟩)) instance finset.fintype [fintype α] : fintype (finset α) := ⟨univ.powerset, λ x, finset.mem_powerset.2 (finset.subset_univ _)⟩ -- irreducible due to this conversation on Zulip: -- https://leanprover.zulipchat.com/#narrow/stream/113488-general/ -- topic/.60simp.60.20ignoring.20lemmas.3F/near/241824115 @[irreducible] instance function.embedding.fintype {α β} [fintype α] [fintype β] [decidable_eq α] [decidable_eq β] : fintype (α ↪ β) := fintype.of_equiv _ (equiv.subtype_injective_equiv_embedding α β) instance [decidable_eq α] [fintype α] {n : ℕ} : fintype (sym.sym' α n) := quotient.fintype _ instance [decidable_eq α] [fintype α] {n : ℕ} : fintype (sym α n) := fintype.of_equiv _ sym.sym_equiv_sym'.symm @[simp] lemma fintype.card_finset [fintype α] : fintype.card (finset α) = 2 ^ (fintype.card α) := finset.card_powerset finset.univ @[simp] lemma finset.univ_filter_card_eq (α : Type*) [fintype α] (k : ℕ) : (finset.univ : finset (finset α)).filter (λ s, s.card = k) = finset.univ.powerset_len k := by { ext, simp [finset.mem_powerset_len] } @[simp] lemma fintype.card_finset_len [fintype α] (k : ℕ) : fintype.card {s : finset α // s.card = k} = nat.choose (fintype.card α) k := by simp [fintype.subtype_card, finset.card_univ] @[simp] lemma set.to_finset_univ [fintype α] : (set.univ : set α).to_finset = finset.univ := by { ext, simp only [set.mem_univ, mem_univ, set.mem_to_finset] } @[simp] lemma set.to_finset_eq_empty_iff {s : set α} [fintype s] : s.to_finset = ∅ ↔ s = ∅ := by simp [ext_iff, set.ext_iff] @[simp] lemma set.to_finset_empty : (∅ : set α).to_finset = ∅ := set.to_finset_eq_empty_iff.mpr rfl @[simp] lemma set.to_finset_range [decidable_eq α] [fintype β] (f : β → α) [fintype (set.range f)] : (set.range f).to_finset = finset.univ.image f := by simp [ext_iff] theorem fintype.card_subtype_le [fintype α] (p : α → Prop) [decidable_pred p] : fintype.card {x // p x} ≤ fintype.card α := fintype.card_le_of_embedding (function.embedding.subtype _) theorem fintype.card_subtype_lt [fintype α] {p : α → Prop} [decidable_pred p] {x : α} (hx : ¬ p x) : fintype.card {x // p x} < fintype.card α := fintype.card_lt_of_injective_of_not_mem coe subtype.coe_injective $ by rwa subtype.range_coe_subtype lemma fintype.card_subtype [fintype α] (p : α → Prop) [decidable_pred p] : fintype.card {x // p x} = ((finset.univ : finset α).filter p).card := begin refine fintype.card_of_subtype _ _, simp end lemma fintype.card_subtype_or (p q : α → Prop) [fintype {x // p x}] [fintype {x // q x}] [fintype {x // p x ∨ q x}] : fintype.card {x // p x ∨ q x} ≤ fintype.card {x // p x} + fintype.card {x // q x} := begin classical, convert fintype.card_le_of_embedding (subtype_or_left_embedding p q), rw fintype.card_sum end lemma fintype.card_subtype_or_disjoint (p q : α → Prop) (h : disjoint p q) [fintype {x // p x}] [fintype {x // q x}] [fintype {x // p x ∨ q x}] : fintype.card {x // p x ∨ q x} = fintype.card {x // p x} + fintype.card {x // q x} := begin classical, convert fintype.card_congr (subtype_or_equiv p q h), simp end theorem fintype.card_quotient_le [fintype α] (s : setoid α) [decidable_rel ((≈) : α → α → Prop)] : fintype.card (quotient s) ≤ fintype.card α := fintype.card_le_of_surjective _ (surjective_quotient_mk _) theorem fintype.card_quotient_lt [fintype α] {s : setoid α} [decidable_rel ((≈) : α → α → Prop)] {x y : α} (h1 : x ≠ y) (h2 : x ≈ y) : fintype.card (quotient s) < fintype.card α := fintype.card_lt_of_surjective_not_injective _ (surjective_quotient_mk _) $ λ w, h1 (w $ quotient.eq.mpr h2) instance psigma.fintype {α : Type*} {β : α → Type*} [fintype α] [∀ a, fintype (β a)] : fintype (Σ' a, β a) := fintype.of_equiv _ (equiv.psigma_equiv_sigma _).symm instance psigma.fintype_prop_left {α : Prop} {β : α → Type*} [decidable α] [∀ a, fintype (β a)] : fintype (Σ' a, β a) := if h : α then fintype.of_equiv (β h) ⟨λ x, ⟨h, x⟩, psigma.snd, λ _, rfl, λ ⟨_, _⟩, rfl⟩ else ⟨∅, λ x, h x.1⟩ instance psigma.fintype_prop_right {α : Type*} {β : α → Prop} [∀ a, decidable (β a)] [fintype α] : fintype (Σ' a, β a) := fintype.of_equiv {a // β a} ⟨λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, rfl, λ ⟨x, y⟩, rfl⟩ instance psigma.fintype_prop_prop {α : Prop} {β : α → Prop} [decidable α] [∀ a, decidable (β a)] : fintype (Σ' a, β a) := if h : ∃ a, β a then ⟨{⟨h.fst, h.snd⟩}, λ ⟨_, _⟩, by simp⟩ else ⟨∅, λ ⟨x, y⟩, h ⟨x, y⟩⟩ instance set.fintype [fintype α] : fintype (set α) := ⟨(@finset.univ α _).powerset.map ⟨coe, coe_injective⟩, λ s, begin classical, refine mem_map.2 ⟨finset.univ.filter s, mem_powerset.2 (subset_univ _), _⟩, apply (coe_filter _ _).trans, rw [coe_univ, set.sep_univ], refl end⟩ instance pfun_fintype (p : Prop) [decidable p] (α : p → Type*) [Π hp, fintype (α hp)] : fintype (Π hp : p, α hp) := if hp : p then fintype.of_equiv (α hp) ⟨λ a _, a, λ f, f hp, λ _, rfl, λ _, rfl⟩ else ⟨singleton (λ h, (hp h).elim), by simp [hp, function.funext_iff]⟩ @[simp] lemma finset.univ_pi_univ {α : Type*} {β : α → Type*} [decidable_eq α] [fintype α] [∀ a, fintype (β a)] : finset.univ.pi (λ a : α, (finset.univ : finset (β a))) = finset.univ := by { ext, simp } lemma mem_image_univ_iff_mem_range {α β : Type*} [fintype α] [decidable_eq β] {f : α → β} {b : β} : b ∈ univ.image f ↔ b ∈ set.range f := by simp /-- An auxiliary function for `quotient.fin_choice`. Given a collection of setoids indexed by a type `ι`, a (finite) list `l` of indices, and a function that for each `i ∈ l` gives a term of the corresponding quotient type, then there is a corresponding term in the quotient of the product of the setoids indexed by `l`. -/ def quotient.fin_choice_aux {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : Π (l : list ι), (Π i ∈ l, quotient (S i)) → @quotient (Π i ∈ l, α i) (by apply_instance) | [] f := ⟦λ i, false.elim⟧ | (i :: l) f := begin refine quotient.lift_on₂ (f i (list.mem_cons_self _ _)) (quotient.fin_choice_aux l (λ j h, f j (list.mem_cons_of_mem _ h))) _ _, exact λ a l, ⟦λ j h, if e : j = i then by rw e; exact a else l _ (h.resolve_left e)⟧, refine λ a₁ l₁ a₂ l₂ h₁ h₂, quotient.sound (λ j h, _), by_cases e : j = i; simp [e], { subst j, exact h₁ }, { exact h₂ _ _ } end theorem quotient.fin_choice_aux_eq {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : ∀ (l : list ι) (f : Π i ∈ l, α i), quotient.fin_choice_aux l (λ i h, ⟦f i h⟧) = ⟦f⟧ | [] f := quotient.sound (λ i h, h.elim) | (i :: l) f := begin simp [quotient.fin_choice_aux, quotient.fin_choice_aux_eq l], refine quotient.sound (λ j h, _), by_cases e : j = i; simp [e], subst j, refl end /-- Given a collection of setoids indexed by a fintype `ι` and a function that for each `i : ι` gives a term of the corresponding quotient type, then there is corresponding term in the quotient of the product of the setoids. -/ def quotient.fin_choice {ι : Type*} [decidable_eq ι] [fintype ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] (f : Π i, quotient (S i)) : @quotient (Π i, α i) (by apply_instance) := quotient.lift_on (@quotient.rec_on _ _ (λ l : multiset ι, @quotient (Π i ∈ l, α i) (by apply_instance)) finset.univ.1 (λ l, quotient.fin_choice_aux l (λ i _, f i)) (λ a b h, begin have := λ a, quotient.fin_choice_aux_eq a (λ i h, quotient.out (f i)), simp [quotient.out_eq] at this, simp [this], let g := λ a:multiset ι, ⟦λ (i : ι) (h : i ∈ a), quotient.out (f i)⟧, refine eq_of_heq ((eq_rec_heq _ _).trans (_ : g a == g b)), congr' 1, exact quotient.sound h, end)) (λ f, ⟦λ i, f i (finset.mem_univ _)⟧) (λ a b h, quotient.sound $ λ i, h _ _) theorem quotient.fin_choice_eq {ι : Type*} [decidable_eq ι] [fintype ι] {α : ι → Type*} [∀ i, setoid (α i)] (f : Π i, α i) : quotient.fin_choice (λ i, ⟦f i⟧) = ⟦f⟧ := begin let q, swap, change quotient.lift_on q _ _ = _, have : q = ⟦λ i h, f i⟧, { dsimp [q], exact quotient.induction_on (@finset.univ ι _).1 (λ l, quotient.fin_choice_aux_eq _ _) }, simp [this], exact setoid.refl _ end section equiv open list equiv equiv.perm variables [decidable_eq α] [decidable_eq β] /-- Given a list, produce a list of all permutations of its elements. -/ def perms_of_list : list α → list (perm α) | [] := [1] | (a :: l) := perms_of_list l ++ l.bind (λ b, (perms_of_list l).map (λ f, swap a b * f)) lemma length_perms_of_list : ∀ l : list α, length (perms_of_list l) = l.length! | [] := rfl | (a :: l) := begin rw [length_cons, nat.factorial_succ], simp [perms_of_list, length_bind, length_perms_of_list, function.comp, nat.succ_mul], cc end lemma mem_perms_of_list_of_mem {l : list α} {f : perm α} (h : ∀ x, f x ≠ x → x ∈ l) : f ∈ perms_of_list l := begin induction l with a l IH generalizing f h, { exact list.mem_singleton.2 (equiv.ext $ λ x, decidable.by_contradiction $ h _) }, by_cases hfa : f a = a, { refine mem_append_left _ (IH (λ x hx, mem_of_ne_of_mem _ (h x hx))), rintro rfl, exact hx hfa }, have hfa' : f (f a) ≠ f a := mt (λ h, f.injective h) hfa, have : ∀ (x : α), (swap a (f a) * f) x ≠ x → x ∈ l, { intros x hx, have hxa : x ≠ a, { rintro rfl, apply hx, simp only [mul_apply, swap_apply_right] }, refine list.mem_of_ne_of_mem hxa (h x (λ h, _)), simp only [h, mul_apply, swap_apply_def, mul_apply, ne.def, apply_eq_iff_eq] at hx; split_ifs at hx, exacts [hxa (h.symm.trans h_1), hx h] }, suffices : f ∈ perms_of_list l ∨ ∃ (b ∈ l) (g ∈ perms_of_list l), swap a b * g = f, { simpa only [perms_of_list, exists_prop, list.mem_map, mem_append, list.mem_bind] }, refine or_iff_not_imp_left.2 (λ hfl, ⟨f a, _, swap a (f a) * f, IH this, _⟩), { by_cases hffa : f (f a) = a, { exact mem_of_ne_of_mem hfa (h _ (mt (λ h, f.injective h) hfa)) }, { apply this, simp only [mul_apply, swap_apply_def, mul_apply, ne.def, apply_eq_iff_eq], split_ifs; cc } }, { rw [←mul_assoc, mul_def (swap a (f a)) (swap a (f a)), swap_swap, ←perm.one_def, one_mul] } end lemma mem_of_mem_perms_of_list : ∀ {l : list α} {f : perm α}, f ∈ perms_of_list l → ∀ {x}, f x ≠ x → x ∈ l | [] f h := have f = 1 := by simpa [perms_of_list] using h, by rw this; simp | (a :: l) f h := (mem_append.1 h).elim (λ h x hx, mem_cons_of_mem _ (mem_of_mem_perms_of_list h hx)) (λ h x hx, let ⟨y, hy, hy'⟩ := list.mem_bind.1 h in let ⟨g, hg₁, hg₂⟩ := list.mem_map.1 hy' in if hxa : x = a then by simp [hxa] else if hxy : x = y then mem_cons_of_mem _ $ by rwa hxy else mem_cons_of_mem _ $ mem_of_mem_perms_of_list hg₁ $ by rw [eq_inv_mul_iff_mul_eq.2 hg₂, mul_apply, swap_inv, swap_apply_def]; split_ifs; cc) lemma mem_perms_of_list_iff {l : list α} {f : perm α} : f ∈ perms_of_list l ↔ ∀ {x}, f x ≠ x → x ∈ l := ⟨mem_of_mem_perms_of_list, mem_perms_of_list_of_mem⟩ lemma nodup_perms_of_list : ∀ {l : list α} (hl : l.nodup), (perms_of_list l).nodup | [] hl := by simp [perms_of_list] | (a :: l) hl := have hl' : l.nodup, from nodup_of_nodup_cons hl, have hln' : (perms_of_list l).nodup, from nodup_perms_of_list hl', have hmeml : ∀ {f : perm α}, f ∈ perms_of_list l → f a = a, from λ f hf, not_not.1 (mt (mem_of_mem_perms_of_list hf) (nodup_cons.1 hl).1), by rw [perms_of_list, list.nodup_append, list.nodup_bind, pairwise_iff_nth_le]; exact ⟨hln', ⟨λ _ _, nodup_map (λ _ _, mul_left_cancel) hln', λ i j hj hij x hx₁ hx₂, let ⟨f, hf⟩ := list.mem_map.1 hx₁ in let ⟨g, hg⟩ := list.mem_map.1 hx₂ in have hix : x a = nth_le l i (lt_trans hij hj), by rw [←hf.2, mul_apply, hmeml hf.1, swap_apply_left], have hiy : x a = nth_le l j hj, by rw [← hg.2, mul_apply, hmeml hg.1, swap_apply_left], absurd (hf.2.trans (hg.2.symm)) $ λ h, ne_of_lt hij $ nodup_iff_nth_le_inj.1 hl' i j (lt_trans hij hj) hj $ by rw [← hix, hiy]⟩, λ f hf₁ hf₂, let ⟨x, hx, hx'⟩ := list.mem_bind.1 hf₂ in let ⟨g, hg⟩ := list.mem_map.1 hx' in have hgxa : g⁻¹ x = a, from f.injective $ by rw [hmeml hf₁, ← hg.2]; simp, have hxa : x ≠ a, from λ h, (list.nodup_cons.1 hl).1 (h ▸ hx), (list.nodup_cons.1 hl).1 $ hgxa ▸ mem_of_mem_perms_of_list hg.1 (by rwa [apply_inv_self, hgxa])⟩ /-- Given a finset, produce the finset of all permutations of its elements. -/ def perms_of_finset (s : finset α) : finset (perm α) := quotient.hrec_on s.1 (λ l hl, ⟨perms_of_list l, nodup_perms_of_list hl⟩) (λ a b hab, hfunext (congr_arg _ (quotient.sound hab)) (λ ha hb _, heq_of_eq $ finset.ext $ by simp [mem_perms_of_list_iff, hab.mem_iff])) s.2 lemma mem_perms_of_finset_iff : ∀ {s : finset α} {f : perm α}, f ∈ perms_of_finset s ↔ ∀ {x}, f x ≠ x → x ∈ s := by rintros ⟨⟨l⟩, hs⟩ f; exact mem_perms_of_list_iff lemma card_perms_of_finset : ∀ (s : finset α), (perms_of_finset s).card = s.card! := by rintros ⟨⟨l⟩, hs⟩; exact length_perms_of_list l /-- The collection of permutations of a fintype is a fintype. -/ def fintype_perm [fintype α] : fintype (perm α) := ⟨perms_of_finset (@finset.univ α _), by simp [mem_perms_of_finset_iff]⟩ instance [fintype α] [fintype β] : fintype (α ≃ β) := if h : fintype.card β = fintype.card α then trunc.rec_on_subsingleton (fintype.trunc_equiv_fin α) (λ eα, trunc.rec_on_subsingleton (fintype.trunc_equiv_fin β) (λ eβ, @fintype.of_equiv _ (perm α) fintype_perm (equiv_congr (equiv.refl α) (eα.trans (eq.rec_on h eβ.symm)) : (α ≃ α) ≃ (α ≃ β)))) else ⟨∅, λ x, false.elim (h (fintype.card_eq.2 ⟨x.symm⟩))⟩ lemma fintype.card_perm [fintype α] : fintype.card (perm α) = (fintype.card α)! := subsingleton.elim (@fintype_perm α _ _) (@equiv.fintype α α _ _ _ _) ▸ card_perms_of_finset _ lemma fintype.card_equiv [fintype α] [fintype β] (e : α ≃ β) : fintype.card (α ≃ β) = (fintype.card α)! := fintype.card_congr (equiv_congr (equiv.refl α) e) ▸ fintype.card_perm lemma univ_eq_singleton_of_card_one {α} [fintype α] (x : α) (h : fintype.card α = 1) : (univ : finset α) = {x} := begin symmetry, apply eq_of_subset_of_card_le (subset_univ ({x})), apply le_of_eq, simp [h, finset.card_univ] end end equiv namespace fintype section choose open fintype equiv variables [fintype α] (p : α → Prop) [decidable_pred p] /-- Given a fintype `α` and a predicate `p`, associate to a proof that there is a unique element of `α` satisfying `p` this unique element, as an element of the corresponding subtype. -/ def choose_x (hp : ∃! a : α, p a) : {a // p a} := ⟨finset.choose p univ (by simp; exact hp), finset.choose_property _ _ _⟩ /-- Given a fintype `α` and a predicate `p`, associate to a proof that there is a unique element of `α` satisfying `p` this unique element, as an element of `α`. -/ def choose (hp : ∃! a, p a) : α := choose_x p hp lemma choose_spec (hp : ∃! a, p a) : p (choose p hp) := (choose_x p hp).property end choose section bijection_inverse open function variables [fintype α] [decidable_eq β] {f : α → β} /-- `bij_inv f` is the unique inverse to a bijection `f`. This acts as a computable alternative to `function.inv_fun`. -/ def bij_inv (f_bij : bijective f) (b : β) : α := fintype.choose (λ a, f a = b) begin rcases f_bij.right b with ⟨a', fa_eq_b⟩, rw ← fa_eq_b, exact ⟨a', ⟨rfl, (λ a h, f_bij.left h)⟩⟩ end lemma left_inverse_bij_inv (f_bij : bijective f) : left_inverse (bij_inv f_bij) f := λ a, f_bij.left (choose_spec (λ a', f a' = f a) _) lemma right_inverse_bij_inv (f_bij : bijective f) : right_inverse (bij_inv f_bij) f := λ b, choose_spec (λ a', f a' = b) _ lemma bijective_bij_inv (f_bij : bijective f) : bijective (bij_inv f_bij) := ⟨(right_inverse_bij_inv _).injective, (left_inverse_bij_inv _).surjective⟩ end bijection_inverse lemma well_founded_of_trans_of_irrefl [fintype α] (r : α → α → Prop) [is_trans α r] [is_irrefl α r] : well_founded r := by classical; exact have ∀ x y, r x y → (univ.filter (λ z, r z x)).card < (univ.filter (λ z, r z y)).card, from λ x y hxy, finset.card_lt_card $ by simp only [finset.lt_iff_ssubset.symm, lt_iff_le_not_le, finset.le_iff_subset, finset.subset_iff, mem_filter, true_and, mem_univ, hxy]; exact ⟨λ z hzx, trans hzx hxy, not_forall_of_exists_not ⟨x, not_imp.2 ⟨hxy, irrefl x⟩⟩⟩, subrelation.wf this (measure_wf _) lemma preorder.well_founded [fintype α] [preorder α] : well_founded ((<) : α → α → Prop) := well_founded_of_trans_of_irrefl _ @[instance, priority 10] lemma linear_order.is_well_order [fintype α] [linear_order α] : is_well_order α (<) := { wf := preorder.well_founded } end fintype /-- A type is said to be infinite if it has no fintype instance. Note that `infinite α` is equivalent to `is_empty (fintype α)`. -/ class infinite (α : Type*) : Prop := (not_fintype : fintype α → false) lemma not_fintype (α : Type*) [h1 : infinite α] [h2 : fintype α] : false := infinite.not_fintype h2 protected lemma fintype.false {α : Type*} [infinite α] (h : fintype α) : false := not_fintype α protected lemma infinite.false {α : Type*} [fintype α] (h : infinite α) : false := not_fintype α @[simp] lemma is_empty_fintype {α : Type*} : is_empty (fintype α) ↔ infinite α := ⟨λ ⟨x⟩, ⟨x⟩, λ ⟨x⟩, ⟨x⟩⟩ @[simp] lemma not_nonempty_fintype {α : Type*} : ¬ nonempty (fintype α) ↔ infinite α := not_nonempty_iff.trans is_empty_fintype /-- A non-infinite type is a fintype. -/ noncomputable def fintype_of_not_infinite {α : Type*} (h : ¬ infinite α) : fintype α := ((not_iff_comm.mp not_nonempty_fintype).mp h).some section open_locale classical /-- Any type is (classically) either a `fintype`, or `infinite`. One can obtain the relevant typeclasses via `cases fintype_or_infinite α; resetI`. -/ noncomputable def fintype_or_infinite (α : Type*) : psum (fintype α) (infinite α) := if h : infinite α then psum.inr h else psum.inl (fintype_of_not_infinite h) end lemma finset.exists_minimal {α : Type*} [preorder α] (s : finset α) (h : s.nonempty) : ∃ m ∈ s, ∀ x ∈ s, ¬ (x < m) := begin obtain ⟨c, hcs : c ∈ s⟩ := h, have : well_founded (@has_lt.lt {x // x ∈ s} _) := fintype.well_founded_of_trans_of_irrefl _, obtain ⟨⟨m, hms : m ∈ s⟩, -, H⟩ := this.has_min set.univ ⟨⟨c, hcs⟩, trivial⟩, exact ⟨m, hms, λ x hx hxm, H ⟨x, hx⟩ trivial hxm⟩, end lemma finset.exists_maximal {α : Type*} [preorder α] (s : finset α) (h : s.nonempty) : ∃ m ∈ s, ∀ x ∈ s, ¬ (m < x) := @finset.exists_minimal (order_dual α) _ s h namespace infinite lemma exists_not_mem_finset [infinite α] (s : finset α) : ∃ x, x ∉ s := not_forall.1 $ λ h, fintype.false ⟨s, h⟩ @[priority 100] -- see Note [lower instance priority] instance (α : Type*) [H : infinite α] : nontrivial α := ⟨let ⟨x, hx⟩ := exists_not_mem_finset (∅ : finset α) in let ⟨y, hy⟩ := exists_not_mem_finset ({x} : finset α) in ⟨y, x, by simpa only [mem_singleton] using hy⟩⟩ lemma nonempty (α : Type*) [infinite α] : nonempty α := by apply_instance lemma of_injective [infinite β] (f : β → α) (hf : injective f) : infinite α := ⟨λ I, by exactI (fintype.of_injective f hf).false⟩ lemma of_surjective [infinite β] (f : α → β) (hf : surjective f) : infinite α := ⟨λ I, by { classical, exactI (fintype.of_surjective f hf).false }⟩ private noncomputable def nat_embedding_aux (α : Type*) [infinite α] : ℕ → α | n := by letI := classical.dec_eq α; exact classical.some (exists_not_mem_finset ((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux m) (λ _, multiset.mem_range.1)).to_finset) private lemma nat_embedding_aux_injective (α : Type*) [infinite α] : function.injective (nat_embedding_aux α) := begin rintro m n h, letI := classical.dec_eq α, wlog hmlen : m ≤ n using m n, by_contradiction hmn, have hmn : m < n, from lt_of_le_of_ne hmlen hmn, refine (classical.some_spec (exists_not_mem_finset ((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux α m) (λ _, multiset.mem_range.1)).to_finset)) _, refine multiset.mem_to_finset.2 (multiset.mem_pmap.2 ⟨m, multiset.mem_range.2 hmn, _⟩), rw [h, nat_embedding_aux] end /-- Embedding of `ℕ` into an infinite type. -/ noncomputable def nat_embedding (α : Type*) [infinite α] : ℕ ↪ α := ⟨_, nat_embedding_aux_injective α⟩ lemma exists_subset_card_eq (α : Type*) [infinite α] (n : ℕ) : ∃ s : finset α, s.card = n := ⟨(range n).map (nat_embedding α), by rw [card_map, card_range]⟩ end infinite /-- If every finset in a type has bounded cardinality, that type is finite. -/ noncomputable def fintype_of_finset_card_le {ι : Type*} (n : ℕ) (w : ∀ s : finset ι, s.card ≤ n) : fintype ι := begin apply fintype_of_not_infinite, introI i, obtain ⟨s, c⟩ := infinite.exists_subset_card_eq ι (n+1), specialize w s, rw c at w, exact nat.not_succ_le_self n w, end lemma not_injective_infinite_fintype [infinite α] [fintype β] (f : α → β) : ¬ injective f := λ hf, (fintype.of_injective f hf).false /-- The pigeonhole principle for infinitely many pigeons in finitely many pigeonholes. If there are infinitely many pigeons in finitely many pigeonholes, then there are at least two pigeons in the same pigeonhole. See also: `fintype.exists_ne_map_eq_of_card_lt`, `fintype.exists_infinite_fiber`. -/ lemma fintype.exists_ne_map_eq_of_infinite [infinite α] [fintype β] (f : α → β) : ∃ x y : α, x ≠ y ∧ f x = f y := begin classical, by_contra hf, push_neg at hf, apply not_injective_infinite_fintype f, intros x y, contrapose, apply hf, end -- irreducible due to this conversation on Zulip: -- https://leanprover.zulipchat.com/#narrow/stream/113488-general/ -- topic/.60simp.60.20ignoring.20lemmas.3F/near/241824115 @[irreducible] instance function.embedding.is_empty {α β} [infinite α] [fintype β] : is_empty (α ↪ β) := ⟨λ f, let ⟨x, y, ne, feq⟩ := fintype.exists_ne_map_eq_of_infinite f in ne $ f.injective feq⟩ @[priority 100] noncomputable instance function.embedding.fintype' {α β : Type*} [fintype β] : fintype (α ↪ β) := begin by_cases h : infinite α, { resetI, apply_instance }, { have := fintype_of_not_infinite h, classical, apply_instance } -- the `classical` generates `decidable_eq α/β` instances, and resets instance cache end /-- The strong pigeonhole principle for infinitely many pigeons in finitely many pigeonholes. If there are infinitely many pigeons in finitely many pigeonholes, then there is a pigeonhole with infinitely many pigeons. See also: `fintype.exists_ne_map_eq_of_infinite` -/ lemma fintype.exists_infinite_fiber [infinite α] [fintype β] (f : α → β) : ∃ y : β, infinite (f ⁻¹' {y}) := begin classical, by_contra hf, push_neg at hf, haveI := λ y, fintype_of_not_infinite $ hf y, let key : fintype α := { elems := univ.bUnion (λ (y : β), (f ⁻¹' {y}).to_finset), complete := by simp }, exact key.false, end lemma not_surjective_fintype_infinite [fintype α] [infinite β] (f : α → β) : ¬ surjective f := assume (hf : surjective f), have H : infinite α := infinite.of_surjective f hf, by exactI not_fintype α instance nat.infinite : infinite ℕ := ⟨λ ⟨s, hs⟩, finset.not_mem_range_self $ s.subset_range_sup_succ (hs _)⟩ instance int.infinite : infinite ℤ := infinite.of_injective int.of_nat (λ _ _, int.of_nat.inj) section trunc /-- For `s : multiset α`, we can lift the existential statement that `∃ x, x ∈ s` to a `trunc α`. -/ def trunc_of_multiset_exists_mem {α} (s : multiset α) : (∃ x, x ∈ s) → trunc α := quotient.rec_on_subsingleton s $ λ l h, match l, h with | [], _ := false.elim (by tauto) | (a :: _), _ := trunc.mk a end /-- A `nonempty` `fintype` constructively contains an element. -/ def trunc_of_nonempty_fintype (α) [nonempty α] [fintype α] : trunc α := trunc_of_multiset_exists_mem finset.univ.val (by simp) /-- A `fintype` with positive cardinality constructively contains an element. -/ def trunc_of_card_pos {α} [fintype α] (h : 0 < fintype.card α) : trunc α := by { letI := (fintype.card_pos_iff.mp h), exact trunc_of_nonempty_fintype α } /-- By iterating over the elements of a fintype, we can lift an existential statement `∃ a, P a` to `trunc (Σ' a, P a)`, containing data. -/ def trunc_sigma_of_exists {α} [fintype α] {P : α → Prop} [decidable_pred P] (h : ∃ a, P a) : trunc (Σ' a, P a) := @trunc_of_nonempty_fintype (Σ' a, P a) (exists.elim h $ λ a ha, ⟨⟨a, ha⟩⟩) _ end trunc namespace multiset variables [fintype α] [decidable_eq α] @[simp] lemma count_univ (a : α) : count a finset.univ.val = 1 := count_eq_one_of_mem finset.univ.nodup (finset.mem_univ _) end multiset namespace fintype /-- A recursor principle for finite types, analogous to `nat.rec`. It effectively says that every `fintype` is either `empty` or `option α`, up to an `equiv`. -/ def trunc_rec_empty_option {P : Type u → Sort v} (of_equiv : ∀ {α β}, α ≃ β → P α → P β) (h_empty : P pempty) (h_option : ∀ {α} [fintype α] [decidable_eq α], P α → P (option α)) (α : Type u) [fintype α] [decidable_eq α] : trunc (P α) := begin suffices : ∀ n : ℕ, trunc (P (ulift $ fin n)), { apply trunc.bind (this (fintype.card α)), intro h, apply trunc.map _ (fintype.trunc_equiv_fin α), intro e, exact of_equiv (equiv.ulift.trans e.symm) h }, intro n, induction n with n ih, { have : card pempty = card (ulift (fin 0)), { simp only [card_fin, card_pempty, card_ulift] }, apply trunc.bind (trunc_equiv_of_card_eq this), intro e, apply trunc.mk, refine of_equiv e h_empty, }, { have : card (option (ulift (fin n))) = card (ulift (fin n.succ)), { simp only [card_fin, card_option, card_ulift] }, apply trunc.bind (trunc_equiv_of_card_eq this), intro e, apply trunc.map _ ih, intro ih, refine of_equiv e (h_option ih), }, end /-- An induction principle for finite types, analogous to `nat.rec`. It effectively says that every `fintype` is either `empty` or `option α`, up to an `equiv`. -/ lemma induction_empty_option {P : Type u → Prop} (of_equiv : ∀ {α β}, α ≃ β → P α → P β) (h_empty : P pempty) (h_option : ∀ {α} [fintype α], P α → P (option α)) (α : Type u) [fintype α] : P α := begin haveI := classical.dec_eq α, obtain ⟨p⟩ := trunc_rec_empty_option @of_equiv h_empty (λ _ _ _, by exactI h_option) α, exact p, end end fintype
b26c87d7c15556bebe8acc7283c4b63d6e7f4288
63abd62053d479eae5abf4951554e1064a4c45b4
/src/algebra/direct_limit.lean
517d53ba56463622d61c2fdd90c0286d24f659fa
[ "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
27,980
lean
/- Copyright (c) 2019 Kenny Lau, Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Chris Hughes -/ import data.finset.order import linear_algebra.direct_sum_module import ring_theory.free_comm_ring import ring_theory.ideal.operations /-! # Direct limit of modules, abelian groups, rings, and fields. See Atiyah-Macdonald PP.32-33, Matsumura PP.269-270 Generalizes the notion of "union", or "gluing", of incomparable modules over the same ring, or incomparable abelian groups, or rings, or fields. It is constructed as a quotient of the free module (for the module case) or quotient of the free commutative ring (for the ring case) instead of a quotient of the disjoint union so as to make the operations (addition etc.) "computable". -/ universes u v w u₁ open submodule variables {R : Type u} [ring R] variables {ι : Type v} variables [dec_ι : decidable_eq ι] [directed_order ι] variables (G : ι → Type w) /-- A directed system is a functor from the category (directed poset) to another category. This is used for abelian groups and rings and fields because their maps are not bundled. See module.directed_system -/ class directed_system (f : Π i j, i ≤ j → G i → G j) : Prop := (map_self [] : ∀ i x h, f i i h x = x) (map_map [] : ∀ i j k hij hjk x, f j k hjk (f i j hij x) = f i k (le_trans hij hjk) x) namespace module variables [Π i, add_comm_group (G i)] [Π i, module R (G i)] /-- A directed system is a functor from the category (directed poset) to the category of `R`-modules. -/ class directed_system (f : Π i j, i ≤ j → G i →ₗ[R] G j) : Prop := (map_self [] : ∀ i x h, f i i h x = x) (map_map [] : ∀ i j k hij hjk x, f j k hjk (f i j hij x) = f i k (le_trans hij hjk) x) variables (f : Π i j, i ≤ j → G i →ₗ[R] G j) include dec_ι /-- The direct limit of a directed system is the modules glued together along the maps. -/ def direct_limit : Type (max v w) := (span R $ { a | ∃ (i j) (H : i ≤ j) x, direct_sum.lof R ι G i x - direct_sum.lof R ι G j (f i j H x) = a }).quotient namespace direct_limit instance : add_comm_group (direct_limit G f) := quotient.add_comm_group _ instance : semimodule R (direct_limit G f) := quotient.semimodule _ instance : inhabited (direct_limit G f) := ⟨0⟩ variables (R ι) /-- The canonical map from a component to the direct limit. -/ def of (i) : G i →ₗ[R] direct_limit G f := (mkq _).comp $ direct_sum.lof R ι G i variables {R ι G f} @[simp] lemma of_f {i j hij x} : (of R ι G f j (f i j hij x)) = of R ι G f i x := eq.symm $ (submodule.quotient.eq _).2 $ subset_span ⟨i, j, hij, x, rfl⟩ /-- Every element of the direct limit corresponds to some element in some component of the directed system. -/ theorem exists_of [nonempty ι] (z : direct_limit G f) : ∃ i x, of R ι G f i x = z := nonempty.elim (by apply_instance) $ assume ind : ι, quotient.induction_on' z $ λ z, direct_sum.induction_on z ⟨ind, 0, linear_map.map_zero _⟩ (λ i x, ⟨i, x, rfl⟩) (λ p q ⟨i, x, ihx⟩ ⟨j, y, ihy⟩, let ⟨k, hik, hjk⟩ := directed_order.directed i j in ⟨k, f i k hik x + f j k hjk y, by rw [linear_map.map_add, of_f, of_f, ihx, ihy]; refl⟩) @[elab_as_eliminator] protected theorem induction_on [nonempty ι] {C : direct_limit G f → Prop} (z : direct_limit G f) (ih : ∀ i x, C (of R ι G f i x)) : C z := let ⟨i, x, h⟩ := exists_of z in h ▸ ih i x variables {P : Type u₁} [add_comm_group P] [module R P] (g : Π i, G i →ₗ[R] P) variables (Hg : ∀ i j hij x, g j (f i j hij x) = g i x) include Hg variables (R ι G f) /-- The universal property of the direct limit: maps from the components to another module that respect the directed system structure (i.e. make some diagram commute) give rise to a unique map out of the direct limit. -/ def lift : direct_limit G f →ₗ[R] P := liftq _ (direct_sum.to_module R ι P g) (span_le.2 $ λ a ⟨i, j, hij, x, hx⟩, by rw [← hx, mem_coe, linear_map.sub_mem_ker_iff, direct_sum.to_module_lof, direct_sum.to_module_lof, Hg]) variables {R ι G f} omit Hg lemma lift_of {i} (x) : lift R ι G f g Hg (of R ι G f i x) = g i x := direct_sum.to_module_lof R _ _ theorem lift_unique [nonempty ι] (F : direct_limit G f →ₗ[R] P) (x) : F x = lift R ι G f (λ i, F.comp $ of R ι G f i) (λ i j hij x, by rw [linear_map.comp_apply, of_f]; refl) x := direct_limit.induction_on x $ λ i x, by rw lift_of; refl section totalize open_locale classical variables (G f) omit dec_ι /-- `totalize G f i j` is a linear map from `G i` to `G j`, for *every* `i` and `j`. If `i ≤ j`, then it is the map `f i j` that comes with the directed system `G`, and otherwise it is the zero map. -/ noncomputable def totalize : Π i j, G i →ₗ[R] G j := λ i j, if h : i ≤ j then f i j h else 0 variables {G f} lemma totalize_apply (i j x) : totalize G f i j x = if h : i ≤ j then f i j h x else 0 := if h : i ≤ j then by dsimp only [totalize]; rw [dif_pos h, dif_pos h] else by dsimp only [totalize]; rw [dif_neg h, dif_neg h, linear_map.zero_apply] end totalize variables [directed_system G f] open_locale classical lemma to_module_totalize_of_le {x : direct_sum ι G} {i j : ι} (hij : i ≤ j) (hx : ∀ k ∈ x.support, k ≤ i) : direct_sum.to_module R ι (G j) (λ k, totalize G f k j) x = f i j hij (direct_sum.to_module R ι (G i) (λ k, totalize G f k i) x) := begin rw [← @dfinsupp.sum_single ι G _ _ _ x], unfold dfinsupp.sum, simp only [linear_map.map_sum], refine finset.sum_congr rfl (λ k hk, _), rw direct_sum.single_eq_lof R k (x k), simp [totalize_apply, hx k hk, le_trans (hx k hk) hij, directed_system.map_map f] end lemma of.zero_exact_aux [nonempty ι] {x : direct_sum ι G} (H : submodule.quotient.mk x = (0 : direct_limit G f)) : ∃ j, (∀ k ∈ x.support, k ≤ j) ∧ direct_sum.to_module R ι (G j) (λ i, totalize G f i j) x = (0 : G j) := nonempty.elim (by apply_instance) $ assume ind : ι, span_induction ((quotient.mk_eq_zero _).1 H) (λ x ⟨i, j, hij, y, hxy⟩, let ⟨k, hik, hjk⟩ := directed_order.directed i j in ⟨k, begin clear_, subst hxy, split, { intros i0 hi0, rw [dfinsupp.mem_support_iff, direct_sum.sub_apply, ← direct_sum.single_eq_lof, ← direct_sum.single_eq_lof, dfinsupp.single_apply, dfinsupp.single_apply] at hi0, split_ifs at hi0 with hi hj hj, { rwa hi at hik }, { rwa hi at hik }, { rwa hj at hjk }, exfalso, apply hi0, rw sub_zero }, simp [linear_map.map_sub, totalize_apply, hik, hjk, directed_system.map_map f, direct_sum.apply_eq_component, direct_sum.component.of], end⟩) ⟨ind, λ _ h, (finset.not_mem_empty _ h).elim, linear_map.map_zero _⟩ (λ x y ⟨i, hi, hxi⟩ ⟨j, hj, hyj⟩, let ⟨k, hik, hjk⟩ := directed_order.directed i j in ⟨k, λ l hl, (finset.mem_union.1 (dfinsupp.support_add hl)).elim (λ hl, le_trans (hi _ hl) hik) (λ hl, le_trans (hj _ hl) hjk), by simp [linear_map.map_add, hxi, hyj, to_module_totalize_of_le hik hi, to_module_totalize_of_le hjk hj]⟩) (λ a x ⟨i, hi, hxi⟩, ⟨i, λ k hk, hi k (direct_sum.support_smul _ _ hk), by simp [linear_map.map_smul, hxi]⟩) /-- A component that corresponds to zero in the direct limit is already zero in some bigger module in the directed system. -/ theorem of.zero_exact {i x} (H : of R ι G f i x = 0) : ∃ j hij, f i j hij x = (0 : G j) := by haveI : nonempty ι := ⟨i⟩; exact let ⟨j, hj, hxj⟩ := of.zero_exact_aux H in if hx0 : x = 0 then ⟨i, le_refl _, by simp [hx0]⟩ else have hij : i ≤ j, from hj _ $ by simp [direct_sum.apply_eq_component, hx0], ⟨j, hij, by simpa [totalize_apply, hij] using hxj⟩ end direct_limit end module namespace add_comm_group variables [Π i, add_comm_group (G i)] include dec_ι /-- The direct limit of a directed system is the abelian groups glued together along the maps. -/ def direct_limit (f : Π i j, i ≤ j → G i → G j) [Π i j hij, is_add_group_hom (f i j hij)] : Type* := @module.direct_limit ℤ _ ι _ _ G _ _ (λ i j hij, (add_monoid_hom.of $ f i j hij).to_int_linear_map) namespace direct_limit variables (f : Π i j, i ≤ j → G i → G j) variables [Π i j hij, is_add_group_hom (f i j hij)] omit dec_ι protected lemma directed_system [directed_system G f] : module.directed_system G (λ i j hij, (add_monoid_hom.of $ f i j hij).to_int_linear_map) := ⟨directed_system.map_self f, directed_system.map_map f⟩ include dec_ι local attribute [instance] direct_limit.directed_system instance : add_comm_group (direct_limit G f) := module.direct_limit.add_comm_group G (λ i j hij, (add_monoid_hom.of $f i j hij).to_int_linear_map) instance : inhabited (direct_limit G f) := ⟨0⟩ /-- The canonical map from a component to the direct limit. -/ def of (i) : G i → direct_limit G f := module.direct_limit.of ℤ ι G (λ i j hij, (add_monoid_hom.of $ f i j hij).to_int_linear_map) i variables {G f} instance of.is_add_group_hom (i) : is_add_group_hom (of G f i) := linear_map.is_add_group_hom _ @[simp] lemma of_f {i j} (hij) (x) : of G f j (f i j hij x) = of G f i x := module.direct_limit.of_f @[simp] lemma of_zero (i) : of G f i 0 = 0 := is_add_group_hom.map_zero _ @[simp] lemma of_add (i x y) : of G f i (x + y) = of G f i x + of G f i y := is_add_hom.map_add _ _ _ @[simp] lemma of_neg (i x) : of G f i (-x) = -of G f i x := is_add_group_hom.map_neg _ _ @[simp] lemma of_sub (i x y) : of G f i (x - y) = of G f i x - of G f i y := is_add_group_hom.map_sub _ _ _ @[elab_as_eliminator] protected theorem induction_on [nonempty ι] {C : direct_limit G f → Prop} (z : direct_limit G f) (ih : ∀ i x, C (of G f i x)) : C z := module.direct_limit.induction_on z ih /-- A component that corresponds to zero in the direct limit is already zero in some bigger module in the directed system. -/ theorem of.zero_exact [directed_system G f] (i x) (h : of G f i x = 0) : ∃ j hij, f i j hij x = 0 := module.direct_limit.of.zero_exact h variables (P : Type u₁) [add_comm_group P] variables (g : Π i, G i → P) [Π i, is_add_group_hom (g i)] variables (Hg : ∀ i j hij x, g j (f i j hij x) = g i x) variables (G f) /-- The universal property of the direct limit: maps from the components to another abelian group that respect the directed system structure (i.e. make some diagram commute) give rise to a unique map out of the direct limit. -/ def lift : direct_limit G f → P := module.direct_limit.lift ℤ ι G (λ i j hij, (add_monoid_hom.of $ f i j hij).to_int_linear_map) (λ i, (add_monoid_hom.of $ g i).to_int_linear_map) Hg variables {G f} instance lift.is_add_group_hom : is_add_group_hom (lift G f P g Hg) := linear_map.is_add_group_hom _ @[simp] lemma lift_of (i x) : lift G f P g Hg (of G f i x) = g i x := module.direct_limit.lift_of _ _ _ @[simp] lemma lift_zero : lift G f P g Hg 0 = 0 := is_add_group_hom.map_zero _ @[simp] lemma lift_add (x y) : lift G f P g Hg (x + y) = lift G f P g Hg x + lift G f P g Hg y := is_add_hom.map_add _ _ _ @[simp] lemma lift_neg (x) : lift G f P g Hg (-x) = -lift G f P g Hg x := is_add_group_hom.map_neg _ _ @[simp] lemma lift_sub (x y) : lift G f P g Hg (x - y) = lift G f P g Hg x - lift G f P g Hg y := is_add_group_hom.map_sub _ _ _ lemma lift_unique [nonempty ι] (F : direct_limit G f → P) [is_add_group_hom F] (x) : F x = @lift _ _ _ G _ f _ P _ (λ i x, F $ of G f i x) (λ i, is_add_group_hom.comp _ _) (λ i j hij x, by dsimp; rw of_f) x := direct_limit.induction_on x $ λ i x, by rw lift_of end direct_limit end add_comm_group namespace ring variables [Π i, comm_ring (G i)] variables (f : Π i j, i ≤ j → G i → G j) open free_comm_ring /-- The direct limit of a directed system is the rings glued together along the maps. -/ def direct_limit : Type (max v w) := (ideal.span { a | (∃ i j H x, of (⟨j, f i j H x⟩ : Σ i, G i) - of ⟨i, x⟩ = a) ∨ (∃ i, of (⟨i, 1⟩ : Σ i, G i) - 1 = a) ∨ (∃ i x y, of (⟨i, x + y⟩ : Σ i, G i) - (of ⟨i, x⟩ + of ⟨i, y⟩) = a) ∨ (∃ i x y, of (⟨i, x * y⟩ : Σ i, G i) - (of ⟨i, x⟩ * of ⟨i, y⟩) = a) }).quotient namespace direct_limit instance : comm_ring (direct_limit G f) := ideal.quotient.comm_ring _ instance : ring (direct_limit G f) := comm_ring.to_ring _ instance : inhabited (direct_limit G f) := ⟨0⟩ /-- The canonical map from a component to the direct limit. -/ def of (i) (x : G i) : direct_limit G f := ideal.quotient.mk _ (of (⟨i, x⟩ : Σ i, G i)) variables {G f} instance of.is_ring_hom (i) : is_ring_hom (of G f i) := { map_one := ideal.quotient.eq.2 $ subset_span $ or.inr $ or.inl ⟨i, rfl⟩, map_mul := λ x y, ideal.quotient.eq.2 $ subset_span $ or.inr $ or.inr $ or.inr ⟨i, x, y, rfl⟩, map_add := λ x y, ideal.quotient.eq.2 $ subset_span $ or.inr $ or.inr $ or.inl ⟨i, x, y, rfl⟩ } @[simp] lemma of_f {i j} (hij) (x) : of G f j (f i j hij x) = of G f i x := ideal.quotient.eq.2 $ subset_span $ or.inl ⟨i, j, hij, x, rfl⟩ @[simp] lemma of_zero (i) : of G f i 0 = 0 := is_ring_hom.map_zero _ @[simp] lemma of_one (i) : of G f i 1 = 1 := is_ring_hom.map_one _ @[simp] lemma of_add (i x y) : of G f i (x + y) = of G f i x + of G f i y := is_ring_hom.map_add _ @[simp] lemma of_neg (i x) : of G f i (-x) = -of G f i x := is_ring_hom.map_neg _ @[simp] lemma of_sub (i x y) : of G f i (x - y) = of G f i x - of G f i y := is_ring_hom.map_sub _ @[simp] lemma of_mul (i x y) : of G f i (x * y) = of G f i x * of G f i y := is_ring_hom.map_mul _ @[simp] lemma of_pow (i x) (n : ℕ) : of G f i (x ^ n) = of G f i x ^ n := is_monoid_hom.map_pow _ _ _ /-- Every element of the direct limit corresponds to some element in some component of the directed system. -/ theorem exists_of [nonempty ι] (z : direct_limit G f) : ∃ i x, of G f i x = z := nonempty.elim (by apply_instance) $ assume ind : ι, quotient.induction_on' z $ λ x, free_abelian_group.induction_on x ⟨ind, 0, of_zero ind⟩ (λ s, multiset.induction_on s ⟨ind, 1, of_one ind⟩ (λ a s ih, let ⟨i, x⟩ := a, ⟨j, y, hs⟩ := ih, ⟨k, hik, hjk⟩ := directed_order.directed i j in ⟨k, f i k hik x * f j k hjk y, by rw [of_mul, of_f, of_f, hs]; refl⟩)) (λ s ⟨i, x, ih⟩, ⟨i, -x, by rw [of_neg, ih]; refl⟩) (λ p q ⟨i, x, ihx⟩ ⟨j, y, ihy⟩, let ⟨k, hik, hjk⟩ := directed_order.directed i j in ⟨k, f i k hik x + f j k hjk y, by rw [of_add, of_f, of_f, ihx, ihy]; refl⟩) section open_locale classical open polynomial variables [Π i j hij, is_ring_hom (f i j hij)] theorem polynomial.exists_of [nonempty ι] (q : polynomial (direct_limit G f)) : ∃ i p, polynomial.map (ring_hom.of $ of G f i) p = q := polynomial.induction_on q (λ z, let ⟨i, x, h⟩ := exists_of z in ⟨i, C x, by rw [map_C, ring_hom.coe_of, h]⟩) (λ q₁ q₂ ⟨i₁, p₁, ih₁⟩ ⟨i₂, p₂, ih₂⟩, let ⟨i, h1, h2⟩ := directed_order.directed i₁ i₂ in ⟨i, p₁.map (ring_hom.of $ f i₁ i h1) + p₂.map (ring_hom.of $ f i₂ i h2), by { rw [polynomial.map_add, map_map, map_map, ← ih₁, ← ih₂], congr' 2; ext x; simp_rw [ring_hom.comp_apply, ring_hom.coe_of, of_f] }⟩) (λ n z ih, let ⟨i, x, h⟩ := exists_of z in ⟨i, C x * X ^ (n + 1), by rw [polynomial.map_mul, map_C, ring_hom.coe_of, h, polynomial.map_pow, map_X]⟩) end @[elab_as_eliminator] theorem induction_on [nonempty ι] {C : direct_limit G f → Prop} (z : direct_limit G f) (ih : ∀ i x, C (of G f i x)) : C z := let ⟨i, x, hx⟩ := exists_of z in hx ▸ ih i x section of_zero_exact open_locale classical variables [Π i j hij, is_ring_hom (f i j hij)] variables [directed_system G f] variables (G f) lemma of.zero_exact_aux2 {x : free_comm_ring Σ i, G i} {s t} (hxs : is_supported x s) {j k} (hj : ∀ z : Σ i, G i, z ∈ s → z.1 ≤ j) (hk : ∀ z : Σ i, G i, z ∈ t → z.1 ≤ k) (hjk : j ≤ k) (hst : s ⊆ t) : f j k hjk (lift (λ ix : s, f ix.1.1 j (hj ix ix.2) ix.1.2) (restriction s x)) = lift (λ ix : t, f ix.1.1 k (hk ix ix.2) ix.1.2) (restriction t x) := begin refine ring.in_closure.rec_on hxs _ _ _ _, { rw [(restriction _).map_one, (free_comm_ring.lift _).map_one, is_ring_hom.map_one (f j k hjk), (restriction _).map_one, (free_comm_ring.lift _).map_one] }, { rw [(restriction _).map_neg, (restriction _).map_one, (free_comm_ring.lift _).map_neg, (free_comm_ring.lift _).map_one, is_ring_hom.map_neg (f j k hjk), is_ring_hom.map_one (f j k hjk), (restriction _).map_neg, (restriction _).map_one, (free_comm_ring.lift _).map_neg, (free_comm_ring.lift _).map_one] }, { rintros _ ⟨p, hps, rfl⟩ n ih, rw [(restriction _).map_mul, (free_comm_ring.lift _).map_mul, is_ring_hom.map_mul (f j k hjk), ih, (restriction _).map_mul, (free_comm_ring.lift _).map_mul, restriction_of, dif_pos hps, lift_of, restriction_of, dif_pos (hst hps), lift_of], dsimp only, rw directed_system.map_map f, refl }, { rintros x y ihx ihy, rw [(restriction _).map_add, (free_comm_ring.lift _).map_add, is_ring_hom.map_add (f j k hjk), ihx, ihy, (restriction _).map_add, (free_comm_ring.lift _).map_add] } end variables {G f} lemma of.zero_exact_aux [nonempty ι] {x : free_comm_ring Σ i, G i} (H : ideal.quotient.mk _ x = (0 : direct_limit G f)) : ∃ j s, ∃ H : (∀ k : Σ i, G i, k ∈ s → k.1 ≤ j), is_supported x s ∧ lift (λ ix : s, f ix.1.1 j (H ix ix.2) ix.1.2) (restriction s x) = (0 : G j) := begin refine span_induction (ideal.quotient.eq_zero_iff_mem.1 H) _ _ _ _, { rintros x (⟨i, j, hij, x, rfl⟩ | ⟨i, rfl⟩ | ⟨i, x, y, rfl⟩ | ⟨i, x, y, rfl⟩), { refine ⟨j, {⟨i, x⟩, ⟨j, f i j hij x⟩}, _, is_supported_sub (is_supported_of.2 $ or.inr rfl) (is_supported_of.2 $ or.inl rfl), _⟩, { rintros k (rfl | ⟨rfl | _⟩), exact hij, refl }, { rw [(restriction _).map_sub, (free_comm_ring.lift _).map_sub, restriction_of, dif_pos, restriction_of, dif_pos, lift_of, lift_of], dsimp only, rw directed_system.map_map f, exact sub_self _, exacts [or.inr rfl, or.inl rfl] } }, { refine ⟨i, {⟨i, 1⟩}, _, is_supported_sub (is_supported_of.2 rfl) is_supported_one, _⟩, { rintros k (rfl|h), refl }, { rw [(restriction _).map_sub, (free_comm_ring.lift _).map_sub, restriction_of, dif_pos, (restriction _).map_one, lift_of, (free_comm_ring.lift _).map_one], dsimp only, rw [is_ring_hom.map_one (f i i _), sub_self], { apply_assumption }, { exact set.mem_singleton _ } } }, { refine ⟨i, {⟨i, x+y⟩, ⟨i, x⟩, ⟨i, y⟩}, _, is_supported_sub (is_supported_of.2 $ or.inl rfl) (is_supported_add (is_supported_of.2 $ or.inr $ or.inl rfl) (is_supported_of.2 $ or.inr $ or.inr rfl)), _⟩, { rintros k (rfl | ⟨rfl | ⟨rfl | hk⟩⟩); refl }, { rw [(restriction _).map_sub, (restriction _).map_add, restriction_of, restriction_of, restriction_of, dif_pos, dif_pos, dif_pos, (free_comm_ring.lift _).map_sub, (free_comm_ring.lift _).map_add, lift_of, lift_of, lift_of], dsimp only, rw is_ring_hom.map_add (f i i _), exact sub_self _, exacts [or.inl rfl, by apply_instance, or.inr (or.inr rfl), or.inr (or.inl rfl)] } }, { refine ⟨i, {⟨i, x*y⟩, ⟨i, x⟩, ⟨i, y⟩}, _, is_supported_sub (is_supported_of.2 $ or.inl rfl) (is_supported_mul (is_supported_of.2 $ or.inr $ or.inl rfl) (is_supported_of.2 $ or.inr $ or.inr rfl)), _⟩, { rintros k (rfl | ⟨rfl | ⟨rfl | hk⟩⟩); refl }, { rw [(restriction _).map_sub, (restriction _).map_mul, restriction_of, restriction_of, restriction_of, dif_pos, dif_pos, dif_pos, (free_comm_ring.lift _).map_sub, (free_comm_ring.lift _).map_mul, lift_of, lift_of, lift_of], dsimp only, rw is_ring_hom.map_mul (f i i _), exacts [sub_self _, or.inl rfl, by apply_instance, or.inr (or.inr rfl), or.inr (or.inl rfl)] } } }, { refine nonempty.elim (by apply_instance) (assume ind : ι, _), refine ⟨ind, ∅, λ _, false.elim, is_supported_zero, _⟩, rw [(restriction _).map_zero, (free_comm_ring.lift _).map_zero] }, { rintros x y ⟨i, s, hi, hxs, ihs⟩ ⟨j, t, hj, hyt, iht⟩, rcases directed_order.directed i j with ⟨k, hik, hjk⟩, have : ∀ z : Σ i, G i, z ∈ s ∪ t → z.1 ≤ k, { rintros z (hz | hz), exact le_trans (hi z hz) hik, exact le_trans (hj z hz) hjk }, refine ⟨k, s ∪ t, this, is_supported_add (is_supported_upwards hxs $ set.subset_union_left s t) (is_supported_upwards hyt $ set.subset_union_right s t), _⟩, { rw [(restriction _).map_add, (free_comm_ring.lift _).map_add, ← of.zero_exact_aux2 G f hxs hi this hik (set.subset_union_left s t), ← of.zero_exact_aux2 G f hyt hj this hjk (set.subset_union_right s t), ihs, is_ring_hom.map_zero (f i k hik), iht, is_ring_hom.map_zero (f j k hjk), zero_add] } }, { rintros x y ⟨j, t, hj, hyt, iht⟩, rw smul_eq_mul, rcases exists_finset_support x with ⟨s, hxs⟩, rcases (s.image sigma.fst).exists_le with ⟨i, hi⟩, rcases directed_order.directed i j with ⟨k, hik, hjk⟩, have : ∀ z : Σ i, G i, z ∈ ↑s ∪ t → z.1 ≤ k, { rintros z (hz | hz), exacts [(hi z.1 $ finset.mem_image.2 ⟨z, hz, rfl⟩).trans hik, (hj z hz).trans hjk] }, refine ⟨k, ↑s ∪ t, this, is_supported_mul (is_supported_upwards hxs $ set.subset_union_left ↑s t) (is_supported_upwards hyt $ set.subset_union_right ↑s t), _⟩, rw [(restriction _).map_mul, (free_comm_ring.lift _).map_mul, ← of.zero_exact_aux2 G f hyt hj this hjk (set.subset_union_right ↑s t), iht, is_ring_hom.map_zero (f j k hjk), mul_zero] } end /-- A component that corresponds to zero in the direct limit is already zero in some bigger module in the directed system. -/ lemma of.zero_exact {i x} (hix : of G f i x = 0) : ∃ j, ∃ hij : i ≤ j, f i j hij x = 0 := by haveI : nonempty ι := ⟨i⟩; exact let ⟨j, s, H, hxs, hx⟩ := of.zero_exact_aux hix in have hixs : (⟨i, x⟩ : Σ i, G i) ∈ s, from is_supported_of.1 hxs, ⟨j, H ⟨i, x⟩ hixs, by rw [restriction_of, dif_pos hixs, lift_of] at hx; exact hx⟩ end of_zero_exact /-- If the maps in the directed system are injective, then the canonical maps from the components to the direct limits are injective. -/ theorem of_injective [Π i j hij, is_ring_hom (f i j hij)] [directed_system G f] (hf : ∀ i j hij, function.injective (f i j hij)) (i) : function.injective (of G f i) := begin suffices : ∀ x, of G f i x = 0 → x = 0, { intros x y hxy, rw ← sub_eq_zero_iff_eq, apply this, rw [is_ring_hom.map_sub (of G f i), hxy, sub_self] }, intros x hx, rcases of.zero_exact hx with ⟨j, hij, hfx⟩, apply hf i j hij, rw [hfx, is_ring_hom.map_zero (f i j hij)] end variables (P : Type u₁) [comm_ring P] variables (g : Π i, G i → P) [Π i, is_ring_hom (g i)] variables (Hg : ∀ i j hij x, g j (f i j hij x) = g i x) include Hg open free_comm_ring variables (G f) /-- The universal property of the direct limit: maps from the components to another ring that respect the directed system structure (i.e. make some diagram commute) give rise to a unique map out of the direct limit. We don't use this function as the canonical form because Lean 3 fails to automatically coerce it to a function; use `lift` instead. -/ def lift_hom : direct_limit G f →+* P := ideal.quotient.lift _ (free_comm_ring.lift $ λ x, g x.1 x.2) begin suffices : ideal.span _ ≤ ideal.comap (free_comm_ring.lift (λ (x : Σ (i : ι), G i), g (x.fst) (x.snd))) ⊥, { intros x hx, exact (mem_bot P).1 (this hx) }, rw ideal.span_le, intros x hx, rw [mem_coe, ideal.mem_comap, mem_bot], rcases hx with ⟨i, j, hij, x, rfl⟩ | ⟨i, rfl⟩ | ⟨i, x, y, rfl⟩ | ⟨i, x, y, rfl⟩; simp only [ring_hom.map_sub, lift_of, Hg, ring_hom.map_one, ring_hom.map_add, ring_hom.map_mul, is_ring_hom.map_one (g i), is_ring_hom.map_add (g i), is_ring_hom.map_mul (g i), sub_self] end /-- The universal property of the direct limit: maps from the components to another ring that respect the directed system structure (i.e. make some diagram commute) give rise to a unique map out of the direct limit. -/ def lift : direct_limit G f → P := lift_hom G f P g Hg instance lift_is_ring_hom : is_ring_hom (lift G f P g Hg) := (lift_hom G f P g Hg).is_ring_hom variables {G f} omit Hg @[simp] lemma lift_of (i x) : lift G f P g Hg (of G f i x) = g i x := free_comm_ring.lift_of _ _ @[simp] lemma lift_zero : lift G f P g Hg 0 = 0 := (lift_hom G f P g Hg).map_zero @[simp] lemma lift_one : lift G f P g Hg 1 = 1 := (lift_hom G f P g Hg).map_one @[simp] lemma lift_add (x y) : lift G f P g Hg (x + y) = lift G f P g Hg x + lift G f P g Hg y := (lift_hom G f P g Hg).map_add x y @[simp] lemma lift_neg (x) : lift G f P g Hg (-x) = -lift G f P g Hg x := (lift_hom G f P g Hg).map_neg x @[simp] lemma lift_sub (x y) : lift G f P g Hg (x - y) = lift G f P g Hg x - lift G f P g Hg y := (lift_hom G f P g Hg).map_sub x y @[simp] lemma lift_mul (x y) : lift G f P g Hg (x * y) = lift G f P g Hg x * lift G f P g Hg y := (lift_hom G f P g Hg).map_mul x y @[simp] lemma lift_pow (x) (n : ℕ) : lift G f P g Hg (x ^ n) = lift G f P g Hg x ^ n := (lift_hom G f P g Hg).map_pow x n local attribute [instance, priority 100] is_ring_hom.comp theorem lift_unique [nonempty ι] (F : direct_limit G f → P) [is_ring_hom F] (x) : F x = lift G f P (λ i x, F $ of G f i x) (λ i j hij x, by rw [of_f]) x := direct_limit.induction_on x $ λ i x, by rw lift_of end direct_limit end ring namespace field variables [nonempty ι] [Π i, field (G i)] variables (f : Π i j, i ≤ j → G i → G j) namespace direct_limit instance nontrivial [Π i j hij, is_ring_hom (f i j hij)] [directed_system G f] : nontrivial (ring.direct_limit G f) := ⟨⟨0, 1, nonempty.elim (by apply_instance) $ assume i : ι, begin change (0 : ring.direct_limit G f) ≠ 1, rw ← ring.direct_limit.of_one, intros H, rcases ring.direct_limit.of.zero_exact H.symm with ⟨j, hij, hf⟩, rw is_ring_hom.map_one (f i j hij) at hf, exact one_ne_zero hf end ⟩⟩ theorem exists_inv {p : ring.direct_limit G f} : p ≠ 0 → ∃ y, p * y = 1 := ring.direct_limit.induction_on p $ λ i x H, ⟨ring.direct_limit.of G f i (x⁻¹), by erw [← ring.direct_limit.of_mul, mul_inv_cancel (assume h : x = 0, H $ by rw [h, ring.direct_limit.of_zero]), ring.direct_limit.of_one]⟩ section open_locale classical /-- Noncomputable multiplicative inverse in a direct limit of fields. -/ noncomputable def inv (p : ring.direct_limit G f) : ring.direct_limit G f := if H : p = 0 then 0 else classical.some (direct_limit.exists_inv G f H) protected theorem mul_inv_cancel {p : ring.direct_limit G f} (hp : p ≠ 0) : p * inv G f p = 1 := by rw [inv, dif_neg hp, classical.some_spec (direct_limit.exists_inv G f hp)] protected theorem inv_mul_cancel {p : ring.direct_limit G f} (hp : p ≠ 0) : inv G f p * p = 1 := by rw [_root_.mul_comm, direct_limit.mul_inv_cancel G f hp] /-- Noncomputable field structure on the direct limit of fields. -/ protected noncomputable def field [Π i j hij, is_ring_hom (f i j hij)] [directed_system G f] : field (ring.direct_limit G f) := { inv := inv G f, mul_inv_cancel := λ p, direct_limit.mul_inv_cancel G f, inv_zero := dif_pos rfl, .. ring.direct_limit.comm_ring G f, .. direct_limit.nontrivial G f } end end direct_limit end field
8f798d16cd04403ca9ca28bb4c7c711c8609a742
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/computability/primrec_auto.lean
3b0ca666c20e7f443c556679fe22a753056414aa
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
39,886
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.equiv.list import Mathlib.logic.function.iterate import Mathlib.PostPort universes u_1 l u_2 u_3 u_5 u_4 namespace Mathlib /-! # The primitive recursive functions The primitive recursive functions are the least collection of functions `nat → nat` which are closed under projections (using the mkpair pairing function), composition, zero, successor, and primitive recursion (i.e. nat.rec where the motive is C n := nat). We can extend this definition to a large class of basic types by using canonical encodings of types as natural numbers (Gödel numbering), which we implement through the type class `encodable`. (More precisely, we need that the composition of encode with decode yields a primitive recursive function, so we have the `primcodable` type class for this.) ## References * [Mario Carneiro, *Formalizing computability theory via partial recursive functions*][carneiro2019] -/ namespace nat def elim {C : Sort u_1} : C → (ℕ → C → C) → ℕ → C := Nat.rec @[simp] theorem elim_zero {C : Sort u_1} (a : C) (f : ℕ → C → C) : elim a f 0 = a := rfl @[simp] theorem elim_succ {C : Sort u_1} (a : C) (f : ℕ → C → C) (n : ℕ) : elim a f (Nat.succ n) = f n (elim a f n) := rfl def cases {C : Sort u_1} (a : C) (f : ℕ → C) : ℕ → C := elim a fun (n : ℕ) (_x : C) => f n @[simp] theorem cases_zero {C : Sort u_1} (a : C) (f : ℕ → C) : cases a f 0 = a := rfl @[simp] theorem cases_succ {C : Sort u_1} (a : C) (f : ℕ → C) (n : ℕ) : cases a f (Nat.succ n) = f n := rfl @[simp] def unpaired {α : Sort u_1} (f : ℕ → ℕ → α) (n : ℕ) : α := f (prod.fst (unpair n)) (prod.snd (unpair n)) /-- The primitive recursive functions `ℕ → ℕ`. -/ inductive primrec : (ℕ → ℕ) → Prop where | zero : primrec fun (n : ℕ) => 0 | succ : primrec Nat.succ | left : primrec fun (n : ℕ) => prod.fst (unpair n) | right : primrec fun (n : ℕ) => prod.snd (unpair n) | pair : ∀ {f g : ℕ → ℕ}, primrec f → primrec g → primrec fun (n : ℕ) => mkpair (f n) (g n) | comp : ∀ {f g : ℕ → ℕ}, primrec f → primrec g → primrec fun (n : ℕ) => f (g n) | prec : ∀ {f g : ℕ → ℕ}, primrec f → primrec g → primrec (unpaired fun (z n : ℕ) => elim (f z) (fun (y IH : ℕ) => g (mkpair z (mkpair y IH))) n) namespace primrec theorem of_eq {f : ℕ → ℕ} {g : ℕ → ℕ} (hf : primrec f) (H : ∀ (n : ℕ), f n = g n) : primrec g := funext H ▸ hf theorem const (n : ℕ) : primrec fun (_x : ℕ) => n := sorry protected theorem id : primrec id := sorry theorem prec1 {f : ℕ → ℕ} (m : ℕ) (hf : primrec f) : primrec fun (n : ℕ) => elim m (fun (y IH : ℕ) => f (mkpair y IH)) n := sorry theorem cases1 {f : ℕ → ℕ} (m : ℕ) (hf : primrec f) : primrec (cases m f) := sorry theorem cases {f : ℕ → ℕ} {g : ℕ → ℕ} (hf : primrec f) (hg : primrec g) : primrec (unpaired fun (z n : ℕ) => cases (f z) (fun (y : ℕ) => g (mkpair z y)) n) := sorry protected theorem swap : primrec (unpaired (function.swap mkpair)) := sorry theorem swap' {f : ℕ → ℕ → ℕ} (hf : primrec (unpaired f)) : primrec (unpaired (function.swap f)) := sorry theorem pred : primrec Nat.pred := sorry theorem add : primrec (unpaired Add.add) := sorry theorem sub : primrec (unpaired Sub.sub) := sorry theorem mul : primrec (unpaired Mul.mul) := sorry theorem pow : primrec (unpaired pow) := sorry end primrec end nat /-- A `primcodable` type is an `encodable` type for which the encode/decode functions are primitive recursive. -/ class primcodable (α : Type u_1) extends encodable α where prim : nat.primrec fun (n : ℕ) => encodable.encode (encodable.decode α n) namespace primcodable protected instance of_denumerable (α : Type u_1) [denumerable α] : primcodable α := mk sorry def of_equiv (α : Type u_1) {β : Type u_2} [primcodable α] (e : β ≃ α) : primcodable β := mk sorry protected instance empty : primcodable empty := mk nat.primrec.zero protected instance unit : primcodable PUnit := mk sorry protected instance option {α : Type u_1} [h : primcodable α] : primcodable (Option α) := mk sorry protected instance bool : primcodable Bool := mk sorry end primcodable /-- `primrec f` means `f` is primitive recursive (after encoding its input and output as natural numbers). -/ def primrec {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] (f : α → β) := nat.primrec fun (n : ℕ) => encodable.encode (option.map f (encodable.decode α n)) namespace primrec protected theorem encode {α : Type u_1} [primcodable α] : primrec encodable.encode := sorry protected theorem decode {α : Type u_1} [primcodable α] : primrec (encodable.decode α) := nat.primrec.comp nat.primrec.succ (primcodable.prim α) theorem dom_denumerable {α : Type u_1} {β : Type u_2} [denumerable α] [primcodable β] {f : α → β} : primrec f ↔ nat.primrec fun (n : ℕ) => encodable.encode (f (denumerable.of_nat α n)) := sorry theorem nat_iff {f : ℕ → ℕ} : primrec f ↔ nat.primrec f := dom_denumerable theorem encdec {α : Type u_1} [primcodable α] : primrec fun (n : ℕ) => encodable.encode (encodable.decode α n) := iff.mpr nat_iff (primcodable.prim α) theorem option_some {α : Type u_1} [primcodable α] : primrec some := sorry theorem of_eq {α : Type u_1} {σ : Type u_3} [primcodable α] [primcodable σ] {f : α → σ} {g : α → σ} (hf : primrec f) (H : ∀ (n : α), f n = g n) : primrec g := funext H ▸ hf theorem const {α : Type u_1} {σ : Type u_3} [primcodable α] [primcodable σ] (x : σ) : primrec fun (a : α) => x := sorry protected theorem id {α : Type u_1} [primcodable α] : primrec id := sorry theorem comp {α : Type u_1} {β : Type u_2} {σ : Type u_3} [primcodable α] [primcodable β] [primcodable σ] {f : β → σ} {g : α → β} (hf : primrec f) (hg : primrec g) : primrec fun (a : α) => f (g a) := sorry theorem succ : primrec Nat.succ := iff.mpr nat_iff nat.primrec.succ theorem pred : primrec Nat.pred := iff.mpr nat_iff nat.primrec.pred theorem encode_iff {α : Type u_1} {σ : Type u_3} [primcodable α] [primcodable σ] {f : α → σ} : (primrec fun (a : α) => encodable.encode (f a)) ↔ primrec f := sorry theorem of_nat_iff {α : Type u_1} {β : Type u_2} [denumerable α] [primcodable β] {f : α → β} : primrec f ↔ primrec fun (n : ℕ) => f (denumerable.of_nat α n) := iff.trans dom_denumerable (iff.trans (iff.symm nat_iff) encode_iff) protected theorem of_nat (α : Type u_1) [denumerable α] : primrec (denumerable.of_nat α) := iff.mp of_nat_iff primrec.id theorem option_some_iff {α : Type u_1} {σ : Type u_3} [primcodable α] [primcodable σ] {f : α → σ} : (primrec fun (a : α) => some (f a)) ↔ primrec f := { mp := fun (h : primrec fun (a : α) => some (f a)) => iff.mp encode_iff (comp pred (iff.mpr encode_iff h)), mpr := comp option_some } theorem of_equiv {α : Type u_1} [primcodable α] {β : Type u_2} {e : β ≃ α} : primrec ⇑e := iff.mp encode_iff primrec.encode theorem of_equiv_symm {α : Type u_1} [primcodable α] {β : Type u_2} {e : β ≃ α} : primrec ⇑(equiv.symm e) := sorry theorem of_equiv_iff {α : Type u_1} {σ : Type u_3} [primcodable α] [primcodable σ] {β : Type u_2} (e : β ≃ α) {f : σ → β} : (primrec fun (a : σ) => coe_fn e (f a)) ↔ primrec f := sorry theorem of_equiv_symm_iff {α : Type u_1} {σ : Type u_3} [primcodable α] [primcodable σ] {β : Type u_2} (e : β ≃ α) {f : σ → α} : (primrec fun (a : σ) => coe_fn (equiv.symm e) (f a)) ↔ primrec f := sorry end primrec namespace primcodable protected instance prod {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] : primcodable (α × β) := mk sorry end primcodable namespace primrec theorem fst {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] : primrec prod.fst := sorry theorem snd {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] : primrec prod.snd := sorry theorem pair {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α] [primcodable β] [primcodable γ] {f : α → β} {g : α → γ} (hf : primrec f) (hg : primrec g) : primrec fun (a : α) => (f a, g a) := sorry theorem unpair : primrec nat.unpair := sorry theorem list_nth₁ {α : Type u_1} [primcodable α] (l : List α) : primrec (list.nth l) := sorry end primrec /-- `primrec₂ f` means `f` is a binary primitive recursive function. This is technically unnecessary since we can always curry all the arguments together, but there are enough natural two-arg functions that it is convenient to express this directly. -/ def primrec₂ {α : Type u_1} {β : Type u_2} {σ : Type u_3} [primcodable α] [primcodable β] [primcodable σ] (f : α → β → σ) := primrec fun (p : α × β) => f (prod.fst p) (prod.snd p) /-- `primrec_pred p` means `p : α → Prop` is a (decidable) primitive recursive predicate, which is to say that `to_bool ∘ p : α → bool` is primitive recursive. -/ def primrec_pred {α : Type u_1} [primcodable α] (p : α → Prop) [decidable_pred p] := primrec fun (a : α) => to_bool (p a) /-- `primrec_rel p` means `p : α → β → Prop` is a (decidable) primitive recursive relation, which is to say that `to_bool ∘ p : α → β → bool` is primitive recursive. -/ def primrec_rel {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] (s : α → β → Prop) [(a : α) → (b : β) → Decidable (s a b)] := primrec₂ fun (a : α) (b : β) => to_bool (s a b) namespace primrec₂ theorem of_eq {α : Type u_1} {β : Type u_2} {σ : Type u_3} [primcodable α] [primcodable β] [primcodable σ] {f : α → β → σ} {g : α → β → σ} (hg : primrec₂ f) (H : ∀ (a : α) (b : β), f a b = g a b) : primrec₂ g := (funext fun (a : α) => funext fun (b : β) => H a b) ▸ hg theorem const {α : Type u_1} {β : Type u_2} {σ : Type u_3} [primcodable α] [primcodable β] [primcodable σ] (x : σ) : primrec₂ fun (a : α) (b : β) => x := primrec.const x protected theorem pair {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] : primrec₂ Prod.mk := primrec.pair primrec.fst primrec.snd theorem left {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] : primrec₂ fun (a : α) (b : β) => a := primrec.fst theorem right {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] : primrec₂ fun (a : α) (b : β) => b := primrec.snd theorem mkpair : primrec₂ nat.mkpair := sorry theorem unpaired {α : Type u_1} [primcodable α] {f : ℕ → ℕ → α} : primrec (nat.unpaired f) ↔ primrec₂ f := sorry theorem unpaired' {f : ℕ → ℕ → ℕ} : nat.primrec (nat.unpaired f) ↔ primrec₂ f := iff.trans (iff.symm primrec.nat_iff) unpaired theorem encode_iff {α : Type u_1} {β : Type u_2} {σ : Type u_3} [primcodable α] [primcodable β] [primcodable σ] {f : α → β → σ} : (primrec₂ fun (a : α) (b : β) => encodable.encode (f a b)) ↔ primrec₂ f := primrec.encode_iff theorem option_some_iff {α : Type u_1} {β : Type u_2} {σ : Type u_3} [primcodable α] [primcodable β] [primcodable σ] {f : α → β → σ} : (primrec₂ fun (a : α) (b : β) => some (f a b)) ↔ primrec₂ f := primrec.option_some_iff theorem of_nat_iff {α : Type u_1} {β : Type u_2} {σ : Type u_3} [denumerable α] [denumerable β] [primcodable σ] {f : α → β → σ} : primrec₂ f ↔ primrec₂ fun (m n : ℕ) => f (denumerable.of_nat α m) (denumerable.of_nat β n) := sorry theorem uncurry {α : Type u_1} {β : Type u_2} {σ : Type u_3} [primcodable α] [primcodable β] [primcodable σ] {f : α → β → σ} : primrec (function.uncurry f) ↔ primrec₂ f := sorry theorem curry {α : Type u_1} {β : Type u_2} {σ : Type u_3} [primcodable α] [primcodable β] [primcodable σ] {f : α × β → σ} : primrec₂ (function.curry f) ↔ primrec f := sorry end primrec₂ theorem primrec.comp₂ {α : Type u_1} {β : Type u_2} {γ : Type u_3} {σ : Type u_5} [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] {f : γ → σ} {g : α → β → γ} (hf : primrec f) (hg : primrec₂ g) : primrec₂ fun (a : α) (b : β) => f (g a b) := primrec.comp hf hg theorem primrec₂.comp {α : Type u_1} {β : Type u_2} {γ : Type u_3} {σ : Type u_5} [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] {f : β → γ → σ} {g : α → β} {h : α → γ} (hf : primrec₂ f) (hg : primrec g) (hh : primrec h) : primrec fun (a : α) => f (g a) (h a) := primrec.comp hf (primrec.pair hg hh) theorem primrec₂.comp₂ {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} {σ : Type u_5} [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ] {f : γ → δ → σ} {g : α → β → γ} {h : α → β → δ} (hf : primrec₂ f) (hg : primrec₂ g) (hh : primrec₂ h) : primrec₂ fun (a : α) (b : β) => f (g a b) (h a b) := primrec₂.comp hf hg hh theorem primrec_pred.comp {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {p : β → Prop} [decidable_pred p] {f : α → β} : primrec_pred p → primrec f → primrec_pred fun (a : α) => p (f a) := primrec.comp theorem primrec_rel.comp {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α] [primcodable β] [primcodable γ] {R : β → γ → Prop} [(a : β) → (b : γ) → Decidable (R a b)] {f : α → β} {g : α → γ} : primrec_rel R → primrec f → primrec g → primrec_pred fun (a : α) => R (f a) (g a) := primrec₂.comp theorem primrec_rel.comp₂ {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] {R : γ → δ → Prop} [(a : γ) → (b : δ) → Decidable (R a b)] {f : α → β → γ} {g : α → β → δ} : primrec_rel R → primrec₂ f → primrec₂ g → primrec_rel fun (a : α) (b : β) => R (f a b) (g a b) := primrec_rel.comp theorem primrec_pred.of_eq {α : Type u_1} [primcodable α] {p : α → Prop} {q : α → Prop} [decidable_pred p] [decidable_pred q] (hp : primrec_pred p) (H : ∀ (a : α), p a ↔ q a) : primrec_pred q := primrec.of_eq hp fun (a : α) => to_bool_congr (H a) theorem primrec_rel.of_eq {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {r : α → β → Prop} {s : α → β → Prop} [(a : α) → (b : β) → Decidable (r a b)] [(a : α) → (b : β) → Decidable (s a b)] (hr : primrec_rel r) (H : ∀ (a : α) (b : β), r a b ↔ s a b) : primrec_rel s := primrec₂.of_eq hr fun (a : α) (b : β) => to_bool_congr (H a b) namespace primrec₂ theorem swap {α : Type u_1} {β : Type u_2} {σ : Type u_3} [primcodable α] [primcodable β] [primcodable σ] {f : α → β → σ} (h : primrec₂ f) : primrec₂ (function.swap f) := comp₂ h right left theorem nat_iff {α : Type u_1} {β : Type u_2} {σ : Type u_3} [primcodable α] [primcodable β] [primcodable σ] {f : α → β → σ} : primrec₂ f ↔ nat.primrec (nat.unpaired fun (m n : ℕ) => encodable.encode (option.bind (encodable.decode α m) fun (a : α) => option.map (f a) (encodable.decode β n))) := sorry theorem nat_iff' {α : Type u_1} {β : Type u_2} {σ : Type u_3} [primcodable α] [primcodable β] [primcodable σ] {f : α → β → σ} : primrec₂ f ↔ primrec₂ fun (m n : ℕ) => option.bind (encodable.decode α m) fun (a : α) => option.map (f a) (encodable.decode β n) := iff.trans nat_iff (iff.trans unpaired' encode_iff) end primrec₂ namespace primrec theorem to₂ {α : Type u_1} {β : Type u_2} {σ : Type u_5} [primcodable α] [primcodable β] [primcodable σ] {f : α × β → σ} (hf : primrec f) : primrec₂ fun (a : α) (b : β) => f (a, b) := of_eq hf fun (_x : α × β) => (fun (_a : α × β) => prod.cases_on _a fun (fst : α) (snd : β) => idRhs (f (fst, snd) = f (fst, snd)) rfl) _x theorem nat_elim {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {f : α → β} {g : α → ℕ × β → β} (hf : primrec f) (hg : primrec₂ g) : primrec₂ fun (a : α) (n : ℕ) => nat.elim (f a) (fun (n : ℕ) (IH : β) => g a (n, IH)) n := sorry theorem nat_elim' {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {f : α → ℕ} {g : α → β} {h : α → ℕ × β → β} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec fun (a : α) => nat.elim (g a) (fun (n : ℕ) (IH : β) => h a (n, IH)) (f a) := primrec₂.comp (nat_elim hg hh) primrec.id hf theorem nat_elim₁ {α : Type u_1} [primcodable α] {f : ℕ → α → α} (a : α) (hf : primrec₂ f) : primrec (nat.elim a f) := nat_elim' primrec.id (const a) (comp₂ hf primrec₂.right) theorem nat_cases' {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {f : α → β} {g : α → ℕ → β} (hf : primrec f) (hg : primrec₂ g) : primrec₂ fun (a : α) => nat.cases (f a) (g a) := nat_elim hf (primrec₂.comp₂ hg primrec₂.left (comp₂ fst primrec₂.right)) theorem nat_cases {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {f : α → ℕ} {g : α → β} {h : α → ℕ → β} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec fun (a : α) => nat.cases (g a) (h a) (f a) := primrec₂.comp (nat_cases' hg hh) primrec.id hf theorem nat_cases₁ {α : Type u_1} [primcodable α] {f : ℕ → α} (a : α) (hf : primrec f) : primrec (nat.cases a f) := nat_cases primrec.id (const a) (comp₂ hf primrec₂.right) theorem nat_iterate {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {f : α → ℕ} {g : α → β} {h : α → β → β} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec fun (a : α) => nat.iterate (h a) (f a) (g a) := sorry theorem option_cases {α : Type u_1} {β : Type u_2} {σ : Type u_5} [primcodable α] [primcodable β] [primcodable σ] {o : α → Option β} {f : α → σ} {g : α → β → σ} (ho : primrec o) (hf : primrec f) (hg : primrec₂ g) : primrec fun (a : α) => option.cases_on (o a) (f a) (g a) := sorry theorem option_bind {α : Type u_1} {β : Type u_2} {σ : Type u_5} [primcodable α] [primcodable β] [primcodable σ] {f : α → Option β} {g : α → β → Option σ} (hf : primrec f) (hg : primrec₂ g) : primrec fun (a : α) => option.bind (f a) (g a) := sorry theorem option_bind₁ {α : Type u_1} {σ : Type u_5} [primcodable α] [primcodable σ] {f : α → Option σ} (hf : primrec f) : primrec fun (o : Option α) => option.bind o f := option_bind primrec.id (to₂ (comp hf snd)) theorem option_map {α : Type u_1} {β : Type u_2} {σ : Type u_5} [primcodable α] [primcodable β] [primcodable σ] {f : α → Option β} {g : α → β → σ} (hf : primrec f) (hg : primrec₂ g) : primrec fun (a : α) => option.map (g a) (f a) := option_bind hf (comp₂ option_some hg) theorem option_map₁ {α : Type u_1} {σ : Type u_5} [primcodable α] [primcodable σ] {f : α → σ} (hf : primrec f) : primrec (option.map f) := option_map primrec.id (to₂ (comp hf snd)) theorem option_iget {α : Type u_1} [primcodable α] [Inhabited α] : primrec option.iget := sorry theorem option_is_some {α : Type u_1} [primcodable α] : primrec option.is_some := sorry theorem option_get_or_else {α : Type u_1} [primcodable α] : primrec₂ option.get_or_else := sorry theorem bind_decode_iff {α : Type u_1} {β : Type u_2} {σ : Type u_5} [primcodable α] [primcodable β] [primcodable σ] {f : α → β → Option σ} : (primrec₂ fun (a : α) (n : ℕ) => option.bind (encodable.decode β n) (f a)) ↔ primrec₂ f := sorry theorem map_decode_iff {α : Type u_1} {β : Type u_2} {σ : Type u_5} [primcodable α] [primcodable β] [primcodable σ] {f : α → β → σ} : (primrec₂ fun (a : α) (n : ℕ) => option.map (f a) (encodable.decode β n)) ↔ primrec₂ f := iff.trans bind_decode_iff primrec₂.option_some_iff theorem nat_add : primrec₂ Add.add := iff.mp primrec₂.unpaired' nat.primrec.add theorem nat_sub : primrec₂ Sub.sub := iff.mp primrec₂.unpaired' nat.primrec.sub theorem nat_mul : primrec₂ Mul.mul := iff.mp primrec₂.unpaired' nat.primrec.mul theorem cond {α : Type u_1} {σ : Type u_5} [primcodable α] [primcodable σ] {c : α → Bool} {f : α → σ} {g : α → σ} (hc : primrec c) (hf : primrec f) (hg : primrec g) : primrec fun (a : α) => cond (c a) (f a) (g a) := sorry theorem ite {α : Type u_1} {σ : Type u_5} [primcodable α] [primcodable σ] {c : α → Prop} [decidable_pred c] {f : α → σ} {g : α → σ} (hc : primrec_pred c) (hf : primrec f) (hg : primrec g) : primrec fun (a : α) => ite (c a) (f a) (g a) := sorry theorem nat_le : primrec_rel LessEq := sorry theorem nat_min : primrec₂ min := ite nat_le fst snd theorem nat_max : primrec₂ max := ite (primrec_rel.comp nat_le snd fst) fst snd theorem dom_bool {α : Type u_1} [primcodable α] (f : Bool → α) : primrec f := of_eq (cond primrec.id (const (f tt)) (const (f false))) fun (b : Bool) => bool.cases_on b (Eq.refl (cond (id false) (f tt) (f false))) (Eq.refl (cond (id tt) (f tt) (f false))) theorem dom_bool₂ {α : Type u_1} [primcodable α] (f : Bool → Bool → α) : primrec₂ f := sorry protected theorem bnot : primrec bnot := dom_bool bnot protected theorem band : primrec₂ band := dom_bool₂ band protected theorem bor : primrec₂ bor := dom_bool₂ bor protected theorem not {α : Type u_1} [primcodable α] {p : α → Prop} [decidable_pred p] (hp : primrec_pred p) : primrec_pred fun (a : α) => ¬p a := sorry protected theorem and {α : Type u_1} [primcodable α] {p : α → Prop} {q : α → Prop} [decidable_pred p] [decidable_pred q] (hp : primrec_pred p) (hq : primrec_pred q) : primrec_pred fun (a : α) => p a ∧ q a := sorry protected theorem or {α : Type u_1} [primcodable α] {p : α → Prop} {q : α → Prop} [decidable_pred p] [decidable_pred q] (hp : primrec_pred p) (hq : primrec_pred q) : primrec_pred fun (a : α) => p a ∨ q a := sorry protected theorem eq {α : Type u_1} [primcodable α] [DecidableEq α] : primrec_rel Eq := sorry theorem nat_lt : primrec_rel Less := sorry theorem option_guard {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {p : α → β → Prop} [(a : α) → (b : β) → Decidable (p a b)] (hp : primrec_rel p) {f : α → β} (hf : primrec f) : primrec fun (a : α) => option.guard (p a) (f a) := ite (primrec_rel.comp hp primrec.id hf) (iff.mpr option_some_iff hf) (const none) theorem option_orelse {α : Type u_1} [primcodable α] : primrec₂ has_orelse.orelse := sorry protected theorem decode2 {α : Type u_1} [primcodable α] : primrec (encodable.decode2 α) := option_bind primrec.decode (option_guard (primrec_rel.comp primrec.eq (iff.mpr encode_iff snd) (comp fst fst)) snd) theorem list_find_index₁ {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {p : α → β → Prop} [(a : α) → (b : β) → Decidable (p a b)] (hp : primrec_rel p) (l : List β) : primrec fun (a : α) => list.find_index (p a) l := sorry theorem list_index_of₁ {α : Type u_1} [primcodable α] [DecidableEq α] (l : List α) : primrec fun (a : α) => list.index_of a l := list_find_index₁ primrec.eq l theorem dom_fintype {α : Type u_1} {σ : Type u_5} [primcodable α] [primcodable σ] [fintype α] (f : α → σ) : primrec f := sorry theorem nat_bodd_div2 : primrec nat.bodd_div2 := sorry theorem nat_bodd : primrec nat.bodd := comp fst nat_bodd_div2 theorem nat_div2 : primrec nat.div2 := comp snd nat_bodd_div2 theorem nat_bit0 : primrec bit0 := primrec₂.comp nat_add primrec.id primrec.id theorem nat_bit1 : primrec bit1 := primrec₂.comp nat_add nat_bit0 (const 1) theorem nat_bit : primrec₂ nat.bit := sorry theorem nat_div_mod : primrec₂ fun (n k : ℕ) => (n / k, n % k) := sorry theorem nat_div : primrec₂ Div.div := comp₂ fst nat_div_mod theorem nat_mod : primrec₂ Mod.mod := comp₂ snd nat_div_mod end primrec namespace primcodable protected instance sum {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] : primcodable (α ⊕ β) := mk sorry protected instance list {α : Type u_1} [primcodable α] : primcodable (List α) := mk sorry end primcodable namespace primrec theorem sum_inl {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] : primrec sum.inl := iff.mp encode_iff (comp nat_bit0 primrec.encode) theorem sum_inr {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] : primrec sum.inr := iff.mp encode_iff (comp nat_bit1 primrec.encode) theorem sum_cases {α : Type u_1} {β : Type u_2} {γ : Type u_3} {σ : Type u_4} [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] {f : α → β ⊕ γ} {g : α → β → σ} {h : α → γ → σ} (hf : primrec f) (hg : primrec₂ g) (hh : primrec₂ h) : primrec fun (a : α) => sum.cases_on (f a) (g a) (h a) := sorry theorem list_cons {α : Type u_1} [primcodable α] : primrec₂ List.cons := list_cons' (primcodable.prim (List α)) theorem list_cases {α : Type u_1} {β : Type u_2} {σ : Type u_4} [primcodable α] [primcodable β] [primcodable σ] {f : α → List β} {g : α → σ} {h : α → β × List β → σ} : primrec f → primrec g → primrec₂ h → primrec fun (a : α) => list.cases_on (f a) (g a) fun (b : β) (l : List β) => h a (b, l) := list_cases' (primcodable.prim (List β)) theorem list_foldl {α : Type u_1} {β : Type u_2} {σ : Type u_4} [primcodable α] [primcodable β] [primcodable σ] {f : α → List β} {g : α → σ} {h : α → σ × β → σ} : primrec f → primrec g → primrec₂ h → primrec fun (a : α) => list.foldl (fun (s : σ) (b : β) => h a (s, b)) (g a) (f a) := list_foldl' (primcodable.prim (List β)) theorem list_reverse {α : Type u_1} [primcodable α] : primrec list.reverse := list_reverse' (primcodable.prim (List α)) theorem list_foldr {α : Type u_1} {β : Type u_2} {σ : Type u_4} [primcodable α] [primcodable β] [primcodable σ] {f : α → List β} {g : α → σ} {h : α → β × σ → σ} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec fun (a : α) => list.foldr (fun (b : β) (s : σ) => h a (b, s)) (g a) (f a) := sorry theorem list_head' {α : Type u_1} [primcodable α] : primrec list.head' := sorry theorem list_head {α : Type u_1} [primcodable α] [Inhabited α] : primrec list.head := of_eq (comp option_iget list_head') fun (l : List α) => Eq.symm (list.head_eq_head' l) theorem list_tail {α : Type u_1} [primcodable α] : primrec list.tail := sorry theorem list_rec {α : Type u_1} {β : Type u_2} {σ : Type u_4} [primcodable α] [primcodable β] [primcodable σ] {f : α → List β} {g : α → σ} {h : α → β × List β × σ → σ} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec fun (a : α) => list.rec_on (f a) (g a) fun (b : β) (l : List β) (IH : σ) => h a (b, l, IH) := sorry theorem list_nth {α : Type u_1} [primcodable α] : primrec₂ list.nth := sorry theorem list_inth {α : Type u_1} [primcodable α] [Inhabited α] : primrec₂ list.inth := comp₂ option_iget list_nth theorem list_append {α : Type u_1} [primcodable α] : primrec₂ append := sorry theorem list_concat {α : Type u_1} [primcodable α] : primrec₂ fun (l : List α) (a : α) => l ++ [a] := primrec₂.comp list_append fst (primrec₂.comp list_cons snd (const [])) theorem list_map {α : Type u_1} {β : Type u_2} {σ : Type u_4} [primcodable α] [primcodable β] [primcodable σ] {f : α → List β} {g : α → β → σ} (hf : primrec f) (hg : primrec₂ g) : primrec fun (a : α) => list.map (g a) (f a) := sorry theorem list_range : primrec list.range := sorry theorem list_join {α : Type u_1} [primcodable α] : primrec list.join := sorry theorem list_length {α : Type u_1} [primcodable α] : primrec list.length := sorry theorem list_find_index {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {f : α → List β} {p : α → β → Prop} [(a : α) → (b : β) → Decidable (p a b)] (hf : primrec f) (hp : primrec_rel p) : primrec fun (a : α) => list.find_index (p a) (f a) := sorry theorem list_index_of {α : Type u_1} [primcodable α] [DecidableEq α] : primrec₂ list.index_of := to₂ (list_find_index snd (primrec_rel.comp₂ primrec.eq (to₂ (comp fst fst)) (to₂ snd))) theorem nat_strong_rec {α : Type u_1} {σ : Type u_4} [primcodable α] [primcodable σ] (f : α → ℕ → σ) {g : α → List σ → Option σ} (hg : primrec₂ g) (H : ∀ (a : α) (n : ℕ), g a (list.map (f a) (list.range n)) = some (f a n)) : primrec₂ f := sorry end primrec namespace primcodable def subtype {α : Type u_1} [primcodable α] {p : α → Prop} [decidable_pred p] (hp : primrec_pred p) : primcodable (Subtype p) := mk sorry protected instance fin {n : ℕ} : primcodable (fin n) := of_equiv (Subtype fun (a : ℕ) => id a < n) (equiv.fin_equiv_subtype n) protected instance vector {α : Type u_1} [primcodable α] {n : ℕ} : primcodable (vector α n) := subtype sorry protected instance fin_arrow {α : Type u_1} [primcodable α] {n : ℕ} : primcodable (fin n → α) := of_equiv (vector α n) (equiv.symm (equiv.vector_equiv_fin α n)) protected instance array {α : Type u_1} [primcodable α] {n : ℕ} : primcodable (array n α) := of_equiv (fin n → α) (equiv.array_equiv_fin n α) protected instance ulower {α : Type u_1} [primcodable α] : primcodable (ulower α) := (fun (this : primrec_pred fun (n : ℕ) => encodable.decode2 α n ≠ none) => subtype sorry) sorry end primcodable namespace primrec theorem subtype_val {α : Type u_1} [primcodable α] {p : α → Prop} [decidable_pred p] {hp : primrec_pred p} : primrec subtype.val := sorry theorem subtype_val_iff {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {p : β → Prop} [decidable_pred p] {hp : primrec_pred p} {f : α → Subtype p} : (primrec fun (a : α) => subtype.val (f a)) ↔ primrec f := sorry theorem subtype_mk {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {p : β → Prop} [decidable_pred p] {hp : primrec_pred p} {f : α → β} {h : ∀ (a : α), p (f a)} (hf : primrec f) : primrec fun (a : α) => { val := f a, property := h a } := iff.mp subtype_val_iff hf theorem option_get {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {f : α → Option β} {h : ∀ (a : α), ↥(option.is_some (f a))} : primrec f → primrec fun (a : α) => option.get (h a) := sorry theorem ulower_down {α : Type u_1} [primcodable α] : primrec ulower.down := subtype_mk primrec.encode theorem ulower_up {α : Type u_1} [primcodable α] : primrec ulower.up := option_get (comp primrec.decode2 subtype_val) theorem fin_val_iff {α : Type u_1} [primcodable α] {n : ℕ} {f : α → fin n} : (primrec fun (a : α) => subtype.val (f a)) ↔ primrec f := iff.trans (iff.trans (iff.refl (primrec fun (a : α) => subtype.val (f a))) subtype_val_iff) (of_equiv_iff (equiv.fin_equiv_subtype n)) theorem fin_val {n : ℕ} : primrec coe := iff.mpr fin_val_iff primrec.id theorem fin_succ {n : ℕ} : primrec fin.succ := sorry theorem vector_to_list {α : Type u_1} [primcodable α] {n : ℕ} : primrec vector.to_list := subtype_val theorem vector_to_list_iff {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {n : ℕ} {f : α → vector β n} : (primrec fun (a : α) => vector.to_list (f a)) ↔ primrec f := subtype_val_iff theorem vector_cons {α : Type u_1} [primcodable α] {n : ℕ} : primrec₂ vector.cons := sorry theorem vector_length {α : Type u_1} [primcodable α] {n : ℕ} : primrec vector.length := const n theorem vector_head {α : Type u_1} [primcodable α] {n : ℕ} : primrec vector.head := sorry theorem vector_tail {α : Type u_1} [primcodable α] {n : ℕ} : primrec vector.tail := sorry theorem vector_nth {α : Type u_1} [primcodable α] {n : ℕ} : primrec₂ vector.nth := sorry theorem list_of_fn {α : Type u_1} {σ : Type u_4} [primcodable α] [primcodable σ] {n : ℕ} {f : fin n → α → σ} : (∀ (i : fin n), primrec (f i)) → primrec fun (a : α) => list.of_fn fun (i : fin n) => f i a := sorry theorem vector_of_fn {α : Type u_1} {σ : Type u_4} [primcodable α] [primcodable σ] {n : ℕ} {f : fin n → α → σ} (hf : ∀ (i : fin n), primrec (f i)) : primrec fun (a : α) => vector.of_fn fun (i : fin n) => f i a := sorry theorem vector_nth' {α : Type u_1} [primcodable α] {n : ℕ} : primrec vector.nth := of_equiv_symm theorem vector_of_fn' {α : Type u_1} [primcodable α] {n : ℕ} : primrec vector.of_fn := of_equiv theorem fin_app {σ : Type u_4} [primcodable σ] {n : ℕ} : primrec₂ id := sorry theorem fin_curry₁ {α : Type u_1} {σ : Type u_4} [primcodable α] [primcodable σ] {n : ℕ} {f : fin n → α → σ} : primrec₂ f ↔ ∀ (i : fin n), primrec (f i) := sorry theorem fin_curry {α : Type u_1} {σ : Type u_4} [primcodable α] [primcodable σ] {n : ℕ} {f : α → fin n → σ} : primrec f ↔ primrec₂ f := sorry end primrec namespace nat /-- An alternative inductive definition of `primrec` which does not use the pairing function on ℕ, and so has to work with n-ary functions on ℕ instead of unary functions. We prove that this is equivalent to the regular notion in `to_prim` and `of_prim`. -/ inductive primrec' : {n : ℕ} → (vector ℕ n → ℕ) → Prop where | zero : primrec' fun (_x : vector ℕ 0) => 0 | succ : primrec' fun (v : vector ℕ 1) => Nat.succ (vector.head v) | nth : ∀ {n : ℕ} (i : fin n), primrec' fun (v : vector ℕ n) => vector.nth v i | comp : ∀ {m n : ℕ} {f : vector ℕ n → ℕ} (g : fin n → vector ℕ m → ℕ), primrec' f → (∀ (i : fin n), primrec' (g i)) → primrec' fun (a : vector ℕ m) => f (vector.of_fn fun (i : fin n) => g i a) | prec : ∀ {n : ℕ} {f : vector ℕ n → ℕ} {g : vector ℕ (n + bit0 1) → ℕ}, primrec' f → primrec' g → primrec' fun (v : vector ℕ (n + 1)) => elim (f (vector.tail v)) (fun (y IH : ℕ) => g (y::ᵥIH::ᵥvector.tail v)) (vector.head v) end nat namespace nat.primrec' theorem to_prim {n : ℕ} {f : vector ℕ n → ℕ} (pf : primrec' f) : primrec f := sorry theorem of_eq {n : ℕ} {f : vector ℕ n → ℕ} {g : vector ℕ n → ℕ} (hf : primrec' f) (H : ∀ (i : vector ℕ n), f i = g i) : primrec' g := funext H ▸ hf theorem const {n : ℕ} (m : ℕ) : primrec' fun (v : vector ℕ n) => m := sorry theorem head {n : ℕ} : primrec' vector.head := sorry theorem tail {n : ℕ} {f : vector ℕ n → ℕ} (hf : primrec' f) : primrec' fun (v : vector ℕ (Nat.succ n)) => f (vector.tail v) := sorry def vec {n : ℕ} {m : ℕ} (f : vector ℕ n → vector ℕ m) := ∀ (i : fin m), primrec' fun (v : vector ℕ n) => vector.nth (f v) i protected theorem nil {n : ℕ} : vec fun (_x : vector ℕ n) => vector.nil := fun (i : fin 0) => fin.elim0 i protected theorem cons {n : ℕ} {m : ℕ} {f : vector ℕ n → ℕ} {g : vector ℕ n → vector ℕ m} (hf : primrec' f) (hg : vec g) : vec fun (v : vector ℕ n) => f v::ᵥg v := sorry theorem idv {n : ℕ} : vec id := nth theorem comp' {n : ℕ} {m : ℕ} {f : vector ℕ m → ℕ} {g : vector ℕ n → vector ℕ m} (hf : primrec' f) (hg : vec g) : primrec' fun (v : vector ℕ n) => f (g v) := sorry theorem comp₁ (f : ℕ → ℕ) (hf : primrec' fun (v : vector ℕ 1) => f (vector.head v)) {n : ℕ} {g : vector ℕ n → ℕ} (hg : primrec' g) : primrec' fun (v : vector ℕ n) => f (g v) := comp (fun (i : fin 1) => g) hf fun (i : fin 1) => hg theorem comp₂ (f : ℕ → ℕ → ℕ) (hf : primrec' fun (v : vector ℕ (bit0 1)) => f (vector.head v) (vector.head (vector.tail v))) {n : ℕ} {g : vector ℕ n → ℕ} {h : vector ℕ n → ℕ} (hg : primrec' g) (hh : primrec' h) : primrec' fun (v : vector ℕ n) => f (g v) (h v) := sorry theorem prec' {n : ℕ} {f : vector ℕ n → ℕ} {g : vector ℕ n → ℕ} {h : vector ℕ (n + bit0 1) → ℕ} (hf : primrec' f) (hg : primrec' g) (hh : primrec' h) : primrec' fun (v : vector ℕ n) => elim (g v) (fun (y IH : ℕ) => h (y::ᵥIH::ᵥv)) (f v) := sorry theorem pred : primrec' fun (v : vector ℕ 1) => Nat.pred (vector.head v) := sorry theorem add : primrec' fun (v : vector ℕ (bit0 1)) => vector.head v + vector.head (vector.tail v) := sorry theorem sub : primrec' fun (v : vector ℕ (bit0 1)) => vector.head v - vector.head (vector.tail v) := sorry theorem mul : primrec' fun (v : vector ℕ (bit0 1)) => vector.head v * vector.head (vector.tail v) := sorry theorem if_lt {n : ℕ} {a : vector ℕ n → ℕ} {b : vector ℕ n → ℕ} {f : vector ℕ n → ℕ} {g : vector ℕ n → ℕ} (ha : primrec' a) (hb : primrec' b) (hf : primrec' f) (hg : primrec' g) : primrec' fun (v : vector ℕ n) => ite (a v < b v) (f v) (g v) := sorry theorem mkpair : primrec' fun (v : vector ℕ (bit0 1)) => mkpair (vector.head v) (vector.head (vector.tail v)) := if_lt head (tail head) (comp₂ Add.add add (tail (comp₂ Mul.mul mul head head)) head) (comp₂ Add.add add (comp₂ Add.add add (comp₂ Mul.mul mul head head) head) (tail head)) protected theorem encode {n : ℕ} : primrec' encodable.encode := sorry theorem sqrt : primrec' fun (v : vector ℕ 1) => sqrt (vector.head v) := sorry theorem unpair₁ {n : ℕ} {f : vector ℕ n → ℕ} (hf : primrec' f) : primrec' fun (v : vector ℕ n) => prod.fst (unpair (f v)) := sorry theorem unpair₂ {n : ℕ} {f : vector ℕ n → ℕ} (hf : primrec' f) : primrec' fun (v : vector ℕ n) => prod.snd (unpair (f v)) := sorry theorem of_prim {n : ℕ} {f : vector ℕ n → ℕ} : primrec f → primrec' f := sorry theorem prim_iff {n : ℕ} {f : vector ℕ n → ℕ} : primrec' f ↔ primrec f := { mp := to_prim, mpr := of_prim } theorem prim_iff₁ {f : ℕ → ℕ} : (primrec' fun (v : vector ℕ 1) => f (vector.head v)) ↔ primrec f := sorry theorem prim_iff₂ {f : ℕ → ℕ → ℕ} : (primrec' fun (v : vector ℕ (bit0 1)) => f (vector.head v) (vector.head (vector.tail v))) ↔ primrec₂ f := sorry theorem vec_iff {m : ℕ} {n : ℕ} {f : vector ℕ m → vector ℕ n} : vec f ↔ primrec f := sorry end nat.primrec' theorem primrec.nat_sqrt : primrec nat.sqrt := iff.mp nat.primrec'.prim_iff₁ nat.primrec'.sqrt end Mathlib
976fc006e88405f9c4a3b76d1040bd80a4a0c3a7
6b10c15e653d49d146378acda9f3692e9b5b1950
/examples/logic/unnamed_101.lean
ae6342fe63e1e76f094ed4fa592220aa661f6489
[]
no_license
gebner/mathematics_in_lean
3cf7f18767208ea6c3307ec3a67c7ac266d8514d
6d1462bba46d66a9b948fc1aef2714fd265cde0b
refs/heads/master
1,655,301,945,565
1,588,697,505,000
1,588,697,505,000
261,523,603
0
0
null
1,588,695,611,000
1,588,695,610,000
null
UTF-8
Lean
false
false
121
lean
variable A : Prop -- BEGIN example : A → A := by { intro h, apply h } example : A → A := by intro h; apply h -- END
600b1dda08fe9948d1bcc667e3bc78f8b98a183f
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/tests/playground/matchEqs.lean
a96ddc14d4e141bff94c195750c9d56df2c2a470
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
5,447
lean
import Lean namespace Lean.Meta.Match private def isMatchValue (e : Expr) : Bool := e.isNatLit || e.isCharLit || e.isStringLit partial def mkEquationsFor (matchDeclName : Name) : MetaM Unit := do let constInfo ← getConstInfo matchDeclName let us := constInfo.levelParams.map mkLevelParam let some matchInfo ← getMatcherInfo? matchDeclName | throwError "'{matchDeclName}' is not a matcher function" forallTelescopeReducing constInfo.type fun xs _ => do let params := xs[:matchInfo.numParams] let motive := xs[matchInfo.getMotivePos] let alts := xs[xs.size - matchInfo.numAlts:] let firstDiscrIdx := matchInfo.numParams + 1 let discrs := xs[firstDiscrIdx : firstDiscrIdx + matchInfo.numDiscrs] let mut notAlts := #[] for alt in alts do let altType ← inferType alt trace[Meta.debug] ">> {altType}" notAlts ← forallTelescopeReducing altType fun ys altResultType => do let (ys, rhsArgs) ← toFVarsRHSArgs ys let patterns := altResultType.getAppArgs let mut hs := #[] for notAlt in notAlts do hs := hs.push (← instantiateForall notAlt patterns) hs ← simpHs hs patterns.size trace[Meta.debug] "hs: {hs}" -- Create a proposition for representing terms that do not match `patterns` let mut notAlt := mkConst ``False for discr in discrs.toArray.reverse, pattern in patterns.reverse do notAlt ← mkArrow (← mkEq discr pattern) notAlt notAlt ← mkForallFVars (discrs ++ ys) notAlt trace[Meta.debug] "notAlt: {notAlt}" let lhs := mkAppN (mkConst constInfo.name us) (params ++ #[motive] ++ patterns ++ alts) let rhs := mkAppN alt rhsArgs let thmType ← mkEq lhs rhs let thmType ← hs.foldrM (init := thmType) mkArrow let thmType ← mkForallFVars (params ++ #[motive] ++ alts ++ ys) thmType let thmVal ← prove thmType trace[Meta.debug] ">> {thmType}" return notAlts.push notAlt where toFVarsRHSArgs (ys : Array Expr) : MetaM (Array Expr × Array Expr) := do if ys.size == 1 && (← inferType ys[0]).isConstOf ``Unit then return (#[], #[mkConst ``Unit.unit]) else return (ys, ys) simpEq (lhs : Expr) (rhs : Expr) : OptionT (StateRefT (Array Expr) MetaM) Unit := do if isMatchValue lhs && isMatchValue rhs then unless (← isDefEq lhs rhs) do failure else if rhs.isFVar then -- Ignore case since it matches anything pure () else match lhs.arrayLit?, rhs.arrayLit? with | some (_, lhsArgs), some (_, rhsArgs) => if lhsArgs.length != rhsArgs.length then failure else for lhsArg in lhsArgs, rhsArg in rhsArgs do simpEq lhsArg rhsArg | _, _ => match toCtorIfLit lhs |>.constructorApp? (← getEnv), toCtorIfLit rhs |>.constructorApp? (← getEnv) with | some (lhsCtor, lhsArgs), some (rhsCtor, rhsArgs) => if lhsCtor.name == rhsCtor.name then for lhsArg in lhsArgs[lhsCtor.numParams:], rhsArg in rhsArgs[lhsCtor.numParams:] do simpEq lhsArg rhsArg else failure | _, _ => let newEq ← mkEq lhs rhs modify fun eqs => eqs.push newEq simpEqs (eqs : Array Expr) : OptionT (StateRefT (Array Expr) MetaM) Unit := do eqs.forM fun eq => match eq.eq? with | some (_, lhs, rhs) => simpEq lhs rhs | _ => throwError "failed to generate equality theorems for 'match', equality expected{indentExpr eq}" simpHs (hs : Array Expr) (numPatterns : Nat) : MetaM (Array Expr) := hs.filterMapM fun h => forallTelescope h fun ys _ => do trace[Meta.debug] "ys: {ys}" let xs := ys[:ys.size - numPatterns].toArray let eqs ← ys[ys.size - numPatterns : ys.size].toArray.mapM inferType if let some eqsNew ← simpEqs eqs *> get |>.run |>.run' #[] then let newH ← eqsNew.foldrM (init := mkConst ``False) mkArrow let xs ← xs.filterM fun x => dependsOn newH x.fvarId! return some (← mkForallFVars xs newH) else none proveLoop (mvarId : MVarId) : MetaM Unit := do let mvarId ← modifyTargetEqLHS mvarId whnfCore (applyRefl mvarId) <|> (do trace[Meta.debug] "TODO{indentD <| MessageData.ofGoal mvarId}" -- TODO admit mvarId) prove (type : Expr) : MetaM Expr := withLCtx {} {} <| forallTelescope type fun ys target => do let mvar0 ← mkFreshExprSyntheticOpaqueMVar target let mvarId ← deltaTarget mvar0.mvarId! (. == matchDeclName) proveLoop mvarId mkLambdaFVars ys (← instantiateMVars mvar0) end Lean.Meta.Match def f (xs ys : List String) : Nat := match xs, ys with | [], [] => 0 | _, ["abc"] => 1 | _, x::xs => xs.length | _, _ => 2 def h (x y : Nat) : Nat := match x, y with | 10000, _ => 0 | 10001, _ => 5 | _, 20000 => 4 | x+1, _ => 3 | Nat.zero, y+1 => 44 | _, _ => 1 theorem ex1 : h 10000 1 = 0 := rfl theorem ex2 : h 10002 1 = 3 := rfl def g (xs ys : Array Nat) : Nat := match xs, ys with | #[], #[] => 0 | _, #[0, y+1] => 1 | _, #[x, y] => 2 | _, _ => 3 -- #print f.match_1 set_option trace.Meta.debug true #eval Lean.Meta.Match.mkEquationsFor ``f.match_1 #eval Lean.Meta.Match.mkEquationsFor ``h.match_1 #eval Lean.Meta.Match.mkEquationsFor ``g.match_1
4711f7eb211e1418e6e504543663a68d245a72e5
205f0fc16279a69ea36e9fd158e3a97b06834ce2
/EXAMS/exam1_key.lean
d868d0c4a048faf8d6815f2c53262803baffb449
[]
no_license
kevinsullivan/cs-dm-lean
b21d3ca1a9b2a0751ba13fcb4e7b258010a5d124
a06a94e98be77170ca1df486c8189338b16cf6c6
refs/heads/master
1,585,948,743,595
1,544,339,346,000
1,544,339,346,000
155,570,767
1
3
null
1,541,540,372,000
1,540,995,993,000
Lean
UTF-8
Lean
false
false
9,808
lean
/- POINTS: Welcome to the first CS2102 exam. The exam has 11 questions and one extra credit question. The first two questions are worth 5 points each. The rest (but for the extra credit) are worth 10 points each, making a total of 100. The extra credit is worth an addition 5 points. ORGANIZATION: The sections of the exam are labelled and organized around the inference rules we've covered so far: rules for equality, conjunction, implications, functions, and negations. That said, there is some mixing of these issues across the sections. WHAT TO DO: Complete the exam by following the instructions for each question. Save your file then upload the completed and saved file to Collab. You have exactly 75 minutes from the start of the exam to the time where it must be uploaded to Collab. OPEN NOTES: You may use the class notes for this exam, whether provided to you by the instructors or taken by you (or for you). STRICTLY INDIVIDUAL EFFORT: This is a strictly individual exam, taken under the honor system. Do not communicate with anyone except for the instructor about the content of this exam, by any means, until you are absoluately sure that each person you are communicating with has already completed it. -/ /- Write your name and UVa email ID here and acknowledge that you understand that this exam is an individual exam and that the Honor System is in effect for this exam (write "I acknowledge it.") Name: Email id: Acknowledge that the Honor System norms and rules apply: Now proceed to take the exam! -/ /- ********************************** -/ /- ** PROOFS INVOLVING EQUALITY ** -/ /- ********************************** -/ /- #1 - 5 points Prove that for any type, T, and for any two values, a and b, of type T, if you assume that there is a proof of a = b (or if you are given such a proof), then you can derive a proof of b = a. To be precise, what you are to prove is this: ∀ T : Type, ∀ a b : T, a = b → b = a. To prove it, you will present a function that, given a type T, two values, a and b, of type T, and a proof of a = b, returns a proof of b = a. We give you most of such a function definition, below. Your challenge is to write the function "body" in place of the sorry. It should be an expression that evalutes to a proof of b = a. Hint: how do you get a proof of b = a from a proof, pf, of a = b? -/ def from_a_eq_b_prove_b_eq_a (T: Type) (a b : T) (pf : a = b) : b = a := eq.symm pf #check from_a_eq_b_prove_b_eq_a : ∀ (T : Type) (a b : T), a = b → b = a /- #2 - 5 points Here you are asked to prove the same proposition, but now the function type is writen as, ∀ (T : Type), ∀ (a b : T), a = b → b = a. Give your answer by replacing the sorry with the required lambda expression. Hint: A lambda expression is written as lambda followed immediately by the names of one or more arguments, followed by a comma, followed by the body of the function that is being defined. Hint: the function you are to define has the same arguments in the same order as the function you defined above! -/ def from_a_eq_b_prove_b_eq_a' : ∀ (T : Type), ∀ (a b : T), a = b → b = a := λ T a b pf, eq.symm pf /- ************************************** -/ /- *** PROOFS INVOLVING CONJUNCTIONS *** -/ /- ************************************** -/ /- For the questions that follow, assume that P, Q, and R are propositions. We make these assumptions explicit using the following "variables" declaration. -/ variables P Q R : Prop /- #3 - 10 points Given that we've assumed and defined P, Q, and R are arbitrary propositions, prove that P → Q → P ∧ Q. Do it by replacing the sorry with either a lambda expression or a tactic script in the following code. -/ theorem t1 : P → Q → P ∧ Q := λ p q, and.intro p q theorem t1' : P → Q → P ∧ Q := begin assume p q, show P ∧ Q, from and.intro p q end /- #4 - 10 points Prove that (P ∧ Q) → (Q ∧ P). This implication basically states that conjunction is commutative. You will prove it by first assuming that you have a proof of P ∧ Q and by then showing that you can construct a proof of Q ∧ P. To complete the proof,replace the sorry with either a lambda expression or a tactic script as you prefer. Hint: remember the introduction and elimination rules for conjunctions. -/ theorem t2 : (P ∧ Q) → (Q ∧ P) := λ (pf : P ∧ Q), and.intro pf.right pf.left -- SULLIVAN: Was answer included in distributed exam? /- ************************************** -/ /- *** PROOFS INVOLVING IMPLICATIONS *** -/ /- ************************************** -/ /- #5 - 10 points Prove that (P → Q) → (Q → R) → (P → R). This proposition claims that implication is transitive (which it is). Hint #1: assume that you have a proof of (P → Q). Then assume that you have a proof of (Q → R). Then, in the context of these two assumptions, show that you can construct a proof of P → R. Hint #2: To prove P → R, assume that you have a proof of P and show that you can construct a proof of R. Hint #3: Proofs of implications can be used to convert proofs of premises into proofs of conclusions. Think modus ponens. You can use a lambda expression, tactics, or even a mixture of the two -- whatever you prefer -- to give your answer. -/ theorem arrow_trans : (P → Q) → (Q → R) → (P → R) := λ pq qr, λ p, qr (pq p) theorem arrow_trans' : (P → Q) → (Q → R) → (P → R) := begin assume pq qr, show P → R, from assume p, show R, from qr (pq p) end /- *************************** -/ /- *** DEFINING FUNCTIONS *** -/ /- *************************** -/ /- #6 - 10 points Complete the following definition of a function, square, that takes a natural number as an argument and that returns the square of that argument as a result. Give your answer by replacing sorry in the code that follows with your code. -/ -- Your answer goes here def square (n : nat) : nat := n * n /- #7 - 10 points Give an alternative implementation of square, here called square', by replacing the sorry with a lambda expression in the following code. -/ def square' : ℕ → ℕ := λ n, n * n /- #8 - 10 points Write a function, quad, that takes four natural numbers, a, b, c, and x, and that returns a * x * x + b * x + c. Thus function, quad, is thus to take the coefficients of a general quadratic function and evaluate it at the value given by x. Use a lambda expression. Hint, such a function takes four ℕ values as arguments and returns a fifth ℕ value as a result. Make sure you have the right number of ℕ's when you declare the type of quad as something like this: def quad : ℕ → ℕ → ... -/ def quad (a b c x: ℕ) : ℕ := a * x^2 + b * x + c theorem quadRight : quad = λ a b c x, a * x^2 + b * x + c := rfl /- *********************************** -/ /- *** PROOFS INVOLVING NEGATIONS *** -/ /- *********************************** -/ /- #9 - 10 points Given that we've already assumed (above) that Q is some arbitrary (any) proposition, construct a proof, call it noContra, that (Q ∧ ¬ Q) → false. Your answer will start like this: theorem noContra : (Q ∧ ¬ Q) → false := -/ theorem noContra : (Q ∧ ¬ Q) → false := begin assume contra, show false, from contra.right contra.left end /- #10 - 10 points Construct a proof, call it contraPos, that (P → Q) → (¬ Q → ¬ P). You can make sense of this proposition using the "rain/wet" example. If it's true that "if it's raining then the streets are wet" then its true that if the streets are not wet it, then it is not raining. Hint: as you can see plainly, this is an implication. Structure you proof accordingly. What do you assume to begin and what do you then need to show? If what you need to show is itself an implication, follow the same strategy! Assume that you have proof of the premise and show (in the context of all of the assumptions you've made) that you can construct a proof of the conclusion. -/ theorem contraPos : (P → Q) → (¬ Q → ¬ P) := begin assume pq, show ¬ Q → ¬ P, from assume nq: ¬ Q, show ¬ P, from assume p : P, show false, from nq (pq p) end /- #11 -- 10 points Using at most a few sentence in English, give concise answers to the following two questions. #11a: In a few words (within this comment block) explain the strategy of proof by negation. Clearly state the form of the goal to be proved and how exactly one proceeds to use proof by negation to prove it. YOUR ANSWER HERE: Proof by negation is used to prove a proposition of the form ¬ P. To use this strategy, one assumes P and shows that that leads to a contradiction. (This shows that P → false which is the definition of ¬ P). #11b: In a few words (within this comment block) explain the strategy of proof by contradiction. Clearly state the form of the goal to be proved and how exactly one proceeds to use proof by contradiction to prove it. In addition, explain why (classical) double negation elimination is essential to enabling proof by contradiction. YOUR ANSWER HERE: Proof by contradiction is used to prove a proposition of the form P. To use it, one assumes ¬ P and shows that doing so leads to a contradiction. This proves ¬ ¬ P, which, in classical logic also proves P. -/ /- EXTRA CREDIT -- 5 points: In Lean write an axiom, called double_negation_elim, that tells lean to accept double negation elimination as a valid inference rule without a proof of validity. -/ axiom double_negation_elim : ∀ P : Prop, ¬ ¬ P → P.
a32744634216cd4ff7d39a2949707bedead522a8
f1b175e38ffc5cc1c7c5551a72d0dbaf70786f83
/data/real/basic.lean
0e54d4eae0f92de267dac71f2fcc51fb1451f6f0
[ "Apache-2.0" ]
permissive
mjendrusch/mathlib
df3ae884dd5ce38c7edf452bcbfd3baf4e3a6214
5c209edb7eb616a26f64efe3500f2b1ba95b8d55
refs/heads/master
1,585,663,284,800
1,539,062,055,000
1,539,062,055,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
27,068
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro The (classical) real numbers ℝ. This is a direct construction from Cauchy sequences. -/ import order.conditionally_complete_lattice data.real.cau_seq_completion algebra.big_operators algebra.archimedean order.bounds def real := @cau_seq.completion.Cauchy ℚ _ _ _ abs _ notation `ℝ` := real local attribute [reducible] real namespace real open cau_seq cau_seq.completion def of_rat (x : ℚ) : ℝ := of_rat x instance : comm_ring ℝ := cau_seq.completion.comm_ring /- Extra instances to short-circuit type class resolution -/ instance : ring ℝ := by apply_instance instance : comm_semiring ℝ := by apply_instance instance : semiring ℝ := by apply_instance instance : add_comm_group ℝ := by apply_instance instance : add_group ℝ := by apply_instance instance : add_comm_monoid ℝ := by apply_instance instance : add_monoid ℝ := by apply_instance instance : add_left_cancel_semigroup ℝ := by apply_instance instance : add_right_cancel_semigroup ℝ := by apply_instance instance : add_comm_semigroup ℝ := by apply_instance instance : add_semigroup ℝ := by apply_instance instance : comm_monoid ℝ := by apply_instance instance : monoid ℝ := by apply_instance instance : comm_semigroup ℝ := by apply_instance instance : semigroup ℝ := by apply_instance instance : inhabited ℝ := ⟨0⟩ theorem of_rat_sub (x y : ℚ) : of_rat (x - y) = of_rat x - of_rat y := congr_arg mk (const_sub _ _) instance : has_lt ℝ := ⟨λ x y, quotient.lift_on₂ x y (<) $ λ f₁ g₁ f₂ g₂ hf hg, propext $ ⟨λ h, lt_of_eq_of_lt (setoid.symm hf) (lt_of_lt_of_eq h hg), λ h, lt_of_eq_of_lt hf (lt_of_lt_of_eq h (setoid.symm hg))⟩⟩ @[simp] theorem mk_lt {f g : cau_seq ℚ abs} : mk f < mk g ↔ f < g := iff.rfl @[simp] theorem mk_pos {f : cau_seq ℚ abs} : 0 < mk f ↔ pos f := iff_of_eq (congr_arg pos (sub_zero f)) instance : has_le ℝ := ⟨λ x y, x < y ∨ x = y⟩ @[simp] theorem mk_le {f g : cau_seq ℚ abs} : mk f ≤ mk g ↔ f ≤ g := or_congr iff.rfl quotient.eq theorem add_lt_add_iff_left {a b : ℝ} (c : ℝ) : c + a < c + b ↔ a < b := quotient.induction_on₃ a b c (λ f g h, iff_of_eq (congr_arg pos $ by rw add_sub_add_left_eq_sub)) instance : linear_order ℝ := { le := (≤), lt := (<), le_refl := λ a, or.inr rfl, le_trans := λ a b c, quotient.induction_on₃ a b c $ λ f g h, by simpa using le_trans, lt_iff_le_not_le := λ a b, quotient.induction_on₂ a b $ λ f g, by simpa using lt_iff_le_not_le, le_antisymm := λ a b, quotient.induction_on₂ a b $ λ f g, by simpa [mk_eq] using @cau_seq.le_antisymm _ _ f g, le_total := λ a b, quotient.induction_on₂ a b $ λ f g, by simpa using le_total f g } instance : partial_order ℝ := by apply_instance instance : preorder ℝ := by apply_instance theorem of_rat_lt {x y : ℚ} : of_rat x < of_rat y ↔ x < y := const_lt protected theorem zero_lt_one : (0 : ℝ) < 1 := of_rat_lt.2 zero_lt_one protected theorem mul_pos {a b : ℝ} : 0 < a → 0 < b → 0 < a * b := quotient.induction_on₂ a b $ λ f g, by simpa using cau_seq.mul_pos instance : linear_ordered_comm_ring ℝ := { add_le_add_left := λ a b h c, (le_iff_le_iff_lt_iff_lt.2 $ real.add_lt_add_iff_left c).2 h, zero_ne_one := ne_of_lt real.zero_lt_one, mul_nonneg := λ a b a0 b0, match a0, b0 with | or.inl a0, or.inl b0 := le_of_lt (real.mul_pos a0 b0) | or.inr a0, _ := by simp [a0.symm] | _, or.inr b0 := by simp [b0.symm] end, mul_pos := @real.mul_pos, zero_lt_one := real.zero_lt_one, add_lt_add_left := λ a b h c, (real.add_lt_add_iff_left c).2 h, ..real.comm_ring, ..real.linear_order } /- Extra instances to short-circuit type class resolution -/ instance : linear_ordered_ring ℝ := by apply_instance instance : ordered_ring ℝ := by apply_instance instance : linear_ordered_semiring ℝ := by apply_instance instance : ordered_semiring ℝ := by apply_instance instance : ordered_comm_group ℝ := by apply_instance instance : ordered_cancel_comm_monoid ℝ := by apply_instance instance : ordered_comm_monoid ℝ := by apply_instance instance : domain ℝ := by apply_instance local attribute [instance] classical.prop_decidable noncomputable instance : discrete_linear_ordered_field ℝ := { inv := has_inv.inv, inv_mul_cancel := @cau_seq.completion.inv_mul_cancel _ _ _ _ _ _, mul_inv_cancel := λ x x0, by rw [mul_comm, cau_seq.completion.inv_mul_cancel x0], inv_zero := inv_zero, decidable_le := by apply_instance, ..real.linear_ordered_comm_ring } /- Extra instances to short-circuit type class resolution -/ noncomputable instance : linear_ordered_field ℝ := by apply_instance noncomputable instance : decidable_linear_ordered_comm_ring ℝ := by apply_instance noncomputable instance : decidable_linear_ordered_semiring ℝ := by apply_instance noncomputable instance : decidable_linear_ordered_comm_group ℝ := by apply_instance noncomputable instance real.discrete_field : discrete_field ℝ := by apply_instance noncomputable instance : field ℝ := by apply_instance noncomputable instance : division_ring ℝ := by apply_instance noncomputable instance : integral_domain ℝ := by apply_instance noncomputable instance : nonzero_comm_ring ℝ := by apply_instance noncomputable instance : decidable_linear_order ℝ := by apply_instance noncomputable instance : lattice.distrib_lattice ℝ := by apply_instance noncomputable instance : lattice.lattice ℝ := by apply_instance noncomputable instance : lattice.semilattice_inf ℝ := by apply_instance noncomputable instance : lattice.semilattice_sup ℝ := by apply_instance noncomputable instance : lattice.has_inf ℝ := by apply_instance noncomputable instance : lattice.has_sup ℝ := by apply_instance open rat @[simp] theorem of_rat_eq_cast : ∀ x : ℚ, of_rat x = x := eq_cast of_rat rfl of_rat_add of_rat_mul theorem le_mk_of_forall_le {x : ℝ} {f : cau_seq ℚ abs} : (∃ i, ∀ j ≥ i, x ≤ f j) → x ≤ mk f := quotient.induction_on x $ λ g h, le_of_not_lt $ λ ⟨K, K0, hK⟩, let ⟨i, H⟩ := exists_forall_ge_and h $ exists_forall_ge_and hK (f.cauchy₃ $ half_pos K0) in begin apply not_lt_of_le (H _ (le_refl _)).1, rw ← of_rat_eq_cast, refine ⟨_, half_pos K0, i, λ j ij, _⟩, have := add_le_add (H _ ij).2.1 (le_of_lt (abs_lt.1 $ (H _ (le_refl _)).2.2 _ ij).1), rwa [← sub_eq_add_neg, sub_self_div_two, sub_apply, sub_add_sub_cancel] at this end theorem mk_le_of_forall_le {f : cau_seq ℚ abs} {x : ℝ} : (∃ i, ∀ j ≥ i, (f j : ℝ) ≤ x) → mk f ≤ x | ⟨i, H⟩ := by rw [← neg_le_neg_iff, mk_neg]; exact le_mk_of_forall_le ⟨i, λ j ij, by simp [H _ ij]⟩ theorem mk_near_of_forall_near {f : cau_seq ℚ abs} {x : ℝ} {ε : ℝ} (H : ∃ i, ∀ j ≥ i, abs ((f j : ℝ) - x) ≤ ε) : abs (mk f - x) ≤ ε := abs_sub_le_iff.2 ⟨sub_le_iff_le_add'.2 $ mk_le_of_forall_le $ H.imp $ λ i h j ij, sub_le_iff_le_add'.1 (abs_sub_le_iff.1 $ h j ij).1, sub_le.1 $ le_mk_of_forall_le $ H.imp $ λ i h j ij, sub_le.1 (abs_sub_le_iff.1 $ h j ij).2⟩ instance : archimedean ℝ := archimedean_iff_rat_le.2 $ λ x, quotient.induction_on x $ λ f, let ⟨M, M0, H⟩ := f.bounded' 0 in ⟨M, mk_le_of_forall_le ⟨0, λ i _, rat.cast_le.2 $ le_of_lt (abs_lt.1 (H i)).2⟩⟩ noncomputable instance : floor_ring ℝ := archimedean.floor_ring _ theorem is_cau_seq_iff_lift {f : ℕ → ℚ} : is_cau_seq abs f ↔ is_cau_seq abs (λ i, (f i : ℝ)) := ⟨λ H ε ε0, let ⟨δ, δ0, δε⟩ := exists_pos_rat_lt ε0 in (H _ δ0).imp $ λ i hi j ij, lt_trans (by simpa using (@rat.cast_lt ℝ _ _ _).2 (hi _ ij)) δε, λ H ε ε0, (H _ (rat.cast_pos.2 ε0)).imp $ λ i hi j ij, (@rat.cast_lt ℝ _ _ _).1 $ by simpa using hi _ ij⟩ theorem of_near (f : ℕ → ℚ) (x : ℝ) (h : ∀ ε > 0, ∃ i, ∀ j ≥ i, abs ((f j : ℝ) - x) < ε) : ∃ h', cau_seq.completion.mk ⟨f, h'⟩ = x := ⟨is_cau_seq_iff_lift.2 (of_near _ (const abs x) h), sub_eq_zero.1 $ abs_eq_zero.1 $ eq_of_le_of_forall_le_of_dense (abs_nonneg _) $ λ ε ε0, mk_near_of_forall_near $ (h _ ε0).imp (λ i h j ij, le_of_lt (h j ij))⟩ theorem exists_floor (x : ℝ) : ∃ (ub : ℤ), (ub:ℝ) ≤ x ∧ ∀ (z : ℤ), (z:ℝ) ≤ x → z ≤ ub := int.exists_greatest_of_bdd (let ⟨n, hn⟩ := exists_int_gt x in ⟨n, λ z h', int.cast_le.1 $ le_trans h' $ le_of_lt hn⟩) (let ⟨n, hn⟩ := exists_int_lt x in ⟨n, le_of_lt hn⟩) theorem exists_sup (S : set ℝ) : (∃ x, x ∈ S) → (∃ x, ∀ y ∈ S, y ≤ x) → ∃ x, ∀ y, x ≤ y ↔ ∀ z ∈ S, z ≤ y | ⟨L, hL⟩ ⟨U, hU⟩ := begin choose f hf using begin refine λ d : ℕ, @int.exists_greatest_of_bdd (λ n, ∃ y ∈ S, (n:ℝ) ≤ y * d) _ _ _, { cases exists_int_gt U with k hk, refine ⟨k * d, λ z h, _⟩, rcases h with ⟨y, yS, hy⟩, refine int.cast_le.1 (le_trans hy _), simp, exact mul_le_mul_of_nonneg_right (le_trans (hU _ yS) (le_of_lt hk)) (nat.cast_nonneg _) }, { exact ⟨⌊L * d⌋, L, hL, floor_le _⟩ } end, have hf₁ : ∀ n > 0, ∃ y ∈ S, ((f n / n:ℚ):ℝ) ≤ y := λ n n0, let ⟨y, yS, hy⟩ := (hf n).1 in ⟨y, yS, by simpa using (div_le_iff (nat.cast_pos.2 n0)).2 hy⟩, have hf₂ : ∀ (n > 0) (y ∈ S), (y - (n:ℕ)⁻¹ : ℝ) < (f n / n:ℚ), { intros n n0 y yS, have := lt_of_lt_of_le (sub_one_lt_floor _) (int.cast_le.2 $ (hf n).2 _ ⟨y, yS, floor_le _⟩), simp [-sub_eq_add_neg], rwa [lt_div_iff (nat.cast_pos.2 n0), sub_mul, _root_.inv_mul_cancel], exact ne_of_gt (nat.cast_pos.2 n0) }, suffices hg, let g : cau_seq ℚ abs := ⟨λ n, f n / n, hg⟩, refine ⟨mk g, λ y, ⟨λ h x xS, le_trans _ h, λ h, _⟩⟩, { refine le_of_forall_ge_of_dense (λ z xz, _), cases exists_nat_gt (x - z)⁻¹ with K hK, refine le_mk_of_forall_le ⟨K, λ n nK, _⟩, replace xz := sub_pos.2 xz, replace hK := le_trans (le_of_lt hK) (nat.cast_le.2 nK), have n0 : 0 < n := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos xz) hK), refine le_trans _ (le_of_lt $ hf₂ _ n0 _ xS), rwa [le_sub, inv_le (nat.cast_pos.2 n0) xz] }, { exact mk_le_of_forall_le ⟨1, λ n n1, let ⟨x, xS, hx⟩ := hf₁ _ n1 in le_trans hx (h _ xS)⟩ }, intros ε ε0, suffices : ∀ j k ≥ nat_ceil ε⁻¹, (f j / j - f k / k : ℚ) < ε, { refine ⟨_, λ j ij, abs_lt.2 ⟨_, this _ _ ij (le_refl _)⟩⟩, rw [neg_lt, neg_sub], exact this _ _ (le_refl _) ij }, intros j k ij ik, replace ij := le_trans (le_nat_ceil _) (nat.cast_le.2 ij), replace ik := le_trans (le_nat_ceil _) (nat.cast_le.2 ik), have j0 := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos ε0) ij), have k0 := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos ε0) ik), rcases hf₁ _ j0 with ⟨y, yS, hy⟩, refine lt_of_lt_of_le ((@rat.cast_lt ℝ _ _ _).1 _) ((inv_le ε0 (nat.cast_pos.2 k0)).1 ik), simpa using sub_lt_iff_lt_add'.2 (lt_of_le_of_lt hy $ sub_lt_iff_lt_add.1 $ hf₂ _ k0 _ yS) end noncomputable def Sup (S : set ℝ) : ℝ := if h : (∃ x, x ∈ S) ∧ (∃ x, ∀ y ∈ S, y ≤ x) then classical.some (exists_sup S h.1 h.2) else 0 theorem Sup_le (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x) {y} : Sup S ≤ y ↔ ∀ z ∈ S, z ≤ y := by simp [Sup, h₁, h₂]; exact classical.some_spec (exists_sup S h₁ h₂) y theorem lt_Sup (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x) {y} : y < Sup S ↔ ∃ z ∈ S, y < z := by simpa [not_forall] using not_congr (@Sup_le S h₁ h₂ y) theorem le_Sup (S : set ℝ) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x) {x} (xS : x ∈ S) : x ≤ Sup S := (Sup_le S ⟨_, xS⟩ h₂).1 (le_refl _) _ xS theorem Sup_le_ub (S : set ℝ) (h₁ : ∃ x, x ∈ S) {ub} (h₂ : ∀ y ∈ S, y ≤ ub) : Sup S ≤ ub := (Sup_le S h₁ ⟨_, h₂⟩).2 h₂ protected lemma is_lub_Sup {s : set ℝ} {a b : ℝ} (ha : a ∈ s) (hb : b ∈ upper_bounds s) : is_lub s (Sup s) := ⟨λ x xs, real.le_Sup s ⟨_, hb⟩ xs, λ u h, real.Sup_le_ub _ ⟨_, ha⟩ h⟩ noncomputable def Inf (S : set ℝ) : ℝ := -Sup {x | -x ∈ S} theorem le_Inf (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y) {y} : y ≤ Inf S ↔ ∀ z ∈ S, y ≤ z := begin refine le_neg.trans ((Sup_le _ _ _).trans _), { cases h₁ with x xS, exact ⟨-x, by simp [xS]⟩ }, { cases h₂ with ub h, exact ⟨-ub, λ y hy, le_neg.1 $ h _ hy⟩ }, split; intros H z hz, { exact neg_le_neg_iff.1 (H _ $ by simp [hz]) }, { exact le_neg.2 (H _ hz) } end theorem Inf_lt (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y) {y} : Inf S < y ↔ ∃ z ∈ S, z < y := by simpa [not_forall] using not_congr (@le_Inf S h₁ h₂ y) theorem Inf_le (S : set ℝ) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y) {x} (xS : x ∈ S) : Inf S ≤ x := (le_Inf S ⟨_, xS⟩ h₂).1 (le_refl _) _ xS theorem lb_le_Inf (S : set ℝ) (h₁ : ∃ x, x ∈ S) {lb} (h₂ : ∀ y ∈ S, lb ≤ y) : lb ≤ Inf S := (le_Inf S h₁ ⟨_, h₂⟩).2 h₂ open lattice noncomputable instance lattice : lattice ℝ := by apply_instance noncomputable instance : conditionally_complete_linear_order ℝ := { Sup := real.Sup, Inf := real.Inf, le_cSup := assume (s : set ℝ) (a : ℝ) (_ : bdd_above s) (_ : a ∈ s), show a ≤ Sup s, from le_Sup s ‹bdd_above s› ‹a ∈ s›, cSup_le := assume (s : set ℝ) (a : ℝ) (_ : s ≠ ∅) (H : ∀b∈s, b ≤ a), show Sup s ≤ a, from Sup_le_ub s (set.exists_mem_of_ne_empty ‹s ≠ ∅›) H, cInf_le := assume (s : set ℝ) (a : ℝ) (_ : bdd_below s) (_ : a ∈ s), show Inf s ≤ a, from Inf_le s ‹bdd_below s› ‹a ∈ s›, le_cInf := assume (s : set ℝ) (a : ℝ) (_ : s ≠ ∅) (H : ∀b∈s, a ≤ b), show a ≤ Inf s, from lb_le_Inf s (set.exists_mem_of_ne_empty ‹s ≠ ∅›) H, ..real.linear_order, ..real.lattice} theorem Sup_empty : lattice.Sup (∅ : set ℝ) = 0 := dif_neg $ by simp theorem Sup_of_not_bdd_above {s : set ℝ} (hs : ¬ bdd_above s) : lattice.Sup s = 0 := dif_neg $ assume h, hs h.2 theorem Inf_empty : lattice.Inf (∅ : set ℝ) = 0 := show Inf ∅ = 0, by simp [Inf]; exact Sup_empty theorem Inf_of_not_bdd_below {s : set ℝ} (hs : ¬ bdd_below s) : lattice.Inf s = 0 := have bdd_above {x | -x ∈ s} → bdd_below s, from assume ⟨b, hb⟩, ⟨-b, assume x hxs, neg_le.2 $ hb _ $ by simp [hxs]⟩, have ¬ bdd_above {x | -x ∈ s}, from mt this hs, neg_eq_zero.2 $ Sup_of_not_bdd_above $ this theorem cau_seq_converges (f : cau_seq ℝ abs) : ∃ x, f ≈ const abs x := begin let S := {x : ℝ | const abs x < f}, have lb : ∃ x, x ∈ S := exists_lt f, have ub' : ∀ x, f < const abs x → ∀ y ∈ S, y ≤ x := λ x h y yS, le_of_lt $ const_lt.1 $ cau_seq.lt_trans yS h, have ub : ∃ x, ∀ y ∈ S, y ≤ x := (exists_gt f).imp ub', refine ⟨Sup S, ((lt_total _ _).resolve_left (λ h, _)).resolve_right (λ h, _)⟩, { rcases h with ⟨ε, ε0, i, ih⟩, refine not_lt_of_le (Sup_le_ub S lb (ub' _ _)) ((sub_lt_self_iff _).2 (half_pos ε0)), refine ⟨_, half_pos ε0, i, λ j ij, _⟩, rw [sub_apply, const_apply, sub_right_comm, le_sub_iff_add_le, add_halves], exact ih _ ij }, { rcases h with ⟨ε, ε0, i, ih⟩, refine not_lt_of_le (le_Sup S ub _) ((lt_add_iff_pos_left _).2 (half_pos ε0)), refine ⟨_, half_pos ε0, i, λ j ij, _⟩, rw [sub_apply, const_apply, add_comm, ← sub_sub, le_sub_iff_add_le, add_halves], exact ih _ ij } end noncomputable instance : cau_seq.is_complete ℝ abs := ⟨ λ f, let ⟨x, hx⟩ := cau_seq_converges f in have lim_zero (const abs x - f), from lim_zero_sub_rev hx, ⟨x, this⟩ ⟩ section lim open cau_seq noncomputable def lim (f : ℕ → ℝ) : ℝ := if hf : is_cau_seq abs f then classical.some (cau_seq_converges ⟨f, hf⟩) else 0 theorem equiv_lim (f : cau_seq ℝ abs) : f ≈ const abs (lim f) := by simp [lim, f.is_cau]; cases f with f hf; exact classical.some_spec (cau_seq_converges ⟨f, hf⟩) lemma eq_lim_of_const_equiv {f : cau_seq ℝ abs} {x : ℝ} (h : cau_seq.const abs x ≈ f) : x = lim f := const_equiv.mp $ setoid.trans h $ equiv_lim f lemma lim_eq_of_equiv_const {f : cau_seq ℝ abs} {x : ℝ} (h : f ≈ cau_seq.const abs x) : lim f = x := (eq_lim_of_const_equiv $ setoid.symm h).symm lemma lim_eq_lim_of_equiv {f g : cau_seq ℝ abs} (h : f ≈ g) : lim f = lim g := lim_eq_of_equiv_const $ setoid.trans h $ equiv_lim g @[simp] lemma lim_const (x : ℝ) : lim (const abs x) = x := lim_eq_of_equiv_const $ setoid.refl _ lemma lim_add (f g : cau_seq ℝ abs) : lim f + lim g = lim ⇑(f + g) := eq_lim_of_const_equiv $ show lim_zero (const abs (lim ⇑f + lim ⇑g) - (f + g)), by rw [const_add, add_sub_comm]; exact add_lim_zero (setoid.symm (equiv_lim f)) (setoid.symm (equiv_lim g)) lemma lim_mul_lim (f g : cau_seq ℝ abs) : lim f * lim g = lim ⇑(f * g) := eq_lim_of_const_equiv $ show lim_zero (const abs (lim ⇑f * lim ⇑g) - f * g), from have h : const abs (lim ⇑f * lim ⇑g) - f * g = g * (const abs (lim f) - f) + const abs (lim f) * (const abs (lim g) - g) := by simp [mul_sub, mul_comm, const_mul, mul_add], by rw h; exact add_lim_zero (mul_lim_zero _ (setoid.symm (equiv_lim f))) (mul_lim_zero _ (setoid.symm (equiv_lim g))) lemma lim_mul (f : cau_seq ℝ abs) (x : ℝ) : lim f * x = lim ⇑(f * const abs x) := by rw [← lim_mul_lim, lim_const] lemma lim_neg (f : cau_seq ℝ abs) : lim ⇑(-f) = -lim f := lim_eq_of_equiv_const (show lim_zero (-f - const abs (-lim ⇑f)), by rw [const_neg, sub_neg_eq_add, add_comm]; exact setoid.symm (equiv_lim f)) lemma lim_eq_zero_iff (f : cau_seq ℝ abs) : lim f = 0 ↔ lim_zero f := ⟨assume h, by have hf := equiv_lim f; rw h at hf; exact (lim_zero_congr hf).mpr (const_lim_zero.mpr rfl), assume h, have h₁ : f = (f - const abs 0) := ext (λ n, by simp [sub_apply, const_apply]), by rw h₁ at h; exact lim_eq_of_equiv_const h ⟩ lemma lim_inv {f : cau_seq ℝ abs} (hf : ¬ lim_zero f) : lim ⇑(inv f hf) = (lim f)⁻¹ := have hl : lim f ≠ 0 := by rwa ← lim_eq_zero_iff at hf, lim_eq_of_equiv_const $ show lim_zero (inv f hf - const abs (lim ⇑f)⁻¹), from have h₁ : ∀ (g f : cau_seq ℝ abs) (hf : ¬ lim_zero f), lim_zero (g - f * inv f hf * g) := λ g f hf, by rw [← one_mul g, ← mul_assoc, ← sub_mul, mul_one, mul_comm, mul_comm f]; exact mul_lim_zero _ (setoid.symm (cau_seq.inv_mul_cancel _)), have h₂ : lim_zero ((inv f hf - const abs (lim ⇑f)⁻¹) - (const abs (lim f) - f) * (inv f hf * const abs (lim ⇑f)⁻¹)) := by rw [sub_mul, ← sub_add, sub_sub, sub_add_eq_sub_sub, sub_right_comm, sub_add]; exact show lim_zero (inv f hf - const abs (lim ⇑f) * (inv f hf * const abs (lim ⇑f)⁻¹) - (const abs (lim ⇑f)⁻¹ - f * (inv f hf * const abs (lim ⇑f)⁻¹))), from sub_lim_zero (by rw [← mul_assoc, mul_right_comm, const_inv hl]; exact h₁ _ _ _) (by rw [← mul_assoc]; exact h₁ _ _ _), (lim_zero_congr h₂).mpr $ by rw mul_comm; exact mul_lim_zero _ (setoid.symm (equiv_lim f)) end lim theorem sqrt_exists : ∀ {x : ℝ}, 0 ≤ x → ∃ y, 0 ≤ y ∧ y * y = x := suffices H : ∀ {x : ℝ}, 0 < x → x ≤ 1 → ∃ y, 0 < y ∧ y * y = x, begin intros x x0, cases x0, cases le_total x 1 with x1 x1, { rcases H x0 x1 with ⟨y, y0, hy⟩, exact ⟨y, le_of_lt y0, hy⟩ }, { have := (inv_le_inv x0 zero_lt_one).2 x1, rw inv_one at this, rcases H (inv_pos x0) this with ⟨y, y0, hy⟩, refine ⟨y⁻¹, le_of_lt (inv_pos y0), _⟩, rw [← mul_inv', hy, inv_inv'] }, { exact ⟨0, by simp [x0.symm]⟩ } end, λ x x0 x1, begin let S := {y | 0 < y ∧ y * y ≤ x}, have lb : x ∈ S := ⟨x0, by simpa using (mul_le_mul_right x0).2 x1⟩, have ub : ∀ y ∈ S, (y:ℝ) ≤ 1, { intros y yS, cases yS with y0 yx, refine (mul_self_le_mul_self_iff (le_of_lt y0) zero_le_one).2 _, simpa using le_trans yx x1 }, have S0 : 0 < Sup S := lt_of_lt_of_le x0 (le_Sup _ ⟨_, ub⟩ lb), refine ⟨Sup S, S0, le_antisymm (not_lt.1 $ λ h, _) (not_lt.1 $ λ h, _)⟩, { rw [← div_lt_iff S0, lt_Sup S ⟨_, lb⟩ ⟨_, ub⟩] at h, rcases h with ⟨y, ⟨y0, yx⟩, hy⟩, rw [div_lt_iff S0, ← div_lt_iff' y0, lt_Sup S ⟨_, lb⟩ ⟨_, ub⟩] at hy, rcases hy with ⟨z, ⟨z0, zx⟩, hz⟩, rw [div_lt_iff y0] at hz, exact not_lt_of_lt ((mul_lt_mul_right y0).1 (lt_of_le_of_lt yx hz)) ((mul_lt_mul_left z0).1 (lt_of_le_of_lt zx hz)) }, { let s := Sup S, let y := s + (x - s * s) / 3, replace h : 0 < x - s * s := sub_pos.2 h, have _30 := bit1_pos zero_le_one, have : s < y := (lt_add_iff_pos_right _).2 (div_pos h _30), refine not_le_of_lt this (le_Sup S ⟨_, ub⟩ ⟨lt_trans S0 this, _⟩), rw [add_mul_self_eq, add_assoc, ← le_sub_iff_add_le', ← add_mul, ← le_div_iff (div_pos h _30), div_div_cancel (ne_of_gt h)], apply add_le_add, { simpa using (mul_le_mul_left (@two_pos ℝ _)).2 (Sup_le_ub _ ⟨_, lb⟩ ub) }, { rw [div_le_one_iff_le _30], refine le_trans (sub_le_self _ (mul_self_nonneg _)) (le_trans x1 _), exact (le_add_iff_nonneg_left _).2 (le_of_lt two_pos) } } end def sqrt_aux (f : cau_seq ℚ abs) : ℕ → ℚ | 0 := rat.mk_nat (f 0).num.to_nat.sqrt (f 0).denom.sqrt | (n + 1) := let s := sqrt_aux n in max 0 $ (s + f (n+1) / s) / 2 theorem sqrt_aux_nonneg (f : cau_seq ℚ abs) : ∀ i : ℕ, 0 ≤ sqrt_aux f i | 0 := by rw [sqrt_aux, mk_nat_eq, mk_eq_div]; apply div_nonneg'; exact int.cast_nonneg.2 (int.of_nat_nonneg _) | (n + 1) := le_max_left _ _ /- TODO(Mario): finish the proof theorem sqrt_aux_converges (f : cau_seq ℚ abs) : ∃ h x, 0 ≤ x ∧ x * x = max 0 (mk f) ∧ mk ⟨sqrt_aux f, h⟩ = x := begin rcases sqrt_exists (le_max_left 0 (mk f)) with ⟨x, x0, hx⟩, suffices : ∃ h, mk ⟨sqrt_aux f, h⟩ = x, { exact this.imp (λ h e, ⟨x, x0, hx, e⟩) }, apply of_near, suffices : ∃ δ > 0, ∀ i, abs (↑(sqrt_aux f i) - x) < δ / 2 ^ i, { rcases this with ⟨δ, δ0, hδ⟩, intros, } end -/ noncomputable def sqrt (x : ℝ) : ℝ := classical.some (sqrt_exists (le_max_left 0 x)) /-quotient.lift_on x (λ f, mk ⟨sqrt_aux f, (sqrt_aux_converges f).fst⟩) (λ f g e, begin rcases sqrt_aux_converges f with ⟨hf, x, x0, xf, xs⟩, rcases sqrt_aux_converges g with ⟨hg, y, y0, yg, ys⟩, refine xs.trans (eq.trans _ ys.symm), rw [← @mul_self_inj_of_nonneg ℝ _ x y x0 y0, xf, yg], congr' 1, exact quotient.sound e end)-/ theorem sqrt_prop (x : ℝ) : 0 ≤ sqrt x ∧ sqrt x * sqrt x = max 0 x := classical.some_spec (sqrt_exists (le_max_left 0 x)) /-quotient.induction_on x $ λ f, by rcases sqrt_aux_converges f with ⟨hf, _, x0, xf, rfl⟩; exact ⟨x0, xf⟩-/ theorem sqrt_eq_zero_of_nonpos {x : ℝ} (h : x ≤ 0) : sqrt x = 0 := eq_zero_of_mul_self_eq_zero $ (sqrt_prop x).2.trans $ max_eq_left h theorem sqrt_nonneg (x : ℝ) : 0 ≤ sqrt x := (sqrt_prop x).1 @[simp] theorem mul_self_sqrt {x : ℝ} (h : 0 ≤ x) : sqrt x * sqrt x = x := (sqrt_prop x).2.trans (max_eq_right h) @[simp] theorem sqrt_mul_self {x : ℝ} (h : 0 ≤ x) : sqrt (x * x) = x := (mul_self_inj_of_nonneg (sqrt_nonneg _) h).1 (mul_self_sqrt (mul_self_nonneg _)) theorem sqrt_eq_iff_mul_self_eq {x y : ℝ} (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x = y ↔ y * y = x := ⟨λ h, by rw [← h, mul_self_sqrt hx], λ h, by rw [← h, sqrt_mul_self hy]⟩ @[simp] theorem sqr_sqrt {x : ℝ} (h : 0 ≤ x) : sqrt x ^ 2 = x := by rw [pow_two, mul_self_sqrt h] @[simp] theorem sqrt_sqr {x : ℝ} (h : 0 ≤ x) : sqrt (x ^ 2) = x := by rw [pow_two, sqrt_mul_self h] theorem sqrt_eq_iff_sqr_eq {x y : ℝ} (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x = y ↔ y ^ 2 = x := by rw [pow_two, sqrt_eq_iff_mul_self_eq hx hy] theorem sqrt_mul_self_eq_abs (x : ℝ) : sqrt (x * x) = abs x := (le_total 0 x).elim (λ h, (sqrt_mul_self h).trans (abs_of_nonneg h).symm) (λ h, by rw [← neg_mul_neg, sqrt_mul_self (neg_nonneg.2 h), abs_of_nonpos h]) theorem sqrt_sqr_eq_abs (x : ℝ) : sqrt (x ^ 2) = abs x := by rw [pow_two, sqrt_mul_self_eq_abs] @[simp] theorem sqrt_zero : sqrt 0 = 0 := by simpa using sqrt_mul_self (le_refl _) @[simp] theorem sqrt_one : sqrt 1 = 1 := by simpa using sqrt_mul_self zero_le_one @[simp] theorem sqrt_le {x y : ℝ} (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x ≤ sqrt y ↔ x ≤ y := by rw [mul_self_le_mul_self_iff (sqrt_nonneg _) (sqrt_nonneg _), mul_self_sqrt hx, mul_self_sqrt hy] @[simp] theorem sqrt_lt {x y : ℝ} (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x < sqrt y ↔ x < y := le_iff_le_iff_lt_iff_lt.1 (sqrt_le hy hx) @[simp] theorem sqrt_inj {x y : ℝ} (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x = sqrt y ↔ x = y := by simp [le_antisymm_iff, hx, hy] @[simp] theorem sqrt_eq_zero {x : ℝ} (h : 0 ≤ x) : sqrt x = 0 ↔ x = 0 := by simpa using sqrt_inj h (le_refl _) theorem sqrt_eq_zero' {x : ℝ} : sqrt x = 0 ↔ x ≤ 0 := (le_total x 0).elim (λ h, by simp [h, sqrt_eq_zero_of_nonpos]) (λ h, by simp [h]; simp [le_antisymm_iff, h]) @[simp] theorem sqrt_pos {x : ℝ} : 0 < sqrt x ↔ 0 < x := le_iff_le_iff_lt_iff_lt.1 (iff.trans (by simp [le_antisymm_iff, sqrt_nonneg]) sqrt_eq_zero') @[simp] theorem sqrt_mul' (x) {y : ℝ} (hy : 0 ≤ y) : sqrt (x * y) = sqrt x * sqrt y := begin cases le_total 0 x with hx hx, { refine (mul_self_inj_of_nonneg _ (mul_nonneg _ _)).1 _; try {apply sqrt_nonneg}, rw [mul_self_sqrt (mul_nonneg hx hy), mul_assoc, mul_left_comm (sqrt y), mul_self_sqrt hy, ← mul_assoc, mul_self_sqrt hx] }, { rw [sqrt_eq_zero'.2 (mul_nonpos_of_nonpos_of_nonneg hx hy), sqrt_eq_zero'.2 hx, zero_mul] } end @[simp] theorem sqrt_mul {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : sqrt (x * y) = sqrt x * sqrt y := by rw [mul_comm, sqrt_mul' _ hx, mul_comm] @[simp] theorem sqrt_inv (x : ℝ) : sqrt x⁻¹ = (sqrt x)⁻¹ := (le_or_lt x 0).elim (λ h, by simp [sqrt_eq_zero'.2, inv_nonpos, h]) (λ h, by rw [ ← mul_self_inj_of_nonneg (sqrt_nonneg _) (le_of_lt $ inv_pos $ sqrt_pos.2 h), mul_self_sqrt (le_of_lt $ inv_pos h), ← mul_inv', mul_self_sqrt (le_of_lt h)]) @[simp] theorem sqrt_div {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : sqrt (x / y) = sqrt x / sqrt y := by rw [division_def, sqrt_mul hx, sqrt_inv]; refl end real
60366dc253919307228138f3d98ae775e16bb34b
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/algebra/invertible.lean
20be5f67ab14bc0cb9968755c813be25290a4e6d
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
8,295
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Anne Baanen A typeclass for the two-sided multiplicative inverse. -/ import algebra.char_zero import algebra.char_p /-! # Invertible elements This file defines a typeclass `invertible a` for elements `a` with a multiplicative inverse. The intent of the typeclass is to provide a way to write e.g. `⅟2` in a ring like `ℤ[1/2]` where some inverses exist but there is no general `⁻¹` operator; or to specify that a field has characteristic `≠ 2`. It is the `Type`-valued analogue to the `Prop`-valued `is_unit`. This file also includes some instances of `invertible` for specific numbers in characteristic zero. Some more cases are given as a `def`, to be included only when needed. To construct instances for concrete numbers, `invertible_of_nonzero` is a useful definition. ## Notation * `⅟a` is `invertible.inv_of a`, the inverse of `a` ## Implementation notes The `invertible` class lives in `Type`, not `Prop`, to make computation easier. If multiplication is associative, `invertible` is a subsingleton anyway. The `simp` normal form tries to normalize `⅟a` to `a ⁻¹`. Otherwise, it pushes `⅟` inside the expression as much as possible. ## Tags invertible, inverse element, inv_of, a half, one half, a third, one third, ½, ⅓ -/ universes u variables {α : Type u} /-- `invertible a` gives a two-sided multiplicative inverse of `a`. -/ class invertible [has_mul α] [has_one α] (a : α) : Type u := (inv_of : α) (inv_of_mul_self : inv_of * a = 1) (mul_inv_of_self : a * inv_of = 1) -- This notation has the same precedence as `has_inv.inv`. notation `⅟`:1034 := invertible.inv_of @[simp] lemma inv_of_mul_self [has_mul α] [has_one α] (a : α) [invertible a] : ⅟a * a = 1 := invertible.inv_of_mul_self @[simp] lemma mul_inv_of_self [has_mul α] [has_one α] (a : α) [invertible a] : a * ⅟a = 1 := invertible.mul_inv_of_self @[simp] lemma mul_inv_of_mul_self_cancel [monoid α] (a b : α) [invertible b] : a * ⅟b * b = a := by simp [mul_assoc] @[simp] lemma mul_mul_inv_of_self_cancel [monoid α] (a b : α) [invertible b] : a * b * ⅟b = a := by simp [mul_assoc] lemma inv_of_eq_right_inv [monoid α] {a b : α} [invertible a] (hac : a * b = 1) : ⅟a = b := left_inv_eq_right_inv (inv_of_mul_self _) hac lemma invertible_unique {α : Type u} [monoid α] (a b : α) (h : a = b) [invertible a] [invertible b] : ⅟a = ⅟b := by { apply inv_of_eq_right_inv, rw [h, mul_inv_of_self], } instance [monoid α] (a : α) : subsingleton (invertible a) := ⟨ λ ⟨b, hba, hab⟩ ⟨c, hca, hac⟩, by { congr, exact left_inv_eq_right_inv hba hac } ⟩ /-- An `invertible` element is a unit. -/ def unit_of_invertible [monoid α] (a : α) [invertible a] : units α := { val := a, inv := ⅟a, val_inv := by simp, inv_val := by simp, } @[simp] lemma unit_of_invertible_val [monoid α] (a : α) [invertible a] : (unit_of_invertible a : α) = a := rfl @[simp] lemma unit_of_invertible_inv [monoid α] (a : α) [invertible a] : (↑(unit_of_invertible a)⁻¹ : α) = ⅟a := rfl lemma is_unit_of_invertible [monoid α] (a : α) [invertible a] : is_unit a := ⟨unit_of_invertible a, rfl⟩ /-- Each element of a group is invertible. -/ def invertible_of_group [group α] (a : α) : invertible a := ⟨a⁻¹, inv_mul_self a, mul_inv_self a⟩ @[simp] lemma inv_of_eq_group_inv [group α] (a : α) [invertible a] : ⅟a = a⁻¹ := inv_of_eq_right_inv (mul_inv_self a) /-- `1` is the inverse of itself -/ def invertible_one [monoid α] : invertible (1 : α) := ⟨ 1, mul_one _, one_mul _ ⟩ @[simp] lemma inv_of_one [monoid α] [invertible (1 : α)] : ⅟(1 : α) = 1 := inv_of_eq_right_inv (mul_one _) /-- `-⅟a` is the inverse of `-a` -/ def invertible_neg [ring α] (a : α) [invertible a] : invertible (-a) := ⟨ -⅟a, by simp, by simp ⟩ @[simp] lemma inv_of_neg [ring α] (a : α) [invertible a] [invertible (-a)] : ⅟(-a) = -⅟a := inv_of_eq_right_inv (by simp) /-- `a` is the inverse of `⅟a`. -/ def invertible_inv_of [has_one α] [has_mul α] {a : α} [invertible a] : invertible (⅟a) := ⟨ a, mul_inv_of_self a, inv_of_mul_self a ⟩ @[simp] lemma inv_of_inv_of [monoid α] {a : α} [invertible a] [invertible (⅟a)] : ⅟(⅟a) = a := inv_of_eq_right_inv (inv_of_mul_self _) /-- `⅟b * ⅟a` is the inverse of `a * b` -/ def invertible_mul [monoid α] (a b : α) [invertible a] [invertible b] : invertible (a * b) := ⟨ ⅟b * ⅟a, by simp [←mul_assoc], by simp [←mul_assoc] ⟩ @[simp] lemma inv_of_mul [monoid α] (a b : α) [invertible a] [invertible b] [invertible (a * b)] : ⅟(a * b) = ⅟b * ⅟a := inv_of_eq_right_inv (by simp [←mul_assoc]) section group_with_zero variable [group_with_zero α] lemma nonzero_of_invertible (a : α) [invertible a] : a ≠ 0 := λ ha, zero_ne_one $ calc 0 = ⅟a * a : by simp [ha] ... = 1 : inv_of_mul_self a /-- `a⁻¹` is an inverse of `a` if `a ≠ 0` -/ def invertible_of_nonzero {a : α} (h : a ≠ 0) : invertible a := ⟨ a⁻¹, inv_mul_cancel h, mul_inv_cancel h ⟩ @[simp] lemma inv_of_eq_inv (a : α) [invertible a] : ⅟a = a⁻¹ := inv_of_eq_right_inv (mul_inv_cancel (nonzero_of_invertible a)) @[simp] lemma inv_mul_cancel_of_invertible (a : α) [invertible a] : a⁻¹ * a = 1 := inv_mul_cancel (nonzero_of_invertible a) @[simp] lemma mul_inv_cancel_of_invertible (a : α) [invertible a] : a * a⁻¹ = 1 := mul_inv_cancel (nonzero_of_invertible a) @[simp] lemma div_mul_cancel_of_invertible (a b : α) [invertible b] : a / b * b = a := div_mul_cancel a (nonzero_of_invertible b) @[simp] lemma mul_div_cancel_of_invertible (a b : α) [invertible b] : a * b / b = a := mul_div_cancel a (nonzero_of_invertible b) @[simp] lemma div_self_of_invertible (a : α) [invertible a] : a / a = 1 := div_self (nonzero_of_invertible a) /-- `b / a` is the inverse of `a / b` -/ def invertible_div (a b : α) [invertible a] [invertible b] : invertible (a / b) := ⟨b / a, by simp [←mul_div_assoc], by simp [←mul_div_assoc]⟩ @[simp] lemma inv_of_div (a b : α) [invertible a] [invertible b] [invertible (a / b)] : ⅟(a / b) = b / a := inv_of_eq_right_inv (by simp [←mul_div_assoc]) /-- `a` is the inverse of `a⁻¹` -/ def invertible_inv {a : α} [invertible a] : invertible (a⁻¹) := ⟨ a, by simp, by simp ⟩ end group_with_zero /-- Monoid homs preserve invertibility. -/ def invertible.map {R : Type*} {S : Type*} [monoid R] [monoid S] (f : R →* S) (r : R) [invertible r] : invertible (f r) := { inv_of := f (⅟r), inv_of_mul_self := by rw [← f.map_mul, inv_of_mul_self, f.map_one], mul_inv_of_self := by rw [← f.map_mul, mul_inv_of_self, f.map_one] } section ring_char /-- A natural number `t` is invertible in a field `K` if the charactistic of `K` does not divide `t`. -/ def invertible_of_ring_char_not_dvd {K : Type*} [field K] {t : ℕ} (not_dvd : ¬(ring_char K ∣ t)) : invertible (t : K) := invertible_of_nonzero (λ h, not_dvd ((ring_char.spec K t).mp h)) end ring_char section char_p /-- A natural number `t` is invertible in a field `K` of charactistic `p` if `p` does not divide `t`. -/ def invertible_of_char_p_not_dvd {K : Type*} [field K] {p : ℕ} [char_p K p] {t : ℕ} (not_dvd : ¬(p ∣ t)) : invertible (t : K) := invertible_of_nonzero (λ h, not_dvd ((char_p.cast_eq_zero_iff K p t).mp h)) instance invertible_of_pos {K : Type*} [field K] [char_zero K] (n : ℕ) [h : fact (0 < n)] : invertible (n : K) := invertible_of_nonzero $ by simpa [nat.pos_iff_ne_zero] using h end char_p section division_ring variable [division_ring α] instance invertible_succ [char_zero α] (n : ℕ) : invertible (n.succ : α) := invertible_of_nonzero (nat.cast_ne_zero.mpr (nat.succ_ne_zero _)) /-! A few `invertible n` instances for small numerals `n`. Feel free to add your own number when you need its inverse. -/ instance invertible_two [char_zero α] : invertible (2 : α) := invertible_of_nonzero (by exact_mod_cast (dec_trivial : 2 ≠ 0)) instance invertible_three [char_zero α] : invertible (3 : α) := invertible_of_nonzero (by exact_mod_cast (dec_trivial : 3 ≠ 0)) end division_ring
99d8db2efd49c8d50ed6ed33d4d2dc0f4c444fbc
690889011852559ee5ac4dfea77092de8c832e7e
/src/ring_theory/algebra.lean
87a8cafdac33d8eb25c42082db9f372d09dc2032
[ "Apache-2.0" ]
permissive
williamdemeo/mathlib
f6df180148f8acc91de9ba5e558976ab40a872c7
1fa03c29f9f273203bbffb79d10d31f696b3d317
refs/heads/master
1,584,785,260,929
1,572,195,914,000
1,572,195,913,000
138,435,193
0
0
Apache-2.0
1,529,789,739,000
1,529,789,739,000
null
UTF-8
Lean
false
false
19,349
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Algebra over Commutative Ring (under category) -/ import data.polynomial data.mv_polynomial import data.complex.basic import linear_algebra.tensor_product import ring_theory.subring noncomputable theory universes u v w u₁ v₁ open lattice open_locale tensor_product /-- The category of R-algebras where R is a commutative ring is the under category R ↓ CRing. In the categorical setting we have a forgetful functor R-Alg ⥤ R-Mod. However here it extends module in order to preserve definitional equality in certain cases. -/ class algebra (R : Type u) (A : Type v) [comm_ring R] [ring A] extends has_scalar R A := (to_fun : R → A) [hom : is_ring_hom to_fun] (commutes' : ∀ r x, x * to_fun r = to_fun r * x) (smul_def' : ∀ r x, r • x = to_fun r * x) attribute [instance] algebra.hom def algebra_map {R : Type u} (A : Type v) [comm_ring R] [ring A] [algebra R A] (x : R) : A := algebra.to_fun A x namespace algebra variables {R : Type u} {S : Type v} {A : Type w} variables [comm_ring R] [comm_ring S] [ring A] [algebra R A] /-- The codomain of an algebra. -/ instance : has_scalar R A := infer_instance include R instance : is_ring_hom (algebra_map A : R → A) := algebra.hom _ A variables (A) @[simp] lemma map_add (r s : R) : algebra_map A (r + s) = algebra_map A r + algebra_map A s := is_ring_hom.map_add _ @[simp] lemma map_neg (r : R) : algebra_map A (-r) = -algebra_map A r := is_ring_hom.map_neg _ @[simp] lemma map_sub (r s : R) : algebra_map A (r - s) = algebra_map A r - algebra_map A s := is_ring_hom.map_sub _ @[simp] lemma map_mul (r s : R) : algebra_map A (r * s) = algebra_map A r * algebra_map A s := is_ring_hom.map_mul _ variables (R) @[simp] lemma map_zero : algebra_map A (0 : R) = 0 := is_ring_hom.map_zero _ @[simp] lemma map_one : algebra_map A (1 : R) = 1 := is_ring_hom.map_one _ variables {R A} /-- Creating an algebra from a morphism in CRing. -/ def of_ring_hom (i : R → S) (hom : is_ring_hom i) : algebra R S := { smul := λ c x, i c * x, to_fun := i, commutes' := λ _ _, mul_comm _ _, smul_def' := λ c x, rfl } theorem smul_def (r : R) (x : A) : r • x = algebra_map A r * x := algebra.smul_def' r x theorem commutes (r : R) (x : A) : x * algebra_map A r = algebra_map A r * x := algebra.commutes' r x theorem left_comm (r : R) (x y : A) : x * (algebra_map A r * y) = algebra_map A r * (x * y) := by rw [← mul_assoc, commutes, mul_assoc] @[simp] lemma mul_smul_comm (s : R) (x y : A) : x * (s • y) = s • (x * y) := by rw [smul_def, smul_def, left_comm] @[simp] lemma smul_mul_assoc (r : R) (x y : A) : (r • x) * y = r • (x * y) := by rw [smul_def, smul_def, mul_assoc] instance to_module : module R A := { one_smul := by simp [smul_def], mul_smul := by simp [smul_def, mul_assoc], smul_add := by simp [smul_def, mul_add], smul_zero := by simp [smul_def], add_smul := by simp [smul_def, add_mul], zero_smul := by simp [smul_def] } omit R instance {F : Type u} {K : Type v} [discrete_field F] [ring K] [algebra F K] : vector_space F K := @vector_space.mk F _ _ _ algebra.to_module /-- R[X] is the generator of the category R-Alg. -/ instance polynomial (R : Type u) [comm_ring R] : algebra R (polynomial R) := { to_fun := polynomial.C, commutes' := λ _ _, mul_comm _ _, smul_def' := λ c p, (polynomial.C_mul' c p).symm, .. polynomial.module } /-- The algebra of multivariate polynomials. -/ instance mv_polynomial (R : Type u) [comm_ring R] (ι : Type v) : algebra R (mv_polynomial ι R) := { to_fun := mv_polynomial.C, commutes' := λ _ _, mul_comm _ _, smul_def' := λ c p, (mv_polynomial.C_mul' c p).symm, .. mv_polynomial.module } /-- Creating an algebra from a subring. This is the dual of ring extension. -/ instance of_subring (S : set R) [is_subring S] : algebra S R := of_ring_hom subtype.val ⟨rfl, λ _ _, rfl, λ _ _, rfl⟩ variables (R A) /-- The multiplication in an algebra is a bilinear map. -/ def lmul : A →ₗ A →ₗ A := linear_map.mk₂ R (*) (λ x y z, add_mul x y z) (λ c x y, by rw [smul_def, smul_def, mul_assoc _ x y]) (λ x y z, mul_add x y z) (λ c x y, by rw [smul_def, smul_def, left_comm]) set_option class.instance_max_depth 39 def lmul_left (r : A) : A →ₗ A := lmul R A r def lmul_right (r : A) : A →ₗ A := (lmul R A).flip r variables {R A} @[simp] lemma lmul_apply (p q : A) : lmul R A p q = p * q := rfl @[simp] lemma lmul_left_apply (p q : A) : lmul_left R A p q = p * q := rfl @[simp] lemma lmul_right_apply (p q : A) : lmul_right R A p q = q * p := rfl end algebra instance module.endomorphism_algebra (R : Type u) (M : Type v) [comm_ring R] [add_comm_group M] [module R M] : algebra R (M →ₗ[R] M) := { to_fun := (λ r, r • linear_map.id), hom := by apply is_ring_hom.mk; intros; ext; simp [mul_smul, add_smul], commutes' := by intros; ext; simp, smul_def' := by intros; ext; simp } set_option old_structure_cmd true /-- Defining the homomorphism in the category R-Alg. -/ structure alg_hom (R : Type u) (A : Type v) (B : Type w) [comm_ring R] [ring A] [ring B] [algebra R A] [algebra R B] extends ring_hom A B := (commutes' : ∀ r : R, to_fun (algebra_map A r) = algebra_map B r) infixr ` →ₐ `:25 := alg_hom _ notation A ` →ₐ[`:25 R `] ` B := alg_hom R A B namespace alg_hom variables {R : Type u} {A : Type v} {B : Type w} {C : Type u₁} {D : Type v₁} variables {rR : comm_ring R} {rA : ring A} {rB : ring B} {rC : ring C} {rD : ring D} variables {aA : algebra R A} {aB : algebra R B} {aC : algebra R C} {aD : algebra R D} include R rR rA rB aA aB instance : has_coe_to_fun (A →ₐ[R] B) := ⟨_, λ f, f.to_fun⟩ instance : has_coe (A →ₐ[R] B) (A →+* B) := ⟨alg_hom.to_ring_hom⟩ variables (φ : A →ₐ[R] B) instance : is_ring_hom ⇑φ := ring_hom.is_ring_hom φ.to_ring_hom @[extensionality] theorem ext {φ₁ φ₂ : A →ₐ[R] B} (H : ∀ x, φ₁ x = φ₂ x) : φ₁ = φ₂ := by cases φ₁; cases φ₂; congr' 1; ext; apply H theorem commutes (r : R) : φ (algebra_map A r) = algebra_map B r := φ.commutes' r @[simp] lemma map_add (r s : A) : φ (r + s) = φ r + φ s := is_ring_hom.map_add _ @[simp] lemma map_zero : φ 0 = 0 := is_ring_hom.map_zero _ @[simp] lemma map_neg (x) : φ (-x) = -φ x := is_ring_hom.map_neg _ @[simp] lemma map_sub (x y) : φ (x - y) = φ x - φ y := is_ring_hom.map_sub _ @[simp] lemma map_mul (x y) : φ (x * y) = φ x * φ y := is_ring_hom.map_mul _ @[simp] lemma map_one : φ 1 = 1 := is_ring_hom.map_one _ /-- R-Alg ⥤ R-Mod -/ def to_linear_map : A →ₗ B := { to_fun := φ, add := φ.map_add, smul := λ (c : R) x, by rw [algebra.smul_def, φ.map_mul, φ.commutes c, algebra.smul_def] } @[simp] lemma to_linear_map_apply (p : A) : φ.to_linear_map p = φ p := rfl theorem to_linear_map_inj {φ₁ φ₂ : A →ₐ[R] B} (H : φ₁.to_linear_map = φ₂.to_linear_map) : φ₁ = φ₂ := ext $ λ x, show φ₁.to_linear_map x = φ₂.to_linear_map x, by rw H variables (R A) omit rB aB variables [rR] [rA] [aA] protected def id : A →ₐ[R] A := { commutes' := λ _, rfl, ..ring_hom.id A } variables {R A rR rA aA} @[simp] lemma id_to_linear_map : (alg_hom.id R A).to_linear_map = @linear_map.id R A _ _ _ := rfl @[simp] lemma id_apply (p : A) : alg_hom.id R A p = p := rfl include rB rC aB aC def comp (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) : A →ₐ[R] C := { commutes' := λ r : R, by rw [← φ₁.commutes, ← φ₂.commutes]; refl, .. φ₁.to_ring_hom.comp ↑φ₂ } @[simp] lemma comp_to_linear_map (f : A →ₐ[R] B) (g : B →ₐ[R] C) : (g.comp f).to_linear_map = g.to_linear_map.comp f.to_linear_map := rfl @[simp] lemma comp_apply (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) (p : A) : φ₁.comp φ₂ p = φ₁ (φ₂ p) := rfl omit rC aC @[simp] theorem comp_id : φ.comp (alg_hom.id R A) = φ := ext $ λ x, rfl @[simp] theorem id_comp : (alg_hom.id R B).comp φ = φ := ext $ λ x, rfl include rC aC rD aD theorem comp_assoc (φ₁ : C →ₐ[R] D) (φ₂ : B →ₐ[R] C) (φ₃ : A →ₐ[R] B) : (φ₁.comp φ₂).comp φ₃ = φ₁.comp (φ₂.comp φ₃) := ext $ λ x, rfl end alg_hom namespace algebra variables (R : Type u) (S : Type v) (A : Type w) variables [comm_ring R] [comm_ring S] [ring A] [algebra R S] [algebra S A] include R S A def comap : Type w := A def comap.to_comap : A → comap R S A := id def comap.of_comap : comap R S A → A := id omit R S A instance comap.ring : ring (comap R S A) := _inst_3 instance comap.comm_ring (R : Type u) (S : Type v) (A : Type w) [comm_ring R] [comm_ring S] [comm_ring A] [algebra R S] [algebra S A] : comm_ring (comap R S A) := _inst_8 instance comap.module : module S (comap R S A) := show module S A, by apply_instance instance comap.has_scalar : has_scalar S (comap R S A) := show has_scalar S A, by apply_instance set_option class.instance_max_depth 40 /-- R ⟶ S induces S-Alg ⥤ R-Alg -/ instance comap.algebra : algebra R (comap R S A) := { smul := λ r x, (algebra_map S r • x : A), to_fun := (algebra_map A : S → A) ∘ algebra_map S, hom := by letI : is_ring_hom (algebra_map A) := _inst_5.hom; apply_instance, commutes' := λ r x, algebra.commutes _ _, smul_def' := λ _ _, algebra.smul_def _ _ } def to_comap : S →ₐ[R] comap R S A := { commutes' := λ r, rfl, ..ring_hom.of (algebra_map A : S → A) } theorem to_comap_apply (x) : to_comap R S A x = (algebra_map A : S → A) x := rfl end algebra namespace alg_hom variables {R : Type u} {S : Type v} {A : Type w} {B : Type u₁} variables [comm_ring R] [comm_ring S] [ring A] [ring B] variables [algebra R S] [algebra S A] [algebra S B] (φ : A →ₐ[S] B) include R /-- R ⟶ S induces S-Alg ⥤ R-Alg -/ def comap : algebra.comap R S A →ₐ[R] algebra.comap R S B := { commutes' := λ r, φ.commutes (algebra_map S r) ..φ } end alg_hom namespace polynomial variables (R : Type u) (A : Type v) variables [comm_ring R] [comm_ring A] [algebra R A] variables (x : A) /-- A → Hom[R-Alg](R[X],A) -/ def aeval : polynomial R →ₐ[R] A := { commutes' := λ r, eval₂_C _ _, ..ring_hom.of (eval₂ (algebra_map A) x) } theorem aeval_def (p : polynomial R) : aeval R A x p = eval₂ (algebra_map A) x p := rfl instance aeval.is_ring_hom : is_ring_hom (aeval R A x) := by apply_instance theorem eval_unique (φ : polynomial R →ₐ[R] A) (p) : φ p = eval₂ (algebra_map A) (φ X) p := begin apply polynomial.induction_on p, { intro r, rw eval₂_C, exact φ.commutes r }, { intros f g ih1 ih2, rw [is_ring_hom.map_add φ, ih1, ih2, eval₂_add] }, { intros n r ih, rw [pow_succ', ← mul_assoc, is_ring_hom.map_mul φ, eval₂_mul (algebra_map A : R → A), eval₂_X, ih] } end end polynomial namespace mv_polynomial variables (R : Type u) (A : Type v) variables [comm_ring R] [comm_ring A] [algebra R A] variables (σ : set A) /-- (ι → A) → Hom[R-Alg](R[ι],A) -/ def aeval : mv_polynomial σ R →ₐ[R] A := { commutes' := λ r, eval₂_C _ _ _ ..ring_hom.of (eval₂ (algebra_map A) subtype.val) } theorem aeval_def (p : mv_polynomial σ R) : aeval R A σ p = eval₂ (algebra_map A) subtype.val p := rfl instance aeval.is_ring_hom : is_ring_hom (aeval R A σ) := by apply_instance variables (ι : Type w) theorem eval_unique (φ : mv_polynomial ι R →ₐ[R] A) (p) : φ p = eval₂ (algebra_map A) (φ ∘ X) p := begin apply mv_polynomial.induction_on p, { intro r, rw eval₂_C, exact φ.commutes r }, { intros f g ih1 ih2, rw [is_ring_hom.map_add φ, ih1, ih2, eval₂_add] }, { intros p j ih, rw [is_ring_hom.map_mul φ, eval₂_mul, eval₂_X, ih] } end end mv_polynomial namespace complex instance algebra_over_reals : algebra ℝ ℂ := algebra.of_ring_hom coe $ by constructor; intros; simp [one_re] instance : has_scalar ℝ ℂ := { smul := λ r c, ↑r * c} end complex structure subalgebra (R : Type u) (A : Type v) [comm_ring R] [ring A] [algebra R A] : Type v := (carrier : set A) [subring : is_subring carrier] (range_le : set.range (algebra_map A : R → A) ≤ carrier) attribute [instance] subalgebra.subring namespace subalgebra variables {R : Type u} {A : Type v} variables [comm_ring R] [ring A] [algebra R A] include R instance : has_coe (subalgebra R A) (set A) := ⟨λ S, S.carrier⟩ instance : has_mem A (subalgebra R A) := ⟨λ x S, x ∈ S.carrier⟩ variables {A} theorem mem_coe {x : A} {s : subalgebra R A} : x ∈ (s : set A) ↔ x ∈ s := iff.rfl @[extensionality] theorem ext {S T : subalgebra R A} (h : ∀ x : A, x ∈ S ↔ x ∈ T) : S = T := by cases S; cases T; congr; ext x; exact h x variables (S : subalgebra R A) instance : is_subring (S : set A) := S.subring instance : ring S := @@subtype.ring _ S.is_subring instance (R : Type u) (A : Type v) {rR : comm_ring R} [comm_ring A] {aA : algebra R A} (S : subalgebra R A) : comm_ring S := @@subtype.comm_ring _ S.is_subring instance algebra : algebra R S := { smul := λ (c:R) x, ⟨c • x.1, by rw algebra.smul_def; exact @@is_submonoid.mul_mem _ S.2.2 (S.3 ⟨c, rfl⟩) x.2⟩, to_fun := λ r, ⟨algebra_map A r, S.range_le ⟨r, rfl⟩⟩, hom := ⟨subtype.eq $ algebra.map_one R A, λ x y, subtype.eq $ algebra.map_mul A x y, λ x y, subtype.eq $ algebra.map_add A x y⟩, commutes' := λ c x, subtype.eq $ by apply _inst_3.4, smul_def' := λ c x, subtype.eq $ by apply _inst_3.5 } instance to_algebra (R : Type u) (A : Type v) [comm_ring R] [comm_ring A] [algebra R A] (S : subalgebra R A) : algebra S A := algebra.of_subring _ def val : S →ₐ[R] A := by refine_struct { to_fun := subtype.val }; intros; refl def to_submodule : submodule R A := { carrier := S.carrier, zero := (0:S).2, add := λ x y hx hy, (⟨x, hx⟩ + ⟨y, hy⟩ : S).2, smul := λ c x hx, (algebra.smul_def c x).symm ▸ (⟨algebra_map A c, S.range_le ⟨c, rfl⟩⟩ * ⟨x, hx⟩:S).2 } instance coe_to_submodule : has_coe (subalgebra R A) (submodule R A) := ⟨to_submodule⟩ instance to_submodule.is_subring : is_subring ((S : submodule R A) : set A) := S.2 instance : partial_order (subalgebra R A) := { le := λ S T, S.carrier ≤ T.carrier, le_refl := λ _, le_refl _, le_trans := λ _ _ _, le_trans, le_antisymm := λ S T hst hts, ext $ λ x, ⟨@hst x, @hts x⟩ } def comap {R : Type u} {S : Type v} {A : Type w} [comm_ring R] [comm_ring S] [ring A] [algebra R S] [algebra S A] (iSB : subalgebra S A) : subalgebra R (algebra.comap R S A) := { carrier := (iSB : set A), subring := iSB.is_subring, range_le := λ a ⟨r, hr⟩, hr ▸ iSB.range_le ⟨_, rfl⟩ } set_option class.instance_max_depth 48 def under {R : Type u} {A : Type v} [comm_ring R] [comm_ring A] {i : algebra R A} (S : subalgebra R A) (T : subalgebra S A) : subalgebra R A := { carrier := T, range_le := (λ a ⟨r, hr⟩, hr ▸ T.range_le ⟨⟨algebra_map A r, S.range_le ⟨r, rfl⟩⟩, rfl⟩) } end subalgebra namespace alg_hom variables {R : Type u} {A : Type v} {B : Type w} variables [comm_ring R] [ring A] [ring B] [algebra R A] [algebra R B] variables (φ : A →ₐ[R] B) protected def range : subalgebra R B := { carrier := set.range φ, subring := { one_mem := ⟨1, φ.map_one⟩, mul_mem := λ y₁ y₂ ⟨x₁, hx₁⟩ ⟨x₂, hx₂⟩, ⟨x₁ * x₂, hx₁ ▸ hx₂ ▸ φ.map_mul x₁ x₂⟩ }, range_le := λ y ⟨r, hr⟩, ⟨algebra_map A r, hr ▸ φ.commutes r⟩ } end alg_hom namespace algebra variables {R : Type u} (A : Type v) variables [comm_ring R] [ring A] [algebra R A] include R variables (R) instance id : algebra R R := algebra.of_ring_hom id $ by apply_instance def of_id : R →ₐ A := { commutes' := λ _, rfl, .. ring_hom.of (algebra_map A) } variables {R} theorem of_id_apply (r) : of_id R A r = algebra_map A r := rfl variables (R) {A} def adjoin (s : set A) : subalgebra R A := { carrier := ring.closure (set.range (algebra_map A : R → A) ∪ s), range_le := le_trans (set.subset_union_left _ _) ring.subset_closure } variables {R} protected lemma gc : galois_connection (adjoin R : set A → subalgebra R A) coe := λ s S, ⟨λ H, le_trans (le_trans (set.subset_union_right _ _) ring.subset_closure) H, λ H, ring.closure_subset $ set.union_subset S.range_le H⟩ protected def gi : galois_insertion (adjoin R : set A → subalgebra R A) coe := { choice := λ s hs, adjoin R s, gc := algebra.gc, le_l_u := λ S, (algebra.gc (S : set A) (adjoin R S)).1 $ le_refl _, choice_eq := λ _ _, rfl } instance : complete_lattice (subalgebra R A) := galois_insertion.lift_complete_lattice algebra.gi theorem mem_bot {x : A} : x ∈ (⊥ : subalgebra R A) ↔ x ∈ set.range (algebra_map A : R → A) := suffices (⊥ : subalgebra R A) = (of_id R A).range, by rw this; refl, le_antisymm bot_le $ subalgebra.range_le _ theorem mem_top {x : A} : x ∈ (⊤ : subalgebra R A) := ring.mem_closure $ or.inr trivial def to_top : A →ₐ[R] (⊤ : subalgebra R A) := by refine_struct { to_fun := λ x, (⟨x, mem_top⟩ : (⊤ : subalgebra R A)) }; intros; refl end algebra section int variables (R : Type*) [comm_ring R] /-- CRing ⥤ ℤ-Alg -/ def alg_hom_int {R : Type u} [comm_ring R] [algebra ℤ R] {S : Type v} [comm_ring S] [algebra ℤ S] (f : R → S) [is_ring_hom f] : R →ₐ[ℤ] S := { commutes' := λ i, by change (ring_hom.of f).to_fun with f; exact int.induction_on i (by rw [algebra.map_zero, algebra.map_zero, is_ring_hom.map_zero f]) (λ i ih, by rw [algebra.map_add, algebra.map_add, algebra.map_one, algebra.map_one]; rw [is_ring_hom.map_add f, is_ring_hom.map_one f, ih]) (λ i ih, by rw [algebra.map_sub, algebra.map_sub, algebra.map_one, algebra.map_one]; rw [is_ring_hom.map_sub f, is_ring_hom.map_one f, ih]), ..ring_hom.of f } /-- CRing ⥤ ℤ-Alg -/ instance algebra_int : algebra ℤ R := algebra.of_ring_hom coe $ by constructor; intros; simp variables {R} /-- CRing ⥤ ℤ-Alg -/ def subalgebra_of_subring (S : set R) [is_subring S] : subalgebra ℤ R := { carrier := S, range_le := λ x ⟨i, h⟩, h ▸ int.induction_on i (by rw algebra.map_zero; exact is_add_submonoid.zero_mem _) (λ i hi, by rw [algebra.map_add, algebra.map_one]; exact is_add_submonoid.add_mem hi (is_submonoid.one_mem _)) (λ i hi, by rw [algebra.map_sub, algebra.map_one]; exact is_add_subgroup.sub_mem _ _ _ hi (is_submonoid.one_mem _)) } @[simp] lemma mem_subalgebra_of_subring {x : R} {S : set R} [is_subring S] : x ∈ subalgebra_of_subring S ↔ x ∈ S := iff.rfl section span_int open submodule lemma span_int_eq_add_group_closure (s : set R) : ↑(span ℤ s) = add_group.closure s := set.subset.antisymm (λ x hx, span_induction hx (λ _, add_group.mem_closure) (is_add_submonoid.zero_mem _) (λ a b ha hb, is_add_submonoid.add_mem ha hb) (λ n a ha, by { erw [show n • a = gsmul n a, from (gsmul_eq_mul a n).symm], exact is_add_subgroup.gsmul_mem ha})) (add_group.closure_subset subset_span) @[simp] lemma span_int_eq (s : set R) [is_add_subgroup s] : (↑(span ℤ s) : set R) = s := by rw [span_int_eq_add_group_closure, add_group.closure_add_subgroup] end span_int end int
494387b752cd0ce343af520a8043de5d208e89d5
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/ring2.lean
044ea34dd20a9b75dfcd6ab5e2d7ac22dca55a3e
[ "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
21,003
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import tactic.ring import data.num.lemmas import data.tree /-! # ring2 An experimental variant on the `ring` tactic that uses computational reflection instead of proof generation. Useful for kernel benchmarking. -/ namespace tree /-- `(reflect' t u α)` quasiquotes a tree `(t: tree expr)` of quoted values of type `α` at level `u` into an `expr` which reifies to a `tree α` containing the reifications of the `expr`s from the original `t`. -/ protected meta def reflect' (u : level) (α : expr) : tree expr → expr | tree.nil := (expr.const ``tree.nil [u] : expr) α | (tree.node a t₁ t₂) := (expr.const ``tree.node [u] : expr) α a t₁.reflect' t₂.reflect' /-- Returns an element indexed by `n`, or zero if `n` isn't a valid index. See `tree.get`. -/ protected def get_or_zero {α} [has_zero α] (t : tree α) (n : pos_num) : α := t.get_or_else n 0 end tree namespace tactic.ring2 /-- A reflected/meta representation of an expression in a commutative semiring. This representation is a direct translation of such expressions - see `horner_expr` for a normal form. -/ @[derive has_reflect] inductive csring_expr /- (atom n) is an opaque element of the csring. For example, a local variable in the context. n indexes into a storage of such atoms - a `tree α`. -/ | atom : pos_num → csring_expr /- (const n) is technically the csring's one, added n times. Or the zero if n is 0. -/ | const : num → csring_expr | add : csring_expr → csring_expr → csring_expr | mul : csring_expr → csring_expr → csring_expr | pow : csring_expr → num → csring_expr namespace csring_expr instance : inhabited csring_expr := ⟨const 0⟩ /-- Evaluates a reflected `csring_expr` into an element of the original `comm_semiring` type `α`, retrieving opaque elements (atoms) from the tree `t`. -/ def eval {α} [comm_semiring α] (t : tree α) : csring_expr → α | (atom n) := t.get_or_zero n | (const n) := n | (add x y) := eval x + eval y | (mul x y) := eval x * eval y | (pow x n) := eval x ^ (n : ℕ) end csring_expr /-- An efficient representation of expressions in a commutative semiring using the sparse Horner normal form. This type admits non-optimal instantiations (e.g. `P` can be represented as `P+0+0`), so to get good performance out of it, care must be taken to maintain an optimal, *canonical* form. -/ @[derive decidable_eq] inductive horner_expr /- (const n) is a constant n in the csring, similarly to the same constructor in `csring_expr`. This one, however, can be negative. -/ | const : znum → horner_expr /- (horner a x n b) is a*xⁿ + b, where x is the x-th atom in the atom tree. -/ | horner : horner_expr → pos_num → num → horner_expr → horner_expr namespace horner_expr /-- True iff the `horner_expr` argument is a valid `csring_expr`. For that to be the case, all its constants must be non-negative. -/ def is_cs : horner_expr → Prop | (const n) := ∃ m:num, n = m.to_znum | (horner a x n b) := is_cs a ∧ is_cs b instance : has_zero horner_expr := ⟨const 0⟩ instance : has_one horner_expr := ⟨const 1⟩ instance : inhabited horner_expr := ⟨0⟩ /-- Represent a `csring_expr.atom` in Horner form. -/ def atom (n : pos_num) : horner_expr := horner 1 n 1 0 def to_string : horner_expr → string | (const n) := _root_.repr n | (horner a x n b) := "(" ++ to_string a ++ ") * x" ++ _root_.repr x ++ "^" ++ _root_.repr n ++ " + " ++ to_string b instance : has_to_string horner_expr := ⟨to_string⟩ /-- Alternative constructor for (horner a x n b) which maintains canonical form by simplifying special cases of `a`. -/ def horner' (a : horner_expr) (x : pos_num) (n : num) (b : horner_expr) : horner_expr := match a with | const q := if q = 0 then b else horner a x n b | horner a₁ x₁ n₁ b₁ := if x₁ = x ∧ b₁ = 0 then horner a₁ x (n₁ + n) b else horner a x n b end def add_const (k : znum) (e : horner_expr) : horner_expr := if k = 0 then e else begin induction e with n a x n b A B, { exact const (k + n) }, { exact horner a x n B } end def add_aux (a₁ : horner_expr) (A₁ : horner_expr → horner_expr) (x₁ : pos_num) : horner_expr → num → horner_expr → (horner_expr → horner_expr) → horner_expr | (const n₂) n₁ b₁ B₁ := add_const n₂ (horner a₁ x₁ n₁ b₁) | (horner a₂ x₂ n₂ b₂) n₁ b₁ B₁ := let e₂ := horner a₂ x₂ n₂ b₂ in match pos_num.cmp x₁ x₂ with | ordering.lt := horner a₁ x₁ n₁ (B₁ e₂) | ordering.gt := horner a₂ x₂ n₂ (add_aux b₂ n₁ b₁ B₁) | ordering.eq := match num.sub' n₁ n₂ with | znum.zero := horner' (A₁ a₂) x₁ n₁ (B₁ b₂) | (znum.pos k) := horner (add_aux a₂ k 0 id) x₁ n₂ (B₁ b₂) | (znum.neg k) := horner (A₁ (horner a₂ x₁ k 0)) x₁ n₁ (B₁ b₂) end end def add : horner_expr → horner_expr → horner_expr | (const n₁) e₂ := add_const n₁ e₂ | (horner a₁ x₁ n₁ b₁) e₂ := add_aux a₁ (add a₁) x₁ e₂ n₁ b₁ (add b₁) /-begin induction e₁ with n₁ a₁ x₁ n₁ b₁ A₁ B₁ generalizing e₂, { exact add_const n₁ e₂ }, exact match e₂ with e₂ := begin induction e₂ with n₂ a₂ x₂ n₂ b₂ A₂ B₂ generalizing n₁ b₁; let e₁ := horner a₁ x₁ n₁ b₁, { exact add_const n₂ e₁ }, let e₂ := horner a₂ x₂ n₂ b₂, exact match pos_num.cmp x₁ x₂ with | ordering.lt := horner a₁ x₁ n₁ (B₁ e₂) | ordering.gt := horner a₂ x₂ n₂ (B₂ n₁ b₁) | ordering.eq := match num.sub' n₁ n₂ with | znum.zero := horner' (A₁ a₂) x₁ n₁ (B₁ b₂) | (znum.pos k) := horner (A₂ k 0) x₁ n₂ (B₁ b₂) | (znum.neg k) := horner (A₁ (horner a₂ x₁ k 0)) x₁ n₁ (B₁ b₂) end end end end end-/ def neg (e : horner_expr) : horner_expr := begin induction e with n a x n b A B, { exact const (-n) }, { exact horner A x n B } end def mul_const (k : znum) (e : horner_expr) : horner_expr := if k = 0 then 0 else if k = 1 then e else begin induction e with n a x n b A B, { exact const (n * k) }, { exact horner A x n B } end def mul_aux (a₁ x₁ n₁ b₁) (A₁ B₁ : horner_expr → horner_expr) : horner_expr → horner_expr | (const n₂) := mul_const n₂ (horner a₁ x₁ n₁ b₁) | e₂@(horner a₂ x₂ n₂ b₂) := match pos_num.cmp x₁ x₂ with | ordering.lt := horner (A₁ e₂) x₁ n₁ (B₁ e₂) | ordering.gt := horner (mul_aux a₂) x₂ n₂ (mul_aux b₂) | ordering.eq := let haa := horner' (mul_aux a₂) x₁ n₂ 0 in if b₂ = 0 then haa else haa.add (horner (A₁ b₂) x₁ n₁ (B₁ b₂)) end def mul : horner_expr → horner_expr → horner_expr | (const n₁) := mul_const n₁ | (horner a₁ x₁ n₁ b₁) := mul_aux a₁ x₁ n₁ b₁ (mul a₁) (mul b₁). /-begin induction e₁ with n₁ a₁ x₁ n₁ b₁ A₁ B₁ generalizing e₂, { exact mul_const n₁ e₂ }, induction e₂ with n₂ a₂ x₂ n₂ b₂ A₂ B₂; let e₁ := horner a₁ x₁ n₁ b₁, { exact mul_const n₂ e₁ }, let e₂ := horner a₂ x₂ n₂ b₂, cases pos_num.cmp x₁ x₂, { exact horner (A₁ e₂) x₁ n₁ (B₁ e₂) }, { let haa := horner' A₂ x₁ n₂ 0, exact if b₂ = 0 then haa else haa.add (horner (A₁ b₂) x₁ n₁ (B₁ b₂)) }, { exact horner A₂ x₂ n₂ B₂ } end-/ instance : has_add horner_expr := ⟨add⟩ instance : has_neg horner_expr := ⟨neg⟩ instance : has_mul horner_expr := ⟨mul⟩ def pow (e : horner_expr) : num → horner_expr | 0 := 1 | (num.pos p) := begin induction p with p ep p ep, { exact e }, { exact (ep.mul ep).mul e }, { exact ep.mul ep } end def inv (e : horner_expr) : horner_expr := 0 /-- Brings expressions into Horner normal form. -/ def of_csexpr : csring_expr → horner_expr | (csring_expr.atom n) := atom n | (csring_expr.const n) := const n.to_znum | (csring_expr.add x y) := (of_csexpr x).add (of_csexpr y) | (csring_expr.mul x y) := (of_csexpr x).mul (of_csexpr y) | (csring_expr.pow x n) := (of_csexpr x).pow n /-- Evaluates a reflected `horner_expr` - see `csring_expr.eval`. -/ def cseval {α} [comm_semiring α] (t : tree α) : horner_expr → α | (const n) := n.abs | (horner a x n b) := tactic.ring.horner (cseval a) (t.get_or_zero x) n (cseval b) theorem cseval_atom {α} [comm_semiring α] (t : tree α) (n : pos_num) : (atom n).is_cs ∧ cseval t (atom n) = t.get_or_zero n := ⟨⟨⟨1, rfl⟩, ⟨0, rfl⟩⟩, (tactic.ring.horner_atom _).symm⟩ theorem cseval_add_const {α} [comm_semiring α] (t : tree α) (k : num) {e : horner_expr} (cs : e.is_cs) : (add_const k.to_znum e).is_cs ∧ cseval t (add_const k.to_znum e) = k + cseval t e := begin simp [add_const], cases k; simp! *, simp [show znum.pos k ≠ 0, from dec_trivial], induction e with n a x n b A B; simp *, { rcases cs with ⟨n, rfl⟩, refine ⟨⟨n + num.pos k, by simp [add_comm]; refl⟩, _⟩, cases n; simp! }, { rcases B cs.2 with ⟨csb, h⟩, simp! [*, cs.1], rw [← tactic.ring.horner_add_const, add_comm], rw add_comm } end theorem cseval_horner' {α} [comm_semiring α] (t : tree α) (a x n b) (h₁ : is_cs a) (h₂ : is_cs b) : (horner' a x n b).is_cs ∧ cseval t (horner' a x n b) = tactic.ring.horner (cseval t a) (t.get_or_zero x) n (cseval t b) := begin cases a with n₁ a₁ x₁ n₁ b₁; simp [horner']; split_ifs, { simp! [*, tactic.ring.horner] }, { exact ⟨⟨h₁, h₂⟩, rfl⟩ }, { refine ⟨⟨h₁.1, h₂⟩, eq.symm _⟩, simp! *, apply tactic.ring.horner_horner, simp }, { exact ⟨⟨h₁, h₂⟩, rfl⟩ } end theorem cseval_add {α} [comm_semiring α] (t : tree α) {e₁ e₂ : horner_expr} (cs₁ : e₁.is_cs) (cs₂ : e₂.is_cs) : (add e₁ e₂).is_cs ∧ cseval t (add e₁ e₂) = cseval t e₁ + cseval t e₂ := begin induction e₁ with n₁ a₁ x₁ n₁ b₁ A₁ B₁ generalizing e₂; simp!, { rcases cs₁ with ⟨n₁, rfl⟩, simpa using cseval_add_const t n₁ cs₂ }, induction e₂ with n₂ a₂ x₂ n₂ b₂ A₂ B₂ generalizing n₁ b₁, { rcases cs₂ with ⟨n₂, rfl⟩, simp! [cseval_add_const t n₂ cs₁, add_comm] }, cases cs₁ with csa₁ csb₁, cases id cs₂ with csa₂ csb₂, simp!, have C := pos_num.cmp_to_nat x₁ x₂, cases pos_num.cmp x₁ x₂; simp!, { rcases B₁ csb₁ cs₂ with ⟨csh, h⟩, refine ⟨⟨csa₁, csh⟩, eq.symm _⟩, apply tactic.ring.horner_add_const, exact h.symm }, { cases C, have B0 : is_cs 0 → ∀ {e₂ : horner_expr}, is_cs e₂ → is_cs (add 0 e₂) ∧ cseval t (add 0 e₂) = cseval t 0 + cseval t e₂ := λ _ e₂ c, ⟨c, (zero_add _).symm⟩, cases e : num.sub' n₁ n₂ with k k; simp!, { have : n₁ = n₂, { have := congr_arg (coe : znum → ℤ) e, simp at this, have := sub_eq_zero.1 this, rw [← num.to_nat_to_int, ← num.to_nat_to_int] at this, exact num.to_nat_inj.1 (int.coe_nat_inj this) }, subst n₂, rcases cseval_horner' _ _ _ _ _ _ _ with ⟨csh, h⟩, { refine ⟨csh, h.trans (eq.symm _)⟩, simp *, apply tactic.ring.horner_add_horner_eq; try {refl} }, all_goals {simp! *} }, { simp [B₁ csb₁ csb₂, add_comm], rcases A₂ csa₂ _ _ B0 ⟨csa₁, 0, rfl⟩ with ⟨csh, h⟩, refine ⟨csh, eq.symm _⟩, rw [show id = add 0, from rfl, h], apply tactic.ring.horner_add_horner_gt, { change (_ + k : ℕ) = _, rw [← int.coe_nat_inj', int.coe_nat_add, eq_comm, ← sub_eq_iff_eq_add'], simpa using congr_arg (coe : znum → ℤ) e }, { refl }, { apply add_comm } }, { have : (horner a₂ x₁ (num.pos k) 0).is_cs := ⟨csa₂, 0, rfl⟩, simp [B₁ csb₁ csb₂, A₁ csa₁ this], symmetry, apply tactic.ring.horner_add_horner_lt, { change (_ + k : ℕ) = _, rw [← int.coe_nat_inj', int.coe_nat_add, eq_comm, ← sub_eq_iff_eq_add', ← neg_inj, neg_sub], simpa using congr_arg (coe : znum → ℤ) e }, all_goals { refl } } }, { rcases B₂ csb₂ _ _ B₁ ⟨csa₁, csb₁⟩ with ⟨csh, h⟩, refine ⟨⟨csa₂, csh⟩, eq.symm _⟩, apply tactic.ring.const_add_horner, simp [h] } end theorem cseval_mul_const {α} [comm_semiring α] (t : tree α) (k : num) {e : horner_expr} (cs : e.is_cs) : (mul_const k.to_znum e).is_cs ∧ cseval t (mul_const k.to_znum e) = cseval t e * k := begin simp [mul_const], split_ifs with h h, { cases (num.to_znum_inj.1 h : k = 0), exact ⟨⟨0, rfl⟩, (mul_zero _).symm⟩ }, { cases (num.to_znum_inj.1 h : k = 1), exact ⟨cs, (mul_one _).symm⟩ }, induction e with n a x n b A B; simp *, { rcases cs with ⟨n, rfl⟩, suffices, refine ⟨⟨n * k, this⟩, _⟩, swap, {cases n; cases k; refl}, rw [show _, from this], simp! }, { cases cs, simp! *, symmetry, apply tactic.ring.horner_mul_const; refl } end theorem cseval_mul {α} [comm_semiring α] (t : tree α) {e₁ e₂ : horner_expr} (cs₁ : e₁.is_cs) (cs₂ : e₂.is_cs) : (mul e₁ e₂).is_cs ∧ cseval t (mul e₁ e₂) = cseval t e₁ * cseval t e₂ := begin induction e₁ with n₁ a₁ x₁ n₁ b₁ A₁ B₁ generalizing e₂; simp!, { rcases cs₁ with ⟨n₁, rfl⟩, simpa [mul_comm] using cseval_mul_const t n₁ cs₂ }, induction e₂ with n₂ a₂ x₂ n₂ b₂ A₂ B₂, { rcases cs₂ with ⟨n₂, rfl⟩, simpa! using cseval_mul_const t n₂ cs₁ }, cases cs₁ with csa₁ csb₁, cases id cs₂ with csa₂ csb₂, simp!, have C := pos_num.cmp_to_nat x₁ x₂, cases A₂ csa₂ with csA₂ hA₂, cases pos_num.cmp x₁ x₂; simp!, { simp [A₁ csa₁ cs₂, B₁ csb₁ cs₂], symmetry, apply tactic.ring.horner_mul_const; refl }, { cases cseval_horner' t _ x₁ n₂ 0 csA₂ ⟨0, rfl⟩ with csh₁ h₁, cases C, split_ifs, { subst b₂, refine ⟨csh₁, h₁.trans (eq.symm _)⟩, apply tactic.ring.horner_mul_horner_zero; try {refl}, simp! [hA₂] }, { cases A₁ csa₁ csb₂ with csA₁ hA₁, cases cseval_add t csh₁ _ with csh₂ h₂, { refine ⟨csh₂, h₂.trans (eq.symm _)⟩, apply tactic.ring.horner_mul_horner; try {refl}, simp! * }, exact ⟨csA₁, (B₁ csb₁ csb₂).1⟩ } }, { simp [A₂ csa₂, B₂ csb₂], rw [mul_comm, eq_comm], apply tactic.ring.horner_const_mul, {apply mul_comm}, {refl} }, end theorem cseval_pow {α} [comm_semiring α] (t : tree α) {x : horner_expr} (cs : x.is_cs) : ∀ (n : num), (pow x n).is_cs ∧ cseval t (pow x n) = cseval t x ^ (n : ℕ) | 0 := ⟨⟨1, rfl⟩, (pow_zero _).symm⟩ | (num.pos p) := begin simp [pow], induction p with p ep p ep, { simp * }, { simp [pow_bit1], cases cseval_mul t ep.1 ep.1 with cs₀ h₀, cases cseval_mul t cs₀ cs with cs₁ h₁, simp * }, { simp [pow_bit0], cases cseval_mul t ep.1 ep.1 with cs₀ h₀, simp * } end /-- For any given tree `t` of atoms and any reflected expression `r`, the Horner form of `r` is a valid csring expression, and under `t`, the Horner form evaluates to the same thing as `r`. -/ theorem cseval_of_csexpr {α} [comm_semiring α] (t : tree α) : ∀ (r : csring_expr), (of_csexpr r).is_cs ∧ cseval t (of_csexpr r) = r.eval t | (csring_expr.atom n) := cseval_atom _ _ | (csring_expr.const n) := ⟨⟨n, rfl⟩, by cases n; refl⟩ | (csring_expr.add x y) := let ⟨cs₁, h₁⟩ := cseval_of_csexpr x, ⟨cs₂, h₂⟩ := cseval_of_csexpr y, ⟨cs, h⟩ := cseval_add t cs₁ cs₂ in ⟨cs, by simp! [h, *]⟩ | (csring_expr.mul x y) := let ⟨cs₁, h₁⟩ := cseval_of_csexpr x, ⟨cs₂, h₂⟩ := cseval_of_csexpr y, ⟨cs, h⟩ := cseval_mul t cs₁ cs₂ in ⟨cs, by simp! [h, *]⟩ | (csring_expr.pow x n) := let ⟨cs, h⟩ := cseval_of_csexpr x, ⟨cs, h⟩ := cseval_pow t cs n in ⟨cs, by simp! [h, *]⟩ end horner_expr /-- The main proof-by-reflection theorem. Given reflected csring expressions `r₁` and `r₂` plus a storage `t` of atoms, if both expressions go to the same Horner normal form, then the original non-reflected expressions are equal. `H` follows from kernel reduction and is therefore `rfl`. -/ theorem correctness {α} [comm_semiring α] (t : tree α) (r₁ r₂ : csring_expr) (H : horner_expr.of_csexpr r₁ = horner_expr.of_csexpr r₂) : r₁.eval t = r₂.eval t := by repeat {rw ← (horner_expr.cseval_of_csexpr t _).2}; rw H /-- Reflects a csring expression into a `csring_expr`, together with a dlist of atoms, i.e. opaque variables over which the expression is a polynomial. -/ meta def reflect_expr : expr → csring_expr × dlist expr | `(%%e₁ + %%e₂) := let (r₁, l₁) := reflect_expr e₁, (r₂, l₂) := reflect_expr e₂ in (r₁.add r₂, l₁ ++ l₂) /-| `(%%e₁ - %%e₂) := let (r₁, l₁) := reflect_expr e₁, (r₂, l₂) := reflect_expr e₂ in (r₁.add r₂.neg, l₁ ++ l₂) | `(- %%e) := let (r, l) := reflect_expr e in (r.neg, l)-/ | `(%%e₁ * %%e₂) := let (r₁, l₁) := reflect_expr e₁, (r₂, l₂) := reflect_expr e₂ in (r₁.mul r₂, l₁ ++ l₂) /-| `(has_inv.inv %%e) := let (r, l) := reflect_expr e in (r.neg, l) | `(%%e₁ / %%e₂) := let (r₁, l₁) := reflect_expr e₁, (r₂, l₂) := reflect_expr e₂ in (r₁.mul r₂.inv, l₁ ++ l₂)-/ | e@`(%%e₁ ^ %%e₂) := match reflect_expr e₁, expr.to_nat e₂ with | (r₁, l₁), some n₂ := (r₁.pow (num.of_nat' n₂), l₁) | (r₁, l₁), none := (csring_expr.atom 1, dlist.singleton e) end | e := match expr.to_nat e with | some n := (csring_expr.const (num.of_nat' n), dlist.empty) | none := (csring_expr.atom 1, dlist.singleton e) end /-- In the output of `reflect_expr`, `atom`s are initialized with incorrect indices. The indices cannot be computed until the whole tree is built, so another pass over the expressions is needed - this is what `replace` does. The computation (expressed in the state monad) fixes up `atom`s to match their positions in the atom tree. The initial state is a list of all atom occurrences in the goal, left-to-right. -/ meta def csring_expr.replace (t : tree expr) : csring_expr → state_t (list expr) option csring_expr | (csring_expr.atom _) := do e ← get, p ← monad_lift (t.index_of (<) e.head), put e.tail, pure (csring_expr.atom p) | (csring_expr.const n) := pure (csring_expr.const n) | (csring_expr.add x y) := csring_expr.add <$> x.replace <*> y.replace | (csring_expr.mul x y) := csring_expr.mul <$> x.replace <*> y.replace | (csring_expr.pow x n) := (λ x, csring_expr.pow x n) <$> x.replace --| (csring_expr.neg x) := csring_expr.neg <$> x.replace --| (csring_expr.inv x) := csring_expr.inv <$> x.replace end tactic.ring2 namespace tactic namespace interactive open interactive interactive.types lean.parser open tactic.ring2 local postfix (name := parser.optional) `?`:9001 := optional /-- `ring2` solves equations in the language of rings. It supports only the commutative semiring operations, i.e. it does not normalize subtraction or division. This variant on the `ring` tactic uses kernel computation instead of proof generation. In general, you should use `ring` instead of `ring2`. -/ meta def ring2 : tactic unit := do `[repeat {rw ← nat.pow_eq_pow}], `(%%e₁ = %%e₂) ← target | fail "ring2 tactic failed: the goal is not an equality", α ← infer_type e₁, expr.sort (level.succ u) ← infer_type α, let (r₁, l₁) := reflect_expr e₁, let (r₂, l₂) := reflect_expr e₂, let L := (l₁ ++ l₂).to_list, let s := tree.of_rbnode (rbtree_of L).1, (r₁, L) ← (state_t.run (r₁.replace s) L : option _), (r₂, _) ← (state_t.run (r₂.replace s) L : option _), let se : expr := s.reflect' u α, let er₁ : expr := reflect r₁, let er₂ : expr := reflect r₂, cs ← mk_app ``comm_semiring [α] >>= mk_instance, e ← to_expr ``(correctness %%se %%er₁ %%er₂ rfl) <|> fail ("ring2 tactic failed, cannot show equality:\n" ++ to_string (horner_expr.of_csexpr r₁) ++ "\n =?=\n" ++ to_string (horner_expr.of_csexpr r₂)), tactic.exact e add_tactic_doc { name := "ring2", category := doc_category.tactic, decl_names := [`tactic.interactive.ring2], tags := ["arithmetic", "simplification", "decision procedure"] } end interactive end tactic namespace conv.interactive open conv meta def ring2 : conv unit := discharge_eq_lhs tactic.interactive.ring2 end conv.interactive
3cb2866db4e986761fae9c0b59cfbf25402ce7c8
bb31430994044506fa42fd667e2d556327e18dfe
/src/data/list/nodup.lean
fc3b413305d01d8131b6d2915692c6fce9658604
[ "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
14,509
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kenny Lau -/ import data.list.lattice import data.list.pairwise import data.list.forall2 import data.set.pairwise /-! # Lists with no duplicates > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. `list.nodup` is defined in `data/list/defs`. In this file we prove various properties of this predicate. -/ universes u v open nat function variables {α : Type u} {β : Type v} {l l₁ l₂ : list α} {r : α → α → Prop} {a b : α} namespace list @[simp] theorem forall_mem_ne {a : α} {l : list α} : (∀ (a' : α), a' ∈ l → ¬a = a') ↔ a ∉ l := ⟨λ h m, h _ m rfl, λ h a' m e, h (e.symm ▸ m)⟩ @[simp] theorem nodup_nil : @nodup α [] := pairwise.nil @[simp] theorem nodup_cons {a : α} {l : list α} : nodup (a::l) ↔ a ∉ l ∧ nodup l := by simp only [nodup, pairwise_cons, forall_mem_ne] protected lemma pairwise.nodup {l : list α} {r : α → α → Prop} [is_irrefl α r] (h : pairwise r l) : nodup l := h.imp $ λ a b, ne_of_irrefl lemma rel_nodup {r : α → β → Prop} (hr : relator.bi_unique r) : (forall₂ r ⇒ (↔)) nodup nodup | _ _ forall₂.nil := by simp only [nodup_nil] | _ _ (forall₂.cons hab h) := by simpa only [nodup_cons] using relator.rel_and (relator.rel_not (rel_mem hr hab h)) (rel_nodup h) protected lemma nodup.cons (ha : a ∉ l) (hl : nodup l) : nodup (a :: l) := nodup_cons.2 ⟨ha, hl⟩ lemma nodup_singleton (a : α) : nodup [a] := pairwise_singleton _ _ lemma nodup.of_cons (h : nodup (a :: l)) : nodup l := (nodup_cons.1 h).2 lemma nodup.not_mem (h : (a :: l).nodup) : a ∉ l := (nodup_cons.1 h).1 lemma not_nodup_cons_of_mem : a ∈ l → ¬ nodup (a :: l) := imp_not_comm.1 nodup.not_mem protected lemma nodup.sublist : l₁ <+ l₂ → nodup l₂ → nodup l₁ := pairwise.sublist theorem not_nodup_pair (a : α) : ¬ nodup [a, a] := not_nodup_cons_of_mem $ mem_singleton_self _ theorem nodup_iff_sublist {l : list α} : nodup l ↔ ∀ a, ¬ [a, a] <+ l := ⟨λ d a h, not_nodup_pair a (d.sublist h), begin induction l with a l IH; intro h, {exact nodup_nil}, exact (IH $ λ a s, h a $ sublist_cons_of_sublist _ s).cons (λ al, h a $ (singleton_sublist.2 al).cons_cons _) end⟩ theorem nodup_iff_nth_le_inj {l : list α} : nodup l ↔ ∀ i j h₁ h₂, nth_le l i h₁ = nth_le l j h₂ → i = j := pairwise_iff_nth_le.trans ⟨λ H i j h₁ h₂ h, ((lt_trichotomy _ _) .resolve_left (λ h', H _ _ h₂ h' h)) .resolve_right (λ h', H _ _ h₁ h' h.symm), λ H i j h₁ h₂ h, ne_of_lt h₂ (H _ _ _ _ h)⟩ theorem nodup.nth_le_inj_iff {l : list α} (h : nodup l) {i j : ℕ} (hi : i < l.length) (hj : j < l.length) : l.nth_le i hi = l.nth_le j hj ↔ i = j := ⟨nodup_iff_nth_le_inj.mp h _ _ _ _, by simp {contextual := tt}⟩ lemma nodup_iff_nth_ne_nth {l : list α} : l.nodup ↔ ∀ (i j : ℕ), i < j → j < l.length → l.nth i ≠ l.nth j := begin rw nodup_iff_nth_le_inj, simp only [nth_le_eq_iff, some_nth_le_eq], split; rintro h i j h₁ h₂, { exact mt (h i j (h₁.trans h₂) h₂) (ne_of_lt h₁) }, { intro h₃, by_contra h₄, cases lt_or_gt_of_ne h₄ with h₅ h₅, { exact h i j h₅ h₂ h₃ }, { exact h j i h₅ h₁ h₃.symm }}, end lemma nodup.ne_singleton_iff {l : list α} (h : nodup l) (x : α) : l ≠ [x] ↔ l = [] ∨ ∃ y ∈ l, y ≠ x := begin induction l with hd tl hl, { simp }, { specialize hl h.of_cons, by_cases hx : tl = [x], { simpa [hx, and.comm, and_or_distrib_left] using h }, { rw [←ne.def, hl] at hx, rcases hx with rfl | ⟨y, hy, hx⟩, { simp }, { have : tl ≠ [] := ne_nil_of_mem hy, suffices : ∃ (y : α) (H : y ∈ hd :: tl), y ≠ x, { simpa [ne_nil_of_mem hy] }, exact ⟨y, mem_cons_of_mem _ hy, hx⟩ } } } end lemma nth_le_eq_of_ne_imp_not_nodup (xs : list α) (n m : ℕ) (hn : n < xs.length) (hm : m < xs.length) (h : xs.nth_le n hn = xs.nth_le m hm) (hne : n ≠ m) : ¬ nodup xs := begin rw nodup_iff_nth_le_inj, simp only [exists_prop, exists_and_distrib_right, not_forall], exact ⟨n, m, ⟨hn, hm, h⟩, hne⟩ end @[simp] theorem nth_le_index_of [decidable_eq α] {l : list α} (H : nodup l) (n h) : index_of (nth_le l n h) l = n := nodup_iff_nth_le_inj.1 H _ _ _ h $ index_of_nth_le $ index_of_lt_length.2 $ nth_le_mem _ _ _ theorem nodup_iff_count_le_one [decidable_eq α] {l : list α} : nodup l ↔ ∀ a, count a l ≤ 1 := nodup_iff_sublist.trans $ forall_congr $ λ a, have [a, a] <+ l ↔ 1 < count a l, from (@le_count_iff_repeat_sublist _ _ a l 2).symm, (not_congr this).trans not_lt theorem nodup_repeat (a : α) : ∀ {n : ℕ}, nodup (repeat a n) ↔ n ≤ 1 | 0 := by simp [nat.zero_le] | 1 := by simp | (n+2) := iff_of_false (λ H, nodup_iff_sublist.1 H a ((repeat_sublist_repeat _).2 (nat.le_add_left 2 n))) (not_le_of_lt $ nat.le_add_left 2 n) @[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {l : list α} (d : nodup l) (h : a ∈ l) : count a l = 1 := le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos.2 h) lemma count_eq_of_nodup [decidable_eq α] {a : α} {l : list α} (d : nodup l) : count a l = if a ∈ l then 1 else 0 := begin split_ifs with h, { exact count_eq_one_of_mem d h }, { exact count_eq_zero_of_not_mem h }, end lemma nodup.of_append_left : nodup (l₁ ++ l₂) → nodup l₁ := nodup.sublist (sublist_append_left l₁ l₂) lemma nodup.of_append_right : nodup (l₁ ++ l₂) → nodup l₂ := nodup.sublist (sublist_append_right l₁ l₂) theorem nodup_append {l₁ l₂ : list α} : nodup (l₁++l₂) ↔ nodup l₁ ∧ nodup l₂ ∧ disjoint l₁ l₂ := by simp only [nodup, pairwise_append, disjoint_iff_ne] theorem disjoint_of_nodup_append {l₁ l₂ : list α} (d : nodup (l₁++l₂)) : disjoint l₁ l₂ := (nodup_append.1 d).2.2 lemma nodup.append (d₁ : nodup l₁) (d₂ : nodup l₂) (dj : disjoint l₁ l₂) : nodup (l₁ ++ l₂) := nodup_append.2 ⟨d₁, d₂, dj⟩ theorem nodup_append_comm {l₁ l₂ : list α} : nodup (l₁++l₂) ↔ nodup (l₂++l₁) := by simp only [nodup_append, and.left_comm, disjoint_comm] theorem nodup_middle {a : α} {l₁ l₂ : list α} : nodup (l₁ ++ a::l₂) ↔ nodup (a::(l₁++l₂)) := by simp only [nodup_append, not_or_distrib, and.left_comm, and_assoc, nodup_cons, mem_append, disjoint_cons_right] lemma nodup.of_map (f : α → β) {l : list α} : nodup (map f l) → nodup l := pairwise.of_map f $ λ a b, mt $ congr_arg f lemma nodup.map_on {f : α → β} (H : ∀ x ∈ l, ∀ y ∈ l, f x = f y → x = y) (d : nodup l) : (map f l).nodup := pairwise.map _ (by exact λ a b ⟨ma, mb, n⟩ e, n (H a ma b mb e)) (pairwise.and_mem.1 d) theorem inj_on_of_nodup_map {f : α → β} {l : list α} (d : nodup (map f l)) : ∀ ⦃x⦄, x ∈ l → ∀ ⦃y⦄, y ∈ l → f x = f y → x = y := begin induction l with hd tl ih, { simp }, { simp only [map, nodup_cons, mem_map, not_exists, not_and, ←ne.def] at d, rintro _ (rfl | h₁) _ (rfl | h₂) h₃, { refl }, { apply (d.1 _ h₂ h₃.symm).elim }, { apply (d.1 _ h₁ h₃).elim }, { apply ih d.2 h₁ h₂ h₃ } } end theorem nodup_map_iff_inj_on {f : α → β} {l : list α} (d : nodup l) : nodup (map f l) ↔ (∀ (x ∈ l) (y ∈ l), f x = f y → x = y) := ⟨inj_on_of_nodup_map, λ h, d.map_on h⟩ protected lemma nodup.map {f : α → β} (hf : injective f) : nodup l → nodup (map f l) := nodup.map_on (assume x _ y _ h, hf h) theorem nodup_map_iff {f : α → β} {l : list α} (hf : injective f) : nodup (map f l) ↔ nodup l := ⟨nodup.of_map _, nodup.map hf⟩ @[simp] theorem nodup_attach {l : list α} : nodup (attach l) ↔ nodup l := ⟨λ h, attach_map_val l ▸ h.map (λ a b, subtype.eq), λ h, nodup.of_map subtype.val ((attach_map_val l).symm ▸ h)⟩ alias nodup_attach ↔ nodup.of_attach nodup.attach attribute [protected] nodup.attach lemma nodup.pmap {p : α → Prop} {f : Π a, p a → β} {l : list α} {H} (hf : ∀ a ha b hb, f a ha = f b hb → a = b) (h : nodup l) : nodup (pmap f l H) := by rw [pmap_eq_map_attach]; exact h.attach.map (λ ⟨a, ha⟩ ⟨b, hb⟩ h, by congr; exact hf a (H _ ha) b (H _ hb) h) lemma nodup.filter (p : α → Prop) [decidable_pred p] {l} : nodup l → nodup (filter p l) := pairwise.filter p @[simp] theorem nodup_reverse {l : list α} : nodup (reverse l) ↔ nodup l := pairwise_reverse.trans $ by simp only [nodup, ne.def, eq_comm] lemma nodup.erase_eq_filter [decidable_eq α] {l} (d : nodup l) (a : α) : l.erase a = filter (≠ a) l := begin induction d with b l m d IH, {refl}, by_cases b = a, { subst h, rw [erase_cons_head, filter_cons_of_neg], symmetry, rw filter_eq_self, simpa only [ne.def, eq_comm] using m, exact not_not_intro rfl }, { rw [erase_cons_tail _ h, filter_cons_of_pos, IH], exact h } end lemma nodup.erase [decidable_eq α] (a : α) : nodup l → nodup (l.erase a) := nodup.sublist $ erase_sublist _ _ lemma nodup.diff [decidable_eq α] : l₁.nodup → (l₁.diff l₂).nodup := nodup.sublist $ diff_sublist _ _ lemma nodup.mem_erase_iff [decidable_eq α] (d : nodup l) : a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l := by rw [d.erase_eq_filter, mem_filter, and_comm] lemma nodup.not_mem_erase [decidable_eq α] (h : nodup l) : a ∉ l.erase a := λ H, (h.mem_erase_iff.1 H).1 rfl theorem nodup_join {L : list (list α)} : nodup (join L) ↔ (∀ l ∈ L, nodup l) ∧ pairwise disjoint L := by simp only [nodup, pairwise_join, disjoint_left.symm, forall_mem_ne] theorem nodup_bind {l₁ : list α} {f : α → list β} : nodup (l₁.bind f) ↔ (∀ x ∈ l₁, nodup (f x)) ∧ pairwise (λ (a b : α), disjoint (f a) (f b)) l₁ := by simp only [list.bind, nodup_join, pairwise_map, and_comm, and.left_comm, mem_map, exists_imp_distrib, and_imp]; rw [show (∀ (l : list β) (x : α), f x = l → x ∈ l₁ → nodup l) ↔ (∀ (x : α), x ∈ l₁ → nodup (f x)), from forall_swap.trans $ forall_congr $ λ_, forall_eq'] protected lemma nodup.product {l₂ : list β} (d₁ : l₁.nodup) (d₂ : l₂.nodup) : (l₁.product l₂).nodup := nodup_bind.2 ⟨λ a ma, d₂.map $ left_inverse.injective $ λ b, (rfl : (a,b).2 = b), d₁.imp $ λ a₁ a₂ n x h₁ h₂, begin rcases mem_map.1 h₁ with ⟨b₁, mb₁, rfl⟩, rcases mem_map.1 h₂ with ⟨b₂, mb₂, ⟨⟩⟩, exact n rfl end⟩ lemma nodup.sigma {σ : α → Type*} {l₂ : Π a, list (σ a)} (d₁ : nodup l₁) (d₂ : ∀ a, nodup (l₂ a)) : (l₁.sigma l₂).nodup := nodup_bind.2 ⟨λ a ma, (d₂ a).map (λ b b' h, by injection h with _ h; exact eq_of_heq h), d₁.imp $ λ a₁ a₂ n x h₁ h₂, begin rcases mem_map.1 h₁ with ⟨b₁, mb₁, rfl⟩, rcases mem_map.1 h₂ with ⟨b₂, mb₂, ⟨⟩⟩, exact n rfl end⟩ protected lemma nodup.filter_map {f : α → option β} (h : ∀ a a' b, b ∈ f a → b ∈ f a' → a = a') : nodup l → nodup (filter_map f l) := pairwise.filter_map f $ λ a a' n b bm b' bm' e, n $ h a a' b' (e ▸ bm) bm' protected lemma nodup.concat (h : a ∉ l) (h' : l.nodup) : (l.concat a).nodup := by rw concat_eq_append; exact h'.append (nodup_singleton _) (disjoint_singleton.2 h) lemma nodup.insert [decidable_eq α] (h : l.nodup) : (insert a l).nodup := if h' : a ∈ l then by rw [insert_of_mem h']; exact h else by rw [insert_of_not_mem h', nodup_cons]; split; assumption lemma nodup.union [decidable_eq α] (l₁ : list α) (h : nodup l₂) : (l₁ ∪ l₂).nodup := begin induction l₁ with a l₁ ih generalizing l₂, { exact h }, { exact (ih h).insert } end lemma nodup.inter [decidable_eq α] (l₂ : list α) : nodup l₁ → nodup (l₁ ∩ l₂) := nodup.filter _ lemma nodup.diff_eq_filter [decidable_eq α] : ∀ {l₁ l₂ : list α} (hl₁ : l₁.nodup), l₁.diff l₂ = l₁.filter (∉ l₂) | l₁ [] hl₁ := by simp | l₁ (a::l₂) hl₁ := begin rw [diff_cons, (hl₁.erase _).diff_eq_filter, hl₁.erase_eq_filter, filter_filter], simp only [mem_cons_iff, not_or_distrib, and.comm] end lemma nodup.mem_diff_iff [decidable_eq α] (hl₁ : l₁.nodup) : a ∈ l₁.diff l₂ ↔ a ∈ l₁ ∧ a ∉ l₂ := by rw [hl₁.diff_eq_filter, mem_filter] protected lemma nodup.update_nth : ∀ {l : list α} {n : ℕ} {a : α} (hl : l.nodup) (ha : a ∉ l), (l.update_nth n a).nodup | [] n a hl ha := nodup_nil | (b::l) 0 a hl ha := nodup_cons.2 ⟨mt (mem_cons_of_mem _) ha, (nodup_cons.1 hl).2⟩ | (b::l) (n+1) a hl ha := nodup_cons.2 ⟨λ h, (mem_or_eq_of_mem_update_nth h).elim (nodup_cons.1 hl).1 (λ hba, ha (hba ▸ mem_cons_self _ _)), hl.of_cons.update_nth (mt (mem_cons_of_mem _) ha)⟩ lemma nodup.map_update [decidable_eq α] {l : list α} (hl : l.nodup) (f : α → β) (x : α) (y : β) : l.map (function.update f x y) = if x ∈ l then (l.map f).update_nth (l.index_of x) y else l.map f := begin induction l with hd tl ihl, { simp }, rw [nodup_cons] at hl, simp only [mem_cons_iff, map, ihl hl.2], by_cases H : hd = x, { subst hd, simp [update_nth, hl.1] }, { simp [ne.symm H, H, update_nth, ← apply_ite (cons (f hd))] } end lemma nodup.pairwise_of_forall_ne {l : list α} {r : α → α → Prop} (hl : l.nodup) (h : ∀ (a ∈ l) (b ∈ l), a ≠ b → r a b) : l.pairwise r := begin classical, refine pairwise_of_reflexive_on_dupl_of_forall_ne _ h, intros x hx, rw nodup_iff_count_le_one at hl, exact absurd (hl x) hx.not_le end lemma nodup.pairwise_of_set_pairwise {l : list α} {r : α → α → Prop} (hl : l.nodup) (h : {x | x ∈ l}.pairwise r) : l.pairwise r := hl.pairwise_of_forall_ne h @[simp] lemma nodup.pairwise_coe [is_symm α r] (hl : l.nodup) : {a | a ∈ l}.pairwise r ↔ l.pairwise r := begin induction l with a l ih, { simp }, rw list.nodup_cons at hl, have : ∀ b ∈ l, ¬a = b → r a b ↔ r a b := λ b hb, imp_iff_right (ne_of_mem_of_not_mem hb hl.1).symm, simp [set.set_of_or, set.pairwise_insert_of_symmetric (@symm_of _ r _), ih hl.2, and_comm, forall₂_congr this], end end list theorem option.to_list_nodup {α} : ∀ o : option α, o.to_list.nodup | none := list.nodup_nil | (some x) := list.nodup_singleton x
f1a884eff883def5e5cdfd9f6cdcbf6fb09093dc
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/src/Init/Lean/Meta/Tactic/Apply.lean
ffbc3d22d3aaffafbf36d5a6d88e5e755ffa51b5
[ "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
3,884
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.Lean.Util.FindMVar import Init.Lean.Meta.Message import Init.Lean.Meta.ExprDefEq import Init.Lean.Meta.SynthInstance import Init.Lean.Meta.Tactic.Util namespace Lean namespace Meta /- Compute the number of expected arguments and whether the result type is of the form (?m ...) where ?m is an unassigned metavariable. -/ private def getExpectedNumArgsAux (e : Expr) : MetaM (Nat × Bool) := withReducible $ forallTelescopeReducing e $ fun xs body => pure (xs.size, body.getAppFn.isMVar) private def getExpectedNumArgs (e : Expr) : MetaM Nat := do (numArgs, _) ← getExpectedNumArgsAux e; pure numArgs private def throwApplyError {α} (mvarId : MVarId) (eType : Expr) (targetType : Expr) : MetaM α := throwTacticEx `apply mvarId ("failed to unify" ++ indentExpr eType ++ Format.line ++ "with" ++ indentExpr targetType) def synthAppInstances (tacticName : Name) (mvarId : MVarId) (newMVars : Array Expr) (binderInfos : Array BinderInfo) : MetaM Unit := newMVars.size.forM $ fun i => when (binderInfos.get! i).isInstImplicit $ do let mvar := newMVars.get! i; mvarType ← inferType mvar; mvarVal ← synthInstance mvarType; unlessM (isDefEq mvar mvarVal) $ throwTacticEx tacticName mvarId ("failed to assign synthesized instance") def appendParentTag (mvarId : MVarId) (newMVars : Array Expr) (binderInfos : Array BinderInfo) : MetaM Unit := do parentTag ← getMVarTag mvarId; unless parentTag.isAnonymous $ newMVars.size.forM $ fun i => let newMVarId := (newMVars.get! i).mvarId!; unlessM (isExprMVarAssigned newMVarId) $ unless (binderInfos.get! i).isInstImplicit $ do currTag ← getMVarTag newMVarId; renameMVar newMVarId (parentTag ++ currTag.eraseMacroScopes) def postprocessAppMVars (tacticName : Name) (mvarId : MVarId) (newMVars : Array Expr) (binderInfos : Array BinderInfo) : MetaM Unit := do synthAppInstances tacticName mvarId newMVars binderInfos; -- TODO: default and auto params appendParentTag mvarId newMVars binderInfos private def dependsOnOthers (mvar : Expr) (otherMVars : Array Expr) : MetaM Bool := otherMVars.anyM $ fun otherMVar => if mvar == otherMVar then pure false else do otherMVarType ← inferType otherMVar; pure $ (otherMVarType.findMVar? $ fun mvarId => mvarId == mvar.mvarId!).isSome private def reorderNonDependentFirst (newMVars : Array Expr) : MetaM (List MVarId) := do (nonDeps, deps) ← newMVars.foldlM (fun (acc : Array MVarId × Array MVarId) (mvar : Expr) => do let (nonDeps, deps) := acc; let currMVarId := mvar.mvarId!; condM (dependsOnOthers mvar newMVars) (pure (nonDeps, deps.push currMVarId)) (pure (nonDeps.push currMVarId, deps))) (#[], #[]); pure $ nonDeps.toList ++ deps.toList inductive ApplyNewGoals | nonDependentFirst | nonDependentOnly | all def apply (mvarId : MVarId) (e : Expr) : MetaM (List MVarId) := withMVarContext mvarId $ do checkNotAssigned mvarId `apply; targetType ← getMVarType mvarId; eType ← inferType e; (numArgs, hasMVarHead) ← getExpectedNumArgsAux eType; numArgs ← if !hasMVarHead then pure numArgs else do { targetTypeNumArgs ← getExpectedNumArgs targetType; pure (numArgs - targetTypeNumArgs) }; (newMVars, binderInfos, eType) ← forallMetaTelescopeReducing eType (some numArgs); unlessM (isDefEq eType targetType) $ throwApplyError mvarId eType targetType; postprocessAppMVars `apply mvarId newMVars binderInfos; assignExprMVar mvarId (mkAppN e newMVars); newMVars ← newMVars.filterM $ fun mvar => not <$> isExprMVarAssigned mvar.mvarId!; -- TODO: add option `ApplyNewGoals` and implement other orders reorderNonDependentFirst newMVars end Meta end Lean
95b73dcdc4a5ab8f918fb8009ff7ec30d6047819
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/number_theory/bernoulli.lean
200b340cf7b648b16e8709f8bbb9dd50fd8e87e1
[ "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,005
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Kevin Buzzard -/ import algebra.big_operators.nat_antidiagonal import algebra.geom_sum import data.fintype.card import ring_theory.power_series.well_known import tactic.field_simp /-! # Bernoulli numbers The Bernoulli numbers are a sequence of rational numbers that frequently show up in number theory. ## Mathematical overview The Bernoulli numbers $(B_0, B_1, B_2, \ldots)=(1, -1/2, 1/6, 0, -1/30, \ldots)$ are a sequence of rational numbers. They show up in the formula for the sums of $k$th powers. They are related to the Taylor series expansions of $x/\tan(x)$ and of $\coth(x)$, and also show up in the values that the Riemann Zeta function takes both at both negative and positive integers (and hence in the theory of modular forms). For example, if $1 \leq n$ is even then $$\zeta(2n)=\sum_{t\geq1}t^{-2n}=(-1)^{n+1}\frac{(2\pi)^{2n}B_{2n}}{2(2n)!}.$$ Note however that this result is not yet formalised in Lean. The Bernoulli numbers can be formally defined using the power series $$\sum B_n\frac{t^n}{n!}=\frac{t}{1-e^{-t}}$$ although that happens to not be the definition in mathlib (this is an *implementation detail* and need not concern the mathematician). Note that $B_1=-1/2$, meaning that we are using the $B_n^-$ of [from Wikipedia](https://en.wikipedia.org/wiki/Bernoulli_number). ## Implementation detail The Bernoulli numbers are defined using well-founded induction, by the formula $$B_n=1-\sum_{k\lt n}\frac{\binom{n}{k}}{n-k+1}B_k.$$ This formula is true for all $n$ and in particular $B_0=1$. Note that this is the definition for positive Bernoulli numbers, which we call `bernoulli'`. The negative Bernoulli numbers are then defined as `bernoulli := (-1)^n * bernoulli'`. ## Main theorems `sum_bernoulli : ∑ k in finset.range n, (n.choose k : ℚ) * bernoulli k = 0` -/ open_locale nat big_operators open finset nat finset.nat power_series variables (A : Type*) [comm_ring A] [algebra ℚ A] /-! ### Definitions -/ /-- The Bernoulli numbers: the $n$-th Bernoulli number $B_n$ is defined recursively via $$B_n = 1 - \sum_{k < n} \binom{n}{k}\frac{B_k}{n+1-k}$$ -/ def bernoulli' : ℕ → ℚ := well_founded.fix lt_wf $ λ n bernoulli', 1 - ∑ k : fin n, n.choose k / (n - k + 1) * bernoulli' k k.2 lemma bernoulli'_def' (n : ℕ) : bernoulli' n = 1 - ∑ k : fin n, n.choose k / (n - k + 1) * bernoulli' k := well_founded.fix_eq _ _ _ lemma bernoulli'_def (n : ℕ) : bernoulli' n = 1 - ∑ k in range n, n.choose k / (n - k + 1) * bernoulli' k := by { rw [bernoulli'_def', ← fin.sum_univ_eq_sum_range], refl } lemma bernoulli'_spec (n : ℕ) : ∑ k in range n.succ, (n.choose (n - k) : ℚ) / (n - k + 1) * bernoulli' k = 1 := begin rw [sum_range_succ_comm, bernoulli'_def n, tsub_self], conv in (n.choose (_ - _)) { rw choose_symm (mem_range.1 H).le }, simp only [one_mul, cast_one, sub_self, sub_add_cancel, choose_zero_right, zero_add, div_one], end lemma bernoulli'_spec' (n : ℕ) : ∑ k in antidiagonal n, ((k.1 + k.2).choose k.2 : ℚ) / (k.2 + 1) * bernoulli' k.1 = 1 := begin refine ((sum_antidiagonal_eq_sum_range_succ_mk _ n).trans _).trans (bernoulli'_spec n), refine sum_congr rfl (λ x hx, _), simp only [add_tsub_cancel_of_le, mem_range_succ_iff.mp hx, cast_sub], end /-! ### Examples -/ section examples @[simp] lemma bernoulli'_zero : bernoulli' 0 = 1 := by { rw bernoulli'_def, norm_num } @[simp] lemma bernoulli'_one : bernoulli' 1 = 1/2 := by { rw bernoulli'_def, norm_num } @[simp] lemma bernoulli'_two : bernoulli' 2 = 1/6 := by { rw bernoulli'_def, norm_num [sum_range_succ] } @[simp] lemma bernoulli'_three : bernoulli' 3 = 0 := by { rw bernoulli'_def, norm_num [sum_range_succ] } @[simp] lemma bernoulli'_four : bernoulli' 4 = -1/30 := have nat.choose 4 2 = 6 := dec_trivial, -- shrug by { rw bernoulli'_def, norm_num [sum_range_succ, this] } end examples @[simp] lemma sum_bernoulli' (n : ℕ) : ∑ k in range n, (n.choose k : ℚ) * bernoulli' k = n := begin cases n, { simp }, suffices : (n + 1 : ℚ) * ∑ k in range n, ↑(n.choose k) / (n - k + 1) * bernoulli' k = ∑ x in range n, ↑(n.succ.choose x) * bernoulli' x, { rw_mod_cast [sum_range_succ, bernoulli'_def, ← this, choose_succ_self_right], ring }, simp_rw [mul_sum, ← mul_assoc], refine sum_congr rfl (λ k hk, _), congr', have : ((n - k : ℕ) : ℚ) + 1 ≠ 0 := by apply_mod_cast succ_ne_zero, field_simp [← cast_sub (mem_range.1 hk).le, mul_comm], rw_mod_cast [tsub_add_eq_add_tsub (mem_range.1 hk).le, choose_mul_succ_eq], end /-- The exponential generating function for the Bernoulli numbers `bernoulli' n`. -/ def bernoulli'_power_series := mk $ λ n, algebra_map ℚ A (bernoulli' n / n!) theorem bernoulli'_power_series_mul_exp_sub_one : bernoulli'_power_series A * (exp A - 1) = X * exp A := begin ext n, -- constant coefficient is a special case cases n, { simp }, rw [bernoulli'_power_series, coeff_mul, mul_comm X, sum_antidiagonal_succ'], suffices : ∑ p in antidiagonal n, (bernoulli' p.1 / p.1!) * ((p.2 + 1) * p.2!)⁻¹ = n!⁻¹, { simpa [ring_hom.map_sum] using congr_arg (algebra_map ℚ A) this }, apply eq_inv_of_mul_left_eq_one, rw sum_mul, convert bernoulli'_spec' n using 1, apply sum_congr rfl, simp_rw [mem_antidiagonal], rintro ⟨i, j⟩ rfl, have : (j + 1 : ℚ) ≠ 0 := by exact_mod_cast succ_ne_zero j, have : (j + 1 : ℚ) * j! * i! ≠ 0 := by simpa [factorial_ne_zero], have := factorial_mul_factorial_dvd_factorial_add i j, field_simp [mul_comm _ (bernoulli' i), mul_assoc, add_choose], rw_mod_cast [mul_comm (j + 1), mul_div_assoc, ← mul_assoc], rw [cast_mul, cast_mul, mul_div_mul_right, cast_dvd_char_zero, cast_mul], assumption', end /-- Odd Bernoulli numbers (greater than 1) are zero. -/ theorem bernoulli'_odd_eq_zero {n : ℕ} (h_odd : odd n) (hlt : 1 < n) : bernoulli' n = 0 := begin let B := mk (λ n, bernoulli' n / n!), suffices : (B - eval_neg_hom B) * (exp ℚ - 1) = X * (exp ℚ - 1), { cases mul_eq_mul_right_iff.mp this; simp only [power_series.ext_iff, eval_neg_hom, coeff_X] at h, { apply eq_zero_of_neg_eq, specialize h n, split_ifs at h; simp [neg_one_pow_of_odd h_odd, factorial_ne_zero, *] at * }, { simpa using h 1 } }, have h : B * (exp ℚ - 1) = X * exp ℚ, { simpa [bernoulli'_power_series] using bernoulli'_power_series_mul_exp_sub_one ℚ }, rw [sub_mul, h, mul_sub X, sub_right_inj, ← neg_sub, ← neg_mul_eq_mul_neg, neg_eq_iff_neg_eq], suffices : eval_neg_hom (B * (exp ℚ - 1)) * exp ℚ = eval_neg_hom (X * exp ℚ) * exp ℚ, { simpa [mul_assoc, sub_mul, mul_comm (eval_neg_hom (exp ℚ)), exp_mul_exp_neg_eq_one, eq_comm] }, congr', end /-- The Bernoulli numbers are defined to be `bernoulli'` with a parity sign. -/ def bernoulli (n : ℕ) : ℚ := (-1)^n * bernoulli' n lemma bernoulli'_eq_bernoulli (n : ℕ) : bernoulli' n = (-1)^n * bernoulli n := by simp [bernoulli, ← mul_assoc, ← sq, ← pow_mul, mul_comm n 2, pow_mul] @[simp] lemma bernoulli_zero : bernoulli 0 = 1 := by simp [bernoulli] @[simp] lemma bernoulli_one : bernoulli 1 = -1/2 := by norm_num [bernoulli] theorem bernoulli_eq_bernoulli'_of_ne_one {n : ℕ} (hn : n ≠ 1) : bernoulli n = bernoulli' n := begin by_cases h0 : n = 0, { simp [h0] }, rw [bernoulli, neg_one_pow_eq_pow_mod_two], cases mod_two_eq_zero_or_one n, { simp [h] }, simp [bernoulli'_odd_eq_zero (odd_iff.mpr h) (one_lt_iff_ne_zero_and_ne_one.mpr ⟨h0, hn⟩)], end @[simp] theorem sum_bernoulli (n : ℕ): ∑ k in range n, (n.choose k : ℚ) * bernoulli k = if n = 1 then 1 else 0 := begin cases n, { simp }, cases n, { simp }, suffices : ∑ i in range n, ↑((n + 2).choose (i + 2)) * bernoulli (i + 2) = n / 2, { simp only [this, sum_range_succ', cast_succ, bernoulli_one, bernoulli_zero, choose_one_right, mul_one, choose_zero_right, cast_zero, if_false, zero_add, succ_succ_ne_one], ring }, have f := sum_bernoulli' n.succ.succ, simp_rw [sum_range_succ', bernoulli'_one, choose_one_right, cast_succ, ← eq_sub_iff_add_eq] at f, convert f, { funext x, rw bernoulli_eq_bernoulli'_of_ne_one (succ_ne_zero x ∘ succ.inj) }, { simp only [one_div, mul_one, bernoulli'_zero, cast_one, choose_zero_right, add_sub_cancel], ring }, end lemma bernoulli_spec' (n : ℕ) : ∑ k in antidiagonal n, ((k.1 + k.2).choose k.2 : ℚ) / (k.2 + 1) * bernoulli k.1 = if n = 0 then 1 else 0 := begin cases n, { simp }, rw if_neg (succ_ne_zero _), -- algebra facts have h₁ : (1, n) ∈ antidiagonal n.succ := by simp [mem_antidiagonal, add_comm], have h₂ : (n : ℚ) + 1 ≠ 0 := by apply_mod_cast succ_ne_zero, have h₃ : (1 + n).choose n = n + 1 := by simp [add_comm], -- key equation: the corresponding fact for `bernoulli'` have H := bernoulli'_spec' n.succ, -- massage it to match the structure of the goal, then convert piece by piece rw sum_eq_add_sum_diff_singleton h₁ at H ⊢, apply add_eq_of_eq_sub', convert eq_sub_of_add_eq' H using 1, { refine sum_congr rfl (λ p h, _), obtain ⟨h', h''⟩ : p ∈ _ ∧ p ≠ _ := by rwa [mem_sdiff, mem_singleton] at h, simp [bernoulli_eq_bernoulli'_of_ne_one ((not_congr (antidiagonal_congr h' h₁)).mp h'')] }, { field_simp [h₃], norm_num }, end /-- The exponential generating function for the Bernoulli numbers `bernoulli n`. -/ def bernoulli_power_series := mk $ λ n, algebra_map ℚ A (bernoulli n / n!) theorem bernoulli_power_series_mul_exp_sub_one : bernoulli_power_series A * (exp A - 1) = X := begin ext n, -- constant coefficient is a special case cases n, { simp }, simp only [bernoulli_power_series, coeff_mul, coeff_X, sum_antidiagonal_succ', one_div, coeff_mk, coeff_one, coeff_exp, linear_map.map_sub, factorial, if_pos, cast_succ, cast_one, cast_mul, sub_zero, ring_hom.map_one, add_eq_zero_iff, if_false, _root_.inv_one, zero_add, one_ne_zero, mul_zero, and_false, sub_self, ← ring_hom.map_mul, ← ring_hom.map_sum], suffices : ∑ x in antidiagonal n, bernoulli x.1 / x.1! * ((x.2 + 1) * x.2!)⁻¹ = if n.succ = 1 then 1 else 0, { split_ifs; simp [h, this] }, cases n, { simp }, have hfact : ∀ m, (m! : ℚ) ≠ 0 := λ m, by exact_mod_cast factorial_ne_zero m, have hite1 : ite (n.succ.succ = 1) 1 0 = (0 / n.succ! : ℚ) := by simp, have hite2 : ite (n.succ = 0) 1 0 = (0 : ℚ) := by simp [succ_ne_zero], rw [hite1, eq_div_iff (hfact n.succ), ← hite2, ← bernoulli_spec', sum_mul], apply sum_congr rfl, rintro ⟨i, j⟩ h, rw mem_antidiagonal at h, have hj : (j.succ : ℚ) ≠ 0 := by exact_mod_cast succ_ne_zero j, field_simp [← h, mul_ne_zero hj (hfact j), hfact i, mul_comm _ (bernoulli i), mul_assoc], rw_mod_cast [mul_comm (j + 1), mul_div_assoc, ← mul_assoc], rw [cast_mul, cast_mul, mul_div_mul_right _ _ hj, add_choose, cast_dvd_char_zero], apply factorial_mul_factorial_dvd_factorial_add, end section faulhaber /-- **Faulhaber's theorem** relating the **sum of of p-th powers** to the Bernoulli numbers: $$\sum_{k=0}^{n-1} k^p = \sum_{i=0}^p B_i\binom{p+1}{i}\frac{n^{p+1-i}}{p+1}.$$ See https://proofwiki.org/wiki/Faulhaber%27s_Formula and [orosi2018faulhaber] for the proof provided here. -/ theorem sum_range_pow (n p : ℕ) : ∑ k in range n, (k : ℚ) ^ p = ∑ i in range (p + 1), bernoulli i * (p + 1).choose i * n ^ (p + 1 - i) / (p + 1) := begin have hne : ∀ m : ℕ, (m! : ℚ) ≠ 0 := λ m, by exact_mod_cast factorial_ne_zero m, -- compute the Cauchy product of two power series have h_cauchy : mk (λ p, bernoulli p / p!) * mk (λ q, coeff ℚ (q + 1) (exp ℚ ^ n)) = mk (λ p, ∑ i in range (p + 1), bernoulli i * (p + 1).choose i * n ^ (p + 1 - i) / (p + 1)!), { ext q : 1, let f := λ a b, bernoulli a / a! * coeff ℚ (b + 1) (exp ℚ ^ n), -- key step: use `power_series.coeff_mul` and then rewrite sums simp only [coeff_mul, coeff_mk, cast_mul, sum_antidiagonal_eq_sum_range_succ f], apply sum_congr rfl, simp_intros m h only [finset.mem_range], simp only [f, exp_pow_eq_rescale_exp, rescale, one_div, coeff_mk, ring_hom.coe_mk, coeff_exp, ring_hom.id_apply, cast_mul, algebra_map_rat_rat], -- manipulate factorials and binomial coefficients rw [choose_eq_factorial_div_factorial h.le, eq_comm, div_eq_iff (hne q.succ), succ_eq_add_one, mul_assoc _ _ ↑q.succ!, mul_comm _ ↑q.succ!, ← mul_assoc, div_mul_eq_mul_div, mul_comm (↑n ^ (q - m + 1)), ← mul_assoc _ _ (↑n ^ (q - m + 1)), ← one_div, mul_one_div, div_div_eq_div_mul, tsub_add_eq_add_tsub (le_of_lt_succ h), cast_dvd, cast_mul], { ring }, { exact factorial_mul_factorial_dvd_factorial h.le }, { simp [hne] } }, -- same as our goal except we pull out `p!` for convenience have hps : ∑ k in range n, ↑k ^ p = (∑ i in range (p + 1), bernoulli i * (p + 1).choose i * n ^ (p + 1 - i) / (p + 1)!) * p!, { suffices : mk (λ p, ∑ k in range n, ↑k ^ p * algebra_map ℚ ℚ p!⁻¹) = mk (λ p, ∑ i in range (p + 1), bernoulli i * (p + 1).choose i * n ^ (p + 1 - i) / (p + 1)!), { rw [← div_eq_iff (hne p), div_eq_mul_inv, sum_mul], rw power_series.ext_iff at this, simpa using this p }, -- the power series `exp ℚ - 1` is non-zero, a fact we need in order to use `mul_right_inj'` have hexp : exp ℚ - 1 ≠ 0, { simp only [exp, power_series.ext_iff, ne, not_forall], use 1, simp }, have h_r : exp ℚ ^ n - 1 = X * mk (λ p, coeff ℚ (p + 1) (exp ℚ ^ n)), { have h_const : C ℚ (constant_coeff ℚ (exp ℚ ^ n)) = 1 := by simp, rw [← h_const, sub_const_eq_X_mul_shift] }, -- key step: a chain of equalities of power series rw [← mul_right_inj' hexp, mul_comm, ← exp_pow_sum, ← geom_sum_def, geom_sum_mul, h_r, ← bernoulli_power_series_mul_exp_sub_one, bernoulli_power_series, mul_right_comm], simp [h_cauchy, mul_comm] }, -- massage `hps` into our goal rw [hps, sum_mul], refine sum_congr rfl (λ x hx, _), field_simp [mul_right_comm _ ↑p!, ← mul_assoc _ _ ↑p!, cast_add_one_ne_zero, hne], end /-- Alternate form of **Faulhaber's theorem**, relating the sum of p-th powers to the Bernoulli numbers: $$\sum_{k=1}^{n} k^p = \sum_{i=0}^p (-1)^iB_i\binom{p+1}{i}\frac{n^{p+1-i}}{p+1}.$$ Deduced from `sum_range_pow`. -/ theorem sum_Ico_pow (n p : ℕ) : ∑ k in Ico 1 (n + 1), (k : ℚ) ^ p = ∑ i in range (p + 1), bernoulli' i * (p + 1).choose i * n ^ (p + 1 - i) / (p + 1) := begin -- dispose of the trivial case cases p, { simp }, let f := λ i, bernoulli i * p.succ.succ.choose i * n ^ (p.succ.succ - i) / p.succ.succ, let f' := λ i, bernoulli' i * p.succ.succ.choose i * n ^ (p.succ.succ - i) / p.succ.succ, suffices : ∑ k in Ico 1 n.succ, ↑k ^ p.succ = ∑ i in range p.succ.succ, f' i, { convert this }, -- prove some algebraic facts that will make things easier for us later on have hle := nat.le_add_left 1 n, have hne : (p + 1 + 1 : ℚ) ≠ 0 := by exact_mod_cast succ_ne_zero p.succ, have h1 : ∀ r : ℚ, r * (p + 1 + 1) * n ^ p.succ / (p + 1 + 1 : ℚ) = r * n ^ p.succ := λ r, by rw [mul_div_right_comm, mul_div_cancel _ hne], have h2 : f 1 + n ^ p.succ = 1 / 2 * n ^ p.succ, { simp_rw [f, bernoulli_one, choose_one_right, succ_sub_succ_eq_sub, cast_succ, tsub_zero, h1], ring }, have : ∑ i in range p, bernoulli (i + 2) * (p + 2).choose (i + 2) * n ^ (p - i) / ↑(p + 2) = ∑ i in range p, bernoulli' (i + 2) * (p + 2).choose (i + 2) * n ^ (p - i) / ↑(p + 2) := sum_congr rfl (λ i h, by rw bernoulli_eq_bernoulli'_of_ne_one (succ_succ_ne_one i)), calc ∑ k in Ico 1 n.succ, ↑k ^ p.succ -- replace sum over `Ico` with sum over `range` and simplify = ∑ k in range n.succ, ↑k ^ p.succ : by simp [sum_Ico_eq_sub _ hle, succ_ne_zero] -- extract the last term of the sum ... = ∑ k in range n, (k : ℚ) ^ p.succ + n ^ p.succ : by rw sum_range_succ -- apply the key lemma, `sum_range_pow` ... = ∑ i in range p.succ.succ, f i + n ^ p.succ : by simp [f, sum_range_pow] -- extract the first two terms of the sum ... = ∑ i in range p, f i.succ.succ + f 1 + f 0 + n ^ p.succ : by simp_rw [sum_range_succ'] ... = ∑ i in range p, f i.succ.succ + (f 1 + n ^ p.succ) + f 0 : by ring ... = ∑ i in range p, f i.succ.succ + 1 / 2 * n ^ p.succ + f 0 : by rw h2 -- convert from `bernoulli` to `bernoulli'` ... = ∑ i in range p, f' i.succ.succ + f' 1 + f' 0 : by { simp only [f, f'], simpa [h1] } -- rejoin the first two terms of the sum ... = ∑ i in range p.succ.succ, f' i : by simp_rw [sum_range_succ'], end end faulhaber
9bc7a6d5e0cec2e2bd0ee5a3aece0d761d8d9cd6
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/11_Tactic-Style_Proofs.org.49.lean
678b46f99f4dac616001f3f9154314f3d68cbe3a
[]
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
238
lean
import standard open sigma nat example (x y : nat) (H : (fun (a : nat), pr1 ⟨a, y⟩) x = 0) : x = 0 := begin esimp at H, exact H end example (x y : nat) (H : x = 0) : (fun (a : nat), pr1 ⟨a, y⟩) x = 0 := begin esimp, exact H end
25b5cb8cd95c0ec7fffa095862236c928ce5497b
01ae0d022f2e2fefdaaa898938c1ac1fbce3b3ab
/categories/currying/currying_1.lean
931e91bc8319670187ba4121e6b1c575d9697e56
[]
no_license
PatrickMassot/lean-category-theory
0f56a83464396a253c28a42dece16c93baf8ad74
ef239978e91f2e1c3b8e88b6e9c64c155dc56c99
refs/heads/master
1,629,739,187,316
1,512,422,659,000
1,512,422,659,000
113,098,786
0
0
null
1,512,424,022,000
1,512,424,022,000
null
UTF-8
Lean
false
false
2,093
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import ..natural_transformation import ..equivalence import ..products.bifunctors open categories open categories.isomorphism open categories.functor open categories.equivalence open categories.functor_categories namespace categories.natural_transformation universes u1 v1 u2 v2 u3 v3 variable C : Category.{u1 v1} variable D : Category.{u2 v2} variable E : Category.{u3 v3} definition Uncurry_Functors : Functor (FunctorCategory C (FunctorCategory D E)) (FunctorCategory (C × D) E) := { onObjects := λ (F : Functor C (FunctorCategory D E)), { onObjects := λ X, (F.onObjects X.1).onObjects X.2, onMorphisms := λ X Y f, E.compose ((F.onMorphisms f.1).components X.2) ((F.onObjects Y.1).onMorphisms f.2), identities := ♯, functoriality := ♯ }, onMorphisms := λ F G (T : NaturalTransformation F G), { components := λ X, (T.components _).components _, naturality := ♯ }, identities := ♯, functoriality := ♯ } definition Curry_Functors : Functor (FunctorCategory (C × D) E) (FunctorCategory C (FunctorCategory D E)) := { onObjects := λ F: Functor (C × D) E, { onObjects := λ X, { onObjects := λ Y, F.onObjects (X, Y), onMorphisms := λ Y Y' g, F.onMorphisms (C.identity X, g), identities := ♯, functoriality := ♯ }, onMorphisms := λ X X' f, { components := λ Y, F.onMorphisms (f, D.identity Y), naturality := ♯ }, identities := ♯, functoriality := ♯ }, onMorphisms := λ F G T, { components := λ X, { components := λ Y, T.components (X, Y), naturality := ♯ }, naturality := ♯ }, identities := ♯, functoriality := ♯ } end categories.natural_transformation
608f74b21ead039ee17698c6708f7eb4fcc624e2
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/meta/tactic.lean
2a8abaed3e81020db9f651f0dfa2a46be6214795
[ "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
76,457
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 import init.classical 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 (result result.success result.exception result.cases_on result_to_string mk_exception silent_fail orelse' bracket) /-- 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 : 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 /-- `capture t` acts like `t`, but succeeds with a result containing either the returned value or the exception. Changes made by `t` to the `tactic_state` are preserved in both cases. The result can be used to inspect the error message, or passed to `unwrap` to rethrow the failure later. -/ meta def capture (t : tactic α) : tactic (tactic_result α) := λ s, match t s with | (success r s') := success (success r s') s' | (exception f p s') := success (exception f p s') s' end /-- `unwrap r` unwraps a result previously obtained using `capture`. If the previous result was a success, this produces its wrapped value. If the previous result was an exception, this "rethrows" the exception as if it came from where it originated. `do r ← capture t, unwrap r` is identical to `t`, but allows for intermediate tactics to be inserted. -/ meta def unwrap {α : Type*} (t : tactic_result α) : tactic α := match t with | (success r s') := return r | e := λ s, e end /-- `resume r` continues execution from a result previously obtained using `capture`. This is like `unwrap`, but the `tactic_state` is rolled back to point of capture even upon success. -/ meta def resume {α : Type*} (t : tactic_result α) : tactic α := λ s, t 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 constant get_trace_msg_pos : tactic pos 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} nat (a > b) (nat.decidable_gt a b) 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 if 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 /-- Convenience function for creating ` for proofs. -/ meta def mk_tagged_proof (prop : expr) (pr : expr) (tag : name) : expr := expr.mk_app (expr.const ``id_tag []) [expr.const tag [], prop, pr] /-- 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`. Note: There is one "new hypothesis" for every constructor argument. These are usually local constants, but due to dependent pattern matching, they can also be arbitrary terms. -/ 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. -/ /-- Avoid this function! Use `unfreezingI`/`resetI`/etc. instead! Unfreezes the current set of local instances. After this tactic, the instance cache is disabled. -/ 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)) /-- Run the provided tactic, associating it to the given AST node. -/ meta constant with_ast {α : Type u} (ast : ℕ) (t : tactic α) : tactic α 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 ast : ℕ) (t : tactic α) : tactic unit := λ s, (@scope_trace _ line col (λ _, with_ast ast (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 /-- A variant of `intro` which makes sure that the introduced hypothesis's name is unique in the context. If there is no hypothesis named `n` in the context yet, `intro_fresh n` is the same as `intro n`. If there is already a hypothesis named `n`, the new hypothesis is named `n_1` (or `n_2` if `n_1` already exists, etc.). If `offset` is given, the new names are `n_offset`, `n_offset+1` etc. If `n` is `_`, `intro_fresh n` is the same as `intro1`. The `offset` is ignored in this case. -/ meta def intro_fresh (n : name) (offset : option nat := none) : tactic expr := if n = `_ then intro `_ else do n ← get_unused_name n offset, intro 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 (ns : list name) : tactic (list expr) := ns.mmap intro /-- A variant of `intro_lst` which makes sure that the introduced hypotheses' names are unique in the context. See `intro_fresh`. -/ meta def intro_lst_fresh (ns : list name) : tactic (list expr) := ns.mmap intro_fresh /-- 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' (n : ℕ) : tactic (list expr) := iterate_exactly n intro1 /-- Like `intron'` but the introduced hypotheses' names are derived from `base`, i.e. `base`, `base_1` etc. The new names are unique in the context. If `offset` is given, the new names will be `base_offset`, `base_offset+1` etc. -/ meta def intron_base (n : ℕ) (base : name) (offset : option nat := none) : tactic (list expr) := iterate_exactly n (intro_fresh base offset) /-- `intron_with i ns base offset` introduces `i` hypotheses using the names from `ns`. If `ns` contains less than `i` names, the remaining hypotheses' names are derived from `base` and `offset` (as with `intron_base`). If `base` is `_`, the names are derived from the Π binder names. Returns the introduced local constants and the remaining names from `ns` (if `ns` contains more than `i` names). -/ meta def intron_with : ℕ → list name → opt_param name `_ → opt_param (option ℕ) none → tactic (list expr × list name) | 0 ns _ _ := pure ([], ns) | (i + 1) [] base offset := do hs ← intron_base (i + 1) base offset, pure (hs, []) | (i + 1) (n :: ns) base offset := do h ← intro n, ⟨hs, rest⟩ ← intron_with i ns base offset, pure (h :: hs, rest) /-- Returns n fully qualified if it refers to a constant, or else fails. -/ meta def resolve_constant (n : name) : tactic name := do e ← resolve_name n, match e with | expr.const n _ := pure n | _ := do e ← to_expr e tt ff, expr.const n _ ← pure $ e.get_app_fn, pure n end 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, use `unfreezing revert_all` instead. -/ 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 : name) : tactic expr := do tgt ← target, tgt_wh ← whnf tgt reducible, -- to ensure that `not` in `ne` is found (match_not tgt_wh $> ()) <|> (mk_mapp `decidable.by_contradiction [some tgt, none] >>= eapply >> skip) <|> (mk_mapp `classical.by_contradiction [some tgt] >>= eapply >> skip) <|> fail "tactic by_contradiction failed, target is not a proposition", intro H 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 /-- Postprocess the output of `cases_core`: - The third component of each tuple in the input list (the list of substitutions) is dropped since we don't use it anywhere. - The second component (the list of new hypotheses) is filtered: any expression that is not a local constant is dropped. We only use the new hypotheses for the renaming functionality of `case`, so we want to keep only those "new hypotheses" that are, in fact, local constants. -/ private meta def cases_postprocess (hs : list (name × list expr × list (name × expr))) : list (name × list expr) := hs.map $ λ ⟨n, hs, _⟩, (n, hs.filter (λ h, h.is_local_constant)) /-- 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. Note that while `cases_core` may return "new hypotheses" that are not local constants, this tactic only returns local constants. -/ 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 $ cases_postprocess r 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 $ cases_postprocess $ r.map₂ (λ ⟨n, hs, x⟩ hs', (n, hs ++ hs', x)) 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 /-- `by_cases p h` splits the main goal into two cases, assuming `h : p` in the first branch, and `h : ¬ p` in the second branch. The expression `p` needs to be a proposition. The produced proof term is `dite p ?m_1 ?m_2`. -/ 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 <|> pure `(classical.prop_decidable %%e), tgt ← target, expr.sort tgt_u ← infer_type tgt >>= whnf, g1 ← mk_meta_var (e.imp tgt), g2 ← mk_meta_var (`(¬ %%e).imp tgt), focus1 $ do exact $ expr.const ``dite [tgt_u] tgt e inst g1 g2, set_goals [g1, g2], all_goals' $ 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 /-- Execute `tac` for `max` milliseconds. Useful due to variance in the number of heartbeats taken by various tactics. -/ meta def try_for_time {α} (max : nat) (tac : tactic α) : tactic α := λ s, match _root_.try_for_time max (tac s) with | some r := r | none := mk_exception "try_for_time 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 `unfreezing (rename_many ...)`. 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 `unfreezingI { ... }`." ] }, -- 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) (tag : name := `unit.star) : tactic expr := do h_type ← infer_type h, new_h ← assert h.local_pp_name new_type, eq_pr_type ← mk_app `eq [h_type, new_type], let eq_pr := mk_tagged_proof eq_pr_type eq_pr tag, 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 replace_target (new_target : expr) (pr : expr) (tag : name := `unit.star) : tactic unit := do t ← target, assert `htarget new_target, swap, ht ← get_local `htarget, pr_type ← mk_app `eq [t, new_target], let locked_pr := mk_tagged_proof pr_type pr tag, 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 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
34e8915446d6526b9b092c9ee09414635db643d4
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/group_theory/is_free_group.lean
8a86d700a2247bd92ed93164da33a27346e72de7
[ "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
5,830
lean
/- Copyright (c) 2021 David Wärn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Wärn, Eric Wieser -/ import group_theory.free_group /-! # Free groups structures on arbitrary types This file defines the universal property of free groups, and proves some things about groups with this property. For an explicit construction of free groups, see `group_theory/free_group`. ## Main definitions * `is_free_group G` - a typeclass to indicate that `G` is free over some generators * `is_free_group.lift` - the (noncomputable) universal property of the free group * `is_free_group.to_free_group` - any free group with generators `A` is equivalent to `free_group A`. ## Implementation notes While the typeclass only requires the universal property hold within a single universe `u`, our explicit construction of `free_group` allows this to be extended universe polymorphically. The primed definition names in this file refer to the non-polymorphic versions. -/ noncomputable theory universes u w /-- `is_free_group G` means that `G` has the universal property of a free group, That is, it has a family `generators G` of elements, such that a group homomorphism `G →* X` is uniquely determined by a function `generators G → X`. -/ class is_free_group (G : Type u) [group G] : Type (u+1) := (generators : Type u) (of : generators → G) (unique_lift' : ∀ {X : Type u} [group X] (f : generators → X), ∃! F : G →* X, ∀ a, F (of a) = f a) instance free_group_is_free_group {A} : is_free_group (free_group A) := { generators := A, of := free_group.of, unique_lift' := begin introsI X _ f, have := free_group.lift.symm.bijective.exists_unique f, simp_rw function.funext_iff at this, exact this, end } namespace is_free_group variables {G H : Type u} {X : Type w} [group G] [group H] [group X] [is_free_group G] /-- The equivalence between functions on the generators and group homomorphisms from a free group given by those generators. -/ @[simps symm_apply] def lift' : (generators G → H) ≃ (G →* H) := { to_fun := λ f, classical.some (unique_lift' f), inv_fun := λ F, F ∘ of, left_inv := λ f, funext (classical.some_spec (unique_lift' f)).left, right_inv := λ F, ((classical.some_spec (unique_lift' (F ∘ of))).right F (λ _, rfl)).symm } @[simp] lemma lift'_of (f : generators G → H) (a : generators G) : (lift' f) (of a) = f a := congr_fun (lift'.symm_apply_apply f) a @[simp] lemma lift'_eq_free_group_lift {A : Type u} : (@lift' (free_group A) H _ _ _) = free_group.lift := begin -- TODO: `apply equiv.symm_bijective.injective`, rw [←free_group.lift.symm_symm, ←(@lift' (free_group A) H _ _ _).symm_symm], congr' 1, ext, refl, end @[simp] lemma of_eq_free_group_of {A : Type u} : (@of (free_group A) _ _) = free_group.of := rfl @[ext] lemma ext_hom' ⦃f g : G →* H⦄ (h : ∀ a, f (of a) = g (of a)) : f = g := lift'.symm.injective $ funext h /-- Being a free group transports across group isomorphisms within a universe. -/ def of_mul_equiv (h : G ≃* H) : is_free_group H := { generators := generators G, of := h ∘ of, unique_lift' := begin introsI X _ f, refine ⟨(lift' f).comp h.symm.to_monoid_hom, _, _⟩, { simp }, intros F' hF', suffices : F'.comp h.to_monoid_hom = lift' f, { rw ←this, ext, apply congr_arg, symmetry, apply mul_equiv.apply_symm_apply }, ext, simp [hF'], end } /-! ### Universe-polymorphic definitions The primed definitions and lemmas above require `G` and `H` to be in the same universe `u`. The lemmas below use `X` in a different universe `w` -/ variable (G) /-- Any free group is isomorphic to "the" free group. -/ @[simps] def to_free_group : G ≃* free_group (generators G) := { to_fun := lift' free_group.of, inv_fun := free_group.lift of, left_inv := suffices (free_group.lift of).comp (lift' free_group.of) = monoid_hom.id G, from monoid_hom.congr_fun this, by { ext, simp }, right_inv := suffices (lift' free_group.of).comp (free_group.lift of) = monoid_hom.id (free_group (generators G)), from monoid_hom.congr_fun this, by { ext, simp }, map_mul' := (lift' free_group.of).map_mul } variable {G} private lemma lift_right_inv_aux (F : G →* X) : free_group.lift.symm (F.comp (to_free_group G).symm.to_monoid_hom) = F ∘ of := by { ext, simp } /-- A universe-polymorphic version of `is_free_group.lift'`. -/ @[simps symm_apply] def lift : (generators G → X) ≃ (G →* X) := { to_fun := λ f, (free_group.lift f).comp (to_free_group G).to_monoid_hom, inv_fun := λ F, F ∘ of, left_inv := λ f, free_group.lift.injective begin ext x, simp, end, right_inv := λ F, begin dsimp, rw ←lift_right_inv_aux, simp only [equiv.apply_symm_apply], ext x, dsimp only [monoid_hom.comp_apply, mul_equiv.coe_to_monoid_hom], rw mul_equiv.symm_apply_apply, end} @[ext] lemma ext_hom ⦃f g : G →* X⦄ (h : ∀ a, f (of a) = g (of a)) : f = g := is_free_group.lift.symm.injective $ funext h @[simp] lemma lift_of (f : generators G → X) (a : generators G) : (lift f) (of a) = f a := congr_fun (lift.symm_apply_apply f) a @[simp] lemma lift_eq_free_group_lift {A : Type u} : (@lift (free_group A) H _ _ _) = free_group.lift := begin -- TODO: `apply equiv.symm_bijective.injective`, rw [←free_group.lift.symm_symm, ←(@lift (free_group A) H _ _ _).symm_symm], congr' 1, ext, refl, end /-- A universe-polymorphic version of `unique_lift`. -/ lemma unique_lift {X : Type w} [group X] (f : generators G → X) : ∃! F : G →* X, ∀ a, F (of a) = f a := begin have := lift.symm.bijective.exists_unique f, simp_rw function.funext_iff at this, exact this, end end is_free_group
c4c7ee3041a98f1a1cd7886662f24b78dc1cac03
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Meta/Coe.lean
82131807a6e8cb6ca1b1a60b728c24aef332b347
[ "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
1,459
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.WHNF import Lean.Meta.Transform namespace Lean.Meta /-- Return true iff `declName` is one of the auxiliary definitions/projections used to implement coercions. -/ def isCoeDecl (declName : Name) : Bool := declName == ``coe || declName == ``coeB || declName == ``coeHead || declName == ``coeTail || declName == ``coeD || declName == ``coeTC || declName == ``coeFun || declName == ``coeSort || declName == ``Coe.coe || declName == ``CoeTC.coe || declName == ``CoeHead.coe || declName == ``CoeTail.coe || declName == ``CoeHTCT.coe || declName == ``CoeDep.coe || declName == ``CoeT.coe || declName == ``CoeFun.coe || declName == ``CoeSort.coe || declName == ``liftCoeM || declName == ``coeM /-- Expand coercions occurring in `e` -/ partial def expandCoe (e : Expr) : MetaM Expr := withReducibleAndInstances do return (← transform e (pre := step)) where step (e : Expr) : MetaM TransformStep := do let f := e.getAppFn if !f.isConst then return TransformStep.visit e else let declName := f.constName! if isCoeDecl declName then match (← unfoldDefinition? e) with | none => return TransformStep.visit e | some e => step e.headBeta else return TransformStep.visit e end Lean.Meta
2872163a37ca70e75203b4dfde746901c8a55d44
9dc8cecdf3c4634764a18254e94d43da07142918
/src/analysis/convex/strict.lean
bd63c97e0952d550c08659f56b18b9081afbc6c4
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
16,017
lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import analysis.convex.basic import topology.algebra.order.basic /-! # Strictly convex sets This file defines strictly convex sets. A set is strictly convex if the open segment between any two distinct points lies in its interior. -/ open set open_locale convex pointwise variables {𝕜 𝕝 E F β : Type*} open function set open_locale convex section ordered_semiring variables [ordered_semiring 𝕜] [topological_space E] [topological_space F] section add_comm_monoid variables [add_comm_monoid E] [add_comm_monoid F] section has_smul variables (𝕜) [has_smul 𝕜 E] [has_smul 𝕜 F] (s : set E) /-- A set is strictly convex if the open segment between any two distinct points lies is in its interior. This basically means "convex and not flat on the boundary". -/ def strict_convex : Prop := s.pairwise $ λ x y, ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1 → a • x + b • y ∈ interior s variables {𝕜 s} {x y : E} {a b : 𝕜} lemma strict_convex_iff_open_segment_subset : strict_convex 𝕜 s ↔ s.pairwise (λ x y, open_segment 𝕜 x y ⊆ interior s) := forall₅_congr $ λ x hx y hy hxy, (open_segment_subset_iff 𝕜).symm lemma strict_convex.open_segment_subset (hs : strict_convex 𝕜 s) (hx : x ∈ s) (hy : y ∈ s) (h : x ≠ y) : open_segment 𝕜 x y ⊆ interior s := strict_convex_iff_open_segment_subset.1 hs hx hy h lemma strict_convex_empty : strict_convex 𝕜 (∅ : set E) := pairwise_empty _ lemma strict_convex_univ : strict_convex 𝕜 (univ : set E) := begin intros x hx y hy hxy a b ha hb hab, rw interior_univ, exact mem_univ _, end protected lemma strict_convex.eq (hs : strict_convex 𝕜 s) (hx : x ∈ s) (hy : y ∈ s) (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1) (h : a • x + b • y ∉ interior s) : x = y := hs.eq hx hy $ λ H, h $ H ha hb hab protected lemma strict_convex.inter {t : set E} (hs : strict_convex 𝕜 s) (ht : strict_convex 𝕜 t) : strict_convex 𝕜 (s ∩ t) := begin intros x hx y hy hxy a b ha hb hab, rw interior_inter, exact ⟨hs hx.1 hy.1 hxy ha hb hab, ht hx.2 hy.2 hxy ha hb hab⟩, end lemma directed.strict_convex_Union {ι : Sort*} {s : ι → set E} (hdir : directed (⊆) s) (hs : ∀ ⦃i : ι⦄, strict_convex 𝕜 (s i)) : strict_convex 𝕜 (⋃ i, s i) := begin rintro x hx y hy hxy a b ha hb hab, rw mem_Union at hx hy, obtain ⟨i, hx⟩ := hx, obtain ⟨j, hy⟩ := hy, obtain ⟨k, hik, hjk⟩ := hdir i j, exact interior_mono (subset_Union s k) (hs (hik hx) (hjk hy) hxy ha hb hab), end lemma directed_on.strict_convex_sUnion {S : set (set E)} (hdir : directed_on (⊆) S) (hS : ∀ s ∈ S, strict_convex 𝕜 s) : strict_convex 𝕜 (⋃₀ S) := begin rw sUnion_eq_Union, exact (directed_on_iff_directed.1 hdir).strict_convex_Union (λ s, hS _ s.2), end end has_smul section module variables [module 𝕜 E] [module 𝕜 F] {s : set E} protected lemma strict_convex.convex (hs : strict_convex 𝕜 s) : convex 𝕜 s := convex_iff_pairwise_pos.2 $ λ x hx y hy hxy a b ha hb hab, interior_subset $ hs hx hy hxy ha hb hab /-- An open convex set is strictly convex. -/ protected lemma convex.strict_convex (h : is_open s) (hs : convex 𝕜 s) : strict_convex 𝕜 s := λ x hx y hy _ a b ha hb hab, h.interior_eq.symm ▸ hs hx hy ha.le hb.le hab lemma is_open.strict_convex_iff (h : is_open s) : strict_convex 𝕜 s ↔ convex 𝕜 s := ⟨strict_convex.convex, convex.strict_convex h⟩ lemma strict_convex_singleton (c : E) : strict_convex 𝕜 ({c} : set E) := pairwise_singleton _ _ lemma set.subsingleton.strict_convex (hs : s.subsingleton) : strict_convex 𝕜 s := hs.pairwise _ lemma strict_convex.linear_image [semiring 𝕝] [module 𝕝 E] [module 𝕝 F] [linear_map.compatible_smul E F 𝕜 𝕝] (hs : strict_convex 𝕜 s) (f : E →ₗ[𝕝] F) (hf : is_open_map f) : strict_convex 𝕜 (f '' s) := begin rintro _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩ hxy a b ha hb hab, refine hf.image_interior_subset _ ⟨a • x + b • y, hs hx hy (ne_of_apply_ne _ hxy) ha hb hab, _⟩, rw [map_add, f.map_smul_of_tower a, f.map_smul_of_tower b] end lemma strict_convex.is_linear_image (hs : strict_convex 𝕜 s) {f : E → F} (h : is_linear_map 𝕜 f) (hf : is_open_map f) : strict_convex 𝕜 (f '' s) := hs.linear_image (h.mk' f) hf lemma strict_convex.linear_preimage {s : set F} (hs : strict_convex 𝕜 s) (f : E →ₗ[𝕜] F) (hf : continuous f) (hfinj : injective f) : strict_convex 𝕜 (s.preimage f) := begin intros x hx y hy hxy a b ha hb hab, refine preimage_interior_subset_interior_preimage hf _, rw [mem_preimage, f.map_add, f.map_smul, f.map_smul], exact hs hx hy (hfinj.ne hxy) ha hb hab, end lemma strict_convex.is_linear_preimage {s : set F} (hs : strict_convex 𝕜 s) {f : E → F} (h : is_linear_map 𝕜 f) (hf : continuous f) (hfinj : injective f) : strict_convex 𝕜 (s.preimage f) := hs.linear_preimage (h.mk' f) hf hfinj section linear_ordered_cancel_add_comm_monoid variables [topological_space β] [linear_ordered_cancel_add_comm_monoid β] [order_topology β] [module 𝕜 β] [ordered_smul 𝕜 β] lemma strict_convex_Iic (r : β) : strict_convex 𝕜 (Iic r) := begin rintro x (hx : x ≤ r) y (hy : y ≤ r) hxy a b ha hb hab, refine (subset_interior_iff_subset_of_open is_open_Iio).2 Iio_subset_Iic_self _, rw ←convex.combo_self hab r, obtain rfl | hx := hx.eq_or_lt, { exact add_lt_add_left (smul_lt_smul_of_pos (hy.lt_of_ne hxy.symm) hb) _ }, obtain rfl | hy := hy.eq_or_lt, { exact add_lt_add_right (smul_lt_smul_of_pos hx ha) _ }, { exact add_lt_add (smul_lt_smul_of_pos hx ha) (smul_lt_smul_of_pos hy hb) } end lemma strict_convex_Ici (r : β) : strict_convex 𝕜 (Ici r) := @strict_convex_Iic 𝕜 βᵒᵈ _ _ _ _ _ _ r lemma strict_convex_Icc (r s : β) : strict_convex 𝕜 (Icc r s) := (strict_convex_Ici r).inter $ strict_convex_Iic s lemma strict_convex_Iio (r : β) : strict_convex 𝕜 (Iio r) := (convex_Iio r).strict_convex is_open_Iio lemma strict_convex_Ioi (r : β) : strict_convex 𝕜 (Ioi r) := (convex_Ioi r).strict_convex is_open_Ioi lemma strict_convex_Ioo (r s : β) : strict_convex 𝕜 (Ioo r s) := (strict_convex_Ioi r).inter $ strict_convex_Iio s lemma strict_convex_Ico (r s : β) : strict_convex 𝕜 (Ico r s) := (strict_convex_Ici r).inter $ strict_convex_Iio s lemma strict_convex_Ioc (r s : β) : strict_convex 𝕜 (Ioc r s) := (strict_convex_Ioi r).inter $ strict_convex_Iic s lemma strict_convex_interval (r s : β) : strict_convex 𝕜 (interval r s) := strict_convex_Icc _ _ end linear_ordered_cancel_add_comm_monoid end module end add_comm_monoid section add_cancel_comm_monoid variables [add_cancel_comm_monoid E] [has_continuous_add E] [module 𝕜 E] {s : set E} /-- The translation of a strictly convex set is also strictly convex. -/ lemma strict_convex.preimage_add_right (hs : strict_convex 𝕜 s) (z : E) : strict_convex 𝕜 ((λ x, z + x) ⁻¹' s) := begin intros x hx y hy hxy a b ha hb hab, refine preimage_interior_subset_interior_preimage (continuous_add_left _) _, have h := hs hx hy ((add_right_injective _).ne hxy) ha hb hab, rwa [smul_add, smul_add, add_add_add_comm, ←add_smul, hab, one_smul] at h, end /-- The translation of a strictly convex set is also strictly convex. -/ lemma strict_convex.preimage_add_left (hs : strict_convex 𝕜 s) (z : E) : strict_convex 𝕜 ((λ x, x + z) ⁻¹' s) := by simpa only [add_comm] using hs.preimage_add_right z end add_cancel_comm_monoid section add_comm_group variables [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F] section continuous_add variables [has_continuous_add E] {s t : set E} lemma strict_convex.add (hs : strict_convex 𝕜 s) (ht : strict_convex 𝕜 t) : strict_convex 𝕜 (s + t) := begin rintro _ ⟨v, w, hv, hw, rfl⟩ _ ⟨x, y, hx, hy, rfl⟩ h a b ha hb hab, rw [smul_add, smul_add, add_add_add_comm], obtain rfl | hvx := eq_or_ne v x, { refine interior_mono (add_subset_add (singleton_subset_iff.2 hv) subset.rfl) _, rw [convex.combo_self hab, singleton_add], exact (is_open_map_add_left _).image_interior_subset _ (mem_image_of_mem _ $ ht hw hy (ne_of_apply_ne _ h) ha hb hab) }, exact subset_interior_add_left (add_mem_add (hs hv hx hvx ha hb hab) $ ht.convex hw hy ha.le hb.le hab) end lemma strict_convex.add_left (hs : strict_convex 𝕜 s) (z : E) : strict_convex 𝕜 ((λ x, z + x) '' s) := by simpa only [singleton_add] using (strict_convex_singleton z).add hs lemma strict_convex.add_right (hs : strict_convex 𝕜 s) (z : E) : strict_convex 𝕜 ((λ x, x + z) '' s) := by simpa only [add_comm] using hs.add_left z /-- The translation of a strictly convex set is also strictly convex. -/ lemma strict_convex.vadd (hs : strict_convex 𝕜 s) (x : E) : strict_convex 𝕜 (x +ᵥ s) := hs.add_left x end continuous_add section continuous_smul variables [linear_ordered_field 𝕝] [module 𝕝 E] [has_continuous_const_smul 𝕝 E] [linear_map.compatible_smul E E 𝕜 𝕝] {s : set E} {x : E} lemma strict_convex.smul (hs : strict_convex 𝕜 s) (c : 𝕝) : strict_convex 𝕜 (c • s) := begin obtain rfl | hc := eq_or_ne c 0, { exact (subsingleton_zero_smul_set _).strict_convex }, { exact hs.linear_image (linear_map.lsmul _ _ c) (is_open_map_smul₀ hc) } end lemma strict_convex.affinity [has_continuous_add E] (hs : strict_convex 𝕜 s) (z : E) (c : 𝕝) : strict_convex 𝕜 (z +ᵥ c • s) := (hs.smul c).vadd z end continuous_smul end add_comm_group end ordered_semiring section ordered_comm_semiring variables [ordered_comm_semiring 𝕜] [topological_space E] section add_comm_group variables [add_comm_group E] [module 𝕜 E] [no_zero_smul_divisors 𝕜 E] [has_continuous_const_smul 𝕜 E] {s : set E} lemma strict_convex.preimage_smul (hs : strict_convex 𝕜 s) (c : 𝕜) : strict_convex 𝕜 ((λ z, c • z) ⁻¹' s) := begin classical, obtain rfl | hc := eq_or_ne c 0, { simp_rw [zero_smul, preimage_const], split_ifs, { exact strict_convex_univ }, { exact strict_convex_empty } }, refine hs.linear_preimage (linear_map.lsmul _ _ c) _ (smul_right_injective E hc), unfold linear_map.lsmul linear_map.mk₂ linear_map.mk₂' linear_map.mk₂'ₛₗ, exact continuous_const_smul _, end end add_comm_group end ordered_comm_semiring section ordered_ring variables [ordered_ring 𝕜] [topological_space E] [topological_space F] section add_comm_group variables [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F] {s t : set E} {x y : E} lemma strict_convex.eq_of_open_segment_subset_frontier [nontrivial 𝕜] [densely_ordered 𝕜] (hs : strict_convex 𝕜 s) (hx : x ∈ s) (hy : y ∈ s) (h : open_segment 𝕜 x y ⊆ frontier s) : x = y := begin obtain ⟨a, ha₀, ha₁⟩ := densely_ordered.dense (0 : 𝕜) 1 zero_lt_one, classical, by_contra hxy, exact (h ⟨a, 1 - a, ha₀, sub_pos_of_lt ha₁, add_sub_cancel'_right _ _, rfl⟩).2 (hs hx hy hxy ha₀ (sub_pos_of_lt ha₁) $ add_sub_cancel'_right _ _), end lemma strict_convex.add_smul_mem (hs : strict_convex 𝕜 s) (hx : x ∈ s) (hxy : x + y ∈ s) (hy : y ≠ 0) {t : 𝕜} (ht₀ : 0 < t) (ht₁ : t < 1) : x + t • y ∈ interior s := begin have h : x + t • y = (1 - t) • x + t • (x + y), { rw [smul_add, ←add_assoc, ←add_smul, sub_add_cancel, one_smul] }, rw h, refine hs hx hxy (λ h, hy $ add_left_cancel _) (sub_pos_of_lt ht₁) ht₀ (sub_add_cancel _ _), exact x, rw [←h, add_zero], end lemma strict_convex.smul_mem_of_zero_mem (hs : strict_convex 𝕜 s) (zero_mem : (0 : E) ∈ s) (hx : x ∈ s) (hx₀ : x ≠ 0) {t : 𝕜} (ht₀ : 0 < t) (ht₁ : t < 1) : t • x ∈ interior s := by simpa using hs.add_smul_mem zero_mem (by simpa using hx) hx₀ ht₀ ht₁ lemma strict_convex.add_smul_sub_mem (h : strict_convex 𝕜 s) (hx : x ∈ s) (hy : y ∈ s) (hxy : x ≠ y) {t : 𝕜} (ht₀ : 0 < t) (ht₁ : t < 1) : x + t • (y - x) ∈ interior s := begin apply h.open_segment_subset hx hy hxy, rw open_segment_eq_image', exact mem_image_of_mem _ ⟨ht₀, ht₁⟩, end /-- The preimage of a strictly convex set under an affine map is strictly convex. -/ lemma strict_convex.affine_preimage {s : set F} (hs : strict_convex 𝕜 s) {f : E →ᵃ[𝕜] F} (hf : continuous f) (hfinj : injective f) : strict_convex 𝕜 (f ⁻¹' s) := begin intros x hx y hy hxy a b ha hb hab, refine preimage_interior_subset_interior_preimage hf _, rw [mem_preimage, convex.combo_affine_apply hab], exact hs hx hy (hfinj.ne hxy) ha hb hab, end /-- The image of a strictly convex set under an affine map is strictly convex. -/ lemma strict_convex.affine_image (hs : strict_convex 𝕜 s) {f : E →ᵃ[𝕜] F} (hf : is_open_map f) : strict_convex 𝕜 (f '' s) := begin rintro _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩ hxy a b ha hb hab, exact hf.image_interior_subset _ ⟨a • x + b • y, ⟨hs hx hy (ne_of_apply_ne _ hxy) ha hb hab, convex.combo_affine_apply hab⟩⟩, end variables [topological_add_group E] lemma strict_convex.neg (hs : strict_convex 𝕜 s) : strict_convex 𝕜 (-s) := hs.is_linear_preimage is_linear_map.is_linear_map_neg continuous_id.neg neg_injective lemma strict_convex.sub (hs : strict_convex 𝕜 s) (ht : strict_convex 𝕜 t) : strict_convex 𝕜 (s - t) := (sub_eq_add_neg s t).symm ▸ hs.add ht.neg end add_comm_group end ordered_ring section linear_ordered_field variables [linear_ordered_field 𝕜] [topological_space E] section add_comm_group variables [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F] {s : set E} {x : E} /-- Alternative definition of set strict convexity, using division. -/ lemma strict_convex_iff_div : strict_convex 𝕜 s ↔ s.pairwise (λ x y, ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → (a / (a + b)) • x + (b / (a + b)) • y ∈ interior s) := ⟨λ h x hx y hy hxy a b ha hb, begin apply h hx hy hxy (div_pos ha $ add_pos ha hb) (div_pos hb $ add_pos ha hb), rw ←add_div, exact div_self (add_pos ha hb).ne', end, λ h x hx y hy hxy a b ha hb hab, by convert h hx hy hxy ha hb; rw [hab, div_one] ⟩ lemma strict_convex.mem_smul_of_zero_mem (hs : strict_convex 𝕜 s) (zero_mem : (0 : E) ∈ s) (hx : x ∈ s) (hx₀ : x ≠ 0) {t : 𝕜} (ht : 1 < t) : x ∈ t • interior s := begin rw mem_smul_set_iff_inv_smul_mem₀ (zero_lt_one.trans ht).ne', exact hs.smul_mem_of_zero_mem zero_mem hx hx₀ (inv_pos.2 $ zero_lt_one.trans ht) (inv_lt_one ht), end end add_comm_group end linear_ordered_field /-! #### Convex sets in an ordered space Relates `convex` and `set.ord_connected`. -/ section variables [topological_space E] /-- A set in a linear ordered field is strictly convex if and only if it is convex. -/ @[simp] lemma strict_convex_iff_convex [linear_ordered_field 𝕜] [topological_space 𝕜] [order_topology 𝕜] {s : set 𝕜} : strict_convex 𝕜 s ↔ convex 𝕜 s := begin refine ⟨strict_convex.convex, λ hs, strict_convex_iff_open_segment_subset.2 (λ x hx y hy hxy, _)⟩, obtain h | h := hxy.lt_or_lt, { refine (open_segment_subset_Ioo h).trans _, rw ←interior_Icc, exact interior_mono (Icc_subset_segment.trans $ hs.segment_subset hx hy) }, { rw open_segment_symm, refine (open_segment_subset_Ioo h).trans _, rw ←interior_Icc, exact interior_mono (Icc_subset_segment.trans $ hs.segment_subset hy hx) } end lemma strict_convex_iff_ord_connected [linear_ordered_field 𝕜] [topological_space 𝕜] [order_topology 𝕜] {s : set 𝕜} : strict_convex 𝕜 s ↔ s.ord_connected := strict_convex_iff_convex.trans convex_iff_ord_connected alias strict_convex_iff_ord_connected ↔ strict_convex.ord_connected _ end
ceccf90c18cfaccb9da1bbc3eee6ca6d1a2465a6
07c76fbd96ea1786cc6392fa834be62643cea420
/hott/algebra/category/constructions/set.hlean
d3a5d501d5be308c5232ca9e05e046551dbc2cf5
[ "Apache-2.0" ]
permissive
fpvandoorn/lean2
5a430a153b570bf70dc8526d06f18fc000a60ad9
0889cf65b7b3cebfb8831b8731d89c2453dd1e9f
refs/heads/master
1,592,036,508,364
1,545,093,958,000
1,545,093,958,000
75,436,854
0
0
null
1,480,718,780,000
1,480,718,780,000
null
UTF-8
Lean
false
false
3,493
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Jakob von Raumer Category of sets -/ import ..functor.basic ..category types.equiv types.lift open eq category equiv iso is_equiv is_trunc function sigma namespace category definition precategory_Set.{u} [reducible] [constructor] : precategory Set.{u} := precategory.mk (λx y : Set, x → y) (λx y z g f a, g (f a)) (λx a, a) (λx y z w h g f, eq_of_homotopy (λa, idp)) (λx y f, eq_of_homotopy (λa, idp)) (λx y f, eq_of_homotopy (λa, idp)) definition Precategory_Set [reducible] [constructor] : Precategory := Precategory.mk Set precategory_Set abbreviation set [constructor] := Precategory_Set namespace set local attribute is_equiv_subtype_eq [instance] definition iso_of_equiv [constructor] {A B : set} (f : A ≃ B) : A ≅ B := iso.MK (to_fun f) (to_inv f) (eq_of_homotopy (left_inv (to_fun f))) (eq_of_homotopy (right_inv (to_fun f))) definition equiv_of_iso [constructor] {A B : set} (f : A ≅ B) : A ≃ B := begin apply equiv.MK (to_hom f) (iso.to_inv f), exact ap10 (to_right_inverse f), exact ap10 (to_left_inverse f) end definition is_equiv_iso_of_equiv [constructor] (A B : set) : is_equiv (@iso_of_equiv A B) := adjointify _ (λf, equiv_of_iso f) (λf, proof iso_eq idp qed) (λf, equiv_eq' idp) local attribute is_equiv_iso_of_equiv [instance] definition iso_of_eq_eq_compose (A B : Set) : @iso_of_eq _ _ A B ~ @iso_of_equiv A B ∘ @equiv_of_eq A B ∘ subtype_eq_inv _ _ ∘ @ap _ _ (to_fun (trunctype.sigma_char 0)) A B := λp, eq.rec_on p idp definition equiv_equiv_iso (A B : set) : (A ≃ B) ≃ (A ≅ B) := equiv.MK (λf, iso_of_equiv f) (λf, proof equiv.MK (to_hom f) (iso.to_inv f) (ap10 (to_right_inverse f)) (ap10 (to_left_inverse f)) qed) (λf, proof iso_eq idp qed) (λf, proof equiv_eq' idp qed) definition equiv_eq_iso (A B : set) : (A ≃ B) = (A ≅ B) := ua !equiv_equiv_iso definition is_univalent_Set (A B : set) : is_equiv (iso_of_eq : A = B → A ≅ B) := have H₁ : is_equiv (@iso_of_equiv A B ∘ @equiv_of_eq A B ∘ subtype_eq_inv _ _ ∘ @ap _ _ (to_fun (trunctype.sigma_char 0)) A B), from is_equiv_compose _ _ (is_equiv_compose _ _ (is_equiv_compose _ _ _ (@is_equiv_subtype_eq_inv _ _ _ _ _)) !univalence) !is_equiv_iso_of_equiv, is_equiv.homotopy_closed _ (iso_of_eq_eq_compose A B)⁻¹ʰᵗʸ _ end set definition category_Set [instance] [constructor] : category Set := category.mk precategory_Set set.is_univalent_Set definition Category_Set [reducible] [constructor] : Category := Category.mk Set category_Set abbreviation cset [constructor] := Category_Set open functor lift definition functor_lift.{u v} [constructor] : set.{u} ⇒ set.{max u v} := functor.mk tlift (λa b, lift_functor) (λa, eq_of_homotopy (λx, by induction x; reflexivity)) (λa b c g f, eq_of_homotopy (λx, by induction x; reflexivity)) end category
446014fdd56f4c73197d2447db64f6759dda662b
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/calculus/fderiv/basic.lean
de89c70222e5294e8ef013fe08838f054c652308
[ "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
146,067
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.asymptotics.asymptotic_equivalent import analysis.calculus.tangent_cone import analysis.normed_space.bounded_linear_maps /-! # 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 metric open_locale topology classical nnreal filter asymptotics ennreal noncomputable theory section variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] variables {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] variables {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F] variables {G : Type*} [normed_add_comm_group G] [normed_space 𝕜 G] variables {G' : Type*} [normed_add_comm_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 = 𝓝[s] x` (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) := (λ x', f x' - f x - f' (x' - x)) =o[L] (λ x', x' - x) /-- 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 (𝓝[s] x) /-- 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) := (λ p : E × E, f p.1 - f p.2 - f' (p.1 - p.2)) =o[𝓝 (x, x)] (λ p : E × E, p.1 - p.2) 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 (𝓝[s] x), { conv in (𝓝[s] x) { 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 : (λ y, f y - f x - f' (y - x)) =o[𝓝[s] x] (λ y, y - x) := h, have : (λ n, f (x + d n) - f x - f' ((x + d n) - x)) =o[l] (λ n, (x + d n) - x) := this.comp_tendsto tendsto_arg, have : (λ n, f (x + d n) - f x - f' (d n)) =o[l] d := by simpa only [add_sub_cancel'], have : (λ n, c n • (f (x + d n) - f x - f' (d n))) =o[l] (λ n, c n • d n) := (is_O_refl c l).smul_is_o this, have : (λ n, c n • (f (x + d n) - f x - f' (d n))) =o[l] (λ n, (1:ℝ)) := this.trans_is_O (cdlim.is_O_one ℝ), 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 /-- If `f'` and `f₁'` are two derivatives of `f` within `s` at `x`, then they are equal on the tangent cone to `s` at `x` -/ theorem has_fderiv_within_at.unique_on (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at f f₁' s x) : eq_on f' f₁' (tangent_cone_at 𝕜 s x) := λ y ⟨c, d, dtop, clim, cdlim⟩, tendsto_nhds_unique (hf.lim at_top dtop clim cdlim) (hg.lim at_top dtop clim cdlim) /-- `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) (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at f f₁' s x) : f' = f₁' := continuous_linear_map.ext_on H.1 (hf.unique_on hg) 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₁' := (H x hx).eq 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)‖) (𝓝[s] x) (𝓝 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 ↔ (λ h : E, f (x + h) - f x - f' h) =o[𝓝 0] (λh, h) := begin rw [has_fderiv_at, has_fderiv_at_filter, ← map_add_left_nhds_zero x, is_o_map], simp [(∘)] end /-- Converse to the mean value inequality: if `f` is differentiable at `x₀` and `C`-lipschitz on a neighborhood of `x₀` then it its derivative at `x₀` has norm bounded by `C`. This version only assumes that `‖f x - f x₀‖ ≤ C * ‖x - x₀‖` in a neighborhood of `x`. -/ lemma has_fderiv_at.le_of_lip' {f : E → F} {f' : E →L[𝕜] F} {x₀ : E} (hf : has_fderiv_at f f' x₀) {C : ℝ} (hC₀ : 0 ≤ C) (hlip : ∀ᶠ x in 𝓝 x₀, ‖f x - f x₀‖ ≤ C * ‖x - x₀‖) : ‖f'‖ ≤ C := begin refine le_of_forall_pos_le_add (λ ε ε0, op_norm_le_of_nhds_zero _ _), exact add_nonneg hC₀ ε0.le, rw [← map_add_left_nhds_zero x₀, eventually_map] at hlip, filter_upwards [is_o_iff.1 (has_fderiv_at_iff_is_o_nhds_zero.1 hf) ε0, hlip] with y hy hyC, rw add_sub_cancel' at hyC, calc ‖f' y‖ ≤ ‖f (x₀ + y) - f x₀‖ + ‖f (x₀ + y) - f x₀ - f' y‖ : norm_le_insert _ _ ... ≤ C * ‖y‖ + ε * ‖y‖ : add_le_add hyC hy ... = (C + ε) * ‖y‖ : (add_mul _ _ _).symm end /-- Converse to the mean value inequality: if `f` is differentiable at `x₀` and `C`-lipschitz on a neighborhood of `x₀` then it its derivative at `x₀` has norm bounded by `C`. -/ lemma has_fderiv_at.le_of_lip {f : E → F} {f' : E →L[𝕜] F} {x₀ : E} (hf : has_fderiv_at f f' x₀) {s : set E} (hs : s ∈ 𝓝 x₀) {C : ℝ≥0} (hlip : lipschitz_on_with C f s) : ‖f'‖ ≤ C := begin refine hf.le_of_lip' C.coe_nonneg _, filter_upwards [hs] with x hx using hlip.norm_sub_le hx (mem_of_mem_nhds hs), 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_of_mem (h : has_fderiv_within_at f f' t x) (hst : t ∈ 𝓝[s] x) : has_fderiv_within_at f f' s x := h.mono $ nhds_within_le_iff.mpr 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 } alias has_fderiv_within_at_univ ↔ has_fderiv_within_at.has_fderiv_at_of_univ _ lemma has_fderiv_within_at_insert {y : E} {g' : E →L[𝕜] F} : has_fderiv_within_at g g' (insert y s) x ↔ has_fderiv_within_at g g' s x := begin rcases eq_or_ne x y with rfl|h, { simp_rw [has_fderiv_within_at, has_fderiv_at_filter], apply asymptotics.is_o_insert, simp only [sub_self, g'.map_zero] }, refine ⟨λ h, h.mono $ subset_insert y s, λ hg, hg.mono_of_mem _⟩, simp_rw [nhds_within_insert_of_ne h, self_mem_nhds_within] end alias has_fderiv_within_at_insert ↔ has_fderiv_within_at.of_insert has_fderiv_within_at.insert' lemma has_fderiv_within_at.insert {g' : E →L[𝕜] F} (h : has_fderiv_within_at g g' s x) : has_fderiv_within_at g g' (insert x s) x := h.insert' lemma has_strict_fderiv_at.is_O_sub (hf : has_strict_fderiv_at f f' x) : (λ p : E × E, f p.1 - f p.2) =O[𝓝 (x, x)] (λ p : E × E, p.1 - p.2) := 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) : (λ x', f x' - f x) =O[L] (λ x', x' - x) := 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 /-- If `f` is strictly differentiable at `x` with derivative `f'` and `K > ‖f'‖₊`, then `f` is `K`-Lipschitz in a neighborhood of `x`. -/ lemma has_strict_fderiv_at.exists_lipschitz_on_with_of_nnnorm_lt (hf : has_strict_fderiv_at f f' x) (K : ℝ≥0) (hK : ‖f'‖₊ < K) : ∃ s ∈ 𝓝 x, lipschitz_on_with K f s := begin have := hf.add_is_O_with (f'.is_O_with_comp _ _) hK, simp only [sub_add_cancel, is_O_with] at this, rcases exists_nhds_square this with ⟨U, Uo, xU, hU⟩, exact ⟨U, Uo.mem_nhds xU, lipschitz_on_with_iff_norm_sub_le.2 $ λ x hx y hy, hU (mk_mem_prod hx hy)⟩ end /-- If `f` is strictly differentiable at `x` with derivative `f'`, then `f` is Lipschitz in a neighborhood of `x`. See also `has_strict_fderiv_at.exists_lipschitz_on_with_of_nnnorm_lt` for a more precise statement. -/ lemma has_strict_fderiv_at.exists_lipschitz_on_with (hf : has_strict_fderiv_at f f' x) : ∃ K (s ∈ 𝓝 x), lipschitz_on_with K f s := (exists_gt _).imp hf.exists_lipschitz_on_with_of_nnnorm_lt /-- 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 hc _, assume U hU, refine (eventually_ne_of_tendsto_norm_at_top hc (0:𝕜)).mono (λ y hy, _), convert mem_of_mem_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 ∈ 𝓝[s] 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_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.sup ht, end lemma has_fderiv_within_at.nhds_within (h : has_fderiv_within_at f f' s x) (ht : s ∈ 𝓝[t] x) : 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.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_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 differentiable_on.has_fderiv_at (h : differentiable_on 𝕜 f s) (hs : s ∈ 𝓝 x) : has_fderiv_at f (fderiv 𝕜 f x) x := ((h x (mem_of_mem_nhds hs)).differentiable_at hs).has_fderiv_at lemma differentiable_on.differentiable_at (h : differentiable_on 𝕜 f s) (hs : s ∈ 𝓝 x) : differentiable_at 𝕜 f x := (h.has_fderiv_at hs).differentiable_at lemma differentiable_on.eventually_differentiable_at (h : differentiable_on 𝕜 f s) (hs : s ∈ 𝓝 x) : ∀ᶠ y in 𝓝 x, differentiable_at 𝕜 f y := (eventually_eventually_nhds.2 hs).mono $ λ y, h.differentiable_at lemma has_fderiv_at.fderiv (h : has_fderiv_at f f' x) : fderiv 𝕜 f x = f' := by { ext, rw h.unique h.differentiable_at.has_fderiv_at } lemma fderiv_eq {f' : E → E →L[𝕜] F} (h : ∀ x, has_fderiv_at f (f' x) x) : fderiv 𝕜 f = f' := funext $ λ x, (h x).fderiv /-- Converse to the mean value inequality: if `f` is differentiable at `x₀` and `C`-lipschitz on a neighborhood of `x₀` then it its derivative at `x₀` has norm bounded by `C`. Version using `fderiv`. -/ lemma fderiv_at.le_of_lip {f : E → F} {x₀ : E} (hf : differentiable_at 𝕜 f x₀) {s : set E} (hs : s ∈ 𝓝 x₀) {C : ℝ≥0} (hlip : lipschitz_on_with C f s) : ‖fderiv 𝕜 f x₀‖ ≤ C := hf.has_fderiv_at.le_of_lip hs hlip 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 only [mem_closure_iff_nhds_within_ne_bot, ne_bot_iff, ne.def, not_not] 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.mono_of_mem (h : differentiable_within_at 𝕜 f s x) {t : set E} (hst : s ∈ nhds_within x t) : differentiable_within_at 𝕜 f t x := (h.has_fderiv_within_at.mono_of_mem hst).differentiable_within_at 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 ∈ 𝓝[s] 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.antimono (h : differentiable_within_at 𝕜 f s x) (hst : s ⊆ t) (hx : s ∈ 𝓝[t] x) : differentiable_within_at 𝕜 f t x := by rwa [← differentiable_within_at_inter' hx, inter_eq_self_of_subset_right hst] lemma has_fderiv_within_at.antimono (h : has_fderiv_within_at f f' s x) (hst : s ⊆ t) (hs : unique_diff_within_at 𝕜 s x) (hx : s ∈ 𝓝[t] x) : has_fderiv_within_at f f' t x := begin have h' : has_fderiv_within_at f _ t x := (h.differentiable_within_at.antimono hst hx).has_fderiv_within_at, rwa hs.eq h (h'.mono hst), end 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_at.fderiv_within (h : differentiable_at 𝕜 f x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = fderiv 𝕜 f x := h.has_fderiv_at.has_fderiv_within_at.fderiv_within hxs 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 only [differentiable_on, differentiable, differentiable_within_at_univ, mem_univ, forall_true_left] 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 (is_open.mem_nhds 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 lemma fderiv_within_subset' (st : s ⊆ t) (ht : unique_diff_within_at 𝕜 s x) (hx : s ∈ 𝓝[t] x) (h : differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 f s x = fderiv_within 𝕜 f t x := fderiv_within_subset st ht (h.antimono st hx) @[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, { 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, { rwa ←differentiable_within_at_inter ht }, rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at this] } end lemma fderiv_within_of_mem_nhds (h : s ∈ 𝓝 x) : fderiv_within 𝕜 f s x = fderiv 𝕜 f x := begin have : s = univ ∩ s, by simp only [univ_inter], rw [this, ← fderiv_within_univ], exact fderiv_within_inter h (unique_diff_on_univ _ (mem_univ _)) end lemma fderiv_within_of_open (hs : is_open s) (hx : x ∈ s) : fderiv_within 𝕜 f s x = fderiv 𝕜 f x := fderiv_within_of_mem_nhds (is_open.mem_nhds hs hx) lemma fderiv_within_eq_fderiv (hs : unique_diff_within_at 𝕜 s x) (h : differentiable_at 𝕜 f x) : fderiv_within 𝕜 f s x = fderiv 𝕜 f x := begin rw ← fderiv_within_univ, exact fderiv_within_subset (subset_univ _) hs h.differentiable_within_at end lemma fderiv_mem_iff {f : E → F} {s : set (E →L[𝕜] F)} {x : E} : fderiv 𝕜 f x ∈ s ↔ (differentiable_at 𝕜 f x ∧ fderiv 𝕜 f x ∈ s) ∨ (¬differentiable_at 𝕜 f x ∧ (0 : E →L[𝕜] F) ∈ s) := by by_cases hx : differentiable_at 𝕜 f x; simp [fderiv_zero_of_not_differentiable_at, *] lemma fderiv_within_mem_iff {f : E → F} {t : set E} {s : set (E →L[𝕜] F)} {x : E} : fderiv_within 𝕜 f t x ∈ s ↔ (differentiable_within_at 𝕜 f t x ∧ fderiv_within 𝕜 f t x ∈ s) ∨ (¬differentiable_within_at 𝕜 f t x ∧ (0 : E →L[𝕜] F) ∈ s) := by by_cases hx : differentiable_within_at 𝕜 f t x; simp [fderiv_within_zero_of_not_differentiable_within_at, *] lemma asymptotics.is_O.has_fderiv_within_at {s : set E} {x₀ : E} {n : ℕ} (h : f =O[𝓝[s] x₀] λ x, ‖x - x₀‖^n) (hx₀ : x₀ ∈ s) (hn : 1 < n) : has_fderiv_within_at f (0 : E →L[𝕜] F) s x₀ := by simp_rw [has_fderiv_within_at, has_fderiv_at_filter, h.eq_zero_of_norm_pow_within hx₀ $ zero_lt_one.trans hn, zero_apply, sub_zero, h.trans_is_o ((is_o_pow_sub_sub x₀ hn).mono nhds_within_le_nhds)] lemma asymptotics.is_O.has_fderiv_at {x₀ : E} {n : ℕ} (h : f =O[𝓝 x₀] λ x, ‖x - x₀‖^n) (hn : 1 < n) : has_fderiv_at f (0 : E →L[𝕜] F) x₀ := begin rw [← nhds_within_univ] at h, exact (h.has_fderiv_within_at (mem_univ _) hn).has_fderiv_at_of_univ end lemma has_fderiv_within_at.is_O {f : E → F} {s : set E} {x₀ : E} {f' : E →L[𝕜] F} (h : has_fderiv_within_at f f' s x₀) : (λ x, f x - f x₀) =O[𝓝[s] x₀] λ x, x - x₀ := by simpa only [sub_add_cancel] using h.is_O.add (is_O_sub f' (𝓝[s] x₀) x₀) lemma has_fderiv_at.is_O {f : E → F} {x₀ : E} {f' : E →L[𝕜] F} (h : has_fderiv_at f f' x₀) : (λ x, f x - f x₀) =O[𝓝 x₀] λ x, x - x₀ := by simpa only [sub_add_cancel] using h.is_O.add (is_O_sub f' (𝓝 x₀) x₀) 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.mono_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 only [sub_add_cancel, eq_self_iff_true, forall_const]) 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_rfl 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) : (λ p : E × E, p.1 - p.2) =O[𝓝 (x, x)](λ p : E × E, f p.1 - f p.2) := ((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 (hf : has_fderiv_at_filter f f' x L) {C} (hf' : antilipschitz_with C f') : (λ x', x' - x) =O[L] (λ x', f x' - f x) := have (λ x', x' - x) =O[L] (λ x', f' (x' - x)), from is_O_iff.2 ⟨C, eventually_of_forall $ λ x', add_monoid_hom_class.bound_of_antilipschitz f' hf' _⟩, (this.trans (hf.trans_is_O this).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 theorem filter.eventually_eq.has_fderiv_at_iff (h : f₀ =ᶠ[𝓝 x] f₁) : has_fderiv_at f₀ f' x ↔ has_fderiv_at f₁ f' x := h.has_fderiv_at_filter_iff h.eq_of_nhds (λ _, rfl) theorem filter.eventually_eq.differentiable_at_iff (h : f₀ =ᶠ[𝓝 x] f₁) : differentiable_at 𝕜 f₀ x ↔ differentiable_at 𝕜 f₁ x := exists_congr $ λ f', h.has_fderiv_at_iff theorem filter.eventually_eq.has_fderiv_within_at_iff (h : f₀ =ᶠ[𝓝[s] x] f₁) (hx : f₀ x = f₁ x) : has_fderiv_within_at f₀ f' s x ↔ has_fderiv_within_at f₁ f' s x := h.has_fderiv_at_filter_iff hx (λ _, rfl) theorem filter.eventually_eq.has_fderiv_within_at_iff_of_mem (h : f₀ =ᶠ[𝓝[s] x] f₁) (hx : x ∈ s) : has_fderiv_within_at f₀ f' s x ↔ has_fderiv_within_at f₁ f' s x := h.has_fderiv_within_at_iff (h.eq_of_nhds_within hx) theorem filter.eventually_eq.differentiable_within_at_iff (h : f₀ =ᶠ[𝓝[s] x] f₁) (hx : f₀ x = f₁ x) : differentiable_within_at 𝕜 f₀ s x ↔ differentiable_within_at 𝕜 f₁ s x := exists_congr $ λ f', h.has_fderiv_within_at_iff hx theorem filter.eventually_eq.differentiable_within_at_iff_of_mem (h : f₀ =ᶠ[𝓝[s] x] f₁) (hx : x ∈ s) : differentiable_within_at 𝕜 f₀ s x ↔ differentiable_within_at 𝕜 f₁ s x := h.differentiable_within_at_iff (h.eq_of_nhds_within hx) 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_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' (h : has_fderiv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x) (hx : x ∈ s) : has_fderiv_within_at f₁ f' s x := h.congr hs (hs x hx) lemma has_fderiv_within_at.congr_of_eventually_eq (h : has_fderiv_within_at f f' s x) (h₁ : f₁ =ᶠ[𝓝[s] x] 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_mem_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₁ =ᶠ[𝓝[s] x] 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 := hL.differentiable_at_iff.2 h 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₁ =ᶠ[𝓝[s] x] 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 filter.eventually_eq.fderiv_within_eq_nhds (hs : unique_diff_within_at 𝕜 s x) (hL : f₁ =ᶠ[𝓝 x] f) : fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x := (show f₁ =ᶠ[𝓝[s] x] f, from nhds_within_le_nhds hL).fderiv_within_eq hs (mem_of_mem_nhds hL : _) 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_of_superset self_mem_nhds_within, exact hL end lemma fderiv_within_congr' (hs : unique_diff_within_at 𝕜 s x) (hL : ∀ y ∈ s, f₁ y = f y) (hx : x ∈ s) : fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x := fderiv_within_congr hs hL (hL x hx) lemma filter.eventually_eq.fderiv_eq (hL : f₁ =ᶠ[𝓝 x] f) : fderiv 𝕜 f₁ x = fderiv 𝕜 f x := begin have A : f₁ x = f x := hL.eq_of_nhds, 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 protected lemma filter.eventually_eq.fderiv (h : f₁ =ᶠ[𝓝 x] f) : fderiv 𝕜 f₁ =ᶠ[𝓝 x] fderiv 𝕜 f := h.eventually_eq_nhds.mono $ λ x h, h.fderiv_eq 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) @[simp] lemma fderiv_id' : fderiv 𝕜 (λ (x : E), x) x = continuous_linear_map.id 𝕜 E := fderiv_id 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 lemma fderiv_within_id' (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λ (x : E), x) s x = continuous_linear_map.id 𝕜 E := fderiv_within_id hxs 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) @[simp] 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 lemma has_fderiv_within_at_singleton (f : E → F) (x : E) : has_fderiv_within_at f (0 : E →L[𝕜] F) {x} x := by simp only [has_fderiv_within_at, nhds_within_singleton, has_fderiv_at_filter, is_o_pure, continuous_linear_map.zero_apply, sub_self] lemma has_fderiv_at_of_subsingleton [h : subsingleton E] (f : E → F) (x : E) : has_fderiv_at f (0 : E →L[𝕜] F) x := begin rw [← has_fderiv_within_at_univ, subsingleton_univ.eq_singleton_of_mem (mem_univ x)], exact has_fderiv_within_at_singleton f x end lemma differentiable_on_empty : differentiable_on 𝕜 f ∅ := λ x, false.elim lemma differentiable_on_singleton : differentiable_on 𝕜 f {x} := forall_eq.2 (has_fderiv_within_at_singleton f x).differentiable_within_at lemma set.subsingleton.differentiable_on (hs : s.subsingleton) : differentiable_on 𝕜 f s := hs.induction_on differentiable_on_empty (λ x, differentiable_on_singleton) lemma has_fderiv_at_zero_of_eventually_const (c : F) (hf : f =ᶠ[𝓝 x] (λ y, c)) : has_fderiv_at f (0 : E →L[𝕜] F) x := (has_fderiv_at_const _ _).congr_of_eventually_eq hf 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 @[simp] 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} {L' : filter F} (hg : has_fderiv_at_filter g g' (f x) L') (hf : has_fderiv_at_filter f f' x L) (hL : tendsto f L 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 hL).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 := calc (λ x', g (f x') - g (f x) - g' (f x' - f x)) =o[L] (λ x', f x' - f x) : hg.comp_tendsto le_rfl ... =O[L] (λ x', x' - x) : hf.is_O_sub, refine this.triangle _, calc (λ x' : E, g' (f x' - f x) - g'.comp f' (x' - x)) =ᶠ[L] λ x', g' (f x' - f x - f' (x' - x)) : eventually_of_forall (λ x', by simp) ... =O[L] λ x', f x' - f x - f' (x' - x) : g'.is_O_comp _ _ ... =o[L] λ x', x' - x : hf 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 : maps_to f s t) : has_fderiv_within_at (g ∘ f) (g'.comp f') s x := hg.comp x hf $ hf.continuous_within_at.tendsto_nhds_within hst 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 := hg.comp x hf hf.continuous_within_at theorem has_fderiv_within_at.comp_of_mem {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 : tendsto f (𝓝[s] x) (𝓝[t] f x)) : has_fderiv_within_at (g ∘ f) (g'.comp f') s x := has_fderiv_at_filter.comp x hg hf hst /-- 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.comp x hf hf.continuous_at 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 : maps_to f s t) : differentiable_within_at 𝕜 (g ∘ f) s x := (hg.has_fderiv_within_at.comp x hf.has_fderiv_within_at h).differentiable_within_at 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 := hg.differentiable_within_at.comp x hf (maps_to_univ _ _) 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) := (hg.has_fderiv_within_at.comp x (hf.has_fderiv_within_at) h).fderiv_within hxs /-- A version of `fderiv_within.comp` that is useful to rewrite the composition of two derivatives into a single derivative. This version always applies, but creates a new side-goal `f x = y`. -/ lemma fderiv_within_fderiv_within {g : F → G} {f : E → F} {x : E} {y : F} {s : set E} {t : set F} (hg : differentiable_within_at 𝕜 g t y) (hf : differentiable_within_at 𝕜 f s x) (h : maps_to f s t) (hxs : unique_diff_within_at 𝕜 s x) (hy : f x = y) (v : E) : fderiv_within 𝕜 g t y (fderiv_within 𝕜 f s x v) = fderiv_within 𝕜 (g ∘ f) s x v := by { subst y, rw [fderiv_within.comp x hg hf h hxs], refl } /-- Ternary version of `fderiv_within.comp`, with equality assumptions of basepoints added, in order to apply more easily as a rewrite from right-to-left. -/ lemma fderiv_within.comp₃ {g' : G → G'} {g : F → G} {t : set F} {u : set G} {y : F} {y' : G} (hg' : differentiable_within_at 𝕜 g' u y') (hg : differentiable_within_at 𝕜 g t y) (hf : differentiable_within_at 𝕜 f s x) (h2g : maps_to g t u) (h2f : maps_to f s t) (h3g : g y = y') (h3f : f x = y) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (g' ∘ g ∘ f) s x = (fderiv_within 𝕜 g' u y').comp ((fderiv_within 𝕜 g t y).comp (fderiv_within 𝕜 f s x)) := begin substs h3g h3f, exact (hg'.has_fderiv_within_at.comp x (hg.has_fderiv_within_at.comp x (hf.has_fderiv_within_at) h2f) $ h2g.comp h2f).fderiv_within hxs 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) := (hg.has_fderiv_at.comp x hf.has_fderiv_at).fderiv 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) := (hg.has_fderiv_at.comp_has_fderiv_within_at x hf.has_fderiv_within_at).fderiv_within hxs lemma differentiable_on.comp {g : F → G} {t : set F} (hg : differentiable_on 𝕜 g t) (hf : differentiable_on 𝕜 f s) (st : maps_to f s 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 := hg.differentiable_on.comp hf (maps_to_univ _ _) /-- 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 }, { rw [function.iterate_succ, pow_succ'], rw ← hx at ihn, exact ihn.comp x hf 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_principal_principal.2 hs).mono_left inf_le_right] 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 }, { rw [function.iterate_succ, pow_succ'], rw ← hx at ihn, exact ihn.comp x hf } end protected lemma differentiable_at.iterate {f : E → E} (hf : differentiable_at 𝕜 f x) (hx : f x = x) (n : ℕ) : differentiable_at 𝕜 (f^[n]) x := (hf.has_fderiv_at.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 := (hf.has_fderiv_within_at.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)) (f₁'.prod 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)) (f₁'.prod 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)) (f₁'.prod 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)) (f₁'.prod f₂') x := hf₁.prod hf₂ lemma has_fderiv_at_prod_mk_left (e₀ : E) (f₀ : F) : has_fderiv_at (λ e : E, (e, f₀)) (inl 𝕜 E F) e₀ := (has_fderiv_at_id e₀).prod (has_fderiv_at_const f₀ e₀) lemma has_fderiv_at_prod_mk_right (e₀ : E) (f₀ : F) : has_fderiv_at (λ f : F, (e₀, f)) (inr 𝕜 E F) f₀ := (has_fderiv_at_const e₀ f₀).prod (has_fderiv_at_id f₀) 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 = (fderiv 𝕜 f₁ x).prod (fderiv 𝕜 f₂ x) := (hf₁.has_fderiv_at.prod hf₂.has_fderiv_at).fderiv 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 = (fderiv_within 𝕜 f₁ s x).prod (fderiv_within 𝕜 f₂ s x) := (hf₁.has_fderiv_within_at.prod hf₂.has_fderiv_within_at).fderiv_within hxs 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 E F) (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 E F) (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 tendsto_map lemma has_fderiv_at_fst : has_fderiv_at (@prod.fst E F) (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 E F) (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 E F) (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 E F) (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 tendsto_map lemma has_fderiv_at_snd : has_fderiv_at (@prod.snd E F) (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 E F) (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) 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 (prod.map f f₂) (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 (prod.map f f₂) (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 variables {R : Type*} [semiring R] [module R F] [smul_comm_class 𝕜 R F] [has_continuous_const_smul R F] /-! ### Derivative of a function multiplied by a constant -/ theorem has_strict_fderiv_at.const_smul (h : has_strict_fderiv_at f f' x) (c : R) : 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 : R) : has_fderiv_at_filter (λ x, c • f x) (c • f') x L := (c • (1 : F →L[𝕜] F)).has_fderiv_at_filter.comp x h tendsto_map theorem has_fderiv_within_at.const_smul (h : has_fderiv_within_at f f' s x) (c : R) : 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 : R) : 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 : R) : 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 : R) : 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 : R) : differentiable_on 𝕜 (λy, c • f y) s := λx hx, (h x hx).const_smul c lemma differentiable.const_smul (h : differentiable 𝕜 f) (c : R) : 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 : R) : 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 : R) : 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 only [linear_map.sub_apply, linear_map.add_apply, map_sub, map_add, add_apply], 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 only [linear_map.sub_apply, linear_map.add_apply, map_sub, map_add, add_apply], 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 @[simp] lemma differentiable_within_at_add_const_iff (c : F) : differentiable_within_at 𝕜 (λ y, f y + c) s x ↔ differentiable_within_at 𝕜 f s x := ⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩ 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 @[simp] lemma differentiable_at_add_const_iff (c : F) : differentiable_at 𝕜 (λ y, f y + c) x ↔ differentiable_at 𝕜 f x := ⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩ 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 @[simp] lemma differentiable_on_add_const_iff (c : F) : differentiable_on 𝕜 (λ y, f y + c) s ↔ differentiable_on 𝕜 f s := ⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩ lemma differentiable.add_const (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, f y + c) := λx, (hf x).add_const c @[simp] lemma differentiable_add_const_iff (c : F) : differentiable 𝕜 (λ y, f y + c) ↔ differentiable 𝕜 f := ⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩ lemma fderiv_within_add_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) : fderiv_within 𝕜 (λy, f y + c) s x = fderiv_within 𝕜 f s x := if hf : differentiable_within_at 𝕜 f s x then (hf.has_fderiv_within_at.add_const c).fderiv_within hxs else by { rw [fderiv_within_zero_of_not_differentiable_within_at hf, fderiv_within_zero_of_not_differentiable_within_at], simpa } lemma fderiv_add_const (c : F) : fderiv 𝕜 (λy, f y + c) x = fderiv 𝕜 f x := by simp only [← fderiv_within_univ, fderiv_within_add_const unique_diff_within_at_univ] 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 @[simp] lemma differentiable_within_at_const_add_iff (c : F) : differentiable_within_at 𝕜 (λ y, c + f y) s x ↔ differentiable_within_at 𝕜 f s x := ⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩ 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 @[simp] lemma differentiable_at_const_add_iff (c : F) : differentiable_at 𝕜 (λ y, c + f y) x ↔ differentiable_at 𝕜 f x := ⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩ 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 @[simp] lemma differentiable_on_const_add_iff (c : F) : differentiable_on 𝕜 (λ y, c + f y) s ↔ differentiable_on 𝕜 f s := ⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩ lemma differentiable.const_add (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, c + f y) := λx, (hf x).const_add c @[simp] lemma differentiable_const_add_iff (c : F) : differentiable 𝕜 (λ y, c + f y) ↔ differentiable 𝕜 f := ⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩ lemma fderiv_within_const_add (hxs : unique_diff_within_at 𝕜 s x) (c : F) : fderiv_within 𝕜 (λy, c + f y) s x = fderiv_within 𝕜 f s x := by simpa only [add_comm] using fderiv_within_add_const hxs c lemma fderiv_const_add (c : F) : fderiv 𝕜 (λy, c + f y) x = fderiv 𝕜 f x := by simp only [add_comm c, fderiv_add_const] 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 pi /-! ### Derivatives of functions `f : E → Π i, F' i` In this section we formulate `has_*fderiv*_pi` theorems as `iff`s, and provide two versions of each theorem: * the version without `'` deals with `φ : Π i, E → F' i` and `φ' : Π i, E →L[𝕜] F' i` and is designed to deduce differentiability of `λ x i, φ i x` from differentiability of each `φ i`; * the version with `'` deals with `Φ : E → Π i, F' i` and `Φ' : E →L[𝕜] Π i, F' i` and is designed to deduce differentiability of the components `λ x, Φ x i` from differentiability of `Φ`. -/ variables {ι : Type*} [fintype ι] {F' : ι → Type*} [Π i, normed_add_comm_group (F' i)] [Π i, normed_space 𝕜 (F' i)] {φ : Π i, E → F' i} {φ' : Π i, E →L[𝕜] F' i} {Φ : E → Π i, F' i} {Φ' : E →L[𝕜] Π i, F' i} @[simp] lemma has_strict_fderiv_at_pi' : has_strict_fderiv_at Φ Φ' x ↔ ∀ i, has_strict_fderiv_at (λ x, Φ x i) ((proj i).comp Φ') x := begin simp only [has_strict_fderiv_at, continuous_linear_map.coe_pi], exact is_o_pi end @[simp] lemma has_strict_fderiv_at_pi : has_strict_fderiv_at (λ x i, φ i x) (continuous_linear_map.pi φ') x ↔ ∀ i, has_strict_fderiv_at (φ i) (φ' i) x := has_strict_fderiv_at_pi' @[simp] lemma has_fderiv_at_filter_pi' : has_fderiv_at_filter Φ Φ' x L ↔ ∀ i, has_fderiv_at_filter (λ x, Φ x i) ((proj i).comp Φ') x L := begin simp only [has_fderiv_at_filter, continuous_linear_map.coe_pi], exact is_o_pi end lemma has_fderiv_at_filter_pi : has_fderiv_at_filter (λ x i, φ i x) (continuous_linear_map.pi φ') x L ↔ ∀ i, has_fderiv_at_filter (φ i) (φ' i) x L := has_fderiv_at_filter_pi' @[simp] lemma has_fderiv_at_pi' : has_fderiv_at Φ Φ' x ↔ ∀ i, has_fderiv_at (λ x, Φ x i) ((proj i).comp Φ') x := has_fderiv_at_filter_pi' lemma has_fderiv_at_pi : has_fderiv_at (λ x i, φ i x) (continuous_linear_map.pi φ') x ↔ ∀ i, has_fderiv_at (φ i) (φ' i) x := has_fderiv_at_filter_pi @[simp] lemma has_fderiv_within_at_pi' : has_fderiv_within_at Φ Φ' s x ↔ ∀ i, has_fderiv_within_at (λ x, Φ x i) ((proj i).comp Φ') s x := has_fderiv_at_filter_pi' lemma has_fderiv_within_at_pi : has_fderiv_within_at (λ x i, φ i x) (continuous_linear_map.pi φ') s x ↔ ∀ i, has_fderiv_within_at (φ i) (φ' i) s x := has_fderiv_at_filter_pi @[simp] lemma differentiable_within_at_pi : differentiable_within_at 𝕜 Φ s x ↔ ∀ i, differentiable_within_at 𝕜 (λ x, Φ x i) s x := ⟨λ h i, (has_fderiv_within_at_pi'.1 h.has_fderiv_within_at i).differentiable_within_at, λ h, (has_fderiv_within_at_pi.2 (λ i, (h i).has_fderiv_within_at)).differentiable_within_at⟩ @[simp] lemma differentiable_at_pi : differentiable_at 𝕜 Φ x ↔ ∀ i, differentiable_at 𝕜 (λ x, Φ x i) x := ⟨λ h i, (has_fderiv_at_pi'.1 h.has_fderiv_at i).differentiable_at, λ h, (has_fderiv_at_pi.2 (λ i, (h i).has_fderiv_at)).differentiable_at⟩ lemma differentiable_on_pi : differentiable_on 𝕜 Φ s ↔ ∀ i, differentiable_on 𝕜 (λ x, Φ x i) s := ⟨λ h i x hx, differentiable_within_at_pi.1 (h x hx) i, λ h x hx, differentiable_within_at_pi.2 (λ i, h i x hx)⟩ lemma differentiable_pi : differentiable 𝕜 Φ ↔ ∀ i, differentiable 𝕜 (λ x, Φ x i) := ⟨λ h i x, differentiable_at_pi.1 (h x) i, λ h x, differentiable_at_pi.2 (λ i, h i x)⟩ -- TODO: find out which version (`φ` or `Φ`) works better with `rw`/`simp` lemma fderiv_within_pi (h : ∀ i, differentiable_within_at 𝕜 (φ i) s x) (hs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λ x i, φ i x) s x = pi (λ i, fderiv_within 𝕜 (φ i) s x) := (has_fderiv_within_at_pi.2 (λ i, (h i).has_fderiv_within_at)).fderiv_within hs lemma fderiv_pi (h : ∀ i, differentiable_at 𝕜 (φ i) x) : fderiv 𝕜 (λ x i, φ i x) x = pi (λ i, fderiv 𝕜 (φ i) x) := (has_fderiv_at_pi.2 (λ i, (h i).has_fderiv_at)).fderiv end pi 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 tendsto_map 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_within_at_neg_iff : differentiable_within_at 𝕜 (λy, -f y) s x ↔ differentiable_within_at 𝕜 f s x := ⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩ lemma differentiable_at.neg (h : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (λy, -f y) x := h.has_fderiv_at.neg.differentiable_at @[simp] lemma differentiable_at_neg_iff : differentiable_at 𝕜 (λy, -f y) x ↔ differentiable_at 𝕜 f x := ⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩ lemma differentiable_on.neg (h : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (λy, -f y) s := λx hx, (h x hx).neg @[simp] lemma differentiable_on_neg_iff : differentiable_on 𝕜 (λy, -f y) s ↔ differentiable_on 𝕜 f s := ⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩ lemma differentiable.neg (h : differentiable 𝕜 f) : differentiable 𝕜 (λy, -f y) := λx, (h x).neg @[simp] lemma differentiable_neg_iff : differentiable 𝕜 (λy, -f y) ↔ differentiable 𝕜 f := ⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩ lemma fderiv_within_neg (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λy, -f y) s x = - fderiv_within 𝕜 f s x := if h : differentiable_within_at 𝕜 f s x then h.has_fderiv_within_at.neg.fderiv_within hxs else by { rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at, neg_zero], simpa } @[simp] lemma fderiv_neg : fderiv 𝕜 (λy, -f y) x = - fderiv 𝕜 f x := by simp only [← fderiv_within_univ, fderiv_within_neg unique_diff_within_at_univ] 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 := by simpa only [sub_eq_add_neg] using 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 := by simpa only [sub_eq_add_neg] using 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 := by simpa only [sub_eq_add_neg] using 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 := by simpa only [sub_eq_add_neg] using 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 @[simp] lemma differentiable_within_at_sub_const_iff (c : F) : differentiable_within_at 𝕜 (λ y, f y - c) s x ↔ differentiable_within_at 𝕜 f s x := by simp only [sub_eq_add_neg, differentiable_within_at_add_const_iff] 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 @[simp] lemma differentiable_at_sub_const_iff (c : F) : differentiable_at 𝕜 (λ y, f y - c) x ↔ differentiable_at 𝕜 f x := by simp only [sub_eq_add_neg, differentiable_at_add_const_iff] 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 @[simp] lemma differentiable_on_sub_const_iff (c : F) : differentiable_on 𝕜 (λ y, f y - c) s ↔ differentiable_on 𝕜 f s := by simp only [sub_eq_add_neg, differentiable_on_add_const_iff] lemma differentiable.sub_const (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, f y - c) := λx, (hf x).sub_const c @[simp] lemma differentiable_sub_const_iff (c : F) : differentiable 𝕜 (λ y, f y - c) ↔ differentiable 𝕜 f := by simp only [sub_eq_add_neg, differentiable_add_const_iff] lemma fderiv_within_sub_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) : fderiv_within 𝕜 (λy, f y - c) s x = fderiv_within 𝕜 f s x := by simp only [sub_eq_add_neg, fderiv_within_add_const hxs] lemma fderiv_sub_const (c : F) : fderiv 𝕜 (λy, f y - c) x = fderiv 𝕜 f x := by simp only [sub_eq_add_neg, fderiv_add_const] 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 := by simpa only [sub_eq_add_neg] using 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 := by simpa only [sub_eq_add_neg] using 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 @[simp] lemma differentiable_within_at_const_sub_iff (c : F) : differentiable_within_at 𝕜 (λ y, c - f y) s x ↔ differentiable_within_at 𝕜 f s x := by simp [sub_eq_add_neg] 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 @[simp] lemma differentiable_at_const_sub_iff (c : F) : differentiable_at 𝕜 (λ y, c - f y) x ↔ differentiable_at 𝕜 f x := by simp [sub_eq_add_neg] 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 @[simp] lemma differentiable_on_const_sub_iff (c : F) : differentiable_on 𝕜 (λ y, c - f y) s ↔ differentiable_on 𝕜 f s := by simp [sub_eq_add_neg] lemma differentiable.const_sub (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, c - f y) := λx, (hf x).const_sub c @[simp] lemma differentiable_const_sub_iff (c : F) : differentiable 𝕜 (λ y, c - f y) ↔ differentiable 𝕜 f := by simp [sub_eq_add_neg] lemma fderiv_within_const_sub (hxs : unique_diff_within_at 𝕜 s x) (c : F) : fderiv_within 𝕜 (λy, c - f y) s x = -fderiv_within 𝕜 f s x := by simp only [sub_eq_add_neg, fderiv_within_const_add, fderiv_within_neg, hxs] lemma fderiv_const_sub (c : F) : fderiv 𝕜 (λy, c - f y) x = -fderiv 𝕜 f x := by simp only [← fderiv_within_univ, fderiv_within_const_sub unique_diff_within_at_univ] 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 : (λ q : T, b (q.1 - q.2)) =o[𝓝 (p, p)] (λ q : T, ‖q.1 - q.2‖ * 1), { 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 (λ q : T, h.deriv (p - q.2) (q.1 - q.2)) =o[𝓝 (p, p)] (λ q : T, q.1 - q.2), { 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 : (λ q : T, p - q.2) =o[𝓝 (p, p)] (λ q, (1:ℝ)), 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 variable (B : E →L[𝕜] F →L[𝕜] G) lemma continuous_linear_map.has_fderiv_within_at_of_bilinear {f : G' → E} {g : G' → F} {f' : G' →L[𝕜] E} {g' : G' →L[𝕜] F} {x : G'} {s : set G'} (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) : has_fderiv_within_at (λ y, B (f y) (g y)) (B.precompR G' (f x) g' + B.precompL G' f' (g x)) s x := (B.is_bounded_bilinear_map.has_fderiv_at (f x, g x)).comp_has_fderiv_within_at x (hf.prod hg) lemma continuous_linear_map.has_fderiv_at_of_bilinear {f : G' → E} {g : G' → F} {f' : G' →L[𝕜] E} {g' : G' →L[𝕜] F} {x : G'} (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) : has_fderiv_at (λ y, B (f y) (g y)) (B.precompR G' (f x) g' + B.precompL G' f' (g x)) x := (B.is_bounded_bilinear_map.has_fderiv_at (f x, g x)).comp x (hf.prod hg) lemma continuous_linear_map.fderiv_within_of_bilinear {f : G' → E} {g : G' → F} {x : G'} {s : set G'} (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) (hs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λ y, B (f y) (g y)) s x = (B.precompR G' (f x) (fderiv_within 𝕜 g s x) + B.precompL G' (fderiv_within 𝕜 f s x) (g x)) := (B.has_fderiv_within_at_of_bilinear hf.has_fderiv_within_at hg.has_fderiv_within_at).fderiv_within hs lemma continuous_linear_map.fderiv_of_bilinear {f : G' → E} {g : G' → F} {x : G'} (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : fderiv 𝕜 (λ y, B (f y) (g y)) x = (B.precompR G' (f x) (fderiv 𝕜 g x) + B.precompL G' (fderiv 𝕜 f x) (g x)) := (B.has_fderiv_at_of_bilinear hf.has_fderiv_at hg.has_fderiv_at).fderiv end bilinear_map section clm_comp_apply /-! ### Derivative of the pointwise composition/application of continuous linear maps -/ variables {H : Type*} [normed_add_comm_group H] [normed_space 𝕜 H] {c : E → G →L[𝕜] H} {c' : E →L[𝕜] G →L[𝕜] H} {d : E → F →L[𝕜] G} {d' : E →L[𝕜] F →L[𝕜] G} {u : E → G} {u' : E →L[𝕜] G} lemma has_strict_fderiv_at.clm_comp (hc : has_strict_fderiv_at c c' x) (hd : has_strict_fderiv_at d d' x) : has_strict_fderiv_at (λ y, (c y).comp (d y)) ((compL 𝕜 F G H (c x)).comp d' + ((compL 𝕜 F G H).flip (d x)).comp c') x := (is_bounded_bilinear_map_comp.has_strict_fderiv_at (c x, d x)).comp x $ hc.prod hd lemma has_fderiv_within_at.clm_comp (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).comp (d y)) ((compL 𝕜 F G H (c x)).comp d' + ((compL 𝕜 F G H).flip (d x)).comp c') s x := (is_bounded_bilinear_map_comp.has_fderiv_at (c x, d x)).comp_has_fderiv_within_at x $ hc.prod hd lemma has_fderiv_at.clm_comp (hc : has_fderiv_at c c' x) (hd : has_fderiv_at d d' x) : has_fderiv_at (λ y, (c y).comp (d y)) ((compL 𝕜 F G H (c x)).comp d' + ((compL 𝕜 F G H).flip (d x)).comp c') x := (is_bounded_bilinear_map_comp.has_fderiv_at (c x, d x)).comp x $ hc.prod hd lemma differentiable_within_at.clm_comp (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : differentiable_within_at 𝕜 (λ y, (c y).comp (d y)) s x := (hc.has_fderiv_within_at.clm_comp hd.has_fderiv_within_at).differentiable_within_at lemma differentiable_at.clm_comp (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : differentiable_at 𝕜 (λ y, (c y).comp (d y)) x := (hc.has_fderiv_at.clm_comp hd.has_fderiv_at).differentiable_at lemma differentiable_on.clm_comp (hc : differentiable_on 𝕜 c s) (hd : differentiable_on 𝕜 d s) : differentiable_on 𝕜 (λ y, (c y).comp (d y)) s := λx hx, (hc x hx).clm_comp (hd x hx) lemma differentiable.clm_comp (hc : differentiable 𝕜 c) (hd : differentiable 𝕜 d) : differentiable 𝕜 (λ y, (c y).comp (d y)) := λx, (hc x).clm_comp (hd x) lemma fderiv_within_clm_comp (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).comp (d y)) s x = (compL 𝕜 F G H (c x)).comp (fderiv_within 𝕜 d s x) + ((compL 𝕜 F G H).flip (d x)).comp (fderiv_within 𝕜 c s x) := (hc.has_fderiv_within_at.clm_comp hd.has_fderiv_within_at).fderiv_within hxs lemma fderiv_clm_comp (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : fderiv 𝕜 (λ y, (c y).comp (d y)) x = (compL 𝕜 F G H (c x)).comp (fderiv 𝕜 d x) + ((compL 𝕜 F G H).flip (d x)).comp (fderiv 𝕜 c x) := (hc.has_fderiv_at.clm_comp hd.has_fderiv_at).fderiv lemma has_strict_fderiv_at.clm_apply (hc : has_strict_fderiv_at c c' x) (hu : has_strict_fderiv_at u u' x) : has_strict_fderiv_at (λ y, (c y) (u y)) ((c x).comp u' + c'.flip (u x)) x := (is_bounded_bilinear_map_apply.has_strict_fderiv_at (c x, u x)).comp x (hc.prod hu) lemma has_fderiv_within_at.clm_apply (hc : has_fderiv_within_at c c' s x) (hu : has_fderiv_within_at u u' s x) : has_fderiv_within_at (λ y, (c y) (u y)) ((c x).comp u' + c'.flip (u x)) s x := (is_bounded_bilinear_map_apply.has_fderiv_at (c x, u x)).comp_has_fderiv_within_at x (hc.prod hu) lemma has_fderiv_at.clm_apply (hc : has_fderiv_at c c' x) (hu : has_fderiv_at u u' x) : has_fderiv_at (λ y, (c y) (u y)) ((c x).comp u' + c'.flip (u x)) x := (is_bounded_bilinear_map_apply.has_fderiv_at (c x, u x)).comp x (hc.prod hu) lemma differentiable_within_at.clm_apply (hc : differentiable_within_at 𝕜 c s x) (hu : differentiable_within_at 𝕜 u s x) : differentiable_within_at 𝕜 (λ y, (c y) (u y)) s x := (hc.has_fderiv_within_at.clm_apply hu.has_fderiv_within_at).differentiable_within_at lemma differentiable_at.clm_apply (hc : differentiable_at 𝕜 c x) (hu : differentiable_at 𝕜 u x) : differentiable_at 𝕜 (λ y, (c y) (u y)) x := (hc.has_fderiv_at.clm_apply hu.has_fderiv_at).differentiable_at lemma differentiable_on.clm_apply (hc : differentiable_on 𝕜 c s) (hu : differentiable_on 𝕜 u s) : differentiable_on 𝕜 (λ y, (c y) (u y)) s := λx hx, (hc x hx).clm_apply (hu x hx) lemma differentiable.clm_apply (hc : differentiable 𝕜 c) (hu : differentiable 𝕜 u) : differentiable 𝕜 (λ y, (c y) (u y)) := λx, (hc x).clm_apply (hu x) lemma fderiv_within_clm_apply (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hu : differentiable_within_at 𝕜 u s x) : fderiv_within 𝕜 (λ y, (c y) (u y)) s x = ((c x).comp (fderiv_within 𝕜 u s x) + (fderiv_within 𝕜 c s x).flip (u x)) := (hc.has_fderiv_within_at.clm_apply hu.has_fderiv_within_at).fderiv_within hxs lemma fderiv_clm_apply (hc : differentiable_at 𝕜 c x) (hu : differentiable_at 𝕜 u x) : fderiv 𝕜 (λ y, (c y) (u y)) x = ((c x).comp (fderiv 𝕜 u x) + (fderiv 𝕜 c x).flip (u x)) := (hc.has_fderiv_at.clm_apply hu.has_fderiv_at).fderiv end clm_comp_apply section smul /-! ### Derivative of the product of a scalar-valued function and a vector-valued function If `c` is a differentiable scalar-valued function and `f` is a differentiable vector-valued function, then `λ x, c x • f x` is differentiable as well. Lemmas in this section works for function `c` taking values in the base field, as well as in a normed algebra over the base field: e.g., they work for `c : E → ℂ` and `f : E → F` provided that `F` is a complex normed vector space. -/ variables {𝕜' : Type*} [nontrivially_normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] [normed_space 𝕜' F] [is_scalar_tower 𝕜 𝕜' F] 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 functions -/ variables {𝔸 𝔸' : Type*} [normed_ring 𝔸] [normed_comm_ring 𝔸'] [normed_algebra 𝕜 𝔸] [normed_algebra 𝕜 𝔸'] {a b : E → 𝔸} {a' b' : E →L[𝕜] 𝔸} {c d : E → 𝔸'} {c' d' : E →L[𝕜] 𝔸'} theorem has_strict_fderiv_at.mul' {x : E} (ha : has_strict_fderiv_at a a' x) (hb : has_strict_fderiv_at b b' x) : has_strict_fderiv_at (λ y, a y * b y) (a x • b' + a'.smul_right (b x)) x := ((continuous_linear_map.mul 𝕜 𝔸).is_bounded_bilinear_map.has_strict_fderiv_at (a x, b x)).comp x (ha.prod hb) 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.mul' hd, ext z, apply mul_comm } theorem has_fderiv_within_at.mul' (ha : has_fderiv_within_at a a' s x) (hb : has_fderiv_within_at b b' s x) : has_fderiv_within_at (λ y, a y * b y) (a x • b' + a'.smul_right (b x)) s x := ((continuous_linear_map.mul 𝕜 𝔸).is_bounded_bilinear_map.has_fderiv_at (a x, b x)).comp_has_fderiv_within_at x (ha.prod hb) 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.mul' hd, ext z, apply mul_comm } theorem has_fderiv_at.mul' (ha : has_fderiv_at a a' x) (hb : has_fderiv_at b b' x) : has_fderiv_at (λ y, a y * b y) (a x • b' + a'.smul_right (b x)) x := ((continuous_linear_map.mul 𝕜 𝔸).is_bounded_bilinear_map.has_fderiv_at (a x, b x)).comp x (ha.prod hb) 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.mul' hd, ext z, apply mul_comm } lemma differentiable_within_at.mul (ha : differentiable_within_at 𝕜 a s x) (hb : differentiable_within_at 𝕜 b s x) : differentiable_within_at 𝕜 (λ y, a y * b y) s x := (ha.has_fderiv_within_at.mul' hb.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.mul (ha : differentiable_at 𝕜 a x) (hb : differentiable_at 𝕜 b x) : differentiable_at 𝕜 (λ y, a y * b y) x := (ha.has_fderiv_at.mul' hb.has_fderiv_at).differentiable_at lemma differentiable_on.mul (ha : differentiable_on 𝕜 a s) (hb : differentiable_on 𝕜 b s) : differentiable_on 𝕜 (λ y, a y * b y) s := λx hx, (ha x hx).mul (hb x hx) @[simp] lemma differentiable.mul (ha : differentiable 𝕜 a) (hb : differentiable 𝕜 b) : differentiable 𝕜 (λ y, a y * b y) := λx, (ha x).mul (hb x) lemma differentiable_within_at.pow (ha : differentiable_within_at 𝕜 a s x) : ∀ n : ℕ, differentiable_within_at 𝕜 (λ x, a x ^ n) s x | 0 := by simp only [pow_zero, differentiable_within_at_const] | (n + 1) := by simp only [pow_succ, differentiable_within_at.pow n, ha.mul] @[simp] lemma differentiable_at.pow (ha : differentiable_at 𝕜 a x) (n : ℕ) : differentiable_at 𝕜 (λ x, a x ^ n) x := differentiable_within_at_univ.mp $ ha.differentiable_within_at.pow n lemma differentiable_on.pow (ha : differentiable_on 𝕜 a s) (n : ℕ) : differentiable_on 𝕜 (λ x, a x ^ n) s := λ x h, (ha x h).pow n @[simp] lemma differentiable.pow (ha : differentiable 𝕜 a) (n : ℕ) : differentiable 𝕜 (λ x, a x ^ n) := λx, (ha x).pow n lemma fderiv_within_mul' (hxs : unique_diff_within_at 𝕜 s x) (ha : differentiable_within_at 𝕜 a s x) (hb : differentiable_within_at 𝕜 b s x) : fderiv_within 𝕜 (λ y, a y * b y) s x = a x • fderiv_within 𝕜 b s x + (fderiv_within 𝕜 a s x).smul_right (b x) := (ha.has_fderiv_within_at.mul' hb.has_fderiv_within_at).fderiv_within hxs 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' (ha : differentiable_at 𝕜 a x) (hb : differentiable_at 𝕜 b x) : fderiv 𝕜 (λ y, a y * b y) x = a x • fderiv 𝕜 b x + (fderiv 𝕜 a x).smul_right (b x) := (ha.has_fderiv_at.mul' hb.has_fderiv_at).fderiv 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' (ha : has_strict_fderiv_at a a' x) (b : 𝔸) : has_strict_fderiv_at (λ y, a y * b) (a'.smul_right b) x := (((continuous_linear_map.mul 𝕜 𝔸).flip b).has_strict_fderiv_at).comp x ha 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 { convert hc.mul_const' d, ext z, apply mul_comm } theorem has_fderiv_within_at.mul_const' (ha : has_fderiv_within_at a a' s x) (b : 𝔸) : has_fderiv_within_at (λ y, a y * b) (a'.smul_right b) s x := (((continuous_linear_map.mul 𝕜 𝔸).flip b).has_fderiv_at).comp_has_fderiv_within_at x ha 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 { convert hc.mul_const' d, ext z, apply mul_comm } theorem has_fderiv_at.mul_const' (ha : has_fderiv_at a a' x) (b : 𝔸) : has_fderiv_at (λ y, a y * b) (a'.smul_right b) x := (((continuous_linear_map.mul 𝕜 𝔸).flip b).has_fderiv_at).comp x ha theorem has_fderiv_at.mul_const (hc : has_fderiv_at c c' x) (d : 𝔸') : has_fderiv_at (λ y, c y * d) (d • c') x := by { convert hc.mul_const' d, ext z, apply mul_comm } lemma differentiable_within_at.mul_const (ha : differentiable_within_at 𝕜 a s x) (b : 𝔸) : differentiable_within_at 𝕜 (λ y, a y * b) s x := (ha.has_fderiv_within_at.mul_const' b).differentiable_within_at lemma differentiable_at.mul_const (ha : differentiable_at 𝕜 a x) (b : 𝔸) : differentiable_at 𝕜 (λ y, a y * b) x := (ha.has_fderiv_at.mul_const' b).differentiable_at lemma differentiable_on.mul_const (ha : differentiable_on 𝕜 a s) (b : 𝔸) : differentiable_on 𝕜 (λ y, a y * b) s := λx hx, (ha x hx).mul_const b lemma differentiable.mul_const (ha : differentiable 𝕜 a) (b : 𝔸) : differentiable 𝕜 (λ y, a y * b) := λx, (ha x).mul_const b lemma fderiv_within_mul_const' (hxs : unique_diff_within_at 𝕜 s x) (ha : differentiable_within_at 𝕜 a s x) (b : 𝔸) : fderiv_within 𝕜 (λ y, a y * b) s x = (fderiv_within 𝕜 a s x).smul_right b := (ha.has_fderiv_within_at.mul_const' b).fderiv_within hxs 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' (ha : differentiable_at 𝕜 a x) (b : 𝔸) : fderiv 𝕜 (λ y, a y * b) x = (fderiv 𝕜 a x).smul_right b := (ha.has_fderiv_at.mul_const' b).fderiv 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 (ha : has_strict_fderiv_at a a' x) (b : 𝔸) : has_strict_fderiv_at (λ y, b * a y) (b • a') x := (((continuous_linear_map.mul 𝕜 𝔸) b).has_strict_fderiv_at).comp x ha theorem has_fderiv_within_at.const_mul (ha : has_fderiv_within_at a a' s x) (b : 𝔸) : has_fderiv_within_at (λ y, b * a y) (b • a') s x := (((continuous_linear_map.mul 𝕜 𝔸) b).has_fderiv_at).comp_has_fderiv_within_at x ha theorem has_fderiv_at.const_mul (ha : has_fderiv_at a a' x) (b : 𝔸) : has_fderiv_at (λ y, b * a y) (b • a') x := (((continuous_linear_map.mul 𝕜 𝔸) b).has_fderiv_at).comp x ha lemma differentiable_within_at.const_mul (ha : differentiable_within_at 𝕜 a s x) (b : 𝔸) : differentiable_within_at 𝕜 (λ y, b * a y) s x := (ha.has_fderiv_within_at.const_mul b).differentiable_within_at lemma differentiable_at.const_mul (ha : differentiable_at 𝕜 a x) (b : 𝔸) : differentiable_at 𝕜 (λ y, b * a y) x := (ha.has_fderiv_at.const_mul b).differentiable_at lemma differentiable_on.const_mul (ha : differentiable_on 𝕜 a s) (b : 𝔸) : differentiable_on 𝕜 (λ y, b * a y) s := λx hx, (ha x hx).const_mul b lemma differentiable.const_mul (ha : differentiable 𝕜 a) (b : 𝔸) : differentiable 𝕜 (λ y, b * a y) := λx, (ha x).const_mul b lemma fderiv_within_const_mul (hxs : unique_diff_within_at 𝕜 s x) (ha : differentiable_within_at 𝕜 a s x) (b : 𝔸) : fderiv_within 𝕜 (λ y, b * a y) s x = b • fderiv_within 𝕜 a s x := (ha.has_fderiv_within_at.const_mul b).fderiv_within hxs lemma fderiv_const_mul (ha : differentiable_at 𝕜 a x) (b : 𝔸) : fderiv 𝕜 (λ y, b * a y) x = b • fderiv 𝕜 a x := (ha.has_fderiv_at.const_mul b).fderiv end mul section algebra_inverse variables {R : Type*} [normed_ring R] [normed_algebra 𝕜 R] [complete_space R] open normed_ring continuous_linear_map ring /-- At an invertible element `x` of a normed algebra `R`, the Fréchet derivative of the inversion operation is the linear map `λ t, - x⁻¹ * t * x⁻¹`. -/ lemma has_fderiv_at_ring_inverse (x : Rˣ) : has_fderiv_at ring.inverse (-mul_left_right 𝕜 R ↑x⁻¹ ↑x⁻¹) x := begin have h_is_o : (λ (t : R), inverse (↑x + t) - ↑x⁻¹ + ↑x⁻¹ * t * ↑x⁻¹) =o[𝓝 0] (λ (t : R), t), { refine (inverse_add_norm_diff_second_order x).trans_is_o ((is_o_norm_norm).mp _), simp only [norm_pow, norm_norm], have h12 : 1 < 2 := by norm_num, convert (asymptotics.is_o_pow_pow h12).comp_tendsto tendsto_norm_zero, ext, simp }, have h_lim : tendsto (λ (y:R), y - x) (𝓝 x) (𝓝 0), { refine tendsto_zero_iff_norm_tendsto_zero.mpr _, exact tendsto_iff_norm_tendsto_zero.mp tendsto_id }, simp only [has_fderiv_at, has_fderiv_at_filter], convert h_is_o.comp_tendsto h_lim, ext y, simp only [coe_comp', function.comp_app, mul_left_right_apply, neg_apply, inverse_unit x, units.inv_mul, add_sub_cancel'_right, mul_sub, sub_mul, one_mul, sub_neg_eq_add] end lemma differentiable_at_inverse (x : Rˣ) : differentiable_at 𝕜 (@ring.inverse R _) x := (has_fderiv_at_ring_inverse x).differentiable_at lemma fderiv_inverse (x : Rˣ) : fderiv 𝕜 (@ring.inverse R _) x = - mul_left_right 𝕜 R ↑x⁻¹ ↑x⁻¹ := (has_fderiv_at_ring_inverse x).fderiv end algebra_inverse namespace continuous_linear_equiv /-! ### Differentiability of linear equivs, and invariance of differentiability -/ variable (iso : E ≃L[𝕜] F) protected lemma 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 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 has_fderiv_at : has_fderiv_at iso (iso : E →L[𝕜] F) x := iso.to_continuous_linear_map.has_fderiv_at_filter protected lemma differentiable_at : differentiable_at 𝕜 iso x := iso.has_fderiv_at.differentiable_at protected lemma differentiable_within_at : differentiable_within_at 𝕜 iso s x := iso.differentiable_at.differentiable_within_at protected lemma fderiv : fderiv 𝕜 iso x = iso := iso.has_fderiv_at.fderiv protected lemma 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 differentiable : differentiable 𝕜 iso := λx, iso.differentiable_at protected lemma differentiable_on : differentiable_on 𝕜 iso s := iso.differentiable.differentiable_on lemma 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 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 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 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 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 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 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 simp_rw [← has_fderiv_within_at_univ, iso.comp_has_fderiv_within_at_iff] lemma 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 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 simp_rw [← has_fderiv_within_at_univ, iso.comp_has_fderiv_within_at_iff'] lemma 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 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 lemma comp_right_differentiable_within_at_iff {f : F → G} {s : set F} {x : E} : differentiable_within_at 𝕜 (f ∘ iso) (iso ⁻¹' s) x ↔ differentiable_within_at 𝕜 f s (iso x) := begin refine ⟨λ H, _, λ H, H.comp x iso.differentiable_within_at (maps_to_preimage _ s)⟩, have : differentiable_within_at 𝕜 ((f ∘ iso) ∘ iso.symm) s (iso x), { rw ← iso.symm_apply_apply x at H, apply H.comp (iso x) iso.symm.differentiable_within_at, assume y hy, simpa only [mem_preimage, apply_symm_apply] using hy }, rwa [function.comp.assoc, iso.self_comp_symm] at this, end lemma comp_right_differentiable_at_iff {f : F → G} {x : E} : differentiable_at 𝕜 (f ∘ iso) x ↔ differentiable_at 𝕜 f (iso x) := by simp only [← differentiable_within_at_univ, ← iso.comp_right_differentiable_within_at_iff, preimage_univ] lemma comp_right_differentiable_on_iff {f : F → G} {s : set F} : differentiable_on 𝕜 (f ∘ iso) (iso ⁻¹' s) ↔ differentiable_on 𝕜 f s := begin refine ⟨λ H y hy, _, λ H y hy, iso.comp_right_differentiable_within_at_iff.2 (H _ hy)⟩, rw [← iso.apply_symm_apply y, ← comp_right_differentiable_within_at_iff], apply H, simpa only [mem_preimage, apply_symm_apply] using hy, end lemma comp_right_differentiable_iff {f : F → G} : differentiable 𝕜 (f ∘ iso) ↔ differentiable 𝕜 f := by simp only [← differentiable_on_univ, ← iso.comp_right_differentiable_on_iff, preimage_univ] lemma comp_right_has_fderiv_within_at_iff {f : F → G} {s : set F} {x : E} {f' : F →L[𝕜] G} : has_fderiv_within_at (f ∘ iso) (f'.comp (iso : E →L[𝕜] F)) (iso ⁻¹' s) x ↔ has_fderiv_within_at f f' s (iso x) := begin refine ⟨λ H, _, λ H, H.comp x iso.has_fderiv_within_at (maps_to_preimage _ s)⟩, rw [← iso.symm_apply_apply x] at H, have A : f = (f ∘ iso) ∘ iso.symm, by { rw [function.comp.assoc, iso.self_comp_symm], refl }, have B : f' = (f'.comp (iso : E →L[𝕜] F)).comp (iso.symm : F →L[𝕜] E), by rw [continuous_linear_map.comp_assoc, iso.coe_comp_coe_symm, continuous_linear_map.comp_id], rw [A, B], apply H.comp (iso x) iso.symm.has_fderiv_within_at, assume y hy, simpa only [mem_preimage, apply_symm_apply] using hy end lemma comp_right_has_fderiv_at_iff {f : F → G} {x : E} {f' : F →L[𝕜] G} : has_fderiv_at (f ∘ iso) (f'.comp (iso : E →L[𝕜] F)) x ↔ has_fderiv_at f f' (iso x) := by simp only [← has_fderiv_within_at_univ, ← comp_right_has_fderiv_within_at_iff, preimage_univ] lemma comp_right_has_fderiv_within_at_iff' {f : F → G} {s : set F} {x : E} {f' : E →L[𝕜] G} : has_fderiv_within_at (f ∘ iso) f' (iso ⁻¹' s) x ↔ has_fderiv_within_at f (f'.comp (iso.symm : F →L[𝕜] E)) s (iso x) := by rw [← iso.comp_right_has_fderiv_within_at_iff, continuous_linear_map.comp_assoc, iso.coe_symm_comp_coe, continuous_linear_map.comp_id] lemma comp_right_has_fderiv_at_iff' {f : F → G} {x : E} {f' : E →L[𝕜] G} : has_fderiv_at (f ∘ iso) f' x ↔ has_fderiv_at f (f'.comp (iso.symm : F →L[𝕜] E)) (iso x) := by simp only [← has_fderiv_within_at_univ, ← iso.comp_right_has_fderiv_within_at_iff', preimage_univ] lemma comp_right_fderiv_within {f : F → G} {s : set F} {x : E} (hxs : unique_diff_within_at 𝕜 (iso ⁻¹' s) x) : fderiv_within 𝕜 (f ∘ iso) (iso ⁻¹'s) x = (fderiv_within 𝕜 f s (iso x)).comp (iso : E →L[𝕜] F) := begin by_cases h : differentiable_within_at 𝕜 f s (iso x), { exact (iso.comp_right_has_fderiv_within_at_iff.2 (h.has_fderiv_within_at)).fderiv_within hxs }, { have : ¬ differentiable_within_at 𝕜 (f ∘ iso) (iso ⁻¹' s) x, { assume h', exact h (iso.comp_right_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.zero_comp] } end lemma comp_right_fderiv {f : F → G} {x : E} : fderiv 𝕜 (f ∘ iso) x = (fderiv 𝕜 f (iso x)).comp (iso : E →L[𝕜] F) := begin rw [← fderiv_within_univ, ← fderiv_within_univ, ← iso.comp_right_fderiv_within, preimage_univ], exact unique_diff_within_at_univ, end end continuous_linear_equiv namespace linear_isometry_equiv /-! ### Differentiability of linear isometry equivs, and invariance of differentiability -/ variable (iso : E ≃ₗᵢ[𝕜] F) protected lemma has_strict_fderiv_at : has_strict_fderiv_at iso (iso : E →L[𝕜] F) x := (iso : E ≃L[𝕜] F).has_strict_fderiv_at protected lemma has_fderiv_within_at : has_fderiv_within_at iso (iso : E →L[𝕜] F) s x := (iso : E ≃L[𝕜] F).has_fderiv_within_at protected lemma has_fderiv_at : has_fderiv_at iso (iso : E →L[𝕜] F) x := (iso : E ≃L[𝕜] F).has_fderiv_at protected lemma differentiable_at : differentiable_at 𝕜 iso x := iso.has_fderiv_at.differentiable_at protected lemma differentiable_within_at : differentiable_within_at 𝕜 iso s x := iso.differentiable_at.differentiable_within_at protected lemma fderiv : fderiv 𝕜 iso x = iso := iso.has_fderiv_at.fderiv protected lemma fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 iso s x = iso := (iso : E ≃L[𝕜] F).fderiv_within hxs protected lemma differentiable : differentiable 𝕜 iso := λx, iso.differentiable_at protected lemma differentiable_on : differentiable_on 𝕜 iso s := iso.differentiable.differentiable_on lemma 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 := (iso : E ≃L[𝕜] F).comp_differentiable_within_at_iff lemma comp_differentiable_at_iff {f : G → E} {x : G} : differentiable_at 𝕜 (iso ∘ f) x ↔ differentiable_at 𝕜 f x := (iso : E ≃L[𝕜] F).comp_differentiable_at_iff lemma comp_differentiable_on_iff {f : G → E} {s : set G} : differentiable_on 𝕜 (iso ∘ f) s ↔ differentiable_on 𝕜 f s := (iso : E ≃L[𝕜] F).comp_differentiable_on_iff lemma comp_differentiable_iff {f : G → E} : differentiable 𝕜 (iso ∘ f) ↔ differentiable 𝕜 f := (iso : E ≃L[𝕜] F).comp_differentiable_iff lemma 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 := (iso : E ≃L[𝕜] F).comp_has_fderiv_within_at_iff lemma 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 := (iso : E ≃L[𝕜] F).comp_has_strict_fderiv_at_iff lemma 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 := (iso : E ≃L[𝕜] F).comp_has_fderiv_at_iff lemma 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 := (iso : E ≃L[𝕜] F).comp_has_fderiv_within_at_iff' lemma 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 := (iso : E ≃L[𝕜] F).comp_has_fderiv_at_iff' lemma 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) := (iso : E ≃L[𝕜] F).comp_fderiv_within hxs lemma comp_fderiv {f : G → E} {x : G} : fderiv 𝕜 (iso ∘ f) x = (iso : E →L[𝕜] F).comp (fderiv 𝕜 f x) := (iso : E ≃L[𝕜] F).comp_fderiv end linear_isometry_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 : (λ p : F × F, g p.1 - g p.2 - f'.symm (p.1 - p.2)) =O[𝓝 (a, a)] (λ p : F × F, f' (g p.1 - g p.2) - (p.1 - p.2)), { 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 : (λ x : F, g x - g a - f'.symm (x - a)) =O[𝓝 a] (λ x : F, f' (g x - g a) - (x - 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 f'.antilipschitz).comp_tendsto hg).congr' (eventually_of_forall $ λ _, rfl) (hfg.mono _), rintros p hp, simp only [(∘), hp, hfg.self_of_nhds] } end /-- If `f` is a local homeomorphism defined on a neighbourhood of `f.symm a`, and `f` has an invertible derivative `f'` in the sense of strict differentiability at `f.symm a`, then `f.symm` 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. -/ lemma local_homeomorph.has_strict_fderiv_at_symm (f : local_homeomorph E F) {f' : E ≃L[𝕜] F} {a : F} (ha : a ∈ f.target) (htff' : has_strict_fderiv_at f (f' : E →L[𝕜] F) (f.symm a)) : has_strict_fderiv_at f.symm (f'.symm : F →L[𝕜] E) a := htff'.of_local_left_inverse (f.symm.continuous_at ha) (f.eventually_right_inverse ha) /-- If `f` is a local homeomorphism defined on a neighbourhood of `f.symm a`, and `f` has an invertible derivative `f'` at `f.symm a`, then `f.symm` 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. -/ lemma local_homeomorph.has_fderiv_at_symm (f : local_homeomorph E F) {f' : E ≃L[𝕜] F} {a : F} (ha : a ∈ f.target) (htff' : has_fderiv_at f (f' : E →L[𝕜] F) (f.symm a)) : has_fderiv_at f.symm (f'.symm : F →L[𝕜] E) a := htff'.of_local_left_inverse (f.symm.continuous_at ha) (f.eventually_right_inverse ha) lemma has_fderiv_within_at.eventually_ne (h : has_fderiv_within_at f f' s x) (hf' : ∃ C, ∀ z, ‖z‖ ≤ C * ‖f' z‖) : ∀ᶠ z in 𝓝[s \ {x}] x, f z ≠ f x := begin rw [nhds_within, diff_eq, ← inf_principal, ← inf_assoc, eventually_inf_principal], have A : (λ z, z - x) =O[𝓝[s] x] (λ z, f' (z - x)) := (is_O_iff.2 $ hf'.imp $ λ C hC, eventually_of_forall $ λ z, hC _), have : (λ z, f z - f x) ~[𝓝[s] x] (λ z, f' (z - x)) := h.trans_is_O A, simpa [not_imp_not, sub_eq_zero] using (A.trans this.is_O_symm).eq_zero_imp end lemma has_fderiv_at.eventually_ne (h : has_fderiv_at f f' x) (hf' : ∃ C, ∀ z, ‖z‖ ≤ C * ‖f' z‖) : ∀ᶠ z in 𝓝[≠] x, f z ≠ f x := by simpa only [compl_eq_univ_diff] using (has_fderiv_within_at_univ.2 h).eventually_ne hf' 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_add_comm_group E] [normed_space ℝ E] variables {F : Type*} [normed_add_comm_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, 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*} [nontrivially_normed_field 𝕜] {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] {F : Type*} [normed_add_comm_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_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' : dense_range f') : unique_diff_within_at 𝕜 (f '' s) (f x) := begin refine ⟨h'.dense_of_maps_to f'.continuous hs.1 _, h.continuous_within_at.mem_closure_image hs.2⟩, show submodule.span 𝕜 (tangent_cone_at 𝕜 s x) ≤ (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x))).comap f', rw [submodule.span_le], exact h.maps_to_tangent_cone.mono (subset.refl _) submodule.subset_span end lemma unique_diff_on.image {f' : E → E →L[𝕜] F} (hs : unique_diff_on 𝕜 s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hd : ∀ x ∈ s, dense_range (f' x)) : unique_diff_on 𝕜 (f '' s) := ball_image_iff.2 $ λ x hx, (hf' x hx).unique_diff_within_at (hs x hx) (hd x hx) 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) := h.unique_diff_within_at hs e'.surjective.dense_range lemma continuous_linear_equiv.unique_diff_on_image (e : E ≃L[𝕜] F) (h : unique_diff_on 𝕜 s) : unique_diff_on 𝕜 (e '' s) := h.image (λ x _, e.has_fderiv_within_at) (λ x hx, e.surjective.dense_range) @[simp] lemma continuous_linear_equiv.unique_diff_on_image_iff (e : E ≃L[𝕜] F) : unique_diff_on 𝕜 (e '' s) ↔ unique_diff_on 𝕜 s := ⟨λ h, e.symm_image_image s ▸ e.symm.unique_diff_on_image h, e.unique_diff_on_image⟩ @[simp] lemma continuous_linear_equiv.unique_diff_on_preimage_iff (e : F ≃L[𝕜] E) : unique_diff_on 𝕜 (e ⁻¹' s) ↔ unique_diff_on 𝕜 s := by rw [← e.image_symm_eq_preimage, e.symm.unique_diff_on_image_iff] 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*) [nontrivially_normed_field 𝕜] variables {𝕜' : Type*} [nontrivially_normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] variables {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] [normed_space 𝕜' E] variables [is_scalar_tower 𝕜 𝕜' E] variables {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F] [normed_space 𝕜' F] variables [is_scalar_tower 𝕜 𝕜' F] variables {f : E → F} {f' : E →L[𝕜'] F} {s : set E} {x : E} 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_filter.restrict_scalars {L} (h : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter f (f'.restrict_scalars 𝕜) x L := 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 𝕜 lemma has_fderiv_within_at_of_restrict_scalars {g' : E →L[𝕜] F} (h : has_fderiv_within_at f g' s x) (H : f'.restrict_scalars 𝕜 = g') : has_fderiv_within_at f f' s x := by { rw ← H at h, exact h } lemma has_fderiv_at_of_restrict_scalars {g' : E →L[𝕜] F} (h : has_fderiv_at f g' x) (H : f'.restrict_scalars 𝕜 = g') : has_fderiv_at f f' x := by { rw ← H at h, exact h } lemma differentiable_at.fderiv_restrict_scalars (h : differentiable_at 𝕜' f x) : fderiv 𝕜 f x = (fderiv 𝕜' f x).restrict_scalars 𝕜 := (h.has_fderiv_at.restrict_scalars 𝕜).fderiv lemma differentiable_within_at_iff_restrict_scalars (hf : differentiable_within_at 𝕜 f s x) (hs : unique_diff_within_at 𝕜 s x) : differentiable_within_at 𝕜' f s x ↔ ∃ (g' : E →L[𝕜'] F), g'.restrict_scalars 𝕜 = fderiv_within 𝕜 f s x := begin split, { rintros ⟨g', hg'⟩, exact ⟨g', hs.eq (hg'.restrict_scalars 𝕜) hf.has_fderiv_within_at⟩, }, { rintros ⟨f', hf'⟩, exact ⟨f', has_fderiv_within_at_of_restrict_scalars 𝕜 hf.has_fderiv_within_at hf'⟩, }, end lemma differentiable_at_iff_restrict_scalars (hf : differentiable_at 𝕜 f x) : differentiable_at 𝕜' f x ↔ ∃ (g' : E →L[𝕜'] F), g'.restrict_scalars 𝕜 = fderiv 𝕜 f x := begin rw [← differentiable_within_at_univ, ← fderiv_within_univ], exact differentiable_within_at_iff_restrict_scalars 𝕜 hf.differentiable_within_at unique_diff_within_at_univ, end end restrict_scalars /-! ### Support of derivatives -/ section support open function variables (𝕜 : Type*) {E F : Type*} [nontrivially_normed_field 𝕜] [normed_add_comm_group E] [normed_space 𝕜 E] [normed_add_comm_group F] [normed_space 𝕜 F] {f : E → F} lemma support_fderiv_subset : support (fderiv 𝕜 f) ⊆ tsupport f := begin intros x, rw [← not_imp_not], intro h2x, rw [not_mem_tsupport_iff_eventually_eq] at h2x, exact nmem_support.mpr (h2x.fderiv_eq.trans $ fderiv_const_apply 0), end lemma has_compact_support.fderiv (hf : has_compact_support f) : has_compact_support (fderiv 𝕜 f) := hf.mono' $ support_fderiv_subset 𝕜 end support
50755b59f700b09fa80a1538b533bb48d48258ee
ec5a7ae10c533e1b1f4b0bc7713e91ecf829a3eb
/ijcar16/examples/example2.lean
8dda0b456c8445d60272ff953bf6cc3bd7ec9ce0
[ "MIT" ]
permissive
leanprover/leanprover.github.io
cf248934af7c7e9aeff17cf8df3c12c5e7e73f1a
071a20d2e059a2c3733e004c681d3949cac3c07a
refs/heads/master
1,692,621,047,417
1,691,396,994,000
1,691,396,994,000
19,366,263
18
27
MIT
1,693,989,071,000
1,399,006,345,000
Lean
UTF-8
Lean
false
false
4,289
lean
import data.real open real namespace example2 /- Assume we have an exp (exponential) function, and state basic properties using axioms. -/ constant exp : ℝ → ℝ /- The annotation (: t :) is used to indicate that `t` is a pattern for the E-matching procedure. -/ axiom exp_add : ∀ x y : ℝ, (: exp (x + y) :) = exp x * exp y /- The [forward] attribute instructs lean to use the following axioms for E-matching. -/ attribute [forward] exp_add /- Define t² as notation for t*t -/ definition sq (x : ℝ) := x * x notation a `²` := sq a /- (sq x) and (x * x) are equal by definition, and we can prove it using reflexivity. -/ lemma sq_def [forward] : ∀ x : ℝ, sq x = x * x := take x, rfl lemma sq_add [forward] : ∀ x y : ℝ, sq (x + y) = (: sq x + 2 * x * y + sq y :) := take x y, by unfold sq; rewrite add_mul_self_eq /- Define predicate pos and state basic properties using axioms. -/ definition pos (x : ℝ) := x > 0 axiom pos_1 : pos (1:ℝ) axiom pos_bit1 : ∀ x : ℝ, pos x → pos (bit1 x) axiom pos_bit0 : ∀ x : ℝ, pos x → pos (bit0 x) axiom pos_sq : ∀ x : ℝ, pos x → pos (sq x) axiom pos_add : ∀ x y : ℝ, pos x → pos y → (: pos (x + y) :) axiom pos_mul : ∀ x y : ℝ, pos x → pos y → (: pos (x * y) :) axiom pos_exp : ∀ x : ℝ, pos (exp x) /- The [intro!] attribute instructs lean to use the following axioms for backward chaining. -/ attribute [intro!] pos_bit1 pos_bit0 pos_1 pos_add pos_mul pos_sq pos_exp attribute [forward] pos_add pos_mul /- Define predicate nzero and state basic properties using axioms. -/ definition nzero (x : ℝ) := x ≠ 0 axiom nzero_of_pos : ∀ x : ℝ, pos x → nzero x axiom nzero_of_neg : ∀ x : ℝ, pos x → nzero (- x) attribute [intro!] nzero_of_pos nzero_of_neg /- Assume we have safe_log and safe_inv functions. -/ constant safe_log : Π (x : ℝ), pos x → ℝ constant safe_inv : Π (x : ℝ), nzero x → ℝ /- Define notation (log x), (x ⁻¹) and (x / y) for safe_log and safe_inv. We discharge the preconditions pos and nzero using tactics. The grind tactic is based on backward chaining, and uses all axioms/lemmas marked with the `[intro!]` attribute. -/ notation `log`:max x:max := (@safe_log x (by grind)) /- We use priority greater than the default to avoid a conflict with existing notation defined in Lean. -/ notation [priority std.priority.default+1] x ⁻¹ := (@safe_inv x (by grind)) notation [priority std.priority.default+1] x `/` y := (@safe_inv y (by grind) * x) /- Assume basic properties about safe_inf and safe_log as axioms -/ axiom inv_pos : ∀ x : ℝ, pos x → pos (x⁻¹) axiom inv_mul : ∀ x y : ℝ, pos x → pos y → (x * y)⁻¹ = (x⁻¹) * (y⁻¹) axiom inv_cancel_left : ∀ x y : ℝ, pos x → x⁻¹ * (x * y) = y axiom inv_neg : ∀ x : ℝ, pos x → (- x)⁻¹ = - (x⁻¹) attribute [intro!] inv_pos attribute [forward] inv_pos inv_mul inv_cancel_left inv_neg axiom log_mul : ∀ x y : ℝ, pos x → pos y → log (x * y) = log x + log y axiom log_sq : ∀ x : ℝ, pos x → log (sq x) = 2 * log x axiom log_inv : ∀ x : ℝ, pos x → log (x⁻¹) = - log x attribute [forward] log_mul log_sq log_inv /- To prove the main lemma, we also need the following basic properties from the standard library. -/ lemma rdistrib [forward] : ∀ x y z : ℝ, (x + y) * z = x * z + y * z := right_distrib lemma addcomm [forward] : ∀ x y : ℝ, x + y = y + x := add.comm lemma sub_def [forward] : ∀ x y : ℝ, x - y = x + -y := take x y, rfl lemma mul_two_sum [forward] : ∀ x : ℝ, (: 2 * x :) = x + x := take x, show (1 + 1) * x = x + x, by rewrite [rdistrib, one_mul] lemma neg_mul [forward] : ∀ x y : ℝ, (: (- x) * y :) = - (x * y) := take x y, by rewrite neg_mul_eq_neg_mul set_option blast.strategy "ematch" example : ∀ x y z w : ℝ, pos x → pos y → pos z → pos w → x * y = exp z + w → log (2 * w * exp z + w² + exp (2*z)) / -2 = log (y⁻¹) - log x := begin have pos 2, by grind, /- Discharge auxiliary fact using backward chaining. -/ blast /- Use congruence closure and ematching to prove main goal. -/ end end example2
9b71daaf67f44a3532eab0884940658a7e6d1559
7bf54883c04ff2856c37f76a79599ceb380c1996
/mathlib/quartic_solution.lean
5da2b5716b44a4e819265f7eab16bbc6356c4652
[]
no_license
anonymousLeanDocsHosting/lean-polynomials
4094466bf19acc0d1a47b4cabb60d8c21ddb2b00
361ef4cb7b68ef47d43b85cfa2d13f2ea0a47613
refs/heads/main
1,691,112,899,935
1,631,819,522,000
1,631,819,522,000
405,448,439
0
2
null
null
null
null
UTF-8
Lean
false
false
14,514
lean
import algebra.invertible import tactic.linarith import order.filter.at_top_bot import algebra.cubic_solution section field variables {F : Type*} def quartic_expression [field F] (x a b c d e : F) : F := ((x * x * x * x * a) + (x * x * x * b) + (x * x * c) + (x * d) + e) def depressed_quartic_squ_coefficient [field F] (b c : F) : F := (c - (3 * b * b)/8) def depressed_quartic_linear_coefficient [field F] (b c d : F) : F := (b * b * b) / 8 - (b * c) / 2 + d def depressed_quartic_constant [field F] (b c d e : F) : F := -(3 * b * b * b * b) / 256 + (c * b * b) / 16 - (b * d) / 4 + e lemma convert_quartic_to_depressed [field F] (b c d e x : F) (two_ne_zero : (2 : F) ≠ 0) : (quartic_expression x 1 b c d e) = (quartic_expression (x + (b / 4)) 1 0 (depressed_quartic_squ_coefficient b c) (depressed_quartic_linear_coefficient b c d) (depressed_quartic_constant b c d e)) := begin unfold quartic_expression, unfold depressed_quartic_squ_coefficient, unfold depressed_quartic_linear_coefficient, unfold depressed_quartic_constant, have h256 : (256 : F) = (16 : F) * (16 : F), ring, rw h256, clear h256, have h16 : (16 : F) = (4 : F) * (4 : F), ring, rw h16, clear h16, have h8 : (8 : F) = (4 : F) * (2 : F), ring, rw h8, clear h8, have h4 : (4 : F) = (2 : F) * (2 : F), ring, rw h4, clear h4, field_simp, ring, end lemma factorise_depressed_quartic_simultaneous [field F] (c d e x p q s : F) (two_ne_zero : (2 : F) ≠ 0) (p_ne_zero : p ≠ 0) : (c + p * p = s + q) -> (d / p = s - q) -> (e = s * q) -> (quartic_expression x 1 0 c d e) = (x * x + p * x + q) * (x * x - p * x + s) := begin intros h1 h2 h3, unfold quartic_expression, have mul_quad : (x * x + p * x + q) * (x * x - p * x + s) = (x * x * x * x) + (s + q - p * p) * x * x + (p * s - p * q) * x + s * q, ring, rw mul_quad, clear mul_quad, rw <- h1, rw <- h3, rw sub_eq_add_neg (p * s) (p * q), rw neg_mul_eq_mul_neg, rw <- left_distrib, rw <- sub_eq_add_neg, rw <- h2, field_simp, ring, end lemma depressed_quartic_simultaneous_solution [field F] (c d e p q s cubrt sqrt : F) (one_ne_zero : (1 : F) ≠ 0) (two_ne_zero : (2 : F) ≠ 0) (three_ne_zero : (3 : F) ≠ 0) (p_ne_zero : p ≠ 0) (int_quantity_ne_zero : depressed_cubic_x_term 1 (2 * c) (c * c - 4 * e) ≠ 0) : (sqrt * sqrt = (cubic_formula_sqrt 1 (2 * c) (c * c - 4 * e) (- d * d))) -> (cubrt * cubrt * cubrt = (cubic_formula_cubrt 1 (2 * c) (c * c - 4 * e) (- d * d)) sqrt) -> (p * p) = (cubic_formula 1 (2 * c) (c * c - 4 * e) cubrt) -> (s = (c + (p * p) + (d / p)) / 2) -> (q = (c + (p * p) - (d / p)) / 2) -> ((c + p * p = s + q) /\ (d / p = s - q) /\ (e = s * q)) := begin intros h_sqrt h_cubrt h_p h_s h_q, split, rw h_s, rw h_q, field_simp, ring, split, rw h_s, rw h_q, field_simp, ring, rw h_s, rw h_q, field_simp, have h_cubic : 1 * (p * p) * (p * p) * (p * p) + ((2 * c) * (p * p) * (p * p)) + (c * c - 4 * e) * (p * p) + (-d * d) = 0, apply cubic_solution, repeat {assumption}, rw <- neg_inj, rw <- add_eq_zero_iff_neg_eq, simp only [sub_eq_add_neg, left_distrib, right_distrib, <- neg_mul_eq_mul_neg, <- neg_mul_eq_neg_mul], simp only [sub_eq_add_neg, left_distrib, right_distrib, <- neg_mul_eq_mul_neg, <- neg_mul_eq_neg_mul] at h_cubic, ring_nf, ring_nf at h_cubic, rw <- neg_inj, rw neg_zero, rw <- h_cubic, ring, end lemma depressed_quartic_to_quadratic_product [field F] (x c d e sqrt_p sqrt_cubic cubrt: F) (one_ne_zero : (1 : F) ≠ 0) (two_ne_zero : (2 : F) ≠ 0) (three_ne_zero : (3 : F) ≠ 0) (sqrt_p_ne_zero : sqrt_p ≠ 0) (int_quantity_ne_zero : depressed_cubic_x_term 1 (2 * c) (c * c - 4 * e) ≠ 0) : (sqrt_cubic * sqrt_cubic = (cubic_formula_sqrt 1 (2 * c) (c * c - 4 * e) (- d * d))) -> (cubrt * cubrt * cubrt = (cubic_formula_cubrt 1 (2 * c) (c * c - 4 * e) (- d * d)) sqrt_cubic) -> (sqrt_p * sqrt_p = (cubic_formula 1 (2 * c) (c * c - 4 * e) cubrt)) -> (quartic_expression x 1 0 c d e) = (x * x + sqrt_p * x + ((c + (sqrt_p * sqrt_p) - (d / sqrt_p)) / 2)) * (x * x - sqrt_p * x + ((c + (sqrt_p * sqrt_p) + (d / sqrt_p)) / 2)) := begin intros h_sqrt_cubic, intros h_cubrt, intros h_sqrt_p, apply factorise_depressed_quartic_simultaneous, repeat {assumption}, field_simp, ring, field_simp, ring, rw <- neg_inj, rw <- add_eq_zero_iff_neg_eq, field_simp, rw [mul_comm sqrt_p 2] {occs := occurrences.pos [1]}, rw mul_assoc 2 sqrt_p _, rw <- mul_assoc sqrt_p sqrt_p _, simp only [left_distrib, right_distrib, <- neg_mul_eq_mul_neg, <- neg_mul_eq_neg_mul, sub_eq_add_neg], repeat {rw mul_assoc}, rw mul_comm c sqrt_p, repeat {rw <- mul_assoc sqrt_p sqrt_p _, rw h_sqrt_p}, set p := cubic_formula 1 (2 * c) (c * c - 4 * e) cubrt with hp, rw add_comm _ (d * (sqrt_p * p)), have swap : ∀ (x1 x2 x3 : F), x1 * (x2 * x3) = x3 * (x2 * x1), intros, ring, rw swap d sqrt_p p, rw swap d sqrt_p c, clear swap, repeat {rw add_assoc}, rw <- add_assoc (-(p * (sqrt_p * d))) (p * (sqrt_p * d)), have tmp : -(p * (sqrt_p * d)) + p * (sqrt_p * d) = 0, ring, rw tmp, clear tmp, rw zero_add, rw add_comm (c * (sqrt_p * d)) _, repeat {rw add_assoc}, rw add_comm (-(c * (sqrt_p * d))) _, repeat {rw add_assoc}, have tmp : (c * (sqrt_p * d)) + -(c * (sqrt_p * d)) = 0, ring, rw tmp, clear tmp, rw add_zero, rw <- neg_inj, rw neg_zero, have finale : -(e * (2 * (p * 2)) + -(c * (p * c) + (c * (p * p) + (p * (p * c) + (p * (p * p) + -(d * d)))))) = (1 * p * p * p) + (2 * c * p * p) + ((c * c - 4 * e) * p) + (-d * d), ring, rw finale, apply cubic_solution, repeat {assumption}, end /- In a submission to the standard library, I'd use the work in the existing quadratic_discriminant.lean. However, I need some things that aren't already in there, and I don't want to mix my work with the existing work in the same file, as that would leave it ambiguous what I'd done when it comes to mark the project. Hence, I move all the work that I need out to here.-/ def quadratic_formula [field F] (b sqrt : F) : F := (sqrt - b) / 2 def quadratic_discriminant [field F] (b c : F) : F := (b * b) - (4 * c) lemma quadratic_formula_correct [field F] (b c sqrt x : F) (two_ne_zero : (2 : F) ≠ 0) (h_sqrt : sqrt * sqrt = quadratic_discriminant b c) : (x = quadratic_formula b sqrt) -> ((x * x) + (b * x) + c = 0) := begin have tmp : sqrt * sqrt = sqrt ^ 2, ring, rw tmp at h_sqrt, clear tmp, unfold quadratic_formula, intros hx, rw hx, field_simp, ring_nf, rw h_sqrt, unfold quadratic_discriminant, ring, end lemma quadratic_formula_factorise [field F] (b c sqrt x : F) (two_ne_zero : (2 : F) ≠ 0) (h_sqrt : sqrt * sqrt = quadratic_discriminant b c) : ((x * x) + (b * x) + c) = (x - (quadratic_formula b sqrt)) * (x - (quadratic_formula b (- sqrt))) := begin have tmp : sqrt * sqrt = sqrt ^ 2, ring, rw tmp at h_sqrt, clear tmp, unfold quadratic_formula, field_simp, ring_nf, rw h_sqrt, unfold quadratic_discriminant, ring, end lemma depressed_quartic_solution [field F] (x c d e sqrt_p sqrt_cubic sqrt_quadratic cubrt: F) (one_ne_zero : (1 : F) ≠ 0) (two_ne_zero : (2 : F) ≠ 0) (three_ne_zero : (3 : F) ≠ 0) (sqrt_p_ne_zero : sqrt_p ≠ 0) (int_quantity_ne_zero : depressed_cubic_x_term 1 (2 * c) (c * c - 4 * e) ≠ 0) : (sqrt_cubic * sqrt_cubic = (cubic_formula_sqrt 1 (2 * c) (c * c - 4 * e) (- d * d))) -> (cubrt * cubrt * cubrt = (cubic_formula_cubrt 1 (2 * c) (c * c - 4 * e) (- d * d)) sqrt_cubic) -> (sqrt_p * sqrt_p = (cubic_formula 1 (2 * c) (c * c - 4 * e) cubrt)) -> (sqrt_quadratic * sqrt_quadratic = (quadratic_discriminant sqrt_p ((c + (sqrt_p * sqrt_p) - (d / sqrt_p)) / 2))) -> (x = quadratic_formula sqrt_p sqrt_quadratic) -> (quartic_expression x 1 0 c d e = 0) := begin intros h_sqrt_cubic h_cubrt_cubic h_sqrt_p h_sqrt_quadratic h_x, rw depressed_quartic_to_quadratic_product x c d e sqrt_p sqrt_cubic cubrt one_ne_zero two_ne_zero three_ne_zero sqrt_p_ne_zero int_quantity_ne_zero h_sqrt_cubic h_cubrt_cubic h_sqrt_p, rw quadratic_formula_correct sqrt_p ((c + (sqrt_p * sqrt_p) - (d / sqrt_p)) / 2) sqrt_quadratic x two_ne_zero h_sqrt_quadratic h_x, rw zero_mul, end lemma quartic_solution [field F] (x b c d e sqrt_p sqrt_cubic sqrt_quadratic cubrt: F) (one_ne_zero : (1 : F) ≠ 0) (two_ne_zero : (2 : F) ≠ 0) (three_ne_zero : (3 : F) ≠ 0) (sqrt_p_ne_zero : sqrt_p ≠ 0) (int_quantity_ne_zero : depressed_cubic_x_term 1 (2 * (depressed_quartic_squ_coefficient b c)) ((depressed_quartic_squ_coefficient b c) * (depressed_quartic_squ_coefficient b c) - 4 * (depressed_quartic_constant b c d e)) ≠ 0) : (sqrt_cubic * sqrt_cubic = (cubic_formula_sqrt 1 (2 * (depressed_quartic_squ_coefficient b c)) ((depressed_quartic_squ_coefficient b c) * (depressed_quartic_squ_coefficient b c) - 4 * (depressed_quartic_constant b c d e)) (- (depressed_quartic_linear_coefficient b c d) * (depressed_quartic_linear_coefficient b c d)))) -> (cubrt * cubrt * cubrt = (cubic_formula_cubrt 1 (2 * (depressed_quartic_squ_coefficient b c)) ((depressed_quartic_squ_coefficient b c) * (depressed_quartic_squ_coefficient b c) - 4 * (depressed_quartic_constant b c d e)) (- (depressed_quartic_linear_coefficient b c d) * (depressed_quartic_linear_coefficient b c d))) sqrt_cubic) -> (sqrt_p * sqrt_p = (cubic_formula 1 (2 * (depressed_quartic_squ_coefficient b c)) ((depressed_quartic_squ_coefficient b c) * (depressed_quartic_squ_coefficient b c) - 4 * (depressed_quartic_constant b c d e)) cubrt)) -> (sqrt_quadratic * sqrt_quadratic = (quadratic_discriminant sqrt_p (((depressed_quartic_squ_coefficient b c) + (sqrt_p * sqrt_p) - ((depressed_quartic_linear_coefficient b c d) / sqrt_p)) / 2))) -> (x = (quadratic_formula sqrt_p sqrt_quadratic) - (b / 4)) -> (quartic_expression x 1 b c d e = 0) := begin intros h_sqrt_cubic h_cubrt_cubic h_sqrt_p h_sqrt_quadratic h_x, rw convert_quartic_to_depressed, apply depressed_quartic_solution (x + b / 4) (depressed_quartic_squ_coefficient b c) (depressed_quartic_linear_coefficient b c d) (depressed_quartic_constant b c d e) sqrt_p sqrt_cubic sqrt_quadratic cubrt, any_goals {assumption}, rw h_x, simp, end lemma depressed_quartic_to_linear_product [field F] (x c d e sqrt_p sqrt_cubic sqrt_discrim_a sqrt_discrim_b cubrt: F) (one_ne_zero : (1 : F) ≠ 0) (two_ne_zero : (2 : F) ≠ 0) (three_ne_zero : (3 : F) ≠ 0) (sqrt_p_ne_zero : sqrt_p ≠ 0) (int_quantity_ne_zero : depressed_cubic_x_term 1 (2 * c) (c * c - 4 * e) ≠ 0) : (sqrt_cubic * sqrt_cubic = (cubic_formula_sqrt 1 (2 * c) (c * c - 4 * e) (- d * d))) -> (cubrt * cubrt * cubrt = (cubic_formula_cubrt 1 (2 * c) (c * c - 4 * e) (- d * d)) sqrt_cubic) -> (sqrt_p * sqrt_p = (cubic_formula 1 (2 * c) (c * c - 4 * e) cubrt)) -> (sqrt_discrim_a * sqrt_discrim_a = (quadratic_discriminant sqrt_p ((c + (sqrt_p * sqrt_p) - (d / sqrt_p)) / 2))) -> (sqrt_discrim_b * sqrt_discrim_b = (quadratic_discriminant (- sqrt_p) ((c + (sqrt_p * sqrt_p) + (d / sqrt_p)) / 2))) -> (quartic_expression x 1 0 c d e) = (x - (quadratic_formula sqrt_p sqrt_discrim_a)) * (x - (quadratic_formula sqrt_p (- sqrt_discrim_a))) * (x - (quadratic_formula (- sqrt_p) sqrt_discrim_b)) * (x - (quadratic_formula (- sqrt_p) (- sqrt_discrim_b))) := begin intros h_sqrt_cubic h_cubrt h_sqrt_p h_discrim_a h_discrim_b, rw depressed_quartic_to_quadratic_product x c d e sqrt_p sqrt_cubic cubrt one_ne_zero two_ne_zero three_ne_zero sqrt_p_ne_zero int_quantity_ne_zero h_sqrt_cubic h_cubrt h_sqrt_p, rw quadratic_formula_factorise sqrt_p ((c + sqrt_p * sqrt_p - d / sqrt_p) / 2) sqrt_discrim_a x, have tmp : (x * x - sqrt_p * x) = (x * x + (- sqrt_p) * x), ring, rw tmp, clear tmp, rw quadratic_formula_factorise (- sqrt_p) ((c + sqrt_p * sqrt_p + d / sqrt_p) / 2) sqrt_discrim_b x, ring, repeat {assumption}, end lemma quartic_to_linear_product [field F] (x b c d e sqrt_p sqrt_cubic sqrt_discrim_a sqrt_discrim_b cubrt: F) (one_ne_zero : (1 : F) ≠ 0) (two_ne_zero : (2 : F) ≠ 0) (three_ne_zero : (3 : F) ≠ 0) (sqrt_p_ne_zero : sqrt_p ≠ 0) (int_quantity_ne_zero : depressed_cubic_x_term 1 (2 * (depressed_quartic_squ_coefficient b c)) ((depressed_quartic_squ_coefficient b c) * (depressed_quartic_squ_coefficient b c) - 4 * (depressed_quartic_constant b c d e)) ≠ 0) : (sqrt_cubic * sqrt_cubic = (cubic_formula_sqrt 1 (2 * (depressed_quartic_squ_coefficient b c)) ((depressed_quartic_squ_coefficient b c) * (depressed_quartic_squ_coefficient b c) - 4 * (depressed_quartic_constant b c d e)) (- (depressed_quartic_linear_coefficient b c d) * (depressed_quartic_linear_coefficient b c d)))) -> (cubrt * cubrt * cubrt = (cubic_formula_cubrt 1 (2 * (depressed_quartic_squ_coefficient b c)) ((depressed_quartic_squ_coefficient b c) * (depressed_quartic_squ_coefficient b c) - 4 * (depressed_quartic_constant b c d e)) (- (depressed_quartic_linear_coefficient b c d) * (depressed_quartic_linear_coefficient b c d))) sqrt_cubic) -> (sqrt_p * sqrt_p = (cubic_formula 1 (2 * (depressed_quartic_squ_coefficient b c)) ((depressed_quartic_squ_coefficient b c) * (depressed_quartic_squ_coefficient b c) - 4 * (depressed_quartic_constant b c d e)) cubrt)) -> (sqrt_discrim_a * sqrt_discrim_a = (quadratic_discriminant sqrt_p (((depressed_quartic_squ_coefficient b c) + (sqrt_p * sqrt_p) - ((depressed_quartic_linear_coefficient b c d) / sqrt_p)) / 2))) -> (sqrt_discrim_b * sqrt_discrim_b = (quadratic_discriminant (- sqrt_p) (((depressed_quartic_squ_coefficient b c) + (sqrt_p * sqrt_p) + ((depressed_quartic_linear_coefficient b c d) / sqrt_p)) / 2))) -> (quartic_expression x 1 b c d e) = ((x + b/4) - (quadratic_formula sqrt_p sqrt_discrim_a)) * ((x + b/4) - (quadratic_formula sqrt_p (- sqrt_discrim_a))) * ((x + b/4) - (quadratic_formula (- sqrt_p) sqrt_discrim_b)) * ((x + b/4) - (quadratic_formula (- sqrt_p) (- sqrt_discrim_b))) := begin intros h_sqrt_cubic h_cubrt h_sqrt_p h_discrim_a h_discrim_b, rw convert_quartic_to_depressed, apply depressed_quartic_to_linear_product, repeat {assumption}, end end field
af9b14fc896a3f191a65bef6d7a9cc1b825fa751
367134ba5a65885e863bdc4507601606690974c1
/src/analysis/normed_space/units.lean
f0083bfb740051fab555757a243d2a5c71cb849c
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
11,057
lean
/- Copyright (c) 2020 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth -/ import analysis.specific_limits import analysis.asymptotics.asymptotics /-! # The group of units of a complete normed ring This file contains the basic theory for the group of units (invertible elements) of a complete normed ring (Banach algebras being a notable special case). ## Main results The constructions `one_sub`, `add` and `unit_of_nearby` state, in varying forms, that perturbations of a unit are units. The latter two are not stated in their optimal form; more precise versions would use the spectral radius. The first main result is `is_open`: the group of units of a complete normed ring is an open subset of the ring. The function `inverse` (defined in `algebra.ring`), for a ring `R`, sends `a : R` to `a⁻¹` if `a` is a unit and 0 if not. The other major results of this file (notably `inverse_add`, `inverse_add_norm` and `inverse_add_norm_diff_nth_order`) cover the asymptotic properties of `inverse (x + t)` as `t → 0`. -/ noncomputable theory open_locale topological_space variables {R : Type*} [normed_ring R] [complete_space R] namespace units /-- In a complete normed ring, a perturbation of `1` by an element `t` of distance less than `1` from `1` is a unit. Here we construct its `units` structure. -/ def one_sub (t : R) (h : ∥t∥ < 1) : units R := { val := 1 - t, inv := ∑' n : ℕ, t ^ n, val_inv := mul_neg_geom_series t h, inv_val := geom_series_mul_neg t h } @[simp] lemma one_sub_coe (t : R) (h : ∥t∥ < 1) : ↑(one_sub t h) = 1 - t := rfl /-- In a complete normed ring, a perturbation of a unit `x` by an element `t` of distance less than `∥x⁻¹∥⁻¹` from `x` is a unit. Here we construct its `units` structure. -/ def add (x : units R) (t : R) (h : ∥t∥ < ∥(↑x⁻¹ : R)∥⁻¹) : units R := x * (units.one_sub (-(↑x⁻¹ * t)) begin nontriviality R using [zero_lt_one], have hpos : 0 < ∥(↑x⁻¹ : R)∥ := units.norm_pos x⁻¹, calc ∥-(↑x⁻¹ * t)∥ = ∥↑x⁻¹ * t∥ : by { rw norm_neg } ... ≤ ∥(↑x⁻¹ : R)∥ * ∥t∥ : norm_mul_le ↑x⁻¹ _ ... < ∥(↑x⁻¹ : R)∥ * ∥(↑x⁻¹ : R)∥⁻¹ : by nlinarith only [h, hpos] ... = 1 : mul_inv_cancel (ne_of_gt hpos) end) @[simp] lemma add_coe (x : units R) (t : R) (h : ∥t∥ < ∥(↑x⁻¹ : R)∥⁻¹) : ((x.add t h) : R) = x + t := by { unfold units.add, simp [mul_add] } /-- In a complete normed ring, an element `y` of distance less than `∥x⁻¹∥⁻¹` from `x` is a unit. Here we construct its `units` structure. -/ def unit_of_nearby (x : units R) (y : R) (h : ∥y - x∥ < ∥(↑x⁻¹ : R)∥⁻¹) : units R := x.add ((y : R) - x) h @[simp] lemma unit_of_nearby_coe (x : units R) (y : R) (h : ∥y - x∥ < ∥(↑x⁻¹ : R)∥⁻¹) : ↑(x.unit_of_nearby y h) = y := by { unfold units.unit_of_nearby, simp } /-- The group of units of a complete normed ring is an open subset of the ring. -/ protected lemma is_open : is_open {x : R | is_unit x} := begin nontriviality R, apply metric.is_open_iff.mpr, rintros x' ⟨x, rfl⟩, refine ⟨∥(↑x⁻¹ : R)∥⁻¹, inv_pos.mpr (units.norm_pos x⁻¹), _⟩, intros y hy, rw [metric.mem_ball, dist_eq_norm] at hy, exact ⟨x.unit_of_nearby y hy, unit_of_nearby_coe _ _ _⟩ end protected lemma nhds (x : units R) : {x : R | is_unit x} ∈ 𝓝 (x : R) := mem_nhds_sets units.is_open (is_unit_unit x) end units namespace normed_ring open_locale classical big_operators open asymptotics filter metric finset ring lemma inverse_one_sub (t : R) (h : ∥t∥ < 1) : inverse (1 - t) = ↑(units.one_sub t h)⁻¹ := by rw [← inverse_unit (units.one_sub t h), units.one_sub_coe] /-- The formula `inverse (x + t) = inverse (1 + x⁻¹ * t) * x⁻¹` holds for `t` sufficiently small. -/ lemma inverse_add (x : units R) : ∀ᶠ t in (𝓝 0), inverse ((x : R) + t) = inverse (1 + ↑x⁻¹ * t) * ↑x⁻¹ := begin nontriviality R, rw [eventually_iff, mem_nhds_iff], have hinv : 0 < ∥(↑x⁻¹ : R)∥⁻¹, by cancel_denoms, use [∥(↑x⁻¹ : R)∥⁻¹, hinv], intros t ht, simp only [mem_ball, dist_zero_right] at ht, have ht' : ∥-↑x⁻¹ * t∥ < 1, { refine lt_of_le_of_lt (norm_mul_le _ _) _, rw norm_neg, refine lt_of_lt_of_le (mul_lt_mul_of_pos_left ht x⁻¹.norm_pos) _, cancel_denoms }, have hright := inverse_one_sub (-↑x⁻¹ * t) ht', have hleft := inverse_unit (x.add t ht), simp only [← neg_mul_eq_neg_mul, sub_neg_eq_add] at hright, simp only [units.add_coe] at hleft, simp [hleft, hright, units.add] end lemma inverse_one_sub_nth_order (n : ℕ) : ∀ᶠ t in (𝓝 0), inverse ((1:R) - t) = (∑ i in range n, t ^ i) + (t ^ n) * inverse (1 - t) := begin simp only [eventually_iff, mem_nhds_iff], use [1, by norm_num], intros t ht, simp only [mem_ball, dist_zero_right] at ht, simp only [inverse_one_sub t ht, set.mem_set_of_eq], have h : 1 = ((range n).sum (λ i, t ^ i)) * (units.one_sub t ht) + t ^ n, { simp only [units.one_sub_coe], rw [← geom_series, geom_sum_mul_neg], simp }, rw [← one_mul ↑(units.one_sub t ht)⁻¹, h, add_mul], congr, { rw [mul_assoc, (units.one_sub t ht).mul_inv], simp }, { simp only [units.one_sub_coe], rw [← add_mul, ← geom_series, geom_sum_mul_neg], simp } end /-- The formula `inverse (x + t) = (∑ i in range n, (- x⁻¹ * t) ^ i) * x⁻¹ + (- x⁻¹ * t) ^ n * inverse (x + t)` holds for `t` sufficiently small. -/ lemma inverse_add_nth_order (x : units R) (n : ℕ) : ∀ᶠ t in (𝓝 0), inverse ((x : R) + t) = (∑ i in range n, (- ↑x⁻¹ * t) ^ i) * ↑x⁻¹ + (- ↑x⁻¹ * t) ^ n * inverse (x + t) := begin refine (inverse_add x).mp _, have hzero : tendsto (λ (t : R), - ↑x⁻¹ * t) (𝓝 0) (𝓝 0), { convert ((mul_left_continuous (- (↑x⁻¹ : R))).tendsto 0).comp tendsto_id, simp }, refine (hzero.eventually (inverse_one_sub_nth_order n)).mp (eventually_of_forall _), simp only [neg_mul_eq_neg_mul_symm, sub_neg_eq_add], intros t h1 h2, have h := congr_arg (λ (a : R), a * ↑x⁻¹) h1, dsimp at h, convert h, rw [add_mul, mul_assoc], simp [h2.symm] end lemma inverse_one_sub_norm : is_O (λ t, inverse ((1:R) - t)) (λ t, (1:ℝ)) (𝓝 (0:R)) := begin simp only [is_O, is_O_with, eventually_iff, mem_nhds_iff], refine ⟨∥(1:R)∥ + 1, (2:ℝ)⁻¹, by norm_num, _⟩, intros t ht, simp only [ball, dist_zero_right, set.mem_set_of_eq] at ht, have ht' : ∥t∥ < 1, { have : (2:ℝ)⁻¹ < 1 := by cancel_denoms, linarith }, simp only [inverse_one_sub t ht', norm_one, mul_one, set.mem_set_of_eq], change ∥∑' n : ℕ, t ^ n∥ ≤ _, have := normed_ring.tsum_geometric_of_norm_lt_1 t ht', have : (1 - ∥t∥)⁻¹ ≤ 2, { rw ← inv_inv' (2:ℝ), refine inv_le_inv_of_le (by norm_num) _, have : (2:ℝ)⁻¹ + (2:ℝ)⁻¹ = 1 := by ring, linarith }, linarith end /-- The function `λ t, inverse (x + t)` is O(1) as `t → 0`. -/ lemma inverse_add_norm (x : units R) : is_O (λ t, inverse (↑x + t)) (λ t, (1:ℝ)) (𝓝 (0:R)) := begin nontriviality R, simp only [is_O_iff, norm_one, mul_one], cases is_O_iff.mp (@inverse_one_sub_norm R _ _) with C hC, use C * ∥((x⁻¹:units R):R)∥, have hzero : tendsto (λ t, - (↑x⁻¹ : R) * t) (𝓝 0) (𝓝 0), { convert ((mul_left_continuous (-↑x⁻¹ : R)).tendsto 0).comp tendsto_id, simp }, refine (inverse_add x).mp ((hzero.eventually hC).mp (eventually_of_forall _)), intros t bound iden, rw iden, simp at bound, have hmul := norm_mul_le (inverse (1 + ↑x⁻¹ * t)) ↑x⁻¹, nlinarith [norm_nonneg (↑x⁻¹ : R)] end /-- The function `λ t, inverse (x + t) - (∑ i in range n, (- x⁻¹ * t) ^ i) * x⁻¹` is `O(t ^ n)` as `t → 0`. -/ lemma inverse_add_norm_diff_nth_order (x : units R) (n : ℕ) : is_O (λ (t : R), inverse (↑x + t) - (∑ i in range n, (- ↑x⁻¹ * t) ^ i) * ↑x⁻¹) (λ t, ∥t∥ ^ n) (𝓝 (0:R)) := begin by_cases h : n = 0, { simpa [h] using inverse_add_norm x }, have hn : 0 < n := nat.pos_of_ne_zero h, simp [is_O_iff], cases (is_O_iff.mp (inverse_add_norm x)) with C hC, use C * ∥(1:ℝ)∥ * ∥(↑x⁻¹ : R)∥ ^ n, have h : eventually_eq (𝓝 (0:R)) (λ t, inverse (↑x + t) - (∑ i in range n, (- ↑x⁻¹ * t) ^ i) * ↑x⁻¹) (λ t, ((- ↑x⁻¹ * t) ^ n) * inverse (x + t)), { refine (inverse_add_nth_order x n).mp (eventually_of_forall _), intros t ht, convert congr_arg (λ a, a - (range n).sum (pow (-↑x⁻¹ * t)) * ↑x⁻¹) ht, simp }, refine h.mp (hC.mp (eventually_of_forall _)), intros t _ hLHS, simp only [neg_mul_eq_neg_mul_symm] at hLHS, rw hLHS, refine le_trans (norm_mul_le _ _ ) _, have h' : ∥(-(↑x⁻¹ * t)) ^ n∥ ≤ ∥(↑x⁻¹ : R)∥ ^ n * ∥t∥ ^ n, { calc ∥(-(↑x⁻¹ * t)) ^ n∥ ≤ ∥(-(↑x⁻¹ * t))∥ ^ n : norm_pow_le' _ hn ... = ∥↑x⁻¹ * t∥ ^ n : by rw norm_neg ... ≤ (∥(↑x⁻¹ : R)∥ * ∥t∥) ^ n : _ ... = ∥(↑x⁻¹ : R)∥ ^ n * ∥t∥ ^ n : mul_pow _ _ n, exact pow_le_pow_of_le_left (norm_nonneg _) (norm_mul_le ↑x⁻¹ t) n }, have h'' : 0 ≤ ∥(↑x⁻¹ : R)∥ ^ n * ∥t∥ ^ n, { refine mul_nonneg _ _; exact pow_nonneg (norm_nonneg _) n }, nlinarith [norm_nonneg (inverse (↑x + t))], end /-- The function `λ t, inverse (x + t) - x⁻¹` is `O(t)` as `t → 0`. -/ lemma inverse_add_norm_diff_first_order (x : units R) : is_O (λ t, inverse (↑x + t) - ↑x⁻¹) (λ t, ∥t∥) (𝓝 (0:R)) := by { convert inverse_add_norm_diff_nth_order x 1; simp } /-- The function `λ t, inverse (x + t) - x⁻¹ + x⁻¹ * t * x⁻¹` is `O(t ^ 2)` as `t → 0`. -/ lemma inverse_add_norm_diff_second_order (x : units R) : is_O (λ t, inverse (↑x + t) - ↑x⁻¹ + ↑x⁻¹ * t * ↑x⁻¹) (λ t, ∥t∥ ^ 2) (𝓝 (0:R)) := begin convert inverse_add_norm_diff_nth_order x 2, ext t, simp only [range_succ, range_one, sum_insert, mem_singleton, sum_singleton, not_false_iff, one_ne_zero, pow_zero, add_mul], abel, simp end /-- The function `inverse` is continuous at each unit of `R`. -/ lemma inverse_continuous_at (x : units R) : continuous_at inverse (x : R) := begin have h_is_o : is_o (λ (t : R), ∥inverse (↑x + t) - ↑x⁻¹∥) (λ (t : R), (1:ℝ)) (𝓝 0), { refine is_o_norm_left.mpr ((inverse_add_norm_diff_first_order x).trans_is_o _), exact is_o_norm_left.mpr (is_o_id_const one_ne_zero) }, have h_lim : tendsto (λ (y:R), y - x) (𝓝 x) (𝓝 0), { refine tendsto_zero_iff_norm_tendsto_zero.mpr _, exact tendsto_iff_norm_tendsto_zero.mp tendsto_id }, simp only [continuous_at], rw [tendsto_iff_norm_tendsto_zero, inverse_unit], convert h_is_o.tendsto_0.comp h_lim, ext, simp end end normed_ring
e86714ba4d47583e0182b1f7a6c08a6545b00475
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/measure_theory/decomposition/jordan.lean
85d3be72c102744a86dcdadfb1ecb7d13a638f73
[ "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
25,274
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.signed_hahn import measure_theory.measure.mutually_singular /-! # Jordan decomposition > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file proves the existence and uniqueness of the Jordan decomposition for signed measures. The Jordan decomposition theorem states that, given a signed measure `s`, there exists a unique pair of mutually singular measures `μ` and `ν`, such that `s = μ - ν`. The Jordan decomposition theorem for measures is a corollary of the Hahn decomposition theorem and is useful for the Lebesgue decomposition theorem. ## Main definitions * `measure_theory.jordan_decomposition`: a Jordan decomposition of a measurable space is a pair of mutually singular finite measures. We say `j` is a Jordan decomposition of a signed measure `s` if `s = j.pos_part - j.neg_part`. * `measure_theory.signed_measure.to_jordan_decomposition`: the Jordan decomposition of a signed measure. * `measure_theory.signed_measure.to_jordan_decomposition_equiv`: is the `equiv` between `measure_theory.signed_measure` and `measure_theory.jordan_decomposition` formed by `measure_theory.signed_measure.to_jordan_decomposition`. ## Main results * `measure_theory.signed_measure.to_signed_measure_to_jordan_decomposition` : the Jordan decomposition theorem. * `measure_theory.jordan_decomposition.to_signed_measure_injective` : the Jordan decomposition of a signed measure is unique. ## Tags Jordan decomposition theorem -/ noncomputable theory open_locale classical measure_theory ennreal nnreal variables {α β : Type*} [measurable_space α] namespace measure_theory /-- A Jordan decomposition of a measurable space is a pair of mutually singular, finite measures. -/ @[ext] structure jordan_decomposition (α : Type*) [measurable_space α] := (pos_part neg_part : measure α) [pos_part_finite : is_finite_measure pos_part] [neg_part_finite : is_finite_measure neg_part] (mutually_singular : pos_part ⟂ₘ neg_part) attribute [instance] jordan_decomposition.pos_part_finite attribute [instance] jordan_decomposition.neg_part_finite namespace jordan_decomposition open measure vector_measure variable (j : jordan_decomposition α) instance : has_zero (jordan_decomposition α) := { zero := ⟨0, 0, mutually_singular.zero_right⟩ } instance : inhabited (jordan_decomposition α) := { default := 0 } instance : has_involutive_neg (jordan_decomposition α) := { neg := λ j, ⟨j.neg_part, j.pos_part, j.mutually_singular.symm⟩, neg_neg := λ j, jordan_decomposition.ext _ _ rfl rfl } instance : has_smul ℝ≥0 (jordan_decomposition α) := { smul := λ r j, ⟨r • j.pos_part, r • j.neg_part, mutually_singular.smul _ (mutually_singular.smul _ j.mutually_singular.symm).symm⟩ } instance has_smul_real : has_smul ℝ (jordan_decomposition α) := { smul := λ r j, if hr : 0 ≤ r then r.to_nnreal • j else - ((-r).to_nnreal • j) } @[simp] lemma zero_pos_part : (0 : jordan_decomposition α).pos_part = 0 := rfl @[simp] lemma zero_neg_part : (0 : jordan_decomposition α).neg_part = 0 := rfl @[simp] lemma neg_pos_part : (-j).pos_part = j.neg_part := rfl @[simp] lemma neg_neg_part : (-j).neg_part = j.pos_part := rfl @[simp] lemma smul_pos_part (r : ℝ≥0) : (r • j).pos_part = r • j.pos_part := rfl @[simp] lemma smul_neg_part (r : ℝ≥0) : (r • j).neg_part = r • j.neg_part := rfl lemma real_smul_def (r : ℝ) (j : jordan_decomposition α) : r • j = if hr : 0 ≤ r then r.to_nnreal • j else - ((-r).to_nnreal • j) := rfl @[simp] lemma coe_smul (r : ℝ≥0) : (r : ℝ) • j = r • j := show dite _ _ _ = _, by rw [dif_pos (nnreal.coe_nonneg r), real.to_nnreal_coe] lemma real_smul_nonneg (r : ℝ) (hr : 0 ≤ r) : r • j = r.to_nnreal • j := dif_pos hr lemma real_smul_neg (r : ℝ) (hr : r < 0) : r • j = - ((-r).to_nnreal • j) := dif_neg (not_le.2 hr) lemma real_smul_pos_part_nonneg (r : ℝ) (hr : 0 ≤ r) : (r • j).pos_part = r.to_nnreal • j.pos_part := by { rw [real_smul_def, ← smul_pos_part, dif_pos hr] } lemma real_smul_neg_part_nonneg (r : ℝ) (hr : 0 ≤ r) : (r • j).neg_part = r.to_nnreal • j.neg_part := by { rw [real_smul_def, ← smul_neg_part, dif_pos hr] } lemma real_smul_pos_part_neg (r : ℝ) (hr : r < 0) : (r • j).pos_part = (-r).to_nnreal • j.neg_part := by { rw [real_smul_def, ← smul_neg_part, dif_neg (not_le.2 hr), neg_pos_part] } lemma real_smul_neg_part_neg (r : ℝ) (hr : r < 0) : (r • j).neg_part = (-r).to_nnreal • j.pos_part := by { rw [real_smul_def, ← smul_pos_part, dif_neg (not_le.2 hr), neg_neg_part] } /-- The signed measure associated with a Jordan decomposition. -/ def to_signed_measure : signed_measure α := j.pos_part.to_signed_measure - j.neg_part.to_signed_measure lemma to_signed_measure_zero : (0 : jordan_decomposition α).to_signed_measure = 0 := begin ext1 i hi, erw [to_signed_measure, to_signed_measure_sub_apply hi, sub_self, zero_apply], end lemma to_signed_measure_neg : (-j).to_signed_measure = -j.to_signed_measure := begin ext1 i hi, rw [neg_apply, to_signed_measure, to_signed_measure, to_signed_measure_sub_apply hi, to_signed_measure_sub_apply hi, neg_sub], refl, end lemma to_signed_measure_smul (r : ℝ≥0) : (r • j).to_signed_measure = r • j.to_signed_measure := begin ext1 i hi, rw [vector_measure.smul_apply, to_signed_measure, to_signed_measure, to_signed_measure_sub_apply hi, to_signed_measure_sub_apply hi, smul_sub, smul_pos_part, smul_neg_part, ← ennreal.to_real_smul, ← ennreal.to_real_smul], refl end /-- A Jordan decomposition provides a Hahn decomposition. -/ lemma exists_compl_positive_negative : ∃ S : set α, measurable_set S ∧ j.to_signed_measure ≤[S] 0 ∧ 0 ≤[Sᶜ] j.to_signed_measure ∧ j.pos_part S = 0 ∧ j.neg_part Sᶜ = 0 := begin obtain ⟨S, hS₁, hS₂, hS₃⟩ := j.mutually_singular, refine ⟨S, hS₁, _, _, hS₂, hS₃⟩, { refine restrict_le_restrict_of_subset_le _ _ (λ A hA hA₁, _), rw [to_signed_measure, to_signed_measure_sub_apply hA, show j.pos_part A = 0, by exact nonpos_iff_eq_zero.1 (hS₂ ▸ measure_mono hA₁), ennreal.zero_to_real, zero_sub, neg_le, zero_apply, neg_zero], exact ennreal.to_real_nonneg }, { refine restrict_le_restrict_of_subset_le _ _ (λ A hA hA₁, _), rw [to_signed_measure, to_signed_measure_sub_apply hA, show j.neg_part A = 0, by exact nonpos_iff_eq_zero.1 (hS₃ ▸ measure_mono hA₁), ennreal.zero_to_real, sub_zero], exact ennreal.to_real_nonneg }, end end jordan_decomposition namespace signed_measure open classical jordan_decomposition measure set vector_measure variables {s : signed_measure α} {μ ν : measure α} [is_finite_measure μ] [is_finite_measure ν] /-- Given a signed measure `s`, `s.to_jordan_decomposition` is the Jordan decomposition `j`, such that `s = j.to_signed_measure`. This property is known as the Jordan decomposition theorem, and is shown by `measure_theory.signed_measure.to_signed_measure_to_jordan_decomposition`. -/ def to_jordan_decomposition (s : signed_measure α) : jordan_decomposition α := let i := some s.exists_compl_positive_negative in let hi := some_spec s.exists_compl_positive_negative in { pos_part := s.to_measure_of_zero_le i hi.1 hi.2.1, neg_part := s.to_measure_of_le_zero iᶜ hi.1.compl hi.2.2, pos_part_finite := infer_instance, neg_part_finite := infer_instance, mutually_singular := begin refine ⟨iᶜ, hi.1.compl, _, _⟩, { rw [to_measure_of_zero_le_apply _ _ hi.1 hi.1.compl], simp }, { rw [to_measure_of_le_zero_apply _ _ hi.1.compl hi.1.compl.compl], simp } end } lemma to_jordan_decomposition_spec (s : signed_measure α) : ∃ (i : set α) (hi₁ : measurable_set i) (hi₂ : 0 ≤[i] s) (hi₃ : s ≤[iᶜ] 0), s.to_jordan_decomposition.pos_part = s.to_measure_of_zero_le i hi₁ hi₂ ∧ s.to_jordan_decomposition.neg_part = s.to_measure_of_le_zero iᶜ hi₁.compl hi₃ := begin set i := some s.exists_compl_positive_negative, obtain ⟨hi₁, hi₂, hi₃⟩ := some_spec s.exists_compl_positive_negative, exact ⟨i, hi₁, hi₂, hi₃, rfl, rfl⟩, end /-- **The Jordan decomposition theorem**: Given a signed measure `s`, there exists a pair of mutually singular measures `μ` and `ν` such that `s = μ - ν`. In this case, the measures `μ` and `ν` are given by `s.to_jordan_decomposition.pos_part` and `s.to_jordan_decomposition.neg_part` respectively. Note that we use `measure_theory.jordan_decomposition.to_signed_measure` to represent the signed measure corresponding to `s.to_jordan_decomposition.pos_part - s.to_jordan_decomposition.neg_part`. -/ @[simp] lemma to_signed_measure_to_jordan_decomposition (s : signed_measure α) : s.to_jordan_decomposition.to_signed_measure = s := begin obtain ⟨i, hi₁, hi₂, hi₃, hμ, hν⟩ := s.to_jordan_decomposition_spec, simp only [jordan_decomposition.to_signed_measure, hμ, hν], ext k hk, rw [to_signed_measure_sub_apply hk, to_measure_of_zero_le_apply _ hi₂ hi₁ hk, to_measure_of_le_zero_apply _ hi₃ hi₁.compl hk], simp only [ennreal.coe_to_real, subtype.coe_mk, ennreal.some_eq_coe, sub_neg_eq_add], rw [← of_union _ (measurable_set.inter hi₁ hk) (measurable_set.inter hi₁.compl hk), set.inter_comm i, set.inter_comm iᶜ, set.inter_union_compl _ _], { apply_instance }, { exact (disjoint_compl_right.inf_left _).inf_right _ } end section variables {u v w : set α} /-- A subset `v` of a null-set `w` has zero measure if `w` is a subset of a positive set `u`. -/ lemma subset_positive_null_set (hu : measurable_set u) (hv : measurable_set v) (hw : measurable_set w) (hsu : 0 ≤[u] s) (hw₁ : s w = 0) (hw₂ : w ⊆ u) (hwt : v ⊆ w) : s v = 0 := begin have : s v + s (w \ v) = 0, { rw [← hw₁, ← of_union set.disjoint_sdiff_right hv (hw.diff hv), set.union_diff_self, set.union_eq_self_of_subset_left hwt], apply_instance }, have h₁ := nonneg_of_zero_le_restrict _ (restrict_le_restrict_subset _ _ hu hsu (hwt.trans hw₂)), have h₂ := nonneg_of_zero_le_restrict _ (restrict_le_restrict_subset _ _ hu hsu ((w.diff_subset v).trans hw₂)), linarith, end /-- A subset `v` of a null-set `w` has zero measure if `w` is a subset of a negative set `u`. -/ lemma subset_negative_null_set (hu : measurable_set u) (hv : measurable_set v) (hw : measurable_set w) (hsu : s ≤[u] 0) (hw₁ : s w = 0) (hw₂ : w ⊆ u) (hwt : v ⊆ w) : s v = 0 := begin rw [← s.neg_le_neg_iff _ hu, neg_zero] at hsu, have := subset_positive_null_set hu hv hw hsu, simp only [pi.neg_apply, neg_eq_zero, coe_neg] at this, exact this hw₁ hw₂ hwt, end /-- If the symmetric difference of two positive sets is a null-set, then so are the differences between the two sets. -/ lemma of_diff_eq_zero_of_symm_diff_eq_zero_positive (hu : measurable_set u) (hv : measurable_set v) (hsu : 0 ≤[u] s) (hsv : 0 ≤[v] s) (hs : s (u ∆ v) = 0) : s (u \ v) = 0 ∧ s (v \ u) = 0 := begin rw restrict_le_restrict_iff at hsu hsv, have a := hsu (hu.diff hv) (u.diff_subset v), have b := hsv (hv.diff hu) (v.diff_subset u), erw [of_union (set.disjoint_of_subset_left (u.diff_subset v) disjoint_sdiff_self_right) (hu.diff hv) (hv.diff hu)] at hs, rw zero_apply at a b, split, all_goals { linarith <|> apply_instance <|> assumption }, end /-- If the symmetric difference of two negative sets is a null-set, then so are the differences between the two sets. -/ lemma of_diff_eq_zero_of_symm_diff_eq_zero_negative (hu : measurable_set u) (hv : measurable_set v) (hsu : s ≤[u] 0) (hsv : s ≤[v] 0) (hs : s (u ∆ v) = 0) : s (u \ v) = 0 ∧ s (v \ u) = 0 := begin rw [← s.neg_le_neg_iff _ hu, neg_zero] at hsu, rw [← s.neg_le_neg_iff _ hv, neg_zero] at hsv, have := of_diff_eq_zero_of_symm_diff_eq_zero_positive hu hv hsu hsv, simp only [pi.neg_apply, neg_eq_zero, coe_neg] at this, exact this hs, end lemma of_inter_eq_of_symm_diff_eq_zero_positive (hu : measurable_set u) (hv : measurable_set v) (hw : measurable_set w) (hsu : 0 ≤[u] s) (hsv : 0 ≤[v] s) (hs : s (u ∆ v) = 0) : s (w ∩ u) = s (w ∩ v) := begin have hwuv : s ((w ∩ u) ∆ (w ∩ v)) = 0, { refine subset_positive_null_set (hu.union hv) ((hw.inter hu).symm_diff (hw.inter hv)) (hu.symm_diff hv) (restrict_le_restrict_union _ _ hu hsu hv hsv) hs symm_diff_subset_union _, rw ←inter_symm_diff_distrib_left, exact inter_subset_right _ _ }, obtain ⟨huv, hvu⟩ := of_diff_eq_zero_of_symm_diff_eq_zero_positive (hw.inter hu) (hw.inter hv) (restrict_le_restrict_subset _ _ hu hsu (w.inter_subset_right u)) (restrict_le_restrict_subset _ _ hv hsv (w.inter_subset_right v)) hwuv, rw [← of_diff_of_diff_eq_zero (hw.inter hu) (hw.inter hv) hvu, huv, zero_add] end lemma of_inter_eq_of_symm_diff_eq_zero_negative (hu : measurable_set u) (hv : measurable_set v) (hw : measurable_set w) (hsu : s ≤[u] 0) (hsv : s ≤[v] 0) (hs : s (u ∆ v) = 0) : s (w ∩ u) = s (w ∩ v) := begin rw [← s.neg_le_neg_iff _ hu, neg_zero] at hsu, rw [← s.neg_le_neg_iff _ hv, neg_zero] at hsv, have := of_inter_eq_of_symm_diff_eq_zero_positive hu hv hw hsu hsv, simp only [pi.neg_apply, neg_inj, neg_eq_zero, coe_neg] at this, exact this hs, end end end signed_measure namespace jordan_decomposition open measure vector_measure signed_measure function private lemma eq_of_pos_part_eq_pos_part {j₁ j₂ : jordan_decomposition α} (hj : j₁.pos_part = j₂.pos_part) (hj' : j₁.to_signed_measure = j₂.to_signed_measure) : j₁ = j₂ := begin ext1, { exact hj }, { rw ← to_signed_measure_eq_to_signed_measure_iff, suffices : j₁.pos_part.to_signed_measure - j₁.neg_part.to_signed_measure = j₁.pos_part.to_signed_measure - j₂.neg_part.to_signed_measure, { exact sub_right_inj.mp this }, convert hj' } end /-- The Jordan decomposition of a signed measure is unique. -/ theorem to_signed_measure_injective : injective $ @jordan_decomposition.to_signed_measure α _ := begin /- The main idea is that two Jordan decompositions of a signed measure provide two Hahn decompositions for that measure. Then, from `of_symm_diff_compl_positive_negative`, the symmetric difference of the two Hahn decompositions has measure zero, thus, allowing us to show the equality of the underlying measures of the Jordan decompositions. -/ intros j₁ j₂ hj, -- obtain the two Hahn decompositions from the Jordan decompositions obtain ⟨S, hS₁, hS₂, hS₃, hS₄, hS₅⟩ := j₁.exists_compl_positive_negative, obtain ⟨T, hT₁, hT₂, hT₃, hT₄, hT₅⟩ := j₂.exists_compl_positive_negative, rw ← hj at hT₂ hT₃, -- the symmetric differences of the two Hahn decompositions have measure zero obtain ⟨hST₁, -⟩ := of_symm_diff_compl_positive_negative hS₁.compl hT₁.compl ⟨hS₃, (compl_compl S).symm ▸ hS₂⟩ ⟨hT₃, (compl_compl T).symm ▸ hT₂⟩, -- it suffices to show the Jordan decompositions have the same positive parts refine eq_of_pos_part_eq_pos_part _ hj, ext1 i hi, -- we see that the positive parts of the two Jordan decompositions are equal to their -- associated signed measures restricted on their associated Hahn decompositions have hμ₁ : (j₁.pos_part i).to_real = j₁.to_signed_measure (i ∩ Sᶜ), { rw [to_signed_measure, to_signed_measure_sub_apply (hi.inter hS₁.compl), show j₁.neg_part (i ∩ Sᶜ) = 0, by exact nonpos_iff_eq_zero.1 (hS₅ ▸ measure_mono (set.inter_subset_right _ _)), ennreal.zero_to_real, sub_zero], conv_lhs { rw ← set.inter_union_compl i S }, rw [measure_union, show j₁.pos_part (i ∩ S) = 0, by exact nonpos_iff_eq_zero.1 (hS₄ ▸ measure_mono (set.inter_subset_right _ _)), zero_add], { refine set.disjoint_of_subset_left (set.inter_subset_right _ _) (set.disjoint_of_subset_right (set.inter_subset_right _ _) disjoint_compl_right) }, { exact hi.inter hS₁.compl } }, have hμ₂ : (j₂.pos_part i).to_real = j₂.to_signed_measure (i ∩ Tᶜ), { rw [to_signed_measure, to_signed_measure_sub_apply (hi.inter hT₁.compl), show j₂.neg_part (i ∩ Tᶜ) = 0, by exact nonpos_iff_eq_zero.1 (hT₅ ▸ measure_mono (set.inter_subset_right _ _)), ennreal.zero_to_real, sub_zero], conv_lhs { rw ← set.inter_union_compl i T }, rw [measure_union, show j₂.pos_part (i ∩ T) = 0, by exact nonpos_iff_eq_zero.1 (hT₄ ▸ measure_mono (set.inter_subset_right _ _)), zero_add], { exact set.disjoint_of_subset_left (set.inter_subset_right _ _) (set.disjoint_of_subset_right (set.inter_subset_right _ _) disjoint_compl_right) }, { exact hi.inter hT₁.compl } }, -- since the two signed measures associated with the Jordan decompositions are the same, -- and the symmetric difference of the Hahn decompositions have measure zero, the result follows rw [← ennreal.to_real_eq_to_real (measure_ne_top _ _) (measure_ne_top _ _), hμ₁, hμ₂, ← hj], exact of_inter_eq_of_symm_diff_eq_zero_positive hS₁.compl hT₁.compl hi hS₃ hT₃ hST₁, all_goals { apply_instance }, end @[simp] lemma to_jordan_decomposition_to_signed_measure (j : jordan_decomposition α) : (j.to_signed_measure).to_jordan_decomposition = j := (@to_signed_measure_injective _ _ j (j.to_signed_measure).to_jordan_decomposition (by simp)).symm end jordan_decomposition namespace signed_measure open jordan_decomposition /-- `measure_theory.signed_measure.to_jordan_decomposition` and `measure_theory.jordan_decomposition.to_signed_measure` form a `equiv`. -/ @[simps apply symm_apply] def to_jordan_decomposition_equiv (α : Type*) [measurable_space α] : signed_measure α ≃ jordan_decomposition α := { to_fun := to_jordan_decomposition, inv_fun := to_signed_measure, left_inv := to_signed_measure_to_jordan_decomposition, right_inv := to_jordan_decomposition_to_signed_measure } lemma to_jordan_decomposition_zero : (0 : signed_measure α).to_jordan_decomposition = 0 := begin apply to_signed_measure_injective, simp [to_signed_measure_zero], end lemma to_jordan_decomposition_neg (s : signed_measure α) : (-s).to_jordan_decomposition = -s.to_jordan_decomposition := begin apply to_signed_measure_injective, simp [to_signed_measure_neg], end lemma to_jordan_decomposition_smul (s : signed_measure α) (r : ℝ≥0) : (r • s).to_jordan_decomposition = r • s.to_jordan_decomposition := begin apply to_signed_measure_injective, simp [to_signed_measure_smul], end private lemma to_jordan_decomposition_smul_real_nonneg (s : signed_measure α) (r : ℝ) (hr : 0 ≤ r): (r • s).to_jordan_decomposition = r • s.to_jordan_decomposition := begin lift r to ℝ≥0 using hr, rw [jordan_decomposition.coe_smul, ← to_jordan_decomposition_smul], refl end lemma to_jordan_decomposition_smul_real (s : signed_measure α) (r : ℝ) : (r • s).to_jordan_decomposition = r • s.to_jordan_decomposition := begin by_cases hr : 0 ≤ r, { exact to_jordan_decomposition_smul_real_nonneg s r hr }, { ext1, { rw [real_smul_pos_part_neg _ _ (not_le.1 hr), show r • s = -(-r • s), by rw [neg_smul, neg_neg], to_jordan_decomposition_neg, neg_pos_part, to_jordan_decomposition_smul_real_nonneg, ← smul_neg_part, real_smul_nonneg], all_goals { exact left.nonneg_neg_iff.2 (le_of_lt (not_le.1 hr)) } }, { rw [real_smul_neg_part_neg _ _ (not_le.1 hr), show r • s = -(-r • s), by rw [neg_smul, neg_neg], to_jordan_decomposition_neg, neg_neg_part, to_jordan_decomposition_smul_real_nonneg, ← smul_pos_part, real_smul_nonneg], all_goals { exact left.nonneg_neg_iff.2 (le_of_lt (not_le.1 hr)) } } } end lemma to_jordan_decomposition_eq {s : signed_measure α} {j : jordan_decomposition α} (h : s = j.to_signed_measure) : s.to_jordan_decomposition = j := by rw [h, to_jordan_decomposition_to_signed_measure] /-- The total variation of a signed measure. -/ def total_variation (s : signed_measure α) : measure α := s.to_jordan_decomposition.pos_part + s.to_jordan_decomposition.neg_part lemma total_variation_zero : (0 : signed_measure α).total_variation = 0 := by simp [total_variation, to_jordan_decomposition_zero] lemma total_variation_neg (s : signed_measure α) : (-s).total_variation = s.total_variation := by simp [total_variation, to_jordan_decomposition_neg, add_comm] lemma null_of_total_variation_zero (s : signed_measure α) {i : set α} (hs : s.total_variation i = 0) : s i = 0 := begin rw [total_variation, measure.coe_add, pi.add_apply, add_eq_zero_iff] at hs, rw [← to_signed_measure_to_jordan_decomposition s, to_signed_measure, vector_measure.coe_sub, pi.sub_apply, measure.to_signed_measure_apply, measure.to_signed_measure_apply], by_cases hi : measurable_set i, { rw [if_pos hi, if_pos hi], simp [hs.1, hs.2] }, { simp [if_neg hi] } end lemma absolutely_continuous_ennreal_iff (s : signed_measure α) (μ : vector_measure α ℝ≥0∞) : s ≪ᵥ μ ↔ s.total_variation ≪ μ.ennreal_to_measure := begin split; intro h, { refine measure.absolutely_continuous.mk (λ S hS₁ hS₂, _), obtain ⟨i, hi₁, hi₂, hi₃, hpos, hneg⟩ := s.to_jordan_decomposition_spec, rw [total_variation, measure.add_apply, hpos, hneg, to_measure_of_zero_le_apply _ _ _ hS₁, to_measure_of_le_zero_apply _ _ _ hS₁], rw ← vector_measure.absolutely_continuous.ennreal_to_measure at h, simp [h (measure_mono_null (i.inter_subset_right S) hS₂), h (measure_mono_null (iᶜ.inter_subset_right S) hS₂)] }, { refine vector_measure.absolutely_continuous.mk (λ S hS₁ hS₂, _), rw ← vector_measure.ennreal_to_measure_apply hS₁ at hS₂, exact null_of_total_variation_zero s (h hS₂) } end lemma total_variation_absolutely_continuous_iff (s : signed_measure α) (μ : measure α) : s.total_variation ≪ μ ↔ s.to_jordan_decomposition.pos_part ≪ μ ∧ s.to_jordan_decomposition.neg_part ≪ μ := begin split; intro h, { split, all_goals { refine measure.absolutely_continuous.mk (λ S hS₁ hS₂, _), have := h hS₂, rw [total_variation, measure.add_apply, add_eq_zero_iff] at this }, exacts [this.1, this.2] }, { refine measure.absolutely_continuous.mk (λ S hS₁ hS₂, _), rw [total_variation, measure.add_apply, h.1 hS₂, h.2 hS₂, add_zero] } end -- TODO: Generalize to vector measures once total variation on vector measures is defined lemma mutually_singular_iff (s t : signed_measure α) : s ⟂ᵥ t ↔ s.total_variation ⟂ₘ t.total_variation := begin split, { rintro ⟨u, hmeas, hu₁, hu₂⟩, obtain ⟨i, hi₁, hi₂, hi₃, hipos, hineg⟩ := s.to_jordan_decomposition_spec, obtain ⟨j, hj₁, hj₂, hj₃, hjpos, hjneg⟩ := t.to_jordan_decomposition_spec, refine ⟨u, hmeas, _, _⟩, { rw [total_variation, measure.add_apply, hipos, hineg, to_measure_of_zero_le_apply _ _ _ hmeas, to_measure_of_le_zero_apply _ _ _ hmeas], simp [hu₁ _ (set.inter_subset_right _ _)] }, { rw [total_variation, measure.add_apply, hjpos, hjneg, to_measure_of_zero_le_apply _ _ _ hmeas.compl, to_measure_of_le_zero_apply _ _ _ hmeas.compl], simp [hu₂ _ (set.inter_subset_right _ _)] } }, { rintro ⟨u, hmeas, hu₁, hu₂⟩, exact ⟨u, hmeas, (λ t htu, null_of_total_variation_zero _ (measure_mono_null htu hu₁)), (λ t htv, null_of_total_variation_zero _ (measure_mono_null htv hu₂))⟩ } end lemma mutually_singular_ennreal_iff (s : signed_measure α) (μ : vector_measure α ℝ≥0∞) : s ⟂ᵥ μ ↔ s.total_variation ⟂ₘ μ.ennreal_to_measure := begin split, { rintro ⟨u, hmeas, hu₁, hu₂⟩, obtain ⟨i, hi₁, hi₂, hi₃, hpos, hneg⟩ := s.to_jordan_decomposition_spec, refine ⟨u, hmeas, _, _⟩, { rw [total_variation, measure.add_apply, hpos, hneg, to_measure_of_zero_le_apply _ _ _ hmeas, to_measure_of_le_zero_apply _ _ _ hmeas], simp [hu₁ _ (set.inter_subset_right _ _)] }, { rw vector_measure.ennreal_to_measure_apply hmeas.compl, exact hu₂ _ (set.subset.refl _) } }, { rintro ⟨u, hmeas, hu₁, hu₂⟩, refine vector_measure.mutually_singular.mk u hmeas (λ t htu _, null_of_total_variation_zero _ (measure_mono_null htu hu₁)) (λ t htv hmt, _), rw ← vector_measure.ennreal_to_measure_apply hmt, exact measure_mono_null htv hu₂ } end lemma total_variation_mutually_singular_iff (s : signed_measure α) (μ : measure α) : s.total_variation ⟂ₘ μ ↔ s.to_jordan_decomposition.pos_part ⟂ₘ μ ∧ s.to_jordan_decomposition.neg_part ⟂ₘ μ := measure.mutually_singular.add_left_iff end signed_measure end measure_theory
b1c549ffbe128976ded5b5d139e7db2820b2be41
35b83be3126daae10419b573c55e1fed009d3ae8
/_target/deps/mathlib/data/nat/sqrt.lean
9ccc838b7b611aecab5423ac17725cc6e947c256
[]
no_license
AHassan1024/Lean_Playground
ccb25b72029d199c0d23d002db2d32a9f2689ebc
a00b004c3a2eb9e3e863c361aa2b115260472414
refs/heads/master
1,586,221,905,125
1,544,951,310,000
1,544,951,310,000
157,934,290
0
0
null
null
null
null
UTF-8
Lean
false
false
6,802
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Johannes Hölzl, Mario Carneiro An efficient binary implementation of a (sqrt n) function that returns s s.t. s*s ≤ n ≤ s*s + s + s -/ import data.nat.basic algebra.ordered_group algebra.ring tactic namespace nat theorem sqrt_aux_dec {b} (h : b ≠ 0) : shiftr b 2 < b := begin simp [shiftr_eq_div_pow], apply (nat.div_lt_iff_lt_mul' (dec_trivial : 4 > 0)).2, have := nat.mul_lt_mul_of_pos_left (dec_trivial : 1 < 4) (nat.pos_of_ne_zero h), rwa mul_one at this end def sqrt_aux : ℕ → ℕ → ℕ → ℕ | b r n := if b0 : b = 0 then r else let b' := shiftr b 2 in have b' < b, from sqrt_aux_dec b0, match (n - (r + b : ℕ) : ℤ) with | (n' : ℕ) := sqrt_aux b' (div2 r + b) n' | _ := sqrt_aux b' (div2 r) n end /-- `sqrt n` is the square root of a natural number `n`. If `n` is not a perfect square, it returns the largest `k:ℕ` such that `k*k ≤ n`. -/ def sqrt (n : ℕ) : ℕ := match size n with | 0 := 0 | succ s := sqrt_aux (shiftl 1 (bit0 (div2 s))) 0 n end theorem sqrt_aux_0 (r n) : sqrt_aux 0 r n = r := by rw sqrt_aux; simp local attribute [simp] sqrt_aux_0 theorem sqrt_aux_1 {r n b} (h : b ≠ 0) {n'} (h₂ : r + b + n' = n) : sqrt_aux b r n = sqrt_aux (shiftr b 2) (div2 r + b) n' := by rw sqrt_aux; simp only [h, h₂.symm, int.coe_nat_add, if_false]; rw [add_comm _ (n':ℤ), add_sub_cancel, sqrt_aux._match_1] theorem sqrt_aux_2 {r n b} (h : b ≠ 0) (h₂ : n < r + b) : sqrt_aux b r n = sqrt_aux (shiftr b 2) (div2 r) n := begin rw sqrt_aux; simp only [h, h₂, if_false], cases int.eq_neg_succ_of_lt_zero (sub_lt_zero.2 (int.coe_nat_lt_coe_nat_of_lt h₂)) with k e, rw [e, sqrt_aux._match_1] end private def is_sqrt (n q : ℕ) : Prop := q*q ≤ n ∧ n < (q+1)*(q+1) private lemma sqrt_aux_is_sqrt_lemma (m r n : ℕ) (h₁ : r*r ≤ n) (m') (hm : shiftr (2^m * 2^m) 2 = m') (H1 : n < (r + 2^m) * (r + 2^m) → is_sqrt n (sqrt_aux m' (r * 2^m) (n - r * r))) (H2 : (r + 2^m) * (r + 2^m) ≤ n → is_sqrt n (sqrt_aux m' ((r + 2^m) * 2^m) (n - (r + 2^m) * (r + 2^m)))) : is_sqrt n (sqrt_aux (2^m * 2^m) ((2*r)*2^m) (n - r*r)) := begin have b0 := have b0:_, from ne_of_gt (@pos_pow_of_pos 2 m dec_trivial), nat.mul_ne_zero b0 b0, have lb : n - r * r < 2 * r * 2^m + 2^m * 2^m ↔ n < (r+2^m)*(r+2^m), { rw [nat.sub_lt_right_iff_lt_add h₁], simp [left_distrib, right_distrib, two_mul, mul_comm, mul_assoc] }, have re : div2 (2 * r * 2^m) = r * 2^m, { rw [div2_val, mul_assoc, nat.mul_div_cancel_left _ (dec_trivial:2>0)] }, cases lt_or_ge n ((r+2^m)*(r+2^m)) with hl hl, { rw [sqrt_aux_2 b0 (lb.2 hl), hm, re], apply H1 hl }, { cases le.dest hl with n' e, rw [@sqrt_aux_1 (2 * r * 2^m) (n-r*r) (2^m * 2^m) b0 (n - (r + 2^m) * (r + 2^m)), hm, re, ← right_distrib], { apply H2 hl }, apply eq.symm, apply nat.sub_eq_of_eq_add, rw [← add_assoc, (_ : r*r + _ = _)], exact (nat.add_sub_cancel' hl).symm, simp [left_distrib, right_distrib, two_mul, mul_comm, mul_assoc] }, end private lemma sqrt_aux_is_sqrt (n) : ∀ m r, r*r ≤ n → n < (r + 2^(m+1)) * (r + 2^(m+1)) → is_sqrt n (sqrt_aux (2^m * 2^m) (2*r*2^m) (n - r*r)) | 0 r h₁ h₂ := by apply sqrt_aux_is_sqrt_lemma 0 r n h₁ 0 rfl; intros; simp; [exact ⟨h₁, a⟩, exact ⟨a, h₂⟩] | (m+1) r h₁ h₂ := begin apply sqrt_aux_is_sqrt_lemma (m+1) r n h₁ (2^m * 2^m) (by simp [shiftr, pow_succ, div2_val, mul_comm, mul_left_comm]; repeat {rw @nat.mul_div_cancel_left _ 2 dec_trivial}); intros, { have := sqrt_aux_is_sqrt m r h₁ a, simpa [pow_succ, mul_comm, mul_assoc] }, { rw [pow_succ, mul_two, ← add_assoc] at h₂, have := sqrt_aux_is_sqrt m (r + 2^(m+1)) a h₂, rwa show (r + 2^(m + 1)) * 2^(m+1) = 2 * (r + 2^(m + 1)) * 2^m, by simp [pow_succ, mul_comm, mul_left_comm] } end private lemma sqrt_is_sqrt (n : ℕ) : is_sqrt n (sqrt n) := begin generalize e : size n = s, cases s with s; simp [e, sqrt], { rw [size_eq_zero.1 e, is_sqrt], exact dec_trivial }, { have := sqrt_aux_is_sqrt n (div2 s) 0 (zero_le _), simp [show 2^div2 s * 2^div2 s = shiftl 1 (bit0 (div2 s)), by { generalize: div2 s = x, change bit0 x with x+x, rw [one_shiftl, pow_add] }] at this, apply this, rw [← pow_add, ← mul_two], apply size_le.1, rw e, apply (@div_lt_iff_lt_mul _ _ 2 dec_trivial).1, rw [div2_val], apply lt_succ_self } end theorem sqrt_le (n : ℕ) : sqrt n * sqrt n ≤ n := (sqrt_is_sqrt n).left theorem lt_succ_sqrt (n : ℕ) : n < succ (sqrt n) * succ (sqrt n) := (sqrt_is_sqrt n).right theorem sqrt_le_add (n : ℕ) : n ≤ sqrt n * sqrt n + sqrt n + sqrt n := by rw ← succ_mul; exact le_of_lt_succ (lt_succ_sqrt n) theorem le_sqrt {m n : ℕ} : m ≤ sqrt n ↔ m*m ≤ n := ⟨λ h, le_trans (mul_self_le_mul_self h) (sqrt_le n), λ h, le_of_lt_succ $ mul_self_lt_mul_self_iff.2 $ lt_of_le_of_lt h (lt_succ_sqrt n)⟩ theorem sqrt_lt {m n : ℕ} : sqrt m < n ↔ m < n*n := lt_iff_lt_of_le_iff_le le_sqrt theorem sqrt_le_self (n : ℕ) : sqrt n ≤ n := le_trans (le_mul_self _) (sqrt_le n) theorem sqrt_le_sqrt {m n : ℕ} (h : m ≤ n) : sqrt m ≤ sqrt n := le_sqrt.2 (le_trans (sqrt_le _) h) theorem sqrt_eq_zero {n : ℕ} : sqrt n = 0 ↔ n = 0 := ⟨λ h, eq_zero_of_le_zero $ le_of_lt_succ $ (@sqrt_lt n 1).1 $ by rw [h]; exact dec_trivial, λ e, e.symm ▸ rfl⟩ theorem eq_sqrt {n q} : q = sqrt n ↔ q*q ≤ n ∧ n < (q+1)*(q+1) := ⟨λ e, e.symm ▸ sqrt_is_sqrt n, λ ⟨h₁, h₂⟩, le_antisymm (le_sqrt.2 h₁) (le_of_lt_succ $ sqrt_lt.2 h₂)⟩ theorem le_three_of_sqrt_eq_one {n : ℕ} (h : sqrt n = 1) : n ≤ 3 := le_of_lt_succ $ (@sqrt_lt n 2).1 $ by rw [h]; exact dec_trivial theorem sqrt_lt_self {n : ℕ} (h : n > 1) : sqrt n < n := sqrt_lt.2 $ by have := nat.mul_lt_mul_of_pos_left h (lt_of_succ_lt h); rwa [mul_one] at this theorem sqrt_pos {n : ℕ} : sqrt n > 0 ↔ n > 0 := le_sqrt theorem sqrt_add_eq (n : ℕ) {a : ℕ} (h : a ≤ n + n) : sqrt (n*n + a) = n := le_antisymm (le_of_lt_succ $ sqrt_lt.2 $ by rw [succ_mul, mul_succ, add_succ, add_assoc]; exact lt_succ_of_le (nat.add_le_add_left h _)) (le_sqrt.2 $ nat.le_add_right _ _) theorem sqrt_eq (n : ℕ) : sqrt (n*n) = n := sqrt_add_eq n (zero_le _) theorem sqrt_succ_le_succ_sqrt (n : ℕ) : sqrt n.succ ≤ n.sqrt.succ := le_of_lt_succ $ sqrt_lt.2 $ lt_succ_of_le $ succ_le_succ $ le_trans (sqrt_le_add n) $ add_le_add_right (by refine add_le_add (mul_le_mul_right _ _) _; exact le_add_right _ 2) _ end nat
dd466e26c6295e40c1e05f95551ea1e1b657db96
7b02c598aa57070b4cf4fbfe2416d0479220187f
/archive/smash_old.hlean
fff8b186ca2413845c7954b2f6069114c2aa56df
[ "Apache-2.0" ]
permissive
jdchristensen/Spectral
50d4f0ddaea1484d215ef74be951da6549de221d
6ded2b94d7ae07c4098d96a68f80a9cd3d433eb8
refs/heads/master
1,611,555,010,649
1,496,724,191,000
1,496,724,191,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,339
hlean
/- below are some old tries to compute (A ∧ S¹) directly -/ exit /- smash A S¹ = red_susp A -/ definition red_susp_of_smash_pcircle [unfold 2] (x : smash A S¹*) : red_susp A := begin induction x using smash.elim, { induction b, exact base, exact equator a }, { exact base }, { exact base }, { reflexivity }, { exact circle_elim_constant equator_pt b } end definition smash_pcircle_of_red_susp [unfold 2] (x : red_susp A) : smash A S¹* := begin induction x, { exact pt }, { exact gluel' pt a ⬝ ap (smash.mk a) loop ⬝ gluel' a pt }, { refine !con.right_inv ◾ _ ◾ !con.right_inv, exact ap_is_constant gluer loop ⬝ !con.right_inv } end definition smash_pcircle_of_red_susp_of_smash_pcircle_pt [unfold 3] (a : A) (x : S¹*) : smash_pcircle_of_red_susp (red_susp_of_smash_pcircle (smash.mk a x)) = smash.mk a x := begin induction x, { exact gluel' pt a }, { exact abstract begin apply eq_pathover, refine ap_compose smash_pcircle_of_red_susp _ _ ⬝ph _, refine ap02 _ (elim_loop pt (equator a)) ⬝ !elim_equator ⬝ph _, -- make everything below this a lemma defined by path induction? refine !con_idp⁻¹ ⬝pv _, refine !con.assoc⁻¹ ⬝ph _, apply whisker_bl, apply whisker_lb, apply whisker_tl, apply hrfl end end } end definition concat2o [unfold 10] {A B : Type} {f g h : A → B} {q : f ~ g} {r : g ~ h} {a a' : A} {p : a = a'} (s : q a =[p] q a') (t : r a =[p] r a') : q a ⬝ r a =[p] q a' ⬝ r a' := by induction p; exact idpo definition apd_con_fn [unfold 10] {A B : Type} {f g h : A → B} {q : f ~ g} {r : g ~ h} {a a' : A} (p : a = a') : apd (λa, q a ⬝ r a) p = concat2o (apd q p) (apd r p) := by induction p; reflexivity -- definition apd_con_fn_constant [unfold 10] {A B : Type} {f : A → B} {b b' : B} {q : Πa, f a = b} -- {r : b = b'} {a a' : A} (p : a = a') : -- apd (λa, q a ⬝ r) p = concat2o (apd q p) (pathover_of_eq _ idp) := -- by induction p; reflexivity definition smash_pcircle_pequiv_red [constructor] (A : Type*) : smash A S¹* ≃* red_susp A := begin fapply pequiv_of_equiv, { fapply equiv.MK, { exact red_susp_of_smash_pcircle }, { exact smash_pcircle_of_red_susp }, { exact abstract begin intro x, induction x, { reflexivity }, { apply eq_pathover, apply hdeg_square, refine ap_compose red_susp_of_smash_pcircle _ _ ⬝ ap02 _ !elim_equator ⬝ _ ⬝ !ap_id⁻¹, refine !ap_con ⬝ (!ap_con ⬝ !elim_gluel' ◾ !ap_compose'⁻¹) ◾ !elim_gluel' ⬝ _, esimp, exact !idp_con ⬝ !elim_loop }, { exact sorry } end end }, { intro x, induction x, { exact smash_pcircle_of_red_susp_of_smash_pcircle_pt a b }, { exact gluel pt }, { exact gluer pt }, { apply eq_pathover_id_right, refine ap_compose smash_pcircle_of_red_susp _ _ ⬝ph _, unfold [red_susp_of_smash_pcircle], refine ap02 _ !elim_gluel ⬝ph _, esimp, apply whisker_rt, exact vrfl }, { apply eq_pathover_id_right, refine ap_compose smash_pcircle_of_red_susp _ _ ⬝ph _, unfold [red_susp_of_smash_pcircle], -- not sure why so many implicit arguments are needed here... refine ap02 _ (@smash.elim_gluer A S¹* _ (λa, circle.elim red_susp.base (equator a)) red_susp.base red_susp.base (λa, refl red_susp.base) (circle_elim_constant equator_pt) b) ⬝ph _, apply square_of_eq, induction b, { exact whisker_right _ !con.right_inv }, { apply eq_pathover_dep, refine !apd_con_fn ⬝pho _ ⬝hop !apd_con_fn⁻¹, refine ap (λx, concat2o x _) !rec_loop ⬝pho _ ⬝hop (ap011 concat2o (apd_compose1 (λa b, ap smash_pcircle_of_red_susp b) (circle_elim_constant equator_pt) loop) !apd_constant')⁻¹, exact sorry } }}}, { reflexivity } end /- smash A S¹ = susp A -/ open susp definition psusp_of_smash_pcircle [unfold 2] (x : smash A S¹*) : psusp A := begin induction x using smash.elim, { induction b, exact pt, exact merid a ⬝ (merid pt)⁻¹ }, { exact pt }, { exact pt }, { reflexivity }, { induction b, reflexivity, apply eq_pathover_constant_right, apply hdeg_square, exact !elim_loop ⬝ !con.right_inv } end definition smash_pcircle_of_psusp [unfold 2] (x : psusp A) : smash A S¹* := begin induction x, { exact pt }, { exact pt }, { exact gluel' pt a ⬝ (ap (smash.mk a) loop ⬝ gluel' a pt) }, end -- the definitions below compile, but take a long time to do so and have sorry's in them definition smash_pcircle_of_psusp_of_smash_pcircle_pt [unfold 3] (a : A) (x : S¹*) : smash_pcircle_of_psusp (psusp_of_smash_pcircle (smash.mk a x)) = smash.mk a x := begin induction x, { exact gluel' pt a }, { exact abstract begin apply eq_pathover, refine ap_compose smash_pcircle_of_psusp _ _ ⬝ph _, refine ap02 _ (elim_loop north (merid a ⬝ (merid pt)⁻¹)) ⬝ph _, refine !ap_con ⬝ (!elim_merid ◾ (!ap_inv ⬝ !elim_merid⁻²)) ⬝ph _, -- make everything below this a lemma defined by path induction? exact sorry, -- refine !con_idp⁻¹ ⬝pv _, apply whisker_tl, refine !con.assoc⁻¹ ⬝ph _, -- apply whisker_bl, apply whisker_lb, -- refine !con_idp⁻¹ ⬝pv _, apply whisker_tl, apply hrfl -- refine !con_idp⁻¹ ⬝pv _, apply whisker_tl, -- refine !con.assoc⁻¹ ⬝ph _, apply whisker_bl, apply whisker_lb, apply hrfl -- apply square_of_eq, rewrite [+con.assoc], apply whisker_left, apply whisker_left, -- symmetry, apply con_eq_of_eq_inv_con, esimp, apply con_eq_of_eq_con_inv, -- refine _⁻² ⬝ !con_inv, refine _ ⬝ !con.assoc, -- refine _ ⬝ whisker_right _ !inv_con_cancel_right⁻¹, refine _ ⬝ !con.right_inv⁻¹, -- refine !con.right_inv ◾ _, refine _ ◾ !con.right_inv, -- refine !ap_mk_right ⬝ !con.right_inv end end } end -- definition smash_pcircle_of_psusp_of_smash_pcircle_gluer_base (b : S¹*) -- : square (smash_pcircle_of_psusp_of_smash_pcircle_pt (Point A) b) -- (gluer pt) -- (ap smash_pcircle_of_psusp (ap (λ a, psusp_of_smash_pcircle a) (gluer b))) -- (gluer b) := -- begin -- refine ap02 _ !elim_gluer ⬝ph _, -- induction b, -- { apply square_of_eq, exact whisker_right _ !con.right_inv }, -- { apply square_pathover', exact sorry } -- end exit definition smash_pcircle_pequiv [constructor] (A : Type*) : smash A S¹* ≃* psusp A := begin fapply pequiv_of_equiv, { fapply equiv.MK, { exact psusp_of_smash_pcircle }, { exact smash_pcircle_of_psusp }, { exact abstract begin intro x, induction x, { reflexivity }, { exact merid pt }, { apply eq_pathover_id_right, refine ap_compose psusp_of_smash_pcircle _ _ ⬝ph _, refine ap02 _ !elim_merid ⬝ph _, rewrite [↑gluel', +ap_con, +ap_inv, -ap_compose'], refine (_ ◾ _⁻² ◾ _ ◾ (_ ◾ _⁻²)) ⬝ph _, rotate 5, do 2 (unfold [psusp_of_smash_pcircle]; apply elim_gluel), esimp, apply elim_loop, do 2 (unfold [psusp_of_smash_pcircle]; apply elim_gluel), refine idp_con (merid a ⬝ (merid (Point A))⁻¹) ⬝ph _, apply square_of_eq, refine !idp_con ⬝ _⁻¹, apply inv_con_cancel_right } end end }, { intro x, induction x using smash.rec, { exact smash_pcircle_of_psusp_of_smash_pcircle_pt a b }, { exact gluel pt }, { exact gluer pt }, { apply eq_pathover_id_right, refine ap_compose smash_pcircle_of_psusp _ _ ⬝ph _, unfold [psusp_of_smash_pcircle], refine ap02 _ !elim_gluel ⬝ph _, esimp, apply whisker_rt, exact vrfl }, { apply eq_pathover_id_right, refine ap_compose smash_pcircle_of_psusp _ _ ⬝ph _, unfold [psusp_of_smash_pcircle], refine ap02 _ !elim_gluer ⬝ph _, induction b, { apply square_of_eq, exact whisker_right _ !con.right_inv }, { exact sorry} }}}, { reflexivity } end end smash
f8c55ef2e0b52f1739e75a6b5b3a808d4e9df70b
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/hott/algebra/ordered_ring.hlean
7bbd266e9f2d408f8e20cb1249c884ce90b82eef
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
22,088
hlean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad Here an "ordered_ring" is partially ordered ring, which is ordered with respect to both a weak order and an associated strict order. Our numeric structures (int, rat, and real) will be instances of "linear_ordered_comm_ring". This development is modeled after Isabelle's library. Ported from the standard library -/ import algebra.ordered_group algebra.ring open core namespace algebra variable {A : Type} definition absurd_a_lt_a {B : Type} {a : A} [s : strict_order A] (H : a < a) : B := absurd H (lt.irrefl a) structure ordered_semiring [class] (A : Type) extends has_mul A, has_zero A, has_lt A, -- TODO: remove hack for improving performance semiring A, ordered_cancel_comm_monoid A, zero_ne_one_class A := (mul_le_mul_of_nonneg_left: Πa b c, le a b → le zero c → le (mul c a) (mul c b)) (mul_le_mul_of_nonneg_right: Πa b c, le a b → le zero c → le (mul a c) (mul b c)) (mul_lt_mul_of_pos_left: Πa b c, lt a b → lt zero c → lt (mul c a) (mul c b)) (mul_lt_mul_of_pos_right: Πa b c, lt a b → lt zero c → lt (mul a c) (mul b c)) section variable [s : ordered_semiring A] variables (a b c d e : A) include s definition mul_le_mul_of_nonneg_left {a b c : A} (Hab : a ≤ b) (Hc : 0 ≤ c) : c * a ≤ c * b := !ordered_semiring.mul_le_mul_of_nonneg_left Hab Hc definition mul_le_mul_of_nonneg_right {a b c : A} (Hab : a ≤ b) (Hc : 0 ≤ c) : a * c ≤ b * c := !ordered_semiring.mul_le_mul_of_nonneg_right Hab Hc -- TODO: there are four variations, depending on which variables we assume to be nonneg definition mul_le_mul {a b c d : A} (Hac : a ≤ c) (Hbd : b ≤ d) (nn_b : 0 ≤ b) (nn_c : 0 ≤ c) : a * b ≤ c * d := calc a * b ≤ c * b : mul_le_mul_of_nonneg_right Hac nn_b ... ≤ c * d : mul_le_mul_of_nonneg_left Hbd nn_c definition mul_nonneg {a b : A} (Ha : a ≥ 0) (Hb : b ≥ 0) : a * b ≥ 0 := begin have H : 0 * b ≤ a * b, from mul_le_mul_of_nonneg_right Ha Hb, rewrite zero_mul at H, exact H end definition mul_nonpos_of_nonneg_of_nonpos {a b : A} (Ha : a ≥ 0) (Hb : b ≤ 0) : a * b ≤ 0 := begin have H : a * b ≤ a * 0, from mul_le_mul_of_nonneg_left Hb Ha, rewrite mul_zero at H, exact H end definition mul_nonpos_of_nonpos_of_nonneg {a b : A} (Ha : a ≤ 0) (Hb : b ≥ 0) : a * b ≤ 0 := begin have H : a * b ≤ 0 * b, from mul_le_mul_of_nonneg_right Ha Hb, rewrite zero_mul at H, exact H end definition mul_lt_mul_of_pos_left {a b c : A} (Hab : a < b) (Hc : 0 < c) : c * a < c * b := !ordered_semiring.mul_lt_mul_of_pos_left Hab Hc definition mul_lt_mul_of_pos_right {a b c : A} (Hab : a < b) (Hc : 0 < c) : a * c < b * c := !ordered_semiring.mul_lt_mul_of_pos_right Hab Hc -- TODO: once again, there are variations definition mul_lt_mul {a b c d : A} (Hac : a < c) (Hbd : b ≤ d) (pos_b : 0 < b) (nn_c : 0 ≤ c) : a * b < c * d := calc a * b < c * b : mul_lt_mul_of_pos_right Hac pos_b ... ≤ c * d : mul_le_mul_of_nonneg_left Hbd nn_c definition mul_pos {a b : A} (Ha : a > 0) (Hb : b > 0) : a * b > 0 := begin have H : 0 * b < a * b, from mul_lt_mul_of_pos_right Ha Hb, rewrite zero_mul at H, exact H end definition mul_neg_of_pos_of_neg {a b : A} (Ha : a > 0) (Hb : b < 0) : a * b < 0 := begin have H : a * b < a * 0, from mul_lt_mul_of_pos_left Hb Ha, rewrite mul_zero at H, exact H end definition mul_neg_of_neg_of_pos {a b : A} (Ha : a < 0) (Hb : b > 0) : a * b < 0 := begin have H : a * b < 0 * b, from mul_lt_mul_of_pos_right Ha Hb, rewrite zero_mul at H, exact H end end structure linear_ordered_semiring [class] (A : Type) extends ordered_semiring A, linear_strong_order_pair A section variable [s : linear_ordered_semiring A] variables {a b c : A} include s definition lt_of_mul_lt_mul_left (H : c * a < c * b) (Hc : c ≥ 0) : a < b := lt_of_not_le (assume H1 : b ≤ a, have H2 : c * b ≤ c * a, from mul_le_mul_of_nonneg_left H1 Hc, not_lt_of_le H2 H) definition lt_of_mul_lt_mul_right (H : a * c < b * c) (Hc : c ≥ 0) : a < b := lt_of_not_le (assume H1 : b ≤ a, have H2 : b * c ≤ a * c, from mul_le_mul_of_nonneg_right H1 Hc, not_lt_of_le H2 H) definition le_of_mul_le_mul_left (H : c * a ≤ c * b) (Hc : c > 0) : a ≤ b := le_of_not_lt (assume H1 : b < a, have H2 : c * b < c * a, from mul_lt_mul_of_pos_left H1 Hc, not_le_of_lt H2 H) definition le_of_mul_le_mul_right (H : a * c ≤ b * c) (Hc : c > 0) : a ≤ b := le_of_not_lt (assume H1 : b < a, have H2 : b * c < a * c, from mul_lt_mul_of_pos_right H1 Hc, not_le_of_lt H2 H) definition pos_of_mul_pos_left (H : 0 < a * b) (H1 : 0 ≤ a) : 0 < b := lt_of_not_le (assume H2 : b ≤ 0, have H3 : a * b ≤ 0, from mul_nonpos_of_nonneg_of_nonpos H1 H2, not_lt_of_le H3 H) definition pos_of_mul_pos_right (H : 0 < a * b) (H1 : 0 ≤ b) : 0 < a := lt_of_not_le (assume H2 : a ≤ 0, have H3 : a * b ≤ 0, from mul_nonpos_of_nonpos_of_nonneg H2 H1, not_lt_of_le H3 H) end structure ordered_ring [class] (A : Type) extends ring A, ordered_comm_group A, zero_ne_one_class A := (mul_nonneg : Πa b, le zero a → le zero b → le zero (mul a b)) (mul_pos : Πa b, lt zero a → lt zero b → lt zero (mul a b)) definition ordered_ring.mul_le_mul_of_nonneg_left [s : ordered_ring A] {a b c : A} (Hab : a ≤ b) (Hc : 0 ≤ c) : c * a ≤ c * b := have H1 : 0 ≤ b - a, from iff.elim_right !sub_nonneg_iff_le Hab, assert H2 : 0 ≤ c * (b - a), from ordered_ring.mul_nonneg _ _ Hc H1, begin rewrite mul_sub_left_distrib at H2, exact (iff.mp !sub_nonneg_iff_le H2) end definition ordered_ring.mul_le_mul_of_nonneg_right [s : ordered_ring A] {a b c : A} (Hab : a ≤ b) (Hc : 0 ≤ c) : a * c ≤ b * c := have H1 : 0 ≤ b - a, from iff.elim_right !sub_nonneg_iff_le Hab, assert H2 : 0 ≤ (b - a) * c, from ordered_ring.mul_nonneg _ _ H1 Hc, begin rewrite mul_sub_right_distrib at H2, exact (iff.mp !sub_nonneg_iff_le H2) end definition ordered_ring.mul_lt_mul_of_pos_left [s : ordered_ring A] {a b c : A} (Hab : a < b) (Hc : 0 < c) : c * a < c * b := have H1 : 0 < b - a, from iff.elim_right !sub_pos_iff_lt Hab, assert H2 : 0 < c * (b - a), from ordered_ring.mul_pos _ _ Hc H1, begin rewrite mul_sub_left_distrib at H2, exact (iff.mp !sub_pos_iff_lt H2) end definition ordered_ring.mul_lt_mul_of_pos_right [s : ordered_ring A] {a b c : A} (Hab : a < b) (Hc : 0 < c) : a * c < b * c := have H1 : 0 < b - a, from iff.elim_right !sub_pos_iff_lt Hab, assert H2 : 0 < (b - a) * c, from ordered_ring.mul_pos _ _ H1 Hc, begin rewrite mul_sub_right_distrib at H2, exact (iff.mp !sub_pos_iff_lt H2) end definition ordered_ring.to_ordered_semiring [instance] [reducible] [s : ordered_ring A] : ordered_semiring A := ⦃ ordered_semiring, s, mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add.left_cancel A _, add_right_cancel := @add.right_cancel A _, le_of_add_le_add_left := @le_of_add_le_add_left A _, mul_le_mul_of_nonneg_left := @ordered_ring.mul_le_mul_of_nonneg_left A _, mul_le_mul_of_nonneg_right := @ordered_ring.mul_le_mul_of_nonneg_right A _, mul_lt_mul_of_pos_left := @ordered_ring.mul_lt_mul_of_pos_left A _, mul_lt_mul_of_pos_right := @ordered_ring.mul_lt_mul_of_pos_right A _ ⦄ section variable [s : ordered_ring A] variables {a b c : A} include s definition mul_le_mul_of_nonpos_left (H : b ≤ a) (Hc : c ≤ 0) : c * a ≤ c * b := have Hc' : -c ≥ 0, from iff.mpr !neg_nonneg_iff_nonpos Hc, assert H1 : -c * b ≤ -c * a, from mul_le_mul_of_nonneg_left H Hc', have H2 : -(c * b) ≤ -(c * a), begin rewrite [-*neg_mul_eq_neg_mul at H1], exact H1 end, iff.mp !neg_le_neg_iff_le H2 definition mul_le_mul_of_nonpos_right (H : b ≤ a) (Hc : c ≤ 0) : a * c ≤ b * c := have Hc' : -c ≥ 0, from iff.mpr !neg_nonneg_iff_nonpos Hc, assert H1 : b * -c ≤ a * -c, from mul_le_mul_of_nonneg_right H Hc', have H2 : -(b * c) ≤ -(a * c), begin rewrite [-*neg_mul_eq_mul_neg at H1], exact H1 end, iff.mp !neg_le_neg_iff_le H2 definition mul_nonneg_of_nonpos_of_nonpos (Ha : a ≤ 0) (Hb : b ≤ 0) : 0 ≤ a * b := begin have H : 0 * b ≤ a * b, from mul_le_mul_of_nonpos_right Ha Hb, rewrite zero_mul at H, exact H end definition mul_lt_mul_of_neg_left (H : b < a) (Hc : c < 0) : c * a < c * b := have Hc' : -c > 0, from iff.mpr !neg_pos_iff_neg Hc, assert H1 : -c * b < -c * a, from mul_lt_mul_of_pos_left H Hc', have H2 : -(c * b) < -(c * a), begin rewrite [-*neg_mul_eq_neg_mul at H1], exact H1 end, iff.mp !neg_lt_neg_iff_lt H2 definition mul_lt_mul_of_neg_right (H : b < a) (Hc : c < 0) : a * c < b * c := have Hc' : -c > 0, from iff.mpr !neg_pos_iff_neg Hc, assert H1 : b * -c < a * -c, from mul_lt_mul_of_pos_right H Hc', have H2 : -(b * c) < -(a * c), begin rewrite [-*neg_mul_eq_mul_neg at H1], exact H1 end, iff.mp !neg_lt_neg_iff_lt H2 definition mul_pos_of_neg_of_neg (Ha : a < 0) (Hb : b < 0) : 0 < a * b := begin have H : 0 * b < a * b, from mul_lt_mul_of_neg_right Ha Hb, rewrite zero_mul at H, exact H end end -- TODO: we can eliminate mul_pos_of_pos, but now it is not worth the effort to redeclare the -- class instance structure linear_ordered_ring [class] (A : Type) extends ordered_ring A, linear_strong_order_pair A -- print fields linear_ordered_semiring definition linear_ordered_ring.to_linear_ordered_semiring [instance] [reducible] [s : linear_ordered_ring A] : linear_ordered_semiring A := ⦃ linear_ordered_semiring, s, mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add.left_cancel A _, add_right_cancel := @add.right_cancel A _, le_of_add_le_add_left := @le_of_add_le_add_left A _, mul_le_mul_of_nonneg_left := @mul_le_mul_of_nonneg_left A _, mul_le_mul_of_nonneg_right := @mul_le_mul_of_nonneg_right A _, mul_lt_mul_of_pos_left := @mul_lt_mul_of_pos_left A _, mul_lt_mul_of_pos_right := @mul_lt_mul_of_pos_right A _, le_total := linear_ordered_ring.le_total ⦄ structure linear_ordered_comm_ring [class] (A : Type) extends linear_ordered_ring A, comm_monoid A definition linear_ordered_comm_ring.eq_zero_or_eq_zero_of_mul_eq_zero [s : linear_ordered_comm_ring A] {a b : A} (H : a * b = 0) : a = 0 ⊎ b = 0 := lt.by_cases (assume Ha : 0 < a, lt.by_cases (assume Hb : 0 < b, begin have H1 : 0 < a * b, from mul_pos Ha Hb, rewrite H at H1, apply absurd_a_lt_a H1 end) (assume Hb : 0 = b, sum.inr (Hb⁻¹)) (assume Hb : 0 > b, begin have H1 : 0 > a * b, from mul_neg_of_pos_of_neg Ha Hb, rewrite H at H1, apply absurd_a_lt_a H1 end)) (assume Ha : 0 = a, sum.inl (Ha⁻¹)) (assume Ha : 0 > a, lt.by_cases (assume Hb : 0 < b, begin have H1 : 0 > a * b, from mul_neg_of_neg_of_pos Ha Hb, rewrite H at H1, apply absurd_a_lt_a H1 end) (assume Hb : 0 = b, sum.inr (Hb⁻¹)) (assume Hb : 0 > b, begin have H1 : 0 < a * b, from mul_pos_of_neg_of_neg Ha Hb, rewrite H at H1, apply absurd_a_lt_a H1 end)) -- Linearity implies no zero divisors. Doesn't need commutativity. definition linear_ordered_comm_ring.to_integral_domain [instance] [reducible] [s: linear_ordered_comm_ring A] : integral_domain A := ⦃ integral_domain, s, eq_zero_or_eq_zero_of_mul_eq_zero := @linear_ordered_comm_ring.eq_zero_or_eq_zero_of_mul_eq_zero A s ⦄ section variable [s : linear_ordered_ring A] variables (a b c : A) include s definition mul_self_nonneg : a * a ≥ 0 := sum.rec_on (le.total 0 a) (assume H : a ≥ 0, mul_nonneg H H) (assume H : a ≤ 0, mul_nonneg_of_nonpos_of_nonpos H H) definition zero_le_one : 0 ≤ (1:A) := one_mul 1 ▸ mul_self_nonneg (1 : A) definition zero_lt_one : 0 < (1:A) := lt_of_le_of_ne zero_le_one zero_ne_one definition pos_and_pos_or_neg_and_neg_of_mul_pos {a b : A} (Hab : a * b > 0) : (a > 0 × b > 0) ⊎ (a < 0 × b < 0) := lt.by_cases (assume Ha : 0 < a, lt.by_cases (assume Hb : 0 < b, sum.inl (pair Ha Hb)) (assume Hb : 0 = b, begin rewrite [-Hb at Hab, mul_zero at Hab], apply absurd_a_lt_a Hab end) (assume Hb : b < 0, absurd Hab (lt.asymm (mul_neg_of_pos_of_neg Ha Hb)))) (assume Ha : 0 = a, begin rewrite [-Ha at Hab, zero_mul at Hab], apply absurd_a_lt_a Hab end) (assume Ha : a < 0, lt.by_cases (assume Hb : 0 < b, absurd Hab (lt.asymm (mul_neg_of_neg_of_pos Ha Hb))) (assume Hb : 0 = b, begin rewrite [-Hb at Hab, mul_zero at Hab], apply absurd_a_lt_a Hab end) (assume Hb : b < 0, sum.inr (pair Ha Hb))) definition gt_of_mul_lt_mul_neg_left {a b c : A} (H : c * a < c * b) (Hc : c ≤ 0) : a > b := have nhc : -c ≥ 0, from neg_nonneg_of_nonpos Hc, have H2 : -(c * b) < -(c * a), from iff.mpr (neg_lt_neg_iff_lt _ _) H, have H3 : (-c) * b < (-c) * a, from calc (-c) * b = - (c * b) : neg_mul_eq_neg_mul ... < -(c * a) : H2 ... = (-c) * a : neg_mul_eq_neg_mul, lt_of_mul_lt_mul_left H3 nhc definition zero_gt_neg_one : -1 < (0 : A) := neg_zero ▸ (neg_lt_neg zero_lt_one) end /- TODO: Isabelle's library has all kinds of cancelation rules for the simplifier. Search on mult_le_cancel_right1 in Rings.thy. -/ structure decidable_linear_ordered_comm_ring [class] (A : Type) extends linear_ordered_comm_ring A, decidable_linear_ordered_comm_group A section variable [s : decidable_linear_ordered_comm_ring A] variables {a b c : A} include s definition sign (a : A) : A := lt.cases a 0 (-1) 0 1 definition sign_of_neg (H : a < 0) : sign a = -1 := lt.cases_of_lt H definition sign_zero : sign 0 = (0:A) := lt.cases_of_eq rfl definition sign_of_pos (H : a > 0) : sign a = 1 := lt.cases_of_gt H definition sign_one : sign 1 = (1:A) := sign_of_pos zero_lt_one definition sign_neg_one : sign (-1) = -(1:A) := sign_of_neg (neg_neg_of_pos zero_lt_one) definition sign_sign (a : A) : sign (sign a) = sign a := lt.by_cases (assume H : a > 0, calc sign (sign a) = sign 1 : by rewrite (sign_of_pos H) ... = 1 : by rewrite sign_one ... = sign a : by rewrite (sign_of_pos H)) (assume H : 0 = a, calc sign (sign a) = sign (sign 0) : by rewrite H ... = sign 0 : by rewrite sign_zero at {1} ... = sign a : by rewrite -H) (assume H : a < 0, calc sign (sign a) = sign (-1) : by rewrite (sign_of_neg H) ... = -1 : by rewrite sign_neg_one ... = sign a : by rewrite (sign_of_neg H)) definition pos_of_sign_eq_one (H : sign a = 1) : a > 0 := lt.by_cases (assume H1 : 0 < a, H1) (assume H1 : 0 = a, begin rewrite [-H1 at H, sign_zero at H], apply absurd H zero_ne_one end) (assume H1 : 0 > a, have H2 : -1 = 1, from (sign_of_neg H1)⁻¹ ⬝ H, absurd ((eq_zero_of_neg_eq H2)⁻¹) zero_ne_one) definition eq_zero_of_sign_eq_zero (H : sign a = 0) : a = 0 := lt.by_cases (assume H1 : 0 < a, absurd (H⁻¹ ⬝ sign_of_pos H1) zero_ne_one) (assume H1 : 0 = a, H1⁻¹) (assume H1 : 0 > a, have H2 : 0 = -1, from H⁻¹ ⬝ sign_of_neg H1, have H3 : 1 = 0, from eq_neg_of_eq_neg H2 ⬝ neg_zero, absurd (H3⁻¹) zero_ne_one) definition neg_of_sign_eq_neg_one (H : sign a = -1) : a < 0 := lt.by_cases (assume H1 : 0 < a, have H2 : -1 = 1, from H⁻¹ ⬝ (sign_of_pos H1), absurd ((eq_zero_of_neg_eq H2)⁻¹) zero_ne_one) (assume H1 : 0 = a, have H2 : (0:A) = -1, begin rewrite [-H1 at H, sign_zero at H], exact H end, have H3 : 1 = 0, from eq_neg_of_eq_neg H2 ⬝ neg_zero, absurd (H3⁻¹) zero_ne_one) (assume H1 : 0 > a, H1) definition sign_neg (a : A) : sign (-a) = -(sign a) := lt.by_cases (assume H1 : 0 < a, calc sign (-a) = -1 : sign_of_neg (neg_neg_of_pos H1) ... = -(sign a) : by rewrite (sign_of_pos H1)) (assume H1 : 0 = a, calc sign (-a) = sign (-0) : by rewrite H1 ... = sign 0 : by rewrite neg_zero ... = 0 : by rewrite sign_zero ... = -0 : by rewrite neg_zero ... = -(sign 0) : by rewrite sign_zero ... = -(sign a) : by rewrite -H1) (assume H1 : 0 > a, calc sign (-a) = 1 : sign_of_pos (neg_pos_of_neg H1) ... = -(-1) : by rewrite neg_neg ... = -(sign a) : sign_of_neg H1) definition sign_mul (a b : A) : sign (a * b) = sign a * sign b := lt.by_cases (assume z_lt_a : 0 < a, lt.by_cases (assume z_lt_b : 0 < b, by rewrite [sign_of_pos z_lt_a, sign_of_pos z_lt_b, sign_of_pos (mul_pos z_lt_a z_lt_b), one_mul]) (assume z_eq_b : 0 = b, by rewrite [-z_eq_b, mul_zero, *sign_zero, mul_zero]) (assume z_gt_b : 0 > b, by rewrite [sign_of_pos z_lt_a, sign_of_neg z_gt_b, sign_of_neg (mul_neg_of_pos_of_neg z_lt_a z_gt_b), one_mul])) (assume z_eq_a : 0 = a, by rewrite [-z_eq_a, zero_mul, *sign_zero, zero_mul]) (assume z_gt_a : 0 > a, lt.by_cases (assume z_lt_b : 0 < b, by rewrite [sign_of_neg z_gt_a, sign_of_pos z_lt_b, sign_of_neg (mul_neg_of_neg_of_pos z_gt_a z_lt_b), mul_one]) (assume z_eq_b : 0 = b, by rewrite [-z_eq_b, mul_zero, *sign_zero, mul_zero]) (assume z_gt_b : 0 > b, by rewrite [sign_of_neg z_gt_a, sign_of_neg z_gt_b, sign_of_pos (mul_pos_of_neg_of_neg z_gt_a z_gt_b), neg_mul_neg, one_mul])) definition abs_eq_sign_mul (a : A) : abs a = sign a * a := lt.by_cases (assume H1 : 0 < a, calc abs a = a : abs_of_pos H1 ... = 1 * a : by rewrite one_mul ... = sign a * a : by rewrite (sign_of_pos H1)) (assume H1 : 0 = a, calc abs a = abs 0 : by rewrite H1 ... = 0 : by rewrite abs_zero ... = 0 * a : by rewrite zero_mul ... = sign 0 * a : by rewrite sign_zero ... = sign a * a : by rewrite H1) (assume H1 : a < 0, calc abs a = -a : abs_of_neg H1 ... = -1 * a : by rewrite neg_eq_neg_one_mul ... = sign a * a : by rewrite (sign_of_neg H1)) definition eq_sign_mul_abs (a : A) : a = sign a * abs a := lt.by_cases (assume H1 : 0 < a, calc a = abs a : abs_of_pos H1 ... = 1 * abs a : by rewrite one_mul ... = sign a * abs a : by rewrite (sign_of_pos H1)) (assume H1 : 0 = a, calc a = 0 : H1⁻¹ ... = 0 * abs a : by rewrite zero_mul ... = sign 0 * abs a : by rewrite sign_zero ... = sign a * abs a : by rewrite H1) (assume H1 : a < 0, calc a = -(-a) : by rewrite neg_neg ... = -abs a : by rewrite (abs_of_neg H1) ... = -1 * abs a : by rewrite neg_eq_neg_one_mul ... = sign a * abs a : by rewrite (sign_of_neg H1)) definition abs_dvd_iff (a b : A) : abs a ∣ b ↔ a ∣ b := abs.by_cases !iff.refl !neg_dvd_iff_dvd definition dvd_abs_iff (a b : A) : a ∣ abs b ↔ a ∣ b := abs.by_cases !iff.refl !dvd_neg_iff_dvd definition abs_mul (a b : A) : abs (a * b) = abs a * abs b := sum.rec_on (le.total 0 a) (assume H1 : 0 ≤ a, sum.rec_on (le.total 0 b) (assume H2 : 0 ≤ b, calc abs (a * b) = a * b : abs_of_nonneg (mul_nonneg H1 H2) ... = abs a * b : by rewrite (abs_of_nonneg H1) ... = abs a * abs b : by rewrite (abs_of_nonneg H2)) (assume H2 : b ≤ 0, calc abs (a * b) = -(a * b) : abs_of_nonpos (mul_nonpos_of_nonneg_of_nonpos H1 H2) ... = a * -b : by rewrite neg_mul_eq_mul_neg ... = abs a * -b : by rewrite (abs_of_nonneg H1) ... = abs a * abs b : by rewrite (abs_of_nonpos H2))) (assume H1 : a ≤ 0, sum.rec_on (le.total 0 b) (assume H2 : 0 ≤ b, calc abs (a * b) = -(a * b) : abs_of_nonpos (mul_nonpos_of_nonpos_of_nonneg H1 H2) ... = -a * b : by rewrite neg_mul_eq_neg_mul ... = abs a * b : by rewrite (abs_of_nonpos H1) ... = abs a * abs b : by rewrite (abs_of_nonneg H2)) (assume H2 : b ≤ 0, calc abs (a * b) = a * b : abs_of_nonneg (mul_nonneg_of_nonpos_of_nonpos H1 H2) ... = -a * -b : by rewrite neg_mul_neg ... = abs a * -b : by rewrite (abs_of_nonpos H1) ... = abs a * abs b : by rewrite (abs_of_nonpos H2))) definition abs_mul_self (a : A) : abs a * abs a = a * a := abs.by_cases rfl !neg_mul_neg end /- TODO: Multiplication and one, starting with mult_right_le_one_le. -/ end algebra
e6ef49365364dce1a19604882dd7673a008e4efd
57c233acf9386e610d99ed20ef139c5f97504ba3
/archive/sensitivity.lean
330db71772701278167fd079162d46ac09d31c78
[ "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
15,635
lean
/- Copyright (c) 2019 Reid Barton, Johan Commelin, Jesse Han, Chris Hughes, Robert Y. Lewis, Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Johan Commelin, Jesse Han, Chris Hughes, Robert Y. Lewis, Patrick Massot -/ import tactic.fin_cases import tactic.apply_fun import linear_algebra.finite_dimensional import linear_algebra.dual import analysis.normed_space.basic import data.real.sqrt /-! # Huang's sensitivity theorem A formalization of Hao Huang's sensitivity theorem: in the hypercube of dimension n ≥ 1, if one colors more than half the vertices then at least one vertex has at least √n colored neighbors. A fun summer collaboration by Reid Barton, Johan Commelin, Jesse Han, Chris Hughes, Robert Y. Lewis, and Patrick Massot, based on Don Knuth's account of the story (https://www.cs.stanford.edu/~knuth/papers/huang.pdf), using the Lean theorem prover (https://leanprover.github.io/), by Leonardo de Moura at Microsoft Research, and his collaborators (https://leanprover.github.io/people/), and using Lean's user maintained mathematics library (https://github.com/leanprover-community/mathlib). The project was developed at https://github.com/leanprover-community/lean-sensitivity and is now archived at https://github.com/leanprover-community/mathlib/blob/master/archive/sensitivity.lean -/ /-! The next two lines assert we do not want to give a constructive proof, but rather use classical logic. -/ noncomputable theory open_locale classical /-! We also want to use the notation `∑` for sums. -/ open_locale big_operators notation `√` := real.sqrt open function bool linear_map fintype finite_dimensional dual_pair /-! ### The hypercube Notations: - `ℕ` denotes natural numbers (including zero). - `fin n` = {0, ⋯ , n - 1}. - `bool` = {`tt`, `ff`}. -/ /-- The hypercube in dimension `n`. -/ @[derive [inhabited, fintype]] def Q (n : ℕ) := fin n → bool /-- The projection from `Q (n + 1)` to `Q n` forgetting the first value (ie. the image of zero). -/ def π {n : ℕ} : Q (n + 1) → Q n := λ p, p ∘ fin.succ namespace Q /-! `n` will always denote a natural number. -/ variable (n : ℕ) /-- `Q 0` has a unique element. -/ instance : unique (Q 0) := ⟨⟨λ _, tt⟩, by { intro, ext x, fin_cases x }⟩ /-- `Q n` has 2^n elements. -/ lemma card : card (Q n) = 2^n := by simp [Q] /-! Until the end of this namespace, `n` will be an implicit argument (still a natural number). -/ variable {n} lemma succ_n_eq (p q : Q (n+1)) : p = q ↔ (p 0 = q 0 ∧ π p = π q) := begin split, { rintro rfl, exact ⟨rfl, rfl⟩, }, { rintros ⟨h₀, h⟩, ext x, by_cases hx : x = 0, { rwa hx }, { rw ← fin.succ_pred x hx, convert congr_fun h (fin.pred x hx) } } end /-- The adjacency relation defining the graph structure on `Q n`: `p.adjacent q` if there is an edge from `p` to `q` in `Q n`. -/ def adjacent {n : ℕ} (p : Q n) : set (Q n) := λ q, ∃! i, p i ≠ q i /-- In `Q 0`, no two vertices are adjacent. -/ lemma not_adjacent_zero (p q : Q 0) : ¬ p.adjacent q := by rintros ⟨v, _⟩; apply fin_zero_elim v /-- If `p` and `q` in `Q (n+1)` have different values at zero then they are adjacent iff their projections to `Q n` are equal. -/ lemma adj_iff_proj_eq {p q : Q (n+1)} (h₀ : p 0 ≠ q 0) : p.adjacent q ↔ π p = π q := begin split, { rintros ⟨i, h_eq, h_uni⟩, ext x, by_contradiction hx, apply fin.succ_ne_zero x, rw [h_uni _ hx, h_uni _ h₀] }, { intro heq, use [0, h₀], intros y hy, contrapose! hy, rw ←fin.succ_pred _ hy, apply congr_fun heq } end /-- If `p` and `q` in `Q (n+1)` have the same value at zero then they are adjacent iff their projections to `Q n` are adjacent. -/ lemma adj_iff_proj_adj {p q : Q (n+1)} (h₀ : p 0 = q 0) : p.adjacent q ↔ (π p).adjacent (π q) := begin split, { rintros ⟨i, h_eq, h_uni⟩, have h_i : i ≠ 0, from λ h_i, absurd h₀ (by rwa h_i at h_eq), use [i.pred h_i, show p (fin.succ (fin.pred i _)) ≠ q (fin.succ (fin.pred i _)), by rwa fin.succ_pred], intros y hy, simp [eq.symm (h_uni _ hy)] }, { rintros ⟨i, h_eq, h_uni⟩, use [i.succ, h_eq], intros y hy, rw [←fin.pred_inj, fin.pred_succ], { apply h_uni, change p (fin.pred _ _).succ ≠ q (fin.pred _ _).succ, simp [hy] }, { contrapose! hy, rw [hy, h₀] }, { apply fin.succ_ne_zero } } end @[symm] lemma adjacent.symm {p q : Q n} : p.adjacent q ↔ q.adjacent p := by simp only [adjacent, ne_comm] end Q /-! ### The vector space -/ /-- The free vector space on vertices of a hypercube, defined inductively. -/ def V : ℕ → Type | 0 := ℝ | (n+1) := V n × V n namespace V variables (n : ℕ) /-! `V n` is a real vector space whose equality relation is computable. -/ instance : decidable_eq (V n) := by { induction n ; { dunfold V, resetI, apply_instance } } instance : add_comm_group (V n) := by { induction n ; { dunfold V, resetI, apply_instance } } instance : module ℝ (V n) := by { induction n ; { dunfold V, resetI, apply_instance } } end V /-- The basis of `V` indexed by the hypercube, defined inductively. -/ noncomputable def e : Π {n}, Q n → V n | 0 := λ _, (1:ℝ) | (n+1) := λ x, cond (x 0) (e (π x), 0) (0, e (π x)) @[simp] lemma e_zero_apply (x : Q 0) : e x = (1 : ℝ) := rfl /-- The dual basis to `e`, defined inductively. -/ noncomputable def ε : Π {n : ℕ} (p : Q n), V n →ₗ[ℝ] ℝ | 0 _ := linear_map.id | (n+1) p := cond (p 0) ((ε $ π p).comp $ linear_map.fst _ _ _) ((ε $ π p).comp $ linear_map.snd _ _ _) variable {n : ℕ} lemma duality (p q : Q n) : ε p (e q) = if p = q then 1 else 0 := begin induction n with n IH, { rw (show p = q, from subsingleton.elim p q), dsimp [ε, e], simp }, { dsimp [ε, e], cases hp : p 0 ; cases hq : q 0, all_goals { repeat {rw cond_tt}, repeat {rw cond_ff}, simp only [linear_map.fst_apply, linear_map.snd_apply, linear_map.comp_apply, IH], try { congr' 1, rw Q.succ_n_eq, finish }, try { erw (ε _).map_zero, have : p ≠ q, { intro h, rw p.succ_n_eq q at h, finish }, simp [this] } } } end /-- Any vector in `V n` annihilated by all `ε p`'s is zero. -/ lemma epsilon_total {v : V n} (h : ∀ p : Q n, (ε p) v = 0) : v = 0 := begin induction n with n ih, { dsimp [ε] at h, exact h (λ _, tt) }, { cases v with v₁ v₂, ext ; change _ = (0 : V n) ; simp only ; apply ih ; intro p ; [ let q : Q (n+1) := λ i, if h : i = 0 then tt else p (i.pred h), let q : Q (n+1) := λ i, if h : i = 0 then ff else p (i.pred h)], all_goals { specialize h q, rw [ε, show q 0 = tt, from rfl, cond_tt] at h <|> rw [ε, show q 0 = ff, from rfl, cond_ff] at h, rwa show p = π q, by { ext, simp [q, fin.succ_ne_zero, π] } } } end /-- `e` and `ε` are dual families of vectors. It implies that `e` is indeed a basis and `ε` computes coefficients of decompositions of vectors on that basis. -/ def dual_pair_e_ε (n : ℕ) : dual_pair (@e n) (@ε n) := { eval := duality, total := @epsilon_total _ } /-! We will now derive the dimension of `V`, first as a cardinal in `dim_V` and, since this cardinal is finite, as a natural number in `finrank_V` -/ lemma dim_V : module.rank ℝ (V n) = 2^n := have module.rank ℝ (V n) = (2^n : ℕ), by { rw [dim_eq_card_basis (dual_pair_e_ε _).basis, Q.card]; apply_instance }, by assumption_mod_cast instance : finite_dimensional ℝ (V n) := finite_dimensional.of_fintype_basis (dual_pair_e_ε _).basis lemma finrank_V : finrank ℝ (V n) = 2^n := have _ := @dim_V n, by rw ←finrank_eq_dim at this; assumption_mod_cast /-! ### The linear map -/ /-- The linear operator $f_n$ corresponding to Huang's matrix $A_n$, defined inductively as a ℝ-linear map from `V n` to `V n`. -/ noncomputable def f : Π n, V n →ₗ[ℝ] V n | 0 := 0 | (n+1) := linear_map.prod (linear_map.coprod (f n) linear_map.id) (linear_map.coprod linear_map.id (-f n)) /-! The preceding definition uses linear map constructions to automatically get that `f` is linear, but its values are somewhat buried as a side-effect. The next two lemmas unbury them. -/ @[simp] lemma f_zero : f 0 = 0 := rfl lemma f_succ_apply (v : V (n+1)) : f (n+1) v = (f n v.1 + v.2, v.1 - f n v.2) := begin cases v, rw f, simp only [linear_map.id_apply, linear_map.prod_apply, prod.mk.inj_iff, linear_map.neg_apply, sub_eq_add_neg, linear_map.coprod_apply], exact ⟨rfl, rfl⟩ end /-! In the next statement, the explicit conversion `(n : ℝ)` of `n` to a real number is necessary since otherwise `n • v` refers to the multiplication defined using only the addition of `V`. -/ lemma f_squared : ∀ v : V n, (f n) (f n v) = (n : ℝ) • v := begin induction n with n IH; intro, { simpa only [nat.cast_zero, zero_smul] }, { cases v, simp [f_succ_apply, IH, add_smul, add_assoc], abel } end /-! We now compute the matrix of `f` in the `e` basis (`p` is the line index, `q` the column index). -/ lemma f_matrix : ∀ p q : Q n, |ε q (f n (e p))| = if q.adjacent p then 1 else 0 := begin induction n with n IH, { intros p q, dsimp [f], simp [Q.not_adjacent_zero] }, { intros p q, have ite_nonneg : ite (π q = π p) (1 : ℝ) 0 ≥ 0, { split_ifs ; norm_num }, have f_map_zero := (show (V (n+0)) →ₗ[ℝ] (V n), from f n).map_zero, dsimp [e, ε, f], cases hp : p 0 ; cases hq : q 0, all_goals { repeat {rw cond_tt}, repeat {rw cond_ff}, simp [f_map_zero, hp, hq, IH, duality, abs_of_nonneg ite_nonneg, Q.adj_iff_proj_eq, Q.adj_iff_proj_adj] } } end /-- The linear operator $g_m$ corresponding to Knuth's matrix $B_m$. -/ noncomputable def g (m : ℕ) : V m →ₗ[ℝ] V (m+1) := linear_map.prod (f m + √(m+1) • linear_map.id) linear_map.id /-! In the following lemmas, `m` will denote a natural number. -/ variables {m : ℕ} /-! Again we unpack what are the values of `g`. -/ lemma g_apply : ∀ v, g m v = (f m v + √(m+1) • v, v) := by delta g; simp lemma g_injective : injective (g m) := begin rw g, intros x₁ x₂ h, simp only [linear_map.prod_apply, linear_map.id_apply, prod.mk.inj_iff] at h, exact h.right end lemma f_image_g (w : V (m + 1)) (hv : ∃ v, g m v = w) : f (m + 1) w = √(m + 1) • w := begin rcases hv with ⟨v, rfl⟩, have : √(m+1) * √(m+1) = m+1 := real.mul_self_sqrt (by exact_mod_cast zero_le _), simp [this, f_succ_apply, g_apply, f_squared, smul_add, add_smul, smul_smul], abel end /-! ### The main proof In this section, in order to enforce that `n` is positive, we write it as `m + 1` for some natural number `m`. -/ /-! `dim X` will denote the dimension of a subspace `X` as a cardinal. -/ notation `dim` X:70 := module.rank ℝ ↥X /-! `fdim X` will denote the (finite) dimension of a subspace `X` as a natural number. -/ notation `fdim` := finrank ℝ /-! `Span S` will denote the ℝ-subspace spanned by `S`. -/ notation `Span` := submodule.span ℝ /-! `Card X` will denote the cardinal of a subset of a finite type, as a natural number. -/ notation `Card` X:70 := X.to_finset.card /-! In the following, `⊓` and `⊔` will denote intersection and sums of ℝ-subspaces, equipped with their subspace structures. The notations come from the general theory of lattices, with inf and sup (also known as meet and join). -/ /-- If a subset `H` of `Q (m+1)` has cardinal at least `2^m + 1` then the subspace of `V (m+1)` spanned by the corresponding basis vectors non-trivially intersects the range of `g m`. -/ lemma exists_eigenvalue (H : set (Q (m + 1))) (hH : Card H ≥ 2^m + 1) : ∃ y ∈ Span (e '' H) ⊓ (g m).range, y ≠ (0 : _) := begin let W := Span (e '' H), let img := (g m).range, suffices : 0 < dim (W ⊓ img), { simp only [exists_prop], exact_mod_cast exists_mem_ne_zero_of_dim_pos this }, have dim_le : dim (W ⊔ img) ≤ 2^(m + 1), { convert ← dim_submodule_le (W ⊔ img), apply dim_V }, have dim_add : dim (W ⊔ img) + dim (W ⊓ img) = dim W + 2^m, { convert ← dim_sup_add_dim_inf_eq W img, rw ← dim_eq_of_injective (g m) g_injective, apply dim_V }, have dimW : dim W = card H, { have li : linear_independent ℝ (set.restrict e H), { convert (dual_pair_e_ε _).basis.linear_independent.comp _ subtype.val_injective, rw (dual_pair_e_ε _).coe_basis }, have hdW := dim_span li, rw set.range_restrict at hdW, convert hdW, rw [← (dual_pair_e_ε _).coe_basis, cardinal.mk_image_eq (dual_pair_e_ε _).basis.injective, cardinal.mk_fintype] }, rw ← finrank_eq_dim ℝ at ⊢ dim_le dim_add dimW, rw [← finrank_eq_dim ℝ, ← finrank_eq_dim ℝ] at dim_add, norm_cast at ⊢ dim_le dim_add dimW, rw pow_succ' at dim_le, rw set.to_finset_card at hH, linarith end /-- **Huang sensitivity theorem** also known as the **Huang degree theorem** -/ theorem huang_degree_theorem (H : set (Q (m + 1))) (hH : Card H ≥ 2^m + 1) : ∃ q, q ∈ H ∧ √(m + 1) ≤ Card (H ∩ q.adjacent) := begin rcases exists_eigenvalue H hH with ⟨y, ⟨⟨y_mem_H, y_mem_g⟩, y_ne⟩⟩, have coeffs_support : ((dual_pair_e_ε (m+1)).coeffs y).support ⊆ H.to_finset, { intros p p_in, rw finsupp.mem_support_iff at p_in, rw set.mem_to_finset, exact (dual_pair_e_ε _).mem_of_mem_span y_mem_H p p_in }, obtain ⟨q, H_max⟩ : ∃ q : Q (m+1), ∀ q' : Q (m+1), |(ε q' : _) y| ≤ |ε q y|, from fintype.exists_max _, have H_q_pos : 0 < |ε q y|, { contrapose! y_ne, exact epsilon_total (λ p, abs_nonpos_iff.mp (le_trans (H_max p) y_ne)) }, refine ⟨q, (dual_pair_e_ε _).mem_of_mem_span y_mem_H q (abs_pos.mp H_q_pos), _⟩, let s := √(m+1), suffices : s * |ε q y| ≤ ↑(_) * |ε q y|, from (mul_le_mul_right H_q_pos).mp ‹_›, let coeffs := (dual_pair_e_ε (m+1)).coeffs, calc s * |ε q y| = |ε q (s • y)| : by rw [map_smul, smul_eq_mul, abs_mul, abs_of_nonneg (real.sqrt_nonneg _)] ... = |ε q (f (m+1) y)| : by rw [← f_image_g y (by simpa using y_mem_g)] ... = |ε q (f (m+1) (lc _ (coeffs y)))| : by rw (dual_pair_e_ε _).lc_coeffs y ... = |(coeffs y).sum (λ (i : Q (m + 1)) (a : ℝ), a • ((ε q) ∘ (f (m + 1)) ∘ λ (i : Q (m + 1)), e i) i)| : by erw [(f $ m + 1).map_finsupp_total, (ε q).map_finsupp_total, finsupp.total_apply] ... ≤ ∑ p in (coeffs y).support, |(coeffs y p) * (ε q $ f (m+1) $ e p)| : norm_sum_le _ $ λ p, coeffs y p * _ ... = ∑ p in (coeffs y).support, |coeffs y p| * ite (q.adjacent p) 1 0 : by simp only [abs_mul, f_matrix] ... = ∑ p in (coeffs y).support.filter (Q.adjacent q), |coeffs y p| : by simp [finset.sum_filter] ... ≤ ∑ p in (coeffs y).support.filter (Q.adjacent q), |coeffs y q| : finset.sum_le_sum (λ p _, H_max p) ... = (((coeffs y).support.filter (Q.adjacent q)).card : ℝ) * |coeffs y q| : by rw [finset.sum_const, nsmul_eq_mul] ... = (((coeffs y).support ∩ (Q.adjacent q).to_finset).card : ℝ) * |coeffs y q| : by { congr' with x, simp, refl } ... ≤ (finset.card ((H ∩ Q.adjacent q).to_finset )) * |ε q y| : begin refine (mul_le_mul_right H_q_pos).2 _, norm_cast, apply finset.card_le_of_subset, rw set.to_finset_inter, convert finset.inter_subset_inter_right coeffs_support end end
48de51c6c4766776582c8c78f9283ce62b0999a0
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/tactic/interactive_expr.lean
f6d5cce9cbce6bbfbe471ca25dc26691b250189f
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
12,064
lean
/- Copyright (c) 2020 E.W.Ayers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: E.W.Ayers -/ /-! # Widgets used for tactic state and term-mode goal display The vscode extension supports the display of interactive widgets. Default implementation of these widgets are included in the core library. We override them here using `vm_override` so that we can change them quickly without waiting for the next Lean release. The function `widget_override.interactive_expression.mk` renders a single expression as a widget component. Each goal in a tactic state is rendered using the `widget_override.tactic_view_goal` function, a complete tactic state is rendered using `widget_override.tactic_view_component`. Lean itself calls the `widget_override.term_goal_widget` function to render term-mode goals and `widget_override.tactic_state_widget` to render the tactic state in a tactic proof. -/ namespace widget_override open widget open tagged_format open widget.html widget.attr namespace interactive_expression /-- eformat but without any of the formatting stuff like highlighting, groups etc. -/ meta inductive sf : Type | tag_expr : expr.address → expr → sf → sf | compose : sf → sf → sf | of_string : string → sf private meta def to_simple : eformat → sf | (tag ⟨ea,e⟩ m) := sf.tag_expr ea e $ to_simple m | (group m) := to_simple m | (nest i m) := to_simple m | (highlight i m) := to_simple m | (of_format f) := sf.of_string $ format.to_string f | (compose x y) := sf.compose (to_simple x) (to_simple y) private meta def sf.flatten : sf → sf | (sf.tag_expr e ea m) := (sf.tag_expr e ea $ sf.flatten m) | (sf.compose x y) := match (sf.flatten x), (sf.flatten y) with | (sf.of_string sx), (sf.of_string sy) := sf.of_string (sx ++ sy) | (sf.of_string sx), (sf.compose (sf.of_string sy) z) := sf.compose (sf.of_string (sx ++ sy)) z | (sf.compose x (sf.of_string sy)), (sf.of_string sz) := sf.compose x (sf.of_string (sy ++ sz)) | (sf.compose x (sf.of_string sy1)), (sf.compose (sf.of_string sy2) z) := sf.compose x (sf.compose (sf.of_string (sy1 ++ sy2)) z) | x, y := sf.compose x y end | (sf.of_string s) := sf.of_string s /-- The actions accepted by an expression widget. -/ meta inductive action (γ : Type) | on_mouse_enter : subexpr → action | on_mouse_leave_all : action | on_click : subexpr → action | on_tooltip_action : γ → action | on_close_tooltip : action /-- Renders a subexpression as a list of html elements. -/ meta def view {γ} (tooltip_component : tc subexpr (action γ)) (click_address : option expr.address) (select_address : option expr.address) : subexpr → sf → tactic (list (html (action γ))) | ⟨ce, current_address⟩ (sf.tag_expr ea e m) := do let new_address := current_address ++ ea, let select_attrs : list (attr (action γ)) := if some new_address = select_address then [className "highlight"] else [], click_attrs : list (attr (action γ)) ← if some new_address = click_address then do content ← tc.to_html tooltip_component (e, new_address), pure [tooltip $ h "div" [] [ h "button" [cn "fr pointer ba br3", on_click (λ _, action.on_close_tooltip)] ["x"], content ]] else pure [], let as := [className "expr-boundary", key (ea)] ++ select_attrs ++ click_attrs, inner ← view (e,new_address) m, pure [h "span" as inner] | ca (sf.compose x y) := pure (++) <*> view ca x <*> view ca y | ca (sf.of_string s) := pure [h "span" [ on_mouse_enter (λ _, action.on_mouse_enter ca), on_click (λ _, action.on_click ca), key s ] [html.of_string s]] /-- Make an interactive expression. -/ meta def mk {γ} (tooltip : tc subexpr γ) : tc expr γ := let tooltip_comp := component.with_props_eq (λ (x y : tactic_state × expr × expr.address), x.2.2 = y.2.2) $ component.map_action (action.on_tooltip_action) tooltip in tc.mk_simple (action γ) (option subexpr × option subexpr) (λ e, pure $ (none, none)) (λ e ⟨ca, sa⟩ act, pure $ match act with | (action.on_mouse_enter ⟨e, ea⟩) := ((ca, some (e, ea)), none) | (action.on_mouse_leave_all) := ((ca, none), none) | (action.on_click ⟨e, ea⟩) := if some (e,ea) = ca then ((none, sa), none) else ((some (e, ea), sa), none) | (action.on_tooltip_action g) := ((none, sa), some g) | (action.on_close_tooltip) := ((none, sa), none) end ) (λ e ⟨ca, sa⟩, do ts ← tactic.read, let m : sf := sf.flatten $ to_simple $ tactic_state.pp_tagged ts e, let m : sf := sf.tag_expr [] e m, -- [hack] in pp.cpp I forgot to add an expr-boundary for the root expression. v ← view tooltip_comp (prod.snd <$> ca) (prod.snd <$> sa) ⟨e, []⟩ m, pure $ [ h "span" [ className "expr", key e.hash, on_mouse_leave (λ _, action.on_mouse_leave_all) ] $ v ] ) /-- Render the implicit arguments for an expression in fancy, little pills. -/ meta def implicit_arg_list (tooltip : tc subexpr empty) (e : expr) : tactic $ html empty := do fn ← (mk tooltip) $ expr.get_app_fn e, args ← list.mmap (mk tooltip) $ expr.get_app_args e, pure $ h "div" [] ( (h "span" [className "bg-blue br3 ma1 ph2 white"] [fn]) :: list.map (λ a, h "span" [className "bg-gray br3 ma1 ph2 white"] [a]) args ) /-- Component for the type tooltip. -/ meta def type_tooltip : tc subexpr empty := tc.stateless (λ ⟨e,ea⟩, do y ← tactic.infer_type e, y_comp ← mk type_tooltip y, implicit_args ← implicit_arg_list type_tooltip e, pure [ h "div" [] [ h "div" [] [y_comp], h "hr" [] [], implicit_args ] ] ) end interactive_expression /-- Supported tactic state filters. -/ @[derive decidable_eq] meta inductive filter_type | none | no_instances | only_props /-- Filters a local constant using the given filter. -/ meta def filter_local : filter_type → expr → tactic bool | (filter_type.none) e := pure tt | (filter_type.no_instances) e := do t ← tactic.infer_type e, bnot <$> tactic.is_class t | (filter_type.only_props) e := do t ← tactic.infer_type e, tactic.is_prop t /-- Component for the filter dropdown. -/ meta def filter_component : component filter_type filter_type := component.stateless (λ lf, [ h "label" [] ["filter: "], select [ ⟨filter_type.none, "0", ["no filter"]⟩, ⟨filter_type.no_instances, "1", ["no instances"]⟩, ⟨filter_type.only_props, "2", ["only props"]⟩ ] lf ] ) /-- Converts a name into an html element. -/ meta def html.of_name {α : Type} : name → html α | n := html.of_string $ name.to_string n open tactic /-- Component that shows a type. -/ meta def show_type_component : tc expr empty := tc.stateless (λ x, do y ← infer_type x, y_comp ← interactive_expression.mk interactive_expression.type_tooltip $ y, pure y_comp ) /-- A group of local constants in the context that should be rendered as one line. -/ @[derive decidable_eq] meta structure local_collection := (key : string) (locals : list expr) (type : expr) (value : option expr) /-- Converts a single local constant into a (singleton) `local_collection` -/ meta def to_local_collection (l : expr) : tactic local_collection := tactic.unsafe.type_context.run $ do lctx ← tactic.unsafe.type_context.get_local_context, some ldecl ← pure $ lctx.get_local_decl l.local_uniq_name, pure { key := l.local_uniq_name.repr, locals := [l], type := ldecl.type, value := ldecl.value } /-- Groups consecutive local collections by type -/ meta def group_local_collection : list local_collection → list local_collection | (a :: b :: rest) := if a.type = b.type ∧ a.value = b.value then group_local_collection $ { locals := a.locals ++ b.locals, ..a } :: rest else a :: group_local_collection (b :: rest) | ls := ls /-- Component that displays the main (first) goal. -/ meta def tactic_view_goal {γ} (local_c : tc local_collection γ) (target_c : tc expr γ) : tc filter_type γ := tc.stateless $ λ ft, do g@(expr.mvar u_n pp_n y) ← main_goal, t ← get_tag g, let case_tag : list (html γ) := match interactive.case_tag.parse t with | some t := [h "li" [key "_case"] $ [h "span" [cn "goal-case b"] ["case"]] ++ (t.case_names.bind $ λ n, [" ", n])] | none := [] end, lcs ← local_context, lcs ← list.mfilter (filter_local ft) lcs, lcs ← lcs.mmap $ to_local_collection, let lcs := group_local_collection lcs, lchs ← lcs.mmap (λ lc, do lh ← local_c lc, let ns : list (html γ) := lc.locals.map $ λ n, h "span" [cn "goal-hyp b pr2", key n.local_uniq_name] [html.of_name n.local_pp_name], pure $ h "li" [key lc.key] (ns ++ [": ", h "span" [cn "goal-hyp-type", key "type"] [lh]])), t_comp ← target_c g, pure $ h "ul" [key g.hash, className "list pl0 font-code"] $ case_tag ++ lchs ++ [ h "li" [key u_n] [ h "span" [cn "goal-vdash b"] ["⊢ "], t_comp ]] /-- Actions accepted by the `tactic_view_component`. -/ meta inductive tactic_view_action (γ : Type) | out (a:γ): tactic_view_action | filter (f: filter_type): tactic_view_action /-- Component that displays all goals, together with the `$n goals` message. -/ meta def tactic_view_component {γ} (local_c : tc local_collection γ) (target_c : tc expr γ) : tc unit γ := tc.mk_simple (tactic_view_action γ) (filter_type) (λ _, pure $ filter_type.none) (λ ⟨⟩ ft a, match a with | (tactic_view_action.out a) := pure (ft, some a) | (tactic_view_action.filter ft) := pure (ft, none) end) (λ ⟨⟩ ft, do gs ← get_goals, hs ← gs.mmap (λ g, do set_goals [g], flip tc.to_html ft $ tactic_view_goal local_c target_c), set_goals gs, let goal_message := if gs.length = 0 then "goals accomplished 🎉" else if gs.length = 1 then "1 goal" else to_string gs.length ++ " goals", let goal_message : html γ := h "strong" [cn "goal-goals"] [goal_message], let goals : html γ := h "ul" [className "list pl0"] $ list.map_with_index (λ i x, h "li" [className $ "lh-copy mt2", key i] [x]) $ (goal_message :: hs), pure [ h "div" [className "fr"] [html.of_component ft $ component.map_action tactic_view_action.filter filter_component], html.map_action tactic_view_action.out goals ]) /-- Component that displays the term-mode goal. -/ meta def tactic_view_term_goal {γ} (local_c : tc local_collection γ) (target_c : tc expr γ) : tc unit γ := tc.stateless $ λ _, do goal ← flip tc.to_html (filter_type.none) $ tactic_view_goal local_c target_c, pure [h "ul" [className "list pl0"] [ h "li" [className "lh-copy"] [h "strong" [cn "goal-goals"] ["expected type:"]], h "li" [className "lh-copy"] [goal]]] /-- Component showing a local collection. -/ meta def show_local_collection_component : tc local_collection empty := tc.stateless (λ lc, do (l::_) ← pure lc.locals, c ← show_type_component l, match lc.value with | some v := do v ← interactive_expression.mk interactive_expression.type_tooltip v, pure [c, " := ", v] | none := pure [c] end) /-- Renders the current tactic state. -/ meta def tactic_render : tc unit string := component.ignore_action $ tactic_view_component show_local_collection_component show_type_component /-- Component showing the current tactic state. -/ meta def tactic_state_widget : component tactic_state string := tc.to_component tactic_render /-- Widget used to display term-proof goals. -/ meta def term_goal_widget : component tactic_state string := (tactic_view_term_goal show_local_collection_component show_type_component).to_component end widget_override attribute [vm_override widget_override.term_goal_widget] widget.term_goal_widget attribute [vm_override widget_override.tactic_state_widget] widget.tactic_state_widget
1c0030bacda85d880d3ae409598b67b3650f6802
b074a51e20fdb737b2d4c635dd292fc54685e010
/src/category_theory/monoidal/types.lean
2fca1d5e431a08b14a17f00ab03efd85a518864e
[ "Apache-2.0" ]
permissive
minchaowu/mathlib
2daf6ffdb5a56eeca403e894af88bcaaf65aec5e
879da1cf04c2baa9eaa7bd2472100bc0335e5c73
refs/heads/master
1,609,628,676,768
1,564,310,105,000
1,564,310,105,000
99,461,307
0
0
null
null
null
null
UTF-8
Lean
false
false
886
lean
-- Copyright (c) 2018 Michael Jendrusch. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Michael Jendrusch, Scott Morrison import category_theory.types import category_theory.monoidal.category open category_theory open tactic universes u v namespace category_theory.monoidal instance types : monoidal_category.{u+1} (Type u) := { tensor_obj := λ X Y, X × Y, tensor_hom := λ _ _ _ _ f g, prod.map f g, tensor_unit := punit, left_unitor := λ X, (equiv.punit_prod X).to_iso, right_unitor := λ X, (equiv.prod_punit X).to_iso, associator := λ X Y Z, (equiv.prod_assoc X Y Z).to_iso, ..category_theory.types.{u+1} } -- TODO Once we add braided/symmetric categories, include the braiding. -- TODO More generally, define the symmetric monoidal structure on any category with products. end category_theory.monoidal
4e590f9047281739fbc4aef966ef184aa145cabc
1446f520c1db37e157b631385707cc28a17a595e
/stage0/src/Init/Data/Basic.lean
8382655db948de68dc7a3606516683a05707d94d
[ "Apache-2.0" ]
permissive
bdbabiak/lean4
cab06b8a2606d99a168dd279efdd404edb4e825a
3f4d0d78b2ce3ef541cb643bbe21496bd6b057ac
refs/heads/master
1,615,045,275,530
1,583,793,696,000
1,583,793,696,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
412
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.Nat.Basic import Init.Data.Fin.Basic import Init.Data.List.Basic import Init.Data.Char.Basic import Init.Data.String.Basic import Init.Data.Option.Basic import Init.Data.UInt import Init.Data.Repr import Init.Data.ToString
e5bbd8d836f54d5125ffaca70e16c86d9013ee49
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/tests/lean/run/t3.lean
ff469a268ff91eebf2d914ffe66601f21af1b9d6
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
351
lean
constant int : Type.{1} constant nat : Type.{1} namespace int constant plus : int → int → int end int namespace nat constant plus : nat → nat → nat end nat open int nat constants a b : int check plus a b constant f : int → int → int constant g : nat → nat → int notation A `+`:65 B:65 := f A (g B B) constant n : nat check a + n
1825ba8c23e3fe896e0754a79d2b2ac734309dc8
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/tropical/lattice.lean
83b1d1606b71d6d80dcf71752680102f2808e219
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
2,399
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 algebra.tropical.basic import order.conditionally_complete_lattice.basic /-! # Order on tropical algebraic structure This file defines the orders induced on tropical algebraic structures by the underlying type. ## Main declarations * `conditionally_complete_lattice (tropical R)` * `conditionally_complete_linear_order (tropical R)` ## Implementation notes The order induced is the definitionally equal underlying order, which makes the proofs and constructions quicker to implement. -/ variables {R S : Type*} open tropical instance [has_sup R] : has_sup (tropical R) := { sup := λ x y, trop (untrop x ⊔ untrop y) } instance [has_inf R] : has_inf (tropical R) := { inf := λ x y, trop (untrop x ⊓ untrop y) } instance [semilattice_inf R] : semilattice_inf (tropical R) := { le_inf := λ _ _ _, le_inf, inf_le_left := λ _ _, inf_le_left, inf_le_right := λ _ _, inf_le_right, ..tropical.has_inf, ..tropical.partial_order } instance [semilattice_sup R] : semilattice_sup (tropical R) := { sup_le := λ _ _ _, sup_le, le_sup_left := λ _ _, le_sup_left, le_sup_right := λ _ _, le_sup_right, ..tropical.has_sup, ..tropical.partial_order } instance [lattice R] : lattice (tropical R) := { ..tropical.semilattice_inf, ..tropical.semilattice_sup } instance [has_Sup R] : has_Sup (tropical R) := { Sup := λ s, trop (Sup (untrop '' s)) } instance [has_Inf R] : has_Inf (tropical R) := { Inf := λ s, trop (Inf (untrop '' s)) } instance [conditionally_complete_lattice R] : conditionally_complete_lattice (tropical R) := { le_cSup := λ s x hs hx, le_cSup (untrop_monotone.map_bdd_above hs) (set.mem_image_of_mem untrop hx), cSup_le := λ s x hs hx, cSup_le (hs.image untrop) (untrop_monotone.mem_upper_bounds_image hx), le_cInf := λ s x hs hx, le_cInf (hs.image untrop) (untrop_monotone.mem_lower_bounds_image hx), cInf_le := λ s x hs hx, cInf_le (untrop_monotone.map_bdd_below hs) (set.mem_image_of_mem untrop hx), ..tropical.has_Sup, ..tropical.has_Inf, ..tropical.lattice } instance [conditionally_complete_linear_order R] : conditionally_complete_linear_order (tropical R) := { ..tropical.conditionally_complete_lattice, ..tropical.linear_order }
e61e22bf5895984e3c49c22240bf4e03a8fedc74
9dc8cecdf3c4634764a18254e94d43da07142918
/src/category_theory/idempotents/functor_categories.lean
baf4b966076a876ac75e8bf2cc584779e0312f33
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
6,243
lean
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import category_theory.idempotents.karoubi /-! # Idempotent completeness and functor categories In this file we define an instance `functor_category_is_idempotent_complete` expressing that a functor category `J ⥤ C` is idempotent complete when the target category `C` is. We also provide a fully faithful functor `karoubi_functor_category_embedding : karoubi (J ⥤ C)) : J ⥤ karoubi C` for all categories `J` and `C`. -/ open category_theory open category_theory.category open category_theory.idempotents.karoubi open category_theory.limits namespace category_theory namespace idempotents variables (J C : Type*) [category J] [category C] instance functor_category_is_idempotent_complete [is_idempotent_complete C] : is_idempotent_complete (J ⥤ C) := begin refine ⟨_⟩, intros F p hp, have hC := (is_idempotent_complete_iff_has_equalizer_of_id_and_idempotent C).mp infer_instance, haveI : ∀ (j : J), has_equalizer (𝟙 _) (p.app j) := λ j, hC _ _ (congr_app hp j), /- We construct the direct factor `Y` associated to `p : F ⟶ F` by computing the equalizer of the identity and `p.app j` on each object `(j : J)`. -/ let Y : J ⥤ C := { obj := λ j, limits.equalizer (𝟙 _) (p.app j), map := λ j j' φ, equalizer.lift (limits.equalizer.ι (𝟙 _) (p.app j) ≫ F.map φ) (by rw [comp_id, assoc, p.naturality φ, ← assoc, ← limits.equalizer.condition, comp_id]), map_id' := λ j, by { ext, simp only [comp_id, functor.map_id, equalizer.lift_ι, id_comp], }, map_comp' := λ j j' j'' φ φ', begin ext, simp only [assoc, functor.map_comp, equalizer.lift_ι, equalizer.lift_ι_assoc], end }, let i : Y ⟶ F := { app := λ j, equalizer.ι _ _, naturality' := λ j j' φ, by rw [equalizer.lift_ι], }, let e : F ⟶ Y := { app := λ j, equalizer.lift (p.app j) (by { rw comp_id, exact (congr_app hp j).symm, }), naturality' := λ j j' φ, begin ext, simp only [assoc, equalizer.lift_ι, nat_trans.naturality, equalizer.lift_ι_assoc], end }, use [Y, i, e], split; ext j, { simp only [nat_trans.comp_app, assoc, equalizer.lift_ι, nat_trans.id_app, id_comp, ← equalizer.condition, comp_id], }, { simp only [nat_trans.comp_app, equalizer.lift_ι], }, end namespace karoubi_functor_category_embedding variables {J C} /-- On objects, the functor which sends a formal direct factor `P` of a functor `F : J ⥤ C` to the functor `J ⥤ karoubi C` which sends `(j : J)` to the corresponding direct factor of `F.obj j`. -/ @[simps] def obj (P : karoubi (J ⥤ C)) : J ⥤ karoubi C := { obj := λ j, ⟨P.X.obj j, P.p.app j, congr_app P.idem j⟩, map := λ j j' φ, { f := P.p.app j ≫ P.X.map φ, comm := begin simp only [nat_trans.naturality, assoc], have h := congr_app P.idem j, rw [nat_trans.comp_app] at h, slice_rhs 1 3 { erw [h, h], }, end }, map_id' := λ j, by { ext, simp only [functor.map_id, comp_id, id_eq], }, map_comp' := λ j j' j'' φ φ', begin ext, have h := congr_app P.idem j, rw [nat_trans.comp_app] at h, simp only [assoc, nat_trans.naturality_assoc, functor.map_comp, comp], slice_rhs 1 2 { rw h, }, rw [assoc], end } /-- Tautological action on maps of the functor `karoubi (J ⥤ C) ⥤ (J ⥤ karoubi C)`. -/ @[simps] def map {P Q : karoubi (J ⥤ C)} (f : P ⟶ Q) : obj P ⟶ obj Q := { app := λ j, ⟨f.f.app j, congr_app f.comm j⟩, naturality' := λ j j' φ, begin ext, simp only [comp], have h := congr_app (comp_p f) j, have h' := congr_app (p_comp f) j', dsimp at h h' ⊢, slice_rhs 1 2 { erw h, }, rw ← P.p.naturality, slice_lhs 2 3 { erw h', }, rw f.f.naturality, end } end karoubi_functor_category_embedding variables (J C) /-- The tautological fully faithful functor `karoubi (J ⥤ C) ⥤ (J ⥤ karoubi C)`. -/ @[simps] def karoubi_functor_category_embedding : karoubi (J ⥤ C) ⥤ (J ⥤ karoubi C) := { obj := karoubi_functor_category_embedding.obj, map := λ P Q, karoubi_functor_category_embedding.map, map_id' := λ P, rfl, map_comp' := λ P Q R f g, rfl, } instance : full (karoubi_functor_category_embedding J C) := { preimage := λ P Q f, { f := { app := λ j, (f.app j).f, naturality' := λ j j' φ, begin slice_rhs 1 1 { rw ← karoubi.comp_p, }, have h := hom_ext.mp (f.naturality φ), simp only [comp] at h, dsimp [karoubi_functor_category_embedding] at h ⊢, erw [assoc, ← h, ← P.p.naturality φ, assoc, p_comp (f.app j')], end }, comm := by { ext j, exact (f.app j).comm, } }, witness' := λ P Q f, by { ext j, refl, }, } instance : faithful (karoubi_functor_category_embedding J C) := { map_injective' := λ P Q f f' h, by { ext j, exact hom_ext.mp (congr_app h j), }, } /-- The composition of `(J ⥤ C) ⥤ karoubi (J ⥤ C)` and `karoubi (J ⥤ C) ⥤ (J ⥤ karoubi C)` equals the functor `(J ⥤ C) ⥤ (J ⥤ karoubi C)` given by the composition with `to_karoubi C : C ⥤ karoubi C`. -/ lemma to_karoubi_comp_karoubi_functor_category_embedding : (to_karoubi _) ⋙ karoubi_functor_category_embedding J C = (whiskering_right J _ _).obj (to_karoubi C) := begin apply functor.ext, { intros X Y f, ext j, dsimp [to_karoubi], simp only [eq_to_hom_app, eq_to_hom_refl, id_comp], erw [comp_id], }, { intro X, apply functor.ext, { intros j j' φ, ext, dsimp, simpa only [comp_id, id_comp], }, { intro j, refl, }, } end variables {J C} (P Q : karoubi (J ⥤ C)) (f : P ⟶ Q) (X : J) @[simp, reassoc] lemma app_idem (X : J) : P.p.app X ≫ P.p.app X = P.p.app X := congr_app P.idem X variables {P Q} @[simp, reassoc] lemma app_p_comp : P.p.app X ≫ f.f.app X = f.f.app X := congr_app (p_comp f) X @[simp, reassoc] lemma app_comp_p : f.f.app X ≫ Q.p.app X = f.f.app X := congr_app (comp_p f) X @[reassoc] lemma app_p_comm : P.p.app X ≫ f.f.app X = f.f.app X ≫ Q.p.app X := congr_app (p_comm f) X end idempotents end category_theory
01376a681215dbbcfea608d18c2516ebda12e1ea
5ae26df177f810c5006841e9c73dc56e01b978d7
/test/ext.lean
cdab4a42adb180a0cee17e95382ffe63bb3c04e6
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
4,221
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import tactic.core import tactic.ext import tactic.solve_by_elim import data.set.basic data.stream.basic @[extensionality] lemma unit.ext (x y : unit) : x = y := begin cases x, cases y, refl end example : subsingleton unit := begin split, intros, ext end example (x y : ℕ) : true := begin have : x = y, { ext <|> admit }, have : x = y, { ext i <|> admit }, have : x = y, { ext : 1 <|> admit }, trivial end example (X Y : ℕ × ℕ) (h : X.1 = Y.1) (h : X.2 = Y.2) : X = Y := begin ext; assumption end example (X Y : (ℕ → ℕ) × ℕ) (h : ∀ i, X.1 i = Y.1 i) (h : X.2 = Y.2) : X = Y := begin ext x; solve_by_elim, end example (X Y : ℕ → ℕ × ℕ) (h : ∀ i, X i = Y i) : true := begin have : X = Y, { ext i : 1, guard_target X i = Y i, admit }, have : X = Y, { ext i, guard_target (X i).fst = (Y i).fst, admit, guard_target (X i).snd = (Y i).snd, admit, }, have : X = Y, { ext : 1, guard_target X x = Y x, admit }, trivial, end example (s₀ s₁ : set ℕ) (h : s₁ = s₀) : s₀ = s₁ := by { ext1, guard_target x ∈ s₀ ↔ x ∈ s₁, simp * } example (s₀ s₁ : stream ℕ) (h : s₁ = s₀) : s₀ = s₁ := by { ext1, guard_target s₀.nth n = s₁.nth n, simp * } example (s₀ s₁ : ℤ → set (ℕ × ℕ)) (h : ∀ i a b, (a,b) ∈ s₀ i ↔ (a,b) ∈ s₁ i) : s₀ = s₁ := begin ext i ⟨a,b⟩, apply h end def my_foo {α} (x : semigroup α) (y : group α) : true := trivial example {α : Type} : true := begin have : true, { refine_struct (@my_foo α { .. } { .. } ), -- 9 goals guard_tags _field mul semigroup, admit, -- case semigroup, mul -- α : Type -- ⊢ α → α → α guard_tags _field mul_assoc semigroup, admit, -- case semigroup, mul_assoc -- α : Type -- ⊢ ∀ (a b c : α), a * b * c = a * (b * c) guard_tags _field mul group, admit, -- case group, mul -- α : Type -- ⊢ α → α → α guard_tags _field mul_assoc group, admit, -- case group, mul_assoc -- α : Type -- ⊢ ∀ (a b c : α), a * b * c = a * (b * c) guard_tags _field one group, admit, -- case group, one -- α : Type -- ⊢ α guard_tags _field one_mul group, admit, -- case group, one_mul -- α : Type -- ⊢ ∀ (a : α), 1 * a = a guard_tags _field mul_one group, admit, -- case group, mul_one -- α : Type -- ⊢ ∀ (a : α), a * 1 = a guard_tags _field inv group, admit, -- case group, inv -- α : Type -- ⊢ α → α guard_tags _field mul_left_inv group, admit, -- case group, mul_left_inv -- α : Type -- ⊢ ∀ (a : α), a⁻¹ * a = 1 }, trivial end def my_bar {α} (x : semigroup α) (y : group α) (i j : α) : α := i example {α : Type} : true := begin have : monoid α, { refine_struct { mul := my_bar { .. } { .. } }, guard_tags _field mul semigroup, admit, guard_tags _field mul_assoc semigroup, admit, guard_tags _field mul group, admit, guard_tags _field mul_assoc group, admit, guard_tags _field one group, admit, guard_tags _field one_mul group, admit, guard_tags _field mul_one group, admit, guard_tags _field inv group, admit, guard_tags _field mul_left_inv group, admit, guard_tags _field mul_assoc monoid, admit, guard_tags _field one monoid, admit, guard_tags _field one_mul monoid, admit, guard_tags _field mul_one monoid, admit, }, trivial end structure dependent_fields := (a : bool) (v : if a then ℕ else ℤ) @[extensionality] lemma df.ext (s t : dependent_fields) (h : s.a = t.a) (w : (@eq.rec _ s.a (λ b, if b then ℕ else ℤ) s.v t.a h) = t.v) : s = t := begin cases s, cases t, dsimp at *, congr, exact h, subst h, simp, simp at w, exact w, end example (s : dependent_fields) : s = s := begin tactic.ext1 [] {tactic.apply_cfg . new_goals := tactic.new_goals.all}, guard_target s.a = s.a, refl, refl, end
94ebd73f07deb57c8d7814142eef2ef152eb0c09
82e44445c70db0f03e30d7be725775f122d72f3e
/src/number_theory/arithmetic_function.lean
8b0ba3e3df1bfa348bf64a669f32e7b314990df9
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
32,424
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import algebra.big_operators.ring import number_theory.divisors import algebra.squarefree import algebra.invertible /-! # Arithmetic Functions and Dirichlet Convolution This file defines arithmetic functions, which are functions from `ℕ` to a specified type that map 0 to 0. In the literature, they are often instead defined as functions from `ℕ+`. These arithmetic functions are endowed with a multiplication, given by Dirichlet convolution, and pointwise addition, to form the Dirichlet ring. ## Main Definitions * `arithmetic_function R` consists of functions `f : ℕ → R` such that `f 0 = 0`. * An arithmetic function `f` `is_multiplicative` when `x.coprime y → f (x * y) = f x * f y`. * The pointwise operations `pmul` and `ppow` differ from the multiplication and power instances on `arithmetic_function R`, which use Dirichlet multiplication. * `ζ` is the arithmetic function such that `ζ x = 1` for `0 < x`. * `σ k` is the arithmetic function such that `σ k x = ∑ y in divisors x, y ^ k` for `0 < x`. * `pow k` is the arithmetic function such that `pow k x = x ^ k` for `0 < x`. * `id` is the identity arithmetic function on `ℕ`. * `ω n` is the number of distinct prime factors of `n`. * `Ω n` is the number of prime factors of `n` counted with multiplicity. * `μ` is the Möbius function. ## Main Results * Several forms of Möbius inversion: * `sum_eq_iff_sum_mul_moebius_eq` for functions to a `comm_ring` * `sum_eq_iff_sum_smul_moebius_eq` for functions to an `add_comm_group` * `prod_eq_iff_prod_pow_moebius_eq` for functions to a `comm_group` * `prod_eq_iff_prod_pow_moebius_eq_of_nonzero` for functions to a `comm_group_with_zero` ## Notation The arithmetic functions `ζ` and `σ` have Greek letter names, which are localized notation in the namespace `arithmetic_function`. ## Tags arithmetic functions, dirichlet convolution, divisors -/ open finset open_locale big_operators namespace nat variable (R : Type*) /-- An arithmetic function is a function from `ℕ` that maps 0 to 0. In the literature, they are often instead defined as functions from `ℕ+`. Multiplication on `arithmetic_functions` is by Dirichlet convolution. -/ @[derive [has_coe_to_fun, has_zero, inhabited]] def arithmetic_function [has_zero R] := zero_hom ℕ R variable {R} namespace arithmetic_function section has_zero variable [has_zero R] @[simp] lemma to_fun_eq (f : arithmetic_function R) : f.to_fun = f := rfl @[simp] lemma map_zero {f : arithmetic_function R} : f 0 = 0 := zero_hom.map_zero' f theorem coe_inj {f g : arithmetic_function R} : (f : ℕ → R) = g ↔ f = g := ⟨λ h, zero_hom.coe_inj h, λ h, h ▸ rfl⟩ @[simp] lemma zero_apply {x : ℕ} : (0 : arithmetic_function R) x = 0 := zero_hom.zero_apply x @[ext] theorem ext ⦃f g : arithmetic_function R⦄ (h : ∀ x, f x = g x) : f = g := zero_hom.ext h theorem ext_iff {f g : arithmetic_function R} : f = g ↔ ∀ x, f x = g x := zero_hom.ext_iff section has_one variable [has_one R] instance : has_one (arithmetic_function R) := ⟨⟨λ x, ite (x = 1) 1 0, rfl⟩⟩ @[simp] lemma one_one : (1 : arithmetic_function R) 1 = 1 := rfl @[simp] lemma one_apply_ne {x : ℕ} (h : x ≠ 1) : (1 : arithmetic_function R) x = 0 := if_neg h end has_one end has_zero instance nat_coe [has_zero R] [has_one R] [has_add R] : has_coe (arithmetic_function ℕ) (arithmetic_function R) := ⟨λ f, ⟨↑(f : ℕ → ℕ), by { transitivity ↑(f 0), refl, simp }⟩⟩ @[simp] lemma nat_coe_nat (f : arithmetic_function ℕ) : (↑f : arithmetic_function ℕ) = f := ext $ λ _, cast_id _ @[simp] lemma nat_coe_apply [has_zero R] [has_one R] [has_add R] {f : arithmetic_function ℕ} {x : ℕ} : (f : arithmetic_function R) x = f x := rfl instance int_coe [has_zero R] [has_one R] [has_add R] [has_neg R] : has_coe (arithmetic_function ℤ) (arithmetic_function R) := ⟨λ f, ⟨↑(f : ℕ → ℤ), by { transitivity ↑(f 0), refl, simp }⟩⟩ @[simp] lemma int_coe_int (f : arithmetic_function ℤ) : (↑f : arithmetic_function ℤ) = f := ext $ λ _, int.cast_id _ @[simp] lemma int_coe_apply [has_zero R] [has_one R] [has_add R] [has_neg R] {f : arithmetic_function ℤ} {x : ℕ} : (f : arithmetic_function R) x = f x := rfl @[simp] lemma coe_coe [has_zero R] [has_one R] [has_add R] [has_neg R] {f : arithmetic_function ℕ} : ((f : arithmetic_function ℤ) : arithmetic_function R) = f := by { ext, simp, } section add_monoid variable [add_monoid R] instance : has_add (arithmetic_function R) := ⟨λ f g, ⟨λ n, f n + g n, by simp⟩⟩ @[simp] lemma add_apply {f g : arithmetic_function R} {n : ℕ} : (f + g) n = f n + g n := rfl instance : add_monoid (arithmetic_function R) := { add_assoc := λ _ _ _, ext (λ _, add_assoc _ _ _), zero_add := λ _, ext (λ _, zero_add _), add_zero := λ _, ext (λ _, add_zero _), .. arithmetic_function.has_zero R, .. arithmetic_function.has_add } end add_monoid instance [add_comm_monoid R] : add_comm_monoid (arithmetic_function R) := { add_comm := λ _ _, ext (λ _, add_comm _ _), .. arithmetic_function.add_monoid } instance [add_group R] : add_group (arithmetic_function R) := { neg := λ f, ⟨λ n, - f n, by simp⟩, add_left_neg := λ _, ext (λ _, add_left_neg _), .. arithmetic_function.add_monoid } instance [add_comm_group R] : add_comm_group (arithmetic_function R) := { .. arithmetic_function.add_comm_monoid, .. arithmetic_function.add_group } section has_scalar variables {M : Type*} [has_zero R] [add_comm_monoid M] [has_scalar R M] /-- The Dirichlet convolution of two arithmetic functions `f` and `g` is another arithmetic function such that `(f * g) n` is the sum of `f x * g y` over all `(x,y)` such that `x * y = n`. -/ instance : has_scalar (arithmetic_function R) (arithmetic_function M) := ⟨λ f g, ⟨λ n, ∑ x in divisors_antidiagonal n, f x.fst • g x.snd, by simp⟩⟩ @[simp] lemma smul_apply {f : arithmetic_function R} {g : arithmetic_function M} {n : ℕ} : (f • g) n = ∑ x in divisors_antidiagonal n, f x.fst • g x.snd := rfl end has_scalar /-- The Dirichlet convolution of two arithmetic functions `f` and `g` is another arithmetic function such that `(f * g) n` is the sum of `f x * g y` over all `(x,y)` such that `x * y = n`. -/ instance [semiring R] : has_mul (arithmetic_function R) := ⟨(•)⟩ @[simp] lemma mul_apply [semiring R] {f g : arithmetic_function R} {n : ℕ} : (f * g) n = ∑ x in divisors_antidiagonal n, f x.fst * g x.snd := rfl section module variables {M : Type*} [semiring R] [add_comm_monoid M] [module R M] lemma mul_smul' (f g : arithmetic_function R) (h : arithmetic_function M) : (f * g) • h = f • g • h := begin ext n, simp only [mul_apply, smul_apply, sum_smul, mul_smul, smul_sum, finset.sum_sigma'], apply finset.sum_bij, swap 5, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, exact ⟨(k, l*j), (l, j)⟩ }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, simp only [finset.mem_sigma, mem_divisors_antidiagonal] at H ⊢, rcases H with ⟨⟨rfl, n0⟩, rfl, i0⟩, refine ⟨⟨(mul_assoc _ _ _).symm, n0⟩, rfl, _⟩, rw mul_ne_zero_iff at *, exact ⟨i0.2, n0.2⟩, }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, simp only [mul_assoc] }, { rintros ⟨⟨a,b⟩, ⟨c,d⟩⟩ ⟨⟨i,j⟩, ⟨k,l⟩⟩ H₁ H₂, simp only [finset.mem_sigma, mem_divisors_antidiagonal, and_imp, prod.mk.inj_iff, add_comm, heq_iff_eq] at H₁ H₂ ⊢, rintros rfl h2 rfl rfl, exact ⟨⟨eq.trans H₁.2.1.symm H₂.2.1, rfl⟩, rfl, rfl⟩ }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, refine ⟨⟨(i*k, l), (i, k)⟩, _, _⟩, { simp only [finset.mem_sigma, mem_divisors_antidiagonal] at H ⊢, rcases H with ⟨⟨rfl, n0⟩, rfl, j0⟩, refine ⟨⟨mul_assoc _ _ _, n0⟩, rfl, _⟩, rw mul_ne_zero_iff at *, exact ⟨n0.1, j0.1⟩ }, { simp only [true_and, mem_divisors_antidiagonal, and_true, prod.mk.inj_iff, eq_self_iff_true, ne.def, mem_sigma, heq_iff_eq] at H ⊢, rw H.2.1 } } end lemma one_smul' (b : arithmetic_function M) : (1 : arithmetic_function R) • b = b := begin ext, rw smul_apply, by_cases x0 : x = 0, {simp [x0]}, have h : {(1,x)} ⊆ divisors_antidiagonal x := by simp [x0], rw ← sum_subset h, {simp}, intros y ymem ynmem, have y1ne : y.fst ≠ 1, { intro con, simp only [con, mem_divisors_antidiagonal, one_mul, ne.def] at ymem, simp only [mem_singleton, prod.ext_iff] at ynmem, tauto }, simp [y1ne], end end module section semiring variable [semiring R] instance : monoid (arithmetic_function R) := { one_mul := one_smul', mul_one := λ f, begin ext, rw mul_apply, by_cases x0 : x = 0, {simp [x0]}, have h : {(x,1)} ⊆ divisors_antidiagonal x := by simp [x0], rw ← sum_subset h, {simp}, intros y ymem ynmem, have y2ne : y.snd ≠ 1, { intro con, simp only [con, mem_divisors_antidiagonal, mul_one, ne.def] at ymem, simp only [mem_singleton, prod.ext_iff] at ynmem, tauto }, simp [y2ne], end, mul_assoc := mul_smul', .. arithmetic_function.has_one, .. arithmetic_function.has_mul } instance : semiring (arithmetic_function R) := { zero_mul := λ f, by { ext, simp only [mul_apply, zero_mul, sum_const_zero, zero_apply] }, mul_zero := λ f, by { ext, simp only [mul_apply, sum_const_zero, mul_zero, zero_apply] }, left_distrib := λ a b c, by { ext, simp only [←sum_add_distrib, mul_add, mul_apply, add_apply] }, right_distrib := λ a b c, by { ext, simp only [←sum_add_distrib, add_mul, mul_apply, add_apply] }, .. arithmetic_function.has_zero R, .. arithmetic_function.has_mul, .. arithmetic_function.has_add, .. arithmetic_function.add_comm_monoid, .. arithmetic_function.monoid } end semiring instance [comm_semiring R] : comm_semiring (arithmetic_function R) := { mul_comm := λ f g, by { ext, rw [mul_apply, ← map_swap_divisors_antidiagonal, sum_map], simp [mul_comm] }, .. arithmetic_function.semiring } instance [comm_ring R] : comm_ring (arithmetic_function R) := { .. arithmetic_function.add_comm_group, .. arithmetic_function.comm_semiring } instance {M : Type*} [semiring R] [add_comm_monoid M] [module R M] : module (arithmetic_function R) (arithmetic_function M) := { one_smul := one_smul', mul_smul := mul_smul', smul_add := λ r x y, by { ext, simp only [sum_add_distrib, smul_add, smul_apply, add_apply] }, smul_zero := λ r, by { ext, simp only [smul_apply, sum_const_zero, smul_zero, zero_apply] }, add_smul := λ r s x, by { ext, simp only [add_smul, sum_add_distrib, smul_apply, add_apply] }, zero_smul := λ r, by { ext, simp only [smul_apply, sum_const_zero, zero_smul, zero_apply] }, } section zeta /-- `ζ 0 = 0`, otherwise `ζ x = 1`. The Dirichlet Series is the Riemann ζ. -/ def zeta : arithmetic_function ℕ := ⟨λ x, ite (x = 0) 0 1, rfl⟩ localized "notation `ζ` := zeta" in arithmetic_function @[simp] lemma zeta_apply {x : ℕ} : ζ x = if (x = 0) then 0 else 1 := rfl lemma zeta_apply_ne {x : ℕ} (h : x ≠ 0) : ζ x = 1 := if_neg h @[simp] theorem coe_zeta_mul_apply [semiring R] {f : arithmetic_function R} {x : ℕ} : (↑ζ * f) x = ∑ i in divisors x, f i := begin rw mul_apply, transitivity ∑ i in divisors_antidiagonal x, f i.snd, { apply sum_congr rfl, intros i hi, rcases mem_divisors_antidiagonal.1 hi with ⟨rfl, h⟩, rw [nat_coe_apply, zeta_apply_ne (left_ne_zero_of_mul h), cast_one, one_mul] }, { apply sum_bij (λ i h, prod.snd i), { rintros ⟨a, b⟩ h, simp [snd_mem_divisors_of_mem_antidiagonal h] }, { rintros ⟨a, b⟩ h, refl }, { rintros ⟨a1, b1⟩ ⟨a2, b2⟩ h1 h2 h, dsimp at h, rw h at *, rw mem_divisors_antidiagonal at *, ext, swap, {refl}, simp only [prod.fst, prod.snd] at *, apply nat.eq_of_mul_eq_mul_right _ (eq.trans h1.1 h2.1.symm), rcases h1 with ⟨rfl, h⟩, apply nat.pos_of_ne_zero (right_ne_zero_of_mul h) }, { intros a ha, rcases mem_divisors.1 ha with ⟨⟨b, rfl⟩, ne0⟩, use (b, a), simp [ne0, mul_comm] } } end theorem coe_zeta_smul_apply {M : Type*} [comm_ring R] [add_comm_group M] [module R M] {f : arithmetic_function M} {x : ℕ} : ((↑ζ : arithmetic_function R) • f) x = ∑ i in divisors x, f i := begin rw smul_apply, transitivity ∑ i in divisors_antidiagonal x, f i.snd, { apply sum_congr rfl, intros i hi, rcases mem_divisors_antidiagonal.1 hi with ⟨rfl, h⟩, rw [nat_coe_apply, zeta_apply_ne (left_ne_zero_of_mul h), cast_one, one_smul] }, { apply sum_bij (λ i h, prod.snd i), { rintros ⟨a, b⟩ h, simp [snd_mem_divisors_of_mem_antidiagonal h] }, { rintros ⟨a, b⟩ h, refl }, { rintros ⟨a1, b1⟩ ⟨a2, b2⟩ h1 h2 h, dsimp at h, rw h at *, rw mem_divisors_antidiagonal at *, ext, swap, {refl}, simp only [prod.fst, prod.snd] at *, apply nat.eq_of_mul_eq_mul_right _ (eq.trans h1.1 h2.1.symm), rcases h1 with ⟨rfl, h⟩, apply nat.pos_of_ne_zero (right_ne_zero_of_mul h) }, { intros a ha, rcases mem_divisors.1 ha with ⟨⟨b, rfl⟩, ne0⟩, use (b, a), simp [ne0, mul_comm] } } end @[simp] theorem coe_mul_zeta_apply [semiring R] {f : arithmetic_function R} {x : ℕ} : (f * ζ) x = ∑ i in divisors x, f i := begin apply opposite.op_injective, rw [op_sum], convert @coe_zeta_mul_apply Rᵒᵖ _ { to_fun := opposite.op ∘ f, map_zero' := by simp} x, rw [mul_apply, mul_apply, op_sum], conv_lhs { rw ← map_swap_divisors_antidiagonal, }, rw sum_map, apply sum_congr rfl, intros y hy, by_cases h1 : y.fst = 0, { simp [function.comp_apply, h1] }, { simp only [h1, mul_one, one_mul, prod.fst_swap, function.embedding.coe_fn_mk, prod.snd_swap, if_false, zeta_apply, zero_hom.coe_mk, nat_coe_apply, cast_one] } end theorem zeta_mul_apply {f : arithmetic_function ℕ} {x : ℕ} : (ζ * f) x = ∑ i in divisors x, f i := by rw [← nat_coe_nat ζ, coe_zeta_mul_apply] theorem mul_zeta_apply {f : arithmetic_function ℕ} {x : ℕ} : (f * ζ) x = ∑ i in divisors x, f i := by rw [← nat_coe_nat ζ, coe_mul_zeta_apply] end zeta open_locale arithmetic_function section pmul /-- This is the pointwise product of `arithmetic_function`s. -/ def pmul [mul_zero_class R] (f g : arithmetic_function R) : arithmetic_function R := ⟨λ x, f x * g x, by simp⟩ @[simp] lemma pmul_apply [mul_zero_class R] {f g : arithmetic_function R} {x : ℕ} : f.pmul g x = f x * g x := rfl lemma pmul_comm [comm_monoid_with_zero R] (f g : arithmetic_function R) : f.pmul g = g.pmul f := by { ext, simp [mul_comm] } variable [semiring R] @[simp] lemma pmul_zeta (f : arithmetic_function R) : f.pmul ↑ζ = f := begin ext x, cases x; simp [nat.succ_ne_zero], end @[simp] lemma zeta_pmul (f : arithmetic_function R) : (ζ : arithmetic_function R).pmul f = f := begin ext x, cases x; simp [nat.succ_ne_zero], end /-- This is the pointwise power of `arithmetic_function`s. -/ def ppow (f : arithmetic_function R) (k : ℕ) : arithmetic_function R := if h0 : k = 0 then ζ else ⟨λ x, (f x) ^ k, by { rw [map_zero], exact zero_pow (nat.pos_of_ne_zero h0) }⟩ @[simp] lemma ppow_zero {f : arithmetic_function R} : f.ppow 0 = ζ := by rw [ppow, dif_pos rfl] @[simp] lemma ppow_apply {f : arithmetic_function R} {k x : ℕ} (kpos : 0 < k) : f.ppow k x = (f x) ^ k := by { rw [ppow, dif_neg (ne_of_gt kpos)], refl } lemma ppow_succ {f : arithmetic_function R} {k : ℕ} : f.ppow (k + 1) = f.pmul (f.ppow k) := begin ext x, rw [ppow_apply (nat.succ_pos k), pow_succ], induction k; simp, end lemma ppow_succ' {f : arithmetic_function R} {k : ℕ} {kpos : 0 < k} : f.ppow (k + 1) = (f.ppow k).pmul f := begin ext x, rw [ppow_apply (nat.succ_pos k), pow_succ'], induction k; simp, end end pmul /-- Multiplicative functions -/ def is_multiplicative [monoid_with_zero R] (f : arithmetic_function R) : Prop := f 1 = 1 ∧ (∀ {m n : ℕ}, m.coprime n → f (m * n) = f m * f n) namespace is_multiplicative section monoid_with_zero variable [monoid_with_zero R] @[simp] lemma map_one {f : arithmetic_function R} (h : f.is_multiplicative) : f 1 = 1 := h.1 @[simp] lemma map_mul_of_coprime {f : arithmetic_function R} (hf : f.is_multiplicative) {m n : ℕ} (h : m.coprime n) : f (m * n) = f m * f n := hf.2 h end monoid_with_zero lemma nat_cast {f : arithmetic_function ℕ} [semiring R] (h : f.is_multiplicative) : is_multiplicative (f : arithmetic_function R) := ⟨by simp [h], λ m n cop, by simp [cop, h]⟩ lemma int_cast {f : arithmetic_function ℤ} [ring R] (h : f.is_multiplicative) : is_multiplicative (f : arithmetic_function R) := ⟨by simp [h], λ m n cop, by simp [cop, h]⟩ lemma mul [comm_semiring R] {f g : arithmetic_function R} (hf : f.is_multiplicative) (hg : g.is_multiplicative) : is_multiplicative (f * g) := ⟨by { simp [hf, hg], }, begin simp only [mul_apply], intros m n cop, rw sum_mul_sum, symmetry, apply sum_bij (λ (x : (ℕ × ℕ) × ℕ × ℕ) h, (x.1.1 * x.2.1, x.1.2 * x.2.2)), { rintros ⟨⟨a1, a2⟩, ⟨b1, b2⟩⟩ h, simp only [mem_divisors_antidiagonal, ne.def, mem_product] at h, rcases h with ⟨⟨rfl, ha⟩, ⟨rfl, hb⟩⟩, simp only [mem_divisors_antidiagonal, nat.mul_eq_zero, ne.def], split, {ring}, rw nat.mul_eq_zero at *, apply not_or ha hb }, { rintros ⟨⟨a1, a2⟩, ⟨b1, b2⟩⟩ h, simp only [mem_divisors_antidiagonal, ne.def, mem_product] at h, rcases h with ⟨⟨rfl, ha⟩, ⟨rfl, hb⟩⟩, dsimp only, rw [hf.map_mul_of_coprime cop.coprime_mul_right.coprime_mul_right_right, hg.map_mul_of_coprime cop.coprime_mul_left.coprime_mul_left_right], ring, }, { rintros ⟨⟨a1, a2⟩, ⟨b1, b2⟩⟩ ⟨⟨c1, c2⟩, ⟨d1, d2⟩⟩ hab hcd h, simp only [mem_divisors_antidiagonal, ne.def, mem_product] at hab, rcases hab with ⟨⟨rfl, ha⟩, ⟨rfl, hb⟩⟩, simp only [mem_divisors_antidiagonal, ne.def, mem_product] at hcd, simp only [prod.mk.inj_iff] at h, ext; dsimp only, { transitivity nat.gcd (a1 * a2) (a1 * b1), { rw [nat.gcd_mul_left, cop.coprime_mul_left.coprime_mul_right_right.gcd_eq_one, mul_one] }, { rw [← hcd.1.1, ← hcd.2.1] at cop, rw [← hcd.1.1, h.1, nat.gcd_mul_left, cop.coprime_mul_left.coprime_mul_right_right.gcd_eq_one, mul_one] } }, { transitivity nat.gcd (a1 * a2) (a2 * b2), { rw [mul_comm, nat.gcd_mul_left, cop.coprime_mul_right.coprime_mul_left_right.gcd_eq_one, mul_one] }, { rw [← hcd.1.1, ← hcd.2.1] at cop, rw [← hcd.1.1, h.2, mul_comm, nat.gcd_mul_left, cop.coprime_mul_right.coprime_mul_left_right.gcd_eq_one, mul_one] } }, { transitivity nat.gcd (b1 * b2) (a1 * b1), { rw [mul_comm, nat.gcd_mul_right, cop.coprime_mul_right.coprime_mul_left_right.symm.gcd_eq_one, one_mul] }, { rw [← hcd.1.1, ← hcd.2.1] at cop, rw [← hcd.2.1, h.1, mul_comm c1 d1, nat.gcd_mul_left, cop.coprime_mul_right.coprime_mul_left_right.symm.gcd_eq_one, mul_one] } }, { transitivity nat.gcd (b1 * b2) (a2 * b2), { rw [nat.gcd_mul_right, cop.coprime_mul_left.coprime_mul_right_right.symm.gcd_eq_one, one_mul] }, { rw [← hcd.1.1, ← hcd.2.1] at cop, rw [← hcd.2.1, h.2, nat.gcd_mul_right, cop.coprime_mul_left.coprime_mul_right_right.symm.gcd_eq_one, one_mul] } } }, { rintros ⟨b1, b2⟩ h, simp only [mem_divisors_antidiagonal, ne.def, mem_product] at h, use ((b1.gcd m, b2.gcd m), (b1.gcd n, b2.gcd n)), simp only [exists_prop, prod.mk.inj_iff, ne.def, mem_product, mem_divisors_antidiagonal], rw [← cop.gcd_mul _, ← cop.gcd_mul _, ← h.1, nat.gcd_mul_gcd_of_coprime_of_mul_eq_mul cop h.1, nat.gcd_mul_gcd_of_coprime_of_mul_eq_mul cop.symm _], { rw [nat.mul_eq_zero, decidable.not_or_iff_and_not] at h, simp [h.2.1, h.2.2] }, rw [mul_comm n m, h.1] } end⟩ lemma pmul [comm_semiring R] {f g : arithmetic_function R} (hf : f.is_multiplicative) (hg : g.is_multiplicative) : is_multiplicative (f.pmul g) := ⟨by { simp [hf, hg], }, λ m n cop, begin simp only [pmul_apply, hf.map_mul_of_coprime cop, hg.map_mul_of_coprime cop], ring, end⟩ end is_multiplicative section special_functions /-- The identity on `ℕ` as an `arithmetic_function`. -/ def id : arithmetic_function ℕ := ⟨id, rfl⟩ @[simp] lemma id_apply {x : ℕ} : id x = x := rfl /-- `pow k n = n ^ k`, except `pow 0 0 = 0`. -/ def pow (k : ℕ) : arithmetic_function ℕ := id.ppow k @[simp] lemma pow_apply {k n : ℕ} : pow k n = if (k = 0 ∧ n = 0) then 0 else n ^ k := begin cases k, { simp [pow] }, simp [pow, (ne_of_lt (nat.succ_pos k)).symm], end /-- `σ k n` is the sum of the `k`th powers of the divisors of `n` -/ def sigma (k : ℕ) : arithmetic_function ℕ := ⟨λ n, ∑ d in divisors n, d ^ k, by simp⟩ localized "notation `σ` := sigma" in arithmetic_function @[simp] lemma sigma_apply {k n : ℕ} : σ k n = ∑ d in divisors n, d ^ k := rfl lemma sigma_one_apply {n : ℕ} : σ 1 n = ∑ d in divisors n, d := by simp lemma zeta_mul_pow_eq_sigma {k : ℕ} : ζ * pow k = σ k := begin ext, rw [sigma, zeta_mul_apply], apply sum_congr rfl, intros x hx, rw [pow_apply, if_neg (not_and_of_not_right _ _)], contrapose! hx, simp [hx], end lemma is_multiplicative_zeta : is_multiplicative ζ := ⟨by simp, λ m n cop, begin cases m, {simp}, cases n, {simp}, simp [nat.succ_ne_zero] end⟩ lemma is_multiplicative_id : is_multiplicative arithmetic_function.id := ⟨rfl, λ _ _ _, rfl⟩ lemma is_multiplicative.ppow [comm_semiring R] {f : arithmetic_function R} (hf : f.is_multiplicative) {k : ℕ} : is_multiplicative (f.ppow k) := begin induction k with k hi, { exact is_multiplicative_zeta.nat_cast }, { rw ppow_succ, apply hf.pmul hi }, end lemma is_multiplicative_pow {k : ℕ} : is_multiplicative (pow k) := is_multiplicative_id.ppow lemma is_multiplicative_sigma {k : ℕ} : is_multiplicative (sigma k) := begin rw [← zeta_mul_pow_eq_sigma], apply ((is_multiplicative_zeta).mul is_multiplicative_pow) end /-- `Ω n` is the number of prime factors of `n`. -/ def card_factors : arithmetic_function ℕ := ⟨λ n, n.factors.length, by simp⟩ localized "notation `Ω` := card_factors" in arithmetic_function lemma card_factors_apply {n : ℕ} : Ω n = n.factors.length := rfl @[simp] lemma card_factors_one : Ω 1 = 0 := by simp [card_factors] lemma card_factors_eq_one_iff_prime {n : ℕ} : Ω n = 1 ↔ n.prime := begin refine ⟨λ h, _, λ h, list.length_eq_one.2 ⟨n, factors_prime h⟩⟩, cases n, { contrapose! h, simp }, rcases list.length_eq_one.1 h with ⟨x, hx⟩, rw [← prod_factors n.succ_pos, hx, list.prod_singleton], apply prime_of_mem_factors, rw [hx, list.mem_singleton] end lemma card_factors_mul {m n : ℕ} (m0 : m ≠ 0) (n0 : n ≠ 0) : Ω (m * n) = Ω m + Ω n := by rw [card_factors_apply, card_factors_apply, card_factors_apply, ← multiset.coe_card, ← factors_eq, unique_factorization_monoid.factors_mul m0 n0, factors_eq, factors_eq, multiset.card_add, multiset.coe_card, multiset.coe_card] lemma card_factors_multiset_prod {s : multiset ℕ} (h0 : s.prod ≠ 0) : Ω s.prod = (multiset.map Ω s).sum := begin revert h0, apply s.induction_on, by simp, intros a t h h0, rw [multiset.prod_cons, mul_ne_zero_iff] at h0, simp [h0, card_factors_mul, h], end /-- `ω n` is the number of distinct prime factors of `n`. -/ def card_distinct_factors : arithmetic_function ℕ := ⟨λ n, n.factors.erase_dup.length, by simp⟩ localized "notation `ω` := card_distinct_factors" in arithmetic_function lemma card_distinct_factors_zero : ω 0 = 0 := by simp lemma card_distinct_factors_apply {n : ℕ} : ω n = n.factors.erase_dup.length := rfl lemma card_distinct_factors_eq_card_factors_iff_squarefree {n : ℕ} (h0 : n ≠ 0) : ω n = Ω n ↔ squarefree n := begin rw [squarefree_iff_nodup_factors h0, card_distinct_factors_apply], split; intro h, { rw ← list.eq_of_sublist_of_length_eq n.factors.erase_dup_sublist h, apply list.nodup_erase_dup }, { rw list.erase_dup_eq_self.2 h, refl } end /-- `μ` is the Möbius function. If `n` is squarefree with an even number of distinct prime factors, `μ n = 1`. If `n` is squarefree with an odd number of distinct prime factors, `μ n = -1`. If `n` is not squarefree, `μ n = 0`. -/ def moebius : arithmetic_function ℤ := ⟨λ n, if squarefree n then (-1) ^ (card_factors n) else 0, by simp⟩ localized "notation `μ` := moebius" in arithmetic_function @[simp] lemma moebius_apply_of_squarefree {n : ℕ} (h : squarefree n): μ n = (-1) ^ (card_factors n) := if_pos h @[simp] lemma moebius_eq_zero_of_not_squarefree {n : ℕ} (h : ¬ squarefree n): μ n = 0 := if_neg h lemma moebius_ne_zero_iff_squarefree {n : ℕ} : μ n ≠ 0 ↔ squarefree n := begin split; intro h, { contrapose! h, simp [h] }, { simp [h, pow_ne_zero] } end lemma moebius_ne_zero_iff_eq_or {n : ℕ} : μ n ≠ 0 ↔ μ n = 1 ∨ μ n = -1 := begin split; intro h, { rw moebius_ne_zero_iff_squarefree at h, rw moebius_apply_of_squarefree h, apply neg_one_pow_eq_or }, { rcases h with h | h; simp [h] } end open unique_factorization_monoid @[simp] lemma coe_moebius_mul_coe_zeta [comm_ring R] : (μ * ζ : arithmetic_function R) = 1 := begin ext x, cases x, { simp only [divisors_zero, sum_empty, ne.def, not_false_iff, coe_mul_zeta_apply, zero_ne_one, one_apply_ne] }, cases x, { simp only [moebius_apply_of_squarefree, card_factors_one, squarefree_one, divisors_one, int.cast_one, sum_singleton, coe_mul_zeta_apply, one_one, int_coe_apply, pow_zero] }, rw [coe_mul_zeta_apply, one_apply_ne (ne_of_gt (succ_lt_succ (nat.succ_pos _)))], simp_rw [int_coe_apply], rw [←int.cast_sum, ← sum_filter_ne_zero], convert int.cast_zero, simp only [moebius_ne_zero_iff_squarefree], suffices : ∑ (y : finset ℕ) in (unique_factorization_monoid.factors x.succ.succ).to_finset.powerset, ite (squarefree y.val.prod) ((-1:ℤ) ^ Ω y.val.prod) 0 = 0, { have h : ∑ i in _, ite (squarefree i) ((-1:ℤ) ^ Ω i) 0 = _ := (sum_divisors_filter_squarefree (nat.succ_ne_zero _)), exact (eq.trans (by congr') h).trans this }, apply eq.trans (sum_congr rfl _) (sum_powerset_neg_one_pow_card_of_nonempty _), { intros y hy, rw [finset.mem_powerset, ← finset.val_le_iff, multiset.to_finset_val] at hy, have h : unique_factorization_monoid.factors y.val.prod = y.val, { apply factors_multiset_prod_of_irreducible, intros z hz, apply irreducible_of_factor _ (multiset.subset_of_le (le_trans hy (multiset.erase_dup_le _)) hz) }, rw [if_pos], { rw [card_factors_apply, ← multiset.coe_card, ← factors_eq, h, finset.card] }, rw [unique_factorization_monoid.squarefree_iff_nodup_factors, h], { apply y.nodup }, rw [ne.def, multiset.prod_eq_zero_iff], intro con, rw ← h at con, exact not_irreducible_zero (irreducible_of_factor 0 con) }, { rw finset.nonempty, rcases wf_dvd_monoid.exists_irreducible_factor _ (nat.succ_ne_zero _) with ⟨i, hi⟩, { rcases exists_mem_factors_of_dvd (nat.succ_ne_zero _) hi.1 hi.2 with ⟨j, hj, hj2⟩, use j, apply multiset.mem_to_finset.2 hj }, rw nat.is_unit_iff, norm_num }, end @[simp] lemma coe_zeta_mul_coe_moebius [comm_ring R] : (ζ * μ : arithmetic_function R) = 1 := by rw [mul_comm, coe_moebius_mul_coe_zeta] @[simp] lemma moebius_mul_coe_zeta : (μ * ζ : arithmetic_function ℤ) = 1 := by rw [← int_coe_int μ, coe_moebius_mul_coe_zeta] @[simp] lemma coe_zeta_mul_moebius : (ζ * μ : arithmetic_function ℤ) = 1 := by rw [← int_coe_int μ, coe_zeta_mul_coe_moebius] section comm_ring variable [comm_ring R] instance : invertible (ζ : arithmetic_function R) := { inv_of := μ, inv_of_mul_self := coe_moebius_mul_coe_zeta, mul_inv_of_self := coe_zeta_mul_coe_moebius} /-- A unit in `arithmetic_function R` that evaluates to `ζ`, with inverse `μ`. -/ def zeta_unit : units (arithmetic_function R) := ⟨ζ, μ, coe_zeta_mul_coe_moebius, coe_moebius_mul_coe_zeta⟩ @[simp] lemma coe_zeta_unit : ((zeta_unit : units (arithmetic_function R)) : arithmetic_function R) = ζ := rfl @[simp] lemma inv_zeta_unit : ((zeta_unit⁻¹ : units (arithmetic_function R)) : arithmetic_function R) = μ := rfl end comm_ring /-- Möbius inversion for functions to an `add_comm_group`. -/ theorem sum_eq_iff_sum_smul_moebius_eq [add_comm_group R] {f g : ℕ → R} : (∀ (n : ℕ), 0 < n → ∑ i in (n.divisors), f i = g n) ↔ ∀ (n : ℕ), 0 < n → ∑ (x : ℕ × ℕ) in n.divisors_antidiagonal, μ x.fst • g x.snd = f n := begin let f' : arithmetic_function R := ⟨λ x, if x = 0 then 0 else f x, if_pos rfl⟩, let g' : arithmetic_function R := ⟨λ x, if x = 0 then 0 else g x, if_pos rfl⟩, transitivity (ζ : arithmetic_function ℤ) • f' = g', { rw ext_iff, apply forall_congr, intro n, cases n, { simp }, rw coe_zeta_smul_apply, simp only [n.succ_ne_zero, forall_prop_of_true, succ_pos', if_false, zero_hom.coe_mk], rw sum_congr rfl (λ x hx, _), rw (if_neg (ne_of_gt (nat.pos_of_mem_divisors hx))) }, transitivity μ • g' = f', { split; intro h, { rw [← h, ← mul_smul, moebius_mul_coe_zeta, one_smul] }, { rw [← h, ← mul_smul, coe_zeta_mul_moebius, one_smul] } }, { rw ext_iff, apply forall_congr, intro n, cases n, { simp }, simp only [n.succ_ne_zero, forall_prop_of_true, succ_pos', smul_apply, if_false, zero_hom.coe_mk], rw sum_congr rfl (λ x hx, _), rw (if_neg (ne_of_gt (nat.pos_of_mem_divisors (snd_mem_divisors_of_mem_antidiagonal hx)))) }, end /-- Möbius inversion for functions to a `comm_ring`. -/ theorem sum_eq_iff_sum_mul_moebius_eq [comm_ring R] {f g : ℕ → R} : (∀ (n : ℕ), 0 < n → ∑ i in (n.divisors), f i = g n) ↔ ∀ (n : ℕ), 0 < n → ∑ (x : ℕ × ℕ) in n.divisors_antidiagonal, (μ x.fst : R) * g x.snd = f n := begin rw sum_eq_iff_sum_smul_moebius_eq, apply forall_congr, intro a, apply imp_congr (iff.refl _) (eq.congr_left (sum_congr rfl (λ x hx, _))), rw [gsmul_eq_mul], end /-- Möbius inversion for functions to a `comm_group`. -/ theorem prod_eq_iff_prod_pow_moebius_eq [comm_group R] {f g : ℕ → R} : (∀ (n : ℕ), 0 < n → ∏ i in (n.divisors), f i = g n) ↔ ∀ (n : ℕ), 0 < n → ∏ (x : ℕ × ℕ) in n.divisors_antidiagonal, g x.snd ^ (μ x.fst) = f n := @sum_eq_iff_sum_smul_moebius_eq (additive R) _ _ _ /-- Möbius inversion for functions to a `comm_group_with_zero`. -/ theorem prod_eq_iff_prod_pow_moebius_eq_of_nonzero [comm_group_with_zero R] {f g : ℕ → R} (hf : ∀ (n : ℕ), 0 < n → f n ≠ 0) (hg : ∀ (n : ℕ), 0 < n → g n ≠ 0) : (∀ (n : ℕ), 0 < n → ∏ i in (n.divisors), f i = g n) ↔ ∀ (n : ℕ), 0 < n → ∏ (x : ℕ × ℕ) in n.divisors_antidiagonal, g x.snd ^ (μ x.fst) = f n := begin refine iff.trans (iff.trans (forall_congr (λ n, _)) (@prod_eq_iff_prod_pow_moebius_eq (units R) _ (λ n, if h : 0 < n then units.mk0 (f n) (hf n h) else 1) (λ n, if h : 0 < n then units.mk0 (g n) (hg n h) else 1))) (forall_congr (λ n, _)); refine imp_congr_right (λ hn, _), { dsimp, rw [dif_pos hn, ← units.eq_iff, ← units.coe_hom_apply, monoid_hom.map_prod, units.coe_mk0, prod_congr rfl _], intros x hx, rw [dif_pos (nat.pos_of_mem_divisors hx), units.coe_hom_apply, units.coe_mk0] }, { dsimp, rw [dif_pos hn, ← units.eq_iff, ← units.coe_hom_apply, monoid_hom.map_prod, units.coe_mk0, prod_congr rfl _], intros x hx, rw [dif_pos (nat.pos_of_mem_divisors (nat.snd_mem_divisors_of_mem_antidiagonal hx)), units.coe_hom_apply, units.coe_gpow', units.coe_mk0] } end end special_functions end arithmetic_function end nat
5329e5d6b6662452b61a760b73e21dcbb2f7c292
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/localization/construction.lean
e0d318df534db37d1e937036ceeeaae552797bcf
[ "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
13,916
lean
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import category_theory.morphism_property import category_theory.category.Quiv /-! # Construction of the localized category > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file constructs the localized category, obtained by formally inverting a class of maps `W : morphism_property C` in a category `C`. We first construct a quiver `loc_quiver W` whose objects are the same as those of `C` and whose maps are the maps in `C` and placeholders for the formal inverses of the maps in `W`. The localized category `W.localization` is obtained by taking the quotient of the path category of `loc_quiver W` by the congruence generated by four types of relations. The obvious functor `Q W : C ⥤ W.localization` satisfies the universal property of the localization. Indeed, if `G : C ⥤ D` sends morphisms in `W` to isomorphisms in `D` (i.e. we have `hG : W.is_inverted_by G`), then there exists a unique functor `G' : W.localization ⥤ D` such that `Q W ≫ G' = G`. This `G'` is `lift G hG`. The expected property of `lift G hG` if expressed by the lemma `fac` and the uniqueness is expressed by `uniq`. ## References * [P. Gabriel, M. Zisman, *Calculus of fractions and homotopy theory*][gabriel-zisman-1967] -/ noncomputable theory open category_theory.category namespace category_theory variables {C : Type*} [category C] (W : morphism_property C) {D : Type*} [category D] namespace localization namespace construction /-- If `W : morphism_property C`, `loc_quiver W` is a quiver with the same objects as `C`, and whose morphisms are those in `C` and placeholders for formal inverses of the morphisms in `W`. -/ @[nolint has_nonempty_instance] structure loc_quiver (W : morphism_property C) := (obj : C) instance : quiver (loc_quiver W) := { hom := λ A B, (A.obj ⟶ B.obj) ⊕ { f : B.obj ⟶ A.obj // W f} } /-- The object in the path category of `loc_quiver W` attached to an object in the category `C` -/ def ι_paths (X : C) : paths (loc_quiver W) := ⟨X⟩ /-- The morphism in the path category associated to a morphism in the original category. -/ @[simp] def ψ₁ {X Y : C} (f : X ⟶ Y) : ι_paths W X ⟶ ι_paths W Y := paths.of.map (sum.inl f) /-- The morphism in the path category corresponding to a formal inverse. -/ @[simp] def ψ₂ {X Y : C} (w : X ⟶ Y) (hw : W w) : ι_paths W Y ⟶ ι_paths W X := paths.of.map (sum.inr ⟨w, hw⟩) /-- The relations by which we take the quotient in order to get the localized category. -/ inductive relations : hom_rel (paths (loc_quiver W)) | id (X : C) : relations (ψ₁ W (𝟙 X)) (𝟙 _) | comp {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) : relations (ψ₁ W (f ≫ g)) (ψ₁ W f ≫ ψ₁ W g) | Winv₁ {X Y : C} (w : X ⟶ Y) (hw : W w) : relations (ψ₁ W w ≫ ψ₂ W w hw) (𝟙 _) | Winv₂ {X Y : C} (w : X ⟶ Y) (hw : W w) : relations (ψ₂ W w hw ≫ ψ₁ W w) (𝟙 _) end construction end localization namespace morphism_property open localization.construction /-- The localized category obtained by formally inverting the morphisms in `W : morphism_property C` -/ @[derive category, nolint has_nonempty_instance] def localization := category_theory.quotient (localization.construction.relations W) /-- The obvious functor `C ⥤ W.localization` -/ def Q : C ⥤ W.localization := { obj := λ X, (quotient.functor _).obj (paths.of.obj ⟨X⟩), map := λ X Y f, (quotient.functor _).map (ψ₁ W f), map_id' := λ X, quotient.sound _ (relations.id X), map_comp' := λ X Z Y f g, quotient.sound _ (relations.comp f g), } end morphism_property namespace localization namespace construction variable {W} /-- The isomorphism in `W.localization` associated to a morphism `w` in W -/ def Wiso {X Y : C} (w : X ⟶ Y) (hw : W w) : iso (W.Q.obj X) (W.Q.obj Y) := { hom := W.Q.map w, inv := (quotient.functor _).map (paths.of.map (sum.inr ⟨w, hw⟩)), hom_inv_id' := quotient.sound _ (relations.Winv₁ w hw), inv_hom_id' := quotient.sound _ (relations.Winv₂ w hw), } /-- The formal inverse in `W.localization` of a morphism `w` in `W`. -/ abbreviation Winv {X Y : C} (w : X ⟶ Y) (hw : W w) := (Wiso w hw).inv variable (W) lemma _root_.category_theory.morphism_property.Q_inverts : W.is_inverted_by W.Q := λ X Y w hw, is_iso.of_iso (localization.construction.Wiso w hw) variables {W} (G : C ⥤ D) (hG : W.is_inverted_by G) include G hG /-- The lifting of a functor to the path category of `loc_quiver W` -/ @[simps] def lift_to_path_category : paths (loc_quiver W) ⥤ D := Quiv.lift { obj := λ X, G.obj X.obj, map := λ X Y, begin rintro (f|⟨g, hg⟩), { exact G.map f, }, { haveI := hG g hg, exact inv (G.map g), }, end, } /-- The lifting of a functor `C ⥤ D` inverting `W` as a functor `W.localization ⥤ D` -/ @[simps] def lift : W.localization ⥤ D := quotient.lift (relations W) (lift_to_path_category G hG) begin rintro ⟨X⟩ ⟨Y⟩ f₁ f₂ r, rcases r, tidy, end @[simp] lemma fac : W.Q ⋙ lift G hG = G := functor.ext (λ X, rfl) begin intros X Y f, simp only [functor.comp_map, eq_to_hom_refl, comp_id, id_comp], dsimp [lift, lift_to_path_category, morphism_property.Q], rw compose_path_to_path, end omit G hG lemma uniq (G₁ G₂ : W.localization ⥤ D) (h : W.Q ⋙ G₁ = W.Q ⋙ G₂) : G₁ = G₂ := begin suffices h' : quotient.functor _ ⋙ G₁ = quotient.functor _ ⋙ G₂, { refine functor.ext _ _, { rintro ⟨⟨X⟩⟩, apply functor.congr_obj h, }, { rintros ⟨⟨X⟩⟩ ⟨⟨Y⟩⟩ ⟨f⟩, apply functor.congr_hom h', }, }, { refine paths.ext_functor _ _, { ext X, cases X, apply functor.congr_obj h, }, { rintro ⟨X⟩ ⟨Y⟩ (f|⟨w, hw⟩), { simpa only using functor.congr_hom h f, }, { have hw : W.Q.map w = (Wiso w hw).hom := rfl, have hw' := functor.congr_hom h w, simp only [functor.comp_map, hw] at hw', refine functor.congr_inv_of_congr_hom _ _ _ _ _ hw', all_goals { apply functor.congr_obj h, }, }, }, }, end variable (W) /-- The canonical bijection between objects in a category and its localization with respect to a morphism_property `W` -/ @[simps] def obj_equiv : C ≃ W.localization := { to_fun := W.Q.obj, inv_fun := λ X, X.as.obj, left_inv := λ X, rfl, right_inv := by { rintro ⟨⟨X⟩⟩, refl, }, } variable {W} /-- A `morphism_property` in `W.localization` is satisfied by all morphisms in the localized category if it contains the image of the morphisms in the original category, the inverses of the morphisms in `W` and if it is stable under composition -/ lemma morphism_property_is_top (P : morphism_property W.localization) (hP₁ : ∀ ⦃X Y : C⦄ (f : X ⟶ Y), P (W.Q.map f)) (hP₂ : ∀ ⦃X Y : C⦄ (w : X ⟶ Y) (hw : W w), P (Winv w hw)) (hP₃ : P.stable_under_composition) : P = ⊤ := begin ext X Y f, split, { intro hf, simp only [pi.top_apply], }, { intro hf, clear hf, let G : _ ⥤ W.localization := quotient.functor _, suffices : ∀ (X₁ X₂ : C) (p : localization.construction.ι_paths W X₁ ⟶ localization.construction.ι_paths W X₂), P (G.map p), { rcases X with ⟨⟨X⟩⟩, rcases Y with ⟨⟨Y⟩⟩, simpa only [functor.image_preimage] using this _ _ (G.preimage f), }, intros X₁ X₂ p, induction p with X₂ X₃ p g hp, { simpa only [functor.map_id] using hP₁ (𝟙 X₁), }, { cases X₂, cases X₃, let p' : ι_paths W X₁ ⟶ ι_paths W X₂ := p, rw [show p.cons g = p' ≫ quiver.hom.to_path g, by refl, G.map_comp], refine hP₃ _ _ hp _, rcases g with (g | ⟨g, hg⟩), { apply hP₁, }, { apply hP₂, }, }, }, end /-- A `morphism_property` in `W.localization` is satisfied by all morphisms in the localized category if it contains the image of the morphisms in the original category, if is stable under composition and if the property is stable by passing to inverses. -/ lemma morphism_property_is_top' (P : morphism_property W.localization) (hP₁ : ∀ ⦃X Y : C⦄ (f : X ⟶ Y), P (W.Q.map f)) (hP₂ : ∀ ⦃X Y : W.localization⦄ (e : X ≅ Y) (he : P e.hom), P e.inv) (hP₃ : P.stable_under_composition) : P = ⊤ := morphism_property_is_top P hP₁ (λ X Y w hw, hP₂ _ (by exact hP₁ w)) hP₃ namespace nat_trans_extension variables {F₁ F₂ : W.localization ⥤ D} (τ : W.Q ⋙ F₁ ⟶ W.Q ⋙ F₂) include τ /-- If `F₁` and `F₂` are functors `W.localization ⥤ D` and if we have `τ : W.Q ⋙ F₁ ⟶ W.Q ⋙ F₂`, we shall define a natural transformation `F₁ ⟶ F₂`. This is the `app` field of this natural transformation. -/ def app (X : W.localization) : F₁.obj X ⟶ F₂.obj X := eq_to_hom (congr_arg F₁.obj ((obj_equiv W).right_inv X).symm) ≫ τ.app ((obj_equiv W).inv_fun X) ≫ eq_to_hom (congr_arg F₂.obj ((obj_equiv W).right_inv X)) @[simp] lemma app_eq (X : C) : (app τ) (W.Q.obj X) = τ.app X := by simpa only [app, eq_to_hom_refl, comp_id, id_comp] end nat_trans_extension /-- If `F₁` and `F₂` are functors `W.localization ⥤ D`, a natural transformation `F₁ ⟶ F₂` can be obtained from a natural transformation `W.Q ⋙ F₁ ⟶ W.Q ⋙ F₂`. -/ @[simps] def nat_trans_extension {F₁ F₂ : W.localization ⥤ D} (τ : W.Q ⋙ F₁ ⟶ W.Q ⋙ F₂) : F₁ ⟶ F₂ := { app := nat_trans_extension.app τ, naturality' := λ X Y f, begin have h := morphism_property_is_top' (morphism_property.naturality_property (nat_trans_extension.app τ)) _ (morphism_property.naturality_property.is_stable_under_inverse _) (morphism_property.naturality_property.is_stable_under_composition _), swap, { intros X Y f, simpa only [morphism_property.naturality_property, nat_trans_extension.app_eq] using τ.naturality f, }, have hf : (⊤ : morphism_property _) f := by simp only [pi.top_apply], simpa only [← h] using hf, end, } @[simp] lemma nat_trans_extension_hcomp {F G : W.localization ⥤ D} (τ : W.Q ⋙ F ⟶ W.Q ⋙ G) : (𝟙 W.Q) ◫ nat_trans_extension τ = τ := begin ext X, simp only [nat_trans.hcomp_app, nat_trans.id_app, G.map_id, comp_id, nat_trans_extension_app, nat_trans_extension.app_eq], end lemma nat_trans_hcomp_injective {F G : W.localization ⥤ D} {τ₁ τ₂ : F ⟶ G} (h : 𝟙 W.Q ◫ τ₁ = 𝟙 W.Q ◫ τ₂) : τ₁ = τ₂ := begin ext X, have eq := (obj_equiv W).right_inv X, simp only [obj_equiv] at eq, rw [← eq, ← nat_trans.id_hcomp_app, ← nat_trans.id_hcomp_app, h], end variables (W D) namespace whiskering_left_equivalence /-- The functor `(W.localization ⥤ D) ⥤ (W.functors_inverting D)` induced by the composition with `W.Q : C ⥤ W.localization`. -/ @[simps] def functor : (W.localization ⥤ D) ⥤ (W.functors_inverting D) := full_subcategory.lift _ ((whiskering_left _ _ D).obj W.Q) (λ F, morphism_property.is_inverted_by.of_comp W W.Q W.Q_inverts _) /-- The function `(W.functors_inverting D) ⥤ (W.localization ⥤ D)` induced by `construction.lift`. -/ @[simps] def inverse : (W.functors_inverting D) ⥤ (W.localization ⥤ D) := { obj := λ G, lift G.obj G.property, map := λ G₁ G₂ τ, nat_trans_extension (eq_to_hom (by rw fac) ≫ τ ≫ eq_to_hom (by rw fac)), map_id' := λ G, nat_trans_hcomp_injective begin rw nat_trans_extension_hcomp, ext X, simpa only [nat_trans.comp_app, eq_to_hom_app, eq_to_hom_refl, comp_id, id_comp, nat_trans.hcomp_id_app, nat_trans.id_app, functor.map_id], end, map_comp' := λ G₁ G₂ G₃ τ₁ τ₂, nat_trans_hcomp_injective begin ext X, simpa only [nat_trans_extension_hcomp, nat_trans.comp_app, eq_to_hom_app, eq_to_hom_refl, id_comp, comp_id, nat_trans.hcomp_app, nat_trans.id_app, functor.map_id, nat_trans_extension_app, nat_trans_extension.app_eq], end, } /-- The unit isomorphism of the equivalence of categories `whiskering_left_equivalence W D`. -/ @[simps] def unit_iso : 𝟭 (W.localization ⥤ D) ≅ functor W D ⋙ inverse W D := eq_to_iso begin refine functor.ext (λ G, _) (λ G₁ G₂ τ, _), { apply uniq, dsimp [functor], rw fac, }, { apply nat_trans_hcomp_injective, ext X, simp only [functor.id_map, nat_trans.hcomp_app, comp_id, functor.comp_map, inverse_map, nat_trans.comp_app, eq_to_hom_app, eq_to_hom_refl, nat_trans_extension_app, nat_trans_extension.app_eq, functor_map_app, id_comp], }, end /-- The counit isomorphism of the equivalence of categories `whiskering_left_equivalence W D`. -/ @[simps] def counit_iso : inverse W D ⋙ functor W D ≅ 𝟭 (W.functors_inverting D) := eq_to_iso begin refine functor.ext _ _, { rintro ⟨G, hG⟩, ext1, apply fac, }, { rintros ⟨G₁, hG₁⟩ ⟨G₂, hG₂⟩ f, ext X, apply nat_trans_extension.app_eq, }, end end whiskering_left_equivalence /-- The equivalence of categories `(W.localization ⥤ D) ≌ (W.functors_inverting D)` induced by the composition with `W.Q : C ⥤ W.localization`. -/ def whiskering_left_equivalence : (W.localization ⥤ D) ≌ W.functors_inverting D := { functor := whiskering_left_equivalence.functor W D, inverse := whiskering_left_equivalence.inverse W D, unit_iso := whiskering_left_equivalence.unit_iso W D, counit_iso := whiskering_left_equivalence.counit_iso W D, functor_unit_iso_comp' := λ F, begin ext X, simpa only [eq_to_hom_app, whiskering_left_equivalence.unit_iso_hom, whiskering_left_equivalence.counit_iso_hom, eq_to_hom_map, eq_to_hom_trans, eq_to_hom_refl], end, } end construction end localization end category_theory
6140d9159f183b66584198cc6521b32f92199b11
c9ba4946202cfd1e2586e71960dfed00503dcdf4
/src/object_k/object_var.lean
7c656fdec4544b04e095b3f05510393600ca9c6a
[]
no_license
ammkrn/learning_semantics_of_k
f55f669b369e32ef8407c16521b21ac5c106dc4d
c1487b538e1decc0f1fd389cd36bc36d2da012ab
refs/heads/master
1,588,081,593,954
1,552,449,093,000
1,552,449,093,000
175,315,800
0
0
null
null
null
null
UTF-8
Lean
false
false
1,351
lean
import .object_sort import meta_k.meta_sort -- ########################################## -- ##### object_variable ############## @[derive decidable_eq] inductive object_variable : Type | mk : string → object_sort → object_variable open object_variable notation `~Variable` := object_variable notation `~VariableList` := list object_variable notation `~variable` := object_variable.mk definition object_variable_get_sort : object_variable → object_sort | (object_variable.mk (str) (s)) := s instance object_variable.has_sort : has_sort object_variable object_sort := ⟨ object_variable_get_sort ⟩ definition object_var_to_string : object_variable → string | (object_variable.mk (str) (sort)) := (repr str) ++ " : " ++ (repr (object_sort_get_name sort)) definition object_var_get_name : object_variable → string | (object_variable.mk (str) (sort)) := (str) instance : has_name object_variable := ⟨ object_var_get_name ⟩ instance : has_repr object_variable := has_repr.mk (object_var_to_string) def object_sort.to_object_variable : object_sort → ~Variable | s := mk (object_sort_get_name s) s instance object_sort_to_object_var_lift : has_lift object_sort ~Variable := ⟨ object_sort.to_object_variable ⟩ instance object_variable.is_Variable : is_Variable object_variable := ⟨ object_var_get_name ⟩
e0546bd971078f3847c875ae6df327461678df04
e030b0259b777fedcdf73dd966f3f1556d392178
/library/init/funext.lean
6e6fe7f9fe186657b639e5ca853b9bf3e42fb1aa
[ "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
2,127
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad Extensional equality for functions, and a proof of function extensionality from quotients. -/ prelude import init.data.quot init.logic universe variables u v namespace function variables {α : Type u} {β : α → Type v} protected def equiv (f₁ f₂ : Π x : α, β x) : Prop := ∀ x, f₁ x = f₂ x local infix `~` := function.equiv protected theorem equiv.refl (f : Π x : α, β x) : f ~ f := take x, rfl protected theorem equiv.symm {f₁ f₂ : Π x: α, β x} : f₁ ~ f₂ → f₂ ~ f₁ := λ h x, eq.symm (h x) protected theorem equiv.trans {f₁ f₂ f₃ : Π x: α, β x} : f₁ ~ f₂ → f₂ ~ f₃ → f₁ ~ f₃ := λ h₁ h₂ x, eq.trans (h₁ x) (h₂ x) protected theorem equiv.is_equivalence (α : Type u) (β : α → Type v) : equivalence (@function.equiv α β) := mk_equivalence (@function.equiv α β) (@equiv.refl α β) (@equiv.symm α β) (@equiv.trans α β) end function section open quot variables {α : Type u} {β : α → Type v} @[instance] private def fun_setoid (α : Type u) (β : α → Type v) : setoid (Π x : α, β x) := setoid.mk (@function.equiv α β) (function.equiv.is_equivalence α β) private def extfun (α : Type u) (β : α → Type v) : Type (imax u v) := quot (fun_setoid α β) private def fun_to_extfun (f : Π x : α, β x) : extfun α β := ⟦f⟧ private def extfun_app (f : extfun α β) : Π x : α, β x := take x, quot.lift_on f (λ f : Π x : α, β x, f x) (λ f₁ f₂ h, h x) theorem funext {f₁ f₂ : Π x : α, β x} : (∀ x, f₁ x = f₂ x) → f₁ = f₂ := assume h, calc f₁ = extfun_app ⟦f₁⟧ : rfl ... = extfun_app ⟦f₂⟧ : @sound _ _ f₁ f₂ h ▸ rfl ... = f₂ : rfl end attribute [intro!] funext local infix `~` := function.equiv instance pi.subsingleton {α : Type u} {β : α → Type v} [∀ a, subsingleton (β a)] : subsingleton (Π a, β a) := ⟨λ f₁ f₂, funext (λ a, subsingleton.elim (f₁ a) (f₂ a))⟩
38d2d5c25d91db9e9d967173f6ebe76a9d184043
9028d228ac200bbefe3a711342514dd4e4458bff
/src/measure_theory/measurable_space.lean
eb7eb2c7bf50165f1040eabf0e9abe39d8c91ec5
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
55,316
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import data.set.disjointed import data.set.countable import data.indicator_function import data.equiv.encodable.lattice import order.filter.basic /-! # Measurable spaces and measurable functions This file defines measurable spaces and the functions and isomorphisms between them. A measurable space is a set equipped with a σ-algebra, a collection of subsets closed under complementation and countable union. A function between measurable spaces is measurable if the preimage of each measurable subset is measurable. σ-algebras on a fixed set `α` form a complete lattice. Here we order σ-algebras by writing `m₁ ≤ m₂` if every set which is `m₁`-measurable is also `m₂`-measurable (that is, `m₁` is a subset of `m₂`). In particular, any collection of subsets of `α` generates a smallest σ-algebra which contains all of them. A function `f : α → β` induces a Galois connection between the lattices of σ-algebras on `α` and `β`. A measurable equivalence between measurable spaces is an equivalence which respects the σ-algebras, that is, for which both directions of the equivalence are measurable functions. We say that a filter `f` is measurably generated if every set `s ∈ f` includes a measurable set `t ∈ f`. This property is useful, e.g., to extract a measurable witness of `filter.eventually`. ## Main statements The main theorem of this file is Dynkin's π-λ theorem, which appears here as an induction principle `induction_on_inter`. Suppose `s` is a collection of subsets of `α` such that the intersection of two members of `s` belongs to `s` whenever it is nonempty. Let `m` be the σ-algebra generated by `s`. In order to check that a predicate `C` holds on every member of `m`, it suffices to check that `C` holds on the members of `s` and that `C` is preserved by complementation and *disjoint* countable unions. ## Implementation notes Measurability of a function `f : α → β` between measurable spaces is defined in terms of the Galois connection induced by f. ## References * <https://en.wikipedia.org/wiki/Measurable_space> * <https://en.wikipedia.org/wiki/Sigma-algebra> * <https://en.wikipedia.org/wiki/Dynkin_system> ## Tags measurable space, measurable function, dynkin system -/ local attribute [instance] classical.prop_decidable open set encodable function open_locale classical filter universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} {ι : Sort x} {s t u : set α} /-- A measurable space is a space equipped with a σ-algebra. -/ structure measurable_space (α : Type u) := (is_measurable' : set α → Prop) (is_measurable_empty : is_measurable' ∅) (is_measurable_compl : ∀s, is_measurable' s → is_measurable' sᶜ) (is_measurable_Union : ∀f:ℕ → set α, (∀i, is_measurable' (f i)) → is_measurable' (⋃i, f i)) attribute [class] measurable_space section variable [measurable_space α] /-- `is_measurable s` means that `s` is measurable (in the ambient measure space on `α`) -/ def is_measurable : set α → Prop := ‹measurable_space α›.is_measurable' @[simp] lemma is_measurable.empty : is_measurable (∅ : set α) := ‹measurable_space α›.is_measurable_empty lemma is_measurable.compl : is_measurable s → is_measurable sᶜ := ‹measurable_space α›.is_measurable_compl s lemma is_measurable.of_compl (h : is_measurable sᶜ) : is_measurable s := s.compl_compl ▸ h.compl @[simp] lemma is_measurable.compl_iff : is_measurable sᶜ ↔ is_measurable s := ⟨is_measurable.of_compl, is_measurable.compl⟩ @[simp] lemma is_measurable.univ : is_measurable (univ : set α) := by simpa using (@is_measurable.empty α _).compl lemma subsingleton.is_measurable [subsingleton α] {s : set α} : is_measurable s := subsingleton.set_cases is_measurable.empty is_measurable.univ s lemma is_measurable.congr {s t : set α} (hs : is_measurable s) (h : s = t) : is_measurable t := by rwa ← h lemma is_measurable.bUnion_decode2 [encodable β] ⦃f : β → set α⦄ (h : ∀ b, is_measurable (f b)) (n : ℕ) : is_measurable (⋃ b ∈ decode2 β n, f b) := encodable.Union_decode2_cases is_measurable.empty h lemma is_measurable.Union [encodable β] ⦃f : β → set α⦄ (h : ∀b, is_measurable (f b)) : is_measurable (⋃b, f b) := begin rw ← encodable.Union_decode2, exact ‹measurable_space α›.is_measurable_Union _ (is_measurable.bUnion_decode2 h) end lemma is_measurable.bUnion {f : β → set α} {s : set β} (hs : countable s) (h : ∀b∈s, is_measurable (f b)) : is_measurable (⋃b∈s, f b) := begin rw bUnion_eq_Union, haveI := hs.to_encodable, exact is_measurable.Union (by simpa using h) end lemma set.finite.is_measurable_bUnion {f : β → set α} {s : set β} (hs : finite s) (h : ∀ b ∈ s, is_measurable (f b)) : is_measurable (⋃ b ∈ s, f b) := is_measurable.bUnion hs.countable h lemma finset.is_measurable_bUnion {f : β → set α} (s : finset β) (h : ∀ b ∈ s, is_measurable (f b)) : is_measurable (⋃ b ∈ s, f b) := s.finite_to_set.is_measurable_bUnion h lemma is_measurable.sUnion {s : set (set α)} (hs : countable s) (h : ∀t∈s, is_measurable t) : is_measurable (⋃₀ s) := by { rw sUnion_eq_bUnion, exact is_measurable.bUnion hs h } lemma set.finite.is_measurable_sUnion {s : set (set α)} (hs : finite s) (h : ∀ t ∈ s, is_measurable t) : is_measurable (⋃₀ s) := is_measurable.sUnion hs.countable h lemma is_measurable.Union_Prop {p : Prop} {f : p → set α} (hf : ∀b, is_measurable (f b)) : is_measurable (⋃b, f b) := by { by_cases p; simp [h, hf, is_measurable.empty] } lemma is_measurable.Inter [encodable β] {f : β → set α} (h : ∀b, is_measurable (f b)) : is_measurable (⋂b, f b) := is_measurable.compl_iff.1 $ by { rw compl_Inter, exact is_measurable.Union (λ b, (h b).compl) } lemma is_measurable.bInter {f : β → set α} {s : set β} (hs : countable s) (h : ∀b∈s, is_measurable (f b)) : is_measurable (⋂b∈s, f b) := is_measurable.compl_iff.1 $ by { rw compl_bInter, exact is_measurable.bUnion hs (λ b hb, (h b hb).compl) } lemma set.finite.is_measurable_bInter {f : β → set α} {s : set β} (hs : finite s) (h : ∀b∈s, is_measurable (f b)) : is_measurable (⋂b∈s, f b) := is_measurable.bInter hs.countable h lemma finset.is_measurable_bInter {f : β → set α} (s : finset β) (h : ∀b∈s, is_measurable (f b)) : is_measurable (⋂b∈s, f b) := s.finite_to_set.is_measurable_bInter h lemma is_measurable.sInter {s : set (set α)} (hs : countable s) (h : ∀t∈s, is_measurable t) : is_measurable (⋂₀ s) := by { rw sInter_eq_bInter, exact is_measurable.bInter hs h } lemma set.finite.is_measurable_sInter {s : set (set α)} (hs : finite s) (h : ∀t∈s, is_measurable t) : is_measurable (⋂₀ s) := is_measurable.sInter hs.countable h lemma is_measurable.Inter_Prop {p : Prop} {f : p → set α} (hf : ∀b, is_measurable (f b)) : is_measurable (⋂b, f b) := by { by_cases p; simp [h, hf, is_measurable.univ] } @[simp] lemma is_measurable.union {s₁ s₂ : set α} (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : is_measurable (s₁ ∪ s₂) := by { rw union_eq_Union, exact is_measurable.Union (bool.forall_bool.2 ⟨h₂, h₁⟩) } @[simp] lemma is_measurable.inter {s₁ s₂ : set α} (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : is_measurable (s₁ ∩ s₂) := by { rw inter_eq_compl_compl_union_compl, exact (h₁.compl.union h₂.compl).compl } @[simp] lemma is_measurable.diff {s₁ s₂ : set α} (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : is_measurable (s₁ \ s₂) := h₁.inter h₂.compl @[simp] lemma is_measurable.disjointed {f : ℕ → set α} (h : ∀i, is_measurable (f i)) (n) : is_measurable (disjointed f n) := disjointed_induct (h n) (assume t i ht, is_measurable.diff ht $ h _) @[simp] lemma is_measurable.const (p : Prop) : is_measurable {a : α | p} := by { by_cases p; simp [h, is_measurable.empty]; apply is_measurable.univ } end @[ext] lemma measurable_space.ext : ∀{m₁ m₂ : measurable_space α}, (∀s:set α, m₁.is_measurable' s ↔ m₂.is_measurable' s) → m₁ = m₂ | ⟨s₁, _, _, _⟩ ⟨s₂, _, _, _⟩ h := have s₁ = s₂, from funext $ assume x, propext $ h x, by subst this @[ext] lemma measurable_space.ext_iff {m₁ m₂ : measurable_space α} : m₁ = m₂ ↔ (∀s:set α, m₁.is_measurable' s ↔ m₂.is_measurable' s) := ⟨by { unfreezingI {rintro rfl}, intro s, refl }, measurable_space.ext⟩ /-- A typeclass mixin for `measurable_space`s such that each singleton is measurable. -/ class measurable_singleton_class (α : Type*) [measurable_space α] : Prop := (is_measurable_singleton : ∀ x, is_measurable ({x} : set α)) export measurable_singleton_class (is_measurable_singleton) attribute [simp] is_measurable_singleton section measurable_singleton_class variables [measurable_space α] [measurable_singleton_class α] lemma is_measurable_eq {a : α} : is_measurable {x | x = a} := is_measurable_singleton a lemma is_measurable.insert {s : set α} (hs : is_measurable s) (a : α) : is_measurable (insert a s) := (is_measurable_singleton a).union hs @[simp] lemma is_measurable_insert {a : α} {s : set α} : is_measurable (insert a s) ↔ is_measurable s := ⟨λ h, if ha : a ∈ s then by rwa ← insert_eq_of_mem ha else insert_diff_self_of_not_mem ha ▸ h.diff (is_measurable_singleton _), λ h, h.insert a⟩ lemma set.finite.is_measurable {s : set α} (hs : finite s) : is_measurable s := finite.induction_on hs is_measurable.empty $ λ a s ha hsf hsm, hsm.insert _ protected lemma finset.is_measurable (s : finset α) : is_measurable (↑s : set α) := s.finite_to_set.is_measurable end measurable_singleton_class namespace measurable_space section complete_lattice instance : partial_order (measurable_space α) := { le := λm₁ m₂, m₁.is_measurable' ≤ m₂.is_measurable', le_refl := assume a b, le_refl _, le_trans := assume a b c, le_trans, le_antisymm := assume a b h₁ h₂, measurable_space.ext $ assume s, ⟨h₁ s, h₂ s⟩ } /-- The smallest σ-algebra containing a collection `s` of basic sets -/ inductive generate_measurable (s : set (set α)) : set α → Prop | basic : ∀u∈s, generate_measurable u | empty : generate_measurable ∅ | compl : ∀s, generate_measurable s → generate_measurable sᶜ | union : ∀f:ℕ → set α, (∀n, generate_measurable (f n)) → generate_measurable (⋃i, f i) /-- Construct the smallest measure space containing a collection of basic sets -/ def generate_from (s : set (set α)) : measurable_space α := { is_measurable' := generate_measurable s, is_measurable_empty := generate_measurable.empty, is_measurable_compl := generate_measurable.compl, is_measurable_Union := generate_measurable.union } lemma is_measurable_generate_from {s : set (set α)} {t : set α} (ht : t ∈ s) : (generate_from s).is_measurable' t := generate_measurable.basic t ht lemma generate_from_le {s : set (set α)} {m : measurable_space α} (h : ∀t∈s, m.is_measurable' t) : generate_from s ≤ m := assume t (ht : generate_measurable s t), ht.rec_on h (is_measurable_empty m) (assume s _ hs, is_measurable_compl m s hs) (assume f _ hf, is_measurable_Union m f hf) lemma generate_from_le_iff {s : set (set α)} (m : measurable_space α) : generate_from s ≤ m ↔ s ⊆ {t | m.is_measurable' t} := iff.intro (assume h u hu, h _ $ is_measurable_generate_from hu) (assume h, generate_from_le h) /-- If `g` is a collection of subsets of `α` such that the `σ`-algebra generated from `g` contains the same sets as `g`, then `g` was already a `σ`-algebra. -/ protected def mk_of_closure (g : set (set α)) (hg : {t | (generate_from g).is_measurable' t} = g) : measurable_space α := { is_measurable' := λs, s ∈ g, is_measurable_empty := hg ▸ is_measurable_empty _, is_measurable_compl := hg ▸ is_measurable_compl _, is_measurable_Union := hg ▸ is_measurable_Union _ } lemma mk_of_closure_sets {s : set (set α)} {hs : {t | (generate_from s).is_measurable' t} = s} : measurable_space.mk_of_closure s hs = generate_from s := measurable_space.ext $ assume t, show t ∈ s ↔ _, by { conv_lhs { rw [← hs] }, refl } /-- We get a Galois insertion between `σ`-algebras on `α` and `set (set α)` by using `generate_from` on one side and the collection of measurable sets on the other side. -/ def gi_generate_from : galois_insertion (@generate_from α) (λm, {t | @is_measurable α m t}) := { gc := assume s, generate_from_le_iff, le_l_u := assume m s, is_measurable_generate_from, choice := λg hg, measurable_space.mk_of_closure g $ le_antisymm hg $ (generate_from_le_iff _).1 le_rfl, choice_eq := assume g hg, mk_of_closure_sets } instance : complete_lattice (measurable_space α) := gi_generate_from.lift_complete_lattice instance : inhabited (measurable_space α) := ⟨⊤⟩ lemma is_measurable_bot_iff {s : set α} : @is_measurable α ⊥ s ↔ (s = ∅ ∨ s = univ) := let b : measurable_space α := { is_measurable' := λs, s = ∅ ∨ s = univ, is_measurable_empty := or.inl rfl, is_measurable_compl := by simp [or_imp_distrib] {contextual := tt}, is_measurable_Union := assume f hf, classical.by_cases (assume h : ∃i, f i = univ, let ⟨i, hi⟩ := h in or.inr $ eq_univ_of_univ_subset $ hi ▸ le_supr f i) (assume h : ¬ ∃i, f i = univ, or.inl $ eq_empty_of_subset_empty $ Union_subset $ assume i, (hf i).elim (by simp {contextual := tt}) (assume hi, false.elim $ h ⟨i, hi⟩)) } in have b = ⊥, from bot_unique $ assume s hs, hs.elim (assume s, s.symm ▸ @is_measurable_empty _ ⊥) (assume s, s.symm ▸ @is_measurable.univ _ ⊥), this ▸ iff.rfl @[simp] theorem is_measurable_top {s : set α} : @is_measurable _ ⊤ s := trivial @[simp] theorem is_measurable_inf {m₁ m₂ : measurable_space α} {s : set α} : @is_measurable _ (m₁ ⊓ m₂) s ↔ @is_measurable _ m₁ s ∧ @is_measurable _ m₂ s := iff.rfl @[simp] theorem is_measurable_Inf {ms : set (measurable_space α)} {s : set α} : @is_measurable _ (Inf ms) s ↔ ∀ m ∈ ms, @is_measurable _ m s := show s ∈ (⋂m∈ms, {t | @is_measurable _ m t }) ↔ _, by simp @[simp] theorem is_measurable_infi {ι} {m : ι → measurable_space α} {s : set α} : @is_measurable _ (infi m) s ↔ ∀ i, @is_measurable _ (m i) s := show s ∈ (λm, {s | @is_measurable _ m s }) (infi m) ↔ _, by { rw (@gi_generate_from α).gc.u_infi, simp } theorem is_measurable_sup {m₁ m₂ : measurable_space α} {s : set α} : @is_measurable _ (m₁ ⊔ m₂) s ↔ generate_measurable (m₁.is_measurable' ∪ m₂.is_measurable') s := iff.refl _ theorem is_measurable_Sup {ms : set (measurable_space α)} {s : set α} : @is_measurable _ (Sup ms) s ↔ generate_measurable (⋃₀ (measurable_space.is_measurable' '' ms)) s := begin change @is_measurable' _ (generate_from _) _ ↔ _, dsimp [generate_from], rw (show (⨆ (b : measurable_space α) (H : b ∈ ms), set_of (@is_measurable _ b)) = (⋃₀ (is_measurable' '' ms)), { ext, simp only [exists_prop, mem_Union, sUnion_image, mem_set_of_eq], refl, }) end theorem is_measurable_supr {ι} {m : ι → measurable_space α} {s : set α} : @is_measurable _ (supr m) s ↔ generate_measurable (⋃i, (m i).is_measurable') s := begin convert @is_measurable_Sup _ (range m) s, simp, end end complete_lattice section functors variables {m m₁ m₂ : measurable_space α} {m' : measurable_space β} {f : α → β} {g : β → α} /-- The forward image of a measure space under a function. `map f m` contains the sets `s : set β` whose preimage under `f` is measurable. -/ protected def map (f : α → β) (m : measurable_space α) : measurable_space β := { is_measurable' := λs, m.is_measurable' $ f ⁻¹' s, is_measurable_empty := m.is_measurable_empty, is_measurable_compl := assume s hs, m.is_measurable_compl _ hs, is_measurable_Union := assume f hf, by { rw [preimage_Union], exact m.is_measurable_Union _ hf }} @[simp] lemma map_id : m.map id = m := measurable_space.ext $ assume s, iff.rfl @[simp] lemma map_comp {f : α → β} {g : β → γ} : (m.map f).map g = m.map (g ∘ f) := measurable_space.ext $ assume s, iff.rfl /-- The reverse image of a measure space under a function. `comap f m` contains the sets `s : set α` such that `s` is the `f`-preimage of a measurable set in `β`. -/ protected def comap (f : α → β) (m : measurable_space β) : measurable_space α := { is_measurable' := λs, ∃s', m.is_measurable' s' ∧ f ⁻¹' s' = s, is_measurable_empty := ⟨∅, m.is_measurable_empty, rfl⟩, is_measurable_compl := assume s ⟨s', h₁, h₂⟩, ⟨s'ᶜ, m.is_measurable_compl _ h₁, h₂ ▸ rfl⟩, is_measurable_Union := assume s hs, let ⟨s', hs'⟩ := classical.axiom_of_choice hs in ⟨⋃i, s' i, m.is_measurable_Union _ (λi, (hs' i).left), by simp [hs'] ⟩ } @[simp] lemma comap_id : m.comap id = m := measurable_space.ext $ assume s, ⟨assume ⟨s', hs', h⟩, h ▸ hs', assume h, ⟨s, h, rfl⟩⟩ @[simp] lemma comap_comp {f : β → α} {g : γ → β} : (m.comap f).comap g = m.comap (f ∘ g) := measurable_space.ext $ assume s, ⟨assume ⟨t, ⟨u, h, hu⟩, ht⟩, ⟨u, h, ht ▸ hu ▸ rfl⟩, assume ⟨t, h, ht⟩, ⟨f ⁻¹' t, ⟨_, h, rfl⟩, ht⟩⟩ lemma comap_le_iff_le_map {f : α → β} : m'.comap f ≤ m ↔ m' ≤ m.map f := ⟨assume h s hs, h _ ⟨_, hs, rfl⟩, assume h s ⟨t, ht, heq⟩, heq ▸ h _ ht⟩ lemma gc_comap_map (f : α → β) : galois_connection (measurable_space.comap f) (measurable_space.map f) := assume f g, comap_le_iff_le_map lemma map_mono (h : m₁ ≤ m₂) : m₁.map f ≤ m₂.map f := (gc_comap_map f).monotone_u h lemma monotone_map : monotone (measurable_space.map f) := assume a b h, map_mono h lemma comap_mono (h : m₁ ≤ m₂) : m₁.comap g ≤ m₂.comap g := (gc_comap_map g).monotone_l h lemma monotone_comap : monotone (measurable_space.comap g) := assume a b h, comap_mono h @[simp] lemma comap_bot : (⊥:measurable_space α).comap g = ⊥ := (gc_comap_map g).l_bot @[simp] lemma comap_sup : (m₁ ⊔ m₂).comap g = m₁.comap g ⊔ m₂.comap g := (gc_comap_map g).l_sup @[simp] lemma comap_supr {m : ι → measurable_space α} :(⨆i, m i).comap g = (⨆i, (m i).comap g) := (gc_comap_map g).l_supr @[simp] lemma map_top : (⊤:measurable_space α).map f = ⊤ := (gc_comap_map f).u_top @[simp] lemma map_inf : (m₁ ⊓ m₂).map f = m₁.map f ⊓ m₂.map f := (gc_comap_map f).u_inf @[simp] lemma map_infi {m : ι → measurable_space α} : (⨅i, m i).map f = (⨅i, (m i).map f) := (gc_comap_map f).u_infi lemma comap_map_le : (m.map f).comap f ≤ m := (gc_comap_map f).l_u_le _ lemma le_map_comap : m ≤ (m.comap g).map g := (gc_comap_map g).le_u_l _ end functors lemma generate_from_le_generate_from {s t : set (set α)} (h : s ⊆ t) : generate_from s ≤ generate_from t := gi_generate_from.gc.monotone_l h lemma generate_from_sup_generate_from {s t : set (set α)} : generate_from s ⊔ generate_from t = generate_from (s ∪ t) := (@gi_generate_from α).gc.l_sup.symm lemma comap_generate_from {f : α → β} {s : set (set β)} : (generate_from s).comap f = generate_from (preimage f '' s) := le_antisymm (comap_le_iff_le_map.2 $ generate_from_le $ assume t hts, generate_measurable.basic _ $ mem_image_of_mem _ $ hts) (generate_from_le $ assume t ⟨u, hu, eq⟩, eq ▸ ⟨u, generate_measurable.basic _ hu, rfl⟩) end measurable_space section measurable_functions open measurable_space /-- A function `f` between measurable spaces is measurable if the preimage of every measurable set is measurable. -/ def measurable [measurable_space α] [measurable_space β] (f : α → β) : Prop := ∀ ⦃t : set β⦄, is_measurable t → is_measurable (f ⁻¹' t) lemma measurable_iff_le_map {m₁ : measurable_space α} {m₂ : measurable_space β} {f : α → β} : measurable f ↔ m₂ ≤ m₁.map f := iff.rfl alias measurable_iff_le_map ↔ measurable.le_map measurable.of_le_map lemma measurable_iff_comap_le {m₁ : measurable_space α} {m₂ : measurable_space β} {f : α → β} : measurable f ↔ m₂.comap f ≤ m₁ := comap_le_iff_le_map.symm alias measurable_iff_comap_le ↔ measurable.comap_le measurable.of_comap_le lemma subsingleton.measurable [measurable_space α] [measurable_space β] [subsingleton α] {f : α → β} : measurable f := λ s hs, @subsingleton.is_measurable α _ _ _ lemma measurable_id [measurable_space α] : measurable (@id α) := λ t, id lemma measurable.comp [measurable_space α] [measurable_space β] [measurable_space γ] {g : β → γ} {f : α → β} (hg : measurable g) (hf : measurable f) : measurable (g ∘ f) := λ t ht, hf (hg ht) lemma measurable_from_top [measurable_space β] {f : α → β} : @measurable _ _ ⊤ _ f := λ s hs, trivial lemma measurable.mono {ma ma' : measurable_space α} {mb mb' : measurable_space β} {f : α → β} (hf : @measurable α β ma mb f) (ha : ma ≤ ma') (hb : mb' ≤ mb) : @measurable α β ma' mb' f := λ t ht, ha _ $ hf $ hb _ ht lemma measurable_generate_from [measurable_space α] {s : set (set β)} {f : α → β} (h : ∀t∈s, is_measurable (f ⁻¹' t)) : @measurable _ _ _ (generate_from s) f := measurable.of_le_map $ generate_from_le h lemma measurable.piecewise [measurable_space α] [measurable_space β] {s : set α} {_ : decidable_pred s} {f g : α → β} (hs : is_measurable s) (hf : measurable f) (hg : measurable g) : measurable (piecewise s f g) := begin intros t ht, simp only [piecewise_preimage], exact (hs.inter $ hf ht).union (hs.compl.inter $ hg ht) end @[simp] lemma measurable_const {α β} [measurable_space α] [measurable_space β] {a : α} : measurable (λb:β, a) := assume s hs, is_measurable.const (a ∈ s) lemma measurable.indicator [measurable_space α] [measurable_space β] [has_zero β] {s : set α} {f : α → β} (hf : measurable f) (hs : is_measurable s) : measurable (s.indicator f) := hf.piecewise hs measurable_const @[to_additive] lemma measurable_one {α β} [measurable_space α] [has_one α] [measurable_space β] : measurable (1 : β → α) := @measurable_const _ _ _ _ 1 end measurable_functions section constructions instance : measurable_space empty := ⊤ instance : measurable_space unit := ⊤ instance : measurable_space bool := ⊤ instance : measurable_space ℕ := ⊤ instance : measurable_space ℤ := ⊤ instance : measurable_space ℚ := ⊤ lemma measurable_to_encodable [encodable α] [measurable_space α] [measurable_space β] {f : β → α} (h : ∀ y, is_measurable (f ⁻¹' {f y})) : measurable f := begin assume s hs, rw [← bUnion_preimage_singleton], refine is_measurable.Union (λ y, is_measurable.Union_Prop $ λ hy, _), by_cases hyf : y ∈ range f, { rcases hyf with ⟨y, rfl⟩, apply h }, { simp only [preimage_singleton_eq_empty.2 hyf, is_measurable.empty] } end lemma measurable_unit [measurable_space α] (f : unit → α) : measurable f := measurable_from_top section nat lemma measurable_from_nat [measurable_space α] {f : ℕ → α} : measurable f := measurable_from_top lemma measurable_to_nat [measurable_space α] {f : α → ℕ} : (∀ y, is_measurable (f ⁻¹' {f y})) → measurable f := measurable_to_encodable lemma measurable_find_greatest' [measurable_space α] {p : α → ℕ → Prop} {N} (hN : ∀ k ≤ N, is_measurable {x | nat.find_greatest (p x) N = k}) : measurable (λ x, nat.find_greatest (p x) N) := measurable_to_nat $ λ x, hN _ nat.find_greatest_le lemma measurable_find_greatest [measurable_space α] {p : α → ℕ → Prop} {N} (hN : ∀ k ≤ N, is_measurable {x | p x k}) : measurable (λ x, nat.find_greatest (p x) N) := begin refine measurable_find_greatest' (λ k hk, _), simp only [nat.find_greatest_eq_iff, set_of_and, set_of_forall, ← compl_set_of], repeat { apply_rules [is_measurable.inter, is_measurable.const, is_measurable.Inter, is_measurable.Inter_Prop, is_measurable.compl, hN]; try { intros } } end lemma measurable_find [measurable_space α] {p : α → ℕ → Prop} (hp : ∀ x, ∃ N, p x N) (hm : ∀ k, is_measurable {x | p x k}) : measurable (λ x, nat.find (hp x)) := begin refine measurable_to_nat (λ x, _), simp only [set.preimage, mem_singleton_iff, nat.find_eq_iff, set_of_and, set_of_forall, ← compl_set_of], repeat { apply_rules [is_measurable.inter, hm, is_measurable.Inter, is_measurable.Inter_Prop, is_measurable.compl]; try { intros } } end end nat section subtype instance {p : α → Prop} [m : measurable_space α] : measurable_space (subtype p) := m.comap (coe : _ → α) lemma measurable_subtype_coe [measurable_space α] {p : α → Prop} : measurable (coe : subtype p → α) := measurable_space.le_map_comap lemma measurable.subtype_coe [measurable_space α] [measurable_space β] {p : β → Prop} {f : α → subtype p} (hf : measurable f) : measurable (λa:α, (f a : β)) := measurable_subtype_coe.comp hf lemma measurable.subtype_mk [measurable_space α] [measurable_space β] {p : β → Prop} {f : α → β} (hf : measurable f) {h : ∀ x, p (f x)} : measurable (λ x, (⟨f x, h x⟩ : subtype p)) := λ t ⟨s, hs⟩, hs.2 ▸ by simp only [← preimage_comp, (∘), subtype.coe_mk, hf hs.1] lemma is_measurable.subtype_image [measurable_space α] {s : set α} {t : set s} (hs : is_measurable s) : is_measurable t → is_measurable ((coe : s → α) '' t) | ⟨u, (hu : is_measurable u), (eq : coe ⁻¹' u = t)⟩ := begin rw [← eq, subtype.image_preimage_coe], exact hu.inter hs end lemma measurable_of_measurable_union_cover [measurable_space α] [measurable_space β] {f : α → β} (s t : set α) (hs : is_measurable s) (ht : is_measurable t) (h : univ ⊆ s ∪ t) (hc : measurable (λa:s, f a)) (hd : measurable (λa:t, f a)) : measurable f := begin intros u hu, convert (hs.subtype_image (hc hu)).union (ht.subtype_image (hd hu)), change f ⁻¹' u = coe '' (coe ⁻¹' (f ⁻¹' u) : set s) ∪ coe '' (coe ⁻¹' (f ⁻¹' u) : set t), rw [image_preimage_eq_inter_range, image_preimage_eq_inter_range, subtype.range_coe, subtype.range_coe, ← inter_distrib_left, univ_subset_iff.1 h, inter_univ], end lemma measurable_of_measurable_on_compl_singleton [measurable_space α] [measurable_space β] [measurable_singleton_class α] {f : α → β} (a : α) (hf : measurable (set.restrict f {x | x ≠ a})) : measurable f := measurable_of_measurable_union_cover _ _ is_measurable_eq is_measurable_eq.compl (λ x hx, classical.em _) (@subsingleton.measurable {x | x = a} _ _ _ ⟨λ x y, subtype.eq $ x.2.trans y.2.symm⟩ _) hf end subtype section prod instance [m₁ : measurable_space α] [m₂ : measurable_space β] : measurable_space (α × β) := m₁.comap prod.fst ⊔ m₂.comap prod.snd variables [measurable_space α] [measurable_space β] [measurable_space γ] lemma measurable_fst : measurable (prod.fst : α × β → α) := measurable.of_comap_le le_sup_left lemma measurable.fst {f : α → β × γ} (hf : measurable f) : measurable (λa:α, (f a).1) := measurable_fst.comp hf lemma measurable_snd : measurable (prod.snd : α × β → β) := measurable.of_comap_le le_sup_right lemma measurable.snd {f : α → β × γ} (hf : measurable f) : measurable (λa:α, (f a).2) := measurable_snd.comp hf lemma measurable.prod {f : α → β × γ} (hf₁ : measurable (λa, (f a).1)) (hf₂ : measurable (λa, (f a).2)) : measurable f := measurable.of_le_map $ sup_le (by { rw [measurable_space.comap_le_iff_le_map, measurable_space.map_comp], exact hf₁ }) (by { rw [measurable_space.comap_le_iff_le_map, measurable_space.map_comp], exact hf₂ }) lemma measurable_prod {f : α → β × γ} : measurable f ↔ measurable (λa, (f a).1) ∧ measurable (λa, (f a).2) := ⟨λ hf, ⟨measurable_fst.comp hf, measurable_snd.comp hf⟩, λ h, measurable.prod h.1 h.2⟩ lemma measurable.prod_mk {f : α → β} {g : α → γ} (hf : measurable f) (hg : measurable g) : measurable (λa:α, (f a, g a)) := measurable.prod hf hg lemma measurable_prod_mk_left {x : α} : measurable (@prod.mk _ β x) := measurable_const.prod_mk measurable_id lemma measurable_prod_mk_right {y : β} : measurable (λ x : α, (x, y)) := measurable_id.prod_mk measurable_const lemma measurable.of_uncurry_left {f : α → β → γ} (hf : measurable (uncurry f)) {x : α} : measurable (f x) := hf.comp measurable_prod_mk_left lemma measurable.of_uncurry_right {f : α → β → γ} (hf : measurable (uncurry f)) {y : β} : measurable (λ x, f x y) := hf.comp measurable_prod_mk_right lemma measurable_swap : measurable (prod.swap : α × β → β × α) := measurable.prod measurable_snd measurable_fst lemma measurable_swap_iff {f : α × β → γ} : measurable (f ∘ prod.swap) ↔ measurable f := ⟨λ hf, by { convert hf.comp measurable_swap, ext ⟨x, y⟩, refl }, λ hf, hf.comp measurable_swap⟩ lemma is_measurable.prod {s : set α} {t : set β} (hs : is_measurable s) (ht : is_measurable t) : is_measurable (s.prod t) := is_measurable.inter (measurable_fst hs) (measurable_snd ht) lemma is_measurable_prod_of_nonempty {s : set α} {t : set β} (h : (s.prod t).nonempty) : is_measurable (s.prod t) ↔ is_measurable s ∧ is_measurable t := begin rcases h with ⟨⟨x, y⟩, hx, hy⟩, refine ⟨λ hst, _, λ h, h.1.prod h.2⟩, have : is_measurable ((λ x, (x, y)) ⁻¹' s.prod t) := measurable_id.prod_mk measurable_const hst, have : is_measurable (prod.mk x ⁻¹' s.prod t) := measurable_const.prod_mk measurable_id hst, simp * at * end lemma is_measurable_prod {s : set α} {t : set β} : is_measurable (s.prod t) ↔ (is_measurable s ∧ is_measurable t) ∨ s = ∅ ∨ t = ∅ := begin cases (s.prod t).eq_empty_or_nonempty with h h, { simp [h, prod_eq_empty_iff.mp h] }, { simp [←not_nonempty_iff_eq_empty, prod_nonempty_iff.mp h, is_measurable_prod_of_nonempty h] } end lemma is_measurable_swap_iff {s : set (α × β)} : is_measurable (prod.swap ⁻¹' s) ↔ is_measurable s := ⟨λ hs, by { convert measurable_swap hs, ext ⟨x, y⟩, refl }, λ hs, measurable_swap hs⟩ end prod section pi instance measurable_space.pi {α : Type u} {β : α → Type v} [m : Πa, measurable_space (β a)] : measurable_space (Πa, β a) := ⨆a, (m a).comap (λb, b a) lemma measurable_pi_apply {α : Type u} {β : α → Type v} [Πa, measurable_space (β a)] (a : α) : measurable (λf:Πa, β a, f a) := measurable.of_comap_le $ le_supr _ a lemma measurable_pi_lambda {α : Type u} {β : α → Type v} {γ : Type w} [Πa, measurable_space (β a)] [measurable_space γ] (f : γ → Πa, β a) (hf : ∀a, measurable (λc, f c a)) : measurable f := measurable.of_le_map $ supr_le $ assume a, measurable_space.comap_le_iff_le_map.2 (hf a) end pi instance [m₁ : measurable_space α] [m₂ : measurable_space β] : measurable_space (α ⊕ β) := m₁.map sum.inl ⊓ m₂.map sum.inr section sum variables [measurable_space α] [measurable_space β] [measurable_space γ] lemma measurable_inl : measurable (@sum.inl α β) := measurable.of_le_map inf_le_left lemma measurable_inr : measurable (@sum.inr α β) := measurable.of_le_map inf_le_right lemma measurable_sum {f : α ⊕ β → γ} (hl : measurable (f ∘ sum.inl)) (hr : measurable (f ∘ sum.inr)) : measurable f := measurable.of_comap_le $ le_inf (measurable_space.comap_le_iff_le_map.2 $ hl) (measurable_space.comap_le_iff_le_map.2 $ hr) lemma measurable.sum_rec {f : α → γ} {g : β → γ} (hf : measurable f) (hg : measurable g) : @measurable (α ⊕ β) γ _ _ (@sum.rec α β (λ_, γ) f g) := measurable_sum hf hg lemma is_measurable.inl_image {s : set α} (hs : is_measurable s) : is_measurable (sum.inl '' s : set (α ⊕ β)) := ⟨show is_measurable (sum.inl ⁻¹' _), by { rwa [preimage_image_eq], exact (λ a b, sum.inl.inj) }, have sum.inr ⁻¹' (sum.inl '' s : set (α ⊕ β)) = ∅ := eq_empty_of_subset_empty $ assume x ⟨y, hy, eq⟩, by contradiction, show is_measurable (sum.inr ⁻¹' _), by { rw [this], exact is_measurable.empty }⟩ lemma is_measurable_range_inl : is_measurable (range sum.inl : set (α ⊕ β)) := by { rw [← image_univ], exact is_measurable.univ.inl_image } lemma is_measurable_inr_image {s : set β} (hs : is_measurable s) : is_measurable (sum.inr '' s : set (α ⊕ β)) := ⟨ have sum.inl ⁻¹' (sum.inr '' s : set (α ⊕ β)) = ∅ := eq_empty_of_subset_empty $ assume x ⟨y, hy, eq⟩, by contradiction, show is_measurable (sum.inl ⁻¹' _), by { rw [this], exact is_measurable.empty }, show is_measurable (sum.inr ⁻¹' _), by { rwa [preimage_image_eq], exact λ a b, sum.inr.inj }⟩ lemma is_measurable_range_inr : is_measurable (range sum.inr : set (α ⊕ β)) := by { rw [← image_univ], exact is_measurable_inr_image is_measurable.univ } end sum instance {β : α → Type v} [m : Πa, measurable_space (β a)] : measurable_space (sigma β) := ⨅a, (m a).map (sigma.mk a) end constructions /-- Equivalences between measurable spaces. Main application is the simplification of measurability statements along measurable equivalences. -/ structure measurable_equiv (α β : Type*) [measurable_space α] [measurable_space β] extends α ≃ β := (measurable_to_fun : measurable to_fun) (measurable_inv_fun : measurable inv_fun) namespace measurable_equiv instance (α β) [measurable_space α] [measurable_space β] : has_coe_to_fun (measurable_equiv α β) := ⟨λ_, α → β, λe, e.to_equiv⟩ lemma coe_eq {α β} [measurable_space α] [measurable_space β] (e : measurable_equiv α β) : (e : α → β) = e.to_equiv := rfl /-- Any measurable space is equivalent to itself. -/ def refl (α : Type*) [measurable_space α] : measurable_equiv α α := { to_equiv := equiv.refl α, measurable_to_fun := measurable_id, measurable_inv_fun := measurable_id } instance {α} [measurable_space α] : inhabited (measurable_equiv α α) := ⟨refl α⟩ /-- The composition of equivalences between measurable spaces. -/ def trans [measurable_space α] [measurable_space β] [measurable_space γ] (ab : measurable_equiv α β) (bc : measurable_equiv β γ) : measurable_equiv α γ := { to_equiv := ab.to_equiv.trans bc.to_equiv, measurable_to_fun := bc.measurable_to_fun.comp ab.measurable_to_fun, measurable_inv_fun := ab.measurable_inv_fun.comp bc.measurable_inv_fun } lemma trans_to_equiv {α β} [measurable_space α] [measurable_space β] [measurable_space γ] (e : measurable_equiv α β) (f : measurable_equiv β γ) : (e.trans f).to_equiv = e.to_equiv.trans f.to_equiv := rfl /-- The inverse of an equivalence between measurable spaces. -/ def symm [measurable_space α] [measurable_space β] (ab : measurable_equiv α β) : measurable_equiv β α := { to_equiv := ab.to_equiv.symm, measurable_to_fun := ab.measurable_inv_fun, measurable_inv_fun := ab.measurable_to_fun } lemma symm_to_equiv {α β} [measurable_space α] [measurable_space β] (e : measurable_equiv α β) : e.symm.to_equiv = e.to_equiv.symm := rfl /-- Equal measurable spaces are equivalent. -/ protected def cast {α β} [i₁ : measurable_space α] [i₂ : measurable_space β] (h : α = β) (hi : i₁ == i₂) : measurable_equiv α β := { to_equiv := equiv.cast h, measurable_to_fun := by { substI h, substI hi, exact measurable_id }, measurable_inv_fun := by { substI h, substI hi, exact measurable_id }} protected lemma measurable {α β} [measurable_space α] [measurable_space β] (e : measurable_equiv α β) : measurable (e : α → β) := e.measurable_to_fun protected lemma measurable_coe_iff {α β γ} [measurable_space α] [measurable_space β] [measurable_space γ] {f : β → γ} (e : measurable_equiv α β) : measurable (f ∘ e) ↔ measurable f := iff.intro (assume hfe, have measurable (f ∘ (e.symm.trans e).to_equiv) := hfe.comp e.symm.measurable, by rwa [trans_to_equiv, symm_to_equiv, equiv.symm_trans] at this) (λh, h.comp e.measurable) /-- Products of equivalent measurable spaces are equivalent. -/ def prod_congr [measurable_space α] [measurable_space β] [measurable_space γ] [measurable_space δ] (ab : measurable_equiv α β) (cd : measurable_equiv γ δ) : measurable_equiv (α × γ) (β × δ) := { to_equiv := equiv.prod_congr ab.to_equiv cd.to_equiv, measurable_to_fun := measurable.prod_mk (ab.measurable_to_fun.comp (measurable.fst measurable_id)) (cd.measurable_to_fun.comp (measurable.snd measurable_id)), measurable_inv_fun := measurable.prod_mk (ab.measurable_inv_fun.comp (measurable.fst measurable_id)) (cd.measurable_inv_fun.comp (measurable.snd measurable_id)) } /-- Products of measurable spaces are symmetric. -/ def prod_comm [measurable_space α] [measurable_space β] : measurable_equiv (α × β) (β × α) := { to_equiv := equiv.prod_comm α β, measurable_to_fun := measurable.prod_mk (measurable.snd measurable_id) (measurable.fst measurable_id), measurable_inv_fun := measurable.prod_mk (measurable.snd measurable_id) (measurable.fst measurable_id) } /-- Sums of measurable spaces are symmetric. -/ def sum_congr [measurable_space α] [measurable_space β] [measurable_space γ] [measurable_space δ] (ab : measurable_equiv α β) (cd : measurable_equiv γ δ) : measurable_equiv (α ⊕ γ) (β ⊕ δ) := { to_equiv := equiv.sum_congr ab.to_equiv cd.to_equiv, measurable_to_fun := begin cases ab with ab' abm, cases ab', cases cd with cd' cdm, cases cd', refine measurable_sum (measurable_inl.comp abm) (measurable_inr.comp cdm) end, measurable_inv_fun := begin cases ab with ab' _ abm, cases ab', cases cd with cd' _ cdm, cases cd', refine measurable_sum (measurable_inl.comp abm) (measurable_inr.comp cdm) end } /-- `set.prod s t ≃ (s × t)` as measurable spaces. -/ def set.prod [measurable_space α] [measurable_space β] (s : set α) (t : set β) : measurable_equiv (s.prod t) (s × t) := { to_equiv := equiv.set.prod s t, measurable_to_fun := measurable.prod_mk measurable_id.subtype_coe.fst.subtype_mk measurable_id.subtype_coe.snd.subtype_mk, measurable_inv_fun := measurable.subtype_mk $ measurable.prod_mk measurable_id.fst.subtype_coe measurable_id.snd.subtype_coe } /-- `univ α ≃ α` as measurable spaces. -/ def set.univ (α : Type*) [measurable_space α] : measurable_equiv (univ : set α) α := { to_equiv := equiv.set.univ α, measurable_to_fun := measurable_id.subtype_coe, measurable_inv_fun := measurable_id.subtype_mk } /-- `{a} ≃ unit` as measurable spaces. -/ def set.singleton [measurable_space α] (a:α) : measurable_equiv ({a} : set α) unit := { to_equiv := equiv.set.singleton a, measurable_to_fun := measurable_const, measurable_inv_fun := measurable_const } /-- A set is equivalent to its image under a function `f` as measurable spaces, if `f` is an injective measurable function that sends measurable sets to measurable sets. -/ noncomputable def set.image [measurable_space α] [measurable_space β] (f : α → β) (s : set α) (hf : function.injective f) (hfm : measurable f) (hfi : ∀s, is_measurable s → is_measurable (f '' s)) : measurable_equiv s (f '' s) := { to_equiv := equiv.set.image f s hf, measurable_to_fun := (hfm.comp measurable_id.subtype_coe).subtype_mk, measurable_inv_fun := begin rintro t ⟨u, hu, rfl⟩, simp [preimage_preimage, equiv.set.image_symm_preimage hf], exact measurable_subtype_coe (hfi u hu) end } /-- The domain of `f` is equivalent to its range as measurable spaces, if `f` is an injective measurable function that sends measurable sets to measurable sets. -/ noncomputable def set.range [measurable_space α] [measurable_space β] (f : α → β) (hf : function.injective f) (hfm : measurable f) (hfi : ∀s, is_measurable s → is_measurable (f '' s)) : measurable_equiv α (range f) := (measurable_equiv.set.univ _).symm.trans $ (measurable_equiv.set.image f univ hf hfm hfi).trans $ measurable_equiv.cast (by rw image_univ) (by rw image_univ) /-- `α` is equivalent to its image in `α ⊕ β` as measurable spaces. -/ def set.range_inl [measurable_space α] [measurable_space β] : measurable_equiv (range sum.inl : set (α ⊕ β)) α := { to_fun := λab, match ab with | ⟨sum.inl a, _⟩ := a | ⟨sum.inr b, p⟩ := have false, by { cases p, contradiction }, this.elim end, inv_fun := λa, ⟨sum.inl a, a, rfl⟩, left_inv := by { rintro ⟨ab, a, rfl⟩, refl }, right_inv := assume a, rfl, measurable_to_fun := assume s (hs : is_measurable s), begin refine ⟨_, hs.inl_image, set.ext _⟩, rintros ⟨ab, a, rfl⟩, simp [set.range_inl._match_1] end, measurable_inv_fun := measurable.subtype_mk measurable_inl } /-- `β` is equivalent to its image in `α ⊕ β` as measurable spaces. -/ def set.range_inr [measurable_space α] [measurable_space β] : measurable_equiv (range sum.inr : set (α ⊕ β)) β := { to_fun := λab, match ab with | ⟨sum.inr b, _⟩ := b | ⟨sum.inl a, p⟩ := have false, by { cases p, contradiction }, this.elim end, inv_fun := λb, ⟨sum.inr b, b, rfl⟩, left_inv := by { rintro ⟨ab, b, rfl⟩, refl }, right_inv := assume b, rfl, measurable_to_fun := assume s (hs : is_measurable s), begin refine ⟨_, is_measurable_inr_image hs, set.ext _⟩, rintros ⟨ab, b, rfl⟩, simp [set.range_inr._match_1] end, measurable_inv_fun := measurable.subtype_mk measurable_inr } /-- Products distribute over sums (on the right) as measurable spaces. -/ def sum_prod_distrib (α β γ) [measurable_space α] [measurable_space β] [measurable_space γ] : measurable_equiv ((α ⊕ β) × γ) ((α × γ) ⊕ (β × γ)) := { to_equiv := equiv.sum_prod_distrib α β γ, measurable_to_fun := begin refine measurable_of_measurable_union_cover ((range sum.inl).prod univ) ((range sum.inr).prod univ) (is_measurable_range_inl.prod is_measurable.univ) (is_measurable_range_inr.prod is_measurable.univ) (by { rintro ⟨a|b, c⟩; simp [set.prod_eq] }) _ _, { refine (set.prod (range sum.inl) univ).symm.measurable_coe_iff.1 _, refine (prod_congr set.range_inl (set.univ _)).symm.measurable_coe_iff.1 _, dsimp [(∘)], convert measurable_inl, ext ⟨a, c⟩, refl }, { refine (set.prod (range sum.inr) univ).symm.measurable_coe_iff.1 _, refine (prod_congr set.range_inr (set.univ _)).symm.measurable_coe_iff.1 _, dsimp [(∘)], convert measurable_inr, ext ⟨b, c⟩, refl } end, measurable_inv_fun := measurable_sum ((measurable_inl.comp (measurable.fst measurable_id)).prod_mk (measurable.snd measurable_id)) ((measurable_inr.comp (measurable.fst measurable_id)).prod_mk (measurable.snd measurable_id)) } /-- Products distribute over sums (on the left) as measurable spaces. -/ def prod_sum_distrib (α β γ) [measurable_space α] [measurable_space β] [measurable_space γ] : measurable_equiv (α × (β ⊕ γ)) ((α × β) ⊕ (α × γ)) := prod_comm.trans $ (sum_prod_distrib _ _ _).trans $ sum_congr prod_comm prod_comm /-- Products distribute over sums as measurable spaces. -/ def sum_prod_sum (α β γ δ) [measurable_space α] [measurable_space β] [measurable_space γ] [measurable_space δ] : measurable_equiv ((α ⊕ β) × (γ ⊕ δ)) (((α × γ) ⊕ (α × δ)) ⊕ ((β × γ) ⊕ (β × δ))) := (sum_prod_distrib _ _ _).trans $ sum_congr (prod_sum_distrib _ _ _) (prod_sum_distrib _ _ _) end measurable_equiv /-- A pi-system is a collection of subsets of `α` that is closed under intersections of sets that are not disjoint. Usually it is also required that the collection is nonempty, but we don't do that here. -/ def is_pi_system {α} (C : set (set α)) : Prop := ∀ s t ∈ C, (s ∩ t : set α).nonempty → s ∩ t ∈ C namespace measurable_space /-- A Dynkin system is a collection of subsets of a type `α` that contains the empty set, is closed under complementation and under countable union of pairwise disjoint sets. The disjointness condition is the only difference with `σ`-algebras. The main purpose of Dynkin systems is to provide a powerful induction rule for σ-algebras generated by intersection stable set systems. A Dynkin system is also known as a "λ-system" or a "d-system". -/ structure dynkin_system (α : Type*) := (has : set α → Prop) (has_empty : has ∅) (has_compl : ∀{a}, has a → has aᶜ) (has_Union_nat : ∀{f:ℕ → set α}, pairwise (disjoint on f) → (∀i, has (f i)) → has (⋃i, f i)) namespace dynkin_system @[ext] lemma ext : ∀{d₁ d₂ : dynkin_system α}, (∀s:set α, d₁.has s ↔ d₂.has s) → d₁ = d₂ | ⟨s₁, _, _, _⟩ ⟨s₂, _, _, _⟩ h := have s₁ = s₂, from funext $ assume x, propext $ h x, by subst this variable (d : dynkin_system α) lemma has_compl_iff {a} : d.has aᶜ ↔ d.has a := ⟨λ h, by simpa using d.has_compl h, λ h, d.has_compl h⟩ lemma has_univ : d.has univ := by simpa using d.has_compl d.has_empty theorem has_Union {β} [encodable β] {f : β → set α} (hd : pairwise (disjoint on f)) (h : ∀i, d.has (f i)) : d.has (⋃i, f i) := by { rw ← encodable.Union_decode2, exact d.has_Union_nat (Union_decode2_disjoint_on hd) (λ n, encodable.Union_decode2_cases d.has_empty h) } theorem has_union {s₁ s₂ : set α} (h₁ : d.has s₁) (h₂ : d.has s₂) (h : s₁ ∩ s₂ ⊆ ∅) : d.has (s₁ ∪ s₂) := by { rw union_eq_Union, exact d.has_Union (pairwise_disjoint_on_bool.2 h) (bool.forall_bool.2 ⟨h₂, h₁⟩) } lemma has_diff {s₁ s₂ : set α} (h₁ : d.has s₁) (h₂ : d.has s₂) (h : s₂ ⊆ s₁) : d.has (s₁ \ s₂) := begin apply d.has_compl_iff.1, simp [diff_eq, compl_inter], exact d.has_union (d.has_compl h₁) h₂ (λ x ⟨h₁, h₂⟩, h₁ (h h₂)), end instance : partial_order (dynkin_system α) := { le := λm₁ m₂, m₁.has ≤ m₂.has, le_refl := assume a b, le_refl _, le_trans := assume a b c, le_trans, le_antisymm := assume a b h₁ h₂, ext $ assume s, ⟨h₁ s, h₂ s⟩ } /-- Every measurable space (σ-algebra) forms a Dynkin system -/ def of_measurable_space (m : measurable_space α) : dynkin_system α := { has := m.is_measurable', has_empty := m.is_measurable_empty, has_compl := m.is_measurable_compl, has_Union_nat := assume f _ hf, m.is_measurable_Union f hf } lemma of_measurable_space_le_of_measurable_space_iff {m₁ m₂ : measurable_space α} : of_measurable_space m₁ ≤ of_measurable_space m₂ ↔ m₁ ≤ m₂ := iff.rfl /-- The least Dynkin system containing a collection of basic sets. This inductive type gives the underlying collection of sets. -/ inductive generate_has (s : set (set α)) : set α → Prop | basic : ∀t∈s, generate_has t | empty : generate_has ∅ | compl : ∀{a}, generate_has a → generate_has aᶜ | Union : ∀{f:ℕ → set α}, pairwise (disjoint on f) → (∀i, generate_has (f i)) → generate_has (⋃i, f i) lemma generate_has_compl {C : set (set α)} {s : set α} : generate_has C sᶜ ↔ generate_has C s := by { refine ⟨_, generate_has.compl⟩, intro h, convert generate_has.compl h, simp } /-- The least Dynkin system containing a collection of basic sets. -/ def generate (s : set (set α)) : dynkin_system α := { has := generate_has s, has_empty := generate_has.empty, has_compl := assume a, generate_has.compl, has_Union_nat := assume f, generate_has.Union } lemma generate_has_def {C : set (set α)} : (generate C).has = generate_has C := rfl instance : inhabited (dynkin_system α) := ⟨generate univ⟩ /-- If a Dynkin system is closed under binary intersection, then it forms a `σ`-algebra. -/ def to_measurable_space (h_inter : ∀s₁ s₂, d.has s₁ → d.has s₂ → d.has (s₁ ∩ s₂)) := { measurable_space . is_measurable' := d.has, is_measurable_empty := d.has_empty, is_measurable_compl := assume s h, d.has_compl h, is_measurable_Union := assume f hf, have ∀n, d.has (disjointed f n), from assume n, disjointed_induct (hf n) (assume t i h, h_inter _ _ h $ d.has_compl $ hf i), have d.has (⋃n, disjointed f n), from d.has_Union disjoint_disjointed this, by rwa [Union_disjointed] at this } lemma of_measurable_space_to_measurable_space (h_inter : ∀s₁ s₂, d.has s₁ → d.has s₂ → d.has (s₁ ∩ s₂)) : of_measurable_space (d.to_measurable_space h_inter) = d := ext $ assume s, iff.rfl /-- If `s` is in a Dynkin system `d`, we can form the new Dynkin system `{s ∩ t | t ∈ d}`. -/ def restrict_on {s : set α} (h : d.has s) : dynkin_system α := { has := λt, d.has (t ∩ s), has_empty := by simp [d.has_empty], has_compl := assume t hts, have tᶜ ∩ s = ((t ∩ s)ᶜ) \ sᶜ, from set.ext $ assume x, by { by_cases x ∈ s; simp [h] }, by { rw [this], exact d.has_diff (d.has_compl hts) (d.has_compl h) (compl_subset_compl.mpr $ inter_subset_right _ _) }, has_Union_nat := assume f hd hf, begin rw [inter_comm, inter_Union], apply d.has_Union_nat, { exact λ i j h x ⟨⟨_, h₁⟩, _, h₂⟩, hd i j h ⟨h₁, h₂⟩ }, { simpa [inter_comm] using hf }, end } lemma generate_le {s : set (set α)} (h : ∀t∈s, d.has t) : generate s ≤ d := λ t ht, ht.rec_on h d.has_empty (assume a _ h, d.has_compl h) (assume f hd _ hf, d.has_Union hd hf) lemma generate_has_subset_generate_measurable {C : set (set α)} {s : set α} (hs : (generate C).has s) : (generate_from C).is_measurable' s := generate_le (of_measurable_space (generate_from C)) (λ t, is_measurable_generate_from) s hs lemma generate_inter {s : set (set α)} (hs : is_pi_system s) {t₁ t₂ : set α} (ht₁ : (generate s).has t₁) (ht₂ : (generate s).has t₂) : (generate s).has (t₁ ∩ t₂) := have generate s ≤ (generate s).restrict_on ht₂, from generate_le _ $ assume s₁ hs₁, have (generate s).has s₁, from generate_has.basic s₁ hs₁, have generate s ≤ (generate s).restrict_on this, from generate_le _ $ assume s₂ hs₂, show (generate s).has (s₂ ∩ s₁), from (s₂ ∩ s₁).eq_empty_or_nonempty.elim (λ h, h.symm ▸ generate_has.empty) (λ h, generate_has.basic _ (hs _ _ hs₂ hs₁ h)), have (generate s).has (t₂ ∩ s₁), from this _ ht₂, show (generate s).has (s₁ ∩ t₂), by rwa [inter_comm], this _ ht₁ /-- If we have a collection of sets closed under binary intersections, then the Dynkin system it generates is equal to the σ-algebra it generates. This result is known as the π-λ theorem. A collection of sets closed under binary intersection is called a "π-system" if it is non-empty. -/ lemma generate_from_eq {s : set (set α)} (hs : is_pi_system s) : generate_from s = (generate s).to_measurable_space (assume t₁ t₂, generate_inter hs) := le_antisymm (generate_from_le $ assume t ht, generate_has.basic t ht) (of_measurable_space_le_of_measurable_space_iff.mp $ by { rw [of_measurable_space_to_measurable_space], exact (generate_le _ $ assume t ht, is_measurable_generate_from ht) }) end dynkin_system lemma induction_on_inter {C : set α → Prop} {s : set (set α)} [m : measurable_space α] (h_eq : m = generate_from s) (h_inter : is_pi_system s) (h_empty : C ∅) (h_basic : ∀t∈s, C t) (h_compl : ∀t, is_measurable t → C t → C tᶜ) (h_union : ∀f:ℕ → set α, pairwise (disjoint on f) → (∀i, is_measurable (f i)) → (∀i, C (f i)) → C (⋃i, f i)) : ∀ ⦃t⦄, is_measurable t → C t := have eq : is_measurable = dynkin_system.generate_has s, by { rw [h_eq, dynkin_system.generate_from_eq h_inter], refl }, assume t ht, have dynkin_system.generate_has s t, by rwa [eq] at ht, this.rec_on h_basic h_empty (assume t ht, h_compl t $ by { rw [eq], exact ht }) (assume f hf ht, h_union f hf $ assume i, by { rw [eq], exact ht _ }) end measurable_space namespace filter variables [measurable_space α] /-- A filter `f` is measurably generates if each `s ∈ f` includes a measurable `t ∈ f`. -/ class is_measurably_generated (f : filter α) : Prop := (exists_measurable_subset : ∀ ⦃s⦄, s ∈ f → ∃ t ∈ f, is_measurable t ∧ t ⊆ s) instance is_measurably_generated_bot : is_measurably_generated (⊥ : filter α) := ⟨λ _ _, ⟨∅, mem_bot_sets, is_measurable.empty, empty_subset _⟩⟩ instance is_measurably_generated_top : is_measurably_generated (⊤ : filter α) := ⟨λ s hs, ⟨univ, univ_mem_sets, is_measurable.univ, λ x _, hs x⟩⟩ lemma eventually.exists_measurable_mem {f : filter α} [is_measurably_generated f] {p : α → Prop} (h : ∀ᶠ x in f, p x) : ∃ s ∈ f, is_measurable s ∧ ∀ x ∈ s, p x := is_measurably_generated.exists_measurable_subset h instance inf_is_measurably_generated (f g : filter α) [is_measurably_generated f] [is_measurably_generated g] : is_measurably_generated (f ⊓ g) := begin refine ⟨_⟩, rintros t ⟨sf, hsf, sg, hsg, ht⟩, rcases is_measurably_generated.exists_measurable_subset hsf with ⟨s'f, hs'f, hmf, hs'sf⟩, rcases is_measurably_generated.exists_measurable_subset hsg with ⟨s'g, hs'g, hmg, hs'sg⟩, refine ⟨s'f ∩ s'g, inter_mem_inf_sets hs'f hs'g, hmf.inter hmg, _⟩, exact subset.trans (inter_subset_inter hs'sf hs'sg) ht end lemma principal_is_measurably_generated_iff {s : set α} : is_measurably_generated (𝓟 s) ↔ is_measurable s := begin refine ⟨_, λ hs, ⟨λ t ht, ⟨s, mem_principal_self s, hs, ht⟩⟩⟩, rintros ⟨hs⟩, rcases hs (mem_principal_self s) with ⟨t, ht, htm, hts⟩, have : t = s := subset.antisymm hts ht, rwa ← this end alias principal_is_measurably_generated_iff ↔ _ is_measurable.principal_is_measurably_generated instance infi_is_measurably_generated {f : ι → filter α} [∀ i, is_measurably_generated (f i)] : is_measurably_generated (⨅ i, f i) := begin refine ⟨λ s hs, _⟩, rw [← equiv.plift.surjective.infi_comp, mem_infi_iff] at hs, rcases hs with ⟨t, ht, ⟨V, hVf, hVs⟩⟩, choose U hUf hU using λ i, is_measurably_generated.exists_measurable_subset (hVf i), refine ⟨⋂ i : t, U i, _, _, _⟩, { rw [← equiv.plift.surjective.infi_comp, mem_infi_iff], refine ⟨t, ht, U, hUf, subset.refl _⟩ }, { haveI := ht.countable.to_encodable, refine is_measurable.Inter (λ i, (hU i).1) }, { exact subset.trans (Inter_subset_Inter $ λ i, (hU i).2) hVs } end end filter
e40b19e70e641ee7aa68615775c92ebde9347a90
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/binder_matching.lean
0d86b04a3bc3405e6a750881b513b931e94ad274
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
15,630
lean
/- Copyright (c) 2020 Jannis Limperg. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jannis Limperg -/ import data.option.defs import meta.expr /-! # Matching expressions with leading binders This module defines a family of tactics for matching expressions with leading Π or λ binders, similar to Core's `mk_local_pis`. They all iterate over an expression, processing one leading binder at a time. The bound variable is replaced by either a fresh local constant or a fresh metavariable in the binder body, 'opening' the binder. We then recurse into this new body. This scheme is implemented by `tactic.open_binders` and `tactic.open_n_binders`. Based on these general tactics, we define many variations of this recipe: - `open_pis` opens all leading Π binders and replaces them with fresh local constants. This is defined in core. - `open_lambdas` opens leading λ binders instead. Example: ``` open_lambdas `(λ (x : X) (y : Y), f x y) = ([`(_fresh.1), `(_fresh.2)], `(f _fresh.1 _fresh.2)) ``` `_fresh.1` and `_fresh.2` are fresh local constants (with types `X` and `Y`, respectively). The second component of the pair is the lambda body with `x` replaced by `_fresh.1` and `y` replaced by `_fresh.2`. - `open_pis_metas` opens all leading Π binders and replaces them with fresh metavariables (instead of local constants). - `open_n_pis` opens only the first `n` leading Π binders and fails if there are not at least `n` leading binders. Example: ``` open_n_pis `(Π (x : X) (y : Y), P x y) 1 = ([`(_fresh.1)], `(Π (y : Y), P _fresh.1 y)) ``` - `open_lambdas_whnf` normalises the input expression each time before trying to match a binder. Example: ``` open_lambdas_whnf `(let f := λ (x : X), g x y in f) = ([`(_fresh.1)], `(g _fresh.1 y)) ``` - Any combination of these features is also provided, e.g. `open_n_lambdas_metas_whnf` to open `n` λ binders up to normalisation, replacing them with fresh metavariables. The `open_*` functions are commonly used like this: 1. Open (some of) the binders of an expression `e`, producing local constants `lcs` and the 'body' `e'` of `e`. 2. Process `e'` in some way. 3. Reconstruct the binders using `tactic.pis` or `tactic.lambdas`, which Π/λ-bind the `lcs` in `e'`. This reverts the effect of `open_*`. -/ namespace tactic open expr /-- `get_binder do_whnf pi_or_lambda e` matches `e` of the form `λ x, e'` or `Π x, e`. Returns information about the leading binder (its name, `binder_info`, type and body), or `none` if `e` does not start with a binder. If `do_whnf = some (md, unfold_ginductive)`, then `e` is weak head normalised with transparency `md` before matching on it. `unfold_ginductive` controls whether constructors of generalised inductive data types are unfolded during normalisation. If `pi_or_lambda` is `tt`, we match a leading Π binder; otherwise a leading λ binder. -/ @[inline] meta def get_binder (do_whnf : option (transparency × bool)) (pi_or_lambda : bool) (e : expr) : tactic (option (name × binder_info × expr × expr)) := do e ← do_whnf.elim (pure e) (λ p, whnf e p.1 p.2), pure $ if pi_or_lambda then match_pi e else match_lam e /-- `mk_binder_replacement local_or_meta b` creates an expression that can be used to replace the binder `b`. If `local_or_meta` is true, we create a fresh local constant with `b`'s display name, `binder_info` and type; otherwise a fresh metavariable with `b`'s type. -/ meta def mk_binder_replacement (local_or_meta : bool) (b : binder) : tactic expr := if local_or_meta then mk_local' b.name b.info b.type else mk_meta_var b.type /-- `open_binders` is a generalisation of functions like `open_pis`, `mk_meta_lambdas` etc. `open_binders do_whnf pis_or_lamdas local_or_metas e` proceeds as follows: - Match a leading λ or Π binder using `get_binder do_whnf pis_or_lambdas`. See `get_binder` for details. Return `e` unchanged (and an empty list) if `e` does not start with a λ/Π. - Construct a replacement for the bound variable using `mk_binder_replacement locals_or_metas`. See `mk_binder_replacement` for details. Replace the bound variable with this replacement in the binder body. - Recurse into the binder body. Returns the constructed replacement expressions and `e` without its leading binders. -/ meta def open_binders (do_whnf : option (transparency × bool)) (pis_or_lambdas : bool) (locals_or_metas : bool) : expr → tactic (list expr × expr) := λ e, do some (name, bi, type, body) ← get_binder do_whnf pis_or_lambdas e | pure ([], e), replacement ← mk_binder_replacement locals_or_metas ⟨name, bi, type⟩, (rs, rest) ← open_binders (body.instantiate_var replacement), pure (replacement :: rs, rest) /-- `open_n_binders do_whnf pis_or_lambdas local_or_metas e n` is like `open_binders do_whnf pis_or_lambdas local_or_metas e`, but it matches exactly `n` leading Π/λ binders of `e`. If `e` does not start with at least `n` Π/λ binders, (after normalisation, if `do_whnf` is given), the tactic fails. -/ meta def open_n_binders (do_whnf : option (transparency × bool)) (pis_or_lambdas : bool) (locals_or_metas : bool) : expr → ℕ → tactic (list expr × expr) | e 0 := pure ([], e) | e (d + 1) := do some (name, bi, type, body) ← get_binder do_whnf pis_or_lambdas e | failed, replacement ← mk_binder_replacement locals_or_metas ⟨name, bi, type⟩, (rs, rest) ← open_n_binders (body.instantiate_var replacement) d, pure (replacement :: rs, rest) /-- `open_pis e` instantiates all leading Π binders of `e` with fresh local constants. Returns the local constants and the remainder of `e`. This is an alias for `tactic.mk_local_pis`. -/ meta abbreviation open_pis : expr → tactic (list expr × expr) := mk_local_pis /-- `open_pis_metas e` instantiates all leading Π binders of `e` with fresh metavariables. Returns the metavariables and the remainder of `e`. This is `open_pis` but with metavariables instead of local constants. -/ meta def open_pis_metas : expr → tactic (list expr × expr) := open_binders none tt ff /-- `open_n_pis e n` instantiates the first `n` Π binders of `e` with fresh local constants. Returns the local constants and the remainder of `e`. Fails if `e` does not start with at least `n` Π binders. This is `open_pis` but limited to `n` binders. -/ meta def open_n_pis : expr → ℕ → tactic (list expr × expr) := open_n_binders none tt tt /-- `open_n_pis_metas e n` instantiates the first `n` Π binders of `e` with fresh metavariables. Returns the metavariables and the remainder of `e`. This is `open_n_pis` but with metavariables instead of local constants. -/ meta def open_n_pis_metas : expr → ℕ → tactic (list expr × expr) := open_n_binders none tt ff /-- `open_pis_whnf e md unfold_ginductive` instantiates all leading Π binders of `e` with fresh local constants. The leading Π binders of `e` are matched up to normalisation with transparency `md`. `unfold_ginductive` determines whether constructors of generalised inductive types are unfolded during normalisation. This is `open_pis` up to normalisation. -/ meta def open_pis_whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic (list expr × expr) := open_binders (some (md, unfold_ginductive)) tt tt e /-- `open_pis_metas_whnf e md unfold_ginductive` instantiates all leading Π binders of `e` with fresh metavariables. The leading Π binders of `e` are matched up to normalisation with transparency `md`. `unfold_ginductive` determines whether constructors of generalised inductive types are unfolded during normalisation. This is `open_pis_metas` up to normalisation. -/ meta def open_pis_metas_whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic (list expr × expr) := open_binders (some (md, unfold_ginductive)) tt ff e /-- `open_n_pis_whnf e n md unfold_ginductive` instantiates the first `n` Π binders of `e` with fresh local constants. The leading Π binders of `e` are matched up to normalisation with transparency `md`. `unfold_ginductive` determines whether constructors of generalised inductive types are unfolded during normalisation. This is `open_pis_whnf` but restricted to `n` binders. -/ meta def open_n_pis_whnf (e : expr) (n : ℕ) (md := semireducible) (unfold_ginductive := tt) : tactic (list expr × expr) := open_n_binders (some (md, unfold_ginductive)) tt tt e n /-- `open_n_pis_metas_whnf e n md unfold_ginductive` instantiates the first `n` Π binders of `e` with fresh metavariables. The leading Π binders of `e` are matched up to normalisation with transparency `md`. `unfold_ginductive` determines whether constructors of generalised inductive types are unfolded during normalisation. This is `open_pis_metas_whnf` but restricted to `n` binders. -/ meta def open_n_pis_metas_whnf (e : expr) (n : ℕ) (md := semireducible) (unfold_ginductive := tt) : tactic (list expr × expr) := open_n_binders (some (md, unfold_ginductive)) tt ff e n /-- `get_pi_binders e` instantiates all leading Π binders of `e` with fresh local constants (like `open_pis`). Returns the remainder of `e` and information about the binders that were instantiated (but not the new local constants). See also `expr.pi_binders` (which produces open terms). -/ meta def get_pi_binders (e : expr) : tactic (list binder × expr) := do (lcs, rest) ← open_pis e, pure (lcs.map to_binder, rest) private meta def get_pi_binders_nondep_aux : ℕ → expr → tactic (list (ℕ × binder) × expr) := λ i e, do some (name, bi, type, body) ← get_binder none tt e | pure ([], e), replacement ← mk_local' name bi type, (rs, rest) ← get_pi_binders_nondep_aux (i + 1) (body.instantiate_var replacement), let rs' := if body.has_var then rs else (i, replacement.to_binder) :: rs, pure (rs', rest) /-- `get_pi_binders_nondep e` instantiates all leading Π binders of `e` with fresh local constants (like `open_pis`). Returns the remainder of `e` and information about the *nondependent* binders that were instantiated (but not the new local constants). A nondependent binder is one that does not appear later in the expression. Also returns the index of each returned binder (starting at 0). -/ meta def get_pi_binders_nondep : expr → tactic (list (ℕ × binder) × expr) := get_pi_binders_nondep_aux 0 /-- `open_lambdas e` instantiates all leading λ binders of `e` with fresh local constants. Returns the new local constants and the remainder of `e`. This is `open_pis` but for λ binders rather than Π binders. -/ meta def open_lambdas : expr → tactic (list expr × expr) := open_binders none ff tt /-- `open_lambdas_metas e` instantiates all leading λ binders of `e` with fresh metavariables. Returns the new metavariables and the remainder of `e`. This is `open_lambdas` but with metavariables instead of local constants. -/ meta def open_lambdas_metas : expr → tactic (list expr × expr) := open_binders none ff ff /-- `open_n_lambdas e n` instantiates the first `n` λ binders of `e` with fresh local constants. Returns the new local constants and the remainder of `e`. Fails if `e` does not start with at least `n` λ binders. This is `open_lambdas` but restricted to the first `n` binders. -/ meta def open_n_lambdas : expr → ℕ → tactic (list expr × expr) := open_n_binders none ff tt /-- `open_n_lambdas_metas e n` instantiates the first `n` λ binders of `e` with fresh metavariables. Returns the new metavariables and the remainder of `e`. Fails if `e` does not start with at least `n` λ binders. This is `open_lambdas_metas` but restricted to the first `n` binders. -/ meta def open_n_lambdas_metas : expr → ℕ → tactic (list expr × expr) := open_n_binders none ff ff /-- `open_lambdas_whnf e md unfold_ginductive` instantiates all leading λ binders of `e` with fresh local constants. The leading λ binders of `e` are matched up to normalisation with transparency `md`. `unfold_ginductive` determines whether constructors of generalised inductive types are unfolded during normalisation. This is `open_lambdas` up to normalisation. -/ meta def open_lambdas_whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic (list expr × expr) := open_binders (some (md, unfold_ginductive)) ff tt e /-- `open_lambdas_metas_whnf e md unfold_ginductive` instantiates all leading λ binders of `e` with fresh metavariables. The leading λ binders of `e` are matched up to normalisation with transparency `md`. `unfold_ginductive` determines whether constructors of generalised inductive types are unfolded during normalisation. This is `open_lambdas_metas` up to normalisation. -/ meta def open_lambdas_metas_whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic (list expr × expr) := open_binders (some (md, unfold_ginductive)) ff ff e /-- `open_n_lambdas_whnf e md unfold_ginductive` instantiates the first `n` λ binders of `e` with fresh local constants. The λ binders are matched up to normalisation with transparency `md`. `unfold_ginductive` determines whether constructors of generalised inductive types are unfolded during normalisation. Fails if `e` does not start with `n` λ binders (after normalisation). This is `open_n_lambdas` up to normalisation. -/ meta def open_n_lambdas_whnf (e : expr) (n : ℕ) (md := semireducible) (unfold_ginductive := tt) : tactic (list expr × expr) := open_n_binders (some (md, unfold_ginductive)) ff tt e n /-- `open_n_lambdas_metas_whnf e md unfold_ginductive` instantiates the first `n` λ binders of `e` with fresh metavariables. The λ binders are matched up to normalisation with transparency `md`. `unfold_ginductive` determines whether constructors of generalised inductive types are unfolded during normalisation. Fails if `e` does not start with `n` λ binders (after normalisation). This is `open_n_lambdas_metas` up to normalisation. -/ meta def open_n_lambdas_metas_whnf (e : expr) (n : ℕ) (md := semireducible) (unfold_ginductive := tt) : tactic (list expr × expr) := open_n_binders (some (md, unfold_ginductive)) ff ff e n /-! ## Special-purpose tactics The following tactics are variations of the 'opening binders' theme that do not quite fit in the above scheme. -/ /-- `open_pis_whnf_dep e` instantiates all leading Π binders of `e` with fresh local constants (like `tactic.open_pis`). It returns the remainder of the expression and, for each binder, the corresponding local constant and whether the binder was dependent. -/ meta def open_pis_whnf_dep : expr → tactic (list (expr × bool) × expr) := λ e, do e' ← whnf e, match e' with | (pi n bi t rest) := do c ← mk_local' n bi t, let dep := rest.has_var, (cs, rest) ← open_pis_whnf_dep $ rest.instantiate_var c, pure ((c, dep) :: cs, rest) | _ := pure ([], e) end /-- `open_n_pis_metas' e n` instantiates the first `n` leading Π binders of `e` with fresh metavariables. It returns the remainder of the expression and, for each binder, the corresponding metavariable, the name of the bound variable and the binder's `binder_info`. Fails if `e` does not have at least `n` leading Π binders. -/ meta def open_n_pis_metas' : expr → ℕ → tactic (list (expr × name × binder_info) × expr) | e 0 := pure ([], e) | (pi nam bi t rest) (n + 1) := do m ← mk_meta_var t, (ms, rest) ← open_n_pis_metas' (rest.instantiate_var m) n, pure ((m, nam, bi) :: ms, rest) | e (n + 1) := fail $ to_fmt "expected an expression starting with a Π, but got: " ++ to_fmt e end tactic
666423775d3dcdbba3ffa87e6f055ebf6d036490
d6124c8dbe5661dcc5b8c9da0a56fbf1f0480ad6
/test/run/ir/functionRef.lean
058932627f47786e6164d0e7783c7e0c8463529f
[ "Apache-2.0" ]
permissive
xubaiw/lean4-papyrus
c3fbbf8ba162eb5f210155ae4e20feb2d32c8182
02e82973a5badda26fc0f9fd15b3d37e2eb309e0
refs/heads/master
1,691,425,756,824
1,632,122,825,000
1,632,123,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,511
lean
import Papyrus open Papyrus def assertBEq [Repr α] [BEq α] (expected actual : α) : IO PUnit := do unless expected == actual do throw <| IO.userError s!"expected '{repr expected}', got '{repr actual}'" -- empty function #eval LlvmM.run do let name := "foo" let voidTypeRef ← VoidTypeRef.get let fnTy ← FunctionTypeRef.get voidTypeRef #[] let fn ← FunctionRef.create fnTy name assertBEq name (← fn.getName) assertBEq ValueKind.function fn.valueKind assertBEq Linkage.external (← fn.getLinkage) assertBEq Visibility.default (← fn.getVisibility) assertBEq DLLStorageClass.default (← fn.getDLLStorageClass) assertBEq ThreadLocalMode.notLocal (← fn.getThreadLocalMode) assertBEq AddressSignificance.total (← fn.getAddressSignificance) assertBEq AddressSpace.default (← fn.getAddressSpace) assertBEq CallingConvention.c (← fn.getCallingConvention) assertBEq 0 (← fn.getRawAlignment) assertBEq false (← fn.hasSection) assertBEq false (← fn.hasGC) -- single block function #eval LlvmM.run do let bbName := "foo" let voidTypeRef ← VoidTypeRef.get let fnTy ← FunctionTypeRef.get voidTypeRef #[] let fn ← FunctionRef.create fnTy "test" let bb ← BasicBlockRef.create bbName fn.appendBasicBlock bb let bbs ← fn.getBasicBlocks if h : bbs.size = 1 then let bb ← bbs.get (Fin.mk 0 (by simp [h])) assertBEq bbName (← bb.getName) else throw <| IO.userError s!"expected 1 basic block in function, got {bbs.size}"
2b7956f10686987e10a891b1b2d4afe91417d781
626e312b5c1cb2d88fca108f5933076012633192
/src/algebra/floor.lean
19f35510a017c2cfe0aaf1cc36c7d8b04e8ca843
[ "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
15,548
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kevin Kappelmann -/ import tactic.linarith import tactic.abel import algebra.ordered_group import data.set.intervals.basic /-! # Floor and ceil ## Summary We define `floor`, `ceil`, `nat_floor`and `nat_ceil` functions on linear ordered rings. ## Main Definitions - `floor_ring`: Linear ordered ring with a floor function. - `floor x`: Greatest integer `z` such that `z ≤ x`. - `ceil x`: Least integer `z` such that `x ≤ z`. - `fract x`: Fractional part of `x`, defined as `x - floor x`. - `nat_floor x`: Greatest natural `n` such that `n ≤ x`. Defined as `0` if `x < 0`. - `nat_ceil x`: Least natural `n` such that `x ≤ n`. ## Notations - `⌊x⌋` is `floor x`. - `⌈x⌉` is `ceil x`. - `⌊x⌋₊` is `nat_floor x`. - `⌈x⌉₊` is `nat_ceil x`. The index `₊` in the notations for `nat_floor` and `nat_ceil` is used in analogy to the notation for `nnnorm`. ## Tags rounding, floor, ceil -/ variables {α : Type*} open_locale classical /-! ### Floor rings -/ /-- A `floor_ring` is a linear ordered ring over `α` with a function `floor : α → ℤ` satisfying `∀ (z : ℤ) (x : α), z ≤ floor x ↔ (z : α) ≤ x)`. -/ class floor_ring (α) [linear_ordered_ring α] := (floor : α → ℤ) (le_floor : ∀ (z : ℤ) (x : α), z ≤ floor x ↔ (z : α) ≤ x) instance : floor_ring ℤ := { floor := id, le_floor := λ _ _, by rw int.cast_id; refl } variables [linear_ordered_ring α] [floor_ring α] /-- `floor x` is the greatest integer `z` such that `z ≤ x`. It is denoted with `⌊x⌋`. -/ def floor : α → ℤ := floor_ring.floor notation `⌊` x `⌋` := floor x theorem le_floor : ∀ {z : ℤ} {x : α}, z ≤ ⌊x⌋ ↔ (z : α) ≤ x := floor_ring.le_floor theorem floor_lt {x : α} {z : ℤ} : ⌊x⌋ < z ↔ x < z := lt_iff_lt_of_le_iff_le le_floor theorem floor_le (x : α) : (⌊x⌋ : α) ≤ x := le_floor.1 (le_refl _) theorem floor_nonneg {x : α} : 0 ≤ ⌊x⌋ ↔ 0 ≤ x := by rw [le_floor]; refl theorem lt_succ_floor (x : α) : x < ⌊x⌋.succ := floor_lt.1 $ int.lt_succ_self _ theorem lt_floor_add_one (x : α) : x < ⌊x⌋ + 1 := by simpa only [int.succ, int.cast_add, int.cast_one] using lt_succ_floor x theorem sub_one_lt_floor (x : α) : x - 1 < ⌊x⌋ := sub_lt_iff_lt_add.2 (lt_floor_add_one x) @[simp] theorem floor_coe (z : ℤ) : ⌊(z:α)⌋ = z := eq_of_forall_le_iff $ λ a, by rw [le_floor, int.cast_le] @[simp] theorem floor_zero : ⌊(0:α)⌋ = 0 := floor_coe 0 @[simp] theorem floor_one : ⌊(1:α)⌋ = 1 := by rw [← int.cast_one, floor_coe] @[mono] theorem floor_mono {a b : α} (h : a ≤ b) : ⌊a⌋ ≤ ⌊b⌋ := le_floor.2 (le_trans (floor_le _) h) @[simp] theorem floor_add_int (x : α) (z : ℤ) : ⌊x + z⌋ = ⌊x⌋ + z := eq_of_forall_le_iff $ λ a, by rw [le_floor, ← sub_le_iff_le_add, ← sub_le_iff_le_add, le_floor, int.cast_sub] @[simp] theorem floor_int_add (z : ℤ) (x : α) : ⌊↑z + x⌋ = z + ⌊x⌋ := by simpa only [add_comm] using floor_add_int x z @[simp] theorem floor_add_nat (x : α) (n : ℕ) : ⌊x + n⌋ = ⌊x⌋ + n := floor_add_int x n @[simp] theorem floor_nat_add (n : ℕ) (x : α) : ⌊↑n + x⌋ = n + ⌊x⌋ := floor_int_add n x @[simp] theorem floor_sub_int (x : α) (z : ℤ) : ⌊x - z⌋ = ⌊x⌋ - z := eq.trans (by rw [int.cast_neg, sub_eq_add_neg]) (floor_add_int _ _) @[simp] theorem floor_sub_nat (x : α) (n : ℕ) : ⌊x - n⌋ = ⌊x⌋ - n := floor_sub_int x n lemma abs_sub_lt_one_of_floor_eq_floor {α : Type*} [linear_ordered_comm_ring α] [floor_ring α] {x y : α} (h : ⌊x⌋ = ⌊y⌋) : abs (x - y) < 1 := begin have : x < ⌊x⌋ + 1 := lt_floor_add_one x, have : y < ⌊y⌋ + 1 := lt_floor_add_one y, have : (⌊x⌋ : α) = ⌊y⌋ := int.cast_inj.2 h, have : (⌊x⌋: α) ≤ x := floor_le x, have : (⌊y⌋ : α) ≤ y := floor_le y, exact abs_sub_lt_iff.2 ⟨by linarith, by linarith⟩ end lemma floor_eq_iff {r : α} {z : ℤ} : ⌊r⌋ = z ↔ ↑z ≤ r ∧ r < (z + 1) := by rw [←le_floor, ←int.cast_one, ←int.cast_add, ←floor_lt, int.lt_add_one_iff, le_antisymm_iff, and.comm] lemma floor_ring_unique {α} [linear_ordered_ring α] (inst1 inst2 : floor_ring α) : @floor _ _ inst1 = @floor _ _ inst2 := begin ext v, suffices : (⌊v⌋ : α) ≤ v ∧ v < ⌊v⌋ + 1, by rwa [floor_eq_iff], exact ⟨floor_le v, lt_floor_add_one v⟩ end lemma floor_eq_on_Ico (n : ℤ) : ∀ x ∈ (set.Ico n (n+1) : set α), ⌊x⌋ = n := λ x ⟨h₀, h₁⟩, floor_eq_iff.mpr ⟨h₀, h₁⟩ lemma floor_eq_on_Ico' (n : ℤ) : ∀ x ∈ (set.Ico n (n+1) : set α), (⌊x⌋ : α) = n := λ x hx, by exact_mod_cast floor_eq_on_Ico n x hx /-- The fractional part fract r of r is just r - ⌊r⌋ -/ def fract (r : α) : α := r - ⌊r⌋ -- Mathematical notation is usually {r}. Let's not even go there. @[simp] lemma floor_add_fract (r : α) : (⌊r⌋ : α) + fract r = r := by unfold fract; simp @[simp] lemma fract_add_floor (r : α) : fract r + ⌊r⌋ = r := sub_add_cancel _ _ theorem fract_nonneg (r : α) : 0 ≤ fract r := sub_nonneg.2 $ floor_le _ theorem fract_lt_one (r : α) : fract r < 1 := sub_lt.1 $ sub_one_lt_floor _ @[simp] lemma fract_zero : fract (0 : α) = 0 := by unfold fract; simp @[simp] lemma fract_coe (z : ℤ) : fract (z : α) = 0 := by unfold fract; rw floor_coe; exact sub_self _ @[simp] lemma fract_floor (r : α) : fract (⌊r⌋ : α) = 0 := fract_coe _ @[simp] lemma floor_fract (r : α) : ⌊fract r⌋ = 0 := by rw floor_eq_iff; exact ⟨fract_nonneg _, by rw [int.cast_zero, zero_add]; exact fract_lt_one r⟩ theorem fract_eq_iff {r s : α} : fract r = s ↔ 0 ≤ s ∧ s < 1 ∧ ∃ z : ℤ, r - s = z := ⟨λ h, by rw ←h; exact ⟨fract_nonneg _, fract_lt_one _, ⟨⌊r⌋, sub_sub_cancel _ _⟩⟩, begin intro h, show r - ⌊r⌋ = s, apply eq.symm, rw [eq_sub_iff_add_eq, add_comm, ←eq_sub_iff_add_eq], rcases h with ⟨hge, hlt, ⟨z, hz⟩⟩, rw [hz, int.cast_inj, floor_eq_iff, ←hz], clear hz, split; simpa [sub_eq_add_neg, add_assoc] end⟩ theorem fract_eq_fract {r s : α} : fract r = fract s ↔ ∃ z : ℤ, r - s = z := ⟨λ h, ⟨⌊r⌋ - ⌊s⌋, begin unfold fract at h, rw [int.cast_sub, sub_eq_sub_iff_sub_eq_sub.1 h], end⟩, λ h, begin rcases h with ⟨z, hz⟩, rw fract_eq_iff, split, exact fract_nonneg _, split, exact fract_lt_one _, use z + ⌊s⌋, rw [eq_add_of_sub_eq hz, int.cast_add], unfold fract, simp [sub_eq_add_neg, add_assoc] end⟩ @[simp] lemma fract_fract (r : α) : fract (fract r) = fract r := by rw fract_eq_fract; exact ⟨-⌊r⌋, by simp [sub_eq_add_neg, add_assoc, fract]⟩ theorem fract_add (r s : α) : ∃ z : ℤ, fract (r + s) - fract r - fract s = z := ⟨⌊r⌋ + ⌊s⌋ - ⌊r + s⌋, by unfold fract; simp [sub_eq_add_neg]; abel⟩ theorem fract_mul_nat (r : α) (b : ℕ) : ∃ z : ℤ, fract r * b - fract (r * b) = z := begin induction b with c hc, use 0, simp, rcases hc with ⟨z, hz⟩, rw [nat.succ_eq_add_one, nat.cast_add, mul_add, mul_add, nat.cast_one, mul_one, mul_one], rcases fract_add (r * c) r with ⟨y, hy⟩, use z - y, rw [int.cast_sub, ←hz, ←hy], abel end /-- `ceil x` is the smallest integer `z` such that `x ≤ z`. It is denoted with `⌈x⌉`. -/ def ceil (x : α) : ℤ := -⌊-x⌋ notation `⌈` x `⌉` := ceil x theorem ceil_le {z : ℤ} {x : α} : ⌈x⌉ ≤ z ↔ x ≤ z := by rw [ceil, neg_le, le_floor, int.cast_neg, neg_le_neg_iff] theorem lt_ceil {x : α} {z : ℤ} : z < ⌈x⌉ ↔ (z:α) < x := lt_iff_lt_of_le_iff_le ceil_le theorem ceil_le_floor_add_one (x : α) : ⌈x⌉ ≤ ⌊x⌋ + 1 := by rw [ceil_le, int.cast_add, int.cast_one]; exact le_of_lt (lt_floor_add_one x) theorem le_ceil (x : α) : x ≤ ⌈x⌉ := ceil_le.1 (le_refl _) @[simp] theorem ceil_coe (z : ℤ) : ⌈(z:α)⌉ = z := by rw [ceil, ← int.cast_neg, floor_coe, neg_neg] theorem ceil_mono {a b : α} (h : a ≤ b) : ⌈a⌉ ≤ ⌈b⌉ := ceil_le.2 (le_trans h (le_ceil _)) @[simp] theorem ceil_add_int (x : α) (z : ℤ) : ⌈x + z⌉ = ⌈x⌉ + z := by rw [ceil, neg_add', floor_sub_int, neg_sub, sub_eq_neg_add]; refl theorem ceil_sub_int (x : α) (z : ℤ) : ⌈x - z⌉ = ⌈x⌉ - z := eq.trans (by rw [int.cast_neg, sub_eq_add_neg]) (ceil_add_int _ _) theorem ceil_lt_add_one (x : α) : (⌈x⌉ : α) < x + 1 := by rw [← lt_ceil, ← int.cast_one, ceil_add_int]; apply lt_add_one lemma ceil_pos {a : α} : 0 < ⌈a⌉ ↔ 0 < a := ⟨ λ h, have ⌊-a⌋ < 0, from neg_of_neg_pos h, pos_of_neg_neg $ lt_of_not_ge $ (not_iff_not_of_iff floor_nonneg).1 $ not_le_of_gt this, λ h, have -a < 0, from neg_neg_of_pos h, neg_pos_of_neg $ lt_of_not_ge $ (not_iff_not_of_iff floor_nonneg).2 $ not_le_of_gt this ⟩ @[simp] theorem ceil_zero : ⌈(0 : α)⌉ = 0 := by simp [ceil] lemma ceil_nonneg {q : α} (hq : 0 ≤ q) : 0 ≤ ⌈q⌉ := if h : q > 0 then le_of_lt $ ceil_pos.2 h else by rw [le_antisymm (le_of_not_lt h) hq, ceil_zero]; trivial lemma ceil_eq_iff {r : α} {z : ℤ} : ⌈r⌉ = z ↔ ↑z-1 < r ∧ r ≤ z := by rw [←ceil_le, ←int.cast_one, ←int.cast_sub, ←lt_ceil, int.sub_one_lt_iff, le_antisymm_iff, and.comm] lemma ceil_eq_on_Ioc (n : ℤ) : ∀ x ∈ (set.Ioc (n-1) n : set α), ⌈x⌉ = n := λ x ⟨h₀, h₁⟩, ceil_eq_iff.mpr ⟨h₀, h₁⟩ lemma ceil_eq_on_Ioc' (n : ℤ) : ∀ x ∈ (set.Ioc (n-1) n : set α), (⌈x⌉ : α) = n := λ x hx, by exact_mod_cast ceil_eq_on_Ioc n x hx lemma floor_lt_ceil_of_lt {x y : α} (h : x < y) : ⌊x⌋ < ⌈y⌉ := by { rw floor_lt, exact h.trans_le (le_ceil _) } /-! ### `nat_floor` and `nat_ceil` -/ section nat variables {a : α} {n : ℕ} /-- `nat_floor x` is the greatest natural `n` that is less than `x`. It is equal to `⌊x⌋` when `x ≥ 0`, and is `0` otherwise. It is denoted with `⌊x⌋₊`.-/ def nat_floor (a : α) : ℕ := int.to_nat ⌊a⌋ notation `⌊` x `⌋₊` := nat_floor x lemma nat_floor_of_nonpos (ha : a ≤ 0) : ⌊a⌋₊ = 0 := begin apply int.to_nat_of_nonpos, exact_mod_cast (floor_le a).trans ha, end lemma pos_of_nat_floor_pos (h : 0 < ⌊a⌋₊) : 0 < a := begin refine (le_or_lt a 0).resolve_left (λ ha, lt_irrefl 0 _), rwa nat_floor_of_nonpos ha at h, end lemma nat_floor_le (ha : 0 ≤ a) : ↑⌊a⌋₊ ≤ a := begin refine le_trans _ (floor_le _), norm_cast, exact (int.to_nat_of_nonneg (floor_nonneg.2 ha)).le, end lemma le_nat_floor_of_le (h : ↑n ≤ a) : n ≤ ⌊a⌋₊ := begin have hn := int.le_to_nat n, norm_cast at hn, exact hn.trans (int.to_nat_le_to_nat (le_floor.2 h)), end theorem le_nat_floor_iff (ha : 0 ≤ a) : n ≤ ⌊a⌋₊ ↔ ↑n ≤ a := ⟨λ h, (nat.cast_le.2 h).trans (nat_floor_le ha), le_nat_floor_of_le⟩ lemma lt_of_lt_nat_floor (h : n < ⌊a⌋₊) : ↑n < a := (nat.cast_lt.2 h).trans_le (nat_floor_le (pos_of_nat_floor_pos ((nat.zero_le n).trans_lt h)).le) theorem nat_floor_lt_iff (ha : 0 ≤ a) : ⌊a⌋₊ < n ↔ a < ↑n := le_iff_le_iff_lt_iff_lt.1 (le_nat_floor_iff ha) theorem nat_floor_mono {a₁ a₂ : α} (h : a₁ ≤ a₂) : ⌊a₁⌋₊ ≤ ⌊a₂⌋₊ := begin obtain ha | ha := le_total a₁ 0, { rw nat_floor_of_nonpos ha, exact nat.zero_le _ }, exact le_nat_floor_of_le ((nat_floor_le ha).trans h), end @[simp] theorem nat_floor_coe (n : ℕ) : ⌊(n : α)⌋₊ = n := begin rw nat_floor, convert int.to_nat_coe_nat n, exact floor_coe n, end @[simp] theorem nat_floor_zero : ⌊(0 : α)⌋₊ = 0 := nat_floor_coe 0 theorem nat_floor_add_nat (ha : 0 ≤ a) (n : ℕ) : ⌊a + n⌋₊ = ⌊a⌋₊ + n := begin change int.to_nat ⌊a + (n : ℤ)⌋ = int.to_nat ⌊a⌋ + n, rw [floor_add_int, int.to_nat_add_nat (le_floor.2 ha)], end lemma lt_nat_floor_add_one (a : α) : a < ⌊a⌋₊ + 1 := begin refine (lt_floor_add_one a).trans_le (add_le_add_right _ 1), norm_cast, exact int.le_to_nat _, end lemma nat_floor_eq_zero_iff : ⌊a⌋₊ = 0 ↔ a < 1 := begin obtain ha | ha := le_total a 0, { exact iff_of_true (nat_floor_of_nonpos ha) (ha.trans_lt zero_lt_one) }, rw [←nat.cast_one, ←nat_floor_lt_iff ha, nat.lt_add_one_iff, nat.le_zero_iff], end /-- `nat_ceil x` is the least natural `n` that is greater than `x`. It is equal to `⌈x⌉` when `x ≥ 0`, and is `0` otherwise. It is denoted with `⌈x⌉₊`. -/ def nat_ceil (a : α) : ℕ := int.to_nat ⌈a⌉ notation `⌈` x `⌉₊` := nat_ceil x theorem nat_ceil_le : ⌈a⌉₊ ≤ n ↔ a ≤ n := by rw [nat_ceil, int.to_nat_le, ceil_le]; refl theorem lt_nat_ceil : n < ⌈a⌉₊ ↔ (n : α) < a := not_iff_not.1 $ by rw [not_lt, not_lt, nat_ceil_le] theorem le_nat_ceil (a : α) : a ≤ ⌈a⌉₊ := nat_ceil_le.1 (le_refl _) theorem nat_ceil_mono {a₁ a₂ : α} (h : a₁ ≤ a₂) : ⌈a₁⌉₊ ≤ ⌈a₂⌉₊ := nat_ceil_le.2 (le_trans h (le_nat_ceil _)) @[simp] theorem nat_ceil_coe (n : ℕ) : ⌈(n : α)⌉₊ = n := show (⌈((n : ℤ) : α)⌉).to_nat = n, by rw [ceil_coe]; refl @[simp] theorem nat_ceil_zero : ⌈(0 : α)⌉₊ = 0 := nat_ceil_coe 0 theorem nat_ceil_add_nat {a : α} (a_nonneg : 0 ≤ a) (n : ℕ) : ⌈a + n⌉₊ = ⌈a⌉₊ + n := begin change int.to_nat (⌈a + (n:ℤ)⌉) = int.to_nat ⌈a⌉ + n, rw [ceil_add_int], have : 0 ≤ ⌈a⌉, by simpa using (ceil_mono a_nonneg), obtain ⟨_, ceil_a_eq⟩ : ∃ (n : ℕ), ⌈a⌉ = n, from int.eq_coe_of_zero_le this, rw ceil_a_eq, refl end theorem nat_ceil_lt_add_one {a : α} (a_nonneg : 0 ≤ a) : (⌈a⌉₊ : α) < a + 1 := lt_nat_ceil.1 $ by rw ( show ⌈a + 1⌉₊ = ⌈a⌉₊ + 1, by exact_mod_cast (nat_ceil_add_nat a_nonneg 1)); apply nat.lt_succ_self lemma lt_of_nat_ceil_lt {x : α} {n : ℕ} (h : ⌈x⌉₊ < n) : x < n := lt_of_le_of_lt (le_nat_ceil x) (by exact_mod_cast h) lemma le_of_nat_ceil_le {x : α} {n : ℕ} (h : ⌈x⌉₊ ≤ n) : x ≤ n := le_trans (le_nat_ceil x) (by exact_mod_cast h) lemma nat_floor_lt_nat_ceil_of_lt_of_pos {x y : α} (h : x < y) (h' : 0 < y) : ⌊x⌋₊ < ⌈y⌉₊ := begin rcases le_or_lt 0 x with hx|hx, { rw nat_floor_lt_iff hx, exact h.trans_le (le_nat_ceil _) }, { rwa [nat_floor_of_nonpos hx.le, lt_nat_ceil] } end end nat namespace int @[simp] lemma preimage_Ioo {x y : α} : ((coe : ℤ → α) ⁻¹' (set.Ioo x y)) = set.Ioo ⌊x⌋ ⌈y⌉ := by { ext, simp [floor_lt, lt_ceil] } @[simp] lemma preimage_Ico {x y : α} : ((coe : ℤ → α) ⁻¹' (set.Ico x y)) = set.Ico ⌈x⌉ ⌈y⌉ := by { ext, simp [ceil_le, lt_ceil] } @[simp] lemma preimage_Ioc {x y : α} : ((coe : ℤ → α) ⁻¹' (set.Ioc x y)) = set.Ioc ⌊x⌋ ⌊y⌋ := by { ext, simp [floor_lt, le_floor] } @[simp] lemma preimage_Icc {x y : α} : ((coe : ℤ → α) ⁻¹' (set.Icc x y)) = set.Icc ⌈x⌉ ⌊y⌋ := by { ext, simp [ceil_le, le_floor] } @[simp] lemma preimage_Ioi {x : α} : ((coe : ℤ → α) ⁻¹' (set.Ioi x)) = set.Ioi ⌊x⌋ := by { ext, simp [floor_lt] } @[simp] lemma preimage_Ici {x : α} : ((coe : ℤ → α) ⁻¹' (set.Ici x)) = set.Ici ⌈x⌉ := by { ext, simp [ceil_le] } @[simp] lemma preimage_Iio {x : α} : ((coe : ℤ → α) ⁻¹' (set.Iio x)) = set.Iio ⌈x⌉ := by { ext, simp [lt_ceil] } @[simp] lemma preimage_Iic {x : α} : ((coe : ℤ → α) ⁻¹' (set.Iic x)) = set.Iic ⌊x⌋ := by { ext, simp [le_floor] } end int
7c095776ffe705b5116e2a10f218080f71969059
3dd1b66af77106badae6edb1c4dea91a146ead30
/tests/lean/t5.lean
5e54c7258581ec9f4a89b788de35e851daeaed82
[ "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
243
lean
variable N : Type.{1} variable f : N → N variable a : N definition g (a : N) : N := f a check g namespace foo definition h : N := f a check h definition q [private] : N := f a check q end check foo.h check q -- Error q is now hidden
0008e47b17450dde58f30b7ae9e2a9e74f20fe8b
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/rewrite_search/frontend.lean
9c5398a8e1ad1229f8a839fadc9b9c9b34eb254e
[ "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,051
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Keeley Hoek, Scott Morrison -/ import tactic.rewrite_search.explain import tactic.rewrite_search.discovery import tactic.rewrite_search.search /-! # `rewrite_search`: solving goals by searching for a series of rewrites. `rewrite_search` is a tactic for solving equalities or iff statements by searching for a sequence of rewrite tactic applications. ## Algorithm sketch The fundamental data structure behind the search algorithm is a graph of expressions. Each vertex represents one expression, and an edge in the graph represents a way to rewrite one expression into another with a single application of a rewrite tactic. Thus, a path in the graph represents a way to rewrite one expression into another with multiple applications of a rewrite tactic. The graph starts out with two vertices, one for the left hand side of the equality, and one for the right hand side of the equality. The basic loop of the algorithm is to repeatedly add edges to the graph by taking vertices in the graph and applying a possible rewrite to them. Through this process, the graph is made up of two connected components; one component contains expressions that are equivalent to the left hand side, and one component contains expressions that are equivalent to the right hand side. The algorithm completes when we discover an edge that connects the two components, creating a path of rewrites that connects the left hand side and right hand side of the graph. For more detail, see Keeley's report at https://hoek.io/res/2018.s2.lean.report.pdf, although note that the edit distance mechanism described is currently not implemented, only plain breadth-first search. This algorithm is generally superior to one that only expands nodes starting from a single side, because it is replacing one tree of depth `2d` with two trees of depth `d`. This is a quadratic speedup for regular trees; our trees aren't regular but it's still probably a much better algorithm. We can only use this specific algorithm for rewrite-type tactics, though, not general sequences of tactics, because it relies on the fact that any rewrite can be reversed. ## File structure * `discovery.lean` contains the logic for figuring out which rewrite rules to consider. * `search.lean` contains the graph algorithms to find a successful sequence of tactics. * `explain.lean` generates concise Lean code to run a tactic, from the autogenerated sequence of tactics. * `frontend.lean` contains the user-facing interface to the `rewrite_search` tactics. * `types.lean` contains data structures shared across multiple of these components. -/ namespace tactic.interactive open lean.parser interactive interactive.types tactic.rewrite_search /-- Search for a chain of rewrites to prove an equation or iff statement. Collects rewrite rules, runs a graph search to find a chain of rewrites to prove the current target, and generates a string explanation for it. Takes an optional list of rewrite rules specified in the same way as the `rw` tactic accepts. -/ meta def rewrite_search (explain : parse $ optional (tk "?")) (rs : parse $ optional (list_of (rw_rule_p $ lean.parser.pexpr 0))) (cfg : config := {}) : tactic unit := do t ← tactic.target, if t.has_meta_var then tactic.fail "rewrite_search is not suitable for goals containing metavariables" else tactic.skip, implicit_rules ← collect_rules, explicit_rules ← (rs.get_or_else []).mmap (λ ⟨_, dir, pe⟩, do e ← to_expr' pe, return (e, dir)), let rules := implicit_rules ++ explicit_rules, g ← mk_graph cfg rules t, (_, proof, steps) ← g.find_proof, tactic.exact proof, if explain.is_some then explain_search_result cfg rules proof steps else skip add_tactic_doc { name := "rewrite_search", category := doc_category.tactic, decl_names := [`tactic.interactive.rewrite_search], tags := ["rewriting", "search"] } end tactic.interactive
62012f05a786c582de7fb560620ce5774d81a258
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/blast_cc5.lean
84c24309f59edfb6b46722433ed140e9eeefe284
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
587
lean
set_option blast.strategy "cc" example (a b c : Prop) : (a ↔ b) → ((a ∧ (c ∨ b)) ↔ (b ∧ (c ∨ a))) := by blast /- example (a b c : Prop) : (a ↔ b) → ((a ∧ (c ∨ (b ↔ a))) ↔ (b ∧ (c ∨ (a ↔ b)))) := by blast example (a₁ a₂ b₁ b₂ : Prop) : (a₁ ↔ b₁) → (a₂ ↔ b₂) → (a₁ ∧ a₂ ∧ a₁ ∧ a₂ ↔ b₁ ∧ b₂ ∧ b₁ ∧ b₂) := by blast definition lemma1 (a₁ a₂ b₁ b₂ : Prop) : (a₁ = b₁) → (a₂ ↔ b₂) → (a₁ ∧ a₂ ∧ a₁ ∧ a₂ ↔ b₁ ∧ b₂ ∧ b₁ ∧ b₂) := by blast print lemma1 -/
c093106131b5e392c8a467bf406e99fda31da29d
1fd908b06e3f9c1252cb2285ada1102623a67f72
/init/meta/rewrite.lean
3ed401a847b7523fb897df00bf8cd8aef95077ca
[ "Apache-2.0" ]
permissive
avigad/hott3
609a002849182721e7c7ae536d9f1e2956d6d4d3
f64750cd2de7a81e87d4828246d1369d59f16f43
refs/heads/master
1,629,027,243,322
1,510,946,717,000
1,510,946,717,000
103,570,461
0
0
null
1,505,415,620,000
1,505,415,620,000
null
UTF-8
Lean
false
false
3,636
lean
/- Copyright (c) 2017 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Jeremy Avigad -/ import ..path open tactic expr namespace hott -- accumulates a list of metavariables that should be instantiated by class inference, and returns it meta def instantiate_with_metas : expr → list expr → tactic (expr × list expr) | e insts := do t ← infer_type e >>= whnf, if ¬t.is_pi then return (e, list.reverse insts) else do x ← mk_meta_var t.binding_domain, instantiate_with_metas (e.app x) (if t.binding_info = binder_info.inst_implicit then x :: insts else insts) meta def mk_eq_inv (eqn : expr) : tactic expr := mk_app `hott.eq.inverse [eqn] meta def rewrite_core (eqn : expr) (tgt : expr) (cfg : rewrite_cfg) : tactic (expr × expr × expr) := do (eqn, insts) ← instantiate_with_metas eqn [], eqn ← if cfg.symm then mk_eq_inv eqn else return eqn, `(@hott.eq %%A %%lhs %%rhs) ← infer_type eqn | (do e ← pp eqn, fail $ to_fmt "rewrite_core: not an equation\n:" ++ e), abs ← kabstract tgt lhs cfg.md, when ¬abs.has_var $ (do lhs ← pp lhs, tgt ← pp tgt, fail $ to_fmt "rewrite_core: could not find pattern" ++ format.line ++ " " ++ lhs ++ format.line ++ to_fmt "in" ++ format.line ++ " " ++ tgt), when cfg.instances (do gs ← get_goals, set_goals insts, all_goals apply_instance <|> (fail $ to_fmt "rewrite_core: could not instantiate type classes"), set_goals gs), let motive := lam `x binder_info.default A abs, type_check motive <|> (do m ← pp motive, fail $ to_fmt "rewrite_core: motive does not type check\n" ++ m), return (abs.instantiate_var rhs, eqn, motive) meta def mk_eq_transport (motive eqn : expr) : tactic expr := mk_mapp `hott.eq.transport [none, motive, none, none, eqn] meta def rewrite_target (eqn : expr) (cfg : rewrite_cfg := {}) : tactic unit := do tgt ← target, (tgt', prf, motive) ← rewrite_core eqn tgt cfg, prf ← mk_eq_inv prf, prf ← mk_eq_transport motive prf, apply prf meta def rewrite_hyp (eqn : expr) (hyp : expr) (cfg : rewrite_cfg := {}) : tactic expr := do hyp_type ← infer_type hyp, (hyp_type', prf, motive) ← rewrite_core eqn hyp_type cfg, prf ← mk_eq_transport motive prf, hyp' ← assertv hyp.local_pp_name hyp_type' (prf.app hyp), try $ clear hyp, return hyp' end hott namespace tactic.interactive open interactive interactive.types -- TODO(gabriel): rewrite with equational lemmas private meta def rw_goal (cfg : rewrite_cfg) (rs : list rw_rule) : tactic unit := rs.mmap' $ λ r, do save_info r.pos, e ← to_expr' r.rule, hott.rewrite_target e {cfg with symm := r.symm} private meta def rw_hyp (cfg : rewrite_cfg) : list rw_rule → expr → tactic unit | [] hyp := skip | (r::rs) hyp := do save_info r.pos, e ← to_expr' r.rule, hyp ← hott.rewrite_hyp e hyp {cfg with symm := r.symm}, rw_hyp rs hyp private meta def rw_core (rs : parse rw_rules) (loca : parse location) (cfg : rewrite_cfg) : tactic unit := match loca with | loc.wildcard := loca.try_apply (rw_hyp cfg rs.rules) (rw_goal cfg rs.rules) | _ := loca.apply (rw_hyp cfg rs.rules) (rw_goal cfg rs.rules) end >> try (tactic.reflexivity transparency.semireducible) >> (returnopt rs.end_pos >>= save_info <|> skip) meta def rwr (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {}) : tactic unit := rw_core q l cfg /-- rwr followed by assumption -/ meta def rwra (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {}) : tactic unit := rw_core q l cfg >> try assumption end tactic.interactive
6665e6a08fcd38ffabb91457ab33686f944c72cc
c8af905dcd8475f414868d303b2eb0e9d3eb32f9
/src/data/cpi/concretion/congruence.lean
e0d4a028bd6b1d014ba400de3c9a3c4d6ed3d13c
[ "BSD-3-Clause" ]
permissive
continuouspi/lean-cpi
81480a13842d67ff5f3698643210d8ed5dd08de4
443bf2cb236feadc45a01387099c236ab2b78237
refs/heads/master
1,650,307,316,582
1,587,033,364,000
1,587,033,364,000
207,499,661
1
0
null
null
null
null
UTF-8
Lean
false
false
4,265
lean
import data.cpi.concretion.basic namespace cpi namespace concretion variables {ℍ : Type} {ω : context} [∀ Γ, setoid (species ℍ ω Γ)] /-- Structural congruence between concretions. -/ inductive equiv : ∀ {Γ} {b y}, concretion ℍ ω Γ b y → concretion ℍ ω Γ b y → Prop | refl {Γ} {b y} {F : concretion ℍ ω Γ b y} : equiv F F | trans {Γ} {b y} {F G H : concretion ℍ ω Γ b y} : equiv F G → equiv G H → equiv F H | symm {Γ} {b y} {F G : concretion ℍ ω Γ b y} : equiv F G → equiv G F | ξ_parallel₁ {Γ} {b y} {F F' : concretion ℍ ω Γ b y} {A : species ℍ ω Γ} : equiv F F' → equiv (F |₁ A) (F' |₁ A) | ξ_parallel₂ {Γ} {b y} {F F' : concretion ℍ ω Γ b y} {A : species ℍ ω Γ} : equiv F F' → equiv (A |₂ F) (A |₂ F') | ξ_restriction {Γ} {b y} (M : affinity ℍ) {F F' : concretion ℍ ω (context.extend M.arity Γ) b y} : equiv F F' → equiv (ν'(M) F) (ν'(M) F') -- Parallel is a commutative monoid | parallel_nil {Γ} {b y} {F : concretion ℍ ω Γ b y} : equiv (F |₁ species.nil) F | parallel_symm {Γ} {b y} {F : concretion ℍ ω Γ b y} {A : species ℍ ω Γ} : equiv (F |₁ A) (A |₂ F) | parallel_assoc₁ {Γ} {b y} {F : concretion ℍ ω Γ b y} {A B : species ℍ ω Γ} : equiv ((F |₁ A) |₁ B) (F |₁ (A |ₛ B)) | parallel_assoc₂ {Γ} {b y} {F : concretion ℍ ω Γ b y} {A B : species ℍ ω Γ} : equiv ((A |₂ F) |₁ B) (A |₂ (F |₁ B)) -- Projections for species into parallel/apply | ξ_parallel {Γ} {b y} {F : concretion ℍ ω Γ b y} {A B : species ℍ ω Γ} : A ≈ B → equiv (F |₁ A) (F |₁ B) | ξ_apply {Γ} {b y} {bs : vector (name Γ) b} {A B : species ℍ ω (context.extend y Γ)} : A ≈ B → equiv (#(bs; y) A) (#(bs; y) B) -- Standard ν rules | ν_parallel₁ {Γ} {b y} (M : affinity ℍ) {A : species ℍ ω Γ} {F : concretion ℍ ω (context.extend M.arity Γ) b y} : equiv (ν'(M)(species.rename name.extend A |₂ F)) (A |₂ ν'(M) F) | ν_parallel₂ {Γ} {b y} (M : affinity ℍ) {A : species ℍ ω (context.extend M.arity Γ)} {F : concretion ℍ ω Γ b y} : equiv (ν'(M)(concretion.rename name.extend F |₁ A)) (F |₁ (ν(M) A)) | ν_drop {Γ} {b y} (M : affinity ℍ) {F : concretion ℍ ω Γ b y} : equiv (ν'(M) rename name.extend F) F | ν_swap {Γ} {b y} (M N : affinity ℍ) {F : concretion ℍ ω (context.extend N.arity (context.extend M.arity Γ)) b y} : equiv (ν'(M)ν'(N) F) (ν'(N)ν'(M) rename name.swap F) | apply_parallel {Γ} {b y} {bs : vector (name Γ) b} {A : species ℍ ω Γ} {B : species ℍ ω (context.extend y Γ)} : equiv (#(bs; y) (species.rename name.extend A |ₛ B)) (A |₂ #(bs; y) B) instance {Γ} {b y} : is_equiv (concretion ℍ ω Γ b y) equiv := { refl := @equiv.refl ℍ _ _ Γ b y, symm := @equiv.symm ℍ _ _ Γ b y, trans := @equiv.trans ℍ _ _ Γ b y } instance {Γ} {b y} : is_refl (concretion ℍ ω Γ b y) equiv := ⟨ λ _, equiv.refl ⟩ namespace equiv /-- The setoid of species under structural congruence. Can be brought into scope with the "congruence" locale. -/ def setoid {Γ} {b y} : setoid (concretion ℍ ω Γ b y) := ⟨ equiv, ⟨ @refl ℍ _ _ Γ b y, @symm ℍ _ _ Γ b y, @trans ℍ _ _ Γ b y ⟩ ⟩ localized "attribute [instance] cpi.concretion.equiv.setoid" in congruence protected lemma ξ_parallel' {Γ} {b y} {F : concretion ℍ ω Γ b y} {A A' : species ℍ ω Γ} (eq : A ≈ A') : (A |₂ F) ≈ (A' |₂ F) := calc (A |₂ F) ≈ (F |₁ A) : symm parallel_symm ... ≈ (F |₁ A') : ξ_parallel eq ... ≈ (A' |₂ F) : parallel_symm protected lemma parallel_assoc₃ {Γ} {b y : ℕ} {A B : species ℍ ω Γ} {F : concretion ℍ ω Γ b y} : ((A |ₛ B) |₂ F) ≈ (A |₂ B |₂ F) := calc ((A |ₛ B) |₂ F) ≈ (F |₁ (A |ₛ B)) : symm parallel_symm ... ≈ ((F |₁ A) |₁ B) : symm parallel_assoc₁ ... ≈ ((A |₂ F) |₁ B) : ξ_parallel₁ parallel_symm ... ≈ (A |₂ F |₁ B) : parallel_assoc₂ ... ≈ (A |₂ B |₂ F) : ξ_parallel₂ parallel_symm end equiv end concretion end cpi #lint-
9652b019f2ecca9eed95d691ac9948f56c9b63b5
df561f413cfe0a88b1056655515399c546ff32a5
/2-addition-world/l3.lean
a1e1244046f8c8ed433291a79e42f5acdb764e78
[]
no_license
nicholaspun/natural-number-game-solutions
31d5158415c6f582694680044c5c6469032c2a06
1e2aed86d2e76a3f4a275c6d99e795ad30cf6df0
refs/heads/main
1,675,123,625,012
1,607,633,548,000
1,607,633,548,000
318,933,860
3
1
null
null
null
null
UTF-8
Lean
false
false
164
lean
lemma succ_add (a b : mynat) : succ a + b = succ (a + b) := begin induction b with k Pk, rw add_zero, rw add_zero, refl, rw add_succ, rw add_succ, rw Pk, refl, end
ab47c98c1d915deb8329962d3d1e1e18519f8ea4
d53312f14e4be505a8abcc1969b73308b038f020
/06-formalizacija-dokazov/lambda.lean
bd980ad2a34499a9b4f74227615cea5f54e0be5d
[]
no_license
lunar-starlight/teorija-programskih-jezikov
18ccdfaa9200c10c2b1ec14624419532dd671d25
bfdf69114a6b13b1ae5735e8749b543f722e5965
refs/heads/master
1,667,393,466,506
1,577,651,158,000
1,577,651,158,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,194
lean
inductive ty : Type | unit : ty | bool : ty | arrow : ty -> ty -> ty def ident := string inductive tm : Type | var : ident -> tm | unit : tm | true : tm | false : tm | app : tm -> tm -> tm | lam : ident -> tm -> tm | if_then_else : tm -> tm -> tm -> tm def subst : ident -> tm -> tm -> tm | x e (tm.var y) := if x = y then e else tm.var y | x e tm.unit := tm.unit | x e tm.true := tm.true | x e tm.false := tm.false | x e (tm.app e1 e2) := tm.app (subst x e e1) (subst x e e2) | x e (tm.lam y e') := if x = y then tm.lam y e' else tm.lam y (subst x e e') | x e (tm.if_then_else e' e1 e2) := tm.if_then_else (subst x e e') (subst x e e1) (subst x e e2) inductive value : tm -> Prop | unit : value tm.unit | true : value tm.true | false : value tm.false | lam {x e} : value (tm.lam x e) inductive step : tm -> tm -> Prop | app1 {e1 e1' e2} : step e1 e1' -> step (tm.app e1 e2) (tm.app e1' e2) | app2 {v1 e2 e2'} : value v1 -> step e2 e2' -> step (tm.app v1 e2) (tm.app v1 e2') | app_beta {x e1 v2} : value v2 -> step (tm.app (tm.lam x e1) v2) (subst x v2 e1) | if_then_else {e e' e1 e2} : step e e' -> step (tm.if_then_else e e1 e2) (tm.if_then_else e' e1 e2) | if_true {e1 e2} : step (tm.if_then_else tm.true e1 e2) e1 | if_false {e1 e2} : step (tm.if_then_else tm.false e1 e2) e2 inductive ctx : Type | nil : ctx | cons : ctx -> ident -> ty -> ctx inductive lookup : ident -> ctx -> ty -> Prop | here {Γ x A} : lookup x (ctx.cons Γ x A) A | there {x y A B Γ} : x ≠ y -> lookup x Γ A -> lookup x (ctx.cons Γ y B) A inductive of : ctx -> tm -> ty -> Prop | var {x Γ A} : lookup x Γ A -> of Γ (tm.var x) A | unit {Γ} : of Γ tm.unit ty.unit | true {Γ} : of Γ tm.true ty.bool | false {Γ} : of Γ tm.false ty.bool | app {Γ e1 e2 A B} : of Γ e1 (ty.arrow A B) -> of Γ e2 A -> of Γ (tm.app e1 e2) B | lam {Γ x e A B} : of (ctx.cons Γ x A) e B -> of Γ (tm.lam x e) (ty.arrow A B) | if_then_else {Γ e e1 e2 A} : of Γ e ty.bool -> of Γ e1 A -> of Γ e2 A -> of Γ (tm.if_then_else e e1 e2) A theorem substitution {Γ x A e e' A'} : of Γ e A -> of (ctx.cons Γ x A) e' A' -> of Γ (subst x e e') A' := begin intros H, generalize ctx_cons : (ctx.cons Γ x A) = Γ', intros H', induction H', repeat {simp}, case of.var { rewrite <- ctx_cons at H'_a, unfold subst, cases H'_a, case lookup.here { simp, assumption }, case lookup.there { by_cases (x = H'_x), have H := (ne.symm H'_a_a), contradiction, simp [h], apply of.var, assumption } }, case of.unit { apply of.unit }, case of.true { apply of.true }, case of.false { apply of.false }, case of.app { apply of.app, apply H'_ih_a ctx_cons, apply H'_ih_a_1 ctx_cons }, case of.if_then_else { apply of.if_then_else, apply H'_ih_a ctx_cons, apply H'_ih_a_1 ctx_cons, apply H'_ih_a_2 ctx_cons }, case of.lam { unfold subst, by_cases (x = H'_x), simp [h], apply of.lam, sorry, simp [h], apply of.lam, sorry }, end theorem preservation {e e'} : step e e' -> forall {Γ A}, of Γ e A -> of Γ e' A := begin intros Hstep, induction Hstep, repeat {intros Γ A Hof}, case step.app_beta { cases Hof, cases Hof_a, apply substitution Hof_a_1 Hof_a_a }, case step.app1 { cases Hof, apply of.app, apply Hstep_ih Hof_a, apply Hof_a_1 }, case step.app2 { cases Hof, apply of.app, apply Hof_a, apply Hstep_ih Hof_a_1 }, case step.if_then_else { cases Hof, apply of.if_then_else, apply Hstep_ih Hof_a, apply Hof_a_1, apply Hof_a_2 }, case step.if_true { cases Hof, apply Hof_a_1 }, case step.if_false { cases Hof, apply Hof_a_2 } end theorem progress {e A} : of ctx.nil e A -> (value e) ∨ (exists e', step e e') := begin generalize empty : ctx.nil = Γ, intros H, induction H, case of.var { rewrite ←empty at H_a, cases H_a }, case of.unit { left, exact value.unit }, case of.app { cases H_ih_a empty, case or.inl { cases H_a, case of.var {rw ←empty at H_a_a, cases H_a_a}, case of.app {cases h}, case of.lam { cases H_ih_a_1 empty, right, existsi (subst H_a_x H_e2 H_a_e), apply step.app_beta, assumption, right, cases h_1, existsi (tm.app (tm.lam H_a_x H_a_e) h_1_w), eapply step.app2, exact value.lam, assumption }, case of.if_then_else { cases h } }, case or.inr { cases h with e H_step, right, existsi (tm.app e H_e2), apply step.app1, assumption } }, case of.lam { left, exact value.lam }, case of.true { left, exact value.true }, case of.false { left, exact value.false }, case of.if_then_else { cases H_ih_a empty, case or.inl { cases H_a, case of.var { rw ←empty at H_a_a, cases H_a_a }, case of.true { right, existsi H_e1, exact step.if_true }, case of.false { right, existsi H_e2, exact step.if_false }, cases h, cases h }, case or.inr { cases h, right, existsi (tm.if_then_else h_w H_e1 H_e2), exact (step.if_then_else h_h), } } end
66a86908027fd6e6f790abc2b5c9e7bc6bff253d
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/run/optParam.lean
abcfa2dec19957040847c65dc78242f74c4723ed
[ "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
327
lean
def p (x : Nat := 0) : Nat × Nat := (x, x) theorem ex1 : p.1 = 0 := rfl theorem ex2 : (p (x := 1) |>.2) = 1 := rfl def c {α : Type} [Inhabited α] : α × α := (arbitrary, arbitrary) theorem ex3 {α} [Inhabited α] : c.1 = arbitrary (α := α) := rfl theorem ex4 {α} [Inhabited α] : c.2 = arbitrary (α := α) := rfl
15c03e03cdb9888df2021c9314728fe0a695a257
48eee836fdb5c613d9a20741c17db44c8e12e61c
/src/algebra/identities/basic.lean
2bc7a4ad3e379444619955ac99f3ec6d7b16e056
[ "Apache-2.0" ]
permissive
fgdorais/lean-universal
06430443a4abe51e303e602684c2977d1f5c0834
9259b0f7fb3aa83a9e0a7a3eaa44c262e42cc9b1
refs/heads/master
1,592,479,744,136
1,589,473,399,000
1,589,473,399,000
196,287,552
1
1
null
null
null
null
UTF-8
Lean
false
false
9,270
lean
-- Copyright © 2019 François G. Dorais. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. import util.identities variables {α : Sort*} {β : Sort*} {γ : Sort*} {δ : Sort*} {ε : Sort*} {η : Sort*} namespace algebra.identity @[identity] protected abbreviation op_commutative (op : α → α → α) : Prop := ∀ x y, op x y = op y x @[identity] protected abbreviation op_symmetric (op : α → α → β) : Prop := ∀ x y, op x y = op y x @[identity] protected abbreviation op_opposite (op : α → β → γ) (op' : out_param $ β → α → γ) : Prop := ∀ x y, op x y = op' y x @[identity] protected abbreviation op_left_commutative (op : α → β → β) : Prop := ∀ x y z, op x (op y z) = op y (op x z) @[identity] protected abbreviation op_right_commutative (op : α → β → α) : Prop := ∀ x y z, op (op x y) z = op (op x z) y @[identity] protected abbreviation op_associative (op : α → α → α) : Prop := ∀ x y z, op (op x y) z = op x (op y z) @[identity] protected abbreviation op_left_compatible (op : α → β → β) (op' : out_param $ α → α → α) : Prop := ∀ x y z, op (op' x y) z = op x (op y z) @[identity] protected abbreviation op_right_compatible (op : α → β → α) (op' : out_param $ β → β → β) : Prop := ∀ x y z, op (op x y) z = op x (op' y z) @[identity] protected abbreviation op_compatibility (op₁ : α → β → γ) (op₂ : δ → ε → α) (op₃ : δ → η → γ) (op₄ : ε → β → η) : Prop := ∀ x y z, op₁ (op₂ x y) z = op₃ x (op₄ y z) @[identity] protected abbreviation op_left_identity (op : α → β → β) (ct : out_param $ α) : Prop := ∀ x, op ct x = x @[identity] protected abbreviation op_right_identity (op : α → β → α) (ct : out_param $ β) : Prop := ∀ x, op x ct = x @[identity] protected abbreviation op_left_inverse (op : α → β → γ) (fn : out_param $ β → α) (ct : out_param $ γ) : Prop := ∀ x, op (fn x) x = ct @[identity] protected abbreviation op_right_inverse (op : α → β → γ) (fn : out_param $ α → β) (ct : out_param $ γ) : Prop := ∀ x, op x (fn x) = ct @[identity] protected abbreviation op_left_division (op : α → β → γ) (op' : out_param $ α → γ → β) : Prop := ∀ x y, op x (op' x y) = y @[identity] protected abbreviation op_right_division (op : α → β → γ) (op' : out_param $ γ → β → α) : Prop := ∀ x y, op (op' y x) x = y @[identity] protected abbreviation op_left_cancellative (op : α → β → γ) : Prop := ∀ {{x y z}}, op x y = op x z → y = z @[identity] protected abbreviation op_right_cancellative (op : α → β → γ) : Prop := ∀ {{x y z}}, op x y = op z y → x = z @[identity] protected abbreviation op_idempotent (op : α → α → α) : Prop := ∀ x, op x x = x @[identity] protected abbreviation op_left_absorptive (op₁ : α → β → β) (op₂ : γ → β → α) : Prop := ∀ x y, op₁ (op₂ x y) y = y @[identity] protected abbreviation op_right_absorptive (op₁ : α → β → α) (op₂ : α → γ → β) : Prop := ∀ x y, op₁ x (op₂ x y) = x @[identity] protected abbreviation op_op_left_cancellative (op₁ : α → β → γ) (op₂ : α → β → δ) : Prop := ∀ {{x y z}}, op₁ x y = op₁ x z → op₂ x y = op₂ x z → y = z @[identity] protected abbreviation op_op_right_cancellative (op₁ : α → β → γ) (op₂ : α → β → δ) : Prop := ∀ (x y z), op₁ x y = op₁ z y → op₂ x y = op₂ z y → x = z @[identity] protected abbreviation fn_fixpoint (fn : α → α) (ct : out_param $ α) : Prop := fn ct = ct @[identity] protected abbreviation fn_idempotent (fn : α → α) : Prop := ∀ x, fn (fn x) = fn x @[identity] protected abbreviation fn_injective (fn : α → β) : Prop := ∀ {{x y}}, fn x = fn y → x = y @[identity] protected abbreviation fn_fn_commutative (fn_1 : α → α) (fn_2 : α → α) : Prop := ∀ x, fn_1 (fn_2 x) = fn_2 (fn_1 x) @[identity] protected abbreviation fn_fn_inverse (fn_1 : α → β) (fn_2 : β → α) : Prop := ∀ x, fn_1 (fn_2 x) = x @[identity] protected abbreviation fn_fn_inverse' (fn_1 : α → β) (fn_2 : β → α) : Prop := ∀ x y, fn_1 x = y → fn_2 y = x @[identity] protected abbreviation fn_involutive (fn : α → α) : Prop := ∀ x, fn (fn x) = x @[identity] protected abbreviation op_left_fixpoint (op : α → β → α) (ct : out_param $ α) : Prop := ∀ x, op ct x = ct @[identity] protected abbreviation op_right_fixpoint (op : α → β → β) (ct : out_param $ β) : Prop := ∀ x, op x ct = ct @[identity] protected abbreviation fn_ct_homomorphism (fn : α → β) (ct_1 : out_param $ α) (ct_2 : out_param $ β) : Prop := fn ct_1 = ct_2 @[identity] protected abbreviation fn_fn_homomorphism (fn : α → β) (fn_1 : out_param $ α → α) (fn_2 : out_param $ β → β) : Prop := ∀ x, fn (fn_1 x) = fn_2 (fn x) @[identity] protected abbreviation fn_op_homomorphism (fn : α → β) (op_1 : out_param $ α → α → α) (op_2 : out_param $ β → β → β) : Prop := ∀ x y, fn (op_1 x y) = op_2 (fn x) (fn y) @[identity] protected abbreviation fn_op_antimorphism (fn : α → β) (op_1 : out_param $ α → α → α) (op_2 : out_param $ β → β → β) : Prop := ∀ x y, fn (op_1 x y) = op_2 (fn y) (fn x) @[identity] protected abbreviation op_left_ct_homomorphism (op : α → β → γ) (ct_1 : out_param $ α) (ct_2 : out_param $ γ) : Prop := ∀ x, op ct_1 x = ct_2 @[identity] protected abbreviation op_right_ct_homomorphism (op : α → β → γ) (ct_1 : out_param $ β) (ct_2 : out_param $ γ) : Prop := ∀ x, op x ct_1 = ct_2 @[identity] protected abbreviation op_left_fn_homomorphism (op : α → β → γ) (fn_1 : out_param $ α → α) (fn_2 : out_param $ γ → γ) : Prop := ∀ x y, op (fn_1 x) y = fn_2 (op x y) @[identity] protected abbreviation op_right_fn_homomorphism (op : α → β → γ) (fn_1 : out_param $ β → β) (fn_2 : out_param $ γ → γ) : Prop := ∀ x y, op x (fn_1 y) = fn_2 (op x y) @[identity] protected abbreviation op_left_op_homomorphism (op : α → β → γ) (op_1 : out_param $ α → α → α) (op_2 : out_param $ γ → γ → γ) : Prop := ∀ x y z, op (op_1 x y) z = op_2 (op x z) (op y z) @[identity] protected abbreviation op_right_op_homomorphism (op : α → β → γ) (op_1 : out_param $ β → β → β) (op_2 : out_param $ γ → γ → γ) : Prop := ∀ x y z, op x (op_1 y z) = op_2 (op x y) (op x z) @[identity] protected abbreviation op_left_distributive (op_1 : α → β → α) (op_2 : out_param $ α → α → α) : Prop := ∀ x y z, op_1 (op_2 x y) z = op_2 (op_1 x z) (op_1 y z) @[identity] protected abbreviation op_right_distributive (op_1 : α → β → β) (op_2 : out_param $ β → β → β) : Prop := ∀ x y z, op_1 x (op_2 y z) = op_2 (op_1 x y) (op_1 x z) end algebra.identity namespace algebra.class set_option default_priority 0 instance op_left_compatible_of_op_compatibility (op : α → β → β) (op' : α → α → α) [op_compatibility op op' op op] : op_left_compatible op op' := op_left_compatible.of_pattern _ _ instance op_right_compatible_of_op_compatibility (op : α → β → α) (op' : β → β → β) [op_compatibility op op op op'] : op_right_compatible op op' := op_right_compatible.of_pattern _ _ instance op_associative_of_op_left_compatible (op : α → α → α) [op_left_compatible op op] : op_associative op := op_associative.of_pattern _ instance op_associative_of_op_right_compatible (op : α → α → α) [op_right_compatible op op] : op_associative op := op_associative.of_pattern _ instance op_symmetric_of_op_opposite (op : α → α → β) [op_opposite op op] : op_symmetric op := op_symmetric.of_pattern _ instance op_commutative_of_op_symmetric (op : α → α → α) [op_symmetric op] : op_commutative op := op_commutative.of_pattern _ instance fn_fixpoint_of_fn_ct_homomorphism (fn : α → α) (ct : α) [fn_ct_homomorphism fn ct ct] : fn_fixpoint fn ct := fn_fixpoint.of_pattern _ _ instance fn_fn_commutative_of_fn_fn_homomorphism (fn_1 : α → α) (fn_2 : α → α) [fn_fn_homomorphism fn_1 fn_2 fn_2] : fn_fn_commutative fn_1 fn_2 := fn_fn_commutative.of_pattern _ _ instance fn_involutive_of_fn_fn_inverse (fn : α → α) [fn_fn_inverse fn fn] : fn_involutive fn := fn_involutive.of_pattern _ instance op_left_fixpoint_of_op_left_ct_homomorphism_of_op_left_fixpoint (op : α → β → α) (ct : α) [op_left_ct_homomorphism op ct ct] : op_left_fixpoint op ct := op_left_fixpoint.of_pattern _ _ instance op_right_fixpoint_of_op_right_ct_homomorphism_of_op_right_fixpoint (op : α → β → β) (ct : β) [op_right_ct_homomorphism op ct ct] : op_right_fixpoint op ct := op_right_fixpoint.of_pattern _ _ instance op_left_distributive_of_op_left_op_homomorphism (op_1 : α → β → α) (op_2 : α → α → α) [op_left_op_homomorphism op_1 op_2 op_2] : op_left_distributive op_1 op_2 := op_left_distributive.of_pattern _ _ instance op_right_distributive_of_op_right_op_homomorphism (op_1 : α → β → β) (op_2 : β → β → β) [op_right_op_homomorphism op_1 op_2 op_2] : op_right_distributive op_1 op_2 := op_right_distributive.of_pattern _ _ end algebra.class
9be659849b46056969300c0395defe8ff2e8d49d
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/measure_theory/integral/interval_integral.lean
e33e59b0144fc012168e5f95d9df6234e47644f7
[ "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
62,254
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov, Patrick Massot, Sébastien Gouëzel -/ import data.set.intervals.disjoint import measure_theory.integral.set_integral import measure_theory.measure.lebesgue.basic /-! # Integral over an interval > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. 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`. ## 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 `set.uIoc a b = set.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 `set.uIoc a b = set.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 `set.Ioo` and `set.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 `μ`. ## Tags integral -/ noncomputable theory open topological_space (second_countable_topology) open measure_theory set classical filter function open_locale classical topology filter ennreal big_operators interval nnreal variables {ι 𝕜 E F A : Type*} [normed_add_comm_group E] /-! ### Integrability on 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 : ℝ) : Prop := integrable_on f (Ioc a b) μ ∧ integrable_on f (Ioc b a) μ section variables {f : ℝ → E} {a b : ℝ} {μ : measure ℝ} /-- A function is interval integrable with respect to a given measure `μ` on `a..b` if and only if it is integrable on `uIoc a b` with respect to `μ`. This is an equivalent definition of `interval_integrable`. -/ lemma interval_integrable_iff : interval_integrable f μ a b ↔ integrable_on f (Ι a b) μ := by rw [uIoc_eq_union, integrable_on_union, interval_integrable] /-- If a function is interval integrable with respect to a given measure `μ` on `a..b` then it is integrable on `uIoc a b` with respect to `μ`. -/ lemma interval_integrable.def (h : interval_integrable f μ a b) : integrable_on f (Ι a b) μ := interval_integrable_iff.mp h lemma interval_integrable_iff_integrable_Ioc_of_le (hab : a ≤ b) : interval_integrable f μ a b ↔ integrable_on f (Ioc a b) μ := by rw [interval_integrable_iff, uIoc_of_le hab] lemma interval_integrable_iff' [has_no_atoms μ] : interval_integrable f μ a b ↔ integrable_on f (uIcc a b) μ := by rw [interval_integrable_iff, ←Icc_min_max, uIoc, integrable_on_Icc_iff_integrable_on_Ioc] lemma interval_integrable_iff_integrable_Icc_of_le {f : ℝ → E} {a b : ℝ} (hab : a ≤ b) {μ : measure ℝ} [has_no_atoms μ] : interval_integrable f μ a b ↔ integrable_on f (Icc a b) μ := by rw [interval_integrable_iff_integrable_Ioc_of_le hab, integrable_on_Icc_iff_integrable_on_Ioc] /-- If a function is integrable with respect to a given measure `μ` then it is interval integrable with respect to `μ` on `uIcc a b`. -/ lemma measure_theory.integrable.interval_integrable (hf : integrable f μ) : interval_integrable f μ a b := ⟨hf.integrable_on, hf.integrable_on⟩ lemma measure_theory.integrable_on.interval_integrable (hf : integrable_on f [a, b] μ) : interval_integrable f μ a b := ⟨measure_theory.integrable_on.mono_set hf (Ioc_subset_Icc_self.trans Icc_subset_uIcc), measure_theory.integrable_on.mono_set hf (Ioc_subset_Icc_self.trans Icc_subset_uIcc')⟩ lemma interval_integrable_const_iff {c : E} : interval_integrable (λ _, c) μ a b ↔ c = 0 ∨ μ (Ι a b) < ∞ := by simp only [interval_integrable_iff, integrable_on_const] @[simp] lemma interval_integrable_const [is_locally_finite_measure μ] {c : E} : interval_integrable (λ _, c) μ a b := interval_integrable_const_iff.2 $ or.inr measure_Ioc_lt_top end namespace interval_integrable section variables {f : ℝ → E} {a b c d : ℝ} {μ ν : 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 {a b c : ℝ} (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 trans_iterate_Ico {a : ℕ → ℝ} {m n : ℕ} (hmn : m ≤ n) (hint : ∀ k ∈ Ico m n, interval_integrable f μ (a k) (a $ k+1)) : interval_integrable f μ (a m) (a n) := begin revert hint, refine nat.le_induction _ _ n hmn, { simp }, { assume p hp IH h, exact (IH (λ k hk, h k (Ico_subset_Ico_right p.le_succ hk))).trans (h p (by simp [hp])) } end lemma trans_iterate {a : ℕ → ℝ} {n : ℕ} (hint : ∀ k < n, interval_integrable f μ (a k) (a $ k+1)) : interval_integrable f μ (a 0) (a n) := trans_iterate_Ico bot_le (λ k hk, hint k hk.2) lemma neg (h : interval_integrable f μ a b) : interval_integrable (-f) μ a b := ⟨h.1.neg, h.2.neg⟩ lemma norm (h : interval_integrable f μ a b) : interval_integrable (λ x, ‖f x‖) μ a b := ⟨h.1.norm, h.2.norm⟩ lemma interval_integrable_norm_iff {f : ℝ → E} {μ : measure ℝ} {a b : ℝ} (hf : ae_strongly_measurable f (μ.restrict (Ι a b))) : interval_integrable (λ t, ‖f t‖) μ a b ↔ interval_integrable f μ a b := by { simp_rw [interval_integrable_iff, integrable_on], exact integrable_norm_iff hf } lemma abs {f : ℝ → ℝ} (h : interval_integrable f μ a b) : interval_integrable (λ x, |f x|) μ a b := h.norm lemma mono (hf : interval_integrable f ν a b) (h1 : [c, d] ⊆ [a, b]) (h2 : μ ≤ ν) : interval_integrable f μ c d := interval_integrable_iff.mpr $ hf.def.mono (uIoc_subset_uIoc_of_uIcc_subset_uIcc h1) h2 lemma mono_measure (hf : interval_integrable f ν a b) (h : μ ≤ ν) : interval_integrable f μ a b := hf.mono rfl.subset h lemma mono_set (hf : interval_integrable f μ a b) (h : [c, d] ⊆ [a, b]) : interval_integrable f μ c d := hf.mono h rfl.le lemma mono_set_ae (hf : interval_integrable f μ a b) (h : Ι c d ≤ᵐ[μ] Ι a b) : interval_integrable f μ c d := interval_integrable_iff.mpr $ hf.def.mono_set_ae h lemma mono_set' (hf : interval_integrable f μ a b) (hsub : Ι c d ⊆ Ι a b) : interval_integrable f μ c d := hf.mono_set_ae $ eventually_of_forall hsub lemma mono_fun [normed_add_comm_group F] {g : ℝ → F} (hf : interval_integrable f μ a b) (hgm : ae_strongly_measurable g (μ.restrict (Ι a b))) (hle : (λ x, ‖g x‖) ≤ᵐ[μ.restrict (Ι a b)] (λ x, ‖f x‖)) : interval_integrable g μ a b := interval_integrable_iff.2 $ hf.def.integrable.mono hgm hle lemma mono_fun' {g : ℝ → ℝ} (hg : interval_integrable g μ a b) (hfm : ae_strongly_measurable f (μ.restrict (Ι a b))) (hle : (λ x, ‖f x‖) ≤ᵐ[μ.restrict (Ι a b)] g) : interval_integrable f μ a b := interval_integrable_iff.2 $ hg.def.integrable.mono' hfm hle protected lemma ae_strongly_measurable (h : interval_integrable f μ a b) : ae_strongly_measurable f (μ.restrict (Ioc a b)):= h.1.ae_strongly_measurable protected lemma ae_strongly_measurable' (h : interval_integrable f μ a b) : ae_strongly_measurable f (μ.restrict (Ioc b a)):= h.2.ae_strongly_measurable end variables [normed_ring A] {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⟩ @[simp] lemma add (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) : interval_integrable (λ x, f x + g x) μ a b := ⟨hf.1.add hg.1, hf.2.add hg.2⟩ @[simp] lemma sub (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) : interval_integrable (λ x, f x - g x) μ a b := ⟨hf.1.sub hg.1, hf.2.sub hg.2⟩ lemma sum (s : finset ι) {f : ι → ℝ → E} (h : ∀ i ∈ s, interval_integrable (f i) μ a b) : interval_integrable (∑ i in s, f i) μ a b := ⟨integrable_finset_sum' s (λ i hi, (h i hi).1), integrable_finset_sum' s (λ i hi, (h i hi).2)⟩ lemma mul_continuous_on {f g : ℝ → A} (hf : interval_integrable f μ a b) (hg : continuous_on g [a, b]) : interval_integrable (λ x, f x * g x) μ a b := begin rw interval_integrable_iff at hf ⊢, exact hf.mul_continuous_on_of_subset hg measurable_set_Ioc is_compact_uIcc Ioc_subset_Icc_self end lemma continuous_on_mul {f g : ℝ → A} (hf : interval_integrable f μ a b) (hg : continuous_on g [a, b]) : interval_integrable (λ x, g x * f x) μ a b := begin rw interval_integrable_iff at hf ⊢, exact hf.continuous_on_mul_of_subset hg is_compact_uIcc measurable_set_Ioc Ioc_subset_Icc_self end @[simp] lemma const_mul {f : ℝ → A} (hf : interval_integrable f μ a b) (c : A) : interval_integrable (λ x, c * f x) μ a b := hf.continuous_on_mul continuous_on_const @[simp] lemma mul_const {f : ℝ → A} (hf : interval_integrable f μ a b) (c : A) : interval_integrable (λ x, f x * c) μ a b := hf.mul_continuous_on continuous_on_const @[simp] lemma div_const {𝕜 : Type*} {f : ℝ → 𝕜} [normed_field 𝕜] (h : interval_integrable f μ a b) (c : 𝕜) : interval_integrable (λ x, f x / c) μ a b := by simpa only [div_eq_mul_inv] using mul_const h c⁻¹ lemma comp_mul_left (hf : interval_integrable f volume a b) (c : ℝ) : interval_integrable (λ x, f (c * x)) volume (a / c) (b / c) := begin rcases eq_or_ne c 0 with hc|hc, { rw hc, simp }, rw interval_integrable_iff' at hf ⊢, have A : measurable_embedding (λ x, x * c⁻¹) := (homeomorph.mul_right₀ _ (inv_ne_zero hc)).closed_embedding.measurable_embedding, rw [←real.smul_map_volume_mul_right (inv_ne_zero hc), integrable_on, measure.restrict_smul, integrable_smul_measure (by simpa : ennreal.of_real (|c⁻¹|) ≠ 0) ennreal.of_real_ne_top, ←integrable_on, measurable_embedding.integrable_on_map_iff A], convert hf using 1, { ext, simp only [comp_app], congr' 1, field_simp, ring }, { rw preimage_mul_const_uIcc (inv_ne_zero hc), field_simp [hc] }, end lemma comp_mul_right (hf : interval_integrable f volume a b) (c : ℝ) : interval_integrable (λ x, f (x * c)) volume (a / c) (b / c) := by simpa only [mul_comm] using comp_mul_left hf c lemma comp_add_right (hf : interval_integrable f volume a b) (c : ℝ) : interval_integrable (λ x, f (x + c)) volume (a - c) (b - c) := begin wlog h : a ≤ b, { exact interval_integrable.symm (this hf.symm _ (le_of_not_le h)) }, rw interval_integrable_iff' at hf ⊢, have A : measurable_embedding (λ x, x + c) := (homeomorph.add_right c).closed_embedding.measurable_embedding, have Am : measure.map (λ x, x + c) volume = volume, { exact is_add_left_invariant.is_add_right_invariant.map_add_right_eq_self _ }, rw ←Am at hf, convert (measurable_embedding.integrable_on_map_iff A).mp hf, rw preimage_add_const_uIcc, end lemma comp_add_left (hf : interval_integrable f volume a b) (c : ℝ) : interval_integrable (λ x, f (c + x)) volume (a - c) (b - c) := by simpa only [add_comm] using interval_integrable.comp_add_right hf c lemma comp_sub_right (hf : interval_integrable f volume a b) (c : ℝ) : interval_integrable (λ x, f (x - c)) volume (a + c) (b + c) := by simpa only [sub_neg_eq_add] using interval_integrable.comp_add_right hf (-c) lemma iff_comp_neg : interval_integrable f volume a b ↔ interval_integrable (λ x, f (-x)) volume (-a) (-b) := begin split, all_goals { intro hf, convert comp_mul_left hf (-1), simp, field_simp, field_simp }, end lemma comp_sub_left (hf : interval_integrable f volume a b) (c : ℝ) : interval_integrable (λ x, f (c - x)) volume (c - a) (c - b) := by simpa only [neg_sub, ←sub_eq_add_neg] using iff_comp_neg.mp (hf.comp_add_left c) end interval_integrable section variables {μ : measure ℝ} [is_locally_finite_measure μ] lemma continuous_on.interval_integrable {u : ℝ → E} {a b : ℝ} (hu : continuous_on u (uIcc a b)) : interval_integrable u μ a b := (continuous_on.integrable_on_Icc hu).interval_integrable lemma continuous_on.interval_integrable_of_Icc {u : ℝ → E} {a b : ℝ} (h : a ≤ b) (hu : continuous_on u (Icc a b)) : interval_integrable u μ a b := continuous_on.interval_integrable ((uIcc_of_le h).symm ▸ hu) /-- A continuous function on `ℝ` is `interval_integrable` with respect to any locally finite measure `ν` on ℝ. -/ lemma continuous.interval_integrable {u : ℝ → E} (hu : continuous u) (a b : ℝ) : interval_integrable u μ a b := hu.continuous_on.interval_integrable end section variables {μ : measure ℝ} [is_locally_finite_measure μ] [conditionally_complete_linear_order E] [order_topology E] [second_countable_topology E] lemma monotone_on.interval_integrable {u : ℝ → E} {a b : ℝ} (hu : monotone_on u (uIcc a b)) : interval_integrable u μ a b := begin rw interval_integrable_iff, exact (hu.integrable_on_is_compact is_compact_uIcc).mono_set Ioc_subset_Icc_self, end lemma antitone_on.interval_integrable {u : ℝ → E} {a b : ℝ} (hu : antitone_on u (uIcc a b)) : interval_integrable u μ a b := hu.dual_right.interval_integrable lemma monotone.interval_integrable {u : ℝ → E} {a b : ℝ} (hu : monotone u) : interval_integrable u μ a b := (hu.monotone_on _).interval_integrable lemma antitone.interval_integrable {u : ℝ → E} {a b : ℝ} (hu : antitone u) : interval_integrable u μ a b := (hu.antitone_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 : strongly_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 : strongly_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 [complete_space E] [normed_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 ℝ) : E := ∫ 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 basic variables {a b : ℝ} {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 interval_integral_eq_integral_uIoc (f : ℝ → E) (a b : ℝ) (μ : measure ℝ) : ∫ x in a..b, f x ∂μ = (if a ≤ b then 1 else -1 : ℝ) • ∫ x in Ι a b, f x ∂μ := begin split_ifs with h, { simp only [integral_of_le h, uIoc_of_le h, one_smul] }, { simp only [integral_of_ge (not_le.1 h).le, uIoc_of_lt (not_le.1 h), neg_one_smul] } end lemma norm_interval_integral_eq (f : ℝ → E) (a b : ℝ) (μ : measure ℝ) : ‖∫ x in a..b, f x ∂μ‖ = ‖∫ x in Ι a b, f x ∂μ‖ := begin simp_rw [interval_integral_eq_integral_uIoc, norm_smul], split_ifs; simp only [norm_neg, norm_one, one_mul], end lemma abs_interval_integral_eq (f : ℝ → ℝ) (a b : ℝ) (μ : measure ℝ) : |∫ x in a..b, f x ∂μ| = |∫ x in Ι a b, f x ∂μ| := norm_interval_integral_eq f a b μ lemma integral_cases (f : ℝ → E) (a b) : ∫ x in a..b, f x ∂μ ∈ ({∫ x in Ι a b, f x ∂μ, -∫ x in Ι a b, f x ∂μ} : set E) := by { rw interval_integral_eq_integral_uIoc, split_ifs; simp } lemma integral_undef (h : ¬ interval_integrable f μ a b) : ∫ x in a..b, f x ∂μ = 0 := by cases le_total a b with hab hab; simp only [integral_of_le, integral_of_ge, hab, neg_eq_zero]; refine integral_undef (not_imp_not.mpr _ h); simpa only [hab, Ioc_eq_empty_of_le, integrable_on_empty, not_true, false_or, or_false] using not_and_distrib.mp h lemma interval_integrable_of_integral_ne_zero {a b : ℝ} {f : ℝ → E} {μ : measure ℝ} (h : ∫ x in a..b, f x ∂μ ≠ 0) : interval_integrable f μ a b := by { contrapose! h, exact interval_integral.integral_undef h } lemma integral_non_ae_strongly_measurable (hf : ¬ ae_strongly_measurable f (μ.restrict (Ι a b))) : ∫ x in a..b, f x ∂μ = 0 := by rw [interval_integral_eq_integral_uIoc, integral_non_ae_strongly_measurable hf, smul_zero] lemma integral_non_ae_strongly_measurable_of_le (h : a ≤ b) (hf : ¬ ae_strongly_measurable f (μ.restrict (Ioc a b))) : ∫ x in a..b, f x ∂μ = 0 := integral_non_ae_strongly_measurable $ by rwa [uIoc_of_le h] lemma norm_integral_min_max (f : ℝ → E) : ‖∫ x in min a b..max a b, f x ∂μ‖ = ‖∫ x in a..b, f x ∂μ‖ := by cases le_total a b; simp [*, integral_symm a b] lemma norm_integral_eq_norm_integral_Ioc (f : ℝ → E) : ‖∫ x in a..b, f x ∂μ‖ = ‖∫ x in Ι a b, f x ∂μ‖ := by rw [← norm_integral_min_max, integral_of_le min_le_max, uIoc] lemma abs_integral_eq_abs_integral_uIoc (f : ℝ → ℝ) : |∫ x in a..b, f x ∂μ| = |∫ x in Ι a b, f x ∂μ| := norm_integral_eq_norm_integral_Ioc f lemma norm_integral_le_integral_norm_Ioc : ‖∫ x in a..b, f x ∂μ‖ ≤ ∫ x in Ι a b, ‖f x‖ ∂μ := calc ‖∫ x in a..b, f x ∂μ‖ = ‖∫ x in Ι a b, f x ∂μ‖ : norm_integral_eq_norm_integral_Ioc f ... ≤ ∫ x in Ι a b, ‖f x‖ ∂μ : norm_integral_le_integral_norm f lemma norm_integral_le_abs_integral_norm : ‖∫ x in a..b, f x ∂μ‖ ≤ |∫ 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_integral_norm (h : a ≤ b) : ‖∫ x in a..b, f x ∂μ‖ ≤ ∫ x in a..b, ‖f x‖ ∂μ := norm_integral_le_integral_norm_Ioc.trans_eq $ by rw [uIoc_of_le h, integral_of_le h] lemma norm_integral_le_of_norm_le {g : ℝ → ℝ} (h : ∀ᵐ t ∂(μ.restrict $ Ι a b), ‖f t‖ ≤ g t) (hbound : interval_integrable g μ a b) : ‖∫ t in a..b, f t ∂μ‖ ≤ |∫ t in a..b, g t ∂μ| := by simp_rw [norm_interval_integral_eq, abs_interval_integral_eq, abs_eq_self.mpr (integral_nonneg_of_ae $ h.mono $ λ t ht, (norm_nonneg _).trans ht), norm_integral_le_of_norm_le hbound.def h] lemma norm_integral_le_of_norm_le_const_ae {a b C : ℝ} {f : ℝ → E} (h : ∀ᵐ x, x ∈ Ι a b → ‖f x‖ ≤ C) : ‖∫ x in a..b, f x‖ ≤ C * |b - a| := begin rw [norm_integral_eq_norm_integral_Ioc], convert norm_set_integral_le_of_norm_le_const_ae'' _ measurable_set_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 ∈ Ι a b, ‖f x‖ ≤ C) : ‖∫ x in a..b, f x‖ ≤ C * |b - a| := norm_integral_le_of_norm_le_const_ae $ eventually_of_forall h @[simp] 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_eq_integral_uIoc, integral_add hf.def hg.def, smul_add] lemma integral_finset_sum {ι} {s : finset ι} {f : ι → ℝ → E} (h : ∀ i ∈ s, interval_integrable (f i) μ a b) : ∫ x in a..b, ∑ i in s, f i x ∂μ = ∑ i in s, ∫ x in a..b, f i x ∂μ := by simp only [interval_integral_eq_integral_uIoc, integral_finset_sum s (λ i hi, (h i hi).def), finset.smul_sum] @[simp] lemma integral_neg : ∫ x in a..b, -f x ∂μ = -∫ x in a..b, f x ∂μ := by { simp only [interval_integral, integral_neg], abel } @[simp] 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) @[simp] lemma integral_smul {𝕜 : Type*} [nontrivially_normed_field 𝕜] [normed_space 𝕜 E] [smul_comm_class ℝ 𝕜 E] (r : 𝕜) (f : ℝ → E) : ∫ x in a..b, r • f x ∂μ = r • ∫ x in a..b, f x ∂μ := by simp only [interval_integral, integral_smul, smul_sub] @[simp] lemma integral_smul_const {𝕜 : Type*} [is_R_or_C 𝕜] [normed_space 𝕜 E] (f : ℝ → 𝕜) (c : E) : ∫ x in a..b, f x • c ∂μ = (∫ x in a..b, f x ∂μ) • c := by simp only [interval_integral_eq_integral_uIoc, integral_smul_const, smul_assoc] @[simp] lemma integral_const_mul {𝕜 : Type*} [is_R_or_C 𝕜] (r : 𝕜) (f : ℝ → 𝕜) : ∫ x in a..b, r * f x ∂μ = r * ∫ x in a..b, f x ∂μ := integral_smul r f @[simp] lemma integral_mul_const {𝕜 : Type*} [is_R_or_C 𝕜] (r : 𝕜) (f : ℝ → 𝕜) : ∫ x in a..b, f x * r ∂μ = ∫ x in a..b, f x ∂μ * r := by simpa only [mul_comm r] using integral_const_mul r f @[simp] lemma integral_div {𝕜 : Type*} [is_R_or_C 𝕜] (r : 𝕜) (f : ℝ → 𝕜) : ∫ x in a..b, f x / r ∂μ = ∫ x in a..b, f x ∂μ / r := by simpa only [div_eq_mul_inv] using integral_mul_const r⁻¹ f 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] @[simp] lemma integral_const (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 : ℝ≥0∞) : ∫ 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] end basic lemma integral_of_real {a b : ℝ} {μ : measure ℝ} {f : ℝ → ℝ} : ∫ x in a..b, (f x : ℂ) ∂μ = ↑(∫ x in a..b, f x ∂μ) := by simp only [interval_integral, integral_of_real, complex.of_real_sub] section continuous_linear_map variables {a b : ℝ} {μ : measure ℝ} {f : ℝ → E} variables [is_R_or_C 𝕜] [normed_space 𝕜 E] [normed_add_comm_group F] [normed_space 𝕜 F] open continuous_linear_map lemma _root_.continuous_linear_map.interval_integral_apply {a b : ℝ} {φ : ℝ → F →L[𝕜] E} (hφ : interval_integrable φ μ a b) (v : F) : (∫ x in a..b, φ x ∂μ) v = ∫ x in a..b, φ x v ∂μ := by simp_rw [interval_integral_eq_integral_uIoc, ← integral_apply hφ.def v, coe_smul', pi.smul_apply] variables [normed_space ℝ F] [complete_space F] lemma _root_.continuous_linear_map.interval_integral_comp_comm (L : E →L[𝕜] F) (hf : interval_integrable f μ a b) : ∫ x in a..b, L (f x) ∂μ = L (∫ x in a..b, f x ∂μ) := by simp_rw [interval_integral, L.integral_comp_comm hf.1, L.integral_comp_comm hf.2, L.map_sub] end continuous_linear_map section comp variables {a b c d : ℝ} (f : ℝ → E) @[simp] lemma integral_comp_mul_right (hc : c ≠ 0) : ∫ x in a..b, f (x * c) = c⁻¹ • ∫ x in a*c..b*c, f x := begin have A : measurable_embedding (λ x, x * c) := (homeomorph.mul_right₀ c hc).closed_embedding.measurable_embedding, conv_rhs { rw [← real.smul_map_volume_mul_right hc] }, simp_rw [integral_smul_measure, interval_integral, A.set_integral_map, ennreal.to_real_of_real (abs_nonneg c)], cases hc.lt_or_lt, { simp [h, mul_div_cancel, hc, abs_of_neg, measure.restrict_congr_set Ico_ae_eq_Ioc] }, { simp [h, mul_div_cancel, hc, abs_of_pos] } end @[simp] lemma smul_integral_comp_mul_right (c) : c • ∫ x in a..b, f (x * c) = ∫ x in a*c..b*c, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_mul_left (hc : c ≠ 0) : ∫ x in a..b, f (c * x) = c⁻¹ • ∫ x in c*a..c*b, f x := by simpa only [mul_comm c] using integral_comp_mul_right f hc @[simp] lemma smul_integral_comp_mul_left (c) : c • ∫ x in a..b, f (c * x) = ∫ x in c*a..c*b, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_div (hc : c ≠ 0) : ∫ x in a..b, f (x / c) = c • ∫ x in a/c..b/c, f x := by simpa only [inv_inv] using integral_comp_mul_right f (inv_ne_zero hc) @[simp] lemma inv_smul_integral_comp_div (c) : c⁻¹ • ∫ x in a..b, f (x / c) = ∫ x in a/c..b/c, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_add_right (d) : ∫ x in a..b, f (x + d) = ∫ x in a+d..b+d, f x := have A : measurable_embedding (λ x, x + d) := (homeomorph.add_right d).closed_embedding.measurable_embedding, calc ∫ x in a..b, f (x + d) = ∫ x in a+d..b+d, f x ∂(measure.map (λ x, x + d) volume) : by simp [interval_integral, A.set_integral_map] ... = ∫ x in a+d..b+d, f x : by rw [map_add_right_eq_self] @[simp] lemma integral_comp_add_left (d) : ∫ x in a..b, f (d + x) = ∫ x in d+a..d+b, f x := by simpa only [add_comm] using integral_comp_add_right f d @[simp] lemma integral_comp_mul_add (hc : c ≠ 0) (d) : ∫ x in a..b, f (c * x + d) = c⁻¹ • ∫ x in c*a+d..c*b+d, f x := by rw [← integral_comp_add_right, ← integral_comp_mul_left _ hc] @[simp] lemma smul_integral_comp_mul_add (c d) : c • ∫ x in a..b, f (c * x + d) = ∫ x in c*a+d..c*b+d, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_add_mul (hc : c ≠ 0) (d) : ∫ x in a..b, f (d + c * x) = c⁻¹ • ∫ x in d+c*a..d+c*b, f x := by rw [← integral_comp_add_left, ← integral_comp_mul_left _ hc] @[simp] lemma smul_integral_comp_add_mul (c d) : c • ∫ x in a..b, f (d + c * x) = ∫ x in d+c*a..d+c*b, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_div_add (hc : c ≠ 0) (d) : ∫ x in a..b, f (x / c + d) = c • ∫ x in a/c+d..b/c+d, f x := by simpa only [div_eq_inv_mul, inv_inv] using integral_comp_mul_add f (inv_ne_zero hc) d @[simp] lemma inv_smul_integral_comp_div_add (c d) : c⁻¹ • ∫ x in a..b, f (x / c + d) = ∫ x in a/c+d..b/c+d, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_add_div (hc : c ≠ 0) (d) : ∫ x in a..b, f (d + x / c) = c • ∫ x in d+a/c..d+b/c, f x := by simpa only [div_eq_inv_mul, inv_inv] using integral_comp_add_mul f (inv_ne_zero hc) d @[simp] lemma inv_smul_integral_comp_add_div (c d) : c⁻¹ • ∫ x in a..b, f (d + x / c) = ∫ x in d+a/c..d+b/c, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_mul_sub (hc : c ≠ 0) (d) : ∫ x in a..b, f (c * x - d) = c⁻¹ • ∫ x in c*a-d..c*b-d, f x := by simpa only [sub_eq_add_neg] using integral_comp_mul_add f hc (-d) @[simp] lemma smul_integral_comp_mul_sub (c d) : c • ∫ x in a..b, f (c * x - d) = ∫ x in c*a-d..c*b-d, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_sub_mul (hc : c ≠ 0) (d) : ∫ x in a..b, f (d - c * x) = c⁻¹ • ∫ x in d-c*b..d-c*a, f x := begin simp only [sub_eq_add_neg, neg_mul_eq_neg_mul], rw [integral_comp_add_mul f (neg_ne_zero.mpr hc) d, integral_symm], simp only [inv_neg, smul_neg, neg_neg, neg_smul], end @[simp] lemma smul_integral_comp_sub_mul (c d) : c • ∫ x in a..b, f (d - c * x) = ∫ x in d-c*b..d-c*a, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_div_sub (hc : c ≠ 0) (d) : ∫ x in a..b, f (x / c - d) = c • ∫ x in a/c-d..b/c-d, f x := by simpa only [div_eq_inv_mul, inv_inv] using integral_comp_mul_sub f (inv_ne_zero hc) d @[simp] lemma inv_smul_integral_comp_div_sub (c d) : c⁻¹ • ∫ x in a..b, f (x / c - d) = ∫ x in a/c-d..b/c-d, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_sub_div (hc : c ≠ 0) (d) : ∫ x in a..b, f (d - x / c) = c • ∫ x in d-b/c..d-a/c, f x := by simpa only [div_eq_inv_mul, inv_inv] using integral_comp_sub_mul f (inv_ne_zero hc) d @[simp] lemma inv_smul_integral_comp_sub_div (c d) : c⁻¹ • ∫ x in a..b, f (d - x / c) = ∫ x in d-b/c..d-a/c, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_sub_right (d) : ∫ x in a..b, f (x - d) = ∫ x in a-d..b-d, f x := by simpa only [sub_eq_add_neg] using integral_comp_add_right f (-d) @[simp] lemma integral_comp_sub_left (d) : ∫ x in a..b, f (d - x) = ∫ x in d-b..d-a, f x := by simpa only [one_mul, one_smul, inv_one] using integral_comp_sub_mul f one_ne_zero d @[simp] lemma integral_comp_neg : ∫ x in a..b, f (-x) = ∫ x in -b..-a, f x := by simpa only [zero_sub] using integral_comp_sub_left f 0 end comp /-! ### 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`. -/ section order_closed_topology variables {a b c d : ℝ} {f g : ℝ → E} {μ : measure ℝ} /-- If two functions are equal in the relevant interval, their interval integrals are also equal. -/ lemma integral_congr {a b : ℝ} (h : eq_on f g [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 measurable_set_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, sub_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 [*, measurable_set.union, measurable_set_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 sum_integral_adjacent_intervals_Ico {a : ℕ → ℝ} {m n : ℕ} (hmn : m ≤ n) (hint : ∀ k ∈ Ico m n, interval_integrable f μ (a k) (a $ k+1)) : ∑ (k : ℕ) in finset.Ico m n, ∫ x in (a k)..(a $ k+1), f x ∂μ = ∫ x in (a m)..(a n), f x ∂μ := begin revert hint, refine nat.le_induction _ _ n hmn, { simp }, { assume p hmp IH h, rw [finset.sum_Ico_succ_top hmp, IH, integral_add_adjacent_intervals], { apply interval_integrable.trans_iterate_Ico hmp (λ k hk, h k _), exact (Ico_subset_Ico le_rfl (nat.le_succ _)) hk }, { apply h, simp [hmp] }, { assume k hk, exact h _ (Ico_subset_Ico_right p.le_succ hk) } } end lemma sum_integral_adjacent_intervals {a : ℕ → ℝ} {n : ℕ} (hint : ∀ k < n, interval_integrable f μ (a k) (a $ k+1)) : ∑ (k : ℕ) in finset.range n, ∫ x in (a k)..(a $ k+1), f x ∂μ = ∫ x in (a 0)..(a n), f x ∂μ := begin rw ← nat.Ico_zero_eq_range, exact sum_integral_adjacent_intervals_Ico (zero_le n) (λ k hk, hint k hk.2), end 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 generalizing a b, { rw [integral_symm, ← this hb ha (le_of_not_le hab), neg_sub] }, rw [sub_eq_iff_eq_add', integral_of_le hab, ← integral_union (Iic_disjoint_Ioc le_rfl), Iic_union_Ioc_eq_Iic hab], exacts [measurable_set_Ioc, ha, hb.mono_set (λ _, and.right)] end /-- If `μ` is a finite measure then `∫ x in a..b, c ∂μ = (μ (Iic b) - μ (Iic a)) • c`. -/ lemma integral_const_of_cdf [is_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 {a b} (h : 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 measurable_set_Ioc, indicator_eq_self.2 h]; apply_instance }, { rw [Ioc_eq_empty hab.not_lt, subset_empty_iff, support_eq_empty_iff] at h, simp [h] } end lemma integral_congr_ae' (h : ∀ᵐ x ∂μ, x ∈ Ioc a b → f x = g x) (h' : ∀ᵐ x ∂μ, x ∈ Ioc b a → f x = g x) : ∫ x in a..b, f x ∂μ = ∫ x in a..b, g x ∂μ := by simp only [interval_integral, set_integral_congr_ae (measurable_set_Ioc) h, set_integral_congr_ae (measurable_set_Ioc) h'] lemma integral_congr_ae (h : ∀ᵐ x ∂μ, x ∈ Ι a b → f x = g x) : ∫ x in a..b, f x ∂μ = ∫ x in a..b, g x ∂μ := integral_congr_ae' (ae_uIoc_iff.mp h).1 (ae_uIoc_iff.mp h).2 lemma integral_zero_ae (h : ∀ᵐ x ∂μ, x ∈ Ι a b → f x = 0) : ∫ x in a..b, f x ∂μ = 0 := calc ∫ x in a..b, f x ∂μ = ∫ x in a..b, 0 ∂μ : integral_congr_ae h ... = 0 : integral_zero lemma integral_indicator {a₁ a₂ a₃ : ℝ} (h : a₂ ∈ Icc a₁ a₃) : ∫ x in a₁..a₃, indicator {x | x ≤ a₂} f x ∂ μ = ∫ x in a₁..a₂, f x ∂ μ := begin have : {x | x ≤ a₂} ∩ Ioc a₁ a₃ = Ioc a₁ a₂, from Iic_inter_Ioc_of_le h.2, rw [integral_of_le h.1, integral_of_le (h.1.trans h.2), integral_indicator, measure.restrict_restrict, this], exact measurable_set_Iic, all_goals { apply measurable_set_Iic }, 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} (bound : ℝ → ℝ) (hF_meas : ∀ᶠ n in l, ae_strongly_measurable (F n) (μ.restrict (Ι a b))) (h_bound : ∀ᶠ n in l, ∀ᵐ x ∂μ, x ∈ Ι a b → ‖F n x‖ ≤ bound x) (bound_integrable : interval_integrable bound μ a b) (h_lim : ∀ᵐ x ∂μ, x ∈ Ι a b → tendsto (λ n, F n x) l (𝓝 (f x))) : tendsto (λn, ∫ x in a..b, F n x ∂μ) l (𝓝 $ ∫ x in a..b, f x ∂μ) := begin simp only [interval_integrable_iff, interval_integral_eq_integral_uIoc, ← ae_restrict_iff' measurable_set_uIoc] at *, exact tendsto_const_nhds.smul (tendsto_integral_filter_of_dominated_convergence bound hF_meas h_bound bound_integrable h_lim) end /-- Lebesgue dominated convergence theorem for series. -/ lemma has_sum_integral_of_dominated_convergence {ι} [countable ι] {F : ι → ℝ → E} (bound : ι → ℝ → ℝ) (hF_meas : ∀ n, ae_strongly_measurable (F n) (μ.restrict (Ι a b))) (h_bound : ∀ n, ∀ᵐ t ∂μ, t ∈ Ι a b → ‖F n t‖ ≤ bound n t) (bound_summable : ∀ᵐ t ∂μ, t ∈ Ι a b → summable (λ n, bound n t)) (bound_integrable : interval_integrable (λ t, ∑' n, bound n t) μ a b) (h_lim : ∀ᵐ t ∂μ, t ∈ Ι a b → has_sum (λ n, F n t) (f t)) : has_sum (λn, ∫ t in a..b, F n t ∂μ) (∫ t in a..b, f t ∂μ) := begin simp only [interval_integrable_iff, interval_integral_eq_integral_uIoc, ← ae_restrict_iff' measurable_set_uIoc] at *, exact (has_sum_integral_of_dominated_convergence bound hF_meas h_bound bound_summable bound_integrable h_lim).const_smul _, end open topological_space /-- Interval integrals commute with countable sums, when the supremum norms are summable (a special case of the dominated convergence theorem). -/ lemma has_sum_interval_integral_of_summable_norm [countable ι] {f : ι → C(ℝ, E)} (hf_sum : summable (λ i : ι, ‖(f i).restrict (⟨uIcc a b, is_compact_uIcc⟩ : compacts ℝ)‖)) : has_sum (λ i : ι, ∫ x in a..b, f i x) (∫ x in a..b, (∑' i : ι, f i x)) := begin refine has_sum_integral_of_dominated_convergence (λ i (x : ℝ), ‖(f i).restrict ↑(⟨uIcc a b, is_compact_uIcc⟩ : compacts ℝ)‖) (λ i, (map_continuous $ f i).ae_strongly_measurable) (λ i, ae_of_all _ (λ x hx, ((f i).restrict ↑(⟨uIcc a b, is_compact_uIcc⟩ : compacts ℝ)).norm_coe_le_norm ⟨x, ⟨hx.1.le, hx.2⟩⟩)) (ae_of_all _ (λ x hx, hf_sum)) interval_integrable_const (ae_of_all _ (λ x hx, summable.has_sum _)), -- next line is slow, & doesn't work with "exact" in place of "apply" -- ? apply continuous_map.summable_apply (summable_of_summable_norm hf_sum) ⟨x, ⟨hx.1.le, hx.2⟩⟩, end lemma tsum_interval_integral_eq_of_summable_norm [countable ι] {f : ι → C(ℝ, E)} (hf_sum : summable (λ i : ι, ‖(f i).restrict (⟨uIcc a b, is_compact_uIcc⟩ : compacts ℝ)‖)) : ∑' (i : ι), ∫ x in a..b, f i x = ∫ x in a..b, (∑' i : ι, f i x) := (has_sum_interval_integral_of_summable_norm hf_sum).tsum_eq variables {X : Type*} [topological_space X] [first_countable_topology X] /-- Continuity of interval integral with respect to a parameter, at a point within a set. Given `F : X → ℝ → E`, assume `F x` is ae-measurable on `[a, b]` for `x` in a neighborhood of `x₀` within `s` and at `x₀`, and assume it is bounded by a function integrable on `[a, b]` independent of `x` in a neighborhood of `x₀` within `s`. If `(λ x, F x t)` is continuous at `x₀` within `s` for almost every `t` in `[a, b]` then the same holds for `(λ x, ∫ t in a..b, F x t ∂μ) s x₀`. -/ lemma continuous_within_at_of_dominated_interval {F : X → ℝ → E} {x₀ : X} {bound : ℝ → ℝ} {a b : ℝ} {s : set X} (hF_meas : ∀ᶠ x in 𝓝[s] x₀, ae_strongly_measurable (F x) (μ.restrict $ Ι a b)) (h_bound : ∀ᶠ x in 𝓝[s] x₀, ∀ᵐ t ∂μ, t ∈ Ι a b → ‖F x t‖ ≤ bound t) (bound_integrable : interval_integrable bound μ a b) (h_cont : ∀ᵐ t ∂μ, t ∈ Ι a b → continuous_within_at (λ x, F x t) s x₀) : continuous_within_at (λ x, ∫ t in a..b, F x t ∂μ) s x₀ := tendsto_integral_filter_of_dominated_convergence bound hF_meas h_bound bound_integrable h_cont /-- Continuity of interval integral with respect to a parameter at a point. Given `F : X → ℝ → E`, assume `F x` is ae-measurable on `[a, b]` for `x` in a neighborhood of `x₀`, and assume it is bounded by a function integrable on `[a, b]` independent of `x` in a neighborhood of `x₀`. If `(λ x, F x t)` is continuous at `x₀` for almost every `t` in `[a, b]` then the same holds for `(λ x, ∫ t in a..b, F x t ∂μ) s x₀`. -/ lemma continuous_at_of_dominated_interval {F : X → ℝ → E} {x₀ : X} {bound : ℝ → ℝ} {a b : ℝ} (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_strongly_measurable (F x) (μ.restrict $ Ι a b)) (h_bound : ∀ᶠ x in 𝓝 x₀, ∀ᵐ t ∂μ, t ∈ Ι a b → ‖F x t‖ ≤ bound t) (bound_integrable : interval_integrable bound μ a b) (h_cont : ∀ᵐ t ∂μ, t ∈ Ι a b → continuous_at (λ x, F x t) x₀) : continuous_at (λ x, ∫ t in a..b, F x t ∂μ) x₀ := tendsto_integral_filter_of_dominated_convergence bound hF_meas h_bound bound_integrable h_cont /-- Continuity of interval integral with respect to a parameter. Given `F : X → ℝ → E`, assume each `F x` is ae-measurable on `[a, b]`, and assume it is bounded by a function integrable on `[a, b]` independent of `x`. If `(λ x, F x t)` is continuous for almost every `t` in `[a, b]` then the same holds for `(λ x, ∫ t in a..b, F x t ∂μ) s x₀`. -/ lemma continuous_of_dominated_interval {F : X → ℝ → E} {bound : ℝ → ℝ} {a b : ℝ} (hF_meas : ∀ x, ae_strongly_measurable (F x) $ μ.restrict $ Ι a b) (h_bound : ∀ x, ∀ᵐ t ∂μ, t ∈ Ι a b → ‖F x t‖ ≤ bound t) (bound_integrable : interval_integrable bound μ a b) (h_cont : ∀ᵐ t ∂μ, t ∈ Ι a b → continuous (λ x, F x t)) : continuous (λ x, ∫ t in a..b, F x t ∂μ) := continuous_iff_continuous_at.mpr (λ x₀, continuous_at_of_dominated_interval (eventually_of_forall hF_meas) (eventually_of_forall h_bound) bound_integrable $ h_cont.mono $ λ x himp hx, (himp hx).continuous_at) end order_closed_topology section continuous_primitive open topological_space variables {a b b₀ b₁ b₂ : ℝ} {μ : measure ℝ} {f g : ℝ → E} lemma continuous_within_at_primitive (hb₀ : μ {b₀} = 0) (h_int : interval_integrable f μ (min a b₁) (max a b₂)) : continuous_within_at (λ b, ∫ x in a .. b, f x ∂ μ) (Icc b₁ b₂) b₀ := begin by_cases h₀ : b₀ ∈ Icc b₁ b₂, { have h₁₂ : b₁ ≤ b₂ := h₀.1.trans h₀.2, have min₁₂ : min b₁ b₂ = b₁ := min_eq_left h₁₂, have h_int' : ∀ {x}, x ∈ Icc b₁ b₂ → interval_integrable f μ b₁ x, { rintros x ⟨h₁, h₂⟩, apply h_int.mono_set, apply uIcc_subset_uIcc, { exact ⟨min_le_of_left_le (min_le_right a b₁), h₁.trans (h₂.trans $ le_max_of_le_right $ le_max_right _ _)⟩ }, { exact ⟨min_le_of_left_le $ (min_le_right _ _).trans h₁, le_max_of_le_right $ h₂.trans $ le_max_right _ _⟩ } }, have : ∀ b ∈ Icc b₁ b₂, ∫ x in a..b, f x ∂μ = ∫ x in a..b₁, f x ∂μ + ∫ x in b₁..b, f x ∂μ, { rintros b ⟨h₁, h₂⟩, rw ← integral_add_adjacent_intervals _ (h_int' ⟨h₁, h₂⟩), apply h_int.mono_set, apply uIcc_subset_uIcc, { exact ⟨min_le_of_left_le (min_le_left a b₁), le_max_of_le_right (le_max_left _ _)⟩ }, { exact ⟨min_le_of_left_le (min_le_right _ _), le_max_of_le_right (h₁.trans $ h₂.trans (le_max_right a b₂))⟩ } }, apply continuous_within_at.congr _ this (this _ h₀), clear this, refine continuous_within_at_const.add _, have : (λ b, ∫ x in b₁..b, f x ∂μ) =ᶠ[𝓝[Icc b₁ b₂] b₀] λ b, ∫ x in b₁..b₂, indicator {x | x ≤ b} f x ∂ μ, { apply eventually_eq_of_mem self_mem_nhds_within, exact λ b b_in, (integral_indicator b_in).symm }, apply continuous_within_at.congr_of_eventually_eq _ this (integral_indicator h₀).symm, have : interval_integrable (λ x, ‖f x‖) μ b₁ b₂, from interval_integrable.norm (h_int' $ right_mem_Icc.mpr h₁₂), refine continuous_within_at_of_dominated_interval _ _ this _ ; clear this, { apply eventually.mono (self_mem_nhds_within), intros x hx, erw [ae_strongly_measurable_indicator_iff, measure.restrict_restrict, Iic_inter_Ioc_of_le], { rw min₁₂, exact (h_int' hx).1.ae_strongly_measurable }, { exact le_max_of_le_right hx.2 }, exacts [measurable_set_Iic, measurable_set_Iic] }, { refine eventually_of_forall (λ x, eventually_of_forall (λ t, _)), dsimp [indicator], split_ifs ; simp }, { have : ∀ᵐ t ∂μ, t < b₀ ∨ b₀ < t, { apply eventually.mono (compl_mem_ae_iff.mpr hb₀), intros x hx, exact ne.lt_or_lt hx }, apply this.mono, rintros x₀ (hx₀ | hx₀) -, { have : ∀ᶠ x in 𝓝[Icc b₁ b₂] b₀, {t : ℝ | t ≤ x}.indicator f x₀ = f x₀, { apply mem_nhds_within_of_mem_nhds, apply eventually.mono (Ioi_mem_nhds hx₀), intros x hx, simp [hx.le] }, apply continuous_within_at_const.congr_of_eventually_eq this, simp [hx₀.le] }, { have : ∀ᶠ x in 𝓝[Icc b₁ b₂] b₀, {t : ℝ | t ≤ x}.indicator f x₀ = 0, { apply mem_nhds_within_of_mem_nhds, apply eventually.mono (Iio_mem_nhds hx₀), intros x hx, simp [hx] }, apply continuous_within_at_const.congr_of_eventually_eq this, simp [hx₀] } } }, { apply continuous_within_at_of_not_mem_closure, rwa [closure_Icc] } end lemma continuous_on_primitive [has_no_atoms μ] (h_int : integrable_on f (Icc a b) μ) : continuous_on (λ x, ∫ t in Ioc a x, f t ∂ μ) (Icc a b) := begin by_cases h : a ≤ b, { have : ∀ x ∈ Icc a b, ∫ t in Ioc a x, f t ∂μ = ∫ t in a..x, f t ∂μ, { intros x x_in, simp_rw [← uIoc_of_le h, integral_of_le x_in.1] }, rw continuous_on_congr this, intros x₀ hx₀, refine continuous_within_at_primitive (measure_singleton x₀) _, simp only [interval_integrable_iff_integrable_Ioc_of_le, min_eq_left, max_eq_right, h], exact h_int.mono Ioc_subset_Icc_self le_rfl }, { rw Icc_eq_empty h, exact continuous_on_empty _ }, end lemma continuous_on_primitive_Icc [has_no_atoms μ] (h_int : integrable_on f (Icc a b) μ) : continuous_on (λ x, ∫ t in Icc a x, f t ∂ μ) (Icc a b) := begin rw show (λ x, ∫ t in Icc a x, f t ∂μ) = λ x, ∫ t in Ioc a x, f t ∂μ, by { ext x, exact integral_Icc_eq_integral_Ioc }, exact continuous_on_primitive h_int end /-- Note: this assumes that `f` is `interval_integrable`, in contrast to some other lemmas here. -/ lemma continuous_on_primitive_interval' [has_no_atoms μ] (h_int : interval_integrable f μ b₁ b₂) (ha : a ∈ [b₁, b₂]) : continuous_on (λ b, ∫ x in a..b, f x ∂ μ) [b₁, b₂] := begin intros b₀ hb₀, refine continuous_within_at_primitive (measure_singleton _) _, rw [min_eq_right ha.1, max_eq_right ha.2], simpa [interval_integrable_iff, uIoc] using h_int, end lemma continuous_on_primitive_interval [has_no_atoms μ] (h_int : integrable_on f (uIcc a b) μ) : continuous_on (λ x, ∫ t in a..x, f t ∂ μ) (uIcc a b) := continuous_on_primitive_interval' h_int.interval_integrable left_mem_uIcc lemma continuous_on_primitive_interval_left [has_no_atoms μ] (h_int : integrable_on f (uIcc a b) μ) : continuous_on (λ x, ∫ t in x..b, f t ∂ μ) (uIcc a b) := begin rw uIcc_comm a b at h_int ⊢, simp only [integral_symm b], exact (continuous_on_primitive_interval h_int).neg, end variables [has_no_atoms μ] lemma continuous_primitive (h_int : ∀ a b, interval_integrable f μ a b) (a : ℝ) : continuous (λ b, ∫ x in a..b, f x ∂ μ) := begin rw continuous_iff_continuous_at, intro b₀, cases exists_lt b₀ with b₁ hb₁, cases exists_gt b₀ with b₂ hb₂, apply continuous_within_at.continuous_at _ (Icc_mem_nhds hb₁ hb₂), exact continuous_within_at_primitive (measure_singleton b₀) (h_int _ _) end lemma _root_.measure_theory.integrable.continuous_primitive (h_int : integrable f μ) (a : ℝ) : continuous (λ b, ∫ x in a..b, f x ∂ μ) := continuous_primitive (λ _ _, h_int.interval_integrable) a end continuous_primitive section variables {f g : ℝ → ℝ} {a b : ℝ} {μ : measure ℝ} lemma integral_eq_zero_iff_of_le_of_nonneg_ae (hab : a ≤ b) (hf : 0 ≤ᵐ[μ.restrict (Ioc a b)] f) (hfi : interval_integrable f μ a b) : ∫ x in a..b, f x ∂μ = 0 ↔ f =ᵐ[μ.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 (hf : 0 ≤ᵐ[μ.restrict (Ioc a b ∪ Ioc b a)] f) (hfi : interval_integrable f μ a b) : ∫ x in a..b, f x ∂μ = 0 ↔ f =ᵐ[μ.restrict (Ioc a b ∪ Ioc b a)] 0 := begin cases le_total a b with hab hab; simp only [Ioc_eq_empty hab.not_lt, empty_union, union_empty] at hf ⊢, { exact integral_eq_zero_iff_of_le_of_nonneg_ae hab hf hfi }, { rw [integral_symm, neg_eq_zero, integral_eq_zero_iff_of_le_of_nonneg_ae hab hf hfi.symm] } end /-- If `f` is nonnegative and integrable on the unordered interval `set.uIoc a b`, then its integral over `a..b` is positive if and only if `a < b` and the measure of `function.support f ∩ set.Ioc a b` is positive. -/ lemma integral_pos_iff_support_of_nonneg_ae' (hf : 0 ≤ᵐ[μ.restrict (Ι a b)] f) (hfi : interval_integrable f μ a b) : 0 < ∫ x in a..b, f x ∂μ ↔ a < b ∧ 0 < μ (support f ∩ Ioc a b) := begin cases lt_or_le a b with hab hba, { rw uIoc_of_le hab.le at hf, simp only [hab, true_and, integral_of_le hab.le, set_integral_pos_iff_support_of_nonneg_ae hf hfi.1] }, { suffices : ∫ x in a..b, f x ∂μ ≤ 0, by simp only [this.not_lt, hba.not_lt, false_and], rw [integral_of_ge hba, neg_nonpos], rw [uIoc_swap, uIoc_of_le hba] at hf, exact integral_nonneg_of_ae hf } end /-- If `f` is nonnegative a.e.-everywhere and it is integrable on the unordered interval `set.uIoc a b`, then its integral over `a..b` is positive if and only if `a < b` and the measure of `function.support f ∩ set.Ioc a b` is positive. -/ lemma integral_pos_iff_support_of_nonneg_ae (hf : 0 ≤ᵐ[μ] f) (hfi : interval_integrable f μ a b) : 0 < ∫ x in a..b, f x ∂μ ↔ a < b ∧ 0 < μ (support f ∩ Ioc a b) := integral_pos_iff_support_of_nonneg_ae' (ae_mono measure.restrict_le_self hf) hfi /-- If `f : ℝ → ℝ` is integrable on `(a, b]` for real numbers `a < b`, and positive on the interior of the interval, then its integral over `a..b` is strictly positive. -/ lemma interval_integral_pos_of_pos_on {f : ℝ → ℝ} {a b : ℝ} (hfi : interval_integrable f volume a b) (hpos : ∀ (x : ℝ), x ∈ Ioo a b → 0 < f x) (hab : a < b) : 0 < ∫ (x : ℝ) in a..b, f x := begin have hsupp : Ioo a b ⊆ support f ∩ Ioc a b := λ x hx, ⟨mem_support.mpr (hpos x hx).ne', Ioo_subset_Ioc_self hx⟩, have h₀ : 0 ≤ᵐ[volume.restrict (uIoc a b)] f, { rw [eventually_le, uIoc_of_le hab.le], refine ae_restrict_of_ae_eq_of_ae_restrict Ioo_ae_eq_Ioc _, exact (ae_restrict_iff' measurable_set_Ioo).mpr (ae_of_all _ (λ x hx, (hpos x hx).le)) }, rw integral_pos_iff_support_of_nonneg_ae' h₀ hfi, exact ⟨hab, ((measure.measure_Ioo_pos _).mpr hab).trans_le (measure_mono hsupp)⟩, end /-- If `f : ℝ → ℝ` is strictly positive everywhere, and integrable on `(a, b]` for real numbers `a < b`, then its integral over `a..b` is strictly positive. (See `interval_integral_pos_of_pos_on` for a version only assuming positivity of `f` on `(a, b)` rather than everywhere.) -/ lemma interval_integral_pos_of_pos {f : ℝ → ℝ} {a b : ℝ} (hfi : interval_integrable f measure_space.volume a b) (hpos : ∀ x, 0 < f x) (hab : a < b) : 0 < ∫ x in a..b, f x := interval_integral_pos_of_pos_on hfi (λ x hx, hpos x) hab /-- If `f` and `g` are two functions that are interval integrable on `a..b`, `a ≤ b`, `f x ≤ g x` for a.e. `x ∈ set.Ioc a b`, and `f x < g x` on a subset of `set.Ioc a b` of nonzero measure, then `∫ x in a..b, f x ∂μ < ∫ x in a..b, g x ∂μ`. -/ lemma integral_lt_integral_of_ae_le_of_measure_set_of_lt_ne_zero (hab : a ≤ b) (hfi : interval_integrable f μ a b) (hgi : interval_integrable g μ a b) (hle : f ≤ᵐ[μ.restrict (Ioc a b)] g) (hlt : μ.restrict (Ioc a b) {x | f x < g x} ≠ 0) : ∫ x in a..b, f x ∂μ < ∫ x in a..b, g x ∂μ := begin rw [← sub_pos, ← integral_sub hgi hfi, integral_of_le hab, measure_theory.integral_pos_iff_support_of_nonneg_ae], { refine pos_iff_ne_zero.2 (mt (measure_mono_null _) hlt), exact λ x hx, (sub_pos.2 hx).ne' }, exacts [hle.mono (λ x, sub_nonneg.2), hgi.1.sub hfi.1] end /-- If `f` and `g` are continuous on `[a, b]`, `a < b`, `f x ≤ g x` on this interval, and `f c < g c` at some point `c ∈ [a, b]`, then `∫ x in a..b, f x < ∫ x in a..b, g x`. -/ lemma integral_lt_integral_of_continuous_on_of_le_of_exists_lt {f g : ℝ → ℝ} {a b : ℝ} (hab : a < b) (hfc : continuous_on f (Icc a b)) (hgc : continuous_on g (Icc a b)) (hle : ∀ x ∈ Ioc a b, f x ≤ g x) (hlt : ∃ c ∈ Icc a b, f c < g c) : ∫ x in a..b, f x < ∫ x in a..b, g x := begin refine integral_lt_integral_of_ae_le_of_measure_set_of_lt_ne_zero hab.le (hfc.interval_integrable_of_Icc hab.le) (hgc.interval_integrable_of_Icc hab.le) ((ae_restrict_mem measurable_set_Ioc).mono hle) _, contrapose! hlt, have h_eq : f =ᵐ[volume.restrict (Ioc a b)] g, { simp only [← not_le, ← ae_iff] at hlt, exact eventually_le.antisymm ((ae_restrict_iff' measurable_set_Ioc).2 $ eventually_of_forall hle) hlt }, simp only [measure.restrict_congr_set Ioc_ae_eq_Icc] at h_eq, exact λ c hc, (measure.eq_on_Icc_of_ae_eq volume hab.ne h_eq hfc hgc hc).ge end lemma integral_nonneg_of_ae_restrict (hab : a ≤ b) (hf : 0 ≤ᵐ[μ.restrict (Icc a b)] f) : 0 ≤ (∫ u in a..b, f u ∂μ) := let H := ae_restrict_of_ae_restrict_of_subset Ioc_subset_Icc_self hf in by simpa only [integral_of_le hab] using set_integral_nonneg_of_ae_restrict H lemma integral_nonneg_of_ae (hab : a ≤ b) (hf : 0 ≤ᵐ[μ] f) : 0 ≤ (∫ u in a..b, f u ∂μ) := integral_nonneg_of_ae_restrict hab $ ae_restrict_of_ae hf lemma integral_nonneg_of_forall (hab : a ≤ b) (hf : ∀ u, 0 ≤ f u) : 0 ≤ (∫ u in a..b, f u ∂μ) := integral_nonneg_of_ae hab $ eventually_of_forall hf lemma integral_nonneg (hab : a ≤ b) (hf : ∀ u, u ∈ Icc a b → 0 ≤ f u) : 0 ≤ (∫ u in a..b, f u ∂μ) := integral_nonneg_of_ae_restrict hab $ (ae_restrict_iff' measurable_set_Icc).mpr $ ae_of_all μ hf lemma abs_integral_le_integral_abs (hab : a ≤ b) : |∫ x in a..b, f x ∂μ| ≤ ∫ x in a..b, |f x| ∂μ := by simpa only [← real.norm_eq_abs] using norm_integral_le_integral_norm hab section mono variables (hab : a ≤ b) (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) include hab hf hg lemma integral_mono_ae_restrict (h : f ≤ᵐ[μ.restrict (Icc a b)] g) : ∫ u in a..b, f u ∂μ ≤ ∫ u in a..b, g u ∂μ := let H := h.filter_mono $ ae_mono $ measure.restrict_mono Ioc_subset_Icc_self $ le_refl μ in by simpa only [integral_of_le hab] using set_integral_mono_ae_restrict hf.1 hg.1 H lemma integral_mono_ae (h : f ≤ᵐ[μ] g) : ∫ u in a..b, f u ∂μ ≤ ∫ u in a..b, g u ∂μ := by simpa only [integral_of_le hab] using set_integral_mono_ae hf.1 hg.1 h lemma integral_mono_on (h : ∀ x ∈ Icc a b, f x ≤ g x) : ∫ u in a..b, f u ∂μ ≤ ∫ u in a..b, g u ∂μ := let H := λ x hx, h x $ Ioc_subset_Icc_self hx in by simpa only [integral_of_le hab] using set_integral_mono_on hf.1 hg.1 measurable_set_Ioc H lemma integral_mono (h : f ≤ g) : ∫ u in a..b, f u ∂μ ≤ ∫ u in a..b, g u ∂μ := integral_mono_ae hab hf hg $ ae_of_all _ h omit hg hab lemma integral_mono_interval {c d} (hca : c ≤ a) (hab : a ≤ b) (hbd : b ≤ d) (hf : 0 ≤ᵐ[μ.restrict (Ioc c d)] f) (hfi : interval_integrable f μ c d): ∫ x in a..b, f x ∂μ ≤ ∫ x in c..d, f x ∂μ := begin rw [integral_of_le hab, integral_of_le (hca.trans (hab.trans hbd))], exact set_integral_mono_set hfi.1 hf (Ioc_subset_Ioc hca hbd).eventually_le end lemma abs_integral_mono_interval {c d } (h : Ι a b ⊆ Ι c d) (hf : 0 ≤ᵐ[μ.restrict (Ι c d)] f) (hfi : interval_integrable f μ c d) : |∫ x in a..b, f x ∂μ| ≤ |∫ x in c..d, f x ∂μ| := have hf' : 0 ≤ᵐ[μ.restrict (Ι a b)] f, from ae_mono (measure.restrict_mono h le_rfl) hf, calc |∫ x in a..b, f x ∂μ| = |∫ x in Ι a b, f x ∂μ| : abs_integral_eq_abs_integral_uIoc f ... = ∫ x in Ι a b, f x ∂μ : abs_of_nonneg (measure_theory.integral_nonneg_of_ae hf') ... ≤ ∫ x in Ι c d, f x ∂μ : set_integral_mono_set hfi.def hf h.eventually_le ... ≤ |∫ x in Ι c d, f x ∂μ| : le_abs_self _ ... = |∫ x in c..d, f x ∂μ| : (abs_integral_eq_abs_integral_uIoc f).symm end mono end section has_sum variables {μ : measure ℝ} {f : ℝ → E} lemma _root_.measure_theory.integrable.has_sum_interval_integral (hfi : integrable f μ) (y : ℝ) : has_sum (λ (n : ℤ), ∫ x in (y + n)..(y + n + 1), f x ∂μ) (∫ x, f x ∂μ) := begin simp_rw integral_of_le (le_add_of_nonneg_right zero_le_one), rw [←integral_univ, ←Union_Ioc_add_int_cast y], exact has_sum_integral_Union (λ i, measurable_set_Ioc) (pairwise_disjoint_Ioc_add_int_cast y) hfi.integrable_on, end lemma _root_.measure_theory.integrable.has_sum_interval_integral_comp_add_int (hfi : integrable f) : has_sum (λ (n : ℤ), ∫ x in 0..1, f (x + n)) (∫ x, f x) := begin convert hfi.has_sum_interval_integral 0 using 2, ext1 n, rw [integral_comp_add_right, zero_add, add_comm], end end has_sum end interval_integral
6929e921fba26256a13f541a74fac1f272381be6
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/interactive/rb_map_ts.lean
89aa26bc61d6af3956c8f9e06cd0372264eb874a
[ "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,271
lean
meta def mytac := state_t (name_map nat) tactic section local attribute [reducible] mytac meta instance : monad mytac := by apply_instance meta instance : monad_state (name_map nat) mytac := by apply_instance meta instance : has_monad_lift tactic mytac := by apply_instance end meta instance (α : Type) : has_coe (tactic α) (mytac α) := ⟨monad_lift⟩ namespace mytac meta def step {α : Type} (t : mytac α) : mytac unit := t >> return () meta def istep {α : Type} (line0 col0 line col _ : nat) (t : mytac α) : mytac unit := ⟨λ v s, result.cases_on (@scope_trace _ line col (λ_, t.run v s)) (λ ⟨a, v⟩ new_s, result.success ((), v) new_s) (λ opt_msg_thunk e new_s, match opt_msg_thunk with | some msg_thunk := let msg := λ _ : unit, msg_thunk () ++ format.line ++ to_fmt "value: " ++ to_fmt v ++ format.line ++ to_fmt "state:" ++ format.line ++ new_s^.to_format in interaction_monad.result.exception (some msg) (some ⟨line, col⟩) new_s | none := interaction_monad.silent_fail new_s end)⟩ meta instance : interactive.executor mytac := { config_type := unit, execute_with := λ _ tac, tac.run (name_map.mk nat) >> return () } meta def save_info (p : pos) : mytac unit := do v ← get, s ← tactic.read, tactic.save_info_thunk p (λ _, to_fmt "Custom state: " ++ to_fmt v ++ format.line ++ tactic_state.to_format s) namespace interactive meta def intros : mytac unit := tactic.intros >> return () meta def constructor : mytac unit := tactic.constructor >> return () meta def trace (s : string) : mytac unit := tactic.trace s meta def assumption : mytac unit := tactic.assumption open lean.parser open _root_.interactive open interactive.types meta def add (n : parse ident) (v : nat) : mytac punit := modify (λ m, m.insert n v) end interactive end mytac lemma ex₁ (p q : Prop) : p → q → p ∧ q := begin [mytac] intros, add x 10, trace "test", --^ "command": "info" constructor, add y 20, assumption, --^ "command": "info" assumption end #print ex₁ lemma ex₂ (p q : Prop) : p → q → p ∧ q := begin [mytac] intros, add x 10, trace "test", constructor, add y 20, assumption, --^ "command": "info" assumption end #print ex₂
a1552a6beff5656984d5bfbe95ee05edb124e309
82e44445c70db0f03e30d7be725775f122d72f3e
/src/data/nat/gcd.lean
95b497ac939650342f0040ef8121bf90ef3e054d
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
17,936
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura -/ import data.nat.pow /-! # Definitions and properties of `gcd`, `lcm`, and `coprime` -/ namespace nat /-! ### `gcd` -/ theorem gcd_dvd (m n : ℕ) : (gcd m n ∣ m) ∧ (gcd m n ∣ n) := gcd.induction m n (λn, by rw gcd_zero_left; exact ⟨dvd_zero n, dvd_refl n⟩) (λm n npos, by rw ←gcd_rec; exact λ ⟨IH₁, IH₂⟩, ⟨IH₂, (dvd_mod_iff IH₂).1 IH₁⟩) theorem gcd_dvd_left (m n : ℕ) : gcd m n ∣ m := (gcd_dvd m n).left theorem gcd_dvd_right (m n : ℕ) : gcd m n ∣ n := (gcd_dvd m n).right theorem gcd_le_left {m} (n) (h : 0 < m) : gcd m n ≤ m := le_of_dvd h $ gcd_dvd_left m n theorem gcd_le_right (m) {n} (h : 0 < n) : gcd m n ≤ n := le_of_dvd h $ gcd_dvd_right m n theorem dvd_gcd {m n k : ℕ} : k ∣ m → k ∣ n → k ∣ gcd m n := gcd.induction m n (λn _ kn, by rw gcd_zero_left; exact kn) (λn m mpos IH H1 H2, by rw gcd_rec; exact IH ((dvd_mod_iff H1).2 H2) H1) theorem dvd_gcd_iff {m n k : ℕ} : k ∣ gcd m n ↔ k ∣ m ∧ k ∣ n := iff.intro (λ h, ⟨dvd_trans h (gcd_dvd m n).left, dvd_trans h (gcd_dvd m n).right⟩) (λ h, dvd_gcd h.left h.right) theorem gcd_comm (m n : ℕ) : gcd m n = gcd n m := dvd_antisymm (dvd_gcd (gcd_dvd_right m n) (gcd_dvd_left m n)) (dvd_gcd (gcd_dvd_right n m) (gcd_dvd_left n m)) theorem gcd_eq_left_iff_dvd {m n : ℕ} : m ∣ n ↔ gcd m n = m := ⟨λ h, by rw [gcd_rec, mod_eq_zero_of_dvd h, gcd_zero_left], λ h, h ▸ gcd_dvd_right m n⟩ theorem gcd_eq_right_iff_dvd {m n : ℕ} : m ∣ n ↔ gcd n m = m := by rw gcd_comm; apply gcd_eq_left_iff_dvd theorem gcd_assoc (m n k : ℕ) : gcd (gcd m n) k = gcd m (gcd n k) := dvd_antisymm (dvd_gcd (dvd.trans (gcd_dvd_left (gcd m n) k) (gcd_dvd_left m n)) (dvd_gcd (dvd.trans (gcd_dvd_left (gcd m n) k) (gcd_dvd_right m n)) (gcd_dvd_right (gcd m n) k))) (dvd_gcd (dvd_gcd (gcd_dvd_left m (gcd n k)) (dvd.trans (gcd_dvd_right m (gcd n k)) (gcd_dvd_left n k))) (dvd.trans (gcd_dvd_right m (gcd n k)) (gcd_dvd_right n k))) @[simp] theorem gcd_one_right (n : ℕ) : gcd n 1 = 1 := eq.trans (gcd_comm n 1) $ gcd_one_left n theorem gcd_mul_left (m n k : ℕ) : gcd (m * n) (m * k) = m * gcd n k := gcd.induction n k (λk, by repeat {rw mul_zero <|> rw gcd_zero_left}) (λk n H IH, by rwa [←mul_mod_mul_left, ←gcd_rec, ←gcd_rec] at IH) theorem gcd_mul_right (m n k : ℕ) : gcd (m * n) (k * n) = gcd m k * n := by rw [mul_comm m n, mul_comm k n, mul_comm (gcd m k) n, gcd_mul_left] theorem gcd_pos_of_pos_left {m : ℕ} (n : ℕ) (mpos : 0 < m) : 0 < gcd m n := pos_of_dvd_of_pos (gcd_dvd_left m n) mpos theorem gcd_pos_of_pos_right (m : ℕ) {n : ℕ} (npos : 0 < n) : 0 < gcd m n := pos_of_dvd_of_pos (gcd_dvd_right m n) npos theorem eq_zero_of_gcd_eq_zero_left {m n : ℕ} (H : gcd m n = 0) : m = 0 := or.elim (eq_zero_or_pos m) id (assume H1 : 0 < m, absurd (eq.symm H) (ne_of_lt (gcd_pos_of_pos_left _ H1))) theorem eq_zero_of_gcd_eq_zero_right {m n : ℕ} (H : gcd m n = 0) : n = 0 := by rw gcd_comm at H; exact eq_zero_of_gcd_eq_zero_left H theorem gcd_div {m n k : ℕ} (H1 : k ∣ m) (H2 : k ∣ n) : gcd (m / k) (n / k) = gcd m n / k := or.elim (eq_zero_or_pos k) (λk0, by rw [k0, nat.div_zero, nat.div_zero, nat.div_zero, gcd_zero_right]) (λH3, nat.eq_of_mul_eq_mul_right H3 $ by rw [ nat.div_mul_cancel (dvd_gcd H1 H2), ←gcd_mul_right, nat.div_mul_cancel H1, nat.div_mul_cancel H2]) theorem gcd_dvd_gcd_of_dvd_left {m k : ℕ} (n : ℕ) (H : m ∣ k) : gcd m n ∣ gcd k n := dvd_gcd (dvd.trans (gcd_dvd_left m n) H) (gcd_dvd_right m n) theorem gcd_dvd_gcd_of_dvd_right {m k : ℕ} (n : ℕ) (H : m ∣ k) : gcd n m ∣ gcd n k := dvd_gcd (gcd_dvd_left n m) (dvd.trans (gcd_dvd_right n m) H) theorem gcd_dvd_gcd_mul_left (m n k : ℕ) : gcd m n ∣ gcd (k * m) n := gcd_dvd_gcd_of_dvd_left _ (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right (m n k : ℕ) : gcd m n ∣ gcd (m * k) n := gcd_dvd_gcd_of_dvd_left _ (dvd_mul_right _ _) theorem gcd_dvd_gcd_mul_left_right (m n k : ℕ) : gcd m n ∣ gcd m (k * n) := gcd_dvd_gcd_of_dvd_right _ (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right_right (m n k : ℕ) : gcd m n ∣ gcd m (n * k) := gcd_dvd_gcd_of_dvd_right _ (dvd_mul_right _ _) theorem gcd_eq_left {m n : ℕ} (H : m ∣ n) : gcd m n = m := dvd_antisymm (gcd_dvd_left _ _) (dvd_gcd (dvd_refl _) H) theorem gcd_eq_right {m n : ℕ} (H : n ∣ m) : gcd m n = n := by rw [gcd_comm, gcd_eq_left H] @[simp] lemma gcd_mul_left_left (m n : ℕ) : gcd (m * n) n = n := dvd_antisymm (gcd_dvd_right _ _) (dvd_gcd (dvd_mul_left _ _) (dvd_refl _)) @[simp] lemma gcd_mul_left_right (m n : ℕ) : gcd n (m * n) = n := by rw [gcd_comm, gcd_mul_left_left] @[simp] lemma gcd_mul_right_left (m n : ℕ) : gcd (n * m) n = n := by rw [mul_comm, gcd_mul_left_left] @[simp] lemma gcd_mul_right_right (m n : ℕ) : gcd n (n * m) = n := by rw [gcd_comm, gcd_mul_right_left] @[simp] lemma gcd_gcd_self_right_left (m n : ℕ) : gcd m (gcd m n) = gcd m n := dvd_antisymm (gcd_dvd_right _ _) (dvd_gcd (gcd_dvd_left _ _) (dvd_refl _)) @[simp] lemma gcd_gcd_self_right_right (m n : ℕ) : gcd m (gcd n m) = gcd n m := by rw [gcd_comm n m, gcd_gcd_self_right_left] @[simp] lemma gcd_gcd_self_left_right (m n : ℕ) : gcd (gcd n m) m = gcd n m := by rw [gcd_comm, gcd_gcd_self_right_right] @[simp] lemma gcd_gcd_self_left_left (m n : ℕ) : gcd (gcd m n) m = gcd m n := by rw [gcd_comm m n, gcd_gcd_self_left_right] lemma gcd_add_mul_self (m n k : ℕ) : gcd m (n + k * m) = gcd m n := by simp [gcd_rec m (n + k * m), gcd_rec m n] theorem gcd_eq_zero_iff {i j : ℕ} : gcd i j = 0 ↔ i = 0 ∧ j = 0 := begin split, { intro h, exact ⟨eq_zero_of_gcd_eq_zero_left h, eq_zero_of_gcd_eq_zero_right h⟩, }, { intro h, rw [h.1, h.2], exact nat.gcd_zero_right _ } end /-! ### `lcm` -/ theorem lcm_comm (m n : ℕ) : lcm m n = lcm n m := by delta lcm; rw [mul_comm, gcd_comm] @[simp] theorem lcm_zero_left (m : ℕ) : lcm 0 m = 0 := by delta lcm; rw [zero_mul, nat.zero_div] @[simp] theorem lcm_zero_right (m : ℕ) : lcm m 0 = 0 := lcm_comm 0 m ▸ lcm_zero_left m @[simp] theorem lcm_one_left (m : ℕ) : lcm 1 m = m := by delta lcm; rw [one_mul, gcd_one_left, nat.div_one] @[simp] theorem lcm_one_right (m : ℕ) : lcm m 1 = m := lcm_comm 1 m ▸ lcm_one_left m @[simp] theorem lcm_self (m : ℕ) : lcm m m = m := or.elim (eq_zero_or_pos m) (λh, by rw [h, lcm_zero_left]) (λh, by delta lcm; rw [gcd_self, nat.mul_div_cancel _ h]) theorem dvd_lcm_left (m n : ℕ) : m ∣ lcm m n := dvd.intro (n / gcd m n) (nat.mul_div_assoc _ $ gcd_dvd_right m n).symm theorem dvd_lcm_right (m n : ℕ) : n ∣ lcm m n := lcm_comm n m ▸ dvd_lcm_left n m theorem gcd_mul_lcm (m n : ℕ) : gcd m n * lcm m n = m * n := by delta lcm; rw [nat.mul_div_cancel' (dvd.trans (gcd_dvd_left m n) (dvd_mul_right m n))] theorem lcm_dvd {m n k : ℕ} (H1 : m ∣ k) (H2 : n ∣ k) : lcm m n ∣ k := or.elim (eq_zero_or_pos k) (λh, by rw h; exact dvd_zero _) (λkpos, dvd_of_mul_dvd_mul_left (gcd_pos_of_pos_left n (pos_of_dvd_of_pos H1 kpos)) $ by rw [gcd_mul_lcm, ←gcd_mul_right, mul_comm n k]; exact dvd_gcd (mul_dvd_mul_left _ H2) (mul_dvd_mul_right H1 _)) lemma lcm_dvd_iff {m n k : ℕ} : lcm m n ∣ k ↔ m ∣ k ∧ n ∣ k := ⟨λ h, ⟨dvd_trans (dvd_lcm_left _ _) h, dvd_trans (dvd_lcm_right _ _) h⟩, and_imp.2 lcm_dvd⟩ theorem lcm_assoc (m n k : ℕ) : lcm (lcm m n) k = lcm m (lcm n k) := dvd_antisymm (lcm_dvd (lcm_dvd (dvd_lcm_left m (lcm n k)) (dvd.trans (dvd_lcm_left n k) (dvd_lcm_right m (lcm n k)))) (dvd.trans (dvd_lcm_right n k) (dvd_lcm_right m (lcm n k)))) (lcm_dvd (dvd.trans (dvd_lcm_left m n) (dvd_lcm_left (lcm m n) k)) (lcm_dvd (dvd.trans (dvd_lcm_right m n) (dvd_lcm_left (lcm m n) k)) (dvd_lcm_right (lcm m n) k))) theorem lcm_ne_zero {m n : ℕ} (hm : m ≠ 0) (hn : n ≠ 0) : lcm m n ≠ 0 := by { intro h, simpa [h, hm, hn] using gcd_mul_lcm m n, } /-! ### `coprime` See also `nat.coprime_of_dvd` and `nat.coprime_of_dvd'` to prove `nat.coprime m n`. -/ instance (m n : ℕ) : decidable (coprime m n) := by unfold coprime; apply_instance theorem coprime_iff_gcd_eq_one {m n : ℕ} : coprime m n ↔ gcd m n = 1 := iff.rfl theorem coprime.gcd_eq_one {m n : ℕ} : coprime m n → gcd m n = 1 := id theorem coprime.symm {m n : ℕ} : coprime n m → coprime m n := (gcd_comm m n).trans theorem coprime_comm {m n : ℕ} : coprime n m ↔ coprime m n := ⟨coprime.symm, coprime.symm⟩ theorem coprime.dvd_of_dvd_mul_right {m n k : ℕ} (H1 : coprime k n) (H2 : k ∣ m * n) : k ∣ m := let t := dvd_gcd (dvd_mul_left k m) H2 in by rwa [gcd_mul_left, H1.gcd_eq_one, mul_one] at t theorem coprime.dvd_of_dvd_mul_left {m n k : ℕ} (H1 : coprime k m) (H2 : k ∣ m * n) : k ∣ n := by rw mul_comm at H2; exact H1.dvd_of_dvd_mul_right H2 theorem coprime.gcd_mul_left_cancel {k : ℕ} (m : ℕ) {n : ℕ} (H : coprime k n) : gcd (k * m) n = gcd m n := have H1 : coprime (gcd (k * m) n) k, by rw [coprime, gcd_assoc, H.symm.gcd_eq_one, gcd_one_right], dvd_antisymm (dvd_gcd (H1.dvd_of_dvd_mul_left (gcd_dvd_left _ _)) (gcd_dvd_right _ _)) (gcd_dvd_gcd_mul_left _ _ _) theorem coprime.gcd_mul_right_cancel (m : ℕ) {k n : ℕ} (H : coprime k n) : gcd (m * k) n = gcd m n := by rw [mul_comm m k, H.gcd_mul_left_cancel m] theorem coprime.gcd_mul_left_cancel_right {k m : ℕ} (n : ℕ) (H : coprime k m) : gcd m (k * n) = gcd m n := by rw [gcd_comm m n, gcd_comm m (k * n), H.gcd_mul_left_cancel n] theorem coprime.gcd_mul_right_cancel_right {k m : ℕ} (n : ℕ) (H : coprime k m) : gcd m (n * k) = gcd m n := by rw [mul_comm n k, H.gcd_mul_left_cancel_right n] theorem coprime_div_gcd_div_gcd {m n : ℕ} (H : 0 < gcd m n) : coprime (m / gcd m n) (n / gcd m n) := by rw [coprime_iff_gcd_eq_one, gcd_div (gcd_dvd_left m n) (gcd_dvd_right m n), nat.div_self H] theorem not_coprime_of_dvd_of_dvd {m n d : ℕ} (dgt1 : 1 < d) (Hm : d ∣ m) (Hn : d ∣ n) : ¬ coprime m n := λ co, not_lt_of_ge (le_of_dvd zero_lt_one $ by rw [←co.gcd_eq_one]; exact dvd_gcd Hm Hn) dgt1 theorem exists_coprime {m n : ℕ} (H : 0 < gcd m n) : ∃ m' n', coprime m' n' ∧ m = m' * gcd m n ∧ n = n' * gcd m n := ⟨_, _, coprime_div_gcd_div_gcd H, (nat.div_mul_cancel (gcd_dvd_left m n)).symm, (nat.div_mul_cancel (gcd_dvd_right m n)).symm⟩ theorem exists_coprime' {m n : ℕ} (H : 0 < gcd m n) : ∃ g m' n', 0 < g ∧ coprime m' n' ∧ m = m' * g ∧ n = n' * g := let ⟨m', n', h⟩ := exists_coprime H in ⟨_, m', n', H, h⟩ theorem coprime.mul {m n k : ℕ} (H1 : coprime m k) (H2 : coprime n k) : coprime (m * n) k := (H1.gcd_mul_left_cancel n).trans H2 theorem coprime.mul_right {k m n : ℕ} (H1 : coprime k m) (H2 : coprime k n) : coprime k (m * n) := (H1.symm.mul H2.symm).symm theorem coprime.coprime_dvd_left {m k n : ℕ} (H1 : m ∣ k) (H2 : coprime k n) : coprime m n := eq_one_of_dvd_one (by delta coprime at H2; rw ← H2; exact gcd_dvd_gcd_of_dvd_left _ H1) theorem coprime.coprime_dvd_right {m k n : ℕ} (H1 : n ∣ m) (H2 : coprime k m) : coprime k n := (H2.symm.coprime_dvd_left H1).symm theorem coprime.coprime_mul_left {k m n : ℕ} (H : coprime (k * m) n) : coprime m n := H.coprime_dvd_left (dvd_mul_left _ _) theorem coprime.coprime_mul_right {k m n : ℕ} (H : coprime (m * k) n) : coprime m n := H.coprime_dvd_left (dvd_mul_right _ _) theorem coprime.coprime_mul_left_right {k m n : ℕ} (H : coprime m (k * n)) : coprime m n := H.coprime_dvd_right (dvd_mul_left _ _) theorem coprime.coprime_mul_right_right {k m n : ℕ} (H : coprime m (n * k)) : coprime m n := H.coprime_dvd_right (dvd_mul_right _ _) theorem coprime.coprime_div_left {m n a : ℕ} (cmn : coprime m n) (dvd : a ∣ m) : coprime (m / a) n := begin by_cases a_split : (a = 0), { subst a_split, rw zero_dvd_iff at dvd, simpa [dvd] using cmn, }, { rcases dvd with ⟨k, rfl⟩, rw nat.mul_div_cancel_left _ (nat.pos_of_ne_zero a_split), exact coprime.coprime_mul_left cmn, }, end theorem coprime.coprime_div_right {m n a : ℕ} (cmn : coprime m n) (dvd : a ∣ n) : coprime m (n / a) := (coprime.coprime_div_left cmn.symm dvd).symm lemma coprime_mul_iff_left {k m n : ℕ} : coprime (m * n) k ↔ coprime m k ∧ coprime n k := ⟨λ h, ⟨coprime.coprime_mul_right h, coprime.coprime_mul_left h⟩, λ ⟨h, _⟩, by rwa [coprime_iff_gcd_eq_one, coprime.gcd_mul_left_cancel n h]⟩ lemma coprime_mul_iff_right {k m n : ℕ} : coprime k (m * n) ↔ coprime k m ∧ coprime k n := by simpa only [coprime_comm] using coprime_mul_iff_left lemma coprime.gcd_left (k : ℕ) {m n : ℕ} (hmn : coprime m n) : coprime (gcd k m) n := hmn.coprime_dvd_left $ gcd_dvd_right k m lemma coprime.gcd_right (k : ℕ) {m n : ℕ} (hmn : coprime m n) : coprime m (gcd k n) := hmn.coprime_dvd_right $ gcd_dvd_right k n lemma coprime.gcd_both (k l : ℕ) {m n : ℕ} (hmn : coprime m n) : coprime (gcd k m) (gcd l n) := (hmn.gcd_left k).gcd_right l lemma coprime.mul_dvd_of_dvd_of_dvd {a n m : ℕ} (hmn : coprime m n) (hm : m ∣ a) (hn : n ∣ a) : m * n ∣ a := let ⟨k, hk⟩ := hm in hk.symm ▸ mul_dvd_mul_left _ (hmn.symm.dvd_of_dvd_mul_left (hk ▸ hn)) theorem coprime_one_left : ∀ n, coprime 1 n := gcd_one_left theorem coprime_one_right : ∀ n, coprime n 1 := gcd_one_right theorem coprime.pow_left {m k : ℕ} (n : ℕ) (H1 : coprime m k) : coprime (m ^ n) k := nat.rec_on n (coprime_one_left _) (λn IH, H1.mul IH) theorem coprime.pow_right {m k : ℕ} (n : ℕ) (H1 : coprime k m) : coprime k (m ^ n) := (H1.symm.pow_left n).symm theorem coprime.pow {k l : ℕ} (m n : ℕ) (H1 : coprime k l) : coprime (k ^ m) (l ^ n) := (H1.pow_left _).pow_right _ lemma coprime_pow_left_iff {n : ℕ} (hn : 0 < n) (a b : ℕ) : nat.coprime (a ^ n) b ↔ nat.coprime a b := begin obtain ⟨n, rfl⟩ := exists_eq_succ_of_ne_zero hn.ne', rw [pow_succ, nat.coprime_mul_iff_left], exact ⟨and.left, λ hab, ⟨hab, hab.pow_left _⟩⟩ end lemma coprime_pow_right_iff {n : ℕ} (hn : 0 < n) (a b : ℕ) : nat.coprime a (b ^ n) ↔ nat.coprime a b := by rw [nat.coprime_comm, coprime_pow_left_iff hn, nat.coprime_comm] theorem coprime.eq_one_of_dvd {k m : ℕ} (H : coprime k m) (d : k ∣ m) : k = 1 := by rw [← H.gcd_eq_one, gcd_eq_left d] @[simp] theorem coprime_zero_left (n : ℕ) : coprime 0 n ↔ n = 1 := by simp [coprime] @[simp] theorem coprime_zero_right (n : ℕ) : coprime n 0 ↔ n = 1 := by simp [coprime] theorem not_coprime_zero_zero : ¬ coprime 0 0 := by simp @[simp] theorem coprime_one_left_iff (n : ℕ) : coprime 1 n ↔ true := by simp [coprime] @[simp] theorem coprime_one_right_iff (n : ℕ) : coprime n 1 ↔ true := by simp [coprime] @[simp] theorem coprime_self (n : ℕ) : coprime n n ↔ n = 1 := by simp [coprime] lemma coprime.eq_of_mul_eq_zero {m n : ℕ} (h : m.coprime n) (hmn : m * n = 0) : m = 0 ∧ n = 1 ∨ m = 1 ∧ n = 0 := (nat.eq_zero_of_mul_eq_zero hmn).imp (λ hm, ⟨hm, n.coprime_zero_left.mp $ hm ▸ h⟩) (λ hn, ⟨m.coprime_zero_left.mp $ hn ▸ h.symm, hn⟩) /-- Represent a divisor of `m * n` as a product of a divisor of `m` and a divisor of `n`. -/ def prod_dvd_and_dvd_of_dvd_prod {m n k : ℕ} (H : k ∣ m * n) : { d : {m' // m' ∣ m} × {n' // n' ∣ n} // k = d.1 * d.2 } := begin cases h0 : (gcd k m), case nat.zero { have : k = 0 := eq_zero_of_gcd_eq_zero_left h0, subst this, have : m = 0 := eq_zero_of_gcd_eq_zero_right h0, subst this, exact ⟨⟨⟨0, dvd_refl 0⟩, ⟨n, dvd_refl n⟩⟩, (zero_mul n).symm⟩ }, case nat.succ : tmp { have hpos : 0 < gcd k m := h0.symm ▸ nat.zero_lt_succ _; clear h0 tmp, have hd : gcd k m * (k / gcd k m) = k := (nat.mul_div_cancel' (gcd_dvd_left k m)), refine ⟨⟨⟨gcd k m, gcd_dvd_right k m⟩, ⟨k / gcd k m, _⟩⟩, hd.symm⟩, apply dvd_of_mul_dvd_mul_left hpos, rw [hd, ← gcd_mul_right], exact dvd_gcd (dvd_mul_right _ _) H } end theorem gcd_mul_dvd_mul_gcd (k m n : ℕ) : gcd k (m * n) ∣ gcd k m * gcd k n := begin rcases (prod_dvd_and_dvd_of_dvd_prod $ gcd_dvd_right k (m * n)) with ⟨⟨⟨m', hm'⟩, ⟨n', hn'⟩⟩, h⟩, replace h : gcd k (m * n) = m' * n' := h, rw h, have hm'n' : m' * n' ∣ k := h ▸ gcd_dvd_left _ _, apply mul_dvd_mul, { have hm'k : m' ∣ k := dvd_trans (dvd_mul_right m' n') hm'n', exact dvd_gcd hm'k hm' }, { have hn'k : n' ∣ k := dvd_trans (dvd_mul_left n' m') hm'n', exact dvd_gcd hn'k hn' } end theorem coprime.gcd_mul (k : ℕ) {m n : ℕ} (h : coprime m n) : gcd k (m * n) = gcd k m * gcd k n := dvd_antisymm (gcd_mul_dvd_mul_gcd k m n) ((h.gcd_both k k).mul_dvd_of_dvd_of_dvd (gcd_dvd_gcd_mul_right_right _ _ _) (gcd_dvd_gcd_mul_left_right _ _ _)) theorem pow_dvd_pow_iff {a b n : ℕ} (n0 : 0 < n) : a ^ n ∣ b ^ n ↔ a ∣ b := begin refine ⟨λ h, _, λ h, pow_dvd_pow_of_dvd h _⟩, cases eq_zero_or_pos (gcd a b) with g0 g0, { simp [eq_zero_of_gcd_eq_zero_right g0] }, rcases exists_coprime' g0 with ⟨g, a', b', g0', co, rfl, rfl⟩, rw [mul_pow, mul_pow] at h, replace h := dvd_of_mul_dvd_mul_right (pow_pos g0' _) h, have := pow_dvd_pow a' n0, rw [pow_one, (co.pow n n).eq_one_of_dvd h] at this, simp [eq_one_of_dvd_one this] end lemma gcd_mul_gcd_of_coprime_of_mul_eq_mul {a b c d : ℕ} (cop : c.coprime d) (h : a * b = c * d) : a.gcd c * b.gcd c = c := begin apply dvd_antisymm, { apply nat.coprime.dvd_of_dvd_mul_right (nat.coprime.mul (cop.gcd_left _) (cop.gcd_left _)), rw ← h, apply mul_dvd_mul (gcd_dvd _ _).1 (gcd_dvd _ _).1 }, { rw [gcd_comm a _, gcd_comm b _], transitivity c.gcd (a * b), rw [h, gcd_mul_right_right d c], apply gcd_mul_dvd_mul_gcd } end end nat
c662d8f5dd5a275b67c9eca5d2d5aa162f83833b
1dd482be3f611941db7801003235dc84147ec60a
/src/algebra/archimedean.lean
aae19e4f41140173204ee7a83ad3f7ce907a87a9
[ "Apache-2.0" ]
permissive
sanderdahmen/mathlib
479039302bd66434bb5672c2a4cecf8d69981458
8f0eae75cd2d8b7a083cf935666fcce4565df076
refs/heads/master
1,587,491,322,775
1,549,672,060,000
1,549,672,060,000
169,748,224
0
0
Apache-2.0
1,549,636,694,000
1,549,636,694,000
null
UTF-8
Lean
false
false
10,994
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Archimedean groups and fields. -/ import algebra.group_power data.rat tactic.linarith local infix ` • ` := add_monoid.smul variables {α : Type*} class floor_ring (α) [linear_ordered_ring α] := (floor : α → ℤ) (le_floor : ∀ (z : ℤ) (x : α), z ≤ floor x ↔ (z : α) ≤ x) instance : floor_ring ℤ := { floor := id, le_floor := λ _ _, by rw int.cast_id; refl } instance : floor_ring ℚ := { floor := rat.floor, le_floor := @rat.le_floor } section variables [linear_ordered_ring α] [floor_ring α] def floor : α → ℤ := floor_ring.floor notation `⌊` x `⌋` := floor x theorem le_floor : ∀ {z : ℤ} {x : α}, z ≤ ⌊x⌋ ↔ (z : α) ≤ x := floor_ring.le_floor theorem floor_lt {x : α} {z : ℤ} : ⌊x⌋ < z ↔ x < z := lt_iff_lt_of_le_iff_le le_floor theorem floor_le (x : α) : (⌊x⌋ : α) ≤ x := le_floor.1 (le_refl _) theorem floor_nonneg {x : α} : 0 ≤ ⌊x⌋ ↔ 0 ≤ x := by rw [le_floor]; refl theorem lt_succ_floor (x : α) : x < ⌊x⌋.succ := floor_lt.1 $ int.lt_succ_self _ theorem lt_floor_add_one (x : α) : x < ⌊x⌋ + 1 := by simpa only [int.succ, int.cast_add, int.cast_one] using lt_succ_floor x theorem sub_one_lt_floor (x : α) : x - 1 < ⌊x⌋ := sub_lt_iff_lt_add.2 (lt_floor_add_one x) @[simp] theorem floor_coe (z : ℤ) : ⌊(z:α)⌋ = z := eq_of_forall_le_iff $ λ a, by rw [le_floor, int.cast_le] @[simp] theorem floor_zero : ⌊(0:α)⌋ = 0 := floor_coe 0 @[simp] theorem floor_one : ⌊(1:α)⌋ = 1 := by rw [← int.cast_one, floor_coe] theorem floor_mono {a b : α} (h : a ≤ b) : ⌊a⌋ ≤ ⌊b⌋ := le_floor.2 (le_trans (floor_le _) h) @[simp] theorem floor_add_int (x : α) (z : ℤ) : ⌊x + z⌋ = ⌊x⌋ + z := eq_of_forall_le_iff $ λ a, by rw [le_floor, ← sub_le_iff_le_add, ← sub_le_iff_le_add, le_floor, int.cast_sub] theorem floor_sub_int (x : α) (z : ℤ) : ⌊x - z⌋ = ⌊x⌋ - z := eq.trans (by rw [int.cast_neg]; refl) (floor_add_int _ _) lemma abs_sub_lt_one_of_floor_eq_floor {α : Type*} [decidable_linear_ordered_comm_ring α] [floor_ring α] {x y : α} (h : floor x = floor y) : abs (x - y) < 1 := begin have : x < (floor x) + 1 := lt_floor_add_one x, have : y < (floor y) + 1 := lt_floor_add_one y, have : ((floor x) : α) = floor y := int.cast_inj.2 h, have : ((floor x) : α) ≤ x := floor_le x, have : ((floor y) : α) ≤ y := floor_le y, exact abs_sub_lt_iff.2 ⟨by linarith, by linarith⟩ end /-- `ceil x` is the smallest integer `z` such that `x ≤ z` -/ def ceil (x : α) : ℤ := -⌊-x⌋ notation `⌈` x `⌉` := ceil x theorem ceil_le {z : ℤ} {x : α} : ⌈x⌉ ≤ z ↔ x ≤ z := by rw [ceil, neg_le, le_floor, int.cast_neg, neg_le_neg_iff] theorem lt_ceil {x : α} {z : ℤ} : z < ⌈x⌉ ↔ (z:α) < x := lt_iff_lt_of_le_iff_le ceil_le theorem le_ceil (x : α) : x ≤ ⌈x⌉ := ceil_le.1 (le_refl _) @[simp] theorem ceil_coe (z : ℤ) : ⌈(z:α)⌉ = z := by rw [ceil, ← int.cast_neg, floor_coe, neg_neg] theorem ceil_mono {a b : α} (h : a ≤ b) : ⌈a⌉ ≤ ⌈b⌉ := ceil_le.2 (le_trans h (le_ceil _)) @[simp] theorem ceil_add_int (x : α) (z : ℤ) : ⌈x + z⌉ = ⌈x⌉ + z := by rw [ceil, neg_add', floor_sub_int, neg_sub, sub_eq_neg_add]; refl theorem ceil_sub_int (x : α) (z : ℤ) : ⌈x - z⌉ = ⌈x⌉ - z := eq.trans (by rw [int.cast_neg]; refl) (ceil_add_int _ _) theorem ceil_lt_add_one (x : α) : (⌈x⌉ : α) < x + 1 := by rw [← lt_ceil, ← int.cast_one, ceil_add_int]; apply lt_add_one lemma ceil_pos {a : α} : 0 < ⌈a⌉ ↔ 0 < a := ⟨ λ h, have ⌊-a⌋ < 0, from neg_of_neg_pos h, pos_of_neg_neg $ lt_of_not_ge $ (not_iff_not_of_iff floor_nonneg).1 $ not_le_of_gt this, λ h, have -a < 0, from neg_neg_of_pos h, neg_pos_of_neg $ lt_of_not_ge $ (not_iff_not_of_iff floor_nonneg).2 $ not_le_of_gt this ⟩ @[simp] theorem ceil_zero : ⌈(0 : α)⌉ = 0 := by simp [ceil] lemma ceil_nonneg [decidable_rel ((<) : α → α → Prop)] {q : α} (hq : q ≥ 0) : ⌈q⌉ ≥ 0 := if h : q > 0 then le_of_lt $ ceil_pos.2 h else by rw [le_antisymm (le_of_not_lt h) hq, ceil_zero]; trivial end class archimedean (α) [ordered_comm_monoid α] : Prop := (arch : ∀ (x : α) {y}, 0 < y → ∃ n : ℕ, x ≤ n • y) theorem exists_nat_gt [linear_ordered_semiring α] [archimedean α] (x : α) : ∃ n : ℕ, x < n := let ⟨n, h⟩ := archimedean.arch x zero_lt_one in ⟨n+1, lt_of_le_of_lt (by rwa ← add_monoid.smul_one) (nat.cast_lt.2 (nat.lt_succ_self _))⟩ section linear_ordered_ring variables [linear_ordered_ring α] [archimedean α] lemma pow_unbounded_of_gt_one (x : α) {y : α} (hy1 : 1 < y) : ∃ n : ℕ, x < y ^ n := have hy0 : 0 < y - 1 := sub_pos_of_lt hy1, let ⟨n, h⟩ := archimedean.arch x hy0 in ⟨n, calc x ≤ n • (y - 1) : h ... < 1 + n • (y - 1) : by rw add_comm; exact lt_add_one _ ... ≤ y ^ n : pow_ge_one_add_sub_mul (le_of_lt hy1) _⟩ theorem exists_int_gt (x : α) : ∃ n : ℤ, x < n := let ⟨n, h⟩ := exists_nat_gt x in ⟨n, by rwa ← coe_coe⟩ theorem exists_int_lt (x : α) : ∃ n : ℤ, (n : α) < x := let ⟨n, h⟩ := exists_int_gt (-x) in ⟨-n, by rw int.cast_neg; exact neg_lt.1 h⟩ theorem exists_floor (x : α) : ∃ (fl : ℤ), ∀ (z : ℤ), z ≤ fl ↔ (z : α) ≤ x := begin haveI := classical.prop_decidable, have : ∃ (ub : ℤ), (ub:α) ≤ x ∧ ∀ (z : ℤ), (z:α) ≤ x → z ≤ ub := int.exists_greatest_of_bdd (let ⟨n, hn⟩ := exists_int_gt x in ⟨n, λ z h', int.cast_le.1 $ le_trans h' $ le_of_lt hn⟩) (let ⟨n, hn⟩ := exists_int_lt x in ⟨n, le_of_lt hn⟩), refine this.imp (λ fl h z, _), cases h with h₁ h₂, exact ⟨λ h, le_trans (int.cast_le.2 h) h₁, h₂ z⟩, end end linear_ordered_ring section linear_ordered_field variables [linear_ordered_field α] [floor_ring α] lemma sub_floor_div_mul_nonneg (x : α) {y : α} (hy : 0 < y) : 0 ≤ x - ⌊x / y⌋ * y := begin conv in x {rw ← div_mul_cancel x (ne_of_lt hy).symm}, rw ← sub_mul, exact mul_nonneg (sub_nonneg.2 (floor_le _)) (le_of_lt hy) end lemma sub_floor_div_mul_lt (x : α) {y : α} (hy : 0 < y) : x - ⌊x / y⌋ * y < y := sub_lt_iff_lt_add.2 begin conv in y {rw ← one_mul y}, conv in x {rw ← div_mul_cancel x (ne_of_lt hy).symm}, rw ← add_mul, exact (mul_lt_mul_right hy).2 (by rw add_comm; exact lt_floor_add_one _), end end linear_ordered_field instance : archimedean ℕ := ⟨λ n m m0, ⟨n, by simpa only [mul_one, nat.smul_eq_mul] using nat.mul_le_mul_left n m0⟩⟩ instance : archimedean ℤ := ⟨λ n m m0, ⟨n.to_nat, le_trans (int.le_to_nat _) $ by simpa only [add_monoid.smul_eq_mul, int.nat_cast_eq_coe_nat, zero_add, mul_one] using mul_le_mul_of_nonneg_left (int.add_one_le_iff.2 m0) (int.coe_zero_le n.to_nat)⟩⟩ noncomputable def archimedean.floor_ring (α) [linear_ordered_ring α] [archimedean α] : floor_ring α := { floor := λ x, classical.some (exists_floor x), le_floor := λ z x, classical.some_spec (exists_floor x) z } section linear_ordered_field variables [linear_ordered_field α] theorem archimedean_iff_nat_lt : archimedean α ↔ ∀ x : α, ∃ n : ℕ, x < n := ⟨@exists_nat_gt α _, λ H, ⟨λ x y y0, (H (x / y)).imp $ λ n h, le_of_lt $ by rwa [div_lt_iff y0, ← add_monoid.smul_eq_mul] at h⟩⟩ theorem archimedean_iff_nat_le : archimedean α ↔ ∀ x : α, ∃ n : ℕ, x ≤ n := archimedean_iff_nat_lt.trans ⟨λ H x, (H x).imp $ λ _, le_of_lt, λ H x, let ⟨n, h⟩ := H x in ⟨n+1, lt_of_le_of_lt h (nat.cast_lt.2 (lt_add_one _))⟩⟩ theorem exists_rat_gt [archimedean α] (x : α) : ∃ q : ℚ, x < q := let ⟨n, h⟩ := exists_nat_gt x in ⟨n, by rwa rat.cast_coe_nat⟩ theorem archimedean_iff_rat_lt : archimedean α ↔ ∀ x : α, ∃ q : ℚ, x < q := ⟨@exists_rat_gt α _, λ H, archimedean_iff_nat_lt.2 $ λ x, let ⟨q, h⟩ := H x in ⟨rat.nat_ceil q, lt_of_lt_of_le h $ by simpa only [rat.cast_coe_nat] using (@rat.cast_le α _ _ _).2 (rat.le_nat_ceil _)⟩⟩ theorem archimedean_iff_rat_le : archimedean α ↔ ∀ x : α, ∃ q : ℚ, x ≤ q := archimedean_iff_rat_lt.trans ⟨λ H x, (H x).imp $ λ _, le_of_lt, λ H x, let ⟨n, h⟩ := H x in ⟨n+1, lt_of_le_of_lt h (rat.cast_lt.2 (lt_add_one _))⟩⟩ variable [archimedean α] theorem exists_rat_lt (x : α) : ∃ q : ℚ, (q : α) < x := let ⟨n, h⟩ := exists_int_lt x in ⟨n, by rwa rat.cast_coe_int⟩ theorem exists_rat_btwn {x y : α} (h : x < y) : ∃ q : ℚ, x < q ∧ (q:α) < y := begin cases exists_nat_gt (y - x)⁻¹ with n nh, cases exists_floor (x * n) with z zh, refine ⟨(z + 1 : ℤ) / n, _⟩, have n0 := nat.cast_pos.1 (lt_trans (inv_pos (sub_pos.2 h)) nh), have n0' := (@nat.cast_pos α _ _).2 n0, rw [rat.cast_div_of_ne_zero, rat.cast_coe_nat, rat.cast_coe_int, div_lt_iff n0'], refine ⟨(lt_div_iff n0').2 $ (lt_iff_lt_of_le_iff_le (zh _)).1 (lt_add_one _), _⟩, rw [int.cast_add, int.cast_one], refine lt_of_le_of_lt (add_le_add_right ((zh _).1 (le_refl _)) _) _, rwa [← lt_sub_iff_add_lt', ← sub_mul, ← div_lt_iff' (sub_pos.2 h), one_div_eq_inv], { rw [rat.coe_int_denom, nat.cast_one], exact one_ne_zero }, { intro H, rw [rat.coe_nat_num, ← coe_coe, nat.cast_eq_zero] at H, subst H, cases n0 }, { rw [rat.coe_nat_denom, nat.cast_one], exact one_ne_zero } end theorem exists_nat_one_div_lt {ε : α} (hε : ε > 0) : ∃ n : ℕ, 1 / (n + 1: α) < ε := begin cases archimedean_iff_nat_lt.1 (by apply_instance) (1/ε) with n hn, existsi n, apply div_lt_of_mul_lt_of_pos, { simp, apply add_pos_of_pos_of_nonneg zero_lt_one, apply nat.cast_nonneg }, { apply (div_lt_iff' hε).1, transitivity, { exact hn }, { simp [zero_lt_one] }} end theorem exists_pos_rat_lt {x : α} (x0 : 0 < x) : ∃ q : ℚ, 0 < q ∧ (q : α) < x := by simpa only [rat.cast_pos] using exists_rat_btwn x0 include α @[simp] theorem rat.cast_floor (x : ℚ) : by haveI := archimedean.floor_ring α; exact ⌊(x:α)⌋ = ⌊x⌋ := begin haveI := archimedean.floor_ring α, apply le_antisymm, { rw [le_floor, ← @rat.cast_le α, rat.cast_coe_int], apply floor_le }, { rw [le_floor, ← rat.cast_coe_int, rat.cast_le], apply floor_le } end end linear_ordered_field section variables [discrete_linear_ordered_field α] [archimedean α] theorem exists_rat_near (x : α) {ε : α} (ε0 : ε > 0) : ∃ q : ℚ, abs (x - q) < ε := let ⟨q, h₁, h₂⟩ := exists_rat_btwn $ lt_trans ((sub_lt_self_iff x).2 ε0) ((lt_add_iff_pos_left x).2 ε0) in ⟨q, abs_sub_lt_iff.2 ⟨sub_lt.1 h₁, sub_lt_iff_lt_add.2 h₂⟩⟩ end instance : archimedean ℚ := archimedean_iff_rat_le.2 $ λ q, ⟨q, by rw rat.cast_id⟩
d20c80ca241ee15191018aafa3fb793561f7b02f
f57570f33b51ef0271f8c366142363d5ae8fff45
/src/formalizing_logic.lean
6744c2c69eb2b253eaba652ec65d21c5752aa638
[]
no_license
maxd13/lean-logic
4083cb3fbb45b423befca7fda7268b8ba85ff3a6
ddcab46b77adca91b120a5f37afbd48794da8b52
refs/heads/master
1,692,257,681,488
1,631,740,832,000
1,631,740,832,000
246,324,437
0
0
null
null
null
null
UTF-8
Lean
false
false
345
lean
import data.set.finite data.set.countable order.bounded_lattice init.data.list tactic computability.primrec formal_system propositional_logic -- tactic.tidy tactic.find --.philosophy.Interpretation_PeterChen_ER -- We formalize several logical systems. open set lattice logic universe u --local attribute [instance] classical.prop_decidable
3acb9c2bb6f052b44e4ee404d1d5e387313d3b4d
94e33a31faa76775069b071adea97e86e218a8ee
/src/category_theory/monoidal/of_chosen_finite_products.lean
9e822085b515c5ed07a6cb7792461d5fb8a235e0
[ "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
16,186
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Simon Hudon -/ import category_theory.monoidal.braided import category_theory.limits.shapes.binary_products import category_theory.limits.shapes.terminal import category_theory.pempty /-! # The monoidal structure on a category with chosen finite products. This is a variant of the development in `category_theory.monoidal.of_has_finite_products`, which uses specified choices of the terminal object and binary product, enabling the construction of a cartesian category with specific definitions of the tensor unit and tensor product. (Because the construction in `category_theory.monoidal.of_has_finite_products` uses `has_limit` classes, the actual definitions there are opaque behind `classical.choice`.) We use this in `category_theory.monoidal.types` to construct the monoidal category of types so that the tensor product is the usual cartesian product of types. For now we only do the construction from products, and not from coproducts, which seems less often useful. -/ universes v u noncomputable theory namespace category_theory variables (C : Type u) [category.{v} C] {X Y : C} namespace limits section variables {C} /-- Swap the two sides of a `binary_fan`. -/ def binary_fan.swap {P Q : C} (t : binary_fan P Q) : binary_fan Q P := binary_fan.mk t.snd t.fst @[simp] lemma binary_fan.swap_fst {P Q : C} (t : binary_fan P Q) : t.swap.fst = t.snd := rfl @[simp] lemma binary_fan.swap_snd {P Q : C} (t : binary_fan P Q) : t.swap.snd = t.fst := rfl /-- If a cone `t` over `P Q` is a limit cone, then `t.swap` is a limit cone over `Q P`. -/ @[simps] def is_limit.swap_binary_fan {P Q : C} {t : binary_fan P Q} (I : is_limit t) : is_limit t.swap := { lift := λ s, I.lift (binary_fan.swap s), fac' := λ s, by { rintro ⟨⟨⟩⟩; simp, }, uniq' := λ s m w, begin have h := I.uniq (binary_fan.swap s) m, rw h, rintro ⟨j⟩, specialize w ⟨j.swap⟩, cases j; exact w, end } /-- Construct `has_binary_product Q P` from `has_binary_product P Q`. This can't be an instance, as it would cause a loop in typeclass search. -/ lemma has_binary_product.swap (P Q : C) [has_binary_product P Q] : has_binary_product Q P := has_limit.mk ⟨binary_fan.swap (limit.cone (pair P Q)), (limit.is_limit (pair P Q)).swap_binary_fan⟩ /-- Given a limit cone over `X` and `Y`, and another limit cone over `Y` and `X`, we can construct an isomorphism between the cone points. Relative to some fixed choice of limits cones for every pair, these isomorphisms constitute a braiding. -/ def binary_fan.braiding {X Y : C} {s : binary_fan X Y} (P : is_limit s) {t : binary_fan Y X} (Q : is_limit t) : s.X ≅ t.X := is_limit.cone_point_unique_up_to_iso P Q.swap_binary_fan /-- Given binary fans `sXY` over `X Y`, and `sYZ` over `Y Z`, and `s` over `sXY.X Z`, if `sYZ` is a limit cone we can construct a binary fan over `X sYZ.X`. This is an ingredient of building the associator for a cartesian category. -/ def binary_fan.assoc {X Y Z : C} {sXY : binary_fan X Y} {sYZ : binary_fan Y Z} (Q : is_limit sYZ) (s : binary_fan sXY.X Z) : binary_fan X sYZ.X := binary_fan.mk (s.fst ≫ sXY.fst) (Q.lift (binary_fan.mk (s.fst ≫ sXY.snd) s.snd)) @[simp] lemma binary_fan.assoc_fst {X Y Z : C} {sXY : binary_fan X Y} {sYZ : binary_fan Y Z} (Q : is_limit sYZ) (s : binary_fan sXY.X Z) : (s.assoc Q).fst = s.fst ≫ sXY.fst := rfl @[simp] lemma binary_fan.assoc_snd {X Y Z : C} {sXY : binary_fan X Y} {sYZ : binary_fan Y Z} (Q : is_limit sYZ) (s : binary_fan sXY.X Z) : (s.assoc Q).snd = Q.lift (binary_fan.mk (s.fst ≫ sXY.snd) s.snd) := rfl /-- Given binary fans `sXY` over `X Y`, and `sYZ` over `Y Z`, and `s` over `X sYZ.X`, if `sYZ` is a limit cone we can construct a binary fan over `sXY.X Z`. This is an ingredient of building the associator for a cartesian category. -/ def binary_fan.assoc_inv {X Y Z : C} {sXY : binary_fan X Y} (P : is_limit sXY) {sYZ : binary_fan Y Z} (s : binary_fan X sYZ.X) : binary_fan sXY.X Z := binary_fan.mk (P.lift (binary_fan.mk s.fst (s.snd ≫ sYZ.fst))) (s.snd ≫ sYZ.snd) @[simp] lemma binary_fan.assoc_inv_fst {X Y Z : C} {sXY : binary_fan X Y} (P : is_limit sXY) {sYZ : binary_fan Y Z} (s : binary_fan X sYZ.X) : (s.assoc_inv P).fst = P.lift (binary_fan.mk s.fst (s.snd ≫ sYZ.fst)) := rfl @[simp] lemma binary_fan.assoc_inv_snd {X Y Z : C} {sXY : binary_fan X Y} (P : is_limit sXY) {sYZ : binary_fan Y Z} (s : binary_fan X sYZ.X) : (s.assoc_inv P).snd = s.snd ≫ sYZ.snd := rfl /-- If all the binary fans involved a limit cones, `binary_fan.assoc` produces another limit cone. -/ @[simps] def is_limit.assoc {X Y Z : C} {sXY : binary_fan X Y} (P : is_limit sXY) {sYZ : binary_fan Y Z} (Q : is_limit sYZ) {s : binary_fan sXY.X Z} (R : is_limit s) : is_limit (s.assoc Q) := { lift := λ t, R.lift (binary_fan.assoc_inv P t), fac' := λ t, begin rintro ⟨⟨⟩⟩; simp, apply Q.hom_ext, rintro ⟨⟨⟩⟩; simp, end, uniq' := λ t m w, begin have h := R.uniq (binary_fan.assoc_inv P t) m, rw h, rintro ⟨⟨⟩⟩; simp, apply P.hom_ext, rintro ⟨⟨⟩⟩; simp, { exact w ⟨walking_pair.left⟩, }, { specialize w ⟨walking_pair.right⟩, simp at w, rw [←w], simp, }, { specialize w ⟨walking_pair.right⟩, simp at w, rw [←w], simp, }, end, } /-- Given two pairs of limit cones corresponding to the parenthesisations of `X × Y × Z`, we obtain an isomorphism between the cone points. -/ @[reducible] def binary_fan.associator {X Y Z : C} {sXY : binary_fan X Y} (P : is_limit sXY) {sYZ : binary_fan Y Z} (Q : is_limit sYZ) {s : binary_fan sXY.X Z} (R : is_limit s) {t : binary_fan X sYZ.X} (S : is_limit t) : s.X ≅ t.X := is_limit.cone_point_unique_up_to_iso (is_limit.assoc P Q R) S /-- Given a fixed family of limit data for every pair `X Y`, we obtain an associator. -/ @[reducible] def binary_fan.associator_of_limit_cone (L : Π X Y : C, limit_cone (pair X Y)) (X Y Z : C) : (L (L X Y).cone.X Z).cone.X ≅ (L X (L Y Z).cone.X).cone.X := binary_fan.associator (L X Y).is_limit (L Y Z).is_limit (L (L X Y).cone.X Z).is_limit (L X (L Y Z).cone.X).is_limit local attribute [tidy] tactic.discrete_cases /-- Construct a left unitor from specified limit cones. -/ @[simps] def binary_fan.left_unitor {X : C} {s : cone (functor.empty.{v} C)} (P : is_limit s) {t : binary_fan s.X X} (Q : is_limit t) : t.X ≅ X := { hom := t.snd, inv := Q.lift (binary_fan.mk (P.lift { X := X, π := { app := discrete.rec (pempty.rec _) } }) (𝟙 X) ), hom_inv_id' := by { apply Q.hom_ext, rintro ⟨⟨⟩⟩, { apply P.hom_ext, rintro ⟨⟨⟩⟩, }, { simp, }, }, } /-- Construct a right unitor from specified limit cones. -/ @[simps] def binary_fan.right_unitor {X : C} {s : cone (functor.empty.{v} C)} (P : is_limit s) {t : binary_fan X s.X} (Q : is_limit t) : t.X ≅ X := { hom := t.fst, inv := Q.lift (binary_fan.mk (𝟙 X) (P.lift { X := X, π := { app := discrete.rec (pempty.rec _) } })), hom_inv_id' := by { apply Q.hom_ext, rintro ⟨⟨⟩⟩, { simp, }, { apply P.hom_ext, rintro ⟨⟨⟩⟩, }, }, } end end limits open category_theory.limits section local attribute [tidy] tactic.case_bash variables {C} variables (𝒯 : limit_cone (functor.empty.{v} C)) variables (ℬ : Π (X Y : C), limit_cone (pair X Y)) namespace monoidal_of_chosen_finite_products /-- Implementation of the tensor product for `monoidal_of_chosen_finite_products`. -/ @[reducible] def tensor_obj (X Y : C) : C := (ℬ X Y).cone.X /-- Implementation of the tensor product of morphisms for `monoidal_of_chosen_finite_products`. -/ @[reducible] def tensor_hom {W X Y Z : C} (f : W ⟶ X) (g : Y ⟶ Z) : tensor_obj ℬ W Y ⟶ tensor_obj ℬ X Z := (binary_fan.is_limit.lift' (ℬ X Z).is_limit ((ℬ W Y).cone.π.app ⟨walking_pair.left⟩ ≫ f) (((ℬ W Y).cone.π.app ⟨walking_pair.right⟩ : (ℬ W Y).cone.X ⟶ Y) ≫ g)).val lemma tensor_id (X₁ X₂ : C) : tensor_hom ℬ (𝟙 X₁) (𝟙 X₂) = 𝟙 (tensor_obj ℬ X₁ X₂) := begin apply is_limit.hom_ext (ℬ _ _).is_limit, rintro ⟨⟨⟩⟩; { dsimp [tensor_hom], simp, }, end lemma tensor_comp {X₁ Y₁ Z₁ X₂ Y₂ Z₂ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (g₁ : Y₁ ⟶ Z₁) (g₂ : Y₂ ⟶ Z₂) : tensor_hom ℬ (f₁ ≫ g₁) (f₂ ≫ g₂) = tensor_hom ℬ f₁ f₂ ≫ tensor_hom ℬ g₁ g₂ := begin apply is_limit.hom_ext (ℬ _ _).is_limit, rintro ⟨⟨⟩⟩; { dsimp [tensor_hom], simp, }, end lemma pentagon (W X Y Z : C) : tensor_hom ℬ (binary_fan.associator_of_limit_cone ℬ W X Y).hom (𝟙 Z) ≫ (binary_fan.associator_of_limit_cone ℬ W (tensor_obj ℬ X Y) Z).hom ≫ tensor_hom ℬ (𝟙 W) (binary_fan.associator_of_limit_cone ℬ X Y Z).hom = (binary_fan.associator_of_limit_cone ℬ (tensor_obj ℬ W X) Y Z).hom ≫ (binary_fan.associator_of_limit_cone ℬ W X (tensor_obj ℬ Y Z)).hom := begin dsimp [tensor_hom], apply is_limit.hom_ext (ℬ _ _).is_limit, rintro ⟨⟨⟩⟩, { simp, }, { apply is_limit.hom_ext (ℬ _ _).is_limit, rintro ⟨⟨⟩⟩, { simp, }, apply is_limit.hom_ext (ℬ _ _).is_limit, rintro ⟨⟨⟩⟩, { simp, }, { simp, }, } end lemma triangle (X Y : C) : (binary_fan.associator_of_limit_cone ℬ X 𝒯.cone.X Y).hom ≫ tensor_hom ℬ (𝟙 X) (binary_fan.left_unitor 𝒯.is_limit (ℬ 𝒯.cone.X Y).is_limit).hom = tensor_hom ℬ (binary_fan.right_unitor 𝒯.is_limit (ℬ X 𝒯.cone.X).is_limit).hom (𝟙 Y) := begin dsimp [tensor_hom], apply is_limit.hom_ext (ℬ _ _).is_limit, rintro ⟨⟨⟩⟩; simp, end lemma left_unitor_naturality {X₁ X₂ : C} (f : X₁ ⟶ X₂) : tensor_hom ℬ (𝟙 𝒯.cone.X) f ≫ (binary_fan.left_unitor 𝒯.is_limit (ℬ 𝒯.cone.X X₂).is_limit).hom = (binary_fan.left_unitor 𝒯.is_limit (ℬ 𝒯.cone.X X₁).is_limit).hom ≫ f := begin dsimp [tensor_hom], simp, end lemma right_unitor_naturality {X₁ X₂ : C} (f : X₁ ⟶ X₂) : tensor_hom ℬ f (𝟙 𝒯.cone.X) ≫ (binary_fan.right_unitor 𝒯.is_limit (ℬ X₂ 𝒯.cone.X).is_limit).hom = (binary_fan.right_unitor 𝒯.is_limit (ℬ X₁ 𝒯.cone.X).is_limit).hom ≫ f := begin dsimp [tensor_hom], simp, end lemma associator_naturality {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃) : tensor_hom ℬ (tensor_hom ℬ f₁ f₂) f₃ ≫ (binary_fan.associator_of_limit_cone ℬ Y₁ Y₂ Y₃).hom = (binary_fan.associator_of_limit_cone ℬ X₁ X₂ X₃).hom ≫ tensor_hom ℬ f₁ (tensor_hom ℬ f₂ f₃) := begin dsimp [tensor_hom], apply is_limit.hom_ext (ℬ _ _).is_limit, rintro ⟨⟨⟩⟩, { simp, }, { apply is_limit.hom_ext (ℬ _ _).is_limit, rintro ⟨⟨⟩⟩, { simp, }, { simp, }, }, end end monoidal_of_chosen_finite_products open monoidal_of_chosen_finite_products /-- A category with a terminal object and binary products has a natural monoidal structure. -/ def monoidal_of_chosen_finite_products : monoidal_category C := { tensor_unit := 𝒯.cone.X, tensor_obj := λ X Y, tensor_obj ℬ X Y, tensor_hom := λ _ _ _ _ f g, tensor_hom ℬ f g, tensor_id' := tensor_id ℬ, tensor_comp' := λ _ _ _ _ _ _ f₁ f₂ g₁ g₂, tensor_comp ℬ f₁ f₂ g₁ g₂, associator := λ X Y Z, binary_fan.associator_of_limit_cone ℬ X Y Z, left_unitor := λ X, binary_fan.left_unitor (𝒯.is_limit) (ℬ 𝒯.cone.X X).is_limit, right_unitor := λ X, binary_fan.right_unitor (𝒯.is_limit) (ℬ X 𝒯.cone.X).is_limit, pentagon' := pentagon ℬ, triangle' := triangle 𝒯 ℬ, left_unitor_naturality' := λ _ _ f, left_unitor_naturality 𝒯 ℬ f, right_unitor_naturality' := λ _ _ f, right_unitor_naturality 𝒯 ℬ f, associator_naturality' := λ _ _ _ _ _ _ f₁ f₂ f₃, associator_naturality ℬ f₁ f₂ f₃, } namespace monoidal_of_chosen_finite_products open monoidal_category /-- A type synonym for `C` carrying a monoidal category structure corresponding to a fixed choice of limit data for the empty functor, and for `pair X Y` for every `X Y : C`. This is an implementation detail for `symmetric_of_chosen_finite_products`. -/ @[derive category, nolint unused_arguments has_inhabited_instance] def monoidal_of_chosen_finite_products_synonym (𝒯 : limit_cone (functor.empty.{v} C)) (ℬ : Π (X Y : C), limit_cone (pair X Y)):= C instance : monoidal_category (monoidal_of_chosen_finite_products_synonym 𝒯 ℬ) := monoidal_of_chosen_finite_products 𝒯 ℬ lemma braiding_naturality {X X' Y Y' : C} (f : X ⟶ Y) (g : X' ⟶ Y') : (tensor_hom ℬ f g) ≫ (limits.binary_fan.braiding (ℬ Y Y').is_limit (ℬ Y' Y).is_limit).hom = (limits.binary_fan.braiding (ℬ X X').is_limit (ℬ X' X).is_limit).hom ≫ (tensor_hom ℬ g f) := begin dsimp [tensor_hom, limits.binary_fan.braiding], apply (ℬ _ _).is_limit.hom_ext, rintro ⟨⟨⟩⟩; { dsimp [limits.is_limit.cone_point_unique_up_to_iso], simp, }, end lemma hexagon_forward (X Y Z : C) : (binary_fan.associator_of_limit_cone ℬ X Y Z).hom ≫ (limits.binary_fan.braiding (ℬ X (tensor_obj ℬ Y Z)).is_limit (ℬ (tensor_obj ℬ Y Z) X).is_limit).hom ≫ (binary_fan.associator_of_limit_cone ℬ Y Z X).hom = (tensor_hom ℬ (limits.binary_fan.braiding (ℬ X Y).is_limit (ℬ Y X).is_limit).hom (𝟙 Z)) ≫ (binary_fan.associator_of_limit_cone ℬ Y X Z).hom ≫ (tensor_hom ℬ (𝟙 Y) (limits.binary_fan.braiding (ℬ X Z).is_limit (ℬ Z X).is_limit).hom) := begin dsimp [tensor_hom, limits.binary_fan.braiding], apply (ℬ _ _).is_limit.hom_ext, rintro ⟨⟨⟩⟩, { dsimp [limits.is_limit.cone_point_unique_up_to_iso], simp, }, { apply (ℬ _ _).is_limit.hom_ext, rintro ⟨⟨⟩⟩; { dsimp [limits.is_limit.cone_point_unique_up_to_iso], simp, }, } end lemma hexagon_reverse (X Y Z : C) : (binary_fan.associator_of_limit_cone ℬ X Y Z).inv ≫ (limits.binary_fan.braiding (ℬ (tensor_obj ℬ X Y) Z).is_limit (ℬ Z (tensor_obj ℬ X Y)).is_limit).hom ≫ (binary_fan.associator_of_limit_cone ℬ Z X Y).inv = (tensor_hom ℬ (𝟙 X) (limits.binary_fan.braiding (ℬ Y Z).is_limit (ℬ Z Y).is_limit).hom) ≫ (binary_fan.associator_of_limit_cone ℬ X Z Y).inv ≫ (tensor_hom ℬ (limits.binary_fan.braiding (ℬ X Z).is_limit (ℬ Z X).is_limit).hom (𝟙 Y)) := begin dsimp [tensor_hom, limits.binary_fan.braiding], apply (ℬ _ _).is_limit.hom_ext, rintro ⟨⟨⟩⟩, { apply (ℬ _ _).is_limit.hom_ext, rintro ⟨⟨⟩⟩; { dsimp [binary_fan.associator_of_limit_cone, binary_fan.associator, limits.is_limit.cone_point_unique_up_to_iso], simp, }, }, { dsimp [binary_fan.associator_of_limit_cone, binary_fan.associator, limits.is_limit.cone_point_unique_up_to_iso], simp, }, end lemma symmetry (X Y : C) : (limits.binary_fan.braiding (ℬ X Y).is_limit (ℬ Y X).is_limit).hom ≫ (limits.binary_fan.braiding (ℬ Y X).is_limit (ℬ X Y).is_limit).hom = 𝟙 (tensor_obj ℬ X Y) := begin dsimp [tensor_hom, limits.binary_fan.braiding], apply (ℬ _ _).is_limit.hom_ext, rintro ⟨⟨⟩⟩; { dsimp [limits.is_limit.cone_point_unique_up_to_iso], simp, }, end end monoidal_of_chosen_finite_products open monoidal_of_chosen_finite_products /-- The monoidal structure coming from finite products is symmetric. -/ def symmetric_of_chosen_finite_products : symmetric_category (monoidal_of_chosen_finite_products_synonym 𝒯 ℬ) := { braiding := λ X Y, limits.binary_fan.braiding (ℬ _ _).is_limit (ℬ _ _).is_limit, braiding_naturality' := λ X X' Y Y' f g, braiding_naturality ℬ f g, hexagon_forward' := λ X Y Z, hexagon_forward ℬ X Y Z, hexagon_reverse' := λ X Y Z, hexagon_reverse ℬ X Y Z, symmetry' := λ X Y, symmetry ℬ X Y, } end end category_theory
ef4e98ef78cdb81c533e363e0d69410a5c0c1782
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/special_functions/japanese_bracket.lean
30ab3a86d24a36f465c8cf91c7e547829a5535f8
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
8,125
lean
/- Copyright (c) 2022 Moritz Doll. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Moritz Doll -/ import analysis.special_functions.integrals import analysis.special_functions.pow import measure_theory.integral.layercake import tactic.positivity /-! # Japanese Bracket In this file, we show that Japanese bracket $(1 + \|x\|^2)^{1/2}$ can be estimated from above and below by $1 + \|x\|$. The functions $(1 + \|x\|^2)^{-r/2}$ and $(1 + |x|)^{-r}$ are integrable provided that `r` is larger than the dimension. ## Main statements * `integrable_one_add_norm`: the function $(1 + |x|)^{-r}$ is integrable * `integrable_jap` the Japanese bracket is integrable -/ noncomputable theory open_locale big_operators nnreal filter topological_space ennreal open asymptotics filter set real measure_theory finite_dimensional variables {E : Type*} [normed_add_comm_group E] lemma sqrt_one_add_norm_sq_le (x : E) : real.sqrt (1 + ‖x‖^2) ≤ 1 + ‖x‖ := begin refine le_of_pow_le_pow 2 (by positivity) two_pos _, simp [sq_sqrt (zero_lt_one_add_norm_sq x).le, add_pow_two], end lemma one_add_norm_le_sqrt_two_mul_sqrt (x : E) : 1 + ‖x‖ ≤ (real.sqrt 2) * sqrt (1 + ‖x‖^2) := begin suffices : (sqrt 2 * sqrt (1 + ‖x‖ ^ 2)) ^ 2 - (1 + ‖x‖) ^ 2 = (1 - ‖x‖) ^2, { refine le_of_pow_le_pow 2 (by positivity) (by norm_num) _, rw [←sub_nonneg, this], positivity, }, rw [mul_pow, sq_sqrt (zero_lt_one_add_norm_sq x).le, add_pow_two, sub_pow_two], norm_num, ring, end lemma rpow_neg_one_add_norm_sq_le {r : ℝ} (x : E) (hr : 0 < r) : (1 + ‖x‖^2)^(-r/2) ≤ 2^(r/2) * (1 + ‖x‖)^(-r) := begin have h1 : 0 ≤ (2 : ℝ) := by positivity, have h3 : 0 < sqrt 2 := by positivity, have h4 : 0 < 1 + ‖x‖ := by positivity, have h5 : 0 < sqrt (1 + ‖x‖ ^ 2) := by positivity, have h6 : 0 < sqrt 2 * sqrt (1 + ‖x‖^2) := mul_pos h3 h5, rw [rpow_div_two_eq_sqrt _ h1, rpow_div_two_eq_sqrt _ (zero_lt_one_add_norm_sq x).le, ←inv_mul_le_iff (rpow_pos_of_pos h3 _), rpow_neg h4.le, rpow_neg (sqrt_nonneg _), ←mul_inv, ←mul_rpow h3.le h5.le, inv_le_inv (rpow_pos_of_pos h6 _) (rpow_pos_of_pos h4 _), rpow_le_rpow_iff h4.le h6.le hr], exact one_add_norm_le_sqrt_two_mul_sqrt _, end lemma le_rpow_one_add_norm_iff_norm_le {r t : ℝ} (hr : 0 < r) (ht : 0 < t) (x : E) : t ≤ (1 + ‖x‖) ^ -r ↔ ‖x‖ ≤ t ^ -r⁻¹ - 1 := begin rw [le_sub_iff_add_le', neg_inv], exact (real.le_rpow_inv_iff_of_neg (by positivity) ht (neg_lt_zero.mpr hr)).symm, end variables (E) lemma closed_ball_rpow_sub_one_eq_empty_aux {r t : ℝ} (hr : 0 < r) (ht : 1 < t) : metric.closed_ball (0 : E) (t^(-r⁻¹) - 1) = ∅ := begin rw [metric.closed_ball_eq_empty, sub_neg], exact real.rpow_lt_one_of_one_lt_of_neg ht (by simp only [hr, right.neg_neg_iff, inv_pos]), end variables [normed_space ℝ E] [finite_dimensional ℝ E] variables {E} lemma finite_integral_rpow_sub_one_pow_aux {r : ℝ} (n : ℕ) (hnr : (n : ℝ) < r) : ∫⁻ (x : ℝ) in Ioc 0 1, ennreal.of_real ((x ^ -r⁻¹ - 1) ^ n) < ∞ := begin have hr : 0 < r := lt_of_le_of_lt n.cast_nonneg hnr, have h_int : ∀ (x : ℝ) (hx : x ∈ Ioc (0 : ℝ) 1), ennreal.of_real ((x ^ -r⁻¹ - 1) ^ n) ≤ ennreal.of_real (x ^ -(r⁻¹ * n)) := begin intros x hx, have hxr : 0 ≤ x^ -r⁻¹ := rpow_nonneg_of_nonneg hx.1.le _, apply ennreal.of_real_le_of_real, rw [←neg_mul, rpow_mul hx.1.le, rpow_nat_cast], refine pow_le_pow_of_le_left _ (by simp only [sub_le_self_iff, zero_le_one]) n, rw [le_sub_iff_add_le', add_zero], refine real.one_le_rpow_of_pos_of_le_one_of_nonpos hx.1 hx.2 _, rw [right.neg_nonpos_iff, inv_nonneg], exact hr.le, end, refine lt_of_le_of_lt (set_lintegral_mono (by measurability) (by measurability) h_int) _, refine integrable_on.set_lintegral_lt_top _, rw ←interval_integrable_iff_integrable_Ioc_of_le zero_le_one, apply interval_integral.interval_integrable_rpow', rwa [neg_lt_neg_iff, inv_mul_lt_iff' hr, one_mul], end lemma finite_integral_one_add_norm [measure_space E] [borel_space E] [(@volume E _).is_add_haar_measure] {r : ℝ} (hnr : (finrank ℝ E : ℝ) < r) : ∫⁻ (x : E), ennreal.of_real ((1 + ‖x‖) ^ -r) < ∞ := begin have hr : 0 < r := lt_of_le_of_lt (finrank ℝ E).cast_nonneg hnr, -- We start by applying the layer cake formula have h_meas : measurable (λ (ω : E), (1 + ‖ω‖) ^ -r) := by measurability, have h_pos : ∀ x : E, 0 ≤ (1 + ‖x‖) ^ -r := by { intros x, positivity }, rw lintegral_eq_lintegral_meas_le volume h_pos h_meas, -- We use the first transformation of the integrant to show that we only have to integrate from -- 0 to 1 and from 1 to ∞ have h_int : ∀ (t : ℝ) (ht : t ∈ Ioi (0 : ℝ)), (volume {a : E | t ≤ (1 + ‖a‖) ^ -r} : ennreal) = volume (metric.closed_ball (0 : E) (t^(-r⁻¹) - 1)) := begin intros t ht, congr' 1, ext x, simp only [mem_set_of_eq, mem_closed_ball_zero_iff], exact le_rpow_one_add_norm_iff_norm_le hr (mem_Ioi.mp ht) x, end, rw set_lintegral_congr_fun measurable_set_Ioi (ae_of_all volume $ h_int), have hIoi_eq : Ioi (0 : ℝ) = Ioc (0 : ℝ) 1 ∪ Ioi 1 := (set.Ioc_union_Ioi_eq_Ioi zero_le_one).symm, have hdisjoint : disjoint (Ioc (0 : ℝ) 1) (Ioi 1) := by simp [disjoint_iff], rw [hIoi_eq, lintegral_union measurable_set_Ioi hdisjoint, ennreal.add_lt_top], have h_int' : ∀ (t : ℝ) (ht : t ∈ Ioc (0 : ℝ) 1), (volume (metric.closed_ball (0 : E) (t^(-r⁻¹) - 1)) : ennreal) = ennreal.of_real ((t^(-r⁻¹) - 1) ^ finite_dimensional.finrank ℝ E) * volume (metric.ball (0:E) 1) := begin intros t ht, refine volume.add_haar_closed_ball (0 : E) _, rw [le_sub_iff_add_le', add_zero], exact real.one_le_rpow_of_pos_of_le_one_of_nonpos ht.1 ht.2 (by simp [hr.le]), end, have h_meas' : measurable (λ (a : ℝ), ennreal.of_real ((a ^ -r⁻¹ - 1) ^ finrank ℝ E)) := by measurability, split, -- The integral from 0 to 1: { rw [set_lintegral_congr_fun measurable_set_Ioc (ae_of_all volume $ h_int'), lintegral_mul_const _ h_meas', ennreal.mul_lt_top_iff], left, -- We calculate the integral exact ⟨finite_integral_rpow_sub_one_pow_aux (finrank ℝ E) hnr, measure_ball_lt_top⟩ }, -- The integral from 1 to ∞ is zero: have h_int'' : ∀ (t : ℝ) (ht : t ∈ Ioi (1 : ℝ)), (volume (metric.closed_ball (0 : E) (t^(-r⁻¹) - 1)) : ennreal) = 0 := λ t ht, by rw [closed_ball_rpow_sub_one_eq_empty_aux E hr ht, measure_empty], -- The integral over the constant zero function is finite: rw [set_lintegral_congr_fun measurable_set_Ioi (ae_of_all volume $ h_int''), lintegral_const 0, zero_mul], exact with_top.zero_lt_top, end lemma integrable_one_add_norm [measure_space E] [borel_space E] [(@volume E _).is_add_haar_measure] {r : ℝ} (hnr : (finrank ℝ E : ℝ) < r) : integrable (λ (x : E), (1 + ‖x‖) ^ -r) := begin refine ⟨by measurability, _⟩, -- Lower Lebesgue integral have : ∫⁻ (a : E), ‖(1 + ‖a‖) ^ -r‖₊ = ∫⁻ (a : E), ennreal.of_real ((1 + ‖a‖) ^ -r) := lintegral_nnnorm_eq_of_nonneg (λ _, rpow_nonneg_of_nonneg (by positivity) _), rw [has_finite_integral, this], exact finite_integral_one_add_norm hnr, end lemma integrable_rpow_neg_one_add_norm_sq [measure_space E] [borel_space E] [(@volume E _).is_add_haar_measure] {r : ℝ} (hnr : (finrank ℝ E : ℝ) < r) : integrable (λ (x : E), (1 + ‖x‖^2) ^ (-r/2)) := begin have hr : 0 < r := lt_of_le_of_lt (finrank ℝ E).cast_nonneg hnr, refine ((integrable_one_add_norm hnr).const_mul $ 2 ^ (r / 2)).mono (by measurability) (eventually_of_forall $ λ x, _), have h1 : 0 ≤ (1 + ‖x‖ ^ 2) ^ (-r/2) := by positivity, have h2 : 0 ≤ (1 + ‖x‖) ^ -r := by positivity, have h3 : 0 ≤ (2 : ℝ)^(r/2) := by positivity, simp_rw [norm_mul, norm_eq_abs, abs_of_nonneg h1, abs_of_nonneg h2, abs_of_nonneg h3], exact rpow_neg_one_add_norm_sq_le _ hr, end
56fade833459be4e5c2ba4a2c1e5be74c5d7e5f1
07f5f86b00fed90a419ccda4298d8b795a68f657
/library/init/meta/tactic.lean
3f9069e4be8e35425382fd4e85d2882a98a0c091
[ "Apache-2.0" ]
permissive
VBaratham/lean
8ec5c3167b4835cfbcd7f25e2173d61ad9416b3a
450ca5834c1c35318e4b47d553bb9820c1b3eee7
refs/heads/master
1,629,649,471,814
1,512,060,373,000
1,512,060,469,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
46,901
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.function init.data.option.basic init.util import init.category.combinators init.category.monad init.category.alternative init.category.monad_fail import init.data.nat.div init.meta.exceptional init.meta.format init.meta.environment import init.meta.pexpr init.data.repr init.data.string.basic init.meta.interaction_monad meta constant tactic_state : Type universes u v namespace tactic_state /-- Create a tactic state with an empty local context and a dummy goal. -/ meta constant mk_empty : environment → options → 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⟩ @[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) 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 tactic variables {α : Type u} meta def try_core (t : tactic α) : tactic (option α) := λ s, result.cases_on (t s) (λ a, success (some a)) (λ e ref s', success none s) meta def skip : tactic unit := success () meta def try (t : tactic α) : tactic unit := try_core t >>[tactic] skip meta def try_lst : list (tactic unit) → tactic unit | [] := failed | (tac :: tacs) := λ s, match tac s with | result.success _ s' := try (try_lst tacs) s' | result.exception e p s' := match try_lst tacs s' with | result.exception _ _ _ := result.exception e p s' | r := r end end meta def fail_if_success {α : Type u} (t : tactic α) : tactic unit := λ s, result.cases_on (t s) (λ a s, mk_exception "fail_if_success combinator failed, given tactic succeeded" none s) (λ e ref s', success () s) meta def success_if_fail {α : Type u} (t : tactic α) : tactic unit := λ s, match t s with | (interaction_monad.result.exception _ _ s') := success () s | (interaction_monad.result.success a s) := mk_exception "success_if_fail combinator failed, given tactic succeeded" none s end open nat /-- (repeat_at_most n t): repeat the given tactic at most n times or until t fails -/ meta def repeat_at_most : nat → tactic unit → tactic unit | 0 t := skip | (succ n) t := (do t, repeat_at_most n t) <|> skip /-- (repeat_exactly n t) : execute t n times -/ meta def repeat_exactly : nat → tactic unit → tactic unit | 0 t := skip | (succ n) t := do t, repeat_exactly n t meta def repeat : tactic unit → tactic unit := repeat_at_most 100000 meta def 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) @[inline] meta def write (s' : tactic_state) : tactic unit := λ s, success () s' @[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 α) := ⟨has_map.map to_fmt ∘ monad.mapm 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 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 meta constant revert_lst : list expr → tactic nat /-- Return `e` in weak head normal form with respect to the given transparency setting. -/ meta constant whnf (e : expr) (md := semireducible) : tactic expr /-- (head) eta expand the given expression -/ meta constant head_eta_expand : expr → tactic expr /-- (head) beta reduction -/ meta constant head_beta : expr → tactic expr /-- (head) zeta reduction -/ meta constant head_zeta : expr → tactic expr /-- zeta reduction -/ meta constant zeta : expr → tactic expr /-- (head) eta reduction -/ 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) : tactic unit /-- Similar to `unify`, but it treats metavariables as constants. -/ meta constant is_def_eq (t s : expr) (md := semireducible) : tactic unit /-- Infer the type of the given expression. Remark: transparency does not affect type inference -/ meta constant infer_type : expr → tactic expr meta constant get_local : name → tactic expr /-- Resolve a name using the current local context, environment, aliases, etc. -/ meta constant resolve_name : name → tactic 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) meta constant get_unused_name (n : name) (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 : 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. 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 -/ meta constant rotate_left : nat → tactic unit meta constant get_goals : tactic (list expr) meta constant set_goals : list expr → tactic unit inductive new_goals | non_dep_first | non_dep_only | all /-- Configuration options for the `apply` tactic. -/ structure apply_cfg := (md := semireducible) (approx := tt) (new_goals := new_goals.non_dep_first) (instances := tt) (auto_param := tt) (opt_param := tt) /-- Apply the expression `e` to the main goal, the unification is performed using the transparency mode in `cfg`. 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, even the assigned ones. -/ meta constant apply_core (e : expr) (cfg : apply_cfg := {}) : tactic (list 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 meta constant mk_fresh_name : tactic name /-- Return a hash code for expr that ignores inst_implicit arguments, and proofs. -/ meta constant abstract_hash : expr → tactic nat /-- Return the "weight" of the given expr while ignoring inst_implicit arguments, and proofs. -/ meta constant abstract_weight : expr → tactic nat meta constant abstract_eq : expr → expr → tactic bool /-- Induction 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 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. 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 (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`. `new_env` needs to be a descendant from the current environment. -/ meta constant set_env : environment → tactic unit /-- (doc_string env d k) return the doc string for d (if available) -/ meta constant doc_string : name → tactic string meta constant add_doc_string : name → string → tactic unit /-- 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 meta constant module_doc_strings : tactic (list (option name × string)) /-- 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. -/ meta constant has_attribute : name → name → tactic nat /-- `copy_attribute attr_name c_name d_name` copy attribute `attr_name` from `src` to `tgt` if it is defined for `src` -/ meta def copy_attribute (attr_name : name) (src : name) (p : bool) (tgt : name) : tactic unit := try $ do prio ← has_attribute attr_name src, set_basic_attribute 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. -/ meta constant kabstract (e t : expr) (md := reducible) : 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 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 meta def whnf_target : tactic unit := target >>= whnf >>= change meta def unsafe_change (e : expr) : tactic unit := change e ff meta def intro (n : name) : tactic expr := do t ← target, if expr.is_pi t ∨ expr.is_let t then intro_core n else whnf_target >> intro_core n meta def intro1 : tactic expr := intro `_ 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 meta def intro_lst : list name → tactic (list expr) | [] := return [] | (n::ns) := do H ← intro n, Hs ← intro_lst ns, return (H :: Hs) /-- Introduces new hypotheses with forward dependencies -/ meta def intros_dep : tactic (list expr) := do t ← target, let proc (b : expr) := if b.has_var_idx 0 then do h ← intro1, hs ← intros_dep, return (h::hs) else -- body doesn't depend on new hypothesis return [], match t with | expr.pi _ _ _ b := proc b | expr.elet _ _ _ b := proc b | _ := return [] end meta def introv : list name → tactic (list expr) | [] := intros_dep | (n::ns) := do hs ← intros_dep, h ← intro n, hs' ← introv ns, return (hs ++ h :: hs') /-- Returns n fully qualified if it refers to a constant, or else fails. -/ meta def resolve_constant (n : name) : tactic name := do (expr.const n _) ← resolve_name n, pure n meta def to_expr_strict (q : pexpr) : tactic expr := to_expr q meta def revert (l : expr) : tactic nat := revert_lst [l] meta def clear_lst : list name → tactic unit | [] := skip | (n::ns) := do H ← get_local n, clear H, clear_lst ns meta def 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) /-- We have to provide the instance argument `[has_mod nat]` because mod for nat was not defined yet -/ meta def rotate_right (n : nat) [has_mod nat] : tactic unit := do ng ← num_goals, if ng = 0 then skip else rotate_left (ng - n % ng) meta def rotate : nat → tactic unit := rotate_left /-- `first [t_1, ..., t_n]` applies the first tactic that doesn't fail. The tactic fails if all t_i's fail. -/ meta def first {α : Type u} : list (tactic α) → tactic α | [] := fail "first tactic failed, no more alternatives" | (t::ts) := t <|> first ts /-- Applies the given tactic to the main goal and fails if it is not solved. -/ meta def solve1 (tac : tactic unit) : tactic unit := do gs ← get_goals, match gs with | [] := fail "solve1 tactic failed, there isn't any goal left to focus" | (g::rs) := do set_goals [g], tac, gs' ← get_goals, match gs' with | [] := set_goals rs | gs := fail "solve1 tactic failed, focused goal has not been solved" end end /-- `solve [t_1, ... t_n]` applies the first tactic that solves the main goal. -/ meta def solve (ts : list (tactic unit)) : tactic unit := first $ map solve1 ts private meta def focus_aux : list (tactic unit) → list expr → list expr → tactic unit | [] [] rs := set_goals rs | (t::ts) [] rs := fail "focus tactic failed, insufficient number of goals" | tts (g::gs) rs := mcond (is_assigned g) (focus_aux tts gs rs) $ do set_goals [g], t::ts ← pure tts | fail "focus tactic failed, insufficient number of tactics", t, rs' ← get_goals, focus_aux ts gs (rs ++ rs') /-- `focus [t_1, ..., t_n]` applies t_i to the i-th goal. Fails if the number of goals is not n. -/ meta def focus (ts : list (tactic unit)) : tactic unit := do gs ← get_goals, focus_aux ts gs [] meta def focus1 {α} (tac : tactic α) : tactic α := do g::gs ← get_goals, match gs with | [] := tac | _ := do set_goals [g], a ← tac, gs' ← get_goals, set_goals (gs' ++ gs), return a end private meta def all_goals_core (tac : tactic unit) : list expr → list expr → tactic unit | [] ac := set_goals ac | (g :: gs) ac := mcond (is_assigned g) (all_goals_core gs ac) $ do set_goals [g], tac, new_gs ← get_goals, all_goals_core gs (ac ++ new_gs) /-- Apply the given tactic to all goals. -/ meta def all_goals (tac : tactic unit) : tactic unit := do gs ← get_goals, all_goals_core tac gs [] private meta def any_goals_core (tac : tactic unit) : list expr → list expr → bool → tactic unit | [] ac progress := guard progress >> set_goals ac | (g :: gs) ac progress := mcond (is_assigned g) (any_goals_core gs ac progress) $ do set_goals [g], succeeded ← try_core tac, new_gs ← get_goals, any_goals_core gs (ac ++ new_gs) (succeeded.is_some || progress) /-- Apply the given tactic to any goal where it succeeds. The tactic succeeds only if tac succeeds for at least one goal. -/ meta def any_goals (tac : tactic unit) : tactic unit := do gs ← get_goals, any_goals_core tac gs [] ff /-- LCF-style AND_THEN tactic. It applies tac1, and if succeed applies tac2 to each subgoal produced by tac1 -/ meta def seq (tac1 : tactic unit) (tac2 : tactic unit) : tactic unit := do g::gs ← get_goals, set_goals [g], tac1, all_goals tac2, gs' ← get_goals, set_goals (gs' ++ gs) meta def seq_focus (tac1 : tactic unit) (tacs2 : list (tactic unit)) : tactic unit := do g::gs ← get_goals, set_goals [g], tac1, focus tacs2, gs' ← get_goals, set_goals (gs' ++ gs) meta instance andthen_seq : has_andthen (tactic unit) (tactic unit) (tactic unit) := ⟨seq⟩ meta instance andthen_seq_focus : has_andthen (tactic unit) (list (tactic unit)) (tactic unit) := ⟨seq_focus⟩ meta constant is_trace_enabled_for : name → bool /-- Execute tac only if option trace.n is set to true. -/ meta def when_tracing (n : name) (tac : tactic unit) : tactic unit := when (is_trace_enabled_for n = tt) tac /-- Fail if there are no remaining goals. -/ meta def fail_if_no_goals : tactic unit := do n ← num_goals, when (n = 0) (fail "tactic failed, there are no goals to be solved") /-- Fail if there are unsolved goals. -/ meta def done : tactic unit := do n ← num_goals, when (n ≠ 0) (fail "done tactic failed, there are unsolved goals") meta def apply_opt_param : tactic unit := do `(opt_param %%t %%v) ← target, exact v meta def apply_auto_param : tactic unit := do `(auto_param %%type %%tac_name_expr) ← target, change type, tac_name ← eval_expr name tac_name_expr, tac ← eval_expr (tactic unit) (expr.const tac_name []), tac meta def has_opt_auto_param (ms : list expr) : tactic bool := ms.mfoldl (λ r m, do type ← infer_type m, return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2) ff meta def try_apply_opt_auto_param (cfg : apply_cfg) (ms : list expr) : tactic unit := when (cfg.auto_param || cfg.opt_param) $ mwhen (has_opt_auto_param ms) $ do gs ← get_goals, ms.mmap' (λ m, set_goals [m] >> 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 unit := apply_core e cfg >>= try_apply_opt_auto_param cfg meta def fapply (e : expr) : tactic unit := apply e {new_goals := new_goals.all} meta def eapply (e : expr) : tactic unit := 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) : tactic unit := mk_const c >>= apply meta def eapplyc (c : name) : tactic unit := mk_const c >>= eapply 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) <|> fail "tactic by_contradiction failed, target is not a negation nor a decidable proposition (remark: when 'local attribute classical.prop_decidable [instance]' is used all propositions are decidable)", 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`. -/ meta def cases (e : expr) (ids : list name := []) (md := semireducible) (dmd := semireducible) : tactic unit := if e.is_local_constant then cases_core e ids md >> return () else do x ← mk_fresh_name, n ← revert_kdependencies e dmd, (tactic.generalize e x dmd) <|> (do t ← infer_type e, tactic.assertv x t e, get_local x >>= tactic.revert, return ()), h ← tactic.intro1, (step (cases_core h ids md); intron n) 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) (intro h >> skip) 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) meta def rename (curr : name) (new : name) : tactic unit := do h ← get_local curr, n ← revert h, intro new, intron (n - 1) /-- "Replace" hypothesis `h : type` with `h : new_type` where `eq_pr` is a proof that (type = new_type). The tactic actually creates a new hypothesis with the same user facing name, and (tries to) clear `h`. The `clear` step fails if `h` has forward dependencies. In this case, the old `h` will remain in the local context. The tactic returns the new hypothesis. -/ meta def replace_hyp (h : expr) (new_type : expr) (eq_pr : expr) : tactic expr := do h_type ← infer_type h, new_h ← assert h.local_pp_name new_type, mk_eq_mp eq_pr h >>= exact, try $ clear h, return new_h 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 /- Define id_rhs using meta-programming because we don't have syntax for setting reducibility_hints. See module init.meta.declaration. Remark: id_rhs is used in the equation compiler to address performance issues when proving equational lemmas. -/ run_cmd do let l := level.param `l, let Ty : pexpr := expr.sort l, type ← to_expr ``(Π (α : %%Ty), α → α), val ← to_expr ``(λ (α : %%Ty) (a : α), a), add_decl (declaration.defn `id_rhs [`l] type val reducibility_hints.abbrev tt) attribute [reducible, inline] id_rhs /- Install monad laws tactic and use it to prove some instances. -/ meta def control_laws_tac := whnf_target >> intros >> to_expr ``(rfl) >>= exact meta def order_laws_tac := whnf_target >> intros >> to_expr ``(iff.refl _) >>= exact meta def unsafe_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, id_map := undefined, pure_bind := undefined, bind_assoc := undefined} meta instance : monad task := {map := @task.map, bind := @task.bind, pure := @task.pure, id_map := undefined, pure_bind := undefined, bind_assoc := undefined, bind_pure_comp_eq_map := undefined} namespace tactic meta def mk_id_proof (prop : expr) (pr : expr) : expr := expr.app (expr.app (expr.const ``id [level.zero]) prop) pr meta def mk_id_eq (lhs : expr) (rhs : expr) (pr : expr) : tactic expr := do prop ← mk_app `eq [lhs, rhs], return $ mk_id_proof prop pr meta def replace_target (new_target : expr) (pr : expr) : tactic unit := do t ← target, assert `htarget new_target, swap, ht ← get_local `htarget, locked_pr ← mk_id_eq t new_target pr, mk_eq_mpr locked_pr ht >>= exact end tactic
a999a22bbaac3afda9e0cef4d0a7d5b9836bc2e1
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/max_memory.lean
ea508d40d0d2fb6ca891afd3c7f16785790d5b42
[ "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
25
lean
set_option max_memory 40
8cca8e78e6d14d1e029dd81a8362ff3a52363477
b00eb947a9c4141624aa8919e94ce6dcd249ed70
/stage0/src/Init/WF.lean
bc8300ffa50fa5e09e52dbab13f4618e97379d66
[ "Apache-2.0" ]
permissive
gebner/lean4-old
a4129a041af2d4d12afb3a8d4deedabde727719b
ee51cdfaf63ee313c914d83264f91f414a0e3b6e
refs/heads/master
1,683,628,606,745
1,622,651,300,000
1,622,654,405,000
142,608,821
1
0
null
null
null
null
UTF-8
Lean
false
false
11,156
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 -/ prelude import Init.SizeOf import Init.Data.Nat.Basic universes u v set_option codegen false inductive Acc {α : Sort u} (r : α → α → Prop) : α → Prop where | intro (x : α) (h : (y : α) → r y x → Acc r y) : Acc r x abbrev Acc.ndrec.{u1, u2} {α : Sort u2} {r : α → α → Prop} {C : α → Sort u1} (m : (x : α) → ((y : α) → r y x → Acc r y) → ((y : α) → (a : r y x) → C y) → C x) {a : α} (n : Acc r a) : C a := Acc.rec (motive := fun α _ => C α) m n abbrev Acc.ndrecOn.{u1, u2} {α : Sort u2} {r : α → α → Prop} {C : α → Sort u1} {a : α} (n : Acc r a) (m : (x : α) → ((y : α) → r y x → Acc r y) → ((y : α) → (a : r y x) → C y) → C x) : C a := Acc.rec (motive := fun α _ => C α) m n namespace Acc variable {α : Sort u} {r : α → α → Prop} def inv {x y : α} (h₁ : Acc r x) (h₂ : r y x) : Acc r y := Acc.recOn (motive := fun (x : α) _ => r y x → Acc r y) h₁ (fun x₁ ac₁ ih h₂ => ac₁ y h₂) h₂ end Acc inductive WellFounded {α : Sort u} (r : α → α → Prop) : Prop where | intro (h : ∀ a, Acc r a) : WellFounded r class WellFoundedRelation (α : Sort u) : Type u where r : α → α → Prop wf : WellFounded r namespace WellFounded def apply {α : Sort u} {r : α → α → Prop} (wf : WellFounded r) (a : α) : Acc r a := WellFounded.recOn (motive := fun x => (y : α) → Acc r y) wf (fun p => p) a section variable {α : Sort u} {r : α → α → Prop} (hwf : WellFounded r) theorem recursion {C : α → Sort v} (a : α) (h : ∀ x, (∀ y, r y x → C y) → C x) : C a := by induction (apply hwf a) with | intro x₁ ac₁ ih => exact h x₁ ih theorem induction {C : α → Prop} (a : α) (h : ∀ x, (∀ y, r y x → C y) → C x) : C a := recursion hwf a h variable {C : α → Sort v} variable (F : ∀ x, (∀ y, r y x → C y) → C x) def fixF (x : α) (a : Acc r x) : C x := by induction a with | intro x₁ ac₁ ih => exact F x₁ ih def fixFEq (x : α) (acx : Acc r x) : fixF F x acx = F x (fun (y : α) (p : r y x) => fixF F y (Acc.inv acx p)) := by induction acx with | intro x r ih => exact rfl end variable {α : Sort u} {C : α → Sort v} {r : α → α → Prop} -- Well-founded fixpoint def fix (hwf : WellFounded r) (F : ∀ x, (∀ y, r y x → C y) → C x) (x : α) : C x := fixF F x (apply hwf x) -- Well-founded fixpoint satisfies fixpoint equation theorem fixEq (hwf : WellFounded r) (F : ∀ x, (∀ y, r y x → C y) → C x) (x : α) : fix hwf F x = F x (fun y h => fix hwf F y) := fixFEq F x (apply hwf x) end WellFounded open WellFounded -- Empty relation is well-founded def emptyWf {α : Sort u} : WellFounded (@emptyRelation α) := by apply WellFounded.intro intro a apply Acc.intro a intro b h cases h -- Subrelation of a well-founded relation is well-founded namespace Subrelation variable {α : Sort u} {r q : α → α → Prop} def accessible {a : α} (h₁ : Subrelation q r) (ac : Acc r a) : Acc q a := by induction ac with | intro x ax ih => apply Acc.intro intro y h exact ih y (h₁ h) def wf (h₁ : Subrelation q r) (h₂ : WellFounded r) : WellFounded q := ⟨fun a => accessible @h₁ (apply h₂ a)⟩ end Subrelation -- The inverse image of a well-founded relation is well-founded namespace InvImage variable {α : Sort u} {β : Sort v} {r : β → β → Prop} private def accAux (f : α → β) {b : β} (ac : Acc r b) : (x : α) → f x = b → Acc (InvImage r f) x := by induction ac with | intro x acx ih => intro z e apply Acc.intro intro y lt subst x apply ih (f y) lt y rfl def accessible {a : α} (f : α → β) (ac : Acc r (f a)) : Acc (InvImage r f) a := accAux f ac a rfl def wf (f : α → β) (h : WellFounded r) : WellFounded (InvImage r f) := ⟨fun a => accessible f (apply h (f a))⟩ end InvImage -- The transitive closure of a well-founded relation is well-founded namespace TC variable {α : Sort u} {r : α → α → Prop} def accessible {z : α} (ac : Acc r z) : Acc (TC r) z := by induction ac with | intro x acx ih => apply Acc.intro x intro y rel induction rel with | base a b rab => exact ih a rab | trans a b c rab rbc ih₁ ih₂ => apply Acc.inv (ih₂ acx ih) rab def wf (h : WellFounded r) : WellFounded (TC r) := ⟨fun a => accessible (apply h a)⟩ end TC -- less-than is well-founded def Nat.ltWf : WellFounded Nat.lt := by apply WellFounded.intro intro n induction n with | zero => apply Acc.intro 0 intro _ h apply absurd h (Nat.notLtZero _) | succ n ih => apply Acc.intro (Nat.succ n) intro m h have : m = n ∨ m < n := Nat.eqOrLtOfLe (Nat.leOfSuccLeSucc h) match this with | Or.inl e => subst e; assumption | Or.inr e => exact Acc.inv ih e def measure {α : Sort u} : (α → Nat) → α → α → Prop := InvImage (fun a b => a < b) def measureWf {α : Sort u} (f : α → Nat) : WellFounded (measure f) := InvImage.wf f Nat.ltWf def sizeofMeasure (α : Sort u) [SizeOf α] : α → α → Prop := measure sizeOf def sizeofMeasureWf (α : Sort u) [SizeOf α] : WellFounded (sizeofMeasure α) := measureWf sizeOf instance hasWellFoundedOfSizeOf (α : Sort u) [SizeOf α] : WellFoundedRelation α where r := sizeofMeasure α wf := sizeofMeasureWf α namespace Prod open WellFounded section variable {α : Type u} {β : Type v} variable (ra : α → α → Prop) variable (rb : β → β → Prop) -- Lexicographical order based on ra and rb inductive Lex : α × β → α × β → Prop where | left {a₁} (b₁) {a₂} (b₂) (h : ra a₁ a₂) : Lex (a₁, b₁) (a₂, b₂) | right (a) {b₁ b₂} (h : rb b₁ b₂) : Lex (a, b₁) (a, b₂) -- relational product based on ra and rb inductive Rprod : α × β → α × β → Prop where | intro {a₁ b₁ a₂ b₂} (h₁ : ra a₁ a₂) (h₂ : rb b₁ b₂) : Rprod (a₁, b₁) (a₂, b₂) end section variable {α : Type u} {β : Type v} variable {ra : α → α → Prop} {rb : β → β → Prop} def lexAccessible (aca : (a : α) → Acc ra a) (acb : (b : β) → Acc rb b) (a : α) (b : β) : Acc (Lex ra rb) (a, b) := by induction (aca a) generalizing b with | intro xa aca iha => induction (acb b) with | intro xb acb ihb => apply Acc.intro (xa, xb) intro p lt cases lt with | left _ _ h => apply iha _ h | right _ h => apply ihb _ h -- The lexicographical order of well founded relations is well-founded def lexWf (ha : WellFounded ra) (hb : WellFounded rb) : WellFounded (Lex ra rb) := ⟨fun (a, b) => lexAccessible (WellFounded.apply ha) (WellFounded.apply hb) a b⟩ -- relational product is a Subrelation of the Lex def rprodSubLex (a : α × β) (b : α × β) (h : Rprod ra rb a b) : Lex ra rb a b := by cases h with | intro h₁ h₂ => exact Lex.left _ _ h₁ -- The relational product of well founded relations is well-founded def rprodWf (ha : WellFounded ra) (hb : WellFounded rb) : WellFounded (Rprod ra rb) := by apply Subrelation.wf (r := Lex ra rb) (h₂ := lexWf ha hb) intro a b h exact rprodSubLex a b h end instance {α : Type u} {β : Type v} [s₁ : WellFoundedRelation α] [s₂ : WellFoundedRelation β] : WellFoundedRelation (α × β) where r := Lex s₁.r s₂.r wf := lexWf s₁.wf s₂.wf end Prod namespace PSigma section variable {α : Sort u} {β : α → Sort v} variable (r : α → α → Prop) variable (s : ∀ a, β a → β a → Prop) -- Lexicographical order based on r and s inductive Lex : PSigma β → PSigma β → Prop where | left : ∀ {a₁ : α} (b₁ : β a₁) {a₂ : α} (b₂ : β a₂), r a₁ a₂ → Lex ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ | right : ∀ (a : α) {b₁ b₂ : β a}, s a b₁ b₂ → Lex ⟨a, b₁⟩ ⟨a, b₂⟩ end section variable {α : Sort u} {β : α → Sort v} variable {r : α → α → Prop} {s : ∀ (a : α), β a → β a → Prop} def lexAccessible {a} (aca : Acc r a) (acb : (a : α) → WellFounded (s a)) (b : β a) : Acc (Lex r s) ⟨a, b⟩ := by induction aca with | intro xa aca iha => induction (WellFounded.apply (acb xa) b) with | intro xb acb ihb => apply Acc.intro intro p lt cases lt with | left => apply iha; assumption | right => apply ihb; assumption -- The lexicographical order of well founded relations is well-founded def lexWf (ha : WellFounded r) (hb : (x : α) → WellFounded (s x)) : WellFounded (Lex r s) := WellFounded.intro fun ⟨a, b⟩ => lexAccessible (WellFounded.apply ha a) hb b end section variable {α : Sort u} {β : Sort v} def lexNdep (r : α → α → Prop) (s : β → β → Prop) := Lex r (fun a => s) def lexNdepWf {r : α → α → Prop} {s : β → β → Prop} (ha : WellFounded r) (hb : WellFounded s) : WellFounded (lexNdep r s) := WellFounded.intro fun ⟨a, b⟩ => lexAccessible (WellFounded.apply ha a) (fun x => hb) b end section variable {α : Sort u} {β : Sort v} -- Reverse lexicographical order based on r and s inductive RevLex (r : α → α → Prop) (s : β → β → Prop) : @PSigma α (fun a => β) → @PSigma α (fun a => β) → Prop where | left : {a₁ a₂ : α} → (b : β) → r a₁ a₂ → RevLex r s ⟨a₁, b⟩ ⟨a₂, b⟩ | right : (a₁ : α) → {b₁ : β} → (a₂ : α) → {b₂ : β} → s b₁ b₂ → RevLex r s ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ end section open WellFounded variable {α : Sort u} {β : Sort v} variable {r : α → α → Prop} {s : β → β → Prop} def revLexAccessible {b} (acb : Acc s b) (aca : (a : α) → Acc r a): (a : α) → Acc (RevLex r s) ⟨a, b⟩ := by induction acb with | intro xb acb ihb => intro a induction (aca a) with | intro xa aca iha => apply Acc.intro intro p lt cases lt with | left => apply iha; assumption | right => apply ihb; assumption def revLexWf (ha : WellFounded r) (hb : WellFounded s) : WellFounded (RevLex r s) := WellFounded.intro fun ⟨a, b⟩ => revLexAccessible (apply hb b) (WellFounded.apply ha) a end section def skipLeft (α : Type u) {β : Type v} (s : β → β → Prop) : @PSigma α (fun a => β) → @PSigma α (fun a => β) → Prop := RevLex emptyRelation s def skipLeftWf (α : Type u) {β : Type v} {s : β → β → Prop} (hb : WellFounded s) : WellFounded (skipLeft α s) := revLexWf emptyWf hb def mkSkipLeft {α : Type u} {β : Type v} {b₁ b₂ : β} {s : β → β → Prop} (a₁ a₂ : α) (h : s b₁ b₂) : skipLeft α s ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ := RevLex.right _ _ h end instance WellFoundedRelation {α : Type u} {β : α → Type v} [s₁ : WellFoundedRelation α] [s₂ : ∀ a, WellFoundedRelation (β a)] : WellFoundedRelation (PSigma β) where r := Lex s₁.r (fun a => (s₂ a).r) wf := lexWf s₁.wf (fun a => (s₂ a).wf) end PSigma