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
944574b471b227547d26836d64a1d5ae478525e8
7cef822f3b952965621309e88eadf618da0c8ae9
/src/data/fintype/intervals.lean
ed973a1d44dd3e2b80c992bf414b5c9b9dee7413
[ "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
752
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.set.intervals import data.set.finite import data.fintype import tactic /-! # fintype instances for intervals We provide `fintype` instances for `Ico l u`, for `l u : ℕ`, and for `l u : ℤ`. -/ namespace set instance Ico_ℕ_fintype (l u : ℕ) : fintype (Ico l u) := fintype.of_finset (finset.Ico l u) $ (λ n, by { simp only [mem_Ico, finset.Ico.mem], }) instance Ico_ℤ_fintype (l u : ℤ) : fintype (Ico l u) := fintype.of_finset (finset.Ico_ℤ l u) $ (λ n, by { simp only [mem_Ico, finset.Ico_ℤ.mem], }) -- TODO other useful instances: pnat, fin n, zmod? end set
570b7b2484fea30803153f87f4b5141a669d0d3a
626e312b5c1cb2d88fca108f5933076012633192
/src/algebra/module/pi.lean
0892f90ab920fb9b857a3fe0ce0e55edc04e104f
[ "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
7,863
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 -/ import algebra.module.basic import algebra.regular.smul import algebra.ring.pi /-! # Pi instances for module and multiplicative actions This file defines instances for module, mul_action and related structures on Pi Types -/ namespace pi universes u v w variable {I : Type u} -- The indexing type variable {f : I → Type v} -- The family of types already equipped with instances variables (x y : Π i, f i) (i : I) instance has_scalar {α : Type*} [Π i, has_scalar α $ f i] : has_scalar α (Π i : I, f i) := ⟨λ s x, λ i, s • (x i)⟩ lemma smul_def {α : Type*} [Π i, has_scalar α $ f i] (s : α) : s • x = λ i, s • x i := rfl @[simp] lemma smul_apply {α : Type*} [Π i, has_scalar α $ f i] (s : α) : (s • x) i = s • x i := rfl instance has_scalar' {g : I → Type*} [Π i, has_scalar (f i) (g i)] : has_scalar (Π i, f i) (Π i : I, g i) := ⟨λ s x, λ i, (s i) • (x i)⟩ @[simp] lemma smul_apply' {g : I → Type*} [∀ i, has_scalar (f i) (g i)] (s : Π i, f i) (x : Π i, g i) : (s • x) i = s i • x i := rfl lemma _root_.is_smul_regular.pi {α : Type*} [Π i, has_scalar α $ f i] {k : α} (hk : Π i, is_smul_regular (f i) k) : is_smul_regular (Π i, f i) k := λ _ _ h, funext $ λ i, hk i (congr_fun h i : _) instance is_scalar_tower {α β : Type*} [has_scalar α β] [Π i, has_scalar β $ f i] [Π i, has_scalar α $ f i] [Π i, is_scalar_tower α β (f i)] : is_scalar_tower α β (Π i : I, f i) := ⟨λ x y z, funext $ λ i, smul_assoc x y (z i)⟩ instance is_scalar_tower' {g : I → Type*} {α : Type*} [Π i, has_scalar α $ f i] [Π i, has_scalar (f i) (g i)] [Π i, has_scalar α $ g i] [Π i, is_scalar_tower α (f i) (g i)] : is_scalar_tower α (Π i : I, f i) (Π i : I, g i) := ⟨λ x y z, funext $ λ i, smul_assoc x (y i) (z i)⟩ instance is_scalar_tower'' {g : I → Type*} {h : I → Type*} [Π i, has_scalar (f i) (g i)] [Π i, has_scalar (g i) (h i)] [Π i, has_scalar (f i) (h i)] [Π i, is_scalar_tower (f i) (g i) (h i)] : is_scalar_tower (Π i, f i) (Π i, g i) (Π i, h i) := ⟨λ x y z, funext $ λ i, smul_assoc (x i) (y i) (z i)⟩ instance smul_comm_class {α β : Type*} [Π i, has_scalar α $ f i] [Π i, has_scalar β $ f i] [∀ i, smul_comm_class α β (f i)] : smul_comm_class α β (Π i : I, f i) := ⟨λ x y z, funext $ λ i, smul_comm x y (z i)⟩ instance smul_comm_class' {g : I → Type*} {α : Type*} [Π i, has_scalar α $ g i] [Π i, has_scalar (f i) (g i)] [∀ i, smul_comm_class α (f i) (g i)] : smul_comm_class α (Π i : I, f i) (Π i : I, g i) := ⟨λ x y z, funext $ λ i, smul_comm x (y i) (z i)⟩ instance smul_comm_class'' {g : I → Type*} {h : I → Type*} [Π i, has_scalar (g i) (h i)] [Π i, has_scalar (f i) (h i)] [∀ i, smul_comm_class (f i) (g i) (h i)] : smul_comm_class (Π i, f i) (Π i, g i) (Π i, h i) := ⟨λ x y z, funext $ λ i, smul_comm (x i) (y i) (z i)⟩ /-- If `f i` has a faithful scalar action for a given `i`, then so does `Π i, f i`. This is not an instance as `i` cannot be inferred. -/ lemma has_faithful_scalar_at {α : Type*} [Π i, has_scalar α $ f i] [Π i, nonempty (f i)] (i : I) [has_faithful_scalar α (f i)] : has_faithful_scalar α (Π i, f i) := ⟨λ x y h, eq_of_smul_eq_smul $ λ a : f i, begin classical, have := congr_fun (h $ function.update (λ j, classical.choice (‹Π i, nonempty (f i)› j)) i a) i, simpa using this, end⟩ instance has_faithful_scalar {α : Type*} [nonempty I] [Π i, has_scalar α $ f i] [Π i, nonempty (f i)] [Π i, has_faithful_scalar α (f i)] : has_faithful_scalar α (Π i, f i) := let ⟨i⟩ := ‹nonempty I› in has_faithful_scalar_at i instance smul_with_zero (α) [has_zero α] [Π i, has_zero (f i)] [Π i, smul_with_zero α (f i)] : smul_with_zero α (Π i, f i) := { smul_zero := λ _, funext $ λ _, smul_zero' (f _) _, zero_smul := λ _, funext $ λ _, zero_smul _ _, ..pi.has_scalar } instance smul_with_zero' {g : I → Type*} [Π i, has_zero (g i)] [Π i, has_zero (f i)] [Π i, smul_with_zero (g i) (f i)] : smul_with_zero (Π i, g i) (Π i, f i) := { smul_zero := λ _, funext $ λ _, smul_zero' (f _) _, zero_smul := λ _, funext $ λ _, zero_smul _ _, ..pi.has_scalar' } instance mul_action (α) {m : monoid α} [Π i, mul_action α $ f i] : @mul_action α (Π i : I, f i) m := { smul := (•), mul_smul := λ r s f, funext $ λ i, mul_smul _ _ _, one_smul := λ f, funext $ λ i, one_smul α _ } instance mul_action' {g : I → Type*} {m : Π i, monoid (f i)} [Π i, mul_action (f i) (g i)] : @mul_action (Π i, f i) (Π i : I, g i) (@pi.monoid I f m) := { smul := (•), mul_smul := λ r s f, funext $ λ i, mul_smul _ _ _, one_smul := λ f, funext $ λ i, one_smul _ _ } instance mul_action_with_zero (α) [monoid_with_zero α] [Π i, has_zero (f i)] [Π i, mul_action_with_zero α (f i)] : mul_action_with_zero α (Π i, f i) := { ..pi.mul_action _, ..pi.smul_with_zero _ } instance mul_action_with_zero' {g : I → Type*} [Π i, monoid_with_zero (g i)] [Π i, has_zero (f i)] [Π i, mul_action_with_zero (g i) (f i)] : mul_action_with_zero (Π i, g i) (Π i, f i) := { ..pi.mul_action', ..pi.smul_with_zero' } instance distrib_mul_action (α) {m : monoid α} {n : ∀ i, add_monoid $ f i} [∀ i, distrib_mul_action α $ f i] : @distrib_mul_action α (Π i : I, f i) m (@pi.add_monoid I f n) := { smul_zero := λ c, funext $ λ i, smul_zero _, smul_add := λ c f g, funext $ λ i, smul_add _ _ _, ..pi.mul_action _ } instance distrib_mul_action' {g : I → Type*} {m : Π i, monoid (f i)} {n : Π i, add_monoid $ g i} [Π i, distrib_mul_action (f i) (g i)] : @distrib_mul_action (Π i, f i) (Π i : I, g i) (@pi.monoid I f m) (@pi.add_monoid I g n) := { smul_add := by { intros, ext x, apply smul_add }, smul_zero := by { intros, ext x, apply smul_zero } } lemma single_smul {α} [monoid α] [Π i, add_monoid $ f i] [Π i, distrib_mul_action α $ f i] [decidable_eq I] (i : I) (r : α) (x : f i) : single i (r • x) = r • single i x := single_op (λ i : I, ((•) r : f i → f i)) (λ j, smul_zero _) _ _ /-- A version of `pi.single_smul` for non-dependent functions. It is useful in cases Lean fails to apply `pi.single_smul`. -/ lemma single_smul'' {α β} [monoid α] [add_monoid β] [distrib_mul_action α β] [decidable_eq I] (i : I) (r : α) (x : β) : single i (r • x) = r • single i x := single_smul i r x lemma single_smul' {g : I → Type*} [Π i, monoid_with_zero (f i)] [Π i, add_monoid (g i)] [Π i, distrib_mul_action (f i) (g i)] [decidable_eq I] (i : I) (r : f i) (x : g i) : single i (r • x) = single i r • single i x := single_op₂ (λ i : I, ((•) : f i → g i → g i)) (λ j, smul_zero _) _ _ _ variables (I f) instance module (α) {r : semiring α} {m : ∀ i, add_comm_monoid $ f i} [∀ i, module α $ f i] : @module α (Π i : I, f i) r (@pi.add_comm_monoid I f m) := { add_smul := λ c f g, funext $ λ i, add_smul _ _ _, zero_smul := λ f, funext $ λ i, zero_smul α _, ..pi.distrib_mul_action _ } variables {I f} instance module' {g : I → Type*} {r : Π i, semiring (f i)} {m : Π i, add_comm_monoid (g i)} [Π i, module (f i) (g i)] : module (Π i, f i) (Π i, g i) := { add_smul := by { intros, ext1, apply add_smul }, zero_smul := by { intros, ext1, apply zero_smul } } instance (α) {r : semiring α} {m : Π i, add_comm_monoid $ f i} [Π i, module α $ f i] [∀ i, no_zero_smul_divisors α $ f i] : no_zero_smul_divisors α (Π i : I, f i) := ⟨λ c x h, or_iff_not_imp_left.mpr (λ hc, funext (λ i, (smul_eq_zero.mp (congr_fun h i)).resolve_left hc))⟩ end pi
86d146c55eec918f1b5a3585fcd8217833ab2639
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/metric_space/completion_auto.lean
7a5a0316b3960c174883cc5ff59c2f765547d705
[]
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
4,853
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sébastien Gouëzel -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.uniform_space.completion import Mathlib.topology.metric_space.isometry import Mathlib.PostPort universes u namespace Mathlib /-! # The completion of a metric space Completion of uniform spaces are already defined in `topology.uniform_space.completion`. We show here that the uniform space completion of a metric space inherits a metric space structure, by extending the distance to the completion and checking that it is indeed a distance, and that it defines the same uniformity as the already defined uniform structure on the completion -/ namespace metric /-- The distance on the completion is obtained by extending the distance on the original space, by uniform continuity. -/ protected instance uniform_space.completion.has_dist {α : Type u} [metric_space α] : has_dist (uniform_space.completion α) := has_dist.mk (uniform_space.completion.extension₂ dist) /-- The new distance is uniformly continuous. -/ protected theorem completion.uniform_continuous_dist {α : Type u} [metric_space α] : uniform_continuous fun (p : uniform_space.completion α × uniform_space.completion α) => dist (prod.fst p) (prod.snd p) := uniform_space.completion.uniform_continuous_extension₂ dist /-- The new distance is an extension of the original distance. -/ protected theorem completion.dist_eq {α : Type u} [metric_space α] (x : α) (y : α) : dist ↑x ↑y = dist x y := uniform_space.completion.extension₂_coe_coe uniform_continuous_dist x y /- Let us check that the new distance satisfies the axioms of a distance, by starting from the properties on α and extending them to `completion α` by continuity. -/ protected theorem completion.dist_self {α : Type u} [metric_space α] (x : uniform_space.completion α) : dist x x = 0 := sorry protected theorem completion.dist_comm {α : Type u} [metric_space α] (x : uniform_space.completion α) (y : uniform_space.completion α) : dist x y = dist y x := sorry protected theorem completion.dist_triangle {α : Type u} [metric_space α] (x : uniform_space.completion α) (y : uniform_space.completion α) (z : uniform_space.completion α) : dist x z ≤ dist x y + dist y z := sorry /-- Elements of the uniformity (defined generally for completions) can be characterized in terms of the distance. -/ protected theorem completion.mem_uniformity_dist {α : Type u} [metric_space α] (s : set (uniform_space.completion α × uniform_space.completion α)) : s ∈ uniformity (uniform_space.completion α) ↔ ∃ (ε : ℝ), ∃ (H : ε > 0), ∀ {a b : uniform_space.completion α}, dist a b < ε → (a, b) ∈ s := sorry /-- If two points are at distance 0, then they coincide. -/ protected theorem completion.eq_of_dist_eq_zero {α : Type u} [metric_space α] (x : uniform_space.completion α) (y : uniform_space.completion α) (h : dist x y = 0) : x = y := sorry /-- Reformulate `completion.mem_uniformity_dist` in terms that are suitable for the definition of the metric space structure. -/ protected theorem completion.uniformity_dist' {α : Type u} [metric_space α] : uniformity (uniform_space.completion α) = infi fun (ε : Subtype fun (ε : ℝ) => 0 < ε) => filter.principal (set_of fun (p : uniform_space.completion α × uniform_space.completion α) => dist (prod.fst p) (prod.snd p) < subtype.val ε) := sorry protected theorem completion.uniformity_dist {α : Type u} [metric_space α] : uniformity (uniform_space.completion α) = infi fun (ε : ℝ) => infi fun (H : ε > 0) => filter.principal (set_of fun (p : uniform_space.completion α × uniform_space.completion α) => dist (prod.fst p) (prod.snd p) < ε) := sorry /-- Metric space structure on the completion of a metric space. -/ protected instance completion.metric_space {α : Type u} [metric_space α] : metric_space (uniform_space.completion α) := metric_space.mk completion.dist_self completion.eq_of_dist_eq_zero completion.dist_comm completion.dist_triangle (fun (x y : uniform_space.completion α) => ennreal.of_real (uniform_space.completion.extension₂ dist x y)) (uniform_space.completion.uniform_space α) /-- The embedding of a metric space in its completion is an isometry. -/ theorem completion.coe_isometry {α : Type u} [metric_space α] : isometry coe := iff.mpr isometry_emetric_iff_metric completion.dist_eq end Mathlib
b779e1999a69770cc3bb3c40774074709b743117
40ad357bbd0d327dd1e3e7f7beb868bd4e5b0a9d
/src/temporal_logic/basic.lean
a4d53a7b41aab7353287cd0fbde76913929dc4aa
[]
no_license
unitb/temporal-logic
9966424f015976d5997a9ffa30cbd77cc3a9cb1c
accec04d1b09ca841be065511c9e206b725b16e9
refs/heads/master
1,633,868,382,769
1,541,072,223,000
1,541,072,223,000
114,790,987
5
3
null
null
null
null
UTF-8
Lean
false
false
20,075
lean
import util.predicate import util.classical import util.meta.tactic import tactic.linarith @[user_attribute] meta def strengthening_attr : user_attribute := { name := `strengthening , descr := " Strenghtening lemmas to facilitate the stripping of small details in application. Expected shape `∀ p : pred' α, ⊩ f p ⟶ g p` " } run_cmd mk_simp_attr `tl_simp [`simp] run_cmd do ns ← attribute.get_instances `simp, let ns : list name := ns.filter (λ n, name.is_prefix_of `predicate n), n ← tactic.mk_const (mk_simp_attr_decl_name `tl_simp), ns.mmap' (λ n, user_attribute.set simp_attr.tl_simp n () tt), return () namespace tactic.interactive open lean interactive.types open interactive lean.parser tactic open list (hiding map) functor predicate local postfix *:9001 := many meta def TL_unfold (cs : parse ident*) (loc : parse location) : tactic unit := do unfold_coes loc, unfold (cs ++ [`var.apply,`pred'.mk]) loc end tactic.interactive namespace temporal open predicate nat universes u u₀ u₁ u₂ u₃ variables {α : Sort u₀} {β : Sort u₁} {γ : Sort u₂} {φ : Sort u₃} @[reducible] def tvar := var ℕ @[reducible] def cpred := tvar Prop abbreviation act (β : Sort u) := β → β → Prop def eventually (p : cpred) : cpred := ⟨ λ i, ∃ j, p.apply (i+j) ⟩ def henceforth (p : cpred) : cpred := ⟨ λ i, ∀ j, p.apply (i+j) ⟩ def next (p : tvar α) : tvar α := ⟨ λ i, p.apply (i.succ) ⟩ def until (p q : cpred) : cpred := ⟨ λ i, ∃ j, i+j ⊨ q ∧ ∀ k < j, i+k ⊨ p ⟩ def wait (p q : cpred) : cpred := until p q ⋁ henceforth p def action (a : act α) (v : tvar α) : cpred := lifted₂ a v (next v) @[lifted_fn, reducible] def pair {α β} (x : tvar α) (y : tvar β) : tvar (α × β) := lifted₂ prod.mk x y notation `⦃` x₀ `,` x₁ `⦄` := pair x₀ x₁ notation `⦃` x₀ `,` x₁ `,` x₂ `⦄` := pair x₀ (pair x₁ x₂) notation `⦃` x₀ `,` x₁ `,` x₂ `,` x₃ `⦄` := pair x₀ (pair x₁ (pair x₂ x₃)) notation `⦃` x₀ `,` x₁ `,` x₂ `,` x₃ `,` x₄ `⦄` := pair x₀ (pair x₁ (pair x₂ (pair x₃ x₄))) -- notation `⦃` x `,` l:(foldl `,` (h t, pair h t) x `⦄`) := l prefix `⊙`:90 := next prefix `◇`:95 := eventually -- \di prefix `◻`:95 := henceforth -- \sqw infixl ` 𝒰 `:95 := until -- \McU infixl ` 𝒲 `:95 := wait -- \McU notation `⟦ `:max v ` | `:50 R ` ⟧`:0 := action R v notation `⟦ `:max v `,` v' ` | `:50 R ` ⟧`:0 := action R (pair v v') notation `⟦ `:max v₀ `,` v₁ `,` v₂ ` | `:50 R ` ⟧`:0 := action R (pair v₀ (pair v₁ v₂)) notation `⟦ `:max v₀ `,` v₁ `,` v₂ `,` v₃ ` | `:50 R ` ⟧`:0 := action R (pair v₀ (pair v₁ (pair v₂ v₃))) def tl_leads_to (p q : cpred) : cpred := ◻(p ⟶ ◇q) infix ` ~> `:55 := tl_leads_to def to_fun_var (f : var γ α → var γ β) : var γ (α → β) := ⟨ λ i x, (f ↑x).apply i ⟩ def to_fun_var' (f : tvar α → tvar α → tvar β) : tvar (α → α → β) := ⟨ λ i x y, (f x y).apply i ⟩ class persistent (p : cpred) : Prop := (is_persistent : ◻p = p) export persistent (is_persistent) lemma tl_imp_intro (h : cpred) [persistent h] {p q : cpred} (h' : h ⟹ (p ⟶ q)) : ctx_impl h p q := begin constructor, intro, exact (h' True).apply σ trivial, end lemma tl_imp_elim (h : cpred) [persistent h] {p q : cpred} (h' : ctx_impl h p q) : h ⟹ (p ⟶ q) := begin intro, revert Γ, apply intro_p_imp h', end lemma tl_imp_intro' (h : cpred) [persistent h] {p q : cpred} (h' : p ⟹ q) : ctx_impl h p q := h' _ @[tl_simp, simp] lemma hence_true : ◻(True : cpred) = True := begin ext1, split ; intro h, { trivial }, { intro, trivial } end @[tl_simp, simp] lemma next_true : ⊙True = True := by lifted_pred @[tl_simp, simp] lemma next_false : ⊙False = False := by lifted_pred [next] instance true_persistent : persistent (True : cpred) := by { constructor, simp with tl_simp, } lemma tl_imp_elim' {p q : cpred} (h : ctx_impl True p q) : p ⟹ q := begin simp [ctx_impl] at h, apply h, end @[strengthening] lemma eventually_weaken (p : cpred) : (p ⟹ ◇ p) := begin pointwise with τ h, unfold eventually, existsi 0, apply h end open stream @[strengthening] lemma next_entails_eventually (p : cpred) : ⊙p ⟹ ◇p := by { lifted_pred [eventually], intro, existsi 1, assumption } @[strengthening] lemma henceforth_entails_next (p : cpred) : ◻p ⟹ ⊙p := by { lifted_pred [eventually], intro h, apply h 1 } @[strengthening] lemma henceforth_str (p : cpred) : (◻p ⟹ p) := begin pointwise with τ h, apply h 0 end local infix ` <$> ` := fun_app_to_var local infix ` <*> ` := combine_var lemma init_eq_action {p : α → Prop} (v : tvar α) : ⟨p⟩ ! v = ⟦ v | λ s s', p s ⟧ := by { cases v, refl } lemma coe_eq (v : tvar α) (x : α) : ⟨λ y, y = x⟩ ! v = v ≃ x := by { cases v, refl } lemma init_eq_action' {p : pred' α} (v : tvar α) : (p ! v) = ⟦ v | λ s s', p.apply s ⟧ := by { cases v, cases p, refl } lemma next_eq_action {p : α → Prop} (v : tvar α) : ⊙(p <$> v) = ⟦ v | λ s s' : α, p s' ⟧ := by { cases v, refl } lemma action_eq {A : act α} (v : tvar α) : ⟦ v | A ⟧ = (A : tvar (act α)) v (⊙v) := by { cases v, refl } lemma next_eq_action' {p : pred' α} (v : tvar α) : ⊙(p ! v) = ⟦ v | λ s s' : α, p.apply s' ⟧ := by { cases v, cases p, refl } lemma not_action {A : act α} (v : tvar α) : -⟦ v | A ⟧ = ⟦ v | λ s s', ¬ A s s' ⟧ := rfl lemma action_imp (p q : act α) (v : tvar α) : (⟦ v | λ s s' : α, p s s' → q s s' ⟧ : cpred) = ⟦ v | p ⟧ ⟶ ⟦ v | q ⟧ := rfl lemma action_and_action (p q : act α) (v : tvar α) : ⟦ v | p ⟧ ⋀ ⟦ v | q ⟧ = ⟦ v | λ s s' : α, p s s' ∧ q s s' ⟧ := rfl lemma action_or_action (p q : act α) (v : tvar α) : ⟦ v | p ⟧ ⋁ ⟦ v | q ⟧ = ⟦ v | λ s s' : α, p s s' ∨ q s s' ⟧ := rfl lemma action_false (v : tvar α) : (⟦ v | λ _ _, false ⟧ : cpred) = False := by { funext x, refl } variables {Γ : cpred} lemma unlift_action (A : act α) (v : tvar α) (h : ∀ σ σ', A σ σ') : Γ ⊢ ⟦ v | A ⟧ := begin constructor, simp_intros [action], apply h end @[tl_simp, simp] lemma eventually_eventually (p : cpred) : ◇◇ p = ◇ p := begin ext k, split ; unfold eventually ; intro h ; cases h with i h, { cases h with j h, existsi (i+j), simp at h, apply h, }, { existsi (0 : ℕ), existsi i, apply h } end @[tl_simp, simp] lemma henceforth_henceforth (p : cpred) : ◻◻ p = ◻ p := begin ext _, split ; intro h, { intro i, have h' := h i 0, simp [drop_drop] at h', apply h' }, { intros i j, simp [drop_drop], apply h } end lemma henceforth_next_intro (p : cpred) : ◻p = ◻(p ⋀ ⊙p) := by { lifted_pred, split ; intros h i, { split, apply h i, specialize h (succ i), simp [add_succ] at h, simp [next,h], }, { apply (h i).left }} /- True / False -/ @[tl_simp, simp] lemma hence_false : ◻(False : cpred) = False := begin ext _, split ; intro h, { cases h 0 }, { cases h } end @[tl_simp, simp] lemma event_false : ◇(False : cpred) = False := begin ext _, split ; intro h, { cases h with _ h, cases h }, { cases h } end @[tl_simp, simp] lemma eventually_true : ◇(True : cpred) = True := begin ext1, split ; intro h, { trivial }, { apply exists.intro 0, trivial } end /- monotonicity -/ @[monotonic] lemma eventually_tl_imp_eventually {h p q : cpred} [persistent h] (f : ctx_impl h p q) : ctx_impl h (◇p) (◇q) := begin unfold ctx_impl at ⊢ f, rw ← is_persistent h at *, pointwise f with τ h', apply exists_imp_exists, intro i, apply f, rw ← henceforth_henceforth at h', apply h', end @[monotonic] lemma eventually_entails_eventually {p q : cpred} (f : p ⟹ q) : (◇p) ⟹ (◇q) := begin apply tl_imp_elim', mono, end lemma eventually_imp_eventually {p q : cpred} {Γ} (f : Γ ⊢ ◻ (p ⟶ q)) : Γ ⊢ (◇p) ⟶ (◇q) := begin constructor, introv hΓ, apply exists_imp_exists, intro i, apply f.apply _ hΓ, end @[monotonic] lemma henceforth_tl_imp_henceforth {h p q : cpred} [persistent h] (f : ctx_impl h p q) : ctx_impl h (◻p) (◻q) := begin unfold ctx_impl at *, rw ← is_persistent h, pointwise f with i h', simp [henceforth], intro_mono i, apply f , apply h', end @[monotonic] lemma henceforth_entails_henceforth {p q : cpred} (f : p ⟹ q) : (◻p) ⟹ (◻q) := begin refine tl_imp_elim' _, mono end lemma henceforth_imp_henceforth {p q : cpred} {Γ} (h : Γ ⊢ ◻ (p ⟶ q)) : Γ ⊢ (◻p) ⟶ (◻q) := begin pointwise h with τ, specialize h τ, simp [henceforth] at ⊢ h, introv h₀ h₁, solve_by_elim, end lemma inf_often_entails_inf_often {p q : cpred} (f : p ⟹ q) : ◻◇p ⟹ ◻◇q := by mono* lemma stable_entails_stable {p q : cpred} (f : p ⟹ q) : ◇◻p ⟹ ◇◻q := by mono* lemma henceforth_and (p q : cpred) : ◻(p ⋀ q) = ◻p ⋀ ◻q := begin ext1, repeat { split ; intros } ; intros i ; try { simp, split }, { apply (a i).left }, { apply (a i).right }, { apply a.left }, { apply a.right }, end lemma eventually_or (p q : cpred) : ◇(p ⋁ q) = ◇p ⋁ ◇q := begin ext1, simp [eventually,exists_or], end lemma henceforth_forall (P : α → cpred) : ◻(∀∀ x, P x) = ∀∀ x, ◻P x := begin ext1, simp [henceforth,p_forall], rw forall_swap, end @[tl_simp, simp] lemma not_henceforth (p : cpred) : (- ◻p) = (◇-p) := begin ext1, simp [henceforth,not_forall_iff_exists_not,eventually], end @[tl_simp, simp] lemma not_eventually (p : cpred) : (-◇p) = (◻-p) := begin ext1, simp [henceforth,not_forall_iff_exists_not,eventually], end @[tl_simp, simp, predicate] lemma models_to_fun_var (σ : γ) (x : var γ α → var γ β) : σ ⊨ to_fun_var x = λ i, σ ⊨ x i := by { refl } @[tl_simp, simp, predicate] lemma models_to_fun_var' (σ : ℕ) (f : tvar (α → α → β)) : σ ⊨ to_fun_var' (λ x, var_seq $ var_seq f x) = σ ⊨ f := by { casesm* tvar _, dunfold to_fun_var', simp_coes [var_seq], } @[tl_simp, simp, predicate] lemma models_to_fun_var''' (σ : ℕ) (f : tvar α → tvar α → tvar β) (x y : tvar α) : (σ ⊨ to_fun_var' f x y) = (σ ⊨ f x y) := sorry @[tl_simp, simp, predicate, lifted_fn] lemma to_fun_var_fn_coe_proj (f : var γ α) (g : var β φ → var β γ) (w : var β φ) : to_fun_var (λ w, f ! g w) w = f ! to_fun_var g w := by { funext, lifted_pred, simp!, } @[tl_simp, simp, predicate, lifted_fn] lemma to_fun_var_fn_coe (g : var β (φ → γ)) (w : var β φ) : to_fun_var (λ w, g w) w = g w := by { funext, lifted_pred, simp!, } @[tl_simp, simp, predicate, lifted_fn] lemma to_fun_var_fn_coe' (f : tvar (α → α → β)) (w w' : tvar α) : ⇑(to_fun_var' $ λ w w', f w w') w w' = f w w' := by { lifted_pred, } @[tl_simp, simp, predicate, lifted_fn] lemma to_fun_var_p_exists' (f : γ → tvar α → tvar α → tvar Prop) (w w' : tvar α) : ⇑(to_fun_var' $ λ w w', ∃∃ x : γ, f x w w') w w' = ∃∃ x : γ, to_fun_var' (f x) w w' := by { lifted_pred, } @[lifted_fn] lemma to_fun_var_lift₁ (f : φ → β) (g : var γ α → var γ φ) (w : var γ α) : (to_fun_var (λ (w : var γ α), lifted₁ f (g w))) w = lifted₁ f (to_fun_var g w) := by { lifted_pred, simp! } @[lifted_fn] lemma to_fun_var_lift₂ {σ} (f : φ → σ → β) (g₀ : var γ α → var γ φ) (g₁ : var γ α → var γ σ) (w : var γ α) : (to_fun_var (λ (w : var γ α), lifted₂ f (g₀ w) (g₁ w))) w = lifted₂ f (to_fun_var g₀ w) (to_fun_var g₁ w) := by { lifted_pred, simp } @[lifted_fn] lemma to_fun_var_coe (w : var γ α) (v : var γ β) : to_fun_var (λ (w : var γ α), v) w = v := by { lifted_pred, simp } @[lifted_fn] lemma to_fun_var_id (w : var γ α) : to_fun_var (λ w : var γ α, w) w = w := by { lifted_pred, simp } @[lifted_fn] lemma to_fun_var'_fn_coe (f : var φ β) (g : tvar α → tvar α → tvar φ) (w w' : tvar α) : (to_fun_var' (λ (w w' : tvar α), f ! g w w')) w w' = f ! to_fun_var' g w w' := by { lifted_pred, } @[lifted_fn] lemma to_fun_var'_coe (w w' : tvar α) (v : tvar β) : (to_fun_var' (λ (w w' : tvar α), v)) w w' = v := by { lifted_pred, } @[lifted_fn] lemma to_fun_var'_id (w w' : tvar α) : to_fun_var' (λ w w' : tvar α, w) w w' = w := by { lifted_pred, } @[lifted_fn] lemma to_fun_var'_id' (w w' : tvar α) : to_fun_var' (λ w w' : tvar α, w') w w' = w' := by { lifted_pred, } @[lifted_fn] lemma to_fun_var'_lift₂ {σ} (f : φ → σ → β) (g₀ : tvar α → tvar α → tvar φ) (g₁ : tvar α → tvar α → tvar σ) (w w' : tvar α) : to_fun_var' (λ (w w' : tvar α), lifted₂ f (g₀ w w') (g₁ w w')) w w' = lifted₂ f (to_fun_var' g₀ w w') (to_fun_var' g₁ w w') := by { lifted_pred, } @[lifted_fn] lemma to_fun_var'_action {σ} (f : tvar α → tvar β) (A : act β) (g₁ : tvar α → tvar α → tvar σ) (w w' : tvar α) : to_fun_var' (λ (w w' : tvar α), ⟦ f w | A ⟧ ) w w' = ⟦ f w | A ⟧ := by { lifted_pred, } @[tl_simp, simp, predicate] lemma models_coe (σ : α) (x : β) : σ ⊨ ↑x = x := by { refl } @[tl_simp, simp, predicate] lemma models_action (A : act α) (v : tvar α) (i : ℕ) : i ⊨ ⟦ v | A ⟧ ↔ A (i ⊨ v) (succ i ⊨ v) := by { refl } @[tl_simp, simp, predicate] lemma models_next (p : tvar α) (t : ℕ) : t ⊨ ⊙p = succ t ⊨ p := by refl lemma induct' (p : cpred) {Γ} (h : Γ ⊢ ◻ (p ⟶ ⊙p)) : Γ ⊢ ◻ (p ⟶ ◻p) := begin constructor, intros τ hΓ k hp i, induction i with i, assumption, have := h.apply τ hΓ (k+i) (cast (by simp) i_ih), simp [next] at this, simp [add_succ,this], end lemma induct (p : cpred) {Γ} (h : Γ ⊢ ◻ (p ⟶ ⊙p)) : Γ ⊢ p ⟶ ◻p := henceforth_str (p ⟶ ◻p) Γ (induct' _ h) lemma induct_evt' (p q : cpred) {Γ} (h : Γ ⊢ ◻ (p ⟶ -q ⟶ ⊙p ⋁ ⊙q)) : Γ ⊢ ◻ (p ⟶ ◇q ⋁ ◻p) := begin lifted_pred using h, simp only [henceforth] with tl_simp at *, intros, simp [or_iff_not_imp,eventually], intros hnq k, induction k with k, { simp [a] }, { simp [add_succ], specialize h _ k_ih (hnq _), rw [or_comm,or_iff_not_imp] at h, apply h, rw [← add_succ,← add_succ], apply hnq } end lemma eventually_exists (P : α → cpred) : ◇(∃∃ x, P x) = ∃∃ x, ◇P x := begin ext1, unfold eventually p_exists, split ; intro H ; cases H with i H ; cases H with j H ; exact ⟨_,_,H⟩ , end lemma one_point_elim {t} (Γ p : cpred) (v : tvar t) (h : ∀ x : t, Γ ⊢ (↑x ≃ v) ⟶ p) : Γ ⊢ p := begin rw [← p_forall_to_fun] at h, constructor, intros i h', apply h.apply i h' (v.apply $ i), simp, end local attribute [instance] classical.prop_decidable lemma until_not_of_eventually {Γ p : cpred} : Γ ⊢ ◇p ⟶ -p 𝒰 p := begin lifted_pred, intro h, cases h with i h, induction i using nat.strong_induction_on with i ih, by_cases h' : ∃ j < i, σ + j ⊨ p, { rcases h' with ⟨j,h₀,h₁⟩, apply ih _ h₀ h₁ }, { simp only [not_exists] at h', existsi [i,h], apply h' } end lemma until_backward_induction {Γ p q : cpred} (h' : Γ ⊢ ◻(p ⟶ q)) (h : Γ ⊢ ◻(⊙q ⟶ -p ⟶ q)) : Γ ⊢ ◇p ⟶ q 𝒰 p := begin suffices : Γ ⊢ -p 𝒰 p ⟶ q 𝒰 p, { have h' := @until_not_of_eventually Γ p, lifted_pred using this h', tauto }, lifted_pred using h h', dsimp [until], apply exists_imp_exists, rintros i ⟨h₀,h₁⟩, existsi h₀, introv h₂, generalize h₃ : (i - (k + 1)) = n, induction n generalizing k, { apply h, dsimp [next], rw ← add_succ, apply h', convert h₀, apply le_antisymm, apply succ_le_of_lt h₂, apply nat.le_of_sub_eq_zero h₃, apply h₁ _ h₂, }, { apply h, { have h₄ : k + 1 ≤ i := succ_le_of_lt h₂, dsimp [next], rw ← add_succ, apply n_ih, rw nat.sub_eq_iff_eq_add at h₃; try { assumption }, { rw [h₃,succ_add], apply succ_lt_succ, apply lt_of_lt_of_le (lt_succ_self _), apply nat.le_add_left }, { apply succ.inj, rw [← h₃,succ_add,← succ_sub,succ_sub_succ_eq_sub], apply succ_le_of_lt, rw nat.sub_eq_iff_eq_add at h₃; try { assumption }, rw h₃, apply lt_add_of_pos_left, apply zero_lt_succ }, }, apply h₁ _ h₂, }, end lemma henceforth_until {Γ p q : cpred} (h : Γ ⊢ ◻(p 𝒰 q)) : Γ ⊢ ◻(p ⋁ q) := begin lifted_pred using h, intro i, specialize h i, rcases h with ⟨⟨j⟩,h₀,h₁⟩, { right, apply h₀ }, { left, apply h₁ 0, apply zero_lt_succ } end lemma henceforth_until' {Γ p : cpred} (q : cpred) (h : Γ ⊢ ◻(p 𝒰 (p ⋀ q))) : Γ ⊢ ◻p := begin replace h := henceforth_until h, suffices : p ⋁ p ⋀ q = p, { simp [this] at h, exact h }, lifted_pred, tauto, end def nelist (α : Type*) := { xs : list α // xs.empty = ff } def nelist.head {α : Type*} : nelist α → α | ⟨ x::xs, _ ⟩ := x def nelist.tail {α : Type*} : nelist α → option (nelist α) | ⟨ x::x'::xs, _ ⟩ := some ⟨ x'::xs, rfl ⟩ | ⟨ _ :: [], _ ⟩ := none def nelist.uncons {α : Type*} : nelist α → α ⊕ (α × nelist α) | ⟨ x::x'::xs, _ ⟩ := sum.inr (x,⟨x'::xs,rfl⟩) | ⟨ x :: [], _ ⟩ := sum.inl x def nelist.single {α : Type*} : α → nelist α | x := ⟨ x :: [] ,rfl ⟩ def nelist.cons {α : Type*} : α → nelist α → nelist α | x ⟨ xs, _⟩ := ⟨ x::xs,rfl ⟩ noncomputable def epsilon [nonempty α] (p : tvar (α → Prop)) : tvar α := ⟨ λ i, classical.epsilon $ i ⊨ p ⟩ section witness variables x₀ : tvar α variables f : tvar (α → α) variables (i : ℕ) open classical nat private def w : ℕ → α | 0 := i ⊨ x₀ | (succ j) := (i + j ⊨ f) (w j) lemma fwd_witness : ⊩ ∃∃ w, w ≃ x₀ ⋀ ◻( ⊙w ≃ f w ) := begin lifted_pred, existsi (⟨ λ i, w x₀ f x (i - x) ⟩ : tvar α), simp [nat.sub_self,w], intro i, have h : x + i ≥ x := nat.le_add_right _ _, simp [next,nat.add_sub_cancel_left,succ_sub h,w], end variables {P : cpred} variables (j : ℕ) local attribute [instance] classical.prop_decidable lemma first_P {p : ℕ → Prop} (h : ∃ i, p i) : (∃ i, (∀ j < i, ¬ p j) ∧ p i) := begin cases h with i h, induction i using nat.strong_induction_on with i ih, by_cases h' : (∀ (j : ℕ), j < i → ¬p j), { exact ⟨_,h',h⟩, }, { simp [not_forall] at h', rcases h' with ⟨j,h₀,h₁⟩, apply ih _ h₀ h₁, } end noncomputable def next_P {x} (h : x ⊨ ◻◇P) (y : ℕ) : ℕ := classical.some (first_P (h y)) lemma next_P_eq_self {x} (h : x ⊨ ◻◇P) (y : ℕ) (h' : x+y ⊨ P) : next_P h y = 0 := begin simp [next_P], apply_some_spec, intros h, by_contradiction h₂, replace h₂ := nat.lt_of_le_and_ne (nat.zero_le _) (ne.symm h₂), apply h.1 _ h₂, simp [h'] end lemma next_P_eq_succ {x} (h : x ⊨ ◻◇P) (y : ℕ) (h' : ¬ x+y ⊨ P) : next_P h y = succ (next_P h (succ y)) := begin simp [next_P], apply_some_spec, apply_some_spec, simp, intros h₀ h₁ h₂ h₃, by_contradiction h₄, replace h₄ := lt_or_gt_of_ne (h₄), cases h₄, cases x_1, { apply h', convert h₃ using 2, }, { replace h₄ := lt_of_succ_lt_succ h₄, apply h₀ _ h₄, convert h₃ using 2, simp [add_succ] }, { apply h₂ _ h₄, convert h₁ using 2, simp [add_succ] }, end lemma back_witness {Γ} (h : Γ ⊢ ◻◇P) : Γ ⊢ ∃∃ w, ◻( (P ⋀ w ≃ x₀) ⋁ (- P ⋀ w ≃ ⊙(f w)) ) := begin lifted_pred using h, existsi (⟨ λ i, w x₀ f (i) (next_P h (i - x)) ⟩ : tvar α), intro j, simp [nat.add_sub_cancel_left,w], by_cases h' : x + j ⊨ P; simp [next_P_eq_self,*,w], rw [next_P_eq_succ,w], congr' 1, { admit }, have : (succ (x + j) - x) = succ j, admit, rw this, clear this, end end witness end temporal
d8b92f5b93deaedbf8d9997e1446f7f65f6640de
3b15c7b0b62d8ada1399c112ad88a529e6bfa115
/src/Lean/Elab/Match.lean
b7c1f5c08a6933730a1f1222bd6c087fd7e0da26
[ "Apache-2.0" ]
permissive
stephenbrady/lean4
74bf5cae8a433e9c815708ce96c9e54a5caf2115
b1bd3fc304d0f7bc6810ec78bfa4c51476d263f9
refs/heads/master
1,692,621,473,161
1,634,308,743,000
1,634,310,749,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
45,520
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.Util.CollectFVars import Lean.Meta.Match.MatchPatternAttr import Lean.Meta.Match.Match import Lean.Meta.SortLocalDecls import Lean.Meta.GeneralizeVars import Lean.Elab.SyntheticMVars import Lean.Elab.Arg import Lean.Parser.Term import Lean.Elab.PatternVar namespace Lean.Elab.Term open Meta open Lean.Parser.Term private def expandSimpleMatch (stx discr lhsVar rhs : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do let newStx ← `(let $lhsVar := $discr; $rhs) withMacroExpansion stx newStx <| elabTerm newStx expectedType? private def mkUserNameFor (e : Expr) : TermElabM Name := do match e with /- Remark: we use `mkFreshUserName` to make sure we don't add a variable to the local context that can be resolved to `e`. -/ | Expr.fvar fvarId _ => mkFreshUserName ((← getLocalDecl fvarId).userName) | _ => mkFreshBinderName /-- Return true iff `n` is an auxiliary variable created by `expandNonAtomicDiscrs?` -/ def isAuxDiscrName (n : Name) : Bool := n.hasMacroScopes && n.eraseMacroScopes == `_discr /-- We treat `@x` as atomic to avoid unnecessary extra local declarations from being inserted into the local context. Recall that `expandMatchAltsIntoMatch` uses `@` modifier. Thus this is kind of discriminant is quite common. Remark: if the discriminat is `Systax.missing`, we abort the elaboration of the `match`-expression. This can happen due to error recovery. Example ``` example : (p ∨ p) → p := fun h => match ``` If we don't abort, the elaborator loops because we will keep trying to expand ``` match ``` into ``` let d := <Syntax.missing>; match ``` Recall that `Syntax.setArg stx i arg` is a no-op when `i` is out-of-bounds. -/ def isAtomicDiscr? (discr : Syntax) : TermElabM (Option Expr) := do match discr with | `($x:ident) => isLocalIdent? x | `(@$x:ident) => isLocalIdent? x | _ => if discr.isMissing then throwAbortTerm else return none -- See expandNonAtomicDiscrs? private def elabAtomicDiscr (discr : Syntax) : TermElabM Expr := do let term := discr[1] match (← isAtomicDiscr? term) with | some e@(Expr.fvar fvarId _) => let localDecl ← getLocalDecl fvarId if !isAuxDiscrName localDecl.userName then return e -- it is not an auxiliary local created by `expandNonAtomicDiscrs?` else instantiateMVars localDecl.value | _ => throwErrorAt discr "unexpected discriminant" structure ElabMatchTypeAndDiscrsResult where discrs : Array Expr matchType : Expr /- `true` when performing dependent elimination. We use this to decide whether we optimize the "match unit" case. See `isMatchUnit?`. -/ isDep : Bool alts : Array MatchAltView private partial def elabMatchTypeAndDiscrs (discrStxs : Array Syntax) (matchOptType : Syntax) (matchAltViews : Array MatchAltView) (expectedType : Expr) : TermElabM ElabMatchTypeAndDiscrsResult := do let numDiscrs := discrStxs.size if matchOptType.isNone then elabDiscrs 0 #[] else let matchTypeStx := matchOptType[0][1] let matchType ← elabType matchTypeStx let (discrs, isDep) ← elabDiscrsWitMatchType matchType expectedType return { discrs := discrs, matchType := matchType, isDep := isDep, alts := matchAltViews } where /- Easy case: elaborate discriminant when the match-type has been explicitly provided by the user. -/ elabDiscrsWitMatchType (matchType : Expr) (expectedType : Expr) : TermElabM (Array Expr × Bool) := do let mut discrs := #[] let mut i := 0 let mut matchType := matchType let mut isDep := false for discrStx in discrStxs do i := i + 1 matchType ← whnf matchType match matchType with | Expr.forallE _ d b _ => let discr ← fullApproxDefEq <| elabTermEnsuringType discrStx[1] d trace[Elab.match] "discr #{i} {discr} : {d}" if b.hasLooseBVars then isDep := true matchType ← b.instantiate1 discr discrs := discrs.push discr | _ => throwError "invalid type provided to match-expression, function type with arity #{discrStxs.size} expected" return (discrs, isDep) markIsDep (r : ElabMatchTypeAndDiscrsResult) := { r with isDep := true } /- Elaborate discriminants inferring the match-type -/ elabDiscrs (i : Nat) (discrs : Array Expr) : TermElabM ElabMatchTypeAndDiscrsResult := do if h : i < discrStxs.size then let discrStx := discrStxs.get ⟨i, h⟩ let discr ← elabAtomicDiscr discrStx let discr ← instantiateMVars discr let discrType ← inferType discr let discrType ← instantiateMVars discrType let discrs := discrs.push discr let userName ← mkUserNameFor discr if discrStx[0].isNone then let mut result ← elabDiscrs (i + 1) discrs let matchTypeBody ← kabstract result.matchType discr if matchTypeBody.hasLooseBVars then result := markIsDep result return { result with matchType := Lean.mkForall userName BinderInfo.default discrType matchTypeBody } else let discrs := discrs.push (← mkEqRefl discr) let result ← elabDiscrs (i + 1) discrs let result := markIsDep result let identStx := discrStx[0][0] withLocalDeclD userName discrType fun x => do let eqType ← mkEq discr x withLocalDeclD identStx.getId eqType fun h => do let matchTypeBody ← kabstract result.matchType discr let matchTypeBody := matchTypeBody.instantiate1 x let matchType ← mkForallFVars #[x, h] matchTypeBody return { result with matchType := matchType alts := result.alts.map fun altView => if i+1 > altView.patterns.size then -- Unexpected number of patterns. The input is invalid, but we want to process whatever to provide info to users. altView else { altView with patterns := altView.patterns.insertAt (i+1) identStx } } else return { discrs, alts := matchAltViews, isDep := false, matchType := expectedType } def expandMacrosInPatterns (matchAlts : Array MatchAltView) : MacroM (Array MatchAltView) := do matchAlts.mapM fun matchAlt => do let patterns ← matchAlt.patterns.mapM expandMacros pure { matchAlt with patterns := patterns } private def getMatchGeneralizing? : Syntax → Option Bool | `(match (generalizing := true) $discrs,* $[: $ty?]? with $alts:matchAlt*) => some true | `(match (generalizing := false) $discrs,* $[: $ty?]? with $alts:matchAlt*) => some false | _ => none /- Given `stx` a match-expression, return its alternatives. -/ private def getMatchAlts : Syntax → Array MatchAltView | `(match $[$gen]? $discrs,* $[: $ty?]? with $alts:matchAlt*) => alts.filterMap fun alt => match alt with | `(matchAltExpr| | $patterns,* => $rhs) => some { ref := alt, patterns := patterns, rhs := rhs } | _ => none | _ => #[] builtin_initialize Parser.registerBuiltinNodeKind `MVarWithIdKind open Meta.Match (mkInaccessible inaccessible?) /-- The elaboration function for `Syntax` created using `mkMVarSyntax`. It just converts the metavariable id wrapped by the Syntax into an `Expr`. -/ @[builtinTermElab MVarWithIdKind] def elabMVarWithIdKind : TermElab := fun stx expectedType? => return mkInaccessible <| mkMVar (getMVarSyntaxMVarId stx) @[builtinTermElab inaccessible] def elabInaccessible : TermElab := fun stx expectedType? => do let e ← elabTerm stx[1] expectedType? return mkInaccessible e open Lean.Elab.Term.Quotation in @[builtinQuotPrecheck Lean.Parser.Term.match] def precheckMatch : Precheck | `(match $[$discrs:term],* with $[| $[$patss],* => $rhss]*) => do discrs.forM precheck for (pats, rhs) in patss.zip rhss do let vars ← try getPatternsVars pats catch | _ => return -- can happen in case of pattern antiquotations Quotation.withNewLocals (getPatternVarNames vars) <| precheck rhs | _ => throwUnsupportedSyntax /- We convert the collected `PatternVar`s intro `PatternVarDecl` -/ inductive PatternVarDecl where /- For `anonymousVar`, we create both a metavariable and a free variable. The free variable is used as an assignment for the metavariable when it is not assigned during pattern elaboration. -/ | anonymousVar (mvarId : MVarId) (fvarId : FVarId) | localVar (fvarId : FVarId) private partial def withPatternVars {α} (pVars : Array PatternVar) (k : Array PatternVarDecl → TermElabM α) : TermElabM α := let rec loop (i : Nat) (decls : Array PatternVarDecl) := do if h : i < pVars.size then match pVars.get ⟨i, h⟩ with | PatternVar.anonymousVar mvarId => let type ← mkFreshTypeMVar let userName ← mkFreshBinderName withLocalDecl userName BinderInfo.default type fun x => loop (i+1) (decls.push (PatternVarDecl.anonymousVar mvarId x.fvarId!)) | PatternVar.localVar userName => let type ← mkFreshTypeMVar withLocalDecl userName BinderInfo.default type fun x => loop (i+1) (decls.push (PatternVarDecl.localVar x.fvarId!)) else /- We must create the metavariables for `PatternVar.anonymousVar` AFTER we create the new local decls using `withLocalDecl`. Reason: their scope must include the new local decls since some of them are assigned by typing constraints. -/ decls.forM fun decl => match decl with | PatternVarDecl.anonymousVar mvarId fvarId => do let type ← inferType (mkFVar fvarId) discard <| mkFreshExprMVarWithId mvarId type | _ => pure () k decls loop 0 #[] /- Remark: when performing dependent pattern matching, we often had to write code such as ```lean def Vec.map' (f : α → β) (xs : Vec α n) : Vec β n := match n, xs with | _, nil => nil | _, cons a as => cons (f a) (map' f as) ``` We had to include `n` and the `_`s because the type of `xs` depends on `n`. Moreover, `nil` and `cons a as` have different types. This was quite tedious. So, we have implemented an automatic "discriminant refinement procedure". The procedure is based on the observation that we get a type error whenenver we forget to include `_`s and the indices a discriminant depends on. So, we catch the exception, check whether the type of the discriminant is an indexed family, and add their indices as new discriminants. The current implementation, adds indices as they are found, and does not try to "sort" the new discriminants. If the refinement process fails, we report the original error message. -/ /- Auxiliary structure for storing an type mismatch exception when processing the pattern #`idx` of some alternative. -/ structure PatternElabException where ex : Exception patternIdx : Nat -- Discriminant that sh pathToIndex : List Nat -- Path to the problematic inductive type index that produced the type mismatch /-- This method is part of the "discriminant refinement" procedure. It in invoked when the type of the `pattern` does not match the expected type. The expected type is based on the motive computed using the `match` discriminants. It tries to compute a path to an index of the discriminant type. For example, suppose the user has written ``` inductive Mem (a : α) : List α → Prop where | head {as} : Mem a (a::as) | tail {as} : Mem a as → Mem a (a'::as) infix:50 " ∈ " => Mem example (a b : Nat) (h : a ∈ [b]) : b = a := match h with | Mem.head => rfl ``` The motive for the match is `a ∈ [b] → b = a`, and get a type mismatch between the type of `Mem.head` and `a ∈ [b]`. This procedure return the path `[2, 1]` to the index `b`. We use it to produce the following refinement ``` example (a b : Nat) (h : a ∈ [b]) : b = a := match b, h with | _, Mem.head => rfl ``` which produces the new motive `(x : Nat) → a ∈ [x] → x = a` After this refinement step, the `match` is elaborated successfully. This method relies on the fact that the dependent pattern matcher compiler solves equations between indices of indexed inductive families. The following kinds of equations are supported by this compiler: - `x = t` - `t = x` - `ctor ... = ctor ...` where `x` is a free variable, `t` is an arbitrary term, and `ctor` is constructor. Our procedure ensures that "information" is not lost, and will *not* succeed in an example such as ``` example (a b : Nat) (f : Nat → Nat) (h : f a ∈ [f b]) : f b = f a := match h with | Mem.head => rfl ``` and will not add `f b` as a new discriminant. We may add an option in the future to enable this more liberal form of refinement. -/ private partial def findDiscrRefinementPath (pattern : Expr) (expected : Expr) : OptionT MetaM (List Nat) := do goType (← instantiateMVars (← inferType pattern)) expected where checkCompatibleApps (t d : Expr) : OptionT MetaM Unit := do guard d.isApp guard <| t.getAppNumArgs == d.getAppNumArgs let tFn := t.getAppFn let dFn := d.getAppFn guard <| tFn.isConst && dFn.isConst guard (← isDefEq tFn dFn) -- Visitor for inductive types goType (t d : Expr) : OptionT MetaM (List Nat) := do trace[Meta.debug] "type {t} =?= {d}" let t ← whnf t let d ← whnf d checkCompatibleApps t d matchConstInduct t.getAppFn (fun _ => failure) fun info _ => do let tArgs := t.getAppArgs let dArgs := d.getAppArgs for i in [:info.numParams] do let tArg := tArgs[i] let dArg := dArgs[i] unless (← isDefEq tArg dArg) do return i :: (← goType tArg dArg) for i in [info.numParams : tArgs.size] do let tArg := tArgs[i] let dArg := dArgs[i] unless (← isDefEq tArg dArg) do return i :: (← goIndex tArg dArg) failure -- Visitor for indexed families goIndex (t d : Expr) : OptionT MetaM (List Nat) := do let t ← whnfD t let d ← whnfD d if t.isFVar || d.isFVar then return [] -- Found refinement path else trace[Meta.debug] "index {t} =?= {d}" checkCompatibleApps t d matchConstCtor t.getAppFn (fun _ => failure) fun info _ => do let tArgs := t.getAppArgs let dArgs := d.getAppArgs for i in [:info.numParams] do let tArg := tArgs[i] let dArg := dArgs[i] unless (← isDefEq tArg dArg) do failure for i in [info.numParams : tArgs.size] do let tArg := tArgs[i] let dArg := dArgs[i] unless (← isDefEq tArg dArg) do return i :: (← goIndex tArg dArg) failure private partial def eraseIndices (type : Expr) : MetaM Expr := do let type' ← whnfD type matchConstInduct type'.getAppFn (fun _ => return type) fun info _ => do let args := type'.getAppArgs let params ← args[:info.numParams].toArray.mapM eraseIndices let result := mkAppN type'.getAppFn params let resultType ← inferType result let (newIndices, _, _) ← forallMetaTelescopeReducing resultType (some (args.size - info.numParams)) return mkAppN result newIndices private def elabPatterns (patternStxs : Array Syntax) (matchType : Expr) : ExceptT PatternElabException TermElabM (Array Expr × Expr) := withReader (fun ctx => { ctx with implicitLambda := false }) do let mut patterns := #[] let mut matchType := matchType for idx in [:patternStxs.size] do let patternStx := patternStxs[idx] matchType ← whnf matchType match matchType with | Expr.forallE _ d b _ => let pattern ← do let s ← saveState try liftM <| withSynthesize <| withoutErrToSorry <| elabTermEnsuringType patternStx d catch ex : Exception => restoreState s match (← liftM <| commitIfNoErrors? <| withoutErrToSorry do elabTermAndSynthesize patternStx (← eraseIndices d)) with | some pattern => match (← findDiscrRefinementPath pattern d |>.run) with | some path => trace[Meta.debug] "refinement path: {path}" restoreState s -- Wrap the type mismatch exception for the "discriminant refinement" feature. throwThe PatternElabException { ex := ex, patternIdx := idx, pathToIndex := path } | none => restoreState s; throw ex | none => throw ex matchType := b.instantiate1 pattern patterns := patterns.push pattern | _ => throwError "unexpected match type" return (patterns, matchType) def finalizePatternDecls (patternVarDecls : Array PatternVarDecl) : TermElabM (Array LocalDecl) := do let mut decls := #[] for pdecl in patternVarDecls do match pdecl with | PatternVarDecl.localVar fvarId => let decl ← getLocalDecl fvarId let decl ← instantiateLocalDeclMVars decl decls := decls.push decl | PatternVarDecl.anonymousVar mvarId fvarId => let e ← instantiateMVars (mkMVar mvarId); trace[Elab.match] "finalizePatternDecls: mvarId: {mvarId.name} := {e}, fvar: {mkFVar fvarId}" match e with | Expr.mvar newMVarId _ => /- Metavariable was not assigned, or assigned to another metavariable. So, we assign to the auxiliary free variable we created at `withPatternVars` to `newMVarId`. -/ assignExprMVar newMVarId (mkFVar fvarId) trace[Elab.match] "finalizePatternDecls: {mkMVar newMVarId} := {mkFVar fvarId}" let decl ← getLocalDecl fvarId let decl ← instantiateLocalDeclMVars decl decls := decls.push decl | _ => pure () /- We perform a topological sort (dependecies) on `decls` because the pattern elaboration process may produce a sequence where a declaration d₁ may occur after d₂ when d₂ depends on d₁. -/ sortLocalDecls decls open Meta.Match (Pattern Pattern.var Pattern.inaccessible Pattern.ctor Pattern.as Pattern.val Pattern.arrayLit AltLHS MatcherResult) namespace ToDepElimPattern structure State where found : FVarIdSet := {} localDecls : Array LocalDecl newLocals : FVarIdSet := {} abbrev M := StateRefT State TermElabM private def alreadyVisited (fvarId : FVarId) : M Bool := do let s ← get return s.found.contains fvarId private def markAsVisited (fvarId : FVarId) : M Unit := modify fun s => { s with found := s.found.insert fvarId } private def throwInvalidPattern {α} (e : Expr) : M α := throwError "invalid pattern {indentExpr e}" /- Create a new LocalDecl `x` for the metavariable `mvar`, and return `Pattern.var x` -/ private def mkLocalDeclFor (mvar : Expr) : M Pattern := do let mvarId := mvar.mvarId! let s ← get match (← getExprMVarAssignment? mvarId) with | some val => return Pattern.inaccessible val | none => let fvarId ← mkFreshFVarId let type ← inferType mvar /- HACK: `fvarId` is not in the scope of `mvarId` If this generates problems in the future, we should update the metavariable declarations. -/ assignExprMVar mvarId (mkFVar fvarId) let userName ← mkFreshBinderName let newDecl := LocalDecl.cdecl arbitrary fvarId userName type BinderInfo.default; modify fun s => { s with newLocals := s.newLocals.insert fvarId, localDecls := match s.localDecls.findIdx? fun decl => mvar.occurs decl.type with | none => s.localDecls.push newDecl -- None of the existing declarations depend on `mvar` | some i => s.localDecls.insertAt i newDecl } return Pattern.var fvarId partial def main (e : Expr) : M Pattern := do let isLocalDecl (fvarId : FVarId) : M Bool := do return (← get).localDecls.any fun d => d.fvarId == fvarId let mkPatternVar (fvarId : FVarId) (e : Expr) : M Pattern := do if (← alreadyVisited fvarId) then return Pattern.inaccessible e else markAsVisited fvarId return Pattern.var e.fvarId! let mkInaccessible (e : Expr) : M Pattern := do match e with | Expr.fvar fvarId _ => if (← isLocalDecl fvarId) then mkPatternVar fvarId e else return Pattern.inaccessible e | _ => return Pattern.inaccessible e match inaccessible? e with | some t => mkInaccessible t | none => match e.arrayLit? with | some (α, lits) => return Pattern.arrayLit α (← lits.mapM main) | none => if e.isAppOfArity `namedPattern 3 then let p ← main <| e.getArg! 2 match e.getArg! 1 with | Expr.fvar fvarId _ => return Pattern.as fvarId p | _ => throwError "unexpected occurrence of auxiliary declaration 'namedPattern'" else if isMatchValue e then return Pattern.val e else if e.isFVar then let fvarId := e.fvarId! unless (← isLocalDecl fvarId) do throwInvalidPattern e mkPatternVar fvarId e else if e.isMVar then mkLocalDeclFor e else let newE ← whnf e if newE != e then main newE else matchConstCtor e.getAppFn (fun _ => do if (← isProof e) then /- We mark nested proofs as inaccessible. This is fine due to proof irrelevance. We need this feature to be able to elaborate definitions such as: ``` def f : Fin 2 → Nat | 0 => 5 | 1 => 45 ``` -/ return Pattern.inaccessible e else throwInvalidPattern e) (fun v us => do let args := e.getAppArgs unless args.size == v.numParams + v.numFields do throwInvalidPattern e let params := args.extract 0 v.numParams let fields := args.extract v.numParams args.size let fields ← fields.mapM main return Pattern.ctor v.name us params.toList fields.toList) end ToDepElimPattern def withDepElimPatterns {α} (localDecls : Array LocalDecl) (ps : Array Expr) (k : Array LocalDecl → Array Pattern → TermElabM α) : TermElabM α := do let (patterns, s) ← (ps.mapM ToDepElimPattern.main).run { localDecls := localDecls } let localDecls ← s.localDecls.mapM fun d => instantiateLocalDeclMVars d /- toDepElimPatterns may have added new localDecls. Thus, we must update the local context before we execute `k` -/ let lctx ← getLCtx let lctx := localDecls.foldl (fun (lctx : LocalContext) d => lctx.erase d.fvarId) lctx let lctx := localDecls.foldl (fun (lctx : LocalContext) d => lctx.addDecl d) lctx withTheReader Meta.Context (fun ctx => { ctx with lctx := lctx }) do k localDecls patterns private def withElaboratedLHS {α} (ref : Syntax) (patternVarDecls : Array PatternVarDecl) (patternStxs : Array Syntax) (matchType : Expr) (k : AltLHS → Expr → TermElabM α) : ExceptT PatternElabException TermElabM α := do let (patterns, matchType) ← withSynthesize <| elabPatterns patternStxs matchType id (α := TermElabM α) do let localDecls ← finalizePatternDecls patternVarDecls let patterns ← patterns.mapM (instantiateMVars ·) withDepElimPatterns localDecls patterns fun localDecls patterns => k { ref := ref, fvarDecls := localDecls.toList, patterns := patterns.toList } matchType private def elabMatchAltView (alt : MatchAltView) (matchType : Expr) : ExceptT PatternElabException TermElabM (AltLHS × Expr) := withRef alt.ref do let (patternVars, alt) ← collectPatternVars alt trace[Elab.match] "patternVars: {patternVars}" withPatternVars patternVars fun patternVarDecls => do withElaboratedLHS alt.ref patternVarDecls alt.patterns matchType fun altLHS matchType => do let rhs ← elabTermEnsuringType alt.rhs matchType let xs := altLHS.fvarDecls.toArray.map LocalDecl.toExpr let rhs ← if xs.isEmpty then pure <| mkSimpleThunk rhs else mkLambdaFVars xs rhs trace[Elab.match] "rhs: {rhs}" return (altLHS, rhs) /-- Collect problematic index for the "discriminant refinement feature". This method is invoked when we detect a type mismatch at a pattern #`idx` of some alternative. -/ private partial def getIndexToInclude? (discr : Expr) (pathToIndex : List Nat) : TermElabM (Option Expr) := do go (← inferType discr) pathToIndex |>.run where go (e : Expr) (path : List Nat) : OptionT MetaM Expr := do match path with | [] => return e | i::path => let e ← whnfD e guard <| e.isApp && i < e.getAppNumArgs go (e.getArg! i) path /-- "Generalize" variables that depend on the discriminants. Remarks and limitations: - If `matchType` is a proposition, then we generalize even when the user did not provide `(generalizing := true)`. Motivation: users should have control about the actual `match`-expressions in their programs. - We currently do not generalize let-decls. - We abort generalization if the new `matchType` is type incorrect. - Only discriminants that are free variables are considered during specialization. - We "generalize" by adding new discriminants and pattern variables. We do not "clear" the generalized variables, but they become inaccessible since they are shadowed by the patterns variables. We assume this is ok since this is the exact behavior users would get if they had written it by hand. Recall there is no `clear` in term mode. -/ private def generalize (discrs : Array Expr) (matchType : Expr) (altViews : Array MatchAltView) (generalizing? : Option Bool) : TermElabM (Array Expr × Expr × Array MatchAltView × Bool) := do let gen ← match generalizing? with | some g => pure g | _ => isProp matchType if !gen then return (discrs, matchType, altViews, false) else let ysFVarIds ← getFVarsToGeneralize discrs /- let-decls are currently being ignored by the generalizer. -/ let ysFVarIds ← ysFVarIds.filterM fun fvarId => return !(← getLocalDecl fvarId).isLet if ysFVarIds.isEmpty then return (discrs, matchType, altViews, false) else let ys := ysFVarIds.map mkFVar -- trace[Meta.debug] "ys: {ys}, discrs: {discrs}" let matchType' ← forallBoundedTelescope matchType discrs.size fun ds type => do let type ← mkForallFVars ys type let (discrs', ds') := Array.unzip <| Array.zip discrs ds |>.filter fun (di, d) => di.isFVar let type := type.replaceFVars discrs' ds' mkForallFVars ds type -- trace[Meta.debug] "matchType': {matchType'}" if (← isTypeCorrect matchType') then let discrs := discrs ++ ys let altViews ← altViews.mapM fun altView => do let patternVars ← getPatternsVars altView.patterns -- We traverse backwards because we want to keep the most recent names. -- For example, if `ys` contains `#[h, h]`, we want to make sure `mkFreshUsername is applied to the first `h`, -- since it is already shadowed by the second. let ysUserNames ← ys.foldrM (init := #[]) fun ys ysUserNames => do let yDecl ← getLocalDecl ys.fvarId! let mut yUserName := yDecl.userName if ysUserNames.contains yUserName then yUserName ← mkFreshUserName yUserName -- Explicitly provided pattern variables shadow `y` else if patternVars.any fun | PatternVar.localVar x => x == yUserName | _ => false then yUserName ← mkFreshUserName yUserName return ysUserNames.push yUserName let ysIds ← ysUserNames.reverse.mapM fun n => return mkIdentFrom (← getRef) n return { altView with patterns := altView.patterns ++ ysIds } return (discrs, matchType', altViews, true) else return (discrs, matchType, altViews, true) private partial def elabMatchAltViews (generalizing? : Option Bool) (discrs : Array Expr) (matchType : Expr) (altViews : Array MatchAltView) : TermElabM (Array Expr × Expr × Array (AltLHS × Expr) × Bool) := do loop discrs matchType altViews none where /- "Discriminant refinement" main loop. `first?` contains the first error message we found before updated the `discrs`. -/ loop (discrs : Array Expr) (matchType : Expr) (altViews : Array MatchAltView) (first? : Option (SavedState × Exception)) : TermElabM (Array Expr × Expr × Array (AltLHS × Expr) × Bool) := do let s ← saveState let (discrs', matchType', altViews', refined) ← generalize discrs matchType altViews generalizing? match (← altViews'.mapM (fun altView => elabMatchAltView altView matchType') |>.run) with | Except.ok alts => return (discrs', matchType', alts, first?.isSome || refined) | Except.error { patternIdx := patternIdx, pathToIndex := pathToIndex, ex := ex } => trace[Meta.debug] "pathToIndex: {toString pathToIndex}" let some index ← getIndexToInclude? discrs[patternIdx] pathToIndex | throwEx (← updateFirst first? ex) trace[Meta.debug] "index: {index}" if (← discrs.anyM fun discr => isDefEq discr index) then throwEx (← updateFirst first? ex) let first ← updateFirst first? ex s.restore let indices ← collectDeps #[index] discrs let matchType ← try updateMatchType indices matchType catch ex => throwEx first let altViews ← addWildcardPatterns indices.size altViews let discrs := indices ++ discrs loop discrs matchType altViews first throwEx {α} (p : SavedState × Exception) : TermElabM α := do p.1.restore; throw p.2 updateFirst (first? : Option (SavedState × Exception)) (ex : Exception) : TermElabM (SavedState × Exception) := do match first? with | none => return (← saveState, ex) | some first => return first containsFVar (es : Array Expr) (fvarId : FVarId) : Bool := es.any fun e => e.isFVar && e.fvarId! == fvarId /- Update `indices` by including any free variable `x` s.t. - Type of some `discr` depends on `x`. - Type of `x` depends on some free variable in `indices`. If we don't include these extra variables in indices, then `updateMatchType` will generate a type incorrect term. For example, suppose `discr` contains `h : @HEq α a α b`, and `indices` is `#[α, b]`, and `matchType` is `@HEq α a α b → B`. `updateMatchType indices matchType` produces the type `(α' : Type) → (b : α') → @HEq α' a α' b → B` which is type incorrect because we have `a : α`. The method `collectDeps` will include `a` into `indices`. This method does not handle dependencies among non-free variables. We rely on the type checking method `check` at `updateMatchType`. Remark: `indices : Array Expr` does not need to be an array anymore. We should cleanup this code, and use `index : Expr` instead. -/ collectDeps (indices : Array Expr) (discrs : Array Expr) : TermElabM (Array Expr) := do let mut s : CollectFVars.State := {} for discr in discrs do s := collectFVars s (← instantiateMVars (← inferType discr)) let (indicesFVar, indicesNonFVar) := indices.split Expr.isFVar let indicesFVar := indicesFVar.map Expr.fvarId! let mut toAdd := #[] for fvarId in s.fvarSet.toList do unless containsFVar discrs fvarId || containsFVar indices fvarId do let localDecl ← getLocalDecl fvarId let mctx ← getMCtx for indexFVarId in indicesFVar do if mctx.localDeclDependsOn localDecl indexFVarId then toAdd := toAdd.push fvarId let indicesFVar ← sortFVarIds (indicesFVar ++ toAdd) return indicesFVar.map mkFVar ++ indicesNonFVar updateMatchType (indices : Array Expr) (matchType : Expr) : TermElabM Expr := do let matchType ← indices.foldrM (init := matchType) fun index matchType => do let indexType ← inferType index let matchTypeBody ← kabstract matchType index let userName ← mkUserNameFor index return Lean.mkForall userName BinderInfo.default indexType matchTypeBody check matchType return matchType addWildcardPatterns (num : Nat) (altViews : Array MatchAltView) : TermElabM (Array MatchAltView) := do let hole := mkHole (← getRef) let wildcards := mkArray num hole return altViews.map fun altView => { altView with patterns := wildcards ++ altView.patterns } def mkMatcher (input : Meta.Match.MkMatcherInput) : TermElabM MatcherResult := Meta.Match.mkMatcher input register_builtin_option match.ignoreUnusedAlts : Bool := { defValue := false descr := "if true, do not generate error if an alternative is not used" } def reportMatcherResultErrors (altLHSS : List AltLHS) (result : MatcherResult) : TermElabM Unit := do unless result.counterExamples.isEmpty do withHeadRefOnly <| logError m!"missing cases:\n{Meta.Match.counterExamplesToMessageData result.counterExamples}" unless match.ignoreUnusedAlts.get (← getOptions) || result.unusedAltIdxs.isEmpty do let mut i := 0 for alt in altLHSS do if result.unusedAltIdxs.contains i then withRef alt.ref do logError "redundant alternative" i := i + 1 /-- If `altLHSS + rhss` is encoding `| PUnit.unit => rhs[0]`, return `rhs[0]` Otherwise, return none. -/ private def isMatchUnit? (altLHSS : List Match.AltLHS) (rhss : Array Expr) : MetaM (Option Expr) := do assert! altLHSS.length == rhss.size match altLHSS with | [ { fvarDecls := [], patterns := [ Pattern.ctor `PUnit.unit .. ], .. } ] => /- Recall that for alternatives of the form `| PUnit.unit => rhs`, `rhss[0]` is of the form `fun _ : Unit => b`. -/ match rhss[0] with | Expr.lam _ _ b _ => return if b.hasLooseBVars then none else b | _ => return none | _ => return none private def elabMatchAux (generalizing? : Option Bool) (discrStxs : Array Syntax) (altViews : Array MatchAltView) (matchOptType : Syntax) (expectedType : Expr) : TermElabM Expr := do let mut generalizing? := generalizing? if !matchOptType.isNone then if generalizing? == some true then throwError "the '(generalizing := true)' parameter is not supported when the 'match' type is explicitly provided" generalizing? := some false let (discrs, matchType, altLHSS, isDep, rhss) ← commitIfDidNotPostpone do let ⟨discrs, matchType, isDep, altViews⟩ ← elabMatchTypeAndDiscrs discrStxs matchOptType altViews expectedType let matchAlts ← liftMacroM <| expandMacrosInPatterns altViews trace[Elab.match] "matchType: {matchType}" let (discrs, matchType, alts, refined) ← elabMatchAltViews generalizing? discrs matchType matchAlts let isDep := isDep || refined /- We should not use `synthesizeSyntheticMVarsNoPostponing` here. Otherwise, we will not be able to elaborate examples such as: ``` def f (x : Nat) : Option Nat := none def g (xs : List (Nat × Nat)) : IO Unit := xs.forM fun x => match f x.fst with | _ => pure () ``` If `synthesizeSyntheticMVarsNoPostponing`, the example above fails at `x.fst` because the type of `x` is only available after we proces the last argument of `List.forM`. We apply pending default types to make sure we can process examples such as ``` let (a, b) := (0, 0) ``` -/ synthesizeSyntheticMVarsUsingDefault let rhss := alts.map Prod.snd let matchType ← instantiateMVars matchType let altLHSS ← alts.toList.mapM fun alt => do let altLHS ← Match.instantiateAltLHSMVars alt.1 /- Remark: we try to postpone before throwing an error. The combinator `commitIfDidNotPostpone` ensures we backtrack any updates that have been performed. The quick-check `waitExpectedTypeAndDiscrs` minimizes the number of scenarios where we have to postpone here. Here is an example that passes the `waitExpectedTypeAndDiscrs` test, but postpones here. ``` def bad (ps : Array (Nat × Nat)) : Array (Nat × Nat) := (ps.filter fun (p : Prod _ _) => match p with | (x, y) => x == 0) ++ ps ``` When we try to elaborate `fun (p : Prod _ _) => ...` for the first time, we haven't propagated the type of `ps` yet because `Array.filter` has type `{α : Type u_1} → (α → Bool) → (as : Array α) → optParam Nat 0 → optParam Nat (Array.size as) → Array α` However, the partial type annotation `(p : Prod _ _)` makes sure we succeed at the quick-check `waitExpectedTypeAndDiscrs`. -/ withRef altLHS.ref do for d in altLHS.fvarDecls do if d.hasExprMVar then withExistingLocalDecls altLHS.fvarDecls do tryPostpone throwMVarError m!"invalid match-expression, type of pattern variable '{d.toExpr}' contains metavariables{indentExpr d.type}" for p in altLHS.patterns do if p.hasExprMVar then withExistingLocalDecls altLHS.fvarDecls do tryPostpone throwMVarError m!"invalid match-expression, pattern contains metavariables{indentExpr (← p.toExpr)}" pure altLHS return (discrs, matchType, altLHSS, isDep, rhss) if let some r ← if isDep then pure none else isMatchUnit? altLHSS rhss then return r else let numDiscrs := discrs.size let matcherName ← mkAuxName `match let matcherResult ← mkMatcher { matcherName, matchType, numDiscrs, lhss := altLHSS } matcherResult.addMatcher let motive ← forallBoundedTelescope matchType numDiscrs fun xs matchType => mkLambdaFVars xs matchType reportMatcherResultErrors altLHSS matcherResult let r := mkApp matcherResult.matcher motive let r := mkAppN r discrs let r := mkAppN r rhss trace[Elab.match] "result: {r}" return r private def getDiscrs (matchStx : Syntax) : Array Syntax := matchStx[2].getSepArgs private def getMatchOptType (matchStx : Syntax) : Syntax := matchStx[3] private def expandNonAtomicDiscrs? (matchStx : Syntax) : TermElabM (Option Syntax) := let matchOptType := getMatchOptType matchStx; if matchOptType.isNone then do let discrs := getDiscrs matchStx; let allLocal ← discrs.allM fun discr => Option.isSome <$> isAtomicDiscr? discr[1] if allLocal then return none else -- We use `foundFVars` to make sure the discriminants are distinct variables. -- See: code for computing "matchType" at `elabMatchTypeAndDiscrs` let rec loop (discrs : List Syntax) (discrsNew : Array Syntax) (foundFVars : FVarIdSet) := do match discrs with | [] => let discrs := Syntax.mkSep discrsNew (mkAtomFrom matchStx ", "); pure (matchStx.setArg 2 discrs) | discr :: discrs => -- Recall that -- matchDiscr := leading_parser optional (ident >> ":") >> termParser let term := discr[1] let addAux : TermElabM Syntax := withFreshMacroScope do let d ← `(_discr); unless isAuxDiscrName d.getId do -- Use assertion? throwError "unexpected internal auxiliary discriminant name" let discrNew := discr.setArg 1 d; let r ← loop discrs (discrsNew.push discrNew) foundFVars `(let _discr := $term; $r) match (← isAtomicDiscr? term) with | some x => if x.isFVar then loop discrs (discrsNew.push discr) (foundFVars.insert x.fvarId!) else addAux | none => addAux return some (← loop discrs.toList #[] {}) else -- We do not pull non atomic discriminants when match type is provided explicitly by the user return none private def waitExpectedType (expectedType? : Option Expr) : TermElabM Expr := do tryPostponeIfNoneOrMVar expectedType? match expectedType? with | some expectedType => pure expectedType | none => mkFreshTypeMVar private def tryPostponeIfDiscrTypeIsMVar (matchStx : Syntax) : TermElabM Unit := do -- We don't wait for the discriminants types when match type is provided by user if getMatchOptType matchStx |>.isNone then let discrs := getDiscrs matchStx for discr in discrs do let term := discr[1] match (← isAtomicDiscr? term) with | none => throwErrorAt discr "unexpected discriminant" -- see `expandNonAtomicDiscrs? | some d => let dType ← inferType d trace[Elab.match] "discr {d} : {dType}" tryPostponeIfMVar dType /- We (try to) elaborate a `match` only when the expected type is available. If the `matchType` has not been provided by the user, we also try to postpone elaboration if the type of a discriminant is not available. That is, it is of the form `(?m ...)`. We use `expandNonAtomicDiscrs?` to make sure all discriminants are local variables. This is a standard trick we use in the elaborator, and it is also used to elaborate structure instances. Suppose, we are trying to elaborate ``` match g x with | ... => ... ``` `expandNonAtomicDiscrs?` converts it intro ``` let _discr := g x match _discr with | ... => ... ``` Thus, at `tryPostponeIfDiscrTypeIsMVar` we only need to check whether the type of `_discr` is not of the form `(?m ...)`. Note that, the auxiliary variable `_discr` is expanded at `elabAtomicDiscr`. This elaboration technique is needed to elaborate terms such as: ```lean xs.filter fun (a, b) => a > b ``` which are syntax sugar for ```lean List.filter (fun p => match p with | (a, b) => a > b) xs ``` When we visit `match p with | (a, b) => a > b`, we don't know the type of `p` yet. -/ private def waitExpectedTypeAndDiscrs (matchStx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do tryPostponeIfNoneOrMVar expectedType? tryPostponeIfDiscrTypeIsMVar matchStx match expectedType? with | some expectedType => return expectedType | none => mkFreshTypeMVar /- ``` leading_parser:leadPrec "match " >> sepBy1 matchDiscr ", " >> optType >> " with " >> matchAlts ``` Remark the `optIdent` must be `none` at `matchDiscr`. They are expanded by `expandMatchDiscr?`. -/ private def elabMatchCore (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do let expectedType ← waitExpectedTypeAndDiscrs stx expectedType? let discrStxs := (getDiscrs stx).map fun d => d let gen? := getMatchGeneralizing? stx let altViews := getMatchAlts stx let matchOptType := getMatchOptType stx elabMatchAux gen? discrStxs altViews matchOptType expectedType private def isPatternVar (stx : Syntax) : TermElabM Bool := do match (← resolveId? stx "pattern") with | none => isAtomicIdent stx | some f => match f with | Expr.const fName _ _ => match (← getEnv).find? fName with | some (ConstantInfo.ctorInfo _) => return false | some _ => return !hasMatchPatternAttribute (← getEnv) fName | _ => isAtomicIdent stx | _ => isAtomicIdent stx where isAtomicIdent (stx : Syntax) : Bool := stx.isIdent && stx.getId.eraseMacroScopes.isAtomic -- leading_parser "match " >> sepBy1 termParser ", " >> optType >> " with " >> matchAlts @[builtinTermElab «match»] def elabMatch : TermElab := fun stx expectedType? => do match stx with | `(match $discr:term with | $y:ident => $rhs:term) => if (← isPatternVar y) then expandSimpleMatch stx discr y rhs expectedType? else elabMatchDefault stx expectedType? | _ => elabMatchDefault stx expectedType? where elabMatchDefault (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do match (← expandNonAtomicDiscrs? stx) with | some stxNew => withMacroExpansion stx stxNew <| elabTerm stxNew expectedType? | none => let discrs := getDiscrs stx; let matchOptType := getMatchOptType stx; if !matchOptType.isNone && discrs.any fun d => !d[0].isNone then throwErrorAt matchOptType "match expected type should not be provided when discriminants with equality proofs are used" elabMatchCore stx expectedType? builtin_initialize registerTraceClass `Elab.match -- leading_parser:leadPrec "nomatch " >> termParser @[builtinTermElab «nomatch»] def elabNoMatch : TermElab := fun stx expectedType? => do match stx with | `(nomatch $discrExpr) => match (← isLocalIdent? discrExpr) with | some _ => let expectedType ← waitExpectedType expectedType? let discr := Syntax.node ``Lean.Parser.Term.matchDiscr #[mkNullNode, discrExpr] elabMatchAux none #[discr] #[] mkNullNode expectedType | _ => let stxNew ← `(let _discr := $discrExpr; nomatch _discr) withMacroExpansion stx stxNew <| elabTerm stxNew expectedType? | _ => throwUnsupportedSyntax end Lean.Elab.Term
ebd384c2ad50e544aed18863cc3dccd71df69b7d
5ee26964f602030578ef0159d46145dd2e357ba5
/src/for_mathlib/uniform_space/group.lean
d52e5fabcd296206fe618c4fb252537f1e5bb2d2
[ "Apache-2.0" ]
permissive
fpvandoorn/lean-perfectoid-spaces
569b4006fdfe491ca8b58dd817bb56138ada761f
06cec51438b168837fc6e9268945735037fd1db6
refs/heads/master
1,590,154,571,918
1,557,685,392,000
1,557,685,392,000
186,363,547
0
0
Apache-2.0
1,557,730,933,000
1,557,730,933,000
null
UTF-8
Lean
false
false
3,557
lean
import topology.algebra.group_completion import for_mathlib.uniform_space.separation noncomputable theory local attribute [instance, priority 0] classical.prop_decidable section uniform_add_group_sep_quot open uniform_space variables {α : Type*} [add_group α] [uniform_space α] [uniform_add_group α] variables {β : Type*} [add_group β] [uniform_space β] [uniform_add_group β] lemma separated_of_group_hom {f : α → β} [is_add_group_hom f] (hf : continuous f) : separated_map f := (uniform_continuous_of_continuous hf).separated_map lemma uniform_continuous₂_add : uniform_continuous₂ ((+) : α → α → α) := begin dsimp [uniform_continuous₂], convert @uniform_continuous_add' α _ _ _, ext x, cases x, refl end local attribute [instance] separation_setoid instance uniform_space_sep_quot.add_group : add_group (sep_quot α) := { add := sep_quot.map₂ (+), add_assoc := begin apply sep_quot.map₂_assoc ; try { exact uniform_continuous₂_add.separated_map }, exact add_assoc end, zero := ⟦0⟧, zero_add := begin change ∀ a : sep_quot α, sep_quot.map₂ has_add.add ⟦0⟧ a = id a, rw ←sep_quot.map_id, exact sep_quot.map₂_const_left_eq_map uniform_continuous₂_add.separated_map uniform_continuous_id.separated_map _ zero_add end, add_zero := begin change ∀ a : sep_quot α, sep_quot.map₂ has_add.add a ⟦0⟧ = id a, rw ←sep_quot.map_id, exact sep_quot.map₂_const_right_eq_map uniform_continuous₂_add.separated_map uniform_continuous_id.separated_map _ add_zero end, neg := sep_quot.map add_group.neg, add_left_neg := sep_quot.map₂_map_left_self_const uniform_continuous₂_add.separated_map uniform_continuous_neg'.separated_map (0 : α) add_left_neg } -- MOVEME theorem uniform_add_group.mk'' {α} [uniform_space α] [add_group α] (h₁ : uniform_continuous₂ ((+) : α → α → α)) (h₂ : uniform_continuous (λp:α, -p)) : uniform_add_group α := ⟨(uniform_continuous_fst.prod_mk (uniform_continuous_snd.comp h₂)).comp h₁⟩ instance : uniform_add_group (sep_quot α) := uniform_add_group.mk'' (sep_quot.uniform_continuous_map₂ uniform_continuous₂_add) (sep_quot.uniform_continuous_map uniform_continuous_neg') lemma sep_quot.add_mk (a b : α) : ⟦a⟧ + ⟦b⟧ = ⟦a+b⟧ := sep_quot.map₂_mk_mk uniform_continuous₂_add.separated_map _ _ instance sep_quot.is_add_group_hom_mk : is_add_group_hom (quotient.mk : α → sep_quot α) := ⟨λ a b, eq.symm $ sep_quot.add_mk a b⟩ variables {f : α → β} instance sep_quot.is_add_group_hom_lift [separated β] [hom : is_add_group_hom f] (hf : continuous f) : is_add_group_hom (sep_quot.lift f) := ⟨begin rintros ⟨a⟩ ⟨b⟩, repeat { rw quot_mk_quotient_mk }, rw [sep_quot.add_mk], repeat { rw sep_quot.lift_mk (separated_of_group_hom hf) }, rw hom.map_add, end⟩ instance sep_quot.is_add_group_hom_map [hom : is_add_group_hom f](hf : continuous f) : is_add_group_hom (sep_quot.map f) := sep_quot.is_add_group_hom_lift (hf.comp continuous_quotient_mk) end uniform_add_group_sep_quot section uniform_add_comm_group_sep_quot open uniform_space variables {α : Type*} [add_comm_group α] [uniform_space α] [uniform_add_group α] local attribute [instance] separation_setoid instance uniform_space.sep_quot.add_comm_group : add_comm_group (sep_quot α) := { add_comm := sep_quot.map₂_comm uniform_continuous₂_add.separated_map add_comm, ..uniform_space_sep_quot.add_group, } end uniform_add_comm_group_sep_quot
7a4bea10d69e5a1917ca93bb5f70e64d15f5d4f3
4727251e0cd73359b15b664c3170e5d754078599
/src/data/real/pi/bounds.lean
82276154949846317dbbd3a0b81adc8b5ba3b408
[ "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
7,777
lean
/- Copyright (c) 2019 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Mario Carneiro -/ import analysis.special_functions.trigonometric.bounds /-! # Pi This file contains lemmas which establish bounds on `real.pi`. Notably, these include `pi_gt_sqrt_two_add_series` and `pi_lt_sqrt_two_add_series`, which bound `π` using series; numerical bounds on `π` such as `pi_gt_314`and `pi_lt_315` (more precise versions are given, too). See also `data.real.pi.leibniz` and `data.real.pi.wallis` for infinite formulas for `π`. -/ open_locale real namespace real lemma pi_gt_sqrt_two_add_series (n : ℕ) : 2 ^ (n+1) * sqrt (2 - sqrt_two_add_series 0 n) < π := begin have : sqrt (2 - sqrt_two_add_series 0 n) / 2 * 2 ^ (n+2) < π, { rw [← lt_div_iff, ←sin_pi_over_two_pow_succ], apply sin_lt, apply div_pos pi_pos, all_goals { apply pow_pos, norm_num } }, apply lt_of_le_of_lt (le_of_eq _) this, rw [pow_succ _ (n+1), ←mul_assoc, div_mul_cancel, mul_comm], norm_num end lemma pi_lt_sqrt_two_add_series (n : ℕ) : π < 2 ^ (n+1) * sqrt (2 - sqrt_two_add_series 0 n) + 1 / 4 ^ n := begin have : π < (sqrt (2 - sqrt_two_add_series 0 n) / 2 + 1 / (2 ^ n) ^ 3 / 4) * 2 ^ (n+2), { rw [← div_lt_iff, ← sin_pi_over_two_pow_succ], refine lt_of_lt_of_le (lt_add_of_sub_right_lt (sin_gt_sub_cube _ _)) _, { apply div_pos pi_pos, apply pow_pos, norm_num }, { rw div_le_iff', { refine le_trans pi_le_four _, simp only [show ((4 : ℝ) = 2 ^ 2), by norm_num, mul_one], apply pow_le_pow, norm_num, apply le_add_of_nonneg_left, apply nat.zero_le }, { apply pow_pos, norm_num } }, apply add_le_add_left, rw div_le_div_right, rw [le_div_iff, ←mul_pow], refine le_trans _ (le_of_eq (one_pow 3)), apply pow_le_pow_of_le_left, { apply le_of_lt, apply mul_pos, apply div_pos pi_pos, apply pow_pos, norm_num, apply pow_pos, norm_num }, rw ← le_div_iff, refine le_trans ((div_le_div_right _).mpr pi_le_four) _, apply pow_pos, norm_num, rw [pow_succ, pow_succ, ←mul_assoc, ←div_div], convert le_rfl, all_goals { repeat {apply pow_pos}, norm_num }}, apply lt_of_lt_of_le this (le_of_eq _), rw [add_mul], congr' 1, { rw [pow_succ _ (n+1), ←mul_assoc, div_mul_cancel, mul_comm], norm_num }, rw [pow_succ, ←pow_mul, mul_comm n 2, pow_mul, show (2 : ℝ) ^ 2 = 4, by norm_num, pow_succ, pow_succ, ←mul_assoc (2 : ℝ), show (2 : ℝ) * 2 = 4, by norm_num, ←mul_assoc, div_mul_cancel, mul_comm ((2 : ℝ) ^ n), ←div_div, div_mul_cancel], apply pow_ne_zero, norm_num, norm_num end /-- From an upper bound on `sqrt_two_add_series 0 n = 2 cos (π / 2 ^ (n+1))` of the form `sqrt_two_add_series 0 n ≤ 2 - (a / 2 ^ (n + 1)) ^ 2)`, one can deduce the lower bound `a < π` thanks to basic trigonometric inequalities as expressed in `pi_gt_sqrt_two_add_series`. -/ theorem pi_lower_bound_start (n : ℕ) {a} (h : sqrt_two_add_series ((0:ℕ) / (1:ℕ)) n ≤ 2 - (a / 2 ^ (n + 1)) ^ 2) : a < π := begin refine lt_of_le_of_lt _ (pi_gt_sqrt_two_add_series n), rw [mul_comm], refine (div_le_iff (pow_pos (by norm_num) _ : (0 : ℝ) < _)).mp (le_sqrt_of_sq_le _), rwa [le_sub, show (0:ℝ) = (0:ℕ)/(1:ℕ), by rw [nat.cast_zero, zero_div]], end lemma sqrt_two_add_series_step_up (c d : ℕ) {a b n : ℕ} {z : ℝ} (hz : sqrt_two_add_series (c/d) n ≤ z) (hb : 0 < b) (hd : 0 < d) (h : (2 * b + a) * d ^ 2 ≤ c ^ 2 * b) : sqrt_two_add_series (a/b) (n+1) ≤ z := begin refine le_trans _ hz, rw sqrt_two_add_series_succ, apply sqrt_two_add_series_monotone_left, have hb' : 0 < (b:ℝ) := nat.cast_pos.2 hb, have hd' : 0 < (d:ℝ) := nat.cast_pos.2 hd, rw [sqrt_le_left (div_nonneg c.cast_nonneg d.cast_nonneg), div_pow, add_div_eq_mul_add_div _ _ (ne_of_gt hb'), div_le_div_iff hb' (pow_pos hd' _)], exact_mod_cast h end /-- Create a proof of `a < π` for a fixed rational number `a`, given a witness, which is a sequence of rational numbers `sqrt 2 < r 1 < r 2 < ... < r n < 2` satisfying the property that `sqrt (2 + r i) ≤ r(i+1)`, where `r 0 = 0` and `sqrt (2 - r n) ≥ a/2^(n+1)`. -/ meta def pi_lower_bound (l : list ℚ) : tactic unit := do let n := l.length, tactic.apply `(@pi_lower_bound_start %%(reflect n)), l.mmap' (λ r, do let a := r.num.to_nat, let b := r.denom, (() <$ tactic.apply `(@sqrt_two_add_series_step_up %%(reflect a) %%(reflect b))); [tactic.skip, `[norm_num1], `[norm_num1], `[norm_num1]]), `[simp only [sqrt_two_add_series, nat.cast_bit0, nat.cast_bit1, nat.cast_one, nat.cast_zero]], `[norm_num1] /-- From a lower bound on `sqrt_two_add_series 0 n = 2 cos (π / 2 ^ (n+1))` of the form `2 - ((a - 1 / 4 ^ n) / 2 ^ (n + 1)) ^ 2 ≤ sqrt_two_add_series 0 n`, one can deduce the upper bound `π < a` thanks to basic trigonometric formulas as expressed in `pi_lt_sqrt_two_add_series`. -/ theorem pi_upper_bound_start (n : ℕ) {a} (h : 2 - ((a - 1 / 4 ^ n) / 2 ^ (n + 1)) ^ 2 ≤ sqrt_two_add_series ((0:ℕ) / (1:ℕ)) n) (h₂ : 1 / 4 ^ n ≤ a) : π < a := begin refine lt_of_lt_of_le (pi_lt_sqrt_two_add_series n) _, rw [← le_sub_iff_add_le, ← le_div_iff', sqrt_le_left, sub_le], { rwa [nat.cast_zero, zero_div] at h }, { exact div_nonneg (sub_nonneg.2 h₂) (pow_nonneg (le_of_lt zero_lt_two) _) }, { exact pow_pos zero_lt_two _ } end lemma sqrt_two_add_series_step_down (a b : ℕ) {c d n : ℕ} {z : ℝ} (hz : z ≤ sqrt_two_add_series (a/b) n) (hb : 0 < b) (hd : 0 < d) (h : a ^ 2 * d ≤ (2 * d + c) * b ^ 2) : z ≤ sqrt_two_add_series (c/d) (n+1) := begin apply le_trans hz, rw sqrt_two_add_series_succ, apply sqrt_two_add_series_monotone_left, apply le_sqrt_of_sq_le, have hb' : 0 < (b:ℝ) := nat.cast_pos.2 hb, have hd' : 0 < (d:ℝ) := nat.cast_pos.2 hd, rw [div_pow, add_div_eq_mul_add_div _ _ (ne_of_gt hd'), div_le_div_iff (pow_pos hb' _) hd'], exact_mod_cast h end /-- Create a proof of `π < a` for a fixed rational number `a`, given a witness, which is a sequence of rational numbers `sqrt 2 < r 1 < r 2 < ... < r n < 2` satisfying the property that `sqrt (2 + r i) ≥ r(i+1)`, where `r 0 = 0` and `sqrt (2 - r n) ≥ (a - 1/4^n) / 2^(n+1)`. -/ meta def pi_upper_bound (l : list ℚ) : tactic unit := do let n := l.length, (() <$ tactic.apply `(@pi_upper_bound_start %%(reflect n))); [pure (), `[norm_num1]], l.mmap' (λ r, do let a := r.num.to_nat, let b := r.denom, (() <$ tactic.apply `(@sqrt_two_add_series_step_down %%(reflect a) %%(reflect b))); [pure (), `[norm_num1], `[norm_num1], `[norm_num1]]), `[simp only [sqrt_two_add_series, nat.cast_bit0, nat.cast_bit1, nat.cast_one, nat.cast_zero]], `[norm_num] lemma pi_gt_three : 3 < π := by pi_lower_bound [23/16] lemma pi_gt_314 : 3.14 < π := by pi_lower_bound [99/70, 874/473, 1940/989, 1447/727] lemma pi_lt_315 : π < 3.15 := by pi_upper_bound [140/99, 279/151, 51/26, 412/207] lemma pi_gt_31415 : 3.1415 < π := by pi_lower_bound [ 11482/8119, 5401/2923, 2348/1197, 11367/5711, 25705/12868, 23235/11621] lemma pi_lt_31416 : π < 3.1416 := by pi_upper_bound [ 4756/3363, 101211/54775, 505534/257719, 83289/41846, 411278/205887, 438142/219137, 451504/225769, 265603/132804, 849938/424971] lemma pi_gt_3141592 : 3.141592 < π := by pi_lower_bound [ 11482/8119, 7792/4217, 54055/27557, 949247/476920, 3310126/1657059, 2635492/1318143, 1580265/790192, 1221775/610899, 3612247/1806132, 849943/424972] lemma pi_lt_3141593 : π < 3.141593 := by pi_upper_bound [ 27720/19601, 56935/30813, 49359/25163, 258754/130003, 113599/56868, 1101994/551163, 8671537/4336095, 3877807/1938940, 52483813/26242030, 56946167/28473117, 23798415/11899211] end real
274451c1e3b23f298f957e3034804c249e7b9a65
9cb9db9d79fad57d80ca53543dc07efb7c4f3838
/src/combinatorial_lemma.lean
215114d46d525d73fb68a752b2807e272e1fc8bb
[]
no_license
mr-infty/lean-liquid
3ff89d1f66244b434654c59bdbd6b77cb7de0109
a8db559073d2101173775ccbd85729d3a4f1ed4d
refs/heads/master
1,678,465,145,334
1,614,565,310,000
1,614,565,310,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,509
lean
import algebra.group.basic import normed_group.NormedGroup import set_theory.ordinal import set_theory.cardinal_ordinal import order.lexicographic import Mbar.basic import polyhedral_lattice.basic import normed_group.pseudo_normed_group /-! In this file we state and prove lemmas 9.7 and 9.8 of [Analytic]. -/ open_locale nnreal big_operators section lem97 variables (Λ : Type*) [add_comm_group Λ] lemma le_or_le {α : Type*} [linear_order α] (a b : α) : a ≤ b ∨ b ≤ a := (le_or_lt a b).imp id le_of_lt lemma abs_add_eq_add_abs_iff (a b : ℤ) : abs (a + b) = abs a + abs b ↔ (0 ≤ a ∧ 0 ≤ b ∨ a ≤ 0 ∧ b ≤ 0) := begin sorry end /- jmc: I don't know exactly which version of the two lemmas below will be easier to prove, `lem97` or `lem97'`. The first one is closer to [Analytic], but the second one is easier to use. Mathematically they are indistinguishable. -/ /-- Lemma 9.7 of [Analytic]. -/ lemma lem97 (hΛ_tf : torsion_free Λ) [hΛ_fg : module.finite ℤ Λ] {ι : Type*} [fintype ι] (N : ℕ) (l : ι → Λ) : ∃ A : finset (Λ →+ ℤ), ∀ x : Λ →+ ℤ, ∃ (x' ∈ A) (y : Λ →+ ℤ), x = N • y + x' ∧ ∀ i, (0 ≤ x' (l i) ∧ 0 ≤ (x - x') (l i)) ∨ (x' (l i) ≤ 0 ∧ (x - x') (l i) ≤ 0) := begin sorry end /-- Lemma 9.7 of [Analytic]. -/ lemma lem97' (hΛ_tf : torsion_free Λ) [hΛ_fg : module.finite ℤ Λ] {ι : Type*} [fintype ι] (N : ℕ) (l : ι → Λ) : ∃ A : finset (Λ →+ ℤ), ∀ x : Λ →+ ℤ, ∃ (x' ∈ A) (y : Λ →+ ℤ), x = N • y + x' ∧ ∀ i, (x (l i)).nat_abs = N * (y (l i)).nat_abs + (x' (l i)).nat_abs := begin sorry end end lem97 open pseudo_normed_group variables (Λ : Type*) (r' : ℝ≥0) (S : Type*) variables [fintype S] [normed_group Λ] [polyhedral_lattice Λ] section variables {S} -- move this @[simps] def Mbar.coeff (s : S) (n : ℕ) : Mbar r' S →+ ℤ := { to_fun := λ x, x s n, map_zero' := rfl, map_add' := λ x y, rfl } -- move this @[simp] lemma pi.nat_apply {α β : Type*} [has_zero β] [has_one β] [has_add β] : ∀ (n : ℕ), (n : α → β) = λ _, n | 0 := rfl | (n+1) := show (n + 1 : α → β) = λ _, n + 1, by { rw pi.nat_apply, refl } . variables {Λ r'} @[simps] def Mbar.of_mask (x : Mbar r' S) (mask : S → ℕ → Prop) [∀ s n, decidable (mask s n)] : Mbar r' S := { to_fun := λ s n, if mask s n then x s n else 0, coeff_zero' := λ s, by { split_ifs, { exact x.coeff_zero s }, { refl } }, summable' := λ s, begin apply nnreal.summable_of_le _ (x.summable s), intro n, apply mul_le_mul' _ le_rfl, norm_cast, split_ifs, { refl }, { rw int.nat_abs_zero, exact zero_le' } end } -- ugly name @[simps] def Mbar.mk_aux {ι : Type} [fintype ι] {l : ι → Λ} (hl : generates_norm l) (x : Λ →+ Mbar r' S) (y : S → ℕ → Λ →+ ℤ) (h : ∀ s n i, (y s n (l i)).nat_abs ≤ (x (l i) s n).nat_abs) : Λ →+ Mbar r' S := add_monoid_hom.mk' (λ l', { to_fun := λ s n, y s n l', coeff_zero' := λ s, begin obtain ⟨d, hd, c, h1, h2⟩ := hl l', suffices : y s 0 (d • l') = 0, { rw [← nsmul_eq_smul, add_monoid_hom.map_nsmul, nsmul_eq_mul, mul_eq_zero, int.nat_cast_eq_coe_nat, int.coe_nat_eq_zero] at this, exact this.resolve_left hd.ne' }, rw [h1, add_monoid_hom.map_sum, finset.sum_eq_zero], rintro i -, suffices : y s 0 (l i) = 0, { rw [← nsmul_eq_smul, add_monoid_hom.map_nsmul, this, nsmul_zero] }, specialize h s 0 i, simpa only [int.nat_abs_eq_zero, Mbar.coeff_zero, le_zero_iff, int.nat_abs_zero] using h end, summable' := begin intro s, obtain ⟨d, hd, c, h1, h2⟩ := hl.generates_nnnorm l', suffices : summable (λ n, ↑(y s n (d • l')).nat_abs * r' ^ n), { refine nnreal.summable_of_le _ this, intro n, refine mul_le_mul' _ le_rfl, rw [← nsmul_eq_smul, add_monoid_hom.map_nsmul, nsmul_eq_mul, int.nat_abs_mul, int.nat_cast_eq_coe_nat, int.nat_abs_of_nat], norm_cast, exact nat.le_mul_of_pos_left hd }, rw h1, suffices : summable (λ n, ∑ i, c i • ↑(y s n (l i)).nat_abs * r' ^ n), { apply nnreal.summable_of_le _ this, intro n, rw ← finset.sum_mul, refine mul_le_mul' _ le_rfl, simp only [add_monoid_hom.map_sum, ← nsmul_eq_smul, nnreal.coe_nat_abs, add_monoid_hom.map_nsmul], refine le_trans (nnnorm_sum_le _ _) (le_of_eq (fintype.sum_congr _ _ _)), intro i, simp only [nsmul_eq_mul, int.nat_cast_eq_coe_nat, ← nnreal.coe_nat_abs, int.nat_abs_mul, int.nat_abs_of_nat, nat.cast_mul] }, apply summable_sum, rintro i -, apply nnreal.summable_of_le _ ((c i • x (l i)).summable s), intro n, apply mul_le_mul' _ le_rfl, simp only [← nsmul_eq_smul, nsmul_eq_mul, int.nat_cast_eq_coe_nat, ← nnreal.coe_nat_abs, int.nat_abs_mul, int.nat_abs_of_nat, ← nat.cast_mul, Mbar.coe_nsmul, pi.mul_apply, pi.nat_apply, @pi.nat_apply ℕ ℤ _ _ _ (c i)], norm_cast, exact nat.mul_le_mul le_rfl (h _ _ _) end }) $ λ l₁ l₂, by { ext s n, exact (y s n).map_add l₁ l₂ } section pseudo_normed_group variables (M : Type*) [pseudo_normed_group M] def pseudo_normed_group.archimedean : Prop := ∀ (m : M) (c : ℝ≥0) (n : ℕ), 0 < n → ((n • m) ∈ filtration M (n • c) ↔ m ∈ filtration M c) lemma Mbar.archimedean : pseudo_normed_group.archimedean (Mbar r' S) := begin intros x c N hN, simp only [Mbar.mem_filtration_iff], have hN' : 0 < (N : ℝ≥0) := by exact_mod_cast hN, conv_rhs { rw ← mul_le_mul_left hN' }, simp only [Mbar.nnnorm_def, ← nsmul_eq_smul, nsmul_eq_mul, finset.mul_sum, finset.sum_mul, Mbar.coe_nsmul, pi.mul_apply, pi.nat_apply, @pi.nat_apply ℕ ℤ _ _ _ N, int.nat_abs_mul, int.nat_abs_of_nat, int.nat_cast_eq_coe_nat, nat.cast_mul], convert iff.rfl, ext s, simp only [nnreal.coe_nat_cast, nnreal.coe_tsum, nnreal.coe_mul, ← tsum_mul_left, ← mul_assoc] end lemma pseudo_normed_group.archimedean.add_monoid_hom (h : pseudo_normed_group.archimedean M) : pseudo_normed_group.archimedean (Λ →+ M) := begin intros f c N hN, apply forall_congr, intro c, apply forall_congr, intro l, apply forall_congr, intro hl, simp only [← nsmul_eq_smul, nsmul_eq_mul, mul_assoc], simp only [nsmul_eq_smul, ← nsmul_eq_mul, add_monoid_hom.nat_smul_apply], exact h _ _ N hN end variables {M} -- move this lemma pseudo_normed_group.nat_smul_mem_filtration (n : ℕ) (m : M) (c : ℝ≥0) (h : m ∈ filtration M c) : (n • m) ∈ filtration M (n • c) := begin induction n with n ih, { simpa only [zero_smul] using zero_mem_filtration _ }, simp only [nat.succ_eq_add_one, add_smul, one_smul], exact add_mem_filtration ih h, end -- move this lemma pseudo_normed_group.smul_mem_filtration (n : ℤ) (m : M) (c : ℝ≥0) (h : m ∈ filtration M c) : (n • m) ∈ filtration M (n.nat_abs • c) := begin by_cases hn : 0 ≤ n, { lift n to ℕ using hn, simp only [int.nat_abs_of_nat, ← gsmul_eq_smul, gsmul_coe_nat, nsmul_eq_smul], exact pseudo_normed_group.nat_smul_mem_filtration n m c h }, { push_neg at hn, rw ← neg_pos at hn, lift -n to ℕ using hn.le with k hk, rw [← neg_neg n, int.nat_abs_neg, ← hk, int.nat_abs_of_nat, neg_smul], apply neg_mem_filtration, simp only [neg_smul, ← gsmul_eq_smul, gsmul_coe_nat, nsmul_eq_smul], exact pseudo_normed_group.nat_smul_mem_filtration k m c h } end lemma generates_norm.add_monoid_hom_mem_filtration_iff {ι : Type} [fintype ι] {l : ι → Λ} (hl : generates_norm l) (hM : pseudo_normed_group.archimedean M) (x : Λ →+ M) (c : ℝ≥0) : x ∈ filtration (Λ →+ M) c ↔ ∀ i, x (l i) ∈ filtration M (c * nnnorm (l i)) := begin refine ⟨λ H i, H (le_refl (nnnorm (l i))), _⟩, intros H c' l' hl', obtain ⟨d, hd, cᵢ, h1, h2⟩ := hl.generates_nnnorm l', rw [← hM _ _ d hd, ← nsmul_eq_smul, ← x.map_nsmul, nsmul_eq_smul, h1, x.map_sum], refine filtration_mono _ (sum_mem_filtration _ (λ i, c * cᵢ i * nnnorm (l i)) _ _), { calc ∑ i, c * cᵢ i * nnnorm (l i) = c * ∑ i, cᵢ i * nnnorm (l i) : by simp only [mul_assoc, ← finset.mul_sum] ... = c * (d * nnnorm l') : by rw h2 ... ≤ c * (d * c') : mul_le_mul' le_rfl (mul_le_mul' le_rfl hl') ... = d • (c * c') : by rw [← nsmul_eq_smul, nsmul_eq_mul, mul_left_comm] }, rintro i -, convert pseudo_normed_group.nat_smul_mem_filtration (cᵢ i) _ _ (H i), { rw [← nsmul_eq_smul, x.map_nsmul, nsmul_eq_smul] }, { rw [← nsmul_eq_smul, nsmul_eq_mul, mul_left_comm, mul_assoc] } end end pseudo_normed_group end @[simps] def Mbar.geom [fact (r' < 1)] : Mbar r' S := { to_fun := λ s n, if n = 0 then 0 else 1, coeff_zero' := λ s, if_pos rfl, summable' := λ s, begin have := (normed_ring.summable_geometric_of_norm_lt_1 (r' : ℝ) _), swap, { rwa nnreal.norm_eq }, simp only [← nnreal.coe_pow, nnreal.summable_coe] at this, apply nnreal.summable_of_le _ this, intro n, refine (mul_le_mul' _ le_rfl).trans (one_mul _).le, split_ifs; simp end } variables {Λ r' S} @[simps] def Mbar.mk_of_add_monoid_hom [fact (r' < 1)] (x : S → ℕ → Λ →+ ℤ) (a : Λ →+ ℤ) [∀ s n, decidable (x s n = a)] : Mbar r' S := Mbar.of_mask (Mbar.geom r' S) $ λ s n, x s n = a lemma Mbar.mk_aux_mem_filtration (ι : Type) (c : ℝ≥0) (N : ℕ) (hN : 0 < N) [fintype ι] {l : ι → Λ} (hl : generates_norm l) {x : Λ →+ Mbar r' S} (hx : x ∈ filtration (Λ →+ Mbar r' S) c) (x₀' : S → ℕ → Λ →+ ℤ) (x₁' : S → ℕ → Λ →+ ℤ) (x' : S → ℕ → Λ →+ ℤ) (hx' : ∀ l s n, x l s n = x' s n l) (H : ∀ s n i, (x' s n (l i)).nat_abs = N * (x₀' s n (l i)).nat_abs + (x₁' s n (l i)).nat_abs) (H' : ∀ s n i, (x₀' s n (l i)).nat_abs ≤ (x (l i) s n).nat_abs) : Mbar.mk_aux hl x x₀' H' ∈ filtration (Λ →+ Mbar r' S) (c / ↑N) := begin set x₀ := Mbar.mk_aux hl x x₀' H', refine (Mbar.archimedean.add_monoid_hom _ _ _ _ hN).mp _, have aux : N • (c / N) = c, { rw [← nsmul_eq_smul, nsmul_eq_mul, mul_comm, div_mul_cancel], exact_mod_cast hN.ne' }, rw aux, rw hl.add_monoid_hom_mem_filtration_iff Mbar.archimedean at hx ⊢, intro i, specialize hx i, rw Mbar.mem_filtration_iff at hx ⊢, refine le_trans (finset.sum_le_sum _) hx, rintro s -, refine tsum_le_tsum _ (((N • x₀) (l i)).summable s) ((x (l i)).summable s), intro n, refine mul_le_mul' _ le_rfl, norm_cast, simp only [add_monoid_hom.nat_smul_apply], simp only [← nsmul_eq_smul, Mbar.coe_nsmul, nsmul_eq_mul, pi.mul_apply, pi.nat_apply, @pi.nat_apply ℕ ℤ _ _ _ N, int.nat_cast_eq_coe_nat, int.nat_abs_mul, int.nat_abs_of_nat], convert le_trans (le_add_right le_rfl) (H s n i).ge, apply hx' end @[simps] lemma Mbar.mk_tensor (a : Λ →+ ℤ) (x : Mbar r' S) : Λ →+ Mbar r' S := add_monoid_hom.mk' (λ l, a l • x) $ λ l₁ l₂, by rw [a.map_add, add_smul] lemma Mbar.mk_tensor_mem_filtration {ι : Type} [fintype ι] {l : ι → Λ} (hl : generates_norm l) (a : Λ →+ ℤ) (x : Mbar r' S) (c : ℝ≥0) (hxc : x ∈ filtration (Mbar r' S) c) : Mbar.mk_tensor a x ∈ filtration (Λ →+ Mbar r' S) ((finset.univ.sup $ λ i, (a (l i)).nat_abs / nnnorm (l i)) * c) := begin rw hl.add_monoid_hom_mem_filtration_iff Mbar.archimedean, intro i, rw [Mbar.mk_tensor_apply, mul_right_comm], by_cases H : l i = 0, { simpa only [H, a.map_zero, zero_smul] using zero_mem_filtration _ }, rw ← nnnorm_eq_zero at H, refine filtration_mono _ (pseudo_normed_group.smul_mem_filtration _ _ _ hxc), rw [← nsmul_eq_smul, nsmul_eq_mul], refine mul_le_mul' _ le_rfl, rw ← inv_inv' (nnnorm (l i)), apply le_mul_inv_of_mul_le (inv_ne_zero H), rw ← div_eq_mul_inv, exact finset.le_sup (finset.mem_univ i), end -- better name? lemma lem_98_aux [fact (r' < 1)] (A : finset (Λ →+ ℤ)) (x₁' : S → ℕ → Λ →+ ℤ) [∀ s n a, decidable (x₁' s n = a)] (hx₁' : ∀ s n, x₁' s n ∈ A) (x₁ : Λ →+ Mbar r' S) (hx₁ : ∀ l s n, x₁ l s n = x₁' s n l) (l : Λ) : x₁ l = ∑ a in A, a l • Mbar.mk_of_add_monoid_hom x₁' a := begin ext s n, simp only [finset.sum_apply, Mbar.coe_sum, pi.smul_apply, Mbar.coe_smul, Mbar.coe_mk], rw [finset.sum_eq_single (x₁' s n)], { simp only [true_and, and_congr, if_congr, eq_self_iff_true, if_true, Mbar.mk_of_add_monoid_hom_to_fun], split_ifs with hn, { rw [smul_zero, hn], exact (x₁ l).coeff_zero s }, { simp only [← gsmul_eq_smul, mul_one, gsmul_int_int, hx₁] } }, { intros a haA ha, simp only [ha.symm, false_and, if_false, smul_zero, Mbar.mk_of_add_monoid_hom_to_fun] }, { intro hsn, exact (hsn (hx₁' s n)).elim } end def mask_fun (f : ℕ → ℝ≥0) (mask : ℕ → Prop) [∀ n, decidable (mask n)] : ℕ → ℝ≥0 := λ n, if mask n then f n else 0 lemma exists_partition (N : ℕ) (hN : 0 < N) (f : ℕ → ℝ≥0) (hf : ∀ n, f n ≤ 1) : ∃ (mask : fin N → ℕ → Prop) [∀ i n, decidable (mask i n)], by exactI (∀ n, ∃! i, mask i n) ∧ (∀ i, ∑' n, mask_fun f (mask i) n ≤ (∑' n, f n) / N + 1) := sorry lemma lem98_int_fin (nS : ℕ) [fact (r' < 1)] (N : ℕ) (hN : 0 < N) (c : ℝ≥0) (x : Mbar r' (fin nS)) (hx : x ∈ filtration (Mbar r' (fin nS)) c) (H : ∀ s n, (x s n).nat_abs ≤ 1) : ∃ y : fin N → Mbar r' (fin nS), (x = ∑ i, y i) ∧ (∀ i, y i ∈ filtration (Mbar r' (fin nS)) (c/N + 1)) := begin sorry end lemma fintype_prod_nat_equiv_nat (S : Type*) [fintype S] [hS : nonempty S] : nonempty (S × ℕ ≃ ℕ) := begin classical, obtain ⟨e'⟩ := fintype.equiv_fin S, refine nonempty.intro _, calc S × ℕ ≃ fin (fintype.card S) × ℕ : equiv.prod_congr_left (λ _, e') ... ≃ ℕ : classical.choice $ cardinal.eq.1 _, rw [← cardinal.lift_id (cardinal.mk ℕ), cardinal.mk_prod, ← cardinal.omega, cardinal.mul_eq_right]; simp [le_of_lt (cardinal.nat_lt_omega _), le_refl], rw ← fintype.card_pos_iff at hS, exact_mod_cast hS.ne' end lemma lem98_int [fact (r' < 1)] (N : ℕ) (hN : 0 < N) (c : ℝ≥0) (x : Mbar r' S) (hx : x ∈ filtration (Mbar r' S) c) (H : ∀ s n, (x s n).nat_abs ≤ 1) : ∃ y : fin N → Mbar r' S, (x = ∑ i, y i) ∧ (∀ i, y i ∈ filtration (Mbar r' S) (c/N + 1)) := begin by_cases hS : nonempty S, swap, { refine ⟨λ i, 0, _, _⟩, { ext s n, exact (hS ⟨s⟩).elim }, { intro, exact zero_mem_filtration _ } }, resetI, obtain ⟨e⟩ := fintype_prod_nat_equiv_nat S, let f : ℕ → ℝ≥0 := λ n, ↑(x (e.symm n).1 (e.symm n).2).nat_abs * r' ^ (e.symm n).2, obtain ⟨mask, h0, h1, h2⟩ := exists_partition N hN f _, swap, { intro n, calc f n ≤ 1 * 1 : mul_le_mul' _ _ ... = 1 : mul_one 1, { exact_mod_cast (H _ _) }, { exact pow_le_one _ zero_le' (le_of_lt ‹_›) } }, resetI, have hf : ∑ i, mask_fun f (mask i) = f, { ext1 n, simp only [fintype.sum_apply, mask_fun], obtain ⟨i, hi1, hi2⟩ := h1 n, rw [finset.sum_eq_single i, if_pos hi1], { rintro j - hj, rw if_neg, exact mt (hi2 j) hj }, { intro hi, exact (hi (finset.mem_univ i)).elim } }, let y := λ i, Mbar.of_mask x (λ s n, mask i (e (s, n))), have hxy : x = ∑ i, y i, { ext s n, simp only [Mbar.coe_sum, if_congr, function.curry_apply, fintype.sum_apply, function.comp_app, Mbar.of_mask_to_fun, finset.sum_congr], obtain ⟨i, hi1, hi2⟩ := h1 (e (s, n)), rw [finset.sum_eq_single i, if_pos hi1], { rintro j - hj, rw if_neg, exact mt (hi2 j) hj }, { intro hi, exact (hi (finset.mem_univ i)).elim } }, have hxf : ∥x∥₊ = ∑' n, f n, { sorry }, refine ⟨y, hxy, _⟩, intro i, rw [Mbar.mem_filtration_iff] at hx ⊢, refine le_trans (le_of_eq _) ((h2 i).trans _), { rw [Mbar.nnnorm_def, ← tsum_sum], swap, { rintro s -, exact (y i).summable s }, -- now we need to massage the RHS using `e : S × ℕ ≃ ℕ` sorry }, { simp only [div_eq_mul_inv], refine add_le_add (mul_le_mul' _ le_rfl) le_rfl, exact hxf.ge.trans hx } end lemma lem98_aux' [fact (r' < 1)] (N : ℕ) (A : finset (Λ →+ ℤ)) (x x₀ x₁ : Λ →+ Mbar r' S) (x' x₀' x₁' : S → ℕ → Λ →+ ℤ) [∀ s n a, decidable (x₁' s n = a)] (H : ∀ s n, x' s n = N • x₀' s n + x₁' s n) (hx : ∀ l s n, x l s n = x' s n l) (hx₀ : ∀ l s n, x₀ l s n = x₀' s n l) (hx₁ : ∀ l s n, x₁ l s n = x₁' s n l) (Hx₁ : ∀ (l : Λ), x₁ l = ∑ (a : Λ →+ ℤ) in A, a l • Mbar.mk_of_add_monoid_hom x₁' a) (y' : (Λ →+ ℤ) → fin N → Mbar r' S) (hy' : ∀ (a : Λ →+ ℤ), Mbar.mk_of_add_monoid_hom x₁' a = finset.univ.sum (y' a)) (y : fin N → Λ →+ Mbar r' S) (hy : ∀ i, y i = x₀ + ∑ a in A, Mbar.mk_tensor a (y' a i)) : x = ∑ (i : fin N), y i := begin intros, ext l s n, simp only [hx, H, hy, ← hx₁, Hx₁, hy', Mbar.coe_add, finset.sum_apply, add_monoid_hom.coe_add, Mbar.coe_sum, pi.add_apply, Mbar.mk_tensor_apply, fintype.sum_apply, finset.sum_congr, add_monoid_hom.nat_smul_apply, pi.smul_apply, add_monoid_hom.sum_apply, add_monoid_hom.sum_apply, finset.smul_sum, Mbar.mk_tensor_apply], rw [finset.sum_add_distrib, finset.sum_const, finset.card_univ, fintype.card_fin, nsmul_eq_smul, finset.sum_comm, ← hx₀], end lemma lem98_crux [fact (r' < 1)] {ι : Type} [fintype ι] {l : ι → Λ} (hl : generates_norm l) (N : ℕ) (hN : 0 < N) (A : finset (Λ →+ ℤ)) (x x₀ x₁ : Λ →+ Mbar r' S) (x' x₀' x₁' : S → ℕ → Λ →+ ℤ) [∀ s n a, decidable (x₁' s n = a)] (xₐ : (Λ →+ ℤ) → Mbar r' S) -- (H : ∀ s n, x' s n = N • x₀' s n + x₁' s n) (hx : ∀ l s n, x l s n = x' s n l) (hx₀ : ∀ l s n, x₀ l s n = x₀' s n l) (hx₁ : ∀ l s n, x₁ l s n = x₁' s n l) (hxₐ : ∀ a, xₐ a = Mbar.mk_of_add_monoid_hom x₁' a) (Hx₁ : ∀ (l : Λ), x₁ l = ∑ (a : Λ →+ ℤ) in A, a l • xₐ a) (hx₁'A : ∀ s n, x₁' s n ∈ A) (H : ∀ s n i, (x' s n (l i)).nat_abs = N * (x₀' s n (l i)).nat_abs + (x₁' s n (l i)).nat_abs) (i : ι) : ∥x (l i)∥₊ = N • ∥x₀ (l i)∥₊ + ∑ a in A, nnnorm (a (l i)) * ∥xₐ a∥₊ := begin simp only [hx, H, ← hx₀, ← hx₁, Mbar.nnnorm_def, ← nsmul_eq_smul, nsmul_eq_mul, mul_assoc, finset.smul_sum, finset.mul_sum, nat.cast_add, nat.cast_mul, add_mul], rw [finset.sum_comm, ← finset.sum_add_distrib], apply fintype.sum_congr, intro s, apply nnreal.eq, simp only [nnreal.coe_tsum, nnreal.coe_sum, nnreal.coe_add, nnreal.coe_mul, nnreal.coe_pow, nnreal.coe_nat_cast, nnreal.coe_nat_abs, coe_nnnorm], rw [tsum_add _ ((x₁ (l i)).summable_coe_real s)], swap, { rw ← summable_mul_left_iff, { exact (x₀ (l i)).summable_coe_real s }, { exact_mod_cast hN.ne' } }, simp only [← tsum_mul_left], rw [← tsum_sum], swap, { intros a ha, exact summable.mul_left _ ((xₐ a).summable_coe_real s) }, simp only [← mul_assoc, ← finset.sum_mul, hxₐ, Hx₁], congr, ext n, congr, simp only [finset.sum_apply, Mbar.coe_sum, Mbar.mk_of_add_monoid_hom_to_fun, pi.smul_apply], rw [finset.sum_eq_single (x₁' s n), finset.sum_eq_single (x₁' s n)], { simp only [Mbar.coe_smul, Mbar.mk_of_add_monoid_hom_to_fun, if_true, pi.smul_apply, eq_self_iff_true, true_and, if_congr, and_congr], split_ifs, { simp only [mul_zero, norm_zero, smul_zero] }, { simp only [int.norm_def, ← abs_mul, ← int.cast_mul], simp only [← smul_eq_mul], congr, /- evil congr, should be simp -/ } }, all_goals { try { intro hsnA, exact (hsnA (hx₁'A s n)).elim } }, all_goals { intros a haA hasn }, { simp only [hasn.symm, Mbar.mk_of_add_monoid_hom_to_fun, norm_zero, mul_zero, if_congr, and_congr, eq_self_iff_true, if_false, false_and] }, { simp only [hasn.symm, Mbar.coe_smul, pi.smul_apply, Mbar.mk_of_add_monoid_hom_to_fun, smul_zero, if_congr, and_congr, eq_self_iff_true, if_false, false_and] }, end -- the `d` below doesn't and musn't depend on `S` -- in the future we may want to reformulate to make this explicit lemma lem98 [fact (r' < 1)] (N : ℕ) (hN : 0 < N) : ∃ d, ∀ c (x : Λ →+ Mbar r' S) (hx : x ∈ filtration (Λ →+ Mbar r' S) c), ∃ y : fin N → (Λ →+ Mbar r' S), (x = ∑ i, y i) ∧ (∀ i, y i ∈ filtration (Λ →+ Mbar r' S) (c/N + d)) := begin classical, obtain ⟨ι, _ftι, l, hl⟩ := polyhedral_lattice.polyhedral Λ, resetI, obtain ⟨A, hA⟩ := lem97' Λ polyhedral_lattice.tf N l, let d : ℝ≥0 := finset.univ.sup (λ i, ∑ a in A, nnnorm (a (l i)) / nnnorm (l i)), use d, intros c x hx, -- `x` is a homomorphism `Λ →+ Mbar r' S` -- we split it into pieces `Λ →+ ℤ` for all coefficients indexed by `s` and `n` let x' : S → ℕ → Λ →+ ℤ := λ s n, (Mbar.coeff r' s n).comp x, have := λ s n, hA (x' s n), clear hA, choose x₁' hx₁' x₀' hx₀' H using this, have hx₀_aux : ∀ s n i, (x₀' s n (l i)).nat_abs ≤ (x (l i) s n).nat_abs := (λ s n i, le_trans (le_add_right (nat.le_mul_of_pos_left hN)) (H s n i).ge), -- now we assemble `x₀' : S → ℕ → Λ →+ ℤ` into a homomorphism `Λ →+ Mbar r' S` let x₀ : Λ →+ Mbar r' S := Mbar.mk_aux hl x x₀' hx₀_aux, have hx₀ : x₀ ∈ filtration (Λ →+ Mbar r' S) (c / N) := Mbar.mk_aux_mem_filtration _ _ _ hN hl hx x₀' x₁' x' (λ _ _ _, rfl) H hx₀_aux, -- and similarly for `x₁'` let x₁ : Λ →+ Mbar r' S := Mbar.mk_aux hl x x₁' (λ s n i, le_trans (le_add_left le_rfl) (H s n i).ge), -- `x₁` can be written as a sum of tensors -- `x₁ = ∑ a in A, a ⊗ xₐ`, for some `xₐ : Mbar r' S` let xₐ : (Λ →+ ℤ) → Mbar r' S := λ a, Mbar.mk_of_add_monoid_hom x₁' a, have hx₁ : ∀ l, x₁ l = ∑ a in A, a l • xₐ a := lem_98_aux _ _ hx₁' _ (λ _ _ _, rfl), -- now it is time to start building `y` -- we first decompose the `xₐ a` into `N` pieces have hxₐ : ∀ a s n, (xₐ a s n).nat_abs ≤ 1, { intros a s n, dsimp [xₐ, Mbar.mk_of_add_monoid_hom_to_fun], split_ifs; simp }, have := λ a, lem98_int N hN _ (xₐ a) _ (hxₐ a), swap 3, { rw Mbar.mem_filtration_iff }, choose y' hy'1 hy'2 using this, -- the candidate `y` combines `x₀` together with the pieces `y'` of `xₐ a` let y : fin N → Λ →+ Mbar r' S := λ j, x₀ + ∑ a in A, Mbar.mk_tensor a (y' a j), have hxy : x = ∑ i, y i, { apply lem98_aux' N A x x₀ x₁ x' x₀' x₁' hx₀' _ _ _ hx₁ y' hy'1 y, all_goals { intros, refl } }, use [y, hxy], intro j, rw hl.add_monoid_hom_mem_filtration_iff Mbar.archimedean at hx ⊢, intro i, specialize hx i, simp only [Mbar.mem_filtration_iff] at hx hy'2 ⊢, have Hx : ∥x (l i)∥₊ = N • ∥x₀ (l i)∥₊ + ∑ a in A, nnnorm (a (l i)) * ∥xₐ a∥₊, { apply lem98_crux hl N hN A x x₀ x₁ x' x₀' x₁' xₐ, all_goals { intros, refl <|> apply_assumption } }, calc ∥y j (l i)∥₊ ≤ ∥x₀ (l i)∥₊ + ∑ a in A, nnnorm (a (l i)) * ∥xₐ a∥₊ / N + d * (nnnorm (l i)) : _ ... = (N • ∥x₀ (l i)∥₊ + ∑ a in A, nnnorm (a (l i)) * ∥xₐ a∥₊) / N + d * (nnnorm (l i)) : _ ... = ∥x (l i)∥₊ / N + d * (nnnorm (l i)) : by rw Hx ... ≤ _ : _, { simp only [add_monoid_hom.add_apply, add_assoc, add_monoid_hom.sum_apply, Mbar.mk_tensor_apply], refine (Mbar.nnnorm_add_le _ _).trans (add_le_add le_rfl _), refine (Mbar.nnnorm_sum_le _ _).trans _, calc ∑ a in A, ∥a (l i) • y' a j∥₊ = ∑ a in A, nnnorm (a (l i)) * ∥y' a j∥₊ : finset.sum_congr rfl _ ... ≤ ∑ a in A, nnnorm (a (l i)) * (∥xₐ a∥₊ / N + 1) : finset.sum_le_sum _ ... = ∑ a in A, (nnnorm (a (l i)) * ∥xₐ a∥₊ / N + nnnorm (a (l i))) : finset.sum_congr rfl _ ... = ∑ a in A, (nnnorm (a (l i)) * ∥xₐ a∥₊ / N) + ∑ a in A, nnnorm (a (l i)) : _ ... ≤ ∑ a in A, (nnnorm (a (l i)) * ∥xₐ a∥₊ / N) + d * nnnorm (l i) : add_le_add le_rfl _, { intros a ha, rw Mbar.nnnorm_smul }, { intros a ha, refine mul_le_mul' le_rfl (hy'2 a j) }, { intros a ha, rw [mul_add, mul_one, mul_div_assoc] }, { rw finset.sum_add_distrib }, { calc ∑ a in A, nnnorm (a (l i)) = (∑ a in A, nnnorm (a (l i)) / nnnorm (l i)) * nnnorm (l i) : _ ... ≤ finset.univ.sup (λ i, ∑ a in A, nnnorm (a (l i)) / nnnorm (l i)) * nnnorm (l i) : _, { by_cases hli : l i = 0, { simp only [hli, nnnorm_zero, add_monoid_hom.map_zero, zero_div, finset.sum_const_zero, zero_mul] }, rw ← nnnorm_eq_zero at hli, simp only [div_eq_mul_inv, ← finset.sum_mul], rw [inv_mul_cancel_right' hli] }, { exact mul_le_mul' (finset.le_sup (finset.mem_univ i)) le_rfl } } }, { simp only [div_eq_mul_inv, add_mul, finset.sum_mul, ← nsmul_eq_smul, nsmul_eq_mul], congr' 2, rw [mul_comm, inv_mul_cancel_left'], exact_mod_cast hN.ne' }, { simp only [add_mul, div_eq_mul_inv], refine add_le_add _ le_rfl, rw [mul_right_comm], refine mul_le_mul' hx le_rfl } end
71316a0a363c46e3fe753a587f5398142f03e4ac
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/src/Lean/Meta/TransparencyMode.lean
22f602b8d6c01cb3b3425f3090a7578ae58e89c6
[ "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
948
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ namespace Lean.Meta inductive TransparencyMode | all | default | reducible namespace TransparencyMode instance : Inhabited TransparencyMode := ⟨TransparencyMode.default⟩ def beq : TransparencyMode → TransparencyMode → Bool | all, all => true | default, default => true | reducible, reducible => true | _, _ => false instance : BEq TransparencyMode := ⟨beq⟩ def hash : TransparencyMode → USize | all => 7 | default => 11 | reducible => 13 instance : Hashable TransparencyMode := ⟨hash⟩ def lt : TransparencyMode → TransparencyMode → Bool | reducible, default => true | reducible, all => true | default, all => true | _, _ => false end TransparencyMode end Lean.Meta
1aeabbd951e22b3fd2928d283f45ac66a9b47e6e
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/Lake/DSL.lean
ec4003ad61bc4ae6e9e20a345348adbeea6dfc20
[ "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
364
lean
/- Copyright (c) 2021 Mac Malone. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mac Malone -/ import Lake.DSL.DeclUtil import Lake.DSL.Attributes import Lake.DSL.Extensions import Lake.DSL.Config import Lake.DSL.Package import Lake.DSL.Script import Lake.DSL.Require import Lake.DSL.Targets import Lake.DSL.Meta
5fc84e247e3ce872d8de041a6e50f7c91f2357a9
27a31d06bcfc7c5d379fd04a08a9f5ed3f5302d4
/stage0/src/Lean/Elab/PreDefinition/Structural/BRecOn.lean
39479ff6be49f53a80ec0bd238ecc3f4bc1187cb
[ "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
joehendrix/lean4
0d1486945f7ca9fe225070374338f4f7e74bab03
1221bdd3c7d5395baa451ce8fdd2c2f8a00cbc8f
refs/heads/master
1,640,573,727,861
1,639,662,710,000
1,639,665,515,000
198,893,504
0
0
Apache-2.0
1,564,084,645,000
1,564,084,644,000
null
UTF-8
Lean
false
false
10,272
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.Match.Match import Lean.Elab.PreDefinition.Structural.Basic namespace Lean.Elab.Structural open Meta private def throwToBelowFailed : MetaM α := throwError "toBelow failed" /- See toBelow -/ private partial def toBelowAux (C : Expr) : Expr → Expr → Expr → MetaM Expr | belowDict, arg, F => do let belowDict ← whnf belowDict trace[Elab.definition.structural] "belowDict: {belowDict}, arg: {arg}" match belowDict with | Expr.app (Expr.app (Expr.const `PProd _ _) d1 _) d2 _ => (do toBelowAux C d1 arg (← mkAppM `PProd.fst #[F])) <|> (do toBelowAux C d2 arg (← mkAppM `PProd.snd #[F])) | Expr.app (Expr.app (Expr.const `And _ _) d1 _) d2 _ => (do toBelowAux C d1 arg (← mkAppM `And.left #[F])) <|> (do toBelowAux C d2 arg (← mkAppM `And.right #[F])) | _ => forallTelescopeReducing belowDict fun xs belowDict => do let argArgs := arg.getAppArgs unless argArgs.size >= xs.size do throwToBelowFailed let n := argArgs.size let argTailArgs := argArgs.extract (n - xs.size) n let belowDict := belowDict.replaceFVars xs argTailArgs match belowDict with | Expr.app belowDictFun belowDictArg _ => unless belowDictFun.getAppFn == C do throwToBelowFailed unless ← isDefEq belowDictArg arg do throwToBelowFailed pure (mkAppN F argTailArgs) | _ => throwToBelowFailed /- See toBelow -/ private def withBelowDict (below : Expr) (numIndParams : Nat) (k : Expr → Expr → MetaM α) : MetaM α := do let belowType ← inferType below trace[Elab.definition.structural] "belowType: {belowType}" belowType.withApp fun f args => do let motivePos := numIndParams + 1 unless motivePos < args.size do throwError "unexpected 'below' type{indentExpr belowType}" let pre := mkAppN f (args.extract 0 numIndParams) let preType ← inferType pre forallBoundedTelescope preType (some 1) fun x _ => do let motiveType ← inferType x[0] withLocalDeclD (← mkFreshUserName `C) motiveType fun C => let belowDict := mkApp pre C let belowDict := mkAppN belowDict (args.extract (numIndParams + 1) args.size) k C belowDict /- `below` is a free variable with type of the form `I.below indParams motive indices major`, where `I` is the name of an inductive datatype. For example, when trying to show that the following function terminates using structural recursion ```lean def addAdjacent : List Nat → List Nat | [] => [] | [a] => [a] | a::b::as => (a+b) :: addAdjacent as ``` when we are visiting `addAdjacent as` at `replaceRecApps`, `below` has type `@List.below Nat (fun (x : List Nat) => List Nat) (a::b::as)` The motive `fun (x : List Nat) => List Nat` depends on the actual function we are trying to compute. So, we first replace it with a fresh variable `C` at `withBelowDict`. Recall that `brecOn` implements course-of-values recursion, and `below` can be viewed as a dictionary of the "previous values". We search this dictionary using the auxiliary function `toBelowAux`. The dictionary is built using the `PProd` (`And` for inductive predicates). We keep searching it until we find `C recArg`, where `C` is the auxiliary fresh variable created at `withBelowDict`. -/ private partial def toBelow (below : Expr) (numIndParams : Nat) (recArg : Expr) : MetaM Expr := do withBelowDict below numIndParams fun C belowDict => toBelowAux C belowDict recArg below private partial def replaceRecApps (recFnName : Name) (recArgInfo : RecArgInfo) (below : Expr) (e : Expr) : M Expr := let rec loop (below : Expr) (e : Expr) : M Expr := do match e with | Expr.lam n d b c => withLocalDecl n c.binderInfo (← loop below d) fun x => do mkLambdaFVars #[x] (← loop below (b.instantiate1 x)) | Expr.forallE n d b c => withLocalDecl n c.binderInfo (← loop below d) fun x => do mkForallFVars #[x] (← loop below (b.instantiate1 x)) | Expr.letE n type val body _ => withLetDecl n (← loop below type) (← loop below val) fun x => do mkLetFVars #[x] (← loop below (body.instantiate1 x)) (usedLetOnly := false) | Expr.mdata d e _ => return mkMData d (← loop below e) | Expr.proj n i e _ => return mkProj n i (← loop below e) | Expr.app _ _ _ => let processApp (e : Expr) : M Expr := e.withApp fun f args => do if f.isConstOf recFnName then let numFixed := recArgInfo.fixedParams.size let recArgPos := recArgInfo.fixedParams.size + recArgInfo.pos if recArgPos >= args.size then throwError "insufficient number of parameters at recursive application {indentExpr e}" let recArg := args[recArgPos] -- For reflexive type, we may have nested recursive applications in recArg let recArg ← loop below recArg let f ← try toBelow below recArgInfo.indParams.size recArg catch _ => throwError "failed to eliminate recursive application{indentExpr e}" -- Recall that the fixed parameters are not in the scope of the `brecOn`. So, we skip them. let argsNonFixed := args.extract numFixed args.size -- The function `f` does not explicitly take `recArg` and its indices as arguments. So, we skip them too. let mut fArgs := #[] for i in [:argsNonFixed.size] do if recArgInfo.pos != i && !recArgInfo.indicesPos.contains i then let arg := argsNonFixed[i] let arg ← replaceRecApps recFnName recArgInfo below arg fArgs := fArgs.push arg return mkAppN f fArgs else return mkAppN (← loop below f) (← args.mapM (loop below)) let matcherApp? ← matchMatcherApp? e match matcherApp? with | some matcherApp => if !recArgHasLooseBVarsAt recFnName recArgInfo.recArgPos e then processApp e else /- Here is an example we currently not handle ``` def g (xs : List Nat) : Nat := match xs with | [] => 0 | y::ys => match ys with | [] => 1 | _::_::zs => g zs + 1 | zs => g ys + 2 ``` We are matching on `ys`, but still using `ys` in the third alternative. If we push the `below` argument over the dependent match it will be able to eliminate recursive call using `zs`. To make it work, users have to write the third alternative as `| zs => g zs + 2` If this is too annoying in practice, we may replace `ys` with the matching term, but this may generate weird error messages, when it doesn't work. -/ trace[Elab.definition.structural] "below before matcherApp.addArg: {below} : {← inferType below}" let matcherApp ← mapError (matcherApp.addArg below) (fun msg => "failed to add `below` argument to 'matcher' application" ++ indentD msg) let altsNew ← (Array.zip matcherApp.alts matcherApp.altNumParams).mapM fun (alt, numParams) => lambdaTelescope alt fun xs altBody => do trace[Elab.definition.structural] "altNumParams: {numParams}, xs: {xs}" unless xs.size >= numParams do throwError "unexpected matcher application alternative{indentExpr alt}\nat application{indentExpr e}" let belowForAlt := xs[numParams - 1] mkLambdaFVars xs (← loop belowForAlt altBody) pure { matcherApp with alts := altsNew }.toExpr | none => processApp e | e => ensureNoRecFn recFnName e loop below e def mkBRecOn (recFnName : Name) (recArgInfo : RecArgInfo) (value : Expr) : M Expr := do trace[Elab.definition.structural] "mkBRecOn: {value}" let type := (← inferType value).headBeta let major := recArgInfo.ys[recArgInfo.pos] let otherArgs := recArgInfo.ys.filter fun y => y != major && !recArgInfo.indIndices.contains y trace[Elab.definition.structural] "fixedParams: {recArgInfo.fixedParams}, otherArgs: {otherArgs}" let motive ← mkForallFVars otherArgs type let mut brecOnUniv ← getLevel motive trace[Elab.definition.structural] "brecOn univ: {brecOnUniv}" let useBInductionOn := recArgInfo.reflexive && brecOnUniv == levelZero if recArgInfo.reflexive && brecOnUniv != levelZero then brecOnUniv ← decLevel brecOnUniv let motive ← mkLambdaFVars (recArgInfo.indIndices.push major) motive trace[Elab.definition.structural] "brecOn motive: {motive}" let brecOn := if useBInductionOn then Lean.mkConst (mkBInductionOnName recArgInfo.indName) recArgInfo.indLevels else Lean.mkConst (mkBRecOnName recArgInfo.indName) (brecOnUniv :: recArgInfo.indLevels) let brecOn := mkAppN brecOn recArgInfo.indParams let brecOn := mkApp brecOn motive let brecOn := mkAppN brecOn recArgInfo.indIndices let brecOn := mkApp brecOn major check brecOn let brecOnType ← inferType brecOn trace[Elab.definition.structural] "brecOn {brecOn}" trace[Elab.definition.structural] "brecOnType {brecOnType}" forallBoundedTelescope brecOnType (some 1) fun F _ => do let F := F[0] let FType ← inferType F trace[Elab.definition.structural] "FType: {FType}" let FType ← instantiateForall FType recArgInfo.indIndices let FType ← instantiateForall FType #[major] forallBoundedTelescope FType (some 1) fun below _ => do -- TODO: `below` user name is `f`, and it will make a global `f` to be pretty printed as `_root_.f` in error messages. -- We should add an option to `forallBoundedTelescope` to ensure fresh names are used. let below := below[0] let valueNew ← replaceRecApps recFnName recArgInfo below value let Farg ← mkLambdaFVars (recArgInfo.indIndices ++ #[major, below] ++ otherArgs) valueNew let brecOn := mkApp brecOn Farg return mkAppN brecOn otherArgs end Lean.Elab.Structural
e4157f5c1b84cbfdf7bc1e9dcacbbbf67a4e1a4d
9dc8cecdf3c4634764a18254e94d43da07142918
/src/tactic/push_neg.lean
0feea63b832a09756e730e9605b46937027636b5
[ "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
8,013
lean
/- Copyright (c) 2019 Patrick Massot All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Simon Hudon A tactic pushing negations into an expression -/ import logic.basic open tactic expr namespace push_neg section universe u variable {α : Sort u} variables (p q : Prop) variable (s : α → Prop) local attribute [instance, priority 10] classical.prop_decidable theorem not_not_eq : (¬ ¬ p) = p := propext not_not theorem not_and_eq : (¬ (p ∧ q)) = (p → ¬ q) := propext not_and theorem not_or_eq : (¬ (p ∨ q)) = (¬ p ∧ ¬ q) := propext not_or_distrib theorem not_forall_eq : (¬ ∀ x, s x) = (∃ x, ¬ s x) := propext not_forall theorem not_exists_eq : (¬ ∃ x, s x) = (∀ x, ¬ s x) := propext not_exists theorem not_implies_eq : (¬ (p → q)) = (p ∧ ¬ q) := propext not_imp theorem classical.implies_iff_not_or : (p → q) ↔ (¬ p ∨ q) := imp_iff_not_or theorem not_eq (a b : α) : (¬ a = b) ↔ (a ≠ b) := iff.rfl variable {β : Type u} variable [linear_order β] theorem not_le_eq (a b : β) : (¬ (a ≤ b)) = (b < a) := propext not_le theorem not_lt_eq (a b : β) : (¬ (a < b)) = (b ≤ a) := propext not_lt end meta def whnf_reducible (e : expr) : tactic expr := whnf e reducible private meta def transform_negation_step (e : expr) : tactic (option (expr × expr)) := do e ← whnf_reducible e, match e with | `(¬ %%ne) := (do ne ← whnf_reducible ne, match ne with | `(¬ %%a) := do pr ← mk_app ``not_not_eq [a], return (some (a, pr)) | `(%%a ∧ %%b) := do pr ← mk_app ``not_and_eq [a, b], return (some (`((%%a : Prop) → ¬ %%b), pr)) | `(%%a ∨ %%b) := do pr ← mk_app ``not_or_eq [a, b], return (some (`(¬ %%a ∧ ¬ %%b), pr)) | `(%%a ≤ %%b) := do e ← to_expr ``(%%b < %%a), pr ← mk_app ``not_le_eq [a, b], return (some (e, pr)) | `(%%a < %%b) := do e ← to_expr ``(%%b ≤ %%a), pr ← mk_app ``not_lt_eq [a, b], return (some (e, pr)) | `(Exists %%p) := do pr ← mk_app ``not_exists_eq [p], e ← match p with | (lam n bi typ bo) := do body ← mk_app ``not [bo], return (pi n bi typ body) | _ := tactic.fail "Unexpected failure negating ∃" end, return (some (e, pr)) | (pi n bi d p) := if p.has_var then do pr ← mk_app ``not_forall_eq [lam n bi d p], body ← mk_app ``not [p], e ← mk_app ``Exists [lam n bi d body], return (some (e, pr)) else do pr ← mk_app ``not_implies_eq [d, p], `(%%_ = %%e') ← infer_type pr, return (some (e', pr)) | _ := return none end) | _ := return none end private meta def transform_negation : expr → tactic (option (expr × expr)) | e := do (some (e', pr)) ← transform_negation_step e | return none, (some (e'', pr')) ← transform_negation e' | return (some (e', pr)), pr'' ← mk_eq_trans pr pr', return (some (e'', pr'')) meta def normalize_negations (t : expr) : tactic (expr × expr) := do (_, e, pr) ← simplify_top_down () (λ _, λ e, do oepr ← transform_negation e, match oepr with | (some (e', pr)) := return ((), e', pr) | none := do pr ← mk_eq_refl e, return ((), e, pr) end) t { eta := ff }, return (e, pr) meta def push_neg_at_hyp (h : name) : tactic unit := do H ← get_local h, t ← infer_type H, (e, pr) ← normalize_negations t, replace_hyp H e pr, skip meta def push_neg_at_goal : tactic unit := do H ← target, (e, pr) ← normalize_negations H, replace_target e pr end push_neg open interactive (parse loc.ns loc.wildcard) open interactive.types (location texpr) open lean.parser (tk ident many) interactive.loc local postfix (name := parser.optional) `?`:9001 := optional local postfix (name := parser.many) *:9001 := many open push_neg /-- Push negations in the goal of some assumption. For instance, a hypothesis `h : ¬ ∀ x, ∃ y, x ≤ y` will be transformed by `push_neg at h` into `h : ∃ x, ∀ y, y < x`. Variables names are conserved. This tactic pushes negations inside expressions. For instance, given an assumption ```lean h : ¬ ∀ ε > 0, ∃ δ > 0, ∀ x, |x - x₀| ≤ δ → |f x - y₀| ≤ ε) ``` writing `push_neg at h` will turn `h` into ```lean h : ∃ ε, ε > 0 ∧ ∀ δ, δ > 0 → (∃ x, |x - x₀| ≤ δ ∧ ε < |f x - y₀|), ``` (the pretty printer does *not* use the abreviations `∀ δ > 0` and `∃ ε > 0` but this issue has nothing to do with `push_neg`). Note that names are conserved by this tactic, contrary to what would happen with `simp` using the relevant lemmas. One can also use this tactic at the goal using `push_neg`, at every assumption and the goal using `push_neg at *` or at selected assumptions and the goal using say `push_neg at h h' ⊢` as usual. -/ meta def tactic.interactive.push_neg : parse location → tactic unit | (loc.ns loc_l) := loc_l.mmap' (λ l, match l with | some h := do push_neg_at_hyp h, try $ interactive.simp_core { eta := ff } failed tt [simp_arg_type.expr ``(push_neg.not_eq)] [] (interactive.loc.ns [some h]) | none := do push_neg_at_goal, try `[simp only [push_neg.not_eq] { eta := ff }] end) | loc.wildcard := do push_neg_at_goal, local_context >>= mmap' (λ h, push_neg_at_hyp (local_pp_name h)) , try `[simp only [push_neg.not_eq] at * { eta := ff }] add_tactic_doc { name := "push_neg", category := doc_category.tactic, decl_names := [`tactic.interactive.push_neg], tags := ["logic"] } lemma imp_of_not_imp_not (P Q : Prop) : (¬ Q → ¬ P) → (P → Q) := λ h hP, classical.by_contradiction (λ h', h h' hP) /-- Matches either an identifier "h" or a pair of identifiers "h with k" -/ meta def name_with_opt : lean.parser (name × option name) := prod.mk <$> ident <*> (some <$> (tk "with" *> ident) <|> return none) /-- Transforms the goal into its contrapositive. * `contrapose` turns a goal `P → Q` into `¬ Q → ¬ P` * `contrapose!` turns a goal `P → Q` into `¬ Q → ¬ P` and pushes negations inside `P` and `Q` using `push_neg` * `contrapose h` first reverts the local assumption `h`, and then uses `contrapose` and `intro h` * `contrapose! h` first reverts the local assumption `h`, and then uses `contrapose!` and `intro h` * `contrapose h with new_h` uses the name `new_h` for the introduced hypothesis -/ meta def tactic.interactive.contrapose (push : parse (tk "!" )?) : parse name_with_opt? → tactic unit | (some (h, h')) := get_local h >>= revert >> tactic.interactive.contrapose none >> intro (h'.get_or_else h) >> skip | none := do `(%%P → %%Q) ← target | fail "The goal is not an implication, and you didn't specify an assumption", cp ← mk_mapp ``imp_of_not_imp_not [P, Q] <|> fail "contrapose only applies to nondependent arrows between props", apply cp, when push.is_some $ try (tactic.interactive.push_neg (loc.ns [none])) add_tactic_doc { name := "contrapose", category := doc_category.tactic, decl_names := [`tactic.interactive.contrapose], tags := ["logic"] }
721195cd57a5859db6a9d0be20111a85c85ed7d8
cc060cf567f81c404a13ee79bf21f2e720fa6db0
/lean/20180207-pp-implicit-bug.lean
22567383947dee9522a19e667f65e661518d263c
[ "Apache-2.0" ]
permissive
semorrison/proof
cf0a8c6957153bdb206fd5d5a762a75958a82bca
5ee398aa239a379a431190edbb6022b1a0aa2c70
refs/heads/master
1,610,414,502,842
1,518,696,851,000
1,518,696,851,000
78,375,937
2
1
null
null
null
null
UTF-8
Lean
false
false
228
lean
set_option pp.implicit true structure C := ( d : Π { X : Type }, list X → list X ) def P(c : C):= c.d [0] #print P def P : C → list ℕ := λ (c : C), c.d ℕ [0] def P : C → list ℕ := λ (c : C), @C.d c ℕ [0]
30f772f2f3bdcbd3652f1e10ecccc9bd45a1fe5d
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/data/nat/multiplicity.lean
10f07b444c033128094ae21aaba7c434ca4dbcca
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
9,478
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.nat.choose import ring_theory.multiplicity import data.nat.modeq import algebra.gcd_domain /-! # Natural number multiplicity This file contains lemmas about the multiplicity function (the maximum prime power divding a number). # Main results There are natural number versions of some basic lemmas about multiplicity. There are also lemmas about the multiplicity of primes in factorials and in binomial coefficients. -/ open finset nat multiplicity open_locale big_operators namespace nat /-- The multiplicity of a divisor `m` of `n`, is the cardinality of the set of positive natural numbers `i` such that `p ^ i` divides `n`. The set is expressed by filtering `Ico 1 b` where `b` is any bound at least `n` -/ lemma multiplicity_eq_card_pow_dvd {m n b : ℕ} (hm1 : m ≠ 1) (hn0 : 0 < n) (hb : n ≤ b): multiplicity m n = ↑((finset.Ico 1 b).filter (λ i, m ^ i ∣ n)).card := calc multiplicity m n = ↑(Ico 1 $ ((multiplicity m n).get (finite_nat_iff.2 ⟨hm1, hn0⟩) + 1)).card : by simp ... = ↑((finset.Ico 1 b).filter (λ i, m ^ i ∣ n)).card : congr_arg coe $ congr_arg card $ finset.ext $ λ i, have hmn : ¬ m ^ n ∣ n, from if hm0 : m = 0 then λ _, by cases n; simp [*, lt_irrefl, nat.pow_succ] at * else mt (le_of_dvd hn0) (not_le_of_gt $ lt_pow_self (lt_of_le_of_ne (nat.pos_of_ne_zero hm0) hm1.symm) _), ⟨λ hi, begin simp only [Ico.mem, mem_filter, lt_succ_iff] at *, exact ⟨⟨hi.1, lt_of_le_of_lt hi.2 $ lt_of_lt_of_le (by rw [← enat.coe_lt_coe, enat.coe_get, multiplicity_lt_iff_neg_dvd, nat.pow_eq_pow]; exact hmn) hb⟩, by rw [← nat.pow_eq_pow, pow_dvd_iff_le_multiplicity]; rw [← @enat.coe_le_coe i, enat.coe_get] at hi; exact hi.2⟩ end, begin simp only [Ico.mem, mem_filter, lt_succ_iff, and_imp, true_and] { contextual := tt }, assume h1i hib hmin, rwa [← enat.coe_le_coe, enat.coe_get, ← pow_dvd_iff_le_multiplicity, nat.pow_eq_pow] end⟩ namespace prime lemma multiplicity_one {p : ℕ} (hp : p.prime) : multiplicity p 1 = 0 := by rw [multiplicity.one_right (mt nat.is_unit_iff.mp (ne_of_gt hp.one_lt))] lemma multiplicity_mul {p m n : ℕ} (hp : p.prime) : multiplicity p (m * n) = multiplicity p m + multiplicity p n := by rw [← int.coe_nat_multiplicity, ← int.coe_nat_multiplicity, ← int.coe_nat_multiplicity, int.coe_nat_mul, multiplicity.mul (nat.prime_iff_prime_int.1 hp)] lemma multiplicity_pow {p m n : ℕ} (hp : p.prime) : multiplicity p (m ^ n) = n •ℕ (multiplicity p m) := by induction n; simp [nat.pow_succ, hp.multiplicity_mul, *, hp.multiplicity_one, succ_nsmul, add_comm] lemma multiplicity_self {p : ℕ} (hp : p.prime) : multiplicity p p = 1 := have h₁ : ¬ is_unit (p : ℤ), from mt is_unit_int.1 (ne_of_gt hp.one_lt), have h₂ : (p : ℤ) ≠ 0, from int.coe_nat_ne_zero.2 hp.ne_zero, by rw [← int.coe_nat_multiplicity, multiplicity_self h₁ h₂] lemma multiplicity_pow_self {p n : ℕ} (hp : p.prime) : multiplicity p (p ^ n) = n := by induction n; simp [hp.multiplicity_one, nat.pow_succ, hp.multiplicity_mul, *, hp.multiplicity_self, succ_eq_add_one] /-- The multiplicity of a prime in `fact n` is the sum of the quotients `n / p ^ i`. This sum is expressed over the set `Ico 1 b` where `b` is any bound at least `n` -/ lemma multiplicity_fact {p : ℕ} (hp : p.prime) : ∀ {n b : ℕ}, n ≤ b → multiplicity p n.fact = (∑ i in Ico 1 b, n / p ^ i : ℕ) | 0 b hb := by simp [Ico, hp.multiplicity_one] | (n+1) b hb := calc multiplicity p (n+1).fact = multiplicity p n.fact + multiplicity p (n+1) : by rw [fact_succ, hp.multiplicity_mul, add_comm] ... = (∑ i in Ico 1 b, n / p ^ i : ℕ) + ((finset.Ico 1 b).filter (λ i, p ^ i ∣ n+1)).card : by rw [multiplicity_fact (le_of_succ_le hb), ← multiplicity_eq_card_pow_dvd (ne_of_gt hp.one_lt) (succ_pos _) hb] ... = (∑ i in Ico 1 b, (n / p ^ i + if p^i ∣ n+1 then 1 else 0) : ℕ) : by rw [sum_add_distrib, sum_boole]; simp ... = (∑ i in Ico 1 b, (n + 1) / p ^ i : ℕ) : congr_arg coe $ finset.sum_congr rfl (by intros; simp [nat.succ_div]; congr) /-- A prime power divides `fact n` iff it is at most the sum of the quotients `n / p ^ i`. This sum is expressed over the set `Ico 1 b` where `b` is any bound at least `n` -/ lemma pow_dvd_fact_iff {p : ℕ} {n r b : ℕ} (hp : p.prime) (hbn : n ≤ b) : p ^ r ∣ fact n ↔ r ≤ ∑ i in Ico 1 b, n / p ^ i := by rw [← enat.coe_le_coe, ← hp.multiplicity_fact hbn, ← pow_dvd_iff_le_multiplicity, nat.pow_eq_pow] lemma multiplicity_choose_aux {p n b k : ℕ} (hp : p.prime) (hkn : k ≤ n) : ∑ i in finset.Ico 1 b, n / p ^ i = ∑ i in finset.Ico 1 b, k / p ^ i + ∑ i in finset.Ico 1 b, (n - k) / p ^ i + ((finset.Ico 1 b).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i)).card := calc ∑ i in finset.Ico 1 b, n / p ^ i = ∑ i in finset.Ico 1 b, (k + (n - k)) / p ^ i : by simp only [nat.add_sub_cancel' hkn] ... = ∑ i in finset.Ico 1 b, (k / p ^ i + (n - k) / p ^ i + if p ^ i ≤ k % p ^ i + (n - k) % p ^ i then 1 else 0) : by simp only [nat.add_div (nat.pow_pos hp.pos _)] ... = _ : begin simp only [sum_add_distrib], simp [sum_boole], end -- we have to use `sum_add_distrib` before `add_ite` fires. /-- The multiplity of `p` in `choose n k` is the number of carries when `k` and `n - k` are added in base `p`. The set is expressed by filtering `Ico 1 b` where `b` is any bound at least `n`. -/ lemma multiplicity_choose {p n k b : ℕ} (hp : p.prime) (hkn : k ≤ n) (hnb : n ≤ b) : multiplicity p (choose n k) = ((Ico 1 b).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i)).card := have h₁ : multiplicity p (choose n k) + multiplicity p (k.fact * (n - k).fact) = ((finset.Ico 1 b).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i)).card + multiplicity p (k.fact * (n - k).fact), begin rw [← hp.multiplicity_mul, ← mul_assoc, choose_mul_fact_mul_fact hkn, hp.multiplicity_fact hnb, hp.multiplicity_mul, hp.multiplicity_fact (le_trans hkn hnb), hp.multiplicity_fact (le_trans (nat.sub_le_self _ _) hnb), multiplicity_choose_aux hp hkn], simp [add_comm], end, (enat.add_right_cancel_iff (enat.ne_top_iff_dom.2 $ by exact finite_nat_iff.2 ⟨ne_of_gt hp.one_lt, mul_pos (fact_pos k) (fact_pos (n - k))⟩)).1 h₁ /-- A lower bound on the multiplicity of `p` in `choose n k`. -/ lemma multiplicity_le_multiplicity_choose_add {p : ℕ} (hp : p.prime) (n k : ℕ) : multiplicity p n ≤ multiplicity p (choose n k) + multiplicity p k := if hkn : n < k then by simp [choose_eq_zero_of_lt hkn] else if hk0 : k = 0 then by simp [hk0] else if hn0 : n = 0 then by cases k; simp [hn0, *] at * else begin rw [multiplicity_choose hp (le_of_not_gt hkn) (le_refl _), multiplicity_eq_card_pow_dvd (ne_of_gt hp.one_lt) (nat.pos_of_ne_zero hk0) (le_of_not_gt hkn), multiplicity_eq_card_pow_dvd (ne_of_gt hp.one_lt) (nat.pos_of_ne_zero hn0) (le_refl _), ← enat.coe_add, enat.coe_le_coe], calc ((Ico 1 n).filter (λ i, p ^ i ∣ n)).card ≤ ((Ico 1 n).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i) ∪ (Ico 1 n).filter (λ i, p ^ i ∣ k) ).card : card_le_of_subset $ λ i, begin have := @le_mod_add_mod_of_dvd_add_of_not_dvd k (n - k) (p ^ i), simp [nat.add_sub_cancel' (le_of_not_gt hkn)] at * {contextual := tt}, tauto end ... ≤ ((Ico 1 n).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i)).card + ((Ico 1 n).filter (λ i, p ^ i ∣ k)).card : card_union_le _ _ end lemma multiplicity_choose_prime_pow {p n k : ℕ} (hp : p.prime) (hkn : k ≤ p ^ n) (hk0 : 0 < k) : multiplicity p (choose (p ^ n) k) + multiplicity p k = n := le_antisymm (have hdisj : disjoint ((Ico 1 (p ^ n)).filter (λ i, p ^ i ≤ k % p ^ i + (p ^ n - k) % p ^ i)) ((Ico 1 (p ^ n)).filter (λ i, p ^ i ∣ k)), by simp [disjoint_right, *, dvd_iff_mod_eq_zero, nat.mod_lt _ (nat.pow_pos hp.pos _)] {contextual := tt}, have filter_subset_Ico : filter (λ i, p ^ i ≤ k % p ^ i + (p ^ n - k) % p ^ i ∨ p ^ i ∣ k) (Ico 1 (p ^ n)) ⊆ Ico 1 n.succ, from begin simp only [finset.subset_iff, Ico.mem, mem_filter, and_imp, true_and] {contextual := tt}, assume i h1i hip h, refine lt_succ_of_le (le_of_not_gt (λ hin, _)), have hpik : ¬ p ^ i ∣ k, from mt (le_of_dvd hk0) (not_le_of_gt (lt_of_le_of_lt hkn (pow_right_strict_mono hp.two_le hin))), have hpn : k % p ^ i + (p ^ n - k) % p ^ i < p ^ i, from calc k % p ^ i + (p ^ n - k) % p ^ i ≤ k + (p ^ n - k) : add_le_add (mod_le _ _) (mod_le _ _) ... = p ^ n : nat.add_sub_cancel' hkn ... < p ^ i : pow_right_strict_mono hp.two_le hin, simpa [hpik, not_le_of_gt hpn] using h end, begin rw [multiplicity_choose hp hkn (le_refl _), multiplicity_eq_card_pow_dvd (ne_of_gt hp.one_lt) hk0 hkn, ← enat.coe_add, enat.coe_le_coe, ← card_disjoint_union hdisj, filter_union_right], exact le_trans (card_le_of_subset filter_subset_Ico) (by simp) end) (by rw [← hp.multiplicity_pow_self]; exact multiplicity_le_multiplicity_choose_add hp _ _) end prime end nat
923e9409362f5d05fdab1edb26ba9736130d00fe
05b503addd423dd68145d68b8cde5cd595d74365
/src/algebra/char_p.lean
368d713dde20fb6aaad21a0cbb71e9634946aa7e
[ "Apache-2.0" ]
permissive
aestriplex/mathlib
77513ff2b176d74a3bec114f33b519069788811d
e2fa8b2b1b732d7c25119229e3cdfba8370cb00f
refs/heads/master
1,621,969,960,692
1,586,279,279,000
1,586,279,279,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,747
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Kenny Lau, Joey van Langen, Casper Putz Characteristic of semirings. -/ import data.padics.padic_norm data.nat.choose data.fintype.basic import data.zmod.basic algebra.module universes u v /-- The generator of the kernel of the unique homomorphism ℕ → α for a semiring α -/ class char_p (α : Type u) [semiring α] (p : ℕ) : Prop := (cast_eq_zero_iff : ∀ x:ℕ, (x:α) = 0 ↔ p ∣ x) theorem char_p.cast_eq_zero (α : Type u) [semiring α] (p : ℕ) [char_p α p] : (p:α) = 0 := (char_p.cast_eq_zero_iff α p p).2 (dvd_refl p) theorem char_p.eq (α : Type u) [semiring α] {p q : ℕ} (c1 : char_p α p) (c2 : char_p α q) : p = q := nat.dvd_antisymm ((char_p.cast_eq_zero_iff α p q).1 (char_p.cast_eq_zero _ _)) ((char_p.cast_eq_zero_iff α q p).1 (char_p.cast_eq_zero _ _)) instance char_p.of_char_zero (α : Type u) [semiring α] [char_zero α] : char_p α 0 := ⟨λ x, by rw [zero_dvd_iff, ← nat.cast_zero, nat.cast_inj]⟩ theorem char_p.exists (α : Type u) [semiring α] : ∃ p, char_p α p := by letI := classical.dec_eq α; exact classical.by_cases (assume H : ∀ p:ℕ, (p:α) = 0 → p = 0, ⟨0, ⟨λ x, by rw [zero_dvd_iff]; exact ⟨H x, by rintro rfl; refl⟩⟩⟩) (λ H, ⟨nat.find (classical.not_forall.1 H), ⟨λ x, ⟨λ H1, nat.dvd_of_mod_eq_zero (by_contradiction $ λ H2, nat.find_min (classical.not_forall.1 H) (nat.mod_lt x $ nat.pos_of_ne_zero $ not_of_not_imp $ nat.find_spec (classical.not_forall.1 H)) (not_imp_of_and_not ⟨by rwa [← nat.mod_add_div x (nat.find (classical.not_forall.1 H)), nat.cast_add, nat.cast_mul, of_not_not (not_not_of_not_imp $ nat.find_spec (classical.not_forall.1 H)), zero_mul, add_zero] at H1, H2⟩)), λ H1, by rw [← nat.mul_div_cancel' H1, nat.cast_mul, of_not_not (not_not_of_not_imp $ nat.find_spec (classical.not_forall.1 H)), zero_mul]⟩⟩⟩) theorem char_p.exists_unique (α : Type u) [semiring α] : ∃! p, char_p α p := let ⟨c, H⟩ := char_p.exists α in ⟨c, H, λ y H2, char_p.eq α H2 H⟩ /-- Noncomuptable function that outputs the unique characteristic of a semiring. -/ noncomputable def ring_char (α : Type u) [semiring α] : ℕ := classical.some (char_p.exists_unique α) theorem ring_char.spec (α : Type u) [semiring α] : ∀ x:ℕ, (x:α) = 0 ↔ ring_char α ∣ x := by letI := (classical.some_spec (char_p.exists_unique α)).1; unfold ring_char; exact char_p.cast_eq_zero_iff α (ring_char α) theorem ring_char.eq (α : Type u) [semiring α] {p : ℕ} (C : char_p α p) : p = ring_char α := (classical.some_spec (char_p.exists_unique α)).2 p C theorem add_pow_char (α : Type u) [comm_ring α] {p : ℕ} (hp : nat.prime p) [char_p α p] (x y : α) : (x + y)^p = x^p + y^p := begin rw [add_pow, finset.sum_range_succ, nat.sub_self, pow_zero, nat.choose_self], rw [nat.cast_one, mul_one, mul_one, add_left_inj], transitivity, { refine finset.sum_eq_single 0 _ _, { intros b h1 h2, have := nat.prime.dvd_choose (nat.pos_of_ne_zero h2) (finset.mem_range.1 h1) hp, rw [← nat.div_mul_cancel this, nat.cast_mul, char_p.cast_eq_zero α p], simp only [mul_zero] }, { intro H, exfalso, apply H, exact finset.mem_range.2 hp.pos } }, rw [pow_zero, nat.sub_zero, one_mul, nat.choose_zero_right, nat.cast_one, mul_one] end /-- The frobenius map that sends x to x^p -/ def frobenius (α : Type u) [monoid α] (p : ℕ) (x : α) : α := x^p theorem frobenius_def (α : Type u) [monoid α] (p : ℕ) (x : α) : frobenius α p x = x ^ p := rfl theorem frobenius_mul (α : Type u) [comm_monoid α] (p : ℕ) (x y : α) : frobenius α p (x * y) = frobenius α p x * frobenius α p y := mul_pow x y p theorem frobenius_one (α : Type u) [monoid α] (p : ℕ) : frobenius α p 1 = 1 := one_pow _ theorem is_monoid_hom.map_frobenius {α : Type u} {β : Type v} [monoid α] [monoid β] (f : α → β) [is_monoid_hom f] (p : ℕ) (x : α) : f (frobenius α p x) = frobenius β p (f x) := by unfold frobenius; induction p; simp only [pow_zero, pow_succ, is_monoid_hom.map_one f, is_monoid_hom.map_mul f, *] instance {α : Type u} [comm_ring α] (p : ℕ) [hp : nat.prime p] [char_p α p] : is_ring_hom (frobenius α p) := { map_one := frobenius_one α p, map_mul := frobenius_mul α p, map_add := add_pow_char α hp } section variables (α : Type u) [comm_ring α] (p : ℕ) [hp : nat.prime p] theorem frobenius_zero : frobenius α p 0 = 0 := zero_pow hp.pos variables [char_p α p] (x y : α) include hp theorem frobenius_add : frobenius α p (x + y) = frobenius α p x + frobenius α p y := is_ring_hom.map_add _ theorem frobenius_neg : frobenius α p (-x) = -frobenius α p x := is_ring_hom.map_neg _ theorem frobenius_sub : frobenius α p (x - y) = frobenius α p x - frobenius α p y := is_ring_hom.map_sub _ end theorem frobenius_inj (α : Type u) [integral_domain α] (p : ℕ) [nat.prime p] [char_p α p] (x y : α) (H : frobenius α p x = frobenius α p y) : x = y := by rw ← sub_eq_zero at H ⊢; rw ← frobenius_sub at H; exact pow_eq_zero H theorem frobenius_nat_cast (α : Type u) [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] (x : ℕ) : frobenius α p x = x := by induction x; simp only [nat.cast_zero, nat.cast_succ, frobenius_zero, frobenius_one, frobenius_add, *] namespace char_p section variables (α : Type u) [ring α] lemma char_p_to_char_zero [char_p α 0] : char_zero α := add_group.char_zero_of_inj_zero $ λ n h0, eq_zero_of_zero_dvd ((cast_eq_zero_iff α 0 n).mp h0) lemma cast_eq_mod (p : ℕ) [char_p α p] (k : ℕ) : (k : α) = (k % p : ℕ) := calc (k : α) = ↑(k % p + p * (k / p)) : by rw [nat.mod_add_div] ... = ↑(k % p) : by simp[cast_eq_zero] theorem char_ne_zero_of_fintype (p : ℕ) [hc : char_p α p] [fintype α] : p ≠ 0 := assume h : p = 0, have char_zero α := @char_p_to_char_zero α _ (h ▸ hc), absurd (@nat.cast_injective α _ _ this) (not_injective_infinite_fintype coe) end section integral_domain open nat variables (α : Type u) [integral_domain α] theorem char_ne_one (p : ℕ) [hc : char_p α p] : p ≠ 1 := assume hp : p = 1, have ( 1 : α) = 0, by simpa using (cast_eq_zero_iff α p 1).mpr (hp ▸ dvd_refl p), absurd this one_ne_zero theorem char_is_prime_of_ge_two (p : ℕ) [hc : char_p α p] (hp : p ≥ 2) : nat.prime p := suffices ∀d ∣ p, d = 1 ∨ d = p, from ⟨hp, this⟩, assume (d : ℕ) (hdvd : ∃ e, p = d * e), let ⟨e, hmul⟩ := hdvd in have (p : α) = 0, from (cast_eq_zero_iff α p p).mpr (dvd_refl p), have (d : α) * e = 0, from (@cast_mul α _ d e) ▸ (hmul ▸ this), or.elim (no_zero_divisors.eq_zero_or_eq_zero_of_mul_eq_zero (d : α) e this) (assume hd : (d : α) = 0, have p ∣ d, from (cast_eq_zero_iff α p d).mp hd, show d = 1 ∨ d = p, from or.inr (dvd_antisymm ⟨e, hmul⟩ this)) (assume he : (e : α) = 0, have p ∣ e, from (cast_eq_zero_iff α p e).mp he, have e ∣ p, from dvd_of_mul_left_eq d (eq.symm hmul), have e = p, from dvd_antisymm ‹e ∣ p› ‹p ∣ e›, have h₀ : p > 0, from gt_of_ge_of_gt hp (nat.zero_lt_succ 1), have d * p = 1 * p, by rw ‹e = p› at hmul; rw [one_mul]; exact eq.symm hmul, show d = 1 ∨ d = p, from or.inl (eq_of_mul_eq_mul_right h₀ this)) theorem char_is_prime_or_zero (p : ℕ) [hc : char_p α p] : nat.prime p ∨ p = 0 := match p, hc with | 0, _ := or.inr rfl | 1, hc := absurd (eq.refl (1 : ℕ)) (@char_ne_one α _ (1 : ℕ) hc) | (m+2), hc := or.inl (@char_is_prime_of_ge_two α _ (m+2) hc (nat.le_add_left 2 m)) end theorem char_is_prime [fintype α] (p : ℕ) [char_p α p] : nat.prime p := or.resolve_right (char_is_prime_or_zero α p) (char_ne_zero_of_fintype α p) end integral_domain end char_p namespace zmod variables (α : Type u) [ring α] {n : ℕ+} /-- `zmod.cast : zmod n →+* α` as a ring homomorphism. -/ def cast_hom [char_p α n] : zmod n →+* α := { to_fun := cast, map_zero' := rfl, map_one' := by rw ←@nat.cast_one α _ _; exact eq.symm (char_p.cast_eq_mod α n 1), map_mul' := assume x y : zmod n, show ↑((x * y).val) = ↑(x.val) * ↑(y.val), by rw [zmod.mul_val, ←char_p.cast_eq_mod, nat.cast_mul], map_add' := assume x y : zmod n, show ↑((x + y).val) = ↑(x.val) + ↑(y.val), by rw [zmod.add_val, ←char_p.cast_eq_mod, nat.cast_add] } instance to_module [char_p α n] : module (zmod n) α := (cast_hom α).to_module instance to_module' {m : ℕ} {hm : m > 0} [hc : char_p α m] : module (zmod ⟨m, hm⟩) α := @zmod.to_module α _ ⟨m, hm⟩ hc end zmod
1fac5dd852aea76efd40e02a4c9a8316893c780c
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/data/mv_polynomial/variables.lean
c4cf865645f95a0661b56f288c91c73a1552f7ea
[ "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
23,200
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Johan Commelin, Mario Carneiro -/ import data.mv_polynomial.monad import data.set.disjointed /-! # Degrees and variables of polynomials This file establishes many results about the degree and variable sets of a multivariate polynomial. The *variable set* of a polynomial $P \in R[X]$ is a `finset` containing each $x \in X$ that appears in a monomial in $P$. The *degree set* of a polynomial $P \in R[X]$ is a `multiset` containing, for each $x$ in the variable set, $n$ copies of $x$, where $n$ is the maximum number of copies of $x$ appearing in a monomial of $P$. ## Main declarations * `mv_polynomial.degrees p` : the multiset of variables representing the union of the multisets corresponding to each non-zero monomial in `p`. For example if `7 ≠ 0` in `R` and `p = x²y+7y³` then `degrees p = {x, x, y, y, y}` * `mv_polynomial.vars p` : the finset of variables occurring in `p`. For example if `p = x⁴y+yz` then `vars p = {x, y, z}` * `mv_polynomial.degree_of n p : ℕ` -- the total degree of `p` with respect to the variable `n`. For example if `p = x⁴y+yz` then `degree_of y p = 1`. * `mv_polynomial.total_degree p : ℕ` -- the max of the sizes of the multisets `s` whose monomials `X^s` occur in `p`. For example if `p = x⁴y+yz` then `total_degree p = 5`. ## Notation As in other polynomial files, we typically use the notation: + `σ τ : Type*` (indexing the variables) + `R : Type*` `[comm_semiring R]` (the coefficients) + `s : σ →₀ ℕ`, a function from `σ` to `ℕ` which is zero away from a finite set. This will give rise to a monomial in `mv_polynomial σ R` which mathematicians might call `X^s` + `r : R` + `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians + `p : mv_polynomial σ R` -/ noncomputable theory open_locale classical big_operators open set function finsupp add_monoid_algebra open_locale big_operators universes u v w variables {R : Type u} {S : Type v} namespace mv_polynomial variables {σ τ : Type*} {r : R} {e : ℕ} {n m : σ} {s : σ →₀ ℕ} section comm_semiring variables [comm_semiring R] {p q : mv_polynomial σ R} section degrees /-! ### `degrees` -/ /-- The maximal degrees of each variable in a multi-variable polynomial, expressed as a multiset. (For example, `degrees (x^2 * y + y^3)` would be `{x, x, y, y, y}`.) -/ def degrees (p : mv_polynomial σ R) : multiset σ := p.support.sup (λs:σ →₀ ℕ, s.to_multiset) lemma degrees_monomial (s : σ →₀ ℕ) (a : R) : degrees (monomial s a) ≤ s.to_multiset := finset.sup_le $ assume t h, begin have := finsupp.support_single_subset h, rw [finset.mem_singleton] at this, rw this end lemma degrees_monomial_eq (s : σ →₀ ℕ) (a : R) (ha : a ≠ 0) : degrees (monomial s a) = s.to_multiset := le_antisymm (degrees_monomial s a) $ finset.le_sup $ by rw [monomial, finsupp.support_single_ne_zero ha, finset.mem_singleton] lemma degrees_C (a : R) : degrees (C a : mv_polynomial σ R) = 0 := multiset.le_zero.1 $ degrees_monomial _ _ lemma degrees_X' (n : σ) : degrees (X n : mv_polynomial σ R) ≤ {n} := le_trans (degrees_monomial _ _) $ le_of_eq $ to_multiset_single _ _ @[simp] lemma degrees_X [nontrivial R] (n : σ) : degrees (X n : mv_polynomial σ R) = {n} := (degrees_monomial_eq _ _ one_ne_zero).trans (to_multiset_single _ _) @[simp] lemma degrees_zero : degrees (0 : mv_polynomial σ R) = 0 := by { rw ← C_0, exact degrees_C 0 } @[simp] lemma degrees_one : degrees (1 : mv_polynomial σ R) = 0 := degrees_C 1 lemma degrees_add (p q : mv_polynomial σ R) : (p + q).degrees ≤ p.degrees ⊔ q.degrees := begin refine finset.sup_le (assume b hb, _), have := finsupp.support_add hb, rw finset.mem_union at this, cases this, { exact le_sup_left_of_le (finset.le_sup this) }, { exact le_sup_right_of_le (finset.le_sup this) }, end lemma degrees_sum {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) : (∑ i in s, f i).degrees ≤ s.sup (λi, (f i).degrees) := begin refine s.induction _ _, { simp only [finset.sum_empty, finset.sup_empty, degrees_zero], exact le_refl _ }, { assume i s his ih, rw [finset.sup_insert, finset.sum_insert his], exact le_trans (degrees_add _ _) (sup_le_sup_left ih _) } end lemma degrees_mul (p q : mv_polynomial σ R) : (p * q).degrees ≤ p.degrees + q.degrees := begin refine finset.sup_le (assume b hb, _), have := support_mul p q hb, simp only [finset.mem_bUnion, finset.mem_singleton] at this, rcases this with ⟨a₁, h₁, a₂, h₂, rfl⟩, rw [finsupp.to_multiset_add], exact add_le_add (finset.le_sup h₁) (finset.le_sup h₂) end lemma degrees_prod {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) : (∏ i in s, f i).degrees ≤ ∑ i in s, (f i).degrees := begin refine s.induction _ _, { simp only [finset.prod_empty, finset.sum_empty, degrees_one] }, { assume i s his ih, rw [finset.prod_insert his, finset.sum_insert his], exact le_trans (degrees_mul _ _) (add_le_add_left ih _) } end lemma degrees_pow (p : mv_polynomial σ R) : ∀(n : ℕ), (p^n).degrees ≤ n •ℕ p.degrees | 0 := begin rw [pow_zero, degrees_one], exact multiset.zero_le _ end | (n + 1) := le_trans (degrees_mul _ _) (add_le_add_left (degrees_pow n) _) lemma mem_degrees {p : mv_polynomial σ R} {i : σ} : i ∈ p.degrees ↔ ∃ d, p.coeff d ≠ 0 ∧ i ∈ d.support := by simp only [degrees, multiset.mem_sup, ← finsupp.mem_support_iff, coeff, finsupp.mem_to_multiset, exists_prop] lemma le_degrees_add {p q : mv_polynomial σ R} (h : p.degrees.disjoint q.degrees) : p.degrees ≤ (p + q).degrees := begin apply finset.sup_le, intros d hd, rw multiset.disjoint_iff_ne at h, rw multiset.le_iff_count, intros i, rw [degrees, multiset.count_sup], simp only [finsupp.count_to_multiset], by_cases h0 : d = 0, { simp only [h0, zero_le, finsupp.zero_apply], }, { refine @finset.le_sup _ _ _ (p + q).support _ d _, rw [finsupp.mem_support_iff, ← coeff, coeff_add], suffices : q.coeff d = 0, { rwa [this, add_zero, coeff, ← finsupp.mem_support_iff], }, rw [← finsupp.support_eq_empty, ← ne.def, ← finset.nonempty_iff_ne_empty] at h0, obtain ⟨j, hj⟩ := h0, contrapose! h, rw finsupp.mem_support_iff at hd, refine ⟨j, _, j, _, rfl⟩, all_goals { rw mem_degrees, refine ⟨d, _, hj⟩, assumption } } end lemma degrees_add_of_disjoint {p q : mv_polynomial σ R} (h : multiset.disjoint p.degrees q.degrees) : (p + q).degrees = p.degrees ∪ q.degrees := begin apply le_antisymm, { apply degrees_add }, { apply multiset.union_le, { apply le_degrees_add h }, { rw add_comm, apply le_degrees_add h.symm } } end lemma degrees_map [comm_semiring S] (p : mv_polynomial σ R) (f : R →+* S) : (map f p).degrees ⊆ p.degrees := begin dsimp only [degrees], apply multiset.subset_of_le, convert finset.sup_subset _ _, apply mv_polynomial.support_map_subset end lemma degrees_rename (f : σ → τ) (φ : mv_polynomial σ R) : (rename f φ).degrees ⊆ (φ.degrees.map f) := begin intros i, rw [mem_degrees, multiset.mem_map], rintro ⟨d, hd, hi⟩, obtain ⟨x, rfl, hx⟩ := coeff_rename_ne_zero _ _ _ hd, simp only [map_domain, mem_support_iff] at hi, rw [sum_apply, finsupp.sum] at hi, contrapose! hi, rw [finset.sum_eq_zero], intros j hj, simp only [exists_prop, mem_degrees] at hi, specialize hi j ⟨x, hx, hj⟩, rw [single_apply, if_neg hi], end lemma degrees_map_of_injective [comm_semiring S] (p : mv_polynomial σ R) {f : R →+* S} (hf : injective f) : (map f p).degrees = p.degrees := by simp only [degrees, mv_polynomial.support_map_of_injective _ hf] end degrees section vars /-! ### `vars` -/ /-- `vars p` is the set of variables appearing in the polynomial `p` -/ def vars (p : mv_polynomial σ R) : finset σ := p.degrees.to_finset @[simp] lemma vars_0 : (0 : mv_polynomial σ R).vars = ∅ := by rw [vars, degrees_zero, multiset.to_finset_zero] @[simp] lemma vars_monomial (h : r ≠ 0) : (monomial s r).vars = s.support := by rw [vars, degrees_monomial_eq _ _ h, finsupp.to_finset_to_multiset] @[simp] lemma vars_C : (C r : mv_polynomial σ R).vars = ∅ := by rw [vars, degrees_C, multiset.to_finset_zero] @[simp] lemma vars_X [nontrivial R] : (X n : mv_polynomial σ R).vars = {n} := by rw [X, vars_monomial (@one_ne_zero R _ _), finsupp.support_single_ne_zero (one_ne_zero : 1 ≠ 0)] lemma mem_vars (i : σ) : i ∈ p.vars ↔ ∃ (d : σ →₀ ℕ) (H : d ∈ p.support), i ∈ d.support := by simp only [vars, multiset.mem_to_finset, mem_degrees, coeff, finsupp.mem_support_iff, exists_prop] lemma mem_support_not_mem_vars_zero {f : mv_polynomial σ R} {x : σ →₀ ℕ} (H : x ∈ f.support) {v : σ} (h : v ∉ vars f) : x v = 0 := begin rw [vars, multiset.mem_to_finset] at h, rw ←not_mem_support_iff, contrapose! h, unfold degrees, rw (show f.support = insert x f.support, from eq.symm $ finset.insert_eq_of_mem H), rw finset.sup_insert, simp only [multiset.mem_union, multiset.sup_eq_union], left, rwa [←to_finset_to_multiset, multiset.mem_to_finset] at h, end lemma vars_add_subset (p q : mv_polynomial σ R) : (p + q).vars ⊆ p.vars ∪ q.vars := begin intros x hx, simp only [vars, finset.mem_union, multiset.mem_to_finset] at hx ⊢, simpa using multiset.mem_of_le (degrees_add _ _) hx, end lemma vars_add_of_disjoint (h : disjoint p.vars q.vars) : (p + q).vars = p.vars ∪ q.vars := begin apply finset.subset.antisymm (vars_add_subset p q), intros x hx, simp only [vars, multiset.disjoint_to_finset] at h hx ⊢, rw [degrees_add_of_disjoint h, multiset.to_finset_union], exact hx end section mul lemma vars_mul (φ ψ : mv_polynomial σ R) : (φ * ψ).vars ⊆ φ.vars ∪ ψ.vars := begin intro i, simp only [mem_vars, finset.mem_union], rintro ⟨d, hd, hi⟩, rw [finsupp.mem_support_iff, ← coeff, coeff_mul] at hd, contrapose! hd, cases hd, rw finset.sum_eq_zero, rintro ⟨d₁, d₂⟩ H, rw finsupp.mem_antidiagonal_support at H, subst H, obtain H|H : i ∈ d₁.support ∨ i ∈ d₂.support, { simpa only [finset.mem_union] using finsupp.support_add hi, }, { suffices : coeff d₁ φ = 0, by simp [this], rw [coeff, ← finsupp.not_mem_support_iff], intro, solve_by_elim, }, { suffices : coeff d₂ ψ = 0, by simp [this], rw [coeff, ← finsupp.not_mem_support_iff], intro, solve_by_elim, }, end @[simp] lemma vars_one : (1 : mv_polynomial σ R).vars = ∅ := vars_C lemma vars_pow (φ : mv_polynomial σ R) (n : ℕ) : (φ ^ n).vars ⊆ φ.vars := begin induction n with n ih, { simp }, { rw pow_succ, apply finset.subset.trans (vars_mul _ _), exact finset.union_subset (finset.subset.refl _) ih } end /-- The variables of the product of a family of polynomials are a subset of the union of the sets of variables of each polynomial. -/ lemma vars_prod {ι : Type*} {s : finset ι} (f : ι → mv_polynomial σ R) : (∏ i in s, f i).vars ⊆ s.bUnion (λ i, (f i).vars) := begin apply s.induction_on, { simp }, { intros a s hs hsub, simp only [hs, finset.bUnion_insert, finset.prod_insert, not_false_iff], apply finset.subset.trans (vars_mul _ _), exact finset.union_subset_union (finset.subset.refl _) hsub } end section integral_domain variables {A : Type*} [integral_domain A] lemma vars_C_mul (a : A) (ha : a ≠ 0) (φ : mv_polynomial σ A) : (C a * φ).vars = φ.vars := begin ext1 i, simp only [mem_vars, exists_prop, finsupp.mem_support_iff], apply exists_congr, intro d, apply and_congr _ iff.rfl, rw [← coeff, ← coeff, coeff_C_mul, mul_ne_zero_iff, eq_true_intro ha, true_and], end end integral_domain end mul section sum variables {ι : Type*} (t : finset ι) (φ : ι → mv_polynomial σ R) lemma vars_sum_subset : (∑ i in t, φ i).vars ⊆ finset.bUnion t (λ i, (φ i).vars) := begin apply t.induction_on, { simp }, { intros a s has hsum, rw [finset.bUnion_insert, finset.sum_insert has], refine finset.subset.trans (vars_add_subset _ _) (finset.union_subset_union (finset.subset.refl _) _), assumption } end lemma vars_sum_of_disjoint (h : pairwise $ disjoint on (λ i, (φ i).vars)) : (∑ i in t, φ i).vars = finset.bUnion t (λ i, (φ i).vars) := begin apply t.induction_on, { simp }, { intros a s has hsum, rw [finset.bUnion_insert, finset.sum_insert has, vars_add_of_disjoint, hsum], unfold pairwise on_fun at h, rw hsum, simp only [finset.disjoint_iff_ne] at h ⊢, intros v hv v2 hv2, rw finset.mem_bUnion at hv2, rcases hv2 with ⟨i, his, hi⟩, refine h a i _ _ hv _ hi, rintro rfl, contradiction } end end sum section map variables [comm_semiring S] (f : R →+* S) variable (p) lemma vars_map : (map f p).vars ⊆ p.vars := by simp [vars, degrees_map] variable {f} lemma vars_map_of_injective (hf : injective f) : (map f p).vars = p.vars := by simp [vars, degrees_map_of_injective _ hf] lemma vars_monomial_single (i : σ) {e : ℕ} {r : R} (he : e ≠ 0) (hr : r ≠ 0) : (monomial (finsupp.single i e) r).vars = {i} := by rw [vars_monomial hr, finsupp.support_single_ne_zero he] lemma vars_eq_support_bUnion_support : p.vars = p.support.bUnion finsupp.support := by { ext i, rw [mem_vars, finset.mem_bUnion] } end map end vars section degree_of /-! ### `degree_of` -/ /-- `degree_of n p` gives the highest power of X_n that appears in `p` -/ def degree_of (n : σ) (p : mv_polynomial σ R) : ℕ := p.degrees.count n end degree_of section total_degree /-! ### `total_degree` -/ /-- `total_degree p` gives the maximum |s| over the monomials X^s in `p` -/ def total_degree (p : mv_polynomial σ R) : ℕ := p.support.sup (λs, s.sum $ λn e, e) lemma total_degree_eq (p : mv_polynomial σ R) : p.total_degree = p.support.sup (λm, m.to_multiset.card) := begin rw [total_degree], congr, funext m, exact (finsupp.card_to_multiset _).symm end lemma total_degree_le_degrees_card (p : mv_polynomial σ R) : p.total_degree ≤ p.degrees.card := begin rw [total_degree_eq], exact finset.sup_le (assume s hs, multiset.card_le_of_le $ finset.le_sup hs) end @[simp] lemma total_degree_C (a : R) : (C a : mv_polynomial σ R).total_degree = 0 := nat.eq_zero_of_le_zero $ finset.sup_le $ assume n hn, have _ := finsupp.support_single_subset hn, begin rw [finset.mem_singleton] at this, subst this, exact le_refl _ end @[simp] lemma total_degree_zero : (0 : mv_polynomial σ R).total_degree = 0 := by rw [← C_0]; exact total_degree_C (0 : R) @[simp] lemma total_degree_one : (1 : mv_polynomial σ R).total_degree = 0 := total_degree_C (1 : R) @[simp] lemma total_degree_X {R} [comm_semiring R] [nontrivial R] (s : σ) : (X s : mv_polynomial σ R).total_degree = 1 := begin rw [total_degree, X, monomial, finsupp.support_single_ne_zero (one_ne_zero : (1 : R) ≠ 0)], simp only [finset.sup, sum_single_index, finset.fold_singleton, sup_bot_eq], end lemma total_degree_add (a b : mv_polynomial σ R) : (a + b).total_degree ≤ max a.total_degree b.total_degree := finset.sup_le $ assume n hn, have _ := finsupp.support_add hn, begin rw finset.mem_union at this, cases this, { exact le_max_left_of_le (finset.le_sup this) }, { exact le_max_right_of_le (finset.le_sup this) } end lemma total_degree_mul (a b : mv_polynomial σ R) : (a * b).total_degree ≤ a.total_degree + b.total_degree := finset.sup_le $ assume n hn, have _ := add_monoid_algebra.support_mul a b hn, begin simp only [finset.mem_bUnion, finset.mem_singleton] at this, rcases this with ⟨a₁, h₁, a₂, h₂, rfl⟩, rw [finsupp.sum_add_index], { exact add_le_add (finset.le_sup h₁) (finset.le_sup h₂) }, { assume a, refl }, { assume a b₁ b₂, refl } end lemma total_degree_pow (a : mv_polynomial σ R) (n : ℕ) : (a ^ n).total_degree ≤ n * a.total_degree := begin induction n with n ih, { simp only [nat.nat_zero_eq_zero, zero_mul, pow_zero, total_degree_one] }, rw pow_succ, calc total_degree (a * a ^ n) ≤ a.total_degree + (a^n).total_degree : total_degree_mul _ _ ... ≤ a.total_degree + n * a.total_degree : add_le_add_left ih _ ... = (n+1) * a.total_degree : by rw [add_mul, one_mul, add_comm] end lemma total_degree_list_prod : ∀(s : list (mv_polynomial σ R)), s.prod.total_degree ≤ (s.map mv_polynomial.total_degree).sum | [] := by rw [@list.prod_nil (mv_polynomial σ R) _, total_degree_one]; refl | (p :: ps) := begin rw [@list.prod_cons (mv_polynomial σ R) _, list.map, list.sum_cons], exact le_trans (total_degree_mul _ _) (add_le_add_left (total_degree_list_prod ps) _) end lemma total_degree_multiset_prod (s : multiset (mv_polynomial σ R)) : s.prod.total_degree ≤ (s.map mv_polynomial.total_degree).sum := begin refine quotient.induction_on s (assume l, _), rw [multiset.quot_mk_to_coe, multiset.coe_prod, multiset.coe_map, multiset.coe_sum], exact total_degree_list_prod l end lemma total_degree_finset_prod {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) : (s.prod f).total_degree ≤ ∑ i in s, (f i).total_degree := begin refine le_trans (total_degree_multiset_prod _) _, rw [multiset.map_map], refl end lemma exists_degree_lt [fintype σ] (f : mv_polynomial σ R) (n : ℕ) (h : f.total_degree < n * fintype.card σ) {d : σ →₀ ℕ} (hd : d ∈ f.support) : ∃ i, d i < n := begin contrapose! h, calc n * fintype.card σ = ∑ s:σ, n : by rw [finset.sum_const, nat.nsmul_eq_mul, mul_comm, finset.card_univ] ... ≤ ∑ s, d s : finset.sum_le_sum (λ s _, h s) ... ≤ d.sum (λ i e, e) : by { rw [finsupp.sum_fintype], intros, refl } ... ≤ f.total_degree : finset.le_sup hd, end lemma coeff_eq_zero_of_total_degree_lt {f : mv_polynomial σ R} {d : σ →₀ ℕ} (h : f.total_degree < ∑ i in d.support, d i) : coeff d f = 0 := begin classical, rw [total_degree, finset.sup_lt_iff] at h, { specialize h d, rw mem_support_iff at h, refine not_not.mp (mt h _), exact lt_irrefl _, }, { exact lt_of_le_of_lt (nat.zero_le _) h, } end lemma total_degree_rename_le (f : σ → τ) (p : mv_polynomial σ R) : (rename f p).total_degree ≤ p.total_degree := finset.sup_le $ assume b, begin assume h, rw rename_eq at h, have h' := finsupp.map_domain_support h, rw finset.mem_image at h', rcases h' with ⟨s, hs, rfl⟩, rw finsupp.sum_map_domain_index, exact le_trans (le_refl _) (finset.le_sup hs), exact assume _, rfl, exact assume _ _ _, rfl end end total_degree section eval_vars /-! ### `vars` and `eval` -/ variables [comm_semiring S] lemma eval₂_hom_eq_constant_coeff_of_vars (f : R →+* S) {g : σ → S} {p : mv_polynomial σ R} (hp : ∀ i ∈ p.vars, g i = 0) : eval₂_hom f g p = f (constant_coeff p) := begin conv_lhs { rw p.as_sum }, simp only [ring_hom.map_sum, eval₂_hom_monomial], by_cases h0 : constant_coeff p = 0, work_on_goal 0 { rw [h0, f.map_zero, finset.sum_eq_zero], intros d hd }, work_on_goal 1 { rw [finset.sum_eq_single (0 : σ →₀ ℕ)], { rw [finsupp.prod_zero_index, mul_one], refl }, intros d hd hd0, }, repeat { obtain ⟨i, hi⟩ : d.support.nonempty, { rw [constant_coeff_eq, coeff, ← finsupp.not_mem_support_iff] at h0, rw [finset.nonempty_iff_ne_empty, ne.def, finsupp.support_eq_empty], rintro rfl, contradiction }, rw [finsupp.prod, finset.prod_eq_zero hi, mul_zero], rw [hp, zero_pow (nat.pos_of_ne_zero $ finsupp.mem_support_iff.mp hi)], rw [mem_vars], exact ⟨d, hd, hi⟩ }, { rw [constant_coeff_eq, coeff, ← ne.def, ← finsupp.mem_support_iff] at h0, intro, contradiction } end lemma aeval_eq_constant_coeff_of_vars [algebra R S] {g : σ → S} {p : mv_polynomial σ R} (hp : ∀ i ∈ p.vars, g i = 0) : aeval g p = algebra_map _ _ (constant_coeff p) := eval₂_hom_eq_constant_coeff_of_vars _ hp lemma eval₂_hom_congr' {f₁ f₂ : R →+* S} {g₁ g₂ : σ → S} {p₁ p₂ : mv_polynomial σ R} : f₁ = f₂ → (∀ i, i ∈ p₁.vars → i ∈ p₂.vars → g₁ i = g₂ i) → p₁ = p₂ → eval₂_hom f₁ g₁ p₁ = eval₂_hom f₂ g₂ p₂ := begin rintro rfl h rfl, rename [p₁ p, f₁ f], rw p.as_sum, simp only [ring_hom.map_sum, eval₂_hom_monomial], apply finset.sum_congr rfl, intros d hd, congr' 1, simp only [finsupp.prod], apply finset.prod_congr rfl, intros i hi, have : i ∈ p.vars, { rw mem_vars, exact ⟨d, hd, hi⟩ }, rw h i this this, end lemma vars_bind₁ (f : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : (bind₁ f φ).vars ⊆ φ.vars.bUnion (λ i, (f i).vars) := begin calc (bind₁ f φ).vars = (φ.support.sum (λ (x : σ →₀ ℕ), (bind₁ f) (monomial x (coeff x φ)))).vars : by { rw [← alg_hom.map_sum, ← φ.as_sum], } ... ≤ φ.support.bUnion (λ (i : σ →₀ ℕ), ((bind₁ f) (monomial i (coeff i φ))).vars) : vars_sum_subset _ _ ... = φ.support.bUnion (λ (d : σ →₀ ℕ), (C (coeff d φ) * ∏ i in d.support, f i ^ d i).vars) : by simp only [bind₁_monomial] ... ≤ φ.support.bUnion (λ (d : σ →₀ ℕ), d.support.bUnion (λ i, (f i).vars)) : _ -- proof below ... ≤ φ.vars.bUnion (λ (i : σ), (f i).vars) : _, -- proof below { apply finset.bUnion_mono, intros d hd, calc (C (coeff d φ) * ∏ (i : σ) in d.support, f i ^ d i).vars ≤ (C (coeff d φ)).vars ∪ (∏ (i : σ) in d.support, f i ^ d i).vars : vars_mul _ _ ... ≤ (∏ (i : σ) in d.support, f i ^ d i).vars : by simp only [finset.empty_union, vars_C, finset.le_iff_subset, finset.subset.refl] ... ≤ d.support.bUnion (λ (i : σ), (f i ^ d i).vars) : vars_prod _ ... ≤ d.support.bUnion (λ (i : σ), (f i).vars) : _, apply finset.bUnion_mono, intros i hi, apply vars_pow, }, { intro j, simp_rw finset.mem_bUnion, rintro ⟨d, hd, ⟨i, hi, hj⟩⟩, exact ⟨i, (mem_vars _).mpr ⟨d, hd, hi⟩, hj⟩ } end lemma mem_vars_bind₁ (f : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) {j : τ} (h : j ∈ (bind₁ f φ).vars) : ∃ (i : σ), i ∈ φ.vars ∧ j ∈ (f i).vars := by simpa only [exists_prop, finset.mem_bUnion, mem_support_iff, ne.def] using vars_bind₁ f φ h lemma vars_rename (f : σ → τ) (φ : mv_polynomial σ R) : (rename f φ).vars ⊆ (φ.vars.image f) := begin intros i hi, simp only [vars, exists_prop, multiset.mem_to_finset, finset.mem_image] at hi ⊢, simpa only [multiset.mem_map] using degrees_rename _ _ hi end lemma mem_vars_rename (f : σ → τ) (φ : mv_polynomial σ R) {j : τ} (h : j ∈ (rename f φ).vars) : ∃ (i : σ), i ∈ φ.vars ∧ f i = j := by simpa only [exists_prop, finset.mem_image] using vars_rename f φ h end eval_vars end comm_semiring end mv_polynomial
d220589c24f571b83397c234ee8fd5e189f582a8
abd85493667895c57a7507870867b28124b3998f
/src/field_theory/finite.lean
4b7f44bb60b8d4810e1d9ae21c1452bbb41f77b9
[ "Apache-2.0" ]
permissive
pechersky/mathlib
d56eef16bddb0bfc8bc552b05b7270aff5944393
f1df14c2214ee114c9738e733efd5de174deb95d
refs/heads/master
1,666,714,392,571
1,591,747,567,000
1,591,747,567,000
270,557,274
0
0
Apache-2.0
1,591,597,975,000
1,591,597,974,000
null
UTF-8
Lean
false
false
10,066
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Joey van Langen, Casper Putz -/ import data.equiv.ring import data.zmod.basic import linear_algebra.basis import ring_theory.integral_domain /-! # Finite fields This file contains basic results about finite fields. Throughout most of this file, `K` denotes a finite field and `q` is notation for the cardinality of `K`. ## Main results 1. Every finite integral domain is a field (`field_of_integral_domain`). 2. The unit group of a finite field is a cyclic group of order `q - 1`. (`finite_field.is_cyclic` and `card_units`) 3. `sum_pow_units`: The sum of `x^i`, where `x` ranges over the units of `K`, is - `q-1` if `q-1 ∣ i` - `0` otherwise 4. `finite_field.card`: The cardinality `q` is a power of the characteristic of `K`. See `card'` for a variant. ## Notation Throughout most of this file, `K` denotes a finite field and `q` is notation for the cardinality of `K`. -/ variables {K : Type*} [field K] [fintype K] variables {R : Type*} [integral_domain R] local notation `q` := fintype.card K open_locale big_operators namespace finite_field open finset function section polynomial open polynomial /-- The cardinality of a field is at most `n` times the cardinality of the image of a degree `n` polynomial -/ lemma card_image_polynomial_eval [fintype R] [decidable_eq R] {p : polynomial R} (hp : 0 < p.degree) : fintype.card R ≤ nat_degree p * (univ.image (λ x, eval x p)).card := finset.card_le_mul_card_image _ _ (λ a _, calc _ = (p - C a).roots.card : congr_arg card (by simp [finset.ext, mem_roots_sub_C hp, -sub_eq_add_neg]) ... ≤ _ : card_roots_sub_C' hp) /-- If `f` and `g` are quadratic polynomials, then the `f.eval a + g.eval b = 0` has a solution. -/ lemma exists_root_sum_quadratic [fintype R] {f g : polynomial R} (hf2 : degree f = 2) (hg2 : degree g = 2) (hR : fintype.card R % 2 = 1) : ∃ a b, f.eval a + g.eval b = 0 := by letI := classical.dec_eq R; exact suffices ¬ disjoint (univ.image (λ x : R, eval x f)) (univ.image (λ x : R, eval x (-g))), begin simp only [disjoint_left, mem_image] at this, push_neg at this, rcases this with ⟨x, ⟨a, _, ha⟩, ⟨b, _, hb⟩⟩, exact ⟨a, b, by rw [ha, ← hb, eval_neg, neg_add_self]⟩ end, assume hd : disjoint _ _, lt_irrefl (2 * ((univ.image (λ x : R, eval x f)) ∪ (univ.image (λ x : R, eval x (-g)))).card) $ calc 2 * ((univ.image (λ x : R, eval x f)) ∪ (univ.image (λ x : R, eval x (-g)))).card ≤ 2 * fintype.card R : nat.mul_le_mul_left _ (finset.card_le_of_subset (subset_univ _)) ... = fintype.card R + fintype.card R : two_mul _ ... < nat_degree f * (univ.image (λ x : R, eval x f)).card + nat_degree (-g) * (univ.image (λ x : R, eval x (-g))).card : add_lt_add_of_lt_of_le (lt_of_le_of_ne (card_image_polynomial_eval (by rw hf2; exact dec_trivial)) (mt (congr_arg (%2)) (by simp [nat_degree_eq_of_degree_eq_some hf2, hR]))) (card_image_polynomial_eval (by rw [degree_neg, hg2]; exact dec_trivial)) ... = 2 * (univ.image (λ x : R, eval x f) ∪ univ.image (λ x : R, eval x (-g))).card : by rw [card_disjoint_union hd]; simp [nat_degree_eq_of_degree_eq_some hf2, nat_degree_eq_of_degree_eq_some hg2, bit0, mul_add] end polynomial lemma card_units : fintype.card (units K) = fintype.card K - 1 := begin classical, rw [eq_comm, nat.sub_eq_iff_eq_add (fintype.card_pos_iff.2 ⟨(0 : K)⟩)], haveI := set_fintype {a : K | a ≠ 0}, haveI := set_fintype (@set.univ K), rw [fintype.card_congr (equiv.units_equiv_ne_zero _), ← @set.card_insert _ _ {a : K | a ≠ 0} _ (not_not.2 (eq.refl (0 : K))) (set.fintype_insert _ _), fintype.card_congr (equiv.set.univ K).symm], congr; simp [set.ext_iff, classical.em] end lemma prod_univ_units_id_eq_neg_one : (∏ x : units K, x) = (-1 : units K) := begin classical, have : (∏ x in (@univ (units K) _).erase (-1), x) = 1, from prod_involution (λ x _, x⁻¹) (by simp) (λ a, by simp [units.inv_eq_self_iff] {contextual := tt}) (λ a, by simp [@inv_eq_iff_inv_eq _ _ a, eq_comm] {contextual := tt}) (by simp), rw [← insert_erase (mem_univ (-1 : units K)), prod_insert (not_mem_erase _ _), this, mul_one] end lemma pow_card_sub_one_eq_one (a : K) (ha : a ≠ 0) : a ^ (fintype.card K - 1) = 1 := calc a ^ (fintype.card K - 1) = (units.mk0 a ha ^ (fintype.card K - 1) : units K) : by rw [units.coe_pow, units.coe_mk0] ... = 1 : by { classical, rw [← card_units, pow_card_eq_one], refl } variable (K) theorem card (p : ℕ) [char_p K p] : ∃ (n : ℕ+), nat.prime p ∧ q = p^(n : ℕ) := begin haveI hp : fact p.prime := char_p.char_is_prime K p, letI : vector_space (zmod p) K := { .. (zmod.cast_hom (dvd_refl _) K).to_semimodule }, obtain ⟨n, h⟩ := vector_space.card_fintype (zmod p) K, rw zmod.card at h, refine ⟨⟨n, _⟩, hp, h⟩, apply or.resolve_left (nat.eq_zero_or_pos n), rintro rfl, rw nat.pow_zero at h, have : (0 : K) = 1, { apply fintype.card_le_one_iff.mp (le_of_eq h) }, exact absurd this zero_ne_one, end theorem card' : ∃ (p : ℕ) (n : ℕ+), nat.prime p ∧ q = p^(n : ℕ) := let ⟨p, hc⟩ := char_p.exists K in ⟨p, @finite_field.card K _ _ p hc⟩ @[simp] lemma cast_card_eq_zero : (q : K) = 0 := begin rcases char_p.exists K with ⟨p, _char_p⟩, resetI, rcases card K p with ⟨n, hp, hn⟩, simp only [char_p.cast_eq_zero_iff K p, hn], conv { congr, rw [← nat.pow_one p] }, exact nat.pow_dvd_pow _ n.2, end lemma forall_pow_eq_one_iff (i : ℕ) : (∀ x : units K, x ^ i = 1) ↔ q - 1 ∣ i := begin obtain ⟨x, hx⟩ := is_cyclic.exists_generator (units K), classical, rw [← card_units, ← order_of_eq_card_of_forall_mem_gpowers hx, order_of_dvd_iff_pow_eq_one], split, { intro h, apply h }, { intros h y, rw ← powers_eq_gpowers at hx, rcases hx y with ⟨j, rfl⟩, rw [← pow_mul, mul_comm, pow_mul, h, one_pow], } end /-- The sum of `x ^ i` as `x` ranges over the units of a finite field of cardinality `q` is equal to `0` unless `(q - 1) ∣ i`, in which case the sum is `q - 1`. -/ lemma sum_pow_units (i : ℕ) : ∑ x : units K, (x ^ i : K) = if (q - 1) ∣ i then -1 else 0 := begin let φ : units K →* K := { to_fun := λ x, x ^ i, map_one' := by rw [units.coe_one, one_pow], map_mul' := by { intros, rw [units.coe_mul, mul_pow] } }, haveI : decidable (φ = 1) := by { classical, apply_instance }, calc ∑ x : units K, φ x = if φ = 1 then fintype.card (units K) else 0 : sum_hom_units φ ... = if (q - 1) ∣ i then -1 else 0 : _, suffices : (q - 1) ∣ i ↔ φ = 1, { simp only [this], split_ifs with h h, swap, refl, rw [card_units, nat.cast_sub, cast_card_eq_zero, nat.cast_one, zero_sub], show 1 ≤ q, from fintype.card_pos_iff.mpr ⟨0⟩ }, rw [← forall_pow_eq_one_iff, monoid_hom.ext_iff], apply forall_congr, intro x, rw [units.ext_iff, units.coe_pow, units.coe_one, monoid_hom.one_apply], refl, end /-- The sum of `x ^ i` as `x` ranges over a finite field of cardinality `q` is equal to `0` if `i < q - 1`. -/ lemma sum_pow_lt_card_sub_one (i : ℕ) (h : i < q - 1) : ∑ x : K, x ^ i = 0 := begin by_cases hi : i = 0, { simp only [hi, nsmul_one, sum_const, pow_zero, card_univ, cast_card_eq_zero], }, classical, have hiq : ¬ (q - 1) ∣ i, { contrapose! h, exact nat.le_of_dvd (nat.pos_of_ne_zero hi) h }, let φ : units K ↪ K := ⟨coe, units.ext⟩, have : univ.map φ = univ \ {0}, { ext x, simp only [true_and, embedding.coe_fn_mk, mem_sdiff, units.exists_iff_ne_zero, mem_univ, mem_map, exists_prop_of_true, mem_singleton] }, calc ∑ x : K, x ^ i = ∑ x in univ \ {(0 : K)}, x ^ i : by rw [← sum_sdiff ({0} : finset K).subset_univ, sum_singleton, zero_pow (nat.pos_of_ne_zero hi), add_zero] ... = ∑ x : units K, x ^ i : by { rw [← this, univ.sum_map φ], refl } ... = 0 : by { rw [sum_pow_units K i, if_neg], exact hiq, } end end finite_field namespace zmod open finite_field polynomial lemma sum_two_squares (p : ℕ) [hp : fact p.prime] (x : zmod p) : ∃ a b : zmod p, a^2 + b^2 = x := begin cases hp.eq_two_or_odd with hp2 hp_odd, { unfreezeI, subst p, revert x, exact dec_trivial }, let f : polynomial (zmod p) := X^2, let g : polynomial (zmod p) := X^2 - C x, obtain ⟨a, b, hab⟩ : ∃ a b, f.eval a + g.eval b = 0 := @exists_root_sum_quadratic _ _ _ f g (degree_X_pow 2) (degree_X_pow_sub_C dec_trivial _) (by rw [zmod.card, hp_odd]), refine ⟨a, b, _⟩, rw ← sub_eq_zero, simpa only [eval_C, eval_X, eval_pow, eval_sub, ← add_sub_assoc] using hab, end end zmod namespace char_p lemma sum_two_squares (R : Type*) [integral_domain R] (p : ℕ) [fact (0 < p)] [char_p R p] (x : ℤ) : ∃ a b : ℕ, (a^2 + b^2 : R) = x := begin haveI := char_is_prime_of_pos R p, obtain ⟨a, b, hab⟩ := zmod.sum_two_squares p x, refine ⟨a.val, b.val, _⟩, simpa using congr_arg (zmod.cast_hom (dvd_refl _) R) hab end end char_p open_locale nat open zmod /-- The Fermat-Euler totient theorem. `nat.modeq.pow_totient` is an alternative statement of the same theorem. -/ @[simp] lemma zmod.pow_totient {n : ℕ} [fact (0 < n)] (x : units (zmod n)) : x ^ φ n = 1 := by rw [← card_units_eq_totient, pow_card_eq_one] /-- The Fermat-Euler totient theorem. `zmod.pow_totient` is an alternative statement of the same theorem. -/ lemma nat.modeq.pow_totient {x n : ℕ} (h : nat.coprime x n) : x ^ φ n ≡ 1 [MOD n] := begin cases n, {simp}, rw ← zmod.eq_iff_modeq_nat, let x' : units (zmod (n+1)) := zmod.unit_of_coprime _ h, have := zmod.pow_totient x', apply_fun (coe : units (zmod (n+1)) → zmod (n+1)) at this, simpa only [-zmod.pow_totient, nat.succ_eq_add_one, nat.cast_pow, units.coe_one, nat.cast_one, cast_unit_of_coprime, units.coe_pow], end
7902cdb0e92dc108abb9ddf84793b24e20bcb2b8
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/data/int/basic.lean
d3636d2015fd700679b71512dd701d155a2b233f
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
54,875
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad The integers, with addition, multiplication, and subtraction. -/ import data.nat.basic import algebra.order_functions open nat namespace int instance : inhabited ℤ := ⟨int.zero⟩ instance : nontrivial ℤ := ⟨⟨0, 1, int.zero_ne_one⟩⟩ instance : comm_ring int := { add := int.add, add_assoc := int.add_assoc, zero := int.zero, zero_add := int.zero_add, add_zero := int.add_zero, neg := int.neg, add_left_neg := int.add_left_neg, add_comm := int.add_comm, mul := int.mul, mul_assoc := int.mul_assoc, one := int.one, one_mul := int.one_mul, mul_one := int.mul_one, sub := int.sub, left_distrib := int.distrib_left, right_distrib := int.distrib_right, mul_comm := int.mul_comm, gsmul := (*), gsmul_zero' := int.zero_mul, gsmul_succ' := λ n x, by rw [succ_eq_one_add, of_nat_add, int.distrib_right, of_nat_one, int.one_mul], gsmul_neg' := λ n x, neg_mul_eq_neg_mul_symm (n.succ : ℤ) x } /-! ### Extra instances to short-circuit type class resolution -/ -- instance : has_sub int := by apply_instance -- This is in core instance : add_comm_monoid int := by apply_instance instance : add_monoid int := by apply_instance instance : monoid int := by apply_instance instance : comm_monoid int := by apply_instance instance : comm_semigroup int := by apply_instance instance : semigroup int := by apply_instance instance : add_comm_semigroup int := by apply_instance instance : add_semigroup int := by apply_instance instance : comm_semiring int := by apply_instance instance : semiring int := by apply_instance instance : ring int := by apply_instance instance : distrib int := by apply_instance instance : linear_ordered_comm_ring int := { add_le_add_left := @int.add_le_add_left, mul_pos := @int.mul_pos, zero_le_one := le_of_lt int.zero_lt_one, .. int.comm_ring, .. int.linear_order, .. int.nontrivial } instance : linear_ordered_add_comm_group int := by apply_instance @[simp] lemma add_neg_one (i : ℤ) : i + -1 = i - 1 := rfl theorem abs_eq_nat_abs : ∀ a : ℤ, abs a = nat_abs a | (n : ℕ) := abs_of_nonneg $ coe_zero_le _ | -[1+ n] := abs_of_nonpos $ le_of_lt $ neg_succ_lt_zero _ theorem nat_abs_abs (a : ℤ) : nat_abs (abs a) = nat_abs a := by rw [abs_eq_nat_abs]; refl theorem sign_mul_abs (a : ℤ) : sign a * abs a = a := by rw [abs_eq_nat_abs, sign_mul_nat_abs] @[simp] lemma default_eq_zero : default ℤ = 0 := rfl meta instance : has_to_format ℤ := ⟨λ z, to_string z⟩ meta instance : has_reflect ℤ := by tactic.mk_has_reflect_instance attribute [simp] int.coe_nat_add int.coe_nat_mul int.coe_nat_zero int.coe_nat_one int.coe_nat_succ attribute [simp] int.of_nat_eq_coe int.bodd @[simp] theorem add_def {a b : ℤ} : int.add a b = a + b := rfl @[simp] theorem mul_def {a b : ℤ} : int.mul a b = a * b := rfl @[simp] lemma neg_succ_not_nonneg (n : ℕ) : 0 ≤ -[1+ n] ↔ false := by { simp only [not_le, iff_false], exact int.neg_succ_lt_zero n, } @[simp] lemma neg_succ_not_pos (n : ℕ) : 0 < -[1+ n] ↔ false := by simp only [not_lt, iff_false] @[simp] lemma neg_succ_sub_one (n : ℕ) : -[1+ n] - 1 = -[1+ (n+1)] := rfl @[simp] theorem coe_nat_mul_neg_succ (m n : ℕ) : (m : ℤ) * -[1+ n] = -(m * succ n) := rfl @[simp] theorem neg_succ_mul_coe_nat (m n : ℕ) : -[1+ m] * n = -(succ m * n) := rfl @[simp] theorem neg_succ_mul_neg_succ (m n : ℕ) : -[1+ m] * -[1+ n] = succ m * succ n := rfl @[simp, norm_cast] theorem coe_nat_le {m n : ℕ} : (↑m : ℤ) ≤ ↑n ↔ m ≤ n := coe_nat_le_coe_nat_iff m n @[simp, norm_cast] theorem coe_nat_lt {m n : ℕ} : (↑m : ℤ) < ↑n ↔ m < n := coe_nat_lt_coe_nat_iff m n @[simp, norm_cast] theorem coe_nat_inj' {m n : ℕ} : (↑m : ℤ) = ↑n ↔ m = n := int.coe_nat_eq_coe_nat_iff m n @[simp] theorem coe_nat_pos {n : ℕ} : (0 : ℤ) < n ↔ 0 < n := by rw [← int.coe_nat_zero, coe_nat_lt] @[simp] theorem coe_nat_eq_zero {n : ℕ} : (n : ℤ) = 0 ↔ n = 0 := by rw [← int.coe_nat_zero, coe_nat_inj'] theorem coe_nat_ne_zero {n : ℕ} : (n : ℤ) ≠ 0 ↔ n ≠ 0 := not_congr coe_nat_eq_zero @[simp] lemma coe_nat_nonneg (n : ℕ) : 0 ≤ (n : ℤ) := coe_nat_le.2 (nat.zero_le _) lemma coe_nat_ne_zero_iff_pos {n : ℕ} : (n : ℤ) ≠ 0 ↔ 0 < n := ⟨λ h, nat.pos_of_ne_zero (coe_nat_ne_zero.1 h), λ h, (ne_of_lt (coe_nat_lt.2 h)).symm⟩ lemma coe_nat_succ_pos (n : ℕ) : 0 < (n.succ : ℤ) := int.coe_nat_pos.2 (succ_pos n) @[simp, norm_cast] theorem coe_nat_abs (n : ℕ) : abs (n : ℤ) = n := abs_of_nonneg (coe_nat_nonneg n) /-! ### succ and pred -/ /-- Immediate successor of an integer: `succ n = n + 1` -/ def succ (a : ℤ) := a + 1 /-- Immediate predecessor of an integer: `pred n = n - 1` -/ def pred (a : ℤ) := a - 1 theorem nat_succ_eq_int_succ (n : ℕ) : (nat.succ n : ℤ) = int.succ n := rfl theorem pred_succ (a : ℤ) : pred (succ a) = a := add_sub_cancel _ _ theorem succ_pred (a : ℤ) : succ (pred a) = a := sub_add_cancel _ _ theorem neg_succ (a : ℤ) : -succ a = pred (-a) := neg_add _ _ theorem succ_neg_succ (a : ℤ) : succ (-succ a) = -a := by rw [neg_succ, succ_pred] theorem neg_pred (a : ℤ) : -pred a = succ (-a) := by rw [eq_neg_of_eq_neg (neg_succ (-a)).symm, neg_neg] theorem pred_neg_pred (a : ℤ) : pred (-pred a) = -a := by rw [neg_pred, pred_succ] theorem pred_nat_succ (n : ℕ) : pred (nat.succ n) = n := pred_succ n theorem neg_nat_succ (n : ℕ) : -(nat.succ n : ℤ) = pred (-n) := neg_succ n theorem succ_neg_nat_succ (n : ℕ) : succ (-nat.succ n) = -n := succ_neg_succ n theorem lt_succ_self (a : ℤ) : a < succ a := lt_add_of_pos_right _ zero_lt_one theorem pred_self_lt (a : ℤ) : pred a < a := sub_lt_self _ zero_lt_one theorem add_one_le_iff {a b : ℤ} : a + 1 ≤ b ↔ a < b := iff.rfl theorem lt_add_one_iff {a b : ℤ} : a < b + 1 ↔ a ≤ b := @add_le_add_iff_right _ _ a b 1 @[simp] lemma succ_coe_nat_pos (n : ℕ) : 0 < (n : ℤ) + 1 := lt_add_one_iff.mpr (by simp) @[norm_cast] lemma coe_pred_of_pos (n : ℕ) (h : 0 < n) : ((n - 1 : ℕ) : ℤ) = (n : ℤ) - 1 := by { cases n, cases h, simp, } lemma le_add_one {a b : ℤ} (h : a ≤ b) : a ≤ b + 1 := le_of_lt (int.lt_add_one_iff.mpr h) theorem sub_one_lt_iff {a b : ℤ} : a - 1 < b ↔ a ≤ b := sub_lt_iff_lt_add.trans lt_add_one_iff theorem le_sub_one_iff {a b : ℤ} : a ≤ b - 1 ↔ a < b := le_sub_iff_add_le @[simp] lemma eq_zero_iff_abs_lt_one {a : ℤ} : abs a < 1 ↔ a = 0 := ⟨λ a0, let ⟨hn, hp⟩ := abs_lt.mp a0 in (le_of_lt_add_one (by exact hp)).antisymm hn, λ a0, (abs_eq_zero.mpr a0).le.trans_lt zero_lt_one⟩ @[elab_as_eliminator] protected lemma induction_on {p : ℤ → Prop} (i : ℤ) (hz : p 0) (hp : ∀i : ℕ, p i → p (i + 1)) (hn : ∀i : ℕ, p (-i) → p (-i - 1)) : p i := begin induction i, { induction i, { exact hz }, { exact hp _ i_ih } }, { have : ∀n:ℕ, p (- n), { intro n, induction n, { simp [hz] }, { convert hn _ n_ih using 1, simp [sub_eq_neg_add] } }, exact this (i + 1) } end /-- Inductively define a function on `ℤ` by defining it at `b`, for the `succ` of a number greater than `b`, and the `pred` of a number less than `b`. -/ protected def induction_on' {C : ℤ → Sort*} (z : ℤ) (b : ℤ) : C b → (∀ k, b ≤ k → C k → C (k + 1)) → (∀ k ≤ b, C k → C (k - 1)) → C z := λ H0 Hs Hp, begin rw ←sub_add_cancel z b, induction (z - b) with n n, { induction n with n ih, { rwa [of_nat_zero, zero_add] }, rw [of_nat_succ, add_assoc, add_comm 1 b, ←add_assoc], exact Hs _ (le_add_of_nonneg_left (of_nat_nonneg _)) ih }, { induction n with n ih, { rw [neg_succ_of_nat_eq, ←of_nat_eq_coe, of_nat_zero, zero_add, neg_add_eq_sub], exact Hp _ (le_refl _) H0 }, { rw [neg_succ_of_nat_coe', nat.succ_eq_add_one, ←neg_succ_of_nat_coe, sub_add_eq_add_sub], exact Hp _ (le_of_lt (add_lt_of_neg_of_le (neg_succ_lt_zero _) (le_refl _))) ih } } end /-! ### nat abs -/ attribute [simp] nat_abs nat_abs_of_nat nat_abs_zero nat_abs_one theorem nat_abs_add_le (a b : ℤ) : nat_abs (a + b) ≤ nat_abs a + nat_abs b := begin have : ∀ (a b : ℕ), nat_abs (sub_nat_nat a (nat.succ b)) ≤ nat.succ (a + b), { refine (λ a b : ℕ, sub_nat_nat_elim a b.succ (λ m n i, n = b.succ → nat_abs i ≤ (m + b).succ) _ _ rfl); intros i n e, { subst e, rw [add_comm _ i, add_assoc], exact nat.le_add_right i (b.succ + b).succ }, { apply succ_le_succ, rw [← succ.inj e, ← add_assoc, add_comm], apply nat.le_add_right } }, cases a; cases b with b b; simp [nat_abs, nat.succ_add]; try {refl}; [skip, rw add_comm a b]; apply this end theorem nat_abs_neg_of_nat (n : ℕ) : nat_abs (neg_of_nat n) = n := by cases n; refl theorem nat_abs_mul (a b : ℤ) : nat_abs (a * b) = (nat_abs a) * (nat_abs b) := by cases a; cases b; simp only [← int.mul_def, int.mul, nat_abs_neg_of_nat, eq_self_iff_true, int.nat_abs] lemma nat_abs_mul_nat_abs_eq {a b : ℤ} {c : ℕ} (h : a * b = (c : ℤ)) : a.nat_abs * b.nat_abs = c := by rw [← nat_abs_mul, h, nat_abs_of_nat] @[simp] lemma nat_abs_mul_self' (a : ℤ) : (nat_abs a * nat_abs a : ℤ) = a * a := by rw [← int.coe_nat_mul, nat_abs_mul_self] theorem neg_succ_of_nat_eq' (m : ℕ) : -[1+ m] = -m - 1 := by simp [neg_succ_of_nat_eq, sub_eq_neg_add] lemma nat_abs_ne_zero_of_ne_zero {z : ℤ} (hz : z ≠ 0) : z.nat_abs ≠ 0 := λ h, hz $ int.eq_zero_of_nat_abs_eq_zero h @[simp] lemma nat_abs_eq_zero {a : ℤ} : a.nat_abs = 0 ↔ a = 0 := ⟨int.eq_zero_of_nat_abs_eq_zero, λ h, h.symm ▸ rfl⟩ lemma nat_abs_ne_zero {a : ℤ} : a.nat_abs ≠ 0 ↔ a ≠ 0 := not_congr int.nat_abs_eq_zero lemma nat_abs_lt_nat_abs_of_nonneg_of_lt {a b : ℤ} (w₁ : 0 ≤ a) (w₂ : a < b) : a.nat_abs < b.nat_abs := begin lift b to ℕ using le_trans w₁ (le_of_lt w₂), lift a to ℕ using w₁, simpa using w₂, end lemma nat_abs_eq_nat_abs_iff {a b : ℤ} : a.nat_abs = b.nat_abs ↔ a = b ∨ a = -b := begin split; intro h, { cases int.nat_abs_eq a with h₁ h₁; cases int.nat_abs_eq b with h₂ h₂; rw [h₁, h₂]; simp [h], }, { cases h; rw h, rw int.nat_abs_neg, }, end lemma nat_abs_eq_iff {a : ℤ} {n : ℕ} : a.nat_abs = n ↔ a = n ∨ a = -n := by rw [←int.nat_abs_eq_nat_abs_iff, int.nat_abs_of_nat] lemma nat_abs_eq_iff_mul_self_eq {a b : ℤ} : a.nat_abs = b.nat_abs ↔ a * a = b * b := begin rw [← abs_eq_iff_mul_self_eq, abs_eq_nat_abs, abs_eq_nat_abs], exact int.coe_nat_inj'.symm end lemma nat_abs_lt_iff_mul_self_lt {a b : ℤ} : a.nat_abs < b.nat_abs ↔ a * a < b * b := begin rw [← abs_lt_iff_mul_self_lt, abs_eq_nat_abs, abs_eq_nat_abs], exact int.coe_nat_lt.symm end lemma nat_abs_le_iff_mul_self_le {a b : ℤ} : a.nat_abs ≤ b.nat_abs ↔ a * a ≤ b * b := begin rw [← abs_le_iff_mul_self_le, abs_eq_nat_abs, abs_eq_nat_abs], exact int.coe_nat_le.symm end lemma nat_abs_eq_iff_sq_eq {a b : ℤ} : a.nat_abs = b.nat_abs ↔ a ^ 2 = b ^ 2 := by { rw [sq, sq], exact nat_abs_eq_iff_mul_self_eq } lemma nat_abs_lt_iff_sq_lt {a b : ℤ} : a.nat_abs < b.nat_abs ↔ a ^ 2 < b ^ 2 := by { rw [sq, sq], exact nat_abs_lt_iff_mul_self_lt } lemma nat_abs_le_iff_sq_le {a b : ℤ} : a.nat_abs ≤ b.nat_abs ↔ a ^ 2 ≤ b ^ 2 := by { rw [sq, sq], exact nat_abs_le_iff_mul_self_le } /-! ### `/` -/ @[simp] theorem of_nat_div (m n : ℕ) : of_nat (m / n) = (of_nat m) / (of_nat n) := rfl @[simp, norm_cast] theorem coe_nat_div (m n : ℕ) : ((m / n : ℕ) : ℤ) = m / n := rfl theorem neg_succ_of_nat_div (m : ℕ) {b : ℤ} (H : 0 < b) : -[1+m] / b = -(m / b + 1) := match b, eq_succ_of_zero_lt H with ._, ⟨n, rfl⟩ := rfl end -- Will be generalized to Euclidean domains. local attribute [simp] protected theorem zero_div : ∀ (b : ℤ), 0 / b = 0 | 0 := show of_nat _ = _, by simp | (n+1:ℕ) := show of_nat _ = _, by simp | -[1+ n] := show -of_nat _ = _, by simp local attribute [simp] -- Will be generalized to Euclidean domains. protected theorem div_zero : ∀ (a : ℤ), a / 0 = 0 | 0 := show of_nat _ = _, by simp | (n+1:ℕ) := show of_nat _ = _, by simp | -[1+ n] := rfl @[simp] protected theorem div_neg : ∀ (a b : ℤ), a / -b = -(a / b) | (m : ℕ) 0 := show of_nat (m / 0) = -(m / 0 : ℕ), by rw nat.div_zero; refl | (m : ℕ) (n+1:ℕ) := rfl | 0 -[1+ n] := by simp | (m+1:ℕ) -[1+ n] := (neg_neg _).symm | -[1+ m] 0 := rfl | -[1+ m] (n+1:ℕ) := rfl | -[1+ m] -[1+ n] := rfl theorem div_of_neg_of_pos {a b : ℤ} (Ha : a < 0) (Hb : 0 < b) : a / b = -((-a - 1) / b + 1) := match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := by change (- -[1+ m] : ℤ) with (m+1 : ℤ); rw add_sub_cancel; refl end protected theorem div_nonneg {a b : ℤ} (Ha : 0 ≤ a) (Hb : 0 ≤ b) : 0 ≤ a / b := match a, b, eq_coe_of_zero_le Ha, eq_coe_of_zero_le Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := coe_zero_le _ end protected theorem div_nonpos {a b : ℤ} (Ha : 0 ≤ a) (Hb : b ≤ 0) : a / b ≤ 0 := nonpos_of_neg_nonneg $ by rw [← int.div_neg]; exact int.div_nonneg Ha (neg_nonneg_of_nonpos Hb) theorem div_neg' {a b : ℤ} (Ha : a < 0) (Hb : 0 < b) : a / b < 0 := match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := neg_succ_lt_zero _ end @[simp] protected theorem div_one : ∀ (a : ℤ), a / 1 = a | 0 := show of_nat _ = _, by simp | (n+1:ℕ) := congr_arg of_nat (nat.div_one _) | -[1+ n] := congr_arg neg_succ_of_nat (nat.div_one _) theorem div_eq_zero_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a / b = 0 := match a, b, eq_coe_of_zero_le H1, eq_succ_of_zero_lt (lt_of_le_of_lt H1 H2), H2 with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 := congr_arg of_nat $ nat.div_eq_of_lt $ lt_of_coe_nat_lt_coe_nat H2 end theorem div_eq_zero_of_lt_abs {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < abs b) : a / b = 0 := match b, abs b, abs_eq_nat_abs b, H2 with | (n : ℕ), ._, rfl, H2 := div_eq_zero_of_lt H1 H2 | -[1+ n], ._, rfl, H2 := neg_injective $ by rw [← int.div_neg]; exact div_eq_zero_of_lt H1 H2 end protected theorem add_mul_div_right (a b : ℤ) {c : ℤ} (H : c ≠ 0) : (a + b * c) / c = a / c + b := have ∀ {k n : ℕ} {a : ℤ}, (a + n * k.succ) / k.succ = a / k.succ + n, from λ k n a, match a with | (m : ℕ) := congr_arg of_nat $ nat.add_mul_div_right _ _ k.succ_pos | -[1+ m] := show ((n * k.succ:ℕ) - m.succ : ℤ) / k.succ = n - (m / k.succ + 1 : ℕ), begin cases lt_or_ge m (n*k.succ) with h h, { rw [← int.coe_nat_sub h, ← int.coe_nat_sub ((nat.div_lt_iff_lt_mul _ _ k.succ_pos).2 h)], apply congr_arg of_nat, rw [mul_comm, nat.mul_sub_div], rwa mul_comm }, { change (↑(n * nat.succ k) - (m + 1) : ℤ) / ↑(nat.succ k) = ↑n - ((m / nat.succ k : ℕ) + 1), rw [← sub_sub, ← sub_sub, ← neg_sub (m:ℤ), ← neg_sub _ (n:ℤ), ← int.coe_nat_sub h, ← int.coe_nat_sub ((nat.le_div_iff_mul_le _ _ k.succ_pos).2 h), ← neg_succ_of_nat_coe', ← neg_succ_of_nat_coe'], { apply congr_arg neg_succ_of_nat, rw [mul_comm, nat.sub_mul_div], rwa mul_comm } } end end, have ∀ {a b c : ℤ}, 0 < c → (a + b * c) / c = a / c + b, from λ a b c H, match c, eq_succ_of_zero_lt H, b with | ._, ⟨k, rfl⟩, (n : ℕ) := this | ._, ⟨k, rfl⟩, -[1+ n] := show (a - n.succ * k.succ) / k.succ = (a / k.succ) - n.succ, from eq_sub_of_add_eq $ by rw [← this, sub_add_cancel] end, match lt_trichotomy c 0 with | or.inl hlt := neg_inj.1 $ by rw [← int.div_neg, neg_add, ← int.div_neg, ← neg_mul_neg]; apply this (neg_pos_of_neg hlt) | or.inr (or.inl heq) := absurd heq H | or.inr (or.inr hgt) := this hgt end protected theorem add_mul_div_left (a : ℤ) {b : ℤ} (c : ℤ) (H : b ≠ 0) : (a + b * c) / b = a / b + c := by rw [mul_comm, int.add_mul_div_right _ _ H] protected theorem add_div_of_dvd_right {a b c : ℤ} (H : c ∣ b) : (a + b) / c = a / c + b / c := begin by_cases h1 : c = 0, { simp [h1] }, cases H with k hk, rw hk, change c ≠ 0 at h1, rw [mul_comm c k, int.add_mul_div_right _ _ h1, ←zero_add (k * c), int.add_mul_div_right _ _ h1, int.zero_div, zero_add] end protected theorem add_div_of_dvd_left {a b c : ℤ} (H : c ∣ a) : (a + b) / c = a / c + b / c := by rw [add_comm, int.add_div_of_dvd_right H, add_comm] @[simp] protected theorem mul_div_cancel (a : ℤ) {b : ℤ} (H : b ≠ 0) : a * b / b = a := by have := int.add_mul_div_right 0 a H; rwa [zero_add, int.zero_div, zero_add] at this @[simp] protected theorem mul_div_cancel_left {a : ℤ} (b : ℤ) (H : a ≠ 0) : a * b / a = b := by rw [mul_comm, int.mul_div_cancel _ H] @[simp] protected theorem div_self {a : ℤ} (H : a ≠ 0) : a / a = 1 := by have := int.mul_div_cancel 1 H; rwa one_mul at this /-! ### mod -/ theorem of_nat_mod (m n : nat) : (m % n : ℤ) = of_nat (m % n) := rfl @[simp, norm_cast] theorem coe_nat_mod (m n : ℕ) : (↑(m % n) : ℤ) = ↑m % ↑n := rfl theorem neg_succ_of_nat_mod (m : ℕ) {b : ℤ} (bpos : 0 < b) : -[1+m] % b = b - 1 - m % b := by rw [sub_sub, add_comm]; exact match b, eq_succ_of_zero_lt bpos with ._, ⟨n, rfl⟩ := rfl end @[simp] theorem mod_neg : ∀ (a b : ℤ), a % -b = a % b | (m : ℕ) n := @congr_arg ℕ ℤ _ _ (λ i, ↑(m % i)) (nat_abs_neg _) | -[1+ m] n := @congr_arg ℕ ℤ _ _ (λ i, sub_nat_nat i (nat.succ (m % i))) (nat_abs_neg _) @[simp] theorem mod_abs (a b : ℤ) : a % (abs b) = a % b := abs_by_cases (λ i, a % i = a % b) rfl (mod_neg _ _) local attribute [simp] -- Will be generalized to Euclidean domains. theorem zero_mod (b : ℤ) : 0 % b = 0 := rfl local attribute [simp] -- Will be generalized to Euclidean domains. theorem mod_zero : ∀ (a : ℤ), a % 0 = a | (m : ℕ) := congr_arg of_nat $ nat.mod_zero _ | -[1+ m] := congr_arg neg_succ_of_nat $ nat.mod_zero _ local attribute [simp] -- Will be generalized to Euclidean domains. theorem mod_one : ∀ (a : ℤ), a % 1 = 0 | (m : ℕ) := congr_arg of_nat $ nat.mod_one _ | -[1+ m] := show (1 - (m % 1).succ : ℤ) = 0, by rw nat.mod_one; refl theorem mod_eq_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a % b = a := match a, b, eq_coe_of_zero_le H1, eq_coe_of_zero_le (le_trans H1 (le_of_lt H2)), H2 with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 := congr_arg of_nat $ nat.mod_eq_of_lt (lt_of_coe_nat_lt_coe_nat H2) end theorem mod_nonneg : ∀ (a : ℤ) {b : ℤ}, b ≠ 0 → 0 ≤ a % b | (m : ℕ) n H := coe_zero_le _ | -[1+ m] n H := sub_nonneg_of_le $ coe_nat_le_coe_nat_of_le $ nat.mod_lt _ (nat_abs_pos_of_ne_zero H) theorem mod_lt_of_pos (a : ℤ) {b : ℤ} (H : 0 < b) : a % b < b := match a, b, eq_succ_of_zero_lt H with | (m : ℕ), ._, ⟨n, rfl⟩ := coe_nat_lt_coe_nat_of_lt (nat.mod_lt _ (nat.succ_pos _)) | -[1+ m], ._, ⟨n, rfl⟩ := sub_lt_self _ (coe_nat_lt_coe_nat_of_lt $ nat.succ_pos _) end theorem mod_lt (a : ℤ) {b : ℤ} (H : b ≠ 0) : a % b < abs b := by rw [← mod_abs]; exact mod_lt_of_pos _ (abs_pos.2 H) theorem mod_add_div_aux (m n : ℕ) : (n - (m % n + 1) - (n * (m / n) + n) : ℤ) = -[1+ m] := begin rw [← sub_sub, neg_succ_of_nat_coe, sub_sub (n:ℤ)], apply eq_neg_of_eq_neg, rw [neg_sub, sub_sub_self, add_right_comm], exact @congr_arg ℕ ℤ _ _ (λi, (i + 1 : ℤ)) (nat.mod_add_div _ _).symm end theorem mod_add_div : ∀ (a b : ℤ), a % b + b * (a / b) = a | (m : ℕ) 0 := congr_arg of_nat (nat.mod_add_div _ _) | (m : ℕ) (n+1:ℕ) := congr_arg of_nat (nat.mod_add_div _ _) | 0 -[1+ n] := by simp | (m+1:ℕ) -[1+ n] := show (_ + -(n+1) * -((m + 1) / (n + 1) : ℕ) : ℤ) = _, by rw [neg_mul_neg]; exact congr_arg of_nat (nat.mod_add_div _ _) | -[1+ m] 0 := by rw [mod_zero, int.div_zero]; refl | -[1+ m] (n+1:ℕ) := mod_add_div_aux m n.succ | -[1+ m] -[1+ n] := mod_add_div_aux m n.succ theorem div_add_mod (a b : ℤ) : b * (a / b) + a % b = a := (add_comm _ _).trans (mod_add_div _ _) lemma mod_add_div' (m k : ℤ) : m % k + (m / k) * k = m := by { rw mul_comm, exact mod_add_div _ _ } lemma div_add_mod' (m k : ℤ) : (m / k) * k + m % k = m := by { rw mul_comm, exact div_add_mod _ _ } theorem mod_def (a b : ℤ) : a % b = a - b * (a / b) := eq_sub_of_add_eq (mod_add_div _ _) @[simp] theorem add_mul_mod_self {a b c : ℤ} : (a + b * c) % c = a % c := if cz : c = 0 then by rw [cz, mul_zero, add_zero] else by rw [mod_def, mod_def, int.add_mul_div_right _ _ cz, mul_add, mul_comm, add_sub_add_right_eq_sub] @[simp] theorem add_mul_mod_self_left (a b c : ℤ) : (a + b * c) % b = a % b := by rw [mul_comm, add_mul_mod_self] @[simp] theorem add_mod_self {a b : ℤ} : (a + b) % b = a % b := by have := add_mul_mod_self_left a b 1; rwa mul_one at this @[simp] theorem add_mod_self_left {a b : ℤ} : (a + b) % a = b % a := by rw [add_comm, add_mod_self] @[simp] theorem mod_add_mod (m n k : ℤ) : (m % n + k) % n = (m + k) % n := by have := (add_mul_mod_self_left (m % n + k) n (m / n)).symm; rwa [add_right_comm, mod_add_div] at this @[simp] theorem add_mod_mod (m n k : ℤ) : (m + n % k) % k = (m + n) % k := by rw [add_comm, mod_add_mod, add_comm] lemma add_mod (a b n : ℤ) : (a + b) % n = ((a % n) + (b % n)) % n := by rw [add_mod_mod, mod_add_mod] theorem add_mod_eq_add_mod_right {m n k : ℤ} (i : ℤ) (H : m % n = k % n) : (m + i) % n = (k + i) % n := by rw [← mod_add_mod, ← mod_add_mod k, H] theorem add_mod_eq_add_mod_left {m n k : ℤ} (i : ℤ) (H : m % n = k % n) : (i + m) % n = (i + k) % n := by rw [add_comm, add_mod_eq_add_mod_right _ H, add_comm] theorem mod_add_cancel_right {m n k : ℤ} (i) : (m + i) % n = (k + i) % n ↔ m % n = k % n := ⟨λ H, by have := add_mod_eq_add_mod_right (-i) H; rwa [add_neg_cancel_right, add_neg_cancel_right] at this, add_mod_eq_add_mod_right _⟩ theorem mod_add_cancel_left {m n k i : ℤ} : (i + m) % n = (i + k) % n ↔ m % n = k % n := by rw [add_comm, add_comm i, mod_add_cancel_right] theorem mod_sub_cancel_right {m n k : ℤ} (i) : (m - i) % n = (k - i) % n ↔ m % n = k % n := mod_add_cancel_right _ theorem mod_eq_mod_iff_mod_sub_eq_zero {m n k : ℤ} : m % n = k % n ↔ (m - k) % n = 0 := (mod_sub_cancel_right k).symm.trans $ by simp @[simp] theorem mul_mod_left (a b : ℤ) : (a * b) % b = 0 := by rw [← zero_add (a * b), add_mul_mod_self, zero_mod] @[simp] theorem mul_mod_right (a b : ℤ) : (a * b) % a = 0 := by rw [mul_comm, mul_mod_left] lemma mul_mod (a b n : ℤ) : (a * b) % n = ((a % n) * (b % n)) % n := begin conv_lhs { rw [←mod_add_div a n, ←mod_add_div' b n, right_distrib, left_distrib, left_distrib, mul_assoc, mul_assoc, ←left_distrib n _ _, add_mul_mod_self_left, ← mul_assoc, add_mul_mod_self] } end @[simp] lemma neg_mod_two (i : ℤ) : (-i) % 2 = i % 2 := begin apply int.mod_eq_mod_iff_mod_sub_eq_zero.mpr, convert int.mul_mod_right 2 (-i), simp only [two_mul, sub_eq_add_neg] end local attribute [simp] -- Will be generalized to Euclidean domains. theorem mod_self {a : ℤ} : a % a = 0 := by have := mul_mod_left 1 a; rwa one_mul at this @[simp] theorem mod_mod_of_dvd (n : int) {m k : int} (h : m ∣ k) : n % k % m = n % m := begin conv { to_rhs, rw ←mod_add_div n k }, rcases h with ⟨t, rfl⟩, rw [mul_assoc, add_mul_mod_self_left] end @[simp] theorem mod_mod (a b : ℤ) : a % b % b = a % b := by conv {to_rhs, rw [← mod_add_div a b, add_mul_mod_self_left]} lemma sub_mod (a b n : ℤ) : (a - b) % n = ((a % n) - (b % n)) % n := begin apply (mod_add_cancel_right b).mp, rw [sub_add_cancel, ← add_mod_mod, sub_add_cancel, mod_mod] end /-! ### properties of `/` and `%` -/ @[simp] theorem mul_div_mul_of_pos {a : ℤ} (b c : ℤ) (H : 0 < a) : a * b / (a * c) = b / c := suffices ∀ (m k : ℕ) (b : ℤ), (m.succ * b / (m.succ * k) : ℤ) = b / k, from match a, eq_succ_of_zero_lt H, c, eq_coe_or_neg c with | ._, ⟨m, rfl⟩, ._, ⟨k, or.inl rfl⟩ := this _ _ _ | ._, ⟨m, rfl⟩, ._, ⟨k, or.inr rfl⟩ := by rw [← neg_mul_eq_mul_neg, int.div_neg, int.div_neg]; apply congr_arg has_neg.neg; apply this end, λ m k b, match b, k with | (n : ℕ), k := congr_arg of_nat (nat.mul_div_mul _ _ m.succ_pos) | -[1+ n], 0 := by rw [int.coe_nat_zero, mul_zero, int.div_zero, int.div_zero] | -[1+ n], k+1 := congr_arg neg_succ_of_nat $ show (m.succ * n + m) / (m.succ * k.succ) = n / k.succ, begin apply nat.div_eq_of_lt_le, { refine le_trans _ (nat.le_add_right _ _), rw [← nat.mul_div_mul _ _ m.succ_pos], apply nat.div_mul_le_self }, { change m.succ * n.succ ≤ _, rw [mul_left_comm], apply nat.mul_le_mul_left, apply (nat.div_lt_iff_lt_mul _ _ k.succ_pos).1, apply nat.lt_succ_self } end end @[simp] theorem mul_div_mul_of_pos_left (a : ℤ) {b : ℤ} (c : ℤ) (H : 0 < b) : a * b / (c * b) = a / c := by rw [mul_comm, mul_comm c, mul_div_mul_of_pos _ _ H] @[simp] theorem mul_mod_mul_of_pos {a : ℤ} (b c : ℤ) (H : 0 < a) : a * b % (a * c) = a * (b % c) := by rw [mod_def, mod_def, mul_div_mul_of_pos _ _ H, mul_sub_left_distrib, mul_assoc] theorem lt_div_add_one_mul_self (a : ℤ) {b : ℤ} (H : 0 < b) : a < (a / b + 1) * b := by { rw [add_mul, one_mul, mul_comm, ← sub_lt_iff_lt_add', ← mod_def], exact mod_lt_of_pos _ H } theorem abs_div_le_abs : ∀ (a b : ℤ), abs (a / b) ≤ abs a := suffices ∀ (a : ℤ) (n : ℕ), abs (a / n) ≤ abs a, from λ a b, match b, eq_coe_or_neg b with | ._, ⟨n, or.inl rfl⟩ := this _ _ | ._, ⟨n, or.inr rfl⟩ := by rw [int.div_neg, abs_neg]; apply this end, λ a n, by rw [abs_eq_nat_abs, abs_eq_nat_abs]; exact coe_nat_le_coe_nat_of_le (match a, n with | (m : ℕ), n := nat.div_le_self _ _ | -[1+ m], 0 := nat.zero_le _ | -[1+ m], n+1 := nat.succ_le_succ (nat.div_le_self _ _) end) theorem div_le_self {a : ℤ} (b : ℤ) (Ha : 0 ≤ a) : a / b ≤ a := by have := le_trans (le_abs_self _) (abs_div_le_abs a b); rwa [abs_of_nonneg Ha] at this theorem mul_div_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : b * (a / b) = a := by have := mod_add_div a b; rwa [H, zero_add] at this theorem div_mul_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : a / b * b = a := by rw [mul_comm, mul_div_cancel_of_mod_eq_zero H] lemma mod_two_eq_zero_or_one (n : ℤ) : n % 2 = 0 ∨ n % 2 = 1 := have h : n % 2 < 2 := abs_of_nonneg (show 0 ≤ (2 : ℤ), from dec_trivial) ▸ int.mod_lt _ dec_trivial, have h₁ : 0 ≤ n % 2 := int.mod_nonneg _ dec_trivial, match (n % 2), h, h₁ with | (0 : ℕ) := λ _ _, or.inl rfl | (1 : ℕ) := λ _ _, or.inr rfl | (k + 2 : ℕ) := λ h _, absurd h dec_trivial | -[1+ a] := λ _ h₁, absurd h₁ dec_trivial end /-! ### dvd -/ @[norm_cast] theorem coe_nat_dvd {m n : ℕ} : (↑m : ℤ) ∣ ↑n ↔ m ∣ n := ⟨λ ⟨a, ae⟩, m.eq_zero_or_pos.elim (λm0, by simp [m0] at ae; simp [ae, m0]) (λm0l, by { cases eq_coe_of_zero_le (@nonneg_of_mul_nonneg_left ℤ _ m a (by simp [ae.symm]) (by simpa using m0l)) with k e, subst a, exact ⟨k, int.coe_nat_inj ae⟩ }), λ ⟨k, e⟩, dvd.intro k $ by rw [e, int.coe_nat_mul]⟩ theorem coe_nat_dvd_left {n : ℕ} {z : ℤ} : (↑n : ℤ) ∣ z ↔ n ∣ z.nat_abs := by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd] theorem coe_nat_dvd_right {n : ℕ} {z : ℤ} : z ∣ (↑n : ℤ) ↔ z.nat_abs ∣ n := by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd] theorem dvd_antisymm {a b : ℤ} (H1 : 0 ≤ a) (H2 : 0 ≤ b) : a ∣ b → b ∣ a → a = b := begin rw [← abs_of_nonneg H1, ← abs_of_nonneg H2, abs_eq_nat_abs, abs_eq_nat_abs], rw [coe_nat_dvd, coe_nat_dvd, coe_nat_inj'], apply nat.dvd_antisymm end theorem dvd_of_mod_eq_zero {a b : ℤ} (H : b % a = 0) : a ∣ b := ⟨b / a, (mul_div_cancel_of_mod_eq_zero H).symm⟩ theorem mod_eq_zero_of_dvd : ∀ {a b : ℤ}, a ∣ b → b % a = 0 | a ._ ⟨c, rfl⟩ := mul_mod_right _ _ theorem dvd_iff_mod_eq_zero (a b : ℤ) : a ∣ b ↔ b % a = 0 := ⟨mod_eq_zero_of_dvd, dvd_of_mod_eq_zero⟩ /-- If `a % b = c` then `b` divides `a - c`. -/ lemma dvd_sub_of_mod_eq {a b c : ℤ} (h : a % b = c) : b ∣ a - c := begin have hx : a % b % b = c % b, { rw h }, rw [mod_mod, ←mod_sub_cancel_right c, sub_self, zero_mod] at hx, exact dvd_of_mod_eq_zero hx end theorem nat_abs_dvd {a b : ℤ} : (a.nat_abs : ℤ) ∣ b ↔ a ∣ b := (nat_abs_eq a).elim (λ e, by rw ← e) (λ e, by rw [← neg_dvd_iff_dvd, ← e]) theorem dvd_nat_abs {a b : ℤ} : a ∣ b.nat_abs ↔ a ∣ b := (nat_abs_eq b).elim (λ e, by rw ← e) (λ e, by rw [← dvd_neg_iff_dvd, ← e]) instance decidable_dvd : @decidable_rel ℤ (∣) := assume a n, decidable_of_decidable_of_iff (by apply_instance) (dvd_iff_mod_eq_zero _ _).symm protected theorem div_mul_cancel {a b : ℤ} (H : b ∣ a) : a / b * b = a := div_mul_cancel_of_mod_eq_zero (mod_eq_zero_of_dvd H) protected theorem mul_div_cancel' {a b : ℤ} (H : a ∣ b) : a * (b / a) = b := by rw [mul_comm, int.div_mul_cancel H] protected theorem mul_div_assoc (a : ℤ) : ∀ {b c : ℤ}, c ∣ b → (a * b) / c = a * (b / c) | ._ c ⟨d, rfl⟩ := if cz : c = 0 then by simp [cz] else by rw [mul_left_comm, int.mul_div_cancel_left _ cz, int.mul_div_cancel_left _ cz] protected theorem mul_div_assoc' (b : ℤ) {a c : ℤ} (h : c ∣ a) : a * b / c = a / c * b := by rw [mul_comm, int.mul_div_assoc _ h, mul_comm] theorem div_dvd_div : ∀ {a b c : ℤ} (H1 : a ∣ b) (H2 : b ∣ c), b / a ∣ c / a | a ._ ._ ⟨b, rfl⟩ ⟨c, rfl⟩ := if az : a = 0 then by simp [az] else by rw [int.mul_div_cancel_left _ az, mul_assoc, int.mul_div_cancel_left _ az]; apply dvd_mul_right protected theorem eq_mul_of_div_eq_right {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) : a = b * c := by rw [← H2, int.mul_div_cancel' H1] protected theorem div_eq_of_eq_mul_right {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = b * c) : a / b = c := by rw [H2, int.mul_div_cancel_left _ H1] protected theorem eq_div_of_mul_eq_right {a b c : ℤ} (H1 : a ≠ 0) (H2 : a * b = c) : b = c / a := eq.symm $ int.div_eq_of_eq_mul_right H1 H2.symm protected theorem div_eq_iff_eq_mul_right {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) : a / b = c ↔ a = b * c := ⟨int.eq_mul_of_div_eq_right H', int.div_eq_of_eq_mul_right H⟩ protected theorem div_eq_iff_eq_mul_left {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) : a / b = c ↔ a = c * b := by rw mul_comm; exact int.div_eq_iff_eq_mul_right H H' protected theorem eq_mul_of_div_eq_left {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) : a = c * b := by rw [mul_comm, int.eq_mul_of_div_eq_right H1 H2] protected theorem div_eq_of_eq_mul_left {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = c * b) : a / b = c := int.div_eq_of_eq_mul_right H1 (by rw [mul_comm, H2]) theorem neg_div_of_dvd : ∀ {a b : ℤ} (H : b ∣ a), -a / b = -(a / b) | ._ b ⟨c, rfl⟩ := if bz : b = 0 then by simp [bz] else by rw [neg_mul_eq_mul_neg, int.mul_div_cancel_left _ bz, int.mul_div_cancel_left _ bz] lemma sub_div_of_dvd {a b c : ℤ} (hcb : c ∣ b) : (a - b) / c = a / c - b / c := begin rw [sub_eq_add_neg, sub_eq_add_neg, int.add_div_of_dvd_right ((dvd_neg c b).mpr hcb)], congr, exact neg_div_of_dvd hcb, end lemma sub_div_of_dvd_sub {a b c : ℤ} (hcab : c ∣ (a - b)) : (a - b) / c = a / c - b / c := by rw [eq_sub_iff_add_eq, ← int.add_div_of_dvd_left hcab, sub_add_cancel] theorem div_sign : ∀ a b, a / sign b = a * sign b | a (n+1:ℕ) := by unfold sign; simp | a 0 := by simp [sign] | a -[1+ n] := by simp [sign] @[simp] theorem sign_mul : ∀ a b, sign (a * b) = sign a * sign b | a 0 := by simp | 0 b := by simp | (m+1:ℕ) (n+1:ℕ) := rfl | (m+1:ℕ) -[1+ n] := rfl | -[1+ m] (n+1:ℕ) := rfl | -[1+ m] -[1+ n] := rfl protected theorem sign_eq_div_abs (a : ℤ) : sign a = a / (abs a) := if az : a = 0 then by simp [az] else (int.div_eq_of_eq_mul_left (mt abs_eq_zero.1 az) (sign_mul_abs _).symm).symm theorem mul_sign : ∀ (i : ℤ), i * sign i = nat_abs i | (n+1:ℕ) := mul_one _ | 0 := mul_zero _ | -[1+ n] := mul_neg_one _ theorem le_of_dvd {a b : ℤ} (bpos : 0 < b) (H : a ∣ b) : a ≤ b := match a, b, eq_succ_of_zero_lt bpos, H with | (m : ℕ), ._, ⟨n, rfl⟩, H := coe_nat_le_coe_nat_of_le $ nat.le_of_dvd n.succ_pos $ coe_nat_dvd.1 H | -[1+ m], ._, ⟨n, rfl⟩, _ := le_trans (le_of_lt $ neg_succ_lt_zero _) (coe_zero_le _) end theorem eq_one_of_dvd_one {a : ℤ} (H : 0 ≤ a) (H' : a ∣ 1) : a = 1 := match a, eq_coe_of_zero_le H, H' with | ._, ⟨n, rfl⟩, H' := congr_arg coe $ nat.eq_one_of_dvd_one $ coe_nat_dvd.1 H' end theorem eq_one_of_mul_eq_one_right {a b : ℤ} (H : 0 ≤ a) (H' : a * b = 1) : a = 1 := eq_one_of_dvd_one H ⟨b, H'.symm⟩ theorem eq_one_of_mul_eq_one_left {a b : ℤ} (H : 0 ≤ b) (H' : a * b = 1) : b = 1 := eq_one_of_mul_eq_one_right H (by rw [mul_comm, H']) lemma of_nat_dvd_of_dvd_nat_abs {a : ℕ} : ∀ {z : ℤ} (haz : a ∣ z.nat_abs), ↑a ∣ z | (int.of_nat _) haz := int.coe_nat_dvd.2 haz | -[1+k] haz := begin change ↑a ∣ -(k+1 : ℤ), apply dvd_neg_of_dvd, apply int.coe_nat_dvd.2, exact haz end lemma dvd_nat_abs_of_of_nat_dvd {a : ℕ} : ∀ {z : ℤ} (haz : ↑a ∣ z), a ∣ z.nat_abs | (int.of_nat _) haz := int.coe_nat_dvd.1 (int.dvd_nat_abs.2 haz) | -[1+k] haz := have haz' : (↑a:ℤ) ∣ (↑(k+1):ℤ), from dvd_of_dvd_neg haz, int.coe_nat_dvd.1 haz' lemma pow_dvd_of_le_of_pow_dvd {p m n : ℕ} {k : ℤ} (hmn : m ≤ n) (hdiv : ↑(p ^ n) ∣ k) : ↑(p ^ m) ∣ k := begin induction k, { apply int.coe_nat_dvd.2, apply pow_dvd_of_le_of_pow_dvd hmn, apply int.coe_nat_dvd.1 hdiv }, { change -[1+k] with -(↑(k+1) : ℤ), apply dvd_neg_of_dvd, apply int.coe_nat_dvd.2, apply pow_dvd_of_le_of_pow_dvd hmn, apply int.coe_nat_dvd.1, apply dvd_of_dvd_neg, exact hdiv } end lemma dvd_of_pow_dvd {p k : ℕ} {m : ℤ} (hk : 1 ≤ k) (hpk : ↑(p^k) ∣ m) : ↑p ∣ m := by rw ←pow_one p; exact pow_dvd_of_le_of_pow_dvd hk hpk /-- If `n > 0` then `m` is not divisible by `n` iff it is between `n * k` and `n * (k + 1)` for some `k`. -/ lemma exists_lt_and_lt_iff_not_dvd (m : ℤ) {n : ℤ} (hn : 0 < n) : (∃ k, n * k < m ∧ m < n * (k + 1)) ↔ ¬ n ∣ m := begin split, { rintro ⟨k, h1k, h2k⟩ ⟨l, rfl⟩, rw [mul_lt_mul_left hn] at h1k h2k, rw [lt_add_one_iff, ← not_lt] at h2k, exact h2k h1k }, { intro h, rw [dvd_iff_mod_eq_zero, ← ne.def] at h, have := (mod_nonneg m hn.ne.symm).lt_of_ne h.symm, simp only [← mod_add_div m n] {single_pass := tt}, refine ⟨m / n, lt_add_of_pos_left _ this, _⟩, rw [add_comm _ (1 : ℤ), left_distrib, mul_one], exact add_lt_add_right (mod_lt_of_pos _ hn) _ } end /-! ### `/` and ordering -/ protected theorem div_mul_le (a : ℤ) {b : ℤ} (H : b ≠ 0) : a / b * b ≤ a := le_of_sub_nonneg $ by rw [mul_comm, ← mod_def]; apply mod_nonneg _ H protected theorem div_le_of_le_mul {a b c : ℤ} (H : 0 < c) (H' : a ≤ b * c) : a / c ≤ b := le_of_mul_le_mul_right (le_trans (int.div_mul_le _ (ne_of_gt H)) H') H protected theorem mul_lt_of_lt_div {a b c : ℤ} (H : 0 < c) (H3 : a < b / c) : a * c < b := lt_of_not_ge $ mt (int.div_le_of_le_mul H) (not_le_of_gt H3) protected theorem mul_le_of_le_div {a b c : ℤ} (H1 : 0 < c) (H2 : a ≤ b / c) : a * c ≤ b := le_trans (mul_le_mul_of_nonneg_right H2 (le_of_lt H1)) (int.div_mul_le _ (ne_of_gt H1)) protected theorem le_div_of_mul_le {a b c : ℤ} (H1 : 0 < c) (H2 : a * c ≤ b) : a ≤ b / c := le_of_lt_add_one $ lt_of_mul_lt_mul_right (lt_of_le_of_lt H2 (lt_div_add_one_mul_self _ H1)) (le_of_lt H1) protected theorem le_div_iff_mul_le {a b c : ℤ} (H : 0 < c) : a ≤ b / c ↔ a * c ≤ b := ⟨int.mul_le_of_le_div H, int.le_div_of_mul_le H⟩ protected theorem div_le_div {a b c : ℤ} (H : 0 < c) (H' : a ≤ b) : a / c ≤ b / c := int.le_div_of_mul_le H (le_trans (int.div_mul_le _ (ne_of_gt H)) H') protected theorem div_lt_of_lt_mul {a b c : ℤ} (H : 0 < c) (H' : a < b * c) : a / c < b := lt_of_not_ge $ mt (int.mul_le_of_le_div H) (not_le_of_gt H') protected theorem lt_mul_of_div_lt {a b c : ℤ} (H1 : 0 < c) (H2 : a / c < b) : a < b * c := lt_of_not_ge $ mt (int.le_div_of_mul_le H1) (not_le_of_gt H2) protected theorem div_lt_iff_lt_mul {a b c : ℤ} (H : 0 < c) : a / c < b ↔ a < b * c := ⟨int.lt_mul_of_div_lt H, int.div_lt_of_lt_mul H⟩ protected theorem le_mul_of_div_le {a b c : ℤ} (H1 : 0 ≤ b) (H2 : b ∣ a) (H3 : a / b ≤ c) : a ≤ c * b := by rw [← int.div_mul_cancel H2]; exact mul_le_mul_of_nonneg_right H3 H1 protected theorem lt_div_of_mul_lt {a b c : ℤ} (H1 : 0 ≤ b) (H2 : b ∣ c) (H3 : a * b < c) : a < c / b := lt_of_not_ge $ mt (int.le_mul_of_div_le H1 H2) (not_le_of_gt H3) protected theorem lt_div_iff_mul_lt {a b : ℤ} (c : ℤ) (H : 0 < c) (H' : c ∣ b) : a < b / c ↔ a * c < b := ⟨int.mul_lt_of_lt_div H, int.lt_div_of_mul_lt (le_of_lt H) H'⟩ theorem div_pos_of_pos_of_dvd {a b : ℤ} (H1 : 0 < a) (H2 : 0 ≤ b) (H3 : b ∣ a) : 0 < a / b := int.lt_div_of_mul_lt H2 H3 (by rwa zero_mul) theorem div_eq_div_of_mul_eq_mul {a b c d : ℤ} (H2 : d ∣ c) (H3 : b ≠ 0) (H4 : d ≠ 0) (H5 : a * d = b * c) : a / b = c / d := int.div_eq_of_eq_mul_right H3 $ by rw [← int.mul_div_assoc _ H2]; exact (int.div_eq_of_eq_mul_left H4 H5.symm).symm theorem eq_mul_div_of_mul_eq_mul_of_dvd_left {a b c d : ℤ} (hb : b ≠ 0) (hbc : b ∣ c) (h : b * a = c * d) : a = c / b * d := begin cases hbc with k hk, subst hk, rw [int.mul_div_cancel_left _ hb], rw mul_assoc at h, apply mul_left_cancel' hb h end /-- If an integer with larger absolute value divides an integer, it is zero. -/ lemma eq_zero_of_dvd_of_nat_abs_lt_nat_abs {a b : ℤ} (w : a ∣ b) (h : nat_abs b < nat_abs a) : b = 0 := begin rw [←nat_abs_dvd, ←dvd_nat_abs, coe_nat_dvd] at w, rw ←nat_abs_eq_zero, exact eq_zero_of_dvd_of_lt w h end lemma eq_zero_of_dvd_of_nonneg_of_lt {a b : ℤ} (w₁ : 0 ≤ a) (w₂ : a < b) (h : b ∣ a) : a = 0 := eq_zero_of_dvd_of_nat_abs_lt_nat_abs h (nat_abs_lt_nat_abs_of_nonneg_of_lt w₁ w₂) /-- If two integers are congruent to a sufficiently large modulus, they are equal. -/ lemma eq_of_mod_eq_of_nat_abs_sub_lt_nat_abs {a b c : ℤ} (h1 : a % b = c) (h2 : nat_abs (a - c) < nat_abs b) : a = c := eq_of_sub_eq_zero (eq_zero_of_dvd_of_nat_abs_lt_nat_abs (dvd_sub_of_mod_eq h1) h2) theorem of_nat_add_neg_succ_of_nat_of_lt {m n : ℕ} (h : m < n.succ) : of_nat m + -[1+n] = -[1+ n - m] := begin change sub_nat_nat _ _ = _, have h' : n.succ - m = (n - m).succ, apply succ_sub, apply le_of_lt_succ h, simp [*, sub_nat_nat] end theorem of_nat_add_neg_succ_of_nat_of_ge {m n : ℕ} (h : n.succ ≤ m) : of_nat m + -[1+n] = of_nat (m - n.succ) := begin change sub_nat_nat _ _ = _, have h' : n.succ - m = 0, apply sub_eq_zero_of_le h, simp [*, sub_nat_nat] end @[simp] theorem neg_add_neg (m n : ℕ) : -[1+m] + -[1+n] = -[1+nat.succ(m+n)] := rfl /-! ### to_nat -/ theorem to_nat_eq_max : ∀ (a : ℤ), (to_nat a : ℤ) = max a 0 | (n : ℕ) := (max_eq_left (coe_zero_le n)).symm | -[1+ n] := (max_eq_right (le_of_lt (neg_succ_lt_zero n))).symm @[simp] lemma to_nat_zero : (0 : ℤ).to_nat = 0 := rfl @[simp] lemma to_nat_one : (1 : ℤ).to_nat = 1 := rfl @[simp] theorem to_nat_of_nonneg {a : ℤ} (h : 0 ≤ a) : (to_nat a : ℤ) = a := by rw [to_nat_eq_max, max_eq_left h] @[simp] lemma to_nat_sub_of_le (a b : ℤ) (h : b ≤ a) : (to_nat (a + -b) : ℤ) = a + - b := int.to_nat_of_nonneg (sub_nonneg_of_le h) @[simp] theorem to_nat_coe_nat (n : ℕ) : to_nat ↑n = n := rfl @[simp] lemma to_nat_coe_nat_add_one {n : ℕ} : ((n : ℤ) + 1).to_nat = n + 1 := rfl theorem le_to_nat (a : ℤ) : a ≤ to_nat a := by rw [to_nat_eq_max]; apply le_max_left @[simp] theorem to_nat_le {a : ℤ} {n : ℕ} : to_nat a ≤ n ↔ a ≤ n := by rw [(coe_nat_le_coe_nat_iff _ _).symm, to_nat_eq_max, max_le_iff]; exact and_iff_left (coe_zero_le _) @[simp] theorem lt_to_nat {n : ℕ} {a : ℤ} : n < to_nat a ↔ (n : ℤ) < a := le_iff_le_iff_lt_iff_lt.1 to_nat_le theorem to_nat_le_to_nat {a b : ℤ} (h : a ≤ b) : to_nat a ≤ to_nat b := by rw to_nat_le; exact le_trans h (le_to_nat b) theorem to_nat_lt_to_nat {a b : ℤ} (hb : 0 < b) : to_nat a < to_nat b ↔ a < b := ⟨λ h, begin cases a, exact lt_to_nat.1 h, exact lt_trans (neg_succ_of_nat_lt_zero a) hb, end, λ h, begin rw lt_to_nat, cases a, exact h, exact hb end⟩ theorem lt_of_to_nat_lt {a b : ℤ} (h : to_nat a < to_nat b) : a < b := (to_nat_lt_to_nat $ lt_to_nat.1 $ lt_of_le_of_lt (nat.zero_le _) h).1 h lemma to_nat_add {a b : ℤ} (ha : 0 ≤ a) (hb : 0 ≤ b) : (a + b).to_nat = a.to_nat + b.to_nat := begin lift a to ℕ using ha, lift b to ℕ using hb, norm_cast, end lemma to_nat_add_one {a : ℤ} (h : 0 ≤ a) : (a + 1).to_nat = a.to_nat + 1 := to_nat_add h (zero_le_one) @[simp] lemma pred_to_nat : ∀ (i : ℤ), (i - 1).to_nat = i.to_nat - 1 | (0:ℕ) := rfl | (n+1:ℕ) := by simp | -[1+ n] := rfl @[simp] lemma to_nat_pred_coe_of_pos {i : ℤ} (h : 0 < i) : ((i.to_nat - 1 : ℕ) : ℤ) = i - 1 := by simp [h, le_of_lt h] with push_cast /-- If `n : ℕ`, then `int.to_nat' n = some n`, if `n : ℤ` is negative, then `int.to_nat' n = none`. -/ def to_nat' : ℤ → option ℕ | (n : ℕ) := some n | -[1+ n] := none theorem mem_to_nat' : ∀ (a : ℤ) (n : ℕ), n ∈ to_nat' a ↔ a = n | (m : ℕ) n := option.some_inj.trans coe_nat_inj'.symm | -[1+ m] n := by split; intro h; cases h lemma to_nat_zero_of_neg : ∀ {z : ℤ}, z < 0 → z.to_nat = 0 | (-[1+n]) _ := rfl | (int.of_nat n) h := (not_le_of_gt h $ int.of_nat_nonneg n).elim /-! ### units -/ @[simp] theorem units_nat_abs (u : units ℤ) : nat_abs u = 1 := units.ext_iff.1 $ nat.units_eq_one ⟨nat_abs u, nat_abs ↑u⁻¹, by rw [← nat_abs_mul, units.mul_inv]; refl, by rw [← nat_abs_mul, units.inv_mul]; refl⟩ theorem units_eq_one_or (u : units ℤ) : u = 1 ∨ u = -1 := by simpa only [units.ext_iff, units_nat_abs] using nat_abs_eq u lemma is_unit_eq_one_or {a : ℤ} : is_unit a → a = 1 ∨ a = -1 | ⟨x, hx⟩ := hx ▸ (units_eq_one_or _).imp (congr_arg coe) (congr_arg coe) lemma is_unit_iff {a : ℤ} : is_unit a ↔ a = 1 ∨ a = -1 := begin refine ⟨λ h, is_unit_eq_one_or h, λ h, _⟩, rcases h with rfl | rfl, { exact is_unit_one }, { exact is_unit_one.neg } end theorem is_unit_iff_nat_abs_eq {n : ℤ} : is_unit n ↔ n.nat_abs = 1 := by simp [nat_abs_eq_iff, is_unit_iff] lemma units_inv_eq_self (u : units ℤ) : u⁻¹ = u := (units_eq_one_or u).elim (λ h, h.symm ▸ rfl) (λ h, h.symm ▸ rfl) @[simp] lemma units_mul_self (u : units ℤ) : u * u = 1 := (units_eq_one_or u).elim (λ h, h.symm ▸ rfl) (λ h, h.symm ▸ rfl) -- `units.coe_mul` is a "wrong turn" for the simplifier, this undoes it and simplifies further @[simp] lemma units_coe_mul_self (u : units ℤ) : (u * u : ℤ) = 1 := by rw [←units.coe_mul, units_mul_self, units.coe_one] @[simp] lemma neg_one_pow_ne_zero {n : ℕ} : (-1 : ℤ)^n ≠ 0 := pow_ne_zero _ (abs_pos.mp trivial) /-! ### bitwise ops -/ @[simp] lemma bodd_zero : bodd 0 = ff := rfl @[simp] lemma bodd_one : bodd 1 = tt := rfl lemma bodd_two : bodd 2 = ff := rfl @[simp, norm_cast] lemma bodd_coe (n : ℕ) : int.bodd n = nat.bodd n := rfl @[simp] lemma bodd_sub_nat_nat (m n : ℕ) : bodd (sub_nat_nat m n) = bxor m.bodd n.bodd := by apply sub_nat_nat_elim m n (λ m n i, bodd i = bxor m.bodd n.bodd); intros; simp; cases i.bodd; simp @[simp] lemma bodd_neg_of_nat (n : ℕ) : bodd (neg_of_nat n) = n.bodd := by cases n; simp; refl @[simp] lemma bodd_neg (n : ℤ) : bodd (-n) = bodd n := by cases n; simp [has_neg.neg, int.coe_nat_eq, int.neg, bodd, -of_nat_eq_coe] @[simp] lemma bodd_add (m n : ℤ) : bodd (m + n) = bxor (bodd m) (bodd n) := by cases m with m m; cases n with n n; unfold has_add.add; simp [int.add, -of_nat_eq_coe, bool.bxor_comm] @[simp] lemma bodd_mul (m n : ℤ) : bodd (m * n) = bodd m && bodd n := by cases m with m m; cases n with n n; simp [← int.mul_def, int.mul, -of_nat_eq_coe, bool.bxor_comm] theorem bodd_add_div2 : ∀ n, cond (bodd n) 1 0 + 2 * div2 n = n | (n : ℕ) := by rw [show (cond (bodd n) 1 0 : ℤ) = (cond (bodd n) 1 0 : ℕ), by cases bodd n; refl]; exact congr_arg of_nat n.bodd_add_div2 | -[1+ n] := begin refine eq.trans _ (congr_arg neg_succ_of_nat n.bodd_add_div2), dsimp [bodd], cases nat.bodd n; dsimp [cond, bnot, div2, int.mul], { change -[1+ 2 * nat.div2 n] = _, rw zero_add }, { rw [zero_add, add_comm], refl } end theorem div2_val : ∀ n, div2 n = n / 2 | (n : ℕ) := congr_arg of_nat n.div2_val | -[1+ n] := congr_arg neg_succ_of_nat n.div2_val lemma bit0_val (n : ℤ) : bit0 n = 2 * n := (two_mul _).symm lemma bit1_val (n : ℤ) : bit1 n = 2 * n + 1 := congr_arg (+(1:ℤ)) (bit0_val _) lemma bit_val (b n) : bit b n = 2 * n + cond b 1 0 := by { cases b, apply (bit0_val n).trans (add_zero _).symm, apply bit1_val } lemma bit_decomp (n : ℤ) : bit (bodd n) (div2 n) = n := (bit_val _ _).trans $ (add_comm _ _).trans $ bodd_add_div2 _ /-- Defines a function from `ℤ` conditionally, if it is defined for odd and even integers separately using `bit`. -/ def {u} bit_cases_on {C : ℤ → Sort u} (n) (h : ∀ b n, C (bit b n)) : C n := by rw [← bit_decomp n]; apply h @[simp] lemma bit_zero : bit ff 0 = 0 := rfl @[simp] lemma bit_coe_nat (b) (n : ℕ) : bit b n = nat.bit b n := by rw [bit_val, nat.bit_val]; cases b; refl @[simp] lemma bit_neg_succ (b) (n : ℕ) : bit b -[1+ n] = -[1+ nat.bit (bnot b) n] := by rw [bit_val, nat.bit_val]; cases b; refl @[simp] lemma bodd_bit (b n) : bodd (bit b n) = b := by rw bit_val; simp; cases b; cases bodd n; refl @[simp] lemma bodd_bit0 (n : ℤ) : bodd (bit0 n) = ff := bodd_bit ff n @[simp] lemma bodd_bit1 (n : ℤ) : bodd (bit1 n) = tt := bodd_bit tt n @[simp] lemma div2_bit (b n) : div2 (bit b n) = n := begin rw [bit_val, div2_val, add_comm, int.add_mul_div_left, (_ : (_/2:ℤ) = 0), zero_add], cases b, { simp }, { show of_nat _ = _, rw nat.div_eq_zero; simp }, { cc } end lemma bit0_ne_bit1 (m n : ℤ) : bit0 m ≠ bit1 n := mt (congr_arg bodd) $ by simp lemma bit1_ne_bit0 (m n : ℤ) : bit1 m ≠ bit0 n := (bit0_ne_bit1 _ _).symm lemma bit1_ne_zero (m : ℤ) : bit1 m ≠ 0 := by simpa only [bit0_zero] using bit1_ne_bit0 m 0 @[simp] lemma test_bit_zero (b) : ∀ n, test_bit (bit b n) 0 = b | (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_zero | -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_zero]; clear test_bit_zero; cases b; refl @[simp] lemma test_bit_succ (m b) : ∀ n, test_bit (bit b n) (nat.succ m) = test_bit n m | (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_succ | -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_succ] private meta def bitwise_tac : tactic unit := `[ funext m, funext n, cases m with m m; cases n with n n; try {refl}, all_goals { apply congr_arg of_nat <|> apply congr_arg neg_succ_of_nat, try {dsimp [nat.land, nat.ldiff, nat.lor]}, try {rw [ show nat.bitwise (λ a b, a && bnot b) n m = nat.bitwise (λ a b, b && bnot a) m n, from congr_fun (congr_fun (@nat.bitwise_swap (λ a b, b && bnot a) rfl) n) m]}, apply congr_arg (λ f, nat.bitwise f m n), funext a, funext b, cases a; cases b; refl }, all_goals {unfold nat.land nat.ldiff nat.lor} ] theorem bitwise_or : bitwise bor = lor := by bitwise_tac theorem bitwise_and : bitwise band = land := by bitwise_tac theorem bitwise_diff : bitwise (λ a b, a && bnot b) = ldiff := by bitwise_tac theorem bitwise_xor : bitwise bxor = lxor := by bitwise_tac @[simp] lemma bitwise_bit (f : bool → bool → bool) (a m b n) : bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) := begin cases m with m m; cases n with n n; repeat { rw [← int.coe_nat_eq] <|> rw bit_coe_nat <|> rw bit_neg_succ }; unfold bitwise nat_bitwise bnot; [ induction h : f ff ff, induction h : f ff tt, induction h : f tt ff, induction h : f tt tt ], all_goals { unfold cond, rw nat.bitwise_bit, repeat { rw bit_coe_nat <|> rw bit_neg_succ <|> rw bnot_bnot } }, all_goals { unfold bnot {fail_if_unchanged := ff}; rw h; refl } end @[simp] lemma lor_bit (a m b n) : lor (bit a m) (bit b n) = bit (a || b) (lor m n) := by rw [← bitwise_or, bitwise_bit] @[simp] lemma land_bit (a m b n) : land (bit a m) (bit b n) = bit (a && b) (land m n) := by rw [← bitwise_and, bitwise_bit] @[simp] lemma ldiff_bit (a m b n) : ldiff (bit a m) (bit b n) = bit (a && bnot b) (ldiff m n) := by rw [← bitwise_diff, bitwise_bit] @[simp] lemma lxor_bit (a m b n) : lxor (bit a m) (bit b n) = bit (bxor a b) (lxor m n) := by rw [← bitwise_xor, bitwise_bit] @[simp] lemma lnot_bit (b) : ∀ n, lnot (bit b n) = bit (bnot b) (lnot n) | (n : ℕ) := by simp [lnot] | -[1+ n] := by simp [lnot] @[simp] lemma test_bit_bitwise (f : bool → bool → bool) (m n k) : test_bit (bitwise f m n) k = f (test_bit m k) (test_bit n k) := begin induction k with k IH generalizing m n; apply bit_cases_on m; intros a m'; apply bit_cases_on n; intros b n'; rw bitwise_bit, { simp [test_bit_zero] }, { simp [test_bit_succ, IH] } end @[simp] lemma test_bit_lor (m n k) : test_bit (lor m n) k = test_bit m k || test_bit n k := by rw [← bitwise_or, test_bit_bitwise] @[simp] lemma test_bit_land (m n k) : test_bit (land m n) k = test_bit m k && test_bit n k := by rw [← bitwise_and, test_bit_bitwise] @[simp] lemma test_bit_ldiff (m n k) : test_bit (ldiff m n) k = test_bit m k && bnot (test_bit n k) := by rw [← bitwise_diff, test_bit_bitwise] @[simp] lemma test_bit_lxor (m n k) : test_bit (lxor m n) k = bxor (test_bit m k) (test_bit n k) := by rw [← bitwise_xor, test_bit_bitwise] @[simp] lemma test_bit_lnot : ∀ n k, test_bit (lnot n) k = bnot (test_bit n k) | (n : ℕ) k := by simp [lnot, test_bit] | -[1+ n] k := by simp [lnot, test_bit] lemma shiftl_add : ∀ (m : ℤ) (n : ℕ) (k : ℤ), shiftl m (n + k) = shiftl (shiftl m n) k | (m : ℕ) n (k:ℕ) := congr_arg of_nat (nat.shiftl_add _ _ _) | -[1+ m] n (k:ℕ) := congr_arg neg_succ_of_nat (nat.shiftl'_add _ _ _ _) | (m : ℕ) n -[1+k] := sub_nat_nat_elim n k.succ (λ n k i, shiftl ↑m i = nat.shiftr (nat.shiftl m n) k) (λ i n, congr_arg coe $ by rw [← nat.shiftl_sub, nat.add_sub_cancel_left]; apply nat.le_add_right) (λ i n, congr_arg coe $ by rw [add_assoc, nat.shiftr_add, ← nat.shiftl_sub, nat.sub_self]; refl) | -[1+ m] n -[1+k] := sub_nat_nat_elim n k.succ (λ n k i, shiftl -[1+ m] i = -[1+ nat.shiftr (nat.shiftl' tt m n) k]) (λ i n, congr_arg neg_succ_of_nat $ by rw [← nat.shiftl'_sub, nat.add_sub_cancel_left]; apply nat.le_add_right) (λ i n, congr_arg neg_succ_of_nat $ by rw [add_assoc, nat.shiftr_add, ← nat.shiftl'_sub, nat.sub_self]; refl) lemma shiftl_sub (m : ℤ) (n : ℕ) (k : ℤ) : shiftl m (n - k) = shiftr (shiftl m n) k := shiftl_add _ _ _ @[simp] lemma shiftl_neg (m n : ℤ) : shiftl m (-n) = shiftr m n := rfl @[simp] lemma shiftr_neg (m n : ℤ) : shiftr m (-n) = shiftl m n := by rw [← shiftl_neg, neg_neg] @[simp] lemma shiftl_coe_nat (m n : ℕ) : shiftl m n = nat.shiftl m n := rfl @[simp] lemma shiftr_coe_nat (m n : ℕ) : shiftr m n = nat.shiftr m n := by cases n; refl @[simp] lemma shiftl_neg_succ (m n : ℕ) : shiftl -[1+ m] n = -[1+ nat.shiftl' tt m n] := rfl @[simp] lemma shiftr_neg_succ (m n : ℕ) : shiftr -[1+ m] n = -[1+ nat.shiftr m n] := by cases n; refl lemma shiftr_add : ∀ (m : ℤ) (n k : ℕ), shiftr m (n + k) = shiftr (shiftr m n) k | (m : ℕ) n k := by rw [shiftr_coe_nat, shiftr_coe_nat, ← int.coe_nat_add, shiftr_coe_nat, nat.shiftr_add] | -[1+ m] n k := by rw [shiftr_neg_succ, shiftr_neg_succ, ← int.coe_nat_add, shiftr_neg_succ, nat.shiftr_add] lemma shiftl_eq_mul_pow : ∀ (m : ℤ) (n : ℕ), shiftl m n = m * ↑(2 ^ n) | (m : ℕ) n := congr_arg coe (nat.shiftl_eq_mul_pow _ _) | -[1+ m] n := @congr_arg ℕ ℤ _ _ (λi, -i) (nat.shiftl'_tt_eq_mul_pow _ _) lemma shiftr_eq_div_pow : ∀ (m : ℤ) (n : ℕ), shiftr m n = m / ↑(2 ^ n) | (m : ℕ) n := by rw shiftr_coe_nat; exact congr_arg coe (nat.shiftr_eq_div_pow _ _) | -[1+ m] n := begin rw [shiftr_neg_succ, neg_succ_of_nat_div, nat.shiftr_eq_div_pow], refl, exact coe_nat_lt_coe_nat_of_lt (pow_pos dec_trivial _) end lemma one_shiftl (n : ℕ) : shiftl 1 n = (2 ^ n : ℕ) := congr_arg coe (nat.one_shiftl _) @[simp] lemma zero_shiftl : ∀ n : ℤ, shiftl 0 n = 0 | (n : ℕ) := congr_arg coe (nat.zero_shiftl _) | -[1+ n] := congr_arg coe (nat.zero_shiftr _) @[simp] lemma zero_shiftr (n) : shiftr 0 n = 0 := zero_shiftl _ /-! ### Least upper bound property for integers -/ section classical open_locale classical theorem exists_least_of_bdd {P : ℤ → Prop} (Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → b ≤ z) (Hinh : ∃ z : ℤ, P z) : ∃ lb : ℤ, P lb ∧ (∀ z : ℤ, P z → lb ≤ z) := let ⟨b, Hb⟩ := Hbdd in have EX : ∃ n : ℕ, P (b + n), from let ⟨elt, Helt⟩ := Hinh in match elt, le.dest (Hb _ Helt), Helt with | ._, ⟨n, rfl⟩, Hn := ⟨n, Hn⟩ end, ⟨b + (nat.find EX : ℤ), nat.find_spec EX, λ z h, match z, le.dest (Hb _ h), h with | ._, ⟨n, rfl⟩, h := add_le_add_left (int.coe_nat_le.2 $ nat.find_min' _ h) _ end⟩ theorem exists_greatest_of_bdd {P : ℤ → Prop} (Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → z ≤ b) (Hinh : ∃ z : ℤ, P z) : ∃ ub : ℤ, P ub ∧ (∀ z : ℤ, P z → z ≤ ub) := have Hbdd' : ∃ (b : ℤ), ∀ (z : ℤ), P (-z) → b ≤ z, from let ⟨b, Hb⟩ := Hbdd in ⟨-b, λ z h, neg_le.1 (Hb _ h)⟩, have Hinh' : ∃ z : ℤ, P (-z), from let ⟨elt, Helt⟩ := Hinh in ⟨-elt, by rw [neg_neg]; exact Helt⟩, let ⟨lb, Plb, al⟩ := exists_least_of_bdd Hbdd' Hinh' in ⟨-lb, Plb, λ z h, le_neg.1 $ al _ $ by rwa neg_neg⟩ end classical end int attribute [irreducible] int.nonneg
ada0d74f6e9927aa8ccce50f36a6a19e8d0f291a
26bff4ed296b8373c92b6b025f5d60cdf02104b9
/tests/lean/run/vec_inv2.lean
be5cacfb8ffeec972680687ddddf3ed180619e7a
[ "Apache-2.0" ]
permissive
guiquanz/lean
b8a878ea24f237b84b0e6f6be2f300e8bf028229
242f8ba0486860e53e257c443e965a82ee342db3
refs/heads/master
1,526,680,092,098
1,427,492,833,000
1,427,493,281,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
751
lean
import data.nat.basic data.empty data.prod open nat eq.ops prod inductive vector (T : Type) : ℕ → Type := | nil {} : vector T 0 | cons : T → ∀{n}, vector T n → vector T (succ n) set_option pp.metavar_args true set_option pp.implicit true set_option pp.notation false namespace vector variables {A B C : Type} variables {n m : nat} theorem z_cases_on {C : vector A 0 → Type} (v : vector A 0) (Hnil : C nil) : C v := begin cases v, apply Hnil end protected definition destruct (v : vector A (succ n)) {P : Π {n : nat}, vector A (succ n) → Type} (H : Π {n : nat} (h : A) (t : vector A n), P (cons h t)) : P v := begin cases v with (h', n', t'), apply (H h' t') end end vector
42f26b6a61ddff69013e6b32690c79c200cf1158
137c667471a40116a7afd7261f030b30180468c2
/src/group_theory/sylow.lean
f5d9683607801073417c7581914a1e8eb65528f0
[ "Apache-2.0" ]
permissive
bragadeesh153/mathlib
46bf814cfb1eecb34b5d1549b9117dc60f657792
b577bb2cd1f96eb47031878256856020b76f73cd
refs/heads/master
1,687,435,188,334
1,626,384,207,000
1,626,384,207,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,274
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import group_theory.group_action import group_theory.quotient_group import group_theory.order_of_element import data.zmod.basic import data.fintype.card import data.list.rotate /-! # Sylow theorems The Sylow theorems are the following results for every finite group `G` and every prime number `p`. * There exists a Sylow `p`-subgroup of `G`. * All Sylow `p`-subgroups of `G` are conjugate to each other. * Let `nₚ` be the number of Sylow `p`-subgroups of `G`, then `nₚ` divides the index of the Sylow `p`-subgroup, `nₚ ≡ 1 [MOD p]`, and `nₚ` is equal to the index of the normalizer of the Sylow `p`-subgroup in `G`. In this file, currently only the first of these results is proven. ## Main statements * `exists_prime_order_of_dvd_card`: For every prime `p` dividing the order of `G` there exists an element of order `p` in `G`. This is known as Cauchy`s theorem. * `exists_subgroup_card_pow_prime`: A generalisation of the first of the Sylow theorems: For every prime power `pⁿ` dividing `G`, there exists a subgroup of `G` of order `pⁿ`. ## TODO * Prove the second and third of the Sylow theorems. * Sylow theorems for infinite groups -/ open equiv fintype finset mul_action function open equiv.perm subgroup list quotient_group open_locale big_operators universes u v w variables {G : Type u} {α : Type v} {β : Type w} [group G] local attribute [instance, priority 10] subtype.fintype set_fintype classical.prop_decidable namespace mul_action variables [mul_action G α] lemma mem_fixed_points_iff_card_orbit_eq_one {a : α} [fintype (orbit G a)] : a ∈ fixed_points G α ↔ card (orbit G a) = 1 := begin rw [fintype.card_eq_one_iff, mem_fixed_points], split, { exact λ h, ⟨⟨a, mem_orbit_self _⟩, λ ⟨b, ⟨x, hx⟩⟩, subtype.eq $ by simp [h x, hx.symm]⟩ }, { assume h x, rcases h with ⟨⟨z, hz⟩, hz₁⟩, exact calc x • a = z : subtype.mk.inj (hz₁ ⟨x • a, mem_orbit _ _⟩) ... = a : (subtype.mk.inj (hz₁ ⟨a, mem_orbit_self _⟩)).symm } end lemma card_modeq_card_fixed_points [fintype α] [fintype G] [fintype (fixed_points G α)] (p : ℕ) {n : ℕ} [hp : fact p.prime] (h : card G = p ^ n) : card α ≡ card (fixed_points G α) [MOD p] := calc card α = card (Σ y : quotient (orbit_rel G α), {x // quotient.mk' x = y}) : card_congr (sigma_preimage_equiv (@quotient.mk' _ (orbit_rel G α))).symm ... = ∑ a : quotient (orbit_rel G α), card {x // quotient.mk' x = a} : card_sigma _ ... ≡ ∑ a : fixed_points G α, 1 [MOD p] : begin rw [←zmod.eq_iff_modeq_nat p, nat.cast_sum, nat.cast_sum], refine eq.symm (sum_bij_ne_zero (λ a _ _, quotient.mk' a.1) (λ _ _ _, mem_univ _) (λ a₁ a₂ _ _ _ _ h, subtype.eq ((mem_fixed_points' α).1 a₂.2 a₁.1 (quotient.exact' h))) (λ b, _) (λ a ha _, by rw [← mem_fixed_points_iff_card_orbit_eq_one.1 a.2]; simp only [quotient.eq']; congr)), { refine quotient.induction_on' b (λ b _ hb, _), have : card (orbit G b) ∣ p ^ n, { rw [← h, fintype.card_congr (orbit_equiv_quotient_stabilizer G b)], exact card_quotient_dvd_card _ }, rcases (nat.dvd_prime_pow hp.1).1 this with ⟨k, _, hk⟩, have hb' :¬ p ^ 1 ∣ p ^ k, { rw [pow_one, ← hk, ← nat.modeq.modeq_zero_iff, ← zmod.eq_iff_modeq_nat, nat.cast_zero, ← ne.def], exact eq.mpr (by simp only [quotient.eq']; congr) hb }, have : k = 0 := nat.le_zero_iff.1 (nat.le_of_lt_succ (lt_of_not_ge (mt (pow_dvd_pow p) hb'))), refine ⟨⟨b, mem_fixed_points_iff_card_orbit_eq_one.2 $ by rw [hk, this, pow_zero]⟩, mem_univ _, _, rfl⟩, rw [nat.cast_one], exact one_ne_zero } end ... = _ : by simp; refl end mul_action lemma quotient_group.card_preimage_mk [fintype G] (s : subgroup G) (t : set (quotient s)) : fintype.card (quotient_group.mk ⁻¹' t) = fintype.card s * fintype.card t := by rw [← fintype.card_prod, fintype.card_congr (preimage_mk_equiv_subgroup_times_set _ _)] namespace sylow /-- Given a vector `v` of length `n`, make a vector of length `n+1` whose product is `1`, by consing the the inverse of the product of `v`. -/ def mk_vector_prod_eq_one (n : ℕ) (v : vector G n) : vector G (n+1) := v.to_list.prod⁻¹ ::ᵥ v lemma mk_vector_prod_eq_one_injective (n : ℕ) : injective (@mk_vector_prod_eq_one G _ n) := λ ⟨v, _⟩ ⟨w, _⟩ h, subtype.eq (show v = w, by injection h with h; injection h) /-- The type of vectors with terms from `G`, length `n`, and product equal to `1:G`. -/ def vectors_prod_eq_one (G : Type*) [group G] (n : ℕ) : set (vector G n) := {v | v.to_list.prod = 1} lemma mem_vectors_prod_eq_one {n : ℕ} (v : vector G n) : v ∈ vectors_prod_eq_one G n ↔ v.to_list.prod = 1 := iff.rfl lemma mem_vectors_prod_eq_one_iff {n : ℕ} (v : vector G (n + 1)) : v ∈ vectors_prod_eq_one G (n + 1) ↔ v ∈ set.range (@mk_vector_prod_eq_one G _ n) := ⟨λ (h : v.to_list.prod = 1), ⟨v.tail, begin unfold mk_vector_prod_eq_one, conv {to_rhs, rw ← vector.cons_head_tail v}, suffices : (v.tail.to_list.prod)⁻¹ = v.head, { rw this }, rw [← mul_left_inj v.tail.to_list.prod, inv_mul_self, ← list.prod_cons, ← vector.to_list_cons, vector.cons_head_tail, h] end⟩, λ ⟨w, hw⟩, by rw [mem_vectors_prod_eq_one, ← hw, mk_vector_prod_eq_one, vector.to_list_cons, list.prod_cons, inv_mul_self]⟩ /-- The rotation action of `zmod n` (viewed as multiplicative group) on `vectors_prod_eq_one G n`, where `G` is a multiplicative group. -/ def rotate_vectors_prod_eq_one (G : Type*) [group G] (n : ℕ) (m : multiplicative (zmod n)) (v : vectors_prod_eq_one G n) : vectors_prod_eq_one G n := ⟨⟨v.1.to_list.rotate m.val, by simp⟩, prod_rotate_eq_one_of_prod_eq_one v.2 _⟩ instance rotate_vectors_prod_eq_one.mul_action (n : ℕ) [fact (0 < n)] : mul_action (multiplicative (zmod n)) (vectors_prod_eq_one G n) := { smul := (rotate_vectors_prod_eq_one G n), one_smul := begin intro v, apply subtype.eq, apply vector.eq _ _, show rotate _ (0 : zmod n).val = _, rw zmod.val_zero, exact rotate_zero v.1.to_list end, mul_smul := λ a b ⟨⟨v, hv₁⟩, hv₂⟩, subtype.eq $ vector.eq _ _ $ show v.rotate ((a + b : zmod n).val) = list.rotate (list.rotate v (b.val)) (a.val), by rw [zmod.val_add, rotate_rotate, ← rotate_mod _ (b.val + a.val), add_comm, hv₁] } lemma one_mem_vectors_prod_eq_one (n : ℕ) : vector.repeat (1 : G) n ∈ vectors_prod_eq_one G n := by simp [vector.repeat, vectors_prod_eq_one] lemma one_mem_fixed_points_rotate (n : ℕ) [fact (0 < n)] : (⟨vector.repeat (1 : G) n, one_mem_vectors_prod_eq_one n⟩ : vectors_prod_eq_one G n) ∈ fixed_points (multiplicative (zmod n)) (vectors_prod_eq_one G n) := λ m, subtype.eq $ vector.eq _ _ $ rotate_eq_self_iff_eq_repeat.2 ⟨(1 : G), show list.repeat (1 : G) n = list.repeat 1 (list.repeat (1 : G) n).length, by simp⟩ _ /-- **Cauchy's theorem** -/ lemma exists_prime_order_of_dvd_card [fintype G] (p : ℕ) [hp : fact p.prime] (hdvd : p ∣ card G) : ∃ x : G, order_of x = p := let n : ℕ+ := ⟨p - 1, nat.sub_pos_of_lt hp.1.one_lt⟩ in have hn : p = n + 1 := nat.succ_sub hp.1.pos, have hcard : card (vectors_prod_eq_one G (n + 1)) = card G ^ (n : ℕ), by rw [set.ext mem_vectors_prod_eq_one_iff, set.card_range_of_injective (mk_vector_prod_eq_one_injective _), card_vector], have hzmod : fintype.card (multiplicative (zmod p)) = p ^ 1, by { rw pow_one p, exact zmod.card p }, have hmodeq : _ = _ := @mul_action.card_modeq_card_fixed_points (multiplicative (zmod p)) (vectors_prod_eq_one G p) _ _ _ _ _ _ 1 hp hzmod, have hdvdcard : p ∣ fintype.card (vectors_prod_eq_one G (n + 1)) := calc p ∣ card G ^ 1 : by rwa pow_one ... ∣ card G ^ (n : ℕ) : pow_dvd_pow _ n.2 ... = card (vectors_prod_eq_one G (n + 1)) : hcard.symm, have hdvdcard₂ : p ∣ card (fixed_points (multiplicative (zmod p)) (vectors_prod_eq_one G p)), by { rw nat.dvd_iff_mod_eq_zero at hdvdcard ⊢, rwa [← hn, hmodeq] at hdvdcard }, have hcard_pos : 0 < card (fixed_points (multiplicative (zmod p)) (vectors_prod_eq_one G p)) := fintype.card_pos_iff.2 ⟨⟨⟨vector.repeat 1 p, one_mem_vectors_prod_eq_one _⟩, one_mem_fixed_points_rotate _⟩⟩, have hlt : 1 < card (fixed_points (multiplicative (zmod p)) (vectors_prod_eq_one G p)) := calc (1 : ℕ) < p : hp.1.one_lt ... ≤ _ : nat.le_of_dvd hcard_pos hdvdcard₂, let ⟨⟨⟨⟨x, hx₁⟩, hx₂⟩, hx₃⟩, hx₄⟩ := fintype.exists_ne_of_one_lt_card hlt ⟨_, one_mem_fixed_points_rotate p⟩ in have hx : x ≠ list.repeat (1 : G) p, from λ h, by simpa [h, vector.repeat] using hx₄, have ∃ a, x = list.repeat a x.length := by exactI rotate_eq_self_iff_eq_repeat.1 (λ n, have list.rotate x (n : zmod p).val = x := subtype.mk.inj (subtype.mk.inj (hx₃ (n : zmod p))), by rwa [zmod.val_nat_cast, ← hx₁, rotate_mod] at this), let ⟨a, ha⟩ := this in ⟨a, have hx1 : x.prod = 1 := hx₂, have ha1: a ≠ 1, from λ h, hx (ha.symm ▸ h ▸ hx₁ ▸ rfl), have a ^ p = 1, by rwa [ha, list.prod_repeat, hx₁] at hx1, (hp.1.2 _ (order_of_dvd_of_pow_eq_one this)).resolve_left (λ h, ha1 (order_of_eq_one_iff.1 h))⟩ open subgroup submonoid is_group_hom mul_action lemma mem_fixed_points_mul_left_cosets_iff_mem_normalizer {H : subgroup G} [fintype ((H : set G) : Type u)] {x : G} : (x : quotient H) ∈ fixed_points H (quotient H) ↔ x ∈ normalizer H := ⟨λ hx, have ha : ∀ {y : quotient H}, y ∈ orbit H (x : quotient H) → y = x, from λ _, ((mem_fixed_points' _).1 hx _), (inv_mem_iff _).1 (@mem_normalizer_fintype _ _ _ _inst_2 _ (λ n (hn : n ∈ H), have (n⁻¹ * x)⁻¹ * x ∈ H := quotient_group.eq.1 (ha (mem_orbit _ ⟨n⁻¹, H.inv_mem hn⟩)), show _ ∈ H, by {rw [mul_inv_rev, inv_inv] at this, convert this, rw inv_inv} )), λ (hx : ∀ (n : G), n ∈ H ↔ x * n * x⁻¹ ∈ H), (mem_fixed_points' _).2 $ λ y, quotient.induction_on' y $ λ y hy, quotient_group.eq.2 (let ⟨⟨b, hb₁⟩, hb₂⟩ := hy in have hb₂ : (b * x)⁻¹ * y ∈ H := quotient_group.eq.1 hb₂, (inv_mem_iff H).1 $ (hx _).2 $ (mul_mem_cancel_left H (H.inv_mem hb₁)).1 $ by rw hx at hb₂; simpa [mul_inv_rev, mul_assoc] using hb₂)⟩ def fixed_points_mul_left_cosets_equiv_quotient (H : subgroup G) [fintype (H : set G)] : mul_action.fixed_points H (quotient H) ≃ quotient (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H) := @subtype_quotient_equiv_quotient_subtype G (normalizer H : set G) (id _) (id _) (fixed_points _ _) (λ a, (@mem_fixed_points_mul_left_cosets_iff_mem_normalizer _ _ _ _inst_2 _).symm) (by intros; refl) /-- The first of the **Sylow theorems** -/ theorem exists_subgroup_card_pow_prime [fintype G] (p : ℕ) : ∀ {n : ℕ} [hp : fact p.prime] (hdvd : p ^ n ∣ card G), ∃ H : subgroup G, fintype.card H = p ^ n | 0 := λ _ _, ⟨(⊥ : subgroup G), by convert card_bot⟩ | (n+1) := λ hp hdvd, let ⟨H, hH2⟩ := @exists_subgroup_card_pow_prime _ hp (dvd.trans (pow_dvd_pow _ (nat.le_succ _)) hdvd) in let ⟨s, hs⟩ := exists_eq_mul_left_of_dvd hdvd in have hcard : card (quotient H) = s * p := (nat.mul_left_inj (show card H > 0, from fintype.card_pos_iff.2 ⟨⟨1, H.one_mem⟩⟩)).1 (by rwa [← card_eq_card_quotient_mul_card_subgroup H, hH2, hs, pow_succ', mul_assoc, mul_comm p]), have hm : s * p % p = card (quotient (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H)) % p := card_congr (fixed_points_mul_left_cosets_equiv_quotient H) ▸ hcard ▸ @card_modeq_card_fixed_points _ _ _ _ _ _ _ p _ hp hH2, have hm' : p ∣ card (quotient (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H)) := nat.dvd_of_mod_eq_zero (by rwa [nat.mod_eq_zero_of_dvd (dvd_mul_left _ _), eq_comm] at hm), let ⟨x, hx⟩ := @exists_prime_order_of_dvd_card _ (quotient_group.quotient.group _) _ _ hp hm' in have hequiv : H ≃ (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H) := ⟨λ a, ⟨⟨a.1, le_normalizer a.2⟩, a.2⟩, λ a, ⟨a.1.1, a.2⟩, λ ⟨_, _⟩, rfl, λ ⟨⟨_, _⟩, _⟩, rfl⟩, -- begin proof of ∃ H : subgroup G, fintype.card H = p ^ n ⟨subgroup.map ((normalizer H).subtype) (subgroup.comap (quotient_group.mk' (comap H.normalizer.subtype H)) (gpowers x)), begin show card ↥(map H.normalizer.subtype (comap (mk' (comap H.normalizer.subtype H)) (subgroup.gpowers x))) = p ^ (n + 1), suffices : card ↥(subtype.val '' ((subgroup.comap (mk' (comap H.normalizer.subtype H)) (gpowers x)) : set (↥(H.normalizer)))) = p^(n+1), { convert this using 2 }, rw [set.card_image_of_injective (subgroup.comap (mk' (comap H.normalizer.subtype H)) (gpowers x) : set (H.normalizer)) subtype.val_injective, pow_succ', ← hH2, fintype.card_congr hequiv, ← hx, order_eq_card_gpowers, ← fintype.card_prod], exact @fintype.card_congr _ _ (id _) (id _) (preimage_mk_equiv_subgroup_times_set _ _) end⟩ end sylow
2eb1b15767fb31e39f9c40c739d0e87743b7b639
6096e76aa1d83b3f250d2c69eeda5b692d6bd3e2
/src/metric_space_fintype_pi.lean
4801c808413066f2d743cfe1f5b15594a426e38c
[]
no_license
ChrisHughes24/lean-differential-topology
3782f1841e5205f76a122b7e8ceb9c65ace06088
0abdf5a61414459fb0833f39b4d04c3528404454
refs/heads/master
1,584,570,674,323
1,527,526,729,000
1,527,526,729,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,750
lean
import analysis.metric_space variables {α : Type*} {β : Type*} noncomputable theory namespace finset lemma image_const [decidable_eq β] {s : finset α} (h : s ≠ ∅) (b : β) : s.image (λa, b) = singleton b := ext.2 $ assume b', by simp [exists_mem_of_ne_empty h, eq_comm] @[simp] theorem max_singleton' [decidable_linear_order α] {a : α} : finset.max (singleton a) = some a := max_singleton section Max open option variables [decidable_linear_order β] [inhabited β] {s : finset α} {f : α → β} def maxi [decidable_linear_order β] [inhabited β] (s : finset α) (f : α → β) : β := (s.image f).max.iget @[simp] lemma maxi_empty : (∅ : finset α).maxi f = default β := rfl lemma maxi_mem (f : α → β) (h : s ≠ ∅) : s.maxi f ∈ s.image f := let ⟨a, ha⟩ := exists_mem_of_ne_empty h in mem_of_max $ (iget_mem $ is_some_iff_exists.2 $ max_of_mem (mem_image_of_mem f ha)) lemma maxi_le {b : β} (hf : ∀a∈s, f a ≤ b) (hd : s = ∅ → default β ≤ b) : s.maxi f ≤ b := classical.by_cases (assume h : s = ∅, by simp * at * ) (assume h : s ≠ ∅, let ⟨a, ha, eq⟩ := mem_image.1 $ maxi_mem f h in eq ▸ hf a ha) lemma le_maxi {a : α} (h : a ∈ s) : f a ≤ s.maxi f := le_max_of_mem (mem_image_of_mem f h) (iget_mem $ is_some_iff_exists.2 $ max_of_mem (mem_image_of_mem f h)) lemma le_maxi_of_forall {b : β} (hb : ∀a∈s, b ≤ f a) (hd : s = ∅ → b ≤ default β) : b ≤ s.maxi f := classical.by_cases (assume h : s = ∅, by simp * at * ) (assume h : s ≠ ∅, let ⟨a, ha, eq⟩ := mem_image.1 $ maxi_mem f h in eq ▸ hb a ha) @[simp] lemma maxi_const {b : β} (h : s = ∅ → b = default β) : s.maxi (λa, b) = b := classical.by_cases (assume h : s = ∅, by simp * at * ) (assume h, by simp [maxi, image_const h]) end Max end finset @[simp] lemma real.default_eq : default ℝ = 0 := rfl namespace metric_space open finset instance fintype_function {α : β → Type*} [fintype β] [∀b, metric_space (α b)] : metric_space (Πb, α b) := { dist := λf g, maxi univ (λb, _root_.dist (f b) (g b)), dist_self := assume f, by simp, dist_comm := assume f g, by congr; funext b; exact dist_comm _ _, dist_triangle := assume f g h, maxi_le (assume b hb, calc dist (f b) (h b) ≤ dist (f b) (g b) + dist (g b) (h b) : dist_triangle _ _ _ ... ≤ maxi univ (λb, _root_.dist (f b) (g b)) + maxi univ (λb, _root_.dist (g b) (h b)) : add_le_add (le_maxi hb) (le_maxi hb)) (by simp [le_refl] {contextual := tt}), eq_of_dist_eq_zero := assume f g eq0, funext $ assume b, dist_le_zero.1 $ eq0 ▸ show dist (f b) (g b) ≤ maxi univ (λb, dist (f b) (g b)), from le_maxi (mem_univ b) } end metric_space
9bdeaa5fd88c6925f4036258d0864b7b8c279775
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/linarith/verification.lean
6b26bb480b1635e15ca0bf23356d2a02e8d0927c
[]
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
894
lean
/- Copyright (c) 2020 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.linarith.elimination import Mathlib.tactic.linarith.parsing import Mathlib.PostPort namespace Mathlib /-! # Deriving a proof of false `linarith` uses an untrusted oracle to produce a certificate of unsatisfiability. It needs to do some proof reconstruction work to turn this into a proof term. This file implements the reconstruction. ## Main declarations The public facing declaration in this file is `prove_false_by_linarith`. -/ namespace linarith /-! ### Auxiliary functions for assembling proofs -/ /-- `mul_expr n e` creates a `pexpr` representing `n*e`. When elaborated, the coefficient will be a native numeral of the same type as `e`. -/
f64972f5bcc28dd79370a0a9779f36de425a5037
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/388.lean
e69ca59c19ae4d4cd5c14156fe09b8d2f0640708
[ "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
524
lean
inductive trans_gen {α} (r : α → α → Prop) (a : α) : α → Prop | single {b} : r a b → trans_gen b | tail {b c} : trans_gen b → r b c → trans_gen c def uncurry {α β γ} (f : α → β → γ) (p : α × β) : γ := f p.fst p.snd def curry {α β γ} (f : α × β → γ) (a : α) (b : β) : γ := f (a, b) def foo {α : Type} {r : α × α → Prop} {x : α × α} (h : uncurry (trans_gen (curry r)) x) : true := begin cases h, case tail : a b c { trivial }, case single { trivial } end
c05908dec04c069bcc4b2f55eb284da52418115b
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/category/BoolRing.lean
9ec49984dc885ea2b90822db62fdcae683f9c896
[ "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,519
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import algebra.category.Ring.basic import algebra.ring.boolean_ring import order.category.BoolAlg /-! # The category of Boolean rings > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines `BoolRing`, the category of Boolean rings. ## TODO Finish the equivalence with `BoolAlg`. -/ universes u open category_theory order /-- The category of Boolean rings. -/ def BoolRing := bundled boolean_ring namespace BoolRing instance : has_coe_to_sort BoolRing Type* := bundled.has_coe_to_sort instance (X : BoolRing) : boolean_ring X := X.str /-- Construct a bundled `BoolRing` from a `boolean_ring`. -/ def of (α : Type*) [boolean_ring α] : BoolRing := bundled.of α @[simp] lemma coe_of (α : Type*) [boolean_ring α] : ↥(of α) = α := rfl instance : inhabited BoolRing := ⟨of punit⟩ instance : bundled_hom.parent_projection @boolean_ring.to_comm_ring := ⟨⟩ attribute [derive [large_category, concrete_category]] BoolRing @[simps] instance has_forget_to_CommRing : has_forget₂ BoolRing CommRing := bundled_hom.forget₂ _ _ /-- Constructs an isomorphism of Boolean rings from a ring isomorphism between them. -/ @[simps] def iso.mk {α β : BoolRing.{u}} (e : α ≃+* β) : α ≅ β := { hom := e, inv := e.symm, hom_inv_id' := by { ext, exact e.symm_apply_apply _ }, inv_hom_id' := by { ext, exact e.apply_symm_apply _ } } end BoolRing /-! ### Equivalence between `BoolAlg` and `BoolRing` -/ @[simps] instance BoolRing.has_forget_to_BoolAlg : has_forget₂ BoolRing BoolAlg := { forget₂ := { obj := λ X, BoolAlg.of (as_boolalg X), map := λ X Y, ring_hom.as_boolalg } } @[simps] instance BoolAlg.has_forget_to_BoolRing : has_forget₂ BoolAlg BoolRing := { forget₂ := { obj := λ X, BoolRing.of (as_boolring X), map := λ X Y, bounded_lattice_hom.as_boolring } } /-- The equivalence between Boolean rings and Boolean algebras. This is actually an isomorphism. -/ @[simps functor inverse] def BoolRing_equiv_BoolAlg : BoolRing ≌ BoolAlg := equivalence.mk (forget₂ BoolRing BoolAlg) (forget₂ BoolAlg BoolRing) (nat_iso.of_components (λ X, BoolRing.iso.mk $ (ring_equiv.as_boolring_as_boolalg X).symm) $ λ X Y f, rfl) (nat_iso.of_components (λ X, BoolAlg.iso.mk $ order_iso.as_boolalg_as_boolring X) $ λ X Y f, rfl)
9290c490ff721852fe11b2f185eaf092f8017393
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/measure_theory/indicator_function.lean
ff2904472f9cc72988bb05649d0451e70f12589e
[ "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,663
lean
/- Copyright (c) 2020 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou -/ import data.indicator_function import measure_theory.measure_space import analysis.normed_space.basic /-! # Indicator function Properties of indicator functions. ## Tags indicator, characteristic -/ noncomputable theory open_locale classical open set measure_theory filter universes u v variables {α : Type u} {β : Type v} section has_zero variables [has_zero β] {s t : set α} {f g : α → β} {a : α} lemma indicator_congr_ae [measure_space α] (h : ∀ₘ a, a ∈ s → f a = g a) : ∀ₘ a, indicator s f a = indicator s g a := begin filter_upwards [h], simp only [mem_set_of_eq, indicator], assume a ha, split_ifs with h₁, { exact ha h₁ }, refl end lemma indicator_congr_of_set [measure_space α] (h : ∀ₘ a, a ∈ s ↔ a ∈ t) : ∀ₘ a, indicator s f a = indicator t f a := begin filter_upwards [h], simp only [mem_set_of_eq, indicator], assume a ha, split_ifs with h₁ h₂ h₂, { refl }, { have := ha.1 h₁, contradiction }, { have := ha.2 h₂, contradiction }, refl end end has_zero section has_add variables [add_monoid β] {s t : set α} {f g : α → β} {a : α} lemma indicator_union_ae [measure_space α] {β : Type*} [add_monoid β] (h : ∀ₘ a, a ∉ s ∩ t) (f : α → β) : ∀ₘ a, indicator (s ∪ t) f a = indicator s f a + indicator t f a := begin filter_upwards [h], simp only [mem_set_of_eq], assume a ha, exact indicator_union_of_not_mem_inter ha _ end end has_add section norm variables [normed_group β] {s t : set α} {f g : α → β} {a : α} lemma norm_indicator_le_of_subset (h : s ⊆ t) (f : α → β) (a : α) : ∥indicator s f a∥ ≤ ∥indicator t f a∥ := begin simp only [indicator], split_ifs with h₁ h₂, { refl }, { exact absurd (h h₁) h₂ }, { simp only [norm_zero, norm_nonneg] }, refl end lemma norm_indicator_le_norm_self (f : α → β) (a : α) : ∥indicator s f a∥ ≤ ∥f a∥ := by { convert norm_indicator_le_of_subset (subset_univ s) f a, rw indicator_univ } lemma norm_indicator_eq_indicator_norm (f : α → β) (a : α) : ∥indicator s f a∥ = indicator s (λa, ∥f a∥) a := by { simp only [indicator], split_ifs, { refl }, rw norm_zero } lemma indicator_norm_le_norm_self (f : α → β) (a : α) : indicator s (λa, ∥f a∥) a ≤ ∥f a∥ := by { rw ← norm_indicator_eq_indicator_norm, exact norm_indicator_le_norm_self _ _ } end norm section order variables [has_zero β] [preorder β] {s t : set α} {f g : α → β} {a : α} lemma indicator_le_indicator_ae [measure_space α] (h : ∀ₘ a, a ∈ s → f a ≤ g a) : ∀ₘ a, indicator s f a ≤ indicator s g a := begin filter_upwards [h], simp only [mem_set_of_eq, indicator], assume a h, split_ifs with ha, { exact h ha }, refl end end order section tendsto variables {ι : Type*} [semilattice_sup ι] [has_zero β] lemma tendsto_indicator_of_monotone [nonempty ι] (s : ι → set α) (hs : monotone s) (f : α → β) (a : α) : tendsto (λi, indicator (s i) f a) at_top (pure $ indicator (Union s) f a) := begin by_cases h : ∃i, a ∈ s i, { simp only [tendsto_pure, mem_at_top_sets, mem_set_of_eq], rcases h with ⟨i, hi⟩, use i, assume n hn, rw [indicator_of_mem (hs hn hi) _, indicator_of_mem ((subset_Union _ _) hi) _] }, { rw [not_exists] at h, have : (λi, indicator (s i) f a) = λi, 0 := funext (λi, indicator_of_not_mem (h i) _), rw this, have : indicator (Union s) f a = 0, { apply indicator_of_not_mem, simpa only [not_exists, mem_Union] }, rw this, exact tendsto_const_pure } end lemma tendsto_indicator_of_antimono [nonempty ι] (s : ι → set α) (hs : ∀i j, i ≤ j → s j ⊆ s i) (f : α → β) (a : α) : tendsto (λi, indicator (s i) f a) at_top (pure $ indicator (Inter s) f a) := begin by_cases h : ∃i, a ∉ s i, { simp only [tendsto_pure, mem_at_top_sets, mem_set_of_eq], rcases h with ⟨i, hi⟩, use i, assume n hn, rw [indicator_of_not_mem _ _, indicator_of_not_mem _ _], { simp only [mem_Inter, not_forall], exact ⟨i, hi⟩ }, { assume h, have := hs i _ hn h, contradiction } }, { simp only [not_exists, not_not_mem] at h, have : (λi, indicator (s i) f a) = λi, f a := funext (λi, indicator_of_mem (h i) _), rw this, have : indicator (Inter s) f a = f a, { apply indicator_of_mem, simpa only [mem_Inter] }, rw this, exact tendsto_const_pure } end lemma tendsto_indicator_bUnion_finset (s : ι → set α) (f : α → β) (a : α) : tendsto (λ (n : finset ι), indicator (⋃i∈n, s i) f a) at_top (pure $ indicator (Union s) f a) := begin by_cases h : ∃i, a ∈ s i, { simp only [mem_at_top_sets, tendsto_pure, mem_set_of_eq, ge_iff_le, finset.le_iff_subset], rcases h with ⟨i, hi⟩, use {i}, assume n hn, replace hn : i ∈ n := hn (finset.mem_singleton_self _), rw [indicator_of_mem, indicator_of_mem], { rw [mem_Union], use i, assumption }, { rw [mem_Union], use i, rw [mem_Union], use hn, assumption } }, { rw [not_exists] at h, have : (λ (n : finset ι), indicator (⋃ (i : ι) (H : i ∈ n), s i) f a) = λi, 0, { funext, rw indicator_of_not_mem, simp only [not_exists, exists_prop, mem_Union, not_and], intros, apply h }, rw this, have : indicator (Union s) f a = 0, { apply indicator_of_not_mem, simpa only [not_exists, mem_Union] }, rw this, exact tendsto_const_pure } end end tendsto
7badc0710f1c242bc305b88f4716850783794dae
46125763b4dbf50619e8846a1371029346f4c3db
/src/ring_theory/unique_factorization_domain.lean
7f267a53c721660cbf8cf4a80a27a7036753ac89
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
19,713
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jens Wagemaker Theory of unique factorization domains. @TODO: setup the complete lattice structure on `factor_set`. -/ import algebra.gcd_domain variables {α : Type*} local infix ` ~ᵤ ` : 50 := associated /-- Unique factorization domains. In a unique factorization domain each element (except zero) is uniquely represented as a multiset of irreducible factors. Uniqueness is only up to associated elements. This is equivalent to defining a unique factorization domain as a domain in which each element (except zero) is non-uniquely represented as a multiset of prime factors. This definition is used. To define a UFD using the traditional definition in terms of multisets of irreducible factors, use the definition `of_unique_irreducible_factorization` -/ class unique_factorization_domain (α : Type*) [integral_domain α] := (factors : α → multiset α) (factors_prod : ∀{a : α}, a ≠ 0 → (factors a).prod ~ᵤ a) (prime_factors : ∀{a : α}, a ≠ 0 → ∀x∈factors a, prime x) namespace unique_factorization_domain variables [integral_domain α] [unique_factorization_domain α] @[elab_as_eliminator] lemma induction_on_prime {P : α → Prop} (a : α) (h₁ : P 0) (h₂ : ∀ x : α, is_unit x → P x) (h₃ : ∀ a p : α, a ≠ 0 → prime p → P a → P (p * a)) : P a := by haveI := classical.dec_eq α; exact if ha0 : a = 0 then ha0.symm ▸ h₁ else @multiset.induction_on _ (λ s : multiset α, ∀ (a : α), a ≠ 0 → s.prod ~ᵤ a → (∀ p ∈ s, prime p) → P a) (factors a) (λ _ _ h _, h₂ _ ((is_unit_iff_of_associated h.symm).2 is_unit_one)) (λ p s ih a ha0 ⟨u, hu⟩ hsp, have ha : a = (p * u) * s.prod, by simp [hu.symm, mul_comm, mul_assoc], have hs0 : s.prod ≠ 0, from λ _ : s.prod = 0, by simp * at *, ha.symm ▸ h₃ _ _ hs0 (prime_of_associated ⟨u, rfl⟩ (hsp p (multiset.mem_cons_self _ _))) (ih _ hs0 (by refl) (λ p hp, hsp p (multiset.mem_cons.2 (or.inr hp))))) _ ha0 (factors_prod ha0) (prime_factors ha0) lemma factors_irreducible {a : α} (ha : irreducible a) : ∃ p, a ~ᵤ p ∧ factors a = p :: 0 := by haveI := classical.dec_eq α; exact multiset.induction_on (factors a) (λ h, (ha.1 (associated_one_iff_is_unit.1 h.symm)).elim) (λ p s _ hp hs, let ⟨u, hu⟩ := hp in ⟨p, have hs0 : s = 0, from classical.by_contradiction (λ hs0, let ⟨q, hq⟩ := multiset.exists_mem_of_ne_zero hs0 in (hs q (by simp [hq])).2.1 $ (ha.2 ((p * u) * (s.erase q).prod) _ (by rw [mul_right_comm _ _ q, mul_assoc, ← multiset.prod_cons, multiset.cons_erase hq]; simp [hu.symm, mul_comm, mul_assoc])).resolve_left $ mt is_unit_of_mul_is_unit_left $ mt is_unit_of_mul_is_unit_left (hs p (multiset.mem_cons_self _ _)).2.1), ⟨associated.symm (by clear _let_match; simp * at *), hs0 ▸ rfl⟩⟩) (factors_prod ha.ne_zero) (prime_factors ha.ne_zero) lemma irreducible_iff_prime {p : α} : irreducible p ↔ prime p := by letI := classical.dec_eq α; exact if hp0 : p = 0 then by simp [hp0] else ⟨λ h, let ⟨q, hq⟩ := factors_irreducible h in have prime q, from hq.2 ▸ prime_factors hp0 _ (by simp [hq.2]), suffices prime (factors p).prod, from prime_of_associated (factors_prod hp0) this, hq.2.symm ▸ by simp [this], irreducible_of_prime⟩ lemma irreducible_factors : ∀{a : α}, a ≠ 0 → ∀x∈factors a, irreducible x := by simp only [irreducible_iff_prime]; exact @prime_factors _ _ _ lemma unique : ∀{f g : multiset α}, (∀x∈f, irreducible x) → (∀x∈g, irreducible x) → f.prod ~ᵤ g.prod → multiset.rel associated f g := by haveI := classical.dec_eq α; exact λ f, multiset.induction_on f (λ g _ hg h, multiset.rel_zero_left.2 $ multiset.eq_zero_of_forall_not_mem (λ x hx, have is_unit g.prod, by simpa [associated_one_iff_is_unit] using h.symm, (hg x hx).1 (is_unit_iff_dvd_one.2 (dvd.trans (multiset.dvd_prod hx) (is_unit_iff_dvd_one.1 this))))) (λ p f ih g hf hg hfg, let ⟨b, hbg, hb⟩ := exists_associated_mem_of_dvd_prod (irreducible_iff_prime.1 (hf p (by simp))) (λ q hq, irreducible_iff_prime.1 (hg _ hq)) $ (dvd_iff_dvd_of_rel_right hfg).1 (show p ∣ (p :: f).prod, by simp) in begin rw ← multiset.cons_erase hbg, exact multiset.rel.cons hb (ih (λ q hq, hf _ (by simp [hq])) (λ q (hq : q ∈ g.erase b), hg q (multiset.mem_of_mem_erase hq)) (associated_mul_left_cancel (by rwa [← multiset.prod_cons, ← multiset.prod_cons, multiset.cons_erase hbg]) hb (hf p (by simp)).ne_zero)) end) end unique_factorization_domain structure unique_irreducible_factorization (α : Type*) [integral_domain α] := (factors : α → multiset α) (factors_prod : ∀{a : α}, a ≠ 0 → (factors a).prod ~ᵤ a) (irreducible_factors : ∀{a : α}, a ≠ 0 → ∀x∈factors a, irreducible x) (unique : ∀{f g : multiset α}, (∀x∈f, irreducible x) → (∀x∈g, irreducible x) → f.prod ~ᵤ g.prod → multiset.rel associated f g) namespace unique_factorization_domain open unique_factorization_domain associated lattice variables [integral_domain α] [unique_factorization_domain α] [decidable_eq (associates α)] lemma exists_mem_factors_of_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) : p ∣ a → ∃ q ∈ factors a, p ~ᵤ q := λ ⟨b, hb⟩, have hb0 : b ≠ 0, from λ hb0, by simp * at *, have multiset.rel associated (p :: factors b) (factors a), from unique (λ x hx, (multiset.mem_cons.1 hx).elim (λ h, h.symm ▸ hp) (irreducible_factors hb0 _)) (irreducible_factors ha0) (associated.symm $ calc multiset.prod (factors a) ~ᵤ a : factors_prod ha0 ... = p * b : hb ... ~ᵤ multiset.prod (p :: factors b) : by rw multiset.prod_cons; exact associated_mul_mul (associated.refl _) (associated.symm (factors_prod hb0))), multiset.exists_mem_of_rel_of_mem this (by simp) def of_unique_irreducible_factorization {α : Type*} [integral_domain α] (o : unique_irreducible_factorization α) : unique_factorization_domain α := by letI := classical.dec_eq α; exact { prime_factors := λ a h p (hpa : p ∈ o.factors a), have hpi : irreducible p, from o.irreducible_factors h _ hpa, ⟨hpi.ne_zero, hpi.1, λ a b ⟨x, hx⟩, if hab0 : a * b = 0 then (eq_zero_or_eq_zero_of_mul_eq_zero hab0).elim (λ ha0, by simp [ha0]) (λ hb0, by simp [hb0]) else have hx0 : x ≠ 0, from λ hx0, by simp * at *, have ha0 : a ≠ 0, from ne_zero_of_mul_ne_zero_right hab0, have hb0 : b ≠ 0, from ne_zero_of_mul_ne_zero_left hab0, have multiset.rel associated (p :: o.factors x) (o.factors a + o.factors b), from o.unique (λ i hi, (multiset.mem_cons.1 hi).elim (λ hip, hip.symm ▸ hpi) (o.irreducible_factors hx0 _)) (show ∀ x ∈ o.factors a + o.factors b, irreducible x, from λ x hx, (multiset.mem_add.1 hx).elim (o.irreducible_factors (ne_zero_of_mul_ne_zero_right hab0) _) (o.irreducible_factors (ne_zero_of_mul_ne_zero_left hab0) _)) $ calc multiset.prod (p :: o.factors x) ~ᵤ a * b : by rw [hx, multiset.prod_cons]; exact associated_mul_mul (by refl) (o.factors_prod hx0) ... ~ᵤ (o.factors a).prod * (o.factors b).prod : associated_mul_mul (o.factors_prod ha0).symm (o.factors_prod hb0).symm ... = _ : by rw multiset.prod_add, let ⟨q, hqf, hq⟩ := multiset.exists_mem_of_rel_of_mem this (multiset.mem_cons_self p _) in (multiset.mem_add.1 hqf).elim (λ hqa, or.inl $ (dvd_iff_dvd_of_rel_left hq).2 $ (dvd_iff_dvd_of_rel_right (o.factors_prod ha0)).1 (multiset.dvd_prod hqa)) (λ hqb, or.inr $ (dvd_iff_dvd_of_rel_left hq).2 $ (dvd_iff_dvd_of_rel_right (o.factors_prod hb0)).1 (multiset.dvd_prod hqb))⟩, ..o } end unique_factorization_domain namespace associates open unique_factorization_domain associated lattice variables [integral_domain α] [unique_factorization_domain α] [decidable_eq (associates α)] /-- `factor_set α` representation elements of unique factorization domain as multisets. `multiset α` produced by `factors` are only unique up to associated elements, while the multisets in `factor_set α` are unqiue by equality and restricted to irreducible elements. This gives us a representation of each element as a unique multisets (or the added ⊤ for 0), which has a complete lattice struture. Infimum is the greatest common divisor and supremum is the least common multiple. -/ @[reducible] def {u} factor_set (α : Type u) [integral_domain α] [unique_factorization_domain α] : Type u := with_top (multiset { a : associates α // irreducible a }) local attribute [instance] associated.setoid theorem unique' {p q : multiset (associates α)} : (∀a∈p, irreducible a) → (∀a∈q, irreducible a) → p.prod = q.prod → p = q := begin apply multiset.induction_on_multiset_quot p, apply multiset.induction_on_multiset_quot q, assume s t hs ht eq, refine multiset.map_mk_eq_map_mk_of_rel (unique_factorization_domain.unique _ _ _), { exact assume a ha, ((irreducible_mk_iff _).1 $ hs _ $ multiset.mem_map_of_mem _ ha) }, { exact assume a ha, ((irreducible_mk_iff _).1 $ ht _ $ multiset.mem_map_of_mem _ ha) }, simpa [quot_mk_eq_mk, prod_mk, mk_eq_mk_iff_associated] using eq end private theorem forall_map_mk_factors_irreducible (x : α) (hx : x ≠ 0) : ∀(a : associates α), a ∈ multiset.map associates.mk (factors x) → irreducible a := begin assume a ha, rcases multiset.mem_map.1 ha with ⟨c, hc, rfl⟩, exact (irreducible_mk_iff c).2 (irreducible_factors hx _ hc) end theorem prod_le_prod_iff_le {p q : multiset (associates α)} (hp : ∀a∈p, irreducible a) (hq : ∀a∈q, irreducible a) : p.prod ≤ q.prod ↔ p ≤ q := iff.intro begin rintros ⟨⟨c⟩, eq⟩, have : c ≠ 0, from (mt mk_eq_zero_iff_eq_zero.2 $ assume (hc : quot.mk setoid.r c = 0), have (0 : associates α) ∈ q, from prod_eq_zero_iff.1 $ eq ▸ hc.symm ▸ mul_zero _, not_irreducible_zero ((irreducible_mk_iff 0).1 $ hq _ this)), have : associates.mk (factors c).prod = quot.mk setoid.r c, from mk_eq_mk_iff_associated.2 (factors_prod this), refine le_iff_exists_add.2 ⟨(factors c).map associates.mk, unique' hq _ _⟩, { assume x hx, rcases multiset.mem_add.1 hx with h | h, exact hp x h, exact forall_map_mk_factors_irreducible c ‹c ≠ 0› _ h }, { simp [multiset.prod_add, prod_mk, *] at * } end prod_le_prod @[simp, nolint simp_nf] -- takes a crazy amount of time to simplify lhs theorem factor_set.coe_add {a b : multiset { a : associates α // irreducible a }} : (↑a + ↑b : factor_set α) = ↑(a + b) := with_top.coe_add lemma factor_set.sup_add_inf_eq_add : ∀(a b : factor_set α), a ⊔ b + a ⊓ b = a + b | none b := show ⊤ ⊔ b + ⊤ ⊓ b = ⊤ + b, by simp | a none := show a ⊔ ⊤ + a ⊓ ⊤ = a + ⊤, by simp | (some a) (some b) := show (a : factor_set α) ⊔ b + a ⊓ b = a + b, from begin rw [← with_top.coe_sup, ← with_top.coe_inf, ← with_top.coe_add, ← with_top.coe_add, with_top.coe_eq_coe], exact multiset.union_add_inter _ _ end def factors' (a : α) (ha : a ≠ 0) : multiset { a : associates α // irreducible a } := (factors a).pmap (λa ha, ⟨associates.mk a, (irreducible_mk_iff _).2 ha⟩) (irreducible_factors $ ha) @[simp] theorem map_subtype_val_factors' {a : α} (ha : a ≠ 0) : (factors' a ha).map subtype.val = (factors a).map associates.mk := by simp [factors', multiset.map_pmap, multiset.pmap_eq_map] theorem factors'_cong {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) (h : a ~ᵤ b) : factors' a ha = factors' b hb := have multiset.rel associated (factors a) (factors b), from unique (irreducible_factors ha) (irreducible_factors hb) ((factors_prod ha).trans $ h.trans $ (factors_prod hb).symm), by simpa [(multiset.map_eq_map subtype.val_injective).symm, rel_associated_iff_map_eq_map.symm] def factors (a : associates α) : factor_set α := begin refine (if h : a = 0 then ⊤ else quotient.hrec_on a (λx h, some $ factors' x (mt mk_eq_zero_iff_eq_zero.2 h)) _ h), assume a b hab, apply function.hfunext, { have : a ~ᵤ 0 ↔ b ~ᵤ 0, from iff.intro (assume ha0, hab.symm.trans ha0) (assume hb0, hab.trans hb0), simp [quotient_mk_eq_mk, mk_eq_zero_iff_eq_zero, (associated_zero_iff_eq_zero _).symm, this] }, exact (assume ha hb eq, heq_of_eq $ congr_arg some $ factors'_cong _ _ hab) end @[simp] theorem factors_0 : (0 : associates α).factors = ⊤ := dif_pos rfl @[simp] theorem factors_mk (a : α) (h : a ≠ 0) : (associates.mk a).factors = factors' a h := dif_neg (mt mk_eq_zero_iff_eq_zero.1 h) def factor_set.prod : factor_set α → associates α | none := 0 | (some s) := (s.map subtype.val).prod @[simp] theorem prod_top : (⊤ : factor_set α).prod = 0 := rfl @[simp] theorem prod_coe {s : multiset { a : associates α // irreducible a }} : (s : factor_set α).prod = (s.map subtype.val).prod := rfl theorem prod_factors : ∀(s : factor_set α), s.prod.factors = s | none := by simp [factor_set.prod]; refl | (some s) := begin unfold factor_set.prod, generalize eq_a : (s.map subtype.val).prod = a, rcases a with ⟨a⟩, rw quot_mk_eq_mk at *, have : (s.map subtype.val).prod ≠ 0, from assume ha, let ⟨⟨a, ha⟩, h, eq⟩ := multiset.mem_map.1 (prod_eq_zero_iff.1 ha) in have irreducible (0 : associates α), from eq ▸ ha, not_irreducible_zero ((irreducible_mk_iff _).1 this), have ha : a ≠ 0, by simp [*] at *, suffices : (unique_factorization_domain.factors a).map associates.mk = s.map subtype.val, { rw [factors_mk a ha], apply congr_arg some _, simpa [(multiset.map_eq_map subtype.val_injective).symm] }, refine unique' (forall_map_mk_factors_irreducible _ ha) (assume a ha, let ⟨⟨x, hx⟩, ha, eq⟩ := multiset.mem_map.1 ha in eq ▸ hx) _, rw [prod_mk, eq_a, mk_eq_mk_iff_associated], exact factors_prod ha end theorem factors_prod (a : associates α) : a.factors.prod = a := quotient.induction_on a $ assume a, decidable.by_cases (assume : associates.mk a = 0, by simp [quotient_mk_eq_mk, this]) (assume : associates.mk a ≠ 0, have a ≠ 0, by simp * at *, by simp [this, quotient_mk_eq_mk, prod_mk, mk_eq_mk_iff_associated.2 (factors_prod this)]) theorem eq_of_factors_eq_factors {a b : associates α} (h : a.factors = b.factors) : a = b := have a.factors.prod = b.factors.prod, by rw h, by rwa [factors_prod, factors_prod] at this theorem eq_of_prod_eq_prod {a b : factor_set α} (h : a.prod = b.prod) : a = b := have a.prod.factors = b.prod.factors, by rw h, by rwa [prod_factors, prod_factors] at this @[simp] theorem prod_add : ∀(a b : factor_set α), (a + b).prod = a.prod * b.prod | none b := show (⊤ + b).prod = (⊤:factor_set α).prod * b.prod, by simp | a none := show (a + ⊤).prod = a.prod * (⊤:factor_set α).prod, by simp | (some a) (some b) := show (↑a + ↑b:factor_set α).prod = (↑a:factor_set α).prod * (↑b:factor_set α).prod, by rw [factor_set.coe_add, prod_coe, prod_coe, prod_coe, multiset.map_add, multiset.prod_add] theorem prod_mono : ∀{a b : factor_set α}, a ≤ b → a.prod ≤ b.prod | none b h := have b = ⊤, from top_unique h, by rw [this, prod_top]; exact le_refl _ | a none h := show a.prod ≤ (⊤ : factor_set α).prod, by simp; exact le_top | (some a) (some b) h := prod_le_prod $ multiset.map_le_map $ with_top.coe_le_coe.1 $ h @[simp] theorem factors_mul (a b : associates α) : (a * b).factors = a.factors + b.factors := eq_of_prod_eq_prod $ eq_of_factors_eq_factors $ by rw [prod_add, factors_prod, factors_prod, factors_prod] theorem factors_mono : ∀{a b : associates α}, a ≤ b → a.factors ≤ b.factors | s t ⟨d, rfl⟩ := by rw [factors_mul] ; exact le_add_of_nonneg_right' bot_le theorem factors_le {a b : associates α} : a.factors ≤ b.factors ↔ a ≤ b := iff.intro (assume h, have a.factors.prod ≤ b.factors.prod, from prod_mono h, by rwa [factors_prod, factors_prod] at this) factors_mono theorem prod_le {a b : factor_set α} : a.prod ≤ b.prod ↔ a ≤ b := iff.intro (assume h, have a.prod.factors ≤ b.prod.factors, from factors_mono h, by rwa [prod_factors, prod_factors] at this) prod_mono instance : has_sup (associates α) := ⟨λa b, (a.factors ⊔ b.factors).prod⟩ instance : has_inf (associates α) := ⟨λa b, (a.factors ⊓ b.factors).prod⟩ instance : bounded_lattice (associates α) := { sup := (⊔), inf := (⊓), sup_le := assume a b c hac hbc, factors_prod c ▸ prod_mono (sup_le (factors_mono hac) (factors_mono hbc)), le_sup_left := assume a b, le_trans (le_of_eq (factors_prod a).symm) $ prod_mono $ le_sup_left, le_sup_right := assume a b, le_trans (le_of_eq (factors_prod b).symm) $ prod_mono $ le_sup_right, le_inf := assume a b c hac hbc, factors_prod a ▸ prod_mono (le_inf (factors_mono hac) (factors_mono hbc)), inf_le_left := assume a b, le_trans (prod_mono inf_le_left) (le_of_eq (factors_prod a)), inf_le_right := assume a b, le_trans (prod_mono inf_le_right) (le_of_eq (factors_prod b)), .. associates.partial_order, .. associates.lattice.order_top, .. associates.lattice.order_bot } lemma sup_mul_inf (a b : associates α) : (a ⊔ b) * (a ⊓ b) = a * b := show (a.factors ⊔ b.factors).prod * (a.factors ⊓ b.factors).prod = a * b, begin refine eq_of_factors_eq_factors _, rw [← prod_add, prod_factors, factors_mul, factor_set.sup_add_inf_eq_add] end end associates section open associates unique_factorization_domain lattice /-- `to_gcd_domain` constructs a GCD domain out of a unique factorization domain over a normalization domain. -/ def unique_factorization_domain.to_gcd_domain (α : Type*) [normalization_domain α] [unique_factorization_domain α] [decidable_eq (associates α)] : gcd_domain α := { gcd := λa b, (associates.mk a ⊓ associates.mk b).out, lcm := λa b, (associates.mk a ⊔ associates.mk b).out, gcd_dvd_left := assume a b, (out_dvd_iff a (associates.mk a ⊓ associates.mk b)).2 $ inf_le_left, gcd_dvd_right := assume a b, (out_dvd_iff b (associates.mk a ⊓ associates.mk b)).2 $ inf_le_right, dvd_gcd := assume a b c hac hab, show a ∣ (associates.mk c ⊓ associates.mk b).out, by rw [dvd_out_iff, le_inf_iff, mk_le_mk_iff_dvd_iff, mk_le_mk_iff_dvd_iff]; exact ⟨hac, hab⟩, lcm_zero_left := assume a, show (⊤ ⊔ associates.mk a).out = 0, by simp, lcm_zero_right := assume a, show (associates.mk a ⊔ ⊤).out = 0, by simp, gcd_mul_lcm := assume a b, show (associates.mk a ⊓ associates.mk b).out * (associates.mk a ⊔ associates.mk b).out = normalize (a * b), by rw [← out_mk, ← out_mul, mul_comm, sup_mul_inf]; refl, normalize_gcd := assume a b, by convert normalize_out _, .. ‹normalization_domain α› } end
64a47ff2440ed42d7c2a7f69abe2e71db251db39
82e44445c70db0f03e30d7be725775f122d72f3e
/src/category_theory/preadditive/projective.lean
4745c47d719a1302c853bccc230a98c9ae3458aa
[ "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
6,439
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel, Scott Morrison -/ import algebra.homology.exact import category_theory.types /-! # Projective objects and categories with enough projectives An object `P` is called projective if every morphism out of `P` factors through every epimorphism. A category `C` has enough projectives if every object admits an epimorphism from some projective object. `projective.over X` picks an arbitrary such projective object, and `projective.π X : projective.over X ⟶ X` is the corresponding epimorphism. Given a morphism `f : X ⟶ Y`, `projective.left f` is a projective object over `kernel f`, and `projective.d f : projective.left f ⟶ X` is the morphism `π (kernel f) ≫ kernel.ι f`. -/ noncomputable theory open category_theory open category_theory.limits universes v u namespace category_theory variables {C : Type u} [category.{v} C] /-- An object `P` is called projective if every morphism out of `P` factors through every epimorphism. -/ class projective (P : C) : Prop := (factors : ∀ {E X : C} (f : P ⟶ X) (e : E ⟶ X) [epi e], ∃ f', f' ≫ e = f) section /-- A projective presentation of an object `X` consists of an epimorphism `f : P ⟶ X` from some projective object `P`. -/ @[nolint has_inhabited_instance] structure projective_presentation (X : C) := (P : C) (projective : projective P . tactic.apply_instance) (f : P ⟶ X) (epi : epi f . tactic.apply_instance) variables (C) /-- A category "has enough projectives" if for every object `X` there is a projective object `P` and an epimorphism `P ↠ X`. -/ class enough_projectives : Prop := (presentation : ∀ (X : C), nonempty (projective_presentation X)) end namespace projective /-- An arbitrarily chosen factorisation of a morphism out of a projective object through an epimorphism. -/ def factor_thru {P X E : C} [projective P] (f : P ⟶ X) (e : E ⟶ X) [epi e] : P ⟶ E := (projective.factors f e).some @[simp] lemma factor_thru_comp {P X E : C} [projective P] (f : P ⟶ X) (e : E ⟶ X) [epi e] : factor_thru f e ≫ e = f := (projective.factors f e).some_spec section open_locale zero_object instance zero_projective [has_zero_object C] [has_zero_morphisms C] : projective (0 : C) := { factors := λ E X f e epi, by { use 0, ext, }} end lemma of_iso {P Q : C} (i : P ≅ Q) (hP : projective P) : projective Q := begin fsplit, introsI E X f e e_epi, obtain ⟨f', hf'⟩ := projective.factors (i.hom ≫ f) e, exact ⟨i.inv ≫ f', by simp [hf']⟩ end lemma iso_iff {P Q : C} (i : P ≅ Q) : projective P ↔ projective Q := ⟨of_iso i, of_iso i.symm⟩ /-- The axiom of choice says that every type is a projective object in `Type`. -/ instance (X : Type u) : projective X := { factors := λ E X' f e epi, ⟨λ x, ((epi_iff_surjective _).mp epi (f x)).some, by { ext x, exact ((epi_iff_surjective _).mp epi (f x)).some_spec, }⟩ } instance Type.enough_projectives : enough_projectives (Type u) := { presentation := λ X, ⟨{ P := X, f := 𝟙 X, }⟩, } instance {P Q : C} [has_binary_coproduct P Q] [projective P] [projective Q] : projective (P ⨿ Q) := { factors := λ E X' f e epi, by exactI ⟨coprod.desc (factor_thru (coprod.inl ≫ f) e) (factor_thru (coprod.inr ≫ f) e), by tidy⟩, } instance {β : Type v} (g : β → C) [has_coproduct g] [∀ b, projective (g b)] : projective (∐ g) := { factors := λ E X' f e epi, by exactI ⟨sigma.desc (λ b, factor_thru (sigma.ι g b ≫ f) e), by tidy⟩, } instance {P Q : C} [has_zero_morphisms C] [has_binary_biproduct P Q] [projective P] [projective Q] : projective (P ⊞ Q) := { factors := λ E X' f e epi, by exactI ⟨biprod.desc (factor_thru (biprod.inl ≫ f) e) (factor_thru (biprod.inr ≫ f) e), by tidy⟩, } instance {β : Type v} [decidable_eq β] (g : β → C) [has_zero_morphisms C] [has_biproduct g] [∀ b, projective (g b)] : projective (⨁ g) := { factors := λ E X' f e epi, by exactI ⟨biproduct.desc (λ b, factor_thru (biproduct.ι g b ≫ f) e), by tidy⟩, } section enough_projectives variables [enough_projectives C] /-- `projective.over X` provides an arbitrarily chosen projective object equipped with an epimorphism `projective.π : projective.over X ⟶ X`. -/ def over (X : C) : C := (enough_projectives.presentation X).some.P instance projective_over (X : C) : projective (over X) := (enough_projectives.presentation X).some.projective /-- The epimorphism `projective.π : projective.over X ⟶ X` from the arbitrarily chosen projective object over `X`. -/ def π (X : C) : over X ⟶ X := (enough_projectives.presentation X).some.f instance π_epi (X : C) : epi (π X) := (enough_projectives.presentation X).some.epi section variables [has_zero_morphisms C] {X Y : C} (f : X ⟶ Y) [has_kernel f] /-- When `C` has enough projectives, the object `projective.syzygies f` is an arbitrarily chosen projective object over `kernel f`. -/ @[derive projective] def syzygies : C := over (kernel f) /-- When `C` has enough projectives, `projective.d f : projective.syzygies f ⟶ X` is the composition `π (kernel f) ≫ kernel.ι f`. (When `C` is abelian, we have `exact (projective.d f) f`.) -/ abbreviation d : syzygies f ⟶ X := π (kernel f) ≫ kernel.ι f end end enough_projectives end projective open projective section variables [has_zero_morphisms C] [has_equalizers C] [has_images C] /-- Given a projective object `P` mapping via `h` into the middle object `R` of a pair of exact morphisms `f : Q ⟶ R` and `g : R ⟶ S`, such that `h ≫ g = 0`, there is a lift of `h` to `Q`. -/ def exact.lift {P Q R S : C} [projective P] (h : P ⟶ R) (f : Q ⟶ R) (g : R ⟶ S) [exact f g] (w : h ≫ g = 0) : P ⟶ Q := factor_thru (factor_thru (factor_thru_kernel_subobject g h w) (image_to_kernel f g (by simp))) (factor_thru_image_subobject f) @[simp] lemma exact.lift_comp {P Q R S : C} [projective P] (h : P ⟶ R) (f : Q ⟶ R) (g : R ⟶ S) [exact f g] (w : h ≫ g = 0) : exact.lift h f g w ≫ f = h := begin simp [exact.lift], conv_lhs { congr, skip, rw ← image_subobject_arrow_comp f, }, rw [←category.assoc, factor_thru_comp, ←image_to_kernel_arrow, ←category.assoc, category_theory.projective.factor_thru_comp, factor_thru_kernel_subobject_comp_arrow], end end end category_theory
2308540f1c9e383b3ce51176d1cf9b5607951b91
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/lift.lean
6fa9bdf5ad5e2a58cf9657add0c7ea9d845518c4
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
9,522
lean
/- Copyright (c) 2019 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import tactic.rcases /-! # lift tactic This file defines the `lift` tactic, allowing the user to lift elements from one type to another under a specified condition. ## Tags lift, tactic -/ /-- A class specifying that you can lift elements from `α` to `β` assuming `cond` is true. Used by the tactic `lift`. -/ class can_lift (α β : Sort*) (coe : out_param $ β → α) (cond : out_param $ α → Prop) := (prf : ∀(x : α), cond x → ∃(y : β), coe y = x) instance : can_lift ℤ ℕ coe ((≤) 0) := ⟨λ n hn, ⟨n.nat_abs, int.nat_abs_of_nonneg hn⟩⟩ /-- Enable automatic handling of pi types in `can_lift`. -/ instance pi.can_lift (ι : Sort*) (α β : ι → Sort*) (coe : Π i, β i → α i) (P : Π i, α i → Prop) [Π i : ι, can_lift (α i) (β i) (coe i) (P i)] : can_lift (Π i : ι, α i) (Π i : ι, β i) (λ f i, coe i (f i)) (λ f, ∀ i, P i (f i)) := { prf := λ f hf, ⟨λ i, classical.some (can_lift.prf (f i) (hf i)), funext $ λ i, classical.some_spec (can_lift.prf (f i) (hf i))⟩ } lemma subtype.exists_pi_extension {ι : Sort*} {α : ι → Sort*} [ne : Π i, nonempty (α i)] {p : ι → Prop} (f : Π i : subtype p, α i) : ∃ g : Π i : ι, α i, (λ i : subtype p, g i) = f := begin tactic.classical, refine ⟨λ i, if hi : p i then f ⟨i, hi⟩ else classical.choice (ne i), funext _⟩, rintro ⟨i, hi⟩, exact dif_pos hi end instance pi_subtype.can_lift (ι : Sort*) (α : ι → Sort*) [ne : Π i, nonempty (α i)] (p : ι → Prop) : can_lift (Π i : subtype p, α i) (Π i, α i) (λ f i, f i) (λ _, true) := { prf := λ f _, subtype.exists_pi_extension f } instance pi_subtype.can_lift' (ι : Sort*) (α : Sort*) [ne : nonempty α] (p : ι → Prop) : can_lift (subtype p → α) (ι → α) (λ f i, f i) (λ _, true) := pi_subtype.can_lift ι (λ _, α) p instance subtype.can_lift {α : Sort*} (p : α → Prop) : can_lift α {x // p x} coe p := { prf := λ a ha, ⟨⟨a, ha⟩, rfl⟩ } open tactic namespace tactic /-- Construct the proof of `cond x` in the lift tactic. * `e` is the expression being lifted and `h` is the specified proof of `can_lift.cond e`. * `old_tp` and `new_tp` are the arguments to `can_lift` and `inst` is the `can_lift`-instance. * `s` and `to_unfold` contain the information of the simp set used to simplify. If the proof was specified, we check whether it has the correct type. If it doesn't have the correct type, we display an error message. If the proof was not specified, we create assert it as a local constant. (The name of this local constant doesn't matter, since `lift` will remove it from the context.) -/ meta def get_lift_prf (h : option pexpr) (e P : expr) : tactic (expr × bool) := do let expected_prf_ty := P.app e, expected_prf_ty ← simp_lemmas.mk.dsimplify [] expected_prf_ty {fail_if_unchanged := ff}, match h with | some h := do e ← decorate_error "lift tactic failed." (i_to_expr ``((%%h : %%expected_prf_ty))), return (e, tt) | none := do prf_nm ← get_unused_name, prf ← assert prf_nm expected_prf_ty, swap, return (prf, ff) end /-- Lift the expression `p` to the type `t`, with proof obligation given by `h`. The list `n` is used for the two newly generated names, and to specify whether `h` should remain in the local context. See the doc string of `tactic.interactive.lift` for more information. -/ meta def lift (p : pexpr) (t : pexpr) (h : option pexpr) (n : list name) : tactic unit := do propositional_goal <|> fail "lift tactic failed. Tactic is only applicable when the target is a proposition.", e ← i_to_expr p, old_tp ← infer_type e, new_tp ← i_to_expr ``(%%t : Sort*), coe ← i_to_expr (``(%%new_tp → %%old_tp)) >>= mk_meta_var, P ← i_to_expr (``(%%old_tp → Prop)) >>= mk_meta_var, inst_type ← mk_app ``can_lift [old_tp, new_tp, coe, P], inst ← mk_instance inst_type <|> pformat!"Failed to find a lift from {old_tp} to {new_tp}. Provide an instance of\n {inst_type}" >>= fail, inst ← instantiate_mvars inst, coe ← instantiate_mvars coe, P ← instantiate_mvars P, (prf_cond, b) ← get_lift_prf h e P, let prf_nm := if prf_cond.is_local_constant then some prf_cond.local_pp_name else none, /- We use mk_mapp to apply `can_lift.prf` to all but one argument, and then just use expr.app for the last argument. For some reason we get an error when applying mk_mapp it to all arguments. -/ prf_ex0 ← mk_mapp `can_lift.prf [old_tp, new_tp, coe, P, inst, e], let prf_ex := prf_ex0 prf_cond, /- Find the name of the new variable -/ new_nm ← if n ≠ [] then return n.head else if e.is_local_constant then return e.local_pp_name else get_unused_name, /- Find the name of the proof of the equation -/ eq_nm ← if hn : 1 < n.length then return (n.nth_le 1 hn) else if e.is_local_constant then return `rfl else get_unused_name `h, /- We add the proof of the existential statement to the context -/ temp_nm ← get_unused_name, temp_e ← note temp_nm none prf_ex, dsimp_hyp temp_e none [] { fail_if_unchanged := ff }, /- We case on the existential. We use `rcases` because `eq_nm` could be `rfl`. -/ rcases none (pexpr.of_expr temp_e) $ rcases_patt.tuple ([new_nm, eq_nm].map rcases_patt.one), /- If the lifted variable is not a local constant, try to rewrite it away using the new equality. -/ when (¬ e.is_local_constant) (get_local eq_nm >>= λ e, interactive.rw ⟨[⟨⟨0, 0⟩, tt, (pexpr.of_expr e)⟩], none⟩ interactive.loc.wildcard), /- If the proof `prf_cond` is a local constant, remove it from the context, unless `n` specifies to keep it. -/ if h_prf_nm : prf_nm.is_some ∧ n.nth 2 ≠ prf_nm then get_local (option.get h_prf_nm.1) >>= clear else skip, if b then skip else swap setup_tactic_parser /-- Parses an optional token "using" followed by a trailing `pexpr`. -/ meta def using_texpr := (tk "using" *> texpr)? /-- Parses a token "to" followed by a trailing `pexpr`. -/ meta def to_texpr := (tk "to" *> texpr) namespace interactive /-- Lift an expression to another type. * Usage: `'lift' expr 'to' expr ('using' expr)? ('with' id (id id?)?)?`. * If `n : ℤ` and `hn : n ≥ 0` then the tactic `lift n to ℕ using hn` creates a new constant of type `ℕ`, also named `n` and replaces all occurrences of the old variable `(n : ℤ)` with `↑n` (where `n` in the new variable). It will remove `n` and `hn` from the context. + So for example the tactic `lift n to ℕ using hn` transforms the goal `n : ℤ, hn : n ≥ 0, h : P n ⊢ n = 3` to `n : ℕ, h : P ↑n ⊢ ↑n = 3` (here `P` is some term of type `ℤ → Prop`). * The argument `using hn` is optional, the tactic `lift n to ℕ` does the same, but also creates a new subgoal that `n ≥ 0` (where `n` is the old variable). This subgoal will be placed at the top of the goal list. + So for example the tactic `lift n to ℕ` transforms the goal `n : ℤ, h : P n ⊢ n = 3` to two goals `n : ℤ, h : P n ⊢ n ≥ 0` and `n : ℕ, h : P ↑n ⊢ ↑n = 3`. * You can also use `lift n to ℕ using e` where `e` is any expression of type `n ≥ 0`. * Use `lift n to ℕ with k` to specify the name of the new variable. * Use `lift n to ℕ with k hk` to also specify the name of the equality `↑k = n`. In this case, `n` will remain in the context. You can use `rfl` for the name of `hk` to substitute `n` away (i.e. the default behavior). * You can also use `lift e to ℕ with k hk` where `e` is any expression of type `ℤ`. In this case, the `hk` will always stay in the context, but it will be used to rewrite `e` in all hypotheses and the target. + So for example the tactic `lift n + 3 to ℕ using hn with k hk` transforms the goal `n : ℤ, hn : n + 3 ≥ 0, h : P (n + 3) ⊢ n + 3 = 2 * n` to the goal `n : ℤ, k : ℕ, hk : ↑k = n + 3, h : P ↑k ⊢ ↑k = 2 * n`. * The tactic `lift n to ℕ using h` will remove `h` from the context. If you want to keep it, specify it again as the third argument to `with`, like this: `lift n to ℕ using h with n rfl h`. * More generally, this can lift an expression from `α` to `β` assuming that there is an instance of `can_lift α β`. In this case the proof obligation is specified by `can_lift.cond`. * Given an instance `can_lift β γ`, it can also lift `α → β` to `α → γ`; more generally, given `β : Π a : α, Type*`, `γ : Π a : α, Type*`, and `[Π a : α, can_lift (β a) (γ a)]`, it automatically generates an instance `can_lift (Π a, β a) (Π a, γ a)`. `lift` is in some sense dual to the `zify` tactic. `lift (z : ℤ) to ℕ` will change the type of an integer `z` (in the supertype) to `ℕ` (the subtype), given a proof that `z ≥ 0`; propositions concerning `z` will still be over `ℤ`. `zify` changes propositions about `ℕ` (the subtype) to propositions about `ℤ` (the supertype), without changing the type of any variable. -/ meta def lift (p : parse texpr) (t : parse to_texpr) (h : parse using_texpr) (n : parse with_ident_list) : tactic unit := tactic.lift p t h n add_tactic_doc { name := "lift", category := doc_category.tactic, decl_names := [`tactic.interactive.lift], tags := ["coercions"] } end interactive end tactic
d8b2e4cf6b9e5bc9ba70d424bfe32d24ddaa7b03
8b9f17008684d796c8022dab552e42f0cb6fb347
/library/data/list/basic.lean
c8a526c38fc97a00870f94cffbd2d41bb4832fff
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,911
lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: data.list.basic Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura Basic properties of lists. -/ import logic tools.helper_tactics data.nat.basic algebra.function open eq.ops helper_tactics nat prod function option inductive list (T : Type) : Type := | nil {} : list T | cons : T → list T → list T namespace list notation h :: t := cons h t notation `[` l:(foldr `,` (h t, cons h t) nil `]`) := l variable {T : Type} /- append -/ definition append : list T → list T → list T | [] l := l | (h :: s) t := h :: (append s t) notation l₁ ++ l₂ := append l₁ l₂ theorem append_nil_left (t : list T) : [] ++ t = t theorem append_cons (x : T) (s t : list T) : (x::s) ++ t = x::(s ++ t) theorem append_nil_right : ∀ (t : list T), t ++ [] = t | [] := rfl | (a :: l) := calc (a :: l) ++ [] = a :: (l ++ []) : rfl ... = a :: l : append_nil_right l theorem append.assoc : ∀ (s t u : list T), s ++ t ++ u = s ++ (t ++ u) | [] t u := rfl | (a :: l) t u := show a :: (l ++ t ++ u) = (a :: l) ++ (t ++ u), by rewrite (append.assoc l t u) /- length -/ definition length : list T → nat | [] := 0 | (a :: l) := length l + 1 theorem length_nil : length (@nil T) = 0 theorem length_cons (x : T) (t : list T) : length (x::t) = length t + 1 theorem length_append : ∀ (s t : list T), length (s ++ t) = length s + length t | [] t := calc length ([] ++ t) = length t : rfl ... = length [] + length t : zero_add | (a :: s) t := calc length (a :: s ++ t) = length (s ++ t) + 1 : rfl ... = length s + length t + 1 : length_append ... = (length s + 1) + length t : succ_add ... = length (a :: s) + length t : rfl theorem eq_nil_of_length_eq_zero : ∀ {l : list T}, length l = 0 → l = [] | [] H := rfl | (a::s) H := nat.no_confusion H -- add_rewrite length_nil length_cons /- concat -/ definition concat : Π (x : T), list T → list T | a [] := [a] | a (b :: l) := b :: concat a l theorem concat_nil (x : T) : concat x [] = [x] theorem concat_cons (x y : T) (l : list T) : concat x (y::l) = y::(concat x l) theorem concat_eq_append (a : T) : ∀ (l : list T), concat a l = l ++ [a] | [] := rfl | (b :: l) := show b :: (concat a l) = (b :: l) ++ (a :: []), by rewrite concat_eq_append -- add_rewrite append_nil append_cons /- reverse -/ definition reverse : list T → list T | [] := [] | (a :: l) := concat a (reverse l) theorem reverse_nil : reverse (@nil T) = [] theorem reverse_cons (x : T) (l : list T) : reverse (x::l) = concat x (reverse l) theorem reverse_singleton (x : T) : reverse [x] = [x] theorem reverse_append : ∀ (s t : list T), reverse (s ++ t) = (reverse t) ++ (reverse s) | [] t2 := calc reverse ([] ++ t2) = reverse t2 : rfl ... = (reverse t2) ++ [] : append_nil_right ... = (reverse t2) ++ (reverse []) : by rewrite reverse_nil | (a2 :: s2) t2 := calc reverse ((a2 :: s2) ++ t2) = concat a2 (reverse (s2 ++ t2)) : rfl ... = concat a2 (reverse t2 ++ reverse s2) : reverse_append ... = (reverse t2 ++ reverse s2) ++ [a2] : concat_eq_append ... = reverse t2 ++ (reverse s2 ++ [a2]) : append.assoc ... = reverse t2 ++ concat a2 (reverse s2) : concat_eq_append ... = reverse t2 ++ reverse (a2 :: s2) : rfl theorem reverse_reverse : ∀ (l : list T), reverse (reverse l) = l | [] := rfl | (a :: l) := calc reverse (reverse (a :: l)) = reverse (concat a (reverse l)) : rfl ... = reverse (reverse l ++ [a]) : concat_eq_append ... = reverse [a] ++ reverse (reverse l) : reverse_append ... = reverse [a] ++ l : reverse_reverse ... = a :: l : rfl theorem concat_eq_reverse_cons (x : T) (l : list T) : concat x l = reverse (x :: reverse l) := calc concat x l = concat x (reverse (reverse l)) : reverse_reverse ... = reverse (x :: reverse l) : rfl /- head and tail -/ definition head [h : inhabited T] : list T → T | [] := arbitrary T | (a :: l) := a theorem head_cons [h : inhabited T] (a : T) (l : list T) : head (a::l) = a theorem head_append [h : inhabited T] (t : list T) : ∀ {s : list T}, s ≠ [] → head (s ++ t) = head s | [] H := absurd rfl H | (a :: s) H := show head (a :: (s ++ t)) = head (a :: s), by rewrite head_cons definition tail : list T → list T | [] := [] | (a :: l) := l theorem tail_nil : tail (@nil T) = [] theorem tail_cons (a : T) (l : list T) : tail (a::l) = l theorem cons_head_tail [h : inhabited T] {l : list T} : l ≠ [] → (head l)::(tail l) = l := list.cases_on l (assume H : [] ≠ [], absurd rfl H) (take x l, assume H : x::l ≠ [], rfl) /- list membership -/ definition mem : T → list T → Prop | a [] := false | a (b :: l) := a = b ∨ mem a l notation e ∈ s := mem e s notation e ∉ s := ¬ e ∈ s theorem mem_nil (x : T) : x ∈ [] ↔ false := iff.rfl theorem not_mem_nil (x : T) : x ∉ [] := iff.mp !mem_nil theorem mem_cons (x : T) (l : list T) : x ∈ x :: l := or.inl rfl theorem mem_cons_of_mem (y : T) {x : T} {l : list T} : x ∈ l → x ∈ y :: l := assume H, or.inr H theorem mem_cons_iff (x y : T) (l : list T) : x ∈ y::l ↔ (x = y ∨ x ∈ l) := iff.rfl theorem eq_or_mem_of_mem_cons {x y : T} {l : list T} : x ∈ y::l → x = y ∨ x ∈ l := assume h, h theorem mem_singleton {x a : T} : x ∈ [a] → x = a := assume h : x ∈ [a], or.elim (eq_or_mem_of_mem_cons h) (λ xeqa : x = a, xeqa) (λ xinn : x ∈ [], absurd xinn !not_mem_nil) theorem mem_of_mem_cons_of_mem {a b : T} {l : list T} : a ∈ b::l → b ∈ l → a ∈ l := assume ainbl binl, or.elim (eq_or_mem_of_mem_cons ainbl) (λ aeqb : a = b, by rewrite [aeqb]; exact binl) (λ ainl : a ∈ l, ainl) theorem mem_or_mem_of_mem_append {x : T} {s t : list T} : x ∈ s ++ t → x ∈ s ∨ x ∈ t := list.induction_on s or.inr (take y s, assume IH : x ∈ s ++ t → x ∈ s ∨ x ∈ t, assume H1 : x ∈ y::s ++ t, have H2 : x = y ∨ x ∈ s ++ t, from H1, have H3 : x = y ∨ x ∈ s ∨ x ∈ t, from or_of_or_of_imp_right H2 IH, iff.elim_right or.assoc H3) theorem mem_append_of_mem_or_mem {x : T} {s t : list T} : x ∈ s ∨ x ∈ t → x ∈ s ++ t := list.induction_on s (take H, or.elim H false.elim (assume H, H)) (take y s, assume IH : x ∈ s ∨ x ∈ t → x ∈ s ++ t, assume H : x ∈ y::s ∨ x ∈ t, or.elim H (assume H1, or.elim (eq_or_mem_of_mem_cons H1) (take H2 : x = y, or.inl H2) (take H2 : x ∈ s, or.inr (IH (or.inl H2)))) (assume H1 : x ∈ t, or.inr (IH (or.inr H1)))) theorem mem_append_iff (x : T) (s t : list T) : x ∈ s ++ t ↔ x ∈ s ∨ x ∈ t := iff.intro mem_or_mem_of_mem_append mem_append_of_mem_or_mem theorem not_mem_of_not_mem_append_left {x : T} {s t : list T} : x ∉ s++t → x ∉ s := λ nxinst xins, absurd (mem_append_of_mem_or_mem (or.inl xins)) nxinst theorem not_mem_of_not_mem_append_right {x : T} {s t : list T} : x ∉ s++t → x ∉ t := λ nxinst xint, absurd (mem_append_of_mem_or_mem (or.inr xint)) nxinst theorem not_mem_append {x : T} {s t : list T} : x ∉ s → x ∉ t → x ∉ s++t := λ nxins nxint xinst, or.elim (mem_or_mem_of_mem_append xinst) (λ xins, absurd xins nxins) (λ xint, absurd xint nxint) local attribute mem [reducible] local attribute append [reducible] theorem mem_split {x : T} {l : list T} : x ∈ l → ∃s t : list T, l = s ++ (x::t) := list.induction_on l (take H : x ∈ [], false.elim (iff.elim_left !mem_nil H)) (take y l, assume IH : x ∈ l → ∃s t : list T, l = s ++ (x::t), assume H : x ∈ y::l, or.elim (eq_or_mem_of_mem_cons H) (assume H1 : x = y, exists.intro [] (!exists.intro (H1 ▸ rfl))) (assume H1 : x ∈ l, obtain s (H2 : ∃t : list T, l = s ++ (x::t)), from IH H1, obtain t (H3 : l = s ++ (x::t)), from H2, have H4 : y :: l = (y::s) ++ (x::t), from H3 ▸ rfl, !exists.intro (!exists.intro H4))) theorem mem_append_left {a : T} {l₁ : list T} (l₂ : list T) : a ∈ l₁ → a ∈ l₁ ++ l₂ := assume ainl₁, mem_append_of_mem_or_mem (or.inl ainl₁) theorem mem_append_right {a : T} (l₁ : list T) {l₂ : list T} : a ∈ l₂ → a ∈ l₁ ++ l₂ := assume ainl₂, mem_append_of_mem_or_mem (or.inr ainl₂) definition decidable_mem [instance] [H : decidable_eq T] (x : T) (l : list T) : decidable (x ∈ l) := list.rec_on l (decidable.inr (not_of_iff_false !mem_nil)) (take (h : T) (l : list T) (iH : decidable (x ∈ l)), show decidable (x ∈ h::l), from decidable.rec_on iH (assume Hp : x ∈ l, decidable.rec_on (H x h) (assume Heq : x = h, decidable.inl (or.inl Heq)) (assume Hne : x ≠ h, decidable.inl (or.inr Hp))) (assume Hn : ¬x ∈ l, decidable.rec_on (H x h) (assume Heq : x = h, decidable.inl (or.inl Heq)) (assume Hne : x ≠ h, have H1 : ¬(x = h ∨ x ∈ l), from assume H2 : x = h ∨ x ∈ l, or.elim H2 (assume Heq, absurd Heq Hne) (assume Hp, absurd Hp Hn), have H2 : ¬x ∈ h::l, from iff.elim_right (not_iff_not_of_iff !mem_cons_iff) H1, decidable.inr H2))) theorem mem_of_ne_of_mem {x y : T} {l : list T} (H₁ : x ≠ y) (H₂ : x ∈ y :: l) : x ∈ l := or.elim (eq_or_mem_of_mem_cons H₂) (λe, absurd e H₁) (λr, r) theorem not_eq_of_not_mem {a b : T} {l : list T} : a ∉ b::l → a ≠ b := assume nin aeqb, absurd (or.inl aeqb) nin theorem not_mem_of_not_mem {a b : T} {l : list T} : a ∉ b::l → a ∉ l := assume nin nainl, absurd (or.inr nainl) nin definition sublist (l₁ l₂ : list T) := ∀ ⦃a : T⦄, a ∈ l₁ → a ∈ l₂ infix `⊆`:50 := sublist theorem nil_sub (l : list T) : [] ⊆ l := λ b i, false.elim (iff.mp (mem_nil b) i) theorem sub.refl (l : list T) : l ⊆ l := λ b i, i theorem sub.trans {l₁ l₂ l₃ : list T} (H₁ : l₁ ⊆ l₂) (H₂ : l₂ ⊆ l₃) : l₁ ⊆ l₃ := λ b i, H₂ (H₁ i) theorem sub_cons (a : T) (l : list T) : l ⊆ a::l := λ b i, or.inr i theorem sub_of_cons_sub {a : T} {l₁ l₂ : list T} : a::l₁ ⊆ l₂ → l₁ ⊆ l₂ := λ s b i, s b (mem_cons_of_mem _ i) theorem cons_sub_cons {l₁ l₂ : list T} (a : T) (s : l₁ ⊆ l₂) : (a::l₁) ⊆ (a::l₂) := λ b Hin, or.elim (eq_or_mem_of_mem_cons Hin) (λ e : b = a, or.inl e) (λ i : b ∈ l₁, or.inr (s i)) theorem sub_append_left (l₁ l₂ : list T) : l₁ ⊆ l₁++l₂ := λ b i, iff.mp' (mem_append_iff b l₁ l₂) (or.inl i) theorem sub_append_right (l₁ l₂ : list T) : l₂ ⊆ l₁++l₂ := λ b i, iff.mp' (mem_append_iff b l₁ l₂) (or.inr i) theorem sub_cons_of_sub (a : T) {l₁ l₂ : list T} : l₁ ⊆ l₂ → l₁ ⊆ (a::l₂) := λ (s : l₁ ⊆ l₂) (x : T) (i : x ∈ l₁), or.inr (s i) theorem sub_app_of_sub_left (l l₁ l₂ : list T) : l ⊆ l₁ → l ⊆ l₁++l₂ := λ (s : l ⊆ l₁) (x : T) (xinl : x ∈ l), have xinl₁ : x ∈ l₁, from s xinl, mem_append_of_mem_or_mem (or.inl xinl₁) theorem sub_app_of_sub_right (l l₁ l₂ : list T) : l ⊆ l₂ → l ⊆ l₁++l₂ := λ (s : l ⊆ l₂) (x : T) (xinl : x ∈ l), have xinl₁ : x ∈ l₂, from s xinl, mem_append_of_mem_or_mem (or.inr xinl₁) theorem cons_sub_of_sub_of_mem {a : T} {l m : list T} : a ∈ m → l ⊆ m → a::l ⊆ m := λ (ainm : a ∈ m) (lsubm : l ⊆ m) (x : T) (xinal : x ∈ a::l), or.elim (eq_or_mem_of_mem_cons xinal) (assume xeqa : x = a, eq.rec_on (eq.symm xeqa) ainm) (assume xinl : x ∈ l, lsubm xinl) theorem app_sub_of_sub_of_sub {l₁ l₂ l : list T} : l₁ ⊆ l → l₂ ⊆ l → l₁++l₂ ⊆ l := λ (l₁subl : l₁ ⊆ l) (l₂subl : l₂ ⊆ l) (x : T) (xinl₁l₂ : x ∈ l₁++l₂), or.elim (mem_or_mem_of_mem_append xinl₁l₂) (λ xinl₁ : x ∈ l₁, l₁subl xinl₁) (λ xinl₂ : x ∈ l₂, l₂subl xinl₂) /- find -/ section variable [H : decidable_eq T] include H definition find : T → list T → nat | a [] := 0 | a (b :: l) := if a = b then 0 else succ (find a l) theorem find_nil (x : T) : find x [] = 0 theorem find_cons (x y : T) (l : list T) : find x (y::l) = if x = y then 0 else succ (find x l) theorem find_cons_of_eq {x y : T} (l : list T) : x = y → find x (y::l) = 0 := assume e, if_pos e theorem find_cons_of_ne {x y : T} (l : list T) : x ≠ y → find x (y::l) = succ (find x l) := assume n, if_neg n theorem find.not_mem {l : list T} {x : T} : ¬x ∈ l → find x l = length l := list.rec_on l (assume P₁ : ¬x ∈ [], _) (take y l, assume iH : ¬x ∈ l → find x l = length l, assume P₁ : ¬x ∈ y::l, have P₂ : ¬(x = y ∨ x ∈ l), from iff.elim_right (not_iff_not_of_iff !mem_cons_iff) P₁, have P₃ : ¬x = y ∧ ¬x ∈ l, from (iff.elim_left not_or_iff_not_and_not P₂), calc find x (y::l) = if x = y then 0 else succ (find x l) : !find_cons ... = succ (find x l) : if_neg (and.elim_left P₃) ... = succ (length l) : {iH (and.elim_right P₃)} ... = length (y::l) : !length_cons⁻¹) end /- nth element -/ section nth definition nth : list T → nat → option T | [] n := none | (a :: l) 0 := some a | (a :: l) (n+1) := nth l n theorem nth_zero (a : T) (l : list T) : nth (a :: l) 0 = some a theorem nth_succ (a : T) (l : list T) (n : nat) : nth (a::l) (succ n) = nth l n open decidable theorem find_nth [h : decidable_eq T] {a : T} : ∀ {l}, a ∈ l → nth l (find a l) = some a | [] ain := absurd ain !not_mem_nil | (b::l) ainbl := by_cases (λ aeqb : a = b, by rewrite [find_cons_of_eq _ aeqb, nth_zero, aeqb]) (λ aneb : a ≠ b, or.elim (eq_or_mem_of_mem_cons ainbl) (λ aeqb : a = b, absurd aeqb aneb) (λ ainl : a ∈ l, by rewrite [find_cons_of_ne _ aneb, nth_succ, find_nth ainl])) definition inth [h : inhabited T] (l : list T) (n : nat) : T := match nth l n with | some a := a | none := arbitrary T end theorem inth_zero [h : inhabited T] (a : T) (l : list T) : inth (a :: l) 0 = a theorem inth_succ [h : inhabited T] (a : T) (l : list T) (n : nat) : inth (a::l) (n+1) = inth l n end nth open decidable definition has_decidable_eq {A : Type} [H : decidable_eq A] : ∀ l₁ l₂ : list A, decidable (l₁ = l₂) | [] [] := inl rfl | [] (b::l₂) := inr (λ H, list.no_confusion H) | (a::l₁) [] := inr (λ H, list.no_confusion H) | (a::l₁) (b::l₂) := match H a b with | inl Hab := match has_decidable_eq l₁ l₂ with | inl He := inl (eq.rec_on Hab (eq.rec_on He rfl)) | inr Hn := inr (λ H, list.no_confusion H (λ Hab Ht, absurd Ht Hn)) end | inr Hnab := inr (λ H, list.no_confusion H (λ Hab Ht, absurd Hab Hnab)) end /- quasiequal a l l' means that l' is exactly l, with a added once somewhere -/ section qeq variable {A : Type} inductive qeq (a : A) : list A → list A → Prop := | qhead : ∀ l, qeq a l (a::l) | qcons : ∀ (b : A) {l l' : list A}, qeq a l l' → qeq a (b::l) (b::l') open qeq notation l' `≈`:50 a `|` l:50 := qeq a l l' theorem qeq_app : ∀ (l₁ : list A) (a : A) (l₂ : list A), l₁++(a::l₂) ≈ a|l₁++l₂ | [] a l₂ := qhead a l₂ | (x::xs) a l₂ := qcons x (qeq_app xs a l₂) theorem mem_head_of_qeq {a : A} {l₁ l₂ : list A} : l₁≈a|l₂ → a ∈ l₁ := take q, qeq.induction_on q (λ l, !mem_cons) (λ b l l' q r, or.inr r) theorem mem_tail_of_qeq {a : A} {l₁ l₂ : list A} : l₁≈a|l₂ → ∀ x, x ∈ l₂ → x ∈ l₁ := take q, qeq.induction_on q (λ l x i, or.inr i) (λ b l l' q r x xinbl, or.elim (eq_or_mem_of_mem_cons xinbl) (λ xeqb : x = b, xeqb ▸ mem_cons x l') (λ xinl : x ∈ l, or.inr (r x xinl))) theorem mem_cons_of_qeq {a : A} {l₁ l₂ : list A} : l₁≈a|l₂ → ∀ x, x ∈ l₁ → x ∈ a::l₂ := take q, qeq.induction_on q (λ l x i, i) (λ b l l' q r x xinbl', or.elim (eq_or_mem_of_mem_cons xinbl') (λ xeqb : x = b, xeqb ▸ or.inr (mem_cons x l)) (λ xinl' : x ∈ l', or.elim (eq_or_mem_of_mem_cons (r x xinl')) (λ xeqa : x = a, xeqa ▸ mem_cons x (b::l)) (λ xinl : x ∈ l, or.inr (or.inr xinl)))) theorem length_eq_of_qeq {a : A} {l₁ l₂ : list A} : l₁≈a|l₂ → length l₁ = succ (length l₂) := take q, qeq.induction_on q (λ l, rfl) (λ b l l' q r, by rewrite [*length_cons, r]) theorem qeq_of_mem {a : A} {l : list A} : a ∈ l → (∃l', l≈a|l') := list.induction_on l (λ h : a ∈ nil, absurd h (not_mem_nil a)) (λ x xs r ainxxs, or.elim (eq_or_mem_of_mem_cons ainxxs) (λ aeqx : a = x, assert aux : ∃ l, x::xs≈x|l, from exists.intro xs (qhead x xs), by rewrite aeqx; exact aux) (λ ainxs : a ∈ xs, have ex : ∃l', xs ≈ a|l', from r ainxs, obtain (l' : list A) (q : xs ≈ a|l'), from ex, have q₂ : x::xs ≈ a | x::l', from qcons x q, exists.intro (x::l') q₂)) theorem qeq_split {a : A} {l l' : list A} : l'≈a|l → ∃l₁ l₂, l = l₁++l₂ ∧ l' = l₁++(a::l₂) := take q, qeq.induction_on q (λ t, have aux : t = []++t ∧ a::t = []++(a::t), from and.intro rfl rfl, exists.intro [] (exists.intro t aux)) (λ b t t' q r, obtain (l₁ l₂ : list A) (h : t = l₁++l₂ ∧ t' = l₁++(a::l₂)), from r, have aux : b::t = (b::l₁)++l₂ ∧ b::t' = (b::l₁)++(a::l₂), begin rewrite [and.elim_right h, and.elim_left h], exact (and.intro rfl rfl) end, exists.intro (b::l₁) (exists.intro l₂ aux)) theorem sub_of_mem_of_sub_of_qeq {a : A} {l : list A} {u v : list A} : a ∉ l → a::l ⊆ v → v≈a|u → l ⊆ u := λ (nainl : a ∉ l) (s : a::l ⊆ v) (q : v≈a|u) (x : A) (xinl : x ∈ l), have xinv : x ∈ v, from s (or.inr xinl), have xinau : x ∈ a::u, from mem_cons_of_qeq q x xinv, or.elim (eq_or_mem_of_mem_cons xinau) (λ xeqa : x = a, absurd (xeqa ▸ xinl) nainl) (λ xinu : x ∈ u, xinu) end qeq end list attribute list.has_decidable_eq [instance] attribute list.decidable_mem [instance]
f21abd6010209538c6bef618f28c50f79f32e47c
500f65bb93c499cd35c3254d894d762208cae042
/src/meta/expr.lean
10f84b2802649425b1b391509cf18a36aeba1632
[ "Apache-2.0" ]
permissive
PatrickMassot/mathlib
c39dc0ff18bbde42f1c93a1642f6e429adad538c
45df75b3c9da159fe3192fa7f769dfbec0bd6bda
refs/heads/master
1,623,168,646,390
1,566,940,765,000
1,566,940,765,000
115,220,590
0
1
null
1,514,061,524,000
1,514,061,524,000
null
UTF-8
Lean
false
false
11,813
lean
/- Copyright (c) 2019 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek, Robert Y. Lewis -/ /-! # Additional operations on expr and related types This file defines basic operations on the types expr, name, declaration, level, environment. This file is mostly for non-tactics. Tactics should generally be placed in `tactic.core`. ## Tags expr, name, declaration, level, environment, meta, metaprogramming, tactic -/ namespace name /-- Find the largest prefix `n` of a `name` such that `f n ≠ none`, then replace this prefix with the value of `f n`. -/ def map_prefix (f : name → option name) : name → name | anonymous := anonymous | (mk_string s n') := (f (mk_string s n')).get_or_else (mk_string s $ map_prefix n') | (mk_numeral d n') := (f (mk_numeral d n')).get_or_else (mk_numeral d $ map_prefix n') /-- If `nm` is a simple name (having only one string component) starting with `_`, then `deinternalize_field nm` removes the underscore. Otherwise, it does nothing. -/ meta def deinternalize_field : name → name | (mk_string s name.anonymous) := let i := s.mk_iterator in if i.curr = '_' then i.next.next_to_string else s | n := n /-- `get_nth_prefix nm n` removes the last `n` components from `nm` -/ meta def get_nth_prefix : name → ℕ → name | nm 0 := nm | nm (n + 1) := get_nth_prefix nm.get_prefix n /-- Auxilliary definition for `pop_nth_prefix` -/ private meta def pop_nth_prefix_aux : name → ℕ → name × ℕ | anonymous n := (anonymous, 1) | nm n := let (pfx, height) := pop_nth_prefix_aux nm.get_prefix n in if height ≤ n then (anonymous, height + 1) else (nm.update_prefix pfx, height + 1) /-- Pops the top `n` prefixes from the given name. -/ meta def pop_nth_prefix (nm : name) (n : ℕ) : name := prod.fst $ pop_nth_prefix_aux nm n /-- Pop the prefix of a name -/ meta def pop_prefix (n : name) : name := pop_nth_prefix n 1 /-- Auxilliary definition for `from_components` -/ private def from_components_aux : name → list string → name | n [] := n | n (s :: rest) := from_components_aux (name.mk_string s n) rest /-- Build a name from components. For example `from_components ["foo","bar"]` becomes ``` `foo.bar``` -/ def from_components : list string → name := from_components_aux name.anonymous /-- `name`s can contain numeral pieces, which are not legal names when typed/passed directly to the parser. We turn an arbitrary name into a legal identifier name by turning the numbers to strings. -/ meta def sanitize_name : name → name | name.anonymous := name.anonymous | (name.mk_string s p) := name.mk_string s $ sanitize_name p | (name.mk_numeral s p) := name.mk_string sformat!"n{s}" $ sanitize_name p /-- Append a string to the last component of a name -/ def append_suffix : name → string → name | (mk_string s n) s' := mk_string (s ++ s') n | n _ := n /-- The first component of a name, turning a number to a string -/ meta def head : name → string | (mk_string s anonymous) := s | (mk_string s p) := head p | (mk_numeral n p) := head p | anonymous := "[anonymous]" /-- Tests whether the first component of a name is `"_private"` -/ meta def is_private (n : name) : bool := n.head = "_private" /-- Get the last component of a name, and convert it to a string. -/ meta def last : name → string | (mk_string s _) := s | (mk_numeral n _) := repr n | anonymous := "[anonymous]" /-- Returns the number of characters used to print all the string components of a name, including periods between name segments. Ignores numerical parts of a name. -/ meta def length : name → ℕ | (mk_string s anonymous) := s.length | (mk_string s p) := s.length + 1 + p.length | (mk_numeral n p) := p.length | anonymous := "[anonymous]".length end name namespace level /-- Tests whether a universe level is non-zero for all assignments of its variables -/ meta def nonzero : level → bool | (succ _) := tt | (max l₁ l₂) := l₁.nonzero || l₂.nonzero | (imax _ l₂) := l₂.nonzero | _ := ff end level namespace expr open tactic /-- Apply a function to each constant (inductive type, defined function etc) in an expression. -/ protected meta def apply_replacement_fun (f : name → name) (e : expr) : expr := e.replace $ λ e d, match e with | expr.const n ls := some $ expr.const (f n) ls | _ := none end /-- Turns an expression into a positive natural number, assuming it is only built up from `has_one.one`, `bit0` and `bit1`. -/ protected meta def to_pos_nat : expr → option ℕ | `(has_one.one _) := some 1 | `(bit0 %%e) := bit0 <$> e.to_pos_nat | `(bit1 %%e) := bit1 <$> e.to_pos_nat | _ := none /-- Turns an expression into a natural number, assuming it is only built up from `has_one.one`, `bit0`, `bit1` and `has_zero.zero`. -/ protected meta def to_nat : expr → option ℕ | `(has_zero.zero _) := some 0 | e := e.to_pos_nat /-- Turns an expression into a integer, assuming it is only built up from `has_one.one`, `bit0`, `bit1`, `has_zero.zero` and a optionally a single `has_neg.neg` as head. -/ protected meta def to_int : expr → option ℤ | `(has_neg.neg %%e) := do n ← e.to_nat, some (-n) | e := coe <$> e.to_nat /-- Tests whether an expression is a meta-variable. -/ meta def is_mvar : expr → bool | (mvar _ _ _) := tt | _ := ff /-- Tests whether an expression is a sort. -/ meta def is_sort : expr → bool | (sort _) := tt | e := ff /-- Returns a list of all local constants in an expression (without duplicates). -/ meta def list_local_consts (e : expr) : list expr := e.fold [] (λ e' _ es, if e'.is_local_constant then insert e' es else es) /-- Returns a name_set of all constants in an expression. -/ meta def list_constant (e : expr) : name_set := e.fold mk_name_set (λ e' _ es, if e'.is_constant then es.insert e'.const_name else es) /-- Returns a list of all meta-variables in an expression (without duplicates). -/ meta def list_meta_vars (e : expr) : list expr := e.fold [] (λ e' _ es, if e'.is_mvar then insert e' es else es) /-- Returns a name_set of all constants in an expression starting with a certain prefix. -/ meta def list_names_with_prefix (pre : name) (e : expr) : name_set := e.fold mk_name_set $ λ e' _ l, match e' with | expr.const n _ := if n.get_prefix = pre then l.insert n else l | _ := l end /-- is_num_eq n1 n2 returns true if n1 and n2 are both numerals with the same numeral structure, ignoring differences in type and type class arguments. -/ meta def is_num_eq : expr → expr → bool | `(@has_zero.zero _ _) `(@has_zero.zero _ _) := tt | `(@has_one.one _ _) `(@has_one.one _ _) := tt | `(bit0 %%a) `(bit0 %%b) := a.is_num_eq b | `(bit1 %%a) `(bit1 %%b) := a.is_num_eq b | `(-%%a) `(-%%b) := a.is_num_eq b | `(%%a/%%a') `(%%b/%%b') := a.is_num_eq b | _ _ := ff /-- Simplifies the expression `t` with the specified options. The result is `(new_e, pr)` with the new expression `new_e` and a proof `pr : e = new_e`. -/ meta def simp (t : expr) (cfg : simp_config := {}) (discharger : tactic unit := failed) (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) : tactic (expr × expr) := do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs, simplify s to_unfold t cfg `eq discharger /-- Definitionally simplifies the expression `t` with the specified options. The result is the simplified expression. -/ meta def dsimp (t : expr) (cfg : dsimp_config := {}) (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) : tactic expr := do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs, s.dsimplify to_unfold t cfg /-- Auxilliary definition for `expr.pi_arity` -/ meta def pi_arity_aux : ℕ → expr → ℕ | n (pi _ _ _ b) := pi_arity_aux (n + 1) b | n e := n /-- The arity of a pi-type. Does not perform any reduction of the expression. In one application this was ~30 times quicker than `tactic.get_pi_arity`. -/ meta def pi_arity : expr → ℕ := pi_arity_aux 0 end expr namespace environment /-- Tests whether a name is declared in the current file. Fixes an error in `in_current_file` which returns `tt` for the four names `quot, quot.mk, quot.lift, quot.ind` -/ meta def in_current_file' (env : environment) (n : name) : bool := env.in_current_file n && (n ∉ [``quot, ``quot.mk, ``quot.lift, ``quot.ind]) /-- Tests whether `n` is an inductive type with one constructor without indices. If so, returns the number of paramaters and the name of the constructor. Otherwise, returns `none`. -/ meta def is_structure_like (env : environment) (n : name) : option (nat × name) := do guardb (env.is_inductive n), d ← (env.get n).to_option, [intro] ← pure (env.constructors_of n) | none, guard (env.inductive_num_indices n = 0), some (env.inductive_num_params n, intro) /-- Tests whether `n` is a structure. It will first test whether `n` is structure-like and then test that the first projection is defined in the environment and is a projection. -/ meta def is_structure (env : environment) (n : name) : bool := option.is_some $ do (nparams, intro) ← env.is_structure_like n, di ← (env.get intro).to_option, expr.pi x _ _ _ ← nparams.iterate (λ e : option expr, do expr.pi _ _ _ body ← e | none, some body) (some di.type) | none, env.is_projection (n ++ x.deinternalize_field) /-- For all declarations `d` where `f d = some x` this adds `x` to the returned list. -/ meta def decl_filter_map {α : Type} (e : environment) (f : declaration → option α) : list α := e.fold [] $ λ d l, match f d with | some r := r :: l | none := l end /-- Maps `f` to all declarations in the environment. -/ meta def decl_map {α : Type} (e : environment) (f : declaration → α) : list α := e.decl_filter_map $ λ d, some (f d) /-- Lists all declarations in the environment -/ meta def get_decls (e : environment) : list declaration := e.decl_map id /-- Lists all trusted (non-meta) declarations in the environment -/ meta def get_trusted_decls (e : environment) : list declaration := e.decl_filter_map (λ d, if d.is_trusted then some d else none) /-- Lists the name of all declarations in the environment -/ meta def get_decl_names (e : environment) : list name := e.decl_map declaration.to_name /-- Fold a monad over all declarations in the environment. -/ meta def mfold {α : Type} {m : Type → Type} [monad m] (e : environment) (x : α) (fn : declaration → α → m α) : m α := e.fold (return x) (λ d t, t >>= fn d) end environment namespace declaration open tactic protected meta def update_with_fun (f : name → name) (tgt : name) (decl : declaration) : declaration := let decl := decl.update_name $ tgt in let decl := decl.update_type $ decl.type.apply_replacement_fun f in decl.update_value $ decl.value.apply_replacement_fun f /-- Checks whether the declaration is declared in the current file. This is a simple wrapper around `environment.in_current_file'` -/ meta def in_current_file (d : declaration) : tactic bool := do e ← get_env, return $ e.in_current_file' d.to_name /-- Checks whether a declaration is a theorem -/ meta def is_theorem : declaration → bool | (thm _ _ _ _) := tt | _ := ff /-- Checks whether a declaration is a constant -/ meta def is_constant : declaration → bool | (cnst _ _ _ _) := tt | _ := ff /-- Checks whether a declaration is a axiom -/ meta def is_axiom : declaration → bool | (ax _ _ _) := tt | _ := ff end declaration
1adffaa52b1d3b5efb81130fd15cc1ec775e6da0
59aed81a2ce7741e690907fc374be338f4f88b6f
/src/math-688/lectures/lec-26.lean
44eaecf0e1017d37bddda85937334dc4d07e5a56
[]
no_license
agusakov/math-688-lean
c84d5e1423eb208a0281135f0214b91b30d0ef48
67dc27ebff55a74c6b5a1c469ba04e7981d2e550
refs/heads/main
1,679,699,340,788
1,616,602,782,000
1,616,602,782,000
332,894,454
0
0
null
null
null
null
UTF-8
Lean
false
false
66
lean
/- 30 Oct 2019 -/ -- MWT -- weighted cover -- cost -- transversal
6165f4d6e460a61cb5843ab4b5bf22d22cf6829f
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/data/nat/digits.lean
f93cb193dddc8c0b37280303e80c8ffd65fe68b6
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
20,659
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Shing Tak Lam, Mario Carneiro -/ import data.int.modeq import tactic.interval_cases import tactic.linarith /-! # Digits of a natural number This provides a basic API for extracting the digits of a natural number in a given base, and reconstructing numbers from their digits. We also prove some divisibility tests based on digits, in particular completing Theorem #85 from https://www.cs.ru.nl/~freek/100/. A basic `norm_digits` tactic is also provided for proving goals of the form `nat.digits a b = l` where `a` and `b` are numerals. -/ namespace nat /-- (Impl.) An auxiliary definition for `digits`, to help get the desired definitional unfolding. -/ def digits_aux_0 : ℕ → list ℕ | 0 := [] | (n+1) := [n+1] /-- (Impl.) An auxiliary definition for `digits`, to help get the desired definitional unfolding. -/ def digits_aux_1 (n : ℕ) : list ℕ := list.repeat 1 n /-- (Impl.) An auxiliary definition for `digits`, to help get the desired definitional unfolding. -/ def digits_aux (b : ℕ) (h : 2 ≤ b) : ℕ → list ℕ | 0 := [] | (n+1) := have (n+1)/b < n+1 := nat.div_lt_self (nat.succ_pos _) h, (n+1) % b :: digits_aux ((n+1)/b) @[simp] lemma digits_aux_zero (b : ℕ) (h : 2 ≤ b) : digits_aux b h 0 = [] := rfl lemma digits_aux_def (b : ℕ) (h : 2 ≤ b) (n : ℕ) (w : 0 < n) : digits_aux b h n = n % b :: digits_aux b h (n/b) := begin cases n, { cases w, }, { rw [digits_aux], } end /-- `digits b n` gives the digits, in little-endian order, of a natural number `n` in a specified base `b`. In any base, we have `of_digits b L = L.foldr (λ x y, x + b * y) 0`. * For any `2 ≤ b`, we have `l < b` for any `l ∈ digits b n`, and the last digit is not zero. This uniquely specifies the behaviour of `digits b`. * For `b = 1`, we define `digits 1 n = list.repeat 1 n`. * For `b = 0`, we define `digits 0 n = [n]`, except `digits 0 0 = []`. Note this differs from the existing `nat.to_digits` in core, which is used for printing numerals. In particular, `nat.to_digits b 0 = [0]`, while `digits b 0 = []`. -/ def digits : ℕ → ℕ → list ℕ | 0 := digits_aux_0 | 1 := digits_aux_1 | (b+2) := digits_aux (b+2) (by norm_num) @[simp] lemma digits_zero (b : ℕ) : digits b 0 = [] := begin cases b, { refl, }, { cases b; refl, }, end @[simp] lemma digits_zero_zero : digits 0 0 = [] := rfl @[simp] lemma digits_zero_succ (n : ℕ) : digits 0 (n.succ) = [n+1] := rfl theorem digits_zero_succ' : ∀ {n : ℕ} (w : 0 < n), digits 0 n = [n] | 0 h := absurd h dec_trivial | (n+1) _ := rfl @[simp] lemma digits_one (n : ℕ) : digits 1 n = list.repeat 1 n := rfl @[simp] lemma digits_one_succ (n : ℕ) : digits 1 (n + 1) = 1 :: digits 1 n := rfl @[simp] lemma digits_add_two_add_one (b n : ℕ) : digits (b+2) (n+1) = (((n+1) % (b+2)) :: digits (b+2) ((n+1) / (b+2))) := rfl theorem digits_def' : ∀ {b : ℕ} (h : 2 ≤ b) {n : ℕ} (w : 0 < n), digits b n = n % b :: digits b (n/b) | 0 h := absurd h dec_trivial | 1 h := absurd h dec_trivial | (b+2) h := digits_aux_def _ _ @[simp] lemma digits_of_lt (b x : ℕ) (w₁ : 0 < x) (w₂ : x < b) : digits b x = [x] := begin cases b, { cases w₂ }, { cases b, { interval_cases x, }, { cases x, { cases w₁, }, { dsimp [digits], rw digits_aux, rw nat.div_eq_of_lt w₂, dsimp only [digits_aux_zero], rw nat.mod_eq_of_lt w₂, } } } end lemma digits_add (b : ℕ) (h : 2 ≤ b) (x y : ℕ) (w : x < b) (w' : 0 < x ∨ 0 < y) : digits b (x + b * y) = x :: digits b y := begin cases b, { cases h, }, { cases b, { norm_num at h, }, { cases y, { norm_num at w', simp [w, w'], }, dsimp [digits], rw digits_aux_def, { congr, { simp [nat.add_mod, nat.mod_eq_of_lt w], }, { simp [mul_comm (b+2), nat.add_mul_div_right, nat.div_eq_of_lt w], } }, { apply nat.succ_pos, }, }, }, end /-- `of_digits b L` takes a list `L` of natural numbers, and interprets them as a number in semiring, as the little-endian digits in base `b`. -/ -- If we had a function converting a list into a polynomial, -- and appropriate lemmas about that function, -- we could rewrite this in terms of that. def of_digits {α : Type*} [semiring α] (b : α) : list ℕ → α | [] := 0 | (h :: t) := h + b * of_digits t lemma of_digits_eq_foldr {α : Type*} [semiring α] (b : α) (L : list ℕ) : of_digits b L = L.foldr (λ x y, x + b * y) 0 := begin induction L with d L ih, { refl, }, { dsimp [of_digits], rw ih, }, end @[simp] lemma of_digits_singleton {b n : ℕ} : of_digits b [n] = n := by simp [of_digits] @[simp] lemma of_digits_one_cons {α : Type*} [semiring α] (h : ℕ) (L : list ℕ) : of_digits (1 : α) (h :: L) = h + of_digits 1 L := by simp [of_digits] lemma of_digits_append {b : ℕ} {l1 l2 : list ℕ} : of_digits b (l1 ++ l2) = of_digits b l1 + b^(l1.length) * of_digits b l2 := begin induction l1 with hd tl IH, { simp [of_digits] }, { rw [of_digits, list.cons_append, of_digits, IH, list.length_cons, pow_succ'], ring } end @[norm_cast] lemma coe_of_digits (α : Type*) [semiring α] (b : ℕ) (L : list ℕ) : ((of_digits b L : ℕ) : α) = of_digits (b : α) L := begin induction L with d L ih, { refl, }, { dsimp [of_digits], push_cast, rw ih, } end @[norm_cast] lemma coe_int_of_digits (b : ℕ) (L : list ℕ) : ((of_digits b L : ℕ) : ℤ) = of_digits (b : ℤ) L := begin induction L with d L ih, { refl, }, { dsimp [of_digits], push_cast, rw ih, } end lemma digits_zero_of_eq_zero {b : ℕ} (h : 1 ≤ b) {L : list ℕ} (w : of_digits b L = 0) : ∀ l ∈ L, l = 0 := begin induction L with d L ih, { intros l m, cases m, }, { intros l m, dsimp [of_digits] at w, rcases m with ⟨rfl⟩, { convert nat.eq_zero_of_add_eq_zero_right w, simp, }, { exact ih ((nat.mul_right_inj h).mp (nat.eq_zero_of_add_eq_zero_left w)) _ m, }, } end lemma digits_of_digits (b : ℕ) (h : 2 ≤ b) (L : list ℕ) (w₁ : ∀ l ∈ L, l < b) (w₂ : ∀ (h : L ≠ []), L.last h ≠ 0) : digits b (of_digits b L) = L := begin induction L with d L ih, { dsimp [of_digits], simp }, { dsimp [of_digits], replace w₂ := w₂ (by simp), rw digits_add b h, { rw ih, { simp, }, { intros l m, apply w₁, exact list.mem_cons_of_mem _ m, }, { intro h, { rw [list.last_cons _ h] at w₂, convert w₂, }}}, { convert w₁ d (list.mem_cons_self _ _), simp, }, { by_cases h' : L = [], { rcases h' with rfl, simp at w₂, left, apply nat.pos_of_ne_zero, convert w₂, simp, }, { right, apply nat.pos_of_ne_zero, contrapose! w₂, apply digits_zero_of_eq_zero _ w₂, { rw list.last_cons _ h', exact list.last_mem h', }, { exact le_of_lt h, }, }, }, }, end lemma of_digits_digits (b n : ℕ) : of_digits b (digits b n) = n := begin cases b with b, { cases n with n, { refl, }, { change of_digits 0 [n+1] = n+1, dsimp [of_digits], simp, } }, { cases b with b, { induction n with n ih, { refl, }, { simp only [ih, add_comm 1, of_digits_one_cons, nat.cast_id, digits_one_succ], } }, { apply nat.strong_induction_on n _, clear n, intros n h, cases n, { refl, }, { simp only [nat.succ_eq_add_one, digits_add_two_add_one], dsimp [of_digits], rw h _ (nat.div_lt_self' n b), rw [nat.cast_id, nat.mod_add_div], }, }, }, end lemma of_digits_one (L : list ℕ) : of_digits 1 L = L.sum := begin induction L with d L ih, { refl, }, { simp [of_digits, list.sum_cons, ih], } end /-! ### Properties This section contains various lemmas of properties relating to `digits` and `of_digits`. -/ lemma digits_eq_nil_iff_eq_zero {b n : ℕ} : digits b n = [] ↔ n = 0 := begin split, { intro h, have : of_digits b (digits b n) = of_digits b [], by rw h, convert this, rw of_digits_digits }, { rintro rfl, simp } end lemma digits_ne_nil_iff_ne_zero {b n : ℕ} : digits b n ≠ [] ↔ n ≠ 0 := not_congr digits_eq_nil_iff_eq_zero private lemma digits_last_aux {b n : ℕ} (h : 2 ≤ b) (w : 0 < n) : digits b n = ((n % b) :: digits b (n / b)) := begin rcases b with _|_|b, { finish }, { norm_num at h }, rcases n with _|n, { norm_num at w }, simp, end lemma digits_last {b m : ℕ} (h : 2 ≤ b) (hm : 0 < m) (p q) : (digits b m).last p = (digits b (m/b)).last q := by { simp only [digits_last_aux h hm], rw list.last_cons } lemma last_digit_ne_zero (b : ℕ) {m : ℕ} (hm : m ≠ 0) : (digits b m).last (digits_ne_nil_iff_ne_zero.mpr hm) ≠ 0 := begin rcases b with _|_|b, { cases m; finish }, { cases m, { finish }, simp_rw [digits_one, list.last_repeat_succ 1 m], norm_num }, revert hm, apply nat.strong_induction_on m, intros n IH hn, have hnpos : 0 < n := nat.pos_of_ne_zero hn, by_cases hnb : n < b + 2, { simp_rw [digits_of_lt b.succ.succ n hnpos hnb], exact pos_iff_ne_zero.mp hnpos }, { rw digits_last (show 2 ≤ b + 2, from dec_trivial) hnpos, refine IH _ (nat.div_lt_self hnpos dec_trivial) _, { rw ←pos_iff_ne_zero, exact nat.div_pos (le_of_not_lt hnb) dec_trivial } }, end /-- The digits in the base b+2 expansion of n are all less than b+2 -/ lemma digits_lt_base' {b m : ℕ} : ∀ {d}, d ∈ digits (b+2) m → d < b+2 := begin apply nat.strong_induction_on m, intros n IH d hd, unfold digits at hd IH, cases n with n, { cases hd }, -- base b+2 expansion of 0 has no digits rw digits_aux_def (b+2) (by linarith) n.succ (nat.zero_lt_succ n) at hd, cases hd, { rw hd, exact n.succ.mod_lt (by linarith) }, { exact IH _ (nat.div_lt_self (nat.succ_pos _) (by linarith)) hd } end /-- The digits in the base b expansion of n are all less than b, if b ≥ 2 -/ lemma digits_lt_base {b m d : ℕ} (hb : 2 ≤ b) (hd : d ∈ digits b m) : d < b := begin rcases b with _ | _ | b; try {linarith}, exact digits_lt_base' hd, end /-- an n-digit number in base b + 2 is less than (b + 2)^n -/ lemma of_digits_lt_base_pow_length' {b : ℕ} {l : list ℕ} (hl : ∀ x ∈ l, x < b+2) : of_digits (b+2) l < (b+2)^(l.length) := begin induction l with hd tl IH, { simp [of_digits], }, { rw [of_digits, list.length_cons, pow_succ], have : (of_digits (b + 2) tl + 1) * (b+2) ≤ (b + 2) ^ tl.length * (b+2) := mul_le_mul (IH (λ x hx, hl _ (list.mem_cons_of_mem _ hx))) (by refl) dec_trivial (nat.zero_le _), suffices : ↑hd < b + 2, { linarith }, norm_cast, exact hl hd (list.mem_cons_self _ _) } end /-- an n-digit number in base b is less than b^n if b ≥ 2 -/ lemma of_digits_lt_base_pow_length {b : ℕ} {l : list ℕ} (hb : 2 ≤ b) (hl : ∀ x ∈ l, x < b) : of_digits b l < b^l.length := begin rcases b with _ | _ | b; try { linarith }, exact of_digits_lt_base_pow_length' hl, end /-- Any number m is less than (b+2)^(number of digits in the base b + 2 representation of m) -/ lemma lt_base_pow_length_digits' {b m : ℕ} : m < (b + 2) ^ (digits (b + 2) m).length := begin convert of_digits_lt_base_pow_length' (λ _, digits_lt_base'), rw of_digits_digits (b+2) m, end /-- Any number m is less than b^(number of digits in the base b representation of m) -/ lemma lt_base_pow_length_digits {b m : ℕ} (hb : 2 ≤ b) : m < b^(digits b m).length := begin rcases b with _ | _ | b; try { linarith }, exact lt_base_pow_length_digits', end lemma of_digits_digits_append_digits {b m n : ℕ} : of_digits b (digits b n ++ digits b m) = n + b ^ (digits b n).length * m:= by rw [of_digits_append, of_digits_digits, of_digits_digits] lemma digits_len_le_digits_len_succ (b n : ℕ) : (digits b n).length ≤ (digits b (n + 1)).length := begin cases b, { -- base 0 cases n; simp }, { cases b, { -- base 1 simp }, { -- base >= 2 apply nat.strong_induction_on n, clear n, intros n IH, cases n, { simp }, { rw [digits_add_two_add_one, digits_add_two_add_one], by_cases hdvd : (b.succ.succ) ∣ (n.succ+1), { rw [nat.succ_div_of_dvd hdvd, list.length_cons, list.length_cons, nat.succ_le_succ_iff], apply IH, exact nat.div_lt_self (by linarith) (by linarith) }, { rw nat.succ_div_of_not_dvd hdvd, refl } } } } end lemma le_digits_len_le (b n m : ℕ) (h : n ≤ m) : (digits b n).length ≤ (digits b m).length := monotone_of_monotone_nat (digits_len_le_digits_len_succ b) h lemma pow_length_le_mul_of_digits {b : ℕ} {l : list ℕ} (hl : l ≠ []) (hl2 : l.last hl ≠ 0): (b + 2) ^ l.length ≤ (b + 2) * of_digits (b+2) l := begin rw [←list.init_append_last hl], simp only [list.length_append, list.length, zero_add, list.length_init, of_digits_append, list.length_init, of_digits_singleton, add_comm (l.length - 1), pow_add, pow_one], apply nat.mul_le_mul_left, refine le_trans _ (nat.le_add_left _ _), have : 0 < l.last hl, { rwa [pos_iff_ne_zero] }, convert nat.mul_le_mul_left _ this, rw [mul_one] end /-- Any non-zero natural number `m` is greater than (b+2)^((number of digits in the base (b+2) representation of m) - 1) -/ lemma base_pow_length_digits_le' (b m : ℕ) (hm : m ≠ 0) : (b + 2) ^ ((digits (b + 2) m).length) ≤ (b + 2) * m := begin have : digits (b + 2) m ≠ [], from digits_ne_nil_iff_ne_zero.mpr hm, convert pow_length_le_mul_of_digits this (last_digit_ne_zero _ hm), rwa of_digits_digits, end /-- Any non-zero natural number `m` is greater than b^((number of digits in the base b representation of m) - 1) -/ lemma base_pow_length_digits_le (b m : ℕ) (hb : 2 ≤ b): m ≠ 0 → b ^ ((digits b m).length) ≤ b * m := begin rcases b with _ | _ | b; try { linarith }, exact base_pow_length_digits_le' b m, end /-! ### Modular Arithmetic -/ -- This is really a theorem about polynomials. lemma dvd_of_digits_sub_of_digits {α : Type*} [comm_ring α] {a b k : α} (h : k ∣ a - b) (L : list ℕ) : k ∣ of_digits a L - of_digits b L := begin induction L with d L ih, { change k ∣ 0 - 0, simp, }, { simp only [of_digits, add_sub_add_left_eq_sub], exact dvd_mul_sub_mul h ih, } end lemma of_digits_modeq' (b b' : ℕ) (k : ℕ) (h : b ≡ b' [MOD k]) (L : list ℕ) : of_digits b L ≡ of_digits b' L [MOD k] := begin induction L with d L ih, { refl, }, { dsimp [of_digits], dsimp [nat.modeq] at *, conv_lhs { rw [nat.add_mod, nat.mul_mod, h, ih], }, conv_rhs { rw [nat.add_mod, nat.mul_mod], }, } end lemma of_digits_modeq (b k : ℕ) (L : list ℕ) : of_digits b L ≡ of_digits (b % k) L [MOD k] := of_digits_modeq' b (b % k) k (nat.modeq.symm (nat.modeq.mod_modeq b k)) L lemma of_digits_mod (b k : ℕ) (L : list ℕ) : of_digits b L % k = of_digits (b % k) L % k := of_digits_modeq b k L lemma of_digits_zmodeq' (b b' : ℤ) (k : ℕ) (h : b ≡ b' [ZMOD k]) (L : list ℕ) : of_digits b L ≡ of_digits b' L [ZMOD k] := begin induction L with d L ih, { refl, }, { dsimp [of_digits], dsimp [int.modeq] at *, conv_lhs { rw [int.add_mod, int.mul_mod, h, ih], }, conv_rhs { rw [int.add_mod, int.mul_mod], }, } end lemma of_digits_zmodeq (b : ℤ) (k : ℕ) (L : list ℕ) : of_digits b L ≡ of_digits (b % k) L [ZMOD k] := of_digits_zmodeq' b (b % k) k (int.modeq.symm (int.modeq.mod_modeq b ↑k)) L lemma of_digits_zmod (b : ℤ) (k : ℕ) (L : list ℕ) : of_digits b L % k = of_digits (b % k) L % k := of_digits_zmodeq b k L lemma modeq_digits_sum (b b' : ℕ) (h : b' % b = 1) (n : ℕ) : n ≡ (digits b' n).sum [MOD b] := begin rw ←of_digits_one, conv { congr, skip, rw ←(of_digits_digits b' n) }, convert of_digits_modeq _ _ _, exact h.symm, end lemma modeq_three_digits_sum (n : ℕ) : n ≡ (digits 10 n).sum [MOD 3] := modeq_digits_sum 3 10 (by norm_num) n lemma modeq_nine_digits_sum (n : ℕ) : n ≡ (digits 10 n).sum [MOD 9] := modeq_digits_sum 9 10 (by norm_num) n lemma zmodeq_of_digits_digits (b b' : ℕ) (c : ℤ) (h : b' ≡ c [ZMOD b]) (n : ℕ) : n ≡ of_digits c (digits b' n) [ZMOD b] := begin conv { congr, skip, rw ←(of_digits_digits b' n) }, rw coe_int_of_digits, apply of_digits_zmodeq' _ _ _ h, end lemma of_digits_neg_one : Π (L : list ℕ), of_digits (-1 : ℤ) L = (L.map (λ n : ℕ, (n : ℤ))).alternating_sum | [] := rfl | [n] := by simp [of_digits, list.alternating_sum] | (a :: b :: t) := begin simp only [of_digits, list.alternating_sum, list.map_cons, of_digits_neg_one t], push_cast, ring, end lemma modeq_eleven_digits_sum (n : ℕ) : n ≡ ((digits 10 n).map (λ n : ℕ, (n : ℤ))).alternating_sum [ZMOD 11] := begin have t := zmodeq_of_digits_digits 11 10 (-1 : ℤ) dec_trivial n, rw of_digits_neg_one at t, exact t, end /-! ## Divisibility -/ lemma dvd_iff_dvd_digits_sum (b b' : ℕ) (h : b' % b = 1) (n : ℕ) : b ∣ n ↔ b ∣ (digits b' n).sum := begin rw ←of_digits_one, conv_lhs { rw ←(of_digits_digits b' n) }, rw [nat.dvd_iff_mod_eq_zero, nat.dvd_iff_mod_eq_zero, of_digits_mod, h], end lemma three_dvd_iff (n : ℕ) : 3 ∣ n ↔ 3 ∣ (digits 10 n).sum := dvd_iff_dvd_digits_sum 3 10 (by norm_num) n lemma nine_dvd_iff (n : ℕ) : 9 ∣ n ↔ 9 ∣ (digits 10 n).sum := dvd_iff_dvd_digits_sum 9 10 (by norm_num) n lemma dvd_iff_dvd_of_digits (b b' : ℕ) (c : ℤ) (h : (b : ℤ) ∣ (b' : ℤ) - c) (n : ℕ) : b ∣ n ↔ (b : ℤ) ∣ of_digits c (digits b' n) := begin rw ←int.coe_nat_dvd, exact dvd_iff_dvd_of_dvd_sub (int.modeq.modeq_iff_dvd.1 (zmodeq_of_digits_digits b b' c (int.modeq.modeq_iff_dvd.2 h).symm _).symm), end lemma eleven_dvd_iff (n : ℕ) : 11 ∣ n ↔ (11 : ℤ) ∣ ((digits 10 n).map (λ n : ℕ, (n : ℤ))).alternating_sum := begin have t := dvd_iff_dvd_of_digits 11 10 (-1 : ℤ) (by norm_num) n, rw of_digits_neg_one at t, exact t, end /-! ### `norm_digits` tactic -/ namespace norm_digits theorem digits_succ (b n m r l) (e : r + b * m = n) (hr : r < b) (h : nat.digits b m = l ∧ 2 ≤ b ∧ 0 < m) : nat.digits b n = r :: l ∧ 2 ≤ b ∧ 0 < n := begin rcases h with ⟨h, b2, m0⟩, have b0 : 0 < b := by linarith, have n0 : 0 < n := by linarith [mul_pos b0 m0], refine ⟨_, b2, n0⟩, obtain ⟨rfl, rfl⟩ := (nat.div_mod_unique b0).2 ⟨e, hr⟩, subst h, exact nat.digits_def' b2 n0, end theorem digits_one (b n) (n0 : 0 < n) (nb : n < b) : nat.digits b n = [n] ∧ 2 ≤ b ∧ 0 < n := begin have b2 : 2 ≤ b := by linarith, refine ⟨_, b2, n0⟩, rw [nat.digits_def' b2 n0, nat.mod_eq_of_lt nb, (nat.div_eq_zero_iff (by linarith : 0 < b)).2 nb, nat.digits_zero], end open tactic /-- Helper function for the `norm_digits` tactic. -/ meta def eval_aux (eb : expr) (b : ℕ) : expr → ℕ → instance_cache → tactic (instance_cache × expr × expr) | en n ic := do let m := n / b, let r := n % b, (ic, er) ← ic.of_nat r, (ic, pr) ← norm_num.prove_lt_nat ic er eb, if m = 0 then do (_, pn0) ← norm_num.prove_pos ic en, return (ic, `([%%en] : list nat), `(digits_one %%eb %%en %%pn0 %%pr)) else do em ← expr.of_nat `(ℕ) m, (_, pe) ← norm_num.derive `(%%er + %%eb * %%em : ℕ), (ic, el, p) ← eval_aux em m ic, return (ic, `(@list.cons ℕ %%er %%el), `(digits_succ %%eb %%en %%em %%er %%el %%pe %%pr %%p)) /-- A tactic for normalizing expressions of the form `nat.digits a b = l` where `a` and `b` are numerals. ``` example : nat.digits 10 123 = [3,2,1] := by norm_num ``` -/ @[norm_num] meta def eval : expr → tactic (expr × expr) | `(nat.digits %%eb %%en) := do b ← expr.to_nat eb, n ← expr.to_nat en, if n = 0 then return (`([] : list ℕ), `(nat.digits_zero %%eb)) else if b = 0 then do ic ← mk_instance_cache `(ℕ), (_, pn0) ← norm_num.prove_pos ic en, return (`([%%en] : list ℕ), `(@nat.digits_zero_succ' %%en %%pn0)) else if b = 1 then do ic ← mk_instance_cache `(ℕ), (_, pn0) ← norm_num.prove_pos ic en, s ← simp_lemmas.add_simp simp_lemmas.mk `list.repeat, (rhs, p2) ← simplify s [] `(list.repeat 1 %%en), p ← mk_eq_trans `(nat.digits_one %%en) p2, return (rhs, p) else do ic ← mk_instance_cache `(ℕ), (_, l, p) ← eval_aux eb b en n ic, p ← mk_app ``and.left [p], return (l, p) | _ := failed end norm_digits end nat
6026d51410c6251088cba25dbd324fe921f8f27d
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/src/Lean/Elab/PreDefinition/Main.lean
dc4d9c7b1ab3cf2041c919ba45d1fc0ffd2a7ace
[ "Apache-2.0" ]
permissive
walterhu1015/lean4
b2c71b688975177402758924eaa513475ed6ce72
2214d81e84646a905d0b20b032c89caf89c737ad
refs/heads/master
1,671,342,096,906
1,599,695,985,000
1,599,695,985,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,812
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.PreDefinition.Basic import Lean.Elab.PreDefinition.Structural import Lean.Elab.PreDefinition.WF namespace Lean namespace Elab open Meta open Term private def addAndCompilePartial (preDefs : Array PreDefinition) : TermElabM Unit := do preDefs.forM fun preDef => forallTelescopeReducing preDef.type fun xs type => do inh ← liftM $ mkInhabitantFor preDef.declName xs type; addNonRec { preDef with kind := DefKind.«opaque», value := inh }; addAndCompileUnsafeRec preDefs private def isNonRecursive (preDef : PreDefinition) : Bool := Option.isNone $ preDef.value.find? fun c => match c with | Expr.const declName _ _ => preDef.declName == declName | _ => false private def partitionPreDefs (preDefs : Array PreDefinition) : Array (Array PreDefinition) := let getPreDef := fun declName => (preDefs.find? fun preDef => preDef.declName == declName).get!; let vertices := preDefs.toList.map fun preDef => preDef.declName; let successorsOf := fun declName => (getPreDef declName).value.foldConsts [] fun declName successors => if preDefs.any fun preDef => preDef.declName == declName then declName :: successors else successors; let sccs := SCC.scc vertices successorsOf; sccs.toArray.map fun scc => scc.toArray.map getPreDef private def collectMVarsAtPreDef (preDef : PreDefinition) : StateRefT CollectMVars.State MetaM Unit := do collectMVars preDef.value; collectMVars preDef.type private def getMVarsAtPreDef (preDef : PreDefinition) : MetaM (Array MVarId) := do (_, s) ← (collectMVarsAtPreDef preDef).run {}; pure s.result private def ensureNoUnassignedMVarsAtPreDef (preDef : PreDefinition) : TermElabM Unit := do pendingMVarIds ← liftMetaM $ getMVarsAtPreDef preDef; foundError ← logUnassignedUsingErrorContext pendingMVarIds; when foundError throwAbort def addPreDefinitions (preDefs : Array PreDefinition) : TermElabM Unit := do preDefs.forM fun preDef => trace `Elab.definition.body fun _ => preDef.declName ++ " : " ++ preDef.type ++ " :=" ++ Format.line ++ preDef.value; preDefs.forM ensureNoUnassignedMVarsAtPreDef; (partitionPreDefs preDefs).forM fun preDefs => do if preDefs.size == 1 && isNonRecursive (preDefs.get! 0) then let preDef := preDefs.get! 0; if preDef.modifiers.isNoncomputable then addNonRec preDef else addAndCompileNonRec preDef else if preDefs.any fun preDef => preDef.modifiers.isUnsafe then addAndCompileUnsafe preDefs else if preDefs.any fun preDef => preDef.modifiers.isPartial then addAndCompilePartial preDefs else unlessM (structuralRecursion preDefs) do WFRecursion preDefs end Elab end Lean
957ba1963d6683e2f10d5146e0237cdb8b810920
94e33a31faa76775069b071adea97e86e218a8ee
/src/analysis/asymptotics/asymptotics.lean
b360c534cec973999a88fff82cdf712d426f0cb2
[ "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
69,572
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Yury Kudryashov -/ import analysis.normed_space.basic import topology.algebra.order.liminf_limsup import topology.local_homeomorph /-! # Asymptotics We introduce these relations: * `is_O_with c l f g` : "f is big O of g along l with constant c"; * `f =O[l] g` : "f is big O of g along l"; * `f =o[l] g` : "f is little o of g along l". Here `l` is any filter on the domain of `f` and `g`, which are assumed to be the same. The codomains of `f` and `g` do not need to be the same; all that is needed that there is a norm associated with these types, and it is the norm that is compared asymptotically. The relation `is_O_with c` is introduced to factor out common algebraic arguments in the proofs of similar properties of `is_O` and `is_o`. Usually proofs outside of this file should use `is_O` instead. Often the ranges of `f` and `g` will be the real numbers, in which case the norm is the absolute value. In general, we have `f =O[l] g ↔ (λ x, ∥f x∥) =O[l] (λ x, ∥g x∥)`, and similarly for `is_o`. But our setup allows us to use the notions e.g. with functions to the integers, rationals, complex numbers, or any normed vector space without mentioning the norm explicitly. If `f` and `g` are functions to a normed field like the reals or complex numbers and `g` is always nonzero, we have `f =o[l] g ↔ tendsto (λ x, f x / (g x)) l (𝓝 0)`. In fact, the right-to-left direction holds without the hypothesis on `g`, and in the other direction it suffices to assume that `f` is zero wherever `g` is. (This generalization is useful in defining the Fréchet derivative.) -/ open filter set open_locale topological_space big_operators classical filter nnreal namespace asymptotics variables {α : Type*} {β : Type*} {E : Type*} {F : Type*} {G : Type*} {E' : Type*} {F' : Type*} {G' : Type*} {E'' : Type*} {F'' : Type*} {G'' : Type*} {R : Type*} {R' : Type*} {𝕜 : Type*} {𝕜' : Type*} variables [has_norm E] [has_norm F] [has_norm G] variables [semi_normed_group E'] [semi_normed_group F'] [semi_normed_group G'] variables [normed_group E''] [normed_group F''] [normed_group G''] variables [semi_normed_ring R] [semi_normed_ring R'] variables [normed_field 𝕜] [normed_field 𝕜'] variables {c c' c₁ c₂ : ℝ} {f : α → E} {g : α → F} {k : α → G} variables {f' : α → E'} {g' : α → F'} {k' : α → G'} variables {f'' : α → E''} {g'' : α → F''} {k'' : α → G''} variables {l l' : filter α} section defs /-! ### Definitions -/ /-- This version of the Landau notation `is_O_with C l f g` where `f` and `g` are two functions on a type `α` and `l` is a filter on `α`, means that eventually for `l`, `∥f∥` is bounded by `C * ∥g∥`. In other words, `∥f∥ / ∥g∥` is eventually bounded by `C`, modulo division by zero issues that are avoided by this definition. Probably you want to use `is_O` instead of this relation. -/ @[irreducible] def is_O_with (c : ℝ) (l : filter α) (f : α → E) (g : α → F) : Prop := ∀ᶠ x in l, ∥ f x ∥ ≤ c * ∥ g x ∥ /-- Definition of `is_O_with`. We record it in a lemma as `is_O_with` is irreducible. -/ lemma is_O_with_iff : is_O_with c l f g ↔ ∀ᶠ x in l, ∥f x∥ ≤ c * ∥g x∥ := by rw is_O_with alias is_O_with_iff ↔ is_O_with.bound is_O_with.of_bound /-- The Landau notation `f =O[l] g` where `f` and `g` are two functions on a type `α` and `l` is a filter on `α`, means that eventually for `l`, `∥f∥` is bounded by a constant multiple of `∥g∥`. In other words, `∥f∥ / ∥g∥` is eventually bounded, modulo division by zero issues that are avoided by this definition. -/ @[irreducible] def is_O (l : filter α) (f : α → E) (g : α → F) : Prop := ∃ c : ℝ, is_O_with c l f g notation f ` =O[`:100 l `] ` g:100 := is_O l f g /-- Definition of `is_O` in terms of `is_O_with`. We record it in a lemma as `is_O` is irreducible. -/ lemma is_O_iff_is_O_with : f =O[l] g ↔ ∃ c : ℝ, is_O_with c l f g := by rw is_O /-- Definition of `is_O` in terms of filters. We record it in a lemma as we will set `is_O` to be irreducible at the end of this file. -/ lemma is_O_iff : f =O[l] g ↔ ∃ c : ℝ, ∀ᶠ x in l, ∥f x∥ ≤ c * ∥g x∥ := by simp only [is_O, is_O_with] lemma is_O.of_bound (c : ℝ) (h : ∀ᶠ x in l, ∥f x∥ ≤ c * ∥g x∥) : f =O[l] g := is_O_iff.2 ⟨c, h⟩ lemma is_O.bound : f =O[l] g → ∃ c : ℝ, ∀ᶠ x in l, ∥f x∥ ≤ c * ∥g x∥ := is_O_iff.1 /-- The Landau notation `f =o[l] g` where `f` and `g` are two functions on a type `α` and `l` is a filter on `α`, means that eventually for `l`, `∥f∥` is bounded by an arbitrarily small constant multiple of `∥g∥`. In other words, `∥f∥ / ∥g∥` tends to `0` along `l`, modulo division by zero issues that are avoided by this definition. -/ @[irreducible] def is_o (l : filter α) (f : α → E) (g : α → F) : Prop := ∀ ⦃c : ℝ⦄, 0 < c → is_O_with c l f g notation f ` =o[`:100 l `] ` g:100 := is_o l f g /-- Definition of `is_o` in terms of `is_O_with`. We record it in a lemma as we will set `is_o` to be irreducible at the end of this file. -/ lemma is_o_iff_forall_is_O_with : f =o[l] g ↔ ∀ ⦃c : ℝ⦄, 0 < c → is_O_with c l f g := by rw is_o alias is_o_iff_forall_is_O_with ↔ is_o.forall_is_O_with is_o.of_is_O_with /-- Definition of `is_o` in terms of filters. We record it in a lemma as we will set `is_o` to be irreducible at the end of this file. -/ lemma is_o_iff : f =o[l] g ↔ ∀ ⦃c : ℝ⦄, 0 < c → ∀ᶠ x in l, ∥f x∥ ≤ c * ∥g x∥ := by simp only [is_o, is_O_with] alias is_o_iff ↔ is_o.bound is_o.of_bound lemma is_o.def (h : f =o[l] g) (hc : 0 < c) : ∀ᶠ x in l, ∥f x∥ ≤ c * ∥g x∥ := is_o_iff.1 h hc lemma is_o.def' (h : f =o[l] g) (hc : 0 < c) : is_O_with c l f g := is_O_with_iff.2 $ is_o_iff.1 h hc end defs /-! ### Conversions -/ theorem is_O_with.is_O (h : is_O_with c l f g) : f =O[l] g := by rw is_O; exact ⟨c, h⟩ theorem is_o.is_O_with (hgf : f =o[l] g) : is_O_with 1 l f g := hgf.def' zero_lt_one theorem is_o.is_O (hgf : f =o[l] g) : f =O[l] g := hgf.is_O_with.is_O lemma is_O.is_O_with : f =O[l] g → ∃ c : ℝ, is_O_with c l f g := is_O_iff_is_O_with.1 theorem is_O_with.weaken (h : is_O_with c l f g') (hc : c ≤ c') : is_O_with c' l f g' := is_O_with.of_bound $ mem_of_superset h.bound $ λ x hx, calc ∥f x∥ ≤ c * ∥g' x∥ : hx ... ≤ _ : mul_le_mul_of_nonneg_right hc (norm_nonneg _) theorem is_O_with.exists_pos (h : is_O_with c l f g') : ∃ c' (H : 0 < c'), is_O_with c' l f g' := ⟨max c 1, lt_of_lt_of_le zero_lt_one (le_max_right c 1), h.weaken $ le_max_left c 1⟩ theorem is_O.exists_pos (h : f =O[l] g') : ∃ c (H : 0 < c), is_O_with c l f g' := let ⟨c, hc⟩ := h.is_O_with in hc.exists_pos theorem is_O_with.exists_nonneg (h : is_O_with c l f g') : ∃ c' (H : 0 ≤ c'), is_O_with c' l f g' := let ⟨c, cpos, hc⟩ := h.exists_pos in ⟨c, le_of_lt cpos, hc⟩ theorem is_O.exists_nonneg (h : f =O[l] g') : ∃ c (H : 0 ≤ c), is_O_with c l f g' := let ⟨c, hc⟩ := h.is_O_with in hc.exists_nonneg /-- `f = O(g)` if and only if `is_O_with c f g` for all sufficiently large `c`. -/ lemma is_O_iff_eventually_is_O_with : f =O[l] g' ↔ ∀ᶠ c in at_top, is_O_with c l f g' := is_O_iff_is_O_with.trans ⟨λ ⟨c, hc⟩, mem_at_top_sets.2 ⟨c, λ c' hc', hc.weaken hc'⟩, λ h, h.exists⟩ /-- `f = O(g)` if and only if `∀ᶠ x in l, ∥f x∥ ≤ c * ∥g x∥` for all sufficiently large `c`. -/ lemma is_O_iff_eventually : f =O[l] g' ↔ ∀ᶠ c in at_top, ∀ᶠ x in l, ∥f x∥ ≤ c * ∥g' x∥ := is_O_iff_eventually_is_O_with.trans $ by simp only [is_O_with] lemma is_O.exists_mem_basis {ι} {p : ι → Prop} {s : ι → set α} (h : f =O[l] g') (hb : l.has_basis p s) : ∃ (c : ℝ) (hc : 0 < c) (i : ι) (hi : p i), ∀ x ∈ s i, ∥f x∥ ≤ c * ∥g' x∥ := flip Exists₂.imp h.exists_pos $ λ c hc h, by simpa only [is_O_with_iff, hb.eventually_iff, exists_prop] using h lemma is_O_with_inv (hc : 0 < c) : is_O_with c⁻¹ l f g ↔ ∀ᶠ x in l, c * ∥f x∥ ≤ ∥g x∥ := by simp only [is_O_with, ← div_eq_inv_mul, le_div_iff' hc] -- We prove this lemma with strange assumptions to get two lemmas below automatically lemma is_o_iff_nat_mul_le_aux (h₀ : (∀ x, 0 ≤ ∥f x∥) ∨ ∀ x, 0 ≤ ∥g x∥) : f =o[l] g ↔ ∀ n : ℕ, ∀ᶠ x in l, ↑n * ∥f x∥ ≤ ∥g x∥ := begin split, { rintro H (_|n), { refine (H.def one_pos).mono (λ x h₀', _), rw [nat.cast_zero, zero_mul], refine h₀.elim (λ hf, (hf x).trans _) (λ hg, hg x), rwa one_mul at h₀' }, { have : (0 : ℝ) < n.succ, from nat.cast_pos.2 n.succ_pos, exact (is_O_with_inv this).1 (H.def' $ inv_pos.2 this) } }, { refine λ H, is_o_iff.2 (λ ε ε0, _), rcases exists_nat_gt ε⁻¹ with ⟨n, hn⟩, have hn₀ : (0 : ℝ) < n, from (inv_pos.2 ε0).trans hn, refine ((is_O_with_inv hn₀).2 (H n)).bound.mono (λ x hfg, _), refine hfg.trans (mul_le_mul_of_nonneg_right (inv_le_of_inv_le ε0 hn.le) _), refine h₀.elim (λ hf, nonneg_of_mul_nonneg_right ((hf x).trans hfg) _) (λ h, h x), exact inv_pos.2 hn₀ } end lemma is_o_iff_nat_mul_le : f =o[l] g' ↔ ∀ n : ℕ, ∀ᶠ x in l, ↑n * ∥f x∥ ≤ ∥g' x∥ := is_o_iff_nat_mul_le_aux (or.inr $ λ x, norm_nonneg _) lemma is_o_iff_nat_mul_le' : f' =o[l] g ↔ ∀ n : ℕ, ∀ᶠ x in l, ↑n * ∥f' x∥ ≤ ∥g x∥ := is_o_iff_nat_mul_le_aux (or.inl $ λ x, norm_nonneg _) /-! ### Subsingleton -/ @[nontriviality] lemma is_o_of_subsingleton [subsingleton E'] : f' =o[l] g' := is_o.of_bound $ λ c hc, by simp [subsingleton.elim (f' _) 0, mul_nonneg hc.le] @[nontriviality] lemma is_O_of_subsingleton [subsingleton E'] : f' =O[l] g' := is_o_of_subsingleton.is_O section congr variables {f₁ f₂ : α → E} {g₁ g₂ : α → F} /-! ### Congruence -/ theorem is_O_with_congr (hc : c₁ = c₂) (hf : f₁ =ᶠ[l] f₂) (hg : g₁ =ᶠ[l] g₂) : is_O_with c₁ l f₁ g₁ ↔ is_O_with c₂ l f₂ g₂ := begin unfold is_O_with, subst c₂, apply filter.eventually_congr, filter_upwards [hf, hg] with _ e₁ e₂, rw [e₁, e₂], end theorem is_O_with.congr' (h : is_O_with c₁ l f₁ g₁) (hc : c₁ = c₂) (hf : f₁ =ᶠ[l] f₂) (hg : g₁ =ᶠ[l] g₂) : is_O_with c₂ l f₂ g₂ := (is_O_with_congr hc hf hg).mp h theorem is_O_with.congr (h : is_O_with c₁ l f₁ g₁) (hc : c₁ = c₂) (hf : ∀ x, f₁ x = f₂ x) (hg : ∀ x, g₁ x = g₂ x) : is_O_with c₂ l f₂ g₂ := h.congr' hc (univ_mem' hf) (univ_mem' hg) theorem is_O_with.congr_left (h : is_O_with c l f₁ g) (hf : ∀ x, f₁ x = f₂ x) : is_O_with c l f₂ g := h.congr rfl hf (λ _, rfl) theorem is_O_with.congr_right (h : is_O_with c l f g₁) (hg : ∀ x, g₁ x = g₂ x) : is_O_with c l f g₂ := h.congr rfl (λ _, rfl) hg theorem is_O_with.congr_const (h : is_O_with c₁ l f g) (hc : c₁ = c₂) : is_O_with c₂ l f g := h.congr hc (λ _, rfl) (λ _, rfl) theorem is_O_congr (hf : f₁ =ᶠ[l] f₂) (hg : g₁ =ᶠ[l] g₂) : f₁ =O[l] g₁ ↔ f₂ =O[l] g₂ := by { unfold is_O, exact exists_congr (λ c, is_O_with_congr rfl hf hg) } theorem is_O.congr' (h : f₁ =O[l] g₁) (hf : f₁ =ᶠ[l] f₂) (hg : g₁ =ᶠ[l] g₂) : f₂ =O[l] g₂ := (is_O_congr hf hg).mp h theorem is_O.congr (h : f₁ =O[l] g₁) (hf : ∀ x, f₁ x = f₂ x) (hg : ∀ x, g₁ x = g₂ x) : f₂ =O[l] g₂ := h.congr' (univ_mem' hf) (univ_mem' hg) theorem is_O.congr_left (h : f₁ =O[l] g) (hf : ∀ x, f₁ x = f₂ x) : f₂ =O[l] g := h.congr hf (λ _, rfl) theorem is_O.congr_right (h : f =O[l] g₁) (hg : ∀ x, g₁ x = g₂ x) : f =O[l] g₂ := h.congr (λ _, rfl) hg theorem is_o_congr (hf : f₁ =ᶠ[l] f₂) (hg : g₁ =ᶠ[l] g₂) : f₁ =o[l] g₁ ↔ f₂ =o[l] g₂ := by { unfold is_o, exact forall₂_congr (λ c hc, is_O_with_congr (eq.refl c) hf hg) } theorem is_o.congr' (h : f₁ =o[l] g₁) (hf : f₁ =ᶠ[l] f₂) (hg : g₁ =ᶠ[l] g₂) : f₂ =o[l] g₂ := (is_o_congr hf hg).mp h theorem is_o.congr (h : f₁ =o[l] g₁) (hf : ∀ x, f₁ x = f₂ x) (hg : ∀ x, g₁ x = g₂ x) : f₂ =o[l] g₂ := h.congr' (univ_mem' hf) (univ_mem' hg) theorem is_o.congr_left (h : f₁ =o[l] g) (hf : ∀ x, f₁ x = f₂ x) : f₂ =o[l] g := h.congr hf (λ _, rfl) theorem is_o.congr_right (h : f =o[l] g₁) (hg : ∀ x, g₁ x = g₂ x) : f =o[l] g₂ := h.congr (λ _, rfl) hg @[trans] theorem _root_.filter.eventually_eq.trans_is_O {f₁ f₂ : α → E} {g : α → F} (hf : f₁ =ᶠ[l] f₂) (h : f₂ =O[l] g) : f₁ =O[l] g := h.congr' hf.symm eventually_eq.rfl @[trans] theorem _root_.filter.eventually_eq.trans_is_o {f₁ f₂ : α → E} {g : α → F} (hf : f₁ =ᶠ[l] f₂) (h : f₂ =o[l] g) : f₁ =o[l] g := h.congr' hf.symm eventually_eq.rfl @[trans] theorem is_O.trans_eventually_eq {f : α → E} {g₁ g₂ : α → F} (h : f =O[l] g₁) (hg : g₁ =ᶠ[l] g₂) : f =O[l] g₂ := h.congr' eventually_eq.rfl hg @[trans] theorem is_o.trans_eventually_eq {f : α → E} {g₁ g₂ : α → F} (h : f =o[l] g₁) (hg : g₁ =ᶠ[l] g₂) : f =o[l] g₂ := h.congr' eventually_eq.rfl hg end congr /-! ### Filter operations and transitivity -/ theorem is_O_with.comp_tendsto (hcfg : is_O_with c l f g) {k : β → α} {l' : filter β} (hk : tendsto k l' l): is_O_with c l' (f ∘ k) (g ∘ k) := is_O_with.of_bound $ hk hcfg.bound theorem is_O.comp_tendsto (hfg : f =O[l] g) {k : β → α} {l' : filter β} (hk : tendsto k l' l) : (f ∘ k) =O[l'] (g ∘ k) := is_O_iff_is_O_with.2 $ hfg.is_O_with.imp (λ c h, h.comp_tendsto hk) theorem is_o.comp_tendsto (hfg : f =o[l] g) {k : β → α} {l' : filter β} (hk : tendsto k l' l) : (f ∘ k) =o[l'] (g ∘ k) := is_o.of_is_O_with $ λ c cpos, (hfg.forall_is_O_with cpos).comp_tendsto hk @[simp] theorem is_O_with_map {k : β → α} {l : filter β} : is_O_with c (map k l) f g ↔ is_O_with c l (f ∘ k) (g ∘ k) := by { unfold is_O_with, exact eventually_map } @[simp] theorem is_O_map {k : β → α} {l : filter β} : f =O[map k l] g ↔ (f ∘ k) =O[l] (g ∘ k) := by simp only [is_O, is_O_with_map] @[simp] theorem is_o_map {k : β → α} {l : filter β} : f =o[map k l] g ↔ (f ∘ k) =o[l] (g ∘ k) := by simp only [is_o, is_O_with_map] theorem is_O_with.mono (h : is_O_with c l' f g) (hl : l ≤ l') : is_O_with c l f g := is_O_with.of_bound $ hl h.bound theorem is_O.mono (h : f =O[l'] g) (hl : l ≤ l') : f =O[l] g := is_O_iff_is_O_with.2 $ h.is_O_with.imp (λ c h, h.mono hl) theorem is_o.mono (h : f =o[l'] g) (hl : l ≤ l') : f =o[l] g := is_o.of_is_O_with $ λ c cpos, (h.forall_is_O_with cpos).mono hl theorem is_O_with.trans (hfg : is_O_with c l f g) (hgk : is_O_with c' l g k) (hc : 0 ≤ c) : is_O_with (c * c') l f k := begin unfold is_O_with at *, filter_upwards [hfg, hgk] with x hx hx', calc ∥f x∥ ≤ c * ∥g x∥ : hx ... ≤ c * (c' * ∥k x∥) : mul_le_mul_of_nonneg_left hx' hc ... = c * c' * ∥k x∥ : (mul_assoc _ _ _).symm end @[trans] theorem is_O.trans {f : α → E} {g : α → F'} {k : α → G} (hfg : f =O[l] g) (hgk : g =O[l] k) : f =O[l] k := let ⟨c, cnonneg, hc⟩ := hfg.exists_nonneg, ⟨c', hc'⟩ := hgk.is_O_with in (hc.trans hc' cnonneg).is_O theorem is_o.trans_is_O_with (hfg : f =o[l] g) (hgk : is_O_with c l g k) (hc : 0 < c) : f =o[l] k := begin unfold is_o at *, intros c' c'pos, have : 0 < c' / c, from div_pos c'pos hc, exact ((hfg this).trans hgk this.le).congr_const (div_mul_cancel _ hc.ne') end @[trans] theorem is_o.trans_is_O {f : α → E} {g : α → F} {k : α → G'} (hfg : f =o[l] g) (hgk : g =O[l] k) : f =o[l] k := let ⟨c, cpos, hc⟩ := hgk.exists_pos in hfg.trans_is_O_with hc cpos theorem is_O_with.trans_is_o (hfg : is_O_with c l f g) (hgk : g =o[l] k) (hc : 0 < c) : f =o[l] k := begin unfold is_o at *, intros c' c'pos, have : 0 < c' / c, from div_pos c'pos hc, exact (hfg.trans (hgk this) hc.le).congr_const (mul_div_cancel' _ hc.ne') end @[trans] theorem is_O.trans_is_o {f : α → E} {g : α → F'} {k : α → G} (hfg : f =O[l] g) (hgk : g =o[l] k) : f =o[l] k := let ⟨c, cpos, hc⟩ := hfg.exists_pos in hc.trans_is_o hgk cpos @[trans] theorem is_o.trans {f : α → E} {g : α → F} {k : α → G} (hfg : f =o[l] g) (hgk : g =o[l] k) : f =o[l] k := hfg.trans_is_O_with hgk.is_O_with one_pos section variable (l) theorem is_O_with_of_le' (hfg : ∀ x, ∥f x∥ ≤ c * ∥g x∥) : is_O_with c l f g := is_O_with.of_bound $ univ_mem' hfg theorem is_O_with_of_le (hfg : ∀ x, ∥f x∥ ≤ ∥g x∥) : is_O_with 1 l f g := is_O_with_of_le' l $ λ x, by { rw one_mul, exact hfg x } theorem is_O_of_le' (hfg : ∀ x, ∥f x∥ ≤ c * ∥g x∥) : f =O[l] g := (is_O_with_of_le' l hfg).is_O theorem is_O_of_le (hfg : ∀ x, ∥f x∥ ≤ ∥g x∥) : f =O[l] g := (is_O_with_of_le l hfg).is_O end theorem is_O_with_refl (f : α → E) (l : filter α) : is_O_with 1 l f f := is_O_with_of_le l $ λ _, le_rfl theorem is_O_refl (f : α → E) (l : filter α) : f =O[l] f := (is_O_with_refl f l).is_O theorem is_O_with.trans_le (hfg : is_O_with c l f g) (hgk : ∀ x, ∥g x∥ ≤ ∥k x∥) (hc : 0 ≤ c) : is_O_with c l f k := (hfg.trans (is_O_with_of_le l hgk) hc).congr_const $ mul_one c theorem is_O.trans_le (hfg : f =O[l] g') (hgk : ∀ x, ∥g' x∥ ≤ ∥k x∥) : f =O[l] k := hfg.trans (is_O_of_le l hgk) theorem is_o.trans_le (hfg : f =o[l] g) (hgk : ∀ x, ∥g x∥ ≤ ∥k x∥) : f =o[l] k := hfg.trans_is_O_with (is_O_with_of_le _ hgk) zero_lt_one theorem is_o_irrefl' (h : ∃ᶠ x in l, ∥f' x∥ ≠ 0) : ¬f' =o[l] f' := begin intro ho, rcases ((ho.bound one_half_pos).and_frequently h).exists with ⟨x, hle, hne⟩, rw [one_div, ← div_eq_inv_mul] at hle, exact (half_lt_self (lt_of_le_of_ne (norm_nonneg _) hne.symm)).not_le hle end theorem is_o_irrefl (h : ∃ᶠ x in l, f'' x ≠ 0) : ¬f'' =o[l] f'' := is_o_irrefl' $ h.mono $ λ x, norm_ne_zero_iff.mpr theorem is_O.not_is_o (h : f'' =O[l] g') (hf : ∃ᶠ x in l, f'' x ≠ 0) : ¬g' =o[l] f'' := λ h', is_o_irrefl hf (h.trans_is_o h') theorem is_o.not_is_O (h : f'' =o[l] g') (hf : ∃ᶠ x in l, f'' x ≠ 0) : ¬g' =O[l] f'' := λ h', is_o_irrefl hf (h.trans_is_O h') section bot variables (c f g) @[simp] theorem is_O_with_bot : is_O_with c ⊥ f g := is_O_with.of_bound $ trivial @[simp] theorem is_O_bot : f =O[⊥] g := (is_O_with_bot 1 f g).is_O @[simp] theorem is_o_bot : f =o[⊥] g := is_o.of_is_O_with $ λ c _, is_O_with_bot c f g end bot @[simp] theorem is_O_with_pure {x} : is_O_with c (pure x) f g ↔ ∥f x∥ ≤ c * ∥g x∥ := is_O_with_iff theorem is_O_with.sup (h : is_O_with c l f g) (h' : is_O_with c l' f g) : is_O_with c (l ⊔ l') f g := is_O_with.of_bound $ mem_sup.2 ⟨h.bound, h'.bound⟩ theorem is_O_with.sup' (h : is_O_with c l f g') (h' : is_O_with c' l' f g') : is_O_with (max c c') (l ⊔ l') f g' := is_O_with.of_bound $ mem_sup.2 ⟨(h.weaken $ le_max_left c c').bound, (h'.weaken $ le_max_right c c').bound⟩ theorem is_O.sup (h : f =O[l] g') (h' : f =O[l'] g') : f =O[l ⊔ l'] g' := let ⟨c, hc⟩ := h.is_O_with, ⟨c', hc'⟩ := h'.is_O_with in (hc.sup' hc').is_O theorem is_o.sup (h : f =o[l] g) (h' : f =o[l'] g) : f =o[l ⊔ l'] g := is_o.of_is_O_with $ λ c cpos, (h.forall_is_O_with cpos).sup (h'.forall_is_O_with cpos) @[simp] lemma is_O_sup : f =O[l ⊔ l'] g' ↔ f =O[l] g' ∧ f =O[l'] g' := ⟨λ h, ⟨h.mono le_sup_left, h.mono le_sup_right⟩, λ h, h.1.sup h.2⟩ @[simp] lemma is_o_sup : f =o[l ⊔ l'] g ↔ f =o[l] g ∧ f =o[l'] g := ⟨λ h, ⟨h.mono le_sup_left, h.mono le_sup_right⟩, λ h, h.1.sup h.2⟩ /-! ### Simplification : norm, abs -/ section norm_abs variables {u v : α → ℝ} @[simp] theorem is_O_with_norm_right : is_O_with c l f (λ x, ∥g' x∥) ↔ is_O_with c l f g' := by simp only [is_O_with, norm_norm] @[simp] theorem is_O_with_abs_right : is_O_with c l f (λ x, |u x|) ↔ is_O_with c l f u := @is_O_with_norm_right _ _ _ _ _ _ f u l alias is_O_with_norm_right ↔ is_O_with.of_norm_right is_O_with.norm_right alias is_O_with_abs_right ↔ is_O_with.of_abs_right is_O_with.abs_right @[simp] theorem is_O_norm_right : f =O[l] (λ x, ∥g' x∥) ↔ f =O[l] g' := by { unfold is_O, exact exists_congr (λ _, is_O_with_norm_right) } @[simp] theorem is_O_abs_right : f =O[l] (λ x, |u x|) ↔ f =O[l] u := @is_O_norm_right _ _ ℝ _ _ _ _ _ alias is_O_norm_right ↔ is_O.of_norm_right is_O.norm_right alias is_O_abs_right ↔ is_O.of_abs_right is_O.abs_right @[simp] theorem is_o_norm_right : f =o[l] (λ x, ∥g' x∥) ↔ f =o[l] g' := by { unfold is_o, exact forall₂_congr (λ _ _, is_O_with_norm_right) } @[simp] theorem is_o_abs_right : f =o[l] (λ x, |u x|) ↔ f =o[l] u := @is_o_norm_right _ _ ℝ _ _ _ _ _ alias is_o_norm_right ↔ is_o.of_norm_right is_o.norm_right alias is_o_abs_right ↔ is_o.of_abs_right is_o.abs_right @[simp] theorem is_O_with_norm_left : is_O_with c l (λ x, ∥f' x∥) g ↔ is_O_with c l f' g := by simp only [is_O_with, norm_norm] @[simp] theorem is_O_with_abs_left : is_O_with c l (λ x, |u x|) g ↔ is_O_with c l u g := @is_O_with_norm_left _ _ _ _ _ _ g u l alias is_O_with_norm_left ↔ is_O_with.of_norm_left is_O_with.norm_left alias is_O_with_abs_left ↔ is_O_with.of_abs_left is_O_with.abs_left @[simp] theorem is_O_norm_left : (λ x, ∥f' x∥) =O[l] g ↔ f' =O[l] g := by { unfold is_O, exact exists_congr (λ _, is_O_with_norm_left) } @[simp] theorem is_O_abs_left : (λ x, |u x|) =O[l] g ↔ u =O[l] g := @is_O_norm_left _ _ _ _ _ g u l alias is_O_norm_left ↔ is_O.of_norm_left is_O.norm_left alias is_O_abs_left ↔ is_O.of_abs_left is_O.abs_left @[simp] theorem is_o_norm_left : (λ x, ∥f' x∥) =o[l] g ↔ f' =o[l] g := by { unfold is_o, exact forall₂_congr (λ _ _, is_O_with_norm_left) } @[simp] theorem is_o_abs_left : (λ x, |u x|) =o[l] g ↔ u =o[l] g := @is_o_norm_left _ _ _ _ _ g u l alias is_o_norm_left ↔ is_o.of_norm_left is_o.norm_left alias is_o_abs_left ↔ is_o.of_abs_left is_o.abs_left theorem is_O_with_norm_norm : is_O_with c l (λ x, ∥f' x∥) (λ x, ∥g' x∥) ↔ is_O_with c l f' g' := is_O_with_norm_left.trans is_O_with_norm_right theorem is_O_with_abs_abs : is_O_with c l (λ x, |u x|) (λ x, |v x|) ↔ is_O_with c l u v := is_O_with_abs_left.trans is_O_with_abs_right alias is_O_with_norm_norm ↔ is_O_with.of_norm_norm is_O_with.norm_norm alias is_O_with_abs_abs ↔ is_O_with.of_abs_abs is_O_with.abs_abs theorem is_O_norm_norm : (λ x, ∥f' x∥) =O[l] (λ x, ∥g' x∥) ↔ f' =O[l] g' := is_O_norm_left.trans is_O_norm_right theorem is_O_abs_abs : (λ x, |u x|) =O[l] (λ x, |v x|) ↔ u =O[l] v := is_O_abs_left.trans is_O_abs_right alias is_O_norm_norm ↔ is_O.of_norm_norm is_O.norm_norm alias is_O_abs_abs ↔ is_O.of_abs_abs is_O.abs_abs theorem is_o_norm_norm : (λ x, ∥f' x∥) =o[l] (λ x, ∥g' x∥) ↔ f' =o[l] g' := is_o_norm_left.trans is_o_norm_right theorem is_o_abs_abs : (λ x, |u x|) =o[l] (λ x, |v x|) ↔ u =o[l] v := is_o_abs_left.trans is_o_abs_right alias is_o_norm_norm ↔ is_o.of_norm_norm is_o.norm_norm alias is_o_abs_abs ↔ is_o.of_abs_abs is_o.abs_abs end norm_abs /-! ### Simplification: negate -/ @[simp] theorem is_O_with_neg_right : is_O_with c l f (λ x, -(g' x)) ↔ is_O_with c l f g' := by simp only [is_O_with, norm_neg] alias is_O_with_neg_right ↔ is_O_with.of_neg_right is_O_with.neg_right @[simp] theorem is_O_neg_right : f =O[l] (λ x, -(g' x)) ↔ f =O[l] g' := by { unfold is_O, exact exists_congr (λ _, is_O_with_neg_right) } alias is_O_neg_right ↔ is_O.of_neg_right is_O.neg_right @[simp] theorem is_o_neg_right : f =o[l] (λ x, -(g' x)) ↔ f =o[l] g' := by { unfold is_o, exact forall₂_congr (λ _ _, is_O_with_neg_right) } alias is_o_neg_right ↔ is_o.of_neg_right is_o.neg_right @[simp] theorem is_O_with_neg_left : is_O_with c l (λ x, -(f' x)) g ↔ is_O_with c l f' g := by simp only [is_O_with, norm_neg] alias is_O_with_neg_left ↔ is_O_with.of_neg_left is_O_with.neg_left @[simp] theorem is_O_neg_left : (λ x, -(f' x)) =O[l] g ↔ f' =O[l] g := by { unfold is_O, exact exists_congr (λ _, is_O_with_neg_left) } alias is_O_neg_left ↔ is_O.of_neg_left is_O.neg_left @[simp] theorem is_o_neg_left : (λ x, -(f' x)) =o[l] g ↔ f' =o[l] g := by { unfold is_o, exact forall₂_congr (λ _ _, is_O_with_neg_left) } alias is_o_neg_left ↔ is_o.of_neg_right is_o.neg_left /-! ### Product of functions (right) -/ lemma is_O_with_fst_prod : is_O_with 1 l f' (λ x, (f' x, g' x)) := is_O_with_of_le l $ λ x, le_max_left _ _ lemma is_O_with_snd_prod : is_O_with 1 l g' (λ x, (f' x, g' x)) := is_O_with_of_le l $ λ x, le_max_right _ _ lemma is_O_fst_prod : f' =O[l] (λ x, (f' x, g' x)) := is_O_with_fst_prod.is_O lemma is_O_snd_prod : g' =O[l] (λ x, (f' x, g' x)) := is_O_with_snd_prod.is_O lemma is_O_fst_prod' {f' : α → E' × F'} : (λ x, (f' x).1) =O[l] f' := by simpa [is_O, is_O_with] using is_O_fst_prod lemma is_O_snd_prod' {f' : α → E' × F'} : (λ x, (f' x).2) =O[l] f' := by simpa [is_O, is_O_with] using is_O_snd_prod section variables (f' k') lemma is_O_with.prod_rightl (h : is_O_with c l f g') (hc : 0 ≤ c) : is_O_with c l f (λ x, (g' x, k' x)) := (h.trans is_O_with_fst_prod hc).congr_const (mul_one c) lemma is_O.prod_rightl (h : f =O[l] g') : f =O[l] (λ x, (g' x, k' x)) := let ⟨c, cnonneg, hc⟩ := h.exists_nonneg in (hc.prod_rightl k' cnonneg).is_O lemma is_o.prod_rightl (h : f =o[l] g') : f =o[l] (λ x, (g' x, k' x)) := is_o.of_is_O_with $ λ c cpos, (h.forall_is_O_with cpos).prod_rightl k' cpos.le lemma is_O_with.prod_rightr (h : is_O_with c l f g') (hc : 0 ≤ c) : is_O_with c l f (λ x, (f' x, g' x)) := (h.trans is_O_with_snd_prod hc).congr_const (mul_one c) lemma is_O.prod_rightr (h : f =O[l] g') : f =O[l] (λ x, (f' x, g' x)) := let ⟨c, cnonneg, hc⟩ := h.exists_nonneg in (hc.prod_rightr f' cnonneg).is_O lemma is_o.prod_rightr (h : f =o[l] g') : f =o[l] (λx, (f' x, g' x)) := is_o.of_is_O_with $ λ c cpos, (h.forall_is_O_with cpos).prod_rightr f' cpos.le end lemma is_O_with.prod_left_same (hf : is_O_with c l f' k') (hg : is_O_with c l g' k') : is_O_with c l (λ x, (f' x, g' x)) k' := by rw is_O_with_iff at *; filter_upwards [hf, hg] with x using max_le lemma is_O_with.prod_left (hf : is_O_with c l f' k') (hg : is_O_with c' l g' k') : is_O_with (max c c') l (λ x, (f' x, g' x)) k' := (hf.weaken $ le_max_left c c').prod_left_same (hg.weaken $ le_max_right c c') lemma is_O_with.prod_left_fst (h : is_O_with c l (λ x, (f' x, g' x)) k') : is_O_with c l f' k' := (is_O_with_fst_prod.trans h zero_le_one).congr_const $ one_mul c lemma is_O_with.prod_left_snd (h : is_O_with c l (λ x, (f' x, g' x)) k') : is_O_with c l g' k' := (is_O_with_snd_prod.trans h zero_le_one).congr_const $ one_mul c lemma is_O_with_prod_left : is_O_with c l (λ x, (f' x, g' x)) k' ↔ is_O_with c l f' k' ∧ is_O_with c l g' k' := ⟨λ h, ⟨h.prod_left_fst, h.prod_left_snd⟩, λ h, h.1.prod_left_same h.2⟩ lemma is_O.prod_left (hf : f' =O[l] k') (hg : g' =O[l] k') : (λ x, (f' x, g' x)) =O[l] k' := let ⟨c, hf⟩ := hf.is_O_with, ⟨c', hg⟩ := hg.is_O_with in (hf.prod_left hg).is_O lemma is_O.prod_left_fst (h : (λ x, (f' x, g' x)) =O[l] k') : f' =O[l] k' := is_O_fst_prod.trans h lemma is_O.prod_left_snd (h : (λ x, (f' x, g' x)) =O[l] k') : g' =O[l] k' := is_O_snd_prod.trans h @[simp] lemma is_O_prod_left : (λ x, (f' x, g' x)) =O[l] k' ↔ f' =O[l] k' ∧ g' =O[l] k' := ⟨λ h, ⟨h.prod_left_fst, h.prod_left_snd⟩, λ h, h.1.prod_left h.2⟩ lemma is_o.prod_left (hf : f' =o[l] k') (hg : g' =o[l] k') : (λ x, (f' x, g' x)) =o[l] k' := is_o.of_is_O_with $ λ c hc, (hf.forall_is_O_with hc).prod_left_same (hg.forall_is_O_with hc) lemma is_o.prod_left_fst (h : (λ x, (f' x, g' x)) =o[l] k') : f' =o[l] k' := is_O_fst_prod.trans_is_o h lemma is_o.prod_left_snd (h : (λ x, (f' x, g' x)) =o[l] k') : g' =o[l] k' := is_O_snd_prod.trans_is_o h @[simp] lemma is_o_prod_left : (λ x, (f' x, g' x)) =o[l] k' ↔ f' =o[l] k' ∧ g' =o[l] k' := ⟨λ h, ⟨h.prod_left_fst, h.prod_left_snd⟩, λ h, h.1.prod_left h.2⟩ lemma is_O_with.eq_zero_imp (h : is_O_with c l f'' g'') : ∀ᶠ x in l, g'' x = 0 → f'' x = 0 := eventually.mono h.bound $ λ x hx hg, norm_le_zero_iff.1 $ by simpa [hg] using hx lemma is_O.eq_zero_imp (h : f'' =O[l] g'') : ∀ᶠ x in l, g'' x = 0 → f'' x = 0 := let ⟨C, hC⟩ := h.is_O_with in hC.eq_zero_imp /-! ### Addition and subtraction -/ section add_sub variables {f₁ f₂ : α → E'} {g₁ g₂ : α → F'} theorem is_O_with.add (h₁ : is_O_with c₁ l f₁ g) (h₂ : is_O_with c₂ l f₂ g) : is_O_with (c₁ + c₂) l (λ x, f₁ x + f₂ x) g := by rw is_O_with at *; filter_upwards [h₁, h₂] with x hx₁ hx₂ using calc ∥f₁ x + f₂ x∥ ≤ c₁ * ∥g x∥ + c₂ * ∥g x∥ : norm_add_le_of_le hx₁ hx₂ ... = (c₁ + c₂) * ∥g x∥ : (add_mul _ _ _).symm theorem is_O.add (h₁ : f₁ =O[l] g) (h₂ : f₂ =O[l] g) : (λ x, f₁ x + f₂ x) =O[l] g := let ⟨c₁, hc₁⟩ := h₁.is_O_with, ⟨c₂, hc₂⟩ := h₂.is_O_with in (hc₁.add hc₂).is_O theorem is_o.add (h₁ : f₁ =o[l] g) (h₂ : f₂ =o[l] g) : (λ x, f₁ x + f₂ x) =o[l] g := is_o.of_is_O_with $ λ c cpos, ((h₁.forall_is_O_with $ half_pos cpos).add (h₂.forall_is_O_with $ half_pos cpos)).congr_const (add_halves c) theorem is_o.add_add (h₁ : f₁ =o[l] g₁) (h₂ : f₂ =o[l] g₂) : (λ x, f₁ x + f₂ x) =o[l] (λ x, ∥g₁ x∥ + ∥g₂ x∥) := by refine (h₁.trans_le $ λ x, _).add (h₂.trans_le _); simp [abs_of_nonneg, add_nonneg] theorem is_O.add_is_o (h₁ : f₁ =O[l] g) (h₂ : f₂ =o[l] g) : (λ x, f₁ x + f₂ x) =O[l] g := h₁.add h₂.is_O theorem is_o.add_is_O (h₁ : f₁ =o[l] g) (h₂ : f₂ =O[l] g) : (λ x, f₁ x + f₂ x) =O[l] g := h₁.is_O.add h₂ theorem is_O_with.add_is_o (h₁ : is_O_with c₁ l f₁ g) (h₂ : f₂ =o[l] g) (hc : c₁ < c₂) : is_O_with c₂ l (λx, f₁ x + f₂ x) g := (h₁.add (h₂.forall_is_O_with (sub_pos.2 hc))).congr_const (add_sub_cancel'_right _ _) theorem is_o.add_is_O_with (h₁ : f₁ =o[l] g) (h₂ : is_O_with c₁ l f₂ g) (hc : c₁ < c₂) : is_O_with c₂ l (λx, f₁ x + f₂ x) g := (h₂.add_is_o h₁ hc).congr_left $ λ _, add_comm _ _ theorem is_O_with.sub (h₁ : is_O_with c₁ l f₁ g) (h₂ : is_O_with c₂ l f₂ g) : is_O_with (c₁ + c₂) l (λ x, f₁ x - f₂ x) g := by simpa only [sub_eq_add_neg] using h₁.add h₂.neg_left theorem is_O_with.sub_is_o (h₁ : is_O_with c₁ l f₁ g) (h₂ : f₂ =o[l] g) (hc : c₁ < c₂) : is_O_with c₂ l (λ x, f₁ x - f₂ x) g := by simpa only [sub_eq_add_neg] using h₁.add_is_o h₂.neg_left hc theorem is_O.sub (h₁ : f₁ =O[l] g) (h₂ : f₂ =O[l] g) : (λ x, f₁ x - f₂ x) =O[l] g := by simpa only [sub_eq_add_neg] using h₁.add h₂.neg_left theorem is_o.sub (h₁ : f₁ =o[l] g) (h₂ : f₂ =o[l] g) : (λ x, f₁ x - f₂ x) =o[l] g := by simpa only [sub_eq_add_neg] using h₁.add h₂.neg_left end add_sub /-! ### Lemmas about `is_O (f₁ - f₂) g l` / `is_o (f₁ - f₂) g l` treated as a binary relation -/ section is_oO_as_rel variables {f₁ f₂ f₃ : α → E'} theorem is_O_with.symm (h : is_O_with c l (λ x, f₁ x - f₂ x) g) : is_O_with c l (λ x, f₂ x - f₁ x) g := h.neg_left.congr_left $ λ x, neg_sub _ _ theorem is_O_with_comm : is_O_with c l (λ x, f₁ x - f₂ x) g ↔ is_O_with c l (λ x, f₂ x - f₁ x) g := ⟨is_O_with.symm, is_O_with.symm⟩ theorem is_O.symm (h : (λ x, f₁ x - f₂ x) =O[l] g) : (λ x, f₂ x - f₁ x) =O[l] g := h.neg_left.congr_left $ λ x, neg_sub _ _ theorem is_O_comm : (λ x, f₁ x - f₂ x) =O[l] g ↔ (λ x, f₂ x - f₁ x) =O[l] g := ⟨is_O.symm, is_O.symm⟩ theorem is_o.symm (h : (λ x, f₁ x - f₂ x) =o[l] g) : (λ x, f₂ x - f₁ x) =o[l] g := by simpa only [neg_sub] using h.neg_left theorem is_o_comm : (λ x, f₁ x - f₂ x) =o[l] g ↔ (λ x, f₂ x - f₁ x) =o[l] g := ⟨is_o.symm, is_o.symm⟩ theorem is_O_with.triangle (h₁ : is_O_with c l (λ x, f₁ x - f₂ x) g) (h₂ : is_O_with c' l (λ x, f₂ x - f₃ x) g) : is_O_with (c + c') l (λ x, f₁ x - f₃ x) g := (h₁.add h₂).congr_left $ λ x, sub_add_sub_cancel _ _ _ theorem is_O.triangle (h₁ : (λ x, f₁ x - f₂ x) =O[l] g) (h₂ : (λ x, f₂ x - f₃ x) =O[l] g) : (λ x, f₁ x - f₃ x) =O[l] g := (h₁.add h₂).congr_left $ λ x, sub_add_sub_cancel _ _ _ theorem is_o.triangle (h₁ : (λ x, f₁ x - f₂ x) =o[l] g) (h₂ : (λ x, f₂ x - f₃ x) =o[l] g) : (λ x, f₁ x - f₃ x) =o[l] g := (h₁.add h₂).congr_left $ λ x, sub_add_sub_cancel _ _ _ theorem is_O.congr_of_sub (h : (λ x, f₁ x - f₂ x) =O[l] g) : f₁ =O[l] g ↔ f₂ =O[l] g := ⟨λ h', (h'.sub h).congr_left (λ x, sub_sub_cancel _ _), λ h', (h.add h').congr_left (λ x, sub_add_cancel _ _)⟩ theorem is_o.congr_of_sub (h : (λ x, f₁ x - f₂ x) =o[l] g) : f₁ =o[l] g ↔ f₂ =o[l] g := ⟨λ h', (h'.sub h).congr_left (λ x, sub_sub_cancel _ _), λ h', (h.add h').congr_left (λ x, sub_add_cancel _ _)⟩ end is_oO_as_rel /-! ### Zero, one, and other constants -/ section zero_const variables (g g' l) theorem is_o_zero : (λ x, (0 : E')) =o[l] g' := is_o.of_bound $ λ c hc, univ_mem' $ λ x, by simpa using mul_nonneg hc.le (norm_nonneg $ g' x) theorem is_O_with_zero (hc : 0 ≤ c) : is_O_with c l (λ x, (0 : E')) g' := is_O_with.of_bound $ univ_mem' $ λ x, by simpa using mul_nonneg hc (norm_nonneg $ g' x) theorem is_O_with_zero' : is_O_with 0 l (λ x, (0 : E')) g := is_O_with.of_bound $ univ_mem' $ λ x, by simp theorem is_O_zero : (λ x, (0 : E')) =O[l] g := is_O_iff_is_O_with.2 ⟨0, is_O_with_zero' _ _⟩ theorem is_O_refl_left : (λ x, f' x - f' x) =O[l] g' := (is_O_zero g' l).congr_left $ λ x, (sub_self _).symm theorem is_o_refl_left : (λ x, f' x - f' x) =o[l] g' := (is_o_zero g' l).congr_left $ λ x, (sub_self _).symm variables {g g' l} @[simp] theorem is_O_with_zero_right_iff : is_O_with c l f'' (λ x, (0 : F')) ↔ f'' =ᶠ[l] 0 := by simp only [is_O_with, exists_prop, true_and, norm_zero, mul_zero, norm_le_zero_iff, eventually_eq, pi.zero_apply] @[simp] theorem is_O_zero_right_iff : f'' =O[l] (λ x, (0 : F')) ↔ f'' =ᶠ[l] 0 := ⟨λ h, let ⟨c, hc⟩ := h.is_O_with in is_O_with_zero_right_iff.1 hc, λ h, (is_O_with_zero_right_iff.2 h : is_O_with 1 _ _ _).is_O⟩ @[simp] theorem is_o_zero_right_iff : f'' =o[l] (λ x, (0 : F')) ↔ f'' =ᶠ[l] 0 := ⟨λ h, is_O_zero_right_iff.1 h.is_O, λ h, is_o.of_is_O_with $ λ c hc, is_O_with_zero_right_iff.2 h⟩ theorem is_O_with_const_const (c : E) {c' : F''} (hc' : c' ≠ 0) (l : filter α) : is_O_with (∥c∥ / ∥c'∥) l (λ x : α, c) (λ x, c') := begin unfold is_O_with, apply univ_mem', intro x, rw [mem_set_of_eq, div_mul_cancel], rwa [ne.def, norm_eq_zero] end theorem is_O_const_const (c : E) {c' : F''} (hc' : c' ≠ 0) (l : filter α) : (λ x : α, c) =O[l] (λ x, c') := (is_O_with_const_const c hc' l).is_O @[simp] theorem is_O_const_const_iff {c : E''} {c' : F''} (l : filter α) [l.ne_bot] : (λ x : α, c) =O[l] (λ x, c') ↔ (c' = 0 → c = 0) := begin rcases eq_or_ne c' 0 with rfl|hc', { simp [eventually_eq] }, { simp [hc', is_O_const_const _ hc'] } end @[simp] lemma is_O_pure {x} : f'' =O[pure x] g'' ↔ (g'' x = 0 → f'' x = 0) := calc f'' =O[pure x] g'' ↔ (λ y : α, f'' x) =O[pure x] (λ _, g'' x) : is_O_congr rfl rfl ... ↔ g'' x = 0 → f'' x = 0 : is_O_const_const_iff _ end zero_const @[simp] lemma is_O_with_top : is_O_with c ⊤ f g ↔ ∀ x, ∥f x∥ ≤ c * ∥g x∥ := by rw is_O_with; refl @[simp] lemma is_O_top : f =O[⊤] g ↔ ∃ C, ∀ x, ∥f x∥ ≤ C * ∥g x∥ := by rw is_O_iff; refl @[simp] lemma is_o_top : f'' =o[⊤] g'' ↔ ∀ x, f'' x = 0 := begin refine ⟨_, λ h, (is_o_zero g'' ⊤).congr (λ x, (h x).symm) (λ x, rfl)⟩, simp only [is_o_iff, eventually_top], refine λ h x, norm_le_zero_iff.1 _, have : tendsto (λ c : ℝ, c * ∥g'' x∥) (𝓝[>] 0) (𝓝 0) := ((continuous_id.mul continuous_const).tendsto' _ _ (zero_mul _)).mono_left inf_le_left, exact le_of_tendsto_of_tendsto tendsto_const_nhds this (eventually_nhds_within_iff.2 $ eventually_of_forall $ λ c hc, h hc x) end @[simp] lemma is_O_with_principal {s : set α} : is_O_with c (𝓟 s) f g ↔ ∀ x ∈ s, ∥f x∥ ≤ c * ∥g x∥ := by rw is_O_with; refl lemma is_O_principal {s : set α} : f =O[𝓟 s] g ↔ ∃ c, ∀ x ∈ s, ∥f x∥ ≤ c * ∥g x∥ := by rw is_O_iff; refl section variables (F) [has_one F] [norm_one_class F] theorem is_O_with_const_one (c : E) (l : filter α) : is_O_with ∥c∥ l (λ x : α, c) (λ x, (1 : F)) := by simp [is_O_with_iff] theorem is_O_const_one (c : E) (l : filter α) : (λ x : α, c) =O[l] (λ x, (1 : F)) := (is_O_with_const_one F c l).is_O theorem is_o_const_iff_is_o_one {c : F''} (hc : c ≠ 0) : f =o[l] (λ x, c) ↔ f =o[l] (λ x, (1 : F)) := ⟨λ h, h.trans_is_O_with (is_O_with_const_one _ _ _) (norm_pos_iff.2 hc), λ h, h.trans_is_O $ is_O_const_const _ hc _⟩ @[simp] theorem is_o_one_iff : f' =o[l] (λ x, 1 : α → F) ↔ tendsto f' l (𝓝 0) := by simp only [is_o_iff, norm_one, mul_one, metric.nhds_basis_closed_ball.tendsto_right_iff, metric.mem_closed_ball, dist_zero_right] @[simp] theorem is_O_one_iff : f =O[l] (λ x, 1 : α → F) ↔ is_bounded_under (≤) l (λ x, ∥f x∥) := by { simp only [is_O_iff, norm_one, mul_one], refl } alias is_O_one_iff ↔ _ _root_.filter.is_bounded_under.is_O_one @[simp] theorem is_o_one_left_iff : (λ x, 1 : α → F) =o[l] f ↔ tendsto (λ x, ∥f x∥) l at_top := calc (λ x, 1 : α → F) =o[l] f ↔ ∀ n : ℕ, ∀ᶠ x in l, ↑n * ∥(1 : F)∥ ≤ ∥f x∥ : is_o_iff_nat_mul_le_aux $ or.inl $ λ x, by simp only [norm_one, zero_le_one] ... ↔ ∀ n : ℕ, true → ∀ᶠ x in l, ∥f x∥ ∈ Ici (n : ℝ) : by simp only [norm_one, mul_one, true_implies_iff, mem_Ici] ... ↔ tendsto (λ x, ∥f x∥) l at_top : at_top_countable_basis_of_archimedean.1.tendsto_right_iff.symm theorem _root_.filter.tendsto.is_O_one {c : E'} (h : tendsto f' l (𝓝 c)) : f' =O[l] (λ x, 1 : α → F) := h.norm.is_bounded_under_le.is_O_one F theorem is_O.trans_tendsto_nhds (hfg : f =O[l] g') {y : F'} (hg : tendsto g' l (𝓝 y)) : f =O[l] (λ x, 1 : α → F) := hfg.trans $ hg.is_O_one F end theorem is_o_const_iff {c : F''} (hc : c ≠ 0) : f'' =o[l] (λ x, c) ↔ tendsto f'' l (𝓝 0) := (is_o_const_iff_is_o_one ℝ hc).trans (is_o_one_iff _) lemma is_o_id_const {c : F''} (hc : c ≠ 0) : (λ (x : E''), x) =o[𝓝 0] (λ x, c) := (is_o_const_iff hc).mpr (continuous_id.tendsto 0) theorem _root_.filter.is_bounded_under.is_O_const (h : is_bounded_under (≤) l (norm ∘ f)) {c : F''} (hc : c ≠ 0) : f =O[l] (λ x, c) := (h.is_O_one ℝ).trans (is_O_const_const _ hc _) theorem is_O_const_of_tendsto {y : E''} (h : tendsto f'' l (𝓝 y)) {c : F''} (hc : c ≠ 0) : f'' =O[l] (λ x, c) := h.norm.is_bounded_under_le.is_O_const hc lemma is_O.is_bounded_under_le {c : F} (h : f =O[l] (λ x, c)) : is_bounded_under (≤) l (norm ∘ f) := let ⟨c', hc'⟩ := h.bound in ⟨c' * ∥c∥, eventually_map.2 hc'⟩ theorem is_O_const_of_ne {c : F''} (hc : c ≠ 0) : f =O[l] (λ x, c) ↔ is_bounded_under (≤) l (norm ∘ f) := ⟨λ h, h.is_bounded_under_le, λ h, h.is_O_const hc⟩ theorem is_O_const_iff {c : F''} : f'' =O[l] (λ x, c) ↔ (c = 0 → f'' =ᶠ[l] 0) ∧ is_bounded_under (≤) l (λ x, ∥f'' x∥) := begin refine ⟨λ h, ⟨λ hc, is_O_zero_right_iff.1 (by rwa ← hc), h.is_bounded_under_le⟩, _⟩, rintro ⟨hcf, hf⟩, rcases eq_or_ne c 0 with hc|hc, exacts [(hcf hc).trans_is_O (is_O_zero _ _), hf.is_O_const hc] end theorem is_O_iff_is_bounded_under_le_div (h : ∀ᶠ x in l, g'' x ≠ 0) : f =O[l] g'' ↔ is_bounded_under (≤) l (λ x, ∥f x∥ / ∥g'' x∥) := begin simp only [is_O_iff, is_bounded_under, is_bounded, eventually_map], exact exists_congr (λ c, eventually_congr $ h.mono $ λ x hx, (div_le_iff $ norm_pos_iff.2 hx).symm) end /-- `(λ x, c) =O[l] f` if and only if `f` is bounded away from zero. -/ lemma is_O_const_left_iff_pos_le_norm {c : E''} (hc : c ≠ 0) : (λ x, c) =O[l] f' ↔ ∃ b, 0 < b ∧ ∀ᶠ x in l, b ≤ ∥f' x∥ := begin split, { intro h, rcases h.exists_pos with ⟨C, hC₀, hC⟩, refine ⟨∥c∥ / C, div_pos (norm_pos_iff.2 hc) hC₀, _⟩, exact hC.bound.mono (λ x, (div_le_iff' hC₀).2) }, { rintro ⟨b, hb₀, hb⟩, refine is_O.of_bound (∥c∥ / b) (hb.mono $ λ x hx, _), rw [div_mul_eq_mul_div, mul_div_assoc], exact le_mul_of_one_le_right (norm_nonneg _) ((one_le_div hb₀).2 hx) } end section variable (𝕜) end theorem is_O.trans_tendsto (hfg : f'' =O[l] g'') (hg : tendsto g'' l (𝓝 0)) : tendsto f'' l (𝓝 0) := (is_o_one_iff ℝ).1 $ hfg.trans_is_o $ (is_o_one_iff ℝ).2 hg theorem is_o.trans_tendsto (hfg : f'' =o[l] g'') (hg : tendsto g'' l (𝓝 0)) : tendsto f'' l (𝓝 0) := hfg.is_O.trans_tendsto hg /-! ### Multiplication by a constant -/ theorem is_O_with_const_mul_self (c : R) (f : α → R) (l : filter α) : is_O_with ∥c∥ l (λ x, c * f x) f := is_O_with_of_le' _ $ λ x, norm_mul_le _ _ theorem is_O_const_mul_self (c : R) (f : α → R) (l : filter α) : (λ x, c * f x) =O[l] f := (is_O_with_const_mul_self c f l).is_O theorem is_O_with.const_mul_left {f : α → R} (h : is_O_with c l f g) (c' : R) : is_O_with (∥c'∥ * c) l (λ x, c' * f x) g := (is_O_with_const_mul_self c' f l).trans h (norm_nonneg c') theorem is_O.const_mul_left {f : α → R} (h : f =O[l] g) (c' : R) : (λ x, c' * f x) =O[l] g := let ⟨c, hc⟩ := h.is_O_with in (hc.const_mul_left c').is_O theorem is_O_with_self_const_mul' (u : Rˣ) (f : α → R) (l : filter α) : is_O_with ∥(↑u⁻¹:R)∥ l f (λ x, ↑u * f x) := (is_O_with_const_mul_self ↑u⁻¹ _ l).congr_left $ λ x, u.inv_mul_cancel_left (f x) theorem is_O_with_self_const_mul (c : 𝕜) (hc : c ≠ 0) (f : α → 𝕜) (l : filter α) : is_O_with ∥c∥⁻¹ l f (λ x, c * f x) := (is_O_with_self_const_mul' (units.mk0 c hc) f l).congr_const $ norm_inv c theorem is_O_self_const_mul' {c : R} (hc : is_unit c) (f : α → R) (l : filter α) : f =O[l] (λ x, c * f x) := let ⟨u, hu⟩ := hc in hu ▸ (is_O_with_self_const_mul' u f l).is_O theorem is_O_self_const_mul (c : 𝕜) (hc : c ≠ 0) (f : α → 𝕜) (l : filter α) : f =O[l] (λ x, c * f x) := is_O_self_const_mul' (is_unit.mk0 c hc) f l theorem is_O_const_mul_left_iff' {f : α → R} {c : R} (hc : is_unit c) : (λ x, c * f x) =O[l] g ↔ f =O[l] g := ⟨(is_O_self_const_mul' hc f l).trans, λ h, h.const_mul_left c⟩ theorem is_O_const_mul_left_iff {f : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) : (λ x, c * f x) =O[l] g ↔ f =O[l] g := is_O_const_mul_left_iff' $ is_unit.mk0 c hc theorem is_o.const_mul_left {f : α → R} (h : f =o[l] g) (c : R) : (λ x, c * f x) =o[l] g := (is_O_const_mul_self c f l).trans_is_o h theorem is_o_const_mul_left_iff' {f : α → R} {c : R} (hc : is_unit c) : (λ x, c * f x) =o[l] g ↔ f =o[l] g := ⟨(is_O_self_const_mul' hc f l).trans_is_o, λ h, h.const_mul_left c⟩ theorem is_o_const_mul_left_iff {f : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) : (λ x, c * f x) =o[l] g ↔ f =o[l] g := is_o_const_mul_left_iff' $ is_unit.mk0 c hc theorem is_O_with.of_const_mul_right {g : α → R} {c : R} (hc' : 0 ≤ c') (h : is_O_with c' l f (λ x, c * g x)) : is_O_with (c' * ∥c∥) l f g := h.trans (is_O_with_const_mul_self c g l) hc' theorem is_O.of_const_mul_right {g : α → R} {c : R} (h : f =O[l] (λ x, c * g x)) : f =O[l] g := let ⟨c, cnonneg, hc⟩ := h.exists_nonneg in (hc.of_const_mul_right cnonneg).is_O theorem is_O_with.const_mul_right' {g : α → R} {u : Rˣ} {c' : ℝ} (hc' : 0 ≤ c') (h : is_O_with c' l f g) : is_O_with (c' * ∥(↑u⁻¹:R)∥) l f (λ x, ↑u * g x) := h.trans (is_O_with_self_const_mul' _ _ _) hc' theorem is_O_with.const_mul_right {g : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) {c' : ℝ} (hc' : 0 ≤ c') (h : is_O_with c' l f g) : is_O_with (c' * ∥c∥⁻¹) l f (λ x, c * g x) := h.trans (is_O_with_self_const_mul c hc g l) hc' theorem is_O.const_mul_right' {g : α → R} {c : R} (hc : is_unit c) (h : f =O[l] g) : f =O[l] (λ x, c * g x) := h.trans (is_O_self_const_mul' hc g l) theorem is_O.const_mul_right {g : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) (h : f =O[l] g) : f =O[l] (λ x, c * g x) := h.const_mul_right' $ is_unit.mk0 c hc theorem is_O_const_mul_right_iff' {g : α → R} {c : R} (hc : is_unit c) : f =O[l] (λ x, c * g x) ↔ f =O[l] g := ⟨λ h, h.of_const_mul_right, λ h, h.const_mul_right' hc⟩ theorem is_O_const_mul_right_iff {g : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) : f =O[l] (λ x, c * g x) ↔ f =O[l] g := is_O_const_mul_right_iff' $ is_unit.mk0 c hc theorem is_o.of_const_mul_right {g : α → R} {c : R} (h : f =o[l] (λ x, c * g x)) : f =o[l] g := h.trans_is_O (is_O_const_mul_self c g l) theorem is_o.const_mul_right' {g : α → R} {c : R} (hc : is_unit c) (h : f =o[l] g) : f =o[l] (λ x, c * g x) := h.trans_is_O (is_O_self_const_mul' hc g l) theorem is_o.const_mul_right {g : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) (h : f =o[l] g) : f =o[l] (λ x, c * g x) := h.const_mul_right' $ is_unit.mk0 c hc theorem is_o_const_mul_right_iff' {g : α → R} {c : R} (hc : is_unit c) : f =o[l] (λ x, c * g x) ↔ f =o[l] g := ⟨λ h, h.of_const_mul_right, λ h, h.const_mul_right' hc⟩ theorem is_o_const_mul_right_iff {g : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) : f =o[l] (λ x, c * g x) ↔ f =o[l] g := is_o_const_mul_right_iff' $ is_unit.mk0 c hc /-! ### Multiplication -/ theorem is_O_with.mul {f₁ f₂ : α → R} {g₁ g₂ : α → 𝕜} {c₁ c₂ : ℝ} (h₁ : is_O_with c₁ l f₁ g₁) (h₂ : is_O_with c₂ l f₂ g₂) : is_O_with (c₁ * c₂) l (λ x, f₁ x * f₂ x) (λ x, g₁ x * g₂ x) := begin unfold is_O_with at *, filter_upwards [h₁, h₂] with _ hx₁ hx₂, apply le_trans (norm_mul_le _ _), convert mul_le_mul hx₁ hx₂ (norm_nonneg _) (le_trans (norm_nonneg _) hx₁) using 1, rw [norm_mul, mul_mul_mul_comm] end theorem is_O.mul {f₁ f₂ : α → R} {g₁ g₂ : α → 𝕜} (h₁ : f₁ =O[l] g₁) (h₂ : f₂ =O[l] g₂) : (λ x, f₁ x * f₂ x) =O[l] (λ x, g₁ x * g₂ x) := let ⟨c, hc⟩ := h₁.is_O_with, ⟨c', hc'⟩ := h₂.is_O_with in (hc.mul hc').is_O theorem is_O.mul_is_o {f₁ f₂ : α → R} {g₁ g₂ : α → 𝕜} (h₁ : f₁ =O[l] g₁) (h₂ : f₂ =o[l] g₂) : (λ x, f₁ x * f₂ x) =o[l] (λ x, g₁ x * g₂ x) := begin unfold is_o at *, intros c cpos, rcases h₁.exists_pos with ⟨c', c'pos, hc'⟩, exact (hc'.mul (h₂ (div_pos cpos c'pos))).congr_const (mul_div_cancel' _ (ne_of_gt c'pos)) end theorem is_o.mul_is_O {f₁ f₂ : α → R} {g₁ g₂ : α → 𝕜} (h₁ : f₁ =o[l] g₁) (h₂ : f₂ =O[l] g₂) : (λ x, f₁ x * f₂ x) =o[l] (λ x, g₁ x * g₂ x) := begin unfold is_o at *, intros c cpos, rcases h₂.exists_pos with ⟨c', c'pos, hc'⟩, exact ((h₁ (div_pos cpos c'pos)).mul hc').congr_const (div_mul_cancel _ (ne_of_gt c'pos)) end theorem is_o.mul {f₁ f₂ : α → R} {g₁ g₂ : α → 𝕜} (h₁ : f₁ =o[l] g₁) (h₂ : f₂ =o[l] g₂) : (λ x, f₁ x * f₂ x) =o[l] (λ x, g₁ x * g₂ x) := h₁.mul_is_O h₂.is_O theorem is_O_with.pow' {f : α → R} {g : α → 𝕜} (h : is_O_with c l f g) : ∀ n : ℕ, is_O_with (nat.cases_on n ∥(1 : R)∥ (λ n, c ^ (n + 1))) l (λ x, f x ^ n) (λ x, g x ^ n) | 0 := by simpa using is_O_with_const_const (1 : R) (@one_ne_zero 𝕜 _ _) l | 1 := by simpa | (n + 2) := by simpa [pow_succ] using h.mul (is_O_with.pow' (n + 1)) theorem is_O_with.pow [norm_one_class R] {f : α → R} {g : α → 𝕜} (h : is_O_with c l f g) : ∀ n : ℕ, is_O_with (c ^ n) l (λ x, f x ^ n) (λ x, g x ^ n) | 0 := by simpa using h.pow' 0 | (n + 1) := h.pow' (n + 1) theorem is_O.pow {f : α → R} {g : α → 𝕜} (h : f =O[l] g) (n : ℕ) : (λ x, f x ^ n) =O[l] (λ x, g x ^ n) := let ⟨C, hC⟩ := h.is_O_with in is_O_iff_is_O_with.2 ⟨_, hC.pow' n⟩ theorem is_o.pow {f : α → R} {g : α → 𝕜} (h : f =o[l] g) {n : ℕ} (hn : 0 < n) : (λ x, f x ^ n) =o[l] (λ x, g x ^ n) := begin cases n, exact hn.false.elim, clear hn, induction n with n ihn, { simpa only [pow_one] }, convert h.mul ihn; simp [pow_succ] end /-! ### Inverse -/ theorem is_O_with.inv_rev {f : α → 𝕜} {g : α → 𝕜'} (h : is_O_with c l f g) (h₀ : ∀ᶠ x in l, f x = 0 → g x = 0) : is_O_with c l (λ x, (g x)⁻¹) (λ x, (f x)⁻¹) := begin refine is_O_with.of_bound (h.bound.mp (h₀.mono $ λ x h₀ hle, _)), cases eq_or_ne (f x) 0 with hx hx, { simp only [hx, h₀ hx, inv_zero, norm_zero, mul_zero] }, { have hc : 0 < c, from pos_of_mul_pos_left ((norm_pos_iff.2 hx).trans_le hle) (norm_nonneg _), replace hle := inv_le_inv_of_le (norm_pos_iff.2 hx) hle, simpa only [norm_inv, mul_inv, ← div_eq_inv_mul, div_le_iff hc] using hle } end theorem is_O.inv_rev {f : α → 𝕜} {g : α → 𝕜'} (h : f =O[l] g) (h₀ : ∀ᶠ x in l, f x = 0 → g x = 0) : (λ x, (g x)⁻¹) =O[l] (λ x, (f x)⁻¹) := let ⟨c, hc⟩ := h.is_O_with in (hc.inv_rev h₀).is_O theorem is_o.inv_rev {f : α → 𝕜} {g : α → 𝕜'} (h : f =o[l] g) (h₀ : ∀ᶠ x in l, f x = 0 → g x = 0) : (λ x, (g x)⁻¹) =o[l] (λ x, (f x)⁻¹) := is_o.of_is_O_with $ λ c hc, (h.def' hc).inv_rev h₀ /-! ### Scalar multiplication -/ section smul_const variables [normed_space 𝕜 E'] theorem is_O_with.const_smul_left (h : is_O_with c l f' g) (c' : 𝕜) : is_O_with (∥c'∥ * c) l (λ x, c' • f' x) g := is_O_with.of_norm_left $ by simpa only [← norm_smul, norm_norm] using h.norm_left.const_mul_left (∥c'∥) lemma is_O.const_smul_left (h : f' =O[l] g) (c : 𝕜) : (c • f') =O[l] g := let ⟨b, hb⟩ := h.is_O_with in (hb.const_smul_left _).is_O lemma is_o.const_smul_left (h : f' =o[l] g) (c : 𝕜) : (c • f') =o[l] g := is_o.of_norm_left $ by simpa only [← norm_smul] using h.norm_left.const_mul_left (∥c∥) theorem is_O_const_smul_left {c : 𝕜} (hc : c ≠ 0) : (λ x, c • f' x) =O[l] g ↔ f' =O[l] g := begin have cne0 : ∥c∥ ≠ 0, from mt norm_eq_zero.mp hc, rw [←is_O_norm_left], simp only [norm_smul], rw [is_O_const_mul_left_iff cne0, is_O_norm_left], end theorem is_o_const_smul_left {c : 𝕜} (hc : c ≠ 0) : (λ x, c • f' x) =o[l] g ↔ f' =o[l] g := begin have cne0 : ∥c∥ ≠ 0, from mt norm_eq_zero.mp hc, rw [←is_o_norm_left], simp only [norm_smul], rw [is_o_const_mul_left_iff cne0, is_o_norm_left] end theorem is_O_const_smul_right {c : 𝕜} (hc : c ≠ 0) : f =O[l] (λ x, c • f' x) ↔ f =O[l] f' := begin have cne0 : ∥c∥ ≠ 0, from mt norm_eq_zero.mp hc, rw [←is_O_norm_right], simp only [norm_smul], rw [is_O_const_mul_right_iff cne0, is_O_norm_right] end theorem is_o_const_smul_right {c : 𝕜} (hc : c ≠ 0) : f =o[l] (λ x, c • f' x) ↔ f =o[l] f' := begin have cne0 : ∥c∥ ≠ 0, from mt norm_eq_zero.mp hc, rw [←is_o_norm_right], simp only [norm_smul], rw [is_o_const_mul_right_iff cne0, is_o_norm_right] end end smul_const section smul variables [normed_space 𝕜 E'] [normed_space 𝕜' F'] {k₁ : α → 𝕜} {k₂ : α → 𝕜'} theorem is_O_with.smul (h₁ : is_O_with c l k₁ k₂) (h₂ : is_O_with c' l f' g') : is_O_with (c * c') l (λ x, k₁ x • f' x) (λ x, k₂ x • g' x) := by refine ((h₁.norm_norm.mul h₂.norm_norm).congr rfl _ _).of_norm_norm; by intros; simp only [norm_smul] theorem is_O.smul (h₁ : k₁ =O[l] k₂) (h₂ : f' =O[l] g') : (λ x, k₁ x • f' x) =O[l] (λ x, k₂ x • g' x) := by refine ((h₁.norm_norm.mul h₂.norm_norm).congr _ _).of_norm_norm; by intros; simp only [norm_smul] theorem is_O.smul_is_o (h₁ : k₁ =O[l] k₂) (h₂ : f' =o[l] g') : (λ x, k₁ x • f' x) =o[l] (λ x, k₂ x • g' x) := by refine ((h₁.norm_norm.mul_is_o h₂.norm_norm).congr _ _).of_norm_norm; by intros; simp only [norm_smul] theorem is_o.smul_is_O (h₁ : k₁ =o[l] k₂) (h₂ : f' =O[l] g') : (λ x, k₁ x • f' x) =o[l] (λ x, k₂ x • g' x) := by refine ((h₁.norm_norm.mul_is_O h₂.norm_norm).congr _ _).of_norm_norm; by intros; simp only [norm_smul] theorem is_o.smul (h₁ : k₁ =o[l] k₂) (h₂ : f' =o[l] g') : (λ x, k₁ x • f' x) =o[l] (λ x, k₂ x • g' x) := by refine ((h₁.norm_norm.mul h₂.norm_norm).congr _ _).of_norm_norm; by intros; simp only [norm_smul] end smul /-! ### Sum -/ section sum variables {ι : Type*} {A : ι → α → E'} {C : ι → ℝ} {s : finset ι} theorem is_O_with.sum (h : ∀ i ∈ s, is_O_with (C i) l (A i) g) : is_O_with (∑ i in s, C i) l (λ x, ∑ i in s, A i x) g := begin induction s using finset.induction_on with i s is IH, { simp only [is_O_with_zero', finset.sum_empty, forall_true_iff] }, { simp only [is, finset.sum_insert, not_false_iff], exact (h _ (finset.mem_insert_self i s)).add (IH (λ j hj, h _ (finset.mem_insert_of_mem hj))) } end theorem is_O.sum (h : ∀ i ∈ s, A i =O[l] g) : (λ x, ∑ i in s, A i x) =O[l] g := begin unfold is_O at *, choose! C hC using h, exact ⟨_, is_O_with.sum hC⟩, end theorem is_o.sum (h : ∀ i ∈ s, (A i) =o[l] g') : (λ x, ∑ i in s, A i x) =o[l] g' := begin induction s using finset.induction_on with i s is IH, { simp only [is_o_zero, finset.sum_empty, forall_true_iff] }, { simp only [is, finset.sum_insert, not_false_iff], exact (h _ (finset.mem_insert_self i s)).add (IH (λ j hj, h _ (finset.mem_insert_of_mem hj))) } end end sum /-! ### Relation between `f = o(g)` and `f / g → 0` -/ theorem is_o.tendsto_div_nhds_zero {f g : α → 𝕜} (h : f =o[l] g) : tendsto (λ x, f x / (g x)) l (𝓝 0) := (is_o_one_iff 𝕜).mp $ calc (λ x, f x / g x) =o[l] (λ x, g x / g x) : by simpa only [div_eq_mul_inv] using h.mul_is_O (is_O_refl _ _) ... =O[l] (λ x, (1 : 𝕜)) : is_O_of_le _ (λ x, by simp [div_self_le_one]) theorem is_o.tendsto_inv_smul_nhds_zero [normed_space 𝕜 E'] {f : α → E'} {g : α → 𝕜} {l : filter α} (h : f =o[l] g) : tendsto (λ x, (g x)⁻¹ • f x) l (𝓝 0) := by simpa only [div_eq_inv_mul, ← norm_inv, ← norm_smul, ← tendsto_zero_iff_norm_tendsto_zero] using h.norm_norm.tendsto_div_nhds_zero theorem is_o_iff_tendsto' {f g : α → 𝕜} (hgf : ∀ᶠ x in l, g x = 0 → f x = 0) : f =o[l] g ↔ tendsto (λ x, f x / (g x)) l (𝓝 0) := ⟨is_o.tendsto_div_nhds_zero, λ h, (((is_o_one_iff _).mpr h).mul_is_O (is_O_refl g l)).congr' (hgf.mono $ λ x, div_mul_cancel_of_imp) (eventually_of_forall $ λ x, one_mul _)⟩ theorem is_o_iff_tendsto {f g : α → 𝕜} (hgf : ∀ x, g x = 0 → f x = 0) : f =o[l] g ↔ tendsto (λ x, f x / (g x)) l (𝓝 0) := is_o_iff_tendsto' (eventually_of_forall hgf) alias is_o_iff_tendsto' ↔ _ is_o_of_tendsto' alias is_o_iff_tendsto ↔ _ is_o_of_tendsto lemma is_o_const_left_of_ne {c : E''} (hc : c ≠ 0) : (λ x, c) =o[l] g ↔ tendsto (λ x, ∥g x∥) l at_top := begin simp only [← is_o_one_left_iff ℝ], exact ⟨(is_O_const_const (1 : ℝ) hc l).trans_is_o, (is_O_const_one ℝ c l).trans_is_o⟩ end @[simp] lemma is_o_const_left {c : E''} : (λ x, c) =o[l] g'' ↔ c = 0 ∨ tendsto (norm ∘ g'') l at_top := begin rcases eq_or_ne c 0 with rfl | hc, { simp only [is_o_zero, eq_self_iff_true, true_or] }, { simp only [hc, false_or, is_o_const_left_of_ne hc] } end @[simp] theorem is_o_const_const_iff [ne_bot l] {d : E''} {c : F''} : (λ x, d) =o[l] (λ x, c) ↔ d = 0 := have ¬tendsto (function.const α ∥c∥) l at_top, from not_tendsto_at_top_of_tendsto_nhds tendsto_const_nhds, by simp [function.const, this] @[simp] lemma is_o_pure {x} : f'' =o[pure x] g'' ↔ f'' x = 0 := calc f'' =o[pure x] g'' ↔ (λ y : α, f'' x) =o[pure x] (λ _, g'' x) : is_o_congr rfl rfl ... ↔ f'' x = 0 : is_o_const_const_iff lemma is_o_const_id_comap_norm_at_top (c : F'') : (λ x : E'', c) =o[comap norm at_top] id := is_o_const_left.2 $ or.inr tendsto_comap lemma is_o_const_id_at_top (c : E'') : (λ x : ℝ, c) =o[at_top] id := is_o_const_left.2 $ or.inr tendsto_abs_at_top_at_top lemma is_o_const_id_at_bot (c : E'') : (λ x : ℝ, c) =o[at_bot] id := is_o_const_left.2 $ or.inr tendsto_abs_at_bot_at_top /-! ### Eventually (u / v) * v = u If `u` and `v` are linked by an `is_O_with` relation, then we eventually have `(u / v) * v = u`, even if `v` vanishes. -/ section eventually_mul_div_cancel variables {u v : α → 𝕜} lemma is_O_with.eventually_mul_div_cancel (h : is_O_with c l u v) : (u / v) * v =ᶠ[l] u := eventually.mono h.bound (λ y hy, div_mul_cancel_of_imp $ λ hv, by simpa [hv] using hy) /-- If `u = O(v)` along `l`, then `(u / v) * v = u` eventually at `l`. -/ lemma is_O.eventually_mul_div_cancel (h : u =O[l] v) : (u / v) * v =ᶠ[l] u := let ⟨c, hc⟩ := h.is_O_with in hc.eventually_mul_div_cancel /-- If `u = o(v)` along `l`, then `(u / v) * v = u` eventually at `l`. -/ lemma is_o.eventually_mul_div_cancel (h : u =o[l] v) : (u / v) * v =ᶠ[l] u := (h.forall_is_O_with zero_lt_one).eventually_mul_div_cancel end eventually_mul_div_cancel /-! ### Equivalent definitions of the form `∃ φ, u =ᶠ[l] φ * v` in a `normed_field`. -/ section exists_mul_eq variables {u v : α → 𝕜} /-- If `∥φ∥` is eventually bounded by `c`, and `u =ᶠ[l] φ * v`, then we have `is_O_with c u v l`. This does not require any assumptions on `c`, which is why we keep this version along with `is_O_with_iff_exists_eq_mul`. -/ lemma is_O_with_of_eq_mul (φ : α → 𝕜) (hφ : ∀ᶠ x in l, ∥φ x∥ ≤ c) (h : u =ᶠ[l] φ * v) : is_O_with c l u v := begin unfold is_O_with, refine h.symm.rw (λ x a, ∥a∥ ≤ c * ∥v x∥) (hφ.mono $ λ x hx, _), simp only [norm_mul, pi.mul_apply], exact mul_le_mul_of_nonneg_right hx (norm_nonneg _) end lemma is_O_with_iff_exists_eq_mul (hc : 0 ≤ c) : is_O_with c l u v ↔ ∃ (φ : α → 𝕜) (hφ : ∀ᶠ x in l, ∥φ x∥ ≤ c), u =ᶠ[l] φ * v := begin split, { intro h, use (λ x, u x / v x), refine ⟨eventually.mono h.bound (λ y hy, _), h.eventually_mul_div_cancel.symm⟩, simpa using div_le_of_nonneg_of_le_mul (norm_nonneg _) hc hy }, { rintros ⟨φ, hφ, h⟩, exact is_O_with_of_eq_mul φ hφ h } end lemma is_O_with.exists_eq_mul (h : is_O_with c l u v) (hc : 0 ≤ c) : ∃ (φ : α → 𝕜) (hφ : ∀ᶠ x in l, ∥φ x∥ ≤ c), u =ᶠ[l] φ * v := (is_O_with_iff_exists_eq_mul hc).mp h lemma is_O_iff_exists_eq_mul : u =O[l] v ↔ ∃ (φ : α → 𝕜) (hφ : l.is_bounded_under (≤) (norm ∘ φ)), u =ᶠ[l] φ * v := begin split, { rintros h, rcases h.exists_nonneg with ⟨c, hnnc, hc⟩, rcases hc.exists_eq_mul hnnc with ⟨φ, hφ, huvφ⟩, exact ⟨φ, ⟨c, hφ⟩, huvφ⟩ }, { rintros ⟨φ, ⟨c, hφ⟩, huvφ⟩, exact is_O_iff_is_O_with.2 ⟨c, is_O_with_of_eq_mul φ hφ huvφ⟩ } end alias is_O_iff_exists_eq_mul ↔ is_O.exists_eq_mul _ lemma is_o_iff_exists_eq_mul : u =o[l] v ↔ ∃ (φ : α → 𝕜) (hφ : tendsto φ l (𝓝 0)), u =ᶠ[l] φ * v := begin split, { exact λ h, ⟨λ x, u x / v x, h.tendsto_div_nhds_zero, h.eventually_mul_div_cancel.symm⟩ }, { unfold is_o, rintros ⟨φ, hφ, huvφ⟩ c hpos, rw normed_group.tendsto_nhds_zero at hφ, exact is_O_with_of_eq_mul _ ((hφ c hpos).mono $ λ x, le_of_lt) huvφ } end alias is_o_iff_exists_eq_mul ↔ is_o.exists_eq_mul _ end exists_mul_eq /-! ### Miscellanous lemmas -/ theorem div_is_bounded_under_of_is_O {α : Type*} {l : filter α} {f g : α → 𝕜} (h : f =O[l] g) : is_bounded_under (≤) l (λ x, ∥f x / g x∥) := begin obtain ⟨c, h₀, hc⟩ := h.exists_nonneg, refine ⟨c, eventually_map.2 (hc.bound.mono (λ x hx, _))⟩, rw [norm_div], exact div_le_of_nonneg_of_le_mul (norm_nonneg _) h₀ hx, end theorem is_O_iff_div_is_bounded_under {α : Type*} {l : filter α} {f g : α → 𝕜} (hgf : ∀ᶠ x in l, g x = 0 → f x = 0) : f =O[l] g ↔ is_bounded_under (≤) l (λ x, ∥f x / g x∥) := begin refine ⟨div_is_bounded_under_of_is_O, λ h, _⟩, obtain ⟨c, hc⟩ := h, simp only [eventually_map, norm_div] at hc, refine is_O.of_bound c (hc.mp $ hgf.mono (λ x hx₁ hx₂, _)), by_cases hgx : g x = 0, { simp [hx₁ hgx, hgx] }, { exact (div_le_iff (norm_pos_iff.2 hgx)).mp hx₂ }, end theorem is_O_of_div_tendsto_nhds {α : Type*} {l : filter α} {f g : α → 𝕜} (hgf : ∀ᶠ x in l, g x = 0 → f x = 0) (c : 𝕜) (H : filter.tendsto (f / g) l (𝓝 c)) : f =O[l] g := (is_O_iff_div_is_bounded_under hgf).2 $ H.norm.is_bounded_under_le lemma is_o.tendsto_zero_of_tendsto {α E 𝕜 : Type*} [normed_group E] [normed_field 𝕜] {u : α → E} {v : α → 𝕜} {l : filter α} {y : 𝕜} (huv : u =o[l] v) (hv : tendsto v l (𝓝 y)) : tendsto u l (𝓝 0) := begin suffices h : u =o[l] (λ x, (1 : 𝕜)), { rwa is_o_one_iff at h }, exact huv.trans_is_O (hv.is_O_one 𝕜), end theorem is_o_pow_pow {m n : ℕ} (h : m < n) : (λ x : 𝕜, x ^ n) =o[𝓝 0] (λ x, x ^ m) := begin rcases lt_iff_exists_add.1 h with ⟨p, hp0 : 0 < p, rfl⟩, suffices : (λ x : 𝕜, x ^ m * x ^ p) =o[𝓝 0] (λ x, x ^ m * 1 ^ p), by simpa only [pow_add, one_pow, mul_one], exact is_O.mul_is_o (is_O_refl _ _) (is_o.pow ((is_o_one_iff _).2 tendsto_id) hp0) end theorem is_o_norm_pow_norm_pow {m n : ℕ} (h : m < n) : (λ x : E', ∥x∥^n) =o[𝓝 0] (λ x, ∥x∥^m) := (is_o_pow_pow h).comp_tendsto tendsto_norm_zero theorem is_o_pow_id {n : ℕ} (h : 1 < n) : (λ x : 𝕜, x^n) =o[𝓝 0] (λ x, x) := by { convert is_o_pow_pow h, simp only [pow_one] } theorem is_o_norm_pow_id {n : ℕ} (h : 1 < n) : (λ x : E', ∥x∥^n) =o[𝓝 0] (λ x, x) := by simpa only [pow_one, is_o_norm_right] using @is_o_norm_pow_norm_pow E' _ _ _ h theorem is_O_with.right_le_sub_of_lt_1 {f₁ f₂ : α → E'} (h : is_O_with c l f₁ f₂) (hc : c < 1) : is_O_with (1 / (1 - c)) l f₂ (λx, f₂ x - f₁ x) := is_O_with.of_bound $ mem_of_superset h.bound $ λ x hx, begin simp only [mem_set_of_eq] at hx ⊢, rw [mul_comm, one_div, ← div_eq_mul_inv, le_div_iff, mul_sub, mul_one, mul_comm], { exact le_trans (sub_le_sub_left hx _) (norm_sub_norm_le _ _) }, { exact sub_pos.2 hc } end theorem is_O_with.right_le_add_of_lt_1 {f₁ f₂ : α → E'} (h : is_O_with c l f₁ f₂) (hc : c < 1) : is_O_with (1 / (1 - c)) l f₂ (λx, f₁ x + f₂ x) := (h.neg_right.right_le_sub_of_lt_1 hc).neg_right.of_neg_left.congr rfl (λ x, rfl) (λ x, by rw [neg_sub, sub_neg_eq_add]) theorem is_o.right_is_O_sub {f₁ f₂ : α → E'} (h : f₁ =o[l] f₂) : f₂ =O[l] (λx, f₂ x - f₁ x) := ((h.def' one_half_pos).right_le_sub_of_lt_1 one_half_lt_one).is_O theorem is_o.right_is_O_add {f₁ f₂ : α → E'} (h : f₁ =o[l] f₂) : f₂ =O[l] (λx, f₁ x + f₂ x) := ((h.def' one_half_pos).right_le_add_of_lt_1 one_half_lt_one).is_O /-- If `f x = O(g x)` along `cofinite`, then there exists a positive constant `C` such that `∥f x∥ ≤ C * ∥g x∥` whenever `g x ≠ 0`. -/ theorem bound_of_is_O_cofinite (h : f =O[cofinite] g'') : ∃ C > 0, ∀ ⦃x⦄, g'' x ≠ 0 → ∥f x∥ ≤ C * ∥g'' x∥ := begin rcases h.exists_pos with ⟨C, C₀, hC⟩, rw [is_O_with, eventually_cofinite] at hC, rcases (hC.to_finset.image (λ x, ∥f x∥ / ∥g'' x∥)).exists_le with ⟨C', hC'⟩, have : ∀ x, C * ∥g'' x∥ < ∥f x∥ → ∥f x∥ / ∥g'' x∥ ≤ C', by simpa using hC', refine ⟨max C C', lt_max_iff.2 (or.inl C₀), λ x h₀, _⟩, rw [max_mul_of_nonneg _ _ (norm_nonneg _), le_max_iff, or_iff_not_imp_left, not_le], exact λ hx, (div_le_iff (norm_pos_iff.2 h₀)).1 (this _ hx) end theorem is_O_cofinite_iff (h : ∀ x, g'' x = 0 → f'' x = 0) : f'' =O[cofinite] g'' ↔ ∃ C, ∀ x, ∥f'' x∥ ≤ C * ∥g'' x∥ := ⟨λ h', let ⟨C, C₀, hC⟩ := bound_of_is_O_cofinite h' in ⟨C, λ x, if hx : g'' x = 0 then by simp [h _ hx, hx] else hC hx⟩, λ h, (is_O_top.2 h).mono le_top⟩ theorem bound_of_is_O_nat_at_top {f : ℕ → E} {g'' : ℕ → E''} (h : f =O[at_top] g'') : ∃ C > 0, ∀ ⦃x⦄, g'' x ≠ 0 → ∥f x∥ ≤ C * ∥g'' x∥ := bound_of_is_O_cofinite $ by rwa nat.cofinite_eq_at_top theorem is_O_nat_at_top_iff {f : ℕ → E''} {g : ℕ → F''} (h : ∀ x, g x = 0 → f x = 0) : f =O[at_top] g ↔ ∃ C, ∀ x, ∥f x∥ ≤ C * ∥g x∥ := by rw [← nat.cofinite_eq_at_top, is_O_cofinite_iff h] theorem is_O_one_nat_at_top_iff {f : ℕ → E''} : f =O[at_top] (λ n, 1 : ℕ → ℝ) ↔ ∃ C, ∀ n, ∥f n∥ ≤ C := iff.trans (is_O_nat_at_top_iff (λ n h, (one_ne_zero h).elim)) $ by simp only [norm_one, mul_one] theorem is_O_with_pi {ι : Type*} [fintype ι] {E' : ι → Type*} [Π i, normed_group (E' i)] {f : α → Π i, E' i} {C : ℝ} (hC : 0 ≤ C) : is_O_with C l f g' ↔ ∀ i, is_O_with C l (λ x, f x i) g' := have ∀ x, 0 ≤ C * ∥g' x∥, from λ x, mul_nonneg hC (norm_nonneg _), by simp only [is_O_with_iff, pi_norm_le_iff (this _), eventually_all] @[simp] theorem is_O_pi {ι : Type*} [fintype ι] {E' : ι → Type*} [Π i, normed_group (E' i)] {f : α → Π i, E' i} : f =O[l] g' ↔ ∀ i, (λ x, f x i) =O[l] g' := begin simp only [is_O_iff_eventually_is_O_with, ← eventually_all], exact eventually_congr (eventually_at_top.2 ⟨0, λ c, is_O_with_pi⟩) end @[simp] theorem is_o_pi {ι : Type*} [fintype ι] {E' : ι → Type*} [Π i, normed_group (E' i)] {f : α → Π i, E' i} : f =o[l] g' ↔ ∀ i, (λ x, f x i) =o[l] g' := begin simp only [is_o, is_O_with_pi, le_of_lt] { contextual := tt }, exact ⟨λ h i c hc, h hc i, λ h c hc i, h i hc⟩ end end asymptotics open asymptotics lemma summable_of_is_O {ι E} [normed_group E] [complete_space E] {f : ι → E} {g : ι → ℝ} (hg : summable g) (h : f =O[cofinite] g) : summable f := let ⟨C, hC⟩ := h.is_O_with in summable_of_norm_bounded_eventually (λ x, C * ∥g x∥) (hg.abs.mul_left _) hC.bound lemma summable_of_is_O_nat {E} [normed_group E] [complete_space E] {f : ℕ → E} {g : ℕ → ℝ} (hg : summable g) (h : f =O[at_top] g) : summable f := summable_of_is_O hg $ nat.cofinite_eq_at_top.symm ▸ h namespace local_homeomorph variables {α : Type*} {β : Type*} [topological_space α] [topological_space β] variables {E : Type*} [has_norm E] {F : Type*} [has_norm F] /-- Transfer `is_O_with` over a `local_homeomorph`. -/ lemma is_O_with_congr (e : local_homeomorph α β) {b : β} (hb : b ∈ e.target) {f : β → E} {g : β → F} {C : ℝ} : is_O_with C (𝓝 b) f g ↔ is_O_with C (𝓝 (e.symm b)) (f ∘ e) (g ∘ e) := ⟨λ h, h.comp_tendsto $ by { convert e.continuous_at (e.map_target hb), exact (e.right_inv hb).symm }, λ h, (h.comp_tendsto (e.continuous_at_symm hb)).congr' rfl ((e.eventually_right_inverse hb).mono $ λ x hx, congr_arg f hx) ((e.eventually_right_inverse hb).mono $ λ x hx, congr_arg g hx)⟩ /-- Transfer `is_O` over a `local_homeomorph`. -/ lemma is_O_congr (e : local_homeomorph α β) {b : β} (hb : b ∈ e.target) {f : β → E} {g : β → F} : f =O[𝓝 b] g ↔ (f ∘ e) =O[𝓝 (e.symm b)] (g ∘ e) := by { unfold is_O, exact exists_congr (λ C, e.is_O_with_congr hb) } /-- Transfer `is_o` over a `local_homeomorph`. -/ lemma is_o_congr (e : local_homeomorph α β) {b : β} (hb : b ∈ e.target) {f : β → E} {g : β → F} : f =o[𝓝 b] g ↔ (f ∘ e) =o[𝓝 (e.symm b)] (g ∘ e) := by { unfold is_o, exact forall₂_congr (λ c hc, e.is_O_with_congr hb) } end local_homeomorph namespace homeomorph variables {α : Type*} {β : Type*} [topological_space α] [topological_space β] variables {E : Type*} [has_norm E] {F : Type*} [has_norm F] open asymptotics /-- Transfer `is_O_with` over a `homeomorph`. -/ lemma is_O_with_congr (e : α ≃ₜ β) {b : β} {f : β → E} {g : β → F} {C : ℝ} : is_O_with C (𝓝 b) f g ↔ is_O_with C (𝓝 (e.symm b)) (f ∘ e) (g ∘ e) := e.to_local_homeomorph.is_O_with_congr trivial /-- Transfer `is_O` over a `homeomorph`. -/ lemma is_O_congr (e : α ≃ₜ β) {b : β} {f : β → E} {g : β → F} : f =O[𝓝 b] g ↔ (f ∘ e) =O[𝓝 (e.symm b)] (g ∘ e) := by { unfold is_O, exact exists_congr (λ C, e.is_O_with_congr) } /-- Transfer `is_o` over a `homeomorph`. -/ lemma is_o_congr (e : α ≃ₜ β) {b : β} {f : β → E} {g : β → F} : f =o[𝓝 b] g ↔ (f ∘ e) =o[𝓝 (e.symm b)] (g ∘ e) := by { unfold is_o, exact forall₂_congr (λ c hc, e.is_O_with_congr) } end homeomorph
6436991279728566a2deddb08714cbadb0b5bda0
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/special_functions/trigonometric/inverse_deriv.lean
897138e6344f93221f9c7bd82adb86b4134cbcc1
[ "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
7,779
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Benjamin Davidson -/ import analysis.special_functions.trigonometric.inverse import analysis.special_functions.trigonometric.deriv /-! # derivatives of the inverse trigonometric functions Derivatives of `arcsin` and `arccos`. -/ noncomputable theory open_locale classical topological_space filter open set filter open_locale real namespace real section arcsin lemma deriv_arcsin_aux {x : ℝ} (h₁ : x ≠ -1) (h₂ : x ≠ 1) : has_strict_deriv_at arcsin (1 / sqrt (1 - x ^ 2)) x ∧ cont_diff_at ℝ ⊤ arcsin x := begin cases h₁.lt_or_lt with h₁ h₁, { have : 1 - x ^ 2 < 0, by nlinarith [h₁], rw [sqrt_eq_zero'.2 this.le, div_zero], have : arcsin =ᶠ[𝓝 x] λ _, -(π / 2) := (gt_mem_nhds h₁).mono (λ y hy, arcsin_of_le_neg_one hy.le), exact ⟨(has_strict_deriv_at_const _ _).congr_of_eventually_eq this.symm, cont_diff_at_const.congr_of_eventually_eq this⟩ }, cases h₂.lt_or_lt with h₂ h₂, { have : 0 < sqrt (1 - x ^ 2) := sqrt_pos.2 (by nlinarith [h₁, h₂]), simp only [← cos_arcsin h₁.le h₂.le, one_div] at this ⊢, exact ⟨sin_local_homeomorph.has_strict_deriv_at_symm ⟨h₁, h₂⟩ this.ne' (has_strict_deriv_at_sin _), sin_local_homeomorph.cont_diff_at_symm_deriv this.ne' ⟨h₁, h₂⟩ (has_deriv_at_sin _) cont_diff_sin.cont_diff_at⟩ }, { have : 1 - x ^ 2 < 0, by nlinarith [h₂], rw [sqrt_eq_zero'.2 this.le, div_zero], have : arcsin =ᶠ[𝓝 x] λ _, π / 2 := (lt_mem_nhds h₂).mono (λ y hy, arcsin_of_one_le hy.le), exact ⟨(has_strict_deriv_at_const _ _).congr_of_eventually_eq this.symm, cont_diff_at_const.congr_of_eventually_eq this⟩ } end lemma has_strict_deriv_at_arcsin {x : ℝ} (h₁ : x ≠ -1) (h₂ : x ≠ 1) : has_strict_deriv_at arcsin (1 / sqrt (1 - x ^ 2)) x := (deriv_arcsin_aux h₁ h₂).1 lemma has_deriv_at_arcsin {x : ℝ} (h₁ : x ≠ -1) (h₂ : x ≠ 1) : has_deriv_at arcsin (1 / sqrt (1 - x ^ 2)) x := (has_strict_deriv_at_arcsin h₁ h₂).has_deriv_at lemma cont_diff_at_arcsin {x : ℝ} (h₁ : x ≠ -1) (h₂ : x ≠ 1) {n : with_top ℕ} : cont_diff_at ℝ n arcsin x := (deriv_arcsin_aux h₁ h₂).2.of_le le_top lemma has_deriv_within_at_arcsin_Ici {x : ℝ} (h : x ≠ -1) : has_deriv_within_at arcsin (1 / sqrt (1 - x ^ 2)) (Ici x) x := begin rcases em (x = 1) with (rfl|h'), { convert (has_deriv_within_at_const _ _ (π / 2)).congr _ _; simp [arcsin_of_one_le] { contextual := tt } }, { exact (has_deriv_at_arcsin h h').has_deriv_within_at } end lemma has_deriv_within_at_arcsin_Iic {x : ℝ} (h : x ≠ 1) : has_deriv_within_at arcsin (1 / sqrt (1 - x ^ 2)) (Iic x) x := begin rcases em (x = -1) with (rfl|h'), { convert (has_deriv_within_at_const _ _ (-(π / 2))).congr _ _; simp [arcsin_of_le_neg_one] { contextual := tt } }, { exact (has_deriv_at_arcsin h' h).has_deriv_within_at } end lemma differentiable_within_at_arcsin_Ici {x : ℝ} : differentiable_within_at ℝ arcsin (Ici x) x ↔ x ≠ -1 := begin refine ⟨_, λ h, (has_deriv_within_at_arcsin_Ici h).differentiable_within_at⟩, rintro h rfl, have : sin ∘ arcsin =ᶠ[𝓝[≥] (-1 : ℝ)] id, { filter_upwards [Icc_mem_nhds_within_Ici ⟨le_rfl, neg_lt_self (@zero_lt_one ℝ _ _)⟩] with x using sin_arcsin', }, have := h.has_deriv_within_at.sin.congr_of_eventually_eq this.symm (by simp), simpa using (unique_diff_on_Ici _ _ left_mem_Ici).eq_deriv _ this (has_deriv_within_at_id _ _) end lemma differentiable_within_at_arcsin_Iic {x : ℝ} : differentiable_within_at ℝ arcsin (Iic x) x ↔ x ≠ 1 := begin refine ⟨λ h, _, λ h, (has_deriv_within_at_arcsin_Iic h).differentiable_within_at⟩, rw [← neg_neg x, ← image_neg_Ici] at h, have := (h.comp (-x) differentiable_within_at_id.neg (maps_to_image _ _)).neg, simpa [(∘), differentiable_within_at_arcsin_Ici] using this end lemma differentiable_at_arcsin {x : ℝ} : differentiable_at ℝ arcsin x ↔ x ≠ -1 ∧ x ≠ 1 := ⟨λ h, ⟨differentiable_within_at_arcsin_Ici.1 h.differentiable_within_at, differentiable_within_at_arcsin_Iic.1 h.differentiable_within_at⟩, λ h, (has_deriv_at_arcsin h.1 h.2).differentiable_at⟩ @[simp] lemma deriv_arcsin : deriv arcsin = λ x, 1 / sqrt (1 - x ^ 2) := begin funext x, by_cases h : x ≠ -1 ∧ x ≠ 1, { exact (has_deriv_at_arcsin h.1 h.2).deriv }, { rw [deriv_zero_of_not_differentiable_at (mt differentiable_at_arcsin.1 h)], simp only [not_and_distrib, ne.def, not_not] at h, rcases h with (rfl|rfl); simp } end lemma differentiable_on_arcsin : differentiable_on ℝ arcsin {-1, 1}ᶜ := λ x hx, (differentiable_at_arcsin.2 ⟨λ h, hx (or.inl h), λ h, hx (or.inr h)⟩).differentiable_within_at lemma cont_diff_on_arcsin {n : with_top ℕ} : cont_diff_on ℝ n arcsin {-1, 1}ᶜ := λ x hx, (cont_diff_at_arcsin (mt or.inl hx) (mt or.inr hx)).cont_diff_within_at lemma cont_diff_at_arcsin_iff {x : ℝ} {n : with_top ℕ} : cont_diff_at ℝ n arcsin x ↔ n = 0 ∨ (x ≠ -1 ∧ x ≠ 1) := ⟨λ h, or_iff_not_imp_left.2 $ λ hn, differentiable_at_arcsin.1 $ h.differentiable_at $ with_top.one_le_iff_pos.2 (pos_iff_ne_zero.2 hn), λ h, h.elim (λ hn, hn.symm ▸ (cont_diff_zero.2 continuous_arcsin).cont_diff_at) $ λ hx, cont_diff_at_arcsin hx.1 hx.2⟩ end arcsin section arccos lemma has_strict_deriv_at_arccos {x : ℝ} (h₁ : x ≠ -1) (h₂ : x ≠ 1) : has_strict_deriv_at arccos (-(1 / sqrt (1 - x ^ 2))) x := (has_strict_deriv_at_arcsin h₁ h₂).const_sub (π / 2) lemma has_deriv_at_arccos {x : ℝ} (h₁ : x ≠ -1) (h₂ : x ≠ 1) : has_deriv_at arccos (-(1 / sqrt (1 - x ^ 2))) x := (has_deriv_at_arcsin h₁ h₂).const_sub (π / 2) lemma cont_diff_at_arccos {x : ℝ} (h₁ : x ≠ -1) (h₂ : x ≠ 1) {n : with_top ℕ} : cont_diff_at ℝ n arccos x := cont_diff_at_const.sub (cont_diff_at_arcsin h₁ h₂) lemma has_deriv_within_at_arccos_Ici {x : ℝ} (h : x ≠ -1) : has_deriv_within_at arccos (-(1 / sqrt (1 - x ^ 2))) (Ici x) x := (has_deriv_within_at_arcsin_Ici h).const_sub _ lemma has_deriv_within_at_arccos_Iic {x : ℝ} (h : x ≠ 1) : has_deriv_within_at arccos (-(1 / sqrt (1 - x ^ 2))) (Iic x) x := (has_deriv_within_at_arcsin_Iic h).const_sub _ lemma differentiable_within_at_arccos_Ici {x : ℝ} : differentiable_within_at ℝ arccos (Ici x) x ↔ x ≠ -1 := (differentiable_within_at_const_sub_iff _).trans differentiable_within_at_arcsin_Ici lemma differentiable_within_at_arccos_Iic {x : ℝ} : differentiable_within_at ℝ arccos (Iic x) x ↔ x ≠ 1 := (differentiable_within_at_const_sub_iff _).trans differentiable_within_at_arcsin_Iic lemma differentiable_at_arccos {x : ℝ} : differentiable_at ℝ arccos x ↔ x ≠ -1 ∧ x ≠ 1 := (differentiable_at_const_sub_iff _).trans differentiable_at_arcsin @[simp] lemma deriv_arccos : deriv arccos = λ x, -(1 / sqrt (1 - x ^ 2)) := funext $ λ x, (deriv_const_sub _).trans $ by simp only [deriv_arcsin] lemma differentiable_on_arccos : differentiable_on ℝ arccos {-1, 1}ᶜ := differentiable_on_arcsin.const_sub _ lemma cont_diff_on_arccos {n : with_top ℕ} : cont_diff_on ℝ n arccos {-1, 1}ᶜ := cont_diff_on_const.sub cont_diff_on_arcsin lemma cont_diff_at_arccos_iff {x : ℝ} {n : with_top ℕ} : cont_diff_at ℝ n arccos x ↔ n = 0 ∨ (x ≠ -1 ∧ x ≠ 1) := by refine iff.trans ⟨λ h, _, λ h, _⟩ cont_diff_at_arcsin_iff; simpa [arccos] using (@cont_diff_at_const _ _ _ _ _ _ _ _ _ _ (π / 2)).sub h end arccos end real
125537cea3cd286436c65199d5f9e13a9b078b56
7cef822f3b952965621309e88eadf618da0c8ae9
/src/topology/uniform_space/completion.lean
c6ce4d504d597b9420bfabc6e87c2a04b2944f05
[ "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
23,425
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl Hausdorff completions of uniform spaces. The goal is to construct a left-adjoint to the inclusion of complete Hausdorff uniform spaces into all uniform spaces. Any uniform space `α` gets a completion `completion α` and a morphism (ie. uniformly continuous map) `completion : α → completion α` which solves the universal mapping problem of factorizing morphisms from `α` to any complete Hausdorff uniform space `β`. It means any uniformly continuous `f : α → β` gives rise to a unique morphism `completion.extension f : completion α → β` such that `f = completion.extension f ∘ completion α`. Actually `completion.extension f` is defined for all maps from `α` to `β` but it has the desired properties only if `f` is uniformly continuous. Beware that `completion α` is not injective if `α` is not Hausdorff. But its image is always dense. The adjoint functor acting on morphisms is then constructed by the usual abstract nonsense. For every uniform spaces `α` and `β`, it turns `f : α → β` into a morphism `completion.map f : completion α → completion β` such that `coe ∘ f = (completion.map f) ∘ coe` provided `f` is uniformly continuous. This construction is compatible with composition. In this file we introduce the following concepts: * `Cauchy α` the uniform completion of the uniform space `α` (using Cauchy filters). These are not minimal filters. * `completion α := quotient (separation_setoid (Cauchy α))` the Hausdorff completion. This formalization is mostly based on N. Bourbaki: General Topology I. M. James: Topologies and Uniformities From a slightly different perspective in order to reuse material in topology.uniform_space.basic. -/ import data.set.basic import topology.uniform_space.abstract_completion topology.uniform_space.separation noncomputable theory open filter set universes u v w x open_locale uniformity classical topological_space /-- Space of Cauchy filters This is essentially the completion of a uniform space. The embeddings are the neighbourhood filters. This space is not minimal, the separated uniform space (i.e. quotiented on the intersection of all entourages) is necessary for this. -/ def Cauchy (α : Type u) [uniform_space α] : Type u := { f : filter α // cauchy f } namespace Cauchy section parameters {α : Type u} [uniform_space α] variables {β : Type v} {γ : Type w} variables [uniform_space β] [uniform_space γ] def gen (s : set (α × α)) : set (Cauchy α × Cauchy α) := {p | s ∈ filter.prod (p.1.val) (p.2.val) } lemma monotone_gen : monotone gen := monotone_set_of $ assume p, @monotone_mem_sets (α×α) (filter.prod (p.1.val) (p.2.val)) private lemma symm_gen : map prod.swap ((𝓤 α).lift' gen) ≤ (𝓤 α).lift' gen := calc map prod.swap ((𝓤 α).lift' gen) = (𝓤 α).lift' (λs:set (α×α), {p | s ∈ filter.prod (p.2.val) (p.1.val) }) : begin delta gen, simp [map_lift'_eq, monotone_set_of, monotone_mem_sets, function.comp, image_swap_eq_preimage_swap] end ... ≤ (𝓤 α).lift' gen : uniformity_lift_le_swap (monotone_principal.comp (monotone_set_of $ assume p, @monotone_mem_sets (α×α) ((filter.prod ((p.2).val) ((p.1).val))))) begin have h := λ(p:Cauchy α×Cauchy α), @filter.prod_comm _ _ (p.2.val) (p.1.val), simp [function.comp, h], exact le_refl _ end private lemma comp_rel_gen_gen_subset_gen_comp_rel {s t : set (α×α)} : comp_rel (gen s) (gen t) ⊆ (gen (comp_rel s t) : set (Cauchy α × Cauchy α)) := assume ⟨f, g⟩ ⟨h, h₁, h₂⟩, let ⟨t₁, (ht₁ : t₁ ∈ f.val), t₂, (ht₂ : t₂ ∈ h.val), (h₁ : set.prod t₁ t₂ ⊆ s)⟩ := mem_prod_iff.mp h₁ in let ⟨t₃, (ht₃ : t₃ ∈ h.val), t₄, (ht₄ : t₄ ∈ g.val), (h₂ : set.prod t₃ t₄ ⊆ t)⟩ := mem_prod_iff.mp h₂ in have t₂ ∩ t₃ ∈ h.val, from inter_mem_sets ht₂ ht₃, let ⟨x, xt₂, xt₃⟩ := inhabited_of_mem_sets (h.property.left) this in (filter.prod f.val g.val).sets_of_superset (prod_mem_prod ht₁ ht₄) (assume ⟨a, b⟩ ⟨(ha : a ∈ t₁), (hb : b ∈ t₄)⟩, ⟨x, h₁ (show (a, x) ∈ set.prod t₁ t₂, from ⟨ha, xt₂⟩), h₂ (show (x, b) ∈ set.prod t₃ t₄, from ⟨xt₃, hb⟩)⟩) private lemma comp_gen : ((𝓤 α).lift' gen).lift' (λs, comp_rel s s) ≤ (𝓤 α).lift' gen := calc ((𝓤 α).lift' gen).lift' (λs, comp_rel s s) = (𝓤 α).lift' (λs, comp_rel (gen s) (gen s)) : begin rw [lift'_lift'_assoc], exact monotone_gen, exact (monotone_comp_rel monotone_id monotone_id) end ... ≤ (𝓤 α).lift' (λs, gen $ comp_rel s s) : lift'_mono' $ assume s hs, comp_rel_gen_gen_subset_gen_comp_rel ... = ((𝓤 α).lift' $ λs:set(α×α), comp_rel s s).lift' gen : begin rw [lift'_lift'_assoc], exact (monotone_comp_rel monotone_id monotone_id), exact monotone_gen end ... ≤ (𝓤 α).lift' gen : lift'_mono comp_le_uniformity (le_refl _) instance : uniform_space (Cauchy α) := uniform_space.of_core { uniformity := (𝓤 α).lift' gen, refl := principal_le_lift' $ assume s hs ⟨a, b⟩ (a_eq_b : a = b), a_eq_b ▸ a.property.right hs, symm := symm_gen, comp := comp_gen } theorem mem_uniformity {s : set (Cauchy α × Cauchy α)} : s ∈ 𝓤 (Cauchy α) ↔ ∃ t ∈ 𝓤 α, gen t ⊆ s := mem_lift'_sets monotone_gen theorem mem_uniformity' {s : set (Cauchy α × Cauchy α)} : s ∈ 𝓤 (Cauchy α) ↔ ∃ t ∈ 𝓤 α, ∀ f g : Cauchy α, t ∈ filter.prod f.1 g.1 → (f, g) ∈ s := mem_uniformity.trans $ bex_congr $ λ t h, prod.forall /-- Embedding of `α` into its completion -/ def pure_cauchy (a : α) : Cauchy α := ⟨pure a, cauchy_pure⟩ lemma uniform_inducing_pure_cauchy : uniform_inducing (pure_cauchy : α → Cauchy α) := ⟨have (preimage (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ∘ gen) = id, from funext $ assume s, set.ext $ assume ⟨a₁, a₂⟩, by simp [preimage, gen, pure_cauchy, prod_principal_principal], calc comap (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ((𝓤 α).lift' gen) = (𝓤 α).lift' (preimage (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ∘ gen) : comap_lift'_eq monotone_gen ... = 𝓤 α : by simp [this]⟩ lemma uniform_embedding_pure_cauchy : uniform_embedding (pure_cauchy : α → Cauchy α) := { inj := assume a₁ a₂ h, have (pure_cauchy a₁).val = (pure_cauchy a₂).val, from congr_arg _ h, have {a₁} = ({a₂} : set α), from principal_eq_iff_eq.mp this, by simp at this; assumption, ..uniform_inducing_pure_cauchy } lemma pure_cauchy_dense : ∀x, x ∈ closure (range pure_cauchy) := assume f, have h_ex : ∀ s ∈ 𝓤 (Cauchy α), ∃y:α, (f, pure_cauchy y) ∈ s, from assume s hs, let ⟨t'', ht''₁, (ht''₂ : gen t'' ⊆ s)⟩ := (mem_lift'_sets monotone_gen).mp hs in let ⟨t', ht'₁, ht'₂⟩ := comp_mem_uniformity_sets ht''₁ in have t' ∈ filter.prod (f.val) (f.val), from f.property.right ht'₁, let ⟨t, ht, (h : set.prod t t ⊆ t')⟩ := mem_prod_same_iff.mp this in let ⟨x, (hx : x ∈ t)⟩ := inhabited_of_mem_sets f.property.left ht in have t'' ∈ filter.prod f.val (pure x), from mem_prod_iff.mpr ⟨t, ht, {y:α | (x, y) ∈ t'}, assume y, begin simp, intro h, simp [h], exact refl_mem_uniformity ht'₁ end, assume ⟨a, b⟩ ⟨(h₁ : a ∈ t), (h₂ : (x, b) ∈ t')⟩, ht'₂ $ prod_mk_mem_comp_rel (@h (a, x) ⟨h₁, hx⟩) h₂⟩, ⟨x, ht''₂ $ by dsimp [gen]; exact this⟩, begin simp [closure_eq_nhds, nhds_eq_uniformity, lift'_inf_principal_eq, set.inter_comm], exact (lift'_neq_bot_iff $ monotone_inter monotone_const monotone_preimage).mpr (assume s hs, let ⟨y, hy⟩ := h_ex s hs in have pure_cauchy y ∈ range pure_cauchy ∩ {y : Cauchy α | (f, y) ∈ s}, from ⟨mem_range_self y, hy⟩, ne_empty_of_mem this) end lemma dense_inducing_pure_cauchy : dense_inducing pure_cauchy := uniform_inducing_pure_cauchy.dense_inducing pure_cauchy_dense lemma dense_embedding_pure_cauchy : dense_embedding pure_cauchy := uniform_embedding_pure_cauchy.dense_embedding pure_cauchy_dense lemma nonempty_Cauchy_iff : nonempty (Cauchy α) ↔ nonempty α := begin split ; rintro ⟨c⟩, { have := eq_univ_iff_forall.1 dense_embedding_pure_cauchy.to_dense_inducing.closure_range c, have := mem_closure_iff.1 this _ is_open_univ trivial, rcases exists_mem_of_ne_empty this with ⟨_, ⟨_, a, _⟩⟩, exact ⟨a⟩ }, { exact ⟨pure_cauchy c⟩ } end section set_option eqn_compiler.zeta true instance : complete_space (Cauchy α) := complete_space_extension uniform_inducing_pure_cauchy pure_cauchy_dense $ assume f hf, let f' : Cauchy α := ⟨f, hf⟩ in have map pure_cauchy f ≤ (𝓤 $ Cauchy α).lift' (preimage (prod.mk f')), from le_lift' $ assume s hs, let ⟨t, ht₁, (ht₂ : gen t ⊆ s)⟩ := (mem_lift'_sets monotone_gen).mp hs in let ⟨t', ht', (h : set.prod t' t' ⊆ t)⟩ := mem_prod_same_iff.mp (hf.right ht₁) in have t' ⊆ { y : α | (f', pure_cauchy y) ∈ gen t }, from assume x hx, (filter.prod f (pure x)).sets_of_superset (prod_mem_prod ht' $ mem_pure hx) h, f.sets_of_superset ht' $ subset.trans this (preimage_mono ht₂), ⟨f', by simp [nhds_eq_uniformity]; assumption⟩ end instance [inhabited α] : inhabited (Cauchy α) := ⟨pure_cauchy $ default α⟩ instance [h : nonempty α] : nonempty (Cauchy α) := h.rec_on $ assume a, nonempty.intro $ Cauchy.pure_cauchy a section extend def extend (f : α → β) : (Cauchy α → β) := if uniform_continuous f then dense_inducing_pure_cauchy.extend f else λ x, f (classical.inhabited_of_nonempty $ nonempty_Cauchy_iff.1 ⟨x⟩).default variables [separated β] lemma extend_pure_cauchy {f : α → β} (hf : uniform_continuous f) (a : α) : extend f (pure_cauchy a) = f a := begin rw [extend, if_pos hf], exact uniformly_extend_of_ind uniform_inducing_pure_cauchy pure_cauchy_dense hf _ end variables [_root_.complete_space β] lemma uniform_continuous_extend {f : α → β} : uniform_continuous (extend f) := begin by_cases hf : uniform_continuous f, { rw [extend, if_pos hf], exact uniform_continuous_uniformly_extend uniform_inducing_pure_cauchy pure_cauchy_dense hf }, { rw [extend, if_neg hf], exact uniform_continuous_of_const (assume a b, by congr) } end end extend end theorem Cauchy_eq {α : Type*} [inhabited α] [uniform_space α] [complete_space α] [separated α] {f g : Cauchy α} : lim f.1 = lim g.1 ↔ (f, g) ∈ separation_rel (Cauchy α) := begin split, { intros e s hs, rcases Cauchy.mem_uniformity'.1 hs with ⟨t, tu, ts⟩, apply ts, rcases comp_mem_uniformity_sets tu with ⟨d, du, dt⟩, refine mem_prod_iff.2 ⟨_, le_nhds_lim_of_cauchy f.2 (mem_nhds_right (lim f.1) du), _, le_nhds_lim_of_cauchy g.2 (mem_nhds_left (lim g.1) du), λ x h, _⟩, cases x with a b, cases h with h₁ h₂, rw ← e at h₂, exact dt ⟨_, h₁, h₂⟩ }, { intros H, refine separated_def.1 (by apply_instance) _ _ (λ t tu, _), rcases mem_uniformity_is_closed tu with ⟨d, du, dc, dt⟩, refine H {p | (lim p.1.1, lim p.2.1) ∈ t} (Cauchy.mem_uniformity'.2 ⟨d, du, λ f g h, _⟩), rcases mem_prod_iff.1 h with ⟨x, xf, y, yg, h⟩, have limc : ∀ (f : Cauchy α) (x ∈ f.1), lim f.1 ∈ closure x, { intros f x xf, rw closure_eq_nhds, exact lattice.neq_bot_of_le_neq_bot f.2.1 (lattice.le_inf (le_nhds_lim_of_cauchy f.2) (le_principal_iff.2 xf)) }, have := (closure_subset_iff_subset_of_is_closed dc).2 h, rw closure_prod_eq at this, refine dt (this ⟨_, _⟩); dsimp; apply limc; assumption } end section local attribute [instance] uniform_space.separation_setoid lemma injective_separated_pure_cauchy {α : Type*} [uniform_space α] [s : separated α] : function.injective (λa:α, ⟦pure_cauchy a⟧) | a b h := separated_def.1 s _ _ $ assume s hs, let ⟨t, ht, hts⟩ := by rw [← (@uniform_embedding_pure_cauchy α _).comap_uniformity, filter.mem_comap_sets] at hs; exact hs in have (pure_cauchy a, pure_cauchy b) ∈ t, from quotient.exact h t ht, @hts (a, b) this end end Cauchy local attribute [instance] uniform_space.separation_setoid open Cauchy set namespace uniform_space variables (α : Type*) [uniform_space α] variables {β : Type*} [uniform_space β] variables {γ : Type*} [uniform_space γ] instance complete_space_separation [h : complete_space α] : complete_space (quotient (separation_setoid α)) := ⟨assume f, assume hf : cauchy f, have cauchy (f.comap (λx, ⟦x⟧)), from cauchy_comap comap_quotient_le_uniformity hf $ comap_neq_bot_of_surj hf.left $ assume b, quotient.exists_rep _, let ⟨x, (hx : f.comap (λx, ⟦x⟧) ≤ 𝓝 x)⟩ := complete_space.complete this in ⟨⟦x⟧, calc f = map (λx, ⟦x⟧) (f.comap (λx, ⟦x⟧)) : (map_comap $ univ_mem_sets' $ assume b, quotient.exists_rep _).symm ... ≤ map (λx, ⟦x⟧) (𝓝 x) : map_mono hx ... ≤ _ : continuous_iff_continuous_at.mp uniform_continuous_quotient_mk.continuous _⟩⟩ /-- Hausdorff completion of `α` -/ def completion := quotient (separation_setoid $ Cauchy α) namespace completion @[priority 50] instance : uniform_space (completion α) := by dunfold completion ; apply_instance instance : complete_space (completion α) := by dunfold completion ; apply_instance instance : separated (completion α) := by dunfold completion ; apply_instance instance : t2_space (completion α) := separated_t2 instance : regular_space (completion α) := separated_regular /-- Automatic coercion from `α` to its completion. Not always injective. -/ instance : has_coe_t α (completion α) := ⟨quotient.mk ∘ pure_cauchy⟩ -- note [use has_coe_t] protected lemma coe_eq : (coe : α → completion α) = quotient.mk ∘ pure_cauchy := rfl lemma comap_coe_eq_uniformity : (𝓤 _).comap (λ(p:α×α), ((p.1 : completion α), (p.2 : completion α))) = 𝓤 α := begin have : (λx:α×α, ((x.1 : completion α), (x.2 : completion α))) = (λx:(Cauchy α)×(Cauchy α), (⟦x.1⟧, ⟦x.2⟧)) ∘ (λx:α×α, (pure_cauchy x.1, pure_cauchy x.2)), { ext ⟨a, b⟩; simp; refl }, rw [this, ← filter.comap_comap_comp], change filter.comap _ (filter.comap _ (𝓤 $ quotient $ separation_setoid $ Cauchy α)) = 𝓤 α, rw [comap_quotient_eq_uniformity, uniform_embedding_pure_cauchy.comap_uniformity] end lemma uniform_inducing_coe : uniform_inducing (coe : α → completion α) := ⟨comap_coe_eq_uniformity α⟩ variables {α} lemma dense : dense_range (coe : α → completion α) := begin rw [dense_range_iff_closure_range, completion.coe_eq, range_comp], exact quotient_dense_of_dense pure_cauchy_dense end variables (α) def cpkg {α : Type*} [uniform_space α] : abstract_completion α := { space := completion α, coe := coe, uniform_struct := by apply_instance, complete := by apply_instance, separation := by apply_instance, uniform_inducing := completion.uniform_inducing_coe α, dense := completion.dense } local attribute [instance] abstract_completion.uniform_struct abstract_completion.complete abstract_completion.separation lemma nonempty_completion_iff : nonempty (completion α) ↔ nonempty α := (dense_range.nonempty (cpkg.dense)).symm lemma uniform_continuous_coe : uniform_continuous (coe : α → completion α) := cpkg.uniform_continuous_coe lemma continuous_coe : continuous (coe : α → completion α) := cpkg.continuous_coe lemma uniform_embedding_coe [separated α] : uniform_embedding (coe : α → completion α) := { comap_uniformity := comap_coe_eq_uniformity α, inj := injective_separated_pure_cauchy } variable {α} lemma dense_inducing_coe : dense_inducing (coe : α → completion α) := { dense := dense, ..(uniform_inducing_coe α).inducing } lemma dense_embedding_coe [separated α]: dense_embedding (coe : α → completion α) := { inj := injective_separated_pure_cauchy, ..dense_inducing_coe } lemma dense₂ : dense_range (λx:α × β, ((x.1 : completion α), (x.2 : completion β))) := dense.prod dense lemma dense₃ : dense_range (λx:α × (β × γ), ((x.1 : completion α), ((x.2.1 : completion β), (x.2.2 : completion γ)))) := dense.prod dense₂ @[elab_as_eliminator] lemma induction_on {p : completion α → Prop} (a : completion α) (hp : is_closed {a | p a}) (ih : ∀a:α, p a) : p a := is_closed_property dense hp ih a @[elab_as_eliminator] lemma induction_on₂ {p : completion α → completion β → Prop} (a : completion α) (b : completion β) (hp : is_closed {x : completion α × completion β | p x.1 x.2}) (ih : ∀(a:α) (b:β), p a b) : p a b := have ∀x : completion α × completion β, p x.1 x.2, from is_closed_property dense₂ hp $ assume ⟨a, b⟩, ih a b, this (a, b) @[elab_as_eliminator] lemma induction_on₃ {p : completion α → completion β → completion γ → Prop} (a : completion α) (b : completion β) (c : completion γ) (hp : is_closed {x : completion α × completion β × completion γ | p x.1 x.2.1 x.2.2}) (ih : ∀(a:α) (b:β) (c:γ), p a b c) : p a b c := have ∀x : completion α × completion β × completion γ, p x.1 x.2.1 x.2.2, from is_closed_property dense₃ hp $ assume ⟨a, b, c⟩, ih a b c, this (a, b, c) lemma ext [t2_space β] {f g : completion α → β} (hf : continuous f) (hg : continuous g) (h : ∀a:α, f a = g a) : f = g := cpkg.funext hf hg h section extension variables {f : α → β} /-- "Extension" to the completion. It is defined for any map `f` but returns an arbitrary constant value if `f` is not uniformly continuous -/ protected def extension (f : α → β) : completion α → β := cpkg.extend f variables [separated β] @[simp] lemma extension_coe (hf : uniform_continuous f) (a : α) : (completion.extension f) a = f a := cpkg.extend_coe hf a variables [complete_space β] lemma uniform_continuous_extension : uniform_continuous (completion.extension f) := cpkg.uniform_continuous_extend lemma continuous_extension : continuous (completion.extension f) := cpkg.continuous_extend lemma extension_unique (hf : uniform_continuous f) {g : completion α → β} (hg : uniform_continuous g) (h : ∀ a : α, f a = g (a : completion α)) : completion.extension f = g := cpkg.extend_unique hf hg h @[simp] lemma extension_comp_coe {f : completion α → β} (hf : uniform_continuous f) : completion.extension (f ∘ coe) = f := cpkg.extend_comp_coe hf end extension section map variables {f : α → β} /-- Completion functor acting on morphisms -/ protected def map (f : α → β) : completion α → completion β := cpkg.map cpkg f lemma uniform_continuous_map : uniform_continuous (completion.map f) := cpkg.uniform_continuous_map cpkg f lemma continuous_map : continuous (completion.map f) := cpkg.continuous_map cpkg f @[simp] lemma map_coe (hf : uniform_continuous f) (a : α) : (completion.map f) a = f a := cpkg.map_coe cpkg hf a lemma map_unique {f : α → β} {g : completion α → completion β} (hg : uniform_continuous g) (h : ∀a:α, ↑(f a) = g a) : completion.map f = g := cpkg.map_unique cpkg hg h @[simp] lemma map_id : completion.map (@id α) = id := cpkg.map_id lemma extension_map [complete_space γ] [separated γ] {f : β → γ} {g : α → β} (hf : uniform_continuous f) (hg : uniform_continuous g) : completion.extension f ∘ completion.map g = completion.extension (f ∘ g) := completion.ext (continuous_extension.comp continuous_map) continuous_extension $ by intro a; simp only [hg, hf, hf.comp hg, (∘), map_coe, extension_coe] lemma map_comp {g : β → γ} {f : α → β} (hg : uniform_continuous g) (hf : uniform_continuous f) : completion.map g ∘ completion.map f = completion.map (g ∘ f) := extension_map ((uniform_continuous_coe _).comp hg) hf end map /- In this section we construct isomorphisms between the completion of a uniform space and the completion of its separation quotient -/ section separation_quotient_completion def completion_separation_quotient_equiv (α : Type u) [uniform_space α] : completion (separation_quotient α) ≃ completion α := begin refine ⟨completion.extension (separation_quotient.lift (coe : α → completion α)), completion.map quotient.mk, _, _⟩, { assume a, refine induction_on a (is_closed_eq (continuous_map.comp continuous_extension) continuous_id) _, rintros ⟨a⟩, show completion.map quotient.mk (completion.extension (separation_quotient.lift coe) ↑⟦a⟧) = ↑⟦a⟧, rw [extension_coe (separation_quotient.uniform_continuous_lift _), separation_quotient.lift_mk (uniform_continuous_coe α), completion.map_coe uniform_continuous_quotient_mk] ; apply_instance }, { assume a, refine completion.induction_on a (is_closed_eq (continuous_extension.comp continuous_map) continuous_id) _, assume a, rw [map_coe uniform_continuous_quotient_mk, extension_coe (separation_quotient.uniform_continuous_lift _), separation_quotient.lift_mk (uniform_continuous_coe α) _] ; apply_instance } end lemma uniform_continuous_completion_separation_quotient_equiv : uniform_continuous ⇑(completion_separation_quotient_equiv α) := uniform_continuous_extension lemma uniform_continuous_completion_separation_quotient_equiv_symm : uniform_continuous ⇑(completion_separation_quotient_equiv α).symm := uniform_continuous_map end separation_quotient_completion section extension₂ variables (f : α → β → γ) open function protected def extension₂ (f : α → β → γ) : completion α → completion β → γ := cpkg.extend₂ cpkg f variables [separated γ] {f} @[simp] lemma extension₂_coe_coe (hf : uniform_continuous $ uncurry' f) (a : α) (b : β) : completion.extension₂ f a b = f a b := cpkg.extension₂_coe_coe cpkg hf a b variables [complete_space γ] (f) lemma uniform_continuous_extension₂ : uniform_continuous₂ (completion.extension₂ f) := cpkg.uniform_continuous_extension₂ cpkg f end extension₂ section map₂ open function protected def map₂ (f : α → β → γ) : completion α → completion β → completion γ := cpkg.map₂ cpkg cpkg f lemma uniform_continuous_map₂ (f : α → β → γ) : uniform_continuous (uncurry' $ completion.map₂ f) := cpkg.uniform_continuous_map₂ cpkg cpkg f lemma continuous_map₂ {δ} [topological_space δ] {f : α → β → γ} {a : δ → completion α} {b : δ → completion β} (ha : continuous a) (hb : continuous b) : continuous (λd:δ, completion.map₂ f (a d) (b d)) := cpkg.continuous_map₂ cpkg cpkg ha hb lemma map₂_coe_coe (a : α) (b : β) (f : α → β → γ) (hf : uniform_continuous $ uncurry' f) : completion.map₂ f (a : completion α) (b : completion β) = f a b := cpkg.map₂_coe_coe cpkg cpkg a b f hf end map₂ end completion end uniform_space
07e07423c731d26dee6723436ae440e028b0baeb
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/quaternion.lean
964e93ea8a988e7cd881b784bbdb8c610781d337
[]
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
31,843
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.ring_exp import Mathlib.algebra.algebra.basic import Mathlib.algebra.opposites import Mathlib.data.equiv.ring import Mathlib.PostPort universes u_1 l namespace Mathlib /-! # Quaternions In this file we define quaternions `ℍ[R]` over a commutative ring `R`, and define some algebraic structures on `ℍ[R]`. ## Main definitions * `quaternion_algebra R a b`, `ℍ[R, a, b]` : [quaternion algebra](https://en.wikipedia.org/wiki/Quaternion_algebra) with coefficients `a`, `b` * `quaternion R`, `ℍ[R]` : the space of quaternions, a.k.a. `quaternion_algebra R (-1) (-1)`; * `quaternion.norm_sq` : square of the norm of a quaternion; * `quaternion.conj` : conjugate of a quaternion; We also define the following algebraic structures on `ℍ[R]`: * `ring ℍ[R, a, b]` and `algebra R ℍ[R, a, b]` : for any commutative ring `R`; * `ring ℍ[R]` and `algebra R ℍ[R]` : for any commutative ring `R`; * `domain ℍ[R]` : for a linear ordered commutative ring `R`; * `division_algebra ℍ[R]` : for a linear ordered field `R`. ## Notation The following notation is available with `open_locale quaternion`. * `ℍ[R, c₁, c₂]` : `quaternion_algebra R c₁ c₂` * `ℍ[R]` : quaternions over `R`. ## Implementation notes We define quaternions over any ring `R`, not just `ℝ` to be able to deal with, e.g., integer or rational quaternions without using real numbers. In particular, all definitions in this file are computable. ## Tags quaternion -/ /-- Quaternion algebra over a type with fixed coefficients $a=i^2$ and $b=j^2$. Implemented as a structure with four fields: `re`, `im_i`, `im_j`, and `im_k`. -/ structure quaternion_algebra (R : Type u_1) (a : R) (b : R) where re : R im_i : R im_j : R im_k : R namespace quaternion_algebra @[simp] theorem mk.eta {R : Type u_1} {c₁ : R} {c₂ : R} (a : quaternion_algebra R c₁ c₂) : mk (re a) (im_i a) (im_j a) (im_k a) = a := sorry protected instance has_coe_t {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} : has_coe_t R (quaternion_algebra R c₁ c₂) := has_coe_t.mk fun (x : R) => mk x 0 0 0 @[simp] theorem coe_re {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (x : R) : re ↑x = x := rfl @[simp] theorem coe_im_i {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (x : R) : im_i ↑x = 0 := rfl @[simp] theorem coe_im_j {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (x : R) : im_j ↑x = 0 := rfl @[simp] theorem coe_im_k {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (x : R) : im_k ↑x = 0 := rfl theorem coe_injective {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} : function.injective coe := fun (x y : R) (h : ↑x = ↑y) => congr_arg re h @[simp] theorem coe_inj {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} {x : R} {y : R} : ↑x = ↑y ↔ x = y := function.injective.eq_iff coe_injective @[simp] theorem has_zero_zero_im_j {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} : im_j 0 = 0 := Eq.refl (im_j 0) @[simp] theorem coe_zero {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} : ↑0 = 0 := rfl protected instance inhabited {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} : Inhabited (quaternion_algebra R c₁ c₂) := { default := 0 } @[simp] theorem has_one_one_re {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} : re 1 = 1 := Eq.refl (re 1) @[simp] theorem coe_one {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} : ↑1 = 1 := rfl @[simp] theorem has_add_add_im_i {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (a : quaternion_algebra R c₁ c₂) (b : quaternion_algebra R c₁ c₂) : im_i (a + b) = im_i a + im_i b := Eq.refl (im_i (a + b)) @[simp] theorem mk_add_mk {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (a₁ : R) (a₂ : R) (a₃ : R) (a₄ : R) (b₁ : R) (b₂ : R) (b₃ : R) (b₄ : R) : mk a₁ a₂ a₃ a₄ + mk b₁ b₂ b₃ b₄ = mk (a₁ + b₁) (a₂ + b₂) (a₃ + b₃) (a₄ + b₄) := rfl protected instance has_neg {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} : Neg (quaternion_algebra R c₁ c₂) := { neg := fun (a : quaternion_algebra R c₁ c₂) => mk (-re a) (-im_i a) (-im_j a) (-im_k a) } @[simp] theorem neg_mk {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (a₁ : R) (a₂ : R) (a₃ : R) (a₄ : R) : -mk a₁ a₂ a₃ a₄ = mk (-a₁) (-a₂) (-a₃) (-a₄) := rfl @[simp] theorem has_sub_sub_im_k {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (a : quaternion_algebra R c₁ c₂) (b : quaternion_algebra R c₁ c₂) : im_k (a - b) = im_k a - im_k b := Eq.refl (im_k (a - b)) @[simp] theorem mk_sub_mk {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (a₁ : R) (a₂ : R) (a₃ : R) (a₄ : R) (b₁ : R) (b₂ : R) (b₃ : R) (b₄ : R) : mk a₁ a₂ a₃ a₄ - mk b₁ b₂ b₃ b₄ = mk (a₁ - b₁) (a₂ - b₂) (a₃ - b₃) (a₄ - b₄) := rfl /-- Multiplication is given by * `1 * x = x * 1 = x`; * `i * i = c₁`; * `j * j = c₂`; * `i * j = k`, `j * i = -k`; * `k * k = -c₁ * c₂`; * `i * k = c₁ * j`, `k * i = `-c₁ * j`; * `j * k = -c₂ * i`, `k * j = c₂ * i`. -/ @[simp] theorem has_mul_mul_im_i {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (a : quaternion_algebra R c₁ c₂) (b : quaternion_algebra R c₁ c₂) : im_i (a * b) = re a * im_i b + im_i a * re b - c₂ * im_j a * im_k b + c₂ * im_k a * im_j b := Eq.refl (im_i (a * b)) @[simp] theorem mk_mul_mk {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (a₁ : R) (a₂ : R) (a₃ : R) (a₄ : R) (b₁ : R) (b₂ : R) (b₃ : R) (b₄ : R) : mk a₁ a₂ a₃ a₄ * mk b₁ b₂ b₃ b₄ = mk (a₁ * b₁ + c₁ * a₂ * b₂ + c₂ * a₃ * b₃ - c₁ * c₂ * a₄ * b₄) (a₁ * b₂ + a₂ * b₁ - c₂ * a₃ * b₄ + c₂ * a₄ * b₃) (a₁ * b₃ + c₁ * a₂ * b₄ + a₃ * b₁ - c₁ * a₄ * b₂) (a₁ * b₄ + a₂ * b₃ - a₃ * b₂ + a₄ * b₁) := rfl protected instance ring {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} : ring (quaternion_algebra R c₁ c₂) := ring.mk Add.add sorry 0 sorry sorry Neg.neg Sub.sub sorry sorry Mul.mul sorry 1 sorry sorry sorry sorry protected instance algebra {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} : algebra R (quaternion_algebra R c₁ c₂) := algebra.mk (ring_hom.mk coe sorry sorry sorry sorry) sorry sorry @[simp] theorem smul_re {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (r : R) (a : quaternion_algebra R c₁ c₂) : re (r • a) = r • re a := rfl @[simp] theorem smul_im_i {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (r : R) (a : quaternion_algebra R c₁ c₂) : im_i (r • a) = r • im_i a := rfl @[simp] theorem smul_im_j {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (r : R) (a : quaternion_algebra R c₁ c₂) : im_j (r • a) = r • im_j a := rfl @[simp] theorem smul_im_k {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (r : R) (a : quaternion_algebra R c₁ c₂) : im_k (r • a) = r • im_k a := rfl @[simp] theorem coe_add {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (x : R) (y : R) : ↑(x + y) = ↑x + ↑y := ring_hom.map_add (algebra_map R (quaternion_algebra R c₁ c₂)) x y @[simp] theorem coe_sub {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (x : R) (y : R) : ↑(x - y) = ↑x - ↑y := ring_hom.map_sub (algebra_map R (quaternion_algebra R c₁ c₂)) x y @[simp] theorem coe_neg {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (x : R) : ↑(-x) = -↑x := ring_hom.map_neg (algebra_map R (quaternion_algebra R c₁ c₂)) x @[simp] theorem coe_mul {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (x : R) (y : R) : ↑(x * y) = ↑x * ↑y := ring_hom.map_mul (algebra_map R (quaternion_algebra R c₁ c₂)) x y theorem coe_commutes {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (r : R) (a : quaternion_algebra R c₁ c₂) : ↑r * a = a * ↑r := algebra.commutes r a theorem coe_commute {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (r : R) (a : quaternion_algebra R c₁ c₂) : commute (↑r) a := coe_commutes r a theorem coe_mul_eq_smul {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (r : R) (a : quaternion_algebra R c₁ c₂) : ↑r * a = r • a := Eq.symm (algebra.smul_def r a) theorem mul_coe_eq_smul {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (r : R) (a : quaternion_algebra R c₁ c₂) : a * ↑r = r • a := eq.mpr (id (Eq._oldrec (Eq.refl (a * ↑r = r • a)) (Eq.symm (coe_commutes r a)))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑r * a = r • a)) (coe_mul_eq_smul r a))) (Eq.refl (r • a))) @[simp] theorem coe_algebra_map {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} : ⇑(algebra_map R (quaternion_algebra R c₁ c₂)) = coe := rfl theorem smul_coe {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (x : R) (y : R) : x • ↑y = ↑(x * y) := eq.mpr (id (Eq._oldrec (Eq.refl (x • ↑y = ↑(x * y))) (coe_mul x y))) (eq.mpr (id (Eq._oldrec (Eq.refl (x • ↑y = ↑x * ↑y)) (coe_mul_eq_smul x ↑y))) (Eq.refl (x • ↑y))) /-- Quaternion conjugate. -/ def conj {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} : linear_equiv R (quaternion_algebra R c₁ c₂) (quaternion_algebra R c₁ c₂) := linear_equiv.of_involutive (linear_map.mk (fun (a : quaternion_algebra R c₁ c₂) => mk (re a) (-im_i a) (-im_j a) (-im_k a)) sorry sorry) sorry @[simp] theorem re_conj {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (a : quaternion_algebra R c₁ c₂) : re (coe_fn conj a) = re a := rfl @[simp] theorem im_i_conj {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (a : quaternion_algebra R c₁ c₂) : im_i (coe_fn conj a) = -im_i a := rfl @[simp] theorem im_j_conj {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (a : quaternion_algebra R c₁ c₂) : im_j (coe_fn conj a) = -im_j a := rfl @[simp] theorem im_k_conj {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (a : quaternion_algebra R c₁ c₂) : im_k (coe_fn conj a) = -im_k a := rfl @[simp] theorem conj_conj {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (a : quaternion_algebra R c₁ c₂) : coe_fn conj (coe_fn conj a) = a := ext (coe_fn conj (coe_fn conj a)) a rfl (neg_neg (im_i a)) (neg_neg (im_j a)) (neg_neg (im_k a)) theorem conj_add {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (a : quaternion_algebra R c₁ c₂) (b : quaternion_algebra R c₁ c₂) : coe_fn conj (a + b) = coe_fn conj a + coe_fn conj b := linear_equiv.map_add conj a b @[simp] theorem conj_mul {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (a : quaternion_algebra R c₁ c₂) (b : quaternion_algebra R c₁ c₂) : coe_fn conj (a * b) = coe_fn conj b * coe_fn conj a := sorry theorem conj_conj_mul {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (a : quaternion_algebra R c₁ c₂) (b : quaternion_algebra R c₁ c₂) : coe_fn conj (coe_fn conj a * b) = coe_fn conj b * a := eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn conj (coe_fn conj a * b) = coe_fn conj b * a)) (conj_mul (coe_fn conj a) b))) (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn conj b * coe_fn conj (coe_fn conj a) = coe_fn conj b * a)) (conj_conj a))) (Eq.refl (coe_fn conj b * a))) theorem conj_mul_conj {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (a : quaternion_algebra R c₁ c₂) (b : quaternion_algebra R c₁ c₂) : coe_fn conj (a * coe_fn conj b) = b * coe_fn conj a := eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn conj (a * coe_fn conj b) = b * coe_fn conj a)) (conj_mul a (coe_fn conj b)))) (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn conj (coe_fn conj b) * coe_fn conj a = b * coe_fn conj a)) (conj_conj b))) (Eq.refl (b * coe_fn conj a))) theorem self_add_conj' {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (a : quaternion_algebra R c₁ c₂) : a + coe_fn conj a = ↑(bit0 1 * re a) := sorry theorem self_add_conj {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (a : quaternion_algebra R c₁ c₂) : a + coe_fn conj a = bit0 1 * ↑(re a) := sorry theorem conj_add_self' {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (a : quaternion_algebra R c₁ c₂) : coe_fn conj a + a = ↑(bit0 1 * re a) := eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn conj a + a = ↑(bit0 1 * re a))) (add_comm (coe_fn conj a) a))) (eq.mpr (id (Eq._oldrec (Eq.refl (a + coe_fn conj a = ↑(bit0 1 * re a))) (self_add_conj' a))) (Eq.refl ↑(bit0 1 * re a))) theorem conj_add_self {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (a : quaternion_algebra R c₁ c₂) : coe_fn conj a + a = bit0 1 * ↑(re a) := eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn conj a + a = bit0 1 * ↑(re a))) (add_comm (coe_fn conj a) a))) (eq.mpr (id (Eq._oldrec (Eq.refl (a + coe_fn conj a = bit0 1 * ↑(re a))) (self_add_conj a))) (Eq.refl (bit0 1 * ↑(re a)))) theorem conj_eq_two_re_sub {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (a : quaternion_algebra R c₁ c₂) : coe_fn conj a = ↑(bit0 1 * re a) - a := iff.mpr eq_sub_iff_add_eq (conj_add_self' a) theorem commute_conj_self {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (a : quaternion_algebra R c₁ c₂) : commute (coe_fn conj a) a := eq.mpr (id (Eq._oldrec (Eq.refl (commute (coe_fn conj a) a)) (conj_eq_two_re_sub a))) (commute.sub_left (coe_commute (bit0 1 * re a) a) (commute.refl a)) theorem commute_self_conj {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (a : quaternion_algebra R c₁ c₂) : commute a (coe_fn conj a) := commute.symm (commute_conj_self a) theorem commute_conj_conj {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} {a : quaternion_algebra R c₁ c₂} {b : quaternion_algebra R c₁ c₂} (h : commute a b) : commute (coe_fn conj a) (coe_fn conj b) := sorry @[simp] theorem conj_coe {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (x : R) : coe_fn conj ↑x = ↑x := sorry theorem conj_smul {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (r : R) (a : quaternion_algebra R c₁ c₂) : coe_fn conj (r • a) = r • coe_fn conj a := linear_equiv.map_smul conj r a @[simp] theorem conj_one {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} : coe_fn conj 1 = 1 := conj_coe 1 theorem eq_re_of_eq_coe {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} {a : quaternion_algebra R c₁ c₂} {x : R} (h : a = ↑x) : a = ↑(re a) := eq.mpr (id (Eq._oldrec (Eq.refl (a = ↑(re a))) h)) (eq.mpr (id (Eq._oldrec (Eq.refl (↑x = ↑(re ↑x))) (coe_re x))) (Eq.refl ↑x)) theorem eq_re_iff_mem_range_coe {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} {a : quaternion_algebra R c₁ c₂} : a = ↑(re a) ↔ a ∈ set.range coe := sorry @[simp] theorem conj_fixed {R : Type u_1} [comm_ring R] [no_zero_divisors R] [char_zero R] {c₁ : R} {c₂ : R} {a : quaternion_algebra R c₁ c₂} : coe_fn conj a = a ↔ a = ↑(re a) := sorry -- Can't use `rw ← conj_fixed` in the proof without additional assumptions theorem conj_mul_eq_coe {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (a : quaternion_algebra R c₁ c₂) : coe_fn conj a * a = ↑(re (coe_fn conj a * a)) := sorry theorem mul_conj_eq_coe {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (a : quaternion_algebra R c₁ c₂) : a * coe_fn conj a = ↑(re (a * coe_fn conj a)) := eq.mpr (id (Eq._oldrec (Eq.refl (a * coe_fn conj a = ↑(re (a * coe_fn conj a)))) (commute.eq (commute_self_conj a)))) (conj_mul_eq_coe a) theorem conj_zero {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} : coe_fn conj 0 = 0 := linear_equiv.map_zero conj theorem conj_neg {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (a : quaternion_algebra R c₁ c₂) : coe_fn conj (-a) = -coe_fn conj a := linear_equiv.map_neg conj a theorem conj_sub {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (a : quaternion_algebra R c₁ c₂) (b : quaternion_algebra R c₁ c₂) : coe_fn conj (a - b) = coe_fn conj a - coe_fn conj b := linear_equiv.map_sub conj a b protected instance star_ring {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} : star_ring (quaternion_algebra R c₁ c₂) := star_ring.mk conj_add @[simp] theorem star_def {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} (a : quaternion_algebra R c₁ c₂) : star a = coe_fn conj a := rfl /-- Quaternion conjugate as an `alg_equiv` to the opposite ring. -/ def conj_alg_equiv {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} : alg_equiv R (quaternion_algebra R c₁ c₂) (quaternion_algebra R c₁ c₂ᵒᵖ) := alg_equiv.mk (opposite.op ∘ ⇑conj) (⇑conj ∘ opposite.unop) sorry sorry sorry sorry sorry @[simp] theorem coe_conj_alg_equiv {R : Type u_1} [comm_ring R] {c₁ : R} {c₂ : R} : ⇑conj_alg_equiv = opposite.op ∘ ⇑conj := rfl end quaternion_algebra /-- Space of quaternions over a type. Implemented as a structure with four fields: `re`, `im_i`, `im_j`, and `im_k`. -/ def quaternion (R : Type u_1) [HasOne R] [Neg R] := quaternion_algebra R (-1) (-1) namespace quaternion protected instance has_coe_t {R : Type u_1} [comm_ring R] : has_coe_t R (quaternion R) := quaternion_algebra.has_coe_t protected instance ring {R : Type u_1} [comm_ring R] : ring (quaternion R) := quaternion_algebra.ring protected instance inhabited {R : Type u_1} [comm_ring R] : Inhabited (quaternion R) := quaternion_algebra.inhabited protected instance algebra {R : Type u_1} [comm_ring R] : algebra R (quaternion R) := quaternion_algebra.algebra protected instance star_ring {R : Type u_1} [comm_ring R] : star_ring (quaternion R) := quaternion_algebra.star_ring theorem ext {R : Type u_1} [comm_ring R] (a : quaternion R) (b : quaternion R) : re a = re b → im_i a = im_i b → im_j a = im_j b → im_k a = im_k b → a = b := quaternion_algebra.ext a b theorem ext_iff {R : Type u_1} [comm_ring R] {a : quaternion R} {b : quaternion R} : a = b ↔ re a = re b ∧ im_i a = im_i b ∧ im_j a = im_j b ∧ im_k a = im_k b := quaternion_algebra.ext_iff a b @[simp] theorem coe_re {R : Type u_1} [comm_ring R] (x : R) : re ↑x = x := rfl @[simp] theorem coe_im_i {R : Type u_1} [comm_ring R] (x : R) : im_i ↑x = 0 := rfl @[simp] theorem coe_im_j {R : Type u_1} [comm_ring R] (x : R) : im_j ↑x = 0 := rfl @[simp] theorem coe_im_k {R : Type u_1} [comm_ring R] (x : R) : im_k ↑x = 0 := rfl @[simp] theorem zero_re {R : Type u_1} [comm_ring R] : re 0 = 0 := rfl @[simp] theorem zero_im_i {R : Type u_1} [comm_ring R] : im_i 0 = 0 := rfl @[simp] theorem zero_im_j {R : Type u_1} [comm_ring R] : im_j 0 = 0 := rfl @[simp] theorem zero_im_k {R : Type u_1} [comm_ring R] : im_k 0 = 0 := rfl @[simp] theorem coe_zero {R : Type u_1} [comm_ring R] : ↑0 = 0 := rfl @[simp] theorem one_re {R : Type u_1} [comm_ring R] : re 1 = 1 := rfl @[simp] theorem one_im_i {R : Type u_1} [comm_ring R] : im_i 1 = 0 := rfl @[simp] theorem one_im_j {R : Type u_1} [comm_ring R] : im_j 1 = 0 := rfl @[simp] theorem one_im_k {R : Type u_1} [comm_ring R] : im_k 1 = 0 := rfl @[simp] theorem coe_one {R : Type u_1} [comm_ring R] : ↑1 = 1 := rfl @[simp] theorem add_re {R : Type u_1} [comm_ring R] (a : quaternion R) (b : quaternion R) : re (a + b) = re a + re b := rfl @[simp] theorem add_im_i {R : Type u_1} [comm_ring R] (a : quaternion R) (b : quaternion R) : im_i (a + b) = im_i a + im_i b := rfl @[simp] theorem add_im_j {R : Type u_1} [comm_ring R] (a : quaternion R) (b : quaternion R) : im_j (a + b) = im_j a + im_j b := rfl @[simp] theorem add_im_k {R : Type u_1} [comm_ring R] (a : quaternion R) (b : quaternion R) : im_k (a + b) = im_k a + im_k b := rfl @[simp] theorem coe_add {R : Type u_1} [comm_ring R] (x : R) (y : R) : ↑(x + y) = ↑x + ↑y := quaternion_algebra.coe_add x y @[simp] theorem neg_re {R : Type u_1} [comm_ring R] (a : quaternion R) : re (-a) = -re a := rfl @[simp] theorem neg_im_i {R : Type u_1} [comm_ring R] (a : quaternion R) : im_i (-a) = -im_i a := rfl @[simp] theorem neg_im_j {R : Type u_1} [comm_ring R] (a : quaternion R) : im_j (-a) = -im_j a := rfl @[simp] theorem neg_im_k {R : Type u_1} [comm_ring R] (a : quaternion R) : im_k (-a) = -im_k a := rfl @[simp] theorem coe_neg {R : Type u_1} [comm_ring R] (x : R) : ↑(-x) = -↑x := quaternion_algebra.coe_neg x @[simp] theorem sub_re {R : Type u_1} [comm_ring R] (a : quaternion R) (b : quaternion R) : re (a - b) = re a - re b := rfl @[simp] theorem sub_im_i {R : Type u_1} [comm_ring R] (a : quaternion R) (b : quaternion R) : im_i (a - b) = im_i a - im_i b := rfl @[simp] theorem sub_im_j {R : Type u_1} [comm_ring R] (a : quaternion R) (b : quaternion R) : im_j (a - b) = im_j a - im_j b := rfl @[simp] theorem sub_im_k {R : Type u_1} [comm_ring R] (a : quaternion R) (b : quaternion R) : im_k (a - b) = im_k a - im_k b := rfl @[simp] theorem coe_sub {R : Type u_1} [comm_ring R] (x : R) (y : R) : ↑(x - y) = ↑x - ↑y := quaternion_algebra.coe_sub x y @[simp] theorem mul_re {R : Type u_1} [comm_ring R] (a : quaternion R) (b : quaternion R) : re (a * b) = re a * re b - im_i a * im_i b - im_j a * im_j b - im_k a * im_k b := sorry @[simp] theorem mul_im_i {R : Type u_1} [comm_ring R] (a : quaternion R) (b : quaternion R) : im_i (a * b) = re a * im_i b + im_i a * re b + im_j a * im_k b - im_k a * im_j b := sorry @[simp] theorem mul_im_j {R : Type u_1} [comm_ring R] (a : quaternion R) (b : quaternion R) : im_j (a * b) = re a * im_j b - im_i a * im_k b + im_j a * re b + im_k a * im_i b := sorry @[simp] theorem mul_im_k {R : Type u_1} [comm_ring R] (a : quaternion R) (b : quaternion R) : im_k (a * b) = re a * im_k b + im_i a * im_j b - im_j a * im_i b + im_k a * re b := sorry @[simp] theorem coe_mul {R : Type u_1} [comm_ring R] (x : R) (y : R) : ↑(x * y) = ↑x * ↑y := quaternion_algebra.coe_mul x y theorem coe_injective {R : Type u_1} [comm_ring R] : function.injective coe := quaternion_algebra.coe_injective @[simp] theorem coe_inj {R : Type u_1} [comm_ring R] {x : R} {y : R} : ↑x = ↑y ↔ x = y := function.injective.eq_iff coe_injective @[simp] theorem smul_re {R : Type u_1} [comm_ring R] (r : R) (a : quaternion R) : re (r • a) = r • re a := rfl @[simp] theorem smul_im_i {R : Type u_1} [comm_ring R] (r : R) (a : quaternion R) : im_i (r • a) = r • im_i a := rfl @[simp] theorem smul_im_j {R : Type u_1} [comm_ring R] (r : R) (a : quaternion R) : im_j (r • a) = r • im_j a := rfl @[simp] theorem smul_im_k {R : Type u_1} [comm_ring R] (r : R) (a : quaternion R) : im_k (r • a) = r • im_k a := rfl theorem coe_commutes {R : Type u_1} [comm_ring R] (r : R) (a : quaternion R) : ↑r * a = a * ↑r := quaternion_algebra.coe_commutes r a theorem coe_commute {R : Type u_1} [comm_ring R] (r : R) (a : quaternion R) : commute (↑r) a := quaternion_algebra.coe_commute r a theorem coe_mul_eq_smul {R : Type u_1} [comm_ring R] (r : R) (a : quaternion R) : ↑r * a = r • a := quaternion_algebra.coe_mul_eq_smul r a theorem mul_coe_eq_smul {R : Type u_1} [comm_ring R] (r : R) (a : quaternion R) : a * ↑r = r • a := quaternion_algebra.mul_coe_eq_smul r a @[simp] theorem algebra_map_def {R : Type u_1} [comm_ring R] : ⇑(algebra_map R (quaternion R)) = coe := rfl theorem smul_coe {R : Type u_1} [comm_ring R] (x : R) (y : R) : x • ↑y = ↑(x * y) := quaternion_algebra.smul_coe x y /-- Quaternion conjugate. -/ def conj {R : Type u_1} [comm_ring R] : linear_equiv R (quaternion R) (quaternion R) := quaternion_algebra.conj @[simp] theorem conj_re {R : Type u_1} [comm_ring R] (a : quaternion R) : re (coe_fn conj a) = re a := rfl @[simp] theorem conj_im_i {R : Type u_1} [comm_ring R] (a : quaternion R) : im_i (coe_fn conj a) = -im_i a := rfl @[simp] theorem conj_im_j {R : Type u_1} [comm_ring R] (a : quaternion R) : im_j (coe_fn conj a) = -im_j a := rfl @[simp] theorem conj_im_k {R : Type u_1} [comm_ring R] (a : quaternion R) : im_k (coe_fn conj a) = -im_k a := rfl @[simp] theorem conj_conj {R : Type u_1} [comm_ring R] (a : quaternion R) : coe_fn conj (coe_fn conj a) = a := quaternion_algebra.conj_conj a @[simp] theorem conj_add {R : Type u_1} [comm_ring R] (a : quaternion R) (b : quaternion R) : coe_fn conj (a + b) = coe_fn conj a + coe_fn conj b := quaternion_algebra.conj_add a b @[simp] theorem conj_mul {R : Type u_1} [comm_ring R] (a : quaternion R) (b : quaternion R) : coe_fn conj (a * b) = coe_fn conj b * coe_fn conj a := quaternion_algebra.conj_mul a b theorem conj_conj_mul {R : Type u_1} [comm_ring R] (a : quaternion R) (b : quaternion R) : coe_fn conj (coe_fn conj a * b) = coe_fn conj b * a := quaternion_algebra.conj_conj_mul a b theorem conj_mul_conj {R : Type u_1} [comm_ring R] (a : quaternion R) (b : quaternion R) : coe_fn conj (a * coe_fn conj b) = b * coe_fn conj a := quaternion_algebra.conj_mul_conj a b theorem self_add_conj' {R : Type u_1} [comm_ring R] (a : quaternion R) : a + coe_fn conj a = ↑(bit0 1 * re a) := quaternion_algebra.self_add_conj' a theorem self_add_conj {R : Type u_1} [comm_ring R] (a : quaternion R) : a + coe_fn conj a = bit0 1 * ↑(re a) := quaternion_algebra.self_add_conj a theorem conj_add_self' {R : Type u_1} [comm_ring R] (a : quaternion R) : coe_fn conj a + a = ↑(bit0 1 * re a) := quaternion_algebra.conj_add_self' a theorem conj_add_self {R : Type u_1} [comm_ring R] (a : quaternion R) : coe_fn conj a + a = bit0 1 * ↑(re a) := quaternion_algebra.conj_add_self a theorem conj_eq_two_re_sub {R : Type u_1} [comm_ring R] (a : quaternion R) : coe_fn conj a = ↑(bit0 1 * re a) - a := quaternion_algebra.conj_eq_two_re_sub a theorem commute_conj_self {R : Type u_1} [comm_ring R] (a : quaternion R) : commute (coe_fn conj a) a := quaternion_algebra.commute_conj_self a theorem commute_self_conj {R : Type u_1} [comm_ring R] (a : quaternion R) : commute a (coe_fn conj a) := quaternion_algebra.commute_self_conj a theorem commute_conj_conj {R : Type u_1} [comm_ring R] {a : quaternion R} {b : quaternion R} (h : commute a b) : commute (coe_fn conj a) (coe_fn conj b) := quaternion_algebra.commute_conj_conj h theorem Mathlib.commute.quaternion_conj {R : Type u_1} [comm_ring R] {a : quaternion R} {b : quaternion R} (h : commute a b) : commute (coe_fn conj a) (coe_fn conj b) := commute_conj_conj @[simp] theorem conj_coe {R : Type u_1} [comm_ring R] (x : R) : coe_fn conj ↑x = ↑x := quaternion_algebra.conj_coe x @[simp] theorem conj_smul {R : Type u_1} [comm_ring R] (r : R) (a : quaternion R) : coe_fn conj (r • a) = r • coe_fn conj a := quaternion_algebra.conj_smul r a @[simp] theorem conj_one {R : Type u_1} [comm_ring R] : coe_fn conj 1 = 1 := conj_coe 1 theorem eq_re_of_eq_coe {R : Type u_1} [comm_ring R] {a : quaternion R} {x : R} (h : a = ↑x) : a = ↑(re a) := quaternion_algebra.eq_re_of_eq_coe h theorem eq_re_iff_mem_range_coe {R : Type u_1} [comm_ring R] {a : quaternion R} : a = ↑(re a) ↔ a ∈ set.range coe := quaternion_algebra.eq_re_iff_mem_range_coe @[simp] theorem conj_fixed {R : Type u_1} [comm_ring R] [no_zero_divisors R] [char_zero R] {a : quaternion R} : coe_fn conj a = a ↔ a = ↑(re a) := quaternion_algebra.conj_fixed theorem conj_mul_eq_coe {R : Type u_1} [comm_ring R] (a : quaternion R) : coe_fn conj a * a = ↑(re (coe_fn conj a * a)) := quaternion_algebra.conj_mul_eq_coe a theorem mul_conj_eq_coe {R : Type u_1} [comm_ring R] (a : quaternion R) : a * coe_fn conj a = ↑(re (a * coe_fn conj a)) := quaternion_algebra.mul_conj_eq_coe a @[simp] theorem conj_zero {R : Type u_1} [comm_ring R] : coe_fn conj 0 = 0 := quaternion_algebra.conj_zero @[simp] theorem conj_neg {R : Type u_1} [comm_ring R] (a : quaternion R) : coe_fn conj (-a) = -coe_fn conj a := quaternion_algebra.conj_neg a @[simp] theorem conj_sub {R : Type u_1} [comm_ring R] (a : quaternion R) (b : quaternion R) : coe_fn conj (a - b) = coe_fn conj a - coe_fn conj b := quaternion_algebra.conj_sub a b /-- Quaternion conjugate as an `alg_equiv` to the opposite ring. -/ def conj_alg_equiv {R : Type u_1} [comm_ring R] : alg_equiv R (quaternion R) (quaternion Rᵒᵖ) := quaternion_algebra.conj_alg_equiv @[simp] theorem coe_conj_alg_equiv {R : Type u_1} [comm_ring R] : ⇑conj_alg_equiv = opposite.op ∘ ⇑conj := rfl /-- Square of the norm. -/ def norm_sq {R : Type u_1} [comm_ring R] : monoid_with_zero_hom (quaternion R) R := monoid_with_zero_hom.mk (fun (a : quaternion R) => re (a * coe_fn conj a)) sorry sorry sorry theorem norm_sq_def {R : Type u_1} [comm_ring R] (a : quaternion R) : coe_fn norm_sq a = re (a * coe_fn conj a) := rfl theorem norm_sq_def' {R : Type u_1} [comm_ring R] (a : quaternion R) : coe_fn norm_sq a = re a ^ bit0 1 + im_i a ^ bit0 1 + im_j a ^ bit0 1 + im_k a ^ bit0 1 := sorry theorem norm_sq_coe {R : Type u_1} [comm_ring R] (x : R) : coe_fn norm_sq ↑x = x ^ bit0 1 := sorry @[simp] theorem norm_sq_neg {R : Type u_1} [comm_ring R] (a : quaternion R) : coe_fn norm_sq (-a) = coe_fn norm_sq a := sorry theorem self_mul_conj {R : Type u_1} [comm_ring R] (a : quaternion R) : a * coe_fn conj a = ↑(coe_fn norm_sq a) := eq.mpr (id (Eq._oldrec (Eq.refl (a * coe_fn conj a = ↑(coe_fn norm_sq a))) (mul_conj_eq_coe a))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑(re (a * coe_fn conj a)) = ↑(coe_fn norm_sq a))) (norm_sq_def a))) (Eq.refl ↑(re (a * coe_fn conj a)))) theorem conj_mul_self {R : Type u_1} [comm_ring R] (a : quaternion R) : coe_fn conj a * a = ↑(coe_fn norm_sq a) := sorry theorem coe_norm_sq_add {R : Type u_1} [comm_ring R] (a : quaternion R) (b : quaternion R) : ↑(coe_fn norm_sq (a + b)) = ↑(coe_fn norm_sq a) + a * coe_fn conj b + b * coe_fn conj a + ↑(coe_fn norm_sq b) := sorry end quaternion namespace quaternion @[simp] theorem norm_sq_eq_zero {R : Type u_1} [linear_ordered_comm_ring R] {a : quaternion R} : coe_fn norm_sq a = 0 ↔ a = 0 := sorry theorem norm_sq_ne_zero {R : Type u_1} [linear_ordered_comm_ring R] {a : quaternion R} : coe_fn norm_sq a ≠ 0 ↔ a ≠ 0 := not_congr norm_sq_eq_zero @[simp] theorem norm_sq_nonneg {R : Type u_1} [linear_ordered_comm_ring R] {a : quaternion R} : 0 ≤ coe_fn norm_sq a := eq.mpr (id (Eq._oldrec (Eq.refl (0 ≤ coe_fn norm_sq a)) (norm_sq_def' a))) (add_nonneg (add_nonneg (add_nonneg (pow_two_nonneg (re a)) (pow_two_nonneg (im_i a))) (pow_two_nonneg (im_j a))) (pow_two_nonneg (im_k a))) @[simp] theorem norm_sq_le_zero {R : Type u_1} [linear_ordered_comm_ring R] {a : quaternion R} : coe_fn norm_sq a ≤ 0 ↔ a = 0 := sorry protected instance domain {R : Type u_1} [linear_ordered_comm_ring R] : domain (quaternion R) := domain.mk ring.add sorry ring.zero sorry sorry ring.neg ring.sub sorry sorry ring.mul sorry ring.one sorry sorry sorry sorry sorry sorry theorem has_inv_inv {R : Type u_1} [linear_ordered_field R] (a : quaternion R) : a⁻¹ = coe_fn norm_sq a⁻¹ • coe_fn conj a := Eq.refl (a⁻¹) protected instance division_ring {R : Type u_1} [linear_ordered_field R] : division_ring (quaternion R) := division_ring.mk domain.add sorry domain.zero sorry sorry domain.neg domain.sub sorry sorry domain.mul sorry domain.one sorry sorry sorry sorry has_inv.inv (div_inv_monoid.div._default domain.mul sorry domain.one sorry sorry has_inv.inv) sorry sorry sorry @[simp] theorem norm_sq_inv {R : Type u_1} [linear_ordered_field R] (a : quaternion R) : coe_fn norm_sq (a⁻¹) = (coe_fn norm_sq a⁻¹) := monoid_with_zero_hom.map_inv' norm_sq a @[simp] theorem norm_sq_div {R : Type u_1} [linear_ordered_field R] (a : quaternion R) (b : quaternion R) : coe_fn norm_sq (a / b) = coe_fn norm_sq a / coe_fn norm_sq b := monoid_with_zero_hom.map_div norm_sq a b
7887ded90efdf902b06766b3a696f2c718091b77
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/adjunction/default.lean
2332ab897fe05ead7fd9a0e799b0f613fdd996c7
[]
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
258
lean
import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.adjunction.limits import Mathlib.category_theory.adjunction.opposites import Mathlib.category_theory.adjunction.reflective import Mathlib.PostPort namespace Mathlib
92029b320fa98b3ef8cc67fe3d213e8122920a76
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/data/rbtree/default.lean
5f4c624f847986368cc4a3a30185c61045668f0f
[]
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
256
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.data.rbtree.basic namespace Mathlib
df7bc740dc3f8600a4d529c51b6cd8bccd248192
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/2077.lean
cbee5c37ef538195e3ee1086b253403c07987ede
[ "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
576
lean
import Lean noncomputable section @[simp] def foo : Nat := 1 @[simp] noncomputable def bar : Nat := Classical.choice ⟨0⟩ @[simp] def baz : Nat := Classical.choice ⟨0⟩ -- `@[simp]` attribute doesn't get executed open Lean Meta Elab Command #eval liftCoreM <| do let x1 := simpExtension.getState (← getEnv) |>.toUnfold.contains <| ``foo let x2 := simpExtension.getState (← getEnv) |>.toUnfold.contains <| ``bar let x3 := simpExtension.getState (← getEnv) |>.toUnfold.contains <| ``baz logInfo m!"{x1} {x2} {x3}" -- should not return: "true true false".
51fc2441f56bdc5fd9301ee0fb64b4e70fc8714e
63abd62053d479eae5abf4951554e1064a4c45b4
/src/ring_theory/polynomial/scale_roots.lean
b916e8f00477f4517a31b09654a6b8a741cd7e68
[ "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
5,101
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen, Devon Tuma -/ import ring_theory.polynomial.basic import ring_theory.non_zero_divisors section scale_roots variables {A K R S : Type*} [integral_domain A] [field K] [comm_ring R] [comm_ring S] variables {M : submonoid A} open finsupp polynomial /-- `scale_roots p s` is a polynomial with root `r * s` for each root `r` of `p`. -/ noncomputable def scale_roots (p : polynomial R) (s : R) : polynomial R := on_finset p.support (λ i, coeff p i * s ^ (p.nat_degree - i)) (λ i h, mem_support_iff.mpr (left_ne_zero_of_mul h)) @[simp] lemma coeff_scale_roots (p : polynomial R) (s : R) (i : ℕ) : (scale_roots p s).coeff i = coeff p i * s ^ (p.nat_degree - i) := rfl lemma coeff_scale_roots_nat_degree (p : polynomial R) (s : R) : (scale_roots p s).coeff p.nat_degree = p.leading_coeff := by rw [leading_coeff, coeff_scale_roots, nat.sub_self, pow_zero, mul_one] @[simp] lemma zero_scale_roots (s : R) : scale_roots 0 s = 0 := by { ext, simp } lemma scale_roots_ne_zero {p : polynomial R} (hp : p ≠ 0) (s : R) : scale_roots p s ≠ 0 := begin intro h, have : p.coeff p.nat_degree ≠ 0 := mt leading_coeff_eq_zero.mp hp, have : (scale_roots p s).coeff p.nat_degree = 0 := congr_fun (congr_arg (coeff : polynomial R → ℕ → R) h) p.nat_degree, rw [coeff_scale_roots_nat_degree] at this, contradiction end lemma support_scale_roots_le (p : polynomial R) (s : R) : (scale_roots p s).support ≤ p.support := begin intros i, simp only [mem_support_iff, scale_roots, on_finset_apply], exact left_ne_zero_of_mul end lemma support_scale_roots_eq (p : polynomial R) {s : R} (hs : s ∈ non_zero_divisors R) : (scale_roots p s).support = p.support := le_antisymm (support_scale_roots_le p s) begin intro i, simp only [mem_support_iff, scale_roots, on_finset_apply], intros p_ne_zero ps_zero, have := ((non_zero_divisors R).pow_mem hs (p.nat_degree - i)) _ ps_zero, contradiction end @[simp] lemma degree_scale_roots (p : polynomial R) {s : R} : degree (scale_roots p s) = degree p := begin haveI := classical.prop_decidable, by_cases hp : p = 0, { rw [hp, zero_scale_roots] }, have := scale_roots_ne_zero hp s, refine le_antisymm (finset.sup_mono (support_scale_roots_le p s)) (degree_le_degree _), rw coeff_scale_roots_nat_degree, intro h, have := leading_coeff_eq_zero.mp h, contradiction, end @[simp] lemma nat_degree_scale_roots (p : polynomial R) (s : R) : nat_degree (scale_roots p s) = nat_degree p := by simp only [nat_degree, degree_scale_roots] lemma monic_scale_roots_iff {p : polynomial R} (s : R) : monic (scale_roots p s) ↔ monic p := by simp only [monic, leading_coeff, nat_degree_scale_roots, coeff_scale_roots_nat_degree] lemma scale_roots_eval₂_eq_zero {p : polynomial S} (f : S →+* R) {r : R} {s : S} (hr : eval₂ f r p = 0) : eval₂ f (f s * r) (scale_roots p s) = 0 := calc eval₂ f (f s * r) (scale_roots p s) = (scale_roots p s).support.sum (λ i, f (coeff p i * s ^ (p.nat_degree - i)) * (f s * r) ^ i) : eval₂_eq_sum ... = p.support.sum (λ i, f (coeff p i * s ^ (p.nat_degree - i)) * (f s * r) ^ i) : finset.sum_subset (support_scale_roots_le p s) (λ i hi hi', let this : coeff p i * s ^ (p.nat_degree - i) = 0 := by simpa using hi' in by simp [this]) ... = p.support.sum (λ (i : ℕ), f (p.coeff i) * f s ^ (p.nat_degree - i + i) * r ^ i) : finset.sum_congr rfl (λ i hi, by simp_rw [f.map_mul, f.map_pow, pow_add, mul_pow, mul_assoc]) ... = p.support.sum (λ (i : ℕ), f s ^ p.nat_degree * (f (p.coeff i) * r ^ i)) : finset.sum_congr rfl (λ i hi, by { rw [mul_assoc, mul_left_comm, nat.sub_add_cancel], exact le_nat_degree_of_ne_zero (mem_support_iff.mp hi) }) ... = f s ^ p.nat_degree * p.support.sum (λ (i : ℕ), (f (p.coeff i) * r ^ i)) : finset.mul_sum.symm ... = f s ^ p.nat_degree * eval₂ f r p : by { rw [eval₂_eq_sum], refl } ... = 0 : by rw [hr, _root_.mul_zero] lemma scale_roots_aeval_eq_zero [algebra S R] {p : polynomial S} {r : R} {s : S} (hr : aeval r p = 0) : aeval (algebra_map S R s * r) (scale_roots p s) = 0 := scale_roots_eval₂_eq_zero (algebra_map S R) hr lemma scale_roots_eval₂_eq_zero_of_eval₂_div_eq_zero {p : polynomial A} {f : A →+* K} (hf : function.injective f) {r s : A} (hr : eval₂ f (f r / f s) p = 0) (hs : s ∈ non_zero_divisors A) : eval₂ f (f r) (scale_roots p s) = 0 := begin convert scale_roots_eval₂_eq_zero f hr, rw [←mul_div_assoc, mul_comm, mul_div_cancel], exact @map_ne_zero_of_mem_non_zero_divisors _ _ _ _ _ _ hf ⟨s, hs⟩ end lemma scale_roots_aeval_eq_zero_of_aeval_div_eq_zero [algebra A K] (inj : function.injective (algebra_map A K)) {p : polynomial A} {r s : A} (hr : aeval (algebra_map A K r / algebra_map A K s) p = 0) (hs : s ∈ non_zero_divisors A) : aeval (algebra_map A K r) (scale_roots p s) = 0 := scale_roots_eval₂_eq_zero_of_eval₂_div_eq_zero inj hr hs end scale_roots
b055298af3d176e96c482d11d7a267c60c138a70
94e33a31faa76775069b071adea97e86e218a8ee
/src/category_theory/natural_isomorphism.lean
db6947c5a6bcb0de4b1760f39728bcc618a13520
[ "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
7,822
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tim Baumann, Stephen Morgan, Scott Morrison, Floris van Doorn -/ import category_theory.functor.category import category_theory.isomorphism /-! # Natural isomorphisms For the most part, natural isomorphisms are just another sort of isomorphism. We provide some special support for extracting components: * if `α : F ≅ G`, then `a.app X : F.obj X ≅ G.obj X`, and building natural isomorphisms from components: * ``` nat_iso.of_components (app : ∀ X : C, F.obj X ≅ G.obj X) (naturality : ∀ {X Y : C} (f : X ⟶ Y), F.map f ≫ (app Y).hom = (app X).hom ≫ G.map f) : F ≅ G ``` only needing to check naturality in one direction. ## Implementation Note that `nat_iso` is a namespace without a corresponding definition; we put some declarations that are specifically about natural isomorphisms in the `iso` namespace so that they are available using dot notation. -/ open category_theory -- declare the `v`'s first; see `category_theory.category` for an explanation universes v₁ v₂ v₃ v₄ u₁ u₂ u₃ u₄ namespace category_theory open nat_trans variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] {E : Type u₃} [category.{v₃} E] namespace iso /-- The application of a natural isomorphism to an object. We put this definition in a different namespace, so that we can use `α.app` -/ @[simps] def app {F G : C ⥤ D} (α : F ≅ G) (X : C) : F.obj X ≅ G.obj X := { hom := α.hom.app X, inv := α.inv.app X, hom_inv_id' := begin rw [← comp_app, iso.hom_inv_id], refl end, inv_hom_id' := begin rw [← comp_app, iso.inv_hom_id], refl end } @[simp, reassoc] lemma hom_inv_id_app {F G : C ⥤ D} (α : F ≅ G) (X : C) : α.hom.app X ≫ α.inv.app X = 𝟙 (F.obj X) := congr_fun (congr_arg nat_trans.app α.hom_inv_id) X @[simp, reassoc] lemma inv_hom_id_app {F G : C ⥤ D} (α : F ≅ G) (X : C) : α.inv.app X ≫ α.hom.app X = 𝟙 (G.obj X) := congr_fun (congr_arg nat_trans.app α.inv_hom_id) X end iso namespace nat_iso open category_theory.category category_theory.functor @[simp] lemma trans_app {F G H : C ⥤ D} (α : F ≅ G) (β : G ≅ H) (X : C) : (α ≪≫ β).app X = α.app X ≪≫ β.app X := rfl lemma app_hom {F G : C ⥤ D} (α : F ≅ G) (X : C) : (α.app X).hom = α.hom.app X := rfl lemma app_inv {F G : C ⥤ D} (α : F ≅ G) (X : C) : (α.app X).inv = α.inv.app X := rfl variables {F G : C ⥤ D} instance hom_app_is_iso (α : F ≅ G) (X : C) : is_iso (α.hom.app X) := ⟨⟨α.inv.app X, ⟨by rw [←comp_app, iso.hom_inv_id, ←id_app], by rw [←comp_app, iso.inv_hom_id, ←id_app]⟩⟩⟩ instance inv_app_is_iso (α : F ≅ G) (X : C) : is_iso (α.inv.app X) := ⟨⟨α.hom.app X, ⟨by rw [←comp_app, iso.inv_hom_id, ←id_app], by rw [←comp_app, iso.hom_inv_id, ←id_app]⟩⟩⟩ section /-! Unfortunately we need a separate set of cancellation lemmas for components of natural isomorphisms, because the `simp` normal form is `α.hom.app X`, rather than `α.app.hom X`. (With the later, the morphism would be visibly part of an isomorphism, so general lemmas about isomorphisms would apply.) In the future, we should consider a redesign that changes this simp norm form, but for now it breaks too many proofs. -/ variables (α : F ≅ G) @[simp] lemma cancel_nat_iso_hom_left {X : C} {Z : D} (g g' : G.obj X ⟶ Z) : α.hom.app X ≫ g = α.hom.app X ≫ g' ↔ g = g' := by simp only [cancel_epi] @[simp] lemma cancel_nat_iso_inv_left {X : C} {Z : D} (g g' : F.obj X ⟶ Z) : α.inv.app X ≫ g = α.inv.app X ≫ g' ↔ g = g' := by simp only [cancel_epi] @[simp] lemma cancel_nat_iso_hom_right {X : D} {Y : C} (f f' : X ⟶ F.obj Y) : f ≫ α.hom.app Y = f' ≫ α.hom.app Y ↔ f = f' := by simp only [cancel_mono] @[simp] lemma cancel_nat_iso_inv_right {X : D} {Y : C} (f f' : X ⟶ G.obj Y) : f ≫ α.inv.app Y = f' ≫ α.inv.app Y ↔ f = f' := by simp only [cancel_mono] @[simp] lemma cancel_nat_iso_hom_right_assoc {W X X' : D} {Y : C} (f : W ⟶ X) (g : X ⟶ F.obj Y) (f' : W ⟶ X') (g' : X' ⟶ F.obj Y) : f ≫ g ≫ α.hom.app Y = f' ≫ g' ≫ α.hom.app Y ↔ f ≫ g = f' ≫ g' := by simp only [←category.assoc, cancel_mono] @[simp] lemma cancel_nat_iso_inv_right_assoc {W X X' : D} {Y : C} (f : W ⟶ X) (g : X ⟶ G.obj Y) (f' : W ⟶ X') (g' : X' ⟶ G.obj Y) : f ≫ g ≫ α.inv.app Y = f' ≫ g' ≫ α.inv.app Y ↔ f ≫ g = f' ≫ g' := by simp only [←category.assoc, cancel_mono] @[simp] lemma inv_inv_app {F G : C ⥤ D} (e : F ≅ G) (X : C) : inv (e.inv.app X) = e.hom.app X := by { ext, simp } end variables {X Y : C} lemma naturality_1 (α : F ≅ G) (f : X ⟶ Y) : α.inv.app X ≫ F.map f ≫ α.hom.app Y = G.map f := by simp lemma naturality_2 (α : F ≅ G) (f : X ⟶ Y) : α.hom.app X ≫ G.map f ≫ α.inv.app Y = F.map f := by simp lemma naturality_1' (α : F ⟶ G) (f : X ⟶ Y) [is_iso (α.app X)] : inv (α.app X) ≫ F.map f ≫ α.app Y = G.map f := by simp @[simp, reassoc] lemma naturality_2' (α : F ⟶ G) (f : X ⟶ Y) [is_iso (α.app Y)] : α.app X ≫ G.map f ≫ inv (α.app Y) = F.map f := by rw [←category.assoc, ←naturality, category.assoc, is_iso.hom_inv_id, category.comp_id] /-- The components of a natural isomorphism are isomorphisms. -/ instance is_iso_app_of_is_iso (α : F ⟶ G) [is_iso α] (X) : is_iso (α.app X) := ⟨⟨(inv α).app X, ⟨congr_fun (congr_arg nat_trans.app (is_iso.hom_inv_id α)) X, congr_fun (congr_arg nat_trans.app (is_iso.inv_hom_id α)) X⟩⟩⟩ @[simp] lemma is_iso_inv_app (α : F ⟶ G) [is_iso α] (X) : (inv α).app X = inv (α.app X) := by { ext, rw ←nat_trans.comp_app, simp, } @[simp] lemma inv_map_inv_app (F : C ⥤ D ⥤ E) {X Y : C} (e : X ≅ Y) (Z : D) : inv ((F.map e.inv).app Z) = (F.map e.hom).app Z := by { ext, simp, } /-- Construct a natural isomorphism between functors by giving object level isomorphisms, and checking naturality only in the forward direction. -/ def of_components (app : ∀ X : C, F.obj X ≅ G.obj X) (naturality : ∀ {X Y : C} (f : X ⟶ Y), F.map f ≫ (app Y).hom = (app X).hom ≫ G.map f) : F ≅ G := { hom := { app := λ X, (app X).hom }, inv := { app := λ X, (app X).inv, naturality' := λ X Y f, begin have h := congr_arg (λ f, (app X).inv ≫ (f ≫ (app Y).inv)) (naturality f).symm, simp only [iso.inv_hom_id_assoc, iso.hom_inv_id, assoc, comp_id, cancel_mono] at h, exact h end }, } @[simp] lemma of_components.app (app' : ∀ X : C, F.obj X ≅ G.obj X) (naturality) (X) : (of_components app' naturality).app X = app' X := by tidy @[simp] lemma of_components.hom_app (app : ∀ X : C, F.obj X ≅ G.obj X) (naturality) (X) : (of_components app naturality).hom.app X = (app X).hom := rfl @[simp] lemma of_components.inv_app (app : ∀ X : C, F.obj X ≅ G.obj X) (naturality) (X) : (of_components app naturality).inv.app X = (app X).inv := by simp [of_components] /-- A natural transformation is an isomorphism if all its components are isomorphisms. -/ -- Making this an instance would cause a typeclass inference loop with `is_iso_app_of_is_iso`. lemma is_iso_of_is_iso_app (α : F ⟶ G) [∀ X : C, is_iso (α.app X)] : is_iso α := ⟨(is_iso.of_iso (of_components (λ X, as_iso (α.app X)) (by tidy))).1⟩ /-- Horizontal composition of natural isomorphisms. -/ def hcomp {F G : C ⥤ D} {H I : D ⥤ E} (α : F ≅ G) (β : H ≅ I) : F ⋙ H ≅ G ⋙ I := begin refine ⟨α.hom ◫ β.hom, α.inv ◫ β.inv, _, _⟩, { ext, rw [←nat_trans.exchange], simp, refl }, ext, rw [←nat_trans.exchange], simp, refl end end nat_iso end category_theory
35e3e461953bedc7fa82b44adcd0987c7428a798
52b9f0379b3b0200088f3b2ec594d4dd3d3e6128
/factor_matrix.lean
26aacb776de068afd92e455e43861ed51fad47d2
[]
no_license
minchaowu/mathematica_examples
f83fdf092a136f157dde8119b8a75c2cd4d91aae
fcc65b0b9fcb854f8671c0ebbca77bb3c1a9ecc1
refs/heads/master
1,610,729,580,720
1,498,331,049,000
1,498,331,049,000
99,731,631
0
0
null
1,502,222,706,000
1,502,222,706,000
null
UTF-8
Lean
false
false
2,366
lean
/- Copyright (c) 2017 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis -/ import init.meta.mathematica .bquant .datatypes open expr tactic @[reducible] def {u} ith {α : Type u} [inhabited α] (l : list α) (i : ℕ) : α := match l^.nth i with | some a := a | none := default α end def {u} transpose_list {α : Type u} [inhabited α] (m : list (list α)) : list (list α) := list.map (λ i, m^.map (λ l, ith l i)) (native.upto (ith m 0)^.length) def {u} dot_lists {α : Type u} [has_zero α] [has_mul α] [has_add α] : list α → list α → α | [a] [b] := a*b | (h1::t1) (h2::t2) := h1*h2 + dot_lists t1 t2 | _ _ := 0 def {u} mul_lists {α : Type u} [has_zero α] [has_mul α] [has_add α] [inhabited α] (m1 m2 : list (list α)) : list (list α) := list.map (λ i, (list.map (λ j, dot_lists (ith m1 i) (ith (transpose_list m2) j)) (native.upto (ith m1 0)^.length))) (native.upto m1^.length) infix `**`:50 := mul_lists @[reducible] def {u} is_lower_triangular {α : Type u} [has_lt α] [has_zero α] (m : list (list α)) : Prop := ∀ i < m^.length, ∀ j < (ith m i)^.length, i < j → ith (ith m i) j = 0 @[reducible] def {u} is_upper_triangular {α : Type u} [has_lt α] [has_zero α] (m : list (list α)) : Prop := ∀ i < m^.length, ∀ j < (ith m i)^.length, i > j → ith (ith m i) j = 0 meta def dec_triv_tac : tactic unit := do t ← target, to_expr ```(dec_trivial : %%t) >>= apply meta def lu_tac : tactic unit := do t ← target, (lam _ _ _ bd) ← return $ app_arg t, (lam _ _ _ ande) ← return $ app_arg bd, `(%%_ ∧ %%_ ∧ %%_ = %%e) ← return $ ande, tp ← infer_type e, m ← mathematica.run_command_on_using (λ e, e ++ " // LeanForm // Activate // LUDecomp") e "~/lean/lean/extras/mathematica/matrix_factor.m", m2 ← to_expr ```((%%m : list %%tp)), lhs ← to_expr ```(ith %%m2 0), rhs ← to_expr ```(ith %%m2 1), existsi lhs, existsi rhs, split, dec_triv_tac, split, dec_triv_tac, reflexivity example : ∃ l u, is_lower_triangular l ∧ is_upper_triangular u ∧ mul_lists l u = [[(1 : ℤ), 2], [3, 4]] := by lu_tac example : ∃ l u, is_lower_triangular l ∧ is_upper_triangular u ∧ l ** u = [[1, 2, 3], [1, 4, 9], [1, 8, 27]] := by lu_tac
475db8106330bc2da83a63fcc6518b406a475b2f
e0b0b1648286e442507eb62344760d5cd8d13f2d
/stage0/src/Lean/Parser/Basic.lean
7f65798c7e12092907b29ff77bc3733b12c291f7
[ "Apache-2.0" ]
permissive
MULXCODE/lean4
743ed389e05e26e09c6a11d24607ad5a697db39b
4675817a9e89824eca37192364cd47a4027c6437
refs/heads/master
1,682,231,879,857
1,620,423,501,000
1,620,423,501,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
76,120
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ /-! # Basic Lean parser infrastructure The Lean parser was developed with the following primary goals in mind: * flexibility: Lean's grammar is complex and includes indentation and other whitespace sensitivity. It should be possible to introduce such custom "tweaks" locally without having to adjust the fundamental parsing approach. * extensibility: Lean's grammar can be extended on the fly within a Lean file, and with Lean 4 we want to extend this to cover embedding domain-specific languages that may look nothing like Lean, down to using a separate set of tokens. * losslessness: The parser should produce a concrete syntax tree that preserves all whitespace and other "sub-token" information for the use in tooling. * performance: The overhead of the parser building blocks, and the overall parser performance on average-complexity input, should be comparable with that of the previous parser hand-written in C++. No fancy optimizations should be necessary for this. Given these constraints, we decided to implement a combinatoric, non-monadic, lexer-less, memoizing recursive-descent parser. Using combinators instead of some more formal and introspectible grammar representation ensures ultimate flexibility as well as efficient extensibility: there is (almost) no pre-processing necessary when extending the grammar with a new parser. However, because the all results the combinators produce are of the homogeneous `Syntax` type, the basic parser type is not actually a monad but a monomorphic linear function `ParserState → ParserState`, avoiding constructing and deconstructing countless monadic return values. Instead of explicitly returning syntax objects, parsers push (zero or more of) them onto a syntax stack inside the linear state. Chaining parsers via `>>` accumulates their output on the stack. Combinators such as `node` then pop off all syntax objects produced during their invocation and wrap them in a single `Syntax.node` object that is again pushed on this stack. Instead of calling `node` directly, we usually use the macro `leading_parser p`, which unfolds to `node k p` where the new syntax node kind `k` is the name of the declaration being defined. The lack of a dedicated lexer ensures we can modify and replace the lexical grammar at any point, and simplifies detecting and propagating whitespace. The parser still has a concept of "tokens", however, and caches the most recent one for performance: when `tokenFn` is called twice at the same position in the input, it will reuse the result of the first call. `tokenFn` recognizes some built-in variable-length tokens such as identifiers as well as any fixed token in the `ParserContext`'s `TokenTable` (a trie); however, the same cache field and strategy could be reused by custom token parsers. Tokens also play a central role in the `prattParser` combinator, which selects a *leading* parser followed by zero or more *trailing* parsers based on the current token (via `peekToken`); see the documentation of `prattParser` for more details. Tokens are specified via the `symbol` parser, or with `symbolNoWs` for tokens that should not be preceded by whitespace. The `Parser` type is extended with additional metadata over the mere parsing function to propagate token information: `collectTokens` collects all tokens within a parser for registering. `firstTokens` holds information about the "FIRST" token set used to speed up parser selection in `prattParser`. This approach of combining static and dynamic information in the parser type is inspired by the paper "Deterministic, Error-Correcting Combinator Parsers" by Swierstra and Duponcheel. If multiple parsers accept the same current token, `prattParser` tries all of them using the backtracking `longestMatchFn` combinator. This is the only case where standard parsers might execute arbitrary backtracking. At the moment there is no memoization shared by these parallel parsers apart from the first token, though we might change this in the future if the need arises. Finally, error reporting follows the standard combinatoric approach of collecting a single unexpected token/... and zero or more expected tokens (see `Error` below). Expected tokens are e.g. set by `symbol` and merged by `<|>`. Combinators running multiple parsers should check if an error message is set in the parser state (`hasError`) and act accordingly. Error recovery is left to the designer of the specific language; for example, Lean's top-level `parseCommand` loop skips tokens until the next command keyword on error. -/ import Lean.Data.Trie import Lean.Data.Position import Lean.Syntax import Lean.ToExpr import Lean.Environment import Lean.Attributes import Lean.Message import Lean.Compiler.InitAttr import Lean.ResolveName namespace Lean namespace Parser def isLitKind (k : SyntaxNodeKind) : Bool := k == strLitKind || k == numLitKind || k == charLitKind || k == nameLitKind || k == scientificLitKind abbrev mkAtom (info : SourceInfo) (val : String) : Syntax := Syntax.atom info val abbrev mkIdent (info : SourceInfo) (rawVal : Substring) (val : Name) : Syntax := Syntax.ident info rawVal val [] /- Return character after position `pos` -/ def getNext (input : String) (pos : Nat) : Char := input.get (input.next pos) /- Maximal (and function application) precedence. In the standard lean language, no parser has precedence higher than `maxPrec`. Note that nothing prevents users from using a higher precedence, but we strongly discourage them from doing it. -/ def maxPrec : Nat := eval_prec max def argPrec : Nat := eval_prec arg def leadPrec : Nat := eval_prec lead def minPrec : Nat := eval_prec min abbrev Token := String structure TokenCacheEntry where startPos : String.Pos := 0 stopPos : String.Pos := 0 token : Syntax := Syntax.missing structure ParserCache where tokenCache : TokenCacheEntry def initCacheForInput (input : String) : ParserCache := { tokenCache := { startPos := input.bsize + 1 /- make sure it is not a valid position -/} } abbrev TokenTable := Trie Token abbrev SyntaxNodeKindSet := Std.PersistentHashMap SyntaxNodeKind Unit def SyntaxNodeKindSet.insert (s : SyntaxNodeKindSet) (k : SyntaxNodeKind) : SyntaxNodeKindSet := Std.PersistentHashMap.insert s k () /- Input string and related data. Recall that the `FileMap` is a helper structure for mapping `String.Pos` in the input string to line/column information. -/ structure InputContext where input : String fileName : String fileMap : FileMap deriving Inhabited /-- Input context derived from elaboration of previous commands. -/ structure ParserModuleContext where env : Environment options : Options -- for name lookup currNamespace : Name := Name.anonymous openDecls : List OpenDecl := [] structure ParserContext extends InputContext, ParserModuleContext where prec : Nat tokens : TokenTable quotDepth : Nat := 0 suppressInsideQuot : Bool := false savedPos? : Option String.Pos := none forbiddenTk? : Option Token := none def ParserContext.resolveName (ctx : ParserContext) (id : Name) : List (Name × List String) := ResolveName.resolveGlobalName ctx.env ctx.currNamespace ctx.openDecls id structure Error where unexpected : String := "" expected : List String := [] deriving Inhabited, BEq namespace Error private def expectedToString : List String → String | [] => "" | [e] => e | [e1, e2] => e1 ++ " or " ++ e2 | e::es => e ++ ", " ++ expectedToString es protected def toString (e : Error) : String := let unexpected := if e.unexpected == "" then [] else [e.unexpected] let expected := if e.expected == [] then [] else let expected := e.expected.toArray.qsort (fun e e' => e < e') let expected := expected.toList.eraseReps ["expected " ++ expectedToString expected] "; ".intercalate $ unexpected ++ expected instance : ToString Error := ⟨Error.toString⟩ def merge (e₁ e₂ : Error) : Error := match e₂ with | { unexpected := u, .. } => { unexpected := if u == "" then e₁.unexpected else u, expected := e₁.expected ++ e₂.expected } end Error structure ParserState where stxStack : Array Syntax := #[] /-- Set to the precedence of the preceding (not surrounding) parser by `runLongestMatchParser` for the use of `checkLhsPrec` in trailing parsers. Note that with chaining, the preceding parser can be another trailing parser: in `1 * 2 + 3`, the preceding parser is '*' when '+' is executed. -/ lhsPrec : Nat := 0 pos : String.Pos := 0 cache : ParserCache errorMsg : Option Error := none namespace ParserState @[inline] def hasError (s : ParserState) : Bool := s.errorMsg != none @[inline] def stackSize (s : ParserState) : Nat := s.stxStack.size def restore (s : ParserState) (iniStackSz : Nat) (iniPos : Nat) : ParserState := { s with stxStack := s.stxStack.shrink iniStackSz, errorMsg := none, pos := iniPos } def setPos (s : ParserState) (pos : Nat) : ParserState := { s with pos := pos } def setCache (s : ParserState) (cache : ParserCache) : ParserState := { s with cache := cache } def pushSyntax (s : ParserState) (n : Syntax) : ParserState := { s with stxStack := s.stxStack.push n } def popSyntax (s : ParserState) : ParserState := { s with stxStack := s.stxStack.pop } def shrinkStack (s : ParserState) (iniStackSz : Nat) : ParserState := { s with stxStack := s.stxStack.shrink iniStackSz } def next (s : ParserState) (input : String) (pos : Nat) : ParserState := { s with pos := input.next pos } def toErrorMsg (ctx : ParserContext) (s : ParserState) : String := match s.errorMsg with | none => "" | some msg => let pos := ctx.fileMap.toPosition s.pos mkErrorStringWithPos ctx.fileName pos (toString msg) def mkNode (s : ParserState) (k : SyntaxNodeKind) (iniStackSz : Nat) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, err⟩ => if err != none && stack.size == iniStackSz then -- If there is an error but there are no new nodes on the stack, use `missing` instead. -- Thus we ensure the property that an syntax tree contains (at least) one `missing` node -- if (and only if) there was a parse error. -- We should not create an actual node of kind `k` in this case because it would mean we -- choose an "arbitrary" node (in practice the last one) in an alternative of the form -- `node k1 p1 <|> ... <|> node kn pn` when all parsers fail. With the code below we -- instead return a less misleading single `missing` node without randomly selecting any `ki`. let stack := stack.push Syntax.missing ⟨stack, lhsPrec, pos, cache, err⟩ else let newNode := Syntax.node k (stack.extract iniStackSz stack.size) let stack := stack.shrink iniStackSz let stack := stack.push newNode ⟨stack, lhsPrec, pos, cache, err⟩ def mkTrailingNode (s : ParserState) (k : SyntaxNodeKind) (iniStackSz : Nat) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, err⟩ => let newNode := Syntax.node k (stack.extract (iniStackSz - 1) stack.size) let stack := stack.shrink (iniStackSz - 1) let stack := stack.push newNode ⟨stack, lhsPrec, pos, cache, err⟩ def setError (s : ParserState) (msg : String) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, _⟩ => ⟨stack, lhsPrec, pos, cache, some { expected := [ msg ] }⟩ def mkError (s : ParserState) (msg : String) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, _⟩ => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { expected := [ msg ] }⟩ def mkUnexpectedError (s : ParserState) (msg : String) (expected : List String := []) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, _⟩ => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { unexpected := msg, expected := expected }⟩ def mkEOIError (s : ParserState) (expected : List String := []) : ParserState := s.mkUnexpectedError "unexpected end of input" expected def mkErrorAt (s : ParserState) (msg : String) (pos : String.Pos) (initStackSz? : Option Nat := none) : ParserState := match s, initStackSz? with | ⟨stack, lhsPrec, _, cache, _⟩, none => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { expected := [ msg ] }⟩ | ⟨stack, lhsPrec, _, cache, _⟩, some sz => ⟨stack.shrink sz |>.push Syntax.missing, lhsPrec, pos, cache, some { expected := [ msg ] }⟩ def mkErrorsAt (s : ParserState) (ex : List String) (pos : String.Pos) (initStackSz? : Option Nat := none) : ParserState := match s, initStackSz? with | ⟨stack, lhsPrec, _, cache, _⟩, none => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { expected := ex }⟩ | ⟨stack, lhsPrec, _, cache, _⟩, some sz => ⟨stack.shrink sz |>.push Syntax.missing, lhsPrec, pos, cache, some { expected := ex }⟩ def mkUnexpectedErrorAt (s : ParserState) (msg : String) (pos : String.Pos) : ParserState := match s with | ⟨stack, lhsPrec, _, cache, _⟩ => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { unexpected := msg }⟩ end ParserState def ParserFn := ParserContext → ParserState → ParserState instance : Inhabited ParserFn where default := fun ctx s => s inductive FirstTokens where | epsilon : FirstTokens | unknown : FirstTokens | tokens : List Token → FirstTokens | optTokens : List Token → FirstTokens deriving Inhabited namespace FirstTokens def seq : FirstTokens → FirstTokens → FirstTokens | epsilon, tks => tks | optTokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂) | optTokens s₁, tokens s₂ => tokens (s₁ ++ s₂) | tks, _ => tks def toOptional : FirstTokens → FirstTokens | tokens tks => optTokens tks | tks => tks def merge : FirstTokens → FirstTokens → FirstTokens | epsilon, tks => toOptional tks | tks, epsilon => toOptional tks | tokens s₁, tokens s₂ => tokens (s₁ ++ s₂) | optTokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂) | tokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂) | optTokens s₁, tokens s₂ => optTokens (s₁ ++ s₂) | _, _ => unknown def toStr : FirstTokens → String | epsilon => "epsilon" | unknown => "unknown" | tokens tks => toString tks | optTokens tks => "?" ++ toString tks instance : ToString FirstTokens := ⟨toStr⟩ end FirstTokens structure ParserInfo where collectTokens : List Token → List Token := id collectKinds : SyntaxNodeKindSet → SyntaxNodeKindSet := id firstTokens : FirstTokens := FirstTokens.unknown deriving Inhabited structure Parser where info : ParserInfo := {} fn : ParserFn deriving Inhabited abbrev TrailingParser := Parser def dbgTraceStateFn (label : String) (p : ParserFn) : ParserFn := fun c s => let sz := s.stxStack.size let s' := p c s dbg_trace "{label} pos: {s'.pos} err: {s'.errorMsg} out: {s'.stxStack.extract sz s'.stxStack.size}" s' def dbgTraceState (label : String) (p : Parser) : Parser where fn := dbgTraceStateFn label p.fn info := p.info @[noinline] def epsilonInfo : ParserInfo := { firstTokens := FirstTokens.epsilon } @[inline] def checkStackTopFn (p : Syntax → Bool) (msg : String) : ParserFn := fun c s => if p s.stxStack.back then s else s.mkUnexpectedError msg @[inline] def checkStackTop (p : Syntax → Bool) (msg : String) : Parser := { info := epsilonInfo, fn := checkStackTopFn p msg } @[inline] def andthenFn (p q : ParserFn) : ParserFn := fun c s => let s := p c s if s.hasError then s else q c s @[noinline] def andthenInfo (p q : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens ∘ q.collectTokens, collectKinds := p.collectKinds ∘ q.collectKinds, firstTokens := p.firstTokens.seq q.firstTokens } @[inline] def andthen (p q : Parser) : Parser := { info := andthenInfo p.info q.info, fn := andthenFn p.fn q.fn } instance : AndThen Parser := ⟨andthen⟩ @[inline] def nodeFn (n : SyntaxNodeKind) (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let s := p c s s.mkNode n iniSz @[inline] def trailingNodeFn (n : SyntaxNodeKind) (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let s := p c s s.mkTrailingNode n iniSz @[noinline] def nodeInfo (n : SyntaxNodeKind) (p : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens, collectKinds := fun s => (p.collectKinds s).insert n, firstTokens := p.firstTokens } @[inline] def node (n : SyntaxNodeKind) (p : Parser) : Parser := { info := nodeInfo n p.info, fn := nodeFn n p.fn } def errorFn (msg : String) : ParserFn := fun _ s => s.mkUnexpectedError msg @[inline] def error (msg : String) : Parser := { info := epsilonInfo, fn := errorFn msg } def errorAtSavedPosFn (msg : String) (delta : Bool) : ParserFn := fun c s => match c.savedPos? with | none => s | some pos => let pos := if delta then c.input.next pos else pos match s with | ⟨stack, lhsPrec, _, cache, _⟩ => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { unexpected := msg }⟩ /- Generate an error at the position saved with the `withPosition` combinator. If `delta == true`, then it reports at saved position+1. This useful to make sure a parser consumed at least one character. -/ @[inline] def errorAtSavedPos (msg : String) (delta : Bool) : Parser := { fn := errorAtSavedPosFn msg delta } /- Succeeds if `c.prec <= prec` -/ def checkPrecFn (prec : Nat) : ParserFn := fun c s => if c.prec <= prec then s else s.mkUnexpectedError "unexpected token at this precedence level; consider parenthesizing the term" @[inline] def checkPrec (prec : Nat) : Parser := { info := epsilonInfo, fn := checkPrecFn prec } /- Succeeds if `c.lhsPrec >= prec` -/ def checkLhsPrecFn (prec : Nat) : ParserFn := fun c s => if s.lhsPrec >= prec then s else s.mkUnexpectedError "unexpected token at this precedence level; consider parenthesizing the term" @[inline] def checkLhsPrec (prec : Nat) : Parser := { info := epsilonInfo, fn := checkLhsPrecFn prec } def setLhsPrecFn (prec : Nat) : ParserFn := fun c s => if s.hasError then s else { s with lhsPrec := prec } @[inline] def setLhsPrec (prec : Nat) : Parser := { info := epsilonInfo, fn := setLhsPrecFn prec } def checkInsideQuotFn : ParserFn := fun c s => if c.quotDepth > 0 && !c.suppressInsideQuot then s else s.mkUnexpectedError "unexpected syntax outside syntax quotation" @[inline] def checkInsideQuot : Parser := { info := epsilonInfo, fn := checkInsideQuotFn } def checkOutsideQuotFn : ParserFn := fun c s => if !c.quotDepth == 0 || c.suppressInsideQuot then s else s.mkUnexpectedError "unexpected syntax inside syntax quotation" @[inline] def checkOutsideQuot : Parser := { info := epsilonInfo, fn := checkOutsideQuotFn } def addQuotDepthFn (i : Int) (p : ParserFn) : ParserFn := fun c s => p { c with quotDepth := c.quotDepth + i |>.toNat } s @[inline] def incQuotDepth (p : Parser) : Parser := { info := p.info, fn := addQuotDepthFn 1 p.fn } @[inline] def decQuotDepth (p : Parser) : Parser := { info := p.info, fn := addQuotDepthFn (-1) p.fn } def suppressInsideQuotFn (p : ParserFn) : ParserFn := fun c s => p { c with suppressInsideQuot := true } s @[inline] def suppressInsideQuot (p : Parser) : Parser := { info := p.info, fn := suppressInsideQuotFn p.fn } @[inline] def leadingNode (n : SyntaxNodeKind) (prec : Nat) (p : Parser) : Parser := checkPrec prec >> node n p >> setLhsPrec prec @[inline] def trailingNodeAux (n : SyntaxNodeKind) (p : Parser) : TrailingParser := { info := nodeInfo n p.info, fn := trailingNodeFn n p.fn } @[inline] def trailingNode (n : SyntaxNodeKind) (prec lhsPrec : Nat) (p : Parser) : TrailingParser := checkPrec prec >> checkLhsPrec lhsPrec >> trailingNodeAux n p >> setLhsPrec prec def mergeOrElseErrors (s : ParserState) (error1 : Error) (iniPos : Nat) (mergeErrors : Bool) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, some error2⟩ => if pos == iniPos then ⟨stack, lhsPrec, pos, cache, some (if mergeErrors then error1.merge error2 else error2)⟩ else s | other => other def orelseFnCore (p q : ParserFn) (mergeErrors : Bool) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos let s := p c s match s.errorMsg with | some errorMsg => if s.pos == iniPos then mergeOrElseErrors (q c (s.restore iniSz iniPos)) errorMsg iniPos mergeErrors else s | none => s @[inline] def orelseFn (p q : ParserFn) : ParserFn := orelseFnCore p q true @[noinline] def orelseInfo (p q : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens ∘ q.collectTokens, collectKinds := p.collectKinds ∘ q.collectKinds, firstTokens := p.firstTokens.merge q.firstTokens } /-- Run `p`, falling back to `q` if `p` failed without consuming any input. NOTE: In order for the pretty printer to retrace an `orelse`, `p` must be a call to `node` or some other parser producing a single node kind. Nested `orelse` calls are flattened for this, i.e. `(node k1 p1 <|> node k2 p2) <|> ...` is fine as well. -/ @[inline] def orelse (p q : Parser) : Parser := { info := orelseInfo p.info q.info, fn := orelseFn p.fn q.fn } instance : OrElse Parser := ⟨orelse⟩ @[noinline] def noFirstTokenInfo (info : ParserInfo) : ParserInfo := { collectTokens := info.collectTokens, collectKinds := info.collectKinds } def atomicFn (p : ParserFn) : ParserFn := fun c s => let iniPos := s.pos match p c s with | ⟨stack, lhsPrec, _, cache, some msg⟩ => ⟨stack, lhsPrec, iniPos, cache, some msg⟩ | other => other @[inline] def atomic (p : Parser) : Parser := { info := p.info, fn := atomicFn p.fn } def optionalFn (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos let s := p c s let s := if s.hasError && s.pos == iniPos then s.restore iniSz iniPos else s s.mkNode nullKind iniSz @[noinline] def optionaInfo (p : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens, collectKinds := p.collectKinds, firstTokens := p.firstTokens.toOptional } @[inline] def optionalNoAntiquot (p : Parser) : Parser := { info := optionaInfo p.info, fn := optionalFn p.fn } def lookaheadFn (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos let s := p c s if s.hasError then s else s.restore iniSz iniPos @[inline] def lookahead (p : Parser) : Parser := { info := p.info, fn := lookaheadFn p.fn } def notFollowedByFn (p : ParserFn) (msg : String) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos let s := p c s if s.hasError then s.restore iniSz iniPos else let s := s.restore iniSz iniPos s.mkUnexpectedError s!"unexpected {msg}" @[inline] def notFollowedBy (p : Parser) (msg : String) : Parser := { fn := notFollowedByFn p.fn msg } partial def manyAux (p : ParserFn) : ParserFn := fun c s => do let iniSz := s.stackSize let iniPos := s.pos let mut s := p c s if s.hasError then return if iniPos == s.pos then s.restore iniSz iniPos else s if iniPos == s.pos then return s.mkUnexpectedError "invalid 'many' parser combinator application, parser did not consume anything" if s.stackSize > iniSz + 1 then s := s.mkNode nullKind iniSz manyAux p c s @[inline] def manyFn (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let s := manyAux p c s s.mkNode nullKind iniSz @[inline] def manyNoAntiquot (p : Parser) : Parser := { info := noFirstTokenInfo p.info, fn := manyFn p.fn } @[inline] def many1Fn (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let s := andthenFn p (manyAux p) c s s.mkNode nullKind iniSz @[inline] def many1NoAntiquot (p : Parser) : Parser := { info := p.info, fn := many1Fn p.fn } private partial def sepByFnAux (p : ParserFn) (sep : ParserFn) (allowTrailingSep : Bool) (iniSz : Nat) (pOpt : Bool) : ParserFn := let rec parse (pOpt : Bool) (c s) := do let sz := s.stackSize let pos := s.pos let mut s := p c s if s.hasError then if s.pos > pos then return s.mkNode nullKind iniSz else if pOpt then let s := s.restore sz pos return s.mkNode nullKind iniSz else -- append `Syntax.missing` to make clear that List is incomplete let s := s.pushSyntax Syntax.missing return s.mkNode nullKind iniSz if s.stackSize > sz + 1 then s := s.mkNode nullKind sz let sz := s.stackSize let pos := s.pos let s := sep c s if s.hasError then let s := s.restore sz pos return s.mkNode nullKind iniSz if s.stackSize > sz + 1 then s := s.mkNode nullKind sz parse allowTrailingSep c s parse pOpt def sepByFn (allowTrailingSep : Bool) (p : ParserFn) (sep : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize sepByFnAux p sep allowTrailingSep iniSz true c s def sepBy1Fn (allowTrailingSep : Bool) (p : ParserFn) (sep : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize sepByFnAux p sep allowTrailingSep iniSz false c s @[noinline] def sepByInfo (p sep : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens ∘ sep.collectTokens, collectKinds := p.collectKinds ∘ sep.collectKinds } @[noinline] def sepBy1Info (p sep : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens ∘ sep.collectTokens, collectKinds := p.collectKinds ∘ sep.collectKinds, firstTokens := p.firstTokens } @[inline] def sepByNoAntiquot (p sep : Parser) (allowTrailingSep : Bool := false) : Parser := { info := sepByInfo p.info sep.info, fn := sepByFn allowTrailingSep p.fn sep.fn } @[inline] def sepBy1NoAntiquot (p sep : Parser) (allowTrailingSep : Bool := false) : Parser := { info := sepBy1Info p.info sep.info, fn := sepBy1Fn allowTrailingSep p.fn sep.fn } /- Apply `f` to the syntax object produced by `p` -/ def withResultOfFn (p : ParserFn) (f : Syntax → Syntax) : ParserFn := fun c s => let s := p c s if s.hasError then s else let stx := s.stxStack.back s.popSyntax.pushSyntax (f stx) @[noinline] def withResultOfInfo (p : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens, collectKinds := p.collectKinds } @[inline] def withResultOf (p : Parser) (f : Syntax → Syntax) : Parser := { info := withResultOfInfo p.info, fn := withResultOfFn p.fn f } @[inline] def many1Unbox (p : Parser) : Parser := withResultOf (many1NoAntiquot p) fun stx => if stx.getNumArgs == 1 then stx.getArg 0 else stx partial def satisfyFn (p : Char → Bool) (errorMsg : String := "unexpected character") : ParserFn := fun c s => let i := s.pos if c.input.atEnd i then s.mkEOIError else if p (c.input.get i) then s.next c.input i else s.mkUnexpectedError errorMsg partial def takeUntilFn (p : Char → Bool) : ParserFn := fun c s => let i := s.pos if c.input.atEnd i then s else if p (c.input.get i) then s else takeUntilFn p c (s.next c.input i) def takeWhileFn (p : Char → Bool) : ParserFn := takeUntilFn (fun c => !p c) @[inline] def takeWhile1Fn (p : Char → Bool) (errorMsg : String) : ParserFn := andthenFn (satisfyFn p errorMsg) (takeWhileFn p) variable (startPos : String.Pos) in partial def finishCommentBlock (nesting : Nat) : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then eoi s else let curr := input.get i let i := input.next i if curr == '-' then if input.atEnd i then eoi s else let curr := input.get i if curr == '/' then -- "-/" end of comment if nesting == 1 then s.next input i else finishCommentBlock (nesting-1) c (s.next input i) else finishCommentBlock nesting c (s.next input i) else if curr == '/' then if input.atEnd i then eoi s else let curr := input.get i if curr == '-' then finishCommentBlock (nesting+1) c (s.next input i) else finishCommentBlock nesting c (s.setPos i) else finishCommentBlock nesting c (s.setPos i) where eoi s := s.mkUnexpectedErrorAt "unterminated comment" startPos /- Consume whitespace and comments -/ partial def whitespace : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s else let curr := input.get i if curr == '\t' then s.mkUnexpectedError "tabs are not allowed; please configure your editor to expand them" else if curr.isWhitespace then whitespace c (s.next input i) else if curr == '-' then let i := input.next i let curr := input.get i if curr == '-' then andthenFn (takeUntilFn (fun c => c = '\n')) whitespace c (s.next input i) else s else if curr == '/' then let startPos := i let i := input.next i let curr := input.get i if curr == '-' then let i := input.next i let curr := input.get i if curr == '-' then s -- "/--" doc comment is an actual token else andthenFn (finishCommentBlock startPos 1) whitespace c (s.next input i) else s else s def mkEmptySubstringAt (s : String) (p : Nat) : Substring := { str := s, startPos := p, stopPos := p } private def rawAux (startPos : Nat) (trailingWs : Bool) : ParserFn := fun c s => let input := c.input let stopPos := s.pos let leading := mkEmptySubstringAt input startPos let val := input.extract startPos stopPos if trailingWs then let s := whitespace c s let stopPos' := s.pos let trailing := { str := input, startPos := stopPos, stopPos := stopPos' : Substring } let atom := mkAtom (SourceInfo.original leading startPos trailing) val s.pushSyntax atom else let trailing := mkEmptySubstringAt input stopPos let atom := mkAtom (SourceInfo.original leading startPos trailing) val s.pushSyntax atom /-- Match an arbitrary Parser and return the consumed String in a `Syntax.atom`. -/ @[inline] def rawFn (p : ParserFn) (trailingWs := false) : ParserFn := fun c s => let startPos := s.pos let s := p c s if s.hasError then s else rawAux startPos trailingWs c s @[inline] def chFn (c : Char) (trailingWs := false) : ParserFn := rawFn (satisfyFn (fun d => c == d) ("'" ++ toString c ++ "'")) trailingWs def rawCh (c : Char) (trailingWs := false) : Parser := { fn := chFn c trailingWs } def hexDigitFn : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError else let curr := input.get i let i := input.next i if curr.isDigit || ('a' <= curr && curr <= 'f') || ('A' <= curr && curr <= 'F') then s.setPos i else s.mkUnexpectedError "invalid hexadecimal numeral" def quotedCharCoreFn (isQuotable : Char → Bool) : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError else let curr := input.get i if isQuotable curr then s.next input i else if curr == 'x' then andthenFn hexDigitFn hexDigitFn c (s.next input i) else if curr == 'u' then andthenFn hexDigitFn (andthenFn hexDigitFn (andthenFn hexDigitFn hexDigitFn)) c (s.next input i) else s.mkUnexpectedError "invalid escape sequence" def isQuotableCharDefault (c : Char) : Bool := c == '\\' || c == '\"' || c == '\'' || c == 'r' || c == 'n' || c == 't' def quotedCharFn : ParserFn := quotedCharCoreFn isQuotableCharDefault /-- Push `(Syntax.node tk <new-atom>)` into syntax stack -/ def mkNodeToken (n : SyntaxNodeKind) (startPos : Nat) : ParserFn := fun c s => let input := c.input let stopPos := s.pos let leading := mkEmptySubstringAt input startPos let val := input.extract startPos stopPos let s := whitespace c s let wsStopPos := s.pos let trailing := { str := input, startPos := stopPos, stopPos := wsStopPos : Substring } let info := SourceInfo.original leading startPos trailing s.pushSyntax (Syntax.mkLit n val info) def charLitFnAux (startPos : Nat) : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError else let curr := input.get i let s := s.setPos (input.next i) let s := if curr == '\\' then quotedCharFn c s else s if s.hasError then s else let i := s.pos let curr := input.get i let s := s.setPos (input.next i) if curr == '\'' then mkNodeToken charLitKind startPos c s else s.mkUnexpectedError "missing end of character literal" partial def strLitFnAux (startPos : Nat) : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkUnexpectedErrorAt "unterminated string literal" startPos else let curr := input.get i let s := s.setPos (input.next i) if curr == '\"' then mkNodeToken strLitKind startPos c s else if curr == '\\' then andthenFn quotedCharFn (strLitFnAux startPos) c s else strLitFnAux startPos c s def decimalNumberFn (startPos : Nat) (c : ParserContext) : ParserState → ParserState := fun s => let s := takeWhileFn (fun c => c.isDigit) c s let input := c.input let i := s.pos let curr := input.get i if curr == '.' || curr == 'e' || curr == 'E' then let s := parseOptDot s let s := parseOptExp s mkNodeToken scientificLitKind startPos c s else mkNodeToken numLitKind startPos c s where parseOptDot s := let input := c.input let i := s.pos let curr := input.get i if curr == '.' then let i := input.next i let curr := input.get i if curr.isDigit then takeWhileFn (fun c => c.isDigit) c (s.setPos i) else s.setPos i else s parseOptExp s := let input := c.input let i := s.pos let curr := input.get i if curr == 'e' || curr == 'E' then let i := input.next i let i := if input.get i == '-' then input.next i else i let curr := input.get i if curr.isDigit then takeWhileFn (fun c => c.isDigit) c (s.setPos i) else s.setPos i else s def binNumberFn (startPos : Nat) : ParserFn := fun c s => let s := takeWhile1Fn (fun c => c == '0' || c == '1') "binary number" c s mkNodeToken numLitKind startPos c s def octalNumberFn (startPos : Nat) : ParserFn := fun c s => let s := takeWhile1Fn (fun c => '0' ≤ c && c ≤ '7') "octal number" c s mkNodeToken numLitKind startPos c s def hexNumberFn (startPos : Nat) : ParserFn := fun c s => let s := takeWhile1Fn (fun c => ('0' ≤ c && c ≤ '9') || ('a' ≤ c && c ≤ 'f') || ('A' ≤ c && c ≤ 'F')) "hexadecimal number" c s mkNodeToken numLitKind startPos c s def numberFnAux : ParserFn := fun c s => let input := c.input let startPos := s.pos if input.atEnd startPos then s.mkEOIError else let curr := input.get startPos if curr == '0' then let i := input.next startPos let curr := input.get i if curr == 'b' || curr == 'B' then binNumberFn startPos c (s.next input i) else if curr == 'o' || curr == 'O' then octalNumberFn startPos c (s.next input i) else if curr == 'x' || curr == 'X' then hexNumberFn startPos c (s.next input i) else decimalNumberFn startPos c (s.setPos i) else if curr.isDigit then decimalNumberFn startPos c (s.next input startPos) else s.mkError "numeral" def isIdCont : String → ParserState → Bool := fun input s => let i := s.pos let curr := input.get i if curr == '.' then let i := input.next i if input.atEnd i then false else let curr := input.get i isIdFirst curr || isIdBeginEscape curr else false private def isToken (idStartPos idStopPos : Nat) (tk : Option Token) : Bool := match tk with | none => false | some tk => -- if a token is both a symbol and a valid identifier (i.e. a keyword), -- we want it to be recognized as a symbol tk.bsize ≥ idStopPos - idStartPos def mkTokenAndFixPos (startPos : Nat) (tk : Option Token) : ParserFn := fun c s => match tk with | none => s.mkErrorAt "token" startPos | some tk => if c.forbiddenTk? == some tk then s.mkErrorAt "forbidden token" startPos else let input := c.input let leading := mkEmptySubstringAt input startPos let stopPos := startPos + tk.bsize let s := s.setPos stopPos let s := whitespace c s let wsStopPos := s.pos let trailing := { str := input, startPos := stopPos, stopPos := wsStopPos : Substring } let atom := mkAtom (SourceInfo.original leading startPos trailing) tk s.pushSyntax atom def mkIdResult (startPos : Nat) (tk : Option Token) (val : Name) : ParserFn := fun c s => let stopPos := s.pos if isToken startPos stopPos tk then mkTokenAndFixPos startPos tk c s else let input := c.input let rawVal := { str := input, startPos := startPos, stopPos := stopPos : Substring } let s := whitespace c s let trailingStopPos := s.pos let leading := mkEmptySubstringAt input startPos let trailing := { str := input, startPos := stopPos, stopPos := trailingStopPos : Substring } let info := SourceInfo.original leading startPos trailing let atom := mkIdent info rawVal val s.pushSyntax atom partial def identFnAux (startPos : Nat) (tk : Option Token) (r : Name) : ParserFn := let rec parse (r : Name) (c s) := do let input := c.input let i := s.pos if input.atEnd i then return s.mkEOIError let curr := input.get i if isIdBeginEscape curr then let startPart := input.next i let s := takeUntilFn isIdEndEscape c (s.setPos startPart) if input.atEnd s.pos then return s.mkUnexpectedErrorAt "unterminated identifier escape" startPart let stopPart := s.pos let s := s.next c.input s.pos let r := Name.mkStr r (input.extract startPart stopPart) if isIdCont input s then let s := s.next input s.pos parse r c s else mkIdResult startPos tk r c s else if isIdFirst curr then let startPart := i let s := takeWhileFn isIdRest c (s.next input i) let stopPart := s.pos let r := Name.mkStr r (input.extract startPart stopPart) if isIdCont input s then let s := s.next input s.pos parse r c s else mkIdResult startPos tk r c s else mkTokenAndFixPos startPos tk c s parse r private def isIdFirstOrBeginEscape (c : Char) : Bool := isIdFirst c || isIdBeginEscape c private def nameLitAux (startPos : Nat) : ParserFn := fun c s => let input := c.input let s := identFnAux startPos none Name.anonymous c (s.next input startPos) if s.hasError then s else let stx := s.stxStack.back match stx with | Syntax.ident _ rawStr _ _ => let s := s.popSyntax s.pushSyntax (Syntax.node nameLitKind #[mkAtomFrom stx rawStr.toString]) | _ => s.mkError "invalid Name literal" private def tokenFnAux : ParserFn := fun c s => let input := c.input let i := s.pos let curr := input.get i if curr == '\"' then strLitFnAux i c (s.next input i) else if curr == '\'' then charLitFnAux i c (s.next input i) else if curr.isDigit then numberFnAux c s else if curr == '`' && isIdFirstOrBeginEscape (getNext input i) then nameLitAux i c s else let (_, tk) := c.tokens.matchPrefix input i identFnAux i tk Name.anonymous c s private def updateCache (startPos : Nat) (s : ParserState) : ParserState := -- do not cache token parsing errors, which are rare and usually fatal and thus not worth an extra field in `TokenCache` match s with | ⟨stack, lhsPrec, pos, cache, none⟩ => if stack.size == 0 then s else let tk := stack.back ⟨stack, lhsPrec, pos, { tokenCache := { startPos := startPos, stopPos := pos, token := tk } }, none⟩ | other => other def tokenFn (expected : List String := []) : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError expected else let tkc := s.cache.tokenCache if tkc.startPos == i then let s := s.pushSyntax tkc.token s.setPos tkc.stopPos else let s := tokenFnAux c s updateCache i s def peekTokenAux (c : ParserContext) (s : ParserState) : ParserState × Except ParserState Syntax := let iniSz := s.stackSize let iniPos := s.pos let s := tokenFn [] c s if let some e := s.errorMsg then (s.restore iniSz iniPos, Except.error s) else let stx := s.stxStack.back (s.restore iniSz iniPos, Except.ok stx) def peekToken (c : ParserContext) (s : ParserState) : ParserState × Except ParserState Syntax := let tkc := s.cache.tokenCache if tkc.startPos == s.pos then (s, Except.ok tkc.token) else peekTokenAux c s /- Treat keywords as identifiers. -/ def rawIdentFn : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError else identFnAux i none Name.anonymous c s @[inline] def satisfySymbolFn (p : String → Bool) (expected : List String) : ParserFn := fun c s => let initStackSz := s.stackSize let startPos := s.pos let s := tokenFn expected c s if s.hasError then s else match s.stxStack.back with | Syntax.atom _ sym => if p sym then s else s.mkErrorsAt expected startPos initStackSz | _ => s.mkErrorsAt expected startPos initStackSz def symbolFnAux (sym : String) (errorMsg : String) : ParserFn := satisfySymbolFn (fun s => s == sym) [errorMsg] def symbolInfo (sym : String) : ParserInfo := { collectTokens := fun tks => sym :: tks, firstTokens := FirstTokens.tokens [ sym ] } @[inline] def symbolFn (sym : String) : ParserFn := symbolFnAux sym ("'" ++ sym ++ "'") @[inline] def symbolNoAntiquot (sym : String) : Parser := let sym := sym.trim { info := symbolInfo sym, fn := symbolFn sym } def checkTailNoWs (prev : Syntax) : Bool := match prev.getTailInfo with | SourceInfo.original _ _ trailing => trailing.stopPos == trailing.startPos | _ => false /-- Check if the following token is the symbol _or_ identifier `sym`. Useful for parsing local tokens that have not been added to the token table (but may have been so by some unrelated code). For example, the universe `max` Function is parsed using this combinator so that it can still be used as an identifier outside of universes (but registering it as a token in a Term Syntax would not break the universe Parser). -/ def nonReservedSymbolFnAux (sym : String) (errorMsg : String) : ParserFn := fun c s => let initStackSz := s.stackSize let startPos := s.pos let s := tokenFn [errorMsg] c s if s.hasError then s else match s.stxStack.back with | Syntax.atom _ sym' => if sym == sym' then s else s.mkErrorAt errorMsg startPos initStackSz | Syntax.ident info rawVal _ _ => if sym == rawVal.toString then let s := s.popSyntax s.pushSyntax (Syntax.atom info sym) else s.mkErrorAt errorMsg startPos initStackSz | _ => s.mkErrorAt errorMsg startPos initStackSz @[inline] def nonReservedSymbolFn (sym : String) : ParserFn := nonReservedSymbolFnAux sym ("'" ++ sym ++ "'") def nonReservedSymbolInfo (sym : String) (includeIdent : Bool) : ParserInfo := { firstTokens := if includeIdent then FirstTokens.tokens [ sym, "ident" ] else FirstTokens.tokens [ sym ] } @[inline] def nonReservedSymbolNoAntiquot (sym : String) (includeIdent := false) : Parser := let sym := sym.trim { info := nonReservedSymbolInfo sym includeIdent, fn := nonReservedSymbolFn sym } partial def strAux (sym : String) (errorMsg : String) (j : Nat) :ParserFn := let rec parse (j c s) := if sym.atEnd j then s else let i := s.pos let input := c.input if input.atEnd i || sym.get j != input.get i then s.mkError errorMsg else parse (sym.next j) c (s.next input i) parse j def checkTailWs (prev : Syntax) : Bool := match prev.getTailInfo with | SourceInfo.original _ _ trailing => trailing.stopPos > trailing.startPos | _ => false def checkWsBeforeFn (errorMsg : String) : ParserFn := fun c s => let prev := s.stxStack.back if checkTailWs prev then s else s.mkError errorMsg def checkWsBefore (errorMsg : String := "space before") : Parser := { info := epsilonInfo, fn := checkWsBeforeFn errorMsg } def checkTailLinebreak (prev : Syntax) : Bool := match prev.getTailInfo with | SourceInfo.original _ _ trailing => trailing.contains '\n' | _ => false def checkLinebreakBeforeFn (errorMsg : String) : ParserFn := fun c s => let prev := s.stxStack.back if checkTailLinebreak prev then s else s.mkError errorMsg def checkLinebreakBefore (errorMsg : String := "line break") : Parser := { info := epsilonInfo fn := checkLinebreakBeforeFn errorMsg } private def pickNonNone (stack : Array Syntax) : Syntax := match stack.findRev? $ fun stx => !stx.isNone with | none => Syntax.missing | some stx => stx def checkNoWsBeforeFn (errorMsg : String) : ParserFn := fun c s => let prev := pickNonNone s.stxStack if checkTailNoWs prev then s else s.mkError errorMsg def checkNoWsBefore (errorMsg : String := "no space before") : Parser := { info := epsilonInfo, fn := checkNoWsBeforeFn errorMsg } def unicodeSymbolFnAux (sym asciiSym : String) (expected : List String) : ParserFn := satisfySymbolFn (fun s => s == sym || s == asciiSym) expected def unicodeSymbolInfo (sym asciiSym : String) : ParserInfo := { collectTokens := fun tks => sym :: asciiSym :: tks, firstTokens := FirstTokens.tokens [ sym, asciiSym ] } @[inline] def unicodeSymbolFn (sym asciiSym : String) : ParserFn := unicodeSymbolFnAux sym asciiSym ["'" ++ sym ++ "', '" ++ asciiSym ++ "'"] @[inline] def unicodeSymbolNoAntiquot (sym asciiSym : String) : Parser := let sym := sym.trim let asciiSym := asciiSym.trim { info := unicodeSymbolInfo sym asciiSym, fn := unicodeSymbolFn sym asciiSym } def mkAtomicInfo (k : String) : ParserInfo := { firstTokens := FirstTokens.tokens [ k ] } def numLitFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["numeral"] c s if !s.hasError && !(s.stxStack.back.isOfKind numLitKind) then s.mkErrorAt "numeral" iniPos initStackSz else s @[inline] def numLitNoAntiquot : Parser := { fn := numLitFn, info := mkAtomicInfo "numLit" } def scientificLitFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["scientific number"] c s if !s.hasError && !(s.stxStack.back.isOfKind scientificLitKind) then s.mkErrorAt "scientific number" iniPos initStackSz else s @[inline] def scientificLitNoAntiquot : Parser := { fn := scientificLitFn, info := mkAtomicInfo "scientificLit" } def strLitFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["string literal"] c s if !s.hasError && !(s.stxStack.back.isOfKind strLitKind) then s.mkErrorAt "string literal" iniPos initStackSz else s @[inline] def strLitNoAntiquot : Parser := { fn := strLitFn, info := mkAtomicInfo "strLit" } def charLitFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["char literal"] c s if !s.hasError && !(s.stxStack.back.isOfKind charLitKind) then s.mkErrorAt "character literal" iniPos initStackSz else s @[inline] def charLitNoAntiquot : Parser := { fn := charLitFn, info := mkAtomicInfo "charLit" } def nameLitFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["Name literal"] c s if !s.hasError && !(s.stxStack.back.isOfKind nameLitKind) then s.mkErrorAt "Name literal" iniPos initStackSz else s @[inline] def nameLitNoAntiquot : Parser := { fn := nameLitFn, info := mkAtomicInfo "nameLit" } def identFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["identifier"] c s if !s.hasError && !(s.stxStack.back.isIdent) then s.mkErrorAt "identifier" iniPos initStackSz else s @[inline] def identNoAntiquot : Parser := { fn := identFn, info := mkAtomicInfo "ident" } @[inline] def rawIdentNoAntiquot : Parser := { fn := rawIdentFn } def identEqFn (id : Name) : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["identifier"] c s if s.hasError then s else match s.stxStack.back with | Syntax.ident _ _ val _ => if val != id then s.mkErrorAt ("expected identifier '" ++ toString id ++ "'") iniPos initStackSz else s | _ => s.mkErrorAt "identifier" iniPos initStackSz @[inline] def identEq (id : Name) : Parser := { fn := identEqFn id, info := mkAtomicInfo "ident" } namespace ParserState def keepTop (s : Array Syntax) (startStackSize : Nat) : Array Syntax := let node := s.back s.shrink startStackSize |>.push node def keepNewError (s : ParserState) (oldStackSize : Nat) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, err⟩ => ⟨keepTop stack oldStackSize, lhsPrec, pos, cache, err⟩ def keepPrevError (s : ParserState) (oldStackSize : Nat) (oldStopPos : String.Pos) (oldError : Option Error) : ParserState := match s with | ⟨stack, lhsPrec, _, cache, _⟩ => ⟨stack.shrink oldStackSize, lhsPrec, oldStopPos, cache, oldError⟩ def mergeErrors (s : ParserState) (oldStackSize : Nat) (oldError : Error) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, some err⟩ => if oldError == err then s else ⟨stack.shrink oldStackSize, lhsPrec, pos, cache, some (oldError.merge err)⟩ | other => other def keepLatest (s : ParserState) (startStackSize : Nat) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, _⟩ => ⟨keepTop stack startStackSize, lhsPrec, pos, cache, none⟩ def replaceLongest (s : ParserState) (startStackSize : Nat) : ParserState := s.keepLatest startStackSize end ParserState def invalidLongestMatchParser (s : ParserState) : ParserState := s.mkError "longestMatch parsers must generate exactly one Syntax node" /-- Auxiliary function used to execute parsers provided to `longestMatchFn`. Push `left?` into the stack if it is not `none`, and execute `p`. Remark: `p` must produce exactly one syntax node. Remark: the `left?` is not none when we are processing trailing parsers. -/ def runLongestMatchParser (left? : Option Syntax) (startLhsPrec : Nat) (p : ParserFn) : ParserFn := fun c s => do /- We assume any registered parser `p` has one of two forms: * a direct call to `leadingParser` or `trailingParser` * a direct call to a (leading) token parser In the first case, we can extract the precedence of the parser by having `leadingParser/trailingParser` set `ParserState.lhsPrec` to it in the very end so that no nested parser can interfere. In the second case, the precedence is effectively `max` (there is a `checkPrec` merely for the convenience of the pretty printer) and there are no nested `leadingParser/trailingParser` calls, so the value of `lhsPrec` will not be changed by the parser (nor will it be read by any leading parser). Thus we initialize the field to `maxPrec` in the leading case. -/ let mut s := { s with lhsPrec := if left?.isSome then startLhsPrec else maxPrec } let startSize := s.stackSize if let some left := left? then s := s.pushSyntax left s := p c s -- stack contains `[..., result ]` if s.stackSize == startSize + 1 then s -- success or error with the expected number of nodes else if s.hasError then -- error with an unexpected number of nodes. s.shrinkStack startSize |>.pushSyntax Syntax.missing else -- parser succeded with incorrect number of nodes invalidLongestMatchParser s def longestMatchStep (left? : Option Syntax) (startSize startLhsPrec : Nat) (startPos : String.Pos) (prevPrio : Nat) (prio : Nat) (p : ParserFn) : ParserContext → ParserState → ParserState × Nat := fun c s => let prevErrorMsg := s.errorMsg let prevStopPos := s.pos let prevSize := s.stackSize let prevLhsPrec := s.lhsPrec let s := s.restore prevSize startPos let s := runLongestMatchParser left? startLhsPrec p c s match prevErrorMsg, s.errorMsg with | none, none => -- both succeeded if s.pos > prevStopPos || (s.pos == prevStopPos && prio > prevPrio) then (s.replaceLongest startSize, prio) else if s.pos < prevStopPos || (s.pos == prevStopPos && prio < prevPrio) then ({ s.restore prevSize prevStopPos with lhsPrec := prevLhsPrec }, prevPrio) -- keep prev -- it is not clear what the precedence of a choice node should be, so we conservatively take the minimum else ({s with lhsPrec := s.lhsPrec.min prevLhsPrec }, prio) | none, some _ => -- prev succeeded, current failed ({ s.restore prevSize prevStopPos with lhsPrec := prevLhsPrec }, prevPrio) | some oldError, some _ => -- both failed if s.pos > prevStopPos || (s.pos == prevStopPos && prio > prevPrio) then (s.keepNewError startSize, prio) else if s.pos < prevStopPos || (s.pos == prevStopPos && prio < prevPrio) then (s.keepPrevError prevSize prevStopPos prevErrorMsg, prevPrio) else (s.mergeErrors prevSize oldError, prio) | some _, none => -- prev failed, current succeeded let successNode := s.stxStack.back let s := s.shrinkStack startSize -- restore stack to initial size to make sure (failure) nodes are removed from the stack (s.pushSyntax successNode, prio) -- put successNode back on the stack def longestMatchMkResult (startSize : Nat) (s : ParserState) : ParserState := if !s.hasError && s.stackSize > startSize + 1 then s.mkNode choiceKind startSize else s def longestMatchFnAux (left? : Option Syntax) (startSize startLhsPrec : Nat) (startPos : String.Pos) (prevPrio : Nat) (ps : List (Parser × Nat)) : ParserFn := let rec parse (prevPrio : Nat) (ps : List (Parser × Nat)) := match ps with | [] => fun _ s => longestMatchMkResult startSize s | p::ps => fun c s => let (s, prevPrio) := longestMatchStep left? startSize startLhsPrec startPos prevPrio p.2 p.1.fn c s parse prevPrio ps c s parse prevPrio ps def longestMatchFn (left? : Option Syntax) : List (Parser × Nat) → ParserFn | [] => fun _ s => s.mkError "longestMatch: empty list" | [p] => fun c s => runLongestMatchParser left? s.lhsPrec p.1.fn c s | p::ps => fun c s => let startSize := s.stackSize let startLhsPrec := s.lhsPrec let startPos := s.pos let s := runLongestMatchParser left? s.lhsPrec p.1.fn c s longestMatchFnAux left? startSize startLhsPrec startPos p.2 ps c s def anyOfFn : List Parser → ParserFn | [], _, s => s.mkError "anyOf: empty list" | [p], c, s => p.fn c s | p::ps, c, s => orelseFn p.fn (anyOfFn ps) c s @[inline] def checkColGeFn (errorMsg : String) : ParserFn := fun c s => match c.savedPos? with | none => s | some savedPos => let savedPos := c.fileMap.toPosition savedPos let pos := c.fileMap.toPosition s.pos if pos.column ≥ savedPos.column then s else s.mkError errorMsg @[inline] def checkColGe (errorMsg : String := "checkColGe") : Parser := { fn := checkColGeFn errorMsg } @[inline] def checkColGtFn (errorMsg : String) : ParserFn := fun c s => match c.savedPos? with | none => s | some savedPos => let savedPos := c.fileMap.toPosition savedPos let pos := c.fileMap.toPosition s.pos if pos.column > savedPos.column then s else s.mkError errorMsg @[inline] def checkColGt (errorMsg : String := "checkColGt") : Parser := { fn := checkColGtFn errorMsg } @[inline] def checkLineEqFn (errorMsg : String) : ParserFn := fun c s => match c.savedPos? with | none => s | some savedPos => let savedPos := c.fileMap.toPosition savedPos let pos := c.fileMap.toPosition s.pos if pos.line == savedPos.line then s else s.mkError errorMsg @[inline] def checkLineEq (errorMsg : String := "checkLineEq") : Parser := { fn := checkLineEqFn errorMsg } @[inline] def withPosition (p : Parser) : Parser := { info := p.info, fn := fun c s => p.fn { c with savedPos? := s.pos } s } @[inline] def withoutPosition (p : Parser) : Parser := { info := p.info, fn := fun c s => let pos := c.fileMap.toPosition s.pos p.fn { c with savedPos? := none } s } @[inline] def withForbidden (tk : Token) (p : Parser) : Parser := { info := p.info, fn := fun c s => p.fn { c with forbiddenTk? := tk } s } @[inline] def withoutForbidden (p : Parser) : Parser := { info := p.info, fn := fun c s => p.fn { c with forbiddenTk? := none } s } def eoiFn : ParserFn := fun c s => let i := s.pos if c.input.atEnd i then s else s.mkError "expected end of file" @[inline] def eoi : Parser := { fn := eoiFn } open Std (RBMap RBMap.empty) /-- A multimap indexed by tokens. Used for indexing parsers by their leading token. -/ def TokenMap (α : Type) := RBMap Name (List α) Name.quickCmp namespace TokenMap def insert (map : TokenMap α) (k : Name) (v : α) : TokenMap α := match map.find? k with | none => Std.RBMap.insert map k [v] | some vs => Std.RBMap.insert map k (v::vs) instance : Inhabited (TokenMap α) := ⟨RBMap.empty⟩ instance : EmptyCollection (TokenMap α) := ⟨RBMap.empty⟩ end TokenMap structure PrattParsingTables where leadingTable : TokenMap (Parser × Nat) := {} leadingParsers : List (Parser × Nat) := [] -- for supporting parsers we cannot obtain first token trailingTable : TokenMap (Parser × Nat) := {} trailingParsers : List (Parser × Nat) := [] -- for supporting parsers such as function application instance : Inhabited PrattParsingTables := ⟨{}⟩ /- The type `leadingIdentBehavior` specifies how the parsing table lookup function behaves for identifiers. The function `prattParser` uses two tables `leadingTable` and `trailingTable`. They map tokens to parsers. - `LeadingIdentBehavior.default`: if the leading token is an identifier, then `prattParser` just executes the parsers associated with the auxiliary token "ident". - `LeadingIdentBehavior.symbol`: if the leading token is an identifier `<foo>`, and there are parsers `P` associated with the toek `<foo>`, then it executes `P`. Otherwise, it executes only the parsers associated with the auxiliary token "ident". - `LeadingIdentBehavior.both`: if the leading token an identifier `<foo>`, the it executes the parsers associated with token `<foo>` and parsers associated with the auxiliary token "ident". We use `LeadingIdentBehavior.symbol` and `LeadingIdentBehavior.both` and `nonReservedSymbol` parser to implement the `tactic` parsers. The idea is to avoid creating a reserved symbol for each builtin tactic (e.g., `apply`, `assumption`, etc.). That is, users may still use these symbols as identifiers (e.g., naming a function). -/ inductive LeadingIdentBehavior where | default | symbol | both deriving Inhabited, BEq /-- Each parser category is implemented using a Pratt's parser. The system comes equipped with the following categories: `level`, `term`, `tactic`, and `command`. Users and plugins may define extra categories. The method ``` categoryParser `term prec ``` executes the Pratt's parser for category `term` with precedence `prec`. That is, only parsers with precedence at least `prec` are considered. The method `termParser prec` is equivalent to the method above. -/ structure ParserCategory where tables : PrattParsingTables behavior : LeadingIdentBehavior deriving Inhabited abbrev ParserCategories := Std.PersistentHashMap Name ParserCategory def indexed {α : Type} (map : TokenMap α) (c : ParserContext) (s : ParserState) (behavior : LeadingIdentBehavior) : ParserState × List α := let (s, stx) := peekToken c s let find (n : Name) : ParserState × List α := match map.find? n with | some as => (s, as) | _ => (s, []) match stx with | Except.ok (Syntax.atom _ sym) => find (Name.mkSimple sym) | Except.ok (Syntax.ident _ _ val _) => match behavior with | LeadingIdentBehavior.default => find identKind | LeadingIdentBehavior.symbol => match map.find? val with | some as => (s, as) | none => find identKind | LeadingIdentBehavior.both => match map.find? val with | some as => match map.find? identKind with | some as' => (s, as ++ as') | _ => (s, as) | none => find identKind | Except.ok (Syntax.node k _) => find k | Except.ok _ => (s, []) | Except.error s' => (s', []) abbrev CategoryParserFn := Name → ParserFn builtin_initialize categoryParserFnRef : IO.Ref CategoryParserFn ← IO.mkRef fun _ => whitespace builtin_initialize categoryParserFnExtension : EnvExtension CategoryParserFn ← registerEnvExtension $ categoryParserFnRef.get def categoryParserFn (catName : Name) : ParserFn := fun ctx s => categoryParserFnExtension.getState ctx.env catName ctx s def categoryParser (catName : Name) (prec : Nat) : Parser := { fn := fun c s => categoryParserFn catName { c with prec := prec } s } -- Define `termParser` here because we need it for antiquotations @[inline] def termParser (prec : Nat := 0) : Parser := categoryParser `term prec /- ============== -/ /- Antiquotations -/ /- ============== -/ /-- Fail if previous token is immediately followed by ':'. -/ def checkNoImmediateColon : Parser := { fn := fun c s => let prev := s.stxStack.back if checkTailNoWs prev then let input := c.input let i := s.pos if input.atEnd i then s else let curr := input.get i if curr == ':' then s.mkUnexpectedError "unexpected ':'" else s else s } def setExpectedFn (expected : List String) (p : ParserFn) : ParserFn := fun c s => match p c s with | s'@{ errorMsg := some msg, .. } => { s' with errorMsg := some { msg with expected := [] } } | s' => s' def setExpected (expected : List String) (p : Parser) : Parser := { fn := setExpectedFn expected p.fn, info := p.info } def pushNone : Parser := { fn := fun c s => s.pushSyntax mkNullNode } -- We support two kinds of antiquotations: `$id` and `$(t)`, where `id` is a term identifier and `t` is a term. def antiquotNestedExpr : Parser := node `antiquotNestedExpr (symbolNoAntiquot "(" >> decQuotDepth termParser >> symbolNoAntiquot ")") def antiquotExpr : Parser := identNoAntiquot <|> antiquotNestedExpr @[inline] def tokenWithAntiquotFn (p : ParserFn) : ParserFn := fun c s => do let s := p c s if s.hasError || c.quotDepth == 0 then return s let iniSz := s.stackSize let iniPos := s.pos let s := (checkNoWsBefore >> symbolNoAntiquot "%" >> symbolNoAntiquot "$" >> checkNoWsBefore >> antiquotExpr).fn c s if s.hasError then return s.restore iniSz iniPos s.mkNode (`token_antiquot) (iniSz - 1) @[inline] def tokenWithAntiquot (p : Parser) : Parser where fn := tokenWithAntiquotFn p.fn info := p.info @[inline] def symbol (sym : String) : Parser := tokenWithAntiquot (symbolNoAntiquot sym) instance : Coe String Parser := ⟨fun s => symbol s ⟩ @[inline] def nonReservedSymbol (sym : String) (includeIdent := false) : Parser := tokenWithAntiquot (nonReservedSymbolNoAntiquot sym includeIdent) @[inline] def unicodeSymbol (sym asciiSym : String) : Parser := tokenWithAntiquot (unicodeSymbolNoAntiquot sym asciiSym) /-- Define parser for `$e` (if anonymous == true) and `$e:name`. Both forms can also be used with an appended `*` to turn them into an antiquotation "splice". If `kind` is given, it will additionally be checked when evaluating `match_syntax`. Antiquotations can be escaped as in `$$e`, which produces the syntax tree for `$e`. -/ def mkAntiquot (name : String) (kind : Option SyntaxNodeKind) (anonymous := true) : Parser := let kind := (kind.getD Name.anonymous) ++ `antiquot let nameP := node `antiquotName $ checkNoWsBefore ("no space before ':" ++ name ++ "'") >> symbol ":" >> nonReservedSymbol name -- if parsing the kind fails and `anonymous` is true, check that we're not ignoring a different -- antiquotation kind via `noImmediateColon` let nameP := if anonymous then nameP <|> checkNoImmediateColon >> pushNone else nameP -- antiquotations are not part of the "standard" syntax, so hide "expected '$'" on error leadingNode kind maxPrec $ atomic $ setExpected [] "$" >> manyNoAntiquot (checkNoWsBefore "" >> "$") >> checkNoWsBefore "no space before spliced term" >> antiquotExpr >> nameP def tryAnti (c : ParserContext) (s : ParserState) : Bool := do if c.quotDepth == 0 then return false let (s, stx) := peekToken c s match stx with | Except.ok stx@(Syntax.atom _ sym) => sym == "$" | _ => false @[inline] def withAntiquotFn (antiquotP p : ParserFn) : ParserFn := fun c s => if tryAnti c s then orelseFn antiquotP p c s else p c s /-- Optimized version of `mkAntiquot ... <|> p`. -/ @[inline] def withAntiquot (antiquotP p : Parser) : Parser := { fn := withAntiquotFn antiquotP.fn p.fn, info := orelseInfo antiquotP.info p.info } def withoutInfo (p : Parser) : Parser := { fn := p.fn } /-- Parse `$[p]suffix`, e.g. `$[p],*`. -/ def mkAntiquotSplice (kind : SyntaxNodeKind) (p suffix : Parser) : Parser := let kind := kind ++ `antiquot_scope leadingNode kind maxPrec $ atomic $ setExpected [] "$" >> manyNoAntiquot (checkNoWsBefore "" >> "$") >> checkNoWsBefore "no space before spliced term" >> symbol "[" >> node nullKind p >> symbol "]" >> suffix @[inline] def withAntiquotSuffixSpliceFn (kind : SyntaxNodeKind) (p suffix : ParserFn) : ParserFn := fun c s => do let s := p c s if s.hasError || c.quotDepth == 0 || !s.stxStack.back.isAntiquot then return s let iniSz := s.stackSize let iniPos := s.pos let s := suffix c s if s.hasError then return s.restore iniSz iniPos s.mkNode (kind ++ `antiquot_suffix_splice) (s.stxStack.size - 2) /-- Parse `suffix` after an antiquotation, e.g. `$x,*`, and put both into a new node. -/ @[inline] def withAntiquotSuffixSplice (kind : SyntaxNodeKind) (p suffix : Parser) : Parser := { info := andthenInfo p.info suffix.info, fn := withAntiquotSuffixSpliceFn kind p.fn suffix.fn } def withAntiquotSpliceAndSuffix (kind : SyntaxNodeKind) (p suffix : Parser) := -- prevent `p`'s info from being collected twice withAntiquot (mkAntiquotSplice kind (withoutInfo p) suffix) (withAntiquotSuffixSplice kind p suffix) def nodeWithAntiquot (name : String) (kind : SyntaxNodeKind) (p : Parser) (anonymous := false) : Parser := withAntiquot (mkAntiquot name kind anonymous) $ node kind p /- ===================== -/ /- End of Antiquotations -/ /- ===================== -/ def sepByElemParser (p : Parser) (sep : String) : Parser := withAntiquotSpliceAndSuffix `sepBy p (symbol (sep.trim ++ "*")) def sepBy (p : Parser) (sep : String) (psep : Parser := symbol sep) (allowTrailingSep : Bool := false) : Parser := sepByNoAntiquot (sepByElemParser p sep) psep allowTrailingSep def sepBy1 (p : Parser) (sep : String) (psep : Parser := symbol sep) (allowTrailingSep : Bool := false) : Parser := sepBy1NoAntiquot (sepByElemParser p sep) psep allowTrailingSep def categoryParserOfStackFn (offset : Nat) : ParserFn := fun ctx s => let stack := s.stxStack if stack.size < offset + 1 then s.mkUnexpectedError ("failed to determine parser category using syntax stack, stack is too small") else match stack.get! (stack.size - offset - 1) with | Syntax.ident _ _ catName _ => categoryParserFn catName ctx s | _ => s.mkUnexpectedError ("failed to determine parser category using syntax stack, the specified element on the stack is not an identifier") def categoryParserOfStack (offset : Nat) (prec : Nat := 0) : Parser := { fn := fun c s => categoryParserOfStackFn offset { c with prec := prec } s } unsafe def evalParserConstUnsafe (declName : Name) : ParserFn := fun ctx s => match ctx.env.evalConstCheck Parser ctx.options `Lean.Parser.Parser declName <|> ctx.env.evalConstCheck Parser ctx.options `Lean.Parser.TrailingParser declName with | Except.ok p => p.fn ctx s | Except.error e => s.mkUnexpectedError s!"error running parser {declName}: {e}" @[implementedBy evalParserConstUnsafe] constant evalParserConst (declName : Name) : ParserFn unsafe def parserOfStackFnUnsafe (offset : Nat) : ParserFn := fun ctx s => let stack := s.stxStack if stack.size < offset + 1 then s.mkUnexpectedError ("failed to determine parser using syntax stack, stack is too small") else match stack.get! (stack.size - offset - 1) with | Syntax.ident (val := parserName) .. => match ctx.resolveName parserName with | [(parserName, [])] => let iniSz := s.stackSize let s := evalParserConst parserName ctx s if !s.hasError && s.stackSize != iniSz + 1 then s.mkUnexpectedError "expected parser to return exactly one syntax object" else s | _::_::_ => s.mkUnexpectedError s!"ambiguous parser name {parserName}" | _ => s.mkUnexpectedError s!"unknown parser {parserName}" | _ => s.mkUnexpectedError ("failed to determine parser using syntax stack, the specified element on the stack is not an identifier") @[implementedBy parserOfStackFnUnsafe] constant parserOfStackFn (offset : Nat) : ParserFn def parserOfStack (offset : Nat) (prec : Nat := 0) : Parser := { fn := fun c s => parserOfStackFn offset { c with prec := prec } s } /-- Run `declName` if possible and inside a quotation, or else `p`. The `ParserInfo` will always be taken from `p`. -/ def evalInsideQuot (declName : Name) (p : Parser) : Parser := { p with fn := fun c s => if c.quotDepth > 0 && !c.suppressInsideQuot && c.env.contains declName then evalParserConst declName c s else p.fn c s } private def mkResult (s : ParserState) (iniSz : Nat) : ParserState := if s.stackSize == iniSz + 1 then s else s.mkNode nullKind iniSz -- throw error instead? def leadingParserAux (kind : Name) (tables : PrattParsingTables) (behavior : LeadingIdentBehavior) : ParserFn := fun c s => do let iniSz := s.stackSize let (s, ps) := indexed tables.leadingTable c s behavior if s.hasError then return s let ps := tables.leadingParsers ++ ps if ps.isEmpty then return s.mkError (toString kind) let s := longestMatchFn none ps c s mkResult s iniSz @[inline] def leadingParser (kind : Name) (tables : PrattParsingTables) (behavior : LeadingIdentBehavior) (antiquotParser : ParserFn) : ParserFn := withAntiquotFn antiquotParser (leadingParserAux kind tables behavior) def trailingLoopStep (tables : PrattParsingTables) (left : Syntax) (ps : List (Parser × Nat)) : ParserFn := fun c s => longestMatchFn left (ps ++ tables.trailingParsers) c s partial def trailingLoop (tables : PrattParsingTables) (c : ParserContext) (s : ParserState) : ParserState := do let iniSz := s.stackSize let iniPos := s.pos let (s, ps) := indexed tables.trailingTable c s LeadingIdentBehavior.default if s.hasError then -- Discard token parse errors and break the trailing loop instead. -- The error will be flagged when the next leading position is parsed, unless the token -- is in fact valid there (e.g. EOI at command level, no-longer forbidden token) return s.restore iniSz iniPos if ps.isEmpty && tables.trailingParsers.isEmpty then return s -- no available trailing parser let left := s.stxStack.back let s := s.popSyntax let s := trailingLoopStep tables left ps c s if s.hasError then -- Discard non-consuming parse errors and break the trailing loop instead, restoring `left`. -- This is necessary for fallback parsers like `app` that pretend to be always applicable. return if s.pos == iniPos then s.restore (iniSz - 1) iniPos |>.pushSyntax left else s trailingLoop tables c s /-- Implements a variant of Pratt's algorithm. In Pratt's algorithms tokens have a right and left binding power. In our implementation, parsers have precedence instead. This method selects a parser (or more, via `longestMatchFn`) from `leadingTable` based on the current token. Note that the unindexed `leadingParsers` parsers are also tried. We have the unidexed `leadingParsers` because some parsers do not have a "first token". Example: ``` syntax term:51 "≤" ident "<" term "|" term : index ``` Example, in principle, the set of first tokens for this parser is any token that can start a term, but this set is always changing. Thus, this parsing rule is stored as an unindexed leading parser at `leadingParsers`. After processing the leading parser, we chain with parsers from `trailingTable`/`trailingParsers` that have precedence at least `c.prec` where `c` is the `ParsingContext`. Recall that `c.prec` is set by `categoryParser`. Note that in the original Pratt's algorith, precedences are only checked before calling trailing parsers. In our implementation, leading *and* trailing parsers check the precendece. We claim our algorithm is more flexible, modular and easier to understand. `antiquotParser` should be a `mkAntiquot` parser (or always fail) and is tried before all other parsers. It should not be added to the regular leading parsers because it would heavily overlap with antiquotation parsers nested inside them. -/ @[inline] def prattParser (kind : Name) (tables : PrattParsingTables) (behavior : LeadingIdentBehavior) (antiquotParser : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos let s := leadingParser kind tables behavior antiquotParser c s if s.hasError then s else trailingLoop tables c s def fieldIdxFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let curr := c.input.get iniPos if curr.isDigit && curr != '0' then let s := takeWhileFn (fun c => c.isDigit) c s mkNodeToken fieldIdxKind iniPos c s else s.mkErrorAt "field index" iniPos initStackSz @[inline] def fieldIdx : Parser := withAntiquot (mkAntiquot "fieldIdx" `fieldIdx) { fn := fieldIdxFn, info := mkAtomicInfo "fieldIdx" } @[inline] def skip : Parser := { fn := fun c s => s, info := epsilonInfo } end Parser namespace Syntax section variable {β : Type} {m : Type → Type} [Monad m] @[inline] def foldArgsM (s : Syntax) (f : Syntax → β → m β) (b : β) : m β := s.getArgs.foldlM (flip f) b @[inline] def foldArgs (s : Syntax) (f : Syntax → β → β) (b : β) : β := Id.run (s.foldArgsM f b) @[inline] def forArgsM (s : Syntax) (f : Syntax → m Unit) : m Unit := s.foldArgsM (fun s _ => f s) () end end Syntax end Lean
9984b576819866c40c884a56fd2162901a1d1a48
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/algebra/lie/base_change.lean
2f4ae5df7b53d02ab1d6b8aa00f5328582a25c91
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
5,871
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.algebra.restrict_scalars import algebra.lie.tensor_product /-! # Extension and restriction of scalars for Lie algebras Lie algebras have a well-behaved theory of extension and restriction of scalars. ## Main definitions * `lie_algebra.extend_scalars.lie_algebra` * `lie_algebra.restrict_scalars.lie_algebra` ## Tags lie ring, lie algebra, extension of scalars, restriction of scalars, base change -/ universes u v w w₁ w₂ w₃ open_locale tensor_product variables (R : Type u) (A : Type w) (L : Type v) namespace lie_algebra namespace extend_scalars variables [comm_ring R] [comm_ring A] [algebra R A] [lie_ring L] [lie_algebra R L] /-- The Lie bracket on the extension of a Lie algebra `L` over `R` by an algebra `A` over `R`. In fact this bracket is fully `A`-bilinear but without a significant upgrade to our mixed-scalar support in the tensor product library, it is far easier to bootstrap like this, starting with the definition below. -/ private def bracket' : (A ⊗[R] L) →ₗ[R] (A ⊗[R] L) →ₗ[R] A ⊗[R] L := tensor_product.curry $ (tensor_product.map (algebra.lmul' R) (lie_module.to_module_hom R L L : L ⊗[R] L →ₗ[R] L)) ∘ₗ ↑(tensor_product.tensor_tensor_tensor_comm R A L A L) @[simp] private lemma bracket'_tmul (s t : A) (x y : L) : bracket' R A L (s ⊗ₜ[R] x) (t ⊗ₜ[R] y) = (s*t) ⊗ₜ ⁅x, y⁆ := by simp [bracket'] instance : has_bracket (A ⊗[R] L) (A ⊗[R] L) := { bracket := λ x y, bracket' R A L x y, } private lemma bracket_def (x y : A ⊗[R] L) : ⁅x, y⁆ = bracket' R A L x y := rfl @[simp] lemma bracket_tmul (s t : A) (x y : L) : ⁅s ⊗ₜ[R] x, t ⊗ₜ[R] y⁆ = (s*t) ⊗ₜ ⁅x, y⁆ := by rw [bracket_def, bracket'_tmul] private lemma bracket_lie_self (x : A ⊗[R] L) : ⁅x, x⁆ = 0 := begin simp only [bracket_def], apply x.induction_on, { simp only [linear_map.map_zero, eq_self_iff_true, linear_map.zero_apply], }, { intros a l, simp only [bracket'_tmul, tensor_product.tmul_zero, eq_self_iff_true, lie_self], }, { intros z₁ z₂ h₁ h₂, suffices : bracket' R A L z₁ z₂ + bracket' R A L z₂ z₁ = 0, { rw [linear_map.map_add, linear_map.map_add, linear_map.add_apply, linear_map.add_apply, h₁, h₂, zero_add, add_zero, add_comm, this], }, apply z₁.induction_on, { simp only [linear_map.map_zero, add_zero, linear_map.zero_apply], }, { intros a₁ l₁, apply z₂.induction_on, { simp only [linear_map.map_zero, add_zero, linear_map.zero_apply], }, { intros a₂ l₂, simp only [← lie_skew l₂ l₁, mul_comm a₁ a₂, tensor_product.tmul_neg, bracket'_tmul, add_right_neg], }, { intros y₁ y₂ hy₁ hy₂, simp only [hy₁, hy₂, add_add_add_comm, add_zero, linear_map.add_apply, linear_map.map_add], }, }, { intros y₁ y₂ hy₁ hy₂, simp only [add_add_add_comm, hy₁, hy₂, add_zero, linear_map.add_apply, linear_map.map_add], }, }, end private lemma bracket_leibniz_lie (x y z : A ⊗[R] L) : ⁅x, ⁅y, z⁆⁆ = ⁅⁅x, y⁆, z⁆ + ⁅y, ⁅x, z⁆⁆ := begin simp only [bracket_def], apply x.induction_on, { simp only [linear_map.map_zero, add_zero, eq_self_iff_true, linear_map.zero_apply], }, { intros a₁ l₁, apply y.induction_on, { simp only [linear_map.map_zero, add_zero, eq_self_iff_true, linear_map.zero_apply], }, { intros a₂ l₂, apply z.induction_on, { simp only [linear_map.map_zero, add_zero], }, { intros a₃ l₃, simp only [bracket'_tmul], rw [mul_left_comm a₂ a₁ a₃, mul_assoc, leibniz_lie, tensor_product.tmul_add], }, { intros u₁ u₂ h₁ h₂, simp only [add_add_add_comm, h₁, h₂, linear_map.map_add], }, }, { intros u₁ u₂ h₁ h₂, simp only [add_add_add_comm, h₁, h₂, linear_map.add_apply, linear_map.map_add], }, }, { intros u₁ u₂ h₁ h₂, simp only [add_add_add_comm, h₁, h₂, linear_map.add_apply, linear_map.map_add], }, end instance : lie_ring (A ⊗[R] L) := { add_lie := λ x y z, by simp only [bracket_def, linear_map.add_apply, linear_map.map_add], lie_add := λ x y z, by simp only [bracket_def, linear_map.map_add], lie_self := bracket_lie_self R A L, leibniz_lie := bracket_leibniz_lie R A L, } private lemma bracket_lie_smul (a : A) (x y : A ⊗[R] L) : ⁅x, a • y⁆ = a • ⁅x, y⁆ := begin apply x.induction_on, { simp only [zero_lie, smul_zero], }, { intros a₁ l₁, apply y.induction_on, { simp only [lie_zero, smul_zero], }, { intros a₂ l₂, simp only [bracket_def, bracket', tensor_product.smul_tmul', mul_left_comm a₁ a a₂, tensor_product.curry_apply, algebra.lmul'_apply, algebra.id.smul_eq_mul, function.comp_app, linear_equiv.coe_coe, linear_map.coe_comp, tensor_product.map_tmul, tensor_product.tensor_tensor_tensor_comm_tmul], }, { intros z₁ z₂ h₁ h₂, simp only [h₁, h₂, smul_add, lie_add], }, }, { intros z₁ z₂ h₁ h₂, simp only [h₁, h₂, smul_add, add_lie], }, end instance lie_algebra : lie_algebra A (A ⊗[R] L) := { lie_smul := bracket_lie_smul R A L, } end extend_scalars namespace restrict_scalars open restrict_scalars variables [h : lie_ring L] include h instance : lie_ring (restrict_scalars R A L) := h variables [comm_ring A] [lie_algebra A L] @[nolint unused_arguments] instance lie_algebra [comm_ring R] [algebra R A] : lie_algebra R (restrict_scalars R A L) := { lie_smul := λ t x y, (lie_smul _ (show L, from x) (show L, from y) : _), .. (by apply_instance : module R (restrict_scalars R A L)), } end restrict_scalars end lie_algebra
4ad3ab301cbec43031df02cc5ab3980864d548b9
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/tactic/interval_cases.lean
53585b0acaecea79093b8575a5db9092c97305da
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
10,943
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Scott Morrison Case bashing on variables in finite intervals. In particular, `interval_cases n` 1) inspects hypotheses looking for lower and upper bounds of the form `a ≤ n` and `n < b` (although in `ℕ`, `ℤ`, and `ℕ+` bounds of the form `a < n` and `n ≤ b` are also allowed), and also makes use of lower and upper bounds found via `le_top` and `bot_le` (so for example if `n : ℕ`, then the bound `0 ≤ n` is found automatically), then 2) calls `fin_cases` on the synthesised hypothesis `n ∈ set.Ico a b`, assuming an appropriate `fintype` instance can be found for the type of `n`. The variable `n` can belong to any type `α`, with the following restrictions: * only bounds on which `expr.to_rat` succeeds will be considered "explicit" (TODO: generalise this?) * an instance of `decidable_eq α` is available, * an explicit lower bound can be found amongst the hypotheses, or from `bot_le n`, * an explicit upper bound can be found amongst the hypotheses, or from `le_top n`, * if multiple bounds are located, an instance of `decidable_linear_order α` is available, and * an instance of `fintype set.Ico l u` is available for the relevant bounds. You can also explicitly specify a lower and upper bound to use, as `interval_cases using hl hu`. The hypotheses should be in the form `hl : a ≤ n` and `hu : n < b`, in which case `interval_cases` calls `fin_cases` on the resulting fact `n ∈ set.Ico a b`. -/ import tactic.fin_cases import data.fintype.intervals open set namespace tactic namespace interval_cases /-- If `e` easily implies `(%%n < %%b)` for some explicit `b`, return that proof. -/ -- We use `expr.to_rat` merely to decide if an `expr` is an explicit number. -- It would be more natural to use `expr.to_int`, but that hasn't been implemented. meta def gives_upper_bound (n e : expr) : tactic expr := do t ← infer_type e, match t with | `(%%n' < %%b) := do guard (n = n'), b ← b.to_rat, return e | `(%%b > %%n') := do guard (n = n'), b ← b.to_rat, return e | `(%%n' ≤ %%b) := do guard (n = n'), b ← b.to_rat, tn ← infer_type n, match tn with | `(ℕ) := to_expr ``(nat.lt_add_one_iff.mpr %%e) | `(ℕ+) := to_expr ``(pnat.lt_add_one_iff.mpr %%e) | `(ℤ) := to_expr ``(int.lt_add_one_iff.mpr %%e) | _ := failed end | `(%%b ≥ %%n') := do guard (n = n'), b ← b.to_rat, tn ← infer_type n, match tn with | `(ℕ) := to_expr ``(nat.lt_add_one_iff.mpr %%e) | `(ℕ+) := to_expr ``(pnat.lt_add_one_iff.mpr %%e) | `(ℤ) := to_expr ``(int.lt_add_one_iff.mpr %%e) | _ := failed end | _ := failed end /-- If `e` easily implies `(%%n ≥ %%b)` for some explicit `b`, return that proof. -/ meta def gives_lower_bound (n e : expr) : tactic expr := do t ← infer_type e, match t with | `(%%n' ≥ %%b) := do guard (n = n'), b ← b.to_rat, return e | `(%%b ≤ %%n') := do guard (n = n'), b ← b.to_rat, return e | `(%%n' > %%b) := do guard (n = n'), b ← b.to_rat, tn ← infer_type n, match tn with | `(ℕ) := to_expr ``(nat.add_one_le_iff.mpr %%e) | `(ℕ+) := to_expr ``(pnat.add_one_le_iff.mpr %%e) | `(ℤ) := to_expr ``(int.add_one_le_iff.mpr %%e) | _ := failed end | `(%%b < %%n') := do guard (n = n'), b ← b.to_rat, tn ← infer_type n, match tn with | `(ℕ) := to_expr ``(nat.add_one_le_iff.mpr %%e) | `(ℕ+) := to_expr ``(pnat.add_one_le_iff.mpr %%e) | `(ℤ) := to_expr ``(int.add_one_le_iff.mpr %%e) | _ := failed end | _ := failed end /-- Combine two upper bounds. -/ meta def combine_upper_bounds : option expr → option expr → tactic (option expr) | none none := return none | (some prf) none := return $ some prf | none (some prf) := return $ some prf | (some prf₁) (some prf₂) := do option.some <$> to_expr ``(lt_min %%prf₁ %%prf₂) /-- Combine two lower bounds. -/ meta def combine_lower_bounds : option expr → option expr → tactic (option expr) | none none := return $ none | (some prf) none := return $ some prf | none (some prf) := return $ some prf | (some prf₁) (some prf₂) := do option.some <$> to_expr ``(max_le %%prf₂ %%prf₁) /-- Inspect a given expression, using it to update a set of upper and lower bounds on `n`. -/ meta def update_bounds (n : expr) (bounds : option expr × option expr) (e : expr) : tactic (option expr × option expr) := do nlb ← try_core $ gives_lower_bound n e, nub ← try_core $ gives_upper_bound n e, clb ← combine_lower_bounds bounds.1 nlb, cub ← combine_upper_bounds bounds.2 nub, return (clb, cub) /-- Attempt to find a lower bound for the variable `n`, by evaluating `bot_le n`. -/ meta def initial_lower_bound (n : expr) : tactic expr := do e ← to_expr ``(@bot_le _ _ %%n), t ← infer_type e, match t with | `(%%b ≤ %%n) := do return e | _ := failed end /-- Attempt to find an upper bound for the variable `n`, by evaluating `le_top n`. -/ meta def initial_upper_bound (n : expr) : tactic expr := do e ← to_expr ``(@le_top _ _ %%n), match e with | `(%%n ≤ %%b) := do tn ← infer_type n, e ← match tn with | `(ℕ) := to_expr ``(nat.add_one_le_iff.mpr %%e) | `(ℕ+) := to_expr ``(pnat.add_one_le_iff.mpr %%e) | `(ℤ) := to_expr ``(int.add_one_le_iff.mpr %%e) | _ := failed end, return e | _ := failed end /-- Inspect the local hypotheses for upper and lower bounds on a variable `n`. -/ meta def get_bounds (n : expr) : tactic (expr × expr) := do hl ← try_core (initial_lower_bound n), hu ← try_core (initial_upper_bound n), lc ← local_context, r ← lc.mfoldl (update_bounds n) (hl, hu), match r with | (_, none) := fail "No upper bound located." | (none, _) := fail "No lower bound located." | (some lb_prf, some ub_prf) := return (lb_prf, ub_prf) end /-- The finset of elements of a set `s` for which we have `fintype s`. -/ def set_elems {α} [decidable_eq α] (s : set α) [fintype s] : finset α := (fintype.elems s).image subtype.val /-- Each element of `s` is a member of `set_elems s`. -/ lemma mem_set_elems {α} [decidable_eq α] (s : set α) [fintype s] {a : α} (h : a ∈ s) : a ∈ set_elems s := finset.mem_image.2 ⟨⟨a, h⟩, fintype.complete _, rfl⟩ end interval_cases open interval_cases /-- Call `fin_cases` on membership of the finset built from an `Ico` interval corresponding to a lower and an upper bound. Here `hl` should be an expression of the form `a ≤ n`, for some explicit `a`, and `hu` should be of the form `n < b`, for some explicit `b`. By default `interval_cases_using` automatically generates a name for the new hypothesis. The name can be specified via the optional argument `n`. -/ meta def interval_cases_using (hl hu : expr) (n : option name) : tactic unit := to_expr ``(mem_set_elems (Ico _ _) ⟨%%hl, %%hu⟩) >>= (if hn : n.is_some then note (option.get hn) else note_anon none) >>= fin_cases_at none setup_tactic_parser namespace interactive local postfix `?`:9001 := optional /-- `interval_cases n` searches for upper and lower bounds on a variable `n`, and if bounds are found, splits into separate cases for each possible value of `n`. As an example, in ``` example (n : ℕ) (w₁ : n ≥ 3) (w₂ : n < 5) : n = 3 ∨ n = 4 := begin interval_cases n, all_goals {simp} end ``` after `interval_cases n`, the goals are `3 = 3 ∨ 3 = 4` and `4 = 3 ∨ 4 = 4`. You can also explicitly specify a lower and upper bound to use, as `interval_cases using hl hu`. The hypotheses should be in the form `hl : a ≤ n` and `hu : n < b`, in which case `interval_cases` calls `fin_cases` on the resulting fact `n ∈ set.Ico a b`. You can specify a name `h` for the new hypothesis, as `interval_cases n with h` or `interval_cases n using hl hu with h`. -/ meta def interval_cases (n : parse texpr?) (bounds : parse (tk "using" *> (prod.mk <$> ident <*> ident))?) (lname : parse (tk "with" *> ident)?) : tactic unit := do if h : n.is_some then (do guard bounds.is_none <|> fail "Do not use the `using` keyword if specifying the variable explicitly.", n ← to_expr (option.get h), (hl, hu) ← get_bounds n, tactic.interval_cases_using hl hu lname) else if h' : bounds.is_some then (do [hl, hu] ← [(option.get h').1, (option.get h').2].mmap get_local, tactic.interval_cases_using hl hu lname) else fail "Call `interval_cases n` (specifying a variable), or `interval_cases lb ub` (specifying a lower bound and upper bound on the same variable)." /-- `interval_cases n` searches for upper and lower bounds on a variable `n`, and if bounds are found, splits into separate cases for each possible value of `n`. As an example, in ``` example (n : ℕ) (w₁ : n ≥ 3) (w₂ : n < 5) : n = 3 ∨ n = 4 := begin interval_cases n, all_goals {simp} end ``` after `interval_cases n`, the goals are `3 = 3 ∨ 3 = 4` and `4 = 3 ∨ 4 = 4`. You can also explicitly specify a lower and upper bound to use, as `interval_cases using hl hu`. The hypotheses should be in the form `hl : a ≤ n` and `hu : n < b`, in which case `interval_cases` calls `fin_cases` on the resulting fact `n ∈ set.Ico a b`. You can also explicitly specify a name to use for the hypothesis added, as `interval_cases n with hn` or `interval_cases n using hl hu with hn`. In particular, `interval_cases n` 1) inspects hypotheses looking for lower and upper bounds of the form `a ≤ n` and `n < b` (although in `ℕ`, `ℤ`, and `ℕ+` bounds of the form `a < n` and `n ≤ b` are also allowed), and also makes use of lower and upper bounds found via `le_top` and `bot_le` (so for example if `n : ℕ`, then the bound `0 ≤ n` is found automatically), then 2) calls `fin_cases` on the synthesised hypothesis `n ∈ set.Ico a b`, assuming an appropriate `fintype` instance can be found for the type of `n`. The variable `n` can belong to any type `α`, with the following restrictions: * only bounds on which `expr.to_rat` succeeds will be considered "explicit" (TODO: generalise this?) * an instance of `decidable_eq α` is available, * an explicit lower bound can be found amongst the hypotheses, or from `bot_le n`, * an explicit upper bound can be found amongst the hypotheses, or from `le_top n`, * if multiple bounds are located, an instance of `decidable_linear_order α` is available, and * an instance of `fintype set.Ico l u` is available for the relevant bounds. -/ add_tactic_doc { name := "interval_cases", category := doc_category.tactic, decl_names := [`tactic.interactive.interval_cases], tags := ["case bashing"] } end interactive end tactic
267b19231992396ff2b58c43bdd2495c3fe5f668
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/list/func.lean
4cbef33c6264e4e27ab0a74b244e6ffa455f7d8c
[ "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
11,127
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Seul Baek -/ import data.nat.basic /-! # Lists as Functions Definitions for using lists as finite representations of finitely-supported functions with domain ℕ. These include pointwise operations on lists, as well as get and set operations. ## Notations An index notation is introduced in this file for setting a particular element of a list. With `as` as a list `m` as an index, and `a` as a new element, the notation is `as {m ↦ a}`. So, for example `[1, 3, 5] {1 ↦ 9}` would result in `[1, 9, 5]` This notation is in the locale `list.func`. -/ open list universes u v w variables {α : Type u} {β : Type v} {γ : Type w} namespace list namespace func variables {a : α} variables {as as1 as2 as3 : list α} /-- Elementwise negation of a list -/ def neg [has_neg α] (as : list α) := as.map (λ a, -a) variables [inhabited α] [inhabited β] /-- Update element of a list by index. If the index is out of range, extend the list with default elements -/ @[simp] def set (a : α) : list α → ℕ → list α | (_::as) 0 := a::as | [] 0 := [a] | (h::as) (k+1) := h::(set as k) | [] (k+1) := default::(set ([] : list α) k) localized "notation (name := list.func.set) as ` {` m ` ↦ ` a `}` := list.func.set a as m" in list.func /-- Get element of a list by index. If the index is out of range, return the default element -/ @[simp] def get : ℕ → list α → α | _ [] := default | 0 (a::as) := a | (n+1) (a::as) := get n as /-- Pointwise equality of lists. If lists are different lengths, compare with the default element. -/ def equiv (as1 as2 : list α) : Prop := ∀ (m : nat), get m as1 = get m as2 /-- Pointwise operations on lists. If lists are different lengths, use the default element. -/ @[simp] def pointwise (f : α → β → γ) : list α → list β → list γ | [] [] := [] | [] (b::bs) := map (f default) (b::bs) | (a::as) [] := map (λ x, f x default) (a::as) | (a::as) (b::bs) := (f a b)::(pointwise as bs) /-- Pointwise addition on lists. If lists are different lengths, use zero. -/ def add {α : Type u} [has_zero α] [has_add α] : list α → list α → list α := @pointwise α α α ⟨0⟩ ⟨0⟩ (+) /-- Pointwise subtraction on lists. If lists are different lengths, use zero. -/ def sub {α : Type u} [has_zero α] [has_sub α] : list α → list α → list α := @pointwise α α α ⟨0⟩ ⟨0⟩ (@has_sub.sub α _) /- set -/ lemma length_set : ∀ {m : ℕ} {as : list α}, (as {m ↦ a}).length = max as.length (m+1) | 0 [] := rfl | 0 (a::as) := by {rw max_eq_left, refl, simp [nat.le_add_right]} | (m+1) [] := by simp only [set, nat.zero_max, length, @length_set m] | (m+1) (a::as) := by simp only [set, nat.max_succ_succ, length, @length_set m] @[simp] lemma get_nil {k : ℕ} : (get k [] : α) = default := by {cases k; refl} lemma get_eq_default_of_le : ∀ (k : ℕ) {as : list α}, as.length ≤ k → get k as = default | 0 [] h1 := rfl | 0 (a::as) h1 := by cases h1 | (k+1) [] h1 := rfl | (k+1) (a::as) h1 := begin apply get_eq_default_of_le k, rw ← nat.succ_le_succ_iff, apply h1, end @[simp] lemma get_set {a : α} : ∀ {k : ℕ} {as : list α}, get k (as {k ↦ a}) = a | 0 as := by {cases as; refl, } | (k+1) as := by {cases as; simp [get_set]} lemma eq_get_of_mem {a : α} : ∀ {as : list α}, a ∈ as → ∃ n : nat, ∀ d : α, a = (get n as) | [] h := by cases h | (b::as) h := begin rw mem_cons_iff at h, cases h, { existsi 0, intro d, apply h }, { cases eq_get_of_mem h with n h2, existsi (n+1), apply h2 } end lemma mem_get_of_le : ∀ {n : ℕ} {as : list α}, n < as.length → get n as ∈ as | _ [] h1 := by cases h1 | 0 (a::as) _ := or.inl rfl | (n+1) (a::as) h1 := begin apply or.inr, unfold get, apply mem_get_of_le, apply nat.lt_of_succ_lt_succ h1, end lemma mem_get_of_ne_zero : ∀ {n : ℕ} {as : list α}, get n as ≠ default → get n as ∈ as | _ [] h1 := begin exfalso, apply h1, rw get_nil end | 0 (a::as) h1 := or.inl rfl | (n+1) (a::as) h1 := begin unfold get, apply (or.inr (mem_get_of_ne_zero _)), apply h1 end lemma get_set_eq_of_ne {a : α} : ∀ {as : list α} (k : ℕ) (m : ℕ), m ≠ k → get m (as {k ↦ a}) = get m as | as 0 m h1 := by { cases m, contradiction, cases as; simp only [set, get, get_nil] } | as (k+1) m h1 := begin cases as; cases m, simp only [set, get], { have h3 : get m (nil {k ↦ a}) = default, { rw [get_set_eq_of_ne k m, get_nil], intro hc, apply h1, simp [hc] }, apply h3 }, simp only [set, get], { apply get_set_eq_of_ne k m, intro hc, apply h1, simp [hc], } end lemma get_map {f : α → β} : ∀ {n : ℕ} {as : list α}, n < as.length → get n (as.map f) = f (get n as) | _ [] h := by cases h | 0 (a::as) h := rfl | (n+1) (a::as) h1 := begin have h2 : n < length as, { rw [← nat.succ_le_iff, ← nat.lt_succ_iff], apply h1 }, apply get_map h2, end lemma get_map' {f : α → β} {n : ℕ} {as : list α} : f default = default → get n (as.map f) = f (get n as) := begin intro h1, by_cases h2 : n < as.length, { apply get_map h2, }, { rw not_lt at h2, rw [get_eq_default_of_le _ h2, get_eq_default_of_le, h1], rw [length_map], apply h2 } end lemma forall_val_of_forall_mem {as : list α} {p : α → Prop} : p default → (∀ x ∈ as, p x) → (∀ n, p (get n as)) := begin intros h1 h2 n, by_cases h3 : n < as.length, { apply h2 _ (mem_get_of_le h3) }, { rw not_lt at h3, rw get_eq_default_of_le _ h3, apply h1 } end /- equiv -/ lemma equiv_refl : equiv as as := λ k, rfl lemma equiv_symm : equiv as1 as2 → equiv as2 as1 := λ h1 k, (h1 k).symm lemma equiv_trans : equiv as1 as2 → equiv as2 as3 → equiv as1 as3 := λ h1 h2 k, eq.trans (h1 k) (h2 k) lemma equiv_of_eq : as1 = as2 → equiv as1 as2 := begin intro h1, rw h1, apply equiv_refl end lemma eq_of_equiv : ∀ {as1 as2 : list α}, as1.length = as2.length → equiv as1 as2 → as1 = as2 | [] [] h1 h2 := rfl | (_::_) [] h1 h2 := by cases h1 | [] (_::_) h1 h2 := by cases h1 | (a1::as1) (a2::as2) h1 h2 := begin congr, { apply h2 0 }, have h3 : as1.length = as2.length, { simpa [add_left_inj, add_comm, length] using h1 }, apply eq_of_equiv h3, intro m, apply h2 (m+1) end end func -- We want to drop the `inhabited` instances for a moment, -- so we close and open the namespace namespace func /- neg -/ @[simp] lemma get_neg [add_group α] {k : ℕ} {as : list α} : @get α ⟨0⟩ k (neg as) = -(@get α ⟨0⟩ k as) := by {unfold neg, rw (@get_map' α α ⟨0⟩), apply neg_zero} @[simp] lemma length_neg [has_neg α] (as : list α) : (neg as).length = as.length := by simp only [neg, length_map] variables [inhabited α] [inhabited β] /- pointwise -/ lemma nil_pointwise {f : α → β → γ} : ∀ bs : list β, pointwise f [] bs = bs.map (f default) | [] := rfl | (b::bs) := by simp only [nil_pointwise bs, pointwise, eq_self_iff_true, and_self, map] lemma pointwise_nil {f : α → β → γ} : ∀ as : list α, pointwise f as [] = as.map (λ a, f a default) | [] := rfl | (a::as) := by simp only [pointwise_nil as, pointwise, eq_self_iff_true, and_self, list.map] lemma get_pointwise [inhabited γ] {f : α → β → γ} (h1 : f default default = default) : ∀ (k : nat) (as : list α) (bs : list β), get k (pointwise f as bs) = f (get k as) (get k bs) | k [] [] := by simp only [h1, get_nil, pointwise, get] | 0 [] (b::bs) := by simp only [get_pointwise, get_nil, pointwise, get, nat.nat_zero_eq_zero, map] | (k+1) [] (b::bs) := by { have : get k (map (f default) bs) = f default (get k bs), { simpa [nil_pointwise, get_nil] using (get_pointwise k [] bs) }, simpa [get, get_nil, pointwise, map] } | 0 (a::as) [] := by simp only [get_pointwise, get_nil, pointwise, get, nat.nat_zero_eq_zero, map] | (k+1) (a::as) [] := by simpa [get, get_nil, pointwise, map, pointwise_nil, get_nil] using get_pointwise k as [] | 0 (a::as) (b::bs) := by simp only [pointwise, get] | (k+1) (a::as) (b::bs) := by simp only [pointwise, get, get_pointwise k] lemma length_pointwise {f : α → β → γ} : ∀ {as : list α} {bs : list β}, (pointwise f as bs).length = max as.length bs.length | [] [] := rfl | [] (b::bs) := by simp only [pointwise, length, length_map, max_eq_right (nat.zero_le (length bs + 1))] | (a::as) [] := by simp only [pointwise, length, length_map, max_eq_left (nat.zero_le (length as + 1))] | (a::as) (b::bs) := by simp only [pointwise, length, nat.max_succ_succ, @length_pointwise as bs] end func namespace func /- add -/ @[simp] lemma get_add {α : Type u} [add_monoid α] {k : ℕ} {xs ys : list α} : @get α ⟨0⟩ k (add xs ys) = ( @get α ⟨0⟩ k xs + @get α ⟨0⟩ k ys) := by {apply get_pointwise, apply zero_add} @[simp] lemma length_add {α : Type u} [has_zero α] [has_add α] {xs ys : list α} : (add xs ys).length = max xs.length ys.length := @length_pointwise α α α ⟨0⟩ ⟨0⟩ _ _ _ @[simp] lemma nil_add {α : Type u} [add_monoid α] (as : list α) : add [] as = as := begin rw [add, @nil_pointwise α α α ⟨0⟩ ⟨0⟩], apply eq.trans _ (map_id as), congr' with x, rw [zero_add, id] end @[simp] lemma add_nil {α : Type u} [add_monoid α] (as : list α) : add as [] = as := begin rw [add, @pointwise_nil α α α ⟨0⟩ ⟨0⟩], apply eq.trans _ (map_id as), congr' with x, rw [add_zero, id] end lemma map_add_map {α : Type u} [add_monoid α] (f g : α → α) {as : list α} : add (as.map f) (as.map g) = as.map (λ x, f x + g x) := begin apply @eq_of_equiv _ (⟨0⟩ : inhabited α), { rw [length_map, length_add, max_eq_left, length_map], apply le_of_eq, rw [length_map, length_map] }, intros m, rw [get_add], by_cases h : m < length as, { repeat {rw [@get_map α α ⟨0⟩ ⟨0⟩ _ _ _ h]} }, rw not_lt at h, repeat {rw [get_eq_default_of_le m]}; try {rw length_map, apply h}, apply zero_add end /- sub -/ @[simp] lemma get_sub {α : Type u} [add_group α] {k : ℕ} {xs ys : list α} : @get α ⟨0⟩ k (sub xs ys) = (@get α ⟨0⟩ k xs - @get α ⟨0⟩ k ys) := by {apply get_pointwise, apply sub_zero} @[simp] lemma length_sub [has_zero α] [has_sub α] {xs ys : list α} : (sub xs ys).length = max xs.length ys.length := @length_pointwise α α α ⟨0⟩ ⟨0⟩ _ _ _ @[simp] lemma nil_sub {α : Type} [add_group α] (as : list α) : sub [] as = neg as := begin rw [sub, nil_pointwise], congr' with x, rw [zero_sub] end @[simp] lemma sub_nil {α : Type} [add_group α] (as : list α) : sub as [] = as := begin rw [sub, pointwise_nil], apply eq.trans _ (map_id as), congr' with x, rw [sub_zero, id] end end func end list
3f0786c3631ecc26a981708cc24d158dc89acc62
aa101d73b1a3173c7ec56de02b96baa8ca64c42e
/src/exercises/03_forall_or.lean
1c8d4cad45393b856febab84e3e6efb259efa6e3
[ "Apache-2.0" ]
permissive
gihanmarasingha/tutorials
b554d4d53866c493c4341dc13e914b01444e95a6
56617114ef0f9f7b808476faffd11e22e4380918
refs/heads/master
1,671,141,758,153
1,599,173,318,000
1,599,173,318,000
282,405,870
0
0
Apache-2.0
1,595,666,751,000
1,595,666,750,000
null
UTF-8
Lean
false
false
7,800
lean
import data.real.basic import algebra.pi_instances set_option pp.beta true /- In this file, we'll learn about the ∀ quantifier, and the disjunction operator ∨ (logical OR). Let P be a predicate on a type X. This means for every mathematical object x with type X, we get a mathematical statement P x. In Lean, P x has type Prop. Lean sees a proof h of `∀ x, P x` as a function sending any `x : X` to a proof `h x` of `P x`. This already explains the main way to use an assumption or lemma which starts with a ∀. In order to prove `∀ x, P x`, we use `intros x` to fix an arbitrary object with type X, and call it x. Note also we don't need to give the type of x in the expression `∀ x, P x` as long as the type of P is clear to Lean, which can then infer the type of x. Let's define two predicates to play with ∀. -/ def even_fun (f : ℝ → ℝ) := ∀ x, f (-x) = f x def odd_fun (f : ℝ → ℝ) := ∀ x, f (-x) = -f x /- In the next proof, we also take the opportunity to introduce the `unfold` tactic, which simply unfolds definitions. Here this is purely for didactic reason, Lean doesn't need those `unfold` invocations. We will also use `rfl` which is a term proving equalities that are true by definition (in a very strong sense to be discussed later). -/ example (f g : ℝ → ℝ) : even_fun f → even_fun g → even_fun (f + g) := begin -- Assume f is even intros hf, -- which means ∀ x, f (-x) = f x unfold even_fun at hf, -- and the same for g intros hg, unfold even_fun at hg, -- We need to prove ∀ x, (f+g)(-x) = (f+g)(x) unfold even_fun, -- Let x be any real number intros x, -- and let's compute calc (f + g) (-x) = f (-x) + g (-x) : rfl ... = f x + g (-x) : by rw hf x ... = f x + g x : by rw hg x ... = (f + g) x : rfl end /- In the preceding proof, all `unfold` lines are purely for psychological comfort. Sometimes unfolding is necessary because we want to apply a tactic that operates purely on the syntactical level. The main such tactic is `rw`. The same property of `rw` explain why the first computation line is necessary, although its proof is simply `rfl`. Before that line, `rw hf x` won't find anything like `f (-x)` hence will give up. The last line is not necessary however, since it only proves something that is true by definition, and is not followed by a `rw`. Also, Lean doesn't need to be told that hf should be specialized to x before rewriting, exactly as in the first file 01_equality_rewriting. We can also gather several rewrites using a list of expressions. Hence we can compress the above proof to: -/ example (f g : ℝ → ℝ) : even_fun f → even_fun g → even_fun (f + g) := begin intros hf hg x, calc (f + g) (-x) = f (-x) + g (-x) : rfl ... = f x + g x : by rw [hf, hg] end /- Note that the tactic state displays changes when we move the cursor inside the list of expressions given to `rw`. Now let's practice. -/ -- 0023 example (f g : ℝ → ℝ) : even_fun f → even_fun (g ∘ f) := begin sorry end -- 0024 example (f g : ℝ → ℝ) : odd_fun f → odd_fun g → odd_fun (g ∘ f) := begin sorry end /- Let's have more quantifiers, and play with forward and backward reasoning. In the next definitions, note how `∀ x₁, ∀ x₂` is abreviated to `∀ x₁ x₂`. -/ def non_decreasing (f : ℝ → ℝ) := ∀ x₁ x₂, x₁ ≤ x₂ → f x₁ ≤ f x₂ def non_increasing (f : ℝ → ℝ) := ∀ x₁ x₂, x₁ ≤ x₂ → f x₁ ≥ f x₂ /- Let's be very explicit and use forward reasonning first. -/ example (f g : ℝ → ℝ) (hf : non_decreasing f) (hg : non_decreasing g) : non_decreasing (g ∘ f) := begin -- Let x₁ and x₂ be real numbers such that x₁ ≤ x₂ intros x₁ x₂ h, -- Since f is non-decreasing, f x₁ ≤ f x₂. have step₁ : f x₁ ≤ f x₂, exact hf x₁ x₂ h, -- Since g is non-decreasing, we then get g (f x₁) ≤ g (f x₂). exact hg (f x₁) (f x₂) step₁, end /- In the above proof, note how inconvenient it is to specify x₁ and x₂ in `hf x₁ x₂ h` since they could be inferred from the type of h. We could have written `hf _ _ h` and Lean would have filled the holes denoted by _. Even better we could have written the definition of `non_decreasing` as: ∀ {x₁ x₂}, x₁ ≤ x₂ → f x₁ ≤ f x₂, with curly braces to denote implicit arguments. But let's leave that aside for now. One possible variation on the above proof is to use the `specialize` tactic to replace hf by its specialization to the relevant value. -/ example (f g : ℝ → ℝ) (hf : non_decreasing f) (hg : non_decreasing g) : non_decreasing (g ∘ f) := begin intros x₁ x₂ h, specialize hf x₁ x₂ h, exact hg (f x₁) (f x₂) hf, end /- This `specialize` tactic is mostly useful for exploration, or in preparation for rewriting in the assumption. One can very often replace its use by using more complicated expressions directly involving the original assumption, as in the next variation: -/ example (f g : ℝ → ℝ) (hf : non_decreasing f) (hg : non_decreasing g) : non_decreasing (g ∘ f) := begin intros x₁ x₂ h, exact hg (f x₁) (f x₂) (hf x₁ x₂ h), end /- Since the above proof uses only `intros` and `exact`, we could very easily replace it by the raw proof term: -/ example (f g : ℝ → ℝ) (hf : non_decreasing f) (hg : non_decreasing g) : non_decreasing (g ∘ f) := λ x₁ x₂ h, hg (f x₁) (f x₂) (hf x₁ x₂ h) /- Of course the above proof is difficult to decipher. The principle in mathlib is to use such a proof when the result is obvious and you don't want to read the proof anyway. Instead of pursuing this style, let's see how backward reasoning would look like here. As usual with this style, we use `apply` and enjoy Lean specializing assumptions for us using unification. -/ example (f g : ℝ → ℝ) (hf : non_decreasing f) (hg : non_decreasing g) : non_decreasing (g ∘ f) := begin -- Let x₁ and x₂ be real numbers such that x₁ ≤ x₂ intros x₁ x₂ h, -- We need to prove (g ∘ f) x₁ ≤ (g ∘ f) x₂. -- Since g is non-decreasing, it suffices to prove f x₁ ≤ f x₂ apply hg, -- which follows from our assumption on f apply hf, -- and on x₁ and x₂ exact h end -- 0025 example (f g : ℝ → ℝ) (hf : non_decreasing f) (hg : non_increasing g) : non_increasing (g ∘ f) := begin sorry end /- Let's switch to disjunctions now. Lean denotes by ∨ the logical OR operator. In order to make use of an assumption hyp : P ∨ Q we use the cases tactic: cases hyp with hP hQ which creates two proof branches: one branch assuming hP : P, and one branch assuming hQ : Q. In order to directly prove a goal P ∨ Q, we use either the `left` tactic and prove P or the `right` tactic and prove Q. In the next proof we use `ring` and `linarith` to get rid of easy computations or inequalities, as well as one lemma: mul_eq_zero : a*b = 0 ↔ a = 0 ∨ b = 0 -/ example (a b : ℝ) : a = a*b → a = 0 ∨ b = 1 := begin intro hyp, have H : a*(1 - b) = 0, { calc a*(1 - b) = a - a*b : by ring ... = 0 : by linarith, }, rw mul_eq_zero at H, cases H with Ha Hb, { left, exact Ha, }, { right, linarith, }, end -- 0026 example (x y : ℝ) : x^2 = y^2 → x = y ∨ x = -y := begin sorry end /- In the next exercise, we can use: eq_or_lt_of_le : x ≤ y → x = y ∨ x < y -/ -- 0027 example (f : ℝ → ℝ) : non_decreasing f ↔ ∀ x y, x < y → f x ≤ f y := begin sorry end /- In the next exercise, we can use: le_total x y : x ≤ y ∨ y ≤ x -/ -- 0028 example (f : ℝ → ℝ) (h : non_decreasing f) (h' : ∀ x, f (f x) = x) : ∀ x, f x = x := begin sorry end
128dfc030817b16393db9b471f3127d7eb7e99b9
6f510b1ed724f95a55b7d26a8dcd13e1264123dd
/src/nat/extra.lean
bcf86b8ed053870c5af93e9f9acc942b0e05bc13
[]
no_license
jcommelin/oberharmersbach2019
adaf2e54ba4eff7c178c933978055ff4d6b0593b
d2cdf780a10baa8502a9b0cae01c7efa318649a6
refs/heads/master
1,587,558,516,731
1,550,558,213,000
1,550,558,213,000
170,372,753
0
0
null
null
null
null
UTF-8
Lean
false
false
534
lean
import tactic.interactive namespace nat lemma dvd_add_iff_right_of_left (k m n : ℕ) (h : k ∣ m) : k ∣ n ↔ k ∣ m + n := nat.dvd_add_iff_right h lemma dvd_right_of_dvd_add_of_dvd_left (k m n : ℕ) (h : k ∣ m) : k ∣ m + n → k ∣ n := (dvd_add_iff_right_of_left _ _ _ h).mpr end nat namespace tactic namespace interactive open interactive interactive.types meta def use_this (l : parse pexpr_list_or_texpr) : tactic unit := (tactic.use l >> (triv <|> try `[apply exists_prop.mpr])) end interactive end tactic
b538690d7626ee9744304ab3264af082ac5c385b
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/category_theory/limits/creates.lean
accb1c29cd63ea0565bb0e5e146dbb9c6d4c29f3
[ "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
22,213
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.limits.preserves.basic open category_theory category_theory.limits noncomputable theory namespace category_theory universes v u₁ u₂ u₃ variables {C : Type u₁} [category.{v} C] section creates variables {D : Type u₂} [category.{v} D] variables {J : Type v} [small_category J] {K : J ⥤ C} /-- Define the lift of a cone: For a cone `c` for `K ⋙ F`, give a cone for `K` which is a lift of `c`, i.e. the image of it under `F` is (iso) to `c`. We will then use this as part of the definition of creation of limits: every limit cone has a lift. Note this definition is really only useful when `c` is a limit already. -/ structure liftable_cone (K : J ⥤ C) (F : C ⥤ D) (c : cone (K ⋙ F)) := (lifted_cone : cone K) (valid_lift : F.map_cone lifted_cone ≅ c) /-- Define the lift of a cocone: For a cocone `c` for `K ⋙ F`, give a cocone for `K` which is a lift of `c`, i.e. the image of it under `F` is (iso) to `c`. We will then use this as part of the definition of creation of colimits: every limit cocone has a lift. Note this definition is really only useful when `c` is a colimit already. -/ structure liftable_cocone (K : J ⥤ C) (F : C ⥤ D) (c : cocone (K ⋙ F)) := (lifted_cocone : cocone K) (valid_lift : F.map_cocone lifted_cocone ≅ c) /-- Definition 3.3.1 of [Riehl]. We say that `F` creates limits of `K` if, given any limit cone `c` for `K ⋙ F` (i.e. below) we can lift it to a cone "above", and further that `F` reflects limits for `K`. If `F` reflects isomorphisms, it suffices to show only that the lifted cone is a limit - see `creates_limit_of_reflects_iso`. -/ class creates_limit (K : J ⥤ C) (F : C ⥤ D) extends reflects_limit K F := (lifts : Π c, is_limit c → liftable_cone K F c) /-- `F` creates limits of shape `J` if `F` creates the limit of any diagram `K : J ⥤ C`. -/ class creates_limits_of_shape (J : Type v) [small_category J] (F : C ⥤ D) := (creates_limit : Π {K : J ⥤ C}, creates_limit K F . tactic.apply_instance) /-- `F` creates limits if it creates limits of shape `J` for any small `J`. -/ class creates_limits (F : C ⥤ D) := (creates_limits_of_shape : Π {J : Type v} [small_category J], creates_limits_of_shape J F . tactic.apply_instance) /-- Dual of definition 3.3.1 of [Riehl]. We say that `F` creates colimits of `K` if, given any limit cocone `c` for `K ⋙ F` (i.e. below) we can lift it to a cocone "above", and further that `F` reflects limits for `K`. If `F` reflects isomorphisms, it suffices to show only that the lifted cocone is a limit - see `creates_limit_of_reflects_iso`. -/ class creates_colimit (K : J ⥤ C) (F : C ⥤ D) extends reflects_colimit K F := (lifts : Π c, is_colimit c → liftable_cocone K F c) /-- `F` creates colimits of shape `J` if `F` creates the colimit of any diagram `K : J ⥤ C`. -/ class creates_colimits_of_shape (J : Type v) [small_category J] (F : C ⥤ D) := (creates_colimit : Π {K : J ⥤ C}, creates_colimit K F . tactic.apply_instance) /-- `F` creates colimits if it creates colimits of shape `J` for any small `J`. -/ class creates_colimits (F : C ⥤ D) := (creates_colimits_of_shape : Π {J : Type v} [small_category J], creates_colimits_of_shape J F . tactic.apply_instance) attribute [instance, priority 100] -- see Note [lower instance priority] creates_limits_of_shape.creates_limit creates_limits.creates_limits_of_shape creates_colimits_of_shape.creates_colimit creates_colimits.creates_colimits_of_shape /- Interface to the `creates_limit` class. -/ /-- `lift_limit t` is the cone for `K` given by lifting the limit `t` for `K ⋙ F`. -/ def lift_limit {K : J ⥤ C} {F : C ⥤ D} [creates_limit K F] {c : cone (K ⋙ F)} (t : is_limit c) : cone K := (creates_limit.lifts c t).lifted_cone /-- The lifted cone has an image isomorphic to the original cone. -/ def lifted_limit_maps_to_original {K : J ⥤ C} {F : C ⥤ D} [creates_limit K F] {c : cone (K ⋙ F)} (t : is_limit c) : F.map_cone (lift_limit t) ≅ c := (creates_limit.lifts c t).valid_lift /-- The lifted cone is a limit. -/ def lifted_limit_is_limit {K : J ⥤ C} {F : C ⥤ D} [creates_limit K F] {c : cone (K ⋙ F)} (t : is_limit c) : is_limit (lift_limit t) := reflects_limit.reflects (is_limit.of_iso_limit t (lifted_limit_maps_to_original t).symm) /-- If `F` creates the limit of `K` and `K ⋙ F` has a limit, then `K` has a limit. -/ lemma has_limit_of_created (K : J ⥤ C) (F : C ⥤ D) [has_limit (K ⋙ F)] [creates_limit K F] : has_limit K := has_limit.mk { cone := lift_limit (limit.is_limit (K ⋙ F)), is_limit := lifted_limit_is_limit _ } /-- If `F` creates limits of shape `J`, and `D` has limits of shape `J`, then `C` has limits of shape `J`. -/ lemma has_limits_of_shape_of_has_limits_of_shape_creates_limits_of_shape (F : C ⥤ D) [has_limits_of_shape J D] [creates_limits_of_shape J F] : has_limits_of_shape J C := ⟨λ G, has_limit_of_created G F⟩ /-- If `F` creates limits, and `D` has all limits, then `C` has all limits. -/ lemma has_limits_of_has_limits_creates_limits (F : C ⥤ D) [has_limits D] [creates_limits F] : has_limits C := ⟨λ J I, by exactI has_limits_of_shape_of_has_limits_of_shape_creates_limits_of_shape F⟩ /- Interface to the `creates_colimit` class. -/ /-- `lift_colimit t` is the cocone for `K` given by lifting the colimit `t` for `K ⋙ F`. -/ def lift_colimit {K : J ⥤ C} {F : C ⥤ D} [creates_colimit K F] {c : cocone (K ⋙ F)} (t : is_colimit c) : cocone K := (creates_colimit.lifts c t).lifted_cocone /-- The lifted cocone has an image isomorphic to the original cocone. -/ def lifted_colimit_maps_to_original {K : J ⥤ C} {F : C ⥤ D} [creates_colimit K F] {c : cocone (K ⋙ F)} (t : is_colimit c) : F.map_cocone (lift_colimit t) ≅ c := (creates_colimit.lifts c t).valid_lift /-- The lifted cocone is a colimit. -/ def lifted_colimit_is_colimit {K : J ⥤ C} {F : C ⥤ D} [creates_colimit K F] {c : cocone (K ⋙ F)} (t : is_colimit c) : is_colimit (lift_colimit t) := reflects_colimit.reflects (is_colimit.of_iso_colimit t (lifted_colimit_maps_to_original t).symm) /-- If `F` creates the limit of `K` and `K ⋙ F` has a limit, then `K` has a limit. -/ lemma has_colimit_of_created (K : J ⥤ C) (F : C ⥤ D) [has_colimit (K ⋙ F)] [creates_colimit K F] : has_colimit K := has_colimit.mk { cocone := lift_colimit (colimit.is_colimit (K ⋙ F)), is_colimit := lifted_colimit_is_colimit _ } /-- If `F` creates colimits of shape `J`, and `D` has colimits of shape `J`, then `C` has colimits of shape `J`. -/ lemma has_colimits_of_shape_of_has_colimits_of_shape_creates_colimits_of_shape (F : C ⥤ D) [has_colimits_of_shape J D] [creates_colimits_of_shape J F] : has_colimits_of_shape J C := ⟨λ G, has_colimit_of_created G F⟩ /-- If `F` creates colimits, and `D` has all colimits, then `C` has all colimits. -/ lemma has_colimits_of_has_colimits_creates_colimits (F : C ⥤ D) [has_colimits D] [creates_colimits F] : has_colimits C := ⟨λ J I, by exactI has_colimits_of_shape_of_has_colimits_of_shape_creates_colimits_of_shape F⟩ @[priority 10] instance reflects_limits_of_shape_of_creates_limits_of_shape (F : C ⥤ D) [creates_limits_of_shape J F] : reflects_limits_of_shape J F := {} @[priority 10] instance reflects_limits_of_creates_limits (F : C ⥤ D) [creates_limits F] : reflects_limits F := {} @[priority 10] instance reflects_colimits_of_shape_of_creates_colimits_of_shape (F : C ⥤ D) [creates_colimits_of_shape J F] : reflects_colimits_of_shape J F := {} @[priority 10] instance reflects_colimits_of_creates_colimits (F : C ⥤ D) [creates_colimits F] : reflects_colimits F := {} /-- A helper to show a functor creates limits. In particular, if we can show that for any limit cone `c` for `K ⋙ F`, there is a lift of it which is a limit and `F` reflects isomorphisms, then `F` creates limits. Usually, `F` creating limits says that _any_ lift of `c` is a limit, but here we only need to show that our particular lift of `c` is a limit. -/ structure lifts_to_limit (K : J ⥤ C) (F : C ⥤ D) (c : cone (K ⋙ F)) (t : is_limit c) extends liftable_cone K F c := (makes_limit : is_limit lifted_cone) /-- A helper to show a functor creates colimits. In particular, if we can show that for any limit cocone `c` for `K ⋙ F`, there is a lift of it which is a limit and `F` reflects isomorphisms, then `F` creates colimits. Usually, `F` creating colimits says that _any_ lift of `c` is a colimit, but here we only need to show that our particular lift of `c` is a colimit. -/ structure lifts_to_colimit (K : J ⥤ C) (F : C ⥤ D) (c : cocone (K ⋙ F)) (t : is_colimit c) extends liftable_cocone K F c := (makes_colimit : is_colimit lifted_cocone) /-- If `F` reflects isomorphisms and we can lift any limit cone to a limit cone, then `F` creates limits. In particular here we don't need to assume that F reflects limits. -/ def creates_limit_of_reflects_iso {K : J ⥤ C} {F : C ⥤ D} [reflects_isomorphisms F] (h : Π c t, lifts_to_limit K F c t) : creates_limit K F := { lifts := λ c t, (h c t).to_liftable_cone, to_reflects_limit := { reflects := λ (d : cone K) (hd : is_limit (F.map_cone d)), begin let d' : cone K := (h (F.map_cone d) hd).to_liftable_cone.lifted_cone, let i : F.map_cone d' ≅ F.map_cone d := (h (F.map_cone d) hd).to_liftable_cone.valid_lift, let hd' : is_limit d' := (h (F.map_cone d) hd).makes_limit, let f : d ⟶ d' := hd'.lift_cone_morphism d, have : (cones.functoriality K F).map f = i.inv := (hd.of_iso_limit i.symm).uniq_cone_morphism, haveI : is_iso ((cones.functoriality K F).map f) := (by { rw this, apply_instance }), haveI : is_iso f := is_iso_of_reflects_iso f (cones.functoriality K F), exact is_limit.of_iso_limit hd' (as_iso f).symm, end } } /-- When `F` is fully faithful, and `has_limit (K ⋙ F)`, to show that `F` creates the limit for `K` it suffices to exhibit a lift of the chosen limit cone for `K ⋙ F`. -/ -- Notice however that even if the isomorphism is `iso.refl _`, -- this construction will insert additional identity morphisms in the cone maps, -- so the constructed limits may not be ideal, definitionally. def creates_limit_of_fully_faithful_of_lift {K : J ⥤ C} {F : C ⥤ D} [full F] [faithful F] [has_limit (K ⋙ F)] (c : cone K) (i : F.map_cone c ≅ limit.cone (K ⋙ F)) : creates_limit K F := creates_limit_of_reflects_iso (λ c' t, { lifted_cone := c, valid_lift := i.trans (is_limit.unique_up_to_iso (limit.is_limit _) t), makes_limit := is_limit.of_faithful F (is_limit.of_iso_limit (limit.is_limit _) i.symm) (λ s, F.preimage _) (λ s, F.image_preimage _) }) /-- When `F` is fully faithful, and `has_limit (K ⋙ F)`, to show that `F` creates the limit for `K` it suffices to show that the chosen limit point is in the essential image of `F`. -/ -- Notice however that even if the isomorphism is `iso.refl _`, -- this construction will insert additional identity morphisms in the cone maps, -- so the constructed limits may not be ideal, definitionally. def creates_limit_of_fully_faithful_of_iso {K : J ⥤ C} {F : C ⥤ D} [full F] [faithful F] [has_limit (K ⋙ F)] (X : C) (i : F.obj X ≅ limit (K ⋙ F)) : creates_limit K F := creates_limit_of_fully_faithful_of_lift ({ X := X, π := { app := λ j, F.preimage (i.hom ≫ limit.π (K ⋙ F) j), naturality' := λ Y Z f, F.map_injective (by { dsimp, simp, erw limit.w (K ⋙ F), }) }} : cone K) (by { fapply cones.ext, exact i, tidy, }) /-- `F` preserves the limit of `K` if it creates the limit and `K ⋙ F` has the limit. -/ @[priority 100] -- see Note [lower instance priority] instance preserves_limit_of_creates_limit_and_has_limit (K : J ⥤ C) (F : C ⥤ D) [creates_limit K F] [has_limit (K ⋙ F)] : preserves_limit K F := { preserves := λ c t, is_limit.of_iso_limit (limit.is_limit _) ((lifted_limit_maps_to_original (limit.is_limit _)).symm ≪≫ ((cones.functoriality K F).map_iso ((lifted_limit_is_limit (limit.is_limit _)).unique_up_to_iso t))) } /-- `F` preserves the limit of shape `J` if it creates these limits and `D` has them. -/ @[priority 100] -- see Note [lower instance priority] instance preserves_limit_of_shape_of_creates_limits_of_shape_and_has_limits_of_shape (F : C ⥤ D) [creates_limits_of_shape J F] [has_limits_of_shape J D] : preserves_limits_of_shape J F := { preserves_limit := λ K, category_theory.preserves_limit_of_creates_limit_and_has_limit K F } /-- `F` preserves limits if it creates limits and `D` has limits. -/ @[priority 100] -- see Note [lower instance priority] instance preserves_limits_of_creates_limits_and_has_limits (F : C ⥤ D) [creates_limits F] [has_limits D] : preserves_limits F := { preserves_limits_of_shape := λ J 𝒥, by exactI category_theory.preserves_limit_of_shape_of_creates_limits_of_shape_and_has_limits_of_shape F } /-- If `F` reflects isomorphisms and we can lift any colimit cocone to a colimit cocone, then `F` creates colimits. In particular here we don't need to assume that F reflects colimits. -/ def creates_colimit_of_reflects_iso {K : J ⥤ C} {F : C ⥤ D} [reflects_isomorphisms F] (h : Π c t, lifts_to_colimit K F c t) : creates_colimit K F := { lifts := λ c t, (h c t).to_liftable_cocone, to_reflects_colimit := { reflects := λ (d : cocone K) (hd : is_colimit (F.map_cocone d)), begin let d' : cocone K := (h (F.map_cocone d) hd).to_liftable_cocone.lifted_cocone, let i : F.map_cocone d' ≅ F.map_cocone d := (h (F.map_cocone d) hd).to_liftable_cocone.valid_lift, let hd' : is_colimit d' := (h (F.map_cocone d) hd).makes_colimit, let f : d' ⟶ d := hd'.desc_cocone_morphism d, have : (cocones.functoriality K F).map f = i.hom := (hd.of_iso_colimit i.symm).uniq_cocone_morphism, haveI : is_iso ((cocones.functoriality K F).map f) := (by { rw this, apply_instance }), haveI := is_iso_of_reflects_iso f (cocones.functoriality K F), exact is_colimit.of_iso_colimit hd' (as_iso f), end } } /-- `F` preserves the colimit of `K` if it creates the colimit and `K ⋙ F` has the colimit. -/ @[priority 100] -- see Note [lower instance priority] instance preserves_colimit_of_creates_colimit_and_has_colimit (K : J ⥤ C) (F : C ⥤ D) [creates_colimit K F] [has_colimit (K ⋙ F)] : preserves_colimit K F := { preserves := λ c t, is_colimit.of_iso_colimit (colimit.is_colimit _) ((lifted_colimit_maps_to_original (colimit.is_colimit _)).symm ≪≫ ((cocones.functoriality K F).map_iso ((lifted_colimit_is_colimit (colimit.is_colimit _)).unique_up_to_iso t))) } /-- `F` preserves the colimit of shape `J` if it creates these colimits and `D` has them. -/ @[priority 100] -- see Note [lower instance priority] instance preserves_colimit_of_shape_of_creates_colimits_of_shape_and_has_colimits_of_shape (F : C ⥤ D) [creates_colimits_of_shape J F] [has_colimits_of_shape J D] : preserves_colimits_of_shape J F := { preserves_colimit := λ K, category_theory.preserves_colimit_of_creates_colimit_and_has_colimit K F } /-- `F` preserves limits if it creates limits and `D` has limits. -/ @[priority 100] -- see Note [lower instance priority] instance preserves_colimits_of_creates_colimits_and_has_colimits (F : C ⥤ D) [creates_colimits F] [has_colimits D] : preserves_colimits F := { preserves_colimits_of_shape := λ J 𝒥, by exactI category_theory.preserves_colimit_of_shape_of_creates_colimits_of_shape_and_has_colimits_of_shape F } /-- If `F` creates the limit of `K` and `F ≅ G`, then `G` creates the limit of `K`. -/ def creates_limit_of_nat_iso {F G : C ⥤ D} (h : F ≅ G) [creates_limit K F] : creates_limit K G := { lifts := λ c t, { lifted_cone := lift_limit ((is_limit.postcompose_inv_equiv (iso_whisker_left K h : _) c).symm t), valid_lift := begin refine (is_limit.map_cone_equiv h _).unique_up_to_iso t, apply is_limit.of_iso_limit _ ((lifted_limit_maps_to_original _).symm), apply (is_limit.postcompose_inv_equiv _ _).symm t, end }, to_reflects_limit := reflects_limit_of_nat_iso _ h } /-- If `F` creates limits of shape `J` and `F ≅ G`, then `G` creates limits of shape `J`. -/ def creates_limits_of_shape_of_nat_iso {F G : C ⥤ D} (h : F ≅ G) [creates_limits_of_shape J F] : creates_limits_of_shape J G := { creates_limit := λ K, creates_limit_of_nat_iso h } /-- If `F` creates limits and `F ≅ G`, then `G` creates limits. -/ def creates_limits_of_nat_iso {F G : C ⥤ D} (h : F ≅ G) [creates_limits F] : creates_limits G := { creates_limits_of_shape := λ J 𝒥₁, by exactI creates_limits_of_shape_of_nat_iso h } /-- If `F` creates the colimit of `K` and `F ≅ G`, then `G` creates the colimit of `K`. -/ def creates_colimit_of_nat_iso {F G : C ⥤ D} (h : F ≅ G) [creates_colimit K F] : creates_colimit K G := { lifts := λ c t, { lifted_cocone := lift_colimit ((is_colimit.precompose_hom_equiv (iso_whisker_left K h : _) c).symm t), valid_lift := begin refine (is_colimit.map_cocone_equiv h _).unique_up_to_iso t, apply is_colimit.of_iso_colimit _ ((lifted_colimit_maps_to_original _).symm), apply (is_colimit.precompose_hom_equiv _ _).symm t, end }, to_reflects_colimit := reflects_colimit_of_nat_iso _ h } /-- If `F` creates colimits of shape `J` and `F ≅ G`, then `G` creates colimits of shape `J`. -/ def creates_colimits_of_shape_of_nat_iso {F G : C ⥤ D} (h : F ≅ G) [creates_colimits_of_shape J F] : creates_colimits_of_shape J G := { creates_colimit := λ K, creates_colimit_of_nat_iso h } /-- If `F` creates colimits and `F ≅ G`, then `G` creates colimits. -/ def creates_colimits_of_nat_iso {F G : C ⥤ D} (h : F ≅ G) [creates_colimits F] : creates_colimits G := { creates_colimits_of_shape := λ J 𝒥₁, by exactI creates_colimits_of_shape_of_nat_iso h } -- For the inhabited linter later. /-- If F creates the limit of K, any cone lifts to a limit. -/ def lifts_to_limit_of_creates (K : J ⥤ C) (F : C ⥤ D) [creates_limit K F] (c : cone (K ⋙ F)) (t : is_limit c) : lifts_to_limit K F c t := { lifted_cone := lift_limit t, valid_lift := lifted_limit_maps_to_original t, makes_limit := lifted_limit_is_limit t } -- For the inhabited linter later. /-- If F creates the colimit of K, any cocone lifts to a colimit. -/ def lifts_to_colimit_of_creates (K : J ⥤ C) (F : C ⥤ D) [creates_colimit K F] (c : cocone (K ⋙ F)) (t : is_colimit c) : lifts_to_colimit K F c t := { lifted_cocone := lift_colimit t, valid_lift := lifted_colimit_maps_to_original t, makes_colimit := lifted_colimit_is_colimit t } /-- Any cone lifts through the identity functor. -/ def id_lifts_cone (c : cone (K ⋙ 𝟭 C)) : liftable_cone K (𝟭 C) c := { lifted_cone := { X := c.X, π := c.π ≫ K.right_unitor.hom }, valid_lift := cones.ext (iso.refl _) (by tidy) } /-- The identity functor creates all limits. -/ instance id_creates_limits : creates_limits (𝟭 C) := { creates_limits_of_shape := λ J 𝒥, by exactI { creates_limit := λ F, { lifts := λ c t, id_lifts_cone c } } } /-- Any cocone lifts through the identity functor. -/ def id_lifts_cocone (c : cocone (K ⋙ 𝟭 C)) : liftable_cocone K (𝟭 C) c := { lifted_cocone := { X := c.X, ι := K.right_unitor.inv ≫ c.ι }, valid_lift := cocones.ext (iso.refl _) (by tidy) } /-- The identity functor creates all colimits. -/ instance id_creates_colimits : creates_colimits (𝟭 C) := { creates_colimits_of_shape := λ J 𝒥, by exactI { creates_colimit := λ F, { lifts := λ c t, id_lifts_cocone c } } } /-- Satisfy the inhabited linter -/ instance inhabited_liftable_cone (c : cone (K ⋙ 𝟭 C)) : inhabited (liftable_cone K (𝟭 C) c) := ⟨id_lifts_cone c⟩ instance inhabited_liftable_cocone (c : cocone (K ⋙ 𝟭 C)) : inhabited (liftable_cocone K (𝟭 C) c) := ⟨id_lifts_cocone c⟩ /-- Satisfy the inhabited linter -/ instance inhabited_lifts_to_limit (K : J ⥤ C) (F : C ⥤ D) [creates_limit K F] (c : cone (K ⋙ F)) (t : is_limit c) : inhabited (lifts_to_limit _ _ _ t) := ⟨lifts_to_limit_of_creates K F c t⟩ instance inhabited_lifts_to_colimit (K : J ⥤ C) (F : C ⥤ D) [creates_colimit K F] (c : cocone (K ⋙ F)) (t : is_colimit c) : inhabited (lifts_to_colimit _ _ _ t) := ⟨lifts_to_colimit_of_creates K F c t⟩ section comp variables {E : Type u₃} [ℰ : category.{v} E] variables (F : C ⥤ D) (G : D ⥤ E) instance comp_creates_limit [creates_limit K F] [creates_limit (K ⋙ F) G] : creates_limit K (F ⋙ G) := { lifts := λ c t, { lifted_cone := lift_limit (lifted_limit_is_limit t), valid_lift := (cones.functoriality (K ⋙ F) G).map_iso (lifted_limit_maps_to_original (lifted_limit_is_limit t)) ≪≫ (lifted_limit_maps_to_original t) } } instance comp_creates_limits_of_shape [creates_limits_of_shape J F] [creates_limits_of_shape J G] : creates_limits_of_shape J (F ⋙ G) := { creates_limit := infer_instance } instance comp_creates_limits [creates_limits F] [creates_limits G] : creates_limits (F ⋙ G) := { creates_limits_of_shape := infer_instance } instance comp_creates_colimit [creates_colimit K F] [creates_colimit (K ⋙ F) G] : creates_colimit K (F ⋙ G) := { lifts := λ c t, { lifted_cocone := lift_colimit (lifted_colimit_is_colimit t), valid_lift := (cocones.functoriality (K ⋙ F) G).map_iso (lifted_colimit_maps_to_original (lifted_colimit_is_colimit t)) ≪≫ (lifted_colimit_maps_to_original t) } } instance comp_creates_colimits_of_shape [creates_colimits_of_shape J F] [creates_colimits_of_shape J G] : creates_colimits_of_shape J (F ⋙ G) := { creates_colimit := infer_instance } instance comp_creates_colimits [creates_colimits F] [creates_colimits G] : creates_colimits (F ⋙ G) := { creates_colimits_of_shape := infer_instance } end comp end creates end category_theory
c385aa36b34fafd4e9e32479cbc6512b34903230
130c49f47783503e462c16b2eff31933442be6ff
/src/Lean/Elab/MutualDef.lean
1b9c8417afec00781e7576df3450c66930fd9040
[ "Apache-2.0" ]
permissive
Hazel-Brown/lean4
8aa5860e282435ffc30dcdfccd34006c59d1d39c
79e6732fc6bbf5af831b76f310f9c488d44e7a16
refs/heads/master
1,689,218,208,951
1,629,736,869,000
1,629,736,896,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
29,280
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Parser.Term import Lean.Meta.Closure import Lean.Meta.Check import Lean.Elab.Command import Lean.Elab.DefView import Lean.Elab.PreDefinition import Lean.Elab.DeclarationRange namespace Lean.Elab open Lean.Parser.Term /- DefView after elaborating the header. -/ structure DefViewElabHeader where ref : Syntax modifiers : Modifiers kind : DefKind shortDeclName : Name declName : Name levelNames : List Name numParams : Nat type : Expr -- including the parameters valueStx : Syntax deriving Inhabited namespace Term open Meta private def checkModifiers (m₁ m₂ : Modifiers) : TermElabM Unit := do unless m₁.isUnsafe == m₂.isUnsafe do throwError "cannot mix unsafe and safe definitions" unless m₁.isNoncomputable == m₂.isNoncomputable do throwError "cannot mix computable and non-computable definitions" unless m₁.isPartial == m₂.isPartial do throwError "cannot mix partial and non-partial definitions" private def checkKinds (k₁ k₂ : DefKind) : TermElabM Unit := do unless k₁.isExample == k₂.isExample do throwError "cannot mix examples and definitions" -- Reason: we should discard examples unless k₁.isTheorem == k₂.isTheorem do throwError "cannot mix theorems and definitions" -- Reason: we will eventually elaborate theorems in `Task`s. private def check (prevHeaders : Array DefViewElabHeader) (newHeader : DefViewElabHeader) : TermElabM Unit := do if newHeader.kind.isTheorem && newHeader.modifiers.isUnsafe then throwError "'unsafe' theorems are not allowed" if newHeader.kind.isTheorem && newHeader.modifiers.isPartial then throwError "'partial' theorems are not allowed, 'partial' is a code generation directive" if newHeader.kind.isTheorem && newHeader.modifiers.isNoncomputable then throwError "'theorem' subsumes 'noncomputable', code is not generated for theorems" if newHeader.modifiers.isNoncomputable && newHeader.modifiers.isUnsafe then throwError "'noncomputable unsafe' is not allowed" if newHeader.modifiers.isNoncomputable && newHeader.modifiers.isPartial then throwError "'noncomputable partial' is not allowed" if newHeader.modifiers.isPartial && newHeader.modifiers.isUnsafe then throwError "'unsafe' subsumes 'partial'" if h : 0 < prevHeaders.size then let firstHeader := prevHeaders.get ⟨0, h⟩ try unless newHeader.levelNames == firstHeader.levelNames do throwError "universe parameters mismatch" checkModifiers newHeader.modifiers firstHeader.modifiers checkKinds newHeader.kind firstHeader.kind catch | Exception.error ref msg => throw (Exception.error ref m!"invalid mutually recursive definitions, {msg}") | ex => throw ex else pure () private def registerFailedToInferDefTypeInfo (type : Expr) (ref : Syntax) : TermElabM Unit := registerCustomErrorIfMVar type ref "failed to infer definition type" private def elabHeaders (views : Array DefView) : TermElabM (Array DefViewElabHeader) := do let mut headers := #[] for view in views do let newHeader ← withRef view.ref do let ⟨shortDeclName, declName, levelNames⟩ ← expandDeclId (← getCurrNamespace) (← getLevelNames) view.declId view.modifiers addDeclarationRanges declName view.ref applyAttributesAt declName view.modifiers.attrs AttributeApplicationTime.beforeElaboration withDeclName declName <| withAutoBoundImplicit <| withLevelNames levelNames <| elabBinders view.binders.getArgs fun xs => do let refForElabFunType := view.value let type ← match view.type? with | some typeStx => let type ← elabType typeStx registerFailedToInferDefTypeInfo type typeStx pure type | none => let hole := mkHole refForElabFunType let type ← elabType hole registerFailedToInferDefTypeInfo type refForElabFunType pure type Term.synthesizeSyntheticMVarsNoPostponing let type ← mkForallFVars xs type let type ← mkForallFVars (← read).autoBoundImplicits.toArray type let type ← instantiateMVars type let xs ← addAutoBoundImplicits xs let levelNames ← getLevelNames if view.type?.isSome then let pendingMVarIds ← getMVars type discard <| logUnassignedUsingErrorInfos pendingMVarIds <| m!"\nwhen the resulting type of a declaration is explicitly provided, all holes (e.g., `_`) in the header are resolved before the declaration body is processed" let newHeader := { ref := view.ref, modifiers := view.modifiers, kind := view.kind, shortDeclName := shortDeclName, declName := declName, levelNames := levelNames, numParams := xs.size, type := type, valueStx := view.value : DefViewElabHeader } check headers newHeader pure newHeader headers := headers.push newHeader pure headers private partial def withFunLocalDecls {α} (headers : Array DefViewElabHeader) (k : Array Expr → TermElabM α) : TermElabM α := let rec loop (i : Nat) (fvars : Array Expr) := do if h : i < headers.size then let header := headers.get ⟨i, h⟩ if header.modifiers.isNonrec then loop (i+1) fvars else withLocalDecl header.shortDeclName BinderInfo.auxDecl header.type fun fvar => loop (i+1) (fvars.push fvar) else k fvars loop 0 #[] private def expandWhereDeclsAsStructInst : Macro | `(whereDecls|where $[$decls:letRecDecl$[;]?]*) => do let letIdDecls ← decls.mapM fun stx => match stx with | `(letRecDecl|$attrs:attributes $decl:letDecl) => Macro.throwErrorAt stx "attributes are 'where' elements are currently not supported here" | `(letRecDecl|$decl:letPatDecl) => Macro.throwErrorAt stx "patterns are not allowed here" | `(letRecDecl|$decl:letEqnsDecl) => expandLetEqnsDecl decl | `(letRecDecl|$decl:letIdDecl) => pure decl | _ => Macro.throwUnsupported let structInstFields ← letIdDecls.mapM fun | stx@`(letIdDecl|$id:ident $[$binders]* $[: $ty?]? := $val) => withRef stx do let mut val := val if let some ty := ty? then val ← `(($val : $ty)) val ← if binders.size > 0 then `(fun $[$binders]* => $val:term) else val `(structInstField|$id:ident := $val) | _ => Macro.throwUnsupported `({ $[$structInstFields,]* }) | _ => Macro.throwUnsupported /- Recall that ``` def declValSimple := leading_parser " :=\n" >> termParser >> optional Term.whereDecls def declValEqns := leading_parser Term.matchAltsWhereDecls def declVal := declValSimple <|> declValEqns <|> Term.whereDecls ``` -/ private def declValToTerm (declVal : Syntax) : MacroM Syntax := withRef declVal do if declVal.isOfKind `Lean.Parser.Command.declValSimple then expandWhereDeclsOpt declVal[2] declVal[1] else if declVal.isOfKind `Lean.Parser.Command.declValEqns then expandMatchAltsWhereDecls declVal[0] else if declVal.isOfKind `Lean.Parser.Term.whereDecls then expandWhereDeclsAsStructInst declVal else if declVal.isMissing then Macro.throwErrorAt declVal "declaration body is missing" else Macro.throwErrorAt declVal "unexpected declaration body" private def elabFunValues (headers : Array DefViewElabHeader) : TermElabM (Array Expr) := headers.mapM fun header => withDeclName header.declName $ withLevelNames header.levelNames do let valStx ← liftMacroM $ declValToTerm header.valueStx forallBoundedTelescope header.type header.numParams fun xs type => do let val ← elabTermEnsuringType valStx type mkLambdaFVars xs val private def collectUsed (headers : Array DefViewElabHeader) (values : Array Expr) (toLift : List LetRecToLift) : StateRefT CollectFVars.State MetaM Unit := do headers.forM fun header => collectUsedFVars header.type values.forM collectUsedFVars toLift.forM fun letRecToLift => do collectUsedFVars letRecToLift.type collectUsedFVars letRecToLift.val private def removeUnusedVars (vars : Array Expr) (headers : Array DefViewElabHeader) (values : Array Expr) (toLift : List LetRecToLift) : TermElabM (LocalContext × LocalInstances × Array Expr) := do let (_, used) ← (collectUsed headers values toLift).run {} removeUnused vars used private def withUsed {α} (vars : Array Expr) (headers : Array DefViewElabHeader) (values : Array Expr) (toLift : List LetRecToLift) (k : Array Expr → TermElabM α) : TermElabM α := do let (lctx, localInsts, vars) ← removeUnusedVars vars headers values toLift withLCtx lctx localInsts $ k vars private def isExample (views : Array DefView) : Bool := views.any (·.kind.isExample) private def isTheorem (views : Array DefView) : Bool := views.any (·.kind.isTheorem) private def instantiateMVarsAtHeader (header : DefViewElabHeader) : TermElabM DefViewElabHeader := do let type ← instantiateMVars header.type pure { header with type := type } private def instantiateMVarsAtLetRecToLift (toLift : LetRecToLift) : TermElabM LetRecToLift := do let type ← instantiateMVars toLift.type let val ← instantiateMVars toLift.val pure { toLift with type := type, val := val } private def typeHasRecFun (type : Expr) (funFVars : Array Expr) (letRecsToLift : List LetRecToLift) : Option FVarId := let occ? := type.find? fun e => match e with | Expr.fvar fvarId _ => funFVars.contains e || letRecsToLift.any fun toLift => toLift.fvarId == fvarId | _ => false match occ? with | some (Expr.fvar fvarId _) => some fvarId | _ => none private def getFunName (fvarId : FVarId) (letRecsToLift : List LetRecToLift) : TermElabM Name := do match (← findLocalDecl? fvarId) with | some decl => pure decl.userName | none => /- Recall that the FVarId of nested let-recs are not in the current local context. -/ match letRecsToLift.findSome? fun toLift => if toLift.fvarId == fvarId then some toLift.shortDeclName else none with | none => throwError "unknown function" | some n => pure n /- Ensures that the of let-rec definition types do not contain functions being defined. In principle, this test can be improved. We could perform it after we separate the set of functions is strongly connected components. However, this extra complication doesn't seem worth it. -/ private def checkLetRecsToLiftTypes (funVars : Array Expr) (letRecsToLift : List LetRecToLift) : TermElabM Unit := letRecsToLift.forM fun toLift => match typeHasRecFun toLift.type funVars letRecsToLift with | none => pure () | some fvarId => do let fnName ← getFunName fvarId letRecsToLift throwErrorAt toLift.ref "invalid type in 'let rec', it uses '{fnName}' which is being defined simultaneously" namespace MutualClosure /- A mapping from FVarId to Set of FVarIds. -/ abbrev UsedFVarsMap := NameMap NameSet /- Create the `UsedFVarsMap` mapping that takes the variable id for the mutually recursive functions being defined to the set of free variables in its definition. For `mainFVars`, this is just the set of section variables `sectionVars` used. For nested let-rec functions, we collect their free variables. Recall that a `let rec` expressions are encoded as follows in the elaborator. ```lean let rec f : A := t, g : B := s; body ``` is encoded as ```lean let f : A := ?m₁; let g : B := ?m₂; body ``` where `?m₁` and `?m₂` are synthetic opaque metavariables. That are assigned by this module. We may have nested `let rec`s. ```lean let rec f : A := let rec g : B := t; s; body ``` is encoded as ```lean let f : A := ?m₁; body ``` and the body of `f` is stored the field `val` of a `LetRecToLift`. For the example above, we would have a `LetRecToLift` containing: ``` { mvarId := m₁, val := `(let g : B := ?m₂; body) ... } ``` Note that `g` is not a free variable at `(let g : B := ?m₂; body)`. We recover the fact that `f` depends on `g` because it contains `m₂` -/ private def mkInitialUsedFVarsMap (mctx : MetavarContext) (sectionVars : Array Expr) (mainFVarIds : Array FVarId) (letRecsToLift : List LetRecToLift) : UsedFVarsMap := do let mut sectionVarSet := {} for var in sectionVars do sectionVarSet := sectionVarSet.insert var.fvarId! let mut usedFVarMap := {} for mainFVarId in mainFVarIds do usedFVarMap := usedFVarMap.insert mainFVarId sectionVarSet for toLift in letRecsToLift do let state := Lean.collectFVars {} toLift.val let state := Lean.collectFVars state toLift.type let mut set := state.fvarSet /- toLift.val may contain metavariables that are placeholders for nested let-recs. We should collect the fvarId for the associated let-rec because we need this information to compute the fixpoint later. -/ let mvarIds := (toLift.val.collectMVars {}).result for mvarId in mvarIds do match letRecsToLift.findSome? fun (toLift : LetRecToLift) => if toLift.mvarId == mctx.getDelayedRoot mvarId then some toLift.fvarId else none with | some fvarId => set := set.insert fvarId | none => pure () usedFVarMap := usedFVarMap.insert toLift.fvarId set pure usedFVarMap /- The let-recs may invoke each other. Example: ``` let rec f (x : Nat) := g x + y g : Nat → Nat | 0 => 1 | x+1 => f x + z ``` `y` is free variable in `f`, and `z` is a free variable in `g`. To close `f` and `g`, `y` and `z` must be in the closure of both. That is, we need to generate the top-level definitions. ``` def f (y z x : Nat) := g y z x + y def g (y z : Nat) : Nat → Nat | 0 => 1 | x+1 => f y z x + z ``` -/ namespace FixPoint structure State where usedFVarsMap : UsedFVarsMap := {} modified : Bool := false abbrev M := ReaderT (List FVarId) $ StateM State private def isModified : M Bool := do pure (← get).modified private def resetModified : M Unit := modify fun s => { s with modified := false } private def markModified : M Unit := modify fun s => { s with modified := true } private def getUsedFVarsMap : M UsedFVarsMap := do pure (← get).usedFVarsMap private def modifyUsedFVars (f : UsedFVarsMap → UsedFVarsMap) : M Unit := modify fun s => { s with usedFVarsMap := f s.usedFVarsMap } -- merge s₂ into s₁ private def merge (s₁ s₂ : NameSet) : M NameSet := s₂.foldM (init := s₁) fun s₁ k => do if s₁.contains k then pure s₁ else markModified pure $ s₁.insert k private def updateUsedVarsOf (fvarId : FVarId) : M Unit := do let usedFVarsMap ← getUsedFVarsMap match usedFVarsMap.find? fvarId with | none => pure () | some fvarIds => let fvarIdsNew ← fvarIds.foldM (init := fvarIds) fun fvarIdsNew fvarId' => if fvarId == fvarId' then pure fvarIdsNew else match usedFVarsMap.find? fvarId' with | none => pure fvarIdsNew /- We are being sloppy here `otherFVarIds` may contain free variables that are not in the context of the let-rec associated with fvarId. We filter these out-of-context free variables later. -/ | some otherFVarIds => merge fvarIdsNew otherFVarIds modifyUsedFVars fun usedFVars => usedFVars.insert fvarId fvarIdsNew private partial def fixpoint : Unit → M Unit | _ => do resetModified let letRecFVarIds ← read letRecFVarIds.forM updateUsedVarsOf if (← isModified) then fixpoint () def run (letRecFVarIds : List FVarId) (usedFVarsMap : UsedFVarsMap) : UsedFVarsMap := let (_, s) := ((fixpoint ()).run letRecFVarIds).run { usedFVarsMap := usedFVarsMap } s.usedFVarsMap end FixPoint abbrev FreeVarMap := NameMap (Array FVarId) private def mkFreeVarMap (mctx : MetavarContext) (sectionVars : Array Expr) (mainFVarIds : Array FVarId) (recFVarIds : Array FVarId) (letRecsToLift : List LetRecToLift) : FreeVarMap := do let usedFVarsMap := mkInitialUsedFVarsMap mctx sectionVars mainFVarIds letRecsToLift let letRecFVarIds := letRecsToLift.map fun toLift => toLift.fvarId let usedFVarsMap := FixPoint.run letRecFVarIds usedFVarsMap let mut freeVarMap := {} for toLift in letRecsToLift do let lctx := toLift.lctx let fvarIdsSet := (usedFVarsMap.find? toLift.fvarId).get! let fvarIds := fvarIdsSet.fold (init := #[]) fun fvarIds fvarId => if lctx.contains fvarId && !recFVarIds.contains fvarId then fvarIds.push fvarId else fvarIds freeVarMap := freeVarMap.insert toLift.fvarId fvarIds pure freeVarMap structure ClosureState where newLocalDecls : Array LocalDecl := #[] localDecls : Array LocalDecl := #[] newLetDecls : Array LocalDecl := #[] exprArgs : Array Expr := #[] private def pickMaxFVar? (lctx : LocalContext) (fvarIds : Array FVarId) : Option FVarId := fvarIds.getMax? fun fvarId₁ fvarId₂ => (lctx.get! fvarId₁).index < (lctx.get! fvarId₂).index private def preprocess (e : Expr) : TermElabM Expr := do let e ← instantiateMVars e -- which let-decls are dependent. We say a let-decl is dependent if its lambda abstraction is type incorrect. Meta.check e pure e /- Push free variables in `s` to `toProcess` if they are not already there. -/ private def pushNewVars (toProcess : Array FVarId) (s : CollectFVars.State) : Array FVarId := s.fvarSet.fold (init := toProcess) fun toProcess fvarId => if toProcess.contains fvarId then toProcess else toProcess.push fvarId private def pushLocalDecl (toProcess : Array FVarId) (fvarId : FVarId) (userName : Name) (type : Expr) (bi := BinderInfo.default) : StateRefT ClosureState TermElabM (Array FVarId) := do let type ← preprocess type modify fun s => { s with newLocalDecls := s.newLocalDecls.push $ LocalDecl.cdecl arbitrary fvarId userName type bi, exprArgs := s.exprArgs.push (mkFVar fvarId) } pure $ pushNewVars toProcess (collectFVars {} type) private partial def mkClosureForAux (toProcess : Array FVarId) : StateRefT ClosureState TermElabM Unit := do let lctx ← getLCtx match pickMaxFVar? lctx toProcess with | none => pure () | some fvarId => trace[Elab.definition.mkClosure] "toProcess: {toProcess.map mkFVar}, maxVar: {mkFVar fvarId}" let toProcess := toProcess.erase fvarId let localDecl ← getLocalDecl fvarId match localDecl with | LocalDecl.cdecl _ _ userName type bi => let toProcess ← pushLocalDecl toProcess fvarId userName type bi mkClosureForAux toProcess | LocalDecl.ldecl _ _ userName type val _ => let zetaFVarIds ← getZetaFVarIds if !zetaFVarIds.contains fvarId then /- Non-dependent let-decl. See comment at src/Lean/Meta/Closure.lean -/ let toProcess ← pushLocalDecl toProcess fvarId userName type mkClosureForAux toProcess else /- Dependent let-decl. -/ let type ← preprocess type let val ← preprocess val modify fun s => { s with newLetDecls := s.newLetDecls.push $ LocalDecl.ldecl arbitrary fvarId userName type val false, /- We don't want to interleave let and lambda declarations in our closure. So, we expand any occurrences of fvarId at `newLocalDecls` and `localDecls` -/ newLocalDecls := s.newLocalDecls.map (replaceFVarIdAtLocalDecl fvarId val), localDecls := s.localDecls.map (replaceFVarIdAtLocalDecl fvarId val) } mkClosureForAux (pushNewVars toProcess (collectFVars (collectFVars {} type) val)) private partial def mkClosureFor (freeVars : Array FVarId) (localDecls : Array LocalDecl) : TermElabM ClosureState := do let (_, s) ← (mkClosureForAux freeVars).run { localDecls := localDecls } pure { s with newLocalDecls := s.newLocalDecls.reverse, newLetDecls := s.newLetDecls.reverse, exprArgs := s.exprArgs.reverse } structure LetRecClosure where ref : Syntax localDecls : Array LocalDecl closed : Expr -- expression used to replace occurrences of the let-rec FVarId toLift : LetRecToLift private def mkLetRecClosureFor (toLift : LetRecToLift) (freeVars : Array FVarId) : TermElabM LetRecClosure := do let lctx := toLift.lctx withLCtx lctx toLift.localInstances do lambdaTelescope toLift.val fun xs val => do let type ← instantiateForall toLift.type xs let lctx ← getLCtx let s ← mkClosureFor freeVars $ xs.map fun x => lctx.get! x.fvarId! let type := Closure.mkForall s.localDecls $ Closure.mkForall s.newLetDecls type let val := Closure.mkLambda s.localDecls $ Closure.mkLambda s.newLetDecls val let c := mkAppN (Lean.mkConst toLift.declName) s.exprArgs assignExprMVar toLift.mvarId c return { ref := toLift.ref localDecls := s.newLocalDecls closed := c toLift := { toLift with val := val, type := type } } private def mkLetRecClosures (letRecsToLift : List LetRecToLift) (freeVarMap : FreeVarMap) : TermElabM (List LetRecClosure) := letRecsToLift.mapM fun toLift => mkLetRecClosureFor toLift (freeVarMap.find? toLift.fvarId).get! /- Mapping from FVarId of mutually recursive functions being defined to "closure" expression. -/ abbrev Replacement := NameMap Expr def insertReplacementForMainFns (r : Replacement) (sectionVars : Array Expr) (mainHeaders : Array DefViewElabHeader) (mainFVars : Array Expr) : Replacement := mainFVars.size.fold (init := r) fun i r => r.insert mainFVars[i].fvarId! (mkAppN (Lean.mkConst mainHeaders[i].declName) sectionVars) def insertReplacementForLetRecs (r : Replacement) (letRecClosures : List LetRecClosure) : Replacement := letRecClosures.foldl (init := r) fun r c => r.insert c.toLift.fvarId c.closed def Replacement.apply (r : Replacement) (e : Expr) : Expr := e.replace fun e => match e with | Expr.fvar fvarId _ => match r.find? fvarId with | some c => some c | _ => none | _ => none def pushMain (preDefs : Array PreDefinition) (sectionVars : Array Expr) (mainHeaders : Array DefViewElabHeader) (mainVals : Array Expr) : TermElabM (Array PreDefinition) := mainHeaders.size.foldM (init := preDefs) fun i preDefs => do let header := mainHeaders[i] let val ← mkLambdaFVars sectionVars mainVals[i] let type ← mkForallFVars sectionVars header.type return preDefs.push { ref := getDeclarationSelectionRef header.ref kind := header.kind declName := header.declName levelParams := [], -- we set it later modifiers := header.modifiers type := type value := val } def pushLetRecs (preDefs : Array PreDefinition) (letRecClosures : List LetRecClosure) (kind : DefKind) (modifiers : Modifiers) : Array PreDefinition := letRecClosures.foldl (init := preDefs) fun preDefs c => let type := Closure.mkForall c.localDecls c.toLift.type let val := Closure.mkLambda c.localDecls c.toLift.val preDefs.push { ref := c.ref kind := kind declName := c.toLift.declName levelParams := [] -- we set it later modifiers := { modifiers with attrs := c.toLift.attrs } type := type value := val } def getKindForLetRecs (mainHeaders : Array DefViewElabHeader) : DefKind := if mainHeaders.any fun h => h.kind.isTheorem then DefKind.«theorem» else DefKind.«def» def getModifiersForLetRecs (mainHeaders : Array DefViewElabHeader) : Modifiers := { isNoncomputable := mainHeaders.any fun h => h.modifiers.isNoncomputable recKind := if mainHeaders.any fun h => h.modifiers.isPartial then RecKind.partial else RecKind.default isUnsafe := mainHeaders.any fun h => h.modifiers.isUnsafe } /- - `sectionVars`: The section variables used in the `mutual` block. - `mainHeaders`: The elaborated header of the top-level definitions being defined by the mutual block. - `mainFVars`: The auxiliary variables used to represent the top-level definitions being defined by the mutual block. - `mainVals`: The elaborated value for the top-level definitions - `letRecsToLift`: The let-rec's definitions that need to be lifted -/ def main (sectionVars : Array Expr) (mainHeaders : Array DefViewElabHeader) (mainFVars : Array Expr) (mainVals : Array Expr) (letRecsToLift : List LetRecToLift) : TermElabM (Array PreDefinition) := do -- Store in recFVarIds the fvarId of every function being defined by the mutual block. let mainFVarIds := mainFVars.map Expr.fvarId! let recFVarIds := (letRecsToLift.toArray.map fun toLift => toLift.fvarId) ++ mainFVarIds -- Compute the set of free variables (excluding `recFVarIds`) for each let-rec. let mctx ← getMCtx let freeVarMap := mkFreeVarMap mctx sectionVars mainFVarIds recFVarIds letRecsToLift resetZetaFVarIds withTrackingZeta do -- By checking `toLift.type` and `toLift.val` we populate `zetaFVarIds`. See comments at `src/Lean/Meta/Closure.lean`. letRecsToLift.forM fun toLift => withLCtx toLift.lctx toLift.localInstances do Meta.check toLift.type; Meta.check toLift.val let letRecClosures ← mkLetRecClosures letRecsToLift freeVarMap -- mkLetRecClosures assign metavariables that were placeholders for the lifted declarations. let mainVals ← mainVals.mapM (instantiateMVars ·) let mainHeaders ← mainHeaders.mapM instantiateMVarsAtHeader let letRecClosures ← letRecClosures.mapM fun closure => do pure { closure with toLift := (← instantiateMVarsAtLetRecToLift closure.toLift) } -- Replace fvarIds for functions being defined with closed terms let r := insertReplacementForMainFns {} sectionVars mainHeaders mainFVars let r := insertReplacementForLetRecs r letRecClosures let mainVals := mainVals.map r.apply let mainHeaders := mainHeaders.map fun h => { h with type := r.apply h.type } let letRecClosures := letRecClosures.map fun c => { c with toLift := { c.toLift with type := r.apply c.toLift.type, val := r.apply c.toLift.val } } let letRecKind := getKindForLetRecs mainHeaders let letRecMods := getModifiersForLetRecs mainHeaders pushMain (pushLetRecs #[] letRecClosures letRecKind letRecMods) sectionVars mainHeaders mainVals end MutualClosure private def getAllUserLevelNames (headers : Array DefViewElabHeader) : List Name := if h : 0 < headers.size then -- Recall that all top-level functions must have the same levels. See `check` method above (headers.get ⟨0, h⟩).levelNames else [] /-- Eagerly convert universe metavariables occurring in theorem headers to universe parameters. -/ private def levelMVarToParamHeaders (views : Array DefView) (headers : Array DefViewElabHeader) : TermElabM (Array DefViewElabHeader) := do let rec process : StateRefT Nat TermElabM (Array DefViewElabHeader) := do let mut newHeaders := #[] for view in views, header in headers do if view.kind.isTheorem then newHeaders := newHeaders.push { header with type := (← levelMVarToParam' header.type) } else newHeaders := newHeaders.push header return newHeaders let newHeaders ← process.run' 1 newHeaders.mapM fun header => return { header with type := (← instantiateMVars header.type) } def elabMutualDef (vars : Array Expr) (views : Array DefView) : TermElabM Unit := if isExample views then withoutModifyingEnv go else go where go := do let scopeLevelNames ← getLevelNames let headers ← elabHeaders views let headers ← levelMVarToParamHeaders views headers let allUserLevelNames := getAllUserLevelNames headers withFunLocalDecls headers fun funFVars => do let values ← elabFunValues headers Term.synthesizeSyntheticMVarsNoPostponing let values ← values.mapM (instantiateMVars ·) let headers ← headers.mapM instantiateMVarsAtHeader let letRecsToLift ← getLetRecsToLift let letRecsToLift ← letRecsToLift.mapM instantiateMVarsAtLetRecToLift checkLetRecsToLiftTypes funFVars letRecsToLift withUsed vars headers values letRecsToLift fun vars => do let preDefs ← MutualClosure.main vars headers funFVars values letRecsToLift let preDefs ← levelMVarToParamPreDecls preDefs let preDefs ← instantiateMVarsAtPreDecls preDefs let preDefs ← fixLevelParams preDefs scopeLevelNames allUserLevelNames addPreDefinitions preDefs end Term namespace Command def elabMutualDef (ds : Array Syntax) : CommandElabM Unit := do let views ← ds.mapM fun d => do let modifiers ← elabModifiers d[0] if ds.size > 1 && modifiers.isNonrec then throwErrorAt d "invalid use of 'nonrec' modifier in 'mutual' block" mkDefView modifiers d[1] runTermElabM none fun vars => Term.elabMutualDef vars views end Command end Lean.Elab
7fa4ad32550dd10ee7d994ebb8a8e6cb9bd868b6
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/category/bitraversable/instances.lean
d41415e73f3011192e9e05b733f557bffcf7e8b6
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
3,995
lean
import category.bitraversable.basic category.bitraversable.lemmas category.traversable.lemmas tactic.interactive universes u v w variables {t : Type u → Type u → Type u} [bitraversable t] section variables {F : Type u → Type u} [applicative F] def prod.bitraverse {α α' β β'} (f : α → F α') (f' : β → F β') : α × β → F (α' × β') | (x,y) := prod.mk <$> f x <*> f' y instance : bitraversable prod := { bitraverse := @prod.bitraverse } instance : is_lawful_bitraversable prod := by constructor; introsI; cases x; simp [bitraverse,prod.bitraverse] with functor_norm; refl open functor def sum.bitraverse {α α' β β'} (f : α → F α') (f' : β → F β') : α ⊕ β → F (α' ⊕ β') | (sum.inl x) := sum.inl <$> f x | (sum.inr x) := sum.inr <$> f' x instance : bitraversable sum := { bitraverse := @sum.bitraverse } instance : is_lawful_bitraversable sum := by constructor; introsI; cases x; simp [bitraverse,sum.bitraverse] with functor_norm; refl def const.bitraverse {α α' β β'} (f : α → F α') (f' : β → F β') : const α β → F (const α' β') := f instance bitraversable.const : bitraversable const := { bitraverse := @const.bitraverse } instance is_lawful_bitraversable.const : is_lawful_bitraversable const := by constructor; introsI; simp [bitraverse,const.bitraverse] with functor_norm; refl def flip.bitraverse {α α' β β'} (f : α → F α') (f' : β → F β') : flip t α β → F (flip t α' β') := (bitraverse f' f : t β α → F (t β' α')) instance bitraversable.flip : bitraversable (flip t) := { bitraverse := @flip.bitraverse t _ } variables [is_lawful_bitraversable t] open is_lawful_bitraversable instance is_lawful_bitraversable.flip : is_lawful_bitraversable (flip t) := by constructor; introsI; casesm is_lawful_bitraversable t; apply_assumption open bitraversable functor @[priority 0] instance bitraversable.traversable {α} : traversable (t α) := { traverse := @tsnd t _ _ } open is_lawful_traversable @[priority 0] instance bitraversable.is_lawful_traversable [is_lawful_bitraversable t] {α} : is_lawful_traversable (t α) := by { constructor; introsI; simp [traverse,comp_tsnd] with functor_norm, { refl }, { simp [tsnd_eq_snd_id], refl }, { simp [tsnd,binaturality,function.comp] with functor_norm } } end open bifunctor traversable is_lawful_traversable is_lawful_bitraversable section bicompl variables (F G : Type u → Type u) [traversable F] [traversable G] def bicompl.bitraverse {m} [applicative m] {α β α' β'} (f : α → m β) (f' : α' → m β') : bicompl t F G α α' → m (bicompl t F G β β') := (bitraverse (traverse f) (traverse f') : t (F α) (G α') → m _) instance : bitraversable (bicompl t F G) := { bitraverse := @bicompl.bitraverse t _ F G _ _ } instance [is_lawful_traversable F] [is_lawful_traversable G] [is_lawful_bitraversable t] : is_lawful_bitraversable (bicompl t F G) := begin constructor; introsI; simp [bitraverse,bicompl.bitraverse,bimap,traverse_id,bitraverse_id_id,comp_bitraverse] with functor_norm, { simp [traverse_eq_map_id',bitraverse_eq_bimap_id], }, { revert x, dunfold bicompl, simp [binaturality,naturality_pf] } end end bicompl section bicompr variables (F : Type u → Type u) [traversable F] def bicompr.bitraverse {m} [applicative m] {α β α' β'} (f : α → m β) (f' : α' → m β') : bicompr F t α α' → m (bicompr F t β β') := (traverse (bitraverse f f') : F (t α α') → m _) instance : bitraversable (bicompr F t) := { bitraverse := @bicompr.bitraverse t _ F _ } instance [is_lawful_traversable F] [is_lawful_bitraversable t] : is_lawful_bitraversable (bicompr F t) := begin constructor; introsI; simp [bitraverse,bicompr.bitraverse,bitraverse_id_id] with functor_norm, { simp [bitraverse_eq_bimap_id',traverse_eq_map_id'], refl }, { revert x, dunfold bicompr, intro, simp [naturality,binaturality'] } end end bicompr
df5fd850629070401932946aff8c4f7e9436f6b6
75c54c8946bb4203e0aaf196f918424a17b0de99
/src/forcing_CH.lean
54e805973c5f4e1d3f1ea584e004b04ffd8dba87
[ "Apache-2.0" ]
permissive
urkud/flypitch
261e2a45f1038130178575406df8aea78255ba77
2250f5eda14b6ef9fc3e4e1f4a9ac4005634de5c
refs/heads/master
1,653,266,469,246
1,577,819,679,000
1,577,819,679,000
259,862,235
1
0
Apache-2.0
1,588,147,244,000
1,588,147,244,000
null
UTF-8
Lean
false
false
31,443
lean
import .collapse .aleph_one /- Forcing the continuum hypothesis. -/ universe u open lattice bSet topological_space pSet cardinal local infix ` ⟹ `:65 := lattice.imp local infix ` ⇔ `:50 := lattice.biimp local infix `≺`:75 := (λ x y, -(bSet.larger_than x y)) local infix `≼`:75 := (λ x y, bSet.injects_into x y) @[reducible]private noncomputable definition ℵ₁ : pSet := (card_ex $ aleph 1) local notation `ω` := (bSet.omega) local attribute [instance, priority 0] classical.prop_decidable namespace bSet section aleph_one variables {𝔹 : Type*} [nontrivial_complete_boolean_algebra 𝔹] noncomputable def aleph_one : bSet 𝔹 := a1 lemma aleph_one_satisfies_spec {Γ : 𝔹} : Γ ≤ aleph_one_Ord_spec (aleph_one) := a1_spec lemma aleph_one_check_sub_aleph_one {Γ : 𝔹} : Γ ≤ (pSet.card_ex (aleph 1))̌ ⊆ᴮ aleph_one := aleph_one_check_sub_aleph_one_aux a1_Ord a1_spec lemma aleph_one_le_of_omega_lt {Γ : 𝔹} : Γ ≤ le_of_omega_lt (aleph_one) := a1_le_of_omega_lt end aleph_one section lemmas variables {𝔹 : Type u} [nontrivial_complete_boolean_algebra 𝔹] /-- Corresponds to proposition 5.2 in Moore's 'the method of forcing': Let x be a set and let ϕ(v) be a formula in the forcing language. If ∀ y ∈ x, p ⊩ ϕ(y̌), then p ⊩ ∀ y ∈ (x̌), ϕ(y) -/ lemma check_forall (x : pSet.{u}) (ϕ : bSet 𝔹 → 𝔹) {b : 𝔹} : (∀ (y : x.type), b ≤ ϕ((x.func y)̌ )) → (b ≤ (⨅(y : x.type), ϕ((x.func y)̌ ))) := λ H, le_infi ‹_› lemma aleph_one_check_is_aleph_one_of_omega_lt {Γ : 𝔹} (H : Γ ≤ bSet.omega ≺ (ℵ₁)̌ ): Γ ≤ (ℵ₁̌ ) =ᴮ (aleph_one) := begin refine subset_ext aleph_one_check_sub_aleph_one _, have := @bSet.aleph_one_satisfies_spec _ _ Γ, unfold aleph_one_Ord_spec at this, bv_split, bv_split_at this_right, refine this_right_right (ℵ₁ ̌) (by simp) _, dsimp at H, rw ←imp_bot at ⊢ H, bv_imp_intro H', refine H (larger_than_of_surjects_onto $ surjects_onto_of_injects_into ‹_› $ by simp), end theorem CH_true_aux (H_aleph_one : ∀{Γ : 𝔹}, Γ ≤ le_of_omega_lt (ℵ₁̌ )) (H_not_lt : ∀{Γ : 𝔹}, Γ ≤ - ((ℵ₁)̌ ≺ 𝒫(ω))) : ∀{Γ : 𝔹}, Γ ≤ CH := begin intro Γ, unfold CH, rw ←imp_bot, bv_imp_intro H_CH, suffices H_aleph_lt_continuum : Γ_1 ≤ (ℵ₁)̌ ≺ 𝒫(ω), by {refine bv_absurd _ ‹Γ_1 ≤ (ℵ₁)̌ ≺ 𝒫(ω)› (by solve_by_elim) }, bv_cases_at H_CH x Hx, bv_split_at Hx, bv_cases_at Hx_right y Hy, bv_split_at Hy, bv_split_at Hy_left, refine bSet_lt_of_lt_of_le _ Hy_right, refine bSet_lt_of_le_of_lt _ Hy_left_right, refine @H_aleph_one Γ_3 x Hx_left Hy_left_left end def rel_of_array (x y : bSet 𝔹) (af : x.type → y.type → 𝔹) : bSet 𝔹 := set_of_indicator (λ pr, (af pr.1 pr.2) : (prod x y).type → 𝔹) lemma rel_of_array_surj (x y : bSet 𝔹) (af : x.type → y.type → 𝔹) (H_bval₁ : ∀ i, x.bval i = ⊤) (H_bval₂ : ∀ i, y.bval i = ⊤) (H_wide : ∀ j, (⨆ i, af i j) = ⊤) {Γ} : Γ ≤ (is_surj x y (rel_of_array x y af)) := begin bv_intro z, bv_imp_intro Hz, rw[<-@bounded_exists 𝔹 _ x _ _], simp [H_bval₁], { rw[bSet.mem_unfold] at Hz, bv_cases_at Hz i, simp[H_bval₂] at Hz_1, apply bv_rw' Hz_1, { apply B_ext_supr, intro i, from @B_ext_pair_right 𝔹 _ (λ z, z ∈ᴮ rel_of_array x y af) (by simp) _}, { rw[rel_of_array], simp, erw[supr_comm], transitivity ⨆ (j : type x), af j i ⊓ pair (func x j) (func y i) =ᴮ pair (func x j) (func y i), conv {congr, skip, congr, funext, rw[bv_eq_refl _]}, simp[H_wide], clear_except, tidy_context, bv_cases_at a j, refine bv_use (j,i), refine bv_use j, from ‹_›}}, { change B_ext _, from B_ext_term _ _ (B_ext_mem_left) (by simp) } end lemma mem_left_of_mem_rel_of_array {x y w₁ w₂ : bSet 𝔹} {af : x.type → y.type → 𝔹} {Γ} (H_mem_left : Γ ≤ pair w₁ w₂ ∈ᴮ rel_of_array x y af) (H_bval₁ : ∀ i, x.bval i = ⊤) : Γ ≤ w₁ ∈ᴮ x := begin unfold rel_of_array at H_mem_left, dsimp at H_mem_left, bv_cases_at H_mem_left p, cases p with i j, dsimp at H_mem_left_1, bv_split_at H_mem_left_1, have := eq_of_eq_pair_left' ‹_›, apply bv_rw' this, simp, from mem.mk'' (by simp only [H_bval₁ _, le_top]) end lemma mem_right_of_mem_rel_of_array {x y w₁ w₂ : bSet 𝔹} {af : x.type → y.type → 𝔹} {Γ} (H_mem_right : Γ ≤ pair w₁ w₂ ∈ᴮ rel_of_array x y af) (H_bval₂ : ∀ i, y.bval i = ⊤) : Γ ≤ w₂ ∈ᴮ y := begin unfold rel_of_array at H_mem_right, dsimp at H_mem_right, bv_cases_at H_mem_right p, cases p with i j, dsimp at H_mem_right_1, bv_split_at H_mem_right_1, have := eq_of_eq_pair_right' ‹_›, apply bv_rw' this, simp, apply mem.mk'', simp only [H_bval₂ _, le_top] end local attribute [instance] classical.prop_decidable lemma rel_of_array_extensional (x y : bSet 𝔹) (af : x.type → y.type → 𝔹) (H_anti : ∀ i, (∀ j₁ j₂, j₁ ≠ j₂ → af i j₁ ⊓ af i j₂ ≤ ⊥)) (H_inj : ∀ i₁ i₂, ⊥ < (func x i₁) =ᴮ (func x i₂) → i₁ = i₂) {Γ} : Γ ≤ (is_func (rel_of_array x y af)) := begin bv_intro w₁, bv_intro v₁, bv_intro w₂, bv_intro v₂, bv_imp_intro H_mem, bv_split, bv_imp_intro H_eq, have this : Γ_2 ≤ pair w₁ v₂ ∈ᴮ rel_of_array x y af, by {apply bv_rw' H_eq, { exact B_ext_term _ _ (B_ext_mem_left) (by simp) }, { from ‹_› }}, clear_except H_mem_left this H_anti H_inj H_eq, dsimp[rel_of_array] at H_mem_left this, bv_cases_at H_mem_left p₁, cases p₁ with i₁ j₁, suffices : Γ_3 ≤ v₂ =ᴮ (y.func j₁), by {refine bv_trans _ (bv_symm this), bv_split, from eq_of_eq_pair_right' ‹_›}, bv_cases_at this p₂, cases p₂ with i₂ j₂, suffices : Γ_4 ≤ (y.func j₂) =ᴮ (func y j₁), by {exact bv_trans (by bv_split; from eq_of_eq_pair_right' ‹_›) (this)}, by_cases j₁ = j₂, { subst h, from bv_refl}, { bv_exfalso, by_cases i₁ = i₂, { subst h, specialize H_anti i₁ j₁ j₂ ‹_›, refine le_trans _ H_anti, bv_split, bv_split_goal}, { suffices : Γ_4 ≤ - (w₁ =ᴮ v₁), by {exact bv_absurd (w₁ =ᴮ v₁) ‹_› ‹_›}, suffices : Γ_4 ≤ w₁ =ᴮ (func x i₁) ∧ Γ_4 ≤ v₁ =ᴮ (func x i₂), by { clear_except H_inj this h, apply bv_rw' this.left, by simp, apply bv_rw' this.right, by simp, suffices H_le_bot : (func x i₁ =ᴮ func x i₂) ≤ ⊥, by {rw[<-imp_bot, <-deduction], from le_trans (by simp) H_le_bot}, suffices H_not_bot_lt : ¬ (⊥ < func x i₁ =ᴮ func x i₂), by {clear_except H_not_bot_lt, finish[bot_lt_iff_not_le_bot]}, clear_except H_inj h, intro H, from absurd (H_inj _ _ H) ‹_›}, bv_split, exact ⟨eq_of_eq_pair_left' H_mem_left_1_right, bv_trans (bv_symm H_eq) (eq_of_eq_pair_left' this_1_right)⟩}} end lemma rel_of_array_is_func' (x y : bSet 𝔹) (af : x.type → y.type → 𝔹) (H_bval₂ : ∀ i, y.bval i = ⊤) (H_tall : ∀ i, (⨆ j, af i j) = ⊤) -- this is not in the book, but I think it should be (H_anti : ∀ i, (∀ j₁ j₂, j₁ ≠ j₂ → af i j₁ ⊓ af i j₂ ≤ ⊥)) (H_inj : ∀ i₁ i₂, ⊥ < (func x i₁) =ᴮ (func x i₂) → i₁ = i₂) {Γ} : Γ ≤ is_func' x y (rel_of_array x y af) := begin refine le_inf (by apply rel_of_array_extensional; assumption) _, rw bSet.is_total, rw[<-bounded_forall], bv_intro i_x, bv_imp_intro Hi_x, rw[<-bounded_exists], { simp[*,rel_of_array, -Γ_1], erw[supr_comm, supr_prod], apply bv_use i_x, transitivity ⨆ (j : type y), af ((i_x, j).fst) ((i_x, j).snd) ⊓ pair (func x i_x) (func y j) =ᴮ pair (func x ((i_x, j).fst)) (func y ((i_x, j).snd)), { conv { to_rhs, funext, congr, funext,rw[bv_eq_refl] }, simp[H_tall]}, { exact diagonal_supr_le_supr (by refl) }}, { change B_ext _, from B_ext_term _ _ (B_ext_mem_left) (by simp) }, { change B_ext _, apply B_ext_supr, intro, apply B_ext_inf, { simp }, { from B_ext_term _ _ (B_ext_mem_left) (by simp) }} end section function_reflect variables {D : set 𝔹} (H_docs : dense_omega_closed_subset D) {y : pSet.{u}} {g : bSet 𝔹} {Γ : 𝔹} (H_nonzero : ⊥ < Γ) (H : Γ ≤ is_func' bSet.omega y̌ g) (AE : ∀ (x y : pSet) {f : bSet 𝔹} {Γ : 𝔹}, Γ ≤ is_func' x̌ y̌ f → ⊥ < Γ → ∀ (i : pSet.type x), ∃ (j : pSet.type y) (Γ' : 𝔹) (H_nonzero' : ⊥ < Γ') (H_le : Γ' ≤ Γ), Γ' ≤ is_func' x̌ y̌ f ∧ Γ' ≤ pair (pSet.func x i)̌ (pSet.func y j)̌ ∈ᴮ f ∧ Γ' ∈ D ) local notation `ae₀` := AE pSet.omega y H H_nonzero local notation `aeₖ` := AE pSet.omega y include y g Γ H_nonzero H AE noncomputable def function_reflect.fB : ℕ → Σ' (j : y.type) (B : 𝔹), (⊥ < B ∧ B ≤ is_func' bSet.omega y̌ g) | 0 := begin use classical.some (ae₀ (ulift.up 0)), use classical.some (classical.some_spec (ae₀ (ulift.up 0))), rcases classical.some_spec (classical.some_spec (ae₀ (ulift.up 0))) with ⟨_,_,_,_⟩, from ⟨‹_›,‹_›⟩ end | (k+1) := begin use classical.some ((aeₖ ((function_reflect.fB) k).2.2.2 ((function_reflect.fB) k).2.2.1 ((ulift.up $ k + 1)))), use classical.some (classical.some_spec ((aeₖ ((function_reflect.fB) k).2.2.2 ((function_reflect.fB) k).2.2.1 ((ulift.up $ k + 1))))), rcases classical.some_spec (classical.some_spec ((aeₖ ((function_reflect.fB) k).2.2.2 ((function_reflect.fB) k).2.2.1 ((ulift.up $ k + 1))))) with ⟨_,_,_,_⟩, from ⟨‹_›,‹_›⟩ end @[reducible]noncomputable def function_reflect.B : ℕ → 𝔹 := λ n, (function_reflect.fB H_nonzero H AE n).2.1 @[reducible]noncomputable def function_reflect.f : ℕ → y.type := λ n, (function_reflect.fB H_nonzero H AE n).1 lemma function_reflect.B_nonzero (n) : ⊥ < (function_reflect.B H_nonzero H AE n) := (function_reflect.fB H_nonzero H AE n).2.2.left lemma function_reflect.B_is_func' (n) : (function_reflect.B H_nonzero H AE n) ≤ is_func' bSet.omega y̌ g := (function_reflect.fB H_nonzero H AE n).2.2.right lemma function_reflect.B_unfold {n} : function_reflect.B H_nonzero H AE (n+1) = classical.some ((function_reflect.fB._main._proof_7 H_nonzero H AE n)) -- yuck := rfl lemma function_reflect.B_le {n} : (function_reflect.B H_nonzero H AE (n + 1)) ≤ function_reflect.B H_nonzero H AE n := begin rw function_reflect.B_unfold, let p := _, change classical.some p ≤ _, rcases classical.some_spec p with ⟨_,_,_,_⟩, convert h_w, clear_except, unfold function_reflect.B, cases n, refl, refl, end lemma function_reflect.B_pair {n} : (function_reflect.B H_nonzero H AE n) ≤ pair (pSet.omega.func (ulift.up n))̌ (y.func $ function_reflect.f H_nonzero H AE n)̌ ∈ᴮ g := begin cases n, { change classical.some _ ≤ _, let p := _, change classical.some p ≤ _, rcases classical.some_spec p with ⟨_,_,_,_,_⟩, from ‹_› }, { rw function_reflect.B_unfold, let p := _, change classical.some p ≤ _, rcases classical.some_spec p with ⟨_,_,_,_,_⟩, from ‹_› } end lemma function_reflect.B_mem_dense {n} : (function_reflect.B H_nonzero H AE n) ∈ D := begin cases n, { let p := _, change classical.some p ∈ _, rcases classical.some_spec p with ⟨_,_,_,_,_⟩, from ‹_› }, { rw function_reflect.B_unfold, let p := _, change classical.some p ∈ _, rcases classical.some_spec p with ⟨_,_,_,_,_⟩, from ‹_› } end variable (H_function : Γ ≤ is_function bSet.omega y̌ g) lemma function_reflect.B_infty_le_Γ : (⨅ n, (function_reflect.B H_nonzero H AE n)) ≤ Γ := begin refine infi_le_of_le 0 _, let p := _, change classical.some p ≤ _, rcases classical.some_spec p with ⟨_,_,_,_⟩, from ‹_› end lemma function_reflect_aux : (⨅n, function_reflect.B H_nonzero H AE n) ≤ (⨅n, pair (pSet.omega.func (ulift.up n))̌ (y.func $ function_reflect.f H_nonzero H AE n)̌ ∈ᴮ g) := infi_le_infi $ λ _, by apply function_reflect.B_pair noncomputable def function_reflect.f' : pSet.{u} := begin refine @pSet.function.mk pSet.omega _ _, intro k, cases k with k', exact y.func (function_reflect.f H_nonzero H AE k'), intros i j Heqv, suffices this : i = j, by { subst this }, from pSet.omega_inj ‹_› end lemma function_reflect.f'_is_function : ∀ {Γ : 𝔹}, Γ ≤ is_function (pSet.omega)̌ y̌ (function_reflect.f' H_nonzero H AE)̌ := begin refine @check_is_func 𝔹 _ pSet.omega y (function_reflect.f' H_nonzero H AE) _, apply pSet.function.mk_is_func, intro i, cases i, simp end lemma function_reflect_aux₂ : (⨅n, function_reflect.B H_nonzero H AE n) ≤ (⨅n, (pair (pSet.omega.func (ulift.up n))̌ (y.func $ function_reflect.f H_nonzero H AE n)̌ ∈ᴮ (function_reflect.f' H_nonzero H AE)̌ ⇔ (pair (pSet.omega.func (ulift.up n))̌ (y.func $ function_reflect.f H_nonzero H AE n)̌ ∈ᴮ g))) := begin refine infi_le_infi (λ n, _), tidy_context, refine ⟨_,_⟩; bv_imp_intro H_mem, { refine le_trans a _, apply function_reflect.B_pair }, { apply @bv_rw' _ _ _ _ _ (bv_symm check_pair) (λ z, z ∈ᴮ (function_reflect.f' H_nonzero H AE)̌ ), simp, refine check_mem _, convert pSet.function.mk_mem, refl } end include H_function lemma function_reflect.B_infty_le_function : (⨅ n, (function_reflect.B H_nonzero H AE n)) ≤ is_function ω y̌ g := le_trans (by apply function_reflect.B_infty_le_Γ) H_function lemma function_reflect_aux₃ : (⨅n, function_reflect.B H_nonzero H AE n) ≤ ⨅ (p : bSet 𝔹), p ∈ᴮ prod pSet.omegǎ y̌ ⟹ (p ∈ᴮ (function_reflect.f' H_nonzero H AE)̌ ⇔ p ∈ᴮ g) := begin rw ←bounded_forall, swap, {change B_ext _, simp}, bv_intro pr, rcases pr with ⟨⟨i⟩, j⟩, simp only [prod_check_bval, top_imp, prod_func], have := (function_reflect_aux₂ H_nonzero H AE) i, bv_split_at this, refine le_inf _ _; bv_imp_intro H', { have this' : Γ_1 ≤ (pair (func pSet.omegǎ {down := i}) (func y̌ j)) =ᴮ (pair (pSet.func pSet.omega {down := i})̌ (pSet.func y (function_reflect.f H_nonzero H AE i))̌ ), by {rw pair_eq_pair_iff, refine ⟨bv_refl, _⟩, refine eq_of_is_func'_of_eq (is_func'_of_is_function _) _ _ _, show _ ≤ is_function bSet.omega y̌ (function_reflect.f' H_nonzero H AE)̌ , refine check_is_func _, apply pSet.function.mk_is_func, intro n, cases n, simp, show _ ≤ _ =ᴮ _, apply bv_refl, from H', refine this_right _, refine le_trans (inf_le_right) (infi_le_of_le i (by apply function_reflect.B_pair))}, apply @bv_rw' _ _ _ _ _ this' (λ z, z ∈ᴮ g), simp, have := (inf_le_right : Γ_1 ≤ _), exact le_trans this (le_trans (by apply function_reflect_aux) (infi_le_of_le i (by refl)))}, { have this' : Γ_1 ≤ (pair (func pSet.omegǎ {down := i}) (func y̌ j)) =ᴮ (pair (pSet.func pSet.omega {down := i})̌ (pSet.func y (function_reflect.f H_nonzero H AE i))̌ ), by {rw pair_eq_pair_iff, refine ⟨bv_refl, _⟩, refine eq_of_is_func'_of_eq (is_func'_of_is_function _) _ _ _, show _ ≤ is_function _ _ _, refine le_trans inf_le_right (function_reflect.B_infty_le_function _ _ _ H_function), show _ ≤ _ =ᴮ _, from (bv_refl : _ ≤ (func pSet.omegǎ {down := i}) =ᴮ _), from H', refine le_trans (inf_le_right) (infi_le_of_le i _), apply function_reflect.B_pair }, apply @bv_rw' _ _ _ _ _ this' (λ z, z ∈ᴮ ((function_reflect.f' H_nonzero H AE)̌ )), simp, apply @bv_rw' _ _ _ _ _ (bv_symm check_pair) (λ z, z ∈ᴮ (function_reflect.f' H_nonzero H AE)̌ ), simp, refine check_mem _, convert pSet.function.mk_mem, refl} end include H_docs lemma function_reflect_of_omega_closed : ∃ (f : pSet.{u}) (Γ' : 𝔹) (H_nonzero' : ⊥ < Γ') (H_le' : Γ' ≤ Γ), (Γ' ≤ f̌ =ᴮ g) ∧ pSet.is_func pSet.omega y f := begin refine ⟨function_reflect.f' H_nonzero H AE,_⟩, { use (⨅ n, function_reflect.B H_nonzero H AE n), -- this is Γ' refine ⟨_,_,⟨_,_⟩⟩, { apply nonzero_infi_of_mem_dense_omega_closed_subset, apply H_docs, apply function_reflect.B_le, apply function_reflect.B_mem_dense }, { refine infi_le_of_le 0 _, let p := _, change classical.some p ≤ _, rcases classical.some_spec p with ⟨_,_,_,_⟩, from ‹_› }, { apply bSet.funext, apply function_reflect.f'_is_function, refine le_trans _ H_function, {exact function_reflect.B_infty_le_Γ H_nonzero H AE}, apply function_reflect_aux₃, from ‹_› }, { apply pSet.function.mk_is_func, intro n, cases n, simp } } end end function_reflect end lemmas end bSet namespace collapse_algebra open bSet local prefix `#`:50 := cardinal.mk local attribute [instance] collapse_space open collapse_poset def 𝔹_collapse : Type u := collapse_algebra ((ℵ₁ : pSet.{u}).type) (powerset omega : pSet.{u}).type attribute instance 𝔹_collapse_boolean_algebra : nontrivial_complete_boolean_algebra 𝔹_collapse := by {unfold 𝔹_collapse, apply_instance} local notation `β` := 𝔹_collapse section AE_of_check_func_check' local notation `ι` := (collapse_poset.inclusion : _ → 𝔹_collapse) local attribute [irreducible] regular_open_algebra lemma nonzero_wit'' {𝓑 : Type*} [nontrivial_complete_boolean_algebra 𝓑] {D : set 𝓑} (H_docs : dense_omega_closed_subset D) {I : Type*} {s : I → 𝓑} {Γ : 𝓑} (H_nonzero : ⊥ < Γ) (H_le : Γ ≤ ⨆ i , s i ): ∃ (j) (Γ' : 𝓑) (H_nonzero' : ⊥ < Γ') (H_le' : Γ' ≤ s j ⊓ Γ), Γ' ∈ D := begin have := nonzero_wit' H_nonzero H_le, cases this with j Hj, have := H_docs.left, rcases this with ⟨H_dense₁, H_dense₂⟩, specialize H_dense₂ _ Hj, rcases H_dense₂ with ⟨Γ', HΓ'₁, HΓ'₂⟩, use j, use Γ', use (nonzero_of_mem_dense_omega_closed_subset H_docs ‹_›), use ‹_›, from ‹_› end lemma AE_of_check_func_check' (x y : pSet) {f : bSet (collapse_algebra (type ℵ₁) (type (powerset omega)))} {Γ : collapse_algebra (type ℵ₁) (type (powerset omega))} (H : Γ ≤ is_func' x̌ y̌ f) (H_nonzero : ⊥ < Γ ) (i : type x) : ∃ (j : type y) (Γ' : collapse_algebra (type ℵ₁) (type (powerset omega))) (H_nonzero' : ⊥ < Γ') (H_le : Γ' ≤ Γ), Γ' ≤ is_func' x̌ y̌ f ∧ Γ' ≤ pair (func x i)̌ (func y j)̌ ∈ᴮ f ∧ Γ' ∈ set.range ι := begin have := is_total_of_is_func' H ((x.func i)̌ ) (by simp), have H' : Γ ≤ (is_func' (x̌) (y̌) f) ⊓ ⨆ w, w ∈ᴮ (y̌) ⊓ pair (x.func i)̌ w ∈ᴮ f , by exact le_inf ‹_› ‹_›, erw[←bounded_exists] at H', swap, {exact B_ext_pair_mem_right}, rw[inf_supr_eq] at H', cases y, dsimp at H', simp only [top_inf_eq] at H', have := nonzero_wit'' principal_opens_dense_omega_closed H_nonzero H', rcases this with ⟨j,Γ', Γ'_nonzero, Γ'_le, HΓ'⟩, use j, use Γ', use ‹_›, bv_split_at Γ'_le, use ‹_›, bv_split_at Γ'_le_left, from ⟨‹_›,‹_›,‹_›⟩ end end AE_of_check_func_check' lemma check_functions_eq_functions (y : pSet.{u}) {Γ : β} : Γ ≤ check (functions (pSet.omega) y) =ᴮ functions (bSet.omega) y̌ := begin refine subset_ext check_functions_subset_functions _, rw[subset_unfold'], bv_intro g, bv_imp_intro Hg, rw[mem_unfold'], let A := _, change _ ≤ A, let B := _, change _ ≤ B at Hg, suffices this : A ⊓ B = B, by {refine le_trans _ inf_le_left, from B, rw this, simp* }, apply Sup_eq_top_of_dense_Union_rel, apply rel_dense_of_dense_in_basis B.1 _ collapse_space_basis_spec, intros D HD HD_ne, unfold collapse_space_basis at HD, cases HD with p Hp, { clear_except p HD_ne, exfalso, finish }, rcases Hp with ⟨p,⟨_,Hp⟩⟩, subst Hp, let P : β := ⟨principal_open p, is_regular_principal_open p⟩, have bot_lt_Γ : (⊥ : β) < P ⊓ B, rw [bot_lt_iff_not_le_bot, le_bot_iff], rwa subtype.ext, have := function_reflect_of_omega_closed principal_opens_dense_omega_closed bot_lt_Γ (by {dsimp[B], refine inf_le_right_of_le (is_func'_of_is_function (by { refine poset_yoneda _, rotate 2, intros Γ HΓ, rw[bSet.mem_functions_iff] at HΓ, convert HΓ }))}) _ (by {dsimp [B], refine poset_yoneda _, intros Γ HΓ, exact bSet.mem_functions_iff.mp (bv_and.right HΓ) }), rcases this with ⟨f, Γ', H_nonzero', H_lt', H_pr', H_func'⟩, apply set.inter_sUnion_ne_empty_of_exists_mem, let C := g ∈ᴮ (functions omega y)̌ ⊓ g =ᴮ g, use C.val, simp, refine ⟨⟨C.property, _⟩, _⟩, use g, suffices this : P ⊓ B ⊓ C ≠ ⊥, by {change ¬ _ at this, rwa subtype.ext at this }, rw ←bot_lt_iff_ne_bot, suffices this : Γ' ≤ C, by {exact lt_of_lt_of_le H_nonzero' (le_inf ‹_› ‹_›)}, refine le_inf _ (bv_refl), apply bv_rw' (bv_symm H_pr'), simp, rw ←pSet.mem_functions_iff at H_func', from check_mem H_func', exact AE_of_check_func_check' end lemma π_χ_regular (p : type (card_ex (aleph 1)) × (powerset omega).type) : @topological_space.is_regular _ collapse_space {g : type (card_ex (aleph 1)) → type (powerset omega) | g (p.fst) = p.snd} := by simp def π_χ : ((ℵ₁ : pSet.{u}).type × (pSet.powerset omega : pSet.{u}).type) → β := λ p, ⟨{g | g p.1 = p.2}, π_χ_regular _⟩ private lemma eq₀ : ((ℵ₁)̌ : bSet β).type = (ℵ₁).type := by simp private lemma eq₀' : ((powerset omega)̌ : bSet.{u} β).type = (powerset omega).type := by simp private lemma eq₁ : ((ℵ₁̌ : bSet β).type × ((powerset omega)̌ : bSet β).type) = ((ℵ₁).type × (powerset omega : pSet.{u}).type ):= by simp lemma aleph_one_type_uncountable : cardinal.omega.succ ≤ # ℵ₁.type := by simp only [succ_le, pSet.omega_lt_aleph_one, pSet.mk_type_mk_eq'''] @[reducible]def π_af : ((ℵ₁̌ : bSet β) .type) → ((powerset omega)̌ : bSet β) .type → β := λ η S, (⟨{g | g (cast eq₀ η) = (cast eq₀' S)}, by simp⟩ : β) lemma π_af_wide : ∀ (j : ((powerset omega)̌ ).type), (⨆ (i : type (ℵ₁̌ )), π_af i j) = (⊤ : β) := begin intro S, refine Sup_eq_top_of_dense_Union _, apply dense_of_dense_in_basis _ collapse_space_basis_spec _, intros B HB HB_ne, unfold collapse_space_basis at HB, cases HB with p Hp, { contradiction }, cases Hp with p Hp, simp at Hp, subst Hp, refine set.ne_empty_of_exists_mem _, { cases exists_mem_compl_dom_of_unctbl p aleph_one_type_uncountable with η Hη, use p.f.trivial_extension S, use trivial_extension_mem_principal_open, change ∃ x, _, use (π_af (cast eq₀.symm η) S).val, refine ⟨_, _⟩, change ∃ x, _, refine ⟨_,_⟩, apply π_af (cast eq₀.symm η) S, refine ⟨_,_⟩, { exact set.mem_range_self _ }, { refl }, { unfold pfun.trivial_extension pfun.extend_via, dsimp, suffices this : (cast eq₀ (cast eq₀.symm η) ∉ pfun.dom (p.f)), by {simpa*}, intro, apply Hη, cc } } end lemma π_af_tall : ∀ (i : (card_ex $ aleph 1)̌ .type), (⨆(j : (powerset omega)̌ .type), π_af i j) = (⊤ : β) := begin intro i, refine Sup_eq_top_of_dense_Union _, apply dense_of_dense_in_basis _ collapse_space_basis_spec _, intros B HB HB_ne, unfold collapse_space_basis at HB, cases HB with p Hp, { contradiction }, { cases Hp with p Hp, simp at Hp, subst Hp, refine set.ne_empty_of_exists_mem _, let f := classical.choice (classical.nonempty_of_not_empty _ ‹_›), use f, use f.property, refine ⟨_,_⟩, { exact {g | g (cast eq₀ i) = f.val (cast eq₀ i)} }, { refine ⟨⟨_,_⟩,by ext; refl⟩, { exact ⟨_, π_χ_regular ((cast eq₀ i), f.val (cast eq₀ i))⟩ }, { exact ⟨⟨f.val (cast eq₀ i), rfl⟩, rfl⟩ }}} end lemma π_af_anti : ∀ (i : type (ℵ₁̌ : bSet β)) (j₁ j₂ : type ((powerset omega)̌ )), j₁ ≠ j₂ → π_af i j₁ ⊓ π_af i j₂ ≤ ⊥ := λ _ _ _ _ _ h, by cases h; finish lemma check_index_inj_of_pSet_index_inj {x : pSet.{u}} (H_inj : ∀ i₁ i₂ : x.type, pSet.equiv (x.func i₁) (x.func i₂) → i₁ = i₂) : ∀ i₁ i₂ : (x̌ : bSet β).type, ⊥ < x̌.func i₁ =ᴮ x̌.func i₂ → i₁ = i₂ := begin have : ∀ i₁ i₂ : x.type, i₁ ≠ i₂ → ¬ equiv (func x i₁) (func x i₂), by finish, {intros i₁ i₂ H, haveI : decidable (i₁ = i₂) := classical.prop_decidable _, by_contra, have H_cast_eq : (check_cast i₁) ≠ (check_cast i₂), by { intro H_eq, apply a, unfold check_cast at H_eq, cc }, specialize this (check_cast i₁) (check_cast i₂) ‹_›, have this₀ := check_bv_eq_bot_of_not_equiv this, suffices this₁ : x̌.func i₁ =ᴮ x̌.func i₂ = ⊥, by {exfalso, rw[eq_bot_iff] at this₀, rw[bot_lt_iff_not_le_bot] at H, suffices : x̌.func i₁ =ᴮ x̌.func i₂ ≤ ⊥, by contradiction, convert_to (func x (check_cast i₁))̌ =ᴮ (func x (check_cast i₂)) ̌ ≤ ⊥ using 2, apply check_func, apply check_func, from ‹_›}, convert this₀; apply check_func} end lemma aleph_one_inj : (∀ i₁ i₂, ⊥ < (func (ℵ₁̌ : bSet β) i₁) =ᴮ (func (ℵ₁̌ : bSet β) i₂) → i₁ = i₂) := check_index_inj_of_pSet_index_inj $ by {intros _ _ H, contrapose H, apply ordinal.mk_inj, from ‹_› } noncomputable def π : bSet β := rel_of_array (ℵ₁̌ : bSet β) ((powerset omega)̌ ) π_af lemma π_is_func {Γ} : Γ ≤ is_func π := begin unfold π, refine rel_of_array_extensional _ _ _ _ _, { from π_af_anti }, { from aleph_one_inj }, end lemma π_is_func' {Γ} : Γ ≤ is_func' (ℵ₁̌ : bSet β) ((powerset omega)̌ ) π := begin unfold π, refine rel_of_array_is_func' _ _ _ (by simp) _ _ _, { from π_af_tall }, { from π_af_anti }, { from aleph_one_inj } end lemma π_is_functional {Γ} : Γ ≤ is_functional π := is_functional_of_is_func _ π_is_func lemma π_is_surj {Γ} : Γ ≤ is_surj (ℵ₁̌ ) ((powerset omega)̌ ) π := rel_of_array_surj _ _ _ (by simp) (by simp) (π_af_wide) lemma π_spec {Γ : β} : Γ ≤ (is_func π) ⊓ ⨅v, v ∈ᴮ (powerset omega)̌ ⟹ (⨆w, w ∈ᴮ (ℵ₁̌ ) ⊓ pair w v ∈ᴮ π) := le_inf π_is_func π_is_surj lemma π_spec' {Γ : β} : Γ ≤ (is_func' ((card_ex $ aleph 1)̌ ) ((powerset omega)̌ ) π) ⊓ is_surj ((card_ex $ aleph 1)̌ ) ((powerset omega)̌ ) π:= le_inf π_is_func' π_is_surj lemma ℵ₁_larger_than_continuum {Γ : β} : Γ ≤ larger_than (ℵ₁ ̌) ((powerset omega)̌ ) := by { apply bv_use (ℵ₁ ̌), apply bv_use π, rw[inf_assoc], from le_inf subset_self π_spec' } lemma surjection_reflect {Γ : β} (H_bot_lt : ⊥ < Γ) (H_surj : Γ ≤ surjects_onto (bSet.omega : bSet.{u} β) ((ℵ₁)̌ : bSet β)) : ∃ (f : pSet.{u}), is_func omega (ordinal.mk (ord (aleph 1))) f ∧ is_surj pSet.omega (card_ex $ aleph 1) f := begin by_contra H, simp only [not_exists, not_and_distrib] at H, suffices this : Γ ≤ ⊥, by {rw[bot_lt_iff_not_le_bot] at H_bot_lt, contradiction}, have := exists_surjection_of_surjects_onto H_surj, bv_cases_at this f Hf, bv_split_at Hf, rw[<-bSet.mem_functions_iff] at Hf_left, suffices this : Γ_1 ≤ f ∈ᴮ (pSet.functions pSet.omega (ℵ₁))̌ , by { by_contra H', rw[<-bot_lt_iff_not_le_bot] at H', replace this := eq_check_of_mem_check H' this, rcases this with ⟨i_g, Γ', H₁,H₂,H₃⟩, apply_at Hf_right le_trans H₂, apply_at Hf_left le_trans H₂, let g := (pSet.functions pSet.omega ℵ₁).func i_g, specialize H g, cases H, { apply_at H check_not_is_func, show β, from Γ', rw[bSet.mem_functions_iff] at Hf_left, tactic.rotate 1, apply_instance, refine false_of_bot_lt_and_le_bot H₁ (H _), change Γ' ≤ f =ᴮ ǧ at H₃, apply_at H₃ bv_symm, apply bv_rw' H₃, simp, from Hf_left }, { apply_at H check_not_is_surj, show β, from Γ', tactic.rotate 1, apply_instance, refine false_of_bot_lt_and_le_bot H₁ (H _), change Γ' ≤ f =ᴮ ǧ at H₃, apply_at H₃ bv_symm, apply bv_rw' H₃, simp, from Hf_right} }, have : Γ_1 ≤ _, from check_functions_eq_functions ℵ₁, bv_cc end lemma omega_lt_aleph_one {Γ : β} : Γ ≤ bSet.omega ≺ (ℵ₁̌ ) := begin unfold larger_than, rw[<-imp_bot, <-deduction], /- `tidy_context` says -/ refine poset_yoneda _, intros Γ_1 a, simp only [le_inf_iff] at *, cases a, bv_cases_at a_right S HS, apply lattice.context_Or_elim HS, intros f Hf, specialize_context Γ_2, simp only [le_inf_iff] at Hf, repeat{auto_cases}, by_contra H, replace H := (bot_lt_iff_not_le_bot.mpr H), suffices : ∃ f : pSet, is_func pSet.omega (ordinal.mk (aleph 1).ord) f ∧ pSet.is_surj (pSet.omega) (ordinal.mk (aleph 1).ord) f, by {exfalso, from ex_no_surj_omega_aleph_one ‹_›}, suffices : Γ_3 ≤ surjects_onto ω ℵ₁̌ , by {from surjection_reflect H this}, refine surjects_onto_of_larger_than_and_exists_mem ‹_› (by simp), end lemma aleph_one_check_le_of_omega_lt (Γ : β) : Γ ≤ le_of_omega_lt (ℵ₁̌ : bSet β) := begin apply bv_rw' (aleph_one_check_is_aleph_one_of_omega_lt (omega_lt_aleph_one)), { simp }, { exact aleph_one_le_of_omega_lt } end lemma continuum_le_continuum_check {Γ : β} : Γ ≤ bv_powerset (bSet.omega : bSet β) ≼ (pSet.powerset (pSet.omega : pSet.{u}) : pSet.{u})̌ := begin refine injects_into_trans _ _, tactic.rotate 1, from powerset_injects_into_functions, have : (Γ : β) ≤ injects_into (functions pSet.omega (of_nat 2) : pSet.{u})̌ (powerset (omega) : pSet.{u})̌ , by { rw injects_into_iff_injection_into, rcases functions_2_injects_into_powerset (pSet.omega : pSet.{u}) with ⟨f,Hf⟩, apply bv_use f̌, refine check_is_injective_function _, from Hf }, change Γ ≤ (λ z, injects_into z (powerset omega)̌ ) _ at this, have := bv_rw'' _ this, tactic.rotate 2, exact check_functions_eq_functions (of_nat 2), from this end lemma aleph_one_not_lt_powerset_omega : ∀ {Γ : β}, Γ ≤ - (ℵ₁̌ ≺ 𝒫(ω)) := begin intro Γ, rw[<-imp_bot], dsimp, bv_imp_intro H, refine bv_absurd _ ℵ₁_larger_than_continuum _, exact bSet_lt_of_lt_of_le H continuum_le_continuum_check end theorem CH_true : (⊤ : β) ≤ CH := CH_true_aux aleph_one_check_le_of_omega_lt (by apply aleph_one_not_lt_powerset_omega) theorem CH₂_true : (⊤ : β) ≤ CH₂ := CH_iff_CH₂.mp CH_true end collapse_algebra
3e9afde9b4ee17f8927b1881bd1bb875f2f3e5b1
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/topology/metric_space/hausdorff_distance.lean
34a23f43cfa33930cdf8183004d360d1921d5ff7
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
32,407
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sébastien Gouëzel -/ import topology.metric_space.isometry topology.instances.ennreal topology.metric_space.lipschitz /-! # Hausdorff distance The Hausdorff distance on subsets of a metric (or emetric) space. Given two subsets `s` and `t` of a metric space, their Hausdorff distance is the smallest `d` such that any point `s` is within `d` of a point in `t`, and conversely. This quantity is often infinite (think of `s` bounded and `t` unbounded), and therefore better expressed in the setting of emetric spaces. ## Main definitions This files introduces: * `inf_edist x s`, the infimum edistance of a point `x` to a set `s` in an emetric space * `Hausdorff_edist s t`, the Hausdorff edistance of two sets in an emetric space * Versions of these notions on metric spaces, called respectively `inf_dist` and `Hausdorff_dist`. -/ noncomputable theory open_locale classical universes u v w open classical set function topological_space filter namespace emetric section inf_edist open_locale ennreal variables {α : Type u} {β : Type v} [emetric_space α] [emetric_space β] {x y : α} {s t : set α} {Φ : α → β} /-- The minimal edistance of a point to a set -/ def inf_edist (x : α) (s : set α) : ennreal := Inf ((edist x) '' s) @[simp] lemma inf_edist_empty : inf_edist x ∅ = ∞ := by unfold inf_edist; simp /-- The edist to a union is the minimum of the edists -/ @[simp] lemma inf_edist_union : inf_edist x (s ∪ t) = inf_edist x s ⊓ inf_edist x t := by simp [inf_edist, image_union, Inf_union] /-- The edist to a singleton is the edistance to the single point of this singleton -/ @[simp] lemma inf_edist_singleton : inf_edist x {y} = edist x y := by simp [inf_edist] /-- The edist to a set is bounded above by the edist to any of its points -/ lemma inf_edist_le_edist_of_mem (h : y ∈ s) : inf_edist x s ≤ edist x y := Inf_le ((mem_image _ _ _).2 ⟨y, h, by refl⟩) /-- If a point `x` belongs to `s`, then its edist to `s` vanishes -/ lemma inf_edist_zero_of_mem (h : x ∈ s) : inf_edist x s = 0 := le_zero_iff_eq.1 $ @edist_self _ _ x ▸ inf_edist_le_edist_of_mem h /-- The edist is monotonous with respect to inclusion -/ lemma inf_edist_le_inf_edist_of_subset (h : s ⊆ t) : inf_edist x t ≤ inf_edist x s := Inf_le_Inf (image_subset _ h) /-- If the edist to a set is `< r`, there exists a point in the set at edistance `< r` -/ lemma exists_edist_lt_of_inf_edist_lt {r : ennreal} (h : inf_edist x s < r) : ∃y∈s, edist x y < r := let ⟨t, ⟨ht, tr⟩⟩ := Inf_lt_iff.1 h in let ⟨y, ⟨ys, hy⟩⟩ := (mem_image _ _ _).1 ht in ⟨y, ys, by rwa ← hy at tr⟩ /-- The edist of `x` to `s` is bounded by the sum of the edist of `y` to `s` and the edist from `x` to `y` -/ lemma inf_edist_le_inf_edist_add_edist : inf_edist x s ≤ inf_edist y s + edist x y := begin have : ∀z ∈ s, Inf (edist x '' s) ≤ edist y z + edist x y := λz hz, calc Inf (edist x '' s) ≤ edist x z : Inf_le ((mem_image _ _ _).2 ⟨z, hz, by refl⟩) ... ≤ edist x y + edist y z : edist_triangle _ _ _ ... = edist y z + edist x y : add_comm _ _, have : (λz, z + edist x y) (Inf (edist y '' s)) = Inf ((λz, z + edist x y) '' (edist y '' s)), { refine Inf_of_continuous _ _ (by simp), { exact continuous_id.add continuous_const }, { assume a b h, simp, apply add_le_add_right' h }}, simp only [inf_edist] at this, rw [inf_edist, inf_edist, this, ← image_comp], simpa only [and_imp, function.comp_app, le_Inf_iff, exists_imp_distrib, ball_image_iff] end /-- The edist to a set depends continuously on the point -/ lemma continuous_inf_edist : continuous (λx, inf_edist x s) := continuous_of_le_add_edist 1 (by simp) $ by simp only [one_mul, inf_edist_le_inf_edist_add_edist, forall_2_true_iff] /-- The edist to a set and to its closure coincide -/ lemma inf_edist_closure : inf_edist x (closure s) = inf_edist x s := begin refine le_antisymm (inf_edist_le_inf_edist_of_subset subset_closure) _, refine ennreal.le_of_forall_epsilon_le (λε εpos h, _), have εpos' : (0 : ennreal) < ε := by simpa, have : inf_edist x (closure s) < inf_edist x (closure s) + ε/2 := ennreal.lt_add_right h (ennreal.half_pos εpos'), rcases exists_edist_lt_of_inf_edist_lt this with ⟨y, ycs, hy⟩, -- y : α, ycs : y ∈ closure s, hy : edist x y < inf_edist x (closure s) + ↑ε / 2 rcases emetric.mem_closure_iff.1 ycs (ε/2) (ennreal.half_pos εpos') with ⟨z, zs, dyz⟩, -- z : α, zs : z ∈ s, dyz : edist y z < ↑ε / 2 calc inf_edist x s ≤ edist x z : inf_edist_le_edist_of_mem zs ... ≤ edist x y + edist y z : edist_triangle _ _ _ ... ≤ (inf_edist x (closure s) + ε / 2) + (ε/2) : add_le_add' (le_of_lt hy) (le_of_lt dyz) ... = inf_edist x (closure s) + ↑ε : by simp [ennreal.add_halves] end /-- A point belongs to the closure of `s` iff its infimum edistance to this set vanishes -/ lemma mem_closure_iff_inf_edist_zero : x ∈ closure s ↔ inf_edist x s = 0 := ⟨λh, by rw ← inf_edist_closure; exact inf_edist_zero_of_mem h, λh, emetric.mem_closure_iff.2 $ λε εpos, exists_edist_lt_of_inf_edist_lt (by rwa h)⟩ /-- Given a closed set `s`, a point belongs to `s` iff its infimum edistance to this set vanishes -/ lemma mem_iff_ind_edist_zero_of_closed (h : is_closed s) : x ∈ s ↔ inf_edist x s = 0 := begin convert ← mem_closure_iff_inf_edist_zero, exact closure_eq_iff_is_closed.2 h end /-- The infimum edistance is invariant under isometries -/ lemma inf_edist_image (hΦ : isometry Φ) : inf_edist (Φ x) (Φ '' t) = inf_edist x t := begin simp only [inf_edist], apply congr_arg, ext b, split, { assume hb, rcases (mem_image _ _ _).1 hb with ⟨y, ⟨hy, hy'⟩⟩, rcases (mem_image _ _ _).1 hy with ⟨z, ⟨hz, hz'⟩⟩, rw [← hy', ← hz', hΦ x z], exact mem_image_of_mem _ hz }, { assume hb, rcases (mem_image _ _ _).1 hb with ⟨y, ⟨hy, hy'⟩⟩, rw [← hy', ← hΦ x y], exact mem_image_of_mem _ (mem_image_of_mem _ hy) } end end inf_edist --section /-- The Hausdorff edistance between two sets is the smallest `r` such that each set is contained in the `r`-neighborhood of the other one -/ def Hausdorff_edist {α : Type u} [emetric_space α] (s t : set α) : ennreal := Sup ((λx, inf_edist x t) '' s) ⊔ Sup ((λx, inf_edist x s) '' t) lemma Hausdorff_edist_def {α : Type u} [emetric_space α] (s t : set α) : Hausdorff_edist s t = Sup ((λx, inf_edist x t) '' s) ⊔ Sup ((λx, inf_edist x s) '' t) := rfl attribute [irreducible] Hausdorff_edist section Hausdorff_edist open_locale ennreal variables {α : Type u} {β : Type v} [emetric_space α] [emetric_space β] {x y : α} {s t u : set α} {Φ : α → β} /-- The Hausdorff edistance of a set to itself vanishes -/ @[simp] lemma Hausdorff_edist_self : Hausdorff_edist s s = 0 := begin erw [Hausdorff_edist_def, sup_idem, ← le_bot_iff], apply Sup_le _, simp [le_bot_iff, inf_edist_zero_of_mem, le_refl] {contextual := tt}, end /-- The Haudorff edistances of `s` to `t` and of `t` to `s` coincide -/ lemma Hausdorff_edist_comm : Hausdorff_edist s t = Hausdorff_edist t s := by unfold Hausdorff_edist; apply sup_comm /-- Bounding the Hausdorff edistance by bounding the edistance of any point in each set to the other set -/ lemma Hausdorff_edist_le_of_inf_edist {r : ennreal} (H1 : ∀x ∈ s, inf_edist x t ≤ r) (H2 : ∀x ∈ t, inf_edist x s ≤ r) : Hausdorff_edist s t ≤ r := begin simp only [Hausdorff_edist, -mem_image, set.ball_image_iff, Sup_le_iff, sup_le_iff], exact ⟨H1, H2⟩ end /-- Bounding the Hausdorff edistance by exhibiting, for any point in each set, another point in the other set at controlled distance -/ lemma Hausdorff_edist_le_of_mem_edist {r : ennreal} (H1 : ∀x ∈ s, ∃y ∈ t, edist x y ≤ r) (H2 : ∀x ∈ t, ∃y ∈ s, edist x y ≤ r) : Hausdorff_edist s t ≤ r := begin refine Hausdorff_edist_le_of_inf_edist _ _, { assume x xs, rcases H1 x xs with ⟨y, yt, hy⟩, exact le_trans (inf_edist_le_edist_of_mem yt) hy }, { assume x xt, rcases H2 x xt with ⟨y, ys, hy⟩, exact le_trans (inf_edist_le_edist_of_mem ys) hy } end /-- The distance to a set is controlled by the Hausdorff distance -/ lemma inf_edist_le_Hausdorff_edist_of_mem (h : x ∈ s) : inf_edist x t ≤ Hausdorff_edist s t := begin rw Hausdorff_edist_def, refine le_trans (le_Sup _) le_sup_left, exact mem_image_of_mem _ h end /-- If the Hausdorff distance is `<r`, then any point in one of the sets has a corresponding point at distance `<r` in the other set -/ lemma exists_edist_lt_of_Hausdorff_edist_lt {r : ennreal} (h : x ∈ s) (H : Hausdorff_edist s t < r) : ∃y∈t, edist x y < r := exists_edist_lt_of_inf_edist_lt $ calc inf_edist x t ≤ Sup ((λx, inf_edist x t) '' s) : le_Sup (mem_image_of_mem _ h) ... ≤ Sup ((λx, inf_edist x t) '' s) ⊔ Sup ((λx, inf_edist x s) '' t) : le_sup_left ... < r : by rwa Hausdorff_edist_def at H /-- The distance from `x` to `s`or `t` is controlled in terms of the Hausdorff distance between `s` and `t` -/ lemma inf_edist_le_inf_edist_add_Hausdorff_edist : inf_edist x t ≤ inf_edist x s + Hausdorff_edist s t := ennreal.le_of_forall_epsilon_le $ λε εpos h, begin have εpos' : (0 : ennreal) < ε := by simpa, have : inf_edist x s < inf_edist x s + ε/2 := ennreal.lt_add_right (ennreal.add_lt_top.1 h).1 (ennreal.half_pos εpos'), rcases exists_edist_lt_of_inf_edist_lt this with ⟨y, ys, dxy⟩, -- y : α, ys : y ∈ s, dxy : edist x y < inf_edist x s + ↑ε / 2 have : Hausdorff_edist s t < Hausdorff_edist s t + ε/2 := ennreal.lt_add_right (ennreal.add_lt_top.1 h).2 (ennreal.half_pos εpos'), rcases exists_edist_lt_of_Hausdorff_edist_lt ys this with ⟨z, zt, dyz⟩, -- z : α, zt : z ∈ t, dyz : edist y z < Hausdorff_edist s t + ↑ε / 2 calc inf_edist x t ≤ edist x z : inf_edist_le_edist_of_mem zt ... ≤ edist x y + edist y z : edist_triangle _ _ _ ... ≤ (inf_edist x s + ε/2) + (Hausdorff_edist s t + ε/2) : add_le_add' (le_of_lt dxy) (le_of_lt dyz) ... = inf_edist x s + Hausdorff_edist s t + ε : by simp [ennreal.add_halves, add_comm, add_left_comm] end /-- The Hausdorff edistance is invariant under eisometries -/ lemma Hausdorff_edist_image (h : isometry Φ) : Hausdorff_edist (Φ '' s) (Φ '' t) = Hausdorff_edist s t := begin unfold Hausdorff_edist, congr, { ext b, split, { assume hb, rcases (mem_image _ _ _ ).1 hb with ⟨y, ⟨hy, hy'⟩⟩, rcases (mem_image _ _ _ ).1 hy with ⟨z, ⟨hz, hz'⟩⟩, rw [← hy', ← hz', inf_edist_image h], exact mem_image_of_mem _ hz }, { assume hb, rcases (mem_image _ _ _ ).1 hb with ⟨y, ⟨hy, hy'⟩⟩, rw [← hy', ← inf_edist_image h], exact mem_image_of_mem _ (mem_image_of_mem _ hy) }}, { ext b, split, { assume hb, rcases (mem_image _ _ _ ).1 hb with ⟨y, ⟨hy, hy'⟩⟩, rcases (mem_image _ _ _ ).1 hy with ⟨z, ⟨hz, hz'⟩⟩, rw [← hy', ← hz', inf_edist_image h], exact mem_image_of_mem _ hz }, { assume hb, rcases (mem_image _ _ _ ).1 hb with ⟨y, ⟨hy, hy'⟩⟩, rw [← hy', ← inf_edist_image h], exact mem_image_of_mem _ (mem_image_of_mem _ hy) }} end /-- The Hausdorff distance is controlled by the diameter of the union -/ lemma Hausdorff_edist_le_ediam (hs : s.nonempty) (ht : t.nonempty) : Hausdorff_edist s t ≤ diam (s ∪ t) := begin rcases hs with ⟨x, xs⟩, rcases ht with ⟨y, yt⟩, refine Hausdorff_edist_le_of_mem_edist _ _, { exact λz hz, ⟨y, yt, edist_le_diam_of_mem (subset_union_left _ _ hz) (subset_union_right _ _ yt)⟩ }, { exact λz hz, ⟨x, xs, edist_le_diam_of_mem (subset_union_right _ _ hz) (subset_union_left _ _ xs)⟩ } end /-- The Hausdorff distance satisfies the triangular inequality -/ lemma Hausdorff_edist_triangle : Hausdorff_edist s u ≤ Hausdorff_edist s t + Hausdorff_edist t u := begin rw Hausdorff_edist_def, simp only [and_imp, set.mem_image, Sup_le_iff, exists_imp_distrib, sup_le_iff, -mem_image, set.ball_image_iff], split, show ∀x ∈ s, inf_edist x u ≤ Hausdorff_edist s t + Hausdorff_edist t u, from λx xs, calc inf_edist x u ≤ inf_edist x t + Hausdorff_edist t u : inf_edist_le_inf_edist_add_Hausdorff_edist ... ≤ Hausdorff_edist s t + Hausdorff_edist t u : add_le_add_right' (inf_edist_le_Hausdorff_edist_of_mem xs), show ∀x ∈ u, inf_edist x s ≤ Hausdorff_edist s t + Hausdorff_edist t u, from λx xu, calc inf_edist x s ≤ inf_edist x t + Hausdorff_edist t s : inf_edist_le_inf_edist_add_Hausdorff_edist ... ≤ Hausdorff_edist u t + Hausdorff_edist t s : add_le_add_right' (inf_edist_le_Hausdorff_edist_of_mem xu) ... = Hausdorff_edist s t + Hausdorff_edist t u : by simp [Hausdorff_edist_comm, add_comm] end /-- The Hausdorff edistance between a set and its closure vanishes -/ @[simp, priority 1100] lemma Hausdorff_edist_self_closure : Hausdorff_edist s (closure s) = 0 := begin erw ← le_bot_iff, simp only [Hausdorff_edist, inf_edist_closure, -le_zero_iff_eq, and_imp, set.mem_image, Sup_le_iff, exists_imp_distrib, sup_le_iff, set.ball_image_iff, ennreal.bot_eq_zero, -mem_image], simp only [inf_edist_zero_of_mem, mem_closure_iff_inf_edist_zero, le_refl, and_self, forall_true_iff] {contextual := tt} end /-- Replacing a set by its closure does not change the Hausdorff edistance. -/ @[simp] lemma Hausdorff_edist_closure₁ : Hausdorff_edist (closure s) t = Hausdorff_edist s t := begin refine le_antisymm _ _, { calc _ ≤ Hausdorff_edist (closure s) s + Hausdorff_edist s t : Hausdorff_edist_triangle ... = Hausdorff_edist s t : by simp [Hausdorff_edist_comm] }, { calc _ ≤ Hausdorff_edist s (closure s) + Hausdorff_edist (closure s) t : Hausdorff_edist_triangle ... = Hausdorff_edist (closure s) t : by simp } end /-- Replacing a set by its closure does not change the Hausdorff edistance. -/ @[simp] lemma Hausdorff_edist_closure₂ : Hausdorff_edist s (closure t) = Hausdorff_edist s t := by simp [@Hausdorff_edist_comm _ _ s _] /-- The Hausdorff edistance between sets or their closures is the same -/ @[simp] lemma Hausdorff_edist_closure : Hausdorff_edist (closure s) (closure t) = Hausdorff_edist s t := by simp /-- Two sets are at zero Hausdorff edistance if and only if they have the same closure -/ lemma Hausdorff_edist_zero_iff_closure_eq_closure : Hausdorff_edist s t = 0 ↔ closure s = closure t := ⟨begin assume h, refine subset.antisymm _ _, { have : s ⊆ closure t := λx xs, mem_closure_iff_inf_edist_zero.2 $ begin erw ← le_bot_iff, have := @inf_edist_le_Hausdorff_edist_of_mem _ _ _ _ t xs, rwa h at this, end, by rw ← @closure_closure _ _ t; exact closure_mono this }, { have : t ⊆ closure s := λx xt, mem_closure_iff_inf_edist_zero.2 $ begin erw ← le_bot_iff, have := @inf_edist_le_Hausdorff_edist_of_mem _ _ _ _ s xt, rw Hausdorff_edist_comm at h, rwa h at this, end, by rw ← @closure_closure _ _ s; exact closure_mono this } end, λh, by rw [← Hausdorff_edist_closure, h, Hausdorff_edist_self]⟩ /-- Two closed sets are at zero Hausdorff edistance if and only if they coincide -/ lemma Hausdorff_edist_zero_iff_eq_of_closed (hs : is_closed s) (ht : is_closed t) : Hausdorff_edist s t = 0 ↔ s = t := by rw [Hausdorff_edist_zero_iff_closure_eq_closure, closure_eq_iff_is_closed.2 hs, closure_eq_iff_is_closed.2 ht] /-- The Haudorff edistance to the empty set is infinite -/ lemma Hausdorff_edist_empty (ne : s.nonempty) : Hausdorff_edist s ∅ = ∞ := begin rcases ne with ⟨x, xs⟩, have : inf_edist x ∅ ≤ Hausdorff_edist s ∅ := inf_edist_le_Hausdorff_edist_of_mem xs, simpa using this, end /-- If a set is at finite Hausdorff edistance of a nonempty set, it is nonempty -/ lemma nonempty_of_Hausdorff_edist_ne_top (hs : s.nonempty) (fin : Hausdorff_edist s t ≠ ⊤) : t.nonempty := t.eq_empty_or_nonempty.elim (λ ht, (fin $ ht.symm ▸ Hausdorff_edist_empty hs).elim) id lemma empty_or_nonempty_of_Hausdorff_edist_ne_top (fin : Hausdorff_edist s t ≠ ⊤) : s = ∅ ∧ t = ∅ ∨ s.nonempty ∧ t.nonempty := begin cases s.eq_empty_or_nonempty with hs hs, { cases t.eq_empty_or_nonempty with ht ht, { exact or.inl ⟨hs, ht⟩ }, { rw Hausdorff_edist_comm at fin, exact or.inr ⟨nonempty_of_Hausdorff_edist_ne_top ht fin, ht⟩ } }, { exact or.inr ⟨hs, nonempty_of_Hausdorff_edist_ne_top hs fin⟩ } end end Hausdorff_edist -- section end emetric --namespace /-Now, we turn to the same notions in metric spaces. To avoid the difficulties related to Inf and Sup on ℝ (which is only conditionnally complete), we use the notions in ennreal formulated in terms of the edistance, and coerce them to ℝ. Then their properties follow readily from the corresponding properties in ennreal, modulo some tedious rewriting of inequalities from one to the other -/ namespace metric section variables {α : Type u} {β : Type v} [metric_space α] [metric_space β] {s t u : set α} {x y : α} {Φ : α → β} open emetric /-- The minimal distance of a point to a set -/ def inf_dist (x : α) (s : set α) : ℝ := ennreal.to_real (inf_edist x s) /-- the minimal distance is always nonnegative -/ lemma inf_dist_nonneg : 0 ≤ inf_dist x s := by simp [inf_dist] /-- the minimal distance to the empty set is 0 (if you want to have the more reasonable value ∞ instead, use `inf_edist`, which takes values in ennreal) -/ @[simp] lemma inf_dist_empty : inf_dist x ∅ = 0 := by simp [inf_dist] /-- In a metric space, the minimal edistance to a nonempty set is finite -/ lemma inf_edist_ne_top (h : s.nonempty) : inf_edist x s ≠ ⊤ := begin rcases h with ⟨y, hy⟩, apply lt_top_iff_ne_top.1, calc inf_edist x s ≤ edist x y : inf_edist_le_edist_of_mem hy ... < ⊤ : lt_top_iff_ne_top.2 (edist_ne_top _ _) end /-- The minimal distance of a point to a set containing it vanishes -/ lemma inf_dist_zero_of_mem (h : x ∈ s) : inf_dist x s = 0 := by simp [inf_edist_zero_of_mem h, inf_dist] /-- The minimal distance to a singleton is the distance to the unique point in this singleton -/ @[simp] lemma inf_dist_singleton : inf_dist x {y} = dist x y := by simp [inf_dist, inf_edist, dist_edist] /-- The minimal distance to a set is bounded by the distance to any point in this set -/ lemma inf_dist_le_dist_of_mem (h : y ∈ s) : inf_dist x s ≤ dist x y := begin rw [dist_edist, inf_dist, ennreal.to_real_le_to_real (inf_edist_ne_top ⟨_, h⟩) (edist_ne_top _ _)], exact inf_edist_le_edist_of_mem h end /-- The minimal distance is monotonous with respect to inclusion -/ lemma inf_dist_le_inf_dist_of_subset (h : s ⊆ t) (hs : s.nonempty) : inf_dist x t ≤ inf_dist x s := begin have ht : t.nonempty := hs.mono h, rw [inf_dist, inf_dist, ennreal.to_real_le_to_real (inf_edist_ne_top ht) (inf_edist_ne_top hs)], exact inf_edist_le_inf_edist_of_subset h end /-- If the minimal distance to a set is `<r`, there exists a point in this set at distance `<r` -/ lemma exists_dist_lt_of_inf_dist_lt {r : real} (h : inf_dist x s < r) (hs : s.nonempty) : ∃y∈s, dist x y < r := begin have rpos : 0 < r := lt_of_le_of_lt inf_dist_nonneg h, have : inf_edist x s < ennreal.of_real r, { rwa [inf_dist, ← ennreal.to_real_of_real (le_of_lt rpos), ennreal.to_real_lt_to_real (inf_edist_ne_top hs)] at h, simp }, rcases exists_edist_lt_of_inf_edist_lt this with ⟨y, ys, hy⟩, rw [edist_dist, ennreal.of_real_lt_of_real_iff rpos] at hy, exact ⟨y, ys, hy⟩, end /-- The minimal distance from `x` to `s` is bounded by the distance from `y` to `s`, modulo the distance between `x` and `y` -/ lemma inf_dist_le_inf_dist_add_dist : inf_dist x s ≤ inf_dist y s + dist x y := begin cases s.eq_empty_or_nonempty with hs hs, { by simp [hs, dist_nonneg] }, { rw [inf_dist, inf_dist, dist_edist, ← ennreal.to_real_add (inf_edist_ne_top hs) (edist_ne_top _ _), ennreal.to_real_le_to_real (inf_edist_ne_top hs)], { apply inf_edist_le_inf_edist_add_edist }, { simp [ennreal.add_eq_top, inf_edist_ne_top hs, edist_ne_top] }} end variable (s) /-- The minimal distance to a set is Lipschitz in point with constant 1 -/ lemma lipschitz_inf_dist_pt : lipschitz_with 1 (λx, inf_dist x s) := lipschitz_with.of_le_add $ λ x y, inf_dist_le_inf_dist_add_dist /-- The minimal distance to a set is uniformly continuous in point -/ lemma uniform_continuous_inf_dist_pt : uniform_continuous (λx, inf_dist x s) := (lipschitz_inf_dist_pt s).uniform_continuous /-- The minimal distance to a set is continuous in point -/ lemma continuous_inf_dist_pt : continuous (λx, inf_dist x s) := (uniform_continuous_inf_dist_pt s).continuous variable {s} /-- The minimal distance to a set and its closure coincide -/ lemma inf_dist_eq_closure : inf_dist x (closure s) = inf_dist x s := by simp [inf_dist, inf_edist_closure] /-- A point belongs to the closure of `s` iff its infimum distance to this set vanishes -/ lemma mem_closure_iff_inf_dist_zero (h : s.nonempty) : x ∈ closure s ↔ inf_dist x s = 0 := by simp [mem_closure_iff_inf_edist_zero, inf_dist, ennreal.to_real_eq_zero_iff, inf_edist_ne_top h] /-- Given a closed set `s`, a point belongs to `s` iff its infimum distance to this set vanishes -/ lemma mem_iff_inf_dist_zero_of_closed (h : is_closed s) (hs : s.nonempty) : x ∈ s ↔ inf_dist x s = 0 := begin have := @mem_closure_iff_inf_dist_zero _ _ s x hs, rwa closure_eq_iff_is_closed.2 h at this end /-- The infimum distance is invariant under isometries -/ lemma inf_dist_image (hΦ : isometry Φ) : inf_dist (Φ x) (Φ '' t) = inf_dist x t := by simp [inf_dist, inf_edist_image hΦ] /-- The Hausdorff distance between two sets is the smallest nonnegative `r` such that each set is included in the `r`-neighborhood of the other. If there is no such `r`, it is defined to be `0`, arbitrarily -/ def Hausdorff_dist (s t : set α) : ℝ := ennreal.to_real (Hausdorff_edist s t) /-- The Hausdorff distance is nonnegative -/ lemma Hausdorff_dist_nonneg : 0 ≤ Hausdorff_dist s t := by simp [Hausdorff_dist] /-- If two sets are nonempty and bounded in a metric space, they are at finite Hausdorff edistance -/ lemma Hausdorff_edist_ne_top_of_nonempty_of_bounded (hs : s.nonempty) (ht : t.nonempty) (bs : bounded s) (bt : bounded t) : Hausdorff_edist s t ≠ ⊤ := begin rcases hs with ⟨cs, hcs⟩, rcases ht with ⟨ct, hct⟩, rcases (bounded_iff_subset_ball ct).1 bs with ⟨rs, hrs⟩, rcases (bounded_iff_subset_ball cs).1 bt with ⟨rt, hrt⟩, have : Hausdorff_edist s t ≤ ennreal.of_real (max rs rt), { apply Hausdorff_edist_le_of_mem_edist, { assume x xs, existsi [ct, hct], have : dist x ct ≤ max rs rt := le_trans (hrs xs) (le_max_left _ _), rwa [edist_dist, ennreal.of_real_le_of_real_iff], exact le_trans dist_nonneg this }, { assume x xt, existsi [cs, hcs], have : dist x cs ≤ max rs rt := le_trans (hrt xt) (le_max_right _ _), rwa [edist_dist, ennreal.of_real_le_of_real_iff], exact le_trans dist_nonneg this }}, exact ennreal.lt_top_iff_ne_top.1 (lt_of_le_of_lt this (by simp [lt_top_iff_ne_top])) end /-- The Hausdorff distance between a set and itself is zero -/ @[simp] lemma Hausdorff_dist_self_zero : Hausdorff_dist s s = 0 := by simp [Hausdorff_dist] /-- The Hausdorff distance from `s` to `t` and from `t` to `s` coincide -/ lemma Hausdorff_dist_comm : Hausdorff_dist s t = Hausdorff_dist t s := by simp [Hausdorff_dist, Hausdorff_edist_comm] /-- The Hausdorff distance to the empty set vanishes (if you want to have the more reasonable value ∞ instead, use `Hausdorff_edist`, which takes values in ennreal) -/ @[simp] lemma Hausdorff_dist_empty : Hausdorff_dist s ∅ = 0 := begin cases s.eq_empty_or_nonempty with h h, { simp [h] }, { simp [Hausdorff_dist, Hausdorff_edist_empty h] } end /-- The Hausdorff distance to the empty set vanishes (if you want to have the more reasonable value ∞ instead, use `Hausdorff_edist`, which takes values in ennreal) -/ @[simp] lemma Hausdorff_dist_empty' : Hausdorff_dist ∅ s = 0 := by simp [Hausdorff_dist_comm] /-- Bounding the Hausdorff distance by bounding the distance of any point in each set to the other set -/ lemma Hausdorff_dist_le_of_inf_dist {r : ℝ} (hr : r ≥ 0) (H1 : ∀x ∈ s, inf_dist x t ≤ r) (H2 : ∀x ∈ t, inf_dist x s ≤ r) : Hausdorff_dist s t ≤ r := begin by_cases h1 : Hausdorff_edist s t = ⊤, by rwa [Hausdorff_dist, h1, ennreal.top_to_real], cases s.eq_empty_or_nonempty with hs hs, by rwa [hs, Hausdorff_dist_empty'], cases t.eq_empty_or_nonempty with ht ht, by rwa [ht, Hausdorff_dist_empty], have : Hausdorff_edist s t ≤ ennreal.of_real r, { apply Hausdorff_edist_le_of_inf_edist _ _, { assume x hx, have I := H1 x hx, rwa [inf_dist, ← ennreal.to_real_of_real hr, ennreal.to_real_le_to_real (inf_edist_ne_top ht) ennreal.of_real_ne_top] at I }, { assume x hx, have I := H2 x hx, rwa [inf_dist, ← ennreal.to_real_of_real hr, ennreal.to_real_le_to_real (inf_edist_ne_top hs) ennreal.of_real_ne_top] at I }}, rwa [Hausdorff_dist, ← ennreal.to_real_of_real hr, ennreal.to_real_le_to_real h1 ennreal.of_real_ne_top] end /-- Bounding the Hausdorff distance by exhibiting, for any point in each set, another point in the other set at controlled distance -/ lemma Hausdorff_dist_le_of_mem_dist {r : ℝ} (hr : 0 ≤ r) (H1 : ∀x ∈ s, ∃y ∈ t, dist x y ≤ r) (H2 : ∀x ∈ t, ∃y ∈ s, dist x y ≤ r) : Hausdorff_dist s t ≤ r := begin apply Hausdorff_dist_le_of_inf_dist hr, { assume x xs, rcases H1 x xs with ⟨y, yt, hy⟩, exact le_trans (inf_dist_le_dist_of_mem yt) hy }, { assume x xt, rcases H2 x xt with ⟨y, ys, hy⟩, exact le_trans (inf_dist_le_dist_of_mem ys) hy } end /-- The Hausdorff distance is controlled by the diameter of the union -/ lemma Hausdorff_dist_le_diam (hs : s.nonempty) (bs : bounded s) (ht : t.nonempty) (bt : bounded t) : Hausdorff_dist s t ≤ diam (s ∪ t) := begin rcases hs with ⟨x, xs⟩, rcases ht with ⟨y, yt⟩, refine Hausdorff_dist_le_of_mem_dist diam_nonneg _ _, { exact λz hz, ⟨y, yt, dist_le_diam_of_mem (bounded_union.2 ⟨bs, bt⟩) (subset_union_left _ _ hz) (subset_union_right _ _ yt)⟩ }, { exact λz hz, ⟨x, xs, dist_le_diam_of_mem (bounded_union.2 ⟨bs, bt⟩) (subset_union_right _ _ hz) (subset_union_left _ _ xs)⟩ } end /-- The distance to a set is controlled by the Hausdorff distance -/ lemma inf_dist_le_Hausdorff_dist_of_mem (hx : x ∈ s) (fin : Hausdorff_edist s t ≠ ⊤) : inf_dist x t ≤ Hausdorff_dist s t := begin have ht : t.nonempty := nonempty_of_Hausdorff_edist_ne_top ⟨x, hx⟩ fin, rw [Hausdorff_dist, inf_dist, ennreal.to_real_le_to_real (inf_edist_ne_top ht) fin], exact inf_edist_le_Hausdorff_edist_of_mem hx end /-- If the Hausdorff distance is `<r`, then any point in one of the sets is at distance `<r` of a point in the other set -/ lemma exists_dist_lt_of_Hausdorff_dist_lt {r : ℝ} (h : x ∈ s) (H : Hausdorff_dist s t < r) (fin : Hausdorff_edist s t ≠ ⊤) : ∃y∈t, dist x y < r := begin have r0 : 0 < r := lt_of_le_of_lt (Hausdorff_dist_nonneg) H, have : Hausdorff_edist s t < ennreal.of_real r, by rwa [Hausdorff_dist, ← ennreal.to_real_of_real (le_of_lt r0), ennreal.to_real_lt_to_real fin (ennreal.of_real_ne_top)] at H, rcases exists_edist_lt_of_Hausdorff_edist_lt h this with ⟨y, hy, yr⟩, rw [edist_dist, ennreal.of_real_lt_of_real_iff r0] at yr, exact ⟨y, hy, yr⟩ end /-- If the Hausdorff distance is `<r`, then any point in one of the sets is at distance `<r` of a point in the other set -/ lemma exists_dist_lt_of_Hausdorff_dist_lt' {r : ℝ} (h : y ∈ t) (H : Hausdorff_dist s t < r) (fin : Hausdorff_edist s t ≠ ⊤) : ∃x∈s, dist x y < r := begin rw Hausdorff_dist_comm at H, rw Hausdorff_edist_comm at fin, simpa [dist_comm] using exists_dist_lt_of_Hausdorff_dist_lt h H fin end /-- The infimum distance to `s` and `t` are the same, up to the Hausdorff distance between `s` and `t` -/ lemma inf_dist_le_inf_dist_add_Hausdorff_dist (fin : Hausdorff_edist s t ≠ ⊤) : inf_dist x t ≤ inf_dist x s + Hausdorff_dist s t := begin rcases empty_or_nonempty_of_Hausdorff_edist_ne_top fin with ⟨hs,ht⟩|⟨hs,ht⟩, { simp only [hs, ht, Hausdorff_dist_empty, inf_dist_empty, zero_add] }, rw [inf_dist, inf_dist, Hausdorff_dist, ← ennreal.to_real_add (inf_edist_ne_top hs) fin, ennreal.to_real_le_to_real (inf_edist_ne_top ht)], { exact inf_edist_le_inf_edist_add_Hausdorff_edist }, { exact ennreal.add_ne_top.2 ⟨inf_edist_ne_top hs, fin⟩ } end /-- The Hausdorff distance is invariant under isometries -/ lemma Hausdorff_dist_image (h : isometry Φ) : Hausdorff_dist (Φ '' s) (Φ '' t) = Hausdorff_dist s t := by simp [Hausdorff_dist, Hausdorff_edist_image h] /-- The Hausdorff distance satisfies the triangular inequality -/ lemma Hausdorff_dist_triangle (fin : Hausdorff_edist s t ≠ ⊤) : Hausdorff_dist s u ≤ Hausdorff_dist s t + Hausdorff_dist t u := begin by_cases Hausdorff_edist s u = ⊤, { calc Hausdorff_dist s u = 0 + 0 : by simp [Hausdorff_dist, h] ... ≤ Hausdorff_dist s t + Hausdorff_dist t u : add_le_add (Hausdorff_dist_nonneg) (Hausdorff_dist_nonneg) }, { have Dtu : Hausdorff_edist t u < ⊤ := calc Hausdorff_edist t u ≤ Hausdorff_edist t s + Hausdorff_edist s u : Hausdorff_edist_triangle ... = Hausdorff_edist s t + Hausdorff_edist s u : by simp [Hausdorff_edist_comm] ... < ⊤ : by simp [ennreal.add_lt_top]; simp [ennreal.lt_top_iff_ne_top, h, fin], rw [Hausdorff_dist, Hausdorff_dist, Hausdorff_dist, ← ennreal.to_real_add fin (lt_top_iff_ne_top.1 Dtu), ennreal.to_real_le_to_real h], { exact Hausdorff_edist_triangle }, { simp [ennreal.add_eq_top, lt_top_iff_ne_top.1 Dtu, fin] }} end /-- The Hausdorff distance satisfies the triangular inequality -/ lemma Hausdorff_dist_triangle' (fin : Hausdorff_edist t u ≠ ⊤) : Hausdorff_dist s u ≤ Hausdorff_dist s t + Hausdorff_dist t u := begin rw Hausdorff_edist_comm at fin, have I : Hausdorff_dist u s ≤ Hausdorff_dist u t + Hausdorff_dist t s := Hausdorff_dist_triangle fin, simpa [add_comm, Hausdorff_dist_comm] using I end /-- The Hausdorff distance between a set and its closure vanish -/ @[simp, priority 1100] lemma Hausdorff_dist_self_closure : Hausdorff_dist s (closure s) = 0 := by simp [Hausdorff_dist] /-- Replacing a set by its closure does not change the Hausdorff distance. -/ @[simp] lemma Hausdorff_dist_closure₁ : Hausdorff_dist (closure s) t = Hausdorff_dist s t := by simp [Hausdorff_dist] /-- Replacing a set by its closure does not change the Hausdorff distance. -/ @[simp] lemma Hausdorff_dist_closure₂ : Hausdorff_dist s (closure t) = Hausdorff_dist s t := by simp [Hausdorff_dist] /-- The Hausdorff distance between two sets and their closures coincide -/ @[simp] lemma Hausdorff_dist_closure : Hausdorff_dist (closure s) (closure t) = Hausdorff_dist s t := by simp [Hausdorff_dist] /-- Two sets are at zero Hausdorff distance if and only if they have the same closures -/ lemma Hausdorff_dist_zero_iff_closure_eq_closure (fin : Hausdorff_edist s t ≠ ⊤) : Hausdorff_dist s t = 0 ↔ closure s = closure t := by simp [Hausdorff_edist_zero_iff_closure_eq_closure.symm, Hausdorff_dist, ennreal.to_real_eq_zero_iff, fin] /-- Two closed sets are at zero Hausdorff distance if and only if they coincide -/ lemma Hausdorff_dist_zero_iff_eq_of_closed (hs : is_closed s) (ht : is_closed t) (fin : Hausdorff_edist s t ≠ ⊤) : Hausdorff_dist s t = 0 ↔ s = t := by simp [(Hausdorff_edist_zero_iff_eq_of_closed hs ht).symm, Hausdorff_dist, ennreal.to_real_eq_zero_iff, fin] end --section end metric --namespace
5eeb1a242a126cc1a6a3219a68371703ff84b568
da23b545e1653cafd4ab88b3a42b9115a0b1355f
/src/tidy/if_then_else.lean
6167035c7c38b53d2eb0f311f29a93145129999b
[]
no_license
minchaowu/lean-tidy
137f5058896e0e81dae84bf8d02b74101d21677a
2d4c52d66cf07c59f8746e405ba861b4fa0e3835
refs/heads/master
1,585,283,406,120
1,535,094,033,000
1,535,094,033,000
145,945,792
0
0
null
null
null
null
UTF-8
Lean
false
false
616
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison open tactic def if_then_else { α β : Type } { m : Type → Type } [monad m] [has_orelse m] ( i : m α ) ( t e : m β ) : m β := do r ← (i >> pure tt) <|> pure ff, if r then do t else do e def dependent_if_then_else { α β : Type } { m : Type → Type } [monad m] [has_orelse m] ( i : m α ) ( t : α → m β ) ( e : m β ) : m β := do r ← i >>= (λ x, pure (some x)) <|> pure none, match r with | some a := t a | none := e end
d8b72067d65888298ed0c3dc4361c1a019e85759
076f5040b63237c6dd928c6401329ed5adcb0e44
/instructor-notes/2019.10.props_and_proofs.lean
770b83ea2caafb2ff88c96a6b0a37090e04f2b9b
[]
no_license
kevinsullivan/uva-cs-dm-f19
0f123689cf6cb078f263950b18382a7086bf30be
09a950752884bd7ade4be33e9e89a2c4b1927167
refs/heads/master
1,594,771,841,541
1,575,853,850,000
1,575,853,850,000
205,433,890
4
9
null
1,571,592,121,000
1,567,188,539,000
Lean
UTF-8
Lean
false
false
11,495
lean
/- Key differences: Predicate vs propositional logic. (1) In propositional logic, variables range over Boolean truth values. A variable is either Boolean true or Boolean false. In predicate logic, variables can range over values of many types. A variable can represent a Boolean truth value, but also a natural number, a string, a person, a chemical, or whatever. Predicate logic thus has far greater expressiveness than propositional logic. (2) Predicate logic has quantifiers: forall (∀) and exists (∃). These allow one to express the ideas that some proposition is true of, every, or of at least one, object of some kind. (3) Predicate logic has predicates, which you can think of as propositions with parameters, such that the application of a predicate to argument values of its parameter types gives rise to a specific proposition about those specific argument values. In general, some of these propositions will be true and some won't be. Here's an example of a proposition in predicate logic that illustrates all three points. It states in precise mathematical terms that every natural number is equal to itself. -/ def every_nat_eq_itself := ∀ (n : ℕ), eq n n /- This example illustrates all three points. First, the logical variable, n, ranges over all values of type nat. Second, the proposition has a universal quantifier, asserting a subsequent claim about all values in the given domain of natural numbers. And, third, in the context of the "binding" of n to some arbitrary but specific natural number by the ∀, the proposition then asserts that a proposition about n it true using a two-argument predicate, eq. This is a predicate that asserts equality of two terms, and is usually written in infix notation as =. We can thus write the same proposition more naturally as follows. -/ def every_nat_eq_itself' := ∀ (n : ℕ), n = n. /- It will be important for you to learn both how to translate predicate logical expressions into natural language (here, English), and to express logical concepts in English in predicate logic. Let's start with some expressions in predicate logic. We imagine a world in which there are people and a relation between people that we will called "likes _ _", where the proposition "likes p q" asserts that person p likes person q. What, then, do the following proposition mean, translating from predicate logic to English? ∀ (p : Person), ∃ (q : Person), likes p q ∀ (p : Person), ∃ (q : Person), ¬ likes p q ∃ (p : Person), ∀ (q : Person), likes p q ∃ (p : Person), ∀ (q : Person), likes q p ∃ (p : Person), ∀ (q : Person), ¬ likes q p (∀ (p : Person), ∃ (q : Person), ¬ likes p q) → (∃ (p : Person), ∀ (q : Person), ¬ likes q p) (∃ (p : Person), ∀ (q : Person), ¬ likes q p) → (∀ (p : Person), ∃ (q : Person), ¬ likes p q) -/ /- One of the last two propositions is valid, in the sense that it's true no matter what Person and likes mean. Which is it? In predicate logic, we no longer evaluate the validity of a proposition using truth tables. What we need instead is a proof. A proof is a kind of mathematical object that we accept as compelling evidence for the truth of a given proposition. It will be important for you likewise to learn to express proofs in natural language, and to understand that, just like propositions and predicates, they be formalized as mathematical expressions/objects/values. Let's go for a natural language proof of this: (∃ (p : Person), ∀ (q : Person), ¬ likes q p) → (∀ (p : Person), ∃ (q : Person), ¬ likes p q) What is says is that if there is a person that no one likes, then everyone dislikes somebody. To prove such an implication we will assume that there is a proof of the premise (and that the premise is therefore true), and we will then show that given this assumption we can construct a proof of the conclusion. Step 1: To prove the proposition, we assume (∃ (p : Person), ∀ (q : Person), ¬ likes q p). Given (in the context of) this assumption, it remains to be proved that (∀ (p : Person), ∃ (q : Person), ¬ likes p q). Step 2: We've assumed that there is someone no one likes. We give that someone (whoever it is) a name: let's say, w. What we know about w is that ∀ (q : Person), ¬ likes q w. That is, we know everyone dislikes w in particular. Step 3: To prove our remaining goal, that (∀ (p : Person), ∃ (q : Person), ¬ likes p q), for each person p, we select w as a "witness" for q: a person that we expect will make the remaining proposition true. All that remains to be proved now is that ¬ likes p w. Step 4: To prove this, we just apply the fact from step 2 that ∀ (q : Person), ¬ likes q w, i.e., that *everyone* dislikes w, to conclude that p, in particular, dislikes w. We've thus shown that if there is someone everyone dislikes then everyone dislikes someone. For every (∀) person, p, it is enough to point to w to show there is (∃) someone that p dislikes. While p might dislike other people, we can be sure that he or she dislikes w because w is someone whom everyone dislikes. QED. [Latin for Quod Est Demonstratum. Thus it is shown/proved/demonstrated.] -/ /- So what are the *valid* forms of reasoning that we are allowed to use in constructing proofs of propositions in predicate logic? The answer is that we already have a fairly complete set from propositional logic that we are now validating! Warning: a few of the following rules are not valid. We will take the valid ones as *axioms* for use in proofs of propositions in predicate logic. def true_intro : pExp := pTrue def false_elim := pFalse ⇒ P def and_intro := P ⇒ Q ⇒ (P ∧ Q) def and_elim_left := (P ∧ Q) ⇒ P def and_elim_right := (P ∧ Q) ⇒ Q def or_intro_left := P ⇒ (P ∨ Q) def or_intro_right := Q ⇒ (P ∨ Q) def or_elim := (P ∨ Q) ⇒ (P ⇒ R) ⇒ (Q ⇒ R) ⇒ R def iff_intro := (P ⇒ Q) ⇒ (Q ⇒ P) ⇒ (P ↔ Q) def iff_elim_left := (P ↔ Q) ⇒ (P ⇒ Q) def iff_elim_right := (P ↔ Q) ⇒ (Q ⇒ P) def arrow_elim := (P ⇒ Q) ⇒ P ⇒ Q def affirm_consequence := (P ⇒ Q) ⇒ Q ⇒ P def resolution := (P ∨ Q) ⇒ (¬ Q ∨ R) ⇒ (P ∨ R) def unit_resolution := (P ∨ Q) ⇒ (¬ Q) ⇒ P def syllogism := (P ⇒ Q) ⇒ (Q ⇒ R) ⇒ (P ⇒ R) def modus_tollens := (P ⇒ Q) ⇒ ¬ Q ⇒ ¬ P def neg_elim := ¬ ¬ P ⇒ P def excluded_middle := P ∨ ¬ P def neg_intro := (P ⇒ pFalse) ⇒ ¬ P def affirm_disjunct := (P ∨ Q) ⇒ P ⇒ ¬ Q def deny_antecedent := (P ⇒ Q) ⇒ (¬ P ⇒ ¬ Q) -/ /- Finally, we get to the main idea behind automation of logic in tools like Lean: we represent predicate logic propositions as special types and values of these types as proofs of the propositions. Each of the propositions above then describes the type of a function that operates on such proofs, taking proofs and propositions as arguments and returning them as results. -/ /- That sounds super-complicated but let's make it super-easy. We'll do this by defining an ordinary type (day) and its values, and by then defining a logical type -- a proposition represented as a type -- and its values, its proofs. Here we go. -/ /- We define day to be a new type. -/ inductive day : Type /- Type is the type of *computational* types. Constructors define the values of the type. -/ | mon | tue | wed | thu | fri | sat | sun /- Now we can define variables of this type. -/ def d : day := day.mon /- A proposition with proof constructors. -/ inductive emily's_from_cville : Prop /- Constructors define the proofs of the proposition Proofs in Lean are values of *logical* types. -/ | drivers_license | passport | utility_bill open emily's_from_cville def a_proof : emily's_from_cville := passport theorem a_proof' : emily's_from_cville := drivers_license /- Another data (computational) type. -/ inductive person : Type | mari | jose | jane | bill open person /- A predicate is a proposition with a parameter. When applied to an argument of the right type, the result is a proposition. The constructors define the set of proofs of the corresponding propositions. -/ inductive is_from_cville : person → Prop | jose_birth_cert : is_from_cville jose | jane_birth_cert : is_from_cville jane open is_from_cville theorem jane's_from_cville : is_from_cville jane := jane_birth_cert /- Some comments about function definitions. Consider the following simple definition. -/ def evenb (n : ℕ) : bool := n % 2 = 0 #eval evenb 3 #eval evenb 4 #check evenb def evenb' : ℕ → bool := λ n, n % 2 = 0 def evenb'' : Π (n : ℕ), bool := λ n, n % 2 = 0 #eval evenb'' 5 def evenb''' : ∀ (n : ℕ), bool := λ n, n % 2 = 0 #eval evenb''' 6 /- Predicates are often used to represent properties of objects, here, a property of people, namely the property of a person being from Cville. -/ inductive is_zero : ℕ → Prop | zmk: ∀ (n : ℕ), n = 0 → is_zero n open is_zero theorem zero_is_zero_0 : is_zero 0 := zmk 0 rfl /- Even: inductively defined proofs -/ inductive is_even : ℕ → Prop | pf_zero_is_even : (is_even 0) | pf_n_minus_two_is_even : ∀ (n : ℕ), is_even n → is_even (nat.succ (nat.succ n)) open is_even theorem zero_is_even : is_even 0 := pf_zero_is_even theorem zero_is_even' : is_even 0 := begin exact pf_zero_is_even end /- Inductive -/ theorem two_is_even : is_even 2 := pf_n_minus_two_is_even 0 zero_is_even theorem two_is_even' : is_even 2 := begin apply pf_n_minus_two_is_even 0 zero_is_even, end theorem two_is_even'' : is_even 2 := begin apply pf_n_minus_two_is_even 0 _, exact zero_is_even, end theorem two_is_even''' : is_even 2 := begin apply pf_n_minus_two_is_even _ _, exact zero_is_even, end theorem two_is_even'''' : is_even 2 := begin apply pf_n_minus_two_is_even, exact zero_is_even, end theorem four_is_even : is_even 4 := pf_n_minus_two_is_even 2 two_is_even theorem four_is_even' : is_even 4 := begin apply pf_n_minus_two_is_even 2 two_is_even, end theorem four_is_even'' : is_even 4 := begin apply pf_n_minus_two_is_even, apply two_is_even, end theorem four_is_even''' : is_even 4 := begin apply pf_n_minus_two_is_even, apply pf_n_minus_two_is_even, apply zero_is_even, end theorem ten_is_even' : is_even 10 := begin apply pf_n_minus_two_is_even, apply pf_n_minus_two_is_even, apply pf_n_minus_two_is_even, apply pf_n_minus_two_is_even, apply pf_n_minus_two_is_even, exact zero_is_even, end #print ten_is_even' theorem ten_is_even'' : is_even 10 := begin repeat {apply pf_n_minus_two_is_even}, exact zero_is_even, end inductive successor_of : ℕ → ℕ → Prop | mk : ∀ (n : ℕ), successor_of (nat.succ n) n theorem five_succ_four : successor_of 5 4 := successor_of.mk 4 inductive equal_to_nat : ℕ → ℕ → Prop | refl : ∀ (n : ℕ), equal_to_nat n n theorem five_equals_five : equal_to_nat 5 5 := equal_to_nat.refl 5 theorem five_equals_five' : equal_to_nat 5 5 := begin apply equal_to_nat.refl _, end inductive equal_to_nat' (n : ℕ) : ℕ → Prop | refl : ∀ (n : ℕ), equal_to_nat' n #check equal_to_nat #check equal_to_nat' theorem five_eq_five'' : equal_to_nat' 5 5 := equal_to_nat'.refl 5 5 inductive equal_to {α : Type} : α → α → Prop | refl : ∀ (a : α), equal_to a a
c39e8eb34635342143f92242149047087712a333
7850aae797be6c31052ce4633d86f5991178d3df
/src/Lean/Elab/Util.lean
c1c6cd52ee4dfff7ed38ae28a330442cea039ca8
[ "Apache-2.0" ]
permissive
miriamgoetze/lean4
4dc24d4dbd360cc969713647c2958c6691947d16
062cc5d5672250be456a168e9c7b9299a9c69bdb
refs/heads/master
1,685,865,971,011
1,624,107,703,000
1,624,107,703,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,861
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.Trace import Lean.Parser.Syntax import Lean.Parser.Extension import Lean.KeyedDeclsAttribute import Lean.Elab.Exception namespace Lean def Syntax.prettyPrint (stx : Syntax) : Format := match stx.unsetTrailing.reprint with -- TODO use syntax pretty printer | some str => format str.toFormat | none => format stx def MacroScopesView.format (view : MacroScopesView) (mainModule : Name) : Format := fmt $ if view.scopes.isEmpty then view.name else if view.mainModule == mainModule then view.scopes.foldl Name.mkNum (view.name ++ view.imported) else view.scopes.foldl Name.mkNum (view.name ++ view.imported ++ view.mainModule) namespace Elab def expandOptNamedPrio (stx : Syntax) : MacroM Nat := if stx.isNone then return eval_prio default else match stx[0] with | `(Parser.Command.namedPrio| (priority := $prio)) => evalPrio prio | _ => Macro.throwUnsupported def expandOptNamedName (stx : Syntax) : MacroM (Option Name) := do if stx.isNone then return none else match stx[0] with | `(Parser.Command.namedName| (name := $name)) => return name.getId | _ => Macro.throwUnsupported structure MacroStackElem where before : Syntax after : Syntax abbrev MacroStack := List MacroStackElem /- If `ref` does not have position information, then try to use macroStack -/ def getBetterRef (ref : Syntax) (macroStack : MacroStack) : Syntax := match ref.getPos? with | some _ => ref | none => match macroStack.find? (·.before.getPos? != none) with | some elem => elem.before | none => ref register_builtin_option pp.macroStack : Bool := { defValue := false group := "pp" descr := "dispaly macro expansion stack" } def addMacroStack {m} [Monad m] [MonadOptions m] (msgData : MessageData) (macroStack : MacroStack) : m MessageData := do if !pp.macroStack.get (← getOptions) then pure msgData else match macroStack with | [] => pure msgData | stack@(top::_) => let msgData := msgData ++ Format.line ++ "with resulting expansion" ++ indentD top.after pure $ stack.foldl (fun (msgData : MessageData) (elem : MacroStackElem) => msgData ++ Format.line ++ "while expanding" ++ indentD elem.before) msgData def checkSyntaxNodeKind (k : Name) : AttrM Name := do if Parser.isValidSyntaxNodeKind (← getEnv) k then pure k else throwError "failed" def checkSyntaxNodeKindAtNamespacesAux (k : Name) : Name → AttrM Name | n@(Name.str p _ _) => checkSyntaxNodeKind (n ++ k) <|> checkSyntaxNodeKindAtNamespacesAux k p | _ => throwError "failed" def checkSyntaxNodeKindAtNamespaces (k : Name) : AttrM Name := do let ctx ← read checkSyntaxNodeKindAtNamespacesAux k ctx.currNamespace def syntaxNodeKindOfAttrParam (defaultParserNamespace : Name) (stx : Syntax) : AttrM SyntaxNodeKind := do let k ← Attribute.Builtin.getId stx checkSyntaxNodeKind k <|> checkSyntaxNodeKindAtNamespaces k <|> checkSyntaxNodeKind (defaultParserNamespace ++ k) <|> throwError "invalid syntax node kind '{k}'" private unsafe def evalSyntaxConstantUnsafe (env : Environment) (opts : Options) (constName : Name) : ExceptT String Id Syntax := env.evalConstCheck Syntax opts `Lean.Syntax constName @[implementedBy evalSyntaxConstantUnsafe] constant evalSyntaxConstant (env : Environment) (opts : Options) (constName : Name) : ExceptT String Id Syntax := throw "" unsafe def mkElabAttribute (γ) (attrDeclName attrBuiltinName attrName : Name) (parserNamespace : Name) (typeName : Name) (kind : String) : IO (KeyedDeclsAttribute γ) := KeyedDeclsAttribute.init { builtinName := attrBuiltinName name := attrName descr := kind ++ " elaborator" valueTypeName := typeName evalKey := fun _ stx => syntaxNodeKindOfAttrParam parserNamespace stx } attrDeclName unsafe def mkMacroAttributeUnsafe : IO (KeyedDeclsAttribute Macro) := mkElabAttribute Macro `Lean.Elab.macroAttribute `builtinMacro `macro Name.anonymous `Lean.Macro "macro" @[implementedBy mkMacroAttributeUnsafe] constant mkMacroAttribute : IO (KeyedDeclsAttribute Macro) builtin_initialize macroAttribute : KeyedDeclsAttribute Macro ← mkMacroAttribute private def expandMacroFns (stx : Syntax) : List Macro → MacroM Syntax | [] => throw Macro.Exception.unsupportedSyntax | m::ms => do try m stx catch | Macro.Exception.unsupportedSyntax => expandMacroFns stx ms | ex => throw ex def getMacros (env : Environment) : Macro := fun stx => expandMacroFns stx (macroAttribute.getValues env stx.getKind) class MonadMacroAdapter (m : Type → Type) where getCurrMacroScope : m MacroScope getNextMacroScope : m MacroScope setNextMacroScope : MacroScope → m Unit instance (m n) [MonadLift m n] [MonadMacroAdapter m] : MonadMacroAdapter n := { getCurrMacroScope := liftM (MonadMacroAdapter.getCurrMacroScope : m _), getNextMacroScope := liftM (MonadMacroAdapter.getNextMacroScope : m _), setNextMacroScope := fun s => liftM (MonadMacroAdapter.setNextMacroScope s : m _) } private def expandMacro? (env : Environment) (stx : Syntax) : MacroM (Option Syntax) := do try let newStx ← getMacros env stx pure (some newStx) catch | Macro.Exception.unsupportedSyntax => pure none | ex => throw ex def liftMacroM {α} {m : Type → Type} [Monad m] [MonadMacroAdapter m] [MonadEnv m] [MonadRecDepth m] [MonadError m] [MonadResolveName m] [MonadTrace m] [MonadOptions m] [AddMessageContext m] (x : MacroM α) : m α := do let env ← getEnv let currNamespace ← getCurrNamespace let openDecls ← getOpenDecls let methods := Macro.mkMethods { expandMacro? := expandMacro? env hasDecl := fun declName => return env.contains declName getCurrNamespace := return currNamespace resolveNamespace? := fun n => return ResolveName.resolveNamespace? env currNamespace openDecls n resolveGlobalName := fun n => return ResolveName.resolveGlobalName env currNamespace openDecls n } match x { methods := methods ref := ← getRef currMacroScope := ← MonadMacroAdapter.getCurrMacroScope mainModule := env.mainModule currRecDepth := ← MonadRecDepth.getRecDepth maxRecDepth := ← MonadRecDepth.getMaxRecDepth } { macroScope := (← MonadMacroAdapter.getNextMacroScope) } with | EStateM.Result.error Macro.Exception.unsupportedSyntax _ => throwUnsupportedSyntax | EStateM.Result.error (Macro.Exception.error ref msg) _ => throwErrorAt ref msg | EStateM.Result.ok a s => MonadMacroAdapter.setNextMacroScope s.macroScope s.traceMsgs.reverse.forM fun (clsName, msg) => trace clsName fun _ => msg pure a @[inline] def adaptMacro {m : Type → Type} [Monad m] [MonadMacroAdapter m] [MonadEnv m] [MonadRecDepth m] [MonadError m] [MonadResolveName m] [MonadTrace m] [MonadOptions m] [AddMessageContext m] (x : Macro) (stx : Syntax) : m Syntax := liftMacroM (x stx) partial def mkUnusedBaseName (baseName : Name) : MacroM Name := do let currNamespace ← Macro.getCurrNamespace if ← Macro.hasDecl (currNamespace ++ baseName) then let rec loop (idx : Nat) := do let name := baseName.appendIndexAfter idx if ← Macro.hasDecl (currNamespace ++ name) then loop (idx+1) else name loop 1 else return baseName builtin_initialize registerTraceClass `Elab registerTraceClass `Elab.step end Lean.Elab
3bca52c4215e806b3471c2214ceadb1e463c8c22
562dafcca9e8bf63ce6217723b51f32e89cdcc80
/src/super/inhabited.lean
d9ff75d6161ce35c5f51172b1a781533ad47b743
[]
no_license
digama0/super
660801ef3edab2c046d6a01ba9bbce53e41523e8
976957fe46128e6ef057bc771f532c27cce5a910
refs/heads/master
1,606,987,814,510
1,498,621,778,000
1,498,621,778,000
95,626,306
0
0
null
1,498,621,692,000
1,498,621,692,000
null
UTF-8
Lean
false
false
2,498
lean
/- Copyright (c) 2017 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import .clause_ops .prover_state open expr tactic monad namespace super meta def try_assumption_lookup_left (c : clause) : tactic (list clause) := on_first_left c $ λtype, do ass ← find_assumption type, return [([], ass)] meta def try_nonempty_lookup_left (c : clause) : tactic (list clause) := on_first_left_dn c $ λhnx, match is_local_not c.local_false hnx.local_type with | some type := do univ ← infer_univ type, lf_univ ← infer_univ c.local_false, guard $ lf_univ = level.zero, inst ← mk_instance (app (const ``nonempty [univ]) type), instt ← infer_type inst, return [([], app_of_list (const ``nonempty.elim [univ]) [type, c.local_false, inst, hnx])] | _ := failed end meta def try_nonempty_left (c : clause) : tactic (list clause) := on_first_left c $ λprop, match prop with | (app (const ``nonempty [u]) type) := do x ← mk_local_def `x type, return [([x], app_of_list (const ``nonempty.intro [u]) [type, x])] | _ := failed end meta def try_nonempty_right (c : clause) : tactic (list clause) := on_first_right c $ λhnonempty, match hnonempty.local_type with | (app (const ``nonempty [u]) type) := do lf_univ ← infer_univ c.local_false, guard $ lf_univ = level.zero, hnx ← mk_local_def `nx (imp type c.local_false), return [([hnx], app_of_list (const ``nonempty.elim [u]) [type, c.local_false, hnonempty, hnx])] | _ := failed end meta def try_inhabited_left (c : clause) : tactic (list clause) := on_first_left c $ λprop, match prop with | (app (const ``inhabited [u]) type) := do x ← mk_local_def `x type, return [([x], app_of_list (const ``inhabited.mk [u]) [type, x])] | _ := failed end meta def try_inhabited_right (c : clause) : tactic (list clause) := on_first_right' c $ λhinh, match hinh.local_type with | (app (const ``inhabited [u]) type) := return [([], app_of_list (const ``inhabited.default [u]) [type, hinh])] | _ := failed end @[super.inf] meta def inhabited_infs : inf_decl := inf_decl.mk 10 $ take given, do for' [try_assumption_lookup_left, try_nonempty_lookup_left, try_nonempty_left, try_nonempty_right, try_inhabited_left, try_inhabited_right] $ λr, simp_if_successful given (r given.c) end super
d117c31f8ae75291e5b58cbcd79f7b0d0b22d413
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/data/bool/lemmas.lean
9847373a09e13609bacab38500c7d4487af61625
[ "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
4,784
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.data.bool.basic init.meta attribute [simp] cond bor band bnot bxor @[simp] lemma {u} cond_a_a {α : Type u} (b : bool) (a : α) : cond b a a = a := by cases b; simp @[simp] lemma band_self (b : bool) : b && b = b := by cases b; simp @[simp] lemma band_tt (b : bool) : b && tt = b := by cases b; simp @[simp] lemma band_ff (b : bool) : b && ff = ff := by cases b; simp @[simp] lemma tt_band (b : bool) : tt && b = b := by cases b; simp @[simp] lemma ff_band (b : bool) : ff && b = ff := by cases b; simp @[simp] lemma bor_self (b : bool) : b || b = b := by cases b; simp @[simp] lemma bor_tt (b : bool) : b || tt = tt := by cases b; simp @[simp] lemma bor_ff (b : bool) : b || ff = b := by cases b; simp @[simp] lemma tt_bor (b : bool) : tt || b = tt := by cases b; simp @[simp] lemma ff_bor (b : bool) : ff || b = b := by cases b; simp @[simp] lemma bxor_self (b : bool) : bxor b b = ff := by cases b; simp @[simp] lemma bxor_tt (b : bool) : bxor b tt = bnot b := by cases b; simp lemma bxor_ff (b : bool) : bxor b ff = b := by cases b; simp @[simp] lemma tt_bxor (b : bool) : bxor tt b = bnot b := by cases b; simp lemma ff_bxor (b : bool) : bxor ff b = b := by cases b; simp @[simp] lemma bnot_bnot (b : bool) : bnot (bnot b) = b := by cases b; simp lemma tt_eq_ff_eq_false : ¬(tt = ff) := by contradiction lemma ff_eq_tt_eq_false : ¬(ff = tt) := by contradiction @[simp] lemma eq_ff_eq_not_eq_tt (b : bool) : (¬(b = tt)) = (b = ff) := by cases b; simp @[simp] lemma eq_tt_eq_not_eq_ff (b : bool) : (¬(b = ff)) = (b = tt) := by cases b; simp lemma eq_ff_of_not_eq_tt {b : bool} : (¬(b = tt)) → (b = ff) := eq.mp (eq_ff_eq_not_eq_tt b) lemma eq_tt_of_not_eq_ff {b : bool} : (¬(b = ff)) → (b = tt) := eq.mp (eq_tt_eq_not_eq_ff b) @[simp] lemma band_eq_true_eq_eq_tt_and_eq_tt (a b : bool) : (a && b = tt) = (a = tt ∧ b = tt) := by cases a; cases b; simp @[simp] lemma bor_eq_true_eq_eq_tt_or_eq_tt (a b : bool) : (a || b = tt) = (a = tt ∨ b = tt) := by cases a; cases b; simp @[simp] lemma bnot_eq_true_eq_eq_ff (a : bool) : (bnot a = tt) = (a = ff) := by cases a; simp @[simp] lemma band_eq_false_eq_eq_ff_or_eq_ff (a b : bool) : (a && b = ff) = (a = ff ∨ b = ff) := by cases a; cases b; simp @[simp] lemma bor_eq_false_eq_eq_ff_and_eq_ff (a b : bool) : (a || b = ff) = (a = ff ∧ b = ff) := by cases a; cases b; simp @[simp] lemma bnot_eq_ff_eq_eq_tt (a : bool) : (bnot a = ff) = (a = tt) := by cases a; simp @[simp] lemma coe_ff : ↑ff = false := show (ff = tt) = false, by simp @[simp] lemma coe_tt : ↑tt = true := show (tt = tt) = true, by simp @[simp] lemma coe_sort_ff : ↥ff = false := show (ff = tt) = false, by simp @[simp] lemma coe_sort_tt : ↥tt = true := show (tt = tt) = true, by simp @[simp] theorem to_bool_iff (p : Prop) [d : decidable p] : (to_bool p = tt) ↔ p := match d with | is_true hp := ⟨λh, hp, λ_, rfl⟩ | is_false hnp := ⟨λh, bool.no_confusion h, λhp, absurd hp hnp⟩ end theorem to_bool_true {p : Prop} [decidable p] : p → to_bool p := (to_bool_iff p).2 theorem to_bool_tt {p : Prop} [decidable p] : p → to_bool p = tt := to_bool_true theorem of_to_bool_true {p : Prop} [decidable p] : to_bool p → p := (to_bool_iff p).1 theorem bool_iff_false {b : bool} : ¬ b ↔ b = ff := by cases b; exact dec_trivial theorem bool_eq_false {b : bool} : ¬ b → b = ff := bool_iff_false.1 @[simp] theorem to_bool_ff_iff (p : Prop) [decidable p] : to_bool p = ff ↔ ¬p := bool_iff_false.symm.trans (not_congr (to_bool_iff _)) theorem to_bool_ff {p : Prop} [decidable p] : ¬p → to_bool p = ff := (to_bool_ff_iff p).2 theorem of_to_bool_ff {p : Prop} [decidable p] : to_bool p = ff → ¬p := (to_bool_ff_iff p).1 theorem to_bool_congr {p q : Prop} [decidable p] [decidable q] (h : p ↔ q) : to_bool p = to_bool q := begin induction h' : to_bool q, exact to_bool_ff (mt h.1 $ of_to_bool_ff h'), exact to_bool_true (h.2 $ of_to_bool_true h') end @[simp] theorem bor_coe_iff (a b : bool) : a || b ↔ a ∨ b := by cases a; cases b; exact dec_trivial @[simp] theorem band_coe_iff (a b : bool) : a && b ↔ a ∧ b := by cases a; cases b; exact dec_trivial @[simp] theorem bxor_coe_iff (a b : bool) : bxor a b ↔ xor a b := by cases a; cases b; exact dec_trivial @[simp] theorem ite_eq_tt_distrib (c : Prop) [decidable c] (a b : bool) : ((if c then a else b) = tt) = (if c then a = tt else b = tt) := by by_cases c; simp [*] @[simp] theorem ite_eq_ff_distrib (c : Prop) [decidable c] (a b : bool) : ((if c then a else b) = ff) = (if c then a = ff else b = ff) := by by_cases c; simp [*]
16c4720b309b85b332a6df162f961a0816252ab7
08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4
/src/Lean/Util/Trace.lean
318042a5536fad33a1c88b9aed94940851273e57
[ "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "Apache-2.0", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
gebner/lean4
d51c4922640a52a6f7426536ea669ef18a1d9af5
8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f
refs/heads/master
1,685,732,780,391
1,672,962,627,000
1,673,459,398,000
373,307,283
0
0
Apache-2.0
1,691,316,730,000
1,622,669,271,000
Lean
UTF-8
Lean
false
false
9,397
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich, Leonardo de Moura -/ import Lean.Exception /-! # Trace messages Trace messages explain to the user what problem Lean solved and what steps it took. Think of trace messages like a figure in a paper. They are shown in the editor as a collapsible tree, usually as `[class.name] message ▸`. Every trace node has a class name, a message, and an array of children. This module provides the API to produce trace messages, the key entry points are: - ``registerTraceMessage `class.name`` registers a trace class - ``withTraceNode `class.name (fun result => return msg) do body` produces a trace message containing the trace messages in `body` as children - `trace[class.name] msg` produces a trace message without children Users can enable trace options for a class using `set_option trace.class.name true`. This only enables trace messages for the `class.name` trace class as well as child classes that are explicitly marked as inherited (see `registerTraceClass`). Internally, trace messages are stored as `MessageData`: `.trace cls msg #[.trace .., .trace ..]` When writing trace messages, try to follow these guidelines: 1. **Expansion progressively increases detail.** Each level of expansion (of the trace node in the editor) should reveal more details. For example, the unexpanded node should show the top-level goal. Expanding it should show a list of steps. Expanding one of the steps then shows what happens during that step. 2. **One trace message per step.** The `[trace.class]` marker functions as a visual bullet point, making it easy to identify the different steps at a glance. 3. **Outcome first.** The top-level trace message should already show whether the action failed or succeeded, as opposed to a "success" trace message that comes pages later. 4. **Be concise.** Keep messages short. Avoid repetitive text. (This is also why the editor plugins abbreviate the common prefixes.) 5. **Emoji are concisest.** Several helper functions in this module help with a consistent emoji language. 6. **Good defaults.** Setting `set_option trace.Meta.synthInstance true` (etc.) should produce great trace messages out-of-the-box, without needing extra options to tweak it. -/ namespace Lean structure TraceElem where ref : Syntax msg : MessageData deriving Inhabited structure TraceState where traces : PersistentArray TraceElem := {} deriving Inhabited builtin_initialize inheritedTraceOptions : IO.Ref (HashSet Name) ← IO.mkRef ∅ class MonadTrace (m : Type → Type) where modifyTraceState : (TraceState → TraceState) → m Unit getTraceState : m TraceState export MonadTrace (getTraceState modifyTraceState) instance (m n) [MonadLift m n] [MonadTrace m] : MonadTrace n where modifyTraceState := fun f => liftM (modifyTraceState f : m _) getTraceState := liftM (getTraceState : m _) variable {α : Type} {m : Type → Type} [Monad m] [MonadTrace m] [MonadOptions m] [MonadLiftT IO m] def printTraces : m Unit := do for {msg, ..} in (← getTraceState).traces do IO.println (← msg.format) def resetTraceState : m Unit := modifyTraceState (fun _ => {}) private def checkTraceOption (inherited : HashSet Name) (opts : Options) (cls : Name) : Bool := !opts.isEmpty && go (`trace ++ cls) where go (opt : Name) : Bool := if let some enabled := opts.get? opt then enabled else if let .str parent _ := opt then inherited.contains opt && go parent else false def isTracingEnabledFor (cls : Name) : m Bool := do let inherited ← (inheritedTraceOptions.get : IO _) pure (checkTraceOption inherited (← getOptions) cls) @[inline] def getTraces : m (PersistentArray TraceElem) := do let s ← getTraceState pure s.traces @[inline] def modifyTraces (f : PersistentArray TraceElem → PersistentArray TraceElem) : m Unit := modifyTraceState fun s => { s with traces := f s.traces } @[inline] def setTraceState (s : TraceState) : m Unit := modifyTraceState fun _ => s private def getResetTraces : m (PersistentArray TraceElem) := do let oldTraces ← getTraces modifyTraces fun _ => {} pure oldTraces section variable [MonadRef m] [AddMessageContext m] [MonadOptions m] def addRawTrace (msg : MessageData) : m Unit := do let ref ← getRef let msg ← addMessageContext msg modifyTraces (·.push { ref, msg }) def addTrace (cls : Name) (msg : MessageData) : m Unit := do let ref ← getRef let msg ← addMessageContext msg modifyTraces (·.push { ref, msg := .trace cls msg #[] }) @[inline] def trace (cls : Name) (msg : Unit → MessageData) : m Unit := do if (← isTracingEnabledFor cls) then addTrace cls (msg ()) @[inline] def traceM (cls : Name) (mkMsg : m MessageData) : m Unit := do if (← isTracingEnabledFor cls) then let msg ← mkMsg addTrace cls msg private def addTraceNodeCore (oldTraces : PersistentArray TraceElem) (cls : Name) (ref : Syntax) (msg : MessageData) (collapsed : Bool) : m Unit := modifyTraces fun newTraces => oldTraces.push { ref, msg := .trace cls msg (newTraces.toArray.map (·.msg)) collapsed } private def addTraceNode (oldTraces : PersistentArray TraceElem) (cls : Name) (ref : Syntax) (msg : MessageData) (collapsed : Bool) : m Unit := withRef ref do let msg ← addMessageContext msg addTraceNodeCore oldTraces cls ref msg collapsed def withSeconds [Monad m] [MonadLiftT BaseIO m] (act : m α) : m (α × Float) := do let start ← IO.monoNanosNow let a ← act let stop ← IO.monoNanosNow return (a, (stop - start).toFloat / 1000000000) def withOptProfile [Monad m] [MonadLiftT BaseIO m] [MonadOptions m] (act : m α) : m (α × Option Float) := do if (← getBoolOption `profiler) then (fun (a, s) => (a, some s)) <$> withSeconds act else (·, none) <$> act def withTraceNode [MonadExcept ε m] [MonadLiftT BaseIO m] (cls : Name) (msg : Except ε α → m MessageData) (k : m α) (collapsed := true) : m α := do if !(← isTracingEnabledFor cls) then k else let ref ← getRef let oldTraces ← getResetTraces let (res, secs?) ← withOptProfile <| observing k let mut m ← msg res if let some secs := secs? then m := m!"[{secs}s] {m}" addTraceNode oldTraces cls ref m collapsed MonadExcept.ofExcept res def withTraceNode' [MonadExcept Exception m] [MonadLiftT BaseIO m] (cls : Name) (k : m (α × MessageData)) (collapsed := true) : m α := let msg := fun | .ok (_, msg) => return msg | .error err => return err.toMessageData Prod.fst <$> withTraceNode cls msg k collapsed end /-- Registers a trace class. By default, trace classes are not inherited; that is, `set_option trace.foo true` does not imply `set_option trace.foo.bar true`. Calling ``registerTraceClass `foo.bar (inherited := true)`` enables this inheritance on an opt-in basis. -/ def registerTraceClass (traceClassName : Name) (inherited := false) (ref : Name := by exact decl_name%) : IO Unit := do let optionName := `trace ++ traceClassName registerOption optionName { declName := ref group := "trace" defValue := false descr := "enable/disable tracing for the given module and submodules" } if inherited then inheritedTraceOptions.modify (·.insert optionName) macro "trace[" id:ident "]" s:(interpolatedStr(term) <|> term) : doElem => do let msg ← if s.raw.getKind == interpolatedStrKind then `(m! $(⟨s⟩)) else `(($(⟨s⟩) : MessageData)) `(doElem| do let cls := $(quote id.getId.eraseMacroScopes) if (← Lean.isTracingEnabledFor cls) then Lean.addTrace cls $msg) def bombEmoji := "💥" def checkEmoji := "✅" def crossEmoji := "❌" def exceptBoolEmoji : Except ε Bool → String | .error _ => bombEmoji | .ok true => checkEmoji | .ok false => crossEmoji def exceptOptionEmoji : Except ε (Option α) → String | .error _ => bombEmoji | .ok (some _) => checkEmoji | .ok none => crossEmoji class ExceptToEmoji (ε α : Type) where toEmoji : Except ε α → String instance : ExceptToEmoji ε Bool where toEmoji := exceptBoolEmoji instance : ExceptToEmoji ε (Option α) where toEmoji := exceptOptionEmoji /-- Similar to `withTraceNode`, but msg is constructed **before** executing `k`. This is important when debugging methods such as `isDefEq`, and we want to generate the message before `k` updates the metavariable assignment. The class `ExceptToEmoji` is used to convert the result produced by `k` into an emoji (e.g., `💥`, `✅`, `❌`). TODO: find better name for this function. -/ def withTraceNodeBefore [MonadRef m] [AddMessageContext m] [MonadOptions m] [MonadExcept ε m] [MonadLiftT BaseIO m] [ExceptToEmoji ε α] (cls : Name) (msg : m MessageData) (k : m α) (collapsed := true) : m α := do if !(← isTracingEnabledFor cls) then k else let ref ← getRef let oldTraces ← getResetTraces let msg ← withRef ref do addMessageContext (← msg) let (res, secs?) ← withOptProfile <| observing k let mut msg := m!"{ExceptToEmoji.toEmoji res} {msg}" if let some secs := secs? then msg := m!"[{secs}s] {msg}" addTraceNodeCore oldTraces cls ref msg collapsed MonadExcept.ofExcept res end Lean
8c24631ffb1f3a61b7428e65a03b483414da4b17
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/typevec.lean
8236b115dee8b2df000185cfc5f69b0210dcc929
[ "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
24,496
lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Mario Carneiro, Simon Hudon -/ import data.fin.fin2 import logic.function.basic import tactic.basic /-! # Tuples of types, and their categorical structure. ## Features * `typevec n` - n-tuples of types * `α ⟹ β` - n-tuples of maps * `f ⊚ g` - composition Also, support functions for operating with n-tuples of types, such as: * `append1 α β` - append type `β` to n-tuple `α` to obtain an (n+1)-tuple * `drop α` - drops the last element of an (n+1)-tuple * `last α` - returns the last element of an (n+1)-tuple * `append_fun f g` - appends a function g to an n-tuple of functions * `drop_fun f` - drops the last function from an n+1-tuple * `last_fun f` - returns the last function of a tuple. Since e.g. `append1 α.drop α.last` is propositionally equal to `α` but not definitionally equal to it, we need support functions and lemmas to mediate between constructions. -/ universes u v w /-- n-tuples of types, as a category -/ def typevec (n : ℕ) := fin2 n → Type* instance {n} : inhabited (typevec.{u} n) := ⟨ λ _, punit ⟩ namespace typevec variable {n : ℕ} /-- arrow in the category of `typevec` -/ def arrow (α β : typevec n) := Π i : fin2 n, α i → β i localized "infixl ` ⟹ `:40 := typevec.arrow" in mvfunctor instance arrow.inhabited (α β : typevec n) [Π i, inhabited (β i)] : inhabited (α ⟹ β) := ⟨ λ _ _, default _ ⟩ /-- identity of arrow composition -/ def id {α : typevec n} : α ⟹ α := λ i x, x /-- arrow composition in the category of `typevec` -/ def comp {α β γ : typevec n} (g : β ⟹ γ) (f : α ⟹ β) : α ⟹ γ := λ i x, g i (f i x) localized "infixr ` ⊚ `:80 := typevec.comp" in mvfunctor -- type as \oo @[simp] theorem id_comp {α β : typevec n} (f : α ⟹ β) : id ⊚ f = f := rfl @[simp] theorem comp_id {α β : typevec n} (f : α ⟹ β) : f ⊚ id = f := rfl theorem comp_assoc {α β γ δ : typevec n} (h : γ ⟹ δ) (g : β ⟹ γ) (f : α ⟹ β) : (h ⊚ g) ⊚ f = h ⊚ g ⊚ f := rfl /-- Support for extending a typevec by one element. -/ def append1 (α : typevec n) (β : Type*) : typevec (n+1) | (fin2.fs i) := α i | fin2.fz := β infixl ` ::: `:67 := append1 /-- retain only a `n-length` prefix of the argument -/ def drop (α : typevec.{u} (n+1)) : typevec n := λ i, α i.fs /-- take the last value of a `(n+1)-length` vector -/ def last (α : typevec.{u} (n+1)) : Type* := α fin2.fz instance last.inhabited (α : typevec (n+1)) [inhabited (α fin2.fz)] : inhabited (last α) := ⟨ (default (α fin2.fz) : α fin2.fz) ⟩ theorem drop_append1 {α : typevec n} {β : Type*} {i : fin2 n} : drop (append1 α β) i = α i := rfl theorem drop_append1' {α : typevec n} {β : Type*} : drop (append1 α β) = α := by ext; apply drop_append1 theorem last_append1 {α : typevec n} {β : Type*} : last (append1 α β) = β := rfl @[simp] theorem append1_drop_last (α : typevec (n+1)) : append1 (drop α) (last α) = α := funext $ λ i, by cases i; refl /-- cases on `(n+1)-length` vectors -/ @[elab_as_eliminator] def append1_cases {C : typevec (n+1) → Sort u} (H : ∀ α β, C (append1 α β)) (γ) : C γ := by rw [← @append1_drop_last _ γ]; apply H @[simp] theorem append1_cases_append1 {C : typevec (n+1) → Sort u} (H : ∀ α β, C (append1 α β)) (α β) : @append1_cases _ C H (append1 α β) = H α β := rfl /-- append an arrow and a function for arbitrary source and target type vectors -/ def split_fun {α α' : typevec (n+1)} (f : drop α ⟹ drop α') (g : last α → last α') : α ⟹ α' | (fin2.fs i) := f i | fin2.fz := g /-- append an arrow and a function as well as their respective source and target types / typevecs -/ def append_fun {α α' : typevec n} {β β' : Type*} (f : α ⟹ α') (g : β → β') : append1 α β ⟹ append1 α' β' := split_fun f g infixl ` ::: ` := append_fun /-- split off the prefix of an arrow -/ def drop_fun {α β : typevec (n+1)} (f : α ⟹ β) : drop α ⟹ drop β := λ i, f i.fs /-- split off the last function of an arrow -/ def last_fun {α β : typevec (n+1)} (f : α ⟹ β) : last α → last β := f fin2.fz /-- arrow in the category of `0-length` vectors -/ def nil_fun {α : typevec 0} {β : typevec 0} : α ⟹ β := λ i, fin2.elim0 i theorem eq_of_drop_last_eq {α β : typevec (n+1)} {f g : α ⟹ β} (h₀ : drop_fun f = drop_fun g) (h₁ : last_fun f = last_fun g) : f = g := by replace h₀ := congr_fun h₀; ext1 (ieq | ⟨j, ieq⟩); apply_assumption @[simp] theorem drop_fun_split_fun {α α' : typevec (n+1)} (f : drop α ⟹ drop α') (g : last α → last α') : drop_fun (split_fun f g) = f := rfl /-- turn an equality into an arrow -/ def arrow.mp {α β : typevec n} (h : α = β) : α ⟹ β | i := eq.mp (congr_fun h _) /-- turn an equality into an arrow, with reverse direction -/ def arrow.mpr {α β : typevec n} (h : α = β) : β ⟹ α | i := eq.mpr (congr_fun h _) /-- decompose a vector into its prefix appended with its last element -/ def to_append1_drop_last {α : typevec (n+1)} : α ⟹ drop α ::: last α := arrow.mpr (append1_drop_last _) /-- stitch two bits of a vector back together -/ def from_append1_drop_last {α : typevec (n+1)} : drop α ::: last α ⟹ α := arrow.mp (append1_drop_last _) @[simp] theorem last_fun_split_fun {α α' : typevec (n+1)} (f : drop α ⟹ drop α') (g : last α → last α') : last_fun (split_fun f g) = g := rfl @[simp] theorem drop_fun_append_fun {α α' : typevec n} {β β' : Type*} (f : α ⟹ α') (g : β → β') : drop_fun (f ::: g) = f := rfl @[simp] theorem last_fun_append_fun {α α' : typevec n} {β β' : Type*} (f : α ⟹ α') (g : β → β') : last_fun (f ::: g) = g := rfl theorem split_drop_fun_last_fun {α α' : typevec (n+1)} (f : α ⟹ α') : split_fun (drop_fun f) (last_fun f) = f := eq_of_drop_last_eq rfl rfl theorem split_fun_inj {α α' : typevec (n+1)} {f f' : drop α ⟹ drop α'} {g g' : last α → last α'} (H : split_fun f g = split_fun f' g') : f = f' ∧ g = g' := by rw [← drop_fun_split_fun f g, H, ← last_fun_split_fun f g, H]; simp theorem append_fun_inj {α α' : typevec n} {β β' : Type*} {f f' : α ⟹ α'} {g g' : β → β'} : f ::: g = f' ::: g' → f = f' ∧ g = g' := split_fun_inj theorem split_fun_comp {α₀ α₁ α₂ : typevec (n+1)} (f₀ : drop α₀ ⟹ drop α₁) (f₁ : drop α₁ ⟹ drop α₂) (g₀ : last α₀ → last α₁) (g₁ : last α₁ → last α₂) : split_fun (f₁ ⊚ f₀) (g₁ ∘ g₀) = split_fun f₁ g₁ ⊚ split_fun f₀ g₀ := eq_of_drop_last_eq rfl rfl theorem append_fun_comp_split_fun {α γ : typevec n} {β δ : Type*} {ε : typevec (n + 1)} (f₀ : drop ε ⟹ α) (f₁ : α ⟹ γ) (g₀ : last ε → β) (g₁ : β → δ) : append_fun f₁ g₁ ⊚ split_fun f₀ g₀ = split_fun (f₁ ⊚ f₀) (g₁ ∘ g₀) := (split_fun_comp _ _ _ _).symm lemma append_fun_comp {α₀ α₁ α₂ : typevec n} {β₀ β₁ β₂ : Type*} (f₀ : α₀ ⟹ α₁) (f₁ : α₁ ⟹ α₂) (g₀ : β₀ → β₁) (g₁ : β₁ → β₂) : f₁ ⊚ f₀ ::: g₁ ∘ g₀ = (f₁ ::: g₁) ⊚ (f₀ ::: g₀) := eq_of_drop_last_eq rfl rfl lemma append_fun_comp' {α₀ α₁ α₂ : typevec n} {β₀ β₁ β₂ : Type*} (f₀ : α₀ ⟹ α₁) (f₁ : α₁ ⟹ α₂) (g₀ : β₀ → β₁) (g₁ : β₁ → β₂) : (f₁ ::: g₁) ⊚ (f₀ ::: g₀) = f₁ ⊚ f₀ ::: g₁ ∘ g₀ := eq_of_drop_last_eq rfl rfl lemma nil_fun_comp {α₀ : typevec 0} (f₀ : α₀ ⟹ fin2.elim0) : nil_fun ⊚ f₀ = f₀ := funext $ λ x, fin2.elim0 x theorem append_fun_comp_id {α : typevec n} {β₀ β₁ β₂ : Type*} (g₀ : β₀ → β₁) (g₁ : β₁ → β₂) : @id _ α ::: g₁ ∘ g₀ = (id ::: g₁) ⊚ (id ::: g₀) := eq_of_drop_last_eq rfl rfl @[simp] theorem drop_fun_comp {α₀ α₁ α₂ : typevec (n+1)} (f₀ : α₀ ⟹ α₁) (f₁ : α₁ ⟹ α₂) : drop_fun (f₁ ⊚ f₀) = drop_fun f₁ ⊚ drop_fun f₀ := rfl @[simp] theorem last_fun_comp {α₀ α₁ α₂ : typevec (n+1)} (f₀ : α₀ ⟹ α₁) (f₁ : α₁ ⟹ α₂) : last_fun (f₁ ⊚ f₀) = last_fun f₁ ∘ last_fun f₀ := rfl theorem append_fun_aux {α α' : typevec n} {β β' : Type*} (f : α ::: β ⟹ α' ::: β') : drop_fun f ::: last_fun f = f := eq_of_drop_last_eq rfl rfl theorem append_fun_id_id {α : typevec n} {β : Type*} : @typevec.id n α ::: @_root_.id β = typevec.id := eq_of_drop_last_eq rfl rfl instance subsingleton0 : subsingleton (typevec 0) := ⟨ λ a b, funext $ λ a, fin2.elim0 a ⟩ run_cmd do mk_simp_attr `typevec, tactic.add_doc_string `simp_attr.typevec "simp set for the manipulation of typevec and arrow expressions" local prefix `♯`:0 := cast (by try { simp }; congr' 1; try { simp }) /-- cases distinction for 0-length type vector -/ protected def cases_nil {β : typevec 0 → Sort*} (f : β fin2.elim0) : Π v, β v := λ v, ♯ f /-- cases distinction for (n+1)-length type vector -/ protected def cases_cons (n : ℕ) {β : typevec (n+1) → Sort*} (f : Π t (v : typevec n), β (v ::: t)) : Π v, β v := λ v : typevec (n+1), ♯ f v.last v.drop protected lemma cases_nil_append1 {β : typevec 0 → Sort*} (f : β fin2.elim0) : typevec.cases_nil f fin2.elim0 = f := rfl protected lemma cases_cons_append1 (n : ℕ) {β : typevec (n+1) → Sort*} (f : Π t (v : typevec n), β (v ::: t)) (v : typevec n) (α) : typevec.cases_cons n f (v ::: α) = f α v := rfl /-- cases distinction for an arrow in the category of 0-length type vectors -/ def typevec_cases_nil₃ {β : Π v v' : typevec 0, v ⟹ v' → Sort*} (f : β fin2.elim0 fin2.elim0 nil_fun) : Π v v' fs, β v v' fs := λ v v' fs, begin refine cast _ f; congr' 1; ext; try { intros; casesm fin2 0 }, refl end /-- cases distinction for an arrow in the category of (n+1)-length type vectors -/ def typevec_cases_cons₃ (n : ℕ) {β : Π v v' : typevec (n+1), v ⟹ v' → Sort*} (F : Π t t' (f : t → t') (v v' : typevec n) (fs : v ⟹ v'), β (v ::: t) (v' ::: t') (fs ::: f)) : Π v v' fs, β v v' fs := begin intros v v', rw [←append1_drop_last v, ←append1_drop_last v'], intro fs, rw [←split_drop_fun_last_fun fs], apply F end /-- specialized cases distinction for an arrow in the category of 0-length type vectors -/ def typevec_cases_nil₂ {β : fin2.elim0 ⟹ fin2.elim0 → Sort*} (f : β nil_fun) : Π f, β f := begin intro g, have : g = nil_fun, ext ⟨ ⟩, rw this, exact f end /-- specialized cases distinction for an arrow in the category of (n+1)-length type vectors -/ def typevec_cases_cons₂ (n : ℕ) (t t' : Type*) (v v' : typevec (n)) {β : (v ::: t) ⟹ (v' ::: t') → Sort*} (F : Π (f : t → t') (fs : v ⟹ v'), β (fs ::: f)) : Π fs, β fs := begin intro fs, rw [←split_drop_fun_last_fun fs], apply F end lemma typevec_cases_nil₂_append_fun {β : fin2.elim0 ⟹ fin2.elim0 → Sort*} (f : β nil_fun) : typevec_cases_nil₂ f nil_fun = f := rfl lemma typevec_cases_cons₂_append_fun (n : ℕ) (t t' : Type*) (v v' : typevec (n)) {β : (v ::: t) ⟹ (v' ::: t') → Sort*} (F : Π (f : t → t') (fs : v ⟹ v'), β (fs ::: f)) (f fs) : typevec_cases_cons₂ n t t' v v' F (fs ::: f) = F f fs := rfl /- for lifting predicates and relations -/ /-- `pred_last α p x` predicates `p` of the last element of `x : α.append1 β`. -/ def pred_last (α : typevec n) {β : Type*} (p : β → Prop) : Π ⦃i⦄, (α.append1 β) i → Prop | (fin2.fs i) := λ x, true | fin2.fz := p /-- `rel_last α r x y` says that `p` the last elements of `x y : α.append1 β` are related by `r` and all the other elements are equal. -/ def rel_last (α : typevec n) {β γ : Type*} (r : β → γ → Prop) : Π ⦃i⦄, (α.append1 β) i → (α.append1 γ) i → Prop | (fin2.fs i) := eq | fin2.fz := r section liftp' open nat /-- `repeat n t` is a `n-length` type vector that contains `n` occurences of `t` -/ def repeat : Π (n : ℕ) (t : Sort*), typevec n | 0 t := fin2.elim0 | (nat.succ i) t := append1 (repeat i t) t /-- `prod α β` is the pointwise product of the components of `α` and `β` -/ def prod : Π {n} (α β : typevec.{u} n), typevec n | 0 α β := fin2.elim0 | (n+1) α β := prod (drop α) (drop β) ::: (last α × last β) localized "infix ` ⊗ `:45 := typevec.prod" in mvfunctor /-- `const x α` is an arrow that ignores its source and constructs a `typevec` that contains nothing but `x` -/ protected def const {β} (x : β) : Π {n} (α : typevec n), α ⟹ repeat _ β | (succ n) α (fin2.fs i) := const (drop α) _ | (succ n) α fin2.fz := λ _, x open function (uncurry) /-- vector of equality on a product of vectors -/ def repeat_eq : Π {n} (α : typevec n), α ⊗ α ⟹ repeat _ Prop | 0 α := nil_fun | (succ n) α := repeat_eq (drop α) ::: uncurry eq lemma const_append1 {β γ} (x : γ) {n} (α : typevec n) : typevec.const x (α ::: β) = append_fun (typevec.const x α) (λ _, x) := by ext i : 1; cases i; refl lemma eq_nil_fun {α β : typevec 0} (f : α ⟹ β) : f = nil_fun := by ext x; cases x lemma id_eq_nil_fun {α : typevec 0} : @id _ α = nil_fun := by ext x; cases x lemma const_nil {β} (x : β) (α : typevec 0) : typevec.const x α = nil_fun := by ext i : 1; cases i; refl @[typevec] lemma repeat_eq_append1 {β} {n} (α : typevec n) : repeat_eq (α ::: β) = split_fun (repeat_eq α) (uncurry eq) := by induction n; refl @[typevec] lemma repeat_eq_nil (α : typevec 0) : repeat_eq α = nil_fun := by ext i : 1; cases i; refl /-- predicate on a type vector to constrain only the last object -/ def pred_last' (α : typevec n) {β : Type*} (p : β → Prop) : α ::: β ⟹ repeat (n+1) Prop := split_fun (typevec.const true α) p /-- predicate on the product of two type vectors to constrain only their last object -/ def rel_last' (α : typevec n) {β : Type*} (p : β → β → Prop) : (α ::: β ⊗ α ::: β) ⟹ repeat (n+1) Prop := split_fun (repeat_eq α) (uncurry p) /-- given `F : typevec.{u} (n+1) → Type u`, `curry F : Type u → typevec.{u} → Type u`, i.e. its first argument can be fed in separately from the rest of the vector of arguments -/ def curry (F : typevec.{u} (n+1) → Type*) (α : Type u) (β : typevec.{u} n) : Type* := F (β ::: α) instance curry.inhabited (F : typevec.{u} (n+1) → Type*) (α : Type u) (β : typevec.{u} n) [I : inhabited (F $ β ::: α)]: inhabited (curry F α β) := I /-- arrow to remove one element of a `repeat` vector -/ def drop_repeat (α : Type*) : Π {n}, drop (repeat (succ n) α) ⟹ repeat n α | (succ n) (fin2.fs i) := drop_repeat i | (succ n) fin2.fz := _root_.id /-- projection for a repeat vector -/ def of_repeat {α : Sort*} : Π {n i}, repeat n α i → α | ._ fin2.fz := _root_.id | ._ (fin2.fs i) := @of_repeat _ i lemma const_iff_true {α : typevec n} {i x p} : of_repeat (typevec.const p α i x) ↔ p := by induction i; [refl, erw [typevec.const,@i_ih (drop α) x]] -- variables {F : typevec.{u} n → Type*} [mvfunctor F] variables {α β γ : typevec.{u} n} variables (p : α ⟹ repeat n Prop) (r : α ⊗ α ⟹ repeat n Prop) /-- left projection of a `prod` vector -/ def prod.fst : Π {n} {α β : typevec.{u} n}, α ⊗ β ⟹ α | (succ n) α β (fin2.fs i) := @prod.fst _ (drop α) (drop β) i | (succ n) α β fin2.fz := _root_.prod.fst /-- right projection of a `prod` vector -/ def prod.snd : Π {n} {α β : typevec.{u} n}, α ⊗ β ⟹ β | (succ n) α β (fin2.fs i) := @prod.snd _ (drop α) (drop β) i | (succ n) α β fin2.fz := _root_.prod.snd /-- introduce a product where both components are the same -/ def prod.diag : Π {n} {α : typevec.{u} n}, α ⟹ α ⊗ α | (succ n) α (fin2.fs i) x := @prod.diag _ (drop α) _ x | (succ n) α fin2.fz x := (x,x) /-- constructor for `prod` -/ def prod.mk : Π {n} {α β : typevec.{u} n} (i : fin2 n), α i → β i → (α ⊗ β) i | (succ n) α β (fin2.fs i) := prod.mk i | (succ n) α β fin2.fz := _root_.prod.mk @[simp] lemma prod_fst_mk {α β : typevec n} (i : fin2 n) (a : α i) (b : β i) : typevec.prod.fst i (prod.mk i a b) = a := by induction i; simp [prod.fst, prod.mk, *] at * @[simp] lemma prod_snd_mk {α β : typevec n} (i : fin2 n) (a : α i) (b : β i) : typevec.prod.snd i (prod.mk i a b) = b := by induction i; simp [prod.snd, prod.mk, *] at * /-- `prod` is functorial -/ protected def prod.map : Π {n} {α α' β β' : typevec.{u} n}, (α ⟹ β) → (α' ⟹ β') → α ⊗ α' ⟹ β ⊗ β' | (succ n) α α' β β' x y (fin2.fs i) a := @prod.map _ (drop α) (drop α') (drop β) (drop β') (drop_fun x) (drop_fun y) _ a | (succ n) α α' β β' x y fin2.fz a := (x _ a.1,y _ a.2) localized "infix ` ⊗' `:45 := typevec.prod.map" in mvfunctor theorem fst_prod_mk {α α' β β' : typevec n} (f : α ⟹ β) (g : α' ⟹ β') : typevec.prod.fst ⊚ (f ⊗' g) = f ⊚ typevec.prod.fst := by ext i; induction i; [refl, apply i_ih] theorem snd_prod_mk {α α' β β' : typevec n} (f : α ⟹ β) (g : α' ⟹ β') : typevec.prod.snd ⊚ (f ⊗' g) = g ⊚ typevec.prod.snd := by ext i; induction i; [refl, apply i_ih] theorem fst_diag {α : typevec n} : typevec.prod.fst ⊚ (prod.diag : α ⟹ _) = id := by ext i; induction i; [refl, apply i_ih] theorem snd_diag {α : typevec n} : typevec.prod.snd ⊚ (prod.diag : α ⟹ _) = id := by ext i; induction i; [refl, apply i_ih] lemma repeat_eq_iff_eq {α : typevec n} {i x y} : of_repeat (repeat_eq α i (prod.mk _ x y)) ↔ x = y := by induction i; [refl, erw [repeat_eq,@i_ih (drop α) x y]] /-- given a predicate vector `p` over vector `α`, `subtype_ p` is the type of vectors that contain an `α` that satisfies `p` -/ def subtype_ : Π {n} {α : typevec.{u} n} (p : α ⟹ repeat n Prop), typevec n | ._ α p fin2.fz := _root_.subtype (λ x, p fin2.fz x) | ._ α p (fin2.fs i) := subtype_ (drop_fun p) i /-- projection on `subtype_` -/ def subtype_val : Π {n} {α : typevec.{u} n} (p : α ⟹ repeat n Prop), subtype_ p ⟹ α | (succ n) α p (fin2.fs i) := @subtype_val n _ _ i | (succ n) α p fin2.fz := _root_.subtype.val /-- arrow that rearranges the type of `subtype_` to turn a subtype of vector into a vector of subtypes -/ def to_subtype : Π {n} {α : typevec.{u} n} (p : α ⟹ repeat n Prop), (λ (i : fin2 n), { x // of_repeat $ p i x }) ⟹ subtype_ p | (succ n) α p (fin2.fs i) x := to_subtype (drop_fun p) i x | (succ n) α p fin2.fz x := x /-- arrow that rearranges the type of `subtype_` to turn a vector of subtypes into a subtype of vector -/ def of_subtype : Π {n} {α : typevec.{u} n} (p : α ⟹ repeat n Prop), subtype_ p ⟹ (λ (i : fin2 n), { x // of_repeat $ p i x }) | (succ n) α p (fin2.fs i) x := of_subtype _ i x | (succ n) α p fin2.fz x := x /-- similar to `to_subtype` adapted to relations (i.e. predicate on product) -/ def to_subtype' : Π {n} {α : typevec.{u} n} (p : α ⊗ α ⟹ repeat n Prop), (λ (i : fin2 n), { x : α i × α i // of_repeat $ p i (prod.mk _ x.1 x.2) }) ⟹ subtype_ p | (succ n) α p (fin2.fs i) x := to_subtype' (drop_fun p) i x | (succ n) α p fin2.fz x := ⟨x.val,cast (by congr; simp [prod.mk]) x.property⟩ /-- similar to `of_subtype` adapted to relations (i.e. predicate on product) -/ def of_subtype' : Π {n} {α : typevec.{u} n} (p : α ⊗ α ⟹ repeat n Prop), subtype_ p ⟹ (λ (i : fin2 n), { x : α i × α i // of_repeat $ p i (prod.mk _ x.1 x.2) }) | ._ α p (fin2.fs i) x := of_subtype' _ i x | ._ α p fin2.fz x := ⟨x.val,cast (by congr; simp [prod.mk]) x.property⟩ /-- similar to `diag` but the target vector is a `subtype_` guaranteeing the equality of the components -/ def diag_sub : Π {n} {α : typevec.{u} n}, α ⟹ subtype_ (repeat_eq α) | (succ n) α (fin2.fs i) x := @diag_sub _ (drop α) _ x | (succ n) α fin2.fz x := ⟨(x,x), rfl⟩ lemma subtype_val_nil {α : typevec.{u} 0} (ps : α ⟹ repeat 0 Prop) : typevec.subtype_val ps = nil_fun := funext $ by rintro ⟨ ⟩; refl lemma diag_sub_val {n} {α : typevec.{u} n} : subtype_val (repeat_eq α) ⊚ diag_sub = prod.diag := by ext i; induction i; [refl, apply i_ih] lemma prod_id : Π {n} {α β : typevec.{u} n}, (id ⊗' id) = (id : α ⊗ β ⟹ _) := begin intros, ext i a, induction i, { cases a, refl }, { apply i_ih }, end lemma append_prod_append_fun {n} {α α' β β' : typevec.{u} n} {φ φ' ψ ψ' : Type u} {f₀ : α ⟹ α'} {g₀ : β ⟹ β'} {f₁ : φ → φ'} {g₁ : ψ → ψ'} : (f₀ ⊗' g₀) ::: _root_.prod.map f₁ g₁ = ((f₀ ::: f₁) ⊗' (g₀ ::: g₁)) := by ext i a; cases i; [cases a, skip]; refl end liftp' @[simp] lemma drop_fun_diag {α} : drop_fun (@prod.diag (n+1) α) = prod.diag := by { ext i : 2, induction i; simp [drop_fun,*]; refl } @[simp] lemma drop_fun_subtype_val {α} (p : α ⟹ repeat (n+1) Prop) : drop_fun (subtype_val p) = subtype_val _ := rfl @[simp] lemma last_fun_subtype_val {α} (p : α ⟹ repeat (n+1) Prop) : last_fun (subtype_val p) = subtype.val := rfl @[simp] lemma drop_fun_to_subtype {α} (p : α ⟹ repeat (n+1) Prop) : drop_fun (to_subtype p) = to_subtype _ := by { ext i : 2, induction i; simp [drop_fun,*]; refl } @[simp] lemma last_fun_to_subtype {α} (p : α ⟹ repeat (n+1) Prop) : last_fun (to_subtype p) = _root_.id := by { ext i : 2, induction i; simp [drop_fun,*]; refl } @[simp] lemma drop_fun_of_subtype {α} (p : α ⟹ repeat (n+1) Prop) : drop_fun (of_subtype p) = of_subtype _ := by { ext i : 2, induction i; simp [drop_fun,*]; refl } @[simp] lemma last_fun_of_subtype {α} (p : α ⟹ repeat (n+1) Prop) : last_fun (of_subtype p) = _root_.id := by { ext i : 2, induction i; simp [drop_fun,*]; refl } @[simp] lemma drop_fun_rel_last {α : typevec n} {β} (R : β → β → Prop) : drop_fun (rel_last' α R) = repeat_eq α := rfl attribute [simp] drop_append1' open_locale mvfunctor @[simp] lemma drop_fun_prod {α α' β β' : typevec (n+1)} (f : α ⟹ β) (f' : α' ⟹ β') : drop_fun (f ⊗' f') = (drop_fun f ⊗' drop_fun f') := by { ext i : 2, induction i; simp [drop_fun,*]; refl } @[simp] lemma last_fun_prod {α α' β β' : typevec (n+1)} (f : α ⟹ β) (f' : α' ⟹ β') : last_fun (f ⊗' f') = _root_.prod.map (last_fun f) (last_fun f') := by { ext i : 1, induction i; simp [last_fun,*]; refl } @[simp] lemma drop_fun_from_append1_drop_last {α : typevec (n+1)} : drop_fun (@from_append1_drop_last _ α) = id := rfl @[simp] lemma last_fun_from_append1_drop_last {α : typevec (n+1)} : last_fun (@from_append1_drop_last _ α) = _root_.id := rfl @[simp] lemma drop_fun_id {α : typevec (n+1)} : drop_fun (@typevec.id _ α) = id := rfl @[simp] lemma prod_map_id {α β : typevec n} : (@typevec.id _ α ⊗' @typevec.id _ β) = id := by { ext i : 2, induction i; simp only [typevec.prod.map,*,drop_fun_id], cases x, refl, refl } @[simp] lemma subtype_val_diag_sub {α : typevec n} : subtype_val (repeat_eq α) ⊚ diag_sub = prod.diag := by { clear_except, ext i, induction i; [refl, apply i_ih], } @[simp] lemma to_subtype_of_subtype {α : typevec n} (p : α ⟹ repeat n Prop) : to_subtype p ⊚ of_subtype p = id := by ext i x; induction i; dsimp only [id, to_subtype, comp, of_subtype] at *; simp * @[simp] lemma subtype_val_to_subtype {α : typevec n} (p : α ⟹ repeat n Prop) : subtype_val p ⊚ to_subtype p = λ _, subtype.val := by ext i x; induction i; dsimp only [to_subtype, comp, subtype_val] at *; simp * @[simp] lemma to_subtype_of_subtype_assoc {α β : typevec n} (p : α ⟹ repeat n Prop) (f : β ⟹ subtype_ p) : @to_subtype n _ p ⊚ of_subtype _ ⊚ f = f := by rw [← comp_assoc,to_subtype_of_subtype]; simp @[simp] lemma to_subtype'_of_subtype' {α : typevec n} (r : α ⊗ α ⟹ repeat n Prop) : to_subtype' r ⊚ of_subtype' r = id := by ext i x; induction i; dsimp only [id, to_subtype', comp, of_subtype'] at *; simp [subtype.eta, *] lemma subtype_val_to_subtype' {α : typevec n} (r : α ⊗ α ⟹ repeat n Prop) : subtype_val r ⊚ to_subtype' r = λ i x, prod.mk i x.1.fst x.1.snd := by ext i x; induction i; dsimp only [id, to_subtype', comp, subtype_val, prod.mk] at *; simp * end typevec
0dd64a9df4645024fd917d446664e5d003e3d2b0
ad0c7d243dc1bd563419e2767ed42fb323d7beea
/linear_algebra/subtype_module.lean
2d0313c22ed17b343d2366cff924e1c745ffdda5
[ "Apache-2.0" ]
permissive
sebzim4500/mathlib
e0b5a63b1655f910dee30badf09bd7e191d3cf30
6997cafbd3a7325af5cb318561768c316ceb7757
refs/heads/master
1,585,549,958,618
1,538,221,723,000
1,538,221,723,000
150,869,076
0
0
Apache-2.0
1,538,229,323,000
1,538,229,323,000
null
UTF-8
Lean
false
false
2,417
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Kenny Lau Subtype construction of sub modules. -/ import linear_algebra.basic universes u v w variables {α : Type u} {β : Type v} {γ : Type w} variables [ring α] [module α β] [module α γ] {p : set β} [is_submodule p] variables {r : α} {x y : p} open set namespace is_submodule include α instance : has_add p := ⟨λx y, ⟨x.1 + y.1, add x.2 y.2⟩⟩ instance : has_zero p := ⟨⟨0, zero⟩⟩ instance : has_neg p := ⟨λx, ⟨-x.1, neg x.2⟩⟩ instance : has_scalar α p := ⟨λ c x, ⟨c • x.1, smul c x.2⟩⟩ @[simp] lemma coe_add : (↑(x + y) : β) = ↑x + ↑y := rfl @[simp] lemma coe_zero : ((0 : p) : β) = 0 := rfl @[simp] lemma coe_neg : ((-x : p) : β) = -x := rfl @[simp] lemma coe_smul : ((r • x : p) : β) = r • ↑x := rfl instance : add_comm_group p := by refine {add := (+), zero := 0, neg := has_neg.neg, ..}; { intros, apply set_coe.ext, simp } instance {α β} {r : ring α} [m : module α β] {p : set β} [h : is_submodule p] : module α p := begin refine {smul := (•), ..@is_submodule.add_comm_group α β r m p h, ..}; { intros, apply set_coe.ext, simp [smul_add, add_smul, mul_smul], try { exact smul_add <|> exact add_smul <|> exact mul_smul <|> exact one_smul } } end instance {α β} {f : field α} [vector_space α β] {p : set β} [is_submodule p] : vector_space α {x : β // x ∈ p} := { .. @is_submodule.module α β (@comm_ring.to_ring α (@field.to_comm_ring α f)) _ p _ } @[simp] lemma sub_val : (↑(x - y) : β) = ↑x - ↑y := by simp lemma is_linear_map_coe (s : set β) [is_submodule s] : is_linear_map (coe : s → β) := by refine {..}; simp [coe_smul] -- should this be in the root namespace? lemma is_linear_map_subtype_val {f : γ → p} (hf : is_linear_map f) : is_linear_map (λb, (f b).val) := (is_linear_map_coe p).comp hf -- should this be in the root namespace? lemma is_linear_map_subtype_mk (f : γ → β) (hf : is_linear_map f) (h : ∀c, f c ∈ p) : is_linear_map (λc, ⟨f c, h c⟩ : γ → {x : β // x ∈ p}) := by refine {..}; intros; apply set_coe.ext; simp [hf.add, hf.smul] instance {s t : set β} [is_submodule s] [is_submodule t] : is_submodule (coe ⁻¹' t) := is_submodule.preimage (is_linear_map_coe s) end is_submodule
50e46db34c5361e0adbe42be57501a21bdbabc4b
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/univ_cnstr1.lean
026d37289358433f09e6005bc08d0d74a127c232
[ "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
396
lean
constant {u₁ u₂ v} M : (Type (max u₁ u₂) → Type v) → Type attribute [class] M constant {u} L : Type u → Type u constant {u₁ u₂} I : M.{u₁ u₂ (max u₁ u₂)} L.{max u₁ u₂} attribute [instance] I constant {u₁ u₂ v} R : ∀ {m : Type (max u₁ u₂) → Type v} [M m] {A : Type u₁} (a : A), m (ulift.{u₂} A) noncomputable example : L (ulift.{3} unit) := R ()
abae984e98714440e4c17e2a7664359cab413524
c777c32c8e484e195053731103c5e52af26a25d1
/src/linear_algebra/unitary_group.lean
9a72696fc368477b77521ec61d258e259dd3b70b
[ "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
6,090
lean
/- Copyright (c) 2021 Shing Tak Lam. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Shing Tak Lam -/ import linear_algebra.general_linear_group import linear_algebra.matrix.to_lin import linear_algebra.matrix.nonsingular_inverse import algebra.star.unitary /-! # The Unitary Group This file defines elements of the unitary group `unitary_group n α`, where `α` is a `star_ring`. This consists of all `n` by `n` matrices with entries in `α` such that the star-transpose is its inverse. In addition, we define the group structure on `unitary_group n α`, and the embedding into the general linear group `general_linear_group α (n → α)`. We also define the orthogonal group `orthogonal_group n β`, where `β` is a `comm_ring`. ## Main Definitions * `matrix.unitary_group` is the type of matrices where the star-transpose is the inverse * `matrix.unitary_group.group` is the group structure (under multiplication) * `matrix.unitary_group.embedding_GL` is the embedding `unitary_group n α → GLₙ(α)` * `matrix.orthogonal_group` is the type of matrices where the transpose is the inverse ## References * https://en.wikipedia.org/wiki/Unitary_group ## Tags matrix group, group, unitary group, orthogonal group -/ universes u v namespace matrix open linear_map open_locale matrix section variables (n : Type u) [decidable_eq n] [fintype n] variables (α : Type v) [comm_ring α] [star_ring α] /-- `unitary_group n` is the group of `n` by `n` matrices where the star-transpose is the inverse. -/ abbreviation unitary_group := unitary (matrix n n α) end variables {n : Type u} [decidable_eq n] [fintype n] variables {α : Type v} [comm_ring α] [star_ring α] lemma mem_unitary_group_iff {A : matrix n n α} : A ∈ matrix.unitary_group n α ↔ A * star A = 1 := begin refine ⟨and.right, λ hA, ⟨_, hA⟩⟩, simpa only [mul_eq_mul, mul_eq_one_comm] using hA end lemma mem_unitary_group_iff' {A : matrix n n α} : A ∈ matrix.unitary_group n α ↔ star A * A = 1 := begin refine ⟨and.left, λ hA, ⟨hA, _⟩⟩, rwa [mul_eq_mul, mul_eq_one_comm] at hA, end lemma det_of_mem_unitary {A : matrix n n α} (hA : A ∈ matrix.unitary_group n α) : A.det ∈ unitary α := begin split, { simpa [star, det_transpose] using congr_arg det hA.1 }, { simpa [star, det_transpose] using congr_arg det hA.2 }, end namespace unitary_group instance coe_matrix : has_coe (unitary_group n α) (matrix n n α) := ⟨subtype.val⟩ instance coe_fun : has_coe_to_fun (unitary_group n α) (λ _, n → n → α) := { coe := λ A, A.val } /-- `to_lin' A` is matrix multiplication of vectors by `A`, as a linear map. After the group structure on `unitary_group n` is defined, we show in `to_linear_equiv` that this gives a linear equivalence. -/ def to_lin' (A : unitary_group n α) := matrix.to_lin' A lemma ext_iff (A B : unitary_group n α) : A = B ↔ ∀ i j, A i j = B i j := subtype.ext_iff_val.trans ⟨(λ h i j, congr_fun (congr_fun h i) j), matrix.ext⟩ @[ext] lemma ext (A B : unitary_group n α) : (∀ i j, A i j = B i j) → A = B := (unitary_group.ext_iff A B).mpr @[simp] lemma star_mul_self (A : unitary_group n α) : star A ⬝ A = 1 := A.2.1 section coe_lemmas variables (A B : unitary_group n α) @[simp] lemma inv_val : ↑(A⁻¹) = (star A : matrix n n α) := rfl @[simp] lemma inv_apply : ⇑(A⁻¹) = (star A : matrix n n α) := rfl @[simp] lemma mul_val : ↑(A * B) = A ⬝ B := rfl @[simp] lemma mul_apply : ⇑(A * B) = (A ⬝ B) := rfl @[simp] lemma one_val : ↑(1 : unitary_group n α) = (1 : matrix n n α) := rfl @[simp] lemma one_apply : ⇑(1 : unitary_group n α) = (1 : matrix n n α) := rfl @[simp] lemma to_lin'_mul : to_lin' (A * B) = (to_lin' A).comp (to_lin' B) := matrix.to_lin'_mul A B @[simp] lemma to_lin'_one : to_lin' (1 : unitary_group n α) = linear_map.id := matrix.to_lin'_one end coe_lemmas /-- `to_linear_equiv A` is matrix multiplication of vectors by `A`, as a linear equivalence. -/ def to_linear_equiv (A : unitary_group n α) : (n → α) ≃ₗ[α] (n → α) := { inv_fun := to_lin' A⁻¹, left_inv := λ x, calc (to_lin' A⁻¹).comp (to_lin' A) x = (to_lin' (A⁻¹ * A)) x : by rw [←to_lin'_mul] ... = x : by rw [mul_left_inv, to_lin'_one, id_apply], right_inv := λ x, calc (to_lin' A).comp (to_lin' A⁻¹) x = to_lin' (A * A⁻¹) x : by rw [←to_lin'_mul] ... = x : by rw [mul_right_inv, to_lin'_one, id_apply], ..matrix.to_lin' A } /-- `to_GL` is the map from the unitary group to the general linear group -/ def to_GL (A : unitary_group n α) : general_linear_group α (n → α) := general_linear_group.of_linear_equiv (to_linear_equiv A) lemma coe_to_GL (A : unitary_group n α) : ↑(to_GL A) = to_lin' A := rfl @[simp] lemma to_GL_one : to_GL (1 : unitary_group n α) = 1 := by { ext1 v i, rw [coe_to_GL, to_lin'_one], refl } @[simp] lemma to_GL_mul (A B : unitary_group n α) : to_GL (A * B) = to_GL A * to_GL B := by { ext1 v i, rw [coe_to_GL, to_lin'_mul], refl } /-- `unitary_group.embedding_GL` is the embedding from `unitary_group n α` to `general_linear_group n α`. -/ def embedding_GL : unitary_group n α →* general_linear_group α (n → α) := ⟨λ A, to_GL A, by simp, by simp⟩ end unitary_group section orthogonal_group variables (n) (β : Type v) [comm_ring β] local attribute [instance] star_ring_of_comm /-- `orthogonal_group n` is the group of `n` by `n` matrices where the transpose is the inverse. -/ abbreviation orthogonal_group := unitary_group n β lemma mem_orthogonal_group_iff {A : matrix n n β} : A ∈ matrix.orthogonal_group n β ↔ A * star A = 1 := begin refine ⟨and.right, λ hA, ⟨_, hA⟩⟩, simpa only [mul_eq_mul, mul_eq_one_comm] using hA end lemma mem_orthogonal_group_iff' {A : matrix n n β} : A ∈ matrix.orthogonal_group n β ↔ star A * A = 1 := begin refine ⟨and.left, λ hA, ⟨hA, _⟩⟩, rwa [mul_eq_mul, mul_eq_one_comm] at hA, end end orthogonal_group end matrix
0e30ff56fab1a0cf5fbd226bd26e429a05958ba6
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/category/Profinite_auto.lean
efd072e54510118cbbd6070b35704fe97b953ff9
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
1,128
lean
/- Copyright (c) 2020 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.category.CompHaus import Mathlib.PostPort universes u_1 l namespace Mathlib /-! # The category of Profinite Types We construct the category of profinite topological spaces, often called profinite sets -- perhaps they could be called profinite types in Lean. The type of profinite topological spaces is called `Profinite`. It has a category instance and is a fully faithful subcategory of `Top`. The fully faithful functor is called `Profinite_to_Top`. ## Implementation notes A profinite type is defined to be a topological space which is compact, Hausdorff and totally disconnected. ## TODO 0. Link to category of projective limits of finite discrete sets. 1. existence of products, limits(?), finite coproducts 2. `Profinite_to_Top` creates limits? 3. Clausen/Scholze topology on the category `Profinite`. ## Tags profinite -/ /-- The type of profinite topological spaces. -/
651c73ba7c24cb1198f52df56bd28f88af25221d
e61a235b8468b03aee0120bf26ec615c045005d2
/stage0/src/Init/Lean/Meta/InferType.lean
f166cb0b199de06da22f347d789ce189e0e51022
[ "Apache-2.0" ]
permissive
SCKelemen/lean4
140dc63a80539f7c61c8e43e1c174d8500ec3230
e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc
refs/heads/master
1,660,973,595,917
1,590,278,033,000
1,590,278,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,184
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Lean.Data.LBool import Init.Lean.Meta.Basic namespace Lean namespace Meta private def inferAppType (f : Expr) (args : Array Expr) : MetaM Expr := do fType ← inferType f; (j, fType) ← args.size.foldM (fun i (acc : Nat × Expr) => let (j, type) := acc; match type with | Expr.forallE _ _ b _ => pure (j, b) | _ => do type ← whnf $ type.instantiateRevRange j i args; match type with | Expr.forallE _ _ b _ => pure (i, b) | _ => throwEx $ Exception.functionExpected (mkAppRange f 0 i args) (args.get! i)) (0, fType); pure $ fType.instantiateRevRange j args.size args private def inferConstType (c : Name) (lvls : List Level) : MetaM Expr := do env ← getEnv; match env.find? c with | some cinfo => if cinfo.lparams.length == lvls.length then pure $ cinfo.instantiateTypeLevelParams lvls else throwEx $ Exception.incorrectNumOfLevels c lvls | none => throwEx $ Exception.unknownConst c private def inferProjType (structName : Name) (idx : Nat) (e : Expr) : MetaM Expr := do let failed : Unit → MetaM Expr := fun _ => throwEx $ Exception.invalidProjection structName idx e; structType ← inferType e; structType ← whnf structType; env ← getEnv; matchConst env structType.getAppFn failed $ fun structInfo structLvls => do match structInfo with | ConstantInfo.inductInfo { nparams := n, ctors := [ctor], .. } => let structParams := structType.getAppArgs; if n != structParams.size then failed () else match env.find? ctor with | none => failed () | some (ctorInfo) => do ctorType ← inferAppType (mkConst ctor structLvls) structParams; ctorType ← idx.foldM (fun i ctorType => do ctorType ← whnf ctorType; match ctorType with | Expr.forallE _ _ body _ => if body.hasLooseBVars then pure $ body.instantiate1 $ mkProj structName i e else pure body | _ => failed ()) ctorType; ctorType ← whnf ctorType; match ctorType with | Expr.forallE _ d _ _ => pure d | _ => failed () | _ => failed () def getLevel (type : Expr) : MetaM Level := do typeType ← inferType type; typeType ← whnfD typeType; match typeType with | Expr.sort lvl _ => pure lvl | Expr.mvar mvarId _ => condM (isReadOnlyOrSyntheticOpaqueExprMVar mvarId) (throwEx $ Exception.typeExpected type) (do lvl ← mkFreshLevelMVar; assignExprMVar mvarId (mkSort lvl); pure lvl) | _ => throwEx $ Exception.typeExpected type private def inferForallType (e : Expr) : MetaM Expr := forallTelescope e $ fun xs e => do lvl ← getLevel e; lvl ← xs.foldrM (fun x lvl => do xType ← inferType x; xTypeLvl ← getLevel xType; pure $ mkLevelIMax xTypeLvl lvl) lvl; pure $ mkSort lvl.normalize /- Infer type of lambda and let expressions -/ private def inferLambdaType (e : Expr) : MetaM Expr := lambdaTelescope e $ fun xs e => do type ← inferType e; mkForall xs type @[inline] private def withLocalDecl {α} (name : Name) (bi : BinderInfo) (type : Expr) (x : Expr → MetaM α) : MetaM α := savingCache $ do fvarId ← mkFreshId; adaptReader (fun (ctx : Context) => { ctx with lctx := ctx.lctx.mkLocalDecl fvarId name type bi }) $ x (mkFVar fvarId) private def inferMVarType (mvarId : MVarId) : MetaM Expr := do mctx ← getMCtx; match mctx.findDecl? mvarId with | some d => pure d.type | none => throwEx $ Exception.unknownExprMVar mvarId private def inferFVarType (fvarId : FVarId) : MetaM Expr := do lctx ← getLCtx; match lctx.find? fvarId with | some d => pure d.type | none => throwEx $ Exception.unknownFVar fvarId @[inline] private def checkInferTypeCache (e : Expr) (inferType : MetaM Expr) : MetaM Expr := do s ← get; match s.cache.inferType.find? e with | some type => pure type | none => do type ← inferType; modify $ fun s => { s with cache := { s.cache with inferType := s.cache.inferType.insert e type } }; pure type private partial def inferTypeAux : Expr → MetaM Expr | Expr.const c lvls _ => inferConstType c lvls | e@(Expr.proj n i s _) => checkInferTypeCache e (inferProjType n i s) | e@(Expr.app f _ _) => checkInferTypeCache e (inferAppType f.getAppFn e.getAppArgs) | Expr.mvar mvarId _ => inferMVarType mvarId | Expr.fvar fvarId _ => inferFVarType fvarId | Expr.bvar bidx _ => throw $ Exception.unexpectedBVar bidx | Expr.mdata _ e _ => inferTypeAux e | Expr.lit v _ => pure v.type | Expr.sort lvl _ => pure $ mkSort (mkLevelSucc lvl) | e@(Expr.forallE _ _ _ _) => checkInferTypeCache e (inferForallType e) | e@(Expr.lam _ _ _ _) => checkInferTypeCache e (inferLambdaType e) | e@(Expr.letE _ _ _ _ _) => checkInferTypeCache e (inferLambdaType e) | Expr.localE _ _ _ _ => unreachable! def inferTypeImpl (e : Expr) : MetaM Expr := withTransparency TransparencyMode.default (inferTypeAux e) @[init] def setInferTypeRef : IO Unit := inferTypeRef.set inferTypeImpl /-- Return `LBool.true` if given level is always equivalent to universe level zero. It is used to implement `isProp`. -/ private def isAlwaysZero : Level → Bool | Level.zero _ => true | Level.mvar _ _ => false | Level.param _ _ => false | Level.succ _ _ => false | Level.max u v _ => isAlwaysZero u && isAlwaysZero v | Level.imax _ u _ => isAlwaysZero u /-- `isArrowProp type n` is an "approximate" predicate which returns `LBool.true` if `type` is of the form `A_1 -> ... -> A_n -> Prop`. Remark: `type` can be a dependent arrow. -/ private partial def isArrowProp : Expr → Nat → MetaM LBool | Expr.sort u _, 0 => do u ← instantiateLevelMVars u; pure $ (isAlwaysZero u).toLBool | Expr.forallE _ _ _ _, 0 => pure LBool.false | Expr.forallE _ _ b _, n+1 => isArrowProp b n | Expr.letE _ _ _ b _, n => isArrowProp b n | Expr.mdata _ e _, n => isArrowProp e n | _, _ => pure LBool.undef /-- `isPropQuickApp f n` is an "approximate" predicate which returns `LBool.true` if `f` applied to `n` arguments is a proposition. -/ private partial def isPropQuickApp : Expr → Nat → MetaM LBool | Expr.const c lvls _, arity => do constType ← inferConstType c lvls; isArrowProp constType arity | Expr.fvar fvarId _, arity => do fvarType ← inferFVarType fvarId; isArrowProp fvarType arity | Expr.mvar mvarId _, arity => do mvarType ← inferMVarType mvarId; isArrowProp mvarType arity | Expr.app f _ _, arity => isPropQuickApp f (arity+1) | Expr.mdata _ e _, arity => isPropQuickApp e arity | Expr.letE _ _ _ b _, arity => isPropQuickApp b arity | Expr.lam _ _ _ _, 0 => pure LBool.false | Expr.lam _ _ b _, arity+1 => isPropQuickApp b arity | _, _ => pure LBool.undef /-- `isPropQuick e` is an "approximate" predicate which returns `LBool.true` if `e` is a proposition. -/ partial def isPropQuick : Expr → MetaM LBool | Expr.bvar _ _ => pure LBool.undef | Expr.lit _ _ => pure LBool.false | Expr.sort _ _ => pure LBool.false | Expr.lam _ _ _ _ => pure LBool.false | Expr.letE _ _ _ b _ => isPropQuick b | Expr.proj _ _ _ _ => pure LBool.undef | Expr.forallE _ _ b _ => isPropQuick b | Expr.mdata _ e _ => isPropQuick e | Expr.const c lvls _ => do constType ← inferConstType c lvls; isArrowProp constType 0 | Expr.fvar fvarId _ => do fvarType ← inferFVarType fvarId; isArrowProp fvarType 0 | Expr.mvar mvarId _ => do mvarType ← inferMVarType mvarId; isArrowProp mvarType 0 | Expr.app f _ _ => isPropQuickApp f 1 | Expr.localE _ _ _ _ => unreachable! /-- `isProp whnf e` return `true` if `e` is a proposition. If `e` contains metavariables, it may not be possible to decide whether is a proposition or not. We return `false` in this case. We considered using `LBool` and retuning `LBool.undef`, but we have no applications for it. -/ def isProp (e : Expr) : MetaM Bool := do r ← isPropQuick e; match r with | LBool.true => pure true | LBool.false => pure false | LBool.undef => do -- dbgTrace ("isPropQuick failed " ++ toString e); type ← inferType e; type ← whnfD type; match type with | Expr.sort u _ => do u ← instantiateLevelMVars u; pure $ isAlwaysZero u | _ => pure false /-- `isArrowProposition type n` is an "approximate" predicate which returns `LBool.true` if `type` is of the form `A_1 -> ... -> A_n -> B`, where `B` is a proposition. Remark: `type` can be a dependent arrow. -/ private partial def isArrowProposition : Expr → Nat → MetaM LBool | Expr.forallE _ _ b _, n+1 => isArrowProposition b n | Expr.letE _ _ _ b _, n => isArrowProposition b n | Expr.mdata _ e _, n => isArrowProposition e n | type, 0 => isPropQuick type | _, _ => pure LBool.undef /-- `isProofQuickApp f n` is an "approximate" predicate which returns `LBool.true` if `f` applied to `n` arguments is a proof. -/ @[specialize] private partial def isProofQuickApp (isProofQuick : Expr → MetaM LBool) : Expr → Nat → MetaM LBool | Expr.const c lvls _, arity => do constType ← inferConstType c lvls; isArrowProposition constType arity | Expr.fvar fvarId _, arity => do fvarType ← inferFVarType fvarId; isArrowProposition fvarType arity | Expr.mvar mvarId _, arity => do mvarType ← inferMVarType mvarId; isArrowProposition mvarType arity | Expr.app f _ _, arity => isProofQuickApp f (arity+1) | Expr.mdata _ e _, arity => isProofQuickApp e arity | Expr.letE _ _ _ b _, arity => isProofQuickApp b arity | Expr.lam _ _ b _, 0 => isProofQuick b | Expr.lam _ _ b _, arity+1 => isProofQuickApp b arity | _, _ => pure LBool.undef /-- `isProofQuick e` is an "approximate" predicate which returns `LBool.true` if `e` is a proof. -/ partial def isProofQuick : Expr → MetaM LBool | Expr.bvar _ _ => pure LBool.undef | Expr.lit _ _ => pure LBool.false | Expr.sort _ _ => pure LBool.false | Expr.lam _ _ b _ => isProofQuick b | Expr.letE _ _ _ b _ => isProofQuick b | Expr.proj _ _ _ _ => pure LBool.undef | Expr.forallE _ _ b _ => pure LBool.false | Expr.mdata _ e _ => isProofQuick e | Expr.const c lvls _ => do constType ← inferConstType c lvls; isArrowProposition constType 0 | Expr.fvar fvarId _ => do fvarType ← inferFVarType fvarId; isArrowProposition fvarType 0 | Expr.mvar mvarId _ => do mvarType ← inferMVarType mvarId; isArrowProposition mvarType 0 | Expr.app f _ _ => isProofQuickApp isProofQuick f 1 | Expr.localE _ _ _ _ => unreachable! def isProof (e : Expr) : MetaM Bool := do r ← isProofQuick e; match r with | LBool.true => pure true | LBool.false => pure false | LBool.undef => do type ← inferType e; isProp type /-- `isArrowType type n` is an "approximate" predicate which returns `LBool.true` if `type` is of the form `A_1 -> ... -> A_n -> Sort _`. Remark: `type` can be a dependent arrow. -/ private partial def isArrowType : Expr → Nat → MetaM LBool | Expr.sort u _, 0 => pure LBool.true | Expr.forallE _ _ _ _, 0 => pure LBool.false | Expr.forallE _ _ b _, n+1 => isArrowType b n | Expr.letE _ _ _ b _, n => isArrowType b n | Expr.mdata _ e _, n => isArrowType e n | _, _ => pure LBool.undef /-- `isTypeQuickApp f n` is an "approximate" predicate which returns `LBool.true` if `f` applied to `n` arguments is a type. -/ private partial def isTypeQuickApp : Expr → Nat → MetaM LBool | Expr.const c lvls _, arity => do constType ← inferConstType c lvls; isArrowType constType arity | Expr.fvar fvarId _, arity => do fvarType ← inferFVarType fvarId; isArrowType fvarType arity | Expr.mvar mvarId _, arity => do mvarType ← inferMVarType mvarId; isArrowType mvarType arity | Expr.app f _ _, arity => isTypeQuickApp f (arity+1) | Expr.mdata _ e _, arity => isTypeQuickApp e arity | Expr.letE _ _ _ b _, arity => isTypeQuickApp b arity | Expr.lam _ _ _ _, 0 => pure LBool.false | Expr.lam _ _ b _, arity+1 => isTypeQuickApp b arity | _, _ => pure LBool.undef /-- `isTypeQuick e` is an "approximate" predicate which returns `LBool.true` if `e` is a type. -/ partial def isTypeQuick : Expr → MetaM LBool | Expr.bvar _ _ => pure LBool.undef | Expr.lit _ _ => pure LBool.false | Expr.sort _ _ => pure LBool.true | Expr.lam _ _ _ _ => pure LBool.false | Expr.letE _ _ _ b _ => isTypeQuick b | Expr.proj _ _ _ _ => pure LBool.undef | Expr.forallE _ _ b _ => pure LBool.true | Expr.mdata _ e _ => isTypeQuick e | Expr.const c lvls _ => do constType ← inferConstType c lvls; isArrowType constType 0 | Expr.fvar fvarId _ => do fvarType ← inferFVarType fvarId; isArrowType fvarType 0 | Expr.mvar mvarId _ => do mvarType ← inferMVarType mvarId; isArrowType mvarType 0 | Expr.app f _ _ => isTypeQuickApp f 1 | Expr.localE _ _ _ _ => unreachable! def isType (e : Expr) : MetaM Bool := do r ← isTypeQuick e; match r with | LBool.true => pure true | LBool.false => pure false | LBool.undef => do type ← inferType e; type ← whnfD type; match type with | Expr.sort _ _ => pure true | _ => pure false partial def isTypeFormerAux : Expr → MetaM Bool | type => do type ← whnfD type; match type with | Expr.sort _ _ => pure true | Expr.forallE n d b c => withLocalDecl n d c.binderInfo $ fun fvar => isTypeFormerAux (b.instantiate1 fvar) | _ => pure false /-- Return true iff `e : Sort _` or `e : (forall As, Sort _)`. Remark: it subsumes `isType` -/ def isTypeFormer (e : Expr) : MetaM Bool := do type ← inferType e; isTypeFormerAux type end Meta end Lean
2ca1f7bda1752b498ecfef41a7992b42cc4c36a6
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/order/max.lean
54860a98e8e620d3c93382fd041c7fb109103f0b
[ "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
12,675
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Yury Kudryashov, Yaël Dillies -/ import order.synonym /-! # Minimal/maximal and bottom/top elements > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > https://github.com/leanprover-community/mathlib4/pull/567 > Any changes to this file require a corresponding PR to mathlib4. This file defines predicates for elements to be minimal/maximal or bottom/top and typeclasses saying that there are no such elements. ## Predicates * `is_bot`: An element is *bottom* if all elements are greater than it. * `is_top`: An element is *top* if all elements are less than it. * `is_min`: An element is *minimal* if no element is strictly less than it. * `is_max`: An element is *maximal* if no element is strictly greater than it. See also `is_bot_iff_is_min` and `is_top_iff_is_max` for the equivalences in a (co)directed order. ## Typeclasses * `no_bot_order`: An order without bottom elements. * `no_top_order`: An order without top elements. * `no_min_order`: An order without minimal elements. * `no_max_order`: An order without maximal elements. -/ open order_dual variables {ι α β : Type*} {π : ι → Type*} /-- Order without bottom elements. -/ class no_bot_order (α : Type*) [has_le α] : Prop := (exists_not_ge (a : α) : ∃ b, ¬ a ≤ b) /-- Order without top elements. -/ class no_top_order (α : Type*) [has_le α] : Prop := (exists_not_le (a : α) : ∃ b, ¬ b ≤ a) /-- Order without minimal elements. Sometimes called coinitial or dense. -/ class no_min_order (α : Type*) [has_lt α] : Prop := (exists_lt (a : α) : ∃ b, b < a) /-- Order without maximal elements. Sometimes called cofinal. -/ class no_max_order (α : Type*) [has_lt α] : Prop := (exists_gt (a : α) : ∃ b, a < b) export no_bot_order (exists_not_ge) export no_top_order (exists_not_le) export no_min_order (exists_lt) export no_max_order (exists_gt) instance nonempty_lt [has_lt α] [no_min_order α] (a : α) : nonempty {x // x < a} := nonempty_subtype.2 (exists_lt a) instance nonempty_gt [has_lt α] [no_max_order α] (a : α) : nonempty {x // a < x} := nonempty_subtype.2 (exists_gt a) instance order_dual.no_bot_order (α : Type*) [has_le α] [no_top_order α] : no_bot_order αᵒᵈ := ⟨λ a, @exists_not_le α _ _ a⟩ instance order_dual.no_top_order (α : Type*) [has_le α] [no_bot_order α] : no_top_order αᵒᵈ := ⟨λ a, @exists_not_ge α _ _ a⟩ instance order_dual.no_min_order (α : Type*) [has_lt α] [no_max_order α] : no_min_order αᵒᵈ := ⟨λ a, @exists_gt α _ _ a⟩ instance order_dual.no_max_order (α : Type*) [has_lt α] [no_min_order α] : no_max_order αᵒᵈ := ⟨λ a, @exists_lt α _ _ a⟩ instance no_max_order_of_left [preorder α] [preorder β] [no_max_order α] : no_max_order (α × β) := ⟨λ ⟨a, b⟩, by { obtain ⟨c, h⟩ := exists_gt a, exact ⟨(c, b), prod.mk_lt_mk_iff_left.2 h⟩ }⟩ instance no_max_order_of_right [preorder α] [preorder β] [no_max_order β] : no_max_order (α × β) := ⟨λ ⟨a, b⟩, by { obtain ⟨c, h⟩ := exists_gt b, exact ⟨(a, c), prod.mk_lt_mk_iff_right.2 h⟩ }⟩ instance no_min_order_of_left [preorder α] [preorder β] [no_min_order α] : no_min_order (α × β) := ⟨λ ⟨a, b⟩, by { obtain ⟨c, h⟩ := exists_lt a, exact ⟨(c, b), prod.mk_lt_mk_iff_left.2 h⟩ }⟩ instance no_min_order_of_right [preorder α] [preorder β] [no_min_order β] : no_min_order (α × β) := ⟨λ ⟨a, b⟩, by { obtain ⟨c, h⟩ := exists_lt b, exact ⟨(a, c), prod.mk_lt_mk_iff_right.2 h⟩ }⟩ instance [nonempty ι] [Π i, preorder (π i)] [Π i, no_max_order (π i)] : no_max_order (Π i, π i) := ⟨λ a, begin classical, obtain ⟨b, hb⟩ := exists_gt (a $ classical.arbitrary _), exact ⟨_, lt_update_self_iff.2 hb⟩, end⟩ instance [nonempty ι] [Π i, preorder (π i)] [Π i, no_min_order (π i)] : no_min_order (Π i, π i) := ⟨λ a, begin obtain ⟨b, hb⟩ := exists_lt (a $ classical.arbitrary _), exact ⟨_, update_lt_self_iff.2 hb⟩, end⟩ @[priority 100] -- See note [lower instance priority] instance no_min_order.to_no_bot_order (α : Type*) [preorder α] [no_min_order α] : no_bot_order α := ⟨λ a, (exists_lt a).imp $ λ _, not_le_of_lt⟩ @[priority 100] -- See note [lower instance priority] instance no_max_order.to_no_top_order (α : Type*) [preorder α] [no_max_order α] : no_top_order α := ⟨λ a, (exists_gt a).imp $ λ _, not_le_of_lt⟩ lemma no_bot_order.to_no_min_order (α : Type*) [linear_order α] [no_bot_order α] : no_min_order α := { exists_lt := by { convert λ a : α, exists_not_ge a, simp_rw not_le, } } lemma no_top_order.to_no_max_order (α : Type*) [linear_order α] [no_top_order α] : no_max_order α := { exists_gt := by { convert λ a : α, exists_not_le a, simp_rw not_le, } } lemma no_bot_order_iff_no_min_order (α : Type*) [linear_order α] : no_bot_order α ↔ no_min_order α := ⟨λ h, by { haveI := h, exact no_bot_order.to_no_min_order α }, λ h, by { haveI := h, exact no_min_order.to_no_bot_order α }⟩ lemma no_top_order_iff_no_max_order (α : Type*) [linear_order α] : no_top_order α ↔ no_max_order α := ⟨λ h, by { haveI := h, exact no_top_order.to_no_max_order α }, λ h, by { haveI := h, exact no_max_order.to_no_top_order α }⟩ theorem no_min_order.not_acc [has_lt α] [no_min_order α] (a : α) : ¬ acc (<) a := λ h, acc.rec_on h $ λ x _, (exists_lt x).rec_on theorem no_max_order.not_acc [has_lt α] [no_max_order α] (a : α) : ¬ acc (>) a := λ h, acc.rec_on h $ λ x _, (exists_gt x).rec_on section has_le variables [has_le α] {a b : α} /-- `a : α` is a bottom element of `α` if it is less than or equal to any other element of `α`. This predicate is roughly an unbundled version of `order_bot`, except that a preorder may have several bottom elements. When `α` is linear, this is useful to make a case disjunction on `no_min_order α` within a proof. -/ def is_bot (a : α) : Prop := ∀ b, a ≤ b /-- `a : α` is a top element of `α` if it is greater than or equal to any other element of `α`. This predicate is roughly an unbundled version of `order_bot`, except that a preorder may have several top elements. When `α` is linear, this is useful to make a case disjunction on `no_max_order α` within a proof. -/ def is_top (a : α) : Prop := ∀ b, b ≤ a /-- `a` is a minimal element of `α` if no element is strictly less than it. We spell it without `<` to avoid having to convert between `≤` and `<`. Instead, `is_min_iff_forall_not_lt` does the conversion. -/ def is_min (a : α) : Prop := ∀ ⦃b⦄, b ≤ a → a ≤ b /-- `a` is a maximal element of `α` if no element is strictly greater than it. We spell it without `<` to avoid having to convert between `≤` and `<`. Instead, `is_max_iff_forall_not_lt` does the conversion. -/ def is_max (a : α) : Prop := ∀ ⦃b⦄, a ≤ b → b ≤ a @[simp] lemma not_is_bot [no_bot_order α] (a : α) : ¬is_bot a := λ h, let ⟨b, hb⟩ := exists_not_ge a in hb $ h _ @[simp] lemma not_is_top [no_top_order α] (a : α) : ¬is_top a := λ h, let ⟨b, hb⟩ := exists_not_le a in hb $ h _ protected lemma is_bot.is_min (h : is_bot a) : is_min a := λ b _, h b protected lemma is_top.is_max (h : is_top a) : is_max a := λ b _, h b @[simp] lemma is_bot_to_dual_iff : is_bot (to_dual a) ↔ is_top a := iff.rfl @[simp] lemma is_top_to_dual_iff : is_top (to_dual a) ↔ is_bot a := iff.rfl @[simp] lemma is_min_to_dual_iff : is_min (to_dual a) ↔ is_max a := iff.rfl @[simp] lemma is_max_to_dual_iff : is_max (to_dual a) ↔ is_min a := iff.rfl @[simp] lemma is_bot_of_dual_iff {a : αᵒᵈ} : is_bot (of_dual a) ↔ is_top a := iff.rfl @[simp] lemma is_top_of_dual_iff {a : αᵒᵈ} : is_top (of_dual a) ↔ is_bot a := iff.rfl @[simp] lemma is_min_of_dual_iff {a : αᵒᵈ} : is_min (of_dual a) ↔ is_max a := iff.rfl @[simp] lemma is_max_of_dual_iff {a : αᵒᵈ} : is_max (of_dual a) ↔ is_min a := iff.rfl alias is_bot_to_dual_iff ↔ _ is_top.to_dual alias is_top_to_dual_iff ↔ _ is_bot.to_dual alias is_min_to_dual_iff ↔ _ is_max.to_dual alias is_max_to_dual_iff ↔ _ is_min.to_dual alias is_bot_of_dual_iff ↔ _ is_top.of_dual alias is_top_of_dual_iff ↔ _ is_bot.of_dual alias is_min_of_dual_iff ↔ _ is_max.of_dual alias is_max_of_dual_iff ↔ _ is_min.of_dual end has_le section preorder variables [preorder α] {a b : α} lemma is_bot.mono (ha : is_bot a) (h : b ≤ a) : is_bot b := λ c, h.trans $ ha _ lemma is_top.mono (ha : is_top a) (h : a ≤ b) : is_top b := λ c, (ha _).trans h lemma is_min.mono (ha : is_min a) (h : b ≤ a) : is_min b := λ c hc, h.trans $ ha $ hc.trans h lemma is_max.mono (ha : is_max a) (h : a ≤ b) : is_max b := λ c hc, (ha $ h.trans hc).trans h lemma is_min.not_lt (h : is_min a) : ¬ b < a := λ hb, hb.not_le $ h hb.le lemma is_max.not_lt (h : is_max a) : ¬ a < b := λ hb, hb.not_le $ h hb.le @[simp] lemma not_is_min_of_lt (h : b < a) : ¬ is_min a := λ ha, ha.not_lt h @[simp] lemma not_is_max_of_lt (h : a < b) : ¬ is_max a := λ ha, ha.not_lt h alias not_is_min_of_lt ← has_lt.lt.not_is_min alias not_is_max_of_lt ← has_lt.lt.not_is_max lemma is_min_iff_forall_not_lt : is_min a ↔ ∀ b, ¬ b < a := ⟨λ h _, h.not_lt, λ h b hba, of_not_not $ λ hab, h _ $ hba.lt_of_not_le hab⟩ lemma is_max_iff_forall_not_lt : is_max a ↔ ∀ b, ¬ a < b := ⟨λ h _, h.not_lt, λ h b hba, of_not_not $ λ hab, h _ $ hba.lt_of_not_le hab⟩ @[simp] lemma not_is_min_iff : ¬ is_min a ↔ ∃ b, b < a := by simp_rw [lt_iff_le_not_le, is_min, not_forall, exists_prop] @[simp] lemma not_is_max_iff : ¬ is_max a ↔ ∃ b, a < b := by simp_rw [lt_iff_le_not_le, is_max, not_forall, exists_prop] @[simp] lemma not_is_min [no_min_order α] (a : α) : ¬ is_min a := not_is_min_iff.2 $ exists_lt a @[simp] lemma not_is_max [no_max_order α] (a : α) : ¬ is_max a := not_is_max_iff.2 $ exists_gt a namespace subsingleton variable [subsingleton α] protected lemma is_bot (a : α) : is_bot a := λ _, (subsingleton.elim _ _).le protected lemma is_top (a : α) : is_top a := λ _, (subsingleton.elim _ _).le protected lemma is_min (a : α) : is_min a := (subsingleton.is_bot _).is_min protected lemma is_max (a : α) : is_max a := (subsingleton.is_top _).is_max end subsingleton end preorder section partial_order variables [partial_order α] {a b : α} protected lemma is_min.eq_of_le (ha : is_min a) (h : b ≤ a) : b = a := h.antisymm $ ha h protected lemma is_min.eq_of_ge (ha : is_min a) (h : b ≤ a) : a = b := h.antisymm' $ ha h protected lemma is_max.eq_of_le (ha : is_max a) (h : a ≤ b) : a = b := h.antisymm $ ha h protected lemma is_max.eq_of_ge (ha : is_max a) (h : a ≤ b) : b = a := h.antisymm' $ ha h end partial_order section prod variables [preorder α] [preorder β] {a a₁ a₂ : α} {b b₁ b₂ : β} {x y : α × β} lemma is_bot.prod_mk (ha : is_bot a) (hb : is_bot b) : is_bot (a, b) := λ c, ⟨ha _, hb _⟩ lemma is_top.prod_mk (ha : is_top a) (hb : is_top b) : is_top (a, b) := λ c, ⟨ha _, hb _⟩ lemma is_min.prod_mk (ha : is_min a) (hb : is_min b) : is_min (a, b) := λ c hc, ⟨ha hc.1, hb hc.2⟩ lemma is_max.prod_mk (ha : is_max a) (hb : is_max b) : is_max (a, b) := λ c hc, ⟨ha hc.1, hb hc.2⟩ lemma is_bot.fst (hx : is_bot x) : is_bot x.1 := λ c, (hx (c, x.2)).1 lemma is_bot.snd (hx : is_bot x) : is_bot x.2 := λ c, (hx (x.1, c)).2 lemma is_top.fst (hx : is_top x) : is_top x.1 := λ c, (hx (c, x.2)).1 lemma is_top.snd (hx : is_top x) : is_top x.2 := λ c, (hx (x.1, c)).2 lemma is_min.fst (hx : is_min x) : is_min x.1 := λ c hc, (hx $ show (c, x.2) ≤ x, from (and_iff_left le_rfl).2 hc).1 lemma is_min.snd (hx : is_min x) : is_min x.2 := λ c hc, (hx $ show (x.1, c) ≤ x, from (and_iff_right le_rfl).2 hc).2 lemma is_max.fst (hx : is_max x) : is_max x.1 := λ c hc, (hx $ show x ≤ (c, x.2), from (and_iff_left le_rfl).2 hc).1 lemma is_max.snd (hx : is_max x) : is_max x.2 := λ c hc, (hx $ show x ≤ (x.1, c), from (and_iff_right le_rfl).2 hc).2 lemma prod.is_bot_iff : is_bot x ↔ is_bot x.1 ∧ is_bot x.2 := ⟨λ hx, ⟨hx.fst, hx.snd⟩, λ h, h.1.prod_mk h.2⟩ lemma prod.is_top_iff : is_top x ↔ is_top x.1 ∧ is_top x.2 := ⟨λ hx, ⟨hx.fst, hx.snd⟩, λ h, h.1.prod_mk h.2⟩ lemma prod.is_min_iff : is_min x ↔ is_min x.1 ∧ is_min x.2 := ⟨λ hx, ⟨hx.fst, hx.snd⟩, λ h, h.1.prod_mk h.2⟩ lemma prod.is_max_iff : is_max x ↔ is_max x.1 ∧ is_max x.2 := ⟨λ hx, ⟨hx.fst, hx.snd⟩, λ h, h.1.prod_mk h.2⟩ end prod
2f97ba93bcd5d6782326831ed21a390f2162645d
0003047346476c031128723dfd16fe273c6bc605
/src/algebra/archimedean.lean
cfe7da71ce4a1d046886fb82626f99046cf31aa3
[ "Apache-2.0" ]
permissive
ChandanKSingh/mathlib
d2bf4724ccc670bf24915c12c475748281d3fb73
d60d1616958787ccb9842dc943534f90ea0bab64
refs/heads/master
1,588,238,823,679
1,552,867,469,000
1,552,867,469,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,305
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 tactic.abel 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 : ⌊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] /-- 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; linarith {discharger := `[simp]} 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 end⟩ @[simp] lemma fract_fract (r : α) : fract (fract r) = fract r := by rw fract_eq_fract; exact ⟨-⌊r⌋, by unfold fract;simp⟩ theorem fract_add (r s : α) : ∃ z : ℤ, fract (r + s) - fract r - fract s = z := ⟨⌊r⌋ + ⌊s⌋ - ⌊r + s⌋, by unfold fract; simp⟩ 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` -/ 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 /-- `round` rounds a number to the nearest integer. `round (1 / 2) = 1` -/ def round [floor_ring α] (x : α) : ℤ := ⌊x + 1 / 2⌋ 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₂⟩⟩ lemma abs_sub_round [floor_ring α] (x : α) : abs (x - round x) ≤ 1 / 2 := begin rw [round, abs_sub_le_iff], have := floor_le (x + 1 / 2), have := lt_floor_add_one (x + 1 / 2), split; linarith end instance : archimedean ℚ := archimedean_iff_rat_le.2 $ λ q, ⟨q, by rw rat.cast_id⟩ @[simp] theorem rat.cast_round {α : Type*} [discrete_linear_ordered_field α] [archimedean α] (x : ℚ) : by haveI := archimedean.floor_ring α; exact round (x:α) = round x := have ((x + (1 : ℚ) / (2 : ℚ) : ℚ) : α) = x + 1 / 2, by simp, by rw [round, round, ← this, rat.cast_floor] end
bf9daa107721931d07c2c61c35608ecff5496bc9
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/data/polynomial/basic.lean
e25ad643c47bd1057675af7f9af61a311111ff0d
[ "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
7,230
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import tactic.ring_exp import tactic.chain import algebra.monoid_algebra import data.finset.sort /-! # Theory of univariate polynomials Polynomials are represented as `add_monoid_algebra R ℕ`, where `R` is a commutative semiring. In this file, we define `polynomial`, provide basic instances, and prove an `ext` lemma. -/ noncomputable theory /-- `polynomial R` is the type of univariate polynomials over `R`. Polynomials should be seen as (semi-)rings with the additional constructor `X`. The embedding from `R` is called `C`. -/ def polynomial (R : Type*) [semiring R] := add_monoid_algebra R ℕ open finsupp add_monoid_algebra open_locale big_operators namespace polynomial universes u variables {R : Type u} {a : R} {m n : ℕ} section semiring variables [semiring R] {p q : polynomial R} instance : inhabited (polynomial R) := add_monoid_algebra.inhabited _ _ instance : semiring (polynomial R) := add_monoid_algebra.semiring instance {S} [semiring S] [semimodule S R] : semimodule S (polynomial R) := add_monoid_algebra.semimodule instance [subsingleton R] : unique (polynomial R) := add_monoid_algebra.unique @[simp] lemma support_zero : (0 : polynomial R).support = ∅ := rfl /-- `monomial s a` is the monomial `a * X^s` -/ def monomial (n : ℕ) : R →ₗ[R] polynomial R := finsupp.lsingle n lemma monomial_zero_right (n : ℕ) : monomial n (0 : R) = 0 := finsupp.single_zero lemma monomial_def (n : ℕ) (a : R) : monomial n a = finsupp.single n a := rfl lemma monomial_add (n : ℕ) (r s : R) : monomial n (r + s) = monomial n r + monomial n s := finsupp.single_add lemma monomial_mul_monomial (n m : ℕ) (r s : R) : monomial n r * monomial m s = monomial (n + m) (r * s) := add_monoid_algebra.single_mul_single lemma smul_monomial {S} [semiring S] [semimodule S R] (a : S) (n : ℕ) (b : R) : a • monomial n b = monomial n (a • b) := finsupp.smul_single _ _ _ /-- `X` is the polynomial variable (aka indeterminant). -/ def X : polynomial R := monomial 1 1 /-- `X` commutes with everything, even when the coefficients are noncommutative. -/ lemma X_mul : X * p = p * X := by { ext, simp [X, monomial, add_monoid_algebra.mul_apply, sum_single_index, add_comm] } lemma X_pow_mul {n : ℕ} : X^n * p = p * X^n := begin induction n with n ih, { simp, }, { conv_lhs { rw pow_succ', }, rw [mul_assoc, X_mul, ←mul_assoc, ih, mul_assoc, ←pow_succ'], } end lemma X_pow_mul_assoc {n : ℕ} : (p * X^n) * q = (p * q) * X^n := by rw [mul_assoc, X_pow_mul, ←mul_assoc] lemma commute_X (p : polynomial R) : commute X p := X_mul /-- coeff p n is the coefficient of X^n in p -/ def coeff (p : polynomial R) : ℕ → R := @coe_fn (ℕ →₀ R) _ p @[simp] lemma coeff_mk (s) (f) (h) : coeff (finsupp.mk s f h : polynomial R) = f := rfl lemma coeff_monomial : coeff (monomial n a) m = if n = m then a else 0 := by { dsimp [monomial, coeff], rw finsupp.single_apply, congr } @[simp] lemma coeff_zero (n : ℕ) : coeff (0 : polynomial R) n = 0 := rfl @[simp] lemma coeff_one_zero : coeff (1 : polynomial R) 0 = 1 := coeff_monomial @[simp] lemma coeff_X_one : coeff (X : polynomial R) 1 = 1 := coeff_monomial @[simp] lemma coeff_X_zero : coeff (X : polynomial R) 0 = 0 := coeff_monomial @[simp] lemma coeff_monomial_succ : coeff (monomial (n+1) a) 0 = 0 := by simp [coeff_monomial] lemma coeff_X : coeff (X : polynomial R) n = if 1 = n then 1 else 0 := coeff_monomial lemma coeff_X_of_ne_one {n : ℕ} (hn : n ≠ 1) : coeff (X : polynomial R) n = 0 := by rw [coeff_X, if_neg hn.symm] theorem ext_iff {p q : polynomial R} : p = q ↔ ∀ n, coeff p n = coeff q n := finsupp.ext_iff @[ext] lemma ext {p q : polynomial R} : (∀ n, coeff p n = coeff q n) → p = q := finsupp.ext @[ext] lemma add_hom_ext' {M : Type*} [add_monoid M] {f g : polynomial R →+ M} (h : ∀ n, f.comp (monomial n).to_add_monoid_hom = g.comp (monomial n).to_add_monoid_hom) : f = g := finsupp.add_hom_ext' h lemma add_hom_ext {M : Type*} [add_monoid M] {f g : polynomial R →+ M} (h : ∀ n a, f (monomial n a) = g (monomial n a)) : f = g := finsupp.add_hom_ext h @[ext] lemma lhom_ext' {M : Type*} [add_comm_monoid M] [semimodule R M] {f g : polynomial R →ₗ[R] M} (h : ∀ n, f.comp (monomial n) = g.comp (monomial n)) : f = g := finsupp.lhom_ext' h -- this has the same content as the subsingleton lemma eq_zero_of_eq_zero (h : (0 : R) = (1 : R)) (p : polynomial R) : p = 0 := by rw [←one_smul R p, ←h, zero_smul] lemma support_monomial (n) (a : R) (H : a ≠ 0) : (monomial n a).support = singleton n := finsupp.support_single_ne_zero H lemma support_monomial' (n) (a : R) : (monomial n a).support ⊆ singleton n := finsupp.support_single_subset lemma X_pow_eq_monomial (n) : X ^ n = monomial n (1:R) := begin induction n with n hn, { refl, }, { rw [pow_succ', hn, X, monomial_mul_monomial, one_mul] }, end lemma support_X_pow (H : ¬ (1:R) = 0) (n : ℕ) : (X^n : polynomial R).support = singleton n := begin convert support_monomial n 1 H, exact X_pow_eq_monomial n, end lemma support_X_empty (H : (1:R)=0) : (X : polynomial R).support = ∅ := begin rw [X, H, monomial_zero_right, support_zero], end lemma support_X (H : ¬ (1 : R) = 0) : (X : polynomial R).support = singleton 1 := begin rw [← pow_one X, support_X_pow H 1], end lemma monomial_left_inj {R : Type*} [semiring R] {a : R} (ha : a ≠ 0) {i j : ℕ} : (monomial i a) = (monomial j a) ↔ i = j := finsupp.single_left_inj ha end semiring section comm_semiring variables [comm_semiring R] instance : comm_semiring (polynomial R) := add_monoid_algebra.comm_semiring end comm_semiring section ring variables [ring R] instance : ring (polynomial R) := add_monoid_algebra.ring @[simp] lemma coeff_neg (p : polynomial R) (n : ℕ) : coeff (-p) n = -coeff p n := rfl @[simp] lemma coeff_sub (p q : polynomial R) (n : ℕ) : coeff (p - q) n = coeff p n - coeff q n := rfl @[simp] lemma monomial_neg (n : ℕ) (a : R) : monomial n (-a) = -(monomial n a) := by rw [eq_neg_iff_add_eq_zero, ←monomial_add, neg_add_self, monomial_zero_right] end ring instance [comm_ring R] : comm_ring (polynomial R) := add_monoid_algebra.comm_ring section nonzero_semiring variables [semiring R] [nontrivial R] instance : nontrivial (polynomial R) := add_monoid_algebra.nontrivial lemma X_ne_zero : (X : polynomial R) ≠ 0 := mt (congr_arg (λ p, coeff p 1)) (by simp) end nonzero_semiring section repr variables [semiring R] local attribute [instance, priority 100] classical.prop_decidable instance [has_repr R] : has_repr (polynomial R) := ⟨λ p, if p = 0 then "0" else (p.support.sort (≤)).foldr (λ n a, a ++ (if a = "" then "" else " + ") ++ if n = 0 then "C (" ++ repr (coeff p n) ++ ")" else if n = 1 then if (coeff p n) = 1 then "X" else "C (" ++ repr (coeff p n) ++ ") * X" else if (coeff p n) = 1 then "X ^ " ++ repr n else "C (" ++ repr (coeff p n) ++ ") * X ^ " ++ repr n) ""⟩ end repr end polynomial
9f0244051dd62e8710527f4bf640e3ef42cfd58d
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/set/pairwise/basic.lean
25b2a2fac226ea5f8a783f80bc0cc96bf31db654
[ "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,667
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 data.set.function import logic.relation import logic.pairwise /-! # Relations holding pairwise > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file develops pairwise relations and defines pairwise disjoint indexed sets. We also prove many basic facts about `pairwise`. It is possible that an intermediate file, with more imports than `logic.pairwise` but not importing `data.set.function` would be appropriate to hold many of these basic facts. ## Main declarations * `set.pairwise_disjoint`: `s.pairwise_disjoint f` states that images under `f` of distinct elements of `s` are either equal or `disjoint`. ## Notes The spelling `s.pairwise_disjoint id` is preferred over `s.pairwise disjoint` to permit dot notation on `set.pairwise_disjoint`, even though the latter unfolds to something nicer. -/ open function order set variables {α β γ ι ι' : Type*} {r p q : α → α → Prop} section pairwise variables {f g : ι → α} {s t u : set α} {a b : α} lemma pairwise_on_bool (hr : symmetric r) {a b : α} : pairwise (r on (λ c, cond c a b)) ↔ r a b := by simpa [pairwise, function.on_fun] using @hr a b lemma pairwise_disjoint_on_bool [semilattice_inf α] [order_bot α] {a b : α} : pairwise (disjoint on (λ c, cond c a b)) ↔ disjoint a b := pairwise_on_bool disjoint.symm lemma symmetric.pairwise_on [linear_order ι] (hr : symmetric r) (f : ι → α) : pairwise (r on f) ↔ ∀ ⦃m n⦄, m < n → r (f m) (f n) := ⟨λ h m n hmn, h hmn.ne, λ h m n hmn, hmn.lt_or_lt.elim (@h _ _) (λ h', hr (h h'))⟩ lemma pairwise_disjoint_on [semilattice_inf α] [order_bot α] [linear_order ι] (f : ι → α) : pairwise (disjoint on f) ↔ ∀ ⦃m n⦄, m < n → disjoint (f m) (f n) := symmetric.pairwise_on disjoint.symm f lemma pairwise_disjoint.mono [semilattice_inf α] [order_bot α] (hs : pairwise (disjoint on f)) (h : g ≤ f) : pairwise (disjoint on g) := hs.mono (λ i j hij, disjoint.mono (h i) (h j) hij) namespace set lemma pairwise.mono (h : t ⊆ s) (hs : s.pairwise r) : t.pairwise r := λ x xt y yt, hs (h xt) (h yt) lemma pairwise.mono' (H : r ≤ p) (hr : s.pairwise r) : s.pairwise p := hr.imp H lemma pairwise_top (s : set α) : s.pairwise ⊤ := pairwise_of_forall s _ (λ a b, trivial) protected lemma subsingleton.pairwise (h : s.subsingleton) (r : α → α → Prop) : s.pairwise r := λ x hx y hy hne, (hne (h hx hy)).elim @[simp] lemma pairwise_empty (r : α → α → Prop) : (∅ : set α).pairwise r := subsingleton_empty.pairwise r @[simp] lemma pairwise_singleton (a : α) (r : α → α → Prop) : set.pairwise {a} r := subsingleton_singleton.pairwise r lemma pairwise_iff_of_refl [is_refl α r] : s.pairwise r ↔ ∀ ⦃a⦄, a ∈ s → ∀ ⦃b⦄, b ∈ s → r a b := forall₄_congr $ λ a _ b _, or_iff_not_imp_left.symm.trans $ or_iff_right_of_imp of_eq alias pairwise_iff_of_refl ↔ pairwise.of_refl _ lemma nonempty.pairwise_iff_exists_forall [is_equiv α r] {s : set ι} (hs : s.nonempty) : (s.pairwise (r on f)) ↔ ∃ z, ∀ x ∈ s, r (f x) z := begin fsplit, { rcases hs with ⟨y, hy⟩, refine λ H, ⟨f y, λ x hx, _⟩, rcases eq_or_ne x y with rfl|hne, { apply is_refl.refl }, { exact H hx hy hne } }, { rintro ⟨z, hz⟩ x hx y hy hne, exact @is_trans.trans α r _ (f x) z (f y) (hz _ hx) (is_symm.symm _ _ $ hz _ hy) } end /-- For a nonempty set `s`, a function `f` takes pairwise equal values on `s` if and only if for some `z` in the codomain, `f` takes value `z` on all `x ∈ s`. See also `set.pairwise_eq_iff_exists_eq` for a version that assumes `[nonempty ι]` instead of `set.nonempty s`. -/ lemma nonempty.pairwise_eq_iff_exists_eq {s : set α} (hs : s.nonempty) {f : α → ι} : (s.pairwise (λ x y, f x = f y)) ↔ ∃ z, ∀ x ∈ s, f x = z := hs.pairwise_iff_exists_forall lemma pairwise_iff_exists_forall [nonempty ι] (s : set α) (f : α → ι) {r : ι → ι → Prop} [is_equiv ι r] : (s.pairwise (r on f)) ↔ ∃ z, ∀ x ∈ s, r (f x) z := begin rcases s.eq_empty_or_nonempty with rfl|hne, { simp }, { exact hne.pairwise_iff_exists_forall } end /-- A function `f : α → ι` with nonempty codomain takes pairwise equal values on a set `s` if and only if for some `z` in the codomain, `f` takes value `z` on all `x ∈ s`. See also `set.nonempty.pairwise_eq_iff_exists_eq` for a version that assumes `set.nonempty s` instead of `[nonempty ι]`. -/ lemma pairwise_eq_iff_exists_eq [nonempty ι] (s : set α) (f : α → ι) : (s.pairwise (λ x y, f x = f y)) ↔ ∃ z, ∀ x ∈ s, f x = z := pairwise_iff_exists_forall s f lemma pairwise_union : (s ∪ t).pairwise r ↔ s.pairwise r ∧ t.pairwise r ∧ ∀ (a ∈ s) (b ∈ t), a ≠ b → r a b ∧ r b a := begin simp only [set.pairwise, mem_union, or_imp_distrib, forall_and_distrib], exact ⟨λ H, ⟨H.1.1, H.2.2, H.2.1, λ x hx y hy hne, H.1.2 y hy x hx hne.symm⟩, λ H, ⟨⟨H.1, λ x hx y hy hne, H.2.2.2 y hy x hx hne.symm⟩, H.2.2.1, H.2.1⟩⟩ end lemma pairwise_union_of_symmetric (hr : symmetric r) : (s ∪ t).pairwise r ↔ s.pairwise r ∧ t.pairwise r ∧ ∀ (a ∈ s) (b ∈ t), a ≠ b → r a b := pairwise_union.trans $ by simp only [hr.iff, and_self] lemma pairwise_insert : (insert a s).pairwise r ↔ s.pairwise r ∧ ∀ b ∈ s, a ≠ b → r a b ∧ r b a := by simp only [insert_eq, pairwise_union, pairwise_singleton, true_and, mem_singleton_iff, forall_eq] lemma pairwise_insert_of_not_mem (ha : a ∉ s) : (insert a s).pairwise r ↔ s.pairwise r ∧ ∀ b ∈ s, r a b ∧ r b a := pairwise_insert.trans $ and_congr_right' $ forall₂_congr $ λ b hb, by simp [(ne_of_mem_of_not_mem hb ha).symm] lemma pairwise.insert (hs : s.pairwise r) (h : ∀ b ∈ s, a ≠ b → r a b ∧ r b a) : (insert a s).pairwise r := pairwise_insert.2 ⟨hs, h⟩ lemma pairwise.insert_of_not_mem (ha : a ∉ s) (hs : s.pairwise r) (h : ∀ b ∈ s, r a b ∧ r b a) : (insert a s).pairwise r := (pairwise_insert_of_not_mem ha).2 ⟨hs, h⟩ lemma pairwise_insert_of_symmetric (hr : symmetric r) : (insert a s).pairwise r ↔ s.pairwise r ∧ ∀ b ∈ s, a ≠ b → r a b := by simp only [pairwise_insert, hr.iff a, and_self] lemma pairwise_insert_of_symmetric_of_not_mem (hr : symmetric r) (ha : a ∉ s) : (insert a s).pairwise r ↔ s.pairwise r ∧ ∀ b ∈ s, r a b := by simp only [pairwise_insert_of_not_mem ha, hr.iff a, and_self] lemma pairwise.insert_of_symmetric (hs : s.pairwise r) (hr : symmetric r) (h : ∀ b ∈ s, a ≠ b → r a b) : (insert a s).pairwise r := (pairwise_insert_of_symmetric hr).2 ⟨hs, h⟩ lemma pairwise.insert_of_symmetric_of_not_mem (hs : s.pairwise r) (hr : symmetric r) (ha : a ∉ s) (h : ∀ b ∈ s, r a b) : (insert a s).pairwise r := (pairwise_insert_of_symmetric_of_not_mem hr ha).2 ⟨hs, h⟩ lemma pairwise_pair : set.pairwise {a, b} r ↔ (a ≠ b → r a b ∧ r b a) := by simp [pairwise_insert] lemma pairwise_pair_of_symmetric (hr : symmetric r) : set.pairwise {a, b} r ↔ (a ≠ b → r a b) := by simp [pairwise_insert_of_symmetric hr] lemma pairwise_univ : (univ : set α).pairwise r ↔ pairwise r := by simp only [set.pairwise, pairwise, mem_univ, forall_const] @[simp] lemma pairwise_bot_iff : s.pairwise (⊥ : α → α → Prop) ↔ (s : set α).subsingleton := ⟨λ h a ha b hb, h.eq ha hb id, λ h, h.pairwise _⟩ alias pairwise_bot_iff ↔ pairwise.subsingleton _ lemma inj_on.pairwise_image {s : set ι} (h : s.inj_on f) : (f '' s).pairwise r ↔ s.pairwise (r on f) := by simp [h.eq_iff, set.pairwise] {contextual := tt} end set end pairwise lemma pairwise_subtype_iff_pairwise_set (s : set α) (r : α → α → Prop) : pairwise (λ (x : s) (y : s), r x y) ↔ s.pairwise r := by simp only [pairwise, set.pairwise, set_coe.forall, ne.def, subtype.ext_iff, subtype.coe_mk] alias pairwise_subtype_iff_pairwise_set ↔ pairwise.set_of_subtype set.pairwise.subtype namespace set section partial_order_bot variables [partial_order α] [order_bot α] {s t : set ι} {f g : ι → α} /-- A set is `pairwise_disjoint` under `f`, if the images of any distinct two elements under `f` are disjoint. `s.pairwise disjoint` is (definitionally) the same as `s.pairwise_disjoint id`. We prefer the latter in order to allow dot notation on `set.pairwise_disjoint`, even though the former unfolds more nicely. -/ def pairwise_disjoint (s : set ι) (f : ι → α) : Prop := s.pairwise (disjoint on f) lemma pairwise_disjoint.subset (ht : t.pairwise_disjoint f) (h : s ⊆ t) : s.pairwise_disjoint f := pairwise.mono h ht lemma pairwise_disjoint.mono_on (hs : s.pairwise_disjoint f) (h : ∀ ⦃i⦄, i ∈ s → g i ≤ f i) : s.pairwise_disjoint g := λ a ha b hb hab, (hs ha hb hab).mono (h ha) (h hb) lemma pairwise_disjoint.mono (hs : s.pairwise_disjoint f) (h : g ≤ f) : s.pairwise_disjoint g := hs.mono_on (λ i _, h i) @[simp] lemma pairwise_disjoint_empty : (∅ : set ι).pairwise_disjoint f := pairwise_empty _ @[simp] lemma pairwise_disjoint_singleton (i : ι) (f : ι → α) : pairwise_disjoint {i} f := pairwise_singleton i _ lemma pairwise_disjoint_insert {i : ι} : (insert i s).pairwise_disjoint f ↔ s.pairwise_disjoint f ∧ ∀ j ∈ s, i ≠ j → disjoint (f i) (f j) := set.pairwise_insert_of_symmetric $ symmetric_disjoint.comap f lemma pairwise_disjoint_insert_of_not_mem {i : ι} (hi : i ∉ s) : (insert i s).pairwise_disjoint f ↔ s.pairwise_disjoint f ∧ ∀ j ∈ s, disjoint (f i) (f j) := pairwise_insert_of_symmetric_of_not_mem (symmetric_disjoint.comap f) hi lemma pairwise_disjoint.insert (hs : s.pairwise_disjoint f) {i : ι} (h : ∀ j ∈ s, i ≠ j → disjoint (f i) (f j)) : (insert i s).pairwise_disjoint f := set.pairwise_disjoint_insert.2 ⟨hs, h⟩ lemma pairwise_disjoint.insert_of_not_mem (hs : s.pairwise_disjoint f) {i : ι} (hi : i ∉ s) (h : ∀ j ∈ s, disjoint (f i) (f j)) : (insert i s).pairwise_disjoint f := (set.pairwise_disjoint_insert_of_not_mem hi).2 ⟨hs, h⟩ lemma pairwise_disjoint.image_of_le (hs : s.pairwise_disjoint f) {g : ι → ι} (hg : f ∘ g ≤ f) : (g '' s).pairwise_disjoint f := begin rintro _ ⟨a, ha, rfl⟩ _ ⟨b, hb, rfl⟩ h, exact (hs ha hb $ ne_of_apply_ne _ h).mono (hg a) (hg b), end lemma inj_on.pairwise_disjoint_image {g : ι' → ι} {s : set ι'} (h : s.inj_on g) : (g '' s).pairwise_disjoint f ↔ s.pairwise_disjoint (f ∘ g) := h.pairwise_image lemma pairwise_disjoint.range (g : s → ι) (hg : ∀ (i : s), f (g i) ≤ f i) (ht : s.pairwise_disjoint f) : (range g).pairwise_disjoint f := begin rintro _ ⟨x, rfl⟩ _ ⟨y, rfl⟩ hxy, exact (ht x.2 y.2 $ λ h, hxy $ congr_arg g $ subtype.ext h).mono (hg x) (hg y), end lemma pairwise_disjoint_union : (s ∪ t).pairwise_disjoint f ↔ s.pairwise_disjoint f ∧ t.pairwise_disjoint f ∧ ∀ ⦃i⦄, i ∈ s → ∀ ⦃j⦄, j ∈ t → i ≠ j → disjoint (f i) (f j) := pairwise_union_of_symmetric $ symmetric_disjoint.comap f lemma pairwise_disjoint.union (hs : s.pairwise_disjoint f) (ht : t.pairwise_disjoint f) (h : ∀ ⦃i⦄, i ∈ s → ∀ ⦃j⦄, j ∈ t → i ≠ j → disjoint (f i) (f j)) : (s ∪ t).pairwise_disjoint f := pairwise_disjoint_union.2 ⟨hs, ht, h⟩ -- classical lemma pairwise_disjoint.elim (hs : s.pairwise_disjoint f) {i j : ι} (hi : i ∈ s) (hj : j ∈ s) (h : ¬ disjoint (f i) (f j)) : i = j := hs.eq hi hj h end partial_order_bot section semilattice_inf_bot variables [semilattice_inf α] [order_bot α] {s t : set ι} {f g : ι → α} -- classical lemma pairwise_disjoint.elim' (hs : s.pairwise_disjoint f) {i j : ι} (hi : i ∈ s) (hj : j ∈ s) (h : f i ⊓ f j ≠ ⊥) : i = j := hs.elim hi hj $ λ hij, h hij.eq_bot lemma pairwise_disjoint.eq_of_le (hs : s.pairwise_disjoint f) {i j : ι} (hi : i ∈ s) (hj : j ∈ s) (hf : f i ≠ ⊥) (hij : f i ≤ f j) : i = j := hs.elim' hi hj $ λ h, hf $ (inf_of_le_left hij).symm.trans h end semilattice_inf_bot /-! ### Pairwise disjoint set of sets -/ variables {s : set ι} {t : set ι'} lemma pairwise_disjoint_range_singleton : (set.range (singleton : ι → set ι)).pairwise_disjoint id := begin rintro _ ⟨a, rfl⟩ _ ⟨b, rfl⟩ h, exact disjoint_singleton.2 (ne_of_apply_ne _ h), end lemma pairwise_disjoint_fiber (f : ι → α) (s : set α) : s.pairwise_disjoint (λ a, f ⁻¹' {a}) := λ a _ b _ h, disjoint_iff_inf_le.mpr $ λ i ⟨hia, hib⟩, h $ (eq.symm hia).trans hib -- classical lemma pairwise_disjoint.elim_set {s : set ι} {f : ι → set α} (hs : s.pairwise_disjoint f) {i j : ι} (hi : i ∈ s) (hj : j ∈ s) (a : α) (hai : a ∈ f i) (haj : a ∈ f j) : i = j := hs.elim hi hj $ not_disjoint_iff.2 ⟨a, hai, haj⟩ lemma pairwise_disjoint.prod {f : ι → set α} {g : ι' → set β} (hs : s.pairwise_disjoint f) (ht : t.pairwise_disjoint g) : (s ×ˢ t : set (ι × ι')).pairwise_disjoint (λ i, f i.1 ×ˢ g i.2) := λ ⟨i, i'⟩ ⟨hi, hi'⟩ ⟨j, j'⟩ ⟨hj, hj'⟩ hij, disjoint_left.2 $ λ ⟨a, b⟩ ⟨hai, hbi⟩ ⟨haj, hbj⟩, hij $ prod.ext (hs.elim_set hi hj _ hai haj) $ ht.elim_set hi' hj' _ hbi hbj lemma pairwise_disjoint_pi {ι' α : ι → Type*} {s : Π i, set (ι' i)} {f : Π i, ι' i → set (α i)} (hs : ∀ i, (s i).pairwise_disjoint (f i)) : ((univ : set ι).pi s).pairwise_disjoint (λ I, (univ : set ι).pi (λ i, f _ (I i))) := λ I hI J hJ hIJ, disjoint_left.2 $ λ a haI haJ, hIJ $ funext $ λ i, (hs i).elim_set (hI i trivial) (hJ i trivial) (a i) (haI i trivial) (haJ i trivial) /-- The partial images of a binary function `f` whose partial evaluations are injective are pairwise disjoint iff `f` is injective . -/ lemma pairwise_disjoint_image_right_iff {f : α → β → γ} {s : set α} {t : set β} (hf : ∀ a ∈ s, injective (f a)) : s.pairwise_disjoint (λ a, f a '' t) ↔ (s ×ˢ t).inj_on (λ p, f p.1 p.2) := begin refine ⟨λ hs x hx y hy (h : f _ _ = _), _, λ hs x hx y hy h, _⟩, { suffices : x.1 = y.1, { exact prod.ext this (hf _ hx.1 $ h.trans $ by rw this) }, refine hs.elim hx.1 hy.1 (not_disjoint_iff.2 ⟨_, mem_image_of_mem _ hx.2, _⟩), rw h, exact mem_image_of_mem _ hy.2 }, { refine disjoint_iff_inf_le.mpr _, rintro _ ⟨⟨a, ha, hab⟩, b, hb, rfl⟩, exact h (congr_arg prod.fst $ hs (mk_mem_prod hx ha) (mk_mem_prod hy hb) hab) } end /-- The partial images of a binary function `f` whose partial evaluations are injective are pairwise disjoint iff `f` is injective . -/ lemma pairwise_disjoint_image_left_iff {f : α → β → γ} {s : set α} {t : set β} (hf : ∀ b ∈ t, injective (λ a, f a b)) : t.pairwise_disjoint (λ b, (λ a, f a b) '' s) ↔ (s ×ˢ t).inj_on (λ p, f p.1 p.2) := begin refine ⟨λ ht x hx y hy (h : f _ _ = _), _, λ ht x hx y hy h, _⟩, { suffices : x.2 = y.2, { exact prod.ext (hf _ hx.2 $ h.trans $ by rw this) this }, refine ht.elim hx.2 hy.2 (not_disjoint_iff.2 ⟨_, mem_image_of_mem _ hx.1, _⟩), rw h, exact mem_image_of_mem _ hy.1 }, { refine disjoint_iff_inf_le.mpr _, rintro _ ⟨⟨a, ha, hab⟩, b, hb, rfl⟩, exact h (congr_arg prod.snd $ ht (mk_mem_prod ha hx) (mk_mem_prod hb hy) hab) } end end set lemma pairwise_disjoint_fiber (f : ι → α) : pairwise (disjoint on (λ a : α, f ⁻¹' {a})) := set.pairwise_univ.1 $ set.pairwise_disjoint_fiber f univ
9d55b6235cf9439bc437ad7acc237c59fc6d68d1
54c9ed381c63410c9b6af3b0a1722c41152f037f
/Lib4/Examples/Asymptotics.lean
11d138a889a276db95d8896717689a65a4eb0d7c
[ "Apache-2.0" ]
permissive
dselsam/binport
0233f1aa961a77c4fc96f0dccc780d958c5efc6c
aef374df0e169e2c3f1dc911de240c076315805c
refs/heads/master
1,687,453,448,108
1,627,483,296,000
1,627,483,296,000
333,825,622
0
0
null
null
null
null
UTF-8
Lean
false
false
2,794
lean
import Mathlib.analysis.normed_space.basic import Mathlib.topology.local_homeomorph namespace Mathlib open filter open set namespace asymptotics macro "∀ᶠ " xs:Lean.explicitBinders " in " l:term "," b:term : term => do `($(← Lean.expandExplicitBinders `filter.eventually xs b) $l) macro "∥ " x:term " ∥" : term => `(norm $x) -- TODO: Type* syntax variable {α : Type} {β : Type} {E : Type} {F : Type} {G : Type} {E' : Type} {F' : Type} {G' : Type} {R : Type} {R' : Type} variable [has_norm E] [has_norm F] [has_norm G] [normed_group E'] [normed_group F'] [normed_group G'] [normed_ring R] [normed_ring R'] {c c' : ℝ} {f : α → E} {g : α → F} {k : α → G} {f' : α → E'} {g' : α → F'} {k' : α → G'} {l l' : filter α} section defs def is_O_with (c : ℝ) (f : α → E) (g : α → F) (l : filter α) : Prop := ∀ᶠ x in l, ∥f x∥ ≤ c * ∥g x∥ theorem is_O_with_iff {c : real} {f : α → E} {g : α → F} {l : filter α} : is_O_with c f g l ↔ ∀ᶠ x in l, ∥f x∥ ≤ c * ∥g x∥ := iff.rfl theorem is_O_with.of_bound {c : real} {f : α → E} {g : α → F} {l : filter α} (h : ∀ᶠ x in l, ∥f x∥ ≤ c * ∥g x∥) : is_O_with c f g l := h def is_O (f : α → E) (g : α → F) (l : filter α) : Prop := ∃ c : ℝ, is_O_with c f g l theorem is_O_iff_is_O_with {f : α → E} {g : α → F} {l : filter α} : is_O f g l ↔ ∃ c : ℝ, is_O_with c f g l := iff.rfl theorem is_O_iff {f : α → E} {g : α → F} {l : filter α} : is_O f g l ↔ ∃ c : ℝ, ∀ᶠ x in l, ∥f x∥ ≤ c * ∥g x∥ := iff.rfl theorem is_O.of_bound (c : ℝ) {f : α → E} {g : α → F} {l : filter α} (h : ∀ᶠ x in l, ∥f x∥ ≤ c * ∥g x∥) : is_O f g l := ⟨c, h⟩ def is_o (f : α → E) (g : α → F) (l : filter α) : Prop := ∀ (c : ℝ), 0 < c → is_O_with c f g l theorem is_o_iff_forall_is_O_with {f : α → E} {g : α → F} {l : filter α} : is_o f g l ↔ ∀ (c : ℝ), 0 < c → is_O_with c f g l := iff.rfl theorem is_o_iff {f : α → E} {g : α → F} {l : filter α} : is_o f g l ↔ ∀ (c : ℝ), 0 < c → ∀ᶠ x in l, ∥f x∥ ≤ c * ∥g x∥ := iff.rfl theorem is_o.def {f : α → E} {g : α → F} {l : filter α} (h : is_o f g l) {c : ℝ} (hc : 0 < c) : ∀ᶠ x in l, ∥f x∥ ≤ c * ∥g x∥ := h _ hc theorem is_o.def' {f : α → E} {g : α → F} {l : filter α} (h : is_o f g l) {c : ℝ} (hc : 0 < c) : is_O_with c f g l := h _ hc end defs theorem is_O_with.is_O (h : is_O_with c f g l) : is_O f g l := ⟨c, h⟩ theorem is_o.is_O_with (hgf : is_o f g l) : is_O_with 1 f g l := hgf _ zero_lt_one theorem is_o.is_O (hgf : is_o f g l) : is_O f g l := hgf.is_O_with.is_O end asymptotics end Mathlib
960996b499674dcf7737a311cf01653d6e71d9a8
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/data/list/nodup.lean
0a00cc2e111bee59c2d3baa35c4870ade9fcc39e
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,570
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.pairwise import data.list.forall2 /-! # Lists with no duplicates `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} 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) theorem nodup_cons_of_nodup {a : α} {l : list α} (m : a ∉ l) (n : nodup l) : nodup (a::l) := nodup_cons.2 ⟨m, n⟩ theorem nodup_singleton (a : α) : nodup [a] := nodup_cons_of_nodup (not_mem_nil a) nodup_nil theorem nodup_of_nodup_cons {a : α} {l : list α} (h : nodup (a::l)) : nodup l := (nodup_cons.1 h).2 theorem not_mem_of_nodup_cons {a : α} {l : list α} (h : nodup (a::l)) : a ∉ l := (nodup_cons.1 h).1 theorem not_nodup_cons_of_mem {a : α} {l : list α} : a ∈ l → ¬ nodup (a :: l) := imp_not_comm.1 not_mem_of_nodup_cons theorem nodup_of_sublist {l₁ l₂ : list α} : l₁ <+ l₂ → nodup l₂ → nodup l₁ := pairwise_of_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 (nodup_of_sublist h d), begin induction l with a l IH; intro h, {exact nodup_nil}, exact nodup_cons_of_nodup (λ al, h a $ cons_sublist_cons _ $ singleton_sublist.2 al) (IH $ λ a s, h a $ sublist_cons_of_sublist _ s) 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 {α : Type*} {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.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 (nodup_of_nodup_cons h), 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) theorem nodup_of_nodup_append_left {l₁ l₂ : list α} : nodup (l₁++l₂) → nodup l₁ := nodup_of_sublist (sublist_append_left l₁ l₂) theorem nodup_of_nodup_append_right {l₁ l₂ : list α} : nodup (l₁++l₂) → nodup l₂ := nodup_of_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 theorem nodup_append_of_nodup {l₁ l₂ : list α} (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] theorem nodup_of_nodup_map (f : α → β) {l : list α} : nodup (map f l) → nodup l := pairwise_of_pairwise_map f $ λ a b, mt $ congr_arg f theorem nodup_map_on {f : α → β} {l : list α} (H : ∀x∈l, ∀y∈l, f x = f y → x = y) (d : nodup l) : nodup (map f l) := pairwise_map_of_pairwise _ (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, nodup_map_on h d⟩ theorem nodup_map {f : α → β} {l : list α} (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_nodup_map _, nodup_map hf⟩ @[simp] theorem nodup_attach {l : list α} : nodup (attach l) ↔ nodup l := ⟨λ h, attach_map_val l ▸ nodup_map (λ a b, subtype.eq) h, λ h, nodup_of_nodup_map subtype.val ((attach_map_val l).symm ▸ h)⟩ theorem 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 nodup_map (λ ⟨a, ha⟩ ⟨b, hb⟩ h, by congr; exact hf a (H _ ha) b (H _ hb) h) (nodup_attach.2 h) theorem nodup_filter (p : α → Prop) [decidable_pred p] {l} : nodup l → nodup (filter p l) := pairwise_filter_of_pairwise p @[simp] theorem nodup_reverse {l : list α} : nodup (reverse l) ↔ nodup l := pairwise_reverse.trans $ by simp only [nodup, ne.def, eq_comm] theorem nodup_erase_eq_filter [decidable_eq α] (a : α) {l} (d : nodup l) : 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 theorem nodup_erase_of_nodup [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) := nodup_of_sublist (erase_sublist _ _) theorem nodup_diff [decidable_eq α] : ∀ {l₁ l₂ : list α} (h : l₁.nodup), (l₁.diff l₂).nodup | l₁ [] h := h | l₁ (a::l₂) h := by rw diff_cons; exact nodup_diff (nodup_erase_of_nodup _ h) theorem mem_erase_iff_of_nodup [decidable_eq α] {a b : α} {l} (d : nodup l) : a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l := by rw nodup_erase_eq_filter b d; simp only [mem_filter, and_comm] theorem mem_erase_of_nodup [decidable_eq α] {a : α} {l} (h : nodup l) : a ∉ l.erase a := λ H, ((mem_erase_iff_of_nodup h).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'] theorem nodup_product {l₁ : list α} {l₂ : list β} (d₁ : nodup l₁) (d₂ : nodup l₂) : nodup (product l₁ l₂) := nodup_bind.2 ⟨λ a ma, nodup_map (left_inverse.injective (λ b, (rfl : (a,b).2 = b))) d₂, 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⟩ theorem nodup_sigma {σ : α → Type*} {l₁ : list α} {l₂ : Π a, list (σ a)} (d₁ : nodup l₁) (d₂ : ∀ a, nodup (l₂ a)) : nodup (l₁.sigma l₂) := nodup_bind.2 ⟨λ a ma, nodup_map (λ b b' h, by injection h with _ h; exact eq_of_heq h) (d₂ a), 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⟩ theorem nodup_filter_map {f : α → option β} {l : list α} (H : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a') : nodup l → nodup (filter_map f l) := pairwise_filter_map_of_pairwise f $ λ a a' n b bm b' bm' e, n $ H a a' b' (e ▸ bm) bm' theorem nodup_concat {a : α} {l : list α} (h : a ∉ l) (h' : nodup l) : nodup (concat l a) := by rw concat_eq_append; exact nodup_append_of_nodup h' (nodup_singleton _) (disjoint_singleton.2 h) theorem nodup_insert [decidable_eq α] {a : α} {l : list α} (h : nodup l) : nodup (insert a l) := 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 theorem nodup_union [decidable_eq α] (l₁ : list α) {l₂ : list α} (h : nodup l₂) : nodup (l₁ ∪ l₂) := begin induction l₁ with a l₁ ih generalizing l₂, { exact h }, apply nodup_insert, exact ih h end theorem nodup_inter_of_nodup [decidable_eq α] {l₁ : list α} (l₂) : nodup l₁ → nodup (l₁ ∩ l₂) := nodup_filter _ @[simp] theorem nodup_sublists {l : list α} : nodup (sublists l) ↔ nodup l := ⟨λ h, nodup_of_nodup_map _ (nodup_of_sublist (map_ret_sublist_sublists _) h), λ h, (pairwise_sublists h).imp (λ _ _ h, mt reverse_inj.2 h.to_ne)⟩ @[simp] theorem nodup_sublists' {l : list α} : nodup (sublists' l) ↔ nodup l := by rw [sublists'_eq_sublists, nodup_map_iff reverse_injective, nodup_sublists, nodup_reverse] lemma nodup_sublists_len {α : Type*} (n) {l : list α} (nd : nodup l) : (sublists_len n l).nodup := nodup_of_sublist (sublists_len_sublist_sublists' _ _) (nodup_sublists'.2 nd) lemma diff_eq_filter_of_nodup [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, diff_eq_filter_of_nodup (nodup_erase_of_nodup _ hl₁), nodup_erase_eq_filter _ hl₁, filter_filter], simp only [mem_cons_iff, not_or_distrib, and.comm], congr end lemma mem_diff_iff_of_nodup [decidable_eq α] {l₁ l₂ : list α} (hl₁ : l₁.nodup) {a : α} : a ∈ l₁.diff l₂ ↔ a ∈ l₁ ∧ a ∉ l₂ := by rw [diff_eq_filter_of_nodup hl₁, mem_filter] 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 _ _)), nodup_update_nth (nodup_cons.1 hl).2 (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_on {l : list α} {r : α → α → Prop} (hl : l.nodup) (h : {x | x ∈ l}.pairwise_on r) : l.pairwise r := hl.pairwise_of_forall_ne h end list theorem option.to_list_nodup {α} : ∀ o : option α, o.to_list.nodup | none := list.nodup_nil | (some x) := list.nodup_singleton x
5d79130effdb6a14bb6b1ffc0cf2b991cd8227f0
f10d66a159ce037d07005bd6021cee6bbd6d5ff0
/unused_lemmas.lean
08fbb88e670cb321dabdda92cb94115c379e146f
[]
no_license
johoelzl/mason-stother
0c78bca183eb729d7f0f93e87ce073bc8cd8808d
573ecfaada288176462c03c87b80ad05bdab4644
refs/heads/master
1,631,751,973,492
1,528,923,934,000
1,528,923,934,000
109,133,224
0
1
null
null
null
null
UTF-8
Lean
false
false
4,208
lean
#exit -- so every polynomial has a GCD? Shouldn't there be some restriction on α --axiom gcd_ax : ∀ a b : polynomial α,( ∃( d : polynomial α ), (is_gcd a b d)) --@[instance] constant polynomial.has_gcd : has_gcd (polynomial α) --def monic (p : polynomial α) : Prop := leading_coeff p = 1 --Assume has_gcd on polynomials --∈ set.range (units.val : _ → polynomial α) --We need to define the radical and the number of distinct roots of a polynomial --First define roots structure roots_of (a : polynomial α):= --Can this be made as a set directly? (val : α)(h1 : root_of a val) def roots_of_as_set (a : polynomial α) := set_of (root_of a) --Can we proof this set is finite? --Can I define the radical? --Proof linear factor iff root, makes use of the division algorithm. Hence that polynomials are a euclidian ring. section field variable β : Type u variable [field β] --Again an anoying diamond porblem with field to UFD open finsupp def lin_fac {β : Type u} [field β] (q : β) : polynomial β := X - C q lemma deg_ln_fac {q : β} : degree (X + (- C q)) = 1 := have one_le_deg : 1 ≤ degree (X + (- C q)), from have h1: ((X : polynomial β) + (- C q)) 1 = (1:β), -- Type annotation is needed here, otherwise + will fail. begin show (X : polynomial β) 1 + - (C q : polynomial β) 1 = (1:β), rw [X, single_eq_same, C, single_eq_of_ne]; simp end, have ((X : polynomial β) + (- C q)) 1 ≠ 0, from calc ((X : polynomial β) + (- C q)) 1 = 1 : h1 ... ≠ 0 : one_ne_zero, le_degree this, have ((0 : β ) ≠ (1 : β)), from zero_ne_one, have h_deg_X : degree X = 1, from degree_X this, have degree (C q) = 0, from degree_C, have h_deg_neg_C :degree (- C q) = 0, by rw [degree_neg, this], have ha: degree (X + (- C q)) ≤ 1, from calc degree (X + (- C q)) ≤ max (degree (X)) (degree (- C q)) : degree_add ... ≤ max 1 0 : by rw [h_deg_X, h_deg_neg_C ] ... = 1 : max_eq_left zero_le_one, have 1 ≤ degree (X + (- C q)), from (one_le_deg), show degree (X + (- C q)) = 1, from le_antisymm ha this open euclidean_domain lemma degree_ne_zero_ne_zero2 {f : polynomial β } : degree f ≠ 0 → f ≠ 0 :=--I want to apply normal by_cpntradiction here, but I don't know how to apply that, due to ambiguous overload. begin intro, apply (@classical.by_contradiction (f ≠ 0) _), intro, have h3: (f = 0), from iff.elim_left (@not_not _ (classical.prop_decidable _)) a_1, have h4: degree f = 0, calc degree f = degree 0 : by rw [h3] ... = 0 : degree_zero, apply a h4 end /- NOT USED: --Why is there no instance for has subtract? lemma root_iff_lin_fac : ∀p : polynomial β, ∀k:β, (root_of p k) ↔ (X - C k ∣ p) := begin intros, apply iff.intro, {intro, --apply (exists.elim a), intros, -- have h1 : 1 ≠ 0, from dec_trivial, have h2 : degree (X + (- (C k ))) ≠ 0, from calc degree (X + (- (C k))) = 1 : @deg_ln_fac _ _ k ... ≠ 0 : one_ne_zero, have h3 : (X + (- (C k))) ≠ 0, from degree_ne_zero_ne_zero2 _ h2, --Mogelijk gaat deze fout omdat het lemma niet was gedefinieerd voor een integral domain. --Lemma is gedefinieerd voor semiring, maar mogelijk is het niet zo dat de integral domain kan worden omgezet in een semiring? -- Ik zie dat er wel een instance is met naar comm_semi_ring vanaf comm_ring. En een comm_semiring is een ring. have h4 : (∃ q : polynomial β, ∃ r : polynomial β ,( (p = q * (X + (- (C k))) + r) ∧ ((r = 0) ∨ ( (norm r ) < (norm (X + (- (C k))))) ) ) ), apply @h_norm (polynomial β) _ p (X + (- (C k))) (degree_ne_zero_ne_zero2 β h2) , --dom.h p (X + (- (C α))) h3 --Er gaat gebeurt iets geks met de type universes, want degree h2, zit in type universe max 1 (u+1), en de andere zir in (u+1). --Of mogelijk heeft het te maken met field, integral_domain enzovoort. Maar snapt ie zelf dan niet dat max 1 (1+u) = 1 + u? --Mogelijk gaat het fout door het gebruik van de classical axioms, en dat je dat dan overal moet doen?? Zie maar degree_ne_zero2 admit } , {admit} end -/ lemma finite_roots {a : polynomial β} : set.finite (roots_of_as_set a):= sorry --How do we do an induction on the degree? end field
c6cd6cf16b1c7d96d63d9dce1211a6600d504f1d
e2c1ee9c02c59b832eb48536755242ce5f9b2c3e
/src/t5.lean
d7d98e768cf36cfd365bcb197fd362f2d8b0d721
[]
no_license
yairgueta/Lean
cb5bb16d81674e8a07f85c9dbeb56dc2f543d4eb
af8a4fa24f76edfdd0dd33f013db194e611e6a86
refs/heads/master
1,676,275,529,938
1,610,289,661,000
1,610,289,661,000
328,405,309
0
0
null
null
null
null
UTF-8
Lean
false
false
2,997
lean
/- Yair Gueta : 208624908 : t4 Exercise 4 -/ import data.int.basic variable U : Type variables R : U → U → Prop -- Question 9: example : (∃ x, ∀ y, R x y) → ∀ y, ∃ x, R x y := begin intro, cases a with x, intro, existsi x, exact a_h y end -- Question 10: theorem foo {A : Type} {a b c : A} : a = b → c = b → a = c := begin intros, exact a_1.trans a_2.symm, end -- notice that you can now use foo as a rule. The curly braces mean that -- you do not have to give A, a, b, or c section variable A : Type variables a b c : A example (h1 : a = b) (h2 : c = b) : a = c := foo h1 h2 end section variable {A : Type} variables {a b c : A} -- replace the sorry with a proof, using foo and rfl, without using eq.symm. theorem my_symm (h : b = a) : a = b := by exact foo (eq.refl a) h -- now use foo and my_symm to prove transitivity theorem my_trans (h1 : a = b) (h2 : b = c) : a = c := by exact foo h1 (my_symm h2) end -- Question 11: -- these are the axioms for a commutative ring #check @add_assoc #check @add_comm #check @add_zero #check @zero_add #check @mul_assoc #check @mul_comm #check @mul_one #check @one_mul #check @left_distrib #check @right_distrib #check @add_left_neg #check @add_right_neg #check @sub_eq_add_neg variables x y z : int theorem t1 : x - x = 0 := calc x - x = x + -x : by rw sub_eq_add_neg ... = 0 : by rw add_right_neg theorem t2 (h : x + y = x + z) : y = z := calc y = 0 + y : by rw zero_add ... = (-x + x) + y : by rw add_left_neg ... = -x + (x + y) : by rw add_assoc ... = -x + (x + z) : by rw h ... = (-x + x) + z : by rw add_assoc ... = 0 + z : by rw add_left_neg ... = z : by rw zero_add theorem t3 (h : x + y = z + y) : x = z := calc x = x + 0 : by rw add_zero ... = x + (y + -y) : by rw ← add_right_neg ... = (x + y) + -y : by rw add_assoc ... = (z + y) + -y : by rw h ... = z + (y + -y) : by rw add_assoc ... = z + 0 : by rw add_right_neg ... = z : by rw add_zero theorem t4 (h : x + y = 0) : x = -y := calc x = x + 0 : by rw add_zero ... = x + (y + -y) : by rw add_right_neg ... = (x + y) + -y : by rw add_assoc ... = 0 + -y : by rw h ... = -y : by rw zero_add theorem t5 : x * 0 = 0 := have h1 : x * 0 + x * 0 = x * 0 + 0, from calc x * 0 + x * 0 = x * (0 + 0) : by rw mul_add ... = x * 0 : by rw add_zero ... = x * 0 + 0 : by rw add_zero, show x * 0 = 0, from t2 _ _ _ h1 theorem t6 : x * (-y) = -(x * y) := have h1 : x * (-y) + x * y = 0, from calc x * (-y) + x * y = x * (-y + y) : by rw mul_add ... = x * 0 : by rw add_left_neg ... = 0 : by rw t5 x, show x * (-y) = -(x * y), from t4 _ _ h1 theorem t7 : x + x = 2 * x := calc x + x = 1 * x + 1 * x : by rw one_mul ... = (1 + 1) * x : by rw add_mul ... = 2 * x : rfl
61fdc53188a2c37b8ee7349abed5baaabacbc859
618003631150032a5676f229d13a079ac875ff77
/src/tactic/lint/simp.lean
9a2918da77172be3b27dc49b2de8885e96b77d82
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
8,539
lean
/- Copyright (c) 2020 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import tactic.lint.basic /-! # Linter for simplification lemmas This files defines several linters that prevent common mistakes when declaring simp lemmas: * `simp_nf` checks that the left-hand side of a simp lemma is not simplified by a different lemma. * `simp_var_head` checks that the head symbol of the left-hand side is not a variable. * `simp_comm` checks that commutativity lemmas are not marked as simplification lemmas. -/ open tactic expr /-- `simp_lhs_rhs ty` returns the left-hand and right-hand side of a simp lemma with type `ty`. -/ private meta def simp_lhs_rhs : expr → tactic (expr × expr) | ty := do ty ← whnf ty transparency.reducible, -- We only detect a fixed set of simp relations here. -- This is somewhat justified since for a custom simp relation R, -- the simp lemma `R a b` is implicitly converted to `R a b ↔ true` as well. match ty with | `(¬ %%lhs) := pure (lhs, `(false)) | `(%%lhs = %%rhs) := pure (lhs, rhs) | `(%%lhs ↔ %%rhs) := pure (lhs, rhs) | (expr.pi n bi a b) := do l ← mk_local' n bi a, simp_lhs_rhs (b.instantiate_var l) | ty := pure (ty, `(true)) end /-- `simp_lhs ty` returns the left-hand side of a simp lemma with type `ty`. -/ private meta def simp_lhs (ty : expr): tactic expr := prod.fst <$> simp_lhs_rhs ty /-- `simp_is_conditional_core ty` returns `none` if `ty` is a conditional simp lemma, and `some lhs` otherwise. -/ private meta def simp_is_conditional_core : expr → tactic (option expr) | ty := do ty ← whnf ty transparency.semireducible, match ty with | `(¬ %%lhs) := pure lhs | `(%%lhs = _) := pure lhs | `(%%lhs ↔ _) := pure lhs | (expr.pi n bi a b) := do l ← mk_local' n bi a, some lhs ← simp_is_conditional_core (b.instantiate_var l) | pure none, if bi ≠ binder_info.inst_implicit ∧ ¬ (lhs.abstract_local l.local_uniq_name).has_var then pure none else pure lhs | ty := pure ty end /-- `simp_is_conditional ty` returns true iff the simp lemma with type `ty` is conditional. -/ private meta def simp_is_conditional (ty : expr) : tactic bool := option.is_none <$> simp_is_conditional_core ty private meta def heuristic_simp_lemma_extraction (prf : expr) : tactic (list name) := prf.list_constant.to_list.mfilter is_simp_lemma /-- Checks whether two expressions are equal for the simplifier. That is, they are reducibly-definitional equal, and they have the same head symbol. -/ meta def is_simp_eq (a b : expr) : tactic bool := if a.get_app_fn.const_name ≠ b.get_app_fn.const_name then pure ff else succeeds $ is_def_eq a b transparency.reducible /-- Reports declarations that are simp lemmas whose left-hand side is not in simp-normal form. -/ meta def simp_nf_linter (timeout := 200000) (d : declaration) : tactic (option string) := do tt ← is_simp_lemma d.to_name | pure none, -- Sometimes, a definition is tagged @[simp] to add the equational lemmas to the simp set. -- In this case, ignore the declaration if it is not a valid simp lemma by itself. tt ← is_valid_simp_lemma_cnst d.to_name | pure none, [] ← get_eqn_lemmas_for ff d.to_name | pure none, try_for timeout $ retrieve $ do reset_instance_cache, g ← mk_meta_var d.type, set_goals [g], intros, (lhs, rhs) ← target >>= simp_lhs_rhs, sls ← simp_lemmas.mk_default, let sls' := sls.erase [d.to_name], (lhs', prf1) ← decorate_error "simplify fails on left-hand side:" $ simplify sls [] lhs {fail_if_unchanged := ff}, prf1_lems ← heuristic_simp_lemma_extraction prf1, if d.to_name ∈ prf1_lems then pure none else do is_cond ← simp_is_conditional d.type, (rhs', prf2) ← decorate_error "simplify fails on right-hand side:" $ simplify sls [] rhs {fail_if_unchanged := ff}, lhs'_eq_rhs' ← is_simp_eq lhs' rhs', lhs_in_nf ← is_simp_eq lhs' lhs, if lhs'_eq_rhs' then do used_lemmas ← heuristic_simp_lemma_extraction (prf1 prf2), pure $ pure $ "simp can prove this:\n" ++ " by simp only " ++ to_string used_lemmas ++ "\n" ++ "One of the lemmas above could be a duplicate.\n" ++ "If that's not the case try reordering lemmas or adding @[priority].\n" else if ¬ lhs_in_nf then do lhs ← pp lhs, lhs' ← pp lhs', pure $ format.to_string $ to_fmt "Left-hand side simplifies from" ++ lhs.group.indent 2 ++ format.line ++ "to" ++ lhs'.group.indent 2 ++ format.line ++ "using " ++ (to_fmt prf1_lems).group.indent 2 ++ format.line ++ "Try to change the left-hand side to the simplified term!\n" else if ¬ is_cond ∧ lhs = lhs' then do pure "Left-hand side does not simplify.\nYou need to debug this yourself using `set_option trace.simplify.rewrite true`" else pure none /-- A linter for simp lemmas whose lhs is not in simp-normal form, and which hence never fire. -/ @[linter] meta def linter.simp_nf : linter := { test := simp_nf_linter, auto_decls := tt, no_errors_found := "All left-hand sides of simp lemmas are in simp-normal form", errors_found := "SOME SIMP LEMMAS ARE REDUNDANT. That is, their left-hand side is not in simp-normal form. These lemmas are hence never used by the simplifier. This linter gives you a list of other simp lemmas, look at them! Here are some guidelines to get you started: 1. 'the left-hand side reduces to XYZ': you should probably use XYZ as the left-hand side. 2. 'simp can prove this': This typically means that lemma is a duplicate, or is shadowed by another lemma: 2a. Always put more general lemmas after specific ones: @[simp] lemma zero_add_zero : 0 + 0 = 0 := rfl @[simp] lemma add_zero : x + 0 = x := rfl And not the other way around! The simplifier always picks the last matching lemma. 2b. You can also use @[priority] instead of moving simp-lemmas around in the file. Tip: the default priority is 1000. Use `@[priority 1100]` instead of moving a lemma down, and `@[priority 900]` instead of moving a lemma up. 2c. Conditional simp lemmas are tried last, if they are shadowed just remove the simp attribute. 2d. If two lemmas are duplicates, the linter will complain about the first one. Try to fix the second one instead! (You can find it among the other simp lemmas the linter prints out!) " } private meta def simp_var_head (d : declaration) : tactic (option string) := do tt ← is_simp_lemma d.to_name | pure none, -- Sometimes, a definition is tagged @[simp] to add the equational lemmas to the simp set. -- In this case, ignore the declaration if it is not a valid simp lemma by itself. tt ← is_valid_simp_lemma_cnst d.to_name | pure none, lhs ← simp_lhs d.type, head_sym@(expr.local_const _ _ _ _) ← pure lhs.get_app_fn | pure none, head_sym ← pp head_sym, pure $ format.to_string $ "Left-hand side has variable as head symbol: " ++ head_sym /-- A linter for simp lemmas whose lhs has a variable as head symbol, and which hence never fire. -/ @[linter] meta def linter.simp_var_head : linter := { test := simp_var_head, auto_decls := tt, no_errors_found := "No left-hand sides of a simp lemma has a variable as head symbol", errors_found := "LEFT-HAND SIDE HAS VARIABLE AS HEAD SYMBOL.\n" ++ "Some simp lemmas have a variable as head symbol of the left-hand side" } private meta def simp_comm (d : declaration) : tactic (option string) := do tt ← is_simp_lemma d.to_name | pure none, -- Sometimes, a definition is tagged @[simp] to add the equational lemmas to the simp set. -- In this case, ignore the declaration if it is not a valid simp lemma by itself. tt ← is_valid_simp_lemma_cnst d.to_name | pure none, (lhs, rhs) ← simp_lhs_rhs d.type, if lhs.get_app_fn.const_name ≠ rhs.get_app_fn.const_name then pure none else do (lhs', rhs') ← (prod.snd <$> mk_meta_pis d.type) >>= simp_lhs_rhs, tt ← succeeds $ unify rhs lhs' transparency.reducible | pure none, tt ← succeeds $ is_def_eq rhs lhs' transparency.reducible | pure none, -- ensure that the second application makes progress: ff ← succeeds $ unify lhs' rhs' transparency.reducible | pure none, pure $ "should not be marked simp" /-- A linter for commutativity lemmas that are marked simp. -/ @[linter] meta def linter.simp_comm : linter := { test := simp_comm, auto_decls := tt, no_errors_found := "No commutativity lemma is marked simp", errors_found := "COMMUTATIVITY LEMMA IS SIMP.\n" ++ "Some commutativity lemmas are simp lemmas" }
9e95618b412f3d151d0d29f5681b8f52604c28a2
367134ba5a65885e863bdc4507601606690974c1
/src/control/monad/cont.lean
f1d35ccc3504772112189b2db12e0f27c4599994
[ "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
9,371
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon Monad encapsulating continuation passing programming style, similar to Haskell's `Cont`, `ContT` and `MonadCont`: <http://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Cont.html> -/ import control.monad.writer universes u v w u₀ u₁ v₀ v₁ structure monad_cont.label (α : Type w) (m : Type u → Type v) (β : Type u) := (apply : α → m β) def monad_cont.goto {α β} {m : Type u → Type v} (f : monad_cont.label α m β) (x : α) := f.apply x class monad_cont (m : Type u → Type v) := (call_cc : Π {α β}, ((monad_cont.label α m β) → m α) → m α) open monad_cont class is_lawful_monad_cont (m : Type u → Type v) [monad m] [monad_cont m] extends is_lawful_monad m := (call_cc_bind_right {α ω γ} (cmd : m α) (next : (label ω m γ) → α → m ω) : call_cc (λ f, cmd >>= next f) = cmd >>= λ x, call_cc (λ f, next f x)) (call_cc_bind_left {α} (β) (x : α) (dead : label α m β → β → m α) : call_cc (λ f : label α m β, goto f x >>= dead f) = pure x) (call_cc_dummy {α β} (dummy : m α) : call_cc (λ f : label α m β, dummy) = dummy) export is_lawful_monad_cont def cont_t (r : Type u) (m : Type u → Type v) (α : Type w) := (α → m r) → m r @[reducible] def cont (r : Type u) (α : Type w) := cont_t r id α namespace cont_t export monad_cont (label goto) variables {r : Type u} {m : Type u → Type v} {α β γ ω : Type w} def run : cont_t r m α → (α → m r) → m r := id def map (f : m r → m r) (x : cont_t r m α) : cont_t r m α := f ∘ x lemma run_cont_t_map_cont_t (f : m r → m r) (x : cont_t r m α) : run (map f x) = f ∘ run x := rfl def with_cont_t (f : (β → m r) → α → m r) (x : cont_t r m α) : cont_t r m β := λ g, x $ f g lemma run_with_cont_t (f : (β → m r) → α → m r) (x : cont_t r m α) : run (with_cont_t f x) = run x ∘ f := rfl @[ext] protected lemma ext {x y : cont_t r m α} (h : ∀ f, x.run f = y.run f) : x = y := by { ext; apply h } instance : monad (cont_t r m) := { pure := λ α x f, f x, bind := λ α β x f g, x $ λ i, f i g } instance : is_lawful_monad (cont_t r m) := { id_map := by { intros, refl }, pure_bind := by { intros, ext, refl }, bind_assoc := by { intros, ext, refl } } def monad_lift [monad m] {α} : m α → cont_t r m α := λ x f, x >>= f instance [monad m] : has_monad_lift m (cont_t r m) := { monad_lift := λ α, cont_t.monad_lift } lemma monad_lift_bind [monad m] [is_lawful_monad m] {α β} (x : m α) (f : α → m β) : (monad_lift (x >>= f) : cont_t r m β) = monad_lift x >>= monad_lift ∘ f := begin ext, simp only [monad_lift,has_monad_lift.monad_lift,(∘),(>>=),bind_assoc,id.def,run,cont_t.monad_lift] end instance : monad_cont (cont_t r m) := { call_cc := λ α β f g, f ⟨λ x h, g x⟩ g } instance : is_lawful_monad_cont (cont_t r m) := { call_cc_bind_right := by intros; ext; refl, call_cc_bind_left := by intros; ext; refl, call_cc_dummy := by intros; ext; refl } instance (ε) [monad_except ε m] : monad_except ε (cont_t r m) := { throw := λ x e f, throw e, catch := λ α act h f, catch (act f) (λ e, h e f) } instance : monad_run (λ α, (α → m r) → ulift.{u v} (m r)) (cont_t.{u v u} r m) := { run := λ α f x, ⟨ f x ⟩ } end cont_t variables {m : Type u → Type v} [monad m] def except_t.mk_label {α β ε} : label (except.{u u} ε α) m β → label α (except_t ε m) β | ⟨ f ⟩ := ⟨ λ a, monad_lift $ f (except.ok a) ⟩ lemma except_t.goto_mk_label {α β ε : Type*} (x : label (except.{u u} ε α) m β) (i : α) : goto (except_t.mk_label x) i = ⟨ except.ok <$> goto x (except.ok i) ⟩ := by cases x; refl def except_t.call_cc {ε} [monad_cont m] {α β : Type*} (f : label α (except_t ε m) β → except_t ε m α) : except_t ε m α := except_t.mk (call_cc $ λ x : label _ m β, except_t.run $ f (except_t.mk_label x) : m (except ε α)) instance {ε} [monad_cont m] : monad_cont (except_t ε m) := { call_cc := λ α β, except_t.call_cc } instance {ε} [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (except_t ε m) := { call_cc_bind_right := by { intros, simp [call_cc,except_t.call_cc,call_cc_bind_right], ext, dsimp, congr' with ⟨ ⟩; simp [except_t.bind_cont,@call_cc_dummy m _], }, call_cc_bind_left := by { intros, simp [call_cc,except_t.call_cc,call_cc_bind_right,except_t.goto_mk_label,map_eq_bind_pure_comp, bind_assoc,@call_cc_bind_left m _], ext, refl }, call_cc_dummy := by { intros, simp [call_cc,except_t.call_cc,@call_cc_dummy m _], ext, refl }, } def option_t.mk_label {α β} : label (option.{u} α) m β → label α (option_t m) β | ⟨ f ⟩ := ⟨ λ a, monad_lift $ f (some a) ⟩ lemma option_t.goto_mk_label {α β : Type*} (x : label (option.{u} α) m β) (i : α) : goto (option_t.mk_label x) i = ⟨ some <$> goto x (some i) ⟩ := by cases x; refl def option_t.call_cc [monad_cont m] {α β : Type*} (f : label α (option_t m) β → option_t m α) : option_t m α := option_t.mk (call_cc $ λ x : label _ m β, option_t.run $ f (option_t.mk_label x) : m (option α)) instance [monad_cont m] : monad_cont (option_t m) := { call_cc := λ α β, option_t.call_cc } instance [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (option_t m) := { call_cc_bind_right := by { intros, simp [call_cc,option_t.call_cc,call_cc_bind_right], ext, dsimp, congr' with ⟨ ⟩; simp [option_t.bind_cont,@call_cc_dummy m _], }, call_cc_bind_left := by { intros, simp [call_cc,option_t.call_cc,call_cc_bind_right, option_t.goto_mk_label,map_eq_bind_pure_comp,bind_assoc,@call_cc_bind_left m _], ext, refl }, call_cc_dummy := by { intros, simp [call_cc,option_t.call_cc,@call_cc_dummy m _], ext, refl }, } def writer_t.mk_label {α β ω} [has_one ω] : label (α × ω) m β → label α (writer_t ω m) β | ⟨ f ⟩ := ⟨ λ a, monad_lift $ f (a,1) ⟩ lemma writer_t.goto_mk_label {α β ω : Type*} [has_one ω] (x : label (α × ω) m β) (i : α) : goto (writer_t.mk_label x) i = monad_lift (goto x (i,1)) := by cases x; refl def writer_t.call_cc [monad_cont m] {α β ω : Type*} [has_one ω] (f : label α (writer_t ω m) β → writer_t ω m α) : writer_t ω m α := ⟨ call_cc (writer_t.run ∘ f ∘ writer_t.mk_label : label (α × ω) m β → m (α × ω)) ⟩ instance (ω) [monad m] [has_one ω] [monad_cont m] : monad_cont (writer_t ω m) := { call_cc := λ α β, writer_t.call_cc } def state_t.mk_label {α β σ : Type u} : label (α × σ) m (β × σ) → label α (state_t σ m) β | ⟨ f ⟩ := ⟨ λ a, ⟨ λ s, f (a,s) ⟩ ⟩ lemma state_t.goto_mk_label {α β σ : Type u} (x : label (α × σ) m (β × σ)) (i : α) : goto (state_t.mk_label x) i = ⟨ λ s, (goto x (i,s)) ⟩ := by cases x; refl def state_t.call_cc {σ} [monad_cont m] {α β : Type*} (f : label α (state_t σ m) β → state_t σ m α) : state_t σ m α := ⟨ λ r, call_cc (λ f', (f $ state_t.mk_label f').run r) ⟩ instance {σ} [monad_cont m] : monad_cont (state_t σ m) := { call_cc := λ α β, state_t.call_cc } instance {σ} [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (state_t σ m) := { call_cc_bind_right := by { intros, simp [call_cc,state_t.call_cc,call_cc_bind_right,(>>=),state_t.bind], ext, dsimp, congr' with ⟨x₀,x₁⟩, refl }, call_cc_bind_left := by { intros, simp [call_cc,state_t.call_cc,call_cc_bind_left,(>>=), state_t.bind,state_t.goto_mk_label], ext, refl }, call_cc_dummy := by { intros, simp [call_cc,state_t.call_cc,call_cc_bind_right,(>>=), state_t.bind,@call_cc_dummy m _], ext, refl }, } def reader_t.mk_label {α β} (ρ) : label α m β → label α (reader_t ρ m) β | ⟨ f ⟩ := ⟨ monad_lift ∘ f ⟩ lemma reader_t.goto_mk_label {α ρ β} (x : label α m β) (i : α) : goto (reader_t.mk_label ρ x) i = monad_lift (goto x i) := by cases x; refl def reader_t.call_cc {ε} [monad_cont m] {α β : Type*} (f : label α (reader_t ε m) β → reader_t ε m α) : reader_t ε m α := ⟨ λ r, call_cc (λ f', (f $ reader_t.mk_label _ f').run r) ⟩ instance {ρ} [monad_cont m] : monad_cont (reader_t ρ m) := { call_cc := λ α β, reader_t.call_cc } instance {ρ} [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (reader_t ρ m) := { call_cc_bind_right := by { intros, simp [call_cc,reader_t.call_cc,call_cc_bind_right], ext, refl }, call_cc_bind_left := by { intros, simp [call_cc,reader_t.call_cc,call_cc_bind_left, reader_t.goto_mk_label], ext, refl }, call_cc_dummy := by { intros, simp [call_cc,reader_t.call_cc,@call_cc_dummy m _], ext, refl } } /-- reduce the equivalence between two continuation passing monads to the equivalence between their underlying monad -/ def cont_t.equiv {m₁ : Type u₀ → Type v₀} {m₂ : Type u₁ → Type v₁} {α₁ r₁ : Type u₀} {α₂ r₂ : Type u₁} (F : m₁ r₁ ≃ m₂ r₂) (G : α₁ ≃ α₂) : cont_t r₁ m₁ α₁ ≃ cont_t r₂ m₂ α₂ := { to_fun := λ f r, F $ f $ λ x, F.symm $ r $ G x, inv_fun := λ f r, F.symm $ f $ λ x, F $ r $ G.symm x, left_inv := λ f, by funext r; simp, right_inv := λ f, by funext r; simp }
3679a5de75e591b059a62fe0e787447ad878e87a
f4bff2062c030df03d65e8b69c88f79b63a359d8
/already_there/stuff.lean
89e61d89bf38a787801c3dcf48e8b8c681136e28
[ "Apache-2.0" ]
permissive
adastra7470/real-number-game
776606961f52db0eb824555ed2f8e16f92216ea3
f9dcb7d9255a79b57e62038228a23346c2dc301b
refs/heads/master
1,669,221,575,893
1,594,669,800,000
1,594,669,800,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,231
lean
-- list of functions which will surely be useful import data.real.basic -- in order.bounds #check @upper_bounds -- and lower_bounds -- upper_bounds : Π {α : Type u_1} [_inst_1 : preorder α], set α → set α #check @is_least -- and is_greatest -- is_least : Π {α : Type u_1} [_inst_1 : preorder α], set α → α → Prop #check @is_lub -- and is_glb -- is_lub : Π {α : Type u_1} [_inst_1 : preorder α], set α → α → Prop -- and lots of lemmas e.g. eq_of_is_lub_of_is_lub -- in order.conditionally_complete_lattice #check @bdd_above -- "is bounded above" -- and bdd_below -- bdd_above : Π {α : Type u_1} [_inst_1 : preorder α], set α → Prop -- in order.complete_lattice -- notation \Lub = ⨆ #check @lattice.supr -- sup over an indexed family of elements -- lattice.supr : Π {α : Type u_1} {ι : Sort u_2} [_inst_1 : lattice.has_Sup α], (ι → α) → α -- see also lattice.infi = ⨅ = \Glb -- in data.real.basic #check real.Sup -- real.Sup : set ℝ → ℝ #check real.Sup_le /- real.Sup_le : ∀ (S : set ℝ), (∃ (x : ℝ), x ∈ S) → (∃ (x : ℝ), ∀ (y : ℝ), y ∈ S → y ≤ x) → ∀ {y : ℝ}, real.Sup S ≤ y ↔ ∀ (z : ℝ), z ∈ S → z ≤ y -/
43179e722a9a4da33d018a4eb38e4e2f4d7d55c0
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/priority_test.lean
68b195982958828f9eb1facbb39a4a647a4699bb
[ "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
317
lean
open nat structure foo [class] := (a : nat) (b : nat) definition i1 [instance] [priority std.priority.default+1] : foo := foo.mk 1 1 definition i2 [instance] : foo := foo.mk 2 2 example : foo.a = 1 := rfl definition i3 [instance] [priority std.priority.default+2] : foo := foo.mk 3 3 example : foo.a = 3 := rfl
8fe5318f4f7f5684bf7971fa3bb2d0725b44456b
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/topology/algebra/localization.lean
c195c8603fe026dc272b75823c606418fb337479
[ "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
1,251
lean
/- Copyright (c) 2021 María Inés de Frutos-Fernández. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: María Inés de Frutos-Fernández -/ import ring_theory.localization import topology.algebra.ring /-! # Localization of topological rings The topological localization of a topological commutative ring `R` at a submonoid `M` is the ring `localization M` endowed with the final ring topology of the natural homomorphism sending `x : R` to the equivalence class of `(x, 1)` in the localization of `R` at a `M`. ## Main Results - `localization.topological_ring`: The localization of a topological commutative ring at a submonoid is a topological ring. -/ variables {R : Type*} [comm_ring R] [topological_space R] {M : submonoid R} /-- The ring topology on `localization M` coinduced from the natural homomorphism sending `x : R` to the equivalence class of `(x, 1)`. -/ def localization.ring_topology : ring_topology (localization M) := ring_topology.coinduced (localization.monoid_of M).to_fun instance : topological_space (localization M) := localization.ring_topology.to_topological_space instance : topological_ring (localization M) := localization.ring_topology.to_topological_ring
9a1bce52bd25b64158f836242cf86d49dc7e0f2c
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/analysis/calculus/mean_value.lean
f9ec7a90b9f3ba0fed8c109f7b44d05d83593c31
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
62,454
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Yury Kudryashov -/ import analysis.calculus.local_extr import analysis.convex.slope import analysis.convex.topology import data.complex.is_R_or_C /-! # The mean value inequality and equalities In this file we prove the following facts: * `convex.norm_image_sub_le_of_norm_deriv_le` : if `f` is differentiable on a convex set `s` and the norm of its derivative is bounded by `C`, then `f` is Lipschitz continuous on `s` with constant `C`; also a variant in which what is bounded by `C` is the norm of the difference of the derivative from a fixed linear map. This lemma and its versions are formulated using `is_R_or_C`, so they work both for real and complex derivatives. * `image_le_of*`, `image_norm_le_of_*` : several similar lemmas deducing `f x ≤ B x` or `∥f x∥ ≤ B x` from upper estimates on `f'` or `∥f'∥`, respectively. These lemmas differ by their assumptions: * `of_liminf_*` lemmas assume that limit inferior of some ratio is less than `B' x`; * `of_deriv_right_*`, `of_norm_deriv_right_*` lemmas assume that the right derivative or its norm is less than `B' x`; * `of_*_lt_*` lemmas assume a strict inequality whenever `f x = B x` or `∥f x∥ = B x`; * `of_*_le_*` lemmas assume a non-strict inequality everywhere on `[a, b)`; * name of a lemma ends with `'` if (1) it assumes that `B` is continuous on `[a, b]` and has a right derivative at every point of `[a, b)`, and (2) the lemma has a counterpart assuming that `B` is differentiable everywhere on `ℝ` * `norm_image_sub_le_*_segment` : if derivative of `f` on `[a, b]` is bounded above by a constant `C`, then `∥f x - f a∥ ≤ C * ∥x - a∥`; several versions deal with right derivative and derivative within `[a, b]` (`has_deriv_within_at` or `deriv_within`). * `convex.is_const_of_fderiv_within_eq_zero` : if a function has derivative `0` on a convex set `s`, then it is a constant on `s`. * `exists_ratio_has_deriv_at_eq_ratio_slope` and `exists_ratio_deriv_eq_ratio_slope` : Cauchy's Mean Value Theorem. * `exists_has_deriv_at_eq_slope` and `exists_deriv_eq_slope` : Lagrange's Mean Value Theorem. * `domain_mvt` : Lagrange's Mean Value Theorem, applied to a segment in a convex domain. * `convex.image_sub_lt_mul_sub_of_deriv_lt`, `convex.mul_sub_lt_image_sub_of_lt_deriv`, `convex.image_sub_le_mul_sub_of_deriv_le`, `convex.mul_sub_le_image_sub_of_le_deriv`, if `∀ x, C (</≤/>/≥) (f' x)`, then `C * (y - x) (</≤/>/≥) (f y - f x)` whenever `x < y`. * `convex.monotone_on_of_deriv_nonneg`, `convex.antitone_on_of_deriv_nonpos`, `convex.strict_mono_of_deriv_pos`, `convex.strict_anti_of_deriv_neg` : if the derivative of a function is non-negative/non-positive/positive/negative, then the function is monotone/antitone/strictly monotone/strictly monotonically decreasing. * `convex_on_of_deriv_monotone_on`, `convex_on_of_deriv2_nonneg` : if the derivative of a function is increasing or its second derivative is nonnegative, then the original function is convex. * `strict_fderiv_of_cont_diff` : a C^1 function over the reals is strictly differentiable. (This is a corollary of the mean value inequality.) -/ variables {E : Type*} [normed_group E] [normed_space ℝ E] {F : Type*} [normed_group F] [normed_space ℝ F] open metric set asymptotics continuous_linear_map filter open_locale classical topological_space nnreal /-! ### One-dimensional fencing inequalities -/ /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has right derivative `B'` at every point of `[a, b)`; * for each `x ∈ [a, b)` the right-side limit inferior of `(f z - f x) / (z - x)` is bounded above by a function `f'`; * we have `f' x < B' x` whenever `f x = B x`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_liminf_slope_right_lt_deriv_boundary' {f f' : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) -- `hf'` actually says `liminf (z - x)⁻¹ * (f z - f x) ≤ f' x` (hf' : ∀ x ∈ Ico a b, ∀ r, f' x < r → ∃ᶠ z in 𝓝[Ioi x] x, (z - x)⁻¹ * (f z - f x) < r) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x) (bound : ∀ x ∈ Ico a b, f x = B x → f' x < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := begin change Icc a b ⊆ {x | f x ≤ B x}, set s := {x | f x ≤ B x} ∩ Icc a b, have A : continuous_on (λ x, (f x, B x)) (Icc a b), from hf.prod hB, have : is_closed s, { simp only [s, inter_comm], exact A.preimage_closed_of_closed is_closed_Icc order_closed_topology.is_closed_le' }, apply this.Icc_subset_of_forall_exists_gt ha, rintros x ⟨hxB : f x ≤ B x, xab⟩ y hy, cases hxB.lt_or_eq with hxB hxB, { -- If `f x < B x`, then all we need is continuity of both sides refine nonempty_of_mem (inter_mem _ (Ioc_mem_nhds_within_Ioi ⟨le_rfl, hy⟩)), have : ∀ᶠ x in 𝓝[Icc a b] x, f x < B x, from A x (Ico_subset_Icc_self xab) (is_open.mem_nhds (is_open_lt continuous_fst continuous_snd) hxB), have : ∀ᶠ x in 𝓝[Ioi x] x, f x < B x, from nhds_within_le_of_mem (Icc_mem_nhds_within_Ioi xab) this, exact this.mono (λ y, le_of_lt) }, { rcases exists_between (bound x xab hxB) with ⟨r, hfr, hrB⟩, specialize hf' x xab r hfr, have HB : ∀ᶠ z in 𝓝[Ioi x] x, r < (z - x)⁻¹ * (B z - B x), from (has_deriv_within_at_iff_tendsto_slope' $ lt_irrefl x).1 (hB' x xab).Ioi_of_Ici (Ioi_mem_nhds hrB), obtain ⟨z, ⟨hfz, hzB⟩, hz⟩ : ∃ z, ((z - x)⁻¹ * (f z - f x) < r ∧ r < (z - x)⁻¹ * (B z - B x)) ∧ z ∈ Ioc x y, from ((hf'.and_eventually HB).and_eventually (Ioc_mem_nhds_within_Ioi ⟨le_rfl, hy⟩)).exists, refine ⟨z, _, hz⟩, have := (hfz.trans hzB).le, rwa [mul_le_mul_left (inv_pos.2 $ sub_pos.2 hz.1), hxB, sub_le_sub_iff_right] at this } end /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has derivative `B'` everywhere on `ℝ`; * for each `x ∈ [a, b)` the right-side limit inferior of `(f z - f x) / (z - x)` is bounded above by a function `f'`; * we have `f' x < B' x` whenever `f x = B x`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_liminf_slope_right_lt_deriv_boundary {f f' : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) -- `hf'` actually says `liminf (z - x)⁻¹ * (f z - f x) ≤ f' x` (hf' : ∀ x ∈ Ico a b, ∀ r, f' x < r → ∃ᶠ z in 𝓝[Ioi x] x, (z - x)⁻¹ * (f z - f x) < r) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : ∀ x, has_deriv_at B (B' x) x) (bound : ∀ x ∈ Ico a b, f x = B x → f' x < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := image_le_of_liminf_slope_right_lt_deriv_boundary' hf hf' ha (λ x hx, (hB x).continuous_at.continuous_within_at) (λ x hx, (hB x).has_deriv_within_at) bound /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has right derivative `B'` at every point of `[a, b)`; * for each `x ∈ [a, b)` the right-side limit inferior of `(f z - f x) / (z - x)` is bounded above by `B'`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_liminf_slope_right_le_deriv_boundary {f : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x) -- `bound` actually says `liminf (z - x)⁻¹ * (f z - f x) ≤ B' x` (bound : ∀ x ∈ Ico a b, ∀ r, B' x < r → ∃ᶠ z in 𝓝[Ioi x] x, (z - x)⁻¹ * (f z - f x) < r) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := begin have Hr : ∀ x ∈ Icc a b, ∀ r > 0, f x ≤ B x + r * (x - a), { intros x hx r hr, apply image_le_of_liminf_slope_right_lt_deriv_boundary' hf bound, { rwa [sub_self, mul_zero, add_zero] }, { exact hB.add (continuous_on_const.mul (continuous_id.continuous_on.sub continuous_on_const)) }, { assume x hx, exact (hB' x hx).add (((has_deriv_within_at_id x (Ici x)).sub_const a).const_mul r) }, { assume x hx _, rw [mul_one], exact (lt_add_iff_pos_right _).2 hr }, exact hx }, assume x hx, have : continuous_within_at (λ r, B x + r * (x - a)) (Ioi 0) 0, from continuous_within_at_const.add (continuous_within_at_id.mul continuous_within_at_const), convert continuous_within_at_const.closure_le _ this (Hr x hx); simp end /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has right derivative `B'` at every point of `[a, b)`; * `f` has right derivative `f'` at every point of `[a, b)`; * we have `f' x < B' x` whenever `f x = B x`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_deriv_right_lt_deriv_boundary' {f f' : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x) (bound : ∀ x ∈ Ico a b, f x = B x → f' x < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := image_le_of_liminf_slope_right_lt_deriv_boundary' hf (λ x hx r hr, (hf' x hx).liminf_right_slope_le hr) ha hB hB' bound /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has derivative `B'` everywhere on `ℝ`; * `f` has right derivative `f'` at every point of `[a, b)`; * we have `f' x < B' x` whenever `f x = B x`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_deriv_right_lt_deriv_boundary {f f' : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : ∀ x, has_deriv_at B (B' x) x) (bound : ∀ x ∈ Ico a b, f x = B x → f' x < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := image_le_of_deriv_right_lt_deriv_boundary' hf hf' ha (λ x hx, (hB x).continuous_at.continuous_within_at) (λ x hx, (hB x).has_deriv_within_at) bound /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has derivative `B'` everywhere on `ℝ`; * `f` has right derivative `f'` at every point of `[a, b)`; * we have `f' x ≤ B' x` on `[a, b)`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_deriv_right_le_deriv_boundary {f f' : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x) (bound : ∀ x ∈ Ico a b, f' x ≤ B' x) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := image_le_of_liminf_slope_right_le_deriv_boundary hf ha hB hB' $ assume x hx r hr, (hf' x hx).liminf_right_slope_le (lt_of_le_of_lt (bound x hx) hr) /-! ### Vector-valued functions `f : ℝ → E` -/ section variables {f : ℝ → E} {a b : ℝ} /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `∥f a∥ ≤ B a`; * `B` has right derivative at every point of `[a, b)`; * for each `x ∈ [a, b)` the right-side limit inferior of `(∥f z∥ - ∥f x∥) / (z - x)` is bounded above by a function `f'`; * we have `f' x < B' x` whenever `∥f x∥ = B x`. Then `∥f x∥ ≤ B x` everywhere on `[a, b]`. -/ lemma image_norm_le_of_liminf_right_slope_norm_lt_deriv_boundary {E : Type*} [normed_group E] {f : ℝ → E} {f' : ℝ → ℝ} (hf : continuous_on f (Icc a b)) -- `hf'` actually says `liminf ∥z - x∥⁻¹ * (∥f z∥ - ∥f x∥) ≤ f' x` (hf' : ∀ x ∈ Ico a b, ∀ r, f' x < r → ∃ᶠ z in 𝓝[Ioi x] x, (z - x)⁻¹ * (∥f z∥ - ∥f x∥) < r) {B B' : ℝ → ℝ} (ha : ∥f a∥ ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x) (bound : ∀ x ∈ Ico a b, ∥f x∥ = B x → f' x < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → ∥f x∥ ≤ B x := image_le_of_liminf_slope_right_lt_deriv_boundary' (continuous_norm.comp_continuous_on hf) hf' ha hB hB' bound /-- General fencing theorem for continuous functions with an estimate on the norm of the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `∥f a∥ ≤ B a`; * `f` and `B` have right derivatives `f'` and `B'` respectively at every point of `[a, b)`; * the norm of `f'` is strictly less than `B'` whenever `∥f x∥ = B x`. Then `∥f x∥ ≤ B x` everywhere on `[a, b]`. We use one-sided derivatives in the assumptions to make this theorem work for piecewise differentiable functions. -/ lemma image_norm_le_of_norm_deriv_right_lt_deriv_boundary' {f' : ℝ → E} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) {B B' : ℝ → ℝ} (ha : ∥f a∥ ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x) (bound : ∀ x ∈ Ico a b, ∥f x∥ = B x → ∥f' x∥ < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → ∥f x∥ ≤ B x := image_norm_le_of_liminf_right_slope_norm_lt_deriv_boundary hf (λ x hx r hr, (hf' x hx).liminf_right_slope_norm_le hr) ha hB hB' bound /-- General fencing theorem for continuous functions with an estimate on the norm of the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `∥f a∥ ≤ B a`; * `f` has right derivative `f'` at every point of `[a, b)`; * `B` has derivative `B'` everywhere on `ℝ`; * the norm of `f'` is strictly less than `B'` whenever `∥f x∥ = B x`. Then `∥f x∥ ≤ B x` everywhere on `[a, b]`. We use one-sided derivatives in the assumptions to make this theorem work for piecewise differentiable functions. -/ lemma image_norm_le_of_norm_deriv_right_lt_deriv_boundary {f' : ℝ → E} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) {B B' : ℝ → ℝ} (ha : ∥f a∥ ≤ B a) (hB : ∀ x, has_deriv_at B (B' x) x) (bound : ∀ x ∈ Ico a b, ∥f x∥ = B x → ∥f' x∥ < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → ∥f x∥ ≤ B x := image_norm_le_of_norm_deriv_right_lt_deriv_boundary' hf hf' ha (λ x hx, (hB x).continuous_at.continuous_within_at) (λ x hx, (hB x).has_deriv_within_at) bound /-- General fencing theorem for continuous functions with an estimate on the norm of the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `∥f a∥ ≤ B a`; * `f` and `B` have right derivatives `f'` and `B'` respectively at every point of `[a, b)`; * we have `∥f' x∥ ≤ B x` everywhere on `[a, b)`. Then `∥f x∥ ≤ B x` everywhere on `[a, b]`. We use one-sided derivatives in the assumptions to make this theorem work for piecewise differentiable functions. -/ lemma image_norm_le_of_norm_deriv_right_le_deriv_boundary' {f' : ℝ → E} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) {B B' : ℝ → ℝ} (ha : ∥f a∥ ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x) (bound : ∀ x ∈ Ico a b, ∥f' x∥ ≤ B' x) : ∀ ⦃x⦄, x ∈ Icc a b → ∥f x∥ ≤ B x := image_le_of_liminf_slope_right_le_deriv_boundary (continuous_norm.comp_continuous_on hf) ha hB hB' $ (λ x hx r hr, (hf' x hx).liminf_right_slope_norm_le (lt_of_le_of_lt (bound x hx) hr)) /-- General fencing theorem for continuous functions with an estimate on the norm of the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `∥f a∥ ≤ B a`; * `f` has right derivative `f'` at every point of `[a, b)`; * `B` has derivative `B'` everywhere on `ℝ`; * we have `∥f' x∥ ≤ B x` everywhere on `[a, b)`. Then `∥f x∥ ≤ B x` everywhere on `[a, b]`. We use one-sided derivatives in the assumptions to make this theorem work for piecewise differentiable functions. -/ lemma image_norm_le_of_norm_deriv_right_le_deriv_boundary {f' : ℝ → E} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) {B B' : ℝ → ℝ} (ha : ∥f a∥ ≤ B a) (hB : ∀ x, has_deriv_at B (B' x) x) (bound : ∀ x ∈ Ico a b, ∥f' x∥ ≤ B' x) : ∀ ⦃x⦄, x ∈ Icc a b → ∥f x∥ ≤ B x := image_norm_le_of_norm_deriv_right_le_deriv_boundary' hf hf' ha (λ x hx, (hB x).continuous_at.continuous_within_at) (λ x hx, (hB x).has_deriv_within_at) bound /-- A function on `[a, b]` with the norm of the right derivative bounded by `C` satisfies `∥f x - f a∥ ≤ C * (x - a)`. -/ theorem norm_image_sub_le_of_norm_deriv_right_le_segment {f' : ℝ → E} {C : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) (bound : ∀x ∈ Ico a b, ∥f' x∥ ≤ C) : ∀ x ∈ Icc a b, ∥f x - f a∥ ≤ C * (x - a) := begin let g := λ x, f x - f a, have hg : continuous_on g (Icc a b), from hf.sub continuous_on_const, have hg' : ∀ x ∈ Ico a b, has_deriv_within_at g (f' x) (Ici x) x, { assume x hx, simpa using (hf' x hx).sub (has_deriv_within_at_const _ _ _) }, let B := λ x, C * (x - a), have hB : ∀ x, has_deriv_at B C x, { assume x, simpa using (has_deriv_at_const x C).mul ((has_deriv_at_id x).sub (has_deriv_at_const x a)) }, convert image_norm_le_of_norm_deriv_right_le_deriv_boundary hg hg' _ hB bound, simp only [g, B], rw [sub_self, norm_zero, sub_self, mul_zero] end /-- A function on `[a, b]` with the norm of the derivative within `[a, b]` bounded by `C` satisfies `∥f x - f a∥ ≤ C * (x - a)`, `has_deriv_within_at` version. -/ theorem norm_image_sub_le_of_norm_deriv_le_segment' {f' : ℝ → E} {C : ℝ} (hf : ∀ x ∈ Icc a b, has_deriv_within_at f (f' x) (Icc a b) x) (bound : ∀x ∈ Ico a b, ∥f' x∥ ≤ C) : ∀ x ∈ Icc a b, ∥f x - f a∥ ≤ C * (x - a) := begin refine norm_image_sub_le_of_norm_deriv_right_le_segment (λ x hx, (hf x hx).continuous_within_at) (λ x hx, _) bound, exact (hf x $ Ico_subset_Icc_self hx).nhds_within (Icc_mem_nhds_within_Ici hx) end /-- A function on `[a, b]` with the norm of the derivative within `[a, b]` bounded by `C` satisfies `∥f x - f a∥ ≤ C * (x - a)`, `deriv_within` version. -/ theorem norm_image_sub_le_of_norm_deriv_le_segment {C : ℝ} (hf : differentiable_on ℝ f (Icc a b)) (bound : ∀x ∈ Ico a b, ∥deriv_within f (Icc a b) x∥ ≤ C) : ∀ x ∈ Icc a b, ∥f x - f a∥ ≤ C * (x - a) := begin refine norm_image_sub_le_of_norm_deriv_le_segment' _ bound, exact λ x hx, (hf x hx).has_deriv_within_at end /-- A function on `[0, 1]` with the norm of the derivative within `[0, 1]` bounded by `C` satisfies `∥f 1 - f 0∥ ≤ C`, `has_deriv_within_at` version. -/ theorem norm_image_sub_le_of_norm_deriv_le_segment_01' {f' : ℝ → E} {C : ℝ} (hf : ∀ x ∈ Icc (0:ℝ) 1, has_deriv_within_at f (f' x) (Icc (0:ℝ) 1) x) (bound : ∀x ∈ Ico (0:ℝ) 1, ∥f' x∥ ≤ C) : ∥f 1 - f 0∥ ≤ C := by simpa only [sub_zero, mul_one] using norm_image_sub_le_of_norm_deriv_le_segment' hf bound 1 (right_mem_Icc.2 zero_le_one) /-- A function on `[0, 1]` with the norm of the derivative within `[0, 1]` bounded by `C` satisfies `∥f 1 - f 0∥ ≤ C`, `deriv_within` version. -/ theorem norm_image_sub_le_of_norm_deriv_le_segment_01 {C : ℝ} (hf : differentiable_on ℝ f (Icc (0:ℝ) 1)) (bound : ∀x ∈ Ico (0:ℝ) 1, ∥deriv_within f (Icc (0:ℝ) 1) x∥ ≤ C) : ∥f 1 - f 0∥ ≤ C := by simpa only [sub_zero, mul_one] using norm_image_sub_le_of_norm_deriv_le_segment hf bound 1 (right_mem_Icc.2 zero_le_one) theorem constant_of_has_deriv_right_zero (hcont : continuous_on f (Icc a b)) (hderiv : ∀ x ∈ Ico a b, has_deriv_within_at f 0 (Ici x) x) : ∀ x ∈ Icc a b, f x = f a := by simpa only [zero_mul, norm_le_zero_iff, sub_eq_zero] using λ x hx, norm_image_sub_le_of_norm_deriv_right_le_segment hcont hderiv (λ y hy, by rw norm_le_zero_iff) x hx theorem constant_of_deriv_within_zero (hdiff : differentiable_on ℝ f (Icc a b)) (hderiv : ∀ x ∈ Ico a b, deriv_within f (Icc a b) x = 0) : ∀ x ∈ Icc a b, f x = f a := begin have H : ∀ x ∈ Ico a b, ∥deriv_within f (Icc a b) x∥ ≤ 0 := by simpa only [norm_le_zero_iff] using λ x hx, hderiv x hx, simpa only [zero_mul, norm_le_zero_iff, sub_eq_zero] using λ x hx, norm_image_sub_le_of_norm_deriv_le_segment hdiff H x hx, end variables {f' g : ℝ → E} /-- If two continuous functions on `[a, b]` have the same right derivative and are equal at `a`, then they are equal everywhere on `[a, b]`. -/ theorem eq_of_has_deriv_right_eq (derivf : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) (derivg : ∀ x ∈ Ico a b, has_deriv_within_at g (f' x) (Ici x) x) (fcont : continuous_on f (Icc a b)) (gcont : continuous_on g (Icc a b)) (hi : f a = g a) : ∀ y ∈ Icc a b, f y = g y := begin simp only [← @sub_eq_zero _ _ (f _)] at hi ⊢, exact hi ▸ constant_of_has_deriv_right_zero (fcont.sub gcont) (λ y hy, by simpa only [sub_self] using (derivf y hy).sub (derivg y hy)), end /-- If two differentiable functions on `[a, b]` have the same derivative within `[a, b]` everywhere on `[a, b)` and are equal at `a`, then they are equal everywhere on `[a, b]`. -/ theorem eq_of_deriv_within_eq (fdiff : differentiable_on ℝ f (Icc a b)) (gdiff : differentiable_on ℝ g (Icc a b)) (hderiv : eq_on (deriv_within f (Icc a b)) (deriv_within g (Icc a b)) (Ico a b)) (hi : f a = g a) : ∀ y ∈ Icc a b, f y = g y := begin have A : ∀ y ∈ Ico a b, has_deriv_within_at f (deriv_within f (Icc a b) y) (Ici y) y := λ y hy, (fdiff y (mem_Icc_of_Ico hy)).has_deriv_within_at.nhds_within (Icc_mem_nhds_within_Ici hy), have B : ∀ y ∈ Ico a b, has_deriv_within_at g (deriv_within g (Icc a b) y) (Ici y) y := λ y hy, (gdiff y (mem_Icc_of_Ico hy)).has_deriv_within_at.nhds_within (Icc_mem_nhds_within_Ici hy), exact eq_of_has_deriv_right_eq A (λ y hy, (hderiv hy).symm ▸ B y hy) fdiff.continuous_on gdiff.continuous_on hi end end /-! ### Vector-valued functions `f : E → G` Theorems in this section work both for real and complex differentiable functions. We use assumptions `[is_R_or_C 𝕜] [normed_space 𝕜 E] [normed_space 𝕜 G]` to achieve this result. For the domain `E` we also assume `[normed_space ℝ E] [is_scalar_tower ℝ 𝕜 E]` to have a notion of a `convex` set. In both interesting cases `𝕜 = ℝ` and `𝕜 = ℂ` the assumption `[is_scalar_tower ℝ 𝕜 E]` is satisfied automatically. -/ section variables {𝕜 G : Type*} [is_R_or_C 𝕜] [normed_space 𝕜 E] [is_scalar_tower ℝ 𝕜 E] [normed_group G] [normed_space 𝕜 G] {f : E → G} {C : ℝ} {s : set E} {x y : E} {f' : E → E →L[𝕜] G} {φ : E →L[𝕜] G} /-- The mean value theorem on a convex set: if the derivative of a function is bounded by `C`, then the function is `C`-Lipschitz. Version with `has_fderiv_within`. -/ theorem convex.norm_image_sub_le_of_norm_has_fderiv_within_le (hf : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (bound : ∀x∈s, ∥f' x∥ ≤ C) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x∥ ≤ C * ∥y - x∥ := begin letI : normed_space ℝ G := restrict_scalars.normed_space ℝ 𝕜 G, letI : is_scalar_tower ℝ 𝕜 G := restrict_scalars.is_scalar_tower _ _ _, /- By composition with `t ↦ x + t • (y-x)`, we reduce to a statement for functions defined on `[0,1]`, for which it is proved in `norm_image_sub_le_of_norm_deriv_le_segment`. We just have to check the differentiability of the composition and bounds on its derivative, which is straightforward but tedious for lack of automation. -/ have C0 : 0 ≤ C := le_trans (norm_nonneg _) (bound x xs), set g : ℝ → E := λ t, x + t • (y - x), have Dg : ∀ t, has_deriv_at g (y-x) t, { assume t, simpa only [one_smul] using ((has_deriv_at_id t).smul_const (y - x)).const_add x }, have segm : Icc 0 1 ⊆ g ⁻¹' s, { rw [← image_subset_iff, ← segment_eq_image'], apply hs.segment_subset xs ys }, have : f x = f (g 0), by { simp only [g], rw [zero_smul, add_zero] }, rw this, have : f y = f (g 1), by { simp only [g], rw [one_smul, add_sub_cancel'_right] }, rw this, have D2: ∀ t ∈ Icc (0:ℝ) 1, has_deriv_within_at (f ∘ g) (f' (g t) (y - x)) (Icc 0 1) t, { intros t ht, have : has_fderiv_within_at f ((f' (g t)).restrict_scalars ℝ) s (g t), from hf (g t) (segm ht), exact this.comp_has_deriv_within_at _ (Dg t).has_deriv_within_at segm }, apply norm_image_sub_le_of_norm_deriv_le_segment_01' D2, refine λ t ht, le_of_op_norm_le _ _ _, exact bound (g t) (segm $ Ico_subset_Icc_self ht) end /-- The mean value theorem on a convex set: if the derivative of a function is bounded by `C` on `s`, then the function is `C`-Lipschitz on `s`. Version with `has_fderiv_within` and `lipschitz_on_with`. -/ theorem convex.lipschitz_on_with_of_nnnorm_has_fderiv_within_le {C : ℝ≥0} (hf : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (bound : ∀x∈s, ∥f' x∥₊ ≤ C) (hs : convex ℝ s) : lipschitz_on_with C f s := begin rw lipschitz_on_with_iff_norm_sub_le, intros x x_in y y_in, exact hs.norm_image_sub_le_of_norm_has_fderiv_within_le hf bound y_in x_in end /-- Let `s` be a convex set in a real normed vector space `E`, let `f : E → G` be a function differentiable within `s` in a neighborhood of `x : E` with derivative `f'`. Suppose that `f'` is continuous within `s` at `x`. Then for any number `K : ℝ≥0` larger than `∥f' x∥₊`, `f` is `K`-Lipschitz on some neighborhood of `x` within `s`. See also `convex.exists_nhds_within_lipschitz_on_with_of_has_fderiv_within_at` for a version that claims existence of `K` instead of an explicit estimate. -/ lemma convex.exists_nhds_within_lipschitz_on_with_of_has_fderiv_within_at_of_nnnorm_lt (hs : convex ℝ s) {f : E → G} (hder : ∀ᶠ y in 𝓝[s] x, has_fderiv_within_at f (f' y) s y) (hcont : continuous_within_at f' s x) (K : ℝ≥0) (hK : ∥f' x∥₊ < K) : ∃ t ∈ 𝓝[s] x, lipschitz_on_with K f t := begin obtain ⟨ε, ε0, hε⟩ : ∃ ε > 0, ball x ε ∩ s ⊆ {y | has_fderiv_within_at f (f' y) s y ∧ ∥f' y∥₊ < K}, from mem_nhds_within_iff.1 (hder.and $ hcont.nnnorm.eventually (gt_mem_nhds hK)), rw inter_comm at hε, refine ⟨s ∩ ball x ε, inter_mem_nhds_within _ (ball_mem_nhds _ ε0), _⟩, exact (hs.inter (convex_ball _ _)).lipschitz_on_with_of_nnnorm_has_fderiv_within_le (λ y hy, (hε hy).1.mono (inter_subset_left _ _)) (λ y hy, (hε hy).2.le) end /-- Let `s` be a convex set in a real normed vector space `E`, let `f : E → G` be a function differentiable within `s` in a neighborhood of `x : E` with derivative `f'`. Suppose that `f'` is continuous within `s` at `x`. Then for any number `K : ℝ≥0` larger than `∥f' x∥₊`, `f` is Lipschitz on some neighborhood of `x` within `s`. See also `convex.exists_nhds_within_lipschitz_on_with_of_has_fderiv_within_at_of_nnnorm_lt` for a version with an explicit estimate on the Lipschitz constant. -/ lemma convex.exists_nhds_within_lipschitz_on_with_of_has_fderiv_within_at (hs : convex ℝ s) {f : E → G} (hder : ∀ᶠ y in 𝓝[s] x, has_fderiv_within_at f (f' y) s y) (hcont : continuous_within_at f' s x) : ∃ K (t ∈ 𝓝[s] x), lipschitz_on_with K f t := (no_top _).imp $ hs.exists_nhds_within_lipschitz_on_with_of_has_fderiv_within_at_of_nnnorm_lt hder hcont /-- The mean value theorem on a convex set: if the derivative of a function within this set is bounded by `C`, then the function is `C`-Lipschitz. Version with `fderiv_within`. -/ theorem convex.norm_image_sub_le_of_norm_fderiv_within_le (hf : differentiable_on 𝕜 f s) (bound : ∀x∈s, ∥fderiv_within 𝕜 f s x∥ ≤ C) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x∥ ≤ C * ∥y - x∥ := hs.norm_image_sub_le_of_norm_has_fderiv_within_le (λ x hx, (hf x hx).has_fderiv_within_at) bound xs ys /-- The mean value theorem on a convex set: if the derivative of a function is bounded by `C` on `s`, then the function is `C`-Lipschitz on `s`. Version with `fderiv_within` and `lipschitz_on_with`. -/ theorem convex.lipschitz_on_with_of_nnnorm_fderiv_within_le {C : ℝ≥0} (hf : differentiable_on 𝕜 f s) (bound : ∀ x ∈ s, ∥fderiv_within 𝕜 f s x∥₊ ≤ C) (hs : convex ℝ s) : lipschitz_on_with C f s:= hs.lipschitz_on_with_of_nnnorm_has_fderiv_within_le (λ x hx, (hf x hx).has_fderiv_within_at) bound /-- The mean value theorem on a convex set: if the derivative of a function is bounded by `C`, then the function is `C`-Lipschitz. Version with `fderiv`. -/ theorem convex.norm_image_sub_le_of_norm_fderiv_le (hf : ∀ x ∈ s, differentiable_at 𝕜 f x) (bound : ∀x∈s, ∥fderiv 𝕜 f x∥ ≤ C) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x∥ ≤ C * ∥y - x∥ := hs.norm_image_sub_le_of_norm_has_fderiv_within_le (λ x hx, (hf x hx).has_fderiv_at.has_fderiv_within_at) bound xs ys /-- The mean value theorem on a convex set: if the derivative of a function is bounded by `C` on `s`, then the function is `C`-Lipschitz on `s`. Version with `fderiv` and `lipschitz_on_with`. -/ theorem convex.lipschitz_on_with_of_nnnorm_fderiv_le {C : ℝ≥0} (hf : ∀ x ∈ s, differentiable_at 𝕜 f x) (bound : ∀x∈s, ∥fderiv 𝕜 f x∥₊ ≤ C) (hs : convex ℝ s) : lipschitz_on_with C f s := hs.lipschitz_on_with_of_nnnorm_has_fderiv_within_le (λ x hx, (hf x hx).has_fderiv_at.has_fderiv_within_at) bound /-- Variant of the mean value inequality on a convex set, using a bound on the difference between the derivative and a fixed linear map, rather than a bound on the derivative itself. Version with `has_fderiv_within`. -/ theorem convex.norm_image_sub_le_of_norm_has_fderiv_within_le' (hf : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (bound : ∀x∈s, ∥f' x - φ∥ ≤ C) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x - φ (y - x)∥ ≤ C * ∥y - x∥ := begin /- We subtract `φ` to define a new function `g` for which `g' = 0`, for which the previous theorem applies, `convex.norm_image_sub_le_of_norm_has_fderiv_within_le`. Then, we just need to glue together the pieces, expressing back `f` in terms of `g`. -/ let g := λy, f y - φ y, have hg : ∀ x ∈ s, has_fderiv_within_at g (f' x - φ) s x := λ x xs, (hf x xs).sub φ.has_fderiv_within_at, calc ∥f y - f x - φ (y - x)∥ = ∥f y - f x - (φ y - φ x)∥ : by simp ... = ∥(f y - φ y) - (f x - φ x)∥ : by abel ... = ∥g y - g x∥ : by simp ... ≤ C * ∥y - x∥ : convex.norm_image_sub_le_of_norm_has_fderiv_within_le hg bound hs xs ys, end /-- Variant of the mean value inequality on a convex set. Version with `fderiv_within`. -/ theorem convex.norm_image_sub_le_of_norm_fderiv_within_le' (hf : differentiable_on 𝕜 f s) (bound : ∀x∈s, ∥fderiv_within 𝕜 f s x - φ∥ ≤ C) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x - φ (y - x)∥ ≤ C * ∥y - x∥ := hs.norm_image_sub_le_of_norm_has_fderiv_within_le' (λ x hx, (hf x hx).has_fderiv_within_at) bound xs ys /-- Variant of the mean value inequality on a convex set. Version with `fderiv`. -/ theorem convex.norm_image_sub_le_of_norm_fderiv_le' (hf : ∀ x ∈ s, differentiable_at 𝕜 f x) (bound : ∀x∈s, ∥fderiv 𝕜 f x - φ∥ ≤ C) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x - φ (y - x)∥ ≤ C * ∥y - x∥ := hs.norm_image_sub_le_of_norm_has_fderiv_within_le' (λ x hx, (hf x hx).has_fderiv_at.has_fderiv_within_at) bound xs ys /-- If a function has zero Fréchet derivative at every point of a convex set, then it is a constant on this set. -/ theorem convex.is_const_of_fderiv_within_eq_zero (hs : convex ℝ s) (hf : differentiable_on 𝕜 f s) (hf' : ∀ x ∈ s, fderiv_within 𝕜 f s x = 0) (hx : x ∈ s) (hy : y ∈ s) : f x = f y := have bound : ∀ x ∈ s, ∥fderiv_within 𝕜 f s x∥ ≤ 0, from λ x hx, by simp only [hf' x hx, norm_zero], by simpa only [(dist_eq_norm _ _).symm, zero_mul, dist_le_zero, eq_comm] using hs.norm_image_sub_le_of_norm_fderiv_within_le hf bound hx hy theorem is_const_of_fderiv_eq_zero (hf : differentiable 𝕜 f) (hf' : ∀ x, fderiv 𝕜 f x = 0) (x y : E) : f x = f y := convex_univ.is_const_of_fderiv_within_eq_zero hf.differentiable_on (λ x _, by rw fderiv_within_univ; exact hf' x) trivial trivial end /-- The mean value theorem on a convex set in dimension 1: if the derivative of a function is bounded by `C`, then the function is `C`-Lipschitz. Version with `has_deriv_within`. -/ theorem convex.norm_image_sub_le_of_norm_has_deriv_within_le {f f' : ℝ → F} {C : ℝ} {s : set ℝ} {x y : ℝ} (hf : ∀ x ∈ s, has_deriv_within_at f (f' x) s x) (bound : ∀x∈s, ∥f' x∥ ≤ C) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x∥ ≤ C * ∥y - x∥ := convex.norm_image_sub_le_of_norm_has_fderiv_within_le (λ x hx, (hf x hx).has_fderiv_within_at) (λ x hx, le_trans (by simp) (bound x hx)) hs xs ys /-- The mean value theorem on a convex set in dimension 1: if the derivative of a function is bounded by `C` on `s`, then the function is `C`-Lipschitz on `s`. Version with `has_deriv_within` and `lipschitz_on_with`. -/ theorem convex.lipschitz_on_with_of_nnnorm_has_deriv_within_le {f f' : ℝ → F} {C : ℝ≥0} {s : set ℝ} (hs : convex ℝ s) (hf : ∀ x ∈ s, has_deriv_within_at f (f' x) s x) (bound : ∀x∈s, ∥f' x∥₊ ≤ C) : lipschitz_on_with C f s := convex.lipschitz_on_with_of_nnnorm_has_fderiv_within_le (λ x hx, (hf x hx).has_fderiv_within_at) (λ x hx, le_trans (by simp) (bound x hx)) hs /-- The mean value theorem on a convex set in dimension 1: if the derivative of a function within this set is bounded by `C`, then the function is `C`-Lipschitz. Version with `deriv_within` -/ theorem convex.norm_image_sub_le_of_norm_deriv_within_le {f : ℝ → F} {C : ℝ} {s : set ℝ} {x y : ℝ} (hf : differentiable_on ℝ f s) (bound : ∀x∈s, ∥deriv_within f s x∥ ≤ C) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x∥ ≤ C * ∥y - x∥ := hs.norm_image_sub_le_of_norm_has_deriv_within_le (λ x hx, (hf x hx).has_deriv_within_at) bound xs ys /-- The mean value theorem on a convex set in dimension 1: if the derivative of a function is bounded by `C` on `s`, then the function is `C`-Lipschitz on `s`. Version with `deriv_within` and `lipschitz_on_with`. -/ theorem convex.lipschitz_on_with_of_nnnorm_deriv_within_le {f : ℝ → F} {C : ℝ≥0} {s : set ℝ} (hs : convex ℝ s) (hf : differentiable_on ℝ f s) (bound : ∀x∈s, ∥deriv_within f s x∥₊ ≤ C) : lipschitz_on_with C f s := hs.lipschitz_on_with_of_nnnorm_has_deriv_within_le (λ x hx, (hf x hx).has_deriv_within_at) bound /-- The mean value theorem on a convex set in dimension 1: if the derivative of a function is bounded by `C`, then the function is `C`-Lipschitz. Version with `deriv`. -/ theorem convex.norm_image_sub_le_of_norm_deriv_le {f : ℝ → F} {C : ℝ} {s : set ℝ} {x y : ℝ} (hf : ∀ x ∈ s, differentiable_at ℝ f x) (bound : ∀x∈s, ∥deriv f x∥ ≤ C) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x∥ ≤ C * ∥y - x∥ := hs.norm_image_sub_le_of_norm_has_deriv_within_le (λ x hx, (hf x hx).has_deriv_at.has_deriv_within_at) bound xs ys /-- The mean value theorem on a convex set in dimension 1: if the derivative of a function is bounded by `C` on `s`, then the function is `C`-Lipschitz on `s`. Version with `deriv` and `lipschitz_on_with`. -/ theorem convex.lipschitz_on_with_of_nnnorm_deriv_le {f : ℝ → F} {C : ℝ≥0} {s : set ℝ} (hf : ∀ x ∈ s, differentiable_at ℝ f x) (bound : ∀x∈s, ∥deriv f x∥₊ ≤ C) (hs : convex ℝ s) : lipschitz_on_with C f s := hs.lipschitz_on_with_of_nnnorm_has_deriv_within_le (λ x hx, (hf x hx).has_deriv_at.has_deriv_within_at) bound /-! ### Functions `[a, b] → ℝ`. -/ section interval -- Declare all variables here to make sure they come in a correct order variables (f f' : ℝ → ℝ) {a b : ℝ} (hab : a < b) (hfc : continuous_on f (Icc a b)) (hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) (hfd : differentiable_on ℝ f (Ioo a b)) (g g' : ℝ → ℝ) (hgc : continuous_on g (Icc a b)) (hgg' : ∀ x ∈ Ioo a b, has_deriv_at g (g' x) x) (hgd : differentiable_on ℝ g (Ioo a b)) include hab hfc hff' hgc hgg' /-- Cauchy's **Mean Value Theorem**, `has_deriv_at` version. -/ lemma exists_ratio_has_deriv_at_eq_ratio_slope : ∃ c ∈ Ioo a b, (g b - g a) * f' c = (f b - f a) * g' c := begin let h := λ x, (g b - g a) * f x - (f b - f a) * g x, have hI : h a = h b, { simp only [h], ring }, let h' := λ x, (g b - g a) * f' x - (f b - f a) * g' x, have hhh' : ∀ x ∈ Ioo a b, has_deriv_at h (h' x) x, from λ x hx, ((hff' x hx).const_mul (g b - g a)).sub ((hgg' x hx).const_mul (f b - f a)), have hhc : continuous_on h (Icc a b), from (continuous_on_const.mul hfc).sub (continuous_on_const.mul hgc), rcases exists_has_deriv_at_eq_zero h h' hab hhc hI hhh' with ⟨c, cmem, hc⟩, exact ⟨c, cmem, sub_eq_zero.1 hc⟩ end omit hfc hgc /-- Cauchy's **Mean Value Theorem**, extended `has_deriv_at` version. -/ lemma exists_ratio_has_deriv_at_eq_ratio_slope' {lfa lga lfb lgb : ℝ} (hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) (hgg' : ∀ x ∈ Ioo a b, has_deriv_at g (g' x) x) (hfa : tendsto f (𝓝[Ioi a] a) (𝓝 lfa)) (hga : tendsto g (𝓝[Ioi a] a) (𝓝 lga)) (hfb : tendsto f (𝓝[Iio b] b) (𝓝 lfb)) (hgb : tendsto g (𝓝[Iio b] b) (𝓝 lgb)) : ∃ c ∈ Ioo a b, (lgb - lga) * (f' c) = (lfb - lfa) * (g' c) := begin let h := λ x, (lgb - lga) * f x - (lfb - lfa) * g x, have hha : tendsto h (𝓝[Ioi a] a) (𝓝 $ lgb * lfa - lfb * lga), { have : tendsto h (𝓝[Ioi a] a)(𝓝 $ (lgb - lga) * lfa - (lfb - lfa) * lga) := (tendsto_const_nhds.mul hfa).sub (tendsto_const_nhds.mul hga), convert this using 2, ring }, have hhb : tendsto h (𝓝[Iio b] b) (𝓝 $ lgb * lfa - lfb * lga), { have : tendsto h (𝓝[Iio b] b)(𝓝 $ (lgb - lga) * lfb - (lfb - lfa) * lgb) := (tendsto_const_nhds.mul hfb).sub (tendsto_const_nhds.mul hgb), convert this using 2, ring }, let h' := λ x, (lgb - lga) * f' x - (lfb - lfa) * g' x, have hhh' : ∀ x ∈ Ioo a b, has_deriv_at h (h' x) x, { intros x hx, exact ((hff' x hx).const_mul _ ).sub (((hgg' x hx)).const_mul _) }, rcases exists_has_deriv_at_eq_zero' hab hha hhb hhh' with ⟨c, cmem, hc⟩, exact ⟨c, cmem, sub_eq_zero.1 hc⟩ end include hfc omit hgg' /-- Lagrange's Mean Value Theorem, `has_deriv_at` version -/ lemma exists_has_deriv_at_eq_slope : ∃ c ∈ Ioo a b, f' c = (f b - f a) / (b - a) := begin rcases exists_ratio_has_deriv_at_eq_ratio_slope f f' hab hfc hff' id 1 continuous_id.continuous_on (λ x hx, has_deriv_at_id x) with ⟨c, cmem, hc⟩, use [c, cmem], simp only [_root_.id, pi.one_apply, mul_one] at hc, rw [← hc, mul_div_cancel_left], exact ne_of_gt (sub_pos.2 hab) end omit hff' /-- Cauchy's Mean Value Theorem, `deriv` version. -/ lemma exists_ratio_deriv_eq_ratio_slope : ∃ c ∈ Ioo a b, (g b - g a) * (deriv f c) = (f b - f a) * (deriv g c) := exists_ratio_has_deriv_at_eq_ratio_slope f (deriv f) hab hfc (λ x hx, ((hfd x hx).differentiable_at $ is_open.mem_nhds is_open_Ioo hx).has_deriv_at) g (deriv g) hgc $ λ x hx, ((hgd x hx).differentiable_at $ is_open.mem_nhds is_open_Ioo hx).has_deriv_at omit hfc /-- Cauchy's Mean Value Theorem, extended `deriv` version. -/ lemma exists_ratio_deriv_eq_ratio_slope' {lfa lga lfb lgb : ℝ} (hdf : differentiable_on ℝ f $ Ioo a b) (hdg : differentiable_on ℝ g $ Ioo a b) (hfa : tendsto f (𝓝[Ioi a] a) (𝓝 lfa)) (hga : tendsto g (𝓝[Ioi a] a) (𝓝 lga)) (hfb : tendsto f (𝓝[Iio b] b) (𝓝 lfb)) (hgb : tendsto g (𝓝[Iio b] b) (𝓝 lgb)) : ∃ c ∈ Ioo a b, (lgb - lga) * (deriv f c) = (lfb - lfa) * (deriv g c) := exists_ratio_has_deriv_at_eq_ratio_slope' _ _ hab _ _ (λ x hx, ((hdf x hx).differentiable_at $ Ioo_mem_nhds hx.1 hx.2).has_deriv_at) (λ x hx, ((hdg x hx).differentiable_at $ Ioo_mem_nhds hx.1 hx.2).has_deriv_at) hfa hga hfb hgb /-- Lagrange's **Mean Value Theorem**, `deriv` version. -/ lemma exists_deriv_eq_slope : ∃ c ∈ Ioo a b, deriv f c = (f b - f a) / (b - a) := exists_has_deriv_at_eq_slope f (deriv f) hab hfc (λ x hx, ((hfd x hx).differentiable_at $ is_open.mem_nhds is_open_Ioo hx).has_deriv_at) end interval /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `C < f'`, then `f` grows faster than `C * x` on `D`, i.e., `C * (y - x) < f y - f x` whenever `x, y ∈ D`, `x < y`. -/ theorem convex.mul_sub_lt_image_sub_of_lt_deriv {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) {C} (hf'_gt : ∀ x ∈ interior D, C < deriv f x) : ∀ x y ∈ D, x < y → C * (y - x) < f y - f x := begin assume x y hx hy hxy, have hxyD : Icc x y ⊆ D, from hD.ord_connected.out hx hy, have hxyD' : Ioo x y ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hxyD⟩, obtain ⟨a, a_mem, ha⟩ : ∃ a ∈ Ioo x y, deriv f a = (f y - f x) / (y - x), from exists_deriv_eq_slope f hxy (hf.mono hxyD) (hf'.mono hxyD'), have : C < (f y - f x) / (y - x), by { rw [← ha], exact hf'_gt _ (hxyD' a_mem) }, exact (lt_div_iff (sub_pos.2 hxy)).1 this end /-- Let `f : ℝ → ℝ` be a differentiable function. If `C < f'`, then `f` grows faster than `C * x`, i.e., `C * (y - x) < f y - f x` whenever `x < y`. -/ theorem mul_sub_lt_image_sub_of_lt_deriv {f : ℝ → ℝ} (hf : differentiable ℝ f) {C} (hf'_gt : ∀ x, C < deriv f x) ⦃x y⦄ (hxy : x < y) : C * (y - x) < f y - f x := convex_univ.mul_sub_lt_image_sub_of_lt_deriv hf.continuous.continuous_on hf.differentiable_on (λ x _, hf'_gt x) x y trivial trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `C ≤ f'`, then `f` grows at least as fast as `C * x` on `D`, i.e., `C * (y - x) ≤ f y - f x` whenever `x, y ∈ D`, `x ≤ y`. -/ theorem convex.mul_sub_le_image_sub_of_le_deriv {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) {C} (hf'_ge : ∀ x ∈ interior D, C ≤ deriv f x) : ∀ x y ∈ D, x ≤ y → C * (y - x) ≤ f y - f x := begin assume x y hx hy hxy, cases eq_or_lt_of_le hxy with hxy' hxy', by rw [hxy', sub_self, sub_self, mul_zero], have hxyD : Icc x y ⊆ D, from hD.ord_connected.out hx hy, have hxyD' : Ioo x y ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hxyD⟩, obtain ⟨a, a_mem, ha⟩ : ∃ a ∈ Ioo x y, deriv f a = (f y - f x) / (y - x), from exists_deriv_eq_slope f hxy' (hf.mono hxyD) (hf'.mono hxyD'), have : C ≤ (f y - f x) / (y - x), by { rw [← ha], exact hf'_ge _ (hxyD' a_mem) }, exact (le_div_iff (sub_pos.2 hxy')).1 this end /-- Let `f : ℝ → ℝ` be a differentiable function. If `C ≤ f'`, then `f` grows at least as fast as `C * x`, i.e., `C * (y - x) ≤ f y - f x` whenever `x ≤ y`. -/ theorem mul_sub_le_image_sub_of_le_deriv {f : ℝ → ℝ} (hf : differentiable ℝ f) {C} (hf'_ge : ∀ x, C ≤ deriv f x) ⦃x y⦄ (hxy : x ≤ y) : C * (y - x) ≤ f y - f x := convex_univ.mul_sub_le_image_sub_of_le_deriv hf.continuous.continuous_on hf.differentiable_on (λ x _, hf'_ge x) x y trivial trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f' < C`, then `f` grows slower than `C * x` on `D`, i.e., `f y - f x < C * (y - x)` whenever `x, y ∈ D`, `x < y`. -/ theorem convex.image_sub_lt_mul_sub_of_deriv_lt {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) {C} (lt_hf' : ∀ x ∈ interior D, deriv f x < C) : ∀ x y ∈ D, x < y → f y - f x < C * (y - x) := begin assume x y hx hy hxy, have hf'_gt : ∀ x ∈ interior D, -C < deriv (λ y, -f y) x, { assume x hx, rw [deriv.neg, neg_lt_neg_iff], exact lt_hf' x hx }, simpa [-neg_lt_neg_iff] using neg_lt_neg (hD.mul_sub_lt_image_sub_of_lt_deriv hf.neg hf'.neg hf'_gt x y hx hy hxy) end /-- Let `f : ℝ → ℝ` be a differentiable function. If `f' < C`, then `f` grows slower than `C * x` on `D`, i.e., `f y - f x < C * (y - x)` whenever `x < y`. -/ theorem image_sub_lt_mul_sub_of_deriv_lt {f : ℝ → ℝ} (hf : differentiable ℝ f) {C} (lt_hf' : ∀ x, deriv f x < C) ⦃x y⦄ (hxy : x < y) : f y - f x < C * (y - x) := convex_univ.image_sub_lt_mul_sub_of_deriv_lt hf.continuous.continuous_on hf.differentiable_on (λ x _, lt_hf' x) x y trivial trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f' ≤ C`, then `f` grows at most as fast as `C * x` on `D`, i.e., `f y - f x ≤ C * (y - x)` whenever `x, y ∈ D`, `x ≤ y`. -/ theorem convex.image_sub_le_mul_sub_of_deriv_le {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) {C} (le_hf' : ∀ x ∈ interior D, deriv f x ≤ C) : ∀ x y ∈ D, x ≤ y → f y - f x ≤ C * (y - x) := begin assume x y hx hy hxy, have hf'_ge : ∀ x ∈ interior D, -C ≤ deriv (λ y, -f y) x, { assume x hx, rw [deriv.neg, neg_le_neg_iff], exact le_hf' x hx }, simpa [-neg_le_neg_iff] using neg_le_neg (hD.mul_sub_le_image_sub_of_le_deriv hf.neg hf'.neg hf'_ge x y hx hy hxy) end /-- Let `f : ℝ → ℝ` be a differentiable function. If `f' ≤ C`, then `f` grows at most as fast as `C * x`, i.e., `f y - f x ≤ C * (y - x)` whenever `x ≤ y`. -/ theorem image_sub_le_mul_sub_of_deriv_le {f : ℝ → ℝ} (hf : differentiable ℝ f) {C} (le_hf' : ∀ x, deriv f x ≤ C) ⦃x y⦄ (hxy : x ≤ y) : f y - f x ≤ C * (y - x) := convex_univ.image_sub_le_mul_sub_of_deriv_le hf.continuous.continuous_on hf.differentiable_on (λ x _, le_hf' x) x y trivial trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f'` is positive, then `f` is a strictly monotone function on `D`. -/ theorem convex.strict_mono_on_of_deriv_pos {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'_pos : ∀ x ∈ interior D, 0 < deriv f x) : strict_mono_on f D := λ x hx y hy, by simpa only [zero_mul, sub_pos] using hD.mul_sub_lt_image_sub_of_lt_deriv hf hf' hf'_pos x y hx hy /-- Let `f : ℝ → ℝ` be a differentiable function. If `f'` is positive, then `f` is a strictly monotone function. -/ theorem strict_mono_of_deriv_pos {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf'_pos : ∀ x, 0 < deriv f x) : strict_mono f := strict_mono_on_univ.1 $ convex_univ.strict_mono_on_of_deriv_pos hf.continuous.continuous_on hf.differentiable_on (λ x _, hf'_pos x) /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f'` is nonnegative, then `f` is a monotone function on `D`. -/ theorem convex.monotone_on_of_deriv_nonneg {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'_nonneg : ∀ x ∈ interior D, 0 ≤ deriv f x) : monotone_on f D := λ x hx y hy hxy, by simpa only [zero_mul, sub_nonneg] using hD.mul_sub_le_image_sub_of_le_deriv hf hf' hf'_nonneg x y hx hy hxy /-- Let `f : ℝ → ℝ` be a differentiable function. If `f'` is nonnegative, then `f` is a monotone function. -/ theorem monotone_of_deriv_nonneg {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf' : ∀ x, 0 ≤ deriv f x) : monotone f := monotone_on_univ.1 $ convex_univ.monotone_on_of_deriv_nonneg hf.continuous.continuous_on hf.differentiable_on (λ x _, hf' x) /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f'` is negative, then `f` is a strictly antitone function on `D`. -/ theorem convex.strict_anti_on_of_deriv_neg {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'_neg : ∀ x ∈ interior D, deriv f x < 0) : strict_anti_on f D := λ x hx y, by simpa only [zero_mul, sub_lt_zero] using hD.image_sub_lt_mul_sub_of_deriv_lt hf hf' hf'_neg x y hx /-- Let `f : ℝ → ℝ` be a differentiable function. If `f'` is negative, then `f` is a strictly antitone function. -/ theorem strict_anti_of_deriv_neg {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf' : ∀ x, deriv f x < 0) : strict_anti f := strict_anti_on_univ.1 $ convex_univ.strict_anti_on_of_deriv_neg hf.continuous.continuous_on hf.differentiable_on (λ x _, hf' x) /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f'` is nonpositive, then `f` is an antitone function on `D`. -/ theorem convex.antitone_on_of_deriv_nonpos {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'_nonpos : ∀ x ∈ interior D, deriv f x ≤ 0) : antitone_on f D := λ x hx y hy hxy, by simpa only [zero_mul, sub_nonpos] using hD.image_sub_le_mul_sub_of_deriv_le hf hf' hf'_nonpos x y hx hy hxy /-- Let `f : ℝ → ℝ` be a differentiable function. If `f'` is nonpositive, then `f` is an antitone function. -/ theorem antitone_of_deriv_nonpos {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf' : ∀ x, deriv f x ≤ 0) : antitone f := antitone_on_univ.1 $ convex_univ.antitone_on_of_deriv_nonpos hf.continuous.continuous_on hf.differentiable_on (λ x _, hf' x) /-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is differentiable on its interior, and `f'` is monotone on the interior, then `f` is convex on `D`. -/ theorem convex_on_of_deriv_monotone_on {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'_mono : monotone_on (deriv f) (interior D)) : convex_on ℝ D f := convex_on_of_slope_mono_adjacent hD begin intros x y z hx hz hxy hyz, -- First we prove some trivial inclusions have hxzD : Icc x z ⊆ D, from hD.ord_connected.out hx hz, have hxyD : Icc x y ⊆ D, from subset.trans (Icc_subset_Icc_right $ le_of_lt hyz) hxzD, have hxyD' : Ioo x y ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hxyD⟩, have hyzD : Icc y z ⊆ D, from subset.trans (Icc_subset_Icc_left $ le_of_lt hxy) hxzD, have hyzD' : Ioo y z ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hyzD⟩, -- Then we apply MVT to both `[x, y]` and `[y, z]` obtain ⟨a, ⟨hxa, hay⟩, ha⟩ : ∃ a ∈ Ioo x y, deriv f a = (f y - f x) / (y - x), from exists_deriv_eq_slope f hxy (hf.mono hxyD) (hf'.mono hxyD'), obtain ⟨b, ⟨hyb, hbz⟩, hb⟩ : ∃ b ∈ Ioo y z, deriv f b = (f z - f y) / (z - y), from exists_deriv_eq_slope f hyz (hf.mono hyzD) (hf'.mono hyzD'), rw [← ha, ← hb], exact hf'_mono (hxyD' ⟨hxa, hay⟩) (hyzD' ⟨hyb, hbz⟩) (hay.trans hyb).le end /-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is differentiable on its interior, and `f'` is antitone on the interior, then `f` is concave on `D`. -/ theorem concave_on_of_deriv_antitone_on {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (h_anti : antitone_on (deriv f) (interior D)) : concave_on ℝ D f := begin have : monotone_on (deriv (-f)) (interior D), { intros x hx y hy hxy, convert neg_le_neg (h_anti hx hy hxy); convert deriv.neg }, exact neg_convex_on_iff.mp (convex_on_of_deriv_monotone_on hD hf.neg hf'.neg this), end /-- If a function `f` is differentiable and `f'` is monotone on `ℝ` then `f` is convex. -/ theorem convex_on_univ_of_deriv_monotone {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf'_mono : monotone (deriv f)) : convex_on ℝ univ f := convex_on_of_deriv_monotone_on convex_univ hf.continuous.continuous_on hf.differentiable_on (hf'_mono.monotone_on _) /-- If a function `f` is differentiable and `f'` is antitone on `ℝ` then `f` is concave. -/ theorem antitone.concave_on_univ {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf'_anti : antitone (deriv f)) : concave_on ℝ univ f := concave_on_of_deriv_antitone_on convex_univ hf.continuous.continuous_on hf.differentiable_on (hf'_anti.antitone_on _) /-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is twice differentiable on its interior, and `f''` is nonnegative on the interior, then `f` is convex on `D`. -/ theorem convex_on_of_deriv2_nonneg {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'' : differentiable_on ℝ (deriv f) (interior D)) (hf''_nonneg : ∀ x ∈ interior D, 0 ≤ (deriv^[2] f x)) : convex_on ℝ D f := convex_on_of_deriv_monotone_on hD hf hf' $ hD.interior.monotone_on_of_deriv_nonneg hf''.continuous_on (by rwa interior_interior) (by rwa interior_interior) /-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is twice differentiable on its interior, and `f''` is nonpositive on the interior, then `f` is concave on `D`. -/ theorem concave_on_of_deriv2_nonpos {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'' : differentiable_on ℝ (deriv f) (interior D)) (hf''_nonpos : ∀ x ∈ interior D, (deriv^[2] f x) ≤ 0) : concave_on ℝ D f := concave_on_of_deriv_antitone_on hD hf hf' $ hD.interior.antitone_on_of_deriv_nonpos hf''.continuous_on (by rwa interior_interior) (by rwa interior_interior) /-- If a function `f` is twice differentiable on a open convex set `D ⊆ ℝ` and `f''` is nonnegative on `D`, then `f` is convex on `D`. -/ theorem convex_on_open_of_deriv2_nonneg {D : set ℝ} (hD : convex ℝ D) (hD₂ : is_open D) {f : ℝ → ℝ} (hf' : differentiable_on ℝ f D) (hf'' : differentiable_on ℝ (deriv f) D) (hf''_nonneg : ∀ x ∈ D, 0 ≤ (deriv^[2] f x)) : convex_on ℝ D f := convex_on_of_deriv2_nonneg hD hf'.continuous_on (by simpa [hD₂.interior_eq] using hf') (by simpa [hD₂.interior_eq] using hf'') (by simpa [hD₂.interior_eq] using hf''_nonneg) /-- If a function `f` is twice differentiable on an open convex set `D ⊆ ℝ` and `f''` is nonpositive on `D`, then `f` is concave on `D`. -/ theorem concave_on_open_of_deriv2_nonpos {D : set ℝ} (hD : convex ℝ D) (hD₂ : is_open D) {f : ℝ → ℝ} (hf' : differentiable_on ℝ f D) (hf'' : differentiable_on ℝ (deriv f) D) (hf''_nonpos : ∀ x ∈ D, (deriv^[2] f x) ≤ 0) : concave_on ℝ D f := concave_on_of_deriv2_nonpos hD hf'.continuous_on (by simpa [hD₂.interior_eq] using hf') (by simpa [hD₂.interior_eq] using hf'') (by simpa [hD₂.interior_eq] using hf''_nonpos) /-- If a function `f` is twice differentiable on `ℝ`, and `f''` is nonnegative on `ℝ`, then `f` is convex on `ℝ`. -/ theorem convex_on_univ_of_deriv2_nonneg {f : ℝ → ℝ} (hf' : differentiable ℝ f) (hf'' : differentiable ℝ (deriv f)) (hf''_nonneg : ∀ x, 0 ≤ (deriv^[2] f x)) : convex_on ℝ univ f := convex_on_open_of_deriv2_nonneg convex_univ is_open_univ hf'.differentiable_on hf''.differentiable_on (λ x _, hf''_nonneg x) /-- If a function `f` is twice differentiable on `ℝ`, and `f''` is nonpositive on `ℝ`, then `f` is concave on `ℝ`. -/ theorem concave_on_univ_of_deriv2_nonpos {f : ℝ → ℝ} (hf' : differentiable ℝ f) (hf'' : differentiable ℝ (deriv f)) (hf''_nonpos : ∀ x, (deriv^[2] f x) ≤ 0) : concave_on ℝ univ f := concave_on_open_of_deriv2_nonpos convex_univ is_open_univ hf'.differentiable_on hf''.differentiable_on (λ x _, hf''_nonpos x) /-! ### Functions `f : E → ℝ` -/ /-- Lagrange's Mean Value Theorem, applied to convex domains. -/ theorem domain_mvt {f : E → ℝ} {s : set E} {x y : E} {f' : E → (E →L[ℝ] ℝ)} (hf : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∃ z ∈ segment ℝ x y, f y - f x = f' z (y - x) := begin have hIccIoo := @Ioo_subset_Icc_self ℝ _ 0 1, -- parametrize segment set g : ℝ → E := λ t, x + t • (y - x), have hseg : ∀ t ∈ Icc (0:ℝ) 1, g t ∈ segment ℝ x y, { rw segment_eq_image', simp only [mem_image, and_imp, add_right_inj], intros t ht, exact ⟨t, ht, rfl⟩ }, have hseg' : Icc 0 1 ⊆ g ⁻¹' s, { rw ← image_subset_iff, unfold image, change ∀ _, _, intros z Hz, rw mem_set_of_eq at Hz, rcases Hz with ⟨t, Ht, hgt⟩, rw ← hgt, exact hs.segment_subset xs ys (hseg t Ht) }, -- derivative of pullback of f under parametrization have hfg: ∀ t ∈ Icc (0:ℝ) 1, has_deriv_within_at (f ∘ g) ((f' (g t) : E → ℝ) (y-x)) (Icc (0:ℝ) 1) t, { intros t Ht, have hg : has_deriv_at g (y-x) t, { have := ((has_deriv_at_id t).smul_const (y - x)).const_add x, rwa one_smul at this }, exact (hf (g t) $ hseg' Ht).comp_has_deriv_within_at _ hg.has_deriv_within_at hseg' }, -- apply 1-variable mean value theorem to pullback have hMVT : ∃ (t ∈ Ioo (0:ℝ) 1), ((f' (g t) : E → ℝ) (y-x)) = (f (g 1) - f (g 0)) / (1 - 0), { refine exists_has_deriv_at_eq_slope (f ∘ g) _ (by norm_num) _ _, { unfold continuous_on, exact λ t Ht, (hfg t Ht).continuous_within_at }, { refine λ t Ht, (hfg t $ hIccIoo Ht).has_deriv_at _, refine _root_.mem_nhds_iff.mpr _, use (Ioo (0:ℝ) 1), refine ⟨hIccIoo, _, Ht⟩, simp [real.Ioo_eq_ball, is_open_ball] } }, -- reinterpret on domain rcases hMVT with ⟨t, Ht, hMVT'⟩, use g t, refine ⟨hseg t $ hIccIoo Ht, _⟩, simp [g, hMVT'], end section is_R_or_C /-! ### Vector-valued functions `f : E → F`. Strict differentiability. A `C^1` function is strictly differentiable, when the field is `ℝ` or `ℂ`. This follows from the mean value inequality on balls, which is a particular case of the above results after restricting the scalars to `ℝ`. Note that it does not make sense to talk of a convex set over `ℂ`, but balls make sense and are enough. Many formulations of the mean value inequality could be generalized to balls over `ℝ` or `ℂ`. For now, we only include the ones that we need. -/ variables {𝕜 : Type*} [is_R_or_C 𝕜] {G : Type*} [normed_group G] [normed_space 𝕜 G] {H : Type*} [normed_group H] [normed_space 𝕜 H] {f : G → H} {f' : G → G →L[𝕜] H} {x : G} /-- Over the reals or the complexes, a continuously differentiable function is strictly differentiable. -/ lemma has_strict_fderiv_at_of_has_fderiv_at_of_continuous_at (hder : ∀ᶠ y in 𝓝 x, has_fderiv_at f (f' y) y) (hcont : continuous_at f' x) : has_strict_fderiv_at f (f' x) x := begin -- turn little-o definition of strict_fderiv into an epsilon-delta statement refine is_o_iff.mpr (λ c hc, metric.eventually_nhds_iff_ball.mpr _), -- the correct ε is the modulus of continuity of f' rcases metric.mem_nhds_iff.mp (inter_mem hder (hcont $ ball_mem_nhds _ hc)) with ⟨ε, ε0, hε⟩, refine ⟨ε, ε0, _⟩, -- simplify formulas involving the product E × E rintros ⟨a, b⟩ h, rw [← ball_prod_same, prod_mk_mem_set_prod_eq] at h, -- exploit the choice of ε as the modulus of continuity of f' have hf' : ∀ x' ∈ ball x ε, ∥f' x' - f' x∥ ≤ c, { intros x' H', rw ← dist_eq_norm, exact le_of_lt (hε H').2 }, -- apply mean value theorem letI : normed_space ℝ G := restrict_scalars.normed_space ℝ 𝕜 G, letI : is_scalar_tower ℝ 𝕜 G := restrict_scalars.is_scalar_tower _ _ _, refine (convex_ball _ _).norm_image_sub_le_of_norm_has_fderiv_within_le' _ hf' h.2 h.1, exact λ y hy, (hε hy).1.has_fderiv_within_at end /-- Over the reals or the complexes, a continuously differentiable function is strictly differentiable. -/ lemma has_strict_deriv_at_of_has_deriv_at_of_continuous_at {f f' : 𝕜 → G} {x : 𝕜} (hder : ∀ᶠ y in 𝓝 x, has_deriv_at f (f' y) y) (hcont : continuous_at f' x) : has_strict_deriv_at f (f' x) x := has_strict_fderiv_at_of_has_fderiv_at_of_continuous_at (hder.mono (λ y hy, hy.has_fderiv_at)) $ (smul_rightL 𝕜 _ _ 1).continuous.continuous_at.comp hcont end is_R_or_C
5f1672e94811842f9568f3a2e68bec05801c27a5
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/algebra/group/with_one.lean
558b7d919db95a093ca6a8d6eb7ab2cb41a36e18
[ "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
8,887
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johan Commelin -/ import algebra.ring.basic import data.equiv.basic /-! # Adjoining a zero/one to semigroups and related algebraic structures This file contains different results about adjoining an element to an algebraic structure which then behaves like a zero or a one. An example is adjoining a one to a semigroup to obtain a monoid. That this provides an example of an adjunction is proved in `algebra.category.Mon.adjunctions`. Another result says that adjoining to a group an element `zero` gives a `group_with_zero`. For more information about these structures (which are not that standard in informal mathematics, see `algebra.group_with_zero.basic`) -/ universes u v w variable {α : Type u} /-- Add an extra element `1` to a type -/ @[to_additive "Add an extra element `0` to a type"] def with_one (α) := option α namespace with_one @[to_additive] instance : monad with_one := option.monad @[to_additive] instance : has_one (with_one α) := ⟨none⟩ @[to_additive] instance : inhabited (with_one α) := ⟨1⟩ @[to_additive] instance [nonempty α] : nontrivial (with_one α) := option.nontrivial @[to_additive] instance : has_coe_t α (with_one α) := ⟨some⟩ @[to_additive] lemma some_eq_coe {a : α} : (some a : with_one α) = ↑a := rfl @[simp, to_additive] lemma coe_ne_one {a : α} : (a : with_one α) ≠ (1 : with_one α) := option.some_ne_none a @[simp, to_additive] lemma one_ne_coe {a : α} : (1 : with_one α) ≠ a := coe_ne_one.symm @[to_additive] lemma ne_one_iff_exists {x : with_one α} : x ≠ 1 ↔ ∃ (a : α), ↑a = x := option.ne_none_iff_exists -- `to_additive` fails to generate some meta info around eqn lemmas, so `lift` doesn't work -- unless we explicitly define this instance instance : can_lift (with_one α) α := { coe := coe, cond := λ a, a ≠ 1, prf := λ a, ne_one_iff_exists.1 } @[simp, to_additive] lemma coe_inj {a b : α} : (a : with_one α) = b ↔ a = b := option.some_inj attribute [norm_cast] coe_inj with_zero.coe_inj @[elab_as_eliminator, to_additive] protected lemma cases_on {P : with_one α → Prop} : ∀ (x : with_one α), P 1 → (∀ a : α, P a) → P x := option.cases_on @[to_additive] instance [has_mul α] : mul_one_class (with_one α) := { mul := option.lift_or_get (*), one := (1), one_mul := (option.lift_or_get_is_left_id _).1, mul_one := (option.lift_or_get_is_right_id _).1 } @[to_additive] instance [semigroup α] : monoid (with_one α) := { mul_assoc := (option.lift_or_get_assoc _).1, ..with_one.mul_one_class } @[to_additive] instance [comm_semigroup α] : comm_monoid (with_one α) := { mul_comm := (option.lift_or_get_comm _).1, ..with_one.monoid } /-- `coe` as a bundled morphism -/ @[to_additive "`coe` as a bundled morphism", simps apply] def coe_mul_hom [has_mul α] : mul_hom α (with_one α) := { to_fun := coe, map_mul' := λ x y, rfl } section lift variables [has_mul α] {β : Type v} [mul_one_class β] /-- Lift a semigroup homomorphism `f` to a bundled monoid homorphism. -/ @[to_additive "Lift an add_semigroup homomorphism `f` to a bundled add_monoid homorphism."] def lift : mul_hom α β ≃ (with_one α →* β) := { to_fun := λ f, { to_fun := λ x, option.cases_on x 1 f, map_one' := rfl, map_mul' := λ x y, with_one.cases_on x (by { rw one_mul, exact (one_mul _).symm }) $ λ x, with_one.cases_on y (by { rw mul_one, exact (mul_one _).symm }) $ λ y, f.map_mul x y }, inv_fun := λ F, F.to_mul_hom.comp coe_mul_hom, left_inv := λ f, mul_hom.ext $ λ x, rfl, right_inv := λ F, monoid_hom.ext $ λ x, with_one.cases_on x F.map_one.symm $ λ x, rfl } variables (f : mul_hom α β) @[simp, to_additive] lemma lift_coe (x : α) : lift f x = f x := rfl @[simp, to_additive] lemma lift_one : lift f 1 = 1 := rfl @[to_additive] theorem lift_unique (f : with_one α →* β) : f = lift (f.to_mul_hom.comp coe_mul_hom) := (lift.apply_symm_apply f).symm end lift section map variables {β : Type v} [has_mul α] [has_mul β] /-- Given a multiplicative map from `α → β` returns a monoid homomorphism from `with_one α` to `with_one β` -/ @[to_additive "Given an additive map from `α → β` returns an add_monoid homomorphism from `with_zero α` to `with_zero β`"] def map (f : mul_hom α β) : with_one α →* with_one β := lift (coe_mul_hom.comp f) @[simp, to_additive] lemma map_id : map (mul_hom.id α) = monoid_hom.id (with_one α) := by { ext, cases x; refl } @[simp, to_additive] lemma map_comp {γ : Type w} [has_mul γ] (f : mul_hom α β) (g : mul_hom β γ) : map (g.comp f) = (map g).comp (map f) := by { ext, cases x; refl } end map attribute [irreducible] with_one @[simp, norm_cast, to_additive] lemma coe_mul [has_mul α] (a b : α) : ((a * b : α) : with_one α) = a * b := rfl end with_one namespace with_zero -- `to_additive` fails to generate some meta info around eqn lemmas, so `lift` doesn't work -- unless we explicitly define this instance instance : can_lift (with_zero α) α := { coe := coe, cond := λ a, a ≠ 0, prf := λ a, ne_zero_iff_exists.1 } attribute [to_additive] with_one.can_lift instance [one : has_one α] : has_one (with_zero α) := { ..one } @[simp, norm_cast] lemma coe_one [has_one α] : ((1 : α) : with_zero α) = 1 := rfl instance [has_mul α] : mul_zero_class (with_zero α) := { mul := λ o₁ o₂, o₁.bind (λ a, option.map (λ b, a * b) o₂), zero_mul := λ a, rfl, mul_zero := λ a, by cases a; refl, ..with_zero.has_zero } @[simp, norm_cast] lemma coe_mul {α : Type u} [has_mul α] {a b : α} : ((a * b : α) : with_zero α) = a * b := rfl @[simp] lemma zero_mul {α : Type u} [has_mul α] (a : with_zero α) : 0 * a = 0 := rfl @[simp] lemma mul_zero {α : Type u} [has_mul α] (a : with_zero α) : a * 0 = 0 := by cases a; refl instance [semigroup α] : semigroup_with_zero (with_zero α) := { mul_assoc := λ a b c, match a, b, c with | none, _, _ := rfl | some a, none, _ := rfl | some a, some b, none := rfl | some a, some b, some c := congr_arg some (mul_assoc _ _ _) end, ..with_zero.mul_zero_class } instance [comm_semigroup α] : comm_semigroup (with_zero α) := { mul_comm := λ a b, match a, b with | none, _ := (mul_zero _).symm | some a, none := rfl | some a, some b := congr_arg some (mul_comm _ _) end, ..with_zero.semigroup_with_zero } instance [mul_one_class α] : mul_zero_one_class (with_zero α) := { one_mul := λ a, match a with | none := rfl | some a := congr_arg some $ one_mul _ end, mul_one := λ a, match a with | none := rfl | some a := congr_arg some $ mul_one _ end, ..with_zero.mul_zero_class, ..with_zero.has_one } instance [monoid α] : monoid_with_zero (with_zero α) := { ..with_zero.mul_zero_one_class, ..with_zero.semigroup_with_zero } instance [comm_monoid α] : comm_monoid_with_zero (with_zero α) := { ..with_zero.monoid_with_zero, ..with_zero.comm_semigroup } /-- Given an inverse operation on `α` there is an inverse operation on `with_zero α` sending `0` to `0`-/ definition inv [has_inv α] (x : with_zero α) : with_zero α := do a ← x, return a⁻¹ instance [has_inv α] : has_inv (with_zero α) := ⟨with_zero.inv⟩ @[simp, norm_cast] lemma coe_inv [has_inv α] (a : α) : ((a⁻¹ : α) : with_zero α) = a⁻¹ := rfl @[simp] lemma inv_zero [has_inv α] : (0 : with_zero α)⁻¹ = 0 := rfl section group variables [group α] @[simp] lemma inv_one : (1 : with_zero α)⁻¹ = 1 := show ((1⁻¹ : α) : with_zero α) = 1, by simp /-- if `G` is a group then `with_zero G` is a group with zero. -/ instance : group_with_zero (with_zero α) := { inv_zero := inv_zero, mul_inv_cancel := by { intros a ha, lift a to α using ha, norm_cast, apply mul_right_inv }, .. with_zero.monoid_with_zero, .. with_zero.has_inv, .. with_zero.nontrivial } @[norm_cast] lemma div_coe (a b : α) : (a : with_zero α) / b = (a * b⁻¹ : α) := rfl end group instance [comm_group α] : comm_group_with_zero (with_zero α) := { .. with_zero.group_with_zero, .. with_zero.comm_monoid_with_zero } instance [semiring α] : semiring (with_zero α) := { left_distrib := λ a b c, begin cases a with a, {refl}, cases b with b; cases c with c; try {refl}, exact congr_arg some (left_distrib _ _ _) end, right_distrib := λ a b c, begin cases c with c, { change (a + b) * 0 = a * 0 + b * 0, simp }, cases a with a; cases b with b; try {refl}, exact congr_arg some (right_distrib _ _ _) end, ..with_zero.add_comm_monoid, ..with_zero.mul_zero_class, ..with_zero.monoid_with_zero } attribute [irreducible] with_zero end with_zero
cc7ca9da1468a2fd51146ae87cac1b34332206b9
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/ring_theory/nullstellensatz.lean
1b85983119e65ca518a2c35d5e47f4aca926f0ce
[ "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
8,175
lean
/- Copyright (c) 2021 Devon Tuma. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Devon Tuma -/ import ring_theory.jacobson import field_theory.algebraic_closure import field_theory.mv_polynomial import algebraic_geometry.prime_spectrum /-! # Nullstellensatz This file establishes a version of Hilbert's classical Nullstellensatz for `mv_polynomial`s. The main statement of the theorem is `vanishing_ideal_zero_locus_eq_radical`. The statement is in terms of new definitions `vanishing_ideal` and `zero_locus`. Mathlib already has versions of these in terms of the prime spectrum of a ring, but those are not well-suited for expressing this result. Suggestions for better ways to state this theorem or organize things are welcome. The machinery around `vanishing_ideal` and `zero_locus` is also minimal, I only added lemmas directly needed in this proof, since I'm not sure if they are the right approach. -/ open ideal noncomputable theory namespace mv_polynomial open mv_polynomial variables {k : Type*} [field k] variables {σ : Type*} /-- Set of points that are zeroes of all polynomials in an ideal -/ def zero_locus (I : ideal (mv_polynomial σ k)) : set (σ → k) := {x : σ → k | ∀ p ∈ I, eval x p = 0} @[simp] lemma mem_zero_locus_iff {I : ideal (mv_polynomial σ k)} {x : σ → k} : x ∈ zero_locus I ↔ ∀ p ∈ I, eval x p = 0 := iff.rfl lemma zero_locus_anti_mono {I J : ideal (mv_polynomial σ k)} (h : I ≤ J) : zero_locus J ≤ zero_locus I := λ x hx p hp, hx p $ h hp lemma zero_locus_bot : zero_locus (⊥ : ideal (mv_polynomial σ k)) = ⊤ := eq_top_iff.2 (λ x hx p hp, trans (congr_arg (eval x) (mem_bot.1 hp)) (eval x).map_zero) lemma zero_locus_top : zero_locus (⊤ : ideal (mv_polynomial σ k)) = ⊥ := eq_bot_iff.2 $ λ x hx, one_ne_zero ((eval x).map_one ▸ (hx 1 submodule.mem_top) : (1 : k) = 0) /-- Ideal of polynomials with common zeroes at all elements of a set -/ def vanishing_ideal (V : set (σ → k)) : ideal (mv_polynomial σ k) := { carrier := {p | ∀ x ∈ V, eval x p = 0}, zero_mem' := λ x hx, ring_hom.map_zero _, add_mem' := λ p q hp hq x hx, by simp only [hq x hx, hp x hx, add_zero, ring_hom.map_add], smul_mem' := λ p q hq x hx, by simp only [hq x hx, algebra.id.smul_eq_mul, mul_zero, ring_hom.map_mul] } @[simp] lemma mem_vanishing_ideal_iff {V : set (σ → k)} {p : mv_polynomial σ k} : p ∈ vanishing_ideal V ↔ ∀ x ∈ V, eval x p = 0 := iff.rfl lemma vanishing_ideal_anti_mono {A B : set (σ → k)} (h : A ≤ B) : vanishing_ideal B ≤ vanishing_ideal A := λ p hp x hx, hp x $ h hx lemma vanishing_ideal_empty : vanishing_ideal (∅ : set (σ → k)) = ⊤ := le_antisymm le_top (λ p hp x hx, absurd hx (set.not_mem_empty x)) lemma le_vanishing_ideal_zero_locus (I : ideal (mv_polynomial σ k)) : I ≤ vanishing_ideal (zero_locus I) := λ p hp x hx, hx p hp lemma zero_locus_vanishing_ideal_le (V : set (σ → k)) : V ≤ zero_locus (vanishing_ideal V) := λ V hV p hp, hp V hV theorem zero_locus_vanishing_ideal_galois_connection : @galois_connection (ideal (mv_polynomial σ k)) (order_dual (set (σ → k))) _ _ zero_locus vanishing_ideal := λ I V, ⟨λ h, le_trans (le_vanishing_ideal_zero_locus I) (vanishing_ideal_anti_mono h), λ h, le_trans (zero_locus_anti_mono h) (zero_locus_vanishing_ideal_le V)⟩ lemma mem_vanishing_ideal_singleton_iff (x : σ → k) (p : mv_polynomial σ k) : p ∈ (vanishing_ideal {x} : ideal (mv_polynomial σ k)) ↔ (eval x p = 0) := ⟨λ h, h x rfl, λ hpx y hy, hy.symm ▸ hpx⟩ instance vanishing_ideal_singleton_is_maximal {x : σ → k} : (vanishing_ideal {x} : ideal (mv_polynomial σ k)).is_maximal := begin have : (vanishing_ideal {x} : ideal (mv_polynomial σ k)).quotient ≃+* k := ring_equiv.of_bijective (ideal.quotient.lift _ (eval x) (λ p h, (mem_vanishing_ideal_singleton_iff x p).mp h)) begin refine ⟨(ring_hom.injective_iff _).mpr (λ p hp, _), λ z, ⟨(ideal.quotient.mk (vanishing_ideal {x} : ideal (mv_polynomial σ k))) (C z), by simp⟩⟩, obtain ⟨q, rfl⟩ := quotient.mk_surjective p, rwa [ideal.quotient.lift_mk, ← mem_vanishing_ideal_singleton_iff, ← quotient.eq_zero_iff_mem] at hp, end, rw [← bot_quotient_is_maximal_iff, ring_equiv.bot_maximal_iff this], exact bot_is_maximal, end lemma radical_le_vanishing_ideal_zero_locus (I : ideal (mv_polynomial σ k)) : I.radical ≤ vanishing_ideal (zero_locus I) := begin intros p hp x hx, rw ← mem_vanishing_ideal_singleton_iff, rw radical_eq_Inf at hp, refine (mem_Inf.mp hp) ⟨le_trans (le_vanishing_ideal_zero_locus I) (vanishing_ideal_anti_mono (λ y hy, hy.symm ▸ hx)), is_maximal.is_prime' _⟩, end /-- The point in the prime spectrum assosiated to a given point -/ def point_to_point (x : σ → k) : prime_spectrum (mv_polynomial σ k) := ⟨(vanishing_ideal {x} : ideal (mv_polynomial σ k)), by apply_instance⟩ @[simp] lemma vanishing_ideal_point_to_point (V : set (σ → k)) : prime_spectrum.vanishing_ideal (point_to_point '' V) = mv_polynomial.vanishing_ideal V := le_antisymm (λ p hp x hx, (((prime_spectrum.mem_vanishing_ideal _ _).1 hp) ⟨vanishing_ideal {x}, by apply_instance⟩ ⟨x, ⟨hx, rfl⟩⟩) x rfl) (λ p hp, (prime_spectrum.mem_vanishing_ideal _ _).2 (λ I hI, let ⟨x, hx⟩ := hI in hx.2 ▸ λ x' hx', (set.mem_singleton_iff.1 hx').symm ▸ hp x hx.1)) lemma point_to_point_zero_locus_le (I : ideal (mv_polynomial σ k)) : point_to_point '' (mv_polynomial.zero_locus I) ≤ prime_spectrum.zero_locus ↑I := λ J hJ, let ⟨x, hx⟩ := hJ in (le_trans (le_vanishing_ideal_zero_locus I) (hx.2 ▸ vanishing_ideal_anti_mono (set.singleton_subset_iff.2 hx.1)) : I ≤ J.as_ideal) variables [is_alg_closed k] [fintype σ] lemma is_maximal_iff_eq_vanishing_ideal_singleton (I : ideal (mv_polynomial σ k)) : I.is_maximal ↔ ∃ (x : σ → k), I = vanishing_ideal {x} := begin refine ⟨λ hI, _, λ h, let ⟨x, hx⟩ := h in hx.symm ▸ (mv_polynomial.vanishing_ideal_singleton_is_maximal)⟩, letI : I.is_maximal := hI, letI : field I.quotient := quotient.field I, let ϕ : k →+* I.quotient := (ideal.quotient.mk I).comp C, have hϕ : function.bijective ϕ := ⟨quotient_mk_comp_C_injective _ _ I hI.ne_top, is_alg_closed.algebra_map_surjective_of_is_integral' ϕ (mv_polynomial.comp_C_integral_of_surjective_of_jacobson _ quotient.mk_surjective)⟩, obtain ⟨φ, hφ⟩ := function.surjective.has_right_inverse hϕ.2, let x : σ → k := λ s, φ ((ideal.quotient.mk I) (X s)), have hx : ∀ s : σ, ϕ (x s) = (ideal.quotient.mk I) (X s) := λ s, hφ ((ideal.quotient.mk I) (X s)), refine ⟨x, (is_maximal.eq_of_le (by apply_instance) hI.ne_top _).symm⟩, intros p hp, rw [← quotient.eq_zero_iff_mem, map_mv_polynomial_eq_eval₂ (ideal.quotient.mk I) p, eval₂_eq'], rw [mem_vanishing_ideal_singleton_iff, eval_eq'] at hp, convert (trans (congr_arg ϕ hp) ϕ.map_zero), simp only [ϕ.map_sum, ϕ.map_mul, ϕ.map_prod, ϕ.map_pow, hx], end /-- Main statement of the Nullstellensatz -/ @[simp] theorem vanishing_ideal_zero_locus_eq_radical (I : ideal (mv_polynomial σ k)) : vanishing_ideal (zero_locus I) = I.radical := begin rw I.radical_eq_jacobson, refine le_antisymm (le_Inf _) (λ p hp x hx, _), { rintros J ⟨hJI, hJ⟩, obtain ⟨x, hx⟩ := (is_maximal_iff_eq_vanishing_ideal_singleton J).1 hJ, refine hx.symm ▸ vanishing_ideal_anti_mono (λ y hy p hp, _), rw [← mem_vanishing_ideal_singleton_iff, set.mem_singleton_iff.1 hy, ← hx], refine hJI hp }, { rw ← mem_vanishing_ideal_singleton_iff x p, refine (mem_Inf.mp hp) ⟨le_trans (le_vanishing_ideal_zero_locus I) (vanishing_ideal_anti_mono (λ y hy, hy.symm ▸ hx)), mv_polynomial.vanishing_ideal_singleton_is_maximal⟩ }, end @[simp] lemma is_prime.vanishing_ideal_zero_locus (P : ideal (mv_polynomial σ k)) [h : P.is_prime] : vanishing_ideal (zero_locus P) = P := trans (vanishing_ideal_zero_locus_eq_radical P) h.radical end mv_polynomial
1a2569165095593f62a191ee6895d8296668bf3f
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/src/Lean/Elab/Tactic/Injection.lean
0e79fedcd99de7035e1ad6ccc4b16a727124e6c8
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
1,200
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Tactic.Injection import Lean.Elab.Tactic.ElabTerm namespace Lean.Elab.Tactic -- optional (" with " >> many1 ident') private def getInjectionNewIds (stx : Syntax) : List Name := if stx.isNone then [] else stx[1].getArgs.toList.map getNameOfIdent' private def checkUnusedIds (mvarId : MVarId) (unusedIds : List Name) : MetaM Unit := unless unusedIds.isEmpty do Meta.throwTacticEx `injection mvarId m!"too many identifiers provided, unused: {unusedIds}" @[builtinTactic «injection»] def evalInjection : Tactic := fun stx => do -- leading_parser nonReservedSymbol "injection " >> termParser >> withIds let fvarId ← elabAsFVar stx[1] let ids := getInjectionNewIds stx[2] liftMetaTactic fun mvarId => do match ← Meta.injection mvarId fvarId ids (!ids.isEmpty) with | Meta.InjectionResult.solved => checkUnusedIds mvarId ids; pure [] | Meta.InjectionResult.subgoal mvarId' _ unusedIds => checkUnusedIds mvarId unusedIds; pure [mvarId'] end Lean.Elab.Tactic
881c8b03208d443784bb8d5a86da09fdb06e51f4
07c6143268cfb72beccd1cc35735d424ebcb187b
/src/analysis/calculus/fderiv.lean
41d485bfcf5c9039c0f0ef9adf66d4de0bb71bc2
[ "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
93,951
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 analysis.calculus.tangent_cone /-! # The Fréchet derivative Let `E` and `F` be normed spaces, `f : E → F`, and `f' : E →L[𝕜] F` a continuous 𝕜-linear map, where `𝕜` is a non-discrete normed field. Then `has_fderiv_within_at f f' s x` says that `f` has derivative `f'` at `x`, where the domain of interest is restricted to `s`. We also have `has_fderiv_at f f' x := has_fderiv_within_at f f' x univ` Finally, `has_strict_fderiv_at f f' x` means that `f : E → F` has derivative `f' : E →L[𝕜] F` in the sense of strict differentiability, i.e., `f y - f z - f'(y - z) = o(y - z)` as `y, z → x`. This notion is used in the inverse function theorem, and is defined here only to avoid proving theorems like `is_bounded_bilinear_map.has_fderiv_at` twice: first for `has_fderiv_at`, then for `has_strict_fderiv_at`. ## Main results In addition to the definition and basic properties of the derivative, this file contains the usual formulas (and existence assertions) for the derivative of * constants * the identity * bounded linear maps * bounded bilinear maps * sum of two functions * 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) 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.complex.exponential`. The simplifier is not set up to compute the Fréchet derivative of maps (as these are in general complicated multidimensional linear maps), but it will compute one-dimensional derivatives, see `deriv.lean`. ## Implementation details The derivative is defined in terms of the `is_o` relation, but also characterized in terms of the `tendsto` relation. We also introduce predicates `differentiable_within_at 𝕜 f s x` (where `𝕜` is the base field, `f` the function to be differentiated, `x` the point at which the derivative is asserted to exist, and `s` the set along which the derivative is defined), as well as `differentiable_at 𝕜 f x`, `differentiable_on 𝕜 f s` and `differentiable 𝕜 f` to express the existence of a derivative. To be able to compute with derivatives, we write `fderiv_within 𝕜 f s x` and `fderiv 𝕜 f x` for some choice of a derivative if it exists, and the zero function otherwise. This choice only behaves well along sets for which the derivative is unique, i.e., those for which the tangent directions span a dense subset of the whole space. The predicates `unique_diff_within_at s x` and `unique_diff_on s`, defined in `tangent_cone.lean` express this property. We prove that indeed they imply the uniqueness of the derivative. This is satisfied for open subsets, and in particular for `univ`. This uniqueness only holds when the field is non-discrete, which we request at the very beginning: otherwise, a derivative can be defined, but it has no interesting properties whatsoever. To make sure that the simplifier can prove automatically that functions are differentiable, we tag many lemmas with the `simp` attribute, for instance those saying that the sum of differentiable functions is differentiable, as well as their product, their cartesian product, and so on. A notable exception is the chain rule: we do not mark as a simp lemma the fact that, if `f` and `g` are differentiable, then their composition also is: `simp` would always be able to match this lemma, by taking `f` or `g` to be the identity. Instead, for every reasonable function (say, `exp`), we add a lemma that if `f` is differentiable then so is `(λ x, exp (f x))`. This means adding some boilerplate lemmas, but these can also be useful in their own right. Tests for this ability of the simplifier (with more examples) are provided in `tests/differentiable.lean`. ## Tags derivative, differentiable, Fréchet, calculus -/ open filter asymptotics continuous_linear_map set open_locale topological_space classical noncomputable theory set_option class.instance_max_depth 90 section variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] variables {G : Type*} [normed_group G] [normed_space 𝕜 G] variables {G' : Type*} [normed_group G'] [normed_space 𝕜 G'] /-- A function `f` has the continuous linear map `f'` as derivative along the filter `L` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` converges along the filter `L`. This definition is designed to be specialized for `L = 𝓝 x` (in `has_fderiv_at`), giving rise to the usual notion of Fréchet derivative, and for `L = nhds_within x s` (in `has_fderiv_within_at`), giving rise to the notion of Fréchet derivative along the set `s`. -/ def has_fderiv_at_filter (f : E → F) (f' : E →L[𝕜] F) (x : E) (L : filter E) := is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L /-- A function `f` has the continuous linear map `f'` as derivative at `x` within a set `s` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` tends to `x` inside `s`. -/ def has_fderiv_within_at (f : E → F) (f' : E →L[𝕜] F) (s : set E) (x : E) := has_fderiv_at_filter f f' x (nhds_within x s) /-- A function `f` has the continuous linear map `f'` as derivative at `x` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` tends to `x`. -/ def has_fderiv_at (f : E → F) (f' : E →L[𝕜] F) (x : E) := has_fderiv_at_filter f f' x (𝓝 x) /-- A function `f` has derivative `f'` at `a` in the sense of *strict differentiability* if `f x - f y - f' (x - y) = o(x - y)` as `x, y → a`. This form of differentiability is required, e.g., by the inverse function theorem. Any `C^1` function on a vector space over `ℝ` is strictly differentiable but this definition works, e.g., for vector spaces over `p`-adic numbers. -/ def has_strict_fderiv_at (f : E → F) (f' : E →L[𝕜] F) (x : E) := is_o (λ p : E × E, f p.1 - f p.2 - f' (p.1 - p.2)) (λ p : E × E, p.1 - p.2) (𝓝 (x, x)) variables (𝕜) /-- A function `f` is differentiable at a point `x` within a set `s` if it admits a derivative there (possibly non-unique). -/ def differentiable_within_at (f : E → F) (s : set E) (x : E) := ∃f' : E →L[𝕜] F, has_fderiv_within_at f f' s x /-- A function `f` is differentiable at a point `x` if it admits a derivative there (possibly non-unique). -/ def differentiable_at (f : E → F) (x : E) := ∃f' : E →L[𝕜] F, has_fderiv_at f f' x /-- If `f` has a derivative at `x` within `s`, then `fderiv_within 𝕜 f s x` is such a derivative. Otherwise, it is set to `0`. -/ def fderiv_within (f : E → F) (s : set E) (x : E) : E →L[𝕜] F := if h : ∃f', has_fderiv_within_at f f' s x then classical.some h else 0 /-- If `f` has a derivative at `x`, then `fderiv 𝕜 f x` is such a derivative. Otherwise, it is set to `0`. -/ def fderiv (f : E → F) (x : E) : E →L[𝕜] F := if h : ∃f', has_fderiv_at f f' x then classical.some h else 0 /-- `differentiable_on 𝕜 f s` means that `f` is differentiable within `s` at any point of `s`. -/ def differentiable_on (f : E → F) (s : set E) := ∀x ∈ s, differentiable_within_at 𝕜 f s x /-- `differentiable 𝕜 f` means that `f` is differentiable at any point. -/ def differentiable (f : E → F) := ∀x, differentiable_at 𝕜 f x variables {𝕜} variables {f f₀ f₁ g : E → F} variables {f' f₀' f₁' g' : E →L[𝕜] F} variables (e : E →L[𝕜] F) variables {x : E} variables {s t : set E} variables {L L₁ L₂ : filter E} lemma fderiv_within_zero_of_not_differentiable_within_at (h : ¬ differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 f s x = 0 := have ¬ ∃ f', has_fderiv_within_at f f' s x, from h, by simp [fderiv_within, this] lemma fderiv_zero_of_not_differentiable_at (h : ¬ differentiable_at 𝕜 f x) : fderiv 𝕜 f x = 0 := have ¬ ∃ f', has_fderiv_at f f' x, from h, by simp [fderiv, this] section derivative_uniqueness /- In this section, we discuss the uniqueness of the derivative. We prove that the definitions `unique_diff_within_at` and `unique_diff_on` indeed imply the uniqueness of the derivative. -/ /-- If a function f has a derivative f' at x, a rescaled version of f around x converges to f', i.e., `n (f (x + (1/n) v) - f x)` converges to `f' v`. More generally, if `c n` tends to infinity and `c n * d n` tends to `v`, then `c n * (f (x + d n) - f x)` tends to `f' v`. This lemma expresses this fact, for functions having a derivative within a set. Its specific formulation is useful for tangent cone related discussions. -/ theorem has_fderiv_within_at.lim (h : has_fderiv_within_at f f' s x) {α : Type*} (l : filter α) {c : α → 𝕜} {d : α → E} {v : E} (dtop : ∀ᶠ n in l, x + d n ∈ s) (clim : tendsto (λ n, ∥c n∥) l at_top) (cdlim : tendsto (λ n, c n • d n) l (𝓝 v)) : tendsto (λn, c n • (f (x + d n) - f x)) l (𝓝 (f' v)) := begin have tendsto_arg : tendsto (λ n, x + d n) l (nhds_within x s), { conv in (nhds_within x s) { rw ← add_zero x }, rw [nhds_within, tendsto_inf], split, { apply tendsto_const_nhds.add (tangent_cone_at.lim_zero l clim cdlim) }, { rwa tendsto_principal } }, have : is_o (λ y, f y - f x - f' (y - x)) (λ y, y - x) (nhds_within x s) := h, have : is_o (λ n, f (x + d n) - f x - f' ((x + d n) - x)) (λ n, (x + d n) - x) l := this.comp_tendsto tendsto_arg, have : is_o (λ n, f (x + d n) - f x - f' (d n)) d l := by simpa only [add_sub_cancel'], have : is_o (λn, c n • (f (x + d n) - f x - f' (d n))) (λn, c n • d n) l := (is_O_refl c l).smul_is_o this, have : is_o (λn, c n • (f (x + d n) - f x - f' (d n))) (λn, (1:ℝ)) l := this.trans_is_O (is_O_one_of_tendsto ℝ cdlim), have L1 : tendsto (λn, c n • (f (x + d n) - f x - f' (d n))) l (𝓝 0) := (is_o_one_iff ℝ).1 this, have L2 : tendsto (λn, f' (c n • d n)) l (𝓝 (f' v)) := tendsto.comp f'.cont.continuous_at cdlim, have L3 : tendsto (λn, (c n • (f (x + d n) - f x - f' (d n)) + f' (c n • d n))) l (𝓝 (0 + f' v)) := L1.add L2, have : (λn, (c n • (f (x + d n) - f x - f' (d n)) + f' (c n • d n))) = (λn, c n • (f (x + d n) - f x)), by { ext n, simp [smul_add, smul_sub] }, rwa [this, zero_add] at L3 end /-- `unique_diff_within_at` achieves its goal: it implies the uniqueness of the derivative. -/ theorem unique_diff_within_at.eq (H : unique_diff_within_at 𝕜 s x) (h : has_fderiv_within_at f f' s x) (h₁ : has_fderiv_within_at f f₁' s x) : f' = f₁' := begin have A : ∀y ∈ tangent_cone_at 𝕜 s x, f' y = f₁' y, { rintros y ⟨c, d, dtop, clim, cdlim⟩, exact tendsto_nhds_unique (by simp) (h.lim at_top dtop clim cdlim) (h₁.lim at_top dtop clim cdlim) }, have B : ∀y ∈ submodule.span 𝕜 (tangent_cone_at 𝕜 s x), f' y = f₁' y, { assume y hy, apply submodule.span_induction hy, { exact λy hy, A y hy }, { simp only [continuous_linear_map.map_zero] }, { simp {contextual := tt} }, { simp {contextual := tt} } }, have C : ∀y ∈ closure ((submodule.span 𝕜 (tangent_cone_at 𝕜 s x)) : set E), f' y = f₁' y, { assume y hy, let K := {y | f' y = f₁' y}, have : (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E) ⊆ K := B, have : closure (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E) ⊆ closure K := closure_mono this, have : y ∈ closure K := this hy, rwa closure_eq_of_is_closed (is_closed_eq f'.continuous f₁'.continuous) at this }, rw H.1 at C, ext y, exact C y (mem_univ _) end theorem unique_diff_on.eq (H : unique_diff_on 𝕜 s) (hx : x ∈ s) (h : has_fderiv_within_at f f' s x) (h₁ : has_fderiv_within_at f f₁' s x) : f' = f₁' := unique_diff_within_at.eq (H x hx) h h₁ end derivative_uniqueness section fderiv_properties /-! ### Basic properties of the derivative -/ theorem has_fderiv_at_filter_iff_tendsto : has_fderiv_at_filter f f' x L ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (𝓝 0) := have h : ∀ x', ∥x' - x∥ = 0 → ∥f x' - f x - f' (x' - x)∥ = 0, from λ x' hx', by { rw [sub_eq_zero.1 (norm_eq_zero.1 hx')], simp }, begin unfold has_fderiv_at_filter, rw [←is_o_norm_left, ←is_o_norm_right, is_o_iff_tendsto h], exact tendsto_congr (λ _, div_eq_inv_mul'), end theorem has_fderiv_within_at_iff_tendsto : has_fderiv_within_at f f' s x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) (nhds_within x s) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_fderiv_at_iff_tendsto : has_fderiv_at f f' x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) (𝓝 x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_fderiv_at_iff_is_o_nhds_zero : has_fderiv_at f f' x ↔ is_o (λh, f (x + h) - f x - f' h) (λh, h) (𝓝 0) := begin split, { assume H, have : tendsto (λ (z : E), z + x) (𝓝 0) (𝓝 (0 + x)), from tendsto_id.add tendsto_const_nhds, rw [zero_add] at this, refine (H.comp_tendsto this).congr _ _; intro z; simp only [function.comp, add_sub_cancel', add_comm z] }, { assume H, have : tendsto (λ (z : E), z - x) (𝓝 x) (𝓝 (x - x)), from tendsto_id.sub tendsto_const_nhds, rw [sub_self] at this, refine (H.comp_tendsto this).congr _ _; intro z; simp only [function.comp, add_sub_cancel'_right] } end theorem has_fderiv_at_filter.mono (h : has_fderiv_at_filter f f' x L₂) (hst : L₁ ≤ L₂) : has_fderiv_at_filter f f' x L₁ := h.mono hst theorem has_fderiv_within_at.mono (h : has_fderiv_within_at f f' t x) (hst : s ⊆ t) : has_fderiv_within_at f f' s x := h.mono (nhds_within_mono _ hst) theorem has_fderiv_at.has_fderiv_at_filter (h : has_fderiv_at f f' x) (hL : L ≤ 𝓝 x) : has_fderiv_at_filter f f' x L := h.mono hL theorem has_fderiv_at.has_fderiv_within_at (h : has_fderiv_at f f' x) : has_fderiv_within_at f f' s x := h.has_fderiv_at_filter inf_le_left lemma has_fderiv_within_at.differentiable_within_at (h : has_fderiv_within_at f f' s x) : differentiable_within_at 𝕜 f s x := ⟨f', h⟩ lemma has_fderiv_at.differentiable_at (h : has_fderiv_at f f' x) : differentiable_at 𝕜 f x := ⟨f', h⟩ @[simp] lemma has_fderiv_within_at_univ : has_fderiv_within_at f f' univ x ↔ has_fderiv_at f f' x := by { simp only [has_fderiv_within_at, nhds_within_univ], refl } lemma has_strict_fderiv_at.is_O_sub (hf : has_strict_fderiv_at f f' x) : is_O (λ p : E × E, f p.1 - f p.2) (λ p : E × E, p.1 - p.2) (𝓝 (x, x)) := hf.is_O.congr_of_sub.2 (f'.is_O_comp _ _) lemma has_fderiv_at_filter.is_O_sub (h : has_fderiv_at_filter f f' x L) : is_O (λ x', f x' - f x) (λ x', x' - x) L := h.is_O.congr_of_sub.2 (f'.is_O_sub _ _) 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 lemma has_strict_fderiv_at.differentiable_at (hf : has_strict_fderiv_at f f' x) : differentiable_at 𝕜 f x := hf.has_fderiv_at.differentiable_at /-- Directional derivative agrees with `has_fderiv`. -/ lemma has_fderiv_at.lim (hf : has_fderiv_at f f' x) (v : E) {α : Type*} {c : α → 𝕜} {l : filter α} (hc : tendsto (λ n, ∥c n∥) l at_top) : tendsto (λ n, (c n) • (f (x + (c n)⁻¹ • v) - f x)) l (𝓝 (f' v)) := begin refine (has_fderiv_within_at_univ.2 hf).lim _ (univ_mem_sets' (λ _, trivial)) hc _, assume U hU, refine (eventually_ne_of_tendsto_norm_at_top hc (0:𝕜)).mono (λ y hy, _), convert mem_of_nhds hU, dsimp only [], rw [← mul_smul, mul_inv_cancel hy, one_smul] end theorem has_fderiv_at_unique (h₀ : has_fderiv_at f f₀' x) (h₁ : has_fderiv_at f f₁' x) : f₀' = f₁' := begin rw ← has_fderiv_within_at_univ at h₀ h₁, exact unique_diff_within_at_univ.eq h₀ h₁ end lemma has_fderiv_within_at_inter' (h : t ∈ nhds_within x s) : has_fderiv_within_at f f' (s ∩ t) x ↔ has_fderiv_within_at f f' s x := by simp [has_fderiv_within_at, nhds_within_restrict'' s h] lemma has_fderiv_within_at_inter (h : t ∈ 𝓝 x) : has_fderiv_within_at f f' (s ∩ t) x ↔ has_fderiv_within_at f f' s x := by simp [has_fderiv_within_at, nhds_within_restrict' s h] lemma has_fderiv_within_at.union (hs : has_fderiv_within_at f f' s x) (ht : has_fderiv_within_at f f' t x) : has_fderiv_within_at f f' (s ∪ t) x := begin simp only [has_fderiv_within_at, nhds_within_union], exact hs.join ht, end lemma has_fderiv_within_at.nhds_within (h : has_fderiv_within_at f f' s x) (ht : s ∈ nhds_within x t) : has_fderiv_within_at f f' t x := (has_fderiv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _)) lemma has_fderiv_within_at.has_fderiv_at (h : has_fderiv_within_at f f' s x) (hs : s ∈ 𝓝 x) : has_fderiv_at f f' x := by rwa [← univ_inter s, has_fderiv_within_at_inter hs, has_fderiv_within_at_univ] at h lemma differentiable_within_at.has_fderiv_within_at (h : differentiable_within_at 𝕜 f s x) : has_fderiv_within_at f (fderiv_within 𝕜 f s x) s x := begin dunfold fderiv_within, dunfold differentiable_within_at at h, rw dif_pos h, exact classical.some_spec h end lemma differentiable_at.has_fderiv_at (h : differentiable_at 𝕜 f x) : has_fderiv_at f (fderiv 𝕜 f x) x := begin dunfold fderiv, dunfold differentiable_at at h, rw dif_pos h, exact classical.some_spec h end lemma has_fderiv_at.fderiv (h : has_fderiv_at f f' x) : fderiv 𝕜 f x = f' := by { ext, rw has_fderiv_at_unique h h.differentiable_at.has_fderiv_at } lemma has_fderiv_within_at.fderiv_within (h : has_fderiv_within_at f f' s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = f' := (hxs.eq h h.differentiable_within_at.has_fderiv_within_at).symm /-- If `x` is not in the closure of `s`, then `f` has any derivative at `x` within `s`, as this statement is empty. -/ lemma has_fderiv_within_at_of_not_mem_closure (h : x ∉ closure s) : has_fderiv_within_at f f' s x := begin simp [mem_closure_iff_nhds_within_ne_bot] at h, simp [has_fderiv_within_at, has_fderiv_at_filter, h, is_o, is_O_with], end lemma differentiable_within_at.mono (h : differentiable_within_at 𝕜 f t x) (st : s ⊆ t) : differentiable_within_at 𝕜 f s x := begin rcases h with ⟨f', hf'⟩, exact ⟨f', hf'.mono st⟩ end lemma differentiable_within_at_univ : differentiable_within_at 𝕜 f univ x ↔ differentiable_at 𝕜 f x := by simp only [differentiable_within_at, has_fderiv_within_at_univ, differentiable_at] lemma differentiable_within_at_inter (ht : t ∈ 𝓝 x) : differentiable_within_at 𝕜 f (s ∩ t) x ↔ differentiable_within_at 𝕜 f s x := by simp only [differentiable_within_at, has_fderiv_within_at, has_fderiv_at_filter, nhds_within_restrict' s ht] lemma differentiable_within_at_inter' (ht : t ∈ nhds_within x s) : differentiable_within_at 𝕜 f (s ∩ t) x ↔ differentiable_within_at 𝕜 f s x := by simp only [differentiable_within_at, has_fderiv_within_at, has_fderiv_at_filter, nhds_within_restrict'' s ht] lemma differentiable_at.differentiable_within_at (h : differentiable_at 𝕜 f x) : differentiable_within_at 𝕜 f s x := (differentiable_within_at_univ.2 h).mono (subset_univ _) lemma differentiable.differentiable_at (h : differentiable 𝕜 f) : differentiable_at 𝕜 f x := h x lemma differentiable_within_at.differentiable_at (h : differentiable_within_at 𝕜 f s x) (hs : s ∈ 𝓝 x) : differentiable_at 𝕜 f x := h.imp (λ f' hf', hf'.has_fderiv_at hs) lemma differentiable_at.fderiv_within (h : differentiable_at 𝕜 f x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = fderiv 𝕜 f x := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact h.has_fderiv_at.has_fderiv_within_at end lemma differentiable_on.mono (h : differentiable_on 𝕜 f t) (st : s ⊆ t) : differentiable_on 𝕜 f s := λx hx, (h x (st hx)).mono st lemma differentiable_on_univ : differentiable_on 𝕜 f univ ↔ differentiable 𝕜 f := by { simp [differentiable_on, differentiable_within_at_univ], refl } lemma differentiable.differentiable_on (h : differentiable 𝕜 f) : differentiable_on 𝕜 f s := (differentiable_on_univ.2 h).mono (subset_univ _) lemma differentiable_on_of_locally_differentiable_on (h : ∀x∈s, ∃u, is_open u ∧ x ∈ u ∧ differentiable_on 𝕜 f (s ∩ u)) : differentiable_on 𝕜 f s := begin assume x xs, rcases h x xs with ⟨t, t_open, xt, ht⟩, exact (differentiable_within_at_inter (mem_nhds_sets t_open xt)).1 (ht x ⟨xs, xt⟩) end lemma fderiv_within_subset (st : s ⊆ t) (ht : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f t x) : fderiv_within 𝕜 f s x = fderiv_within 𝕜 f t x := ((differentiable_within_at.has_fderiv_within_at h).mono st).fderiv_within ht @[simp] lemma fderiv_within_univ : fderiv_within 𝕜 f univ = fderiv 𝕜 f := begin ext x : 1, by_cases h : differentiable_at 𝕜 f x, { apply has_fderiv_within_at.fderiv_within _ unique_diff_within_at_univ, rw has_fderiv_within_at_univ, apply h.has_fderiv_at }, { have : ¬ differentiable_within_at 𝕜 f univ x, by contrapose! h; rwa ← differentiable_within_at_univ, rw [fderiv_zero_of_not_differentiable_at h, fderiv_within_zero_of_not_differentiable_within_at this] } end lemma fderiv_within_inter (ht : t ∈ 𝓝 x) (hs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f (s ∩ t) x = fderiv_within 𝕜 f s x := begin by_cases h : differentiable_within_at 𝕜 f (s ∩ t) x, { apply fderiv_within_subset (inter_subset_left _ _) _ ((differentiable_within_at_inter ht).1 h), apply hs.inter ht }, { have : ¬ differentiable_within_at 𝕜 f s x, by contrapose! h; rw differentiable_within_at_inter; assumption, rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at this] } end end fderiv_properties section continuous /-! ### Deducing continuity from differentiability -/ theorem has_fderiv_at_filter.tendsto_nhds (hL : L ≤ 𝓝 x) (h : has_fderiv_at_filter f f' x L) : tendsto f L (𝓝 (f x)) := begin have : tendsto (λ x', f x' - f x) L (𝓝 0), { refine h.is_O_sub.trans_tendsto (tendsto_le_left hL _), rw ← sub_self x, exact tendsto_id.sub tendsto_const_nhds }, have := tendsto.add this tendsto_const_nhds, rw zero_add (f x) at this, exact this.congr (by simp) end theorem has_fderiv_within_at.continuous_within_at (h : has_fderiv_within_at f f' s x) : continuous_within_at f s x := has_fderiv_at_filter.tendsto_nhds inf_le_left h theorem has_fderiv_at.continuous_at (h : has_fderiv_at f f' x) : continuous_at f x := has_fderiv_at_filter.tendsto_nhds (le_refl _) h lemma differentiable_within_at.continuous_within_at (h : differentiable_within_at 𝕜 f s x) : continuous_within_at f s x := let ⟨f', hf'⟩ := h in hf'.continuous_within_at lemma differentiable_at.continuous_at (h : differentiable_at 𝕜 f x) : continuous_at f x := let ⟨f', hf'⟩ := h in hf'.continuous_at lemma differentiable_on.continuous_on (h : differentiable_on 𝕜 f s) : continuous_on f s := λx hx, (h x hx).continuous_within_at lemma differentiable.continuous (h : differentiable 𝕜 f) : continuous f := continuous_iff_continuous_at.2 $ λx, (h x).continuous_at 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 end continuous section congr /-! ### congr properties of the derivative -/ theorem has_strict_fderiv_at_congr_of_mem_sets (h : ∀ᶠ y in 𝓝 x, f₀ y = f₁ y) (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_fderiv_at_filter_congr_of_mem_sets (hx : f₀ x = f₁ x) (h₀ : ∀ᶠ x in L, 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_mem_sets (h : has_fderiv_at_filter f f' x L) (hL : ∀ᶠ x in L, f₁ x = f x) (hx : f₁ x = f x) : has_fderiv_at_filter f₁ f' x L := (has_fderiv_at_filter_congr_of_mem_sets hx hL $ λ _, rfl).2 h lemma has_fderiv_within_at.congr_mono (h : has_fderiv_within_at f f' s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : has_fderiv_within_at f₁ f' t x := has_fderiv_at_filter.congr_of_mem_sets (h.mono h₁) (filter.mem_inf_sets_of_right ht) hx lemma has_fderiv_within_at.congr (h : has_fderiv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : has_fderiv_within_at f₁ f' s x := h.congr_mono hs hx (subset.refl _) lemma has_fderiv_within_at.congr_of_mem_nhds_within (h : has_fderiv_within_at f f' s x) (h₁ : ∀ᶠ y in nhds_within x s, f₁ y = f y) (hx : f₁ x = f x) : has_fderiv_within_at f₁ f' s x := has_fderiv_at_filter.congr_of_mem_sets h h₁ hx lemma has_fderiv_at.congr_of_mem_nhds (h : has_fderiv_at f f' x) (h₁ : ∀ᶠ y in 𝓝 x, f₁ y = f y) : has_fderiv_at f₁ f' x := has_fderiv_at_filter.congr_of_mem_sets h h₁ (mem_of_nhds h₁ : _) lemma differentiable_within_at.congr_mono (h : differentiable_within_at 𝕜 f s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : differentiable_within_at 𝕜 f₁ t x := (has_fderiv_within_at.congr_mono h.has_fderiv_within_at ht hx h₁).differentiable_within_at lemma differentiable_within_at.congr (h : differentiable_within_at 𝕜 f s x) (ht : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : differentiable_within_at 𝕜 f₁ s x := differentiable_within_at.congr_mono h ht hx (subset.refl _) lemma differentiable_within_at.congr_of_mem_nhds_within (h : differentiable_within_at 𝕜 f s x) (h₁ : ∀ᶠ y in nhds_within x s, f₁ y = f y) (hx : f₁ x = f x) : differentiable_within_at 𝕜 f₁ s x := (h.has_fderiv_within_at.congr_of_mem_nhds_within 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_mem_nhds (h : differentiable_at 𝕜 f x) (hL : ∀ᶠ y in 𝓝 x, f₁ y = f y) : differentiable_at 𝕜 f₁ x := has_fderiv_at.differentiable_at (has_fderiv_at_filter.congr_of_mem_sets h.has_fderiv_at hL (mem_of_nhds hL : _)) lemma differentiable_within_at.fderiv_within_congr_mono (h : differentiable_within_at 𝕜 f s x) (hs : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (hxt : unique_diff_within_at 𝕜 t x) (h₁ : t ⊆ s) : fderiv_within 𝕜 f₁ t x = fderiv_within 𝕜 f s x := (has_fderiv_within_at.congr_mono h.has_fderiv_within_at hs hx h₁).fderiv_within hxt lemma fderiv_within_congr_of_mem_nhds_within (hs : unique_diff_within_at 𝕜 s x) (hL : ∀ᶠ y in nhds_within x s, f₁ y = f y) (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_mem_sets hL hx) hs else have h' : ¬ differentiable_within_at 𝕜 f₁ s x, from mt (λ h, h.congr_of_mem_nhds_within (hL.mono $ λ x, eq.symm) hx.symm) h, by rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at h'] lemma fderiv_within_congr (hs : unique_diff_within_at 𝕜 s x) (hL : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) : fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x := begin apply fderiv_within_congr_of_mem_nhds_within hs _ hx, apply mem_sets_of_superset self_mem_nhds_within, exact hL end lemma fderiv_congr_of_mem_nhds (hL : ∀ᶠ y in 𝓝 x, f₁ y = f y) : fderiv 𝕜 f₁ x = fderiv 𝕜 f x := begin have A : f₁ x = f x := (mem_of_nhds hL : _), rw [← fderiv_within_univ, ← fderiv_within_univ], rw ← nhds_within_univ at hL, exact fderiv_within_congr_of_mem_nhds_within unique_diff_within_at_univ hL A end end congr section id /-! ### Derivative of the identity -/ theorem has_strict_fderiv_at_id (x : E) : has_strict_fderiv_at id (id : E →L[𝕜] 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 →L[𝕜] 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 →L[𝕜] E) s x := has_fderiv_at_filter_id _ _ theorem has_fderiv_at_id (x : E) : has_fderiv_at id (id : E →L[𝕜] 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 := has_fderiv_at.fderiv (has_fderiv_at_id x) lemma fderiv_within_id (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 id s x = id := begin rw differentiable_at.fderiv_within (differentiable_at_id) hxs, exact fderiv_id end end id section const /-! ### derivative of a constant function -/ theorem has_strict_fderiv_at_const (c : F) (x : E) : has_strict_fderiv_at (λ _, c) (0 : E →L[𝕜] F) x := (is_o_zero _ _).congr_left $ λ _, by simp only [zero_apply, sub_self] theorem has_fderiv_at_filter_const (c : F) (x : E) (L : filter E) : has_fderiv_at_filter (λ x, c) (0 : E →L[𝕜] F) x L := (is_o_zero _ _).congr_left $ λ _, by simp only [zero_apply, sub_self] theorem has_fderiv_within_at_const (c : F) (x : E) (s : set E) : has_fderiv_within_at (λ x, c) (0 : E →L[𝕜] F) s x := has_fderiv_at_filter_const _ _ _ theorem has_fderiv_at_const (c : F) (x : E) : has_fderiv_at (λ x, c) (0 : E →L[𝕜] F) x := has_fderiv_at_filter_const _ _ _ @[simp] lemma differentiable_at_const (c : F) : differentiable_at 𝕜 (λx, c) x := ⟨0, has_fderiv_at_const c x⟩ lemma differentiable_within_at_const (c : F) : differentiable_within_at 𝕜 (λx, c) s x := differentiable_at.differentiable_within_at (differentiable_at_const _) lemma fderiv_const_apply (c : F) : fderiv 𝕜 (λy, c) x = 0 := has_fderiv_at.fderiv (has_fderiv_at_const c x) lemma fderiv_const (c : F) : fderiv 𝕜 (λ (y : E), c) = 0 := by { ext m, rw fderiv_const_apply, refl } lemma fderiv_within_const_apply (c : F) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λy, c) s x = 0 := begin rw differentiable_at.fderiv_within (differentiable_at_const _) hxs, exact fderiv_const_apply _ end @[simp] lemma differentiable_const (c : F) : differentiable 𝕜 (λx : E, c) := λx, differentiable_at_const _ lemma differentiable_on_const (c : F) : differentiable_on 𝕜 (λx, c) s := (differentiable_const _).differentiable_on end const section continuous_linear_map /-! ### Continuous linear maps There are currently two variants of these in mathlib, the bundled version (named `continuous_linear_map`, and denoted `E →L[𝕜] F`), and the unbundled version (with a predicate `is_bounded_linear_map`). We give statements for both versions. -/ protected theorem continuous_linear_map.has_strict_fderiv_at {x : E} : has_strict_fderiv_at e e x := (is_o_zero _ _).congr_left $ λ x, by simp only [e.map_sub, sub_self] protected lemma continuous_linear_map.has_fderiv_at_filter : has_fderiv_at_filter e e x L := (is_o_zero _ _).congr_left $ λ x, by simp only [e.map_sub, sub_self] protected lemma continuous_linear_map.has_fderiv_within_at : has_fderiv_within_at e e s x := e.has_fderiv_at_filter protected lemma continuous_linear_map.has_fderiv_at : has_fderiv_at e e x := e.has_fderiv_at_filter @[simp] protected lemma continuous_linear_map.differentiable_at : differentiable_at 𝕜 e x := e.has_fderiv_at.differentiable_at protected lemma continuous_linear_map.differentiable_within_at : differentiable_within_at 𝕜 e s x := e.differentiable_at.differentiable_within_at protected lemma continuous_linear_map.fderiv : fderiv 𝕜 e x = e := e.has_fderiv_at.fderiv protected lemma continuous_linear_map.fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 e s x = e := begin rw differentiable_at.fderiv_within e.differentiable_at hxs, exact e.fderiv end @[simp]protected lemma continuous_linear_map.differentiable : differentiable 𝕜 e := λx, e.differentiable_at protected lemma continuous_linear_map.differentiable_on : differentiable_on 𝕜 e s := e.differentiable.differentiable_on lemma is_bounded_linear_map.has_fderiv_at_filter (h : is_bounded_linear_map 𝕜 f) : has_fderiv_at_filter f h.to_continuous_linear_map x L := h.to_continuous_linear_map.has_fderiv_at_filter lemma is_bounded_linear_map.has_fderiv_within_at (h : is_bounded_linear_map 𝕜 f) : has_fderiv_within_at f h.to_continuous_linear_map s x := h.has_fderiv_at_filter lemma is_bounded_linear_map.has_fderiv_at (h : is_bounded_linear_map 𝕜 f) : has_fderiv_at f h.to_continuous_linear_map x := h.has_fderiv_at_filter lemma is_bounded_linear_map.differentiable_at (h : is_bounded_linear_map 𝕜 f) : differentiable_at 𝕜 f x := h.has_fderiv_at.differentiable_at lemma is_bounded_linear_map.differentiable_within_at (h : is_bounded_linear_map 𝕜 f) : differentiable_within_at 𝕜 f s x := h.differentiable_at.differentiable_within_at lemma is_bounded_linear_map.fderiv (h : is_bounded_linear_map 𝕜 f) : fderiv 𝕜 f x = h.to_continuous_linear_map := has_fderiv_at.fderiv (h.has_fderiv_at) lemma is_bounded_linear_map.fderiv_within (h : is_bounded_linear_map 𝕜 f) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = h.to_continuous_linear_map := begin rw differentiable_at.fderiv_within h.differentiable_at hxs, exact h.fderiv end lemma is_bounded_linear_map.differentiable (h : is_bounded_linear_map 𝕜 f) : differentiable 𝕜 f := λx, h.differentiable_at lemma is_bounded_linear_map.differentiable_on (h : is_bounded_linear_map 𝕜 f) : differentiable_on 𝕜 f s := h.differentiable.differentiable_on end continuous_linear_map section composition /-! ### Derivative of the composition of two functions For composition lemmas, we put x explicit to help the elaborator, as otherwise Lean tends to get confused since there are too many possibilities for composition -/ variable (x) theorem has_fderiv_at_filter.comp {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at_filter g g' (f x) (L.map f)) (hf : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (g ∘ f) (g'.comp f') x L := let eq₁ := (g'.is_O_comp _ _).trans_is_o hf in let eq₂ := (hg.comp_tendsto tendsto_map).trans_is_O hf.is_O_sub in by { refine eq₂.triangle (eq₁.congr_left (λ x', _)), simp } /- A readable version of the previous theorem, a general form of the chain rule. -/ example {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at_filter g g' (f x) (L.map f)) (hf : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (g ∘ f) (g'.comp f') x L := begin unfold has_fderiv_at_filter at hg, have : is_o (λ x', g (f x') - g (f x) - g' (f x' - f x)) (λ x', f x' - f x) L, from hg.comp_tendsto (le_refl _), have eq₁ : is_o (λ x', g (f x') - g (f x) - g' (f x' - f x)) (λ x', x' - x) L, from this.trans_is_O hf.is_O_sub, have eq₂ : is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L, from hf, have : is_O (λ x', g' (f x' - f x - f' (x' - x))) (λ x', f x' - f x - f' (x' - x)) L, from g'.is_O_comp _ _, have : is_o (λ x', g' (f x' - f x - f' (x' - x))) (λ x', x' - x) L, from this.trans_is_o eq₂, have eq₃ : is_o (λ x', g' (f x' - f x) - (g' (f' (x' - x)))) (λ x', x' - x) L, by { refine this.congr_left _, simp}, exact eq₁.triangle eq₃ end theorem has_fderiv_within_at.comp {g : F → G} {g' : F →L[𝕜] G} {t : set F} (hg : has_fderiv_within_at g g' t (f x)) (hf : has_fderiv_within_at f f' s x) (hst : s ⊆ f ⁻¹' t) : has_fderiv_within_at (g ∘ f) (g'.comp f') s x := begin apply has_fderiv_at_filter.comp _ (has_fderiv_at_filter.mono hg _) hf, calc map f (nhds_within x s) ≤ nhds_within (f x) (f '' s) : hf.continuous_within_at.tendsto_nhds_within_image ... ≤ nhds_within (f x) t : nhds_within_mono _ (image_subset_iff.mpr hst) end /-- The chain rule. -/ theorem has_fderiv_at.comp {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at g g' (f x)) (hf : has_fderiv_at f f' x) : has_fderiv_at (g ∘ f) (g'.comp f') x := (hg.mono hf.continuous_at).comp x hf theorem has_fderiv_at.comp_has_fderiv_within_at {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at g g' (f x)) (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (g ∘ f) (g'.comp f') s x := begin rw ← has_fderiv_within_at_univ at hg, exact has_fderiv_within_at.comp x hg hf subset_preimage_univ end lemma differentiable_within_at.comp {g : F → G} {t : set F} (hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) (h : s ⊆ f ⁻¹' t) : differentiable_within_at 𝕜 (g ∘ f) s x := begin rcases hf with ⟨f', hf'⟩, rcases hg with ⟨g', hg'⟩, exact ⟨continuous_linear_map.comp g' f', hg'.comp x hf' h⟩ end lemma differentiable_at.comp {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (g ∘ f) x := (hg.has_fderiv_at.comp x hf.has_fderiv_at).differentiable_at lemma differentiable_at.comp_differentiable_within_at {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (g ∘ f) s x := (differentiable_within_at_univ.2 hg).comp x hf (by simp) lemma fderiv_within.comp {g : F → G} {t : set F} (hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) (h : maps_to f s t) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (g ∘ f) s x = (fderiv_within 𝕜 g t (f x)).comp (fderiv_within 𝕜 f s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_within_at.comp x (hg.has_fderiv_within_at) (hf.has_fderiv_within_at) h end lemma fderiv.comp {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_at 𝕜 f x) : fderiv 𝕜 (g ∘ f) x = (fderiv 𝕜 g (f x)).comp (fderiv 𝕜 f x) := begin apply has_fderiv_at.fderiv, exact has_fderiv_at.comp x hg.has_fderiv_at hf.has_fderiv_at end lemma fderiv.comp_fderiv_within {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_within_at 𝕜 f s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (g ∘ f) s x = (fderiv 𝕜 g (f x)).comp (fderiv_within 𝕜 f s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_at.comp_has_fderiv_within_at x (hg.has_fderiv_at) (hf.has_fderiv_within_at) end lemma differentiable_on.comp {g : F → G} {t : set F} (hg : differentiable_on 𝕜 g t) (hf : differentiable_on 𝕜 f s) (st : s ⊆ f ⁻¹' t) : differentiable_on 𝕜 (g ∘ f) s := λx hx, differentiable_within_at.comp x (hg (f x) (st hx)) (hf x hx) st lemma differentiable.comp {g : F → G} (hg : differentiable 𝕜 g) (hf : differentiable 𝕜 f) : differentiable 𝕜 (g ∘ f) := λx, differentiable_at.comp x (hg (f x)) (hf x) lemma differentiable.comp_differentiable_on {g : F → G} (hg : differentiable 𝕜 g) (hf : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (g ∘ f) s := (differentiable_on_univ.2 hg).comp hf (by simp) /-- The chain rule for derivatives in the sense of strict differentiability. -/ 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 end composition section cartesian_product /-! ### Derivative of the cartesian product of two functions -/ section prod variables {f₂ : E → G} {f₂' : E →L[𝕜] G} lemma has_strict_fderiv_at.prod (hf₁ : has_strict_fderiv_at f₁ f₁' x) (hf₂ : has_strict_fderiv_at f₂ f₂' x) : has_strict_fderiv_at (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') x := hf₁.prod_left hf₂ lemma has_fderiv_at_filter.prod (hf₁ : has_fderiv_at_filter f₁ f₁' x L) (hf₂ : has_fderiv_at_filter f₂ f₂' x L) : has_fderiv_at_filter (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') x L := hf₁.prod_left hf₂ lemma has_fderiv_within_at.prod (hf₁ : has_fderiv_within_at f₁ f₁' s x) (hf₂ : has_fderiv_within_at f₂ f₂' s x) : has_fderiv_within_at (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') s x := hf₁.prod hf₂ lemma has_fderiv_at.prod (hf₁ : has_fderiv_at f₁ f₁' x) (hf₂ : has_fderiv_at f₂ f₂' x) : has_fderiv_at (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') x := hf₁.prod hf₂ lemma differentiable_within_at.prod (hf₁ : differentiable_within_at 𝕜 f₁ s x) (hf₂ : differentiable_within_at 𝕜 f₂ s x) : differentiable_within_at 𝕜 (λx:E, (f₁ x, f₂ x)) s x := (hf₁.has_fderiv_within_at.prod hf₂.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.prod (hf₁ : differentiable_at 𝕜 f₁ x) (hf₂ : differentiable_at 𝕜 f₂ x) : differentiable_at 𝕜 (λx:E, (f₁ x, f₂ x)) x := (hf₁.has_fderiv_at.prod hf₂.has_fderiv_at).differentiable_at lemma differentiable_on.prod (hf₁ : differentiable_on 𝕜 f₁ s) (hf₂ : differentiable_on 𝕜 f₂ s) : differentiable_on 𝕜 (λx:E, (f₁ x, f₂ x)) s := λx hx, differentiable_within_at.prod (hf₁ x hx) (hf₂ x hx) @[simp] lemma differentiable.prod (hf₁ : differentiable 𝕜 f₁) (hf₂ : differentiable 𝕜 f₂) : differentiable 𝕜 (λx:E, (f₁ x, f₂ x)) := λ x, differentiable_at.prod (hf₁ x) (hf₂ x) lemma differentiable_at.fderiv_prod (hf₁ : differentiable_at 𝕜 f₁ x) (hf₂ : differentiable_at 𝕜 f₂ x) : fderiv 𝕜 (λx:E, (f₁ x, f₂ x)) x = continuous_linear_map.prod (fderiv 𝕜 f₁ x) (fderiv 𝕜 f₂ x) := has_fderiv_at.fderiv (has_fderiv_at.prod hf₁.has_fderiv_at hf₂.has_fderiv_at) lemma differentiable_at.fderiv_within_prod (hf₁ : differentiable_within_at 𝕜 f₁ s x) (hf₂ : differentiable_within_at 𝕜 f₂ s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx:E, (f₁ x, f₂ x)) s x = continuous_linear_map.prod (fderiv_within 𝕜 f₁ s x) (fderiv_within 𝕜 f₂ s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_within_at.prod hf₁.has_fderiv_within_at hf₂.has_fderiv_within_at end end prod section fst variables {f₂ : E → F × G} {f₂' : E →L[𝕜] F × G} {p : E × F} lemma has_strict_fderiv_at_fst : has_strict_fderiv_at prod.fst (fst 𝕜 E F) p := (fst 𝕜 E F).has_strict_fderiv_at lemma has_strict_fderiv_at.fst (h : has_strict_fderiv_at f₂ f₂' x) : has_strict_fderiv_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x := has_strict_fderiv_at_fst.comp x h lemma has_fderiv_at_filter_fst {L : filter (E × F)} : has_fderiv_at_filter prod.fst (fst 𝕜 E F) p L := (fst 𝕜 E F).has_fderiv_at_filter lemma has_fderiv_at_filter.fst (h : has_fderiv_at_filter f₂ f₂' x L) : has_fderiv_at_filter (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x L := has_fderiv_at_filter_fst.comp x h lemma has_fderiv_at_fst : has_fderiv_at prod.fst (fst 𝕜 E F) p := has_fderiv_at_filter_fst lemma has_fderiv_at.fst (h : has_fderiv_at f₂ f₂' x) : has_fderiv_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x := h.fst lemma has_fderiv_within_at_fst {s : set (E × F)} : has_fderiv_within_at prod.fst (fst 𝕜 E F) s p := has_fderiv_at_filter_fst 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] 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] 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 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 lemma differentiable_on.fst (h : differentiable_on 𝕜 f₂ s) : differentiable_on 𝕜 (λ x, (f₂ x).1) s := differentiable_fst.comp_differentiable_on h lemma fderiv_fst : fderiv 𝕜 prod.fst p = fst 𝕜 E F := has_fderiv_at_fst.fderiv lemma fderiv.fst (h : differentiable_at 𝕜 f₂ x) : fderiv 𝕜 (λ x, (f₂ x).1) x = (fst 𝕜 F G).comp (fderiv 𝕜 f₂ x) := h.has_fderiv_at.fst.fderiv lemma fderiv_within_fst {s : set (E × F)} (hs : unique_diff_within_at 𝕜 s p) : fderiv_within 𝕜 prod.fst s p = fst 𝕜 E F := has_fderiv_within_at_fst.fderiv_within hs lemma fderiv_within.fst (hs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f₂ s x) : fderiv_within 𝕜 (λ x, (f₂ x).1) s x = (fst 𝕜 F G).comp (fderiv_within 𝕜 f₂ s x) := h.has_fderiv_within_at.fst.fderiv_within hs end fst section snd variables {f₂ : E → F × G} {f₂' : E →L[𝕜] F × G} {p : E × F} lemma has_strict_fderiv_at_snd : has_strict_fderiv_at prod.snd (snd 𝕜 E F) p := (snd 𝕜 E F).has_strict_fderiv_at lemma has_strict_fderiv_at.snd (h : has_strict_fderiv_at f₂ f₂' x) : has_strict_fderiv_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x := has_strict_fderiv_at_snd.comp x h lemma has_fderiv_at_filter_snd {L : filter (E × F)} : has_fderiv_at_filter prod.snd (snd 𝕜 E F) p L := (snd 𝕜 E F).has_fderiv_at_filter lemma has_fderiv_at_filter.snd (h : has_fderiv_at_filter f₂ f₂' x L) : has_fderiv_at_filter (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x L := has_fderiv_at_filter_snd.comp x h lemma has_fderiv_at_snd : has_fderiv_at prod.snd (snd 𝕜 E F) p := has_fderiv_at_filter_snd lemma has_fderiv_at.snd (h : has_fderiv_at f₂ f₂' x) : has_fderiv_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x := h.snd lemma has_fderiv_within_at_snd {s : set (E × F)} : has_fderiv_within_at prod.snd (snd 𝕜 E F) s p := has_fderiv_at_filter_snd 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] 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] 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 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 lemma differentiable_on.snd (h : differentiable_on 𝕜 f₂ s) : differentiable_on 𝕜 (λ x, (f₂ x).2) s := differentiable_snd.comp_differentiable_on h lemma fderiv_snd : fderiv 𝕜 prod.snd p = snd 𝕜 E F := has_fderiv_at_snd.fderiv lemma fderiv.snd (h : differentiable_at 𝕜 f₂ x) : fderiv 𝕜 (λ x, (f₂ x).2) x = (snd 𝕜 F G).comp (fderiv 𝕜 f₂ x) := h.has_fderiv_at.snd.fderiv lemma fderiv_within_snd {s : set (E × F)} (hs : unique_diff_within_at 𝕜 s p) : fderiv_within 𝕜 prod.snd s p = snd 𝕜 E F := has_fderiv_within_at_snd.fderiv_within hs lemma fderiv_within.snd (hs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f₂ s x) : fderiv_within 𝕜 (λ x, (f₂ x).2) s x = (snd 𝕜 F G).comp (fderiv_within 𝕜 f₂ s x) := h.has_fderiv_within_at.snd.fderiv_within hs end snd section prod_map variables {f₂ : G → G'} {f₂' : G →L[𝕜] G'} {y : G} (p : E × G) -- TODO (Lean 3.8): use `prod.map f f₂`` theorem has_strict_fderiv_at.prod_map (hf : has_strict_fderiv_at f f' p.1) (hf₂ : has_strict_fderiv_at f₂ f₂' p.2) : has_strict_fderiv_at (λ p : E × G, (f p.1, f₂ p.2)) (f'.prod_map f₂') p := (hf.comp p has_strict_fderiv_at_fst).prod (hf₂.comp p has_strict_fderiv_at_snd) theorem has_fderiv_at.prod_map (hf : has_fderiv_at f f' p.1) (hf₂ : has_fderiv_at f₂ f₂' p.2) : has_fderiv_at (λ p : E × G, (f p.1, f₂ p.2)) (f'.prod_map f₂') p := (hf.comp p has_fderiv_at_fst).prod (hf₂.comp p has_fderiv_at_snd) @[simp] theorem differentiable_at.prod_map (hf : differentiable_at 𝕜 f p.1) (hf₂ : differentiable_at 𝕜 f₂ p.2) : differentiable_at 𝕜 (λ p : E × G, (f p.1, f₂ p.2)) p := (hf.comp p differentiable_at_fst).prod (hf₂.comp p differentiable_at_snd) end prod_map end cartesian_product section const_smul /-! ### Derivative of a function multiplied by a constant -/ theorem has_strict_fderiv_at.const_smul (h : has_strict_fderiv_at f f' x) (c : 𝕜) : has_strict_fderiv_at (λ x, c • f x) (c • f') x := (c • (1 : F →L[𝕜] F)).has_strict_fderiv_at.comp x h theorem has_fderiv_at_filter.const_smul (h : has_fderiv_at_filter f f' x L) (c : 𝕜) : has_fderiv_at_filter (λ x, c • f x) (c • f') x L := (c • (1 : F →L[𝕜] F)).has_fderiv_at_filter.comp x h theorem has_fderiv_within_at.const_smul (h : has_fderiv_within_at f f' s x) (c : 𝕜) : has_fderiv_within_at (λ x, c • f x) (c • f') s x := h.const_smul c theorem has_fderiv_at.const_smul (h : has_fderiv_at f f' x) (c : 𝕜) : has_fderiv_at (λ x, c • f x) (c • f') x := h.const_smul c lemma differentiable_within_at.const_smul (h : differentiable_within_at 𝕜 f s x) (c : 𝕜) : differentiable_within_at 𝕜 (λy, c • f y) s x := (h.has_fderiv_within_at.const_smul c).differentiable_within_at lemma differentiable_at.const_smul (h : differentiable_at 𝕜 f x) (c : 𝕜) : differentiable_at 𝕜 (λy, c • f y) x := (h.has_fderiv_at.const_smul c).differentiable_at lemma differentiable_on.const_smul (h : differentiable_on 𝕜 f s) (c : 𝕜) : differentiable_on 𝕜 (λy, c • f y) s := λx hx, (h x hx).const_smul c lemma differentiable.const_smul (h : differentiable 𝕜 f) (c : 𝕜) : differentiable 𝕜 (λy, c • f y) := λx, (h x).const_smul c lemma fderiv_within_const_smul (hxs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f s x) (c : 𝕜) : fderiv_within 𝕜 (λy, c • f y) s x = c • fderiv_within 𝕜 f s x := (h.has_fderiv_within_at.const_smul c).fderiv_within hxs lemma fderiv_const_smul (h : differentiable_at 𝕜 f x) (c : 𝕜) : fderiv 𝕜 (λy, c • f y) x = c • fderiv 𝕜 f x := (h.has_fderiv_at.const_smul c).fderiv end const_smul section add /-! ### Derivative of the sum of two functions -/ theorem has_strict_fderiv_at.add (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) : has_strict_fderiv_at (λ y, f y + g y) (f' + g') x := (hf.add hg).congr_left $ λ y, by simp; abel theorem has_fderiv_at_filter.add (hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) : has_fderiv_at_filter (λ y, f y + g y) (f' + g') x L := (hf.add hg).congr_left $ λ _, by simp; abel theorem has_fderiv_within_at.add (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) : has_fderiv_within_at (λ y, f y + g y) (f' + g') s x := hf.add hg theorem has_fderiv_at.add (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) : has_fderiv_at (λ x, f x + g x) (f' + g') x := hf.add hg lemma differentiable_within_at.add (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : differentiable_within_at 𝕜 (λ y, f y + g y) s x := (hf.has_fderiv_within_at.add hg.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : differentiable_at 𝕜 (λ y, f y + g y) x := (hf.has_fderiv_at.add hg.has_fderiv_at).differentiable_at lemma differentiable_on.add (hf : differentiable_on 𝕜 f s) (hg : differentiable_on 𝕜 g s) : differentiable_on 𝕜 (λy, f y + g y) s := λx hx, (hf x hx).add (hg x hx) @[simp] lemma differentiable.add (hf : differentiable 𝕜 f) (hg : differentiable 𝕜 g) : differentiable 𝕜 (λy, f y + g y) := λx, (hf x).add (hg x) lemma fderiv_within_add (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : fderiv_within 𝕜 (λy, f y + g y) s x = fderiv_within 𝕜 f s x + fderiv_within 𝕜 g s x := (hf.has_fderiv_within_at.add hg.has_fderiv_within_at).fderiv_within hxs lemma fderiv_add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : fderiv 𝕜 (λy, f y + g y) x = fderiv 𝕜 f x + fderiv 𝕜 g x := (hf.has_fderiv_at.add hg.has_fderiv_at).fderiv theorem has_strict_fderiv_at.add_const (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ y, f y + c) f' x := add_zero f' ▸ hf.add (has_strict_fderiv_at_const _ _) theorem has_fderiv_at_filter.add_const (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ y, f y + c) f' x L := add_zero f' ▸ hf.add (has_fderiv_at_filter_const _ _ _) theorem has_fderiv_within_at.add_const (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ y, f y + c) f' s x := hf.add_const c theorem has_fderiv_at.add_const (hf : has_fderiv_at f f' x) (c : F): has_fderiv_at (λ x, f x + c) f' x := hf.add_const c lemma differentiable_within_at.add_const (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, f y + c) s x := (hf.has_fderiv_within_at.add_const c).differentiable_within_at lemma differentiable_at.add_const (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, f y + c) x := (hf.has_fderiv_at.add_const c).differentiable_at lemma differentiable_on.add_const (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, f y + c) s := λx hx, (hf x hx).add_const c lemma differentiable.add_const (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, f y + c) := λx, (hf x).add_const c lemma fderiv_within_add_const (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : fderiv_within 𝕜 (λy, f y + c) s x = fderiv_within 𝕜 f s x := (hf.has_fderiv_within_at.add_const c).fderiv_within hxs lemma fderiv_add_const (hf : differentiable_at 𝕜 f x) (c : F) : fderiv 𝕜 (λy, f y + c) x = fderiv 𝕜 f x := (hf.has_fderiv_at.add_const c).fderiv theorem has_strict_fderiv_at.const_add (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ y, c + f y) f' x := zero_add f' ▸ (has_strict_fderiv_at_const _ _).add hf theorem has_fderiv_at_filter.const_add (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ y, c + f y) f' x L := zero_add f' ▸ (has_fderiv_at_filter_const _ _ _).add hf theorem has_fderiv_within_at.const_add (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ y, c + f y) f' s x := hf.const_add c theorem has_fderiv_at.const_add (hf : has_fderiv_at f f' x) (c : F): has_fderiv_at (λ x, c + f x) f' x := hf.const_add c lemma differentiable_within_at.const_add (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, c + f y) s x := (hf.has_fderiv_within_at.const_add c).differentiable_within_at lemma differentiable_at.const_add (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, c + f y) x := (hf.has_fderiv_at.const_add c).differentiable_at lemma differentiable_on.const_add (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, c + f y) s := λx hx, (hf x hx).const_add c lemma differentiable.const_add (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, c + f y) := λx, (hf x).const_add c lemma fderiv_within_const_add (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : fderiv_within 𝕜 (λy, c + f y) s x = fderiv_within 𝕜 f s x := (hf.has_fderiv_within_at.const_add c).fderiv_within hxs lemma fderiv_const_add (hf : differentiable_at 𝕜 f x) (c : F) : fderiv 𝕜 (λy, c + f y) x = fderiv 𝕜 f x := (hf.has_fderiv_at.const_add c).fderiv end add section neg /-! ### Derivative of the negative of a function -/ theorem has_strict_fderiv_at.neg (h : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, -f x) (-f') x := (-1 : F →L[𝕜] F).has_strict_fderiv_at.comp x h theorem has_fderiv_at_filter.neg (h : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (λ x, -f x) (-f') x L := (-1 : F →L[𝕜] F).has_fderiv_at_filter.comp x h theorem has_fderiv_within_at.neg (h : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, -f x) (-f') s x := h.neg theorem has_fderiv_at.neg (h : has_fderiv_at f f' x) : has_fderiv_at (λ x, -f x) (-f') x := h.neg lemma differentiable_within_at.neg (h : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (λy, -f y) s x := h.has_fderiv_within_at.neg.differentiable_within_at @[simp] lemma differentiable_at.neg (h : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (λy, -f y) x := h.has_fderiv_at.neg.differentiable_at lemma differentiable_on.neg (h : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (λy, -f y) s := λx hx, (h x hx).neg @[simp] lemma differentiable.neg (h : differentiable 𝕜 f) : differentiable 𝕜 (λy, -f y) := λx, (h x).neg lemma fderiv_within_neg (hxs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 (λy, -f y) s x = - fderiv_within 𝕜 f s x := h.has_fderiv_within_at.neg.fderiv_within hxs lemma fderiv_neg (h : differentiable_at 𝕜 f x) : fderiv 𝕜 (λy, -f y) x = - fderiv 𝕜 f x := h.has_fderiv_at.neg.fderiv end neg section sub /-! ### Derivative of the difference of two functions -/ theorem has_strict_fderiv_at.sub (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) : has_strict_fderiv_at (λ x, f x - g x) (f' - g') x := hf.add hg.neg theorem has_fderiv_at_filter.sub (hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) : has_fderiv_at_filter (λ x, f x - g x) (f' - g') x L := hf.add hg.neg theorem has_fderiv_within_at.sub (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) : has_fderiv_within_at (λ x, f x - g x) (f' - g') s x := hf.sub hg theorem has_fderiv_at.sub (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) : has_fderiv_at (λ x, f x - g x) (f' - g') x := hf.sub hg lemma differentiable_within_at.sub (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : differentiable_within_at 𝕜 (λ y, f y - g y) s x := (hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : differentiable_at 𝕜 (λ y, f y - g y) x := (hf.has_fderiv_at.sub hg.has_fderiv_at).differentiable_at lemma differentiable_on.sub (hf : differentiable_on 𝕜 f s) (hg : differentiable_on 𝕜 g s) : differentiable_on 𝕜 (λy, f y - g y) s := λx hx, (hf x hx).sub (hg x hx) @[simp] lemma differentiable.sub (hf : differentiable 𝕜 f) (hg : differentiable 𝕜 g) : differentiable 𝕜 (λy, f y - g y) := λx, (hf x).sub (hg x) lemma fderiv_within_sub (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : fderiv_within 𝕜 (λy, f y - g y) s x = fderiv_within 𝕜 f s x - fderiv_within 𝕜 g s x := (hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).fderiv_within hxs lemma fderiv_sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : fderiv 𝕜 (λy, f y - g y) x = fderiv 𝕜 f x - fderiv 𝕜 g x := (hf.has_fderiv_at.sub hg.has_fderiv_at).fderiv theorem has_strict_fderiv_at.sub_const (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ x, f x - c) f' x := hf.add_const (-c) theorem has_fderiv_at_filter.sub_const (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ x, f x - c) f' x L := hf.add_const (-c) theorem has_fderiv_within_at.sub_const (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ x, f x - c) f' s x := hf.sub_const c theorem has_fderiv_at.sub_const (hf : has_fderiv_at f f' x) (c : F) : has_fderiv_at (λ x, f x - c) f' x := hf.sub_const c lemma differentiable_within_at.sub_const (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, f y - c) s x := (hf.has_fderiv_within_at.sub_const c).differentiable_within_at lemma differentiable_at.sub_const (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, f y - c) x := (hf.has_fderiv_at.sub_const c).differentiable_at lemma differentiable_on.sub_const (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, f y - c) s := λx hx, (hf x hx).sub_const c lemma differentiable.sub_const (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, f y - c) := λx, (hf x).sub_const c lemma fderiv_within_sub_const (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : fderiv_within 𝕜 (λy, f y - c) s x = fderiv_within 𝕜 f s x := (hf.has_fderiv_within_at.sub_const c).fderiv_within hxs lemma fderiv_sub_const (hf : differentiable_at 𝕜 f x) (c : F) : fderiv 𝕜 (λy, f y - c) x = fderiv 𝕜 f x := (hf.has_fderiv_at.sub_const c).fderiv theorem has_strict_fderiv_at.const_sub (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ x, c - f x) (-f') x := hf.neg.const_add c theorem has_fderiv_at_filter.const_sub (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ x, c - f x) (-f') x L := hf.neg.const_add c theorem has_fderiv_within_at.const_sub (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ x, c - f x) (-f') s x := hf.const_sub c theorem has_fderiv_at.const_sub (hf : has_fderiv_at f f' x) (c : F) : has_fderiv_at (λ x, c - f x) (-f') x := hf.const_sub c lemma differentiable_within_at.const_sub (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, c - f y) s x := (hf.has_fderiv_within_at.const_sub c).differentiable_within_at lemma differentiable_at.const_sub (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, c - f y) x := (hf.has_fderiv_at.const_sub c).differentiable_at lemma differentiable_on.const_sub (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, c - f y) s := λx hx, (hf x hx).const_sub c lemma differentiable.const_sub (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, c - f y) := λx, (hf x).const_sub c lemma fderiv_within_const_sub (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : fderiv_within 𝕜 (λy, c - f y) s x = -fderiv_within 𝕜 f s x := (hf.has_fderiv_within_at.const_sub c).fderiv_within hxs lemma fderiv_const_sub (hf : differentiable_at 𝕜 f x) (c : F) : fderiv 𝕜 (λy, c - f y) x = -fderiv 𝕜 f x := (hf.has_fderiv_at.const_sub c).fderiv end sub section bilinear_map /-! ### Derivative of a bounded bilinear map -/ variables {b : E × F → G} {u : set (E × F) } open normed_field lemma is_bounded_bilinear_map.has_strict_fderiv_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_strict_fderiv_at b (h.deriv p) p := begin rw has_strict_fderiv_at, set T := (E × F) × (E × F), have : is_o (λ q : T, b (q.1 - q.2)) (λ q : T, ∥q.1 - q.2∥ * 1) (𝓝 (p, p)), { refine (h.is_O'.comp_tendsto le_top).trans_is_o _, simp only [(∘)], refine (is_O_refl (λ q : T, ∥q.1 - q.2∥) _).mul_is_o (is_o.norm_left $ (is_o_one_iff _).2 _), rw [← sub_self p], exact continuous_at_fst.sub continuous_at_snd }, simp only [mul_one, is_o_norm_right] at this, refine (is_o.congr_of_sub _).1 this, clear this, convert_to is_o (λ q : T, h.deriv (p - q.2) (q.1 - q.2)) (λ q : T, q.1 - q.2) (𝓝 (p, p)), { ext q, rcases q with ⟨⟨x₁, y₁⟩, ⟨x₂, y₂⟩⟩, rcases p with ⟨x, y⟩, simp only [is_bounded_bilinear_map_deriv_coe, prod.mk_sub_mk, h.map_sub_left, h.map_sub_right], abel }, have : is_o (λ q : T, p - q.2) (λ q, (1:ℝ)) (𝓝 (p, p)), from (is_o_one_iff _).2 (sub_self p ▸ tendsto_const_nhds.sub continuous_at_snd), apply is_bounded_bilinear_map_apply.is_O_comp.trans_is_o, refine is_o.trans_is_O _ (is_O_const_mul_self 1 _ _).of_norm_right, refine is_o.mul_is_O _ (is_O_refl _ _), exact (((h.is_bounded_linear_map_deriv.is_O_id ⊤).comp_tendsto le_top : _).trans_is_o this).norm_left end lemma is_bounded_bilinear_map.has_fderiv_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_fderiv_at b (h.deriv p) p := (h.has_strict_fderiv_at p).has_fderiv_at lemma is_bounded_bilinear_map.has_fderiv_within_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_fderiv_within_at b (h.deriv p) u p := (h.has_fderiv_at p).has_fderiv_within_at lemma is_bounded_bilinear_map.differentiable_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : differentiable_at 𝕜 b p := (h.has_fderiv_at p).differentiable_at lemma is_bounded_bilinear_map.differentiable_within_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : differentiable_within_at 𝕜 b u p := (h.differentiable_at p).differentiable_within_at lemma is_bounded_bilinear_map.fderiv (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : fderiv 𝕜 b p = h.deriv p := has_fderiv_at.fderiv (h.has_fderiv_at p) lemma is_bounded_bilinear_map.fderiv_within (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) (hxs : unique_diff_within_at 𝕜 u p) : fderiv_within 𝕜 b u p = h.deriv p := begin rw differentiable_at.fderiv_within (h.differentiable_at p) hxs, exact h.fderiv p end lemma is_bounded_bilinear_map.differentiable (h : is_bounded_bilinear_map 𝕜 b) : differentiable 𝕜 b := λx, h.differentiable_at x lemma is_bounded_bilinear_map.differentiable_on (h : is_bounded_bilinear_map 𝕜 b) : differentiable_on 𝕜 b u := h.differentiable.differentiable_on lemma is_bounded_bilinear_map.continuous (h : is_bounded_bilinear_map 𝕜 b) : continuous b := h.differentiable.continuous lemma is_bounded_bilinear_map.continuous_left (h : is_bounded_bilinear_map 𝕜 b) {f : F} : continuous (λe, b (e, f)) := h.continuous.comp (continuous_id.prod_mk continuous_const) lemma is_bounded_bilinear_map.continuous_right (h : is_bounded_bilinear_map 𝕜 b) {e : E} : continuous (λf, b (e, f)) := h.continuous.comp (continuous_const.prod_mk continuous_id) end bilinear_map section smul /-! ### Derivative of the product of a scalar-valued function and a vector-valued function -/ variables {c : E → 𝕜} {c' : E →L[𝕜] 𝕜} theorem has_strict_fderiv_at.smul (hc : has_strict_fderiv_at c c' x) (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) x := (is_bounded_bilinear_map_smul.has_strict_fderiv_at (c x, f x)).comp x $ hc.prod hf theorem has_fderiv_within_at.smul (hc : has_fderiv_within_at c c' s x) (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) s x := (is_bounded_bilinear_map_smul.has_fderiv_at (c x, f x)).comp_has_fderiv_within_at x $ hc.prod hf theorem has_fderiv_at.smul (hc : has_fderiv_at c c' x) (hf : has_fderiv_at f f' x) : has_fderiv_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) x := (is_bounded_bilinear_map_smul.has_fderiv_at (c x, f x)).comp x $ hc.prod hf lemma differentiable_within_at.smul (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (λ y, c y • f y) s x := (hc.has_fderiv_within_at.smul hf.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (λ y, c y • f y) x := (hc.has_fderiv_at.smul hf.has_fderiv_at).differentiable_at lemma differentiable_on.smul (hc : differentiable_on 𝕜 c s) (hf : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (λ y, c y • f y) s := λx hx, (hc x hx).smul (hf x hx) @[simp] lemma differentiable.smul (hc : differentiable 𝕜 c) (hf : differentiable 𝕜 f) : differentiable 𝕜 (λ y, c y • f y) := λx, (hc x).smul (hf x) lemma fderiv_within_smul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 (λ y, c y • f y) s x = c x • fderiv_within 𝕜 f s x + (fderiv_within 𝕜 c s x).smul_right (f x) := (hc.has_fderiv_within_at.smul hf.has_fderiv_within_at).fderiv_within hxs lemma fderiv_smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : fderiv 𝕜 (λ y, c y • f y) x = c x • fderiv 𝕜 f x + (fderiv 𝕜 c x).smul_right (f x) := (hc.has_fderiv_at.smul hf.has_fderiv_at).fderiv theorem has_strict_fderiv_at.smul_const (hc : has_strict_fderiv_at c c' x) (f : F) : has_strict_fderiv_at (λ y, c y • f) (c'.smul_right f) x := by simpa only [smul_zero, zero_add] using hc.smul (has_strict_fderiv_at_const f x) theorem has_fderiv_within_at.smul_const (hc : has_fderiv_within_at c c' s x) (f : F) : has_fderiv_within_at (λ y, c y • f) (c'.smul_right f) s x := by simpa only [smul_zero, zero_add] using hc.smul (has_fderiv_within_at_const f x s) theorem has_fderiv_at.smul_const (hc : has_fderiv_at c c' x) (f : F) : has_fderiv_at (λ y, c y • f) (c'.smul_right f) x := by simpa only [smul_zero, zero_add] using hc.smul (has_fderiv_at_const f x) lemma differentiable_within_at.smul_const (hc : differentiable_within_at 𝕜 c s x) (f : F) : differentiable_within_at 𝕜 (λ y, c y • f) s x := (hc.has_fderiv_within_at.smul_const f).differentiable_within_at lemma differentiable_at.smul_const (hc : differentiable_at 𝕜 c x) (f : F) : differentiable_at 𝕜 (λ y, c y • f) x := (hc.has_fderiv_at.smul_const f).differentiable_at lemma differentiable_on.smul_const (hc : differentiable_on 𝕜 c s) (f : F) : differentiable_on 𝕜 (λ y, c y • f) s := λx hx, (hc x hx).smul_const f lemma differentiable.smul_const (hc : differentiable 𝕜 c) (f : F) : differentiable 𝕜 (λ y, c y • f) := λx, (hc x).smul_const f lemma fderiv_within_smul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (f : F) : fderiv_within 𝕜 (λ y, c y • f) s x = (fderiv_within 𝕜 c s x).smul_right f := (hc.has_fderiv_within_at.smul_const f).fderiv_within hxs lemma fderiv_smul_const (hc : differentiable_at 𝕜 c x) (f : F) : fderiv 𝕜 (λ y, c y • f) x = (fderiv 𝕜 c x).smul_right f := (hc.has_fderiv_at.smul_const f).fderiv end smul section mul /-! ### Derivative of the product of two scalar-valued functions -/ set_option class.instance_max_depth 120 variables {c d : E → 𝕜} {c' d' : E →L[𝕜] 𝕜} theorem has_strict_fderiv_at.mul (hc : has_strict_fderiv_at c c' x) (hd : has_strict_fderiv_at d d' x) : has_strict_fderiv_at (λ y, c y * d y) (c x • d' + d x • c') x := by { convert hc.smul hd, ext z, apply mul_comm } theorem has_fderiv_within_at.mul (hc : has_fderiv_within_at c c' s x) (hd : has_fderiv_within_at d d' s x) : has_fderiv_within_at (λ y, c y * d y) (c x • d' + d x • c') s x := by { convert hc.smul hd, ext z, apply mul_comm } theorem has_fderiv_at.mul (hc : has_fderiv_at c c' x) (hd : has_fderiv_at d d' x) : has_fderiv_at (λ y, c y * d y) (c x • d' + d x • c') x := by { convert hc.smul hd, ext z, apply mul_comm } lemma differentiable_within_at.mul (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : differentiable_within_at 𝕜 (λ y, c y * d y) s x := (hc.has_fderiv_within_at.mul hd.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : differentiable_at 𝕜 (λ y, c y * d y) x := (hc.has_fderiv_at.mul hd.has_fderiv_at).differentiable_at lemma differentiable_on.mul (hc : differentiable_on 𝕜 c s) (hd : differentiable_on 𝕜 d s) : differentiable_on 𝕜 (λ y, c y * d y) s := λx hx, (hc x hx).mul (hd x hx) @[simp] lemma differentiable.mul (hc : differentiable 𝕜 c) (hd : differentiable 𝕜 d) : differentiable 𝕜 (λ y, c y * d y) := λx, (hc x).mul (hd x) lemma fderiv_within_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : fderiv_within 𝕜 (λ y, c y * d y) s x = c x • fderiv_within 𝕜 d s x + d x • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.mul hd.has_fderiv_within_at).fderiv_within hxs lemma fderiv_mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : fderiv 𝕜 (λ y, c y * d y) x = c x • fderiv 𝕜 d x + d x • fderiv 𝕜 c x := (hc.has_fderiv_at.mul hd.has_fderiv_at).fderiv theorem has_strict_fderiv_at.mul_const (hc : has_strict_fderiv_at c c' x) (d : 𝕜) : has_strict_fderiv_at (λ y, c y * d) (d • c') x := by simpa only [smul_zero, zero_add] using hc.mul (has_strict_fderiv_at_const d x) theorem has_fderiv_within_at.mul_const (hc : has_fderiv_within_at c c' s x) (d : 𝕜) : has_fderiv_within_at (λ y, c y * d) (d • c') s x := by simpa only [smul_zero, zero_add] using hc.mul (has_fderiv_within_at_const d x s) theorem has_fderiv_at.mul_const (hc : has_fderiv_at c c' x) (d : 𝕜) : has_fderiv_at (λ y, c y * d) (d • c') x := begin rw [← has_fderiv_within_at_univ] at *, exact hc.mul_const d end lemma differentiable_within_at.mul_const (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : differentiable_within_at 𝕜 (λ y, c y * d) s x := (hc.has_fderiv_within_at.mul_const d).differentiable_within_at lemma differentiable_at.mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) : differentiable_at 𝕜 (λ y, c y * d) x := (hc.has_fderiv_at.mul_const d).differentiable_at lemma differentiable_on.mul_const (hc : differentiable_on 𝕜 c s) (d : 𝕜) : differentiable_on 𝕜 (λ y, c y * d) s := λx hx, (hc x hx).mul_const d lemma differentiable.mul_const (hc : differentiable 𝕜 c) (d : 𝕜) : differentiable 𝕜 (λ y, c y * d) := λx, (hc x).mul_const d lemma fderiv_within_mul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : fderiv_within 𝕜 (λ y, c y * d) s x = d • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.mul_const d).fderiv_within hxs lemma fderiv_mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) : fderiv 𝕜 (λ y, c y * d) x = d • fderiv 𝕜 c x := (hc.has_fderiv_at.mul_const d).fderiv theorem has_strict_fderiv_at.const_mul (hc : has_strict_fderiv_at c c' x) (d : 𝕜) : has_strict_fderiv_at (λ y, d * c y) (d • c') x := begin simp only [mul_comm d], exact hc.mul_const d, end theorem has_fderiv_within_at.const_mul (hc : has_fderiv_within_at c c' s x) (d : 𝕜) : has_fderiv_within_at (λ y, d * c y) (d • c') s x := begin simp only [mul_comm d], exact hc.mul_const d, end theorem has_fderiv_at.const_mul (hc : has_fderiv_at c c' x) (d : 𝕜) : has_fderiv_at (λ y, d * c y) (d • c') x := begin simp only [mul_comm d], exact hc.mul_const d, end lemma differentiable_within_at.const_mul (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : differentiable_within_at 𝕜 (λ y, d * c y) s x := (hc.has_fderiv_within_at.const_mul d).differentiable_within_at lemma differentiable_at.const_mul (hc : differentiable_at 𝕜 c x) (d : 𝕜) : differentiable_at 𝕜 (λ y, d * c y) x := (hc.has_fderiv_at.const_mul d).differentiable_at lemma differentiable_on.const_mul (hc : differentiable_on 𝕜 c s) (d : 𝕜) : differentiable_on 𝕜 (λ y, d * c y) s := λx hx, (hc x hx).const_mul d lemma differentiable.const_mul (hc : differentiable 𝕜 c) (d : 𝕜) : differentiable 𝕜 (λ y, d * c y) := λx, (hc x).const_mul d lemma fderiv_within_const_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : fderiv_within 𝕜 (λ y, d * c y) s x = d • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.const_mul d).fderiv_within hxs lemma fderiv_const_mul (hc : differentiable_at 𝕜 c x) (d : 𝕜) : fderiv 𝕜 (λ y, d * c y) x = d • fderiv 𝕜 c x := (hc.has_fderiv_at.const_mul d).fderiv end mul section continuous_linear_equiv /-! ### Differentiability of linear equivs, and invariance of differentiability -/ variable (iso : E ≃L[𝕜] F) protected lemma continuous_linear_equiv.has_strict_fderiv_at : has_strict_fderiv_at iso (iso : E →L[𝕜] F) x := iso.to_continuous_linear_map.has_strict_fderiv_at protected lemma continuous_linear_equiv.has_fderiv_within_at : has_fderiv_within_at iso (iso : E →L[𝕜] F) s x := iso.to_continuous_linear_map.has_fderiv_within_at protected lemma continuous_linear_equiv.has_fderiv_at : has_fderiv_at iso (iso : E →L[𝕜] F) x := iso.to_continuous_linear_map.has_fderiv_at_filter protected lemma continuous_linear_equiv.differentiable_at : differentiable_at 𝕜 iso x := iso.has_fderiv_at.differentiable_at protected lemma continuous_linear_equiv.differentiable_within_at : differentiable_within_at 𝕜 iso s x := iso.differentiable_at.differentiable_within_at protected lemma continuous_linear_equiv.fderiv : fderiv 𝕜 iso x = iso := iso.has_fderiv_at.fderiv protected lemma continuous_linear_equiv.fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 iso s x = iso := iso.to_continuous_linear_map.fderiv_within hxs protected lemma continuous_linear_equiv.differentiable : differentiable 𝕜 iso := λx, iso.differentiable_at protected lemma continuous_linear_equiv.differentiable_on : differentiable_on 𝕜 iso s := iso.differentiable.differentiable_on lemma continuous_linear_equiv.comp_differentiable_within_at_iff {f : G → E} {s : set G} {x : G} : differentiable_within_at 𝕜 (iso ∘ f) s x ↔ differentiable_within_at 𝕜 f s x := begin refine ⟨λ H, _, λ H, iso.differentiable.differentiable_at.comp_differentiable_within_at x H⟩, have : differentiable_within_at 𝕜 (iso.symm ∘ (iso ∘ f)) s x := iso.symm.differentiable.differentiable_at.comp_differentiable_within_at x H, rwa [← function.comp.assoc iso.symm iso f, iso.symm_comp_self] at this, end lemma continuous_linear_equiv.comp_differentiable_at_iff {f : G → E} {x : G} : differentiable_at 𝕜 (iso ∘ f) x ↔ differentiable_at 𝕜 f x := by rw [← differentiable_within_at_univ, ← differentiable_within_at_univ, iso.comp_differentiable_within_at_iff] lemma continuous_linear_equiv.comp_differentiable_on_iff {f : G → E} {s : set G} : differentiable_on 𝕜 (iso ∘ f) s ↔ differentiable_on 𝕜 f s := begin rw [differentiable_on, differentiable_on], simp only [iso.comp_differentiable_within_at_iff], end lemma continuous_linear_equiv.comp_differentiable_iff {f : G → E} : differentiable 𝕜 (iso ∘ f) ↔ differentiable 𝕜 f := begin rw [← differentiable_on_univ, ← differentiable_on_univ], exact iso.comp_differentiable_on_iff end lemma continuous_linear_equiv.comp_has_fderiv_within_at_iff {f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] E} : has_fderiv_within_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') s x ↔ has_fderiv_within_at f f' s x := begin refine ⟨λ H, _, λ H, iso.has_fderiv_at.comp_has_fderiv_within_at x H⟩, have A : f = iso.symm ∘ (iso ∘ f), by { rw [← function.comp.assoc, iso.symm_comp_self], refl }, have B : f' = (iso.symm : F →L[𝕜] E).comp ((iso : E →L[𝕜] F).comp f'), by rw [← continuous_linear_map.comp_assoc, iso.coe_symm_comp_coe, continuous_linear_map.id_comp], rw [A, B], exact iso.symm.has_fderiv_at.comp_has_fderiv_within_at x H end lemma continuous_linear_equiv.comp_has_strict_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} : has_strict_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_strict_fderiv_at f f' x := begin refine ⟨λ H, _, λ H, iso.has_strict_fderiv_at.comp x H⟩, convert iso.symm.has_strict_fderiv_at.comp x H; ext z; apply (iso.symm_apply_apply _).symm end lemma continuous_linear_equiv.comp_has_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} : has_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_fderiv_at f f' x := by rw [← has_fderiv_within_at_univ, ← has_fderiv_within_at_univ, iso.comp_has_fderiv_within_at_iff] lemma continuous_linear_equiv.comp_has_fderiv_within_at_iff' {f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] F} : has_fderiv_within_at (iso ∘ f) f' s x ↔ has_fderiv_within_at f ((iso.symm : F →L[𝕜] E).comp f') s x := by rw [← iso.comp_has_fderiv_within_at_iff, ← continuous_linear_map.comp_assoc, iso.coe_comp_coe_symm, continuous_linear_map.id_comp] lemma continuous_linear_equiv.comp_has_fderiv_at_iff' {f : G → E} {x : G} {f' : G →L[𝕜] F} : has_fderiv_at (iso ∘ f) f' x ↔ has_fderiv_at f ((iso.symm : F →L[𝕜] E).comp f') x := by rw [← has_fderiv_within_at_univ, ← has_fderiv_within_at_univ, iso.comp_has_fderiv_within_at_iff'] lemma continuous_linear_equiv.comp_fderiv_within {f : G → E} {s : set G} {x : G} (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (iso ∘ f) s x = (iso : E →L[𝕜] F).comp (fderiv_within 𝕜 f s x) := begin by_cases h : differentiable_within_at 𝕜 f s x, { rw [fderiv.comp_fderiv_within x iso.differentiable_at h hxs, iso.fderiv] }, { have : ¬differentiable_within_at 𝕜 (iso ∘ f) s x, from mt iso.comp_differentiable_within_at_iff.1 h, rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at this, continuous_linear_map.comp_zero] } end lemma continuous_linear_equiv.comp_fderiv {f : G → E} {x : G} : fderiv 𝕜 (iso ∘ f) x = (iso : E →L[𝕜] F).comp (fderiv 𝕜 f x) := begin rw [← fderiv_within_univ, ← fderiv_within_univ], exact iso.comp_fderiv_within unique_diff_within_at_univ, end end continuous_linear_equiv end section /- In the special case of a normed space over the reals, we can use scalar multiplication in the `tendsto` characterization of the Fréchet derivative. -/ variables {E : Type*} [normed_group E] [normed_space ℝ E] variables {F : Type*} [normed_group F] [normed_space ℝ F] variables {f : E → F} {f' : E →L[ℝ] F} {x : E} theorem has_fderiv_at_filter_real_equiv {L : filter E} : tendsto (λ x' : E, ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (𝓝 0) ↔ tendsto (λ x' : E, ∥x' - x∥⁻¹ • (f x' - f x - f' (x' - x))) L (𝓝 0) := begin symmetry, rw [tendsto_iff_norm_tendsto_zero], refine tendsto_congr (λ x', _), have : ∥x' - x∥⁻¹ ≥ 0, from inv_nonneg.mpr (norm_nonneg _), simp [norm_smul, real.norm_eq_abs, abs_of_nonneg this] end lemma has_fderiv_at.lim_real (hf : has_fderiv_at f f' x) (v : E) : tendsto (λ (c:ℝ), c • (f (x + c⁻¹ • v) - f x)) at_top (𝓝 (f' v)) := begin apply hf.lim v, rw tendsto_at_top_at_top, exact λ b, ⟨b, λ a ha, le_trans ha (le_abs_self _)⟩ end end section tangent_cone variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {f : E → F} {s : set E} {f' : E →L[𝕜] F} /-- The image of a tangent cone under the differential of a map is included in the tangent cone to the image. -/ lemma has_fderiv_within_at.maps_to_tangent_cone {x : E} (h : has_fderiv_within_at f f' s x) : maps_to f' (tangent_cone_at 𝕜 s x) (tangent_cone_at 𝕜 (f '' s) (f x)) := begin rintros v ⟨c, d, dtop, clim, cdlim⟩, refine ⟨c, (λn, f (x + d n) - f x), mem_sets_of_superset dtop _, clim, h.lim at_top dtop clim cdlim⟩, simp [-mem_image, mem_image_of_mem] {contextual := tt} end /-- If a set has the unique differentiability property at a point x, then the image of this set under a map with onto derivative has also the unique differentiability property at the image point. -/ lemma has_fderiv_within_at.unique_diff_within_at {x : E} (h : has_fderiv_within_at f f' s x) (hs : unique_diff_within_at 𝕜 s x) (h' : closure (range f') = univ) : unique_diff_within_at 𝕜 (f '' s) (f x) := begin have B : ∀v ∈ (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E), f' v ∈ (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x)) : set F), { assume v hv, apply submodule.span_induction hv, { exact λ w hw, submodule.subset_span (h.maps_to_tangent_cone hw) }, { simp }, { assume w₁ w₂ hw₁ hw₂, rw continuous_linear_map.map_add, exact submodule.add_mem (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x))) hw₁ hw₂ }, { assume a w hw, rw continuous_linear_map.map_smul, exact submodule.smul_mem (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x))) _ hw } }, rw [unique_diff_within_at, ← univ_subset_iff], split, show f x ∈ closure (f '' s), from h.continuous_within_at.mem_closure_image hs.2, show univ ⊆ closure ↑(submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x))), from calc univ ⊆ closure (range f') : univ_subset_iff.2 h' ... = closure (f' '' univ) : by rw image_univ ... = closure (f' '' (closure (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E))) : by rw hs.1 ... ⊆ closure (closure (f' '' (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E))) : closure_mono (image_closure_subset_closure_image f'.cont) ... = closure (f' '' (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E)) : closure_closure ... ⊆ closure (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x)) : set F) : closure_mono (image_subset_iff.mpr B) end lemma has_fderiv_within_at.unique_diff_within_at_of_continuous_linear_equiv {x : E} (e' : E ≃L[𝕜] F) (h : has_fderiv_within_at f (e' : E →L[𝕜] F) s x) (hs : unique_diff_within_at 𝕜 s x) : unique_diff_within_at 𝕜 (f '' s) (f x) := begin apply h.unique_diff_within_at hs, have : range (e' : E →L[𝕜] F) = univ := e'.to_linear_equiv.to_equiv.range_eq_univ, rw [this, closure_univ] end lemma continuous_linear_equiv.unique_diff_on_preimage_iff (e : F ≃L[𝕜] E) : unique_diff_on 𝕜 (e ⁻¹' s) ↔ unique_diff_on 𝕜 s := begin split, { assume hs x hx, have A : s = e '' (e.symm '' s) := (equiv.symm_image_image (e.symm.to_linear_equiv.to_equiv) s).symm, have B : e.symm '' s = e⁻¹' s := equiv.image_eq_preimage e.symm.to_linear_equiv.to_equiv s, rw [A, B, (e.apply_symm_apply x).symm], refine has_fderiv_within_at.unique_diff_within_at_of_continuous_linear_equiv e e.has_fderiv_within_at (hs _ _), rwa [mem_preimage, e.apply_symm_apply x] }, { assume hs x hx, have : e ⁻¹' s = e.symm '' s := (equiv.image_eq_preimage e.symm.to_linear_equiv.to_equiv s).symm, rw [this, (e.symm_apply_apply x).symm], exact has_fderiv_within_at.unique_diff_within_at_of_continuous_linear_equiv e.symm e.symm.has_fderiv_within_at (hs _ hx) }, end end tangent_cone section restrict_scalars /-! ### Restricting from `ℂ` to `ℝ`, or generally from `𝕜'` to `𝕜` If a function is differentiable over `ℂ`, then it is differentiable over `ℝ`. In this paragraph, we give variants of this statement, in the general situation where `ℂ` and `ℝ` are replaced respectively by `𝕜'` and `𝕜` where `𝕜'` is a normed algebra over `𝕜`. -/ variables (𝕜 : Type*) [nondiscrete_normed_field 𝕜] {𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] {E : Type*} [normed_group E] [normed_space 𝕜' E] {F : Type*} [normed_group F] [normed_space 𝕜' F] {f : E → F} {f' : E →L[𝕜'] F} {s : set E} {x : E} local attribute [instance] normed_space.restrict_scalars lemma has_strict_fderiv_at.restrict_scalars (h : has_strict_fderiv_at f f' x) : has_strict_fderiv_at f (f'.restrict_scalars 𝕜) x := h lemma has_fderiv_at.restrict_scalars (h : has_fderiv_at f f' x) : has_fderiv_at f (f'.restrict_scalars 𝕜) x := h lemma has_fderiv_within_at.restrict_scalars (h : has_fderiv_within_at f f' s x) : has_fderiv_within_at f (f'.restrict_scalars 𝕜) s x := h lemma differentiable_at.restrict_scalars (h : differentiable_at 𝕜' f x) : differentiable_at 𝕜 f x := (h.has_fderiv_at.restrict_scalars 𝕜).differentiable_at lemma differentiable_within_at.restrict_scalars (h : differentiable_within_at 𝕜' f s x) : differentiable_within_at 𝕜 f s x := (h.has_fderiv_within_at.restrict_scalars 𝕜).differentiable_within_at lemma differentiable_on.restrict_scalars (h : differentiable_on 𝕜' f s) : differentiable_on 𝕜 f s := λx hx, (h x hx).restrict_scalars 𝕜 lemma differentiable.restrict_scalars (h : differentiable 𝕜' f) : differentiable 𝕜 f := λx, (h x).restrict_scalars 𝕜 end restrict_scalars
6cd5db4dd7e9bafce6c765c485119f5fc0828a5f
3bdd27ffdff3ffa22d4bb010eba695afcc96bc4a
/src/combinatorics/simplicial_complex/convex_join.lean
20b3438212a8f62f1884ce2b013471e8df90f2fe
[]
no_license
mmasdeu/brouwerfixedpoint
684d712c982c6a8b258b4e2c6b2eab923f2f1289
548270f79ecf12d7e20a256806ccb9fcf57b87e2
refs/heads/main
1,690,539,793,996
1,631,801,831,000
1,631,801,831,000
368,139,809
4
3
null
1,624,453,250,000
1,621,246,034,000
Lean
UTF-8
Lean
false
false
11,558
lean
/- Copyright (c) 2021 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import analysis.convex.basic import linear_algebra.affine_space.affine_subspace import combinatorics.simplicial_complex.to_move.default open set variables {E : Type*} [add_comm_group E] [module ℝ E] {x y : E} {A B C D : set E} {c : set (set E)} def convex_join (A B : set E) : set E := A ∪ B ∪ ⋃ a b (ha : a ∈ A) (hb : b ∈ B), open_segment a b /-The three other possible defs of `convex_join`. They are *not* equivalent. This one is the weakest, not even respecting `convex_hull (A ∪ B) = convex_join (convex_hull A) (convex_hull B)` as it doesn't cope well with `A = ∅` or `B = ∅`. def convex_join (A B : set E) : set E := ⋃ a b (ha : a ∈ A) (hb : b ∈ B), segment a b That one is stronger than the one I went for. It respects `convex_hull (A ∪ B) = convex_join (convex_hull A) (convex_hull B)` and even adds some segments, but doesn't unfold nicely as it breaks into four cases `(a ∈ A ∨ a ∈ B) ∧ (b ∈ A ∨ b ∈ B)` two of which are hard but essentially the same. def convex_join (A B : set E) : set E := ⋃ a b (ha : a ∈ A ∪ B) (hb : b ∈ A ∪ B), segment a b -/ lemma mem_convex_join_iff : x ∈ convex_join A B ↔ x ∈ A ∪ B ∨ ∃ a b : E, a ∈ A ∧ b ∈ B ∧ x ∈ open_segment a b := begin unfold convex_join, simp, end lemma convex_join_comm (A B : set E) : convex_join A B = convex_join B A := begin ext x, rw [mem_convex_join_iff, mem_convex_join_iff, union_comm], split; { rintro (hx | ⟨a, b, ha, hb, hx⟩), { left, exact hx }, right, rw open_segment_symm at hx, exact ⟨b, a, hb, ha, hx⟩ } end lemma subset_convex_join_left (A B : set E) : A ⊆ convex_join A B := begin rintro x hx, left, left, exact hx, end lemma subset_convex_join_right (A B : set E) : B ⊆ convex_join A B := begin rintro x hx, left, right, exact hx, end lemma convex_join_subset_convex_join_left (hAB : A ⊆ B) (C : set E) : convex_join A C ⊆ convex_join B C := begin rintro x (hx | hx), { left, exact union_subset_union_left C hAB hx }, right, simp only [mem_Union] at ⊢ hx, obtain ⟨a, c, ha, hc, hx⟩ := hx, exact ⟨a, c, hAB ha, hc, hx⟩, end lemma convex_join_subset_convex_join_right (A : set E) (hBC : B ⊆ C) : convex_join A B ⊆ convex_join A C := begin rw [convex_join_comm, convex_join_comm A C], exact convex_join_subset_convex_join_left hBC A, end lemma convex_join_subset_convex_join (hAC : A ⊆ C) (hBD : B ⊆ D) : convex_join A B ⊆ convex_join C D := subset.trans (convex_join_subset_convex_join_left hAC B) (convex_join_subset_convex_join_right C hBD) lemma union_subset_convex_join (A B : set E) : A ∪ B ⊆ convex_join A B := union_subset (subset_convex_join_left A B) (subset_convex_join_right A B) lemma convex_join_empty : convex_join A ∅ = A := begin unfold convex_join, rw union_empty, simp only [Union_false, Union_empty, union_empty], end lemma empty_convex_join : convex_join ∅ B = B := begin rw convex_join_comm, exact convex_join_empty, end lemma segment_subset_convex_join {a b : E} (ha : a ∈ A) (hb : b ∈ B) : segment a b ⊆ convex_join A B := begin rintro x hx, obtain rfl | rfl | hx := eq_left_or_right_or_mem_open_segment_of_mem_segment hx, { exact subset_convex_join_left A B ha }, { exact subset_convex_join_right A B hb }, right, simp only [mem_Union], exact ⟨a, b, ha, hb, hx⟩, end lemma convex_join_eq_of_nonempty (hA : A.nonempty) (hB : B.nonempty) : convex_join A B = ⋃ a b (ha : a ∈ A) (hb : b ∈ B), segment a b := begin ext x, simp only [mem_convex_join_iff, mem_Union], split, { rintro ((hx | hx) | ⟨a, b, ha, hb, hx⟩), { obtain ⟨b, hb⟩ := hB, exact ⟨x, b, hx, hb, left_mem_segment x b⟩ }, { obtain ⟨a, ha⟩ := hA, exact ⟨a, x, ha, hx, right_mem_segment a x⟩ }, exact ⟨a, b, ha, hb, open_segment_subset_segment a b hx⟩ }, rintro ⟨a, b, ha, hb, hx⟩, obtain rfl | (rfl | hx) := eq_left_or_right_or_mem_open_segment_of_mem_segment hx, { left, exact subset_union_left _ _ ha }, { left, exact subset_union_right _ _ hb }, right, exact ⟨a, b, ha, hb, hx⟩, end lemma convex_hull_quadruple {a b c d : E} : convex_join (segment a b) (segment c d) = convex_hull {a, b, c, d} := begin rw [finite.convex_hull_eq, convex_join_eq_of_nonempty ⟨a, left_mem_segment _ _⟩ ⟨c, left_mem_segment _ _⟩], swap, { simp only [finite.insert, finite_singleton] }, ext x, simp only [mem_Union], split, { rintro ⟨y, z, ⟨ya, yb, hya, hyb, hyab, hy⟩, ⟨zc, zd, hzc, hzd, hzcd, hz⟩, ⟨xy, xz, hxy, hxz, hxyz, hx⟩⟩, sorry }, rintro ⟨w, hw₀, hw₁, hx⟩, rw ←hx, let y := (1 - (w b)/(w a + w b)) • a + ((w b)/(w a + w b)) • b, let z := (1 - (w d)/(w c + w d)) • c + ((w d)/(w c + w d)) • d, have hwa : 0 ≤ w a := hw₀ a (by simp only [true_or, eq_self_iff_true, mem_insert_iff]), have hwb : 0 ≤ w b := hw₀ b (by simp only [true_or, or_true, eq_self_iff_true, mem_insert_iff]), have hwc : 0 ≤ w c := hw₀ c (by simp only [true_or, or_true, eq_self_iff_true, mem_insert_iff]), have hwd : 0 ≤ w d := hw₀ d (by simp only [or_true, eq_self_iff_true, mem_insert_iff, mem_singleton_iff]), have hwab : 0 ≤ w a + w b := add_nonneg hwa hwb, have hwcd : 0 ≤ w c + w d := add_nonneg hwc hwd, have hy : y ∈ segment a b, { refine ⟨(1 - (w b)/(w a + w b)), ((w b)/(w a + w b)), _, _, _, rfl⟩, { rw sub_nonneg, exact div_le_one_of_le ((le_add_iff_nonneg_left _).2 hwa) hwab }, { exact div_nonneg hwb hwab }, exact sub_add_cancel 1 _ }, have hz : z ∈ segment c d, { refine ⟨(1 - (w d)/(w c + w d)), ((w d)/(w c + w d)), _, _, _, rfl⟩, { rw sub_nonneg, exact div_le_one_of_le ((le_add_iff_nonneg_left _).2 hwc) hwcd }, { exact div_nonneg hwd hwcd }, exact sub_add_cancel 1 _ }, refine ⟨y, z, hy, hz, w a + w b, w c + w d, hwab, hwcd, _, _⟩, { rw ← hw₁, sorry, }, sorry /-cases A.eq_empty_or_nonempty with hAemp hAnemp, { rw [hAemp, empty_convex_join], exact hB }, cases B.eq_empty_or_nonempty with hBemp hBnemp, { rw [hBemp, convex_join_empty], exact hA }, rw convex_join_eq_of_nonempty hAnemp hBnemp, rintro x y hx hy wx wy hwx hwy hwxy, simp only [mem_Union] at ⊢ hy hx, obtain ⟨ax, bx, hax, hbx, wax, wbx, hwax, hwbx, hwabx, hx⟩ := hx, obtain ⟨ay, b_y, hay, hby, way, wby, hway, hwby, hwaby, hy⟩ := hy, let az := (1 - wy*way/(wx*wax + wy*way)) • ax + (wy*way/(wx*wax + wy*way)) • ay, let bz := (1 - wy*wby/(wx*wbx + wy*wby)) • bx + (wy*wby/(wx*wbx + wy*wby)) • b_y, have da_nonneg : 0 ≤ wx*wax + wy*way := add_nonneg (mul_nonneg hwx hwax) (mul_nonneg hwy hway), have db_nonneg : 0 ≤ wx*wbx + wy*wby := add_nonneg (mul_nonneg hwx hwbx) (mul_nonneg hwy hwby), have haz : az ∈ A, { apply hA hax hay, { rw sub_nonneg, exact div_le_one_of_le ((le_add_iff_nonneg_left _).2 (mul_nonneg hwx hwax)) da_nonneg }, { exact div_nonneg (mul_nonneg hwy hway) da_nonneg }, exact sub_add_cancel 1 _ }, have hbz : bz ∈ B, { apply hB hbx hby, { rw sub_nonneg, exact div_le_one_of_le ((le_add_iff_nonneg_left _).2 (mul_nonneg hwx hwbx)) db_nonneg }, { exact div_nonneg (mul_nonneg hwy hwby) db_nonneg }, exact sub_add_cancel 1 _ }, refine ⟨az, bz, haz, hbz, wx * wax + wy * way, wx * wbx + wy * wby, da_nonneg, db_nonneg, _, _⟩, { calc wx * wax + wy * way + (wx * wbx + wy * wby) = wx * (wax + wbx) + wy * (way + wby) : by ring ... = 1 : by rw [hwabx, hwaby, mul_one, mul_one, hwxy] }, rw [←hx, ←hy], simp,-/ /-rw convex_iff_open_segment_subset at ⊢ hB hA, simp only [mem_convex_join_iff, mem_Union], rintro x y ((hx | hx) | ⟨a, b, ha, hb, hx⟩) hy, --((hy | hy) | ⟨a, b, ha, hb, hy⟩) { obtain ((hy | hy) | ⟨a, b, ha, hb, hy⟩) := hy, exact subset.trans (hA hx hy) (subset_convex_join_left A B), }, { rintro z hz, simp only [mem_convex_join_iff, mem_Union], right, exact ⟨x, y, hx, hy, hz⟩, }, { }-/ end lemma convex_hull_triple {a b c : E} : convex_join (segment a b) {c} = convex_hull {a, b, c} := by rw [←pair_eq_singleton, ←convex_hull_quadruple, segment_same, pair_eq_singleton] lemma convex_convex_join (hA : convex A) (hB : convex B) : convex (convex_join A B) := begin cases A.eq_empty_or_nonempty with hAemp hAnemp, { rw [hAemp, empty_convex_join], exact hB }, cases B.eq_empty_or_nonempty with hBemp hBnemp, { rw [hBemp, convex_join_empty], exact hA }, rw convex_join_eq_of_nonempty hAnemp hBnemp, rw convex_iff_segment_subset at ⊢ hB hA, rintro x y hx hy z hz, simp only [mem_Union] at ⊢ hy hx, obtain ⟨ax, bx, hax, hbx, hx⟩ := hx, obtain ⟨ay, b_y, hay, hby, hy⟩ := hy, have h : z ∈ convex_join (segment ax ay) (segment bx b_y), { have triv : ({ax, ay, bx, b_y} : set E) = {ax, bx, ay, b_y} := by simp only [set.insert_comm], rw [convex_hull_quadruple, triv, ←convex_hull_quadruple], exact segment_subset_convex_join hx hy hz }, rw convex_join_eq_of_nonempty ⟨ax, left_mem_segment _ _⟩ ⟨bx, left_mem_segment _ _⟩ at h, simp only [mem_Union] at h, obtain ⟨az, bz, haz, hbz, hz⟩ := h, exact ⟨az, bz, hA hax hay haz, hB hbx hby hbz, hz⟩, end lemma convex_join_subset_convex_hull_union (A B : set E) : convex_join A B ⊆ convex_hull (A ∪ B) := begin cases A.eq_empty_or_nonempty with hAemp hAnemp, { rw [hAemp, empty_union, empty_convex_join], exact subset_convex_hull B }, cases B.eq_empty_or_nonempty with hBemp hBnemp, { rw [hBemp, union_empty, convex_join_empty], exact subset_convex_hull A }, rw convex_join_eq_of_nonempty hAnemp hBnemp, rintro x hx, simp only [mem_Union] at hx, obtain ⟨a, b, ha, hb, hx⟩ := hx, exact convex_iff_segment_subset.1 (convex_convex_hull _) (convex_hull_mono (subset_union_left _ _) (subset_convex_hull A ha)) (convex_hull_mono (subset_union_right _ _) (subset_convex_hull B hb)) hx, end lemma convex_hull_union_of_convex (hA : convex A) (hB : convex B) : convex_hull (A ∪ B) = convex_join A B := begin apply (convex_hull_min (union_subset_convex_join A B) (convex_convex_join hA hB)).antisymm, exact (convex_join_subset_convex_hull_union A B), end lemma convex_hull_union (A B : set E) : convex_hull (A ∪ B) = convex_join (convex_hull A) (convex_hull B) := begin rw [←convex_hull_convex_hull_union, ←convex_hull_self_union_convex_hull], exact convex_hull_union_of_convex (convex_convex_hull A) (convex_convex_hull B), end lemma convex_hull_insert (hA : A.nonempty) : convex_hull (insert x A) = ⋃ a ∈ convex_hull A, segment x a := begin rw [insert_eq, ←convex_hull_self_union_convex_hull, convex_hull_union_of_convex (convex_singleton x) (convex_convex_hull A), convex_join_eq_of_nonempty (singleton_nonempty x) (convex_hull_nonempty_iff.2 hA)], ext x, simp, end lemma convex_join_min {A B C : set E} (hAC : A ⊆ C) (hBC : B ⊆ C) (hC : convex C) : convex_join A B ⊆ C := begin refine subset.trans (convex_join_subset_convex_join (subset_convex_hull A) (subset_convex_hull B)) _, rw ←convex_hull_union, exact convex_hull_min (union_subset hAC hBC) hC, end
e392bd064b40da9056a438d861ca7138c563955a
e953c38599905267210b87fb5d82dcc3e52a4214
/hott/types/trunc.hlean
fddcd441b629bc6372a404a41c897b52a47ab16d
[ "Apache-2.0" ]
permissive
c-cube/lean
563c1020bff98441c4f8ba60111fef6f6b46e31b
0fb52a9a139f720be418dafac35104468e293b66
refs/heads/master
1,610,753,294,113
1,440,451,356,000
1,440,499,588,000
41,748,334
0
0
null
1,441,122,656,000
1,441,122,656,000
null
UTF-8
Lean
false
false
10,162
hlean
/- Copyright (c) 2015 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Properties of is_trunc and trunctype -/ -- NOTE: the fact that (is_trunc n A) is a mere proposition is proved in .hprop_trunc import types.pi types.eq types.equiv ..function open eq sigma sigma.ops pi function equiv is_trunc.trunctype is_equiv prod is_trunc.trunc_index pointed nat namespace is_trunc variables {A B : Type} {n : trunc_index} definition is_trunc_succ_of_imp_is_trunc_succ (H : A → is_trunc (n.+1) A) : is_trunc (n.+1) A := @is_trunc_succ_intro _ _ (λx y, @is_trunc_eq _ _ (H x) x y) definition is_trunc_of_imp_is_trunc_of_leq (Hn : -1 ≤ n) (H : A → is_trunc n A) : is_trunc n A := trunc_index.rec_on n (λHn H, empty.rec _ Hn) (λn IH Hn, is_trunc_succ_of_imp_is_trunc_succ) Hn H /- theorems about trunctype -/ protected definition trunctype.sigma_char.{l} (n : trunc_index) : (trunctype.{l} n) ≃ (Σ (A : Type.{l}), is_trunc n A) := begin fapply equiv.MK, { intro A, exact (⟨carrier A, struct A⟩)}, { intro S, exact (trunctype.mk S.1 S.2)}, { intro S, induction S with S1 S2, reflexivity}, { intro A, induction A with A1 A2, reflexivity}, end definition trunctype_eq_equiv (n : trunc_index) (A B : n-Type) : (A = B) ≃ (carrier A = carrier B) := calc (A = B) ≃ (to_fun (trunctype.sigma_char n) A = to_fun (trunctype.sigma_char n) B) : eq_equiv_fn_eq_of_equiv ... ≃ ((to_fun (trunctype.sigma_char n) A).1 = (to_fun (trunctype.sigma_char n) B).1) : equiv.symm (!equiv_subtype) ... ≃ (carrier A = carrier B) : equiv.refl definition is_trunc_is_embedding_closed (f : A → B) [Hf : is_embedding f] [HB : is_trunc n B] (Hn : -1 ≤ n) : is_trunc n A := begin induction n with n, {exact !empty.elim Hn}, {apply is_trunc_succ_intro, intro a a', fapply @is_trunc_is_equiv_closed_rev _ _ n (ap f)} end definition is_trunc_is_retraction_closed (f : A → B) [Hf : is_retraction f] (n : trunc_index) [HA : is_trunc n A] : is_trunc n B := begin revert A B f Hf HA, induction n with n IH, { intro A B f Hf HA, induction Hf with g ε, fapply is_contr.mk, { exact f (center A)}, { intro b, apply concat, { apply (ap f), exact (center_eq (g b))}, { apply ε}}}, { intro A B f Hf HA, induction Hf with g ε, apply is_trunc_succ_intro, intro b b', fapply (IH (g b = g b')), { intro q, exact ((ε b)⁻¹ ⬝ ap f q ⬝ ε b')}, { apply (is_retraction.mk (ap g)), { intro p, induction p, {rewrite [↑ap, con.left_inv]}}}, { apply is_trunc_eq}} end definition is_embedding_to_fun (A B : Type) : is_embedding (@to_fun A B) := is_embedding.mk (λf f', !is_equiv_ap_to_fun) definition is_trunc_trunctype [instance] (n : trunc_index) : is_trunc n.+1 (n-Type) := begin apply is_trunc_succ_intro, intro X Y, fapply is_trunc_equiv_closed, {apply equiv.symm, apply trunctype_eq_equiv}, fapply is_trunc_equiv_closed, {apply equiv.symm, apply eq_equiv_equiv}, induction n, {apply @is_contr_of_inhabited_hprop, {apply is_trunc_is_embedding_closed, {apply is_embedding_to_fun} , {exact unit.star}}, {apply equiv_of_is_contr_of_is_contr}}, {apply is_trunc_is_embedding_closed, {apply is_embedding_to_fun}, {exact unit.star}} end /- theorems about decidable equality and axiom K -/ definition is_hset_of_axiom_K {A : Type} (K : Π{a : A} (p : a = a), p = idp) : is_hset A := is_hset.mk _ (λa b p q, eq.rec_on q K p) theorem is_hset_of_relation.{u} {A : Type.{u}} (R : A → A → Type.{u}) (mere : Π(a b : A), is_hprop (R a b)) (refl : Π(a : A), R a a) (imp : Π{a b : A}, R a b → a = b) : is_hset A := is_hset_of_axiom_K (λa p, have H2 : transport (λx, R a x → a = x) p (@imp a a) = @imp a a, from !apd, have H3 : Π(r : R a a), transport (λx, a = x) p (imp r) = imp (transport (λx, R a x) p r), from to_fun (equiv.symm !heq_pi) H2, have H4 : imp (refl a) ⬝ p = imp (refl a), from calc imp (refl a) ⬝ p = transport (λx, a = x) p (imp (refl a)) : transport_eq_r ... = imp (transport (λx, R a x) p (refl a)) : H3 ... = imp (refl a) : is_hprop.elim, cancel_left H4) definition relation_equiv_eq {A : Type} (R : A → A → Type) (mere : Π(a b : A), is_hprop (R a b)) (refl : Π(a : A), R a a) (imp : Π{a b : A}, R a b → a = b) (a b : A) : R a b ≃ a = b := @equiv_of_is_hprop _ _ _ (@is_trunc_eq _ _ (is_hset_of_relation R mere refl @imp) a b) imp (λp, p ▸ refl a) local attribute not [reducible] definition is_hset_of_double_neg_elim {A : Type} (H : Π(a b : A), ¬¬a = b → a = b) : is_hset A := is_hset_of_relation (λa b, ¬¬a = b) _ (λa n, n idp) H section open decidable --this is proven differently in init.hedberg definition is_hset_of_decidable_eq (A : Type) [H : decidable_eq A] : is_hset A := is_hset_of_double_neg_elim (λa b, by_contradiction) end definition is_trunc_of_axiom_K_of_leq {A : Type} (n : trunc_index) (H : -1 ≤ n) (K : Π(a : A), is_trunc n (a = a)) : is_trunc (n.+1) A := @is_trunc_succ_intro _ _ (λa b, is_trunc_of_imp_is_trunc_of_leq H (λp, eq.rec_on p !K)) definition is_trunc_succ_of_is_trunc_loop (Hn : -1 ≤ n) (Hp : Π(a : A), is_trunc n (a = a)) : is_trunc (n.+1) A := begin apply is_trunc_succ_intro, intros a a', apply is_trunc_of_imp_is_trunc_of_leq Hn, intro p, induction p, apply Hp end definition is_trunc_succ_iff_is_trunc_loop (A : Type) (Hn : -1 ≤ n) : is_trunc (n.+1) A ↔ Π(a : A), is_trunc n (a = a) := iff.intro _ (is_trunc_succ_of_is_trunc_loop Hn) definition is_trunc_iff_is_contr_loop_succ (n : ℕ) (A : Type) : is_trunc n A ↔ Π(a : A), is_contr (Ω[succ n](Pointed.mk a)) := begin revert A, induction n with n IH, { intros, esimp [Iterated_loop_space], apply iff.intro, { intros H a, apply is_contr.mk idp, apply is_hprop.elim}, { intro H, apply is_hset_of_axiom_K, intros, apply is_hprop.elim}}, { intros, transitivity _, apply @is_trunc_succ_iff_is_trunc_loop n, constructor, apply iff.pi_iff_pi, intros, transitivity _, apply IH, assert H : Πp : a = a, Ω(Pointed.mk p) = Ω(Pointed.mk (idpath a)), { intros, fapply Pointed_eq, { esimp, transitivity _, apply eq_equiv_fn_eq_of_equiv (equiv_eq_closed_right _ p⁻¹), esimp, apply eq_equiv_eq_closed, apply con.right_inv, apply con.right_inv}, { esimp, apply con.left_inv}}, transitivity _, apply iff.pi_iff_pi, intro p, rewrite [↑Iterated_loop_space,H], apply iff.refl, apply iff.imp_iff, reflexivity} end definition is_trunc_iff_is_contr_loop (n : ℕ) (A : Type) : is_trunc (n.-2.+1) A ↔ (Π(a : A), is_contr (Ω[n](pointed.Mk a))) := begin induction n with n, { esimp [sub_two,Iterated_loop_space], apply iff.intro, intro H a, exact is_contr_of_inhabited_hprop a, intro H, apply is_hprop_of_imp_is_contr, exact H}, { apply is_trunc_iff_is_contr_loop_succ}, end end is_trunc open is_trunc namespace trunc variable {A : Type} protected definition code (n : trunc_index) (aa aa' : trunc n.+1 A) : n-Type := trunc.rec_on aa (λa, trunc.rec_on aa' (λa', trunctype.mk' n (trunc n (a = a')))) protected definition encode (n : trunc_index) (aa aa' : trunc n.+1 A) : aa = aa' → trunc.code n aa aa' := begin intro p, induction p, apply (trunc.rec_on aa), intro a, esimp [trunc.code,trunc.rec_on], exact (tr idp) end protected definition decode (n : trunc_index) (aa aa' : trunc n.+1 A) : trunc.code n aa aa' → aa = aa' := begin eapply (trunc.rec_on aa'), eapply (trunc.rec_on aa), intro a a' x, esimp [trunc.code, trunc.rec_on] at x, apply (trunc.rec_on x), intro p, exact (ap tr p) end definition trunc_eq_equiv (n : trunc_index) (aa aa' : trunc n.+1 A) : aa = aa' ≃ trunc.code n aa aa' := begin fapply equiv.MK, { apply trunc.encode}, { apply trunc.decode}, { eapply (trunc.rec_on aa'), eapply (trunc.rec_on aa), intro a a' x, esimp [trunc.code, trunc.rec_on] at x, refine (@trunc.rec_on n _ _ x _ _), intro x, apply is_trunc_eq, intro p, induction p, reflexivity}, { intro p, induction p, apply (trunc.rec_on aa), intro a, exact idp}, end definition tr_eq_tr_equiv (n : trunc_index) (a a' : A) : (tr a = tr a' :> trunc n.+1 A) ≃ trunc n (a = a') := !trunc_eq_equiv definition is_trunc_trunc_of_is_trunc [instance] [priority 500] (A : Type) (n m : trunc_index) [H : is_trunc n A] : is_trunc n (trunc m A) := begin revert A m H, eapply (trunc_index.rec_on n), { clear n, intro A m H, apply is_contr_equiv_closed, { apply equiv_trunc, apply (@is_trunc_of_leq _ -2), exact unit.star} }, { clear n, intro n IH A m H, induction m with m, { apply (@is_trunc_of_leq _ -2), exact unit.star}, { apply is_trunc_succ_intro, intro aa aa', apply (@trunc.rec_on _ _ _ aa (λy, !is_trunc_succ_of_is_hprop)), eapply (@trunc.rec_on _ _ _ aa' (λy, !is_trunc_succ_of_is_hprop)), intro a a', apply (is_trunc_equiv_closed_rev), { apply tr_eq_tr_equiv}, { exact (IH _ _ _)}}} end end trunc open trunc namespace function variables {A B : Type} definition is_surjective_of_is_equiv [instance] (f : A → B) [H : is_equiv f] : is_surjective f := is_surjective.mk (λb, !center) definition is_equiv_equiv_is_embedding_times_is_surjective (f : A → B) : is_equiv f ≃ (is_embedding f × is_surjective f) := equiv_of_is_hprop (λH, (_, _)) (λP, prod.rec_on P (λH₁ H₂, !is_equiv_of_is_surjective_of_is_embedding)) end function
48a806efd781cebdb1484e36ba0ea05dcad7752d
9dc8cecdf3c4634764a18254e94d43da07142918
/src/number_theory/padics/ring_homs.lean
3172279bbab2727f014ce5aa90046437763c7eb3
[ "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
24,058
lean
/- Copyright (c) 2020 Johan Commelin, Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Robert Y. Lewis -/ import data.zmod.basic import number_theory.padics.padic_integers /-! # Relating `ℤ_[p]` to `zmod (p ^ n)` In this file we establish connections between the `p`-adic integers $\mathbb{Z}_p$ and the integers modulo powers of `p`, $\mathbb{Z}/p^n\mathbb{Z}$. ## Main declarations We show that $\mathbb{Z}_p$ has a ring hom to $\mathbb{Z}/p^n\mathbb{Z}$ for each `n`. The case for `n = 1` is handled separately, since it is used in the general construction and we may want to use it without the `^1` getting in the way. * `padic_int.to_zmod`: ring hom to `zmod p` * `padic_int.to_zmod_pow`: ring hom to `zmod (p^n)` * `padic_int.ker_to_zmod` / `padic_int.ker_to_zmod_pow`: the kernels of these maps are the ideals generated by `p^n` We also establish the universal property of $\mathbb{Z}_p$ as a projective limit. Given a family of compatible ring homs $f_k : R \to \mathbb{Z}/p^n\mathbb{Z}$, there is a unique limit $R \to \mathbb{Z}_p$. * `padic_int.lift`: the limit function * `padic_int.lift_spec` / `padic_int.lift_unique`: the universal property ## Implementation notes The ring hom constructions go through an auxiliary constructor `padic_int.to_zmod_hom`, which removes some boilerplate code. -/ noncomputable theory open_locale classical open nat local_ring padic namespace padic_int variables {p : ℕ} [hp_prime : fact p.prime] include hp_prime section ring_homs /-! ### Ring homomorphisms to `zmod p` and `zmod (p ^ n)` -/ variables (p) (r : ℚ) omit hp_prime /-- `mod_part p r` is an integer that satisfies `∥(r - mod_part p r : ℚ_[p])∥ < 1` when `∥(r : ℚ_[p])∥ ≤ 1`, see `padic_int.norm_sub_mod_part`. It is the unique non-negative integer that is `< p` with this property. (Note that this definition assumes `r : ℚ`. See `padic_int.zmod_repr` for a version that takes values in `ℕ` and works for arbitrary `x : ℤ_[p]`.) -/ def mod_part : ℤ := (r.num * gcd_a r.denom p) % p include hp_prime variable {p} lemma mod_part_lt_p : mod_part p r < p := begin convert int.mod_lt _ _, { simp }, { exact_mod_cast hp_prime.1.ne_zero } end lemma mod_part_nonneg : 0 ≤ mod_part p r := int.mod_nonneg _ $ by exact_mod_cast hp_prime.1.ne_zero lemma is_unit_denom (r : ℚ) (h : ∥(r : ℚ_[p])∥ ≤ 1) : is_unit (r.denom : ℤ_[p]) := begin rw is_unit_iff, apply le_antisymm (r.denom : ℤ_[p]).2, rw [← not_lt, val_eq_coe, coe_nat_cast], intro norm_denom_lt, have hr : ∥(r * r.denom : ℚ_[p])∥ = ∥(r.num : ℚ_[p])∥, { rw_mod_cast @rat.mul_denom_eq_num r, refl, }, rw padic_norm_e.mul at hr, have key : ∥(r.num : ℚ_[p])∥ < 1, { calc _ = _ : hr.symm ... < 1 * 1 : mul_lt_mul' h norm_denom_lt (norm_nonneg _) zero_lt_one ... = 1 : mul_one 1 }, have : ↑p ∣ r.num ∧ (p : ℤ) ∣ r.denom, { simp only [← norm_int_lt_one_iff_dvd, ← padic_norm_e_of_padic_int], norm_cast, exact ⟨key, norm_denom_lt⟩ }, apply hp_prime.1.not_dvd_one, rwa [← r.cop.gcd_eq_one, nat.dvd_gcd_iff, ← int.coe_nat_dvd_left, ← int.coe_nat_dvd], end lemma norm_sub_mod_part_aux (r : ℚ) (h : ∥(r : ℚ_[p])∥ ≤ 1) : ↑p ∣ r.num - r.num * r.denom.gcd_a p % p * ↑(r.denom) := begin rw ← zmod.int_coe_zmod_eq_zero_iff_dvd, simp only [int.cast_coe_nat, zmod.nat_cast_mod, int.cast_mul, int.cast_sub], have := congr_arg (coe : ℤ → zmod p) (gcd_eq_gcd_ab r.denom p), simp only [int.cast_coe_nat, add_zero, int.cast_add, zmod.nat_cast_self, int.cast_mul, zero_mul] at this, push_cast, rw [mul_right_comm, mul_assoc, ←this], suffices rdcp : r.denom.coprime p, { rw rdcp.gcd_eq_one, simp only [mul_one, cast_one, sub_self], }, apply coprime.symm, apply (coprime_or_dvd_of_prime hp_prime.1 _).resolve_right, rw [← int.coe_nat_dvd, ← norm_int_lt_one_iff_dvd, not_lt], apply ge_of_eq, rw ← is_unit_iff, exact is_unit_denom r h, end lemma norm_sub_mod_part (h : ∥(r : ℚ_[p])∥ ≤ 1) : ∥(⟨r,h⟩ - mod_part p r : ℤ_[p])∥ < 1 := begin let n := mod_part p r, rw [norm_lt_one_iff_dvd, ← (is_unit_denom r h).dvd_mul_right], suffices : ↑p ∣ r.num - n * r.denom, { convert (int.cast_ring_hom ℤ_[p]).map_dvd this, simp only [sub_mul, int.cast_coe_nat, eq_int_cast, int.cast_mul, sub_left_inj, int.cast_sub], apply subtype.coe_injective, simp only [coe_mul, subtype.coe_mk, coe_nat_cast], rw_mod_cast @rat.mul_denom_eq_num r, refl }, exact norm_sub_mod_part_aux r h end lemma exists_mem_range_of_norm_rat_le_one (h : ∥(r : ℚ_[p])∥ ≤ 1) : ∃ n : ℤ, 0 ≤ n ∧ n < p ∧ ∥(⟨r,h⟩ - n : ℤ_[p])∥ < 1 := ⟨mod_part p r, mod_part_nonneg _, mod_part_lt_p _, norm_sub_mod_part _ h⟩ lemma zmod_congr_of_sub_mem_span_aux (n : ℕ) (x : ℤ_[p]) (a b : ℤ) (ha : x - a ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) (hb : x - b ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) : (a : zmod (p ^ n)) = b := begin rw [ideal.mem_span_singleton] at ha hb, rw [← sub_eq_zero, ← int.cast_sub, zmod.int_coe_zmod_eq_zero_iff_dvd, int.coe_nat_pow], rw [← dvd_neg, neg_sub] at ha, have := dvd_add ha hb, rwa [sub_eq_add_neg, sub_eq_add_neg, add_assoc, neg_add_cancel_left, ← sub_eq_add_neg, ← int.cast_sub, pow_p_dvd_int_iff] at this, end lemma zmod_congr_of_sub_mem_span (n : ℕ) (x : ℤ_[p]) (a b : ℕ) (ha : x - a ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) (hb : x - b ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) : (a : zmod (p ^ n)) = b := by simpa using zmod_congr_of_sub_mem_span_aux n x a b ha hb lemma zmod_congr_of_sub_mem_max_ideal (x : ℤ_[p]) (m n : ℕ) (hm : x - m ∈ maximal_ideal ℤ_[p]) (hn : x - n ∈ maximal_ideal ℤ_[p]) : (m : zmod p) = n := begin rw maximal_ideal_eq_span_p at hm hn, have := zmod_congr_of_sub_mem_span_aux 1 x m n, simp only [pow_one] at this, specialize this hm hn, apply_fun zmod.cast_hom (show p ∣ p ^ 1, by rw pow_one) (zmod p) at this, simp only [map_int_cast] at this, simpa only [int.cast_coe_nat] using this end variable (x : ℤ_[p]) lemma exists_mem_range : ∃ n : ℕ, n < p ∧ (x - n ∈ maximal_ideal ℤ_[p]) := begin simp only [maximal_ideal_eq_span_p, ideal.mem_span_singleton, ← norm_lt_one_iff_dvd], obtain ⟨r, hr⟩ := rat_dense (x : ℚ_[p]) zero_lt_one, have H : ∥(r : ℚ_[p])∥ ≤ 1, { rw norm_sub_rev at hr, calc _ = ∥(r : ℚ_[p]) - x + x∥ : by ring_nf ... ≤ _ : padic_norm_e.nonarchimedean _ _ ... ≤ _ : max_le (le_of_lt hr) x.2 }, obtain ⟨n, hzn, hnp, hn⟩ := exists_mem_range_of_norm_rat_le_one r H, lift n to ℕ using hzn, use n, split, {exact_mod_cast hnp}, simp only [norm_def, coe_sub, subtype.coe_mk, coe_nat_cast] at hn ⊢, rw show (x - n : ℚ_[p]) = (x - r) + (r - n), by ring, apply lt_of_le_of_lt (padic_norm_e.nonarchimedean _ _), apply max_lt hr, simpa using hn end /-- `zmod_repr x` is the unique natural number smaller than `p` satisfying `∥(x - zmod_repr x : ℤ_[p])∥ < 1`. -/ def zmod_repr : ℕ := classical.some (exists_mem_range x) lemma zmod_repr_spec : zmod_repr x < p ∧ (x - zmod_repr x ∈ maximal_ideal ℤ_[p]) := classical.some_spec (exists_mem_range x) lemma zmod_repr_lt_p : zmod_repr x < p := (zmod_repr_spec _).1 lemma sub_zmod_repr_mem : (x - zmod_repr x ∈ maximal_ideal ℤ_[p]) := (zmod_repr_spec _).2 /-- `to_zmod_hom` is an auxiliary constructor for creating ring homs from `ℤ_[p]` to `zmod v`. -/ def to_zmod_hom (v : ℕ) (f : ℤ_[p] → ℕ) (f_spec : ∀ x, x - f x ∈ (ideal.span {v} : ideal ℤ_[p])) (f_congr : ∀ (x : ℤ_[p]) (a b : ℕ), x - a ∈ (ideal.span {v} : ideal ℤ_[p]) → x - b ∈ (ideal.span {v} : ideal ℤ_[p]) → (a : zmod v) = b) : ℤ_[p] →+* zmod v := { to_fun := λ x, f x, map_zero' := begin rw [f_congr (0 : ℤ_[p]) _ 0, cast_zero], { exact f_spec _ }, { simp only [sub_zero, cast_zero, submodule.zero_mem], } end, map_one' := begin rw [f_congr (1 : ℤ_[p]) _ 1, cast_one], { exact f_spec _ }, { simp only [sub_self, cast_one, submodule.zero_mem], } end, map_add' := begin intros x y, rw [f_congr (x + y) _ (f x + f y), cast_add], { exact f_spec _ }, { convert ideal.add_mem _ (f_spec x) (f_spec y), rw cast_add, ring, } end, map_mul' := begin intros x y, rw [f_congr (x * y) _ (f x * f y), cast_mul], { exact f_spec _ }, { let I : ideal ℤ_[p] := ideal.span {v}, convert I.add_mem (I.mul_mem_left x (f_spec y)) (I.mul_mem_right (f y) (f_spec x)), rw cast_mul, ring, } end, } /-- `to_zmod` is a ring hom from `ℤ_[p]` to `zmod p`, with the equality `to_zmod x = (zmod_repr x : zmod p)`. -/ def to_zmod : ℤ_[p] →+* zmod p := to_zmod_hom p zmod_repr (by { rw ←maximal_ideal_eq_span_p, exact sub_zmod_repr_mem }) (by { rw ←maximal_ideal_eq_span_p, exact zmod_congr_of_sub_mem_max_ideal } ) /-- `z - (to_zmod z : ℤ_[p])` is contained in the maximal ideal of `ℤ_[p]`, for every `z : ℤ_[p]`. The coercion from `zmod p` to `ℤ_[p]` is `zmod.has_coe_t`, which coerces `zmod p` into artibrary rings. This is unfortunate, but a consequence of the fact that we allow `zmod p` to coerce to rings of arbitrary characteristic, instead of only rings of characteristic `p`. This coercion is only a ring homomorphism if it coerces into a ring whose characteristic divides `p`. While this is not the case here we can still make use of the coercion. -/ lemma to_zmod_spec (z : ℤ_[p]) : z - (to_zmod z : ℤ_[p]) ∈ maximal_ideal ℤ_[p] := begin convert sub_zmod_repr_mem z using 2, dsimp [to_zmod, to_zmod_hom], unfreezingI { rcases (exists_eq_add_of_lt (hp_prime.1.pos)) with ⟨p', rfl⟩ }, change ↑(zmod.val _) = _, simp only [zmod.val_nat_cast, add_zero, add_def, nat.cast_inj, zero_add], apply mod_eq_of_lt, simpa only [zero_add] using zmod_repr_lt_p z, end lemma ker_to_zmod : (to_zmod : ℤ_[p] →+* zmod p).ker = maximal_ideal ℤ_[p] := begin ext x, rw ring_hom.mem_ker, split, { intro h, simpa only [h, zmod.cast_zero, sub_zero] using to_zmod_spec x, }, { intro h, rw ← sub_zero x at h, dsimp [to_zmod, to_zmod_hom], convert zmod_congr_of_sub_mem_max_ideal x _ 0 _ h, norm_cast, apply sub_zmod_repr_mem, } end /-- `appr n x` gives a value `v : ℕ` such that `x` and `↑v : ℤ_p` are congruent mod `p^n`. See `appr_spec`. -/ noncomputable def appr : ℤ_[p] → ℕ → ℕ | x 0 := 0 | x (n+1) := let y := x - appr x n in if hy : y = 0 then appr x n else let u := unit_coeff hy in appr x n + p ^ n * (to_zmod ((u : ℤ_[p]) * (p ^ (y.valuation - n).nat_abs))).val lemma appr_lt (x : ℤ_[p]) (n : ℕ) : x.appr n < p ^ n := begin induction n with n ih generalizing x, { simp only [appr, succ_pos', pow_zero], }, simp only [appr, map_nat_cast, zmod.nat_cast_self, ring_hom.map_pow, int.nat_abs, ring_hom.map_mul], have hp : p ^ n < p ^ (n + 1), { apply pow_lt_pow hp_prime.1.one_lt (lt_add_one n) }, split_ifs with h, { apply lt_trans (ih _) hp, }, { calc _ < p ^ n + p ^ n * (p - 1) : _ ... = p ^ (n + 1) : _, { apply add_lt_add_of_lt_of_le (ih _), apply nat.mul_le_mul_left, apply le_pred_of_lt, apply zmod.val_lt }, { rw [mul_tsub, mul_one, ← pow_succ'], apply add_tsub_cancel_of_le (le_of_lt hp) } } end lemma appr_mono (x : ℤ_[p]) : monotone x.appr := begin apply monotone_nat_of_le_succ, intro n, dsimp [appr], split_ifs, { refl, }, apply nat.le_add_right, end lemma dvd_appr_sub_appr (x : ℤ_[p]) (m n : ℕ) (h : m ≤ n) : p ^ m ∣ x.appr n - x.appr m := begin obtain ⟨k, rfl⟩ := nat.exists_eq_add_of_le h, clear h, induction k with k ih, { simp only [add_zero, tsub_self, dvd_zero], }, rw [nat.succ_eq_add_one, ← add_assoc], dsimp [appr], split_ifs with h, { exact ih }, rw [add_comm, add_tsub_assoc_of_le (appr_mono _ (nat.le_add_right m k))], apply dvd_add _ ih, apply dvd_mul_of_dvd_left, apply pow_dvd_pow _ (nat.le_add_right m k), end lemma appr_spec (n : ℕ) : ∀ (x : ℤ_[p]), x - appr x n ∈ (ideal.span {p^n} : ideal ℤ_[p]) := begin simp only [ideal.mem_span_singleton], induction n with n ih, { simp only [is_unit_one, is_unit.dvd, pow_zero, forall_true_iff], }, intro x, dsimp only [appr], split_ifs with h, { rw h, apply dvd_zero }, push_cast, rw sub_add_eq_sub_sub, obtain ⟨c, hc⟩ := ih x, simp only [map_nat_cast, zmod.nat_cast_self, ring_hom.map_pow, ring_hom.map_mul, zmod.nat_cast_val], have hc' : c ≠ 0, { rintro rfl, simp only [mul_zero] at hc, contradiction }, conv_rhs { congr, simp only [hc], }, rw show (x - ↑(appr x n)).valuation = (↑p ^ n * c).valuation, { rw hc }, rw [valuation_p_pow_mul _ _ hc', add_sub_cancel', pow_succ', ← mul_sub], apply mul_dvd_mul_left, obtain hc0 | hc0 := c.valuation.nat_abs.eq_zero_or_pos, { simp only [hc0, mul_one, pow_zero], rw [mul_comm, unit_coeff_spec h] at hc, suffices : c = unit_coeff h, { rw [← this, ← ideal.mem_span_singleton, ← maximal_ideal_eq_span_p], apply to_zmod_spec }, obtain ⟨c, rfl⟩ : is_unit c, -- TODO: write a can_lift instance for units { rw int.nat_abs_eq_zero at hc0, rw [is_unit_iff, norm_eq_pow_val hc', hc0, neg_zero, zpow_zero], }, rw discrete_valuation_ring.unit_mul_pow_congr_unit _ _ _ _ _ hc, exact irreducible_p }, { rw zero_pow hc0, simp only [sub_zero, zmod.cast_zero, mul_zero], rw unit_coeff_spec hc', exact (dvd_pow_self (p : ℤ_[p]) hc0.ne').mul_left _, }, end attribute [irreducible] appr /-- A ring hom from `ℤ_[p]` to `zmod (p^n)`, with underlying function `padic_int.appr n`. -/ def to_zmod_pow (n : ℕ) : ℤ_[p] →+* zmod (p ^ n) := to_zmod_hom (p^n) (λ x, appr x n) (by { intros, convert appr_spec n _ using 1, simp }) (by { intros x a b ha hb, apply zmod_congr_of_sub_mem_span n x a b, { simpa using ha }, { simpa using hb } }) lemma ker_to_zmod_pow (n : ℕ) : (to_zmod_pow n : ℤ_[p] →+* zmod (p ^ n)).ker = ideal.span {p ^ n} := begin ext x, rw ring_hom.mem_ker, split, { intro h, suffices : x.appr n = 0, { convert appr_spec n x, simp only [this, sub_zero, cast_zero], }, dsimp [to_zmod_pow, to_zmod_hom] at h, rw zmod.nat_coe_zmod_eq_zero_iff_dvd at h, apply eq_zero_of_dvd_of_lt h (appr_lt _ _), }, { intro h, rw ← sub_zero x at h, dsimp [to_zmod_pow, to_zmod_hom], rw [zmod_congr_of_sub_mem_span n x _ 0 _ h, cast_zero], apply appr_spec, } end @[simp] lemma zmod_cast_comp_to_zmod_pow (m n : ℕ) (h : m ≤ n) : (zmod.cast_hom (pow_dvd_pow p h) (zmod (p ^ m))).comp (to_zmod_pow n) = to_zmod_pow m := begin apply zmod.ring_hom_eq_of_ker_eq, ext x, rw [ring_hom.mem_ker, ring_hom.mem_ker], simp only [function.comp_app, zmod.cast_hom_apply, ring_hom.coe_comp], simp only [to_zmod_pow, to_zmod_hom, ring_hom.coe_mk], rw [zmod.cast_nat_cast (pow_dvd_pow p h), zmod_congr_of_sub_mem_span m (x.appr n) (x.appr n) (x.appr m)], { rw [sub_self], apply ideal.zero_mem _, }, { rw ideal.mem_span_singleton, rcases dvd_appr_sub_appr x m n h with ⟨c, hc⟩, use c, rw [← nat.cast_sub (appr_mono _ h), hc, nat.cast_mul, nat.cast_pow], }, { apply_instance } end @[simp] lemma cast_to_zmod_pow (m n : ℕ) (h : m ≤ n) (x : ℤ_[p]) : ↑(to_zmod_pow n x) = to_zmod_pow m x := by { rw ← zmod_cast_comp_to_zmod_pow _ _ h, refl } lemma dense_range_nat_cast : dense_range (nat.cast : ℕ → ℤ_[p]) := begin intro x, rw metric.mem_closure_range_iff, intros ε hε, obtain ⟨n, hn⟩ := exists_pow_neg_lt p hε, use (x.appr n), rw dist_eq_norm, apply lt_of_le_of_lt _ hn, rw norm_le_pow_iff_mem_span_pow, apply appr_spec, end lemma dense_range_int_cast : dense_range (int.cast : ℤ → ℤ_[p]) := begin intro x, apply dense_range_nat_cast.induction_on x, { exact is_closed_closure, }, { intro a, change (a.cast : ℤ_[p]) with (a : ℤ).cast, apply subset_closure, exact set.mem_range_self _ } end end ring_homs section lift /-! ### Universal property as projective limit -/ open cau_seq padic_seq variables {R : Type*} [non_assoc_semiring R] (f : Π k : ℕ, R →+* zmod (p^k)) (f_compat : ∀ k1 k2 (hk : k1 ≤ k2), (zmod.cast_hom (pow_dvd_pow p hk) _).comp (f k2) = f k1) omit hp_prime /-- Given a family of ring homs `f : Π n : ℕ, R →+* zmod (p ^ n)`, `nth_hom f r` is an integer-valued sequence whose `n`th value is the unique integer `k` such that `0 ≤ k < p ^ n` and `f n r = (k : zmod (p ^ n))`. -/ def nth_hom (r : R) : ℕ → ℤ := λ n, (f n r : zmod (p^n)).val @[simp] lemma nth_hom_zero : nth_hom f 0 = 0 := by simp [nth_hom]; refl variable {f} include hp_prime include f_compat lemma pow_dvd_nth_hom_sub (r : R) (i j : ℕ) (h : i ≤ j) : ↑p ^ i ∣ nth_hom f r j - nth_hom f r i := begin specialize f_compat i j h, rw [← int.coe_nat_pow, ← zmod.int_coe_zmod_eq_zero_iff_dvd, int.cast_sub], dsimp [nth_hom], rw [← f_compat, ring_hom.comp_apply], simp only [zmod.cast_id, zmod.cast_hom_apply, sub_self, zmod.nat_cast_val, zmod.int_cast_cast], end lemma is_cau_seq_nth_hom (r : R): is_cau_seq (padic_norm p) (λ n, nth_hom f r n) := begin intros ε hε, obtain ⟨k, hk⟩ : ∃ k : ℕ, (p ^ - (↑(k : ℕ) : ℤ) : ℚ) < ε := exists_pow_neg_lt_rat p hε, use k, intros j hj, refine lt_of_le_of_lt _ hk, norm_cast, rw ← padic_norm.dvd_iff_norm_le, exact_mod_cast pow_dvd_nth_hom_sub f_compat r k j hj end /-- `nth_hom_seq f_compat r` bundles `padic_int.nth_hom f r` as a Cauchy sequence of rationals with respect to the `p`-adic norm. The `n`th value of the sequence is `((f n r).val : ℚ)`. -/ def nth_hom_seq (r : R) : padic_seq p := ⟨λ n, nth_hom f r n, is_cau_seq_nth_hom f_compat r⟩ -- this lemma ran into issues after changing to `ne_zero` and I'm not sure why. lemma nth_hom_seq_one : nth_hom_seq f_compat 1 ≈ 1 := begin intros ε hε, change _ < _ at hε, use 1, intros j hj, haveI : fact (1 < p ^ j) := ⟨nat.one_lt_pow _ _ (by linarith) hp_prime.1.one_lt⟩, suffices : ((1 : zmod (p ^ j)) : ℚ) = 1, by simp [nth_hom_seq, nth_hom, this, hε], rw [zmod.cast_eq_val, zmod.val_one, nat.cast_one] end lemma nth_hom_seq_add (r s : R) : nth_hom_seq f_compat (r + s) ≈ nth_hom_seq f_compat r + nth_hom_seq f_compat s := begin intros ε hε, obtain ⟨n, hn⟩ := exists_pow_neg_lt_rat p hε, use n, intros j hj, dsimp [nth_hom_seq], apply lt_of_le_of_lt _ hn, rw [← int.cast_add, ← int.cast_sub, ← padic_norm.dvd_iff_norm_le, ← zmod.int_coe_zmod_eq_zero_iff_dvd], dsimp [nth_hom], simp only [zmod.nat_cast_val, ring_hom.map_add, int.cast_sub, zmod.int_cast_cast, int.cast_add], rw [zmod.cast_add (show p^n ∣ p^j, from pow_dvd_pow _ hj), sub_self], { apply_instance }, end lemma nth_hom_seq_mul (r s : R) : nth_hom_seq f_compat (r * s) ≈ nth_hom_seq f_compat r * nth_hom_seq f_compat s := begin intros ε hε, obtain ⟨n, hn⟩ := exists_pow_neg_lt_rat p hε, use n, intros j hj, dsimp [nth_hom_seq], apply lt_of_le_of_lt _ hn, rw [← int.cast_mul, ← int.cast_sub, ← padic_norm.dvd_iff_norm_le, ← zmod.int_coe_zmod_eq_zero_iff_dvd], dsimp [nth_hom], simp only [zmod.nat_cast_val, ring_hom.map_mul, int.cast_sub, zmod.int_cast_cast, int.cast_mul], rw [zmod.cast_mul (show p^n ∣ p^j, from pow_dvd_pow _ hj), sub_self], { apply_instance }, end /-- `lim_nth_hom f_compat r` is the limit of a sequence `f` of compatible ring homs `R →+* zmod (p^k)`. This is itself a ring hom: see `padic_int.lift`. -/ def lim_nth_hom (r : R) : ℤ_[p] := of_int_seq (nth_hom f r) (is_cau_seq_nth_hom f_compat r) lemma lim_nth_hom_spec (r : R) : ∀ ε : ℝ, 0 < ε → ∃ N : ℕ, ∀ n ≥ N, ∥lim_nth_hom f_compat r - nth_hom f r n∥ < ε := begin intros ε hε, obtain ⟨ε', hε'0, hε'⟩ : ∃ v : ℚ, (0 : ℝ) < v ∧ ↑v < ε := exists_rat_btwn hε, norm_cast at hε'0, obtain ⟨N, hN⟩ := padic_norm_e.defn (nth_hom_seq f_compat r) hε'0, use N, intros n hn, apply lt_trans _ hε', change ↑(padic_norm_e _) < _, norm_cast, exact hN _ hn, end lemma lim_nth_hom_zero : lim_nth_hom f_compat 0 = 0 := by simp [lim_nth_hom]; refl lemma lim_nth_hom_one : lim_nth_hom f_compat 1 = 1 := subtype.ext $ quot.sound $ nth_hom_seq_one _ lemma lim_nth_hom_add (r s : R) : lim_nth_hom f_compat (r + s) = lim_nth_hom f_compat r + lim_nth_hom f_compat s := subtype.ext $ quot.sound $ nth_hom_seq_add _ _ _ lemma lim_nth_hom_mul (r s : R) : lim_nth_hom f_compat (r * s) = lim_nth_hom f_compat r * lim_nth_hom f_compat s := subtype.ext $ quot.sound $ nth_hom_seq_mul _ _ _ -- TODO: generalize this to arbitrary complete discrete valuation rings /-- `lift f_compat` is the limit of a sequence `f` of compatible ring homs `R →+* zmod (p^k)`, with the equality `lift f_compat r = padic_int.lim_nth_hom f_compat r`. -/ def lift : R →+* ℤ_[p] := { to_fun := lim_nth_hom f_compat, map_one' := lim_nth_hom_one f_compat, map_mul' := lim_nth_hom_mul f_compat, map_zero' := lim_nth_hom_zero f_compat, map_add' := lim_nth_hom_add f_compat } omit f_compat lemma lift_sub_val_mem_span (r : R) (n : ℕ) : (lift f_compat r - (f n r).val) ∈ (ideal.span {↑p ^ n} : ideal ℤ_[p]) := begin obtain ⟨k, hk⟩ := lim_nth_hom_spec f_compat r _ (show (0 : ℝ) < p ^ (-n : ℤ), from nat.zpow_pos_of_pos hp_prime.1.pos _), have := le_of_lt (hk (max n k) (le_max_right _ _)), rw norm_le_pow_iff_mem_span_pow at this, dsimp [lift], rw sub_eq_sub_add_sub (lim_nth_hom f_compat r) _ ↑(nth_hom f r (max n k)), apply ideal.add_mem _ _ this, rw [ideal.mem_span_singleton], simpa only [eq_int_cast, ring_hom.map_pow, int.cast_sub] using (int.cast_ring_hom ℤ_[p]).map_dvd (pow_dvd_nth_hom_sub f_compat r n (max n k) (le_max_left _ _)), end /-- One part of the universal property of `ℤ_[p]` as a projective limit. See also `padic_int.lift_unique`. -/ lemma lift_spec (n : ℕ) : (to_zmod_pow n).comp (lift f_compat) = f n := begin ext r, rw [ring_hom.comp_apply, ← zmod.nat_cast_zmod_val (f n r), ← map_nat_cast $ to_zmod_pow n, ← sub_eq_zero, ← ring_hom.map_sub, ← ring_hom.mem_ker, ker_to_zmod_pow], apply lift_sub_val_mem_span, end /-- One part of the universal property of `ℤ_[p]` as a projective limit. See also `padic_int.lift_spec`. -/ lemma lift_unique (g : R →+* ℤ_[p]) (hg : ∀ n, (to_zmod_pow n).comp g = f n) : lift f_compat = g := begin ext1 r, apply eq_of_forall_dist_le, intros ε hε, obtain ⟨n, hn⟩ := exists_pow_neg_lt p hε, apply le_trans _ (le_of_lt hn), rw [dist_eq_norm, norm_le_pow_iff_mem_span_pow, ← ker_to_zmod_pow, ring_hom.mem_ker, ring_hom.map_sub, ← ring_hom.comp_apply, ← ring_hom.comp_apply, lift_spec, hg, sub_self], end @[simp] lemma lift_self (z : ℤ_[p]) : @lift p _ ℤ_[p] _ to_zmod_pow zmod_cast_comp_to_zmod_pow z = z := begin show _ = ring_hom.id _ z, rw @lift_unique p _ ℤ_[p] _ _ zmod_cast_comp_to_zmod_pow (ring_hom.id ℤ_[p]), intro, rw ring_hom.comp_id, end end lift lemma ext_of_to_zmod_pow {x y : ℤ_[p]} : (∀ n, to_zmod_pow n x = to_zmod_pow n y) ↔ x = y := begin split, { intro h, rw [← lift_self x, ← lift_self y], simp [lift, lim_nth_hom, nth_hom, h] }, { rintro rfl _, refl } end lemma to_zmod_pow_eq_iff_ext {R : Type*} [non_assoc_semiring R] {g g' : R →+* ℤ_[p]} : (∀ n, (to_zmod_pow n).comp g = (to_zmod_pow n).comp g') ↔ g = g' := begin split, { intro hg, ext x : 1, apply ext_of_to_zmod_pow.mp, intro n, show (to_zmod_pow n).comp g x = (to_zmod_pow n).comp g' x, rw hg n }, { rintro rfl _, refl } end end padic_int
8b4e6c95f6d90e3abfff3a636977f8a959e8a71e
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/structuralEqns.lean
f9e1892554dd65b14e6c64b329c574df872254ab
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,574
lean
import Lean open Lean open Lean.Meta def tst (declName : Name) : MetaM Unit := do IO.println (← getUnfoldEqnFor? declName) #eval tst ``List.map #check @List.map._eq_1 #check @List.map._eq_2 #check @List.map._unfold def foo (xs ys zs : List Nat) : List Nat := match (xs, ys) with | (xs', ys') => match zs with | z::zs => foo xs ys zs | _ => match ys' with | [] => [1] | _ => [2] #eval tst ``foo #check foo._eq_1 #check foo._eq_2 #check foo._unfold #eval tst ``foo def g : List Nat → List Nat → Nat | [], y::ys => y | [], ys => 0 | [x1], ys => g [] ys | x::xs, y::ys => g xs ys + y | x::xs, [] => g xs [] #eval tst ``g #check g._eq_1 #check g._eq_2 #check g._eq_3 #check g._eq_4 #check g._eq_5 #check g._unfold def h (xs : List Nat) (y : Nat) : Nat := match xs with | [] => y | x::xs => match y with | 0 => h xs 10 | y+1 => h xs y #eval tst ``h #check h._eq_1 #check h._eq_2 #check h._unfold def r (i j : Nat) : Nat := i + match j with | Nat.zero => 1 | Nat.succ j => i * match j with | Nat.zero => 2 | Nat.succ j => r i j #eval tst ``r #check r._eq_1 #check r._eq_2 #check r._eq_3 #check r._unfold def bla (f g : α → α → α) (a : α) (i : α) (j : Nat) : α := f i <| match j with | Nat.zero => i | Nat.succ j => g i <| match j with | Nat.zero => a | Nat.succ j => bla f g a i j #eval tst ``bla #check @bla._eq_1 #check @bla._eq_2 #check @bla._eq_3 #check @bla._unfold
3f0f39ed24b943c58f0e0e094d53efd97e396bcf
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/analysis/special_functions/pow.lean
c20e2b5140dcfb26c692456d16dfd78b4f1a2f79
[ "Apache-2.0" ]
permissive
SAAluthwela/mathlib
62044349d72dd63983a8500214736aa7779634d3
83a4b8b990907291421de54a78988c024dc8a552
refs/heads/master
1,679,433,873,417
1,615,998,031,000
1,615,998,031,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
71,493
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Sébastien Gouëzel, Rémy Degenne -/ import analysis.special_functions.trigonometric import analysis.calculus.extend_deriv /-! # Power function on `ℂ`, `ℝ`, `ℝ≥0`, and `ℝ≥0∞` We construct the power functions `x ^ y` where * `x` and `y` are complex numbers, * or `x` and `y` are real numbers, * or `x` is a nonnegative real number and `y` is a real number; * or `x` is a number from `[0, +∞]` (a.k.a. `ℝ≥0∞`) and `y` is a real number. We also prove basic properties of these functions. -/ noncomputable theory open_locale classical real topological_space nnreal ennreal filter open filter namespace complex /-- The complex power function `x^y`, given by `x^y = exp(y log x)` (where `log` is the principal determination of the logarithm), unless `x = 0` where one sets `0^0 = 1` and `0^y = 0` for `y ≠ 0`. -/ noncomputable def cpow (x y : ℂ) : ℂ := if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) noncomputable instance : has_pow ℂ ℂ := ⟨cpow⟩ @[simp] lemma cpow_eq_pow (x y : ℂ) : cpow x y = x ^ y := rfl lemma cpow_def (x y : ℂ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) := rfl lemma cpow_def_of_ne_zero {x : ℂ} (hx : x ≠ 0) (y : ℂ) : x ^ y = exp (log x * y) := if_neg hx @[simp] lemma cpow_zero (x : ℂ) : x ^ (0 : ℂ) = 1 := by simp [cpow_def] @[simp] lemma cpow_eq_zero_iff (x y : ℂ) : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := by { simp only [cpow_def], split_ifs; simp [*, exp_ne_zero] } @[simp] lemma zero_cpow {x : ℂ} (h : x ≠ 0) : (0 : ℂ) ^ x = 0 := by simp [cpow_def, *] @[simp] lemma cpow_one (x : ℂ) : x ^ (1 : ℂ) = x := if hx : x = 0 then by simp [hx, cpow_def] else by rw [cpow_def, if_neg (one_ne_zero : (1 : ℂ) ≠ 0), if_neg hx, mul_one, exp_log hx] @[simp] lemma one_cpow (x : ℂ) : (1 : ℂ) ^ x = 1 := by rw cpow_def; split_ifs; simp [one_ne_zero, *] at * lemma cpow_add {x : ℂ} (y z : ℂ) (hx : x ≠ 0) : x ^ (y + z) = x ^ y * x ^ z := by simp [cpow_def]; split_ifs; simp [*, exp_add, mul_add] at * lemma cpow_mul {x y : ℂ} (z : ℂ) (h₁ : -π < (log x * y).im) (h₂ : (log x * y).im ≤ π) : x ^ (y * z) = (x ^ y) ^ z := begin simp only [cpow_def], split_ifs; simp [*, exp_ne_zero, log_exp h₁ h₂, mul_assoc] at * end lemma cpow_neg (x y : ℂ) : x ^ -y = (x ^ y)⁻¹ := by simp [cpow_def]; split_ifs; simp [exp_neg] lemma cpow_sub {x : ℂ} (y z : ℂ) (hx : x ≠ 0) : x ^ (y - z) = x ^ y / x ^ z := by rw [sub_eq_add_neg, cpow_add _ _ hx, cpow_neg, div_eq_mul_inv] lemma cpow_neg_one (x : ℂ) : x ^ (-1 : ℂ) = x⁻¹ := by simpa using cpow_neg x 1 @[simp] lemma cpow_nat_cast (x : ℂ) : ∀ (n : ℕ), x ^ (n : ℂ) = x ^ n | 0 := by simp | (n + 1) := if hx : x = 0 then by simp only [hx, pow_succ, complex.zero_cpow (nat.cast_ne_zero.2 (nat.succ_ne_zero _)), zero_mul] else by simp [cpow_add, hx, pow_add, cpow_nat_cast n] @[simp] lemma cpow_int_cast (x : ℂ) : ∀ (n : ℤ), x ^ (n : ℂ) = x ^ n | (n : ℕ) := by simp; refl | -[1+ n] := by rw fpow_neg_succ_of_nat; simp only [int.neg_succ_of_nat_coe, int.cast_neg, complex.cpow_neg, inv_eq_one_div, int.cast_coe_nat, cpow_nat_cast] lemma cpow_nat_inv_pow (x : ℂ) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℂ)) ^ n = x := begin suffices : im (log x * n⁻¹) ∈ set.Ioc (-π) π, { rw [← cpow_nat_cast, ← cpow_mul _ this.1 this.2, inv_mul_cancel, cpow_one], exact_mod_cast hn.ne' }, rw [mul_comm, ← of_real_nat_cast, ← of_real_inv, of_real_mul_im, ← div_eq_inv_mul], have hn' : 0 < (n : ℝ), by assumption_mod_cast, have hn1 : 1 ≤ (n : ℝ), by exact_mod_cast (nat.succ_le_iff.2 hn), split, { rw lt_div_iff hn', calc -π * n ≤ -π * 1 : mul_le_mul_of_nonpos_left hn1 (neg_nonpos.2 real.pi_pos.le) ... = -π : mul_one _ ... < im (log x) : neg_pi_lt_log_im _ }, { rw div_le_iff hn', calc im (log x) ≤ π : log_im_le_pi _ ... = π * 1 : (mul_one π).symm ... ≤ π * n : mul_le_mul_of_nonneg_left hn1 real.pi_pos.le } end lemma has_strict_fderiv_at_cpow {p : ℂ × ℂ} (hp : 0 < p.1.re ∨ p.1.im ≠ 0) : has_strict_fderiv_at (λ x : ℂ × ℂ, x.1 ^ x.2) ((p.2 * p.1 ^ (p.2 - 1)) • continuous_linear_map.fst ℂ ℂ ℂ + (p.1 ^ p.2 * log p.1) • continuous_linear_map.snd ℂ ℂ ℂ) p := begin have A : p.1 ≠ 0, by { intro h, simpa [h, lt_irrefl] using hp }, have : (λ x : ℂ × ℂ, x.1 ^ x.2) =ᶠ[𝓝 p] (λ x, exp (log x.1 * x.2)), from ((is_open_ne.preimage continuous_fst).eventually_mem A).mono (λ p hp, cpow_def_of_ne_zero hp _), rw [cpow_sub _ _ A, cpow_one, mul_div_comm, mul_smul, mul_smul, ← smul_add], refine has_strict_fderiv_at.congr_of_eventually_eq _ this.symm, simpa only [cpow_def_of_ne_zero A, div_eq_mul_inv, smul_smul, add_comm] using ((has_strict_fderiv_at_fst.clog hp).mul has_strict_fderiv_at_snd).cexp end lemma has_strict_deriv_at_const_cpow {x y : ℂ} (h : x ≠ 0 ∨ y ≠ 0) : has_strict_deriv_at (λ y, x ^ y) (x ^ y * log x) y := begin rcases em (x = 0) with rfl|hx, { replace h := h.neg_resolve_left rfl, rw [log_zero, mul_zero], refine (has_strict_deriv_at_const _ 0).congr_of_eventually_eq _, exact (is_open_ne.eventually_mem h).mono (λ y hy, (zero_cpow hy).symm) }, { simpa only [cpow_def_of_ne_zero hx, mul_one] using ((has_strict_deriv_at_id y).const_mul (log x)).cexp } end lemma has_fderiv_at_cpow {p : ℂ × ℂ} (hp : 0 < p.1.re ∨ p.1.im ≠ 0) : has_fderiv_at (λ x : ℂ × ℂ, x.1 ^ x.2) ((p.2 * p.1 ^ (p.2 - 1)) • continuous_linear_map.fst ℂ ℂ ℂ + (p.1 ^ p.2 * log p.1) • continuous_linear_map.snd ℂ ℂ ℂ) p := (has_strict_fderiv_at_cpow hp).has_fderiv_at end complex section lim open complex variables {α : Type*} lemma measurable.cpow [measurable_space α] {f g : α → ℂ} (hf : measurable f) (hg : measurable g) : measurable (λ x, f x ^ g x) := measurable.ite (hf $ measurable_set_singleton _) (measurable.ite (hg $ measurable_set_singleton _) measurable_const measurable_const) (hf.clog.mul hg).cexp lemma filter.tendsto.cpow {l : filter α} {f g : α → ℂ} {a b : ℂ} (hf : tendsto f l (𝓝 a)) (hg : tendsto g l (𝓝 b)) (ha : 0 < a.re ∨ a.im ≠ 0) : tendsto (λ x, f x ^ g x) l (𝓝 (a ^ b)) := (@has_fderiv_at_cpow (a, b) ha).continuous_at.tendsto.comp (hf.prod_mk_nhds hg) lemma filter.tendsto.const_cpow {l : filter α} {f : α → ℂ} {a b : ℂ} (hf : tendsto f l (𝓝 b)) (h : a ≠ 0 ∨ b ≠ 0) : tendsto (λ x, a ^ f x) l (𝓝 (a ^ b)) := (has_strict_deriv_at_const_cpow h).continuous_at.tendsto.comp hf variables [topological_space α] {f g : α → ℂ} {s : set α} {a : α} lemma continuous_within_at.cpow (hf : continuous_within_at f s a) (hg : continuous_within_at g s a) (h0 : 0 < (f a).re ∨ (f a).im ≠ 0) : continuous_within_at (λ x, f x ^ g x) s a := hf.cpow hg h0 lemma continuous_within_at.const_cpow {b : ℂ} (hf : continuous_within_at f s a) (h : b ≠ 0 ∨ f a ≠ 0) : continuous_within_at (λ x, b ^ f x) s a := hf.const_cpow h lemma continuous_at.cpow (hf : continuous_at f a) (hg : continuous_at g a) (h0 : 0 < (f a).re ∨ (f a).im ≠ 0) : continuous_at (λ x, f x ^ g x) a := hf.cpow hg h0 lemma continuous_at.const_cpow {b : ℂ} (hf : continuous_at f a) (h : b ≠ 0 ∨ f a ≠ 0) : continuous_at (λ x, b ^ f x) a := hf.const_cpow h lemma continuous_on.cpow (hf : continuous_on f s) (hg : continuous_on g s) (h0 : ∀ a ∈ s, 0 < (f a).re ∨ (f a).im ≠ 0) : continuous_on (λ x, f x ^ g x) s := λ a ha, (hf a ha).cpow (hg a ha) (h0 a ha) lemma continuous_on.const_cpow {b : ℂ} (hf : continuous_on f s) (h : b ≠ 0 ∨ ∀ a ∈ s, f a ≠ 0) : continuous_on (λ x, b ^ f x) s := λ a ha, (hf a ha).const_cpow (h.imp id $ λ h, h a ha) lemma continuous.cpow (hf : continuous f) (hg : continuous g) (h0 : ∀ a, 0 < (f a).re ∨ (f a).im ≠ 0) : continuous (λ x, f x ^ g x) := continuous_iff_continuous_at.2 $ λ a, (hf.continuous_at.cpow hg.continuous_at (h0 a)) lemma continuous.const_cpow {b : ℂ} (hf : continuous f) (h : b ≠ 0 ∨ ∀ a, f a ≠ 0) : continuous (λ x, b ^ f x) := continuous_iff_continuous_at.2 $ λ a, (hf.continuous_at.const_cpow $ h.imp id $ λ h, h a) end lim section fderiv open complex variables {E : Type*} [normed_group E] [normed_space ℂ E] {f g : E → ℂ} {f' g' : E →L[ℂ] ℂ} {x : E} {s : set E} {c : ℂ} lemma has_strict_fderiv_at.cpow (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_strict_fderiv_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') x := by convert (@has_strict_fderiv_at_cpow ((λ x, (f x, g x)) x) h0).comp x (hf.prod hg) lemma has_strict_fderiv_at.const_cpow (hf : has_strict_fderiv_at f f' x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_strict_fderiv_at (λ x, c ^ f x) ((c ^ f x * log c) • f') x := (has_strict_deriv_at_const_cpow h0).comp_has_strict_fderiv_at x hf lemma has_fderiv_at.cpow (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_fderiv_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') x := by convert (@complex.has_fderiv_at_cpow ((λ x, (f x, g x)) x) h0).comp x (hf.prod hg) lemma has_fderiv_at.const_cpow (hf : has_fderiv_at f f' x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_fderiv_at (λ x, c ^ f x) ((c ^ f x * log c) • f') x := (has_strict_deriv_at_const_cpow h0).has_deriv_at.comp_has_fderiv_at x hf lemma has_fderiv_within_at.cpow (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_fderiv_within_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') s x := by convert (@complex.has_fderiv_at_cpow ((λ x, (f x, g x)) x) h0).comp_has_fderiv_within_at x (hf.prod hg) lemma has_fderiv_within_at.const_cpow (hf : has_fderiv_within_at f f' s x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_fderiv_within_at (λ x, c ^ f x) ((c ^ f x * log c) • f') s x := (has_strict_deriv_at_const_cpow h0).has_deriv_at.comp_has_fderiv_within_at x hf lemma differentiable_at.cpow (hf : differentiable_at ℂ f x) (hg : differentiable_at ℂ g x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : differentiable_at ℂ (λ x, f x ^ g x) x := (hf.has_fderiv_at.cpow hg.has_fderiv_at h0).differentiable_at lemma differentiable_at.const_cpow (hf : differentiable_at ℂ f x) (h0 : c ≠ 0 ∨ f x ≠ 0) : differentiable_at ℂ (λ x, c ^ f x) x := (hf.has_fderiv_at.const_cpow h0).differentiable_at lemma differentiable_within_at.cpow (hf : differentiable_within_at ℂ f s x) (hg : differentiable_within_at ℂ g s x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : differentiable_within_at ℂ (λ x, f x ^ g x) s x := (hf.has_fderiv_within_at.cpow hg.has_fderiv_within_at h0).differentiable_within_at lemma differentiable_within_at.const_cpow (hf : differentiable_within_at ℂ f s x) (h0 : c ≠ 0 ∨ f x ≠ 0) : differentiable_within_at ℂ (λ x, c ^ f x) s x := (hf.has_fderiv_within_at.const_cpow h0).differentiable_within_at end fderiv section deriv open complex variables {f g : ℂ → ℂ} {s : set ℂ} {f' g' x c : ℂ} /-- A private lemma that rewrites the output of lemmas like `has_fderiv_at.cpow` to the form expected by lemmas like `has_deriv_at.cpow`. -/ private lemma aux : ((g x * f x ^ (g x - 1)) • (1 : ℂ →L[ℂ] ℂ).smul_right f' + (f x ^ g x * log (f x)) • (1 : ℂ →L[ℂ] ℂ).smul_right g') 1 = g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g' := by simp only [algebra.id.smul_eq_mul, one_mul, continuous_linear_map.one_apply, continuous_linear_map.smul_right_apply, continuous_linear_map.add_apply, pi.smul_apply, continuous_linear_map.coe_smul'] lemma has_strict_deriv_at.cpow (hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_strict_deriv_at (λ x, f x ^ g x) (g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g') x := by simpa only [aux] using (hf.cpow hg h0).has_strict_deriv_at lemma has_strict_deriv_at.const_cpow (hf : has_strict_deriv_at f f' x) (h : c ≠ 0 ∨ f x ≠ 0) : has_strict_deriv_at (λ x, c ^ f x) (c ^ f x * log c * f') x := (has_strict_deriv_at_const_cpow h).comp x hf lemma complex.has_strict_deriv_at_cpow_const (h : 0 < x.re ∨ x.im ≠ 0) : has_strict_deriv_at (λ z : ℂ, z ^ c) (c * x ^ (c - 1)) x := by simpa only [mul_zero, add_zero, mul_one] using (has_strict_deriv_at_id x).cpow (has_strict_deriv_at_const x c) h lemma has_strict_deriv_at.cpow_const (hf : has_strict_deriv_at f f' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_strict_deriv_at (λ x, f x ^ c) (c * f x ^ (c - 1) * f') x := (complex.has_strict_deriv_at_cpow_const h0).comp x hf lemma has_deriv_at.cpow (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_deriv_at (λ x, f x ^ g x) (g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g') x := by simpa only [aux] using (hf.has_fderiv_at.cpow hg h0).has_deriv_at lemma has_deriv_at.const_cpow (hf : has_deriv_at f f' x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_deriv_at (λ x, c ^ f x) (c ^ f x * log c * f') x := (has_strict_deriv_at_const_cpow h0).has_deriv_at.comp x hf lemma has_deriv_at.cpow_const (hf : has_deriv_at f f' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_deriv_at (λ x, f x ^ c) (c * f x ^ (c - 1) * f') x := (complex.has_strict_deriv_at_cpow_const h0).has_deriv_at.comp x hf lemma has_deriv_within_at.cpow (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_deriv_within_at (λ x, f x ^ g x) (g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g') s x := by simpa only [aux] using (hf.has_fderiv_within_at.cpow hg h0).has_deriv_within_at lemma has_deriv_within_at.const_cpow (hf : has_deriv_within_at f f' s x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_deriv_within_at (λ x, c ^ f x) (c ^ f x * log c * f') s x := (has_strict_deriv_at_const_cpow h0).has_deriv_at.comp_has_deriv_within_at x hf lemma has_deriv_within_at.cpow_const (hf : has_deriv_within_at f f' s x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_deriv_within_at (λ x, f x ^ c) (c * f x ^ (c - 1) * f') s x := (complex.has_strict_deriv_at_cpow_const h0).has_deriv_at.comp_has_deriv_within_at x hf end deriv namespace real /-- The real power function `x^y`, defined as the real part of the complex power function. For `x > 0`, it is equal to `exp(y log x)`. For `x = 0`, one sets `0^0=1` and `0^y=0` for `y ≠ 0`. For `x < 0`, the definition is somewhat arbitary as it depends on the choice of a complex determination of the logarithm. With our conventions, it is equal to `exp (y log x) cos (πy)`. -/ noncomputable def rpow (x y : ℝ) := ((x : ℂ) ^ (y : ℂ)).re noncomputable instance : has_pow ℝ ℝ := ⟨rpow⟩ @[simp] lemma rpow_eq_pow (x y : ℝ) : rpow x y = x ^ y := rfl lemma rpow_def (x y : ℝ) : x ^ y = ((x : ℂ) ^ (y : ℂ)).re := rfl lemma rpow_def_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) := by simp only [rpow_def, complex.cpow_def]; split_ifs; simp [*, (complex.of_real_log hx).symm, -complex.of_real_mul, -is_R_or_C.of_real_mul, (complex.of_real_mul _ _).symm, complex.exp_of_real_re] at * lemma rpow_def_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : x ^ y = exp (log x * y) := by rw [rpow_def_of_nonneg (le_of_lt hx), if_neg (ne_of_gt hx)] lemma exp_mul (x y : ℝ) : exp (x * y) = (exp x) ^ y := by rw [rpow_def_of_pos (exp_pos _), log_exp] lemma rpow_eq_zero_iff_of_nonneg {x y : ℝ} (hx : 0 ≤ x) : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := by { simp only [rpow_def_of_nonneg hx], split_ifs; simp [*, exp_ne_zero] } open_locale real lemma rpow_def_of_neg {x : ℝ} (hx : x < 0) (y : ℝ) : x ^ y = exp (log x * y) * cos (y * π) := begin rw [rpow_def, complex.cpow_def, if_neg], have : complex.log x * y = ↑(log(-x) * y) + ↑(y * π) * complex.I, { simp only [complex.log, abs_of_neg hx, complex.arg_of_real_of_neg hx, complex.abs_of_real, complex.of_real_mul], ring }, { rw [this, complex.exp_add_mul_I, ← complex.of_real_exp, ← complex.of_real_cos, ← complex.of_real_sin, mul_add, ← complex.of_real_mul, ← mul_assoc, ← complex.of_real_mul, complex.add_re, complex.of_real_re, complex.mul_re, complex.I_re, complex.of_real_im, real.log_neg_eq_log], ring }, { rw complex.of_real_eq_zero, exact ne_of_lt hx } end lemma rpow_def_of_nonpos {x : ℝ} (hx : x ≤ 0) (y : ℝ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) * cos (y * π) := by split_ifs; simp [rpow_def, *]; exact rpow_def_of_neg (lt_of_le_of_ne hx h) _ lemma rpow_pos_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : 0 < x ^ y := by rw rpow_def_of_pos hx; apply exp_pos @[simp] lemma rpow_zero (x : ℝ) : x ^ (0 : ℝ) = 1 := by simp [rpow_def] @[simp] lemma zero_rpow {x : ℝ} (h : x ≠ 0) : (0 : ℝ) ^ x = 0 := by simp [rpow_def, *] @[simp] lemma rpow_one (x : ℝ) : x ^ (1 : ℝ) = x := by simp [rpow_def] @[simp] lemma one_rpow (x : ℝ) : (1 : ℝ) ^ x = 1 := by simp [rpow_def] lemma zero_rpow_le_one (x : ℝ) : (0 : ℝ) ^ x ≤ 1 := by { by_cases h : x = 0; simp [h, zero_le_one] } lemma zero_rpow_nonneg (x : ℝ) : 0 ≤ (0 : ℝ) ^ x := by { by_cases h : x = 0; simp [h, zero_le_one] } lemma rpow_nonneg_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : 0 ≤ x ^ y := by rw [rpow_def_of_nonneg hx]; split_ifs; simp only [zero_le_one, le_refl, le_of_lt (exp_pos _)] lemma abs_rpow_le_abs_rpow (x y : ℝ) : abs (x ^ y) ≤ abs (x) ^ y := begin rcases lt_trichotomy 0 x with (hx|rfl|hx), { rw [abs_of_pos hx, abs_of_pos (rpow_pos_of_pos hx _)] }, { rw [abs_zero, abs_of_nonneg (rpow_nonneg_of_nonneg le_rfl _)] }, { rw [abs_of_neg hx, rpow_def_of_neg hx, rpow_def_of_pos (neg_pos.2 hx), log_neg_eq_log, abs_mul, abs_of_pos (exp_pos _)], exact mul_le_of_le_one_right (exp_pos _).le (abs_cos_le_one _) } end lemma abs_rpow_of_nonneg {x y : ℝ} (hx_nonneg : 0 ≤ x) : abs (x ^ y) = (abs x) ^ y := begin have h_rpow_nonneg : 0 ≤ x ^ y, from real.rpow_nonneg_of_nonneg hx_nonneg _, rw [abs_eq_self.mpr hx_nonneg, abs_eq_self.mpr h_rpow_nonneg], end lemma norm_rpow_of_nonneg {x y : ℝ} (hx_nonneg : 0 ≤ x) : ∥x ^ y∥ = ∥x∥ ^ y := by { simp_rw real.norm_eq_abs, exact abs_rpow_of_nonneg hx_nonneg, } end real namespace complex lemma of_real_cpow {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : ((x ^ y : ℝ) : ℂ) = (x : ℂ) ^ (y : ℂ) := by simp [real.rpow_def_of_nonneg hx, complex.cpow_def]; split_ifs; simp [complex.of_real_log hx] @[simp] lemma abs_cpow_real (x : ℂ) (y : ℝ) : abs (x ^ (y : ℂ)) = x.abs ^ y := begin rw [real.rpow_def_of_nonneg (abs_nonneg _), complex.cpow_def], split_ifs; simp [*, abs_of_nonneg (le_of_lt (real.exp_pos _)), complex.log, complex.exp_add, add_mul, mul_right_comm _ I, exp_mul_I, abs_cos_add_sin_mul_I, (complex.of_real_mul _ _).symm, -complex.of_real_mul, -is_R_or_C.of_real_mul] at * end @[simp] lemma abs_cpow_inv_nat (x : ℂ) (n : ℕ) : abs (x ^ (n⁻¹ : ℂ)) = x.abs ^ (n⁻¹ : ℝ) := by rw ← abs_cpow_real; simp [-abs_cpow_real] end complex namespace real variables {x y z : ℝ} lemma rpow_add {x : ℝ} (hx : 0 < x) (y z : ℝ) : x ^ (y + z) = x ^ y * x ^ z := by simp only [rpow_def_of_pos hx, mul_add, exp_add] lemma rpow_add' {x : ℝ} (hx : 0 ≤ x) {y z : ℝ} (h : y + z ≠ 0) : x ^ (y + z) = x ^ y * x ^ z := begin rcases le_iff_eq_or_lt.1 hx with H|pos, { simp only [← H, h, rpow_eq_zero_iff_of_nonneg, true_and, zero_rpow, eq_self_iff_true, ne.def, not_false_iff, zero_eq_mul], by_contradiction F, push_neg at F, apply h, simp [F] }, { exact rpow_add pos _ _ } end /-- For `0 ≤ x`, the only problematic case in the equality `x ^ y * x ^ z = x ^ (y + z)` is for `x = 0` and `y + z = 0`, where the right hand side is `1` while the left hand side can vanish. The inequality is always true, though, and given in this lemma. -/ lemma le_rpow_add {x : ℝ} (hx : 0 ≤ x) (y z : ℝ) : x ^ y * x ^ z ≤ x ^ (y + z) := begin rcases le_iff_eq_or_lt.1 hx with H|pos, { by_cases h : y + z = 0, { simp only [H.symm, h, rpow_zero], calc (0 : ℝ) ^ y * 0 ^ z ≤ 1 * 1 : mul_le_mul (zero_rpow_le_one y) (zero_rpow_le_one z) (zero_rpow_nonneg z) zero_le_one ... = 1 : by simp }, { simp [rpow_add', ← H, h] } }, { simp [rpow_add pos] } end lemma rpow_mul {x : ℝ} (hx : 0 ≤ x) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := by rw [← complex.of_real_inj, complex.of_real_cpow (rpow_nonneg_of_nonneg hx _), complex.of_real_cpow hx, complex.of_real_mul, complex.cpow_mul, complex.of_real_cpow hx]; simp only [(complex.of_real_mul _ _).symm, (complex.of_real_log hx).symm, complex.of_real_im, neg_lt_zero, pi_pos, le_of_lt pi_pos] lemma rpow_neg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ := by simp only [rpow_def_of_nonneg hx]; split_ifs; simp [*, exp_neg] at * lemma rpow_sub {x : ℝ} (hx : 0 < x) (y z : ℝ) : x ^ (y - z) = x ^ y / x ^ z := by simp only [sub_eq_add_neg, rpow_add hx, rpow_neg (le_of_lt hx), div_eq_mul_inv] lemma rpow_sub' {x : ℝ} (hx : 0 ≤ x) {y z : ℝ} (h : y - z ≠ 0) : x ^ (y - z) = x ^ y / x ^ z := by { simp only [sub_eq_add_neg] at h ⊢, simp only [rpow_add' hx h, rpow_neg hx, div_eq_mul_inv] } @[simp] lemma rpow_nat_cast (x : ℝ) (n : ℕ) : x ^ (n : ℝ) = x ^ n := by simp only [rpow_def, (complex.of_real_pow _ _).symm, complex.cpow_nat_cast, complex.of_real_nat_cast, complex.of_real_re] @[simp] lemma rpow_int_cast (x : ℝ) (n : ℤ) : x ^ (n : ℝ) = x ^ n := by simp only [rpow_def, (complex.of_real_fpow _ _).symm, complex.cpow_int_cast, complex.of_real_int_cast, complex.of_real_re] lemma rpow_neg_one (x : ℝ) : x ^ (-1 : ℝ) = x⁻¹ := begin suffices H : x ^ ((-1 : ℤ) : ℝ) = x⁻¹, by exact_mod_cast H, simp only [rpow_int_cast, fpow_one, fpow_neg], end lemma mul_rpow {x y z : ℝ} (h : 0 ≤ x) (h₁ : 0 ≤ y) : (x*y)^z = x^z * y^z := begin iterate 3 { rw real.rpow_def_of_nonneg }, split_ifs; simp * at *, { have hx : 0 < x, { cases lt_or_eq_of_le h with h₂ h₂, { exact h₂ }, exfalso, apply h_2, exact eq.symm h₂ }, have hy : 0 < y, { cases lt_or_eq_of_le h₁ with h₂ h₂, { exact h₂ }, exfalso, apply h_3, exact eq.symm h₂ }, rw [log_mul (ne_of_gt hx) (ne_of_gt hy), add_mul, exp_add]}, { exact h₁ }, { exact h }, { exact mul_nonneg h h₁ }, end lemma inv_rpow (hx : 0 ≤ x) (y : ℝ) : (x⁻¹)^y = (x^y)⁻¹ := begin by_cases hy0 : y = 0, { simp [*] }, by_cases hx0 : x = 0, { simp [*] }, simp only [real.rpow_def_of_nonneg hx, real.rpow_def_of_nonneg (inv_nonneg.2 hx), if_false, hx0, mt inv_eq_zero.1 hx0, log_inv, ← neg_mul_eq_neg_mul, exp_neg] end lemma div_rpow (hx : 0 ≤ x) (hy : 0 ≤ y) (z : ℝ) : (x / y) ^ z = x^z / y^z := by simp only [div_eq_mul_inv, mul_rpow hx (inv_nonneg.2 hy), inv_rpow hy] lemma log_rpow {x : ℝ} (hx : 0 < x) (y : ℝ) : log (x^y) = y * (log x) := begin apply exp_injective, rw [exp_log (rpow_pos_of_pos hx y), ← exp_log hx, mul_comm, rpow_def_of_pos (exp_pos (log x)) y], end lemma rpow_lt_rpow (hx : 0 ≤ x) (hxy : x < y) (hz : 0 < z) : x^z < y^z := begin rw le_iff_eq_or_lt at hx, cases hx, { rw [← hx, zero_rpow (ne_of_gt hz)], exact rpow_pos_of_pos (by rwa ← hx at hxy) _ }, rw [rpow_def_of_pos hx, rpow_def_of_pos (lt_trans hx hxy), exp_lt_exp], exact mul_lt_mul_of_pos_right (log_lt_log hx hxy) hz end lemma rpow_le_rpow {x y z: ℝ} (h : 0 ≤ x) (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z := begin rcases eq_or_lt_of_le h₁ with rfl|h₁', { refl }, rcases eq_or_lt_of_le h₂ with rfl|h₂', { simp }, exact le_of_lt (rpow_lt_rpow h h₁' h₂') end lemma rpow_lt_rpow_iff (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 < z) : x ^ z < y ^ z ↔ x < y := ⟨lt_imp_lt_of_le_imp_le $ λ h, rpow_le_rpow hy h (le_of_lt hz), λ h, rpow_lt_rpow hx h hz⟩ lemma rpow_le_rpow_iff (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 < z) : x ^ z ≤ y ^ z ↔ x ≤ y := le_iff_le_iff_lt_iff_lt.2 $ rpow_lt_rpow_iff hy hx hz lemma rpow_lt_rpow_of_exponent_lt (hx : 1 < x) (hyz : y < z) : x^y < x^z := begin repeat {rw [rpow_def_of_pos (lt_trans zero_lt_one hx)]}, rw exp_lt_exp, exact mul_lt_mul_of_pos_left hyz (log_pos hx), end lemma rpow_le_rpow_of_exponent_le (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z := begin repeat {rw [rpow_def_of_pos (lt_of_lt_of_le zero_lt_one hx)]}, rw exp_le_exp, exact mul_le_mul_of_nonneg_left hyz (log_nonneg hx), end lemma rpow_lt_rpow_of_exponent_gt (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) : x^y < x^z := begin repeat {rw [rpow_def_of_pos hx0]}, rw exp_lt_exp, exact mul_lt_mul_of_neg_left hyz (log_neg hx0 hx1), end lemma rpow_le_rpow_of_exponent_ge (hx0 : 0 < x) (hx1 : x ≤ 1) (hyz : z ≤ y) : x^y ≤ x^z := begin repeat {rw [rpow_def_of_pos hx0]}, rw exp_le_exp, exact mul_le_mul_of_nonpos_left hyz (log_nonpos (le_of_lt hx0) hx1), end lemma rpow_lt_one {x z : ℝ} (hx1 : 0 ≤ x) (hx2 : x < 1) (hz : 0 < z) : x^z < 1 := by { rw ← one_rpow z, exact rpow_lt_rpow hx1 hx2 hz } lemma rpow_le_one {x z : ℝ} (hx1 : 0 ≤ x) (hx2 : x ≤ 1) (hz : 0 ≤ z) : x^z ≤ 1 := by { rw ← one_rpow z, exact rpow_le_rpow hx1 hx2 hz } lemma rpow_lt_one_of_one_lt_of_neg {x z : ℝ} (hx : 1 < x) (hz : z < 0) : x^z < 1 := by { convert rpow_lt_rpow_of_exponent_lt hx hz, exact (rpow_zero x).symm } lemma rpow_le_one_of_one_le_of_nonpos {x z : ℝ} (hx : 1 ≤ x) (hz : z ≤ 0) : x^z ≤ 1 := by { convert rpow_le_rpow_of_exponent_le hx hz, exact (rpow_zero x).symm } lemma one_lt_rpow {x z : ℝ} (hx : 1 < x) (hz : 0 < z) : 1 < x^z := by { rw ← one_rpow z, exact rpow_lt_rpow zero_le_one hx hz } lemma one_le_rpow {x z : ℝ} (hx : 1 ≤ x) (hz : 0 ≤ z) : 1 ≤ x^z := by { rw ← one_rpow z, exact rpow_le_rpow zero_le_one hx hz } lemma one_lt_rpow_of_pos_of_lt_one_of_neg (hx1 : 0 < x) (hx2 : x < 1) (hz : z < 0) : 1 < x^z := by { convert rpow_lt_rpow_of_exponent_gt hx1 hx2 hz, exact (rpow_zero x).symm } lemma one_le_rpow_of_pos_of_le_one_of_nonpos (hx1 : 0 < x) (hx2 : x ≤ 1) (hz : z ≤ 0) : 1 ≤ x^z := by { convert rpow_le_rpow_of_exponent_ge hx1 hx2 hz, exact (rpow_zero x).symm } lemma rpow_lt_one_iff_of_pos (hx : 0 < x) : x ^ y < 1 ↔ 1 < x ∧ y < 0 ∨ x < 1 ∧ 0 < y := by rw [rpow_def_of_pos hx, exp_lt_one_iff, mul_neg_iff, log_pos_iff hx, log_neg_iff hx] lemma rpow_lt_one_iff (hx : 0 ≤ x) : x ^ y < 1 ↔ x = 0 ∧ y ≠ 0 ∨ 1 < x ∧ y < 0 ∨ x < 1 ∧ 0 < y := begin rcases hx.eq_or_lt with (rfl|hx), { rcases em (y = 0) with (rfl|hy); simp [*, lt_irrefl, zero_lt_one] }, { simp [rpow_lt_one_iff_of_pos hx, hx.ne.symm] } end lemma one_lt_rpow_iff_of_pos (hx : 0 < x) : 1 < x ^ y ↔ 1 < x ∧ 0 < y ∨ x < 1 ∧ y < 0 := by rw [rpow_def_of_pos hx, one_lt_exp_iff, mul_pos_iff, log_pos_iff hx, log_neg_iff hx] lemma one_lt_rpow_iff (hx : 0 ≤ x) : 1 < x ^ y ↔ 1 < x ∧ 0 < y ∨ 0 < x ∧ x < 1 ∧ y < 0 := begin rcases hx.eq_or_lt with (rfl|hx), { rcases em (y = 0) with (rfl|hy); simp [*, lt_irrefl, (@zero_lt_one ℝ _ _).not_lt] }, { simp [one_lt_rpow_iff_of_pos hx, hx] } end lemma rpow_le_one_iff_of_pos (hx : 0 < x) : x ^ y ≤ 1 ↔ 1 ≤ x ∧ y ≤ 0 ∨ x ≤ 1 ∧ 0 ≤ y := by rw [rpow_def_of_pos hx, exp_le_one_iff, mul_nonpos_iff, log_nonneg_iff hx, log_nonpos_iff hx] lemma pow_nat_rpow_nat_inv {x : ℝ} (hx : 0 ≤ x) {n : ℕ} (hn : 0 < n) : (x ^ n) ^ (n⁻¹ : ℝ) = x := have hn0 : (n : ℝ) ≠ 0, by simpa [pos_iff_ne_zero] using hn, by rw [← rpow_nat_cast, ← rpow_mul hx, mul_inv_cancel hn0, rpow_one] lemma rpow_nat_inv_pow_nat {x : ℝ} (hx : 0 ≤ x) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℝ)) ^ n = x := have hn0 : (n : ℝ) ≠ 0, by simpa [pos_iff_ne_zero] using hn, by rw [← rpow_nat_cast, ← rpow_mul hx, inv_mul_cancel hn0, rpow_one] section prove_rpow_is_continuous lemma continuous_rpow_aux1 : continuous (λp : {p:ℝ×ℝ // 0 < p.1}, p.val.1 ^ p.val.2) := suffices h : continuous (λ p : {p:ℝ×ℝ // 0 < p.1 }, exp (log p.val.1 * p.val.2)), by { convert h, ext p, rw rpow_def_of_pos p.2 }, continuous_exp.comp $ (show continuous ((λp:{p:ℝ//0 < p}, log (p.val)) ∘ (λp:{p:ℝ×ℝ//0<p.fst}, ⟨p.val.1, p.2⟩)), from continuous_log'.comp $ continuous_subtype_mk _ $ continuous_fst.comp continuous_subtype_val).mul (continuous_snd.comp $ continuous_subtype_val.comp continuous_id) lemma continuous_rpow_aux2 : continuous (λ p : {p:ℝ×ℝ // p.1 < 0}, p.val.1 ^ p.val.2) := suffices h : continuous (λp:{p:ℝ×ℝ // p.1 < 0}, exp (log (-p.val.1) * p.val.2) * cos (p.val.2 * π)), by { convert h, ext p, rw [rpow_def_of_neg p.2, log_neg_eq_log] }, (continuous_exp.comp $ (show continuous $ (λp:{p:ℝ//0<p}, log (p.val))∘(λp:{p:ℝ×ℝ//p.1<0}, ⟨-p.val.1, neg_pos_of_neg p.2⟩), from continuous_log'.comp $ continuous_subtype_mk _ $ continuous_neg.comp $ continuous_fst.comp continuous_subtype_val).mul (continuous_snd.comp $ continuous_subtype_val.comp continuous_id)).mul (continuous_cos.comp $ (continuous_snd.comp $ continuous_subtype_val.comp continuous_id).mul continuous_const) lemma continuous_at_rpow_of_ne_zero (hx : x ≠ 0) (y : ℝ) : continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) := begin cases lt_trichotomy 0 x, exact continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux1 _ h) (mem_nhds_sets (by { convert (is_open_lt' (0:ℝ)).prod is_open_univ, ext, finish }) h), cases h, { exact absurd h.symm hx }, exact continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux2 _ h) (mem_nhds_sets (by { convert (is_open_gt' (0:ℝ)).prod is_open_univ, ext, finish }) h) end lemma continuous_rpow_aux3 : continuous (λ p : {p:ℝ×ℝ // 0 < p.2}, p.val.1 ^ p.val.2) := continuous_iff_continuous_at.2 $ λ ⟨(x₀, y₀), hy₀⟩, begin by_cases hx₀ : x₀ = 0, { simp only [continuous_at, hx₀, zero_rpow (ne_of_gt hy₀), metric.tendsto_nhds_nhds], assume ε ε0, rcases exists_pos_rat_lt (half_pos hy₀) with ⟨q, q_pos, q_lt⟩, let q := (q:ℝ), replace q_pos : 0 < q := rat.cast_pos.2 q_pos, let δ := min (min q (ε ^ (1 / q))) (1/2), have δ0 : 0 < δ := lt_min (lt_min q_pos (rpow_pos_of_pos ε0 _)) (by norm_num), have : δ ≤ q := le_trans (min_le_left _ _) (min_le_left _ _), have : δ ≤ ε ^ (1 / q) := le_trans (min_le_left _ _) (min_le_right _ _), have : δ < 1 := lt_of_le_of_lt (min_le_right _ _) (by norm_num), use δ, use δ0, rintros ⟨⟨x, y⟩, hy⟩, simp only [subtype.dist_eq, real.dist_eq, prod.dist_eq, sub_zero, subtype.coe_mk], assume h, rw max_lt_iff at h, cases h with xδ yy₀, have qy : q < y, calc q < y₀ / 2 : q_lt ... = y₀ - y₀ / 2 : (sub_half _).symm ... ≤ y₀ - δ : by linarith ... < y : sub_lt_of_abs_sub_lt_left yy₀, calc abs(x^y) ≤ abs(x)^y : abs_rpow_le_abs_rpow _ _ ... < δ ^ y : rpow_lt_rpow (abs_nonneg _) xδ hy ... < δ ^ q : by { refine rpow_lt_rpow_of_exponent_gt _ _ _, repeat {linarith} } ... ≤ (ε ^ (1 / q)) ^ q : by { refine rpow_le_rpow _ _ _, repeat {linarith} } ... = ε : by { rw [← rpow_mul, div_mul_cancel, rpow_one], exact ne_of_gt q_pos, linarith }}, { exact (continuous_within_at_iff_continuous_at_restrict (λp:ℝ×ℝ, p.1^p.2) _).1 (continuous_at_rpow_of_ne_zero hx₀ _).continuous_within_at } end lemma continuous_at_rpow_of_pos (hy : 0 < y) (x : ℝ) : continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) := continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux3 _ hy) (mem_nhds_sets (by { convert is_open_univ.prod (is_open_lt' (0:ℝ)), ext, finish }) hy) lemma continuous_at_rpow {x y : ℝ} (h : x ≠ 0 ∨ 0 < y) : continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) := by { cases h, exact continuous_at_rpow_of_ne_zero h _, exact continuous_at_rpow_of_pos h x } variables {α : Type*} [topological_space α] {f g : α → ℝ} /-- `real.rpow` is continuous at all points except for the lower half of the y-axis. In other words, the function `λp:ℝ×ℝ, p.1^p.2` is continuous at `(x, y)` if `x ≠ 0` or `y > 0`. Multiple forms of the claim is provided in the current section. -/ lemma continuous_rpow (h : ∀a, f a ≠ 0 ∨ 0 < g a) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_iff_continuous_at.2 $ λ a, begin show continuous_at ((λp:ℝ×ℝ, p.1^p.2) ∘ (λa, (f a, g a))) a, refine continuous_at.comp _ (continuous_iff_continuous_at.1 (hf.prod_mk hg) _), { replace h := h a, cases h, { exact continuous_at_rpow_of_ne_zero h _ }, { exact continuous_at_rpow_of_pos h _ }}, end lemma continuous_rpow_of_ne_zero (h : ∀a, f a ≠ 0) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_rpow (λa, or.inl $ h a) hf hg lemma continuous_rpow_of_pos (h : ∀a, 0 < g a) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_rpow (λa, or.inr $ h a) hf hg end prove_rpow_is_continuous section prove_rpow_is_differentiable lemma has_deriv_at_rpow_of_pos {x : ℝ} (h : 0 < x) (p : ℝ) : has_deriv_at (λ x, x^p) (p * x^(p-1)) x := begin have : has_deriv_at (λ x, exp (log x * p)) (p * x^(p-1)) x, { convert (has_deriv_at_exp _).comp x ((has_deriv_at_log (ne_of_gt h)).mul_const p) using 1, field_simp [rpow_def_of_pos h, mul_sub, exp_sub, exp_log h, ne_of_gt h], ring }, apply this.congr_of_eventually_eq, have : set.Ioi (0 : ℝ) ∈ 𝓝 x := mem_nhds_sets is_open_Ioi h, exact filter.eventually_of_mem this (λ y hy, rpow_def_of_pos hy _) end lemma has_deriv_at_rpow_of_neg {x : ℝ} (h : x < 0) (p : ℝ) : has_deriv_at (λ x, x^p) (p * x^(p-1)) x := begin have : has_deriv_at (λ x, exp (log x * p) * cos (p * π)) (p * x^(p-1)) x, { convert ((has_deriv_at_exp _).comp x ((has_deriv_at_log (ne_of_lt h)).mul_const p)).mul_const _ using 1, field_simp [rpow_def_of_neg h, mul_sub, exp_sub, sub_mul, cos_sub, exp_log_of_neg h, ne_of_lt h], ring }, apply this.congr_of_eventually_eq, have : set.Iio (0 : ℝ) ∈ 𝓝 x := mem_nhds_sets is_open_Iio h, exact filter.eventually_of_mem this (λ y hy, rpow_def_of_neg hy _) end lemma has_deriv_at_rpow {x : ℝ} (h : x ≠ 0) (p : ℝ) : has_deriv_at (λ x, x^p) (p * x^(p-1)) x := begin rcases lt_trichotomy x 0 with H|H|H, { exact has_deriv_at_rpow_of_neg H p }, { exact (h H).elim }, { exact has_deriv_at_rpow_of_pos H p }, end lemma has_deriv_at_rpow_zero_of_one_le {p : ℝ} (h : 1 ≤ p) : has_deriv_at (λ x, x^p) (p * (0 : ℝ)^(p-1)) 0 := begin apply has_deriv_at_of_has_deriv_at_of_ne (λ x hx, has_deriv_at_rpow hx p), { exact (continuous_rpow_of_pos (λ _, (lt_of_lt_of_le zero_lt_one h)) continuous_id continuous_const).continuous_at }, { rcases le_iff_eq_or_lt.1 h with rfl|h, { simp [continuous_const.continuous_at] }, { exact (continuous_const.mul (continuous_rpow_of_pos (λ _, sub_pos_of_lt h) continuous_id continuous_const)).continuous_at } } end lemma has_deriv_at_rpow_of_one_le (x : ℝ) {p : ℝ} (h : 1 ≤ p) : has_deriv_at (λ x, x^p) (p * x^(p-1)) x := begin by_cases hx : x = 0, { rw hx, exact has_deriv_at_rpow_zero_of_one_le h }, { exact has_deriv_at_rpow hx p } end end prove_rpow_is_differentiable section sqrt lemma sqrt_eq_rpow : sqrt = λx:ℝ, x ^ (1/(2:ℝ)) := begin funext, by_cases h : 0 ≤ x, { rw [← mul_self_inj_of_nonneg, mul_self_sqrt h, ← pow_two, ← rpow_nat_cast, ← rpow_mul h], norm_num, exact sqrt_nonneg _, exact rpow_nonneg_of_nonneg h _ }, { replace h : x < 0 := lt_of_not_ge h, have : 1 / (2:ℝ) * π = π / (2:ℝ), ring, rw [sqrt_eq_zero_of_nonpos (le_of_lt h), rpow_def_of_neg h, this, cos_pi_div_two, mul_zero] } end end sqrt end real section measurability_real open complex lemma measurable.rpow {α} [measurable_space α] {f g : α → ℝ} (hf : measurable f) (hg : measurable g) : measurable (λ a : α, (f a) ^ (g a)) := measurable_re.comp $ ((measurable_of_real.comp hf).cpow (measurable_of_real.comp hg)) lemma measurable.rpow_const {α} [measurable_space α] {f : α → ℝ} (hf : measurable f) {y : ℝ} : measurable (λ a : α, (f a) ^ y) := hf.rpow measurable_const lemma ae_measurable.rpow_const {α} [measurable_space α] {f : α → ℝ} {μ : measure_theory.measure α} (hf : ae_measurable f μ) {y : ℝ} : ae_measurable (λ a : α, (f a) ^ y) μ := measurable.comp_ae_measurable (measurable.rpow_const measurable_id) hf lemma real.measurable_rpow_const {y : ℝ} : measurable (λ x : ℝ, x ^ y) := measurable_id.rpow_const end measurability_real section differentiability open real variables {f : ℝ → ℝ} {x f' : ℝ} {s : set ℝ} (p : ℝ) /- Differentiability statements for the power of a function, when the function does not vanish and the exponent is arbitrary-/ lemma has_deriv_within_at.rpow (hf : has_deriv_within_at f f' s x) (hx : f x ≠ 0) : has_deriv_within_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) s x := begin convert (has_deriv_at_rpow hx p).comp_has_deriv_within_at x hf using 1, ring end lemma has_deriv_at.rpow (hf : has_deriv_at f f' x) (hx : f x ≠ 0) : has_deriv_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) x := begin rw ← has_deriv_within_at_univ at *, exact hf.rpow p hx end lemma differentiable_within_at.rpow (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) : differentiable_within_at ℝ (λx, (f x)^p) s x := (hf.has_deriv_within_at.rpow p hx).differentiable_within_at @[simp] lemma differentiable_at.rpow (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) : differentiable_at ℝ (λx, (f x)^p) x := (hf.has_deriv_at.rpow p hx).differentiable_at lemma differentiable_on.rpow (hf : differentiable_on ℝ f s) (hx : ∀ x ∈ s, f x ≠ 0) : differentiable_on ℝ (λx, (f x)^p) s := λx h, (hf x h).rpow p (hx x h) @[simp] lemma differentiable.rpow (hf : differentiable ℝ f) (hx : ∀ x, f x ≠ 0) : differentiable ℝ (λx, (f x)^p) := λx, (hf x).rpow p (hx x) lemma deriv_within_rpow (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, (f x)^p) s x = (deriv_within f s x) * p * (f x)^(p-1) := (hf.has_deriv_within_at.rpow p hx).deriv_within hxs @[simp] lemma deriv_rpow (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) : deriv (λx, (f x)^p) x = (deriv f x) * p * (f x)^(p-1) := (hf.has_deriv_at.rpow p hx).deriv /- Differentiability statements for the power of a function, when the function may vanish but the exponent is at least one. -/ variable {p} lemma has_deriv_within_at.rpow_of_one_le (hf : has_deriv_within_at f f' s x) (hp : 1 ≤ p) : has_deriv_within_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) s x := begin convert (has_deriv_at_rpow_of_one_le (f x) hp).comp_has_deriv_within_at x hf using 1, ring end lemma has_deriv_at.rpow_of_one_le (hf : has_deriv_at f f' x) (hp : 1 ≤ p) : has_deriv_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) x := begin rw ← has_deriv_within_at_univ at *, exact hf.rpow_of_one_le hp end lemma differentiable_within_at.rpow_of_one_le (hf : differentiable_within_at ℝ f s x) (hp : 1 ≤ p) : differentiable_within_at ℝ (λx, (f x)^p) s x := (hf.has_deriv_within_at.rpow_of_one_le hp).differentiable_within_at @[simp] lemma differentiable_at.rpow_of_one_le (hf : differentiable_at ℝ f x) (hp : 1 ≤ p) : differentiable_at ℝ (λx, (f x)^p) x := (hf.has_deriv_at.rpow_of_one_le hp).differentiable_at lemma differentiable_on.rpow_of_one_le (hf : differentiable_on ℝ f s) (hp : 1 ≤ p) : differentiable_on ℝ (λx, (f x)^p) s := λx h, (hf x h).rpow_of_one_le hp @[simp] lemma differentiable.rpow_of_one_le (hf : differentiable ℝ f) (hp : 1 ≤ p) : differentiable ℝ (λx, (f x)^p) := λx, (hf x).rpow_of_one_le hp lemma deriv_within_rpow_of_one_le (hf : differentiable_within_at ℝ f s x) (hp : 1 ≤ p) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, (f x)^p) s x = (deriv_within f s x) * p * (f x)^(p-1) := (hf.has_deriv_within_at.rpow_of_one_le hp).deriv_within hxs @[simp] lemma deriv_rpow_of_one_le (hf : differentiable_at ℝ f x) (hp : 1 ≤ p) : deriv (λx, (f x)^p) x = (deriv f x) * p * (f x)^(p-1) := (hf.has_deriv_at.rpow_of_one_le hp).deriv end differentiability section limits open real filter /-- The function `x ^ y` tends to `+∞` at `+∞` for any positive real `y`. -/ lemma tendsto_rpow_at_top {y : ℝ} (hy : 0 < y) : tendsto (λ x : ℝ, x ^ y) at_top at_top := begin rw tendsto_at_top_at_top, intro b, use (max b 0) ^ (1/y), intros x hx, exact le_of_max_le_left (by { convert rpow_le_rpow (rpow_nonneg_of_nonneg (le_max_right b 0) (1/y)) hx (le_of_lt hy), rw [← rpow_mul (le_max_right b 0), (eq_div_iff (ne_of_gt hy)).mp rfl, rpow_one] }), end /-- The function `x ^ (-y)` tends to `0` at `+∞` for any positive real `y`. -/ lemma tendsto_rpow_neg_at_top {y : ℝ} (hy : 0 < y) : tendsto (λ x : ℝ, x ^ (-y)) at_top (𝓝 0) := tendsto.congr' (eventually_eq_of_mem (Ioi_mem_at_top 0) (λ x hx, (rpow_neg (le_of_lt hx) y).symm)) (tendsto_rpow_at_top hy).inv_tendsto_at_top /-- The function `x ^ (a / (b * x + c))` tends to `1` at `+∞`, for any real numbers `a`, `b`, and `c` such that `b` is nonzero. -/ lemma tendsto_rpow_div_mul_add (a b c : ℝ) (hb : 0 ≠ b) : tendsto (λ x, x ^ (a / (b*x+c))) at_top (𝓝 1) := begin refine tendsto.congr' _ ((tendsto_exp_nhds_0_nhds_1.comp (by simpa only [mul_zero, pow_one] using ((@tendsto_const_nhds _ _ _ a _).mul (tendsto_div_pow_mul_exp_add_at_top b c 1 hb (by norm_num))))).comp (tendsto_log_at_top)), apply eventually_eq_of_mem (Ioi_mem_at_top (0:ℝ)), intros x hx, simp only [set.mem_Ioi, function.comp_app] at hx ⊢, rw [exp_log hx, ← exp_log (rpow_pos_of_pos hx (a / (b * x + c))), log_rpow hx (a / (b * x + c))], field_simp, end /-- The function `x ^ (1 / x)` tends to `1` at `+∞`. -/ lemma tendsto_rpow_div : tendsto (λ x, x ^ ((1:ℝ) / x)) at_top (𝓝 1) := by { convert tendsto_rpow_div_mul_add (1:ℝ) _ (0:ℝ) zero_ne_one, ring } /-- The function `x ^ (-1 / x)` tends to `1` at `+∞`. -/ lemma tendsto_rpow_neg_div : tendsto (λ x, x ^ (-(1:ℝ) / x)) at_top (𝓝 1) := by { convert tendsto_rpow_div_mul_add (-(1:ℝ)) _ (0:ℝ) zero_ne_one, ring } end limits namespace nnreal /-- The nonnegative real power function `x^y`, defined for `x : ℝ≥0` and `y : ℝ ` as the restriction of the real power function. For `x > 0`, it is equal to `exp (y log x)`. For `x = 0`, one sets `0 ^ 0 = 1` and `0 ^ y = 0` for `y ≠ 0`. -/ noncomputable def rpow (x : ℝ≥0) (y : ℝ) : ℝ≥0 := ⟨(x : ℝ) ^ y, real.rpow_nonneg_of_nonneg x.2 y⟩ noncomputable instance : has_pow ℝ≥0 ℝ := ⟨rpow⟩ @[simp] lemma rpow_eq_pow (x : ℝ≥0) (y : ℝ) : rpow x y = x ^ y := rfl @[simp, norm_cast] lemma coe_rpow (x : ℝ≥0) (y : ℝ) : ((x ^ y : ℝ≥0) : ℝ) = (x : ℝ) ^ y := rfl @[simp] lemma rpow_zero (x : ℝ≥0) : x ^ (0 : ℝ) = 1 := nnreal.eq $ real.rpow_zero _ @[simp] lemma rpow_eq_zero_iff {x : ℝ≥0} {y : ℝ} : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := begin rw [← nnreal.coe_eq, coe_rpow, ← nnreal.coe_eq_zero], exact real.rpow_eq_zero_iff_of_nonneg x.2 end @[simp] lemma zero_rpow {x : ℝ} (h : x ≠ 0) : (0 : ℝ≥0) ^ x = 0 := nnreal.eq $ real.zero_rpow h @[simp] lemma rpow_one (x : ℝ≥0) : x ^ (1 : ℝ) = x := nnreal.eq $ real.rpow_one _ @[simp] lemma one_rpow (x : ℝ) : (1 : ℝ≥0) ^ x = 1 := nnreal.eq $ real.one_rpow _ lemma rpow_add {x : ℝ≥0} (hx : x ≠ 0) (y z : ℝ) : x ^ (y + z) = x ^ y * x ^ z := nnreal.eq $ real.rpow_add (pos_iff_ne_zero.2 hx) _ _ lemma rpow_add' (x : ℝ≥0) {y z : ℝ} (h : y + z ≠ 0) : x ^ (y + z) = x ^ y * x ^ z := nnreal.eq $ real.rpow_add' x.2 h lemma rpow_mul (x : ℝ≥0) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := nnreal.eq $ real.rpow_mul x.2 y z lemma rpow_neg (x : ℝ≥0) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ := nnreal.eq $ real.rpow_neg x.2 _ lemma rpow_neg_one (x : ℝ≥0) : x ^ (-1 : ℝ) = x ⁻¹ := by simp [rpow_neg] lemma rpow_sub {x : ℝ≥0} (hx : x ≠ 0) (y z : ℝ) : x ^ (y - z) = x ^ y / x ^ z := nnreal.eq $ real.rpow_sub (pos_iff_ne_zero.2 hx) y z lemma rpow_sub' (x : ℝ≥0) {y z : ℝ} (h : y - z ≠ 0) : x ^ (y - z) = x ^ y / x ^ z := nnreal.eq $ real.rpow_sub' x.2 h lemma inv_rpow (x : ℝ≥0) (y : ℝ) : (x⁻¹) ^ y = (x ^ y)⁻¹ := nnreal.eq $ real.inv_rpow x.2 y lemma div_rpow (x y : ℝ≥0) (z : ℝ) : (x / y) ^ z = x ^ z / y ^ z := nnreal.eq $ real.div_rpow x.2 y.2 z @[simp, norm_cast] lemma rpow_nat_cast (x : ℝ≥0) (n : ℕ) : x ^ (n : ℝ) = x ^ n := nnreal.eq $ by simpa only [coe_rpow, coe_pow] using real.rpow_nat_cast x n lemma mul_rpow {x y : ℝ≥0} {z : ℝ} : (x*y)^z = x^z * y^z := nnreal.eq $ real.mul_rpow x.2 y.2 lemma rpow_le_rpow {x y : ℝ≥0} {z: ℝ} (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z := real.rpow_le_rpow x.2 h₁ h₂ lemma rpow_lt_rpow {x y : ℝ≥0} {z: ℝ} (h₁ : x < y) (h₂ : 0 < z) : x^z < y^z := real.rpow_lt_rpow x.2 h₁ h₂ lemma rpow_lt_rpow_iff {x y : ℝ≥0} {z : ℝ} (hz : 0 < z) : x ^ z < y ^ z ↔ x < y := real.rpow_lt_rpow_iff x.2 y.2 hz lemma rpow_le_rpow_iff {x y : ℝ≥0} {z : ℝ} (hz : 0 < z) : x ^ z ≤ y ^ z ↔ x ≤ y := real.rpow_le_rpow_iff x.2 y.2 hz lemma rpow_lt_rpow_of_exponent_lt {x : ℝ≥0} {y z : ℝ} (hx : 1 < x) (hyz : y < z) : x^y < x^z := real.rpow_lt_rpow_of_exponent_lt hx hyz lemma rpow_le_rpow_of_exponent_le {x : ℝ≥0} {y z : ℝ} (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z := real.rpow_le_rpow_of_exponent_le hx hyz lemma rpow_lt_rpow_of_exponent_gt {x : ℝ≥0} {y z : ℝ} (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) : x^y < x^z := real.rpow_lt_rpow_of_exponent_gt hx0 hx1 hyz lemma rpow_le_rpow_of_exponent_ge {x : ℝ≥0} {y z : ℝ} (hx0 : 0 < x) (hx1 : x ≤ 1) (hyz : z ≤ y) : x^y ≤ x^z := real.rpow_le_rpow_of_exponent_ge hx0 hx1 hyz lemma rpow_lt_one {x : ℝ≥0} {z : ℝ} (hx : 0 ≤ x) (hx1 : x < 1) (hz : 0 < z) : x^z < 1 := real.rpow_lt_one hx hx1 hz lemma rpow_le_one {x : ℝ≥0} {z : ℝ} (hx2 : x ≤ 1) (hz : 0 ≤ z) : x^z ≤ 1 := real.rpow_le_one x.2 hx2 hz lemma rpow_lt_one_of_one_lt_of_neg {x : ℝ≥0} {z : ℝ} (hx : 1 < x) (hz : z < 0) : x^z < 1 := real.rpow_lt_one_of_one_lt_of_neg hx hz lemma rpow_le_one_of_one_le_of_nonpos {x : ℝ≥0} {z : ℝ} (hx : 1 ≤ x) (hz : z ≤ 0) : x^z ≤ 1 := real.rpow_le_one_of_one_le_of_nonpos hx hz lemma one_lt_rpow {x : ℝ≥0} {z : ℝ} (hx : 1 < x) (hz : 0 < z) : 1 < x^z := real.one_lt_rpow hx hz lemma one_le_rpow {x : ℝ≥0} {z : ℝ} (h : 1 ≤ x) (h₁ : 0 ≤ z) : 1 ≤ x^z := real.one_le_rpow h h₁ lemma one_lt_rpow_of_pos_of_lt_one_of_neg {x : ℝ≥0} {z : ℝ} (hx1 : 0 < x) (hx2 : x < 1) (hz : z < 0) : 1 < x^z := real.one_lt_rpow_of_pos_of_lt_one_of_neg hx1 hx2 hz lemma one_le_rpow_of_pos_of_le_one_of_nonpos {x : ℝ≥0} {z : ℝ} (hx1 : 0 < x) (hx2 : x ≤ 1) (hz : z ≤ 0) : 1 ≤ x^z := real.one_le_rpow_of_pos_of_le_one_of_nonpos hx1 hx2 hz lemma pow_nat_rpow_nat_inv (x : ℝ≥0) {n : ℕ} (hn : 0 < n) : (x ^ n) ^ (n⁻¹ : ℝ) = x := by { rw [← nnreal.coe_eq, coe_rpow, nnreal.coe_pow], exact real.pow_nat_rpow_nat_inv x.2 hn } lemma rpow_nat_inv_pow_nat (x : ℝ≥0) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℝ)) ^ n = x := by { rw [← nnreal.coe_eq, nnreal.coe_pow, coe_rpow], exact real.rpow_nat_inv_pow_nat x.2 hn } lemma continuous_at_rpow {x : ℝ≥0} {y : ℝ} (h : x ≠ 0 ∨ 0 < y) : continuous_at (λp:ℝ≥0×ℝ, p.1^p.2) (x, y) := begin have : (λp:ℝ≥0×ℝ, p.1^p.2) = nnreal.of_real ∘ (λp:ℝ×ℝ, p.1^p.2) ∘ (λp:ℝ≥0 × ℝ, (p.1.1, p.2)), { ext p, rw [coe_rpow, nnreal.coe_of_real _ (real.rpow_nonneg_of_nonneg p.1.2 _)], refl }, rw this, refine nnreal.continuous_of_real.continuous_at.comp (continuous_at.comp _ _), { apply real.continuous_at_rpow, simp at h, rw ← (nnreal.coe_eq_zero x) at h, exact h }, { exact ((continuous_subtype_val.comp continuous_fst).prod_mk continuous_snd).continuous_at } end lemma of_real_rpow_of_nonneg {x y : ℝ} (hx : 0 ≤ x) : nnreal.of_real (x ^ y) = (nnreal.of_real x) ^ y := begin nth_rewrite 0 ← nnreal.coe_of_real x hx, rw [←nnreal.coe_rpow, nnreal.of_real_coe], end end nnreal namespace measurable variables {α : Type*} [measurable_space α] lemma nnreal_rpow {f : α → ℝ≥0} (hf : measurable f) {g : α → ℝ} (hg : measurable g) : measurable (λ a : α, (f a) ^ (g a)) := (hf.nnreal_coe.rpow hg).subtype_mk lemma nnreal_rpow_const {f : α → ℝ≥0} (hf : measurable f) {y : ℝ} : measurable (λ a : α, (f a) ^ y) := hf.nnreal_rpow measurable_const end measurable open filter lemma filter.tendsto.nnrpow {α : Type*} {f : filter α} {u : α → ℝ≥0} {v : α → ℝ} {x : ℝ≥0} {y : ℝ} (hx : tendsto u f (𝓝 x)) (hy : tendsto v f (𝓝 y)) (h : x ≠ 0 ∨ 0 < y) : tendsto (λ a, (u a) ^ (v a)) f (𝓝 (x ^ y)) := tendsto.comp (nnreal.continuous_at_rpow h) (hx.prod_mk_nhds hy) namespace nnreal lemma continuous_at_rpow_const {x : ℝ≥0} {y : ℝ} (h : x ≠ 0 ∨ 0 ≤ y) : continuous_at (λ z, z^y) x := h.elim (λ h, tendsto_id.nnrpow tendsto_const_nhds (or.inl h)) $ λ h, h.eq_or_lt.elim (λ h, h ▸ by simp only [rpow_zero, continuous_at_const]) (λ h, tendsto_id.nnrpow tendsto_const_nhds (or.inr h)) lemma continuous_rpow_const {y : ℝ} (h : 0 ≤ y) : continuous (λ x : ℝ≥0, x^y) := continuous_iff_continuous_at.2 $ λ x, continuous_at_rpow_const (or.inr h) end nnreal namespace ennreal /-- The real power function `x^y` on extended nonnegative reals, defined for `x : ℝ≥0∞` and `y : ℝ` as the restriction of the real power function if `0 < x < ⊤`, and with the natural values for `0` and `⊤` (i.e., `0 ^ x = 0` for `x > 0`, `1` for `x = 0` and `⊤` for `x < 0`, and `⊤ ^ x = 1 / 0 ^ x`). -/ noncomputable def rpow : ℝ≥0∞ → ℝ → ℝ≥0∞ | (some x) y := if x = 0 ∧ y < 0 then ⊤ else (x ^ y : ℝ≥0) | none y := if 0 < y then ⊤ else if y = 0 then 1 else 0 noncomputable instance : has_pow ℝ≥0∞ ℝ := ⟨rpow⟩ @[simp] lemma rpow_eq_pow (x : ℝ≥0∞) (y : ℝ) : rpow x y = x ^ y := rfl @[simp] lemma rpow_zero {x : ℝ≥0∞} : x ^ (0 : ℝ) = 1 := by cases x; { dsimp only [(^), rpow], simp [lt_irrefl] } lemma top_rpow_def (y : ℝ) : (⊤ : ℝ≥0∞) ^ y = if 0 < y then ⊤ else if y = 0 then 1 else 0 := rfl @[simp] lemma top_rpow_of_pos {y : ℝ} (h : 0 < y) : (⊤ : ℝ≥0∞) ^ y = ⊤ := by simp [top_rpow_def, h] @[simp] lemma top_rpow_of_neg {y : ℝ} (h : y < 0) : (⊤ : ℝ≥0∞) ^ y = 0 := by simp [top_rpow_def, asymm h, ne_of_lt h] @[simp] lemma zero_rpow_of_pos {y : ℝ} (h : 0 < y) : (0 : ℝ≥0∞) ^ y = 0 := begin rw [← ennreal.coe_zero, ← ennreal.some_eq_coe], dsimp only [(^), rpow], simp [h, asymm h, ne_of_gt h], end @[simp] lemma zero_rpow_of_neg {y : ℝ} (h : y < 0) : (0 : ℝ≥0∞) ^ y = ⊤ := begin rw [← ennreal.coe_zero, ← ennreal.some_eq_coe], dsimp only [(^), rpow], simp [h, ne_of_gt h], end lemma zero_rpow_def (y : ℝ) : (0 : ℝ≥0∞) ^ y = if 0 < y then 0 else if y = 0 then 1 else ⊤ := begin rcases lt_trichotomy 0 y with H|rfl|H, { simp [H, ne_of_gt, zero_rpow_of_pos, lt_irrefl] }, { simp [lt_irrefl] }, { simp [H, asymm H, ne_of_lt, zero_rpow_of_neg] } end @[norm_cast] lemma coe_rpow_of_ne_zero {x : ℝ≥0} (h : x ≠ 0) (y : ℝ) : (x : ℝ≥0∞) ^ y = (x ^ y : ℝ≥0) := begin rw [← ennreal.some_eq_coe], dsimp only [(^), rpow], simp [h] end @[norm_cast] lemma coe_rpow_of_nonneg (x : ℝ≥0) {y : ℝ} (h : 0 ≤ y) : (x : ℝ≥0∞) ^ y = (x ^ y : ℝ≥0) := begin by_cases hx : x = 0, { rcases le_iff_eq_or_lt.1 h with H|H, { simp [hx, H.symm] }, { simp [hx, zero_rpow_of_pos H, nnreal.zero_rpow (ne_of_gt H)] } }, { exact coe_rpow_of_ne_zero hx _ } end lemma coe_rpow_def (x : ℝ≥0) (y : ℝ) : (x : ℝ≥0∞) ^ y = if x = 0 ∧ y < 0 then ⊤ else (x ^ y : ℝ≥0) := rfl @[simp] lemma rpow_one (x : ℝ≥0∞) : x ^ (1 : ℝ) = x := by cases x; dsimp only [(^), rpow]; simp [zero_lt_one, not_lt_of_le zero_le_one] @[simp] lemma one_rpow (x : ℝ) : (1 : ℝ≥0∞) ^ x = 1 := by { rw [← coe_one, coe_rpow_of_ne_zero one_ne_zero], simp } @[simp] lemma rpow_eq_zero_iff {x : ℝ≥0∞} {y : ℝ} : x ^ y = 0 ↔ (x = 0 ∧ 0 < y) ∨ (x = ⊤ ∧ y < 0) := begin cases x, { rcases lt_trichotomy y 0 with H|H|H; simp [H, top_rpow_of_neg, top_rpow_of_pos, le_of_lt] }, { by_cases h : x = 0, { rcases lt_trichotomy y 0 with H|H|H; simp [h, H, zero_rpow_of_neg, zero_rpow_of_pos, le_of_lt] }, { simp [coe_rpow_of_ne_zero h, h] } } end @[simp] lemma rpow_eq_top_iff {x : ℝ≥0∞} {y : ℝ} : x ^ y = ⊤ ↔ (x = 0 ∧ y < 0) ∨ (x = ⊤ ∧ 0 < y) := begin cases x, { rcases lt_trichotomy y 0 with H|H|H; simp [H, top_rpow_of_neg, top_rpow_of_pos, le_of_lt] }, { by_cases h : x = 0, { rcases lt_trichotomy y 0 with H|H|H; simp [h, H, zero_rpow_of_neg, zero_rpow_of_pos, le_of_lt] }, { simp [coe_rpow_of_ne_zero h, h] } } end lemma rpow_eq_top_iff_of_pos {x : ℝ≥0∞} {y : ℝ} (hy : 0 < y) : x ^ y = ⊤ ↔ x = ⊤ := by simp [rpow_eq_top_iff, hy, asymm hy] lemma rpow_eq_top_of_nonneg (x : ℝ≥0∞) {y : ℝ} (hy0 : 0 ≤ y) : x ^ y = ⊤ → x = ⊤ := begin rw ennreal.rpow_eq_top_iff, intro h, cases h, { exfalso, rw lt_iff_not_ge at h, exact h.right hy0, }, { exact h.left, }, end lemma rpow_ne_top_of_nonneg {x : ℝ≥0∞} {y : ℝ} (hy0 : 0 ≤ y) (h : x ≠ ⊤) : x ^ y ≠ ⊤ := mt (ennreal.rpow_eq_top_of_nonneg x hy0) h lemma rpow_lt_top_of_nonneg {x : ℝ≥0∞} {y : ℝ} (hy0 : 0 ≤ y) (h : x ≠ ⊤) : x ^ y < ⊤ := ennreal.lt_top_iff_ne_top.mpr (ennreal.rpow_ne_top_of_nonneg hy0 h) lemma rpow_add {x : ℝ≥0∞} (y z : ℝ) (hx : x ≠ 0) (h'x : x ≠ ⊤) : x ^ (y + z) = x ^ y * x ^ z := begin cases x, { exact (h'x rfl).elim }, have : x ≠ 0 := λ h, by simpa [h] using hx, simp [coe_rpow_of_ne_zero this, nnreal.rpow_add this] end lemma rpow_neg (x : ℝ≥0∞) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ := begin cases x, { rcases lt_trichotomy y 0 with H|H|H; simp [top_rpow_of_pos, top_rpow_of_neg, H, neg_pos.mpr] }, { by_cases h : x = 0, { rcases lt_trichotomy y 0 with H|H|H; simp [h, zero_rpow_of_pos, zero_rpow_of_neg, H, neg_pos.mpr] }, { have A : x ^ y ≠ 0, by simp [h], simp [coe_rpow_of_ne_zero h, ← coe_inv A, nnreal.rpow_neg] } } end lemma rpow_neg_one (x : ℝ≥0∞) : x ^ (-1 : ℝ) = x ⁻¹ := by simp [rpow_neg] lemma rpow_mul (x : ℝ≥0∞) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := begin cases x, { rcases lt_trichotomy y 0 with Hy|Hy|Hy; rcases lt_trichotomy z 0 with Hz|Hz|Hz; simp [Hy, Hz, zero_rpow_of_neg, zero_rpow_of_pos, top_rpow_of_neg, top_rpow_of_pos, mul_pos_of_neg_of_neg, mul_neg_of_neg_of_pos, mul_neg_of_pos_of_neg] }, { by_cases h : x = 0, { rcases lt_trichotomy y 0 with Hy|Hy|Hy; rcases lt_trichotomy z 0 with Hz|Hz|Hz; simp [h, Hy, Hz, zero_rpow_of_neg, zero_rpow_of_pos, top_rpow_of_neg, top_rpow_of_pos, mul_pos_of_neg_of_neg, mul_neg_of_neg_of_pos, mul_neg_of_pos_of_neg] }, { have : x ^ y ≠ 0, by simp [h], simp [coe_rpow_of_ne_zero h, coe_rpow_of_ne_zero this, nnreal.rpow_mul] } } end @[simp, norm_cast] lemma rpow_nat_cast (x : ℝ≥0∞) (n : ℕ) : x ^ (n : ℝ) = x ^ n := begin cases x, { cases n; simp [top_rpow_of_pos (nat.cast_add_one_pos _), top_pow (nat.succ_pos _)] }, { simp [coe_rpow_of_nonneg _ (nat.cast_nonneg n)] } end @[norm_cast] lemma coe_mul_rpow (x y : ℝ≥0) (z : ℝ) : ((x : ℝ≥0∞) * y) ^ z = x^z * y^z := begin rcases lt_trichotomy z 0 with H|H|H, { by_cases hx : x = 0; by_cases hy : y = 0, { simp [hx, hy, zero_rpow_of_neg, H] }, { have : (y : ℝ≥0∞) ^ z ≠ 0, by simp [rpow_eq_zero_iff, hy], simp [hx, hy, zero_rpow_of_neg, H, with_top.top_mul this] }, { have : (x : ℝ≥0∞) ^ z ≠ 0, by simp [rpow_eq_zero_iff, hx], simp [hx, hy, zero_rpow_of_neg H, with_top.mul_top this] }, { rw [← coe_mul, coe_rpow_of_ne_zero, nnreal.mul_rpow, coe_mul, coe_rpow_of_ne_zero hx, coe_rpow_of_ne_zero hy], simp [hx, hy] } }, { simp [H] }, { by_cases hx : x = 0; by_cases hy : y = 0, { simp [hx, hy, zero_rpow_of_pos, H] }, { have : (y : ℝ≥0∞) ^ z ≠ 0, by simp [rpow_eq_zero_iff, hy], simp [hx, hy, zero_rpow_of_pos H, with_top.top_mul this] }, { have : (x : ℝ≥0∞) ^ z ≠ 0, by simp [rpow_eq_zero_iff, hx], simp [hx, hy, zero_rpow_of_pos H, with_top.mul_top this] }, { rw [← coe_mul, coe_rpow_of_ne_zero, nnreal.mul_rpow, coe_mul, coe_rpow_of_ne_zero hx, coe_rpow_of_ne_zero hy], simp [hx, hy] } }, end lemma mul_rpow_of_ne_top {x y : ℝ≥0∞} (hx : x ≠ ⊤) (hy : y ≠ ⊤) (z : ℝ) : (x * y) ^ z = x^z * y^z := begin lift x to ℝ≥0 using hx, lift y to ℝ≥0 using hy, exact coe_mul_rpow x y z end lemma mul_rpow_of_ne_zero {x y : ℝ≥0∞} (hx : x ≠ 0) (hy : y ≠ 0) (z : ℝ) : (x * y) ^ z = x ^ z * y ^ z := begin rcases lt_trichotomy z 0 with H|H|H, { cases x; cases y, { simp [hx, hy, top_rpow_of_neg, H] }, { have : y ≠ 0, by simpa using hy, simp [hx, hy, top_rpow_of_neg, H, rpow_eq_zero_iff, this] }, { have : x ≠ 0, by simpa using hx, simp [hx, hy, top_rpow_of_neg, H, rpow_eq_zero_iff, this] }, { have hx' : x ≠ 0, by simpa using hx, have hy' : y ≠ 0, by simpa using hy, simp only [some_eq_coe], rw [← coe_mul, coe_rpow_of_ne_zero, nnreal.mul_rpow, coe_mul, coe_rpow_of_ne_zero hx', coe_rpow_of_ne_zero hy'], simp [hx', hy'] } }, { simp [H] }, { cases x; cases y, { simp [hx, hy, top_rpow_of_pos, H] }, { have : y ≠ 0, by simpa using hy, simp [hx, hy, top_rpow_of_pos, H, rpow_eq_zero_iff, this] }, { have : x ≠ 0, by simpa using hx, simp [hx, hy, top_rpow_of_pos, H, rpow_eq_zero_iff, this] }, { have hx' : x ≠ 0, by simpa using hx, have hy' : y ≠ 0, by simpa using hy, simp only [some_eq_coe], rw [← coe_mul, coe_rpow_of_ne_zero, nnreal.mul_rpow, coe_mul, coe_rpow_of_ne_zero hx', coe_rpow_of_ne_zero hy'], simp [hx', hy'] } } end lemma mul_rpow_of_nonneg (x y : ℝ≥0∞) {z : ℝ} (hz : 0 ≤ z) : (x * y) ^ z = x ^ z * y ^ z := begin rcases le_iff_eq_or_lt.1 hz with H|H, { simp [← H] }, by_cases h : x = 0 ∨ y = 0, { cases h; simp [h, zero_rpow_of_pos H] }, push_neg at h, exact mul_rpow_of_ne_zero h.1 h.2 z end lemma inv_rpow_of_pos {x : ℝ≥0∞} {y : ℝ} (hy : 0 < y) : (x⁻¹) ^ y = (x ^ y)⁻¹ := begin by_cases h0 : x = 0, { rw [h0, zero_rpow_of_pos hy, inv_zero, top_rpow_of_pos hy], }, by_cases h_top : x = ⊤, { rw [h_top, top_rpow_of_pos hy, inv_top, zero_rpow_of_pos hy], }, rw ←coe_to_nnreal h_top, have h : x.to_nnreal ≠ 0, { rw [ne.def, to_nnreal_eq_zero_iff], simp [h0, h_top], }, rw [←coe_inv h, coe_rpow_of_nonneg _ (le_of_lt hy), coe_rpow_of_nonneg _ (le_of_lt hy), ←coe_inv], { rw coe_eq_coe, exact nnreal.inv_rpow x.to_nnreal y, }, { simp [h], }, end lemma div_rpow_of_nonneg (x y : ℝ≥0∞) {z : ℝ} (hz : 0 ≤ z) : (x / y) ^ z = x ^ z / y ^ z := begin by_cases h0 : z = 0, { simp [h0], }, rw ←ne.def at h0, have hz_pos : 0 < z, from lt_of_le_of_ne hz h0.symm, rw [div_eq_mul_inv, mul_rpow_of_nonneg x y⁻¹ hz, inv_rpow_of_pos hz_pos, ←div_eq_mul_inv], end lemma rpow_le_rpow {x y : ℝ≥0∞} {z : ℝ} (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z := begin rcases le_iff_eq_or_lt.1 h₂ with H|H, { simp [← H, le_refl] }, cases y, { simp [top_rpow_of_pos H] }, cases x, { exact (not_top_le_coe h₁).elim }, simp at h₁, simp [coe_rpow_of_nonneg _ h₂, nnreal.rpow_le_rpow h₁ h₂] end lemma rpow_lt_rpow {x y : ℝ≥0∞} {z : ℝ} (h₁ : x < y) (h₂ : 0 < z) : x^z < y^z := begin cases x, { exact (not_top_lt h₁).elim }, cases y, { simp [top_rpow_of_pos h₂, coe_rpow_of_nonneg _ (le_of_lt h₂)] }, simp at h₁, simp [coe_rpow_of_nonneg _ (le_of_lt h₂), nnreal.rpow_lt_rpow h₁ h₂] end lemma rpow_le_rpow_iff {x y : ℝ≥0∞} {z : ℝ} (hz : 0 < z) : x ^ z ≤ y ^ z ↔ x ≤ y := begin refine ⟨λ h, _, λ h, rpow_le_rpow h (le_of_lt hz)⟩, rw [←rpow_one x, ←rpow_one y, ←@_root_.mul_inv_cancel _ _ z (ne_of_lt hz).symm, rpow_mul, rpow_mul, ←one_div], exact rpow_le_rpow h (by simp [le_of_lt hz]), end lemma rpow_lt_rpow_iff {x y : ℝ≥0∞} {z : ℝ} (hz : 0 < z) : x ^ z < y ^ z ↔ x < y := begin refine ⟨λ h_lt, _, λ h, rpow_lt_rpow h hz⟩, rw [←rpow_one x, ←rpow_one y, ←@_root_.mul_inv_cancel _ _ z (ne_of_lt hz).symm, rpow_mul, rpow_mul], exact rpow_lt_rpow h_lt (by simp [hz]), end lemma le_rpow_one_div_iff {x y : ℝ≥0∞} {z : ℝ} (hz : 0 < z) : x ≤ y ^ (1 / z) ↔ x ^ z ≤ y := begin nth_rewrite 0 ←rpow_one x, nth_rewrite 0 ←@_root_.mul_inv_cancel _ _ z (ne_of_lt hz).symm, rw [rpow_mul, ←one_div, @rpow_le_rpow_iff _ _ (1/z) (by simp [hz])], end lemma lt_rpow_one_div_iff {x y : ℝ≥0∞} {z : ℝ} (hz : 0 < z) : x < y ^ (1 / z) ↔ x ^ z < y := begin nth_rewrite 0 ←rpow_one x, nth_rewrite 0 ←@_root_.mul_inv_cancel _ _ z (ne_of_lt hz).symm, rw [rpow_mul, ←one_div, @rpow_lt_rpow_iff _ _ (1/z) (by simp [hz])], end lemma rpow_lt_rpow_of_exponent_lt {x : ℝ≥0∞} {y z : ℝ} (hx : 1 < x) (hx' : x ≠ ⊤) (hyz : y < z) : x^y < x^z := begin lift x to ℝ≥0 using hx', rw [one_lt_coe_iff] at hx, simp [coe_rpow_of_ne_zero (ne_of_gt (lt_trans zero_lt_one hx)), nnreal.rpow_lt_rpow_of_exponent_lt hx hyz] end lemma rpow_le_rpow_of_exponent_le {x : ℝ≥0∞} {y z : ℝ} (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z := begin cases x, { rcases lt_trichotomy y 0 with Hy|Hy|Hy; rcases lt_trichotomy z 0 with Hz|Hz|Hz; simp [Hy, Hz, top_rpow_of_neg, top_rpow_of_pos, le_refl]; linarith }, { simp only [one_le_coe_iff, some_eq_coe] at hx, simp [coe_rpow_of_ne_zero (ne_of_gt (lt_of_lt_of_le zero_lt_one hx)), nnreal.rpow_le_rpow_of_exponent_le hx hyz] } end lemma rpow_lt_rpow_of_exponent_gt {x : ℝ≥0∞} {y z : ℝ} (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) : x^y < x^z := begin lift x to ℝ≥0 using ne_of_lt (lt_of_lt_of_le hx1 le_top), simp at hx0 hx1, simp [coe_rpow_of_ne_zero (ne_of_gt hx0), nnreal.rpow_lt_rpow_of_exponent_gt hx0 hx1 hyz] end lemma rpow_le_rpow_of_exponent_ge {x : ℝ≥0∞} {y z : ℝ} (hx1 : x ≤ 1) (hyz : z ≤ y) : x^y ≤ x^z := begin lift x to ℝ≥0 using ne_of_lt (lt_of_le_of_lt hx1 coe_lt_top), by_cases h : x = 0, { rcases lt_trichotomy y 0 with Hy|Hy|Hy; rcases lt_trichotomy z 0 with Hz|Hz|Hz; simp [Hy, Hz, h, zero_rpow_of_neg, zero_rpow_of_pos, le_refl]; linarith }, { simp at hx1, simp [coe_rpow_of_ne_zero h, nnreal.rpow_le_rpow_of_exponent_ge (bot_lt_iff_ne_bot.mpr h) hx1 hyz] } end lemma rpow_le_self_of_le_one {x : ℝ≥0∞} {z : ℝ} (hx : x ≤ 1) (h_one_le : 1 ≤ z) : x ^ z ≤ x := begin nth_rewrite 1 ←ennreal.rpow_one x, exact ennreal.rpow_le_rpow_of_exponent_ge hx h_one_le, end lemma le_rpow_self_of_one_le {x : ℝ≥0∞} {z : ℝ} (hx : 1 ≤ x) (h_one_le : 1 ≤ z) : x ≤ x ^ z := begin nth_rewrite 0 ←ennreal.rpow_one x, exact ennreal.rpow_le_rpow_of_exponent_le hx h_one_le, end lemma rpow_pos_of_nonneg {p : ℝ} {x : ℝ≥0∞} (hx_pos : 0 < x) (hp_nonneg : 0 ≤ p) : 0 < x^p := begin by_cases hp_zero : p = 0, { simp [hp_zero, ennreal.zero_lt_one], }, { rw ←ne.def at hp_zero, have hp_pos := lt_of_le_of_ne hp_nonneg hp_zero.symm, rw ←zero_rpow_of_pos hp_pos, exact rpow_lt_rpow hx_pos hp_pos, }, end lemma rpow_pos {p : ℝ} {x : ℝ≥0∞} (hx_pos : 0 < x) (hx_ne_top : x ≠ ⊤) : 0 < x^p := begin cases lt_or_le 0 p with hp_pos hp_nonpos, { exact rpow_pos_of_nonneg hx_pos (le_of_lt hp_pos), }, { rw [←neg_neg p, rpow_neg, inv_pos], exact rpow_ne_top_of_nonneg (by simp [hp_nonpos]) hx_ne_top, }, end lemma rpow_lt_one {x : ℝ≥0∞} {z : ℝ} (hx : x < 1) (hz : 0 < z) : x^z < 1 := begin lift x to ℝ≥0 using ne_of_lt (lt_of_lt_of_le hx le_top), simp only [coe_lt_one_iff] at hx, simp [coe_rpow_of_nonneg _ (le_of_lt hz), nnreal.rpow_lt_one (zero_le x) hx hz], end lemma rpow_le_one {x : ℝ≥0∞} {z : ℝ} (hx : x ≤ 1) (hz : 0 ≤ z) : x^z ≤ 1 := begin lift x to ℝ≥0 using ne_of_lt (lt_of_le_of_lt hx coe_lt_top), simp only [coe_le_one_iff] at hx, simp [coe_rpow_of_nonneg _ hz, nnreal.rpow_le_one hx hz], end lemma rpow_lt_one_of_one_lt_of_neg {x : ℝ≥0∞} {z : ℝ} (hx : 1 < x) (hz : z < 0) : x^z < 1 := begin cases x, { simp [top_rpow_of_neg hz, ennreal.zero_lt_one] }, { simp only [some_eq_coe, one_lt_coe_iff] at hx, simp [coe_rpow_of_ne_zero (ne_of_gt (lt_trans zero_lt_one hx)), nnreal.rpow_lt_one_of_one_lt_of_neg hx hz] }, end lemma rpow_le_one_of_one_le_of_neg {x : ℝ≥0∞} {z : ℝ} (hx : 1 ≤ x) (hz : z < 0) : x^z ≤ 1 := begin cases x, { simp [top_rpow_of_neg hz, ennreal.zero_lt_one] }, { simp only [one_le_coe_iff, some_eq_coe] at hx, simp [coe_rpow_of_ne_zero (ne_of_gt (lt_of_lt_of_le zero_lt_one hx)), nnreal.rpow_le_one_of_one_le_of_nonpos hx (le_of_lt hz)] }, end lemma one_lt_rpow {x : ℝ≥0∞} {z : ℝ} (hx : 1 < x) (hz : 0 < z) : 1 < x^z := begin cases x, { simp [top_rpow_of_pos hz] }, { simp only [some_eq_coe, one_lt_coe_iff] at hx, simp [coe_rpow_of_nonneg _ (le_of_lt hz), nnreal.one_lt_rpow hx hz] } end lemma one_le_rpow {x : ℝ≥0∞} {z : ℝ} (hx : 1 ≤ x) (hz : 0 < z) : 1 ≤ x^z := begin cases x, { simp [top_rpow_of_pos hz] }, { simp only [one_le_coe_iff, some_eq_coe] at hx, simp [coe_rpow_of_nonneg _ (le_of_lt hz), nnreal.one_le_rpow hx (le_of_lt hz)] }, end lemma one_lt_rpow_of_pos_of_lt_one_of_neg {x : ℝ≥0∞} {z : ℝ} (hx1 : 0 < x) (hx2 : x < 1) (hz : z < 0) : 1 < x^z := begin lift x to ℝ≥0 using ne_of_lt (lt_of_lt_of_le hx2 le_top), simp only [coe_lt_one_iff, coe_pos] at ⊢ hx1 hx2, simp [coe_rpow_of_ne_zero (ne_of_gt hx1), nnreal.one_lt_rpow_of_pos_of_lt_one_of_neg hx1 hx2 hz], end lemma one_le_rpow_of_pos_of_le_one_of_neg {x : ℝ≥0∞} {z : ℝ} (hx1 : 0 < x) (hx2 : x ≤ 1) (hz : z < 0) : 1 ≤ x^z := begin lift x to ℝ≥0 using ne_of_lt (lt_of_le_of_lt hx2 coe_lt_top), simp only [coe_le_one_iff, coe_pos] at ⊢ hx1 hx2, simp [coe_rpow_of_ne_zero (ne_of_gt hx1), nnreal.one_le_rpow_of_pos_of_le_one_of_nonpos hx1 hx2 (le_of_lt hz)], end lemma to_nnreal_rpow (x : ℝ≥0∞) (z : ℝ) : (x.to_nnreal) ^ z = (x ^ z).to_nnreal := begin rcases lt_trichotomy z 0 with H|H|H, { cases x, { simp [H, ne_of_lt] }, by_cases hx : x = 0, { simp [hx, H, ne_of_lt] }, { simp [coe_rpow_of_ne_zero hx] } }, { simp [H] }, { cases x, { simp [H, ne_of_gt] }, simp [coe_rpow_of_nonneg _ (le_of_lt H)] } end lemma to_real_rpow (x : ℝ≥0∞) (z : ℝ) : (x.to_real) ^ z = (x ^ z).to_real := by rw [ennreal.to_real, ennreal.to_real, ←nnreal.coe_rpow, ennreal.to_nnreal_rpow] lemma of_real_rpow_of_pos {x p : ℝ} (hx_pos : 0 < x) : ennreal.of_real x ^ p = ennreal.of_real (x ^ p) := begin simp_rw ennreal.of_real, rw [coe_rpow_of_ne_zero, coe_eq_coe, nnreal.of_real_rpow_of_nonneg hx_pos.le], simp [hx_pos], end lemma of_real_rpow_of_nonneg {x p : ℝ} (hx_nonneg : 0 ≤ x) (hp_nonneg : 0 ≤ p) : ennreal.of_real x ^ p = ennreal.of_real (x ^ p) := begin by_cases hp0 : p = 0, { simp [hp0], }, by_cases hx0 : x = 0, { rw ← ne.def at hp0, have hp_pos : 0 < p := lt_of_le_of_ne hp_nonneg hp0.symm, simp [hx0, hp_pos, hp_pos.ne.symm], }, rw ← ne.def at hx0, exact of_real_rpow_of_pos (hx_nonneg.lt_of_ne hx0.symm), end lemma rpow_left_injective {x : ℝ} (hx : x ≠ 0) : function.injective (λ y : ℝ≥0∞, y^x) := begin intros y z hyz, dsimp only at hyz, rw [←rpow_one y, ←rpow_one z, ←_root_.mul_inv_cancel hx, rpow_mul, rpow_mul, hyz], end lemma rpow_left_surjective {x : ℝ} (hx : x ≠ 0) : function.surjective (λ y : ℝ≥0∞, y^x) := λ y, ⟨y ^ x⁻¹, by simp_rw [←rpow_mul, _root_.inv_mul_cancel hx, rpow_one]⟩ lemma rpow_left_bijective {x : ℝ} (hx : x ≠ 0) : function.bijective (λ y : ℝ≥0∞, y^x) := ⟨rpow_left_injective hx, rpow_left_surjective hx⟩ lemma rpow_left_monotone_of_nonneg {x : ℝ} (hx : 0 ≤ x) : monotone (λ y : ℝ≥0∞, y^x) := λ y z hyz, rpow_le_rpow hyz hx lemma rpow_left_strict_mono_of_pos {x : ℝ} (hx : 0 < x) : strict_mono (λ y : ℝ≥0∞, y^x) := λ y z hyz, rpow_lt_rpow hyz hx end ennreal section measurability_ennreal variables {α : Type*} [measurable_space α] lemma ennreal.measurable_rpow : measurable (λ p : ℝ≥0∞ × ℝ, p.1 ^ p.2) := begin refine ennreal.measurable_of_measurable_nnreal_prod _ _, { simp_rw ennreal.coe_rpow_def, refine measurable.ite _ measurable_const (measurable_fst.nnreal_rpow measurable_snd).ennreal_coe, exact measurable_set.inter (measurable_fst (measurable_set_singleton 0)) (measurable_snd measurable_set_Iio), }, { simp_rw ennreal.top_rpow_def, refine measurable.ite measurable_set_Ioi measurable_const _, exact measurable.ite (measurable_set_singleton 0) measurable_const measurable_const, }, end lemma measurable.ennreal_rpow {f : α → ℝ≥0∞} (hf : measurable f) {g : α → ℝ} (hg : measurable g) : measurable (λ a : α, (f a) ^ (g a)) := begin change measurable ((λ p : ℝ≥0∞ × ℝ, p.1 ^ p.2) ∘ (λ a, (f a, g a))), exact ennreal.measurable_rpow.comp (measurable.prod hf hg), end lemma measurable.ennreal_rpow_const {f : α → ℝ≥0∞} (hf : measurable f) {y : ℝ} : measurable (λ a : α, (f a) ^ y) := hf.ennreal_rpow measurable_const lemma ennreal.measurable_rpow_const {y : ℝ} : measurable (λ a : ℝ≥0∞, a ^ y) := measurable_id.ennreal_rpow_const lemma ae_measurable.ennreal_rpow_const {α} [measurable_space α] {f : α → ℝ≥0∞} {μ : measure_theory.measure α} (hf : ae_measurable f μ) {y : ℝ} : ae_measurable (λ a : α, (f a) ^ y) μ := ennreal.measurable_rpow_const.comp_ae_measurable hf end measurability_ennreal
495d67e625c295eb7dfcc6b0da1afe27ae92059f
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/stage0/src/Lean/Elab/Tactic/Rewrite.lean
0b9b668eb4b637d3855e16d44028907243472790
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
3,143
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Tactic.Rewrite import Lean.Meta.Tactic.Replace import Lean.Elab.Tactic.Location import Lean.Elab.Tactic.Config namespace Lean.Elab.Tactic open Meta def rewriteTarget (stx : Syntax) (symm : Bool) (config : Rewrite.Config) : TacticM Unit := do Term.withSynthesize <| withMainContext do let e ← elabTerm stx none true let r ← (← getMainGoal).rewrite (← getMainTarget) e symm (config := config) let mvarId' ← (← getMainGoal).replaceTargetEq r.eNew r.eqProof replaceMainGoal (mvarId' :: r.mvarIds) def rewriteLocalDecl (stx : Syntax) (symm : Bool) (fvarId : FVarId) (config : Rewrite.Config) : TacticM Unit := do Term.withSynthesize <| withMainContext do let e ← elabTerm stx none true let localDecl ← fvarId.getDecl let rwResult ← (← getMainGoal).rewrite localDecl.type e symm (config := config) let replaceResult ← (← getMainGoal).replaceLocalDecl fvarId rwResult.eNew rwResult.eqProof replaceMainGoal (replaceResult.mvarId :: rwResult.mvarIds) def withRWRulesSeq (token : Syntax) (rwRulesSeqStx : Syntax) (x : (symm : Bool) → (term : Syntax) → TacticM Unit) : TacticM Unit := do let lbrak := rwRulesSeqStx[0] let rules := rwRulesSeqStx[1].getArgs -- show initial state up to (incl.) `[` withTacticInfoContext (mkNullNode #[token, lbrak]) (pure ()) let numRules := (rules.size + 1) / 2 for i in [:numRules] do let rule := rules[i * 2]! let sep := rules.getD (i * 2 + 1) Syntax.missing -- show rule state up to (incl.) next `,` withTacticInfoContext (mkNullNode #[rule, sep]) do -- show errors on rule withRef rule do let symm := !rule[0].isNone let term := rule[1] let processId (id : Syntax) : TacticM Unit := do -- Try to get equation theorems for `id` first let declName ← try resolveGlobalConstNoOverload id catch _ => return (← x symm term) let some eqThms ← getEqnsFor? declName (nonRec := true) | x symm term let rec go : List Name → TacticM Unit | [] => throwError "failed to rewrite using equation theorems for '{declName}'" | eqThm::eqThms => (x symm (mkIdentFrom id eqThm)) <|> go eqThms go eqThms.toList discard <| Term.addTermInfo id (← mkConstWithFreshMVarLevels declName) (lctx? := ← getLCtx) match term with | `($id:ident) => processId id | `(@$id:ident) => processId id | _ => x symm term declare_config_elab elabRewriteConfig Rewrite.Config @[builtinTactic Lean.Parser.Tactic.rewriteSeq] def evalRewriteSeq : Tactic := fun stx => do let cfg ← elabRewriteConfig stx[1] let loc := expandOptLocation stx[3] withRWRulesSeq stx[0] stx[2] fun symm term => do withLocation loc (rewriteLocalDecl term symm · cfg) (rewriteTarget term symm cfg) (throwTacticEx `rewrite · "did not find instance of the pattern in the current goal") end Lean.Elab.Tactic
dcdd2cb95cf5e16cac66d82eaeb6ae126f58cb52
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Widget/InteractiveCode.lean
6258bc7c3f1cb4dadb4d1ad52443f299300c77b7
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
2,274
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki -/ import Lean.PrettyPrinter import Lean.Server.Rpc.Basic import Lean.Widget.TaggedText import Lean.Widget.Basic /-! RPC infrastructure for storing and formatting code fragments, in particular `Expr`s, with environment and subexpression information. -/ namespace Lean.Widget open Server /-- Information about a subexpression within delaborated code. -/ structure SubexprInfo where /-- The `Elab.Info` node with the semantics of this part of the output. -/ info : WithRpcRef InfoWithCtx /-- The position of this subexpression within the top-level expression. See `Lean.SubExpr`. -/ subexprPos : Lean.SubExpr.Pos -- TODO(WN): add fields for semantic highlighting -- kind : Lsp.SymbolKind deriving Inhabited, RpcEncodable /-- Pretty-printed syntax (usually but not necessarily an `Expr`) with embedded `Info`s. -/ abbrev CodeWithInfos := TaggedText SubexprInfo def CodeWithInfos.pretty (tt : CodeWithInfos) := tt.stripTags /-- Tags a pretty-printed `Expr` with infos from the delaborator. -/ partial def tagExprInfos (ctx : Elab.ContextInfo) (infos : Std.RBMap Nat Elab.Info compare) (tt : TaggedText (Nat × Nat)) : CodeWithInfos := go tt where go (tt : TaggedText (Nat × Nat)) := tt.rewrite fun (n, _) subTt => match infos.find? n with | none => go subTt | some i => TaggedText.tag ⟨WithRpcRef.mk { ctx, info := i }, n⟩ (go subTt) def ppExprTagged (e : Expr) (explicit : Bool := false) : MetaM CodeWithInfos := do let optsPerPos := if explicit then Std.RBMap.ofList [ (SubExpr.Pos.root, KVMap.empty.setBool `pp.all true), (SubExpr.Pos.root, KVMap.empty.setBool `pp.tagAppFns true) ] else {} let (fmt, infos) ← PrettyPrinter.ppExprWithInfos e optsPerPos let tt := TaggedText.prettyTagged fmt let ctx := { env := (← getEnv) mctx := (← getMCtx) options := (← getOptions) currNamespace := (← getCurrNamespace) openDecls := (← getOpenDecls) fileMap := default ngen := (← getNGen) } return tagExprInfos ctx infos tt end Lean.Widget
6ad26a768e7816a7ddc08a1bb5c05d43d667358e
98beff2e97d91a54bdcee52f922c4e1866a6c9b9
/src/over.lean
c72d0233718f04654f6227038168f90774c0e865
[]
no_license
b-mehta/topos
c3fc43fb04ba16bae1965ce5c26c6461172e5bc6
c9032b11789e36038bc841a1e2b486972421b983
refs/heads/master
1,629,609,492,867
1,609,907,263,000
1,609,907,263,000
240,943,034
43
3
null
1,598,210,062,000
1,581,877,668,000
Lean
UTF-8
Lean
false
false
9,513
lean
import category_theory.comma import category_theory.adjunction.basic import category_theory.limits.shapes import category_theory.epi_mono import category_theory.limits.over import category_theory.closed.cartesian import category.binary_products import category.adjunction /-! # Properties of the over category. We can interpret the forgetful functor `forget : over B ⥤ C` as dependent sum, (written `Σ_B`) and when C has binary products, it has a right adjoint `B*` given by `A ↦ (π₁ : B × A → B)`, denoted `star` in Lean. Furthermore, if the original category C has pullbacks and terminal object (i.e. all finite limits), `B*` has a right adjoint iff `B` is exponentiable in `C`. This right adjoint is written `Π_B` and is interpreted as dependent product. Given `f : A ⟶ B` in `C/B`, the iterated slice `(C/B)/f` is isomorphic to `C/A`. -/ noncomputable theory namespace category_theory open category limits universes v u variables {C : Type u} [category.{v} C] -- def has_finite_products_of_has_finite_limits [has_finite_limits.{v} C] : has_finite_products.{v} C := -- λ _ _ _, by resetI; apply_instance def has_finite_coproducts_of_has_finite_colimits [has_finite_colimits.{v} C] : has_finite_coproducts.{v} C := λ _ _ _, by resetI; apply_instance @[simps] def over_iso {B : C} {f g : over B} (hl : f.left ≅ g.left) (hw : hl.hom ≫ g.hom = f.hom) : f ≅ g := { hom := over.hom_mk hl.hom, inv := over.hom_mk hl.inv (by simp [iso.inv_comp_eq, hw]) } section adjunction variable (B : C) section variable [has_pullbacks.{v} C] @[simps] def real_pullback {A B : C} (f : A ⟶ B) : over B ⥤ over A := { obj := λ g, over.mk (pullback.snd : pullback g.hom f ⟶ A), map := λ g h k, over.hom_mk (pullback.lift (pullback.fst ≫ k.left) pullback.snd (by simp [pullback.condition])) (by tidy) } end section variable [has_binary_products.{v} C] @[simps] def star : C ⥤ over B := { obj := λ A, over.mk (limits.prod.fst : B ⨯ A ⟶ B), map := λ X Y f, over.hom_mk (limits.prod.map (𝟙 _) f), map_id' := λ X, begin apply over.over_morphism.ext, dsimp, simp, end, map_comp' := λ X Y Z f g, begin apply over.over_morphism.ext, dsimp, ext, { rw [limits.prod.map_fst, comp_id, assoc, limits.prod.map_fst, comp_id, limits.prod.map_fst, comp_id] }, { rw [limits.prod.map_snd, assoc, limits.prod.map_snd, limits.prod.map_snd_assoc] } end } local attribute [tidy] tactic.case_bash def forget_adj_star : over.forget B ⊣ star B := adjunction.mk_of_hom_equiv { hom_equiv := λ g A, { to_fun := λ f, over.hom_mk (prod.lift g.hom f), inv_fun := λ k, k.left ≫ limits.prod.snd, left_inv := λ f, prod.lift_snd _ _, right_inv := λ k, begin ext; dsimp, rw prod.lift_fst, rw ← over.w k, refl, rw prod.lift_snd, end }, hom_equiv_naturality_right' := λ X Y Y' f g, begin dsimp, ext1, dsimp, rw prod.lift_map, rw comp_id, end, hom_equiv_naturality_left_symm' := λ X' X Y f g, begin dsimp, rw assoc end } end def exponentiable_of_star_is_left_adj [has_finite_products C] (h : is_left_adjoint (star B)) : exponentiable B := { is_adj := { right := star B ⋙ h.right, adj := adjunction.comp _ _ h.adj (forget_adj_star B) } } def dependent_sum {A B : C} (f : A ⟶ B) : over A ⥤ over B := (over.iterated_slice_equiv (over.mk f)).inverse ⋙ over.forget _ /-- `over.map f` gives nice definitional equalities but `dependent_sum` makes it easy to prove adjunction properties -/ def over_map_iso_dependent_sum {A B : C} (f : A ⟶ B) : dependent_sum f ≅ over.map f := begin refine nat_iso.of_components (λ X, over_iso (iso.refl _) (id_comp _)) (λ X Y g, _), { ext1, change g.left ≫ 𝟙 _ = 𝟙 _ ≫ g.left, rw [comp_id, id_comp] } end def over_map_id {A : C} : over.map (𝟙 A) ≅ 𝟭 _ := nat_iso.of_components (λ X, over_iso (iso.refl _) (begin dsimp, simp end)) (λ X Y f, begin ext, dsimp, simp end) def over_map_comp {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) : over.map (f ≫ g) ≅ over.map f ⋙ over.map g := nat_iso.of_components (λ X, over_iso (iso.refl _) (begin dsimp, simp end)) (λ X Y f, begin ext, dsimp, simp end) -- local attribute [instance] has_finite_wide_pullbacks_of_has_finite_limits def pullback_along {A B : C} (f : A ⟶ B) [has_binary_products (over B)] : over B ⥤ over A := star (over.mk f) ⋙ (over.iterated_slice_equiv _).functor lemma jointly_mono {A B : C} [has_binary_products (over B)] {f g : over B} (t₁ t₂ : A ⟶ (g ⨯ f).left) : t₁ ≫ (limits.prod.fst : g ⨯ f ⟶ _).left = t₂ ≫ (limits.prod.fst : g ⨯ f ⟶ _).left → t₁ ≫ (limits.prod.snd : g ⨯ f ⟶ _).left = t₂ ≫ (limits.prod.snd : g ⨯ f ⟶ _).left → t₁ = t₂ := begin intros h₁ h₂, let A' : over B := over.mk (t₂ ≫ (g ⨯ f).hom), -- usually easier in practice to use the second one have : t₁ ≫ (g ⨯ f).hom = t₂ ≫ (g ⨯ f).hom, rw [← over.w (limits.prod.fst : g ⨯ f ⟶ _), reassoc_of h₁], let t₁' : A' ⟶ g ⨯ f := over.hom_mk t₁ this, let t₂' : A' ⟶ g ⨯ f := over.hom_mk t₂, suffices : t₁' = t₂', apply congr_arg comma_morphism.left this, apply prod.hom_ext; { ext1, assumption } end def iso_pb {A B : C} (f : A ⟶ B) [has_binary_products (over B)] [has_pullbacks C] : pullback_along f ≅ real_pullback f := begin refine nat_iso.of_components _ _, { intro X, let p : over B := over.mk (pullback.snd ≫ f : pullback X.hom f ⟶ B), let q : p ⟶ over.mk f ⨯ X := prod.lift (over.hom_mk pullback.snd rfl) (over.hom_mk pullback.fst pullback.condition), apply over_iso _ _, refine ⟨pullback.lift _ _ _, q.left, _, _⟩, { apply (limits.prod.snd : over.mk f ⨯ X ⟶ _).left }, { apply (limits.prod.fst : over.mk f ⨯ X ⟶ _).left }, { rw [over.w limits.prod.snd, ← over.w limits.prod.fst, over.mk_hom] }, { apply jointly_mono; simp [← over.comp_left] }, { apply pullback.hom_ext; simp [← over.comp_left] }, { apply pullback.lift_snd } }, { intros X Y g, ext1, dsimp [pullback_along], apply pullback.hom_ext, { simp only [assoc, pullback.lift_fst, ← over.comp_left, limits.prod.map_snd, pullback.lift_fst_assoc] }, { simp only [assoc, pullback.lift_snd, ← over.comp_left, limits.prod.map_fst, comp_id] } }, end section -- local attribute [instance] over.construct_products.over_binary_product_of_pullback def radj {A B : C} (f : A ⟶ B) [has_pullbacks C] : over.map f ⊣ real_pullback f := adjunction.mk_of_hom_equiv { hom_equiv := λ g h, { to_fun := λ X, over.hom_mk (pullback.lift X.left g.hom (over.w X)) (pullback.lift_snd _ _ _), inv_fun := λ Y, begin refine over.hom_mk _ _, refine Y.left ≫ pullback.fst, dsimp, rw [← over.w Y, assoc, pullback.condition, assoc], refl, end, left_inv := by tidy, right_inv := λ Y, by { ext, dsimp, simp, dsimp, rw [pullback.lift_snd, ← over.w Y], refl } } } -- (((over.mk f).iterated_slice_equiv.symm.to_adjunction.comp _ _ (forget_adj_star _)).of_nat_iso_left (over_map_iso_dependent_sum f)).of_nat_iso_right (iso_pb f) def pullback_id {A : C} [has_pullbacks C] : real_pullback (𝟙 A) ≅ 𝟭 _ := adjunction.right_adjoint_uniq (radj _) (adjunction.id.of_nat_iso_left over_map_id.symm) def pullback_comp {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [has_pullbacks C] : real_pullback (f ≫ g) ≅ real_pullback g ⋙ real_pullback f := adjunction.right_adjoint_uniq (radj _) (((radj _).comp _ _ (radj _)).of_nat_iso_left (over_map_comp _ _).symm) instance thing {A B : C} (f : A ⟶ B) [has_pullbacks C] : is_right_adjoint (real_pullback f) := ⟨_, radj f⟩ end variables [has_finite_products.{v} C] [has_pullbacks.{v} C] def Pi_obj [exponentiable B] (f : over B) : C := pullback ((exp B).map f.hom) (internalize_hom (𝟙 B)) @[simps] private def pi_obj.equiv [exponentiable B] (X : C) (Y : over B) : ((star B).obj X ⟶ Y) ≃ (X ⟶ Pi_obj B Y) := { to_fun := λ f, pullback.lift (cartesian_closed.curry f.left) (terminal.from _) (by { rw [internalize_hom, comp_id, ← curry_natural_left, ← curry_natural_right, limits.prod.map_fst, comp_id, over.w f], refl }), inv_fun := λ g, begin apply over.hom_mk _ _, { apply (cartesian_closed.uncurry (g ≫ pullback.fst)) }, { rw [← uncurry_natural_right, assoc, pullback.condition, ← assoc, uncurry_natural_left], dsimp [internalize_hom], rw [uncurry_curry, limits.prod.map_fst_assoc, comp_id, comp_id] } end, left_inv := λ f, by { ext1, simp }, right_inv := λ g, by { ext1, { simp }, { apply subsingleton.elim } } } private lemma pi_obj.natural_equiv [exponentiable B] (X' X : C) (Y : over B) (f : X' ⟶ X) (g : (star B).obj X ⟶ Y) : (pi_obj.equiv B X' Y).to_fun ((star B).map f ≫ g) = f ≫ (pi_obj.equiv B X Y).to_fun g := begin apply pullback.hom_ext, { simp [curry_natural_left] }, { apply subsingleton.elim } end def Pi_functor [exponentiable B] : over B ⥤ C := adjunction.right_adjoint_of_equiv (pi_obj.equiv B) (pi_obj.natural_equiv B) def star_adj_pi_of_exponentiable [exponentiable B] : star B ⊣ Pi_functor B := adjunction.adjunction_of_equiv_right _ _ instance star_is_left_adj_of_exponentiable [exponentiable B] : is_left_adjoint (star B) := ⟨Pi_functor B, star_adj_pi_of_exponentiable B⟩ end adjunction end category_theory
0d5a67a8c855cb35070f247c279d498e368b9ac9
f57749ca63d6416f807b770f67559503fdb21001
/library/data/finset/bigops.lean
ac69062389d4aedb8a043eb40ea29ffe579d6883
[ "Apache-2.0" ]
permissive
aliassaf/lean
bd54e85bed07b1ff6f01396551867b2677cbc6ac
f9b069b6a50756588b309b3d716c447004203152
refs/heads/master
1,610,982,152,948
1,438,916,029,000
1,438,916,029,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,711
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Haitao Zhang Finite unions and intersections on finsets. Note: for the moment we only do unions. We need to generalize bigops for intersections. -/ import data.finset.comb algebra.group_bigops open list namespace finset variables {A B : Type} [deceqA : decidable_eq A] [deceqB : decidable_eq B] /- Unionl and Union -/ section union definition to_comm_monoid_Union (B : Type) [deceqB : decidable_eq B] : algebra.comm_monoid (finset B) := ⦃ algebra.comm_monoid, mul := union, mul_assoc := union.assoc, one := empty, mul_one := union_empty, one_mul := empty_union, mul_comm := union.comm ⦄ open [classes] algebra local attribute finset.to_comm_monoid_Union [instance] include deceqB definition Unionl (l : list A) (f : A → finset B) : finset B := algebra.Prodl l f notation `⋃` binders `←` l, r:(scoped f, Unionl l f) := r definition Union (s : finset A) (f : A → finset B) : finset B := algebra.Prod s f notation `⋃` binders `∈` s, r:(scoped f, finset.Union s f) := r theorem Unionl_nil (f : A → finset B) : Unionl [] f = ∅ := algebra.Prodl_nil f theorem Unionl_cons (f : A → finset B) (a : A) (l : list A) : Unionl (a::l) f = f a ∪ Unionl l f := algebra.Prodl_cons f a l theorem Unionl_append (l₁ l₂ : list A) (f : A → finset B) : Unionl (l₁++l₂) f = Unionl l₁ f ∪ Unionl l₂ f := algebra.Prodl_append l₁ l₂ f theorem Unionl_mul (l : list A) (f g : A → finset B) : Unionl l (λx, f x ∪ g x) = Unionl l f ∪ Unionl l g := algebra.Prodl_mul l f g section deceqA include deceqA theorem Unionl_insert_of_mem (f : A → finset B) {a : A} {l : list A} (H : a ∈ l) : Unionl (list.insert a l) f = Unionl l f := algebra.Prodl_insert_of_mem f H theorem Unionl_insert_of_not_mem (f : A → finset B) {a : A} {l : list A} (H : a ∉ l) : Unionl (list.insert a l) f = f a ∪ Unionl l f := algebra.Prodl_insert_of_not_mem f H theorem Unionl_union {l₁ l₂ : list A} (f : A → finset B) (d : list.disjoint l₁ l₂) : Unionl (list.union l₁ l₂) f = Unionl l₁ f ∪ Unionl l₂ f := algebra.Prodl_union f d theorem Unionl_empty (l : list A) : Unionl l (λ x, ∅) = (∅ : finset B) := algebra.Prodl_one l end deceqA theorem Union_empty (f : A → finset B) : Union ∅ f = ∅ := algebra.Prod_empty f theorem Union_mul (s : finset A) (f g : A → finset B) : Union s (λx, f x ∪ g x) = Union s f ∪ Union s g := algebra.Prod_mul s f g section deceqA include deceqA theorem Union_insert_of_mem (f : A → finset B) {a : A} {s : finset A} (H : a ∈ s) : Union (insert a s) f = Union s f := algebra.Prod_insert_of_mem f H private theorem Union_insert_of_not_mem (f : A → finset B) {a : A} {s : finset A} (H : a ∉ s) : Union (insert a s) f = f a ∪ Union s f := algebra.Prod_insert_of_not_mem f H theorem Union_union (f : A → finset B) {s₁ s₂ : finset A} (disj : s₁ ∩ s₂ = ∅) : Union (s₁ ∪ s₂) f = Union s₁ f ∪ Union s₂ f := algebra.Prod_union f disj theorem Union_ext {s : finset A} {f g : A → finset B} (H : ∀x, x ∈ s → f x = g x) : Union s f = Union s g := algebra.Prod_ext H theorem Union_empty' (s : finset A) : Union s (λ x, ∅) = (∅ : finset B) := algebra.Prod_one s -- this will eventually be an instance of something more general theorem inter_Union (s : finset B) (t : finset A) (f : A → finset B) : s ∩ (⋃ x ∈ t, f x) = (⋃ x ∈ t, s ∩ f x) := begin induction t with s' x H IH, rewrite [*Union_empty, inter_empty], rewrite [*Union_insert_of_not_mem _ H, inter.distrib_left, IH], end theorem mem_Union_iff (s : finset A) (f : A → finset B) (b : B) : b ∈ (⋃ x ∈ s, f x) ↔ (∃ x, x ∈ s ∧ b ∈ f x ) := begin induction s with s' a H IH, rewrite [exists_mem_empty_eq], rewrite [Union_insert_of_not_mem _ H, mem_union_eq, IH, exists_mem_insert_eq] end theorem mem_Union_eq (s : finset A) (f : A → finset B) (b : B) : b ∈ (⋃ x ∈ s, f x) = (∃ x, x ∈ s ∧ b ∈ f x ) := propext !mem_Union_iff theorem Union_insert (f : A → finset B) {a : A} {s : finset A} : Union (insert a s) f = f a ∪ Union s f := decidable.by_cases (assume Pin : a ∈ s, begin rewrite [Union_insert_of_mem f Pin], apply ext, intro x, apply iff.intro, exact mem_union_r, rewrite [mem_union_eq], intro Por, exact or.elim Por (assume Pl, begin rewrite mem_Union_eq, exact (exists.intro a (and.intro Pin Pl)) end) (assume Pr, Pr) end) (assume H : a ∉ s, !Union_insert_of_not_mem H) lemma image_eq_Union_index_image (s : finset A) (f : A → finset B) : Union s f = Union (image f s) function.id := finset.induction_on s (by rewrite Union_empty) (take s1 a Pa IH, by rewrite [image_insert, *Union_insert, IH]) lemma Union_const [deceqB : decidable_eq B] {f : A → finset B} {s : finset A} {t : finset B} : s ≠ ∅ → (∀ x, x ∈ s → f x = t) → Union s f = t := begin induction s with a' s' H IH, {intros [H1, H2], exfalso, apply H1 !rfl}, intros [H1, H2], rewrite [Union_insert, H2 _ !mem_insert], cases (decidable.em (s' = ∅)) with [seq, sne], {rewrite [seq, Union_empty, union_empty]}, have H3 : ∀ x, x ∈ s' → f x = t, from (λ x H', H2 x (mem_insert_of_mem _ H')), rewrite [IH sne H3, union_self] end end deceqA end union end finset
831b77bce69ea6edd5ad1b30a80e65b41eac07de
3dc4623269159d02a444fe898d33e8c7e7e9461b
/.github/workflows/project_1_a_decrire/lean-scheme-submission/src/spectrum_of_a_ring/structure_presheaf_localization.lean
cfef59220b00a21451e64a04fa656146c03b71cd
[]
no_license
Or7ando/lean
cc003e6c41048eae7c34aa6bada51c9e9add9e66
d41169cf4e416a0d42092fb6bdc14131cee9dd15
refs/heads/master
1,650,600,589,722
1,587,262,906,000
1,587,262,906,000
255,387,160
0
0
null
null
null
null
UTF-8
Lean
false
false
2,646
lean
/- We show that R[1/S(D(f))] ≅ R[1/f]. Where S(U) := { r | U ⊆ D(r) } -/ import to_mathlib.localization.localization_alt import spectrum_of_a_ring.structure_presheaf universe u local attribute [instance] classical.prop_decidable noncomputable theory variables {R : Type u} [comm_ring R] open topological_space open classical open localization open localization_alt section localization_property -- Proof of the localization property. R[1/S(D(f))] ≃ R[1/f]. variables {U : opens (Spec R)} (BU : U ∈ D_fs R) lemma structure_presheaf.inverts_data : inverts_data (powers (some BU)) (of : R → localization R (S U)) := begin rintros ⟨s, Hs⟩, have HsS : s ∈ S (Spec.DO R (classical.some BU)) := (is_submonoid.power_subset (S.f_mem (classical.some BU))) Hs, rw ←classical.some_spec BU at HsS, use [⟦⟨1, ⟨s, HsS⟩⟩⟧], apply quotient.sound, use [1, is_submonoid.one_mem _], simp, end lemma structure_presheaf.has_denom_data : has_denom_data (powers (some BU)) (of : R → localization R (S U)) := begin intros x, have Hx := quotient.exists_rep x, rcases (classical.indefinite_description _ Hx) with ⟨⟨p, q⟩, Hpq⟩, rcases q with ⟨q, Hq⟩, change U.val ⊆ Spec.D'(q) at Hq, rw classical.some_spec BU at Hq, have Hea := pow_eq.of_Dfs_subset Hq, rcases (classical.indefinite_description _ Hea) with ⟨a, He⟩, rcases (classical.indefinite_description _ He) with ⟨e, Hfe⟩, use [⟨⟨(classical.some BU)^e, ⟨e, rfl⟩⟩, a * p⟩], dsimp only [subtype.coe_mk], rw [Hfe, ←Hpq], apply quotient.sound, use [1, is_submonoid.one_mem _], dsimp, ring, end lemma structure_presheaf.ker_le : ker (of : R → localization R (S U)) ≤ submonoid_ann (powers (some BU)) := begin intros x Hx, change localization.of x = 0 at Hx, erw quotient.eq at Hx, rcases Hx with ⟨s, ⟨Hs, Hx⟩⟩, simp at Hx, dsimp [S] at Hs, change U.val ⊆ Spec.D'(s) at Hs, rw classical.some_spec BU at Hs, have Hea := pow_eq.of_Dfs_subset Hs, rcases (classical.indefinite_description _ Hea) with ⟨a, He⟩, rcases (classical.indefinite_description _ He) with ⟨e, Hfe⟩, use [⟨x, ⟨(some BU)^e, ⟨e, rfl⟩⟩⟩], { dsimp only [subtype.coe_mk], rw [Hfe, mul_comm a, ←mul_assoc, Hx, zero_mul], }, { refl, } end lemma structure_presheaf.localization : is_localization_data (powers (some BU)) (of : R → localization R (S U)) := { inverts := structure_presheaf.inverts_data BU, has_denom := structure_presheaf.has_denom_data BU, ker_le := structure_presheaf.ker_le BU } end localization_property
60397caa3fc32ea3bbcac13b27a2b7e6563d2b03
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/sheaves/skyscraper.lean
08b19fe467af6c37a2d453f40223fa03fc6587af
[ "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
17,847
lean
/- Copyright (c) 2022 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jujian Zhang, Junyan Xu -/ import topology.sheaves.punit import topology.sheaves.stalks import topology.sheaves.functors /-! # Skyscraper (pre)sheaves > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A skyscraper (pre)sheaf `𝓕 : (pre)sheaf C X` is the (pre)sheaf with value `A` at point `p₀` that is supported only at open sets contain `p₀`, i.e. `𝓕(U) = A` if `p₀ ∈ U` and `𝓕(U) = *` if `p₀ ∉ U` where `*` is a terminal object of `C`. In terms of stalks, `𝓕` is supported at all specializations of `p₀`, i.e. if `p₀ ⤳ x` then `𝓕ₓ ≅ A` and if `¬ p₀ ⤳ x` then `𝓕ₓ ≅ *`. ## Main definitions * `skyscraper_presheaf`: `skyscraper_presheaf p₀ A` is the skyscraper presheaf at point `p₀` with value `A`. * `skyscraper_sheaf`: the skyscraper presheaf satisfies the sheaf condition. ## Main statements * `skyscraper_presheaf_stalk_of_specializes`: if `y ∈ closure {p₀}` then the stalk of `skyscraper_presheaf p₀ A` at `y` is `A`. * `skyscraper_presheaf_stalk_of_not_specializes`: if `y ∉ closure {p₀}` then the stalk of `skyscraper_presheaf p₀ A` at `y` is `*` the terminal object. TODO: generalize universe level when calculating stalks, after generalizing universe level of stalk. -/ noncomputable theory open topological_space Top category_theory category_theory.limits opposite universes u v w variables {X : Top.{u}} (p₀ : X) [Π (U : opens X), decidable (p₀ ∈ U)] section variables {C : Type v} [category.{w} C] [has_terminal C] (A : C) /-- A skyscraper presheaf is a presheaf supported at a single point: if `p₀ ∈ X` is a specified point, then the skyscraper presheaf `𝓕` with value `A` is defined by `U ↦ A` if `p₀ ∈ U` and `U ↦ *` if `p₀ ∉ A` where `*` is some terminal object. -/ @[simps] def skyscraper_presheaf : presheaf C X := { obj := λ U, if p₀ ∈ unop U then A else terminal C, map := λ U V i, if h : p₀ ∈ unop V then eq_to_hom $ by erw [if_pos h, if_pos (le_of_hom i.unop h)] else ((if_neg h).symm.rec terminal_is_terminal).from _, map_id' := λ U, (em (p₀ ∈ U.unop)).elim (λ h, dif_pos h) (λ h, ((if_neg h).symm.rec terminal_is_terminal).hom_ext _ _), map_comp' := λ U V W iVU iWV, begin by_cases hW : p₀ ∈ unop W, { have hV : p₀ ∈ unop V := le_of_hom iWV.unop hW, simp only [dif_pos hW, dif_pos hV, eq_to_hom_trans] }, { rw [dif_neg hW], apply ((if_neg hW).symm.rec terminal_is_terminal).hom_ext } end } lemma skyscraper_presheaf_eq_pushforward [hd : Π (U : opens (Top.of punit.{u+1})), decidable (punit.star ∈ U)] : skyscraper_presheaf p₀ A = continuous_map.const (Top.of punit) p₀ _* skyscraper_presheaf punit.star A := by convert_to @skyscraper_presheaf X p₀ (λ U, hd $ (opens.map $ continuous_map.const _ p₀).obj U) C _ _ A = _; congr <|> refl /-- Taking skyscraper presheaf at a point is functorial: `c ↦ skyscraper p₀ c` defines a functor by sending every `f : a ⟶ b` to the natural transformation `α` defined as: `α(U) = f : a ⟶ b` if `p₀ ∈ U` and the unique morphism to a terminal object in `C` if `p₀ ∉ U`. -/ @[simps] def skyscraper_presheaf_functor.map' {a b : C} (f : a ⟶ b) : skyscraper_presheaf p₀ a ⟶ skyscraper_presheaf p₀ b := { app := λ U, if h : p₀ ∈ U.unop then eq_to_hom (if_pos h) ≫ f ≫ eq_to_hom (if_pos h).symm else ((if_neg h).symm.rec terminal_is_terminal).from _, naturality' := λ U V i, begin simp only [skyscraper_presheaf_map], by_cases hV : p₀ ∈ V.unop, { have hU : p₀ ∈ U.unop := le_of_hom i.unop hV, split_ifs, simpa only [eq_to_hom_trans_assoc, category.assoc, eq_to_hom_trans], }, { apply ((if_neg hV).symm.rec terminal_is_terminal).hom_ext, }, end } lemma skyscraper_presheaf_functor.map'_id {a : C} : skyscraper_presheaf_functor.map' p₀ (𝟙 a) = 𝟙 _ := begin ext1, ext1, simp only [skyscraper_presheaf_functor.map'_app, nat_trans.id_app], split_ifs, { simp only [category.id_comp, category.comp_id, eq_to_hom_trans, eq_to_hom_refl], }, { apply ((if_neg h).symm.rec terminal_is_terminal).hom_ext, }, end lemma skyscraper_presheaf_functor.map'_comp {a b c : C} (f : a ⟶ b) (g : b ⟶ c) : skyscraper_presheaf_functor.map' p₀ (f ≫ g) = skyscraper_presheaf_functor.map' p₀ f ≫ skyscraper_presheaf_functor.map' p₀ g := begin ext1, ext1, simp only [skyscraper_presheaf_functor.map'_app, nat_trans.comp_app], split_ifs, { simp only [category.assoc, eq_to_hom_trans_assoc, eq_to_hom_refl, category.id_comp], }, { apply ((if_neg h).symm.rec terminal_is_terminal).hom_ext, }, end /-- Taking skyscraper presheaf at a point is functorial: `c ↦ skyscraper p₀ c` defines a functor by sending every `f : a ⟶ b` to the natural transformation `α` defined as: `α(U) = f : a ⟶ b` if `p₀ ∈ U` and the unique morphism to a terminal object in `C` if `p₀ ∉ U`. -/ @[simps] def skyscraper_presheaf_functor : C ⥤ presheaf C X := { obj := skyscraper_presheaf p₀, map := λ _ _, skyscraper_presheaf_functor.map' p₀, map_id' := λ _, skyscraper_presheaf_functor.map'_id p₀, map_comp' := λ _ _ _, skyscraper_presheaf_functor.map'_comp p₀ } end section -- In this section, we calculate the stalks for skyscraper presheaves. -- We need to restrict universe level. variables {C : Type v} [category.{u} C] (A : C) [has_terminal C] /-- The cocone at `A` for the stalk functor of `skyscraper_presheaf p₀ A` when `y ∈ closure {p₀}` -/ @[simps] def skyscraper_presheaf_cocone_of_specializes {y : X} (h : p₀ ⤳ y) : cocone ((open_nhds.inclusion y).op ⋙ skyscraper_presheaf p₀ A) := { X := A, ι := { app := λ U, eq_to_hom $ if_pos $ h.mem_open U.unop.1.2 U.unop.2, naturality' := λ U V inc, begin change dite _ _ _ ≫ _ = _, rw dif_pos, { erw [category.comp_id, eq_to_hom_trans], refl }, { exact h.mem_open V.unop.1.2 V.unop.2 }, end } } /-- The cocone at `A` for the stalk functor of `skyscraper_presheaf p₀ A` when `y ∈ closure {p₀}` is a colimit -/ noncomputable def skyscraper_presheaf_cocone_is_colimit_of_specializes {y : X} (h : p₀ ⤳ y) : is_colimit (skyscraper_presheaf_cocone_of_specializes p₀ A h) := { desc := λ c, eq_to_hom (if_pos trivial).symm ≫ c.ι.app (op ⊤), fac' := λ c U, begin rw ← c.w (hom_of_le $ (le_top : unop U ≤ _)).op, change _ ≫ _ ≫ dite _ _ _ ≫ _ = _, rw dif_pos, { simpa only [skyscraper_presheaf_cocone_of_specializes_ι_app, eq_to_hom_trans_assoc, eq_to_hom_refl, category.id_comp] }, { exact h.mem_open U.unop.1.2 U.unop.2 }, end, uniq' := λ c f h, by rw [← h, skyscraper_presheaf_cocone_of_specializes_ι_app, eq_to_hom_trans_assoc, eq_to_hom_refl, category.id_comp] } /-- If `y ∈ closure {p₀}`, then the stalk of `skyscraper_presheaf p₀ A` at `y` is `A`. -/ noncomputable def skyscraper_presheaf_stalk_of_specializes [has_colimits C] {y : X} (h : p₀ ⤳ y) : (skyscraper_presheaf p₀ A).stalk y ≅ A := colimit.iso_colimit_cocone ⟨_, skyscraper_presheaf_cocone_is_colimit_of_specializes p₀ A h⟩ /-- The cocone at `*` for the stalk functor of `skyscraper_presheaf p₀ A` when `y ∉ closure {p₀}` -/ @[simps] def skyscraper_presheaf_cocone (y : X) : cocone ((open_nhds.inclusion y).op ⋙ skyscraper_presheaf p₀ A) := { X := terminal C, ι := { app := λ U, terminal.from _, naturality' := λ U V inc, terminal_is_terminal.hom_ext _ _ } } /-- The cocone at `*` for the stalk functor of `skyscraper_presheaf p₀ A` when `y ∉ closure {p₀}` is a colimit -/ noncomputable def skyscraper_presheaf_cocone_is_colimit_of_not_specializes {y : X} (h : ¬p₀ ⤳ y) : is_colimit (skyscraper_presheaf_cocone p₀ A y) := let h1 : ∃ (U : open_nhds y), p₀ ∉ U.1 := let ⟨U, ho, h₀, hy⟩ := not_specializes_iff_exists_open.mp h in ⟨⟨⟨U, ho⟩, h₀⟩, hy⟩ in { desc := λ c, eq_to_hom (if_neg h1.some_spec).symm ≫ c.ι.app (op h1.some), fac' := λ c U, begin change _ = c.ι.app (op U.unop), simp only [← c.w (hom_of_le $ @inf_le_left _ _ h1.some U.unop).op, ← c.w (hom_of_le $ @inf_le_right _ _ h1.some U.unop).op, ← category.assoc], congr' 1, refine ((if_neg _).symm.rec terminal_is_terminal).hom_ext _ _, exact λ h, h1.some_spec h.1, end, uniq' := λ c f H, begin rw [← category.id_comp f, ← H, ← category.assoc], congr' 1, apply terminal_is_terminal.hom_ext, end } /-- If `y ∉ closure {p₀}`, then the stalk of `skyscraper_presheaf p₀ A` at `y` is isomorphic to a terminal object. -/ noncomputable def skyscraper_presheaf_stalk_of_not_specializes [has_colimits C] {y : X} (h : ¬p₀ ⤳ y) : (skyscraper_presheaf p₀ A).stalk y ≅ terminal C := colimit.iso_colimit_cocone ⟨_, skyscraper_presheaf_cocone_is_colimit_of_not_specializes _ A h⟩ /-- If `y ∉ closure {p₀}`, then the stalk of `skyscraper_presheaf p₀ A` at `y` is a terminal object -/ def skyscraper_presheaf_stalk_of_not_specializes_is_terminal [has_colimits C] {y : X} (h : ¬p₀ ⤳ y) : is_terminal ((skyscraper_presheaf p₀ A).stalk y) := is_terminal.of_iso terminal_is_terminal $ (skyscraper_presheaf_stalk_of_not_specializes _ _ h).symm lemma skyscraper_presheaf_is_sheaf : (skyscraper_presheaf p₀ A).is_sheaf := by classical; exact (presheaf.is_sheaf_iso_iff (eq_to_iso $ skyscraper_presheaf_eq_pushforward p₀ A)).mpr (sheaf.pushforward_sheaf_of_sheaf _ (presheaf.is_sheaf_on_punit_of_is_terminal _ (by { dsimp, rw if_neg, exact terminal_is_terminal, exact set.not_mem_empty punit.star }))) /-- The skyscraper presheaf supported at `p₀` with value `A` is the sheaf that assigns `A` to all opens `U` that contain `p₀` and assigns `*` otherwise. -/ def skyscraper_sheaf : sheaf C X := ⟨skyscraper_presheaf p₀ A, skyscraper_presheaf_is_sheaf _ _⟩ /-- Taking skyscraper sheaf at a point is functorial: `c ↦ skyscraper p₀ c` defines a functor by sending every `f : a ⟶ b` to the natural transformation `α` defined as: `α(U) = f : a ⟶ b` if `p₀ ∈ U` and the unique morphism to a terminal object in `C` if `p₀ ∉ U`. -/ def skyscraper_sheaf_functor : C ⥤ sheaf C X := { obj := λ c, skyscraper_sheaf p₀ c, map := λ a b f, Sheaf.hom.mk $ (skyscraper_presheaf_functor p₀).map f, map_id' := λ c, Sheaf.hom.ext _ _ $ (skyscraper_presheaf_functor p₀).map_id _, map_comp' := λ _ _ _ f g, Sheaf.hom.ext _ _ $ (skyscraper_presheaf_functor p₀).map_comp _ _ } namespace stalk_skyscraper_presheaf_adjunction_auxs variables [has_colimits C] /-- If `f : 𝓕.stalk p₀ ⟶ c`, then a natural transformation `𝓕 ⟶ skyscraper_presheaf p₀ c` can be defined by: `𝓕.germ p₀ ≫ f : 𝓕(U) ⟶ c` if `p₀ ∈ U` and the unique morphism to a terminal object if `p₀ ∉ U`. -/ @[simps] def to_skyscraper_presheaf {𝓕 : presheaf C X} {c : C} (f : 𝓕.stalk p₀ ⟶ c) : 𝓕 ⟶ skyscraper_presheaf p₀ c := { app := λ U, if h : p₀ ∈ U.unop then 𝓕.germ ⟨p₀, h⟩ ≫ f ≫ eq_to_hom (if_pos h).symm else ((if_neg h).symm.rec terminal_is_terminal).from _, naturality' := λ U V inc, begin dsimp, by_cases hV : p₀ ∈ V.unop, { have hU : p₀ ∈ U.unop := le_of_hom inc.unop hV, split_ifs, erw [←category.assoc, 𝓕.germ_res inc.unop, category.assoc, category.assoc, eq_to_hom_trans], refl, }, { split_ifs, apply ((if_neg hV).symm.rec terminal_is_terminal).hom_ext }, end } /-- If `f : 𝓕 ⟶ skyscraper_presheaf p₀ c` is a natural transformation, then there is a morphism `𝓕.stalk p₀ ⟶ c` defined as the morphism from colimit to cocone at `c`. -/ def from_stalk {𝓕 : presheaf C X} {c : C} (f : 𝓕 ⟶ skyscraper_presheaf p₀ c) : 𝓕.stalk p₀ ⟶ c := let χ : cocone ((open_nhds.inclusion p₀).op ⋙ 𝓕) := cocone.mk c $ { app := λ U, f.app (op U.unop.1) ≫ eq_to_hom (if_pos U.unop.2), naturality' := λ U V inc, begin dsimp, erw [category.comp_id, ←category.assoc, comp_eq_to_hom_iff, category.assoc, eq_to_hom_trans, f.naturality, skyscraper_presheaf_map], have hV : p₀ ∈ (open_nhds.inclusion p₀).obj V.unop := V.unop.2, split_ifs, simpa only [comp_eq_to_hom_iff, category.assoc, eq_to_hom_trans, eq_to_hom_refl, category.comp_id], end } in colimit.desc _ χ lemma to_skyscraper_from_stalk {𝓕 : presheaf C X} {c : C} (f : 𝓕 ⟶ skyscraper_presheaf p₀ c) : to_skyscraper_presheaf p₀ (from_stalk _ f) = f := nat_trans.ext _ _ $ funext $ λ U, (em (p₀ ∈ U.unop)).elim (λ h, by { dsimp, split_ifs, erw [←category.assoc, colimit.ι_desc, category.assoc, eq_to_hom_trans, eq_to_hom_refl, category.comp_id], refl }) $ λ h, by { dsimp, split_ifs, apply ((if_neg h).symm.rec terminal_is_terminal).hom_ext } lemma from_stalk_to_skyscraper {𝓕 : presheaf C X} {c : C} (f : 𝓕.stalk p₀ ⟶ c) : from_stalk p₀ (to_skyscraper_presheaf _ f) = f := colimit.hom_ext $ λ U, by { erw [colimit.ι_desc], dsimp, rw dif_pos U.unop.2, rw [category.assoc, category.assoc, eq_to_hom_trans, eq_to_hom_refl, category.comp_id, presheaf.germ], congr' 3, apply_fun opposite.unop using unop_injective, rw [unop_op], ext, refl } /-- The unit in `presheaf.stalk ⊣ skyscraper_presheaf_functor` -/ @[simps] protected def unit : 𝟭 (presheaf C X) ⟶ presheaf.stalk_functor C p₀ ⋙ skyscraper_presheaf_functor p₀ := { app := λ 𝓕, to_skyscraper_presheaf _ $ 𝟙 _, naturality' := λ 𝓕 𝓖 f, begin ext U, dsimp, split_ifs, { simp only [category.id_comp, ←category.assoc], rw [comp_eq_to_hom_iff], simp only [category.assoc, eq_to_hom_trans, eq_to_hom_refl, category.comp_id], erw [colimit.ι_map], refl, }, { apply ((if_neg h).symm.rec terminal_is_terminal).hom_ext, }, end } /-- The counit in `presheaf.stalk ⊣ skyscraper_presheaf_functor` -/ @[simps] protected def counit : (skyscraper_presheaf_functor p₀ ⋙ (presheaf.stalk_functor C p₀ : presheaf C X ⥤ C)) ⟶ 𝟭 C := { app := λ c, (skyscraper_presheaf_stalk_of_specializes p₀ c specializes_rfl).hom, naturality' := λ x y f, colimit.hom_ext $ λ U, begin erw [←category.assoc, colimit.ι_map, colimit.iso_colimit_cocone_ι_hom_assoc, skyscraper_presheaf_cocone_of_specializes_ι_app, category.assoc, colimit.ι_desc, whiskering_left_obj_map, whisker_left_app, skyscraper_presheaf_functor.map'_app, dif_pos U.unop.2, skyscraper_presheaf_cocone_of_specializes_ι_app, comp_eq_to_hom_iff, category.assoc, eq_to_hom_comp_iff, ←category.assoc, eq_to_hom_trans, eq_to_hom_refl, category.id_comp, comp_eq_to_hom_iff, category.assoc, eq_to_hom_trans, eq_to_hom_refl, category.comp_id, category_theory.functor.id_map], end } end stalk_skyscraper_presheaf_adjunction_auxs section open stalk_skyscraper_presheaf_adjunction_auxs /-- `skyscraper_presheaf_functor` is the right adjoint of `presheaf.stalk_functor` -/ def skyscraper_presheaf_stalk_adjunction [has_colimits C] : (presheaf.stalk_functor C p₀ : presheaf C X ⥤ C) ⊣ skyscraper_presheaf_functor p₀ := { hom_equiv := λ c 𝓕, { to_fun := to_skyscraper_presheaf _, inv_fun := from_stalk _, left_inv := from_stalk_to_skyscraper _, right_inv := to_skyscraper_from_stalk _ }, unit := stalk_skyscraper_presheaf_adjunction_auxs.unit _, counit := stalk_skyscraper_presheaf_adjunction_auxs.counit _, hom_equiv_unit' := λ 𝓕 c α, begin ext U, simp only [equiv.coe_fn_mk, to_skyscraper_presheaf_app, nat_trans.comp_app, skyscraper_presheaf_functor.map'_app, skyscraper_presheaf_functor_map, unit_app], split_ifs, { erw [category.id_comp, ←category.assoc, comp_eq_to_hom_iff, category.assoc, category.assoc, category.assoc, category.assoc, eq_to_hom_trans, eq_to_hom_refl, category.comp_id, ←category.assoc _ _ α, eq_to_hom_trans, eq_to_hom_refl, category.id_comp], }, { apply ((if_neg h).symm.rec terminal_is_terminal).hom_ext } end, hom_equiv_counit' := λ 𝓕 c α, begin ext U, simp only [equiv.coe_fn_symm_mk, counit_app], erw [colimit.ι_desc, ←category.assoc, colimit.ι_map, whisker_left_app, category.assoc, colimit.ι_desc], refl, end } instance [has_colimits C] : is_right_adjoint (skyscraper_presheaf_functor p₀ : C ⥤ presheaf C X) := ⟨_, skyscraper_presheaf_stalk_adjunction _⟩ instance [has_colimits C] : is_left_adjoint (presheaf.stalk_functor C p₀) := ⟨_, skyscraper_presheaf_stalk_adjunction _⟩ /-- Taking stalks of a sheaf is the left adjoint functor to `skyscraper_sheaf_functor` -/ def stalk_skyscraper_sheaf_adjunction [has_colimits C] : sheaf.forget C X ⋙ presheaf.stalk_functor _ p₀ ⊣ skyscraper_sheaf_functor p₀ := { hom_equiv := λ 𝓕 c, ⟨λ f, ⟨to_skyscraper_presheaf p₀ f⟩, λ g, from_stalk p₀ g.1, from_stalk_to_skyscraper p₀, λ g, by { ext1, apply to_skyscraper_from_stalk }⟩, unit := { app := λ 𝓕, ⟨(stalk_skyscraper_presheaf_adjunction_auxs.unit p₀).app 𝓕.1⟩, naturality' := λ 𝓐 𝓑 ⟨f⟩, by { ext1, apply (stalk_skyscraper_presheaf_adjunction_auxs.unit p₀).naturality } }, counit := stalk_skyscraper_presheaf_adjunction_auxs.counit p₀, hom_equiv_unit' := λ 𝓐 c f, by { ext1, exact (skyscraper_presheaf_stalk_adjunction p₀).hom_equiv_unit }, hom_equiv_counit' := λ 𝓐 c f, (skyscraper_presheaf_stalk_adjunction p₀).hom_equiv_counit } instance [has_colimits C] : is_right_adjoint (skyscraper_sheaf_functor p₀ : C ⥤ sheaf C X) := ⟨_, stalk_skyscraper_sheaf_adjunction _⟩ end end
75e7e561d71602744300943dbe8653e31906d339
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/logic/equiv/transfer_instance.lean
16a3667c8ae7cc7cb0167e0df142820603dba517
[ "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
17,009
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import algebra.algebra.basic import algebra.field.basic import logic.equiv.defs import ring_theory.ideal.local_ring /-! # Transfer algebraic structures across `equiv`s In this file we prove theorems of the following form: if `β` has a group structure and `α ≃ β` then `α` has a group structure, and similarly for monoids, semigroups, rings, integral domains, fields and so on. Note that most of these constructions can also be obtained using the `transport` tactic. ### Implementation details When adding new definitions that transfer type-classes across an equivalence, please mark them `@[reducible]`. See note [reducible non-instances]. ## Tags equiv, group, ring, field, module, algebra -/ universes u v variables {α : Type u} {β : Type v} namespace equiv section instances variables (e : α ≃ β) /-- Transfer `has_one` across an `equiv` -/ @[reducible, to_additive "Transfer `has_zero` across an `equiv`"] protected def has_one [has_one β] : has_one α := ⟨e.symm 1⟩ @[to_additive] lemma one_def [has_one β] : @has_one.one _ (equiv.has_one e) = e.symm 1 := rfl /-- Transfer `has_mul` across an `equiv` -/ @[reducible, to_additive "Transfer `has_add` across an `equiv`"] protected def has_mul [has_mul β] : has_mul α := ⟨λ x y, e.symm (e x * e y)⟩ @[to_additive] lemma mul_def [has_mul β] (x y : α) : @has_mul.mul _ (equiv.has_mul e) x y = e.symm (e x * e y) := rfl /-- Transfer `has_div` across an `equiv` -/ @[reducible, to_additive "Transfer `has_sub` across an `equiv`"] protected def has_div [has_div β] : has_div α := ⟨λ x y, e.symm (e x / e y)⟩ @[to_additive] lemma div_def [has_div β] (x y : α) : @has_div.div _ (equiv.has_div e) x y = e.symm (e x / e y) := rfl /-- Transfer `has_inv` across an `equiv` -/ @[reducible, to_additive "Transfer `has_neg` across an `equiv`"] protected def has_inv [has_inv β] : has_inv α := ⟨λ x, e.symm (e x)⁻¹⟩ @[to_additive] lemma inv_def [has_inv β] (x : α) : @has_inv.inv _ (equiv.has_inv e) x = e.symm (e x)⁻¹ := rfl /-- Transfer `has_smul` across an `equiv` -/ @[reducible] protected def has_smul (R : Type*) [has_smul R β] : has_smul R α := ⟨λ r x, e.symm (r • (e x))⟩ lemma smul_def {R : Type*} [has_smul R β] (r : R) (x : α) : @has_smul.smul _ _ (e.has_smul R) r x = e.symm (r • (e x)) := rfl /-- Transfer `has_pow` across an `equiv` -/ @[reducible, to_additive has_smul] protected def has_pow (N : Type*) [has_pow β N] : has_pow α N := ⟨λ x n, e.symm (e x ^ n)⟩ lemma pow_def {N : Type*} [has_pow β N] (n : N) (x : α) : @has_pow.pow _ _ (e.has_pow N) x n = e.symm (e x ^ n) := rfl /-- An equivalence `e : α ≃ β` gives a multiplicative equivalence `α ≃* β` where the multiplicative structure on `α` is the one obtained by transporting a multiplicative structure on `β` back along `e`. -/ @[to_additive "An equivalence `e : α ≃ β` gives a additive equivalence `α ≃+ β` where the additive structure on `α` is the one obtained by transporting an additive structure on `β` back along `e`."] def mul_equiv (e : α ≃ β) [has_mul β] : by { letI := equiv.has_mul e, exact α ≃* β } := begin introsI, exact { map_mul' := λ x y, by { apply e.symm.injective, simp, }, ..e } end @[simp, to_additive] lemma mul_equiv_apply (e : α ≃ β) [has_mul β] (a : α) : (mul_equiv e) a = e a := rfl @[to_additive] lemma mul_equiv_symm_apply (e : α ≃ β) [has_mul β] (b : β) : by { letI := equiv.has_mul e, exact (mul_equiv e).symm b = e.symm b } := begin intros, refl, end /-- An equivalence `e : α ≃ β` gives a ring equivalence `α ≃+* β` where the ring structure on `α` is the one obtained by transporting a ring structure on `β` back along `e`. -/ def ring_equiv (e : α ≃ β) [has_add β] [has_mul β] : by { letI := equiv.has_add e, letI := equiv.has_mul e, exact α ≃+* β } := begin introsI, exact { map_add' := λ x y, by { apply e.symm.injective, simp, }, map_mul' := λ x y, by { apply e.symm.injective, simp, }, ..e } end @[simp] lemma ring_equiv_apply (e : α ≃ β) [has_add β] [has_mul β] (a : α) : (ring_equiv e) a = e a := rfl lemma ring_equiv_symm_apply (e : α ≃ β) [has_add β] [has_mul β] (b : β) : by { letI := equiv.has_add e, letI := equiv.has_mul e, exact (ring_equiv e).symm b = e.symm b } := begin intros, refl, end /-- Transfer `semigroup` across an `equiv` -/ @[reducible, to_additive "Transfer `add_semigroup` across an `equiv`"] protected def semigroup [semigroup β] : semigroup α := let mul := e.has_mul in by resetI; apply e.injective.semigroup _; intros; exact e.apply_symm_apply _ /-- Transfer `semigroup_with_zero` across an `equiv` -/ @[reducible] protected def semigroup_with_zero [semigroup_with_zero β] : semigroup_with_zero α := let mul := e.has_mul, zero := e.has_zero in by resetI; apply e.injective.semigroup_with_zero _; intros; exact e.apply_symm_apply _ /-- Transfer `comm_semigroup` across an `equiv` -/ @[reducible, to_additive "Transfer `add_comm_semigroup` across an `equiv`"] protected def comm_semigroup [comm_semigroup β] : comm_semigroup α := let mul := e.has_mul in by resetI; apply e.injective.comm_semigroup _; intros; exact e.apply_symm_apply _ /-- Transfer `mul_zero_class` across an `equiv` -/ @[reducible] protected def mul_zero_class [mul_zero_class β] : mul_zero_class α := let zero := e.has_zero, mul := e.has_mul in by resetI; apply e.injective.mul_zero_class _; intros; exact e.apply_symm_apply _ /-- Transfer `mul_one_class` across an `equiv` -/ @[reducible, to_additive "Transfer `add_zero_class` across an `equiv`"] protected def mul_one_class [mul_one_class β] : mul_one_class α := let one := e.has_one, mul := e.has_mul in by resetI; apply e.injective.mul_one_class _; intros; exact e.apply_symm_apply _ /-- Transfer `mul_zero_one_class` across an `equiv` -/ @[reducible] protected def mul_zero_one_class [mul_zero_one_class β] : mul_zero_one_class α := let zero := e.has_zero, one := e.has_one,mul := e.has_mul in by resetI; apply e.injective.mul_zero_one_class _; intros; exact e.apply_symm_apply _ /-- Transfer `monoid` across an `equiv` -/ @[reducible, to_additive "Transfer `add_monoid` across an `equiv`"] protected def monoid [monoid β] : monoid α := let one := e.has_one, mul := e.has_mul, pow := e.has_pow ℕ in by resetI; apply e.injective.monoid _; intros; exact e.apply_symm_apply _ /-- Transfer `comm_monoid` across an `equiv` -/ @[reducible, to_additive "Transfer `add_comm_monoid` across an `equiv`"] protected def comm_monoid [comm_monoid β] : comm_monoid α := let one := e.has_one, mul := e.has_mul, pow := e.has_pow ℕ in by resetI; apply e.injective.comm_monoid _; intros; exact e.apply_symm_apply _ /-- Transfer `group` across an `equiv` -/ @[reducible, to_additive "Transfer `add_group` across an `equiv`"] protected def group [group β] : group α := let one := e.has_one, mul := e.has_mul, inv := e.has_inv, div := e.has_div, npow := e.has_pow ℕ, zpow := e.has_pow ℤ in by resetI; apply e.injective.group _; intros; exact e.apply_symm_apply _ /-- Transfer `comm_group` across an `equiv` -/ @[reducible, to_additive "Transfer `add_comm_group` across an `equiv`"] protected def comm_group [comm_group β] : comm_group α := let one := e.has_one, mul := e.has_mul, inv := e.has_inv, div := e.has_div, npow := e.has_pow ℕ, zpow := e.has_pow ℤ in by resetI; apply e.injective.comm_group _; intros; exact e.apply_symm_apply _ /-- Transfer `non_unital_non_assoc_semiring` across an `equiv` -/ @[reducible] protected def non_unital_non_assoc_semiring [non_unital_non_assoc_semiring β] : non_unital_non_assoc_semiring α := let zero := e.has_zero, add := e.has_add, mul := e.has_mul, nsmul := e.has_smul ℕ in by resetI; apply e.injective.non_unital_non_assoc_semiring _; intros; exact e.apply_symm_apply _ /-- Transfer `non_unital_semiring` across an `equiv` -/ @[reducible] protected def non_unital_semiring [non_unital_semiring β] : non_unital_semiring α := let zero := e.has_zero, add := e.has_add, mul := e.has_mul, nsmul := e.has_smul ℕ in by resetI; apply e.injective.non_unital_semiring _; intros; exact e.apply_symm_apply _ /-- Transfer `add_monoid_with_one` across an `equiv` -/ @[reducible] protected def add_monoid_with_one [add_monoid_with_one β] : add_monoid_with_one α := { nat_cast := λ n, e.symm n, nat_cast_zero := show e.symm _ = _, by simp [zero_def], nat_cast_succ := λ n, show e.symm _ = e.symm (e (e.symm _) + _), by simp [add_def, one_def], .. e.add_monoid, .. e.has_one } /-- Transfer `add_group_with_one` across an `equiv` -/ @[reducible] protected def add_group_with_one [add_group_with_one β] : add_group_with_one α := { int_cast := λ n, e.symm n, int_cast_of_nat := λ n, by rw [int.cast_coe_nat]; refl, int_cast_neg_succ_of_nat := λ n, congr_arg e.symm $ (int.cast_neg_succ_of_nat _).trans $ congr_arg _ (e.apply_symm_apply _).symm, .. e.add_monoid_with_one, .. e.add_group } /-- Transfer `non_assoc_semiring` across an `equiv` -/ @[reducible] protected def non_assoc_semiring [non_assoc_semiring β] : non_assoc_semiring α := let mul := e.has_mul, add_monoid_with_one := e.add_monoid_with_one in by resetI; apply e.injective.non_assoc_semiring _; intros; exact e.apply_symm_apply _ /-- Transfer `semiring` across an `equiv` -/ @[reducible] protected def semiring [semiring β] : semiring α := let mul := e.has_mul, add_monoid_with_one := e.add_monoid_with_one, npow := e.has_pow ℕ in by resetI; apply e.injective.semiring _; intros; exact e.apply_symm_apply _ /-- Transfer `non_unital_comm_semiring` across an `equiv` -/ @[reducible] protected def non_unital_comm_semiring [non_unital_comm_semiring β] : non_unital_comm_semiring α := let zero := e.has_zero, add := e.has_add, mul := e.has_mul, nsmul := e.has_smul ℕ in by resetI; apply e.injective.non_unital_comm_semiring _; intros; exact e.apply_symm_apply _ /-- Transfer `comm_semiring` across an `equiv` -/ @[reducible] protected def comm_semiring [comm_semiring β] : comm_semiring α := let mul := e.has_mul, add_monoid_with_one := e.add_monoid_with_one, npow := e.has_pow ℕ in by resetI; apply e.injective.comm_semiring _; intros; exact e.apply_symm_apply _ /-- Transfer `non_unital_non_assoc_ring` across an `equiv` -/ @[reducible] protected def non_unital_non_assoc_ring [non_unital_non_assoc_ring β] : non_unital_non_assoc_ring α := let zero := e.has_zero, add := e.has_add, mul := e.has_mul, neg := e.has_neg, sub := e.has_sub, nsmul := e.has_smul ℕ, zsmul := e.has_smul ℤ in by resetI; apply e.injective.non_unital_non_assoc_ring _; intros; exact e.apply_symm_apply _ /-- Transfer `non_unital_ring` across an `equiv` -/ @[reducible] protected def non_unital_ring [non_unital_ring β] : non_unital_ring α := let zero := e.has_zero, add := e.has_add, mul := e.has_mul, neg := e.has_neg, sub := e.has_sub, nsmul := e.has_smul ℕ, zsmul := e.has_smul ℤ in by resetI; apply e.injective.non_unital_ring _; intros; exact e.apply_symm_apply _ /-- Transfer `non_assoc_ring` across an `equiv` -/ @[reducible] protected def non_assoc_ring [non_assoc_ring β] : non_assoc_ring α := let add_group_with_one := e.add_group_with_one, mul := e.has_mul in by resetI; apply e.injective.non_assoc_ring _; intros; exact e.apply_symm_apply _ /-- Transfer `ring` across an `equiv` -/ @[reducible] protected def ring [ring β] : ring α := let mul := e.has_mul, add_group_with_one := e.add_group_with_one, npow := e.has_pow ℕ in by resetI; apply e.injective.ring _; intros; exact e.apply_symm_apply _ /-- Transfer `non_unital_comm_ring` across an `equiv` -/ @[reducible] protected def non_unital_comm_ring [non_unital_comm_ring β] : non_unital_comm_ring α := let zero := e.has_zero, add := e.has_add, mul := e.has_mul, neg := e.has_neg, sub := e.has_sub, nsmul := e.has_smul ℕ, zsmul := e.has_smul ℤ in by resetI; apply e.injective.non_unital_comm_ring _; intros; exact e.apply_symm_apply _ /-- Transfer `comm_ring` across an `equiv` -/ @[reducible] protected def comm_ring [comm_ring β] : comm_ring α := let mul := e.has_mul, add_group_with_one := e.add_group_with_one, npow := e.has_pow ℕ in by resetI; apply e.injective.comm_ring _; intros; exact e.apply_symm_apply _ /-- Transfer `nontrivial` across an `equiv` -/ @[reducible] protected theorem nontrivial [nontrivial β] : nontrivial α := e.surjective.nontrivial /-- Transfer `is_domain` across an `equiv` -/ @[reducible] protected theorem is_domain [ring α] [ring β] [is_domain β] (e : α ≃+* β) : is_domain α := function.injective.is_domain e.to_ring_hom e.injective /-- Transfer `has_rat_cast` across an `equiv` -/ @[reducible] protected def has_rat_cast [has_rat_cast β] : has_rat_cast α := { rat_cast := λ n, e.symm n } /-- Transfer `division_ring` across an `equiv` -/ @[reducible] protected def division_ring [division_ring β] : division_ring α := let add_group_with_one := e.add_group_with_one, mul := e.has_mul, inv := e.has_inv, div := e.has_div, mul := e.has_mul, npow := e.has_pow ℕ, zpow := e.has_pow ℤ, rat_cast := e.has_rat_cast, qsmul := e.has_smul ℚ in by resetI; apply e.injective.division_ring _; intros; exact e.apply_symm_apply _ /-- Transfer `field` across an `equiv` -/ @[reducible] protected def field [field β] : field α := let add_group_with_one := e.add_group_with_one, mul := e.has_mul, neg := e.has_neg, inv := e.has_inv, div := e.has_div, mul := e.has_mul, npow := e.has_pow ℕ, zpow := e.has_pow ℤ, rat_cast := e.has_rat_cast, qsmul := e.has_smul ℚ in by resetI; apply e.injective.field _; intros; exact e.apply_symm_apply _ section R variables (R : Type*) include R section variables [monoid R] /-- Transfer `mul_action` across an `equiv` -/ @[reducible] protected def mul_action (e : α ≃ β) [mul_action R β] : mul_action R α := { one_smul := by simp [smul_def], mul_smul := by simp [smul_def, mul_smul], ..e.has_smul R } /-- Transfer `distrib_mul_action` across an `equiv` -/ @[reducible] protected def distrib_mul_action (e : α ≃ β) [add_comm_monoid β] : begin letI := equiv.add_comm_monoid e, exact Π [distrib_mul_action R β], distrib_mul_action R α end := begin intros, letI := equiv.add_comm_monoid e, exact ( { smul_zero := by simp [zero_def, smul_def], smul_add := by simp [add_def, smul_def, smul_add], ..equiv.mul_action R e } : distrib_mul_action R α) end end section variables [semiring R] /-- Transfer `module` across an `equiv` -/ @[reducible] protected def module (e : α ≃ β) [add_comm_monoid β] : begin letI := equiv.add_comm_monoid e, exact Π [module R β], module R α end := begin introsI, exact ( { zero_smul := by simp [zero_def, smul_def], add_smul := by simp [add_def, smul_def, add_smul], ..equiv.distrib_mul_action R e } : module R α) end /-- An equivalence `e : α ≃ β` gives a linear equivalence `α ≃ₗ[R] β` where the `R`-module structure on `α` is the one obtained by transporting an `R`-module structure on `β` back along `e`. -/ def linear_equiv (e : α ≃ β) [add_comm_monoid β] [module R β] : begin letI := equiv.add_comm_monoid e, letI := equiv.module R e, exact α ≃ₗ[R] β end := begin introsI, exact { map_smul' := λ r x, by { apply e.symm.injective, simp, refl, }, ..equiv.add_equiv e } end end section variables [comm_semiring R] /-- Transfer `algebra` across an `equiv` -/ @[reducible] protected def algebra (e : α ≃ β) [semiring β] : begin letI := equiv.semiring e, exact Π [algebra R β], algebra R α end := begin introsI, fapply ring_hom.to_algebra', { exact ((ring_equiv e).symm : β →+* α).comp (algebra_map R β), }, { intros r x, simp only [function.comp_app, ring_hom.coe_comp], have p := ring_equiv_symm_apply e, dsimp at p, erw p, clear p, apply (ring_equiv e).injective, simp only [(ring_equiv e).map_mul], simp [algebra.commutes], } end /-- An equivalence `e : α ≃ β` gives an algebra equivalence `α ≃ₐ[R] β` where the `R`-algebra structure on `α` is the one obtained by transporting an `R`-algebra structure on `β` back along `e`. -/ def alg_equiv (e : α ≃ β) [semiring β] [algebra R β] : begin letI := equiv.semiring e, letI := equiv.algebra R e, exact α ≃ₐ[R] β end := begin introsI, exact { commutes' := λ r, by { apply e.symm.injective, simp, refl, }, ..equiv.ring_equiv e } end end end R end instances end equiv namespace ring_equiv @[reducible] protected lemma local_ring {A B : Type*} [comm_semiring A] [local_ring A] [comm_semiring B] (e : A ≃+* B) : local_ring B := begin haveI := e.symm.to_equiv.nontrivial, exact local_ring.of_surjective (e : A →+* B) e.surjective end end ring_equiv
8901f608e4fb7c25004a3427ff48bacc1b42ed74
367134ba5a65885e863bdc4507601606690974c1
/src/algebra/lie/nilpotent.lean
8bc4d4727a4e9560c38745b42b6e726248b2aa49
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
5,460
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.solvable /-! # Nilpotent Lie algebras Like groups, Lie algebras admit a natural concept of nilpotency. More generally, any Lie module carries a natural concept of nilpotency. We define these here via the lower central series. ## Main definitions * `lie_module.lower_central_series` * `lie_module.is_nilpotent` ## Tags lie algebra, lower central series, nilpotent -/ universes u v w w₁ w₂ namespace lie_module variables (R : Type u) (L : Type v) (M : Type w) variables [comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M] variables [lie_ring_module L M] [lie_module R L M] /-- The lower central series of Lie submodules of a Lie module. -/ def lower_central_series (k : ℕ) : lie_submodule R L M := (λ I, ⁅(⊤ : lie_ideal R L), I⁆)^[k] ⊤ @[simp] lemma lower_central_series_zero : lower_central_series R L M 0 = ⊤ := rfl @[simp] lemma lower_central_series_succ (k : ℕ) : lower_central_series R L M (k + 1) = ⁅(⊤ : lie_ideal R L), lower_central_series R L M k⁆ := function.iterate_succ_apply' (λ I, ⁅(⊤ : lie_ideal R L), I⁆) k ⊤ lemma trivial_iff_lower_central_eq_bot : is_trivial L M ↔ lower_central_series R L M 1 = ⊥ := begin split; intros h, { erw [eq_bot_iff, lie_submodule.lie_span_le], rintros m ⟨x, n, hn⟩, rw [← hn, h.trivial], simp,}, { rw lie_submodule.eq_bot_iff at h, apply is_trivial.mk, intros x m, apply h, apply lie_submodule.subset_lie_span, use [x, m], refl, }, end open lie_algebra lemma derived_series_le_lower_central_series (k : ℕ) : derived_series R L k ≤ lower_central_series R L L k := begin induction k with k h, { exact le_refl _, }, { have h' : derived_series R L k ≤ ⊤, { by simp only [le_top], }, rw [derived_series_def, derived_series_of_ideal_succ, lower_central_series_succ], exact lie_submodule.mono_lie _ _ _ _ h' h, }, end /-- A Lie module is nilpotent if its lower central series reaches 0 (in a finite number of steps). -/ class is_nilpotent : Prop := (nilpotent : ∃ k, lower_central_series R L M k = ⊥) @[priority 100] instance trivial_is_nilpotent [is_trivial L M] : is_nilpotent R L M := ⟨by { use 1, change ⁅⊤, ⊤⁆ = ⊥, simp, }⟩ end lie_module @[priority 100] instance lie_algebra.is_solvable_of_is_nilpotent (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L] [hL : lie_module.is_nilpotent R L L] : lie_algebra.is_solvable R L := begin obtain ⟨k, h⟩ : ∃ k, lie_module.lower_central_series R L L k = ⊥ := hL.nilpotent, use k, rw ← le_bot_iff at h ⊢, exact le_trans (lie_module.derived_series_le_lower_central_series R L k) h, end section nilpotent_algebras -- TODO Generalise the below to Lie modules if / when we define morphisms, equivs of Lie modules -- covering a Lie algebra morphism of (possibly different) Lie algebras. variables (R : Type u) (L : Type v) (L' : Type w) variables [comm_ring R] [lie_ring L] [lie_algebra R L] [lie_ring L'] [lie_algebra R L'] /-- We say a Lie algebra is nilpotent when it is nilpotent as a Lie module over itself via the adjoint representation. -/ abbreviation lie_algebra.is_nilpotent (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L] : Prop := lie_module.is_nilpotent R L L variables {R L L'} open lie_algebra open lie_module (lower_central_series) lemma lie_ideal.lower_central_series_map_le (k : ℕ) {f : L →ₗ⁅R⁆ L'} : lie_ideal.map f (lower_central_series R L L k) ≤ lower_central_series R L' L' k := begin induction k with k ih, { simp only [lie_module.lower_central_series_zero, le_top], }, { simp only [lie_module.lower_central_series_succ], exact le_trans (lie_ideal.map_bracket_le f) (lie_submodule.mono_lie _ _ _ _ le_top ih), }, end lemma lie_ideal.lower_central_series_map_eq (k : ℕ) {f : L →ₗ⁅R⁆ L'} (h : function.surjective f) : lie_ideal.map f (lower_central_series R L L k) = lower_central_series R L' L' k := begin have h' : (⊤ : lie_ideal R L).map f = ⊤, { exact f.ideal_range_eq_top_of_surjective h, }, induction k with k ih, { simp only [lie_module.lower_central_series_zero], exact h', }, { simp only [lie_module.lower_central_series_succ, lie_ideal.map_bracket_eq f h, ih, h'], }, end lemma function.injective.lie_algebra_is_nilpotent [h₁ : is_nilpotent R L'] {f : L →ₗ⁅R⁆ L'} (h₂ : function.injective f) : is_nilpotent R L := { nilpotent := begin tactic.unfreeze_local_instances, obtain ⟨k, hk⟩ := h₁, use k, apply lie_ideal.bot_of_map_eq_bot h₂, rw [eq_bot_iff, ← hk], apply lie_ideal.lower_central_series_map_le, end, } lemma function.surjective.lie_algebra_is_nilpotent [h₁ : is_nilpotent R L] {f : L →ₗ⁅R⁆ L'} (h₂ : function.surjective f) : is_nilpotent R L' := { nilpotent := begin tactic.unfreeze_local_instances, obtain ⟨k, hk⟩ := h₁, use k, rw [← lie_ideal.lower_central_series_map_eq k h₂, hk], simp only [lie_ideal.map_eq_bot_iff, bot_le], end, } lemma lie_algebra.nilpotent_iff_equiv_nilpotent (e : L ≃ₗ⁅R⁆ L') : is_nilpotent R L ↔ is_nilpotent R L' := begin split; introsI h, { exact e.symm.injective.lie_algebra_is_nilpotent, }, { exact e.injective.lie_algebra_is_nilpotent, }, end end nilpotent_algebras
b080a9846fabd633f38d34de904c76249effe2ea
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/hott/algebra/category/constructions/comma.hlean
5f51b89d121d512ab6a07eabf7d6692d04a72c06
[ "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
6,765
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 Comma category -/ import ..functor.basic ..strict ..category open eq functor equiv sigma sigma.ops is_trunc iso is_equiv namespace category structure comma_object {A B C : Precategory} (S : A ⇒ C) (T : B ⇒ C) := (a : A) (b : B) (f : S a ⟶ T b) abbreviation ob1 [unfold 6] := @comma_object.a abbreviation ob2 [unfold 6] := @comma_object.b abbreviation mor [unfold 6] := @comma_object.f variables {A B C : Precategory} (S : A ⇒ C) (T : B ⇒ C) definition comma_object_sigma_char : (Σ(a : A) (b : B), S a ⟶ T b) ≃ comma_object S T := begin fapply equiv.MK, { intro u, exact comma_object.mk u.1 u.2.1 u.2.2}, { intro x, cases x with a b f, exact ⟨a, b, f⟩}, { intro x, cases x, reflexivity}, { intro u, cases u with u1 u2, cases u2, reflexivity}, end theorem is_trunc_comma_object (n : trunc_index) [HA : is_trunc n A] [HB : is_trunc n B] [H : Π(s d : C), is_trunc n (hom s d)] : is_trunc n (comma_object S T) := by apply is_trunc_equiv_closed;apply comma_object_sigma_char variables {S T} definition comma_object_eq' {x y : comma_object S T} (p : ob1 x = ob1 y) (q : ob2 x = ob2 y) (r : mor x =[ap011 (@hom C C) (ap (to_fun_ob S) p) (ap (to_fun_ob T) q)] mor y) : x = y := begin cases x with a b f, cases y with a' b' f', cases p, cases q, esimp [ap011,congr,ap,subst] at r, eapply (idp_rec_on r), reflexivity end --TODO: remove. This is a different version where Hq is not in square brackets -- definition eq_comp_inverse_of_comp_eq' {ob : Type} {C : precategory ob} {d c b : ob} {r : hom c d} -- {q : hom b c} {x : hom b d} {Hq : is_iso q} (p : r ∘ q = x) : r = x ∘ q⁻¹ʰ := -- sorry -- := sorry --eq_inverse_comp_of_comp_eq p definition comma_object_eq {x y : comma_object S T} (p : ob1 x = ob1 y) (q : ob2 x = ob2 y) (r : T (hom_of_eq q) ∘ mor x ∘ S (inv_of_eq p) = mor y) : x = y := begin cases x with a b f, cases y with a' b' f', cases p, cases q, apply ap (comma_object.mk a' b'), rewrite [▸* at r, -r, +respect_id, id_leftright] end definition ap_ob1_comma_object_eq' (x y : comma_object S T) (p : ob1 x = ob1 y) (q : ob2 x = ob2 y) (r : mor x =[ap011 (@hom C C) (ap (to_fun_ob S) p) (ap (to_fun_ob T) q)] mor y) : ap ob1 (comma_object_eq' p q r) = p := begin cases x with a b f, cases y with a' b' f', cases p, cases q, eapply (idp_rec_on r), reflexivity end definition ap_ob2_comma_object_eq' (x y : comma_object S T) (p : ob1 x = ob1 y) (q : ob2 x = ob2 y) (r : mor x =[ap011 (@hom C C) (ap (to_fun_ob S) p) (ap (to_fun_ob T) q)] mor y) : ap ob2 (comma_object_eq' p q r) = q := begin cases x with a b f, cases y with a' b' f', cases p, cases q, eapply (idp_rec_on r), reflexivity end structure comma_morphism (x y : comma_object S T) := mk' :: (g : ob1 x ⟶ ob1 y) (h : ob2 x ⟶ ob2 y) (p : T h ∘ mor x = mor y ∘ S g) (p' : mor y ∘ S g = T h ∘ mor x) abbreviation mor1 := @comma_morphism.g abbreviation mor2 := @comma_morphism.h abbreviation coh := @comma_morphism.p abbreviation coh' := @comma_morphism.p' protected definition comma_morphism.mk [constructor] [reducible] {x y : comma_object S T} (g h p) : comma_morphism x y := comma_morphism.mk' g h p p⁻¹ variables (x y z w : comma_object S T) definition comma_morphism_sigma_char : (Σ(g : ob1 x ⟶ ob1 y) (h : ob2 x ⟶ ob2 y), T h ∘ mor x = mor y ∘ S g) ≃ comma_morphism x y := begin fapply equiv.MK, { intro u, exact (comma_morphism.mk u.1 u.2.1 u.2.2)}, { intro f, cases f with g h p p', exact ⟨g, h, p⟩}, { intro f, cases f with g h p p', esimp, apply ap (comma_morphism.mk' g h p), apply is_prop.elim}, { intro u, cases u with u1 u2, cases u2 with u2 u3, reflexivity}, end theorem is_trunc_comma_morphism (n : trunc_index) [H1 : is_trunc n (ob1 x ⟶ ob1 y)] [H2 : is_trunc n (ob2 x ⟶ ob2 y)] [Hp : Πm1 m2, is_trunc n (T m2 ∘ mor x = mor y ∘ S m1)] : is_trunc n (comma_morphism x y) := by apply is_trunc_equiv_closed; apply comma_morphism_sigma_char variables {x y z w} definition comma_morphism_eq {f f' : comma_morphism x y} (p : mor1 f = mor1 f') (q : mor2 f = mor2 f') : f = f' := begin cases f with g h p₁ p₁', cases f' with g' h' p₂ p₂', cases p, cases q, apply ap011 (comma_morphism.mk' g' h'), apply is_prop.elim, apply is_prop.elim end definition comma_compose (g : comma_morphism y z) (f : comma_morphism x y) : comma_morphism x z := comma_morphism.mk (mor1 g ∘ mor1 f) (mor2 g ∘ mor2 f) (by rewrite [+respect_comp,-assoc,coh,assoc,coh,-assoc]) local infix `∘∘`:60 := comma_compose definition comma_id : comma_morphism x x := comma_morphism.mk id id (by rewrite [+respect_id,id_left,id_right]) theorem comma_assoc (h : comma_morphism z w) (g : comma_morphism y z) (f : comma_morphism x y) : h ∘∘ (g ∘∘ f) = (h ∘∘ g) ∘∘ f := comma_morphism_eq !assoc !assoc theorem comma_id_left (f : comma_morphism x y) : comma_id ∘∘ f = f := comma_morphism_eq !id_left !id_left theorem comma_id_right (f : comma_morphism x y) : f ∘∘ comma_id = f := comma_morphism_eq !id_right !id_right variables (S T) definition comma_category [constructor] : Precategory := precategory.MK (comma_object S T) comma_morphism (λa b, !is_trunc_comma_morphism) (@comma_compose _ _ _ _ _) (@comma_id _ _ _ _ _) (@comma_assoc _ _ _ _ _) (@comma_id_left _ _ _ _ _) (@comma_id_right _ _ _ _ _) --TODO: this definition doesn't use category structure of A and B definition strict_precategory_comma [HA : strict_precategory A] [HB : strict_precategory B] : strict_precategory (comma_object S T) := strict_precategory.mk (comma_category S T) !is_trunc_comma_object /- --set_option pp.notation false definition is_univalent_comma (HA : is_univalent A) (HB : is_univalent B) : is_univalent (comma_category S T) := begin intros c d, fapply adjointify, { intro i, cases i with f s, cases s with g l r, cases f with fA fB fp, cases g with gA gB gp, esimp at *, fapply comma_object_eq, {apply iso_of_eq⁻¹ᶠ, exact (iso.MK fA gA (ap mor1 l) (ap mor1 r))}, {apply iso_of_eq⁻¹ᶠ, exact (iso.MK fB gB (ap mor2 l) (ap mor2 r))}, { apply sorry /-rewrite hom_of_eq_eq_of_iso,-/ }}, { apply sorry}, { apply sorry}, end -/ end category
62d0a5724df530d9b47c4dbd1ea2414a77122296
da3a76c514d38801bae19e8a9e496dc31f8e5866
/library/init/meta/expr.lean
8ad27535084e0d842202c18349f2a6081e3e84b3
[ "Apache-2.0" ]
permissive
cipher1024/lean
270c1ac5781e6aee12f5c8d720d267563a164beb
f5cbdff8932dd30c6dd8eec68f3059393b4f8b3a
refs/heads/master
1,611,223,459,029
1,487,566,573,000
1,487,566,573,000
83,356,543
0
0
null
1,488,229,336,000
1,488,229,336,000
null
UTF-8
Lean
false
false
10,367
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.level inductive binder_info | default | implicit | strict_implicit | inst_implicit | other instance : has_to_string binder_info := ⟨λ bi, match bi with | binder_info.default := "default" | binder_info.implicit := "implicit" | binder_info.strict_implicit := "strict_implicit" | binder_info.inst_implicit := "inst_implicit" | binder_info.other := "other" end⟩ meta constant macro_def : Type /- Reflect a C++ expr object. The VM replaces it with the C++ implementation. -/ meta inductive expr | var : unsigned → expr | sort : level → expr | const : name → list level → expr | mvar : name → expr → expr | local_const : name → name → binder_info → expr → expr | app : expr → expr → expr | lam : name → binder_info → expr → expr → expr | pi : name → binder_info → expr → expr → expr | elet : name → expr → expr → expr → expr | macro : macro_def → ∀ n : unsigned, (fin (unsigned.to_nat n) → expr) → expr meta instance : inhabited expr := ⟨expr.sort level.zero⟩ meta constant expr.mk_macro (d : macro_def) : list expr → expr meta constant expr.macro_def_name (d : macro_def) : name meta def expr.mk_var (n : nat) : expr := expr.var (unsigned.of_nat n) /- Choice macros are used to implement overloading. -/ meta constant expr.is_choice_macro : expr → bool -- Compares expressions, including binder names. meta constant expr.has_decidable_eq : decidable_eq expr attribute [instance] expr.has_decidable_eq -- Compares expressions while ignoring binder names. meta constant expr.alpha_eqv : expr → expr → bool notation a ` =ₐ `:50 b:50 := expr.alpha_eqv a b = bool.tt protected meta constant expr.to_string : expr → string meta instance : has_to_string expr := has_to_string.mk expr.to_string /- Coercion for letting users write (f a) instead of (expr.app f a) -/ meta instance : has_coe_to_fun expr := { F := λ e, expr → expr, coe := λ e, expr.app e } meta constant expr.hash : expr → nat -- Compares expressions, ignoring binder names, and sorting by hash. meta constant expr.lt : expr → expr → bool -- Compares expressions, ignoring binder names. meta constant expr.lex_lt : expr → expr → bool -- Compares expressions, ignoring binder names, and sorting by hash. meta def expr.cmp (a b : expr) : ordering := if expr.lt a b then ordering.lt else if a =ₐ b then ordering.eq else ordering.gt meta constant expr.fold {α : Type} : expr → α → (expr → nat → α → α) → α meta constant expr.replace : expr → (expr → nat → option expr) → expr meta constant expr.abstract_local : expr → name → expr meta constant expr.abstract_locals : expr → list name → expr meta def expr.abstract : expr → expr → expr | e (expr.local_const n m bi t) := e^.abstract_local n | e _ := e meta constant expr.instantiate_univ_params : expr → list (name × level) → expr meta constant expr.instantiate_var : expr → expr → expr meta constant expr.instantiate_vars : expr → list expr → expr meta constant expr.has_var : expr → bool meta constant expr.has_var_idx : expr → nat → bool meta constant expr.has_local : expr → bool meta constant expr.has_meta_var : expr → bool meta constant expr.lift_vars : expr → nat → nat → expr meta constant expr.lower_vars : expr → nat → nat → expr /- (copy_pos_info src tgt) copy position information from src to tgt. -/ meta constant expr.copy_pos_info : expr → expr → expr meta constant expr.is_internal_cnstr : expr → option unsigned meta constant expr.get_nat_value : expr → option nat meta constant expr.collect_univ_params : expr → list name /-- `occurs e t` returns `tt` iff `e` occurs in `t` -/ meta constant expr.occurs : expr → expr → bool namespace expr open decidable -- Compares expressions, ignoring binder names, and sorting by hash. meta instance : has_ordering expr := ⟨ expr.cmp ⟩ meta def mk_true : expr := const `true [] meta def mk_false : expr := const `false [] /-- Returns the sorry macro with the given type. -/ meta constant mk_sorry (type : expr) : expr /-- Checks whether e is sorry, and returns its type. -/ meta constant is_sorry (e : expr) : option expr meta def is_var : expr → bool | (var _) := tt | _ := ff meta def app_of_list : expr → list expr → expr | f [] := f | f (p::ps) := app_of_list (f p) ps meta def is_app : expr → bool | (app f a) := tt | e := ff meta def app_fn : expr → expr | (app f a) := f | a := a meta def app_arg : expr → expr | (app f a) := a | a := a meta def get_app_fn : expr → expr | (app f a) := get_app_fn f | a := a meta def get_app_num_args : expr → nat | (app f a) := get_app_num_args f + 1 | e := 0 meta def get_app_args_aux : list expr → expr → list expr | r (app f a) := get_app_args_aux (a::r) f | r e := r meta def get_app_args : expr → list expr := get_app_args_aux [] meta def mk_app : expr → list expr → expr | e [] := e | e (x::xs) := mk_app (e x) xs meta def ith_arg_aux : expr → nat → expr | (app f a) 0 := a | (app f a) (n+1) := ith_arg_aux f n | e _ := e meta def ith_arg (e : expr) (i : nat) : expr := ith_arg_aux e (get_app_num_args e - i - 1) meta def const_name : expr → name | (const n ls) := n | e := name.anonymous meta def is_constant : expr → bool | (const n ls) := tt | e := ff meta def is_local_constant : expr → bool | (local_const n m bi t) := tt | e := ff meta def local_uniq_name : expr → name | (local_const n m bi t) := n | e := name.anonymous meta def local_pp_name : expr → name | (local_const x n bi t) := n | e := name.anonymous meta def local_type : expr → expr | (local_const _ _ _ t) := t | e := e meta def is_constant_of : expr → name → bool | (const n₁ ls) n₂ := n₁ = n₂ | e n := ff meta def is_app_of (e : expr) (n : name) : bool := is_constant_of (get_app_fn e) n meta def is_napp_of (e : expr) (c : name) (n : nat) : bool := is_app_of e c ∧ get_app_num_args e = n meta def is_false (e : expr) : bool := is_constant_of e `false meta def is_not : expr → option expr | (app f a) := if is_constant_of f `not then some a else none | (pi n bi a b) := if is_false b then some a else none | e := none meta def is_eq (e : expr) : option (expr × expr) := if is_napp_of e `eq 3 then some (app_arg (app_fn e), app_arg e) else none meta def is_ne (e : expr) : option (expr × expr) := if is_napp_of e `ne 3 then some (app_arg (app_fn e), app_arg e) else none meta def is_bin_arith_app (e : expr) (op : name) : option (expr × expr) := if is_napp_of e op 4 then some (app_arg (app_fn e), app_arg e) else none meta def is_lt (e : expr) : option (expr × expr) := is_bin_arith_app e `lt meta def is_gt (e : expr) : option (expr × expr) := is_bin_arith_app e `gt meta def is_le (e : expr) : option (expr × expr) := is_bin_arith_app e `le meta def is_ge (e : expr) : option (expr × expr) := is_bin_arith_app e `ge meta def is_heq (e : expr) : option (expr × expr × expr × expr) := if is_napp_of e `heq 4 then some (app_arg (app_fn (app_fn (app_fn e))), app_arg (app_fn (app_fn e)), app_arg (app_fn e), app_arg e) else none meta def is_pi : expr → bool | (pi _ _ _ _) := tt | e := ff meta def is_arrow : expr → bool | (pi _ _ _ b) := bnot (has_var b) | e := ff meta def is_let : expr → bool | (elet _ _ _ _) := tt | e := ff meta def binding_name : expr → name | (pi n _ _ _) := n | (lam n _ _ _) := n | e := name.anonymous meta def binding_info : expr → binder_info | (pi _ bi _ _) := bi | (lam _ bi _ _) := bi | e := binder_info.default meta def binding_domain : expr → expr | (pi _ _ d _) := d | (lam _ _ d _) := d | e := e meta def binding_body : expr → expr | (pi _ _ _ b) := b | (lam _ _ _ b) := b | e := e meta def prop : expr := expr.sort level.zero meta def imp (a b : expr) : expr := pi `a binder_info.default a b meta def and_ (a b : expr) : expr := app (app (const ``and []) a) b meta def not_ (a : expr) : expr := app (const ``not []) a meta def false_ : expr := const ``false [] meta def lambdas : list expr → expr → expr | (local_const uniq pp info t :: es) f := lam pp info t (abstract_local (lambdas es f) uniq) | _ f := f meta def pis : list expr → expr → expr | (local_const uniq pp info t :: es) f := pi pp info t (abstract_local (pis es f) uniq) | _ f := f open format private meta def p := λ xs, paren (format.join (list.intersperse " " xs)) private meta def macro_args_to_list_aux (n : unsigned) (args : fin (unsigned.to_nat n) → expr) : Π (i : nat), i ≤ n^.to_nat → list expr | 0 _ := [] | (i+1) h := args ⟨i, h⟩ :: macro_args_to_list_aux i (nat.le_trans (nat.le_succ _) h) meta def macro_args_to_list (n : unsigned) (args : fin (unsigned.to_nat n) → expr) : list expr := macro_args_to_list_aux n args n^.to_nat (nat.le_refl _) meta def to_raw_fmt : expr → format | (var n) := p ["var", to_fmt n^.to_nat] | (sort l) := p ["sort", to_fmt l] | (const n ls) := p ["const", to_fmt n, to_fmt ls] | (mvar n t) := p ["mvar", to_fmt n, to_raw_fmt t] | (local_const n m bi t) := p ["local_const", to_fmt n, to_fmt m, to_raw_fmt t] | (app e f) := p ["app", to_raw_fmt e, to_raw_fmt f] | (lam n bi e t) := p ["lam", to_fmt n, to_string bi, to_raw_fmt e, to_raw_fmt t] | (pi n bi e t) := p ["pi", to_fmt n, to_string bi, to_raw_fmt e, to_raw_fmt t] | (elet n g e f) := p ["elet", to_fmt n, to_raw_fmt g, to_raw_fmt e, to_raw_fmt f] | (macro d n args) := sbracket (format.join (list.intersperse " " ("macro" :: to_fmt (macro_def_name d) :: list.map to_raw_fmt (macro_args_to_list n args)))) meta def mfold {α : Type} {m : Type → Type} [monad m] (e : expr) (a : α) (fn : expr → nat → α → m α) : m α := fold e (return a) (λ e n a, a >>= fn e n) end expr
e45324d137281e6f2f6d55d2aaea4e87d9d5491a
b2fe74b11b57d362c13326bc5651244f111fa6f4
/src/data/option/basic.lean
8250f25d02702b3a86d4708220d1b1b9f261c54b
[ "Apache-2.0" ]
permissive
midfield/mathlib
c4db5fa898b5ac8f2f80ae0d00c95eb6f745f4c7
775edc615ecec631d65b6180dbcc7bc26c3abc26
refs/heads/master
1,675,330,551,921
1,608,304,514,000
1,608,304,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,773
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 tactic.basic namespace option variables {α : Type*} {β : Type*} {γ : Type*} lemma coe_def : (coe : α → option α) = some := rfl lemma some_ne_none (x : α) : some x ≠ none := λ h, option.no_confusion h @[simp] theorem get_mem : ∀ {o : option α} (h : is_some o), option.get h ∈ o | (some a) _ := rfl theorem get_of_mem {a : α} : ∀ {o : option α} (h : is_some o), a ∈ o → option.get h = a | _ _ rfl := rfl @[simp] lemma not_mem_none (a : α) : a ∉ (none : option α) := λ h, option.no_confusion h @[simp] lemma some_get : ∀ {x : option α} (h : is_some x), some (option.get h) = x | (some x) hx := rfl @[simp] lemma get_some (x : α) (h : is_some (some x)) : option.get h = x := rfl @[simp] lemma get_or_else_some (x y : α) : option.get_or_else (some x) y = x := rfl @[simp] lemma get_or_else_coe (x y : α) : option.get_or_else ↑x y = x := rfl lemma get_or_else_of_ne_none {x : option α} (hx : x ≠ none) (y : α) : some (x.get_or_else y) = x := by cases x; [contradiction, rw get_or_else_some] theorem mem_unique {o : option α} {a b : α} (ha : a ∈ o) (hb : b ∈ o) : a = b := option.some.inj $ ha.symm.trans hb theorem some_injective (α : Type*) : function.injective (@some α) := λ _ _, some_inj.mp /-- `option.map f` is injective if `f` is injective. -/ theorem map_injective {f : α → β} (Hf : function.injective f) : function.injective (option.map f) | none none H := rfl | (some a₁) (some a₂) H := by rw Hf (option.some.inj H) @[ext] theorem ext : ∀ {o₁ o₂ : option α}, (∀ a, a ∈ o₁ ↔ a ∈ o₂) → o₁ = o₂ | none none H := rfl | (some a) o H := ((H _).1 rfl).symm | o (some b) H := (H _).2 rfl theorem eq_none_iff_forall_not_mem {o : option α} : o = none ↔ (∀ a, a ∉ o) := ⟨λ e a h, by rw e at h; cases h, λ h, ext $ by simpa⟩ @[simp] theorem none_bind {α β} (f : α → option β) : none >>= f = none := rfl @[simp] theorem some_bind {α β} (a : α) (f : α → option β) : some a >>= f = f a := rfl @[simp] theorem none_bind' (f : α → option β) : none.bind f = none := rfl @[simp] theorem some_bind' (a : α) (f : α → option β) : (some a).bind f = f a := rfl @[simp] theorem bind_some : ∀ x : option α, x >>= some = x := @bind_pure α option _ _ @[simp] theorem bind_eq_some {α β} {x : option α} {f : α → option β} {b : β} : x >>= f = some b ↔ ∃ a, x = some a ∧ f a = some b := by cases x; simp @[simp] theorem bind_eq_some' {x : option α} {f : α → option β} {b : β} : x.bind f = some b ↔ ∃ a, x = some a ∧ f a = some b := by cases x; simp @[simp] theorem bind_eq_none' {o : option α} {f : α → option β} : o.bind f = none ↔ (∀ b a, a ∈ o → b ∉ f a) := by simp only [eq_none_iff_forall_not_mem, not_exists, not_and, mem_def, bind_eq_some'] @[simp] theorem bind_eq_none {α β} {o : option α} {f : α → option β} : o >>= f = none ↔ (∀ b a, a ∈ o → b ∉ f a) := bind_eq_none' lemma bind_comm {α β γ} {f : α → β → option γ} (a : option α) (b : option β) : a.bind (λx, b.bind (f x)) = b.bind (λy, a.bind (λx, f x y)) := by cases a; cases b; refl lemma bind_assoc (x : option α) (f : α → option β) (g : β → option γ) : (x.bind f).bind g = x.bind (λ y, (f y).bind g) := by cases x; refl @[simp] lemma map_eq_map {α β} {f : α → β} : (<$>) f = option.map f := rfl theorem map_none {α β} {f : α → β} : f <$> none = none := rfl theorem map_some {α β} {a : α} {f : α → β} : f <$> some a = some (f a) := rfl @[simp] theorem map_none' {f : α → β} : option.map f none = none := rfl @[simp] theorem map_some' {a : α} {f : α → β} : option.map f (some a) = some (f a) := rfl theorem map_eq_some {α β} {x : option α} {f : α → β} {b : β} : f <$> x = some b ↔ ∃ a, x = some a ∧ f a = b := by cases x; simp @[simp] theorem map_eq_some' {x : option α} {f : α → β} {b : β} : x.map f = some b ↔ ∃ a, x = some a ∧ f a = b := by cases x; simp @[simp] theorem map_id' : option.map (@id α) = id := map_id @[simp] lemma map_map (h : β → γ) (g : α → β) (x : option α) : option.map h (option.map g x) = option.map (h ∘ g) x := by { cases x; simp only [map_none', map_some'] } lemma comp_map (h : β → γ) (g : α → β) (x : option α) : option.map (h ∘ g) x = option.map h (option.map g x) := (map_map _ _ _).symm @[simp] lemma map_comp_map (f : α → β) (g : β → γ) : option.map g ∘ option.map f = option.map (g ∘ f) := by { ext x, rw comp_map } @[simp] theorem seq_some {α β} {a : α} {f : α → β} : some f <*> some a = some (f a) := rfl @[simp] theorem some_orelse' (a : α) (x : option α) : (some a).orelse x = some a := rfl @[simp] theorem some_orelse (a : α) (x : option α) : (some a <|> x) = some a := rfl @[simp] theorem none_orelse' (x : option α) : none.orelse x = x := by cases x; refl @[simp] theorem none_orelse (x : option α) : (none <|> x) = x := none_orelse' x @[simp] theorem orelse_none' (x : option α) : x.orelse none = x := by cases x; refl @[simp] theorem orelse_none (x : option α) : (x <|> none) = x := orelse_none' x @[simp] theorem is_some_none : @is_some α none = ff := rfl @[simp] theorem is_some_some {a : α} : is_some (some a) = tt := rfl theorem is_some_iff_exists {x : option α} : is_some x ↔ ∃ a, x = some a := by cases x; simp [is_some]; exact ⟨_, rfl⟩ @[simp] theorem is_none_none : @is_none α none = tt := rfl @[simp] theorem is_none_some {a : α} : is_none (some a) = ff := rfl @[simp] theorem not_is_some {a : option α} : is_some a = ff ↔ a.is_none = tt := by cases a; simp lemma eq_some_iff_get_eq {o : option α} {a : α} : o = some a ↔ ∃ h : o.is_some, option.get h = a := by cases o; simp lemma not_is_some_iff_eq_none {o : option α} : ¬o.is_some ↔ o = none := by cases o; simp lemma ne_none_iff_is_some {o : option α} : o ≠ none ↔ o.is_some := by cases o; simp lemma ne_none_iff_exists {o : option α} : o ≠ none ↔ ∃ (x : α), some x = o := by {cases o; simp} lemma ne_none_iff_exists' {o : option α} : o ≠ none ↔ ∃ (x : α), o = some x := ne_none_iff_exists.trans $ exists_congr $ λ _, eq_comm lemma bex_ne_none {p : option α → Prop} : (∃ x ≠ none, p x) ↔ ∃ x, p (some x) := ⟨λ ⟨x, hx, hp⟩, ⟨get $ ne_none_iff_is_some.1 hx, by rwa [some_get]⟩, λ ⟨x, hx⟩, ⟨some x, some_ne_none x, hx⟩⟩ lemma ball_ne_none {p : option α → Prop} : (∀ x ≠ none, p x) ↔ ∀ x, p (some x) := ⟨λ h x, h (some x) (some_ne_none x), λ h x hx, by simpa only [some_get] using h (get $ ne_none_iff_is_some.1 hx)⟩ theorem iget_mem [inhabited α] : ∀ {o : option α}, is_some o → o.iget ∈ o | (some a) _ := rfl theorem iget_of_mem [inhabited α] {a : α} : ∀ {o : option α}, a ∈ o → o.iget = a | _ rfl := rfl @[simp] theorem guard_eq_some {p : α → Prop} [decidable_pred p] {a b : α} : guard p a = some b ↔ a = b ∧ p a := by by_cases p a; simp [option.guard, h]; intro; contradiction @[simp] theorem guard_eq_some' {p : Prop} [decidable p] : ∀ u, _root_.guard p = some u ↔ p | () := by by_cases p; simp [guard, h, pure]; intro; contradiction theorem lift_or_get_choice {f : α → α → α} (h : ∀ a b, f a b = a ∨ f a b = b) : ∀ o₁ o₂, lift_or_get f o₁ o₂ = o₁ ∨ lift_or_get f o₁ o₂ = o₂ | none none := or.inl rfl | (some a) none := or.inl rfl | none (some b) := or.inr rfl | (some a) (some b) := by simpa [lift_or_get] using h a b @[simp] lemma lift_or_get_none_left {f} {b : option α} : lift_or_get f none b = b := by cases b; refl @[simp] lemma lift_or_get_none_right {f} {a : option α} : lift_or_get f a none = a := by cases a; refl @[simp] lemma lift_or_get_some_some {f} {a b : α} : lift_or_get f (some a) (some b) = f a b := rfl /-- given an element of `a : option α`, a default element `b : β` and a function `α → β`, apply this function to `a` if it comes from `α`, and return `b` otherwise. -/ def cases_on' : option α → β → (α → β) → β | none n s := n | (some a) n s := s a @[simp] lemma cases_on'_none (x : β) (f : α → β) : cases_on' none x f = x := rfl @[simp] lemma cases_on'_some (x : β) (f : α → β) (a : α) : cases_on' (some a) x f = f a := rfl @[simp] lemma cases_on'_coe (x : β) (f : α → β) (a : α) : cases_on' (a : option α) x f = f a := rfl @[simp] lemma cases_on'_none_coe (f : option α → β) (o : option α) : cases_on' o (f none) (f ∘ coe) = f o := by cases o; refl end option