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
2c8c1791ec1c5b8066df6e5525a7ad2a38ee261e
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/logic/basic.lean
0a712ccba10a8dc61e05afb98813b50d97829f0f
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
66,796
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura -/ import tactic.doc_commands import tactic.reserved_notation /-! # Basic logic properties This file is one of the earliest imports in mathlib. ## Implementation notes Theorems that require decidability hypotheses are in the namespace "decidable". Classical versions are in the namespace "classical". In the presence of automation, this whole file may be unnecessary. On the other hand, maybe it is useful for writing automation. -/ open function local attribute [instance, priority 10] classical.prop_decidable section miscellany /- We add the `inline` attribute to optimize VM computation using these declarations. For example, `if p ∧ q then ... else ...` will not evaluate the decidability of `q` if `p` is false. -/ attribute [inline] and.decidable or.decidable decidable.false xor.decidable iff.decidable decidable.true implies.decidable not.decidable ne.decidable bool.decidable_eq decidable.to_bool attribute [simp] cast_eq cast_heq variables {α : Type*} {β : Type*} /-- An identity function with its main argument implicit. This will be printed as `hidden` even if it is applied to a large term, so it can be used for elision, as done in the `elide` and `unelide` tactics. -/ @[reducible] def hidden {α : Sort*} {a : α} := a /-- Ex falso, the nondependent eliminator for the `empty` type. -/ def empty.elim {C : Sort*} : empty → C. instance : subsingleton empty := ⟨λa, a.elim⟩ instance subsingleton.prod {α β : Type*} [subsingleton α] [subsingleton β] : subsingleton (α × β) := ⟨by { intros a b, cases a, cases b, congr, }⟩ instance : decidable_eq empty := λa, a.elim instance sort.inhabited : inhabited Sort* := ⟨punit⟩ instance sort.inhabited' : inhabited default := ⟨punit.star⟩ instance psum.inhabited_left {α β} [inhabited α] : inhabited (psum α β) := ⟨psum.inl default⟩ instance psum.inhabited_right {α β} [inhabited β] : inhabited (psum α β) := ⟨psum.inr default⟩ @[priority 10] instance decidable_eq_of_subsingleton {α} [subsingleton α] : decidable_eq α | a b := is_true (subsingleton.elim a b) @[simp] lemma eq_iff_true_of_subsingleton {α : Sort*} [subsingleton α] (x y : α) : x = y ↔ true := by cc /-- If all points are equal to a given point `x`, then `α` is a subsingleton. -/ lemma subsingleton_of_forall_eq {α : Sort*} (x : α) (h : ∀ y, y = x) : subsingleton α := ⟨λ a b, (h a).symm ▸ (h b).symm ▸ rfl⟩ lemma subsingleton_iff_forall_eq {α : Sort*} (x : α) : subsingleton α ↔ ∀ y, y = x := ⟨λ h y, @subsingleton.elim _ h y x, subsingleton_of_forall_eq x⟩ instance subtype.subsingleton (α : Sort*) [subsingleton α] (p : α → Prop) : subsingleton (subtype p) := ⟨λ ⟨x,_⟩ ⟨y,_⟩, have x = y, from subsingleton.elim _ _, by { cases this, refl }⟩ /-- Add an instance to "undo" coercion transitivity into a chain of coercions, because most simp lemmas are stated with respect to simple coercions and will not match when part of a chain. -/ @[simp] theorem coe_coe {α β γ} [has_coe α β] [has_coe_t β γ] (a : α) : (a : γ) = (a : β) := rfl theorem coe_fn_coe_trans {α β γ δ} [has_coe α β] [has_coe_t_aux β γ] [has_coe_to_fun γ δ] (x : α) : @coe_fn α _ _ x = @coe_fn β _ _ x := rfl /-- Non-dependent version of `coe_fn_coe_trans`, helps `rw` figure out the argument. -/ theorem coe_fn_coe_trans' {α β γ} {δ : out_param $ _} [has_coe α β] [has_coe_t_aux β γ] [has_coe_to_fun γ (λ _, δ)] (x : α) : @coe_fn α _ _ x = @coe_fn β _ _ x := rfl @[simp] theorem coe_fn_coe_base {α β γ} [has_coe α β] [has_coe_to_fun β γ] (x : α) : @coe_fn α _ _ x = @coe_fn β _ _ x := rfl /-- Non-dependent version of `coe_fn_coe_base`, helps `rw` figure out the argument. -/ theorem coe_fn_coe_base' {α β} {γ : out_param $ _} [has_coe α β] [has_coe_to_fun β (λ _, γ)] (x : α) : @coe_fn α _ _ x = @coe_fn β _ _ x := rfl -- This instance should have low priority, to ensure we follow the chain -- `set_like → has_coe_to_sort` attribute [instance, priority 10] coe_sort_trans theorem coe_sort_coe_trans {α β γ δ} [has_coe α β] [has_coe_t_aux β γ] [has_coe_to_sort γ δ] (x : α) : @coe_sort α _ _ x = @coe_sort β _ _ x := rfl /-- Many structures such as bundled morphisms coerce to functions so that you can transparently apply them to arguments. For example, if `e : α ≃ β` and `a : α` then you can write `e a` and this is elaborated as `⇑e a`. This type of coercion is implemented using the `has_coe_to_fun` type class. There is one important consideration: If a type coerces to another type which in turn coerces to a function, then it **must** implement `has_coe_to_fun` directly: ```lean structure sparkling_equiv (α β) extends α ≃ β -- if we add a `has_coe` instance, instance {α β} : has_coe (sparkling_equiv α β) (α ≃ β) := ⟨sparkling_equiv.to_equiv⟩ -- then a `has_coe_to_fun` instance **must** be added as well: instance {α β} : has_coe_to_fun (sparkling_equiv α β) := ⟨λ _, α → β, λ f, f.to_equiv.to_fun⟩ ``` (Rationale: if we do not declare the direct coercion, then `⇑e a` is not in simp-normal form. The lemma `coe_fn_coe_base` will unfold it to `⇑↑e a`. This often causes loops in the simplifier.) -/ library_note "function coercion" @[simp] theorem coe_sort_coe_base {α β γ} [has_coe α β] [has_coe_to_sort β γ] (x : α) : @coe_sort α _ _ x = @coe_sort β _ _ x := rfl /-- `pempty` is the universe-polymorphic analogue of `empty`. -/ @[derive decidable_eq] inductive {u} pempty : Sort u /-- Ex falso, the nondependent eliminator for the `pempty` type. -/ def pempty.elim {C : Sort*} : pempty → C. instance subsingleton_pempty : subsingleton pempty := ⟨λa, a.elim⟩ @[simp] lemma not_nonempty_pempty : ¬ nonempty pempty := assume ⟨h⟩, h.elim lemma congr_heq {α β γ : Sort*} {f : α → γ} {g : β → γ} {x : α} {y : β} (h₁ : f == g) (h₂ : x == y) : f x = g y := by { cases h₂, cases h₁, refl } lemma congr_arg_heq {α} {β : α → Sort*} (f : ∀ a, β a) : ∀ {a₁ a₂ : α}, a₁ = a₂ → f a₁ == f a₂ | a _ rfl := heq.rfl lemma ulift.down_injective {α : Sort*} : function.injective (@ulift.down α) | ⟨a⟩ ⟨b⟩ rfl := rfl @[simp] lemma ulift.down_inj {α : Sort*} {a b : ulift α} : a.down = b.down ↔ a = b := ⟨λ h, ulift.down_injective h, λ h, by rw h⟩ lemma plift.down_injective {α : Sort*} : function.injective (@plift.down α) | ⟨a⟩ ⟨b⟩ rfl := rfl @[simp] lemma plift.down_inj {α : Sort*} {a b : plift α} : a.down = b.down ↔ a = b := ⟨λ h, plift.down_injective h, λ h, by rw h⟩ -- missing [symm] attribute for ne in core. attribute [symm] ne.symm lemma ne_comm {α} {a b : α} : a ≠ b ↔ b ≠ a := ⟨ne.symm, ne.symm⟩ @[simp] lemma eq_iff_eq_cancel_left {b c : α} : (∀ {a}, a = b ↔ a = c) ↔ (b = c) := ⟨λ h, by rw [← h], λ h a, by rw h⟩ @[simp] lemma eq_iff_eq_cancel_right {a b : α} : (∀ {c}, a = c ↔ b = c) ↔ (a = b) := ⟨λ h, by rw h, λ h a, by rw h⟩ /-- Wrapper for adding elementary propositions to the type class systems. Warning: this can easily be abused. See the rest of this docstring for details. Certain propositions should not be treated as a class globally, but sometimes it is very convenient to be able to use the type class system in specific circumstances. For example, `zmod p` is a field if and only if `p` is a prime number. In order to be able to find this field instance automatically by type class search, we have to turn `p.prime` into an instance implicit assumption. On the other hand, making `nat.prime` a class would require a major refactoring of the library, and it is questionable whether making `nat.prime` a class is desirable at all. The compromise is to add the assumption `[fact p.prime]` to `zmod.field`. In particular, this class is not intended for turning the type class system into an automated theorem prover for first order logic. -/ class fact (p : Prop) : Prop := (out [] : p) /-- In most cases, we should not have global instances of `fact`; typeclass search only reads the head symbol and then tries any instances, which means that adding any such instance will cause slowdowns everywhere. We instead make them as lemmata and make them local instances as required. -/ library_note "fact non-instances" lemma fact.elim {p : Prop} (h : fact p) : p := h.1 lemma fact_iff {p : Prop} : fact p ↔ p := ⟨λ h, h.1, λ h, ⟨h⟩⟩ /-- Swaps two pairs of arguments to a function. -/ @[reducible] def function.swap₂ {ι₁ ι₂ : Sort*} {κ₁ : ι₁ → Sort*} {κ₂ : ι₂ → Sort*} {φ : Π i₁, κ₁ i₁ → Π i₂, κ₂ i₂ → Sort*} (f : Π i₁ j₁ i₂ j₂, φ i₁ j₁ i₂ j₂) : Π i₂ j₂ i₁ j₁, φ i₁ j₁ i₂ j₂ := λ i₂ j₂ i₁ j₁, f i₁ j₁ i₂ j₂ /-- If `x : α . tac_name` then `x.out : α`. These are definitionally equal, but this can nevertheless be useful for various reasons, e.g. to apply further projection notation or in an argument to `simp`. -/ def auto_param.out {α : Sort*} {n : name} (x : auto_param α n) : α := x /-- If `x : α := d` then `x.out : α`. These are definitionally equal, but this can nevertheless be useful for various reasons, e.g. to apply further projection notation or in an argument to `simp`. -/ def opt_param.out {α : Sort*} {d : α} (x : α := d) : α := x end miscellany open function /-! ### Declarations about propositional connectives -/ theorem false_ne_true : false ≠ true | h := h.symm ▸ trivial section propositional variables {a b c d e f : Prop} /-! ### Declarations about `implies` -/ instance : is_refl Prop iff := ⟨iff.refl⟩ instance : is_trans Prop iff := ⟨λ _ _ _, iff.trans⟩ theorem iff_of_eq (e : a = b) : a ↔ b := e ▸ iff.rfl theorem iff_iff_eq : (a ↔ b) ↔ a = b := ⟨propext, iff_of_eq⟩ @[simp] lemma eq_iff_iff {p q : Prop} : (p = q) ↔ (p ↔ q) := iff_iff_eq.symm @[simp] theorem imp_self : (a → a) ↔ true := iff_true_intro id lemma iff.imp (h₁ : a ↔ b) (h₂ : c ↔ d) : (a → c) ↔ (b → d) := imp_congr h₁ h₂ @[simp] lemma eq_true_eq_id : eq true = id := by { funext, simp only [true_iff, id.def, iff_self, eq_iff_iff], } theorem imp_intro {α β : Prop} (h : α) : β → α := λ _, h theorem imp_false : (a → false) ↔ ¬ a := iff.rfl theorem imp_and_distrib {α} : (α → b ∧ c) ↔ (α → b) ∧ (α → c) := ⟨λ h, ⟨λ ha, (h ha).left, λ ha, (h ha).right⟩, λ h ha, ⟨h.left ha, h.right ha⟩⟩ @[simp] theorem and_imp : (a ∧ b → c) ↔ (a → b → c) := iff.intro (λ h ha hb, h ⟨ha, hb⟩) (λ h ⟨ha, hb⟩, h ha hb) theorem iff_def : (a ↔ b) ↔ (a → b) ∧ (b → a) := iff_iff_implies_and_implies _ _ theorem iff_def' : (a ↔ b) ↔ (b → a) ∧ (a → b) := iff_def.trans and.comm theorem imp_true_iff {α : Sort*} : (α → true) ↔ true := iff_true_intro $ λ_, trivial theorem imp_iff_right (ha : a) : (a → b) ↔ b := ⟨λf, f ha, imp_intro⟩ lemma imp_iff_not (hb : ¬ b) : a → b ↔ ¬ a := imp_congr_right $ λ _, iff_false_intro hb theorem decidable.imp_iff_right_iff [decidable a] : ((a → b) ↔ b) ↔ (a ∨ b) := ⟨λ H, (decidable.em a).imp_right $ λ ha', H.1 $ λ ha, (ha' ha).elim, λ H, H.elim imp_iff_right $ λ hb, ⟨λ hab, hb, λ _ _, hb⟩⟩ @[simp] theorem imp_iff_right_iff : ((a → b) ↔ b) ↔ (a ∨ b) := decidable.imp_iff_right_iff lemma decidable.and_or_imp [decidable a] : (a ∧ b) ∨ (a → c) ↔ a → (b ∨ c) := if ha : a then by simp only [ha, true_and, true_implies_iff] else by simp only [ha, false_or, false_and, false_implies_iff] @[simp] theorem and_or_imp : (a ∧ b) ∨ (a → c) ↔ a → (b ∨ c) := decidable.and_or_imp /-! ### Declarations about `not` -/ /-- Ex falso for negation. From `¬ a` and `a` anything follows. This is the same as `absurd` with the arguments flipped, but it is in the `not` namespace so that projection notation can be used. -/ def not.elim {α : Sort*} (H1 : ¬a) (H2 : a) : α := absurd H2 H1 @[reducible] theorem not.imp {a b : Prop} (H2 : ¬b) (H1 : a → b) : ¬a := mt H1 H2 theorem not_not_of_not_imp : ¬(a → b) → ¬¬a := mt not.elim theorem not_of_not_imp {a : Prop} : ¬(a → b) → ¬b := mt imp_intro theorem dec_em (p : Prop) [decidable p] : p ∨ ¬p := decidable.em p theorem dec_em' (p : Prop) [decidable p] : ¬p ∨ p := (dec_em p).swap theorem em (p : Prop) : p ∨ ¬p := classical.em _ theorem em' (p : Prop) : ¬p ∨ p := (em p).swap theorem or_not {p : Prop} : p ∨ ¬p := em _ section eq_or_ne variables {α : Sort*} (x y : α) theorem decidable.eq_or_ne [decidable (x = y)] : x = y ∨ x ≠ y := dec_em $ x = y theorem decidable.ne_or_eq [decidable (x = y)] : x ≠ y ∨ x = y := dec_em' $ x = y theorem eq_or_ne : x = y ∨ x ≠ y := em $ x = y theorem ne_or_eq : x ≠ y ∨ x = y := em' $ x = y end eq_or_ne theorem by_contradiction {p} : (¬p → false) → p := decidable.by_contradiction -- alias by_contradiction ← by_contra theorem by_contra {p} : (¬p → false) → p := decidable.by_contradiction /-- In most of mathlib, we use the law of excluded middle (LEM) and the axiom of choice (AC) freely. The `decidable` namespace contains versions of lemmas from the root namespace that explicitly attempt to avoid the axiom of choice, usually by adding decidability assumptions on the inputs. You can check if a lemma uses the axiom of choice by using `#print axioms foo` and seeing if `classical.choice` appears in the list. -/ library_note "decidable namespace" /-- As mathlib is primarily classical, if the type signature of a `def` or `lemma` does not require any `decidable` instances to state, it is preferable not to introduce any `decidable` instances that are needed in the proof as arguments, but rather to use the `classical` tactic as needed. In the other direction, when `decidable` instances do appear in the type signature, it is better to use explicitly introduced ones rather than allowing Lean to automatically infer classical ones, as these may cause instance mismatch errors later. -/ library_note "decidable arguments" -- See Note [decidable namespace] protected theorem decidable.not_not [decidable a] : ¬¬a ↔ a := iff.intro decidable.by_contradiction not_not_intro /-- The Double Negation Theorem: `¬ ¬ P` is equivalent to `P`. The left-to-right direction, double negation elimination (DNE), is classically true but not constructively. -/ @[simp] theorem not_not : ¬¬a ↔ a := decidable.not_not theorem of_not_not : ¬¬a → a := by_contra lemma not_ne_iff {α : Sort*} {a b : α} : ¬ a ≠ b ↔ a = b := not_not -- See Note [decidable namespace] protected theorem decidable.of_not_imp [decidable a] (h : ¬ (a → b)) : a := decidable.by_contradiction (not_not_of_not_imp h) theorem of_not_imp : ¬ (a → b) → a := decidable.of_not_imp -- See Note [decidable namespace] protected theorem decidable.not_imp_symm [decidable a] (h : ¬a → b) (hb : ¬b) : a := decidable.by_contradiction $ hb ∘ h theorem not.decidable_imp_symm [decidable a] : (¬a → b) → ¬b → a := decidable.not_imp_symm theorem not.imp_symm : (¬a → b) → ¬b → a := not.decidable_imp_symm -- See Note [decidable namespace] protected theorem decidable.not_imp_comm [decidable a] [decidable b] : (¬a → b) ↔ (¬b → a) := ⟨not.decidable_imp_symm, not.decidable_imp_symm⟩ theorem not_imp_comm : (¬a → b) ↔ (¬b → a) := decidable.not_imp_comm @[simp] theorem imp_not_self : (a → ¬a) ↔ ¬a := ⟨λ h ha, h ha ha, λ h _, h⟩ theorem decidable.not_imp_self [decidable a] : (¬a → a) ↔ a := by { have := @imp_not_self (¬a), rwa decidable.not_not at this } @[simp] theorem not_imp_self : (¬a → a) ↔ a := decidable.not_imp_self theorem imp.swap : (a → b → c) ↔ (b → a → c) := ⟨swap, swap⟩ theorem imp_not_comm : (a → ¬b) ↔ (b → ¬a) := imp.swap lemma iff.not (h : a ↔ b) : ¬ a ↔ ¬ b := not_congr h lemma iff.not_left (h : a ↔ ¬ b) : ¬ a ↔ b := h.not.trans not_not lemma iff.not_right (h : ¬ a ↔ b) : a ↔ ¬ b := not_not.symm.trans h.not /-! ### Declarations about `xor` -/ @[simp] theorem xor_true : xor true = not := funext $ λ a, by simp [xor] @[simp] theorem xor_false : xor false = id := funext $ λ a, by simp [xor] theorem xor_comm (a b) : xor a b = xor b a := by simp [xor, and_comm, or_comm] instance : is_commutative Prop xor := ⟨xor_comm⟩ @[simp] theorem xor_self (a : Prop) : xor a a = false := by simp [xor] /-! ### Declarations about `and` -/ lemma iff.and (h₁ : a ↔ b) (h₂ : c ↔ d) : a ∧ c ↔ b ∧ d := and_congr h₁ h₂ theorem and_congr_left (h : c → (a ↔ b)) : a ∧ c ↔ b ∧ c := and.comm.trans $ (and_congr_right h).trans and.comm theorem and_congr_left' (h : a ↔ b) : a ∧ c ↔ b ∧ c := h.and iff.rfl theorem and_congr_right' (h : b ↔ c) : a ∧ b ↔ a ∧ c := iff.rfl.and h theorem not_and_of_not_left (b : Prop) : ¬a → ¬(a ∧ b) := mt and.left theorem not_and_of_not_right (a : Prop) {b : Prop} : ¬b → ¬(a ∧ b) := mt and.right theorem and.imp_left (h : a → b) : a ∧ c → b ∧ c := and.imp h id theorem and.imp_right (h : a → b) : c ∧ a → c ∧ b := and.imp id h lemma and.right_comm : (a ∧ b) ∧ c ↔ (a ∧ c) ∧ b := by simp only [and.left_comm, and.comm] lemma and_and_and_comm (a b c d : Prop) : (a ∧ b) ∧ c ∧ d ↔ (a ∧ c) ∧ b ∧ d := by rw [←and_assoc, @and.right_comm a, and_assoc] lemma and_and_distrib_left (a b c : Prop) : a ∧ (b ∧ c) ↔ (a ∧ b) ∧ (a ∧ c) := by rw [and_and_and_comm, and_self] lemma and_and_distrib_right (a b c : Prop) : (a ∧ b) ∧ c ↔ (a ∧ c) ∧ (b ∧ c) := by rw [and_and_and_comm, and_self] lemma and_rotate : a ∧ b ∧ c ↔ b ∧ c ∧ a := by simp only [and.left_comm, and.comm] lemma and.rotate : a ∧ b ∧ c → b ∧ c ∧ a := and_rotate.1 theorem and_not_self_iff (a : Prop) : a ∧ ¬ a ↔ false := iff.intro (assume h, (h.right) (h.left)) (assume h, h.elim) theorem not_and_self_iff (a : Prop) : ¬ a ∧ a ↔ false := iff.intro (assume ⟨hna, ha⟩, hna ha) false.elim theorem and_iff_left_of_imp {a b : Prop} (h : a → b) : (a ∧ b) ↔ a := iff.intro and.left (λ ha, ⟨ha, h ha⟩) theorem and_iff_right_of_imp {a b : Prop} (h : b → a) : (a ∧ b) ↔ b := iff.intro and.right (λ hb, ⟨h hb, hb⟩) @[simp] theorem and_iff_left_iff_imp {a b : Prop} : ((a ∧ b) ↔ a) ↔ (a → b) := ⟨λ h ha, (h.2 ha).2, and_iff_left_of_imp⟩ @[simp] theorem and_iff_right_iff_imp {a b : Prop} : ((a ∧ b) ↔ b) ↔ (b → a) := ⟨λ h ha, (h.2 ha).1, and_iff_right_of_imp⟩ @[simp] lemma iff_self_and {p q : Prop} : (p ↔ p ∧ q) ↔ (p → q) := by rw [@iff.comm p, and_iff_left_iff_imp] @[simp] lemma iff_and_self {p q : Prop} : (p ↔ q ∧ p) ↔ (p → q) := by rw [and_comm, iff_self_and] @[simp] lemma and.congr_right_iff : (a ∧ b ↔ a ∧ c) ↔ (a → (b ↔ c)) := ⟨λ h ha, by simp [ha] at h; exact h, and_congr_right⟩ @[simp] lemma and.congr_left_iff : (a ∧ c ↔ b ∧ c) ↔ c → (a ↔ b) := by simp only [and.comm, ← and.congr_right_iff] @[simp] lemma and_self_left : a ∧ a ∧ b ↔ a ∧ b := ⟨λ h, ⟨h.1, h.2.2⟩, λ h, ⟨h.1, h.1, h.2⟩⟩ @[simp] lemma and_self_right : (a ∧ b) ∧ b ↔ a ∧ b := ⟨λ h, ⟨h.1.1, h.2⟩, λ h, ⟨⟨h.1, h.2⟩, h.2⟩⟩ /-! ### Declarations about `or` -/ lemma iff.or (h₁ : a ↔ b) (h₂ : c ↔ d) : a ∨ c ↔ b ∨ d := or_congr h₁ h₂ lemma or_congr_left' (h : a ↔ b) : a ∨ c ↔ b ∨ c := h.or iff.rfl lemma or_congr_right' (h : b ↔ c) : a ∨ b ↔ a ∨ c := iff.rfl.or h theorem or.right_comm : (a ∨ b) ∨ c ↔ (a ∨ c) ∨ b := by rw [or_assoc, or_assoc, or_comm b] lemma or_or_or_comm (a b c d : Prop) : (a ∨ b) ∨ c ∨ d ↔ (a ∨ c) ∨ b ∨ d := by rw [←or_assoc, @or.right_comm a, or_assoc] lemma or_or_distrib_left (a b c : Prop) : a ∨ (b ∨ c) ↔ (a ∨ b) ∨ (a ∨ c) := by rw [or_or_or_comm, or_self] lemma or_or_distrib_right (a b c : Prop) : (a ∨ b) ∨ c ↔ (a ∨ c) ∨ (b ∨ c) := by rw [or_or_or_comm, or_self] lemma or_rotate : a ∨ b ∨ c ↔ b ∨ c ∨ a := by simp only [or.left_comm, or.comm] lemma or.rotate : a ∨ b ∨ c → b ∨ c ∨ a := or_rotate.1 theorem or_of_or_of_imp_of_imp (h₁ : a ∨ b) (h₂ : a → c) (h₃ : b → d) : c ∨ d := or.imp h₂ h₃ h₁ theorem or_of_or_of_imp_left (h₁ : a ∨ c) (h : a → b) : b ∨ c := or.imp_left h h₁ theorem or_of_or_of_imp_right (h₁ : c ∨ a) (h : a → b) : c ∨ b := or.imp_right h h₁ theorem or.elim3 (h : a ∨ b ∨ c) (ha : a → d) (hb : b → d) (hc : c → d) : d := or.elim h ha (assume h₂, or.elim h₂ hb hc) lemma or.imp3 (had : a → d) (hbe : b → e) (hcf : c → f) : a ∨ b ∨ c → d ∨ e ∨ f := or.imp had $ or.imp hbe hcf theorem or_imp_distrib : (a ∨ b → c) ↔ (a → c) ∧ (b → c) := ⟨assume h, ⟨assume ha, h (or.inl ha), assume hb, h (or.inr hb)⟩, assume ⟨ha, hb⟩, or.rec ha hb⟩ -- See Note [decidable namespace] protected theorem decidable.or_iff_not_imp_left [decidable a] : a ∨ b ↔ (¬ a → b) := ⟨or.resolve_left, λ h, dite _ or.inl (or.inr ∘ h)⟩ theorem or_iff_not_imp_left : a ∨ b ↔ (¬ a → b) := decidable.or_iff_not_imp_left -- See Note [decidable namespace] protected theorem decidable.or_iff_not_imp_right [decidable b] : a ∨ b ↔ (¬ b → a) := or.comm.trans decidable.or_iff_not_imp_left theorem or_iff_not_imp_right : a ∨ b ↔ (¬ b → a) := decidable.or_iff_not_imp_right -- See Note [decidable namespace] protected lemma decidable.not_or_of_imp [decidable a] (h : a → b) : ¬ a ∨ b := dite _ (or.inr ∘ h) or.inl lemma not_or_of_imp : (a → b) → ¬ a ∨ b := decidable.not_or_of_imp -- See Note [decidable namespace] protected lemma decidable.or_not_of_imp [decidable a] (h : a → b) : b ∨ ¬ a := dite _ (or.inl ∘ h) or.inr lemma or_not_of_imp : (a → b) → b ∨ ¬ a := decidable.or_not_of_imp -- See Note [decidable namespace] protected lemma decidable.imp_iff_not_or [decidable a] : a → b ↔ ¬ a ∨ b := ⟨decidable.not_or_of_imp, or.neg_resolve_left⟩ lemma imp_iff_not_or : a → b ↔ ¬ a ∨ b := decidable.imp_iff_not_or -- See Note [decidable namespace] protected lemma decidable.imp_iff_or_not [decidable b] : b → a ↔ a ∨ ¬ b := decidable.imp_iff_not_or.trans or.comm lemma imp_iff_or_not : b → a ↔ a ∨ ¬ b := decidable.imp_iff_or_not -- See Note [decidable namespace] protected theorem decidable.not_imp_not [decidable a] : (¬ a → ¬ b) ↔ (b → a) := ⟨assume h hb, decidable.by_contradiction $ assume na, h na hb, mt⟩ theorem not_imp_not : (¬ a → ¬ b) ↔ (b → a) := decidable.not_imp_not -- See Note [decidable namespace] protected lemma decidable.or_congr_left [decidable c] (h : ¬ c → (a ↔ b)) : a ∨ c ↔ b ∨ c := by { rw [decidable.or_iff_not_imp_right, decidable.or_iff_not_imp_right], exact imp_congr_right h } lemma or_congr_left (h : ¬ c → (a ↔ b)) : a ∨ c ↔ b ∨ c := decidable.or_congr_left h -- See Note [decidable namespace] protected lemma decidable.or_congr_right [decidable a] (h : ¬ a → (b ↔ c)) : a ∨ b ↔ a ∨ c := by { rw [decidable.or_iff_not_imp_left, decidable.or_iff_not_imp_left], exact imp_congr_right h } lemma or_congr_right (h : ¬ a → (b ↔ c)) : a ∨ b ↔ a ∨ c := decidable.or_congr_right h @[simp] theorem or_iff_left_iff_imp : (a ∨ b ↔ a) ↔ (b → a) := ⟨λ h hb, h.1 (or.inr hb), or_iff_left_of_imp⟩ @[simp] theorem or_iff_right_iff_imp : (a ∨ b ↔ b) ↔ (a → b) := by rw [or_comm, or_iff_left_iff_imp] lemma or_iff_left (hb : ¬ b) : a ∨ b ↔ a := ⟨λ h, h.resolve_right hb, or.inl⟩ lemma or_iff_right (ha : ¬ a) : a ∨ b ↔ b := ⟨λ h, h.resolve_left ha, or.inr⟩ /-! ### Declarations about distributivity -/ /-- `∧` distributes over `∨` (on the left). -/ theorem and_or_distrib_left : a ∧ (b ∨ c) ↔ (a ∧ b) ∨ (a ∧ c) := ⟨λ ⟨ha, hbc⟩, hbc.imp (and.intro ha) (and.intro ha), or.rec (and.imp_right or.inl) (and.imp_right or.inr)⟩ /-- `∧` distributes over `∨` (on the right). -/ theorem or_and_distrib_right : (a ∨ b) ∧ c ↔ (a ∧ c) ∨ (b ∧ c) := (and.comm.trans and_or_distrib_left).trans (and.comm.or and.comm) /-- `∨` distributes over `∧` (on the left). -/ theorem or_and_distrib_left : a ∨ (b ∧ c) ↔ (a ∨ b) ∧ (a ∨ c) := ⟨or.rec (λha, and.intro (or.inl ha) (or.inl ha)) (and.imp or.inr or.inr), and.rec $ or.rec (imp_intro ∘ or.inl) (or.imp_right ∘ and.intro)⟩ /-- `∨` distributes over `∧` (on the right). -/ theorem and_or_distrib_right : (a ∧ b) ∨ c ↔ (a ∨ c) ∧ (b ∨ c) := (or.comm.trans or_and_distrib_left).trans (or.comm.and or.comm) @[simp] lemma or_self_left : a ∨ a ∨ b ↔ a ∨ b := ⟨λ h, h.elim or.inl id, λ h, h.elim or.inl (or.inr ∘ or.inr)⟩ @[simp] lemma or_self_right : (a ∨ b) ∨ b ↔ a ∨ b := ⟨λ h, h.elim id or.inr, λ h, h.elim (or.inl ∘ or.inl) or.inr⟩ /-! Declarations about `iff` -/ lemma iff.iff (h₁ : a ↔ b) (h₂ : c ↔ d) : (a ↔ c) ↔ (b ↔ d) := iff_congr h₁ h₂ theorem iff_of_true (ha : a) (hb : b) : a ↔ b := ⟨λ_, hb, λ _, ha⟩ theorem iff_of_false (ha : ¬a) (hb : ¬b) : a ↔ b := ⟨ha.elim, hb.elim⟩ theorem iff_true_left (ha : a) : (a ↔ b) ↔ b := ⟨λ h, h.1 ha, iff_of_true ha⟩ theorem iff_true_right (ha : a) : (b ↔ a) ↔ b := iff.comm.trans (iff_true_left ha) theorem iff_false_left (ha : ¬a) : (a ↔ b) ↔ ¬b := ⟨λ h, mt h.2 ha, iff_of_false ha⟩ theorem iff_false_right (ha : ¬a) : (b ↔ a) ↔ ¬b := iff.comm.trans (iff_false_left ha) @[simp] lemma iff_mpr_iff_true_intro {P : Prop} (h : P) : iff.mpr (iff_true_intro h) true.intro = h := rfl -- See Note [decidable namespace] protected theorem decidable.imp_or_distrib [decidable a] : (a → b ∨ c) ↔ (a → b) ∨ (a → c) := by simp [decidable.imp_iff_not_or, or.comm, or.left_comm] theorem imp_or_distrib : (a → b ∨ c) ↔ (a → b) ∨ (a → c) := decidable.imp_or_distrib -- See Note [decidable namespace] protected theorem decidable.imp_or_distrib' [decidable b] : (a → b ∨ c) ↔ (a → b) ∨ (a → c) := by by_cases b; simp [h, or_iff_right_of_imp ((∘) false.elim)] theorem imp_or_distrib' : (a → b ∨ c) ↔ (a → b) ∨ (a → c) := decidable.imp_or_distrib' theorem not_imp_of_and_not : a ∧ ¬ b → ¬ (a → b) | ⟨ha, hb⟩ h := hb $ h ha -- See Note [decidable namespace] protected theorem decidable.not_imp [decidable a] : ¬(a → b) ↔ a ∧ ¬b := ⟨λ h, ⟨decidable.of_not_imp h, not_of_not_imp h⟩, not_imp_of_and_not⟩ theorem not_imp : ¬(a → b) ↔ a ∧ ¬b := decidable.not_imp -- for monotonicity lemma imp_imp_imp (h₀ : c → a) (h₁ : b → d) : (a → b) → (c → d) := assume (h₂ : a → b), h₁ ∘ h₂ ∘ h₀ -- See Note [decidable namespace] protected theorem decidable.peirce (a b : Prop) [decidable a] : ((a → b) → a) → a := if ha : a then λ h, ha else λ h, h ha.elim theorem peirce (a b : Prop) : ((a → b) → a) → a := decidable.peirce _ _ theorem peirce' {a : Prop} (H : ∀ b : Prop, (a → b) → a) : a := H _ id -- See Note [decidable namespace] protected theorem decidable.not_iff_not [decidable a] [decidable b] : (¬ a ↔ ¬ b) ↔ (a ↔ b) := by rw [@iff_def (¬ a), @iff_def' a]; exact decidable.not_imp_not.and decidable.not_imp_not theorem not_iff_not : (¬ a ↔ ¬ b) ↔ (a ↔ b) := decidable.not_iff_not -- See Note [decidable namespace] protected theorem decidable.not_iff_comm [decidable a] [decidable b] : (¬ a ↔ b) ↔ (¬ b ↔ a) := by rw [@iff_def (¬ a), @iff_def (¬ b)]; exact decidable.not_imp_comm.and imp_not_comm theorem not_iff_comm : (¬ a ↔ b) ↔ (¬ b ↔ a) := decidable.not_iff_comm -- See Note [decidable namespace] protected theorem decidable.not_iff : ∀ [decidable b], ¬ (a ↔ b) ↔ (¬ a ↔ b) := by intro h; cases h; simp only [h, iff_true, iff_false] theorem not_iff : ¬ (a ↔ b) ↔ (¬ a ↔ b) := decidable.not_iff -- See Note [decidable namespace] protected theorem decidable.iff_not_comm [decidable a] [decidable b] : (a ↔ ¬ b) ↔ (b ↔ ¬ a) := by rw [@iff_def a, @iff_def b]; exact imp_not_comm.and decidable.not_imp_comm theorem iff_not_comm : (a ↔ ¬ b) ↔ (b ↔ ¬ a) := decidable.iff_not_comm -- See Note [decidable namespace] protected theorem decidable.iff_iff_and_or_not_and_not [decidable b] : (a ↔ b) ↔ (a ∧ b) ∨ (¬ a ∧ ¬ b) := by { split; intro h, { rw h; by_cases b; [left,right]; split; assumption }, { cases h with h h; cases h; split; intro; { contradiction <|> assumption } } } theorem iff_iff_and_or_not_and_not : (a ↔ b) ↔ (a ∧ b) ∨ (¬ a ∧ ¬ b) := decidable.iff_iff_and_or_not_and_not lemma decidable.iff_iff_not_or_and_or_not [decidable a] [decidable b] : (a ↔ b) ↔ ((¬a ∨ b) ∧ (a ∨ ¬b)) := begin rw [iff_iff_implies_and_implies a b], simp only [decidable.imp_iff_not_or, or.comm] end lemma iff_iff_not_or_and_or_not : (a ↔ b) ↔ ((¬a ∨ b) ∧ (a ∨ ¬b)) := decidable.iff_iff_not_or_and_or_not -- See Note [decidable namespace] protected theorem decidable.not_and_not_right [decidable b] : ¬(a ∧ ¬b) ↔ (a → b) := ⟨λ h ha, h.decidable_imp_symm $ and.intro ha, λ h ⟨ha, hb⟩, hb $ h ha⟩ theorem not_and_not_right : ¬(a ∧ ¬b) ↔ (a → b) := decidable.not_and_not_right /-- Transfer decidability of `a` to decidability of `b`, if the propositions are equivalent. **Important**: this function should be used instead of `rw` on `decidable b`, because the kernel will get stuck reducing the usage of `propext` otherwise, and `dec_trivial` will not work. -/ @[inline] def decidable_of_iff (a : Prop) (h : a ↔ b) [D : decidable a] : decidable b := decidable_of_decidable_of_iff D h /-- Transfer decidability of `b` to decidability of `a`, if the propositions are equivalent. This is the same as `decidable_of_iff` but the iff is flipped. -/ @[inline] def decidable_of_iff' (b : Prop) (h : a ↔ b) [D : decidable b] : decidable a := decidable_of_decidable_of_iff D h.symm /-- Prove that `a` is decidable by constructing a boolean `b` and a proof that `b ↔ a`. (This is sometimes taken as an alternate definition of decidability.) -/ def decidable_of_bool : ∀ (b : bool) (h : b ↔ a), decidable a | tt h := is_true (h.1 rfl) | ff h := is_false (mt h.2 bool.ff_ne_tt) /-! ### De Morgan's laws -/ theorem not_and_of_not_or_not (h : ¬ a ∨ ¬ b) : ¬ (a ∧ b) | ⟨ha, hb⟩ := or.elim h (absurd ha) (absurd hb) -- See Note [decidable namespace] protected theorem decidable.not_and_distrib [decidable a] : ¬ (a ∧ b) ↔ ¬a ∨ ¬b := ⟨λ h, if ha : a then or.inr (λ hb, h ⟨ha, hb⟩) else or.inl ha, not_and_of_not_or_not⟩ -- See Note [decidable namespace] protected theorem decidable.not_and_distrib' [decidable b] : ¬ (a ∧ b) ↔ ¬a ∨ ¬b := ⟨λ h, if hb : b then or.inl (λ ha, h ⟨ha, hb⟩) else or.inr hb, not_and_of_not_or_not⟩ /-- One of de Morgan's laws: the negation of a conjunction is logically equivalent to the disjunction of the negations. -/ theorem not_and_distrib : ¬ (a ∧ b) ↔ ¬a ∨ ¬b := decidable.not_and_distrib @[simp] theorem not_and : ¬ (a ∧ b) ↔ (a → ¬ b) := and_imp theorem not_and' : ¬ (a ∧ b) ↔ b → ¬a := not_and.trans imp_not_comm /-- One of de Morgan's laws: the negation of a disjunction is logically equivalent to the conjunction of the negations. -/ theorem not_or_distrib : ¬ (a ∨ b) ↔ ¬ a ∧ ¬ b := ⟨λ h, ⟨λ ha, h (or.inl ha), λ hb, h (or.inr hb)⟩, λ ⟨h₁, h₂⟩ h, or.elim h h₁ h₂⟩ -- See Note [decidable namespace] protected theorem decidable.or_iff_not_and_not [decidable a] [decidable b] : a ∨ b ↔ ¬ (¬a ∧ ¬b) := by rw [← not_or_distrib, decidable.not_not] theorem or_iff_not_and_not : a ∨ b ↔ ¬ (¬a ∧ ¬b) := decidable.or_iff_not_and_not -- See Note [decidable namespace] protected theorem decidable.and_iff_not_or_not [decidable a] [decidable b] : a ∧ b ↔ ¬ (¬ a ∨ ¬ b) := by rw [← decidable.not_and_distrib, decidable.not_not] theorem and_iff_not_or_not : a ∧ b ↔ ¬ (¬ a ∨ ¬ b) := decidable.and_iff_not_or_not @[simp] theorem not_xor (P Q : Prop) : ¬ xor P Q ↔ (P ↔ Q) := by simp only [not_and, xor, not_or_distrib, not_not, ← iff_iff_implies_and_implies] theorem xor_iff_not_iff (P Q : Prop) : xor P Q ↔ ¬ (P ↔ Q) := by rw [iff_not_comm, not_xor] end propositional /-! ### Declarations about equality -/ section mem variables {α β : Type*} [has_mem α β] {s t : β} {a b : α} lemma ne_of_mem_of_not_mem (h : a ∈ s) : b ∉ s → a ≠ b := mt $ λ e, e ▸ h lemma ne_of_mem_of_not_mem' (h : a ∈ s) : a ∉ t → s ≠ t := mt $ λ e, e ▸ h /-- **Alias** of `ne_of_mem_of_not_mem`. -/ lemma has_mem.mem.ne_of_not_mem : a ∈ s → b ∉ s → a ≠ b := ne_of_mem_of_not_mem /-- **Alias** of `ne_of_mem_of_not_mem'`. -/ lemma has_mem.mem.ne_of_not_mem' : a ∈ s → a ∉ t → s ≠ t := ne_of_mem_of_not_mem' end mem section equality variables {α : Sort*} {a b : α} @[simp] theorem heq_iff_eq : a == b ↔ a = b := ⟨eq_of_heq, heq_of_eq⟩ theorem proof_irrel_heq {p q : Prop} (hp : p) (hq : q) : hp == hq := have p = q, from propext ⟨λ _, hq, λ _, hp⟩, by subst q; refl -- todo: change name lemma ball_cond_comm {α} {s : α → Prop} {p : α → α → Prop} : (∀ a, s a → ∀ b, s b → p a b) ↔ (∀ a b, s a → s b → p a b) := ⟨λ h a b ha hb, h a ha b hb, λ h a ha b hb, h a b ha hb⟩ lemma ball_mem_comm {α β} [has_mem α β] {s : β} {p : α → α → Prop} : (∀ a b ∈ s, p a b) ↔ (∀ a b, a ∈ s → b ∈ s → p a b) := ball_cond_comm lemma ne_of_apply_ne {α β : Sort*} (f : α → β) {x y : α} (h : f x ≠ f y) : x ≠ y := λ (w : x = y), h (congr_arg f w) theorem eq_equivalence : equivalence (@eq α) := ⟨eq.refl, @eq.symm _, @eq.trans _⟩ /-- Transport through trivial families is the identity. -/ @[simp] lemma eq_rec_constant {α : Sort*} {a a' : α} {β : Sort*} (y : β) (h : a = a') : (@eq.rec α a (λ a, β) y a' h) = y := by { cases h, refl, } @[simp] lemma eq_mp_eq_cast {α β : Sort*} (h : α = β) : eq.mp h = cast h := rfl @[simp] lemma eq_mpr_eq_cast {α β : Sort*} (h : α = β) : eq.mpr h = cast h.symm := rfl @[simp] lemma cast_cast : ∀ {α β γ : Sort*} (ha : α = β) (hb : β = γ) (a : α), cast hb (cast ha a) = cast (ha.trans hb) a | _ _ _ rfl rfl a := rfl @[simp] lemma congr_refl_left {α β : Sort*} (f : α → β) {a b : α} (h : a = b) : congr (eq.refl f) h = congr_arg f h := rfl @[simp] lemma congr_refl_right {α β : Sort*} {f g : α → β} (h : f = g) (a : α) : congr h (eq.refl a) = congr_fun h a := rfl @[simp] lemma congr_arg_refl {α β : Sort*} (f : α → β) (a : α) : congr_arg f (eq.refl a) = eq.refl (f a) := rfl @[simp] lemma congr_fun_rfl {α β : Sort*} (f : α → β) (a : α) : congr_fun (eq.refl f) a = eq.refl (f a) := rfl @[simp] lemma congr_fun_congr_arg {α β γ : Sort*} (f : α → β → γ) {a a' : α} (p : a = a') (b : β) : congr_fun (congr_arg f p) b = congr_arg (λ a, f a b) p := rfl lemma heq_of_cast_eq : ∀ {α β : Sort*} {a : α} {a' : β} (e : α = β) (h₂ : cast e a = a'), a == a' | α ._ a a' rfl h := eq.rec_on h (heq.refl _) lemma cast_eq_iff_heq {α β : Sort*} {a : α} {a' : β} {e : α = β} : cast e a = a' ↔ a == a' := ⟨heq_of_cast_eq _, λ h, by cases h; refl⟩ lemma rec_heq_of_heq {β} {C : α → Sort*} {x : C a} {y : β} (eq : a = b) (h : x == y) : @eq.rec α a C x b eq == y := by subst eq; exact h protected lemma eq.congr {x₁ x₂ y₁ y₂ : α} (h₁ : x₁ = y₁) (h₂ : x₂ = y₂) : (x₁ = x₂) ↔ (y₁ = y₂) := by { subst h₁, subst h₂ } lemma eq.congr_left {x y z : α} (h : x = y) : x = z ↔ y = z := by rw [h] lemma eq.congr_right {x y z : α} (h : x = y) : z = x ↔ z = y := by rw [h] lemma congr_arg2 {α β γ : Sort*} (f : α → β → γ) {x x' : α} {y y' : β} (hx : x = x') (hy : y = y') : f x y = f x' y' := by { subst hx, subst hy } variables {β : α → Sort*} {γ : Π a, β a → Sort*} {δ : Π a b, γ a b → Sort*} lemma congr_fun₂ {f g : Π a b, γ a b} (h : f = g) (a : α) (b : β a) : f a b = g a b := congr_fun (congr_fun h _) _ lemma congr_fun₃ {f g : Π a b c, δ a b c} (h : f = g) (a : α) (b : β a) (c : γ a b) : f a b c = g a b c := congr_fun₂ (congr_fun h _) _ _ lemma funext₂ {f g : Π a b, γ a b} (h : ∀ a b, f a b = g a b) : f = g := funext $ λ _, funext $ h _ lemma funext₃ {f g : Π a b c, δ a b c} (h : ∀ a b c, f a b c = g a b c) : f = g := funext $ λ _, funext₂ $ h _ end equality /-! ### Declarations about quantifiers -/ section quantifiers variables {α : Sort*} section dependent variables {β : α → Sort*} {γ : Π a, β a → Sort*} {δ : Π a b, γ a b → Sort*} {ε : Π a b c, δ a b c → Sort*} lemma pi_congr {β' : α → Sort*} (h : ∀ a, β a = β' a) : (Π a, β a) = Π a, β' a := (funext h : β = β') ▸ rfl lemma forall₂_congr {p q : Π a, β a → Prop} (h : ∀ a b, p a b ↔ q a b) : (∀ a b, p a b) ↔ ∀ a b, q a b := forall_congr $ λ a, forall_congr $ h a lemma forall₃_congr {p q : Π a b, γ a b → Prop} (h : ∀ a b c, p a b c ↔ q a b c) : (∀ a b c, p a b c) ↔ ∀ a b c, q a b c := forall_congr $ λ a, forall₂_congr $ h a lemma forall₄_congr {p q : Π a b c, δ a b c → Prop} (h : ∀ a b c d, p a b c d ↔ q a b c d) : (∀ a b c d, p a b c d) ↔ ∀ a b c d, q a b c d := forall_congr $ λ a, forall₃_congr $ h a lemma forall₅_congr {p q : Π a b c d, ε a b c d → Prop} (h : ∀ a b c d e, p a b c d e ↔ q a b c d e) : (∀ a b c d e, p a b c d e) ↔ ∀ a b c d e, q a b c d e := forall_congr $ λ a, forall₄_congr $ h a lemma exists₂_congr {p q : Π a, β a → Prop} (h : ∀ a b, p a b ↔ q a b) : (∃ a b, p a b) ↔ ∃ a b, q a b := exists_congr $ λ a, exists_congr $ h a lemma exists₃_congr {p q : Π a b, γ a b → Prop} (h : ∀ a b c, p a b c ↔ q a b c) : (∃ a b c, p a b c) ↔ ∃ a b c, q a b c := exists_congr $ λ a, exists₂_congr $ h a lemma exists₄_congr {p q : Π a b c, δ a b c → Prop} (h : ∀ a b c d, p a b c d ↔ q a b c d) : (∃ a b c d, p a b c d) ↔ ∃ a b c d, q a b c d := exists_congr $ λ a, exists₃_congr $ h a lemma exists₅_congr {p q : Π a b c d, ε a b c d → Prop} (h : ∀ a b c d e, p a b c d e ↔ q a b c d e) : (∃ a b c d e, p a b c d e) ↔ ∃ a b c d e, q a b c d e := exists_congr $ λ a, exists₄_congr $ h a lemma forall_imp {p q : α → Prop} (h : ∀ a, p a → q a) : (∀ a, p a) → ∀ a, q a := λ h' a, h a (h' a) lemma forall₂_imp {p q : Π a, β a → Prop} (h : ∀ a b, p a b → q a b) : (∀ a b, p a b) → ∀ a b, q a b := forall_imp $ λ i, forall_imp $ h i lemma forall₃_imp {p q : Π a b, γ a b → Prop} (h : ∀ a b c, p a b c → q a b c) : (∀ a b c, p a b c) → ∀ a b c, q a b c := forall_imp $ λ a, forall₂_imp $ h a lemma Exists.imp {p q : α → Prop} (h : ∀ a, (p a → q a)) : (∃ a, p a) → ∃ a, q a := exists_imp_exists h lemma Exists₂.imp {p q : Π a, β a → Prop} (h : ∀ a b, p a b → q a b) : (∃ a b, p a b) → ∃ a b, q a b := Exists.imp $ λ a, Exists.imp $ h a lemma Exists₃.imp {p q : Π a b, γ a b → Prop} (h : ∀ a b c, p a b c → q a b c) : (∃ a b c, p a b c) → ∃ a b c, q a b c := Exists.imp $ λ a, Exists₂.imp $ h a end dependent variables {ι β : Sort*} {κ : ι → Sort*} {p q : α → Prop} {b : Prop} lemma exists_imp_exists' {p : α → Prop} {q : β → Prop} (f : α → β) (hpq : ∀ a, p a → q (f a)) (hp : ∃ a, p a) : ∃ b, q b := exists.elim hp (λ a hp', ⟨_, hpq _ hp'⟩) theorem forall_swap {p : α → β → Prop} : (∀ x y, p x y) ↔ ∀ y x, p x y := ⟨swap, swap⟩ lemma forall₂_swap {ι₁ ι₂ : Sort*} {κ₁ : ι₁ → Sort*} {κ₂ : ι₂ → Sort*} {p : Π i₁, κ₁ i₁ → Π i₂, κ₂ i₂ → Prop} : (∀ i₁ j₁ i₂ j₂, p i₁ j₁ i₂ j₂) ↔ ∀ i₂ j₂ i₁ j₁, p i₁ j₁ i₂ j₂ := ⟨swap₂, swap₂⟩ /-- We intentionally restrict the type of `α` in this lemma so that this is a safer to use in simp than `forall_swap`. -/ lemma imp_forall_iff {α : Type*} {p : Prop} {q : α → Prop} : (p → ∀ x, q x) ↔ (∀ x, p → q x) := forall_swap theorem exists_swap {p : α → β → Prop} : (∃ x y, p x y) ↔ ∃ y x, p x y := ⟨λ ⟨x, y, h⟩, ⟨y, x, h⟩, λ ⟨y, x, h⟩, ⟨x, y, h⟩⟩ @[simp] theorem forall_exists_index {q : (∃ x, p x) → Prop} : (∀ h, q h) ↔ ∀ x (h : p x), q ⟨x, h⟩ := ⟨λ h x hpx, h ⟨x, hpx⟩, λ h ⟨x, hpx⟩, h x hpx⟩ theorem exists_imp_distrib : ((∃ x, p x) → b) ↔ ∀ x, p x → b := forall_exists_index /-- Extract an element from a existential statement, using `classical.some`. -/ -- This enables projection notation. @[reducible] noncomputable def Exists.some {p : α → Prop} (P : ∃ a, p a) : α := classical.some P /-- Show that an element extracted from `P : ∃ a, p a` using `P.some` satisfies `p`. -/ lemma Exists.some_spec {p : α → Prop} (P : ∃ a, p a) : p (P.some) := classical.some_spec P --theorem forall_not_of_not_exists (h : ¬ ∃ x, p x) : ∀ x, ¬ p x := --forall_imp_of_exists_imp h theorem not_exists_of_forall_not (h : ∀ x, ¬ p x) : ¬ ∃ x, p x := exists_imp_distrib.2 h @[simp] theorem not_exists : (¬ ∃ x, p x) ↔ ∀ x, ¬ p x := exists_imp_distrib theorem not_forall_of_exists_not : (∃ x, ¬ p x) → ¬ ∀ x, p x | ⟨x, hn⟩ h := hn (h x) -- See Note [decidable namespace] protected theorem decidable.not_forall {p : α → Prop} [decidable (∃ x, ¬ p x)] [∀ x, decidable (p x)] : (¬ ∀ x, p x) ↔ ∃ x, ¬ p x := ⟨not.decidable_imp_symm $ λ nx x, nx.decidable_imp_symm $ λ h, ⟨x, h⟩, not_forall_of_exists_not⟩ @[simp] theorem not_forall {p : α → Prop} : (¬ ∀ x, p x) ↔ ∃ x, ¬ p x := decidable.not_forall -- See Note [decidable namespace] protected theorem decidable.not_forall_not [decidable (∃ x, p x)] : (¬ ∀ x, ¬ p x) ↔ ∃ x, p x := (@decidable.not_iff_comm _ _ _ (decidable_of_iff (¬ ∃ x, p x) not_exists)).1 not_exists theorem not_forall_not : (¬ ∀ x, ¬ p x) ↔ ∃ x, p x := decidable.not_forall_not -- See Note [decidable namespace] protected theorem decidable.not_exists_not [∀ x, decidable (p x)] : (¬ ∃ x, ¬ p x) ↔ ∀ x, p x := by simp [decidable.not_not] @[simp] theorem not_exists_not : (¬ ∃ x, ¬ p x) ↔ ∀ x, p x := decidable.not_exists_not theorem forall_imp_iff_exists_imp [ha : nonempty α] : ((∀ x, p x) → b) ↔ ∃ x, p x → b := let ⟨a⟩ := ha in ⟨λ h, not_forall_not.1 $ λ h', classical.by_cases (λ hb : b, h' a $ λ _, hb) (λ hb, hb $ h $ λ x, (not_imp.1 (h' x)).1), λ ⟨x, hx⟩ h, hx (h x)⟩ -- TODO: duplicate of a lemma in core theorem forall_true_iff : (α → true) ↔ true := implies_true_iff α -- Unfortunately this causes simp to loop sometimes, so we -- add the 2 and 3 cases as simp lemmas instead theorem forall_true_iff' (h : ∀ a, p a ↔ true) : (∀ a, p a) ↔ true := iff_true_intro (λ _, of_iff_true (h _)) @[simp] theorem forall_2_true_iff {β : α → Sort*} : (∀ a, β a → true) ↔ true := forall_true_iff' $ λ _, forall_true_iff @[simp] theorem forall_3_true_iff {β : α → Sort*} {γ : Π a, β a → Sort*} : (∀ a (b : β a), γ a b → true) ↔ true := forall_true_iff' $ λ _, forall_2_true_iff lemma exists_unique.exists {α : Sort*} {p : α → Prop} (h : ∃! x, p x) : ∃ x, p x := exists.elim h (λ x hx, ⟨x, and.left hx⟩) @[simp] lemma exists_unique_iff_exists {α : Sort*} [subsingleton α] {p : α → Prop} : (∃! x, p x) ↔ ∃ x, p x := ⟨λ h, h.exists, Exists.imp $ λ x hx, ⟨hx, λ y _, subsingleton.elim y x⟩⟩ @[simp] theorem forall_const (α : Sort*) [i : nonempty α] : (α → b) ↔ b := ⟨i.elim, λ hb x, hb⟩ /-- For some reason simp doesn't use `forall_const` to simplify in this case. -/ @[simp] lemma forall_forall_const {α β : Type*} (p : β → Prop) [nonempty α] : (∀ x, α → p x) ↔ ∀ x, p x := forall_congr $ λ x, forall_const α @[simp] theorem exists_const (α : Sort*) [i : nonempty α] : (∃ x : α, b) ↔ b := ⟨λ ⟨x, h⟩, h, i.elim exists.intro⟩ theorem exists_unique_const (α : Sort*) [i : nonempty α] [subsingleton α] : (∃! x : α, b) ↔ b := by simp theorem forall_and_distrib : (∀ x, p x ∧ q x) ↔ (∀ x, p x) ∧ (∀ x, q x) := ⟨λ h, ⟨λ x, (h x).left, λ x, (h x).right⟩, λ ⟨h₁, h₂⟩ x, ⟨h₁ x, h₂ x⟩⟩ theorem exists_or_distrib : (∃ x, p x ∨ q x) ↔ (∃ x, p x) ∨ (∃ x, q x) := ⟨λ ⟨x, hpq⟩, hpq.elim (λ hpx, or.inl ⟨x, hpx⟩) (λ hqx, or.inr ⟨x, hqx⟩), λ hepq, hepq.elim (λ ⟨x, hpx⟩, ⟨x, or.inl hpx⟩) (λ ⟨x, hqx⟩, ⟨x, or.inr hqx⟩)⟩ @[simp] theorem exists_and_distrib_left {q : Prop} {p : α → Prop} : (∃x, q ∧ p x) ↔ q ∧ (∃x, p x) := ⟨λ ⟨x, hq, hp⟩, ⟨hq, x, hp⟩, λ ⟨hq, x, hp⟩, ⟨x, hq, hp⟩⟩ @[simp] theorem exists_and_distrib_right {q : Prop} {p : α → Prop} : (∃x, p x ∧ q) ↔ (∃x, p x) ∧ q := by simp [and_comm] @[simp] theorem forall_eq {a' : α} : (∀a, a = a' → p a) ↔ p a' := ⟨λ h, h a' rfl, λ h a e, e.symm ▸ h⟩ @[simp] theorem forall_eq' {a' : α} : (∀a, a' = a → p a) ↔ p a' := by simp [@eq_comm _ a'] theorem and_forall_ne (a : α) : (p a ∧ ∀ b ≠ a, p b) ↔ ∀ b, p b := by simp only [← @forall_eq _ p a, ← forall_and_distrib, ← or_imp_distrib, classical.em, forall_const] -- this lemma is needed to simplify the output of `list.mem_cons_iff` @[simp] theorem forall_eq_or_imp {a' : α} : (∀ a, a = a' ∨ q a → p a) ↔ p a' ∧ ∀ a, q a → p a := by simp only [or_imp_distrib, forall_and_distrib, forall_eq] lemma ne.ne_or_ne {x y : α} (z : α) (h : x ≠ y) : x ≠ z ∨ y ≠ z := not_and_distrib.1 $ mt (and_imp.2 eq.substr) h.symm theorem exists_eq {a' : α} : ∃ a, a = a' := ⟨_, rfl⟩ @[simp] theorem exists_eq' {a' : α} : ∃ a, a' = a := ⟨_, rfl⟩ @[simp] theorem exists_unique_eq {a' : α} : ∃! a, a = a' := by simp only [eq_comm, exists_unique, and_self, forall_eq', exists_eq'] @[simp] theorem exists_unique_eq' {a' : α} : ∃! a, a' = a := by simp only [exists_unique, and_self, forall_eq', exists_eq'] @[simp] theorem exists_eq_left {a' : α} : (∃ a, a = a' ∧ p a) ↔ p a' := ⟨λ ⟨a, e, h⟩, e ▸ h, λ h, ⟨_, rfl, h⟩⟩ @[simp] theorem exists_eq_right {a' : α} : (∃ a, p a ∧ a = a') ↔ p a' := (exists_congr $ by exact λ a, and.comm).trans exists_eq_left @[simp] theorem exists_eq_right_right {a' : α} : (∃ (a : α), p a ∧ q a ∧ a = a') ↔ p a' ∧ q a' := ⟨λ ⟨_, hp, hq, rfl⟩, ⟨hp, hq⟩, λ ⟨hp, hq⟩, ⟨a', hp, hq, rfl⟩⟩ @[simp] theorem exists_eq_right_right' {a' : α} : (∃ (a : α), p a ∧ q a ∧ a' = a) ↔ p a' ∧ q a' := ⟨λ ⟨_, hp, hq, rfl⟩, ⟨hp, hq⟩, λ ⟨hp, hq⟩, ⟨a', hp, hq, rfl⟩⟩ @[simp] theorem exists_apply_eq_apply (f : α → β) (a' : α) : ∃ a, f a = f a' := ⟨a', rfl⟩ @[simp] theorem exists_apply_eq_apply' (f : α → β) (a' : α) : ∃ a, f a' = f a := ⟨a', rfl⟩ @[simp] theorem exists_exists_and_eq_and {f : α → β} {p : α → Prop} {q : β → Prop} : (∃ b, (∃ a, p a ∧ f a = b) ∧ q b) ↔ ∃ a, p a ∧ q (f a) := ⟨λ ⟨b, ⟨a, ha, hab⟩, hb⟩, ⟨a, ha, hab.symm ▸ hb⟩, λ ⟨a, hp, hq⟩, ⟨f a, ⟨a, hp, rfl⟩, hq⟩⟩ @[simp] theorem exists_exists_eq_and {f : α → β} {p : β → Prop} : (∃ b, (∃ a, f a = b) ∧ p b) ↔ ∃ a, p (f a) := ⟨λ ⟨b, ⟨a, ha⟩, hb⟩, ⟨a, ha.symm ▸ hb⟩, λ ⟨a, ha⟩, ⟨f a, ⟨a, rfl⟩, ha⟩⟩ @[simp] lemma exists_or_eq_left (y : α) (p : α → Prop) : ∃ (x : α), x = y ∨ p x := ⟨y, or.inl rfl⟩ @[simp] lemma exists_or_eq_right (y : α) (p : α → Prop) : ∃ (x : α), p x ∨ x = y := ⟨y, or.inr rfl⟩ @[simp] lemma exists_or_eq_left' (y : α) (p : α → Prop) : ∃ (x : α), y = x ∨ p x := ⟨y, or.inl rfl⟩ @[simp] lemma exists_or_eq_right' (y : α) (p : α → Prop) : ∃ (x : α), p x ∨ y = x := ⟨y, or.inr rfl⟩ @[simp] theorem forall_apply_eq_imp_iff {f : α → β} {p : β → Prop} : (∀ a, ∀ b, f a = b → p b) ↔ (∀ a, p (f a)) := ⟨λ h a, h a (f a) rfl, λ h a b hab, hab ▸ h a⟩ @[simp] theorem forall_apply_eq_imp_iff' {f : α → β} {p : β → Prop} : (∀ b, ∀ a, f a = b → p b) ↔ (∀ a, p (f a)) := by { rw forall_swap, simp } @[simp] theorem forall_eq_apply_imp_iff {f : α → β} {p : β → Prop} : (∀ a, ∀ b, b = f a → p b) ↔ (∀ a, p (f a)) := by simp [@eq_comm _ _ (f _)] @[simp] theorem forall_eq_apply_imp_iff' {f : α → β} {p : β → Prop} : (∀ b, ∀ a, b = f a → p b) ↔ (∀ a, p (f a)) := by { rw forall_swap, simp } @[simp] theorem forall_apply_eq_imp_iff₂ {f : α → β} {p : α → Prop} {q : β → Prop} : (∀ b, ∀ a, p a → f a = b → q b) ↔ ∀ a, p a → q (f a) := ⟨λ h a ha, h (f a) a ha rfl, λ h b a ha hb, hb ▸ h a ha⟩ @[simp] theorem exists_eq_left' {a' : α} : (∃ a, a' = a ∧ p a) ↔ p a' := by simp [@eq_comm _ a'] @[simp] theorem exists_eq_right' {a' : α} : (∃ a, p a ∧ a' = a) ↔ p a' := by simp [@eq_comm _ a'] theorem exists_comm {p : α → β → Prop} : (∃ a b, p a b) ↔ ∃ b a, p a b := ⟨λ ⟨a, b, h⟩, ⟨b, a, h⟩, λ ⟨b, a, h⟩, ⟨a, b, h⟩⟩ lemma exists₂_comm {ι₁ ι₂ : Sort*} {κ₁ : ι₁ → Sort*} {κ₂ : ι₂ → Sort*} {p : Π i₁, κ₁ i₁ → Π i₂, κ₂ i₂ → Prop} : (∃ i₁ j₁ i₂ j₂, p i₁ j₁ i₂ j₂) ↔ ∃ i₂ j₂ i₁ j₁, p i₁ j₁ i₂ j₂ := by simp only [@exists_comm (κ₁ _), @exists_comm ι₁] theorem and.exists {p q : Prop} {f : p ∧ q → Prop} : (∃ h, f h) ↔ ∃ hp hq, f ⟨hp, hq⟩ := ⟨λ ⟨h, H⟩, ⟨h.1, h.2, H⟩, λ ⟨hp, hq, H⟩, ⟨⟨hp, hq⟩, H⟩⟩ theorem forall_or_of_or_forall (h : b ∨ ∀x, p x) (x) : b ∨ p x := h.imp_right $ λ h₂, h₂ x -- See Note [decidable namespace] protected theorem decidable.forall_or_distrib_left {q : Prop} {p : α → Prop} [decidable q] : (∀x, q ∨ p x) ↔ q ∨ (∀x, p x) := ⟨λ h, if hq : q then or.inl hq else or.inr $ λ x, (h x).resolve_left hq, forall_or_of_or_forall⟩ theorem forall_or_distrib_left {q : Prop} {p : α → Prop} : (∀x, q ∨ p x) ↔ q ∨ (∀x, p x) := decidable.forall_or_distrib_left -- See Note [decidable namespace] protected theorem decidable.forall_or_distrib_right {q : Prop} {p : α → Prop} [decidable q] : (∀x, p x ∨ q) ↔ (∀x, p x) ∨ q := by simp [or_comm, decidable.forall_or_distrib_left] theorem forall_or_distrib_right {q : Prop} {p : α → Prop} : (∀x, p x ∨ q) ↔ (∀x, p x) ∨ q := decidable.forall_or_distrib_right @[simp] theorem exists_prop {p q : Prop} : (∃ h : p, q) ↔ p ∧ q := ⟨λ ⟨h₁, h₂⟩, ⟨h₁, h₂⟩, λ ⟨h₁, h₂⟩, ⟨h₁, h₂⟩⟩ theorem exists_unique_prop {p q : Prop} : (∃! h : p, q) ↔ p ∧ q := by simp @[simp] theorem exists_false : ¬ (∃a:α, false) := assume ⟨a, h⟩, h @[simp] lemma exists_unique_false : ¬ (∃! (a : α), false) := assume ⟨a, h, h'⟩, h theorem Exists.fst {p : b → Prop} : Exists p → b | ⟨h, _⟩ := h theorem Exists.snd {p : b → Prop} : ∀ h : Exists p, p h.fst | ⟨_, h⟩ := h theorem forall_prop_of_true {p : Prop} {q : p → Prop} (h : p) : (∀ h' : p, q h') ↔ q h := @forall_const (q h) p ⟨h⟩ theorem exists_prop_of_true {p : Prop} {q : p → Prop} (h : p) : (∃ h' : p, q h') ↔ q h := @exists_const (q h) p ⟨h⟩ lemma exists_iff_of_forall {p : Prop} {q : p → Prop} (h : ∀ h, q h) : (∃ h, q h) ↔ p := ⟨Exists.fst, λ H, ⟨H, h H⟩⟩ theorem exists_unique_prop_of_true {p : Prop} {q : p → Prop} (h : p) : (∃! h' : p, q h') ↔ q h := @exists_unique_const (q h) p ⟨h⟩ _ theorem forall_prop_of_false {p : Prop} {q : p → Prop} (hn : ¬ p) : (∀ h' : p, q h') ↔ true := iff_true_intro $ λ h, hn.elim h theorem exists_prop_of_false {p : Prop} {q : p → Prop} : ¬ p → ¬ (∃ h' : p, q h') := mt Exists.fst @[congr] lemma exists_prop_congr {p p' : Prop} {q q' : p → Prop} (hq : ∀ h, q h ↔ q' h) (hp : p ↔ p') : Exists q ↔ ∃ h : p', q' (hp.2 h) := ⟨λ ⟨_, _⟩, ⟨hp.1 ‹_›, (hq _).1 ‹_›⟩, λ ⟨_, _⟩, ⟨_, (hq _).2 ‹_›⟩⟩ @[congr] lemma exists_prop_congr' {p p' : Prop} {q q' : p → Prop} (hq : ∀ h, q h ↔ q' h) (hp : p ↔ p') : Exists q = ∃ h : p', q' (hp.2 h) := propext (exists_prop_congr hq _) /-- See `is_empty.exists_iff` for the `false` version. -/ @[simp] lemma exists_true_left (p : true → Prop) : (∃ x, p x) ↔ p true.intro := exists_prop_of_true _ lemma exists_unique.unique {α : Sort*} {p : α → Prop} (h : ∃! x, p x) {y₁ y₂ : α} (py₁ : p y₁) (py₂ : p y₂) : y₁ = y₂ := unique_of_exists_unique h py₁ py₂ @[congr] lemma forall_prop_congr {p p' : Prop} {q q' : p → Prop} (hq : ∀ h, q h ↔ q' h) (hp : p ↔ p') : (∀ h, q h) ↔ ∀ h : p', q' (hp.2 h) := ⟨λ h1 h2, (hq _).1 (h1 (hp.2 _)), λ h1 h2, (hq _).2 (h1 (hp.1 h2))⟩ @[congr] lemma forall_prop_congr' {p p' : Prop} {q q' : p → Prop} (hq : ∀ h, q h ↔ q' h) (hp : p ↔ p') : (∀ h, q h) = ∀ h : p', q' (hp.2 h) := propext (forall_prop_congr hq _) /-- See `is_empty.forall_iff` for the `false` version. -/ @[simp] lemma forall_true_left (p : true → Prop) : (∀ x, p x) ↔ p true.intro := forall_prop_of_true _ lemma exists_unique.elim2 {α : Sort*} {p : α → Sort*} [∀ x, subsingleton (p x)] {q : Π x (h : p x), Prop} {b : Prop} (h₂ : ∃! x (h : p x), q x h) (h₁ : ∀ x (h : p x), q x h → (∀ y (hy : p y), q y hy → y = x) → b) : b := begin simp only [exists_unique_iff_exists] at h₂, apply h₂.elim, exact λ x ⟨hxp, hxq⟩ H, h₁ x hxp hxq (λ y hyp hyq, H y ⟨hyp, hyq⟩) end lemma exists_unique.intro2 {α : Sort*} {p : α → Sort*} [∀ x, subsingleton (p x)] {q : Π (x : α) (h : p x), Prop} (w : α) (hp : p w) (hq : q w hp) (H : ∀ y (hy : p y), q y hy → y = w) : ∃! x (hx : p x), q x hx := begin simp only [exists_unique_iff_exists], exact exists_unique.intro w ⟨hp, hq⟩ (λ y ⟨hyp, hyq⟩, H y hyp hyq) end lemma exists_unique.exists2 {α : Sort*} {p : α → Sort*} {q : Π (x : α) (h : p x), Prop} (h : ∃! x (hx : p x), q x hx) : ∃ x (hx : p x), q x hx := h.exists.imp (λ x hx, hx.exists) lemma exists_unique.unique2 {α : Sort*} {p : α → Sort*} [∀ x, subsingleton (p x)] {q : Π (x : α) (hx : p x), Prop} (h : ∃! x (hx : p x), q x hx) {y₁ y₂ : α} (hpy₁ : p y₁) (hqy₁ : q y₁ hpy₁) (hpy₂ : p y₂) (hqy₂ : q y₂ hpy₂) : y₁ = y₂ := begin simp only [exists_unique_iff_exists] at h, exact h.unique ⟨hpy₁, hqy₁⟩ ⟨hpy₂, hqy₂⟩ end end quantifiers /-! ### Classical lemmas -/ namespace classical variables {α : Sort*} {p : α → Prop} theorem cases {p : Prop → Prop} (h1 : p true) (h2 : p false) : ∀a, p a := assume a, cases_on a h1 h2 /- use shortened names to avoid conflict when classical namespace is open. -/ /-- Any prop `p` is decidable classically. A shorthand for `classical.prop_decidable`. -/ noncomputable def dec (p : Prop) : decidable p := by apply_instance /-- Any predicate `p` is decidable classically. -/ noncomputable def dec_pred (p : α → Prop) : decidable_pred p := by apply_instance /-- Any relation `p` is decidable classically. -/ noncomputable def dec_rel (p : α → α → Prop) : decidable_rel p := by apply_instance /-- Any type `α` has decidable equality classically. -/ noncomputable def dec_eq (α : Sort*) : decidable_eq α := by apply_instance /-- Construct a function from a default value `H0`, and a function to use if there exists a value satisfying the predicate. -/ @[elab_as_eliminator] noncomputable def {u} exists_cases {C : Sort u} (H0 : C) (H : ∀ a, p a → C) : C := if h : ∃ a, p a then H (classical.some h) (classical.some_spec h) else H0 lemma some_spec2 {α : Sort*} {p : α → Prop} {h : ∃a, p a} (q : α → Prop) (hpq : ∀a, p a → q a) : q (some h) := hpq _ $ some_spec _ /-- A version of classical.indefinite_description which is definitionally equal to a pair -/ noncomputable def subtype_of_exists {α : Type*} {P : α → Prop} (h : ∃ x, P x) : {x // P x} := ⟨classical.some h, classical.some_spec h⟩ /-- A version of `by_contradiction` that uses types instead of propositions. -/ protected noncomputable def by_contradiction' {α : Sort*} (H : ¬ (α → false)) : α := classical.choice $ peirce _ false $ λ h, (H $ λ a, h ⟨a⟩).elim /-- `classical.by_contradiction'` is equivalent to lean's axiom `classical.choice`. -/ def choice_of_by_contradiction' {α : Sort*} (contra : ¬ (α → false) → α) : nonempty α → α := λ H, contra H.elim end classical /-- This function has the same type as `exists.rec_on`, and can be used to case on an equality, but `exists.rec_on` can only eliminate into Prop, while this version eliminates into any universe using the axiom of choice. -/ @[elab_as_eliminator] noncomputable def {u} exists.classical_rec_on {α} {p : α → Prop} (h : ∃ a, p a) {C : Sort u} (H : ∀ a, p a → C) : C := H (classical.some h) (classical.some_spec h) /-! ### Declarations about bounded quantifiers -/ section bounded_quantifiers variables {α : Sort*} {r p q : α → Prop} {P Q : ∀ x, p x → Prop} {b : Prop} theorem bex_def : (∃ x (h : p x), q x) ↔ ∃ x, p x ∧ q x := ⟨λ ⟨x, px, qx⟩, ⟨x, px, qx⟩, λ ⟨x, px, qx⟩, ⟨x, px, qx⟩⟩ theorem bex.elim {b : Prop} : (∃ x h, P x h) → (∀ a h, P a h → b) → b | ⟨a, h₁, h₂⟩ h' := h' a h₁ h₂ theorem bex.intro (a : α) (h₁ : p a) (h₂ : P a h₁) : ∃ x (h : p x), P x h := ⟨a, h₁, h₂⟩ theorem ball_congr (H : ∀ x h, P x h ↔ Q x h) : (∀ x h, P x h) ↔ (∀ x h, Q x h) := forall_congr $ λ x, forall_congr (H x) theorem bex_congr (H : ∀ x h, P x h ↔ Q x h) : (∃ x h, P x h) ↔ (∃ x h, Q x h) := exists_congr $ λ x, exists_congr (H x) theorem bex_eq_left {a : α} : (∃ x (_ : x = a), p x) ↔ p a := by simp only [exists_prop, exists_eq_left] theorem ball.imp_right (H : ∀ x h, (P x h → Q x h)) (h₁ : ∀ x h, P x h) (x h) : Q x h := H _ _ $ h₁ _ _ theorem bex.imp_right (H : ∀ x h, (P x h → Q x h)) : (∃ x h, P x h) → ∃ x h, Q x h | ⟨x, h, h'⟩ := ⟨_, _, H _ _ h'⟩ theorem ball.imp_left (H : ∀ x, p x → q x) (h₁ : ∀ x, q x → r x) (x) (h : p x) : r x := h₁ _ $ H _ h theorem bex.imp_left (H : ∀ x, p x → q x) : (∃ x (_ : p x), r x) → ∃ x (_ : q x), r x | ⟨x, hp, hr⟩ := ⟨x, H _ hp, hr⟩ theorem ball_of_forall (h : ∀ x, p x) (x) : p x := h x theorem forall_of_ball (H : ∀ x, p x) (h : ∀ x, p x → q x) (x) : q x := h x $ H x theorem bex_of_exists (H : ∀ x, p x) : (∃ x, q x) → ∃ x (_ : p x), q x | ⟨x, hq⟩ := ⟨x, H x, hq⟩ theorem exists_of_bex : (∃ x (_ : p x), q x) → ∃ x, q x | ⟨x, _, hq⟩ := ⟨x, hq⟩ @[simp] theorem bex_imp_distrib : ((∃ x h, P x h) → b) ↔ (∀ x h, P x h → b) := by simp theorem not_bex : (¬ ∃ x h, P x h) ↔ ∀ x h, ¬ P x h := bex_imp_distrib theorem not_ball_of_bex_not : (∃ x h, ¬ P x h) → ¬ ∀ x h, P x h | ⟨x, h, hp⟩ al := hp $ al x h -- See Note [decidable namespace] protected theorem decidable.not_ball [decidable (∃ x h, ¬ P x h)] [∀ x h, decidable (P x h)] : (¬ ∀ x h, P x h) ↔ (∃ x h, ¬ P x h) := ⟨not.decidable_imp_symm $ λ nx x h, nx.decidable_imp_symm $ λ h', ⟨x, h, h'⟩, not_ball_of_bex_not⟩ theorem not_ball : (¬ ∀ x h, P x h) ↔ (∃ x h, ¬ P x h) := decidable.not_ball theorem ball_true_iff (p : α → Prop) : (∀ x, p x → true) ↔ true := iff_true_intro (λ h hrx, trivial) theorem ball_and_distrib : (∀ x h, P x h ∧ Q x h) ↔ (∀ x h, P x h) ∧ (∀ x h, Q x h) := iff.trans (forall_congr $ λ x, forall_and_distrib) forall_and_distrib theorem bex_or_distrib : (∃ x h, P x h ∨ Q x h) ↔ (∃ x h, P x h) ∨ (∃ x h, Q x h) := iff.trans (exists_congr $ λ x, exists_or_distrib) exists_or_distrib theorem ball_or_left_distrib : (∀ x, p x ∨ q x → r x) ↔ (∀ x, p x → r x) ∧ (∀ x, q x → r x) := iff.trans (forall_congr $ λ x, or_imp_distrib) forall_and_distrib theorem bex_or_left_distrib : (∃ x (_ : p x ∨ q x), r x) ↔ (∃ x (_ : p x), r x) ∨ (∃ x (_ : q x), r x) := by simp only [exists_prop]; exact iff.trans (exists_congr $ λ x, or_and_distrib_right) exists_or_distrib end bounded_quantifiers namespace classical local attribute [instance] prop_decidable theorem not_ball {α : Sort*} {p : α → Prop} {P : Π (x : α), p x → Prop} : (¬ ∀ x h, P x h) ↔ (∃ x h, ¬ P x h) := _root_.not_ball end classical section ite variables {α β γ : Sort*} {σ : α → Sort*} (f : α → β) {P Q : Prop} [decidable P] [decidable Q] {a b c : α} {A : P → α} {B : ¬ P → α} lemma dite_eq_iff : dite P A B = c ↔ (∃ h, A h = c) ∨ ∃ h, B h = c := by by_cases P; simp [*, exists_prop_of_false not_false] lemma ite_eq_iff : ite P a b = c ↔ P ∧ a = c ∨ ¬ P ∧ b = c := dite_eq_iff.trans $ by rw [exists_prop, exists_prop] @[simp] lemma dite_eq_left_iff : dite P (λ _, a) B = a ↔ ∀ h, B h = a := by by_cases P; simp [*, forall_prop_of_false not_false] @[simp] lemma dite_eq_right_iff : dite P A (λ _, b) = b ↔ ∀ h, A h = b := by by_cases P; simp [*, forall_prop_of_false not_false] @[simp] lemma ite_eq_left_iff : ite P a b = a ↔ (¬ P → b = a) := dite_eq_left_iff @[simp] lemma ite_eq_right_iff : ite P a b = b ↔ (P → a = b) := dite_eq_right_iff lemma dite_ne_left_iff : dite P (λ _, a) B ≠ a ↔ ∃ h, a ≠ B h := by { rw [ne.def, dite_eq_left_iff, not_forall], exact exists_congr (λ h, by rw ne_comm) } lemma dite_ne_right_iff : dite P A (λ _, b) ≠ b ↔ ∃ h, A h ≠ b := by simp only [ne.def, dite_eq_right_iff, not_forall] lemma ite_ne_left_iff : ite P a b ≠ a ↔ ¬ P ∧ a ≠ b := dite_ne_left_iff.trans $ by rw exists_prop lemma ite_ne_right_iff : ite P a b ≠ b ↔ P ∧ a ≠ b := dite_ne_right_iff.trans $ by rw exists_prop protected lemma ne.dite_eq_left_iff (h : ∀ h, a ≠ B h) : dite P (λ _, a) B = a ↔ P := dite_eq_left_iff.trans $ ⟨λ H, of_not_not $ λ h', h h' (H h').symm, λ h H, (H h).elim⟩ protected lemma ne.dite_eq_right_iff (h : ∀ h, A h ≠ b) : dite P A (λ _, b) = b ↔ ¬ P := dite_eq_right_iff.trans $ ⟨λ H h', h h' (H h'), λ h' H, (h' H).elim⟩ protected lemma ne.ite_eq_left_iff (h : a ≠ b) : ite P a b = a ↔ P := ne.dite_eq_left_iff $ λ _, h protected lemma ne.ite_eq_right_iff (h : a ≠ b) : ite P a b = b ↔ ¬ P := ne.dite_eq_right_iff $ λ _, h protected lemma ne.dite_ne_left_iff (h : ∀ h, a ≠ B h) : dite P (λ _, a) B ≠ a ↔ ¬ P := dite_ne_left_iff.trans $ exists_iff_of_forall h protected lemma ne.dite_ne_right_iff (h : ∀ h, A h ≠ b) : dite P A (λ _, b) ≠ b ↔ P := dite_ne_right_iff.trans $ exists_iff_of_forall h protected lemma ne.ite_ne_left_iff (h : a ≠ b) : ite P a b ≠ a ↔ ¬ P := ne.dite_ne_left_iff $ λ _, h protected lemma ne.ite_ne_right_iff (h : a ≠ b) : ite P a b ≠ b ↔ P := ne.dite_ne_right_iff $ λ _, h variables (P Q) (a b) /-- A `dite` whose results do not actually depend on the condition may be reduced to an `ite`. -/ @[simp] lemma dite_eq_ite : dite P (λ h, a) (λ h, b) = ite P a b := rfl lemma dite_eq_or_eq : (∃ h, dite P A B = A h) ∨ ∃ h, dite P A B = B h := decidable.by_cases (λ h, or.inl ⟨h, dif_pos h⟩) (λ h, or.inr ⟨h, dif_neg h⟩) lemma ite_eq_or_eq : ite P a b = a ∨ ite P a b = b := decidable.by_cases (λ h, or.inl (if_pos h)) (λ h, or.inr (if_neg h)) /-- A function applied to a `dite` is a `dite` of that function applied to each of the branches. -/ lemma apply_dite (x : P → α) (y : ¬P → α) : f (dite P x y) = dite P (λ h, f (x h)) (λ h, f (y h)) := by by_cases h : P; simp [h] /-- A function applied to a `ite` is a `ite` of that function applied to each of the branches. -/ lemma apply_ite : f (ite P a b) = ite P (f a) (f b) := apply_dite f P (λ _, a) (λ _, b) /-- A two-argument function applied to two `dite`s is a `dite` of that two-argument function applied to each of the branches. -/ lemma apply_dite2 (f : α → β → γ) (P : Prop) [decidable P] (a : P → α) (b : ¬P → α) (c : P → β) (d : ¬P → β) : f (dite P a b) (dite P c d) = dite P (λ h, f (a h) (c h)) (λ h, f (b h) (d h)) := by by_cases h : P; simp [h] /-- A two-argument function applied to two `ite`s is a `ite` of that two-argument function applied to each of the branches. -/ lemma apply_ite2 (f : α → β → γ) (P : Prop) [decidable P] (a b : α) (c d : β) : f (ite P a b) (ite P c d) = ite P (f a c) (f b d) := apply_dite2 f P (λ _, a) (λ _, b) (λ _, c) (λ _, d) /-- A 'dite' producing a `Pi` type `Π a, σ a`, applied to a value `a : α` is a `dite` that applies either branch to `a`. -/ lemma dite_apply (f : P → Π a, σ a) (g : ¬ P → Π a, σ a) (a : α) : (dite P f g) a = dite P (λ h, f h a) (λ h, g h a) := by by_cases h : P; simp [h] /-- A 'ite' producing a `Pi` type `Π a, σ a`, applied to a value `a : α` is a `ite` that applies either branch to `a`. -/ lemma ite_apply (f g : Π a, σ a) (a : α) : (ite P f g) a = ite P (f a) (g a) := dite_apply P (λ _, f) (λ _, g) a /-- Negation of the condition `P : Prop` in a `dite` is the same as swapping the branches. -/ @[simp] lemma dite_not (x : ¬ P → α) (y : ¬¬ P → α) : dite (¬ P) x y = dite P (λ h, y (not_not_intro h)) x := by by_cases h : P; simp [h] /-- Negation of the condition `P : Prop` in a `ite` is the same as swapping the branches. -/ @[simp] lemma ite_not : ite (¬ P) a b = ite P b a := dite_not P (λ _, a) (λ _, b) lemma ite_and : ite (P ∧ Q) a b = ite P (ite Q a b) b := by by_cases hp : P; by_cases hq : Q; simp [hp, hq] end ite
4fc903fdcbacf6553adfcb883b7ba44e5827763e
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/probability/martingale/convergence.lean
340f3fba23564d4f8434d78cdc70a3bbd6a50ad3
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
25,579
lean
/- Copyright (c) 2022 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import probability.martingale.upcrossing import measure_theory.function.uniform_integrable import measure_theory.constructions.polish /-! # Martingale convergence theorems > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The martingale convergence theorems are a collection of theorems characterizing the convergence of a martingale provided it satisfies some boundedness conditions. This file contains the almost everywhere martingale convergence theorem which provides an almost everywhere limit to an L¹ bounded submartingale. It also contains the L¹ martingale convergence theorem which provides an L¹ limit to a uniformly integrable submartingale. Finally, it also contains the Lévy upwards theorems. ## Main results * `measure_theory.submartingale.ae_tendsto_limit_process`: the almost everywhere martingale convergence theorem: an L¹-bounded submartingale adapted to the filtration `ℱ` converges almost everywhere to its limit process. * `measure_theory.submartingale.mem_ℒp_limit_process`: the limit process of an Lᵖ-bounded submartingale is Lᵖ. * `measure_theory.submartingale.tendsto_snorm_one_limit_process`: part a of the L¹ martingale convergence theorem: a uniformly integrable submartingale adapted to the filtration `ℱ` converges almost everywhere and in L¹ to an integrable function which is measurable with respect to the σ-algebra `⨆ n, ℱ n`. * `measure_theory.martingale.ae_eq_condexp_limit_process`: part b the L¹ martingale convergence theorem: if `f` is a uniformly integrable martingale adapted to the filtration `ℱ`, then `f n` equals `𝔼[g | ℱ n]` almost everywhere where `g` is the limiting process of `f`. * `measure_theory.integrable.tendsto_ae_condexp`: part c the L¹ martingale convergence theorem: given a `⨆ n, ℱ n`-measurable function `g` where `ℱ` is a filtration, `𝔼[g | ℱ n]` converges almost everywhere to `g`. * `measure_theory.integrable.tendsto_snorm_condexp`: part c the L¹ martingale convergence theorem: given a `⨆ n, ℱ n`-measurable function `g` where `ℱ` is a filtration, `𝔼[g | ℱ n]` converges in L¹ to `g`. -/ open topological_space filter measure_theory.filtration open_locale nnreal ennreal measure_theory probability_theory big_operators topology namespace measure_theory variables {Ω ι : Type*} {m0 : measurable_space Ω} {μ : measure Ω} {ℱ : filtration ℕ m0} variables {a b : ℝ} {f : ℕ → Ω → ℝ} {ω : Ω} {R : ℝ≥0} section ae_convergence /-! ### Almost everywhere martingale convergence theorem We will now prove the almost everywhere martingale convergence theorem. The a.e. martingale convergence theorem states: if `f` is an L¹-bounded `ℱ`-submartingale, then it converges almost everywhere to an integrable function which is measurable with respect to the σ-algebra `ℱ∞ := ⨆ n, ℱ n`. Mathematically, we proceed by first noting that a real sequence $(x_n)$ converges if (a) $\limsup_{n \to \infty} |x_n| < \infty$, (b) for all $a < b \in \mathbb{Q}$ we have the number of upcrossings of $(x_n)$ from below $a$ to above $b$ is finite. Thus, for all $\omega$ satisfying $\limsup_{n \to \infty} |f_n(\omega)| < \infty$ and the number of upcrossings of $(f_n(\omega))$ from below $a$ to above $b$ is finite for all $a < b \in \mathbb{Q}$, we have $(f_n(\omega))$ is convergent. Hence, assuming $(f_n)$ is L¹-bounded, using Fatou's lemma, we have $$ \mathbb{E} \limsup_{n \to \infty} |f_n| \le \limsup_{n \to \infty} \mathbb{E}|f_n| < \infty $$ implying $\limsup_{n \to \infty} |f_n| < \infty$ a.e. Furthermore, by the upcrossing estimate, the number of upcrossings is finite almost everywhere implying $f$ converges pointwise almost everywhere. Thus, denoting $g$ the a.e. limit of $(f_n)$, $g$ is $\mathcal{F}_\infty$-measurable as for all $n$, $f_n$ is $\mathcal{F}_n$-measurable and $\mathcal{F}_n \le \mathcal{F}_\infty$. Finally, $g$ is integrable as $|g| \le \liminf_{n \to \infty} |f_n|$ so $$ \mathbb{E}|g| \le \mathbb{E} \limsup_{n \to \infty} |f_n| \le \limsup_{n \to \infty} \mathbb{E}|f_n| < \infty $$ as required. Implementation wise, we have `tendsto_of_no_upcrossings` which showed that a bounded sequence converges if it does not visit below $a$ and above $b$ infinitely often for all $a, b ∈ s$ for some dense set $s$. So, we may skip the first step provided we can prove that the realizations are bounded almost everywhere. Indeed, suppose $(|f_n(\omega)|)$ is not bounded, then either $f_n(\omega) \to \pm \infty$ or one of $\limsup f_n(\omega)$ or $\liminf f_n(\omega)$ equals $\pm \infty$ while the other is finite. But the first case contradicts $\liminf |f_n(\omega)| < \infty$ while the second case contradicts finite upcrossings. Furthermore, we introduced `filtration.limit_process` which chooses the limiting random variable of a stochastic process if it exists, otherwise it returns 0. Hence, instead of showing an existence statement, we phrased the a.e. martingale convergence theorem by showed that a submartingale converges to its `limit_process` almost everywhere. -/ /-- If a stochastic process has bounded upcrossing from below `a` to above `b`, then it does not frequently visit both below `a` and above `b`. -/ lemma not_frequently_of_upcrossings_lt_top (hab : a < b) (hω : upcrossings a b f ω ≠ ∞) : ¬((∃ᶠ n in at_top, f n ω < a) ∧ (∃ᶠ n in at_top, b < f n ω)) := begin rw [← lt_top_iff_ne_top, upcrossings_lt_top_iff] at hω, replace hω : ∃ k, ∀ N, upcrossings_before a b f N ω < k, { obtain ⟨k, hk⟩ := hω, exact ⟨k + 1, λ N, lt_of_le_of_lt (hk N) k.lt_succ_self⟩ }, rintro ⟨h₁, h₂⟩, rw frequently_at_top at h₁ h₂, refine not_not.2 hω _, push_neg, intro k, induction k with k ih, { simp only [zero_le', exists_const] }, { obtain ⟨N, hN⟩ := ih, obtain ⟨N₁, hN₁, hN₁'⟩ := h₁ N, obtain ⟨N₂, hN₂, hN₂'⟩ := h₂ N₁, exact ⟨(N₂ + 1), nat.succ_le_of_lt $ lt_of_le_of_lt hN (upcrossings_before_lt_of_exists_upcrossing hab hN₁ hN₁' hN₂ hN₂')⟩ } end /-- A stochastic process that frequently visits below `a` and above `b` have infinite upcrossings. -/ lemma upcrossings_eq_top_of_frequently_lt (hab : a < b) (h₁ : ∃ᶠ n in at_top, f n ω < a) (h₂ : ∃ᶠ n in at_top, b < f n ω) : upcrossings a b f ω = ∞ := classical.by_contradiction (λ h, not_frequently_of_upcrossings_lt_top hab h ⟨h₁, h₂⟩) /-- A realization of a stochastic process with bounded upcrossings and bounded liminfs is convergent. We use the spelling `< ∞` instead of the standard `≠ ∞` in the assumptions since it is not as easy to change `<` to `≠` under binders. -/ lemma tendsto_of_uncrossing_lt_top (hf₁ : liminf (λ n, (‖f n ω‖₊ : ℝ≥0∞)) at_top < ∞) (hf₂ : ∀ a b : ℚ, a < b → upcrossings a b f ω < ∞) : ∃ c, tendsto (λ n, f n ω) at_top (𝓝 c) := begin by_cases h : is_bounded_under (≤) at_top (λ n, |f n ω|), { rw is_bounded_under_le_abs at h, refine tendsto_of_no_upcrossings rat.dense_range_cast _ h.1 h.2, { intros a ha b hb hab, obtain ⟨⟨a, rfl⟩, ⟨b, rfl⟩⟩ := ⟨ha, hb⟩, exact not_frequently_of_upcrossings_lt_top hab (hf₂ a b (rat.cast_lt.1 hab)).ne } }, { obtain ⟨a, b, hab, h₁, h₂⟩ := ennreal.exists_upcrossings_of_not_bounded_under hf₁.ne h, exact false.elim ((hf₂ a b hab).ne (upcrossings_eq_top_of_frequently_lt (rat.cast_lt.2 hab) h₁ h₂)) } end /-- An L¹-bounded submartingale has bounded upcrossings almost everywhere. -/ lemma submartingale.upcrossings_ae_lt_top' [is_finite_measure μ] (hf : submartingale f ℱ μ) (hbdd : ∀ n, snorm (f n) 1 μ ≤ R) (hab : a < b) : ∀ᵐ ω ∂μ, upcrossings a b f ω < ∞ := begin refine ae_lt_top (hf.adapted.measurable_upcrossings hab) _, have := hf.mul_lintegral_upcrossings_le_lintegral_pos_part a b, rw [mul_comm, ← ennreal.le_div_iff_mul_le] at this, { refine (lt_of_le_of_lt this (ennreal.div_lt_top _ _)).ne, { have hR' : ∀ n, ∫⁻ ω, ‖f n ω - a‖₊ ∂μ ≤ R + ‖a‖₊ * μ set.univ, { simp_rw snorm_one_eq_lintegral_nnnorm at hbdd, intro n, refine (lintegral_mono _ : ∫⁻ ω, ‖f n ω - a‖₊ ∂μ ≤ ∫⁻ ω, ‖f n ω‖₊ + ‖a‖₊ ∂μ).trans _, { intro ω, simp_rw [sub_eq_add_neg, ← nnnorm_neg a, ← ennreal.coe_add, ennreal.coe_le_coe], exact nnnorm_add_le _ _ }, { simp_rw [ lintegral_add_right _ measurable_const, lintegral_const], exact add_le_add (hbdd _) le_rfl } }, refine ne_of_lt (supr_lt_iff.2 ⟨R + ‖a‖₊ * μ set.univ, ennreal.add_lt_top.2 ⟨ennreal.coe_lt_top, ennreal.mul_lt_top ennreal.coe_lt_top.ne (measure_ne_top _ _)⟩, λ n, le_trans _ (hR' n)⟩), refine lintegral_mono (λ ω, _), rw [ennreal.of_real_le_iff_le_to_real, ennreal.coe_to_real, coe_nnnorm], by_cases hnonneg : 0 ≤ f n ω - a, { rw [lattice_ordered_comm_group.pos_of_nonneg _ hnonneg, real.norm_eq_abs, abs_of_nonneg hnonneg] }, { rw lattice_ordered_comm_group.pos_of_nonpos _ (not_le.1 hnonneg).le, exact norm_nonneg _ }, { simp only [ne.def, ennreal.coe_ne_top, not_false_iff] } }, { simp only [hab, ne.def, ennreal.of_real_eq_zero, sub_nonpos, not_le] } }, { simp only [hab, ne.def, ennreal.of_real_eq_zero, sub_nonpos, not_le, true_or]}, { simp only [ne.def, ennreal.of_real_ne_top, not_false_iff, true_or] } end lemma submartingale.upcrossings_ae_lt_top [is_finite_measure μ] (hf : submartingale f ℱ μ) (hbdd : ∀ n, snorm (f n) 1 μ ≤ R) : ∀ᵐ ω ∂μ, ∀ a b : ℚ, a < b → upcrossings a b f ω < ∞ := begin simp only [ae_all_iff, eventually_imp_distrib_left], rintro a b hab, exact hf.upcrossings_ae_lt_top' hbdd (rat.cast_lt.2 hab), end /-- An L¹-bounded submartingale converges almost everywhere. -/ lemma submartingale.exists_ae_tendsto_of_bdd [is_finite_measure μ] (hf : submartingale f ℱ μ) (hbdd : ∀ n, snorm (f n) 1 μ ≤ R) : ∀ᵐ ω ∂μ, ∃ c, tendsto (λ n, f n ω) at_top (𝓝 c) := begin filter_upwards [hf.upcrossings_ae_lt_top hbdd, ae_bdd_liminf_at_top_of_snorm_bdd one_ne_zero (λ n, (hf.strongly_measurable n).measurable.mono (ℱ.le n) le_rfl) hbdd] with ω h₁ h₂, exact tendsto_of_uncrossing_lt_top h₂ h₁, end lemma submartingale.exists_ae_trim_tendsto_of_bdd [is_finite_measure μ] (hf : submartingale f ℱ μ) (hbdd : ∀ n, snorm (f n) 1 μ ≤ R) : ∀ᵐ ω ∂(μ.trim (Sup_le (λ m ⟨n, hn⟩, hn ▸ ℱ.le _) : (⨆ n, ℱ n) ≤ m0)), ∃ c, tendsto (λ n, f n ω) at_top (𝓝 c) := begin rw [ae_iff, trim_measurable_set_eq], { exact hf.exists_ae_tendsto_of_bdd hbdd }, { exact measurable_set.compl (@measurable_set_exists_tendsto _ _ _ _ _ _ (⨆ n, ℱ n) _ _ _ _ _ (λ n, ((hf.strongly_measurable n).measurable.mono (le_Sup ⟨n, rfl⟩) le_rfl))) } end /-- **Almost everywhere martingale convergence theorem**: An L¹-bounded submartingale converges almost everywhere to a `⨆ n, ℱ n`-measurable function. -/ lemma submartingale.ae_tendsto_limit_process [is_finite_measure μ] (hf : submartingale f ℱ μ) (hbdd : ∀ n, snorm (f n) 1 μ ≤ R) : ∀ᵐ ω ∂μ, tendsto (λ n, f n ω) at_top (𝓝 (ℱ.limit_process f μ ω)) := begin classical, suffices : ∃ g, strongly_measurable[⨆ n, ℱ n] g ∧ ∀ᵐ ω ∂μ, tendsto (λ n, f n ω) at_top (𝓝 (g ω)), { rw [limit_process, dif_pos this], exact (classical.some_spec this).2 }, set g' : Ω → ℝ := λ ω, if h : ∃ c, tendsto (λ n, f n ω) at_top (𝓝 c) then h.some else 0, have hle : (⨆ n, ℱ n) ≤ m0 := Sup_le (λ m ⟨n, hn⟩, hn ▸ ℱ.le _), have hg' : ∀ᵐ ω ∂(μ.trim hle), tendsto (λ n, f n ω) at_top (𝓝 (g' ω)), { filter_upwards [hf.exists_ae_trim_tendsto_of_bdd hbdd] with ω hω, simp_rw [g', dif_pos hω], exact hω.some_spec }, have hg'm : @ae_strongly_measurable _ _ _ (⨆ n, ℱ n) g' (μ.trim hle) := (@ae_measurable_of_tendsto_metrizable_ae' _ _ (⨆ n, ℱ n) _ _ _ _ _ _ _ (λ n, ((hf.strongly_measurable n).measurable.mono (le_Sup ⟨n, rfl⟩ : ℱ n ≤ ⨆ n, ℱ n) le_rfl).ae_measurable) hg').ae_strongly_measurable, obtain ⟨g, hgm, hae⟩ := hg'm, have hg : ∀ᵐ ω ∂μ.trim hle, tendsto (λ n, f n ω) at_top (𝓝 (g ω)), { filter_upwards [hae, hg'] with ω hω hg'ω, exact hω ▸ hg'ω }, exact ⟨g, hgm, measure_eq_zero_of_trim_eq_zero hle hg⟩, end /-- The limiting process of an Lᵖ-bounded submartingale is Lᵖ. -/ lemma submartingale.mem_ℒp_limit_process {p : ℝ≥0∞} (hf : submartingale f ℱ μ) (hbdd : ∀ n, snorm (f n) p μ ≤ R) : mem_ℒp (ℱ.limit_process f μ) p μ := mem_ℒp_limit_process_of_snorm_bdd (λ n, ((hf.strongly_measurable n).mono (ℱ.le n)).ae_strongly_measurable) hbdd end ae_convergence section L1_convergence variables [is_finite_measure μ] {g : Ω → ℝ} /-! ### L¹ martingale convergence theorem We will now prove the L¹ martingale convergence theorems. The L¹ martingale convergence theorem states that: (a) if `f` is a uniformly integrable (in the probability sense) submartingale adapted to the filtration `ℱ`, it converges in L¹ to an integrable function `g` which is measurable with respect to `ℱ∞ := ⨆ n, ℱ n` and (b) if `f` is actually a martingale, `f n = 𝔼[g | ℱ n]` almost everywhere. (c) Finally, if `h` is integrable and measurable with respect to `ℱ∞`, `(𝔼[h | ℱ n])ₙ` is a uniformly integrable martingale which converges to `h` almost everywhere and in L¹. The proof is quite simple. (a) follows directly from the a.e. martingale convergence theorem and the Vitali convergence theorem as our definition of uniform integrability (in the probability sense) directly implies L¹-uniform boundedness. We note that our definition of uniform integrability is slightly non-standard but is equivalent to the usual literary definition. This equivalence is provided by `measure_theory.uniform_integrable_iff`. (b) follows since given $n$, we have for all $m \ge n$, $$ \|f_n - \mathbb{E}[g \mid \mathcal{F}_n]\|_1 = \|\mathbb{E}[f_m - g \mid \mathcal{F}_n]\|_1 \le \|\|f_m - g\|_1. $$ Thus, taking $m \to \infty$ provides the almost everywhere equality. Finally, to prove (c), we define $f_n := \mathbb{E}[h \mid \mathcal{F}_n]$. It is clear that $(f_n)_n$ is a martingale by the tower property for conditional expectations. Furthermore, $(f_n)_n$ is uniformly integrable in the probability sense. Indeed, as a single function is uniformly integrable in the measure theory sense, for all $\epsilon > 0$, there exists some $\delta > 0$ such that for all measurable set $A$ with $\mu(A) < δ$, we have $\mathbb{E}|h|\mathbf{1}_A < \epsilon$. So, since for sufficently large $\lambda$, by the Markov inequality, we have for all $n$, $$ \mu(|f_n| \ge \lambda) \le \lambda^{-1}\mathbb{E}|f_n| \le \lambda^{-1}\mathbb|g| < \delta, $$ we have for sufficently large $\lambda$, for all $n$, $$ \mathbb{E}|f_n|\mathbf{1}_{|f_n| \ge \lambda} \le \mathbb|g|\mathbf{1}_{|f_n| \ge \lambda} < \epsilon, $$ implying $(f_n)_n$ is uniformly integrable. Now, to prove $f_n \to h$ almost everywhere and in L¹, it suffices to show that $h = g$ almost everywhere where $g$ is the almost everywhere and L¹ limit of $(f_n)_n$ from part (b) of the theorem. By noting that, for all $s \in \mathcal{F}_n$, we have $$ \mathbb{E}g\mathbf{1}_s = \mathbb{E}[\mathbb{E}[g \mid \mathcal{F}_n]\mathbf{1}_s] = \mathbb{E}[\mathbb{E}[h \mid \mathcal{F}_n]\mathbf{1}_s] = \mathbb{E}h\mathbf{1}_s $$ where $\mathbb{E}[g \mid \mathcal{F}_n = \mathbb{E}[h \mid \mathcal{F}_n]$ almost everywhere by part (b); the equality also holds for all $s \in \mathcal{F}_\infty$ by Dynkin's theorem. Thus, as both $h$ and $g$ are $\mathcal{F}_\infty$-measurable, $h = g$ almost everywhere as required. Similar to the a.e. martingale convergence theorem, rather than showing the existence of the limiting process, we phrased the L¹-martingale convergence theorem by proving that a submartingale does converge in L¹ to its `limit_process`. However, in contrast to the a.e. martingale convergence theorem, we do not need to introduce a L¹ version of `filtration.limit_process` as the L¹ limit and the a.e. limit of a submartingale coincide. -/ /-- Part a of the **L¹ martingale convergence theorem**: a uniformly integrable submartingale adapted to the filtration `ℱ` converges a.e. and in L¹ to an integrable function which is measurable with respect to the σ-algebra `⨆ n, ℱ n`. -/ lemma submartingale.tendsto_snorm_one_limit_process (hf : submartingale f ℱ μ) (hunif : uniform_integrable f 1 μ) : tendsto (λ n, snorm (f n - ℱ.limit_process f μ) 1 μ) at_top (𝓝 0) := begin obtain ⟨R, hR⟩ := hunif.2.2, have hmeas : ∀ n, ae_strongly_measurable (f n) μ := λ n, ((hf.strongly_measurable n).mono (ℱ.le _)).ae_strongly_measurable, exact tendsto_Lp_of_tendsto_in_measure _ le_rfl ennreal.one_ne_top hmeas (mem_ℒp_limit_process_of_snorm_bdd hmeas hR) hunif.2.1 (tendsto_in_measure_of_tendsto_ae hmeas $ hf.ae_tendsto_limit_process hR), end lemma submartingale.ae_tendsto_limit_process_of_uniform_integrable (hf : submartingale f ℱ μ) (hunif : uniform_integrable f 1 μ) : ∀ᵐ ω ∂μ, tendsto (λ n, f n ω) at_top (𝓝 (ℱ.limit_process f μ ω)) := let ⟨R, hR⟩ := hunif.2.2 in hf.ae_tendsto_limit_process hR /-- If a martingale `f` adapted to `ℱ` converges in L¹ to `g`, then for all `n`, `f n` is almost everywhere equal to `𝔼[g | ℱ n]`. -/ lemma martingale.eq_condexp_of_tendsto_snorm {μ : measure Ω} (hf : martingale f ℱ μ) (hg : integrable g μ) (hgtends : tendsto (λ n, snorm (f n - g) 1 μ) at_top (𝓝 0)) (n : ℕ) : f n =ᵐ[μ] μ[g | ℱ n] := begin rw [← sub_ae_eq_zero, ← snorm_eq_zero_iff ((((hf.strongly_measurable n).mono (ℱ.le _)).sub (strongly_measurable_condexp.mono (ℱ.le _))).ae_strongly_measurable) one_ne_zero], have ht : tendsto (λ m, snorm (μ[f m - g | ℱ n]) 1 μ) at_top (𝓝 0), { have hint : ∀ m, integrable (f m - g) μ := λ m, (hf.integrable m).sub hg, exact tendsto_of_tendsto_of_tendsto_of_le_of_le tendsto_const_nhds hgtends (λ m, zero_le _) (λ m, snorm_one_condexp_le_snorm _) }, have hev : ∀ m ≥ n, snorm (μ[f m - g | ℱ n]) 1 μ = snorm (f n - μ[g | ℱ n]) 1 μ, { refine λ m hm, snorm_congr_ae ((condexp_sub (hf.integrable m) hg).trans _), filter_upwards [hf.2 n m hm] with x hx, simp only [hx, pi.sub_apply] }, exact tendsto_nhds_unique (tendsto_at_top_of_eventually_const hev) ht, end /-- Part b of the **L¹ martingale convergence theorem**: if `f` is a uniformly integrable martingale adapted to the filtration `ℱ`, then for all `n`, `f n` is almost everywhere equal to the conditional expectation of its limiting process wrt. `ℱ n`. -/ lemma martingale.ae_eq_condexp_limit_process (hf : martingale f ℱ μ) (hbdd : uniform_integrable f 1 μ) (n : ℕ) : f n =ᵐ[μ] μ[ℱ.limit_process f μ | ℱ n] := let ⟨R, hR⟩ := hbdd.2.2 in hf.eq_condexp_of_tendsto_snorm ((mem_ℒp_limit_process_of_snorm_bdd hbdd.1 hR).integrable le_rfl) (hf.submartingale.tendsto_snorm_one_limit_process hbdd) n /-- Part c of the **L¹ martingale convergnce theorem**: Given a integrable function `g` which is measurable with respect to `⨆ n, ℱ n` where `ℱ` is a filtration, the martingale defined by `𝔼[g | ℱ n]` converges almost everywhere to `g`. This martingale also converges to `g` in L¹ and this result is provided by `measure_theory.integrable.tendsto_snorm_condexp` -/ lemma integrable.tendsto_ae_condexp (hg : integrable g μ) (hgmeas : strongly_measurable[⨆ n, ℱ n] g) : ∀ᵐ x ∂μ, tendsto (λ n, μ[g | ℱ n] x) at_top (𝓝 (g x)) := begin have hle : (⨆ n, ℱ n) ≤ m0 := Sup_le (λ m ⟨n, hn⟩, hn ▸ ℱ.le _), have hunif : uniform_integrable (λ n, μ[g | ℱ n]) 1 μ := hg.uniform_integrable_condexp_filtration, obtain ⟨R, hR⟩ := hunif.2.2, have hlimint : integrable (ℱ.limit_process (λ n, μ[g | ℱ n]) μ) μ := (mem_ℒp_limit_process_of_snorm_bdd hunif.1 hR).integrable le_rfl, suffices : g =ᵐ[μ] ℱ.limit_process (λ n x, μ[g | ℱ n] x) μ, { filter_upwards [this, (martingale_condexp g ℱ μ).submartingale.ae_tendsto_limit_process hR] with x heq ht, rwa heq }, have : ∀ n s, measurable_set[ℱ n] s → ∫ x in s, g x ∂μ = ∫ x in s, ℱ.limit_process (λ n x, μ[g | ℱ n] x) μ x ∂μ, { intros n s hs, rw [← set_integral_condexp (ℱ.le n) hg hs, ← set_integral_condexp (ℱ.le n) hlimint hs], refine set_integral_congr_ae (ℱ.le _ _ hs) _, filter_upwards [(martingale_condexp g ℱ μ).ae_eq_condexp_limit_process hunif n] with x hx _, rwa hx }, refine ae_eq_of_forall_set_integral_eq_of_sigma_finite' hle (λ s _ _, hg.integrable_on) (λ s _ _, hlimint.integrable_on) (λ s hs, _) hgmeas.ae_strongly_measurable' strongly_measurable_limit_process.ae_strongly_measurable', refine @measurable_space.induction_on_inter _ _ _ (⨆ n, ℱ n) (measurable_space.measurable_space_supr_eq ℱ) _ _ _ _ _ _ hs, { rintro s ⟨n, hs⟩ t ⟨m, ht⟩ -, by_cases hnm : n ≤ m, { exact ⟨m, (ℱ.mono hnm _ hs).inter ht⟩ }, { exact ⟨n, hs.inter (ℱ.mono (not_le.1 hnm).le _ ht)⟩ } }, { simp only [measure_empty, with_top.zero_lt_top, measure.restrict_empty, integral_zero_measure, forall_true_left] }, { rintro t ⟨n, ht⟩ -, exact this n _ ht }, { rintro t htmeas ht -, have hgeq := @integral_add_compl _ _ (⨆ n, ℱ n) _ _ _ _ _ _ htmeas (hg.trim hle hgmeas), have hheq := @integral_add_compl _ _ (⨆ n, ℱ n) _ _ _ _ _ _ htmeas (hlimint.trim hle strongly_measurable_limit_process), rw [add_comm, ← eq_sub_iff_add_eq] at hgeq hheq, rw [set_integral_trim hle hgmeas htmeas.compl, set_integral_trim hle strongly_measurable_limit_process htmeas.compl, hgeq, hheq, ← set_integral_trim hle hgmeas htmeas, ← set_integral_trim hle strongly_measurable_limit_process htmeas, ← integral_trim hle hgmeas, ← integral_trim hle strongly_measurable_limit_process, ← integral_univ, this 0 _ measurable_set.univ, integral_univ, ht (measure_lt_top _ _)] }, { rintro f hf hfmeas heq -, rw [integral_Union (λ n, hle _ (hfmeas n)) hf hg.integrable_on, integral_Union (λ n, hle _ (hfmeas n)) hf hlimint.integrable_on], exact tsum_congr (λ n, heq _ (measure_lt_top _ _)) } end /-- Part c of the **L¹ martingale convergnce theorem**: Given a integrable function `g` which is measurable with respect to `⨆ n, ℱ n` where `ℱ` is a filtration, the martingale defined by `𝔼[g | ℱ n]` converges in L¹ to `g`. This martingale also converges to `g` almost everywhere and this result is provided by `measure_theory.integrable.tendsto_ae_condexp` -/ lemma integrable.tendsto_snorm_condexp (hg : integrable g μ) (hgmeas : strongly_measurable[⨆ n, ℱ n] g) : tendsto (λ n, snorm (μ[g | ℱ n] - g) 1 μ) at_top (𝓝 0) := tendsto_Lp_of_tendsto_in_measure _ le_rfl ennreal.one_ne_top (λ n, (strongly_measurable_condexp.mono (ℱ.le n)).ae_strongly_measurable) (mem_ℒp_one_iff_integrable.2 hg) (hg.uniform_integrable_condexp_filtration).2.1 (tendsto_in_measure_of_tendsto_ae (λ n,(strongly_measurable_condexp.mono (ℱ.le n)).ae_strongly_measurable) (hg.tendsto_ae_condexp hgmeas)) /-- **Lévy's upward theorem**, almost everywhere version: given a function `g` and a filtration `ℱ`, the sequence defined by `𝔼[g | ℱ n]` converges almost everywhere to `𝔼[g | ⨆ n, ℱ n]`. -/ lemma tendsto_ae_condexp (g : Ω → ℝ) : ∀ᵐ x ∂μ, tendsto (λ n, μ[g | ℱ n] x) at_top (𝓝 (μ[g | ⨆ n, ℱ n] x)) := begin have ht : ∀ᵐ x ∂μ, tendsto (λ n, μ[μ[g | ⨆ n, ℱ n] | ℱ n] x) at_top (𝓝 (μ[g | ⨆ n, ℱ n] x)) := integrable_condexp.tendsto_ae_condexp strongly_measurable_condexp, have heq : ∀ n, ∀ᵐ x ∂μ, μ[μ[g | ⨆ n, ℱ n] | ℱ n] x = μ[g | ℱ n] x := λ n, condexp_condexp_of_le (le_supr _ n) (supr_le (λ n, ℱ.le n)), rw ← ae_all_iff at heq, filter_upwards [heq, ht] with x hxeq hxt, exact hxt.congr hxeq, end /-- **Lévy's upward theorem**, L¹ version: given a function `g` and a filtration `ℱ`, the sequence defined by `𝔼[g | ℱ n]` converges in L¹ to `𝔼[g | ⨆ n, ℱ n]`. -/ lemma tendsto_snorm_condexp (g : Ω → ℝ) : tendsto (λ n, snorm (μ[g | ℱ n] - μ[g | ⨆ n, ℱ n]) 1 μ) at_top (𝓝 0) := begin have ht : tendsto (λ n, snorm (μ[μ[g | ⨆ n, ℱ n] | ℱ n] - μ[g | ⨆ n, ℱ n]) 1 μ) at_top (𝓝 0) := integrable_condexp.tendsto_snorm_condexp strongly_measurable_condexp, have heq : ∀ n, ∀ᵐ x ∂μ, μ[μ[g | ⨆ n, ℱ n] | ℱ n] x = μ[g | ℱ n] x := λ n, condexp_condexp_of_le (le_supr _ n) (supr_le (λ n, ℱ.le n)), refine ht.congr (λ n, snorm_congr_ae _), filter_upwards [heq n] with x hxeq, simp only [hxeq, pi.sub_apply], end end L1_convergence end measure_theory
a8682a7f3bf4b890d9164a34b5f1d62667051204
fe25de614feb5587799621c41487aaee0d083b08
/stage0/src/Lean/Elab/Quotation.lean
1687eea006923b6237b5ebea7063cdf33b29c1c0
[ "Apache-2.0" ]
permissive
pollend/lean4
e8469c2f5fb8779b773618c3267883cf21fb9fac
c913886938c4b3b83238a3f99673c6c5a9cec270
refs/heads/master
1,687,973,251,481
1,628,039,739,000
1,628,039,739,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
24,833
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich Elaboration of syntax quotations as terms and patterns (in `match_syntax`). See also `./Hygiene.lean` for the basic hygiene workings and data types. -/ import Lean.Syntax import Lean.ResolveName import Lean.Elab.Term import Lean.Elab.Quotation.Util import Lean.Elab.Quotation.Precheck import Lean.Parser.Term namespace Lean.Elab.Term.Quotation open Lean.Parser.Term open Lean.Syntax open Meta /-- `C[$(e)]` ~> `let a := e; C[$a]`. Used in the implementation of antiquot splices. -/ private partial def floatOutAntiquotTerms : Syntax → StateT (Syntax → TermElabM Syntax) TermElabM Syntax | stx@(Syntax.node k args) => do if isAntiquot stx && !isEscapedAntiquot stx then let e := getAntiquotTerm stx if !e.isIdent || !e.getId.isAtomic then return ← withFreshMacroScope do let a ← `(a) modify (fun cont stx => (`(let $a:ident := $e; $stx) : TermElabM _)) stx.setArg 2 a Syntax.node k (← args.mapM floatOutAntiquotTerms) | stx => pure stx private def getSepFromSplice (splice : Syntax) : Syntax := do let Syntax.atom _ sep ← getAntiquotSpliceSuffix splice | unreachable! Syntax.mkStrLit (sep.dropRight 1) partial def mkTuple : Array Syntax → TermElabM Syntax | #[] => `(Unit.unit) | #[e] => e | es => do let stx ← mkTuple (es.eraseIdx 0) `(Prod.mk $(es[0]) $stx) def resolveSectionVariable (sectionVars : NameMap Name) (id : Name) : List (Name × List String) := -- decode macro scopes from name before recursion let extractionResult := extractMacroScopes id let rec loop : Name → List String → List (Name × List String) | id@(Name.str p s _), projs => -- NOTE: we assume that macro scopes always belong to the projected constant, not the projections let id := { extractionResult with name := id }.review match sectionVars.find? id with | some newId => [(newId, projs)] | none => loop p (s::projs) | _, _ => [] loop extractionResult.name [] /-- Transform sequence of pushes and appends into acceptable code -/ def ArrayStxBuilder := Sum (Array Syntax) Syntax namespace ArrayStxBuilder def empty : ArrayStxBuilder := Sum.inl #[] def build : ArrayStxBuilder → Syntax | Sum.inl elems => quote elems | Sum.inr arr => arr def push (b : ArrayStxBuilder) (elem : Syntax) : ArrayStxBuilder := match b with | Sum.inl elems => Sum.inl <| elems.push elem | Sum.inr arr => Sum.inr <| mkCApp ``Array.push #[arr, elem] def append (b : ArrayStxBuilder) (arr : Syntax) (appendName := ``Array.append) : ArrayStxBuilder := Sum.inr <| mkCApp appendName #[b.build, arr] end ArrayStxBuilder -- Elaborate the content of a syntax quotation term private partial def quoteSyntax : Syntax → TermElabM Syntax | Syntax.ident info rawVal val preresolved => do if !hygiene.get (← getOptions) then return ← `(Syntax.ident info $(quote rawVal) $(quote val) $(quote preresolved)) -- Add global scopes at compilation time (now), add macro scope at runtime (in the quotation). -- See the paper for details. let r ← resolveGlobalName val -- extension of the paper algorithm: also store unique section variable names as top-level scopes -- so they can be captured and used inside the section, but not outside let r' := resolveSectionVariable (← read).sectionVars val let preresolved := r ++ r' ++ preresolved let val := quote val -- `scp` is bound in stxQuot.expand `(Syntax.ident info $(quote rawVal) (addMacroScope mainModule $val scp) $(quote preresolved)) -- if antiquotation, insert contents as-is, else recurse | stx@(Syntax.node k _) => do if isAntiquot stx && !isEscapedAntiquot stx then getAntiquotTerm stx else if isTokenAntiquot stx && !isEscapedAntiquot stx then match stx[0] with | Syntax.atom _ val => `(Syntax.atom (Option.getD (getHeadInfo? $(getAntiquotTerm stx)) info) $(quote val)) | _ => throwErrorAt stx "expected token" else if isAntiquotSuffixSplice stx && !isEscapedAntiquot stx then -- splices must occur in a `many` node throwErrorAt stx "unexpected antiquotation splice" else if isAntiquotSplice stx && !isEscapedAntiquot stx then throwErrorAt stx "unexpected antiquotation splice" else -- if escaped antiquotation, decrement by one escape level let stx := unescapeAntiquot stx let mut args := ArrayStxBuilder.empty let appendName := if (← getEnv).contains ``Array.append then ``Array.append else ``Array.appendCore for arg in stx.getArgs do if k == nullKind && isAntiquotSuffixSplice arg then let antiquot := getAntiquotSuffixSpliceInner arg args := args.append (appendName := appendName) <| ← match antiquotSuffixSplice? arg with | `optional => `(match $(getAntiquotTerm antiquot):term with | some x => Array.empty.push x | none => Array.empty) | `many => getAntiquotTerm antiquot | `sepBy => `(@SepArray.elemsAndSeps $(getSepFromSplice arg) $(getAntiquotTerm antiquot)) | k => throwErrorAt arg "invalid antiquotation suffix splice kind '{k}'" else if k == nullKind && isAntiquotSplice arg then let k := antiquotSpliceKind? arg let (arg, bindLets) ← floatOutAntiquotTerms arg |>.run pure let inner ← (getAntiquotSpliceContents arg).mapM quoteSyntax let ids ← getAntiquotationIds arg if ids.isEmpty then throwErrorAt stx "antiquotation splice must contain at least one antiquotation" let arr ← match k with | `optional => `(match $[$ids:ident],* with | $[some $ids:ident],* => $(quote inner) | none => Array.empty) | _ => let arr ← ids[:ids.size-1].foldrM (fun id arr => `(Array.zip $id $arr)) ids.back `(Array.map (fun $(← mkTuple ids) => $(inner[0])) $arr) let arr ← if k == `sepBy then `(mkSepArray $arr (mkAtom $(getSepFromSplice arg))) else arr let arr ← bindLets arr args := args.append arr else do let arg ← quoteSyntax arg args := args.push arg `(Syntax.node $(quote k) $(args.build)) | Syntax.atom _ val => `(Syntax.atom info $(quote val)) | Syntax.missing => throwUnsupportedSyntax def stxQuot.expand (stx : Syntax) : TermElabM Syntax := do /- Syntax quotations are monadic values depending on the current macro scope. For efficiency, we bind the macro scope once for each quotation, then build the syntax tree in a completely pure computation depending on this binding. Note that regular function calls do not introduce a new macro scope (i.e. we preserve referential transparency), so we can refer to this same `scp` inside `quoteSyntax` by including it literally in a syntax quotation. -/ -- TODO: simplify to `(do scp ← getCurrMacroScope; pure $(quoteSyntax quoted)) let stx ← quoteSyntax stx.getQuotContent; `(Bind.bind MonadRef.mkInfoFromRefPos (fun info => Bind.bind getCurrMacroScope (fun scp => Bind.bind getMainModule (fun mainModule => Pure.pure $stx)))) /- NOTE: It may seem like the newly introduced binding `scp` may accidentally capture identifiers in an antiquotation introduced by `quoteSyntax`. However, note that the syntax quotation above enjoys the same hygiene guarantees as anywhere else in Lean; that is, we implement hygienic quotations by making use of the hygienic quotation support of the bootstrapped Lean compiler! Aside: While this might sound "dangerous", it is in fact less reliant on a "chain of trust" than other bootstrapping parts of Lean: because this implementation itself never uses `scp` (or any other identifier) both inside and outside quotations, it can actually correctly be compiled by an unhygienic (but otherwise correct) implementation of syntax quotations. As long as it is then compiled again with the resulting executable (i.e. up to stage 2), the result is a correct hygienic implementation. In this sense the implementation is "self-stabilizing". It was in fact originally compiled by an unhygienic prototype implementation. -/ macro "elab_stx_quot" kind:ident : command => `(@[builtinTermElab $kind:ident] def elabQuot : TermElab := adaptExpander stxQuot.expand) -- elab_stx_quot Parser.Level.quot elab_stx_quot Parser.Term.quot elab_stx_quot Parser.Term.funBinder.quot elab_stx_quot Parser.Term.bracketedBinder.quot elab_stx_quot Parser.Term.matchDiscr.quot elab_stx_quot Parser.Tactic.quot elab_stx_quot Parser.Tactic.quotSeq elab_stx_quot Parser.Term.stx.quot elab_stx_quot Parser.Term.prec.quot elab_stx_quot Parser.Term.attr.quot elab_stx_quot Parser.Term.prio.quot elab_stx_quot Parser.Term.doElem.quot elab_stx_quot Parser.Term.dynamicQuot /- match -/ -- an "alternative" of patterns plus right-hand side private abbrev Alt := List Syntax × Syntax /-- In a single match step, we match the first discriminant against the "head" of the first pattern of the first alternative. This datatype describes what kind of check this involves, which helps other patterns decide if they are covered by the same check and don't have to be checked again (see also `MatchResult`). -/ inductive HeadCheck where -- match step that always succeeds: _, x, `($x), ... | unconditional -- match step based on kind and, optionally, arity of discriminant -- If `arity` is given, that number of new discriminants is introduced. `covered` patterns should then introduce the -- same number of new patterns. -- We actually check the arity at run time only in the case of `null` nodes since it should otherwise by implied by -- the node kind. -- without arity: `($x:k) -- with arity: any quotation without an antiquotation head pattern | shape (k : SyntaxNodeKind) (arity : Option Nat) -- Match step that succeeds on `null` nodes of arity at least `numPrefix + numSuffix`, introducing discriminants -- for the first `numPrefix` children, one `null` node for those in between, and for the `numSuffix` last children. -- example: `([$x, $xs,*, $y]) is `slice 2 2` | slice (numPrefix numSuffix : Nat) -- other, complicated match step that will probably only cover identical patterns -- example: antiquotation splices `($[...]*) | other (pat : Syntax) open HeadCheck /-- Describe whether a pattern is covered by a head check (induced by the pattern itself or a different pattern). -/ inductive MatchResult where -- Pattern agrees with head check, remove and transform remaining alternative. -- If `exhaustive` is `false`, *also* include unchanged alternative in the "no" branch. | covered (f : Alt → TermElabM Alt) (exhaustive : Bool) -- Pattern disagrees with head check, include in "no" branch only | uncovered -- Pattern is not quite sure yet; include unchanged in both branches | undecided open MatchResult /-- All necessary information on a pattern head. -/ structure HeadInfo where -- check induced by the pattern check : HeadCheck -- compute compatibility of pattern with given head check onMatch (taken : HeadCheck) : MatchResult -- actually run the specified head check, with the discriminant bound to `discr` doMatch (yes : (newDiscrs : List Syntax) → TermElabM Syntax) (no : TermElabM Syntax) : TermElabM Syntax /-- Adapt alternatives that do not introduce new discriminants in `doMatch`, but are covered by those that do so. -/ private def noOpMatchAdaptPats : HeadCheck → Alt → Alt | shape k (some sz), (pats, rhs) => (List.replicate sz (Unhygienic.run `(_)) ++ pats, rhs) | slice p s, (pats, rhs) => (List.replicate (p + 1 + s) (Unhygienic.run `(_)) ++ pats, rhs) | _, alt => alt private def adaptRhs (fn : Syntax → TermElabM Syntax) : Alt → TermElabM Alt | (pats, rhs) => do (pats, ← fn rhs) private partial def getHeadInfo (alt : Alt) : TermElabM HeadInfo := let pat := alt.fst.head! let unconditionally (rhsFn) := pure { check := unconditional, doMatch := fun yes no => yes [], onMatch := fun taken => covered (adaptRhs rhsFn ∘ noOpMatchAdaptPats taken) (match taken with | unconditional => true | _ => false) } -- quotation pattern if isQuot pat then let quoted := getQuotContent pat if quoted.isAtom then -- We assume that atoms are uniquely determined by the node kind and never have to be checked unconditionally pure else if quoted.isTokenAntiquot then unconditionally (`(let $(quoted.getAntiquotTerm) := discr; $(·))) else if isAntiquot quoted && !isEscapedAntiquot quoted then -- quotation contains a single antiquotation let k := antiquotKind? quoted |>.get! let rhsFn := match getAntiquotTerm quoted with | `(_) => pure | `($id:ident) => fun stx => `(let $id := discr; $(stx)) | anti => fun _ => throwErrorAt anti "unsupported antiquotation kind in pattern" -- Antiquotation kinds like `$id:ident` influence the parser, but also need to be considered by -- `match` (but not by quotation terms). For example, `($id:ident) and `($e) are not -- distinguishable without checking the kind of the node to be captured. Note that some -- antiquotations like the latter one for terms do not correspond to any actual node kind -- (signified by `k == Name.anonymous`), so we would only check for `ident` here. -- -- if stx.isOfKind `ident then -- let id := stx; let e := stx; ... -- else -- let e := stx; ... if k == Name.anonymous then unconditionally rhsFn else pure { check := shape k none, onMatch := fun | other _ => undecided | taken@(shape k' sz) => if k' == k then covered (adaptRhs rhsFn ∘ noOpMatchAdaptPats taken) (exhaustive := sz.isNone) else uncovered | _ => uncovered, doMatch := fun yes no => do `(cond (Syntax.isOfKind discr $(quote k)) $(← yes []) $(← no)), } else if isAntiquotSuffixSplice quoted then throwErrorAt quoted "unexpected antiquotation splice" else if isAntiquotSplice quoted then throwErrorAt quoted "unexpected antiquotation splice" else if quoted.getArgs.size == 1 && isAntiquotSuffixSplice quoted[0] then let anti := getAntiquotTerm (getAntiquotSuffixSpliceInner quoted[0]) unconditionally fun rhs => match antiquotSuffixSplice? quoted[0] with | `optional => `(let $anti := Syntax.getOptional? discr; $rhs) | `many => `(let $anti := Syntax.getArgs discr; $rhs) | `sepBy => `(let $anti := @SepArray.mk $(getSepFromSplice quoted[0]) (Syntax.getArgs discr); $rhs) | k => throwErrorAt quoted "invalid antiquotation suffix splice kind '{k}'" else if quoted.getArgs.size == 1 && isAntiquotSplice quoted[0] then pure { check := other pat, onMatch := fun | other pat' => if pat' == pat then covered pure (exhaustive := true) else undecided | _ => undecided, doMatch := fun yes no => do let splice := quoted[0] let k := antiquotSpliceKind? splice let contents := getAntiquotSpliceContents splice let ids ← getAntiquotationIds splice let yes ← yes [] let no ← no match k with | `optional => let nones := mkArray ids.size (← `(none)) `(let_delayed yes _ $ids* := $yes; if discr.isNone then yes () $[ $nones]* else match discr with | `($(mkNullNode contents)) => yes () $[ (some $ids)]* | _ => $no) | _ => let mut discrs ← `(Syntax.getArgs discr) if k == `sepBy then discrs ← `(Array.getSepElems $discrs) let tuple ← mkTuple ids let mut yes := yes let resId ← match ids with | #[id] => id | _ => for id in ids do yes ← `(let $id := tuples.map (fun $tuple => $id); $yes) `(tuples) let contents := if contents.size == 1 then contents[0] else mkNullNode contents `(match OptionM.run ($(discrs).sequenceMap fun | `($contents) => some $tuple | _ => none) with | some $resId => $yes | none => $no) } else if let some idx := quoted.getArgs.findIdx? (fun arg => isAntiquotSuffixSplice arg || isAntiquotSplice arg) then do /- pattern of the form `match discr, ... with | `(pat_0 ... pat_(idx-1) $[...]* pat_(idx+1) ...), ...` transform to ``` if discr.getNumArgs >= $quoted.getNumArgs - 1 then match discr[0], ..., discr[idx-1], mkNullNode (discr.getArgs.extract idx (discr.getNumArgs - $numSuffix))), ..., discr[quoted.getNumArgs - 1] with | `(pat_0), ... `(pat_(idx-1)), `($[...])*, `(pat_(idx+1)), ... ``` -/ let numSuffix := quoted.getNumArgs - 1 - idx pure { check := slice idx numSuffix onMatch := fun | other _ => undecided | slice p s => if p == idx && s == numSuffix then let argPats := quoted.getArgs.mapIdx fun i arg => let arg := if (i : Nat) == idx then mkNullNode #[arg] else arg Unhygienic.run `(`($(arg))) covered (fun (pats, rhs) => (argPats.toList ++ pats, rhs)) (exhaustive := true) else uncovered | _ => uncovered doMatch := fun yes no => do let prefixDiscrs ← (List.range idx).mapM (`(Syntax.getArg discr $(quote ·))) let sliceDiscr ← `(mkNullNode (discr.getArgs.extract $(quote idx) (discr.getNumArgs - $(quote numSuffix)))) let suffixDiscrs ← (List.range numSuffix).mapM fun i => `(Syntax.getArg discr (discr.getNumArgs - $(quote (numSuffix - i)))) `(ite (GE.ge discr.getNumArgs $(quote (quoted.getNumArgs - 1))) $(← yes (prefixDiscrs ++ sliceDiscr :: suffixDiscrs)) $(← no)) } else -- not an antiquotation, or an escaped antiquotation: match head shape let quoted := unescapeAntiquot quoted let kind := quoted.getKind let argPats := quoted.getArgs.map fun arg => Unhygienic.run `(`($(arg))) pure { check := if quoted.isIdent then -- identifiers only match identical identifiers -- NOTE: We could make this case more precise by including the matched identifier, -- if any, in the `shape` constructor, but matching on literal identifiers is quite -- rare. other quoted else shape kind argPats.size, onMatch := fun | other stx' => if quoted.isIdent && quoted == stx' then covered pure (exhaustive := true) else uncovered | shape k' sz => if k' == kind && sz == argPats.size then covered (fun (pats, rhs) => (argPats.toList ++ pats, rhs)) (exhaustive := true) else uncovered | _ => uncovered, doMatch := fun yes no => do let cond ← match kind with | `null => `(Syntax.matchesNull discr $(quote argPats.size)) | `ident => `(Syntax.matchesIdent discr $(quote quoted.getId)) | _ => `(Syntax.isOfKind discr $(quote kind)) let newDiscrs ← (List.range argPats.size).mapM fun i => `(Syntax.getArg discr $(quote i)) `(ite (Eq $cond true) $(← yes newDiscrs) $(← no)) } else match pat with | `(_) => unconditionally pure | `($id:ident) => unconditionally (`(let $id := discr; $(·))) | `($id:ident@$pat) => do let info ← getHeadInfo (pat::alt.1.tail!, alt.2) { info with onMatch := fun taken => match info.onMatch taken with | covered f exh => covered (fun alt => f alt >>= adaptRhs (`(let $id := discr; $(·)))) exh | r => r } | _ => throwErrorAt pat "match (syntax) : unexpected pattern kind {pat}" -- Bind right-hand side to new `let_delayed` decl in order to prevent code duplication private def deduplicate (floatedLetDecls : Array Syntax) : Alt → TermElabM (Array Syntax × Alt) -- NOTE: new macro scope so that introduced bindings do not collide | (pats, rhs) => do if let `($f:ident $[ $args:ident]*) := rhs then -- looks simple enough/created by this function, skip return (floatedLetDecls, (pats, rhs)) withFreshMacroScope do match (← getPatternsVars pats.toArray) with | #[] => -- no antiquotations => introduce Unit parameter to preserve evaluation order let rhs' ← `(rhs Unit.unit) (floatedLetDecls.push (← `(letDecl|rhs _ := $rhs)), (pats, rhs')) | vars => let rhs' ← `(rhs $vars*) (floatedLetDecls.push (← `(letDecl|rhs $vars:ident* := $rhs)), (pats, rhs')) private partial def compileStxMatch (discrs : List Syntax) (alts : List Alt) : TermElabM Syntax := do trace[Elab.match_syntax] "match {discrs} with {alts}" match discrs, alts with | [], ([], rhs)::_ => pure rhs -- nothing left to match | _, [] => logError "non-exhaustive 'match' (syntax)" pure Syntax.missing | discr::discrs, alt::alts => do let info ← getHeadInfo alt let pat := alt.1.head! let alts ← (alt::alts).mapM fun alt => do ((← getHeadInfo alt).onMatch info.check, alt) let mut yesAlts := #[] let mut undecidedAlts := #[] let mut nonExhaustiveAlts := #[] let mut floatedLetDecls := #[] for alt in alts do let mut alt := alt match alt with | (covered f exh, alt') => -- we can only factor out a common check if there are no undecided patterns in between; -- otherwise we would change the order of alternatives if undecidedAlts.isEmpty then yesAlts ← yesAlts.push <$> f (alt'.1.tail!, alt'.2) if !exh then nonExhaustiveAlts := nonExhaustiveAlts.push alt' else (floatedLetDecls, alt) ← deduplicate floatedLetDecls alt' undecidedAlts := undecidedAlts.push alt nonExhaustiveAlts := nonExhaustiveAlts.push alt | (undecided, alt') => (floatedLetDecls, alt) ← deduplicate floatedLetDecls alt' undecidedAlts := undecidedAlts.push alt nonExhaustiveAlts := nonExhaustiveAlts.push alt | (uncovered, alt') => nonExhaustiveAlts := nonExhaustiveAlts.push alt' let mut stx ← info.doMatch (yes := fun newDiscrs => do let mut yesAlts := yesAlts if !undecidedAlts.isEmpty then -- group undecided alternatives in a new default case `| discr2, ... => match discr, discr2, ... with ...` let vars ← discrs.mapM fun _ => withFreshMacroScope `(discr) let pats := List.replicate newDiscrs.length (Unhygienic.run `(_)) ++ vars let alts ← undecidedAlts.mapM fun alt => `(matchAltExpr| | $(alt.1.toArray),* => $(alt.2)) let rhs ← `(match discr, $[$(vars.toArray):term],* with $alts:matchAlt*) yesAlts := yesAlts.push (pats, rhs) withFreshMacroScope $ compileStxMatch (newDiscrs ++ discrs) yesAlts.toList) (no := withFreshMacroScope $ compileStxMatch (discr::discrs) nonExhaustiveAlts.toList) for d in floatedLetDecls do stx ← `(let_delayed $d:letDecl; $stx) `(let discr := $discr; $stx) | _, _ => unreachable! def match_syntax.expand (stx : Syntax) : TermElabM Syntax := do match stx with | `(match $[$discrs:term],* with $[| $[$patss],* => $rhss]*) => do if !patss.any (·.any (fun | `($id@$pat) => pat.isQuot | pat => pat.isQuot)) then -- no quotations => fall back to regular `match` throwUnsupportedSyntax let stx ← compileStxMatch discrs.toList (patss.map (·.toList) |>.zip rhss).toList trace[Elab.match_syntax.result] "{stx}" stx | _ => throwUnsupportedSyntax @[builtinTermElab «match»] def elabMatchSyntax : TermElab := adaptExpander match_syntax.expand builtin_initialize registerTraceClass `Elab.match_syntax registerTraceClass `Elab.match_syntax.result end Lean.Elab.Term.Quotation
21100b5d3578d729cbe798d2fdf49acff20f8389
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/logic/embedding/basic.lean
06cf19825d7907e053ae648f8dcd2b99b9f11205
[ "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,040
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import data.fun_like.embedding import data.prod.pprod import data.sigma.basic import data.option.basic import data.subtype import logic.equiv.basic /-! # Injective functions > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ universes u v w x namespace function /-- `α ↪ β` is a bundled injective function. -/ @[nolint has_nonempty_instance] -- depending on cardinalities, an injective function may not exist structure embedding (α : Sort*) (β : Sort*) := (to_fun : α → β) (inj' : injective to_fun) infixr ` ↪ `:25 := embedding instance {α : Sort u} {β : Sort v} : has_coe_to_fun (α ↪ β) (λ _, α → β) := ⟨embedding.to_fun⟩ initialize_simps_projections embedding (to_fun → apply) instance {α : Sort u} {β : Sort v} : embedding_like (α ↪ β) α β := { coe := embedding.to_fun, injective' := embedding.inj', coe_injective' := λ f g h, by { cases f, cases g, congr' } } instance {α β : Sort*} : can_lift (α → β) (α ↪ β) coe_fn injective := { prf := λ f hf, ⟨⟨f, hf⟩, rfl⟩ } end function section equiv variables {α : Sort u} {β : Sort v} (f : α ≃ β) /-- Convert an `α ≃ β` to `α ↪ β`. This is also available as a coercion `equiv.coe_embedding`. The explicit `equiv.to_embedding` version is preferred though, since the coercion can have issues inferring the type of the resulting embedding. For example: ```lean -- Works: example (s : finset (fin 3)) (f : equiv.perm (fin 3)) : s.map f.to_embedding = s.map f := by simp -- Error, `f` has type `fin 3 ≃ fin 3` but is expected to have type `fin 3 ↪ ?m_1 : Type ?` example (s : finset (fin 3)) (f : equiv.perm (fin 3)) : s.map f = s.map f.to_embedding := by simp ``` -/ protected def equiv.to_embedding : α ↪ β := ⟨f, f.injective⟩ @[simp] lemma equiv.coe_to_embedding : ⇑f.to_embedding = f := rfl lemma equiv.to_embedding_apply (a : α) : f.to_embedding a = f a := rfl instance equiv.coe_embedding : has_coe (α ≃ β) (α ↪ β) := ⟨equiv.to_embedding⟩ @[reducible] instance equiv.perm.coe_embedding : has_coe (equiv.perm α) (α ↪ α) := equiv.coe_embedding @[simp] lemma equiv.coe_eq_to_embedding : ↑f = f.to_embedding := rfl /-- Given an equivalence to a subtype, produce an embedding to the elements of the corresponding set. -/ @[simps] def equiv.as_embedding {p : β → Prop} (e : α ≃ subtype p) : α ↪ β := ⟨coe ∘ e, subtype.coe_injective.comp e.injective⟩ end equiv namespace function namespace embedding lemma coe_injective {α β} : @function.injective (α ↪ β) (α → β) coe_fn := fun_like.coe_injective @[ext] lemma ext {α β} {f g : embedding α β} (h : ∀ x, f x = g x) : f = g := fun_like.ext f g h lemma ext_iff {α β} {f g : embedding α β} : (∀ x, f x = g x) ↔ f = g := fun_like.ext_iff.symm @[simp] theorem to_fun_eq_coe {α β} (f : α ↪ β) : to_fun f = f := rfl @[simp] theorem coe_fn_mk {α β} (f : α → β) (i) : (@mk _ _ f i : α → β) = f := rfl @[simp] lemma mk_coe {α β : Type*} (f : α ↪ β) (inj) : (⟨f, inj⟩ : α ↪ β) = f := by { ext, simp } protected theorem injective {α β} (f : α ↪ β) : injective f := embedding_like.injective f lemma apply_eq_iff_eq {α β} (f : α ↪ β) (x y : α) : f x = f y ↔ x = y := embedding_like.apply_eq_iff_eq f /-- The identity map as a `function.embedding`. -/ @[refl, simps {simp_rhs := tt}] protected def refl (α : Sort*) : α ↪ α := ⟨id, injective_id⟩ /-- Composition of `f : α ↪ β` and `g : β ↪ γ`. -/ @[trans, simps {simp_rhs := tt}] protected def trans {α β γ} (f : α ↪ β) (g : β ↪ γ) : α ↪ γ := ⟨g ∘ f, g.injective.comp f.injective⟩ @[simp] lemma equiv_to_embedding_trans_symm_to_embedding {α β : Sort*} (e : α ≃ β) : e.to_embedding.trans e.symm.to_embedding = embedding.refl _ := by { ext, simp, } @[simp] lemma equiv_symm_to_embedding_trans_to_embedding {α β : Sort*} (e : α ≃ β) : e.symm.to_embedding.trans e.to_embedding = embedding.refl _ := by { ext, simp, } /-- Transfer an embedding along a pair of equivalences. -/ @[simps { fully_applied := ff }] protected def congr {α : Sort u} {β : Sort v} {γ : Sort w} {δ : Sort x} (e₁ : α ≃ β) (e₂ : γ ≃ δ) (f : α ↪ γ) : (β ↪ δ) := (equiv.to_embedding e₁.symm).trans (f.trans e₂.to_embedding) /-- A right inverse `surj_inv` of a surjective function as an `embedding`. -/ protected noncomputable def of_surjective {α β} (f : β → α) (hf : surjective f) : α ↪ β := ⟨surj_inv hf, injective_surj_inv _⟩ /-- Convert a surjective `embedding` to an `equiv` -/ protected noncomputable def equiv_of_surjective {α β} (f : α ↪ β) (hf : surjective f) : α ≃ β := equiv.of_bijective f ⟨f.injective, hf⟩ /-- There is always an embedding from an empty type. -/ protected def of_is_empty {α β} [is_empty α] : α ↪ β := ⟨is_empty_elim, is_empty_elim⟩ /-- Change the value of an embedding `f` at one point. If the prescribed image is already occupied by some `f a'`, then swap the values at these two points. -/ def set_value {α β} (f : α ↪ β) (a : α) (b : β) [∀ a', decidable (a' = a)] [∀ a', decidable (f a' = b)] : α ↪ β := ⟨λ a', if a' = a then b else if f a' = b then f a else f a', begin intros x y h, dsimp at h, split_ifs at h; try { substI b }; try { simp only [f.injective.eq_iff] at * }; cc end⟩ theorem set_value_eq {α β} (f : α ↪ β) (a : α) (b : β) [∀ a', decidable (a' = a)] [∀ a', decidable (f a' = b)] : set_value f a b a = b := by simp [set_value] /-- Embedding into `option α` using `some`. -/ @[simps { fully_applied := ff }] protected def some {α} : α ↪ option α := ⟨some, option.some_injective α⟩ /-- Embedding into `option α` using `coe`. Usually the correct synctatical form for `simp`. -/ @[simps { fully_applied := ff }] def coe_option {α} : α ↪ option α := ⟨coe, option.some_injective α⟩ /-- A version of `option.map` for `function.embedding`s. -/ @[simps { fully_applied := ff }] def option_map {α β} (f : α ↪ β) : option α ↪ option β := ⟨option.map f, option.map_injective f.injective⟩ /-- Embedding of a `subtype`. -/ def subtype {α} (p : α → Prop) : subtype p ↪ α := ⟨coe, λ _ _, subtype.ext_val⟩ @[simp] lemma coe_subtype {α} (p : α → Prop) : ⇑(subtype p) = coe := rfl /-- `quotient.out` as an embedding. -/ noncomputable def quotient_out (α) [s : setoid α] : quotient s ↪ α := ⟨_, quotient.out_injective⟩ @[simp] theorem coe_quotient_out (α) [s : setoid α] : ⇑(quotient_out α) = quotient.out := rfl /-- Choosing an element `b : β` gives an embedding of `punit` into `β`. -/ def punit {β : Sort*} (b : β) : punit ↪ β := ⟨λ _, b, by { rintros ⟨⟩ ⟨⟩ _, refl, }⟩ /-- Fixing an element `b : β` gives an embedding `α ↪ α × β`. -/ @[simps] def sectl (α : Sort*) {β : Sort*} (b : β) : α ↪ α × β := ⟨λ a, (a, b), λ a a' h, congr_arg prod.fst h⟩ /-- Fixing an element `a : α` gives an embedding `β ↪ α × β`. -/ @[simps] def sectr {α : Sort*} (a : α) (β : Sort*): β ↪ α × β := ⟨λ b, (a, b), λ b b' h, congr_arg prod.snd h⟩ /-- If `e₁` and `e₂` are embeddings, then so is `prod.map e₁ e₂ : (a, b) ↦ (e₁ a, e₂ b)`. -/ def prod_map {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : α × γ ↪ β × δ := ⟨prod.map e₁ e₂, e₁.injective.prod_map e₂.injective⟩ @[simp] lemma coe_prod_map {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : ⇑(e₁.prod_map e₂) = prod.map e₁ e₂ := rfl /-- If `e₁` and `e₂` are embeddings, then so is `λ ⟨a, b⟩, ⟨e₁ a, e₂ b⟩ : pprod α γ → pprod β δ`. -/ def pprod_map {α β γ δ : Sort*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : pprod α γ ↪ pprod β δ := ⟨λ x, ⟨e₁ x.1, e₂ x.2⟩, e₁.injective.pprod_map e₂.injective⟩ section sum open sum /-- If `e₁` and `e₂` are embeddings, then so is `sum.map e₁ e₂`. -/ def sum_map {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : α ⊕ γ ↪ β ⊕ δ := ⟨sum.map e₁ e₂, assume s₁ s₂ h, match s₁, s₂, h with | inl a₁, inl a₂, h := congr_arg inl $ e₁.injective $ inl.inj h | inr b₁, inr b₂, h := congr_arg inr $ e₂.injective $ inr.inj h end⟩ @[simp] theorem coe_sum_map {α β γ δ} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : ⇑(sum_map e₁ e₂) = sum.map e₁ e₂ := rfl /-- The embedding of `α` into the sum `α ⊕ β`. -/ @[simps] def inl {α β : Type*} : α ↪ α ⊕ β := ⟨sum.inl, λ a b, sum.inl.inj⟩ /-- The embedding of `β` into the sum `α ⊕ β`. -/ @[simps] def inr {α β : Type*} : β ↪ α ⊕ β := ⟨sum.inr, λ a b, sum.inr.inj⟩ end sum section sigma variables {α α' : Type*} {β : α → Type*} {β' : α' → Type*} /-- `sigma.mk` as an `function.embedding`. -/ @[simps apply] def sigma_mk (a : α) : β a ↪ Σ x, β x := ⟨sigma.mk a, sigma_mk_injective⟩ /-- If `f : α ↪ α'` is an embedding and `g : Π a, β α ↪ β' (f α)` is a family of embeddings, then `sigma.map f g` is an embedding. -/ @[simps apply] def sigma_map (f : α ↪ α') (g : Π a, β a ↪ β' (f a)) : (Σ a, β a) ↪ Σ a', β' a' := ⟨sigma.map f (λ a, g a), f.injective.sigma_map (λ a, (g a).injective)⟩ end sigma /-- Define an embedding `(Π a : α, β a) ↪ (Π a : α, γ a)` from a family of embeddings `e : Π a, (β a ↪ γ a)`. This embedding sends `f` to `λ a, e a (f a)`. -/ @[simps] def Pi_congr_right {α : Sort*} {β γ : α → Sort*} (e : ∀ a, β a ↪ γ a) : (Π a, β a) ↪ (Π a, γ a) := ⟨λf a, e a (f a), λ f₁ f₂ h, funext $ λ a, (e a).injective (congr_fun h a)⟩ /-- An embedding `e : α ↪ β` defines an embedding `(γ → α) ↪ (γ → β)` that sends each `f` to `e ∘ f`. -/ def arrow_congr_right {α : Sort u} {β : Sort v} {γ : Sort w} (e : α ↪ β) : (γ → α) ↪ (γ → β) := Pi_congr_right (λ _, e) @[simp] lemma arrow_congr_right_apply {α : Sort u} {β : Sort v} {γ : Sort w} (e : α ↪ β) (f : γ ↪ α) : arrow_congr_right e f = e ∘ f := rfl /-- An embedding `e : α ↪ β` defines an embedding `(α → γ) ↪ (β → γ)` for any inhabited type `γ`. This embedding sends each `f : α → γ` to a function `g : β → γ` such that `g ∘ e = f` and `g y = default` whenever `y ∉ range e`. -/ noncomputable def arrow_congr_left {α : Sort u} {β : Sort v} {γ : Sort w} [inhabited γ] (e : α ↪ β) : (α → γ) ↪ (β → γ) := ⟨λ f, extend e f default, λ f₁ f₂ h, funext $ λ x, by simpa only [e.injective.extend_apply] using congr_fun h (e x)⟩ /-- Restrict both domain and codomain of an embedding. -/ protected def subtype_map {α β} {p : α → Prop} {q : β → Prop} (f : α ↪ β) (h : ∀{{x}}, p x → q (f x)) : {x : α // p x} ↪ {y : β // q y} := ⟨subtype.map f h, subtype.map_injective h f.2⟩ open set lemma swap_apply {α β : Type*} [decidable_eq α] [decidable_eq β] (f : α ↪ β) (x y z : α) : equiv.swap (f x) (f y) (f z) = f (equiv.swap x y z) := f.injective.swap_apply x y z lemma swap_comp {α β : Type*} [decidable_eq α] [decidable_eq β] (f : α ↪ β) (x y : α) : equiv.swap (f x) (f y) ∘ f = f ∘ equiv.swap x y := f.injective.swap_comp x y end embedding end function namespace equiv open function.embedding /-- The type of embeddings `α ↪ β` is equivalent to the subtype of all injective functions `α → β`. -/ def subtype_injective_equiv_embedding (α β : Sort*) : {f : α → β // function.injective f} ≃ (α ↪ β) := { to_fun := λ f, ⟨f.val, f.property⟩, inv_fun := λ f, ⟨f, f.injective⟩, left_inv := λ f, by simp, right_inv := λ f, by {ext, refl} } /-- If `α₁ ≃ α₂` and `β₁ ≃ β₂`, then the type of embeddings `α₁ ↪ β₁` is equivalent to the type of embeddings `α₂ ↪ β₂`. -/ @[congr, simps apply] def embedding_congr {α β γ δ : Sort*} (h : α ≃ β) (h' : γ ≃ δ) : (α ↪ γ) ≃ (β ↪ δ) := { to_fun := λ f, f.congr h h', inv_fun := λ f, f.congr h.symm h'.symm, left_inv := λ x, by {ext, simp}, right_inv := λ x, by {ext, simp} } @[simp] lemma embedding_congr_refl {α β : Sort*} : embedding_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α ↪ β) := by {ext, refl} @[simp] lemma embedding_congr_trans {α₁ β₁ α₂ β₂ α₃ β₃ : Sort*} (e₁ : α₁ ≃ α₂) (e₁' : β₁ ≃ β₂) (e₂ : α₂ ≃ α₃) (e₂' : β₂ ≃ β₃) : embedding_congr (e₁.trans e₂) (e₁'.trans e₂') = (embedding_congr e₁ e₁').trans (embedding_congr e₂ e₂') := rfl @[simp] lemma embedding_congr_symm {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (embedding_congr e₁ e₂).symm = embedding_congr e₁.symm e₂.symm := rfl lemma embedding_congr_apply_trans {α₁ β₁ γ₁ α₂ β₂ γ₂ : Sort*} (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) (ec : γ₁ ≃ γ₂) (f : α₁ ↪ β₁) (g : β₁ ↪ γ₁) : equiv.embedding_congr ea ec (f.trans g) = (equiv.embedding_congr ea eb f).trans (equiv.embedding_congr eb ec g) := by {ext, simp} @[simp] lemma refl_to_embedding {α : Type*} : (equiv.refl α).to_embedding = function.embedding.refl α := rfl @[simp] lemma trans_to_embedding {α β γ : Type*} (e : α ≃ β) (f : β ≃ γ) : (e.trans f).to_embedding = e.to_embedding.trans f.to_embedding := rfl end equiv section subtype variable {α : Type*} /-- A subtype `{x // p x ∨ q x}` over a disjunction of `p q : α → Prop` can be injectively split into a sum of subtypes `{x // p x} ⊕ {x // q x}` such that `¬ p x` is sent to the right. -/ def subtype_or_left_embedding (p q : α → Prop) [decidable_pred p] : {x // p x ∨ q x} ↪ {x // p x} ⊕ {x // q x} := ⟨λ x, if h : p x then sum.inl ⟨x, h⟩ else sum.inr ⟨x, x.prop.resolve_left h⟩, begin intros x y, dsimp only, split_ifs; simp [subtype.ext_iff] end⟩ lemma subtype_or_left_embedding_apply_left {p q : α → Prop} [decidable_pred p] (x : {x // p x ∨ q x}) (hx : p x) : subtype_or_left_embedding p q x = sum.inl ⟨x, hx⟩ := dif_pos hx lemma subtype_or_left_embedding_apply_right {p q : α → Prop} [decidable_pred p] (x : {x // p x ∨ q x}) (hx : ¬ p x) : subtype_or_left_embedding p q x = sum.inr ⟨x, x.prop.resolve_left hx⟩ := dif_neg hx /-- A subtype `{x // p x}` can be injectively sent to into a subtype `{x // q x}`, if `p x → q x` for all `x : α`. -/ @[simps] def subtype.imp_embedding (p q : α → Prop) (h : ∀ x, p x → q x) : {x // p x} ↪ {x // q x} := ⟨λ x, ⟨x, h x x.prop⟩, λ x y, by simp [subtype.ext_iff]⟩ end subtype
63e37e78fe04199e24e1b4e469aa8e9f54e9a5ae
d406927ab5617694ec9ea7001f101b7c9e3d9702
/archive/100-theorems-list/54_konigsberg.lean
683d7314664dbf85417c74824117de72d82d506d
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
2,801
lean
/- Copyright (c) 2022 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import combinatorics.simple_graph.trails import tactic.derive_fintype /-! # The Königsberg bridges problem We show that a graph that represents the islands and mainlands of Königsberg and seven bridges between them has no Eulerian trail. -/ namespace konigsberg /-- The vertices for the Königsberg graph; four vertices for the bodies of land and seven vertices for the bridges. -/ @[derive [decidable_eq, fintype], nolint has_inhabited_instance] inductive verts : Type | V1 | V2 | V3 | V4 -- The islands and mainlands | B1 | B2 | B3 | B4 | B5 | B6 | B7 -- The bridges open verts /-- Each of the connections between the islands/mainlands and the bridges. These are ordered pairs, but the data becomes symmetric in `konigsberg.adj`. -/ def edges : list (verts × verts) := [ (V1, B1), (V1, B2), (V1, B3), (V1, B4), (V1, B5), (B1, V2), (B2, V2), (B3, V4), (B4, V3), (B5, V3), (V2, B6), (B6, V4), (V3, B7), (B7, V4) ] /-- The adjacency relation for the Königsberg graph. -/ def adj (v w : verts) : bool := ((v, w) ∈ edges) || ((w, v) ∈ edges) /-- The Königsberg graph structure. While the Königsberg bridge problem is usually described using a multigraph, the we use a "mediant" construction to transform it into a simple graph -- every edge in the multigraph is subdivided into a path of two edges. This construction preserves whether a graph is Eulerian. (TODO: once mathlib has multigraphs, either prove the mediant construction preserves the Eulerian property or switch this file to use multigraphs. -/ @[simps] def graph : simple_graph verts := { adj := λ v w, adj v w, symm := begin dsimp [symmetric, adj], dec_trivial, end, loopless := begin dsimp [irreflexive, adj], dec_trivial end } instance : decidable_rel graph.adj := λ a b, decidable_of_bool (adj a b) iff.rfl /-- To speed up the proof, this is a cache of all the degrees of each vertex, proved in `konigsberg.degree_eq_degree`. -/ @[simp] def degree : verts → ℕ | V1 := 5 | V2 := 3 | V3 := 3 | V4 := 3 | B1 := 2 | B2 := 2 | B3 := 2 | B4 := 2 | B5 := 2 | B6 := 2 | B7 := 2 @[simp] lemma degree_eq_degree (v : verts) : graph.degree v = degree v := by cases v; refl /-- The Königsberg graph is not Eulerian. -/ theorem not_is_eulerian {u v : verts} (p : graph.walk u v) (h : p.is_eulerian) : false := begin have : {v | odd (graph.degree v)} = {verts.V1, verts.V2, verts.V3, verts.V4}, { ext w, simp only [degree_eq_degree, nat.odd_iff_not_even, set.mem_set_of_eq, set.mem_insert_iff, set.mem_singleton_iff], cases w; simp, }, have h := h.card_odd_degree, simp_rw [this] at h, norm_num at h, end end konigsberg
7d80fed668b338c6df86be1d1504263053ae91be
94e33a31faa76775069b071adea97e86e218a8ee
/src/topology/continuous_function/zero_at_infty.lean
2c019c816e7433df7c667f6c364eb1b67d451201
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
22,496
lean
/- Copyright (c) 2022 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import topology.continuous_function.bounded import topology.continuous_function.cocompact_map /-! # Continuous functions vanishing at infinity The type of continuous functions vanishing at infinity. When the domain is compact `C(α, β) ≃ C₀(α, β)` via the identity map. When the codomain is a metric space, every continuous map which vanishes at infinity is a bounded continuous function. When the domain is a locally compact space, this type has nice properties. ## TODO * Create more intances of algebraic structures (e.g., `non_unital_semiring`) once the necessary type classes (e.g., `topological_ring`) are sufficiently generalized. * Relate the unitization of `C₀(α, β)` to the Alexandroff compactification. -/ universes u v w variables {F : Type*} {α : Type u} {β : Type v} {γ : Type w} [topological_space α] open_locale bounded_continuous_function topological_space open filter metric /-- `C₀(α, β)` is the type of continuous functions `α → β` which vanish at infinity from a topological space to a metric space with a zero element. When possible, instead of parametrizing results over `(f : C₀(α, β))`, you should parametrize over `(F : Type*) [zero_at_infty_continuous_map_class F α β] (f : F)`. When you extend this structure, make sure to extend `zero_at_infty_continuous_map_class`. -/ structure zero_at_infty_continuous_map (α : Type u) (β : Type v) [topological_space α] [has_zero β] [topological_space β] extends continuous_map α β : Type (max u v) := (zero_at_infty' : tendsto to_fun (cocompact α) (𝓝 0)) localized "notation [priority 2000] `C₀(` α `, ` β `)` := zero_at_infty_continuous_map α β" in zero_at_infty localized "notation α ` →C₀ ` β := zero_at_infty_continuous_map α β" in zero_at_infty /-- `zero_at_infty_continuous_map_class F α β` states that `F` is a type of continuous maps which vanish at infinity. You should also extend this typeclass when you extend `zero_at_infty_continuous_map`. -/ class zero_at_infty_continuous_map_class (F : Type*) (α β : out_param $ Type*) [topological_space α] [has_zero β] [topological_space β] extends continuous_map_class F α β := (zero_at_infty (f : F) : tendsto f (cocompact α) (𝓝 0)) export zero_at_infty_continuous_map_class (zero_at_infty) namespace zero_at_infty_continuous_map section basics variables [topological_space β] [has_zero β] [zero_at_infty_continuous_map_class F α β] instance : zero_at_infty_continuous_map_class C₀(α, β) α β := { coe := λ f, f.to_fun, coe_injective' := λ f g h, by { obtain ⟨⟨_, _⟩, _⟩ := f, obtain ⟨⟨_, _⟩, _⟩ := g, congr' }, map_continuous := λ f, f.continuous_to_fun, zero_at_infty := λ f, f.zero_at_infty' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun C₀(α, β) (λ _, α → β) := fun_like.has_coe_to_fun instance : has_coe_t F C₀(α, β) := ⟨λ f, { to_fun := f, continuous_to_fun := map_continuous f, zero_at_infty' := zero_at_infty f }⟩ @[simp] lemma coe_to_continuous_fun (f : C₀(α, β)) : (f.to_continuous_map : α → β) = f := rfl @[ext] lemma ext {f g : C₀(α, β)} (h : ∀ x, f x = g x) : f = g := fun_like.ext _ _ h /-- Copy of a `zero_at_infinity_continuous_map` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : C₀(α, β)) (f' : α → β) (h : f' = f) : C₀(α, β) := { to_fun := f', continuous_to_fun := by { rw h, exact f.continuous_to_fun }, zero_at_infty' := by { simp_rw h, exact f.zero_at_infty' } } lemma eq_of_empty [is_empty α] (f g : C₀(α, β)) : f = g := ext $ is_empty.elim ‹_› /-- A continuous function on a compact space is automatically a continuous function vanishing at infinity. -/ @[simps] def continuous_map.lift_zero_at_infty [compact_space α] : C(α, β) ≃ C₀(α, β) := { to_fun := λ f, { to_fun := f, continuous_to_fun := f.continuous, zero_at_infty' := by simp }, inv_fun := λ f, f, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, refl } } /-- A continuous function on a compact space is automatically a continuous function vanishing at infinity. This is not an instance to avoid type class loops. -/ @[simps] def zero_at_infty_continuous_map_class.of_compact {G : Type*} [continuous_map_class G α β] [compact_space α] : zero_at_infty_continuous_map_class G α β := { coe := λ g, g, coe_injective' := λ f g h, fun_like.coe_fn_eq.mp h, map_continuous := map_continuous, zero_at_infty := by simp } end basics /-! ### Algebraic structure Whenever `β` has suitable algebraic structure and a compatible topological structure, then `C₀(α, β)` inherits a corresponding algebraic structure. The primary exception to this is that `C₀(α, β)` will not have a multiplicative identity. -/ section algebraic_structure variables [topological_space β] (x : α) instance [has_zero β] : has_zero C₀(α, β) := ⟨⟨0, tendsto_const_nhds⟩⟩ instance [has_zero β] : inhabited C₀(α, β) := ⟨0⟩ @[simp] lemma coe_zero [has_zero β] : ⇑(0 : C₀(α, β)) = 0 := rfl lemma zero_apply [has_zero β] : (0 : C₀(α, β)) x = 0 := rfl instance [mul_zero_class β] [has_continuous_mul β] : has_mul C₀(α, β) := ⟨λ f g, ⟨f * g, by simpa only [mul_zero] using (zero_at_infty f).mul (zero_at_infty g)⟩⟩ @[simp] lemma coe_mul [mul_zero_class β] [has_continuous_mul β] (f g : C₀(α, β)) : ⇑(f * g) = f * g := rfl lemma mul_apply [mul_zero_class β] [has_continuous_mul β] (f g : C₀(α, β)) : (f * g) x = f x * g x := rfl instance [mul_zero_class β] [has_continuous_mul β] : mul_zero_class C₀(α, β) := fun_like.coe_injective.mul_zero_class _ coe_zero coe_mul instance [semigroup_with_zero β] [has_continuous_mul β] : semigroup_with_zero C₀(α, β) := fun_like.coe_injective.semigroup_with_zero _ coe_zero coe_mul instance [add_zero_class β] [has_continuous_add β] : has_add C₀(α, β) := ⟨λ f g, ⟨f + g, by simpa only [add_zero] using (zero_at_infty f).add (zero_at_infty g)⟩⟩ @[simp] lemma coe_add [add_zero_class β] [has_continuous_add β] (f g : C₀(α, β)) : ⇑(f + g) = f + g := rfl lemma add_apply [add_zero_class β] [has_continuous_add β] (f g : C₀(α, β)) : (f + g) x = f x + g x := rfl instance [add_zero_class β] [has_continuous_add β] : add_zero_class C₀(α, β) := fun_like.coe_injective.add_zero_class _ coe_zero coe_add section add_monoid variables [add_monoid β] [has_continuous_add β] (f g : C₀(α, β)) @[simp] lemma coe_nsmul_rec : ∀ n, ⇑(nsmul_rec n f) = n • f | 0 := by rw [nsmul_rec, zero_smul, coe_zero] | (n + 1) := by rw [nsmul_rec, succ_nsmul, coe_add, coe_nsmul_rec] instance has_nat_scalar : has_smul ℕ C₀(α, β) := ⟨λ n f, ⟨n • f, by simpa [coe_nsmul_rec] using zero_at_infty (nsmul_rec n f)⟩⟩ instance : add_monoid C₀(α, β) := fun_like.coe_injective.add_monoid _ coe_zero coe_add (λ _ _, rfl) end add_monoid instance [add_comm_monoid β] [has_continuous_add β] : add_comm_monoid C₀(α, β) := fun_like.coe_injective.add_comm_monoid _ coe_zero coe_add (λ _ _, rfl) section add_group variables [add_group β] [topological_add_group β] (f g : C₀(α, β)) instance : has_neg C₀(α, β) := ⟨λ f, ⟨-f, by simpa only [neg_zero] using (zero_at_infty f).neg⟩⟩ @[simp] lemma coe_neg : ⇑(-f) = -f := rfl lemma neg_apply : (-f) x = -f x := rfl instance : has_sub C₀(α, β) := ⟨λ f g, ⟨f - g, by simpa only [sub_zero] using (zero_at_infty f).sub (zero_at_infty g)⟩⟩ @[simp] lemma coe_sub : ⇑(f - g) = f - g := rfl lemma sub_apply : (f - g) x = f x - g x := rfl @[simp] lemma coe_zsmul_rec : ∀ z, ⇑(zsmul_rec z f) = z • f | (int.of_nat n) := by rw [zsmul_rec, int.of_nat_eq_coe, coe_nsmul_rec, coe_nat_zsmul] | -[1+ n] := by rw [zsmul_rec, zsmul_neg_succ_of_nat, coe_neg, coe_nsmul_rec] instance has_int_scalar : has_smul ℤ C₀(α, β) := ⟨λ n f, ⟨n • f, by simpa using zero_at_infty (zsmul_rec n f)⟩⟩ instance : add_group C₀(α, β) := fun_like.coe_injective.add_group _ coe_zero coe_add coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl) end add_group instance [add_comm_group β] [topological_add_group β] : add_comm_group C₀(α, β) := fun_like.coe_injective.add_comm_group _ coe_zero coe_add coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl) instance [has_zero β] {R : Type*} [has_zero R] [smul_with_zero R β] [has_continuous_const_smul R β] : has_smul R C₀(α, β) := ⟨λ r f, ⟨r • f, by simpa [smul_zero] using (zero_at_infty f).const_smul r⟩⟩ @[simp] lemma coe_smul [has_zero β] {R : Type*} [has_zero R] [smul_with_zero R β] [has_continuous_const_smul R β] (r : R) (f : C₀(α, β)) : ⇑(r • f) = r • f := rfl lemma smul_apply [has_zero β] {R : Type*} [has_zero R] [smul_with_zero R β] [has_continuous_const_smul R β] (r : R) (f : C₀(α, β)) (x : α) : (r • f) x = r • f x := rfl instance [has_zero β] {R : Type*} [has_zero R] [smul_with_zero R β] [smul_with_zero Rᵐᵒᵖ β] [has_continuous_const_smul R β] [is_central_scalar R β] : is_central_scalar R C₀(α, β) := ⟨λ r f, ext $ λ x, op_smul_eq_smul _ _⟩ instance [has_zero β] {R : Type*} [has_zero R] [smul_with_zero R β] [has_continuous_const_smul R β] : smul_with_zero R C₀(α, β) := function.injective.smul_with_zero ⟨_, coe_zero⟩ fun_like.coe_injective coe_smul instance [has_zero β] {R : Type*} [monoid_with_zero R] [mul_action_with_zero R β] [has_continuous_const_smul R β] : mul_action_with_zero R C₀(α, β) := function.injective.mul_action_with_zero ⟨_, coe_zero⟩ fun_like.coe_injective coe_smul instance [add_comm_monoid β] [has_continuous_add β] {R : Type*} [semiring R] [module R β] [has_continuous_const_smul R β] : module R C₀(α, β) := function.injective.module R ⟨_, coe_zero, coe_add⟩ fun_like.coe_injective coe_smul instance [non_unital_non_assoc_semiring β] [topological_semiring β] : non_unital_non_assoc_semiring C₀(α, β) := fun_like.coe_injective.non_unital_non_assoc_semiring _ coe_zero coe_add coe_mul (λ _ _, rfl) instance [non_unital_semiring β] [topological_semiring β] : non_unital_semiring C₀(α, β) := fun_like.coe_injective.non_unital_semiring _ coe_zero coe_add coe_mul (λ _ _, rfl) instance [non_unital_comm_semiring β] [topological_semiring β] : non_unital_comm_semiring C₀(α, β) := fun_like.coe_injective.non_unital_comm_semiring _ coe_zero coe_add coe_mul (λ _ _, rfl) instance [non_unital_non_assoc_ring β] [topological_ring β] : non_unital_non_assoc_ring C₀(α, β) := fun_like.coe_injective.non_unital_non_assoc_ring _ coe_zero coe_add coe_mul coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl) instance [non_unital_ring β] [topological_ring β] : non_unital_ring C₀(α, β) := fun_like.coe_injective.non_unital_ring _ coe_zero coe_add coe_mul coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl) instance [non_unital_comm_ring β] [topological_ring β] : non_unital_comm_ring C₀(α, β) := fun_like.coe_injective.non_unital_comm_ring _ coe_zero coe_add coe_mul coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl) instance {R : Type*} [semiring R] [non_unital_non_assoc_semiring β] [topological_semiring β] [module R β] [has_continuous_const_smul R β] [is_scalar_tower R β β] : is_scalar_tower R C₀(α, β) C₀(α, β) := { smul_assoc := λ r f g, begin ext, simp only [smul_eq_mul, coe_mul, coe_smul, pi.mul_apply, pi.smul_apply], rw [←smul_eq_mul, ←smul_eq_mul, smul_assoc], end } instance {R : Type*} [semiring R] [non_unital_non_assoc_semiring β] [topological_semiring β] [module R β] [has_continuous_const_smul R β] [smul_comm_class R β β] : smul_comm_class R C₀(α, β) C₀(α, β) := { smul_comm := λ r f g, begin ext, simp only [smul_eq_mul, coe_smul, coe_mul, pi.smul_apply, pi.mul_apply], rw [←smul_eq_mul, ←smul_eq_mul, smul_comm], end } end algebraic_structure /-! ### Metric structure When `β` is a metric space, then every element of `C₀(α, β)` is bounded, and so there is a natural inclusion map `zero_at_infty_continuous_map.to_bcf : C₀(α, β) → (α →ᵇ β)`. Via this map `C₀(α, β)` inherits a metric as the pullback of the metric on `α →ᵇ β`. Moreover, this map has closed range in `α →ᵇ β` and consequently `C₀(α, β)` is a complete space whenever `β` is complete. -/ section metric open metric set variables [metric_space β] [has_zero β] [zero_at_infty_continuous_map_class F α β] protected lemma bounded (f : F) : ∃ C, ∀ x y : α, dist ((f : α → β) x) (f y) ≤ C := begin obtain ⟨K : set α, hK₁, hK₂⟩ := mem_cocompact.mp (tendsto_def.mp (zero_at_infty (f : F)) _ (closed_ball_mem_nhds (0 : β) zero_lt_one)), obtain ⟨C, hC⟩ := (hK₁.image (map_continuous f)).bounded.subset_ball (0 : β), refine ⟨max C 1 + max C 1, (λ x y, _)⟩, have : ∀ x, f x ∈ closed_ball (0 : β) (max C 1), { intro x, by_cases hx : x ∈ K, { exact (mem_closed_ball.mp $ hC ⟨x, hx, rfl⟩).trans (le_max_left _ _) }, { exact (mem_closed_ball.mp $ mem_preimage.mp (hK₂ hx)).trans (le_max_right _ _) } }, exact (dist_triangle (f x) 0 (f y)).trans (add_le_add (mem_closed_ball.mp $ this x) (mem_closed_ball'.mp $ this y)), end lemma bounded_range (f : C₀(α, β)) : bounded (range f) := bounded_range_iff.2 f.bounded lemma bounded_image (f : C₀(α, β)) (s : set α) : bounded (f '' s) := f.bounded_range.mono $ image_subset_range _ _ @[priority 100] instance : bounded_continuous_map_class F α β := { map_bounded := λ f, zero_at_infty_continuous_map.bounded f } /-- Construct a bounded continuous function from a continuous function vanishing at infinity. -/ @[simps] def to_bcf (f : C₀(α, β)) : α →ᵇ β := ⟨f, map_bounded f⟩ section variables (α) (β) lemma to_bcf_injective : function.injective (to_bcf : C₀(α, β) → α →ᵇ β) := λ f g h, by { ext, simpa only using fun_like.congr_fun h x, } end variables {C : ℝ} {f g : C₀(α, β)} /-- The type of continuous functions vanishing at infinity, with the uniform distance induced by the inclusion `zero_at_infinity_continuous_map.to_bcf`, is a metric space. -/ noncomputable instance : metric_space C₀(α, β) := metric_space.induced _ (to_bcf_injective α β) (by apply_instance) @[simp] lemma dist_to_bcf_eq_dist {f g : C₀(α, β)} : dist f.to_bcf g.to_bcf = dist f g := rfl open bounded_continuous_function /-- Convergence in the metric on `C₀(α, β)` is uniform convergence. -/ lemma tendsto_iff_tendsto_uniformly {ι : Type*} {F : ι → C₀(α, β)} {f : C₀(α, β)} {l : filter ι} : tendsto F l (𝓝 f) ↔ tendsto_uniformly (λ i, F i) f l := by simpa only [metric.tendsto_nhds] using @bounded_continuous_function.tendsto_iff_tendsto_uniformly _ _ _ _ _ (λ i, (F i).to_bcf) f.to_bcf l lemma isometry_to_bcf : isometry (to_bcf : C₀(α, β) → α →ᵇ β) := by tauto lemma closed_range_to_bcf : is_closed (range (to_bcf : C₀(α, β) → α →ᵇ β)) := begin refine is_closed_iff_cluster_pt.mpr (λ f hf, _), rw cluster_pt_principal_iff at hf, have : tendsto f (cocompact α) (𝓝 0), { refine metric.tendsto_nhds.mpr (λ ε hε, _), obtain ⟨_, hg, g, rfl⟩ := hf (ball f (ε / 2)) (ball_mem_nhds f $ half_pos hε), refine (metric.tendsto_nhds.mp (zero_at_infty g) (ε / 2) (half_pos hε)).mp (eventually_of_forall $ λ x hx, _), calc dist (f x) 0 ≤ dist (g.to_bcf x) (f x) + dist (g x) 0 : dist_triangle_left _ _ _ ... < dist g.to_bcf f + ε / 2 : add_lt_add_of_le_of_lt (dist_coe_le_dist x) hx ... < ε : by simpa [add_halves ε] using add_lt_add_right hg (ε / 2) }, exact ⟨⟨f.to_continuous_map, this⟩, by {ext, refl}⟩, end /-- Continuous functions vanishing at infinity taking values in a complete space form a complete space. -/ instance [complete_space β] : complete_space C₀(α, β) := (complete_space_iff_is_complete_range isometry_to_bcf.uniform_inducing).mpr closed_range_to_bcf.is_complete end metric section norm /-! ### Normed space The norm structure on `C₀(α, β)` is the one induced by the inclusion `to_bcf : C₀(α, β) → (α →ᵇ b)`, viewed as an additive monoid homomorphism. Then `C₀(α, β)` is naturally a normed space over a normed field `𝕜` whenever `β` is as well. -/ section normed_space variables [normed_group β] {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] /-- The natural inclusion `to_bcf : C₀(α, β) → (α →ᵇ β)` realized as an additive monoid homomorphism. -/ def to_bcf_add_monoid_hom : C₀(α, β) →+ (α →ᵇ β) := { to_fun := to_bcf, map_zero' := rfl, map_add' := λ x y, rfl } @[simp] lemma coe_to_bcf_add_monoid_hom (f : C₀(α, β)) : (f.to_bcf_add_monoid_hom : α → β) = f := rfl noncomputable instance : normed_group C₀(α, β) := normed_group.induced to_bcf_add_monoid_hom (to_bcf_injective α β) @[simp] lemma norm_to_bcf_eq_norm {f : C₀(α, β)} : ∥f.to_bcf∥ = ∥f∥ := rfl instance : normed_space 𝕜 C₀(α, β) := { norm_smul_le := λ k f, (norm_smul k f.to_bcf).le } end normed_space section normed_ring variables [non_unital_normed_ring β] noncomputable instance : non_unital_normed_ring C₀(α, β) := { norm_mul := λ f g, norm_mul_le f.to_bcf g.to_bcf, ..zero_at_infty_continuous_map.non_unital_ring, ..zero_at_infty_continuous_map.normed_group } end normed_ring end norm section star /-! ### Star structure It is possible to equip `C₀(α, β)` with a pointwise `star` operation whenever there is a continuous `star : β → β` for which `star (0 : β) = 0`. We don't have quite this weak a typeclass, but `star_add_monoid` is close enough. The `star_add_monoid` and `normed_star_group` classes on `C₀(α, β)` are inherited from their counterparts on `α →ᵇ β`. Ultimately, when `β` is a C⋆-ring, then so is `C₀(α, β)`. -/ variables [topological_space β] [add_monoid β] [star_add_monoid β] [has_continuous_star β] instance : has_star C₀(α, β) := { star := λ f, { to_fun := λ x, star (f x), continuous_to_fun := (map_continuous f).star, zero_at_infty' := by simpa only [star_zero] using (continuous_star.tendsto (0 : β)).comp (zero_at_infty f) } } @[simp] lemma coe_star (f : C₀(α, β)) : ⇑(star f) = star f := rfl lemma star_apply (f : C₀(α, β)) (x : α) : (star f) x = star (f x) := rfl instance [has_continuous_add β] : star_add_monoid C₀(α, β) := { star_involutive := λ f, ext $ λ x, star_star (f x), star_add := λ f g, ext $ λ x, star_add (f x) (g x) } end star section normed_star variables [normed_group β] [star_add_monoid β] [normed_star_group β] instance : normed_star_group C₀(α, β) := { norm_star := λ f, (norm_star f.to_bcf : _) } end normed_star section star_module variables {𝕜 : Type*} [has_zero 𝕜] [has_star 𝕜] [add_monoid β] [star_add_monoid β] [topological_space β] [has_continuous_star β] [smul_with_zero 𝕜 β] [has_continuous_const_smul 𝕜 β] [star_module 𝕜 β] instance : star_module 𝕜 C₀(α, β) := { star_smul := λ k f, ext $ λ x, star_smul k (f x) } end star_module section star_ring variables [non_unital_semiring β] [star_ring β] [topological_space β] [has_continuous_star β] [topological_semiring β] instance : star_ring C₀(α, β) := { star_mul := λ f g, ext $ λ x, star_mul (f x) (g x), ..zero_at_infty_continuous_map.star_add_monoid } end star_ring section cstar_ring instance [non_unital_normed_ring β] [star_ring β] [cstar_ring β] : cstar_ring C₀(α, β) := { norm_star_mul_self := λ f, @cstar_ring.norm_star_mul_self _ _ _ _ f.to_bcf } end cstar_ring /-! ### C₀ as a functor For each `β` with sufficient structure, there is a contravariant functor `C₀(-, β)` from the category of topological spaces with morphisms given by `cocompact_map`s. -/ variables {δ : Type*} [topological_space β] [topological_space γ] [topological_space δ] local notation α ` →co ` β := cocompact_map α β section variables [has_zero δ] /-- Composition of a continuous function vanishing at infinity with a cocompact map yields another continuous function vanishing at infinity. -/ def comp (f : C₀(γ, δ)) (g : β →co γ) : C₀(β, δ) := { to_continuous_map := (f : C(γ, δ)).comp g, zero_at_infty' := (zero_at_infty f).comp (cocompact_tendsto g) } @[simp] lemma coe_comp_to_continuous_fun (f : C₀(γ, δ)) (g : β →co γ) : ((f.comp g).to_continuous_map : β → δ) = f ∘ g := rfl @[simp] lemma comp_id (f : C₀(γ, δ)) : f.comp (cocompact_map.id γ) = f := ext (λ x, rfl) @[simp] lemma comp_assoc (f : C₀(γ, δ)) (g : β →co γ) (h : α →co β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma zero_comp (g : β →co γ) : (0 : C₀(γ, δ)).comp g = 0 := rfl end /-- Composition as an additive monoid homomorphism. -/ def comp_add_monoid_hom [add_monoid δ] [has_continuous_add δ] (g : β →co γ) : C₀(γ, δ) →+ C₀(β, δ) := { to_fun := λ f, f.comp g, map_zero' := zero_comp g, map_add' := λ f₁ f₂, rfl } /-- Composition as a semigroup homomorphism. -/ def comp_mul_hom [mul_zero_class δ] [has_continuous_mul δ] (g : β →co γ) : C₀(γ, δ) →ₙ* C₀(β, δ) := { to_fun := λ f, f.comp g, map_mul' := λ f₁ f₂, rfl } /-- Composition as a linear map. -/ def comp_linear_map [add_comm_monoid δ] [has_continuous_add δ] {R : Type*} [semiring R] [module R δ] [has_continuous_const_smul R δ] (g : β →co γ) : C₀(γ, δ) →ₗ[R] C₀(β, δ) := { to_fun := λ f, f.comp g, map_add' := λ f₁ f₂, rfl, map_smul' := λ r f, rfl } /-- Composition as a non-unital algebra homomorphism. -/ def comp_non_unital_alg_hom {R : Type*} [semiring R] [non_unital_non_assoc_semiring δ] [topological_semiring δ] [module R δ] [has_continuous_const_smul R δ] (g : β →co γ) : C₀(γ, δ) →ₙₐ[R] C₀(β, δ) := { to_fun := λ f, f.comp g, map_smul' := λ r f, rfl, map_zero' := rfl, map_add' := λ f₁ f₂, rfl, map_mul' := λ f₁ f₂, rfl } end zero_at_infty_continuous_map
7b358d51f9c4dc81b0ae3bcb64eea77694089cc5
367134ba5a65885e863bdc4507601606690974c1
/src/data/real/ereal.lean
c5590e5b6981cf6c50b9579a316950975a95ed42
[ "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
3,359
lean
/- Copyright (c) 2019 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard -/ import data.real.basic /-! # The extended reals [-∞, ∞]. This file defines `ereal`, the real numbers together with a top and bottom element, referred to as ⊤ and ⊥. It is implemented as `with_top (with_bot ℝ)` Addition and multiplication are problematic in the presence of ±∞, but negation has a natural definition and satisfies the usual properties. An addition is derived, but `ereal` is not even a monoid (there is no identity). `ereal` is a `complete_lattice`; this is now deduced by type class inference from the fact that `with_top (with_bot L)` is a complete lattice if `L` is a conditionally complete lattice. ## Tags real, ereal, complete lattice ## TODO abs : ereal → ℝ≥0∞ In Isabelle they define + - * and / (making junk choices for things like -∞ + ∞) and then prove whatever bits of the ordered ring/field axioms still hold. They also do some limits stuff (liminf/limsup etc). See https://isabelle.in.tum.de/dist/library/HOL/HOL-Library/Extended_Real.html -/ /-- ereal : The type `[-∞, ∞]` -/ @[derive [linear_order, order_bot, order_top, has_Sup, has_Inf, complete_lattice, has_add]] def ereal := with_top (with_bot ℝ) namespace ereal instance : has_coe ℝ ereal := ⟨some ∘ some⟩ @[simp, norm_cast] protected lemma coe_real_le {x y : ℝ} : (x : ereal) ≤ (y : ereal) ↔ x ≤ y := by { unfold_coes, norm_num } @[simp, norm_cast] protected lemma coe_real_lt {x y : ℝ} : (x : ereal) < (y : ereal) ↔ x < y := by { unfold_coes, norm_num } @[simp, norm_cast] protected lemma coe_real_inj' {x y : ℝ} : (x : ereal) = (y : ereal) ↔ x = y := by { unfold_coes, simp [option.some_inj] } instance : has_zero ereal := ⟨(0 : ℝ)⟩ instance : inhabited ereal := ⟨0⟩ /-! ### Negation -/ /-- negation on ereal -/ protected def neg : ereal → ereal | ⊥ := ⊤ | ⊤ := ⊥ | (x : ℝ) := (-x : ℝ) instance : has_neg ereal := ⟨ereal.neg⟩ @[norm_cast] protected lemma neg_def (x : ℝ) : ((-x : ℝ) : ereal) = -x := rfl /-- - -a = a on ereal -/ protected theorem neg_neg : ∀ (a : ereal), - (- a) = a | ⊥ := rfl | ⊤ := rfl | (a : ℝ) := by { norm_cast, simp [neg_neg a] } theorem neg_inj (a b : ereal) (h : -a = -b) : a = b := by rw [←ereal.neg_neg a, h, ereal.neg_neg b] /-- Even though ereal is not an additive group, -a = b ↔ -b = a still holds -/ theorem neg_eq_iff_neg_eq {a b : ereal} : -a = b ↔ -b = a := ⟨by {intro h, rw ←h, exact ereal.neg_neg a}, by {intro h, rw ←h, exact ereal.neg_neg b}⟩ /-- if -a ≤ b then -b ≤ a on ereal -/ protected theorem neg_le_of_neg_le : ∀ {a b : ereal} (h : -a ≤ b), -b ≤ a | ⊥ ⊥ h := h | ⊥ (some b) h := by cases (top_le_iff.1 h) | ⊤ l h := le_top | (a : ℝ) ⊥ h := by cases (le_bot_iff.1 h) | l ⊤ h := bot_le | (a : ℝ) (b : ℝ) h := by { norm_cast at h ⊢, exact _root_.neg_le_of_neg_le h } /-- -a ≤ b ↔ -b ≤ a on ereal-/ protected theorem neg_le {a b : ereal} : -a ≤ b ↔ -b ≤ a := ⟨ereal.neg_le_of_neg_le, ereal.neg_le_of_neg_le⟩ /-- a ≤ -b → b ≤ -a on ereal -/ theorem le_neg_of_le_neg {a b : ereal} (h : a ≤ -b) : b ≤ -a := by rwa [←ereal.neg_neg b, ereal.neg_le, ereal.neg_neg] end ereal
5e24d50e272816649433e7f0718cd11b7211f896
82e44445c70db0f03e30d7be725775f122d72f3e
/src/linear_algebra/determinant.lean
04bcc4513a14d4c3b46dcab3cabe5dad51d1c952
[ "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
12,417
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Patrick Massot, Casper Putz, Anne Baanen -/ import linear_algebra.free_module_pid import linear_algebra.matrix.basis import linear_algebra.matrix.diagonal import linear_algebra.matrix.to_linear_equiv import linear_algebra.matrix.reindex import linear_algebra.multilinear import linear_algebra.dual import ring_theory.algebra_tower /-! # Determinant of families of vectors This file defines the determinant of an endomorphism, and of a family of vectors with respect to some basis. For the determinant of a matrix, see the file `linear_algebra.matrix.determinant`. ## Main definitions In the list below, and in all this file, `R` is a commutative ring (semiring is sometimes enough), `M` and its variations are `R`-modules, `ι`, `κ`, `n` and `m` are finite types used for indexing. * `basis.det`: the determinant of a family of vectors with respect to a basis, as a multilinear map * `linear_map.det`: the determinant of an endomorphism `f : End R M` as a multiplicative homomorphism (if `M` does not have a finite `R`-basis, the result is `1` instead) ## Tags basis, det, determinant -/ noncomputable theory open_locale big_operators open_locale matrix open linear_map open submodule universes u v w open linear_map matrix variables {R : Type*} [comm_ring R] variables {M : Type*} [add_comm_group M] [module R M] variables {M' : Type*} [add_comm_group M'] [module R M'] variables {ι : Type*} [decidable_eq ι] [fintype ι] variables (e : basis ι R M) section conjugate variables {A : Type*} [integral_domain A] variables {m n : Type*} [fintype m] [fintype n] /-- If `R^m` and `R^n` are linearly equivalent, then `m` and `n` are also equivalent. -/ def equiv_of_pi_lequiv_pi {R : Type*} [integral_domain R] (e : (m → R) ≃ₗ[R] (n → R)) : m ≃ n := basis.index_equiv (basis.of_equiv_fun e.symm) (pi.basis_fun _ _) /-- If `M` and `M'` are each other's inverse matrices, they are square matrices up to equivalence of types. -/ def matrix.index_equiv_of_inv [decidable_eq m] [decidable_eq n] {M : matrix m n A} {M' : matrix n m A} (hMM' : M ⬝ M' = 1) (hM'M : M' ⬝ M = 1) : m ≃ n := equiv_of_pi_lequiv_pi (matrix.to_lin'_of_inv hMM' hM'M) /-- If `M'` is a two-sided inverse for `M` (indexed differently), `det (M ⬝ N ⬝ M') = det N`. -/ lemma matrix.det_conj [decidable_eq m] [decidable_eq n] {M : matrix m n A} {M' : matrix n m A} {N : matrix n n A} (hMM' : M ⬝ M' = 1) (hM'M : M' ⬝ M = 1) : det (M ⬝ N ⬝ M') = det N := begin -- Although `m` and `n` are different a priori, we will show they have the same cardinality. -- This turns the problem into one for square matrices (`matrix.det_units_conj`), which is easy. let e : m ≃ n := matrix.index_equiv_of_inv hMM' hM'M, let U : units (matrix n n A) := ⟨M.minor e.symm (equiv.refl _), M'.minor (equiv.refl _) e.symm, by rw [mul_eq_mul, ←minor_mul_equiv, hMM', minor_one_equiv], by rw [mul_eq_mul, ←minor_mul_equiv, hM'M, minor_one_equiv]⟩, rw [← matrix.det_units_conj U N, ← det_minor_equiv_self e.symm], simp only [minor_mul_equiv _ _ _ (equiv.refl n) _, equiv.coe_refl, minor_id_id, units.coe_mk, units.inv_mk] end end conjugate namespace linear_map /-! ### Determinant of a linear map -/ variables {A : Type*} [integral_domain A] [module A M] variables {κ : Type*} [fintype κ] /-- The determinant of `linear_map.to_matrix` does not depend on the choice of basis. -/ lemma det_to_matrix_eq_det_to_matrix [decidable_eq κ] (b : basis ι A M) (c : basis κ A M) (f : M →ₗ[A] M) : det (linear_map.to_matrix b b f) = det (linear_map.to_matrix c c f) := by rw [← linear_map_to_matrix_mul_basis_to_matrix c b c, ← basis_to_matrix_mul_linear_map_to_matrix b c b, matrix.det_conj]; rw [basis.to_matrix_mul_to_matrix, basis.to_matrix_self] /-- The determinant of an endomorphism given a basis. See `linear_map.det` for a version that populates the basis non-computably. Although the `trunc (basis ι A M)` parameter makes it slightly more convenient to switch bases, there is no good way to generalize over universe parameters, so we can't fully state in `det_aux`'s type that it does not depend on the choice of basis. Instead you can use the `det_aux_def'` lemma, or avoid mentioning a basis at all using `linear_map.det`. -/ def det_aux : trunc (basis ι A M) → (M →ₗ[A] M) →* A := trunc.lift (λ b : basis ι A M, (det_monoid_hom).comp (to_matrix_alg_equiv b : (M →ₗ[A] M) →* matrix ι ι A)) (λ b c, monoid_hom.ext $ det_to_matrix_eq_det_to_matrix b c) /-- Unfold lemma for `det_aux`. See also `det_aux_def'` which allows you to vary the basis. -/ lemma det_aux_def (b : basis ι A M) (f : M →ₗ[A] M) : linear_map.det_aux (trunc.mk b) f = matrix.det (linear_map.to_matrix b b f) := rfl -- Discourage the elaborator from unfolding `det_aux` and producing a huge term. attribute [irreducible] linear_map.det_aux lemma det_aux_def' {ι' : Type*} [fintype ι'] [decidable_eq ι'] (tb : trunc $ basis ι A M) (b' : basis ι' A M) (f : M →ₗ[A] M) : linear_map.det_aux tb f = matrix.det (linear_map.to_matrix b' b' f) := by { apply trunc.induction_on tb, intro b, rw [det_aux_def, det_to_matrix_eq_det_to_matrix b b'] } @[simp] lemma det_aux_id (b : trunc $ basis ι A M) : linear_map.det_aux b (linear_map.id) = 1 := (linear_map.det_aux b).map_one @[simp] lemma det_aux_comp (b : trunc $ basis ι A M) (f g : M →ₗ[A] M) : linear_map.det_aux b (f.comp g) = linear_map.det_aux b f * linear_map.det_aux b g := (linear_map.det_aux b).map_mul f g section open_locale classical /-- The determinant of an endomorphism independent of basis. If there is no finite basis on `M`, the result is `1` instead. -/ protected def det : (M →ₗ[A] M) →* A := if H : ∃ (s : finset M), nonempty (basis s A M) then linear_map.det_aux (trunc.mk H.some_spec.some) else 1 lemma coe_det [decidable_eq M] : ⇑(linear_map.det : (M →ₗ[A] M) →* A) = if H : ∃ (s : finset M), nonempty (basis s A M) then linear_map.det_aux (trunc.mk H.some_spec.some) else 1 := by { ext, unfold linear_map.det, split_ifs, { congr }, -- use the correct `decidable_eq` instance refl } end -- Discourage the elaborator from unfolding `det` and producing a huge term. attribute [irreducible] linear_map.det -- Auxiliary lemma, the `simp` normal form goes in the other direction -- (using `linear_map.det_to_matrix`) lemma det_eq_det_to_matrix_of_finset [decidable_eq M] {s : finset M} (b : basis s A M) (f : M →ₗ[A] M) : f.det = matrix.det (linear_map.to_matrix b b f) := have ∃ (s : finset M), nonempty (basis s A M), from ⟨s, ⟨b⟩⟩, by rw [linear_map.coe_det, dif_pos, det_aux_def' _ b]; assumption @[simp] lemma det_to_matrix (b : basis ι A M) (f : M →ₗ[A] M) : matrix.det (to_matrix b b f) = f.det := by { haveI := classical.dec_eq M, rw [det_eq_det_to_matrix_of_finset b.reindex_finset_range, det_to_matrix_eq_det_to_matrix b] } /-- To show `P f.det` it suffices to consider `P (to_matrix _ _ f).det` and `P 1`. -/ @[elab_as_eliminator] lemma det_cases [decidable_eq M] {P : A → Prop} (f : M →ₗ[A] M) (hb : ∀ (s : finset M) (b : basis s A M), P (to_matrix b b f).det) (h1 : P 1) : P f.det := begin unfold linear_map.det, split_ifs with h, { convert hb _ h.some_spec.some, apply det_aux_def' }, { exact h1 } end @[simp] lemma det_comp (f g : M →ₗ[A] M) : (f.comp g).det = f.det * g.det := linear_map.det.map_mul f g @[simp] lemma det_id : (linear_map.id : M →ₗ[A] M).det = 1 := linear_map.det.map_one lemma det_zero {ι : Type*} [fintype ι] [nonempty ι] (b : basis ι A M) : linear_map.det (0 : M →ₗ[A] M) = 0 := by { haveI := classical.dec_eq ι, rw [← det_to_matrix b, linear_equiv.map_zero, det_zero], assumption } end linear_map -- Cannot be stated using `linear_map.det` because `f` is not an endomorphism. lemma linear_equiv.is_unit_det (f : M ≃ₗ[R] M') (v : basis ι R M) (v' : basis ι R M') : is_unit (linear_map.to_matrix v v' f).det := begin apply is_unit_det_of_left_inverse, simpa using (linear_map.to_matrix_comp v v' v f.symm f).symm end /-- Specialization of `linear_equiv.is_unit_det` -/ lemma linear_equiv.is_unit_det' {A : Type*} [integral_domain A] [module A M] (f : M ≃ₗ[A] M) : is_unit (linear_map.det (f : M →ₗ[A] M)) := by haveI := classical.dec_eq M; exact (f : M →ₗ[A] M).det_cases (λ s b, f.is_unit_det _ _) is_unit_one /-- Builds a linear equivalence from a linear map whose determinant in some bases is a unit. -/ @[simps] def linear_equiv.of_is_unit_det {f : M →ₗ[R] M'} {v : basis ι R M} {v' : basis ι R M'} (h : is_unit (linear_map.to_matrix v v' f).det) : M ≃ₗ[R] M' := { to_fun := f, map_add' := f.map_add, map_smul' := f.map_smul, inv_fun := to_lin v' v (to_matrix v v' f)⁻¹, left_inv := λ x, calc to_lin v' v (to_matrix v v' f)⁻¹ (f x) = to_lin v v ((to_matrix v v' f)⁻¹ ⬝ to_matrix v v' f) x : by { rw [to_lin_mul v v' v, to_lin_to_matrix, linear_map.comp_apply] } ... = x : by simp [h], right_inv := λ x, calc f (to_lin v' v (to_matrix v v' f)⁻¹ x) = to_lin v' v' (to_matrix v v' f ⬝ (to_matrix v v' f)⁻¹) x : by { rw [to_lin_mul v' v v', linear_map.comp_apply, to_lin_to_matrix v v'] } ... = x : by simp [h] } /-- The determinant of a family of vectors with respect to some basis, as an alternating multilinear map. -/ def basis.det : alternating_map R M R ι := { to_fun := λ v, det (e.to_matrix v), map_add' := begin intros v i x y, simp only [e.to_matrix_update, linear_equiv.map_add], apply det_update_column_add end, map_smul' := begin intros u i c x, simp only [e.to_matrix_update, algebra.id.smul_eq_mul, linear_equiv.map_smul], apply det_update_column_smul end, map_eq_zero_of_eq' := begin intros v i j h hij, rw [←function.update_eq_self i v, h, ←det_transpose, e.to_matrix_update, ←update_row_transpose, ←e.to_matrix_transpose_apply], apply det_zero_of_row_eq hij, rw [update_row_ne hij.symm, update_row_self], end } lemma basis.det_apply (v : ι → M) : e.det v = det (e.to_matrix v) := rfl lemma basis.det_self : e.det e = 1 := by simp [e.det_apply] lemma is_basis_iff_det {v : ι → M} : linear_independent R v ∧ span R (set.range v) = ⊤ ↔ is_unit (e.det v) := begin split, { rintro ⟨hli, hspan⟩, set v' := basis.mk hli hspan with v'_eq, rw e.det_apply, convert linear_equiv.is_unit_det (linear_equiv.refl _ _) v' e using 2, ext i j, simp }, { intro h, rw [basis.det_apply, basis.to_matrix_eq_to_matrix_constr] at h, set v' := basis.map e (linear_equiv.of_is_unit_det h) with v'_def, have : ⇑ v' = v, { ext i, rw [v'_def, basis.map_apply, linear_equiv.of_is_unit_det_apply, e.constr_basis] }, rw ← this, exact ⟨v'.linear_independent, v'.span_eq⟩ }, end lemma basis.is_unit_det (e' : basis ι R M) : is_unit (e.det e') := (is_basis_iff_det e).mp ⟨e'.linear_independent, e'.span_eq⟩ variables {A : Type*} [integral_domain A] [module A M] @[simp] lemma basis.det_comp (e : basis ι A M) (f : M →ₗ[A] M) (v : ι → M) : e.det (f ∘ v) = f.det * e.det v := by { rw [basis.det_apply, basis.det_apply, ← f.det_to_matrix e, ← matrix.det_mul, e.to_matrix_eq_to_matrix_constr (f ∘ v), e.to_matrix_eq_to_matrix_constr v, ← to_matrix_comp, e.constr_comp] } lemma basis.det_reindex {ι' : Type*} [fintype ι'] [decidable_eq ι'] (b : basis ι R M) (v : ι' → M) (e : ι ≃ ι') : (b.reindex e).det v = b.det (v ∘ e) := by rw [basis.det_apply, basis.to_matrix_reindex', det_reindex_alg_equiv, basis.det_apply] lemma basis.det_reindex_symm {ι' : Type*} [fintype ι'] [decidable_eq ι'] (b : basis ι R M) (v : ι → M) (e : ι' ≃ ι) : (b.reindex e.symm).det (v ∘ e) = b.det v := by rw [basis.det_reindex, function.comp.assoc, e.self_comp_symm, function.comp.right_id] @[simp] lemma basis.det_map (b : basis ι R M) (f : M ≃ₗ[R] M') (v : ι → M') : (b.map f).det v = b.det (f.symm ∘ v) := by { rw [basis.det_apply, basis.to_matrix_map, basis.det_apply] }
dbcae0b7d4cf2d7b06d3f0b0854caff33d68e0ec
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/topology/metric_space/gromov_hausdorff_realized.lean
8d4e36ff93b81faa87e9f187f93769f832f411f7
[ "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
26,254
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 Construction of a good coupling between nonempty compact metric spaces, minimizing their Hausdorff distance. This construction is instrumental to study the Gromov-Hausdorff distance between nonempty compact metric spaces -/ import topology.metric_space.gluing import topology.metric_space.hausdorff_distance import topology.continuous_function.bounded noncomputable theory open_locale classical topological_space nnreal universes u v w open classical set function topological_space filter metric quotient open bounded_continuous_function open sum (inl inr) local attribute [instance] metric_space_sum namespace Gromov_Hausdorff section Gromov_Hausdorff_realized /- This section shows that the Gromov-Hausdorff distance is realized. For this, we consider candidate distances on the disjoint union α ⊕ β of two compact nonempty metric spaces, almost realizing the Gromov-Hausdorff distance, and show that they form a compact family by applying Arzela-Ascoli theorem. The existence of a minimizer follows. -/ section definitions variables (α : Type u) (β : Type v) [metric_space α] [compact_space α] [nonempty α] [metric_space β] [compact_space β] [nonempty β] @[reducible] private def prod_space_fun : Type* := ((α ⊕ β) × (α ⊕ β)) → ℝ @[reducible] private def Cb : Type* := bounded_continuous_function ((α ⊕ β) × (α ⊕ β)) ℝ private def max_var : ℝ≥0 := 2 * ⟨diam (univ : set α), diam_nonneg⟩ + 1 + 2 * ⟨diam (univ : set β), diam_nonneg⟩ private lemma one_le_max_var : 1 ≤ max_var α β := calc (1 : real) = 2 * 0 + 1 + 2 * 0 : by simp ... ≤ 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β) : by apply_rules [add_le_add, mul_le_mul_of_nonneg_left, diam_nonneg]; norm_num /-- The set of functions on α ⊕ β that are candidates distances to realize the minimum of the Hausdorff distances between α and β in a coupling -/ def candidates : set (prod_space_fun α β) := {f | (((((∀x y : α, f (sum.inl x, sum.inl y) = dist x y) ∧ (∀x y : β, f (sum.inr x, sum.inr y) = dist x y)) ∧ (∀x y, f (x, y) = f (y, x))) ∧ (∀x y z, f (x, z) ≤ f (x, y) + f (y, z))) ∧ (∀x, f (x, x) = 0)) ∧ (∀x y, f (x, y) ≤ max_var α β) } /-- Version of the set of candidates in bounded_continuous_functions, to apply Arzela-Ascoli -/ private def candidates_b : set (Cb α β) := {f : Cb α β | f.to_fun ∈ candidates α β} end definitions --section section constructions variables {α : Type u} {β : Type v} [metric_space α] [compact_space α] [nonempty α] [metric_space β] [compact_space β] [nonempty β] {f : prod_space_fun α β} {x y z t : α ⊕ β} local attribute [instance, priority 10] inhabited_of_nonempty' private lemma max_var_bound : dist x y ≤ max_var α β := calc dist x y ≤ diam (univ : set (α ⊕ β)) : dist_le_diam_of_mem (bounded_of_compact compact_univ) (mem_univ _) (mem_univ _) ... = diam (inl '' (univ : set α) ∪ inr '' (univ : set β)) : by apply congr_arg; ext x y z; cases x; simp [mem_univ, mem_range_self] ... ≤ diam (inl '' (univ : set α)) + dist (inl (default α)) (inr (default β)) + diam (inr '' (univ : set β)) : diam_union (mem_image_of_mem _ (mem_univ _)) (mem_image_of_mem _ (mem_univ _)) ... = diam (univ : set α) + (dist (default α) (default α) + 1 + dist (default β) (default β)) + diam (univ : set β) : by { rw [isometry_on_inl.diam_image, isometry_on_inr.diam_image], refl } ... = 1 * diam (univ : set α) + 1 + 1 * diam (univ : set β) : by simp ... ≤ 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β) : begin apply_rules [add_le_add, mul_le_mul_of_nonneg_right, diam_nonneg, le_refl], norm_num, norm_num end private lemma candidates_symm (fA : f ∈ candidates α β) : f (x, y) = f (y ,x) := fA.1.1.1.2 x y private lemma candidates_triangle (fA : f ∈ candidates α β) : f (x, z) ≤ f (x, y) + f (y, z) := fA.1.1.2 x y z private lemma candidates_refl (fA : f ∈ candidates α β) : f (x, x) = 0 := fA.1.2 x private lemma candidates_nonneg (fA : f ∈ candidates α β) : 0 ≤ f (x, y) := begin have : 0 ≤ 2 * f (x, y) := calc 0 = f (x, x) : (candidates_refl fA).symm ... ≤ f (x, y) + f (y, x) : candidates_triangle fA ... = f (x, y) + f (x, y) : by rw [candidates_symm fA] ... = 2 * f (x, y) : by ring, by linarith end private lemma candidates_dist_inl (fA : f ∈ candidates α β) (x y: α) : f (inl x, inl y) = dist x y := fA.1.1.1.1.1 x y private lemma candidates_dist_inr (fA : f ∈ candidates α β) (x y : β) : f (inr x, inr y) = dist x y := fA.1.1.1.1.2 x y private lemma candidates_le_max_var (fA : f ∈ candidates α β) : f (x, y) ≤ max_var α β := fA.2 x y /-- candidates are bounded by max_var α β -/ private lemma candidates_dist_bound (fA : f ∈ candidates α β) : ∀ {x y : α ⊕ β}, f (x, y) ≤ max_var α β * dist x y | (inl x) (inl y) := calc f (inl x, inl y) = dist x y : candidates_dist_inl fA x y ... = dist (inl x) (inl y) : by { rw @sum.dist_eq α β, refl } ... = 1 * dist (inl x) (inl y) : by simp ... ≤ max_var α β * dist (inl x) (inl y) : mul_le_mul_of_nonneg_right (one_le_max_var α β) dist_nonneg | (inl x) (inr y) := calc f (inl x, inr y) ≤ max_var α β : candidates_le_max_var fA ... = max_var α β * 1 : by simp ... ≤ max_var α β * dist (inl x) (inr y) : mul_le_mul_of_nonneg_left sum.one_dist_le (le_trans (zero_le_one) (one_le_max_var α β)) | (inr x) (inl y) := calc f (inr x, inl y) ≤ max_var α β : candidates_le_max_var fA ... = max_var α β * 1 : by simp ... ≤ max_var α β * dist (inl x) (inr y) : mul_le_mul_of_nonneg_left sum.one_dist_le (le_trans (zero_le_one) (one_le_max_var α β)) | (inr x) (inr y) := calc f (inr x, inr y) = dist x y : candidates_dist_inr fA x y ... = dist (inr x) (inr y) : by { rw @sum.dist_eq α β, refl } ... = 1 * dist (inr x) (inr y) : by simp ... ≤ max_var α β * dist (inr x) (inr y) : mul_le_mul_of_nonneg_right (one_le_max_var α β) dist_nonneg /-- Technical lemma to prove that candidates are Lipschitz -/ private lemma candidates_lipschitz_aux (fA : f ∈ candidates α β) : f (x, y) - f (z, t) ≤ 2 * max_var α β * dist (x, y) (z, t) := calc f (x, y) - f(z, t) ≤ f (x, t) + f (t, y) - f (z, t) : sub_le_sub_right (candidates_triangle fA) _ ... ≤ (f (x, z) + f (z, t) + f(t, y)) - f (z, t) : sub_le_sub_right (add_le_add_right (candidates_triangle fA) _ ) _ ... = f (x, z) + f (t, y) : by simp [sub_eq_add_neg, add_assoc] ... ≤ max_var α β * dist x z + max_var α β * dist t y : add_le_add (candidates_dist_bound fA) (candidates_dist_bound fA) ... ≤ max_var α β * max (dist x z) (dist t y) + max_var α β * max (dist x z) (dist t y) : begin apply add_le_add, apply mul_le_mul_of_nonneg_left (le_max_left (dist x z) (dist t y)) (zero_le_one.trans (one_le_max_var α β)), apply mul_le_mul_of_nonneg_left (le_max_right (dist x z) (dist t y)) (zero_le_one.trans (one_le_max_var α β)), end ... = 2 * max_var α β * max (dist x z) (dist y t) : by { simp [dist_comm], ring } ... = 2 * max_var α β * dist (x, y) (z, t) : by refl /-- Candidates are Lipschitz -/ private lemma candidates_lipschitz (fA : f ∈ candidates α β) : lipschitz_with (2 * max_var α β) f := begin apply lipschitz_with.of_dist_le_mul, rintros ⟨x, y⟩ ⟨z, t⟩, rw [real.dist_eq, abs_sub_le_iff], use candidates_lipschitz_aux fA, rw [dist_comm], exact candidates_lipschitz_aux fA end /-- candidates give rise to elements of bounded_continuous_functions -/ def candidates_b_of_candidates (f : prod_space_fun α β) (fA : f ∈ candidates α β) : Cb α β := bounded_continuous_function.mk_of_compact ⟨f, (candidates_lipschitz fA).continuous⟩ lemma candidates_b_of_candidates_mem (f : prod_space_fun α β) (fA : f ∈ candidates α β) : candidates_b_of_candidates f fA ∈ candidates_b α β := fA /-- The distance on α ⊕ β is a candidate -/ private lemma dist_mem_candidates : (λp : (α ⊕ β) × (α ⊕ β), dist p.1 p.2) ∈ candidates α β := begin simp only [candidates, dist_comm, forall_const, and_true, add_comm, eq_self_iff_true, and_self, sum.forall, set.mem_set_of_eq, dist_self], repeat { split <|> exact (λa y z, dist_triangle_left _ _ _) <|> exact (λx y, by refl) <|> exact (λx y, max_var_bound) } end def candidates_b_dist (α : Type u) (β : Type v) [metric_space α] [compact_space α] [inhabited α] [metric_space β] [compact_space β] [inhabited β] : Cb α β := candidates_b_of_candidates _ dist_mem_candidates lemma candidates_b_dist_mem_candidates_b : candidates_b_dist α β ∈ candidates_b α β := candidates_b_of_candidates_mem _ _ private lemma candidates_b_nonempty : (candidates_b α β).nonempty := ⟨_, candidates_b_dist_mem_candidates_b⟩ /-- To apply Arzela-Ascoli, we need to check that the set of candidates is closed and equicontinuous. Equicontinuity follows from the Lipschitz control, we check closedness. -/ private lemma closed_candidates_b : is_closed (candidates_b α β) := begin have I1 : ∀x y, is_closed {f : Cb α β | f (inl x, inl y) = dist x y} := λx y, is_closed_eq continuous_evalx continuous_const, have I2 : ∀x y, is_closed {f : Cb α β | f (inr x, inr y) = dist x y } := λx y, is_closed_eq continuous_evalx continuous_const, have I3 : ∀x y, is_closed {f : Cb α β | f (x, y) = f (y, x)} := λx y, is_closed_eq continuous_evalx continuous_evalx, have I4 : ∀x y z, is_closed {f : Cb α β | f (x, z) ≤ f (x, y) + f (y, z)} := λx y z, is_closed_le continuous_evalx (continuous_evalx.add continuous_evalx), have I5 : ∀x, is_closed {f : Cb α β | f (x, x) = 0} := λx, is_closed_eq continuous_evalx continuous_const, have I6 : ∀x y, is_closed {f : Cb α β | f (x, y) ≤ max_var α β} := λx y, is_closed_le continuous_evalx continuous_const, have : candidates_b α β = (⋂x y, {f : Cb α β | f ((@inl α β x), (@inl α β y)) = dist x y}) ∩ (⋂x y, {f : Cb α β | f ((@inr α β x), (@inr α β y)) = dist x y}) ∩ (⋂x y, {f : Cb α β | f (x, y) = f (y, x)}) ∩ (⋂x y z, {f : Cb α β | f (x, z) ≤ f (x, y) + f (y, z)}) ∩ (⋂x, {f : Cb α β | f (x, x) = 0}) ∩ (⋂x y, {f : Cb α β | f (x, y) ≤ max_var α β}) := begin ext, unfold candidates_b, unfold candidates, simp [-sum.forall], refl end, rw this, repeat { apply is_closed_inter _ _ <|> apply is_closed_Inter _ <|> apply I1 _ _ <|> apply I2 _ _ <|> apply I3 _ _ <|> apply I4 _ _ _ <|> apply I5 _ <|> apply I6 _ _ <|> assume x }, end /-- Compactness of candidates (in bounded_continuous_functions) follows. -/ private lemma compact_candidates_b : is_compact (candidates_b α β) := begin refine arzela_ascoli₂ (Icc 0 (max_var α β)) compact_Icc (candidates_b α β) closed_candidates_b _ _, { rintros f ⟨x1, x2⟩ hf, simp only [set.mem_Icc], exact ⟨candidates_nonneg hf, candidates_le_max_var hf⟩ }, { refine equicontinuous_of_continuity_modulus (λt, 2 * max_var α β * t) _ _ _, { have : tendsto (λ (t : ℝ), 2 * (max_var α β : ℝ) * t) (𝓝 0) (𝓝 (2 * max_var α β * 0)) := tendsto_const_nhds.mul tendsto_id, simpa using this }, { assume x y f hf, exact (candidates_lipschitz hf).dist_le_mul _ _ } } end /-- We will then choose the candidate minimizing the Hausdorff distance. Except that we are not in a metric space setting, so we need to define our custom version of Hausdorff distance, called HD, and prove its basic properties. -/ def HD (f : Cb α β) := max (⨆ x, ⨅ y, f (inl x, inr y)) (⨆ y, ⨅ x, f (inl x, inr y)) /- We will show that HD is continuous on bounded_continuous_functions, to deduce that its minimum on the compact set candidates_b is attained. Since it is defined in terms of infimum and supremum on ℝ, which is only conditionnally complete, we will need all the time to check that the defining sets are bounded below or above. This is done in the next few technical lemmas -/ lemma HD_below_aux1 {f : Cb α β} (C : ℝ) {x : α} : bdd_below (range (λ (y : β), f (inl x, inr y) + C)) := let ⟨cf, hcf⟩ := (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 in ⟨cf + C, forall_range_iff.2 (λi, add_le_add_right ((λx, hcf (mem_range_self x)) _) _)⟩ private lemma HD_bound_aux1 (f : Cb α β) (C : ℝ) : bdd_above (range (λ (x : α), ⨅ y, f (inl x, inr y) + C)) := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).2 with ⟨Cf, hCf⟩, refine ⟨Cf + C, forall_range_iff.2 (λx, _)⟩, calc (⨅ y, f (inl x, inr y) + C) ≤ f (inl x, inr (default β)) + C : cinfi_le (HD_below_aux1 C) (default β) ... ≤ Cf + C : add_le_add ((λx, hCf (mem_range_self x)) _) (le_refl _) end lemma HD_below_aux2 {f : Cb α β} (C : ℝ) {y : β} : bdd_below (range (λ (x : α), f (inl x, inr y) + C)) := let ⟨cf, hcf⟩ := (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 in ⟨cf + C, forall_range_iff.2 (λi, add_le_add_right ((λx, hcf (mem_range_self x)) _) _)⟩ private lemma HD_bound_aux2 (f : Cb α β) (C : ℝ) : bdd_above (range (λ (y : β), ⨅ x, f (inl x, inr y) + C)) := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).2 with ⟨Cf, hCf⟩, refine ⟨Cf + C, forall_range_iff.2 (λy, _)⟩, calc (⨅ x, f (inl x, inr y) + C) ≤ f (inl (default α), inr y) + C : cinfi_le (HD_below_aux2 C) (default α) ... ≤ Cf + C : add_le_add ((λx, hCf (mem_range_self x)) _) (le_refl _) end /-- Explicit bound on HD (dist). This means that when looking for minimizers it will be sufficient to look for functions with HD(f) bounded by this bound. -/ lemma HD_candidates_b_dist_le : HD (candidates_b_dist α β) ≤ diam (univ : set α) + 1 + diam (univ : set β) := begin refine max_le (csupr_le (λx, _)) (csupr_le (λy, _)), { have A : (⨅ y, candidates_b_dist α β (inl x, inr y)) ≤ candidates_b_dist α β (inl x, inr (default β)) := cinfi_le (by simpa using HD_below_aux1 0) (default β), have B : dist (inl x) (inr (default β)) ≤ diam (univ : set α) + 1 + diam (univ : set β) := calc dist (inl x) (inr (default β)) = dist x (default α) + 1 + dist (default β) (default β) : rfl ... ≤ diam (univ : set α) + 1 + diam (univ : set β) : begin apply add_le_add (add_le_add _ (le_refl _)), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _) end, exact le_trans A B }, { have A : (⨅ x, candidates_b_dist α β (inl x, inr y)) ≤ candidates_b_dist α β (inl (default α), inr y) := cinfi_le (by simpa using HD_below_aux2 0) (default α), have B : dist (inl (default α)) (inr y) ≤ diam (univ : set α) + 1 + diam (univ : set β) := calc dist (inl (default α)) (inr y) = dist (default α) (default α) + 1 + dist (default β) y : rfl ... ≤ diam (univ : set α) + 1 + diam (univ : set β) : begin apply add_le_add (add_le_add _ (le_refl _)), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _) end, exact le_trans A B }, end /- To check that HD is continuous, we check that it is Lipschitz. As HD is a max, we prove separately inequalities controlling the two terms (relying too heavily on copy-paste...) -/ private lemma HD_lipschitz_aux1 (f g : Cb α β) : (⨆ x, ⨅ y, f (inl x, inr y)) ≤ (⨆ x, ⨅ y, g (inl x, inr y)) + dist f g := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cg, hcg⟩, have Hcg : ∀x, cg ≤ g x := λx, hcg (mem_range_self x), rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cf, hcf⟩, have Hcf : ∀x, cf ≤ f x := λx, hcf (mem_range_self x), -- prove the inequality but with `dist f g` inside, by using inequalities comparing -- supr to supr and infi to infi have Z : (⨆ x, ⨅ y, f (inl x, inr y)) ≤ ⨆ x, ⨅ y, g (inl x, inr y) + dist f g := csupr_le_csupr (HD_bound_aux1 _ (dist f g)) (λx, cinfi_le_cinfi ⟨cf, forall_range_iff.2(λi, Hcf _)⟩ (λy, coe_le_coe_add_dist)), -- move the `dist f g` out of the infimum and the supremum, arguing that continuous monotone maps -- (here the addition of `dist f g`) preserve infimum and supremum have E1 : ∀x, (⨅ y, g (inl x, inr y)) + dist f g = ⨅ y, g (inl x, inr y) + dist f g, { assume x, refine map_cinfi_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { show bdd_below (range (λ (y : β), g (inl x, inr y))), from ⟨cg, forall_range_iff.2(λi, Hcg _)⟩ } }, have E2 : (⨆ x, ⨅ y, g (inl x, inr y)) + dist f g = ⨆ x, (⨅ y, g (inl x, inr y)) + dist f g, { refine map_csupr_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { by simpa using HD_bound_aux1 _ 0 } }, -- deduce the result from the above two steps simpa [E2, E1, function.comp] end private lemma HD_lipschitz_aux2 (f g : Cb α β) : (⨆ y, ⨅ x, f (inl x, inr y)) ≤ (⨆ y, ⨅ x, g (inl x, inr y)) + dist f g := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cg, hcg⟩, have Hcg : ∀x, cg ≤ g x := λx, hcg (mem_range_self x), rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cf, hcf⟩, have Hcf : ∀x, cf ≤ f x := λx, hcf (mem_range_self x), -- prove the inequality but with `dist f g` inside, by using inequalities comparing -- supr to supr and infi to infi have Z : (⨆ y, ⨅ x, f (inl x, inr y)) ≤ ⨆ y, ⨅ x, g (inl x, inr y) + dist f g := csupr_le_csupr (HD_bound_aux2 _ (dist f g)) (λy, cinfi_le_cinfi ⟨cf, forall_range_iff.2(λi, Hcf _)⟩ (λy, coe_le_coe_add_dist)), -- move the `dist f g` out of the infimum and the supremum, arguing that continuous monotone maps -- (here the addition of `dist f g`) preserve infimum and supremum have E1 : ∀y, (⨅ x, g (inl x, inr y)) + dist f g = ⨅ x, g (inl x, inr y) + dist f g, { assume y, refine map_cinfi_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { show bdd_below (range (λx:α, g (inl x, inr y))), from ⟨cg, forall_range_iff.2 (λi, Hcg _)⟩ } }, have E2 : (⨆ y, ⨅ x, g (inl x, inr y)) + dist f g = ⨆ y, (⨅ x, g (inl x, inr y)) + dist f g, { refine map_csupr_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { by simpa using HD_bound_aux2 _ 0 } }, -- deduce the result from the above two steps simpa [E2, E1] end private lemma HD_lipschitz_aux3 (f g : Cb α β) : HD f ≤ HD g + dist f g := max_le (le_trans (HD_lipschitz_aux1 f g) (add_le_add_right (le_max_left _ _) _)) (le_trans (HD_lipschitz_aux2 f g) (add_le_add_right (le_max_right _ _) _)) /-- Conclude that HD, being Lipschitz, is continuous -/ private lemma HD_continuous : continuous (HD : Cb α β → ℝ) := lipschitz_with.continuous (lipschitz_with.of_le_add HD_lipschitz_aux3) end constructions --section section consequences variables (α : Type u) (β : Type v) [metric_space α] [compact_space α] [nonempty α] [metric_space β] [compact_space β] [nonempty β] /- Now that we have proved that the set of candidates is compact, and that HD is continuous, we can finally select a candidate minimizing HD. This will be the candidate realizing the optimal coupling. -/ private lemma exists_minimizer : ∃f ∈ candidates_b α β, ∀g ∈ candidates_b α β, HD f ≤ HD g := compact_candidates_b.exists_forall_le candidates_b_nonempty HD_continuous.continuous_on private definition optimal_GH_dist : Cb α β := classical.some (exists_minimizer α β) private lemma optimal_GH_dist_mem_candidates_b : optimal_GH_dist α β ∈ candidates_b α β := by cases (classical.some_spec (exists_minimizer α β)); assumption private lemma HD_optimal_GH_dist_le (g : Cb α β) (hg : g ∈ candidates_b α β) : HD (optimal_GH_dist α β) ≤ HD g := let ⟨Z1, Z2⟩ := classical.some_spec (exists_minimizer α β) in Z2 g hg /-- With the optimal candidate, construct a premetric space structure on α ⊕ β, on which the predistance is given by the candidate. Then, we will identify points at 0 predistance to obtain a genuine metric space -/ def premetric_optimal_GH_dist : pseudo_metric_space (α ⊕ β) := { dist := λp q, optimal_GH_dist α β (p, q), dist_self := λx, candidates_refl (optimal_GH_dist_mem_candidates_b α β), dist_comm := λx y, candidates_symm (optimal_GH_dist_mem_candidates_b α β), dist_triangle := λx y z, candidates_triangle (optimal_GH_dist_mem_candidates_b α β) } local attribute [instance] premetric_optimal_GH_dist pseudo_metric.dist_setoid /-- A metric space which realizes the optimal coupling between α and β -/ @[derive [metric_space]] definition optimal_GH_coupling : Type* := pseudo_metric_quot (α ⊕ β) /-- Injection of α in the optimal coupling between α and β -/ def optimal_GH_injl (x : α) : optimal_GH_coupling α β := ⟦inl x⟧ /-- The injection of α in the optimal coupling between α and β is an isometry. -/ lemma isometry_optimal_GH_injl : isometry (optimal_GH_injl α β) := begin refine isometry_emetric_iff_metric.2 (λx y, _), change dist ⟦inl x⟧ ⟦inl y⟧ = dist x y, exact candidates_dist_inl (optimal_GH_dist_mem_candidates_b α β) _ _, end /-- Injection of β in the optimal coupling between α and β -/ def optimal_GH_injr (y : β) : optimal_GH_coupling α β := ⟦inr y⟧ /-- The injection of β in the optimal coupling between α and β is an isometry. -/ lemma isometry_optimal_GH_injr : isometry (optimal_GH_injr α β) := begin refine isometry_emetric_iff_metric.2 (λx y, _), change dist ⟦inr x⟧ ⟦inr y⟧ = dist x y, exact candidates_dist_inr (optimal_GH_dist_mem_candidates_b α β) _ _, end /-- The optimal coupling between two compact spaces α and β is still a compact space -/ instance compact_space_optimal_GH_coupling : compact_space (optimal_GH_coupling α β) := ⟨begin have : (univ : set (optimal_GH_coupling α β)) = (optimal_GH_injl α β '' univ) ∪ (optimal_GH_injr α β '' univ), { refine subset.antisymm (λxc hxc, _) (subset_univ _), rcases quotient.exists_rep xc with ⟨x, hx⟩, cases x; rw ← hx, { have : ⟦inl x⟧ = optimal_GH_injl α β x := rfl, rw this, exact mem_union_left _ (mem_image_of_mem _ (mem_univ _)) }, { have : ⟦inr x⟧ = optimal_GH_injr α β x := rfl, rw this, exact mem_union_right _ (mem_image_of_mem _ (mem_univ _)) } }, rw this, exact (compact_univ.image (isometry_optimal_GH_injl α β).continuous).union (compact_univ.image (isometry_optimal_GH_injr α β).continuous) end⟩ /-- For any candidate f, HD(f) is larger than or equal to the Hausdorff distance in the optimal coupling. This follows from the fact that HD of the optimal candidate is exactly the Hausdorff distance in the optimal coupling, although we only prove here the inequality we need. -/ lemma Hausdorff_dist_optimal_le_HD {f} (h : f ∈ candidates_b α β) : Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ HD f := begin refine le_trans (le_of_forall_le_of_dense (λr hr, _)) (HD_optimal_GH_dist_le α β f h), have A : ∀ x ∈ range (optimal_GH_injl α β), ∃ y ∈ range (optimal_GH_injr α β), dist x y ≤ r, { assume x hx, rcases mem_range.1 hx with ⟨z, hz⟩, rw ← hz, have I1 : (⨆ x, ⨅ y, optimal_GH_dist α β (inl x, inr y)) < r := lt_of_le_of_lt (le_max_left _ _) hr, have I2 : (⨅ y, optimal_GH_dist α β (inl z, inr y)) ≤ ⨆ x, ⨅ y, optimal_GH_dist α β (inl x, inr y) := le_cSup (by simpa using HD_bound_aux1 _ 0) (mem_range_self _), have I : (⨅ y, optimal_GH_dist α β (inl z, inr y)) < r := lt_of_le_of_lt I2 I1, rcases exists_lt_of_cInf_lt (range_nonempty _) I with ⟨r', r'range, hr'⟩, rcases mem_range.1 r'range with ⟨z', hz'⟩, existsi [optimal_GH_injr α β z', mem_range_self _], have : (optimal_GH_dist α β) (inl z, inr z') ≤ r := begin rw hz', exact le_of_lt hr' end, exact this }, refine Hausdorff_dist_le_of_mem_dist _ A _, { rcases exists_mem_of_nonempty α with ⟨xα, _⟩, have : optimal_GH_injl α β xα ∈ range (optimal_GH_injl α β) := mem_range_self _, rcases A _ this with ⟨y, yrange, hy⟩, exact le_trans dist_nonneg hy }, { assume y hy, rcases mem_range.1 hy with ⟨z, hz⟩, rw ← hz, have I1 : (⨆ y, ⨅ x, optimal_GH_dist α β (inl x, inr y)) < r := lt_of_le_of_lt (le_max_right _ _) hr, have I2 : (⨅ x, optimal_GH_dist α β (inl x, inr z)) ≤ ⨆ y, ⨅ x, optimal_GH_dist α β (inl x, inr y) := le_cSup (by simpa using HD_bound_aux2 _ 0) (mem_range_self _), have I : (⨅ x, optimal_GH_dist α β (inl x, inr z)) < r := lt_of_le_of_lt I2 I1, rcases exists_lt_of_cInf_lt (range_nonempty _) I with ⟨r', r'range, hr'⟩, rcases mem_range.1 r'range with ⟨z', hz'⟩, existsi [optimal_GH_injl α β z', mem_range_self _], have : (optimal_GH_dist α β) (inl z', inr z) ≤ r := begin rw hz', exact le_of_lt hr' end, rw dist_comm, exact this } end end consequences /- We are done with the construction of the optimal coupling -/ end Gromov_Hausdorff_realized end Gromov_Hausdorff
7eaaa7e2649dfde03e3f5751567fea9c497e148f
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/measure_theory/constructions/polish.lean
94562f03a28854059d6668eb44120046309d8432
[ "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
34,610
lean
/- Copyright (c) 2022 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.metric_space.polish import measure_theory.constructions.borel_space /-! # The Borel sigma-algebra on Polish spaces We discuss several results pertaining to the relationship between the topology and the Borel structure on Polish spaces. ## Main definitions and results First, we define the class of analytic sets and establish its basic properties. * `measure_theory.analytic_set s`: a set in a topological space is analytic if it is the continuous image of a Polish space. Equivalently, it is empty, or the image of `ℕ → ℕ`. * `measure_theory.analytic_set.image_of_continuous`: a continuous image of an analytic set is analytic. * `measurable_set.analytic_set`: in a Polish space, any Borel-measurable set is analytic. Then, we show Lusin's theorem that two disjoint analytic sets can be separated by Borel sets. * `measurably_separable s t` states that there exists a measurable set containing `s` and disjoint from `t`. * `analytic_set.measurably_separable` shows that two disjoint analytic sets are separated by a Borel set. Finally, we prove the Lusin-Souslin theorem that a continuous injective image of a Borel subset of a Polish space is Borel. The proof of this nontrivial result relies on the above results on analytic sets. * `measurable_set.image_of_continuous_on_inj_on` asserts that, if `s` is a Borel measurable set in a Polish space, then the image of `s` under a continuous injective map is still Borel measurable. * `continuous.measurable_embedding` states that a continuous injective map on a Polish space is a measurable embedding for the Borel sigma-algebra. * `continuous_on.measurable_embedding` is the same result for a map restricted to a measurable set on which it is continuous. * `measurable.measurable_embedding` states that a measurable injective map from a Polish space to a second-countable topological space is a measurable embedding. * `is_clopenable_iff_measurable_set`: in a Polish space, a set is clopenable (i.e., it can be made open and closed by using a finer Polish topology) if and only if it is Borel-measurable. -/ open set function polish_space pi_nat topological_space metric filter open_locale topological_space measure_theory filter variables {α : Type*} [topological_space α] {ι : Type*} namespace measure_theory /-! ### Analytic sets -/ /-- An analytic set is a set which is the continuous image of some Polish space. There are several equivalent characterizations of this definition. For the definition, we pick one that avoids universe issues: a set is analytic if and only if it is a continuous image of `ℕ → ℕ` (or if it is empty). The above more usual characterization is given in `analytic_set_iff_exists_polish_space_range`. Warning: these are analytic sets in the context of descriptive set theory (which is why they are registered in the namespace `measure_theory`). They have nothing to do with analytic sets in the context of complex analysis. -/ @[irreducible] def analytic_set (s : set α) : Prop := s = ∅ ∨ ∃ (f : (ℕ → ℕ) → α), continuous f ∧ range f = s lemma analytic_set_empty : analytic_set (∅ : set α) := begin rw analytic_set, exact or.inl rfl end lemma analytic_set_range_of_polish_space {β : Type*} [topological_space β] [polish_space β] {f : β → α} (f_cont : continuous f) : analytic_set (range f) := begin casesI is_empty_or_nonempty β, { rw range_eq_empty, exact analytic_set_empty }, { rw analytic_set, obtain ⟨g, g_cont, hg⟩ : ∃ (g : (ℕ → ℕ) → β), continuous g ∧ surjective g := exists_nat_nat_continuous_surjective β, refine or.inr ⟨f ∘ g, f_cont.comp g_cont, _⟩, rwa hg.range_comp } end /-- The image of an open set under a continuous map is analytic. -/ lemma _root_.is_open.analytic_set_image {β : Type*} [topological_space β] [polish_space β] {s : set β} (hs : is_open s) {f : β → α} (f_cont : continuous f) : analytic_set (f '' s) := begin rw image_eq_range, haveI : polish_space s := hs.polish_space, exact analytic_set_range_of_polish_space (f_cont.comp continuous_subtype_coe), end /-- A set is analytic if and only if it is the continuous image of some Polish space. -/ theorem analytic_set_iff_exists_polish_space_range {s : set α} : analytic_set s ↔ ∃ (β : Type) (h : topological_space β) (h' : @polish_space β h) (f : β → α), @continuous _ _ h _ f ∧ range f = s := begin split, { assume h, rw analytic_set at h, cases h, { refine ⟨empty, by apply_instance, by apply_instance, empty.elim, continuous_bot, _⟩, rw h, exact range_eq_empty _ }, { exact ⟨ℕ → ℕ, by apply_instance, by apply_instance, h⟩ } }, { rintros ⟨β, h, h', f, f_cont, f_range⟩, resetI, rw ← f_range, exact analytic_set_range_of_polish_space f_cont } end /-- The continuous image of an analytic set is analytic -/ lemma analytic_set.image_of_continuous_on {β : Type*} [topological_space β] {s : set α} (hs : analytic_set s) {f : α → β} (hf : continuous_on f s) : analytic_set (f '' s) := begin rcases analytic_set_iff_exists_polish_space_range.1 hs with ⟨γ, γtop, γpolish, g, g_cont, gs⟩, resetI, have : f '' s = range (f ∘ g), by rw [range_comp, gs], rw this, apply analytic_set_range_of_polish_space, apply hf.comp_continuous g_cont (λ x, _), rw ← gs, exact mem_range_self _ end lemma analytic_set.image_of_continuous {β : Type*} [topological_space β] {s : set α} (hs : analytic_set s) {f : α → β} (hf : continuous f) : analytic_set (f '' s) := hs.image_of_continuous_on hf.continuous_on /-- A countable intersection of analytic sets is analytic. -/ theorem analytic_set.Inter [hι : nonempty ι] [countable ι] [t2_space α] {s : ι → set α} (hs : ∀ n, analytic_set (s n)) : analytic_set (⋂ n, s n) := begin unfreezingI { rcases hι with ⟨i₀⟩ }, /- For the proof, write each `s n` as the continuous image under a map `f n` of a Polish space `β n`. The product space `γ = Π n, β n` is also Polish, and so is the subset `t` of sequences `x n` for which `f n (x n)` is independent of `n`. The set `t` is Polish, and the range of `x ↦ f 0 (x 0)` on `t` is exactly `⋂ n, s n`, so this set is analytic. -/ choose β hβ h'β f f_cont f_range using λ n, analytic_set_iff_exists_polish_space_range.1 (hs n), resetI, let γ := Π n, β n, let t : set γ := ⋂ n, {x | f n (x n) = f i₀ (x i₀)}, have t_closed : is_closed t, { apply is_closed_Inter, assume n, exact is_closed_eq ((f_cont n).comp (continuous_apply n)) ((f_cont i₀).comp (continuous_apply i₀)) }, haveI : polish_space t := t_closed.polish_space, let F : t → α := λ x, f i₀ ((x : γ) i₀), have F_cont : continuous F := (f_cont i₀).comp ((continuous_apply i₀).comp continuous_subtype_coe), have F_range : range F = ⋂ (n : ι), s n, { apply subset.antisymm, { rintros y ⟨x, rfl⟩, apply mem_Inter.2 (λ n, _), have : f n ((x : γ) n) = F x := (mem_Inter.1 x.2 n : _), rw [← this, ← f_range n], exact mem_range_self _ }, { assume y hy, have A : ∀ n, ∃ (x : β n), f n x = y, { assume n, rw [← mem_range, f_range n], exact mem_Inter.1 hy n }, choose x hx using A, have xt : x ∈ t, { apply mem_Inter.2 (λ n, _), simp [hx] }, refine ⟨⟨x, xt⟩, _⟩, exact hx i₀ } }, rw ← F_range, exact analytic_set_range_of_polish_space F_cont, end /-- A countable union of analytic sets is analytic. -/ theorem analytic_set.Union [countable ι] {s : ι → set α} (hs : ∀ n, analytic_set (s n)) : analytic_set (⋃ n, s n) := begin /- For the proof, write each `s n` as the continuous image under a map `f n` of a Polish space `β n`. The union space `γ = Σ n, β n` is also Polish, and the map `F : γ → α` which coincides with `f n` on `β n` sends it to `⋃ n, s n`. -/ choose β hβ h'β f f_cont f_range using λ n, analytic_set_iff_exists_polish_space_range.1 (hs n), resetI, let γ := Σ n, β n, let F : γ → α := by { rintros ⟨n, x⟩, exact f n x }, have F_cont : continuous F := continuous_sigma f_cont, have F_range : range F = ⋃ n, s n, { rw [range_sigma_eq_Union_range], congr, ext1 n, rw ← f_range n }, rw ← F_range, exact analytic_set_range_of_polish_space F_cont, end theorem _root_.is_closed.analytic_set [polish_space α] {s : set α} (hs : is_closed s) : analytic_set s := begin haveI : polish_space s := hs.polish_space, rw ← @subtype.range_val α s, exact analytic_set_range_of_polish_space continuous_subtype_coe, end /-- Given a Borel-measurable set in a Polish space, there exists a finer Polish topology making it clopen. This is in fact an equivalence, see `is_clopenable_iff_measurable_set`. -/ lemma _root_.measurable_set.is_clopenable [polish_space α] [measurable_space α] [borel_space α] {s : set α} (hs : measurable_set s) : is_clopenable s := begin revert s, apply measurable_set.induction_on_open, { exact λ u hu, hu.is_clopenable }, { exact λ u hu h'u, h'u.compl }, { exact λ f f_disj f_meas hf, is_clopenable.Union hf } end theorem _root_.measurable_set.analytic_set {α : Type*} [t : topological_space α] [polish_space α] [measurable_space α] [borel_space α] {s : set α} (hs : measurable_set s) : analytic_set s := begin /- For a short proof (avoiding measurable induction), one sees `s` as a closed set for a finer topology `t'`. It is analytic for this topology. As the identity from `t'` to `t` is continuous and the image of an analytic set is analytic, it follows that `s` is also analytic for `t`. -/ obtain ⟨t', t't, t'_polish, s_closed, s_open⟩ : ∃ (t' : topological_space α), t' ≤ t ∧ @polish_space α t' ∧ @is_closed α t' s ∧ @is_open α t' s := hs.is_clopenable, have A := @is_closed.analytic_set α t' t'_polish s s_closed, convert @analytic_set.image_of_continuous α t' α t s A id (continuous_id_of_le t't), simp only [id.def, image_id'], end /-- Given a Borel-measurable function from a Polish space to a second-countable space, there exists a finer Polish topology on the source space for which the function is continuous. -/ lemma _root_.measurable.exists_continuous {α β : Type*} [t : topological_space α] [polish_space α] [measurable_space α] [borel_space α] [tβ : topological_space β] [second_countable_topology β] [measurable_space β] [borel_space β] {f : α → β} (hf : measurable f) : ∃ (t' : topological_space α), t' ≤ t ∧ @continuous α β t' tβ f ∧ @polish_space α t' := begin obtain ⟨b, b_count, -, hb⟩ : ∃b : set (set β), b.countable ∧ ∅ ∉ b ∧ is_topological_basis b := exists_countable_basis β, haveI : encodable b := b_count.to_encodable, have : ∀ (s : b), is_clopenable (f ⁻¹' s), { assume s, apply measurable_set.is_clopenable, exact hf (hb.is_open s.2).measurable_set }, choose T Tt Tpolish Tclosed Topen using this, obtain ⟨t', t'T, t't, t'_polish⟩ : ∃ (t' : topological_space α), (∀ i, t' ≤ T i) ∧ (t' ≤ t) ∧ @polish_space α t' := exists_polish_space_forall_le T Tt Tpolish, refine ⟨t', t't, _, t'_polish⟩, apply hb.continuous _ (λ s hs, _), exact t'T ⟨s, hs⟩ _ (Topen ⟨s, hs⟩), end /-! ### Separating sets with measurable sets -/ /-- Two sets `u` and `v` in a measurable space are measurably separable if there exists a measurable set containing `u` and disjoint from `v`. This is mostly interesting for Borel-separable sets. -/ def measurably_separable {α : Type*} [measurable_space α] (s t : set α) : Prop := ∃ u, s ⊆ u ∧ disjoint t u ∧ measurable_set u lemma measurably_separable.Union [countable ι] {α : Type*} [measurable_space α] {s t : ι → set α} (h : ∀ m n, measurably_separable (s m) (t n)) : measurably_separable (⋃ n, s n) (⋃ m, t m) := begin choose u hsu htu hu using h, refine ⟨⋃ m, (⋂ n, u m n), _, _, _⟩, { refine Union_subset (λ m, subset_Union_of_subset m _), exact subset_Inter (λ n, hsu m n) }, { simp_rw [disjoint_Union_left, disjoint_Union_right], assume n m, apply disjoint.mono_right _ (htu m n), apply Inter_subset }, { refine measurable_set.Union (λ m, _), exact measurable_set.Inter (λ n, hu m n) } end /-- The hard part of the Lusin separation theorem saying that two disjoint analytic sets are contained in disjoint Borel sets (see the full statement in `analytic_set.measurably_separable`). Here, we prove this when our analytic sets are the ranges of functions from `ℕ → ℕ`. -/ lemma measurably_separable_range_of_disjoint [t2_space α] [measurable_space α] [borel_space α] {f g : (ℕ → ℕ) → α} (hf : continuous f) (hg : continuous g) (h : disjoint (range f) (range g)) : measurably_separable (range f) (range g) := begin /- We follow [Kechris, *Classical Descriptive Set Theory* (Theorem 14.7)][kechris1995]. If the ranges are not Borel-separated, then one can find two cylinders of length one whose images are not Borel-separated, and then two smaller cylinders of length two whose images are not Borel-separated, and so on. One thus gets two sequences of cylinders, that decrease to two points `x` and `y`. Their images are different by the disjointness assumption, hence contained in two disjoint open sets by the T2 property. By continuity, long enough cylinders around `x` and `y` have images which are separated by these two disjoint open sets, a contradiction. -/ by_contra hfg, have I : ∀ n x y, (¬(measurably_separable (f '' (cylinder x n)) (g '' (cylinder y n)))) → ∃ x' y', x' ∈ cylinder x n ∧ y' ∈ cylinder y n ∧ ¬(measurably_separable (f '' (cylinder x' (n+1))) (g '' (cylinder y' (n+1)))), { assume n x y, contrapose!, assume H, rw [← Union_cylinder_update x n, ← Union_cylinder_update y n, image_Union, image_Union], refine measurably_separable.Union (λ i j, _), exact H _ _ (update_mem_cylinder _ _ _) (update_mem_cylinder _ _ _) }, -- consider the set of pairs of cylinders of some length whose images are not Borel-separated let A := {p : ℕ × (ℕ → ℕ) × (ℕ → ℕ) // ¬(measurably_separable (f '' (cylinder p.2.1 p.1)) (g '' (cylinder p.2.2 p.1)))}, -- for each such pair, one can find longer cylinders whose images are not Borel-separated either have : ∀ (p : A), ∃ (q : A), q.1.1 = p.1.1 + 1 ∧ q.1.2.1 ∈ cylinder p.1.2.1 p.1.1 ∧ q.1.2.2 ∈ cylinder p.1.2.2 p.1.1, { rintros ⟨⟨n, x, y⟩, hp⟩, rcases I n x y hp with ⟨x', y', hx', hy', h'⟩, exact ⟨⟨⟨n+1, x', y'⟩, h'⟩, rfl, hx', hy'⟩ }, choose F hFn hFx hFy using this, let p0 : A := ⟨⟨0, λ n, 0, λ n, 0⟩, by simp [hfg]⟩, -- construct inductively decreasing sequences of cylinders whose images are not separated let p : ℕ → A := λ n, F^[n] p0, have prec : ∀ n, p (n+1) = F (p n) := λ n, by simp only [p, iterate_succ'], -- check that at the `n`-th step we deal with cylinders of length `n` have pn_fst : ∀ n, (p n).1.1 = n, { assume n, induction n with n IH, { refl }, { simp only [prec, hFn, IH] } }, -- check that the cylinders we construct are indeed decreasing, by checking that the coordinates -- are stationary. have Ix : ∀ m n, m + 1 ≤ n → (p n).1.2.1 m = (p (m+1)).1.2.1 m, { assume m, apply nat.le_induction, { refl }, assume n hmn IH, have I : (F (p n)).val.snd.fst m = (p n).val.snd.fst m, { apply hFx (p n) m, rw pn_fst, exact hmn }, rw [prec, I, IH] }, have Iy : ∀ m n, m + 1 ≤ n → (p n).1.2.2 m = (p (m+1)).1.2.2 m, { assume m, apply nat.le_induction, { refl }, assume n hmn IH, have I : (F (p n)).val.snd.snd m = (p n).val.snd.snd m, { apply hFy (p n) m, rw pn_fst, exact hmn }, rw [prec, I, IH] }, -- denote by `x` and `y` the limit points of these two sequences of cylinders. set x : ℕ → ℕ := λ n, (p (n+1)).1.2.1 n with hx, set y : ℕ → ℕ := λ n, (p (n+1)).1.2.2 n with hy, -- by design, the cylinders around these points have images which are not Borel-separable. have M : ∀ n, ¬(measurably_separable (f '' (cylinder x n)) (g '' (cylinder y n))), { assume n, convert (p n).2 using 3, { rw [pn_fst, ← mem_cylinder_iff_eq, mem_cylinder_iff], assume i hi, rw hx, exact (Ix i n hi).symm }, { rw [pn_fst, ← mem_cylinder_iff_eq, mem_cylinder_iff], assume i hi, rw hy, exact (Iy i n hi).symm } }, -- consider two open sets separating `f x` and `g y`. obtain ⟨u, v, u_open, v_open, xu, yv, huv⟩ : ∃ u v : set α, is_open u ∧ is_open v ∧ f x ∈ u ∧ g y ∈ v ∧ disjoint u v, { apply t2_separation, exact disjoint_iff_forall_ne.1 h _ (mem_range_self _) _ (mem_range_self _) }, letI : metric_space (ℕ → ℕ) := metric_space_nat_nat, obtain ⟨εx, εxpos, hεx⟩ : ∃ (εx : ℝ) (H : εx > 0), metric.ball x εx ⊆ f ⁻¹' u, { apply metric.mem_nhds_iff.1, exact hf.continuous_at.preimage_mem_nhds (u_open.mem_nhds xu) }, obtain ⟨εy, εypos, hεy⟩ : ∃ (εy : ℝ) (H : εy > 0), metric.ball y εy ⊆ g ⁻¹' v, { apply metric.mem_nhds_iff.1, exact hg.continuous_at.preimage_mem_nhds (v_open.mem_nhds yv) }, obtain ⟨n, hn⟩ : ∃ (n : ℕ), (1/2 : ℝ)^n < min εx εy := exists_pow_lt_of_lt_one (lt_min εxpos εypos) (by norm_num), -- for large enough `n`, these open sets separate the images of long cylinders around `x` and `y` have B : measurably_separable (f '' (cylinder x n)) (g '' (cylinder y n)), { refine ⟨u, _, _, u_open.measurable_set⟩, { rw image_subset_iff, apply subset.trans _ hεx, assume z hz, rw mem_cylinder_iff_dist_le at hz, exact hz.trans_lt (hn.trans_le (min_le_left _ _)) }, { refine disjoint.mono_left _ huv.symm, change g '' cylinder y n ⊆ v, rw image_subset_iff, apply subset.trans _ hεy, assume z hz, rw mem_cylinder_iff_dist_le at hz, exact hz.trans_lt (hn.trans_le (min_le_right _ _)) } }, -- this is a contradiction. exact M n B end /-- The Lusin separation theorem: if two analytic sets are disjoint, then they are contained in disjoint Borel sets. -/ theorem analytic_set.measurably_separable [t2_space α] [measurable_space α] [borel_space α] {s t : set α} (hs : analytic_set s) (ht : analytic_set t) (h : disjoint s t) : measurably_separable s t := begin rw analytic_set at hs ht, rcases hs with rfl|⟨f, f_cont, rfl⟩, { refine ⟨∅, subset.refl _, by simp, measurable_set.empty⟩ }, rcases ht with rfl|⟨g, g_cont, rfl⟩, { exact ⟨univ, subset_univ _, by simp, measurable_set.univ⟩ }, exact measurably_separable_range_of_disjoint f_cont g_cont h, end /-! ### Injective images of Borel sets -/ variables {γ : Type*} [tγ : topological_space γ] [polish_space γ] include tγ /-- The Lusin-Souslin theorem: the range of a continuous injective function defined on a Polish space is Borel-measurable. -/ theorem measurable_set_range_of_continuous_injective {β : Type*} [topological_space β] [t2_space β] [measurable_space β] [borel_space β] {f : γ → β} (f_cont : continuous f) (f_inj : injective f) : measurable_set (range f) := begin /- We follow [Fremlin, *Measure Theory* (volume 4, 423I)][fremlin_vol4]. Let `b = {s i}` be a countable basis for `α`. When `s i` and `s j` are disjoint, their images are disjoint analytic sets, hence by the separation theorem one can find a Borel-measurable set `q i j` separating them. Let `E i = closure (f '' s i) ∩ ⋂ j, q i j \ q j i`. It contains `f '' (s i)` and it is measurable. Let `F n = ⋃ E i`, where the union is taken over those `i` for which `diam (s i)` is bounded by some number `u n` tending to `0` with `n`. We claim that `range f = ⋂ F n`, from which the measurability is obvious. The inclusion `⊆` is straightforward. To show `⊇`, consider a point `x` in the intersection. For each `n`, it belongs to some `E i` with `diam (s i) ≤ u n`. Pick a point `y i ∈ s i`. We claim that for such `i` and `j`, the intersection `s i ∩ s j` is nonempty: if it were empty, then thanks to the separating set `q i j` in the definition of `E i` one could not have `x ∈ E i ∩ E j`. Since these two sets have small diameter, it follows that `y i` and `y j` are close. Thus, `y` is a Cauchy sequence, converging to a limit `z`. We claim that `f z = x`, completing the proof. Otherwise, one could find open sets `v` and `w` separating `f z` from `x`. Then, for large `n`, the image `f '' (s i)` would be included in `v` by continuity of `f`, so its closure would be contained in the closure of `v`, and therefore it would be disjoint from `w`. This is a contradiction since `x` belongs both to this closure and to `w`. -/ letI := upgrade_polish_space γ, obtain ⟨b, b_count, b_nonempty, hb⟩ : ∃ b : set (set γ), b.countable ∧ ∅ ∉ b ∧ is_topological_basis b := exists_countable_basis γ, haveI : encodable b := b_count.to_encodable, let A := {p : b × b // disjoint (p.1 : set γ) p.2}, -- for each pair of disjoint sets in the topological basis `b`, consider Borel sets separating -- their images, by injectivity of `f` and the Lusin separation theorem. have : ∀ (p : A), ∃ (q : set β), f '' (p.1.1 : set γ) ⊆ q ∧ disjoint (f '' (p.1.2 : set γ)) q ∧ measurable_set q, { assume p, apply analytic_set.measurably_separable ((hb.is_open p.1.1.2).analytic_set_image f_cont) ((hb.is_open p.1.2.2).analytic_set_image f_cont), exact disjoint.image p.2 (f_inj.inj_on univ) (subset_univ _) (subset_univ _) }, choose q hq1 hq2 q_meas using this, -- define sets `E i` and `F n` as in the proof sketch above let E : b → set β := λ s, closure (f '' s) ∩ (⋂ (t : b) (ht : disjoint s.1 t.1), q ⟨(s, t), ht⟩ \ q ⟨(t, s), ht.symm⟩), obtain ⟨u, u_anti, u_pos, u_lim⟩ : ∃ (u : ℕ → ℝ), strict_anti u ∧ (∀ (n : ℕ), 0 < u n) ∧ tendsto u at_top (𝓝 0) := exists_seq_strict_anti_tendsto (0 : ℝ), let F : ℕ → set β := λ n, ⋃ (s : b) (hs : bounded s.1 ∧ diam s.1 ≤ u n), E s, -- it is enough to show that `range f = ⋂ F n`, as the latter set is obviously measurable. suffices : range f = ⋂ n, F n, { have E_meas : ∀ (s : b), measurable_set (E s), { assume b, refine is_closed_closure.measurable_set.inter _, refine measurable_set.Inter (λ s, _), exact measurable_set.Inter (λ hs, (q_meas _).diff (q_meas _)) }, have F_meas : ∀ n, measurable_set (F n), { assume n, refine measurable_set.Union (λ s, _), exact measurable_set.Union (λ hs, E_meas _) }, rw this, exact measurable_set.Inter (λ n, F_meas n) }, -- we check both inclusions. apply subset.antisymm, -- we start with the easy inclusion `range f ⊆ ⋂ F n`. One just needs to unfold the definitions. { rintros x ⟨y, rfl⟩, apply mem_Inter.2 (λ n, _), obtain ⟨s, sb, ys, hs⟩ : ∃ (s : set γ) (H : s ∈ b), y ∈ s ∧ s ⊆ ball y (u n / 2), { apply hb.mem_nhds_iff.1, exact ball_mem_nhds _ (half_pos (u_pos n)) }, have diam_s : diam s ≤ u n, { apply (diam_mono hs bounded_ball).trans, convert diam_ball (half_pos (u_pos n)).le, ring }, refine mem_Union.2 ⟨⟨s, sb⟩, _⟩, refine mem_Union.2 ⟨⟨metric.bounded.mono hs bounded_ball, diam_s⟩, _⟩, apply mem_inter (subset_closure (mem_image_of_mem _ ys)), refine mem_Inter.2 (λ t, mem_Inter.2 (λ ht, ⟨_, _⟩)), { apply hq1, exact mem_image_of_mem _ ys }, { apply disjoint_left.1 (hq2 ⟨(t, ⟨s, sb⟩), ht.symm⟩), exact mem_image_of_mem _ ys } }, -- Now, let us prove the harder inclusion `⋂ F n ⊆ range f`. { assume x hx, -- pick for each `n` a good set `s n` of small diameter for which `x ∈ E (s n)`. have C1 : ∀ n, ∃ (s : b) (hs : bounded s.1 ∧ diam s.1 ≤ u n), x ∈ E s := λ n, by simpa only [mem_Union] using mem_Inter.1 hx n, choose s hs hxs using C1, have C2 : ∀ n, (s n).1.nonempty, { assume n, rw ← ne_empty_iff_nonempty, assume hn, have := (s n).2, rw hn at this, exact b_nonempty this }, -- choose a point `y n ∈ s n`. choose y hy using C2, have I : ∀ m n, ((s m).1 ∩ (s n).1).nonempty, { assume m n, rw ← not_disjoint_iff_nonempty_inter, by_contra' h, have A : x ∈ q ⟨(s m, s n), h⟩ \ q ⟨(s n, s m), h.symm⟩, { have := mem_Inter.1 (hxs m).2 (s n), exact (mem_Inter.1 this h : _) }, have B : x ∈ q ⟨(s n, s m), h.symm⟩ \ q ⟨(s m, s n), h⟩, { have := mem_Inter.1 (hxs n).2 (s m), exact (mem_Inter.1 this h.symm : _) }, exact A.2 B.1 }, -- the points `y n` are nearby, and therefore they form a Cauchy sequence. have cauchy_y : cauchy_seq y, { have : tendsto (λ n, 2 * u n) at_top (𝓝 0), by simpa only [mul_zero] using u_lim.const_mul 2, apply cauchy_seq_of_le_tendsto_0' (λ n, 2 * u n) (λ m n hmn, _) this, rcases I m n with ⟨z, zsm, zsn⟩, calc dist (y m) (y n) ≤ dist (y m) z + dist z (y n) : dist_triangle _ _ _ ... ≤ u m + u n : add_le_add ((dist_le_diam_of_mem (hs m).1 (hy m) zsm).trans (hs m).2) ((dist_le_diam_of_mem (hs n).1 zsn (hy n)).trans (hs n).2) ... ≤ 2 * u m : by linarith [u_anti.antitone hmn] }, haveI : nonempty γ := ⟨y 0⟩, -- let `z` be its limit. let z := lim at_top y, have y_lim : tendsto y at_top (𝓝 z) := cauchy_y.tendsto_lim, suffices : f z = x, by { rw ← this, exact mem_range_self _ }, -- assume for a contradiction that `f z ≠ x`. by_contra' hne, -- introduce disjoint open sets `v` and `w` separating `f z` from `x`. obtain ⟨v, w, v_open, w_open, fzv, xw, hvw⟩ := t2_separation hne, obtain ⟨δ, δpos, hδ⟩ : ∃ δ > (0 : ℝ), ball z δ ⊆ f ⁻¹' v, { apply metric.mem_nhds_iff.1, exact f_cont.continuous_at.preimage_mem_nhds (v_open.mem_nhds fzv) }, obtain ⟨n, hn⟩ : ∃ n, u n + dist (y n) z < δ, { have : tendsto (λ n, u n + dist (y n) z) at_top (𝓝 0), by simpa only [add_zero] using u_lim.add (tendsto_iff_dist_tendsto_zero.1 y_lim), exact ((tendsto_order.1 this).2 _ δpos).exists }, -- for large enough `n`, the image of `s n` is contained in `v`, by continuity of `f`. have fsnv : f '' (s n) ⊆ v, { rw image_subset_iff, apply subset.trans _ hδ, assume a ha, calc dist a z ≤ dist a (y n) + dist (y n) z : dist_triangle _ _ _ ... ≤ u n + dist (y n) z : add_le_add_right ((dist_le_diam_of_mem (hs n).1 ha (hy n)).trans (hs n).2) _ ... < δ : hn }, -- as `x` belongs to the closure of `f '' (s n)`, it belongs to the closure of `v`. have : x ∈ closure v := closure_mono fsnv (hxs n).1, -- this is a contradiction, as `x` is supposed to belong to `w`, which is disjoint from -- the closure of `v`. exact disjoint_left.1 (hvw.closure_left w_open) this xw } end theorem _root_.is_closed.measurable_set_image_of_continuous_on_inj_on {β : Type*} [topological_space β] [t2_space β] [measurable_space β] [borel_space β] {s : set γ} (hs : is_closed s) {f : γ → β} (f_cont : continuous_on f s) (f_inj : inj_on f s) : measurable_set (f '' s) := begin rw image_eq_range, haveI : polish_space s := is_closed.polish_space hs, apply measurable_set_range_of_continuous_injective, { rwa continuous_on_iff_continuous_restrict at f_cont }, { rwa inj_on_iff_injective at f_inj } end variables [measurable_space γ] [hγb : borel_space γ] {β : Type*} [tβ : topological_space β] [t2_space β] [measurable_space β] [borel_space β] {s : set γ} {f : γ → β} include tβ hγb /-- The Lusin-Souslin theorem: if `s` is Borel-measurable in a Polish space, then its image under a continuous injective map is also Borel-measurable. -/ theorem _root_.measurable_set.image_of_continuous_on_inj_on (hs : measurable_set s) (f_cont : continuous_on f s) (f_inj : inj_on f s) : measurable_set (f '' s) := begin obtain ⟨t', t't, t'_polish, s_closed, s_open⟩ : ∃ (t' : topological_space γ), t' ≤ tγ ∧ @polish_space γ t' ∧ @is_closed γ t' s ∧ @is_open γ t' s := hs.is_clopenable, exact @is_closed.measurable_set_image_of_continuous_on_inj_on γ t' t'_polish β _ _ _ _ s s_closed f (f_cont.mono_dom t't) f_inj, end /-- The Lusin-Souslin theorem: if `s` is Borel-measurable in a Polish space, then its image under a measurable injective map taking values in a second-countable topological space is also Borel-measurable. -/ theorem _root_.measurable_set.image_of_measurable_inj_on [second_countable_topology β] (hs : measurable_set s) (f_meas : measurable f) (f_inj : inj_on f s) : measurable_set (f '' s) := begin -- for a finer Polish topology, `f` is continuous. Therefore, one may apply the corresponding -- result for continuous maps. obtain ⟨t', t't, f_cont, t'_polish⟩ : ∃ (t' : topological_space γ), t' ≤ tγ ∧ @continuous γ β t' tβ f ∧ @polish_space γ t' := f_meas.exists_continuous, have M : measurable_set[@borel γ t'] s := @continuous.measurable γ γ t' (@borel γ t') (@borel_space.opens_measurable γ t' (@borel γ t') (by { constructor, refl })) tγ _ _ _ (continuous_id_of_le t't) s hs, exact @measurable_set.image_of_continuous_on_inj_on γ t' t'_polish (@borel γ t') (by { constructor, refl }) β _ _ _ _ s f M (@continuous.continuous_on γ β t' tβ f s f_cont) f_inj, end /-- An injective continuous function on a Polish space is a measurable embedding. -/ theorem _root_.continuous.measurable_embedding (f_cont : continuous f) (f_inj : injective f) : measurable_embedding f := { injective := f_inj, measurable := f_cont.measurable, measurable_set_image' := λ u hu, hu.image_of_continuous_on_inj_on f_cont.continuous_on (f_inj.inj_on _) } /-- If `s` is Borel-measurable in a Polish space and `f` is continuous injective on `s`, then the restriction of `f` to `s` is a measurable embedding. -/ theorem _root_.continuous_on.measurable_embedding (hs : measurable_set s) (f_cont : continuous_on f s) (f_inj : inj_on f s) : measurable_embedding (s.restrict f) := { injective := inj_on_iff_injective.1 f_inj, measurable := (continuous_on_iff_continuous_restrict.1 f_cont).measurable, measurable_set_image' := begin assume u hu, have A : measurable_set ((coe : s → γ) '' u) := (measurable_embedding.subtype_coe hs).measurable_set_image.2 hu, have B : measurable_set (f '' ((coe : s → γ) '' u)) := A.image_of_continuous_on_inj_on (f_cont.mono (subtype.coe_image_subset s u)) (f_inj.mono ((subtype.coe_image_subset s u))), rwa ← image_comp at B, end } /-- An injective measurable function from a Polish space to a second-countable topological space is a measurable embedding. -/ theorem _root_.measurable.measurable_embedding [second_countable_topology β] (f_meas : measurable f) (f_inj : injective f) : measurable_embedding f := { injective := f_inj, measurable := f_meas, measurable_set_image' := λ u hu, hu.image_of_measurable_inj_on f_meas (f_inj.inj_on _) } omit tβ /-- In a Polish space, a set is clopenable if and only if it is Borel-measurable. -/ lemma is_clopenable_iff_measurable_set : is_clopenable s ↔ measurable_set s := begin -- we already know that a measurable set is clopenable. Conversely, assume that `s` is clopenable. refine ⟨λ hs, _, λ hs, hs.is_clopenable⟩, -- consider a finer topology `t'` in which `s` is open and closed. obtain ⟨t', t't, t'_polish, s_closed, s_open⟩ : ∃ (t' : topological_space γ), t' ≤ tγ ∧ @polish_space γ t' ∧ @is_closed γ t' s ∧ @is_open γ t' s := hs, -- the identity is continuous from `t'` to `tγ`. have C : @continuous γ γ t' tγ id := continuous_id_of_le t't, -- therefore, it is also a measurable embedding, by the Lusin-Souslin theorem have E := @continuous.measurable_embedding γ t' t'_polish (@borel γ t') (by { constructor, refl }) γ tγ (polish_space.t2_space γ) _ _ id C injective_id, -- the set `s` is measurable for `t'` as it is closed. have M : @measurable_set γ (@borel γ t') s := @is_closed.measurable_set γ s t' (@borel γ t') (@borel_space.opens_measurable γ t' (@borel γ t') (by { constructor, refl })) s_closed, -- therefore, its image under the measurable embedding `id` is also measurable for `tγ`. convert E.measurable_set_image.2 M, simp only [id.def, image_id'], end omit hγb /-- The set of points for which a measurable sequence of functions converges is measurable. -/ @[measurability] lemma measurable_set_exists_tendsto [hγ : opens_measurable_space γ] [countable ι] {l : filter ι} [l.is_countably_generated] {f : ι → β → γ} (hf : ∀ i, measurable (f i)) : measurable_set {x | ∃ c, tendsto (λ n, f n x) l (𝓝 c)} := begin by_cases hl : l.ne_bot, swap, { rw not_ne_bot at hl, simp [hl] }, letI := upgrade_polish_space γ, rcases l.exists_antitone_basis with ⟨u, hu⟩, simp_rw ← cauchy_map_iff_exists_tendsto, change measurable_set {x | _ ∧ _}, have : ∀ x, ((map (λ i, f i x) l) ×ᶠ (map (λ i, f i x) l)).has_antitone_basis (λ n, ((λ i, f i x) '' u n) ×ˢ ((λ i, f i x) '' u n)) := λ x, hu.map.prod hu.map, simp_rw [and_iff_right (hl.map _), filter.has_basis.le_basis_iff (this _).to_has_basis metric.uniformity_basis_dist_inv_nat_succ, set.set_of_forall], refine measurable_set.bInter set.countable_univ (λ K _, _), simp_rw set.set_of_exists, refine measurable_set.bUnion set.countable_univ (λ N hN, _), simp_rw [prod_image_image_eq, image_subset_iff, prod_subset_iff, set.set_of_forall], exact measurable_set.bInter (to_countable (u N)) (λ i _, measurable_set.bInter (to_countable (u N)) (λ j _, measurable_set_lt (measurable.dist (hf i) (hf j)) measurable_const)), end end measure_theory
c8f3fb6f4f11840a45517d8902ff28921e26b2e3
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/inductive1.lean
f9d638bbe4a224dcc75270aecde6675c597c3700
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach" ]
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
1,927
lean
-- Test1 inductive T1 : Nat -- Error, resultant type is not a sort -- Test2 mutual inductive T1 : Prop inductive T2 : Type -- Error resulting universe mismatch end -- Test3 universe u v mutual inductive T1 (x : Nat) : Type u inductive T2 (x : Nat) : Nat → Type v -- Error resulting universe mismatch end -- Test4 mutual inductive T1 (b : Bool) (x : Nat) : Type inductive T2 (b : Bool) (x : Bool) : Type -- Type mismatch at 'x' end -- Test5 mutual inductive T1 (b : Bool) (x : Nat) : Type inductive T2 (x : Bool) : Type -- number of parameters mismatch end -- Test6 mutual inductive T1 (b : Bool) (x : Nat) : Type inductive T2 (b : Bool) {x : Nat} : Type -- binder annotation mismatch at 'x' end -- Test7 mutual inductive T1.{w1} (b : Bool) (x : Nat) : Type inductive T2.{w2} (b : Bool) (x : Nat) : Type -- universe parameter mismatch end -- Test8 namespace Boo def T1.bla := 10 inductive T1 : Type | bla : T1 -- Boo.T1.bla has already been defined def T1 := 20 inductive T1 : Type -- Boo.T1 has already been defined | bla : T1 end Boo -- Test9 partial inductive T1 : Type -- invalid use of partial noncomputable inductive T1 : Type -- invalid use of noncomputable @[inline] inductive T1' : Type -- declaration is not a definition private inductive T1 : Type | private mk : T1 -- invalid private constructor in private inductive type -- Test10 mutual inductive T1 : Type unsafe inductive T2 : Type end -- Test11 inductive T1 : Nat → Type | z1 : T1 0 | z2 -- constructor resulting type must be specified in inductive family declaration -- Test12 inductive T1 : Nat → Type | z1 : T1 -- unexpected constructor resulting type inductive T1 : Nat → Type | z1 : Nat -- unexpected constructor resulting type -- Test13 inductive A (α : Type u) (β : Type v) | nil {} | protected cons : α → β → A α β → A α β open A #check cons -- unknown `cons`, it is protected
ea03a89316fb05cac0b18ece926b6290dfac43e0
4727251e0cd73359b15b664c3170e5d754078599
/src/ring_theory/witt_vector/defs.lean
09ca4b5ebfe2fcabf8ce43a9e48226fe0019dd07
[ "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
14,129
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Robert Y. Lewis -/ import ring_theory.witt_vector.structure_polynomial /-! # Witt vectors In this file we define the type of `p`-typical Witt vectors and ring operations on it. The ring axioms are verified in `ring_theory/witt_vector/basic.lean`. For a fixed commutative ring `R` and prime `p`, a Witt vector `x : 𝕎 R` is an infinite sequence `ℕ → R` of elements of `R`. However, the ring operations `+` and `*` are not defined in the obvious component-wise way. Instead, these operations are defined via certain polynomials using the machinery in `structure_polynomial.lean`. The `n`th value of the sum of two Witt vectors can depend on the `0`-th through `n`th values of the summands. This effectively simulates a “carrying” operation. ## Main definitions * `witt_vector p R`: the type of `p`-typical Witt vectors with coefficients in `R`. * `witt_vector.coeff x n`: projects the `n`th value of the Witt vector `x`. ## Notation We use notation `𝕎 R`, entered `\bbW`, for the Witt vectors over `R`. ## References * [Hazewinkel, *Witt Vectors*][Haze09] * [Commelin and Lewis, *Formalizing the Ring of Witt Vectors*][CL21] -/ noncomputable theory /-- `witt_vector p R` is the ring of `p`-typical Witt vectors over the commutative ring `R`, where `p` is a prime number. If `p` is invertible in `R`, this ring is isomorphic to `ℕ → R` (the product of `ℕ` copies of `R`). If `R` is a ring of characteristic `p`, then `witt_vector p R` is a ring of characteristic `0`. The canonical example is `witt_vector p (zmod p)`, which is isomorphic to the `p`-adic integers `ℤ_[p]`. -/ structure witt_vector (p : ℕ) (R : Type*) := mk [] :: (coeff : ℕ → R) variables {p : ℕ} /- We cannot make this `localized` notation, because the `p` on the RHS doesn't occur on the left Hiding the `p` in the notation is very convenient, so we opt for repeating the `local notation` in other files that use Witt vectors. -/ local notation `𝕎` := witt_vector p -- type as `\bbW` namespace witt_vector variables (p) {R : Type*} /-- Construct a Witt vector `mk p x : 𝕎 R` from a sequence `x` of elements of `R`. -/ add_decl_doc witt_vector.mk /-- `x.coeff n` is the `n`th coefficient of the Witt vector `x`. This concept does not have a standard name in the literature. -/ add_decl_doc witt_vector.coeff @[ext] lemma ext {x y : 𝕎 R} (h : ∀ n, x.coeff n = y.coeff n) : x = y := begin cases x, cases y, simp only at h, simp [function.funext_iff, h] end lemma ext_iff {x y : 𝕎 R} : x = y ↔ ∀ n, x.coeff n = y.coeff n := ⟨λ h n, by rw h, ext⟩ lemma coeff_mk (x : ℕ → R) : (mk p x).coeff = x := rfl /- These instances are not needed for the rest of the development, but it is interesting to establish early on that `witt_vector p` is a lawful functor. -/ instance : functor (witt_vector p) := { map := λ α β f v, mk p (f ∘ v.coeff), map_const := λ α β a v, mk p (λ _, a) } instance : is_lawful_functor (witt_vector p) := { map_const_eq := λ α β, rfl, id_map := λ α ⟨v, _⟩, rfl, comp_map := λ α β γ f g v, rfl } variables (p) [hp : fact p.prime] [comm_ring R] include hp open mv_polynomial section ring_operations /-- The polynomials used for defining the element `0` of the ring of Witt vectors. -/ def witt_zero : ℕ → mv_polynomial (fin 0 × ℕ) ℤ := witt_structure_int p 0 /-- The polynomials used for defining the element `1` of the ring of Witt vectors. -/ def witt_one : ℕ → mv_polynomial (fin 0 × ℕ) ℤ := witt_structure_int p 1 /-- The polynomials used for defining the addition of the ring of Witt vectors. -/ def witt_add : ℕ → mv_polynomial (fin 2 × ℕ) ℤ := witt_structure_int p (X 0 + X 1) /-- The polynomials used for defining repeated addition of the ring of Witt vectors. -/ def witt_nsmul (n : ℕ) : ℕ → mv_polynomial (fin 1 × ℕ) ℤ := witt_structure_int p (n • X 0) /-- The polynomials used for defining repeated addition of the ring of Witt vectors. -/ def witt_zsmul (n : ℤ) : ℕ → mv_polynomial (fin 1 × ℕ) ℤ := witt_structure_int p (n • X 0) /-- The polynomials used for describing the subtraction of the ring of Witt vectors. -/ def witt_sub : ℕ → mv_polynomial (fin 2 × ℕ) ℤ := witt_structure_int p (X 0 - X 1) /-- The polynomials used for defining the multiplication of the ring of Witt vectors. -/ def witt_mul : ℕ → mv_polynomial (fin 2 × ℕ) ℤ := witt_structure_int p (X 0 * X 1) /-- The polynomials used for defining the negation of the ring of Witt vectors. -/ def witt_neg : ℕ → mv_polynomial (fin 1 × ℕ) ℤ := witt_structure_int p (-X 0) /-- The polynomials used for defining repeated addition of the ring of Witt vectors. -/ def witt_pow (n : ℕ) : ℕ → mv_polynomial (fin 1 × ℕ) ℤ := witt_structure_int p (X 0 ^ n) variable {p} omit hp /-- An auxiliary definition used in `witt_vector.eval`. Evaluates a polynomial whose variables come from the disjoint union of `k` copies of `ℕ`, with a curried evaluation `x`. This can be defined more generally but we use only a specific instance here. -/ def peval {k : ℕ} (φ : mv_polynomial (fin k × ℕ) ℤ) (x : fin k → ℕ → R) : R := aeval (function.uncurry x) φ /-- Let `φ` be a family of polynomials, indexed by natural numbers, whose variables come from the disjoint union of `k` copies of `ℕ`, and let `xᵢ` be a Witt vector for `0 ≤ i < k`. `eval φ x` evaluates `φ` mapping the variable `X_(i, n)` to the `n`th coefficient of `xᵢ`. Instantiating `φ` with certain polynomials defined in `structure_polynomial.lean` establishes the ring operations on `𝕎 R`. For example, `witt_vector.witt_add` is such a `φ` with `k = 2`; evaluating this at `(x₀, x₁)` gives us the sum of two Witt vectors `x₀ + x₁`. -/ def eval {k : ℕ} (φ : ℕ → mv_polynomial (fin k × ℕ) ℤ) (x : fin k → 𝕎 R) : 𝕎 R := mk p $ λ n, peval (φ n) $ λ i, (x i).coeff variables (R) [fact p.prime] instance : has_zero (𝕎 R) := ⟨eval (witt_zero p) ![]⟩ instance : inhabited (𝕎 R) := ⟨0⟩ instance : has_one (𝕎 R) := ⟨eval (witt_one p) ![]⟩ instance : has_add (𝕎 R) := ⟨λ x y, eval (witt_add p) ![x, y]⟩ instance : has_sub (𝕎 R) := ⟨λ x y, eval (witt_sub p) ![x, y]⟩ instance has_nat_scalar : has_scalar ℕ (𝕎 R) := ⟨λ n x, eval (witt_nsmul p n) ![x]⟩ instance has_int_scalar : has_scalar ℤ (𝕎 R) := ⟨λ n x, eval (witt_zsmul p n) ![x]⟩ instance : has_mul (𝕎 R) := ⟨λ x y, eval (witt_mul p) ![x, y]⟩ instance : has_neg (𝕎 R) := ⟨λ x, eval (witt_neg p) ![x]⟩ instance has_nat_pow : has_pow (𝕎 R) ℕ := ⟨λ x n, eval (witt_pow p n) ![x]⟩ end ring_operations section witt_structure_simplifications @[simp] lemma witt_zero_eq_zero (n : ℕ) : witt_zero p n = 0 := begin apply mv_polynomial.map_injective (int.cast_ring_hom ℚ) int.cast_injective, simp only [witt_zero, witt_structure_rat, bind₁, aeval_zero', constant_coeff_X_in_terms_of_W, ring_hom.map_zero, alg_hom.map_zero, map_witt_structure_int], end @[simp] lemma witt_one_zero_eq_one : witt_one p 0 = 1 := begin apply mv_polynomial.map_injective (int.cast_ring_hom ℚ) int.cast_injective, simp only [witt_one, witt_structure_rat, X_in_terms_of_W_zero, alg_hom.map_one, ring_hom.map_one, bind₁_X_right, map_witt_structure_int] end @[simp] lemma witt_one_pos_eq_zero (n : ℕ) (hn : 0 < n) : witt_one p n = 0 := begin apply mv_polynomial.map_injective (int.cast_ring_hom ℚ) int.cast_injective, simp only [witt_one, witt_structure_rat, ring_hom.map_zero, alg_hom.map_one, ring_hom.map_one, map_witt_structure_int], revert hn, apply nat.strong_induction_on n, clear n, intros n IH hn, rw X_in_terms_of_W_eq, simp only [alg_hom.map_mul, alg_hom.map_sub, alg_hom.map_sum, alg_hom.map_pow, bind₁_X_right, bind₁_C_right], rw [sub_mul, one_mul], rw [finset.sum_eq_single 0], { simp only [inv_of_eq_inv, one_mul, inv_pow₀, tsub_zero, ring_hom.map_one, pow_zero], simp only [one_pow, one_mul, X_in_terms_of_W_zero, sub_self, bind₁_X_right] }, { intros i hin hi0, rw [finset.mem_range] at hin, rw [IH _ hin (nat.pos_of_ne_zero hi0), zero_pow (pow_pos hp.1.pos _), mul_zero], }, { rw finset.mem_range, intro, contradiction } end @[simp] lemma witt_add_zero : witt_add p 0 = X (0,0) + X (1,0) := begin apply mv_polynomial.map_injective (int.cast_ring_hom ℚ) int.cast_injective, simp only [witt_add, witt_structure_rat, alg_hom.map_add, ring_hom.map_add, rename_X, X_in_terms_of_W_zero, map_X, witt_polynomial_zero, bind₁_X_right, map_witt_structure_int], end @[simp] lemma witt_sub_zero : witt_sub p 0 = X (0,0) - X (1,0) := begin apply mv_polynomial.map_injective (int.cast_ring_hom ℚ) int.cast_injective, simp only [witt_sub, witt_structure_rat, alg_hom.map_sub, ring_hom.map_sub, rename_X, X_in_terms_of_W_zero, map_X, witt_polynomial_zero, bind₁_X_right, map_witt_structure_int], end @[simp] lemma witt_mul_zero : witt_mul p 0 = X (0,0) * X (1,0) := begin apply mv_polynomial.map_injective (int.cast_ring_hom ℚ) int.cast_injective, simp only [witt_mul, witt_structure_rat, rename_X, X_in_terms_of_W_zero, map_X, witt_polynomial_zero, ring_hom.map_mul, bind₁_X_right, alg_hom.map_mul, map_witt_structure_int] end @[simp] lemma witt_neg_zero : witt_neg p 0 = - X (0,0) := begin apply mv_polynomial.map_injective (int.cast_ring_hom ℚ) int.cast_injective, simp only [witt_neg, witt_structure_rat, rename_X, X_in_terms_of_W_zero, map_X, witt_polynomial_zero, ring_hom.map_neg, alg_hom.map_neg, bind₁_X_right, map_witt_structure_int] end @[simp] lemma constant_coeff_witt_add (n : ℕ) : constant_coeff (witt_add p n) = 0 := begin apply constant_coeff_witt_structure_int p _ _ n, simp only [add_zero, ring_hom.map_add, constant_coeff_X], end @[simp] lemma constant_coeff_witt_sub (n : ℕ) : constant_coeff (witt_sub p n) = 0 := begin apply constant_coeff_witt_structure_int p _ _ n, simp only [sub_zero, ring_hom.map_sub, constant_coeff_X], end @[simp] lemma constant_coeff_witt_mul (n : ℕ) : constant_coeff (witt_mul p n) = 0 := begin apply constant_coeff_witt_structure_int p _ _ n, simp only [mul_zero, ring_hom.map_mul, constant_coeff_X], end @[simp] lemma constant_coeff_witt_neg (n : ℕ) : constant_coeff (witt_neg p n) = 0 := begin apply constant_coeff_witt_structure_int p _ _ n, simp only [neg_zero, ring_hom.map_neg, constant_coeff_X], end @[simp] lemma constant_coeff_witt_nsmul (m : ℕ) (n : ℕ): constant_coeff (witt_nsmul p m n) = 0 := begin apply constant_coeff_witt_structure_int p _ _ n, simp only [smul_zero, map_nsmul, constant_coeff_X], end @[simp] lemma constant_coeff_witt_zsmul (z : ℤ) (n : ℕ): constant_coeff (witt_zsmul p z n) = 0 := begin apply constant_coeff_witt_structure_int p _ _ n, simp only [smul_zero, map_zsmul, constant_coeff_X], end end witt_structure_simplifications section coeff variables (p R) @[simp] lemma zero_coeff (n : ℕ) : (0 : 𝕎 R).coeff n = 0 := show (aeval _ (witt_zero p n) : R) = 0, by simp only [witt_zero_eq_zero, alg_hom.map_zero] @[simp] lemma one_coeff_zero : (1 : 𝕎 R).coeff 0 = 1 := show (aeval _ (witt_one p 0) : R) = 1, by simp only [witt_one_zero_eq_one, alg_hom.map_one] @[simp] lemma one_coeff_eq_of_pos (n : ℕ) (hn : 0 < n) : coeff (1 : 𝕎 R) n = 0 := show (aeval _ (witt_one p n) : R) = 0, by simp only [hn, witt_one_pos_eq_zero, alg_hom.map_zero] variables {p R} omit hp @[simp] lemma v2_coeff {p' R'} (x y : witt_vector p' R') (i : fin 2) : (![x, y] i).coeff = ![x.coeff, y.coeff] i := by fin_cases i; simp include hp lemma add_coeff (x y : 𝕎 R) (n : ℕ) : (x + y).coeff n = peval (witt_add p n) ![x.coeff, y.coeff] := by simp [(+), eval] lemma sub_coeff (x y : 𝕎 R) (n : ℕ) : (x - y).coeff n = peval (witt_sub p n) ![x.coeff, y.coeff] := by simp [has_sub.sub, eval] lemma mul_coeff (x y : 𝕎 R) (n : ℕ) : (x * y).coeff n = peval (witt_mul p n) ![x.coeff, y.coeff] := by simp [(*), eval] lemma neg_coeff (x : 𝕎 R) (n : ℕ) : (-x).coeff n = peval (witt_neg p n) ![x.coeff] := by simp [has_neg.neg, eval, matrix.cons_fin_one] lemma nsmul_coeff (m : ℕ) (x : 𝕎 R) (n : ℕ) : (m • x).coeff n = peval (witt_nsmul p m n) ![x.coeff] := by simp [has_scalar.smul, eval, matrix.cons_fin_one] lemma zsmul_coeff (m : ℤ) (x : 𝕎 R) (n : ℕ) : (m • x).coeff n = peval (witt_zsmul p m n) ![x.coeff] := by simp [has_scalar.smul, eval, matrix.cons_fin_one] lemma pow_coeff (m : ℕ) (x : 𝕎 R) (n : ℕ) : (x ^ m).coeff n = peval (witt_pow p m n) ![x.coeff] := by simp [has_pow.pow, eval, matrix.cons_fin_one] lemma add_coeff_zero (x y : 𝕎 R) : (x + y).coeff 0 = x.coeff 0 + y.coeff 0 := by simp [add_coeff, peval] lemma mul_coeff_zero (x y : 𝕎 R) : (x * y).coeff 0 = x.coeff 0 * y.coeff 0 := by simp [mul_coeff, peval] end coeff lemma witt_add_vars (n : ℕ) : (witt_add p n).vars ⊆ finset.univ.product (finset.range (n + 1)) := witt_structure_int_vars _ _ _ lemma witt_sub_vars (n : ℕ) : (witt_sub p n).vars ⊆ finset.univ.product (finset.range (n + 1)) := witt_structure_int_vars _ _ _ lemma witt_mul_vars (n : ℕ) : (witt_mul p n).vars ⊆ finset.univ.product (finset.range (n + 1)) := witt_structure_int_vars _ _ _ lemma witt_neg_vars (n : ℕ) : (witt_neg p n).vars ⊆ finset.univ.product (finset.range (n + 1)) := witt_structure_int_vars _ _ _ lemma witt_nsmul_vars (m : ℕ) (n : ℕ) : (witt_nsmul p m n).vars ⊆ finset.univ.product (finset.range (n + 1)) := witt_structure_int_vars _ _ _ lemma witt_zsmul_vars (m : ℤ) (n : ℕ) : (witt_zsmul p m n).vars ⊆ finset.univ.product (finset.range (n + 1)) := witt_structure_int_vars _ _ _ lemma witt_pow_vars (m : ℕ) (n : ℕ) : (witt_pow p m n).vars ⊆ finset.univ.product (finset.range (n + 1)) := witt_structure_int_vars _ _ _ end witt_vector
40e969445b4ff5533f494086c2d14415b5f220de
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/data/polynomial/degree/definitions.lean
6bcad8756d4ee1ba488b90697f5050b5bf0075af
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
38,663
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.coeff import data.nat.with_bot /-! # Theory of univariate polynomials The definitions include `degree`, `monic`, `leading_coeff` Results include - `degree_mul` : The degree of the product is the sum of degrees - `leading_coeff_add_of_degree_eq` and `leading_coeff_add_of_degree_lt` : The leading_coefficient of a sum is determined by the leading coefficients and degrees -/ noncomputable theory local attribute [instance, priority 100] classical.prop_decidable open finsupp finset open_locale big_operators namespace polynomial universes u v variables {R : Type u} {S : Type v} {a b : R} {n m : ℕ} section semiring variables [semiring R] {p q r : polynomial R} /-- `degree p` is the degree of the polynomial `p`, i.e. the largest `X`-exponent in `p`. `degree p = some n` when `p ≠ 0` and `n` is the highest power of `X` that appears in `p`, otherwise `degree 0 = ⊥`. -/ def degree (p : polynomial R) : with_bot ℕ := p.support.sup some lemma degree_lt_wf : well_founded (λp q : polynomial R, degree p < degree q) := inv_image.wf degree (with_bot.well_founded_lt nat.lt_wf) instance : has_well_founded (polynomial R) := ⟨_, degree_lt_wf⟩ /-- `nat_degree p` forces `degree p` to ℕ, by defining nat_degree 0 = 0. -/ def nat_degree (p : polynomial R) : ℕ := (degree p).get_or_else 0 /-- `leading_coeff p` gives the coefficient of the highest power of `X` in `p`-/ def leading_coeff (p : polynomial R) : R := coeff p (nat_degree p) /-- a polynomial is `monic` if its leading coefficient is 1 -/ def monic (p : polynomial R) := leading_coeff p = (1 : R) @[nontriviality] lemma monic_of_subsingleton [subsingleton R] (p : polynomial R) : monic p := subsingleton.elim _ _ lemma monic.def : monic p ↔ leading_coeff p = 1 := iff.rfl instance monic.decidable [decidable_eq R] : decidable (monic p) := by unfold monic; apply_instance @[simp] lemma monic.leading_coeff {p : polynomial R} (hp : p.monic) : leading_coeff p = 1 := hp lemma monic.coeff_nat_degree {p : polynomial R} (hp : p.monic) : p.coeff p.nat_degree = 1 := hp @[simp] lemma degree_zero : degree (0 : polynomial R) = ⊥ := rfl @[simp] lemma nat_degree_zero : nat_degree (0 : polynomial R) = 0 := rfl @[simp] lemma coeff_nat_degree : coeff p (nat_degree p) = leading_coeff p := rfl lemma degree_eq_bot : degree p = ⊥ ↔ p = 0 := ⟨λ h, by rw [degree, ← max_eq_sup_with_bot] at h; exact support_eq_empty.1 (max_eq_none.1 h), λ h, h.symm ▸ rfl⟩ @[nontriviality] lemma degree_of_subsingleton [subsingleton R] : degree p = ⊥ := by rw [subsingleton.elim p 0, degree_zero] @[nontriviality] lemma nat_degree_of_subsingleton [subsingleton R] : nat_degree p = 0 := by rw [subsingleton.elim p 0, nat_degree_zero] lemma degree_eq_nat_degree (hp : p ≠ 0) : degree p = (nat_degree p : with_bot ℕ) := let ⟨n, hn⟩ := not_forall.1 (mt option.eq_none_iff_forall_not_mem.2 (mt degree_eq_bot.1 hp)) in have hn : degree p = some n := not_not.1 hn, by rw [nat_degree, hn]; refl lemma degree_eq_iff_nat_degree_eq {p : polynomial R} {n : ℕ} (hp : p ≠ 0) : p.degree = n ↔ p.nat_degree = n := by rw [degree_eq_nat_degree hp, with_bot.coe_eq_coe] lemma degree_eq_iff_nat_degree_eq_of_pos {p : polynomial R} {n : ℕ} (hn : 0 < n) : p.degree = n ↔ p.nat_degree = n := begin split, { intro H, rwa ← degree_eq_iff_nat_degree_eq, rintro rfl, rw degree_zero at H, exact option.no_confusion H }, { intro H, rwa degree_eq_iff_nat_degree_eq, rintro rfl, rw nat_degree_zero at H, rw H at hn, exact lt_irrefl _ hn } end lemma nat_degree_eq_of_degree_eq_some {p : polynomial R} {n : ℕ} (h : degree p = n) : nat_degree p = n := have hp0 : p ≠ 0, from λ hp0, by rw hp0 at h; exact option.no_confusion h, option.some_inj.1 $ show (nat_degree p : with_bot ℕ) = n, by rwa [← degree_eq_nat_degree hp0] @[simp] lemma degree_le_nat_degree : degree p ≤ nat_degree p := with_bot.gi_get_or_else_bot.gc.le_u_l _ lemma nat_degree_eq_of_degree_eq [semiring S] {q : polynomial S} (h : degree p = degree q) : nat_degree p = nat_degree q := by unfold nat_degree; rw h lemma le_degree_of_ne_zero (h : coeff p n ≠ 0) : (n : with_bot ℕ) ≤ degree p := show @has_le.le (with_bot ℕ) _ (some n : with_bot ℕ) (p.support.sup some : with_bot ℕ), from finset.le_sup (finsupp.mem_support_iff.2 h) lemma le_nat_degree_of_ne_zero (h : coeff p n ≠ 0) : n ≤ nat_degree p := begin rw [← with_bot.coe_le_coe, ← degree_eq_nat_degree], exact le_degree_of_ne_zero h, { assume h, subst h, exact h rfl } end lemma le_nat_degree_of_mem_supp (a : ℕ) : a ∈ p.support → a ≤ nat_degree p:= le_nat_degree_of_ne_zero ∘ mem_support_iff.mp lemma supp_subset_range (h : nat_degree p < m) : p.support ⊆ finset.range m := λ n hn, mem_range.2 $ (le_nat_degree_of_mem_supp _ hn).trans_lt h lemma supp_subset_range_nat_degree_succ : p.support ⊆ finset.range (nat_degree p + 1) := supp_subset_range (nat.lt_succ_self _) lemma degree_le_degree (h : coeff q (nat_degree p) ≠ 0) : degree p ≤ degree q := begin by_cases hp : p = 0, { rw hp, exact bot_le }, { rw degree_eq_nat_degree hp, exact le_degree_of_ne_zero h } end lemma degree_ne_of_nat_degree_ne {n : ℕ} : p.nat_degree ≠ n → degree p ≠ n := mt $ λ h, by rw [nat_degree, h, option.get_or_else_coe] theorem nat_degree_le_iff_degree_le {n : ℕ} : nat_degree p ≤ n ↔ degree p ≤ n := with_bot.get_or_else_bot_le_iff alias polynomial.nat_degree_le_iff_degree_le ↔ . . lemma nat_degree_le_nat_degree (hpq : p.degree ≤ q.degree) : p.nat_degree ≤ q.nat_degree := with_bot.gi_get_or_else_bot.gc.monotone_l hpq @[simp] lemma degree_C (ha : a ≠ 0) : degree (C a) = (0 : with_bot ℕ) := show sup (ite (a = 0) ∅ {0}) some = 0, by rw if_neg ha; refl lemma degree_C_le : degree (C a) ≤ (0 : with_bot ℕ) := by by_cases h : a = 0; [rw [h, C_0], rw [degree_C h]]; [exact bot_le, exact le_refl _] lemma degree_one_le : degree (1 : polynomial R) ≤ (0 : with_bot ℕ) := by rw [← C_1]; exact degree_C_le @[simp] lemma nat_degree_C (a : R) : nat_degree (C a) = 0 := begin by_cases ha : a = 0, { have : C a = 0, { rw [ha, C_0] }, rw [nat_degree, degree_eq_bot.2 this], refl }, { rw [nat_degree, degree_C ha], refl } end @[simp] lemma nat_degree_one : nat_degree (1 : polynomial R) = 0 := nat_degree_C 1 @[simp] lemma nat_degree_nat_cast (n : ℕ) : nat_degree (n : polynomial R) = 0 := by simp only [←C_eq_nat_cast, nat_degree_C] @[simp] lemma degree_monomial (n : ℕ) (ha : a ≠ 0) : degree (monomial n a) = n := by rw [degree, support_monomial _ _ ha]; refl @[simp] lemma degree_C_mul_X_pow (n : ℕ) (ha : a ≠ 0) : degree (C a * X ^ n) = n := by rw [← single_eq_C_mul_X, degree_monomial n ha] lemma degree_monomial_le (n : ℕ) (a : R) : degree (monomial n a) ≤ n := if h : a = 0 then by rw [h, (monomial n).map_zero]; exact bot_le else le_of_eq (degree_monomial n h) lemma degree_C_mul_X_pow_le (n : ℕ) (a : R) : degree (C a * X ^ n) ≤ n := by { rw C_mul_X_pow_eq_monomial, apply degree_monomial_le } @[simp] lemma nat_degree_C_mul_X_pow (n : ℕ) (a : R) (ha : a ≠ 0) : nat_degree (C a * X ^ n) = n := nat_degree_eq_of_degree_eq_some (degree_C_mul_X_pow n ha) @[simp] lemma nat_degree_C_mul_X (a : R) (ha : a ≠ 0) : nat_degree (C a * X) = 1 := by simpa only [pow_one] using nat_degree_C_mul_X_pow 1 a ha @[simp] lemma nat_degree_monomial (i : ℕ) (r : R) (hr : r ≠ 0) : nat_degree (monomial i r) = i := by rw [← C_mul_X_pow_eq_monomial, nat_degree_C_mul_X_pow i r hr] lemma coeff_eq_zero_of_degree_lt (h : degree p < n) : coeff p n = 0 := not_not.1 (mt le_degree_of_ne_zero (not_le_of_gt h)) lemma coeff_eq_zero_of_nat_degree_lt {p : polynomial R} {n : ℕ} (h : p.nat_degree < n) : p.coeff n = 0 := begin apply coeff_eq_zero_of_degree_lt, by_cases hp : p = 0, { subst hp, exact with_bot.bot_lt_coe n }, { rwa [degree_eq_nat_degree hp, with_bot.coe_lt_coe] } end @[simp] lemma coeff_nat_degree_succ_eq_zero {p : polynomial R} : p.coeff (p.nat_degree + 1) = 0 := coeff_eq_zero_of_nat_degree_lt (lt_add_one _) -- We need the explicit `decidable` argument here because an exotic one shows up in a moment! lemma ite_le_nat_degree_coeff (p : polynomial R) (n : ℕ) (I : decidable (n < 1 + nat_degree p)) : @ite _ (n < 1 + nat_degree p) I (coeff p n) 0 = coeff p n := begin split_ifs, { refl }, { exact (coeff_eq_zero_of_nat_degree_lt (not_le.1 (λ w, h (nat.lt_one_add_iff.2 w)))).symm, } end lemma as_sum_support (p : polynomial R) : p = ∑ i in p.support, monomial i (p.coeff i) := p.sum_single.symm lemma as_sum_support_C_mul_X_pow (p : polynomial R) : p = ∑ i in p.support, C (p.coeff i) * X^i := trans p.as_sum_support $ by simp only [C_mul_X_pow_eq_monomial] /-- We can reexpress a sum over `p.support` as a sum over `range n`, for any `n` satisfying `p.nat_degree < n`. -/ lemma sum_over_range' [add_comm_monoid S] (p : polynomial R) {f : ℕ → R → S} (h : ∀ n, f n 0 = 0) (n : ℕ) (w : p.nat_degree < n) : p.sum f = ∑ (a : ℕ) in range n, f a (coeff p a) := finsupp.sum_of_support_subset _ (supp_subset_range w) _ $ λ n hn, h n /-- We can reexpress a sum over `p.support` as a sum over `range (p.nat_degree + 1)`. -/ lemma sum_over_range [add_comm_monoid S] (p : polynomial R) {f : ℕ → R → S} (h : ∀ n, f n 0 = 0) : p.sum f = ∑ (a : ℕ) in range (p.nat_degree + 1), f a (coeff p a) := sum_over_range' p h (p.nat_degree + 1) (lt_add_one _) lemma as_sum_range' (p : polynomial R) (n : ℕ) (w : p.nat_degree < n) : p = ∑ i in range n, monomial i (coeff p i) := p.sum_single.symm.trans $ p.sum_over_range' (λ n, single_zero) _ w lemma as_sum_range (p : polynomial R) : p = ∑ i in range (p.nat_degree + 1), monomial i (coeff p i) := p.sum_single.symm.trans $ p.sum_over_range $ λ n, single_zero lemma as_sum_range_C_mul_X_pow (p : polynomial R) : p = ∑ i in range (p.nat_degree + 1), C (coeff p i) * X ^ i := p.as_sum_range.trans $ by simp only [C_mul_X_pow_eq_monomial] lemma coeff_ne_zero_of_eq_degree (hn : degree p = n) : coeff p n ≠ 0 := λ h, mem_support_iff.mp (mem_of_max hn) h lemma eq_X_add_C_of_degree_le_one (h : degree p ≤ 1) : p = C (p.coeff 1) * X + C (p.coeff 0) := ext (λ n, nat.cases_on n (by simp) (λ n, nat.cases_on n (by simp [coeff_C]) (λ m, have degree p < m.succ.succ, from lt_of_le_of_lt h dec_trivial, by simp [coeff_eq_zero_of_degree_lt this, coeff_C, nat.succ_ne_zero, coeff_X, nat.succ_inj', @eq_comm ℕ 0]))) lemma eq_X_add_C_of_degree_eq_one (h : degree p = 1) : p = C (p.leading_coeff) * X + C (p.coeff 0) := (eq_X_add_C_of_degree_le_one (show degree p ≤ 1, from h ▸ le_refl _)).trans (by simp [leading_coeff, nat_degree_eq_of_degree_eq_some h]) lemma eq_X_add_C_of_nat_degree_le_one (h : nat_degree p ≤ 1) : p = C (p.coeff 1) * X + C (p.coeff 0) := eq_X_add_C_of_degree_le_one $ degree_le_of_nat_degree_le h lemma exists_eq_X_add_C_of_nat_degree_le_one (h : nat_degree p ≤ 1) : ∃ a b, p = C a * X + C b := ⟨p.coeff 1, p.coeff 0, eq_X_add_C_of_nat_degree_le_one h⟩ theorem degree_X_pow_le (n : ℕ) : degree (X^n : polynomial R) ≤ n := by simpa only [C_1, one_mul] using degree_C_mul_X_pow_le n (1:R) theorem degree_X_le : degree (X : polynomial R) ≤ 1 := degree_monomial_le _ _ lemma nat_degree_X_le : (X : polynomial R).nat_degree ≤ 1 := nat_degree_le_of_degree_le degree_X_le lemma support_C_mul_X_pow (c : R) (n : ℕ) : (C c * X ^ n).support ⊆ singleton n := begin rw [C_mul_X_pow_eq_monomial], exact support_single_subset end lemma mem_support_C_mul_X_pow {n a : ℕ} {c : R} (h : a ∈ (C c * X ^ n).support) : a = n := mem_singleton.1 $ support_C_mul_X_pow _ _ h lemma card_support_C_mul_X_pow_le_one {c : R} {n : ℕ} : (C c * X ^ n).support.card ≤ 1 := begin rw ← card_singleton n, apply card_le_of_subset (support_C_mul_X_pow c n), end lemma card_supp_le_succ_nat_degree (p : polynomial R) : p.support.card ≤ p.nat_degree + 1 := begin rw ← finset.card_range (p.nat_degree + 1), exact finset.card_le_of_subset supp_subset_range_nat_degree_succ, end lemma le_degree_of_mem_supp (a : ℕ) : a ∈ p.support → ↑a ≤ degree p := le_degree_of_ne_zero ∘ mem_support_iff.mp lemma nonempty_support_iff : p.support.nonempty ↔ p ≠ 0 := by rw [ne.def, nonempty_iff_ne_empty, ne.def, ← support_eq_empty] lemma support_C_mul_X_pow_nonzero {c : R} {n : ℕ} (h : c ≠ 0) : (C c * X ^ n).support = singleton n := begin rw [C_mul_X_pow_eq_monomial], exact support_single_ne_zero h end end semiring section nonzero_semiring variables [semiring R] [nontrivial R] {p q : polynomial R} @[simp] lemma degree_one : degree (1 : polynomial R) = (0 : with_bot ℕ) := degree_C (show (1 : R) ≠ 0, from zero_ne_one.symm) @[simp] lemma degree_X : degree (X : polynomial R) = 1 := degree_monomial _ one_ne_zero @[simp] lemma nat_degree_X : (X : polynomial R).nat_degree = 1 := nat_degree_eq_of_degree_eq_some degree_X end nonzero_semiring section ring variables [ring R] lemma coeff_mul_X_sub_C {p : polynomial R} {r : R} {a : ℕ} : coeff (p * (X - C r)) (a + 1) = coeff p a - coeff p (a + 1) * r := by simp [mul_sub] lemma C_eq_int_cast (n : ℤ) : C (n : R) = n := (C : R →+* _).map_int_cast n @[simp] lemma degree_neg (p : polynomial R) : degree (-p) = degree p := by unfold degree; rw support_neg @[simp] lemma nat_degree_neg (p : polynomial R) : nat_degree (-p) = nat_degree p := by simp [nat_degree] @[simp] lemma nat_degree_int_cast (n : ℤ) : nat_degree (n : polynomial R) = 0 := by simp only [←C_eq_int_cast, nat_degree_C] end ring section semiring variables [semiring R] /-- The second-highest coefficient, or 0 for constants -/ def next_coeff (p : polynomial R) : R := if p.nat_degree = 0 then 0 else p.coeff (p.nat_degree - 1) @[simp] lemma next_coeff_C_eq_zero (c : R) : next_coeff (C c) = 0 := by { rw next_coeff, simp } lemma next_coeff_of_pos_nat_degree (p : polynomial R) (hp : 0 < p.nat_degree) : next_coeff p = p.coeff (p.nat_degree - 1) := by { rw [next_coeff, if_neg], contrapose! hp, simpa } end semiring section semiring variables [semiring R] {p q : polynomial R} {ι : Type*} lemma coeff_nat_degree_eq_zero_of_degree_lt (h : degree p < degree q) : coeff p (nat_degree q) = 0 := coeff_eq_zero_of_degree_lt (lt_of_lt_of_le h degree_le_nat_degree) lemma ne_zero_of_degree_gt {n : with_bot ℕ} (h : n < degree p) : p ≠ 0 := mt degree_eq_bot.2 (ne.symm (ne_of_lt (lt_of_le_of_lt bot_le h))) lemma ne_zero_of_nat_degree_gt {n : ℕ} (h : n < nat_degree p) : p ≠ 0 := λ H, by simpa [H, nat.not_lt_zero] using h lemma degree_lt_degree (h : nat_degree p < nat_degree q) : degree p < degree q := begin by_cases hp : p = 0, { simp [hp], rw bot_lt_iff_ne_bot, intro hq, simpa [hp, degree_eq_bot.mp hq, lt_irrefl] using h }, { rw [degree_eq_nat_degree hp, degree_eq_nat_degree $ ne_zero_of_nat_degree_gt h], exact_mod_cast h } end lemma nat_degree_lt_nat_degree_iff (hp : p ≠ 0) : nat_degree p < nat_degree q ↔ degree p < degree q := ⟨degree_lt_degree, begin intro h, have hq : q ≠ 0 := ne_zero_of_degree_gt h, rw [degree_eq_nat_degree hp, degree_eq_nat_degree hq] at h, exact_mod_cast h end⟩ lemma eq_C_of_degree_le_zero (h : degree p ≤ 0) : p = C (coeff p 0) := begin ext (_|n), { simp }, rw [coeff_C, if_neg (nat.succ_ne_zero _), coeff_eq_zero_of_degree_lt], exact h.trans_lt (with_bot.some_lt_some.2 n.succ_pos), end lemma eq_C_of_degree_eq_zero (h : degree p = 0) : p = C (coeff p 0) := eq_C_of_degree_le_zero (h ▸ le_refl _) lemma degree_le_zero_iff : degree p ≤ 0 ↔ p = C (coeff p 0) := ⟨eq_C_of_degree_le_zero, λ h, h.symm ▸ degree_C_le⟩ lemma degree_add_le (p q : polynomial R) : degree (p + q) ≤ max (degree p) (degree q) := calc degree (p + q) = ((p + q).support).sup some : rfl ... ≤ (p.support ∪ q.support).sup some : by convert sup_mono support_add ... = p.support.sup some ⊔ q.support.sup some : by convert sup_union ... = _ : with_bot.sup_eq_max _ _ @[simp] lemma leading_coeff_zero : leading_coeff (0 : polynomial R) = 0 := rfl @[simp] lemma leading_coeff_eq_zero : leading_coeff p = 0 ↔ p = 0 := ⟨λ h, by_contradiction $ λ hp, mt mem_support_iff.1 (not_not.2 h) (mem_of_max (degree_eq_nat_degree hp)), λ h, h.symm ▸ leading_coeff_zero⟩ lemma leading_coeff_ne_zero : leading_coeff p ≠ 0 ↔ p ≠ 0 := by rw [ne.def, leading_coeff_eq_zero] lemma leading_coeff_eq_zero_iff_deg_eq_bot : leading_coeff p = 0 ↔ degree p = ⊥ := by rw [leading_coeff_eq_zero, degree_eq_bot] lemma nat_degree_mem_support_of_nonzero (H : p ≠ 0) : p.nat_degree ∈ p.support := (p.mem_support_to_fun p.nat_degree).mpr ((not_congr leading_coeff_eq_zero).mpr H) lemma nat_degree_eq_support_max' (h : p ≠ 0) : p.nat_degree = p.support.max' (nonempty_support_iff.mpr h) := (le_max' _ _ $ nat_degree_mem_support_of_nonzero h).antisymm $ max'_le _ _ _ le_nat_degree_of_mem_supp lemma nat_degree_C_mul_X_pow_le (a : R) (n : ℕ) : nat_degree (C a * X ^ n) ≤ n := nat_degree_le_iff_degree_le.2 $ degree_C_mul_X_pow_le _ _ lemma degree_add_eq_left_of_degree_lt (h : degree q < degree p) : degree (p + q) = degree p := le_antisymm (max_eq_left_of_lt h ▸ degree_add_le _ _) $ degree_le_degree $ begin rw [coeff_add, coeff_nat_degree_eq_zero_of_degree_lt h, add_zero], exact mt leading_coeff_eq_zero.1 (ne_zero_of_degree_gt h) end lemma degree_add_eq_right_of_degree_lt (h : degree p < degree q) : degree (p + q) = degree q := by rw [add_comm, degree_add_eq_left_of_degree_lt h] lemma degree_add_C (hp : 0 < degree p) : degree (p + C a) = degree p := add_comm (C a) p ▸ degree_add_eq_right_of_degree_lt $ lt_of_le_of_lt degree_C_le hp lemma degree_add_eq_of_leading_coeff_add_ne_zero (h : leading_coeff p + leading_coeff q ≠ 0) : degree (p + q) = max p.degree q.degree := le_antisymm (degree_add_le _ _) $ match lt_trichotomy (degree p) (degree q) with | or.inl hlt := by rw [degree_add_eq_right_of_degree_lt hlt, max_eq_right_of_lt hlt]; exact le_refl _ | or.inr (or.inl heq) := le_of_not_gt $ assume hlt : max (degree p) (degree q) > degree (p + q), h $ show leading_coeff p + leading_coeff q = 0, begin rw [heq, max_self] at hlt, rw [leading_coeff, leading_coeff, nat_degree_eq_of_degree_eq heq, ← coeff_add], exact coeff_nat_degree_eq_zero_of_degree_lt hlt end | or.inr (or.inr hlt) := by rw [degree_add_eq_left_of_degree_lt hlt, max_eq_left_of_lt hlt]; exact le_refl _ end lemma degree_erase_le (p : polynomial R) (n : ℕ) : degree (p.erase n) ≤ degree p := by convert sup_mono (erase_subset _ _) lemma degree_erase_lt (hp : p ≠ 0) : degree (p.erase (nat_degree p)) < degree p := lt_of_le_of_ne (degree_erase_le _ _) $ (degree_eq_nat_degree hp).symm ▸ (by convert λ h, not_mem_erase _ _ (mem_of_max h)) lemma degree_sum_le (s : finset ι) (f : ι → polynomial R) : degree (∑ i in s, f i) ≤ s.sup (λ b, degree (f b)) := finset.induction_on s (by simp only [sum_empty, sup_empty, degree_zero, le_refl]) $ assume a s has ih, calc degree (∑ i in insert a s, f i) ≤ max (degree (f a)) (degree (∑ i in s, f i)) : by rw sum_insert has; exact degree_add_le _ _ ... ≤ _ : by rw [sup_insert, with_bot.sup_eq_max]; exact max_le_max (le_refl _) ih lemma degree_mul_le (p q : polynomial R) : degree (p * q) ≤ degree p + degree q := calc degree (p * q) ≤ (p.support).sup (λi, degree (sum q (λj a, C (coeff p i * a) * X ^ (i + j)))) : by simp only [single_eq_C_mul_X.symm]; exact degree_sum_le _ _ ... ≤ p.support.sup (λi, q.support.sup (λj, degree (C (coeff p i * coeff q j) * X ^ (i + j)))) : finset.sup_mono_fun (assume i hi, degree_sum_le _ _) ... ≤ degree p + degree q : begin refine finset.sup_le (λ a ha, finset.sup_le (λ b hb, le_trans (degree_C_mul_X_pow_le _ _) _)), rw [with_bot.coe_add], rw mem_support_iff at ha hb, exact add_le_add (le_degree_of_ne_zero ha) (le_degree_of_ne_zero hb) end lemma degree_pow_le (p : polynomial R) : ∀ n, degree (p ^ n) ≤ n •ℕ (degree p) | 0 := by rw [pow_zero, zero_nsmul]; exact degree_one_le | (n+1) := calc degree (p ^ (n + 1)) ≤ degree p + degree (p ^ n) : by rw pow_succ; exact degree_mul_le _ _ ... ≤ _ : by rw succ_nsmul; exact add_le_add (le_refl _) (degree_pow_le _) @[simp] lemma leading_coeff_monomial (a : R) (n : ℕ) : leading_coeff (monomial n a) = a := begin by_cases ha : a = 0, { simp only [ha, (monomial n).map_zero, leading_coeff_zero] }, { rw [leading_coeff, nat_degree_monomial _ _ ha], exact @finsupp.single_eq_same _ _ _ n a } end lemma leading_coeff_C_mul_X_pow (a : R) (n : ℕ) : leading_coeff (C a * X ^ n) = a := by rw [C_mul_X_pow_eq_monomial, leading_coeff_monomial] @[simp] lemma leading_coeff_C (a : R) : leading_coeff (C a) = a := leading_coeff_monomial a 0 @[simp] lemma leading_coeff_X_pow (n : ℕ) : leading_coeff ((X : polynomial R) ^ n) = 1 := by simpa only [C_1, one_mul] using leading_coeff_C_mul_X_pow (1 : R) n @[simp] lemma leading_coeff_X : leading_coeff (X : polynomial R) = 1 := by simpa only [pow_one] using @leading_coeff_X_pow R _ 1 @[simp] lemma monic_X_pow (n : ℕ) : monic (X ^ n : polynomial R) := leading_coeff_X_pow n @[simp] lemma monic_X : monic (X : polynomial R) := leading_coeff_X @[simp] lemma leading_coeff_one : leading_coeff (1 : polynomial R) = 1 := leading_coeff_C 1 @[simp] lemma monic_one : monic (1 : polynomial R) := leading_coeff_C _ lemma monic.ne_zero {R : Type*} [semiring R] [nontrivial R] {p : polynomial R} (hp : p.monic) : p ≠ 0 := by { rintro rfl, simpa [monic] using hp } lemma monic.ne_zero_of_ne (h : (0:R) ≠ 1) {p : polynomial R} (hp : p.monic) : p ≠ 0 := by { nontriviality R, exact hp.ne_zero } lemma monic.ne_zero_of_polynomial_ne {r} (hp : monic p) (hne : q ≠ r) : p ≠ 0 := by { haveI := nontrivial.of_polynomial_ne hne, exact hp.ne_zero } lemma leading_coeff_add_of_degree_lt (h : degree p < degree q) : leading_coeff (p + q) = leading_coeff q := have coeff p (nat_degree q) = 0, from coeff_nat_degree_eq_zero_of_degree_lt h, by simp only [leading_coeff, nat_degree_eq_of_degree_eq (degree_add_eq_right_of_degree_lt h), this, coeff_add, zero_add] lemma leading_coeff_add_of_degree_eq (h : degree p = degree q) (hlc : leading_coeff p + leading_coeff q ≠ 0) : leading_coeff (p + q) = leading_coeff p + leading_coeff q := have nat_degree (p + q) = nat_degree p, by apply nat_degree_eq_of_degree_eq; rw [degree_add_eq_of_leading_coeff_add_ne_zero hlc, h, max_self], by simp only [leading_coeff, this, nat_degree_eq_of_degree_eq h, coeff_add] @[simp] lemma coeff_mul_degree_add_degree (p q : polynomial R) : coeff (p * q) (nat_degree p + nat_degree q) = leading_coeff p * leading_coeff q := calc coeff (p * q) (nat_degree p + nat_degree q) = ∑ x in nat.antidiagonal (nat_degree p + nat_degree q), coeff p x.1 * coeff q x.2 : coeff_mul _ _ _ ... = coeff p (nat_degree p) * coeff q (nat_degree q) : begin refine finset.sum_eq_single (nat_degree p, nat_degree q) _ _, { rintro ⟨i,j⟩ h₁ h₂, rw nat.mem_antidiagonal at h₁, by_cases H : nat_degree p < i, { rw [coeff_eq_zero_of_degree_lt (lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 H)), zero_mul] }, { rw not_lt_iff_eq_or_lt at H, cases H, { subst H, rw add_left_cancel_iff at h₁, dsimp at h₁, subst h₁, exfalso, exact h₂ rfl }, { suffices : nat_degree q < j, { rw [coeff_eq_zero_of_degree_lt (lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 this)), mul_zero] }, { by_contra H', rw not_lt at H', exact ne_of_lt (nat.lt_of_lt_of_le (nat.add_lt_add_right H j) (nat.add_le_add_left H' _)) h₁ } } } }, { intro H, exfalso, apply H, rw nat.mem_antidiagonal } end lemma degree_mul' (h : leading_coeff p * leading_coeff q ≠ 0) : degree (p * q) = degree p + degree q := have hp : p ≠ 0 := by refine mt _ h; exact λ hp, by rw [hp, leading_coeff_zero, zero_mul], have hq : q ≠ 0 := by refine mt _ h; exact λ hq, by rw [hq, leading_coeff_zero, mul_zero], le_antisymm (degree_mul_le _ _) begin rw [degree_eq_nat_degree hp, degree_eq_nat_degree hq], refine le_degree_of_ne_zero _, rwa coeff_mul_degree_add_degree end lemma degree_mul_monic (hq : monic q) : degree (p * q) = degree p + degree q := if hp : p = 0 then by simp [hp] else degree_mul' $ by rwa [hq.leading_coeff, mul_one, ne.def, leading_coeff_eq_zero] lemma nat_degree_mul' (h : leading_coeff p * leading_coeff q ≠ 0) : nat_degree (p * q) = nat_degree p + nat_degree q := have hp : p ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, h $ by rw [h₁, zero_mul]), have hq : q ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, h $ by rw [h₁, mul_zero]), nat_degree_eq_of_degree_eq_some $ by rw [degree_mul' h, with_bot.coe_add, degree_eq_nat_degree hp, degree_eq_nat_degree hq] lemma leading_coeff_mul' (h : leading_coeff p * leading_coeff q ≠ 0) : leading_coeff (p * q) = leading_coeff p * leading_coeff q := begin unfold leading_coeff, rw [nat_degree_mul' h, coeff_mul_degree_add_degree], refl end lemma leading_coeff_pow' : leading_coeff p ^ n ≠ 0 → leading_coeff (p ^ n) = leading_coeff p ^ n := nat.rec_on n (by simp) $ λ n ih h, have h₁ : leading_coeff p ^ n ≠ 0 := λ h₁, h $ by rw [pow_succ, h₁, mul_zero], have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 := by rwa [pow_succ, ← ih h₁] at h, by rw [pow_succ, pow_succ, leading_coeff_mul' h₂, ih h₁] lemma degree_pow' : ∀ {n}, leading_coeff p ^ n ≠ 0 → degree (p ^ n) = n •ℕ (degree p) | 0 := λ h, by rw [pow_zero, ← C_1] at *; rw [degree_C h, zero_nsmul] | (n+1) := λ h, have h₁ : leading_coeff p ^ n ≠ 0 := λ h₁, h $ by rw [pow_succ, h₁, mul_zero], have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 := by rwa [pow_succ, ← leading_coeff_pow' h₁] at h, by rw [pow_succ, degree_mul' h₂, succ_nsmul, degree_pow' h₁] lemma nat_degree_pow' {n : ℕ} (h : leading_coeff p ^ n ≠ 0) : nat_degree (p ^ n) = n * nat_degree p := if hp0 : p = 0 then if hn0 : n = 0 then by simp * else by rw [hp0, zero_pow (nat.pos_of_ne_zero hn0)]; simp else have hpn : p ^ n ≠ 0, from λ hpn0, have h1 : _ := h, by rw [← leading_coeff_pow' h1, hpn0, leading_coeff_zero] at h; exact h rfl, option.some_inj.1 $ show (nat_degree (p ^ n) : with_bot ℕ) = (n * nat_degree p : ℕ), by rw [← degree_eq_nat_degree hpn, degree_pow' h, degree_eq_nat_degree hp0, ← with_bot.coe_nsmul]; simp theorem leading_coeff_mul_monic {p q : polynomial R} (hq : monic q) : leading_coeff (p * q) = leading_coeff p := decidable.by_cases (λ H : leading_coeff p = 0, by rw [H, leading_coeff_eq_zero.1 H, zero_mul, leading_coeff_zero]) (λ H : leading_coeff p ≠ 0, by rw [leading_coeff_mul', hq.leading_coeff, mul_one]; rwa [hq.leading_coeff, mul_one]) @[simp] theorem leading_coeff_mul_X_pow {p : polynomial R} {n : ℕ} : leading_coeff (p * X ^ n) = leading_coeff p := leading_coeff_mul_monic (monic_X_pow n) @[simp] theorem leading_coeff_mul_X {p : polynomial R} : leading_coeff (p * X) = leading_coeff p := leading_coeff_mul_monic monic_X lemma nat_degree_mul_le {p q : polynomial R} : nat_degree (p * q) ≤ nat_degree p + nat_degree q := begin apply nat_degree_le_of_degree_le, apply le_trans (degree_mul_le p q), rw with_bot.coe_add, refine add_le_add _ _; apply degree_le_nat_degree, end lemma subsingleton_of_monic_zero (h : monic (0 : polynomial R)) : (∀ p q : polynomial R, p = q) ∧ (∀ a b : R, a = b) := by rw [monic.def, leading_coeff_zero] at h; exact ⟨λ p q, by rw [← mul_one p, ← mul_one q, ← C_1, ← h, C_0, mul_zero, mul_zero], λ a b, by rw [← mul_one a, ← mul_one b, ← h, mul_zero, mul_zero]⟩ lemma zero_le_degree_iff {p : polynomial R} : 0 ≤ degree p ↔ p ≠ 0 := by rw [ne.def, ← degree_eq_bot]; cases degree p; exact dec_trivial lemma degree_nonneg_iff_ne_zero : 0 ≤ degree p ↔ p ≠ 0 := ⟨λ h0p hp0, absurd h0p (by rw [hp0, degree_zero]; exact dec_trivial), λ hp0, le_of_not_gt (λ h, by simp [gt, degree_eq_bot, *] at *)⟩ lemma nat_degree_eq_zero_iff_degree_le_zero : p.nat_degree = 0 ↔ p.degree ≤ 0 := by rw [← nonpos_iff_eq_zero, nat_degree_le_iff_degree_le, with_bot.coe_zero] theorem degree_le_iff_coeff_zero (f : polynomial R) (n : with_bot ℕ) : degree f ≤ n ↔ ∀ m : ℕ, n < m → coeff f m = 0 := ⟨λ (H : finset.sup (f.support) some ≤ n) m (Hm : n < (m : with_bot ℕ)), decidable.of_not_not $ λ H4, have H1 : m ∉ f.support, from λ H2, not_lt_of_ge ((finset.sup_le_iff.1 H) m H2 : ((m : with_bot ℕ) ≤ n)) Hm, H1 $ (finsupp.mem_support_to_fun f m).2 H4, λ H, finset.sup_le $ λ b Hb, decidable.of_not_not $ λ Hn, (finsupp.mem_support_to_fun f b).1 Hb $ H b $ lt_of_not_ge Hn⟩ theorem degree_lt_iff_coeff_zero (f : polynomial R) (n : ℕ) : degree f < n ↔ ∀ m : ℕ, n ≤ m → coeff f m = 0 := begin refine ⟨λ hf m hm, coeff_eq_zero_of_degree_lt (lt_of_lt_of_le hf (with_bot.coe_le_coe.2 hm)), _⟩, simp only [degree, finset.sup_lt_iff (with_bot.bot_lt_coe n), mem_support_iff, with_bot.some_eq_coe, with_bot.coe_lt_coe, ← @not_le ℕ], exact λ h m, mt (h m), end lemma degree_lt_degree_mul_X (hp : p ≠ 0) : p.degree < (p * X).degree := by haveI := nontrivial.of_polynomial_ne hp; exact have leading_coeff p * leading_coeff X ≠ 0, by simpa, by erw [degree_mul' this, degree_eq_nat_degree hp, degree_X, ← with_bot.coe_one, ← with_bot.coe_add, with_bot.coe_lt_coe]; exact nat.lt_succ_self _ lemma nat_degree_pos_iff_degree_pos : 0 < nat_degree p ↔ 0 < degree p := lt_iff_lt_of_le_iff_le nat_degree_le_iff_degree_le lemma eq_C_of_nat_degree_le_zero (h : nat_degree p ≤ 0) : p = C (coeff p 0) := eq_C_of_degree_le_zero $ degree_le_of_nat_degree_le h lemma eq_C_of_nat_degree_eq_zero (h : nat_degree p = 0) : p = C (coeff p 0) := eq_C_of_nat_degree_le_zero h.le lemma ne_zero_of_coe_le_degree (hdeg : ↑n ≤ p.degree) : p ≠ 0 := by rw ← degree_nonneg_iff_ne_zero; exact trans (by exact_mod_cast n.zero_le) hdeg lemma le_nat_degree_of_coe_le_degree (hdeg : ↑n ≤ p.degree) : n ≤ p.nat_degree := with_bot.coe_le_coe.mp ((degree_eq_nat_degree $ ne_zero_of_coe_le_degree hdeg) ▸ hdeg) end semiring section nonzero_semiring variables [semiring R] [nontrivial R] {p q : polynomial R} @[simp] lemma degree_X_pow (n : ℕ) : degree ((X : polynomial R) ^ n) = n := by rw [X_pow_eq_monomial, degree_monomial _ (@one_ne_zero R _ _)] @[simp] lemma nat_degree_X_pow (n : ℕ) : nat_degree ((X : polynomial R) ^ n) = n := nat_degree_eq_of_degree_eq_some (degree_X_pow n) theorem not_is_unit_X : ¬ is_unit (X : polynomial R) := λ ⟨⟨_, g, hfg, hgf⟩, rfl⟩, @zero_ne_one R _ _ $ by { rw [← coeff_one_zero, ← hgf], simp } @[simp] lemma degree_mul_X : degree (p * X) = degree p + 1 := by simp [degree_mul_monic monic_X] @[simp] lemma degree_mul_X_pow : degree (p * X ^ n) = degree p + n := by simp [degree_mul_monic (monic_X_pow n)] end nonzero_semiring section ring variables [ring R] {p q : polynomial R} lemma degree_sub_le (p q : polynomial R) : degree (p - q) ≤ max (degree p) (degree q) := by simpa only [sub_eq_add_neg, degree_neg q] using degree_add_le p (-q) lemma degree_sub_lt (hd : degree p = degree q) (hp0 : p ≠ 0) (hlc : leading_coeff p = leading_coeff q) : degree (p - q) < degree p := have hp : single (nat_degree p) (leading_coeff p) + p.erase (nat_degree p) = p := finsupp.single_add_erase _ _, have hq : single (nat_degree q) (leading_coeff q) + q.erase (nat_degree q) = q := finsupp.single_add_erase _ _, have hd' : nat_degree p = nat_degree q := by unfold nat_degree; rw hd, have hq0 : q ≠ 0 := mt degree_eq_bot.2 (hd ▸ mt degree_eq_bot.1 hp0), calc degree (p - q) = degree (erase (nat_degree q) p + -erase (nat_degree q) q) : by conv {to_lhs, rw [← hp, ← hq, hlc, hd', add_sub_add_left_eq_sub, sub_eq_add_neg]} ... ≤ max (degree (erase (nat_degree q) p)) (degree (erase (nat_degree q) q)) : degree_neg (erase (nat_degree q) q) ▸ degree_add_le _ _ ... < degree p : max_lt_iff.2 ⟨hd' ▸ degree_erase_lt hp0, hd.symm ▸ degree_erase_lt hq0⟩ lemma nat_degree_X_sub_C_le {r : R} : (X - C r).nat_degree ≤ 1 := nat_degree_le_iff_degree_le.2 $ le_trans (degree_sub_le _ _) $ max_le degree_X_le $ le_trans degree_C_le $ with_bot.coe_le_coe.2 zero_le_one lemma degree_sum_fin_lt {n : ℕ} (f : fin n → R) : degree (∑ i : fin n, C (f i) * X ^ (i : ℕ)) < n := begin haveI : is_commutative (with_bot ℕ) max := ⟨max_comm⟩, haveI : is_associative (with_bot ℕ) max := ⟨max_assoc⟩, calc (∑ i, C (f i) * X ^ (i : ℕ)).degree ≤ finset.univ.fold (⊔) ⊥ (λ i, (C (f i) * X ^ (i : ℕ)).degree) : degree_sum_le _ _ ... = finset.univ.fold max ⊥ (λ i, (C (f i) * X ^ (i : ℕ)).degree) : (@finset.fold_hom _ _ _ (⊔) _ _ _ ⊥ finset.univ _ _ _ id (with_bot.sup_eq_max)).symm ... < n : (finset.fold_max_lt (n : with_bot ℕ)).mpr ⟨with_bot.bot_lt_some _, _⟩, rintros ⟨i, hi⟩ -, calc (C (f ⟨i, hi⟩) * X ^ i).degree ≤ (C _).degree + (X ^ i).degree : degree_mul_le _ _ ... ≤ 0 + i : add_le_add degree_C_le (degree_X_pow_le i) ... = i : zero_add _ ... < n : with_bot.some_lt_some.mpr hi, end lemma degree_sub_eq_left_of_degree_lt (h : degree q < degree p) : degree (p - q) = degree p := by { rw ← degree_neg q at h, rw [sub_eq_add_neg, degree_add_eq_left_of_degree_lt h] } lemma degree_sub_eq_right_of_degree_lt (h : degree p < degree q) : degree (p - q) = degree q := by { rw ← degree_neg q at h, rw [sub_eq_add_neg, degree_add_eq_right_of_degree_lt h, degree_neg] } end ring section nonzero_ring variables [nontrivial R] [ring R] @[simp] lemma degree_X_sub_C (a : R) : degree (X - C a) = 1 := have degree (C a) < degree (X : polynomial R), from calc degree (C a) ≤ 0 : degree_C_le ... < 1 : with_bot.some_lt_some.mpr zero_lt_one ... = degree X : degree_X.symm, by rw [degree_sub_eq_left_of_degree_lt this, degree_X] @[simp] lemma degree_X_add_C (a : R) : degree (X + C a) = 1 := have degree (C a) < degree (X : polynomial R), from calc degree (C a) ≤ 0 : degree_C_le ... < 1 : with_bot.some_lt_some.mpr zero_lt_one ... = degree X : degree_X.symm, by rw [degree_add_eq_left_of_degree_lt this, degree_X] @[simp] lemma nat_degree_X_sub_C (x : R) : (X - C x).nat_degree = 1 := nat_degree_eq_of_degree_eq_some $ degree_X_sub_C x @[simp] lemma next_coeff_X_sub_C (c : R) : next_coeff (X - C c) = - c := by simp [next_coeff_of_pos_nat_degree] lemma degree_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : R) : degree ((X : polynomial R) ^ n - C a) = n := have degree (C a) < degree ((X : polynomial R) ^ n), from calc degree (C a) ≤ 0 : degree_C_le ... < degree ((X : polynomial R) ^ n) : by rwa [degree_X_pow]; exact with_bot.coe_lt_coe.2 hn, by rw [degree_sub_eq_left_of_degree_lt this, degree_X_pow] lemma X_pow_sub_C_ne_zero {n : ℕ} (hn : 0 < n) (a : R) : (X : polynomial R) ^ n - C a ≠ 0 := mt degree_eq_bot.2 (show degree ((X : polynomial R) ^ n - C a) ≠ ⊥, by rw degree_X_pow_sub_C hn a; exact dec_trivial) theorem X_sub_C_ne_zero (r : R) : X - C r ≠ 0 := pow_one (X : polynomial R) ▸ X_pow_sub_C_ne_zero zero_lt_one r theorem zero_nmem_multiset_map_X_sub_C {α : Type*} (m : multiset α) (f : α → R) : (0 : polynomial R) ∉ m.map (λ a, X - C (f a)) := λ mem, let ⟨a, _, ha⟩ := multiset.mem_map.mp mem in X_sub_C_ne_zero _ ha lemma nat_degree_X_pow_sub_C {n : ℕ} {r : R} : (X ^ n - C r).nat_degree = n := begin by_cases hn : n = 0, { rw [hn, pow_zero, ←C_1, ←ring_hom.map_sub, nat_degree_C] }, { exact nat_degree_eq_of_degree_eq_some (degree_X_pow_sub_C (pos_iff_ne_zero.mpr hn) r) }, end @[simp] lemma leading_coeff_X_pow_sub_C {n : ℕ} (hn : 0 < n) {r : R} : (X ^ n - C r).leading_coeff = 1 := by rw [leading_coeff, nat_degree_X_pow_sub_C, coeff_sub, coeff_X_pow_self, coeff_C, if_neg (pos_iff_ne_zero.mp hn), sub_zero] @[simp] lemma leading_coeff_X_pow_sub_one {n : ℕ} (hn : 0 < n) : (X ^ n - 1 : polynomial R).leading_coeff = 1 := leading_coeff_X_pow_sub_C hn end nonzero_ring section no_zero_divisors variables [semiring R] [no_zero_divisors R] {p q : polynomial R} @[simp] lemma degree_mul : degree (p * q) = degree p + degree q := if hp0 : p = 0 then by simp only [hp0, degree_zero, zero_mul, with_bot.bot_add] else if hq0 : q = 0 then by simp only [hq0, degree_zero, mul_zero, with_bot.add_bot] else degree_mul' $ mul_ne_zero (mt leading_coeff_eq_zero.1 hp0) (mt leading_coeff_eq_zero.1 hq0) @[simp] lemma degree_pow [nontrivial R] (p : polynomial R) (n : ℕ) : degree (p ^ n) = n •ℕ (degree p) := by induction n; [simp only [pow_zero, degree_one, zero_nsmul], simp only [*, pow_succ, succ_nsmul, degree_mul]] @[simp] lemma leading_coeff_mul (p q : polynomial R) : leading_coeff (p * q) = leading_coeff p * leading_coeff q := begin by_cases hp : p = 0, { simp only [hp, zero_mul, leading_coeff_zero] }, { by_cases hq : q = 0, { simp only [hq, mul_zero, leading_coeff_zero] }, { rw [leading_coeff_mul'], exact mul_ne_zero (mt leading_coeff_eq_zero.1 hp) (mt leading_coeff_eq_zero.1 hq) } } end @[simp] lemma leading_coeff_X_add_C [nontrivial R] (a b : R) (ha : a ≠ 0): leading_coeff (C a * X + C b) = a := begin rw [add_comm, leading_coeff_add_of_degree_lt], { simp }, { simpa [degree_C ha] using lt_of_le_of_lt degree_C_le (with_bot.coe_lt_coe.2 zero_lt_one)} end /-- `polynomial.leading_coeff` bundled as a `monoid_hom` when `R` has `no_zero_divisors`, and thus `leading_coeff` is multiplicative -/ def leading_coeff_hom : polynomial R →* R := { to_fun := leading_coeff, map_one' := by simp, map_mul' := leading_coeff_mul } @[simp] lemma leading_coeff_hom_apply (p : polynomial R) : leading_coeff_hom p = leading_coeff p := rfl @[simp] lemma leading_coeff_pow (p : polynomial R) (n : ℕ) : leading_coeff (p ^ n) = leading_coeff p ^ n := leading_coeff_hom.map_pow p n end no_zero_divisors end polynomial
e5c63f8a2711168a17ba68c60c5629e2c190b107
96e44fc78cabfc9d646dc37d0e756189b6b79181
/library/init/meta/interactive.lean
7ca4dd82f6644e5c0f21ee572302f2943f2ee189
[ "Apache-2.0" ]
permissive
TwoFX/lean
23c73c10a340f5a381f6abf27a27f53f1fb7e2e3
7e3f336714055869690b7309b6bb651fbc67e76e
refs/heads/master
1,612,504,908,183
1,594,641,622,000
1,594,641,622,000
243,750,847
0
0
Apache-2.0
1,582,890,661,000
1,582,890,661,000
null
UTF-8
Lean
false
false
71,322
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, Jannis Limperg -/ prelude import init.meta.tactic init.meta.rewrite_tactic init.meta.simp_tactic import init.meta.smt.congruence_closure init.control.combinators import init.meta.interactive_base init.meta.derive init.meta.match_tactic import init.meta.congr_tactic init.meta.case_tag open lean open lean.parser open native local postfix `?`:9001 := optional local postfix *:9001 := many namespace tactic /- allows metavars -/ meta def i_to_expr (q : pexpr) : tactic expr := to_expr q tt /- allow metavars and no subgoals -/ meta def i_to_expr_no_subgoals (q : pexpr) : tactic expr := to_expr q tt ff /- doesn't allows metavars -/ meta def i_to_expr_strict (q : pexpr) : tactic expr := to_expr q ff /- Auxiliary version of i_to_expr for apply-like tactics. This is a workaround for comment https://github.com/leanprover/lean/issues/1342#issuecomment-307912291 at issue #1342. In interactive mode, given a tactic apply f we want the apply tactic to create all metavariables. The following definition will return `@f` for `f`. That is, it will **not** create metavariables for implicit arguments. Before we added `i_to_expr_for_apply`, the tactic apply le_antisymm would first elaborate `le_antisymm`, and create @le_antisymm ?m_1 ?m_2 ?m_3 ?m_4 The type class resolution problem ?m_2 : weak_order ?m_1 by the elaborator since ?m_1 is not assigned yet, and the problem is discarded. Then, we would invoke `apply_core`, which would create two new metavariables for the explicit arguments, and try to unify the resulting type with the current target. After the unification, the metavariables ?m_1, ?m_3 and ?m_4 are assigned, but we lost the information about the pending type class resolution problem. With `i_to_expr_for_apply`, `le_antisymm` is elaborate into `@le_antisymm`, the apply_core tactic creates all metavariables, and solves the ones that can be solved by type class resolution. Another possible fix: we modify the elaborator to return pending type class resolution problems, and store them in the tactic_state. -/ meta def i_to_expr_for_apply (q : pexpr) : tactic expr := let aux (n : name) : tactic expr := do p ← resolve_name n, match p with | (expr.const c []) := do r ← mk_const c, save_type_info r q, return r | _ := i_to_expr p end in match q with | (expr.const c []) := aux c | (expr.local_const c _ _ _) := aux c | _ := i_to_expr q end namespace interactive open interactive interactive.types expr /-- itactic: parse a nested "interactive" tactic. That is, parse `{` tactic `}` -/ meta def itactic : Type := tactic unit meta def propagate_tags (tac : tactic unit) : tactic unit := do tag ← get_main_tag, if tag = [] then tac else focus1 $ do tac, gs ← get_goals, when (bnot gs.empty) $ do new_tag ← get_main_tag, when new_tag.empty $ with_enable_tags (set_main_tag tag) meta def concat_tags (tac : tactic (list (name × expr))) : tactic unit := mcond tags_enabled (do in_tag ← get_main_tag, r ← tac, /- remove assigned metavars -/ r ← r.mfilter $ λ ⟨n, m⟩, bnot <$> is_assigned m, match r with | [(_, m)] := set_tag m in_tag /- if there is only new subgoal, we just propagate `in_tag` -/ | _ := r.mmap' (λ ⟨n, m⟩, set_tag m (n::in_tag)) end) (tac >> skip) /-- If the current goal is a Pi/forall `∀ x : t, u` (resp. `let x := t in u`) then `intro` puts `x : t` (resp. `x := t`) in the local context. The new subgoal target is `u`. If the goal is an arrow `t → u`, then it puts `h : t` in the local context and the new goal target is `u`. If the goal is neither a Pi/forall nor begins with a let binder, the tactic `intro` applies the tactic `whnf` until an introduction can be applied or the goal is not head reducible. In the latter case, the tactic fails. -/ meta def intro : parse ident_? → tactic unit | none := propagate_tags (intro1 >> skip) | (some h) := propagate_tags (tactic.intro h >> skip) /-- Similar to `intro` tactic. The tactic `intros` will keep introducing new hypotheses until the goal target is not a Pi/forall or let binder. The variant `intros h₁ ... hₙ` introduces `n` new hypotheses using the given identifiers to name them. -/ meta def intros : parse ident_* → tactic unit | [] := propagate_tags (tactic.intros >> skip) | hs := propagate_tags (intro_lst hs >> skip) /-- The tactic `introv` allows the user to automatically introduce the variables of a theorem and explicitly name the hypotheses involved. The given names are used to name non-dependent hypotheses. Examples: ``` example : ∀ a b : nat, a = b → b = a := begin introv h, exact h.symm end ``` The state after `introv h` is ``` a b : ℕ, h : a = b ⊢ b = a ``` ``` example : ∀ a b : nat, a = b → ∀ c, b = c → a = c := begin introv h₁ h₂, exact h₁.trans h₂ end ``` The state after `introv h₁ h₂` is ``` a b : ℕ, h₁ : a = b, c : ℕ, h₂ : b = c ⊢ a = c ``` -/ meta def introv (ns : parse ident_*) : tactic unit := propagate_tags (tactic.introv ns >> return ()) /-- Parse a current name and new name for `rename`. -/ private meta def rename_arg_parser : parser (name × name) := prod.mk <$> ident <*> (optional (tk "->") *> ident) /-- Parse the arguments of `rename`. -/ private meta def rename_args_parser : parser (list (name × name)) := (functor.map (λ x, [x]) rename_arg_parser) <|> (tk "[" *> sep_by (tk ",") rename_arg_parser <* tk "]") /-- Rename one or more local hypotheses. The renamings are given as follows: ``` rename x y -- rename x to y rename x → y -- ditto rename [x y, a b] -- rename x to y and a to b rename [x → y, a → b] -- ditto ``` Note that if there are multiple hypotheses called `x` in the context, then `rename x y` will rename *all* of them. If you want to rename only one, use `dedup` first. -/ meta def rename (renames : parse rename_args_parser) : tactic unit := propagate_tags $ tactic.rename_many $ native.rb_map.of_list renames /-- The `apply` tactic tries to match the current goal against the conclusion of the type of term. The argument term should be a term well-formed in the local context of the main goal. If it succeeds, then the tactic returns as many subgoals as the number of premises that have not been fixed by type inference or type class resolution. Non-dependent premises are added before dependent ones. The `apply` tactic uses higher-order pattern matching, type class resolution, and first-order unification with dependent types. -/ meta def apply (q : parse texpr) : tactic unit := concat_tags (do h ← i_to_expr_for_apply q, tactic.apply h) /-- Similar to the `apply` tactic, but does not reorder goals. -/ meta def fapply (q : parse texpr) : tactic unit := concat_tags (i_to_expr_for_apply q >>= tactic.fapply) /-- Similar to the `apply` tactic, but only creates subgoals for non-dependent premises that have not been fixed by type inference or type class resolution. -/ meta def eapply (q : parse texpr) : tactic unit := concat_tags (i_to_expr_for_apply q >>= tactic.eapply) /-- Similar to the `apply` tactic, but allows the user to provide a `apply_cfg` configuration object. -/ meta def apply_with (q : parse parser.pexpr) (cfg : apply_cfg) : tactic unit := concat_tags (do e ← i_to_expr_for_apply q, tactic.apply e cfg) /-- Similar to the `apply` tactic, but uses matching instead of unification. `apply_match t` is equivalent to `apply_with t {unify := ff}` -/ meta def mapply (q : parse texpr) : tactic unit := concat_tags (do e ← i_to_expr_for_apply q, tactic.apply e {unify := ff}) /-- This tactic tries to close the main goal `... ⊢ t` by generating a term of type `t` using type class resolution. -/ meta def apply_instance : tactic unit := tactic.apply_instance /-- This tactic behaves like `exact`, but with a big difference: the user can put underscores `_` in the expression as placeholders for holes that need to be filled, and `refine` will generate as many subgoals as there are holes. Note that some holes may be implicit. The type of each hole must either be synthesized by the system or declared by an explicit type ascription like `(_ : nat → Prop)`. -/ meta def refine (q : parse texpr) : tactic unit := tactic.refine q /-- This tactic looks in the local context for a hypothesis whose type is equal to the goal target. If it finds one, it uses it to prove the goal, and otherwise it fails. -/ meta def assumption : tactic unit := tactic.assumption /-- Try to apply `assumption` to all goals. -/ meta def assumption' : tactic unit := tactic.any_goals' tactic.assumption private meta def change_core (e : expr) : option expr → tactic unit | none := tactic.change e | (some h) := do num_reverted : ℕ ← revert h, expr.pi n bi d b ← target, tactic.change $ expr.pi n bi e b, intron num_reverted /-- `change u` replaces the target `t` of the main goal to `u` provided that `t` is well formed with respect to the local context of the main goal and `t` and `u` are definitionally equal. `change u at h` will change a local hypothesis to `u`. `change t with u at h1 h2 ...` will replace `t` with `u` in all the supplied hypotheses (or `*`), or in the goal if no `at` clause is specified, provided that `t` and `u` are definitionally equal. -/ meta def change (q : parse texpr) : parse (tk "with" *> texpr)? → parse location → tactic unit | none (loc.ns [none]) := do e ← i_to_expr q, change_core e none | none (loc.ns [some h]) := do eq ← i_to_expr q, eh ← get_local h, change_core eq (some eh) | none _ := fail "change-at does not support multiple locations" | (some w) l := do u ← mk_meta_univ, ty ← mk_meta_var (sort u), eq ← i_to_expr ``(%%q : %%ty), ew ← i_to_expr ``(%%w : %%ty), let repl := λe : expr, e.replace (λ a n, if a = eq then some ew else none), l.try_apply (λh, do e ← infer_type h, change_core (repl e) (some h)) (do g ← target, change_core (repl g) none) /-- This tactic provides an exact proof term to solve the main goal. If `t` is the goal and `p` is a term of type `u` then `exact p` succeeds if and only if `t` and `u` can be unified. -/ meta def exact (q : parse texpr) : tactic unit := do tgt : expr ← target, i_to_expr_strict ``(%%q : %%tgt) >>= tactic.exact /-- Like `exact`, but takes a list of terms and checks that all goals are discharged after the tactic. -/ meta def exacts : parse pexpr_list_or_texpr → tactic unit | [] := done | (t :: ts) := exact t >> exacts ts /-- A synonym for `exact` that allows writing `have/suffices/show ..., from ...` in tactic mode. -/ meta def «from» := exact /-- `revert h₁ ... hₙ` applies to any goal with hypotheses `h₁` ... `hₙ`. It moves the hypotheses and their dependencies to the target of the goal. This tactic is the inverse of `intro`. -/ meta def revert (ids : parse ident*) : tactic unit := propagate_tags (do hs ← mmap tactic.get_local ids, revert_lst hs, skip) private meta def resolve_name' (n : name) : tactic expr := do { p ← resolve_name n, match p with | expr.const n _ := mk_const n -- create metavars for universe levels | _ := i_to_expr p end } /- Version of to_expr that tries to bypass the elaborator if `p` is just a constant or local constant. This is not an optimization, by skipping the elaborator we make sure that no unwanted resolution is used. Example: the elaborator will force any unassigned ?A that must have be an instance of (has_one ?A) to nat. Remark: another benefit is that auxiliary temporary metavariables do not appear in error messages. -/ meta def to_expr' (p : pexpr) : tactic expr := match p with | (const c []) := do new_e ← resolve_name' c, save_type_info new_e p, return new_e | (local_const c _ _ _) := do new_e ← resolve_name' c, save_type_info new_e p, return new_e | _ := i_to_expr p end @[derive has_reflect] meta structure rw_rule := (pos : pos) (symm : bool) (rule : pexpr) meta def get_rule_eqn_lemmas (r : rw_rule) : tactic (list name) := let aux (n : name) : tactic (list name) := do { p ← resolve_name n, -- unpack local refs let e := p.erase_annotations.get_app_fn.erase_annotations, match e with | const n _ := get_eqn_lemmas_for tt n | _ := return [] end } <|> return [] in match r.rule with | const n _ := aux n | local_const n _ _ _ := aux n | _ := return [] end private meta def rw_goal (cfg : rewrite_cfg) (rs : list rw_rule) : tactic unit := rs.mmap' $ λ r, do save_info r.pos, eq_lemmas ← get_rule_eqn_lemmas r, orelse' (do e ← to_expr' r.rule, rewrite_target e {symm := r.symm, ..cfg}) (eq_lemmas.mfirst $ λ n, do e ← mk_const n, rewrite_target e {symm := r.symm, ..cfg}) (eq_lemmas.empty) private meta def uses_hyp (e : expr) (h : expr) : bool := e.fold ff $ λ t _ r, r || to_bool (t = h) private meta def rw_hyp (cfg : rewrite_cfg) : list rw_rule → expr → tactic unit | [] hyp := skip | (r::rs) hyp := do save_info r.pos, eq_lemmas ← get_rule_eqn_lemmas r, orelse' (do e ← to_expr' r.rule, when (not (uses_hyp e hyp)) $ rewrite_hyp e hyp {symm := r.symm, ..cfg} >>= rw_hyp rs) (eq_lemmas.mfirst $ λ n, do e ← mk_const n, rewrite_hyp e hyp {symm := r.symm, ..cfg} >>= rw_hyp rs) (eq_lemmas.empty) meta def rw_rule_p (ep : parser pexpr) : parser rw_rule := rw_rule.mk <$> cur_pos <*> (option.is_some <$> (with_desc "←" (tk "←" <|> tk "<-"))?) <*> ep @[derive has_reflect] meta structure rw_rules_t := (rules : list rw_rule) (end_pos : option pos) -- accepts the same content as `pexpr_list_or_texpr`, but with correct goal info pos annotations meta def rw_rules : parser rw_rules_t := (tk "[" *> rw_rules_t.mk <$> sep_by (skip_info (tk ",")) (set_goal_info_pos $ rw_rule_p (parser.pexpr 0)) <*> (some <$> cur_pos <* set_goal_info_pos (tk "]"))) <|> rw_rules_t.mk <$> (list.ret <$> rw_rule_p texpr) <*> return none private meta def rw_core (rs : parse rw_rules) (loca : parse location) (cfg : rewrite_cfg) : tactic unit := match loca with | loc.wildcard := loca.try_apply (rw_hyp cfg rs.rules) (rw_goal cfg rs.rules) | _ := loca.apply (rw_hyp cfg rs.rules) (rw_goal cfg rs.rules) end >> try (reflexivity reducible) >> (returnopt rs.end_pos >>= save_info <|> skip) /-- `rewrite e` applies identity `e` as a rewrite rule to the target of the main goal. If `e` is preceded by left arrow (`←` or `<-`), the rewrite is applied in the reverse direction. If `e` is a defined constant, then the equational lemmas associated with `e` are used. This provides a convenient way to unfold `e`. `rewrite [e₁, ..., eₙ]` applies the given rules sequentially. `rewrite e at l` rewrites `e` at location(s) `l`, where `l` is either `*` or a list of hypotheses in the local context. In the latter case, a turnstile `⊢` or `|-` can also be used, to signify the target of the goal. -/ meta def rewrite (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {}) : tactic unit := propagate_tags (rw_core q l cfg) /-- An abbreviation for `rewrite`. -/ meta def rw (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {}) : tactic unit := propagate_tags (rw_core q l cfg) /-- `rewrite` followed by `assumption`. -/ meta def rwa (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {}) : tactic unit := rewrite q l cfg >> try assumption /-- A variant of `rewrite` that uses the unifier more aggressively, unfolding semireducible definitions. -/ meta def erewrite (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {md := semireducible}) : tactic unit := propagate_tags (rw_core q l cfg) /-- An abbreviation for `erewrite`. -/ meta def erw (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {md := semireducible}) : tactic unit := propagate_tags (rw_core q l cfg) /-- Returns the unique names of all hypotheses (local constants) in the context. -/ private meta def hyp_unique_names : tactic name_set := do ctx ← local_context, pure $ ctx.foldl (λ r h, r.insert h.local_uniq_name) mk_name_set /-- Returns all hypotheses (local constants) from the context except those whose unique names are in `hyp_uids`. -/ private meta def hyps_except (hyp_uids : name_set) : tactic (list expr) := do ctx ← local_context, pure $ ctx.filter (λ (h : expr), ¬ hyp_uids.contains h.local_uniq_name) /-- Apply `t` to the main goal and revert any new hypothesis in the generated goals. If `t` is a supported tactic or chain of supported tactics (e.g. `induction`, `cases`, `apply`, `constructor`), the generated goals are also tagged with case tags. You can then use `case` to focus such tagged goals. Two typical uses of `with_cases`: 1. Applying a custom eliminator: ``` lemma my_nat_rec : ∀ n {P : ℕ → Prop} (zero : P 0) (succ : ∀ n, P n → P (n + 1)), P n := ... example (n : ℕ) : n = n := begin with_cases { apply my_nat_rec n }, case zero { refl }, case succ : m ih { refl } end ``` 2. Enabling the use of `case` after a chain of case-splitting tactics: ``` example (n m : ℕ) : unit := begin with_cases { cases n; induction m }, case nat.zero nat.zero { exact () }, case nat.zero nat.succ : k { exact () }, case nat.succ nat.zero : i { exact () }, case nat.succ nat.succ : k i ih_i { exact () } end ``` -/ meta def with_cases (t : itactic) : tactic unit := with_enable_tags $ focus1 $ do input_hyp_uids ← hyp_unique_names, t, all_goals' $ do in_tag ← get_main_tag, new_hyps ← hyps_except input_hyp_uids, n ← revert_lst new_hyps, set_main_tag (case_tag.from_tag_pi in_tag n).render private meta def generalize_arg_p_aux : pexpr → parser (pexpr × name) | (app (app (macro _ [const `eq _ ]) h) (local_const x _ _ _)) := pure (h, x) | _ := fail "parse error" private meta def generalize_arg_p : parser (pexpr × name) := with_desc "expr = id" $ parser.pexpr 0 >>= generalize_arg_p_aux /-- `generalize : e = x` replaces all occurrences of `e` in the target with a new hypothesis `x` of the same type. `generalize h : e = x` in addition registers the hypothesis `h : e = x`. -/ meta def generalize (h : parse ident?) (_ : parse $ tk ":") (p : parse generalize_arg_p) : tactic unit := propagate_tags $ do let (p, x) := p, e ← i_to_expr p, some h ← pure h | tactic.generalize e x >> intro1 >> skip, tgt ← target, -- if generalizing fails, fall back to not replacing anything tgt' ← do { ⟨tgt', _⟩ ← solve_aux tgt (tactic.generalize e x >> target), to_expr ``(Π x, %%e = x → %%(tgt'.binding_body.lift_vars 0 1)) } <|> to_expr ``(Π x, %%e = x → %%tgt), t ← assert h tgt', swap, exact ``(%%t %%e rfl), intro x, intro h meta def cases_arg_p : parser (option name × pexpr) := with_desc "(id :)? expr" $ do t ← texpr, match t with | (local_const x _ _ _) := (tk ":" *> do t ← texpr, pure (some x, t)) <|> pure (none, t) | _ := pure (none, t) end /-- Updates the tags of new subgoals produced by `cases` or `induction`. `in_tag` is the initial tag, i.e. the tag of the goal on which `cases`/`induction` was applied. `rs` should contain, for each subgoal, the constructor name associated with that goal and the hypotheses that were introduced. -/ private meta def set_cases_tags (in_tag : tag) (rs : list (name × list expr)) : tactic unit := do gs ← get_goals, match gs with -- if only one goal was produced, we should not make the tag longer | [g] := set_tag g in_tag | _ := let tgs : list (name × list expr × expr) := rs.map₂ (λ ⟨n, new_hyps⟩ g, ⟨n, new_hyps, g⟩) gs in tgs.mmap' $ λ ⟨n, new_hyps, g⟩, with_enable_tags $ set_tag g $ (case_tag.from_tag_hyps (n :: in_tag) (new_hyps.map expr.local_uniq_name)).render end precedence `generalizing` : 0 /-- Assuming `x` is a variable in the local context with an inductive type, `induction x` applies induction on `x` to the main goal, producing one goal for each constructor of the inductive type, in which the target is replaced by a general instance of that constructor and an inductive hypothesis is added for each recursive argument to the constructor. If the type of an element in the local context depends on `x`, that element is reverted and reintroduced afterward, so that the inductive hypothesis incorporates that hypothesis as well. For example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `induction n` produces one goal with hypothesis `h : P 0` and target `Q 0`, and one goal with hypotheses `h : P (nat.succ a)` and `ih₁ : P a → Q a` and target `Q (nat.succ a)`. Here the names `a` and `ih₁` ire chosen automatically. `induction e`, where `e` is an expression instead of a variable, generalizes `e` in the goal, and then performs induction on the resulting variable. `induction e with y₁ ... yₙ`, where `e` is a variable or an expression, specifies that the sequence of names `y₁ ... yₙ` should be used for the arguments to the constructors and inductive hypotheses, including implicit arguments. If the list does not include enough names for all of the arguments, additional names are generated automatically. If too many names are given, the extra ones are ignored. Underscores can be used in the list, in which case the corresponding names are generated automatically. Note that for long sequences of names, the `case` tactic provides a more convenient naming mechanism. `induction e using r` allows the user to specify the principle of induction that should be used. Here `r` should be a theorem whose result type must be of the form `C t`, where `C` is a bound variable and `t` is a (possibly empty) sequence of bound variables `induction e generalizing z₁ ... zₙ`, where `z₁ ... zₙ` are variables in the local context, generalizes over `z₁ ... zₙ` before applying the induction but then introduces them in each goal. In other words, the net effect is that each inductive hypothesis is generalized. `induction h : t` will introduce an equality of the form `h : t = C x y`, asserting that the input term is equal to the current constructor case, to the context. -/ meta def induction (hp : parse cases_arg_p) (rec_name : parse using_ident) (ids : parse with_ident_list) (revert : parse $ (tk "generalizing" *> ident*)?) : tactic unit := do in_tag ← get_main_tag, focus1 $ do { -- process `h : t` case e ← match hp with | (some h, p) := do x ← get_unused_name, generalize h () (p, x), get_local x | (none, p) := i_to_expr p end, -- generalize major premise e ← if e.is_local_constant then pure e else tactic.generalize e >> intro1, -- generalize major premise args (e, newvars, locals) ← do { none ← pure rec_name | pure (e, [], []), t ← infer_type e, t ← whnf_ginductive t, const n _ ← pure t.get_app_fn | pure (e, [], []), env ← get_env, tt ← pure $ env.is_inductive n | pure (e, [], []), let (locals, nonlocals) := (t.get_app_args.drop $ env.inductive_num_params n).partition (λ arg : expr, arg.is_local_constant), _ :: _ ← pure nonlocals | pure (e, [], []), n ← tactic.revert e, newvars ← nonlocals.mmap $ λ arg, do { n ← revert_kdeps arg, tactic.generalize arg, h ← intro1, intron n, -- now try to clear hypotheses that may have been abstracted away let locals := arg.fold [] (λ e _ acc, if e.is_local_constant then e::acc else acc), locals.mmap' (try ∘ clear), pure h }, intron (n-1), e ← intro1, pure (e, newvars, locals) }, -- revert `generalizing` params (and their dependencies, if any) to_generalize ← (revert.get_or_else []).mmap tactic.get_local, num_generalized ← revert_lst to_generalize, -- perform the induction rs ← tactic.induction e ids rec_name, -- re-introduce the generalized hypotheses gen_hyps ← all_goals $ do { new_hyps ← intron' num_generalized, clear_lst (newvars.map local_pp_name), (e::locals).mmap' (try ∘ clear), pure new_hyps }, set_cases_tags in_tag $ @list.map₂ (name × list expr × list (name × expr)) _ (name × list expr) (λ ⟨n, hyps, _⟩ gen_hyps, ⟨n, hyps ++ gen_hyps⟩) rs gen_hyps } open case_tag.match_result private meta def goals_with_matching_tag (ns : list name) : tactic (list (expr × case_tag) × list (expr × case_tag)) := do gs ← get_goals, (gs : list (expr × tag)) ← gs.mmap (λ g, do t ← get_tag g, pure (g, t)), pure $ gs.foldr (λ ⟨g, t⟩ ⟨exact_matches, suffix_matches⟩, match case_tag.parse t with | none := ⟨exact_matches, suffix_matches⟩ | some t := match case_tag.match_tag ns t with | exact_match := ⟨⟨g, t⟩ :: exact_matches, suffix_matches⟩ | fuzzy_match := ⟨exact_matches, ⟨g, t⟩ :: suffix_matches⟩ | no_match := ⟨exact_matches, suffix_matches⟩ end end) ([], []) private meta def goal_with_matching_tag (ns : list name) : tactic (expr × case_tag) := do ⟨exact_matches, suffix_matches⟩ ← goals_with_matching_tag ns, match exact_matches, suffix_matches with | [] , [] := fail format! "Invalid `case`: there is no goal tagged with suffix {ns}." | [] , [g] := pure g | [] , _ := let tags : list (list name) := suffix_matches.map (λ ⟨_, t⟩, t.case_names.reverse) in fail format! "Invalid `case`: there is more than one goal tagged with suffix {ns}.\nMatching tags: {tags}" | [g], _ := pure g | _ , _ := fail format! "Invalid `case`: there is more than one goal tagged with tag {ns}." end /-- Focuses on a goal ('case') generated by `induction`, `cases` or `with_cases`. The goal is selected by giving one or more names which must match exactly one goal. A goal is matched if the given names are a suffix of its goal tag. Additionally, each name in the sequence can be abbreviated to a suffix of the corresponding name in the goal tag. Thus, a goal with tag ``` nat.zero, list.nil ``` can be selected with any of these invocations (among others): ``` case nat.zero list.nil {...} case nat.zero nil {...} case zero nil {...} case nil {...} ``` Additionally, the form ``` case C : N₀ ... Nₙ {...} ``` can be used to rename hypotheses introduced by the preceding `cases`/`induction`/`with_cases`, using the names `Nᵢ`. For example: ``` example (xs : list ℕ) : xs = xs := begin induction xs, case nil { reflexivity }, case cons : x xs ih { -- x : ℕ, xs : list ℕ, ih : xs = xs reflexivity } end ``` Note that this renaming functionality only work reliably *directly after* an `induction`/`cases`/`with_cases`. If you need to perform additional work after an `induction` or `cases` (e.g. introduce hypotheses in all goals), use `with_cases`. -/ /- TODO `case` could be generalised to work with zero names as well. The form case : x y z { ... } would select the first goal (or the first goal with a case tag), renaming hypotheses to `x, y, z`. The renaming functionality would be available only if the goal has a case tag. -/ meta def case (ns : parse ident_*) (ids : parse $ (tk ":" *> ident_*)?) (tac : itactic) : tactic unit := do ⟨goal, tag⟩ ← goal_with_matching_tag ns, let ids := ids.get_or_else [], let num_ids := ids.length, goals ← get_goals, set_goals $ goal :: goals.filter (≠ goal), match tag with | (case_tag.pi _ num_args) := do intro_lst ids, when (num_ids < num_args) $ intron (num_args - num_ids) | (case_tag.hyps _ new_hyp_names) := do let num_new_hyps := new_hyp_names.length, when (num_ids > num_new_hyps) $ fail format! "Invalid `case`: You gave {num_ids} names, but the case introduces {num_new_hyps} new hypotheses.", let renamings := rb_map.of_list (new_hyp_names.zip ids), propagate_tags $ tactic.rename_many renamings tt tt end, solve1 tac /-- Assuming `x` is a variable in the local context with an inductive type, `destruct x` splits the main goal, producing one goal for each constructor of the inductive type, in which `x` is assumed to be a general instance of that constructor. In contrast to `cases`, the local context is unchanged, i.e. no elements are reverted or introduced. For example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `destruct n` produces one goal with target `n = 0 → Q n`, and one goal with target `∀ (a : ℕ), (λ (w : ℕ), n = w → Q n) (nat.succ a)`. Here the name `a` is chosen automatically. -/ meta def destruct (p : parse texpr) : tactic unit := i_to_expr p >>= tactic.destruct meta def cases_core (e : expr) (ids : list name := []) : tactic unit := do in_tag ← get_main_tag, focus1 $ do rs ← tactic.cases e ids, set_cases_tags in_tag rs /-- Assuming `x` is a variable in the local context with an inductive type, `cases x` splits the main goal, producing one goal for each constructor of the inductive type, in which the target is replaced by a general instance of that constructor. If the type of an element in the local context depends on `x`, that element is reverted and reintroduced afterward, so that the case split affects that hypothesis as well. For example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `cases n` produces one goal with hypothesis `h : P 0` and target `Q 0`, and one goal with hypothesis `h : P (nat.succ a)` and target `Q (nat.succ a)`. Here the name `a` is chosen automatically. `cases e`, where `e` is an expression instead of a variable, generalizes `e` in the goal, and then cases on the resulting variable. `cases e with y₁ ... yₙ`, where `e` is a variable or an expression, specifies that the sequence of names `y₁ ... yₙ` should be used for the arguments to the constructors, including implicit arguments. If the list does not include enough names for all of the arguments, additional names are generated automatically. If too many names are given, the extra ones are ignored. Underscores can be used in the list, in which case the corresponding names are generated automatically. `cases h : e`, where `e` is a variable or an expression, performs cases on `e` as above, but also adds a hypothesis `h : e = ...` to each hypothesis, where `...` is the constructor instance for that particular case. -/ meta def cases : parse cases_arg_p → parse with_ident_list → tactic unit | (none, p) ids := do e ← i_to_expr p, cases_core e ids | (some h, p) ids := do x ← get_unused_name, generalize h () (p, x), hx ← get_local x, cases_core hx ids private meta def find_matching_hyp (ps : list pattern) : tactic expr := any_hyp $ λ h, do type ← infer_type h, ps.mfirst $ λ p, do match_pattern p type, return h /-- `cases_matching p` applies the `cases` tactic to a hypothesis `h : type` if `type` matches the pattern `p`. `cases_matching [p_1, ..., p_n]` applies the `cases` tactic to a hypothesis `h : type` if `type` matches one of the given patterns. `cases_matching* p` more efficient and compact version of `focus1 { repeat { cases_matching p } }`. It is more efficient because the pattern is compiled once. Example: The following tactic destructs all conjunctions and disjunctions in the current goal. ``` cases_matching* [_ ∨ _, _ ∧ _] ``` -/ meta def cases_matching (rec : parse $ (tk "*")?) (ps : parse pexpr_list_or_texpr) : tactic unit := do ps ← ps.mmap pexpr_to_pattern, if rec.is_none then find_matching_hyp ps >>= cases_core else tactic.focus1 $ tactic.repeat $ find_matching_hyp ps >>= cases_core /-- Shorthand for `cases_matching` -/ meta def casesm (rec : parse $ (tk "*")?) (ps : parse pexpr_list_or_texpr) : tactic unit := cases_matching rec ps private meta def try_cases_for_types (type_names : list name) (at_most_one : bool) : tactic unit := any_hyp $ λ h, do I ← expr.get_app_fn <$> (infer_type h >>= head_beta), guard I.is_constant, guard (I.const_name ∈ type_names), tactic.focus1 (cases_core h >> if at_most_one then do n ← num_goals, guard (n <= 1) else skip) /-- `cases_type I` applies the `cases` tactic to a hypothesis `h : (I ...)` `cases_type I_1 ... I_n` applies the `cases` tactic to a hypothesis `h : (I_1 ...)` or ... or `h : (I_n ...)` `cases_type* I` is shorthand for `focus1 { repeat { cases_type I } }` `cases_type! I` only applies `cases` if the number of resulting subgoals is <= 1. Example: The following tactic destructs all conjunctions and disjunctions in the current goal. ``` cases_type* or and ``` -/ meta def cases_type (one : parse $ (tk "!")?) (rec : parse $ (tk "*")?) (type_names : parse ident*) : tactic unit := do type_names ← type_names.mmap resolve_constant, if rec.is_none then try_cases_for_types type_names (bnot one.is_none) else tactic.focus1 $ tactic.repeat $ try_cases_for_types type_names (bnot one.is_none) /-- Tries to solve the current goal using a canonical proof of `true`, or the `reflexivity` tactic, or the `contradiction` tactic. -/ meta def trivial : tactic unit := tactic.triv <|> tactic.reflexivity <|> tactic.contradiction <|> fail "trivial tactic failed" /-- Closes the main goal using `sorry`. -/ meta def admit : tactic unit := tactic.admit /-- Closes the main goal using `sorry`. -/ meta def «sorry» : tactic unit := tactic.admit /-- The contradiction tactic attempts to find in the current local context a hypothesis that is equivalent to an empty inductive type (e.g. `false`), a hypothesis of the form `c_1 ... = c_2 ...` where `c_1` and `c_2` are distinct constructors, or two contradictory hypotheses. -/ meta def contradiction : tactic unit := tactic.contradiction /-- `iterate { t }` repeatedly applies tactic `t` until `t` fails. `iterate { t }` always succeeds. `iterate n { t }` applies `t` `n` times. -/ meta def iterate (n : parse small_nat?) (t : itactic) : tactic unit := match n with | none := tactic.iterate' t | some n := iterate_exactly' n t end /-- `repeat { t }` applies `t` to each goal. If the application succeeds, the tactic is applied recursively to all the generated subgoals until it eventually fails. The recursion stops in a subgoal when the tactic has failed to make progress. The tactic `repeat { t }` never fails. -/ meta def repeat : itactic → tactic unit := tactic.repeat /-- `try { t }` tries to apply tactic `t`, but succeeds whether or not `t` succeeds. -/ meta def try : itactic → tactic unit := tactic.try /-- A do-nothing tactic that always succeeds. -/ meta def skip : tactic unit := tactic.skip /-- `solve1 { t }` applies the tactic `t` to the main goal and fails if it is not solved. -/ meta def solve1 : itactic → tactic unit := tactic.solve1 /-- `abstract id { t }` tries to use tactic `t` to solve the main goal. If it succeeds, it abstracts the goal as an independent definition or theorem with name `id`. If `id` is omitted, a name is generated automatically. -/ meta def abstract (id : parse ident?) (tac : itactic) : tactic unit := tactic.abstract tac id /-- `all_goals { t }` applies the tactic `t` to every goal, and succeeds if each application succeeds. -/ meta def all_goals : itactic → tactic unit := tactic.all_goals' /-- `any_goals { t }` applies the tactic `t` to every goal, and succeeds if at least one application succeeds. -/ meta def any_goals : itactic → tactic unit := tactic.any_goals' /-- `focus { t }` temporarily hides all goals other than the first, applies `t`, and then restores the other goals. It fails if there are no goals. -/ meta def focus (tac : itactic) : tactic unit := tactic.focus1 tac private meta def assume_core (n : name) (ty : pexpr) := do t ← target, when (not $ t.is_pi ∨ t.is_let) whnf_target, t ← target, when (not $ t.is_pi ∨ t.is_let) $ fail "assume tactic failed, Pi/let expression expected", ty ← i_to_expr ty, unify ty t.binding_domain, intro_core n >> skip /-- Assuming the target of the goal is a Pi or a let, `assume h : t` unifies the type of the binder with `t` and introduces it with name `h`, just like `intro h`. If `h` is absent, the tactic uses the name `this`. If `t` is omitted, it will be inferred. `assume (h₁ : t₁) ... (hₙ : tₙ)` introduces multiple hypotheses. Any of the types may be omitted, but the names must be present. -/ meta def «assume» : parse (sum.inl <$> (tk ":" *> texpr) <|> sum.inr <$> parse_binders tac_rbp) → tactic unit | (sum.inl ty) := assume_core `this ty | (sum.inr binders) := binders.mmap' $ λ b, assume_core b.local_pp_name b.local_type /-- `have h : t := p` adds the hypothesis `h : t` to the current goal if `p` a term of type `t`. If `t` is omitted, it will be inferred. `have h : t` adds the hypothesis `h : t` to the current goal and opens a new subgoal with target `t`. The new subgoal becomes the main goal. If `t` is omitted, it will be replaced by a fresh metavariable. If `h` is omitted, the name `this` is used. -/ meta def «have» (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit := let h := h.get_or_else `this in match q₁, q₂ with | some e, some p := do t ← i_to_expr e, v ← i_to_expr ``(%%p : %%t), tactic.assertv h t v | none, some p := do p ← i_to_expr p, tactic.note h none p | some e, none := i_to_expr e >>= tactic.assert h | none, none := do u ← mk_meta_univ, e ← mk_meta_var (sort u), tactic.assert h e end >> skip /-- `let h : t := p` adds the hypothesis `h : t := p` to the current goal if `p` a term of type `t`. If `t` is omitted, it will be inferred. `let h : t` adds the hypothesis `h : t := ?M` to the current goal and opens a new subgoal `?M : t`. The new subgoal becomes the main goal. If `t` is omitted, it will be replaced by a fresh metavariable. If `h` is omitted, the name `this` is used. -/ meta def «let» (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit := let h := h.get_or_else `this in match q₁, q₂ with | some e, some p := do t ← i_to_expr e, v ← i_to_expr ``(%%p : %%t), tactic.definev h t v | none, some p := do p ← i_to_expr p, tactic.pose h none p | some e, none := i_to_expr e >>= tactic.define h | none, none := do u ← mk_meta_univ, e ← mk_meta_var (sort u), tactic.define h e end >> skip /-- `suffices h : t` is the same as `have h : t, tactic.swap`. In other words, it adds the hypothesis `h : t` to the current goal and opens a new subgoal with target `t`. -/ meta def «suffices» (h : parse ident?) (t : parse (tk ":" *> texpr)?) : tactic unit := «have» h t none >> tactic.swap /-- This tactic displays the current state in the tracing buffer. -/ meta def trace_state : tactic unit := tactic.trace_state /-- `trace a` displays `a` in the tracing buffer. -/ meta def trace {α : Type} [has_to_tactic_format α] (a : α) : tactic unit := tactic.trace a /-- `existsi e` will instantiate an existential quantifier in the target with `e` and leave the instantiated body as the new target. More generally, it applies to any inductive type with one constructor and at least two arguments, applying the constructor with `e` as the first argument and leaving the remaining arguments as goals. `existsi [e₁, ..., eₙ]` iteratively does the same for each expression in the list. -/ meta def existsi : parse pexpr_list_or_texpr → tactic unit | [] := return () | (p::ps) := i_to_expr p >>= tactic.existsi >> existsi ps /-- This tactic applies to a goal such that its conclusion is an inductive type (say `I`). It tries to apply each constructor of `I` until it succeeds. -/ meta def constructor : tactic unit := concat_tags tactic.constructor /-- Similar to `constructor`, but only non-dependent premises are added as new goals. -/ meta def econstructor : tactic unit := concat_tags tactic.econstructor /-- Applies the first constructor when the type of the target is an inductive data type with two constructors. -/ meta def left : tactic unit := concat_tags tactic.left /-- Applies the second constructor when the type of the target is an inductive data type with two constructors. -/ meta def right : tactic unit := concat_tags tactic.right /-- Applies the constructor when the type of the target is an inductive data type with one constructor. -/ meta def split : tactic unit := concat_tags tactic.split private meta def constructor_matching_aux (ps : list pattern) : tactic unit := do t ← target, ps.mfirst (λ p, match_pattern p t), constructor meta def constructor_matching (rec : parse $ (tk "*")?) (ps : parse pexpr_list_or_texpr) : tactic unit := do ps ← ps.mmap pexpr_to_pattern, if rec.is_none then constructor_matching_aux ps else tactic.focus1 $ tactic.repeat $ constructor_matching_aux ps /-- Replaces the target of the main goal by `false`. -/ meta def exfalso : tactic unit := tactic.exfalso /-- The `injection` tactic is based on the fact that constructors of inductive data types are injections. That means that if `c` is a constructor of an inductive datatype, and if `(c t₁)` and `(c t₂)` are two terms that are equal then `t₁` and `t₂` are equal too. If `q` is a proof of a statement of conclusion `t₁ = t₂`, then injection applies injectivity to derive the equality of all arguments of `t₁` and `t₂` placed in the same positions. For example, from `(a::b) = (c::d)` we derive `a=c` and `b=d`. To use this tactic `t₁` and `t₂` should be constructor applications of the same constructor. Given `h : a::b = c::d`, the tactic `injection h` adds two new hypothesis with types `a = c` and `b = d` to the main goal. The tactic `injection h with h₁ h₂` uses the names `h₁` and `h₂` to name the new hypotheses. -/ meta def injection (q : parse texpr) (hs : parse with_ident_list) : tactic unit := do e ← i_to_expr q, tactic.injection_with e hs, try assumption /-- `injections with h₁ ... hₙ` iteratively applies `injection` to hypotheses using the names `h₁ ... hₙ`. -/ meta def injections (hs : parse with_ident_list) : tactic unit := do tactic.injections_with hs, try assumption end interactive meta structure simp_config_ext extends simp_config := (discharger : tactic unit := failed) section mk_simp_set open expr interactive.types @[derive has_reflect] meta inductive simp_arg_type : Type | all_hyps : simp_arg_type | except : name → simp_arg_type | expr : pexpr → simp_arg_type | symm_expr : pexpr → simp_arg_type meta instance simp_arg_type_to_tactic_format : has_to_tactic_format simp_arg_type := ⟨λ a, match a with | simp_arg_type.all_hyps := pure "*" | (simp_arg_type.except n) := pure format!"-{n}" | (simp_arg_type.expr e) := i_to_expr_no_subgoals e >>= pp | (simp_arg_type.symm_expr e) := ((++) "←") <$> (i_to_expr_no_subgoals e >>= pp) end⟩ meta def simp_arg : parser simp_arg_type := (tk "*" *> return simp_arg_type.all_hyps) <|> (tk "-" *> simp_arg_type.except <$> ident) <|> (tk "<-" *> simp_arg_type.symm_expr <$> texpr) <|> (simp_arg_type.expr <$> texpr) meta def simp_arg_list : parser (list simp_arg_type) := (tk "*" *> return [simp_arg_type.all_hyps]) <|> list_of simp_arg <|> return [] private meta def resolve_exception_ids (all_hyps : bool) : list name → list name → list name → tactic (list name × list name) | [] gex hex := return (gex.reverse, hex.reverse) | (id::ids) gex hex := do p ← resolve_name id, let e := p.erase_annotations.get_app_fn.erase_annotations, match e with | const n _ := resolve_exception_ids ids (n::gex) hex | local_const n _ _ _ := when (not all_hyps) (fail $ sformat! "invalid local exception {id}, '*' was not used") >> resolve_exception_ids ids gex (n::hex) | _ := fail $ sformat! "invalid exception {id}, unknown identifier" end /-- Decode a list of `simp_arg_type` into lists for each type. This is a backwards-compatibility version of `decode_simp_arg_list_with_symm`. This version fails when an argument of the form `simp_arg_type.symm_expr` is included, so that `simp`-like tactics that do not (yet) support backwards rewriting should properly report an error but function normally on other inputs. -/ meta def decode_simp_arg_list (hs : list simp_arg_type) : tactic $ list pexpr × list name × list name × bool := do (hs, ex, all) ← hs.mfoldl (λ (r : (list pexpr × list name × bool)) h, do let (es, ex, all) := r, match h with | simp_arg_type.all_hyps := pure (es, ex, tt) | simp_arg_type.except id := pure (es, id::ex, all) | simp_arg_type.expr e := pure (e::es, ex, all) | simp_arg_type.symm_expr _ := fail "arguments of the form '←...' are not supported" end) ([], [], ff), (gex, hex) ← resolve_exception_ids all ex [] [], return (hs.reverse, gex, hex, all) /-- Decode a list of `simp_arg_type` into lists for each type. This is the newer version of `decode_simp_arg_list`, and has a new name for backwards compatibility. This version indicates the direction of a `simp` lemma by including a `bool` with the `pexpr`. -/ meta def decode_simp_arg_list_with_symm (hs : list simp_arg_type) : tactic $ list (pexpr × bool) × list name × list name × bool := do let (hs, ex, all) := hs.foldl (λ r h, match r, h with | (es, ex, all), simp_arg_type.all_hyps := (es, ex, tt) | (es, ex, all), simp_arg_type.except id := (es, id::ex, all) | (es, ex, all), simp_arg_type.expr e := ((e, ff)::es, ex, all) | (es, ex, all), simp_arg_type.symm_expr e := ((e, tt)::es, ex, all) end) ([], [], ff), (gex, hex) ← resolve_exception_ids all ex [] [], return (hs.reverse, gex, hex, all) private meta def add_simps : simp_lemmas → list (name × bool) → tactic simp_lemmas | s [] := return s | s (n::ns) := do s' ← s.add_simp n.fst n.snd, add_simps s' ns private meta def report_invalid_simp_lemma {α : Type} (n : name): tactic α := fail format!"invalid simplification lemma '{n}' (use command 'set_option trace.simp_lemmas true' for more details)" private meta def check_no_overload (p : pexpr) : tactic unit := when p.is_choice_macro $ match p with | macro _ ps := fail $ to_fmt "ambiguous overload, possible interpretations" ++ format.join (ps.map (λ p, (to_fmt p).indent 4)) | _ := failed end private meta def simp_lemmas.resolve_and_add (s : simp_lemmas) (u : list name) (n : name) (ref : pexpr) (symm : bool) : tactic (simp_lemmas × list name) := do p ← resolve_name n, check_no_overload p, -- unpack local refs let e := p.erase_annotations.get_app_fn.erase_annotations, match e with | const n _ := (do b ← is_valid_simp_lemma_cnst n, guard b, save_const_type_info n ref, s ← s.add_simp n symm, return (s, u)) <|> (do eqns ← get_eqn_lemmas_for tt n, guard (eqns.length > 0), save_const_type_info n ref, s ← add_simps s (eqns.map (λ e, (e, ff))), return (s, u)) <|> (do env ← get_env, guard (env.is_projection n).is_some, return (s, n::u)) <|> report_invalid_simp_lemma n | _ := (do e ← i_to_expr_no_subgoals p, b ← is_valid_simp_lemma e, guard b, try (save_type_info e ref), s ← s.add e symm, return (s, u)) <|> report_invalid_simp_lemma n end private meta def simp_lemmas.add_pexpr (s : simp_lemmas) (u : list name) (p : pexpr) (symm : bool) : tactic (simp_lemmas × list name) := match p with | (const c []) := simp_lemmas.resolve_and_add s u c p symm | (local_const c _ _ _) := simp_lemmas.resolve_and_add s u c p symm | _ := do new_e ← i_to_expr_no_subgoals p, s ← s.add new_e symm, return (s, u) end private meta def simp_lemmas.append_pexprs : simp_lemmas → list name → list (pexpr × bool) → tactic (simp_lemmas × list name) | s u [] := return (s, u) | s u (l::ls) := do (s, u) ← simp_lemmas.add_pexpr s u l.fst l.snd, simp_lemmas.append_pexprs s u ls meta def mk_simp_set_core (no_dflt : bool) (attr_names : list name) (hs : list simp_arg_type) (at_star : bool) : tactic (bool × simp_lemmas × list name) := do (hs, gex, hex, all_hyps) ← decode_simp_arg_list_with_symm hs, when (all_hyps ∧ at_star ∧ not hex.empty) $ fail "A tactic of the form `simp [*, -h] at *` is currently not supported", s ← join_user_simp_lemmas no_dflt attr_names, -- Erase `h` from the default simp set for calls of the form `simp [←h]`. let to_erase := hs.foldl (λ l h, match h with | (const id _, tt) := id :: l | (local_const id _ _ _, tt) := id :: l | _ := l end ) [], let s := s.erase to_erase, (s, u) ← simp_lemmas.append_pexprs s [] hs, s ← if not at_star ∧ all_hyps then do ctx ← collect_ctx_simps, let ctx := ctx.filter (λ h, h.local_uniq_name ∉ hex), -- remove local exceptions s.append ctx else return s, -- add equational lemmas, if any gex ← gex.mmap (λ n, list.cons n <$> get_eqn_lemmas_for tt n), return (all_hyps, simp_lemmas.erase s $ gex.join, u) meta def mk_simp_set (no_dflt : bool) (attr_names : list name) (hs : list simp_arg_type) : tactic (simp_lemmas × list name) := prod.snd <$> (mk_simp_set_core no_dflt attr_names hs ff) end mk_simp_set namespace interactive open interactive interactive.types expr meta def simp_core_aux (cfg : simp_config) (discharger : tactic unit) (s : simp_lemmas) (u : list name) (hs : list expr) (tgt : bool) : tactic unit := do to_remove ← hs.mfilter $ λ h, do { h_type ← infer_type h, (do (new_h_type, pr) ← simplify s u h_type cfg `eq discharger, assert h.local_pp_name new_h_type, mk_eq_mp pr h >>= tactic.exact >> return tt) <|> (return ff) }, goal_simplified ← if tgt then (simp_target s u cfg discharger >> return tt) <|> (return ff) else return ff, guard (cfg.fail_if_unchanged = ff ∨ to_remove.length > 0 ∨ goal_simplified) <|> fail "simplify tactic failed to simplify", to_remove.mmap' (λ h, try (clear h)) meta def simp_core (cfg : simp_config) (discharger : tactic unit) (no_dflt : bool) (hs : list simp_arg_type) (attr_names : list name) (locat : loc) : tactic unit := match locat with | loc.wildcard := do (all_hyps, s, u) ← mk_simp_set_core no_dflt attr_names hs tt, if all_hyps then tactic.simp_all s u cfg discharger else do hyps ← non_dep_prop_hyps, simp_core_aux cfg discharger s u hyps tt | _ := do (s, u) ← mk_simp_set no_dflt attr_names hs, ns ← locat.get_locals, simp_core_aux cfg discharger s u ns locat.include_goal end >> try tactic.triv >> try (tactic.reflexivity reducible) /-- The `simp` tactic uses lemmas and hypotheses to simplify the main goal target or non-dependent hypotheses. It has many variants. `simp` simplifies the main goal target using lemmas tagged with the attribute `[simp]`. `simp [h₁ h₂ ... hₙ]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and the given `hᵢ`'s, where the `hᵢ`'s are expressions. If `hᵢ` is preceded by left arrow (`←` or `<-`), the simplification is performed in the reverse direction. If an `hᵢ` is a defined constant `f`, then the equational lemmas associated with `f` are used. This provides a convenient way to unfold `f`. `simp [*]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and all hypotheses. `simp *` is a shorthand for `simp [*]`. `simp only [h₁ h₂ ... hₙ]` is like `simp [h₁ h₂ ... hₙ]` but does not use `[simp]` lemmas `simp [-id_1, ... -id_n]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]`, but removes the ones named `idᵢ`. `simp at h₁ h₂ ... hₙ` simplifies the non-dependent hypotheses `h₁ : T₁` ... `hₙ : Tₙ`. The tactic fails if the target or another hypothesis depends on one of them. The token `⊢` or `|-` can be added to the list to include the target. `simp at *` simplifies all the hypotheses and the target. `simp * at *` simplifies target and all (non-dependent propositional) hypotheses using the other hypotheses. `simp with attr₁ ... attrₙ` simplifies the main goal target using the lemmas tagged with any of the attributes `[attr₁]`, ..., `[attrₙ]` or `[simp]`. -/ meta def simp (use_iota_eqn : parse $ (tk "!")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (locat : parse location) (cfg : simp_config_ext := {}) : tactic unit := let cfg := if use_iota_eqn.is_none then cfg else {iota_eqn := tt, ..cfg} in propagate_tags (simp_core cfg.to_simp_config cfg.discharger no_dflt hs attr_names locat) /-- Just construct the simp set and trace it. Used for debugging. -/ meta def trace_simp_set (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) : tactic unit := do (s, _) ← mk_simp_set no_dflt attr_names hs, s.pp >>= trace /-- `simp_intros h₁ h₂ ... hₙ` is similar to `intros h₁ h₂ ... hₙ` except that each hypothesis is simplified as it is introduced, and each introduced hypothesis is used to simplify later ones and the final target. As with `simp`, a list of simplification lemmas can be provided. The modifiers `only` and `with` behave as with `simp`. -/ meta def simp_intros (ids : parse ident_*) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (cfg : simp_intros_config := {}) : tactic unit := do (s, u) ← mk_simp_set no_dflt attr_names hs, when (¬u.empty) (fail (sformat! "simp_intros tactic does not support {u}")), tactic.simp_intros s u ids cfg, try triv >> try (reflexivity reducible) private meta def to_simp_arg_list (symms : list bool) (es : list pexpr) : list simp_arg_type := (symms.zip es).map (λ ⟨s, e⟩, if s then simp_arg_type.symm_expr e else simp_arg_type.expr e) /-- `dsimp` is similar to `simp`, except that it only uses definitional equalities. -/ meta def dsimp (no_dflt : parse only_flag) (es : parse simp_arg_list) (attr_names : parse with_ident_list) (l : parse location) (cfg : dsimp_config := {}) : tactic unit := do (s, u) ← mk_simp_set no_dflt attr_names es, match l with | loc.wildcard := /- Remark: we cannot revert frozen local instances. We disable zeta expansion because to prevent `intron n` from failing. Another option is to put a "marker" at the current target, and implement `intro_upto_marker`. -/ do n ← revert_all, dsimp_target s u {zeta := ff ..cfg}, intron n | _ := l.apply (λ h, dsimp_hyp h s u cfg) (dsimp_target s u cfg) end /-- This tactic applies to a goal whose target has the form `t ~ u` where `~` is a reflexive relation, that is, a relation which has a reflexivity lemma tagged with the attribute `[refl]`. The tactic checks whether `t` and `u` are definitionally equal and then solves the goal. -/ meta def reflexivity : tactic unit := tactic.reflexivity /-- Shorter name for the tactic `reflexivity`. -/ meta def refl : tactic unit := tactic.reflexivity /-- This tactic applies to a goal whose target has the form `t ~ u` where `~` is a symmetric relation, that is, a relation which has a symmetry lemma tagged with the attribute `[symm]`. It replaces the target with `u ~ t`. -/ meta def symmetry : tactic unit := tactic.symmetry /-- This tactic applies to a goal whose target has the form `t ~ u` where `~` is a transitive relation, that is, a relation which has a transitivity lemma tagged with the attribute `[trans]`. `transitivity s` replaces the goal with the two subgoals `t ~ s` and `s ~ u`. If `s` is omitted, then a metavariable is used instead. -/ meta def transitivity (q : parse texpr?) : tactic unit := tactic.transitivity >> match q with | none := skip | some q := do (r, lhs, rhs) ← target_lhs_rhs, i_to_expr q >>= unify rhs end /-- Proves a goal with target `s = t` when `s` and `t` are equal up to the associativity and commutativity of their binary operations. -/ meta def ac_reflexivity : tactic unit := tactic.ac_refl /-- An abbreviation for `ac_reflexivity`. -/ meta def ac_refl : tactic unit := tactic.ac_refl /-- Tries to prove the main goal using congruence closure. -/ meta def cc : tactic unit := tactic.cc /-- Given hypothesis `h : x = t` or `h : t = x`, where `x` is a local constant, `subst h` substitutes `x` by `t` everywhere in the main goal and then clears `h`. -/ meta def subst (q : parse texpr) : tactic unit := i_to_expr q >>= tactic.subst >> try (tactic.reflexivity reducible) /-- Apply `subst` to all hypotheses of the form `h : x = t` or `h : t = x`. -/ meta def subst_vars : tactic unit := tactic.subst_vars /-- `clear h₁ ... hₙ` tries to clear each hypothesis `hᵢ` from the local context. -/ meta def clear : parse ident* → tactic unit := tactic.clear_lst private meta def to_qualified_name_core : name → list name → tactic name | n [] := fail $ "unknown declaration '" ++ to_string n ++ "'" | n (ns::nss) := do curr ← return $ ns ++ n, env ← get_env, if env.contains curr then return curr else to_qualified_name_core n nss private meta def to_qualified_name (n : name) : tactic name := do env ← get_env, if env.contains n then return n else do ns ← open_namespaces, to_qualified_name_core n ns private meta def to_qualified_names : list name → tactic (list name) | [] := return [] | (c::cs) := do new_c ← to_qualified_name c, new_cs ← to_qualified_names cs, return (new_c::new_cs) /-- Similar to `unfold`, but only uses definitional equalities. -/ meta def dunfold (cs : parse ident*) (l : parse location) (cfg : dunfold_config := {}) : tactic unit := match l with | (loc.wildcard) := do ls ← tactic.local_context, n ← revert_lst ls, new_cs ← to_qualified_names cs, dunfold_target new_cs cfg, intron n | _ := do new_cs ← to_qualified_names cs, l.apply (λ h, dunfold_hyp cs h cfg) (dunfold_target new_cs cfg) end private meta def delta_hyps : list name → list name → tactic unit | cs [] := skip | cs (h::hs) := get_local h >>= delta_hyp cs >> delta_hyps cs hs /-- Similar to `dunfold`, but performs a raw delta reduction, rather than using an equation associated with the defined constants. -/ meta def delta : parse ident* → parse location → tactic unit | cs (loc.wildcard) := do ls ← tactic.local_context, n ← revert_lst ls, new_cs ← to_qualified_names cs, delta_target new_cs, intron n | cs l := do new_cs ← to_qualified_names cs, l.apply (delta_hyp new_cs) (delta_target new_cs) private meta def unfold_projs_hyps (cfg : unfold_proj_config := {}) (hs : list name) : tactic bool := hs.mfoldl (λ r h, do h ← get_local h, (unfold_projs_hyp h cfg >> return tt) <|> return r) ff /-- This tactic unfolds all structure projections. -/ meta def unfold_projs (l : parse location) (cfg : unfold_proj_config := {}) : tactic unit := match l with | loc.wildcard := do ls ← local_context, b₁ ← unfold_projs_hyps cfg (ls.map expr.local_pp_name), b₂ ← (tactic.unfold_projs_target cfg >> return tt) <|> return ff, when (not b₁ ∧ not b₂) (fail "unfold_projs failed to simplify") | _ := l.try_apply (λ h, unfold_projs_hyp h cfg) (tactic.unfold_projs_target cfg) <|> fail "unfold_projs failed to simplify" end end interactive meta def ids_to_simp_arg_list (tac_name : name) (cs : list name) : tactic (list simp_arg_type) := cs.mmap $ λ c, do n ← resolve_name c, hs ← get_eqn_lemmas_for ff n.const_name, env ← get_env, let p := env.is_projection n.const_name, when (hs.empty ∧ p.is_none) (fail (sformat! "{tac_name} tactic failed, {c} does not have equational lemmas nor is a projection")), return $ simp_arg_type.expr (expr.const c []) structure unfold_config extends simp_config := (zeta := ff) (proj := ff) (eta := ff) (canonize_instances := ff) (constructor_eq := ff) namespace interactive open interactive interactive.types expr /-- Given defined constants `e₁ ... eₙ`, `unfold e₁ ... eₙ` iteratively unfolds all occurrences in the target of the main goal, using equational lemmas associated with the definitions. As with `simp`, the `at` modifier can be used to specify locations for the unfolding. -/ meta def unfold (cs : parse ident*) (locat : parse location) (cfg : unfold_config := {}) : tactic unit := do es ← ids_to_simp_arg_list "unfold" cs, let no_dflt := tt, simp_core cfg.to_simp_config failed no_dflt es [] locat /-- Similar to `unfold`, but does not iterate the unfolding. -/ meta def unfold1 (cs : parse ident*) (locat : parse location) (cfg : unfold_config := {single_pass := tt}) : tactic unit := unfold cs locat cfg /-- If the target of the main goal is an `opt_param`, assigns the default value. -/ meta def apply_opt_param : tactic unit := tactic.apply_opt_param /-- If the target of the main goal is an `auto_param`, executes the associated tactic. -/ meta def apply_auto_param : tactic unit := tactic.apply_auto_param /-- Fails if the given tactic succeeds. -/ meta def fail_if_success (tac : itactic) : tactic unit := tactic.fail_if_success tac /-- Succeeds if the given tactic fails. -/ meta def success_if_fail (tac : itactic) : tactic unit := tactic.success_if_fail tac meta def guard_expr_eq (t : expr) (p : parse $ tk ":=" *> texpr) : tactic unit := do e ← to_expr p, guard (alpha_eqv t e) /-- `guard_target t` fails if the target of the main goal is not `t`. We use this tactic for writing tests. -/ meta def guard_target (p : parse texpr) : tactic unit := do t ← target, guard_expr_eq t p /-- `guard_hyp h := t` fails if the hypothesis `h` does not have type `t`. We use this tactic for writing tests. -/ meta def guard_hyp (n : parse ident) (p : parse $ tk ":=" *> texpr) : tactic unit := do h ← get_local n >>= infer_type, guard_expr_eq h p /-- `match_target t` fails if target does not match pattern `t`. -/ meta def match_target (t : parse texpr) (m := reducible) : tactic unit := tactic.match_target t m >> skip /-- `by_cases (h :)? p` splits the main goal into two cases, assuming `h : p` in the first branch, and `h : ¬ p` in the second branch. This tactic requires that `p` is decidable. To ensure that all propositions are decidable via classical reasoning, use `local attribute [instance] classical.prop_decidable`. -/ meta def by_cases : parse cases_arg_p → tactic unit | (n, q) := concat_tags $ do p ← tactic.to_expr_strict q, tactic.by_cases p (n.get_or_else `h), pos_g :: neg_g :: rest ← get_goals, return [(`pos, pos_g), (`neg, neg_g)] /-- Apply function extensionality and introduce new hypotheses. The tactic `funext` will keep applying new the `funext` lemma until the goal target is not reducible to ``` |- ((fun x, ...) = (fun x, ...)) ``` The variant `funext h₁ ... hₙ` applies `funext` `n` times, and uses the given identifiers to name the new hypotheses. -/ meta def funext : parse ident_* → tactic unit | [] := tactic.funext >> skip | hs := funext_lst hs >> skip /-- If the target of the main goal is a proposition `p`, `by_contradiction h` reduces the goal to proving `false` using the additional hypothesis `h : ¬ p`. If `h` is omitted, a name is generated automatically. This tactic requires that `p` is decidable. To ensure that all propositions are decidable via classical reasoning, use `local attribute [instance] classical.prop_decidable`. -/ meta def by_contradiction (n : parse ident?) : tactic unit := tactic.by_contradiction n >> return () /-- An abbreviation for `by_contradiction`. -/ meta def by_contra (n : parse ident?) : tactic unit := by_contradiction n /-- Type check the given expression, and trace its type. -/ meta def type_check (p : parse texpr) : tactic unit := do e ← to_expr p, tactic.type_check e, infer_type e >>= trace /-- Fail if there are unsolved goals. -/ meta def done : tactic unit := tactic.done private meta def show_aux (p : pexpr) : list expr → list expr → tactic unit | [] r := fail "show tactic failed" | (g::gs) r := do do {set_goals [g], g_ty ← target, ty ← i_to_expr p, unify g_ty ty, set_goals (g :: r.reverse ++ gs), tactic.change ty} <|> show_aux gs (g::r) /-- `show t` finds the first goal whose target unifies with `t`. It makes that the main goal, performs the unification, and replaces the target with the unified version of `t`. -/ meta def «show» (q : parse texpr) : tactic unit := do gs ← get_goals, show_aux q gs [] /-- The tactic `specialize h a₁ ... aₙ` works on local hypothesis `h`. The premises of this hypothesis, either universal quantifications or non-dependent implications, are instantiated by concrete terms coming either from arguments `a₁` ... `aₙ`. The tactic adds a new hypothesis with the same name `h := h a₁ ... aₙ` and tries to clear the previous one. -/ meta def specialize (p : parse texpr) : tactic unit := do e ← i_to_expr p, let h := expr.get_app_fn e, if h.is_local_constant then tactic.note h.local_pp_name none e >> try (tactic.clear h) else tactic.fail "specialize requires a term of the form `h x_1 .. x_n` where `h` appears in the local context" meta def congr := tactic.congr end interactive end tactic section add_interactive open tactic /- See add_interactive -/ private meta def add_interactive_aux (new_namespace : name) : list name → command | [] := return () | (n::ns) := do env ← get_env, d_name ← resolve_constant n, (declaration.defn _ ls ty val hints trusted) ← env.get d_name, (name.mk_string h _) ← return d_name, let new_name := new_namespace <.> h, add_decl (declaration.defn new_name ls ty (expr.const d_name (ls.map level.param)) hints trusted), do { doc ← doc_string d_name, add_doc_string new_name doc } <|> skip, add_interactive_aux ns /-- Copy a list of meta definitions in the current namespace to tactic.interactive. This command is useful when we want to update tactic.interactive without closing the current namespace. -/ meta def add_interactive (ns : list name) (p : name := `tactic.interactive) : command := add_interactive_aux p ns meta def has_dup : tactic bool := do ctx ← local_context, let p : name_set × bool := ctx.foldl (λ ⟨s, r⟩ h, if r then (s, r) else if s.contains h.local_pp_name then (s, tt) else (s.insert h.local_pp_name, ff)) (mk_name_set, ff), return p.2 /-- Renames hypotheses with the same name. -/ meta def dedup : tactic unit := mwhen has_dup $ do ctx ← local_context, n ← revert_lst ctx, intron n end add_interactive namespace tactic /- Helper tactic for `mk_inj_eq -/ protected meta def apply_inj_lemma : tactic unit := do h ← intro `h, some (lhs, rhs) ← expr.is_eq <$> infer_type h, (expr.const C _) ← return lhs.get_app_fn, -- We disable auto_param and opt_param support to address issue #1943 applyc (name.mk_string "inj" C) {auto_param := ff, opt_param := ff}, assumption /- Auxiliary tactic for proving `I.C.inj_eq` lemmas. These lemmas are automatically generated by the equation compiler. Example: ``` list.cons.inj_eq : forall h1 h2 t1 t2, (h1::t1 = h2::t2) = (h1 = h2 ∧ t1 = t2) := by mk_inj_eq ``` -/ meta def mk_inj_eq : tactic unit := `[ intros, /- We use `_root_.*` in the following tactics because names are resolved at tactic execution time in interactive mode. See PR #1913 TODO(Leo): This is probably not the only instance of this problem. `[ ... ] blocks are convenient to use because they allow us to use the interactive mode to write non interactive tactics. One potential fix for this issue is to resolve names in `[ ... ] at tactic compilation time. After this issue is fixed, we should remove the `_root_.*` workaround. -/ apply _root_.propext, apply _root_.iff.intro, { tactic.apply_inj_lemma }, { intro _, try { cases_matching* _ ∧ _ }, refl <|> { congr; { assumption <|> subst_vars } } } ] end tactic /- Define inj_eq lemmas for inductive datatypes that were declared before `mk_inj_eq` -/ universes u v lemma sum.inl.inj_eq {α : Type u} (β : Type v) (a₁ a₂ : α) : (@sum.inl α β a₁ = sum.inl a₂) = (a₁ = a₂) := by tactic.mk_inj_eq lemma sum.inr.inj_eq (α : Type u) {β : Type v} (b₁ b₂ : β) : (@sum.inr α β b₁ = sum.inr b₂) = (b₁ = b₂) := by tactic.mk_inj_eq lemma psum.inl.inj_eq {α : Sort u} (β : Sort v) (a₁ a₂ : α) : (@psum.inl α β a₁ = psum.inl a₂) = (a₁ = a₂) := by tactic.mk_inj_eq lemma psum.inr.inj_eq (α : Sort u) {β : Sort v} (b₁ b₂ : β) : (@psum.inr α β b₁ = psum.inr b₂) = (b₁ = b₂) := by tactic.mk_inj_eq lemma sigma.mk.inj_eq {α : Type u} {β : α → Type v} (a₁ : α) (b₁ : β a₁) (a₂ : α) (b₂ : β a₂) : (sigma.mk a₁ b₁ = sigma.mk a₂ b₂) = (a₁ = a₂ ∧ b₁ == b₂) := by tactic.mk_inj_eq lemma psigma.mk.inj_eq {α : Sort u} {β : α → Sort v} (a₁ : α) (b₁ : β a₁) (a₂ : α) (b₂ : β a₂) : (psigma.mk a₁ b₁ = psigma.mk a₂ b₂) = (a₁ = a₂ ∧ b₁ == b₂) := by tactic.mk_inj_eq lemma subtype.mk.inj_eq {α : Sort u} {p : α → Prop} (a₁ : α) (h₁ : p a₁) (a₂ : α) (h₂ : p a₂) : (subtype.mk a₁ h₁ = subtype.mk a₂ h₂) = (a₁ = a₂) := by tactic.mk_inj_eq lemma option.some.inj_eq {α : Type u} (a₁ a₂ : α) : (some a₁ = some a₂) = (a₁ = a₂) := by tactic.mk_inj_eq lemma list.cons.inj_eq {α : Type u} (h₁ : α) (t₁ : list α) (h₂ : α) (t₂ : list α) : (list.cons h₁ t₁ = list.cons h₂ t₂) = (h₁ = h₂ ∧ t₁ = t₂) := by tactic.mk_inj_eq lemma nat.succ.inj_eq (n₁ n₂ : nat) : (nat.succ n₁ = nat.succ n₂) = (n₁ = n₂) := by tactic.mk_inj_eq
579f5eca31ae6e9d697bbe6b5ed732868d7a6867
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/set_theory/game/nim.lean
64a8e2d3059891eb9f046c4aeecdcbd5d1bcbfb9
[ "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
15,728
lean
/- Copyright (c) 2020 Fox Thomson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Fox Thomson, Markus Himmel -/ import data.nat.bitwise import set_theory.game.birthday import set_theory.game.impartial /-! # Nim and the Sprague-Grundy theorem This file contains the definition for nim for any ordinal `o`. In the game of `nim o₁` both players may move to `nim o₂` for any `o₂ < o₁`. We also define a Grundy value for an impartial game `G` and prove the Sprague-Grundy theorem, that `G` is equivalent to `nim (grundy_value G)`. Finally, we compute the sum of finite Grundy numbers: if `G` and `H` have Grundy values `n` and `m`, where `n` and `m` are natural numbers, then `G + H` has the Grundy value `n xor m`. ## Implementation details The pen-and-paper definition of nim defines the possible moves of `nim o` to be `set.Iio o`. However, this definition does not work for us because it would make the type of nim `ordinal.{u} → pgame.{u + 1}`, which would make it impossible for us to state the Sprague-Grundy theorem, since that requires the type of `nim` to be `ordinal.{u} → pgame.{u}`. For this reason, we instead use `o.out.α` for the possible moves. You can use `to_left_moves_nim` and `to_right_moves_nim` to convert an ordinal less than `o` into a left or right move of `nim o`, and vice versa. -/ noncomputable theory universe u open_locale pgame namespace pgame /-- The definition of single-heap nim, which can be viewed as a pile of stones where each player can take a positive number of stones from it on their turn. -/ -- Uses `noncomputable!` to avoid `rec_fn_macro only allowed in meta definitions` VM error noncomputable! def nim : ordinal.{u} → pgame.{u} | o₁ := let f := λ o₂, have ordinal.typein o₁.out.r o₂ < o₁ := ordinal.typein_lt_self o₂, nim (ordinal.typein o₁.out.r o₂) in ⟨o₁.out.α, o₁.out.α, f, f⟩ using_well_founded { dec_tac := tactic.assumption } open ordinal lemma nim_def (o : ordinal) : nim o = pgame.mk o.out.α o.out.α (λ o₂, nim (ordinal.typein (<) o₂)) (λ o₂, nim (ordinal.typein (<) o₂)) := by { rw nim, refl } lemma left_moves_nim (o : ordinal) : (nim o).left_moves = o.out.α := by { rw nim_def, refl } lemma right_moves_nim (o : ordinal) : (nim o).right_moves = o.out.α := by { rw nim_def, refl } lemma move_left_nim_heq (o : ordinal) : (nim o).move_left == λ i : o.out.α, nim (typein (<) i) := by { rw nim_def, refl } lemma move_right_nim_heq (o : ordinal) : (nim o).move_right == λ i : o.out.α, nim (typein (<) i) := by { rw nim_def, refl } /-- Turns an ordinal less than `o` into a left move for `nim o` and viceversa. -/ noncomputable def to_left_moves_nim {o : ordinal} : set.Iio o ≃ (nim o).left_moves := (enum_iso_out o).to_equiv.trans (equiv.cast (left_moves_nim o).symm) /-- Turns an ordinal less than `o` into a right move for `nim o` and viceversa. -/ noncomputable def to_right_moves_nim {o : ordinal} : set.Iio o ≃ (nim o).right_moves := (enum_iso_out o).to_equiv.trans (equiv.cast (right_moves_nim o).symm) @[simp] theorem to_left_moves_nim_symm_lt {o : ordinal} (i : (nim o).left_moves) : ↑(to_left_moves_nim.symm i) < o := (to_left_moves_nim.symm i).prop @[simp] theorem to_right_moves_nim_symm_lt {o : ordinal} (i : (nim o).right_moves) : ↑(to_right_moves_nim.symm i) < o := (to_right_moves_nim.symm i).prop @[simp] lemma move_left_nim' {o : ordinal.{u}} (i) : (nim o).move_left i = nim (to_left_moves_nim.symm i).val := (congr_heq (move_left_nim_heq o).symm (cast_heq _ i)).symm lemma move_left_nim {o : ordinal} (i) : (nim o).move_left (to_left_moves_nim i) = nim i := by simp @[simp] lemma move_right_nim' {o : ordinal} (i) : (nim o).move_right i = nim (to_right_moves_nim.symm i).val := (congr_heq (move_right_nim_heq o).symm (cast_heq _ i)).symm lemma move_right_nim {o : ordinal} (i) : (nim o).move_right (to_right_moves_nim i) = nim i := by simp /-- A recursion principle for left moves of a nim game. -/ @[elab_as_eliminator] def left_moves_nim_rec_on {o : ordinal} {P : (nim o).left_moves → Sort*} (i : (nim o).left_moves) (H : ∀ a < o, P $ to_left_moves_nim ⟨a, H⟩) : P i := by { rw ←to_left_moves_nim.apply_symm_apply i, apply H } /-- A recursion principle for right moves of a nim game. -/ @[elab_as_eliminator] def right_moves_nim_rec_on {o : ordinal} {P : (nim o).right_moves → Sort*} (i : (nim o).right_moves) (H : ∀ a < o, P $ to_right_moves_nim ⟨a, H⟩) : P i := by { rw ←to_right_moves_nim.apply_symm_apply i, apply H } instance is_empty_nim_zero_left_moves : is_empty (nim 0).left_moves := by { rw nim_def, exact ordinal.is_empty_out_zero } instance is_empty_nim_zero_right_moves : is_empty (nim 0).right_moves := by { rw nim_def, exact ordinal.is_empty_out_zero } /-- `nim 0` has exactly the same moves as `0`. -/ def nim_zero_relabelling : nim 0 ≡r 0 := relabelling.is_empty _ theorem nim_zero_equiv : nim 0 ≈ 0 := equiv.is_empty _ noncomputable instance unique_nim_one_left_moves : unique (nim 1).left_moves := (equiv.cast $ left_moves_nim 1).unique noncomputable instance unique_nim_one_right_moves : unique (nim 1).right_moves := (equiv.cast $ right_moves_nim 1).unique @[simp] theorem default_nim_one_left_moves_eq : (default : (nim 1).left_moves) = @to_left_moves_nim 1 ⟨0, zero_lt_one⟩ := rfl @[simp] theorem default_nim_one_right_moves_eq : (default : (nim 1).right_moves) = @to_right_moves_nim 1 ⟨0, zero_lt_one⟩ := rfl @[simp] theorem to_left_moves_nim_one_symm (i) : (@to_left_moves_nim 1).symm i = ⟨0, zero_lt_one⟩ := by simp @[simp] theorem to_right_moves_nim_one_symm (i) : (@to_right_moves_nim 1).symm i = ⟨0, zero_lt_one⟩ := by simp theorem nim_one_move_left (x) : (nim 1).move_left x = nim 0 := by simp theorem nim_one_move_right (x) : (nim 1).move_right x = nim 0 := by simp /-- `nim 1` has exactly the same moves as `star`. -/ def nim_one_relabelling : nim 1 ≡r star := begin rw nim_def, refine ⟨_, _, λ i, _, λ j, _⟩, any_goals { dsimp, apply equiv.equiv_of_unique }, all_goals { simp, exact nim_zero_relabelling } end theorem nim_one_equiv : nim 1 ≈ star := nim_one_relabelling.equiv @[simp] lemma nim_birthday (o : ordinal) : (nim o).birthday = o := begin induction o using ordinal.induction with o IH, rw [nim_def, birthday_def], dsimp, rw max_eq_right le_rfl, convert lsub_typein o, exact funext (λ i, IH _ (typein_lt_self i)) end @[simp] lemma neg_nim (o : ordinal) : -nim o = nim o := begin induction o using ordinal.induction with o IH, rw nim_def, dsimp; congr; funext i; exact IH _ (ordinal.typein_lt_self i) end instance nim_impartial (o : ordinal) : impartial (nim o) := begin induction o using ordinal.induction with o IH, rw [impartial_def, neg_nim], refine ⟨equiv_rfl, λ i, _, λ i, _⟩; simpa using IH _ (typein_lt_self _) end lemma exists_ordinal_move_left_eq {o : ordinal} (i) : ∃ o' < o, (nim o).move_left i = nim o' := ⟨_, typein_lt_self _, move_left_nim' i⟩ lemma exists_move_left_eq {o o' : ordinal} (h : o' < o) : ∃ i, (nim o).move_left i = nim o' := ⟨to_left_moves_nim ⟨o', h⟩, by simp⟩ lemma nim_fuzzy_zero_of_ne_zero {o : ordinal} (ho : o ≠ 0) : nim o ‖ 0 := begin rw [impartial.fuzzy_zero_iff_lf, nim_def, lf_zero_le], rw ←ordinal.pos_iff_ne_zero at ho, exact ⟨(ordinal.principal_seg_out ho).top, by simp⟩ end @[simp] lemma nim_add_equiv_zero_iff (o₁ o₂ : ordinal) : nim o₁ + nim o₂ ≈ 0 ↔ o₁ = o₂ := begin split, { refine not_imp_not.1 (λ (h : _ ≠ _), (impartial.not_equiv_zero_iff _).2 _), obtain h | h := h.lt_or_lt, { rw [impartial.fuzzy_zero_iff_gf, zero_lf_le, nim_def o₂], refine ⟨to_left_moves_add (sum.inr _), _⟩, { exact (ordinal.principal_seg_out h).top }, { simpa using (impartial.add_self (nim o₁)).2 } }, { rw [impartial.fuzzy_zero_iff_gf, zero_lf_le, nim_def o₁], refine ⟨to_left_moves_add (sum.inl _), _⟩, { exact (ordinal.principal_seg_out h).top }, { simpa using (impartial.add_self (nim o₂)).2 } } }, { rintro rfl, exact impartial.add_self (nim o₁) } end @[simp] lemma nim_add_fuzzy_zero_iff {o₁ o₂ : ordinal} : nim o₁ + nim o₂ ‖ 0 ↔ o₁ ≠ o₂ := by rw [iff_not_comm, impartial.not_fuzzy_zero_iff, nim_add_equiv_zero_iff] @[simp] lemma nim_equiv_iff_eq {o₁ o₂ : ordinal} : nim o₁ ≈ nim o₂ ↔ o₁ = o₂ := by rw [impartial.equiv_iff_add_equiv_zero, nim_add_equiv_zero_iff] /-- The Grundy value of an impartial game, the ordinal which corresponds to the game of nim that the game is equivalent to -/ noncomputable def grundy_value : Π (G : pgame.{u}), ordinal.{u} | G := ordinal.mex.{u u} (λ i, grundy_value (G.move_left i)) using_well_founded { dec_tac := pgame_wf_tac } lemma grundy_value_eq_mex_left (G : pgame) : grundy_value G = ordinal.mex.{u u} (λ i, grundy_value (G.move_left i)) := by rw grundy_value /-- The Sprague-Grundy theorem which states that every impartial game is equivalent to a game of nim, namely the game of nim corresponding to the games Grundy value -/ theorem equiv_nim_grundy_value : ∀ (G : pgame.{u}) [G.impartial], G ≈ nim (grundy_value G) | G := begin introI hG, rw [impartial.equiv_iff_add_equiv_zero, ←impartial.forall_left_moves_fuzzy_iff_equiv_zero], intro i, apply left_moves_add_cases i, { intro i₁, rw add_move_left_inl, apply (fuzzy_congr_left (add_congr_left (equiv_nim_grundy_value (G.move_left i₁)).symm)).1, rw nim_add_fuzzy_zero_iff, intro heq, rw [eq_comm, grundy_value_eq_mex_left G] at heq, have h := ordinal.ne_mex _, rw heq at h, exact (h i₁).irrefl }, { intro i₂, rw [add_move_left_inr, ←impartial.exists_left_move_equiv_iff_fuzzy_zero], revert i₂, rw nim_def, intro i₂, have h' : ∃ i : G.left_moves, (grundy_value (G.move_left i)) = ordinal.typein (quotient.out (grundy_value G)).r i₂, { revert i₂, rw grundy_value_eq_mex_left, intros i₂, have hnotin : _ ∉ _ := λ hin, (le_not_le_of_lt (ordinal.typein_lt_self i₂)).2 (cInf_le' hin), simpa using hnotin}, cases h' with i hi, use to_left_moves_add (sum.inl i), rw [add_move_left_inl, move_left_mk], apply (add_congr_left (equiv_nim_grundy_value (G.move_left i))).trans, simpa only [hi] using impartial.add_self (nim (grundy_value (G.move_left i))) } end using_well_founded { dec_tac := pgame_wf_tac } lemma grundy_value_eq_iff_equiv_nim {G : pgame} [G.impartial] {o : ordinal} : grundy_value G = o ↔ G ≈ nim o := ⟨by { rintro rfl, exact equiv_nim_grundy_value G }, by { intro h, rw ←nim_equiv_iff_eq, exact (equiv_nim_grundy_value G).symm.trans h }⟩ @[simp] lemma nim_grundy_value (o : ordinal.{u}) : grundy_value (nim o) = o := grundy_value_eq_iff_equiv_nim.2 pgame.equiv_rfl lemma grundy_value_eq_iff_equiv (G H : pgame) [G.impartial] [H.impartial] : grundy_value G = grundy_value H ↔ G ≈ H := grundy_value_eq_iff_equiv_nim.trans (equiv_congr_left.1 (equiv_nim_grundy_value H) _).symm @[simp] lemma grundy_value_zero : grundy_value 0 = 0 := grundy_value_eq_iff_equiv_nim.2 nim_zero_equiv.symm lemma grundy_value_iff_equiv_zero (G : pgame) [G.impartial] : grundy_value G = 0 ↔ G ≈ 0 := by rw [←grundy_value_eq_iff_equiv, grundy_value_zero] @[simp] lemma grundy_value_star : grundy_value star = 1 := grundy_value_eq_iff_equiv_nim.2 nim_one_equiv.symm @[simp] lemma grundy_value_neg (G : pgame) [G.impartial] : grundy_value (-G) = grundy_value G := by rw [grundy_value_eq_iff_equiv_nim, neg_equiv_iff, neg_nim, ←grundy_value_eq_iff_equiv_nim] lemma grundy_value_eq_mex_right : ∀ (G : pgame) [G.impartial], grundy_value G = ordinal.mex.{u u} (λ i, grundy_value (G.move_right i)) | ⟨l, r, L, R⟩ := begin introI H, rw [←grundy_value_neg, grundy_value_eq_mex_left], congr, ext i, haveI : (R i).impartial := @impartial.move_right_impartial ⟨l, r, L, R⟩ _ i, apply grundy_value_neg end @[simp] lemma grundy_value_nim_add_nim (n m : ℕ) : grundy_value (nim.{u} n + nim.{u} m) = nat.lxor n m := begin induction n using nat.strong_induction_on with n hn generalizing m, induction m using nat.strong_induction_on with m hm, rw [grundy_value_eq_mex_left], -- We want to show that `n xor m` is the smallest unreachable Grundy value. We will do this in two -- steps: -- h₀: `n xor m` is not a reachable grundy number. -- h₁: every Grundy number strictly smaller than `n xor m` is reachable. have h₀ : ∀ i, grundy_value ((nim n + nim m).move_left i) ≠ (nat.lxor n m : ordinal), { -- To show that `n xor m` is unreachable, we show that every move produces a Grundy number -- different from `n xor m`. intro i, -- The move operates either on the left pile or on the right pile. apply left_moves_add_cases i, all_goals { -- One of the piles is reduced to `k` stones, with `k < n` or `k < m`. intro a, obtain ⟨ok, hk, hk'⟩ := exists_ordinal_move_left_eq a, obtain ⟨k, rfl⟩ := ordinal.lt_omega.1 (lt_trans hk (ordinal.nat_lt_omega _)), replace hk := ordinal.nat_cast_lt.1 hk, -- Thus, the problem is reduced to computing the Grundy value of `nim n + nim k` or -- `nim k + nim m`, both of which can be dealt with using an inductive hypothesis. simp only [hk', add_move_left_inl, add_move_left_inr, id], rw hn _ hk <|> rw hm _ hk, -- But of course xor is injective, so if we change one of the arguments, we will not get the -- same value again. intro h, rw ordinal.nat_cast_inj at h, try { rw [nat.lxor_comm n k, nat.lxor_comm n m] at h }, exact hk.ne (nat.lxor_left_injective h) } }, have h₁ : ∀ (u : ordinal), u < nat.lxor n m → u ∈ set.range (λ i, grundy_value ((nim n + nim m).move_left i)), { -- Take any natural number `u` less than `n xor m`. intros ou hu, obtain ⟨u, rfl⟩ := ordinal.lt_omega.1 (lt_trans hu (ordinal.nat_lt_omega _)), replace hu := ordinal.nat_cast_lt.1 hu, -- Our goal is to produce a move that gives the Grundy value `u`. rw set.mem_range, -- By a lemma about xor, either `u xor m < n` or `u xor n < m`. cases nat.lt_lxor_cases hu with h h, -- Therefore, we can play the corresponding move, and by the inductive hypothesis the new state -- is `(u xor m) xor m = u` or `n xor (u xor n) = u` as required. { obtain ⟨i, hi⟩ := exists_move_left_eq (ordinal.nat_cast_lt.2 h), refine ⟨to_left_moves_add (sum.inl i), _⟩, simp only [hi, add_move_left_inl], rw [hn _ h, nat.lxor_assoc, nat.lxor_self, nat.lxor_zero] }, { obtain ⟨i, hi⟩ := exists_move_left_eq (ordinal.nat_cast_lt.2 h), refine ⟨to_left_moves_add (sum.inr i), _⟩, simp only [hi, add_move_left_inr], rw [hm _ h, nat.lxor_comm, nat.lxor_assoc, nat.lxor_self, nat.lxor_zero] } }, -- We are done! apply (ordinal.mex_le_of_ne.{u u} h₀).antisymm, contrapose! h₁, exact ⟨_, ⟨h₁, ordinal.mex_not_mem_range _⟩⟩, end lemma nim_add_nim_equiv {n m : ℕ} : nim n + nim m ≈ nim (nat.lxor n m) := by rw [←grundy_value_eq_iff_equiv_nim, grundy_value_nim_add_nim] lemma grundy_value_add (G H : pgame) [G.impartial] [H.impartial] {n m : ℕ} (hG : grundy_value G = n) (hH : grundy_value H = m) : grundy_value (G + H) = nat.lxor n m := begin rw [←nim_grundy_value (nat.lxor n m), grundy_value_eq_iff_equiv], refine equiv.trans _ nim_add_nim_equiv, convert add_congr (equiv_nim_grundy_value G) (equiv_nim_grundy_value H); simp only [hG, hH] end end pgame
17284f4d016182508d7c88c956d43c5b974bd023
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/finset/preimage.lean
ba9639d06700d1d2a019b12f43d8af1d4103ee6d
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
6,193
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import data.set.finite import algebra.big_operators.basic /-! # Preimage of a `finset` under an injective map. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ open set function open_locale big_operators universes u v w x variables {α : Type u} {β : Type v} {ι : Sort w} {γ : Type x} namespace finset section preimage /-- Preimage of `s : finset β` under a map `f` injective of `f ⁻¹' s` as a `finset`. -/ noncomputable def preimage (s : finset β) (f : α → β) (hf : set.inj_on f (f ⁻¹' ↑s)) : finset α := (s.finite_to_set.preimage hf).to_finset @[simp] lemma mem_preimage {f : α → β} {s : finset β} {hf : set.inj_on f (f ⁻¹' ↑s)} {x : α} : x ∈ preimage s f hf ↔ f x ∈ s := set.finite.mem_to_finset _ @[simp, norm_cast] lemma coe_preimage {f : α → β} (s : finset β) (hf : set.inj_on f (f ⁻¹' ↑s)) : (↑(preimage s f hf) : set α) = f ⁻¹' ↑s := set.finite.coe_to_finset _ @[simp] lemma preimage_empty {f : α → β} : preimage ∅ f (by simp [inj_on]) = ∅ := finset.coe_injective (by simp) @[simp] lemma preimage_univ {f : α → β} [fintype α] [fintype β] (hf) : preimage univ f hf = univ := finset.coe_injective (by simp) @[simp] lemma preimage_inter [decidable_eq α] [decidable_eq β] {f : α → β} {s t : finset β} (hs : set.inj_on f (f ⁻¹' ↑s)) (ht : set.inj_on f (f ⁻¹' ↑t)) : preimage (s ∩ t) f (λ x₁ hx₁ x₂ hx₂, hs (mem_of_mem_inter_left hx₁) (mem_of_mem_inter_left hx₂)) = preimage s f hs ∩ preimage t f ht := finset.coe_injective (by simp) @[simp] lemma preimage_union [decidable_eq α] [decidable_eq β] {f : α → β} {s t : finset β} (hst) : preimage (s ∪ t) f hst = preimage s f (λ x₁ hx₁ x₂ hx₂, hst (mem_union_left _ hx₁) (mem_union_left _ hx₂)) ∪ preimage t f (λ x₁ hx₁ x₂ hx₂, hst (mem_union_right _ hx₁) (mem_union_right _ hx₂)) := finset.coe_injective (by simp) @[simp] lemma preimage_compl [decidable_eq α] [decidable_eq β] [fintype α] [fintype β] {f : α → β} (s : finset β) (hf : function.injective f) : preimage sᶜ f (hf.inj_on _) = (preimage s f (hf.inj_on _))ᶜ := finset.coe_injective (by simp) lemma monotone_preimage {f : α → β} (h : injective f) : monotone (λ s, preimage s f (h.inj_on _)) := λ s t hst x hx, mem_preimage.2 (hst $ mem_preimage.1 hx) lemma image_subset_iff_subset_preimage [decidable_eq β] {f : α → β} {s : finset α} {t : finset β} (hf : set.inj_on f (f ⁻¹' ↑t)) : s.image f ⊆ t ↔ s ⊆ t.preimage f hf := image_subset_iff.trans $ by simp only [subset_iff, mem_preimage] lemma map_subset_iff_subset_preimage {f : α ↪ β} {s : finset α} {t : finset β} : s.map f ⊆ t ↔ s ⊆ t.preimage f (f.injective.inj_on _) := by classical; rw [map_eq_image, image_subset_iff_subset_preimage] lemma image_preimage [decidable_eq β] (f : α → β) (s : finset β) [Π x, decidable (x ∈ set.range f)] (hf : set.inj_on f (f ⁻¹' ↑s)) : image f (preimage s f hf) = s.filter (λ x, x ∈ set.range f) := finset.coe_inj.1 $ by simp only [coe_image, coe_preimage, coe_filter, set.image_preimage_eq_inter_range, set.sep_mem_eq] lemma image_preimage_of_bij [decidable_eq β] (f : α → β) (s : finset β) (hf : set.bij_on f (f ⁻¹' ↑s) ↑s) : image f (preimage s f hf.inj_on) = s := finset.coe_inj.1 $ by simpa using hf.image_eq lemma preimage_subset {f : α ↪ β} {s : finset β} {t : finset α} (hs : s ⊆ t.map f) : s.preimage f (f.injective.inj_on _) ⊆ t := λ x hx, (mem_map' f).1 (hs (mem_preimage.1 hx)) lemma subset_map_iff {f : α ↪ β} {s : finset β} {t : finset α} : s ⊆ t.map f ↔ ∃ u ⊆ t, s = u.map f := begin classical, refine ⟨λ h, ⟨_, preimage_subset h, _⟩, _⟩, { rw [map_eq_image, image_preimage, filter_true_of_mem (λ x hx, _)], exact coe_map_subset_range _ _ (h hx) }, { rintro ⟨u, hut, rfl⟩, exact map_subset_map.2 hut } end lemma sigma_preimage_mk {β : α → Type*} [decidable_eq α] (s : finset (Σ a, β a)) (t : finset α) : t.sigma (λ a, s.preimage (sigma.mk a) $ sigma_mk_injective.inj_on _) = s.filter (λ a, a.1 ∈ t) := by { ext x, simp [and_comm] } lemma sigma_preimage_mk_of_subset {β : α → Type*} [decidable_eq α] (s : finset (Σ a, β a)) {t : finset α} (ht : s.image sigma.fst ⊆ t) : t.sigma (λ a, s.preimage (sigma.mk a) $ sigma_mk_injective.inj_on _) = s := by rw [sigma_preimage_mk, filter_true_of_mem $ image_subset_iff.1 ht] lemma sigma_image_fst_preimage_mk {β : α → Type*} [decidable_eq α] (s : finset (Σ a, β a)) : (s.image sigma.fst).sigma (λ a, s.preimage (sigma.mk a) $ sigma_mk_injective.inj_on _) = s := s.sigma_preimage_mk_of_subset (subset.refl _) end preimage @[to_additive] lemma prod_preimage' [comm_monoid β] (f : α → γ) [decidable_pred $ λ x, x ∈ set.range f] (s : finset γ) (hf : set.inj_on f (f ⁻¹' ↑s)) (g : γ → β) : ∏ x in s.preimage f hf, g (f x) = ∏ x in s.filter (λ x, x ∈ set.range f), g x := by haveI := classical.dec_eq γ; calc ∏ x in preimage s f hf, g (f x) = ∏ x in image f (preimage s f hf), g x : eq.symm $ prod_image $ by simpa only [mem_preimage, inj_on] using hf ... = ∏ x in s.filter (λ x, x ∈ set.range f), g x : by rw [image_preimage] @[to_additive] lemma prod_preimage [comm_monoid β] (f : α → γ) (s : finset γ) (hf : set.inj_on f (f ⁻¹' ↑s)) (g : γ → β) (hg : ∀ x ∈ s, x ∉ set.range f → g x = 1) : ∏ x in s.preimage f hf, g (f x) = ∏ x in s, g x := by { classical, rw [prod_preimage', prod_filter_of_ne], exact λ x hx, not.imp_symm (hg x hx) } @[to_additive] lemma prod_preimage_of_bij [comm_monoid β] (f : α → γ) (s : finset γ) (hf : set.bij_on f (f ⁻¹' ↑s) ↑s) (g : γ → β) : ∏ x in s.preimage f hf.inj_on, g (f x) = ∏ x in s, g x := prod_preimage _ _ hf.inj_on g $ λ x hxs hxf, (hxf $ hf.subset_range hxs).elim end finset
3c0ef3dab26afa3aa28fcdb75ee6a08f7c9af710
4727251e0cd73359b15b664c3170e5d754078599
/src/order/ideal.lean
de3958a8d8b57bd93e426770d8fd07516aff0ef2
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
16,297
lean
/- Copyright (c) 2020 David Wärn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Wärn -/ import logic.encodable.basic import order.atoms import order.upper_lower /-! # Order ideals, cofinal sets, and the Rasiowa–Sikorski lemma ## Main definitions Throughout this file, `P` is at least a preorder, but some sections require more structure, such as a bottom element, a top element, or a join-semilattice structure. - `order.ideal P`: the type of nonempty, upward directed, and downward closed subsets of `P`. Dual to the notion of a filter on a preorder. - `order.is_ideal P`: a predicate for when a `set P` is an ideal. - `order.ideal.principal p`: the principal ideal generated by `p : P`. - `order.ideal.is_proper P`: a predicate for proper ideals. Dual to the notion of a proper filter. - `order.ideal.is_maximal`: a predicate for maximal ideals. Dual to the notion of an ultrafilter. - `order.cofinal P`: the type of subsets of `P` containing arbitrarily large elements. Dual to the notion of 'dense set' used in forcing. - `order.ideal_of_cofinals p 𝒟`, where `p : P`, and `𝒟` is a countable family of cofinal subsets of P: an ideal in `P` which contains `p` and intersects every set in `𝒟`. (This a form of the Rasiowa–Sikorski lemma.) ## References - <https://en.wikipedia.org/wiki/Ideal_(order_theory)> - <https://en.wikipedia.org/wiki/Cofinal_(mathematics)> - <https://en.wikipedia.org/wiki/Rasiowa%E2%80%93Sikorski_lemma> Note that for the Rasiowa–Sikorski lemma, Wikipedia uses the opposite ordering on `P`, in line with most presentations of forcing. ## Tags ideal, cofinal, dense, countable, generic -/ open function set namespace order variables {P : Type*} /-- An ideal on an order `P` is a subset of `P` that is - nonempty - upward directed (any pair of elements in the ideal has an upper bound in the ideal) - downward closed (any element less than an element of the ideal is in the ideal). -/ structure ideal (P) [has_le P] extends lower_set P := (nonempty' : carrier.nonempty) (directed' : directed_on (≤) carrier) /-- A subset of a preorder `P` is an ideal if it is - nonempty - upward directed (any pair of elements in the ideal has an upper bound in the ideal) - downward closed (any element less than an element of the ideal is in the ideal). -/ @[mk_iff] structure is_ideal {P} [has_le P] (I : set P) : Prop := (is_lower_set : is_lower_set I) (nonempty : I.nonempty) (directed : directed_on (≤) I) /-- Create an element of type `order.ideal` from a set satisfying the predicate `order.is_ideal`. -/ def is_ideal.to_ideal [has_le P] {I : set P} (h : is_ideal I) : ideal P := ⟨⟨I, h.is_lower_set⟩, h.nonempty, h.directed⟩ namespace ideal section has_le variables [has_le P] section variables {I J s t : ideal P} {x y : P} lemma to_lower_set_injective : injective (to_lower_set : ideal P → lower_set P) := λ s t h, by { cases s, cases t, congr' } instance : set_like (ideal P) P := { coe := λ s, s.carrier, coe_injective' := λ s t h, to_lower_set_injective $ set_like.coe_injective h } @[ext] lemma ext {s t : ideal P} : (s : set P) = t → s = t := set_like.ext' @[simp] lemma carrier_eq_coe (s : ideal P) : s.carrier = s := rfl @[simp] lemma coe_to_lower_set (s : ideal P) : (s.to_lower_set : set P) = s := rfl protected lemma lower (s : ideal P) : is_lower_set (s : set P) := s.lower' protected lemma nonempty (s : ideal P) : (s : set P).nonempty := s.nonempty' protected lemma directed (s : ideal P) : directed_on (≤) (s : set P) := s.directed' protected lemma is_ideal (s : ideal P) : is_ideal (s : set P) := ⟨s.lower, s.nonempty, s.directed⟩ lemma mem_compl_of_ge {x y : P} : x ≤ y → x ∈ (I : set P)ᶜ → y ∈ (I : set P)ᶜ := λ h, mt $ I.lower h /-- The partial ordering by subset inclusion, inherited from `set P`. -/ instance : partial_order (ideal P) := partial_order.lift coe set_like.coe_injective @[simp] lemma coe_subset_coe : (s : set P) ⊆ t ↔ s ≤ t := iff.rfl @[simp] lemma coe_ssubset_coe : (s : set P) ⊂ t ↔ s < t := iff.rfl @[trans] lemma mem_of_mem_of_le {x : P} {I J : ideal P} : x ∈ I → I ≤ J → x ∈ J := @set.mem_of_mem_of_subset P x I J /-- A proper ideal is one that is not the whole set. Note that the whole set might not be an ideal. -/ @[mk_iff] class is_proper (I : ideal P) : Prop := (ne_univ : (I : set P) ≠ univ) lemma is_proper_of_not_mem {I : ideal P} {p : P} (nmem : p ∉ I) : is_proper I := ⟨λ hp, begin change p ∉ ↑I at nmem, rw hp at nmem, exact nmem (mem_univ p), end⟩ /-- An ideal is maximal if it is maximal in the collection of proper ideals. Note that `is_coatom` is less general because ideals only have a top element when `P` is directed and nonempty. -/ @[mk_iff] class is_maximal (I : ideal P) extends is_proper I : Prop := (maximal_proper : ∀ ⦃J : ideal P⦄, I < J → (J : set P) = univ) lemma inter_nonempty [is_directed P (swap (≤))] (I J : ideal P) : (I ∩ J : set P).nonempty := begin obtain ⟨a, ha⟩ := I.nonempty, obtain ⟨b, hb⟩ := J.nonempty, obtain ⟨c, hac, hbc⟩ := directed_of (swap (≤)) a b, exact ⟨c, I.lower hac ha, J.lower hbc hb⟩, end end section directed variables [is_directed P (≤)] [nonempty P] {I : ideal P} /-- In a directed and nonempty order, the top ideal of a is `univ`. -/ instance : order_top (ideal P) := { top := ⟨⊤, univ_nonempty, directed_on_univ⟩, le_top := λ I, le_top } @[simp] lemma top_to_lower_set : (⊤ : ideal P).to_lower_set = ⊤ := rfl @[simp] lemma coe_top : ((⊤ : ideal P) : set P) = univ := rfl lemma is_proper_of_ne_top (ne_top : I ≠ ⊤) : is_proper I := ⟨λ h, ne_top $ ext h⟩ lemma is_proper.ne_top (hI : is_proper I) : I ≠ ⊤ := λ h, is_proper.ne_univ $ congr_arg coe h lemma _root_.is_coatom.is_proper (hI : is_coatom I) : is_proper I := is_proper_of_ne_top hI.1 lemma is_proper_iff_ne_top : is_proper I ↔ I ≠ ⊤ := ⟨λ h, h.ne_top, λ h, is_proper_of_ne_top h⟩ lemma is_maximal.is_coatom (h : is_maximal I) : is_coatom I := ⟨is_maximal.to_is_proper.ne_top, λ J h, ext $ is_maximal.maximal_proper h⟩ lemma is_maximal.is_coatom' [is_maximal I] : is_coatom I := is_maximal.is_coatom ‹_› lemma _root_.is_coatom.is_maximal (hI : is_coatom I) : is_maximal I := { maximal_proper := λ _ _, by simp [hI.2 _ ‹_›], ..is_coatom.is_proper ‹_› } lemma is_maximal_iff_is_coatom : is_maximal I ↔ is_coatom I := ⟨λ h, h.is_coatom, λ h, h.is_maximal⟩ end directed section order_bot variables [order_bot P] @[simp] lemma bot_mem (s : ideal P) : ⊥ ∈ s := s.lower bot_le s.nonempty.some_mem end order_bot section order_top variables [order_top P] {I : ideal P} lemma top_of_top_mem (h : ⊤ ∈ I) : I = ⊤ := by { ext, exact iff_of_true (I.lower le_top h) trivial } lemma is_proper.top_not_mem (hI : is_proper I) : ⊤ ∉ I := λ h, hI.ne_top $ top_of_top_mem h end order_top end has_le section preorder variables [preorder P] section variables {I J : ideal P} {x y : P} /-- The smallest ideal containing a given element. -/ @[simps] def principal (p : P) : ideal P := { to_lower_set := lower_set.Iic p, nonempty' := nonempty_Iic, directed' := λ x hx y hy, ⟨p, le_rfl, hx, hy⟩ } instance [inhabited P] : inhabited (ideal P) := ⟨ideal.principal default⟩ @[simp] lemma principal_le_iff : principal x ≤ I ↔ x ∈ I := ⟨λ h, h le_rfl, λ hx y hy, I.lower hy hx⟩ @[simp] lemma mem_principal : x ∈ principal y ↔ x ≤ y := iff.rfl end section order_bot variables [order_bot P] /-- There is a bottom ideal when `P` has a bottom element. -/ instance : order_bot (ideal P) := { bot := principal ⊥, bot_le := by simp } @[simp] lemma principal_bot : principal (⊥ : P) = ⊥ := rfl end order_bot section order_top variables [order_top P] @[simp] lemma principal_top : principal (⊤ : P) = ⊤ := to_lower_set_injective $ lower_set.Iic_top end order_top end preorder section semilattice_sup variables [semilattice_sup P] {x y : P} {I s : ideal P} /-- A specific witness of `I.directed` when `P` has joins. -/ lemma sup_mem (hx : x ∈ s) (hy : y ∈ s) : x ⊔ y ∈ s := let ⟨z, hz, hx, hy⟩ := s.directed x hx y hy in s.lower (sup_le hx hy) hz @[simp] lemma sup_mem_iff : x ⊔ y ∈ I ↔ x ∈ I ∧ y ∈ I := ⟨λ h, ⟨I.lower le_sup_left h, I.lower le_sup_right h⟩, λ h, sup_mem h.1 h.2⟩ end semilattice_sup section semilattice_sup_directed variables [semilattice_sup P] [is_directed P (swap (≤))] {x : P} {I J K s t : ideal P} /-- The infimum of two ideals of a co-directed order is their intersection. -/ instance : has_inf (ideal P) := ⟨λ I J, { to_lower_set := I.to_lower_set ⊓ J.to_lower_set, nonempty' := inter_nonempty I J, directed' := λ x hx y hy, ⟨x ⊔ y, ⟨sup_mem hx.1 hy.1, sup_mem hx.2 hy.2⟩, by simp⟩ }⟩ /-- The supremum of two ideals of a co-directed order is the union of the down sets of the pointwise supremum of `I` and `J`. -/ instance : has_sup (ideal P) := ⟨λ I J, { carrier := {x | ∃ (i ∈ I) (j ∈ J), x ≤ i ⊔ j}, nonempty' := by { cases inter_nonempty I J, exact ⟨w, w, h.1, w, h.2, le_sup_left⟩ }, directed' := λ x ⟨xi, _, xj, _, _⟩ y ⟨yi, _, yj, _, _⟩, ⟨x ⊔ y, ⟨xi ⊔ yi, sup_mem ‹_› ‹_›, xj ⊔ yj, sup_mem ‹_› ‹_›, sup_le (calc x ≤ xi ⊔ xj : ‹_› ... ≤ (xi ⊔ yi) ⊔ (xj ⊔ yj) : sup_le_sup le_sup_left le_sup_left) (calc y ≤ yi ⊔ yj : ‹_› ... ≤ (xi ⊔ yi) ⊔ (xj ⊔ yj) : sup_le_sup le_sup_right le_sup_right)⟩, le_sup_left, le_sup_right⟩, lower' := λ x y h ⟨yi, _, yj, _, _⟩, ⟨yi, ‹_›, yj, ‹_›, h.trans ‹_›⟩ }⟩ instance : lattice (ideal P) := { sup := (⊔), le_sup_left := λ I J (i ∈ I), by { cases J.nonempty, exact ⟨i, ‹_›, w, ‹_›, le_sup_left⟩ }, le_sup_right := λ I J (j ∈ J), by { cases I.nonempty, exact ⟨w, ‹_›, j, ‹_›, le_sup_right⟩ }, sup_le := λ I J K hIK hJK a ⟨i, hi, j, hj, ha⟩, K.lower ha $ sup_mem (mem_of_mem_of_le hi hIK) (mem_of_mem_of_le hj hJK), inf := (⊓), inf_le_left := λ I J, inter_subset_left I J, inf_le_right := λ I J, inter_subset_right I J, le_inf := λ I J K, subset_inter, .. ideal.partial_order } @[simp] lemma coe_sup : ↑(s ⊔ t) = {x | ∃ (a ∈ s) (b ∈ t), x ≤ a ⊔ b} := rfl @[simp] lemma coe_inf : (↑(s ⊓ t) : set P) = s ∩ t := rfl @[simp] lemma mem_inf : x ∈ I ⊓ J ↔ x ∈ I ∧ x ∈ J := iff.rfl @[simp] lemma mem_sup : x ∈ I ⊔ J ↔ ∃ (i ∈ I) (j ∈ J), x ≤ i ⊔ j := iff.rfl lemma lt_sup_principal_of_not_mem (hx : x ∉ I) : I < I ⊔ principal x := le_sup_left.lt_of_ne $ λ h, hx $ by simpa only [left_eq_sup, principal_le_iff] using h end semilattice_sup_directed section semilattice_sup_order_bot variables [semilattice_sup P] [order_bot P] {x : P} {I J K : ideal P} instance : has_Inf (ideal P) := ⟨λ S, { to_lower_set := ⨅ s ∈ S, to_lower_set s, nonempty' := ⟨⊥, begin rw [lower_set.carrier_eq_coe, lower_set.coe_infi₂, set.mem_Inter₂], exact λ s _, s.bot_mem, end⟩, directed' := λ a ha b hb, ⟨a ⊔ b, ⟨ begin rw [lower_set.carrier_eq_coe, lower_set.coe_infi₂, set.mem_Inter₂] at ⊢ ha hb, exact λ s hs, sup_mem (ha _ hs) (hb _ hs), end, le_sup_left, le_sup_right⟩⟩ }⟩ variables {S : set (ideal P)} @[simp] lemma coe_Inf : (↑(Inf S) : set P) = ⋂ s ∈ S, ↑s := lower_set.coe_infi₂ _ @[simp] lemma mem_Inf : x ∈ Inf S ↔ ∀ s ∈ S, x ∈ s := by simp_rw [←set_like.mem_coe, coe_Inf, mem_Inter₂] instance : complete_lattice (ideal P) := { ..ideal.lattice, ..complete_lattice_of_Inf (ideal P) (λ S, begin refine ⟨λ s hs, _, λ s hs, by rwa [←coe_subset_coe, coe_Inf, subset_Inter₂_iff]⟩, rw [←coe_subset_coe, coe_Inf], exact bInter_subset_of_mem hs, end) } end semilattice_sup_order_bot section distrib_lattice variables [distrib_lattice P] variables {I J : ideal P} lemma eq_sup_of_le_sup {x i j: P} (hi : i ∈ I) (hj : j ∈ J) (hx : x ≤ i ⊔ j) : ∃ (i' ∈ I) (j' ∈ J), x = i' ⊔ j' := begin refine ⟨x ⊓ i, I.lower inf_le_right hi, x ⊓ j, J.lower inf_le_right hj, _⟩, calc x = x ⊓ (i ⊔ j) : left_eq_inf.mpr hx ... = (x ⊓ i) ⊔ (x ⊓ j) : inf_sup_left, end lemma coe_sup_eq : ↑(I ⊔ J) = {x | ∃ i ∈ I, ∃ j ∈ J, x = i ⊔ j} := set.ext $ λ _, ⟨λ ⟨_, _, _, _, _⟩, eq_sup_of_le_sup ‹_› ‹_› ‹_›, λ ⟨i, _, j, _, _⟩, ⟨i, ‹_›, j, ‹_›, le_of_eq ‹_›⟩⟩ end distrib_lattice section boolean_algebra variables [boolean_algebra P] {x : P} {I : ideal P} lemma is_proper.not_mem_of_compl_mem (hI : is_proper I) (hxc : xᶜ ∈ I) : x ∉ I := begin intro hx, apply hI.top_not_mem, have ht : x ⊔ xᶜ ∈ I := sup_mem ‹_› ‹_›, rwa sup_compl_eq_top at ht, end lemma is_proper.not_mem_or_compl_not_mem (hI : is_proper I) : x ∉ I ∨ xᶜ ∉ I := have h : xᶜ ∈ I → x ∉ I := hI.not_mem_of_compl_mem, by tauto end boolean_algebra end ideal /-- For a preorder `P`, `cofinal P` is the type of subsets of `P` containing arbitrarily large elements. They are the dense sets in the topology whose open sets are terminal segments. -/ structure cofinal (P) [preorder P] := (carrier : set P) (mem_gt : ∀ x : P, ∃ y ∈ carrier, x ≤ y) namespace cofinal variables [preorder P] instance : inhabited (cofinal P) := ⟨{ carrier := univ, mem_gt := λ x, ⟨x, trivial, le_rfl⟩ }⟩ instance : has_mem P (cofinal P) := ⟨λ x D, x ∈ D.carrier⟩ variables (D : cofinal P) (x : P) /-- A (noncomputable) element of a cofinal set lying above a given element. -/ noncomputable def above : P := classical.some $ D.mem_gt x lemma above_mem : D.above x ∈ D := exists.elim (classical.some_spec $ D.mem_gt x) $ λ a _, a lemma le_above : x ≤ D.above x := exists.elim (classical.some_spec $ D.mem_gt x) $ λ _ b, b end cofinal section ideal_of_cofinals variables [preorder P] (p : P) {ι : Type*} [encodable ι] (𝒟 : ι → cofinal P) /-- Given a starting point, and a countable family of cofinal sets, this is an increasing sequence that intersects each cofinal set. -/ noncomputable def sequence_of_cofinals : ℕ → P | 0 := p | (n+1) := match encodable.decode ι n with | none := sequence_of_cofinals n | some i := (𝒟 i).above (sequence_of_cofinals n) end lemma sequence_of_cofinals.monotone : monotone (sequence_of_cofinals p 𝒟) := by { apply monotone_nat_of_le_succ, intros n, dunfold sequence_of_cofinals, cases encodable.decode ι n, { refl }, { apply cofinal.le_above }, } lemma sequence_of_cofinals.encode_mem (i : ι) : sequence_of_cofinals p 𝒟 (encodable.encode i + 1) ∈ 𝒟 i := by { dunfold sequence_of_cofinals, rw encodable.encodek, apply cofinal.above_mem, } /-- Given an element `p : P` and a family `𝒟` of cofinal subsets of a preorder `P`, indexed by a countable type, `ideal_of_cofinals p 𝒟` is an ideal in `P` which - contains `p`, according to `mem_ideal_of_cofinals p 𝒟`, and - intersects every set in `𝒟`, according to `cofinal_meets_ideal_of_cofinals p 𝒟`. This proves the Rasiowa–Sikorski lemma. -/ def ideal_of_cofinals : ideal P := { carrier := { x : P | ∃ n, x ≤ sequence_of_cofinals p 𝒟 n }, lower' := λ x y hxy ⟨n, hn⟩, ⟨n, le_trans hxy hn⟩, nonempty' := ⟨p, 0, le_rfl⟩, directed' := λ x ⟨n, hn⟩ y ⟨m, hm⟩, ⟨_, ⟨max n m, le_rfl⟩, le_trans hn $ sequence_of_cofinals.monotone p 𝒟 (le_max_left _ _), le_trans hm $ sequence_of_cofinals.monotone p 𝒟 (le_max_right _ _) ⟩ } lemma mem_ideal_of_cofinals : p ∈ ideal_of_cofinals p 𝒟 := ⟨0, le_rfl⟩ /-- `ideal_of_cofinals p 𝒟` is `𝒟`-generic. -/ lemma cofinal_meets_ideal_of_cofinals (i : ι) : ∃ x : P, x ∈ 𝒟 i ∧ x ∈ ideal_of_cofinals p 𝒟 := ⟨_, sequence_of_cofinals.encode_mem p 𝒟 i, _, le_rfl⟩ end ideal_of_cofinals end order
af2f9cb7b2281193a4faf9b0c910e59f795d3940
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/geometry/manifold/bump_function.lean
ce7319a03ac66f0241604d286f4085dfea3b3df1
[ "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,458
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.calculus.specific_functions import geometry.manifold.diffeomorph import geometry.manifold.instances.real /-! # Smooth bump functions on a smooth manifold In this file we define `smooth_bump_function I c` to be a bundled smooth "bump" function centered at `c`. It is a structure that consists of two real numbers `0 < r < R` with small enough `R`. We define a coercion to function for this type, and for `f : smooth_bump_function I c`, the function `⇑f` written in the extended chart at `c` has the following properties: * `f x = 1` in the closed euclidean ball of radius `f.r` centered at `c`; * `f x = 0` outside of the euclidean ball of radius `f.R` centered at `c`; * `0 ≤ f x ≤ 1` for all `x`. The actual statements involve (pre)images under `ext_chart_at I f` and are given as lemmas in the `smooth_bump_function` namespace. ## Tags manifold, smooth bump function -/ universes uE uF uH uM variables {E : Type uE} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {H : Type uH} [topological_space H] (I : model_with_corners ℝ E H) {M : Type uM} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] open function filter finite_dimensional set open_locale topological_space manifold classical filter big_operators noncomputable theory /-! ### Smooth bump function In this section we define a structure for a bundled smooth bump function and prove its properties. -/ /-- Given a smooth manifold modelled on a finite dimensional space `E`, `f : smooth_bump_function I M` is a smooth function on `M` such that in the extended chart `e` at `f.c`: * `f x = 1` in the closed euclidean ball of radius `f.r` centered at `f.c`; * `f x = 0` outside of the euclidean ball of radius `f.R` centered at `f.c`; * `0 ≤ f x ≤ 1` for all `x`. The structure contains data required to construct a function with these properties. The function is available as `⇑f` or `f x`. Formal statements of the properties listed above involve some (pre)images under `ext_chart_at I f.c` and are given as lemmas in the `smooth_bump_function` namespace. -/ structure smooth_bump_function (c : M) extends times_cont_diff_bump (ext_chart_at I c c) := (closed_ball_subset : (euclidean.closed_ball (ext_chart_at I c c) R) ∩ range I ⊆ (ext_chart_at I c).target) variable {M} namespace smooth_bump_function open euclidean (renaming dist -> eudist) variables {c : M} (f : smooth_bump_function I c) {x : M} {I} /-- The function defined by `f : smooth_bump_function c`. Use automatic coercion to function instead. -/ def to_fun : M → ℝ := indicator (chart_at H c).source (f.to_times_cont_diff_bump ∘ ext_chart_at I c) instance : has_coe_to_fun (smooth_bump_function I c) := ⟨_, to_fun⟩ lemma coe_def : ⇑f = indicator (chart_at H c).source (f.to_times_cont_diff_bump ∘ ext_chart_at I c) := rfl lemma R_pos : 0 < f.R := f.to_times_cont_diff_bump.R_pos lemma ball_subset : ball (ext_chart_at I c c) f.R ∩ range I ⊆ (ext_chart_at I c).target := subset.trans (inter_subset_inter_left _ ball_subset_closed_ball) f.closed_ball_subset lemma eq_on_source : eq_on f (f.to_times_cont_diff_bump ∘ ext_chart_at I c) (chart_at H c).source := eq_on_indicator lemma eventually_eq_of_mem_source (hx : x ∈ (chart_at H c).source) : f =ᶠ[𝓝 x] f.to_times_cont_diff_bump ∘ ext_chart_at I c := f.eq_on_source.eventually_eq_of_mem $ is_open.mem_nhds (chart_at H c).open_source hx lemma one_of_dist_le (hs : x ∈ (chart_at H c).source) (hd : eudist (ext_chart_at I c x) (ext_chart_at I c c) ≤ f.r) : f x = 1 := by simp only [f.eq_on_source hs, (∘), f.to_times_cont_diff_bump.one_of_mem_closed_ball hd] lemma support_eq_inter_preimage : support f = (chart_at H c).source ∩ (ext_chart_at I c ⁻¹' ball (ext_chart_at I c c) f.R) := by rw [coe_def, support_indicator, (∘), support_comp_eq_preimage, ← ext_chart_at_source I, ← (ext_chart_at I c).symm_image_target_inter_eq', ← (ext_chart_at I c).symm_image_target_inter_eq', f.to_times_cont_diff_bump.support_eq] lemma open_support : is_open (support f) := by { rw support_eq_inter_preimage, exact ext_chart_preimage_open_of_open I c is_open_ball } lemma support_eq_symm_image : support f = (ext_chart_at I c).symm '' (ball (ext_chart_at I c c) f.R ∩ range I) := begin rw [f.support_eq_inter_preimage, ← ext_chart_at_source I, ← (ext_chart_at I c).symm_image_target_inter_eq', inter_comm], congr' 1 with y, exact and.congr_right_iff.2 (λ hy, ⟨λ h, ext_chart_at_target_subset_range _ _ h, λ h, f.ball_subset ⟨hy, h⟩⟩) end lemma support_subset_source : support f ⊆ (chart_at H c).source := by { rw [f.support_eq_inter_preimage, ← ext_chart_at_source I], exact inter_subset_left _ _ } lemma image_eq_inter_preimage_of_subset_support {s : set M} (hs : s ⊆ support f) : ext_chart_at I c '' s = closed_ball (ext_chart_at I c c) f.R ∩ range I ∩ (ext_chart_at I c).symm ⁻¹' s := begin rw [support_eq_inter_preimage, subset_inter_iff, ← ext_chart_at_source I, ← image_subset_iff] at hs, cases hs with hse hsf, apply subset.antisymm, { refine subset_inter (subset_inter (subset.trans hsf ball_subset_closed_ball) _) _, { rintro _ ⟨x, -, rfl⟩, exact mem_range_self _ }, { rw [(ext_chart_at I c).image_eq_target_inter_inv_preimage hse], exact inter_subset_right _ _ } }, { refine subset.trans (inter_subset_inter_left _ f.closed_ball_subset) _, rw [(ext_chart_at I c).image_eq_target_inter_inv_preimage hse] } end lemma mem_Icc : f x ∈ Icc (0 : ℝ) 1 := begin have : f x = 0 ∨ f x = _, from indicator_eq_zero_or_self _ _ _, cases this; rw this, exacts [left_mem_Icc.2 zero_le_one, ⟨f.to_times_cont_diff_bump.nonneg, f.to_times_cont_diff_bump.le_one⟩] end lemma nonneg : 0 ≤ f x := f.mem_Icc.1 lemma le_one : f x ≤ 1 := f.mem_Icc.2 lemma eventually_eq_one_of_dist_lt (hs : x ∈ (chart_at H c).source) (hd : eudist (ext_chart_at I c x) (ext_chart_at I c c) < f.r) : f =ᶠ[𝓝 x] 1 := begin filter_upwards [is_open.mem_nhds (ext_chart_preimage_open_of_open I c is_open_ball) ⟨hs, hd⟩], rintro z ⟨hzs, hzd : _ < _⟩, exact f.one_of_dist_le hzs hzd.le end lemma eventually_eq_one : f =ᶠ[𝓝 c] 1 := f.eventually_eq_one_of_dist_lt (mem_chart_source _ _) $ by { rw [euclidean.dist, dist_self], exact f.r_pos } @[simp] lemma eq_one : f c = 1 := f.eventually_eq_one.eq_of_nhds lemma support_mem_nhds : support f ∈ 𝓝 c := f.eventually_eq_one.mono $ λ x hx, by { rw hx, exact one_ne_zero } lemma closure_support_mem_nhds : closure (support f) ∈ 𝓝 c := mem_of_superset f.support_mem_nhds subset_closure lemma c_mem_support : c ∈ support f := mem_of_mem_nhds f.support_mem_nhds lemma nonempty_support : (support f).nonempty := ⟨c, f.c_mem_support⟩ lemma compact_symm_image_closed_ball : is_compact ((ext_chart_at I c).symm '' (closed_ball (ext_chart_at I c c) f.R ∩ range I)) := (is_compact_closed_ball.inter_right I.closed_range).image_of_continuous_on $ (ext_chart_at_continuous_on_symm _ _).mono f.closed_ball_subset /-- Given a smooth bump function `f : smooth_bump_function I c`, the closed ball of radius `f.R` is known to include the support of `f`. These closed balls (in the model normed space `E`) intersected with `set.range I` form a basis of `𝓝[range I] (ext_chart_at I c c)`. -/ lemma nhds_within_range_basis : (𝓝[range I] (ext_chart_at I c c)).has_basis (λ f : smooth_bump_function I c, true) (λ f, closed_ball (ext_chart_at I c c) f.R ∩ range I) := begin refine ((nhds_within_has_basis euclidean.nhds_basis_closed_ball _).restrict_subset (ext_chart_at_target_mem_nhds_within _ _)).to_has_basis' _ _, { rintro R ⟨hR0, hsub⟩, exact ⟨⟨⟨⟨R / 2, R, half_pos hR0, half_lt_self hR0⟩⟩, hsub⟩, trivial, subset.rfl⟩ }, { exact λ f _, inter_mem (mem_nhds_within_of_mem_nhds $ closed_ball_mem_nhds f.R_pos) self_mem_nhds_within } end lemma closed_image_of_closed {s : set M} (hsc : is_closed s) (hs : s ⊆ support f) : is_closed (ext_chart_at I c '' s) := begin rw f.image_eq_inter_preimage_of_subset_support hs, refine continuous_on.preimage_closed_of_closed ((ext_chart_continuous_on_symm _ _).mono f.closed_ball_subset) _ hsc, exact is_closed.inter is_closed_closed_ball I.closed_range end /-- If `f` is a smooth bump function and `s` closed subset of the support of `f` (i.e., of the open ball of radius `f.R`), then there exists `0 < r < f.R` such that `s` is a subset of the open ball of radius `r`. Formally, `s ⊆ e.source ∩ e ⁻¹' (ball (e c) r)`, where `e = ext_chart_at I c`. -/ lemma exists_r_pos_lt_subset_ball {s : set M} (hsc : is_closed s) (hs : s ⊆ support f) : ∃ r (hr : r ∈ Ioo 0 f.R), s ⊆ (chart_at H c).source ∩ ext_chart_at I c ⁻¹' (ball (ext_chart_at I c c) r) := begin set e := ext_chart_at I c, have : is_closed (e '' s) := f.closed_image_of_closed hsc hs, rw [support_eq_inter_preimage, subset_inter_iff, ← image_subset_iff] at hs, rcases euclidean.exists_pos_lt_subset_ball f.R_pos this hs.2 with ⟨r, hrR, hr⟩, exact ⟨r, hrR, subset_inter hs.1 (image_subset_iff.1 hr)⟩ end /-- Replace `r` with another value in the interval `(0, f.R)`. -/ def update_r (r : ℝ) (hr : r ∈ Ioo 0 f.R) : smooth_bump_function I c := ⟨⟨⟨r, f.R, hr.1, hr.2⟩⟩, f.closed_ball_subset⟩ @[simp] lemma update_r_R {r : ℝ} (hr : r ∈ Ioo 0 f.R) : (f.update_r r hr).R = f.R := rfl @[simp] lemma update_r_r {r : ℝ} (hr : r ∈ Ioo 0 f.R) : (f.update_r r hr).r = r := rfl @[simp] lemma support_update_r {r : ℝ} (hr : r ∈ Ioo 0 f.R) : support (f.update_r r hr) = support f := by simp only [support_eq_inter_preimage, update_r_R] instance : inhabited (smooth_bump_function I c) := classical.inhabited_of_nonempty nhds_within_range_basis.nonempty variables [t2_space M] lemma closed_symm_image_closed_ball : is_closed ((ext_chart_at I c).symm '' (closed_ball (ext_chart_at I c c) f.R ∩ range I)) := f.compact_symm_image_closed_ball.is_closed lemma closure_support_subset_symm_image_closed_ball : closure (support f) ⊆ (ext_chart_at I c).symm '' (closed_ball (ext_chart_at I c c) f.R ∩ range I) := begin rw support_eq_symm_image, exact closure_minimal (image_subset _ $ inter_subset_inter_left _ ball_subset_closed_ball) f.closed_symm_image_closed_ball end lemma closure_support_subset_ext_chart_at_source : closure (support f) ⊆ (ext_chart_at I c).source := calc closure (support f) ⊆ (ext_chart_at I c).symm '' (closed_ball (ext_chart_at I c c) f.R ∩ range I) : f.closure_support_subset_symm_image_closed_ball ... ⊆ (ext_chart_at I c).symm '' (ext_chart_at I c).target : image_subset _ f.closed_ball_subset ... = (ext_chart_at I c).source : (ext_chart_at I c).symm_image_target_eq_source lemma closure_support_subset_chart_at_source : closure (support f) ⊆ (chart_at H c).source := by simpa only [ext_chart_at_source] using f.closure_support_subset_ext_chart_at_source lemma compact_closure_support : is_compact (closure $ support f) := compact_of_is_closed_subset f.compact_symm_image_closed_ball is_closed_closure f.closure_support_subset_symm_image_closed_ball variables (I c) /-- The closures of supports of smooth bump functions centered at `c` form a basis of `𝓝 c`. In other words, each of these closures is a neighborhood of `c` and each neighborhood of `c` includes `closure (support f)` for some `f : smooth_bump_function I c`. -/ lemma nhds_basis_closure_support : (𝓝 c).has_basis (λ f : smooth_bump_function I c, true) (λ f, closure $ support f) := begin have : (𝓝 c).has_basis (λ f : smooth_bump_function I c, true) (λ f, (ext_chart_at I c).symm '' (closed_ball (ext_chart_at I c c) f.R ∩ range I)), { rw [← ext_chart_at_symm_map_nhds_within_range I c], exact nhds_within_range_basis.map _ }, refine this.to_has_basis' (λ f hf, ⟨f, trivial, f.closure_support_subset_symm_image_closed_ball⟩) (λ f _, f.closure_support_mem_nhds), end variable {c} /-- Given `s ∈ 𝓝 c`, the supports of smooth bump functions `f : smooth_bump_function I c` such that `closure (support f) ⊆ s` form a basis of `𝓝 c`. In other words, each of these supports is a neighborhood of `c` and each neighborhood of `c` includes `support f` for some `f : smooth_bump_function I c` such that `closure (support f) ⊆ s`. -/ lemma nhds_basis_support {s : set M} (hs : s ∈ 𝓝 c) : (𝓝 c).has_basis (λ f : smooth_bump_function I c, closure (support f) ⊆ s) (λ f, support f) := ((nhds_basis_closure_support I c).restrict_subset hs).to_has_basis' (λ f hf, ⟨f, hf.2, subset_closure⟩) (λ f hf, f.support_mem_nhds) variables [smooth_manifold_with_corners I M] {I} /-- A smooth bump function is infinitely smooth. -/ protected lemma smooth : smooth I 𝓘(ℝ) f := begin refine times_cont_mdiff_of_support (λ x hx, _), have : x ∈ (chart_at H c).source := f.closure_support_subset_chart_at_source hx, refine times_cont_mdiff_at.congr_of_eventually_eq _ (f.eq_on_source.eventually_eq_of_mem $ is_open.mem_nhds (chart_at _ _).open_source this), exact f.to_times_cont_diff_bump.times_cont_diff_at.times_cont_mdiff_at.comp _ (times_cont_mdiff_at_ext_chart_at' this) end protected lemma smooth_at {x} : smooth_at I 𝓘(ℝ) f x := f.smooth.smooth_at protected lemma continuous : continuous f := f.smooth.continuous /-- If `f : smooth_bump_function I c` is a smooth bump function and `g : M → G` is a function smooth on the source of the chart at `c`, then `f • g` is smooth on the whole manifold. -/ lemma smooth_smul {G} [normed_group G] [normed_space ℝ G] {g : M → G} (hg : smooth_on I 𝓘(ℝ, G) g (chart_at H c).source) : smooth I 𝓘(ℝ, G) (λ x, f x • g x) := begin apply times_cont_mdiff_of_support (λ x hx, _), have : x ∈ (chart_at H c).source, calc x ∈ closure (support (λ x, f x • g x)) : hx ... ⊆ closure (support f) : closure_mono (support_smul_subset_left _ _) ... ⊆ (chart_at _ c).source : f.closure_support_subset_chart_at_source, exact f.smooth_at.smul ((hg _ this).times_cont_mdiff_at $ is_open.mem_nhds (chart_at _ _).open_source this) end end smooth_bump_function
80769b50d21b69c0f4f7d941f13e0742431672d1
88fb7558b0636ec6b181f2a548ac11ad3919f8a5
/tests/lean/run/eval_expr_partial.lean
bbdb4ea7b406f88d8df9b3dc0113f04907d6d6d0
[ "Apache-2.0" ]
permissive
moritayasuaki/lean
9f666c323cb6fa1f31ac597d777914aed41e3b7a
ae96ebf6ee953088c235ff7ae0e8c95066ba8001
refs/heads/master
1,611,135,440,814
1,493,852,869,000
1,493,852,869,000
90,269,903
0
0
null
1,493,906,291,000
1,493,906,291,000
null
UTF-8
Lean
false
false
74
lean
open tactic run_cmd to_expr `(bit0 1) >>= eval_expr nat >>= tactic.trace
dd6af782614da4c1c7234e68838ca6490f1af61b
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/adjunction/basic_auto.lean
0f43de2928d20f68518436f4e3cb6c7a5bb72f7f
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
23,669
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Johan Commelin, Bhavik Mehta -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.equivalence import Mathlib.data.equiv.basic import Mathlib.PostPort universes v₁ v₂ u₁ u₂ l u₃ v₃ namespace Mathlib namespace category_theory -- declare the `v`'s first; see `category_theory.category` for an explanation /-- `F ⊣ G` represents the data of an adjunction between two functors `F : C ⥤ D` and `G : D ⥤ C`. `F` is the left adjoint and `G` is the right adjoint. To construct an `adjunction` between two functors, it's often easier to instead use the constructors `mk_of_hom_equiv` or `mk_of_unit_counit`. To construct a left adjoint, there are also constructors `left_adjoint_of_equiv` and `adjunction_of_equiv_left` (as well as their duals) which can be simpler in practice. Uniqueness of adjoints is shown in `category_theory.adjunction.opposites`. See https://stacks.math.columbia.edu/tag/0037. -/ structure adjunction {C : Type u₁} [category C] {D : Type u₂} [category D] (F : C ⥤ D) (G : D ⥤ C) where hom_equiv : (X : C) → (Y : D) → (functor.obj F X ⟶ Y) ≃ (X ⟶ functor.obj G Y) unit : 𝟭 ⟶ F ⋙ G counit : G ⋙ F ⟶ 𝟭 hom_equiv_unit' : autoParam (∀ {X : C} {Y : D} {f : functor.obj F X ⟶ Y}, coe_fn (hom_equiv X Y) f = nat_trans.app unit X ≫ functor.map G f) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) hom_equiv_counit' : autoParam (∀ {X : C} {Y : D} {g : X ⟶ functor.obj G Y}, coe_fn (equiv.symm (hom_equiv X Y)) g = functor.map F g ≫ nat_trans.app counit Y) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) infixl:15 " ⊣ " => Mathlib.category_theory.adjunction /-- A class giving a chosen right adjoint to the functor `left`. -/ class is_left_adjoint {C : Type u₁} [category C] {D : Type u₂} [category D] (left : C ⥤ D) where right : D ⥤ C adj : left ⊣ right /-- A class giving a chosen left adjoint to the functor `right`. -/ class is_right_adjoint {C : Type u₁} [category C] {D : Type u₂} [category D] (right : D ⥤ C) where left : C ⥤ D adj : left ⊣ right /-- Extract the left adjoint from the instance giving the chosen adjoint. -/ def left_adjoint {C : Type u₁} [category C] {D : Type u₂} [category D] (R : D ⥤ C) [is_right_adjoint R] : C ⥤ D := is_right_adjoint.left R /-- Extract the right adjoint from the instance giving the chosen adjoint. -/ def right_adjoint {C : Type u₁} [category C] {D : Type u₂} [category D] (L : C ⥤ D) [is_left_adjoint L] : D ⥤ C := is_left_adjoint.right L /-- The adjunction associated to a functor known to be a left adjoint. -/ def adjunction.of_left_adjoint {C : Type u₁} [category C] {D : Type u₂} [category D] (left : C ⥤ D) [is_left_adjoint left] : left ⊣ right_adjoint left := is_left_adjoint.adj /-- The adjunction associated to a functor known to be a right adjoint. -/ def adjunction.of_right_adjoint {C : Type u₁} [category C] {D : Type u₂} [category D] (right : C ⥤ D) [is_right_adjoint right] : left_adjoint right ⊣ right := is_right_adjoint.adj namespace adjunction @[simp] theorem hom_equiv_unit {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (c : F ⊣ G) {X : C} {Y : D} {f : functor.obj F X ⟶ Y} : coe_fn (hom_equiv c X Y) f = nat_trans.app (unit c) X ≫ functor.map G f := sorry @[simp] theorem hom_equiv_counit {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (c : F ⊣ G) {X : C} {Y : D} {g : X ⟶ functor.obj G Y} : coe_fn (equiv.symm (hom_equiv c X Y)) g = functor.map F g ≫ nat_trans.app (counit c) Y := sorry @[simp] theorem hom_equiv_naturality_left_symm {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) {X' : C} {X : C} {Y : D} (f : X' ⟶ X) (g : X ⟶ functor.obj G Y) : coe_fn (equiv.symm (hom_equiv adj X' Y)) (f ≫ g) = functor.map F f ≫ coe_fn (equiv.symm (hom_equiv adj X Y)) g := sorry @[simp] theorem hom_equiv_naturality_left {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) {X' : C} {X : C} {Y : D} (f : X' ⟶ X) (g : functor.obj F X ⟶ Y) : coe_fn (hom_equiv adj X' Y) (functor.map F f ≫ g) = f ≫ coe_fn (hom_equiv adj X Y) g := sorry @[simp] theorem hom_equiv_naturality_right {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) {X : C} {Y : D} {Y' : D} (f : functor.obj F X ⟶ Y) (g : Y ⟶ Y') : coe_fn (hom_equiv adj X Y') (f ≫ g) = coe_fn (hom_equiv adj X Y) f ≫ functor.map G g := sorry @[simp] theorem hom_equiv_naturality_right_symm {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) {X : C} {Y : D} {Y' : D} (f : X ⟶ functor.obj G Y) (g : Y ⟶ Y') : coe_fn (equiv.symm (hom_equiv adj X Y')) (f ≫ functor.map G g) = coe_fn (equiv.symm (hom_equiv adj X Y)) f ≫ g := sorry @[simp] theorem left_triangle {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) : whisker_right (unit adj) F ≫ whisker_left F (counit adj) = nat_trans.id (𝟭 ⋙ F) := sorry @[simp] theorem right_triangle {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) : whisker_left G (unit adj) ≫ whisker_right (counit adj) G = nat_trans.id (G ⋙ 𝟭) := sorry @[simp] theorem left_triangle_components_assoc {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) {X : C} {X' : D} (f' : functor.obj 𝟭 (functor.obj F X) ⟶ X') : functor.map F (nat_trans.app (unit adj) X) ≫ nat_trans.app (counit adj) (functor.obj F X) ≫ f' = f' := sorry @[simp] theorem right_triangle_components {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) {Y : D} : nat_trans.app (unit adj) (functor.obj G Y) ≫ functor.map G (nat_trans.app (counit adj) Y) = 𝟙 := congr_arg (fun (t : nat_trans (G ⋙ 𝟭) (G ⋙ 𝟭)) => nat_trans.app t Y) (right_triangle adj) @[simp] theorem counit_naturality {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) {X : D} {Y : D} (f : X ⟶ Y) : functor.map F (functor.map G f) ≫ nat_trans.app (counit adj) Y = nat_trans.app (counit adj) X ≫ f := nat_trans.naturality (counit adj) f @[simp] theorem unit_naturality {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) {X : C} {Y : C} (f : X ⟶ Y) : nat_trans.app (unit adj) X ≫ functor.map G (functor.map F f) = f ≫ nat_trans.app (unit adj) Y := Eq.symm (nat_trans.naturality (unit adj) f) theorem hom_equiv_apply_eq {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) {A : C} {B : D} (f : functor.obj F A ⟶ B) (g : A ⟶ functor.obj G B) : coe_fn (hom_equiv adj A B) f = g ↔ f = coe_fn (equiv.symm (hom_equiv adj A B)) g := sorry theorem eq_hom_equiv_apply {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) {A : C} {B : D} (f : functor.obj F A ⟶ B) (g : A ⟶ functor.obj G B) : g = coe_fn (hom_equiv adj A B) f ↔ coe_fn (equiv.symm (hom_equiv adj A B)) g = f := sorry end adjunction namespace adjunction /-- This is an auxiliary data structure useful for constructing adjunctions. See `adjunction.mk_of_hom_equiv`. This structure won't typically be used anywhere else. -/ structure core_hom_equiv {C : Type u₁} [category C] {D : Type u₂} [category D] (F : C ⥤ D) (G : D ⥤ C) where hom_equiv : (X : C) → (Y : D) → (functor.obj F X ⟶ Y) ≃ (X ⟶ functor.obj G Y) hom_equiv_naturality_left_symm' : autoParam (∀ {X' X : C} {Y : D} (f : X' ⟶ X) (g : X ⟶ functor.obj G Y), coe_fn (equiv.symm (hom_equiv X' Y)) (f ≫ g) = functor.map F f ≫ coe_fn (equiv.symm (hom_equiv X Y)) g) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) hom_equiv_naturality_right' : autoParam (∀ {X : C} {Y Y' : D} (f : functor.obj F X ⟶ Y) (g : Y ⟶ Y'), coe_fn (hom_equiv X Y') (f ≫ g) = coe_fn (hom_equiv X Y) f ≫ functor.map G g) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) namespace core_hom_equiv @[simp] theorem hom_equiv_naturality_left_symm {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (c : core_hom_equiv F G) {X' : C} {X : C} {Y : D} (f : X' ⟶ X) (g : X ⟶ functor.obj G Y) : coe_fn (equiv.symm (hom_equiv c X' Y)) (f ≫ g) = functor.map F f ≫ coe_fn (equiv.symm (hom_equiv c X Y)) g := sorry @[simp] theorem hom_equiv_naturality_right {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (c : core_hom_equiv F G) {X : C} {Y : D} {Y' : D} (f : functor.obj F X ⟶ Y) (g : Y ⟶ Y') : coe_fn (hom_equiv c X Y') (f ≫ g) = coe_fn (hom_equiv c X Y) f ≫ functor.map G g := sorry @[simp] theorem hom_equiv_naturality_left {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (adj : core_hom_equiv F G) {X' : C} {X : C} {Y : D} (f : X' ⟶ X) (g : functor.obj F X ⟶ Y) : coe_fn (hom_equiv adj X' Y) (functor.map F f ≫ g) = f ≫ coe_fn (hom_equiv adj X Y) g := sorry @[simp] theorem hom_equiv_naturality_right_symm {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (adj : core_hom_equiv F G) {X : C} {Y : D} {Y' : D} (f : X ⟶ functor.obj G Y) (g : Y ⟶ Y') : coe_fn (equiv.symm (hom_equiv adj X Y')) (f ≫ functor.map G g) = coe_fn (equiv.symm (hom_equiv adj X Y)) f ≫ g := sorry end core_hom_equiv /-- This is an auxiliary data structure useful for constructing adjunctions. See `adjunction.mk_of_hom_equiv`. This structure won't typically be used anywhere else. -/ structure core_unit_counit {C : Type u₁} [category C] {D : Type u₂} [category D] (F : C ⥤ D) (G : D ⥤ C) where unit : 𝟭 ⟶ F ⋙ G counit : G ⋙ F ⟶ 𝟭 left_triangle' : autoParam (whisker_right unit F ≫ iso.hom (functor.associator F G F) ≫ whisker_left F counit = nat_trans.id (𝟭 ⋙ F)) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) right_triangle' : autoParam (whisker_left G unit ≫ iso.inv (functor.associator G F G) ≫ whisker_right counit G = nat_trans.id (G ⋙ 𝟭)) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) namespace core_unit_counit @[simp] theorem left_triangle {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (c : core_unit_counit F G) : whisker_right (unit c) F ≫ iso.hom (functor.associator F G F) ≫ whisker_left F (counit c) = nat_trans.id (𝟭 ⋙ F) := sorry @[simp] theorem right_triangle {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (c : core_unit_counit F G) : whisker_left G (unit c) ≫ iso.inv (functor.associator G F G) ≫ whisker_right (counit c) G = nat_trans.id (G ⋙ 𝟭) := sorry end core_unit_counit /-- Construct an adjunction between `F` and `G` out of a natural bijection between each `F.obj X ⟶ Y` and `X ⟶ G.obj Y`. -/ @[simp] theorem mk_of_hom_equiv_counit_app {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (adj : core_hom_equiv F G) (Y : D) : nat_trans.app (counit (mk_of_hom_equiv adj)) Y = equiv.inv_fun (core_hom_equiv.hom_equiv adj (functor.obj G Y) (functor.obj 𝟭 Y)) 𝟙 := Eq.refl (nat_trans.app (counit (mk_of_hom_equiv adj)) Y) /-- Construct an adjunction between functors `F` and `G` given a unit and counit for the adjunction satisfying the triangle identities. -/ @[simp] theorem mk_of_unit_counit_counit {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (adj : core_unit_counit F G) : counit (mk_of_unit_counit adj) = core_unit_counit.counit adj := Eq.refl (counit (mk_of_unit_counit adj)) /-- The adjunction between the identity functor on a category and itself. -/ def id {C : Type u₁} [category C] : 𝟭 ⊣ 𝟭 := mk (fun (X Y : C) => equiv.refl (functor.obj 𝟭 X ⟶ Y)) 𝟙 𝟙 -- Satisfy the inhabited linter. protected instance inhabited {C : Type u₁} [category C] : Inhabited (𝟭 ⊣ 𝟭) := { default := id } /-- If F and G are naturally isomorphic functors, establish an equivalence of hom-sets. -/ @[simp] theorem equiv_homset_left_of_nat_iso_symm_apply {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {F' : C ⥤ D} (iso : F ≅ F') {X : C} {Y : D} (g : functor.obj F' X ⟶ Y) : coe_fn (equiv.symm (equiv_homset_left_of_nat_iso iso)) g = nat_trans.app (iso.hom iso) X ≫ g := Eq.refl (coe_fn (equiv.symm (equiv_homset_left_of_nat_iso iso)) g) /-- If G and H are naturally isomorphic functors, establish an equivalence of hom-sets. -/ @[simp] theorem equiv_homset_right_of_nat_iso_apply {C : Type u₁} [category C] {D : Type u₂} [category D] {G : D ⥤ C} {G' : D ⥤ C} (iso : G ≅ G') {X : C} {Y : D} (f : X ⟶ functor.obj G Y) : coe_fn (equiv_homset_right_of_nat_iso iso) f = f ≫ nat_trans.app (iso.hom iso) Y := Eq.refl (coe_fn (equiv_homset_right_of_nat_iso iso) f) /-- Transport an adjunction along an natural isomorphism on the left. -/ def of_nat_iso_left {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : C ⥤ D} {H : D ⥤ C} (adj : F ⊣ H) (iso : F ≅ G) : G ⊣ H := mk_of_hom_equiv (core_hom_equiv.mk fun (X : C) (Y : D) => equiv.trans (equiv_homset_left_of_nat_iso (iso.symm iso)) (hom_equiv adj X Y)) /-- Transport an adjunction along an natural isomorphism on the right. -/ def of_nat_iso_right {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} {H : D ⥤ C} (adj : F ⊣ G) (iso : G ≅ H) : F ⊣ H := mk_of_hom_equiv (core_hom_equiv.mk fun (X : C) (Y : D) => equiv.trans (hom_equiv adj X Y) (equiv_homset_right_of_nat_iso iso)) /-- Transport being a right adjoint along a natural isomorphism. -/ def right_adjoint_of_nat_iso {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : C ⥤ D} (h : F ≅ G) [r : is_right_adjoint F] : is_right_adjoint G := is_right_adjoint.mk (is_right_adjoint.left F) (of_nat_iso_right is_right_adjoint.adj h) /-- Transport being a left adjoint along a natural isomorphism. -/ def left_adjoint_of_nat_iso {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : C ⥤ D} (h : F ≅ G) [r : is_left_adjoint F] : is_left_adjoint G := is_left_adjoint.mk (is_left_adjoint.right F) (of_nat_iso_left is_left_adjoint.adj h) /-- Composition of adjunctions. See https://stacks.math.columbia.edu/tag/0DV0. -/ def comp {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} {E : Type u₃} [ℰ : category E] (H : D ⥤ E) (I : E ⥤ D) (adj₁ : F ⊣ G) (adj₂ : H ⊣ I) : F ⋙ H ⊣ I ⋙ G := mk (fun (X : C) (Z : E) => equiv.trans (hom_equiv adj₂ (functor.obj F X) Z) (hom_equiv adj₁ X (functor.obj I Z))) (unit adj₁ ≫ whisker_left F (whisker_right (unit adj₂) G) ≫ iso.inv (functor.associator F (H ⋙ I) G)) (iso.hom (functor.associator I G (F ⋙ H)) ≫ whisker_left I (whisker_right (counit adj₁) H) ≫ counit adj₂) /-- If `F` and `G` are left adjoints then `F ⋙ G` is a left adjoint too. -/ protected instance left_adjoint_of_comp {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [ℰ : category E] (F : C ⥤ D) (G : D ⥤ E) [Fl : is_left_adjoint F] [Gl : is_left_adjoint G] : is_left_adjoint (F ⋙ G) := is_left_adjoint.mk (is_left_adjoint.right G ⋙ is_left_adjoint.right F) (comp G (is_left_adjoint.right G) is_left_adjoint.adj is_left_adjoint.adj) /-- If `F` and `G` are right adjoints then `F ⋙ G` is a right adjoint too. -/ protected instance right_adjoint_of_comp {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [ℰ : category E] {F : C ⥤ D} {G : D ⥤ E} [Fr : is_right_adjoint F] [Gr : is_right_adjoint G] : is_right_adjoint (F ⋙ G) := is_right_adjoint.mk (is_right_adjoint.left G ⋙ is_right_adjoint.left F) (comp (is_right_adjoint.left F) F is_right_adjoint.adj is_right_adjoint.adj) -- Construction of a left adjoint. In order to construct a left -- adjoint to a functor G : D → C, it suffices to give the object part -- of a functor F : C → D together with isomorphisms Hom(FX, Y) ≃ -- Hom(X, GY) natural in Y. The action of F on morphisms can be -- constructed from this data. /-- Construct a left adjoint functor to `G`, given the functor's value on objects `F_obj` and a bijection `e` between `F_obj X ⟶ Y` and `X ⟶ G.obj Y` satisfying a naturality law `he : ∀ X Y Y' g h, e X Y' (h ≫ g) = e X Y h ≫ G.map g`. Dual to `right_adjoint_of_equiv`. -/ @[simp] theorem left_adjoint_of_equiv_obj {C : Type u₁} [category C] {D : Type u₂} [category D] {G : D ⥤ C} {F_obj : C → D} (e : (X : C) → (Y : D) → (F_obj X ⟶ Y) ≃ (X ⟶ functor.obj G Y)) (he : ∀ (X : C) (Y Y' : D) (g : Y ⟶ Y') (h : F_obj X ⟶ Y), coe_fn (e X Y') (h ≫ g) = coe_fn (e X Y) h ≫ functor.map G g) : ∀ (ᾰ : C), functor.obj (left_adjoint_of_equiv e he) ᾰ = F_obj ᾰ := fun (ᾰ : C) => Eq.refl (functor.obj (left_adjoint_of_equiv e he) ᾰ) /-- Show that the functor given by `left_adjoint_of_equiv` is indeed left adjoint to `G`. Dual to `adjunction_of_equiv_right`. -/ @[simp] theorem adjunction_of_equiv_left_hom_equiv {C : Type u₁} [category C] {D : Type u₂} [category D] {G : D ⥤ C} {F_obj : C → D} (e : (X : C) → (Y : D) → (F_obj X ⟶ Y) ≃ (X ⟶ functor.obj G Y)) (he : ∀ (X : C) (Y Y' : D) (g : Y ⟶ Y') (h : F_obj X ⟶ Y), coe_fn (e X Y') (h ≫ g) = coe_fn (e X Y) h ≫ functor.map G g) (X : C) (Y : D) : hom_equiv (adjunction_of_equiv_left e he) X Y = e X Y := Eq.refl (e X Y) -- Construction of a right adjoint, analogous to the above. /-- Construct a right adjoint functor to `F`, given the functor's value on objects `G_obj` and a bijection `e` between `F.obj X ⟶ Y` and `X ⟶ G_obj Y` satisfying a naturality law `he : ∀ X Y Y' g h, e X' Y (F.map f ≫ g) = f ≫ e X Y g`. Dual to `left_adjoint_of_equiv`. -/ @[simp] theorem right_adjoint_of_equiv_obj {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G_obj : D → C} (e : (X : C) → (Y : D) → (functor.obj F X ⟶ Y) ≃ (X ⟶ G_obj Y)) (he : ∀ (X' X : C) (Y : D) (f : X' ⟶ X) (g : functor.obj F X ⟶ Y), coe_fn (e X' Y) (functor.map F f ≫ g) = f ≫ coe_fn (e X Y) g) : ∀ (ᾰ : D), functor.obj (right_adjoint_of_equiv e he) ᾰ = G_obj ᾰ := fun (ᾰ : D) => Eq.refl (functor.obj (right_adjoint_of_equiv e he) ᾰ) /-- Show that the functor given by `right_adjoint_of_equiv` is indeed right adjoint to `F`. Dual to `adjunction_of_equiv_left`. -/ @[simp] theorem adjunction_of_equiv_right_counit_app {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G_obj : D → C} (e : (X : C) → (Y : D) → (functor.obj F X ⟶ Y) ≃ (X ⟶ G_obj Y)) (he : ∀ (X' X : C) (Y : D) (f : X' ⟶ X) (g : functor.obj F X ⟶ Y), coe_fn (e X' Y) (functor.map F f ≫ g) = f ≫ coe_fn (e X Y) g) (Y : D) : nat_trans.app (counit (adjunction_of_equiv_right e he)) Y = coe_fn (equiv.symm (e (G_obj Y) Y)) 𝟙 := Eq.refl (coe_fn (equiv.symm (e (G_obj Y) Y)) 𝟙) /-- If the unit and counit of a given adjunction are (pointwise) isomorphisms, then we can upgrade the adjunction to an equivalence. -/ @[simp] theorem to_equivalence_functor {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) [(X : C) → is_iso (nat_trans.app (unit adj) X)] [(Y : D) → is_iso (nat_trans.app (counit adj) Y)] : equivalence.functor (to_equivalence adj) = F := Eq.refl (equivalence.functor (to_equivalence adj)) /-- If the unit and counit for the adjunction corresponding to a right adjoint functor are (pointwise) isomorphisms, then the functor is an equivalence of categories. -/ @[simp] theorem is_right_adjoint_to_is_equivalence_unit_iso_inv_app {C : Type u₁} [category C] {D : Type u₂} [category D] {G : D ⥤ C} [is_right_adjoint G] [(X : C) → is_iso (nat_trans.app (unit (of_right_adjoint G)) X)] [(Y : D) → is_iso (nat_trans.app (counit (of_right_adjoint G)) Y)] (X : D) : nat_trans.app (iso.inv is_equivalence.unit_iso) X = nat_trans.app (counit (of_right_adjoint G)) X := Eq.refl (nat_trans.app (counit (of_right_adjoint G)) X) end adjunction namespace equivalence /-- The adjunction given by an equivalence of categories. (To obtain the opposite adjunction, simply use `e.symm.to_adjunction`. -/ def to_adjunction {C : Type u₁} [category C] {D : Type u₂} [category D] (e : C ≌ D) : functor e ⊣ inverse e := adjunction.mk_of_unit_counit (adjunction.core_unit_counit.mk (unit e) (counit e)) end equivalence namespace functor /-- An equivalence `E` is left adjoint to its inverse. -/ def adjunction {C : Type u₁} [category C] {D : Type u₂} [category D] (E : C ⥤ D) [is_equivalence E] : E ⊣ inv E := equivalence.to_adjunction (as_equivalence E) /-- If `F` is an equivalence, it's a left adjoint. -/ protected instance left_adjoint_of_equivalence {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} [is_equivalence F] : is_left_adjoint F := is_left_adjoint.mk (inv F) (adjunction F) @[simp] theorem right_adjoint_of_is_equivalence {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} [is_equivalence F] : right_adjoint F = inv F := rfl /-- If `F` is an equivalence, it's a right adjoint. -/ protected instance right_adjoint_of_equivalence {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} [is_equivalence F] : is_right_adjoint F := is_right_adjoint.mk (inv F) (adjunction (inv F)) @[simp] theorem left_adjoint_of_is_equivalence {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} [is_equivalence F] : left_adjoint F = inv F := rfl end Mathlib
2ef967e107ba3f88ab29845d2d17d3cbfe4c02dc
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/def11.lean
1b9edc43e500a157f2d092ecfaaa3c9a39e2153d
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,271
lean
new_frontend inductive Formula | eqf : Nat → Nat → Formula | andf : Formula → Formula → Formula | impf : Formula → Formula → Formula | notf : Formula → Formula | orf : Formula → Formula → Formula | allf : (Nat → Formula) → Formula namespace Formula def implies (a b : Prop) : Prop := a → b def denote : Formula → Prop | eqf n1 n2 => n1 = n2 | andf f1 f2 => denote f1 ∧ denote f2 | impf f1 f2 => implies (denote f1) (denote f2) | orf f1 f2 => denote f1 ∨ denote f2 | notf f => ¬ denote f | allf f => (n : Nat) → denote (f n) theorem denote_eqf (n1 n2 : Nat) : denote (eqf n1 n2) = (n1 = n2) := rfl theorem denote_andf (f1 f2 : Formula) : denote (andf f1 f2) = (denote f1 ∧ denote f2) := rfl theorem denote_impf (f1 f2 : Formula) : denote (impf f1 f2) = (denote f1 → denote f2) := rfl theorem denote_orf (f1 f2 : Formula) : denote (orf f1 f2) = (denote f1 ∨ denote f2) := rfl theorem denote_notf (f : Formula) : denote (notf f) = ¬ denote f := rfl theorem denote_allf (f : Nat → Formula) : denote (allf f) = (∀ n, denote (f n)) := rfl theorem ex : denote (allf (fun n₁ => allf (fun n₂ => impf (eqf n₁ n₂) (eqf n₂ n₁)))) = (∀ (n₁ n₂ : Nat), n₁ = n₂ → n₂ = n₁) := rfl end Formula
4d0ec7e56291e1f7cd002569a3d472d2f8f60cbb
4fa161becb8ce7378a709f5992a594764699e268
/src/data/complex/exponential.lean
5c4c099d53046f0bbec26ce880893ff822c489c8
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
49,784
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir -/ import algebra.geom_sum import data.nat.choose import data.complex.basic /-! # Exponential, trigonometric and hyperbolic trigonometric functions This file containss the definitions of the real and complex exponential, sine, cosine, tangent, hyperbolic sine, hypebolic cosine, and hyperbolic tangent functions. -/ local notation `abs'` := _root_.abs open is_absolute_value open_locale classical big_operators section open real is_absolute_value finset lemma forall_ge_le_of_forall_le_succ {α : Type*} [preorder α] (f : ℕ → α) {m : ℕ} (h : ∀ n ≥ m, f n.succ ≤ f n) : ∀ {l}, ∀ k ≥ m, k ≤ l → f l ≤ f k := begin assume l k hkm hkl, generalize hp : l - k = p, have : l = k + p := add_comm p k ▸ (nat.sub_eq_iff_eq_add hkl).1 hp, subst this, clear hkl hp, induction p with p ih, { simp }, { exact le_trans (h _ (le_trans hkm (nat.le_add_right _ _))) ih } end section variables {α : Type*} {β : Type*} [ring β] [discrete_linear_ordered_field α] [archimedean α] {abv : β → α} [is_absolute_value abv] lemma is_cau_of_decreasing_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, abs (f n) ≤ a) (hnm : ∀ n ≥ m, f n.succ ≤ f n) : is_cau_seq abs f := λ ε ε0, let ⟨k, hk⟩ := archimedean.arch a ε0 in have h : ∃ l, ∀ n ≥ m, a - l •ℕ ε < f n := ⟨k + k + 1, λ n hnm, lt_of_lt_of_le (show a - (k + (k + 1)) •ℕ ε < -abs (f n), from lt_neg.1 $ lt_of_le_of_lt (ham n hnm) (begin rw [neg_sub, lt_sub_iff_add_lt, add_nsmul], exact add_lt_add_of_le_of_lt hk (lt_of_le_of_lt hk (lt_add_of_pos_left _ ε0)), end)) (neg_le.2 $ (abs_neg (f n)) ▸ le_abs_self _)⟩, let l := nat.find h in have hl : ∀ (n : ℕ), n ≥ m → f n > a - l •ℕ ε := nat.find_spec h, have hl0 : l ≠ 0 := λ hl0, not_lt_of_ge (ham m (le_refl _)) (lt_of_lt_of_le (by have := hl m (le_refl m); simpa [hl0] using this) (le_abs_self (f m))), begin cases classical.not_forall.1 (nat.find_min h (nat.pred_lt hl0)) with i hi, rw [not_imp, not_lt] at hi, existsi i, assume j hj, have hfij : f j ≤ f i := forall_ge_le_of_forall_le_succ f hnm _ hi.1 hj, rw [abs_of_nonpos (sub_nonpos.2 hfij), neg_sub, sub_lt_iff_lt_add'], exact calc f i ≤ a - (nat.pred l) •ℕ ε : hi.2 ... = a - l •ℕ ε + ε : by conv {to_rhs, rw [← nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero hl0), succ_nsmul', sub_add, add_sub_cancel] } ... < f j + ε : add_lt_add_right (hl j (le_trans hi.1 hj)) _ end lemma is_cau_of_mono_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, abs (f n) ≤ a) (hnm : ∀ n ≥ m, f n ≤ f n.succ) : is_cau_seq abs f := begin refine @eq.rec_on (ℕ → α) _ (is_cau_seq abs) _ _ (-⟨_, @is_cau_of_decreasing_bounded _ _ _ (λ n, -f n) a m (by simpa) (by simpa)⟩ : cau_seq α abs).2, ext, exact neg_neg _ end end section no_archimedean variables {α : Type*} {β : Type*} [ring β] [discrete_linear_ordered_field α] {abv : β → α} [is_absolute_value abv] lemma is_cau_series_of_abv_le_cau {f : ℕ → β} {g : ℕ → α} (n : ℕ) : (∀ m, n ≤ m → abv (f m) ≤ g m) → is_cau_seq abs (λ n, ∑ i in range n, g i) → is_cau_seq abv (λ n, ∑ i in range n, f i) := begin assume hm hg ε ε0, cases hg (ε / 2) (div_pos ε0 (by norm_num)) with i hi, existsi max n i, assume j ji, have hi₁ := hi j (le_trans (le_max_right n i) ji), have hi₂ := hi (max n i) (le_max_right n i), have sub_le := abs_sub_le (∑ k in range j, g k) (∑ k in range i, g k) (∑ k in range (max n i), g k), have := add_lt_add hi₁ hi₂, rw [abs_sub (∑ k in range (max n i), g k), add_halves ε] at this, refine lt_of_le_of_lt (le_trans (le_trans _ (le_abs_self _)) sub_le) this, generalize hk : j - max n i = k, clear this hi₂ hi₁ hi ε0 ε hg sub_le, rw nat.sub_eq_iff_eq_add ji at hk, rw hk, clear hk ji j, induction k with k' hi, { simp [abv_zero abv] }, { dsimp at *, simp only [nat.succ_add, sum_range_succ, sub_eq_add_neg, add_assoc], refine le_trans (abv_add _ _ _) _, exact add_le_add (hm _ (le_add_of_nonneg_of_le (nat.zero_le _) (le_max_left _ _))) hi }, end lemma is_cau_series_of_abv_cau {f : ℕ → β} : is_cau_seq abs (λ m, ∑ n in range m, abv (f n)) → is_cau_seq abv (λ m, ∑ n in range m, f n) := is_cau_series_of_abv_le_cau 0 (λ n h, le_refl _) end no_archimedean section variables {α : Type*} {β : Type*} [ring β] [discrete_linear_ordered_field α] [archimedean α] {abv : β → α} [is_absolute_value abv] lemma is_cau_geo_series {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] (x : β) (hx1 : abv x < 1) : is_cau_seq abv (λ n, ∑ m in range n, x ^ m) := have hx1' : abv x ≠ 1 := λ h, by simpa [h, lt_irrefl] using hx1, is_cau_series_of_abv_cau begin simp only [abv_pow abv] {eta := ff}, have : (λ (m : ℕ), ∑ n in range m, (abv x) ^ n) = λ m, geom_series (abv x) m := rfl, simp only [this, geom_sum hx1'] {eta := ff}, conv in (_ / _) { rw [← neg_div_neg_eq, neg_sub, neg_sub] }, refine @is_cau_of_mono_bounded _ _ _ _ ((1 : α) / (1 - abv x)) 0 _ _, { assume n hn, rw abs_of_nonneg, refine div_le_div_of_le_of_pos (sub_le_self _ (abv_pow abv x n ▸ abv_nonneg _ _)) (sub_pos.2 hx1), refine div_nonneg (sub_nonneg.2 _) (sub_pos.2 hx1), clear hn, induction n with n ih, { simp }, { rw [pow_succ, ← one_mul (1 : α)], refine mul_le_mul (le_of_lt hx1) ih (abv_pow abv x n ▸ abv_nonneg _ _) (by norm_num) } }, { assume n hn, refine div_le_div_of_le_of_pos (sub_le_sub_left _ _) (sub_pos.2 hx1), rw [← one_mul (_ ^ n), pow_succ], exact mul_le_mul_of_nonneg_right (le_of_lt hx1) (pow_nonneg (abv_nonneg _ _) _) } end lemma is_cau_geo_series_const (a : α) {x : α} (hx1 : abs x < 1) : is_cau_seq abs (λ m, ∑ n in range m, a * x ^ n) := have is_cau_seq abs (λ m, a * ∑ n in range m, x ^ n) := (cau_seq.const abs a * ⟨_, is_cau_geo_series x hx1⟩).2, by simpa only [mul_sum] lemma series_ratio_test {f : ℕ → β} (n : ℕ) (r : α) (hr0 : 0 ≤ r) (hr1 : r < 1) (h : ∀ m, n ≤ m → abv (f m.succ) ≤ r * abv (f m)) : is_cau_seq abv (λ m, ∑ n in range m, f n) := have har1 : abs r < 1, by rwa abs_of_nonneg hr0, begin refine is_cau_series_of_abv_le_cau n.succ _ (is_cau_geo_series_const (abv (f n.succ) * r⁻¹ ^ n.succ) har1), assume m hmn, cases classical.em (r = 0) with r_zero r_ne_zero, { have m_pos := lt_of_lt_of_le (nat.succ_pos n) hmn, have := h m.pred (nat.le_of_succ_le_succ (by rwa [nat.succ_pred_eq_of_pos m_pos])), simpa [r_zero, nat.succ_pred_eq_of_pos m_pos, pow_succ] }, generalize hk : m - n.succ = k, have r_pos : 0 < r := lt_of_le_of_ne hr0 (ne.symm r_ne_zero), replace hk : m = k + n.succ := (nat.sub_eq_iff_eq_add hmn).1 hk, induction k with k ih generalizing m n, { rw [hk, zero_add, mul_right_comm, inv_pow' _ _, ← div_eq_mul_inv, mul_div_cancel], exact (ne_of_lt (pow_pos r_pos _)).symm }, { have kn : k + n.succ ≥ n.succ, by rw ← zero_add n.succ; exact add_le_add (zero_le _) (by simp), rw [hk, nat.succ_add, pow_succ' r, ← mul_assoc], exact le_trans (by rw mul_comm; exact h _ (nat.le_of_succ_le kn)) (mul_le_mul_of_nonneg_right (ih (k + n.succ) n h kn rfl) hr0) } end lemma sum_range_diag_flip {α : Type*} [add_comm_monoid α] (n : ℕ) (f : ℕ → ℕ → α) : ∑ m in range n, ∑ k in range (m + 1), f k (m - k) = ∑ m in range n, ∑ k in range (n - m), f m k := have h₁ : ∑ a in (range n).sigma (range ∘ nat.succ), f (a.2) (a.1 - a.2) = ∑ m in range n, ∑ k in range (m + 1), f k (m - k) := sum_sigma, have h₂ : ∑ a in (range n).sigma (λ m, range (n - m)), f (a.1) (a.2) = ∑ m in range n, ∑ k in range (n - m), f m k := sum_sigma, h₁ ▸ h₂ ▸ sum_bij (λ a _, ⟨a.2, a.1 - a.2⟩) (λ a ha, have h₁ : a.1 < n := mem_range.1 (mem_sigma.1 ha).1, have h₂ : a.2 < nat.succ a.1 := mem_range.1 (mem_sigma.1 ha).2, mem_sigma.2 ⟨mem_range.2 (lt_of_lt_of_le h₂ h₁), mem_range.2 ((nat.sub_lt_sub_right_iff (nat.le_of_lt_succ h₂)).2 h₁)⟩) (λ _ _, rfl) (λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩ ha hb h, have ha : a₁ < n ∧ a₂ ≤ a₁ := ⟨mem_range.1 (mem_sigma.1 ha).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 ha).2)⟩, have hb : b₁ < n ∧ b₂ ≤ b₁ := ⟨mem_range.1 (mem_sigma.1 hb).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 hb).2)⟩, have h : a₂ = b₂ ∧ _ := sigma.mk.inj h, have h' : a₁ = b₁ - b₂ + a₂ := (nat.sub_eq_iff_eq_add ha.2).1 (eq_of_heq h.2), sigma.mk.inj_iff.2 ⟨nat.sub_add_cancel hb.2 ▸ h'.symm ▸ h.1 ▸ rfl, (heq_of_eq h.1)⟩) (λ ⟨a₁, a₂⟩ ha, have ha : a₁ < n ∧ a₂ < n - a₁ := ⟨mem_range.1 (mem_sigma.1 ha).1, (mem_range.1 (mem_sigma.1 ha).2)⟩, ⟨⟨a₂ + a₁, a₁⟩, ⟨mem_sigma.2 ⟨mem_range.2 (nat.lt_sub_right_iff_add_lt.1 ha.2), mem_range.2 (nat.lt_succ_of_le (nat.le_add_left _ _))⟩, sigma.mk.inj_iff.2 ⟨rfl, heq_of_eq (nat.add_sub_cancel _ _).symm⟩⟩⟩) lemma sum_range_sub_sum_range {α : Type*} [add_comm_group α] {f : ℕ → α} {n m : ℕ} (hnm : n ≤ m) : ∑ k in range m, f k - ∑ k in range n, f k = ∑ k in (range m).filter (λ k, n ≤ k), f k := begin rw [← sum_sdiff (@filter_subset _ (λ k, n ≤ k) _ (range m)), sub_eq_iff_eq_add, ← eq_sub_iff_add_eq, add_sub_cancel'], refine finset.sum_congr (finset.ext $ λ a, ⟨λ h, by simp at *; finish, λ h, have ham : a < m := lt_of_lt_of_le (mem_range.1 h) hnm, by simp * at *⟩) (λ _ _, rfl), end end section no_archimedean variables {α : Type*} {β : Type*} [ring β] [discrete_linear_ordered_field α] {abv : β → α} [is_absolute_value abv] lemma abv_sum_le_sum_abv {γ : Type*} (f : γ → β) (s : finset γ) : abv (∑ k in s, f k) ≤ ∑ k in s, abv (f k) := by haveI := classical.dec_eq γ; exact finset.induction_on s (by simp [abv_zero abv]) (λ a s has ih, by rw [sum_insert has, sum_insert has]; exact le_trans (abv_add abv _ _) (add_le_add_left ih _)) @[nolint ge_or_gt] -- see Note [nolint_ge] lemma cauchy_product {a b : ℕ → β} (ha : is_cau_seq abs (λ m, ∑ n in range m, abv (a n))) (hb : is_cau_seq abv (λ m, ∑ n in range m, b n)) (ε : α) (ε0 : 0 < ε) : ∃ i : ℕ, ∀ j ≥ i, abv ((∑ k in range j, a k) * (∑ k in range j, b k) - ∑ n in range j, ∑ m in range (n + 1), a m * b (n - m)) < ε := let ⟨Q, hQ⟩ := cau_seq.bounded ⟨_, hb⟩ in let ⟨P, hP⟩ := cau_seq.bounded ⟨_, ha⟩ in have hP0 : 0 < P, from lt_of_le_of_lt (abs_nonneg _) (hP 0), have hPε0 : 0 < ε / (2 * P), from div_pos ε0 (mul_pos (show (2 : α) > 0, from by norm_num) hP0), let ⟨N, hN⟩ := cau_seq.cauchy₂ ⟨_, hb⟩ hPε0 in have hQε0 : 0 < ε / (4 * Q), from div_pos ε0 (mul_pos (show (0 : α) < 4, by norm_num) (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))), let ⟨M, hM⟩ := cau_seq.cauchy₂ ⟨_, ha⟩ hQε0 in ⟨2 * (max N M + 1), λ K hK, have h₁ : ∑ m in range K, ∑ k in range (m + 1), a k * b (m - k) = ∑ m in range K, ∑ n in range (K - m), a m * b n, by simpa using sum_range_diag_flip K (λ m n, a m * b n), have h₂ : (λ i, ∑ k in range (K - i), a i * b k) = (λ i, a i * ∑ k in range (K - i), b k), by simp [finset.mul_sum], have h₃ : ∑ i in range K, a i * ∑ k in range (K - i), b k = ∑ i in range K, a i * (∑ k in range (K - i), b k - ∑ k in range K, b k) + ∑ i in range K, a i * ∑ k in range K, b k, by rw ← sum_add_distrib; simp [(mul_add _ _ _).symm], have two_mul_two : (4 : α) = 2 * 2, by norm_num, have hQ0 : Q ≠ 0, from λ h, by simpa [h, lt_irrefl] using hQε0, have h2Q0 : 2 * Q ≠ 0, from mul_ne_zero two_ne_zero hQ0, have hε : ε / (2 * P) * P + ε / (4 * Q) * (2 * Q) = ε, by rw [← div_div_eq_div_mul, div_mul_cancel _ (ne.symm (ne_of_lt hP0)), two_mul_two, mul_assoc, ← div_div_eq_div_mul, div_mul_cancel _ h2Q0, add_halves], have hNMK : max N M + 1 < K, from lt_of_lt_of_le (by rw two_mul; exact lt_add_of_pos_left _ (nat.succ_pos _)) hK, have hKN : N < K, from calc N ≤ max N M : le_max_left _ _ ... < max N M + 1 : nat.lt_succ_self _ ... < K : hNMK, have hsumlesum : ∑ i in range (max N M + 1), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) ≤ ∑ i in range (max N M + 1), abv (a i) * (ε / (2 * P)), from sum_le_sum (λ m hmJ, mul_le_mul_of_nonneg_left (le_of_lt (hN (K - m) K (nat.le_sub_left_of_add_le (le_trans (by rw two_mul; exact add_le_add (le_of_lt (mem_range.1 hmJ)) (le_trans (le_max_left _ _) (le_of_lt (lt_add_one _)))) hK)) (le_of_lt hKN))) (abv_nonneg abv _)), have hsumltP : ∑ n in range (max N M + 1), abv (a n) < P := calc ∑ n in range (max N M + 1), abv (a n) = abs (∑ n in range (max N M + 1), abv (a n)) : eq.symm (abs_of_nonneg (sum_nonneg (λ x h, abv_nonneg abv (a x)))) ... < P : hP (max N M + 1), begin rw [h₁, h₂, h₃, sum_mul, ← sub_sub, sub_right_comm, sub_self, zero_sub, abv_neg abv], refine lt_of_le_of_lt (abv_sum_le_sum_abv _ _) _, suffices : ∑ i in range (max N M + 1), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) + (∑ i in range K, abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) - ∑ i in range (max N M + 1), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k)) < ε / (2 * P) * P + ε / (4 * Q) * (2 * Q), { rw hε at this, simpa [abv_mul abv] }, refine add_lt_add (lt_of_le_of_lt hsumlesum (by rw [← sum_mul, mul_comm]; exact (mul_lt_mul_left hPε0).mpr hsumltP)) _, rw sum_range_sub_sum_range (le_of_lt hNMK), exact calc ∑ i in (range K).filter (λ k, max N M + 1 ≤ k), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) ≤ ∑ i in (range K).filter (λ k, max N M + 1 ≤ k), abv (a i) * (2 * Q) : sum_le_sum (λ n hn, begin refine mul_le_mul_of_nonneg_left _ (abv_nonneg _ _), rw sub_eq_add_neg, refine le_trans (abv_add _ _ _) _, rw [two_mul, abv_neg abv], exact add_le_add (le_of_lt (hQ _)) (le_of_lt (hQ _)), end) ... < ε / (4 * Q) * (2 * Q) : by rw [← sum_mul, ← sum_range_sub_sum_range (le_of_lt hNMK)]; refine (mul_lt_mul_right $ by rw two_mul; exact add_pos (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0)) (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))).2 (lt_of_le_of_lt (le_abs_self _) (hM _ _ (le_trans (nat.le_succ_of_le (le_max_right _ _)) (le_of_lt hNMK)) (nat.le_succ_of_le (le_max_right _ _)))) end⟩ end no_archimedean end open finset open cau_seq namespace complex lemma is_cau_abs_exp (z : ℂ) : is_cau_seq _root_.abs (λ n, ∑ m in range n, abs (z ^ m / nat.fact m)) := let ⟨n, hn⟩ := exists_nat_gt (abs z) in have hn0 : (0 : ℝ) < n, from lt_of_le_of_lt (abs_nonneg _) hn, series_ratio_test n (complex.abs z / n) (div_nonneg_of_nonneg_of_pos (complex.abs_nonneg _) hn0) (by rwa [div_lt_iff hn0, one_mul]) (λ m hm, by rw [abs_abs, abs_abs, nat.fact_succ, pow_succ, mul_comm m.succ, nat.cast_mul, ← div_div_eq_div_mul, mul_div_assoc, mul_div_right_comm, abs_mul, abs_div, abs_cast_nat]; exact mul_le_mul_of_nonneg_right (div_le_div_of_le_left (abs_nonneg _) hn0 (nat.cast_le.2 (le_trans hm (nat.le_succ _)))) (abs_nonneg _)) noncomputable theory lemma is_cau_exp (z : ℂ) : is_cau_seq abs (λ n, ∑ m in range n, z ^ m / nat.fact m) := is_cau_series_of_abv_cau (is_cau_abs_exp z) /-- The Cauchy sequence consisting of partial sums of the Taylor series of the complex exponential function -/ @[pp_nodot] def exp' (z : ℂ) : cau_seq ℂ complex.abs := ⟨λ n, ∑ m in range n, z ^ m / nat.fact m, is_cau_exp z⟩ /-- The complex exponential function, defined via its Taylor series -/ @[pp_nodot] def exp (z : ℂ) : ℂ := lim (exp' z) /-- The complex sine function, defined via `exp` -/ @[pp_nodot] def sin (z : ℂ) : ℂ := ((exp (-z * I) - exp (z * I)) * I) / 2 /-- The complex cosine function, defined via `exp` -/ @[pp_nodot] def cos (z : ℂ) : ℂ := (exp (z * I) + exp (-z * I)) / 2 /-- The complex tangent function, defined as `sin z / cos z` -/ @[pp_nodot] def tan (z : ℂ) : ℂ := sin z / cos z /-- The complex hyperbolic sine function, defined via `exp` -/ @[pp_nodot] def sinh (z : ℂ) : ℂ := (exp z - exp (-z)) / 2 /-- The complex hyperbolic cosine function, defined via `exp` -/ @[pp_nodot] def cosh (z : ℂ) : ℂ := (exp z + exp (-z)) / 2 /-- The complex hyperbolic tangent function, defined as `sinh z / cosh z` -/ @[pp_nodot] def tanh (z : ℂ) : ℂ := sinh z / cosh z end complex namespace real open complex /-- The real exponential function, defined as the real part of the complex exponential -/ @[pp_nodot] def exp (x : ℝ) : ℝ := (exp x).re /-- The real sine function, defined as the real part of the complex sine -/ @[pp_nodot] def sin (x : ℝ) : ℝ := (sin x).re /-- The real cosine function, defined as the real part of the complex cosine -/ @[pp_nodot] def cos (x : ℝ) : ℝ := (cos x).re /-- The real tangent function, defined as the real part of the complex tangent -/ @[pp_nodot] def tan (x : ℝ) : ℝ := (tan x).re /-- The real hypebolic sine function, defined as the real part of the complex hyperbolic sine -/ @[pp_nodot] def sinh (x : ℝ) : ℝ := (sinh x).re /-- The real hypebolic cosine function, defined as the real part of the complex hyperbolic cosine -/ @[pp_nodot] def cosh (x : ℝ) : ℝ := (cosh x).re /-- The real hypebolic tangent function, defined as the real part of the complex hyperbolic tangent -/ @[pp_nodot] def tanh (x : ℝ) : ℝ := (tanh x).re end real namespace complex variables (x y : ℂ) @[simp] lemma exp_zero : exp 0 = 1 := lim_eq_of_equiv_const $ λ ε ε0, ⟨1, λ j hj, begin convert ε0, cases j, { exact absurd hj (not_le_of_gt zero_lt_one) }, { dsimp [exp'], induction j with j ih, { dsimp [exp']; simp }, { rw ← ih dec_trivial, simp only [sum_range_succ, pow_succ], simp } } end⟩ lemma exp_add : exp (x + y) = exp x * exp y := show lim (⟨_, is_cau_exp (x + y)⟩ : cau_seq ℂ abs) = lim (show cau_seq ℂ abs, from ⟨_, is_cau_exp x⟩) * lim (show cau_seq ℂ abs, from ⟨_, is_cau_exp y⟩), from have hj : ∀ j : ℕ, ∑ m in range j, (x + y) ^ m / m.fact = ∑ i in range j, ∑ k in range (i + 1), x ^ k / k.fact * (y ^ (i - k) / (i - k).fact), from assume j, finset.sum_congr rfl (λ m hm, begin rw [add_pow, div_eq_mul_inv, sum_mul], refine finset.sum_congr rfl (λ i hi, _), have h₁ : (m.choose i : ℂ) ≠ 0 := nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 (nat.choose_pos (nat.le_of_lt_succ (mem_range.1 hi)))), have h₂ := nat.choose_mul_fact_mul_fact (nat.le_of_lt_succ $ finset.mem_range.1 hi), rw [← h₂, nat.cast_mul, nat.cast_mul, mul_inv', mul_inv'], simp only [mul_left_comm (m.choose i : ℂ), mul_assoc, mul_left_comm (m.choose i : ℂ)⁻¹, mul_comm (m.choose i : ℂ)], rw inv_mul_cancel h₁, simp [div_eq_mul_inv, mul_comm, mul_assoc, mul_left_comm] end), by rw lim_mul_lim; exact eq.symm (lim_eq_lim_of_equiv (by dsimp; simp only [hj]; exact cauchy_product (is_cau_abs_exp x) (is_cau_exp y))) attribute [irreducible] complex.exp lemma exp_list_sum (l : list ℂ) : exp l.sum = (l.map exp).prod := @monoid_hom.map_list_prod (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ l lemma exp_multiset_sum (s : multiset ℂ) : exp s.sum = (s.map exp).prod := @monoid_hom.map_multiset_prod (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ s lemma exp_sum {α : Type*} (s : finset α) (f : α → ℂ) : exp (∑ x in s, f x) = ∏ x in s, exp (f x) := @monoid_hom.map_prod α (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ f s lemma exp_nat_mul (x : ℂ) : ∀ n : ℕ, exp(n*x) = (exp x)^n | 0 := by rw [nat.cast_zero, zero_mul, exp_zero, pow_zero] | (nat.succ n) := by rw [pow_succ', nat.cast_add_one, add_mul, exp_add, ←exp_nat_mul, one_mul] lemma exp_ne_zero : exp x ≠ 0 := λ h, zero_ne_one $ by rw [← exp_zero, ← add_neg_self x, exp_add, h]; simp lemma exp_neg : exp (-x) = (exp x)⁻¹ := by rw [← domain.mul_right_inj (exp_ne_zero x), ← exp_add]; simp [mul_inv_cancel (exp_ne_zero x)] lemma exp_sub : exp (x - y) = exp x / exp y := by simp [sub_eq_add_neg, exp_add, exp_neg, div_eq_mul_inv] @[simp] lemma exp_conj : exp (conj x) = conj (exp x) := begin dsimp [exp], rw [← lim_conj], refine congr_arg lim (cau_seq.ext (λ _, _)), dsimp [exp', function.comp, cau_seq_conj], rw ← sum_hom _ conj, refine sum_congr rfl (λ n hn, _), rw [conj_div, conj_pow, ← of_real_nat_cast, conj_of_real] end @[simp] lemma of_real_exp_of_real_re (x : ℝ) : ((exp x).re : ℂ) = exp x := eq_conj_iff_re.1 $ by rw [← exp_conj, conj_of_real] @[simp] lemma of_real_exp (x : ℝ) : (real.exp x : ℂ) = exp x := of_real_exp_of_real_re _ @[simp] lemma exp_of_real_im (x : ℝ) : (exp x).im = 0 := by rw [← of_real_exp_of_real_re, of_real_im] lemma exp_of_real_re (x : ℝ) : (exp x).re = real.exp x := rfl lemma two_sinh : 2 * sinh x = exp x - exp (-x) := mul_div_cancel' _ two_ne_zero' lemma two_cosh : 2 * cosh x = exp x + exp (-x) := mul_div_cancel' _ two_ne_zero' @[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh] @[simp] lemma sinh_neg : sinh (-x) = -sinh x := by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul] private lemma sinh_add_aux {a b c d : ℂ} : (a - b) * (c + d) + (a + b) * (c - d) = 2 * (a * c - b * d) := by ring lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y := begin rw [← domain.mul_right_inj (@two_ne_zero' ℂ _ _ _), two_sinh, exp_add, neg_add, exp_add, eq_comm, mul_add, ← mul_assoc, two_sinh, mul_left_comm, two_sinh, ← domain.mul_right_inj (@two_ne_zero' ℂ _ _ _), mul_add, mul_left_comm, two_cosh, ← mul_assoc, two_cosh], exact sinh_add_aux end @[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh] @[simp] lemma cosh_neg : cosh (-x) = cosh x := by simp [add_comm, cosh, exp_neg] private lemma cosh_add_aux {a b c d : ℂ} : (a + b) * (c + d) + (a - b) * (c - d) = 2 * (a * c + b * d) := by ring lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y := begin rw [← domain.mul_right_inj (@two_ne_zero' ℂ _ _ _), two_cosh, exp_add, neg_add, exp_add, eq_comm, mul_add, ← mul_assoc, two_cosh, ← mul_assoc, two_sinh, ← domain.mul_right_inj (@two_ne_zero' ℂ _ _ _), mul_add, mul_left_comm, two_cosh, mul_left_comm, two_sinh], exact cosh_add_aux end lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y := by simp [sub_eq_add_neg, sinh_add, sinh_neg, cosh_neg] lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y := by simp [sub_eq_add_neg, cosh_add, sinh_neg, cosh_neg] lemma sinh_conj : sinh (conj x) = conj (sinh x) := by rw [sinh, ← conj_neg, exp_conj, exp_conj, ← conj_sub, sinh, conj_div, conj_bit0, conj_one] @[simp] lemma of_real_sinh_of_real_re (x : ℝ) : ((sinh x).re : ℂ) = sinh x := eq_conj_iff_re.1 $ by rw [← sinh_conj, conj_of_real] @[simp] lemma of_real_sinh (x : ℝ) : (real.sinh x : ℂ) = sinh x := of_real_sinh_of_real_re _ @[simp] lemma sinh_of_real_im (x : ℝ) : (sinh x).im = 0 := by rw [← of_real_sinh_of_real_re, of_real_im] lemma sinh_of_real_re (x : ℝ) : (sinh x).re = real.sinh x := rfl lemma cosh_conj : cosh (conj x) = conj (cosh x) := by rw [cosh, ← conj_neg, exp_conj, exp_conj, ← conj_add, cosh, conj_div, conj_bit0, conj_one] @[simp] lemma of_real_cosh_of_real_re (x : ℝ) : ((cosh x).re : ℂ) = cosh x := eq_conj_iff_re.1 $ by rw [← cosh_conj, conj_of_real] @[simp] lemma of_real_cosh (x : ℝ) : (real.cosh x : ℂ) = cosh x := of_real_cosh_of_real_re _ @[simp] lemma cosh_of_real_im (x : ℝ) : (cosh x).im = 0 := by rw [← of_real_cosh_of_real_re, of_real_im] lemma cosh_of_real_re (x : ℝ) : (cosh x).re = real.cosh x := rfl lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x := rfl @[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh] @[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div] lemma tanh_conj : tanh (conj x) = conj (tanh x) := by rw [tanh, sinh_conj, cosh_conj, ← conj_div, tanh] @[simp] lemma of_real_tanh_of_real_re (x : ℝ) : ((tanh x).re : ℂ) = tanh x := eq_conj_iff_re.1 $ by rw [← tanh_conj, conj_of_real] @[simp] lemma of_real_tanh (x : ℝ) : (real.tanh x : ℂ) = tanh x := of_real_tanh_of_real_re _ @[simp] lemma tanh_of_real_im (x : ℝ) : (tanh x).im = 0 := by rw [← of_real_tanh_of_real_re, of_real_im] lemma tanh_of_real_re (x : ℝ) : (tanh x).re = real.tanh x := rfl lemma cosh_add_sinh : cosh x + sinh x = exp x := by rw [← domain.mul_right_inj (@two_ne_zero' ℂ _ _ _), mul_add, two_cosh, two_sinh, add_add_sub_cancel, two_mul] lemma sinh_add_cosh : sinh x + cosh x = exp x := by rw [add_comm, cosh_add_sinh] lemma cosh_sub_sinh : cosh x - sinh x = exp (-x) := by rw [← domain.mul_right_inj (@two_ne_zero' ℂ _ _ _), mul_sub, two_cosh, two_sinh, add_sub_sub_cancel, two_mul] lemma cosh_sq_sub_sinh_sq : cosh x ^ 2 - sinh x ^ 2 = 1 := by rw [sq_sub_sq, cosh_add_sinh, cosh_sub_sinh, ← exp_add, add_neg_self, exp_zero] @[simp] lemma sin_zero : sin 0 = 0 := by simp [sin] @[simp] lemma sin_neg : sin (-x) = -sin x := by simp [sin, sub_eq_add_neg, exp_neg, (neg_div _ _).symm, add_mul] lemma two_sin : 2 * sin x = (exp (-x * I) - exp (x * I)) * I := mul_div_cancel' _ two_ne_zero' lemma two_cos : 2 * cos x = exp (x * I) + exp (-x * I) := mul_div_cancel' _ two_ne_zero' lemma sinh_mul_I : sinh (x * I) = sin x * I := by rw [← domain.mul_right_inj (@two_ne_zero' ℂ _ _ _), two_sinh, ← mul_assoc, two_sin, mul_assoc, I_mul_I, mul_neg_one, neg_sub, neg_mul_eq_neg_mul] lemma cosh_mul_I : cosh (x * I) = cos x := by rw [← domain.mul_right_inj (@two_ne_zero' ℂ _ _ _), two_cosh, two_cos, neg_mul_eq_neg_mul] lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y := by rw [← domain.mul_left_inj I_ne_zero, ← sinh_mul_I, add_mul, add_mul, mul_right_comm, ← sinh_mul_I, mul_assoc, ← sinh_mul_I, ← cosh_mul_I, ← cosh_mul_I, sinh_add] @[simp] lemma cos_zero : cos 0 = 1 := by simp [cos] @[simp] lemma cos_neg : cos (-x) = cos x := by simp [cos, sub_eq_add_neg, exp_neg, add_comm] private lemma cos_add_aux {a b c d : ℂ} : (a + b) * (c + d) - (b - a) * (d - c) * (-1) = 2 * (a * c + b * d) := by ring lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y := by rw [← cosh_mul_I, add_mul, cosh_add, cosh_mul_I, cosh_mul_I, sinh_mul_I, sinh_mul_I, mul_mul_mul_comm, I_mul_I, mul_neg_one, sub_eq_add_neg] lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y := by simp [sub_eq_add_neg, sin_add, sin_neg, cos_neg] lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y := by simp [sub_eq_add_neg, cos_add, sin_neg, cos_neg] lemma sin_conj : sin (conj x) = conj (sin x) := by rw [← domain.mul_left_inj I_ne_zero, ← sinh_mul_I, ← conj_neg_I, ← conj_mul, ← conj_mul, sinh_conj, mul_neg_eq_neg_mul_symm, sinh_neg, sinh_mul_I, mul_neg_eq_neg_mul_symm] @[simp] lemma of_real_sin_of_real_re (x : ℝ) : ((sin x).re : ℂ) = sin x := eq_conj_iff_re.1 $ by rw [← sin_conj, conj_of_real] @[simp] lemma of_real_sin (x : ℝ) : (real.sin x : ℂ) = sin x := of_real_sin_of_real_re _ @[simp] lemma sin_of_real_im (x : ℝ) : (sin x).im = 0 := by rw [← of_real_sin_of_real_re, of_real_im] lemma sin_of_real_re (x : ℝ) : (sin x).re = real.sin x := rfl lemma cos_conj : cos (conj x) = conj (cos x) := by rw [← cosh_mul_I, ← conj_neg_I, ← conj_mul, ← cosh_mul_I, cosh_conj, mul_neg_eq_neg_mul_symm, cosh_neg] @[simp] lemma of_real_cos_of_real_re (x : ℝ) : ((cos x).re : ℂ) = cos x := eq_conj_iff_re.1 $ by rw [← cos_conj, conj_of_real] @[simp] lemma of_real_cos (x : ℝ) : (real.cos x : ℂ) = cos x := of_real_cos_of_real_re _ @[simp] lemma cos_of_real_im (x : ℝ) : (cos x).im = 0 := by rw [← of_real_cos_of_real_re, of_real_im] lemma cos_of_real_re (x : ℝ) : (cos x).re = real.cos x := rfl @[simp] lemma tan_zero : tan 0 = 0 := by simp [tan] lemma tan_eq_sin_div_cos : tan x = sin x / cos x := rfl @[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div] lemma tan_conj : tan (conj x) = conj (tan x) := by rw [tan, sin_conj, cos_conj, ← conj_div, tan] @[simp] lemma of_real_tan_of_real_re (x : ℝ) : ((tan x).re : ℂ) = tan x := eq_conj_iff_re.1 $ by rw [← tan_conj, conj_of_real] @[simp] lemma of_real_tan (x : ℝ) : (real.tan x : ℂ) = tan x := of_real_tan_of_real_re _ @[simp] lemma tan_of_real_im (x : ℝ) : (tan x).im = 0 := by rw [← of_real_tan_of_real_re, of_real_im] lemma tan_of_real_re (x : ℝ) : (tan x).re = real.tan x := rfl lemma cos_add_sin_I : cos x + sin x * I = exp (x * I) := by rw [← cosh_add_sinh, sinh_mul_I, cosh_mul_I] lemma cos_sub_sin_I : cos x - sin x * I = exp (-x * I) := by rw [← neg_mul_eq_neg_mul, ← cosh_sub_sinh, sinh_mul_I, cosh_mul_I] lemma sin_sq_add_cos_sq : sin x ^ 2 + cos x ^ 2 = 1 := eq.trans (by rw [cosh_mul_I, sinh_mul_I, mul_pow, I_sq, mul_neg_one, sub_neg_eq_add, add_comm]) (cosh_sq_sub_sinh_sq (x * I)) lemma cos_two_mul' : cos (2 * x) = cos x ^ 2 - sin x ^ 2 := by rw [two_mul, cos_add, ← pow_two, ← pow_two] lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 := by rw [cos_two_mul', eq_sub_iff_add_eq.2 (sin_sq_add_cos_sq x), ← sub_add, sub_add_eq_add_sub, two_mul] lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x := by rw [two_mul, sin_add, two_mul, add_mul, mul_comm] lemma cos_square : cos x ^ 2 = 1 / 2 + cos (2 * x) / 2 := by simp [cos_two_mul, div_add_div_same, mul_div_cancel_left, two_ne_zero', -one_div_eq_inv] lemma sin_square : sin x ^ 2 = 1 - cos x ^ 2 := by { rw [←sin_sq_add_cos_sq x], simp } lemma exp_mul_I : exp (x * I) = cos x + sin x * I := (cos_add_sin_I _).symm lemma exp_add_mul_I : exp (x + y * I) = exp x * (cos y + sin y * I) := by rw [exp_add, exp_mul_I] lemma exp_eq_exp_re_mul_sin_add_cos : exp x = exp x.re * (cos x.im + sin x.im * I) := by rw [← exp_add_mul_I, re_add_im] theorem cos_add_sin_mul_I_pow (n : ℕ) (z : ℂ) : (cos z + sin z * I) ^ n = cos (↑n * z) + sin (↑n * z) * I := begin rw [← exp_mul_I, ← exp_mul_I], induction n with n ih, { rw [pow_zero, nat.cast_zero, zero_mul, zero_mul, exp_zero] }, { rw [pow_succ', ih, nat.cast_succ, add_mul, add_mul, one_mul, exp_add] } end end complex namespace real open complex variables (x y : ℝ) @[simp] lemma exp_zero : exp 0 = 1 := by simp [real.exp] lemma exp_add : exp (x + y) = exp x * exp y := by simp [exp_add, exp] lemma exp_list_sum (l : list ℝ) : exp l.sum = (l.map exp).prod := @monoid_hom.map_list_prod (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ l lemma exp_multiset_sum (s : multiset ℝ) : exp s.sum = (s.map exp).prod := @monoid_hom.map_multiset_prod (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ s lemma exp_sum {α : Type*} (s : finset α) (f : α → ℝ) : exp (∑ x in s, f x) = ∏ x in s, exp (f x) := @monoid_hom.map_prod α (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ f s lemma exp_nat_mul (x : ℝ) : ∀ n : ℕ, exp(n*x) = (exp x)^n | 0 := by rw [nat.cast_zero, zero_mul, exp_zero, pow_zero] | (nat.succ n) := by rw [pow_succ', nat.cast_add_one, add_mul, exp_add, ←exp_nat_mul, one_mul] lemma exp_ne_zero : exp x ≠ 0 := λ h, exp_ne_zero x $ by rw [exp, ← of_real_inj] at h; simp * at * lemma exp_neg : exp (-x) = (exp x)⁻¹ := by rw [← of_real_inj, exp, of_real_exp_of_real_re, of_real_neg, exp_neg, of_real_inv, of_real_exp] lemma exp_sub : exp (x - y) = exp x / exp y := by simp [sub_eq_add_neg, exp_add, exp_neg, div_eq_mul_inv] @[simp] lemma sin_zero : sin 0 = 0 := by simp [sin] @[simp] lemma sin_neg : sin (-x) = -sin x := by simp [sin, exp_neg, (neg_div _ _).symm, add_mul] lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y := by rw [← of_real_inj]; simp [sin, sin_add] @[simp] lemma cos_zero : cos 0 = 1 := by simp [cos] @[simp] lemma cos_neg : cos (-x) = cos x := by simp [cos, exp_neg] lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y := by rw ← of_real_inj; simp [cos, cos_add] lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y := by simp [sub_eq_add_neg, sin_add, sin_neg, cos_neg] lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y := by simp [sub_eq_add_neg, cos_add, sin_neg, cos_neg] lemma tan_eq_sin_div_cos : tan x = sin x / cos x := if h : complex.cos x = 0 then by simp [sin, cos, tan, *, complex.tan, div_eq_mul_inv] at * else by rw [sin, cos, tan, complex.tan, ← of_real_inj, div_eq_mul_inv, mul_re]; simp [norm_sq, (div_div_eq_div_mul _ _ _).symm, div_self h]; refl @[simp] lemma tan_zero : tan 0 = 0 := by simp [tan] @[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div] lemma sin_sq_add_cos_sq : sin x ^ 2 + cos x ^ 2 = 1 := of_real_inj.1 $ by simpa using sin_sq_add_cos_sq x lemma sin_sq_le_one : sin x ^ 2 ≤ 1 := by rw ← sin_sq_add_cos_sq x; exact le_add_of_nonneg_right' (pow_two_nonneg _) lemma cos_sq_le_one : cos x ^ 2 ≤ 1 := by rw ← sin_sq_add_cos_sq x; exact le_add_of_nonneg_left' (pow_two_nonneg _) lemma abs_sin_le_one : abs' (sin x) ≤ 1 := (mul_self_le_mul_self_iff (_root_.abs_nonneg (sin x)) (by exact zero_le_one)).2 $ by rw [← _root_.abs_mul, abs_mul_self, mul_one, ← pow_two]; apply sin_sq_le_one lemma abs_cos_le_one : abs' (cos x) ≤ 1 := (mul_self_le_mul_self_iff (_root_.abs_nonneg (cos x)) (by exact zero_le_one)).2 $ by rw [← _root_.abs_mul, abs_mul_self, mul_one, ← pow_two]; apply cos_sq_le_one lemma sin_le_one : sin x ≤ 1 := (abs_le.1 (abs_sin_le_one _)).2 lemma cos_le_one : cos x ≤ 1 := (abs_le.1 (abs_cos_le_one _)).2 lemma neg_one_le_sin : -1 ≤ sin x := (abs_le.1 (abs_sin_le_one _)).1 lemma neg_one_le_cos : -1 ≤ cos x := (abs_le.1 (abs_cos_le_one _)).1 lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 := by rw ← of_real_inj; simp [cos_two_mul] lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x := by rw ← of_real_inj; simp [sin_two_mul] lemma cos_square : cos x ^ 2 = 1 / 2 + cos (2 * x) / 2 := of_real_inj.1 $ by simpa using cos_square x lemma sin_square : sin x ^ 2 = 1 - cos x ^ 2 := eq_sub_iff_add_eq.2 $ sin_sq_add_cos_sq _ @[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh] @[simp] lemma sinh_neg : sinh (-x) = -sinh x := by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul] lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y := by rw ← of_real_inj; simp [sinh_add] @[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh] @[simp] lemma cosh_neg : cosh (-x) = cosh x := by simp [cosh, exp_neg] lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y := by rw ← of_real_inj; simp [cosh, cosh_add] lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y := by simp [sub_eq_add_neg, sinh_add, sinh_neg, cosh_neg] lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y := by simp [sub_eq_add_neg, cosh_add, sinh_neg, cosh_neg] lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x := of_real_inj.1 $ by simp [tanh_eq_sinh_div_cosh] @[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh] @[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div] open is_absolute_value /- TODO make this private and prove ∀ x -/ lemma add_one_le_exp_of_nonneg {x : ℝ} (hx : 0 ≤ x) : x + 1 ≤ exp x := calc x + 1 ≤ lim (⟨(λ n : ℕ, ((exp' x) n).re), is_cau_seq_re (exp' x)⟩ : cau_seq ℝ abs') : le_lim (cau_seq.le_of_exists ⟨2, λ j hj, show x + (1 : ℝ) ≤ (∑ m in range j, (x ^ m / m.fact : ℂ)).re, from have h₁ : (((λ m : ℕ, (x ^ m / m.fact : ℂ)) ∘ nat.succ) 0).re = x, by simp, have h₂ : ((x : ℂ) ^ 0 / nat.fact 0).re = 1, by simp, begin rw [← nat.sub_add_cancel hj, sum_range_succ', sum_range_succ', add_re, add_re, h₁, h₂, add_assoc, ← @sum_hom _ _ _ _ _ _ _ complex.re (is_add_group_hom.to_is_add_monoid_hom _)], refine le_add_of_nonneg_of_le (sum_nonneg (λ m hm, _)) (le_refl _), rw [← of_real_pow, ← of_real_nat_cast, ← of_real_div, of_real_re], exact div_nonneg (pow_nonneg hx _) (nat.cast_pos.2 (nat.fact_pos _)), end⟩) ... = exp x : by rw [exp, complex.exp, ← cau_seq_re, lim_re] lemma one_le_exp {x : ℝ} (hx : 0 ≤ x) : 1 ≤ exp x := by linarith [add_one_le_exp_of_nonneg hx] lemma exp_pos (x : ℝ) : 0 < exp x := (le_total 0 x).elim (lt_of_lt_of_le zero_lt_one ∘ one_le_exp) (λ h, by rw [← neg_neg x, real.exp_neg]; exact inv_pos.2 (lt_of_lt_of_le zero_lt_one (one_le_exp (neg_nonneg.2 h)))) @[simp] lemma abs_exp (x : ℝ) : abs' (exp x) = exp x := abs_of_pos (exp_pos _) lemma exp_strict_mono : strict_mono exp := λ x y h, by rw [← sub_add_cancel y x, real.exp_add]; exact (lt_mul_iff_one_lt_left (exp_pos _)).2 (lt_of_lt_of_le (by linarith) (add_one_le_exp_of_nonneg (by linarith))) lemma exp_lt_exp {x y : ℝ} : exp x < exp y ↔ x < y := exp_strict_mono.lt_iff_lt lemma exp_le_exp {x y : ℝ} : exp x ≤ exp y ↔ x ≤ y := exp_strict_mono.le_iff_le lemma exp_injective : function.injective exp := exp_strict_mono.injective @[simp] lemma exp_eq_one_iff : exp x = 1 ↔ x = 0 := by rw [← exp_zero, exp_injective.eq_iff] lemma one_lt_exp_iff {x : ℝ} : 1 < exp x ↔ 0 < x := by rw [← exp_zero, exp_lt_exp] lemma exp_lt_one_iff {x : ℝ} : exp x < 1 ↔ x < 0 := by rw [← exp_zero, exp_lt_exp] end real namespace complex lemma sum_div_fact_le {α : Type*} [discrete_linear_ordered_field α] (n j : ℕ) (hn : 0 < n) : ∑ m in filter (λ k, n ≤ k) (range j), (1 / m.fact : α) ≤ n.succ * (n.fact * n)⁻¹ := calc ∑ m in filter (λ k, n ≤ k) (range j), (1 / m.fact : α) = ∑ m in range (j - n), 1 / (m + n).fact : sum_bij (λ m _, m - n) (λ m hm, mem_range.2 $ (nat.sub_lt_sub_right_iff (by simp at hm; tauto)).2 (by simp at hm; tauto)) (λ m hm, by rw nat.sub_add_cancel; simp at *; tauto) (λ a₁ a₂ ha₁ ha₂ h, by rwa [nat.sub_eq_iff_eq_add, ← nat.sub_add_comm, eq_comm, nat.sub_eq_iff_eq_add, add_left_inj, eq_comm] at h; simp at *; tauto) (λ b hb, ⟨b + n, mem_filter.2 ⟨mem_range.2 $ nat.add_lt_of_lt_sub_right (mem_range.1 hb), nat.le_add_left _ _⟩, by rw nat.add_sub_cancel⟩) ... ≤ ∑ m in range (j - n), (nat.fact n * n.succ ^ m)⁻¹ : begin refine sum_le_sum (assume m n, _), rw [one_div_eq_inv, inv_le_inv], { rw [← nat.cast_pow, ← nat.cast_mul, nat.cast_le, add_comm], exact nat.fact_mul_pow_le_fact }, { exact nat.cast_pos.2 (nat.fact_pos _) }, { exact mul_pos (nat.cast_pos.2 (nat.fact_pos _)) (pow_pos (nat.cast_pos.2 (nat.succ_pos _)) _) }, end ... = (nat.fact n)⁻¹ * ∑ m in range (j - n), n.succ⁻¹ ^ m : by simp [mul_inv', mul_sum.symm, sum_mul.symm, -nat.fact_succ, mul_comm, inv_pow'] ... = (n.succ - n.succ * n.succ⁻¹ ^ (j - n)) / (n.fact * n) : have h₁ : (n.succ : α) ≠ 1, from @nat.cast_one α _ _ ▸ mt nat.cast_inj.1 (mt nat.succ.inj (nat.pos_iff_ne_zero.1 hn)), have h₂ : (n.succ : α) ≠ 0, from nat.cast_ne_zero.2 (nat.succ_ne_zero _), have h₃ : (n.fact * n : α) ≠ 0, from mul_ne_zero (nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 (nat.fact_pos _))) (nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 hn)), have h₄ : (n.succ - 1 : α) = n, by simp, by rw [← geom_series_def, geom_sum_inv h₁ h₂, eq_div_iff_mul_eq _ _ h₃, mul_comm _ (n.fact * n : α), ← mul_assoc (n.fact⁻¹ : α), ← mul_inv', h₄, ← mul_assoc (n.fact * n : α), mul_comm (n : α) n.fact, mul_inv_cancel h₃]; simp [mul_add, add_mul, mul_assoc, mul_comm] ... ≤ n.succ / (n.fact * n) : begin refine iff.mpr (div_le_div_right (mul_pos _ _)) _, exact nat.cast_pos.2 (nat.fact_pos _), exact nat.cast_pos.2 hn, exact sub_le_self _ (mul_nonneg (nat.cast_nonneg _) (pow_nonneg (inv_nonneg.2 (nat.cast_nonneg _)) _)) end lemma exp_bound {x : ℂ} (hx : abs x ≤ 1) {n : ℕ} (hn : 0 < n) : abs (exp x - ∑ m in range n, x ^ m / m.fact) ≤ abs x ^ n * (n.succ * (n.fact * n)⁻¹) := begin rw [← lim_const (∑ m in range n, _), exp, sub_eq_add_neg, ← lim_neg, lim_add, ← lim_abs], refine lim_le (cau_seq.le_of_exists ⟨n, λ j hj, _⟩), show abs (∑ m in range j, x ^ m / m.fact - ∑ m in range n, x ^ m / m.fact) ≤ abs x ^ n * (n.succ * (n.fact * n)⁻¹), rw sum_range_sub_sum_range hj, exact calc abs (∑ m in (range j).filter (λ k, n ≤ k), (x ^ m / m.fact : ℂ)) = abs (∑ m in (range j).filter (λ k, n ≤ k), (x ^ n * (x ^ (m - n) / m.fact) : ℂ)) : congr_arg abs (sum_congr rfl (λ m hm, by rw [← mul_div_assoc, ← pow_add, nat.add_sub_cancel']; simp at hm; tauto)) ... ≤ ∑ m in filter (λ k, n ≤ k) (range j), abs (x ^ n * (_ / m.fact)) : abv_sum_le_sum_abv _ _ ... ≤ ∑ m in filter (λ k, n ≤ k) (range j), abs x ^ n * (1 / m.fact) : begin refine sum_le_sum (λ m hm, _), rw [abs_mul, abv_pow abs, abs_div, abs_cast_nat], refine mul_le_mul_of_nonneg_left ((div_le_div_right _).2 _) _, exact nat.cast_pos.2 (nat.fact_pos _), rw abv_pow abs, exact (pow_le_one _ (abs_nonneg _) hx), exact pow_nonneg (abs_nonneg _) _ end ... = abs x ^ n * (∑ m in (range j).filter (λ k, n ≤ k), (1 / m.fact : ℝ)) : by simp [abs_mul, abv_pow abs, abs_div, mul_sum.symm] ... ≤ abs x ^ n * (n.succ * (n.fact * n)⁻¹) : mul_le_mul_of_nonneg_left (sum_div_fact_le _ _ hn) (pow_nonneg (abs_nonneg _) _) end lemma abs_exp_sub_one_le {x : ℂ} (hx : abs x ≤ 1) : abs (exp x - 1) ≤ 2 * abs x := calc abs (exp x - 1) = abs (exp x - ∑ m in range 1, x ^ m / m.fact) : by simp [sum_range_succ] ... ≤ abs x ^ 1 * ((nat.succ 1) * (nat.fact 1 * (1 : ℕ))⁻¹) : exp_bound hx dec_trivial ... = 2 * abs x : by simp [two_mul, mul_two, mul_add, mul_comm] lemma abs_exp_sub_one_sub_id_le {x : ℂ} (hx : abs x ≤ 1) : abs (exp x - 1 - x) ≤ (abs x)^2 := calc abs (exp x - 1 - x) = abs (exp x - ∑ m in range 2, x ^ m / m.fact) : by simp [sub_eq_add_neg, sum_range_succ, add_assoc] ... ≤ (abs x)^2 * (nat.succ 2 * (nat.fact 2 * (2 : ℕ))⁻¹) : exp_bound hx dec_trivial ... ≤ (abs x)^2 * 1 : mul_le_mul_of_nonneg_left (by norm_num) (pow_two_nonneg (abs x)) ... = (abs x)^2 : by rw [mul_one] end complex namespace real open complex finset lemma cos_bound {x : ℝ} (hx : abs' x ≤ 1) : abs' (cos x - (1 - x ^ 2 / 2)) ≤ abs' x ^ 4 * (5 / 96) := calc abs' (cos x - (1 - x ^ 2 / 2)) = abs (complex.cos x - (1 - x ^ 2 / 2)) : by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv] ... = abs ((complex.exp (x * I) + complex.exp (-x * I) - (2 - x ^ 2)) / 2) : by simp [complex.cos, sub_div, add_div, neg_div, div_self (@two_ne_zero' ℂ _ _ _)] ... = abs (((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m.fact) + ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m.fact))) / 2) : congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin simp only [sum_range_succ], simp [pow_succ], apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring end) ... ≤ abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m.fact) / 2) + abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m.fact) / 2) : by rw add_div; exact abs_add _ _ ... = (abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m.fact)) / 2 + abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m.fact)) / 2) : by simp [complex.abs_div] ... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2 + (complex.abs (-x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2) : add_le_add ((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial)) ((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial)) ... ≤ abs' x ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc] lemma sin_bound {x : ℝ} (hx : abs' x ≤ 1) : abs' (sin x - (x - x ^ 3 / 6)) ≤ abs' x ^ 4 * (5 / 96) := calc abs' (sin x - (x - x ^ 3 / 6)) = abs (complex.sin x - (x - x ^ 3 / 6)) : by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv] ... = abs (((complex.exp (-x * I) - complex.exp (x * I)) * I - (2 * x - x ^ 3 / 3)) / 2) : by simp [complex.sin, sub_div, add_div, neg_div, mul_div_cancel_left _ (@two_ne_zero' ℂ _ _ _), div_div_eq_div_mul, show (3 : ℂ) * 2 = 6, by norm_num] ... = abs ((((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m.fact) - (complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m.fact)) * I) / 2) : congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin simp only [sum_range_succ], simp [pow_succ], apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring end) ... ≤ abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m.fact) * I / 2) + abs (-((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m.fact) * I) / 2) : by rw [sub_mul, sub_eq_add_neg, add_div]; exact abs_add _ _ ... = (abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m.fact)) / 2 + abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m.fact)) / 2) : by simp [add_comm, complex.abs_div, complex.abs_mul] ... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2 + (complex.abs (-x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2) : add_le_add ((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial)) ((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial)) ... ≤ abs' x ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc] lemma cos_pos_of_le_one {x : ℝ} (hx : abs' x ≤ 1) : 0 < cos x := calc 0 < (1 - x ^ 2 / 2) - abs' x ^ 4 * (5 / 96) : sub_pos.2 $ lt_sub_iff_add_lt.2 (calc abs' x ^ 4 * (5 / 96) + x ^ 2 / 2 ≤ 1 * (5 / 96) + 1 / 2 : add_le_add (mul_le_mul_of_nonneg_right (pow_le_one _ (abs_nonneg _) hx) (by norm_num)) ((div_le_div_right (by norm_num)).2 (by rw [pow_two, ← abs_mul_self, _root_.abs_mul]; exact mul_le_one hx (abs_nonneg _) hx)) ... < 1 : by norm_num) ... ≤ cos x : sub_le.1 (abs_sub_le_iff.1 (cos_bound hx)).2 lemma sin_pos_of_pos_of_le_one {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 1) : 0 < sin x := calc 0 < x - x ^ 3 / 6 - abs' x ^ 4 * (5 / 96) : sub_pos.2 $ lt_sub_iff_add_lt.2 (calc abs' x ^ 4 * (5 / 96) + x ^ 3 / 6 ≤ x * (5 / 96) + x / 6 : add_le_add (mul_le_mul_of_nonneg_right (calc abs' x ^ 4 ≤ abs' x ^ 1 : pow_le_pow_of_le_one (abs_nonneg _) (by rwa _root_.abs_of_nonneg (le_of_lt hx0)) dec_trivial ... = x : by simp [_root_.abs_of_nonneg (le_of_lt (hx0))]) (by norm_num)) ((div_le_div_right (by norm_num)).2 (calc x ^ 3 ≤ x ^ 1 : pow_le_pow_of_le_one (le_of_lt hx0) hx dec_trivial ... = x : pow_one _)) ... < x : by linarith) ... ≤ sin x : sub_le.1 (abs_sub_le_iff.1 (sin_bound (by rwa [_root_.abs_of_nonneg (le_of_lt hx0)]))).2 lemma sin_pos_of_pos_of_le_two {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 2) : 0 < sin x := have x / 2 ≤ 1, from div_le_of_le_mul (by norm_num) (by simpa), calc 0 < 2 * sin (x / 2) * cos (x / 2) : mul_pos (mul_pos (by norm_num) (sin_pos_of_pos_of_le_one (half_pos hx0) this)) (cos_pos_of_le_one (by rwa [_root_.abs_of_nonneg (le_of_lt (half_pos hx0))])) ... = sin x : by rw [← sin_two_mul, two_mul, add_halves] lemma cos_one_le : cos 1 ≤ 2 / 3 := calc cos 1 ≤ abs' (1 : ℝ) ^ 4 * (5 / 96) + (1 - 1 ^ 2 / 2) : sub_le_iff_le_add.1 (abs_sub_le_iff.1 (cos_bound (by simp))).1 ... ≤ 2 / 3 : by norm_num lemma cos_one_pos : 0 < cos 1 := cos_pos_of_le_one (by simp) lemma cos_two_neg : cos 2 < 0 := calc cos 2 = cos (2 * 1) : congr_arg cos (mul_one _).symm ... = _ : real.cos_two_mul 1 ... ≤ 2 * (2 / 3) ^ 2 - 1 : sub_le_sub_right (mul_le_mul_of_nonneg_left (by rw [pow_two, pow_two]; exact mul_self_le_mul_self (le_of_lt cos_one_pos) cos_one_le) (by norm_num)) _ ... < 0 : by norm_num end real namespace complex lemma abs_cos_add_sin_mul_I (x : ℝ) : abs (cos x + sin x * I) = 1 := have _ := real.sin_sq_add_cos_sq x, by simp [add_comm, abs, norm_sq, pow_two, *, sin_of_real_re, cos_of_real_re, mul_re] at * lemma abs_exp_eq_iff_re_eq {x y : ℂ} : abs (exp x) = abs (exp y) ↔ x.re = y.re := by rw [exp_eq_exp_re_mul_sin_add_cos, exp_eq_exp_re_mul_sin_add_cos y, abs_mul, abs_mul, abs_cos_add_sin_mul_I, abs_cos_add_sin_mul_I, ← of_real_exp, ← of_real_exp, abs_of_nonneg (le_of_lt (real.exp_pos _)), abs_of_nonneg (le_of_lt (real.exp_pos _)), mul_one, mul_one]; exact ⟨λ h, real.exp_injective h, congr_arg _⟩ @[simp] lemma abs_exp_of_real (x : ℝ) : abs (exp x) = real.exp x := by rw [← of_real_exp]; exact abs_of_nonneg (le_of_lt (real.exp_pos _)) end complex
22ade8ff3c7ef988a55658d59e8998f5cd883782
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/t10.lean
10803b328a37772c9b03d41bb86f6bae862fe5b1
[ "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
603
lean
prelude constant N : Type.{1} definition B : Type.{1} := Type.{0} constant ite : B → N → N → N constant and : B → B → B constant f : N → N constant p : B constant q : B constant x : N constant y : N constant z : N infixr ` ∧ `:25 := and notation `if ` c ` then ` t:45 ` else ` e:45 := ite c t e #check if p ∧ q then f x else y #check if p ∧ q then q else y constant list : Type.{1} constant nil : list constant cons : N → list → list -- Non empty lists notation `[` l:(foldr `, ` (h t, cons h t) nil) `]` := l #check [x, y, z, x, y, y] #check [x] notation `[` `]` := nil #check []
8aff9641280e1501e8a5ab49bae509157dc7eda5
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/order/category/NonemptyFinLinOrd.lean
32042b5820beab9d174e4667b3bb31dc6b56c8e6
[ "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
3,382
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import data.fintype.order import order.category.LinearOrder /-! # Nonempty finite linear orders This defines `NonemptyFinLinOrd`, the category of nonempty finite linear orders with monotone maps. This is the index category for simplicial objects. -/ universes u v open category_theory /-- A typeclass for nonempty finite linear orders. -/ class nonempty_fin_lin_ord (α : Type*) extends fintype α, linear_order α := (nonempty : nonempty α . tactic.apply_instance) attribute [instance] nonempty_fin_lin_ord.nonempty @[priority 100] instance nonempty_fin_lin_ord.to_bounded_order (α : Type*) [nonempty_fin_lin_ord α] : bounded_order α := fintype.to_bounded_order α instance punit.nonempty_fin_lin_ord : nonempty_fin_lin_ord punit := { .. punit.linear_ordered_cancel_add_comm_monoid, .. punit.fintype } instance fin.nonempty_fin_lin_ord (n : ℕ) : nonempty_fin_lin_ord (fin (n+1)) := { .. fin.fintype _, .. fin.linear_order } instance ulift.nonempty_fin_lin_ord (α : Type u) [nonempty_fin_lin_ord α] : nonempty_fin_lin_ord (ulift.{v} α) := { nonempty := ⟨ulift.up ⊥⟩, .. linear_order.lift equiv.ulift (equiv.injective _), .. ulift.fintype _ } instance (α : Type*) [nonempty_fin_lin_ord α] : nonempty_fin_lin_ord (order_dual α) := { ..order_dual.fintype α } /-- The category of nonempty finite linear orders. -/ def NonemptyFinLinOrd := bundled nonempty_fin_lin_ord namespace NonemptyFinLinOrd instance : bundled_hom.parent_projection @nonempty_fin_lin_ord.to_linear_order := ⟨⟩ attribute [derive [large_category, concrete_category]] NonemptyFinLinOrd instance : has_coe_to_sort NonemptyFinLinOrd Type* := bundled.has_coe_to_sort /-- Construct a bundled `NonemptyFinLinOrd` from the underlying type and typeclass. -/ def of (α : Type*) [nonempty_fin_lin_ord α] : NonemptyFinLinOrd := bundled.of α instance : inhabited NonemptyFinLinOrd := ⟨of punit⟩ instance (α : NonemptyFinLinOrd) : nonempty_fin_lin_ord α := α.str instance has_forget_to_LinearOrder : has_forget₂ NonemptyFinLinOrd LinearOrder := bundled_hom.forget₂ _ _ /-- Constructs an equivalence between nonempty finite linear orders from an order isomorphism between them. -/ @[simps] def iso.mk {α β : NonemptyFinLinOrd.{u}} (e : α ≃o β) : α ≅ β := { hom := e, inv := e.symm, hom_inv_id' := by { ext, exact e.symm_apply_apply x }, inv_hom_id' := by { ext, exact e.apply_symm_apply x } } /-- `order_dual` as a functor. -/ @[simps] def to_dual : NonemptyFinLinOrd ⥤ NonemptyFinLinOrd := { obj := λ X, of (order_dual X), map := λ X Y, order_hom.dual } /-- The equivalence between `FinPartialOrder` and itself induced by `order_dual` both ways. -/ @[simps functor inverse] def dual_equiv : NonemptyFinLinOrd ≌ NonemptyFinLinOrd := equivalence.mk to_dual to_dual (nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl) (nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl) end NonemptyFinLinOrd lemma NonemptyFinLinOrd_dual_equiv_comp_forget_to_LinearOrder : NonemptyFinLinOrd.dual_equiv.functor ⋙ forget₂ NonemptyFinLinOrd LinearOrder = forget₂ NonemptyFinLinOrd LinearOrder ⋙ LinearOrder.dual_equiv.functor := rfl
cccf0a674e81a1c33e933bd76571766bcff004fa
e9078bde91465351e1b354b353c9f9d8b8a9c8c2
/groupoid_quotient.hlean
e039c50e3f87d7960ad4fd6e7b74cb4fc9e7b159
[ "Apache-2.0" ]
permissive
EgbertRijke/leansnippets
09fb7a9813477471532fbdd50c99be8d8fe3e6c4
1d9a7059784c92c0281fcc7ce66ac7b3619c8661
refs/heads/master
1,610,743,957,626
1,442,532,603,000
1,442,532,603,000
41,563,379
0
0
null
1,440,787,514,000
1,440,787,514,000
null
UTF-8
Lean
false
false
7,182
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 Declaration of the groupoid quotient -/ import hit.two_quotient algebra.category.groupoid hit.trunc open two_quotient eq bool unit relation category e_closure iso is_trunc trunc namespace groupoid_quotient section parameter (G : Groupoid) inductive groupoid_quotient_R : G → G → Type := | Rmk : Π{a b : G} (f : a ⟶ b), groupoid_quotient_R a b -- local infix `⬝r`:75 := @e_closure.trans G groupoid_quotient_R -- local postfix `⁻¹ʳ`:(max+10) := @e_closure.symm G groupoid_quotient_R -- local notation `[`:max a `]`:0 := @e_closure.of_rel G groupoid_quotient_R _ _ a open groupoid_quotient_R local abbreviation R := groupoid_quotient_R inductive groupoid_quotient_Q : Π⦃x y : G⦄, e_closure groupoid_quotient_R x y → e_closure groupoid_quotient_R x y → Type := | Qrefl : Π(a : G), groupoid_quotient_Q [Rmk (ID a)] rfl | Qconcat : Π{a b c : G} (g : b ⟶ c) (f : a ⟶ b), groupoid_quotient_Q [Rmk (g ∘ f)] ([Rmk f] ⬝r [Rmk g]) | Qinv : Π{a b : G} (f : a ⟶ b), groupoid_quotient_Q [Rmk f⁻¹] [Rmk f]⁻¹ʳ open groupoid_quotient_Q local abbreviation Q := groupoid_quotient_Q variables {a b c : G} definition groupoid_quotient := trunc 1 (two_quotient R Q) definition elt (a : G) : groupoid_quotient := tr (incl0 _ _ a) definition pth' (f : a ⟶ b) : incl0 _ _ a = incl0 _ _ b := incl1 R Q (Rmk f) definition pth (f : a ⟶ b) : elt a = elt b := ap tr (pth' f) definition resp_id (a : G) : pth (ID a) = idp := ap02 tr (incl2 _ _ (Qrefl a)) definition resp_comp (g : b ⟶ c) (f : a ⟶ b) : pth (g ∘ f) = pth f ⬝ pth g := ap02 tr (incl2 _ _ (Qconcat g f)) ⬝ ap_con tr (pth' f) (pth' g) definition resp_inv (f : a ⟶ b) : pth (f⁻¹) = (pth f)⁻¹ := ap02 tr (incl2 _ _ (Qinv f)) ⬝ ap_inv tr (pth' f) theorem is_trunc_groupoid_quotient : is_trunc 1 groupoid_quotient := !is_trunc_trunc -- protected definition rec {P : groupoid_quotient → Type} (Pb : P base) (Pl1 : Pb =[loop1] Pb) -- (Pl2 : Pb =[loop2] Pb) (Pf : squareover P fill Pl1 Pl1 Pl2 Pl2) -- (x : groupoid_quotient) : P x := -- sorry -- example {P : groupoid_quotient → Type} (Pb : P base) (Pl1 : Pb =[loop1] Pb) (Pl2 : Pb =[loop2] Pb) -- (Pf : squareover P fill Pl1 Pl1 Pl2 Pl2) : groupoid_quotient.rec Pb Pl1 Pl2 Pf base = Pb := idp -- definition rec_loop1 {P : groupoid_quotient → Type} (Pb : P base) (Pl1 : Pb =[loop1] Pb) -- (Pl2 : Pb =[loop2] Pb) (Pf : squareover P fill Pl1 Pl1 Pl2 Pl2) -- : apdo (groupoid_quotient.rec Pb Pl1 Pl2 Pf) loop1 = Pl1 := -- sorry -- definition rec_loop2 {P : groupoid_quotient → Type} (Pb : P base) (Pl1 : Pb =[loop1] Pb) -- (Pl2 : Pb =[loop2] Pb) (Pf : squareover P fill Pl1 Pl1 Pl2 Pl2) -- : apdo (groupoid_quotient.rec Pb Pl1 Pl2 Pf) loop2 = Pl2 := -- sorry -- definition rec_surf {P : groupoid_quotient → Type} (Pb : P base) (Pl1 : Pb =[loop1] Pb) -- (Pl2 : Pb =[loop2] Pb) (Pf : squareover P fill Pl1 Pl1 Pl2 Pl2) -- : cubeover P rfl1 (apds (groupoid_quotient.rec Pb Pl1 Pl2 Pf) fill) Pf -- (vdeg_squareover !rec_loop2) (vdeg_squareover !rec_loop2) -- (vdeg_squareover !rec_loop1) (vdeg_squareover !rec_loop1) := -- sorry protected definition elim {P : 1-Type} (Pe : G → P) (Pp : Π⦃a b⦄ (f : a ⟶ b), Pe a = Pe b) (Pid : Πa, Pp (ID a) = idp) (Pcomp : Π⦃a b c⦄ (g : b ⟶ c) (f : a ⟶ b), Pp (g ∘ f) = Pp f ⬝ Pp g) (Pinv : Π⦃a b⦄ (f : a ⟶ b), Pp f⁻¹ = (Pp f)⁻¹) (x : groupoid_quotient) : P := begin refine trunc.elim _ x, { intro x, induction x, { exact Pe a}, { induction s with a b f, exact Pp f}, { induction q, all_goals esimp [e_closure.elim], { exact Pid a}, { exact Pcomp g f}, { exact Pinv f}}} end protected definition elim_on [reducible] {P : 1-Type} (x : groupoid_quotient) (Pe : G → P) (Pp : Π⦃a b⦄ (f : a ⟶ b), Pe a = Pe b) (Pid : Πa, Pp (ID a) = idp) (Pcomp : Π⦃a b c⦄ (g : b ⟶ c) (f : a ⟶ b), Pp (g ∘ f) = Pp f ⬝ Pp g) (Pinv : Π⦃a b⦄ (f : a ⟶ b), Pp f⁻¹ = (Pp f)⁻¹) : P := elim Pe @Pp Pid @Pcomp @Pinv x definition elim_pth {P : 1-Type} (Pe : G → P) (Pp : Π⦃a b⦄ (f : a ⟶ b), Pe a = Pe b) (Pid : Πa, Pp (ID a) = idp) (Pcomp : Π⦃a b c⦄ (g : b ⟶ c) (f : a ⟶ b), Pp (g ∘ f) = Pp f ⬝ Pp g) (Pinv : Π⦃a b⦄ (f : a ⟶ b), Pp f⁻¹ = (Pp f)⁻¹) {a b : G} (f : a ⟶ b) : ap (elim Pe Pp Pid Pcomp Pinv) (pth f) = Pp f := !ap_compose⁻¹ ⬝ !elim_incl1 -- set_option pp.notation false -- set_option pp.implicit true theorem elim_resp_id {P : 1-Type} (Pe : G → P) (Pp : Π⦃a b⦄ (f : a ⟶ b), Pe a = Pe b) (Pid : Πa, Pp (ID a) = idp) (Pcomp : Π⦃a b c⦄ (g : b ⟶ c) (f : a ⟶ b), Pp (g ∘ f) = Pp f ⬝ Pp g) (Pinv : Π⦃a b⦄ (f : a ⟶ b), Pp f⁻¹ = (Pp f)⁻¹) (a : G) : square (ap02 (elim Pe Pp Pid Pcomp Pinv) (resp_id a)) (Pid a) !elim_pth idp := begin rewrite [↑[groupoid_quotient.elim,elim_pth,resp_id,ap02],-ap_compose], -- let H := eq_top_of_square (natural_square ((ap_compose ((trunc.elim -- (two_quotient.elim R Q Pe @(groupoid_quotient_R.rec Pp) -- (groupoid_quotient_Q.rec Pid Pcomp Pinv)))) -- (@tr 1 _))) (incl2 R Q (Qrefl a))), -- refine tr_rev (λx, square x _ _ _) _ _, -- rotate 1, -- exact eq_top_of_square (natural_square (λx, (ap_compose ((trunc.elim -- (two_quotient.elim R Q Pe @(groupoid_quotient_R.rec Pp) -- (groupoid_quotient_Q.rec Pid Pcomp Pinv)))) -- (@tr 1 _) x)⁻¹) (incl2 R Q (Qrefl a))), -- xrewrite [eq_top_of_square (natural_square ((ap_compose ((trunc.elim -- (two_quotient.elim R Q Pe @(groupoid_quotient_R.rec Pp) -- (groupoid_quotient_Q.rec Pid Pcomp Pinv)))) -- (@tr 1 _))) (incl2 R Q (Qrefl a)))], -- let H := eq_top_of_square -- (elim_incl2 R Q Pe @(groupoid_quotient_R.rec Pp) (groupoid_quotient_Q.rec Pid Pcomp Pinv) (Qrefl a)), xrewrite [eq_top_of_square (natural_square (homotopy.symm (ap_compose ((trunc.elim (two_quotient.elim R Q Pe @(groupoid_quotient_R.rec Pp) (groupoid_quotient_Q.rec Pid Pcomp Pinv)))) (@tr 1 _))) (incl2 R Q (Qrefl a)))], esimp [inclt,e_closure.elim,function.compose], xrewrite [eq_top_of_square (elim_incl2 R Q Pe @(groupoid_quotient_R.rec Pp) (groupoid_quotient_Q.rec Pid Pcomp Pinv) (Qrefl a))], esimp [elim_inclt], exact sorry end end end groupoid_quotient attribute groupoid_quotient.elt [constructor] --attribute /-groupoid_quotient.rec-/ groupoid_quotient.elim [unfold 8] [recursor 8] --attribute groupoid_quotient.elim_type [unfold 9] --attribute /-groupoid_quotient.rec_on-/ groupoid_quotient.elim_on [unfold 2] --attribute groupoid_quotient.elim_type_on [unfold 6]
a85e7ba83e94c853315ca79e1ddf5c36399d6ab6
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Elab/Tactic/Conv/Change.lean
385cbf0c63b5805bd9a90cec881e3cb7547c34a5
[ "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
898
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Tactic.ElabTerm import Lean.Elab.Tactic.Conv.Basic namespace Lean.Elab.Tactic.Conv open Meta @[builtin_tactic Lean.Parser.Tactic.Conv.change] def evalChange : Tactic := fun stx => do match stx with | `(conv| change $e) => withMainContext do let lhs ← getLhs let mvarCounterSaved := (← getMCtx).mvarCounter let r ← elabTermEnsuringType e (← inferType lhs) logUnassignedAndAbort (← filterOldMVars (← getMVars r) mvarCounterSaved) unless (← isDefEqGuarded r lhs) do throwError "invalid 'change' conv tactic, term{indentExpr r}\nis not definitionally equal to current left-hand-side{indentExpr lhs}" changeLhs r | _ => throwUnsupportedSyntax end Lean.Elab.Tactic.Conv
c40d4989ca18c4d0d4e0e2a1c48f659e0fd84e0c
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/data/complex/exponential_bounds.lean
04c64528d33c13abd1f748f20fe80c339d42ef32
[ "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
2,710
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Joseph Myers -/ import data.complex.exponential import analysis.special_functions.exp_log import algebra.continued_fractions.computation.approximation_corollaries /-! # Bounds on specific values of the exponential -/ namespace real local notation `abs'` := _root_.abs open is_absolute_value finset cau_seq complex lemma exp_one_near_10 : abs' (exp 1 - 2244083/825552) ≤ 1/10^10 := begin apply exp_approx_start, iterate 13 { refine exp_1_approx_succ_eq (by norm_num1; refl) (by norm_cast; refl) _ }, norm_num1, refine exp_approx_end' _ (by norm_num1; refl) _ (by norm_cast; refl) (by simp) _, rw [_root_.abs_one, abs_of_pos]; norm_num1, end lemma exp_one_near_20 : abs' (exp 1 - 363916618873/133877442384) ≤ 1/10^20 := begin apply exp_approx_start, iterate 21 { refine exp_1_approx_succ_eq (by norm_num1; refl) (by norm_cast; refl) _ }, norm_num1, refine exp_approx_end' _ (by norm_num1; refl) _ (by norm_cast; refl) (by simp) _, rw [_root_.abs_one, abs_of_pos]; norm_num1, end lemma exp_one_gt_d9 : 2.7182818283 < exp 1 := lt_of_lt_of_le (by norm_num) (sub_le.1 (abs_sub_le_iff.1 exp_one_near_10).2) lemma exp_one_lt_d9 : exp 1 < 2.7182818286 := lt_of_le_of_lt (sub_le_iff_le_add.1 (abs_sub_le_iff.1 exp_one_near_10).1) (by norm_num) lemma exp_neg_one_gt_d9 : 0.36787944116 < exp (-1) := begin rw [exp_neg, lt_inv _ (exp_pos _)], refine lt_of_le_of_lt (sub_le_iff_le_add.1 (abs_sub_le_iff.1 exp_one_near_10).1) _, all_goals {norm_num}, end lemma exp_neg_one_lt_d9 : exp (-1) < 0.36787944120 := begin rw [exp_neg, inv_lt (exp_pos _)], refine lt_of_lt_of_le _ (sub_le.1 (abs_sub_le_iff.1 exp_one_near_10).2), all_goals {norm_num}, end lemma log_two_near_10 : abs' (log 2 - 287209 / 414355) ≤ 1/10^10 := begin suffices : abs' (log 2 - 287209 / 414355) ≤ 1/17179869184 + (1/10^10 - 1/2^34), { norm_num1 at *, assumption }, have t : abs' (2⁻¹ : ℝ) = 2⁻¹, { rw abs_of_pos, norm_num }, have z := real.abs_log_sub_add_sum_range_le (show abs' (2⁻¹ : ℝ) < 1, by { rw t, norm_num }) 34, rw t at z, norm_num1 at z, rw [one_div (2:ℝ), log_inv, ←sub_eq_add_neg, _root_.abs_sub] at z, apply le_trans (_root_.abs_sub_le _ _ _) (add_le_add z _), simp_rw [sum_range_succ], norm_num, rw abs_of_pos; norm_num end lemma log_two_gt_d9 : 0.6931471803 < log 2 := lt_of_lt_of_le (by norm_num1) (sub_le.1 (abs_sub_le_iff.1 log_two_near_10).2) lemma log_two_lt_d9 : log 2 < 0.6931471808 := lt_of_le_of_lt (sub_le_iff_le_add.1 (abs_sub_le_iff.1 log_two_near_10).1) (by norm_num) end real
a9912f4c88c50cd1f006bfb0ad965d7d43189a1e
fecda8e6b848337561d6467a1e30cf23176d6ad0
/src/number_theory/lucas_lehmer.lean
0f779b5d9edd5650ca533ceaf8afd2b1733cd487
[ "Apache-2.0" ]
permissive
spolu/mathlib
bacf18c3d2a561d00ecdc9413187729dd1f705ed
480c92cdfe1cf3c2d083abded87e82162e8814f4
refs/heads/master
1,671,684,094,325
1,600,736,045,000
1,600,736,045,000
297,564,749
1
0
null
1,600,758,368,000
1,600,758,367,000
null
UTF-8
Lean
false
false
17,113
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro, Scott Morrison, Ainsley Pahljina -/ import tactic.ring_exp import tactic.interval_cases import data.nat.parity import data.zmod.basic import group_theory.order_of_element import ring_theory.fintype /-! # The Lucas-Lehmer test for Mersenne primes. We define `lucas_lehmer_residue : Π p : ℕ, zmod (2^p - 1)`, and prove `lucas_lehmer_residue p = 0 → prime (mersenne p)`. We construct a tactic `lucas_lehmer.run_test`, which iteratively certifies the arithmetic required to calculate the residue, and enables us to prove ``` example : prime (mersenne 127) := lucas_lehmer_sufficiency _ (by norm_num) (by lucas_lehmer.run_test) ``` ## TODO - Show reverse implication. - Speed up the calculations using `n ≡ (n % 2^p) + (n / 2^p) [MOD 2^p - 1]`. - Find some bigger primes! ## History This development began as a student project by Ainsley Pahljina, and was then cleaned up for mathlib by Scott Morrison. The tactic for certified computation of Lucas-Lehmer residues was provided by Mario Carneiro. -/ /-- The Mersenne numbers, 2^p - 1. -/ def mersenne (p : ℕ) : ℕ := 2^p - 1 lemma mersenne_pos {p : ℕ} (h : 0 < p) : 0 < mersenne p := begin dsimp [mersenne], calc 0 < 2^1 - 1 : by norm_num ... ≤ 2^p - 1 : nat.pred_le_pred (nat.pow_le_pow_of_le_right (nat.succ_pos 1) h) end namespace lucas_lehmer open nat /-! We now define three(!) different versions of the recurrence `s (i+1) = (s i)^2 - 2`. These versions take values either in `ℤ`, in `zmod (2^p - 1)`, or in `ℤ` but applying `% (2^p - 1)` at each step. They are each useful at different points in the proof, so we take a moment setting up the lemmas relating them. -/ /-- The recurrence `s (i+1) = (s i)^2 - 2` in `ℤ`. -/ def s : ℕ → ℤ | 0 := 4 | (i+1) := (s i)^2 - 2 /-- The recurrence `s (i+1) = (s i)^2 - 2` in `zmod (2^p - 1)`. -/ def s_zmod (p : ℕ) : ℕ → zmod (2^p - 1) | 0 := 4 | (i+1) := (s_zmod i)^2 - 2 /-- The recurrence `s (i+1) = ((s i)^2 - 2) % (2^p - 1)` in `ℤ`. -/ def s_mod (p : ℕ) : ℕ → ℤ | 0 := 4 % (2^p - 1) | (i+1) := ((s_mod i)^2 - 2) % (2^p - 1) lemma mersenne_int_ne_zero (p : ℕ) (w : 0 < p) : (2^p - 1 : ℤ) ≠ 0 := begin apply ne_of_gt, simp only [gt_iff_lt, sub_pos], exact_mod_cast nat.one_lt_two_pow p w, end lemma s_mod_nonneg (p : ℕ) (w : 0 < p) (i : ℕ) : 0 ≤ s_mod p i := begin cases i; dsimp [s_mod], { trivial, }, { apply int.mod_nonneg, exact mersenne_int_ne_zero p w }, end lemma s_mod_mod (p i : ℕ) : s_mod p i % (2^p - 1) = s_mod p i := by cases i; simp [s_mod] lemma s_mod_lt (p : ℕ) (w : 0 < p) (i : ℕ) : s_mod p i < 2^p - 1 := begin rw ←s_mod_mod, convert int.mod_lt _ _, { refine (abs_of_nonneg _).symm, simp only [sub_nonneg, ge_iff_le], exact_mod_cast nat.one_le_two_pow p, }, { exact mersenne_int_ne_zero p w, }, end lemma s_zmod_eq_s (p' : ℕ) (i : ℕ) : s_zmod (p'+2) i = (s i : zmod (2^(p'+2) - 1)):= begin induction i with i ih, { dsimp [s, s_zmod], norm_num, }, { push_cast [s, s_zmod, ih] }, end -- These next two don't make good `norm_cast` lemmas. lemma int.coe_nat_pow_pred (b p : ℕ) (w : 0 < b) : ((b^p - 1 : ℕ) : ℤ) = (b^p - 1 : ℤ) := begin have : 1 ≤ b^p := nat.one_le_pow p b w, push_cast [this], end lemma int.coe_nat_two_pow_pred (p : ℕ) : ((2^p - 1 : ℕ) : ℤ) = (2^p - 1 : ℤ) := int.coe_nat_pow_pred 2 p dec_trivial lemma s_zmod_eq_s_mod (p : ℕ) (i : ℕ) : s_zmod p i = (s_mod p i : zmod (2^p - 1)) := by induction i; push_cast [←int.coe_nat_two_pow_pred p, s_mod, s_zmod, *] /-- The Lucas-Lehmer residue is `s p (p-2)` in `zmod (2^p - 1)`. -/ def lucas_lehmer_residue (p : ℕ) : zmod (2^p - 1) := s_zmod p (p-2) lemma residue_eq_zero_iff_s_mod_eq_zero (p : ℕ) (w : 1 < p) : lucas_lehmer_residue p = 0 ↔ s_mod p (p-2) = 0 := begin dsimp [lucas_lehmer_residue], rw s_zmod_eq_s_mod p, split, { -- We want to use that fact that `0 ≤ s_mod p (p-2) < 2^p - 1` -- and `lucas_lehmer_residue p = 0 → 2^p - 1 ∣ s_mod p (p-2)`. intro h, simp [zmod.int_coe_zmod_eq_zero_iff_dvd] at h, apply int.eq_zero_of_dvd_of_nonneg_of_lt _ _ h; clear h, apply s_mod_nonneg _ (nat.lt_of_succ_lt w), convert s_mod_lt _ (nat.lt_of_succ_lt w) (p-2), push_cast [nat.one_le_two_pow p], refl, }, { intro h, rw h, simp, }, end /-- A Mersenne number `2^p-1` is prime if and only if the Lucas-Lehmer residue `s p (p-2) % (2^p - 1)` is zero. -/ @[derive decidable_pred] def lucas_lehmer_test (p : ℕ) : Prop := lucas_lehmer_residue p = 0 /-- `q` is defined as the minimum factor of `mersenne p`, bundled as an `ℕ+`. -/ def q (p : ℕ) : ℕ+ := ⟨nat.min_fac (mersenne p), nat.min_fac_pos (mersenne p)⟩ instance fact_pnat_pos (q : ℕ+) : fact (0 < (q : ℕ)) := q.2 /-- We construct the ring `X q` as ℤ/qℤ + √3 ℤ/qℤ. -/ -- It would be nice to define this as (ℤ/qℤ)[x] / (x^2 - 3), -- obtaining the ring structure for free, -- but that seems to be more trouble than it's worth; -- if it were easy to make the definition, -- cardinality calculations would be somewhat more involved, too. @[derive [add_comm_group, decidable_eq, fintype, inhabited]] def X (q : ℕ+) : Type := (zmod q) × (zmod q) namespace X variable {q : ℕ+} @[ext] lemma ext {x y : X q} (h₁ : x.1 = y.1) (h₂ : x.2 = y.2) : x = y := begin cases x, cases y, congr; assumption end @[simp] lemma add_fst (x y : X q) : (x + y).1 = x.1 + y.1 := rfl @[simp] lemma add_snd (x y : X q) : (x + y).2 = x.2 + y.2 := rfl @[simp] lemma neg_fst (x : X q) : (-x).1 = -x.1 := rfl @[simp] lemma neg_snd (x : X q) : (-x).2 = -x.2 := rfl instance : has_mul (X q) := { mul := λ x y, (x.1*y.1 + 3*x.2*y.2, x.1*y.2 + x.2*y.1) } @[simp] lemma mul_fst (x y : X q) : (x * y).1 = x.1 * y.1 + 3 * x.2 * y.2 := rfl @[simp] lemma mul_snd (x y : X q) : (x * y).2 = x.1 * y.2 + x.2 * y.1 := rfl instance : has_one (X q) := { one := ⟨1,0⟩ } @[simp] lemma one_fst : (1 : X q).1 = 1 := rfl @[simp] lemma one_snd : (1 : X q).2 = 0 := rfl @[simp] lemma bit0_fst (x : X q) : (bit0 x).1 = bit0 x.1 := rfl @[simp] lemma bit0_snd (x : X q) : (bit0 x).2 = bit0 x.2 := rfl @[simp] lemma bit1_fst (x : X q) : (bit1 x).1 = bit1 x.1 := rfl @[simp] lemma bit1_snd (x : X q) : (bit1 x).2 = bit0 x.2 := by { dsimp [bit1], simp, } instance : monoid (X q) := { mul_assoc := λ x y z, by { ext; { dsimp, ring }, }, one := ⟨1,0⟩, one_mul := λ x, by { ext; simp, }, mul_one := λ x, by { ext; simp, }, ..(infer_instance : has_mul (X q)) } lemma left_distrib (x y z : X q) : x * (y + z) = x * y + x * z := by { ext; { dsimp, ring }, } lemma right_distrib (x y z : X q) : (x + y) * z = x * z + y * z := by { ext; { dsimp, ring }, } instance : ring (X q) := { left_distrib := left_distrib, right_distrib := right_distrib, ..(infer_instance : add_comm_group (X q)), ..(infer_instance : monoid (X q)) } instance : comm_ring (X q) := { mul_comm := λ x y, by { ext; { dsimp, ring }, }, ..(infer_instance : ring (X q))} instance [fact (1 < (q : ℕ))] : nontrivial (X q) := ⟨⟨0, 1, λ h, by { injection h with h1 _, exact zero_ne_one h1 } ⟩⟩ @[simp] lemma nat_coe_fst (n : ℕ) : (n : X q).fst = (n : zmod q) := begin induction n, { refl, }, { dsimp, simp only [add_left_inj], exact n_ih, } end @[simp] lemma nat_coe_snd (n : ℕ) : (n : X q).snd = (0 : zmod q) := begin induction n, { refl, }, { dsimp, simp only [add_zero], exact n_ih, } end @[simp] lemma int_coe_fst (n : ℤ) : (n : X q).fst = (n : zmod q) := by { induction n; simp, } @[simp] lemma int_coe_snd (n : ℤ) : (n : X q).snd = (0 : zmod q) := by { induction n; simp, } @[norm_cast] lemma coe_mul (n m : ℤ) : ((n * m : ℤ) : X q) = (n : X q) * (m : X q) := by { ext; simp; ring } @[norm_cast] lemma coe_nat (n : ℕ) : ((n : ℤ) : X q) = (n : X q) := by { ext; simp, } /-- The cardinality of `X` is `q^2`. -/ lemma X_card : fintype.card (X q) = q^2 := begin dsimp [X], rw [fintype.card_prod, zmod.card q], ring, end /-- There are strictly fewer than `q^2` units, since `0` is not a unit. -/ lemma units_card (w : 1 < q) : fintype.card (units (X q)) < q^2 := begin haveI : fact (1 < (q : ℕ)) := w, convert card_units_lt (X q), rw X_card, end /-- We define `ω = 2 + √3`. -/ def ω : X q := (2, 1) /-- We define `ωb = 2 - √3`, which is the inverse of `ω`. -/ def ωb : X q := (2, -1) lemma ω_mul_ωb (q : ℕ+) : (ω : X q) * ωb = 1 := begin dsimp [ω, ωb], ext; simp; ring, end lemma ωb_mul_ω (q : ℕ+) : (ωb : X q) * ω = 1 := begin dsimp [ω, ωb], ext; simp; ring, end /-- A closed form for the recurrence relation. -/ lemma closed_form (i : ℕ) : (s i : X q) = (ω : X q)^(2^i) + (ωb : X q)^(2^i) := begin induction i with i ih, { dsimp [s, ω, ωb], ext; { simp; refl, }, }, { calc (s (i + 1) : X q) = ((s i)^2 - 2 : ℤ) : rfl ... = ((s i : X q)^2 - 2) : by push_cast ... = (ω^(2^i) + ωb^(2^i))^2 - 2 : by rw ih ... = (ω^(2^i))^2 + (ωb^(2^i))^2 + 2*(ωb^(2^i)*ω^(2^i)) - 2 : by ring ... = (ω^(2^i))^2 + (ωb^(2^i))^2 : by rw [←mul_pow ωb ω, ωb_mul_ω, _root_.one_pow, mul_one, add_sub_cancel] ... = ω^(2^(i+1)) + ωb^(2^(i+1)) : by rw [←pow_mul, ←pow_mul, nat.pow_succ] } end end X open X /-! Here and below, we introduce `p' = p - 2`, in order to avoid using subtraction in `ℕ`. -/ /-- If `1 < p`, then `q p`, the smallest prime factor of `mersenne p`, is more than 2. -/ lemma two_lt_q (p' : ℕ) : 2 < q (p'+2) := begin by_contradiction, simp at a, interval_cases q (p'+2); clear a, { -- If q = 1, we get a contradiction from 2^p = 2 dsimp [q] at h, injection h with h', clear h, simp [mersenne] at h', exact lt_irrefl 2 (calc 2 ≤ p'+2 : nat.le_add_left _ _ ... < 2^(p'+2) : nat.lt_two_pow _ ... = 2 : nat.pred_inj (nat.one_le_two_pow _) dec_trivial h'), }, { -- If q = 2, we get a contradiction from 2 ∣ 2^p - 1 dsimp [q] at h, injection h with h', clear h, rw [mersenne, pnat.one_coe, nat.min_fac_eq_two_iff, nat.pow_succ, nat.mul_comm] at h', exact nat.two_not_dvd_two_mul_sub_one (nat.one_le_two_pow _) h', } end theorem ω_pow_formula (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) : ∃ (k : ℤ), (ω : X (q (p'+2)))^(2^(p'+1)) = k * (mersenne (p'+2)) * ((ω : X (q (p'+2)))^(2^p')) - 1 := begin dsimp [lucas_lehmer_residue] at h, rw s_zmod_eq_s p' at h, simp [zmod.int_coe_zmod_eq_zero_iff_dvd] at h, cases h with k h, use k, replace h := congr_arg (λ (n : ℤ), (n : X (q (p'+2)))) h, -- coercion from ℤ to X q dsimp at h, rw closed_form at h, replace h := congr_arg (λ x, ω^2^p' * x) h, dsimp at h, have t : 2^p' + 2^p' = 2^(p'+1) := by ring_exp, rw [mul_add, ←pow_add ω, t, ←mul_pow ω ωb (2^p'), ω_mul_ωb, _root_.one_pow] at h, rw [mul_comm, coe_mul] at h, rw [mul_comm _ (k : X (q (p'+2)))] at h, replace h := eq_sub_of_add_eq h, exact_mod_cast h, end /-- `q` is the minimum factor of `mersenne p`, so `M p = 0` in `X q`. -/ theorem mersenne_coe_X (p : ℕ) : (mersenne p : X (q p)) = 0 := begin ext; simp [mersenne, q, zmod.nat_coe_zmod_eq_zero_iff_dvd], apply nat.min_fac_dvd, end theorem ω_pow_eq_neg_one (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) : (ω : X (q (p'+2)))^(2^(p'+1)) = -1 := begin cases ω_pow_formula p' h with k w, rw [mersenne_coe_X] at w, simpa using w, end theorem ω_pow_eq_one (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) : (ω : X (q (p'+2)))^(2^(p'+2)) = 1 := calc (ω : X (q (p'+2)))^2^(p'+2) = (ω^(2^(p'+1)))^2 : by rw [←pow_mul, ←nat.pow_succ] ... = (-1)^2 : by rw ω_pow_eq_neg_one p' h ... = 1 : by simp /-- `ω` as an element of the group of units. -/ def ω_unit (p : ℕ) : units (X (q p)) := { val := ω, inv := ωb, val_inv := by simp [ω_mul_ωb], inv_val := by simp [ωb_mul_ω], } @[simp] lemma ω_unit_coe (p : ℕ) : (ω_unit p : X (q p)) = ω := rfl /-- The order of `ω` in the unit group is exactly `2^p`. -/ theorem order_ω (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) : order_of (ω_unit (p'+2)) = 2^(p'+2) := begin apply nat.eq_prime_pow_of_dvd_least_prime_pow, -- the order of ω divides 2^p { norm_num, }, { intro o, have ω_pow := order_of_dvd_iff_pow_eq_one.1 o, replace ω_pow := congr_arg (units.coe_hom (X (q (p'+2))) : units (X (q (p'+2))) → X (q (p'+2))) ω_pow, simp at ω_pow, have h : (1 : zmod (q (p'+2))) = -1 := congr_arg (prod.fst) ((ω_pow.symm).trans (ω_pow_eq_neg_one p' h)), haveI : fact (2 < (q (p'+2) : ℕ)) := two_lt_q _, apply zmod.neg_one_ne_one h.symm, }, { apply order_of_dvd_iff_pow_eq_one.2, apply units.ext, push_cast, exact ω_pow_eq_one p' h, } end lemma order_ineq (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) : 2^(p'+2) < (q (p'+2) : ℕ)^2 := calc 2^(p'+2) = order_of (ω_unit (p'+2)) : (order_ω p' h).symm ... ≤ fintype.card (units (X _)) : order_of_le_card_univ ... < (q (p'+2) : ℕ)^2 : units_card (nat.lt_of_succ_lt (two_lt_q _)) end lucas_lehmer export lucas_lehmer (lucas_lehmer_test lucas_lehmer_residue) open lucas_lehmer theorem lucas_lehmer_sufficiency (p : ℕ) (w : 1 < p) : lucas_lehmer_test p → (mersenne p).prime := begin let p' := p - 2, have z : p = p' + 2 := (nat.sub_eq_iff_eq_add w).mp rfl, have w : 1 < p' + 2 := (nat.lt_of_sub_eq_succ rfl), contrapose, intros a t, rw z at a, rw z at t, have h₁ := order_ineq p' t, have h₂ := nat.min_fac_sq_le_self (mersenne_pos (nat.lt_of_succ_lt w)) a, have h := lt_of_lt_of_le h₁ h₂, exact not_lt_of_ge (nat.sub_le _ _) h, end -- Here we calculate the residue, very inefficiently, using `dec_trivial`. We can do much better. example : (mersenne 5).prime := lucas_lehmer_sufficiency 5 (by norm_num) dec_trivial -- Next we use `norm_num` to calculate each `s p i`. namespace lucas_lehmer open tactic meta instance nat_pexpr : has_to_pexpr ℕ := ⟨pexpr.of_expr ∘ λ n, reflect n⟩ meta instance int_pexpr : has_to_pexpr ℤ := ⟨pexpr.of_expr ∘ λ n, reflect n⟩ lemma s_mod_succ {p a i b c} (h1 : (2^p - 1 : ℤ) = a) (h2 : s_mod p i = b) (h3 : (b * b - 2) % a = c) : s_mod p (i+1) = c := by { dsimp [s_mod, mersenne], rw [h1, h2, _root_.pow_two, h3] } /-- Given a goal of the form `lucas_lehmer_test p`, attempt to do the calculation using `norm_num` to certify each step. -/ meta def run_test : tactic unit := do `(lucas_lehmer_test %%p) ← target, `[dsimp [lucas_lehmer_test]], `[rw lucas_lehmer.residue_eq_zero_iff_s_mod_eq_zero, swap, norm_num], p ← eval_expr ℕ p, -- Calculate the candidate Mersenne prime let M : ℤ := 2^p - 1, t ← to_expr ``(2^%%p - 1 = %%M), v ← to_expr ``(by norm_num : 2^%%p - 1 = %%M), w ← assertv `w t v, -- Unfortunately this creates something like `w : 2^5 - 1 = int.of_nat 31`. -- We could make a better `has_to_pexpr ℤ` instance, or just: `[simp only [int.coe_nat_zero, int.coe_nat_succ, int.of_nat_eq_coe, zero_add, int.coe_nat_bit1] at w], -- base case t ← to_expr ``(s_mod %%p 0 = 4), v ← to_expr ``(by norm_num [lucas_lehmer.s_mod] : s_mod %%p 0 = 4), h ← assertv `h t v, -- step case, repeated p-2 times iterate_exactly (p-2) `[replace h := lucas_lehmer.s_mod_succ w h (by { norm_num, refl })], -- now close the goal h ← get_local `h, exact h end lucas_lehmer /-- We verify that the tactic works to prove `127.prime`. -/ example : (mersenne 7).prime := lucas_lehmer_sufficiency _ (by norm_num) (by lucas_lehmer.run_test). /-! This implementation works successfully to prove `(2^127 - 1).prime`, and all the Mersenne primes up to this point appear in [archive/examples/mersenne_primes.lean]. `(2^127 - 1).prime` takes about 5 minutes to run (depending on your CPU!), and unfortunately the next Mersenne prime `(2^521 - 1)`, which was the first "computer era" prime, is out of reach with the current implementation. There's still low hanging fruit available to do faster computations based on the formula n ≡ (n % 2^p) + (n / 2^p) [MOD 2^p - 1] and the fact that `% 2^p` and `/ 2^p` can be very efficient on the binary representation. Someone should do this, too! -/ lemma modeq_mersenne (n k : ℕ) : k ≡ ((k / 2^n) + (k % 2^n)) [MOD 2^n - 1] := -- See https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/help.20finding.20a.20lemma/near/177698446 begin conv in k {rw [← nat.mod_add_div k (2^n), add_comm]}, refine nat.modeq.modeq_add _ (by refl), conv {congr, skip, skip, rw ← one_mul (k/2^n)}, refine nat.modeq.modeq_mul _ (by refl), symmetry, rw [nat.modeq.modeq_iff_dvd, int.coe_nat_sub], exact nat.pow_pos dec_trivial _ end -- It's hard to know what the limiting factor for large Mersenne primes would be. -- In the purely computational world, I think it's the squaring operation in `s`.
0164a7340c394d5a057e306beeabb5f9465f0fc4
46125763b4dbf50619e8846a1371029346f4c3db
/src/analysis/calculus/fderiv.lean
7c203d6a6f18849e619c4497d00c58400774a962
[ "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
80,401
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` ## 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. ## 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. ## 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] /-- 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) 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 lattice.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 } /-- 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 congr /-! ### congr properties of the derivative -/ 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 := by { rw (ext h₁), exact is_o_congr (by filter_upwards [h₀] λ x (h : _ = _), by simp [h, hx]) (univ_mem_sets' $ λ _, 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 := begin apply (has_fderiv_at_filter_congr_of_mem_sets hx hL _).2 h, exact λx, rfl end 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 := begin by_cases h : differentiable_within_at 𝕜 f s x ∨ differentiable_within_at 𝕜 f₁ s x, { cases h, { apply has_fderiv_within_at.fderiv_within _ hs, exact has_fderiv_at_filter.congr_of_mem_sets h.has_fderiv_within_at hL hx }, { symmetry, apply has_fderiv_within_at.fderiv_within _ hs, apply has_fderiv_at_filter.congr_of_mem_sets h.has_fderiv_within_at _ hx.symm, convert hL, ext y, exact eq_comm } }, { push_neg at h, have A : fderiv_within 𝕜 f s x = 0, by { unfold differentiable_within_at at h, simp [fderiv_within, h] }, have A₁ : fderiv_within 𝕜 f₁ s x = 0, by { unfold differentiable_within_at at h, simp [fderiv_within, h] }, rw [A, A₁] } end 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_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 _ _ lemma differentiable_at_id : differentiable_at 𝕜 id 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 lemma differentiable_id : differentiable 𝕜 (id : E → E) := λ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_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 _ _ _ 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 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. -/ 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 := begin have : (λ (x' : E), f x' - f x - h.to_continuous_linear_map (x' - x)) = λx', 0, { ext, have : ∀a, h.to_continuous_linear_map a = f a := λa, rfl, simp, simp [this] }, rw [has_fderiv_at_filter, this], exact asymptotics.is_o_zero _ _ end 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 lemma continuous_linear_map.has_fderiv_at_filter : has_fderiv_at_filter e e x L := begin have : (λ (x' : E), e x' - e x - e (x' - x)) = λx', 0, by { ext, simp }, rw [has_fderiv_at_filter, this], exact asymptotics.is_o_zero _ _ end 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 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 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 end continuous_linear_map section const_smul /-! ### Derivative of a function multiplied by a constant -/ 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 := (is_o_const_smul_left h c).congr_left $ λ x, by simp [smul_sub] 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_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 [sub_eq_add_neg]; 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 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) 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_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_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_fderiv_at_filter.neg (h : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (λ x, -f x) (-f') x L := (h.const_smul (-1:𝕜)).congr (by simp) (by simp) 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 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 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_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 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) 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_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 _ _) 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_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 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 lattice.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 end continuous 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_fderiv_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_fderiv_at b (h.deriv p) p := begin have : (λ (x : E × F), b x - b p - (h.deriv p) (x - p)) = (λx, b (x.1 - p.1, x.2 - p.2)), { ext x, delta is_bounded_bilinear_map.deriv, change b x - b p - (b (p.1, x.2-p.2) + b (x.1-p.1, p.2)) = b (x.1 - p.1, x.2 - p.2), have : b x = b (x.1, x.2), by { cases x, refl }, rw this, have : b p = b (p.1, p.2), by { cases p, refl }, rw this, simp only [h.map_sub_left, h.map_sub_right], abel }, rw [has_fderiv_at, has_fderiv_at_filter, this], rcases h.bound with ⟨C, Cpos, hC⟩, have A : asymptotics.is_O (λx : E × F, b (x.1 - p.1, x.2 - p.2)) (λx, ∥x - p∥ * ∥x - p∥) (𝓝 p) := ⟨C, filter.univ_mem_sets' (λx, begin simp only [mem_set_of_eq, norm_mul, norm_norm], calc ∥b (x.1 - p.1, x.2 - p.2)∥ ≤ C * ∥x.1 - p.1∥ * ∥x.2 - p.2∥ : hC _ _ ... ≤ C * ∥x-p∥ * ∥x-p∥ : by apply_rules [mul_le_mul, le_max_left, le_max_right, norm_nonneg, le_of_lt Cpos, le_refl, mul_nonneg, norm_nonneg, norm_nonneg] ... = C * (∥x-p∥ * ∥x-p∥) : mul_assoc _ _ _ end)⟩, have B : asymptotics.is_o (λ (x : E × F), ∥x - p∥ * ∥x - p∥) (λx, 1 * ∥x - p∥) (𝓝 p), { refine asymptotics.is_o.mul_is_O (asymptotics.is_o.norm_left _) (asymptotics.is_O_refl _ _), apply (asymptotics.is_o_one_iff ℝ).2, rw [← sub_self p], exact tendsto_id.sub tendsto_const_nhds }, simp only [one_mul, asymptotics.is_o_norm_right] at B, exact A.trans_is_o B end 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 cartesian_product /-! ### Derivative of the cartesian product of two functions -/ variables {f₂ : E → G} {f₂' : E →L[𝕜] G} 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 := begin have : (λ (x' : E), (f₁ x', f₂ x') - (f₁ x, f₂ x) - (continuous_linear_map.prod f₁' f₂') (x' -x)) = (λ (x' : E), (f₁ x' - f₁ x - f₁' (x' - x), f₂ x' - f₂ x - f₂' (x' - x))) := rfl, rw [has_fderiv_at_filter, this], rw [asymptotics.is_o_prod_left], exact ⟨hf₁, hf₂⟩ end 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 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) 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 cartesian_product 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 : s ⊆ f ⁻¹' 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) end composition section smul /-! ### Derivative of the product of a scalar-valued function and a vector-valued function -/ variables {c : E → 𝕜} {c' : E →L[𝕜] 𝕜} 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 := begin have : is_bounded_bilinear_map 𝕜 (λ (p : 𝕜 × F), p.1 • p.2) := is_bounded_bilinear_map_smul, exact has_fderiv_at.comp_has_fderiv_within_at x (this.has_fderiv_at (c x, f x)) (hc.prod hf) end 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 := begin have : is_bounded_bilinear_map 𝕜 (λ (p : 𝕜 × F), p.1 • p.2) := is_bounded_bilinear_map_smul, exact has_fderiv_at.comp x (this.has_fderiv_at (c x, f x)) (hc.prod hf) end 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 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) 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_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 := begin convert hc.smul (has_fderiv_within_at_const f x s), -- Help Lean find an instance letI : distrib_mul_action 𝕜 (E →L[𝕜] F) := continuous_linear_map.module.to_distrib_mul_action, rw [smul_zero, zero_add] end 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 := begin rw [← has_fderiv_within_at_univ] at *, exact hc.smul_const f end 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_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 := begin have : is_bounded_bilinear_map 𝕜 (λ (p : 𝕜 × 𝕜), p.1 * p.2) := is_bounded_bilinear_map_mul, convert has_fderiv_at.comp_has_fderiv_within_at x (this.has_fderiv_at (c x, d x)) (hc.prod hd), ext z, change c x * d' z + d x * c' z = c x * d' z + c' z * d x, ring end 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 := begin have : is_bounded_bilinear_map 𝕜 (λ (p : 𝕜 × 𝕜), p.1 * p.2) := is_bounded_bilinear_map_mul, convert has_fderiv_at.comp x (this.has_fderiv_at (c x, d x)) (hc.prod hd), ext z, change c x * d' z + d x * c' z = c x * d' z + c' z * d x, ring end 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 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) 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_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 := begin have := hc.mul (has_fderiv_within_at_const d x s), letI : distrib_mul_action 𝕜 (E →L[𝕜] 𝕜) := continuous_linear_map.module.to_distrib_mul_action, rwa [smul_zero, zero_add] at this end 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_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_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_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 := begin set g := (iso.symm : F →L[𝕜] E).comp f' with h, have : f' = (iso : E →L[𝕜] F).comp g, by rw [h, ← continuous_linear_map.comp_assoc, iso.coe_comp_coe_symm, continuous_linear_map.id_comp], rw this, exact iso.comp_has_fderiv_within_at_iff end 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, by simp [-coe_fn_coe_base, iso.comp_differentiable_within_at_iff, h], rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at this], ext y, simp [-coe_fn_coe_base] } 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.image_tangent_cone_subset {x : E} (h : has_fderiv_within_at f f' s x) : f' '' (tangent_cone_at 𝕜 s x) ⊆ tangent_cone_at 𝕜 (f '' s) (f x) := begin rw image_subset_iff, 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 A : ∀v ∈ tangent_cone_at 𝕜 s x, f' v ∈ tangent_cone_at 𝕜 (f '' s) (f x), { assume v hv, have := h.image_tangent_cone_subset, rw image_subset_iff at this, exact this hv }, 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 (A w 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_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
f172aae10364f4df5daaa78d8f5d17f99d210d95
e846540d974f0d04ca0ccd21f55379175fb829a8
/syntax.lean
085343fa3aec82748bc3c2868a74bb9afb946ea5
[]
no_license
minchaowu/proof-theory
a16ecdde168561269c3a7e758348b3e4c34a2adc
e16141ff21750f957b5604e44e32ac7f6f030015
refs/heads/master
1,593,035,082,878
1,482,281,443,000
1,482,281,443,000
74,620,325
0
0
null
null
null
null
UTF-8
Lean
false
false
35,625
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura Modified by Minchao Wu. Define propositional calculus, valuation, provability, validity, prove soundness, completeness, compactness. This file is based on Floris van Doorn Coq files. -/ import data.nat data.set open nat bool set decidable classical theorem gnp (S : set ℕ) [finite S] : S ≠ ∅ → ∃₀ n ∈ S, ∀₀ m ∈ S, m ≤ n := induction_on_finite S (λ H, absurd rfl H) (λ a S' finS' notin ih H, by_cases (suppose S' = ∅, have Hl : a ∈ insert a S', from !mem_insert, have eq : insert a S' = '{a}, by+ simp, have ∀ y, y ∈ insert a S' → y ≤ a, from λ y h, have y ∈ '{a}, by+ simp, have y = a, from eq_of_mem_singleton this, by+ simp, show _, from exists.intro a (and.intro Hl this)) (assume Hneg, obtain b hb, from ih Hneg, by_cases (suppose a < b, have Hl : b ∈ insert a S', from !subset_insert (and.left hb), have ∀ y, y ∈ insert a S' → y ≤ b, from λ y hy, or.elim hy (λ Hl, have y < b, by+ simp, le_of_lt this) (λ Hr, (and.right hb) y Hr), show _, from exists.intro b (and.intro Hl this)) (assume nlt, have le : b ≤ a, from le_of_not_gt nlt, have Hl : a ∈ insert a S', from !mem_insert, have ∀ y, y ∈ insert a S' → y ≤ a, from λy hy, or.elim hy (λ Hl, le_of_eq Hl) (λ Hr, have y ≤ b, from (and.right hb) y Hr, nat.le_trans this le), show _, from exists.intro a (and.intro Hl this)))) theorem ne_empty_of_mem {X : Type} {s : set X} {x : X} (H : x ∈ s) : s ≠ ∅ := begin intro Hs, rewrite Hs at H, apply not_mem_empty _ H end theorem image_of_ne_empty {A B : Type} (f : A → B) (s : set A) (H : s ≠ ∅): f ' s ≠ ∅ := obtain a ha, from exists_mem_of_ne_empty H, have f a ∈ f ' s, from !mem_image_of_mem ha, show _, from ne_empty_of_mem this definition PropVar [reducible] := nat inductive PropF := | Var : PropVar → PropF | Bot : PropF | Conj : PropF → PropF → PropF | Disj : PropF → PropF → PropF | Impl : PropF → PropF → PropF namespace PropF notation `#`:max P:max := Var P notation A ∨ B := Disj A B notation A ∧ B := Conj A B infixr `⇒`:27 := Impl notation `⊥` := Bot definition Neg A := A ⇒ ⊥ notation ~ A := Neg A definition Top := ~⊥ notation `⊤` := Top definition BiImpl A B := A ⇒ B ∧ B ⇒ A infixr `⇔`:27 := BiImpl definition valuation := PropVar → bool definition TrueQ (v : valuation) : PropF → bool | TrueQ (# P) := v P | TrueQ ⊥ := ff | TrueQ (A ∨ B) := TrueQ A || TrueQ B | TrueQ (A ∧ B) := TrueQ A && TrueQ B | TrueQ (A ⇒ B) := bnot (TrueQ A) || TrueQ B definition is_true [reducible] (b : bool) := b = tt -- the valuation v satisfies a list of PropF, if forall (A : PropF) in Γ, -- (TrueQ v A) is tt (the Boolean true) definition Satisfies v Γ := ∀ A, A ∈ Γ → is_true (TrueQ v A) definition Models Γ A := ∀ v, Satisfies v Γ → is_true (TrueQ v A) infix `⊨`:80 := Models definition Valid p := ∅ ⊨ p reserve infix `⊢`:26 /- Provability -/ inductive Nc : set PropF → PropF → Prop := infix ⊢ := Nc | Nax : ∀ Γ A, A ∈ Γ → Γ ⊢ A | ImpI : ∀ Γ A B, insert A Γ ⊢ B → Γ ⊢ A ⇒ B | ImpE : ∀ Γ A B, Γ ⊢ A ⇒ B → Γ ⊢ A → Γ ⊢ B | BotC : ∀ Γ A, insert (~A) Γ ⊢ ⊥ → Γ ⊢ A | AndI : ∀ Γ A B, Γ ⊢ A → Γ ⊢ B → Γ ⊢ A ∧ B | AndE₁ : ∀ Γ A B, Γ ⊢ A ∧ B → Γ ⊢ A | AndE₂ : ∀ Γ A B, Γ ⊢ A ∧ B → Γ ⊢ B | OrI₁ : ∀ Γ A B, Γ ⊢ A → Γ ⊢ A ∨ B | OrI₂ : ∀ Γ A B, Γ ⊢ B → Γ ⊢ A ∨ B | OrE : ∀ Γ A B C, Γ ⊢ A ∨ B → insert A Γ ⊢ C → insert B Γ ⊢ C → Γ ⊢ C infix ⊢ := Nc definition Provable A := ∅ ⊢ A definition Prop_Soundness := ∀ A, Provable A → Valid A definition Prop_Completeness := ∀ A, Valid A → Provable A lemma subset_insert_of_not_mem {A : Type} {S s: set A} {a : A} (H1 : s ⊆ insert a S) (H2 : a ∉ s) : s ⊆ S := λ x h, or.elim (H1 h) (λ Hl, have a ∈ s, by+ simp, absurd this H2) (λ Hr, Hr) lemma subset_insert_of_mem {A : Type} {S s: set A} {a : A} (H1 : s ⊆ insert a S) (H2 : a ∈ s) : s \ '{a} ⊆ S := λ x h, have x ∈ insert a S, from H1 (and.left h), or.elim this (λ Hl, have x ∈ '{a}, by+ rewrite Hl; apply mem_singleton, absurd this (and.right h)) (λ Hr, Hr) lemma subset_diff_of_subset {A : Type} {S s: set A} {a : A} (H1 : s ⊆ insert a S) : s \ '{a} ⊆ S := have s \ '{a} ⊆ s, from diff_subset _ _, or.elim (em (a ∈ s)) (λ Hl, subset_insert_of_mem H1 Hl) (λ Hr, subset.trans this (subset_insert_of_not_mem H1 Hr) ) lemma subset_insert_diff {A : Type} {S: set A} {a : A} : S ⊆ insert a (S \ '{a}) := λ x h, or.elim (em (x = a)) (λ Hl, or.inl Hl) (λ Hr, have x ∉ '{a}, from λ Hneg, have x = a, from eq_of_mem_singleton Hneg, Hr this, have x ∈ S \ '{a}, from and.intro h this, or.inr this) theorem insert_sub_insert {A : Type} {s₁ s₂ : set A} (a : A) (H : s₁ ⊆ s₂) : insert a s₁ ⊆ insert a s₂ := take x, assume H1, or.elim H1 (λ Hl, or.inl Hl) (λ Hr, or.inr (H Hr)) open Nc lemma weakening : ∀ Γ A, Γ ⊢ A → ∀ Δ, Γ ⊆ Δ → Δ ⊢ A := λ Γ A H, Nc.induction_on H (λ Γ A Hin Δ Hs, !Nax (Hs A Hin)) (λ Γ A B H w Δ Hs, !ImpI (w _ (insert_sub_insert A Hs))) (λ Γ A B H₁ H₂ w₁ w₂ Δ Hs, !ImpE (w₁ _ Hs) (w₂ _ Hs)) (λ Γ A H w Δ Hs, !BotC (w _ (insert_sub_insert (~A) Hs))) (λ Γ A B H₁ H₂ w₁ w₂ Δ Hs, !AndI (w₁ _ Hs) (w₂ _ Hs)) (λ Γ A B H w Δ Hs, !AndE₁ (w _ Hs)) (λ Γ A B H w Δ Hs, !AndE₂ (w _ Hs)) (λ Γ A B H w Δ Hs, !OrI₁ (w _ Hs)) (λ Γ A B H w Δ Hs, !OrI₂ (w _ Hs)) (λ Γ A B C H₁ H₂ H₃ w₁ w₂ w₃ Δ Hs, !OrE (w₁ _ Hs) (w₂ _ (insert_sub_insert A Hs)) (w₃ _ (insert_sub_insert B Hs))) lemma deduction : ∀ Γ A B, Γ ⊢ A ⇒ B → insert A Γ ⊢ B := λ Γ A B H, ImpE _ A _ (!weakening H _ (subset_insert A Γ)) (!Nax (mem_insert A Γ)) lemma prov_impl : ∀ A B, Provable (A ⇒ B) → ∀ Γ, Γ ⊢ A → Γ ⊢ B := λ A B Hp Γ Ha, have wHp : Γ ⊢ (A ⇒ B), from !weakening Hp Γ (empty_subset Γ), !ImpE wHp Ha lemma Satisfies_cons : ∀ {A Γ v}, Satisfies v Γ → is_true (TrueQ v A) → Satisfies v (insert A Γ) := λ A Γ v s t B BinAG, or.elim BinAG (λ e : B = A, by rewrite e; exact t) (λ i : B ∈ Γ, s _ i) theorem Soundness_general : ∀ A Γ, Γ ⊢ A → Γ ⊨ A := λ A Γ H, Nc.induction_on H (λ Γ A Hin v s, (s _ Hin)) (λ Γ A B H r v s, by_cases (λ t : is_true (TrueQ v A), have aux₁ : Satisfies v (insert A Γ), from Satisfies_cons s t, have aux₂ : is_true (TrueQ v B), from r v aux₁, bor_inr aux₂) (λ f : ¬ is_true (TrueQ v A), have aux : bnot (TrueQ v A) = tt, by rewrite (eq_ff_of_ne_tt f), bor_inl aux)) (λ Γ A B H₁ H₂ r₁ r₂ v s, have aux₁ : bnot (TrueQ v A) || TrueQ v B = tt, from r₁ v s, have aux₂ : TrueQ v A = tt, from r₂ v s, by+ rewrite [aux₂ at aux₁, bnot_true at aux₁, ff_bor at aux₁]; exact aux₁) (λ Γ A H r v s, by_contradiction (λ n : TrueQ v A ≠ tt, have aux₁ : TrueQ v A = ff, from eq_ff_of_ne_tt n, have aux₂ : TrueQ v (~A) = tt, begin+ change (bnot (TrueQ v A) || ff = tt), rewrite aux₁ end, have aux₃ : Satisfies v (insert (~A) Γ), from Satisfies_cons s aux₂, have aux₄ : TrueQ v ⊥ = tt, from r v aux₃, absurd aux₄ ff_ne_tt)) (λ Γ A B H₁ H₂ r₁ r₂ v s, have aux₁ : TrueQ v A = tt, from r₁ v s, have aux₂ : TrueQ v B = tt, from r₂ v s, band_intro aux₁ aux₂) (λ Γ A B H r v s, have aux : TrueQ v (A ∧ B) = tt, from r v s, band_elim_left aux) (λ Γ A B H r v s, have aux : TrueQ v (A ∧ B) = tt, from r v s, band_elim_right aux) (λ Γ A B H r v s, have aux : TrueQ v A = tt, from r v s, bor_inl aux) (λ Γ A B H r v s, have aux : TrueQ v B = tt, from r v s, bor_inr aux) (λ Γ A B C H₁ H₂ H₃ r₁ r₂ r₃ v s, have aux : TrueQ v A || TrueQ v B = tt, from r₁ v s, or.elim (or_of_bor_eq aux) (λ At : TrueQ v A = tt, have aux : Satisfies v (insert A Γ), from Satisfies_cons s At, r₂ v aux) (λ Bt : TrueQ v B = tt, have aux : Satisfies v (insert B Γ), from Satisfies_cons s Bt, r₃ v aux)) theorem Soundness : Prop_Soundness := λ A, Soundness_general A ∅ -- By Minchao theorem finite_proof (Γ : set PropF) (α : PropF) (H : Γ ⊢ α) : ∃ s, finite s ∧ s ⊆ Γ ∧ (s ⊢ α) := Nc.rec_on H (λ Γ a Hin, have Hl : finite '{a}, from finite_insert _ _, have rl : '{a} ⊆ Γ, from λ x h, have x = a, from eq_of_mem_singleton h, by+ simp, have rr : '{a} ⊢ a, from !Nax !mem_singleton, have finite '{a} ∧ '{a} ⊆ Γ ∧ ('{a} ⊢ a), from and.intro Hl (and.intro rl rr), exists.intro '{a} this) (λ Γ' a b H ih, obtain s hs, from ih, have prov : s ⊢ b, from and.right (and.right hs), have rl : s \ '{a} ⊆ Γ', from subset_diff_of_subset (and.left (and.right hs)), have Hl : finite (s \ '{a}), from @finite_diff _ _ _ (and.left hs), have s ⊆ insert a (s \ '{a}), from subset_insert_diff, have insert a (s \ '{a}) ⊢ b, from !weakening prov _ this, have s \ '{a} ⊢ a ⇒ b, from !ImpI this, exists.intro (s \ '{a}) (and.intro Hl (and.intro rl this))) (λ Γ' a b H ih h1 h2, obtain s₁ h₁, from h1, obtain s₂ h₂, from h2, have fin : finite (s₁ ∪ s₂), from @finite_union _ _ _ (and.left h₁) (and.left h₂), have H1 : (s₁ ∪ s₂) ⊢ a ⇒ b, from !weakening (and.right (and.right h₁)) _ (subset_union_left _ _), have (s₁ ∪ s₂) ⊢ a, from !weakening (and.right (and.right h₂)) _ (subset_union_right _ _), have rr : (s₁ ∪ s₂) ⊢ b, from !ImpE H1 this, have sub : (s₁ ∪ s₂) ⊆ Γ', from union_subset (and.left (and.right h₁)) (and.left (and.right h₂)), exists.intro (s₁ ∪ s₂) (and.intro fin (and.intro sub rr))) (λ Γ' a H ih, obtain s hs, from ih, have prov : s ⊢ ⊥, from and.right (and.right hs), have rl : s \ '{~a} ⊆ Γ', from subset_diff_of_subset (and.left (and.right hs)), have Hl : finite (s \ '{~a}), from @finite_diff _ _ _ (and.left hs), have s ⊆ insert (~a) (s \ '{~a}), from subset_insert_diff, have insert (~a) (s \ '{~a}) ⊢ ⊥, from !weakening prov _ this, have s \ '{~a} ⊢ a, from !BotC this, exists.intro (s \ '{~a}) (and.intro Hl (and.intro rl this))) (λ Γ' a b H1 H2 ih1 ih2, obtain s₁ h₁, from ih1, obtain s₂ h₂, from ih2, have fin : finite (s₁ ∪ s₂), from @finite_union _ _ _ (and.left h₁) (and.left h₂), have Ha : (s₁ ∪ s₂) ⊢ a, from !weakening (and.right (and.right h₁)) _ (subset_union_left _ _), have Hb : (s₁ ∪ s₂) ⊢ b, from !weakening (and.right (and.right h₂)) _ (subset_union_right _ _), have rr : (s₁ ∪ s₂) ⊢ a ∧ b, from !AndI Ha Hb, have sub : (s₁ ∪ s₂) ⊆ Γ', from union_subset (and.left (and.right h₁)) (and.left (and.right h₂)), exists.intro (s₁ ∪ s₂) (and.intro fin (and.intro sub rr))) (λ Γ' a b H ih, obtain s hs, from ih, have sub : s ⊆ Γ', from and.left (and.right hs), have s ⊢ a, from !AndE₁ (and.right (and.right hs)), exists.intro s (and.intro (and.left hs) (and.intro sub this))) (λ Γ' a b H ih, obtain s hs, from ih, have sub : s ⊆ Γ', from and.left (and.right hs), have s ⊢ b, from !AndE₂ (and.right (and.right hs)), exists.intro s (and.intro (and.left hs) (and.intro sub this))) (λ Γ' a b H ih, obtain s hs, from ih, have sub : s ⊆ Γ', from and.left (and.right hs), have s ⊢ a ∨ b, from !OrI₁ (and.right (and.right hs)), exists.intro s (and.intro (and.left hs) (and.intro sub this))) (λ Γ' a b H ih, obtain s hs, from ih, have sub : s ⊆ Γ', from and.left (and.right hs), have s ⊢ a ∨ b, from !OrI₂ (and.right (and.right hs)), exists.intro s (and.intro (and.left hs) (and.intro sub this))) (λ Γ' a b c h0 h1 h2 ih1 ih2 ih3, obtain s₁ hs₁, from ih1, obtain s₂ hs₂, from ih2, obtain s₃ hs₃, from ih3, have prov₁ : s₁ ⊢ a ∨ b, from and.right (and.right hs₁), have prov₂ : s₂ ⊢ c, from and.right (and.right hs₂), have prov₃ : s₃ ⊢ c, from and.right (and.right hs₃), have sub₁ : s₁ ⊆ Γ', from and.left (and.right hs₁), have fin₁ : finite s₁, from and.left hs₁, have ua : s₂ \ '{a} ⊆ Γ', from subset_diff_of_subset (and.left (and.right hs₂)), have fina : finite (s₂ \ '{a}), from @finite_diff _ _ _ (and.left hs₂), have ub : s₃ \ '{b} ⊆ Γ', from subset_diff_of_subset (and.left (and.right hs₃)), have finb : finite (s₃ \ '{b}), from @finite_diff _ _ _ (and.left hs₃), have subu : (s₂ \ '{a}) ∪ (s₃ \ '{b}) ⊆ Γ', from union_subset ua ub, have sub : s₁ ∪ ((s₂ \ '{a}) ∪ (s₃ \ '{b})) ⊆ Γ', from union_subset sub₁ subu, have finu : finite ((s₂ \ '{a}) ∪ (s₃ \ '{b})), from @finite_union _ _ _ fina finb, have s₁ ∪ ((s₂ \ '{a}) ∪ (s₃ \ '{b})) ⊆ Γ', from union_subset sub₁ subu, have fin : finite (s₁ ∪ ((s₂ \ '{a}) ∪ (s₃ \ '{b}))), from @finite_union _ _ _ fin₁ finu, have sub₂ : s₂ ⊆ insert a (s₁ ∪ ((s₂ \ '{a}) ∪ (s₃ \ '{b}))), from λ x h, or.elim (em (x = a)) (λ Hl, or.inl Hl) (λ Hr, have x ∉ '{a}, from λ Hneg, Hr (eq_of_mem_singleton Hneg), have x ∈ (s₂ \ '{a}), from and.intro h this, or.inr (or.inr (or.inl this))), have sub₃ : s₃ ⊆ insert b (s₁ ∪ ((s₂ \ '{a}) ∪ (s₃ \ '{b}))), from λ x h, or.elim (em (x = b)) (λ Hl, or.inl Hl) (λ Hr, have x ∉ '{b}, from λ Hneg, Hr (eq_of_mem_singleton Hneg), have x ∈ (s₃ \ '{b}), from and.intro h this, or.inr (or.inr (or.inr this))), have H1 : insert a (s₁ ∪ ((s₂ \ '{a}) ∪ (s₃ \ '{b}))) ⊢ c, from !weakening prov₂ _ sub₂, have H2 : insert b (s₁ ∪ ((s₂ \ '{a}) ∪ (s₃ \ '{b}))) ⊢ c, from !weakening prov₃ _ sub₃, have s₁ ∪ ((s₂ \ '{a}) ∪ (s₃ \ '{b})) ⊢ a ∨ b, from !weakening prov₁ _ (subset_union_left _ _), have rr : s₁ ∪ ((s₂ \ '{a}) ∪ (s₃ \ '{b})) ⊢ c, from !OrE this H1 H2, exists.intro (s₁ ∪ ((s₂ \ '{a}) ∪ (s₃ \ '{b}))) (and.intro fin (and.intro sub rr))) theorem meta_thm0 {Γ : set PropF} {α : PropF} : Γ ⊢ α ⇒ α := !ImpI (!Nax !mem_insert) theorem meta_thm1_left {Γ : set PropF} {α β : PropF} (H : Γ ⊢ ~α) : Γ ⊢ ~(α ∧ β) := have insert (α ∧ β) Γ ⊢ α ∧ β, from !Nax !mem_insert, have H1 : insert (α ∧ β) Γ ⊢ α, from !AndE₁ this, have insert (α ∧ β) Γ ⊢ ~α, from !weakening H _ (subset_insert _ _), show _, from !ImpI (!ImpE this H1) theorem meta_thm1_right {Γ : set PropF} {α β : PropF} (H : Γ ⊢ ~β) : Γ ⊢ ~(α ∧ β) := have insert (α ∧ β) Γ ⊢ α ∧ β, from !Nax !mem_insert, have H1 : insert (α ∧ β) Γ ⊢ β, from !AndE₂ this, have insert (α ∧ β) Γ ⊢ ~β, from !weakening H _ (subset_insert _ _), show _, from !ImpI (!ImpE this H1) -- should be written using tactics. lemma eq_of_shift_insert {A : Type} {S : set A} (a b : A) : insert a (insert b S) = insert b (insert a S) := have H1 : insert a (insert b S) ⊆ insert b (insert a S), from λ x h, or.elim h (λ Hl, or.inr (or.inl Hl)) (λ Hr, or.elim Hr (λ Hlb, or.inl Hlb) (λ Hrb, or.inr (or.inr Hrb))), have insert b (insert a S) ⊆ insert a (insert b S), from λ x h, or.elim h (λ Hl, or.inr (or.inl Hl)) (λ Hr, or.elim Hr (λ Hlb, or.inl Hlb) (λ Hrb, or.inr (or.inr Hrb))), show _, from eq_of_subset_of_subset H1 this theorem meta_thm2 {Γ : set PropF} {α β : PropF} (H1 : Γ ⊢ ~α) (H2 : Γ ⊢ ~β) : Γ ⊢ ~(α ∨ β) := have H3 : insert (α ∨ β) Γ ⊢ α ∨ β, from !Nax !mem_insert, have (insert α Γ) ⊢ ⊥, from !deduction H1, have insert (α ∨ β) (insert α Γ) ⊢ ⊥, from !weakening this _ (subset_insert _ _), have H4 : insert α (insert (α ∨ β) Γ) ⊢ ⊥, by+ rewrite eq_of_shift_insert at this;exact this, have (insert β Γ) ⊢ ⊥, from !deduction H2, have insert (α ∨ β) (insert β Γ) ⊢ ⊥, from !weakening this _ (subset_insert _ _), have insert β (insert (α ∨ β) Γ) ⊢ ⊥, by+ rewrite eq_of_shift_insert at this;exact this, have (insert (α ∨ β) Γ) ⊢ ⊥, from !OrE H3 H4 this, show _, from !ImpI this theorem meta_thm3 {Γ : set PropF} {α β : PropF} (H1 : Γ ⊢ α) (H2 : Γ ⊢ ~β) : Γ ⊢ ~(α ⇒ β) := have H3 : insert (α ⇒ β) Γ ⊢ α ⇒ β, from !Nax !mem_insert, have H4 : insert (α ⇒ β) Γ ⊢ ~β, from !weakening H2 _ (subset_insert _ _), have insert (α ⇒ β) Γ ⊢ α, from !weakening H1 _ (subset_insert _ _), have insert (α ⇒ β) Γ ⊢ β, from !ImpE H3 this, have insert (α ⇒ β) Γ ⊢ ⊥, from !ImpE H4 this, show _, from !ImpI this theorem meta_thm4 {Γ : set PropF} {α β : PropF} (H : Γ ⊢ ~α) : Γ ⊢ α ⇒ β := have insert α Γ ⊢ ⊥, from !deduction H, have insert (~β) (insert α Γ) ⊢ ⊥, from !weakening this _ (subset_insert _ _), have insert α Γ ⊢ β, from !BotC this, show _, from !ImpI this theorem meta_thm5 {Γ : set PropF} {α β : PropF} (H : Γ ⊢ β) : Γ ⊢ α ⇒ β := have insert α Γ ⊢ β, from !weakening H _ (subset_insert _ _), show _, from !ImpI this lemma empty_sat (v : valuation) : Satisfies v ∅ := λ A H, absurd H (!not_mem_empty) lemma empty_model (α : PropF) (H : ∅ ⊨ α) : ∀ v, is_true (TrueQ v α) := λ v, H v (empty_sat v) lemma invalid_bot : ¬ (∅ ⊨ ⊥) := assume H, let v (a : PropVar) := tt in have TrueQ v ⊥ = ff, from rfl, have ¬ ff = tt, from bool.no_confusion, have ¬ TrueQ v ⊥ = tt, by+ simp, have H1 : ∃ v, ¬ is_true (TrueQ v ⊥), from exists.intro v this, have ¬ ∃ v, ¬ is_true (TrueQ v ⊥), from not_exists_not_of_forall (empty_model ⊥ H), show _, from this H1 theorem unprov_bot : ¬ (∅ ⊢ ⊥) := λ H, invalid_bot (Soundness ⊥ H) definition incon (Γ : set PropF) : Prop := ∃ α, (Γ ⊢ α) ∧ (Γ ⊢ ~ α) definition con (Γ : set PropF) : Prop := ¬ incon Γ theorem omni {Γ : set PropF} {α : PropF} (H : incon Γ) : Γ ⊢ α := obtain β Hb, from H, have H1 : Γ ⊢ ⊥, from !ImpE (and.right Hb) (and.left Hb), have Γ ⊆ insert (~α) Γ, from subset_insert (~α) Γ, have insert (~α) Γ ⊢ ⊥, from !weakening H1 (insert (~α) Γ) this, show _, from !BotC this theorem reverse_omni {Γ : set PropF} (H : ∀ α, Γ ⊢ α) : incon Γ := exists.intro ⊥ (and.intro (H ⊥) (H (~⊥))) theorem incon_of_prov_bot {Γ : set PropF} (H : Γ ⊢ ⊥) : incon Γ := have ∀ α, Γ ⊢ α, from λ α, !BotC (!weakening H _ (subset_insert _ _)), show _, from reverse_omni this theorem incon_union_of_prov {Γ : set PropF} {α : PropF} (H : Γ ⊢ α) : incon (insert (~α ) Γ) := have Γ ⊆ insert (~α) Γ, from subset_insert (~α) Γ, have H1 : insert (~α) Γ ⊢ α, from !weakening H (insert (~α) Γ) this, have (~α) ∈ insert (~α) Γ, from !mem_insert, have insert (~α) Γ ⊢ ~α, from !Nax this, show _, from exists.intro (α) (and.intro H1 this) theorem prov_of_incon_union {Γ : set PropF} {α : PropF} (H : incon (insert (~α) Γ)) : Γ ⊢ α := !BotC (omni H) definition Satisfiable (Γ : set PropF) := ∃ v, Satisfies v Γ -- classical theorem TFAE1 {Γ : set PropF} {τ : PropF} (H1 : ∀ {Γ}, con Γ → Satisfiable Γ) (H2 : Γ ⊨ τ) : Γ ⊢ τ := by_contradiction (suppose ¬ (Γ ⊢ τ), have con (insert (~τ) Γ), from not.mto prov_of_incon_union this, have Satisfiable (insert (~τ) Γ), from H1 this, obtain v Hv, from this, have Satisfies v Γ, from λ x, assume Hx, have Γ ⊆ insert (~τ) Γ, from subset_insert (~τ) Γ, have x ∈ insert (~τ) Γ, from this Hx, Hv x this, have TrueQ v τ = tt, from H2 v this, have (~τ) ∈ insert (~τ) Γ, from !mem_insert, have TrueQ v (~τ) = tt, from Hv (~τ) this, have bnot (TrueQ v τ) || ff = tt, from this, have bnot (TrueQ v τ) = tt, by+ simp, have TrueQ v τ = ff, from eq_ff_of_bnot_eq_tt this, have TrueQ v τ ≠ tt, by+ simp, show _, by+ simp) theorem TFAE2 {Γ : set PropF} (H1 : ∀ {Γ τ}, Γ ⊨ τ → Γ ⊢ τ) (H2 : con Γ): Satisfiable Γ := by_contradiction (suppose ¬ Satisfiable Γ, have ∀ v, ¬ Satisfies v Γ, from iff.mp forall_iff_not_exists this, have ∀ τ, Γ ⊢ τ, from take τ, have Γ ⊨ τ, from λ v, assume Hv, absurd Hv (this v), H1 this, have incon Γ, from reverse_omni this, H2 this) -- definition max_con (Γ : set PropF) := con Γ ∧ ∀ α, α ∉ Γ → incon (insert α Γ) noncomputable theory definition enum (Γ : set PropF) (n : nat) : set PropF := nat.rec_on n Γ (λ pred enum', if con (insert (# pred) enum') then insert (# pred) enum' else insert (~(# pred)) enum') lemma con_insert_neg_of_incon {Γ : set PropF} {α : PropF} (H1 : con Γ) (H2 : incon (insert α Γ)) : con (insert (~α) Γ) := assume Hincon, have H3 : Γ ⊢ α, from prov_of_incon_union Hincon, have Γ ⊢ ~α, from !ImpI (omni H2), have Γ ⊢ ⊥, from !ImpE this H3, have incon Γ, from incon_of_prov_bot this, show _, from H1 this theorem con_enum {Γ : set PropF} (H : con Γ) (n : nat) : con (enum Γ n) := nat.rec_on n H (λ a ih, by_cases (suppose con (insert (# a) (enum Γ a)), have enum Γ (succ a) = insert (# a) (enum Γ a), from if_pos this, show _, by+ simp) (assume Hneg, have incon : incon (insert (# a) (enum Γ a)), from not_not_elim Hneg, have enum Γ (succ a) = insert (~(# a)) (enum Γ a), from if_neg Hneg, have con (insert (~(# a)) (enum Γ a)), from con_insert_neg_of_incon ih incon, show _, by+ simp)) theorem succ_enum {Γ : set PropF} {n : ℕ} : enum Γ n ⊆ enum Γ (succ n) := nat.rec_on n (by_cases (suppose con (insert (# 0) (enum Γ 0)), have enum Γ (succ 0) = insert (# 0) (enum Γ 0), from if_pos this, have enum Γ 0 ⊆ insert (# 0) (enum Γ 0), from subset_insert _ _, show _, by+ simp) (assume Hneg, have enum Γ (succ 0) = insert (~(# 0)) (enum Γ 0), from if_neg Hneg, have enum Γ 0 ⊆ insert (~(# 0)) (enum Γ 0), from subset_insert _ _, show _, by+ simp)) (λ a ih, by_cases (suppose con (insert (# (succ a)) (enum Γ (succ a))), have enum Γ (succ (succ a)) = insert (# (succ a)) (enum Γ (succ a)), from if_pos this, have enum Γ (succ a) ⊆ insert (# (succ a)) (enum Γ (succ a)), from subset_insert _ _, show _, by+ simp) (assume Hneg, have enum Γ (succ (succ a)) = insert (~(# (succ a))) (enum Γ (succ a)), from if_neg Hneg, have enum Γ (succ a) ⊆ insert (~(# (succ a))) (enum Γ (succ a)), from subset_insert _ _, show _, by+ simp)) -- Can be strengthened theorem increasing_enum {Γ : set PropF} {n m : ℕ} : n ≤ m → enum Γ n ⊆ enum Γ m := nat.rec_on m (λ H, have n = 0, from eq_zero_of_le_zero H, have enum Γ 0 ⊆ enum Γ 0, from subset.refl _, show _, by+ simp) (λ a ih H, by_cases (suppose n = succ a, have enum Γ (succ a) ⊆ enum Γ (succ a), from subset.refl _, show _, by+ simp) (assume Hneg, have n < succ a, from lt_of_le_of_ne H Hneg, have n ≤ a, from le_of_lt_succ this, have H1 : enum Γ n ⊆ enum Γ a, from ih this, have enum Γ a ⊆ enum Γ (succ a), from succ_enum, show _, from subset.trans H1 this)) section parameter Γ : set PropF parameter Hcon : con Γ definition con_comp_ext : set PropF := {x : PropF | ∃ i, x ∈ enum Γ i} private definition index (α : PropF) : ℕ := if cond : α ∈ con_comp_ext then some cond else 0 -- Maybe we should show further that for any finite set S ⊆ con_com_ext, ∀ s ∈ S, s ∈ enum Γ (max (index ' S)). theorem mem_index (α : PropF) (H : α ∈ con_comp_ext) : α ∈ enum Γ (index α) := have index α = some H, from if_pos H, have α ∈ enum Γ (some H), from some_spec H, show _, by+ simp theorem con_con_comp_ext : con con_comp_ext := assume H, obtain s hs, from finite_proof _ ⊥ (!omni H), have fins : finite s, from and.left hs, let is : set ℕ := index ' s in have s ≠ ∅, from λ H, have ∅ ⊢ ⊥, by+ simp, unprov_bot this, have nemp : is ≠ ∅, from !image_of_ne_empty this, have finite is, from @finite_image _ _ _ _ fins, obtain n hn, from @gnp is this nemp, have pb : s ⊢ ⊥, from and.right (and.right hs), have ∀ a, a ∈ s → a ∈ enum Γ n, from λ a hin, have index a ∈ is, from mem_image hin rfl, have index a ≤ n, from and.right hn (index a) this, have sub : enum Γ (index a) ⊆ enum Γ n, from increasing_enum this, have a ∈ con_comp_ext, from (and.left (and.right hs)) _ hin, have a ∈ enum Γ (index a), from mem_index _ this, sub this, have enum Γ n ⊢ ⊥, from !weakening pb _ this, have incon (enum Γ n), from incon_of_prov_bot this, show _, from (con_enum Hcon n) this lemma unprov_bot_con_comp : ¬ (con_comp_ext ⊢ ⊥) := assume H, con_con_comp_ext (incon_of_prov_bot H) definition max_con_ext : set PropF := {α : PropF | con_comp_ext ⊢ α} theorem sub_con_comp_ext : Γ ⊆ con_comp_ext := λ x h, have Γ = enum Γ 0, from rfl, have x ∈ enum Γ 0, by+ rewrite this at h;exact h, show _, from exists.intro 0 this theorem sub_max_con_ext : Γ ⊆ max_con_ext := λ x h, have x ∈ con_comp_ext, from sub_con_comp_ext h, show _, from !Nax this -- Induction is not necessary. Can be proved by cases. theorem atomic_comp (P : PropVar) : (con_comp_ext ⊢ # P) ∨ (con_comp_ext ⊢ ~(# P)) := nat.rec_on P (or.elim (em (con (insert (# 0) Γ))) (λ Hl, have (# 0) ∈ insert (# 0) Γ, from mem_insert _ _, have enum Γ 1 = insert (# 0) Γ, from if_pos Hl, have (# 0) ∈ enum Γ 1, by+ simp, have (# 0) ∈ con_comp_ext, from exists.intro 1 this, show _, from or.inl (!Nax this)) (λ Hr, have (~(# 0)) ∈ insert (~(# 0)) Γ, from mem_insert _ _, have enum Γ 1 = insert (~(# 0)) Γ, from if_neg Hr, have (~(# 0)) ∈ enum Γ 1, by+ simp, have (~(# 0)) ∈ con_comp_ext, from exists.intro 1 this, show _, from or.inr (!Nax this))) (λ a ih, or.elim (em (con (insert (# (succ a)) (enum Γ (succ a))))) (λ Hl, have (# (succ a)) ∈ insert (# (succ a)) (enum Γ (succ a)), from mem_insert _ _, have enum Γ (succ (succ a)) = insert (# (succ a)) (enum Γ (succ a)), from if_pos Hl, have (# (succ a)) ∈ enum Γ (succ (succ a)), by+ simp, have (# (succ a)) ∈ con_comp_ext, from exists.intro (succ (succ a)) this, show _, from or.inl (!Nax this) ) (λ Hr, have (~(# (succ a))) ∈ insert (~(# (succ a))) (enum Γ (succ a)), from mem_insert _ _, have enum Γ (succ (succ a)) = insert (~(# (succ a))) (enum Γ (succ a)), from if_neg Hr, have (~(# (succ a))) ∈ enum Γ (succ (succ a)), by+ simp, have (~(# (succ a))) ∈ con_comp_ext, from exists.intro (succ (succ a)) this, show _, from or.inr (!Nax this))) theorem comp_con_comp_ext (α : PropF) : (con_comp_ext ⊢ α) ∨ (con_comp_ext ⊢ ~α) := PropF.rec_on α (λ a, atomic_comp a) (or.inr (!meta_thm0)) (λ a b iha ihb, or.elim iha (λ Hl, or.elim ihb (λ Hlb, or.inl (!AndI Hl Hlb)) (λ Hrb, or.inr (meta_thm1_right Hrb))) (λ Hr, or.inr (meta_thm1_left Hr))) (λ a b iha ihb, or.elim iha (λ Hl, or.inl (!OrI₁ Hl)) (λ Hr, or.elim ihb (λ Hlb, or.inl (!OrI₂ Hlb)) (λ Hrb, or.inr (meta_thm2 Hr Hrb)))) (λ a b iha ihb, or.elim iha (λ Hl, or.elim ihb (λ Hlb, or.inl (meta_thm5 Hlb)) (λ Hrb, or.inr (meta_thm3 Hl Hrb))) (λ Hr, or.inl (meta_thm4 Hr))) lemma mutual_exclusion (α : PropF) (H : con_comp_ext ⊢ ~α) : ¬ (con_comp_ext ⊢ α) := assume Hneg, have con_comp_ext ⊢ ⊥, from !ImpE H Hneg, have incon con_comp_ext, from incon_of_prov_bot this, show _, from con_con_comp_ext this lemma mutual_exclusion' (α : PropF) (H : ¬ (con_comp_ext ⊢ α)) : con_comp_ext ⊢ (~α) := or.elim (comp_con_comp_ext α) (λ Hl, absurd Hl H) (λ Hr, Hr) private definition v (P : PropVar) : bool := if # P ∈ max_con_ext then tt else ff theorem ne_ff_of_eq_tt {a : bool} (H : a = tt) : a ≠ ff := by+ rewrite H;apply bool.no_confusion theorem ne_tt_of_eq_ff {a : bool} (H : a = ff) : a ≠ tt := by+ rewrite H;apply bool.no_confusion theorem sat_v {α : PropF} : α ∈ max_con_ext ↔ is_true (TrueQ v α) := PropF.rec_on α (λ a, have Hl : # a ∈ max_con_ext → is_true (TrueQ v (# a)), from λ h, have TrueQ v (# a) = v a, from rfl, have v a = tt, from if_pos h, show _, by+ simp, have is_true (TrueQ v (# a)) → # a ∈ max_con_ext, from λ h, by_contradiction (assume Hneg, have v a = ff, from if_neg Hneg, have v a ≠ tt, from ne_tt_of_eq_ff this, this h), show _, from iff.intro Hl this) (have Hl : ⊥ ∈ max_con_ext → is_true (TrueQ v ⊥), from λ h, absurd h unprov_bot_con_comp, have is_true (TrueQ v ⊥) → ⊥ ∈ max_con_ext, from λ h, have TrueQ v ⊥ = ff, from rfl, have TrueQ v ⊥ ≠ tt, from ne_tt_of_eq_ff this, show _, from absurd h this, show _, from iff.intro Hl this) (λ a b iha ihb, have Hl : (a ∧ b) ∈ max_con_ext → is_true (TrueQ v (a ∧ b)), from λ h, have con_comp_ext ⊢ a, from !AndE₁ h, have t1 : TrueQ v a = tt, from iff.elim_left iha this, have con_comp_ext ⊢ b, from !AndE₂ h, have t2 : TrueQ v b = tt, from iff.elim_left ihb this, have TrueQ v (a ∧ b) = TrueQ v a && TrueQ v b, from rfl, show _, by+ simp, have is_true (TrueQ v (a ∧ b)) → (a ∧ b) ∈ max_con_ext, from λ h, have TrueQ v (a ∧ b) = TrueQ v a && TrueQ v b, from rfl, have eq : tt = TrueQ v a && TrueQ v b, by+ simp, have is_true (TrueQ v a), from band_elim_left (eq.symm eq), have Ha : a ∈ max_con_ext, from iff.elim_right iha this, have is_true (TrueQ v b), from band_elim_right (eq.symm eq), have Hb : b ∈ max_con_ext, from iff.elim_right ihb this, show _, from !AndI Ha Hb, show _, from iff.intro Hl this) (λ a b iha ihb, have Hl : (a ∨ b) ∈ max_con_ext → is_true (TrueQ v (a ∨ b)), from λ h, or.elim (comp_con_comp_ext a) (λ Hl, have TrueQ v a = tt, from iff.elim_left iha Hl, have TrueQ v (a ∨ b) = TrueQ v a || TrueQ v b, from rfl, show _, by+ simp) (λ Hr, or.elim (comp_con_comp_ext b) (λ Hlb, have TrueQ v b = tt, from iff.elim_left ihb Hlb, have TrueQ v (a ∨ b) = TrueQ v a || TrueQ v b, from rfl, show _, by+ simp) (λ Hrb, have con_comp_ext ⊢ ~(a ∨ b), from meta_thm2 Hr Hrb, have incon con_comp_ext, from incon_of_prov_bot (!ImpE this h), show _, from absurd this con_con_comp_ext)), have is_true (TrueQ v (a ∨ b)) → (a ∨ b) ∈ max_con_ext, from λ h, have TrueQ v a = tt ∨ TrueQ v b = tt, from or_of_bor_eq h, or.elim this (λ Hl, have a ∈ max_con_ext, from iff.elim_right iha Hl, !OrI₁ this) (λ Hr, have b ∈ max_con_ext, from iff.elim_right ihb Hr, !OrI₂ this), show _, from iff.intro Hl this) (λ a b iha ihb, have Hl : (a ⇒ b) ∈ max_con_ext → is_true (TrueQ v (a ⇒ b)), from λ h, or.elim (comp_con_comp_ext a) (λ Hl, have b ∈ max_con_ext, from !ImpE h Hl, have TrueQ v b = tt, from iff.elim_left ihb this, have TrueQ v (a ⇒ b) = bnot (TrueQ v a) || TrueQ v b, from rfl, have TrueQ v (a ⇒ b) = bnot (TrueQ v a) || tt, by+ simp, show _, by+ simp) (λ Hr, have Hneg : ¬ (con_comp_ext ⊢ a), from !mutual_exclusion Hr, have ¬ (con_comp_ext ⊢ a) ↔ TrueQ v a ≠ tt, from not_iff_not iha, have TrueQ v a ≠ tt, from iff.elim_left this Hneg, have TrueQ v a = ff, from eq_ff_of_ne_tt this, have bnot (TrueQ v a) = tt, by+ simp, have TrueQ v (a ⇒ b) = bnot (TrueQ v a) || TrueQ v b, from rfl, have TrueQ v (a ⇒ b) = tt || TrueQ v b, by+ simp, show _, by+ simp), have is_true (TrueQ v (a ⇒ b)) → (a ⇒ b) ∈ max_con_ext, from λ h, have bnot (TrueQ v a) = tt ∨ TrueQ v b = tt, from or_of_bor_eq h, or.elim this (λ Hl, have TrueQ v a = ff, from eq_ff_of_bnot_eq_tt Hl, have neq : TrueQ v a ≠ tt, from ne_tt_of_eq_ff this, have ¬ (con_comp_ext ⊢ a) ↔ TrueQ v a ≠ tt, from not_iff_not iha, have ¬ (con_comp_ext ⊢ a), from iff.elim_right this neq, have con_comp_ext ⊢ ~a, from !mutual_exclusion' this, show _, from meta_thm4 this) (λ Hr, have con_comp_ext ⊢ b, from iff.elim_right ihb Hr, show _, from meta_thm5 this), show _, from iff.intro Hl this) theorem sat_Gamma : Satisfiable Γ:= have ∀ α, α ∈ Γ → is_true (TrueQ v α), from λ α h, have α ∈ max_con_ext, from sub_max_con_ext h, show _, from iff.elim_left sat_v this, show _, from exists.intro v this end theorem PL_completeness {Γ : set PropF} {τ : PropF} (H : Γ ⊨ τ) : Γ ⊢ τ := show _, from TFAE1 sat_Gamma H theorem PL_soundness {Γ : set PropF} {τ : PropF} (H : Γ ⊢ τ) : Γ ⊨ τ := show _, from Soundness_general τ Γ H theorem con_of_sat {Γ : set PropF} (H : Satisfiable Γ) : con Γ := obtain v hv, from H, have unprov : ¬ (Γ ⊢ ⊥), from assume Hneg, have Γ ⊨ ⊥, from PL_soundness Hneg, have eq : is_true (TrueQ v ⊥), from this v hv, have TrueQ v ⊥ = ff, from rfl, have ¬ TrueQ v ⊥ = tt, from ne_tt_of_eq_ff this, show _, from this eq, assume Hneg, have Γ ⊢ ⊥, from omni Hneg, show _, from unprov this theorem PL_compactness {Γ : set PropF} (H : ∀ s, finite s → s ⊆ Γ → Satisfiable s) : Satisfiable Γ := have con_fin : ∀ s, finite s → s ⊆ Γ → con s, from λ s fin sub, show _, from con_of_sat (H s fin sub), have con Γ, from assume Hneg, have Γ ⊢ ⊥, from omni Hneg, have ∃ s, finite s ∧ s ⊆ Γ ∧ (s ⊢ ⊥),from !finite_proof this, obtain s h, from this, have Hcon : con s, from con_fin s (and.left h) (and.left (and.right h)), have incon s, from incon_of_prov_bot (and.right (and.right h)), show _, from Hcon this, show _, from sat_Gamma Γ this end PropF
cad5e2b434f7ac7410249f526678e87f47899db7
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/ppbeta.lean
f1ee151890f3fd4c11ed97faff7ed235551648e0
[ "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
286
lean
import data.int open [coercion] [class] int open [coercion] nat definition lt1 (a b : int) := int.le (int.add a 1) b infix `<` := lt1 infixl `+` := int.add theorem lt_add_succ2 (a : int) (n : nat) : a < a + nat.succ n := int.le.intro (show a + 1 + n = a + nat.succ n, from sorry)
d9c3888026d2897fc2236bb908567fb2a16dd6b8
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/limits/creates.lean
f2a49827b2e43cab2e7d939ab900d676647010c1
[ "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
25,972
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 w' w v₁ v₂ v₃ u₁ u₂ u₃ variables {C : Type u₁} [category.{v₁} C] section creates variables {D : Type u₂} [category.{v₂} D] variables {J : Type w} [category.{w'} 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 w) [category.{w'} 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 `J`. -/ @[nolint check_univs] -- This should be used with explicit universe variables. class creates_limits_of_size (F : C ⥤ D) := (creates_limits_of_shape : Π {J : Type w} [category.{w'} J], creates_limits_of_shape J F . tactic.apply_instance) /-- `F` creates small limits if it creates limits of shape `J` for any small `J`. -/ abbreviation creates_limits (F : C ⥤ D) := creates_limits_of_size.{v₂ v₂} F /-- 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 w) [category.{w'} 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`. -/ @[nolint check_univs] -- This should be used with explicit universe variables. class creates_colimits_of_size (F : C ⥤ D) := (creates_colimits_of_shape : Π {J : Type w} [category.{w'} J], creates_colimits_of_shape J F . tactic.apply_instance) /-- `F` creates small colimits if it creates colimits of shape `J` for any small `J`. -/ abbreviation creates_colimits (F : C ⥤ D) := creates_colimits_of_size.{v₂ v₂} F attribute [instance, priority 100] -- see Note [lower instance priority] creates_limits_of_shape.creates_limit creates_limits_of_size.creates_limits_of_shape creates_colimits_of_shape.creates_colimit creates_colimits_of_size.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_of_size.{w w'} D] [creates_limits_of_size.{w w'} F] : has_limits_of_size.{w w'} 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_of_size.{w w'} D] [creates_colimits_of_size.{w w'} F] : has_colimits_of_size.{w w'} 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_of_size.{w w'} F] : reflects_limits_of_size.{w w'} 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_of_size.{w w'} F] : reflects_colimits_of_size.{w w'} 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 := {} /-- `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_of_size.{w w'} F] [has_limits_of_size.{w w'} D] : preserves_limits_of_size.{w w'} 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 } } /-- When `F` is fully faithful, and `has_colimit (K ⋙ F)`, to show that `F` creates the colimit for `K` it suffices to exhibit a lift of the chosen colimit cocone for `K ⋙ F`. -/ -- Notice however that even if the isomorphism is `iso.refl _`, -- this construction will insert additional identity morphisms in the cocone maps, -- so the constructed colimits may not be ideal, definitionally. def creates_colimit_of_fully_faithful_of_lift {K : J ⥤ C} {F : C ⥤ D} [full F] [faithful F] [has_colimit (K ⋙ F)] (c : cocone K) (i : F.map_cocone c ≅ colimit.cocone (K ⋙ F)) : creates_colimit K F := creates_colimit_of_reflects_iso (λ c' t, { lifted_cocone := c, valid_lift := i.trans (is_colimit.unique_up_to_iso (colimit.is_colimit _) t), makes_colimit := is_colimit.of_faithful F (is_colimit.of_iso_colimit (colimit.is_colimit _) i.symm) (λ s, F.preimage _) (λ s, F.image_preimage _) }) /-- When `F` is fully faithful, and `has_colimit (K ⋙ F)`, to show that `F` creates the colimit for `K` it suffices to show that the chosen colimit 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 cocone maps, -- so the constructed colimits may not be ideal, definitionally. def creates_colimit_of_fully_faithful_of_iso {K : J ⥤ C} {F : C ⥤ D} [full F] [faithful F] [has_colimit (K ⋙ F)] (X : C) (i : F.obj X ≅ colimit (K ⋙ F)) : creates_colimit K F := creates_colimit_of_fully_faithful_of_lift ({ X := X, ι := { app := λ j, F.preimage (colimit.ι (K ⋙ F) j ≫ i.inv : _), naturality' := λ Y Z f, F.map_injective (by { erw category.comp_id, simp only [functor.map_comp, functor.image_preimage], erw colimit.w_assoc (K ⋙ F) }) }} : cocone K) (by { fapply cocones.ext, exact i, tidy, }) /-- `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 := {} /-- `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_of_size.{w w'} F] [has_colimits_of_size.{w w'} D] : preserves_colimits_of_size.{w w'} F := {} /-- Transfer creation of limits along a natural isomorphism in the diagram. -/ def creates_limit_of_iso_diagram {K₁ K₂ : J ⥤ C} (F : C ⥤ D) (h : K₁ ≅ K₂) [creates_limit K₁ F] : creates_limit K₂ F := { lifts := λ c t, let t' := (is_limit.postcompose_inv_equiv (iso_whisker_right h F : _) c).symm t in { lifted_cone := (cones.postcompose h.hom).obj (lift_limit t'), valid_lift := F.map_cone_postcompose ≪≫ (cones.postcompose (iso_whisker_right h F).hom).map_iso (lifted_limit_maps_to_original t') ≪≫ cones.ext (iso.refl _) (λ j, by { dsimp, rw [category.assoc, ←F.map_comp], simp }) } ..reflects_limit_of_iso_diagram F h } /-- 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_of_size.{w w'} F] : creates_limits_of_size.{w w'} G := { creates_limits_of_shape := λ J 𝒥₁, by exactI creates_limits_of_shape_of_nat_iso h } /-- Transfer creation of colimits along a natural isomorphism in the diagram. -/ def creates_colimit_of_iso_diagram {K₁ K₂ : J ⥤ C} (F : C ⥤ D) (h : K₁ ≅ K₂) [creates_colimit K₁ F] : creates_colimit K₂ F := { lifts := λ c t, let t' := (is_colimit.precompose_hom_equiv (iso_whisker_right h F : _) c).symm t in { lifted_cocone := (cocones.precompose h.inv).obj (lift_colimit t'), valid_lift := F.map_cocone_precompose ≪≫ (cocones.precompose (iso_whisker_right h F).inv).map_iso (lifted_colimit_maps_to_original t') ≪≫ cocones.ext (iso.refl _) (λ j, by { dsimp, rw ←F.map_comp_assoc, simp }) }, ..reflects_colimit_of_iso_diagram F 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_of_size.{w w'} F] : creates_colimits_of_size.{w w'} 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_of_size.{w w'} (𝟭 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_of_size.{w w'} (𝟭 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_of_size.{w w'} F] [creates_limits_of_size.{w w'} G] : creates_limits_of_size.{w w'} (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_of_size.{w w'} F] [creates_colimits_of_size.{w w'} G] : creates_colimits_of_size.{w w'} (F ⋙ G) := { creates_colimits_of_shape := infer_instance } end comp end creates end category_theory
af956ac400d756a7871174b6780445818f088650
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/stage0/src/Lean/Exception.lean
c1c502420af41d0d03f88df0b7e5b0c7c5c0eedc
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,713
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.Message import Lean.InternalExceptionId import Lean.Data.Options import Lean.Util.MonadCache namespace Lean /- Exception type used in most Lean monads -/ inductive Exception where | error (ref : Syntax) (msg : MessageData) | internal (id : InternalExceptionId) (extra : KVMap := {}) def Exception.toMessageData : Exception → MessageData | Exception.error _ msg => msg | Exception.internal id _ => id.toString def Exception.getRef : Exception → Syntax | Exception.error ref _ => ref | Exception.internal _ _ => Syntax.missing instance : Inhabited Exception := ⟨Exception.error arbitrary arbitrary⟩ /- Similar to `AddMessageContext`, but for error messages. The default instance just uses `AddMessageContext`. In error messages, we may want to provide additional information (e.g., macro expansion stack), and refine the `(ref : Syntax)`. -/ class AddErrorMessageContext (m : Type → Type) where add : Syntax → MessageData → m (Syntax × MessageData) instance (m : Type → Type) [AddMessageContext m] [Monad m] : AddErrorMessageContext m where add ref msg := do let msg ← addMessageContext msg pure (ref, msg) class abbrev MonadError (m : Type → Type) := MonadExceptOf Exception m MonadRef m AddErrorMessageContext m section Methods def throwError [Monad m] [MonadError m] (msg : MessageData) : m α := do let ref ← getRef let (ref, msg) ← AddErrorMessageContext.add ref msg throw $ Exception.error ref msg def throwUnknownConstant [Monad m] [MonadError m] (constName : Name) : m α := throwError m!"unknown constant '{mkConst constName}'" def throwErrorAt [Monad m] [MonadError m] (ref : Syntax) (msg : MessageData) : m α := do withRef ref <| throwError msg def ofExcept [Monad m] [MonadError m] [ToString ε] (x : Except ε α) : m α := match x with | Except.ok a => pure a | Except.error e => throwError $ toString e def throwKernelException [Monad m] [MonadError m] [MonadOptions m] (ex : KernelException) : m α := do throwError <| ex.toMessageData (← getOptions) end Methods class MonadRecDepth (m : Type → Type) where withRecDepth {α} : Nat → m α → m α getRecDepth : m Nat getMaxRecDepth : m Nat instance [Monad m] [MonadRecDepth m] : MonadRecDepth (ReaderT ρ m) where withRecDepth d x := fun ctx => MonadRecDepth.withRecDepth d (x ctx) getRecDepth := fun _ => MonadRecDepth.getRecDepth getMaxRecDepth := fun _ => MonadRecDepth.getMaxRecDepth instance [Monad m] [MonadRecDepth m] : MonadRecDepth (StateRefT' ω σ m) := inferInstanceAs (MonadRecDepth (ReaderT _ _)) instance [BEq α] [Hashable α] [Monad m] [STWorld ω m] [MonadRecDepth m] : MonadRecDepth (MonadCacheT α β m) := inferInstanceAs (MonadRecDepth (StateRefT' _ _ _)) @[inline] def withIncRecDepth [Monad m] [MonadError m] [MonadRecDepth m] (x : m α) : m α := do let curr ← MonadRecDepth.getRecDepth let max ← MonadRecDepth.getMaxRecDepth if curr == max then throwError maxRecDepthErrorMessage MonadRecDepth.withRecDepth (curr+1) x syntax "throwError! " (interpolatedStr(term) <|> term) : term syntax "throwErrorAt! " term:max (interpolatedStr(term) <|> term) : term macro_rules | `(throwError! $msg) => if msg.getKind == interpolatedStrKind then `(throwError (m! $msg)) else `(throwError $msg) macro_rules | `(throwErrorAt! $ref $msg) => if msg.getKind == interpolatedStrKind then `(throwErrorAt $ref (m! $msg)) else `(throwErrorAt $ref $msg) end Lean
20b30198c0e35b7ae8fdfec182548d559547ab9b
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/data/padics/padic_numbers.lean
9d1bcd2c337784bdc0a9502a020b04c288c98830
[ "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
37,645
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import data.padics.padic_norm import analysis.normed_space.basic /-! # p-adic numbers This file defines the p-adic numbers (rationals) `ℚ_p` as the completion of `ℚ` with respect to the p-adic norm. We show that the p-adic norm on ℚ extends to `ℚ_p`, that `ℚ` is embedded in `ℚ_p`, and that `ℚ_p` is Cauchy complete. ## Important definitions * `padic` : the type of p-adic numbers * `padic_norm_e` : the rational valued p-adic norm on `ℚ_p` ## Notation We introduce the notation `ℚ_[p]` for the p-adic numbers. ## Implementation notes Much, but not all, of this file assumes that `p` is prime. This assumption is inferred automatically by taking `[fact (prime p)]` as a type class argument. We use the same concrete Cauchy sequence construction that is used to construct ℝ. `ℚ_p` inherits a field structure from this construction. The extension of the norm on ℚ to `ℚ_p` is *not* analogous to extending the absolute value to ℝ, and hence the proof that `ℚ_p` is complete is different from the proof that ℝ is complete. A small special-purpose simplification tactic, `padic_index_simp`, is used to manipulate sequence indices in the proof that the norm extends. `padic_norm_e` is the rational-valued p-adic norm on `ℚ_p`. To instantiate `ℚ_p` as a normed field, we must cast this into a ℝ-valued norm. The `ℝ`-valued norm, using notation `∥ ∥` from normed spaces, is the canonical representation of this norm. `simp` prefers `padic_norm` to `padic_norm_e` when possible. Since `padic_norm_e` and `∥ ∥` have different types, `simp` does not rewrite one to the other. Coercions from `ℚ` to `ℚ_p` are set up to work with the `norm_cast` tactic. ## References * [F. Q. Gouêva, *p-adic numbers*][gouvea1997] * [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019] * <https://en.wikipedia.org/wiki/P-adic_number> ## Tags p-adic, p adic, padic, norm, valuation, cauchy, completion, p-adic completion -/ noncomputable theory open_locale classical open nat multiplicity padic_norm cau_seq cau_seq.completion metric /-- The type of Cauchy sequences of rationals with respect to the p-adic norm. -/ @[reducible] def padic_seq (p : ℕ) [fact p.prime] := cau_seq _ (padic_norm p) namespace padic_seq section variables {p : ℕ} [fact p.prime] /-- The p-adic norm of the entries of a nonzero Cauchy sequence of rationals is eventually constant. -/ lemma stationary {f : cau_seq ℚ (padic_norm p)} (hf : ¬ f ≈ 0) : ∃ N, ∀ m n, N ≤ m → N ≤ n → padic_norm p (f n) = padic_norm p (f m) := have ∃ ε > 0, ∃ N1, ∀ j ≥ N1, ε ≤ padic_norm p (f j), from cau_seq.abv_pos_of_not_lim_zero $ not_lim_zero_of_not_congr_zero hf, let ⟨ε, hε, N1, hN1⟩ := this, ⟨N2, hN2⟩ := cau_seq.cauchy₂ f hε in ⟨ max N1 N2, λ n m hn hm, have padic_norm p (f n - f m) < ε, from hN2 _ _ (max_le_iff.1 hn).2 (max_le_iff.1 hm).2, have padic_norm p (f n - f m) < padic_norm p (f n), from lt_of_lt_of_le this $ hN1 _ (max_le_iff.1 hn).1, have padic_norm p (f n - f m) < max (padic_norm p (f n)) (padic_norm p (f m)), from lt_max_iff.2 (or.inl this), begin by_contradiction hne, rw ←padic_norm.neg p (f m) at hne, have hnam := add_eq_max_of_ne p hne, rw [padic_norm.neg, max_comm] at hnam, rw [←hnam, sub_eq_add_neg, add_comm] at this, apply _root_.lt_irrefl _ this end ⟩ /-- For all n ≥ stationary_point f hf, the p-adic norm of f n is the same. -/ def stationary_point {f : padic_seq p} (hf : ¬ f ≈ 0) : ℕ := classical.some $ stationary hf lemma stationary_point_spec {f : padic_seq p} (hf : ¬ f ≈ 0) : ∀ {m n}, stationary_point hf ≤ m → stationary_point hf ≤ n → padic_norm p (f n) = padic_norm p (f m) := classical.some_spec $ stationary hf /-- Since the norm of the entries of a Cauchy sequence is eventually stationary, we can lift the norm to sequences. -/ def norm (f : padic_seq p) : ℚ := if hf : f ≈ 0 then 0 else padic_norm p (f (stationary_point hf)) lemma norm_zero_iff (f : padic_seq p) : f.norm = 0 ↔ f ≈ 0 := begin constructor, { intro h, by_contradiction hf, unfold norm at h, split_ifs at h, apply hf, intros ε hε, existsi stationary_point hf, intros j hj, have heq := stationary_point_spec hf (le_refl _) hj, simpa [h, heq] }, { intro h, simp [norm, h] } end end section embedding open cau_seq variables {p : ℕ} [fact p.prime] lemma equiv_zero_of_val_eq_of_equiv_zero {f g : padic_seq p} (h : ∀ k, padic_norm p (f k) = padic_norm p (g k)) (hf : f ≈ 0) : g ≈ 0 := λ ε hε, let ⟨i, hi⟩ := hf _ hε in ⟨i, λ j hj, by simpa [h] using hi _ hj⟩ lemma norm_nonzero_of_not_equiv_zero {f : padic_seq p} (hf : ¬ f ≈ 0) : f.norm ≠ 0 := hf ∘ f.norm_zero_iff.1 lemma norm_eq_norm_app_of_nonzero {f : padic_seq p} (hf : ¬ f ≈ 0) : ∃ k, f.norm = padic_norm p k ∧ k ≠ 0 := have heq : f.norm = padic_norm p (f $ stationary_point hf), by simp [norm, hf], ⟨f $ stationary_point hf, heq, λ h, norm_nonzero_of_not_equiv_zero hf (by simpa [h] using heq)⟩ lemma not_lim_zero_const_of_nonzero {q : ℚ} (hq : q ≠ 0) : ¬ lim_zero (const (padic_norm p) q) := λ h', hq $ const_lim_zero.1 h' lemma not_equiv_zero_const_of_nonzero {q : ℚ} (hq : q ≠ 0) : ¬ (const (padic_norm p) q) ≈ 0 := λ h : lim_zero (const (padic_norm p) q - 0), not_lim_zero_const_of_nonzero hq $ by simpa using h lemma norm_nonneg (f : padic_seq p) : 0 ≤ f.norm := if hf : f ≈ 0 then by simp [hf, norm] else by simp [norm, hf, padic_norm.nonneg] /-- An auxiliary lemma for manipulating sequence indices. -/ lemma lift_index_left_left {f : padic_seq p} (hf : ¬ f ≈ 0) (v2 v3 : ℕ) : padic_norm p (f (stationary_point hf)) = padic_norm p (f (max (stationary_point hf) (max v2 v3))) := let i := max (stationary_point hf) (max v2 v3) in begin apply stationary_point_spec hf, { apply le_max_left }, { apply le_refl } end /-- An auxiliary lemma for manipulating sequence indices. -/ lemma lift_index_left {f : padic_seq p} (hf : ¬ f ≈ 0) (v1 v3 : ℕ) : padic_norm p (f (stationary_point hf)) = padic_norm p (f (max v1 (max (stationary_point hf) v3))) := let i := max v1 (max (stationary_point hf) v3) in begin apply stationary_point_spec hf, { apply le_trans, { apply le_max_left _ v3 }, { apply le_max_right } }, { apply le_refl } end /-- An auxiliary lemma for manipulating sequence indices. -/ lemma lift_index_right {f : padic_seq p} (hf : ¬ f ≈ 0) (v1 v2 : ℕ) : padic_norm p (f (stationary_point hf)) = padic_norm p (f (max v1 (max v2 (stationary_point hf)))) := let i := max v1 (max v2 (stationary_point hf)) in begin apply stationary_point_spec hf, { apply le_trans, { apply le_max_right v2 }, { apply le_max_right } }, { apply le_refl } end end embedding section valuation open cau_seq variables {p : ℕ} [fact p.prime] /-! ### Valuation on `padic_seq` -/ /-- The `p`-adic valuation on `ℚ` lifts to `padic_seq p`. `valuation f` is defined to be the valuation of the (`ℚ`-valued) stationary point of `f`. -/ def valuation (f : padic_seq p) : ℤ := if hf : f ≈ 0 then 0 else padic_val_rat p (f (stationary_point hf)) lemma norm_eq_pow_val {f : padic_seq p} (hf : ¬ f ≈ 0) : f.norm = p^(-f.valuation : ℤ) := begin rw [norm, valuation, dif_neg hf, dif_neg hf, padic_norm, if_neg], intro H, apply cau_seq.not_lim_zero_of_not_congr_zero hf, intros ε hε, use (stationary_point hf), intros n hn, rw stationary_point_spec hf (le_refl _) hn, simpa [H] using hε, end lemma val_eq_iff_norm_eq {f g : padic_seq p} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) : f.valuation = g.valuation ↔ f.norm = g.norm := begin rw [norm_eq_pow_val hf, norm_eq_pow_val hg, ← neg_inj, fpow_inj], { exact_mod_cast nat.prime.pos ‹_› }, { exact_mod_cast nat.prime.ne_one ‹_› }, end end valuation end padic_seq section open padic_seq private meta def index_simp_core (hh hf hg : expr) (at_ : interactive.loc := interactive.loc.ns [none]) : tactic unit := do [v1, v2, v3] ← [hh, hf, hg].mmap (λ n, tactic.mk_app ``stationary_point [n] <|> return n), e1 ← tactic.mk_app ``lift_index_left_left [hh, v2, v3] <|> return `(true), e2 ← tactic.mk_app ``lift_index_left [hf, v1, v3] <|> return `(true), e3 ← tactic.mk_app ``lift_index_right [hg, v1, v2] <|> return `(true), sl ← [e1, e2, e3].mfoldl (λ s e, simp_lemmas.add s e) simp_lemmas.mk, when at_.include_goal (tactic.simp_target sl), hs ← at_.get_locals, hs.mmap' (tactic.simp_hyp sl []) /-- This is a special-purpose tactic that lifts padic_norm (f (stationary_point f)) to padic_norm (f (max _ _ _)). -/ meta def tactic.interactive.padic_index_simp (l : interactive.parse interactive.types.pexpr_list) (at_ : interactive.parse interactive.types.location) : tactic unit := do [h, f, g] ← l.mmap tactic.i_to_expr, index_simp_core h f g at_ end namespace padic_seq section embedding open cau_seq variables {p : ℕ} [hp : fact p.prime] include hp lemma norm_mul (f g : padic_seq p) : (f * g).norm = f.norm * g.norm := if hf : f ≈ 0 then have hg : f * g ≈ 0, from mul_equiv_zero' _ hf, by simp [hf, hg, norm] else if hg : g ≈ 0 then have hf : f * g ≈ 0, from mul_equiv_zero _ hg, by simp [hf, hg, norm] else have hfg : ¬ f * g ≈ 0, by apply mul_not_equiv_zero; assumption, begin unfold norm, split_ifs, padic_index_simp [hfg, hf, hg], apply padic_norm.mul end lemma eq_zero_iff_equiv_zero (f : padic_seq p) : mk f = 0 ↔ f ≈ 0 := mk_eq lemma ne_zero_iff_nequiv_zero (f : padic_seq p) : mk f ≠ 0 ↔ ¬ f ≈ 0 := not_iff_not.2 (eq_zero_iff_equiv_zero _) lemma norm_const (q : ℚ) : norm (const (padic_norm p) q) = padic_norm p q := if hq : q = 0 then have (const (padic_norm p) q) ≈ 0, by simp [hq]; apply setoid.refl (const (padic_norm p) 0), by subst hq; simp [norm, this] else have ¬ (const (padic_norm p) q) ≈ 0, from not_equiv_zero_const_of_nonzero hq, by simp [norm, this] lemma norm_values_discrete (a : padic_seq p) (ha : ¬ a ≈ 0) : (∃ (z : ℤ), a.norm = ↑p ^ (-z)) := let ⟨k, hk, hk'⟩ := norm_eq_norm_app_of_nonzero ha in by simpa [hk] using padic_norm.values_discrete p hk' lemma norm_one : norm (1 : padic_seq p) = 1 := have h1 : ¬ (1 : padic_seq p) ≈ 0, from one_not_equiv_zero _, by simp [h1, norm, hp.one_lt] private lemma norm_eq_of_equiv_aux {f g : padic_seq p} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) (hfg : f ≈ g) (h : padic_norm p (f (stationary_point hf)) ≠ padic_norm p (g (stationary_point hg))) (hlt : padic_norm p (g (stationary_point hg)) < padic_norm p (f (stationary_point hf))) : false := begin have hpn : 0 < padic_norm p (f (stationary_point hf)) - padic_norm p (g (stationary_point hg)), from sub_pos_of_lt hlt, cases hfg _ hpn with N hN, let i := max N (max (stationary_point hf) (stationary_point hg)), have hi : N ≤ i, from le_max_left _ _, have hN' := hN _ hi, padic_index_simp [N, hf, hg] at hN' h hlt, have hpne : padic_norm p (f i) ≠ padic_norm p (-(g i)), by rwa [ ←padic_norm.neg p (g i)] at h, let hpnem := add_eq_max_of_ne p hpne, have hpeq : padic_norm p ((f - g) i) = max (padic_norm p (f i)) (padic_norm p (g i)), { rwa padic_norm.neg at hpnem }, rw [hpeq, max_eq_left_of_lt hlt] at hN', have : padic_norm p (f i) < padic_norm p (f i), { apply lt_of_lt_of_le hN', apply sub_le_self, apply padic_norm.nonneg }, exact lt_irrefl _ this end private lemma norm_eq_of_equiv {f g : padic_seq p} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) (hfg : f ≈ g) : padic_norm p (f (stationary_point hf)) = padic_norm p (g (stationary_point hg)) := begin by_contradiction h, cases (decidable.em (padic_norm p (g (stationary_point hg)) < padic_norm p (f (stationary_point hf)))) with hlt hnlt, { exact norm_eq_of_equiv_aux hf hg hfg h hlt }, { apply norm_eq_of_equiv_aux hg hf (setoid.symm hfg) (ne.symm h), apply lt_of_le_of_ne, apply le_of_not_gt hnlt, apply h } end theorem norm_equiv {f g : padic_seq p} (hfg : f ≈ g) : f.norm = g.norm := if hf : f ≈ 0 then have hg : g ≈ 0, from setoid.trans (setoid.symm hfg) hf, by simp [norm, hf, hg] else have hg : ¬ g ≈ 0, from hf ∘ setoid.trans hfg, by unfold norm; split_ifs; exact norm_eq_of_equiv hf hg hfg private lemma norm_nonarchimedean_aux {f g : padic_seq p} (hfg : ¬ f + g ≈ 0) (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) : (f + g).norm ≤ max (f.norm) (g.norm) := begin unfold norm, split_ifs, padic_index_simp [hfg, hf, hg], apply padic_norm.nonarchimedean end theorem norm_nonarchimedean (f g : padic_seq p) : (f + g).norm ≤ max (f.norm) (g.norm) := if hfg : f + g ≈ 0 then have 0 ≤ max (f.norm) (g.norm), from le_max_left_of_le (norm_nonneg _), by simpa [hfg, norm] else if hf : f ≈ 0 then have hfg' : f + g ≈ g, { change lim_zero (f - 0) at hf, show lim_zero (f + g - g), by simpa using hf }, have hcfg : (f + g).norm = g.norm, from norm_equiv hfg', have hcl : f.norm = 0, from (norm_zero_iff f).2 hf, have max (f.norm) (g.norm) = g.norm, by rw hcl; exact max_eq_right (norm_nonneg _), by rw [this, hcfg] else if hg : g ≈ 0 then have hfg' : f + g ≈ f, { change lim_zero (g - 0) at hg, show lim_zero (f + g - f), by simpa [add_sub_cancel'] using hg }, have hcfg : (f + g).norm = f.norm, from norm_equiv hfg', have hcl : g.norm = 0, from (norm_zero_iff g).2 hg, have max (f.norm) (g.norm) = f.norm, by rw hcl; exact max_eq_left (norm_nonneg _), by rw [this, hcfg] else norm_nonarchimedean_aux hfg hf hg lemma norm_eq {f g : padic_seq p} (h : ∀ k, padic_norm p (f k) = padic_norm p (g k)) : f.norm = g.norm := if hf : f ≈ 0 then have hg : g ≈ 0, from equiv_zero_of_val_eq_of_equiv_zero h hf, by simp [hf, hg, norm] else have hg : ¬ g ≈ 0, from λ hg, hf $ equiv_zero_of_val_eq_of_equiv_zero (by simp [h]) hg, begin simp [hg, hf, norm], let i := max (stationary_point hf) (stationary_point hg), have hpf : padic_norm p (f (stationary_point hf)) = padic_norm p (f i), { apply stationary_point_spec, apply le_max_left, apply le_refl }, have hpg : padic_norm p (g (stationary_point hg)) = padic_norm p (g i), { apply stationary_point_spec, apply le_max_right, apply le_refl }, rw [hpf, hpg, h] end lemma norm_neg (a : padic_seq p) : (-a).norm = a.norm := norm_eq $ by simp lemma norm_eq_of_add_equiv_zero {f g : padic_seq p} (h : f + g ≈ 0) : f.norm = g.norm := have lim_zero (f + g - 0), from h, have f ≈ -g, from show lim_zero (f - (-g)), by simpa, have f.norm = (-g).norm, from norm_equiv this, by simpa [norm_neg] using this lemma add_eq_max_of_ne {f g : padic_seq p} (hfgne : f.norm ≠ g.norm) : (f + g).norm = max f.norm g.norm := have hfg : ¬f + g ≈ 0, from mt norm_eq_of_add_equiv_zero hfgne, if hf : f ≈ 0 then have lim_zero (f - 0), from hf, have f + g ≈ g, from show lim_zero ((f + g) - g), by simpa, have h1 : (f+g).norm = g.norm, from norm_equiv this, have h2 : f.norm = 0, from (norm_zero_iff _).2 hf, by rw [h1, h2]; rw max_eq_right (norm_nonneg _) else if hg : g ≈ 0 then have lim_zero (g - 0), from hg, have f + g ≈ f, from show lim_zero ((f + g) - f), by rw [add_sub_cancel']; simpa, have h1 : (f+g).norm = f.norm, from norm_equiv this, have h2 : g.norm = 0, from (norm_zero_iff _).2 hg, by rw [h1, h2]; rw max_eq_left (norm_nonneg _) else begin unfold norm at ⊢ hfgne, split_ifs at ⊢ hfgne, padic_index_simp [hfg, hf, hg] at ⊢ hfgne, apply padic_norm.add_eq_max_of_ne, simpa [hf, hg, norm] using hfgne end end embedding end padic_seq /-- The p-adic numbers `Q_[p]` are the Cauchy completion of `ℚ` with respect to the p-adic norm. -/ def padic (p : ℕ) [fact p.prime] := @cau_seq.completion.Cauchy _ _ _ _ (padic_norm p) _ notation `ℚ_[` p `]` := padic p namespace padic section completion variables {p : ℕ} [fact p.prime] /-- The discrete field structure on `ℚ_p` is inherited from the Cauchy completion construction. -/ instance field : field (ℚ_[p]) := cau_seq.completion.field instance : inhabited ℚ_[p] := ⟨0⟩ -- short circuits instance : has_zero ℚ_[p] := by apply_instance instance : has_one ℚ_[p] := by apply_instance instance : has_add ℚ_[p] := by apply_instance instance : has_mul ℚ_[p] := by apply_instance instance : has_sub ℚ_[p] := by apply_instance instance : has_neg ℚ_[p] := by apply_instance instance : has_div ℚ_[p] := by apply_instance instance : add_comm_group ℚ_[p] := by apply_instance instance : comm_ring ℚ_[p] := by apply_instance /-- Builds the equivalence class of a Cauchy sequence of rationals. -/ def mk : padic_seq p → ℚ_[p] := quotient.mk end completion section completion variables (p : ℕ) [fact p.prime] lemma mk_eq {f g : padic_seq p} : mk f = mk g ↔ f ≈ g := quotient.eq /-- Embeds the rational numbers in the p-adic numbers. -/ def of_rat : ℚ → ℚ_[p] := cau_seq.completion.of_rat @[simp] lemma of_rat_add : ∀ (x y : ℚ), of_rat p (x + y) = of_rat p x + of_rat p y := cau_seq.completion.of_rat_add @[simp] lemma of_rat_neg : ∀ (x : ℚ), of_rat p (-x) = -of_rat p x := cau_seq.completion.of_rat_neg @[simp] lemma of_rat_mul : ∀ (x y : ℚ), of_rat p (x * y) = of_rat p x * of_rat p y := cau_seq.completion.of_rat_mul @[simp] lemma of_rat_sub : ∀ (x y : ℚ), of_rat p (x - y) = of_rat p x - of_rat p y := cau_seq.completion.of_rat_sub @[simp] lemma of_rat_div : ∀ (x y : ℚ), of_rat p (x / y) = of_rat p x / of_rat p y := cau_seq.completion.of_rat_div @[simp] lemma of_rat_one : of_rat p 1 = 1 := rfl @[simp] lemma of_rat_zero : of_rat p 0 = 0 := rfl lemma cast_eq_of_rat_of_nat (n : ℕ) : (↑n : ℚ_[p]) = of_rat p n := begin induction n with n ih, { refl }, { simpa using ih } end lemma cast_eq_of_rat_of_int (n : ℤ) : ↑n = of_rat p n := by induction n; simp [cast_eq_of_rat_of_nat] lemma cast_eq_of_rat : ∀ (q : ℚ), (↑q : ℚ_[p]) = of_rat p q | ⟨n, d, h1, h2⟩ := show ↑n / ↑d = _, from have (⟨n, d, h1, h2⟩ : ℚ) = rat.mk n d, from rat.num_denom', by simp [this, rat.mk_eq_div, of_rat_div, cast_eq_of_rat_of_int, cast_eq_of_rat_of_nat] @[norm_cast] lemma coe_add : ∀ {x y : ℚ}, (↑(x + y) : ℚ_[p]) = ↑x + ↑y := by simp [cast_eq_of_rat] @[norm_cast] lemma coe_neg : ∀ {x : ℚ}, (↑(-x) : ℚ_[p]) = -↑x := by simp [cast_eq_of_rat] @[norm_cast] lemma coe_mul : ∀ {x y : ℚ}, (↑(x * y) : ℚ_[p]) = ↑x * ↑y := by simp [cast_eq_of_rat] @[norm_cast] lemma coe_sub : ∀ {x y : ℚ}, (↑(x - y) : ℚ_[p]) = ↑x - ↑y := by simp [cast_eq_of_rat] @[norm_cast] lemma coe_div : ∀ {x y : ℚ}, (↑(x / y) : ℚ_[p]) = ↑x / ↑y := by simp [cast_eq_of_rat] @[norm_cast] lemma coe_one : (↑1 : ℚ_[p]) = 1 := rfl @[norm_cast] lemma coe_zero : (↑0 : ℚ_[p]) = 0 := rfl lemma const_equiv {q r : ℚ} : const (padic_norm p) q ≈ const (padic_norm p) r ↔ q = r := ⟨ λ heq : lim_zero (const (padic_norm p) (q - r)), eq_of_sub_eq_zero $ const_lim_zero.1 heq, λ heq, by rw heq; apply setoid.refl _ ⟩ lemma of_rat_eq {q r : ℚ} : of_rat p q = of_rat p r ↔ q = r := ⟨(const_equiv p).1 ∘ quotient.eq.1, λ h, by rw h⟩ @[norm_cast] lemma coe_inj {q r : ℚ} : (↑q : ℚ_[p]) = ↑r ↔ q = r := by simp [cast_eq_of_rat, of_rat_eq] instance : char_zero ℚ_[p] := ⟨λ m n, by { rw ← rat.cast_coe_nat, norm_cast, exact id }⟩ end completion end padic /-- The rational-valued p-adic norm on `ℚ_p` is lifted from the norm on Cauchy sequences. The canonical form of this function is the normed space instance, with notation `∥ ∥`. -/ def padic_norm_e {p : ℕ} [hp : fact p.prime] : ℚ_[p] → ℚ := quotient.lift padic_seq.norm $ @padic_seq.norm_equiv _ _ namespace padic_norm_e section embedding open padic_seq variables {p : ℕ} [fact p.prime] lemma defn (f : padic_seq p) {ε : ℚ} (hε : 0 < ε) : ∃ N, ∀ i ≥ N, padic_norm_e (⟦f⟧ - f i) < ε := begin simp only [padic.cast_eq_of_rat], change ∃ N, ∀ i ≥ N, (f - const _ (f i)).norm < ε, by_contradiction h, cases cauchy₂ f hε with N hN, have : ∀ N, ∃ i ≥ N, ε ≤ (f - const _ (f i)).norm, by simpa [not_forall] using h, rcases this N with ⟨i, hi, hge⟩, have hne : ¬ (f - const (padic_norm p) (f i)) ≈ 0, { intro h, unfold padic_seq.norm at hge; split_ifs at hge, exact not_lt_of_ge hge hε }, unfold padic_seq.norm at hge; split_ifs at hge, apply not_le_of_gt _ hge, cases decidable.em (N ≤ stationary_point hne) with hgen hngen, { apply hN; assumption }, { have := stationary_point_spec hne (le_refl _) (le_of_not_le hngen), rw ←this, apply hN, apply le_refl, assumption } end protected lemma nonneg (q : ℚ_[p]) : 0 ≤ padic_norm_e q := quotient.induction_on q $ norm_nonneg lemma zero_def : (0 : ℚ_[p]) = ⟦0⟧ := rfl lemma zero_iff (q : ℚ_[p]) : padic_norm_e q = 0 ↔ q = 0 := quotient.induction_on q $ by simpa only [zero_def, quotient.eq] using norm_zero_iff @[simp] protected lemma zero : padic_norm_e (0 : ℚ_[p]) = 0 := (zero_iff _).2 rfl /-- Theorems about `padic_norm_e` are named with a `'` so the names do not conflict with the equivalent theorems about `norm` (`∥ ∥`). -/ @[simp] protected lemma one' : padic_norm_e (1 : ℚ_[p]) = 1 := norm_one @[simp] protected lemma neg (q : ℚ_[p]) : padic_norm_e (-q) = padic_norm_e q := quotient.induction_on q $ norm_neg /-- Theorems about `padic_norm_e` are named with a `'` so the names do not conflict with the equivalent theorems about `norm` (`∥ ∥`). -/ theorem nonarchimedean' (q r : ℚ_[p]) : padic_norm_e (q + r) ≤ max (padic_norm_e q) (padic_norm_e r) := quotient.induction_on₂ q r $ norm_nonarchimedean /-- Theorems about `padic_norm_e` are named with a `'` so the names do not conflict with the equivalent theorems about `norm` (`∥ ∥`). -/ theorem add_eq_max_of_ne' {q r : ℚ_[p]} : padic_norm_e q ≠ padic_norm_e r → padic_norm_e (q + r) = max (padic_norm_e q) (padic_norm_e r) := quotient.induction_on₂ q r $ λ _ _, padic_seq.add_eq_max_of_ne lemma triangle_ineq (x y z : ℚ_[p]) : padic_norm_e (x - z) ≤ padic_norm_e (x - y) + padic_norm_e (y - z) := calc padic_norm_e (x - z) = padic_norm_e ((x - y) + (y - z)) : by rw sub_add_sub_cancel ... ≤ max (padic_norm_e (x - y)) (padic_norm_e (y - z)) : padic_norm_e.nonarchimedean' _ _ ... ≤ padic_norm_e (x - y) + padic_norm_e (y - z) : max_le_add_of_nonneg (padic_norm_e.nonneg _) (padic_norm_e.nonneg _) protected lemma add (q r : ℚ_[p]) : padic_norm_e (q + r) ≤ (padic_norm_e q) + (padic_norm_e r) := calc padic_norm_e (q + r) ≤ max (padic_norm_e q) (padic_norm_e r) : nonarchimedean' _ _ ... ≤ (padic_norm_e q) + (padic_norm_e r) : max_le_add_of_nonneg (padic_norm_e.nonneg _) (padic_norm_e.nonneg _) protected lemma mul' (q r : ℚ_[p]) : padic_norm_e (q * r) = (padic_norm_e q) * (padic_norm_e r) := quotient.induction_on₂ q r $ norm_mul instance : is_absolute_value (@padic_norm_e p _) := { abv_nonneg := padic_norm_e.nonneg, abv_eq_zero := zero_iff, abv_add := padic_norm_e.add, abv_mul := padic_norm_e.mul' } @[simp] lemma eq_padic_norm' (q : ℚ) : padic_norm_e (padic.of_rat p q) = padic_norm p q := norm_const _ protected theorem image' {q : ℚ_[p]} : q ≠ 0 → ∃ n : ℤ, padic_norm_e q = p ^ (-n) := quotient.induction_on q $ λ f hf, have ¬ f ≈ 0, from (ne_zero_iff_nequiv_zero f).1 hf, norm_values_discrete f this lemma sub_rev (q r : ℚ_[p]) : padic_norm_e (q - r) = padic_norm_e (r - q) := by rw ←(padic_norm_e.neg); simp end embedding end padic_norm_e namespace padic section complete open padic_seq padic theorem rat_dense' {p : ℕ} [fact p.prime] (q : ℚ_[p]) {ε : ℚ} (hε : 0 < ε) : ∃ r : ℚ, padic_norm_e (q - r) < ε := quotient.induction_on q $ λ q', have ∃ N, ∀ m n ≥ N, padic_norm p (q' m - q' n) < ε, from cauchy₂ _ hε, let ⟨N, hN⟩ := this in ⟨q' N, begin simp only [padic.cast_eq_of_rat], change padic_seq.norm (q' - const _ (q' N)) < ε, cases decidable.em ((q' - const (padic_norm p) (q' N)) ≈ 0) with heq hne', { simpa only [heq, padic_seq.norm, dif_pos] }, { simp only [padic_seq.norm, dif_neg hne'], change padic_norm p (q' _ - q' _) < ε, have := stationary_point_spec hne', cases decidable.em (stationary_point hne' ≤ N) with hle hle, { have := eq.symm (this (le_refl _) hle), simp at this, simpa [this] }, { apply hN, apply le_of_lt, apply lt_of_not_ge, apply hle, apply le_refl }} end⟩ variables {p : ℕ} [fact p.prime] (f : cau_seq _ (@padic_norm_e p _)) open classical private lemma div_nat_pos (n : ℕ) : 0 < (1 / ((n + 1): ℚ)) := div_pos zero_lt_one (by exact_mod_cast succ_pos _) def lim_seq : ℕ → ℚ := λ n, classical.some (rat_dense' (f n) (div_nat_pos n)) lemma exi_rat_seq_conv {ε : ℚ} (hε : 0 < ε) : ∃ N, ∀ i ≥ N, padic_norm_e (f i - ((lim_seq f) i : ℚ_[p])) < ε := begin refine (exists_nat_gt (1/ε)).imp (λ N hN i hi, _), have h := classical.some_spec (rat_dense' (f i) (div_nat_pos i)), refine lt_of_lt_of_le h ((div_le_iff' $ by exact_mod_cast succ_pos _).mpr _), rw right_distrib, apply le_add_of_le_of_nonneg, { exact (div_le_iff hε).mp (le_trans (le_of_lt hN) (by exact_mod_cast hi)) }, { apply le_of_lt, simpa } end lemma exi_rat_seq_conv_cauchy : is_cau_seq (padic_norm p) (lim_seq f) := assume ε hε, have hε3 : 0 < ε / 3, from div_pos hε (by norm_num), let ⟨N, hN⟩ := exi_rat_seq_conv f hε3, ⟨N2, hN2⟩ := f.cauchy₂ hε3 in begin existsi max N N2, intros j hj, suffices : padic_norm_e ((↑(lim_seq f j) - f (max N N2)) + (f (max N N2) - lim_seq f (max N N2))) < ε, { ring at this ⊢, rw [← padic_norm_e.eq_padic_norm', ← padic.cast_eq_of_rat], exact_mod_cast this }, { apply lt_of_le_of_lt, { apply padic_norm_e.add }, { have : (3 : ℚ) ≠ 0, by norm_num, have : ε = ε / 3 + ε / 3 + ε / 3, { field_simp [this], simp [bit0, bit1, mul_add] }, rw this, apply add_lt_add, { suffices : padic_norm_e ((↑(lim_seq f j) - f j) + (f j - f (max N N2))) < ε / 3 + ε / 3, by simpa [sub_add_sub_cancel], apply lt_of_le_of_lt, { apply padic_norm_e.add }, { apply add_lt_add, { rw [padic_norm_e.sub_rev], apply_mod_cast hN, exact le_of_max_le_left hj }, { apply hN2, exact le_of_max_le_right hj, apply le_max_right }}}, { apply_mod_cast hN, apply le_max_left }}} end private def lim' : padic_seq p := ⟨_, exi_rat_seq_conv_cauchy f⟩ private def lim : ℚ_[p] := ⟦lim' f⟧ theorem complete' : ∃ q : ℚ_[p], ∀ ε > 0, ∃ N, ∀ i ≥ N, padic_norm_e (q - f i) < ε := ⟨ lim f, λ ε hε, let ⟨N, hN⟩ := exi_rat_seq_conv f (show 0 < ε / 2, from div_pos hε (by norm_num)), ⟨N2, hN2⟩ := padic_norm_e.defn (lim' f) (show 0 < ε / 2, from div_pos hε (by norm_num)) in begin existsi max N N2, intros i hi, suffices : padic_norm_e ((lim f - lim' f i) + (lim' f i - f i)) < ε, { ring at this; exact this }, { apply lt_of_le_of_lt, { apply padic_norm_e.add }, { have : ε = ε / 2 + ε / 2, by rw ←(add_self_div_two ε); simp, rw this, apply add_lt_add, { apply hN2, exact le_of_max_le_right hi }, { rw_mod_cast [padic_norm_e.sub_rev], apply hN, exact le_of_max_le_left hi }}} end ⟩ end complete section normed_space variables (p : ℕ) [fact p.prime] instance : has_dist ℚ_[p] := ⟨λ x y, padic_norm_e (x - y)⟩ instance : metric_space ℚ_[p] := { dist_self := by simp [dist], dist_comm := λ x y, by unfold dist; rw ←padic_norm_e.neg (x - y); simp, dist_triangle := begin intros, unfold dist, exact_mod_cast padic_norm_e.triangle_ineq _ _ _, end, eq_of_dist_eq_zero := begin unfold dist, intros _ _ h, apply eq_of_sub_eq_zero, apply (padic_norm_e.zero_iff _).1, exact_mod_cast h end } instance : has_norm ℚ_[p] := ⟨λ x, padic_norm_e x⟩ instance : normed_field ℚ_[p] := { dist_eq := λ _ _, rfl, norm_mul' := by simp [has_norm.norm, padic_norm_e.mul'] } instance : is_absolute_value (λ a : ℚ_[p], ∥a∥) := { abv_nonneg := norm_nonneg, abv_eq_zero := λ _, norm_eq_zero, abv_add := norm_add_le, abv_mul := by simp [has_norm.norm, padic_norm_e.mul'] } theorem rat_dense {p : ℕ} {hp : fact p.prime} (q : ℚ_[p]) {ε : ℝ} (hε : 0 < ε) : ∃ r : ℚ, ∥q - r∥ < ε := let ⟨ε', hε'l, hε'r⟩ := exists_rat_btwn hε, ⟨r, hr⟩ := rat_dense' q (by simpa using hε'l) in ⟨r, lt.trans (by simpa [has_norm.norm] using hr) hε'r⟩ end normed_space end padic namespace padic_norm_e section normed_space variables {p : ℕ} [hp : fact p.prime] include hp @[simp] protected lemma mul (q r : ℚ_[p]) : ∥q * r∥ = ∥q∥ * ∥r∥ := by simp [has_norm.norm, padic_norm_e.mul'] protected lemma is_norm (q : ℚ_[p]) : ↑(padic_norm_e q) = ∥q∥ := rfl theorem nonarchimedean (q r : ℚ_[p]) : ∥q + r∥ ≤ max (∥q∥) (∥r∥) := begin unfold has_norm.norm, exact_mod_cast nonarchimedean' _ _ end theorem add_eq_max_of_ne {q r : ℚ_[p]} (h : ∥q∥ ≠ ∥r∥) : ∥q+r∥ = max (∥q∥) (∥r∥) := begin unfold has_norm.norm, apply_mod_cast add_eq_max_of_ne', intro h', apply h, unfold has_norm.norm, exact_mod_cast h' end @[simp] lemma eq_padic_norm (q : ℚ) : ∥(↑q : ℚ_[p])∥ = padic_norm p q := begin unfold has_norm.norm, rw [← padic_norm_e.eq_padic_norm', ← padic.cast_eq_of_rat] end instance : nondiscrete_normed_field ℚ_[p] := { non_trivial := ⟨padic.of_rat p (p⁻¹), begin have h0 : p ≠ 0 := ne_of_gt (hp.pos), have h1 : 1 < p := hp.one_lt, rw [← padic.cast_eq_of_rat, eq_padic_norm], simp only [padic_norm, inv_eq_zero], simp only [if_neg] {discharger := `[exact_mod_cast h0]}, norm_cast, simp only [padic_val_rat.inv] {discharger := `[exact_mod_cast h0]}, rw [neg_neg, padic_val_rat.padic_val_rat_self h1], erw _root_.pow_one, exact_mod_cast h1, end⟩ } @[simp] lemma norm_p : ∥(p : ℚ_[p])∥ = p⁻¹ := begin have p₀ : p ≠ 0 := nat.prime.ne_zero ‹_›, have p₁ : p ≠ 1 := nat.prime.ne_one ‹_›, simp [p₀, p₁, norm, padic_norm, padic_val_rat, fpow_neg, padic.cast_eq_of_rat_of_nat], end lemma norm_p_lt_one : ∥(p : ℚ_[p])∥ < 1 := begin rw [norm_p, inv_eq_one_div, div_lt_iff, one_mul], { exact_mod_cast nat.prime.one_lt ‹_› }, { exact_mod_cast nat.prime.pos ‹_› } end @[simp] lemma norm_p_pow (n : ℤ) : ∥(p^n : ℚ_[p])∥ = p^-n := by rw [normed_field.norm_fpow, norm_p]; field_simp protected theorem image {q : ℚ_[p]} : q ≠ 0 → ∃ n : ℤ, ∥q∥ = ↑((↑p : ℚ) ^ (-n)) := quotient.induction_on q $ λ f hf, have ¬ f ≈ 0, from (padic_seq.ne_zero_iff_nequiv_zero f).1 hf, let ⟨n, hn⟩ := padic_seq.norm_values_discrete f this in ⟨n, congr_arg coe hn⟩ protected lemma is_rat (q : ℚ_[p]) : ∃ q' : ℚ, ∥q∥ = ↑q' := if h : q = 0 then ⟨0, by simp [h]⟩ else let ⟨n, hn⟩ := padic_norm_e.image h in ⟨_, hn⟩ def rat_norm (q : ℚ_[p]) : ℚ := classical.some (padic_norm_e.is_rat q) lemma eq_rat_norm (q : ℚ_[p]) : ∥q∥ = rat_norm q := classical.some_spec (padic_norm_e.is_rat q) theorem norm_rat_le_one : ∀ {q : ℚ} (hq : ¬ p ∣ q.denom), ∥(q : ℚ_[p])∥ ≤ 1 | ⟨n, d, hn, hd⟩ := λ hq : ¬ p ∣ d, if hnz : n = 0 then have (⟨n, d, hn, hd⟩ : ℚ) = 0, from rat.zero_iff_num_zero.mpr hnz, by norm_num [this] else begin have hnz' : {rat . num := n, denom := d, pos := hn, cop := hd} ≠ 0, from mt rat.zero_iff_num_zero.1 hnz, rw [padic_norm_e.eq_padic_norm], norm_cast, rw [padic_norm.eq_fpow_of_nonzero p hnz', padic_val_rat_def p hnz'], have h : (multiplicity p d).get _ = 0, by simp [multiplicity_eq_zero_of_not_dvd, hq], simp only, norm_cast, rw_mod_cast [h, sub_zero], apply fpow_le_one_of_nonpos, { exact_mod_cast le_of_lt hp.one_lt, }, { apply neg_nonpos_of_nonneg, norm_cast, simp, } end theorem norm_int_le_one (z : ℤ) : ∥(z : ℚ_[p])∥ ≤ 1 := suffices ∥((z : ℚ) : ℚ_[p])∥ ≤ 1, by simpa, norm_rat_le_one $ by simp [nat.prime.ne_one ‹_›] lemma norm_int_lt_one_iff_dvd (k : ℤ) : ∥(k : ℚ_[p])∥ < 1 ↔ ↑p ∣ k := begin split, { intro h, contrapose! h, apply le_of_eq, rw eq_comm, calc ∥(k : ℚ_[p])∥ = ∥((k : ℚ) : ℚ_[p])∥ : by { norm_cast } ... = padic_norm p k : padic_norm_e.eq_padic_norm _ ... = 1 : _, rw padic_norm, split_ifs with H, { exfalso, apply h, norm_cast at H, rw H, apply dvd_zero }, { norm_cast at H ⊢, convert fpow_zero _, simp only [neg_eq_zero], rw padic_val_rat.padic_val_rat_of_int _ (nat.prime.ne_one ‹_›) H, norm_cast, rw [← enat.coe_inj, enat.coe_get, enat.coe_zero], apply multiplicity.multiplicity_eq_zero_of_not_dvd h } }, { rintro ⟨x, rfl⟩, push_cast, rw padic_norm_e.mul, calc _ ≤ ∥(p : ℚ_[p])∥ * 1 : mul_le_mul (le_refl _) (by simpa using norm_int_le_one _) (norm_nonneg _) (norm_nonneg _) ... < 1 : _, { rw [mul_one, padic_norm_e.norm_p], apply inv_lt_one, exact_mod_cast nat.prime.one_lt ‹_› }, }, end lemma norm_int_le_pow_iff_dvd (k : ℤ) (n : ℕ) : ∥(k : ℚ_[p])∥ ≤ ((↑p)^(-n : ℤ)) ↔ ↑(p^n) ∣ k := begin have : (p : ℝ) ^ (-n : ℤ) = ↑((p ^ (-n : ℤ) : ℚ)), {simp}, rw [show (k : ℚ_[p]) = ((k : ℚ) : ℚ_[p]), by norm_cast, eq_padic_norm, this], norm_cast, rw padic_norm.dvd_iff_norm_le, end lemma eq_of_norm_add_lt_right {p : ℕ} {hp : fact p.prime} {z1 z2 : ℚ_[p]} (h : ∥z1 + z2∥ < ∥z2∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw padic_norm_e.add_eq_max_of_ne hne; apply le_max_right) h lemma eq_of_norm_add_lt_left {p : ℕ} {hp : fact p.prime} {z1 z2 : ℚ_[p]} (h : ∥z1 + z2∥ < ∥z1∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw padic_norm_e.add_eq_max_of_ne hne; apply le_max_left) h end normed_space end padic_norm_e namespace padic variables {p : ℕ} [fact p.prime] set_option eqn_compiler.zeta true instance complete : cau_seq.is_complete ℚ_[p] norm := begin split, intro f, have cau_seq_norm_e : is_cau_seq padic_norm_e f, { intros ε hε, let h := is_cau f ε (by exact_mod_cast hε), unfold norm at h, apply_mod_cast h }, cases padic.complete' ⟨f, cau_seq_norm_e⟩ with q hq, existsi q, intros ε hε, cases exists_rat_btwn hε with ε' hε', norm_cast at hε', cases hq ε' hε'.1 with N hN, existsi N, intros i hi, let h := hN i hi, unfold norm, rw_mod_cast [cau_seq.sub_apply, padic_norm_e.sub_rev], refine lt.trans _ hε'.2, exact_mod_cast hN i hi end lemma padic_norm_e_lim_le {f : cau_seq ℚ_[p] norm} {a : ℝ} (ha : 0 < a) (hf : ∀ i, ∥f i∥ ≤ a) : ∥f.lim∥ ≤ a := let ⟨N, hN⟩ := setoid.symm (cau_seq.equiv_lim f) _ ha in calc ∥f.lim∥ = ∥f.lim - f N + f N∥ : by simp ... ≤ max (∥f.lim - f N∥) (∥f N∥) : padic_norm_e.nonarchimedean _ _ ... ≤ a : max_le (le_of_lt (hN _ (le_refl _))) (hf _) /-! ### Valuation on `ℚ_[p]` -/ /-- `padic.valuation` lifts the p-adic valuation on rationals to `ℚ_[p]`. -/ def valuation : ℚ_[p] → ℤ := quotient.lift (@padic_seq.valuation p _) (λ f g h, begin by_cases hf : f ≈ 0, { have hg : g ≈ 0, from setoid.trans (setoid.symm h) hf, simp [hf, hg, padic_seq.valuation] }, { have hg : ¬ g ≈ 0, from (λ hg, hf (setoid.trans h hg)), rw padic_seq.val_eq_iff_norm_eq hf hg, exact padic_seq.norm_equiv h }, end) @[simp] lemma valuation_zero : valuation (0 : ℚ_[p]) = 0 := dif_pos ((const_equiv p).2 rfl) @[simp] lemma valuation_one : valuation (1 : ℚ_[p]) = 0 := begin change dite (cau_seq.const (padic_norm p) 1 ≈ _) _ _ = _, have h : ¬ cau_seq.const (padic_norm p) 1 ≈ 0, { assume H, erw const_equiv p at H, exact one_ne_zero H }, rw dif_neg h, simp, end lemma norm_eq_pow_val {x : ℚ_[p]} : x ≠ 0 → ∥x∥ = p^(-x.valuation) := begin apply quotient.induction_on' x, clear x, intros f hf, change (padic_seq.norm _ : ℝ) = (p : ℝ) ^ -padic_seq.valuation _, rw padic_seq.norm_eq_pow_val, change ↑((p : ℚ) ^ -padic_seq.valuation f) = (p : ℝ) ^ -padic_seq.valuation f, { rw rat.cast_fpow, congr' 1, norm_cast }, { apply cau_seq.not_lim_zero_of_not_congr_zero, contrapose! hf, apply quotient.sound, simpa using hf, } end @[simp] lemma valuation_p : valuation (p : ℚ_[p]) = 1 := begin have h : (1 : ℝ) < p := by exact_mod_cast nat.prime.one_lt ‹_›, rw ← neg_inj, apply (fpow_strict_mono h).injective, dsimp only, rw ← norm_eq_pow_val, { simp }, { exact_mod_cast nat.prime.ne_zero ‹_›, } end end padic
60c6e8feb2e924d3959eb5fcd6aed7e465decd82
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/group_theory/submonoid/operations.lean
8721d3289eb279a7799fe8759a856c142ea56d4e
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
15,756
lean
import group_theory.submonoid.basic import data.equiv.mul_add import algebra.group.prod /-! # Operations on `submonoid`s In this file we define various operations on `submonoid`s and `monoid_hom`s. ## Main definitions ### Conversion between multiplicative and additive definitions * `submonoid.to_add_submonoid`, `submonoid.of_add_submonoid`, `add_submonoid.to_submonoid`, `add_submonoid.of_submonoid`: convert between multiplicative and additive submonoids of `M`, `multiplicative M`, and `additive M`. * `submonoid.add_submonoid_equiv`: equivalence between `submonoid M` and `add_submonoid (additive M)`. ### (Commutative) monoid structure on a submonoid * `submonoid.to_monoid`, `submonoid.to_comm_monoid`: a submonoid inherits a (commutative) monoid structure. ### Operations on submonoids * `submonoid.comap`: preimage of a submonoid under a monoid homomorphism as a submonoid of the domain; * `submonoid.map`: image of a submonoid under a monoid homomorphism as a submonoid of the codomain; * `submonoid.prod`: product of two submonoids `s : submonoid M` and `t : submonoid N` as a submonoid of `M × N`; ### Monoid homomorphisms between submonoid * `submonoid.subtype`: embedding of a submonoid into the ambient monoid. * `submonoid.inclusion`: given two submonoids `S`, `T` such that `S ≤ T`, `S.inclusion T` is the inclusion of `S` into `T` as a monoid homomorphism; * `mul_equiv.submonoid_congr`: converts a proof of `S = T` into a monoid isomorphism between `S` and `T`. * `submonoid.prod_equiv`: monoid isomorphism between `s.prod t` and `s × t`; ### Operations on `monoid_hom`s * `monoid_hom.mrange`: range of a monoid homomorphism as a submonoid of the codomain; * `monoid_hom.mrestrict`: restrict a monoid homomorphism to a submonoid; * `monoid_hom.cod_mrestrict`: restrict the codomain of a monoid homomorphism to a submonoid; * `monoid_hom.mrange_restrict`: restrict a monoid homomorphism to its range; ## Tags submonoid, range, product, map, comap -/ variables {M N P : Type*} [monoid M] [monoid N] [monoid P] (S : submonoid M) /-! ### Conversion to/from `additive`/`multiplicative` -/ /-- Map from submonoids of monoid `M` to `add_submonoid`s of `additive M`. -/ def submonoid.to_add_submonoid {M : Type*} [monoid M] (S : submonoid M) : add_submonoid (additive M) := { carrier := S.carrier, zero_mem' := S.one_mem', add_mem' := S.mul_mem' } /-- Map from `add_submonoid`s of `additive M` to submonoids of `M`. -/ def submonoid.of_add_submonoid {M : Type*} [monoid M] (S : add_submonoid (additive M)) : submonoid M := { carrier := S.carrier, one_mem' := S.zero_mem', mul_mem' := S.add_mem' } /-- Map from `add_submonoid`s of `add_monoid M` to submonoids of `multiplicative M`. -/ def add_submonoid.to_submonoid {M : Type*} [add_monoid M] (S : add_submonoid M) : submonoid (multiplicative M) := { carrier := S.carrier, one_mem' := S.zero_mem', mul_mem' := S.add_mem' } /-- Map from submonoids of `multiplicative M` to `add_submonoid`s of `add_monoid M`. -/ def add_submonoid.of_submonoid {M : Type*} [add_monoid M] (S : submonoid (multiplicative M)) : add_submonoid M := { carrier := S.carrier, zero_mem' := S.one_mem', add_mem' := S.mul_mem' } /-- Submonoids of monoid `M` are isomorphic to additive submonoids of `additive M`. -/ def submonoid.add_submonoid_equiv (M : Type*) [monoid M] : submonoid M ≃ add_submonoid (additive M) := { to_fun := submonoid.to_add_submonoid, inv_fun := submonoid.of_add_submonoid, left_inv := λ x, by cases x; refl, right_inv := λ x, by cases x; refl } namespace submonoid open set /-! ### `comap` and `map` -/ /-- The preimage of a submonoid along a monoid homomorphism is a submonoid. -/ @[to_additive "The preimage of an `add_submonoid` along an `add_monoid` homomorphism is an `add_submonoid`."] def comap (f : M →* N) (S : submonoid N) : submonoid M := { carrier := (f ⁻¹' S), one_mem' := show f 1 ∈ S, by rw f.map_one; exact S.one_mem, mul_mem' := λ a b ha hb, show f (a * b) ∈ S, by rw f.map_mul; exact S.mul_mem ha hb } @[simp, to_additive] lemma coe_comap (S : submonoid N) (f : M →* N) : (S.comap f : set M) = f ⁻¹' S := rfl @[simp, to_additive] lemma mem_comap {S : submonoid N} {f : M →* N} {x : M} : x ∈ S.comap f ↔ f x ∈ S := iff.rfl @[to_additive] lemma comap_comap (S : submonoid P) (g : N →* P) (f : M →* N) : (S.comap g).comap f = S.comap (g.comp f) := rfl /-- The image of a submonoid along a monoid homomorphism is a submonoid. -/ @[to_additive "The image of an `add_submonoid` along an `add_monoid` homomorphism is an `add_submonoid`."] def map (f : M →* N) (S : submonoid M) : submonoid N := { carrier := (f '' S), one_mem' := ⟨1, S.one_mem, f.map_one⟩, mul_mem' := begin rintros _ _ ⟨x, hx, rfl⟩ ⟨y, hy, rfl⟩, exact ⟨x * y, S.mul_mem hx hy, by rw f.map_mul; refl⟩ end } @[simp, to_additive] lemma coe_map (f : M →* N) (S : submonoid M) : (S.map f : set N) = f '' S := rfl @[simp, to_additive] lemma mem_map {f : M →* N} {S : submonoid M} {y : N} : y ∈ S.map f ↔ ∃ x ∈ S, f x = y := mem_image_iff_bex @[to_additive] lemma map_map (g : N →* P) (f : M →* N) : (S.map f).map g = S.map (g.comp f) := ext' $ image_image _ _ _ @[to_additive] lemma map_le_iff_le_comap {f : M →* N} {S : submonoid M} {T : submonoid N} : S.map f ≤ T ↔ S ≤ T.comap f := image_subset_iff @[to_additive] lemma gc_map_comap (f : M →* N) : galois_connection (map f) (comap f) := λ S T, map_le_iff_le_comap @[to_additive] lemma map_sup (S T : submonoid M) (f : M →* N) : (S ⊔ T).map f = S.map f ⊔ T.map f := (gc_map_comap f).l_sup @[to_additive] lemma map_supr {ι : Sort*} (f : M →* N) (s : ι → submonoid M) : (supr s).map f = ⨆ i, (s i).map f := (gc_map_comap f).l_supr @[to_additive] lemma comap_inf (S T : submonoid N) (f : M →* N) : (S ⊓ T).comap f = S.comap f ⊓ T.comap f := (gc_map_comap f).u_inf @[to_additive] lemma comap_infi {ι : Sort*} (f : M →* N) (s : ι → submonoid N) : (infi s).comap f = ⨅ i, (s i).comap f := (gc_map_comap f).u_infi @[simp, to_additive] lemma map_bot (f : M →* N) : (⊥ : submonoid M).map f = ⊥ := (gc_map_comap f).l_bot @[simp, to_additive] lemma comap_top (f : M →* N) : (⊤ : submonoid N).comap f = ⊤ := (gc_map_comap f).u_top @[simp, to_additive] lemma map_id (S : submonoid M) : S.map (monoid_hom.id M) = S := ext (λ x, ⟨λ ⟨_, h, rfl⟩, h, λ h, ⟨_, h, rfl⟩⟩) /-- A submonoid of a monoid inherits a multiplication. -/ @[to_additive "An `add_submonoid` of an `add_monoid` inherits an addition."] instance has_mul : has_mul S := ⟨λ a b, ⟨a.1 * b.1, S.mul_mem a.2 b.2⟩⟩ /-- A submonoid of a monoid inherits a 1. -/ @[to_additive "An `add_submonoid` of an `add_monoid` inherits a zero."] instance has_one : has_one S := ⟨⟨_, S.one_mem⟩⟩ @[simp, to_additive] lemma coe_mul (x y : S) : (↑(x * y) : M) = ↑x * ↑y := rfl @[simp, to_additive] lemma coe_one : ((1 : S) : M) = 1 := rfl attribute [norm_cast] coe_mul coe_one attribute [norm_cast] add_submonoid.coe_add add_submonoid.coe_zero /-- A submonoid of a monoid inherits a monoid structure. -/ @[to_additive to_add_monoid "An `add_submonoid` of an `add_monoid` inherits an `add_monoid` structure."] instance to_monoid {M : Type*} [monoid M] (S : submonoid M) : monoid S := by refine { mul := (*), one := 1, .. }; simp [mul_assoc, ← submonoid.coe_eq_coe] /-- A submonoid of a `comm_monoid` is a `comm_monoid`. -/ @[to_additive to_add_comm_monoid "An `add_submonoid` of an `add_comm_monoid` is an `add_comm_monoid`."] instance to_comm_monoid {M} [comm_monoid M] (S : submonoid M) : comm_monoid S := { mul_comm := λ _ _, subtype.eq $ mul_comm _ _, ..S.to_monoid} /-- The natural monoid hom from a submonoid of monoid `M` to `M`. -/ @[to_additive "The natural monoid hom from an `add_submonoid` of `add_monoid` `M` to `M`."] def subtype : S →* M := ⟨coe, rfl, λ _ _, rfl⟩ @[simp, to_additive] theorem coe_subtype : ⇑S.subtype = coe := rfl /-- Given `submonoid`s `s`, `t` of monoids `M`, `N` respectively, `s × t` as a submonoid of `M × N`. -/ @[to_additive prod "Given `add_submonoid`s `s`, `t` of `add_monoid`s `A`, `B` respectively, `s × t` as an `add_submonoid` of `A × B`."] def prod (s : submonoid M) (t : submonoid N) : submonoid (M × N) := { carrier := (s : set M).prod t, one_mem' := ⟨s.one_mem, t.one_mem⟩, mul_mem' := λ p q hp hq, ⟨s.mul_mem hp.1 hq.1, t.mul_mem hp.2 hq.2⟩ } @[to_additive coe_prod] lemma coe_prod (s : submonoid M) (t : submonoid N) : (s.prod t : set (M × N)) = (s : set M).prod (t : set N) := rfl @[to_additive mem_prod] lemma mem_prod {s : submonoid M} {t : submonoid N} {p : M × N} : p ∈ s.prod t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl @[to_additive prod_mono] lemma prod_mono {s₁ s₂ : submonoid M} {t₁ t₂ : submonoid N} (hs : s₁ ≤ s₂) (ht : t₁ ≤ t₂) : s₁.prod t₁ ≤ s₂.prod t₂ := set.prod_mono hs ht @[to_additive prod_top] lemma prod_top (s : submonoid M) : s.prod (⊤ : submonoid N) = s.comap (monoid_hom.fst M N) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst] @[to_additive top_prod] lemma top_prod (s : submonoid N) : (⊤ : submonoid M).prod s = s.comap (monoid_hom.snd M N) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd] @[simp, to_additive top_prod_top] lemma top_prod_top : (⊤ : submonoid M).prod (⊤ : submonoid N) = ⊤ := (top_prod _).trans $ comap_top _ @[to_additive] lemma bot_prod_bot : (⊥ : submonoid M).prod (⊥ : submonoid N) = ⊥ := ext' $ by simp [coe_prod, prod.one_eq_mk] /-- The product of submonoids is isomorphic to their product as monoids. -/ @[to_additive prod_equiv "The product of additive submonoids is isomorphic to their product as additive monoids"] def prod_equiv (s : submonoid M) (t : submonoid N) : s.prod t ≃* s × t := { map_mul' := λ x y, rfl, .. equiv.set.prod ↑s ↑t } open monoid_hom @[to_additive] lemma map_inl (s : submonoid M) : s.map (inl M N) = s.prod ⊥ := ext $ λ p, ⟨λ ⟨x, hx, hp⟩, hp ▸ ⟨hx, set.mem_singleton 1⟩, λ ⟨hps, hp1⟩, ⟨p.1, hps, prod.ext rfl $ (set.eq_of_mem_singleton hp1).symm⟩⟩ @[to_additive] lemma map_inr (s : submonoid N) : s.map (inr M N) = prod ⊥ s := ext $ λ p, ⟨λ ⟨x, hx, hp⟩, hp ▸ ⟨set.mem_singleton 1, hx⟩, λ ⟨hp1, hps⟩, ⟨p.2, hps, prod.ext (set.eq_of_mem_singleton hp1).symm rfl⟩⟩ @[simp, to_additive prod_bot_sup_bot_prod] lemma prod_bot_sup_bot_prod (s : submonoid M) (t : submonoid N) : (s.prod ⊥) ⊔ (prod ⊥ t) = s.prod t := le_antisymm (sup_le (prod_mono (le_refl s) bot_le) (prod_mono bot_le (le_refl t))) $ assume p hp, prod.fst_mul_snd p ▸ mul_mem _ ((le_sup_left : s.prod ⊥ ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨hp.1, set.mem_singleton 1⟩) ((le_sup_right : prod ⊥ t ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨set.mem_singleton 1, hp.2⟩) end submonoid namespace monoid_hom open submonoid /-- The range of a monoid homomorphism is a submonoid. -/ @[to_additive "The range of an `add_monoid_hom` is an `add_submonoid`."] def mrange (f : M →* N) : submonoid N := (⊤ : submonoid M).map f @[simp, to_additive] lemma coe_mrange (f : M →* N) : (f.mrange : set N) = set.range f := set.image_univ @[simp, to_additive] lemma mem_mrange {f : M →* N} {y : N} : y ∈ f.mrange ↔ ∃ x, f x = y := by simp [mrange] @[to_additive] lemma map_mrange (g : N →* P) (f : M →* N) : f.mrange.map g = (g.comp f).mrange := (⊤ : submonoid M).map_map g f @[to_additive] lemma mrange_top_iff_surjective {N} [monoid N] {f : M →* N} : f.mrange = (⊤ : submonoid N) ↔ function.surjective f := submonoid.ext'_iff.trans $ iff.trans (by rw [coe_mrange, coe_top]) set.range_iff_surjective /-- The range of a surjective monoid hom is the whole of the codomain. -/ @[to_additive "The range of a surjective `add_monoid` hom is the whole of the codomain."] lemma mrange_top_of_surjective {N} [monoid N] (f : M →* N) (hf : function.surjective f) : f.mrange = (⊤ : submonoid N) := mrange_top_iff_surjective.2 hf @[to_additive] lemma mclosure_preimage_le (f : M →* N) (s : set N) : closure (f ⁻¹' s) ≤ (closure s).comap f := closure_le.2 $ λ x hx, mem_coe.2 $ mem_comap.2 $ subset_closure hx /-- The image under a monoid hom of the submonoid generated by a set equals the submonoid generated by the image of the set. -/ @[to_additive "The image under an `add_monoid` hom of the `add_submonoid` generated by a set equals the `add_submonoid` generated by the image of the set."] lemma map_mclosure (f : M →* N) (s : set M) : (closure s).map f = closure (f '' s) := le_antisymm (map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image _ _) (mclosure_preimage_le _ _)) (closure_le.2 $ set.image_subset _ subset_closure) /-- Restriction of a monoid hom to a submonoid of the domain. -/ @[to_additive "Restriction of an add_monoid hom to an `add_submonoid` of the domain."] def mrestrict {N : Type*} [monoid N] (f : M →* N) (S : submonoid M) : S →* N := f.comp S.subtype @[simp, to_additive] lemma mrestrict_apply {N : Type*} [monoid N] (f : M →* N) (x : S) : f.mrestrict S x = f x := rfl /-- Restriction of a monoid hom to a submonoid of the codomain. -/ @[to_additive "Restriction of an `add_monoid` hom to an `add_submonoid` of the codomain."] def cod_mrestrict (f : M →* N) (S : submonoid N) (h : ∀ x, f x ∈ S) : M →* S := { to_fun := λ n, ⟨f n, h n⟩, map_one' := subtype.eq f.map_one, map_mul' := λ x y, subtype.eq (f.map_mul x y) } /-- Restriction of a monoid hom to its range interpreted as a submonoid. -/ @[to_additive "Restriction of an `add_monoid` hom to its range interpreted as a submonoid."] def mrange_restrict {N} [monoid N] (f : M →* N) : M →* f.mrange := f.cod_mrestrict f.mrange $ λ x, ⟨x, submonoid.mem_top x, rfl⟩ @[simp, to_additive] lemma coe_mrange_restrict {N} [monoid N] (f : M →* N) (x : M) : (f.mrange_restrict x : N) = f x := rfl end monoid_hom namespace submonoid open monoid_hom @[to_additive] lemma mrange_inl : (inl M N).mrange = prod ⊤ ⊥ := map_inl ⊤ @[to_additive] lemma mrange_inr : (inr M N).mrange = prod ⊥ ⊤ := map_inr ⊤ @[to_additive] lemma mrange_inl' : (inl M N).mrange = comap (snd M N) ⊥ := mrange_inl.trans (top_prod _) @[to_additive] lemma mrange_inr' : (inr M N).mrange = comap (fst M N) ⊥ := mrange_inr.trans (prod_top _) @[simp, to_additive] lemma mrange_fst : (fst M N).mrange = ⊤ := (fst M N).mrange_top_of_surjective $ @prod.fst_surjective _ _ ⟨1⟩ @[simp, to_additive] lemma mrange_snd : (snd M N).mrange = ⊤ := (snd M N).mrange_top_of_surjective $ @prod.snd_surjective _ _ ⟨1⟩ @[simp, to_additive] lemma mrange_inl_sup_mrange_inr : (inl M N).mrange ⊔ (inr M N).mrange = ⊤ := by simp only [mrange_inl, mrange_inr, prod_bot_sup_bot_prod, top_prod_top] /-- The monoid hom associated to an inclusion of submonoids. -/ @[to_additive "The `add_monoid` hom associated to an inclusion of submonoids."] def inclusion {S T : submonoid M} (h : S ≤ T) : S →* T := S.subtype.cod_mrestrict _ (λ x, h x.2) @[simp, to_additive] lemma range_subtype (s : submonoid M) : s.subtype.mrange = s := ext' $ (coe_mrange _).trans $ subtype.range_coe end submonoid namespace mul_equiv variables {S} {T : submonoid M} /-- Makes the identity isomorphism from a proof that two submonoids of a multiplicative monoid are equal. -/ @[to_additive add_submonoid_congr "Makes the identity additive isomorphism from a proof two submonoids of an additive monoid are equal."] def submonoid_congr (h : S = T) : S ≃* T := { map_mul' := λ _ _, rfl, ..equiv.set_congr $ submonoid.ext'_iff.1 h } end mul_equiv
a8b7d946a13874d8eaae63a9060c15148c13755a
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/set/intervals/infinite_auto.lean
eb1f792b4e2543b1a1dc6157c4e14c3cf995c3f2
[]
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,706
lean
/- Copyright (c) 2020 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.set.finite import Mathlib.PostPort universes u_1 namespace Mathlib /-! # Infinitude of intervals Bounded intervals in dense orders are infinite, as are unbounded intervals in orders that are unbounded on the appropriate side. -/ namespace set theorem Ioo.infinite {α : Type u_1} [preorder α] [densely_ordered α] {a : α} {b : α} (h : a < b) : infinite (Ioo a b) := sorry theorem Ico.infinite {α : Type u_1} [preorder α] [densely_ordered α] {a : α} {b : α} (h : a < b) : infinite (Ico a b) := infinite_mono Ioo_subset_Ico_self (Ioo.infinite h) theorem Ioc.infinite {α : Type u_1} [preorder α] [densely_ordered α] {a : α} {b : α} (h : a < b) : infinite (Ioc a b) := infinite_mono Ioo_subset_Ioc_self (Ioo.infinite h) theorem Icc.infinite {α : Type u_1} [preorder α] [densely_ordered α] {a : α} {b : α} (h : a < b) : infinite (Icc a b) := infinite_mono Ioo_subset_Icc_self (Ioo.infinite h) theorem Iio.infinite {α : Type u_1} [preorder α] [no_bot_order α] {b : α} : infinite (Iio b) := sorry theorem Iic.infinite {α : Type u_1} [preorder α] [no_bot_order α] {b : α} : infinite (Iic b) := infinite_mono Iio_subset_Iic_self Iio.infinite theorem Ioi.infinite {α : Type u_1} [preorder α] [no_top_order α] {a : α} : infinite (Ioi a) := Iio.infinite theorem Ici.infinite {α : Type u_1} [preorder α] [no_top_order α] {a : α} : infinite (Ici a) := infinite_mono Ioi_subset_Ici_self Ioi.infinite end Mathlib
00979c53a13288dfbcf589ff9c3e76f979498b66
e0038484ecdd1beda33e5d88605201533d5f4297
/Lean/LEAN01.lean
9f6ac00e5651fa956bc58f9895959ad23fe992a6
[ "MIT" ]
permissive
Brethland/LEARNING-STUFF
aa2899800117a90ad5b50b5109ee7aa138a51940
eb2cef0556efb9a4ce11783f8516789ea48cc344
refs/heads/master
1,633,628,909,614
1,632,827,784,000
1,632,827,784,000
206,292,930
2
1
null
null
null
null
UTF-8
Lean
false
false
1,107
lean
example (A B : Prop) : A ∧ ¬ B → ¬ B ∧ A := assume h, and.intro (and.right h) (and.left h) lemma em (A : Prop) : A ∨ ¬ A := show A ∨ ¬ A, from sorry example : true := trivial example (A B : Prop) (a : A) (b : B) : A ∧ B := show A ∧ B, from and.intro a b section exercises variables A B C D : Prop example : A ∧ (A → B) → B := assume ⟨h₁ , h₂⟩, h₂ h₁ example : A → ¬ (¬ A ∧ B) := assume : A, assume ⟨ h₁ , h₂ ⟩, show false, from h₁ this example : ¬ (A ∧ B) → (A → ¬ B) := assume h, assume a, assume b, h ⟨ a , b ⟩ example (h₁ : A ∨ B) (h₂ : A → C) (h₃ : B → D) : C ∨ D := or.elim h₁ (assume a, or.inl (h₂ a)) (assume b, or.inr (h₃ b)) example (h : ¬ A ∧ ¬ B) : ¬ (A ∨ B) := assume : A ∨ B, or.elim this (assume a, have ¬ A, from h.left, show false, from this a) (assume b, have ¬ B, from h.right, show false, from this b) example : ¬ (A ↔ ¬ A) := assume m : A ↔ ¬ A, or.elim (em A) (assume c, (m.mp c) c) (assume c, c (m.mpr c)) end exercises
186c219b573288cccbe0cefd0e643a9b951b0e98
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/algebra/monoid_algebra/basic.lean
be59f29d52cd23ddc2630194da08548b3cc05206
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
67,680
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Yury G. Kudryashov, Scott Morrison -/ import algebra.big_operators.finsupp import algebra.hom.non_unital_alg import linear_algebra.finsupp /-! # Monoid algebras When the domain of a `finsupp` has a multiplicative or additive structure, we can define a convolution product. To mathematicians this structure is known as the "monoid algebra", i.e. the finite formal linear combinations over a given semiring of elements of the monoid. The "group ring" ℤ[G] or the "group algebra" k[G] are typical uses. In fact the construction of the "monoid algebra" makes sense when `G` is not even a monoid, but merely a magma, i.e., when `G` carries a multiplication which is not required to satisfy any conditions at all. In this case the construction yields a not-necessarily-unital, not-necessarily-associative algebra but it is still adjoint to the forgetful functor from such algebras to magmas, and we prove this as `monoid_algebra.lift_magma`. In this file we define `monoid_algebra k G := G →₀ k`, and `add_monoid_algebra k G` in the same way, and then define the convolution product on these. When the domain is additive, this is used to define polynomials: ``` polynomial α := add_monoid_algebra ℕ α mv_polynomial σ α := add_monoid_algebra (σ →₀ ℕ) α ``` When the domain is multiplicative, e.g. a group, this will be used to define the group ring. ## Implementation note Unfortunately because additive and multiplicative structures both appear in both cases, it doesn't appear to be possible to make much use of `to_additive`, and we just settle for saying everything twice. Similarly, I attempted to just define `add_monoid_algebra k G := monoid_algebra k (multiplicative G)`, but the definitional equality `multiplicative G = G` leaks through everywhere, and seems impossible to use. -/ noncomputable theory open_locale big_operators open finset finsupp universes u₁ u₂ u₃ variables (k : Type u₁) (G : Type u₂) {R : Type*} /-! ### Multiplicative monoids -/ section variables [semiring k] /-- The monoid algebra over a semiring `k` generated by the monoid `G`. It is the type of finite formal `k`-linear combinations of terms of `G`, endowed with the convolution product. -/ @[derive [inhabited, add_comm_monoid]] def monoid_algebra : Type (max u₁ u₂) := G →₀ k instance : has_coe_to_fun (monoid_algebra k G) (λ _, G → k) := finsupp.has_coe_to_fun end namespace monoid_algebra variables {k G} section variables [semiring k] [non_unital_non_assoc_semiring R] /-- A non-commutative version of `monoid_algebra.lift`: given a additive homomorphism `f : k →+ R` and a homomorphism `g : G → R`, returns the additive homomorphism from `monoid_algebra k G` such that `lift_nc f g (single a b) = f b * g a`. If `f` is a ring homomorphism and the range of either `f` or `g` is in center of `R`, then the result is a ring homomorphism. If `R` is a `k`-algebra and `f = algebra_map k R`, then the result is an algebra homomorphism called `monoid_algebra.lift`. -/ def lift_nc (f : k →+ R) (g : G → R) : monoid_algebra k G →+ R := lift_add_hom (λ x : G, (add_monoid_hom.mul_right (g x)).comp f) @[simp] lemma lift_nc_single (f : k →+ R) (g : G → R) (a : G) (b : k) : lift_nc f g (single a b) = f b * g a := lift_add_hom_apply_single _ _ _ end section has_mul variables [semiring k] [has_mul G] /-- The product of `f g : monoid_algebra k G` is the finitely supported function whose value at `a` is the sum of `f x * g y` over all pairs `x, y` such that `x * y = a`. (Think of the group ring of a group.) -/ instance : has_mul (monoid_algebra k G) := ⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ * a₂) (b₁ * b₂)⟩ lemma mul_def {f g : monoid_algebra k G} : f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ * a₂) (b₁ * b₂)) := rfl instance : non_unital_non_assoc_semiring (monoid_algebra k G) := { zero := 0, mul := (*), add := (+), left_distrib := assume f g h, by simp only [mul_def, sum_add_index, mul_add, mul_zero, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_add], right_distrib := assume f g h, by simp only [mul_def, sum_add_index, add_mul, zero_mul, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_zero, sum_add], zero_mul := assume f, by simp only [mul_def, sum_zero_index], mul_zero := assume f, by simp only [mul_def, sum_zero_index, sum_zero], .. finsupp.add_comm_monoid } variables [semiring R] lemma lift_nc_mul {g_hom : Type*} [mul_hom_class g_hom G R] (f : k →+* R) (g : g_hom) (a b : monoid_algebra k G) (h_comm : ∀ {x y}, y ∈ a.support → commute (f (b x)) (g y)) : lift_nc (f : k →+ R) g (a * b) = lift_nc (f : k →+ R) g a * lift_nc (f : k →+ R) g b := begin conv_rhs { rw [← sum_single a, ← sum_single b] }, simp_rw [mul_def, (lift_nc _ g).map_finsupp_sum, lift_nc_single, finsupp.sum_mul, finsupp.mul_sum], refine finset.sum_congr rfl (λ y hy, finset.sum_congr rfl (λ x hx, _)), simp [mul_assoc, (h_comm hy).left_comm] end end has_mul section semigroup variables [semiring k] [semigroup G] [semiring R] instance : non_unital_semiring (monoid_algebra k G) := { zero := 0, mul := (*), add := (+), mul_assoc := assume f g h, by simp only [mul_def, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, add_mul, mul_add, add_assoc, mul_assoc, zero_mul, mul_zero, sum_zero, sum_add], .. monoid_algebra.non_unital_non_assoc_semiring} end semigroup section has_one variables [non_assoc_semiring R] [semiring k] [has_one G] /-- The unit of the multiplication is `single 1 1`, i.e. the function that is `1` at `1` and zero elsewhere. -/ instance : has_one (monoid_algebra k G) := ⟨single 1 1⟩ lemma one_def : (1 : monoid_algebra k G) = single 1 1 := rfl @[simp] lemma lift_nc_one {g_hom : Type*} [one_hom_class g_hom G R] (f : k →+* R) (g : g_hom) : lift_nc (f : k →+ R) g 1 = 1 := by simp [one_def] end has_one section mul_one_class variables [semiring k] [mul_one_class G] instance : non_assoc_semiring (monoid_algebra k G) := { one := 1, mul := (*), zero := 0, add := (+), nat_cast := λ n, single 1 n, nat_cast_zero := by simp [nat.cast], nat_cast_succ := λ _, by simp [nat.cast]; refl, one_mul := assume f, by simp only [mul_def, one_def, sum_single_index, zero_mul, single_zero, sum_zero, zero_add, one_mul, sum_single], mul_one := assume f, by simp only [mul_def, one_def, sum_single_index, mul_zero, single_zero, sum_zero, add_zero, mul_one, sum_single], ..monoid_algebra.non_unital_non_assoc_semiring } lemma nat_cast_def (n : ℕ) : (n : monoid_algebra k G) = single 1 n := rfl end mul_one_class /-! #### Semiring structure -/ section semiring variables [semiring k] [monoid G] instance : semiring (monoid_algebra k G) := { one := 1, mul := (*), zero := 0, add := (+), .. monoid_algebra.non_unital_semiring, .. monoid_algebra.non_assoc_semiring } variables [semiring R] /-- `lift_nc` as a `ring_hom`, for when `f x` and `g y` commute -/ def lift_nc_ring_hom (f : k →+* R) (g : G →* R) (h_comm : ∀ x y, commute (f x) (g y)) : monoid_algebra k G →+* R := { to_fun := lift_nc (f : k →+ R) g, map_one' := lift_nc_one _ _, map_mul' := λ a b, lift_nc_mul _ _ _ _ $ λ _ _ _, h_comm _ _, ..(lift_nc (f : k →+ R) g)} end semiring instance [comm_semiring k] [comm_semigroup G] : non_unital_comm_semiring (monoid_algebra k G) := { mul_comm := assume f g, begin simp only [mul_def, finsupp.sum, mul_comm], rw [finset.sum_comm], simp only [mul_comm] end, .. monoid_algebra.non_unital_semiring } instance [semiring k] [nontrivial k] [nonempty G]: nontrivial (monoid_algebra k G) := finsupp.nontrivial /-! #### Derived instances -/ section derived_instances instance [comm_semiring k] [comm_monoid G] : comm_semiring (monoid_algebra k G) := { .. monoid_algebra.non_unital_comm_semiring, .. monoid_algebra.semiring } instance [semiring k] [subsingleton k] : unique (monoid_algebra k G) := finsupp.unique_of_right instance [ring k] : add_comm_group (monoid_algebra k G) := finsupp.add_comm_group instance [ring k] [has_mul G] : non_unital_non_assoc_ring (monoid_algebra k G) := { .. monoid_algebra.add_comm_group, .. monoid_algebra.non_unital_non_assoc_semiring } instance [ring k] [semigroup G] : non_unital_ring (monoid_algebra k G) := { .. monoid_algebra.add_comm_group, .. monoid_algebra.non_unital_semiring } instance [ring k] [mul_one_class G] : non_assoc_ring (monoid_algebra k G) := { int_cast := λ z, single 1 (z : k), int_cast_of_nat := λ n, by simpa, int_cast_neg_succ_of_nat := λ n, by simpa, .. monoid_algebra.add_comm_group, .. monoid_algebra.non_assoc_semiring } lemma int_cast_def [ring k] [mul_one_class G] (z : ℤ) : (z : monoid_algebra k G) = single 1 z := rfl instance [ring k] [monoid G] : ring (monoid_algebra k G) := { .. monoid_algebra.non_assoc_ring, .. monoid_algebra.semiring } instance [comm_ring k] [comm_semigroup G] : non_unital_comm_ring (monoid_algebra k G) := { .. monoid_algebra.non_unital_comm_semiring, .. monoid_algebra.non_unital_ring } instance [comm_ring k] [comm_monoid G] : comm_ring (monoid_algebra k G) := { .. monoid_algebra.non_unital_comm_ring, .. monoid_algebra.ring } variables {S : Type*} instance [monoid R] [semiring k] [distrib_mul_action R k] : has_smul R (monoid_algebra k G) := finsupp.has_smul instance [monoid R] [semiring k] [distrib_mul_action R k] : distrib_mul_action R (monoid_algebra k G) := finsupp.distrib_mul_action G k instance [semiring R] [semiring k] [module R k] : module R (monoid_algebra k G) := finsupp.module G k instance [monoid R] [semiring k] [distrib_mul_action R k] [has_faithful_smul R k] [nonempty G] : has_faithful_smul R (monoid_algebra k G) := finsupp.has_faithful_smul instance [monoid R] [monoid S] [semiring k] [distrib_mul_action R k] [distrib_mul_action S k] [has_smul R S] [is_scalar_tower R S k] : is_scalar_tower R S (monoid_algebra k G) := finsupp.is_scalar_tower G k instance [monoid R] [monoid S] [semiring k] [distrib_mul_action R k] [distrib_mul_action S k] [smul_comm_class R S k] : smul_comm_class R S (monoid_algebra k G) := finsupp.smul_comm_class G k instance [monoid R] [semiring k] [distrib_mul_action R k] [distrib_mul_action Rᵐᵒᵖ k] [is_central_scalar R k] : is_central_scalar R (monoid_algebra k G) := finsupp.is_central_scalar G k /-- This is not an instance as it conflicts with `monoid_algebra.distrib_mul_action` when `G = kˣ`. -/ def comap_distrib_mul_action_self [group G] [semiring k] : distrib_mul_action G (monoid_algebra k G) := finsupp.comap_distrib_mul_action end derived_instances section misc_theorems variables [semiring k] local attribute [reducible] monoid_algebra lemma mul_apply [decidable_eq G] [has_mul G] (f g : monoid_algebra k G) (x : G) : (f * g) x = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, if a₁ * a₂ = x then b₁ * b₂ else 0) := begin rw [mul_def], simp only [finsupp.sum_apply, single_apply], end lemma mul_apply_antidiagonal [has_mul G] (f g : monoid_algebra k G) (x : G) (s : finset (G × G)) (hs : ∀ {p : G × G}, p ∈ s ↔ p.1 * p.2 = x) : (f * g) x = ∑ p in s, (f p.1 * g p.2) := let F : G × G → k := λ p, by classical; exact if p.1 * p.2 = x then f p.1 * g p.2 else 0 in calc (f * g) x = (∑ a₁ in f.support, ∑ a₂ in g.support, F (a₁, a₂)) : mul_apply f g x ... = ∑ p in f.support ×ˢ g.support, F p : finset.sum_product.symm ... = ∑ p in (f.support ×ˢ g.support).filter (λ p : G × G, p.1 * p.2 = x), f p.1 * g p.2 : (finset.sum_filter _ _).symm ... = ∑ p in s.filter (λ p : G × G, p.1 ∈ f.support ∧ p.2 ∈ g.support), f p.1 * g p.2 : sum_congr (by { ext, simp only [mem_filter, mem_product, hs, and_comm] }) (λ _ _, rfl) ... = ∑ p in s, f p.1 * g p.2 : sum_subset (filter_subset _ _) $ λ p hps hp, begin simp only [mem_filter, mem_support_iff, not_and, not_not] at hp ⊢, by_cases h1 : f p.1 = 0, { rw [h1, zero_mul] }, { rw [hp hps h1, mul_zero] } end lemma support_mul [has_mul G] [decidable_eq G] (a b : monoid_algebra k G) : (a * b).support ⊆ a.support.bUnion (λa₁, b.support.bUnion $ λa₂, {a₁ * a₂}) := subset.trans support_sum $ bUnion_mono $ assume a₁ _, subset.trans support_sum $ bUnion_mono $ assume a₂ _, support_single_subset @[simp] lemma single_mul_single [has_mul G] {a₁ a₂ : G} {b₁ b₂ : k} : (single a₁ b₁ : monoid_algebra k G) * single a₂ b₂ = single (a₁ * a₂) (b₁ * b₂) := (sum_single_index (by simp only [zero_mul, single_zero, sum_zero])).trans (sum_single_index (by rw [mul_zero, single_zero])) @[simp] lemma single_pow [monoid G] {a : G} {b : k} : ∀ n : ℕ, (single a b : monoid_algebra k G)^n = single (a^n) (b ^ n) | 0 := by { simp only [pow_zero], refl } | (n+1) := by simp only [pow_succ, single_pow n, single_mul_single] section /-- Like `finsupp.map_domain_zero`, but for the `1` we define in this file -/ @[simp] lemma map_domain_one {α : Type*} {β : Type*} {α₂ : Type*} [semiring β] [has_one α] [has_one α₂] {F : Type*} [one_hom_class F α α₂] (f : F) : (map_domain f (1 : monoid_algebra β α) : monoid_algebra β α₂) = (1 : monoid_algebra β α₂) := by simp_rw [one_def, map_domain_single, map_one] /-- Like `finsupp.map_domain_add`, but for the convolutive multiplication we define in this file -/ lemma map_domain_mul {α : Type*} {β : Type*} {α₂ : Type*} [semiring β] [has_mul α] [has_mul α₂] {F : Type*} [mul_hom_class F α α₂] (f : F) (x y : monoid_algebra β α) : (map_domain f (x * y : monoid_algebra β α) : monoid_algebra β α₂) = (map_domain f x * map_domain f y : monoid_algebra β α₂) := begin simp_rw [mul_def, map_domain_sum, map_domain_single, map_mul], rw finsupp.sum_map_domain_index, { congr, ext a b, rw finsupp.sum_map_domain_index, { simp }, { simp [mul_add] } }, { simp }, { simp [add_mul] } end variables (k G) /-- The embedding of a magma into its magma algebra. -/ @[simps] def of_magma [has_mul G] : G →ₙ* (monoid_algebra k G) := { to_fun := λ a, single a 1, map_mul' := λ a b, by simp only [mul_def, mul_one, sum_single_index, single_eq_zero, mul_zero], } /-- The embedding of a unital magma into its magma algebra. -/ @[simps] def of [mul_one_class G] : G →* monoid_algebra k G := { to_fun := λ a, single a 1, map_one' := rfl, .. of_magma k G } end lemma smul_of [mul_one_class G] (g : G) (r : k) : r • (of k G g) = single g r := by simp lemma of_injective [mul_one_class G] [nontrivial k] : function.injective (of k G) := λ a b h, by simpa using (single_eq_single_iff _ _ _ _).mp h /-- `finsupp.single` as a `monoid_hom` from the product type into the monoid algebra. Note the order of the elements of the product are reversed compared to the arguments of `finsupp.single`. -/ @[simps] def single_hom [mul_one_class G] : k × G →* monoid_algebra k G := { to_fun := λ a, single a.2 a.1, map_one' := rfl, map_mul' := λ a b, single_mul_single.symm } lemma mul_single_apply_aux [has_mul G] (f : monoid_algebra k G) {r : k} {x y z : G} (H : ∀ a, a * x = z ↔ a = y) : (f * single x r) z = f y * r := by classical; exact have A : ∀ a₁ b₁, (single x r).sum (λ a₂ b₂, ite (a₁ * a₂ = z) (b₁ * b₂) 0) = ite (a₁ * x = z) (b₁ * r) 0, from λ a₁ b₁, sum_single_index $ by simp, calc (f * single x r) z = sum f (λ a b, if (a = y) then (b * r) else 0) : by simp only [mul_apply, A, H] ... = if y ∈ f.support then f y * r else 0 : f.support.sum_ite_eq' _ _ ... = f y * r : by split_ifs with h; simp at h; simp [h] lemma mul_single_one_apply [mul_one_class G] (f : monoid_algebra k G) (r : k) (x : G) : (f * single 1 r) x = f x * r := f.mul_single_apply_aux $ λ a, by rw [mul_one] lemma support_mul_single [right_cancel_semigroup G] (f : monoid_algebra k G) (r : k) (hr : ∀ y, y * r = 0 ↔ y = 0) (x : G) : (f * single x r).support = f.support.map (mul_right_embedding x) := begin ext y, simp only [mem_support_iff, mem_map, exists_prop, mul_right_embedding_apply], by_cases H : ∃ a, a * x = y, { rcases H with ⟨a, rfl⟩, rw [mul_single_apply_aux f (λ _, mul_left_inj x)], simp [hr] }, { push_neg at H, classical, simp [mul_apply, H] } end lemma single_mul_apply_aux [has_mul G] (f : monoid_algebra k G) {r : k} {x y z : G} (H : ∀ a, x * a = y ↔ a = z) : (single x r * f) y = r * f z := by classical; exact ( have f.sum (λ a b, ite (x * a = y) (0 * b) 0) = 0, by simp, calc (single x r * f) y = sum f (λ a b, ite (x * a = y) (r * b) 0) : (mul_apply _ _ _).trans $ sum_single_index (by exact this) ... = f.sum (λ a b, ite (a = z) (r * b) 0) : by simp only [H] ... = if z ∈ f.support then (r * f z) else 0 : f.support.sum_ite_eq' _ _ ... = _ : by split_ifs with h; simp at h; simp [h]) lemma single_one_mul_apply [mul_one_class G] (f : monoid_algebra k G) (r : k) (x : G) : (single 1 r * f) x = r * f x := f.single_mul_apply_aux $ λ a, by rw [one_mul] lemma support_single_mul [left_cancel_semigroup G] (f : monoid_algebra k G) (r : k) (hr : ∀ y, r * y = 0 ↔ y = 0) (x : G) : (single x r * f).support = f.support.map (mul_left_embedding x) := begin ext y, simp only [mem_support_iff, mem_map, exists_prop, mul_left_embedding_apply], by_cases H : ∃ a, x * a = y, { rcases H with ⟨a, rfl⟩, rw [single_mul_apply_aux f (λ _, mul_right_inj x)], simp [hr] }, { push_neg at H, classical, simp [mul_apply, H] } end lemma lift_nc_smul [mul_one_class G] {R : Type*} [semiring R] (f : k →+* R) (g : G →* R) (c : k) (φ : monoid_algebra k G) : lift_nc (f : k →+ R) g (c • φ) = f c * lift_nc (f : k →+ R) g φ := begin suffices : (lift_nc ↑f g).comp (smul_add_hom k (monoid_algebra k G) c) = (add_monoid_hom.mul_left (f c)).comp (lift_nc ↑f g), from add_monoid_hom.congr_fun this φ, ext a b, simp [mul_assoc] end end misc_theorems /-! #### Non-unital, non-associative algebra structure -/ section non_unital_non_assoc_algebra variables (k) [monoid R] [semiring k] [distrib_mul_action R k] [has_mul G] instance is_scalar_tower_self [is_scalar_tower R k k] : is_scalar_tower R (monoid_algebra k G) (monoid_algebra k G) := ⟨λ t a b, begin ext m, classical, simp only [mul_apply, finsupp.smul_sum, smul_ite, smul_mul_assoc, sum_smul_index', zero_mul, if_t_t, implies_true_iff, eq_self_iff_true, sum_zero, coe_smul, smul_eq_mul, pi.smul_apply, smul_zero], end⟩ /-- Note that if `k` is a `comm_semiring` then we have `smul_comm_class k k k` and so we can take `R = k` in the below. In other words, if the coefficients are commutative amongst themselves, they also commute with the algebra multiplication. -/ instance smul_comm_class_self [smul_comm_class R k k] : smul_comm_class R (monoid_algebra k G) (monoid_algebra k G) := ⟨λ t a b, begin ext m, simp only [mul_apply, finsupp.sum, finset.smul_sum, smul_ite, mul_smul_comm, sum_smul_index', implies_true_iff, eq_self_iff_true, coe_smul, ite_eq_right_iff, smul_eq_mul, pi.smul_apply, mul_zero, smul_zero], end⟩ instance smul_comm_class_symm_self [smul_comm_class k R k] : smul_comm_class (monoid_algebra k G) R (monoid_algebra k G) := ⟨λ t a b, by { haveI := smul_comm_class.symm k R k, rw ← smul_comm, } ⟩ variables {A : Type u₃} [non_unital_non_assoc_semiring A] /-- A non_unital `k`-algebra homomorphism from `monoid_algebra k G` is uniquely defined by its values on the functions `single a 1`. -/ lemma non_unital_alg_hom_ext [distrib_mul_action k A] {φ₁ φ₂ : monoid_algebra k G →ₙₐ[k] A} (h : ∀ x, φ₁ (single x 1) = φ₂ (single x 1)) : φ₁ = φ₂ := non_unital_alg_hom.to_distrib_mul_action_hom_injective $ finsupp.distrib_mul_action_hom_ext' $ λ a, distrib_mul_action_hom.ext_ring (h a) /-- See note [partially-applied ext lemmas]. -/ @[ext] lemma non_unital_alg_hom_ext' [distrib_mul_action k A] {φ₁ φ₂ : monoid_algebra k G →ₙₐ[k] A} (h : φ₁.to_mul_hom.comp (of_magma k G) = φ₂.to_mul_hom.comp (of_magma k G)) : φ₁ = φ₂ := non_unital_alg_hom_ext k $ mul_hom.congr_fun h /-- The functor `G ↦ monoid_algebra k G`, from the category of magmas to the category of non-unital, non-associative algebras over `k` is adjoint to the forgetful functor in the other direction. -/ @[simps] def lift_magma [module k A] [is_scalar_tower k A A] [smul_comm_class k A A] : (G →ₙ* A) ≃ (monoid_algebra k G →ₙₐ[k] A) := { to_fun := λ f, { to_fun := λ a, a.sum (λ m t, t • f m), map_smul' := λ t' a, begin rw [finsupp.smul_sum, sum_smul_index'], { simp_rw smul_assoc, }, { intros m, exact zero_smul k (f m), }, end, map_mul' := λ a₁ a₂, begin let g : G → k → A := λ m t, t • f m, have h₁ : ∀ m, g m 0 = 0, { intros, exact zero_smul k (f m), }, have h₂ : ∀ m (t₁ t₂ : k), g m (t₁ + t₂) = g m t₁ + g m t₂, { intros, rw ← add_smul, }, simp_rw [finsupp.mul_sum, finsupp.sum_mul, smul_mul_smul, ← f.map_mul, mul_def, sum_comm a₂ a₁, sum_sum_index h₁ h₂, sum_single_index (h₁ _)], end, .. lift_add_hom (λ x, (smul_add_hom k A).flip (f x)) }, inv_fun := λ F, F.to_mul_hom.comp (of_magma k G), left_inv := λ f, by { ext m, simp only [non_unital_alg_hom.coe_mk, of_magma_apply, non_unital_alg_hom.to_mul_hom_eq_coe, sum_single_index, function.comp_app, one_smul, zero_smul, mul_hom.coe_comp, non_unital_alg_hom.coe_to_mul_hom], }, right_inv := λ F, by { ext m, simp only [non_unital_alg_hom.coe_mk, of_magma_apply, non_unital_alg_hom.to_mul_hom_eq_coe, sum_single_index, function.comp_app, one_smul, zero_smul, mul_hom.coe_comp, non_unital_alg_hom.coe_to_mul_hom], }, } end non_unital_non_assoc_algebra /-! #### Algebra structure -/ section algebra local attribute [reducible] monoid_algebra lemma single_one_comm [comm_semiring k] [mul_one_class G] (r : k) (f : monoid_algebra k G) : single 1 r * f = f * single 1 r := by { ext, rw [single_one_mul_apply, mul_single_one_apply, mul_comm] } /-- `finsupp.single 1` as a `ring_hom` -/ @[simps] def single_one_ring_hom [semiring k] [mul_one_class G] : k →+* monoid_algebra k G := { map_one' := rfl, map_mul' := λ x y, by rw [single_add_hom, single_mul_single, one_mul], ..finsupp.single_add_hom 1} /-- If `f : G → H` is a multiplicative homomorphism between two monoids, then `finsupp.map_domain f` is a ring homomorphism between their monoid algebras. -/ @[simps] def map_domain_ring_hom (k : Type*) {H F : Type*} [semiring k] [monoid G] [monoid H] [monoid_hom_class F G H] (f : F) : monoid_algebra k G →+* monoid_algebra k H := { map_one' := map_domain_one f, map_mul' := λ x y, map_domain_mul f x y, ..(finsupp.map_domain.add_monoid_hom f : monoid_algebra k G →+ monoid_algebra k H) } /-- If two ring homomorphisms from `monoid_algebra k G` are equal on all `single a 1` and `single 1 b`, then they are equal. -/ lemma ring_hom_ext {R} [semiring k] [mul_one_class G] [semiring R] {f g : monoid_algebra k G →+* R} (h₁ : ∀ b, f (single 1 b) = g (single 1 b)) (h_of : ∀ a, f (single a 1) = g (single a 1)) : f = g := ring_hom.coe_add_monoid_hom_injective $ add_hom_ext $ λ a b, by rw [← one_mul a, ← mul_one b, ← single_mul_single, f.coe_add_monoid_hom, g.coe_add_monoid_hom, f.map_mul, g.map_mul, h₁, h_of] /-- If two ring homomorphisms from `monoid_algebra k G` are equal on all `single a 1` and `single 1 b`, then they are equal. See note [partially-applied ext lemmas]. -/ @[ext] lemma ring_hom_ext' {R} [semiring k] [mul_one_class G] [semiring R] {f g : monoid_algebra k G →+* R} (h₁ : f.comp single_one_ring_hom = g.comp single_one_ring_hom) (h_of : (f : monoid_algebra k G →* R).comp (of k G) = (g : monoid_algebra k G →* R).comp (of k G)) : f = g := ring_hom_ext (ring_hom.congr_fun h₁) (monoid_hom.congr_fun h_of) /-- The instance `algebra k (monoid_algebra A G)` whenever we have `algebra k A`. In particular this provides the instance `algebra k (monoid_algebra k G)`. -/ instance {A : Type*} [comm_semiring k] [semiring A] [algebra k A] [monoid G] : algebra k (monoid_algebra A G) := { smul_def' := λ r a, by { ext, simp [single_one_mul_apply, algebra.smul_def, pi.smul_apply], }, commutes' := λ r f, by { ext, simp [single_one_mul_apply, mul_single_one_apply, algebra.commutes], }, ..single_one_ring_hom.comp (algebra_map k A) } /-- `finsupp.single 1` as a `alg_hom` -/ @[simps] def single_one_alg_hom {A : Type*} [comm_semiring k] [semiring A] [algebra k A] [monoid G] : A →ₐ[k] monoid_algebra A G := { commutes' := λ r, by { ext, simp, refl, }, ..single_one_ring_hom} @[simp] lemma coe_algebra_map {A : Type*} [comm_semiring k] [semiring A] [algebra k A] [monoid G] : ⇑(algebra_map k (monoid_algebra A G)) = single 1 ∘ (algebra_map k A) := rfl lemma single_eq_algebra_map_mul_of [comm_semiring k] [monoid G] (a : G) (b : k) : single a b = algebra_map k (monoid_algebra k G) b * of k G a := by simp lemma single_algebra_map_eq_algebra_map_mul_of {A : Type*} [comm_semiring k] [semiring A] [algebra k A] [monoid G] (a : G) (b : k) : single a (algebra_map k A b) = algebra_map k (monoid_algebra A G) b * of A G a := by simp lemma induction_on [semiring k] [monoid G] {p : monoid_algebra k G → Prop} (f : monoid_algebra k G) (hM : ∀ g, p (of k G g)) (hadd : ∀ f g : monoid_algebra k G, p f → p g → p (f + g)) (hsmul : ∀ (r : k) f, p f → p (r • f)) : p f := begin refine finsupp.induction_linear f _ (λ f g hf hg, hadd f g hf hg) (λ g r, _), { simpa using hsmul 0 (of k G 1) (hM 1) }, { convert hsmul r (of k G g) (hM g), simp only [mul_one, smul_single', of_apply] }, end end algebra section lift variables {k G} [comm_semiring k] [monoid G] variables {A : Type u₃} [semiring A] [algebra k A] {B : Type*} [semiring B] [algebra k B] /-- `lift_nc_ring_hom` as a `alg_hom`, for when `f` is an `alg_hom` -/ def lift_nc_alg_hom (f : A →ₐ[k] B) (g : G →* B) (h_comm : ∀ x y, commute (f x) (g y)) : monoid_algebra A G →ₐ[k] B := { to_fun := lift_nc_ring_hom (f : A →+* B) g h_comm, commutes' := by simp [lift_nc_ring_hom], ..(lift_nc_ring_hom (f : A →+* B) g h_comm)} /-- A `k`-algebra homomorphism from `monoid_algebra k G` is uniquely defined by its values on the functions `single a 1`. -/ lemma alg_hom_ext ⦃φ₁ φ₂ : monoid_algebra k G →ₐ[k] A⦄ (h : ∀ x, φ₁ (single x 1) = φ₂ (single x 1)) : φ₁ = φ₂ := alg_hom.to_linear_map_injective $ finsupp.lhom_ext' $ λ a, linear_map.ext_ring (h a) /-- See note [partially-applied ext lemmas]. -/ @[ext] lemma alg_hom_ext' ⦃φ₁ φ₂ : monoid_algebra k G →ₐ[k] A⦄ (h : (φ₁ : monoid_algebra k G →* A).comp (of k G) = (φ₂ : monoid_algebra k G →* A).comp (of k G)) : φ₁ = φ₂ := alg_hom_ext $ monoid_hom.congr_fun h variables (k G A) /-- Any monoid homomorphism `G →* A` can be lifted to an algebra homomorphism `monoid_algebra k G →ₐ[k] A`. -/ def lift : (G →* A) ≃ (monoid_algebra k G →ₐ[k] A) := { inv_fun := λ f, (f : monoid_algebra k G →* A).comp (of k G), to_fun := λ F, lift_nc_alg_hom (algebra.of_id k A) F $ λ _ _, algebra.commutes _ _, left_inv := λ f, by { ext, simp [lift_nc_alg_hom, lift_nc_ring_hom] }, right_inv := λ F, by { ext, simp [lift_nc_alg_hom, lift_nc_ring_hom] } } variables {k G A} lemma lift_apply' (F : G →* A) (f : monoid_algebra k G) : lift k G A F f = f.sum (λ a b, (algebra_map k A b) * F a) := rfl lemma lift_apply (F : G →* A) (f : monoid_algebra k G) : lift k G A F f = f.sum (λ a b, b • F a) := by simp only [lift_apply', algebra.smul_def] lemma lift_def (F : G →* A) : ⇑(lift k G A F) = lift_nc ((algebra_map k A : k →+* A) : k →+ A) F := rfl @[simp] lemma lift_symm_apply (F : monoid_algebra k G →ₐ[k] A) (x : G) : (lift k G A).symm F x = F (single x 1) := rfl lemma lift_of (F : G →* A) (x) : lift k G A F (of k G x) = F x := by rw [of_apply, ← lift_symm_apply, equiv.symm_apply_apply] @[simp] lemma lift_single (F : G →* A) (a b) : lift k G A F (single a b) = b • F a := by rw [lift_def, lift_nc_single, algebra.smul_def, ring_hom.coe_add_monoid_hom] lemma lift_unique' (F : monoid_algebra k G →ₐ[k] A) : F = lift k G A ((F : monoid_algebra k G →* A).comp (of k G)) := ((lift k G A).apply_symm_apply F).symm /-- Decomposition of a `k`-algebra homomorphism from `monoid_algebra k G` by its values on `F (single a 1)`. -/ lemma lift_unique (F : monoid_algebra k G →ₐ[k] A) (f : monoid_algebra k G) : F f = f.sum (λ a b, b • F (single a 1)) := by conv_lhs { rw lift_unique' F, simp [lift_apply] } /-- If `f : G → H` is a homomorphism between two magmas, then `finsupp.map_domain f` is a non-unital algebra homomorphism between their magma algebras. -/ @[simps] def map_domain_non_unital_alg_hom (k A : Type*) [comm_semiring k] [semiring A] [algebra k A] {G H F : Type*} [has_mul G] [has_mul H] [mul_hom_class F G H] (f : F) : monoid_algebra A G →ₙₐ[k] monoid_algebra A H := { map_mul' := λ x y, map_domain_mul f x y, map_smul' := λ r x, map_domain_smul r x, ..(finsupp.map_domain.add_monoid_hom f : monoid_algebra A G →+ monoid_algebra A H) } lemma map_domain_algebra_map (k A : Type*) {H F : Type*} [comm_semiring k] [semiring A] [algebra k A] [monoid H] [monoid_hom_class F G H] (f : F) (r : k) : map_domain f (algebra_map k (monoid_algebra A G) r) = algebra_map k (monoid_algebra A H) r := by simp only [coe_algebra_map, map_domain_single, map_one] /-- If `f : G → H` is a multiplicative homomorphism between two monoids, then `finsupp.map_domain f` is an algebra homomorphism between their monoid algebras. -/ @[simps] def map_domain_alg_hom (k A : Type*) [comm_semiring k] [semiring A] [algebra k A] {H F : Type*} [monoid H] [monoid_hom_class F G H] (f : F) : monoid_algebra A G →ₐ[k] monoid_algebra A H := { commutes' := map_domain_algebra_map k A f, ..map_domain_ring_hom A f} end lift section local attribute [reducible] monoid_algebra variables (k) /-- When `V` is a `k[G]`-module, multiplication by a group element `g` is a `k`-linear map. -/ def group_smul.linear_map [monoid G] [comm_semiring k] (V : Type u₃) [add_comm_monoid V] [module k V] [module (monoid_algebra k G) V] [is_scalar_tower k (monoid_algebra k G) V] (g : G) : V →ₗ[k] V := { to_fun := λ v, (single g (1 : k) • v : V), map_add' := λ x y, smul_add (single g (1 : k)) x y, map_smul' := λ c x, smul_algebra_smul_comm _ _ _ } @[simp] lemma group_smul.linear_map_apply [monoid G] [comm_semiring k] (V : Type u₃) [add_comm_monoid V] [module k V] [module (monoid_algebra k G) V] [is_scalar_tower k (monoid_algebra k G) V] (g : G) (v : V) : (group_smul.linear_map k V g) v = (single g (1 : k) • v : V) := rfl section variables {k} variables [monoid G] [comm_semiring k] {V W : Type u₃} [add_comm_monoid V] [module k V] [module (monoid_algebra k G) V] [is_scalar_tower k (monoid_algebra k G) V] [add_comm_monoid W] [module k W] [module (monoid_algebra k G) W] [is_scalar_tower k (monoid_algebra k G) W] (f : V →ₗ[k] W) (h : ∀ (g : G) (v : V), f (single g (1 : k) • v : V) = (single g (1 : k) • (f v) : W)) include h /-- Build a `k[G]`-linear map from a `k`-linear map and evidence that it is `G`-equivariant. -/ def equivariant_of_linear_of_comm : V →ₗ[monoid_algebra k G] W := { to_fun := f, map_add' := λ v v', by simp, map_smul' := λ c v, begin apply finsupp.induction c, { simp, }, { intros g r c' nm nz w, dsimp at *, simp only [add_smul, f.map_add, w, add_left_inj, single_eq_algebra_map_mul_of, ← smul_smul], erw [algebra_map_smul (monoid_algebra k G) r, algebra_map_smul (monoid_algebra k G) r, f.map_smul, h g v, of_apply], all_goals { apply_instance } } end, } @[simp] lemma equivariant_of_linear_of_comm_apply (v : V) : (equivariant_of_linear_of_comm f h) v = f v := rfl end end section universe ui variable {ι : Type ui} local attribute [reducible] monoid_algebra lemma prod_single [comm_semiring k] [comm_monoid G] {s : finset ι} {a : ι → G} {b : ι → k} : (∏ i in s, single (a i) (b i)) = single (∏ i in s, a i) (∏ i in s, b i) := finset.cons_induction_on s rfl $ λ a s has ih, by rw [prod_cons has, ih, single_mul_single, prod_cons has, prod_cons has] end section -- We now prove some additional statements that hold for group algebras. variables [semiring k] [group G] local attribute [reducible] monoid_algebra @[simp] lemma mul_single_apply (f : monoid_algebra k G) (r : k) (x y : G) : (f * single x r) y = f (y * x⁻¹) * r := f.mul_single_apply_aux $ λ a, eq_mul_inv_iff_mul_eq.symm @[simp] lemma single_mul_apply (r : k) (x : G) (f : monoid_algebra k G) (y : G) : (single x r * f) y = r * f (x⁻¹ * y) := f.single_mul_apply_aux $ λ z, eq_inv_mul_iff_mul_eq.symm lemma mul_apply_left (f g : monoid_algebra k G) (x : G) : (f * g) x = (f.sum $ λ a b, b * (g (a⁻¹ * x))) := calc (f * g) x = sum f (λ a b, (single a b * g) x) : by rw [← finsupp.sum_apply, ← finsupp.sum_mul, f.sum_single] ... = _ : by simp only [single_mul_apply, finsupp.sum] -- If we'd assumed `comm_semiring`, we could deduce this from `mul_apply_left`. lemma mul_apply_right (f g : monoid_algebra k G) (x : G) : (f * g) x = (g.sum $ λa b, (f (x * a⁻¹)) * b) := calc (f * g) x = sum g (λ a b, (f * single a b) x) : by rw [← finsupp.sum_apply, ← finsupp.mul_sum, g.sum_single] ... = _ : by simp only [mul_single_apply, finsupp.sum] end section span variables [semiring k] [mul_one_class G] /-- An element of `monoid_algebra R M` is in the subalgebra generated by its support. -/ lemma mem_span_support (f : monoid_algebra k G) : f ∈ submodule.span k (of k G '' (f.support : set G)) := by rw [of, monoid_hom.coe_mk, ← finsupp.supported_eq_span_single, finsupp.mem_supported] end span section opposite open finsupp mul_opposite variables [semiring k] /-- The opposite of an `monoid_algebra R I` equivalent as a ring to the `monoid_algebra Rᵐᵒᵖ Iᵐᵒᵖ` over the opposite ring, taking elements to their opposite. -/ @[simps {simp_rhs := tt}] protected noncomputable def op_ring_equiv [monoid G] : (monoid_algebra k G)ᵐᵒᵖ ≃+* monoid_algebra kᵐᵒᵖ Gᵐᵒᵖ := { map_mul' := begin dsimp only [add_equiv.to_fun_eq_coe, ←add_equiv.coe_to_add_monoid_hom], rw add_monoid_hom.map_mul_iff, ext i₁ r₁ i₂ r₂ : 6, simp end, ..op_add_equiv.symm.trans $ (finsupp.map_range.add_equiv (op_add_equiv : k ≃+ kᵐᵒᵖ)).trans $ finsupp.dom_congr op_equiv } @[simp] lemma op_ring_equiv_single [monoid G] (r : k) (x : G) : monoid_algebra.op_ring_equiv (op (single x r)) = single (op x) (op r) := by simp @[simp] lemma op_ring_equiv_symm_single [monoid G] (r : kᵐᵒᵖ) (x : Gᵐᵒᵖ) : monoid_algebra.op_ring_equiv.symm (single x r) = op (single x.unop r.unop) := by simp end opposite section submodule variables {k G} [comm_semiring k] [monoid G] variables {V : Type*} [add_comm_monoid V] variables [module k V] [module (monoid_algebra k G) V] [is_scalar_tower k (monoid_algebra k G) V] /-- A submodule over `k` which is stable under scalar multiplication by elements of `G` is a submodule over `monoid_algebra k G` -/ def submodule_of_smul_mem (W : submodule k V) (h : ∀ (g : G) (v : V), v ∈ W → (of k G g) • v ∈ W) : submodule (monoid_algebra k G) V := { carrier := W, zero_mem' := W.zero_mem', add_mem' := W.add_mem', smul_mem' := begin intros f v hv, rw [←finsupp.sum_single f, finsupp.sum, finset.sum_smul], simp_rw [←smul_of, smul_assoc], exact submodule.sum_smul_mem W _ (λ g _, h g v hv) end } end submodule end monoid_algebra /-! ### Additive monoids -/ section variables [semiring k] /-- The monoid algebra over a semiring `k` generated by the additive monoid `G`. It is the type of finite formal `k`-linear combinations of terms of `G`, endowed with the convolution product. -/ @[derive [inhabited, add_comm_monoid]] def add_monoid_algebra := G →₀ k instance : has_coe_to_fun (add_monoid_algebra k G) (λ _, G → k) := finsupp.has_coe_to_fun end namespace add_monoid_algebra variables {k G} section variables [semiring k] [non_unital_non_assoc_semiring R] /-- A non-commutative version of `add_monoid_algebra.lift`: given a additive homomorphism `f : k →+ R` and a map `g : multiplicative G → R`, returns the additive homomorphism from `add_monoid_algebra k G` such that `lift_nc f g (single a b) = f b * g a`. If `f` is a ring homomorphism and the range of either `f` or `g` is in center of `R`, then the result is a ring homomorphism. If `R` is a `k`-algebra and `f = algebra_map k R`, then the result is an algebra homomorphism called `add_monoid_algebra.lift`. -/ def lift_nc (f : k →+ R) (g : multiplicative G → R) : add_monoid_algebra k G →+ R := lift_add_hom (λ x : G, (add_monoid_hom.mul_right (g $ multiplicative.of_add x)).comp f) @[simp] lemma lift_nc_single (f : k →+ R) (g : multiplicative G → R) (a : G) (b : k) : lift_nc f g (single a b) = f b * g (multiplicative.of_add a) := lift_add_hom_apply_single _ _ _ end section has_mul variables [semiring k] [has_add G] /-- The product of `f g : add_monoid_algebra k G` is the finitely supported function whose value at `a` is the sum of `f x * g y` over all pairs `x, y` such that `x + y = a`. (Think of the product of multivariate polynomials where `α` is the additive monoid of monomial exponents.) -/ instance : has_mul (add_monoid_algebra k G) := ⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)⟩ lemma mul_def {f g : add_monoid_algebra k G} : f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)) := rfl instance : non_unital_non_assoc_semiring (add_monoid_algebra k G) := { zero := 0, mul := (*), add := (+), left_distrib := assume f g h, by simp only [mul_def, sum_add_index, mul_add, mul_zero, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_add], right_distrib := assume f g h, by simp only [mul_def, sum_add_index, add_mul, mul_zero, zero_mul, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_zero, sum_add], zero_mul := assume f, by simp only [mul_def, sum_zero_index], mul_zero := assume f, by simp only [mul_def, sum_zero_index, sum_zero], nsmul := λ n f, n • f, nsmul_zero' := by { intros, ext, simp [-nsmul_eq_mul, add_smul] }, nsmul_succ' := by { intros, ext, simp [-nsmul_eq_mul, nat.succ_eq_one_add, add_smul] }, .. finsupp.add_comm_monoid } variables [semiring R] lemma lift_nc_mul {g_hom : Type*} [mul_hom_class g_hom (multiplicative G) R] (f : k →+* R) (g : g_hom) (a b : add_monoid_algebra k G) (h_comm : ∀ {x y}, y ∈ a.support → commute (f (b x)) (g $ multiplicative.of_add y)) : lift_nc (f : k →+ R) g (a * b) = lift_nc (f : k →+ R) g a * lift_nc (f : k →+ R) g b := (monoid_algebra.lift_nc_mul f g _ _ @h_comm : _) end has_mul section has_one variables [semiring k] [has_zero G] [non_assoc_semiring R] /-- The unit of the multiplication is `single 1 1`, i.e. the function that is `1` at `0` and zero elsewhere. -/ instance : has_one (add_monoid_algebra k G) := ⟨single 0 1⟩ lemma one_def : (1 : add_monoid_algebra k G) = single 0 1 := rfl @[simp] lemma lift_nc_one {g_hom : Type*} [one_hom_class g_hom (multiplicative G) R] (f : k →+* R) (g : g_hom) : lift_nc (f : k →+ R) g 1 = 1 := (monoid_algebra.lift_nc_one f g : _) end has_one section semigroup variables [semiring k] [add_semigroup G] instance : non_unital_semiring (add_monoid_algebra k G) := { zero := 0, mul := (*), add := (+), mul_assoc := assume f g h, by simp only [mul_def, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, add_mul, mul_add, add_assoc, mul_assoc, zero_mul, mul_zero, sum_zero, sum_add], .. add_monoid_algebra.non_unital_non_assoc_semiring } end semigroup section mul_one_class variables [semiring k] [add_zero_class G] instance : non_assoc_semiring (add_monoid_algebra k G) := { one := 1, mul := (*), zero := 0, add := (+), nat_cast := λ n, single 0 n, nat_cast_zero := by simp [nat.cast], nat_cast_succ := λ _, by simp [nat.cast]; refl, one_mul := assume f, by simp only [mul_def, one_def, sum_single_index, zero_mul, single_zero, sum_zero, zero_add, one_mul, sum_single], mul_one := assume f, by simp only [mul_def, one_def, sum_single_index, mul_zero, single_zero, sum_zero, add_zero, mul_one, sum_single], .. add_monoid_algebra.non_unital_non_assoc_semiring } lemma nat_cast_def (n : ℕ) : (n : add_monoid_algebra k G) = single 0 n := rfl end mul_one_class /-! #### Semiring structure -/ section semiring instance {R : Type*} [monoid R] [semiring k] [distrib_mul_action R k] : has_smul R (add_monoid_algebra k G) := finsupp.has_smul variables [semiring k] [add_monoid G] instance : semiring (add_monoid_algebra k G) := { one := 1, mul := (*), zero := 0, add := (+), .. add_monoid_algebra.non_unital_semiring, .. add_monoid_algebra.non_assoc_semiring, } variables [semiring R] /-- `lift_nc` as a `ring_hom`, for when `f` and `g` commute -/ def lift_nc_ring_hom (f : k →+* R) (g : multiplicative G →* R) (h_comm : ∀ x y, commute (f x) (g y)) : add_monoid_algebra k G →+* R := { to_fun := lift_nc (f : k →+ R) g, map_one' := lift_nc_one _ _, map_mul' := λ a b, lift_nc_mul _ _ _ _ $ λ _ _ _, h_comm _ _, ..(lift_nc (f : k →+ R) g)} end semiring instance [comm_semiring k] [add_comm_semigroup G] : non_unital_comm_semiring (add_monoid_algebra k G) := { mul_comm := @mul_comm (monoid_algebra k $ multiplicative G) _, .. add_monoid_algebra.non_unital_semiring } instance [semiring k] [nontrivial k] [nonempty G] : nontrivial (add_monoid_algebra k G) := finsupp.nontrivial /-! #### Derived instances -/ section derived_instances instance [comm_semiring k] [add_comm_monoid G] : comm_semiring (add_monoid_algebra k G) := { .. add_monoid_algebra.non_unital_comm_semiring, .. add_monoid_algebra.semiring } instance [semiring k] [subsingleton k] : unique (add_monoid_algebra k G) := finsupp.unique_of_right instance [ring k] : add_comm_group (add_monoid_algebra k G) := finsupp.add_comm_group instance [ring k] [has_add G] : non_unital_non_assoc_ring (add_monoid_algebra k G) := { .. add_monoid_algebra.add_comm_group, .. add_monoid_algebra.non_unital_non_assoc_semiring } instance [ring k] [add_semigroup G] : non_unital_ring (add_monoid_algebra k G) := { .. add_monoid_algebra.add_comm_group, .. add_monoid_algebra.non_unital_semiring } instance [ring k] [add_zero_class G] : non_assoc_ring (add_monoid_algebra k G) := { int_cast := λ z, single 0 (z : k), int_cast_of_nat := λ n, by simpa, int_cast_neg_succ_of_nat := λ n, by simpa, .. add_monoid_algebra.add_comm_group, .. add_monoid_algebra.non_assoc_semiring } lemma int_cast_def [ring k] [add_zero_class G] (z : ℤ) : (z : add_monoid_algebra k G) = single 0 z := rfl instance [ring k] [add_monoid G] : ring (add_monoid_algebra k G) := { .. add_monoid_algebra.non_assoc_ring, .. add_monoid_algebra.semiring } instance [comm_ring k] [add_comm_semigroup G] : non_unital_comm_ring (add_monoid_algebra k G) := { .. add_monoid_algebra.non_unital_comm_semiring, .. add_monoid_algebra.non_unital_ring } instance [comm_ring k] [add_comm_monoid G] : comm_ring (add_monoid_algebra k G) := { .. add_monoid_algebra.non_unital_comm_ring, .. add_monoid_algebra.ring } variables {S : Type*} instance [monoid R] [semiring k] [distrib_mul_action R k] : distrib_mul_action R (add_monoid_algebra k G) := finsupp.distrib_mul_action G k instance [monoid R] [semiring k] [distrib_mul_action R k] [has_faithful_smul R k] [nonempty G] : has_faithful_smul R (add_monoid_algebra k G) := finsupp.has_faithful_smul instance [semiring R] [semiring k] [module R k] : module R (add_monoid_algebra k G) := finsupp.module G k instance [monoid R] [monoid S] [semiring k] [distrib_mul_action R k] [distrib_mul_action S k] [has_smul R S] [is_scalar_tower R S k] : is_scalar_tower R S (add_monoid_algebra k G) := finsupp.is_scalar_tower G k instance [monoid R] [monoid S] [semiring k] [distrib_mul_action R k] [distrib_mul_action S k] [smul_comm_class R S k] : smul_comm_class R S (add_monoid_algebra k G) := finsupp.smul_comm_class G k instance [monoid R] [semiring k] [distrib_mul_action R k] [distrib_mul_action Rᵐᵒᵖ k] [is_central_scalar R k] : is_central_scalar R (add_monoid_algebra k G) := finsupp.is_central_scalar G k /-! It is hard to state the equivalent of `distrib_mul_action G (add_monoid_algebra k G)` because we've never discussed actions of additive groups. -/ end derived_instances section misc_theorems variables [semiring k] lemma mul_apply [decidable_eq G] [has_add G] (f g : add_monoid_algebra k G) (x : G) : (f * g) x = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, if a₁ + a₂ = x then b₁ * b₂ else 0) := @monoid_algebra.mul_apply k (multiplicative G) _ _ _ _ _ _ lemma mul_apply_antidiagonal [has_add G] (f g : add_monoid_algebra k G) (x : G) (s : finset (G × G)) (hs : ∀ {p : G × G}, p ∈ s ↔ p.1 + p.2 = x) : (f * g) x = ∑ p in s, (f p.1 * g p.2) := @monoid_algebra.mul_apply_antidiagonal k (multiplicative G) _ _ _ _ _ s @hs lemma support_mul [decidable_eq G] [has_add G] (a b : add_monoid_algebra k G) : (a * b).support ⊆ a.support.bUnion (λa₁, b.support.bUnion $ λa₂, {a₁ + a₂}) := @monoid_algebra.support_mul k (multiplicative G) _ _ _ _ _ lemma single_mul_single [has_add G] {a₁ a₂ : G} {b₁ b₂ : k} : (single a₁ b₁ * single a₂ b₂ : add_monoid_algebra k G) = single (a₁ + a₂) (b₁ * b₂) := @monoid_algebra.single_mul_single k (multiplicative G) _ _ _ _ _ _ -- This should be a `@[simp]` lemma, but the simp_nf linter times out if we add this. -- Probably the correct fix is to make a `[add_]monoid_algebra.single` with the correct type, -- instead of relying on `finsupp.single`. lemma single_pow [add_monoid G] {a : G} {b : k} : ∀ n : ℕ, ((single a b)^n : add_monoid_algebra k G) = single (n • a) (b ^ n) | 0 := by { simp only [pow_zero, zero_nsmul], refl } | (n+1) := by rw [pow_succ, pow_succ, single_pow n, single_mul_single, add_comm, add_nsmul, one_nsmul] /-- Like `finsupp.map_domain_zero`, but for the `1` we define in this file -/ @[simp] lemma map_domain_one {α : Type*} {β : Type*} {α₂ : Type*} [semiring β] [has_zero α] [has_zero α₂] {F : Type*} [zero_hom_class F α α₂] (f : F) : (map_domain f (1 : add_monoid_algebra β α) : add_monoid_algebra β α₂) = (1 : add_monoid_algebra β α₂) := by simp_rw [one_def, map_domain_single, map_zero] /-- Like `finsupp.map_domain_add`, but for the convolutive multiplication we define in this file -/ lemma map_domain_mul {α : Type*} {β : Type*} {α₂ : Type*} [semiring β] [has_add α] [has_add α₂] {F : Type*} [add_hom_class F α α₂] (f : F) (x y : add_monoid_algebra β α) : (map_domain f (x * y : add_monoid_algebra β α) : add_monoid_algebra β α₂) = (map_domain f x * map_domain f y : add_monoid_algebra β α₂) := begin simp_rw [mul_def, map_domain_sum, map_domain_single, map_add], rw finsupp.sum_map_domain_index, { congr, ext a b, rw finsupp.sum_map_domain_index, { simp }, { simp [mul_add] } }, { simp }, { simp [add_mul] } end section variables (k G) /-- The embedding of an additive magma into its additive magma algebra. -/ @[simps] def of_magma [has_add G] : multiplicative G →ₙ* add_monoid_algebra k G := { to_fun := λ a, single a 1, map_mul' := λ a b, by simpa only [mul_def, mul_one, sum_single_index, single_eq_zero, mul_zero], } /-- Embedding of a magma with zero into its magma algebra. -/ def of [add_zero_class G] : multiplicative G →* add_monoid_algebra k G := { to_fun := λ a, single a 1, map_one' := rfl, .. of_magma k G } /-- Embedding of a magma with zero `G`, into its magma algebra, having `G` as source. -/ def of' : G → add_monoid_algebra k G := λ a, single a 1 end @[simp] lemma of_apply [add_zero_class G] (a : multiplicative G) : of k G a = single a.to_add 1 := rfl @[simp] lemma of'_apply (a : G) : of' k G a = single a 1 := rfl lemma of'_eq_of [add_zero_class G] (a : G) : of' k G a = of k G a := rfl lemma of_injective [nontrivial k] [add_zero_class G] : function.injective (of k G) := λ a b h, by simpa using (single_eq_single_iff _ _ _ _).mp h /-- `finsupp.single` as a `monoid_hom` from the product type into the additive monoid algebra. Note the order of the elements of the product are reversed compared to the arguments of `finsupp.single`. -/ @[simps] def single_hom [add_zero_class G] : k × multiplicative G →* add_monoid_algebra k G := { to_fun := λ a, single a.2.to_add a.1, map_one' := rfl, map_mul' := λ a b, single_mul_single.symm } lemma mul_single_apply_aux [has_add G] (f : add_monoid_algebra k G) (r : k) (x y z : G) (H : ∀ a, a + x = z ↔ a = y) : (f * single x r) z = f y * r := @monoid_algebra.mul_single_apply_aux k (multiplicative G) _ _ _ _ _ _ _ H lemma mul_single_zero_apply [add_zero_class G] (f : add_monoid_algebra k G) (r : k) (x : G) : (f * single 0 r) x = f x * r := f.mul_single_apply_aux r _ _ _ $ λ a, by rw [add_zero] lemma single_mul_apply_aux [has_add G] (f : add_monoid_algebra k G) (r : k) (x y z : G) (H : ∀ a, x + a = y ↔ a = z) : (single x r * f : add_monoid_algebra k G) y = r * f z := @monoid_algebra.single_mul_apply_aux k (multiplicative G) _ _ _ _ _ _ _ H lemma single_zero_mul_apply [add_zero_class G] (f : add_monoid_algebra k G) (r : k) (x : G) : (single 0 r * f : add_monoid_algebra k G) x = r * f x := f.single_mul_apply_aux r _ _ _ $ λ a, by rw [zero_add] lemma mul_single_apply [add_group G] (f : add_monoid_algebra k G) (r : k) (x y : G) : (f * single x r) y = f (y - x) * r := (sub_eq_add_neg y x).symm ▸ @monoid_algebra.mul_single_apply k (multiplicative G) _ _ _ _ _ _ lemma single_mul_apply [add_group G] (r : k) (x : G) (f : add_monoid_algebra k G) (y : G) : (single x r * f : add_monoid_algebra k G) y = r * f (- x + y) := @monoid_algebra.single_mul_apply k (multiplicative G) _ _ _ _ _ _ lemma support_mul_single [add_right_cancel_semigroup G] (f : add_monoid_algebra k G) (r : k) (hr : ∀ y, y * r = 0 ↔ y = 0) (x : G) : (f * single x r : add_monoid_algebra k G).support = f.support.map (add_right_embedding x) := @monoid_algebra.support_mul_single k (multiplicative G) _ _ _ _ hr _ lemma support_single_mul [add_left_cancel_semigroup G] (f : add_monoid_algebra k G) (r : k) (hr : ∀ y, r * y = 0 ↔ y = 0) (x : G) : (single x r * f : add_monoid_algebra k G).support = f.support.map (add_left_embedding x) := @monoid_algebra.support_single_mul k (multiplicative G) _ _ _ _ hr _ lemma lift_nc_smul {R : Type*} [add_zero_class G] [semiring R] (f : k →+* R) (g : multiplicative G →* R) (c : k) (φ : monoid_algebra k G) : lift_nc (f : k →+ R) g (c • φ) = f c * lift_nc (f : k →+ R) g φ := @monoid_algebra.lift_nc_smul k (multiplicative G) _ _ _ _ f g c φ lemma induction_on [add_monoid G] {p : add_monoid_algebra k G → Prop} (f : add_monoid_algebra k G) (hM : ∀ g, p (of k G (multiplicative.of_add g))) (hadd : ∀ f g : add_monoid_algebra k G, p f → p g → p (f + g)) (hsmul : ∀ (r : k) f, p f → p (r • f)) : p f := begin refine finsupp.induction_linear f _ (λ f g hf hg, hadd f g hf hg) (λ g r, _), { simpa using hsmul 0 (of k G (multiplicative.of_add 0)) (hM 0) }, { convert hsmul r (of k G (multiplicative.of_add g)) (hM g), simp only [mul_one, to_add_of_add, smul_single', of_apply] }, end /-- If `f : G → H` is an additive homomorphism between two additive monoids, then `finsupp.map_domain f` is a ring homomorphism between their add monoid algebras. -/ @[simps] def map_domain_ring_hom (k : Type*) [semiring k] {H F : Type*} [add_monoid G] [add_monoid H] [add_monoid_hom_class F G H] (f : F) : add_monoid_algebra k G →+* add_monoid_algebra k H := { map_one' := map_domain_one f, map_mul' := λ x y, map_domain_mul f x y, ..(finsupp.map_domain.add_monoid_hom f : monoid_algebra k G →+ monoid_algebra k H) } end misc_theorems section span variables [semiring k] /-- An element of `add_monoid_algebra R M` is in the submodule generated by its support. -/ lemma mem_span_support [add_zero_class G] (f : add_monoid_algebra k G) : f ∈ submodule.span k (of k G '' (f.support : set G)) := by rw [of, monoid_hom.coe_mk, ← finsupp.supported_eq_span_single, finsupp.mem_supported] /-- An element of `add_monoid_algebra R M` is in the subalgebra generated by its support, using unbundled inclusion. -/ lemma mem_span_support' (f : add_monoid_algebra k G) : f ∈ submodule.span k (of' k G '' (f.support : set G)) := by rw [of', ← finsupp.supported_eq_span_single, finsupp.mem_supported] end span end add_monoid_algebra /-! #### Conversions between `add_monoid_algebra` and `monoid_algebra` We have not defined `add_monoid_algebra k G = monoid_algebra k (multiplicative G)` because historically this caused problems; since the changes that have made `nsmul` definitional, this would be possible, but for now we just contruct the ring isomorphisms using `ring_equiv.refl _`. -/ /-- The equivalence between `add_monoid_algebra` and `monoid_algebra` in terms of `multiplicative` -/ protected def add_monoid_algebra.to_multiplicative [semiring k] [has_add G] : add_monoid_algebra k G ≃+* monoid_algebra k (multiplicative G) := { to_fun := equiv_map_domain multiplicative.of_add, map_mul' := λ x y, begin repeat {rw equiv_map_domain_eq_map_domain}, dsimp [multiplicative.of_add], convert monoid_algebra.map_domain_mul (mul_hom.id (multiplicative G)) _ _, end, ..finsupp.dom_congr multiplicative.of_add } /-- The equivalence between `monoid_algebra` and `add_monoid_algebra` in terms of `additive` -/ protected def monoid_algebra.to_additive [semiring k] [has_mul G] : monoid_algebra k G ≃+* add_monoid_algebra k (additive G) := { to_fun := equiv_map_domain additive.of_mul, map_mul' := λ x y, begin repeat {rw equiv_map_domain_eq_map_domain}, dsimp [additive.of_mul], convert monoid_algebra.map_domain_mul (mul_hom.id G) _ _, end, ..finsupp.dom_congr additive.of_mul } namespace add_monoid_algebra variables {k G} /-! #### Non-unital, non-associative algebra structure -/ section non_unital_non_assoc_algebra variables (k) [monoid R] [semiring k] [distrib_mul_action R k] [has_add G] instance is_scalar_tower_self [is_scalar_tower R k k] : is_scalar_tower R (add_monoid_algebra k G) (add_monoid_algebra k G) := @monoid_algebra.is_scalar_tower_self k (multiplicative G) R _ _ _ _ _ /-- Note that if `k` is a `comm_semiring` then we have `smul_comm_class k k k` and so we can take `R = k` in the below. In other words, if the coefficients are commutative amongst themselves, they also commute with the algebra multiplication. -/ instance smul_comm_class_self [smul_comm_class R k k] : smul_comm_class R (add_monoid_algebra k G) (add_monoid_algebra k G) := @monoid_algebra.smul_comm_class_self k (multiplicative G) R _ _ _ _ _ instance smul_comm_class_symm_self [smul_comm_class k R k] : smul_comm_class (add_monoid_algebra k G) R (add_monoid_algebra k G) := @monoid_algebra.smul_comm_class_symm_self k (multiplicative G) R _ _ _ _ _ variables {A : Type u₃} [non_unital_non_assoc_semiring A] /-- A non_unital `k`-algebra homomorphism from `add_monoid_algebra k G` is uniquely defined by its values on the functions `single a 1`. -/ lemma non_unital_alg_hom_ext [distrib_mul_action k A] {φ₁ φ₂ : add_monoid_algebra k G →ₙₐ[k] A} (h : ∀ x, φ₁ (single x 1) = φ₂ (single x 1)) : φ₁ = φ₂ := @monoid_algebra.non_unital_alg_hom_ext k (multiplicative G) _ _ _ _ _ φ₁ φ₂ h /-- See note [partially-applied ext lemmas]. -/ @[ext] lemma non_unital_alg_hom_ext' [distrib_mul_action k A] {φ₁ φ₂ : add_monoid_algebra k G →ₙₐ[k] A} (h : φ₁.to_mul_hom.comp (of_magma k G) = φ₂.to_mul_hom.comp (of_magma k G)) : φ₁ = φ₂ := @monoid_algebra.non_unital_alg_hom_ext' k (multiplicative G) _ _ _ _ _ φ₁ φ₂ h /-- The functor `G ↦ add_monoid_algebra k G`, from the category of magmas to the category of non-unital, non-associative algebras over `k` is adjoint to the forgetful functor in the other direction. -/ @[simps] def lift_magma [module k A] [is_scalar_tower k A A] [smul_comm_class k A A] : (multiplicative G →ₙ* A) ≃ (add_monoid_algebra k G →ₙₐ[k] A) := { to_fun := λ f, { to_fun := λ a, sum a (λ m t, t • f (multiplicative.of_add m)), .. (monoid_algebra.lift_magma k f : _)}, inv_fun := λ F, F.to_mul_hom.comp (of_magma k G), .. (monoid_algebra.lift_magma k : (multiplicative G →ₙ* A) ≃ (_ →ₙₐ[k] A)) } end non_unital_non_assoc_algebra /-! #### Algebra structure -/ section algebra local attribute [reducible] add_monoid_algebra /-- `finsupp.single 0` as a `ring_hom` -/ @[simps] def single_zero_ring_hom [semiring k] [add_monoid G] : k →+* add_monoid_algebra k G := { map_one' := rfl, map_mul' := λ x y, by rw [single_add_hom, single_mul_single, zero_add], ..finsupp.single_add_hom 0} /-- If two ring homomorphisms from `add_monoid_algebra k G` are equal on all `single a 1` and `single 0 b`, then they are equal. -/ lemma ring_hom_ext {R} [semiring k] [add_monoid G] [semiring R] {f g : add_monoid_algebra k G →+* R} (h₀ : ∀ b, f (single 0 b) = g (single 0 b)) (h_of : ∀ a, f (single a 1) = g (single a 1)) : f = g := @monoid_algebra.ring_hom_ext k (multiplicative G) R _ _ _ _ _ h₀ h_of /-- If two ring homomorphisms from `add_monoid_algebra k G` are equal on all `single a 1` and `single 0 b`, then they are equal. See note [partially-applied ext lemmas]. -/ @[ext] lemma ring_hom_ext' {R} [semiring k] [add_monoid G] [semiring R] {f g : add_monoid_algebra k G →+* R} (h₁ : f.comp single_zero_ring_hom = g.comp single_zero_ring_hom) (h_of : (f : add_monoid_algebra k G →* R).comp (of k G) = (g : add_monoid_algebra k G →* R).comp (of k G)) : f = g := ring_hom_ext (ring_hom.congr_fun h₁) (monoid_hom.congr_fun h_of) section opposite open finsupp mul_opposite variables [semiring k] /-- The opposite of an `add_monoid_algebra R I` is ring equivalent to the `add_monoid_algebra Rᵐᵒᵖ I` over the opposite ring, taking elements to their opposite. -/ @[simps {simp_rhs := tt}] protected noncomputable def op_ring_equiv [add_comm_monoid G] : (add_monoid_algebra k G)ᵐᵒᵖ ≃+* add_monoid_algebra kᵐᵒᵖ G := { map_mul' := begin dsimp only [add_equiv.to_fun_eq_coe, ←add_equiv.coe_to_add_monoid_hom], rw add_monoid_hom.map_mul_iff, ext i r i' r' : 6, dsimp, simp only [map_range_single, single_mul_single, ←op_mul, add_comm] end, ..mul_opposite.op_add_equiv.symm.trans (finsupp.map_range.add_equiv (mul_opposite.op_add_equiv : k ≃+ kᵐᵒᵖ))} @[simp] lemma op_ring_equiv_single [add_comm_monoid G] (r : k) (x : G) : add_monoid_algebra.op_ring_equiv (op (single x r)) = single x (op r) := by simp @[simp] lemma op_ring_equiv_symm_single [add_comm_monoid G] (r : kᵐᵒᵖ) (x : Gᵐᵒᵖ) : add_monoid_algebra.op_ring_equiv.symm (single x r) = op (single x r.unop) := by simp end opposite /-- The instance `algebra R (add_monoid_algebra k G)` whenever we have `algebra R k`. In particular this provides the instance `algebra k (add_monoid_algebra k G)`. -/ instance [comm_semiring R] [semiring k] [algebra R k] [add_monoid G] : algebra R (add_monoid_algebra k G) := { smul_def' := λ r a, by { ext, simp [single_zero_mul_apply, algebra.smul_def, pi.smul_apply], }, commutes' := λ r f, by { ext, simp [single_zero_mul_apply, mul_single_zero_apply, algebra.commutes], }, ..single_zero_ring_hom.comp (algebra_map R k) } /-- `finsupp.single 0` as a `alg_hom` -/ @[simps] def single_zero_alg_hom [comm_semiring R] [semiring k] [algebra R k] [add_monoid G] : k →ₐ[R] add_monoid_algebra k G := { commutes' := λ r, by { ext, simp, refl, }, ..single_zero_ring_hom} @[simp] lemma coe_algebra_map [comm_semiring R] [semiring k] [algebra R k] [add_monoid G] : (algebra_map R (add_monoid_algebra k G) : R → add_monoid_algebra k G) = single 0 ∘ (algebra_map R k) := rfl end algebra section lift variables {k G} [comm_semiring k] [add_monoid G] variables {A : Type u₃} [semiring A] [algebra k A] {B : Type*} [semiring B] [algebra k B] /-- `lift_nc_ring_hom` as a `alg_hom`, for when `f` is an `alg_hom` -/ def lift_nc_alg_hom (f : A →ₐ[k] B) (g : multiplicative G →* B) (h_comm : ∀ x y, commute (f x) (g y)) : add_monoid_algebra A G →ₐ[k] B := { to_fun := lift_nc_ring_hom (f : A →+* B) g h_comm, commutes' := by simp [lift_nc_ring_hom], ..(lift_nc_ring_hom (f : A →+* B) g h_comm)} /-- A `k`-algebra homomorphism from `monoid_algebra k G` is uniquely defined by its values on the functions `single a 1`. -/ lemma alg_hom_ext ⦃φ₁ φ₂ : add_monoid_algebra k G →ₐ[k] A⦄ (h : ∀ x, φ₁ (single x 1) = φ₂ (single x 1)) : φ₁ = φ₂ := @monoid_algebra.alg_hom_ext k (multiplicative G) _ _ _ _ _ _ _ h /-- See note [partially-applied ext lemmas]. -/ @[ext] lemma alg_hom_ext' ⦃φ₁ φ₂ : add_monoid_algebra k G →ₐ[k] A⦄ (h : (φ₁ : add_monoid_algebra k G →* A).comp (of k G) = (φ₂ : add_monoid_algebra k G →* A).comp (of k G)) : φ₁ = φ₂ := alg_hom_ext $ monoid_hom.congr_fun h variables (k G A) /-- Any monoid homomorphism `G →* A` can be lifted to an algebra homomorphism `monoid_algebra k G →ₐ[k] A`. -/ def lift : (multiplicative G →* A) ≃ (add_monoid_algebra k G →ₐ[k] A) := { inv_fun := λ f, (f : add_monoid_algebra k G →* A).comp (of k G), to_fun := λ F, { to_fun := lift_nc_alg_hom (algebra.of_id k A) F $ λ _ _, algebra.commutes _ _, .. @monoid_algebra.lift k (multiplicative G) _ _ A _ _ F}, .. @monoid_algebra.lift k (multiplicative G) _ _ A _ _ } variables {k G A} lemma lift_apply' (F : multiplicative G →* A) (f : monoid_algebra k G) : lift k G A F f = f.sum (λ a b, (algebra_map k A b) * F (multiplicative.of_add a)) := rfl lemma lift_apply (F : multiplicative G →* A) (f : monoid_algebra k G) : lift k G A F f = f.sum (λ a b, b • F (multiplicative.of_add a)) := by simp only [lift_apply', algebra.smul_def] lemma lift_def (F : multiplicative G →* A) : ⇑(lift k G A F) = lift_nc ((algebra_map k A : k →+* A) : k →+ A) F := rfl @[simp] lemma lift_symm_apply (F : add_monoid_algebra k G →ₐ[k] A) (x : multiplicative G) : (lift k G A).symm F x = F (single x.to_add 1) := rfl lemma lift_of (F : multiplicative G →* A) (x : multiplicative G) : lift k G A F (of k G x) = F x := by rw [of_apply, ← lift_symm_apply, equiv.symm_apply_apply] @[simp] lemma lift_single (F : multiplicative G →* A) (a b) : lift k G A F (single a b) = b • F (multiplicative.of_add a) := by rw [lift_def, lift_nc_single, algebra.smul_def, ring_hom.coe_add_monoid_hom] lemma lift_unique' (F : add_monoid_algebra k G →ₐ[k] A) : F = lift k G A ((F : add_monoid_algebra k G →* A).comp (of k G)) := ((lift k G A).apply_symm_apply F).symm /-- Decomposition of a `k`-algebra homomorphism from `monoid_algebra k G` by its values on `F (single a 1)`. -/ lemma lift_unique (F : add_monoid_algebra k G →ₐ[k] A) (f : monoid_algebra k G) : F f = f.sum (λ a b, b • F (single a 1)) := by conv_lhs { rw lift_unique' F, simp [lift_apply] } lemma alg_hom_ext_iff {φ₁ φ₂ : add_monoid_algebra k G →ₐ[k] A} : (∀ x, φ₁ (finsupp.single x 1) = φ₂ (finsupp.single x 1)) ↔ φ₁ = φ₂ := ⟨λ h, alg_hom_ext h, by rintro rfl _; refl⟩ end lift section local attribute [reducible] add_monoid_algebra universe ui variable {ι : Type ui} lemma prod_single [comm_semiring k] [add_comm_monoid G] {s : finset ι} {a : ι → G} {b : ι → k} : (∏ i in s, single (a i) (b i)) = single (∑ i in s, a i) (∏ i in s, b i) := finset.cons_induction_on s rfl $ λ a s has ih, by rw [prod_cons has, ih, single_mul_single, sum_cons has, prod_cons has] end lemma map_domain_algebra_map {A H F : Type*} [comm_semiring k] [semiring A] [algebra k A] [add_monoid G] [add_monoid H] [add_monoid_hom_class F G H] (f : F) (r : k) : map_domain f (algebra_map k (add_monoid_algebra A G) r) = algebra_map k (add_monoid_algebra A H) r := by simp only [function.comp_app, map_domain_single, add_monoid_algebra.coe_algebra_map, map_zero] /-- If `f : G → H` is a homomorphism between two additive magmas, then `finsupp.map_domain f` is a non-unital algebra homomorphism between their additive magma algebras. -/ @[simps] def map_domain_non_unital_alg_hom (k A : Type*) [comm_semiring k] [semiring A] [algebra k A] {G H F : Type*} [has_add G] [has_add H] [add_hom_class F G H] (f : F) : add_monoid_algebra A G →ₙₐ[k] add_monoid_algebra A H := { map_mul' := λ x y, map_domain_mul f x y, map_smul' := λ r x, map_domain_smul r x, ..(finsupp.map_domain.add_monoid_hom f : monoid_algebra A G →+ monoid_algebra A H) } /-- If `f : G → H` is an additive homomorphism between two additive monoids, then `finsupp.map_domain f` is an algebra homomorphism between their add monoid algebras. -/ @[simps] def map_domain_alg_hom (k A : Type*) [comm_semiring k] [semiring A] [algebra k A] [add_monoid G] {H F : Type*} [add_monoid H] [add_monoid_hom_class F G H] (f : F) : add_monoid_algebra A G →ₐ[k] add_monoid_algebra A H := { commutes' := map_domain_algebra_map f, ..map_domain_ring_hom A f} end add_monoid_algebra variables [comm_semiring R] (k G) /-- The algebra equivalence between `add_monoid_algebra` and `monoid_algebra` in terms of `multiplicative`. -/ def add_monoid_algebra.to_multiplicative_alg_equiv [semiring k] [algebra R k] [add_monoid G] : add_monoid_algebra k G ≃ₐ[R] monoid_algebra k (multiplicative G) := { commutes' := λ r, by simp [add_monoid_algebra.to_multiplicative], ..add_monoid_algebra.to_multiplicative k G } /-- The algebra equivalence between `monoid_algebra` and `add_monoid_algebra` in terms of `additive`. -/ def monoid_algebra.to_additive_alg_equiv [semiring k] [algebra R k] [monoid G] : monoid_algebra k G ≃ₐ[R] add_monoid_algebra k (additive G) := { commutes' := λ r, by simp [monoid_algebra.to_additive], ..monoid_algebra.to_additive k G }
8b0a5d5ee9a8216526d223aae8ec3a5b61cedcdd
271e26e338b0c14544a889c31c30b39c989f2e0f
/tests/lean/run/frontend1.lean
ef0785b4732853dad5f9cb005ca50338991a3215
[ "Apache-2.0" ]
permissive
dgorokho/lean4
805f99b0b60c545b64ac34ab8237a8504f89d7d4
e949a052bad59b1c7b54a82d24d516a656487d8a
refs/heads/master
1,607,061,363,851
1,578,006,086,000
1,578,006,086,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,846
lean
import Init.Lean.Elab open Lean open Lean.Elab def run (input : String) (failIff : Bool := true) : MetaIO Unit := do env ← MetaIO.getEnv; opts ← MetaIO.getOptions; let (env, messages) := process input env opts; messages.forM $ fun msg => IO.println msg; when (failIff && messages.hasErrors) $ throw (IO.userError "errors have been found"); when (!failIff && !messages.hasErrors) $ throw (IO.userError "there are no errors"); pure () def fail (input : String) : MetaIO Unit := run input false def M := IO Unit def zero := 0 def one := 1 def two := 2 def hello : String := "hello" def act1 : IO String := pure "hello" #eval run "#check @HasAdd.add" #eval run "#check [zero, one, two]" #eval run "#check id $ Nat.succ one" #eval run "#check HasAdd.add one two" #eval run "#check one + two > one ∧ True" #eval run "#check act1 >>= IO.println" #eval run "#check one + two == one" #eval fail "#check one + one + hello == hello ++ one" #eval run "#check Nat.add one $ Nat.add one two" #eval run "universe u universe v export HasToString (toString) section namespace foo.bla end bla end foo variable (p q : Prop) variable (_ b : _) variable {α : Type} variable {m : Type → Type} variable [Monad m] #check m #check Type #check Prop #check toString zero #check id Nat.zero (α := Nat) #check id _ (α := Nat) #check id Nat.zero #check id (α := Nat) #check @id Nat #check p #check α #check Nat.succ #check Nat.add #check id #check forall (α : Type), α → α #check (α : Type) → α → α #check {α : Type} → {β : Type} → M → (α → β) → α → β #check () #check run end" structure S1 := (x y : Nat := 0) structure S2 extends S1 := (z : Nat := 0) def fD {α} [HasToString α] (a b : α) : String := toString a ++ toString b structure S3 := (w : Nat := 0) (f : forall {α : Type} [HasToString α], α → α → String := @fD) structure S4 extends S2, S3 := (s : Nat := 0) def s4 : S4 := {} structure S (α : Type) := (field1 : S4 := {}) (field2 : S4 × S4 := ({}, {})) (field3 : α) (field4 : List α × Nat := ([], 0)) (vec : Array (α × α) := #[]) (map : HashMap String α := {}) inductive D (α : Type) | mk (a : α) (s : S4) : D def s : S Nat := { field3 := 0 } def d : D Nat := D.mk 10 {} def i : Nat := 10 def k : String := "hello" universes u class Monoid (α : Type u) := (one {} : α) (mul : α → α → α) def m : Monoid Nat := { one := 1, mul := Nat.mul } def f (x y z : Nat) : Nat := x + y + z #eval run "#check s4.x" #eval run "#check s.field1.x" #eval run "#check s.field2.fst" #eval run "#check s.field2.fst.w" #eval run "#check s.1.x" #eval run "#check s.2.1.x" #eval run "#check d.1" #eval run "#check d.2.x" #eval run "#check s4.f s4.x" #eval run "#check m.mul m.one" #eval run "#check s.field4.1.length.succ" #eval run "#check s.field4.1.map Nat.succ" #eval run "#check s.vec[i].1" #eval run "#check \"hello\"" #eval run "#check 1" #eval run "#check Nat.succ 1" #eval run "#check fun _ a (x y : Int) => x + y + a" #eval run "#check (one)" #eval run "#check ()" #eval run "#check (one, two, zero)" #eval run "#check (one, two, zero)" #eval run "#check (1 : Int)" #eval run "#check ((1, 2) : Nat × Int)" #eval run "#check (· + one)" #eval run "#check (· + · : Nat → Nat → Nat)" #eval run "#check (f one · zero)" #eval run "#check (f · · zero)" #eval run "#check fun (_ b : Nat) => b + 1" def foo {α β} (a : α) (b : β) (a' : α) : α := a def bla {α β} (f : α → β) (a : α) : β := f a -- #check fun x => foo x x.w s4 -- fails in old elaborator -- #check bla (fun x => x.w) s4 -- fails in the old elaborator -- #check #[1, 2, 3].foldl (fun r a => r.push a) #[] -- fails in the old elaborator #eval run "#check fun x => foo x x.w s4" #eval run "#check bla (fun x => x.w) s4" #eval run "#check #[1, 2, 3].foldl (fun r a => r.push a) #[]" #eval run "#check #[1, 2, 3].foldl (fun r a => (r.push a).push a) #[]" #eval run "#check #[1, 2, 3].foldl (fun r a => ((r.push a).push a).push a) #[]" #eval run "#check #[].push one $.push two $.push zero $.size.succ" #eval run "#check #[1, 2].foldl (fun r a => r.push a $.push a $.push a) #[]" #eval run "#check #[1, 2].foldl (init := #[]) $ fun r a => r.push a $.push a" #eval run "#check let x := one + zero; x + x" -- set_option trace.Elab true #eval run "#check (fun x => let v := x.w; v + v) s4" #eval run "#check fun x => foo x (let v := x.w; v + one) s4" #eval run "#check fun x => foo x (let v := x.w; let w := x.x; v + w + one) s4" #eval fail "#check id.{1,1}" #eval fail "#check @id.{0} Nat" #eval run "#check @id.{1} Nat" #eval run "universes u #check id.{u}" #eval fail "universes u #check id.{v}" #eval run "universes u #check Type u" #eval run "universes u #check Sort u" #eval run "#check Type 1" #eval run "#check Type 0" #eval run "universes u v #check Sort (max u v)" #eval run "universes u v #check Type (max u v)" #eval run "#check 'a'" #eval fail "#check #['a', \"hello\"]" #eval run "#check fun (a : Array Nat) => a.size" #eval run "#check if 0 = 1 then 'a' else 'b'" #eval run "#check fun (i : Nat) (a : Array Nat) => if h : i < a.size then a.get (Fin.mk i h) else i" #eval run "#check { x : Nat // x > 0 }" #eval run "#check { x // x > 0 }" #eval run "#check fun (i : Nat) (a : Array Nat) => if h : i < a.size then a.get ⟨i, h⟩ else i" #eval run "#check Prod.fst ⟨1, 2⟩" #eval run "#check let x := ⟨1, 2⟩; Prod.fst x" #eval run "#check show Nat from 1" #eval run "#check show Int from 1" #eval run "#check have Nat from one + zero; this + this" #eval run "#check have x : Nat from one + zero; x + x" #eval run "#check have Nat := one + zero; this + this" #eval run "#check have x : Nat := one + zero; x + x" #eval run "#check x + y where x := 1; where y := x + x" #eval run "#check let z := 2; x + y where x := z + 1; where y := x + x"
d017d08ecb48a797fa78ced6446e1de008f4f2bb
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/stage0/src/Lean/Class.lean
d02d7dc640c2137633d5456b20d33c4f3d42813b
[ "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
6,155
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.Attributes namespace Lean inductive ClassEntry | «class» (name : Name) (hasOutParam : Bool) | «instance» (name : Name) (ofClass : Name) -- TODO: remove after we remove old type class resolution namespace ClassEntry @[inline] def getName : ClassEntry → Name | «class» n _ => n | «instance» n _ => n def lt (a b : ClassEntry) : Bool := Name.quickLt a.getName b.getName end ClassEntry structure ClassState := (classToInstances : SMap Name (List Name) := SMap.empty) -- TODO: delete (hasOutParam : SMap Name Bool := SMap.empty) -- We should keep only this one (instances : SMap Name Unit := SMap.empty) -- TODO: delete namespace ClassState instance : Inhabited ClassState := ⟨{}⟩ def addEntry (s : ClassState) (entry : ClassEntry) : ClassState := match entry with | ClassEntry.«class» clsName hasOutParam => { s with hasOutParam := s.hasOutParam.insert clsName hasOutParam } | ClassEntry.«instance» instName clsName => { s with instances := s.instances.insert instName (), classToInstances := match s.classToInstances.find? clsName with | some insts => s.classToInstances.insert clsName (instName :: insts) | none => s.classToInstances.insert clsName [instName] } def switch : ClassState → ClassState | ⟨m₁, m₂, m₃⟩ => ⟨m₁.switch, m₂.switch, m₃.switch⟩ end ClassState /- TODO: add support for scoped instances -/ builtin_initialize classExtension : SimplePersistentEnvExtension ClassEntry ClassState ← registerSimplePersistentEnvExtension { name := `classExt, addEntryFn := ClassState.addEntry, addImportedFn := fun es => (mkStateFromImportedEntries ClassState.addEntry {} es).switch } @[export lean_is_class] def isClass (env : Environment) (n : Name) : Bool := (classExtension.getState env).hasOutParam.contains n @[export lean_is_instance] def isInstance (env : Environment) (n : Name) : Bool := (classExtension.getState env).instances.contains n @[export lean_get_class_instances] def getClassInstances (env : Environment) (n : Name) : List Name := match (classExtension.getState env).classToInstances.find? n with | some insts => insts | none => [] @[export lean_has_out_params] def hasOutParams (env : Environment) (n : Name) : Bool := match (classExtension.getState env).hasOutParam.find? n with | some b => b | none => false @[export lean_is_out_param] def isOutParam (e : Expr) : Bool := e.isAppOfArity `outParam 1 /-- Auxiliary function for checking whether a class has `outParam`, and whether they are being correctly used. A regular (i.e., non `outParam`) must not depend on an `outParam`. Reason for this restriction: When performing type class resolution, we replace arguments that are `outParam`s with fresh metavariables. If regular parameters could depend on `outParam`s, then we would also have to replace them with fresh metavariables. Otherwise, the resulting expression could be type incorrect. This transformation would be counterintuitive to users since we would implicitly treat these regular parameters as `outParam`s. -/ private partial def checkOutParam : Nat → Array FVarId → Expr → Except String Bool | i, outParams, Expr.forallE _ d b _ => if isOutParam d then let fvarId := Name.mkNum `_fvar outParams.size let outParams := outParams.push fvarId let fvar := mkFVar fvarId let b := b.instantiate1 fvar checkOutParam (i+1) outParams b else if d.hasAnyFVar fun fvarId => outParams.contains fvarId then Except.error s!"invalid class, parameter #{i} depends on `outParam`, but it is not an `outParam`" else checkOutParam (i+1) outParams b | i, outParams, e => pure (outParams.size > 0) def addClass (env : Environment) (clsName : Name) : Except String Environment := if isClass env clsName then Except.error s!"class has already been declared '{clsName}'" else match env.find? clsName with | none => Except.error ("unknown declaration '" ++ toString clsName ++ "'") | some decl@(ConstantInfo.inductInfo _) => do let b ← checkOutParam 1 #[] decl.type Except.ok (classExtension.addEntry env (ClassEntry.«class» clsName b)) | some _ => Except.error ("invalid 'class', declaration '" ++ toString clsName ++ "' must be inductive datatype or structure") private def consumeNLambdas : Nat → Expr → Option Expr | 0, e => some e | i+1, Expr.lam _ _ b _ => consumeNLambdas i b | _, _ => none partial def getClassName (env : Environment) : Expr → Option Name | Expr.forallE _ _ b _ => getClassName env b | e => do let Expr.const c _ _ ← pure e.getAppFn | none let info ← env.find? c match info.value? with | some val => do let body ← consumeNLambdas e.getAppNumArgs val getClassName env body | none => if isClass env c then some c else none builtin_initialize registerBuiltinAttribute { name := `class, descr := "type class", add := fun decl args persistent => do let env ← getEnv if args.hasArgs then throwError "invalid attribute 'class', unexpected argument" unless persistent do throwError "invalid attribute 'class', must be persistent" let env ← ofExcept (addClass env decl) setEnv env } -- TODO: delete @[export lean_add_instance_old] def addGlobalInstanceOld (env : Environment) (instName : Name) : Except String Environment := match env.find? instName with | none => Except.error ("unknown declaration '" ++ toString instName ++ "'") | some decl => match getClassName env decl.type with | none => Except.error ("invalid instance '" ++ toString instName ++ "', failed to retrieve class") | some clsName => Except.ok (classExtension.addEntry env (ClassEntry.«instance» instName clsName)) end Lean
84252fd79f09238c6575f3b5f3d23354e5935d85
6b10c15e653d49d146378acda9f3692e9b5b1950
/examples/logic/unnamed_156.lean
09fd79c9cfa0c407d73719da77a44903390723cd
[]
no_license
gebner/mathematics_in_lean
3cf7f18767208ea6c3307ec3a67c7ac266d8514d
6d1462bba46d66a9b948fc1aef2714fd265cde0b
refs/heads/master
1,655,301,945,565
1,588,697,505,000
1,588,697,505,000
261,523,603
0
0
null
1,588,695,611,000
1,588,695,610,000
null
UTF-8
Lean
false
false
159
lean
variables A B C : Prop -- BEGIN example (h₁ : A → B) (h₂ : B → C) : A → C := begin intro h₃, apply h₂, apply h₁, apply h₃ end -- END
e0879b372867d6e0c76063a2138839ae1794a352
dfbb669f3f58ceb57cb207dcfab5726a07425b03
/vscode-lean4/test/test-fixtures/simple/lakefile.lean
1bbccbd9ac562e5f0a14f4c149a8915c003b613c
[ "Apache-2.0" ]
permissive
leanprover/vscode-lean4
8bcf7f06867b3c1d42007fe6da863a7a17444dbb
6ef0bfa668bdeaad0979e6df10551d42fcc01094
refs/heads/master
1,692,247,771,767
1,691,608,804,000
1,691,608,804,000
325,845,305
64
24
Apache-2.0
1,694,176,429,000
1,609,435,614,000
TypeScript
UTF-8
Lean
false
false
197
lean
import Lake open Lake DSL package test { -- add configuration options here } lean_lib Test { -- add library configuration options here } @[default_target] lean_exe test { root := `Main }
40e1bfee09849fe39ea771892c36c2c4c0cd9c04
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/src/Lean/Meta/Match/MatcherInfo.lean
bd99527581dde20d38bf108b675f8d9f6c8ad1ad
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,942
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.Basic namespace Lean.Meta namespace Match /-- A "matcher" auxiliary declaration has the following structure: - `numParams` parameters - motive - `numDiscrs` discriminators (aka major premises) - `altNumParams.size` alternatives (aka minor premises) where alternative `i` has `altNumParams[i]` parameters - `uElimPos?` is `some pos` when the matcher can eliminate in different universe levels, and `pos` is the position of the universe level parameter that specifies the elimination universe. It is `none` if the matcher only eliminates into `Prop`. -/ structure MatcherInfo where numParams : Nat numDiscrs : Nat altNumParams : Array Nat uElimPos? : Option Nat def MatcherInfo.numAlts (matcherInfo : MatcherInfo) : Nat := matcherInfo.altNumParams.size namespace Extension structure Entry where name : Name info : MatcherInfo structure State where map : SMap Name MatcherInfo := {} instance : Inhabited State := ⟨{}⟩ def State.addEntry (s : State) (e : Entry) : State := { s with map := s.map.insert e.name e.info } def State.switch (s : State) : State := { s with map := s.map.switch } builtin_initialize extension : SimplePersistentEnvExtension Entry State ← registerSimplePersistentEnvExtension { name := `matcher, addEntryFn := State.addEntry, addImportedFn := fun es => (mkStateFromImportedEntries State.addEntry {} es).switch } def addMatcherInfo (env : Environment) (matcherName : Name) (info : MatcherInfo) : Environment := extension.addEntry env { name := matcherName, info := info } def getMatcherInfo? (env : Environment) (declName : Name) : Option MatcherInfo := (extension.getState env).map.find? declName end Extension def addMatcherInfo (matcherName : Name) (info : MatcherInfo) : MetaM Unit := modifyEnv fun env => Extension.addMatcherInfo env matcherName info end Match export Match (MatcherInfo) def getMatcherInfo? (declName : Name) : MetaM (Option MatcherInfo) := do let env ← getEnv return Match.Extension.getMatcherInfo? env declName def isMatcher (declName : Name) : MetaM Bool := do let info? ← getMatcherInfo? declName return info?.isSome structure MatcherApp where matcherName : Name matcherLevels : Array Level uElimPos? : Option Nat params : Array Expr motive : Expr discrs : Array Expr altNumParams : Array Nat alts : Array Expr remaining : Array Expr def matchMatcherApp? (e : Expr) : MetaM (Option MatcherApp) := match e.getAppFn with | Expr.const declName declLevels _ => do let some info ← getMatcherInfo? declName | pure none let args := e.getAppArgs if args.size < info.numParams + 1 + info.numDiscrs + info.numAlts then return none else return some { matcherName := declName, matcherLevels := declLevels.toArray, uElimPos? := info.uElimPos?, params := args.extract 0 info.numParams, motive := args.get! info.numParams, discrs := args.extract (info.numParams + 1) (info.numParams + 1 + info.numDiscrs), altNumParams := info.altNumParams, alts := args.extract (info.numParams + 1 + info.numDiscrs) (info.numParams + 1 + info.numDiscrs + info.numAlts), remaining := args.extract (info.numParams + 1 + info.numDiscrs + info.numAlts) args.size } | _ => return none def MatcherApp.toExpr (matcherApp : MatcherApp) : Expr := let result := mkAppN (mkConst matcherApp.matcherName matcherApp.matcherLevels.toList) matcherApp.params let result := mkApp result matcherApp.motive let result := mkAppN result matcherApp.discrs let result := mkAppN result matcherApp.alts mkAppN result matcherApp.remaining end Lean.Meta
7920d3d85e05861ac0cbaf61516b6779ceb3d852
690889011852559ee5ac4dfea77092de8c832e7e
/src/algebra/big_operators.lean
0f5f2b2707d9e4634471fd5792a0286320078a5c
[ "Apache-2.0" ]
permissive
williamdemeo/mathlib
f6df180148f8acc91de9ba5e558976ab40a872c7
1fa03c29f9f273203bbffb79d10d31f696b3d317
refs/heads/master
1,584,785,260,929
1,572,195,914,000
1,572,195,913,000
138,435,193
0
0
Apache-2.0
1,529,789,739,000
1,529,789,739,000
null
UTF-8
Lean
false
false
33,946
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 Some big operators for lists and finite sets. -/ import tactic.tauto data.list.basic data.finset data.nat.enat import algebra.group algebra.ordered_group algebra.group_power universes u v w variables {α : Type u} {β : Type v} {γ : Type w} theorem directed.finset_le {r : α → α → Prop} [is_trans α r] {ι} (hι : nonempty ι) {f : ι → α} (D : directed r f) (s : finset ι) : ∃ z, ∀ i ∈ s, r (f i) (f z) := show ∃ z, ∀ i ∈ s.1, r (f i) (f z), from multiset.induction_on s.1 (let ⟨z⟩ := hι in ⟨z, λ _, false.elim⟩) $ λ i s ⟨j, H⟩, let ⟨k, h₁, h₂⟩ := D i j in ⟨k, λ a h, or.cases_on (multiset.mem_cons.1 h) (λ h, h.symm ▸ h₁) (λ h, trans (H _ h) h₂)⟩ theorem finset.exists_le {α : Type u} [nonempty α] [directed_order α] (s : finset α) : ∃ M, ∀ i ∈ s, i ≤ M := directed.finset_le (by apply_instance) directed_order.directed s namespace finset variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} /-- `prod s f` is the product of `f x` as `x` ranges over the elements of the finite set `s`. -/ @[to_additive] protected def prod [comm_monoid β] (s : finset α) (f : α → β) : β := (s.1.map f).prod @[to_additive] theorem prod_eq_fold [comm_monoid β] (s : finset α) (f : α → β) : s.prod f = s.fold (*) 1 f := rfl section comm_monoid variables [comm_monoid β] @[simp, to_additive] lemma prod_empty {α : Type u} {f : α → β} : (∅:finset α).prod f = 1 := rfl @[simp, to_additive] lemma prod_insert [decidable_eq α] : a ∉ s → (insert a s).prod f = f a * s.prod f := fold_insert @[simp, to_additive] lemma prod_singleton : (singleton a).prod f = f a := eq.trans fold_singleton $ mul_one _ @[simp] lemma prod_const_one : s.prod (λx, (1 : β)) = 1 := by simp only [finset.prod, multiset.map_const, multiset.prod_repeat, one_pow] @[simp] lemma sum_const_zero {β} {s : finset α} [add_comm_monoid β] : s.sum (λx, (0 : β)) = 0 := @prod_const_one _ (multiplicative β) _ _ attribute [to_additive] prod_const_one @[simp, to_additive] lemma prod_image [decidable_eq α] {s : finset γ} {g : γ → α} : (∀x∈s, ∀y∈s, g x = g y → x = y) → (s.image g).prod f = s.prod (λx, f (g x)) := fold_image @[simp, to_additive] lemma prod_map (s : finset α) (e : α ↪ γ) (f : γ → β) : (s.map e).prod f = s.prod (λa, f (e a)) := by rw [finset.prod, finset.map_val, multiset.map_map]; refl @[congr, to_additive] lemma prod_congr (h : s₁ = s₂) : (∀x∈s₂, f x = g x) → s₁.prod f = s₂.prod g := by rw [h]; exact fold_congr attribute [congr] finset.sum_congr @[to_additive] lemma prod_union_inter [decidable_eq α] : (s₁ ∪ s₂).prod f * (s₁ ∩ s₂).prod f = s₁.prod f * s₂.prod f := fold_union_inter @[to_additive] lemma prod_union [decidable_eq α] (h : disjoint s₁ s₂) : (s₁ ∪ s₂).prod f = s₁.prod f * s₂.prod f := by rw [←prod_union_inter, (disjoint_iff_inter_eq_empty.mp h)]; exact (mul_one _).symm @[to_additive] lemma prod_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) : (s₂ \ s₁).prod f * s₁.prod f = s₂.prod f := by rw [←prod_union sdiff_disjoint, sdiff_union_of_subset h] @[to_additive] lemma prod_bind [decidable_eq α] {s : finset γ} {t : γ → finset α} : (∀x∈s, ∀y∈s, x ≠ y → disjoint (t x) (t y)) → (s.bind t).prod f = s.prod (λx, (t x).prod f) := by haveI := classical.dec_eq γ; exact finset.induction_on s (λ _, by simp only [bind_empty, prod_empty]) (assume x s hxs ih hd, have hd' : ∀x∈s, ∀y∈s, x ≠ y → disjoint (t x) (t y), from assume _ hx _ hy, hd _ (mem_insert_of_mem hx) _ (mem_insert_of_mem hy), have ∀y∈s, x ≠ y, from assume _ hy h, by rw [←h] at hy; contradiction, have ∀y∈s, disjoint (t x) (t y), from assume _ hy, hd _ (mem_insert_self _ _) _ (mem_insert_of_mem hy) (this _ hy), have disjoint (t x) (finset.bind s t), from (disjoint_bind_right _ _ _).mpr this, by simp only [bind_insert, prod_insert hxs, prod_union this, ih hd']) @[to_additive] lemma prod_product {s : finset γ} {t : finset α} {f : γ×α → β} : (s.product t).prod f = s.prod (λx, t.prod $ λy, f (x, y)) := begin haveI := classical.dec_eq α, haveI := classical.dec_eq γ, rw [product_eq_bind, prod_bind], { congr, funext, exact prod_image (λ _ _ _ _ H, (prod.mk.inj H).2) }, simp only [disjoint_iff_ne, mem_image], rintros _ _ _ _ h ⟨_, _⟩ ⟨_, _, ⟨_, _⟩⟩ ⟨_, _⟩ ⟨_, _, ⟨_, _⟩⟩ _, apply h, cc end @[to_additive] lemma prod_sigma {σ : α → Type*} {s : finset α} {t : Πa, finset (σ a)} {f : sigma σ → β} : (s.sigma t).prod f = s.prod (λa, (t a).prod $ λs, f ⟨a, s⟩) := by haveI := classical.dec_eq α; haveI := (λ a, classical.dec_eq (σ a)); exact calc (s.sigma t).prod f = (s.bind (λa, (t a).image (λs, sigma.mk a s))).prod f : by rw sigma_eq_bind ... = s.prod (λa, ((t a).image (λs, sigma.mk a s)).prod f) : prod_bind $ assume a₁ ha a₂ ha₂ h, by simp only [disjoint_iff_ne, mem_image]; rintro ⟨_, _⟩ ⟨_, _, _⟩ ⟨_, _⟩ ⟨_, _, _⟩ ⟨_, _⟩; apply h; cc ... = (s.prod $ λa, (t a).prod $ λs, f ⟨a, s⟩) : prod_congr rfl $ λ _ _, prod_image $ λ _ _ _ _ _, by cc @[to_additive] lemma prod_image' [decidable_eq α] {s : finset γ} {g : γ → α} (h : γ → β) (eq : ∀c∈s, f (g c) = (s.filter (λc', g c' = g c)).prod h) : (s.image g).prod f = s.prod h := begin letI := classical.dec_eq γ, rw [← image_bind_filter_eq s g] {occs := occurrences.pos [2]}, rw [finset.prod_bind], { refine finset.prod_congr rfl (assume a ha, _), rcases finset.mem_image.1 ha with ⟨b, hb, rfl⟩, exact eq b hb }, assume a₀ _ a₁ _ ne, refine (disjoint_iff_ne.2 _), assume c₀ h₀ c₁ h₁, rcases mem_filter.1 h₀ with ⟨h₀, rfl⟩, rcases mem_filter.1 h₁ with ⟨h₁, rfl⟩, exact mt (congr_arg g) ne end @[to_additive] lemma prod_mul_distrib : s.prod (λx, f x * g x) = s.prod f * s.prod g := eq.trans (by rw one_mul; refl) fold_op_distrib @[to_additive] lemma prod_comm [decidable_eq γ] {s : finset γ} {t : finset α} {f : γ → α → β} : s.prod (λx, t.prod $ f x) = t.prod (λy, s.prod $ λx, f x y) := finset.induction_on s (by simp only [prod_empty, prod_const_one]) $ λ _ _ H ih, by simp only [prod_insert H, prod_mul_distrib, ih] lemma prod_hom [comm_monoid γ] (g : β → γ) [is_monoid_hom g] : s.prod (λx, g (f x)) = g (s.prod f) := eq.trans (by rw is_monoid_hom.map_one g; refl) (fold_hom $ is_monoid_hom.map_mul g) @[to_additive] lemma prod_hom_rel [comm_monoid γ] {r : β → γ → Prop} {f : α → β} {g : α → γ} {s : finset α} (h₁ : r 1 1) (h₂ : ∀a b c, r b c → r (f a * b) (g a * c)) : r (s.prod f) (s.prod g) := begin letI := classical.dec_eq α, refine finset.induction_on s h₁ (assume a s has ih, _), rw [prod_insert has, prod_insert has], exact h₂ a (s.prod f) (s.prod g) ih, end @[to_additive] lemma prod_subset (h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → f x = 1) : s₁.prod f = s₂.prod f := by haveI := classical.dec_eq α; exact have (s₂ \ s₁).prod f = (s₂ \ s₁).prod (λx, 1), from prod_congr rfl $ by simpa only [mem_sdiff, and_imp], by rw [←prod_sdiff h]; simp only [this, prod_const_one, one_mul] @[to_additive] lemma prod_filter (p : α → Prop) [decidable_pred p] (f : α → β) : (s.filter p).prod f = s.prod (λa, if p a then f a else 1) := calc (s.filter p).prod f = (s.filter p).prod (λa, if p a then f a else 1) : prod_congr rfl (assume a h, by rw [if_pos (mem_filter.1 h).2]) ... = s.prod (λa, if p a then f a else 1) : begin refine prod_subset (filter_subset s) (assume x hs h, _), rw [mem_filter, not_and] at h, exact if_neg (h hs) end @[to_additive] lemma prod_eq_single {s : finset α} {f : α → β} (a : α) (h₀ : ∀b∈s, b ≠ a → f b = 1) (h₁ : a ∉ s → f a = 1) : s.prod f = f a := by haveI := classical.dec_eq α; from classical.by_cases (assume : a ∈ s, calc s.prod f = ({a} : finset α).prod f : begin refine (prod_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { simpa only [mem_singleton] } end ... = f a : prod_singleton) (assume : a ∉ s, (prod_congr rfl $ λ b hb, h₀ b hb $ by rintro rfl; cc).trans $ prod_const_one.trans (h₁ this).symm) @[to_additive] lemma prod_ite [comm_monoid γ] {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f g : α → γ) (h : γ → β) : s.prod (λ x, h (if p x then f x else g x)) = (s.filter p).prod (λ x, h (f x)) * (s.filter (λ x, ¬ p x)).prod (λ x, h (g x)) := by letI := classical.dec_eq α; exact calc s.prod (λ x, h (if p x then f x else g x)) = (s.filter p ∪ s.filter (λ x, ¬ p x)).prod (λ x, h (if p x then f x else g x)) : by rw [filter_union_filter_neg_eq] ... = (s.filter p).prod (λ x, h (if p x then f x else g x)) * (s.filter (λ x, ¬ p x)).prod (λ x, h (if p x then f x else g x)) : prod_union (by simp [disjoint_right] {contextual := tt}) ... = (s.filter p).prod (λ x, h (f x)) * (s.filter (λ x, ¬ p x)).prod (λ x, h (g x)) : congr_arg2 _ (prod_congr rfl (by simp {contextual := tt})) (prod_congr rfl (by simp {contextual := tt})) @[simp, to_additive] lemma prod_ite_eq [decidable_eq α] (s : finset α) (a : α) (b : β) : s.prod (λ x, (ite (a = x) b 1)) = ite (a ∈ s) b 1 := begin rw ←finset.prod_filter, split_ifs; simp only [filter_eq, if_true, if_false, h, prod_empty, prod_singleton, insert_empty_eq_singleton], end @[to_additive] lemma prod_attach {f : α → β} : s.attach.prod (λx, f x.val) = s.prod f := by haveI := classical.dec_eq α; exact calc s.attach.prod (λx, f x.val) = ((s.attach).image subtype.val).prod f : by rw [prod_image]; exact assume x _ y _, subtype.eq ... = _ : by rw [attach_image_val] @[to_additive] lemma prod_bij {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, γ) (hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha)) (i_inj : ∀a₁ a₂ ha₁ ha₂, i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂) (i_surj : ∀b∈t, ∃a ha, b = i a ha) : s.prod f = t.prod g := congr_arg multiset.prod (multiset.map_eq_map_of_bij_of_nodup f g s.2 t.2 i hi h i_inj i_surj) @[to_additive] lemma prod_bij_ne_one {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, f a ≠ 1 → γ) (hi₁ : ∀a h₁ h₂, i a h₁ h₂ ∈ t) (hi₂ : ∀a₁ a₂ h₁₁ h₁₂ h₂₁ h₂₂, i a₁ h₁₁ h₁₂ = i a₂ h₂₁ h₂₂ → a₁ = a₂) (hi₃ : ∀b∈t, g b ≠ 1 → ∃a h₁ h₂, b = i a h₁ h₂) (h : ∀a h₁ h₂, f a = g (i a h₁ h₂)) : s.prod f = t.prod g := by haveI := classical.prop_decidable; exact calc s.prod f = (s.filter $ λx, f x ≠ 1).prod f : (prod_subset (filter_subset _) $ by simp only [not_imp_comm, mem_filter]; exact λ _, and.intro).symm ... = (t.filter $ λx, g x ≠ 1).prod g : prod_bij (assume a ha, i a (mem_filter.mp ha).1 (mem_filter.mp ha).2) (assume a ha, (mem_filter.mp ha).elim $ λh₁ h₂, mem_filter.mpr ⟨hi₁ a h₁ h₂, λ hg, h₂ (hg ▸ h a h₁ h₂)⟩) (assume a ha, (mem_filter.mp ha).elim $ h a) (assume a₁ a₂ ha₁ ha₂, (mem_filter.mp ha₁).elim $ λha₁₁ ha₁₂, (mem_filter.mp ha₂).elim $ λha₂₁ ha₂₂, hi₂ a₁ a₂ _ _ _ _) (assume b hb, (mem_filter.mp hb).elim $ λh₁ h₂, let ⟨a, ha₁, ha₂, eq⟩ := hi₃ b h₁ h₂ in ⟨a, mem_filter.mpr ⟨ha₁, ha₂⟩, eq⟩) ... = t.prod g : (prod_subset (filter_subset _) $ by simp only [not_imp_comm, mem_filter]; exact λ _, and.intro) @[to_additive] lemma exists_ne_one_of_prod_ne_one : s.prod f ≠ 1 → ∃a∈s, f a ≠ 1 := by haveI := classical.dec_eq α; exact finset.induction_on s (λ H, (H rfl).elim) (assume a s has ih h, classical.by_cases (assume ha : f a = 1, let ⟨a, ha, hfa⟩ := ih (by rwa [prod_insert has, ha, one_mul] at h) in ⟨a, mem_insert_of_mem ha, hfa⟩) (assume hna : f a ≠ 1, ⟨a, mem_insert_self _ _, hna⟩)) @[to_additive] lemma prod_range_succ (f : ℕ → β) (n : ℕ) : (range (nat.succ n)).prod f = f n * (range n).prod f := by rw [range_succ, prod_insert not_mem_range_self] lemma prod_range_succ' (f : ℕ → β) : ∀ n : ℕ, (range (nat.succ n)).prod f = (range n).prod (f ∘ nat.succ) * f 0 | 0 := (prod_range_succ _ _).trans $ mul_comm _ _ | (n + 1) := by rw [prod_range_succ (λ m, f (nat.succ m)), mul_assoc, ← prod_range_succ']; exact prod_range_succ _ _ lemma sum_Ico_add {δ : Type*} [add_comm_monoid δ] (f : ℕ → δ) (m n k : ℕ) : (Ico m n).sum (λ l, f (k + l)) = (Ico (m + k) (n + k)).sum f := Ico.image_add m n k ▸ eq.symm $ sum_image $ λ x hx y hy h, nat.add_left_cancel h @[to_additive] lemma prod_Ico_add (f : ℕ → β) (m n k : ℕ) : (Ico m n).prod (λ l, f (k + l)) = (Ico (m + k) (n + k)).prod f := Ico.image_add m n k ▸ eq.symm $ prod_image $ λ x hx y hy h, nat.add_left_cancel h @[to_additive] lemma prod_Ico_consecutive (f : ℕ → β) {m n k : ℕ} (hmn : m ≤ n) (hnk : n ≤ k) : (Ico m n).prod f * (Ico n k).prod f = (Ico m k).prod f := Ico.union_consecutive hmn hnk ▸ eq.symm $ prod_union $ Ico.disjoint_consecutive m n k @[to_additive] lemma prod_range_mul_prod_Ico (f : ℕ → β) {m n : ℕ} (h : m ≤ n) : (range m).prod f * (Ico m n).prod f = (range n).prod f := Ico.zero_bot m ▸ Ico.zero_bot n ▸ prod_Ico_consecutive f (nat.zero_le m) h @[to_additive sum_Ico_eq_add_neg] lemma prod_Ico_eq_div {δ : Type*} [comm_group δ] (f : ℕ → δ) {m n : ℕ} (h : m ≤ n) : (Ico m n).prod f = (range n).prod f * ((range m).prod f)⁻¹ := eq_mul_inv_iff_mul_eq.2 $ by rw [mul_comm]; exact prod_range_mul_prod_Ico f h lemma sum_Ico_eq_sub {δ : Type*} [add_comm_group δ] (f : ℕ → δ) {m n : ℕ} (h : m ≤ n) : (Ico m n).sum f = (range n).sum f - (range m).sum f := sum_Ico_eq_add_neg f h @[to_additive] lemma prod_Ico_eq_prod_range (f : ℕ → β) (m n : ℕ) : (Ico m n).prod f = (range (n - m)).prod (λ l, f (m + l)) := begin by_cases h : m ≤ n, { rw [← Ico.zero_bot, prod_Ico_add, zero_add, nat.sub_add_cancel h] }, { replace h : n ≤ m := le_of_not_ge h, rw [Ico.eq_empty_of_le h, nat.sub_eq_zero_of_le h, range_zero, prod_empty, prod_empty] } end @[to_additive] lemma prod_range_zero (f : ℕ → β) : (range 0).prod f = 1 := by rw [range_zero, prod_empty] lemma prod_range_one (f : ℕ → β) : (range 1).prod f = f 0 := by { rw [range_one], apply @prod_singleton ℕ β 0 f } lemma sum_range_one {δ : Type*} [add_comm_monoid δ] (f : ℕ → δ) : (range 1).sum f = f 0 := by { rw [range_one], apply @sum_singleton ℕ δ 0 f } attribute [to_additive finset.sum_range_one] prod_range_one @[simp] lemma prod_const (b : β) : s.prod (λ a, b) = b ^ s.card := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by rw [prod_insert has, card_insert_of_not_mem has, pow_succ, ih]) lemma prod_pow (s : finset α) (n : ℕ) (f : α → β) : s.prod (λ x, f x ^ n) = s.prod f ^ n := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (by simp [_root_.mul_pow] {contextual := tt}) lemma prod_nat_pow (s : finset α) (n : ℕ) (f : α → ℕ) : s.prod (λ x, f x ^ n) = s.prod f ^ n := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (by simp [nat.mul_pow] {contextual := tt}) @[to_additive] lemma prod_involution {s : finset α} {f : α → β} : ∀ (g : Π a ∈ s, α) (h₁ : ∀ a ha, f a * f (g a ha) = 1) (h₂ : ∀ a ha, f a ≠ 1 → g a ha ≠ a) (h₃ : ∀ a ha, g a ha ∈ s) (h₄ : ∀ a ha, g (g a ha) (h₃ a ha) = a), s.prod f = 1 := by haveI := classical.dec_eq α; haveI := classical.dec_eq β; exact finset.strong_induction_on s (λ s ih g h₁ h₂ h₃ h₄, if hs : s = ∅ then hs.symm ▸ rfl else let ⟨x, hx⟩ := exists_mem_of_ne_empty hs in have hmem : ∀ y ∈ (s.erase x).erase (g x hx), y ∈ s, from λ y hy, (mem_of_mem_erase (mem_of_mem_erase hy)), have g_inj : ∀ {x hx y hy}, g x hx = g y hy → x = y, from λ x hx y hy h, by rw [← h₄ x hx, ← h₄ y hy]; simp [h], have ih': (erase (erase s x) (g x hx)).prod f = (1 : β) := ih ((s.erase x).erase (g x hx)) ⟨subset.trans (erase_subset _ _) (erase_subset _ _), λ h, not_mem_erase (g x hx) (s.erase x) (h (h₃ x hx))⟩ (λ y hy, g y (hmem y hy)) (λ y hy, h₁ y (hmem y hy)) (λ y hy, h₂ y (hmem y hy)) (λ y hy, mem_erase.2 ⟨λ (h : g y _ = g x hx), by simpa [g_inj h] using hy, mem_erase.2 ⟨λ (h : g y _ = x), have y = g x hx, from h₄ y (hmem y hy) ▸ by simp [h], by simpa [this] using hy, h₃ y (hmem y hy)⟩⟩) (λ y hy, h₄ y (hmem y hy)), if hx1 : f x = 1 then ih' ▸ eq.symm (prod_subset hmem (λ y hy hy₁, have y = x ∨ y = g x hx, by simp [hy] at hy₁; tauto, this.elim (λ h, h.symm ▸ hx1) (λ h, h₁ x hx ▸ h ▸ hx1.symm ▸ (one_mul _).symm))) else by rw [← insert_erase hx, prod_insert (not_mem_erase _ _), ← insert_erase (mem_erase.2 ⟨h₂ x hx hx1, h₃ x hx⟩), prod_insert (not_mem_erase _ _), ih', mul_one, h₁ x hx]) @[to_additive] lemma prod_eq_one {f : α → β} {s : finset α} (h : ∀x∈s, f x = 1) : s.prod f = 1 := calc s.prod f = s.prod (λx, 1) : finset.prod_congr rfl h ... = 1 : finset.prod_const_one end comm_monoid attribute [to_additive] prod_hom lemma sum_smul [add_comm_monoid β] (s : finset α) (n : ℕ) (f : α → β) : s.sum (λ x, add_monoid.smul n (f x)) = add_monoid.smul n (s.sum f) := @prod_pow _ (multiplicative β) _ _ _ _ attribute [to_additive sum_smul] prod_pow @[simp] lemma sum_const [add_comm_monoid β] (b : β) : s.sum (λ a, b) = add_monoid.smul s.card b := @prod_const _ (multiplicative β) _ _ _ attribute [to_additive] prod_const lemma sum_range_succ' [add_comm_monoid β] (f : ℕ → β) : ∀ n : ℕ, (range (nat.succ n)).sum f = (range n).sum (f ∘ nat.succ) + f 0 := @prod_range_succ' (multiplicative β) _ _ attribute [to_additive] prod_range_succ' lemma sum_nat_cast [add_comm_monoid β] [has_one β] (s : finset α) (f : α → ℕ) : ↑(s.sum f) = s.sum (λa, f a : α → β) := (sum_hom _).symm lemma prod_nat_cast [comm_semiring β] (s : finset α) (f : α → ℕ) : ↑(s.prod f) = s.prod (λa, f a : α → β) := (prod_hom _).symm protected lemma sum_nat_coe_enat [decidable_eq α] (s : finset α) (f : α → ℕ) : s.sum (λ x, (f x : enat)) = (s.sum f : ℕ) := begin induction s using finset.induction with a s has ih h, { simp }, { simp [has, ih] } end lemma le_sum_of_subadditive [add_comm_monoid α] [ordered_comm_monoid β] (f : α → β) (h_zero : f 0 = 0) (h_add : ∀x y, f (x + y) ≤ f x + f y) (s : finset γ) (g : γ → α) : f (s.sum g) ≤ s.sum (λc, f (g c)) := begin refine le_trans (multiset.le_sum_of_subadditive f h_zero h_add _) _, rw [multiset.map_map], refl end lemma abs_sum_le_sum_abs [discrete_linear_ordered_field α] {f : β → α} {s : finset β} : abs (s.sum f) ≤ s.sum (λa, abs (f a)) := le_sum_of_subadditive _ abs_zero abs_add s f section comm_group variables [comm_group β] @[simp, to_additive] lemma prod_inv_distrib : s.prod (λx, (f x)⁻¹) = (s.prod f)⁻¹ := prod_hom has_inv.inv end comm_group @[simp] theorem card_sigma {σ : α → Type*} (s : finset α) (t : Π a, finset (σ a)) : card (s.sigma t) = s.sum (λ a, card (t a)) := multiset.card_sigma _ _ lemma card_bind [decidable_eq β] {s : finset α} {t : α → finset β} (h : ∀ x ∈ s, ∀ y ∈ s, x ≠ y → disjoint (t x) (t y)) : (s.bind t).card = s.sum (λ u, card (t u)) := calc (s.bind t).card = (s.bind t).sum (λ _, 1) : by simp ... = s.sum (λ a, (t a).sum (λ _, 1)) : finset.sum_bind h ... = s.sum (λ u, card (t u)) : by simp lemma card_bind_le [decidable_eq β] {s : finset α} {t : α → finset β} : (s.bind t).card ≤ s.sum (λ a, (t a).card) := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (λ a s has ih, calc ((insert a s).bind t).card ≤ (t a).card + (s.bind t).card : by rw bind_insert; exact finset.card_union_le _ _ ... ≤ (insert a s).sum (λ a, card (t a)) : by rw sum_insert has; exact add_le_add_left ih _) theorem card_eq_sum_card_image [decidable_eq β] (f : α → β) (s : finset α) : s.card = (s.image f).sum (λ a, (s.filter (λ x, f x = a)).card) := by letI := classical.dec_eq α; exact calc s.card = ((s.image f).bind (λ a, s.filter (λ x, f x = a))).card : congr_arg _ (finset.ext.2 $ λ x, ⟨λ hs, mem_bind.2 ⟨f x, mem_image_of_mem _ hs, mem_filter.2 ⟨hs, rfl⟩⟩, λ h, let ⟨a, ha₁, ha₂⟩ := mem_bind.1 h in by convert filter_subset s ha₂⟩) ... = (s.image f).sum (λ a, (s.filter (λ x, f x = a)).card) : card_bind (by simp [disjoint_left, finset.ext] {contextual := tt}) lemma gsmul_sum [add_comm_group β] {f : α → β} {s : finset α} (z : ℤ) : gsmul z (s.sum f) = s.sum (λa, gsmul z (f a)) := (finset.sum_hom (gsmul z)).symm end finset namespace finset variables {s s₁ s₂ : finset α} {f g : α → β} {b : β} {a : α} @[simp] lemma sum_sub_distrib [add_comm_group β] : s.sum (λx, f x - g x) = s.sum f - s.sum g := sum_add_distrib.trans $ congr_arg _ sum_neg_distrib section semiring variables [semiring β] lemma sum_mul : s.sum f * b = s.sum (λx, f x * b) := (sum_hom (λx, x * b)).symm lemma mul_sum : b * s.sum f = s.sum (λx, b * f x) := (sum_hom (λx, b * x)).symm @[simp] lemma sum_mul_boole [decidable_eq α] (s : finset α) (f : α → β) (a : α) : s.sum (λ x, (f x * ite (a = x) 1 0)) = ite (a ∈ s) (f a) 0 := begin convert sum_ite_eq s a (f a), funext, split_ifs with h; simp [h], end @[simp] lemma sum_boole_mul [decidable_eq α] (s : finset α) (f : α → β) (a : α) : s.sum (λ x, (ite (a = x) 1 0) * f x) = ite (a ∈ s) (f a) 0 := begin convert sum_ite_eq s a (f a), funext, split_ifs with h; simp [h], end end semiring section comm_semiring variables [decidable_eq α] [comm_semiring β] lemma prod_eq_zero (ha : a ∈ s) (h : f a = 0) : s.prod f = 0 := calc s.prod f = (insert a (erase s a)).prod f : by rw insert_erase ha ... = 0 : by rw [prod_insert (not_mem_erase _ _), h, zero_mul] lemma prod_sum {δ : α → Type*} [∀a, decidable_eq (δ a)] {s : finset α} {t : Πa, finset (δ a)} {f : Πa, δ a → β} : s.prod (λa, (t a).sum (λb, f a b)) = (s.pi t).sum (λp, s.attach.prod (λx, f x.1 (p x.1 x.2))) := begin induction s using finset.induction with a s ha ih, { rw [pi_empty, sum_singleton], refl }, { have h₁ : ∀x ∈ t a, ∀y ∈ t a, ∀h : x ≠ y, disjoint (image (pi.cons s a x) (pi s t)) (image (pi.cons s a y) (pi s t)), { assume x hx y hy h, simp only [disjoint_iff_ne, mem_image], rintros _ ⟨p₂, hp, eq₂⟩ _ ⟨p₃, hp₃, eq₃⟩ eq, have : pi.cons s a x p₂ a (mem_insert_self _ _) = pi.cons s a y p₃ a (mem_insert_self _ _), { rw [eq₂, eq₃, eq] }, rw [pi.cons_same, pi.cons_same] at this, exact h this }, rw [prod_insert ha, pi_insert ha, ih, sum_mul, sum_bind h₁], refine sum_congr rfl (λ b _, _), have h₂ : ∀p₁∈pi s t, ∀p₂∈pi s t, pi.cons s a b p₁ = pi.cons s a b p₂ → p₁ = p₂, from assume p₁ h₁ p₂ h₂ eq, injective_pi_cons ha eq, rw [sum_image h₂, mul_sum], refine sum_congr rfl (λ g _, _), rw [attach_insert, prod_insert, prod_image], { simp only [pi.cons_same], congr', ext ⟨v, hv⟩, congr', exact (pi.cons_ne (by rintro rfl; exact ha hv)).symm }, { exact λ _ _ _ _, subtype.eq ∘ subtype.mk.inj }, { simp only [mem_image], rintro ⟨⟨_, hm⟩, _, rfl⟩, exact ha hm } } end end comm_semiring section integral_domain /- add integral_semi_domain to support nat and ennreal -/ variables [decidable_eq α] [integral_domain β] lemma prod_eq_zero_iff : s.prod f = 0 ↔ (∃a∈s, f a = 0) := finset.induction_on s ⟨not.elim one_ne_zero, λ ⟨_, H, _⟩, H.elim⟩ $ λ a s ha ih, by rw [prod_insert ha, mul_eq_zero_iff_eq_zero_or_eq_zero, bex_def, exists_mem_insert, ih, ← bex_def] end integral_domain section ordered_comm_monoid variables [decidable_eq α] [ordered_comm_monoid β] lemma sum_le_sum : (∀x∈s, f x ≤ g x) → s.sum f ≤ s.sum g := finset.induction_on s (λ _, le_refl _) $ assume a s ha ih h, have f a + s.sum f ≤ g a + s.sum g, from add_le_add' (h _ (mem_insert_self _ _)) (ih $ assume x hx, h _ $ mem_insert_of_mem hx), by simpa only [sum_insert ha] lemma sum_nonneg (h : ∀x∈s, 0 ≤ f x) : 0 ≤ s.sum f := le_trans (by rw [sum_const_zero]) (sum_le_sum h) lemma sum_nonpos (h : ∀x∈s, f x ≤ 0) : s.sum f ≤ 0 := le_trans (sum_le_sum h) (by rw [sum_const_zero]) lemma sum_le_sum_of_subset_of_nonneg (h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → 0 ≤ f x) : s₁.sum f ≤ s₂.sum f := calc s₁.sum f ≤ (s₂ \ s₁).sum f + s₁.sum f : le_add_of_nonneg_left' $ sum_nonneg $ by simpa only [mem_sdiff, and_imp] ... = (s₂ \ s₁ ∪ s₁).sum f : (sum_union sdiff_disjoint).symm ... = s₂.sum f : by rw [sdiff_union_of_subset h] lemma sum_eq_zero_iff_of_nonneg : (∀x∈s, 0 ≤ f x) → (s.sum f = 0 ↔ ∀x∈s, f x = 0) := finset.induction_on s (λ _, ⟨λ _ _, false.elim, λ _, rfl⟩) $ λ a s ha ih H, have ∀ x ∈ s, 0 ≤ f x, from λ _, H _ ∘ mem_insert_of_mem, by rw [sum_insert ha, add_eq_zero_iff' (H _ $ mem_insert_self _ _) (sum_nonneg this), forall_mem_insert, ih this] lemma sum_eq_zero_iff_of_nonpos : (∀x∈s, f x ≤ 0) → (s.sum f = 0 ↔ ∀x∈s, f x = 0) := @sum_eq_zero_iff_of_nonneg _ (order_dual β) _ _ _ _ lemma single_le_sum (hf : ∀x∈s, 0 ≤ f x) {a} (h : a ∈ s) : f a ≤ s.sum f := have (singleton a).sum f ≤ s.sum f, from sum_le_sum_of_subset_of_nonneg (λ x e, (mem_singleton.1 e).symm ▸ h) (λ x h _, hf x h), by rwa sum_singleton at this end ordered_comm_monoid section canonically_ordered_monoid variables [decidable_eq α] [canonically_ordered_monoid β] lemma sum_le_sum_of_subset (h : s₁ ⊆ s₂) : s₁.sum f ≤ s₂.sum f := sum_le_sum_of_subset_of_nonneg h $ assume x h₁ h₂, zero_le _ lemma sum_le_sum_of_ne_zero [@decidable_rel β (≤)] (h : ∀x∈s₁, f x ≠ 0 → x ∈ s₂) : s₁.sum f ≤ s₂.sum f := calc s₁.sum f = (s₁.filter (λx, f x = 0)).sum f + (s₁.filter (λx, f x ≠ 0)).sum f : by rw [←sum_union, filter_union_filter_neg_eq]; exact disjoint_filter.2 (assume _ _ h n_h, n_h h) ... ≤ s₂.sum f : add_le_of_nonpos_of_le' (sum_nonpos $ by simp only [mem_filter, and_imp]; exact λ _ _, le_of_eq) (sum_le_sum_of_subset $ by simpa only [subset_iff, mem_filter, and_imp]) end canonically_ordered_monoid section linear_ordered_comm_ring variables [decidable_eq α] [linear_ordered_comm_ring β] /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_nonneg {s : finset α} {f : α → β} (h0 : ∀(x ∈ s), 0 ≤ f x) : 0 ≤ s.prod f := begin induction s using finset.induction with a s has ih h, { simp [zero_le_one] }, { simp [has], apply mul_nonneg, apply h0 a (mem_insert_self a s), exact ih (λ x H, h0 x (mem_insert_of_mem H)) } end /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_pos {s : finset α} {f : α → β} (h0 : ∀(x ∈ s), 0 < f x) : 0 < s.prod f := begin induction s using finset.induction with a s has ih h, { simp [zero_lt_one] }, { simp [has], apply mul_pos, apply h0 a (mem_insert_self a s), exact ih (λ x H, h0 x (mem_insert_of_mem H)) } end /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_le_prod {s : finset α} {f g : α → β} (h0 : ∀(x ∈ s), 0 ≤ f x) (h1 : ∀(x ∈ s), f x ≤ g x) : s.prod f ≤ s.prod g := begin induction s using finset.induction with a s has ih h, { simp }, { simp [has], apply mul_le_mul, exact h1 a (mem_insert_self a s), apply ih (λ x H, h0 _ _) (λ x H, h1 _ _); exact (mem_insert_of_mem H), apply prod_nonneg (λ x H, h0 x (mem_insert_of_mem H)), apply le_trans (h0 a (mem_insert_self a s)) (h1 a (mem_insert_self a s)) } end end linear_ordered_comm_ring @[simp] lemma card_pi [decidable_eq α] {δ : α → Type*} (s : finset α) (t : Π a, finset (δ a)) : (s.pi t).card = s.prod (λ a, card (t a)) := multiset.card_pi _ _ theorem card_le_mul_card_image [decidable_eq β] {f : α → β} (s : finset α) (n : ℕ) (hn : ∀ a ∈ s.image f, (s.filter (λ x, f x = a)).card ≤ n) : s.card ≤ n * (s.image f).card := calc s.card = (s.image f).sum (λ a, (s.filter (λ x, f x = a)).card) : card_eq_sum_card_image _ _ ... ≤ (s.image f).sum (λ _, n) : sum_le_sum hn ... = _ : by simp [mul_comm] @[simp] lemma prod_range_id_eq_fact (n : ℕ) : ((range n.succ).erase 0).prod (λ x, x) = nat.fact n := calc ((range n.succ).erase 0).prod (λ x, x) = (range n).prod nat.succ : eq.symm (prod_bij (λ x _, nat.succ x) (λ a h₁, mem_erase.2 ⟨nat.succ_ne_zero _, mem_range.2 $ nat.succ_lt_succ $ by simpa using h₁⟩) (by simp) (λ _ _ _ _, nat.succ_inj) (λ b h, have b.pred.succ = b, from nat.succ_pred_eq_of_pos $ by simp [nat.pos_iff_ne_zero] at *; tauto, ⟨nat.pred b, mem_range.2 $ nat.lt_of_succ_lt_succ (by simp [*] at *), this.symm⟩)) ... = nat.fact n : by induction n; simp [*, range_succ] end finset namespace finset section gauss_sum /-- Gauss' summation formula -/ lemma sum_range_id_mul_two : ∀(n : ℕ), (finset.range n).sum (λi, i) * 2 = n * (n - 1) | 0 := rfl | 1 := rfl | ((n + 1) + 1) := begin rw [sum_range_succ, add_mul, sum_range_id_mul_two (n + 1), mul_comm, two_mul, nat.add_sub_cancel, nat.add_sub_cancel, mul_comm _ n], simp only [add_mul, one_mul, add_comm, add_assoc, add_left_comm] end /-- Gauss' summation formula -/ lemma sum_range_id (n : ℕ) : (finset.range n).sum (λi, i) = (n * (n - 1)) / 2 := by rw [← sum_range_id_mul_two n, nat.mul_div_cancel]; exact dec_trivial end gauss_sum lemma card_eq_sum_ones (s : finset α) : s.card = s.sum (λ _, 1) := by simp end finset section group open list variables [group α] [group β] @[to_additive] theorem is_group_hom.map_prod (f : α → β) [is_group_hom f] (l : list α) : f (prod l) = prod (map f l) := by induction l; simp only [*, is_mul_hom.map_mul f, is_group_hom.map_one f, prod_nil, prod_cons, map] theorem is_group_anti_hom.map_prod (f : α → β) [is_group_anti_hom f] (l : list α) : f (prod l) = prod (map f (reverse l)) := by induction l with hd tl ih; [exact is_group_anti_hom.map_one f, simp only [prod_cons, is_group_anti_hom.map_mul f, ih, reverse_cons, map_append, prod_append, map_singleton, prod_cons, prod_nil, mul_one]] theorem inv_prod : ∀ l : list α, (prod l)⁻¹ = prod (map (λ x, x⁻¹) (reverse l)) := λ l, @is_group_anti_hom.map_prod _ _ _ _ _ inv_is_group_anti_hom l -- TODO there is probably a cleaner proof of this end group section comm_group variables [comm_group α] [comm_group β] (f : α → β) [is_group_hom f] @[to_additive] lemma is_group_hom.map_multiset_prod (m : multiset α) : f m.prod = (m.map f).prod := quotient.induction_on m $ assume l, by simp [is_group_hom.map_prod f l] @[to_additive] lemma is_group_hom.map_finset_prod (g : γ → α) (s : finset γ) : f (s.prod g) = s.prod (f ∘ g) := show f (s.val.map g).prod = (s.val.map (f ∘ g)).prod, by rw [is_group_hom.map_multiset_prod f]; simp end comm_group @[to_additive is_add_group_hom_finset_sum] lemma is_group_hom_finset_prod {α β γ} [group α] [comm_group β] (s : finset γ) (f : γ → α → β) [∀c, is_group_hom (f c)] : is_group_hom (λa, s.prod (λc, f c a)) := { map_mul := assume a b, by simp only [λc, is_mul_hom.map_mul (f c), finset.prod_mul_distrib] } attribute [instance] is_group_hom_finset_prod is_add_group_hom_finset_sum namespace multiset variables [decidable_eq α] @[simp] lemma to_finset_sum_count_eq (s : multiset α) : s.to_finset.sum (λa, s.count a) = s.card := multiset.induction_on s rfl (assume a s ih, calc (to_finset (a :: s)).sum (λx, count x (a :: s)) = (to_finset (a :: s)).sum (λx, (if x = a then 1 else 0) + count x s) : finset.sum_congr rfl $ λ _ _, by split_ifs; [simp only [h, count_cons_self, nat.one_add], simp only [count_cons_of_ne h, zero_add]] ... = card (a :: s) : begin by_cases a ∈ s.to_finset, { have : (to_finset s).sum (λx, ite (x = a) 1 0) = (finset.singleton a).sum (λx, ite (x = a) 1 0), { apply (finset.sum_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { exact λ _ _ H, if_neg (mt finset.mem_singleton.2 H) } }, rw [to_finset_cons, finset.insert_eq_of_mem h, finset.sum_add_distrib, ih, this, finset.sum_singleton, if_pos rfl, add_comm, card_cons] }, { have ha : a ∉ s, by rwa mem_to_finset at h, have : (to_finset s).sum (λx, ite (x = a) 1 0) = (to_finset s).sum (λx, 0), from finset.sum_congr rfl (λ x hx, if_neg $ by rintro rfl; cc), rw [to_finset_cons, finset.sum_insert h, if_pos rfl, finset.sum_add_distrib, this, finset.sum_const_zero, ih, count_eq_zero_of_not_mem ha, zero_add, add_comm, card_cons] } end) end multiset
dd441bbf453ee4741e6b232f1877c7ac368a2c23
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/group_theory/commutator.lean
a70850a6c160412329c782c6481448d43287ec10
[ "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
9,654
lean
/- Copyright (c) 2021 Jordan Brown, Thomas Browning, Patrick Lutz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jordan Brown, Thomas Browning, Patrick Lutz -/ import data.bracket import group_theory.subgroup.basic import tactic.group /-! # Commutators of Subgroups If `G` is a group and `H₁ H₂ : subgroup G` then the commutator `⁅H₁, H₂⁆ : subgroup G` is the subgroup of `G` generated by the commutators `h₁ * h₂ * h₁⁻¹ * h₂⁻¹`. ## Main definitions * `⁅g₁, g₂⁆` : the commutator of the elements `g₁` and `g₂` (defined by `commutator_element` elsewhere). * `⁅H₁, H₂⁆` : the commutator of the subgroups `H₁` and `H₂`. -/ variables {G G' F : Type*} [group G] [group G'] [monoid_hom_class F G G'] (f : F) {g₁ g₂ g₃ g : G} lemma commutator_element_eq_one_iff_mul_comm : ⁅g₁, g₂⁆ = 1 ↔ g₁ * g₂ = g₂ * g₁ := by rw [commutator_element_def, mul_inv_eq_one, mul_inv_eq_iff_eq_mul] lemma commutator_element_eq_one_iff_commute : ⁅g₁, g₂⁆ = 1 ↔ commute g₁ g₂ := commutator_element_eq_one_iff_mul_comm lemma commute.commutator_eq (h : commute g₁ g₂) : ⁅g₁, g₂⁆ = 1 := commutator_element_eq_one_iff_commute.mpr h variables (g₁ g₂ g₃ g) @[simp] lemma commutator_element_one_right : ⁅g, (1 : G)⁆ = 1 := (commute.one_right g).commutator_eq @[simp] lemma commutator_element_one_left : ⁅(1 : G), g⁆ = 1 := (commute.one_left g).commutator_eq @[simp] lemma commutator_element_self : ⁅g, g⁆ = 1 := (commute.refl g).commutator_eq @[simp] lemma commutator_element_inv : ⁅g₁, g₂⁆⁻¹ = ⁅g₂, g₁⁆ := by simp_rw [commutator_element_def, mul_inv_rev, inv_inv, mul_assoc] lemma map_commutator_element : (f ⁅g₁, g₂⁆ : G') = ⁅f g₁, f g₂⁆ := by simp_rw [commutator_element_def, map_mul f, map_inv f] lemma conjugate_commutator_element : g₃ * ⁅g₁, g₂⁆ * g₃⁻¹ = ⁅g₃ * g₁ * g₃⁻¹, g₃ * g₂ * g₃⁻¹⁆ := map_commutator_element (mul_aut.conj g₃).to_monoid_hom g₁ g₂ namespace subgroup /-- The commutator of two subgroups `H₁` and `H₂`. -/ instance commutator : has_bracket (subgroup G) (subgroup G) := ⟨λ H₁ H₂, closure {g | ∃ (g₁ ∈ H₁) (g₂ ∈ H₂), ⁅g₁, g₂⁆ = g}⟩ lemma commutator_def (H₁ H₂ : subgroup G) : ⁅H₁, H₂⁆ = closure {g | ∃ (g₁ ∈ H₁) (g₂ ∈ H₂), ⁅g₁, g₂⁆ = g} := rfl variables {g₁ g₂ g₃} {H₁ H₂ H₃ K₁ K₂ : subgroup G} lemma commutator_mem_commutator (h₁ : g₁ ∈ H₁) (h₂ : g₂ ∈ H₂) : ⁅g₁, g₂⁆ ∈ ⁅H₁, H₂⁆ := subset_closure ⟨g₁, h₁, g₂, h₂, rfl⟩ lemma commutator_le : ⁅H₁, H₂⁆ ≤ H₃ ↔ ∀ (g₁ ∈ H₁) (g₂ ∈ H₂), ⁅g₁, g₂⁆ ∈ H₃ := H₃.closure_le.trans ⟨λ h a b c d, h ⟨a, b, c, d, rfl⟩, λ h g ⟨a, b, c, d, h_eq⟩, h_eq ▸ h a b c d⟩ lemma commutator_mono (h₁ : H₁ ≤ K₁) (h₂ : H₂ ≤ K₂) : ⁅H₁, H₂⁆ ≤ ⁅K₁, K₂⁆ := commutator_le.mpr (λ g₁ hg₁ g₂ hg₂, commutator_mem_commutator (h₁ hg₁) (h₂ hg₂)) lemma commutator_eq_bot_iff_le_centralizer : ⁅H₁, H₂⁆ = ⊥ ↔ H₁ ≤ H₂.centralizer := begin rw [eq_bot_iff, commutator_le], refine forall_congr (λ p, forall_congr (λ hp, forall_congr (λ q, forall_congr (λ hq, _)))), rw [mem_bot, commutator_element_eq_one_iff_mul_comm, eq_comm], end /-- **The Three Subgroups Lemma** (via the Hall-Witt identity) -/ lemma commutator_commutator_eq_bot_of_rotate (h1 : ⁅⁅H₂, H₃⁆, H₁⁆ = ⊥) (h2 : ⁅⁅H₃, H₁⁆, H₂⁆ = ⊥) : ⁅⁅H₁, H₂⁆, H₃⁆ = ⊥ := begin simp_rw [commutator_eq_bot_iff_le_centralizer, commutator_le, mem_centralizer_iff_commutator_eq_one, ←commutator_element_def] at h1 h2 ⊢, intros x hx y hy z hz, transitivity x * z * ⁅y, ⁅z⁻¹, x⁻¹⁆⁆⁻¹ * z⁻¹ * y * ⁅x⁻¹, ⁅y⁻¹, z⁆⁆⁻¹ * y⁻¹ * x⁻¹, { group }, { rw [h1 _ (H₂.inv_mem hy) _ hz _ (H₁.inv_mem hx), h2 _ (H₃.inv_mem hz) _ (H₁.inv_mem hx) _ hy], group }, end variables (H₁ H₂) lemma commutator_comm_le : ⁅H₁, H₂⁆ ≤ ⁅H₂, H₁⁆ := commutator_le.mpr (λ g₁ h₁ g₂ h₂, commutator_element_inv g₂ g₁ ▸ ⁅H₂, H₁⁆.inv_mem_iff.mpr (commutator_mem_commutator h₂ h₁)) lemma commutator_comm : ⁅H₁, H₂⁆ = ⁅H₂, H₁⁆ := le_antisymm (commutator_comm_le H₁ H₂) (commutator_comm_le H₂ H₁) section normal instance commutator_normal [h₁ : H₁.normal] [h₂ : H₂.normal] : normal ⁅H₁, H₂⁆ := begin let base : set G := {x | ∃ (g₁ ∈ H₁) (g₂ ∈ H₂), ⁅g₁, g₂⁆ = x}, change (closure base).normal, suffices h_base : base = group.conjugates_of_set base, { rw h_base, exact subgroup.normal_closure_normal }, refine set.subset.antisymm group.subset_conjugates_of_set (λ a h, _), simp_rw [group.mem_conjugates_of_set_iff, is_conj_iff] at h, rcases h with ⟨b, ⟨c, hc, e, he, rfl⟩, d, rfl⟩, exact ⟨_, h₁.conj_mem c hc d, _, h₂.conj_mem e he d, (conjugate_commutator_element c e d).symm⟩, end lemma commutator_def' [H₁.normal] [H₂.normal] : ⁅H₁, H₂⁆ = normal_closure {g | ∃ (g₁ ∈ H₁) (g₂ ∈ H₂), ⁅g₁, g₂⁆ = g} := le_antisymm closure_le_normal_closure (normal_closure_le_normal subset_closure) lemma commutator_le_right [h : H₂.normal] : ⁅H₁, H₂⁆ ≤ H₂ := commutator_le.mpr (λ g₁ h₁ g₂ h₂, H₂.mul_mem (h.conj_mem g₂ h₂ g₁) (H₂.inv_mem h₂)) lemma commutator_le_left [H₁.normal] : ⁅H₁, H₂⁆ ≤ H₁ := commutator_comm H₂ H₁ ▸ commutator_le_right H₂ H₁ @[simp] lemma commutator_bot_left : ⁅(⊥ : subgroup G), H₁⁆ = ⊥ := le_bot_iff.mp (commutator_le_left ⊥ H₁) @[simp] lemma commutator_bot_right : ⁅H₁, ⊥⁆ = (⊥ : subgroup G) := le_bot_iff.mp (commutator_le_right H₁ ⊥) lemma commutator_le_inf [normal H₁] [normal H₂] : ⁅H₁, H₂⁆ ≤ H₁ ⊓ H₂ := le_inf (commutator_le_left H₁ H₂) (commutator_le_right H₁ H₂) end normal lemma map_commutator (f : G →* G') : map f ⁅H₁, H₂⁆ = ⁅map f H₁, map f H₂⁆ := begin simp_rw [le_antisymm_iff, map_le_iff_le_comap, commutator_le, mem_comap, map_commutator_element], split, { intros p hp q hq, exact commutator_mem_commutator (mem_map_of_mem _ hp) (mem_map_of_mem _ hq), }, { rintros _ ⟨p, hp, rfl⟩ _ ⟨q, hq, rfl⟩, rw ← map_commutator_element, exact mem_map_of_mem _ (commutator_mem_commutator hp hq) } end variables {H₁ H₂} lemma commutator_le_map_commutator {f : G →* G'} {K₁ K₂ : subgroup G'} (h₁ : K₁ ≤ H₁.map f) (h₂ : K₂ ≤ H₂.map f) : ⁅K₁, K₂⁆ ≤ ⁅H₁, H₂⁆.map f := (commutator_mono h₁ h₂).trans (ge_of_eq (map_commutator H₁ H₂ f)) variables (H₁ H₂) instance commutator_characteristic [h₁ : characteristic H₁] [h₂ : characteristic H₂] : characteristic ⁅H₁, H₂⁆ := characteristic_iff_le_map.mpr (λ ϕ, commutator_le_map_commutator (characteristic_iff_le_map.mp h₁ ϕ) (characteristic_iff_le_map.mp h₂ ϕ)) lemma commutator_prod_prod (K₁ K₂ : subgroup G') : ⁅H₁.prod K₁, H₂.prod K₂⁆ = ⁅H₁, H₂⁆.prod ⁅K₁, K₂⁆ := begin apply le_antisymm, { rw commutator_le, rintros ⟨p₁, p₂⟩ ⟨hp₁, hp₂⟩ ⟨q₁, q₂⟩ ⟨hq₁, hq₂⟩, exact ⟨commutator_mem_commutator hp₁ hq₁, commutator_mem_commutator hp₂ hq₂⟩ }, { rw prod_le_iff, split; { rw map_commutator, apply commutator_mono; simp [le_prod_iff, map_map, monoid_hom.fst_comp_inl, monoid_hom.snd_comp_inl, monoid_hom.fst_comp_inr, monoid_hom.snd_comp_inr ], }, } end /-- The commutator of direct product is contained in the direct product of the commutators. See `commutator_pi_pi_of_finite` for equality given `fintype η`. -/ lemma commutator_pi_pi_le {η : Type*} {Gs : η → Type*} [∀ i, group (Gs i)] (H K : Π i, subgroup (Gs i)) : ⁅subgroup.pi set.univ H, subgroup.pi set.univ K⁆ ≤ subgroup.pi set.univ (λ i, ⁅H i, K i⁆) := commutator_le.mpr $ λ p hp q hq i hi, commutator_mem_commutator (hp i hi) (hq i hi) /-- The commutator of a finite direct product is contained in the direct product of the commutators. -/ lemma commutator_pi_pi_of_finite {η : Type*} [finite η] {Gs : η → Type*} [∀ i, group (Gs i)] (H K : Π i, subgroup (Gs i)) : ⁅subgroup.pi set.univ H, subgroup.pi set.univ K⁆ = subgroup.pi set.univ (λ i, ⁅H i, K i⁆) := begin classical, apply le_antisymm (commutator_pi_pi_le H K), { rw pi_le_iff, intros i hi, rw map_commutator, apply commutator_mono; { rw le_pi_iff, intros j hj, rintros _ ⟨_, ⟨x, hx, rfl⟩, rfl⟩, by_cases h : j = i, { subst h, simpa using hx, }, { simp [h, one_mem] }, }, }, end end subgroup variables (G) /-- The set of commutator elements `⁅g₁, g₂⁆` in `G`. -/ def commutator_set : set G := {g | ∃ g₁ g₂ : G, ⁅g₁, g₂⁆ = g} lemma commutator_set_def : commutator_set G = {g | ∃ g₁ g₂ : G, ⁅g₁, g₂⁆ = g} := rfl lemma one_mem_commutator_set : (1 : G) ∈ commutator_set G := ⟨1, 1, commutator_element_self 1⟩ instance : nonempty (commutator_set G) := ⟨⟨1, one_mem_commutator_set G⟩⟩ variables {G g} lemma mem_commutator_set_iff : g ∈ commutator_set G ↔ ∃ g₁ g₂ : G, ⁅g₁, g₂⁆ = g := iff.rfl lemma commutator_mem_commutator_set : ⁅g₁, g₂⁆ ∈ commutator_set G := ⟨g₁, g₂, rfl⟩
d2e118c264fb43c0096000b6b4d5fc36949668e3
d642a6b1261b2cbe691e53561ac777b924751b63
/src/topology/uniform_space/completion.lean
5e40874f04a24d14bcfbe423dc9f0a85c57d8299
[ "Apache-2.0" ]
permissive
cipher1024/mathlib
fee56b9954e969721715e45fea8bcb95f9dc03fe
d077887141000fefa5a264e30fa57520e9f03522
refs/heads/master
1,651,806,490,504
1,573,508,694,000
1,573,508,694,000
107,216,176
0
0
Apache-2.0
1,647,363,136,000
1,508,213,014,000
Lean
UTF-8
Lean
false
false
24,917
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 /-- 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⟧) ≤ nhds 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⟧) (nhds 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 : closure (range (coe : α → completion α)) = univ := by rw [completion.coe_eq, range_comp]; exact quotient_dense_of_dense pure_cauchy_dense 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 := (dense_range_iff_closure_eq _).2 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_range_iff_closure_eq _).2 dense, ..(uniform_inducing_coe α).inducing } lemma dense_embedding_coe [separated α]: dense_embedding (coe : α → completion α) := { inj := injective_separated_pure_cauchy, ..dense_inducing_coe } lemma dense₂ : closure (range (λx:α × β, ((x.1 : completion α), (x.2 : completion β)))) = univ := by rw [← set.prod_range_range_eq, closure_prod_eq, dense, dense, univ_prod_univ] lemma dense₃ : closure (range (λx:α × (β × γ), ((x.1 : completion α), ((x.2.1 : completion β), (x.2.2 : completion γ))))) = univ := let a : α → completion α := coe, bc := λp:β × γ, ((p.1 : completion β), (p.2 : completion γ)) in show closure (range (λx:α × (β × γ), (a x.1, bc x.2))) = univ, begin rw [← set.prod_range_range_eq, @closure_prod_eq _ _ _ _ (range a) (range bc), ← univ_prod_univ], congr, exact dense, exact dense₂ end @[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) @[elab_as_eliminator] lemma induction_on₄ {δ : Type*} [uniform_space δ] {p : completion α → completion β → completion γ → completion δ → Prop} (a : completion α) (b : completion β) (c : completion γ) (d : completion δ) (hp : is_closed {x : (completion α × completion β) × (completion γ × completion δ) | p x.1.1 x.1.2 x.2.1 x.2.2}) (ih : ∀(a:α) (b:β) (c:γ) (d : δ), p ↑a ↑b ↑c ↑d) : p a b c d := let ab := λp:α × β, ((p.1 : completion α), (p.2 : completion β)), cd := λp:γ × δ, ((p.1 : completion γ), (p.2 : completion δ)) in have dense₄ : closure (range (λx:(α × β) × (γ × δ), (ab x.1, cd x.2))) = univ, begin rw [← set.prod_range_range_eq, @closure_prod_eq _ _ _ _ (range ab) (range cd), ← univ_prod_univ], congr, exact dense₂, exact dense₂ end, have ∀x:(completion α × completion β) × (completion γ × completion δ), p x.1.1 x.1.2 x.2.1 x.2.2, from is_closed_property dense₄ hp (assume p:(α×β)×(γ×δ), ih p.1.1 p.1.2 p.2.1 p.2.2), this ((a, b), (c, d)) 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 completion.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
92a80fda05854bf8667c7aee6d729c6c979cb59f
0c1546a496eccfb56620165cad015f88d56190c5
/library/init/meta/injection_tactic.lean
03103a8cf87c8c245a863a93e6926356a528bf27
[ "Apache-2.0" ]
permissive
Solertis/lean
491e0939957486f664498fbfb02546e042699958
84188c5aa1673fdf37a082b2de8562dddf53df3f
refs/heads/master
1,610,174,257,606
1,486,263,620,000
1,486,263,620,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,000
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.tactic init.function namespace tactic open nat tactic environment expr list private meta def mk_intro_name : name → list name → name | n₁ (n₂ :: ns) := n₂ | n [] := if n = `a then `h else n -- Auxiliary function for introducing the new equalities produced by the -- injection tactic private meta def injection_intro : expr → list name → tactic unit | (pi n bi b d) ns := do hname ← return $ mk_intro_name n ns, h ← intro hname, ht ← infer_type h, -- Clear new hypothesis if it is of the form (a = a) @try unit $ do { (lhs, rhs) ← match_eq ht, unify lhs rhs, clear h }, -- If new hypothesis is of the form (@heq A a B b) where -- A and B can be unified then convert it into (a = b) using -- the eq_of_heq lemma @try unit $ do { (A, lhs, B, rhs) ← match_heq ht, unify A B, heq ← mk_app `eq [lhs, rhs], pr ← mk_app `eq_of_heq [h], assertv hname heq pr, clear h }, injection_intro d (tail ns) | e ns := skip meta def injection_with (h : expr) (ns : list name) : tactic unit := do ht ← infer_type h, (lhs, rhs) ← match_eq ht, env ← get_env, if is_constructor_app env lhs ∧ is_constructor_app env rhs ∧ const_name (get_app_fn lhs) = const_name (get_app_fn rhs) then do tgt ← target, I_name ← return $ name.get_prefix (const_name (get_app_fn lhs)), pr ← mk_app (I_name <.> "no_confusion") [tgt, lhs, rhs, h], pr_type ← infer_type pr, pr_type ← whnf pr_type, apply pr, injection_intro (binding_domain pr_type) ns else fail "injection tactic failed, argument must be an equality proof where lhs and rhs are of the form (c ...), where c is a constructor" meta def injection (h : expr) : tactic unit := injection_with h [] end tactic
e66727f78a1d219439629608ca05daa96866ec38
fe84e287c662151bb313504482b218a503b972f3
/src/data/function_transfer.lean
be2f32465029625e74e6e2c7461b76d6e98b38bd
[]
no_license
NeilStrickland/lean_lib
91e163f514b829c42fe75636407138b5c75cba83
6a9563de93748ace509d9db4302db6cd77d8f92c
refs/heads/master
1,653,408,198,261
1,652,996,419,000
1,652,996,419,000
181,006,067
4
1
null
null
null
null
UTF-8
Lean
false
false
1,120
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland The formation of function types `α → β` is functorial with respect to equivalences of `α` and `β`. This should be placed in some more general context. -/ import logic.equiv.basic open equiv universes u v w x def function_equiv_of_equiv {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} (f : α ≃ γ) (g : β ≃ δ) : (α → β) ≃ (γ → δ) := { to_fun := λ (u : α → β), g ∘ u ∘ f.inv_fun, inv_fun := λ (v : γ → δ), g.inv_fun ∘ v ∘ f, left_inv := begin unfold function.left_inverse, intro u, ext a, by calc g.inv_fun (g.to_fun (u (f.inv_fun (f.to_fun a)))) = u (f.inv_fun (f.to_fun a)) : g.left_inv _ ... = u a : congr_arg u (f.left_inv a), end, right_inv := begin unfold function.right_inverse, intro v, ext c, by calc g.to_fun (g.inv_fun (v (f.to_fun (f.inv_fun c)))) = v (f.to_fun (f.inv_fun c)) : g.right_inv _ ... = v c : congr_arg v (f.right_inv c) end }
502a7ca8c673d642bc4c7f0666edcee66b7f2d4e
2c096fdfecf64e46ea7bc6ce5521f142b5926864
/src/Lean/Parser/Term.lean
1385f91e89676e1ac243b0f75119237b92e03124
[ "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
Kha/lean4
1005785d2c8797ae266a303968848e5f6ce2fe87
b99e11346948023cd6c29d248cd8f3e3fb3474cf
refs/heads/master
1,693,355,498,027
1,669,080,461,000
1,669,113,138,000
184,748,176
0
0
Apache-2.0
1,665,995,520,000
1,556,884,930,000
Lean
UTF-8
Lean
false
false
31,396
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Parser.Attr import Lean.Parser.Level namespace Lean namespace Parser namespace Command def commentBody : Parser := { fn := rawFn (finishCommentBlock (pushMissingOnError := true) 1) (trailingWs := true) } @[combinator_parenthesizer commentBody] def commentBody.parenthesizer := PrettyPrinter.Parenthesizer.visitToken @[combinator_formatter commentBody] def commentBody.formatter := PrettyPrinter.Formatter.visitAtom Name.anonymous def docComment := leading_parser ppDedent $ "/--" >> ppSpace >> commentBody >> ppLine end Command builtin_initialize registerBuiltinParserAttribute `builtin_tactic_parser ``Category.tactic .both registerBuiltinDynamicParserAttribute `tactic_parser `tactic @[inline] def tacticParser (rbp : Nat := 0) : Parser := categoryParser `tactic rbp @[inline] def convParser (rbp : Nat := 0) : Parser := categoryParser `conv rbp namespace Tactic @[run_builtin_parser_attribute_hooks] def sepByIndentSemicolon (p : Parser) : Parser := sepByIndent p "; " (allowTrailingSep := true) @[run_builtin_parser_attribute_hooks] def sepBy1IndentSemicolon (p : Parser) : Parser := sepBy1Indent p "; " (allowTrailingSep := true) builtin_initialize register_parser_alias sepByIndentSemicolon register_parser_alias sepBy1IndentSemicolon def tacticSeq1Indented : Parser := leading_parser sepBy1IndentSemicolon tacticParser /-- The syntax `{ tacs }` is an alternative syntax for `· tacs`. It runs the tactics in sequence, and fails if the goal is not solved. -/ def tacticSeqBracketed : Parser := leading_parser "{" >> sepByIndentSemicolon tacticParser >> ppDedent (ppLine >> "}") /-- A sequence of tactics in brackets, or a delimiter-free indented sequence of tactics. Delimiter-free indentation is determined by the *first* tactic of the sequence. -/ def tacticSeq := leading_parser tacticSeqBracketed <|> tacticSeq1Indented /-- Same as [`tacticSeq`] but requires delimiter-free tactic sequence to have strict indentation. The strict indentation requirement only apply to *nested* `by`s, as top-level `by`s do not have a position set. -/ def tacticSeqIndentGt := withAntiquot (mkAntiquot "tacticSeq" ``tacticSeq) <| node ``tacticSeq <| tacticSeqBracketed <|> (checkColGt "strict indentation" >> tacticSeq1Indented) /- Raw sequence for quotation and grouping -/ def seq1 := node `Lean.Parser.Tactic.seq1 $ sepBy1 tacticParser ";\n" (allowTrailingSep := true) end Tactic def darrow : Parser := " => " def semicolonOrLinebreak := ";" <|> checkLinebreakBefore >> pushNone namespace Term /-! # Built-in parsers -/ /-- `by tac` constructs a term of the expected type by running the tactic(s) `tac`. -/ @[builtin_term_parser] def byTactic := leading_parser:leadPrec ppAllowUngrouped >> "by " >> Tactic.tacticSeqIndentGt /- This is the same as `byTactic`, but it uses a different syntax kind. This is used by `show` and `suffices` instead of `byTactic` because these syntaxes don't support arbitrary terms where `byTactic` is accepted. Mathport uses this to e.g. safely find-replace `by exact $e` by `$e` in any context without causing incorrect syntax when the full expression is `show $T by exact $e`. -/ def byTactic' := leading_parser "by " >> Tactic.tacticSeqIndentGt -- TODO: rename to e.g. `afterSemicolonOrLinebreak` def optSemicolon (p : Parser) : Parser := ppDedent $ semicolonOrLinebreak >> ppLine >> p -- `checkPrec` necessary for the pretty printer @[builtin_term_parser] def ident := checkPrec maxPrec >> Parser.ident @[builtin_term_parser] def num : Parser := checkPrec maxPrec >> numLit @[builtin_term_parser] def scientific : Parser := checkPrec maxPrec >> scientificLit @[builtin_term_parser] def str : Parser := checkPrec maxPrec >> strLit @[builtin_term_parser] def char : Parser := checkPrec maxPrec >> charLit /-- A type universe. `Type ≡ Type 0`, `Type u ≡ Sort (u + 1)`. -/ @[builtin_term_parser] def type := leading_parser "Type" >> optional (checkWsBefore "" >> checkPrec leadPrec >> checkColGt >> levelParser maxPrec) /-- A specific universe in Lean's infinite hierarchy of universes. -/ @[builtin_term_parser] def sort := leading_parser "Sort" >> optional (checkWsBefore "" >> checkPrec leadPrec >> checkColGt >> levelParser maxPrec) /-- The universe of propositions. `Prop ≡ Sort 0`. -/ @[builtin_term_parser] def prop := leading_parser "Prop" /-- A placeholder term, to be synthesized by unification. -/ @[builtin_term_parser] def hole := leading_parser "_" @[builtin_term_parser] def syntheticHole := leading_parser "?" >> (ident <|> hole) /-- A temporary placeholder for a missing proof or value. -/ @[builtin_term_parser] def «sorry» := leading_parser "sorry" /-- A placeholder for an implicit lambda abstraction's variable. The lambda abstraction is scoped to the surrounding parentheses. For example, `(· + ·)` is equivalent to `fun x y => x + y`. -/ @[builtin_term_parser] def cdot := leading_parser symbol "·" <|> "." /-- Type ascription notation: `(0 : Int)` instructs Lean to process `0` as a value of type `Int`. An empty type ascription `(e :)` elaborates `e` without the expected type. This is occasionally useful when Lean's heuristics for filling arguments from the expected type do not yield the right result. -/ @[builtin_term_parser] def typeAscription := leading_parser "(" >> (withoutPosition (withoutForbidden (termParser >> " : " >> optional termParser))) >> ")" /-- Tuple notation; `()` is short for `Unit.unit`, `(a, b, c)` for `Prod.mk a (Prod.mk b c)`, etc. -/ @[builtin_term_parser] def tuple := leading_parser "(" >> optional (withoutPosition (withoutForbidden (termParser >> ", " >> sepBy1 termParser ", "))) >> ")" /-- Parentheses, used for grouping expressions (e.g., `a * (b + c)`). Can also be used for creating simple functions when combined with `·`. Here are some examples: - `(· + 1)` is shorthand for `fun x => x + 1` - `(· + ·)` is shorthand for `fun x y => x + y` - `(f · a b)` is shorthand for `fun x => f x a b` - `(h (· + 1) ·)` is shorthand for `fun x => h (fun y => y + 1) x` - also applies to other parentheses-like notations such as `(·, 1)` -/ @[builtin_term_parser] def paren := leading_parser "(" >> withoutPosition (withoutForbidden (ppDedentIfGrouped termParser)) >> ")" /-- The *anonymous constructor* `⟨e, ...⟩` is equivalent to `c e ...` if the expected type is an inductive type with a single constructor `c`. If more terms are given than `c` has parameters, the remaining arguments are turned into a new anonymous constructor application. For example, `⟨a, b, c⟩ : α × (β × γ)` is equivalent to `⟨a, ⟨b, c⟩⟩`. -/ @[builtin_term_parser] def anonymousCtor := leading_parser "⟨" >> sepBy termParser ", " >> "⟩" def optIdent : Parser := optional (atomic (ident >> " : ")) def fromTerm := leading_parser "from " >> termParser def showRhs := fromTerm <|> byTactic' def sufficesDecl := leading_parser optIdent >> termParser >> ppSpace >> showRhs @[builtin_term_parser] def «suffices» := leading_parser:leadPrec withPosition ("suffices " >> sufficesDecl) >> optSemicolon termParser @[builtin_term_parser] def «show» := leading_parser:leadPrec "show " >> termParser >> ppSpace >> showRhs def structInstArrayRef := leading_parser "[" >> withoutPosition termParser >>"]" def structInstLVal := leading_parser (ident <|> fieldIdx <|> structInstArrayRef) >> many (group ("." >> (ident <|> fieldIdx)) <|> structInstArrayRef) def structInstField := ppGroup $ leading_parser structInstLVal >> " := " >> termParser def structInstFieldAbbrev := leading_parser -- `x` is an abbreviation for `x := x` atomic (ident >> notFollowedBy ("." <|> ":=" <|> symbol "[") "invalid field abbreviation") def optEllipsis := leading_parser optional ".." /-- Structure instance. `{ x := e, ... }` assigns `e` to field `x`, which may be inherited. If `e` is itself a variable called `x`, it can be elided: `fun y => { x := 1, y }`. A *structure update* of an existing value can be given via `with`: `{ point with x := 1 }`. The structure type can be specified if not inferable: `{ x := 1, y := 2 : Point }`. -/ @[builtin_term_parser] def structInst := leading_parser "{" >> withoutPosition (ppHardSpace >> optional (atomic (sepBy1 termParser ", " >> " with ")) >> sepByIndent (structInstFieldAbbrev <|> structInstField) ", " (allowTrailingSep := true) >> optEllipsis >> optional (" : " >> termParser)) >> " }" def typeSpec := leading_parser " : " >> termParser def optType : Parser := optional typeSpec /-- `@x` disables automatic insertion of implicit parameters of the constant `x`. `@e` for any term `e` also disables the insertion of implicit lambdas at this position. -/ @[builtin_term_parser] def explicit := leading_parser "@" >> termParser maxPrec /-- `.(e)` marks an "inaccessible pattern", which does not influence evaluation of the pattern match, but may be necessary for type-checking. In contrast to regular patterns, `e` may be an arbitrary term of the appropriate type. -/ @[builtin_term_parser] def inaccessible := leading_parser ".(" >> withoutPosition termParser >> ")" def binderIdent : Parser := ident <|> hole def binderType (requireType := false) : Parser := if requireType then node nullKind (" : " >> termParser) else optional (" : " >> termParser) def binderTactic := leading_parser atomic (symbol " := " >> " by ") >> Tactic.tacticSeq def binderDefault := leading_parser " := " >> termParser def explicitBinder (requireType := false) := ppGroup $ leading_parser "(" >> withoutPosition (many1 binderIdent >> binderType requireType >> optional (binderTactic <|> binderDefault)) >> ")" /-- Implicit binder. In regular applications without `@`, it is automatically inserted and solved by unification whenever all explicit parameters before it are specified. -/ def implicitBinder (requireType := false) := ppGroup $ leading_parser "{" >> withoutPosition (many1 binderIdent >> binderType requireType) >> "}" def strictImplicitLeftBracket := atomic (group (symbol "{" >> "{")) <|> "⦃" def strictImplicitRightBracket := atomic (group (symbol "}" >> "}")) <|> "⦄" /-- Strict-implicit binder. In contrast to `{ ... }` regular implicit binders, a strict-implicit binder is inserted automatically only when at least one subsequent explicit parameter is specified. -/ def strictImplicitBinder (requireType := false) := ppGroup <| leading_parser strictImplicitLeftBracket >> many1 binderIdent >> binderType requireType >> strictImplicitRightBracket /-- Instance-implicit binder. In regular applications without `@`, it is automatically inserted and solved by typeclass inference of the specified class. -/ def instBinder := ppGroup <| leading_parser "[" >> withoutPosition (optIdent >> termParser) >> "]" def bracketedBinder (requireType := false) := withAntiquot (mkAntiquot "bracketedBinder" decl_name% (isPseudoKind := true)) <| explicitBinder requireType <|> strictImplicitBinder requireType <|> implicitBinder requireType <|> instBinder /- It is feasible to support dependent arrows such as `{α} → α → α` without sacrificing the quality of the error messages for the longer case. `{α} → α → α` would be short for `{α : Type} → α → α` Here is the encoding: ``` def implicitShortBinder := node `Lean.Parser.Term.implicitBinder $ "{" >> many1 binderIdent >> pushNone >> "}" def depArrowShortPrefix := try (implicitShortBinder >> unicodeSymbol " → " " -> ") def depArrowLongPrefix := bracketedBinder true >> unicodeSymbol " → " " -> " def depArrowPrefix := depArrowShortPrefix <|> depArrowLongPrefix @[builtin_term_parser] def depArrow := leading_parser depArrowPrefix >> termParser ``` Note that no changes in the elaborator are needed. We decided to not use it because terms such as `{α} → α → α` may look too cryptic. Note that we did not add a `explicitShortBinder` parser since `(α) → α → α` is really cryptic as a short for `(α : Type) → α → α`. -/ @[builtin_term_parser] def depArrow := leading_parser:25 bracketedBinder true >> unicodeSymbol " → " " -> " >> termParser @[builtin_term_parser] def «forall» := leading_parser:leadPrec unicodeSymbol "∀" "forall" >> many1 (ppSpace >> (binderIdent <|> bracketedBinder)) >> optType >> ", " >> termParser def matchAlt (rhsParser : Parser := termParser) : Parser := leading_parser (withAnonymousAntiquot := false) "| " >> ppIndent ( sepBy1 (sepBy1 termParser ", ") "|" >> darrow >> checkColGe "alternative right-hand-side to start in a column greater than or equal to the corresponding '|'" >> rhsParser) /-- Useful for syntax quotations. Note that generic patterns such as `` `(matchAltExpr| | ... => $rhs) `` should also work with other `rhsParser`s (of arity 1). -/ def matchAltExpr := matchAlt instance : Coe (TSyntax ``matchAltExpr) (TSyntax ``matchAlt) where coe stx := ⟨stx.raw⟩ def matchAlts (rhsParser : Parser := termParser) : Parser := leading_parser withPosition $ many1Indent (ppLine >> matchAlt rhsParser) def matchDiscr := leading_parser optional (atomic (ident >> " : ")) >> termParser def trueVal := leading_parser nonReservedSymbol "true" def falseVal := leading_parser nonReservedSymbol "false" def generalizingParam := leading_parser atomic ("(" >> nonReservedSymbol "generalizing") >> " := " >> (trueVal <|> falseVal) >> ")" >> ppSpace def motive := leading_parser atomic ("(" >> nonReservedSymbol "motive" >> " := ") >> withoutPosition termParser >> ")" >> ppSpace /-- Pattern matching. `match e, ... with | p, ... => f | ...` matches each given term `e` against each pattern `p` of a match alternative. When all patterns of an alternative match, the `match` term evaluates to the value of the corresponding right-hand side `f` with the pattern variables bound to the respective matched values. When not constructing a proof, `match` does not automatically substitute variables matched on in dependent variables' types. Use `match (generalizing := true) ...` to enforce this. Syntax quotations can also be used in a pattern match. This matches a `Syntax` value against quotations, pattern variables, or `_`. Quoted identifiers only match identical identifiers - custom matching such as by the preresolved names only should be done explicitly. `Syntax.atom`s are ignored during matching by default except when part of a built-in literal. For users introducing new atoms, we recommend wrapping them in dedicated syntax kinds if they should participate in matching. For example, in ```lean syntax "c" ("foo" <|> "bar") ... ``` `foo` and `bar` are indistinguishable during matching, but in ```lean syntax foo := "foo" syntax "c" (foo <|> "bar") ... ``` they are not. -/ @[builtin_term_parser] def «match» := leading_parser:leadPrec "match " >> optional generalizingParam >> optional motive >> sepBy1 matchDiscr ", " >> " with " >> ppDedent matchAlts /-- Empty match/ex falso. `nomatch e` is of arbitrary type `α : Sort u` if Lean can show that an empty set of patterns is exhaustive given `e`'s type, e.g. because it has no constructors. -/ @[builtin_term_parser] def «nomatch» := leading_parser:leadPrec "nomatch " >> termParser def funImplicitBinder := withAntiquot (mkAntiquot "implicitBinder" ``implicitBinder) <| atomic (lookahead ("{" >> many1 binderIdent >> (symbol " : " <|> "}"))) >> implicitBinder def funStrictImplicitBinder := atomic (lookahead ( strictImplicitLeftBracket >> many1 binderIdent >> (symbol " : " <|> strictImplicitRightBracket))) >> strictImplicitBinder def funBinder : Parser := withAntiquot (mkAntiquot "funBinder" decl_name% (isPseudoKind := true)) <| funStrictImplicitBinder <|> funImplicitBinder <|> instBinder <|> termParser maxPrec -- NOTE: we disable anonymous antiquotations to ensure that `fun $b => ...` -- remains a `term` antiquotation def basicFun : Parser := leading_parser (withAnonymousAntiquot := false) ppGroup (many1 (ppSpace >> funBinder) >> optType >> " =>") >> ppSpace >> termParser @[builtin_term_parser] def «fun» := leading_parser:maxPrec ppAllowUngrouped >> unicodeSymbol "λ" "fun" >> (basicFun <|> matchAlts) def optExprPrecedence := optional (atomic ":" >> termParser maxPrec) def withAnonymousAntiquot := leading_parser atomic ("(" >> nonReservedSymbol "withAnonymousAntiquot" >> " := ") >> (trueVal <|> falseVal) >> ")" >> ppSpace @[builtin_term_parser] def «leading_parser» := leading_parser:leadPrec "leading_parser " >> optExprPrecedence >> optional withAnonymousAntiquot >> termParser @[builtin_term_parser] def «trailing_parser» := leading_parser:leadPrec "trailing_parser " >> optExprPrecedence >> optExprPrecedence >> termParser @[builtin_term_parser] def borrowed := leading_parser "@& " >> termParser leadPrec /-- A literal of type `Name`. -/ @[builtin_term_parser] def quotedName := leading_parser nameLit /-- A resolved name literal. Evaluates to the full name of the given constant if existent in the current context, or else fails. -/ -- use `rawCh` because ``"`" >> ident`` overlaps with `nameLit`, with the latter being preferred by the tokenizer -- note that we cannot use ```"``"``` as a new token either because it would break `precheckedQuot` @[builtin_term_parser] def doubleQuotedName := leading_parser "`" >> checkNoWsBefore >> rawCh '`' (trailingWs := false) >> ident def letIdBinder := withAntiquot (mkAntiquot "letIdBinder" decl_name% (isPseudoKind := true)) <| binderIdent <|> bracketedBinder /- Remark: we use `checkWsBefore` to ensure `let x[i] := e; b` is not parsed as `let x [i] := e; b` where `[i]` is an `instBinder`. -/ def letIdLhs : Parser := ident >> notFollowedBy (checkNoWsBefore "" >> "[") "space is required before instance '[...]' binders to distinguish them from array updates `let x[i] := e; ...`" >> many (ppSpace >> letIdBinder) >> optType def letIdDecl := leading_parser (withAnonymousAntiquot := false) atomic (letIdLhs >> " := ") >> termParser def letPatDecl := leading_parser (withAnonymousAntiquot := false) atomic (termParser >> pushNone >> optType >> " := ") >> termParser /- Remark: the following `(" := " <|> matchAlts)` is a hack we use to produce a better error message at `letDecl`. Consider this following example ``` def myFun (n : Nat) : IO Nat := let q ← (10 : Nat) n + q ``` Without the hack, we get the error `expected '|'` at `←`. Reason: at `letDecl`, we use the parser `(letIdDecl <|> letPatDecl <|> letEqnsDecl)`, `letIdDecl` and `letEqnsDecl` have the same prefix `letIdLhs`, but `letIdDecl` uses `atomic`. Note that the hack relies on the fact that the parser `":="` never succeeds at `(" := " <|> matchAlts)`. It is there just to make sure we produce the error `expected ':=' or '|'` -/ def letEqnsDecl := leading_parser (withAnonymousAntiquot := false) letIdLhs >> (" := " <|> matchAlts) -- Remark: we disable anonymous antiquotations here to make sure -- anonymous antiquotations (e.g., `$x`) are not `letDecl` def letDecl := leading_parser (withAnonymousAntiquot := false) notFollowedBy (nonReservedSymbol "rec") "rec" >> (letIdDecl <|> letPatDecl <|> letEqnsDecl) /-- `let` is used to declare a local definition. Example: ``` let x := 1 let y := x + 1 x + y ``` Since functions are first class citizens in Lean, you can use `let` to declare local functions too. ``` let double := fun x => 2*x double (double 3) ``` For recursive definitions, you should use `let rec`. You can also perform pattern matching using `let`. For example, assume `p` has type `Nat × Nat`, then you can write ``` let (x, y) := p x + y ``` -/ @[builtin_term_parser] def «let» := leading_parser:leadPrec withPosition ("let " >> letDecl) >> optSemicolon termParser /-- `let_fun x := v; b` is syntax sugar for `(fun x => b) v`. It is very similar to `let x := v; b`, but they are not equivalent. In `let_fun`, the value `v` has been abstracted away and cannot be accessed in `b`. -/ @[builtin_term_parser] def «let_fun» := leading_parser:leadPrec withPosition ((symbol "let_fun " <|> "let_λ") >> letDecl) >> optSemicolon termParser /-- `let_delayed x := v; b` is similar to `let x := v; b`, but `b` is elaborated before `v`. -/ @[builtin_term_parser] def «let_delayed» := leading_parser:leadPrec withPosition ("let_delayed " >> letDecl) >> optSemicolon termParser /-- `let`-declaration that is only included in the elaborated term if variable is still there. It is often used when building macros. -/ @[builtin_term_parser] def «let_tmp» := leading_parser:leadPrec withPosition ("let_tmp " >> letDecl) >> optSemicolon termParser /- like `let_fun` but with optional name -/ def haveIdLhs := optional (ident >> many (ppSpace >> letIdBinder)) >> optType def haveIdDecl := leading_parser (withAnonymousAntiquot := false) atomic (haveIdLhs >> " := ") >> termParser def haveEqnsDecl := leading_parser (withAnonymousAntiquot := false) haveIdLhs >> matchAlts def haveDecl := leading_parser (withAnonymousAntiquot := false) haveIdDecl <|> letPatDecl <|> haveEqnsDecl @[builtin_term_parser] def «have» := leading_parser:leadPrec withPosition ("have " >> haveDecl) >> optSemicolon termParser def «scoped» := leading_parser "scoped " def «local» := leading_parser "local " def attrKind := leading_parser optional («scoped» <|> «local») def attrInstance := ppGroup $ leading_parser attrKind >> attrParser def attributes := leading_parser "@[" >> withoutPosition (sepBy1 attrInstance ", ") >> "]" def letRecDecl := leading_parser optional Command.docComment >> optional «attributes» >> letDecl def letRecDecls := leading_parser sepBy1 letRecDecl ", " @[builtin_term_parser] def «letrec» := leading_parser:leadPrec withPosition (group ("let " >> nonReservedSymbol "rec ") >> letRecDecls) >> optSemicolon termParser @[run_builtin_parser_attribute_hooks] def whereDecls := leading_parser " where" >> sepBy1Indent (ppGroup letRecDecl) "; " (allowTrailingSep := true) @[run_builtin_parser_attribute_hooks] def matchAltsWhereDecls := leading_parser matchAlts >> optional whereDecls @[builtin_term_parser] def noindex := leading_parser "no_index " >> termParser maxPrec @[builtin_term_parser] def binrel := leading_parser "binrel% " >> ident >> ppSpace >> termParser maxPrec >> termParser maxPrec /-- Similar to `binrel`, but coerce `Prop` arguments into `Bool`. -/ @[builtin_term_parser] def binrel_no_prop := leading_parser "binrel_no_prop% " >> ident >> ppSpace >> termParser maxPrec >> termParser maxPrec @[builtin_term_parser] def binop := leading_parser "binop% " >> ident >> ppSpace >> termParser maxPrec >> termParser maxPrec @[builtin_term_parser] def binop_lazy := leading_parser "binop_lazy% " >> ident >> ppSpace >> termParser maxPrec >> termParser maxPrec @[builtin_term_parser] def unop := leading_parser "unop% " >> ident >> ppSpace >> termParser maxPrec @[builtin_term_parser] def forInMacro := leading_parser "for_in% " >> termParser maxPrec >> termParser maxPrec >> termParser maxPrec @[builtin_term_parser] def forInMacro' := leading_parser "for_in'% " >> termParser maxPrec >> termParser maxPrec >> termParser maxPrec /-- A macro which evaluates to the name of the currently elaborating declaration. -/ @[builtin_term_parser] def declName := leading_parser "decl_name%" /-- * `with_decl_name% id e` elaborates `e` in a context while changing the effective declaration name to `id`. * `with_decl_name% ?id e` does the same, but resolves `id` as a new definition name (appending the current namespaces). -/ @[builtin_term_parser] def withDeclName := leading_parser "with_decl_name% " >> optional "?" >> ident >> termParser @[builtin_term_parser] def typeOf := leading_parser "type_of% " >> termParser maxPrec @[builtin_term_parser] def ensureTypeOf := leading_parser "ensure_type_of% " >> termParser maxPrec >> strLit >> termParser @[builtin_term_parser] def ensureExpectedType := leading_parser "ensure_expected_type% " >> strLit >> termParser maxPrec @[builtin_term_parser] def noImplicitLambda := leading_parser "no_implicit_lambda% " >> termParser maxPrec /-- `clear% x; e` elaborates `x` after clearing the free variable `x` from the local context. If `x` cannot be cleared (due to dependencies), it will keep `x` without failing. -/ @[builtin_term_parser] def clear := leading_parser "clear% " >> ident >> semicolonOrLinebreak >> termParser @[builtin_term_parser] def letMVar := leading_parser "let_mvar% " >> "?" >> ident >> " := " >> termParser >> "; " >> termParser @[builtin_term_parser] def waitIfTypeMVar := leading_parser "wait_if_type_mvar% " >> "?" >> ident >> "; " >> termParser @[builtin_term_parser] def waitIfTypeContainsMVar := leading_parser "wait_if_type_contains_mvar% " >> "?" >> ident >> "; " >> termParser @[builtin_term_parser] def waitIfContainsMVar := leading_parser "wait_if_contains_mvar% " >> "?" >> ident >> "; " >> termParser @[builtin_term_parser] def defaultOrOfNonempty := leading_parser "default_or_ofNonempty% " >> optional "unsafe" /-- Helper parser for marking `match`-alternatives that should not trigger errors if unused. We use them to implement `macro_rules` and `elab_rules` -/ @[builtin_term_parser] def noErrorIfUnused := leading_parser "no_error_if_unused%" >> termParser def namedArgument := leading_parser (withAnonymousAntiquot := false) atomic ("(" >> ident >> " := ") >> withoutPosition termParser >> ")" def ellipsis := leading_parser (withAnonymousAntiquot := false) ".." >> notFollowedBy "." "`.` immediately after `..`" def argument := checkWsBefore "expected space" >> checkColGt "expected to be indented" >> (namedArgument <|> ellipsis <|> termParser argPrec) -- `app` precedence is `lead` (cannot be used as argument) -- `lhs` precedence is `max` (i.e. does not accept `arg` precedence) -- argument precedence is `arg` (i.e. does not accept `lead` precedence) @[builtin_term_parser] def app := trailing_parser:leadPrec:maxPrec many1 argument /-- The *extended field notation* `e.f` is roughly short for `T.f e` where `T` is the type of `e`. More precisely, * if `e` is of a function type, `e.f` is translated to `Function.f (p := e)` where `p` is the first explicit parameter of function type * if `e` is of a named type `T ...` and there is a declaration `T.f` (possibly from `export`), `e.f` is translated to `T.f (p := e)` where `p` is the first explicit parameter of type `T ...` * otherwise, if `e` is of a structure type, the above is repeated for every base type of the structure. The field index notation `e.i`, where `i` is a positive number, is short for accessing the `i`-th field (1-indexed) of `e` if it is of a structure type. -/ @[builtin_term_parser] def proj := trailing_parser checkNoWsBefore >> "." >> checkNoWsBefore >> (fieldIdx <|> rawIdent) @[builtin_term_parser] def completion := trailing_parser checkNoWsBefore >> "." @[builtin_term_parser] def arrow := trailing_parser checkPrec 25 >> unicodeSymbol " → " " -> " >> termParser 25 def isIdent (stx : Syntax) : Bool := -- antiquotations should also be allowed where an identifier is expected stx.isAntiquot || stx.isIdent /-- `x.{u, ...}` explicitly specifies the universes `u, ...` of the constant `x`. -/ @[builtin_term_parser] def explicitUniv : TrailingParser := trailing_parser checkStackTop isIdent "expected preceding identifier" >> checkNoWsBefore "no space before '.{'" >> ".{" >> sepBy1 levelParser ", " >> "}" /-- `x@e` matches the pattern `e` and binds its value to the identifier `x`. -/ @[builtin_term_parser] def namedPattern : TrailingParser := trailing_parser checkStackTop isIdent "expected preceding identifier" >> checkNoWsBefore "no space before '@'" >> "@" >> optional (atomic (ident >> ":")) >> termParser maxPrec /-- `e |>.x` is a shorthand for `(e).x`. It is especially useful for avoiding parentheses with repeated applications. -/ @[builtin_term_parser] def pipeProj := trailing_parser:minPrec " |>." >> checkNoWsBefore >> (fieldIdx <|> rawIdent) >> many argument @[builtin_term_parser] def pipeCompletion := trailing_parser:minPrec " |>." /-- `h ▸ e` is a macro built on top of `Eq.rec` and `Eq.symm` definitions. Given `h : a = b` and `e : p a`, the term `h ▸ e` has type `p b`. You can also view `h ▸ e` as a "type casting" operation where you change the type of `e` by using `h`. See the Chapter "Quantifiers and Equality" in the manual "Theorem Proving in Lean" for additional information. -/ @[builtin_term_parser] def subst := trailing_parser:75 " ▸ " >> sepBy1 (termParser 75) " ▸ " def bracketedBinderF := bracketedBinder -- no default arg instance : Coe (TSyntax ``bracketedBinderF) (TSyntax ``bracketedBinder) where coe s := ⟨s⟩ /-- `panic! msg` formally evaluates to `@Inhabited.default α` if the expected type `α` implements `Inhabited`. At runtime, `msg` and the file position are printed to stderr unless the C function `lean_set_panic_messages(false)` has been executed before. If the C function `lean_set_exit_on_panic(true)` has been executed before, the process is then aborted. -/ @[builtin_term_parser] def panic := leading_parser:leadPrec "panic! " >> termParser /-- A shorthand for `panic! "unreachable code has been reached"`. -/ @[builtin_term_parser] def unreachable := leading_parser:leadPrec "unreachable!" /-- `dbg_trace e; body` evaluates to `body` and prints `e` (which can be an interpolated string literal) to stderr. It should only be used for debugging. -/ @[builtin_term_parser] def dbgTrace := leading_parser:leadPrec withPosition ("dbg_trace" >> (interpolatedStr termParser <|> termParser)) >> optSemicolon termParser /-- `assert! cond` panics if `cond` evaluates to `false`. -/ @[builtin_term_parser] def assert := leading_parser:leadPrec withPosition ("assert! " >> termParser) >> optSemicolon termParser def macroArg := termParser maxPrec def macroDollarArg := leading_parser "$" >> termParser 10 def macroLastArg := macroDollarArg <|> macroArg -- Macro for avoiding exponentially big terms when using `STWorld` @[builtin_term_parser] def stateRefT := leading_parser "StateRefT" >> macroArg >> macroLastArg @[builtin_term_parser] def dynamicQuot := withoutPosition <| leading_parser "`(" >> ident >> "|" >> incQuotDepth (parserOfStack 1) >> ")" @[builtin_term_parser] def dotIdent := leading_parser "." >> checkNoWsBefore >> rawIdent end Term @[builtin_term_parser default+1] def Tactic.quot : Parser := leading_parser "`(tactic|" >> withoutPosition (incQuotDepth tacticParser) >> ")" @[builtin_term_parser] def Tactic.quotSeq : Parser := leading_parser "`(tactic|" >> withoutPosition (incQuotDepth Tactic.seq1) >> ")" open Term in builtin_initialize register_parser_alias letDecl register_parser_alias haveDecl register_parser_alias sufficesDecl register_parser_alias letRecDecls register_parser_alias hole register_parser_alias syntheticHole register_parser_alias matchDiscr register_parser_alias bracketedBinder register_parser_alias attrKind end Parser end Lean
22e7d674ebb29d249946442b42d11cc832ce5625
e0b0b1648286e442507eb62344760d5cd8d13f2d
/stage0/src/Init/Meta.lean
33939a1e12dd9a5cedbf32eeb6fc0895fb67fd15
[ "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
29,953
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura and Sebastian Ullrich Additional goodies for writing macros -/ prelude import Init.Data.Array.Basic namespace Lean @[extern c inline "lean_box(LEAN_VERSION_MAJOR)"] private constant version.getMajor (u : Unit) : Nat def version.major : Nat := version.getMajor () @[extern c inline "lean_box(LEAN_VERSION_MINOR)"] private constant version.getMinor (u : Unit) : Nat def version.minor : Nat := version.getMinor () @[extern c inline "lean_box(LEAN_VERSION_PATCH)"] private constant version.getPatch (u : Unit) : Nat def version.patch : Nat := version.getPatch () -- @[extern c inline "lean_mk_string(LEAN_GITHASH)"] -- constant getGithash (u : Unit) : String -- def githash : String := getGithash () @[extern c inline "LEAN_VERSION_IS_RELEASE"] constant version.getIsRelease (u : Unit) : Bool def version.isRelease : Bool := version.getIsRelease () /-- Additional version description like "nightly-2018-03-11" -/ @[extern c inline "lean_mk_string(LEAN_SPECIAL_VERSION_DESC)"] constant version.getSpecialDesc (u : Unit) : String def version.specialDesc : String := version.getSpecialDesc () /- Valid identifier names -/ def isGreek (c : Char) : Bool := 0x391 ≤ c.val && c.val ≤ 0x3dd def isLetterLike (c : Char) : Bool := (0x3b1 ≤ c.val && c.val ≤ 0x3c9 && c.val ≠ 0x3bb) || -- Lower greek, but lambda (0x391 ≤ c.val && c.val ≤ 0x3A9 && c.val ≠ 0x3A0 && c.val ≠ 0x3A3) || -- Upper greek, but Pi and Sigma (0x3ca ≤ c.val && c.val ≤ 0x3fb) || -- Coptic letters (0x1f00 ≤ c.val && c.val ≤ 0x1ffe) || -- Polytonic Greek Extended Character Set (0x2100 ≤ c.val && c.val ≤ 0x214f) || -- Letter like block (0x1d49c ≤ c.val && c.val ≤ 0x1d59f) -- Latin letters, Script, Double-struck, Fractur def isNumericSubscript (c : Char) : Bool := 0x2080 ≤ c.val && c.val ≤ 0x2089 def isSubScriptAlnum (c : Char) : Bool := isNumericSubscript c || (0x2090 ≤ c.val && c.val ≤ 0x209c) || (0x1d62 ≤ c.val && c.val ≤ 0x1d6a) def isIdFirst (c : Char) : Bool := c.isAlpha || c = '_' || isLetterLike c def isIdRest (c : Char) : Bool := c.isAlphanum || c = '_' || c = '\'' || c == '!' || c == '?' || isLetterLike c || isSubScriptAlnum c def idBeginEscape := '«' def idEndEscape := '»' def isIdBeginEscape (c : Char) : Bool := c = idBeginEscape def isIdEndEscape (c : Char) : Bool := c = idEndEscape namespace Name def toStringWithSep (sep : String) : Name → String | anonymous => "[anonymous]" | str anonymous s _ => s | num anonymous v _ => toString v | str n s _ => toStringWithSep sep n ++ sep ++ s | num n v _ => toStringWithSep sep n ++ sep ++ Nat.repr v protected def toString : Name → String := toStringWithSep "." instance : ToString Name where toString n := n.toString instance : Repr Name where reprPrec n _ := Std.Format.text "`" ++ n.toString def capitalize : Name → Name | Name.str p s _ => Name.mkStr p s.capitalize | n => n def replacePrefix : Name → Name → Name → Name | anonymous, anonymous, newP => newP | anonymous, _, _ => anonymous | n@(str p s _), queryP, newP => if n == queryP then newP else Name.mkStr (p.replacePrefix queryP newP) s | n@(num p s _), queryP, newP => if n == queryP then newP else Name.mkNum (p.replacePrefix queryP newP) s /-- Remove macros scopes, apply `f`, and put them back -/ @[inline] def modifyBase (n : Name) (f : Name → Name) : Name := if n.hasMacroScopes then let view := extractMacroScopes n { view with name := f view.name }.review else f n @[export lean_name_append_after] def appendAfter (n : Name) (suffix : String) : Name := n.modifyBase fun | str p s _ => Name.mkStr p (s ++ suffix) | n => Name.mkStr n suffix @[export lean_name_append_index_after] def appendIndexAfter (n : Name) (idx : Nat) : Name := n.modifyBase fun | str p s _ => Name.mkStr p (s ++ "_" ++ toString idx) | n => Name.mkStr n ("_" ++ toString idx) @[export lean_name_append_before] def appendBefore (n : Name) (pre : String) : Name := n.modifyBase fun | anonymous => Name.mkStr anonymous pre | str p s _ => Name.mkStr p (pre ++ s) | num p n _ => Name.mkNum (Name.mkStr p pre) n end Name structure NameGenerator where namePrefix : Name := `_uniq idx : Nat := 1 deriving Inhabited namespace NameGenerator @[inline] def curr (g : NameGenerator) : Name := Name.mkNum g.namePrefix g.idx @[inline] def next (g : NameGenerator) : NameGenerator := { g with idx := g.idx + 1 } @[inline] def mkChild (g : NameGenerator) : NameGenerator × NameGenerator := ({ namePrefix := Name.mkNum g.namePrefix g.idx, idx := 1 }, { g with idx := g.idx + 1 }) end NameGenerator class MonadNameGenerator (m : Type → Type) where getNGen : m NameGenerator setNGen : NameGenerator → m Unit export MonadNameGenerator (getNGen setNGen) def mkFreshId {m : Type → Type} [Monad m] [MonadNameGenerator m] : m Name := do let ngen ← getNGen let r := ngen.curr setNGen ngen.next pure r instance monadNameGeneratorLift (m n : Type → Type) [MonadLift m n] [MonadNameGenerator m] : MonadNameGenerator n := { getNGen := liftM (getNGen : m _), setNGen := fun ngen => liftM (setNGen ngen : m _) } namespace Syntax partial def structEq : Syntax → Syntax → Bool | Syntax.missing, Syntax.missing => true | Syntax.node k args, Syntax.node k' args' => k == k' && args.isEqv args' structEq | Syntax.atom _ val, Syntax.atom _ val' => val == val' | Syntax.ident _ rawVal val preresolved, Syntax.ident _ rawVal' val' preresolved' => rawVal == rawVal' && val == val' && preresolved == preresolved' | _, _ => false instance : BEq Lean.Syntax := ⟨structEq⟩ partial def getTailInfo? : Syntax → Option SourceInfo | atom info _ => info | ident info .. => info | node _ args => args.findSomeRev? getTailInfo? | _ => none def getTailInfo (stx : Syntax) : SourceInfo := stx.getTailInfo?.getD SourceInfo.none def getTrailingSize (stx : Syntax) : Nat := match stx.getTailInfo? with | some (SourceInfo.original (trailing := trailing) ..) => trailing.bsize | _ => 0 @[specialize] private partial def updateLast {α} [Inhabited α] (a : Array α) (f : α → Option α) (i : Nat) : Option (Array α) := if i == 0 then none else let i := i - 1 let v := a[i] match f v with | some v => some <| a.set! i v | none => updateLast a f i partial def setTailInfoAux (info : SourceInfo) : Syntax → Option Syntax | atom _ val => some <| atom info val | ident _ rawVal val pre => some <| ident info rawVal val pre | node k args => match updateLast args (setTailInfoAux info) args.size with | some args => some <| node k args | none => none | stx => none def setTailInfo (stx : Syntax) (info : SourceInfo) : Syntax := match setTailInfoAux info stx with | some stx => stx | none => stx def unsetTrailing (stx : Syntax) : Syntax := match stx.getTailInfo with | SourceInfo.original lead pos trail => stx.setTailInfo (SourceInfo.original lead pos "".toSubstring) | _ => stx @[specialize] private partial def updateFirst {α} [Inhabited α] (a : Array α) (f : α → Option α) (i : Nat) : Option (Array α) := if h : i < a.size then let v := a.get ⟨i, h⟩; match f v with | some v => some <| a.set ⟨i, h⟩ v | none => updateFirst a f (i+1) else none partial def setHeadInfoAux (info : SourceInfo) : Syntax → Option Syntax | atom _ val => some <| atom info val | ident _ rawVal val pre => some <| ident info rawVal val pre | node k args => match updateFirst args (setHeadInfoAux info) 0 with | some args => some <| node k args | noxne => none | stx => none def setHeadInfo (stx : Syntax) (info : SourceInfo) : Syntax := match setHeadInfoAux info stx with | some stx => stx | none => stx def setInfo (info : SourceInfo) : Syntax → Syntax | atom _ val => atom info val | ident _ rawVal val pre => ident info rawVal val pre | stx => stx /-- Return the first atom/identifier that has position information -/ partial def getHead? : Syntax → Option Syntax | stx@(atom info ..) => info.getPos?.map fun _ => stx | stx@(ident info ..) => info.getPos?.map fun _ => stx | node _ args => args.findSome? getHead? | _ => none def copyHeadTailInfoFrom (target source : Syntax) : Syntax := target.setHeadInfo source.getHeadInfo |>.setTailInfo source.getTailInfo end Syntax /-- Use the head atom/identifier of the current `ref` as the `ref` -/ @[inline] def withHeadRefOnly {m : Type → Type} [Monad m] [MonadRef m] {α} (x : m α) : m α := do match (← getRef).getHead? with | none => x | some ref => withRef ref x @[inline] def mkNode (k : SyntaxNodeKind) (args : Array Syntax) : Syntax := Syntax.node k args /- Syntax objects for a Lean module. -/ structure Module where header : Syntax commands : Array Syntax /-- Expand all macros in the given syntax -/ partial def expandMacros : Syntax → MacroM Syntax | stx@(Syntax.node k args) => do match (← expandMacro? stx) with | some stxNew => expandMacros stxNew | none => do let args ← Macro.withIncRecDepth stx <| args.mapM expandMacros pure <| Syntax.node k args | stx => pure stx /- Helper functions for processing Syntax programmatically -/ /-- Create an identifier copying the position from `src`. To refer to a specific constant, use `mkCIdentFrom` instead. -/ def mkIdentFrom (src : Syntax) (val : Name) : Syntax := Syntax.ident (SourceInfo.fromRef src) (toString val).toSubstring val [] def mkIdentFromRef [Monad m] [MonadRef m] (val : Name) : m Syntax := do return mkIdentFrom (← getRef) val /-- Create an identifier referring to a constant `c` copying the position from `src`. This variant of `mkIdentFrom` makes sure that the identifier cannot accidentally be captured. -/ def mkCIdentFrom (src : Syntax) (c : Name) : Syntax := -- Remark: We use the reserved macro scope to make sure there are no accidental collision with our frontend let id := addMacroScope `_internal c reservedMacroScope Syntax.ident (SourceInfo.fromRef src) (toString id).toSubstring id [(c, [])] def mkCIdentFromRef [Monad m] [MonadRef m] (c : Name) : m Syntax := do return mkCIdentFrom (← getRef) c def mkCIdent (c : Name) : Syntax := mkCIdentFrom Syntax.missing c @[export lean_mk_syntax_ident] def mkIdent (val : Name) : Syntax := Syntax.ident SourceInfo.none (toString val).toSubstring val [] @[inline] def mkNullNode (args : Array Syntax := #[]) : Syntax := Syntax.node nullKind args @[inline] def mkGroupNode (args : Array Syntax := #[]) : Syntax := Syntax.node groupKind args def mkSepArray (as : Array Syntax) (sep : Syntax) : Array Syntax := do let mut i := 0 let mut r := #[] for a in as do if i > 0 then r := r.push sep |>.push a else r := r.push a i := i + 1 return r def mkOptionalNode (arg : Option Syntax) : Syntax := match arg with | some arg => Syntax.node nullKind #[arg] | none => Syntax.node nullKind #[] def mkHole (ref : Syntax) : Syntax := Syntax.node `Lean.Parser.Term.hole #[mkAtomFrom ref "_"] namespace Syntax def mkSep (a : Array Syntax) (sep : Syntax) : Syntax := mkNullNode <| mkSepArray a sep def SepArray.ofElems {sep} (elems : Array Syntax) : SepArray sep := ⟨mkSepArray elems (mkAtom sep)⟩ def SepArray.ofElemsUsingRef [Monad m] [MonadRef m] {sep} (elems : Array Syntax) : m (SepArray sep) := do let ref ← getRef; return ⟨mkSepArray elems (mkAtomFrom ref sep)⟩ instance (sep) : Coe (Array Syntax) (SepArray sep) where coe := SepArray.ofElems /-- Create syntax representing a Lean term application, but avoid degenerate empty applications. -/ def mkApp (fn : Syntax) : (args : Array Syntax) → Syntax | #[] => fn | args => Syntax.node `Lean.Parser.Term.app #[fn, mkNullNode args] def mkCApp (fn : Name) (args : Array Syntax) : Syntax := mkApp (mkCIdent fn) args def mkLit (kind : SyntaxNodeKind) (val : String) (info := SourceInfo.none) : Syntax := let atom : Syntax := Syntax.atom info val Syntax.node kind #[atom] def mkStrLit (val : String) (info := SourceInfo.none) : Syntax := mkLit strLitKind (String.quote val) info def mkNumLit (val : String) (info := SourceInfo.none) : Syntax := mkLit numLitKind val info def mkScientificLit (val : String) (info := SourceInfo.none) : Syntax := mkLit scientificLitKind val info /- Recall that we don't have special Syntax constructors for storing numeric and string atoms. The idea is to have an extensible approach where embedded DSLs may have new kind of atoms and/or different ways of representing them. So, our atoms contain just the parsed string. The main Lean parser uses the kind `numLitKind` for storing natural numbers that can be encoded in binary, octal, decimal and hexadecimal format. `isNatLit` implements a "decoder" for Syntax objects representing these numerals. -/ private partial def decodeBinLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else let c := s.get i if c == '0' then decodeBinLitAux s (s.next i) (2*val) else if c == '1' then decodeBinLitAux s (s.next i) (2*val + 1) else none private partial def decodeOctalLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else let c := s.get i if '0' ≤ c && c ≤ '7' then decodeOctalLitAux s (s.next i) (8*val + c.toNat - '0'.toNat) else none private def decodeHexDigit (s : String) (i : String.Pos) : Option (Nat × String.Pos) := let c := s.get i let i := s.next i if '0' ≤ c && c ≤ '9' then some (c.toNat - '0'.toNat, i) else if 'a' ≤ c && c ≤ 'f' then some (10 + c.toNat - 'a'.toNat, i) else if 'A' ≤ c && c ≤ 'F' then some (10 + c.toNat - 'A'.toNat, i) else none private partial def decodeHexLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else match decodeHexDigit s i with | some (d, i) => decodeHexLitAux s i (16*val + d) | none => none private partial def decodeDecimalLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else let c := s.get i if '0' ≤ c && c ≤ '9' then decodeDecimalLitAux s (s.next i) (10*val + c.toNat - '0'.toNat) else none def decodeNatLitVal? (s : String) : Option Nat := let len := s.length if len == 0 then none else let c := s.get 0 if c == '0' then if len == 1 then some 0 else let c := s.get 1 if c == 'x' || c == 'X' then decodeHexLitAux s 2 0 else if c == 'b' || c == 'B' then decodeBinLitAux s 2 0 else if c == 'o' || c == 'O' then decodeOctalLitAux s 2 0 else if c.isDigit then decodeDecimalLitAux s 0 0 else none else if c.isDigit then decodeDecimalLitAux s 0 0 else none def isLit? (litKind : SyntaxNodeKind) (stx : Syntax) : Option String := match stx with | Syntax.node k args => if k == litKind && args.size == 1 then match args.get! 0 with | (Syntax.atom _ val) => some val | _ => none else none | _ => none private def isNatLitAux (litKind : SyntaxNodeKind) (stx : Syntax) : Option Nat := match isLit? litKind stx with | some val => decodeNatLitVal? val | _ => none def isNatLit? (s : Syntax) : Option Nat := isNatLitAux numLitKind s def isFieldIdx? (s : Syntax) : Option Nat := isNatLitAux fieldIdxKind s partial def decodeScientificLitVal? (s : String) : Option (Nat × Bool × Nat) := let len := s.length if len == 0 then none else let c := s.get 0 if c.isDigit then decode 0 0 else none where decodeAfterExp (i : String.Pos) (val : Nat) (e : Nat) (sign : Bool) (exp : Nat) : Option (Nat × Bool × Nat) := if s.atEnd i then if sign then some (val, sign, exp + e) else if exp >= e then some (val, sign, exp - e) else some (val, true, e - exp) else let c := s.get i if '0' ≤ c && c ≤ '9' then decodeAfterExp (s.next i) val e sign (10*exp + c.toNat - '0'.toNat) else none decodeExp (i : String.Pos) (val : Nat) (e : Nat) : Option (Nat × Bool × Nat) := let c := s.get i if c == '-' then decodeAfterExp (s.next i) val e true 0 else decodeAfterExp i val e false 0 decodeAfterDot (i : String.Pos) (val : Nat) (e : Nat) : Option (Nat × Bool × Nat) := if s.atEnd i then some (val, true, e) else let c := s.get i if '0' ≤ c && c ≤ '9' then decodeAfterDot (s.next i) (10*val + c.toNat - '0'.toNat) (e+1) else if c == 'e' || c == 'E' then decodeExp (s.next i) val e else none decode (i : String.Pos) (val : Nat) : Option (Nat × Bool × Nat) := if s.atEnd i then none else let c := s.get i if '0' ≤ c && c ≤ '9' then decode (s.next i) (10*val + c.toNat - '0'.toNat) else if c == '.' then decodeAfterDot (s.next i) val 0 else if c == 'e' || c == 'E' then decodeExp (s.next i) val 0 else none def isScientificLit? (stx : Syntax) : Option (Nat × Bool × Nat) := match isLit? scientificLitKind stx with | some val => decodeScientificLitVal? val | _ => none def isIdOrAtom? : Syntax → Option String | Syntax.atom _ val => some val | Syntax.ident _ rawVal _ _ => some rawVal.toString | _ => none def toNat (stx : Syntax) : Nat := match stx.isNatLit? with | some val => val | none => 0 def decodeQuotedChar (s : String) (i : String.Pos) : Option (Char × String.Pos) := OptionM.run do let c := s.get i let i := s.next i if c == '\\' then pure ('\\', i) else if c = '\"' then pure ('\"', i) else if c = '\'' then pure ('\'', i) else if c = 'r' then pure ('\r', i) else if c = 'n' then pure ('\n', i) else if c = 't' then pure ('\t', i) else if c = 'x' then let (d₁, i) ← decodeHexDigit s i let (d₂, i) ← decodeHexDigit s i pure (Char.ofNat (16*d₁ + d₂), i) else if c = 'u' then do let (d₁, i) ← decodeHexDigit s i let (d₂, i) ← decodeHexDigit s i let (d₃, i) ← decodeHexDigit s i let (d₄, i) ← decodeHexDigit s i pure (Char.ofNat (16*(16*(16*d₁ + d₂) + d₃) + d₄), i) else none partial def decodeStrLitAux (s : String) (i : String.Pos) (acc : String) : Option String := OptionM.run do let c := s.get i let i := s.next i if c == '\"' then pure acc else if s.atEnd i then none else if c == '\\' then do let (c, i) ← decodeQuotedChar s i decodeStrLitAux s i (acc.push c) else decodeStrLitAux s i (acc.push c) def decodeStrLit (s : String) : Option String := decodeStrLitAux s 1 "" def isStrLit? (stx : Syntax) : Option String := match isLit? strLitKind stx with | some val => decodeStrLit val | _ => none def decodeCharLit (s : String) : Option Char := OptionM.run do let c := s.get 1 if c == '\\' then do let (c, _) ← decodeQuotedChar s 2 pure c else pure c def isCharLit? (stx : Syntax) : Option Char := match isLit? charLitKind stx with | some val => decodeCharLit val | _ => none private partial def decodeNameLitAux (s : String) (i : Nat) (r : Name) : Option Name := OptionM.run do let continue? (i : Nat) (r : Name) : OptionM Name := if s.get i == '.' then decodeNameLitAux s (s.next i) r else if s.atEnd i then pure r else none let curr := s.get i if isIdBeginEscape curr then let startPart := s.next i let stopPart := s.nextUntil isIdEndEscape startPart if !isIdEndEscape (s.get stopPart) then none else continue? (s.next stopPart) (Name.mkStr r (s.extract startPart stopPart)) else if isIdFirst curr then let startPart := i let stopPart := s.nextWhile isIdRest startPart continue? stopPart (Name.mkStr r (s.extract startPart stopPart)) else none def decodeNameLit (s : String) : Option Name := if s.get 0 == '`' then decodeNameLitAux s 1 Name.anonymous else none def isNameLit? (stx : Syntax) : Option Name := match isLit? nameLitKind stx with | some val => decodeNameLit val | _ => none def hasArgs : Syntax → Bool | Syntax.node _ args => args.size > 0 | _ => false def isAtom : Syntax → Bool | atom _ _ => true | _ => false def isToken (token : String) : Syntax → Bool | atom _ val => val.trim == token.trim | _ => false def isNone (stx : Syntax) : Bool := match stx with | Syntax.node k args => k == nullKind && args.size == 0 -- when elaborating partial syntax trees, it's reasonable to interpret missing parts as `none` | Syntax.missing => true | _ => false def getOptional? (stx : Syntax) : Option Syntax := match stx with | Syntax.node k args => if k == nullKind && args.size == 1 then some (args.get! 0) else none | _ => none def getOptionalIdent? (stx : Syntax) : Option Name := match stx.getOptional? with | some stx => some stx.getId | none => none partial def findAux (p : Syntax → Bool) : Syntax → Option Syntax | stx@(Syntax.node _ args) => if p stx then some stx else args.findSome? (findAux p) | stx => if p stx then some stx else none def find? (stx : Syntax) (p : Syntax → Bool) : Option Syntax := findAux p stx end Syntax /-- Reflect a runtime datum back to surface syntax (best-effort). -/ class Quote (α : Type) where quote : α → Syntax export Quote (quote) instance : Quote Syntax := ⟨id⟩ instance : Quote Bool := ⟨fun | true => mkCIdent `Bool.true | false => mkCIdent `Bool.false⟩ instance : Quote String := ⟨Syntax.mkStrLit⟩ instance : Quote Nat := ⟨fun n => Syntax.mkNumLit <| toString n⟩ instance : Quote Substring := ⟨fun s => Syntax.mkCApp `String.toSubstring #[quote s.toString]⟩ private def quoteName : Name → Syntax | Name.anonymous => mkCIdent ``Name.anonymous | Name.str n s _ => Syntax.mkCApp ``Name.mkStr #[quoteName n, quote s] | Name.num n i _ => Syntax.mkCApp ``Name.mkNum #[quoteName n, quote i] instance : Quote Name := ⟨quoteName⟩ instance {α β : Type} [Quote α] [Quote β] : Quote (α × β) where quote | ⟨a, b⟩ => Syntax.mkCApp ``Prod.mk #[quote a, quote b] private def quoteList {α : Type} [Quote α] : List α → Syntax | [] => mkCIdent ``List.nil | (x::xs) => Syntax.mkCApp ``List.cons #[quote x, quoteList xs] instance {α : Type} [Quote α] : Quote (List α) where quote := quoteList instance {α : Type} [Quote α] : Quote (Array α) where quote xs := Syntax.mkCApp ``List.toArray #[quote xs.toList] private def quoteOption {α : Type} [Quote α] : Option α → Syntax | none => mkIdent ``none | (some x) => Syntax.mkCApp ``some #[quote x] instance Option.hasQuote {α : Type} [Quote α] : Quote (Option α) where quote := quoteOption /- Evaluator for `prec` DSL -/ def evalPrec (stx : Syntax) : MacroM Nat := Macro.withIncRecDepth stx do let stx ← expandMacros stx match stx with | `(prec| $num:numLit) => return num.isNatLit?.getD 0 | _ => Macro.throwErrorAt stx "unexpected precedence" macro_rules | `(prec| $a + $b) => do `(prec| $(quote <| (← evalPrec a) + (← evalPrec b)):numLit) macro_rules | `(prec| $a - $b) => do `(prec| $(quote <| (← evalPrec a) - (← evalPrec b)):numLit) macro "eval_prec " p:prec:max : term => return quote (← evalPrec p) def evalOptPrec : Option Syntax → MacroM Nat | some prec => evalPrec prec | none => return 0 /- Evaluator for `prio` DSL -/ def evalPrio (stx : Syntax) : MacroM Nat := Macro.withIncRecDepth stx do let stx ← expandMacros stx match stx with | `(prio| $num:numLit) => return num.isNatLit?.getD 0 | _ => Macro.throwErrorAt stx "unexpected priority" macro_rules | `(prio| $a + $b) => do `(prio| $(quote <| (← evalPrio a) + (← evalPrio b)):numLit) macro_rules | `(prio| $a - $b) => do `(prio| $(quote <| (← evalPrio a) - (← evalPrio b)):numLit) macro "eval_prio " p:prio:max : term => return quote (← evalPrio p) def evalOptPrio : Option Syntax → MacroM Nat | some prio => evalPrio prio | none => return eval_prio default end Lean namespace Array abbrev getSepElems := @getEvenElems open Lean private partial def filterSepElemsMAux {m : Type → Type} [Monad m] (a : Array Syntax) (p : Syntax → m Bool) (i : Nat) (acc : Array Syntax) : m (Array Syntax) := do if h : i < a.size then let stx := a.get ⟨i, h⟩ if (← p stx) then if acc.isEmpty then filterSepElemsMAux a p (i+2) (acc.push stx) else if hz : i ≠ 0 then have i.pred < i from Nat.predLt hz let sepStx := a.get ⟨i.pred, Nat.ltTrans this h⟩ filterSepElemsMAux a p (i+2) ((acc.push sepStx).push stx) else filterSepElemsMAux a p (i+2) (acc.push stx) else filterSepElemsMAux a p (i+2) acc else pure acc def filterSepElemsM {m : Type → Type} [Monad m] (a : Array Syntax) (p : Syntax → m Bool) : m (Array Syntax) := filterSepElemsMAux a p 0 #[] def filterSepElems (a : Array Syntax) (p : Syntax → Bool) : Array Syntax := Id.run <| a.filterSepElemsM p private partial def mapSepElemsMAux {m : Type → Type} [Monad m] (a : Array Syntax) (f : Syntax → m Syntax) (i : Nat) (acc : Array Syntax) : m (Array Syntax) := do if h : i < a.size then let stx := a.get ⟨i, h⟩ if i % 2 == 0 then do let stx ← f stx mapSepElemsMAux a f (i+1) (acc.push stx) else mapSepElemsMAux a f (i+1) (acc.push stx) else pure acc def mapSepElemsM {m : Type → Type} [Monad m] (a : Array Syntax) (f : Syntax → m Syntax) : m (Array Syntax) := mapSepElemsMAux a f 0 #[] def mapSepElems (a : Array Syntax) (f : Syntax → Syntax) : Array Syntax := Id.run <| a.mapSepElemsM f end Array namespace Lean.Syntax.SepArray def getElems {sep} (sa : SepArray sep) : Array Syntax := sa.elemsAndSeps.getSepElems /- We use `CoeTail` here instead of `Coe` to avoid a "loop" when computing `CoeTC`. The "loop" is interrupted using the maximum instance size threshold, but it is a performance bottleneck. The loop occurs because the predicate `isNewAnswer` is too imprecise. -/ instance (sep) : CoeTail (SepArray sep) (Array Syntax) where coe := getElems end Lean.Syntax.SepArray /-- Gadget for automatic parameter support. This is similar to the `optParam` gadget, but it uses the given tactic. Like `optParam`, this gadget only affects elaboration. For example, the tactic will *not* be invoked during type class resolution. -/ abbrev autoParam.{u} (α : Sort u) (tactic : Lean.Syntax) : Sort u := α /- Helper functions for manipulating interpolated strings -/ namespace Lean.Syntax private def decodeInterpStrQuotedChar (s : String) (i : String.Pos) : Option (Char × String.Pos) := OptionM.run do match decodeQuotedChar s i with | some r => some r | none => let c := s.get i let i := s.next i if c == '{' then pure ('{', i) else none private partial def decodeInterpStrLit (s : String) : Option String := let rec loop (i : String.Pos) (acc : String) : OptionM String := let c := s.get i let i := s.next i if c == '\"' || c == '{' then pure acc else if s.atEnd i then none else if c == '\\' then do let (c, i) ← decodeInterpStrQuotedChar s i loop i (acc.push c) else loop i (acc.push c) loop 1 "" partial def isInterpolatedStrLit? (stx : Syntax) : Option String := match isLit? interpolatedStrLitKind stx with | none => none | some val => decodeInterpStrLit val def expandInterpolatedStrChunks (chunks : Array Syntax) (mkAppend : Syntax → Syntax → MacroM Syntax) (mkElem : Syntax → MacroM Syntax) : MacroM Syntax := do let mut i := 0 let mut result := Syntax.missing for elem in chunks do let elem ← match elem.isInterpolatedStrLit? with | none => mkElem elem | some str => mkElem (Syntax.mkStrLit str) if i == 0 then result := elem else result ← mkAppend result elem i := i+1 return result def expandInterpolatedStr (interpStr : Syntax) (type : Syntax) (toTypeFn : Syntax) : MacroM Syntax := do let ref := interpStr let r ← expandInterpolatedStrChunks interpStr.getArgs (fun a b => `($a ++ $b)) (fun a => `($toTypeFn $a)) `(($r : $type)) def getSepArgs (stx : Syntax) : Array Syntax := stx.getArgs.getSepElems end Syntax namespace Meta.Simp def defaultMaxSteps := 100000 structure Config where maxSteps : Nat := defaultMaxSteps contextual : Bool := false memoize : Bool := true singlePass : Bool := false zeta : Bool := true beta : Bool := true eta : Bool := true iota : Bool := true proj : Bool := true ctorEq : Bool := true decide : Bool := true deriving Inhabited, BEq, Repr -- Configuration object for `simp_all` structure ConfigCtx extends Config where contextual := true end Meta.Simp end Lean
8148c8cd0bd4853ca047ce4765e391787add43df
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/1369.lean
a9321855442852aca96ef5b14df64e98eb58df49
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
715
lean
open nat open tactic meta def match_le (e : expr) : tactic (expr × expr) := match expr.is_le e with | (some r) := return r | none := tactic.fail "expression is not a leq" end meta def nat_lit_le : tactic unit := do (base_e, bound_e) ← tactic.target >>= match_le, base ← tactic.eval_expr ℕ base_e, skip example : 17 ≤ 555555 := begin nat_lit_le, admit end example : { k : ℕ // k ≤ 555555 } := begin refine subtype.tag _ _, exact 17, target >>= trace, trace_state, nat_lit_le, admit end set_option pp.instantiate_mvars false example : { k : ℕ // k ≤ 555555 } := begin refine subtype.tag _ _, exact 17, target >>= trace, trace_state, nat_lit_le, admit end
5d1cb76f9b5b66f13b11d33fc85bd540e405b862
dc253be9829b840f15d96d986e0c13520b085033
/colimit/pushout.hlean
2c390ce88132de6d896f53873eb621378f0c9f68
[ "Apache-2.0" ]
permissive
cmu-phil/Spectral
4ce68e5c1ef2a812ffda5260e9f09f41b85ae0ea
3b078f5f1de251637decf04bd3fc8aa01930a6b3
refs/heads/master
1,685,119,195,535
1,684,169,772,000
1,684,169,772,000
46,450,197
42
13
null
1,505,516,767,000
1,447,883,921,000
Lean
UTF-8
Lean
false
false
9,666
hlean
/- Suppose we have three sequences A = (Aₙ, fₙ)ₙ, B = (Bₙ, gₙ)ₙ, C = (Cₙ, hₙ)ₙ with natural transformations like this: B ← A → C. We can take pushouts pointwise and then take the colimit, or we can take the colimit of each and then pushout. By the 3x3 lemma these are equivalent. Authors: Floris van Doorn -/ import .seq_colim ..homotopy.pushout ..homotopy.three_by_three open eq nat seq_colim is_trunc equiv is_equiv trunc sigma sum pi function algebra sigma.ops section variables {A B : ℕ → Type} {f : seq_diagram A} {g : seq_diagram B} (i : Π⦃n⦄, A n → B n) (p : Π⦃n⦄ (a : A n), i (f a) = g (i a)) (a a' : Σn, A n) definition total_seq_rel [constructor] (f : seq_diagram A) : (Σ(a a' : Σn, A n), seq_rel f a a') ≃ Σn, A n := begin fapply equiv.MK, { intro x, exact x.2.1 }, { intro x, induction x with n a, exact ⟨⟨n+1, f a⟩, ⟨n, a⟩, seq_rel.Rmk f a⟩ }, { intro x, induction x with n a, reflexivity }, { intro x, induction x with a x, induction x with a' r, induction r with n a, reflexivity } end definition pr1_total_seq_rel_inv (x : Σn, A n) : ((total_seq_rel f)⁻¹ᵉ x).1 = sigma_functor succ f x := begin induction x with n a, reflexivity end definition pr2_total_seq_rel_inv (x : Σn, A n) : ((total_seq_rel f)⁻¹ᵉ x).2.1 = x := to_right_inv (total_seq_rel f) x include p definition seq_rel_functor [unfold 9] : seq_rel f a a' → seq_rel g (total i a) (total i a') := begin intro r, induction r with n a, exact transport (λx, seq_rel g ⟨_, x⟩ _) (p a)⁻¹ (seq_rel.Rmk g (i a)) end open pushout definition total_seq_rel_natural [unfold 7] : hsquare (sigma_functor2 (total i) (seq_rel_functor i p)) (total i) (total_seq_rel f) (total_seq_rel g) := homotopy.rfl end section open pushout sigma.ops quotient parameters {A B C : ℕ → Type} {f : seq_diagram A} {g : seq_diagram B} {h : seq_diagram C} (i : Π⦃n⦄, A n → B n) (j : Π⦃n⦄, A n → C n) (p : Π⦃n⦄ (a : A n), i (f a) = g (i a)) (q : Π⦃n⦄ (a : A n), j (f a) = h (j a)) definition seq_diagram_pushout : seq_diagram (λn, pushout (@i n) (@j n)) := λn, pushout.functor (@f n) (@g n) (@h n) (@p n)⁻¹ʰᵗʸ (@q n)⁻¹ʰᵗʸ local abbreviation sA := Σn, A n local abbreviation sB := Σn, B n local abbreviation sC := Σn, C n local abbreviation si : sA → sB := total i local abbreviation sj : sA → sC := total j local abbreviation rA := Σ(x y : sA), seq_rel f x y local abbreviation rB := Σ(x y : sB), seq_rel g x y local abbreviation rC := Σ(x y : sC), seq_rel h x y set_option pp.abbreviations false local abbreviation ri : rA → rB := sigma_functor2 (total i) (seq_rel_functor i p) local abbreviation rj : rA → rC := sigma_functor2 (total j) (seq_rel_functor j q) definition pushout_seq_colim_span [constructor] : three_by_three_span := @three_by_three_span.mk sB (rB ⊎ rB) rB sA (rA ⊎ rA) rA sC (rC ⊎ rC) rC (sum.rec pr1 (λx, x.2.1)) (sum.rec id id) (sum.rec pr1 (λx, x.2.1)) (sum.rec id id) (sum.rec pr1 (λx, x.2.1)) (sum.rec id id) (total i) (total j) (ri +→ ri) (rj +→ rj) ri rj begin intro x, induction x: reflexivity end begin intro x, induction x: reflexivity end begin intro x, induction x: reflexivity end begin intro x, induction x: reflexivity end definition ua_equiv_ap {A : Type} (P : A → Type) {a b : A} (p : a = b) : ua (equiv_ap P p) = ap P p := begin induction p, apply ua_refl end definition pushout_elim_type_eta {TL BL TR : Type} {f : TL → BL} {g : TL → TR} (P : pushout f g → Type) (x : pushout f g) : P x ≃ pushout.elim_type (P ∘ inl) (P ∘ inr) (λa, equiv_ap P (glue a)) x := begin induction x, { reflexivity }, { reflexivity }, { apply equiv_pathover_inv, apply arrow_pathover_left, intro y, apply pathover_of_tr_eq, symmetry, exact ap10 !elim_type_glue y } end definition pushout_flattening' {TL BL TR : Type} {f : TL → BL} {g : TL → TR} (P : pushout f g → Type) : sigma P ≃ @pushout (sigma (P ∘ inl ∘ f)) (sigma (P ∘ inl)) (sigma (P ∘ inr)) (sigma_functor f (λa, id)) (sigma_functor g (λa, transport P (glue a))) := sigma_equiv_sigma_right (pushout_elim_type_eta P) ⬝e pushout.flattening _ _ (P ∘ inl) (P ∘ inr) (λa, equiv_ap P (glue a)) definition equiv_ap011 {A B : Type} (P : A → B → Type) {a a' : A} {b b' : B} (p : a = a') (q : b = b') : P a b ≃ P a' b' := equiv_ap (P a) q ⬝e equiv_ap (λa, P a b') p definition tr_tr_eq_tr_tr [unfold 8 9] {A B : Type} (P : A → B → Type) {a a' : A} {b b' : B} (p : a = a') (q : b = b') (x : P a b) : transport (P a') q (transport (λa, P a b) p x) = transport (λa, P a b') p (transport (P a) q x) := by induction p; induction q; reflexivity definition pushout_total_seq_rel : pushout (sigma_functor2 (total i) (seq_rel_functor i p)) (sigma_functor2 (total j) (seq_rel_functor j q)) ≃ Σ(x : Σ ⦃n : ℕ⦄, pushout (@i n) (@j n)), sigma (seq_rel seq_diagram_pushout x) := pushout.equiv _ _ _ _ (total_seq_rel f) (total_seq_rel g) (total_seq_rel h) homotopy.rfl homotopy.rfl ⬝e pushout_sigma_equiv_sigma_pushout i j ⬝e (total_seq_rel seq_diagram_pushout)⁻¹ᵉ definition pr1_pushout_total_seq_rel : hsquare pushout_total_seq_rel (pushout_sigma_equiv_sigma_pushout i j) (pushout.functor pr1 pr1 pr1 homotopy.rfl homotopy.rfl) pr1 := begin intro x, refine !pr1_total_seq_rel_inv ⬝ _, esimp, refine !pushout_sigma_equiv_sigma_pushout_natural⁻¹ ⬝ _, apply ap sigma_pushout_of_pushout_sigma, refine !pushout_functor_compose⁻¹ ⬝ _, fapply pushout_functor_homotopy, { intro v, induction v with a v, induction v with a' r, induction r, reflexivity }, { intro v, induction v with a v, induction v with a' r, induction r, reflexivity }, { intro v, induction v with a v, induction v with a' r, induction r, reflexivity }, { intro v, induction v with a v, induction v with a' r, induction r, esimp, generalize p a, generalize i (f a), intro x r, cases r, reflexivity }, { intro v, induction v with a v, induction v with a' r, induction r, esimp, generalize q a, generalize j (f a), intro x r, cases r, reflexivity }, end definition pr2_pushout_total_seq_rel : hsquare pushout_total_seq_rel (pushout_sigma_equiv_sigma_pushout i j) (pushout.functor (λx, x.2.1) (λx, x.2.1) (λx, x.2.1) homotopy.rfl homotopy.rfl) (λx, x.2.1) := begin intro x, apply pr2_total_seq_rel_inv, end /- this result depends on the 3x3 lemma, which is currently not formalized in Lean -/ definition pushout_seq_colim_equiv [constructor] : pushout (seq_colim_functor i p) (seq_colim_functor j q) ≃ seq_colim seq_diagram_pushout := have e1 : pushout (seq_colim_functor i p) (seq_colim_functor j q) ≃ pushout2hv pushout_seq_colim_span, from pushout.equiv _ _ _ _ !quotient_equiv_pushout !quotient_equiv_pushout !quotient_equiv_pushout begin refine _ ⬝hty quotient_equiv_pushout_natural (total i) (seq_rel_functor i p), intro x, apply ap pushout_quotient_of_quotient, induction x, { induction a with n a, reflexivity }, { induction H, apply eq_pathover, apply hdeg_square, refine !elim_glue ⬝ _ ⬝ !elim_eq_of_rel⁻¹, unfold [seq_colim.glue, seq_rel_functor], symmetry, refine fn_tr_eq_tr_fn (p a)⁻¹ _ _ ⬝ eq_transport_Fl (p a)⁻¹ _ ⬝ _, apply whisker_right, exact !ap_inv⁻² ⬝ !inv_inv } end begin refine _ ⬝hty quotient_equiv_pushout_natural (total j) (seq_rel_functor j q), intro x, apply ap pushout_quotient_of_quotient, induction x, { induction a with n a, reflexivity }, { induction H, apply eq_pathover, apply hdeg_square, refine !elim_glue ⬝ _ ⬝ !elim_eq_of_rel⁻¹, unfold [seq_colim.glue, seq_rel_functor], symmetry, refine fn_tr_eq_tr_fn (q a)⁻¹ _ _ ⬝ eq_transport_Fl (q a)⁻¹ _ ⬝ _, apply whisker_right, exact !ap_inv⁻² ⬝ !inv_inv } end, have e2 : pushout2vh pushout_seq_colim_span ≃ pushout_quotient (seq_rel seq_diagram_pushout), from pushout.equiv _ _ _ _ (!pushout_sum_equiv_sum_pushout ⬝e sum_equiv_sum pushout_total_seq_rel pushout_total_seq_rel) (pushout_sigma_equiv_sigma_pushout i j) pushout_total_seq_rel begin intro x, symmetry, refine sum_rec_hsquare pr1_pushout_total_seq_rel pr2_pushout_total_seq_rel (!pushout_sum_equiv_sum_pushout x) ⬝ ap (pushout_sigma_equiv_sigma_pushout i j) _, refine sum_rec_pushout_sum_equiv_sum_pushout _ _ _ _ x ⬝ _, apply pushout_functor_homotopy_constant: intro x; induction x: reflexivity end begin intro x, symmetry, refine !sum_rec_sum_functor ⬝ _, refine sum_rec_same_compose ((total_seq_rel seq_diagram_pushout)⁻¹ᵉ ∘ pushout_sigma_equiv_sigma_pushout i j) _ _ ⬝ _, apply ap (to_fun (total_seq_rel seq_diagram_pushout)⁻¹ᵉ ∘ to_fun (pushout_sigma_equiv_sigma_pushout i j)), refine !sum_rec_pushout_sum_equiv_sum_pushout ⬝ _, refine _ ⬝ !pushout_functor_compose, fapply pushout_functor_homotopy, { intro x, induction x: reflexivity }, { intro x, induction x: reflexivity }, { intro x, induction x: reflexivity }, { intro x, induction x: exact (!idp_con ⬝ !ap_id ⬝ !inv_inv)⁻¹ }, { intro x, induction x: exact (!idp_con ⬝ !ap_id ⬝ !inv_inv)⁻¹ } end, e1 ⬝e three_by_three pushout_seq_colim_span ⬝e e2 ⬝e (quotient_equiv_pushout _)⁻¹ᵉ definition seq_colim_pushout_equiv [constructor] : seq_colim seq_diagram_pushout ≃ pushout (seq_colim_functor i p) (seq_colim_functor j q) := pushout_seq_colim_equiv⁻¹ᵉ end
05b59e13b1397f14f44554a803b4133f4c54c0b5
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/tactic6.lean
8a12e820f0f2fb289b8fcb4134a59cebf5e910a0
[ "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
137
lean
import logic open tactic (renaming id->id_tac) theorem tst {A B : Prop} (H1 : A) (H2 : B) : id A := by unfold id; assumption check tst
f69b68d69aae06e390942fa60e194b1f49129f09
64874bd1010548c7f5a6e3e8902efa63baaff785
/tests/lean/run/nested_begin.lean
0e352e569f0fdd9e6954007e9ea119b87019d047
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,227
lean
import logic data.nat.basic open nat inductive vector (A : Type) : nat → Type := vnil : vector A zero, vcons : Π {n : nat}, A → vector A n → vector A (succ n) namespace vector definition no_confusion2 {A : Type} {n : nat} {P : Type} {v₁ v₂ : vector A n} : v₁ = v₂ → no_confusion_type P v₁ v₂ := assume H₁₂ : v₁ = v₂, begin show no_confusion_type P v₁ v₂, from have aux : v₁ = v₁ → no_confusion_type P v₁ v₁, from take H₁₁, begin apply (cases_on v₁), exact (assume h : P, h), intros (n, a, v, h), apply (h rfl), repeat (apply rfl), repeat (apply heq.refl) end, eq.rec_on H₁₂ aux H₁₂ end theorem vcons.inj₁ {A : Type} {n : nat} (a₁ a₂ : A) (v₁ v₂ : vector A n) : vcons a₁ v₁ = vcons a₂ v₂ → a₁ = a₂ := begin intro h, apply (no_confusion h), intros, assumption end theorem vcons.inj₂ {A : Type} {n : nat} (a₁ a₂ : A) (v₁ v₂ : vector A n) : vcons a₁ v₁ = vcons a₂ v₂ → v₁ == v₂ := begin intro h, apply (no_confusion h), intros, eassumption end end vector
4da2f8005d17375a9f641887047585cf3efdaa8d
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/inner_product_space/basic.lean
173e0f028210449d9d41effbf713e5864281837f
[ "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
96,952
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Sébastien Gouëzel, Frédéric Dupuis -/ import algebra.direct_sum.module import analysis.complex.basic import analysis.convex.uniform import analysis.normed_space.completion import analysis.normed_space.bounded_linear_maps import linear_algebra.bilinear_form /-! # Inner product space > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines inner product spaces and proves the basic properties. We do not formally define Hilbert spaces, but they can be obtained using the set of assumptions `[normed_add_comm_group E] [inner_product_space 𝕜 E] [complete_space E]`. An inner product space is a vector space endowed with an inner product. It generalizes the notion of dot product in `ℝ^n` and provides the means of defining the length of a vector and the angle between two vectors. In particular vectors `x` and `y` are orthogonal if their inner product equals zero. We define both the real and complex cases at the same time using the `is_R_or_C` typeclass. This file proves general results on inner product spaces. For the specific construction of an inner product structure on `n → 𝕜` for `𝕜 = ℝ` or `ℂ`, see `euclidean_space` in `analysis.inner_product_space.pi_L2`. ## Main results - We define the class `inner_product_space 𝕜 E` extending `normed_space 𝕜 E` with a number of basic properties, most notably the Cauchy-Schwarz inequality. Here `𝕜` is understood to be either `ℝ` or `ℂ`, through the `is_R_or_C` typeclass. - We show that the inner product is continuous, `continuous_inner`, and bundle it as the the continuous sesquilinear map `innerSL` (see also `innerₛₗ` for the non-continuous version). - We define `orthonormal`, a predicate on a function `v : ι → E`, and prove the existence of a maximal orthonormal set, `exists_maximal_orthonormal`. Bessel's inequality, `orthonormal.tsum_inner_products_le`, states that given an orthonormal set `v` and a vector `x`, the sum of the norm-squares of the inner products `⟪v i, x⟫` is no more than the norm-square of `x`. For the existence of orthonormal bases, Hilbert bases, etc., see the file `analysis.inner_product_space.projection`. ## Notation We globally denote the real and complex inner products by `⟪·, ·⟫_ℝ` and `⟪·, ·⟫_ℂ` respectively. We also provide two notation namespaces: `real_inner_product_space`, `complex_inner_product_space`, which respectively introduce the plain notation `⟪·, ·⟫` for the real and complex inner product. ## Implementation notes We choose the convention that inner products are conjugate linear in the first argument and linear in the second. ## Tags inner product space, Hilbert space, norm ## References * [Clément & Martin, *The Lax-Milgram Theorem. A detailed proof to be formalized in Coq*] * [Clément & Martin, *A Coq formal proof of the Lax–Milgram theorem*] The Coq code is available at the following address: <http://www.lri.fr/~sboldo/elfic/index.html> -/ noncomputable theory open is_R_or_C real filter open_locale big_operators topology complex_conjugate variables {𝕜 E F : Type*} [is_R_or_C 𝕜] /-- Syntactic typeclass for types endowed with an inner product -/ class has_inner (𝕜 E : Type*) := (inner : E → E → 𝕜) export has_inner (inner) notation `⟪`x`, `y`⟫_ℝ` := @inner ℝ _ _ x y notation `⟪`x`, `y`⟫_ℂ` := @inner ℂ _ _ x y section notations localized "notation (name := inner.real) `⟪`x`, `y`⟫` := @inner ℝ _ _ x y" in real_inner_product_space localized "notation (name := inner.complex) `⟪`x`, `y`⟫` := @inner ℂ _ _ x y" in complex_inner_product_space end notations /-- An inner product space is a vector space with an additional operation called inner product. The norm could be derived from the inner product, instead we require the existence of a norm and the fact that `‖x‖^2 = re ⟪x, x⟫` to be able to put instances on `𝕂` or product spaces. To construct a norm from an inner product, see `inner_product_space.of_core`. -/ class inner_product_space (𝕜 : Type*) (E : Type*) [is_R_or_C 𝕜] [normed_add_comm_group E] extends normed_space 𝕜 E, has_inner 𝕜 E := (norm_sq_eq_inner : ∀ (x : E), ‖x‖^2 = re (inner x x)) (conj_symm : ∀ x y, conj (inner y x) = inner x y) (add_left : ∀ x y z, inner (x + y) z = inner x z + inner y z) (smul_left : ∀ x y r, inner (r • x) y = (conj r) * inner x y) /-! ### Constructing a normed space structure from an inner product In the definition of an inner product space, we require the existence of a norm, which is equal (but maybe not defeq) to the square root of the scalar product. This makes it possible to put an inner product space structure on spaces with a preexisting norm (for instance `ℝ`), with good properties. However, sometimes, one would like to define the norm starting only from a well-behaved scalar product. This is what we implement in this paragraph, starting from a structure `inner_product_space.core` stating that we have a nice scalar product. Our goal here is not to develop a whole theory with all the supporting API, as this will be done below for `inner_product_space`. Instead, we implement the bare minimum to go as directly as possible to the construction of the norm and the proof of the triangular inequality. Warning: Do not use this `core` structure if the space you are interested in already has a norm instance defined on it, otherwise this will create a second non-defeq norm instance! -/ /-- A structure requiring that a scalar product is positive definite and symmetric, from which one can construct an `inner_product_space` instance in `inner_product_space.of_core`. -/ @[nolint has_nonempty_instance] structure inner_product_space.core (𝕜 : Type*) (F : Type*) [is_R_or_C 𝕜] [add_comm_group F] [module 𝕜 F] extends has_inner 𝕜 F := (conj_symm : ∀ x y, conj (inner y x) = inner x y) (nonneg_re : ∀ x, 0 ≤ re (inner x x)) (definite : ∀ x, inner x x = 0 → x = 0) (add_left : ∀ x y z, inner (x + y) z = inner x z + inner y z) (smul_left : ∀ x y r, inner (r • x) y = (conj r) * inner x y) /- We set `inner_product_space.core` to be a class as we will use it as such in the construction of the normed space structure that it produces. However, all the instances we will use will be local to this proof. -/ attribute [class] inner_product_space.core /-- Define `inner_product_space.core` from `inner_product_space`. Defined to reuse lemmas about `inner_product_space.core` for `inner_product_space`s. Note that the `has_norm` instance provided by `inner_product_space.core.has_norm` is propositionally but not definitionally equal to the original norm. -/ def inner_product_space.to_core [normed_add_comm_group E] [c : inner_product_space 𝕜 E] : inner_product_space.core 𝕜 E := { nonneg_re := λ x, by { rw [← inner_product_space.norm_sq_eq_inner], apply sq_nonneg }, definite := λ x hx, norm_eq_zero.1 $ pow_eq_zero $ by rw [inner_product_space.norm_sq_eq_inner x, hx, map_zero], .. c } namespace inner_product_space.core variables [add_comm_group F] [module 𝕜 F] [c : inner_product_space.core 𝕜 F] include c local notation `⟪`x`, `y`⟫` := @inner 𝕜 F _ x y local notation `norm_sqK` := @is_R_or_C.norm_sq 𝕜 _ local notation `reK` := @is_R_or_C.re 𝕜 _ local notation `ext_iff` := @is_R_or_C.ext_iff 𝕜 _ local postfix `†`:90 := star_ring_end _ /-- Inner product defined by the `inner_product_space.core` structure. We can't reuse `inner_product_space.core.to_has_inner` because it takes `inner_product_space.core` as an explicit argument. -/ def to_has_inner' : has_inner 𝕜 F := c.to_has_inner local attribute [instance] to_has_inner' /-- The norm squared function for `inner_product_space.core` structure. -/ def norm_sq (x : F) := reK ⟪x, x⟫ local notation `norm_sqF` := @norm_sq 𝕜 F _ _ _ _ lemma inner_conj_symm (x y : F) : ⟪y, x⟫† = ⟪x, y⟫ := c.conj_symm x y lemma inner_self_nonneg {x : F} : 0 ≤ re ⟪x, x⟫ := c.nonneg_re _ lemma inner_self_im (x : F) : im ⟪x, x⟫ = 0 := by rw [← @of_real_inj 𝕜, im_eq_conj_sub]; simp [inner_conj_symm] lemma inner_add_left (x y z : F) : ⟪x + y, z⟫ = ⟪x, z⟫ + ⟪y, z⟫ := c.add_left _ _ _ lemma inner_add_right (x y z : F) : ⟪x, y + z⟫ = ⟪x, y⟫ + ⟪x, z⟫ := by rw [←inner_conj_symm, inner_add_left, ring_hom.map_add]; simp only [inner_conj_symm] lemma coe_norm_sq_eq_inner_self (x : F) : (norm_sqF x : 𝕜) = ⟪x, x⟫ := begin rw ext_iff, exact ⟨by simp only [of_real_re]; refl, by simp only [inner_self_im, of_real_im]⟩ end lemma inner_re_symm (x y : F) : re ⟪x, y⟫ = re ⟪y, x⟫ := by rw [←inner_conj_symm, conj_re] lemma inner_im_symm (x y : F) : im ⟪x, y⟫ = -im ⟪y, x⟫ := by rw [←inner_conj_symm, conj_im] lemma inner_smul_left (x y : F) {r : 𝕜} : ⟪r • x, y⟫ = r† * ⟪x, y⟫ := c.smul_left _ _ _ lemma inner_smul_right (x y : F) {r : 𝕜} : ⟪x, r • y⟫ = r * ⟪x, y⟫ := by rw [←inner_conj_symm, inner_smul_left]; simp only [conj_conj, inner_conj_symm, ring_hom.map_mul] lemma inner_zero_left (x : F) : ⟪0, x⟫ = 0 := by rw [←zero_smul 𝕜 (0 : F), inner_smul_left]; simp only [zero_mul, ring_hom.map_zero] lemma inner_zero_right (x : F) : ⟪x, 0⟫ = 0 := by rw [←inner_conj_symm, inner_zero_left]; simp only [ring_hom.map_zero] lemma inner_self_eq_zero {x : F} : ⟪x, x⟫ = 0 ↔ x = 0 := ⟨c.definite _, by { rintro rfl, exact inner_zero_left _ }⟩ lemma norm_sq_eq_zero {x : F} : norm_sqF x = 0 ↔ x = 0 := iff.trans (by simp only [norm_sq, ext_iff, map_zero, inner_self_im, eq_self_iff_true, and_true]) (@inner_self_eq_zero 𝕜 _ _ _ _ _ x) lemma inner_self_ne_zero {x : F} : ⟪x, x⟫ ≠ 0 ↔ x ≠ 0 := inner_self_eq_zero.not lemma inner_self_re_to_K (x : F) : (re ⟪x, x⟫ : 𝕜) = ⟪x, x⟫ := by norm_num [ext_iff, inner_self_im] lemma norm_inner_symm (x y : F) : ‖⟪x, y⟫‖ = ‖⟪y, x⟫‖ := by rw [←inner_conj_symm, norm_conj] lemma inner_neg_left (x y : F) : ⟪-x, y⟫ = -⟪x, y⟫ := by { rw [← neg_one_smul 𝕜 x, inner_smul_left], simp } lemma inner_neg_right (x y : F) : ⟪x, -y⟫ = -⟪x, y⟫ := by rw [←inner_conj_symm, inner_neg_left]; simp only [ring_hom.map_neg, inner_conj_symm] lemma inner_sub_left (x y z : F) : ⟪x - y, z⟫ = ⟪x, z⟫ - ⟪y, z⟫ := by { simp [sub_eq_add_neg, inner_add_left, inner_neg_left] } lemma inner_sub_right (x y z : F) : ⟪x, y - z⟫ = ⟪x, y⟫ - ⟪x, z⟫ := by { simp [sub_eq_add_neg, inner_add_right, inner_neg_right] } lemma inner_mul_symm_re_eq_norm (x y : F) : re (⟪x, y⟫ * ⟪y, x⟫) = ‖⟪x, y⟫ * ⟪y, x⟫‖ := by { rw [←inner_conj_symm, mul_comm], exact re_eq_norm_of_mul_conj (inner y x), } /-- Expand `inner (x + y) (x + y)` -/ lemma inner_add_add_self (x y : F) : ⟪x + y, x + y⟫ = ⟪x, x⟫ + ⟪x, y⟫ + ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_add_left, inner_add_right]; ring /- Expand `inner (x - y) (x - y)` -/ lemma inner_sub_sub_self (x y : F) : ⟪x - y, x - y⟫ = ⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_sub_left, inner_sub_right]; ring /-- An auxiliary equality useful to prove the **Cauchy–Schwarz inequality**: the square of the norm of `⟪x, y⟫ • x - ⟪x, x⟫ • y` is equal to `‖x‖ ^ 2 * (‖x‖ ^ 2 * ‖y‖ ^ 2 - ‖⟪x, y⟫‖ ^ 2)`. We use `inner_product_space.of_core.norm_sq x` etc (defeq to `is_R_or_C.re ⟪x, x⟫`) instead of `‖x‖ ^ 2` etc to avoid extra rewrites when applying it to an `inner_product_space`. -/ theorem cauchy_schwarz_aux (x y : F) : norm_sqF (⟪x, y⟫ • x - ⟪x, x⟫ • y) = norm_sqF x * (norm_sqF x * norm_sqF y - ‖⟪x, y⟫‖ ^ 2) := begin rw [← @of_real_inj 𝕜, coe_norm_sq_eq_inner_self], simp only [inner_sub_sub_self, inner_smul_left, inner_smul_right, conj_of_real, mul_sub, ← coe_norm_sq_eq_inner_self x, ← coe_norm_sq_eq_inner_self y], rw [← mul_assoc, mul_conj, is_R_or_C.conj_mul, norm_sq_eq_def', mul_left_comm, ← inner_conj_symm y, mul_conj, norm_sq_eq_def'], push_cast, ring end /-- **Cauchy–Schwarz inequality**. We need this for the `core` structure to prove the triangle inequality below when showing the core is a normed group. -/ lemma inner_mul_inner_self_le (x y : F) : ‖⟪x, y⟫‖ * ‖⟪y, x⟫‖ ≤ re ⟪x, x⟫ * re ⟪y, y⟫ := begin rcases eq_or_ne x 0 with (rfl | hx), { simp only [inner_zero_left, map_zero, zero_mul, norm_zero] }, { have hx' : 0 < norm_sqF x := inner_self_nonneg.lt_of_ne' (mt norm_sq_eq_zero.1 hx), rw [← sub_nonneg, ← mul_nonneg_iff_right_nonneg_of_pos hx', ← norm_sq, ← norm_sq, norm_inner_symm y, ← sq, ← cauchy_schwarz_aux], exact inner_self_nonneg } end /-- Norm constructed from a `inner_product_space.core` structure, defined to be the square root of the scalar product. -/ def to_has_norm : has_norm F := { norm := λ x, sqrt (re ⟪x, x⟫) } local attribute [instance] to_has_norm lemma norm_eq_sqrt_inner (x : F) : ‖x‖ = sqrt (re ⟪x, x⟫) := rfl lemma inner_self_eq_norm_mul_norm (x : F) : re ⟪x, x⟫ = ‖x‖ * ‖x‖ := by rw [norm_eq_sqrt_inner, ←sqrt_mul inner_self_nonneg (re ⟪x, x⟫), sqrt_mul_self inner_self_nonneg] lemma sqrt_norm_sq_eq_norm (x : F) : sqrt (norm_sqF x) = ‖x‖ := rfl /-- Cauchy–Schwarz inequality with norm -/ lemma norm_inner_le_norm (x y : F) : ‖⟪x, y⟫‖ ≤ ‖x‖ * ‖y‖ := nonneg_le_nonneg_of_sq_le_sq (mul_nonneg (sqrt_nonneg _) (sqrt_nonneg _)) $ calc ‖⟪x, y⟫‖ * ‖⟪x, y⟫‖ = ‖⟪x, y⟫‖ * ‖⟪y, x⟫‖ : by rw [norm_inner_symm] ... ≤ re ⟪x, x⟫ * re ⟪y, y⟫ : inner_mul_inner_self_le x y ... = ‖x‖ * ‖y‖ * (‖x‖ * ‖y‖) : by simp only [inner_self_eq_norm_mul_norm]; ring /-- Normed group structure constructed from an `inner_product_space.core` structure -/ def to_normed_add_comm_group : normed_add_comm_group F := add_group_norm.to_normed_add_comm_group { to_fun := λ x, sqrt (re ⟪x, x⟫), map_zero' := by simp only [sqrt_zero, inner_zero_right, map_zero], neg' := λ x, by simp only [inner_neg_left, neg_neg, inner_neg_right], add_le' := λ x y, begin have h₁ : ‖⟪x, y⟫‖ ≤ ‖x‖ * ‖y‖ := norm_inner_le_norm _ _, have h₂ : re ⟪x, y⟫ ≤ ‖⟪x, y⟫‖ := re_le_norm _, have h₃ : re ⟪x, y⟫ ≤ ‖x‖ * ‖y‖ := h₂.trans h₁, have h₄ : re ⟪y, x⟫ ≤ ‖x‖ * ‖y‖ := by rwa [←inner_conj_symm, conj_re], have : ‖x + y‖ * ‖x + y‖ ≤ (‖x‖ + ‖y‖) * (‖x‖ + ‖y‖), { simp only [←inner_self_eq_norm_mul_norm, inner_add_add_self, mul_add, mul_comm, map_add], linarith }, exact nonneg_le_nonneg_of_sq_le_sq (add_nonneg (sqrt_nonneg _) (sqrt_nonneg _)) this, end, eq_zero_of_map_eq_zero' := λ x hx, norm_sq_eq_zero.1 $ (sqrt_eq_zero inner_self_nonneg).1 hx } local attribute [instance] to_normed_add_comm_group /-- Normed space structure constructed from a `inner_product_space.core` structure -/ def to_normed_space : normed_space 𝕜 F := { norm_smul_le := assume r x, begin rw [norm_eq_sqrt_inner, inner_smul_left, inner_smul_right, ←mul_assoc], rw [is_R_or_C.conj_mul, of_real_mul_re, sqrt_mul, ← coe_norm_sq_eq_inner_self, of_real_re], { simp [sqrt_norm_sq_eq_norm, is_R_or_C.sqrt_norm_sq_eq_norm] }, { exact norm_sq_nonneg r } end } end inner_product_space.core section local attribute [instance] inner_product_space.core.to_normed_add_comm_group /-- Given a `inner_product_space.core` structure on a space, one can use it to turn the space into an inner product space. The `normed_add_comm_group` structure is expected to already be defined with `inner_product_space.of_core.to_normed_add_comm_group`. -/ def inner_product_space.of_core [add_comm_group F] [module 𝕜 F] (c : inner_product_space.core 𝕜 F) : inner_product_space 𝕜 F := begin letI : normed_space 𝕜 F := @inner_product_space.core.to_normed_space 𝕜 F _ _ _ c, exact { norm_sq_eq_inner := λ x, begin have h₁ : ‖x‖^2 = (sqrt (re (c.inner x x))) ^ 2 := rfl, have h₂ : 0 ≤ re (c.inner x x) := inner_product_space.core.inner_self_nonneg, simp [h₁, sq_sqrt, h₂], end, ..c } end end /-! ### Properties of inner product spaces -/ variables [normed_add_comm_group E] [inner_product_space 𝕜 E] variables [normed_add_comm_group F] [inner_product_space ℝ F] variables [dec_E : decidable_eq E] local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y local notation `IK` := @is_R_or_C.I 𝕜 _ local postfix `†`:90 := star_ring_end _ export inner_product_space (norm_sq_eq_inner) section basic_properties @[simp] lemma inner_conj_symm (x y : E) : ⟪y, x⟫† = ⟪x, y⟫ := inner_product_space.conj_symm _ _ lemma real_inner_comm (x y : F) : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := @inner_conj_symm ℝ _ _ _ _ x y lemma inner_eq_zero_symm {x y : E} : ⟪x, y⟫ = 0 ↔ ⟪y, x⟫ = 0 := by { rw [← inner_conj_symm], exact star_eq_zero } @[simp] lemma inner_self_im (x : E) : im ⟪x, x⟫ = 0 := by rw [← @of_real_inj 𝕜, im_eq_conj_sub]; simp lemma inner_add_left (x y z : E) : ⟪x + y, z⟫ = ⟪x, z⟫ + ⟪y, z⟫ := inner_product_space.add_left _ _ _ lemma inner_add_right (x y z : E) : ⟪x, y + z⟫ = ⟪x, y⟫ + ⟪x, z⟫ := by { rw [←inner_conj_symm, inner_add_left, ring_hom.map_add], simp only [inner_conj_symm] } lemma inner_re_symm (x y : E) : re ⟪x, y⟫ = re ⟪y, x⟫ := by rw [←inner_conj_symm, conj_re] lemma inner_im_symm (x y : E) : im ⟪x, y⟫ = -im ⟪y, x⟫ := by rw [←inner_conj_symm, conj_im] lemma inner_smul_left (x y : E) (r : 𝕜) : ⟪r • x, y⟫ = r† * ⟪x, y⟫ := inner_product_space.smul_left _ _ _ lemma real_inner_smul_left (x y : F) (r : ℝ) : ⟪r • x, y⟫_ℝ = r * ⟪x, y⟫_ℝ := inner_smul_left _ _ _ lemma inner_smul_real_left (x y : E) (r : ℝ) : ⟪(r : 𝕜) • x, y⟫ = r • ⟪x, y⟫ := by { rw [inner_smul_left, conj_of_real, algebra.smul_def], refl } lemma inner_smul_right (x y : E) (r : 𝕜) : ⟪x, r • y⟫ = r * ⟪x, y⟫ := by rw [←inner_conj_symm, inner_smul_left, ring_hom.map_mul, conj_conj, inner_conj_symm] lemma real_inner_smul_right (x y : F) (r : ℝ) : ⟪x, r • y⟫_ℝ = r * ⟪x, y⟫_ℝ := inner_smul_right _ _ _ lemma inner_smul_real_right (x y : E) (r : ℝ) : ⟪x, (r : 𝕜) • y⟫ = r • ⟪x, y⟫ := by { rw [inner_smul_right, algebra.smul_def], refl } /-- The inner product as a sesquilinear form. Note that in the case `𝕜 = ℝ` this is a bilinear form. -/ @[simps] def sesq_form_of_inner : E →ₗ[𝕜] E →ₗ⋆[𝕜] 𝕜 := linear_map.mk₂'ₛₗ (ring_hom.id 𝕜) (star_ring_end _) (λ x y, ⟪y, x⟫) (λ x y z, inner_add_right _ _ _) (λ r x y, inner_smul_right _ _ _) (λ x y z, inner_add_left _ _ _) (λ r x y, inner_smul_left _ _ _) /-- The real inner product as a bilinear form. -/ @[simps] def bilin_form_of_real_inner : bilin_form ℝ F := { bilin := inner, bilin_add_left := inner_add_left, bilin_smul_left := λ a x y, inner_smul_left _ _ _, bilin_add_right := inner_add_right, bilin_smul_right := λ a x y, inner_smul_right _ _ _ } /-- An inner product with a sum on the left. -/ lemma sum_inner {ι : Type*} (s : finset ι) (f : ι → E) (x : E) : ⟪∑ i in s, f i, x⟫ = ∑ i in s, ⟪f i, x⟫ := (sesq_form_of_inner x).map_sum /-- An inner product with a sum on the right. -/ lemma inner_sum {ι : Type*} (s : finset ι) (f : ι → E) (x : E) : ⟪x, ∑ i in s, f i⟫ = ∑ i in s, ⟪x, f i⟫ := (linear_map.flip sesq_form_of_inner x).map_sum /-- An inner product with a sum on the left, `finsupp` version. -/ lemma finsupp.sum_inner {ι : Type*} (l : ι →₀ 𝕜) (v : ι → E) (x : E) : ⟪l.sum (λ (i : ι) (a : 𝕜), a • v i), x⟫ = l.sum (λ (i : ι) (a : 𝕜), (conj a) • ⟪v i, x⟫) := by { convert sum_inner l.support (λ a, l a • v a) x, simp only [inner_smul_left, finsupp.sum, smul_eq_mul] } /-- An inner product with a sum on the right, `finsupp` version. -/ lemma finsupp.inner_sum {ι : Type*} (l : ι →₀ 𝕜) (v : ι → E) (x : E) : ⟪x, l.sum (λ (i : ι) (a : 𝕜), a • v i)⟫ = l.sum (λ (i : ι) (a : 𝕜), a • ⟪x, v i⟫) := by { convert inner_sum l.support (λ a, l a • v a) x, simp only [inner_smul_right, finsupp.sum, smul_eq_mul] } lemma dfinsupp.sum_inner {ι : Type*} [dec : decidable_eq ι] {α : ι → Type*} [Π i, add_zero_class (α i)] [Π i (x : α i), decidable (x ≠ 0)] (f : Π i, α i → E) (l : Π₀ i, α i) (x : E) : ⟪l.sum f, x⟫ = l.sum (λ i a, ⟪f i a, x⟫) := by simp only [dfinsupp.sum, sum_inner, smul_eq_mul] {contextual := tt} lemma dfinsupp.inner_sum {ι : Type*} [dec : decidable_eq ι] {α : ι → Type*} [Π i, add_zero_class (α i)] [Π i (x : α i), decidable (x ≠ 0)] (f : Π i, α i → E) (l : Π₀ i, α i) (x : E) : ⟪x, l.sum f⟫ = l.sum (λ i a, ⟪x, f i a⟫) := by simp only [dfinsupp.sum, inner_sum, smul_eq_mul] {contextual := tt} @[simp] lemma inner_zero_left (x : E) : ⟪0, x⟫ = 0 := by rw [← zero_smul 𝕜 (0:E), inner_smul_left, ring_hom.map_zero, zero_mul] lemma inner_re_zero_left (x : E) : re ⟪0, x⟫ = 0 := by simp only [inner_zero_left, add_monoid_hom.map_zero] @[simp] lemma inner_zero_right (x : E) : ⟪x, 0⟫ = 0 := by rw [←inner_conj_symm, inner_zero_left, ring_hom.map_zero] lemma inner_re_zero_right (x : E) : re ⟪x, 0⟫ = 0 := by simp only [inner_zero_right, add_monoid_hom.map_zero] lemma inner_self_nonneg {x : E} : 0 ≤ re ⟪x, x⟫ := inner_product_space.to_core.nonneg_re x lemma real_inner_self_nonneg {x : F} : 0 ≤ ⟪x, x⟫_ℝ := @inner_self_nonneg ℝ F _ _ _ x @[simp] lemma inner_self_re_to_K (x : E) : (re ⟪x, x⟫ : 𝕜) = ⟪x, x⟫ := ((is_R_or_C.is_real_tfae (⟪x, x⟫ : 𝕜)).out 2 3).2 (inner_self_im _) lemma inner_self_eq_norm_sq_to_K (x : E) : ⟪x, x⟫ = (‖x‖ ^ 2 : 𝕜) := by rw [← inner_self_re_to_K, ← norm_sq_eq_inner, of_real_pow] lemma inner_self_re_eq_norm (x : E) : re ⟪x, x⟫ = ‖⟪x, x⟫‖ := begin conv_rhs { rw [←inner_self_re_to_K] }, symmetry, exact norm_of_nonneg inner_self_nonneg, end lemma inner_self_norm_to_K (x : E) : (‖⟪x, x⟫‖ : 𝕜) = ⟪x, x⟫ := by { rw [←inner_self_re_eq_norm], exact inner_self_re_to_K _ } lemma real_inner_self_abs (x : F) : |⟪x, x⟫_ℝ| = ⟪x, x⟫_ℝ := @inner_self_norm_to_K ℝ F _ _ _ x @[simp] lemma inner_self_eq_zero {x : E} : ⟪x, x⟫ = 0 ↔ x = 0 := by rw [inner_self_eq_norm_sq_to_K, sq_eq_zero_iff, of_real_eq_zero, norm_eq_zero] lemma inner_self_ne_zero {x : E} : ⟪x, x⟫ ≠ 0 ↔ x ≠ 0 := inner_self_eq_zero.not @[simp] lemma inner_self_nonpos {x : E} : re ⟪x, x⟫ ≤ 0 ↔ x = 0 := by rw [← norm_sq_eq_inner, (sq_nonneg _).le_iff_eq, sq_eq_zero_iff, norm_eq_zero] lemma real_inner_self_nonpos {x : F} : ⟪x, x⟫_ℝ ≤ 0 ↔ x = 0 := @inner_self_nonpos ℝ F _ _ _ x lemma norm_inner_symm (x y : E) : ‖⟪x, y⟫‖ = ‖⟪y, x⟫‖ := by rw [←inner_conj_symm, norm_conj] @[simp] lemma inner_neg_left (x y : E) : ⟪-x, y⟫ = -⟪x, y⟫ := by { rw [← neg_one_smul 𝕜 x, inner_smul_left], simp } @[simp] lemma inner_neg_right (x y : E) : ⟪x, -y⟫ = -⟪x, y⟫ := by rw [←inner_conj_symm, inner_neg_left]; simp only [ring_hom.map_neg, inner_conj_symm] lemma inner_neg_neg (x y : E) : ⟪-x, -y⟫ = ⟪x, y⟫ := by simp @[simp] lemma inner_self_conj (x : E) : ⟪x, x⟫† = ⟪x, x⟫ := by rw [is_R_or_C.ext_iff]; exact ⟨by rw [conj_re], by rw [conj_im, inner_self_im, neg_zero]⟩ lemma inner_sub_left (x y z : E) : ⟪x - y, z⟫ = ⟪x, z⟫ - ⟪y, z⟫ := by { simp [sub_eq_add_neg, inner_add_left] } lemma inner_sub_right (x y z : E) : ⟪x, y - z⟫ = ⟪x, y⟫ - ⟪x, z⟫ := by { simp [sub_eq_add_neg, inner_add_right] } lemma inner_mul_symm_re_eq_norm (x y : E) : re (⟪x, y⟫ * ⟪y, x⟫) = ‖⟪x, y⟫ * ⟪y, x⟫‖ := by { rw [←inner_conj_symm, mul_comm], exact re_eq_norm_of_mul_conj (inner y x), } /-- Expand `⟪x + y, x + y⟫` -/ lemma inner_add_add_self (x y : E) : ⟪x + y, x + y⟫ = ⟪x, x⟫ + ⟪x, y⟫ + ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_add_left, inner_add_right]; ring /-- Expand `⟪x + y, x + y⟫_ℝ` -/ lemma real_inner_add_add_self (x y : F) : ⟪x + y, x + y⟫_ℝ = ⟪x, x⟫_ℝ + 2 * ⟪x, y⟫_ℝ + ⟪y, y⟫_ℝ := begin have : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_symm]; refl, simp only [inner_add_add_self, this, add_left_inj], ring, end /- Expand `⟪x - y, x - y⟫` -/ lemma inner_sub_sub_self (x y : E) : ⟪x - y, x - y⟫ = ⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_sub_left, inner_sub_right]; ring /-- Expand `⟪x - y, x - y⟫_ℝ` -/ lemma real_inner_sub_sub_self (x y : F) : ⟪x - y, x - y⟫_ℝ = ⟪x, x⟫_ℝ - 2 * ⟪x, y⟫_ℝ + ⟪y, y⟫_ℝ := begin have : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_symm]; refl, simp only [inner_sub_sub_self, this, add_left_inj], ring, end variable (𝕜) include 𝕜 lemma ext_inner_left {x y : E} (h : ∀ v, ⟪v, x⟫ = ⟪v, y⟫) : x = y := by rw [←sub_eq_zero, ←@inner_self_eq_zero 𝕜, inner_sub_right, sub_eq_zero, h (x - y)] lemma ext_inner_right {x y : E} (h : ∀ v, ⟪x, v⟫ = ⟪y, v⟫) : x = y := by rw [←sub_eq_zero, ←@inner_self_eq_zero 𝕜, inner_sub_left, sub_eq_zero, h (x - y)] omit 𝕜 variable {𝕜} /-- Parallelogram law -/ lemma parallelogram_law {x y : E} : ⟪x + y, x + y⟫ + ⟪x - y, x - y⟫ = 2 * (⟪x, x⟫ + ⟪y, y⟫) := by simp [inner_add_add_self, inner_sub_sub_self, two_mul, sub_eq_add_neg, add_comm, add_left_comm] /-- **Cauchy–Schwarz inequality**. -/ lemma inner_mul_inner_self_le (x y : E) : ‖⟪x, y⟫‖ * ‖⟪y, x⟫‖ ≤ re ⟪x, x⟫ * re ⟪y, y⟫ := begin letI c : inner_product_space.core 𝕜 E := inner_product_space.to_core, exact inner_product_space.core.inner_mul_inner_self_le x y end /-- Cauchy–Schwarz inequality for real inner products. -/ lemma real_inner_mul_inner_self_le (x y : F) : ⟪x, y⟫_ℝ * ⟪x, y⟫_ℝ ≤ ⟪x, x⟫_ℝ * ⟪y, y⟫_ℝ := calc ⟪x, y⟫_ℝ * ⟪x, y⟫_ℝ ≤ ‖⟪x, y⟫_ℝ‖ * ‖⟪y, x⟫_ℝ‖ : by { rw [real_inner_comm y, ← norm_mul], exact le_abs_self _ } ... ≤ ⟪x, x⟫_ℝ * ⟪y, y⟫_ℝ : @inner_mul_inner_self_le ℝ _ _ _ _ x y /-- A family of vectors is linearly independent if they are nonzero and orthogonal. -/ lemma linear_independent_of_ne_zero_of_inner_eq_zero {ι : Type*} {v : ι → E} (hz : ∀ i, v i ≠ 0) (ho : ∀ i j, i ≠ j → ⟪v i, v j⟫ = 0) : linear_independent 𝕜 v := begin rw linear_independent_iff', intros s g hg i hi, have h' : g i * inner (v i) (v i) = inner (v i) (∑ j in s, g j • v j), { rw inner_sum, symmetry, convert finset.sum_eq_single i _ _, { rw inner_smul_right }, { intros j hj hji, rw [inner_smul_right, ho i j hji.symm, mul_zero] }, { exact λ h, false.elim (h hi) } }, simpa [hg, hz] using h' end end basic_properties section orthonormal_sets variables {ι : Type*} [dec_ι : decidable_eq ι] (𝕜) include 𝕜 /-- An orthonormal set of vectors in an `inner_product_space` -/ def orthonormal (v : ι → E) : Prop := (∀ i, ‖v i‖ = 1) ∧ (∀ {i j}, i ≠ j → ⟪v i, v j⟫ = 0) omit 𝕜 variables {𝕜} include dec_ι /-- `if ... then ... else` characterization of an indexed set of vectors being orthonormal. (Inner product equals Kronecker delta.) -/ lemma orthonormal_iff_ite {v : ι → E} : orthonormal 𝕜 v ↔ ∀ i j, ⟪v i, v j⟫ = if i = j then (1:𝕜) else (0:𝕜) := begin split, { intros hv i j, split_ifs, { simp [h, inner_self_eq_norm_sq_to_K, hv.1] }, { exact hv.2 h } }, { intros h, split, { intros i, have h' : ‖v i‖ ^ 2 = 1 ^ 2 := by simp [@norm_sq_eq_inner 𝕜, h i i], have h₁ : 0 ≤ ‖v i‖ := norm_nonneg _, have h₂ : (0:ℝ) ≤ 1 := zero_le_one, rwa sq_eq_sq h₁ h₂ at h' }, { intros i j hij, simpa [hij] using h i j } } end omit dec_ι include dec_E /-- `if ... then ... else` characterization of a set of vectors being orthonormal. (Inner product equals Kronecker delta.) -/ theorem orthonormal_subtype_iff_ite {s : set E} : orthonormal 𝕜 (coe : s → E) ↔ (∀ v ∈ s, ∀ w ∈ s, ⟪v, w⟫ = if v = w then 1 else 0) := begin rw orthonormal_iff_ite, split, { intros h v hv w hw, convert h ⟨v, hv⟩ ⟨w, hw⟩ using 1, simp }, { rintros h ⟨v, hv⟩ ⟨w, hw⟩, convert h v hv w hw using 1, simp } end omit dec_E /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_right_finsupp {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι →₀ 𝕜) (i : ι) : ⟪v i, finsupp.total ι E 𝕜 v l⟫ = l i := by classical; simp [finsupp.total_apply, finsupp.inner_sum, orthonormal_iff_ite.mp hv] /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_right_sum {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι → 𝕜) {s : finset ι} {i : ι} (hi : i ∈ s) : ⟪v i, ∑ i in s, (l i) • (v i)⟫ = l i := by classical; simp [inner_sum, inner_smul_right, orthonormal_iff_ite.mp hv, hi] /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_right_fintype [fintype ι] {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι → 𝕜) (i : ι) : ⟪v i, ∑ i : ι, (l i) • (v i)⟫ = l i := hv.inner_right_sum l (finset.mem_univ _) /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_left_finsupp {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι →₀ 𝕜) (i : ι) : ⟪finsupp.total ι E 𝕜 v l, v i⟫ = conj (l i) := by rw [← inner_conj_symm, hv.inner_right_finsupp] /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_left_sum {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι → 𝕜) {s : finset ι} {i : ι} (hi : i ∈ s) : ⟪∑ i in s, (l i) • (v i), v i⟫ = conj (l i) := by classical; simp only [sum_inner, inner_smul_left, orthonormal_iff_ite.mp hv, hi, mul_boole, finset.sum_ite_eq', if_true] /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_left_fintype [fintype ι] {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι → 𝕜) (i : ι) : ⟪∑ i : ι, (l i) • (v i), v i⟫ = conj (l i) := hv.inner_left_sum l (finset.mem_univ _) /-- The inner product of two linear combinations of a set of orthonormal vectors, expressed as a sum over the first `finsupp`. -/ lemma orthonormal.inner_finsupp_eq_sum_left {v : ι → E} (hv : orthonormal 𝕜 v) (l₁ l₂ : ι →₀ 𝕜) : ⟪finsupp.total ι E 𝕜 v l₁, finsupp.total ι E 𝕜 v l₂⟫ = l₁.sum (λ i y, conj y * l₂ i) := by simp only [l₁.total_apply _, finsupp.sum_inner, hv.inner_right_finsupp, smul_eq_mul] /-- The inner product of two linear combinations of a set of orthonormal vectors, expressed as a sum over the second `finsupp`. -/ lemma orthonormal.inner_finsupp_eq_sum_right {v : ι → E} (hv : orthonormal 𝕜 v) (l₁ l₂ : ι →₀ 𝕜) : ⟪finsupp.total ι E 𝕜 v l₁, finsupp.total ι E 𝕜 v l₂⟫ = l₂.sum (λ i y, conj (l₁ i) * y) := by simp only [l₂.total_apply _, finsupp.inner_sum, hv.inner_left_finsupp, mul_comm, smul_eq_mul] /-- The inner product of two linear combinations of a set of orthonormal vectors, expressed as a sum. -/ lemma orthonormal.inner_sum {v : ι → E} (hv : orthonormal 𝕜 v) (l₁ l₂ : ι → 𝕜) (s : finset ι) : ⟪∑ i in s, l₁ i • v i, ∑ i in s, l₂ i • v i⟫ = ∑ i in s, conj (l₁ i) * l₂ i := begin simp_rw [sum_inner, inner_smul_left], refine finset.sum_congr rfl (λ i hi, _), rw hv.inner_right_sum l₂ hi end /-- The double sum of weighted inner products of pairs of vectors from an orthonormal sequence is the sum of the weights. -/ lemma orthonormal.inner_left_right_finset {s : finset ι} {v : ι → E} (hv : orthonormal 𝕜 v) {a : ι → ι → 𝕜} : ∑ i in s, ∑ j in s, (a i j) • ⟪v j, v i⟫ = ∑ k in s, a k k := by classical; simp [orthonormal_iff_ite.mp hv, finset.sum_ite_of_true] /-- An orthonormal set is linearly independent. -/ lemma orthonormal.linear_independent {v : ι → E} (hv : orthonormal 𝕜 v) : linear_independent 𝕜 v := begin rw linear_independent_iff, intros l hl, ext i, have key : ⟪v i, finsupp.total ι E 𝕜 v l⟫ = ⟪v i, 0⟫ := by rw hl, simpa only [hv.inner_right_finsupp, inner_zero_right] using key end /-- A subfamily of an orthonormal family (i.e., a composition with an injective map) is an orthonormal family. -/ lemma orthonormal.comp {ι' : Type*} {v : ι → E} (hv : orthonormal 𝕜 v) (f : ι' → ι) (hf : function.injective f) : orthonormal 𝕜 (v ∘ f) := begin classical, rw orthonormal_iff_ite at ⊢ hv, intros i j, convert hv (f i) (f j) using 1, simp [hf.eq_iff] end /-- An injective family `v : ι → E` is orthonormal if and only if `coe : (range v) → E` is orthonormal. -/ lemma orthonormal_subtype_range {v : ι → E} (hv : function.injective v) : orthonormal 𝕜 (coe : set.range v → E) ↔ orthonormal 𝕜 v := begin let f : ι ≃ set.range v := equiv.of_injective v hv, refine ⟨λ h, h.comp f f.injective, λ h, _⟩, rw ← equiv.self_comp_of_injective_symm hv, exact h.comp f.symm f.symm.injective, end /-- If `v : ι → E` is an orthonormal family, then `coe : (range v) → E` is an orthonormal family. -/ lemma orthonormal.to_subtype_range {v : ι → E} (hv : orthonormal 𝕜 v) : orthonormal 𝕜 (coe : set.range v → E) := (orthonormal_subtype_range hv.linear_independent.injective).2 hv /-- A linear combination of some subset of an orthonormal set is orthogonal to other members of the set. -/ lemma orthonormal.inner_finsupp_eq_zero {v : ι → E} (hv : orthonormal 𝕜 v) {s : set ι} {i : ι} (hi : i ∉ s) {l : ι →₀ 𝕜} (hl : l ∈ finsupp.supported 𝕜 𝕜 s) : ⟪finsupp.total ι E 𝕜 v l, v i⟫ = 0 := begin rw finsupp.mem_supported' at hl, simp only [hv.inner_left_finsupp, hl i hi, map_zero], end /-- Given an orthonormal family, a second family of vectors is orthonormal if every vector equals the corresponding vector in the original family or its negation. -/ lemma orthonormal.orthonormal_of_forall_eq_or_eq_neg {v w : ι → E} (hv : orthonormal 𝕜 v) (hw : ∀ i, w i = v i ∨ w i = -(v i)) : orthonormal 𝕜 w := begin classical, rw orthonormal_iff_ite at *, intros i j, cases hw i with hi hi; cases hw j with hj hj; split_ifs with h; simpa only [hi, hj, h, inner_neg_right, inner_neg_left, neg_neg, eq_self_iff_true, neg_eq_zero] using hv i j end /- The material that follows, culminating in the existence of a maximal orthonormal subset, is adapted from the corresponding development of the theory of linearly independents sets. See `exists_linear_independent` in particular. -/ variables (𝕜 E) lemma orthonormal_empty : orthonormal 𝕜 (λ x, x : (∅ : set E) → E) := by classical; simp [orthonormal_subtype_iff_ite] variables {𝕜 E} lemma orthonormal_Union_of_directed {η : Type*} {s : η → set E} (hs : directed (⊆) s) (h : ∀ i, orthonormal 𝕜 (λ x, x : s i → E)) : orthonormal 𝕜 (λ x, x : (⋃ i, s i) → E) := begin classical, rw orthonormal_subtype_iff_ite, rintros x ⟨_, ⟨i, rfl⟩, hxi⟩ y ⟨_, ⟨j, rfl⟩, hyj⟩, obtain ⟨k, hik, hjk⟩ := hs i j, have h_orth : orthonormal 𝕜 (λ x, x : (s k) → E) := h k, rw orthonormal_subtype_iff_ite at h_orth, exact h_orth x (hik hxi) y (hjk hyj) end lemma orthonormal_sUnion_of_directed {s : set (set E)} (hs : directed_on (⊆) s) (h : ∀ a ∈ s, orthonormal 𝕜 (λ x, x : (a : set E) → E)) : orthonormal 𝕜 (λ x, x : (⋃₀ s) → E) := by rw set.sUnion_eq_Union; exact orthonormal_Union_of_directed hs.directed_coe (by simpa using h) /-- Given an orthonormal set `v` of vectors in `E`, there exists a maximal orthonormal set containing it. -/ lemma exists_maximal_orthonormal {s : set E} (hs : orthonormal 𝕜 (coe : s → E)) : ∃ w ⊇ s, orthonormal 𝕜 (coe : w → E) ∧ ∀ u ⊇ w, orthonormal 𝕜 (coe : u → E) → u = w := begin obtain ⟨b, bi, sb, h⟩ := zorn_subset_nonempty {b | orthonormal 𝕜 (coe : b → E)} _ _ hs, { refine ⟨b, sb, bi, _⟩, exact λ u hus hu, h u hu hus }, { refine λ c hc cc c0, ⟨⋃₀ c, _, _⟩, { exact orthonormal_sUnion_of_directed cc.directed_on (λ x xc, hc xc) }, { exact λ _, set.subset_sUnion_of_mem } } end lemma orthonormal.ne_zero {v : ι → E} (hv : orthonormal 𝕜 v) (i : ι) : v i ≠ 0 := begin have : ‖v i‖ ≠ 0, { rw hv.1 i, norm_num }, simpa using this end open finite_dimensional /-- A family of orthonormal vectors with the correct cardinality forms a basis. -/ def basis_of_orthonormal_of_card_eq_finrank [fintype ι] [nonempty ι] {v : ι → E} (hv : orthonormal 𝕜 v) (card_eq : fintype.card ι = finrank 𝕜 E) : basis ι 𝕜 E := basis_of_linear_independent_of_card_eq_finrank hv.linear_independent card_eq @[simp] lemma coe_basis_of_orthonormal_of_card_eq_finrank [fintype ι] [nonempty ι] {v : ι → E} (hv : orthonormal 𝕜 v) (card_eq : fintype.card ι = finrank 𝕜 E) : (basis_of_orthonormal_of_card_eq_finrank hv card_eq : ι → E) = v := coe_basis_of_linear_independent_of_card_eq_finrank _ _ end orthonormal_sets section norm lemma norm_eq_sqrt_inner (x : E) : ‖x‖ = sqrt (re ⟪x, x⟫) := calc ‖x‖ = sqrt (‖x‖ ^ 2) : (sqrt_sq (norm_nonneg _)).symm ... = sqrt (re ⟪x, x⟫) : congr_arg _ (norm_sq_eq_inner _) lemma norm_eq_sqrt_real_inner (x : F) : ‖x‖ = sqrt ⟪x, x⟫_ℝ := @norm_eq_sqrt_inner ℝ _ _ _ _ x lemma inner_self_eq_norm_mul_norm (x : E) : re ⟪x, x⟫ = ‖x‖ * ‖x‖ := by rw [@norm_eq_sqrt_inner 𝕜, ←sqrt_mul inner_self_nonneg (re ⟪x, x⟫), sqrt_mul_self inner_self_nonneg] lemma inner_self_eq_norm_sq (x : E) : re ⟪x, x⟫ = ‖x‖^2 := by rw [pow_two, inner_self_eq_norm_mul_norm] lemma real_inner_self_eq_norm_mul_norm (x : F) : ⟪x, x⟫_ℝ = ‖x‖ * ‖x‖ := by { have h := @inner_self_eq_norm_mul_norm ℝ F _ _ _ x, simpa using h } lemma real_inner_self_eq_norm_sq (x : F) : ⟪x, x⟫_ℝ = ‖x‖^2 := by rw [pow_two, real_inner_self_eq_norm_mul_norm] variables (𝕜) /-- Expand the square -/ lemma norm_add_sq (x y : E) : ‖x + y‖^2 = ‖x‖^2 + 2 * (re ⟪x, y⟫) + ‖y‖^2 := begin repeat {rw [sq, ←@inner_self_eq_norm_mul_norm 𝕜]}, rw [inner_add_add_self, two_mul], simp only [add_assoc, add_left_inj, add_right_inj, add_monoid_hom.map_add], rw [←inner_conj_symm, conj_re], end alias norm_add_sq ← norm_add_pow_two /-- Expand the square -/ lemma norm_add_sq_real (x y : F) : ‖x + y‖^2 = ‖x‖^2 + 2 * ⟪x, y⟫_ℝ + ‖y‖^2 := by { have h := @norm_add_sq ℝ _ _ _ _ x y, simpa using h } alias norm_add_sq_real ← norm_add_pow_two_real /-- Expand the square -/ lemma norm_add_mul_self (x y : E) : ‖x + y‖ * ‖x + y‖ = ‖x‖ * ‖x‖ + 2 * (re ⟪x, y⟫) + ‖y‖ * ‖y‖ := by { repeat {rw [← sq]}, exact norm_add_sq _ _ } /-- Expand the square -/ lemma norm_add_mul_self_real (x y : F) : ‖x + y‖ * ‖x + y‖ = ‖x‖ * ‖x‖ + 2 * ⟪x, y⟫_ℝ + ‖y‖ * ‖y‖ := by { have h := @norm_add_mul_self ℝ _ _ _ _ x y, simpa using h } /-- Expand the square -/ lemma norm_sub_sq (x y : E) : ‖x - y‖^2 = ‖x‖^2 - 2 * (re ⟪x, y⟫) + ‖y‖^2 := by rw [sub_eq_add_neg, @norm_add_sq 𝕜 _ _ _ _ x (-y), norm_neg, inner_neg_right, map_neg, mul_neg, sub_eq_add_neg] alias norm_sub_sq ← norm_sub_pow_two /-- Expand the square -/ lemma norm_sub_sq_real (x y : F) : ‖x - y‖^2 = ‖x‖^2 - 2 * ⟪x, y⟫_ℝ + ‖y‖^2 := @norm_sub_sq ℝ _ _ _ _ _ _ alias norm_sub_sq_real ← norm_sub_pow_two_real /-- Expand the square -/ lemma norm_sub_mul_self (x y : E) : ‖x - y‖ * ‖x - y‖ = ‖x‖ * ‖x‖ - 2 * re ⟪x, y⟫ + ‖y‖ * ‖y‖ := by { repeat {rw [← sq]}, exact norm_sub_sq _ _ } /-- Expand the square -/ lemma norm_sub_mul_self_real (x y : F) : ‖x - y‖ * ‖x - y‖ = ‖x‖ * ‖x‖ - 2 * ⟪x, y⟫_ℝ + ‖y‖ * ‖y‖ := by { have h := @norm_sub_mul_self ℝ _ _ _ _ x y, simpa using h } /-- Cauchy–Schwarz inequality with norm -/ lemma norm_inner_le_norm (x y : E) : ‖⟪x, y⟫‖ ≤ ‖x‖ * ‖y‖ := begin rw [norm_eq_sqrt_inner x, norm_eq_sqrt_inner y], letI : inner_product_space.core 𝕜 E := inner_product_space.to_core, exact inner_product_space.core.norm_inner_le_norm x y end lemma nnnorm_inner_le_nnnorm (x y : E) : ‖⟪x, y⟫‖₊ ≤ ‖x‖₊ * ‖y‖₊ := norm_inner_le_norm x y lemma re_inner_le_norm (x y : E) : re ⟪x, y⟫ ≤ ‖x‖ * ‖y‖ := le_trans (re_le_norm (inner x y)) (norm_inner_le_norm x y) /-- Cauchy–Schwarz inequality with norm -/ lemma abs_real_inner_le_norm (x y : F) : |⟪x, y⟫_ℝ| ≤ ‖x‖ * ‖y‖ := (real.norm_eq_abs _).ge.trans (norm_inner_le_norm x y) /-- Cauchy–Schwarz inequality with norm -/ lemma real_inner_le_norm (x y : F) : ⟪x, y⟫_ℝ ≤ ‖x‖ * ‖y‖ := le_trans (le_abs_self _) (abs_real_inner_le_norm _ _) include 𝕜 variables (𝕜) lemma parallelogram_law_with_norm (x y : E) : ‖x + y‖ * ‖x + y‖ + ‖x - y‖ * ‖x - y‖ = 2 * (‖x‖ * ‖x‖ + ‖y‖ * ‖y‖) := begin simp only [← @inner_self_eq_norm_mul_norm 𝕜], rw [← re.map_add, parallelogram_law, two_mul, two_mul], simp only [re.map_add], end lemma parallelogram_law_with_nnnorm (x y : E) : ‖x + y‖₊ * ‖x + y‖₊ + ‖x - y‖₊ * ‖x - y‖₊ = 2 * (‖x‖₊ * ‖x‖₊ + ‖y‖₊ * ‖y‖₊) := subtype.ext $ parallelogram_law_with_norm 𝕜 x y variables {𝕜} omit 𝕜 /-- Polarization identity: The real part of the inner product, in terms of the norm. -/ lemma re_inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two (x y : E) : re ⟪x, y⟫ = (‖x + y‖ * ‖x + y‖ - ‖x‖ * ‖x‖ - ‖y‖ * ‖y‖) / 2 := by { rw @norm_add_mul_self 𝕜, ring } /-- Polarization identity: The real part of the inner product, in terms of the norm. -/ lemma re_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two (x y : E) : re ⟪x, y⟫ = (‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ - ‖x - y‖ * ‖x - y‖) / 2 := by { rw [@norm_sub_mul_self 𝕜], ring } /-- Polarization identity: The real part of the inner product, in terms of the norm. -/ lemma re_inner_eq_norm_add_mul_self_sub_norm_sub_mul_self_div_four (x y : E) : re ⟪x, y⟫ = (‖x + y‖ * ‖x + y‖ - ‖x - y‖ * ‖x - y‖) / 4 := by { rw [@norm_add_mul_self 𝕜, @norm_sub_mul_self 𝕜], ring } /-- Polarization identity: The imaginary part of the inner product, in terms of the norm. -/ lemma im_inner_eq_norm_sub_I_smul_mul_self_sub_norm_add_I_smul_mul_self_div_four (x y : E) : im ⟪x, y⟫ = (‖x - IK • y‖ * ‖x - IK • y‖ - ‖x + IK • y‖ * ‖x + IK • y‖) / 4 := by { simp only [@norm_add_mul_self 𝕜, @norm_sub_mul_self 𝕜, inner_smul_right, I_mul_re], ring } /-- Polarization identity: The inner product, in terms of the norm. -/ lemma inner_eq_sum_norm_sq_div_four (x y : E) : ⟪x, y⟫ = (‖x + y‖ ^ 2 - ‖x - y‖ ^ 2 + (‖x - IK • y‖ ^ 2 - ‖x + IK • y‖ ^ 2) * IK) / 4 := begin rw [← re_add_im ⟪x, y⟫, re_inner_eq_norm_add_mul_self_sub_norm_sub_mul_self_div_four, im_inner_eq_norm_sub_I_smul_mul_self_sub_norm_add_I_smul_mul_self_div_four], push_cast, simp only [sq, ← mul_div_right_comm, ← add_div] end /-- Formula for the distance between the images of two nonzero points under an inversion with center zero. See also `euclidean_geometry.dist_inversion_inversion` for inversions around a general point. -/ lemma dist_div_norm_sq_smul {x y : F} (hx : x ≠ 0) (hy : y ≠ 0) (R : ℝ) : dist ((R / ‖x‖) ^ 2 • x) ((R / ‖y‖) ^ 2 • y) = (R ^ 2 / (‖x‖ * ‖y‖)) * dist x y := have hx' : ‖x‖ ≠ 0, from norm_ne_zero_iff.2 hx, have hy' : ‖y‖ ≠ 0, from norm_ne_zero_iff.2 hy, calc dist ((R / ‖x‖) ^ 2 • x) ((R / ‖y‖) ^ 2 • y) = sqrt (‖(R / ‖x‖) ^ 2 • x - (R / ‖y‖) ^ 2 • y‖^2) : by rw [dist_eq_norm, sqrt_sq (norm_nonneg _)] ... = sqrt ((R ^ 2 / (‖x‖ * ‖y‖)) ^ 2 * ‖x - y‖ ^ 2) : congr_arg sqrt $ by { field_simp [sq, norm_sub_mul_self_real, norm_smul, real_inner_smul_left, inner_smul_right, real.norm_of_nonneg (mul_self_nonneg _)], ring } ... = (R ^ 2 / (‖x‖ * ‖y‖)) * dist x y : by rw [sqrt_mul (sq_nonneg _), sqrt_sq (norm_nonneg _), sqrt_sq (div_nonneg (sq_nonneg _) (mul_nonneg (norm_nonneg _) (norm_nonneg _))), dist_eq_norm] @[priority 100] -- See note [lower instance priority] instance inner_product_space.to_uniform_convex_space : uniform_convex_space F := ⟨λ ε hε, begin refine ⟨2 - sqrt (4 - ε^2), sub_pos_of_lt $ (sqrt_lt' zero_lt_two).2 _, λ x hx y hy hxy, _⟩, { norm_num, exact pow_pos hε _ }, rw sub_sub_cancel, refine le_sqrt_of_sq_le _, rw [sq, eq_sub_iff_add_eq.2 (parallelogram_law_with_norm ℝ x y), ←sq (‖x - y‖), hx, hy], norm_num, exact pow_le_pow_of_le_left hε.le hxy _, end⟩ section complex variables {V : Type*} [normed_add_comm_group V] [inner_product_space ℂ V] /-- A complex polarization identity, with a linear map -/ lemma inner_map_polarization (T : V →ₗ[ℂ] V) (x y : V): ⟪ T y, x ⟫_ℂ = (⟪T (x + y) , x + y⟫_ℂ - ⟪T (x - y) , x - y⟫_ℂ + complex.I * ⟪T (x + complex.I • y) , x + complex.I • y⟫_ℂ - complex.I * ⟪T (x - complex.I • y), x - complex.I • y ⟫_ℂ) / 4 := begin simp only [map_add, map_sub, inner_add_left, inner_add_right, linear_map.map_smul, inner_smul_left, inner_smul_right, complex.conj_I, ←pow_two, complex.I_sq, inner_sub_left, inner_sub_right, mul_add, ←mul_assoc, mul_neg, neg_neg, sub_neg_eq_add, one_mul, neg_one_mul, mul_sub, sub_sub], ring, end lemma inner_map_polarization' (T : V →ₗ[ℂ] V) (x y : V): ⟪ T x, y ⟫_ℂ = (⟪T (x + y) , x + y⟫_ℂ - ⟪T (x - y) , x - y⟫_ℂ - complex.I * ⟪T (x + complex.I • y) , x + complex.I • y⟫_ℂ + complex.I * ⟪T (x - complex.I • y), x - complex.I • y ⟫_ℂ) / 4 := begin simp only [map_add, map_sub, inner_add_left, inner_add_right, linear_map.map_smul, inner_smul_left, inner_smul_right, complex.conj_I, ←pow_two, complex.I_sq, inner_sub_left, inner_sub_right, mul_add, ←mul_assoc, mul_neg, neg_neg, sub_neg_eq_add, one_mul, neg_one_mul, mul_sub, sub_sub], ring, end /-- A linear map `T` is zero, if and only if the identity `⟪T x, x⟫_ℂ = 0` holds for all `x`. -/ lemma inner_map_self_eq_zero (T : V →ₗ[ℂ] V) : (∀ (x : V), ⟪T x, x⟫_ℂ = 0) ↔ T = 0 := begin split, { intro hT, ext x, simp only [linear_map.zero_apply, ← @inner_self_eq_zero ℂ, inner_map_polarization, hT], norm_num }, { rintro rfl x, simp only [linear_map.zero_apply, inner_zero_left] } end /-- Two linear maps `S` and `T` are equal, if and only if the identity `⟪S x, x⟫_ℂ = ⟪T x, x⟫_ℂ` holds for all `x`. -/ lemma ext_inner_map (S T : V →ₗ[ℂ] V) : (∀ (x : V), ⟪S x, x⟫_ℂ = ⟪T x, x⟫_ℂ) ↔ S = T := begin rw [←sub_eq_zero, ←inner_map_self_eq_zero], refine forall_congr (λ x, _), rw [linear_map.sub_apply, inner_sub_left, sub_eq_zero], end end complex section variables {ι : Type*} {ι' : Type*} {ι'' : Type*} variables {E' : Type*} [normed_add_comm_group E'] [inner_product_space 𝕜 E'] variables {E'' : Type*} [normed_add_comm_group E''] [inner_product_space 𝕜 E''] /-- A linear isometry preserves the inner product. -/ @[simp] lemma linear_isometry.inner_map_map (f : E →ₗᵢ[𝕜] E') (x y : E) : ⟪f x, f y⟫ = ⟪x, y⟫ := by simp [inner_eq_sum_norm_sq_div_four, ← f.norm_map] /-- A linear isometric equivalence preserves the inner product. -/ @[simp] lemma linear_isometry_equiv.inner_map_map (f : E ≃ₗᵢ[𝕜] E') (x y : E) : ⟪f x, f y⟫ = ⟪x, y⟫ := f.to_linear_isometry.inner_map_map x y /-- A linear map that preserves the inner product is a linear isometry. -/ def linear_map.isometry_of_inner (f : E →ₗ[𝕜] E') (h : ∀ x y, ⟪f x, f y⟫ = ⟪x, y⟫) : E →ₗᵢ[𝕜] E' := ⟨f, λ x, by simp only [@norm_eq_sqrt_inner 𝕜, h]⟩ @[simp] lemma linear_map.coe_isometry_of_inner (f : E →ₗ[𝕜] E') (h) : ⇑(f.isometry_of_inner h) = f := rfl @[simp] lemma linear_map.isometry_of_inner_to_linear_map (f : E →ₗ[𝕜] E') (h) : (f.isometry_of_inner h).to_linear_map = f := rfl /-- A linear equivalence that preserves the inner product is a linear isometric equivalence. -/ def linear_equiv.isometry_of_inner (f : E ≃ₗ[𝕜] E') (h : ∀ x y, ⟪f x, f y⟫ = ⟪x, y⟫) : E ≃ₗᵢ[𝕜] E' := ⟨f, ((f : E →ₗ[𝕜] E').isometry_of_inner h).norm_map⟩ @[simp] lemma linear_equiv.coe_isometry_of_inner (f : E ≃ₗ[𝕜] E') (h) : ⇑(f.isometry_of_inner h) = f := rfl @[simp] lemma linear_equiv.isometry_of_inner_to_linear_equiv (f : E ≃ₗ[𝕜] E') (h) : (f.isometry_of_inner h).to_linear_equiv = f := rfl /-- A linear isometry preserves the property of being orthonormal. -/ lemma linear_isometry.orthonormal_comp_iff {v : ι → E} (f : E →ₗᵢ[𝕜] E') : orthonormal 𝕜 (f ∘ v) ↔ orthonormal 𝕜 v := begin classical, simp_rw [orthonormal_iff_ite, linear_isometry.inner_map_map] end /-- A linear isometry preserves the property of being orthonormal. -/ lemma orthonormal.comp_linear_isometry {v : ι → E} (hv : orthonormal 𝕜 v) (f : E →ₗᵢ[𝕜] E') : orthonormal 𝕜 (f ∘ v) := by rwa f.orthonormal_comp_iff /-- A linear isometric equivalence preserves the property of being orthonormal. -/ lemma orthonormal.comp_linear_isometry_equiv {v : ι → E} (hv : orthonormal 𝕜 v) (f : E ≃ₗᵢ[𝕜] E') : orthonormal 𝕜 (f ∘ v) := hv.comp_linear_isometry f.to_linear_isometry /-- A linear isometric equivalence, applied with `basis.map`, preserves the property of being orthonormal. -/ lemma orthonormal.map_linear_isometry_equiv {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) (f : E ≃ₗᵢ[𝕜] E') : orthonormal 𝕜 (v.map f.to_linear_equiv) := hv.comp_linear_isometry_equiv f /-- A linear map that sends an orthonormal basis to orthonormal vectors is a linear isometry. -/ def linear_map.isometry_of_orthonormal (f : E →ₗ[𝕜] E') {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) (hf : orthonormal 𝕜 (f ∘ v)) : E →ₗᵢ[𝕜] E' := f.isometry_of_inner $ λ x y, by rw [←v.total_repr x, ←v.total_repr y, finsupp.apply_total, finsupp.apply_total, hv.inner_finsupp_eq_sum_left, hf.inner_finsupp_eq_sum_left] @[simp] lemma linear_map.coe_isometry_of_orthonormal (f : E →ₗ[𝕜] E') {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) (hf : orthonormal 𝕜 (f ∘ v)) : ⇑(f.isometry_of_orthonormal hv hf) = f := rfl @[simp] lemma linear_map.isometry_of_orthonormal_to_linear_map (f : E →ₗ[𝕜] E') {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) (hf : orthonormal 𝕜 (f ∘ v)) : (f.isometry_of_orthonormal hv hf).to_linear_map = f := rfl /-- A linear equivalence that sends an orthonormal basis to orthonormal vectors is a linear isometric equivalence. -/ def linear_equiv.isometry_of_orthonormal (f : E ≃ₗ[𝕜] E') {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) (hf : orthonormal 𝕜 (f ∘ v)) : E ≃ₗᵢ[𝕜] E' := f.isometry_of_inner $ λ x y, begin rw ←linear_equiv.coe_coe at hf, rw [←v.total_repr x, ←v.total_repr y, ←linear_equiv.coe_coe, finsupp.apply_total, finsupp.apply_total, hv.inner_finsupp_eq_sum_left, hf.inner_finsupp_eq_sum_left] end @[simp] lemma linear_equiv.coe_isometry_of_orthonormal (f : E ≃ₗ[𝕜] E') {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) (hf : orthonormal 𝕜 (f ∘ v)) : ⇑(f.isometry_of_orthonormal hv hf) = f := rfl @[simp] lemma linear_equiv.isometry_of_orthonormal_to_linear_equiv (f : E ≃ₗ[𝕜] E') {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) (hf : orthonormal 𝕜 (f ∘ v)) : (f.isometry_of_orthonormal hv hf).to_linear_equiv = f := rfl /-- A linear isometric equivalence that sends an orthonormal basis to a given orthonormal basis. -/ def orthonormal.equiv {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) {v' : basis ι' 𝕜 E'} (hv' : orthonormal 𝕜 v') (e : ι ≃ ι') : E ≃ₗᵢ[𝕜] E' := (v.equiv v' e).isometry_of_orthonormal hv begin have h : (v.equiv v' e) ∘ v = v' ∘ e, { ext i, simp }, rw h, exact hv'.comp _ e.injective end @[simp] lemma orthonormal.equiv_to_linear_equiv {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) {v' : basis ι' 𝕜 E'} (hv' : orthonormal 𝕜 v') (e : ι ≃ ι') : (hv.equiv hv' e).to_linear_equiv = v.equiv v' e := rfl @[simp] lemma orthonormal.equiv_apply {ι' : Type*} {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) {v' : basis ι' 𝕜 E'} (hv' : orthonormal 𝕜 v') (e : ι ≃ ι') (i : ι) : hv.equiv hv' e (v i) = v' (e i) := basis.equiv_apply _ _ _ _ @[simp] lemma orthonormal.equiv_refl {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) : hv.equiv hv (equiv.refl ι) = linear_isometry_equiv.refl 𝕜 E := v.ext_linear_isometry_equiv $ λ i, by simp only [orthonormal.equiv_apply, equiv.coe_refl, id.def, linear_isometry_equiv.coe_refl] @[simp] lemma orthonormal.equiv_symm {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) {v' : basis ι' 𝕜 E'} (hv' : orthonormal 𝕜 v') (e : ι ≃ ι') : (hv.equiv hv' e).symm = hv'.equiv hv e.symm := v'.ext_linear_isometry_equiv $ λ i, (hv.equiv hv' e).injective $ by simp only [linear_isometry_equiv.apply_symm_apply, orthonormal.equiv_apply, e.apply_symm_apply] @[simp] lemma orthonormal.equiv_trans {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) {v' : basis ι' 𝕜 E'} (hv' : orthonormal 𝕜 v') (e : ι ≃ ι') {v'' : basis ι'' 𝕜 E''} (hv'' : orthonormal 𝕜 v'') (e' : ι' ≃ ι'') : (hv.equiv hv' e).trans (hv'.equiv hv'' e') = hv.equiv hv'' (e.trans e') := v.ext_linear_isometry_equiv $ λ i, by simp only [linear_isometry_equiv.trans_apply, orthonormal.equiv_apply, e.coe_trans] lemma orthonormal.map_equiv {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) {v' : basis ι' 𝕜 E'} (hv' : orthonormal 𝕜 v') (e : ι ≃ ι') : v.map ((hv.equiv hv' e).to_linear_equiv) = v'.reindex e.symm := v.map_equiv _ _ end /-- Polarization identity: The real inner product, in terms of the norm. -/ lemma real_inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two (x y : F) : ⟪x, y⟫_ℝ = (‖x + y‖ * ‖x + y‖ - ‖x‖ * ‖x‖ - ‖y‖ * ‖y‖) / 2 := re_to_real.symm.trans $ re_inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two x y /-- Polarization identity: The real inner product, in terms of the norm. -/ lemma real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two (x y : F) : ⟪x, y⟫_ℝ = (‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ - ‖x - y‖ * ‖x - y‖) / 2 := re_to_real.symm.trans $ re_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two x y /-- Pythagorean theorem, if-and-only-if vector inner product form. -/ lemma norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero (x y : F) : ‖x + y‖ * ‖x + y‖ = ‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ ↔ ⟪x, y⟫_ℝ = 0 := begin rw [@norm_add_mul_self ℝ, add_right_cancel_iff, add_right_eq_self, mul_eq_zero], norm_num end /-- Pythagorean theorem, if-and-if vector inner product form using square roots. -/ lemma norm_add_eq_sqrt_iff_real_inner_eq_zero {x y : F} : ‖x + y‖ = sqrt (‖x‖ * ‖x‖ + ‖y‖ * ‖y‖) ↔ ⟪x, y⟫_ℝ = 0 := by rw [←norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero, eq_comm, sqrt_eq_iff_mul_self_eq (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _)) (norm_nonneg _)] /-- Pythagorean theorem, vector inner product form. -/ lemma norm_add_sq_eq_norm_sq_add_norm_sq_of_inner_eq_zero (x y : E) (h : ⟪x, y⟫ = 0) : ‖x + y‖ * ‖x + y‖ = ‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ := begin rw [@norm_add_mul_self 𝕜, add_right_cancel_iff, add_right_eq_self, mul_eq_zero], apply or.inr, simp only [h, zero_re'], end /-- Pythagorean theorem, vector inner product form. -/ lemma norm_add_sq_eq_norm_sq_add_norm_sq_real {x y : F} (h : ⟪x, y⟫_ℝ = 0) : ‖x + y‖ * ‖x + y‖ = ‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ := (norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero x y).2 h /-- Pythagorean theorem, subtracting vectors, if-and-only-if vector inner product form. -/ lemma norm_sub_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero (x y : F) : ‖x - y‖ * ‖x - y‖ = ‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ ↔ ⟪x, y⟫_ℝ = 0 := begin rw [@norm_sub_mul_self ℝ, add_right_cancel_iff, sub_eq_add_neg, add_right_eq_self, neg_eq_zero, mul_eq_zero], norm_num end /-- Pythagorean theorem, subtracting vectors, if-and-if vector inner product form using square roots. -/ lemma norm_sub_eq_sqrt_iff_real_inner_eq_zero {x y : F} : ‖x - y‖ = sqrt (‖x‖ * ‖x‖ + ‖y‖ * ‖y‖) ↔ ⟪x, y⟫_ℝ = 0 := by rw [←norm_sub_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero, eq_comm, sqrt_eq_iff_mul_self_eq (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _)) (norm_nonneg _)] /-- Pythagorean theorem, subtracting vectors, vector inner product form. -/ lemma norm_sub_sq_eq_norm_sq_add_norm_sq_real {x y : F} (h : ⟪x, y⟫_ℝ = 0) : ‖x - y‖ * ‖x - y‖ = ‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ := (norm_sub_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero x y).2 h /-- The sum and difference of two vectors are orthogonal if and only if they have the same norm. -/ lemma real_inner_add_sub_eq_zero_iff (x y : F) : ⟪x + y, x - y⟫_ℝ = 0 ↔ ‖x‖ = ‖y‖ := begin conv_rhs { rw ←mul_self_inj_of_nonneg (norm_nonneg _) (norm_nonneg _) }, simp only [←@inner_self_eq_norm_mul_norm ℝ, inner_add_left, inner_sub_right, real_inner_comm y x, sub_eq_zero, re_to_real], split, { intro h, rw [add_comm] at h, linarith }, { intro h, linarith } end /-- Given two orthogonal vectors, their sum and difference have equal norms. -/ lemma norm_sub_eq_norm_add {v w : E} (h : ⟪v, w⟫ = 0) : ‖w - v‖ = ‖w + v‖ := begin rw ←mul_self_inj_of_nonneg (norm_nonneg _) (norm_nonneg _), simp only [h, ←@inner_self_eq_norm_mul_norm 𝕜, sub_neg_eq_add, sub_zero, map_sub, zero_re', zero_sub, add_zero, map_add, inner_add_right, inner_sub_left, inner_sub_right, inner_re_symm, zero_add] end /-- The real inner product of two vectors, divided by the product of their norms, has absolute value at most 1. -/ lemma abs_real_inner_div_norm_mul_norm_le_one (x y : F) : |⟪x, y⟫_ℝ / (‖x‖ * ‖y‖)| ≤ 1 := begin rw [abs_div, abs_mul, abs_norm, abs_norm], exact div_le_one_of_le (abs_real_inner_le_norm x y) (by positivity) end /-- The inner product of a vector with a multiple of itself. -/ lemma real_inner_smul_self_left (x : F) (r : ℝ) : ⟪r • x, x⟫_ℝ = r * (‖x‖ * ‖x‖) := by rw [real_inner_smul_left, ←real_inner_self_eq_norm_mul_norm] /-- The inner product of a vector with a multiple of itself. -/ lemma real_inner_smul_self_right (x : F) (r : ℝ) : ⟪x, r • x⟫_ℝ = r * (‖x‖ * ‖x‖) := by rw [inner_smul_right, ←real_inner_self_eq_norm_mul_norm] /-- The inner product of a nonzero vector with a nonzero multiple of itself, divided by the product of their norms, has absolute value 1. -/ lemma norm_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul {x : E} {r : 𝕜} (hx : x ≠ 0) (hr : r ≠ 0) : ‖⟪x, r • x⟫‖ / (‖x‖ * ‖r • x‖) = 1 := begin have hx' : ‖x‖ ≠ 0 := by simp [hx], have hr' : ‖r‖ ≠ 0 := by simp [hr], rw [inner_smul_right, norm_mul, ← inner_self_re_eq_norm, inner_self_eq_norm_mul_norm, norm_smul], rw [← mul_assoc, ← div_div, mul_div_cancel _ hx', ← div_div, mul_comm, mul_div_cancel _ hr', div_self hx'], end /-- The inner product of a nonzero vector with a nonzero multiple of itself, divided by the product of their norms, has absolute value 1. -/ lemma abs_real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul {x : F} {r : ℝ} (hx : x ≠ 0) (hr : r ≠ 0) : |⟪x, r • x⟫_ℝ| / (‖x‖ * ‖r • x‖) = 1 := norm_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul hx hr /-- The inner product of a nonzero vector with a positive multiple of itself, divided by the product of their norms, has value 1. -/ lemma real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul {x : F} {r : ℝ} (hx : x ≠ 0) (hr : 0 < r) : ⟪x, r • x⟫_ℝ / (‖x‖ * ‖r • x‖) = 1 := begin rw [real_inner_smul_self_right, norm_smul, real.norm_eq_abs, ←mul_assoc ‖x‖, mul_comm _ (|r|), mul_assoc, abs_of_nonneg hr.le, div_self], exact mul_ne_zero hr.ne' (mul_self_ne_zero.2 (norm_ne_zero_iff.2 hx)) end /-- The inner product of a nonzero vector with a negative multiple of itself, divided by the product of their norms, has value -1. -/ lemma real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul {x : F} {r : ℝ} (hx : x ≠ 0) (hr : r < 0) : ⟪x, r • x⟫_ℝ / (‖x‖ * ‖r • x‖) = -1 := begin rw [real_inner_smul_self_right, norm_smul, real.norm_eq_abs, ←mul_assoc ‖x‖, mul_comm _ (|r|), mul_assoc, abs_of_neg hr, neg_mul, div_neg_eq_neg_div, div_self], exact mul_ne_zero hr.ne (mul_self_ne_zero.2 (norm_ne_zero_iff.2 hx)) end lemma norm_inner_eq_norm_tfae (x y : E) : tfae [‖⟪x, y⟫‖ = ‖x‖ * ‖y‖, x = 0 ∨ y = (⟪x, y⟫ / ⟪x, x⟫) • x, x = 0 ∨ ∃ r : 𝕜, y = r • x, x = 0 ∨ y ∈ 𝕜 ∙ x] := begin tfae_have : 1 → 2, { refine λ h, or_iff_not_imp_left.2 (λ hx₀, _), have : ‖x‖ ^ 2 ≠ 0 := pow_ne_zero _ (norm_ne_zero_iff.2 hx₀), rw [← sq_eq_sq (norm_nonneg _) (mul_nonneg (norm_nonneg _) (norm_nonneg _)), mul_pow, ← mul_right_inj' this, eq_comm, ← sub_eq_zero, ← mul_sub] at h, simp only [@norm_sq_eq_inner 𝕜] at h, letI : inner_product_space.core 𝕜 E := inner_product_space.to_core, erw [← inner_product_space.core.cauchy_schwarz_aux, inner_product_space.core.norm_sq_eq_zero, sub_eq_zero] at h, rw [div_eq_inv_mul, mul_smul, h, inv_smul_smul₀], rwa [inner_self_ne_zero] }, tfae_have : 2 → 3, from λ h, h.imp_right (λ h', ⟨_, h'⟩), tfae_have : 3 → 1, { rintro (rfl | ⟨r, rfl⟩); simp [inner_smul_right, norm_smul, inner_self_eq_norm_sq_to_K, inner_self_eq_norm_mul_norm, sq, mul_left_comm] }, tfae_have : 3 ↔ 4, by simp only [submodule.mem_span_singleton, eq_comm], tfae_finish end /-- If the inner product of two vectors is equal to the product of their norms, then the two vectors are multiples of each other. One form of the equality case for Cauchy-Schwarz. Compare `inner_eq_norm_mul_iff`, which takes the stronger hypothesis `⟪x, y⟫ = ‖x‖ * ‖y‖`. -/ lemma norm_inner_eq_norm_iff {x y : E} (hx₀ : x ≠ 0) (hy₀ : y ≠ 0) : ‖⟪x, y⟫‖ = ‖x‖ * ‖y‖ ↔ ∃ (r : 𝕜), r ≠ 0 ∧ y = r • x := calc ‖⟪x, y⟫‖ = ‖x‖ * ‖y‖ ↔ x = 0 ∨ ∃ r : 𝕜, y = r • x : (@norm_inner_eq_norm_tfae 𝕜 _ _ _ _ x y).out 0 2 ... ↔ ∃ r : 𝕜, y = r • x : or_iff_right hx₀ ... ↔ ∃ r : 𝕜, r ≠ 0 ∧ y = r • x : ⟨λ ⟨r, h⟩, ⟨r, λ hr₀, hy₀ $ h.symm ▸ smul_eq_zero.2 $ or.inl hr₀, h⟩, λ ⟨r, hr₀, h⟩, ⟨r, h⟩⟩ /-- The inner product of two vectors, divided by the product of their norms, has absolute value 1 if and only if they are nonzero and one is a multiple of the other. One form of equality case for Cauchy-Schwarz. -/ lemma norm_inner_div_norm_mul_norm_eq_one_iff (x y : E) : ‖(⟪x, y⟫ / (‖x‖ * ‖y‖))‖ = 1 ↔ (x ≠ 0 ∧ ∃ (r : 𝕜), r ≠ 0 ∧ y = r • x) := begin split, { intro h, have hx₀ : x ≠ 0 := λ h₀, by simpa [h₀] using h, have hy₀ : y ≠ 0 := λ h₀, by simpa [h₀] using h, refine ⟨hx₀, (norm_inner_eq_norm_iff hx₀ hy₀).1 $ eq_of_div_eq_one _⟩, simpa using h }, { rintro ⟨hx, ⟨r, ⟨hr, rfl⟩⟩⟩, simp only [norm_div, norm_mul, norm_of_real, abs_norm], exact norm_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul hx hr } end /-- The inner product of two vectors, divided by the product of their norms, has absolute value 1 if and only if they are nonzero and one is a multiple of the other. One form of equality case for Cauchy-Schwarz. -/ lemma abs_real_inner_div_norm_mul_norm_eq_one_iff (x y : F) : |⟪x, y⟫_ℝ / (‖x‖ * ‖y‖)| = 1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r ≠ 0 ∧ y = r • x) := @norm_inner_div_norm_mul_norm_eq_one_iff ℝ F _ _ _ x y lemma inner_eq_norm_mul_iff_div {x y : E} (h₀ : x ≠ 0) : ⟪x, y⟫ = (‖x‖ : 𝕜) * ‖y‖ ↔ (‖y‖ / ‖x‖ : 𝕜) • x = y := begin have h₀' := h₀, rw [← norm_ne_zero_iff, ne.def, ← @of_real_eq_zero 𝕜] at h₀', split; intro h, { have : x = 0 ∨ y = (⟪x, y⟫ / ⟪x, x⟫ : 𝕜) • x := ((@norm_inner_eq_norm_tfae 𝕜 _ _ _ _ x y).out 0 1).1 (by simp [h]), rw [this.resolve_left h₀, h], simp [norm_smul, inner_self_norm_to_K, h₀'] }, { conv_lhs { rw [← h, inner_smul_right, inner_self_eq_norm_sq_to_K] }, field_simp [sq, mul_left_comm] } end /-- If the inner product of two vectors is equal to the product of their norms (i.e., `⟪x, y⟫ = ‖x‖ * ‖y‖`), then the two vectors are nonnegative real multiples of each other. One form of the equality case for Cauchy-Schwarz. Compare `norm_inner_eq_norm_iff`, which takes the weaker hypothesis `abs ⟪x, y⟫ = ‖x‖ * ‖y‖`. -/ lemma inner_eq_norm_mul_iff {x y : E} : ⟪x, y⟫ = (‖x‖ : 𝕜) * ‖y‖ ↔ (‖y‖ : 𝕜) • x = (‖x‖ : 𝕜) • y := begin rcases eq_or_ne x 0 with (rfl | h₀), { simp }, { rw [inner_eq_norm_mul_iff_div h₀, div_eq_inv_mul, mul_smul, inv_smul_eq_iff₀], rwa [ne.def, of_real_eq_zero, norm_eq_zero] }, end /-- If the inner product of two vectors is equal to the product of their norms (i.e., `⟪x, y⟫ = ‖x‖ * ‖y‖`), then the two vectors are nonnegative real multiples of each other. One form of the equality case for Cauchy-Schwarz. Compare `norm_inner_eq_norm_iff`, which takes the weaker hypothesis `abs ⟪x, y⟫ = ‖x‖ * ‖y‖`. -/ lemma inner_eq_norm_mul_iff_real {x y : F} : ⟪x, y⟫_ℝ = ‖x‖ * ‖y‖ ↔ ‖y‖ • x = ‖x‖ • y := inner_eq_norm_mul_iff /-- The inner product of two vectors, divided by the product of their norms, has value 1 if and only if they are nonzero and one is a positive multiple of the other. -/ lemma real_inner_div_norm_mul_norm_eq_one_iff (x y : F) : ⟪x, y⟫_ℝ / (‖x‖ * ‖y‖) = 1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), 0 < r ∧ y = r • x) := begin split, { intro h, have hx₀ : x ≠ 0 := λ h₀, by simpa [h₀] using h, have hy₀ : y ≠ 0 := λ h₀, by simpa [h₀] using h, refine ⟨hx₀, ‖y‖ / ‖x‖, div_pos (norm_pos_iff.2 hy₀) (norm_pos_iff.2 hx₀), _⟩, exact ((inner_eq_norm_mul_iff_div hx₀).1 (eq_of_div_eq_one h)).symm }, { rintro ⟨hx, ⟨r, ⟨hr, rfl⟩⟩⟩, exact real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul hx hr } end /-- The inner product of two vectors, divided by the product of their norms, has value -1 if and only if they are nonzero and one is a negative multiple of the other. -/ lemma real_inner_div_norm_mul_norm_eq_neg_one_iff (x y : F) : ⟪x, y⟫_ℝ / (‖x‖ * ‖y‖) = -1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r < 0 ∧ y = r • x) := begin rw [← neg_eq_iff_eq_neg, ← neg_div, ← inner_neg_right, ← norm_neg y, real_inner_div_norm_mul_norm_eq_one_iff, (@neg_surjective ℝ _).exists], refine iff.rfl.and (exists_congr $ λ r, _), rw [neg_pos, neg_smul, neg_inj] end /-- If the inner product of two unit vectors is `1`, then the two vectors are equal. One form of the equality case for Cauchy-Schwarz. -/ lemma inner_eq_one_iff_of_norm_one {x y : E} (hx : ‖x‖ = 1) (hy : ‖y‖ = 1) : ⟪x, y⟫ = 1 ↔ x = y := by { convert inner_eq_norm_mul_iff using 2; simp [hx, hy] } lemma inner_lt_norm_mul_iff_real {x y : F} : ⟪x, y⟫_ℝ < ‖x‖ * ‖y‖ ↔ ‖y‖ • x ≠ ‖x‖ • y := calc ⟪x, y⟫_ℝ < ‖x‖ * ‖y‖ ↔ ⟪x, y⟫_ℝ ≠ ‖x‖ * ‖y‖ : ⟨ne_of_lt, lt_of_le_of_ne (real_inner_le_norm _ _)⟩ ... ↔ ‖y‖ • x ≠ ‖x‖ • y : not_congr inner_eq_norm_mul_iff_real /-- If the inner product of two unit vectors is strictly less than `1`, then the two vectors are distinct. One form of the equality case for Cauchy-Schwarz. -/ lemma inner_lt_one_iff_real_of_norm_one {x y : F} (hx : ‖x‖ = 1) (hy : ‖y‖ = 1) : ⟪x, y⟫_ℝ < 1 ↔ x ≠ y := by { convert inner_lt_norm_mul_iff_real; simp [hx, hy] } /-- The inner product of two weighted sums, where the weights in each sum add to 0, in terms of the norms of pairwise differences. -/ lemma inner_sum_smul_sum_smul_of_sum_eq_zero {ι₁ : Type*} {s₁ : finset ι₁} {w₁ : ι₁ → ℝ} (v₁ : ι₁ → F) (h₁ : ∑ i in s₁, w₁ i = 0) {ι₂ : Type*} {s₂ : finset ι₂} {w₂ : ι₂ → ℝ} (v₂ : ι₂ → F) (h₂ : ∑ i in s₂, w₂ i = 0) : ⟪(∑ i₁ in s₁, w₁ i₁ • v₁ i₁), (∑ i₂ in s₂, w₂ i₂ • v₂ i₂)⟫_ℝ = (-∑ i₁ in s₁, ∑ i₂ in s₂, w₁ i₁ * w₂ i₂ * (‖v₁ i₁ - v₂ i₂‖ * ‖v₁ i₁ - v₂ i₂‖)) / 2 := by simp_rw [sum_inner, inner_sum, real_inner_smul_left, real_inner_smul_right, real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two, ←div_sub_div_same, ←div_add_div_same, mul_sub_left_distrib, left_distrib, finset.sum_sub_distrib, finset.sum_add_distrib, ←finset.mul_sum, ←finset.sum_mul, h₁, h₂, zero_mul, mul_zero, finset.sum_const_zero, zero_add, zero_sub, finset.mul_sum, neg_div, finset.sum_div, mul_div_assoc, mul_assoc] variables (𝕜) /-- The inner product as a sesquilinear map. -/ def innerₛₗ : E →ₗ⋆[𝕜] E →ₗ[𝕜] 𝕜 := linear_map.mk₂'ₛₗ _ _ (λ v w, ⟪v, w⟫) inner_add_left (λ _ _ _, inner_smul_left _ _ _) inner_add_right (λ _ _ _, inner_smul_right _ _ _) @[simp] lemma innerₛₗ_apply_coe (v : E) : ⇑(innerₛₗ 𝕜 v) = λ w, ⟪v, w⟫ := rfl @[simp] lemma innerₛₗ_apply (v w : E) : innerₛₗ 𝕜 v w = ⟪v, w⟫ := rfl /-- The inner product as a continuous sesquilinear map. Note that `to_dual_map` (resp. `to_dual`) in `inner_product_space.dual` is a version of this given as a linear isometry (resp. linear isometric equivalence). -/ def innerSL : E →L⋆[𝕜] E →L[𝕜] 𝕜 := linear_map.mk_continuous₂ (innerₛₗ 𝕜) 1 (λ x y, by simp only [norm_inner_le_norm, one_mul, innerₛₗ_apply]) @[simp] lemma innerSL_apply_coe (v : E) : ⇑(innerSL 𝕜 v) = λ w, ⟪v, w⟫ := rfl @[simp] lemma innerSL_apply (v w : E) : innerSL 𝕜 v w = ⟪v, w⟫ := rfl /-- `innerSL` is an isometry. Note that the associated `linear_isometry` is defined in `inner_product_space.dual` as `to_dual_map`. -/ @[simp] lemma innerSL_apply_norm (x : E) : ‖innerSL 𝕜 x‖ = ‖x‖ := begin refine le_antisymm ((innerSL 𝕜 x).op_norm_le_bound (norm_nonneg _) (λ y, norm_inner_le_norm _ _)) _, rcases eq_or_ne x 0 with (rfl | h), { simp }, { refine (mul_le_mul_right (norm_pos_iff.2 h)).mp _, calc ‖x‖ * ‖x‖ = ‖(⟪x, x⟫ : 𝕜)‖ : by rw [← sq, inner_self_eq_norm_sq_to_K, norm_pow, norm_of_real, abs_norm] ... ≤ ‖innerSL 𝕜 x‖ * ‖x‖ : (innerSL 𝕜 x).le_op_norm _ } end /-- The inner product as a continuous sesquilinear map, with the two arguments flipped. -/ def innerSL_flip : E →L[𝕜] E →L⋆[𝕜] 𝕜 := @continuous_linear_map.flipₗᵢ' 𝕜 𝕜 𝕜 E E 𝕜 _ _ _ _ _ _ _ _ _ (ring_hom.id 𝕜) (star_ring_end 𝕜) _ _ (innerSL 𝕜) @[simp] lemma innerSL_flip_apply (x y : E) : innerSL_flip 𝕜 x y = ⟪y, x⟫ := rfl variables {𝕜} namespace continuous_linear_map variables {E' : Type*} [normed_add_comm_group E'] [inner_product_space 𝕜 E'] /-- Given `f : E →L[𝕜] E'`, construct the continuous sesquilinear form `λ x y, ⟪x, A y⟫`, given as a continuous linear map. -/ def to_sesq_form : (E →L[𝕜] E') →L[𝕜] E' →L⋆[𝕜] E →L[𝕜] 𝕜 := ↑((continuous_linear_map.flipₗᵢ' E E' 𝕜 (star_ring_end 𝕜) (ring_hom.id 𝕜)).to_continuous_linear_equiv) ∘L (continuous_linear_map.compSL E E' (E' →L⋆[𝕜] 𝕜) (ring_hom.id 𝕜) (ring_hom.id 𝕜) (innerSL_flip 𝕜)) @[simp] lemma to_sesq_form_apply_coe (f : E →L[𝕜] E') (x : E') : to_sesq_form f x = (innerSL 𝕜 x).comp f := rfl lemma to_sesq_form_apply_norm_le {f : E →L[𝕜] E'} {v : E'} : ‖to_sesq_form f v‖ ≤ ‖f‖ * ‖v‖ := begin refine op_norm_le_bound _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) _, intro x, have h₁ : ‖f x‖ ≤ ‖f‖ * ‖x‖ := le_op_norm _ _, have h₂ := @norm_inner_le_norm 𝕜 E' _ _ _ v (f x), calc ‖⟪v, f x⟫‖ ≤ ‖v‖ * ‖f x‖ : h₂ ... ≤ ‖v‖ * (‖f‖ * ‖x‖) : mul_le_mul_of_nonneg_left h₁ (norm_nonneg v) ... = ‖f‖ * ‖v‖ * ‖x‖ : by ring, end end continuous_linear_map /-- When an inner product space `E` over `𝕜` is considered as a real normed space, its inner product satisfies `is_bounded_bilinear_map`. In order to state these results, we need a `normed_space ℝ E` instance. We will later establish such an instance by restriction-of-scalars, `inner_product_space.is_R_or_C_to_real 𝕜 E`, but this instance may be not definitionally equal to some other “natural” instance. So, we assume `[normed_space ℝ E]`. -/ lemma is_bounded_bilinear_map_inner [normed_space ℝ E] : is_bounded_bilinear_map ℝ (λ p : E × E, ⟪p.1, p.2⟫) := { add_left := inner_add_left, smul_left := λ r x y, by simp only [← algebra_map_smul 𝕜 r x, algebra_map_eq_of_real, inner_smul_real_left], add_right := inner_add_right, smul_right := λ r x y, by simp only [← algebra_map_smul 𝕜 r y, algebra_map_eq_of_real, inner_smul_real_right], bound := ⟨1, zero_lt_one, λ x y, by { rw [one_mul], exact norm_inner_le_norm x y, }⟩ } end norm section bessels_inequality variables {ι: Type*} (x : E) {v : ι → E} /-- Bessel's inequality for finite sums. -/ lemma orthonormal.sum_inner_products_le {s : finset ι} (hv : orthonormal 𝕜 v) : ∑ i in s, ‖⟪v i, x⟫‖ ^ 2 ≤ ‖x‖ ^ 2 := begin have h₂ : ∑ i in s, ∑ j in s, ⟪v i, x⟫ * ⟪x, v j⟫ * ⟪v j, v i⟫ = (∑ k in s, (⟪v k, x⟫ * ⟪x, v k⟫) : 𝕜), { exact hv.inner_left_right_finset }, have h₃ : ∀ z : 𝕜, re (z * conj (z)) = ‖z‖ ^ 2, { intro z, simp only [mul_conj, norm_sq_eq_def'], norm_cast, }, suffices hbf: ‖x - ∑ i in s, ⟪v i, x⟫ • (v i)‖ ^ 2 = ‖x‖ ^ 2 - ∑ i in s, ‖⟪v i, x⟫‖ ^ 2, { rw [←sub_nonneg, ←hbf], simp only [norm_nonneg, pow_nonneg], }, rw [@norm_sub_sq 𝕜, sub_add], simp only [@inner_product_space.norm_sq_eq_inner 𝕜, inner_sum], simp only [sum_inner, two_mul, inner_smul_right, inner_conj_symm, ←mul_assoc, h₂, ←h₃, inner_conj_symm, add_monoid_hom.map_sum, finset.mul_sum, ←finset.sum_sub_distrib, inner_smul_left, add_sub_cancel'], end /-- Bessel's inequality. -/ lemma orthonormal.tsum_inner_products_le (hv : orthonormal 𝕜 v) : ∑' i, ‖⟪v i, x⟫‖ ^ 2 ≤ ‖x‖ ^ 2 := begin refine tsum_le_of_sum_le' _ (λ s, hv.sum_inner_products_le x), simp only [norm_nonneg, pow_nonneg] end /-- The sum defined in Bessel's inequality is summable. -/ lemma orthonormal.inner_products_summable (hv : orthonormal 𝕜 v) : summable (λ i, ‖⟪v i, x⟫‖ ^ 2) := begin use ⨆ s : finset ι, ∑ i in s, ‖⟪v i, x⟫‖ ^ 2, apply has_sum_of_is_lub_of_nonneg, { intro b, simp only [norm_nonneg, pow_nonneg], }, { refine is_lub_csupr _, use ‖x‖ ^ 2, rintro y ⟨s, rfl⟩, exact hv.sum_inner_products_le x } end end bessels_inequality /-- A field `𝕜` satisfying `is_R_or_C` is itself a `𝕜`-inner product space. -/ instance is_R_or_C.inner_product_space : inner_product_space 𝕜 𝕜 := { inner := λ x y, conj x * y, norm_sq_eq_inner := λ x, by { unfold inner, rw [mul_comm, mul_conj, of_real_re, norm_sq_eq_def'] }, conj_symm := λ x y, by simp only [mul_comm, map_mul, star_ring_end_self_apply], add_left := λ x y z, by simp only [add_mul, map_add], smul_left := λ x y z, by simp only [mul_assoc, smul_eq_mul, map_mul] } @[simp] lemma is_R_or_C.inner_apply (x y : 𝕜) : ⟪x, y⟫ = (conj x) * y := rfl /-! ### Inner product space structure on subspaces -/ /-- Induced inner product on a submodule. -/ instance submodule.inner_product_space (W : submodule 𝕜 E) : inner_product_space 𝕜 W := { inner := λ x y, ⟪(x:E), (y:E)⟫, conj_symm := λ _ _, inner_conj_symm _ _, norm_sq_eq_inner := λ x, norm_sq_eq_inner (x : E), add_left := λ _ _ _, inner_add_left _ _ _, smul_left := λ _ _ _, inner_smul_left _ _ _, ..submodule.normed_space W } /-- The inner product on submodules is the same as on the ambient space. -/ @[simp] lemma submodule.coe_inner (W : submodule 𝕜 E) (x y : W) : ⟪x, y⟫ = ⟪(x:E), ↑y⟫ := rfl lemma orthonormal.cod_restrict {ι : Type*} {v : ι → E} (hv : orthonormal 𝕜 v) (s : submodule 𝕜 E) (hvs : ∀ i, v i ∈ s) : @orthonormal 𝕜 s _ _ _ ι (set.cod_restrict v s hvs) := s.subtypeₗᵢ.orthonormal_comp_iff.mp hv lemma orthonormal_span {ι : Type*} {v : ι → E} (hv : orthonormal 𝕜 v) : @orthonormal 𝕜 (submodule.span 𝕜 (set.range v)) _ _ _ ι (λ i : ι, ⟨v i, submodule.subset_span (set.mem_range_self i)⟩) := hv.cod_restrict (submodule.span 𝕜 (set.range v)) (λ i, submodule.subset_span (set.mem_range_self i)) /-! ### Families of mutually-orthogonal subspaces of an inner product space -/ section orthogonal_family variables {ι : Type*} [dec_ι : decidable_eq ι] (𝕜) open_locale direct_sum /-- An indexed family of mutually-orthogonal subspaces of an inner product space `E`. The simple way to express this concept would be as a condition on `V : ι → submodule 𝕜 E`. We We instead implement it as a condition on a family of inner product spaces each equipped with an isometric embedding into `E`, thus making it a property of morphisms rather than subobjects. The connection to the subobject spelling is shown in `orthogonal_family_iff_pairwise`. This definition is less lightweight, but allows for better definitional properties when the inner product space structure on each of the submodules is important -- for example, when considering their Hilbert sum (`pi_lp V 2`). For example, given an orthonormal set of vectors `v : ι → E`, we have an associated orthogonal family of one-dimensional subspaces of `E`, which it is convenient to be able to discuss using `ι → 𝕜` rather than `Π i : ι, span 𝕜 (v i)`. -/ def orthogonal_family (G : ι → Type*) [Π i, normed_add_comm_group (G i)] [Π i, inner_product_space 𝕜 (G i)] (V : Π i, G i →ₗᵢ[𝕜] E) : Prop := ∀ ⦃i j⦄, i ≠ j → ∀ v : G i, ∀ w : G j, ⟪V i v, V j w⟫ = 0 variables {𝕜} {G : ι → Type*} [Π i, normed_add_comm_group (G i)] [Π i, inner_product_space 𝕜 (G i)] {V : Π i, G i →ₗᵢ[𝕜] E} (hV : orthogonal_family 𝕜 G V) [dec_V : Π i (x : G i), decidable (x ≠ 0)] lemma orthonormal.orthogonal_family {v : ι → E} (hv : orthonormal 𝕜 v) : orthogonal_family 𝕜 (λ i : ι, 𝕜) (λ i, linear_isometry.to_span_singleton 𝕜 E (hv.1 i)) := λ i j hij a b, by simp [inner_smul_left, inner_smul_right, hv.2 hij] include hV dec_ι lemma orthogonal_family.eq_ite {i j : ι} (v : G i) (w : G j) : ⟪V i v, V j w⟫ = ite (i = j) ⟪V i v, V j w⟫ 0 := begin split_ifs, { refl }, { exact hV h v w } end include dec_V lemma orthogonal_family.inner_right_dfinsupp (l : ⨁ i, G i) (i : ι) (v : G i) : ⟪V i v, l.sum (λ j, V j)⟫ = ⟪v, l i⟫ := calc ⟪V i v, l.sum (λ j, V j)⟫ = l.sum (λ j, λ w, ⟪V i v, V j w⟫) : dfinsupp.inner_sum (λ j, V j) l (V i v) ... = l.sum (λ j, λ w, ite (i=j) ⟪V i v, V j w⟫ 0) : congr_arg l.sum $ funext $ λ j, funext $ hV.eq_ite v ... = ⟪v, l i⟫ : begin simp only [dfinsupp.sum, submodule.coe_inner, finset.sum_ite_eq, ite_eq_left_iff, dfinsupp.mem_support_to_fun], split_ifs with h h, { simp only [linear_isometry.inner_map_map] }, { simp only [of_not_not h, inner_zero_right] }, end omit dec_ι dec_V lemma orthogonal_family.inner_right_fintype [fintype ι] (l : Π i, G i) (i : ι) (v : G i) : ⟪V i v, ∑ j : ι, V j (l j)⟫ = ⟪v, l i⟫ := by classical; calc ⟪V i v, ∑ j : ι, V j (l j)⟫ = ∑ j : ι, ⟪V i v, V j (l j)⟫: by rw inner_sum ... = ∑ j, ite (i = j) ⟪V i v, V j (l j)⟫ 0 : congr_arg (finset.sum finset.univ) $ funext $ λ j, (hV.eq_ite v (l j)) ... = ⟪v, l i⟫ : by simp only [finset.sum_ite_eq, finset.mem_univ, (V i).inner_map_map, if_true] lemma orthogonal_family.inner_sum (l₁ l₂ : Π i, G i) (s : finset ι) : ⟪∑ i in s, V i (l₁ i), ∑ j in s, V j (l₂ j)⟫ = ∑ i in s, ⟪l₁ i, l₂ i⟫ := by classical; calc ⟪∑ i in s, V i (l₁ i), ∑ j in s, V j (l₂ j)⟫ = ∑ j in s, ∑ i in s, ⟪V i (l₁ i), V j (l₂ j)⟫ : by simp only [sum_inner, inner_sum] ... = ∑ j in s, ∑ i in s, ite (i = j) ⟪V i (l₁ i), V j (l₂ j)⟫ 0 : begin congr' with i, congr' with j, apply hV.eq_ite, end ... = ∑ i in s, ⟪l₁ i, l₂ i⟫ : by simp only [finset.sum_ite_of_true, finset.sum_ite_eq', linear_isometry.inner_map_map, imp_self, implies_true_iff] lemma orthogonal_family.norm_sum (l : Π i, G i) (s : finset ι) : ‖∑ i in s, V i (l i)‖ ^ 2 = ∑ i in s, ‖l i‖ ^ 2 := begin have : (‖∑ i in s, V i (l i)‖ ^ 2 : 𝕜) = ∑ i in s, ‖l i‖ ^ 2, { simp only [← inner_self_eq_norm_sq_to_K, hV.inner_sum] }, exact_mod_cast this, end /-- The composition of an orthogonal family of subspaces with an injective function is also an orthogonal family. -/ lemma orthogonal_family.comp {γ : Type*} {f : γ → ι} (hf : function.injective f) : orthogonal_family 𝕜 (λ g, G (f g)) (λ g, V (f g)) := λ i j hij v w, hV (hf.ne hij) v w lemma orthogonal_family.orthonormal_sigma_orthonormal {α : ι → Type*} {v_family : Π i, (α i) → G i} (hv_family : ∀ i, orthonormal 𝕜 (v_family i)) : orthonormal 𝕜 (λ a : Σ i, α i, V a.1 (v_family a.1 a.2)) := begin split, { rintros ⟨i, v⟩, simpa only [linear_isometry.norm_map] using (hv_family i).left v }, rintros ⟨i, v⟩ ⟨j, w⟩ hvw, by_cases hij : i = j, { subst hij, have : v ≠ w := λ h, by { subst h, exact hvw rfl }, simpa only [linear_isometry.inner_map_map] using (hv_family i).2 this }, { exact hV hij (v_family i v) (v_family j w) } end include dec_ι lemma orthogonal_family.norm_sq_diff_sum (f : Π i, G i) (s₁ s₂ : finset ι) : ‖∑ i in s₁, V i (f i) - ∑ i in s₂, V i (f i)‖ ^ 2 = ∑ i in s₁ \ s₂, ‖f i‖ ^ 2 + ∑ i in s₂ \ s₁, ‖f i‖ ^ 2 := begin rw [← finset.sum_sdiff_sub_sum_sdiff, sub_eq_add_neg, ← finset.sum_neg_distrib], let F : Π i, G i := λ i, if i ∈ s₁ then f i else - (f i), have hF₁ : ∀ i ∈ s₁ \ s₂, F i = f i := λ i hi, if_pos (finset.sdiff_subset _ _ hi), have hF₂ : ∀ i ∈ s₂ \ s₁, F i = - f i := λ i hi, if_neg (finset.mem_sdiff.mp hi).2, have hF : ∀ i, ‖F i‖ = ‖f i‖, { intros i, dsimp only [F], split_ifs; simp only [eq_self_iff_true, norm_neg], }, have : ‖∑ i in s₁ \ s₂, V i (F i) + ∑ i in s₂ \ s₁, V i (F i)‖ ^ 2 = ∑ i in s₁ \ s₂, ‖F i‖ ^ 2 + ∑ i in s₂ \ s₁, ‖F i‖ ^ 2, { have hs : disjoint (s₁ \ s₂) (s₂ \ s₁) := disjoint_sdiff_sdiff, simpa only [finset.sum_union hs] using hV.norm_sum F (s₁ \ s₂ ∪ s₂ \ s₁) }, convert this using 4, { refine finset.sum_congr rfl (λ i hi, _), simp only [hF₁ i hi] }, { refine finset.sum_congr rfl (λ i hi, _), simp only [hF₂ i hi, linear_isometry.map_neg] }, { simp only [hF] }, { simp only [hF] }, end omit dec_ι /-- A family `f` of mutually-orthogonal elements of `E` is summable, if and only if `(λ i, ‖f i‖ ^ 2)` is summable. -/ lemma orthogonal_family.summable_iff_norm_sq_summable [complete_space E] (f : Π i, G i) : summable (λ i, V i (f i)) ↔ summable (λ i, ‖f i‖ ^ 2) := begin classical, simp only [summable_iff_cauchy_seq_finset, normed_add_comm_group.cauchy_seq_iff, real.norm_eq_abs], split, { intros hf ε hε, obtain ⟨a, H⟩ := hf _ (sqrt_pos.mpr hε), use a, intros s₁ hs₁ s₂ hs₂, rw ← finset.sum_sdiff_sub_sum_sdiff, refine (abs_sub _ _).trans_lt _, have : ∀ i, 0 ≤ ‖f i‖ ^ 2 := λ i : ι, sq_nonneg _, simp only [finset.abs_sum_of_nonneg' this], have : ∑ i in s₁ \ s₂, ‖f i‖ ^ 2 + ∑ i in s₂ \ s₁, ‖f i‖ ^ 2 < (sqrt ε) ^ 2, { rw [← hV.norm_sq_diff_sum, sq_lt_sq, abs_of_nonneg (sqrt_nonneg _), abs_of_nonneg (norm_nonneg _)], exact H s₁ hs₁ s₂ hs₂ }, have hη := sq_sqrt (le_of_lt hε), linarith }, { intros hf ε hε, have hε' : 0 < ε ^ 2 / 2 := half_pos (sq_pos_of_pos hε), obtain ⟨a, H⟩ := hf _ hε', use a, intros s₁ hs₁ s₂ hs₂, refine (abs_lt_of_sq_lt_sq' _ (le_of_lt hε)).2, have has : a ≤ s₁ ⊓ s₂ := le_inf hs₁ hs₂, rw hV.norm_sq_diff_sum, have Hs₁ : ∑ (x : ι) in s₁ \ s₂, ‖f x‖ ^ 2 < ε ^ 2 / 2, { convert H _ hs₁ _ has, have : s₁ ⊓ s₂ ⊆ s₁ := finset.inter_subset_left _ _, rw [← finset.sum_sdiff this, add_tsub_cancel_right, finset.abs_sum_of_nonneg'], { simp }, { exact λ i, sq_nonneg _ } }, have Hs₂ : ∑ (x : ι) in s₂ \ s₁, ‖f x‖ ^ 2 < ε ^ 2 /2, { convert H _ hs₂ _ has, have : s₁ ⊓ s₂ ⊆ s₂ := finset.inter_subset_right _ _, rw [← finset.sum_sdiff this, add_tsub_cancel_right, finset.abs_sum_of_nonneg'], { simp }, { exact λ i, sq_nonneg _ } }, linarith }, end omit hV /-- An orthogonal family forms an independent family of subspaces; that is, any collection of elements each from a different subspace in the family is linearly independent. In particular, the pairwise intersections of elements of the family are 0. -/ lemma orthogonal_family.independent {V : ι → submodule 𝕜 E} (hV : orthogonal_family 𝕜 (λ i, V i) (λ i, (V i).subtypeₗᵢ)) : complete_lattice.independent V := begin classical, apply complete_lattice.independent_of_dfinsupp_lsum_injective, rw [← @linear_map.ker_eq_bot _ _ _ _ _ _ (direct_sum.add_comm_group (λ i, V i)), submodule.eq_bot_iff], intros v hv, rw linear_map.mem_ker at hv, ext i, suffices : ⟪(v i : E), v i⟫ = 0, { simpa only [inner_self_eq_zero] using this }, calc ⟪(v i : E), v i⟫ = ⟪(v i : E), dfinsupp.lsum ℕ (λ i, (V i).subtype) v⟫ : by simpa only [dfinsupp.sum_add_hom_apply, dfinsupp.lsum_apply_apply] using (hV.inner_right_dfinsupp v i (v i)).symm ... = 0 : by simp only [hv, inner_zero_right], end include dec_ι lemma direct_sum.is_internal.collected_basis_orthonormal {V : ι → submodule 𝕜 E} (hV : orthogonal_family 𝕜 (λ i, V i) (λ i, (V i).subtypeₗᵢ)) (hV_sum : direct_sum.is_internal (λ i, V i)) {α : ι → Type*} {v_family : Π i, basis (α i) 𝕜 (V i)} (hv_family : ∀ i, orthonormal 𝕜 (v_family i)) : orthonormal 𝕜 (hV_sum.collected_basis v_family) := by simpa only [hV_sum.collected_basis_coe] using hV.orthonormal_sigma_orthonormal hv_family end orthogonal_family section is_R_or_C_to_real variables {G : Type*} variables (𝕜 E) include 𝕜 /-- A general inner product implies a real inner product. This is not registered as an instance since it creates problems with the case `𝕜 = ℝ`. -/ def has_inner.is_R_or_C_to_real : has_inner ℝ E := { inner := λ x y, re ⟪x, y⟫ } /-- A general inner product space structure implies a real inner product structure. This is not registered as an instance since it creates problems with the case `𝕜 = ℝ`, but in can be used in a proof to obtain a real inner product space structure from a given `𝕜`-inner product space structure. -/ def inner_product_space.is_R_or_C_to_real : inner_product_space ℝ E := { norm_sq_eq_inner := norm_sq_eq_inner, conj_symm := λ x y, inner_re_symm _ _, add_left := λ x y z, by { change re ⟪x + y, z⟫ = re ⟪x, z⟫ + re ⟪y, z⟫, simp only [inner_add_left, map_add] }, smul_left := λ x y r, by { change re ⟪(r : 𝕜) • x, y⟫ = r * re ⟪x, y⟫, simp only [inner_smul_left, conj_of_real, of_real_mul_re] }, ..has_inner.is_R_or_C_to_real 𝕜 E, ..normed_space.restrict_scalars ℝ 𝕜 E } variable {E} lemma real_inner_eq_re_inner (x y : E) : @has_inner.inner ℝ E (has_inner.is_R_or_C_to_real 𝕜 E) x y = re ⟪x, y⟫ := rfl lemma real_inner_I_smul_self (x : E) : @has_inner.inner ℝ E (has_inner.is_R_or_C_to_real 𝕜 E) x ((I : 𝕜) • x) = 0 := by simp [real_inner_eq_re_inner, inner_smul_right] omit 𝕜 /-- A complex inner product implies a real inner product -/ instance inner_product_space.complex_to_real [normed_add_comm_group G] [inner_product_space ℂ G] : inner_product_space ℝ G := inner_product_space.is_R_or_C_to_real ℂ G @[simp] protected lemma complex.inner (w z : ℂ) : ⟪w, z⟫_ℝ = (conj w * z).re := rfl /-- The inner product on an inner product space of dimension 2 can be evaluated in terms of a complex-number representation of the space. -/ lemma inner_map_complex [normed_add_comm_group G] [inner_product_space ℝ G] (f : G ≃ₗᵢ[ℝ] ℂ) (x y : G) : ⟪x, y⟫_ℝ = (conj (f x) * f y).re := by rw [← complex.inner, f.inner_map_map] end is_R_or_C_to_real section continuous /-! ### Continuity of the inner product -/ lemma continuous_inner : continuous (λ p : E × E, ⟪p.1, p.2⟫) := begin letI : inner_product_space ℝ E := inner_product_space.is_R_or_C_to_real 𝕜 E, exact is_bounded_bilinear_map_inner.continuous end variables {α : Type*} lemma filter.tendsto.inner {f g : α → E} {l : filter α} {x y : E} (hf : tendsto f l (𝓝 x)) (hg : tendsto g l (𝓝 y)) : tendsto (λ t, ⟪f t, g t⟫) l (𝓝 ⟪x, y⟫) := (continuous_inner.tendsto _).comp (hf.prod_mk_nhds hg) variables [topological_space α] {f g : α → E} {x : α} {s : set α} include 𝕜 lemma continuous_within_at.inner (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (λ t, ⟪f t, g t⟫) s x := hf.inner hg lemma continuous_at.inner (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λ t, ⟪f t, g t⟫) x := hf.inner hg lemma continuous_on.inner (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λ t, ⟪f t, g t⟫) s := λ x hx, (hf x hx).inner (hg x hx) @[continuity] lemma continuous.inner (hf : continuous f) (hg : continuous g) : continuous (λ t, ⟪f t, g t⟫) := continuous_iff_continuous_at.2 $ λ x, hf.continuous_at.inner hg.continuous_at end continuous section re_apply_inner_self /-- Extract a real bilinear form from an operator `T`, by taking the pairing `λ x, re ⟪T x, x⟫`. -/ def continuous_linear_map.re_apply_inner_self (T : E →L[𝕜] E) (x : E) : ℝ := re ⟪T x, x⟫ lemma continuous_linear_map.re_apply_inner_self_apply (T : E →L[𝕜] E) (x : E) : T.re_apply_inner_self x = re ⟪T x, x⟫ := rfl lemma continuous_linear_map.re_apply_inner_self_continuous (T : E →L[𝕜] E) : continuous T.re_apply_inner_self := re_clm.continuous.comp $ T.continuous.inner continuous_id lemma continuous_linear_map.re_apply_inner_self_smul (T : E →L[𝕜] E) (x : E) {c : 𝕜} : T.re_apply_inner_self (c • x) = ‖c‖ ^ 2 * T.re_apply_inner_self x := by simp only [continuous_linear_map.map_smul, continuous_linear_map.re_apply_inner_self_apply, inner_smul_left, inner_smul_right, ← mul_assoc, mul_conj, norm_sq_eq_def', ← smul_re, algebra.smul_def (‖c‖ ^ 2) ⟪T x, x⟫, algebra_map_eq_of_real] end re_apply_inner_self namespace uniform_space.completion open uniform_space function instance {𝕜' E' : Type*} [topological_space 𝕜'] [uniform_space E'] [has_inner 𝕜' E'] : has_inner 𝕜' (completion E') := { inner := curry $ (dense_inducing_coe.prod dense_inducing_coe).extend (uncurry inner) } @[simp] lemma inner_coe (a b : E) : inner (a : completion E) (b : completion E) = (inner a b : 𝕜) := (dense_inducing_coe.prod dense_inducing_coe).extend_eq (continuous_inner : continuous (uncurry inner : E × E → 𝕜)) (a, b) protected lemma continuous_inner : continuous (uncurry inner : completion E × completion E → 𝕜) := begin let inner' : E →+ E →+ 𝕜 := { to_fun := λ x, (innerₛₗ 𝕜 x).to_add_monoid_hom, map_zero' := by ext x; exact inner_zero_left _, map_add' := λ x y, by ext z; exact inner_add_left _ _ _ }, have : continuous (λ p : E × E, inner' p.1 p.2) := continuous_inner, rw [completion.has_inner, uncurry_curry _], change continuous (((dense_inducing_to_compl E).prod (dense_inducing_to_compl E)).extend (λ p : E × E, inner' p.1 p.2)), exact (dense_inducing_to_compl E).extend_Z_bilin (dense_inducing_to_compl E) this, end protected lemma continuous.inner {α : Type*} [topological_space α] {f g : α → completion E} (hf : continuous f) (hg : continuous g) : continuous (λ x : α, inner (f x) (g x) : α → 𝕜) := uniform_space.completion.continuous_inner.comp (hf.prod_mk hg : _) instance : inner_product_space 𝕜 (completion E) := { norm_sq_eq_inner := λ x, completion.induction_on x (is_closed_eq (continuous_norm.pow 2) (continuous_re.comp (continuous.inner continuous_id' continuous_id'))) (λ a, by simp only [norm_coe, inner_coe, inner_self_eq_norm_sq]), conj_symm := λ x y, completion.induction_on₂ x y (is_closed_eq (continuous_conj.comp (continuous.inner continuous_snd continuous_fst)) (continuous.inner continuous_fst continuous_snd)) (λ a b, by simp only [inner_coe, inner_conj_symm]), add_left := λ x y z, completion.induction_on₃ x y z (is_closed_eq (continuous.inner (continuous_fst.add (continuous_fst.comp continuous_snd)) (continuous_snd.comp continuous_snd)) ((continuous.inner continuous_fst (continuous_snd.comp continuous_snd)).add (continuous.inner (continuous_fst.comp continuous_snd) (continuous_snd.comp continuous_snd)))) (λ a b c, by simp only [← coe_add, inner_coe, inner_add_left]), smul_left := λ x y c, completion.induction_on₂ x y (is_closed_eq (continuous.inner (continuous_fst.const_smul c) continuous_snd) ((continuous_mul_left _).comp (continuous.inner continuous_fst continuous_snd))) (λ a b, by simp only [← coe_smul c a, inner_coe, inner_smul_left]) } end uniform_space.completion
44234b1d8c45b54953fb5a9266a6ad2fe4b7d444
17d3c61bf162bf88be633867ed4cb201378a8769
/tests/lean/run/simp_partial_app.lean
20aba2bc57346a25d8a58d22f13d38640fc2af34
[ "Apache-2.0" ]
permissive
u20024804/lean
11def01468fb4796fb0da76015855adceac7e311
d315e424ff17faf6fe096a0a1407b70193009726
refs/heads/master
1,611,388,567,561
1,485,836,506,000
1,485,836,625,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
684
lean
open tactic meta def check_expr (p : pexpr) (t : expr) : tactic unit := do e ← to_expr p, guard (expr.alpha_eqv t e) meta def check_target (p : pexpr) : tactic unit := do t ← target, check_expr p t example (a : list nat) : a = [1, 2] → a^.for nat.succ = [2, 3] := begin intros, simp [list.for, flip], check_target `(list.map nat.succ a = [2, 3]), subst a, simp [list.map], check_target `([nat.succ 1, nat.succ 2] = [2, 3]), reflexivity end constant f {α : Type} [has_zero α] (a b : α) : a ≠ 0 → b ≠ 0 → α axiom fax {α : Type} [has_zero α] (a : α) : f a = λ b h₁ h₂, a lemma ex : f 1 2 dec_trivial dec_trivial = 1 := begin simp [fax] end
44255f533710909c63d05f9cee9d2d902dcd403c
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/tests/lean/notation.lean
e8789e886530372bc99ff9faa2f3e3c60d6713c4
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
395
lean
import logic data.num data.nat.basic open num constant b : num check b + b + b check true ∧ false ∧ true check (true ∧ false) ∧ true check 2 + (2 + 2) check (2 + 2) + 2 check 1 = (2 + 3)*2 check 2 + 3 * 2 = 3 * 2 + 2 check (true ∨ false) = (true ∨ false) ∧ true check true ∧ (false ∨ true) constant A : Type₁ constant a : A notation 1 := a check a open nat check ℕ → ℕ
2d4791d7d2ce76fde214a6eb04c364c862589a18
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/instances/int.lean
7805d4cb8029c02f928b01bdab806583180653f2
[ "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,399
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import data.int.interval import topology.metric_space.basic import order.filter.archimedean /-! # Topology on the integers > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The structure of a metric space on `ℤ` is introduced in this file, induced from `ℝ`. -/ noncomputable theory open metric set filter namespace int instance : has_dist ℤ := ⟨λ x y, dist (x : ℝ) y⟩ theorem dist_eq (x y : ℤ) : dist x y = |x - y| := rfl @[norm_cast, simp] theorem dist_cast_real (x y : ℤ) : dist (x : ℝ) y = dist x y := rfl lemma pairwise_one_le_dist : pairwise (λ m n : ℤ, 1 ≤ dist m n) := begin intros m n hne, rw dist_eq, norm_cast, rwa [← zero_add (1 : ℤ), int.add_one_le_iff, abs_pos, sub_ne_zero] end lemma uniform_embedding_coe_real : uniform_embedding (coe : ℤ → ℝ) := uniform_embedding_bot_of_pairwise_le_dist zero_lt_one pairwise_one_le_dist lemma closed_embedding_coe_real : closed_embedding (coe : ℤ → ℝ) := closed_embedding_of_pairwise_le_dist zero_lt_one pairwise_one_le_dist instance : metric_space ℤ := int.uniform_embedding_coe_real.comap_metric_space _ theorem preimage_ball (x : ℤ) (r : ℝ) : coe ⁻¹' (ball (x : ℝ) r) = ball x r := rfl theorem preimage_closed_ball (x : ℤ) (r : ℝ) : coe ⁻¹' (closed_ball (x : ℝ) r) = closed_ball x r := rfl theorem ball_eq_Ioo (x : ℤ) (r : ℝ) : ball x r = Ioo ⌊↑x - r⌋ ⌈↑x + r⌉ := by rw [← preimage_ball, real.ball_eq_Ioo, preimage_Ioo] theorem closed_ball_eq_Icc (x : ℤ) (r : ℝ) : closed_ball x r = Icc ⌈↑x - r⌉ ⌊↑x + r⌋ := by rw [← preimage_closed_ball, real.closed_ball_eq_Icc, preimage_Icc] instance : proper_space ℤ := ⟨ begin intros x r, rw closed_ball_eq_Icc, exact (set.finite_Icc _ _).is_compact, end ⟩ @[simp] lemma cocompact_eq : cocompact ℤ = at_bot ⊔ at_top := by simp only [← comap_dist_right_at_top_eq_cocompact (0 : ℤ), dist_eq, sub_zero, cast_zero, ← cast_abs, ← @comap_comap _ _ _ _ abs, int.comap_coe_at_top, comap_abs_at_top] @[simp] lemma cofinite_eq : (cofinite : filter ℤ) = at_bot ⊔ at_top := by rw [← cocompact_eq_cofinite, cocompact_eq] end int
31114f0f8a69302176f95adbc5fa69e4cf03d81d
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/group_theory/perm/support.lean
a3b7f2979a7322a92478053cb207a4bd5ccfb6e6
[ "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
18,957
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Aaron Anderson, Yakov Pechersky -/ import data.finset.sort import data.fintype.basic import group_theory.perm.basic /-! # Support of a permutation ## Main definitions In the following, `f g : equiv.perm α`. * `equiv.perm.disjoint`: two permutations `f` and `g` are `disjoint` if every element is fixed either by `f`, or by `g`. Equivalently, `f` and `g` are `disjoint` iff their `support` are disjoint. * `equiv.perm.is_swap`: `f = swap x y` for `x ≠ y`. * `equiv.perm.support`: the elements `x : α` that are not fixed by `f`. -/ open equiv finset namespace equiv.perm variables {α : Type*} section disjoint /-- Two permutations `f` and `g` are `disjoint` if their supports are disjoint, i.e., every element is fixed either by `f`, or by `g`. -/ def disjoint (f g : perm α) := ∀ x, f x = x ∨ g x = x variables {f g h : perm α} @[symm] lemma disjoint.symm : disjoint f g → disjoint g f := by simp only [disjoint, or.comm, imp_self] lemma disjoint.symmetric : symmetric (@disjoint α) := λ _ _, disjoint.symm lemma disjoint_comm : disjoint f g ↔ disjoint g f := ⟨disjoint.symm, disjoint.symm⟩ lemma disjoint.commute (h : disjoint f g) : commute f g := equiv.ext $ λ x, (h x).elim (λ hf, (h (g x)).elim (λ hg, by simp [mul_apply, hf, hg]) (λ hg, by simp [mul_apply, hf, g.injective hg])) (λ hg, (h (f x)).elim (λ hf, by simp [mul_apply, f.injective hf, hg]) (λ hf, by simp [mul_apply, hf, hg])) @[simp] lemma disjoint_one_left (f : perm α) : disjoint 1 f := λ _, or.inl rfl @[simp] lemma disjoint_one_right (f : perm α) : disjoint f 1 := λ _, or.inr rfl lemma disjoint_iff_eq_or_eq : disjoint f g ↔ ∀ (x : α), f x = x ∨ g x = x := iff.rfl @[simp] lemma disjoint_refl_iff : disjoint f f ↔ f = 1 := begin refine ⟨λ h, _, λ h, h.symm ▸ disjoint_one_left 1⟩, ext x, cases h x with hx hx; simp [hx] end lemma disjoint.inv_left (h : disjoint f g) : disjoint f⁻¹ g := begin intro x, rw [inv_eq_iff_eq, eq_comm], exact h x end lemma disjoint.inv_right (h : disjoint f g) : disjoint f g⁻¹ := h.symm.inv_left.symm @[simp] lemma disjoint_inv_left_iff : disjoint f⁻¹ g ↔ disjoint f g := begin refine ⟨λ h, _, disjoint.inv_left⟩, convert h.inv_left, exact (inv_inv _).symm end @[simp] lemma disjoint_inv_right_iff : disjoint f g⁻¹ ↔ disjoint f g := by rw [disjoint_comm, disjoint_inv_left_iff, disjoint_comm] lemma disjoint.mul_left (H1 : disjoint f h) (H2 : disjoint g h) : disjoint (f * g) h := λ x, by cases H1 x; cases H2 x; simp * lemma disjoint.mul_right (H1 : disjoint f g) (H2 : disjoint f h) : disjoint f (g * h) := by { rw disjoint_comm, exact H1.symm.mul_left H2.symm } lemma disjoint_prod_right (l : list (perm α)) (h : ∀ g ∈ l, disjoint f g) : disjoint f l.prod := begin induction l with g l ih, { exact disjoint_one_right _ }, { rw list.prod_cons, exact (h _ (list.mem_cons_self _ _)).mul_right (ih (λ g hg, h g (list.mem_cons_of_mem _ hg))) } end lemma disjoint_prod_perm {l₁ l₂ : list (perm α)} (hl : l₁.pairwise disjoint) (hp : l₁ ~ l₂) : l₁.prod = l₂.prod := hp.prod_eq' $ hl.imp $ λ f g, disjoint.commute lemma nodup_of_pairwise_disjoint {l : list (perm α)} (h1 : (1 : perm α) ∉ l) (h2 : l.pairwise disjoint) : l.nodup := begin refine list.pairwise.imp_of_mem _ h2, rintros σ - h_mem - h_disjoint rfl, suffices : σ = 1, { rw this at h_mem, exact h1 h_mem }, exact ext (λ a, (or_self _).mp (h_disjoint a)), end lemma pow_apply_eq_self_of_apply_eq_self {x : α} (hfx : f x = x) : ∀ n : ℕ, (f ^ n) x = x | 0 := rfl | (n+1) := by rw [pow_succ', mul_apply, hfx, pow_apply_eq_self_of_apply_eq_self] lemma gpow_apply_eq_self_of_apply_eq_self {x : α} (hfx : f x = x) : ∀ n : ℤ, (f ^ n) x = x | (n : ℕ) := pow_apply_eq_self_of_apply_eq_self hfx n | -[1+ n] := by rw [gpow_neg_succ_of_nat, inv_eq_iff_eq, pow_apply_eq_self_of_apply_eq_self hfx] lemma pow_apply_eq_of_apply_apply_eq_self {x : α} (hffx : f (f x) = x) : ∀ n : ℕ, (f ^ n) x = x ∨ (f ^ n) x = f x | 0 := or.inl rfl | (n+1) := (pow_apply_eq_of_apply_apply_eq_self n).elim (λ h, or.inr (by rw [pow_succ, mul_apply, h])) (λ h, or.inl (by rw [pow_succ, mul_apply, h, hffx])) lemma gpow_apply_eq_of_apply_apply_eq_self {x : α} (hffx : f (f x) = x) : ∀ i : ℤ, (f ^ i) x = x ∨ (f ^ i) x = f x | (n : ℕ) := pow_apply_eq_of_apply_apply_eq_self hffx n | -[1+ n] := by { rw [gpow_neg_succ_of_nat, inv_eq_iff_eq, ← f.injective.eq_iff, ← mul_apply, ← pow_succ, eq_comm, inv_eq_iff_eq, ← mul_apply, ← pow_succ', @eq_comm _ x, or.comm], exact pow_apply_eq_of_apply_apply_eq_self hffx _ } lemma disjoint.mul_apply_eq_iff {σ τ : perm α} (hστ : disjoint σ τ) {a : α} : (σ * τ) a = a ↔ σ a = a ∧ τ a = a := begin refine ⟨λ h, _, λ h, by rw [mul_apply, h.2, h.1]⟩, cases hστ a with hσ hτ, { exact ⟨hσ, σ.injective (h.trans hσ.symm)⟩ }, { exact ⟨(congr_arg σ hτ).symm.trans h, hτ⟩ }, end lemma disjoint.mul_eq_one_iff {σ τ : perm α} (hστ : disjoint σ τ) : σ * τ = 1 ↔ σ = 1 ∧ τ = 1 := by simp_rw [ext_iff, one_apply, hστ.mul_apply_eq_iff, forall_and_distrib] lemma disjoint.gpow_disjoint_gpow {σ τ : perm α} (hστ : disjoint σ τ) (m n : ℤ) : disjoint (σ ^ m) (τ ^ n) := λ x, or.imp (λ h, gpow_apply_eq_self_of_apply_eq_self h m) (λ h, gpow_apply_eq_self_of_apply_eq_self h n) (hστ x) lemma disjoint.pow_disjoint_pow {σ τ : perm α} (hστ : disjoint σ τ) (m n : ℕ) : disjoint (σ ^ m) (τ ^ n) := hστ.gpow_disjoint_gpow m n end disjoint section is_swap variable [decidable_eq α] /-- `f.is_swap` indicates that the permutation `f` is a transposition of two elements. -/ def is_swap (f : perm α) : Prop := ∃ x y, x ≠ y ∧ f = swap x y lemma is_swap.of_subtype_is_swap {p : α → Prop} [decidable_pred p] {f : perm (subtype p)} (h : f.is_swap) : (of_subtype f).is_swap := let ⟨⟨x, hx⟩, ⟨y, hy⟩, hxy⟩ := h in ⟨x, y, by { simp only [ne.def] at hxy, exact hxy.1 }, equiv.ext $ λ z, begin rw [hxy.2, of_subtype], simp only [swap_apply_def, coe_fn_mk, swap_inv, subtype.mk_eq_mk, monoid_hom.coe_mk], split_ifs; rw subtype.coe_mk <|> cc, end⟩ lemma ne_and_ne_of_swap_mul_apply_ne_self {f : perm α} {x y : α} (hy : (swap x (f x) * f) y ≠ y) : f y ≠ y ∧ y ≠ x := begin simp only [swap_apply_def, mul_apply, f.injective.eq_iff] at *, by_cases h : f y = x, { split; intro; simp only [*, if_true, eq_self_iff_true, not_true, ne.def] at * }, { split_ifs at hy; cc } end end is_swap section support variables [decidable_eq α] [fintype α] {f g : perm α} /-- The `finset` of nonfixed points of a permutation. -/ def support (f : perm α) : finset α := univ.filter (λ x, f x ≠ x) @[simp] lemma mem_support {x : α} : x ∈ f.support ↔ f x ≠ x := by rw [support, mem_filter, and_iff_right (mem_univ x)] lemma not_mem_support {x : α} : x ∉ f.support ↔ f x = x := by simp @[simp] lemma support_eq_empty_iff {σ : perm α} : σ.support = ∅ ↔ σ = 1 := by simp_rw [finset.ext_iff, mem_support, finset.not_mem_empty, iff_false, not_not, equiv.perm.ext_iff, one_apply] @[simp] lemma support_one : (1 : perm α).support = ∅ := by rw support_eq_empty_iff @[simp] lemma support_refl : support (equiv.refl α) = ∅ := support_one lemma support_congr (h : f.support ⊆ g.support) (h' : ∀ x ∈ g.support, f x = g x) : f = g := begin ext x, by_cases hx : x ∈ g.support, { exact h' x hx }, { rw [not_mem_support.mp hx, ←not_mem_support], exact λ H, hx (h H) } end lemma support_mul_le (f g : perm α) : (f * g).support ≤ f.support ⊔ g.support := λ x, begin rw [sup_eq_union, mem_union, mem_support, mem_support, mem_support, mul_apply, ←not_and_distrib, not_imp_not], rintro ⟨hf, hg⟩, rw [hg, hf] end lemma exists_mem_support_of_mem_support_prod {l : list (perm α)} {x : α} (hx : x ∈ l.prod.support) : ∃ f : perm α, f ∈ l ∧ x ∈ f.support := begin contrapose! hx, simp_rw [mem_support, not_not] at hx ⊢, induction l with f l ih generalizing hx, { refl }, { rw [list.prod_cons, mul_apply, ih (λ g hg, hx g (or.inr hg)), hx f (or.inl rfl)] }, end lemma support_pow_le (σ : perm α) (n : ℤ) : (σ ^ n).support ≤ σ.support := λ x h1, mem_support.mpr (λ h2, mem_support.mp h1 (gpow_apply_eq_self_of_apply_eq_self h2 n)) @[simp] lemma support_inv (σ : perm α) : support (σ⁻¹) = σ.support := by simp_rw [finset.ext_iff, mem_support, not_iff_not, (inv_eq_iff_eq).trans eq_comm, iff_self, imp_true_iff] @[simp] lemma apply_mem_support {x : α} : f x ∈ f.support ↔ x ∈ f.support := by rw [mem_support, mem_support, ne.def, ne.def, not_iff_not, apply_eq_iff_eq] @[simp] lemma pow_apply_mem_support {n : ℕ} {x : α} : (f ^ n) x ∈ f.support ↔ x ∈ f.support := begin induction n with n ih, { refl }, rw [pow_succ, perm.mul_apply, apply_mem_support, ih] end @[simp] lemma gpow_apply_mem_support {n : ℤ} {x : α} : (f ^ n) x ∈ f.support ↔ x ∈ f.support := begin cases n, { rw [int.of_nat_eq_coe, gpow_coe_nat, pow_apply_mem_support] }, { rw [gpow_neg_succ_of_nat, ← support_inv, ← inv_pow, pow_apply_mem_support] } end lemma pow_eq_on_of_mem_support (h : ∀ (x ∈ f.support ∩ g.support), f x = g x) (k : ℕ) : ∀ (x ∈ f.support ∩ g.support), (f ^ k) x = (g ^ k) x := begin induction k with k hk, { simp }, { intros x hx, rw [pow_succ', mul_apply, pow_succ', mul_apply, h _ hx, hk], rwa [mem_inter, apply_mem_support, ←h _ hx, apply_mem_support, ←mem_inter] } end lemma disjoint_iff_disjoint_support : disjoint f g ↔ _root_.disjoint f.support g.support := by simp [disjoint_iff_eq_or_eq, disjoint_iff, finset.ext_iff, not_and_distrib] lemma disjoint.disjoint_support (h : disjoint f g) : _root_.disjoint f.support g.support := disjoint_iff_disjoint_support.1 h lemma disjoint.support_mul (h : disjoint f g) : (f * g).support = f.support ∪ g.support := begin refine le_antisymm (support_mul_le _ _) (λ a, _), rw [mem_union, mem_support, mem_support, mem_support, mul_apply, ←not_and_distrib, not_imp_not], exact (h a).elim (λ hf h, ⟨hf, f.apply_eq_iff_eq.mp (h.trans hf.symm)⟩) (λ hg h, ⟨(congr_arg f hg).symm.trans h, hg⟩), end lemma support_prod_of_pairwise_disjoint (l : list (perm α)) (h : l.pairwise disjoint) : l.prod.support = (l.map support).foldr (⊔) ⊥ := begin induction l with hd tl hl, { simp }, { rw [list.pairwise_cons] at h, have : disjoint hd tl.prod := disjoint_prod_right _ h.left, simp [this.support_mul, hl h.right] } end lemma support_prod_le (l : list (perm α)) : l.prod.support ≤ (l.map support).foldr (⊔) ⊥ := begin induction l with hd tl hl, { simp }, { rw [list.prod_cons, list.map_cons, list.foldr_cons], refine (support_mul_le hd tl.prod).trans _, exact sup_le_sup (le_refl _) hl } end lemma support_gpow_le (σ : perm α) (n : ℤ) : (σ ^ n).support ≤ σ.support := by { cases n; exact support_pow_le σ _ } @[simp] lemma support_swap {x y : α} (h : x ≠ y) : support (swap x y) = {x, y} := begin ext z, by_cases hx : z = x; by_cases hy : z = y, any_goals { simpa [hx, hy] using h.symm }, { simp [swap_apply_of_ne_of_ne, hx, hy] } end lemma support_swap_iff (x y : α) : support (swap x y) = {x, y} ↔ x ≠ y := begin refine ⟨λ h H, _, support_swap⟩, subst H, simp only [swap_self, support_refl, insert_singleton_self_eq] at h, have : x ∈ ∅, { rw h, exact mem_singleton.mpr rfl }, simpa end lemma support_swap_mul_swap {x y z : α} (h : list.nodup [x, y, z]) : support (swap x y * swap y z) = {x, y, z} := begin simp only [list.not_mem_nil, and_true, list.mem_cons_iff, not_false_iff, list.nodup_cons, list.mem_singleton, and_self, list.nodup_nil] at h, push_neg at h, apply le_antisymm, { convert support_mul_le _ _, rw [support_swap h.left.left, support_swap h.right], ext, simp [or.comm, or.left_comm] }, { intro, simp only [mem_insert, mem_singleton], rintro (rfl | rfl | rfl | _); simp [swap_apply_of_ne_of_ne, h.left.left, h.left.left.symm, h.left.right, h.left.right.symm, h.right.symm] } end lemma support_swap_mul_ge_support_diff (f : perm α) (x y : α) : f.support \ {x, y} ≤ (swap x y * f).support := begin intro, simp only [and_imp, perm.coe_mul, function.comp_app, ne.def, mem_support, mem_insert, mem_sdiff, mem_singleton], push_neg, rintro ha ⟨hx, hy⟩ H, rw [swap_apply_eq_iff, swap_apply_of_ne_of_ne hx hy] at H, exact ha H end lemma support_swap_mul_eq (f : perm α) (x : α) (h : f (f x) ≠ x) : (swap x (f x) * f).support = f.support \ {x} := begin by_cases hx : f x = x, { simp [hx, sdiff_singleton_eq_erase, not_mem_support.mpr hx, erase_eq_of_not_mem] }, ext z, by_cases hzx : z = x, { simp [hzx] }, by_cases hzf : z = f x, { simp [hzf, hx, h, swap_apply_of_ne_of_ne], }, by_cases hzfx : f z = x, { simp [ne.symm hzx, hzx, ne.symm hzf, hzfx] }, { simp [ne.symm hzx, hzx, ne.symm hzf, hzfx, f.injective.ne hzx, swap_apply_of_ne_of_ne] } end lemma mem_support_swap_mul_imp_mem_support_ne {x y : α} (hy : y ∈ support (swap x (f x) * f)) : y ∈ support f ∧ y ≠ x := begin simp only [mem_support, swap_apply_def, mul_apply, f.injective.eq_iff] at *, by_cases h : f y = x, { split; intro; simp only [*, if_true, eq_self_iff_true, not_true, ne.def] at * }, { split_ifs at hy; cc } end lemma disjoint.mem_imp (h : disjoint f g) {x : α} (hx : x ∈ f.support) : x ∉ g.support := λ H, h.disjoint_support (mem_inter_of_mem hx H) lemma eq_on_support_mem_disjoint {l : list (perm α)} (h : f ∈ l) (hl : l.pairwise disjoint) : ∀ (x ∈ f.support), f x = l.prod x := begin induction l with hd tl IH, { simpa using h }, { intros x hx, rw list.pairwise_cons at hl, rw list.mem_cons_iff at h, rcases h with rfl|h, { rw [list.prod_cons, mul_apply, not_mem_support.mp ((disjoint_prod_right tl hl.left).mem_imp hx)] }, { rw [list.prod_cons, mul_apply, ←IH h hl.right _ hx, eq_comm, ←not_mem_support], refine (hl.left _ h).symm.mem_imp _, simpa using hx } } end lemma support_le_prod_of_mem {l : list (perm α)} (h : f ∈ l) (hl : l.pairwise disjoint) : f.support ≤ l.prod.support := begin intros x hx, rwa [mem_support, ←eq_on_support_mem_disjoint h hl _ hx, ←mem_support], end section extend_domain variables {β : Type*} [decidable_eq β] [fintype β] {p : β → Prop} [decidable_pred p] @[simp] lemma support_extend_domain (f : α ≃ subtype p) {g : perm α} : support (g.extend_domain f) = g.support.map f.as_embedding := begin ext b, simp only [exists_prop, function.embedding.coe_fn_mk, to_embedding_apply, mem_map, ne.def, function.embedding.trans_apply, mem_support], by_cases pb : p b, { rw [extend_domain_apply_subtype _ _ pb], split, { rintro h, refine ⟨f.symm ⟨b, pb⟩, _, by simp⟩, contrapose! h, simp [h] }, { rintro ⟨a, ha, hb⟩, contrapose! ha, obtain rfl : a = f.symm ⟨b, pb⟩, { rw eq_symm_apply, exact subtype.coe_injective hb }, rw eq_symm_apply, exact subtype.coe_injective ha } }, { rw [extend_domain_apply_not_subtype _ _ pb], simp only [not_exists, false_iff, not_and, eq_self_iff_true, not_true], rintros a ha rfl, exact pb (subtype.prop _) } end lemma card_support_extend_domain (f : α ≃ subtype p) {g : perm α} : (g.extend_domain f).support.card = g.support.card := by simp end extend_domain section card @[simp] lemma card_support_eq_zero {f : perm α} : f.support.card = 0 ↔ f = 1 := by rw [finset.card_eq_zero, support_eq_empty_iff] lemma one_lt_card_support_of_ne_one {f : perm α} (h : f ≠ 1) : 1 < f.support.card := begin simp_rw [one_lt_card_iff, mem_support, ←not_or_distrib], contrapose! h, ext a, specialize h (f a) a, rwa [apply_eq_iff_eq, or_self, or_self] at h, end lemma card_support_ne_one (f : perm α) : f.support.card ≠ 1 := begin by_cases h : f = 1, { exact ne_of_eq_of_ne (card_support_eq_zero.mpr h) zero_ne_one }, { exact ne_of_gt (one_lt_card_support_of_ne_one h) }, end @[simp] lemma card_support_le_one {f : perm α} : f.support.card ≤ 1 ↔ f = 1 := by rw [le_iff_lt_or_eq, nat.lt_succ_iff, nat.le_zero_iff, card_support_eq_zero, or_iff_not_imp_right, imp_iff_right f.card_support_ne_one] lemma two_le_card_support_of_ne_one {f : perm α} (h : f ≠ 1) : 2 ≤ f.support.card := one_lt_card_support_of_ne_one h lemma card_support_swap_mul {f : perm α} {x : α} (hx : f x ≠ x) : (swap x (f x) * f).support.card < f.support.card := finset.card_lt_card ⟨λ z hz, (mem_support_swap_mul_imp_mem_support_ne hz).left, λ h, absurd (h (mem_support.2 hx)) (mt mem_support.1 (by simp))⟩ lemma card_support_swap {x y : α} (hxy : x ≠ y) : (swap x y).support.card = 2 := show (swap x y).support.card = finset.card ⟨x ::ₘ y ::ₘ 0, by simp [hxy]⟩, from congr_arg card $ by simp [support_swap hxy, *, finset.ext_iff] @[simp] lemma card_support_eq_two {f : perm α} : f.support.card = 2 ↔ is_swap f := begin split; intro h, { obtain ⟨x, t, hmem, hins, ht⟩ := card_eq_succ.1 h, obtain ⟨y, rfl⟩ := card_eq_one.1 ht, rw mem_singleton at hmem, refine ⟨x, y, hmem, _⟩, ext a, have key : ∀ b, f b ≠ b ↔ _ := λ b, by rw [←mem_support, ←hins, mem_insert, mem_singleton], by_cases ha : f a = a, { have ha' := not_or_distrib.mp (mt (key a).mpr (not_not.mpr ha)), rw [ha, swap_apply_of_ne_of_ne ha'.1 ha'.2] }, { have ha' := (key (f a)).mp (mt f.apply_eq_iff_eq.mp ha), obtain rfl | rfl := ((key a).mp ha), { rw [or.resolve_left ha' ha, swap_apply_left] }, { rw [or.resolve_right ha' ha, swap_apply_right] } } }, { obtain ⟨x, y, hxy, rfl⟩ := h, exact card_support_swap hxy } end lemma disjoint.card_support_mul (h : disjoint f g) : (f * g).support.card = f.support.card + g.support.card := begin rw ←finset.card_disjoint_union, { congr, ext, simp [h.support_mul] }, { simpa using h.disjoint_support } end lemma card_support_prod_list_of_pairwise_disjoint {l : list (perm α)} (h : l.pairwise disjoint) : l.prod.support.card = (l.map (finset.card ∘ support)).sum := begin induction l with a t ih, { exact card_support_eq_zero.mpr rfl, }, { obtain ⟨ha, ht⟩ := list.pairwise_cons.1 h, rw [list.prod_cons, list.map_cons, list.sum_cons, ←ih ht], exact (disjoint_prod_right _ ha).card_support_mul } end end card end support end equiv.perm
c31ce493db4c340ecdcc1b0fd0060a86c1cb1cd3
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/stateT1.lean
f33b046f6c4cfd57a2c3a9610daac59f9cae8735
[ "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
867
lean
meta_definition mytactic (A : Type) := stateT (list nat) tactic A attribute [instance] meta_definition mytactic_is_monad : monad mytactic := @stateT_is_monad _ _ _ meta_definition read_lst : mytactic (list nat) := stateT.read meta_definition write_lst : list nat → mytactic unit := stateT.write meta_definition foo : mytactic unit := write_lst [10, 20] meta_definition ins (a : nat) : mytactic unit := do l : list nat ← read_lst, write_lst (a :: l) meta_definition invoke (s : list nat) (m : mytactic unit) : tactic (list nat) := do (u, s') ← m s, return s' meta_definition tactic_to_mytactic {A : Type} (t : tactic A) : mytactic A := λ s, do a : A ← t, return (a, s) open tactic example : list nat := by do l : list nat ← invoke [] (foo >> ins 30 >> tactic_to_mytactic (trace "foo") >> ins 40), trace l, mk_const `list.nil >>= apply
ebc2eb6ac50e455765b7633aa7e17109002a1f02
17d3c61bf162bf88be633867ed4cb201378a8769
/tests/lean/run/opt_param_cc.lean
82742a52316a3b43e1b78af93379b4fa8af48f25
[ "Apache-2.0" ]
permissive
u20024804/lean
11def01468fb4796fb0da76015855adceac7e311
d315e424ff17faf6fe096a0a1407b70193009726
refs/heads/master
1,611,388,567,561
1,485,836,506,000
1,485,836,625,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
706
lean
def f (a : nat) (b : nat := a) (c : nat := a) := a + b + c lemma ex1 (a a' b c d : nat) (h : b = c) (h2 : a = a') : f a b d = f a' c d := by cc lemma ex2 (a a' b c d : nat) (h : b = c) (h2 : a = a') : f a b d = f a' c d := by rw [h, h2] set_option pp.beta true set_option pp.all true lemma ex3 (a a' b c d : nat) (h : b = c) (h2 : a = a') : f a b d = f a' c d := begin simp [h, h2], end open tactic run_command mk_const `f >>= get_fun_info >>= trace run_command mk_const `eq >>= get_fun_info >>= trace run_command mk_const `id >>= get_fun_info >>= trace set_option trace.congr_lemma true set_option trace.app_builder true run_command mk_const `f >>= mk_congr_lemma_simp >>= (λ l, trace l^.type)
90ccdfbb713d9e07276ef9233ea0c72c6f5818b3
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/list/nodup.lean
1a77d853637ca5aa08e27a0e87ddba533e92932f
[ "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
14,632
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kenny Lau -/ import data.list.lattice import data.list.pairwise import data.list.forall2 /-! # 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} {l l₁ l₂ : list α} {a b : α} namespace list @[simp] theorem forall_mem_ne {a : α} {l : list α} : (∀ (a' : α), a' ∈ l → ¬a = a') ↔ a ∉ l := ⟨λ h m, h _ m rfl, λ h a' m e, h (e.symm ▸ m)⟩ @[simp] theorem nodup_nil : @nodup α [] := pairwise.nil @[simp] theorem nodup_cons {a : α} {l : list α} : nodup (a::l) ↔ a ∉ l ∧ nodup l := by simp only [nodup, pairwise_cons, forall_mem_ne] protected lemma pairwise.nodup {l : list α} {r : α → α → Prop} [is_irrefl α r] (h : pairwise r l) : nodup l := h.imp $ λ a b, ne_of_irrefl lemma rel_nodup {r : α → β → Prop} (hr : relator.bi_unique r) : (forall₂ r ⇒ (↔)) nodup nodup | _ _ forall₂.nil := by simp only [nodup_nil] | _ _ (forall₂.cons hab h) := by simpa only [nodup_cons] using relator.rel_and (relator.rel_not (rel_mem hr hab h)) (rel_nodup h) protected lemma nodup.cons (ha : a ∉ l) (hl : nodup l) : nodup (a :: l) := nodup_cons.2 ⟨ha, hl⟩ lemma nodup_singleton (a : α) : nodup [a] := pairwise_singleton _ _ lemma nodup.of_cons (h : nodup (a :: l)) : nodup l := (nodup_cons.1 h).2 lemma nodup.not_mem (h : (a :: l).nodup) : a ∉ l := (nodup_cons.1 h).1 lemma not_nodup_cons_of_mem : a ∈ l → ¬ nodup (a :: l) := imp_not_comm.1 nodup.not_mem protected lemma nodup.sublist : l₁ <+ l₂ → nodup l₂ → nodup l₁ := pairwise.sublist theorem not_nodup_pair (a : α) : ¬ nodup [a, a] := not_nodup_cons_of_mem $ mem_singleton_self _ theorem nodup_iff_sublist {l : list α} : nodup l ↔ ∀ a, ¬ [a, a] <+ l := ⟨λ d a h, not_nodup_pair a (d.sublist h), begin induction l with a l IH; intro h, {exact nodup_nil}, exact (IH $ λ a s, h a $ sublist_cons_of_sublist _ s).cons (λ al, h a $ (singleton_sublist.2 al).cons_cons _) end⟩ theorem nodup_iff_nth_le_inj {l : list α} : nodup l ↔ ∀ i j h₁ h₂, nth_le l i h₁ = nth_le l j h₂ → i = j := pairwise_iff_nth_le.trans ⟨λ H i j h₁ h₂ h, ((lt_trichotomy _ _) .resolve_left (λ h', H _ _ h₂ h' h)) .resolve_right (λ h', H _ _ h₁ h' h.symm), λ H i j h₁ h₂ h, ne_of_lt h₂ (H _ _ _ _ h)⟩ theorem nodup.nth_le_inj_iff {l : list α} (h : nodup l) {i j : ℕ} (hi : i < l.length) (hj : j < l.length) : l.nth_le i hi = l.nth_le j hj ↔ i = j := ⟨nodup_iff_nth_le_inj.mp h _ _ _ _, by simp {contextual := tt}⟩ lemma nodup_iff_nth_ne_nth {l : list α} : l.nodup ↔ ∀ (i j : ℕ), i < j → j < l.length → l.nth i ≠ l.nth j := begin rw nodup_iff_nth_le_inj, simp only [nth_le_eq_iff, some_nth_le_eq], split; rintro h i j h₁ h₂, { exact mt (h i j (h₁.trans h₂) h₂) (ne_of_lt h₁) }, { intro h₃, by_contra h₄, cases lt_or_gt_of_ne h₄ with h₅ h₅, { exact h i j h₅ h₂ h₃ }, { exact h j i h₅ h₁ h₃.symm }}, end lemma nodup.ne_singleton_iff {l : list α} (h : nodup l) (x : α) : l ≠ [x] ↔ l = [] ∨ ∃ y ∈ l, y ≠ x := begin induction l with hd tl hl, { simp }, { specialize hl h.of_cons, by_cases hx : tl = [x], { simpa [hx, and.comm, and_or_distrib_left] using h }, { rw [←ne.def, hl] at hx, rcases hx with rfl | ⟨y, hy, hx⟩, { simp }, { have : tl ≠ [] := ne_nil_of_mem hy, suffices : ∃ (y : α) (H : y ∈ hd :: tl), y ≠ x, { simpa [ne_nil_of_mem hy] }, exact ⟨y, mem_cons_of_mem _ hy, hx⟩ } } } end lemma nth_le_eq_of_ne_imp_not_nodup (xs : list α) (n m : ℕ) (hn : n < xs.length) (hm : m < xs.length) (h : xs.nth_le n hn = xs.nth_le m hm) (hne : n ≠ m) : ¬ nodup xs := begin rw nodup_iff_nth_le_inj, simp only [exists_prop, exists_and_distrib_right, not_forall], exact ⟨n, m, ⟨hn, hm, h⟩, hne⟩ end @[simp] theorem nth_le_index_of [decidable_eq α] {l : list α} (H : nodup l) (n h) : index_of (nth_le l n h) l = n := nodup_iff_nth_le_inj.1 H _ _ _ h $ index_of_nth_le $ index_of_lt_length.2 $ nth_le_mem _ _ _ theorem nodup_iff_count_le_one [decidable_eq α] {l : list α} : nodup l ↔ ∀ a, count a l ≤ 1 := nodup_iff_sublist.trans $ forall_congr $ λ a, have [a, a] <+ l ↔ 1 < count a l, from (@le_count_iff_repeat_sublist _ _ a l 2).symm, (not_congr this).trans not_lt theorem nodup_repeat (a : α) : ∀ {n : ℕ}, nodup (repeat a n) ↔ n ≤ 1 | 0 := by simp [nat.zero_le] | 1 := by simp | (n+2) := iff_of_false (λ H, nodup_iff_sublist.1 H a ((repeat_sublist_repeat _).2 (nat.le_add_left 2 n))) (not_le_of_lt $ nat.le_add_left 2 n) @[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {l : list α} (d : nodup l) (h : a ∈ l) : count a l = 1 := le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos.2 h) lemma count_eq_of_nodup [decidable_eq α] {a : α} {l : list α} (d : nodup l) : count a l = if a ∈ l then 1 else 0 := begin split_ifs with h, { exact count_eq_one_of_mem d h }, { exact count_eq_zero_of_not_mem h }, end lemma nodup.of_append_left : nodup (l₁ ++ l₂) → nodup l₁ := nodup.sublist (sublist_append_left l₁ l₂) lemma nodup.of_append_right : nodup (l₁ ++ l₂) → nodup l₂ := nodup.sublist (sublist_append_right l₁ l₂) theorem nodup_append {l₁ l₂ : list α} : nodup (l₁++l₂) ↔ nodup l₁ ∧ nodup l₂ ∧ disjoint l₁ l₂ := by simp only [nodup, pairwise_append, disjoint_iff_ne] theorem disjoint_of_nodup_append {l₁ l₂ : list α} (d : nodup (l₁++l₂)) : disjoint l₁ l₂ := (nodup_append.1 d).2.2 lemma nodup.append (d₁ : nodup l₁) (d₂ : nodup l₂) (dj : disjoint l₁ l₂) : nodup (l₁ ++ l₂) := nodup_append.2 ⟨d₁, d₂, dj⟩ theorem nodup_append_comm {l₁ l₂ : list α} : nodup (l₁++l₂) ↔ nodup (l₂++l₁) := by simp only [nodup_append, and.left_comm, disjoint_comm] theorem nodup_middle {a : α} {l₁ l₂ : list α} : nodup (l₁ ++ a::l₂) ↔ nodup (a::(l₁++l₂)) := by simp only [nodup_append, not_or_distrib, and.left_comm, and_assoc, nodup_cons, mem_append, disjoint_cons_right] lemma nodup.of_map (f : α → β) {l : list α} : nodup (map f l) → nodup l := pairwise.of_map f $ λ a b, mt $ congr_arg f lemma nodup.map_on {f : α → β} (H : ∀ x ∈ l, ∀ y ∈ l, f x = f y → x = y) (d : nodup l) : (map f l).nodup := pairwise.map _ (by exact λ a b ⟨ma, mb, n⟩ e, n (H a ma b mb e)) (pairwise.and_mem.1 d) theorem inj_on_of_nodup_map {f : α → β} {l : list α} (d : nodup (map f l)) : ∀ ⦃x⦄, x ∈ l → ∀ ⦃y⦄, y ∈ l → f x = f y → x = y := begin induction l with hd tl ih, { simp }, { simp only [map, nodup_cons, mem_map, not_exists, not_and, ←ne.def] at d, rintro _ (rfl | h₁) _ (rfl | h₂) h₃, { refl }, { apply (d.1 _ h₂ h₃.symm).elim }, { apply (d.1 _ h₁ h₃).elim }, { apply ih d.2 h₁ h₂ h₃ } } end theorem nodup_map_iff_inj_on {f : α → β} {l : list α} (d : nodup l) : nodup (map f l) ↔ (∀ (x ∈ l) (y ∈ l), f x = f y → x = y) := ⟨inj_on_of_nodup_map, λ h, d.map_on h⟩ protected lemma nodup.map {f : α → β} (hf : injective f) : nodup l → nodup (map f l) := nodup.map_on (assume x _ y _ h, hf h) theorem nodup_map_iff {f : α → β} {l : list α} (hf : injective f) : nodup (map f l) ↔ nodup l := ⟨nodup.of_map _, nodup.map hf⟩ @[simp] theorem nodup_attach {l : list α} : nodup (attach l) ↔ nodup l := ⟨λ h, attach_map_val l ▸ h.map (λ a b, subtype.eq), λ h, nodup.of_map subtype.val ((attach_map_val l).symm ▸ h)⟩ alias nodup_attach ↔ nodup.of_attach nodup.attach attribute [protected] nodup.attach lemma nodup.pmap {p : α → Prop} {f : Π a, p a → β} {l : list α} {H} (hf : ∀ a ha b hb, f a ha = f b hb → a = b) (h : nodup l) : nodup (pmap f l H) := by rw [pmap_eq_map_attach]; exact h.attach.map (λ ⟨a, ha⟩ ⟨b, hb⟩ h, by congr; exact hf a (H _ ha) b (H _ hb) h) lemma nodup.filter (p : α → Prop) [decidable_pred p] {l} : nodup l → nodup (filter p l) := pairwise.filter p @[simp] theorem nodup_reverse {l : list α} : nodup (reverse l) ↔ nodup l := pairwise_reverse.trans $ by simp only [nodup, ne.def, eq_comm] lemma nodup.erase_eq_filter [decidable_eq α] {l} (d : nodup l) (a : α) : l.erase a = filter (≠ a) l := begin induction d with b l m d IH, {refl}, by_cases b = a, { subst h, rw [erase_cons_head, filter_cons_of_neg], symmetry, rw filter_eq_self, simpa only [ne.def, eq_comm] using m, exact not_not_intro rfl }, { rw [erase_cons_tail _ h, filter_cons_of_pos, IH], exact h } end lemma nodup.erase [decidable_eq α] (a : α) : nodup l → nodup (l.erase a) := nodup.sublist $ erase_sublist _ _ lemma nodup.diff [decidable_eq α] : l₁.nodup → (l₁.diff l₂).nodup := nodup.sublist $ diff_sublist _ _ lemma nodup.mem_erase_iff [decidable_eq α] (d : nodup l) : a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l := by rw [d.erase_eq_filter, mem_filter, and_comm] lemma nodup.not_mem_erase [decidable_eq α] (h : nodup l) : a ∉ l.erase a := λ H, (h.mem_erase_iff.1 H).1 rfl theorem nodup_join {L : list (list α)} : nodup (join L) ↔ (∀ l ∈ L, nodup l) ∧ pairwise disjoint L := by simp only [nodup, pairwise_join, disjoint_left.symm, forall_mem_ne] theorem nodup_bind {l₁ : list α} {f : α → list β} : nodup (l₁.bind f) ↔ (∀ x ∈ l₁, nodup (f x)) ∧ pairwise (λ (a b : α), disjoint (f a) (f b)) l₁ := by simp only [list.bind, nodup_join, pairwise_map, and_comm, and.left_comm, mem_map, exists_imp_distrib, and_imp]; rw [show (∀ (l : list β) (x : α), f x = l → x ∈ l₁ → nodup l) ↔ (∀ (x : α), x ∈ l₁ → nodup (f x)), from forall_swap.trans $ forall_congr $ λ_, forall_eq'] protected lemma nodup.product {l₂ : list β} (d₁ : l₁.nodup) (d₂ : l₂.nodup) : (l₁.product l₂).nodup := nodup_bind.2 ⟨λ a ma, d₂.map $ left_inverse.injective $ λ b, (rfl : (a,b).2 = b), d₁.imp $ λ a₁ a₂ n x h₁ h₂, begin rcases mem_map.1 h₁ with ⟨b₁, mb₁, rfl⟩, rcases mem_map.1 h₂ with ⟨b₂, mb₂, ⟨⟩⟩, exact n rfl end⟩ lemma nodup.sigma {σ : α → Type*} {l₂ : Π a, list (σ a)} (d₁ : nodup l₁) (d₂ : ∀ a, nodup (l₂ a)) : (l₁.sigma l₂).nodup := nodup_bind.2 ⟨λ a ma, (d₂ a).map (λ b b' h, by injection h with _ h; exact eq_of_heq h), d₁.imp $ λ a₁ a₂ n x h₁ h₂, begin rcases mem_map.1 h₁ with ⟨b₁, mb₁, rfl⟩, rcases mem_map.1 h₂ with ⟨b₂, mb₂, ⟨⟩⟩, exact n rfl end⟩ protected lemma nodup.filter_map {f : α → option β} (h : ∀ a a' b, b ∈ f a → b ∈ f a' → a = a') : nodup l → nodup (filter_map f l) := pairwise.filter_map f $ λ a a' n b bm b' bm' e, n $ h a a' b' (e ▸ bm) bm' protected lemma nodup.concat (h : a ∉ l) (h' : l.nodup) : (l.concat a).nodup := by rw concat_eq_append; exact h'.append (nodup_singleton _) (disjoint_singleton.2 h) lemma nodup.insert [decidable_eq α] (h : l.nodup) : (insert a l).nodup := if h' : a ∈ l then by rw [insert_of_mem h']; exact h else by rw [insert_of_not_mem h', nodup_cons]; split; assumption lemma nodup.union [decidable_eq α] (l₁ : list α) (h : nodup l₂) : (l₁ ∪ l₂).nodup := begin induction l₁ with a l₁ ih generalizing l₂, { exact h }, { exact (ih h).insert } end lemma nodup.inter [decidable_eq α] (l₂ : list α) : nodup l₁ → nodup (l₁ ∩ l₂) := nodup.filter _ @[simp] theorem nodup_sublists {l : list α} : nodup (sublists l) ↔ nodup l := ⟨λ h, (h.sublist (map_ret_sublist_sublists _)).of_map _, λ 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] alias nodup_sublists ↔ nodup.of_sublists nodup.sublists alias nodup_sublists' ↔ nodup.of_sublists' nodup.sublists' attribute [protected] nodup.sublists nodup.sublists' lemma nodup_sublists_len (n : ℕ) (h : nodup l) : (sublists_len n l).nodup := h.sublists'.sublist $ sublists_len_sublist_sublists' _ _ lemma nodup.diff_eq_filter [decidable_eq α] : ∀ {l₁ l₂ : list α} (hl₁ : l₁.nodup), l₁.diff l₂ = l₁.filter (∉ l₂) | l₁ [] hl₁ := by simp | l₁ (a::l₂) hl₁ := begin rw [diff_cons, (hl₁.erase _).diff_eq_filter, hl₁.erase_eq_filter, filter_filter], simp only [mem_cons_iff, not_or_distrib, and.comm] end lemma nodup.mem_diff_iff [decidable_eq α] (hl₁ : l₁.nodup) : a ∈ l₁.diff l₂ ↔ a ∈ l₁ ∧ a ∉ l₂ := by rw [hl₁.diff_eq_filter, mem_filter] protected lemma nodup.update_nth : ∀ {l : list α} {n : ℕ} {a : α} (hl : l.nodup) (ha : a ∉ l), (l.update_nth n a).nodup | [] n a hl ha := nodup_nil | (b::l) 0 a hl ha := nodup_cons.2 ⟨mt (mem_cons_of_mem _) ha, (nodup_cons.1 hl).2⟩ | (b::l) (n+1) a hl ha := nodup_cons.2 ⟨λ h, (mem_or_eq_of_mem_update_nth h).elim (nodup_cons.1 hl).1 (λ hba, ha (hba ▸ mem_cons_self _ _)), hl.of_cons.update_nth (mt (mem_cons_of_mem _) ha)⟩ lemma nodup.map_update [decidable_eq α] {l : list α} (hl : l.nodup) (f : α → β) (x : α) (y : β) : l.map (function.update f x y) = if x ∈ l then (l.map f).update_nth (l.index_of x) y else l.map f := begin induction l with hd tl ihl, { simp }, rw [nodup_cons] at hl, simp only [mem_cons_iff, map, ihl hl.2], by_cases H : hd = x, { subst hd, simp [update_nth, hl.1] }, { simp [ne.symm H, H, update_nth, ← apply_ite (cons (f hd))] } end lemma nodup.pairwise_of_forall_ne {l : list α} {r : α → α → Prop} (hl : l.nodup) (h : ∀ (a ∈ l) (b ∈ l), a ≠ b → r a b) : l.pairwise r := begin classical, refine pairwise_of_reflexive_on_dupl_of_forall_ne _ h, intros x hx, rw nodup_iff_count_le_one at hl, exact absurd (hl x) hx.not_le end lemma nodup.pairwise_of_set_pairwise {l : list α} {r : α → α → Prop} (hl : l.nodup) (h : {x | x ∈ l}.pairwise r) : l.pairwise r := hl.pairwise_of_forall_ne h end list theorem option.to_list_nodup {α} : ∀ o : option α, o.to_list.nodup | none := list.nodup_nil | (some x) := list.nodup_singleton x
c416925e7f91dd4aff7d13d3b1f0a3ef412b586e
e030b0259b777fedcdf73dd966f3f1556d392178
/tests/lean/run/mem_nil.lean
9a4f50996ae4771728a5ff6e2731c97a8658db19
[ "Apache-2.0" ]
permissive
fgdorais/lean
17b46a095b70b21fa0790ce74876658dc5faca06
c3b7c54d7cca7aaa25328f0a5660b6b75fe26055
refs/heads/master
1,611,523,590,686
1,484,412,902,000
1,484,412,902,000
38,489,734
0
0
null
1,435,923,380,000
1,435,923,379,000
null
UTF-8
Lean
false
false
73
lean
universe variables u example {α : Type u} (a : α) : a ∉ [] := sorry
e3f89fe8a2a37c4a1df69b88e48ca1ba9604b94e
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/815.lean
0105228f4a579046ccce3f185ed4a9aec6e502b1
[ "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
4,137
lean
def is_smooth {α β} (f : α → β) : Prop := sorry class IsSmooth {α β} (f : α → β) : Prop where (proof : is_smooth f) instance identity : IsSmooth fun a : α => a := sorry instance const (b : β) : IsSmooth fun a : α => b := sorry instance swap (f : α → β → γ) [∀ a, IsSmooth (f a)] : IsSmooth (λ b a => f a b) := sorry instance parm (f : α → β → γ) [IsSmooth f] (b : β) : IsSmooth (λ a => f a b) := sorry instance comp (f : β → γ) (g : α → β) [IsSmooth f] [IsSmooth g] : IsSmooth (fun a => f (g a)) := sorry instance diag (f : β → δ → γ) (g : α → β) (h : α → δ) [IsSmooth f] [∀ b, IsSmooth (f b)] [IsSmooth g] [IsSmooth h] : IsSmooth (λ a => f (g a) (h a)) := sorry example (f : β → δ → γ) [IsSmooth f] (g : α → β) [IsSmooth g] (d : δ) : IsSmooth (λ a => f (g a) d) := by infer_instance example (f : β → δ → γ) [IsSmooth f] (g : α → β) [IsSmooth g] : IsSmooth (λ a d => f (g a) d) := by infer_instance example (f : β → δ → γ) [IsSmooth f] (g : α → β) [IsSmooth g] (h : α → α) [IsSmooth h] (d : δ) : IsSmooth (λ a => f (g (h a)) d) := by infer_instance example (f : α → β → γ) [∀ a, IsSmooth (f a)] : IsSmooth (λ b a => f a b) := by infer_instance example (f : α → β → γ → δ) [∀ a b, IsSmooth (f a b)] : IsSmooth (λ c b a => f a b c) := by infer_instance example (f : α → β → γ → δ) [∀ a b, IsSmooth (f a b)] : IsSmooth (λ c a b => f a b c) := by infer_instance example (f : α → β → γ → δ → ε) [∀ a b c, IsSmooth (f a b c)] : IsSmooth (λ d a b c => f a b c d) := by infer_instance example (f : α → β → γ) [IsSmooth f] (b : β) : IsSmooth (λ a => f a b) := by infer_instance example (f : α → β → γ → δ) [IsSmooth f] (b : β) (c : γ) : IsSmooth (λ a => f a b c) := by infer_instance example (f : α → β → γ → δ) [IsSmooth f] (b : β) : IsSmooth (λ a c => f a b c) := by infer_instance example (f : α → β → γ → δ) [IsSmooth f] (c : γ) : IsSmooth (λ a b => f a b c) := by infer_instance example (f : α → β → γ → δ) (b : β) [IsSmooth (λ a => f a b)] : IsSmooth (λ a c => f a b c) := by infer_instance example (f : α → β → γ) (g : δ → ε → α) (h : δ → ε → β) [IsSmooth f] [∀ a, IsSmooth (f a)] [IsSmooth g] [IsSmooth h] : IsSmooth (λ x y => f (g x y) (h x y)) := by infer_instance example (f : β → δ → γ) (g : α → β) [IsSmooth f] [∀ b, IsSmooth (f b)] [IsSmooth g] (a : α): IsSmooth (λ (h : α → δ) => f (g a) (h a)) := by infer_instance example (f : β → δ → γ) (h : α → δ) [IsSmooth f] : IsSmooth (λ (g : α → β) a => f (g a) (h a)) := by infer_instance example (f : β → δ → γ) [IsSmooth f] (d : δ) : IsSmooth (λ (g : α → β) a => f (g a) d) := by infer_instance example (f : β → γ) (g : β → β) [IsSmooth f] [IsSmooth g] : IsSmooth (fun x => f (g (g x))) := by infer_instance example (f : α → β → γ) [∀ a, IsSmooth (f a)] : IsSmooth (λ b a => f a b) := by infer_instance example (f : α → β → γ → δ) [∀ a b, IsSmooth (f a b)] : IsSmooth (λ c a b => f a b c) := by infer_instance example (f : α → β → γ → δ → ε) [∀ a b c, IsSmooth (f a b c)] : IsSmooth (λ d a b c => f a b c d) := by infer_instance example (f : β → δ → γ) [IsSmooth f] (g : α → β) [IsSmooth g] (d : δ) : IsSmooth (λ a => f (g a) d) := by infer_instance example (f : β → δ → γ) [IsSmooth f] (g : α → β) [IsSmooth g] : IsSmooth (λ a d => f (g a) d) := by infer_instance example (f : δ → β → γ) [∀ d, IsSmooth (f d)] (g : α → β) [IsSmooth g] : IsSmooth (λ a d => (f d (g a))) := by infer_instance -- Recall Function.comp is not reducible anymore instance (f : β → γ) (g : α → β) [IsSmooth f] [IsSmooth g] : IsSmooth (f ∘ g) := by delta Function.comp infer_instance example (f : β → γ) (g : α → β) [IsSmooth f] [IsSmooth g] : IsSmooth (f ∘ g) := by infer_instance example (f : β → γ) [IsSmooth f] : IsSmooth λ (g : α → β) => (f ∘ g) := by delta Function.comp infer_instance
4e8d08f3fe034165299cb87e963d4962106bc1ef
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/order/filter/pointwise.lean
082b69d85a8952056a335239fdd0c643eeab9541
[ "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
7,567
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou The pointwise operations on filters have nice properties, such as • map m (f₁ * f₂) = map m f₁ * map m f₂ • 𝓝 x * 𝓝 y = 𝓝 (x * y) -/ import algebra.pointwise import order.filter.basic open classical set universes u v w variables {α : Type u} {β : Type v} {γ : Type w} open_locale classical local attribute [instance] pointwise_one pointwise_mul pointwise_add namespace filter open set @[to_additive] def pointwise_one [has_one α] : has_one (filter α) := ⟨principal {1}⟩ local attribute [instance] pointwise_one @[simp, to_additive] lemma mem_pointwise_one [has_one α] (s : set α) : s ∈ (1 : filter α) ↔ (1:α) ∈ s := calc s ∈ (1:filter α) ↔ {(1:α)} ⊆ s : iff.rfl ... ↔ (1:α) ∈ s : by simp @[to_additive] def pointwise_mul [monoid α] : has_mul (filter α) := ⟨λf g, { sets := { s | ∃t₁∈f, ∃t₂∈g, t₁ * t₂ ⊆ s }, univ_sets := begin have h₁ : (∃x, x ∈ f) := ⟨univ, univ_sets f⟩, have h₂ : (∃x, x ∈ g) := ⟨univ, univ_sets g⟩, simpa using and.intro h₁ h₂ end, sets_of_superset := λx y hx hxy, begin rcases hx with ⟨t₁, ht₁, t₂, ht₂, t₁t₂⟩, exact ⟨t₁, ht₁, t₂, ht₂, subset.trans t₁t₂ hxy⟩ end, inter_sets := λx y, begin simp only [exists_prop, mem_set_of_eq, subset_inter_iff], rintros ⟨s₁, hs₁, s₂, hs₂, s₁s₂⟩ ⟨t₁, ht₁, t₂, ht₂, t₁t₂⟩, exact ⟨s₁ ∩ t₁, inter_sets f hs₁ ht₁, s₂ ∩ t₂, inter_sets g hs₂ ht₂, subset.trans (pointwise_mul_subset_mul (inter_subset_left _ _) (inter_subset_left _ _)) s₁s₂, subset.trans (pointwise_mul_subset_mul (inter_subset_right _ _) (inter_subset_right _ _)) t₁t₂⟩, end }⟩ local attribute [instance] pointwise_mul pointwise_add @[to_additive] lemma mem_pointwise_mul [monoid α] {f g : filter α} {s : set α} : s ∈ f * g ↔ ∃ t₁ ∈ f, ∃ t₂ ∈ g, t₁ * t₂ ⊆ s := iff.rfl @[to_additive] lemma mul_mem_pointwise_mul [monoid α] {f g : filter α} {s t : set α} (hs : s ∈ f) (ht : t ∈ g) : s * t ∈ f * g := ⟨_, hs, _, ht, subset.refl _⟩ @[to_additive] lemma pointwise_mul_le_mul [monoid α] {f₁ f₂ g₁ g₂ : filter α} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁ * g₁ ≤ f₂ * g₂ := assume _ ⟨s, hs, t, ht, hst⟩, ⟨s, hf hs, t, hg ht, hst⟩ @[to_additive] lemma pointwise_mul_ne_bot [monoid α] {f g : filter α} : f ≠ ⊥ → g ≠ ⊥ → f * g ≠ ⊥ := begin simp only [forall_sets_nonempty_iff_ne_bot.symm], rintros hf hg s ⟨a, ha, b, hb, ab⟩, exact ((hf a ha).pointwise_mul (hg b hb)).mono ab end @[to_additive] lemma pointwise_mul_assoc [monoid α] (f g h : filter α) : f * g * h = f * (g * h) := begin ext s, split, { rintros ⟨a, ⟨a₁, ha₁, a₂, ha₂, a₁a₂⟩, b, hb, ab⟩, refine ⟨a₁, ha₁, a₂ * b, mul_mem_pointwise_mul ha₂ hb, _⟩, rw [← pointwise_mul_semigroup.mul_assoc], exact calc a₁ * a₂ * b ⊆ a * b : pointwise_mul_subset_mul a₁a₂ (subset.refl _) ... ⊆ s : ab }, { rintros ⟨a, ha, b, ⟨b₁, hb₁, b₂, hb₂, b₁b₂⟩, ab⟩, refine ⟨a * b₁, mul_mem_pointwise_mul ha hb₁, b₂, hb₂, _⟩, rw [pointwise_mul_semigroup.mul_assoc], exact calc a * (b₁ * b₂) ⊆ a * b : pointwise_mul_subset_mul (subset.refl _) b₁b₂ ... ⊆ s : ab } end local attribute [instance] pointwise_mul_monoid @[to_additive] lemma pointwise_one_mul [monoid α] (f : filter α) : 1 * f = f := begin ext s, split, { rintros ⟨t₁, ht₁, t₂, ht₂, t₁t₂⟩, refine mem_sets_of_superset (mem_sets_of_superset ht₂ _) t₁t₂, assume x hx, exact ⟨1, by rwa [← mem_pointwise_one], x, hx, (one_mul _).symm⟩ }, { assume hs, refine ⟨(1:set α), mem_principal_self _, s, hs, by simp only [one_mul]⟩ } end @[to_additive] lemma pointwise_mul_one [monoid α] (f : filter α) : f * 1 = f := begin ext s, split, { rintros ⟨t₁, ht₁, t₂, ht₂, t₁t₂⟩, refine mem_sets_of_superset (mem_sets_of_superset ht₁ _) t₁t₂, assume x hx, exact ⟨x, hx, 1, by rwa [← mem_pointwise_one], (mul_one _).symm⟩ }, { assume hs, refine ⟨s, hs, (1:set α), mem_principal_self _, by simp only [mul_one]⟩ } end @[to_additive pointwise_add_add_monoid] def pointwise_mul_monoid [monoid α] : monoid (filter α) := { mul_assoc := pointwise_mul_assoc, one_mul := pointwise_one_mul, mul_one := pointwise_mul_one, .. pointwise_mul, .. pointwise_one } local attribute [instance] filter.pointwise_mul_monoid filter.pointwise_add_add_monoid section map open is_mul_hom variables [monoid α] [monoid β] {f : filter α} (m : α → β) @[to_additive] lemma map_pointwise_mul [is_mul_hom m] {f₁ f₂ : filter α} : map m (f₁ * f₂) = map m f₁ * map m f₂ := filter_eq $ set.ext $ assume s, begin simp only [mem_pointwise_mul], split, { rintro ⟨t₁, ht₁, t₂, ht₂, t₁t₂⟩, have : m '' (t₁ * t₂) ⊆ s := subset.trans (image_subset m t₁t₂) (image_preimage_subset _ _), refine ⟨m '' t₁, image_mem_map ht₁, m '' t₂, image_mem_map ht₂, _⟩, rwa ← image_pointwise_mul m t₁ t₂ }, { rintro ⟨t₁, ht₁, t₂, ht₂, t₁t₂⟩, refine ⟨m ⁻¹' t₁, ht₁, m ⁻¹' t₂, ht₂, image_subset_iff.1 _⟩, rw image_pointwise_mul m, exact subset.trans (pointwise_mul_subset_mul (image_preimage_subset _ _) (image_preimage_subset _ _)) t₁t₂ }, end @[to_additive] lemma map_pointwise_one [is_monoid_hom m] : map m (1:filter α) = 1 := le_antisymm (le_principal_iff.2 $ mem_map_sets_iff.2 ⟨(1:set α), by simp, by { assume x, simp [is_monoid_hom.map_one m], rintros rfl, refl }⟩) (le_map $ assume s hs, begin simp only [mem_pointwise_one], exact ⟨(1:α), (mem_pointwise_one s).1 hs, is_monoid_hom.map_one _⟩ end) -- TODO: prove similar statements when `m` is group homomorphism etc. lemma pointwise_mul_map_is_monoid_hom [is_monoid_hom m] : is_monoid_hom (map m) := { map_one := map_pointwise_one m, map_mul := λ _ _, map_pointwise_mul m } lemma pointwise_add_map_is_add_monoid_hom {α : Type*} {β : Type*} [add_monoid α] [add_monoid β] (m : α → β) [is_add_monoid_hom m] : is_add_monoid_hom (map m) := { map_zero := map_pointwise_zero m, map_add := λ _ _, map_pointwise_add m } attribute [to_additive pointwise_add_map_is_add_monoid_hom] pointwise_mul_map_is_monoid_hom -- The other direction does not hold in general. @[to_additive] lemma comap_mul_comap_le [is_mul_hom m] {f₁ f₂ : filter β} : comap m f₁ * comap m f₂ ≤ comap m (f₁ * f₂) := begin rintros s ⟨t, ⟨t₁, ht₁, t₂, ht₂, t₁t₂⟩, mt⟩, refine ⟨m ⁻¹' t₁, ⟨t₁, ht₁, subset.refl _⟩, m ⁻¹' t₂, ⟨t₂, ht₂, subset.refl _⟩, _⟩, have := subset.trans (preimage_mono t₁t₂) mt, exact subset.trans (preimage_pointwise_mul_preimage_subset m _ _) this end variables {m} @[to_additive] lemma tendsto.mul_mul [is_mul_hom m] {f₁ g₁ : filter α} {f₂ g₂ : filter β} : tendsto m f₁ f₂ → tendsto m g₁ g₂ → tendsto m (f₁ * g₁) (f₂ * g₂) := assume hf hg, by { rw [tendsto, map_pointwise_mul m], exact pointwise_mul_le_mul hf hg } end map end filter
e7c79b4898578b9c7ec37f84b4b51e76fa1b29d8
9dc8cecdf3c4634764a18254e94d43da07142918
/src/topology/sheaves/sheaf_condition/pairwise_intersections.lean
75a18fd7b8c1f3ac2e4900fb865922f59ed69b1d
[ "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
21,323
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import topology.sheaves.sheaf_condition.sites import category_theory.limits.preserves.basic import category_theory.category.pairwise import category_theory.limits.constructions.binary_products import algebra.category.Ring.constructions /-! # Equivalent formulations of the sheaf condition We give an equivalent formulation of the sheaf condition. Given any indexed type `ι`, we define `overlap ι`, a category with objects corresponding to * individual open sets, `single i`, and * intersections of pairs of open sets, `pair i j`, with morphisms from `pair i j` to both `single i` and `single j`. Any open cover `U : ι → opens X` provides a functor `diagram U : overlap ι ⥤ (opens X)ᵒᵖ`. There is a canonical cone over this functor, `cone U`, whose cone point is `supr U`, and in fact this is a limit cone. A presheaf `F : presheaf C X` is a sheaf precisely if it preserves this limit. We express this in two equivalent ways, as * `is_limit (F.map_cone (cone U))`, or * `preserves_limit (diagram U) F` -/ noncomputable theory universes w v u open topological_space open Top open opposite open category_theory open category_theory.limits namespace Top.presheaf variables {C : Type u} [category.{v} C] section variables {X : Top.{w}} /-- An alternative formulation of the sheaf condition (which we prove equivalent to the usual one below as `is_sheaf_iff_is_sheaf_pairwise_intersections`). A presheaf is a sheaf if `F` sends the cone `(pairwise.cocone U).op` to a limit cone. (Recall `pairwise.cocone U` has cone point `supr U`, mapping down to the `U i` and the `U i ⊓ U j`.) -/ def is_sheaf_pairwise_intersections (F : presheaf C X) : Prop := ∀ ⦃ι : Type w⦄ (U : ι → opens X), nonempty (is_limit (F.map_cone (pairwise.cocone U).op)) /-- An alternative formulation of the sheaf condition (which we prove equivalent to the usual one below as `is_sheaf_iff_is_sheaf_preserves_limit_pairwise_intersections`). A presheaf is a sheaf if `F` preserves the limit of `pairwise.diagram U`. (Recall `pairwise.diagram U` is the diagram consisting of the pairwise intersections `U i ⊓ U j` mapping into the open sets `U i`. This diagram has limit `supr U`.) -/ def is_sheaf_preserves_limit_pairwise_intersections (F : presheaf C X) : Prop := ∀ ⦃ι : Type w⦄ (U : ι → opens X), nonempty (preserves_limit (pairwise.diagram U).op F) end /-! The remainder of this file shows that these conditions are equivalent to the usual sheaf condition. -/ variables {X : Top.{v}} [has_products.{v} C] namespace sheaf_condition_pairwise_intersections open category_theory.pairwise category_theory.pairwise.hom open sheaf_condition_equalizer_products /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simps] def cone_equiv_functor_obj (F : presheaf C X) ⦃ι : Type v⦄ (U : ι → opens ↥X) (c : limits.cone ((diagram U).op ⋙ F)) : limits.cone (sheaf_condition_equalizer_products.diagram F U) := { X := c.X, π := { app := λ Z, walking_parallel_pair.cases_on Z (pi.lift (λ (i : ι), c.π.app (op (single i)))) (pi.lift (λ (b : ι × ι), c.π.app (op (pair b.1 b.2)))), naturality' := λ Y Z f, begin cases Y; cases Z; cases f, { ext i, dsimp, simp only [limit.lift_π, category.id_comp, fan.mk_π_app, category_theory.functor.map_id, category.assoc], dsimp, simp only [limit.lift_π, category.id_comp, fan.mk_π_app], }, { ext ⟨i, j⟩, dsimp [sheaf_condition_equalizer_products.left_res], simp only [limit.lift_π, limit.lift_π_assoc, category.id_comp, fan.mk_π_app, category.assoc], have h := c.π.naturality (quiver.hom.op (hom.left i j)), dsimp at h, simpa using h, }, { ext ⟨i, j⟩, dsimp [sheaf_condition_equalizer_products.right_res], simp only [limit.lift_π, limit.lift_π_assoc, category.id_comp, fan.mk_π_app, category.assoc], have h := c.π.naturality (quiver.hom.op (hom.right i j)), dsimp at h, simpa using h, }, { ext i, dsimp, simp only [limit.lift_π, category.id_comp, fan.mk_π_app, category_theory.functor.map_id, category.assoc], dsimp, simp only [limit.lift_π, category.id_comp, fan.mk_π_app], }, end, }, } section local attribute [tidy] tactic.case_bash /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simps] def cone_equiv_functor (F : presheaf C X) ⦃ι : Type v⦄ (U : ι → opens ↥X) : limits.cone ((diagram U).op ⋙ F) ⥤ limits.cone (sheaf_condition_equalizer_products.diagram F U) := { obj := λ c, cone_equiv_functor_obj F U c, map := λ c c' f, { hom := f.hom, w' := λ j, begin cases j; { ext, simp only [limits.fan.mk_π_app, limits.cone_morphism.w, limits.limit.lift_π, category.assoc, cone_equiv_functor_obj_π_app], }, end }, }. end /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simps] def cone_equiv_inverse_obj (F : presheaf C X) ⦃ι : Type v⦄ (U : ι → opens ↥X) (c : limits.cone (sheaf_condition_equalizer_products.diagram F U)) : limits.cone ((diagram U).op ⋙ F) := { X := c.X, π := { app := begin intro x, induction x using opposite.rec, rcases x with (⟨i⟩|⟨i,j⟩), { exact c.π.app (walking_parallel_pair.zero) ≫ pi.π _ i, }, { exact c.π.app (walking_parallel_pair.one) ≫ pi.π _ (i, j), } end, naturality' := begin intros x y f, induction x using opposite.rec, induction y using opposite.rec, have ef : f = f.unop.op := rfl, revert ef, generalize : f.unop = f', rintro rfl, rcases x with ⟨i⟩|⟨⟩; rcases y with ⟨⟩|⟨j,j⟩; rcases f' with ⟨⟩, { dsimp, erw [F.map_id], simp, }, { dsimp, simp only [category.id_comp, category.assoc], have h := c.π.naturality (walking_parallel_pair_hom.left), dsimp [sheaf_condition_equalizer_products.left_res] at h, simp only [category.id_comp] at h, have h' := h =≫ pi.π _ (i, j), rw h', simp only [category.assoc, limit.lift_π, fan.mk_π_app], refl, }, { dsimp, simp only [category.id_comp, category.assoc], have h := c.π.naturality (walking_parallel_pair_hom.right), dsimp [sheaf_condition_equalizer_products.right_res] at h, simp only [category.id_comp] at h, have h' := h =≫ pi.π _ (j, i), rw h', simp, refl, }, { dsimp, erw [F.map_id], simp, }, end, }, } /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simps] def cone_equiv_inverse (F : presheaf C X) ⦃ι : Type v⦄ (U : ι → opens ↥X) : limits.cone (sheaf_condition_equalizer_products.diagram F U) ⥤ limits.cone ((diagram U).op ⋙ F) := { obj := λ c, cone_equiv_inverse_obj F U c, map := λ c c' f, { hom := f.hom, w' := begin intro x, induction x using opposite.rec, rcases x with (⟨i⟩|⟨i,j⟩), { dsimp, dunfold fork.ι, rw [←(f.w walking_parallel_pair.zero), category.assoc], }, { dsimp, rw [←(f.w walking_parallel_pair.one), category.assoc], }, end }, }. /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simps] def cone_equiv_unit_iso_app (F : presheaf C X) ⦃ι : Type v⦄ (U : ι → opens ↥X) (c : cone ((diagram U).op ⋙ F)) : (𝟭 (cone ((diagram U).op ⋙ F))).obj c ≅ (cone_equiv_functor F U ⋙ cone_equiv_inverse F U).obj c := { hom := { hom := 𝟙 _, w' := λ j, begin induction j using opposite.rec, rcases j; { dsimp, simp only [limits.fan.mk_π_app, category.id_comp, limits.limit.lift_π], } end, }, inv := { hom := 𝟙 _, w' := λ j, begin induction j using opposite.rec, rcases j; { dsimp, simp only [limits.fan.mk_π_app, category.id_comp, limits.limit.lift_π], } end }, hom_inv_id' := begin ext, simp only [category.comp_id, limits.cone.category_comp_hom, limits.cone.category_id_hom], end, inv_hom_id' := begin ext, simp only [category.comp_id, limits.cone.category_comp_hom, limits.cone.category_id_hom], end, } /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simps] def cone_equiv_unit_iso (F : presheaf C X) ⦃ι : Type v⦄ (U : ι → opens X) : 𝟭 (limits.cone ((diagram U).op ⋙ F)) ≅ cone_equiv_functor F U ⋙ cone_equiv_inverse F U := nat_iso.of_components (cone_equiv_unit_iso_app F U) (by tidy) /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simps] def cone_equiv_counit_iso (F : presheaf C X) ⦃ι : Type v⦄ (U : ι → opens X) : cone_equiv_inverse F U ⋙ cone_equiv_functor F U ≅ 𝟭 (limits.cone (sheaf_condition_equalizer_products.diagram F U)) := nat_iso.of_components (λ c, { hom := { hom := 𝟙 _, w' := begin rintro ⟨_|_⟩, { ext ⟨j⟩, dsimp, simp only [category.id_comp, limits.fan.mk_π_app, limits.limit.lift_π], }, { ext ⟨i,j⟩, dsimp, simp only [category.id_comp, limits.fan.mk_π_app, limits.limit.lift_π], }, end }, inv := { hom := 𝟙 _, w' := begin rintro ⟨_|_⟩, { ext ⟨j⟩, dsimp, simp only [category.id_comp, limits.fan.mk_π_app, limits.limit.lift_π], }, { ext ⟨i,j⟩, dsimp, simp only [category.id_comp, limits.fan.mk_π_app, limits.limit.lift_π], }, end, }, hom_inv_id' := by { ext, dsimp, simp only [category.comp_id], }, inv_hom_id' := by { ext, dsimp, simp only [category.comp_id], }, }) (λ c d f, by { ext, dsimp, simp only [category.comp_id, category.id_comp], }) /-- Cones over `diagram U ⋙ F` are the same as a cones over the usual sheaf condition equalizer diagram. -/ @[simps] def cone_equiv (F : presheaf C X) ⦃ι : Type v⦄ (U : ι → opens X) : limits.cone ((diagram U).op ⋙ F) ≌ limits.cone (sheaf_condition_equalizer_products.diagram F U) := { functor := cone_equiv_functor F U, inverse := cone_equiv_inverse F U, unit_iso := cone_equiv_unit_iso F U, counit_iso := cone_equiv_counit_iso F U, } local attribute [reducible] sheaf_condition_equalizer_products.res sheaf_condition_equalizer_products.left_res /-- If `sheaf_condition_equalizer_products.fork` is an equalizer, then `F.map_cone (cone U)` is a limit cone. -/ def is_limit_map_cone_of_is_limit_sheaf_condition_fork (F : presheaf C X) ⦃ι : Type v⦄ (U : ι → opens X) (P : is_limit (sheaf_condition_equalizer_products.fork F U)) : is_limit (F.map_cone (cocone U).op) := is_limit.of_iso_limit ((is_limit.of_cone_equiv (cone_equiv F U).symm).symm P) { hom := { hom := 𝟙 _, w' := begin intro x, induction x using opposite.rec, rcases x with ⟨⟩, { dsimp, simp, refl, }, { dsimp, simp only [limit.lift_π, limit.lift_π_assoc, category.id_comp, fan.mk_π_app, category.assoc], rw ←F.map_comp, refl, } end }, inv := { hom := 𝟙 _, w' := begin intro x, induction x using opposite.rec, rcases x with ⟨⟩, { dsimp, simp, refl, }, { dsimp, simp only [limit.lift_π, limit.lift_π_assoc, category.id_comp, fan.mk_π_app, category.assoc], rw ←F.map_comp, refl, } end }, hom_inv_id' := by { ext, dsimp, simp only [category.comp_id], }, inv_hom_id' := by { ext, dsimp, simp only [category.comp_id], }, } /-- If `F.map_cone (cone U)` is a limit cone, then `sheaf_condition_equalizer_products.fork` is an equalizer. -/ def is_limit_sheaf_condition_fork_of_is_limit_map_cone (F : presheaf C X) ⦃ι : Type v⦄ (U : ι → opens X) (Q : is_limit (F.map_cone (cocone U).op)) : is_limit (sheaf_condition_equalizer_products.fork F U) := is_limit.of_iso_limit ((is_limit.of_cone_equiv (cone_equiv F U)).symm Q) { hom := { hom := 𝟙 _, w' := begin rintro ⟨⟩, { dsimp, simp, refl, }, { dsimp, ext ⟨i, j⟩, simp only [limit.lift_π, limit.lift_π_assoc, category.id_comp, fan.mk_π_app, category.assoc], rw ←F.map_comp, refl, } end }, inv := { hom := 𝟙 _, w' := begin rintro ⟨⟩, { dsimp, simp, refl, }, { dsimp, ext ⟨i, j⟩, simp only [limit.lift_π, limit.lift_π_assoc, category.id_comp, fan.mk_π_app, category.assoc], rw ←F.map_comp, refl, } end }, hom_inv_id' := by { ext, dsimp, simp only [category.comp_id], }, inv_hom_id' := by { ext, dsimp, simp only [category.comp_id], }, } end sheaf_condition_pairwise_intersections open sheaf_condition_pairwise_intersections /-- The sheaf condition in terms of an equalizer diagram is equivalent to the reformulation in terms of a limit diagram over `U i` and `U i ⊓ U j`. -/ lemma is_sheaf_iff_is_sheaf_pairwise_intersections (F : presheaf C X) : F.is_sheaf ↔ F.is_sheaf_pairwise_intersections := (is_sheaf_iff_is_sheaf_equalizer_products F).trans $ iff.intro (λ h ι U, ⟨is_limit_map_cone_of_is_limit_sheaf_condition_fork F U (h U).some⟩) (λ h ι U, ⟨is_limit_sheaf_condition_fork_of_is_limit_map_cone F U (h U).some⟩) /-- The sheaf condition in terms of an equalizer diagram is equivalent to the reformulation in terms of the presheaf preserving the limit of the diagram consisting of the `U i` and `U i ⊓ U j`. -/ lemma is_sheaf_iff_is_sheaf_preserves_limit_pairwise_intersections (F : presheaf C X) : F.is_sheaf ↔ F.is_sheaf_preserves_limit_pairwise_intersections := begin rw is_sheaf_iff_is_sheaf_pairwise_intersections, split, { intros h ι U, exact ⟨preserves_limit_of_preserves_limit_cone (pairwise.cocone_is_colimit U).op (h U).some⟩ }, { intros h ι U, haveI := (h U).some, exact ⟨preserves_limit.preserves (pairwise.cocone_is_colimit U).op⟩ } end end Top.presheaf namespace Top.sheaf variables {X : Top.{v}} {C : Type u} [category.{v} C] variables (F : X.sheaf C) (U V : opens X) open category_theory.limits /-- For a sheaf `F`, `F(U ⊔ V)` is the pullback of `F(U) ⟶ F(U ⊓ V)` and `F(V) ⟶ F(U ⊓ V)`. This is the pullback cone. -/ def inter_union_pullback_cone : pullback_cone (F.1.map (hom_of_le inf_le_left : U ⊓ V ⟶ _).op) (F.1.map (hom_of_le inf_le_right).op) := pullback_cone.mk (F.1.map (hom_of_le le_sup_left).op) (F.1.map (hom_of_le le_sup_right).op) (by { rw [← F.1.map_comp, ← F.1.map_comp], congr }) @[simp] lemma inter_union_pullback_cone_X : (inter_union_pullback_cone F U V).X = F.1.obj (op $ U ⊔ V) := rfl @[simp] lemma inter_union_pullback_cone_fst : (inter_union_pullback_cone F U V).fst = F.1.map (hom_of_le le_sup_left).op := rfl @[simp] lemma inter_union_pullback_cone_snd : (inter_union_pullback_cone F U V).snd = F.1.map (hom_of_le le_sup_right).op := rfl variable (s : pullback_cone (F.1.map (hom_of_le inf_le_left : U ⊓ V ⟶ _).op) (F.1.map (hom_of_le inf_le_right).op)) variable [has_products.{v} C] /-- (Implementation). Every cone over `F(U) ⟶ F(U ⊓ V)` and `F(V) ⟶ F(U ⊓ V)` factors through `F(U ⊔ V)`. TODO: generalize to `C` without products. -/ def inter_union_pullback_cone_lift : s.X ⟶ F.1.obj (op (U ⊔ V)) := begin let ι : ulift.{v} walking_pair → opens X := λ j, walking_pair.cases_on j.down U V, have hι : U ⊔ V = supr ι, { ext, rw [opens.coe_supr, set.mem_Union], split, { rintros (h|h), exacts [⟨⟨walking_pair.left⟩, h⟩, ⟨⟨walking_pair.right⟩, h⟩] }, { rintro ⟨⟨_ | _⟩, h⟩, exacts [or.inl h, or.inr h] } }, refine (F.presheaf.is_sheaf_iff_is_sheaf_pairwise_intersections.mp F.2 ι).some.lift ⟨s.X, { app := _, naturality' := _ }⟩ ≫ F.1.map (eq_to_hom hι).op, { apply opposite.rec, rintro ((_|_)|(_|_)), exacts [s.fst, s.snd, s.fst ≫ F.1.map (hom_of_le inf_le_left).op, s.snd ≫ F.1.map (hom_of_le inf_le_left).op] }, rintros i j f, induction i using opposite.rec, induction j using opposite.rec, let g : j ⟶ i := f.unop, have : f = g.op := rfl, clear_value g, subst this, rcases i with (⟨⟨(_|_)⟩⟩|⟨⟨(_|_)⟩,⟨_⟩⟩); rcases j with (⟨⟨(_|_)⟩⟩|⟨⟨(_|_)⟩,⟨_⟩⟩); rcases g; dsimp; simp only [category.id_comp, s.condition, category_theory.functor.map_id, category.comp_id], { rw [← cancel_mono (F.1.map (eq_to_hom $ inf_comm : U ⊓ V ⟶ _).op), category.assoc, category.assoc], erw [← F.1.map_comp, ← F.1.map_comp], convert s.condition.symm }, end lemma inter_union_pullback_cone_lift_left : inter_union_pullback_cone_lift F U V s ≫ F.1.map (hom_of_le le_sup_left).op = s.fst := begin dsimp, erw [category.assoc, ←F.1.map_comp], exact (F.presheaf.is_sheaf_iff_is_sheaf_pairwise_intersections.mp F.2 _).some.fac _ (op $ pairwise.single (ulift.up walking_pair.left)) end lemma inter_union_pullback_cone_lift_right : inter_union_pullback_cone_lift F U V s ≫ F.1.map (hom_of_le le_sup_right).op = s.snd := begin erw [category.assoc, ←F.1.map_comp], exact (F.presheaf.is_sheaf_iff_is_sheaf_pairwise_intersections.mp F.2 _).some.fac _ (op $ pairwise.single (ulift.up walking_pair.right)) end /-- For a sheaf `F`, `F(U ⊔ V)` is the pullback of `F(U) ⟶ F(U ⊓ V)` and `F(V) ⟶ F(U ⊓ V)`. -/ def is_limit_pullback_cone : is_limit (inter_union_pullback_cone F U V) := begin let ι : ulift.{v} walking_pair → opens X := λ ⟨j⟩, walking_pair.cases_on j U V, have hι : U ⊔ V = supr ι, { ext, rw [opens.coe_supr, set.mem_Union], split, { rintros (h|h), exacts [⟨⟨walking_pair.left⟩, h⟩, ⟨⟨walking_pair.right⟩, h⟩] }, { rintro ⟨⟨_ | _⟩, h⟩, exacts [or.inl h, or.inr h] } }, apply pullback_cone.is_limit_aux', intro s, use inter_union_pullback_cone_lift F U V s, refine ⟨_,_,_⟩, { apply inter_union_pullback_cone_lift_left }, { apply inter_union_pullback_cone_lift_right }, { intros m h₁ h₂, rw ← cancel_mono (F.1.map (eq_to_hom hι.symm).op), apply (F.presheaf.is_sheaf_iff_is_sheaf_pairwise_intersections.mp F.2 ι).some.hom_ext, apply opposite.rec, rintro ((_|_)|(_|_)); rw [category.assoc, category.assoc], { erw ← F.1.map_comp, convert h₁, apply inter_union_pullback_cone_lift_left }, { erw ← F.1.map_comp, convert h₂, apply inter_union_pullback_cone_lift_right }, all_goals { dsimp only [functor.op, pairwise.cocone_ι_app, functor.map_cone_π_app, cocone.op, pairwise.cocone_ι_app_2, unop_op, op_comp, nat_trans.op], simp_rw [F.1.map_comp, ← category.assoc], congr' 1, simp_rw [category.assoc, ← F.1.map_comp] }, { convert h₁, apply inter_union_pullback_cone_lift_left }, { convert h₂, apply inter_union_pullback_cone_lift_right } } end /-- If `U, V` are disjoint, then `F(U ⊔ V) = F(U) × F(V)`. -/ def is_product_of_disjoint (h : U ⊓ V = ⊥) : is_limit (binary_fan.mk (F.1.map (hom_of_le le_sup_left : _ ⟶ U ⊔ V).op) (F.1.map (hom_of_le le_sup_right : _ ⟶ U ⊔ V).op)) := is_product_of_is_terminal_is_pullback _ _ _ _ (F.is_terminal_of_eq_empty h) (is_limit_pullback_cone F U V) /-- `F(U ⊔ V)` is isomorphic to the `eq_locus` of the two maps `F(U) × F(V) ⟶ F(U ⊓ V)`. -/ def obj_sup_iso_prod_eq_locus {X : Top} (F : X.sheaf CommRing) (U V : opens X) : F.1.obj (op $ U ⊔ V) ≅ CommRing.of (ring_hom.eq_locus _ _) := (F.is_limit_pullback_cone U V).cone_point_unique_up_to_iso (CommRing.pullback_cone_is_limit _ _) lemma obj_sup_iso_prod_eq_locus_hom_fst {X : Top} (F : X.sheaf CommRing) (U V : opens X) (x) : ((F.obj_sup_iso_prod_eq_locus U V).hom x).1.fst = F.1.map (hom_of_le le_sup_left).op x := concrete_category.congr_hom ((F.is_limit_pullback_cone U V).cone_point_unique_up_to_iso_hom_comp (CommRing.pullback_cone_is_limit _ _) walking_cospan.left) x lemma obj_sup_iso_prod_eq_locus_hom_snd {X : Top} (F : X.sheaf CommRing) (U V : opens X) (x) : ((F.obj_sup_iso_prod_eq_locus U V).hom x).1.snd = F.1.map (hom_of_le le_sup_right).op x := concrete_category.congr_hom ((F.is_limit_pullback_cone U V).cone_point_unique_up_to_iso_hom_comp (CommRing.pullback_cone_is_limit _ _) walking_cospan.right) x lemma obj_sup_iso_prod_eq_locus_inv_fst {X : Top} (F : X.sheaf CommRing) (U V : opens X) (x) : F.1.map (hom_of_le le_sup_left).op ((F.obj_sup_iso_prod_eq_locus U V).inv x) = x.1.1 := concrete_category.congr_hom ((F.is_limit_pullback_cone U V).cone_point_unique_up_to_iso_inv_comp (CommRing.pullback_cone_is_limit _ _) walking_cospan.left) x lemma obj_sup_iso_prod_eq_locus_inv_snd {X : Top} (F : X.sheaf CommRing) (U V : opens X) (x) : F.1.map (hom_of_le le_sup_right).op ((F.obj_sup_iso_prod_eq_locus U V).inv x) = x.1.2 := concrete_category.congr_hom ((F.is_limit_pullback_cone U V).cone_point_unique_up_to_iso_inv_comp (CommRing.pullback_cone_is_limit _ _) walking_cospan.right) x end Top.sheaf
a16932d71aebc8584ddf1a292a3644eacac9d036
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Widget/UserWidget.lean
f4e3354a71394eff6648a0325359a510703ab6cd
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach" ]
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
6,755
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: E.W.Ayers -/ import Lean.Elab.Eval import Lean.Server.Rpc.RequestHandling open Lean namespace Lean.Widget /-- A custom piece of code that is run on the editor client. The editor can use the `Lean.Widget.getWidgetSource` RPC method to get this object. See the [manual entry](doc/widgets.md) above this declaration for more information on how to use the widgets system. -/ structure WidgetSource where /-- Sourcetext of the code to run.-/ sourcetext : String deriving Inhabited, ToJson, FromJson /-- Use this structure and the `@[widget]` attribute to define your own widgets. ```lean @[widget] def rubiks : UserWidgetDefinition := { name := "Rubiks cube app" javascript := include_str ... } ``` -/ structure UserWidgetDefinition where /-- Pretty name of user widget to display to the user. -/ name : String /-- An ESmodule that exports a react component to render. -/ javascript: String deriving Inhabited, ToJson, FromJson structure UserWidget where id : Name /-- Pretty name of widget to display to the user.-/ name : String javascriptHash: UInt64 deriving Inhabited, ToJson, FromJson private abbrev WidgetSourceRegistry := SimplePersistentEnvExtension (UInt64 × Name) (RBMap UInt64 Name compare) -- Mapping widgetSourceId to hash of sourcetext builtin_initialize userWidgetRegistry : MapDeclarationExtension UserWidget ← mkMapDeclarationExtension builtin_initialize widgetSourceRegistry : WidgetSourceRegistry ← registerSimplePersistentEnvExtension { addImportedFn := fun xss => xss.foldl (Array.foldl (fun s n => s.insert n.1 n.2)) ∅ addEntryFn := fun s n => s.insert n.1 n.2 toArrayFn := fun es => es.toArray } private unsafe def getUserWidgetDefinitionUnsafe (decl : Name) : CoreM UserWidgetDefinition := evalConstCheck UserWidgetDefinition ``UserWidgetDefinition decl @[implemented_by getUserWidgetDefinitionUnsafe] private opaque getUserWidgetDefinition (decl : Name) : CoreM UserWidgetDefinition private def attributeImpl : AttributeImpl where name := `widget descr := "Mark a string as static code that can be loaded by a widget handler." applicationTime := AttributeApplicationTime.afterCompilation add decl _stx _kind := do let env ← getEnv let defn ← getUserWidgetDefinition decl let javascriptHash := hash defn.javascript let env := userWidgetRegistry.insert env decl {id := decl, name := defn.name, javascriptHash} let env := widgetSourceRegistry.addEntry env (javascriptHash, decl) setEnv <| env builtin_initialize registerBuiltinAttribute attributeImpl /-- Input for `getWidgetSource` RPC. -/ structure GetWidgetSourceParams where /-- The hash of the sourcetext to retrieve. -/ hash: UInt64 pos : Lean.Lsp.Position deriving ToJson, FromJson open Server RequestM in @[server_rpc_method] def getWidgetSource (args : GetWidgetSourceParams) : RequestM (RequestTask WidgetSource) := do let doc ← readDoc let pos := doc.meta.text.lspPosToUtf8Pos args.pos let notFound := throwThe RequestError ⟨.invalidParams, s!"No registered user-widget with hash {args.hash}"⟩ withWaitFindSnap doc (notFoundX := notFound) (fun s => s.endPos >= pos || (widgetSourceRegistry.getState s.env).contains args.hash) fun snap => do if let some id := widgetSourceRegistry.getState snap.env |>.find? args.hash then runCoreM snap do return {sourcetext := (← getUserWidgetDefinition id).javascript} else notFound open Lean Elab /-- Try to retrieve the `UserWidgetInfo` at a particular position. -/ def widgetInfosAt? (text : FileMap) (t : InfoTree) (hoverPos : String.Pos) : List UserWidgetInfo := t.deepestNodes fun | _ctx, i@(Info.ofUserWidgetInfo wi), _cs => do if let (some pos, some tailPos) := (i.pos?, i.tailPos?) then let trailSize := i.stx.getTrailingSize -- show info at EOF even if strictly outside token + trail let atEOF := tailPos.byteIdx + trailSize == text.source.endPos.byteIdx guard <| pos ≤ hoverPos ∧ (hoverPos.byteIdx < tailPos.byteIdx + trailSize || atEOF) return wi else failure | _, _, _ => none /-- UserWidget accompanied by component props. -/ structure UserWidgetInstance extends UserWidget where /-- Arguments to be fed to the widget's main component. -/ props : Json /-- The location of the widget instance in the Lean file. -/ range? : Option Lsp.Range deriving ToJson, FromJson /-- Output of `getWidgets` RPC.-/ structure GetWidgetsResponse where widgets : Array UserWidgetInstance deriving ToJson, FromJson open Lean Server RequestM in /-- Get the `UserWidget`s present at a particular position. -/ @[server_rpc_method] def getWidgets (args : Lean.Lsp.Position) : RequestM (RequestTask (GetWidgetsResponse)) := do let doc ← readDoc let filemap := doc.meta.text let pos := filemap.lspPosToUtf8Pos args withWaitFindSnap doc (·.endPos >= pos) (notFoundX := return ⟨∅⟩) fun snap => do let env := snap.env let ws := widgetInfosAt? filemap snap.infoTree pos let ws ← ws.toArray.mapM (fun (w : UserWidgetInfo) => do let some widget := userWidgetRegistry.find? env w.widgetId | throw <| RequestError.mk .invalidParams s!"No registered user-widget with id {w.widgetId}" return { widget with props := w.props range? := String.Range.toLspRange filemap <$> Syntax.getRange? w.stx }) return {widgets := ws} /-- Save a user-widget instance to the infotree. The given `widgetId` should be the declaration name of the widget definition. -/ def saveWidgetInfo [Monad m] [MonadEnv m] [MonadError m] [MonadInfoTree m] (widgetId : Name) (props : Json) (stx : Syntax): m Unit := do let info := Info.ofUserWidgetInfo { widgetId := widgetId props := props stx := stx } pushInfoLeaf info /-! # Widget command -/ /-- Use `#widget <widgetname> <props>` to display a widget. Useful for debugging widgets. -/ syntax (name := widgetCmd) "#widget " ident ppSpace term : command open Lean Lean.Meta Lean.Elab Lean.Elab.Term in private unsafe def evalJsonUnsafe (stx : Syntax) : TermElabM Json := Lean.Elab.Term.evalTerm Json (mkConst ``Json) stx @[implemented_by evalJsonUnsafe] private opaque evalJson (stx : Syntax) : TermElabM Json open Elab Command in @[command_elab widgetCmd] def elabWidgetCmd : CommandElab := fun | stx@`(#widget $id:ident $props) => do let props : Json ← runTermElabM fun _ => evalJson props saveWidgetInfo id.getId props stx | _ => throwUnsupportedSyntax end Lean.Widget
ff9ce73ce467d7b95e676f097e3258ac5f9daebb
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/linear_algebra/free_module/pid.lean
a54dbec23e0bbb64a1c62097903756bdbc65e8b8
[ "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
29,317
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import linear_algebra.dimension import linear_algebra.free_module.basic import ring_theory.principal_ideal_domain import ring_theory.finiteness /-! # Free modules over PID > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A free `R`-module `M` is a module with a basis over `R`, equivalently it is an `R`-module linearly equivalent to `ι →₀ R` for some `ι`. This file proves a submodule of a free `R`-module of finite rank is also a free `R`-module of finite rank, if `R` is a principal ideal domain (PID), i.e. we have instances `[is_domain R] [is_principal_ideal_ring R]`. We express "free `R`-module of finite rank" as a module `M` which has a basis `b : ι → R`, where `ι` is a `fintype`. We call the cardinality of `ι` the rank of `M` in this file; it would be equal to `finrank R M` if `R` is a field and `M` is a vector space. ## Main results In this section, `M` is a free and finitely generated `R`-module, and `N` is a submodule of `M`. - `submodule.induction_on_rank`: if `P` holds for `⊥ : submodule R M` and if `P N` follows from `P N'` for all `N'` that are of lower rank, then `P` holds on all submodules - `submodule.exists_basis_of_pid`: if `R` is a PID, then `N : submodule R M` is free and finitely generated. This is the first part of the structure theorem for modules. - `submodule.smith_normal_form`: if `R` is a PID, then `M` has a basis `bM` and `N` has a basis `bN` such that `bN i = a i • bM i`. Equivalently, a linear map `f : M →ₗ M` with `range f = N` can be written as a matrix in Smith normal form, a diagonal matrix with the coefficients `a i` along the diagonal. ## Tags free module, finitely generated module, rank, structure theorem -/ open_locale big_operators universes u v section ring variables {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] variables {ι : Type*} (b : basis ι R M) open submodule.is_principal submodule lemma eq_bot_of_generator_maximal_map_eq_zero (b : basis ι R M) {N : submodule R M} {ϕ : M →ₗ[R] R} (hϕ : ∀ (ψ : M →ₗ[R] R), ¬ N.map ϕ < N.map ψ) [(N.map ϕ).is_principal] (hgen : generator (N.map ϕ) = (0 : R)) : N = ⊥ := begin rw submodule.eq_bot_iff, intros x hx, refine b.ext_elem (λ i, _), rw (eq_bot_iff_generator_eq_zero _).mpr hgen at hϕ, rw [linear_equiv.map_zero, finsupp.zero_apply], exact (submodule.eq_bot_iff _).mp (not_bot_lt_iff.1 $ hϕ ((finsupp.lapply i) ∘ₗ ↑b.repr)) _ ⟨x, hx, rfl⟩ end lemma eq_bot_of_generator_maximal_submodule_image_eq_zero {N O : submodule R M} (b : basis ι R O) (hNO : N ≤ O) {ϕ : O →ₗ[R] R} (hϕ : ∀ (ψ : O →ₗ[R] R), ¬ ϕ.submodule_image N < ψ.submodule_image N) [(ϕ.submodule_image N).is_principal] (hgen : generator (ϕ.submodule_image N) = 0) : N = ⊥ := begin rw submodule.eq_bot_iff, intros x hx, refine congr_arg coe (show (⟨x, hNO hx⟩ : O) = 0, from b.ext_elem (λ i, _)), rw (eq_bot_iff_generator_eq_zero _).mpr hgen at hϕ, rw [linear_equiv.map_zero, finsupp.zero_apply], refine (submodule.eq_bot_iff _).mp (not_bot_lt_iff.1 $ hϕ ((finsupp.lapply i) ∘ₗ ↑b.repr)) _ _, exact (linear_map.mem_submodule_image_of_le hNO).mpr ⟨x, hx, rfl⟩ end end ring section is_domain variables {ι : Type*} {R : Type*} [comm_ring R] [is_domain R] variables {M : Type*} [add_comm_group M] [module R M] {b : ι → M} open submodule.is_principal set submodule lemma dvd_generator_iff {I : ideal R} [I.is_principal] {x : R} (hx : x ∈ I) : x ∣ generator I ↔ I = ideal.span {x} := begin conv_rhs { rw [← span_singleton_generator I] }, erw [ideal.span_singleton_eq_span_singleton, ← dvd_dvd_iff_associated, ← mem_iff_generator_dvd], exact ⟨λ h, ⟨hx, h⟩, λ h, h.2⟩ end end is_domain section principal_ideal_domain open submodule.is_principal set submodule variables {ι : Type*} {R : Type*} [comm_ring R] [is_domain R] [is_principal_ideal_ring R] variables {M : Type*} [add_comm_group M] [module R M] {b : ι → M} open submodule.is_principal lemma generator_maximal_submodule_image_dvd {N O : submodule R M} (hNO : N ≤ O) {ϕ : O →ₗ[R] R} (hϕ : ∀ (ψ : O →ₗ[R] R), ¬ ϕ.submodule_image N < ψ.submodule_image N) [(ϕ.submodule_image N).is_principal] (y : M) (yN : y ∈ N) (ϕy_eq : ϕ ⟨y, hNO yN⟩ = generator (ϕ.submodule_image N)) (ψ : O →ₗ[R] R) : generator (ϕ.submodule_image N) ∣ ψ ⟨y, hNO yN⟩ := begin let a : R := generator (ϕ.submodule_image N), let d : R := is_principal.generator (submodule.span R {a, ψ ⟨y, hNO yN⟩}), have d_dvd_left : d ∣ a := (mem_iff_generator_dvd _).mp (subset_span (mem_insert _ _)), have d_dvd_right : d ∣ ψ ⟨y, hNO yN⟩ := (mem_iff_generator_dvd _).mp (subset_span (mem_insert_of_mem _ (mem_singleton _))), refine dvd_trans _ d_dvd_right, rw [dvd_generator_iff, ideal.span, ← span_singleton_generator (submodule.span R {a, ψ ⟨y, hNO yN⟩})], obtain ⟨r₁, r₂, d_eq⟩ : ∃ r₁ r₂ : R, d = r₁ * a + r₂ * ψ ⟨y, hNO yN⟩, { obtain ⟨r₁, r₂', hr₂', hr₁⟩ := mem_span_insert.mp (is_principal.generator_mem (submodule.span R {a, ψ ⟨y, hNO yN⟩})), obtain ⟨r₂, rfl⟩ := mem_span_singleton.mp hr₂', exact ⟨r₁, r₂, hr₁⟩ }, let ψ' : O →ₗ[R] R := r₁ • ϕ + r₂ • ψ, have : span R {d} ≤ ψ'.submodule_image N, { rw [span_le, singleton_subset_iff, set_like.mem_coe, linear_map.mem_submodule_image_of_le hNO], refine ⟨y, yN, _⟩, change r₁ * ϕ ⟨y, hNO yN⟩ + r₂ * ψ ⟨y, hNO yN⟩ = d, rw [d_eq, ϕy_eq] }, refine le_antisymm (this.trans (le_of_eq _)) (ideal.span_singleton_le_span_singleton.mpr d_dvd_left), rw span_singleton_generator, apply (le_trans _ this).eq_of_not_gt (hϕ ψ'), rw [← span_singleton_generator (ϕ.submodule_image N)], exact ideal.span_singleton_le_span_singleton.mpr d_dvd_left, { exact subset_span (mem_insert _ _) } end /-- The induction hypothesis of `submodule.basis_of_pid` and `submodule.smith_normal_form`. Basically, it says: let `N ≤ M` be a pair of submodules, then we can find a pair of submodules `N' ≤ M'` of strictly smaller rank, whose basis we can extend to get a basis of `N` and `M`. Moreover, if the basis for `M'` is up to scalars a basis for `N'`, then the basis we find for `M` is up to scalars a basis for `N`. For `basis_of_pid` we only need the first half and can fix `M = ⊤`, for `smith_normal_form` we need the full statement, but must also feed in a basis for `M` using `basis_of_pid` to keep the induction going. -/ lemma submodule.basis_of_pid_aux [finite ι] {O : Type*} [add_comm_group O] [module R O] (M N : submodule R O) (b'M : basis ι R M) (N_bot : N ≠ ⊥) (N_le_M : N ≤ M) : ∃ (y ∈ M) (a : R) (hay : a • y ∈ N) (M' ≤ M) (N' ≤ N) (N'_le_M' : N' ≤ M') (y_ortho_M' : ∀ (c : R) (z : O), z ∈ M' → c • y + z = 0 → c = 0) (ay_ortho_N' : ∀ (c : R) (z : O), z ∈ N' → c • a • y + z = 0 → c = 0), ∀ (n') (bN' : basis (fin n') R N'), ∃ (bN : basis (fin (n' + 1)) R N), ∀ (m') (hn'm' : n' ≤ m') (bM' : basis (fin m') R M'), ∃ (hnm : (n' + 1) ≤ (m' + 1)) (bM : basis (fin (m' + 1)) R M), ∀ (as : fin n' → R) (h : ∀ (i : fin n'), (bN' i : O) = as i • (bM' (fin.cast_le hn'm' i) : O)), ∃ (as' : fin (n' + 1) → R), ∀ (i : fin (n' + 1)), (bN i : O) = as' i • (bM (fin.cast_le hnm i) : O) := begin -- Let `ϕ` be a maximal projection of `M` onto `R`, in the sense that there is -- no `ψ` whose image of `N` is larger than `ϕ`'s image of `N`. have : ∃ ϕ : M →ₗ[R] R, ∀ (ψ : M →ₗ[R] R), ¬ ϕ.submodule_image N < ψ.submodule_image N, { obtain ⟨P, P_eq, P_max⟩ := set_has_maximal_iff_noetherian.mpr (infer_instance : is_noetherian R R) _ (show (set.range (λ ψ : M →ₗ[R] R, ψ.submodule_image N)).nonempty, from ⟨_, set.mem_range.mpr ⟨0, rfl⟩⟩), obtain ⟨ϕ, rfl⟩ := set.mem_range.mp P_eq, exact ⟨ϕ, λ ψ hψ, P_max _ ⟨_, rfl⟩ hψ⟩ }, let ϕ := this.some, have ϕ_max := this.some_spec, -- Since `ϕ(N)` is a `R`-submodule of the PID `R`, -- it is principal and generated by some `a`. let a := generator (ϕ.submodule_image N), have a_mem : a ∈ ϕ.submodule_image N := generator_mem _, -- If `a` is zero, then the submodule is trivial. So let's assume `a ≠ 0`, `N ≠ ⊥`. by_cases a_zero : a = 0, { have := eq_bot_of_generator_maximal_submodule_image_eq_zero b'M N_le_M ϕ_max a_zero, contradiction }, -- We claim that `ϕ⁻¹ a = y` can be taken as basis element of `N`. obtain ⟨y, yN, ϕy_eq⟩ := (linear_map.mem_submodule_image_of_le N_le_M).mp a_mem, have ϕy_ne_zero : ϕ ⟨y, N_le_M yN⟩ ≠ 0 := λ h, a_zero (ϕy_eq.symm.trans h), -- Write `y` as `a • y'` for some `y'`. have hdvd : ∀ i, a ∣ b'M.coord i ⟨y, N_le_M yN⟩ := λ i, generator_maximal_submodule_image_dvd N_le_M ϕ_max y yN ϕy_eq (b'M.coord i), choose c hc using hdvd, casesI nonempty_fintype ι, let y' : O := ∑ i, c i • b'M i, have y'M : y' ∈ M := M.sum_mem (λ i _, M.smul_mem (c i) (b'M i).2), have mk_y' : (⟨y', y'M⟩ : M) = ∑ i, c i • b'M i := subtype.ext (show y' = M.subtype _, by { simp only [linear_map.map_sum, linear_map.map_smul], refl }), have a_smul_y' : a • y' = y, { refine congr_arg coe (show (a • ⟨y', y'M⟩ : M) = ⟨y, N_le_M yN⟩, from _), rw [← b'M.sum_repr ⟨y, N_le_M yN⟩, mk_y', finset.smul_sum], refine finset.sum_congr rfl (λ i _, _), rw [← mul_smul, ← hc], refl }, -- We found an `y` and an `a`! refine ⟨y', y'M, a, a_smul_y'.symm ▸ yN, _⟩, have ϕy'_eq : ϕ ⟨y', y'M⟩ = 1 := mul_left_cancel₀ a_zero (calc a • ϕ ⟨y', y'M⟩ = ϕ ⟨a • y', _⟩ : (ϕ.map_smul a ⟨y', y'M⟩).symm ... = ϕ ⟨y, N_le_M yN⟩ : by simp only [a_smul_y'] ... = a : ϕy_eq ... = a * 1 : (mul_one a).symm), have ϕy'_ne_zero : ϕ ⟨y', y'M⟩ ≠ 0 := by simpa only [ϕy'_eq] using one_ne_zero, -- `M' := ker (ϕ : M → R)` is smaller than `M` and `N' := ker (ϕ : N → R)` is smaller than `N`. let M' : submodule R O := ϕ.ker.map M.subtype, let N' : submodule R O := (ϕ.comp (of_le N_le_M)).ker.map N.subtype, have M'_le_M : M' ≤ M := M.map_subtype_le ϕ.ker, have N'_le_M' : N' ≤ M', { intros x hx, simp only [mem_map, linear_map.mem_ker] at hx ⊢, obtain ⟨⟨x, xN⟩, hx, rfl⟩ := hx, exact ⟨⟨x, N_le_M xN⟩, hx, rfl⟩ }, have N'_le_N : N' ≤ N := N.map_subtype_le (ϕ.comp (of_le N_le_M)).ker, -- So fill in those results as well. refine ⟨M', M'_le_M, N', N'_le_N, N'_le_M', _⟩, -- Note that `y'` is orthogonal to `M'`. have y'_ortho_M' : ∀ (c : R) z ∈ M', c • y' + z = 0 → c = 0, { intros c x xM' hc, obtain ⟨⟨x, xM⟩, hx', rfl⟩ := submodule.mem_map.mp xM', rw linear_map.mem_ker at hx', have hc' : (c • ⟨y', y'M⟩ + ⟨x, xM⟩ : M) = 0 := subtype.coe_injective hc, simpa only [linear_map.map_add, linear_map.map_zero, linear_map.map_smul, smul_eq_mul, add_zero, mul_eq_zero, ϕy'_ne_zero, hx', or_false] using congr_arg ϕ hc' }, -- And `a • y'` is orthogonal to `N'`. have ay'_ortho_N' : ∀ (c : R) z ∈ N', c • a • y' + z = 0 → c = 0, { intros c z zN' hc, refine (mul_eq_zero.mp (y'_ortho_M' (a * c) z (N'_le_M' zN') _)).resolve_left a_zero, rw [mul_comm, mul_smul, hc] }, -- So we can extend a basis for `N'` with `y` refine ⟨y'_ortho_M', ay'_ortho_N', λ n' bN', ⟨_, _⟩⟩, { refine basis.mk_fin_cons_of_le y yN bN' N'_le_N _ _, { intros c z zN' hc, refine ay'_ortho_N' c z zN' _, rwa ← a_smul_y' at hc }, { intros z zN, obtain ⟨b, hb⟩ : _ ∣ ϕ ⟨z, N_le_M zN⟩ := generator_submodule_image_dvd_of_mem N_le_M ϕ zN, refine ⟨-b, submodule.mem_map.mpr ⟨⟨_, N.sub_mem zN (N.smul_mem b yN)⟩, _, _⟩⟩, { refine linear_map.mem_ker.mpr (show ϕ (⟨z, N_le_M zN⟩ - b • ⟨y, N_le_M yN⟩) = 0, from _), rw [linear_map.map_sub, linear_map.map_smul, hb, ϕy_eq, smul_eq_mul, mul_comm, sub_self] }, { simp only [sub_eq_add_neg, neg_smul], refl } } }, -- And extend a basis for `M'` with `y'` intros m' hn'm' bM', refine ⟨nat.succ_le_succ hn'm', _, _⟩, { refine basis.mk_fin_cons_of_le y' y'M bM' M'_le_M y'_ortho_M' _, intros z zM, refine ⟨-ϕ ⟨z, zM⟩, ⟨⟨z, zM⟩ - (ϕ ⟨z, zM⟩) • ⟨y', y'M⟩, linear_map.mem_ker.mpr _, _⟩⟩, { rw [linear_map.map_sub, linear_map.map_smul, ϕy'_eq, smul_eq_mul, mul_one, sub_self] }, { rw [linear_map.map_sub, linear_map.map_smul, sub_eq_add_neg, neg_smul], refl } }, -- It remains to show the extended bases are compatible with each other. intros as h, refine ⟨fin.cons a as, _⟩, intro i, rw [basis.coe_mk_fin_cons_of_le, basis.coe_mk_fin_cons_of_le], refine fin.cases _ (λ i, _) i, { simp only [fin.cons_zero, fin.cast_le_zero], exact a_smul_y'.symm }, { rw fin.cast_le_succ, simp only [fin.cons_succ, coe_of_le, h i] } end /-- A submodule of a free `R`-module of finite rank is also a free `R`-module of finite rank, if `R` is a principal ideal domain. This is a `lemma` to make the induction a bit easier. To actually access the basis, see `submodule.basis_of_pid`. See also the stronger version `submodule.smith_normal_form`. -/ lemma submodule.nonempty_basis_of_pid {ι : Type*} [finite ι] (b : basis ι R M) (N : submodule R M) : ∃ (n : ℕ), nonempty (basis (fin n) R N) := begin haveI := classical.dec_eq M, casesI nonempty_fintype ι, refine N.induction_on_rank b _ _, intros N ih, let b' := (b.reindex (fintype.equiv_fin ι)).map (linear_equiv.of_top _ rfl).symm, by_cases N_bot : N = ⊥, { subst N_bot, exact ⟨0, ⟨basis.empty _⟩⟩ }, obtain ⟨y, -, a, hay, M', -, N', N'_le_N, -, -, ay_ortho, h'⟩ := submodule.basis_of_pid_aux ⊤ N b' N_bot le_top, obtain ⟨n', ⟨bN'⟩⟩ := ih N' N'_le_N _ hay ay_ortho, obtain ⟨bN, hbN⟩ := h' n' bN', exact ⟨n' + 1, ⟨bN⟩⟩ end /-- A submodule of a free `R`-module of finite rank is also a free `R`-module of finite rank, if `R` is a principal ideal domain. See also the stronger version `submodule.smith_normal_form`. -/ noncomputable def submodule.basis_of_pid {ι : Type*} [finite ι] (b : basis ι R M) (N : submodule R M) : Σ (n : ℕ), (basis (fin n) R N) := ⟨_, (N.nonempty_basis_of_pid b).some_spec.some⟩ lemma submodule.basis_of_pid_bot {ι : Type*} [finite ι] (b : basis ι R M) : submodule.basis_of_pid b ⊥ = ⟨0, basis.empty _⟩ := begin obtain ⟨n, b'⟩ := submodule.basis_of_pid b ⊥, let e : fin n ≃ fin 0 := b'.index_equiv (basis.empty _ : basis (fin 0) R (⊥ : submodule R M)), obtain rfl : n = 0 := by simpa using fintype.card_eq.mpr ⟨e⟩, exact sigma.eq rfl (basis.eq_of_apply_eq $ fin_zero_elim) end /-- A submodule inside a free `R`-submodule of finite rank is also a free `R`-module of finite rank, if `R` is a principal ideal domain. See also the stronger version `submodule.smith_normal_form_of_le`. -/ noncomputable def submodule.basis_of_pid_of_le {ι : Type*} [finite ι] {N O : submodule R M} (hNO : N ≤ O) (b : basis ι R O) : Σ (n : ℕ), basis (fin n) R N := let ⟨n, bN'⟩ := submodule.basis_of_pid b (N.comap O.subtype) in ⟨n, bN'.map (submodule.comap_subtype_equiv_of_le hNO)⟩ /-- A submodule inside the span of a linear independent family is a free `R`-module of finite rank, if `R` is a principal ideal domain. -/ noncomputable def submodule.basis_of_pid_of_le_span {ι : Type*} [finite ι] {b : ι → M} (hb : linear_independent R b) {N : submodule R M} (le : N ≤ submodule.span R (set.range b)) : Σ (n : ℕ), basis (fin n) R N := submodule.basis_of_pid_of_le le (basis.span hb) variable {M} /-- A finite type torsion free module over a PID admits a basis. -/ noncomputable def module.basis_of_finite_type_torsion_free [fintype ι] {s : ι → M} (hs : span R (range s) = ⊤) [no_zero_smul_divisors R M] : Σ (n : ℕ), basis (fin n) R M := begin classical, -- We define `N` as the submodule spanned by a maximal linear independent subfamily of `s` have := exists_maximal_independent R s, let I : set ι := this.some, obtain ⟨indepI : linear_independent R (s ∘ coe : I → M), hI : ∀ i ∉ I, ∃ a : R, a ≠ 0 ∧ a • s i ∈ span R (s '' I)⟩ := this.some_spec, let N := span R (range $ (s ∘ coe : I → M)), -- same as `span R (s '' I)` but more convenient let sI : I → N := λ i, ⟨s i.1, subset_span (mem_range_self i)⟩, -- `s` restricted to `I` let sI_basis : basis I R N, -- `s` restricted to `I` is a basis of `N` from basis.span indepI, -- Our first goal is to build `A ≠ 0` such that `A • M ⊆ N` have exists_a : ∀ i : ι, ∃ a : R, a ≠ 0 ∧ a • s i ∈ N, { intro i, by_cases hi : i ∈ I, { use [1, zero_ne_one.symm], rw one_smul, exact subset_span (mem_range_self (⟨i, hi⟩ : I)) }, { simpa [image_eq_range s I] using hI i hi } }, choose a ha ha' using exists_a, let A := ∏ i, a i, have hA : A ≠ 0, { rw finset.prod_ne_zero_iff, simpa using ha }, -- `M ≃ A • M` because `M` is torsion free and `A ≠ 0` let φ : M →ₗ[R] M := linear_map.lsmul R M A, have : φ.ker = ⊥, from linear_map.ker_lsmul hA, let ψ : M ≃ₗ[R] φ.range := linear_equiv.of_injective φ (linear_map.ker_eq_bot.mp this), have : φ.range ≤ N, -- as announced, `A • M ⊆ N` { suffices : ∀ i, φ (s i) ∈ N, { rw [linear_map.range_eq_map, ← hs, φ.map_span_le], rintros _ ⟨i, rfl⟩, apply this }, intro i, calc (∏ j, a j) • s i = (∏ j in {i}ᶜ, a j) • a i • s i : by rw [fintype.prod_eq_prod_compl_mul i, mul_smul] ... ∈ N : N.smul_mem _ (ha' i) }, -- Since a submodule of a free `R`-module is free, we get that `A • M` is free obtain ⟨n, b : basis (fin n) R φ.range⟩ := submodule.basis_of_pid_of_le this sI_basis, -- hence `M` is free. exact ⟨n, b.map ψ.symm⟩ end lemma module.free_of_finite_type_torsion_free [finite ι] {s : ι → M} (hs : span R (range s) = ⊤) [no_zero_smul_divisors R M] : module.free R M := begin casesI nonempty_fintype ι, obtain ⟨n, b⟩ : Σ n, basis (fin n) R M := module.basis_of_finite_type_torsion_free hs, exact module.free.of_basis b, end /-- A finite type torsion free module over a PID admits a basis. -/ noncomputable def module.basis_of_finite_type_torsion_free' [module.finite R M] [no_zero_smul_divisors R M] : Σ (n : ℕ), basis (fin n) R M := module.basis_of_finite_type_torsion_free module.finite.exists_fin.some_spec.some_spec lemma module.free_of_finite_type_torsion_free' [module.finite R M] [no_zero_smul_divisors R M] : module.free R M := begin obtain ⟨n, b⟩ : Σ n, basis (fin n) R M := module.basis_of_finite_type_torsion_free', exact module.free.of_basis b, end section smith_normal /-- A Smith normal form basis for a submodule `N` of a module `M` consists of bases for `M` and `N` such that the inclusion map `N → M` can be written as a (rectangular) matrix with `a` along the diagonal: in Smith normal form. -/ @[nolint has_nonempty_instance] structure basis.smith_normal_form (N : submodule R M) (ι : Type*) (n : ℕ) := (bM : basis ι R M) (bN : basis (fin n) R N) (f : fin n ↪ ι) (a : fin n → R) (snf : ∀ i, (bN i : M) = a i • bM (f i)) /-- If `M` is finite free over a PID `R`, then any submodule `N` is free and we can find a basis for `M` and `N` such that the inclusion map is a diagonal matrix in Smith normal form. See `submodule.smith_normal_form_of_le` for a version of this theorem that returns a `basis.smith_normal_form`. This is a strengthening of `submodule.basis_of_pid_of_le`. -/ theorem submodule.exists_smith_normal_form_of_le [finite ι] (b : basis ι R M) (N O : submodule R M) (N_le_O : N ≤ O) : ∃ (n o : ℕ) (hno : n ≤ o) (bO : basis (fin o) R O) (bN : basis (fin n) R N) (a : fin n → R), ∀ i, (bN i : M) = a i • bO (fin.cast_le hno i) := begin casesI nonempty_fintype ι, revert N, refine induction_on_rank b _ _ O, intros M ih N N_le_M, obtain ⟨m, b'M⟩ := M.basis_of_pid b, by_cases N_bot : N = ⊥, { subst N_bot, exact ⟨0, m, nat.zero_le _, b'M, basis.empty _, fin_zero_elim, fin_zero_elim⟩ }, obtain ⟨y, hy, a, hay, M', M'_le_M, N', N'_le_N, N'_le_M', y_ortho, ay_ortho, h⟩ := submodule.basis_of_pid_aux M N b'M N_bot N_le_M, obtain ⟨n', m', hn'm', bM', bN', as', has'⟩ := ih M' M'_le_M y hy y_ortho N' N'_le_M', obtain ⟨bN, h'⟩ := h n' bN', obtain ⟨hmn, bM, h''⟩ := h' m' hn'm' bM', obtain ⟨as, has⟩ := h'' as' has', exact ⟨_, _, hmn, bM, bN, as, has⟩ end /-- If `M` is finite free over a PID `R`, then any submodule `N` is free and we can find a basis for `M` and `N` such that the inclusion map is a diagonal matrix in Smith normal form. See `submodule.exists_smith_normal_form_of_le` for a version of this theorem that doesn't need to map `N` into a submodule of `O`. This is a strengthening of `submodule.basis_of_pid_of_le`. -/ noncomputable def submodule.smith_normal_form_of_le [finite ι] (b : basis ι R M) (N O : submodule R M) (N_le_O : N ≤ O) : Σ (o n : ℕ), basis.smith_normal_form (N.comap O.subtype) (fin o) n := begin choose n o hno bO bN a snf using N.exists_smith_normal_form_of_le b O N_le_O, refine ⟨o, n, bO, bN.map (comap_subtype_equiv_of_le N_le_O).symm, (fin.cast_le hno).to_embedding, a, λ i, _⟩, ext, simp only [snf, basis.map_apply, submodule.comap_subtype_equiv_of_le_symm_apply_coe_coe, submodule.coe_smul_of_tower, rel_embedding.coe_fn_to_embedding] end /-- If `M` is finite free over a PID `R`, then any submodule `N` is free and we can find a basis for `M` and `N` such that the inclusion map is a diagonal matrix in Smith normal form. This is a strengthening of `submodule.basis_of_pid`. See also `ideal.smith_normal_form`, which moreover proves that the dimension of an ideal is the same as the dimension of the whole ring. -/ noncomputable def submodule.smith_normal_form [finite ι] (b : basis ι R M) (N : submodule R M) : Σ (n : ℕ), basis.smith_normal_form N ι n := let ⟨m, n, bM, bN, f, a, snf⟩ := N.smith_normal_form_of_le b ⊤ le_top, bM' := bM.map (linear_equiv.of_top _ rfl), e := bM'.index_equiv b in ⟨n, bM'.reindex e, bN.map (comap_subtype_equiv_of_le le_top), f.trans e.to_embedding, a, λ i, by simp only [snf, basis.map_apply, linear_equiv.of_top_apply, submodule.coe_smul_of_tower, submodule.comap_subtype_equiv_of_le_apply_coe, coe_coe, basis.reindex_apply, equiv.to_embedding_apply, function.embedding.trans_apply, equiv.symm_apply_apply]⟩ section ideal variables {S : Type*} [comm_ring S] [is_domain S] [algebra R S] /-- If `S` a finite-dimensional ring extension of a PID `R` which is free as an `R`-module, then any nonzero `S`-ideal `I` is free as an `R`-submodule of `S`, and we can find a basis for `S` and `I` such that the inclusion map is a square diagonal matrix. See `ideal.exists_smith_normal_form` for a version of this theorem that doesn't need to map `I` into a submodule of `R`. This is a strengthening of `submodule.basis_of_pid`. -/ noncomputable def ideal.smith_normal_form [fintype ι] (b : basis ι R S) (I : ideal S) (hI : I ≠ ⊥) : basis.smith_normal_form (I.restrict_scalars R) ι (fintype.card ι) := let ⟨n, bS, bI, f, a, snf⟩ := (I.restrict_scalars R).smith_normal_form b in have eq : _ := ideal.rank_eq bS hI (bI.map ((restrict_scalars_equiv R S S I).restrict_scalars _)), let e : fin n ≃ fin (fintype.card ι) := fintype.equiv_of_card_eq (by rw [eq, fintype.card_fin]) in ⟨bS, bI.reindex e, e.symm.to_embedding.trans f, a ∘ e.symm, λ i, by simp only [snf, basis.coe_reindex, function.embedding.trans_apply, equiv.to_embedding_apply]⟩ variables [finite ι] /-- If `S` a finite-dimensional ring extension of a PID `R` which is free as an `R`-module, then any nonzero `S`-ideal `I` is free as an `R`-submodule of `S`, and we can find a basis for `S` and `I` such that the inclusion map is a square diagonal matrix. See also `ideal.smith_normal_form` for a version of this theorem that returns a `basis.smith_normal_form`. The definitions `ideal.ring_basis`, `ideal.self_basis`, `ideal.smith_coeffs` are (noncomputable) choices of values for this existential quantifier. -/ theorem ideal.exists_smith_normal_form (b : basis ι R S) (I : ideal S) (hI : I ≠ ⊥) : ∃ (b' : basis ι R S) (a : ι → R) (ab' : basis ι R I), ∀ i, (ab' i : S) = a i • b' i := by casesI nonempty_fintype ι; exact let ⟨bS, bI, f, a, snf⟩ := I.smith_normal_form b hI, e : fin (fintype.card ι) ≃ ι := equiv.of_bijective f ((fintype.bijective_iff_injective_and_card f).mpr ⟨f.injective, fintype.card_fin _⟩) in have fe : ∀ i, f (e.symm i) = i := e.apply_symm_apply, ⟨bS, a ∘ e.symm, (bI.reindex e).map ((restrict_scalars_equiv _ _ _ _).restrict_scalars R), λ i, by simp only [snf, fe, basis.map_apply, linear_equiv.restrict_scalars_apply, submodule.restrict_scalars_equiv_apply, basis.coe_reindex]⟩ /-- If `S` a finite-dimensional ring extension of a PID `R` which is free as an `R`-module, then any nonzero `S`-ideal `I` is free as an `R`-submodule of `S`, and we can find a basis for `S` and `I` such that the inclusion map is a square diagonal matrix; this is the basis for `S`. See `ideal.self_basis` for the basis on `I`, see `ideal.smith_coeffs` for the entries of the diagonal matrix and `ideal.self_basis_def` for the proof that the inclusion map forms a square diagonal matrix. -/ noncomputable def ideal.ring_basis (b : basis ι R S) (I : ideal S) (hI : I ≠ ⊥) : basis ι R S := (ideal.exists_smith_normal_form b I hI).some /-- If `S` a finite-dimensional ring extension of a PID `R` which is free as an `R`-module, then any nonzero `S`-ideal `I` is free as an `R`-submodule of `S`, and we can find a basis for `S` and `I` such that the inclusion map is a square diagonal matrix; this is the basis for `I`. See `ideal.ring_basis` for the basis on `S`, see `ideal.smith_coeffs` for the entries of the diagonal matrix and `ideal.self_basis_def` for the proof that the inclusion map forms a square diagonal matrix. -/ noncomputable def ideal.self_basis (b : basis ι R S) (I : ideal S) (hI : I ≠ ⊥) : basis ι R I := (ideal.exists_smith_normal_form b I hI).some_spec.some_spec.some /-- If `S` a finite-dimensional ring extension of a PID `R` which is free as an `R`-module, then any nonzero `S`-ideal `I` is free as an `R`-submodule of `S`, and we can find a basis for `S` and `I` such that the inclusion map is a square diagonal matrix; these are the entries of the diagonal matrix. See `ideal.ring_basis` for the basis on `S`, see `ideal.self_basis` for the basis on `I`, and `ideal.self_basis_def` for the proof that the inclusion map forms a square diagonal matrix. -/ noncomputable def ideal.smith_coeffs (b : basis ι R S) (I : ideal S) (hI : I ≠ ⊥) : ι → R := (ideal.exists_smith_normal_form b I hI).some_spec.some /-- If `S` a finite-dimensional ring extension of a PID `R` which is free as an `R`-module, then any nonzero `S`-ideal `I` is free as an `R`-submodule of `S`, and we can find a basis for `S` and `I` such that the inclusion map is a square diagonal matrix. -/ @[simp] lemma ideal.self_basis_def (b : basis ι R S) (I : ideal S) (hI : I ≠ ⊥) : ∀ i, (ideal.self_basis b I hI i : S) = ideal.smith_coeffs b I hI i • ideal.ring_basis b I hI i := (ideal.exists_smith_normal_form b I hI).some_spec.some_spec.some_spec @[simp] lemma ideal.smith_coeffs_ne_zero (b : basis ι R S) (I : ideal S) (hI : I ≠ ⊥) (i) : ideal.smith_coeffs b I hI i ≠ 0 := begin intro hi, apply basis.ne_zero (ideal.self_basis b I hI) i, refine subtype.coe_injective _, simp [hi] end instance (F : Type u) [comm_ring F] [algebra F R] (b : basis ι R S) {I : ideal S} (hI : I ≠ ⊥) (i) : module F (R ⧸ ideal.span ({I.smith_coeffs b hI i} : set R)) := by apply_instance -- quotient.module' _ end ideal end smith_normal end principal_ideal_domain /-- A set of linearly independent vectors in a module `M` over a semiring `S` is also linearly independent over a subring `R` of `K`. -/ lemma linear_independent.restrict_scalars_algebras {R S M ι : Type*} [comm_semiring R] [semiring S] [add_comm_monoid M] [algebra R S] [module R M] [module S M] [is_scalar_tower R S M] (hinj : function.injective (algebra_map R S)) {v : ι → M} (li : linear_independent S v) : linear_independent R v := linear_independent.restrict_scalars (by rwa algebra.algebra_map_eq_smul_one' at hinj) li
e41f529751b51a92c0e30f8e073ca33ea26f1af9
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/continuous_function/polynomial.lean
56cfe2d42254814be280ed9e6d091dbf7db08e3c
[ "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
6,247
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import topology.algebra.polynomial import topology.continuous_function.algebra import topology.continuous_function.compact import topology.unit_interval /-! # Constructions relating polynomial functions and continuous functions. ## Main definitions * `polynomial.to_continuous_map_on p X`: for `X : set R`, interprets a polynomial `p` as a bundled continuous function in `C(X, R)`. * `polynomial.to_continuous_map_on_alg_hom`: the same, as an `R`-algebra homomorphism. * `polynomial_functions (X : set R) : subalgebra R C(X, R)`: polynomial functions as a subalgebra. * `polynomial_functions_separates_points (X : set R) : (polynomial_functions X).separates_points`: the polynomial functions separate points. -/ variables {R : Type*} open_locale polynomial namespace polynomial section variables [semiring R] [topological_space R] [topological_semiring R] /-- Every polynomial with coefficients in a topological semiring gives a (bundled) continuous function. -/ @[simps] def to_continuous_map (p : R[X]) : C(R, R) := ⟨λ x : R, p.eval x, by continuity⟩ /-- A polynomial as a continuous function, with domain restricted to some subset of the semiring of coefficients. (This is particularly useful when restricting to compact sets, e.g. `[0,1]`.) -/ @[simps] def to_continuous_map_on (p : R[X]) (X : set R) : C(X, R) := ⟨λ x : X, p.to_continuous_map x, by continuity⟩ -- TODO some lemmas about when `to_continuous_map_on` is injective? end section variables {α : Type*} [topological_space α] [comm_semiring R] [topological_space R] [topological_semiring R] @[simp] lemma aeval_continuous_map_apply (g : R[X]) (f : C(α, R)) (x : α) : ((polynomial.aeval f) g) x = g.eval (f x) := begin apply polynomial.induction_on' g, { intros p q hp hq, simp [hp, hq], }, { intros n a, simp [pi.pow_apply f x n], }, end end section noncomputable theory variables [comm_semiring R] [topological_space R] [topological_semiring R] /-- The algebra map from `polynomial R` to continuous functions `C(R, R)`. -/ @[simps] def to_continuous_map_alg_hom : R[X] →ₐ[R] C(R, R) := { to_fun := λ p, p.to_continuous_map, map_zero' := by { ext, simp, }, map_add' := by { intros, ext, simp, }, map_one' := by { ext, simp, }, map_mul' := by { intros, ext, simp, }, commutes' := by { intros, ext, simp [algebra.algebra_map_eq_smul_one], }, } /-- The algebra map from `polynomial R` to continuous functions `C(X, R)`, for any subset `X` of `R`. -/ @[simps] def to_continuous_map_on_alg_hom (X : set R) : R[X] →ₐ[R] C(X, R) := { to_fun := λ p, p.to_continuous_map_on X, map_zero' := by { ext, simp, }, map_add' := by { intros, ext, simp, }, map_one' := by { ext, simp, }, map_mul' := by { intros, ext, simp, }, commutes' := by { intros, ext, simp [algebra.algebra_map_eq_smul_one], }, } end end polynomial section variables [comm_semiring R] [topological_space R] [topological_semiring R] /-- The subalgebra of polynomial functions in `C(X, R)`, for `X` a subset of some topological semiring `R`. -/ def polynomial_functions (X : set R) : subalgebra R C(X, R) := (⊤ : subalgebra R R[X]).map (polynomial.to_continuous_map_on_alg_hom X) @[simp] lemma polynomial_functions_coe (X : set R) : (polynomial_functions X : set C(X, R)) = set.range (polynomial.to_continuous_map_on_alg_hom X) := by { ext, simp [polynomial_functions], } -- TODO: -- if `f : R → R` is an affine equivalence, then pulling back along `f` -- induces a normed algebra isomorphism between `polynomial_functions X` and -- `polynomial_functions (f ⁻¹' X)`, intertwining the pullback along `f` of `C(R, R)` to itself. lemma polynomial_functions_separates_points (X : set R) : (polynomial_functions X).separates_points := λ x y h, begin -- We use `polynomial.X`, then clean up. refine ⟨_, ⟨⟨_, ⟨⟨polynomial.X, ⟨algebra.mem_top, rfl⟩⟩, rfl⟩⟩, _⟩⟩, dsimp, simp only [polynomial.eval_X], exact (λ h', h (subtype.ext h')), end open_locale unit_interval open continuous_map /-- The preimage of polynomials on `[0,1]` under the pullback map by `x ↦ (b-a) * x + a` is the polynomials on `[a,b]`. -/ lemma polynomial_functions.comap'_comp_right_alg_hom_Icc_homeo_I (a b : ℝ) (h : a < b) : (polynomial_functions I).comap' (comp_right_alg_hom ℝ (Icc_homeo_I a b h).symm.to_continuous_map) = polynomial_functions (set.Icc a b) := begin ext f, fsplit, { rintro ⟨p, ⟨-,w⟩⟩, rw fun_like.ext_iff at w, dsimp at w, let q := p.comp ((b - a)⁻¹ • polynomial.X + polynomial.C (-a * (b-a)⁻¹)), refine ⟨q, ⟨_, _⟩⟩, { simp, }, { ext x, simp only [neg_mul, ring_hom.map_neg, ring_hom.map_mul, alg_hom.coe_to_ring_hom, polynomial.eval_X, polynomial.eval_neg, polynomial.eval_C, polynomial.eval_smul, smul_eq_mul, polynomial.eval_mul, polynomial.eval_add, polynomial.coe_aeval_eq_eval, polynomial.eval_comp, polynomial.to_continuous_map_on_alg_hom_apply, polynomial.to_continuous_map_on_to_fun, polynomial.to_continuous_map_to_fun], convert w ⟨_, _⟩; clear w, { -- why does `comm_ring.add` appear here!? change x = (Icc_homeo_I a b h).symm ⟨_ + _, _⟩, ext, simp only [Icc_homeo_I_symm_apply_coe, subtype.coe_mk], replace h : b - a ≠ 0 := sub_ne_zero_of_ne h.ne.symm, simp only [mul_add], field_simp, ring, }, { change _ + _ ∈ I, rw [mul_comm (b-a)⁻¹, ←neg_mul, ←add_mul, ←sub_eq_add_neg], have w₁ : 0 < (b-a)⁻¹ := inv_pos.mpr (sub_pos.mpr h), have w₂ : 0 ≤ (x : ℝ) - a := sub_nonneg.mpr x.2.1, have w₃ : (x : ℝ) - a ≤ b - a := sub_le_sub_right x.2.2 a, fsplit, { exact mul_nonneg w₂ (le_of_lt w₁), }, { rw [←div_eq_mul_inv, div_le_one (sub_pos.mpr h)], exact w₃, }, }, }, }, { rintro ⟨p, ⟨-,rfl⟩⟩, let q := p.comp ((b - a) • polynomial.X + polynomial.C a), refine ⟨q, ⟨_, _⟩⟩, { simp, }, { ext x, simp [mul_comm], }, }, end end
ea1bf9cafc331af99a1d3a7828572adee4b5abf0
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/ring_theory/finiteness.lean
68dfb94f4e6d47c11d089161fb5b14fd732dbd32
[ "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
35,152
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import group_theory.finiteness import ring_theory.algebra_tower import ring_theory.ideal.quotient import ring_theory.noetherian /-! # Finiteness conditions in commutative algebra In this file we define several notions of finiteness that are common in commutative algebra. ## Main declarations - `module.finite`, `algebra.finite`, `ring_hom.finite`, `alg_hom.finite` all of these express that some object is finitely generated *as module* over some base ring. - `algebra.finite_type`, `ring_hom.finite_type`, `alg_hom.finite_type` all of these express that some object is finitely generated *as algebra* over some base ring. - `algebra.finite_presentation`, `ring_hom.finite_presentation`, `alg_hom.finite_presentation` all of these express that some object is finitely presented *as algebra* over some base ring. -/ open function (surjective) open_locale big_operators section module_and_algebra variables (R A B M N : Type*) /-- A module over a semiring is `finite` if it is finitely generated as a module. -/ class module.finite [semiring R] [add_comm_monoid M] [module R M] : Prop := (out : (⊤ : submodule R M).fg) /-- An algebra over a commutative semiring is of `finite_type` if it is finitely generated over the base ring as algebra. -/ class algebra.finite_type [comm_semiring R] [semiring A] [algebra R A] : Prop := (out : (⊤ : subalgebra R A).fg) /-- An algebra over a commutative semiring is `finite_presentation` if it is the quotient of a polynomial ring in `n` variables by a finitely generated ideal. -/ def algebra.finite_presentation [comm_semiring R] [semiring A] [algebra R A] : Prop := ∃ (n : ℕ) (f : mv_polynomial (fin n) R →ₐ[R] A), surjective f ∧ f.to_ring_hom.ker.fg namespace module variables [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid N] [module R N] lemma finite_def {R M} [semiring R] [add_comm_monoid M] [module R M] : finite R M ↔ (⊤ : submodule R M).fg := ⟨λ h, h.1, λ h, ⟨h⟩⟩ @[priority 100] -- see Note [lower instance priority] instance is_noetherian.finite [is_noetherian R M] : finite R M := ⟨is_noetherian.noetherian ⊤⟩ namespace finite open _root_.submodule set lemma iff_add_monoid_fg {M : Type*} [add_comm_monoid M] : module.finite ℕ M ↔ add_monoid.fg M := ⟨λ h, add_monoid.fg_def.2 $ (fg_iff_add_submonoid_fg ⊤).1 (finite_def.1 h), λ h, finite_def.2 $ (fg_iff_add_submonoid_fg ⊤).2 (add_monoid.fg_def.1 h)⟩ lemma iff_add_group_fg {G : Type*} [add_comm_group G] : module.finite ℤ G ↔ add_group.fg G := ⟨λ h, add_group.fg_def.2 $ (fg_iff_add_subgroup_fg ⊤).1 (finite_def.1 h), λ h, finite_def.2 $ (fg_iff_add_subgroup_fg ⊤).2 (add_group.fg_def.1 h)⟩ variables {R M N} lemma exists_fin [finite R M] : ∃ (n : ℕ) (s : fin n → M), span R (range s) = ⊤ := submodule.fg_iff_exists_fin_generating_family.mp out lemma of_surjective [hM : finite R M] (f : M →ₗ[R] N) (hf : surjective f) : finite R N := ⟨begin rw [← linear_map.range_eq_top.2 hf, ← submodule.map_top], exact submodule.fg_map hM.1 end⟩ lemma of_injective [is_noetherian R N] (f : M →ₗ[R] N) (hf : function.injective f) : finite R M := ⟨fg_of_injective f hf⟩ variables (R) instance self : finite R R := ⟨⟨{1}, by simpa only [finset.coe_singleton] using ideal.span_singleton_one⟩⟩ variable (M) lemma of_restrict_scalars_finite (R A M : Type*) [comm_semiring R] [semiring A] [add_comm_monoid M] [module R M] [module A M] [algebra R A] [is_scalar_tower R A M] [hM : finite R M] : finite A M := begin rw [finite_def, fg_def] at hM ⊢, obtain ⟨S, hSfin, hSgen⟩ := hM, refine ⟨S, hSfin, eq_top_iff.2 _⟩, have := submodule.span_le_restrict_scalars R A S, rw hSgen at this, exact this end variables {R M} instance prod [hM : finite R M] [hN : finite R N] : finite R (M × N) := ⟨begin rw ← submodule.prod_top, exact submodule.fg_prod hM.1 hN.1 end⟩ lemma equiv [hM : finite R M] (e : M ≃ₗ[R] N) : finite R N := of_surjective (e : M →ₗ[R] N) e.surjective section algebra lemma trans {R : Type*} (A B : Type*) [comm_semiring R] [comm_semiring A] [algebra R A] [semiring B] [algebra R B] [algebra A B] [is_scalar_tower R A B] : ∀ [finite R A] [finite A B], finite R B | ⟨⟨s, hs⟩⟩ ⟨⟨t, ht⟩⟩ := ⟨submodule.fg_def.2 ⟨set.image2 (•) (↑s : set A) (↑t : set B), set.finite.image2 _ s.finite_to_set t.finite_to_set, by rw [set.image2_smul, submodule.span_smul hs (↑t : set B), ht, submodule.restrict_scalars_top]⟩⟩ @[priority 100] -- see Note [lower instance priority] instance finite_type {R : Type*} (A : Type*) [comm_semiring R] [comm_semiring A] [algebra R A] [hRA : finite R A] : algebra.finite_type R A := ⟨subalgebra.fg_of_submodule_fg hRA.1⟩ end algebra end finite end module namespace algebra variables [comm_ring R] [comm_ring A] [algebra R A] [comm_ring B] [algebra R B] variables [add_comm_group M] [module R M] variables [add_comm_group N] [module R N] namespace finite_type lemma self : finite_type R R := ⟨⟨{1}, subsingleton.elim _ _⟩⟩ section open_locale classical protected lemma mv_polynomial (ι : Type*) [fintype ι] : finite_type R (mv_polynomial ι R) := ⟨⟨finset.univ.image mv_polynomial.X, begin rw eq_top_iff, refine λ p, mv_polynomial.induction_on' p (λ u x, finsupp.induction u (subalgebra.algebra_map_mem _ x) (λ i n f hif hn ih, _)) (λ p q ihp ihq, subalgebra.add_mem _ ihp ihq), rw [add_comm, mv_polynomial.monomial_add_single], exact subalgebra.mul_mem _ ih (subalgebra.pow_mem _ (subset_adjoin $ finset.mem_image_of_mem _ $ finset.mem_univ _) _) end⟩⟩ end lemma of_restrict_scalars_finite_type [algebra A B] [is_scalar_tower R A B] [hB : finite_type R B] : finite_type A B := begin obtain ⟨S, hS⟩ := hB.out, refine ⟨⟨S, eq_top_iff.2 (λ b, _)⟩⟩, have le : adjoin R (S : set B) ≤ subalgebra.restrict_scalars R (adjoin A S), { apply (algebra.adjoin_le _ : _ ≤ (subalgebra.restrict_scalars R (adjoin A ↑S))), simp only [subalgebra.coe_restrict_scalars], exact algebra.subset_adjoin, }, exact le (eq_top_iff.1 hS b), end variables {R A B} lemma of_surjective (hRA : finite_type R A) (f : A →ₐ[R] B) (hf : surjective f) : finite_type R B := ⟨begin convert subalgebra.fg_map _ f hRA.1, simpa only [map_top f, @eq_comm _ ⊤, eq_top_iff, alg_hom.mem_range] using hf end⟩ lemma equiv (hRA : finite_type R A) (e : A ≃ₐ[R] B) : finite_type R B := hRA.of_surjective e e.surjective lemma trans [algebra A B] [is_scalar_tower R A B] (hRA : finite_type R A) (hAB : finite_type A B) : finite_type R B := ⟨fg_trans' hRA.1 hAB.1⟩ /-- An algebra is finitely generated if and only if it is a quotient of a polynomial ring whose variables are indexed by a finset. -/ lemma iff_quotient_mv_polynomial : (finite_type R A) ↔ ∃ (s : finset A) (f : (mv_polynomial {x // x ∈ s} R) →ₐ[R] A), (surjective f) := begin split, { rintro ⟨s, hs⟩, use [s, mv_polynomial.aeval coe], intro x, have hrw : (↑s : set A) = (λ (x : A), x ∈ s.val) := rfl, rw [← set.mem_range, ← alg_hom.coe_range, ← adjoin_eq_range, ← hrw, hs], exact set.mem_univ x }, { rintro ⟨s, ⟨f, hsur⟩⟩, exact finite_type.of_surjective (finite_type.mv_polynomial R {x // x ∈ s}) f hsur } end /-- An algebra is finitely generated if and only if it is a quotient of a polynomial ring whose variables are indexed by a fintype. -/ lemma iff_quotient_mv_polynomial' : (finite_type R A) ↔ ∃ (ι : Type u_2) (_ : fintype ι) (f : (mv_polynomial ι R) →ₐ[R] A), (surjective f) := begin split, { rw iff_quotient_mv_polynomial, rintro ⟨s, ⟨f, hsur⟩⟩, use [{x // x ∈ s}, by apply_instance, f, hsur] }, { rintro ⟨ι, ⟨hfintype, ⟨f, hsur⟩⟩⟩, letI : fintype ι := hfintype, exact finite_type.of_surjective (finite_type.mv_polynomial R ι) f hsur } end /-- An algebra is finitely generated if and only if it is a quotient of a polynomial ring in `n` variables. -/ lemma iff_quotient_mv_polynomial'' : (finite_type R A) ↔ ∃ (n : ℕ) (f : (mv_polynomial (fin n) R) →ₐ[R] A), (surjective f) := begin split, { rw iff_quotient_mv_polynomial', rintro ⟨ι, hfintype, ⟨f, hsur⟩⟩, letI := hfintype, obtain ⟨equiv⟩ := @fintype.trunc_equiv_fin ι (classical.dec_eq ι) hfintype, replace equiv := mv_polynomial.rename_equiv R equiv, exact ⟨fintype.card ι, alg_hom.comp f equiv.symm, function.surjective.comp hsur (alg_equiv.symm equiv).surjective⟩ }, { rintro ⟨n, ⟨f, hsur⟩⟩, exact finite_type.of_surjective (finite_type.mv_polynomial R (fin n)) f hsur } end /-- A finitely presented algebra is of finite type. -/ lemma of_finite_presentation : finite_presentation R A → finite_type R A := begin rintro ⟨n, f, hf⟩, apply (finite_type.iff_quotient_mv_polynomial'').2, exact ⟨n, f, hf.1⟩ end instance prod [hA : finite_type R A] [hB : finite_type R B] : finite_type R (A × B) := ⟨begin rw ← subalgebra.prod_top, exact subalgebra.fg_prod hA.1 hB.1 end⟩ end finite_type namespace finite_presentation variables {R A B} /-- An algebra over a Noetherian ring is finitely generated if and only if it is finitely presented. -/ lemma of_finite_type [is_noetherian_ring R] : finite_type R A ↔ finite_presentation R A := begin refine ⟨λ h, _, algebra.finite_type.of_finite_presentation⟩, obtain ⟨n, f, hf⟩ := algebra.finite_type.iff_quotient_mv_polynomial''.1 h, refine ⟨n, f, hf, _⟩, have hnoet : is_noetherian_ring (mv_polynomial (fin n) R) := by apply_instance, replace hnoet := (is_noetherian_ring_iff.1 hnoet).noetherian, exact hnoet f.to_ring_hom.ker, end /-- If `e : A ≃ₐ[R] B` and `A` is finitely presented, then so is `B`. -/ lemma equiv (hfp : finite_presentation R A) (e : A ≃ₐ[R] B) : finite_presentation R B := begin obtain ⟨n, f, hf⟩ := hfp, use [n, alg_hom.comp ↑e f], split, { exact function.surjective.comp e.surjective hf.1 }, suffices hker : (alg_hom.comp ↑e f).to_ring_hom.ker = f.to_ring_hom.ker, { rw hker, exact hf.2 }, { have hco : (alg_hom.comp ↑e f).to_ring_hom = ring_hom.comp ↑e.to_ring_equiv f.to_ring_hom, { have h : (alg_hom.comp ↑e f).to_ring_hom = e.to_alg_hom.to_ring_hom.comp f.to_ring_hom := rfl, have h1 : ↑(e.to_ring_equiv) = (e.to_alg_hom).to_ring_hom := rfl, rw [h, h1] }, rw [ring_hom.ker_eq_comap_bot, hco, ← ideal.comap_comap, ← ring_hom.ker_eq_comap_bot, ring_hom.ker_coe_equiv (alg_equiv.to_ring_equiv e), ring_hom.ker_eq_comap_bot] } end variable (R) /-- The ring of polynomials in finitely many variables is finitely presented. -/ protected lemma mv_polynomial (ι : Type u_2) [fintype ι] : finite_presentation R (mv_polynomial ι R) := begin obtain ⟨equiv⟩ := @fintype.trunc_equiv_fin ι (classical.dec_eq ι) _, replace equiv := mv_polynomial.rename_equiv R equiv, refine ⟨_, alg_equiv.to_alg_hom equiv.symm, _⟩, split, { exact (alg_equiv.symm equiv).surjective }, suffices hinj : function.injective equiv.symm.to_alg_hom.to_ring_hom, { rw [(ring_hom.injective_iff_ker_eq_bot _).1 hinj], exact submodule.fg_bot }, exact (alg_equiv.symm equiv).injective end /-- `R` is finitely presented as `R`-algebra. -/ lemma self : finite_presentation R R := equiv (finite_presentation.mv_polynomial R pempty) (mv_polynomial.is_empty_alg_equiv R pempty) variable {R} /-- The quotient of a finitely presented algebra by a finitely generated ideal is finitely presented. -/ protected lemma quotient {I : ideal A} (h : submodule.fg I) (hfp : finite_presentation R A) : finite_presentation R I.quotient := begin obtain ⟨n, f, hf⟩ := hfp, refine ⟨n, (ideal.quotient.mkₐ R I).comp f, _, _⟩, { exact (ideal.quotient.mkₐ_surjective R I).comp hf.1 }, { refine submodule.fg_ker_ring_hom_comp _ _ hf.2 _ hf.1, simp [h] } end /-- If `f : A →ₐ[R] B` is surjective with finitely generated kernel and `A` is finitely presented, then so is `B`. -/ lemma of_surjective {f : A →ₐ[R] B} (hf : function.surjective f) (hker : f.to_ring_hom.ker.fg) (hfp : finite_presentation R A) : finite_presentation R B := equiv (hfp.quotient hker) (ideal.quotient_ker_alg_equiv_of_surjective hf) lemma iff : finite_presentation R A ↔ ∃ n (I : ideal (mv_polynomial (fin n) R)) (e : I.quotient ≃ₐ[R] A), I.fg := begin split, { rintros ⟨n, f, hf⟩, exact ⟨n, f.to_ring_hom.ker, ideal.quotient_ker_alg_equiv_of_surjective hf.1, hf.2⟩ }, { rintros ⟨n, I, e, hfg⟩, exact equiv ((finite_presentation.mv_polynomial R _).quotient hfg) e } end /-- An algebra is finitely presented if and only if it is a quotient of a polynomial ring whose variables are indexed by a fintype by a finitely generated ideal. -/ lemma iff_quotient_mv_polynomial' : finite_presentation R A ↔ ∃ (ι : Type u_2) (_ : fintype ι) (f : mv_polynomial ι R →ₐ[R] A), surjective f ∧ f.to_ring_hom.ker.fg := begin split, { rintro ⟨n, f, hfs, hfk⟩, set ulift_var := mv_polynomial.rename_equiv R equiv.ulift, refine ⟨ulift (fin n), infer_instance, f.comp ulift_var.to_alg_hom, hfs.comp ulift_var.surjective, submodule.fg_ker_ring_hom_comp _ _ _ hfk ulift_var.surjective⟩, convert submodule.fg_bot, exact ring_hom.ker_coe_equiv ulift_var.to_ring_equiv, }, { rintro ⟨ι, hfintype, f, hf⟩, haveI : fintype ι := hfintype, obtain ⟨equiv⟩ := @fintype.trunc_equiv_fin ι (classical.dec_eq ι) _, replace equiv := mv_polynomial.rename_equiv R equiv, refine ⟨fintype.card ι, f.comp equiv.symm, hf.1.comp (alg_equiv.symm equiv).surjective, submodule.fg_ker_ring_hom_comp _ f _ hf.2 equiv.symm.surjective⟩, convert submodule.fg_bot, exact ring_hom.ker_coe_equiv (equiv.symm.to_ring_equiv), } end /-- If `A` is a finitely presented `R`-algebra, then `mv_polynomial (fin n) A` is finitely presented as `R`-algebra. -/ lemma mv_polynomial_of_finite_presentation (hfp : finite_presentation R A) (ι : Type*) [fintype ι] : finite_presentation R (mv_polynomial ι A) := begin rw iff_quotient_mv_polynomial' at hfp ⊢, classical, obtain ⟨ι', _, f, hf_surj, hf_ker⟩ := hfp, resetI, let g := (mv_polynomial.map_alg_hom f).comp (mv_polynomial.sum_alg_equiv R ι ι').to_alg_hom, refine ⟨ι ⊕ ι', by apply_instance, g, (mv_polynomial.map_surjective f.to_ring_hom hf_surj).comp (alg_equiv.surjective _), submodule.fg_ker_ring_hom_comp _ _ _ _ (alg_equiv.surjective _)⟩, { convert submodule.fg_bot, exact ring_hom.ker_coe_equiv _, }, { rw [alg_hom.to_ring_hom_eq_coe, mv_polynomial.map_alg_hom_coe_ring_hom, mv_polynomial.ker_map], exact submodule.map_fg_of_fg _ hf_ker mv_polynomial.C, } end /-- If `A` is an `R`-algebra and `S` is an `A`-algebra, both finitely presented, then `S` is finitely presented as `R`-algebra. -/ lemma trans [algebra A B] [is_scalar_tower R A B] (hfpA : finite_presentation R A) (hfpB : finite_presentation A B) : finite_presentation R B := begin obtain ⟨n, I, e, hfg⟩ := iff.1 hfpB, exact equiv ((mv_polynomial_of_finite_presentation hfpA _).quotient hfg) (e.restrict_scalars R) end end finite_presentation end algebra end module_and_algebra namespace ring_hom variables {A B C : Type*} [comm_ring A] [comm_ring B] [comm_ring C] /-- A ring morphism `A →+* B` is `finite` if `B` is finitely generated as `A`-module. -/ def finite (f : A →+* B) : Prop := by letI : algebra A B := f.to_algebra; exact module.finite A B /-- A ring morphism `A →+* B` is of `finite_type` if `B` is finitely generated as `A`-algebra. -/ def finite_type (f : A →+* B) : Prop := @algebra.finite_type A B _ _ f.to_algebra /-- A ring morphism `A →+* B` is of `finite_presentation` if `B` is finitely presented as `A`-algebra. -/ def finite_presentation (f : A →+* B) : Prop := @algebra.finite_presentation A B _ _ f.to_algebra namespace finite variables (A) lemma id : finite (ring_hom.id A) := module.finite.self A variables {A} lemma of_surjective (f : A →+* B) (hf : surjective f) : f.finite := begin letI := f.to_algebra, exact module.finite.of_surjective (algebra.of_id A B).to_linear_map hf end lemma comp {g : B →+* C} {f : A →+* B} (hg : g.finite) (hf : f.finite) : (g.comp f).finite := @module.finite.trans A B C _ _ f.to_algebra _ (g.comp f).to_algebra g.to_algebra begin fconstructor, intros a b c, simp only [algebra.smul_def, ring_hom.map_mul, mul_assoc], refl end hf hg lemma finite_type {f : A →+* B} (hf : f.finite) : finite_type f := @module.finite.finite_type _ _ _ _ f.to_algebra hf lemma of_comp_finite {f : A →+* B} {g : B →+* C} (h : (g.comp f).finite) : g.finite := begin letI := f.to_algebra, letI := g.to_algebra, letI := (g.comp f).to_algebra, letI : is_scalar_tower A B C := restrict_scalars.is_scalar_tower A B C, letI : module.finite A C := h, exact module.finite.of_restrict_scalars_finite A B C end end finite namespace finite_type variables (A) lemma id : finite_type (ring_hom.id A) := algebra.finite_type.self A variables {A} lemma comp_surjective {f : A →+* B} {g : B →+* C} (hf : f.finite_type) (hg : surjective g) : (g.comp f).finite_type := @algebra.finite_type.of_surjective A B C _ _ f.to_algebra _ (g.comp f).to_algebra hf { to_fun := g, commutes' := λ a, rfl, .. g } hg lemma of_surjective (f : A →+* B) (hf : surjective f) : f.finite_type := by { rw ← f.comp_id, exact (id A).comp_surjective hf } lemma comp {g : B →+* C} {f : A →+* B} (hg : g.finite_type) (hf : f.finite_type) : (g.comp f).finite_type := @algebra.finite_type.trans A B C _ _ f.to_algebra _ (g.comp f).to_algebra g.to_algebra begin fconstructor, intros a b c, simp only [algebra.smul_def, ring_hom.map_mul, mul_assoc], refl end hf hg lemma of_finite_presentation {f : A →+* B} (hf : f.finite_presentation) : f.finite_type := @algebra.finite_type.of_finite_presentation A B _ _ f.to_algebra hf lemma of_comp_finite_type {f : A →+* B} {g : B →+* C} (h : (g.comp f).finite_type) : g.finite_type := begin letI := f.to_algebra, letI := g.to_algebra, letI := (g.comp f).to_algebra, letI : is_scalar_tower A B C := restrict_scalars.is_scalar_tower A B C, letI : algebra.finite_type A C := h, exact algebra.finite_type.of_restrict_scalars_finite_type A B C end end finite_type namespace finite_presentation variables (A) lemma id : finite_presentation (ring_hom.id A) := algebra.finite_presentation.self A variables {A} lemma comp_surjective {f : A →+* B} {g : B →+* C} (hf : f.finite_presentation) (hg : surjective g) (hker : g.ker.fg) : (g.comp f).finite_presentation := @algebra.finite_presentation.of_surjective A B C _ _ f.to_algebra _ (g.comp f).to_algebra { to_fun := g, commutes' := λ a, rfl, .. g } hg hker hf lemma of_surjective (f : A →+* B) (hf : surjective f) (hker : f.ker.fg) : f.finite_presentation := by { rw ← f.comp_id, exact (id A).comp_surjective hf hker} lemma of_finite_type [is_noetherian_ring A] {f : A →+* B} : f.finite_type ↔ f.finite_presentation := @algebra.finite_presentation.of_finite_type A B _ _ f.to_algebra _ lemma comp {g : B →+* C} {f : A →+* B} (hg : g.finite_presentation) (hf : f.finite_presentation) : (g.comp f).finite_presentation := @algebra.finite_presentation.trans A B C _ _ f.to_algebra _ (g.comp f).to_algebra g.to_algebra { smul_assoc := λ a b c, begin simp only [algebra.smul_def, ring_hom.map_mul, mul_assoc], refl end } hf hg end finite_presentation end ring_hom namespace alg_hom variables {R A B C : Type*} [comm_ring R] variables [comm_ring A] [comm_ring B] [comm_ring C] variables [algebra R A] [algebra R B] [algebra R C] /-- An algebra morphism `A →ₐ[R] B` is finite if it is finite as ring morphism. In other words, if `B` is finitely generated as `A`-module. -/ def finite (f : A →ₐ[R] B) : Prop := f.to_ring_hom.finite /-- An algebra morphism `A →ₐ[R] B` is of `finite_type` if it is of finite type as ring morphism. In other words, if `B` is finitely generated as `A`-algebra. -/ def finite_type (f : A →ₐ[R] B) : Prop := f.to_ring_hom.finite_type /-- An algebra morphism `A →ₐ[R] B` is of `finite_presentation` if it is of finite presentation as ring morphism. In other words, if `B` is finitely presented as `A`-algebra. -/ def finite_presentation (f : A →ₐ[R] B) : Prop := f.to_ring_hom.finite_presentation namespace finite variables (R A) lemma id : finite (alg_hom.id R A) := ring_hom.finite.id A variables {R A} lemma comp {g : B →ₐ[R] C} {f : A →ₐ[R] B} (hg : g.finite) (hf : f.finite) : (g.comp f).finite := ring_hom.finite.comp hg hf lemma of_surjective (f : A →ₐ[R] B) (hf : surjective f) : f.finite := ring_hom.finite.of_surjective f hf lemma finite_type {f : A →ₐ[R] B} (hf : f.finite) : finite_type f := ring_hom.finite.finite_type hf lemma of_comp_finite {f : A →ₐ[R] B} {g : B →ₐ[R] C} (h : (g.comp f).finite) : g.finite := ring_hom.finite.of_comp_finite h end finite namespace finite_type variables (R A) lemma id : finite_type (alg_hom.id R A) := ring_hom.finite_type.id A variables {R A} lemma comp {g : B →ₐ[R] C} {f : A →ₐ[R] B} (hg : g.finite_type) (hf : f.finite_type) : (g.comp f).finite_type := ring_hom.finite_type.comp hg hf lemma comp_surjective {f : A →ₐ[R] B} {g : B →ₐ[R] C} (hf : f.finite_type) (hg : surjective g) : (g.comp f).finite_type := ring_hom.finite_type.comp_surjective hf hg lemma of_surjective (f : A →ₐ[R] B) (hf : surjective f) : f.finite_type := ring_hom.finite_type.of_surjective f hf lemma of_finite_presentation {f : A →ₐ[R] B} (hf : f.finite_presentation) : f.finite_type := ring_hom.finite_type.of_finite_presentation hf lemma of_comp_finite_type {f : A →ₐ[R] B} {g : B →ₐ[R] C} (h : (g.comp f).finite_type) : g.finite_type := ring_hom.finite_type.of_comp_finite_type h end finite_type namespace finite_presentation variables (R A) lemma id : finite_presentation (alg_hom.id R A) := ring_hom.finite_presentation.id A variables {R A} lemma comp {g : B →ₐ[R] C} {f : A →ₐ[R] B} (hg : g.finite_presentation) (hf : f.finite_presentation) : (g.comp f).finite_presentation := ring_hom.finite_presentation.comp hg hf lemma comp_surjective {f : A →ₐ[R] B} {g : B →ₐ[R] C} (hf : f.finite_presentation) (hg : surjective g) (hker : g.to_ring_hom.ker.fg) : (g.comp f).finite_presentation := ring_hom.finite_presentation.comp_surjective hf hg hker lemma of_surjective (f : A →ₐ[R] B) (hf : surjective f) (hker : f.to_ring_hom.ker.fg) : f.finite_presentation := ring_hom.finite_presentation.of_surjective f hf hker lemma of_finite_type [is_noetherian_ring A] {f : A →ₐ[R] B} : f.finite_type ↔ f.finite_presentation := ring_hom.finite_presentation.of_finite_type end finite_presentation end alg_hom section monoid_algebra variables {R : Type*} {M : Type*} namespace add_monoid_algebra open algebra add_submonoid submodule section span section semiring variables [comm_semiring R] [add_monoid M] /-- An element of `add_monoid_algebra R M` is in the subalgebra generated by its support. -/ lemma mem_adjoin_support (f : add_monoid_algebra R M) : f ∈ adjoin R (of' R M '' f.support) := begin suffices : span R (of' R M '' f.support) ≤ (adjoin R (of' R M '' f.support)).to_submodule, { exact this (mem_span_support f) }, rw submodule.span_le, exact subset_adjoin end /-- If a set `S` generates, as algebra, `add_monoid_algebra R M`, then the set of supports of elements of `S` generates `add_monoid_algebra R M`. -/ lemma support_gen_of_gen {S : set (add_monoid_algebra R M)} (hS : algebra.adjoin R S = ⊤) : algebra.adjoin R (⋃ f ∈ S, (of' R M '' (f.support : set M))) = ⊤ := begin refine le_antisymm le_top _, rw [← hS, adjoin_le_iff], intros f hf, have hincl : of' R M '' f.support ⊆ ⋃ (g : add_monoid_algebra R M) (H : g ∈ S), of' R M '' g.support, { intros s hs, exact set.mem_bUnion_iff.2 ⟨f, ⟨hf, hs⟩⟩ }, exact adjoin_mono hincl (mem_adjoin_support f) end /-- If a set `S` generates, as algebra, `add_monoid_algebra R M`, then the image of the union of the supports of elements of `S` generates `add_monoid_algebra R M`. -/ lemma support_gen_of_gen' {S : set (add_monoid_algebra R M)} (hS : algebra.adjoin R S = ⊤) : algebra.adjoin R (of' R M '' (⋃ f ∈ S, (f.support : set M))) = ⊤ := begin suffices : of' R M '' (⋃ f ∈ S, (f.support : set M)) = ⋃ f ∈ S, (of' R M '' (f.support : set M)), { rw this, exact support_gen_of_gen hS }, simp only [set.image_Union] end end semiring section ring variables [comm_ring R] [add_comm_monoid M] /-- If `add_monoid_algebra R M` is of finite type, there there is a `G : finset M` such that its image generates, as algera, `add_monoid_algebra R M`. -/ lemma exists_finset_adjoin_eq_top [h : finite_type R (add_monoid_algebra R M)] : ∃ G : finset M, algebra.adjoin R (of' R M '' G) = ⊤ := begin unfreezingI { obtain ⟨S, hS⟩ := h }, letI : decidable_eq M := classical.dec_eq M, use finset.bUnion S (λ f, f.support), have : (finset.bUnion S (λ f, f.support) : set M) = ⋃ f ∈ S, (f.support : set M), { simp only [finset.set_bUnion_coe, finset.coe_bUnion] }, rw [this], exact support_gen_of_gen' hS end /-- The image of an element `m : M` in `add_monoid_algebra R M` belongs the submodule generated by `S : set M` if and only if `m ∈ S`. -/ lemma of'_mem_span [nontrivial R] {m : M} {S : set M} : of' R M m ∈ span R (of' R M '' S) ↔ m ∈ S := begin refine ⟨λ h, _, λ h, submodule.subset_span $ set.mem_image_of_mem (of R M) h⟩, rw [of', ← finsupp.supported_eq_span_single, finsupp.mem_supported, finsupp.support_single_ne_zero (@one_ne_zero R _ (by apply_instance))] at h, simpa using h end /--If the image of an element `m : M` in `add_monoid_algebra R M` belongs the submodule generated by the closure of some `S : set M` then `m ∈ closure S`. -/ lemma mem_closure_of_mem_span_closure [nontrivial R] {m : M} {S : set M} (h : of' R M m ∈ span R (submonoid.closure (of' R M '' S) : set (add_monoid_algebra R M))) : m ∈ closure S := begin suffices : multiplicative.of_add m ∈ submonoid.closure (multiplicative.to_add ⁻¹' S), { simpa [← to_submonoid_closure] }, rw [set.image_congr' (show ∀ x, of' R M x = of R M x, from λ x, of'_eq_of x), ← monoid_hom.map_mclosure] at h, simpa using of'_mem_span.1 h end end ring end span variables [add_comm_monoid M] /-- If a set `S` generates an additive monoid `M`, then the image of `M` generates, as algebra, `add_monoid_algebra R M`. -/ lemma mv_polynomial_aeval_of_surjective_of_closure [comm_semiring R] {S : set M} (hS : closure S = ⊤) : function.surjective (mv_polynomial.aeval (λ (s : S), of' R M ↑s) : mv_polynomial S R → add_monoid_algebra R M) := begin refine λ f, induction_on f (λ m, _) _ _, { have : m ∈ closure S := hS.symm ▸ mem_top _, refine closure_induction this (λ m hm, _) _ _, { exact ⟨mv_polynomial.X ⟨m, hm⟩, mv_polynomial.aeval_X _ _⟩ }, { exact ⟨1, alg_hom.map_one _⟩ }, { rintro m₁ m₂ ⟨P₁, hP₁⟩ ⟨P₂, hP₂⟩, exact ⟨P₁ * P₂, by rw [alg_hom.map_mul, hP₁, hP₂, of_apply, of_apply, of_apply, single_mul_single, one_mul]; refl⟩ } }, { rintro f g ⟨P, rfl⟩ ⟨Q, rfl⟩, exact ⟨P + Q, alg_hom.map_add _ _ _⟩ }, { rintro r f ⟨P, rfl⟩, exact ⟨r • P, alg_hom.map_smul _ _ _⟩ } end variables (R M) /-- If an additive monoid `M` is finitely generated then `add_monoid_algebra R M` is of finite type. -/ instance finite_type_of_fg [comm_ring R] [h : add_monoid.fg M] : finite_type R (add_monoid_algebra R M) := begin obtain ⟨S, hS⟩ := h.out, exact (finite_type.mv_polynomial R (S : set M)).of_surjective (mv_polynomial.aeval (λ (s : (S : set M)), of' R M ↑s)) (mv_polynomial_aeval_of_surjective_of_closure hS) end variables {R M} /-- An additive monoid `M` is finitely generated if and only if `add_monoid_algebra R M` is of finite type. -/ lemma finite_type_iff_fg [comm_ring R] [nontrivial R] : finite_type R (add_monoid_algebra R M) ↔ add_monoid.fg M := begin refine ⟨λ h, _, λ h, @add_monoid_algebra.finite_type_of_fg _ _ _ _ h⟩, obtain ⟨S, hS⟩ := @exists_finset_adjoin_eq_top R M _ _ h, refine add_monoid.fg_def.2 ⟨S, (eq_top_iff' _).2 (λ m, _)⟩, have hm : of' R M m ∈ (adjoin R (of' R M '' ↑S)).to_submodule, { simp only [hS, top_to_submodule, submodule.mem_top], }, rw [adjoin_eq_span] at hm, exact mem_closure_of_mem_span_closure hm end /-- If `add_monoid_algebra R M` is of finite type then `M` is finitely generated. -/ lemma fg_of_finite_type [comm_ring R] [nontrivial R] [h : finite_type R (add_monoid_algebra R M)] : add_monoid.fg M := finite_type_iff_fg.1 h /-- An additive group `G` is finitely generated if and only if `add_monoid_algebra R G` is of finite type. -/ lemma finite_type_iff_group_fg {G : Type*} [add_comm_group G] [comm_ring R] [nontrivial R] : finite_type R (add_monoid_algebra R G) ↔ add_group.fg G := by simpa [add_group.fg_iff_add_monoid.fg] using finite_type_iff_fg end add_monoid_algebra namespace monoid_algebra open algebra submonoid submodule section span section semiring variables [comm_semiring R] [monoid M] /-- An element of `monoid_algebra R M` is in the subalgebra generated by its support. -/ lemma mem_adjoint_support (f : monoid_algebra R M) : f ∈ adjoin R (of R M '' f.support) := begin suffices : span R (of R M '' f.support) ≤ (adjoin R (of R M '' f.support)).to_submodule, { exact this (mem_span_support f) }, rw submodule.span_le, exact subset_adjoin end /-- If a set `S` generates, as algebra, `monoid_algebra R M`, then the set of supports of elements of `S` generates `monoid_algebra R M`. -/ lemma support_gen_of_gen {S : set (monoid_algebra R M)} (hS : algebra.adjoin R S = ⊤) : algebra.adjoin R (⋃ f ∈ S, (of R M '' (f.support : set M))) = ⊤ := begin refine le_antisymm le_top _, rw [← hS, adjoin_le_iff], intros f hf, have hincl : (of R M) '' f.support ⊆ ⋃ (g : monoid_algebra R M) (H : g ∈ S), of R M '' g.support, { intros s hs, exact set.mem_bUnion_iff.2 ⟨f, ⟨hf, hs⟩⟩ }, exact adjoin_mono hincl (mem_adjoint_support f) end /-- If a set `S` generates, as algebra, `monoid_algebra R M`, then the image of the union of the supports of elements of `S` generates `monoid_algebra R M`. -/ lemma support_gen_of_gen' {S : set (monoid_algebra R M)} (hS : algebra.adjoin R S = ⊤) : algebra.adjoin R (of R M '' (⋃ f ∈ S, (f.support : set M))) = ⊤ := begin suffices : of R M '' (⋃ f ∈ S, (f.support : set M)) = ⋃ f ∈ S, (of R M '' (f.support : set M)), { rw this, exact support_gen_of_gen hS }, simp only [set.image_Union] end end semiring section ring variables [comm_ring R] [comm_monoid M] /-- If `monoid_algebra R M` is of finite type, there there is a `G : finset M` such that its image generates, as algera, `monoid_algebra R M`. -/ lemma exists_finset_adjoin_eq_top [h :finite_type R (monoid_algebra R M)] : ∃ G : finset M, algebra.adjoin R (of R M '' G) = ⊤ := begin unfreezingI { obtain ⟨S, hS⟩ := h }, letI : decidable_eq M := classical.dec_eq M, use finset.bUnion S (λ f, f.support), have : (finset.bUnion S (λ f, f.support) : set M) = ⋃ f ∈ S, (f.support : set M), { simp only [finset.set_bUnion_coe, finset.coe_bUnion] }, rw [this], exact support_gen_of_gen' hS end /-- The image of an element `m : M` in `monoid_algebra R M` belongs the submodule generated by `S : set M` if and only if `m ∈ S`. -/ lemma of_mem_span_of_iff [nontrivial R] {m : M} {S : set M} : of R M m ∈ span R (of R M '' S) ↔ m ∈ S := begin refine ⟨λ h, _, λ h, submodule.subset_span $ set.mem_image_of_mem (of R M) h⟩, rw [of, monoid_hom.coe_mk, ← finsupp.supported_eq_span_single, finsupp.mem_supported, finsupp.support_single_ne_zero (@one_ne_zero R _ (by apply_instance))] at h, simpa using h end /--If the image of an element `m : M` in `monoid_algebra R M` belongs the submodule generated by the closure of some `S : set M` then `m ∈ closure S`. -/ lemma mem_closure_of_mem_span_closure [nontrivial R] {m : M} {S : set M} (h : of R M m ∈ span R (submonoid.closure (of R M '' S) : set (monoid_algebra R M))) : m ∈ closure S := begin rw ← monoid_hom.map_mclosure at h, simpa using of_mem_span_of_iff.1 h end end ring end span variables [comm_monoid M] /-- If a set `S` generates a monoid `M`, then the image of `M` generates, as algebra, `monoid_algebra R M`. -/ lemma mv_polynomial_aeval_of_surjective_of_closure [comm_semiring R] {S : set M} (hS : closure S = ⊤) : function.surjective (mv_polynomial.aeval (λ (s : S), of R M ↑s) : mv_polynomial S R → monoid_algebra R M) := begin refine λ f, induction_on f (λ m, _) _ _, { have : m ∈ closure S := hS.symm ▸ mem_top _, refine closure_induction this (λ m hm, _) _ _, { exact ⟨mv_polynomial.X ⟨m, hm⟩, mv_polynomial.aeval_X _ _⟩ }, { exact ⟨1, alg_hom.map_one _⟩ }, { rintro m₁ m₂ ⟨P₁, hP₁⟩ ⟨P₂, hP₂⟩, exact ⟨P₁ * P₂, by rw [alg_hom.map_mul, hP₁, hP₂, of_apply, of_apply, of_apply, single_mul_single, one_mul]⟩ } }, { rintro f g ⟨P, rfl⟩ ⟨Q, rfl⟩, exact ⟨P + Q, alg_hom.map_add _ _ _⟩ }, { rintro r f ⟨P, rfl⟩, exact ⟨r • P, alg_hom.map_smul _ _ _⟩ } end /-- If a monoid `M` is finitely generated then `monoid_algebra R M` is of finite type. -/ instance finite_type_of_fg [comm_ring R] [monoid.fg M] : finite_type R (monoid_algebra R M) := (add_monoid_algebra.finite_type_of_fg R (additive M)).equiv (to_additive_alg_equiv R M).symm /-- A monoid `M` is finitely generated if and only if `monoid_algebra R M` is of finite type. -/ lemma finite_type_iff_fg [comm_ring R] [nontrivial R] : finite_type R (monoid_algebra R M) ↔ monoid.fg M := ⟨λ h, monoid.fg_iff_add_fg.2 $ add_monoid_algebra.finite_type_iff_fg.1 $ h.equiv $ to_additive_alg_equiv R M, λ h, @monoid_algebra.finite_type_of_fg _ _ _ _ h⟩ /-- If `monoid_algebra R M` is of finite type then `M` is finitely generated. -/ lemma fg_of_finite_type [comm_ring R] [nontrivial R] [h : finite_type R (monoid_algebra R M)] : monoid.fg M := finite_type_iff_fg.1 h /-- A group `G` is finitely generated if and only if `add_monoid_algebra R G` is of finite type. -/ lemma finite_type_iff_group_fg {G : Type*} [comm_group G] [comm_ring R] [nontrivial R] : finite_type R (monoid_algebra R G) ↔ group.fg G := by simpa [group.fg_iff_monoid.fg] using finite_type_iff_fg end monoid_algebra end monoid_algebra
4d6baeabf097940438fe999173954516a4074bbb
78630e908e9624a892e24ebdd21260720d29cf55
/src/logic_propositional/prop_20.lean
fe2efc52720b4ecf766605dee243d7c236a74504
[ "CC0-1.0" ]
permissive
tomasz-lisowski/lean-logic-examples
84e612466776be0a16c23a0439ff8ef6114ddbe1
2b2ccd467b49c3989bf6c92ec0358a8d6ee68c5d
refs/heads/master
1,683,334,199,431
1,621,938,305,000
1,621,938,305,000
365,041,573
1
0
null
null
null
null
UTF-8
Lean
false
false
309
lean
namespace prop_20 variables P Q : Prop theorem prop_20 : ¬ ¬ (P ∧ Q) → ¬ ¬ Q := assume h1: ¬ ¬ (P ∧ Q), have h2: P ∧ Q, from (classical.by_contradiction (assume h2: ¬ (P ∧ Q), h1 h2)), assume h3: ¬ Q, have h4: Q, from and.right h2, show false, from h3 h4 -- end namespace end prop_20
72edef23cd6006ec9a7b7ebaafa86fe9f6328aa9
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/tactic/doc_commands.lean
93c6a8b3f3ba1348d14e04ce33517ba3bb280149
[ "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
15,880
lean
/- Copyright (c) 2020 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import tactic.fix_reflect_string /-! # Documentation commands We generate html documentation from mathlib. It is convenient to collect lists of tactics, commands, notes, etc. To facilitate this, we declare these documentation entries in the library using special commands. * `library_note` adds a note describing a certain feature or design decision. These can be referenced in doc strings with the text `note [name of note]`. * `add_tactic_doc` adds an entry documenting an interactive tactic, command, hole command, or attribute. Since these commands are used in files imported by `tactic.core`, this file has no imports. ## Implementation details `library_note note_id note_msg` creates a declaration `` `library_note.i `` for some `i`. This declaration is a pair of strings `note_id` and `note_msg`, and it gets tagged with the `library_note` attribute. Similarly, `add_tactic_doc` creates a declaration `` `tactic_doc.i `` that stores the provided information. -/ /-- A rudimentary hash function on strings. -/ def string.hash (s : string) : ℕ := s.fold 1 (λ h c, (33*h + c.val) % unsigned_sz) /-- `mk_hashed_name nspace id` hashes the string `id` to a value `i` and returns the name `nspace._i` -/ meta def string.mk_hashed_name (nspace : name) (id : string) : name := nspace <.> ("_" ++ to_string id.hash) /-! ### The `library_note` command -/ /-- A user attribute `library_note` for tagging decls of type `string × string` for use in note output. -/ @[user_attribute] meta def library_note_attr : user_attribute := { name := `library_note, descr := "Notes about library features to be included in documentation" } open tactic /-- `mk_reflected_definition name val` constructs a definition declaration by reflection. Example: ``mk_reflected_definition `foo 17`` constructs the definition declaration corresponding to `def foo : ℕ := 17` -/ meta def mk_reflected_definition (decl_name : name) {type} [reflected type] (body : type) [reflected body] : declaration := mk_definition decl_name (reflect type).collect_univ_params (reflect type) (reflect body) /-- If `note_name` and `note` are `pexpr`s representing strings, `add_library_note note_name note` adds a declaration of type `string × string` and tags it with the `library_note` attribute. -/ meta def tactic.add_library_note (note_name note : string) : tactic unit := do let decl_name := note_name.mk_hashed_name `library_note, add_decl $ mk_reflected_definition decl_name (note_name, note), library_note_attr.set decl_name () tt none /-- `tactic.eval_pexpr e α` evaluates the pre-expression `e` to a VM object of type `α`. -/ meta def tactic.eval_pexpr (α) [reflected α] (e : pexpr) : tactic α := to_expr ``(%%e : %%(reflect α)) ff ff >>= eval_expr α open tactic lean lean.parser interactive /-- A command to add library notes. Syntax: ``` /-- note message -/ library_note "note id" ``` -/ @[user_command] meta def library_note (mi : interactive.decl_meta_info) (_ : parse (tk "library_note")) : parser unit := do note_name ← parser.pexpr, note_name ← eval_pexpr string note_name, some doc_string ← pure mi.doc_string | fail "library_note requires a doc string", add_library_note note_name doc_string /-- Collects all notes in the current environment. Returns a list of pairs `(note_id, note_content)` -/ meta def tactic.get_library_notes : tactic (list (string × string)) := attribute.get_instances `library_note >>= list.mmap (λ dcl, mk_const dcl >>= eval_expr (string × string)) /-! ### The `add_tactic_doc_entry` command -/ /-- The categories of tactic doc entry. -/ @[derive [decidable_eq, has_reflect]] inductive doc_category | tactic | cmd | hole_cmd | attr /-- Format a `doc_category` -/ meta def doc_category.to_string : doc_category → string | doc_category.tactic := "tactic" | doc_category.cmd := "command" | doc_category.hole_cmd := "hole_command" | doc_category.attr := "attribute" meta instance : has_to_format doc_category := ⟨↑doc_category.to_string⟩ /-- The information used to generate a tactic doc entry -/ @[derive has_reflect] structure tactic_doc_entry := (name : string) (category : doc_category) (decl_names : list _root_.name) (tags : list string := []) (description : string := "") (inherit_description_from : option _root_.name := none) /-- format a `tactic_doc_entry` -/ meta def tactic_doc_entry.to_string : tactic_doc_entry → string | ⟨name, category, decl_names, tags, description, _⟩ := let decl_names := decl_names.map (repr ∘ to_string), tags := tags.map repr in "{" ++ to_string (format!"\"name\": {repr name}, \"category\": \"{category}\", \"decl_names\":{decl_names}, \"tags\": {tags}, \"description\": {repr description}") ++ "}" meta instance : has_to_string tactic_doc_entry := ⟨tactic_doc_entry.to_string⟩ /-- `update_description_from tde inh_id` replaces the `description` field of `tde` with the doc string of the declaration named `inh_id`. -/ meta def tactic_doc_entry.update_description_from (tde : tactic_doc_entry) (inh_id : name) : tactic tactic_doc_entry := do ds ← doc_string inh_id <|> fail (to_string inh_id ++ " has no doc string"), return { description := ds .. tde } /-- `update_description tde` replaces the `description` field of `tde` with: * the doc string of `tde.inherit_description_from`, if this field has a value * the doc string of the entry in `tde.decl_names`, if this field has length 1 If neither of these conditions are met, it returns `tde`. -/ meta def tactic_doc_entry.update_description (tde : tactic_doc_entry) : tactic tactic_doc_entry := match tde.inherit_description_from, tde.decl_names with | some inh_id, _ := tde.update_description_from inh_id | none, [inh_id] := tde.update_description_from inh_id | none, _ := return tde end /-- A user attribute `tactic_doc` for tagging decls of type `tactic_doc_entry` for use in doc output -/ @[user_attribute] meta def tactic_doc_entry_attr : user_attribute := { name := `tactic_doc, descr := "Information about a tactic to be included in documentation" } /-- Collects everything in the environment tagged with the attribute `tactic_doc`. -/ meta def tactic.get_tactic_doc_entries : tactic (list tactic_doc_entry) := attribute.get_instances `tactic_doc >>= list.mmap (λ dcl, mk_const dcl >>= eval_expr tactic_doc_entry) /-- `add_tactic_doc tde` adds a declaration to the environment with `tde` as its body and tags it with the `tactic_doc` attribute. If `tde.decl_names` has exactly one entry `` `decl`` and if `tde.description` is the empty string, `add_tactic_doc` uses the doc string of `decl` as the description. -/ meta def tactic.add_tactic_doc (tde : tactic_doc_entry) : tactic unit := do when (tde.description = "" ∧ tde.inherit_description_from.is_none ∧ tde.decl_names.length ≠ 1) $ fail ("A tactic doc entry must either:\n" ++ " 1. have a description written as a doc-string for the `add_tactic_doc` invocation, or\n" ++ " 2. have a single declaration in the `decl_names` field, to inherit a description from, or\n" ++ " 3. explicitly indicate the declaration to inherit the description from using `inherit_description_from`."), tde ← if tde.description = "" then tde.update_description else return tde, let decl_name := (tde.name ++ tde.category.to_string).mk_hashed_name `tactic_doc, add_decl $ mk_definition decl_name [] `(tactic_doc_entry) (reflect tde), tactic_doc_entry_attr.set decl_name () tt none /-- A command used to add documentation for a tactic, command, hole command, or attribute. Usage: after defining an interactive tactic, command, or attribute, add its documentation as follows. ```lean /-- describe what the command does here -/ add_tactic_doc { name := "display name of the tactic", category := cat, decl_names := [`dcl_1, `dcl_2], tags := ["tag_1", "tag_2"] } ``` The argument to `add_tactic_doc` is a structure of type `tactic_doc_entry`. * `name` refers to the display name of the tactic; it is used as the header of the doc entry. * `cat` refers to the category of doc entry. Options: `doc_category.tactic`, `doc_category.cmd`, `doc_category.hole_cmd`, `doc_category.attr` * `decl_names` is a list of the declarations associated with this doc. For instance, the entry for `linarith` would set ``decl_names := [`tactic.interactive.linarith]``. Some entries may cover multiple declarations. It is only necessary to list the interactive versions of tactics. * `tags` is an optional list of strings used to categorize entries. * The doc string is the body of the entry. It can be formatted with markdown. What you are reading now is the description of `add_tactic_doc`. If only one related declaration is listed in `decl_names` and if this invocation of `add_tactic_doc` does not have a doc string, the doc string of that declaration will become the body of the tactic doc entry. If there are multiple declarations, you can select the one to be used by passing a name to the `inherit_description_from` field. If you prefer a tactic to have a doc string that is different then the doc entry, you should write the doc entry as a doc string for the `add_tactic_doc` invocation. Note that providing a badly formed `tactic_doc_entry` to the command can result in strange error messages. -/ @[user_command] meta def add_tactic_doc_command (mi : interactive.decl_meta_info) (_ : parse $ tk "add_tactic_doc") : parser unit := do pe ← parser.pexpr, e ← eval_pexpr tactic_doc_entry pe, let e : tactic_doc_entry := match mi.doc_string with | some desc := { description := desc, ..e } | none := e end, tactic.add_tactic_doc e . /-- At various places in mathlib, we leave implementation notes that are referenced from many other files. To keep track of these notes, we use the command `library_note`. This makes it easy to retrieve a list of all notes, e.g. for documentation output. These notes can be referenced in mathlib with the syntax `Note [note id]`. Often, these references will be made in code comments (`--`) that won't be displayed in docs. If such a reference is made in a doc string or module doc, it will be linked to the corresponding note in the doc display. Syntax: ``` /-- note message -/ library_note "note id" ``` An example from `meta.expr`: ``` /-- Some declarations work with open expressions, i.e. an expr that has free variables. Terms will free variables are not well-typed, and one should not use them in tactics like `infer_type` or `unify`. You can still do syntactic analysis/manipulation on them. The reason for working with open types is for performance: instantiating variables requires iterating through the expression. In one performance test `pi_binders` was more than 6x quicker than `mk_local_pis` (when applied to the type of all imported declarations 100x). -/ library_note "open expressions" ``` This note can be referenced near a usage of `pi_binders`: ``` -- See Note [open expressions] /-- behavior of f -/ def f := pi_binders ... ``` -/ add_tactic_doc { name := "library_note", category := doc_category.cmd, decl_names := [`library_note, `tactic.add_library_note], tags := ["documentation"], inherit_description_from := `library_note } add_tactic_doc { name := "add_tactic_doc", category := doc_category.cmd, decl_names := [`add_tactic_doc_command, `tactic.add_tactic_doc], tags := ["documentation"], inherit_description_from := `add_tactic_doc_command } -- add docs to core tactics /-- The congruence closure tactic `cc` tries to solve the goal by chaining equalities from context and applying congruence (i.e. if `a = b`, then `f a = f b`). It is a finishing tactic, i.e. it is meant to close the current goal, not to make some inconclusive progress. A mostly trivial example would be: ```lean example (a b c : ℕ) (f : ℕ → ℕ) (h: a = b) (h' : b = c) : f a = f c := by cc ``` As an example requiring some thinking to do by hand, consider: ```lean example (f : ℕ → ℕ) (x : ℕ) (H1 : f (f (f x)) = x) (H2 : f (f (f (f (f x)))) = x) : f x = x := by cc ``` The tactic works by building an equality matching graph. It's a graph where the vertices are terms and they are linked by edges if they are known to be equal. Once you've added all the equalities in your context, you take the transitive closure of the graph and, for each connected component (i.e. equivalence class) you can elect a term that will represent the whole class and store proofs that the other elements are equal to it. You then take the transitive closure of these equalities under the congruence lemmas. The `cc` implementation in Lean does a few more tricks: for example it derives `a=b` from `nat.succ a = nat.succ b`, and `nat.succ a != nat.zero` for any `a`. * The starting reference point is Nelson, Oppen, [Fast decision procedures based on congruence closure](http://www.cs.colorado.edu/~bec/courses/csci5535-s09/reading/nelson-oppen-congruence.pdf), Journal of the ACM (1980) * The congruence lemmas for dependent type theory as used in Lean are described in [Congruence closure in intensional type theory](https://leanprover.github.io/papers/congr.pdf) (de Moura, Selsam IJCAR 2016). -/ add_tactic_doc { name := "cc (congruence closure)", category := doc_category.tactic, decl_names := [`tactic.interactive.cc], tags := ["core", "finishing"] } /-- `conv {...}` allows the user to perform targeted rewriting on a goal or hypothesis, by focusing on particular subexpressions. See <https://leanprover-community.github.io/mathlib_docs/conv.html> for more details. Inside `conv` blocks, mathlib currently additionally provides * `erw`, * `ring`, `ring2` and `ring_exp`, * `norm_num`, * `norm_cast`, * `apply_congr`, and * `conv` (within another `conv`). `apply_congr` applies congruence lemmas to step further inside expressions, and sometimes gives between results than the automatically generated congruence lemmas used by `congr`. Using `conv` inside a `conv` block allows the user to return to the previous state of the outer `conv` block after it is finished. Thus you can continue editing an expression without having to start a new `conv` block and re-scoping everything. For example: ```lean example (a b c d : ℕ) (h₁ : b = c) (h₂ : a + c = a + d) : a + b = a + d := by conv { to_lhs, conv { congr, skip, rw h₁, }, rw h₂, } ``` Without `conv`, the above example would need to be proved using two successive `conv` blocks, each beginning with `to_lhs`. Also, as a shorthand, `conv_lhs` and `conv_rhs` are provided, so that ```lean example : 0 + 0 = 0 := begin conv_lhs { simp } end ``` just means ```lean example : 0 + 0 = 0 := begin conv { to_lhs, simp } end ``` and likewise for `to_rhs`. -/ add_tactic_doc { name := "conv", category := doc_category.tactic, decl_names := [`tactic.interactive.conv], tags := ["core"] } add_tactic_doc { name := "simp", category := doc_category.tactic, decl_names := [`tactic.interactive.simp], tags := ["core", "simplification"] } /-- The `add_decl_doc` command is used to add a doc string to an existing declaration. ```lean def foo := 5 /-- Doc string for foo. -/ add_decl_doc foo ``` -/ @[user_command] meta def add_decl_doc_command (mi : interactive.decl_meta_info) (_ : parse $ tk "add_decl_doc") : parser unit := do n ← parser.ident, n ← resolve_constant n, some doc ← pure mi.doc_string | fail "add_decl_doc requires a doc string", add_doc_string n doc add_tactic_doc { name := "add_decl_doc", category := doc_category.cmd, decl_names := [``add_decl_doc_command], tags := ["documentation"] }
33a1afd515001f0eb3a2845613be091b98638fec
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Meta/Tactic/Simp/Rewrite.lean
34aae00e9cefe6e0458499d1c966e326e9f9d3db
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach" ]
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
8,243
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.AppBuilder import Lean.Meta.SynthInstance import Lean.Meta.Tactic.Simp.Types namespace Lean.Meta.Simp def synthesizeArgs (lemmaName : Name) (xs : Array Expr) (bis : Array BinderInfo) (discharge? : Expr → SimpM (Option Expr)) : SimpM Bool := do for x in xs, bi in bis do let type ← inferType x if bi.isInstImplicit then unless (← synthesizeInstance x type) do return false else if (← instantiateMVars x).isMVar then if (← isProp type) then match (← discharge? type) with | some proof => unless (← isDefEq x proof) do trace[Meta.Tactic.simp.discharge] "{lemmaName}, failed to assign proof{indentExpr type}" return false | none => trace[Meta.Tactic.simp.discharge] "{lemmaName}, failed to discharge hypotheses{indentExpr type}" return false else if (← isClass? type).isSome then unless (← synthesizeInstance x type) do return false return true where synthesizeInstance (x type : Expr) : SimpM Bool := do match (← trySynthInstance type) with | LOption.some val => if (← withReducibleAndInstances <| isDefEq x val) then return true else trace[Meta.Tactic.simp.discharge] "{lemmaName}, failed to assign instance{indentExpr type}\nsythesized value{indentExpr val}\nis not definitionally equal to{indentExpr x}" return false | _ => trace[Meta.Tactic.simp.discharge] "{lemmaName}, failed to synthesize instance{indentExpr type}" return false private def tryLemmaCore (lhs : Expr) (xs : Array Expr) (bis : Array BinderInfo) (val : Expr) (type : Expr) (e : Expr) (lemma : SimpLemma) (numExtraArgs : Nat) (discharge? : Expr → SimpM (Option Expr)) : SimpM (Option Result) := do let rec go (e : Expr) : SimpM (Option Result) := do if (← isDefEq lhs e) then unless (← synthesizeArgs lemma.getName xs bis discharge?) do return none let proof ← instantiateMVars (mkAppN val xs) if ← hasAssignableMVar proof then trace[Meta.Tactic.simp.rewrite] "{lemma}, has unassigned metavariables after unification" return none let rhs ← instantiateMVars type.appArg! if e == rhs then return none if lemma.perm && !Expr.lt rhs e then trace[Meta.Tactic.simp.rewrite] "{lemma}, perm rejected {e} ==> {rhs}" return none trace[Meta.Tactic.simp.rewrite] "{lemma}, {e} ==> {rhs}" return some { expr := rhs, proof? := proof } else unless lhs.isMVar do -- We do not report unification failures when `lhs` is a metavariable -- Example: `x = ()` -- TODO: reconsider if we want lemmas such as `(x : Unit) → x = ()` trace[Meta.Tactic.simp.unify] "{lemma}, failed to unify {lhs} with {e}" return none /- Check whether we need something more sophisticated here. This simple approach was good enough for Mathlib 3 -/ let mut extraArgs := #[] let mut e := e for i in [:numExtraArgs] do extraArgs := extraArgs.push e.appArg! e := e.appFn! extraArgs := extraArgs.reverse match (← go e) with | none => return none | some { expr := eNew, proof? := none } => return some { expr := mkAppN eNew extraArgs } | some { expr := eNew, proof? := some proof } => let mut proof := proof for extraArg in extraArgs do proof ← mkCongrFun proof extraArg return some { expr := mkAppN eNew extraArgs, proof? := some proof } def tryLemmaWithExtraArgs? (e : Expr) (lemma : SimpLemma) (numExtraArgs : Nat) (discharge? : Expr → SimpM (Option Expr)) : SimpM (Option Result) := withNewMCtxDepth do let val ← lemma.getValue let type ← inferType val let (xs, bis, type) ← forallMetaTelescopeReducing type let type ← whnf (← instantiateMVars type) let lhs := type.appFn!.appArg! tryLemmaCore lhs xs bis val type e lemma numExtraArgs discharge? def tryLemma? (e : Expr) (lemma : SimpLemma) (discharge? : Expr → SimpM (Option Expr)) : SimpM (Option Result) := do withNewMCtxDepth do let val ← lemma.getValue let type ← inferType val let (xs, bis, type) ← forallMetaTelescopeReducing type let type ← whnf (← instantiateMVars type) let lhs := type.appFn!.appArg! match (← tryLemmaCore lhs xs bis val type e lemma 0 discharge?) with | some result => return some result | none => let lhsNumArgs := lhs.getAppNumArgs let eNumArgs := e.getAppNumArgs if eNumArgs > lhsNumArgs then tryLemmaCore lhs xs bis val type e lemma (eNumArgs - lhsNumArgs) discharge? else return none /- Remark: the parameter tag is used for creating trace messages. It is irrelevant otherwise. -/ def rewrite (e : Expr) (s : DiscrTree SimpLemma) (erased : Std.PHashSet Name) (discharge? : Expr → SimpM (Option Expr)) (tag : String) : SimpM Result := do let candidates ← s.getMatchWithExtra e if candidates.isEmpty then trace[Debug.Meta.Tactic.simp] "no theorems found for {tag}-rewriting {e}" return { expr := e } else let candidates := candidates.insertionSort fun e₁ e₂ => e₁.1.priority > e₂.1.priority for (lemma, numExtraArgs) in candidates do unless inErasedSet lemma do if let some result ← tryLemmaWithExtraArgs? e lemma numExtraArgs discharge? then return result return { expr := e } where inErasedSet (lemma : SimpLemma) : Bool := match lemma.name? with | none => false | some name => erased.contains name def rewriteCtorEq? (e : Expr) : MetaM (Option Result) := withReducibleAndInstances do match e.eq? with | none => return none | some (_, lhs, rhs) => let lhs ← whnf lhs let rhs ← whnf rhs let env ← getEnv match lhs.constructorApp? env, rhs.constructorApp? env with | some (c₁, _), some (c₂, _) => if c₁.name != c₂.name then withLocalDeclD `h e fun h => return some { expr := mkConst ``False, proof? := (← mkEqFalse' (← mkLambdaFVars #[h] (← mkNoConfusion (mkConst ``False) h))) } else return none | _, _ => return none @[inline] def tryRewriteCtorEq (e : Expr) (x : SimpM Step) : SimpM Step := do match (← rewriteCtorEq? e) with | some r => return Step.done r | none => x def rewriteUsingDecide? (e : Expr) : MetaM (Option Result) := withReducibleAndInstances do if e.hasFVar || e.hasMVar || e.isConstOf ``True || e.isConstOf ``False then return none else try let d ← mkDecide e let r ← withDefault <| whnf d if r.isConstOf ``true then return some { expr := mkConst ``True, proof? := mkAppN (mkConst ``eq_true_of_decide) #[e, d.appArg!, (← mkEqRefl (mkConst ``true))] } else if r.isConstOf ``false then let h ← mkEqRefl d return some { expr := mkConst ``False, proof? := mkAppN (mkConst ``eq_false_of_decide) #[e, d.appArg!, (← mkEqRefl (mkConst ``false))] } else return none catch _ => return none @[inline] def tryRewriteUsingDecide (e : Expr) (x : SimpM Step) : SimpM Step := do if (← read).config.decide then match (← rewriteUsingDecide? e) with | some r => return Step.done r | none => x else x def rewritePre (e : Expr) (discharge? : Expr → SimpM (Option Expr)) : SimpM Step := do let lemmas ← (← read).simpLemmas return Step.visit (← rewrite e lemmas.pre lemmas.erased discharge? (tag := "pre")) def rewritePost (e : Expr) (discharge? : Expr → SimpM (Option Expr)) : SimpM Step := do let lemmas ← (← read).simpLemmas return Step.visit (← rewrite e lemmas.post lemmas.erased discharge? (tag := "post")) def preDefault (e : Expr) (discharge? : Expr → SimpM (Option Expr)) : SimpM Step := tryRewriteCtorEq e <| rewritePre e discharge? def postDefault (e : Expr) (discharge? : Expr → SimpM (Option Expr)) : SimpM Step := do -- TODO: try equation lemmas tryRewriteCtorEq e <| tryRewriteUsingDecide e <| rewritePost e discharge? end Lean.Meta.Simp
b265f869bf9daf26f5b90a0fd71354bcf8621889
3b1abba731363bfec018d9d2cfee7fd90e1dc93c
/definitions.lean
e734c2ba0f7977f131a5e573158d1705e550ae7f
[]
no_license
minchaowu/Ramsey.lean
dcf4e0845cca6dc02ef898f3fd9123c079c5a1a9
8ebbead4869bdf3f4788137411c5f36f2e72943a
refs/heads/master
1,610,462,544,433
1,488,596,497,000
1,488,596,497,000
72,063,527
0
0
null
null
null
null
UTF-8
Lean
false
false
1,075
lean
import data.set data.nat standard open classical set nat decidable -------- Definitions and Axioms -------- noncomputable theory definition tuples {A : Type} (S : set A) (n : ℕ) : set (set A) := { T : set A | T ⊆ S ∧ card T = n ∧ finite T} lemma sub_tuples {A : Type} (S1 S2 : set A) (H : S1 ⊆ S2) (n : ℕ) : tuples S1 n ⊆ tuples S2 n := take x, assume H1, have x ⊆ S2, from subset.trans (and.left H1) H, and.intro this (and.right H1) theorem dne {p : Prop} (H : ¬¬p) : p := or.elim (em p) (assume Hp : p, Hp) (assume Hnp : ¬p, absurd Hnp H) section variable {A : Type} abbreviation infinite (X : set A) : Prop := ¬ finite X end constant ω : set ℕ axiom natω : ∀ x : ℕ, x ∈ ω axiom infω : infinite ω abbreviation is_coloring (X : set ℕ) (n : ℕ) (μ : ℕ) (c : set ℕ → ℕ) : Prop := ∀₀ a ∈ tuples X n, c a < μ abbreviation is_homogeneous (X : set ℕ) (c : set ℕ → ℕ) (n μ : ℕ) (H : set ℕ) : Prop := is_coloring X n μ c ∧ H ⊆ X ∧ ∀₀ a ∈ tuples H n, ∀₀ b ∈ tuples H n, c a = c b
c8dcde8abaee28a5b837a159ec54e77f3dad9be2
f4e8ebc2be0df6ce96aeff2aea4781e55522cb21
/src/solutions/00_first_proofs.lean
35016ccbe09048b8d8e341709e6500fa29b18338
[ "Apache-2.0" ]
permissive
robertylewis/tutorials
fb8a78d1352405077d4c82c6a04deabb32c1e37b
d3e1ac9ce73b9ed93a20036ce2a354ee923c783e
refs/heads/master
1,666,261,949,784
1,591,464,085,000
1,591,464,607,000
270,056,466
0
0
Apache-2.0
1,591,465,315,000
1,591,465,314,000
null
UTF-8
Lean
false
false
18,033
lean
/- This file is intended for Lean beginners. The goal is to demonstrate what it feels like to prove things using Lean and mathlib. Complicated definitions and theory building are not covered. Everything is covered again more slowly and with exercises in the next files. -/ -- We want real numbers and their basic properties import data.real.basic -- We want to be able to define functions using the law of excluded middle noncomputable theory open_locale classical /- Our first goal is to define the set of upper bounds of a set of real numbers. This is already defined in mathlib (in a more general context), but we repeat it for the sake of exposition. Right-click "upper_bounds" below to get offered to jump to mathlib's version -/ #check upper_bounds /-- The set of upper bounds of a set of real numbers ℝ -/ def up_bounds (A : set ℝ) := { x : ℝ | ∀ a ∈ A, a ≤ x} /-- Predicate `is_max a A` means `a` is a maximum of `A` -/ def is_max (a : ℝ) (A : set ℝ) := a ∈ A ∧ a ∈ up_bounds A /- In the above definition, the symbol `∧` means "and". We also see the most visible difference between set theoretic foundations and type theoretic ones (used by almost all proof assistants). In set theory, everything is a set, and the only relation you get from foundations are `=` and `∈`. In type theory, there is a meta-theoretic relation of "typing": `a : ℝ` reads "`a` is a real number" or, more precisely, "the type of `a` is `ℝ`". Here "meta-theoretic" means this is not a statement you can prove or disprove inside the theory, it's a fact that is true or not. Here we impose this fact, in other circumstances, it would be checked by the Lean kernel. By contrast, `a ∈ A` is a statement inside the theory. Here it's part of the definition, in other circumstances it could be something proven inside Lean. -/ /- For illustrative purposes, we now define an infix version of the above predicate. It will allow us to write `a is_a_max_of A`, which is closer to a sentence. -/ infix `is_a_max_of`:55 := is_max /- Let's prove something now! A set of real numbers has at most one maximum. Here everything left of the final `:` is introducing the objects and assumption. The equality `x = y` right of the colon is the conclusion. -/ lemma unique_max (A : set ℝ) (x y : ℝ) (hx : x is_a_max_of A) (hy : y is_a_max_of A) : x = y := begin -- We first break our assumptions in their two constituent pieces. -- We are free to choose the name following `with` cases hx with x_in x_up, cases hy with y_in y_up, -- Assumption `x_up` means x isn't less than elements of A, let's apply this to y specialize x_up y, -- Assumption `x_up` now needs the information that `y` is indeed in `A`. specialize x_up y_in, -- Let's do this quicker with roles swapped specialize y_up x x_in, -- We explained to Lean the idea of this proof. -- Now we know `x ≤ y` and `y ≤ x`, and Lean shouldn't need more help. -- `linarith` proves equalities and inequalities that follow linearly from -- the assumption we have. linarith, end /- The above proof is too long, even if you remove comments. We don't really need the unpacking steps at the beginning; we can access both parts of the assumption `hx : x is_a_max_of A` using shortcuts `h.1` and `h.2`. We can also improve readability without assistance from the tactic state display, clearly announcing intermediate goals using `have`. This way we get to the following version of the same proof. -/ example (A : set ℝ) (x y : ℝ) (hx : x is_a_max_of A) (hy : y is_a_max_of A) : x = y := begin have : x ≤ y, from hy.2 x hx.1, have : y ≤ x, from hx.2 y hy.1, linarith, end /- Notice how mathematics based on type theory treats the assumption `∀ a ∈ A, a ≤ y` as a function turning an element `a` of `A` into the statement `a ≤ y`. More precisely, this assumption is the abbreviation of `∀ a : ℝ, a ∈ A → a ≤ y`. The expression `hy.2 x` appearing in the above proof is then the statement `x ∈ A → x ≤ y`, which itself is a function turning a statement `x ∈ A` into `x ≤ y` so that the full expression `hy.2 x hx.1` is indeed a proof of `x ≤ y`. One could argue a three-line-long proof of this lemma is still two lines too long. This is debatable, but mathlib's style is to write very short proofs for trivial lemmas. Those proofs are not easy to read but they are meant to indicate that the proof is probably not worth reading. In order to reach this stage, we need to know what `linarith` did for us. It invoked the lemma `le_antisymm` which says: `x ≤ y → y ≤ x → x = y`. This arrow, which is used both for function and implication, is right associative. So the statement is `x ≤ y → (y ≤ x → x = y)` which reads: I will send a proof `p` of `x ≤ y` to a function sending a proof `q'` of `y ≤ x` to a proof of `x = y`. Hence `le_antisymm p q'` is a proof of `x = y`. Using this we can get our one-line proof: -/ example (A : set ℝ) (x y : ℝ) (hx : x is_a_max_of A) (hy : y is_a_max_of A) : x = y := le_antisymm (hy.2 x hx.1) (hx.2 y hy.1) /- Such a proof is called a proof term (or a "term mode" proof). Notice it has no `begin` and `end`. It is directly the kind of low level proof that the Lean kernel is consuming. Commands like `cases`, `specialize` or `linarith` are called tactics, they help users constructing proof terms that could be very tedious to write directly. The most efficient proof style combines tactics with proof terms like our previous `have : x ≤ y, from hy.2 x hx.1` where `hy.2 x hx.1` is a proof term embeded inside a tactic mode proof. In the remaining of this file, we'll be characterizing infima of sets of real numbers in term of sequences. -/ /-- The set of lower bounds of a set of real numbers ℝ -/ def low_bounds (A : set ℝ) := { x : ℝ | ∀ a ∈ A, x ≤ a} /- We now define `a` is an infimum of `A`. Again there is already a more general version in mathlib. -/ def is_inf (x : ℝ) (A : set ℝ) := x is_a_max_of (low_bounds A) infix `is_an_inf_of`:55 := is_inf /- We need to prove that any number which is greater than the infimum of A is greater than some element of A. -/ lemma inf_lt {A : set ℝ} {x : ℝ} (hx : x is_an_inf_of A) : ∀ y, x < y → ∃ a ∈ A, a < y := begin -- Let `y` be any real number. intro y, -- Let's prove the contrapositive contrapose, -- The symbol `¬` means negation. Let's ask Lean to rewrite the goal without negation, -- pushing negation through quantifiers and inequalities push_neg, -- Let's assume the premise, calling the assumption `h` intro h, -- `h` is exactly saying `y` is a lower bound of `A` so the second part of -- the infimum assumption `hx` applied to `y` and `h` is exactly what we want. exact hx.2 y h end /- In the above proof, the sequence `contrapose, push_neg` is so common that it can be abbreviated to `contrapose!`. With these commands, we enter the gray zone between proof checking and proof finding. Practical computer proof checking crucially needs the computer to handle tedious proof steps. In the next proof, we'll start using `linarith` a bit more seriously, going one step further into automation. Our next real goal is to prove inequalities for limits of sequences. We extract the following lemma: if `y ≤ x + ε` for all positive `ε` then `y ≤ x`. -/ lemma le_of_le_add_eps {x y : ℝ} : (∀ ε > 0, y ≤ x + ε) → y ≤ x := begin -- Let's prove the contrapositive, asking Lean to push negations right away. contrapose!, -- Assume `h : x < y`. intro h, -- We need to find `ε` such that `ε` is positive and `x + ε < y`. -- Let's use `(y-x)/2` use ((y-x)/2), -- we now have two properties to prove. Let's do both in turn, using `linarith` split, linarith, linarith, end /- Note how `linarith` was used for both sub-goals at the end of the above proof. We could have shortened that using the semi-colon combinator instead of comma, writing `split ; linarith`. Next we will study a compressed version of that proof: -/ example {x y : ℝ} : (∀ ε > 0, y ≤ x + ε) → y ≤ x := begin contrapose!, exact assume h, ⟨(y-x)/2, by linarith, by linarith⟩, end /- The angle brackets `⟨` and `⟩` introduce compound data or proofs. A proof of a `∃ z, P z` statemement is composed of a witness `z₀` and a proof `h` of `P z₀`. The compound is denoted by `⟨z₀, h⟩`. In the example above, the predicate is itself compound, it is a conjunction `P z ∧ Q z`. So the proof term should read `⟨z₀, ⟨h₁, h₂⟩⟩` where `h₁` (resp. `h₂`) is a proof of `P z₀` (resp. `Q z₀`). But these so-called "anonymous constructor" brackets are right-associative, so we can get rid of the nested brackets. The keyword `by` introduces tactic mode inside term mode, it is a shorter version of the `begin`/`end` pair, which is more convenient for single tactic blocks. In this example, `begin` enters tactic mode, `exact` leaves it, `by` re-enters it. Going all the way to a proof term would make the proof much longer, because we crucially use automation with `contrapose!` and `linarith`. We can still get a one-line proof using curly braces to gather several tactic invocations, and the `by` abbreviation instead of `begin`/`end`: -/ example {x y : ℝ} : (∀ ε > 0, y ≤ x + ε) → y ≤ x := by { contrapose!, exact assume h, ⟨(y-x)/2, by linarith, by linarith⟩ } /- One could argue that the above proof is a bit too terse, and we are relying too much on linarith. Let's have more `linarith` calls for smaller steps. For the sake of (tiny) variation, we will also assume the premise and argue by contradiction instead of contraposing. -/ example {x y : ℝ} : (∀ ε > 0, y ≤ x + ε) → y ≤ x := begin intro h, -- Assume the conclusion is false, and call this assumption H. by_contradiction H, push_neg at H, -- Now let's compute. have key := calc -- Each line must end with a colon followed by a proof term -- We want to specialize our assumption `h` to `ε = (y-x)/2` but this is long to -- type, so let's put a hole `_` that Lean will fill in by comparing the -- statement we want to prove and our proof term with a hole. As usual, -- positivity of `(y-x)/2` is proved by `linarith` y ≤ x + (y-x)/2 : h _ (by linarith) ... = x/2 + y/2 : by ring ... < y : by linarith, -- our key now says `y < y` (notice how the sequence `≤`, `=`, `<` was correctly -- merged into a `<`). Let `linarith` find the desired contradiction now. linarith, -- alternatively, we could have provided the proof term -- `exact lt_irrefl y key` end /- Now we are ready for some analysis. Let's set up notation for absolute value -/ local notation `|`x`|` := abs x /- And let's define convergence of sequences of real numbers (of course there is a much more general definition in mathlib). -/ /-- The sequence `u` tends to `l` -/ def limit (u : ℕ → ℝ) (l : ℝ) := ∀ ε > 0, ∃ N, ∀ n ≥ N, |u n - l| ≤ ε /- In the above definition, `u n` denotes the n-th term of the sequence. We can add parentheses to get `u(n)` but we try to avoid parentheses because they pile up very quickly -/ -- If y ≤ u n for all n and u n goes to x then y ≤ x lemma le_lim {x y : ℝ} {u : ℕ → ℝ} (hu : limit u x) (ineq : ∀ n, y ≤ u n) : y ≤ x := begin -- Let's apply our previous lemma apply le_of_le_add_eps, -- We need to prove y ≤ x + ε for all positive ε. -- Let ε be any positive real intros ε ε_pos, -- we now specialize our limit assumption to this `ε`, and immediately -- fix a `N` as promised by the definition. cases hu ε ε_pos with N HN, -- Now we only need to compute until reaching the conclusion calc y ≤ u N : ineq N ... = x + (u N - x) : by linarith -- We'll need `add_le_add` which says `a ≤ b` and `c ≤ d` implies `a + c ≤ b + d` -- We need a lemma saying `z ≤ |z|`. Because we don't know the name of this lemma, -- let's use `library_search`. Because searching thourgh the library is slow, -- Lean will write what it found in the Lean message window when cursor is on -- that line, so that we can replace it by the lemma. We see `le_max_left` which -- says `a ≤ max a b`. Actually there is a more specific lemma `le_abs_self` ... ≤ x + |u N - x| : add_le_add (by linarith) (by library_search) ... ≤ x + ε : add_le_add (by linarith) (HN N (by linarith)), end /- The next lemma has been extracted from the main proof in order to discuss numbers. In ordinary maths, we know that ℕ is *not* contained in `ℝ`, whatever the construction of real numbers that we use. For instance a natural number is not an equivalence class of Cauchy sequences. But it's very easy to pretend otherwise. Formal maths requires slightly more care. In the statement below, the "type ascription" `(n + 1 : ℝ)` forces Lean to convert the natural number `n+1` into a real number. The "inclusion" map will be displayed in tactic state as `↑`. There are various lemmas asserting this map is compatible with addition and monotone, but we don't want to bother writing their names. The `norm_cast` tactic is designed to wisely apply those lemmas for us. -/ lemma inv_succ_pos : ∀ n : ℕ, 1/(n+1 : ℝ) > 0 := begin -- Let `n` be any integer intro n, -- Since we don't know the name of the relevant lemma, asserting that the inverse of -- a positive number is positive, let's state that is suffices -- to prove that `n+1`, seen as a real number, is positive, and ask `library_search` suffices : (n + 1 : ℝ) > 0, { library_search }, -- Now we want to reduce to a statement about natural numbers, not real numbers -- coming from natural numbers. norm_cast, -- and then get the usual help from `linarith` linarith, end /- That was a pretty long proof for an obvious fact. And stating it as a lemma feels stupid, so let's find a way to write it on one line in case we want to include it in some other proof without stating a lemma. First the `library_search` call above displays the name of the relevant lemma: `one_div_pos_of_pos`. We can also replace the `linarith` call on the last line by `library_search` to learn the name of the lemma `nat.succ_pos` asserting that the successor of a natural number is positive. There is also a variant on `norm_cast` that combines it with `exact`. The term mode analogue of `intro` is `λ`. We get down to: -/ example : ∀ n : ℕ, 1/(n+1 : ℝ) > 0 := λ n, one_div_pos_of_pos (by exact_mod_cast nat.succ_pos n) /- The next proof uses mostly known things, so we will commment only new aspects. -/ lemma limit_inv_succ : ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, 1/(n + 1 : ℝ) ≤ ε := begin intros ε ε_pos, suffices : ∃ N : ℕ, 1/ε ≤ N, { -- Because we didn't provide a name for the above statement, Lean called it `this`. -- Let's fix an `N` that works. cases this with N HN, use N, intros n Hn, -- Now we want to rewrite the goal using lemmas -- `div_le_iff' : 0 < b → (a / b ≤ c ↔ a ≤ b * c)` -- `div_le_iff : 0 < b → (a / b ≤ c ↔ a ≤ c * b)` -- the second one will be rewritten from right to left, as indicated by `←`. -- Lean will create a side goal for the required positivity assumption that -- we don't provide for `div_le_iff'`. rw [div_le_iff', ← div_le_iff ε_pos], -- We want to replace assumption `Hn` by its real counter-part so that -- linarith can find what it needs. replace Hn : (N : ℝ) ≤ n, exact_mod_cast Hn, linarith, -- we are still left with the positivity assumption, but already discussed -- how to prove it in the preceding lemma exact_mod_cast nat.succ_pos n }, -- Now we need to prove that sufficient statement. -- We want to use that `ℝ` is archimedean. So we start typing -- `exact archimedean_` and hit Ctrl-space to see what completion Lean proposes -- the lemma `archimedean_iff_nat_le` sounds promising. We select the left to -- right implication using `.1`. This a generic lemma for fields equiped with -- a linear (ie total) order. We need to provide a proof that `ℝ` is indeed -- archimedean. This is done using the `apply_instance` tactic that will be -- covered elsewhere. exact archimedean_iff_nat_le.1 (by apply_instance) (1/ε), end /- We can now put all pieces together, with almost no new things to explain. -/ lemma inf_seq (A : set ℝ) (x : ℝ) : (x is_an_inf_of A) ↔ (x ∈ low_bounds A ∧ ∃ u : ℕ → ℝ, limit u x ∧ ∀ n, u n ∈ A ) := begin split, { intro h, split, { exact h.1 }, -- On the next line, we don't need to tell Lean to treat `n+1` as a real number because -- we add `x` to it, so Lean knows there is only one way to make sense of this expression. have key : ∀ n : ℕ, ∃ a ∈ A, a < x + 1/(n+1), { intro n, -- we can use the lemma we proved above apply inf_lt h, -- and another one we proved! have : 0 < 1/(n+1 : ℝ), from inv_succ_pos n, linarith }, -- Now we need to use axiom of (countable) choice choose u hu using key, use u, split, { intros ε ε_pos, -- again we use a lemma we proved, specializing it to our fixed `ε`, and fixing a `N` cases limit_inv_succ ε ε_pos with N H, use N, intros n hn, have : x ≤ u n, from h.1 _ (hu n).1, have := calc u n < x + 1/(n + 1) : (hu n).2 ... ≤ x + ε : add_le_add (le_refl x) (H n hn), rw abs_of_nonneg ; linarith }, { intro n, exact (hu n).1 } }, { intro h, -- Assumption `h` is made of nested compound statements. We can use the -- recursive version of `cases` to unpack it in one go. rcases h with ⟨x_min, u, lim, huA⟩, split, exact x_min, intros y y_mino, apply le_lim lim, intro n, exact y_mino (u n) (huA n) }, end
a5b1f07df63738c12fbb36a10022b5b3e8b295f1
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/sym/card.lean
ce49ebe29e323dad399bc83eaf461c2167083fbf
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
8,795
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, Huỳnh Trần Khanh, Stuart Presnell -/ import algebra.big_operators.basic import data.finset.sym import data.fintype.sum /-! # Stars and bars In this file, we prove (in `sym.card_sym_eq_multichoose`) that the function `multichoose n k` defined in `data/nat/choose/basic` counts the number of multisets of cardinality `k` over an alphabet of cardinality `n`. In conjunction with `nat.multichoose_eq` proved in `data/nat/choose/basic`, which shows that `multichoose n k = choose (n + k - 1) k`, this is central to the "stars and bars" technique in combinatorics, where we switch between counting multisets of size `k` over an alphabet of size `n` to counting strings of `k` elements ("stars") separated by `n-1` dividers ("bars"). ## Informal statement Many problems in mathematics are of the form of (or can be reduced to) putting `k` indistinguishable objects into `n` distinguishable boxes; for example, the problem of finding natural numbers `x1, ..., xn` whose sum is `k`. This is equivalent to forming a multiset of cardinality `k` from an alphabet of cardinality `n` -- for each box `i ∈ [1, n]` the multiset contains as many copies of `i` as there are items in the `i`th box. The "stars and bars" technique arises from another way of presenting the same problem. Instead of putting `k` items into `n` boxes, we take a row of `k` items (the "stars") and separate them by inserting `n-1` dividers (the "bars"). For example, the pattern `*|||**|*|` exhibits 4 items distributed into 6 boxes -- note that any box, including the first and last, may be empty. Such arrangements of `k` stars and `n-1` bars are in 1-1 correspondence with multisets of size `k` over an alphabet of size `n`, and are counted by `choose (n + k - 1) k`. Note that this problem is one component of Gian-Carlo Rota's "Twelvefold Way" https://en.wikipedia.org/wiki/Twelvefold_way ## Formal statement Here we generalise the alphabet to an arbitrary fintype `α`, and we use `sym α k` as the type of multisets of size `k` over `α`. Thus the statement that these are counted by `multichoose` is: `sym.card_sym_eq_multichoose : card (sym α k) = multichoose (card α) k` while the "stars and bars" technique gives `sym.card_sym_eq_choose : card (sym α k) = choose (card α + k - 1) k` ## Tags stars and bars, multichoose -/ open finset fintype function sum nat variables {α β : Type*} namespace sym section sym variables (α) (n : ℕ) /-- Over `fin n+1`, the multisets of size `k+1` containing `0` are equivalent to those of size `k`, as demonstrated by respectively erasing or appending `0`. -/ protected def E1 {n k : ℕ} : {s : sym (fin n.succ) k.succ // ↑0 ∈ s} ≃ sym (fin n.succ) k := { to_fun := λ s, s.1.erase 0 s.2, inv_fun := λ s, ⟨cons 0 s, mem_cons_self 0 s⟩, left_inv := λ s, by simp, right_inv := λ s, by simp } /-- The multisets of size `k` over `fin n+2` not containing `0` are equivalent to those of size `k` over `fin n+1`, as demonstrated by respectively decrementing or incrementing every element of the multiset. -/ protected def E2 {n k : ℕ} : {s : sym (fin n.succ.succ) k // ↑0 ∉ s} ≃ sym (fin n.succ) k := { to_fun := λ s, map (fin.pred_above 0) s.1, inv_fun := λ s, ⟨map (fin.succ_above 0) s, (mt mem_map.1) (not_exists.2 (λ t, (not_and.2 (λ _, (fin.succ_above_ne _ t)))))⟩, left_inv := λ s, by { obtain ⟨s, hs⟩ := s, simp only [map_map, comp_app], nth_rewrite_rhs 0 ←(map_id' s), refine sym.map_congr (λ v hv, _), simp [fin.pred_above_zero (ne_of_mem_of_not_mem hv hs)] }, right_inv := λ s, by { simp only [fin.zero_succ_above, map_map, comp_app], nth_rewrite_rhs 0 ←(map_id' s), refine sym.map_congr (λ v hv, _), rw [←fin.zero_succ_above v, ←fin.cast_succ_zero, fin.pred_above_succ_above 0 v] } } lemma card_sym_fin_eq_multichoose (n k : ℕ) : card (sym (fin n) k) = multichoose n k := begin apply @pincer_recursion (λ n k, card (sym (fin n) k) = multichoose n k), { simp }, { intros b, induction b with b IHb, { simp }, rw [multichoose_zero_succ, card_eq_zero_iff], apply_instance }, { intros x y h1 h2, rw [multichoose_succ_succ, ←h1, ←h2, add_comm], cases x, { simp only [card_eq_zero_iff, card_unique, self_eq_add_right], apply_instance }, rw ←card_sum, refine fintype.card_congr (equiv.symm _), apply (equiv.sum_congr sym.E1.symm sym.E2.symm).trans, apply equiv.sum_compl }, end /-- For any fintype `α` of cardinality `n`, `card (sym α k) = multichoose (card α) k` -/ lemma card_sym_eq_multichoose (α : Type*) (k : ℕ) [fintype α] [fintype (sym α k)] : card (sym α k) = multichoose (card α) k := by { rw ←card_sym_fin_eq_multichoose, exact card_congr (equiv_congr (equiv_fin α)) } /-- The *stars and bars* lemma: the cardinality of `sym α k` is equal to `nat.choose (card α + k - 1) k`. -/ lemma card_sym_eq_choose {α : Type*} [fintype α] (k : ℕ) [fintype (sym α k)] : card (sym α k) = (card α + k - 1).choose k := by rw [card_sym_eq_multichoose, nat.multichoose_eq] end sym end sym namespace sym2 variables [decidable_eq α] /-- The `diag` of `s : finset α` is sent on a finset of `sym2 α` of card `s.card`. -/ lemma card_image_diag (s : finset α) : (s.diag.image quotient.mk).card = s.card := begin rw [card_image_of_inj_on, diag_card], rintro ⟨x₀, x₁⟩ hx _ _ h, cases quotient.eq.1 h, { refl }, { simp only [mem_coe, mem_diag] at hx, rw hx.2 } end lemma two_mul_card_image_off_diag (s : finset α) : 2 * (s.off_diag.image quotient.mk).card = s.off_diag.card := begin rw [card_eq_sum_card_fiberwise (λ x, mem_image_of_mem _ : ∀ x ∈ s.off_diag, quotient.mk x ∈ s.off_diag.image quotient.mk), sum_const_nat (quotient.ind _), mul_comm], rintro ⟨x, y⟩ hxy, simp_rw [mem_image, exists_prop, mem_off_diag, quotient.eq] at hxy, obtain ⟨a, ⟨ha₁, ha₂, ha⟩, h⟩ := hxy, obtain ⟨hx, hy, hxy⟩ : x ∈ s ∧ y ∈ s ∧ x ≠ y, { cases h; have := ha.symm; exact ⟨‹_›, ‹_›, ‹_›⟩ }, have hxy' : y ≠ x := hxy.symm, have : s.off_diag.filter (λ z, ⟦z⟧ = ⟦(x, y)⟧) = ({(x, y), (y, x)} : finset _), { ext ⟨x₁, y₁⟩, rw [mem_filter, mem_insert, mem_singleton, sym2.eq_iff, prod.mk.inj_iff, prod.mk.inj_iff, and_iff_right_iff_imp], rintro (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩); rw mem_off_diag; exact ⟨‹_›, ‹_›, ‹_›⟩ }, -- hxy' is used here rw [this, card_insert_of_not_mem, card_singleton], simp only [not_and, prod.mk.inj_iff, mem_singleton], exact λ _, hxy', end /-- The `off_diag` of `s : finset α` is sent on a finset of `sym2 α` of card `s.off_diag.card / 2`. This is because every element `⟦(x, y)⟧` of `sym2 α` not on the diagonal comes from exactly two pairs: `(x, y)` and `(y, x)`. -/ lemma card_image_off_diag (s : finset α) : (s.off_diag.image quotient.mk).card = s.card.choose 2 := by rw [nat.choose_two_right, mul_tsub, mul_one, ←off_diag_card, nat.div_eq_of_eq_mul_right zero_lt_two (two_mul_card_image_off_diag s).symm] lemma card_subtype_diag [fintype α] : card {a : sym2 α // a.is_diag} = card α := begin convert card_image_diag (univ : finset α), rw [fintype.card_of_subtype, ←filter_image_quotient_mk_is_diag], rintro x, rw [mem_filter, univ_product_univ, mem_image], obtain ⟨a, ha⟩ := quotient.exists_rep x, exact and_iff_right ⟨a, mem_univ _, ha⟩, end lemma card_subtype_not_diag [fintype α] : card {a : sym2 α // ¬a.is_diag} = (card α).choose 2 := begin convert card_image_off_diag (univ : finset α), rw [fintype.card_of_subtype, ←filter_image_quotient_mk_not_is_diag], rintro x, rw [mem_filter, univ_product_univ, mem_image], obtain ⟨a, ha⟩ := quotient.exists_rep x, exact and_iff_right ⟨a, mem_univ _, ha⟩, end /-- Finset **stars and bars** for the case `n = 2`. -/ lemma _root_.finset.card_sym2 (s : finset α) : s.sym2.card = s.card * (s.card + 1) / 2 := begin rw [←image_diag_union_image_off_diag, card_union_eq, sym2.card_image_diag, sym2.card_image_off_diag, nat.choose_two_right, add_comm, ←nat.triangle_succ, nat.succ_sub_one, mul_comm], rw disjoint_left, rintro m ha hb, rw [mem_image] at ha hb, obtain ⟨⟨a, ha, rfl⟩, ⟨b, hb, hab⟩⟩ := ⟨ha, hb⟩, refine not_is_diag_mk_of_mem_off_diag hb _, rw hab, exact is_diag_mk_of_mem_diag ha, end /-- Type **stars and bars** for the case `n = 2`. -/ protected lemma card [fintype α] : card (sym2 α) = card α * (card α + 1) / 2 := finset.card_sym2 _ end sym2
23d9249a8b90998a7736fc8c6dcb26260252b18b
b04a2b9331022307985cb4dee8a75dd804625569
/hockeystick.lean
9585c6d3037f27050a6ba87d6c42855dad481456
[]
no_license
tjhance/lean-project
558de3b6f88b5b12241ec8d0803027a32eaea13f
c00a01e02ae2fee4e90d48bfd8504d2d45fdb43c
refs/heads/master
1,588,096,917,016
1,556,580,095,000
1,556,580,106,000
175,465,730
3
1
null
null
null
null
UTF-8
Lean
false
false
5,200
lean
import data.nat.choose import data.set import data.set.finite import data.multiset import data.finset import data.list import data.finset algebra.big_operators import algebra.big_operators import init.algebra.functions import algebra.group_power #eval choose 5 4 #check nat.rec_on /- Collaboration between Travis Hance (thance) Katherine Cordwell (kcordwell) -/ /- Following the proof at https://artofproblemsolving.com/wiki/index.php/Combinatorial_identity -/ /- sum_for_hockey_stick takes r and k and computes the sum from i = r to i = r + k of (i choose r) -/ def sum_for_hockey_stick (r k : ℕ) : ℕ := nat.rec_on k 1 (λ k ih, ih + (choose (r + k + 1) r)) #eval sum_for_hockey_stick 5 0 /- this is really saying 5 choose 5 is 1 -/ #eval sum_for_hockey_stick 5 1 /- this is saying 5 choose 5 + 6 choose 5 is 7 -/ #eval choose 7 6 #eval sum_for_hockey_stick 5 2 /- calculates 5 choose 5 + 6 choose 5 + 7 choose 5-/ #eval choose 8 6 #eval sum_for_hockey_stick 5 3 /- calculates 5 choose 5 + 6 choose 5 + 7 choose 5 + 8 choose 5-/ #eval choose 9 6 /- Says that for natural numbers r and n, if n >= r, then the sum from i = r to n of i choose r equals n + 1 choose r + 1 -/ theorem hockey_stick_identity (k r : ℕ) : sum_for_hockey_stick r k = (choose (r + k + 1) (r + 1)) := begin induction k with k ih, {have h: sum_for_hockey_stick r 0 = 1, by refl, simp[*, refl]}, { calc sum_for_hockey_stick r (nat.succ k) = (sum_for_hockey_stick r k) + (choose (r + k + 1) r): by simp[sum_for_hockey_stick] ... = (choose (r + k + 1) (r + 1)) + (choose (r + k + 1) r) : by rw[ih] ... = (choose (r + k + 1) r) + (choose (r + k + 1) (r + 1)): by simp ... = choose (r + k + 1) r + choose (r + k + 1) (nat.succ r) : by refl ... = choose (r + k + 1 + 1) (r + 1) : by rw[←choose] } end /- Here is my first attempt at stating Vandermonde's identity. Vandermonde's identity says that m + n choose r equals the sum from k = 0 to r of (m choose k)*(n choose r - k). I tried to do an inductive proof as at https://math.stackexchange.com/questions/219928/inductive-proof-for-vandermondes-identity/219938, but this was not so good because the induction was on both n and r, and it got fairly messy. So I decided to try a different approach (see below). -/ def sum_for_vandermonde (m n r i: ℕ) : ℕ := nat.rec_on i ((choose m 0)*(choose n r)) (λ i ih, ih + (choose m (i + 1))*(choose n (r - (i + 1)))) #eval sum_for_vandermonde 3 4 6 6 #eval choose (3 + 4) 6 #eval sum_for_vandermonde 12 5 8 8 #eval choose (12 + 5) 8 /- double-checked with Mathematica -/ #eval sum_for_vandermonde 12 5 8 3 #eval sum_for_vandermonde 3 4 6 5 lemma sum_for_vandermonde_with_n_is_zero (m r: ℕ) : sum_for_vandermonde m 0 r r = choose m r := begin induction r with r ih, { calc sum_for_vandermonde m 0 0 0 = (choose m 0)*(choose 0 0) : by refl ... = choose m 0 : by simp }, calc sum_for_vandermonde m 0 (nat.succ r) (nat.succ r) = sorry : sorry ... = choose m (nat.succ r): sorry end theorem vandermonde_identity (m n : ℕ) : ∀ r : ℕ, sum_for_vandermonde m n r r = choose (m + n) r := begin induction n with n ih1, {simp[choose, sum_for_vandermonde_with_n_is_zero]}, intro r, simp[sum_for_vandermonde, choose], sorry end /- Next I decided to restate Vandermonde's theorem using big_ops and started on the algebraic proof of Vandermonde's as found on Wikipedia: https://en.wikipedia.org/wiki/Vandermonde%27s_identity. I proved the first few steps but ended up spending time on some other parts of the project and didn't finish. -/ /- Lemma for a case of using the binomial theorem -/ variables x y : ℕ lemma binomial_theorem_with_1 (x n : ℕ) : ∀ n : ℕ, (x + 1)^n = (finset.range (nat.succ n)).sum (λ m, x ^ m * choose n m) := begin intro n, have h3 := add_pow x 1 n, simp at h3, apply h3 end /-show sum from r = 0 to m + n (m + n choose r) x^r = (1 + x)^(m + n) = ( 1 + x)^m = (1 + x)^n = (scary) * (scary) -/ #check pow_add lemma binomial_theorem_for_vandermonde (x m n : ℕ) : ∀ n m: ℕ, (finset.range (m + nat.succ n)).sum(λ r, x^r * (choose (m + n) r)) = (finset.range (nat.succ m)).sum(λ r, x^r * choose m r)*(finset.range (nat.succ n)).sum(λ r, x^r * choose n r) := begin intros n m, have h := pow_add (x + 1) m n, have h1 : n + m = m + n, by simp[add_comm], simp at h, rw h1 at h, calc (finset.range (m + nat.succ n)).sum(λ r, x^r * (choose (m + n) r)) = (x + 1)^(m + n): by rw ← binomial_theorem_with_1 x (m + nat.succ n) ... = (x + 1)^m * (x + 1)^n: h ... = (finset.range (nat.succ m)).sum(λ r, x^r * choose m r) * (x + 1)^n: by rw binomial_theorem_with_1 x (nat.succ m) ... = (finset.range (nat.succ m)).sum(λ r, x^r * choose m r)*(finset.range (nat.succ n)).sum(λ r, x^r * choose n r) : by rw binomial_theorem_with_1 x (nat.succ n) end /- Vandermonde's identity (restated) -/ theorem vandermonde_thm (m n r : ℕ) : ∀ r : ℕ, (finset.range (nat.succ r)).sum(λ k, (choose m k)*(choose n (r-k)))= choose (m + n) r := begin sorry end
855e1ea6811c7b89a462de47312362546653acd6
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/interactive/lean3HoverIssue.lean
885a59e73ceba9ad0d8a269526c9189e8c7d0999
[ "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
751
lean
example (x y : Nat) (h : x = y) : y = x := by exact h.symm --^ textDocument/hover --^ textDocument/hover example (x y : Nat) (h : x = y) : y = x := h.symm --^ textDocument/hover example (x y : Nat) (h : x = y) : y = x := by exact (Eq.symm (Eq.symm h.symm)) --^ textDocument/hover --^ textDocument/hover --^ textDocument/hover --^ textDocument/hover
702c197ca645d24187ce70507578e5790a67cf10
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/num/basic.lean
3a95ab7f0b8e91c01710894bed1de270189f309b
[ "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
16,916
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro -/ /-! # Binary representation of integers using inductive types > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > https://github.com/leanprover-community/mathlib4/pull/607 > Any changes to this file require a corresponding PR to mathlib4. Note: Unlike in Coq, where this representation is preferred because of the reliance on kernel reduction, in Lean this representation is discouraged in favor of the "Peano" natural numbers `nat`, and the purpose of this collection of theorems is to show the equivalence of the different approaches. -/ /-- The type of positive binary numbers. 13 = 1101(base 2) = bit1 (bit0 (bit1 one)) -/ @[derive has_reflect, derive decidable_eq] inductive pos_num : Type | one : pos_num | bit1 : pos_num → pos_num | bit0 : pos_num → pos_num instance : has_one pos_num := ⟨pos_num.one⟩ instance : inhabited pos_num := ⟨1⟩ /-- The type of nonnegative binary numbers, using `pos_num`. 13 = 1101(base 2) = pos (bit1 (bit0 (bit1 one))) -/ @[derive has_reflect, derive decidable_eq] inductive num : Type | zero : num | pos : pos_num → num instance : has_zero num := ⟨num.zero⟩ instance : has_one num := ⟨num.pos 1⟩ instance : inhabited num := ⟨0⟩ /-- Representation of integers using trichotomy around zero. 13 = 1101(base 2) = pos (bit1 (bit0 (bit1 one))) -13 = -1101(base 2) = neg (bit1 (bit0 (bit1 one))) -/ @[derive has_reflect, derive decidable_eq] inductive znum : Type | zero : znum | pos : pos_num → znum | neg : pos_num → znum instance : has_zero znum := ⟨znum.zero⟩ instance : has_one znum := ⟨znum.pos 1⟩ instance : inhabited znum := ⟨0⟩ namespace pos_num /-- `bit b n` appends the bit `b` to the end of `n`, where `bit tt x = x1` and `bit ff x = x0`. -/ def bit (b : bool) : pos_num → pos_num := cond b bit1 bit0 /-- The successor of a `pos_num`. -/ def succ : pos_num → pos_num | 1 := bit0 one | (bit1 n) := bit0 (succ n) | (bit0 n) := bit1 n /-- Returns a boolean for whether the `pos_num` is `one`. -/ def is_one : pos_num → bool | 1 := tt | _ := ff /-- Addition of two `pos_num`s. -/ protected def add : pos_num → pos_num → pos_num | 1 b := succ b | a 1 := succ a | (bit0 a) (bit0 b) := bit0 (add a b) | (bit1 a) (bit1 b) := bit0 (succ (add a b)) | (bit0 a) (bit1 b) := bit1 (add a b) | (bit1 a) (bit0 b) := bit1 (add a b) instance : has_add pos_num := ⟨pos_num.add⟩ /-- The predecessor of a `pos_num` as a `num`. -/ def pred' : pos_num → num | 1 := 0 | (bit0 n) := num.pos (num.cases_on (pred' n) 1 bit1) | (bit1 n) := num.pos (bit0 n) /-- The predecessor of a `pos_num` as a `pos_num`. This means that `pred 1 = 1`. -/ def pred (a : pos_num) : pos_num := num.cases_on (pred' a) 1 id /-- The number of bits of a `pos_num`, as a `pos_num`. -/ def size : pos_num → pos_num | 1 := 1 | (bit0 n) := succ (size n) | (bit1 n) := succ (size n) /-- The number of bits of a `pos_num`, as a `nat`. -/ def nat_size : pos_num → nat | 1 := 1 | (bit0 n) := nat.succ (nat_size n) | (bit1 n) := nat.succ (nat_size n) /-- Multiplication of two `pos_num`s. -/ protected def mul (a : pos_num) : pos_num → pos_num | 1 := a | (bit0 b) := bit0 (mul b) | (bit1 b) := bit0 (mul b) + a instance : has_mul pos_num := ⟨pos_num.mul⟩ /-- `of_nat_succ n` is the `pos_num` corresponding to `n + 1`. -/ def of_nat_succ : ℕ → pos_num | 0 := 1 | (nat.succ n) := succ (of_nat_succ n) /-- `of_nat n` is the `pos_num` corresponding to `n`, except for `of_nat 0 = 1`. -/ def of_nat (n : ℕ) : pos_num := of_nat_succ (nat.pred n) open ordering /-- Ordering of `pos_num`s. -/ def cmp : pos_num → pos_num → ordering | 1 1 := eq | _ 1 := gt | 1 _ := lt | (bit0 a) (bit0 b) := cmp a b | (bit0 a) (bit1 b) := ordering.cases_on (cmp a b) lt lt gt | (bit1 a) (bit0 b) := ordering.cases_on (cmp a b) lt gt gt | (bit1 a) (bit1 b) := cmp a b instance : has_lt pos_num := ⟨λa b, cmp a b = ordering.lt⟩ instance : has_le pos_num := ⟨λa b, ¬ b < a⟩ instance decidable_lt : @decidable_rel pos_num (<) | a b := by dsimp [(<)]; apply_instance instance decidable_le : @decidable_rel pos_num (≤) | a b := by dsimp [(≤)]; apply_instance end pos_num section variables {α : Type*} [has_one α] [has_add α] /-- `cast_pos_num` casts a `pos_num` into any type which has `1` and `+`. -/ def cast_pos_num : pos_num → α | 1 := 1 | (pos_num.bit0 a) := bit0 (cast_pos_num a) | (pos_num.bit1 a) := bit1 (cast_pos_num a) /-- `cast_num` casts a `num` into any type which has `0`, `1` and `+`. -/ def cast_num [z : has_zero α] : num → α | 0 := 0 | (num.pos p) := cast_pos_num p -- see Note [coercion into rings] @[priority 900] instance pos_num_coe : has_coe_t pos_num α := ⟨cast_pos_num⟩ -- see Note [coercion into rings] @[priority 900] instance num_nat_coe [z : has_zero α] : has_coe_t num α := ⟨cast_num⟩ instance : has_repr pos_num := ⟨λ n, repr (n : ℕ)⟩ instance : has_repr num := ⟨λ n, repr (n : ℕ)⟩ end namespace num open pos_num /-- The successor of a `num` as a `pos_num`. -/ def succ' : num → pos_num | 0 := 1 | (pos p) := succ p /-- The successor of a `num` as a `num`. -/ def succ (n : num) : num := pos (succ' n) /-- Addition of two `num`s. -/ protected def add : num → num → num | 0 a := a | b 0 := b | (pos a) (pos b) := pos (a + b) instance : has_add num := ⟨num.add⟩ /-- `bit0 n` appends a `0` to the end of `n`, where `bit0 n = n0`. -/ protected def bit0 : num → num | 0 := 0 | (pos n) := pos (pos_num.bit0 n) /-- `bit1 n` appends a `1` to the end of `n`, where `bit1 n = n1`. -/ protected def bit1 : num → num | 0 := 1 | (pos n) := pos (pos_num.bit1 n) /-- `bit b n` appends the bit `b` to the end of `n`, where `bit tt x = x1` and `bit ff x = x0`. -/ def bit (b : bool) : num → num := cond b num.bit1 num.bit0 /-- The number of bits required to represent a `num`, as a `num`. `size 0` is defined to be `0`. -/ def size : num → num | 0 := 0 | (pos n) := pos (pos_num.size n) /-- The number of bits required to represent a `num`, as a `nat`. `size 0` is defined to be `0`. -/ def nat_size : num → nat | 0 := 0 | (pos n) := pos_num.nat_size n /-- Multiplication of two `num`s. -/ protected def mul : num → num → num | 0 _ := 0 | _ 0 := 0 | (pos a) (pos b) := pos (a * b) instance : has_mul num := ⟨num.mul⟩ open ordering /-- Ordering of `num`s. -/ def cmp : num → num → ordering | 0 0 := eq | _ 0 := gt | 0 _ := lt | (pos a) (pos b) := pos_num.cmp a b instance : has_lt num := ⟨λa b, cmp a b = ordering.lt⟩ instance : has_le num := ⟨λa b, ¬ b < a⟩ instance decidable_lt : @decidable_rel num (<) | a b := by dsimp [(<)]; apply_instance instance decidable_le : @decidable_rel num (≤) | a b := by dsimp [(≤)]; apply_instance /-- Converts a `num` to a `znum`. -/ def to_znum : num → znum | 0 := 0 | (pos a) := znum.pos a /-- Converts `x : num` to `-x : znum`. -/ def to_znum_neg : num → znum | 0 := 0 | (pos a) := znum.neg a /-- Converts a `nat` to a `num`. -/ def of_nat' : ℕ → num := nat.binary_rec 0 (λ b n, cond b num.bit1 num.bit0) end num namespace znum open pos_num /-- The negation of a `znum`. -/ def zneg : znum → znum | 0 := 0 | (pos a) := neg a | (neg a) := pos a instance : has_neg znum := ⟨zneg⟩ /-- The absolute value of a `znum` as a `num`. -/ def abs : znum → num | 0 := 0 | (pos a) := num.pos a | (neg a) := num.pos a /-- The successor of a `znum`. -/ def succ : znum → znum | 0 := 1 | (pos a) := pos (pos_num.succ a) | (neg a) := (pos_num.pred' a).to_znum_neg /-- The predecessor of a `znum`. -/ def pred : znum → znum | 0 := neg 1 | (pos a) := (pos_num.pred' a).to_znum | (neg a) := neg (pos_num.succ a) /-- `bit0 n` appends a `0` to the end of `n`, where `bit0 n = n0`. -/ protected def bit0 : znum → znum | 0 := 0 | (pos n) := pos (pos_num.bit0 n) | (neg n) := neg (pos_num.bit0 n) /-- `bit1 x` appends a `1` to the end of `x`, mapping `x` to `2 * x + 1`. -/ protected def bit1 : znum → znum | 0 := 1 | (pos n) := pos (pos_num.bit1 n) | (neg n) := neg (num.cases_on (pred' n) 1 pos_num.bit1) /-- `bitm1 x` appends a `1` to the end of `x`, mapping `x` to `2 * x - 1`. -/ protected def bitm1 : znum → znum | 0 := neg 1 | (pos n) := pos (num.cases_on (pred' n) 1 pos_num.bit1) | (neg n) := neg (pos_num.bit1 n) /-- Converts an `int` to a `znum`. -/ def of_int' : ℤ → znum | (n : ℕ) := num.to_znum (num.of_nat' n) | -[1+ n] := num.to_znum_neg (num.of_nat' (n+1)) end znum namespace pos_num open znum /-- Subtraction of two `pos_num`s, producing a `znum`. -/ def sub' : pos_num → pos_num → znum | a 1 := (pred' a).to_znum | 1 b := (pred' b).to_znum_neg | (bit0 a) (bit0 b) := (sub' a b).bit0 | (bit0 a) (bit1 b) := (sub' a b).bitm1 | (bit1 a) (bit0 b) := (sub' a b).bit1 | (bit1 a) (bit1 b) := (sub' a b).bit0 /-- Converts a `znum` to `option pos_num`, where it is `some` if the `znum` was positive and `none` otherwise. -/ def of_znum' : znum → option pos_num | (znum.pos p) := some p | _ := none /-- Converts a `znum` to a `pos_num`, mapping all out of range values to `1`. -/ def of_znum : znum → pos_num | (znum.pos p) := p | _ := 1 /-- Subtraction of `pos_num`s, where if `a < b`, then `a - b = 1`. -/ protected def sub (a b : pos_num) : pos_num := match sub' a b with | (znum.pos p) := p | _ := 1 end instance : has_sub pos_num := ⟨pos_num.sub⟩ end pos_num namespace num /-- The predecessor of a `num` as an `option num`, where `ppred 0 = none` -/ def ppred : num → option num | 0 := none | (pos p) := some p.pred' /-- The predecessor of a `num` as a `num`, where `pred 0 = 0`. -/ def pred : num → num | 0 := 0 | (pos p) := p.pred' /-- Divides a `num` by `2` -/ def div2 : num → num | 0 := 0 | 1 := 0 | (pos (pos_num.bit0 p)) := pos p | (pos (pos_num.bit1 p)) := pos p /-- Converts a `znum` to an `option num`, where `of_znum' p = none` if `p < 0`. -/ def of_znum' : znum → option num | 0 := some 0 | (znum.pos p) := some (pos p) | (znum.neg p) := none /-- Converts a `znum` to an `option num`, where `of_znum p = 0` if `p < 0`. -/ def of_znum : znum → num | (znum.pos p) := pos p | _ := 0 /-- Subtraction of two `num`s, producing a `znum`. -/ def sub' : num → num → znum | 0 0 := 0 | (pos a) 0 := znum.pos a | 0 (pos b) := znum.neg b | (pos a) (pos b) := a.sub' b /-- Subtraction of two `num`s, producing an `option num`. -/ def psub (a b : num) : option num := of_znum' (sub' a b) /-- Subtraction of two `num`s, where if `a < b`, `a - b = 0`. -/ protected def sub (a b : num) : num := of_znum (sub' a b) instance : has_sub num := ⟨num.sub⟩ end num namespace znum open pos_num /-- Addition of `znum`s. -/ protected def add : znum → znum → znum | 0 a := a | b 0 := b | (pos a) (pos b) := pos (a + b) | (pos a) (neg b) := sub' a b | (neg a) (pos b) := sub' b a | (neg a) (neg b) := neg (a + b) instance : has_add znum := ⟨znum.add⟩ /-- Multiplication of `znum`s. -/ protected def mul : znum → znum → znum | 0 a := 0 | b 0 := 0 | (pos a) (pos b) := pos (a * b) | (pos a) (neg b) := neg (a * b) | (neg a) (pos b) := neg (a * b) | (neg a) (neg b) := pos (a * b) instance : has_mul znum := ⟨znum.mul⟩ open ordering /-- Ordering on `znum`s. -/ def cmp : znum → znum → ordering | 0 0 := eq | (pos a) (pos b) := pos_num.cmp a b | (neg a) (neg b) := pos_num.cmp b a | (pos _) _ := gt | (neg _) _ := lt | _ (pos _) := lt | _ (neg _) := gt instance : has_lt znum := ⟨λa b, cmp a b = ordering.lt⟩ instance : has_le znum := ⟨λa b, ¬ b < a⟩ instance decidable_lt : @decidable_rel znum (<) | a b := by dsimp [(<)]; apply_instance instance decidable_le : @decidable_rel znum (≤) | a b := by dsimp [(≤)]; apply_instance end znum namespace pos_num /-- Auxiliary definition for `pos_num.divmod`. -/ def divmod_aux (d : pos_num) (q r : num) : num × num := match num.of_znum' (num.sub' r (num.pos d)) with | some r' := (num.bit1 q, r') | none := (num.bit0 q, r) end /-- `divmod x y = (y / x, y % x)`. -/ def divmod (d : pos_num) : pos_num → num × num | (bit0 n) := let (q, r₁) := divmod n in divmod_aux d q (num.bit0 r₁) | (bit1 n) := let (q, r₁) := divmod n in divmod_aux d q (num.bit1 r₁) | 1 := divmod_aux d 0 1 /-- Division of `pos_num`, -/ def div' (n d : pos_num) : num := (divmod d n).1 /-- Modulus of `pos_num`s. -/ def mod' (n d : pos_num) : num := (divmod d n).2 /- private def sqrt_aux1 (b : pos_num) (r n : num) : num × num := match num.of_znum' (n.sub' (r + num.pos b)) with | some n' := (r.div2 + num.pos b, n') | none := (r.div2, n) end private def sqrt_aux : pos_num → num → num → num | b@(bit0 b') r n := let (r', n') := sqrt_aux1 b r n in sqrt_aux b' r' n' | b@(bit1 b') r n := let (r', n') := sqrt_aux1 b r n in sqrt_aux b' r' n' | 1 r n := (sqrt_aux1 1 r n).1 -/ /- def sqrt_aux : ℕ → ℕ → ℕ → ℕ | b r n := if b0 : b = 0 then r else let b' := shiftr b 2 in have b' < b, from sqrt_aux_dec b0, match (n - (r + b : ℕ) : ℤ) with | (n' : ℕ) := sqrt_aux b' (div2 r + b) n' | _ := sqrt_aux b' (div2 r) n end /-- `sqrt n` is the square root of a natural number `n`. If `n` is not a perfect square, it returns the largest `k:ℕ` such that `k*k ≤ n`. -/ def sqrt (n : ℕ) : ℕ := match size n with | 0 := 0 | succ s := sqrt_aux (shiftl 1 (bit0 (div2 s))) 0 n end -/ end pos_num namespace num /-- Division of `num`s, where `x / 0 = 0`. -/ def div : num → num → num | 0 _ := 0 | _ 0 := 0 | (pos n) (pos d) := pos_num.div' n d /-- Modulus of `num`s. -/ def mod : num → num → num | 0 _ := 0 | n 0 := n | (pos n) (pos d) := pos_num.mod' n d instance : has_div num := ⟨num.div⟩ instance : has_mod num := ⟨num.mod⟩ /-- Auxiliary definition for `num.gcd`. -/ def gcd_aux : nat → num → num → num | 0 a b := b | (nat.succ n) 0 b := b | (nat.succ n) a b := gcd_aux n (b % a) a /-- Greatest Common Divisor (GCD) of two `num`s. -/ def gcd (a b : num) : num := if a ≤ b then gcd_aux (a.nat_size + b.nat_size) a b else gcd_aux (b.nat_size + a.nat_size) b a end num namespace znum /-- Division of `znum`, where `x / 0 = 0`. -/ def div : znum → znum → znum | 0 _ := 0 | _ 0 := 0 | (pos n) (pos d) := num.to_znum (pos_num.div' n d) | (pos n) (neg d) := num.to_znum_neg (pos_num.div' n d) | (neg n) (pos d) := neg (pos_num.pred' n / num.pos d).succ' | (neg n) (neg d) := pos (pos_num.pred' n / num.pos d).succ' /-- Modulus of `znum`s. -/ def mod : znum → znum → znum | 0 d := 0 | (pos n) d := num.to_znum (num.pos n % d.abs) | (neg n) d := d.abs.sub' (pos_num.pred' n % d.abs).succ instance : has_div znum := ⟨znum.div⟩ instance : has_mod znum := ⟨znum.mod⟩ /-- Greatest Common Divisor (GCD) of two `znum`s. -/ def gcd (a b : znum) : num := a.abs.gcd b.abs end znum section variables {α : Type*} [has_zero α] [has_one α] [has_add α] [has_neg α] /-- `cast_znum` casts a `znum` into any type which has `0`, `1`, `+` and `neg` -/ def cast_znum : znum → α | 0 := 0 | (znum.pos p) := p | (znum.neg p) := -p -- see Note [coercion into rings] @[priority 900] instance znum_coe : has_coe_t znum α := ⟨cast_znum⟩ instance : has_repr znum := ⟨λ n, repr (n : ℤ)⟩ end
3324981624928831fbc21045bcd0ede958ccdf0a
88fb7558b0636ec6b181f2a548ac11ad3919f8a5
/tests/lean/run/quote1.lean
655606efbb8a33bfde2a4d9158ea8718fe9bea8e
[ "Apache-2.0" ]
permissive
moritayasuaki/lean
9f666c323cb6fa1f31ac597d777914aed41e3b7a
ae96ebf6ee953088c235ff7ae0e8c95066ba8001
refs/heads/master
1,611,135,440,814
1,493,852,869,000
1,493,852,869,000
90,269,903
0
0
null
1,493,906,291,000
1,493,906,291,000
null
UTF-8
Lean
false
false
313
lean
open tactic list meta definition foo (a : pexpr) : pexpr := `(%%a + %%a + %%a + b) example (a b : nat) : a = a := by do a ← get_local `a, t1 ← mk_app ``has_add.add [a, a], t2 ← to_expr (foo (to_pexpr t1)), trace t2, r ← mk_app (`eq.refl) [a], exact r private def f := unit #check ``f
9d9dda621c48686d7705aad8f859dc53e0562ac9
ebb7367fa8ab324601b5abf705720fd4cc0e8598
/algebra/free_commutative_group.hlean
a4599682dcfae7513aa0988f844cb550fbf4a274
[ "Apache-2.0" ]
permissive
radams78/Spectral
3e34916d9bbd0939ee6a629e36744827ff27bfc2
c8145341046cfa2b4960ef3cc5a1117d12c43f63
refs/heads/master
1,610,421,583,830
1,481,232,014,000
1,481,232,014,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,446
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, Egbert Rijke Constructions with groups -/ import algebra.group_theory hit.set_quotient types.list types.sum .free_group open eq algebra is_trunc set_quotient relation sigma sigma.ops prod sum list trunc function equiv namespace group variables {G G' : Group} {g g' h h' k : G} {A B : AbGroup} variables (X : Set) {l l' : list (X ⊎ X)} /- Free Abelian Group of a set -/ namespace free_ab_group inductive fcg_rel : list (X ⊎ X) → list (X ⊎ X) → Type := | rrefl : Πl, fcg_rel l l | cancel1 : Πx, fcg_rel [inl x, inr x] [] | cancel2 : Πx, fcg_rel [inr x, inl x] [] | rflip : Πx y, fcg_rel [x, y] [y, x] | resp_append : Π{l₁ l₂ l₃ l₄}, fcg_rel l₁ l₂ → fcg_rel l₃ l₄ → fcg_rel (l₁ ++ l₃) (l₂ ++ l₄) | rtrans : Π{l₁ l₂ l₃}, fcg_rel l₁ l₂ → fcg_rel l₂ l₃ → fcg_rel l₁ l₃ open fcg_rel local abbreviation R [reducible] := fcg_rel attribute fcg_rel.rrefl [refl] attribute fcg_rel.rtrans [trans] definition fcg_carrier [reducible] : Type := set_quotient (λx y, ∥R X x y∥) local abbreviation FG := fcg_carrier definition is_reflexive_R : is_reflexive (λx y, ∥R X x y∥) := begin constructor, intro s, apply tr, unfold R end local attribute is_reflexive_R [instance] variable {X} theorem rel_respect_flip (r : R X l l') : R X (map sum.flip l) (map sum.flip l') := begin induction r with l x x x y l₁ l₂ l₃ l₄ r₁ r₂ IH₁ IH₂ l₁ l₂ l₃ r₁ r₂ IH₁ IH₂, { reflexivity}, { repeat esimp [map], exact cancel2 x}, { repeat esimp [map], exact cancel1 x}, { repeat esimp [map], apply rflip}, { rewrite [+map_append], exact resp_append IH₁ IH₂}, { exact rtrans IH₁ IH₂} end theorem rel_respect_reverse (r : R X l l') : R X (reverse l) (reverse l') := begin induction r with l x x x y l₁ l₂ l₃ l₄ r₁ r₂ IH₁ IH₂ l₁ l₂ l₃ r₁ r₂ IH₁ IH₂, { reflexivity}, { repeat esimp [map], exact cancel2 x}, { repeat esimp [map], exact cancel1 x}, { repeat esimp [map], apply rflip}, { rewrite [+reverse_append], exact resp_append IH₂ IH₁}, { exact rtrans IH₁ IH₂} end theorem rel_cons_concat (l s) : R X (s :: l) (concat s l) := begin induction l with t l IH, { reflexivity}, { rewrite [concat_cons], transitivity (t :: s :: l), { exact resp_append !rflip !rrefl}, { exact resp_append (rrefl [t]) IH}} end definition fcg_one [constructor] : FG X := class_of [] definition fcg_inv [unfold 3] : FG X → FG X := quotient_unary_map (reverse ∘ map sum.flip) (λl l', trunc_functor -1 (rel_respect_reverse ∘ rel_respect_flip)) definition fcg_mul [unfold 3 4] : FG X → FG X → FG X := quotient_binary_map append (λl l', trunc.elim (λr m m', trunc.elim (λs, tr (resp_append r s)))) section local notation 1 := fcg_one local postfix ⁻¹ := fcg_inv local infix * := fcg_mul theorem fcg_mul_assoc (g₁ g₂ g₃ : FG X) : g₁ * g₂ * g₃ = g₁ * (g₂ * g₃) := begin refine set_quotient.rec_prop _ g₁, refine set_quotient.rec_prop _ g₂, refine set_quotient.rec_prop _ g₃, clear g₁ g₂ g₃, intro g₁ g₂ g₃, exact ap class_of !append.assoc end theorem fcg_one_mul (g : FG X) : 1 * g = g := begin refine set_quotient.rec_prop _ g, clear g, intro g, exact ap class_of !append_nil_left end theorem fcg_mul_one (g : FG X) : g * 1 = g := begin refine set_quotient.rec_prop _ g, clear g, intro g, exact ap class_of !append_nil_right end theorem fcg_mul_left_inv (g : FG X) : g⁻¹ * g = 1 := begin refine set_quotient.rec_prop _ g, clear g, intro g, apply eq_of_rel, apply tr, induction g with s l IH, { reflexivity}, { rewrite [▸*, map_cons, reverse_cons, concat_append], refine rtrans _ IH, apply resp_append, reflexivity, change R X ([flip s, s] ++ l) ([] ++ l), apply resp_append, induction s, apply cancel2, apply cancel1, reflexivity} end theorem fcg_mul_comm (g h : FG X) : g * h = h * g := begin refine set_quotient.rec_prop _ g, clear g, intro g, refine set_quotient.rec_prop _ h, clear h, intro h, apply eq_of_rel, apply tr, revert h, induction g with s l IH: intro h, { rewrite [append_nil_left, append_nil_right]}, { rewrite [append_cons,-concat_append], transitivity concat s (l ++ h), apply rel_cons_concat, rewrite [-append_concat], apply IH} end end end free_ab_group open free_ab_group variables (X) definition group_free_ab_group [constructor] : ab_group (fcg_carrier X) := ab_group.mk fcg_mul _ fcg_mul_assoc fcg_one fcg_one_mul fcg_mul_one fcg_inv fcg_mul_left_inv fcg_mul_comm definition free_ab_group [constructor] : AbGroup := AbGroup.mk _ (group_free_ab_group X) /- The universal property of the free commutative group -/ variables {X A} definition free_ab_group_inclusion [constructor] (x : X) : free_ab_group X := class_of [inl x] theorem fgh_helper_respect_fcg_rel (f : X → A) (r : fcg_rel X l l') : Π(g : A), foldl (fgh_helper f) g l = foldl (fgh_helper f) g l' := begin induction r with l x x x y l₁ l₂ l₃ l₄ r₁ r₂ IH₁ IH₂ l₁ l₂ l₃ r₁ r₂ IH₁ IH₂: intro g, { reflexivity}, { unfold [foldl], apply mul_inv_cancel_right}, { unfold [foldl], apply inv_mul_cancel_right}, { unfold [foldl, fgh_helper], apply mul.right_comm}, { rewrite [+foldl_append, IH₁, IH₂]}, { exact !IH₁ ⬝ !IH₂} end definition free_ab_group_elim [constructor] (f : X → A) : free_ab_group X →g A := begin fapply homomorphism.mk, { intro g, refine set_quotient.elim _ _ g, { intro l, exact foldl (fgh_helper f) 1 l}, { intro l l' r, esimp at *, refine trunc.rec _ r, clear r, intro r, exact fgh_helper_respect_fcg_rel f r 1}}, { refine set_quotient.rec_prop _, intro l, refine set_quotient.rec_prop _, intro l', esimp, refine !foldl_append ⬝ _, esimp, apply fgh_helper_mul} end definition fn_of_free_ab_group_elim [unfold_full] (φ : free_ab_group X →g A) : X → A := φ ∘ free_ab_group_inclusion definition free_ab_group_elim_unique [constructor] (f : X → A) (k : free_ab_group X →g A) (H : k ∘ free_ab_group_inclusion ~ f) : k ~ free_ab_group_elim f := begin refine set_quotient.rec_prop _, intro l, esimp, induction l with s l IH, { esimp [foldl], exact to_respect_one k}, { rewrite [foldl_cons, fgh_helper_mul], refine to_respect_mul k (class_of [s]) (class_of l) ⬝ _, rewrite [IH], apply ap (λx, x * _), induction s: rewrite [▸*, one_mul, -H a], apply to_respect_inv } end variables (X A) definition free_ab_group_elim_equiv_fn [constructor] : (free_ab_group X →g A) ≃ (X → A) := begin fapply equiv.MK, { exact fn_of_free_ab_group_elim}, { exact free_ab_group_elim}, { intro f, apply eq_of_homotopy, intro x, esimp, unfold [foldl], apply one_mul}, { intro k, symmetry, apply homomorphism_eq, apply free_ab_group_elim_unique, reflexivity } end end group
1fcbf4b83e8edb00aeb993ea33f486c02993c93d
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/normed_space/units.lean
2115426c1fa3c9cb2222f7b97577ed6c9de8f921
[ "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
12,010
lean
/- Copyright (c) 2020 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth -/ import analysis.specific_limits.normed /-! # The group of units of a complete normed ring This file contains the basic theory for the group of units (invertible elements) of a complete normed ring (Banach algebras being a notable special case). ## Main results The constructions `one_sub`, `add` and `unit_of_nearby` state, in varying forms, that perturbations of a unit are units. The latter two are not stated in their optimal form; more precise versions would use the spectral radius. The first main result is `is_open`: the group of units of a complete normed ring is an open subset of the ring. The function `inverse` (defined in `algebra.ring`), for a ring `R`, sends `a : R` to `a⁻¹` if `a` is a unit and 0 if not. The other major results of this file (notably `inverse_add`, `inverse_add_norm` and `inverse_add_norm_diff_nth_order`) cover the asymptotic properties of `inverse (x + t)` as `t → 0`. -/ noncomputable theory open_locale topological_space variables {R : Type*} [normed_ring R] [complete_space R] namespace units /-- In a complete normed ring, a perturbation of `1` by an element `t` of distance less than `1` from `1` is a unit. Here we construct its `units` structure. -/ @[simps coe] def one_sub (t : R) (h : ∥t∥ < 1) : Rˣ := { val := 1 - t, inv := ∑' n : ℕ, t ^ n, val_inv := mul_neg_geom_series t h, inv_val := geom_series_mul_neg t h } /-- In a complete normed ring, a perturbation of a unit `x` by an element `t` of distance less than `∥x⁻¹∥⁻¹` from `x` is a unit. Here we construct its `units` structure. -/ @[simps coe] def add (x : Rˣ) (t : R) (h : ∥t∥ < ∥(↑x⁻¹ : R)∥⁻¹) : Rˣ := units.copy -- to make `coe_add` true definitionally, for convenience (x * (units.one_sub (-(↑x⁻¹ * t)) begin nontriviality R using [zero_lt_one], have hpos : 0 < ∥(↑x⁻¹ : R)∥ := units.norm_pos x⁻¹, calc ∥-(↑x⁻¹ * t)∥ = ∥↑x⁻¹ * t∥ : by { rw norm_neg } ... ≤ ∥(↑x⁻¹ : R)∥ * ∥t∥ : norm_mul_le ↑x⁻¹ _ ... < ∥(↑x⁻¹ : R)∥ * ∥(↑x⁻¹ : R)∥⁻¹ : by nlinarith only [h, hpos] ... = 1 : mul_inv_cancel (ne_of_gt hpos) end)) (x + t) (by simp [mul_add]) _ rfl /-- In a complete normed ring, an element `y` of distance less than `∥x⁻¹∥⁻¹` from `x` is a unit. Here we construct its `units` structure. -/ @[simps coe] def unit_of_nearby (x : Rˣ) (y : R) (h : ∥y - x∥ < ∥(↑x⁻¹ : R)∥⁻¹) : Rˣ := units.copy (x.add (y - x : R) h) y (by simp) _ rfl /-- The group of units of a complete normed ring is an open subset of the ring. -/ protected lemma is_open : is_open {x : R | is_unit x} := begin nontriviality R, apply metric.is_open_iff.mpr, rintros x' ⟨x, rfl⟩, refine ⟨∥(↑x⁻¹ : R)∥⁻¹, _root_.inv_pos.mpr (units.norm_pos x⁻¹), _⟩, intros y hy, rw [metric.mem_ball, dist_eq_norm] at hy, exact (x.unit_of_nearby y hy).is_unit end protected lemma nhds (x : Rˣ) : {x : R | is_unit x} ∈ 𝓝 (x : R) := is_open.mem_nhds units.is_open x.is_unit end units namespace normed_ring open_locale classical big_operators open asymptotics filter metric finset ring lemma inverse_one_sub (t : R) (h : ∥t∥ < 1) : inverse (1 - t) = ↑(units.one_sub t h)⁻¹ := by rw [← inverse_unit (units.one_sub t h), units.coe_one_sub] /-- The formula `inverse (x + t) = inverse (1 + x⁻¹ * t) * x⁻¹` holds for `t` sufficiently small. -/ lemma inverse_add (x : Rˣ) : ∀ᶠ t in (𝓝 0), inverse ((x : R) + t) = inverse (1 + ↑x⁻¹ * t) * ↑x⁻¹ := begin nontriviality R, rw [eventually_iff, metric.mem_nhds_iff], have hinv : 0 < ∥(↑x⁻¹ : R)∥⁻¹, by cancel_denoms, use [∥(↑x⁻¹ : R)∥⁻¹, hinv], intros t ht, simp only [mem_ball, dist_zero_right] at ht, have ht' : ∥-↑x⁻¹ * t∥ < 1, { refine lt_of_le_of_lt (norm_mul_le _ _) _, rw norm_neg, refine lt_of_lt_of_le (mul_lt_mul_of_pos_left ht x⁻¹.norm_pos) _, cancel_denoms }, have hright := inverse_one_sub (-↑x⁻¹ * t) ht', have hleft := inverse_unit (x.add t ht), simp only [neg_mul, sub_neg_eq_add] at hright, simp only [units.coe_add] at hleft, simp [hleft, hright, units.add] end lemma inverse_one_sub_nth_order (n : ℕ) : ∀ᶠ t in (𝓝 0), inverse ((1:R) - t) = (∑ i in range n, t ^ i) + (t ^ n) * inverse (1 - t) := begin simp only [eventually_iff, metric.mem_nhds_iff], use [1, by norm_num], intros t ht, simp only [mem_ball, dist_zero_right] at ht, simp only [inverse_one_sub t ht, set.mem_set_of_eq], have h : 1 = ((range n).sum (λ i, t ^ i)) * (units.one_sub t ht) + t ^ n, { simp only [units.coe_one_sub], rw [← geom_sum, geom_sum_mul_neg], simp }, rw [← one_mul ↑(units.one_sub t ht)⁻¹, h, add_mul], congr, { rw [mul_assoc, (units.one_sub t ht).mul_inv], simp }, { simp only [units.coe_one_sub], rw [← add_mul, ← geom_sum, geom_sum_mul_neg], simp } end /-- The formula `inverse (x + t) = (∑ i in range n, (- x⁻¹ * t) ^ i) * x⁻¹ + (- x⁻¹ * t) ^ n * inverse (x + t)` holds for `t` sufficiently small. -/ lemma inverse_add_nth_order (x : Rˣ) (n : ℕ) : ∀ᶠ t in (𝓝 0), inverse ((x : R) + t) = (∑ i in range n, (- ↑x⁻¹ * t) ^ i) * ↑x⁻¹ + (- ↑x⁻¹ * t) ^ n * inverse (x + t) := begin refine (inverse_add x).mp _, have hzero : tendsto (λ (t : R), - ↑x⁻¹ * t) (𝓝 0) (𝓝 0), { convert ((mul_left_continuous (- (↑x⁻¹ : R))).tendsto 0).comp tendsto_id, simp }, refine (hzero.eventually (inverse_one_sub_nth_order n)).mp (eventually_of_forall _), simp only [neg_mul, sub_neg_eq_add], intros t h1 h2, have h := congr_arg (λ (a : R), a * ↑x⁻¹) h1, dsimp at h, convert h, rw [add_mul, mul_assoc], simp [h2.symm] end lemma inverse_one_sub_norm : is_O (λ t, inverse ((1:R) - t)) (λ t, (1:ℝ)) (𝓝 (0:R)) := begin simp only [is_O, is_O_with, eventually_iff, metric.mem_nhds_iff], refine ⟨∥(1:R)∥ + 1, (2:ℝ)⁻¹, by norm_num, _⟩, intros t ht, simp only [ball, dist_zero_right, set.mem_set_of_eq] at ht, have ht' : ∥t∥ < 1, { have : (2:ℝ)⁻¹ < 1 := by cancel_denoms, linarith }, simp only [inverse_one_sub t ht', norm_one, mul_one, set.mem_set_of_eq], change ∥∑' n : ℕ, t ^ n∥ ≤ _, have := normed_ring.tsum_geometric_of_norm_lt_1 t ht', have : (1 - ∥t∥)⁻¹ ≤ 2, { rw ← inv_inv (2:ℝ), refine inv_le_inv_of_le (by norm_num) _, have : (2:ℝ)⁻¹ + (2:ℝ)⁻¹ = 1 := by ring, linarith }, linarith end /-- The function `λ t, inverse (x + t)` is O(1) as `t → 0`. -/ lemma inverse_add_norm (x : Rˣ) : is_O (λ t, inverse (↑x + t)) (λ t, (1:ℝ)) (𝓝 (0:R)) := begin simp only [is_O_iff, norm_one, mul_one], cases is_O_iff.mp (@inverse_one_sub_norm R _ _) with C hC, use C * ∥((x⁻¹:Rˣ):R)∥, have hzero : tendsto (λ t, - (↑x⁻¹ : R) * t) (𝓝 0) (𝓝 0), { convert ((mul_left_continuous (-↑x⁻¹ : R)).tendsto 0).comp tendsto_id, simp }, refine (inverse_add x).mp ((hzero.eventually hC).mp (eventually_of_forall _)), intros t bound iden, rw iden, simp at bound, have hmul := norm_mul_le (inverse (1 + ↑x⁻¹ * t)) ↑x⁻¹, nlinarith [norm_nonneg (↑x⁻¹ : R)] end /-- The function `λ t, inverse (x + t) - (∑ i in range n, (- x⁻¹ * t) ^ i) * x⁻¹` is `O(t ^ n)` as `t → 0`. -/ lemma inverse_add_norm_diff_nth_order (x : Rˣ) (n : ℕ) : is_O (λ (t : R), inverse (↑x + t) - (∑ i in range n, (- ↑x⁻¹ * t) ^ i) * ↑x⁻¹) (λ t, ∥t∥ ^ n) (𝓝 (0:R)) := begin by_cases h : n = 0, { simpa [h] using inverse_add_norm x }, have hn : 0 < n := nat.pos_of_ne_zero h, simp [is_O_iff], cases (is_O_iff.mp (inverse_add_norm x)) with C hC, use C * ∥(1:ℝ)∥ * ∥(↑x⁻¹ : R)∥ ^ n, have h : eventually_eq (𝓝 (0:R)) (λ t, inverse (↑x + t) - (∑ i in range n, (- ↑x⁻¹ * t) ^ i) * ↑x⁻¹) (λ t, ((- ↑x⁻¹ * t) ^ n) * inverse (x + t)), { refine (inverse_add_nth_order x n).mp (eventually_of_forall _), intros t ht, convert congr_arg (λ a, a - (range n).sum (pow (-↑x⁻¹ * t)) * ↑x⁻¹) ht, simp }, refine h.mp (hC.mp (eventually_of_forall _)), intros t _ hLHS, simp only [neg_mul] at hLHS, rw hLHS, refine le_trans (norm_mul_le _ _ ) _, have h' : ∥(-(↑x⁻¹ * t)) ^ n∥ ≤ ∥(↑x⁻¹ : R)∥ ^ n * ∥t∥ ^ n, { calc ∥(-(↑x⁻¹ * t)) ^ n∥ ≤ ∥(-(↑x⁻¹ * t))∥ ^ n : norm_pow_le' _ hn ... = ∥↑x⁻¹ * t∥ ^ n : by rw norm_neg ... ≤ (∥(↑x⁻¹ : R)∥ * ∥t∥) ^ n : _ ... = ∥(↑x⁻¹ : R)∥ ^ n * ∥t∥ ^ n : mul_pow _ _ n, exact pow_le_pow_of_le_left (norm_nonneg _) (norm_mul_le ↑x⁻¹ t) n }, have h'' : 0 ≤ ∥(↑x⁻¹ : R)∥ ^ n * ∥t∥ ^ n, { refine mul_nonneg _ _; exact pow_nonneg (norm_nonneg _) n }, nlinarith [norm_nonneg (inverse (↑x + t))], end /-- The function `λ t, inverse (x + t) - x⁻¹` is `O(t)` as `t → 0`. -/ lemma inverse_add_norm_diff_first_order (x : Rˣ) : is_O (λ t, inverse (↑x + t) - ↑x⁻¹) (λ t, ∥t∥) (𝓝 (0:R)) := by simpa using inverse_add_norm_diff_nth_order x 1 /-- The function `λ t, inverse (x + t) - x⁻¹ + x⁻¹ * t * x⁻¹` is `O(t ^ 2)` as `t → 0`. -/ lemma inverse_add_norm_diff_second_order (x : Rˣ) : is_O (λ t, inverse (↑x + t) - ↑x⁻¹ + ↑x⁻¹ * t * ↑x⁻¹) (λ t, ∥t∥ ^ 2) (𝓝 (0:R)) := begin convert inverse_add_norm_diff_nth_order x 2, ext t, simp only [range_succ, range_one, sum_insert, mem_singleton, sum_singleton, not_false_iff, one_ne_zero, pow_zero, add_mul, pow_one, one_mul, neg_mul, sub_add_eq_sub_sub_swap, sub_neg_eq_add], end /-- The function `inverse` is continuous at each unit of `R`. -/ lemma inverse_continuous_at (x : Rˣ) : continuous_at inverse (x : R) := begin have h_is_o : is_o (λ (t : R), inverse (↑x + t) - ↑x⁻¹) (λ _, 1 : R → ℝ) (𝓝 0) := (inverse_add_norm_diff_first_order x).trans_is_o (is_o.norm_left $ is_o_id_const one_ne_zero), have h_lim : tendsto (λ (y:R), y - x) (𝓝 x) (𝓝 0), { refine tendsto_zero_iff_norm_tendsto_zero.mpr _, exact tendsto_iff_norm_tendsto_zero.mp tendsto_id }, rw [continuous_at, tendsto_iff_norm_tendsto_zero, inverse_unit], simpa [(∘)] using h_is_o.norm_left.tendsto_div_nhds_zero.comp h_lim end end normed_ring namespace units open mul_opposite filter normed_ring /-- In a normed ring, the coercion from `Rˣ` (equipped with the induced topology from the embedding in `R × R`) to `R` is an open map. -/ lemma is_open_map_coe : is_open_map (coe : Rˣ → R) := begin rw is_open_map_iff_nhds_le, intros x s, rw [mem_map, mem_nhds_induced], rintros ⟨t, ht, hts⟩, obtain ⟨u, hu, v, hv, huvt⟩ : ∃ (u : set R), u ∈ 𝓝 ↑x ∧ ∃ (v : set Rᵐᵒᵖ), v ∈ 𝓝 (op ↑x⁻¹) ∧ u ×ˢ v ⊆ t, { simpa [embed_product, mem_nhds_prod_iff] using ht }, have : u ∩ (op ∘ ring.inverse) ⁻¹' v ∩ (set.range (coe : Rˣ → R)) ∈ 𝓝 ↑x, { refine inter_mem (inter_mem hu _) (units.nhds x), refine (continuous_op.continuous_at.comp (inverse_continuous_at x)).preimage_mem_nhds _, simpa using hv }, refine mem_of_superset this _, rintros _ ⟨⟨huy, hvy⟩, ⟨y, rfl⟩⟩, have : embed_product R y ∈ u ×ˢ v := ⟨huy, by simpa using hvy⟩, simpa using hts (huvt this) end /-- In a normed ring, the coercion from `Rˣ` (equipped with the induced topology from the embedding in `R × R`) to `R` is an open embedding. -/ lemma open_embedding_coe : open_embedding (coe : Rˣ → R) := open_embedding_of_continuous_injective_open continuous_coe ext is_open_map_coe end units
3fb8dfdddd4f40288b3ec4cc51df8ca351fe2473
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/set_theory/surreal/dyadic.lean
220a7b15e8a91710337e3fbe514bc000b6d6c61e
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,467
lean
/- Copyright (c) 2021 Apurva Nakade. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Apurva Nakade -/ import set_theory.surreal.basic import ring_theory.localization /-! # Dyadic numbers Dyadic numbers are obtained by localizing ℤ away from 2. They are the initial object in the category of rings with no 2-torsion. ## Dyadic surreal numbers We construct dyadic surreal numbers using the canonical map from ℤ[2 ^ {-1}] to surreals. As we currently do not have a ring structure on `surreal` we construct this map explicitly. Once we have the ring structure, this map can be constructed directly by sending `2 ^ {-1}` to `half`. ## Embeddings The above construction gives us an abelian group embedding of ℤ into `surreal`. The goal is to extend this to an embedding of dyadic rationals into `surreal` and use Cauchy sequences of dyadic rational numbers to construct an ordered field embedding of ℝ into `surreal`. -/ universes u local infix ` ≈ ` := pgame.equiv namespace pgame /-- For a natural number `n`, the pre-game `pow_half (n + 1)` is recursively defined as `{ 0 | pow_half n }`. These are the explicit expressions of powers of `half`. By definition, we have `pow_half 0 = 0` and `pow_half 1 = half` and we prove later on that `pow_half (n + 1) + pow_half (n + 1) ≈ pow_half n`.-/ def pow_half : ℕ → pgame | 0 := mk punit pempty 0 pempty.elim | (n + 1) := mk punit punit 0 (λ _, pow_half n) @[simp] lemma pow_half_left_moves {n} : (pow_half n).left_moves = punit := by cases n; refl @[simp] lemma pow_half_right_moves {n} : (pow_half (n + 1)).right_moves = punit := by cases n; refl @[simp] lemma pow_half_move_left {n i} : (pow_half n).move_left i = 0 := by cases n; cases i; refl @[simp] lemma pow_half_move_right {n i} : (pow_half (n + 1)).move_right i = pow_half n := by cases n; cases i; refl lemma pow_half_move_left' (n) : (pow_half n).move_left (equiv.cast (pow_half_left_moves.symm) punit.star) = 0 := by simp only [eq_self_iff_true, pow_half_move_left] lemma pow_half_move_right' (n) : (pow_half (n + 1)).move_right (equiv.cast (pow_half_right_moves.symm) punit.star) = pow_half n := by simp only [pow_half_move_right, eq_self_iff_true] /-- For all natural numbers `n`, the pre-games `pow_half n` are numeric. -/ theorem numeric_pow_half {n} : (pow_half n).numeric := begin induction n with n hn, { exact numeric_one }, { split, { rintro ⟨ ⟩ ⟨ ⟩, dsimp only [pi.zero_apply], rw ← pow_half_move_left' n, apply hn.move_left_lt }, { exact ⟨λ _, numeric_zero, λ _, hn⟩ } } end theorem pow_half_succ_lt_pow_half {n : ℕ} : pow_half (n + 1) < pow_half n := (@numeric_pow_half (n + 1)).lt_move_right punit.star theorem pow_half_succ_le_pow_half {n : ℕ} : pow_half (n + 1) ≤ pow_half n := le_of_lt numeric_pow_half numeric_pow_half pow_half_succ_lt_pow_half theorem zero_lt_pow_half {n : ℕ} : 0 < pow_half n := by cases n; rw lt_def_le; use ⟨punit.star, pgame.le_refl 0⟩ theorem zero_le_pow_half {n : ℕ} : 0 ≤ pow_half n := le_of_lt numeric_zero numeric_pow_half zero_lt_pow_half theorem add_pow_half_succ_self_eq_pow_half {n} : pow_half (n + 1) + pow_half (n + 1) ≈ pow_half n := begin induction n with n hn, { exact half_add_half_equiv_one }, { split; rw le_def_lt; split, { rintro (⟨⟨ ⟩⟩ | ⟨⟨ ⟩⟩), { calc 0 + pow_half (n.succ + 1) ≈ pow_half (n.succ + 1) : zero_add_equiv _ ... < pow_half n.succ : pow_half_succ_lt_pow_half }, { calc pow_half (n.succ + 1) + 0 ≈ pow_half (n.succ + 1) : add_zero_equiv _ ... < pow_half n.succ : pow_half_succ_lt_pow_half } }, { rintro ⟨ ⟩, rw lt_def_le, right, use sum.inl punit.star, calc pow_half (n.succ) + pow_half (n.succ + 1) ≤ pow_half (n.succ) + pow_half (n.succ) : add_le_add_left pow_half_succ_le_pow_half ... ≈ pow_half n : hn }, { rintro ⟨ ⟩, calc 0 ≈ 0 + 0 : (add_zero_equiv _).symm ... ≤ pow_half (n.succ + 1) + 0 : add_le_add_right zero_le_pow_half ... < pow_half (n.succ + 1) + pow_half (n.succ + 1) : add_lt_add_left zero_lt_pow_half }, { rintro (⟨⟨ ⟩⟩ | ⟨⟨ ⟩⟩), { calc pow_half n.succ ≈ pow_half n.succ + 0 : (add_zero_equiv _).symm ... < pow_half (n.succ) + pow_half (n.succ + 1) : add_lt_add_left zero_lt_pow_half }, { calc pow_half n.succ ≈ 0 + pow_half n.succ : (zero_add_equiv _).symm ... < pow_half (n.succ + 1) + pow_half (n.succ) : add_lt_add_right zero_lt_pow_half }}} end end pgame namespace surreal open pgame /-- The surreal number `half`. -/ def half : surreal := ⟦⟨pgame.half, pgame.numeric_half⟩⟧ /-- Powers of the surreal number `half`. -/ def pow_half (n : ℕ) : surreal := ⟦⟨pgame.pow_half n, pgame.numeric_pow_half⟩⟧ @[simp] lemma pow_half_zero : pow_half 0 = 1 := rfl @[simp] lemma pow_half_one : pow_half 1 = half := rfl @[simp] theorem add_half_self_eq_one : half + half = 1 := quotient.sound pgame.half_add_half_equiv_one lemma double_pow_half_succ_eq_pow_half (n : ℕ) : 2 • pow_half n.succ = pow_half n := begin rw two_nsmul, apply quotient.sound, exact pgame.add_pow_half_succ_self_eq_pow_half, end lemma nsmul_pow_two_pow_half (n : ℕ) : 2 ^ n • pow_half n = 1 := begin induction n with n hn, { simp only [nsmul_one, pow_half_zero, nat.cast_one, pow_zero] }, { rw [← hn, ← double_pow_half_succ_eq_pow_half n, smul_smul (2^n) 2 (pow_half n.succ), mul_comm, pow_succ] } end lemma nsmul_pow_two_pow_half' (n k : ℕ) : 2 ^ n • pow_half (n + k) = pow_half k := begin induction k with k hk, { simp only [add_zero, surreal.nsmul_pow_two_pow_half, nat.nat_zero_eq_zero, eq_self_iff_true, surreal.pow_half_zero] }, { rw [← double_pow_half_succ_eq_pow_half (n + k), ← double_pow_half_succ_eq_pow_half k, smul_algebra_smul_comm] at hk, rwa ← (gsmul_eq_gsmul_iff' two_ne_zero) } end lemma nsmul_int_pow_two_pow_half (m : ℤ) (n k : ℕ) : (m * 2 ^ n) • pow_half (n + k) = m • pow_half k := begin rw mul_gsmul, congr, norm_cast, exact nsmul_pow_two_pow_half' n k, end lemma dyadic_aux {m₁ m₂ : ℤ} {y₁ y₂ : ℕ} (h₂ : m₁ * (2 ^ y₁) = m₂ * (2 ^ y₂)) : m₁ • pow_half y₂ = m₂ • pow_half y₁ := begin revert m₁ m₂, wlog h : y₁ ≤ y₂, intros m₁ m₂ h₂, obtain ⟨c, rfl⟩ := le_iff_exists_add.mp h, rw [add_comm, pow_add, ← mul_assoc, mul_eq_mul_right_iff] at h₂, cases h₂, { rw [h₂, add_comm, nsmul_int_pow_two_pow_half m₂ c y₁] }, { have := nat.one_le_pow y₁ 2 nat.succ_pos', linarith }, end /-- The map `dyadic_map` sends ⟦⟨m, 2^n⟩⟧ to m • half ^ n. -/ def dyadic_map (x : localization (submonoid.powers (2 : ℤ))) : surreal := quotient.lift_on' x (λ x : _ × _, x.1 • pow_half (submonoid.log x.2)) $ begin rintros ⟨m₁, n₁⟩ ⟨m₂, n₂⟩ h₁, obtain ⟨⟨n₃, y₃, hn₃⟩, h₂⟩ := localization.r_iff_exists.mp h₁, simp only [subtype.coe_mk, mul_eq_mul_right_iff] at h₂, cases h₂, { simp only, obtain ⟨a₁, ha₁⟩ := n₁.prop, obtain ⟨a₂, ha₂⟩ := n₂.prop, have hn₁ : n₁ = submonoid.pow 2 a₁ := subtype.ext ha₁.symm, have hn₂ : n₂ = submonoid.pow 2 a₂ := subtype.ext ha₂.symm, have h₂ : 1 < (2 : ℤ).nat_abs, from dec_trivial, rw [hn₁, hn₂, submonoid.log_pow_int_eq_self h₂, submonoid.log_pow_int_eq_self h₂], apply dyadic_aux, rwa [ha₁, ha₂] }, { have := nat.one_le_pow y₃ 2 nat.succ_pos', linarith } end /-- We define dyadic surreals as the range of the map `dyadic_map`. -/ def dyadic : set surreal := set.range dyadic_map -- We conclude with some ideas for further work on surreals; these would make fun projects. -- TODO show that the map from dyadic rationals to surreals is a group homomorphism, and injective -- TODO map the reals into the surreals, using dyadic Dedekind cuts -- TODO show this is a group homomorphism, and injective -- TODO show the maps from the dyadic rationals and from the reals -- into the surreals are multiplicative end surreal
73a7348a3d74ab90c9d26791cc891a0b142b3ac2
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/leak3.lean
e67141864c9ed1b8644787a72f78d66f7f9991e0
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
14
lean
print true = a
b5fe750b5719fbfb7e20bcdd12b8d9483eec8751
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/logic/unnamed_2051.lean
b3d0c3ad9baf8781517b783c6030867f479d970c
[]
no_license
jamescheuk91/mathematics_in_lean
09f1f87d2b0dce53464ff0cbe592c568ff59cf5e
4452499264e2975bca2f42565c0925506ba5dda3
refs/heads/master
1,679,716,410,967
1,613,957,947,000
1,613,957,947,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
165
lean
import data.real.basic variables (x y : ℝ) -- BEGIN example (h : x^2 = 1) : x = 1 ∨ x = -1 := sorry example (h : x^2 = y^2) : x = y ∨ x = -y := sorry -- END
d2b3095cc5faaf370436cb27000d5ada6aacc270
f5f7e6fae601a5fe3cac7cc3ed353ed781d62419
/src/data/subtype.lean
3181ec9737b3714d85f4012e70226f14be00be6b
[ "Apache-2.0" ]
permissive
EdAyers/mathlib
9ecfb2f14bd6caad748b64c9c131befbff0fb4e0
ca5d4c1f16f9c451cf7170b10105d0051db79e1b
refs/heads/master
1,626,189,395,845
1,555,284,396,000
1,555,284,396,000
144,004,030
0
0
Apache-2.0
1,533,727,664,000
1,533,727,663,000
null
UTF-8
Lean
false
false
3,102
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl -/ -- Lean complains if this section is turned into a namespace section subtype variables {α : Sort*} {p : α → Prop} @[simp] theorem subtype.forall {q : {a // p a} → Prop} : (∀ x, q x) ↔ (∀ a b, q ⟨a, b⟩) := ⟨assume h a b, h ⟨a, b⟩, assume h ⟨a, b⟩, h a b⟩ @[simp] theorem subtype.exists {q : {a // p a} → Prop} : (∃ x, q x) ↔ (∃ a b, q ⟨a, b⟩) := ⟨assume ⟨⟨a, b⟩, h⟩, ⟨a, b, h⟩, assume ⟨a, b, h⟩, ⟨⟨a, b⟩, h⟩⟩ end subtype namespace subtype variables {α : Sort*} {β : Sort*} {γ : Sort*} {p : α → Prop} protected lemma eq' : ∀ {a1 a2 : {x // p x}}, a1.val = a2.val → a1 = a2 | ⟨x, h1⟩ ⟨.(x), h2⟩ rfl := rfl lemma ext {a1 a2 : {x // p x}} : a1 = a2 ↔ a1.val = a2.val := ⟨congr_arg _, subtype.eq'⟩ lemma coe_ext {a1 a2 : {x // p x}} : a1 = a2 ↔ (a1 : α) = a2 := ext theorem val_injective : function.injective (@val _ p) := λ a b, subtype.eq' /-- Restriction of a function to a function on subtypes. -/ def map {p : α → Prop} {q : β → Prop} (f : α → β) (h : ∀a, p a → q (f a)) : subtype p → subtype q := λ x, ⟨f x.1, h x.1 x.2⟩ theorem map_comp {p : α → Prop} {q : β → Prop} {r : γ → Prop} {x : subtype p} (f : α → β) (h : ∀a, p a → q (f a)) (g : β → γ) (l : ∀a, q a → r (g a)) : map g l (map f h x) = map (g ∘ f) (assume a ha, l (f a) $ h a ha) x := rfl theorem map_id {p : α → Prop} {h : ∀a, p a → p (id a)} : map (@id α) h = id := funext $ assume ⟨v, h⟩, rfl instance [has_equiv α] (p : α → Prop) : has_equiv (subtype p) := ⟨λ s t, s.val ≈ t.val⟩ theorem equiv_iff [has_equiv α] {p : α → Prop} {s t : subtype p} : s ≈ t ↔ s.val ≈ t.val := iff.rfl variables [setoid α] protected theorem refl (s : subtype p) : s ≈ s := setoid.refl s.val protected theorem symm {s t : subtype p} (h : s ≈ t) : t ≈ s := setoid.symm h protected theorem trans {s t u : subtype p} (h₁ : s ≈ t) (h₂ : t ≈ u) : s ≈ u := setoid.trans h₁ h₂ theorem equivalence (p : α → Prop) : equivalence (@has_equiv.equiv (subtype p) _) := mk_equivalence _ subtype.refl (@subtype.symm _ p _) (@subtype.trans _ p _) instance (p : α → Prop) : setoid (subtype p) := setoid.mk (≈) (equivalence p) end subtype namespace subtype variables {α : Type*} {β : Type*} {γ : Type*} {p : α → Prop} @[simp] theorem coe_eta {α : Type*} {p : α → Prop} (a : {a // p a}) (h : p a) : mk ↑a h = a := eta _ _ @[simp] theorem coe_mk {α : Type*} {p : α → Prop} (a h) : (@mk α p a h : α) = a := rfl @[simp] theorem mk_eq_mk {α : Type*} {p : α → Prop} {a h a' h'} : @mk α p a h = @mk α p a' h' ↔ a = a' := ⟨λ H, by injection H, λ H, by congr; assumption⟩ @[simp] lemma val_prop {S : set α} (a : {a // a ∈ S}) : a.val ∈ S := a.property @[simp] lemma val_prop' {S : set α} (a : {a // a ∈ S}) : ↑a ∈ S := a.property end subtype
83d8149df435222ce56acacb6b284502f028171e
98beff2e97d91a54bdcee52f922c4e1866a6c9b9
/src/category/element.lean
8555aa8c3e30dca087258a52817055b016b6cba3
[]
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
1,389
lean
import category_theory.limits.shapes.binary_products import category_theory.limits.shapes.terminal import category_theory.limits.limits import category_theory.limits.types namespace category_theory open limits noncomputable theory universes v u variables {C : Type u} [category.{v} C] variable {Q : C} section prods variables [has_binary_products C] {X Y : C} def pair (x : Q ⟶ X) (y : Q ⟶ Y) : Q ⟶ X ⨯ Y := prod.lift x y def fst (xy : Q ⟶ X ⨯ Y) : Q ⟶ X := xy ≫ limits.prod.fst def snd (xy : Q ⟶ X ⨯ Y) : Q ⟶ Y := xy ≫ limits.prod.snd def prod.equiv (Q X Y : C) : (Q ⟶ X ⨯ Y) ≃ (Q ⟶ X) × (Q ⟶ Y) := { to_fun := λ f, (fst f, snd f), inv_fun := λ gh, pair gh.1 gh.2, left_inv := λ f, prod.hom_ext (by simp [pair, fst]) (by simp [pair, snd]), right_inv := λ gh, prod.ext (by simp [pair, fst]) (by simp [pair, snd]) } end prods -- section type -- local attribute [instance] has_terminal.has_limits_of_shape -- instance : has_terminal (Type u) := -- { has_limits_of_shape := infer_instance } -- def element_iso_type {X : Type u} : (terminal.{u} (Type u) ⟶ X) ≃ X := -- { to_fun := λ f, f ⟨λ k, k.elim, by rintro ⟨⟩⟩, -- inv_fun := λ x _, x, -- left_inv := λ f, -- begin -- ext1 ⟨⟩, -- dsimp, -- congr' 2, -- ext1 ⟨⟩, -- end, -- right_inv := λ x, rfl } -- end type end category_theory
eda4da582aad3cdf46750f9a992868175cb0e2d4
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/equiv/list.lean
1f3b94714553e8f50d60a6df34fc2ed672a6e4d3
[ "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
13,094
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.equiv.denumerable import data.finset.sort /-! # Equivalences involving `list`-like types This file defines some additional constructive equivalences using `encodable` and the pairing function on `ℕ`. -/ open nat list namespace encodable variables {α : Type*} section list variable [encodable α] /-- Explicit encoding function for `list α` -/ def encode_list : list α → ℕ | [] := 0 | (a::l) := succ (mkpair (encode a) (encode_list l)) /-- Explicit decoding function for `list α` -/ def decode_list : ℕ → option (list α) | 0 := some [] | (succ v) := match unpair v, unpair_right_le v with | (v₁, v₂), h := have v₂ < succ v, from lt_succ_of_le h, (::) <$> decode α v₁ <*> decode_list v₂ end /-- If `α` is encodable, then so is `list α`. This uses the `mkpair` and `unpair` functions from `data.nat.pairing`. -/ instance list : encodable (list α) := ⟨encode_list, decode_list, λ l, by induction l with a l IH; simp [encode_list, decode_list, unpair_mkpair, encodek, *]⟩ @[simp] theorem encode_list_nil : encode (@nil α) = 0 := rfl @[simp] theorem encode_list_cons (a : α) (l : list α) : encode (a :: l) = succ (mkpair (encode a) (encode l)) := rfl @[simp] theorem decode_list_zero : decode (list α) 0 = some [] := show decode_list 0 = some [], by rw decode_list @[simp] theorem decode_list_succ (v : ℕ) : decode (list α) (succ v) = (::) <$> decode α v.unpair.1 <*> decode (list α) v.unpair.2 := show decode_list (succ v) = _, begin cases e : unpair v with v₁ v₂, simp [decode_list, e], refl end theorem length_le_encode : ∀ (l : list α), length l ≤ encode l | [] := _root_.zero_le _ | (a :: l) := succ_le_succ $ (length_le_encode l).trans (right_le_mkpair _ _) end list section finset variables [encodable α] private def enle : α → α → Prop := encode ⁻¹'o (≤) private lemma enle.is_linear_order : is_linear_order α enle := (rel_embedding.preimage ⟨encode, encode_injective⟩ (≤)).is_linear_order private def decidable_enle (a b : α) : decidable (enle a b) := by unfold enle order.preimage; apply_instance local attribute [instance] enle.is_linear_order decidable_enle /-- Explicit encoding function for `multiset α` -/ def encode_multiset (s : multiset α) : ℕ := encode (s.sort enle) /-- Explicit decoding function for `multiset α` -/ def decode_multiset (n : ℕ) : option (multiset α) := coe <$> decode (list α) n /-- If `α` is encodable, then so is `multiset α`. -/ instance multiset : encodable (multiset α) := ⟨encode_multiset, decode_multiset, λ s, by simp [encode_multiset, decode_multiset, encodek]⟩ end finset /-- A listable type with decidable equality is encodable. -/ def encodable_of_list [decidable_eq α] (l : list α) (H : ∀ x, x ∈ l) : encodable α := ⟨λ a, index_of a l, l.nth, λ a, index_of_nth (H _)⟩ def trunc_encodable_of_fintype (α : Type*) [decidable_eq α] [fintype α] : trunc (encodable α) := @@quot.rec_on_subsingleton _ (λ s : multiset α, (∀ x:α, x ∈ s) → trunc (encodable α)) _ finset.univ.1 (λ l H, trunc.mk $ encodable_of_list l H) finset.mem_univ /-- A noncomputable way to arbitrarily choose an ordering on a finite type. It is not made into a global instance, since it involves an arbitrary choice. This can be locally made into an instance with `local attribute [instance] fintype.encodable`. -/ noncomputable def _root_.fintype.encodable (α : Type*) [fintype α] : encodable α := by { classical, exact (encodable.trunc_encodable_of_fintype α).out } /-- If `α` is encodable, then so is `vector α n`. -/ instance vector [encodable α] {n} : encodable (vector α n) := encodable.subtype /-- If `α` is encodable, then so is `fin n → α`. -/ instance fin_arrow [encodable α] {n} : encodable (fin n → α) := of_equiv _ (equiv.vector_equiv_fin _ _).symm instance fin_pi (n) (π : fin n → Type*) [∀ i, encodable (π i)] : encodable (Π i, π i) := of_equiv _ (equiv.pi_equiv_subtype_sigma (fin n) π) /-- If `α` is encodable, then so is `array n α`. -/ instance array [encodable α] {n} : encodable (array n α) := of_equiv _ (equiv.array_equiv_fin _ _) /-- If `α` is encodable, then so is `finset α`. -/ instance finset [encodable α] : encodable (finset α) := by haveI := decidable_eq_of_encodable α; exact of_equiv {s : multiset α // s.nodup} ⟨λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩ def fintype_arrow (α : Type*) (β : Type*) [decidable_eq α] [fintype α] [encodable β] : trunc (encodable (α → β)) := (fintype.trunc_equiv_fin α).map $ λ f, encodable.of_equiv (fin (fintype.card α) → β) $ equiv.arrow_congr f (equiv.refl _) def fintype_pi (α : Type*) (π : α → Type*) [decidable_eq α] [fintype α] [∀ a, encodable (π a)] : trunc (encodable (Π a, π a)) := (encodable.trunc_encodable_of_fintype α).bind $ λ a, (@fintype_arrow α (Σa, π a) _ _ (@encodable.sigma _ _ a _)).bind $ λ f, trunc.mk $ @encodable.of_equiv _ _ (@encodable.subtype _ _ f _) (equiv.pi_equiv_subtype_sigma α π) /-- The elements of a `fintype` as a sorted list. -/ def sorted_univ (α) [fintype α] [encodable α] : list α := finset.univ.sort (encodable.encode' α ⁻¹'o (≤)) @[simp] theorem mem_sorted_univ {α} [fintype α] [encodable α] (x : α) : x ∈ sorted_univ α := (finset.mem_sort _).2 (finset.mem_univ _) @[simp] theorem length_sorted_univ (α) [fintype α] [encodable α] : (sorted_univ α).length = fintype.card α := finset.length_sort _ @[simp] theorem sorted_univ_nodup (α) [fintype α] [encodable α] : (sorted_univ α).nodup := finset.sort_nodup _ _ @[simp] theorem sorted_univ_to_finset (α) [fintype α] [encodable α] [decidable_eq α] : (sorted_univ α).to_finset = finset.univ := finset.sort_to_finset _ _ /-- An encodable `fintype` is equivalent to the same size `fin`. -/ def fintype_equiv_fin {α} [fintype α] [encodable α] : α ≃ fin (fintype.card α) := begin haveI : decidable_eq α := encodable.decidable_eq_of_encodable _, transitivity, { exact ((sorted_univ_nodup α).nth_le_equiv_of_forall_mem_list _ mem_sorted_univ).symm }, exact equiv.cast (congr_arg _ (length_sorted_univ α)) end /-- If `α` and `β` are encodable and `α` is a fintype, then `α → β` is encodable as well. -/ instance fintype_arrow_of_encodable {α β : Type*} [encodable α] [fintype α] [encodable β] : encodable (α → β) := of_equiv (fin (fintype.card α) → β) $ equiv.arrow_congr fintype_equiv_fin (equiv.refl _) end encodable namespace denumerable variables {α : Type*} {β : Type*} [denumerable α] [denumerable β] open encodable section list theorem denumerable_list_aux : ∀ n : ℕ, ∃ a ∈ @decode_list α _ n, encode_list a = n | 0 := by rw decode_list; exact ⟨_, rfl, rfl⟩ | (succ v) := begin cases e : unpair v with v₁ v₂, have h := unpair_right_le v, rw e at h, rcases have v₂ < succ v, from lt_succ_of_le h, denumerable_list_aux v₂ with ⟨a, h₁, h₂⟩, rw option.mem_def at h₁, use of_nat α v₁ :: a, simp [decode_list, e, h₂, h₁, encode_list, mkpair_unpair' e], end /-- If `α` is denumerable, then so is `list α`. -/ instance denumerable_list : denumerable (list α) := ⟨denumerable_list_aux⟩ @[simp] theorem list_of_nat_zero : of_nat (list α) 0 = [] := by rw [← @encode_list_nil α, of_nat_encode] @[simp] theorem list_of_nat_succ (v : ℕ) : of_nat (list α) (succ v) = of_nat α v.unpair.1 :: of_nat (list α) v.unpair.2 := of_nat_of_decode $ show decode_list (succ v) = _, begin cases e : unpair v with v₁ v₂, simp [decode_list, e], rw [show decode_list v₂ = decode (list α) v₂, from rfl, decode_eq_of_nat]; refl end end list section multiset /-- Outputs the list of differences of the input list, that is `lower [a₁, a₂, ...] n = [a₁ - n, a₂ - a₁, ...]` -/ def lower : list ℕ → ℕ → list ℕ | [] n := [] | (m :: l) n := (m - n) :: lower l m /-- Outputs the list of partial sums of the input list, that is `raise [a₁, a₂, ...] n = [n + a₁, n + a₁ + a₂, ...]` -/ def raise : list ℕ → ℕ → list ℕ | [] n := [] | (m :: l) n := (m + n) :: raise l (m + n) lemma lower_raise : ∀ l n, lower (raise l n) n = l | [] n := rfl | (m :: l) n := by rw [raise, lower, add_tsub_cancel_right, lower_raise] lemma raise_lower : ∀ {l n}, list.sorted (≤) (n :: l) → raise (lower l n) n = l | [] n h := rfl | (m :: l) n h := have n ≤ m, from list.rel_of_sorted_cons h _ (l.mem_cons_self _), by simp [raise, lower, tsub_add_cancel_of_le this, raise_lower (list.sorted_of_sorted_cons h)] lemma raise_chain : ∀ l n, list.chain (≤) n (raise l n) | [] n := list.chain.nil | (m :: l) n := list.chain.cons (nat.le_add_left _ _) (raise_chain _ _) /-- `raise l n` is an non-decreasing sequence. -/ lemma raise_sorted : ∀ l n, list.sorted (≤) (raise l n) | [] n := list.sorted_nil | (m :: l) n := (list.chain_iff_pairwise (@le_trans _ _)).1 (raise_chain _ _) /-- If `α` is denumerable, then so is `multiset α`. Warning: this is *not* the same encoding as used in `encodable.multiset`. -/ instance multiset : denumerable (multiset α) := mk' ⟨ λ s : multiset α, encode $ lower ((s.map encode).sort (≤)) 0, λ n, multiset.map (of_nat α) (raise (of_nat (list ℕ) n) 0), λ s, by have := raise_lower (list.sorted_cons.2 ⟨λ n _, zero_le n, (s.map encode).sort_sorted _⟩); simp [-multiset.coe_map, this], λ n, by simp [-multiset.coe_map, list.merge_sort_eq_self _ (raise_sorted _ _), lower_raise]⟩ end multiset section finset /-- Outputs the list of differences minus one of the input list, that is `lower' [a₁, a₂, a₃, ...] n = [a₁ - n, a₂ - a₁ - 1, a₃ - a₂ - 1, ...]`. -/ def lower' : list ℕ → ℕ → list ℕ | [] n := [] | (m :: l) n := (m - n) :: lower' l (m + 1) /-- Outputs the list of partial sums plus one of the input list, that is `raise [a₁, a₂, a₃, ...] n = [n + a₁, n + a₁ + a₂ + 1, n + a₁ + a₂ + a₃ + 2, ...]`. Adding one each time ensures the elements are distinct. -/ def raise' : list ℕ → ℕ → list ℕ | [] n := [] | (m :: l) n := (m + n) :: raise' l (m + n + 1) lemma lower_raise' : ∀ l n, lower' (raise' l n) n = l | [] n := rfl | (m :: l) n := by simp [raise', lower', add_tsub_cancel_right, lower_raise'] lemma raise_lower' : ∀ {l n}, (∀ m ∈ l, n ≤ m) → list.sorted (<) l → raise' (lower' l n) n = l | [] n h₁ h₂ := rfl | (m :: l) n h₁ h₂ := have n ≤ m, from h₁ _ (l.mem_cons_self _), by simp [raise', lower', tsub_add_cancel_of_le this, raise_lower' (list.rel_of_sorted_cons h₂ : ∀ a ∈ l, m < a) (list.sorted_of_sorted_cons h₂)] lemma raise'_chain : ∀ l {m n}, m < n → list.chain (<) m (raise' l n) | [] m n h := list.chain.nil | (a :: l) m n h := list.chain.cons (lt_of_lt_of_le h (nat.le_add_left _ _)) (raise'_chain _ (lt_succ_self _)) /-- `raise' l n` is a strictly increasing sequence. -/ lemma raise'_sorted : ∀ l n, list.sorted (<) (raise' l n) | [] n := list.sorted_nil | (m :: l) n := (list.chain_iff_pairwise (@lt_trans _ _)).1 (raise'_chain _ (lt_succ_self _)) /-- Makes `raise' l n` into a finset. Elements are distinct thanks to `raise'_sorted`. -/ def raise'_finset (l : list ℕ) (n : ℕ) : finset ℕ := ⟨raise' l n, (raise'_sorted _ _).imp (@ne_of_lt _ _)⟩ /-- If `α` is denumerable, then so is `finset α`. Warning: this is *not* the same encoding as used in `encodable.finset`. -/ instance finset : denumerable (finset α) := mk' ⟨ λ s : finset α, encode $ lower' ((s.map (eqv α).to_embedding).sort (≤)) 0, λ n, finset.map (eqv α).symm.to_embedding (raise'_finset (of_nat (list ℕ) n) 0), λ s, finset.eq_of_veq $ by simp [-multiset.coe_map, raise'_finset, raise_lower' (λ n _, zero_le n) (finset.sort_sorted_lt _)], λ n, by simp [-multiset.coe_map, finset.map, raise'_finset, finset.sort, list.merge_sort_eq_self (≤) ((raise'_sorted _ _).imp (@le_of_lt _ _)), lower_raise']⟩ end finset end denumerable namespace equiv /-- The type lists on unit is canonically equivalent to the natural numbers. -/ def list_unit_equiv : list unit ≃ ℕ := { to_fun := list.length, inv_fun := list.repeat (), left_inv := λ u, list.length_injective (by simp), right_inv := λ n, list.length_repeat () n } /-- `list ℕ` is equivalent to `ℕ`. -/ def list_nat_equiv_nat : list ℕ ≃ ℕ := denumerable.eqv _ /-- If `α` is equivalent to `ℕ`, then `list α` is equivalent to `α`. -/ def list_equiv_self_of_equiv_nat {α : Type} (e : α ≃ ℕ) : list α ≃ α := calc list α ≃ list ℕ : list_equiv_of_equiv e ... ≃ ℕ : list_nat_equiv_nat ... ≃ α : e.symm end equiv
f394005bded70e3e90eacd0b44e5fdd546f3e0b7
efa51dd2edbbbbd6c34bd0ce436415eb405832e7
/20161026_ICTAC_Tutorial/ex13.lean
aa25140bceaf8cb5e78163f3fadc0007e6b5b3a7
[ "Apache-2.0" ]
permissive
leanprover/presentations
dd031a05bcb12c8855676c77e52ed84246bd889a
3ce2d132d299409f1de269fa8e95afa1333d644e
refs/heads/master
1,688,703,388,796
1,686,838,383,000
1,687,465,742,000
29,750,158
12
9
Apache-2.0
1,540,211,670,000
1,422,042,683,000
Lean
UTF-8
Lean
false
false
482
lean
/- Beta reduction -/ constants A B C : Type constant f : A → B constant g : B → C constant h : A → A constants (a : A) (b : B) eval (λ x : A, x) a -- a eval (λ x : A, b) a -- b eval (λ x : A, b) (h a) -- b eval (λ x : A, g (f x)) a -- g (f a) eval (λ (v : B → C) (u : A → B) x, v (u x)) g f a -- g (f a) eval (λ (Q R S : Type) (v : R → S) (u : Q → R) (x : Q), v (u x)) A B C g f a -- g (f a)
9e14cee5dbdf44eb3d449e8647b0eb11a9515a0b
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/algebra/category/functor.lean
d4488cef4bc8cab846bf8f78d443a79ea245db09
[ "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
4,205
lean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn -/ import .basic import logic.cast open function open category eq eq.ops heq structure functor (C D : Category) : Type := (object : C → D) (morphism : Π⦃a b : C⦄, hom a b → hom (object a) (object b)) (respect_id : Π (a : C), morphism (ID a) = ID (object a)) (respect_comp : Π ⦃a b c : C⦄ (g : hom b c) (f : hom a b), morphism (g ∘ f) = morphism g ∘ morphism f) infixl `⇒`:25 := functor namespace functor attribute object [coercion] attribute morphism [coercion] attribute respect_id [irreducible] attribute respect_comp [irreducible] variables {A B C D : Category} protected definition compose [reducible] (G : functor B C) (F : functor A B) : functor A C := functor.mk (λx, G (F x)) (λ a b f, G (F f)) (λ a, proof calc G (F (ID a)) = G id : {respect_id F a} --not giving the braces explicitly makes the elaborator compute a couple more seconds ... = id : respect_id G (F a) qed) (λ a b c g f, proof calc G (F (g ∘ f)) = G (F g ∘ F f) : respect_comp F g f ... = G (F g) ∘ G (F f) : respect_comp G (F g) (F f) qed) infixr `∘f`:60 := functor.compose protected theorem assoc (H : functor C D) (G : functor B C) (F : functor A B) : H ∘f (G ∘f F) = (H ∘f G) ∘f F := rfl protected definition id [reducible] {C : Category} : functor C C := mk (λa, a) (λ a b f, f) (λ a, rfl) (λ a b c f g, rfl) protected definition ID [reducible] (C : Category) : functor C C := @functor.id C protected theorem id_left (F : functor C D) : (@functor.id D) ∘f F = F := functor.rec (λ obF homF idF compF, dcongr_arg4 mk rfl rfl !proof_irrel !proof_irrel) F protected theorem id_right (F : functor C D) : F ∘f (@functor.id C) = F := functor.rec (λ obF homF idF compF, dcongr_arg4 mk rfl rfl !proof_irrel !proof_irrel) F end functor namespace category open functor definition category_of_categories [reducible] : category Category := mk (λ a b, functor a b) (λ a b c g f, functor.compose g f) (λ a, functor.id) (λ a b c d h g f, !functor.assoc) (λ a b f, !functor.id_left) (λ a b f, !functor.id_right) definition Category_of_categories [reducible] := Mk category_of_categories namespace ops notation `Cat`:max := Category_of_categories attribute category_of_categories [instance] end ops end category namespace functor variables {C D : Category} theorem mk_heq {obF obG : C → D} {homF homG idF idG compF compG} (Hob : ∀x, obF x = obG x) (Hmor : ∀(a b : C) (f : a ⟶ b), homF a b f == homG a b f) : mk obF homF idF compF = mk obG homG idG compG := hddcongr_arg4 mk (funext Hob) (hfunext (λ a, hfunext (λ b, hfunext (λ f, !Hmor)))) !proof_irrel !proof_irrel protected theorem hequal {F G : C ⇒ D} : Π (Hob : ∀x, F x = G x) (Hmor : ∀a b (f : a ⟶ b), F f == G f), F = G := functor.rec (λ obF homF idF compF, functor.rec (λ obG homG idG compG Hob Hmor, mk_heq Hob Hmor) G) F -- theorem mk_eq {obF obG : C → D} {homF homG idF idG compF compG} (Hob : ∀x, obF x = obG x) -- (Hmor : ∀(a b : C) (f : a ⟶ b), cast (congr_arg (λ x, x a ⟶ x b) (funext Hob)) (homF a b f) -- = homG a b f) -- : mk obF homF idF compF = mk obG homG idG compG := -- dcongr_arg4 mk -- (funext Hob) -- (funext (λ a, funext (λ b, funext (λ f, sorry ⬝ Hmor a b f)))) -- -- to fill this sorry use (a generalization of) cast_pull -- !proof_irrel -- !proof_irrel -- protected theorem equal {F G : C ⇒ D} : Π (Hob : ∀x, F x = G x) -- (Hmor : ∀a b (f : a ⟶ b), cast (congr_arg (λ x, x a ⟶ x b) (funext Hob)) (F f) = G f), F = G := -- functor.rec -- (λ obF homF idF compF, -- functor.rec -- (λ obG homG idG compG Hob Hmor, mk_eq Hob Hmor) -- G) -- F end functor
aa865691b709b2985e165c7473c720a8505ea114
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/topology/order/lattice.lean
29460e9a48f3d3b77700d8d729539da005f67fce
[ "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
2,873
lean
/- Copyright (c) 2021 Christopher Hoskin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Christopher Hoskin -/ import topology.basic import topology.constructions import topology.algebra.ordered.basic /-! # Topological lattices In this file we define mixin classes `has_continuous_inf` and `has_continuous_sup`. We define the class `topological_lattice` as a topological space and lattice `L` extending `has_continuous_inf` and `has_continuous_sup`. ## References * [Gierz et al, A Compendium of Continuous Lattices][GierzEtAl1980] ## Tags topological, lattice -/ /-- Let `L` be a topological space and let `L×L` be equipped with the product topology and let `⊓:L×L → L` be an infimum. Then `L` is said to have *(jointly) continuous infimum* if the map `⊓:L×L → L` is continuous. -/ class has_continuous_inf (L : Type*) [topological_space L] [has_inf L] : Prop := (continuous_inf : continuous (λ p : L × L, p.1 ⊓ p.2)) /-- Let `L` be a topological space and let `L×L` be equipped with the product topology and let `⊓:L×L → L` be a supremum. Then `L` is said to have *(jointly) continuous supremum* if the map `⊓:L×L → L` is continuous. -/ class has_continuous_sup (L : Type*) [topological_space L] [has_sup L] : Prop := (continuous_sup : continuous (λ p : L × L, p.1 ⊔ p.2)) /-- Let `L` be a topological space with a supremum. If the order dual has a continuous infimum then the supremum is continuous. -/ @[priority 100] -- see Note [lower instance priority] instance has_continuous_inf_dual_has_continuous_sup (L : Type*) [topological_space L] [has_sup L] [h: has_continuous_inf (order_dual L)] : has_continuous_sup L := { continuous_sup := @has_continuous_inf.continuous_inf (order_dual L) _ _ h } /-- Let `L` be a lattice equipped with a topology such that `L` has continuous infimum and supremum. Then `L` is said to be a *topological lattice*. -/ class topological_lattice (L : Type*) [topological_space L] [lattice L] extends has_continuous_inf L, has_continuous_sup L variables {L : Type*} [topological_space L] variables {X : Type*} [topological_space X] @[continuity] lemma continuous_inf [has_inf L] [has_continuous_inf L] : continuous (λp:L×L, p.1 ⊓ p.2) := has_continuous_inf.continuous_inf @[continuity] lemma continuous.inf [has_inf L] [has_continuous_inf L] {f g : X → L} (hf : continuous f) (hg : continuous g) : continuous (λx, f x ⊓ g x) := continuous_inf.comp (hf.prod_mk hg : _) @[continuity] lemma continuous_sup [has_sup L] [has_continuous_sup L] : continuous (λp:L×L, p.1 ⊔ p.2) := has_continuous_sup.continuous_sup @[continuity] lemma continuous.sup [has_sup L] [has_continuous_sup L] {f g : X → L} (hf : continuous f) (hg : continuous g) : continuous (λx, f x ⊔ g x) := continuous_sup.comp (hf.prod_mk hg : _)
3a7394e970cd3b4ae4db01a2bc1f78c52a9985bb
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/section4.lean
888ab5d0743208a3f2a193d24805ea0fc9c0b134
[ "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
639
lean
set_option pp.universes true set_option pp.implicit true section universe k parameter A : Type section universe variable l universe variable u parameter B : Type definition foo (a : A) (b : B) := b inductive mypair | mk : A → B → mypair #print mypair.rec #check mypair.mk definition pr1' : mypair → A | (mypair.mk a b) := a definition pr2' : mypair → B | (mypair.mk a b) := b end #check mypair.rec variable a : A #check foo nat a 0 definition pr1 : mypair nat → A | (mypair.mk a b) := a definition pr2 : mypair nat → nat | (mypair.mk a b) := b end
819d3c56b84bc31e9e53f0e0edb236e5292f3f90
2c41ae31b2b771ad5646ad880201393f5269a7f0
/Lean/Examples/Parnas/Functional_Decomposition.lean
122568f9301febdbd95f49caf7a0749ec4a3691e
[]
no_license
kevinsullivan/Boehm
926f25bc6f1a8b6bd47d333d936fdfc278228312
55208395bff20d48a598b7fa33a4d55a2447a9cf
refs/heads/master
1,586,127,134,302
1,488,252,326,000
1,488,252,326,000
32,836,930
0
0
null
null
null
null
UTF-8
Lean
false
false
6,146
lean
import Examples.Parnas.DesignStructure import SystemModel.System import Qualities.Changeable import Examples.Parnas.Shared_Info set_option eqn_compiler.max_steps 256 inductive kwicParameter | computer | corpus | user | alph_abs | alph_alg | alph_data | circ_abs | circ_alg | circ_data | input_abs | input_alg | input_data | output_abs | output_alg | output_data | master open kwicParameter definition uses : kwicParameter -> kwicParameter -> Prop | kwicParameter.master kwicParameter.input_abs := true | kwicParameter.master kwicParameter.circ_abs := true | kwicParameter.master kwicParameter.alph_abs := true | kwicParameter.master kwicParameter.output_abs := true | kwicParameter.input_alg kwicParameter.input_data := true | kwicParameter.input_data kwicParameter.circ_data := true | kwicParameter.input_data kwicParameter.alph_data := true | kwicParameter.circ_alg kwicParameter.circ_data := true | kwicParameter.circ_alg kwicParameter.input_data := true | kwicParameter.circ_data kwicParameter.input_data := true | kwicParameter.circ_data kwicParameter.alph_data := true | kwicParameter.alph_alg kwicParameter.input_data := true | kwicParameter.alph_alg kwicParameter.circ_data := true | kwicParameter.alph_alg kwicParameter.alph_data := true | kwicParameter.alph_data kwicParameter.input_data := true | kwicParameter.alph_data kwicParameter.circ_data := true | kwicParameter.output_alg kwicParameter.input_data := true | kwicParameter.output_alg kwicParameter.alph_data := true | kwicParameter.output_alg kwicParameter.output_data := true | _ _ := false definition satisfies : kwicParameter -> kwicParameter -> Prop | computer input_data := true | computer circ_data := true | computer alph_data := true | computer output_data := true | computer input_alg := true | computer alph_alg := true | computer output_alg := true | corpus input_data := true | corpus input_alg := true | corpus circ_data := true | corpus circ_alg := true | corpus alph_data := true | corpus alph_alg := true | corpus output_data := true | corpus output_alg := true | user circ_alg := true | user alph_alg := true | user master := true | input_abs input_alg := true | circ_abs circ_alg := true | alph_abs alph_alg := true | output_abs output_alg := true | _ _ := false definition input_mod : (@Module kwicParameter) := { name := "Input", elements := []} definition circ_mod : (@Module kwicParameter) := { name := "Circular", elements := []} definition alph_mod : (@Module kwicParameter) := { name := "Alphabetizer", elements := []} definition out_mod : (@Module kwicParameter) := { name := "Output", elements := []} definition master_mod : (@Module kwicParameter) := { name := "Master", elements := []} definition kwic_modules : list Module := [input_mod, circ_mod, alph_mod, out_mod, master_mod] definition kwic_volatile : kwicParameter -> Prop | corpus := true | computer := true | user := true | _ := false definition kwic_ds: DesignStructure := { Modules := kwic_modules, Volatile := kwic_volatile, Uses:= uses, Satisfies:= satisfies } inductive kwic_ds_type | mk_kwic_ds : (@DesignStructure kwicParameter) -> Prop -> kwic_ds_type definition extract_kwic_ds : kwic_ds_type -> (@DesignStructure kwicParameter) | (kwic_ds_type.mk_kwic_ds ds _) := ds record kwic := mk :: (kwic_volatile_state: kwicVolatileState) (kwic_design: kwic_ds_type) definition kwicSystemType : SystemType := { Contexts:=kwicContexts, Stakeholders:= kwicStakeholders, Phases:= kwicPhases, ArtifactType:= kwic, ValueType:= kwicValue } /- Abbreviations for writing propositions, assertions, actions. -/ definition kwicSystemState := @SystemInstance kwicSystemType definition kwicAssertion := @Assertion kwicSystemType definition kwicAction := @Action kwicSystemType /- test more specifically whether a system is modular with respect to a single parameter-/ definition isModular (ks: kwicSystemState): Prop := modular (extract_kwic_ds ks^.artifact^.kwic_design) definition isModular_wrt (kp: kwicParameter) (ks: kwicSystemState): Prop := modular_wrt kp (extract_kwic_ds ks^.artifact^.kwic_design) definition computerPre (ks: kwicSystemState): Prop := ks^.artifact^.kwic_volatile_state^.computer_state = computerState.computer_pre definition computerPost (ks: kwicSystemState): Prop := ks^.artifact^.kwic_volatile_state^.computer_state = computerState.computer_post definition corpusPre (ks: kwicSystemState): Prop := ks^.artifact^.kwic_volatile_state^.corpus_state = corpusState.corpus_pre definition corpusPost (ks: kwicSystemState): Prop := ks^.artifact^.kwic_volatile_state^.corpus_state = corpusState.corpus_post definition userPre (ks: kwicSystemState): Prop := ks^.artifact^.kwic_volatile_state^.user_state = userState.user_pre definition userPost (ks: kwicSystemState): Prop := ks^.artifact^.kwic_volatile_state^.user_state = userState.user_post definition inMaintenancePhase (ks: kwicSystemState): Prop := ks^.phase = kwicPhases.maintenance definition computerPreState : kwicAssertion := fun ks: kwicSystemState, computerPre ks definition computerPostState : kwicAssertion := fun ks: kwicSystemState, computerPost ks definition corpusPreState : kwicAssertion := fun ks: kwicSystemState, corpusPre ks definition corpusPostState : kwicAssertion := fun ks: kwicSystemState,corpusPost ks definition userPreState : kwicAssertion := fun ks: kwicSystemState, userPre ks definition userPostState : kwicAssertion := fun ks: kwicSystemState, userPost ks definition costomerChangeCorpus: kwicAction := fun ks: kwicSystemState, { context:=kwicContexts.nominal, phase:=kwicPhases.maintenance, artifact:= { kwic_volatile_state := { computer_state := ks^.artifact^.kwic_volatile_state^.computer_state, corpus_state:= corpusState.corpus_post, user_state:= ks^.artifact^.kwic_volatile_state^.user_state }, kwic_design := (kwic_ds_type.mk_kwic_ds kwic_ds (kwic_ds=kwic_ds))}, value := ks^.value }
27ab9cd99afd71d072a2ce64991af35bc3f46f20
aa5a655c05e5359a70646b7154e7cac59f0b4132
/src/Init/Classical.lean
5000a451cb2567d1653d2070113aa02307a237fe
[ "Apache-2.0" ]
permissive
lambdaxymox/lean4
ae943c960a42247e06eff25c35338268d07454cb
278d47c77270664ef29715faab467feac8a0f446
refs/heads/master
1,677,891,867,340
1,612,500,005,000
1,612,500,005,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,263
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Core import Init.NotationExtra universes u v /- Classical reasoning support -/ namespace Classical axiom choice {α : Sort u} : Nonempty α → α noncomputable def indefiniteDescription {α : Sort u} (p : α → Prop) (h : ∃ x, p x) : {x // p x} := choice <| let ⟨x, px⟩ := h; ⟨⟨x, px⟩⟩ noncomputable def choose {α : Sort u} {p : α → Prop} (h : ∃ x, p x) : α := (indefiniteDescription p h).val theorem chooseSpec {α : Sort u} {p : α → Prop} (h : ∃ x, p x) : p (choose h) := (indefiniteDescription p h).property /- Diaconescu's theorem: excluded middle from choice, Function extensionality and propositional extensionality. -/ theorem em (p : Prop) : p ∨ ¬p := let U (x : Prop) : Prop := x = True ∨ p; let V (x : Prop) : Prop := x = False ∨ p; have exU : ∃ x, U x from ⟨True, Or.inl rfl⟩; have exV : ∃ x, V x from ⟨False, Or.inl rfl⟩; let u : Prop := choose exU; let v : Prop := choose exV; have uDef : U u from chooseSpec exU; have vDef : V v from chooseSpec exV; have notUvOrP : u ≠ v ∨ p from match uDef, vDef with | Or.inr h, _ => Or.inr h | _, Or.inr h => Or.inr h | Or.inl hut, Or.inl hvf => have hne : u ≠ v from hvf.symm ▸ hut.symm ▸ trueNeFalse Or.inl hne have pImpliesUv : p → u = v from fun hp => have hpred : U = V from funext fun x => have hl : (x = True ∨ p) → (x = False ∨ p) from fun a => Or.inr hp; have hr : (x = False ∨ p) → (x = True ∨ p) from fun a => Or.inr hp; show (x = True ∨ p) = (x = False ∨ p) from propext (Iff.intro hl hr); have h₀ : ∀ exU exV, @choose _ U exU = @choose _ V exV from hpred ▸ fun exU exV => rfl; show u = v from h₀ ..; match notUvOrP with | Or.inl hne => Or.inr (mt pImpliesUv hne) | Or.inr h => Or.inl h theorem existsTrueOfNonempty {α : Sort u} : Nonempty α → ∃ x : α, True | ⟨x⟩ => ⟨x, trivial⟩ noncomputable def inhabitedOfNonempty {α : Sort u} (h : Nonempty α) : Inhabited α := ⟨choice h⟩ noncomputable def inhabitedOfExists {α : Sort u} {p : α → Prop} (h : ∃ x, p x) : Inhabited α := inhabitedOfNonempty (Exists.elim h (fun w hw => ⟨w⟩)) /- all propositions are Decidable -/ noncomputable scoped instance (priority := low) propDecidable (a : Prop) : Decidable a := choice <| match em a with | Or.inl h => ⟨isTrue h⟩ | Or.inr h => ⟨isFalse h⟩ noncomputable def decidableInhabited (a : Prop) : Inhabited (Decidable a) where default := inferInstance noncomputable def typeDecidableEq (α : Sort u) : DecidableEq α := fun x y => inferInstance noncomputable def typeDecidable (α : Sort u) : PSum α (α → False) := match (propDecidable (Nonempty α)) with | (isTrue hp) => PSum.inl (@arbitrary _ (inhabitedOfNonempty hp)) | (isFalse hn) => PSum.inr (fun a => absurd (Nonempty.intro a) hn) noncomputable def strongIndefiniteDescription {α : Sort u} (p : α → Prop) (h : Nonempty α) : {x : α // (∃ y : α, p y) → p x} := @dite _ (∃ x : α, p x) (propDecidable _) (fun (hp : ∃ x : α, p x) => show {x : α // (∃ y : α, p y) → p x} from let xp := indefiniteDescription _ hp; ⟨xp.val, fun h' => xp.property⟩) (fun hp => ⟨choice h, fun h => absurd h hp⟩) /- the Hilbert epsilon Function -/ noncomputable def epsilon {α : Sort u} [h : Nonempty α] (p : α → Prop) : α := (strongIndefiniteDescription p h).val theorem epsilonSpecAux {α : Sort u} (h : Nonempty α) (p : α → Prop) : (∃ y, p y) → p (@epsilon α h p) := (strongIndefiniteDescription p h).property theorem epsilonSpec {α : Sort u} {p : α → Prop} (hex : ∃ y, p y) : p (@epsilon α (nonemptyOfExists hex) p) := epsilonSpecAux (nonemptyOfExists hex) p hex theorem epsilonSingleton {α : Sort u} (x : α) : @epsilon α ⟨x⟩ (fun y => y = x) = x := @epsilonSpec α (fun y => y = x) ⟨x, rfl⟩ /- the axiom of choice -/ theorem axiomOfChoice {α : Sort u} {β : α → Sort v} {r : ∀ x, β x → Prop} (h : ∀ x, ∃ y, r x y) : ∃ (f : ∀ x, β x), ∀ x, r x (f x) := ⟨_, fun x => chooseSpec (h x)⟩ theorem skolem {α : Sort u} {b : α → Sort v} {p : ∀ x, b x → Prop} : (∀ x, ∃ y, p x y) ↔ ∃ (f : ∀ x, b x), ∀ x, p x (f x) := ⟨axiomOfChoice, fun ⟨f, hw⟩ (x) => ⟨f x, hw x⟩⟩ theorem propComplete (a : Prop) : a = True ∨ a = False := by cases em a with | inl _ => apply Or.inl; apply propext; apply Iff.intro; { intros; apply True.intro }; { intro; assumption } | inr hn => apply Or.inr; apply propext; apply Iff.intro; { intro h; exact hn h }; { intro h; apply False.elim h } -- this supercedes byCases in Decidable theorem byCases {p q : Prop} (hpq : p → q) (hnpq : ¬p → q) : q := Decidable.byCases (dec := propDecidable _) hpq hnpq -- this supercedes byContradiction in Decidable theorem byContradiction {p : Prop} (h : ¬p → False) : p := Decidable.byContradiction (dec := propDecidable _) h end Classical
56b3b82569ec93da4eedf034dd1978e831dd34ac
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/measure_theory/function/jacobian.lean
c7469efe8f991e63206a8806c8922c5b104804c5
[ "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
70,967
lean
/- Copyright (c) 2022 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.calculus.inverse import measure_theory.constructions.borel_space.continuous_linear_map import measure_theory.covering.besicovitch_vector_space import measure_theory.measure.lebesgue.eq_haar import analysis.normed_space.pointwise import measure_theory.constructions.polish /-! # Change of variables in higher-dimensional integrals > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Let `μ` be a Lebesgue measure on a finite-dimensional real vector space `E`. Let `f : E → E` be a function which is injective and differentiable on a measurable set `s`, with derivative `f'`. Then we prove that `f '' s` is measurable, and its measure is given by the formula `μ (f '' s) = ∫⁻ x in s, |(f' x).det| ∂μ` (where `(f' x).det` is almost everywhere measurable, but not Borel-measurable in general). This formula is proved in `lintegral_abs_det_fderiv_eq_add_haar_image`. We deduce the change of variables formula for the Lebesgue and Bochner integrals, in `lintegral_image_eq_lintegral_abs_det_fderiv_mul` and `integral_image_eq_integral_abs_det_fderiv_smul` respectively. ## Main results * `add_haar_image_eq_zero_of_differentiable_on_of_add_haar_eq_zero`: if `f` is differentiable on a set `s` with zero measure, then `f '' s` also has zero measure. * `add_haar_image_eq_zero_of_det_fderiv_within_eq_zero`: if `f` is differentiable on a set `s`, and its derivative is never invertible, then `f '' s` has zero measure (a version of Sard's lemma). * `ae_measurable_fderiv_within`: if `f` is differentiable on a measurable set `s`, then `f'` is almost everywhere measurable on `s`. For the next statements, `s` is a measurable set and `f` is differentiable on `s` (with a derivative `f'`) and injective on `s`. * `measurable_image_of_fderiv_within`: the image `f '' s` is measurable. * `measurable_embedding_of_fderiv_within`: the function `s.restrict f` is a measurable embedding. * `lintegral_abs_det_fderiv_eq_add_haar_image`: the image measure is given by `μ (f '' s) = ∫⁻ x in s, |(f' x).det| ∂μ`. * `lintegral_image_eq_lintegral_abs_det_fderiv_mul`: for `g : E → ℝ≥0∞`, one has `∫⁻ x in f '' s, g x ∂μ = ∫⁻ x in s, ennreal.of_real (|(f' x).det|) * g (f x) ∂μ`. * `integral_image_eq_integral_abs_det_fderiv_smul`: for `g : E → F`, one has `∫ x in f '' s, g x ∂μ = ∫ x in s, |(f' x).det| • g (f x) ∂μ`. * `integrable_on_image_iff_integrable_on_abs_det_fderiv_smul`: for `g : E → F`, the function `g` is integrable on `f '' s` if and only if `|(f' x).det| • g (f x))` is integrable on `s`. ## Implementation Typical versions of these results in the literature have much stronger assumptions: `s` would typically be open, and the derivative `f' x` would depend continuously on `x` and be invertible everywhere, to have the local inverse theorem at our disposal. The proof strategy under our weaker assumptions is more involved. We follow [Fremlin, *Measure Theory* (volume 2)][fremlin_vol2]. The first remark is that, if `f` is sufficiently well approximated by a linear map `A` on a set `s`, then `f` expands the volume of `s` by at least `A.det - ε` and at most `A.det + ε`, where the closeness condition depends on `A` in a non-explicit way (see `add_haar_image_le_mul_of_det_lt` and `mul_le_add_haar_image_of_lt_det`). This fact holds for balls by a simple inclusion argument, and follows for general sets using the Besicovitch covering theorem to cover the set by balls with measures adding up essentially to `μ s`. When `f` is differentiable on `s`, one may partition `s` into countably many subsets `s ∩ t n` (where `t n` is measurable), on each of which `f` is well approximated by a linear map, so that the above results apply. See `exists_partition_approximates_linear_on_of_has_fderiv_within_at`, which follows from the pointwise differentiability (in a non-completely trivial way, as one should ensure a form of uniformity on the sets of the partition). Combining the above two results would give the conclusion, except for two difficulties: it is not obvious why `f '' s` and `f'` should be measurable, which prevents us from using countable additivity for the measure and the integral. It turns out that `f '' s` is indeed measurable, and that `f'` is almost everywhere measurable, which is enough to recover countable additivity. The measurability of `f '' s` follows from the deep Lusin-Souslin theorem ensuring that, in a Polish space, a continuous injective image of a measurable set is measurable. The key point to check the almost everywhere measurability of `f'` is that, if `f` is approximated up to `δ` by a linear map on a set `s`, then `f'` is within `δ` of `A` on a full measure subset of `s` (namely, its density points). With the above approximation argument, it follows that `f'` is the almost everywhere limit of a sequence of measurable functions (which are constant on the pieces of the good discretization), and is therefore almost everywhere measurable. ## Tags Change of variables in integrals ## References [Fremlin, *Measure Theory* (volume 2)][fremlin_vol2] -/ open measure_theory measure_theory.measure metric filter set finite_dimensional asymptotics topological_space open_locale nnreal ennreal topology pointwise variables {E F : Type*} [normed_add_comm_group E] [normed_space ℝ E] [finite_dimensional ℝ E] [normed_add_comm_group F] [normed_space ℝ F] {s : set E} {f : E → E} {f' : E → E →L[ℝ] E} /-! ### Decomposition lemmas We state lemmas ensuring that a differentiable function can be approximated, on countably many measurable pieces, by linear maps (with a prescribed precision depending on the linear map). -/ /-- Assume that a function `f` has a derivative at every point of a set `s`. Then one may cover `s` with countably many closed sets `t n` on which `f` is well approximated by linear maps `A n`. -/ lemma exists_closed_cover_approximates_linear_on_of_has_fderiv_within_at [second_countable_topology F] (f : E → F) (s : set E) (f' : E → E →L[ℝ] F) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (r : (E →L[ℝ] F) → ℝ≥0) (rpos : ∀ A, r A ≠ 0) : ∃ (t : ℕ → set E) (A : ℕ → (E →L[ℝ] F)), (∀ n, is_closed (t n)) ∧ (s ⊆ ⋃ n, t n) ∧ (∀ n, approximates_linear_on f (A n) (s ∩ t n) (r (A n))) ∧ (s.nonempty → ∀ n, ∃ y ∈ s, A n = f' y) := begin /- Choose countably many linear maps `f' z`. For every such map, if `f` has a derivative at `x` close enough to `f' z`, then `f y - f x` is well approximated by `f' z (y - x)` for `y` close enough to `x`, say on a ball of radius `r` (or even `u n` for some `n`, where `u` is a fixed sequence tending to `0`). Let `M n z` be the points where this happens. Then this set is relatively closed inside `s`, and moreover in every closed ball of radius `u n / 3` inside it the map is well approximated by `f' z`. Using countably many closed balls to split `M n z` into small diameter subsets `K n z p`, one obtains the desired sets `t q` after reindexing. -/ -- exclude the trivial case where `s` is empty rcases eq_empty_or_nonempty s with rfl|hs, { refine ⟨λ n, ∅, λ n, 0, _, _, _, _⟩; simp }, -- we will use countably many linear maps. Select these from all the derivatives since the -- space of linear maps is second-countable obtain ⟨T, T_count, hT⟩ : ∃ T : set s, T.countable ∧ (⋃ x ∈ T, ball (f' (x : E)) (r (f' x))) = ⋃ (x : s), ball (f' x) (r (f' x)) := topological_space.is_open_Union_countable _ (λ x, is_open_ball), -- fix a sequence `u` of positive reals tending to zero. obtain ⟨u, u_anti, u_pos, u_lim⟩ : ∃ (u : ℕ → ℝ), strict_anti u ∧ (∀ (n : ℕ), 0 < u n) ∧ tendsto u at_top (𝓝 0) := exists_seq_strict_anti_tendsto (0 : ℝ), -- `M n z` is the set of points `x` such that `f y - f x` is close to `f' z (y - x)` for `y` -- in the ball of radius `u n` around `x`. let M : ℕ → T → set E := λ n z, {x | x ∈ s ∧ ∀ y ∈ s ∩ ball x (u n), ‖f y - f x - f' z (y - x)‖ ≤ r (f' z) * ‖y - x‖}, -- As `f` is differentiable everywhere on `s`, the sets `M n z` cover `s` by design. have s_subset : ∀ x ∈ s, ∃ (n : ℕ) (z : T), x ∈ M n z, { assume x xs, obtain ⟨z, zT, hz⟩ : ∃ z ∈ T, f' x ∈ ball (f' (z : E)) (r (f' z)), { have : f' x ∈ ⋃ (z ∈ T), ball (f' (z : E)) (r (f' z)), { rw hT, refine mem_Union.2 ⟨⟨x, xs⟩, _⟩, simpa only [mem_ball, subtype.coe_mk, dist_self] using (rpos (f' x)).bot_lt }, rwa mem_Union₂ at this }, obtain ⟨ε, εpos, hε⟩ : ∃ (ε : ℝ), 0 < ε ∧ ‖f' x - f' z‖ + ε ≤ r (f' z), { refine ⟨r (f' z) - ‖f' x - f' z‖, _, le_of_eq (by abel)⟩, simpa only [sub_pos] using mem_ball_iff_norm.mp hz }, obtain ⟨δ, δpos, hδ⟩ : ∃ (δ : ℝ) (H : 0 < δ), ball x δ ∩ s ⊆ {y | ‖f y - f x - (f' x) (y - x)‖ ≤ ε * ‖y - x‖} := metric.mem_nhds_within_iff.1 (is_o.def (hf' x xs) εpos), obtain ⟨n, hn⟩ : ∃ n, u n < δ := ((tendsto_order.1 u_lim).2 _ δpos).exists, refine ⟨n, ⟨z, zT⟩, ⟨xs, _⟩⟩, assume y hy, calc ‖f y - f x - (f' z) (y - x)‖ = ‖(f y - f x - (f' x) (y - x)) + (f' x - f' z) (y - x)‖ : begin congr' 1, simp only [continuous_linear_map.coe_sub', map_sub, pi.sub_apply], abel, end ... ≤ ‖f y - f x - (f' x) (y - x)‖ + ‖(f' x - f' z) (y - x)‖ : norm_add_le _ _ ... ≤ ε * ‖y - x‖ + ‖f' x - f' z‖ * ‖y - x‖ : begin refine add_le_add (hδ _) (continuous_linear_map.le_op_norm _ _), rw inter_comm, exact inter_subset_inter_right _ (ball_subset_ball hn.le) hy, end ... ≤ r (f' z) * ‖y - x‖ : begin rw [← add_mul, add_comm], exact mul_le_mul_of_nonneg_right hε (norm_nonneg _), end }, -- the sets `M n z` are relatively closed in `s`, as all the conditions defining it are clearly -- closed have closure_M_subset : ∀ n z, s ∩ closure (M n z) ⊆ M n z, { rintros n z x ⟨xs, hx⟩, refine ⟨xs, λ y hy, _⟩, obtain ⟨a, aM, a_lim⟩ : ∃ (a : ℕ → E), (∀ k, a k ∈ M n z) ∧ tendsto a at_top (𝓝 x) := mem_closure_iff_seq_limit.1 hx, have L1 : tendsto (λ (k : ℕ), ‖f y - f (a k) - (f' z) (y - a k)‖) at_top (𝓝 ‖f y - f x - (f' z) (y - x)‖), { apply tendsto.norm, have L : tendsto (λ k, f (a k)) at_top (𝓝 (f x)), { apply (hf' x xs).continuous_within_at.tendsto.comp, apply tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ a_lim, exact eventually_of_forall (λ k, (aM k).1) }, apply tendsto.sub (tendsto_const_nhds.sub L), exact ((f' z).continuous.tendsto _).comp (tendsto_const_nhds.sub a_lim) }, have L2 : tendsto (λ (k : ℕ), (r (f' z) : ℝ) * ‖y - a k‖) at_top (𝓝 (r (f' z) * ‖y - x‖)) := (tendsto_const_nhds.sub a_lim).norm.const_mul _, have I : ∀ᶠ k in at_top, ‖f y - f (a k) - (f' z) (y - a k)‖ ≤ r (f' z) * ‖y - a k‖, { have L : tendsto (λ k, dist y (a k)) at_top (𝓝 (dist y x)) := tendsto_const_nhds.dist a_lim, filter_upwards [(tendsto_order.1 L).2 _ hy.2], assume k hk, exact (aM k).2 y ⟨hy.1, hk⟩ }, exact le_of_tendsto_of_tendsto L1 L2 I }, -- choose a dense sequence `d p` rcases topological_space.exists_dense_seq E with ⟨d, hd⟩, -- split `M n z` into subsets `K n z p` of small diameters by intersecting with the ball -- `closed_ball (d p) (u n / 3)`. let K : ℕ → T → ℕ → set E := λ n z p, closure (M n z) ∩ closed_ball (d p) (u n / 3), -- on the sets `K n z p`, the map `f` is well approximated by `f' z` by design. have K_approx : ∀ n (z : T) p, approximates_linear_on f (f' z) (s ∩ K n z p) (r (f' z)), { assume n z p x hx y hy, have yM : y ∈ M n z := closure_M_subset _ _ ⟨hy.1, hy.2.1⟩, refine yM.2 _ ⟨hx.1, _⟩, calc dist x y ≤ dist x (d p) + dist y (d p) : dist_triangle_right _ _ _ ... ≤ u n / 3 + u n / 3 : add_le_add hx.2.2 hy.2.2 ... < u n : by linarith [u_pos n] }, -- the sets `K n z p` are also closed, again by design. have K_closed : ∀ n (z : T) p, is_closed (K n z p) := λ n z p, is_closed_closure.inter is_closed_ball, -- reindex the sets `K n z p`, to let them only depend on an integer parameter `q`. obtain ⟨F, hF⟩ : ∃ F : ℕ → ℕ × T × ℕ, function.surjective F, { haveI : encodable T := T_count.to_encodable, haveI : nonempty T, { unfreezingI { rcases eq_empty_or_nonempty T with rfl|hT }, { rcases hs with ⟨x, xs⟩, rcases s_subset x xs with ⟨n, z, hnz⟩, exact false.elim z.2 }, { exact hT.coe_sort } }, inhabit (ℕ × T × ℕ), exact ⟨_, encodable.surjective_decode_iget _⟩ }, -- these sets `t q = K n z p` will do refine ⟨λ q, K (F q).1 (F q).2.1 (F q).2.2, λ q, f' (F q).2.1, λ n, K_closed _ _ _, λ x xs, _, λ q, K_approx _ _ _, λ h's q, ⟨(F q).2.1, (F q).2.1.1.2, rfl⟩⟩, -- the only fact that needs further checking is that they cover `s`. -- we already know that any point `x ∈ s` belongs to a set `M n z`. obtain ⟨n, z, hnz⟩ : ∃ (n : ℕ) (z : T), x ∈ M n z := s_subset x xs, -- by density, it also belongs to a ball `closed_ball (d p) (u n / 3)`. obtain ⟨p, hp⟩ : ∃ (p : ℕ), x ∈ closed_ball (d p) (u n / 3), { have : set.nonempty (ball x (u n / 3)), { simp only [nonempty_ball], linarith [u_pos n] }, obtain ⟨p, hp⟩ : ∃ (p : ℕ), d p ∈ ball x (u n / 3) := hd.exists_mem_open is_open_ball this, exact ⟨p, (mem_ball'.1 hp).le⟩ }, -- choose `q` for which `t q = K n z p`. obtain ⟨q, hq⟩ : ∃ q, F q = (n, z, p) := hF _, -- then `x` belongs to `t q`. apply mem_Union.2 ⟨q, _⟩, simp only [hq, subset_closure hnz, hp, mem_inter_iff, and_self], end variables [measurable_space E] [borel_space E] (μ : measure E) [is_add_haar_measure μ] /-- Assume that a function `f` has a derivative at every point of a set `s`. Then one may partition `s` into countably many disjoint relatively measurable sets (i.e., intersections of `s` with measurable sets `t n`) on which `f` is well approximated by linear maps `A n`. -/ lemma exists_partition_approximates_linear_on_of_has_fderiv_within_at [second_countable_topology F] (f : E → F) (s : set E) (f' : E → E →L[ℝ] F) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (r : (E →L[ℝ] F) → ℝ≥0) (rpos : ∀ A, r A ≠ 0) : ∃ (t : ℕ → set E) (A : ℕ → (E →L[ℝ] F)), pairwise (disjoint on t) ∧ (∀ n, measurable_set (t n)) ∧ (s ⊆ ⋃ n, t n) ∧ (∀ n, approximates_linear_on f (A n) (s ∩ t n) (r (A n))) ∧ (s.nonempty → ∀ n, ∃ y ∈ s, A n = f' y) := begin rcases exists_closed_cover_approximates_linear_on_of_has_fderiv_within_at f s f' hf' r rpos with ⟨t, A, t_closed, st, t_approx, ht⟩, refine ⟨disjointed t, A, disjoint_disjointed _, measurable_set.disjointed (λ n, (t_closed n).measurable_set), _, _, ht⟩, { rw Union_disjointed, exact st }, { assume n, exact (t_approx n).mono_set (inter_subset_inter_right _ (disjointed_subset _ _)) }, end namespace measure_theory /-! ### Local lemmas We check that a function which is well enough approximated by a linear map expands the volume essentially like this linear map, and that its derivative (if it exists) is almost everywhere close to the approximating linear map. -/ /-- Let `f` be a function which is sufficiently close (in the Lipschitz sense) to a given linear map `A`. Then it expands the volume of any set by at most `m` for any `m > det A`. -/ lemma add_haar_image_le_mul_of_det_lt (A : E →L[ℝ] E) {m : ℝ≥0} (hm : ennreal.of_real (|A.det|) < m) : ∀ᶠ δ in 𝓝[>] (0 : ℝ≥0), ∀ (s : set E) (f : E → E) (hf : approximates_linear_on f A s δ), μ (f '' s) ≤ m * μ s := begin apply nhds_within_le_nhds, let d := ennreal.of_real (|A.det|), -- construct a small neighborhood of `A '' (closed_ball 0 1)` with measure comparable to -- the determinant of `A`. obtain ⟨ε, hε, εpos⟩ : ∃ (ε : ℝ), μ (closed_ball 0 ε + A '' (closed_ball 0 1)) < m * μ (closed_ball 0 1) ∧ 0 < ε, { have HC : is_compact (A '' closed_ball 0 1) := (proper_space.is_compact_closed_ball _ _).image A.continuous, have L0 : tendsto (λ ε, μ (cthickening ε (A '' (closed_ball 0 1)))) (𝓝[>] 0) (𝓝 (μ (A '' (closed_ball 0 1)))), { apply tendsto.mono_left _ nhds_within_le_nhds, exact tendsto_measure_cthickening_of_is_compact HC }, have L1 : tendsto (λ ε, μ (closed_ball 0 ε + A '' (closed_ball 0 1))) (𝓝[>] 0) (𝓝 (μ (A '' (closed_ball 0 1)))), { apply L0.congr' _, filter_upwards [self_mem_nhds_within] with r hr, rw [←HC.add_closed_ball_zero (le_of_lt hr), add_comm] }, have L2 : tendsto (λ ε, μ (closed_ball 0 ε + A '' (closed_ball 0 1))) (𝓝[>] 0) (𝓝 (d * μ (closed_ball 0 1))), { convert L1, exact (add_haar_image_continuous_linear_map _ _ _).symm }, have I : d * μ (closed_ball 0 1) < m * μ (closed_ball 0 1) := (ennreal.mul_lt_mul_right ((measure_closed_ball_pos μ _ zero_lt_one).ne') measure_closed_ball_lt_top.ne).2 hm, have H : ∀ᶠ (b : ℝ) in 𝓝[>] 0, μ (closed_ball 0 b + A '' closed_ball 0 1) < m * μ (closed_ball 0 1) := (tendsto_order.1 L2).2 _ I, exact (H.and self_mem_nhds_within).exists }, have : Iio (⟨ε, εpos.le⟩ : ℝ≥0) ∈ 𝓝 (0 : ℝ≥0), { apply Iio_mem_nhds, exact εpos }, filter_upwards [this], -- fix a function `f` which is close enough to `A`. assume δ hδ s f hf, -- This function expands the volume of any ball by at most `m` have I : ∀ x r, x ∈ s → 0 ≤ r → μ (f '' (s ∩ closed_ball x r)) ≤ m * μ (closed_ball x r), { assume x r xs r0, have K : f '' (s ∩ closed_ball x r) ⊆ A '' (closed_ball 0 r) + closed_ball (f x) (ε * r), { rintros y ⟨z, ⟨zs, zr⟩, rfl⟩, apply set.mem_add.2 ⟨A (z - x), f z - f x - A (z - x) + f x, _, _, _⟩, { apply mem_image_of_mem, simpa only [dist_eq_norm, mem_closed_ball, mem_closed_ball_zero_iff] using zr }, { rw [mem_closed_ball_iff_norm, add_sub_cancel], calc ‖f z - f x - A (z - x)‖ ≤ δ * ‖z - x‖ : hf _ zs _ xs ... ≤ ε * r : mul_le_mul (le_of_lt hδ) (mem_closed_ball_iff_norm.1 zr) (norm_nonneg _) εpos.le }, { simp only [map_sub, pi.sub_apply], abel } }, have : A '' (closed_ball 0 r) + closed_ball (f x) (ε * r) = {f x} + r • (A '' (closed_ball 0 1) + closed_ball 0 ε), by rw [smul_add, ← add_assoc, add_comm ({f x}), add_assoc, smul_closed_ball _ _ εpos.le, smul_zero, singleton_add_closed_ball_zero, ← image_smul_set ℝ E E A, smul_closed_ball _ _ zero_le_one, smul_zero, real.norm_eq_abs, abs_of_nonneg r0, mul_one, mul_comm], rw this at K, calc μ (f '' (s ∩ closed_ball x r)) ≤ μ ({f x} + r • (A '' (closed_ball 0 1) + closed_ball 0 ε)) : measure_mono K ... = ennreal.of_real (r ^ finrank ℝ E) * μ (A '' closed_ball 0 1 + closed_ball 0 ε) : by simp only [abs_of_nonneg r0, add_haar_smul, image_add_left, abs_pow, singleton_add, measure_preimage_add] ... ≤ ennreal.of_real (r ^ finrank ℝ E) * (m * μ (closed_ball 0 1)) : by { rw add_comm, exact mul_le_mul_left' hε.le _ } ... = m * μ (closed_ball x r) : by { simp only [add_haar_closed_ball' _ _ r0], ring } }, -- covering `s` by closed balls with total measure very close to `μ s`, one deduces that the -- measure of `f '' s` is at most `m * (μ s + a)` for any positive `a`. have J : ∀ᶠ a in 𝓝[>] (0 : ℝ≥0∞), μ (f '' s) ≤ m * (μ s + a), { filter_upwards [self_mem_nhds_within] with a ha, change 0 < a at ha, obtain ⟨t, r, t_count, ts, rpos, st, μt⟩ : ∃ (t : set E) (r : E → ℝ), t.countable ∧ t ⊆ s ∧ (∀ (x : E), x ∈ t → 0 < r x) ∧ (s ⊆ ⋃ (x ∈ t), closed_ball x (r x)) ∧ ∑' (x : ↥t), μ (closed_ball ↑x (r ↑x)) ≤ μ s + a := besicovitch.exists_closed_ball_covering_tsum_measure_le μ ha.ne' (λ x, Ioi 0) s (λ x xs δ δpos, ⟨δ/2, by simp [half_pos δpos, half_lt_self δpos]⟩), haveI : encodable t := t_count.to_encodable, calc μ (f '' s) ≤ μ (⋃ (x : t), f '' (s ∩ closed_ball x (r x))) : begin rw bUnion_eq_Union at st, apply measure_mono, rw [← image_Union, ← inter_Union], exact image_subset _ (subset_inter (subset.refl _) st) end ... ≤ ∑' (x : t), μ (f '' (s ∩ closed_ball x (r x))) : measure_Union_le _ ... ≤ ∑' (x : t), m * μ (closed_ball x (r x)) : ennreal.tsum_le_tsum (λ x, I x (r x) (ts x.2) (rpos x x.2).le) ... ≤ m * (μ s + a) : by { rw ennreal.tsum_mul_left, exact mul_le_mul_left' μt _ } }, -- taking the limit in `a`, one obtains the conclusion have L : tendsto (λ a, (m : ℝ≥0∞) * (μ s + a)) (𝓝[>] 0) (𝓝 (m * (μ s + 0))), { apply tendsto.mono_left _ nhds_within_le_nhds, apply ennreal.tendsto.const_mul (tendsto_const_nhds.add tendsto_id), simp only [ennreal.coe_ne_top, ne.def, or_true, not_false_iff] }, rw add_zero at L, exact ge_of_tendsto L J, end /-- Let `f` be a function which is sufficiently close (in the Lipschitz sense) to a given linear map `A`. Then it expands the volume of any set by at least `m` for any `m < det A`. -/ lemma mul_le_add_haar_image_of_lt_det (A : E →L[ℝ] E) {m : ℝ≥0} (hm : (m : ℝ≥0∞) < ennreal.of_real (|A.det|)) : ∀ᶠ δ in 𝓝[>] (0 : ℝ≥0), ∀ (s : set E) (f : E → E) (hf : approximates_linear_on f A s δ), (m : ℝ≥0∞) * μ s ≤ μ (f '' s) := begin apply nhds_within_le_nhds, -- The assumption `hm` implies that `A` is invertible. If `f` is close enough to `A`, it is also -- invertible. One can then pass to the inverses, and deduce the estimate from -- `add_haar_image_le_mul_of_det_lt` applied to `f⁻¹` and `A⁻¹`. -- exclude first the trivial case where `m = 0`. rcases eq_or_lt_of_le (zero_le m) with rfl|mpos, { apply eventually_of_forall, simp only [forall_const, zero_mul, implies_true_iff, zero_le, ennreal.coe_zero] }, have hA : A.det ≠ 0, { assume h, simpa only [h, ennreal.not_lt_zero, ennreal.of_real_zero, abs_zero] using hm }, -- let `B` be the continuous linear equiv version of `A`. let B := A.to_continuous_linear_equiv_of_det_ne_zero hA, -- the determinant of `B.symm` is bounded by `m⁻¹` have I : ennreal.of_real (|(B.symm : E →L[ℝ] E).det|) < (m⁻¹ : ℝ≥0), { simp only [ennreal.of_real, abs_inv, real.to_nnreal_inv, continuous_linear_equiv.det_coe_symm, continuous_linear_map.coe_to_continuous_linear_equiv_of_det_ne_zero, ennreal.coe_lt_coe] at ⊢ hm, exact nnreal.inv_lt_inv mpos.ne' hm }, -- therefore, we may apply `add_haar_image_le_mul_of_det_lt` to `B.symm` and `m⁻¹`. obtain ⟨δ₀, δ₀pos, hδ₀⟩ : ∃ (δ : ℝ≥0), 0 < δ ∧ ∀ (t : set E) (g : E → E), approximates_linear_on g (B.symm : E →L[ℝ] E) t δ → μ (g '' t) ≤ ↑m⁻¹ * μ t, { have : ∀ᶠ (δ : ℝ≥0) in 𝓝[>] 0, ∀ (t : set E) (g : E → E), approximates_linear_on g (B.symm : E →L[ℝ] E) t δ → μ (g '' t) ≤ ↑m⁻¹ * μ t := add_haar_image_le_mul_of_det_lt μ B.symm I, rcases (this.and self_mem_nhds_within).exists with ⟨δ₀, h, h'⟩, exact ⟨δ₀, h', h⟩, }, -- record smallness conditions for `δ` that will be needed to apply `hδ₀` below. have L1 : ∀ᶠ δ in 𝓝 (0 : ℝ≥0), subsingleton E ∨ δ < ‖(B.symm : E →L[ℝ] E)‖₊⁻¹, { by_cases (subsingleton E), { simp only [h, true_or, eventually_const] }, simp only [h, false_or], apply Iio_mem_nhds, simpa only [h, false_or, inv_pos] using B.subsingleton_or_nnnorm_symm_pos }, have L2 : ∀ᶠ δ in 𝓝 (0 : ℝ≥0), ‖(B.symm : E →L[ℝ] E)‖₊ * (‖(B.symm : E →L[ℝ] E)‖₊⁻¹ - δ)⁻¹ * δ < δ₀, { have : tendsto (λ δ, ‖(B.symm : E →L[ℝ] E)‖₊ * (‖(B.symm : E →L[ℝ] E)‖₊⁻¹ - δ)⁻¹ * δ) (𝓝 0) (𝓝 (‖(B.symm : E →L[ℝ] E)‖₊ * (‖(B.symm : E →L[ℝ] E)‖₊⁻¹ - 0)⁻¹ * 0)), { rcases eq_or_ne (‖(B.symm : E →L[ℝ] E)‖₊) 0 with H|H, { simpa only [H, zero_mul] using tendsto_const_nhds }, refine tendsto.mul (tendsto_const_nhds.mul _) tendsto_id, refine (tendsto.sub tendsto_const_nhds tendsto_id).inv₀ _, simpa only [tsub_zero, inv_eq_zero, ne.def] using H }, simp only [mul_zero] at this, exact (tendsto_order.1 this).2 δ₀ δ₀pos }, -- let `δ` be small enough, and `f` approximated by `B` up to `δ`. filter_upwards [L1, L2], assume δ h1δ h2δ s f hf, have hf' : approximates_linear_on f (B : E →L[ℝ] E) s δ, by { convert hf, exact A.coe_to_continuous_linear_equiv_of_det_ne_zero _ }, let F := hf'.to_local_equiv h1δ, -- the condition to be checked can be reformulated in terms of the inverse maps suffices H : μ ((F.symm) '' F.target) ≤ (m⁻¹ : ℝ≥0) * μ F.target, { change (m : ℝ≥0∞) * μ (F.source) ≤ μ (F.target), rwa [← F.symm_image_target_eq_source, mul_comm, ← ennreal.le_div_iff_mul_le, div_eq_mul_inv, mul_comm, ← ennreal.coe_inv (mpos.ne')], { apply or.inl, simpa only [ennreal.coe_eq_zero, ne.def] using mpos.ne'}, { simp only [ennreal.coe_ne_top, true_or, ne.def, not_false_iff] } }, -- as `f⁻¹` is well approximated by `B⁻¹`, the conclusion follows from `hδ₀` -- and our choice of `δ`. exact hδ₀ _ _ ((hf'.to_inv h1δ).mono_num h2δ.le), end /-- If a differentiable function `f` is approximated by a linear map `A` on a set `s`, up to `δ`, then at almost every `x` in `s` one has `‖f' x - A‖ ≤ δ`. -/ lemma _root_.approximates_linear_on.norm_fderiv_sub_le {A : E →L[ℝ] E} {δ : ℝ≥0} (hf : approximates_linear_on f A s δ) (hs : measurable_set s) (f' : E → E →L[ℝ] E) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) : ∀ᵐ x ∂(μ.restrict s), ‖f' x - A‖₊ ≤ δ := begin /- The conclusion will hold at the Lebesgue density points of `s` (which have full measure). At such a point `x`, for any `z` and any `ε > 0` one has for small `r` that `{x} + r • closed_ball z ε` intersects `s`. At a point `y` in the intersection, `f y - f x` is close both to `f' x (r z)` (by differentiability) and to `A (r z)` (by linear approximation), so these two quantities are close, i.e., `(f' x - A) z` is small. -/ filter_upwards [besicovitch.ae_tendsto_measure_inter_div μ s, ae_restrict_mem hs], -- start from a Lebesgue density point `x`, belonging to `s`. assume x hx xs, -- consider an arbitrary vector `z`. apply continuous_linear_map.op_norm_le_bound _ δ.2 (λ z, _), -- to show that `‖(f' x - A) z‖ ≤ δ ‖z‖`, it suffices to do it up to some error that vanishes -- asymptotically in terms of `ε > 0`. suffices H : ∀ ε, 0 < ε → ‖(f' x - A) z‖ ≤ (δ + ε) * (‖z‖ + ε) + ‖(f' x - A)‖ * ε, { have : tendsto (λ (ε : ℝ), ((δ : ℝ) + ε) * (‖z‖ + ε) + ‖(f' x - A)‖ * ε) (𝓝[>] 0) (𝓝 ((δ + 0) * (‖z‖ + 0) + ‖(f' x - A)‖ * 0)) := tendsto.mono_left (continuous.tendsto (by continuity) 0) nhds_within_le_nhds, simp only [add_zero, mul_zero] at this, apply le_of_tendsto_of_tendsto tendsto_const_nhds this, filter_upwards [self_mem_nhds_within], exact H }, -- fix a positive `ε`. assume ε εpos, -- for small enough `r`, the rescaled ball `r • closed_ball z ε` intersects `s`, as `x` is a -- density point have B₁ : ∀ᶠ r in 𝓝[>] (0 : ℝ), (s ∩ ({x} + r • closed_ball z ε)).nonempty := eventually_nonempty_inter_smul_of_density_one μ s x hx _ measurable_set_closed_ball (measure_closed_ball_pos μ z εpos).ne', obtain ⟨ρ, ρpos, hρ⟩ : ∃ ρ > 0, ball x ρ ∩ s ⊆ {y : E | ‖f y - f x - (f' x) (y - x)‖ ≤ ε * ‖y - x‖} := mem_nhds_within_iff.1 (is_o.def (hf' x xs) εpos), -- for small enough `r`, the rescaled ball `r • closed_ball z ε` is included in the set where -- `f y - f x` is well approximated by `f' x (y - x)`. have B₂ : ∀ᶠ r in 𝓝[>] (0 : ℝ), {x} + r • closed_ball z ε ⊆ ball x ρ := nhds_within_le_nhds (eventually_singleton_add_smul_subset bounded_closed_ball (ball_mem_nhds x ρpos)), -- fix a small positive `r` satisfying the above properties, as well as a corresponding `y`. obtain ⟨r, ⟨y, ⟨ys, hy⟩⟩, rρ, rpos⟩ : ∃ (r : ℝ), (s ∩ ({x} + r • closed_ball z ε)).nonempty ∧ {x} + r • closed_ball z ε ⊆ ball x ρ ∧ 0 < r := (B₁.and (B₂.and self_mem_nhds_within)).exists, -- write `y = x + r a` with `a ∈ closed_ball z ε`. obtain ⟨a, az, ya⟩ : ∃ a, a ∈ closed_ball z ε ∧ y = x + r • a, { simp only [mem_smul_set, image_add_left, mem_preimage, singleton_add] at hy, rcases hy with ⟨a, az, ha⟩, exact ⟨a, az, by simp only [ha, add_neg_cancel_left]⟩ }, have norm_a : ‖a‖ ≤ ‖z‖ + ε := calc ‖a‖ = ‖z + (a - z)‖ : by simp only [add_sub_cancel'_right] ... ≤ ‖z‖ + ‖a - z‖ : norm_add_le _ _ ... ≤ ‖z‖ + ε : add_le_add_left (mem_closed_ball_iff_norm.1 az) _, -- use the approximation properties to control `(f' x - A) a`, and then `(f' x - A) z` as `z` is -- close to `a`. have I : r * ‖(f' x - A) a‖ ≤ r * (δ + ε) * (‖z‖ + ε) := calc r * ‖(f' x - A) a‖ = ‖(f' x - A) (r • a)‖ : by simp only [continuous_linear_map.map_smul, norm_smul, real.norm_eq_abs, abs_of_nonneg rpos.le] ... = ‖(f y - f x - A (y - x)) - (f y - f x - (f' x) (y - x))‖ : begin congr' 1, simp only [ya, add_sub_cancel', sub_sub_sub_cancel_left, continuous_linear_map.coe_sub', eq_self_iff_true, sub_left_inj, pi.sub_apply, continuous_linear_map.map_smul, smul_sub], end ... ≤ ‖f y - f x - A (y - x)‖ + ‖f y - f x - (f' x) (y - x)‖ : norm_sub_le _ _ ... ≤ δ * ‖y - x‖ + ε * ‖y - x‖ : add_le_add (hf _ ys _ xs) (hρ ⟨rρ hy, ys⟩) ... = r * (δ + ε) * ‖a‖ : by { simp only [ya, add_sub_cancel', norm_smul, real.norm_eq_abs, abs_of_nonneg rpos.le], ring } ... ≤ r * (δ + ε) * (‖z‖ + ε) : mul_le_mul_of_nonneg_left norm_a (mul_nonneg rpos.le (add_nonneg δ.2 εpos.le)), show ‖(f' x - A) z‖ ≤ (δ + ε) * (‖z‖ + ε) + ‖(f' x - A)‖ * ε, from calc ‖(f' x - A) z‖ = ‖(f' x - A) a + (f' x - A) (z - a)‖ : begin congr' 1, simp only [continuous_linear_map.coe_sub', map_sub, pi.sub_apply], abel end ... ≤ ‖(f' x - A) a‖ + ‖(f' x - A) (z - a)‖ : norm_add_le _ _ ... ≤ (δ + ε) * (‖z‖ + ε) + ‖f' x - A‖ * ‖z - a‖ : begin apply add_le_add, { rw mul_assoc at I, exact (mul_le_mul_left rpos).1 I }, { apply continuous_linear_map.le_op_norm } end ... ≤ (δ + ε) * (‖z‖ + ε) + ‖f' x - A‖ * ε : add_le_add le_rfl (mul_le_mul_of_nonneg_left (mem_closed_ball_iff_norm'.1 az) (norm_nonneg _)), end /-! ### Measure zero of the image, over non-measurable sets If a set has measure `0`, then its image under a differentiable map has measure zero. This doesn't require the set to be measurable. In the same way, if `f` is differentiable on a set `s` with non-invertible derivative everywhere, then `f '' s` has measure `0`, again without measurability assumptions. -/ /-- A differentiable function maps sets of measure zero to sets of measure zero. -/ lemma add_haar_image_eq_zero_of_differentiable_on_of_add_haar_eq_zero (hf : differentiable_on ℝ f s) (hs : μ s = 0) : μ (f '' s) = 0 := begin refine le_antisymm _ (zero_le _), have : ∀ (A : E →L[ℝ] E), ∃ (δ : ℝ≥0), 0 < δ ∧ ∀ (t : set E) (hf : approximates_linear_on f A t δ), μ (f '' t) ≤ (real.to_nnreal (|A.det|) + 1 : ℝ≥0) * μ t, { assume A, let m : ℝ≥0 := real.to_nnreal ((|A.det|)) + 1, have I : ennreal.of_real (|A.det|) < m, by simp only [ennreal.of_real, m, lt_add_iff_pos_right, zero_lt_one, ennreal.coe_lt_coe], rcases ((add_haar_image_le_mul_of_det_lt μ A I).and self_mem_nhds_within).exists with ⟨δ, h, h'⟩, exact ⟨δ, h', λ t ht, h t f ht⟩ }, choose δ hδ using this, obtain ⟨t, A, t_disj, t_meas, t_cover, ht, -⟩ : ∃ (t : ℕ → set E) (A : ℕ → (E →L[ℝ] E)), pairwise (disjoint on t) ∧ (∀ (n : ℕ), measurable_set (t n)) ∧ (s ⊆ ⋃ (n : ℕ), t n) ∧ (∀ (n : ℕ), approximates_linear_on f (A n) (s ∩ t n) (δ (A n))) ∧ (s.nonempty → ∀ n, ∃ y ∈ s, A n = fderiv_within ℝ f s y) := exists_partition_approximates_linear_on_of_has_fderiv_within_at f s (fderiv_within ℝ f s) (λ x xs, (hf x xs).has_fderiv_within_at) δ (λ A, (hδ A).1.ne'), calc μ (f '' s) ≤ μ (⋃ n, f '' (s ∩ t n)) : begin apply measure_mono, rw [← image_Union, ← inter_Union], exact image_subset f (subset_inter subset.rfl t_cover) end ... ≤ ∑' n, μ (f '' (s ∩ t n)) : measure_Union_le _ ... ≤ ∑' n, (real.to_nnreal (|(A n).det|) + 1 : ℝ≥0) * μ (s ∩ t n) : begin apply ennreal.tsum_le_tsum (λ n, _), apply (hδ (A n)).2, exact ht n, end ... ≤ ∑' n, (real.to_nnreal (|(A n).det|) + 1 : ℝ≥0) * 0 : begin refine ennreal.tsum_le_tsum (λ n, mul_le_mul_left' _ _), exact le_trans (measure_mono (inter_subset_left _ _)) (le_of_eq hs), end ... = 0 : by simp only [tsum_zero, mul_zero] end /-- A version of Sard lemma in fixed dimension: given a differentiable function from `E` to `E` and a set where the differential is not invertible, then the image of this set has zero measure. Here, we give an auxiliary statement towards this result. -/ lemma add_haar_image_eq_zero_of_det_fderiv_within_eq_zero_aux (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (R : ℝ) (hs : s ⊆ closed_ball 0 R) (ε : ℝ≥0) (εpos : 0 < ε) (h'f' : ∀ x ∈ s, (f' x).det = 0) : μ (f '' s) ≤ ε * μ (closed_ball 0 R) := begin rcases eq_empty_or_nonempty s with rfl|h's, { simp only [measure_empty, zero_le, image_empty] }, have : ∀ (A : E →L[ℝ] E), ∃ (δ : ℝ≥0), 0 < δ ∧ ∀ (t : set E) (hf : approximates_linear_on f A t δ), μ (f '' t) ≤ (real.to_nnreal (|A.det|) + ε : ℝ≥0) * μ t, { assume A, let m : ℝ≥0 := real.to_nnreal (|A.det|) + ε, have I : ennreal.of_real (|A.det|) < m, by simp only [ennreal.of_real, m, lt_add_iff_pos_right, εpos, ennreal.coe_lt_coe], rcases ((add_haar_image_le_mul_of_det_lt μ A I).and self_mem_nhds_within).exists with ⟨δ, h, h'⟩, exact ⟨δ, h', λ t ht, h t f ht⟩ }, choose δ hδ using this, obtain ⟨t, A, t_disj, t_meas, t_cover, ht, Af'⟩ : ∃ (t : ℕ → set E) (A : ℕ → (E →L[ℝ] E)), pairwise (disjoint on t) ∧ (∀ (n : ℕ), measurable_set (t n)) ∧ (s ⊆ ⋃ (n : ℕ), t n) ∧ (∀ (n : ℕ), approximates_linear_on f (A n) (s ∩ t n) (δ (A n))) ∧ (s.nonempty → ∀ n, ∃ y ∈ s, A n = f' y) := exists_partition_approximates_linear_on_of_has_fderiv_within_at f s f' hf' δ (λ A, (hδ A).1.ne'), calc μ (f '' s) ≤ μ (⋃ n, f '' (s ∩ t n)) : begin apply measure_mono, rw [← image_Union, ← inter_Union], exact image_subset f (subset_inter subset.rfl t_cover) end ... ≤ ∑' n, μ (f '' (s ∩ t n)) : measure_Union_le _ ... ≤ ∑' n, (real.to_nnreal (|(A n).det|) + ε : ℝ≥0) * μ (s ∩ t n) : begin apply ennreal.tsum_le_tsum (λ n, _), apply (hδ (A n)).2, exact ht n, end ... = ∑' n, ε * μ (s ∩ t n) : begin congr' with n, rcases Af' h's n with ⟨y, ys, hy⟩, simp only [hy, h'f' y ys, real.to_nnreal_zero, abs_zero, zero_add] end ... ≤ ε * ∑' n, μ (closed_ball 0 R ∩ t n) : begin rw ennreal.tsum_mul_left, refine mul_le_mul_left' (ennreal.tsum_le_tsum (λ n, measure_mono _)) _, exact inter_subset_inter_left _ hs, end ... = ε * μ (⋃ n, closed_ball 0 R ∩ t n) : begin rw measure_Union, { exact pairwise_disjoint.mono t_disj (λ n, inter_subset_right _ _) }, { assume n, exact measurable_set_closed_ball.inter (t_meas n) } end ... ≤ ε * μ (closed_ball 0 R) : begin rw ← inter_Union, exact mul_le_mul_left' (measure_mono (inter_subset_left _ _)) _, end end /-- A version of Sard lemma in fixed dimension: given a differentiable function from `E` to `E` and a set where the differential is not invertible, then the image of this set has zero measure. -/ lemma add_haar_image_eq_zero_of_det_fderiv_within_eq_zero (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (h'f' : ∀ x ∈ s, (f' x).det = 0) : μ (f '' s) = 0 := begin suffices H : ∀ R, μ (f '' (s ∩ closed_ball 0 R)) = 0, { apply le_antisymm _ (zero_le _), rw ← Union_inter_closed_ball_nat s 0, calc μ (f '' ⋃ (n : ℕ), s ∩ closed_ball 0 n) ≤ ∑' (n : ℕ), μ (f '' (s ∩ closed_ball 0 n)) : by { rw image_Union, exact measure_Union_le _ } ... ≤ 0 : by simp only [H, tsum_zero, nonpos_iff_eq_zero] }, assume R, have A : ∀ (ε : ℝ≥0) (εpos : 0 < ε), μ (f '' (s ∩ closed_ball 0 R)) ≤ ε * μ (closed_ball 0 R) := λ ε εpos, add_haar_image_eq_zero_of_det_fderiv_within_eq_zero_aux μ (λ x hx, (hf' x hx.1).mono (inter_subset_left _ _)) R (inter_subset_right _ _) ε εpos (λ x hx, h'f' x hx.1), have B : tendsto (λ (ε : ℝ≥0), (ε : ℝ≥0∞) * μ (closed_ball 0 R)) (𝓝[>] 0) (𝓝 0), { have : tendsto (λ (ε : ℝ≥0), (ε : ℝ≥0∞) * μ (closed_ball 0 R)) (𝓝 0) (𝓝 (((0 : ℝ≥0) : ℝ≥0∞) * μ (closed_ball 0 R))) := ennreal.tendsto.mul_const (ennreal.tendsto_coe.2 tendsto_id) (or.inr ((measure_closed_ball_lt_top).ne)), simp only [zero_mul, ennreal.coe_zero] at this, exact tendsto.mono_left this nhds_within_le_nhds }, apply le_antisymm _ (zero_le _), apply ge_of_tendsto B, filter_upwards [self_mem_nhds_within], exact A, end /-! ### Weak measurability statements We show that the derivative of a function on a set is almost everywhere measurable, and that the image `f '' s` is measurable if `f` is injective on `s`. The latter statement follows from the Lusin-Souslin theorem. -/ /-- The derivative of a function on a measurable set is almost everywhere measurable on this set with respect to Lebesgue measure. Note that, in general, it is not genuinely measurable there, as `f'` is not unique (but only on a set of measure `0`, as the argument shows). -/ lemma ae_measurable_fderiv_within (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) : ae_measurable f' (μ.restrict s) := begin /- It suffices to show that `f'` can be uniformly approximated by a measurable function. Fix `ε > 0`. Thanks to `exists_partition_approximates_linear_on_of_has_fderiv_within_at`, one can find a countable measurable partition of `s` into sets `s ∩ t n` on which `f` is well approximated by linear maps `A n`. On almost all of `s ∩ t n`, it follows from `approximates_linear_on.norm_fderiv_sub_le` that `f'` is uniformly approximated by `A n`, which gives the conclusion. -/ -- fix a precision `ε` refine ae_measurable_of_unif_approx (λ ε εpos, _), let δ : ℝ≥0 := ⟨ε, le_of_lt εpos⟩, have δpos : 0 < δ := εpos, -- partition `s` into sets `s ∩ t n` on which `f` is approximated by linear maps `A n`. obtain ⟨t, A, t_disj, t_meas, t_cover, ht, Af'⟩ : ∃ (t : ℕ → set E) (A : ℕ → (E →L[ℝ] E)), pairwise (disjoint on t) ∧ (∀ (n : ℕ), measurable_set (t n)) ∧ (s ⊆ ⋃ (n : ℕ), t n) ∧ (∀ (n : ℕ), approximates_linear_on f (A n) (s ∩ t n) δ) ∧ (s.nonempty → ∀ n, ∃ y ∈ s, A n = f' y) := exists_partition_approximates_linear_on_of_has_fderiv_within_at f s f' hf' (λ A, δ) (λ A, δpos.ne'), -- define a measurable function `g` which coincides with `A n` on `t n`. obtain ⟨g, g_meas, hg⟩ : ∃ g : E → (E →L[ℝ] E), measurable g ∧ ∀ (n : ℕ) (x : E), x ∈ t n → g x = A n := exists_measurable_piecewise_nat t t_meas t_disj (λ n x, A n) (λ n, measurable_const), refine ⟨g, g_meas.ae_measurable, _⟩, -- reduce to checking that `f'` and `g` are close on almost all of `s ∩ t n`, for all `n`. suffices H : ∀ᵐ (x : E) ∂(sum (λ n, μ.restrict (s ∩ t n))), dist (g x) (f' x) ≤ ε, { have : μ.restrict s ≤ sum (λ n, μ.restrict (s ∩ t n)), { have : s = ⋃ n, s ∩ t n, { rw ← inter_Union, exact subset.antisymm (subset_inter subset.rfl t_cover) (inter_subset_left _ _) }, conv_lhs { rw this }, exact restrict_Union_le }, exact ae_mono this H }, -- fix such an `n`. refine ae_sum_iff.2 (λ n, _), -- on almost all `s ∩ t n`, `f' x` is close to `A n` thanks to -- `approximates_linear_on.norm_fderiv_sub_le`. have E₁ : ∀ᵐ (x : E) ∂μ.restrict (s ∩ t n), ‖f' x - A n‖₊ ≤ δ := (ht n).norm_fderiv_sub_le μ (hs.inter (t_meas n)) f' (λ x hx, (hf' x hx.1).mono (inter_subset_left _ _)), -- moreover, `g x` is equal to `A n` there. have E₂ : ∀ᵐ (x : E) ∂μ.restrict (s ∩ t n), g x = A n, { suffices H : ∀ᵐ (x : E) ∂μ.restrict (t n), g x = A n, from ae_mono (restrict_mono (inter_subset_right _ _) le_rfl) H, filter_upwards [ae_restrict_mem (t_meas n)], exact hg n }, -- putting these two properties together gives the conclusion. filter_upwards [E₁, E₂] with x hx1 hx2, rw ← nndist_eq_nnnorm at hx1, rw [hx2, dist_comm], exact hx1, end lemma ae_measurable_of_real_abs_det_fderiv_within (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) : ae_measurable (λ x, ennreal.of_real (|(f' x).det|)) (μ.restrict s) := begin apply ennreal.measurable_of_real.comp_ae_measurable, refine continuous_abs.measurable.comp_ae_measurable _, refine continuous_linear_map.continuous_det.measurable.comp_ae_measurable _, exact ae_measurable_fderiv_within μ hs hf' end lemma ae_measurable_to_nnreal_abs_det_fderiv_within (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) : ae_measurable (λ x, |(f' x).det|.to_nnreal) (μ.restrict s) := begin apply measurable_real_to_nnreal.comp_ae_measurable, refine continuous_abs.measurable.comp_ae_measurable _, refine continuous_linear_map.continuous_det.measurable.comp_ae_measurable _, exact ae_measurable_fderiv_within μ hs hf' end /-- If a function is differentiable and injective on a measurable set, then the image is measurable.-/ lemma measurable_image_of_fderiv_within (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hf : inj_on f s) : measurable_set (f '' s) := begin have : differentiable_on ℝ f s := λ x hx, (hf' x hx).differentiable_within_at, exact hs.image_of_continuous_on_inj_on (differentiable_on.continuous_on this) hf, end /-- If a function is differentiable and injective on a measurable set `s`, then its restriction to `s` is a measurable embedding. -/ lemma measurable_embedding_of_fderiv_within (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hf : inj_on f s) : measurable_embedding (s.restrict f) := begin have : differentiable_on ℝ f s := λ x hx, (hf' x hx).differentiable_within_at, exact this.continuous_on.measurable_embedding hs hf end /-! ### Proving the estimate for the measure of the image We show the formula `∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ = μ (f '' s)`, in `lintegral_abs_det_fderiv_eq_add_haar_image`. For this, we show both inequalities in both directions, first up to controlled errors and then letting these errors tend to `0`. -/ lemma add_haar_image_le_lintegral_abs_det_fderiv_aux1 (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) {ε : ℝ≥0} (εpos : 0 < ε) : μ (f '' s) ≤ ∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ + 2 * ε * μ s := begin /- To bound `μ (f '' s)`, we cover `s` by sets where `f` is well-approximated by linear maps `A n` (and where `f'` is almost everywhere close to `A n`), and then use that `f` expands the measure of such a set by at most `(A n).det + ε`. -/ have : ∀ (A : E →L[ℝ] E), ∃ (δ : ℝ≥0), 0 < δ ∧ (∀ (B : E →L[ℝ] E), ‖B - A‖ ≤ δ → |B.det - A.det| ≤ ε) ∧ ∀ (t : set E) (g : E → E) (hf : approximates_linear_on g A t δ), μ (g '' t) ≤ (ennreal.of_real (|A.det|) + ε) * μ t, { assume A, let m : ℝ≥0 := real.to_nnreal (|A.det|) + ε, have I : ennreal.of_real (|A.det|) < m, by simp only [ennreal.of_real, m, lt_add_iff_pos_right, εpos, ennreal.coe_lt_coe], rcases ((add_haar_image_le_mul_of_det_lt μ A I).and self_mem_nhds_within).exists with ⟨δ, h, δpos⟩, obtain ⟨δ', δ'pos, hδ'⟩ : ∃ (δ' : ℝ) (H : 0 < δ'), ∀ B, dist B A < δ' → dist B.det A.det < ↑ε := continuous_at_iff.1 continuous_linear_map.continuous_det.continuous_at ε εpos, let δ'' : ℝ≥0 := ⟨δ' / 2, (half_pos δ'pos).le⟩, refine ⟨min δ δ'', lt_min δpos (half_pos δ'pos), _, _⟩, { assume B hB, rw ← real.dist_eq, apply (hδ' B _).le, rw dist_eq_norm, calc ‖B - A‖ ≤ (min δ δ'' : ℝ≥0) : hB ... ≤ δ'' : by simp only [le_refl, nnreal.coe_min, min_le_iff, or_true] ... < δ' : half_lt_self δ'pos }, { assume t g htg, exact h t g (htg.mono_num (min_le_left _ _)) } }, choose δ hδ using this, obtain ⟨t, A, t_disj, t_meas, t_cover, ht, -⟩ : ∃ (t : ℕ → set E) (A : ℕ → (E →L[ℝ] E)), pairwise (disjoint on t) ∧ (∀ (n : ℕ), measurable_set (t n)) ∧ (s ⊆ ⋃ (n : ℕ), t n) ∧ (∀ (n : ℕ), approximates_linear_on f (A n) (s ∩ t n) (δ (A n))) ∧ (s.nonempty → ∀ n, ∃ y ∈ s, A n = f' y) := exists_partition_approximates_linear_on_of_has_fderiv_within_at f s f' hf' δ (λ A, (hδ A).1.ne'), calc μ (f '' s) ≤ μ (⋃ n, f '' (s ∩ t n)) : begin apply measure_mono, rw [← image_Union, ← inter_Union], exact image_subset f (subset_inter subset.rfl t_cover) end ... ≤ ∑' n, μ (f '' (s ∩ t n)) : measure_Union_le _ ... ≤ ∑' n, (ennreal.of_real (|(A n).det|) + ε) * μ (s ∩ t n) : begin apply ennreal.tsum_le_tsum (λ n, _), apply (hδ (A n)).2.2, exact ht n, end ... = ∑' n, ∫⁻ x in s ∩ t n, ennreal.of_real (|(A n).det|) + ε ∂μ : by simp only [lintegral_const, measurable_set.univ, measure.restrict_apply, univ_inter] ... ≤ ∑' n, ∫⁻ x in s ∩ t n, ennreal.of_real (|(f' x).det|) + 2 * ε ∂μ : begin apply ennreal.tsum_le_tsum (λ n, _), apply lintegral_mono_ae, filter_upwards [(ht n).norm_fderiv_sub_le μ (hs.inter (t_meas n)) f' (λ x hx, (hf' x hx.1).mono (inter_subset_left _ _))], assume x hx, have I : |(A n).det| ≤ |(f' x).det| + ε := calc |(A n).det| = |(f' x).det - ((f' x).det - (A n).det)| : by { congr' 1, abel } ... ≤ |(f' x).det| + |(f' x).det - (A n).det| : abs_sub _ _ ... ≤ |(f' x).det| + ε : add_le_add le_rfl ((hδ (A n)).2.1 _ hx), calc ennreal.of_real (|(A n).det|) + ε ≤ ennreal.of_real (|(f' x).det| + ε) + ε : add_le_add (ennreal.of_real_le_of_real I) le_rfl ... = ennreal.of_real (|(f' x).det|) + 2 * ε : by simp only [ennreal.of_real_add, abs_nonneg, two_mul, add_assoc, nnreal.zero_le_coe, ennreal.of_real_coe_nnreal], end ... = ∫⁻ x in ⋃ n, s ∩ t n, ennreal.of_real (|(f' x).det|) + 2 * ε ∂μ : begin have M : ∀ (n : ℕ), measurable_set (s ∩ t n) := λ n, hs.inter (t_meas n), rw lintegral_Union M, exact pairwise_disjoint.mono t_disj (λ n, inter_subset_right _ _), end ... = ∫⁻ x in s, ennreal.of_real (|(f' x).det|) + 2 * ε ∂μ : begin have : s = ⋃ n, s ∩ t n, { rw ← inter_Union, exact subset.antisymm (subset_inter subset.rfl t_cover) (inter_subset_left _ _) }, rw ← this, end ... = ∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ + 2 * ε * μ s : by simp only [lintegral_add_right' _ ae_measurable_const, set_lintegral_const] end lemma add_haar_image_le_lintegral_abs_det_fderiv_aux2 (hs : measurable_set s) (h's : μ s ≠ ∞) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) : μ (f '' s) ≤ ∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ := begin /- We just need to let the error tend to `0` in the previous lemma. -/ have : tendsto (λ (ε : ℝ≥0), ∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ + 2 * ε * μ s) (𝓝[>] 0) (𝓝 (∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ + 2 * (0 : ℝ≥0) * μ s)), { apply tendsto.mono_left _ nhds_within_le_nhds, refine tendsto_const_nhds.add _, refine ennreal.tendsto.mul_const _ (or.inr h's), exact ennreal.tendsto.const_mul (ennreal.tendsto_coe.2 tendsto_id) (or.inr ennreal.coe_ne_top) }, simp only [add_zero, zero_mul, mul_zero, ennreal.coe_zero] at this, apply ge_of_tendsto this, filter_upwards [self_mem_nhds_within], rintros ε (εpos : 0 < ε), exact add_haar_image_le_lintegral_abs_det_fderiv_aux1 μ hs hf' εpos, end lemma add_haar_image_le_lintegral_abs_det_fderiv (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) : μ (f '' s) ≤ ∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ := begin /- We already know the result for finite-measure sets. We cover `s` by finite-measure sets using `spanning_sets μ`, and apply the previous result to each of these parts. -/ let u := λ n, disjointed (spanning_sets μ) n, have u_meas : ∀ n, measurable_set (u n), { assume n, apply measurable_set.disjointed (λ i, _), exact measurable_spanning_sets μ i }, have A : s = ⋃ n, s ∩ u n, by rw [← inter_Union, Union_disjointed, Union_spanning_sets, inter_univ], calc μ (f '' s) ≤ ∑' n, μ (f '' (s ∩ u n)) : begin conv_lhs { rw [A, image_Union] }, exact measure_Union_le _, end ... ≤ ∑' n, ∫⁻ x in s ∩ u n, ennreal.of_real (|(f' x).det|) ∂μ : begin apply ennreal.tsum_le_tsum (λ n, _), apply add_haar_image_le_lintegral_abs_det_fderiv_aux2 μ (hs.inter (u_meas n)) _ (λ x hx, (hf' x hx.1).mono (inter_subset_left _ _)), have : μ (u n) < ∞ := lt_of_le_of_lt (measure_mono (disjointed_subset _ _)) (measure_spanning_sets_lt_top μ n), exact ne_of_lt (lt_of_le_of_lt (measure_mono (inter_subset_right _ _)) this), end ... = ∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ : begin conv_rhs { rw A }, rw lintegral_Union, { assume n, exact hs.inter (u_meas n) }, { exact pairwise_disjoint.mono (disjoint_disjointed _) (λ n, inter_subset_right _ _) } end end lemma lintegral_abs_det_fderiv_le_add_haar_image_aux1 (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hf : inj_on f s) {ε : ℝ≥0} (εpos : 0 < ε) : ∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ ≤ μ (f '' s) + 2 * ε * μ s := begin /- To bound `∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ`, we cover `s` by sets where `f` is well-approximated by linear maps `A n` (and where `f'` is almost everywhere close to `A n`), and then use that `f` expands the measure of such a set by at least `(A n).det - ε`. -/ have : ∀ (A : E →L[ℝ] E), ∃ (δ : ℝ≥0), 0 < δ ∧ (∀ (B : E →L[ℝ] E), ‖B - A‖ ≤ δ → |B.det - A.det| ≤ ε) ∧ ∀ (t : set E) (g : E → E) (hf : approximates_linear_on g A t δ), ennreal.of_real (|A.det|) * μ t ≤ μ (g '' t) + ε * μ t, { assume A, obtain ⟨δ', δ'pos, hδ'⟩ : ∃ (δ' : ℝ) (H : 0 < δ'), ∀ B, dist B A < δ' → dist B.det A.det < ↑ε := continuous_at_iff.1 continuous_linear_map.continuous_det.continuous_at ε εpos, let δ'' : ℝ≥0 := ⟨δ' / 2, (half_pos δ'pos).le⟩, have I'' : ∀ (B : E →L[ℝ] E), ‖B - A‖ ≤ ↑δ'' → |B.det - A.det| ≤ ↑ε, { assume B hB, rw ← real.dist_eq, apply (hδ' B _).le, rw dist_eq_norm, exact hB.trans_lt (half_lt_self δ'pos) }, rcases eq_or_ne A.det 0 with hA|hA, { refine ⟨δ'', half_pos δ'pos, I'', _⟩, simp only [hA, forall_const, zero_mul, ennreal.of_real_zero, implies_true_iff, zero_le, abs_zero] }, let m : ℝ≥0 := real.to_nnreal (|A.det|) - ε, have I : (m : ℝ≥0∞) < ennreal.of_real (|A.det|), { simp only [ennreal.of_real, with_top.coe_sub], apply ennreal.sub_lt_self ennreal.coe_ne_top, { simpa only [abs_nonpos_iff, real.to_nnreal_eq_zero, ennreal.coe_eq_zero, ne.def] using hA }, { simp only [εpos.ne', ennreal.coe_eq_zero, ne.def, not_false_iff] } }, rcases ((mul_le_add_haar_image_of_lt_det μ A I).and self_mem_nhds_within).exists with ⟨δ, h, δpos⟩, refine ⟨min δ δ'', lt_min δpos (half_pos δ'pos), _, _⟩, { assume B hB, apply I'' _ (hB.trans _), simp only [le_refl, nnreal.coe_min, min_le_iff, or_true] }, { assume t g htg, rcases eq_or_ne (μ t) ∞ with ht|ht, { simp only [ht, εpos.ne', with_top.mul_top, ennreal.coe_eq_zero, le_top, ne.def, not_false_iff, _root_.add_top] }, have := h t g (htg.mono_num (min_le_left _ _)), rwa [with_top.coe_sub, ennreal.sub_mul, tsub_le_iff_right] at this, simp only [ht, implies_true_iff, ne.def, not_false_iff] } }, choose δ hδ using this, obtain ⟨t, A, t_disj, t_meas, t_cover, ht, -⟩ : ∃ (t : ℕ → set E) (A : ℕ → (E →L[ℝ] E)), pairwise (disjoint on t) ∧ (∀ (n : ℕ), measurable_set (t n)) ∧ (s ⊆ ⋃ (n : ℕ), t n) ∧ (∀ (n : ℕ), approximates_linear_on f (A n) (s ∩ t n) (δ (A n))) ∧ (s.nonempty → ∀ n, ∃ y ∈ s, A n = f' y) := exists_partition_approximates_linear_on_of_has_fderiv_within_at f s f' hf' δ (λ A, (hδ A).1.ne'), have s_eq : s = ⋃ n, s ∩ t n, { rw ← inter_Union, exact subset.antisymm (subset_inter subset.rfl t_cover) (inter_subset_left _ _) }, calc ∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ = ∑' n, ∫⁻ x in s ∩ t n, ennreal.of_real (|(f' x).det|) ∂μ : begin conv_lhs { rw s_eq }, rw lintegral_Union, { exact λ n, hs.inter (t_meas n) }, { exact pairwise_disjoint.mono t_disj (λ n, inter_subset_right _ _) } end ... ≤ ∑' n, ∫⁻ x in s ∩ t n, ennreal.of_real (|(A n).det|) + ε ∂μ : begin apply ennreal.tsum_le_tsum (λ n, _), apply lintegral_mono_ae, filter_upwards [(ht n).norm_fderiv_sub_le μ (hs.inter (t_meas n)) f' (λ x hx, (hf' x hx.1).mono (inter_subset_left _ _))], assume x hx, have I : |(f' x).det| ≤ |(A n).det| + ε := calc |(f' x).det| = |(A n).det + ((f' x).det - (A n).det)| : by { congr' 1, abel } ... ≤ |(A n).det| + |(f' x).det - (A n).det| : abs_add _ _ ... ≤ |(A n).det| + ε : add_le_add le_rfl ((hδ (A n)).2.1 _ hx), calc ennreal.of_real (|(f' x).det|) ≤ ennreal.of_real (|(A n).det| + ε) : ennreal.of_real_le_of_real I ... = ennreal.of_real (|(A n).det|) + ε : by simp only [ennreal.of_real_add, abs_nonneg, nnreal.zero_le_coe, ennreal.of_real_coe_nnreal] end ... = ∑' n, (ennreal.of_real (|(A n).det|) * μ (s ∩ t n) + ε * μ (s ∩ t n)) : by simp only [set_lintegral_const, lintegral_add_right _ measurable_const] ... ≤ ∑' n, ((μ (f '' (s ∩ t n)) + ε * μ (s ∩ t n)) + ε * μ (s ∩ t n)) : begin refine ennreal.tsum_le_tsum (λ n, add_le_add_right _ _), exact (hδ (A n)).2.2 _ _ (ht n), end ... = μ (f '' s) + 2 * ε * μ s : begin conv_rhs { rw s_eq }, rw [image_Union, measure_Union], rotate, { assume i j hij, apply (disjoint.image _ hf (inter_subset_left _ _) (inter_subset_left _ _)), exact disjoint.mono (inter_subset_right _ _) (inter_subset_right _ _) (t_disj hij) }, { assume i, exact measurable_image_of_fderiv_within (hs.inter (t_meas i)) (λ x hx, (hf' x hx.1).mono (inter_subset_left _ _)) (hf.mono (inter_subset_left _ _)) }, rw measure_Union, rotate, { exact pairwise_disjoint.mono t_disj (λ i, inter_subset_right _ _) }, { exact λ i, hs.inter (t_meas i) }, rw [← ennreal.tsum_mul_left, ← ennreal.tsum_add], congr' 1, ext1 i, rw [mul_assoc, two_mul, add_assoc], end end lemma lintegral_abs_det_fderiv_le_add_haar_image_aux2 (hs : measurable_set s) (h's : μ s ≠ ∞) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hf : inj_on f s) : ∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ ≤ μ (f '' s) := begin /- We just need to let the error tend to `0` in the previous lemma. -/ have : tendsto (λ (ε : ℝ≥0), μ (f '' s) + 2 * ε * μ s) (𝓝[>] 0) (𝓝 (μ (f '' s) + 2 * (0 : ℝ≥0) * μ s)), { apply tendsto.mono_left _ nhds_within_le_nhds, refine tendsto_const_nhds.add _, refine ennreal.tendsto.mul_const _ (or.inr h's), exact ennreal.tendsto.const_mul (ennreal.tendsto_coe.2 tendsto_id) (or.inr ennreal.coe_ne_top) }, simp only [add_zero, zero_mul, mul_zero, ennreal.coe_zero] at this, apply ge_of_tendsto this, filter_upwards [self_mem_nhds_within], rintros ε (εpos : 0 < ε), exact lintegral_abs_det_fderiv_le_add_haar_image_aux1 μ hs hf' hf εpos end lemma lintegral_abs_det_fderiv_le_add_haar_image (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hf : inj_on f s) : ∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ ≤ μ (f '' s) := begin /- We already know the result for finite-measure sets. We cover `s` by finite-measure sets using `spanning_sets μ`, and apply the previous result to each of these parts. -/ let u := λ n, disjointed (spanning_sets μ) n, have u_meas : ∀ n, measurable_set (u n), { assume n, apply measurable_set.disjointed (λ i, _), exact measurable_spanning_sets μ i }, have A : s = ⋃ n, s ∩ u n, by rw [← inter_Union, Union_disjointed, Union_spanning_sets, inter_univ], calc ∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ = ∑' n, ∫⁻ x in s ∩ u n, ennreal.of_real (|(f' x).det|) ∂μ : begin conv_lhs { rw A }, rw lintegral_Union, { assume n, exact hs.inter (u_meas n) }, { exact pairwise_disjoint.mono (disjoint_disjointed _) (λ n, inter_subset_right _ _) } end ... ≤ ∑' n, μ (f '' (s ∩ u n)) : begin apply ennreal.tsum_le_tsum (λ n, _), apply lintegral_abs_det_fderiv_le_add_haar_image_aux2 μ (hs.inter (u_meas n)) _ (λ x hx, (hf' x hx.1).mono (inter_subset_left _ _)) (hf.mono (inter_subset_left _ _)), have : μ (u n) < ∞ := lt_of_le_of_lt (measure_mono (disjointed_subset _ _)) (measure_spanning_sets_lt_top μ n), exact ne_of_lt (lt_of_le_of_lt (measure_mono (inter_subset_right _ _)) this), end ... = μ (f '' s) : begin conv_rhs { rw [A, image_Union] }, rw measure_Union, { assume i j hij, apply disjoint.image _ hf (inter_subset_left _ _) (inter_subset_left _ _), exact disjoint.mono (inter_subset_right _ _) (inter_subset_right _ _) (disjoint_disjointed _ hij) }, { assume i, exact measurable_image_of_fderiv_within (hs.inter (u_meas i)) (λ x hx, (hf' x hx.1).mono (inter_subset_left _ _)) (hf.mono (inter_subset_left _ _)) }, end end /-- Change of variable formula for differentiable functions, set version: if a function `f` is injective and differentiable on a measurable set `s`, then the measure of `f '' s` is given by the integral of `|(f' x).det|` on `s`. Note that the measurability of `f '' s` is given by `measurable_image_of_fderiv_within`. -/ theorem lintegral_abs_det_fderiv_eq_add_haar_image (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hf : inj_on f s) : ∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ = μ (f '' s) := le_antisymm (lintegral_abs_det_fderiv_le_add_haar_image μ hs hf' hf) (add_haar_image_le_lintegral_abs_det_fderiv μ hs hf') /-- Change of variable formula for differentiable functions, set version: if a function `f` is injective and differentiable on a measurable set `s`, then the pushforward of the measure with density `|(f' x).det|` on `s` is the Lebesgue measure on the image set. This version requires that `f` is measurable, as otherwise `measure.map f` is zero per our definitions. For a version without measurability assumption but dealing with the restricted function `s.restrict f`, see `restrict_map_with_density_abs_det_fderiv_eq_add_haar`. -/ theorem map_with_density_abs_det_fderiv_eq_add_haar (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hf : inj_on f s) (h'f : measurable f) : measure.map f ((μ.restrict s).with_density (λ x, ennreal.of_real (|(f' x).det|))) = μ.restrict (f '' s) := begin apply measure.ext (λ t ht, _), rw [map_apply h'f ht, with_density_apply _ (h'f ht), measure.restrict_apply ht, restrict_restrict (h'f ht), lintegral_abs_det_fderiv_eq_add_haar_image μ ((h'f ht).inter hs) (λ x hx, (hf' x hx.2).mono (inter_subset_right _ _)) (hf.mono (inter_subset_right _ _)), image_preimage_inter] end /-- Change of variable formula for differentiable functions, set version: if a function `f` is injective and differentiable on a measurable set `s`, then the pushforward of the measure with density `|(f' x).det|` on `s` is the Lebesgue measure on the image set. This version is expressed in terms of the restricted function `s.restrict f`. For a version for the original function, but with a measurability assumption, see `map_with_density_abs_det_fderiv_eq_add_haar`. -/ theorem restrict_map_with_density_abs_det_fderiv_eq_add_haar (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hf : inj_on f s) : measure.map (s.restrict f) (comap coe (μ.with_density (λ x, ennreal.of_real (|(f' x).det|)))) = μ.restrict (f '' s) := begin obtain ⟨u, u_meas, uf⟩ : ∃ u, measurable u ∧ eq_on u f s, { classical, refine ⟨piecewise s f 0, _, piecewise_eq_on _ _ _⟩, refine continuous_on.measurable_piecewise _ continuous_zero.continuous_on hs, have : differentiable_on ℝ f s := λ x hx, (hf' x hx).differentiable_within_at, exact this.continuous_on }, have u' : ∀ x ∈ s, has_fderiv_within_at u (f' x) s x := λ x hx, (hf' x hx).congr (λ y hy, uf hy) (uf hx), set F : s → E := u ∘ coe with hF, have A : measure.map F (comap coe (μ.with_density (λ x, ennreal.of_real (|(f' x).det|)))) = μ.restrict (u '' s), { rw [hF, ← measure.map_map u_meas measurable_subtype_coe, map_comap_subtype_coe hs, restrict_with_density hs], exact map_with_density_abs_det_fderiv_eq_add_haar μ hs u' (hf.congr uf.symm) u_meas }, rw uf.image_eq at A, have : F = s.restrict f, { ext x, exact uf x.2 }, rwa this at A, end /-! ### Change of variable formulas in integrals -/ /- Change of variable formula for differentiable functions: if a function `f` is injective and differentiable on a measurable set `s`, then the Lebesgue integral of a function `g : E → ℝ≥0∞` on `f '' s` coincides with the integral of `|(f' x).det| * g ∘ f` on `s`. Note that the measurability of `f '' s` is given by `measurable_image_of_fderiv_within`. -/ theorem lintegral_image_eq_lintegral_abs_det_fderiv_mul (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hf : inj_on f s) (g : E → ℝ≥0∞) : ∫⁻ x in f '' s, g x ∂μ = ∫⁻ x in s, ennreal.of_real (|(f' x).det|) * g (f x) ∂μ := begin rw [← restrict_map_with_density_abs_det_fderiv_eq_add_haar μ hs hf' hf, (measurable_embedding_of_fderiv_within hs hf' hf).lintegral_map], have : ∀ (x : s), g (s.restrict f x) = (g ∘ f) x := λ x, rfl, simp only [this], rw [← (measurable_embedding.subtype_coe hs).lintegral_map, map_comap_subtype_coe hs, set_lintegral_with_density_eq_set_lintegral_mul_non_measurable₀ _ _ _ hs], { refl }, { simp only [eventually_true, ennreal.of_real_lt_top] }, { exact ae_measurable_of_real_abs_det_fderiv_within μ hs hf' } end /-- Integrability in the change of variable formula for differentiable functions: if a function `f` is injective and differentiable on a measurable set `s`, then a function `g : E → F` is integrable on `f '' s` if and only if `|(f' x).det| • g ∘ f` is integrable on `s`. -/ theorem integrable_on_image_iff_integrable_on_abs_det_fderiv_smul (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hf : inj_on f s) (g : E → F) : integrable_on g (f '' s) μ ↔ integrable_on (λ x, |(f' x).det| • g (f x)) s μ := begin rw [integrable_on, ← restrict_map_with_density_abs_det_fderiv_eq_add_haar μ hs hf' hf, (measurable_embedding_of_fderiv_within hs hf' hf).integrable_map_iff], change (integrable ((g ∘ f) ∘ (coe : s → E)) _) ↔ _, rw [← (measurable_embedding.subtype_coe hs).integrable_map_iff, map_comap_subtype_coe hs], simp only [ennreal.of_real], rw [restrict_with_density hs, integrable_with_density_iff_integrable_coe_smul₀, integrable_on], { congr' 2 with x, rw real.coe_to_nnreal, exact abs_nonneg _ }, { exact ae_measurable_to_nnreal_abs_det_fderiv_within μ hs hf' } end /-- Change of variable formula for differentiable functions: if a function `f` is injective and differentiable on a measurable set `s`, then the Bochner integral of a function `g : E → F` on `f '' s` coincides with the integral of `|(f' x).det| • g ∘ f` on `s`. -/ theorem integral_image_eq_integral_abs_det_fderiv_smul [complete_space F] (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hf : inj_on f s) (g : E → F) : ∫ x in f '' s, g x ∂μ = ∫ x in s, |(f' x).det| • g (f x) ∂μ := begin rw [← restrict_map_with_density_abs_det_fderiv_eq_add_haar μ hs hf' hf, (measurable_embedding_of_fderiv_within hs hf' hf).integral_map], have : ∀ (x : s), g (s.restrict f x) = (g ∘ f) x := λ x, rfl, simp only [this, ennreal.of_real], rw [← (measurable_embedding.subtype_coe hs).integral_map, map_comap_subtype_coe hs, set_integral_with_density_eq_set_integral_smul₀ (ae_measurable_to_nnreal_abs_det_fderiv_within μ hs hf') _ hs], congr' with x, conv_rhs { rw ← real.coe_to_nnreal _ (abs_nonneg (f' x).det) }, refl end /- Porting note: move this to `topology.algebra.module.basic` when port is over -/ lemma det_one_smul_right {𝕜 : Type*} [normed_field 𝕜] (v : 𝕜) : ((1 : 𝕜 →L[𝕜] 𝕜).smul_right v).det = v := begin have : (1 : 𝕜 →L[𝕜] 𝕜).smul_right v = v • (1 : 𝕜 →L[𝕜] 𝕜), { ext1 w, simp only [continuous_linear_map.smul_right_apply, continuous_linear_map.one_apply, algebra.id.smul_eq_mul, one_mul, continuous_linear_map.coe_smul', pi.smul_apply, mul_one] }, rw [this, continuous_linear_map.det, continuous_linear_map.coe_smul], change ((1 : 𝕜 →L[𝕜] 𝕜) : 𝕜 →ₗ[𝕜] 𝕜) with linear_map.id, rw [linear_map.det_smul, finite_dimensional.finrank_self, linear_map.det_id, pow_one, mul_one], end /-- Integrability in the change of variable formula for differentiable functions (one-variable version): if a function `f` is injective and differentiable on a measurable set ``s ⊆ ℝ`, then a function `g : ℝ → F` is integrable on `f '' s` if and only if `|(f' x)| • g ∘ f` is integrable on `s`. -/ theorem integrable_on_image_iff_integrable_on_abs_deriv_smul {s : set ℝ} {f : ℝ → ℝ} {f' : ℝ → ℝ} (hs : measurable_set s) (hf' : ∀ x ∈ s, has_deriv_within_at f (f' x) s x) (hf : inj_on f s) (g : ℝ → F) : integrable_on g (f '' s) ↔ integrable_on (λ x, |(f' x)| • g (f x)) s := by simpa only [det_one_smul_right] using integrable_on_image_iff_integrable_on_abs_det_fderiv_smul volume hs (λ x hx, (hf' x hx).has_fderiv_within_at) hf g /-- Change of variable formula for differentiable functions (one-variable version): if a function `f` is injective and differentiable on a measurable set `s ⊆ ℝ`, then the Bochner integral of a function `g : ℝ → F` on `f '' s` coincides with the integral of `|(f' x)| • g ∘ f` on `s`. -/ theorem integral_image_eq_integral_abs_deriv_smul {s : set ℝ} {f : ℝ → ℝ} {f' : ℝ → ℝ} [complete_space F] (hs : measurable_set s) (hf' : ∀ x ∈ s, has_deriv_within_at f (f' x) s x) (hf : inj_on f s) (g : ℝ → F) : ∫ x in f '' s, g x = ∫ x in s, |(f' x)| • g (f x) := by simpa only [det_one_smul_right] using integral_image_eq_integral_abs_det_fderiv_smul volume hs (λ x hx, (hf' x hx).has_fderiv_within_at) hf g theorem integral_target_eq_integral_abs_det_fderiv_smul [complete_space F] {f : local_homeomorph E E} (hf' : ∀ x ∈ f.source, has_fderiv_at f (f' x) x) (g : E → F) : ∫ x in f.target, g x ∂μ = ∫ x in f.source, |(f' x).det| • g (f x) ∂μ := begin have : f '' f.source = f.target := local_equiv.image_source_eq_target f.to_local_equiv, rw ← this, apply integral_image_eq_integral_abs_det_fderiv_smul μ f.open_source.measurable_set _ f.inj_on, assume x hx, exact (hf' x hx).has_fderiv_within_at end end measure_theory
ae5fa87ffef748e30f44a578fa88477d5b7be2e8
02fbe05a45fda5abde7583464416db4366eedfbf
/library/data/buffer.lean
d72e7b72ccd9b20cfb93130d79af39beac7f7360
[ "Apache-2.0" ]
permissive
jasonrute/lean
cc12807e11f9ac6b01b8951a8bfb9c2eb35a0154
4be962c167ca442a0ec5e84472d7ff9f5302788f
refs/heads/master
1,672,036,664,637
1,601,642,826,000
1,601,642,826,000
260,777,966
0
0
Apache-2.0
1,588,454,819,000
1,588,454,818,000
null
UTF-8
Lean
false
false
4,838
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 -/ universes u w def buffer (α : Type u) := Σ n, array n α def mk_buffer {α : Type u} : buffer α := ⟨0, {data := λ i, fin.elim0 i}⟩ def array.to_buffer {α : Type u} {n : nat} (a : array n α) : buffer α := ⟨n, a⟩ namespace buffer variables {α : Type u} {β : Type w} def nil : buffer α := mk_buffer def size (b : buffer α) : nat := b.1 def to_array (b : buffer α) : array (b.size) α := b.2 def push_back : buffer α → α → buffer α | ⟨n, a⟩ v := ⟨n+1, a.push_back v⟩ def pop_back : buffer α → buffer α | ⟨0, a⟩ := ⟨0, a⟩ | ⟨n+1, a⟩ := ⟨n, a.pop_back⟩ def read : Π (b : buffer α), fin b.size → α | ⟨n, a⟩ i := a.read i def write : Π (b : buffer α), fin b.size → α → buffer α | ⟨n, a⟩ i v := ⟨n, a.write i v⟩ def read' [inhabited α] : buffer α → nat → α | ⟨n, a⟩ i := a.read' i def write' : buffer α → nat → α → buffer α | ⟨n, a⟩ i v := ⟨n, a.write' i v⟩ lemma read_eq_read' [inhabited α] (b : buffer α) (i : nat) (h : i < b.size) : read b ⟨i, h⟩ = read' b i := by cases b; unfold read read'; simp [array.read_eq_read'] lemma write_eq_write' (b : buffer α) (i : nat) (h : i < b.size) (v : α) : write b ⟨i, h⟩ v = write' b i v := by cases b; unfold write write'; simp [array.write_eq_write'] def to_list (b : buffer α) : list α := b.to_array.to_list protected def to_string (b : buffer char) : string := b.to_array.to_list.as_string def append_list {α : Type u} : buffer α → list α → buffer α | b [] := b | b (v::vs) := append_list (b.push_back v) vs def append_string (b : buffer char) (s : string) : buffer char := b.append_list s.to_list lemma lt_aux_1 {a b c : nat} (h : a + c < b) : a < b := lt_of_le_of_lt (nat.le_add_right a c) h lemma lt_aux_2 {n} (h : n > 0) : n - 1 < n := have h₁ : 1 > 0, from dec_trivial, nat.sub_lt h h₁ lemma lt_aux_3 {n i} (h : i + 1 < n) : n - 2 - i < n := have n > 0, from lt.trans (nat.zero_lt_succ i) h, have n - 2 < n, from nat.sub_lt this (dec_trivial), lt_of_le_of_lt (nat.sub_le _ _) this def append_array {α : Type u} {n : nat} (nz : n > 0) : buffer α → array n α → ∀ i : nat, i < n → buffer α | ⟨m, b⟩ a 0 _ := let i : fin n := ⟨n - 1, lt_aux_2 nz⟩ in ⟨m+1, b.push_back (a.read i)⟩ | ⟨m, b⟩ a (j+1) h := let i : fin n := ⟨n - 2 - j, lt_aux_3 h⟩ in append_array ⟨m+1, b.push_back (a.read i)⟩ a j (lt_aux_1 h) protected def append {α : Type u} : buffer α → buffer α → buffer α | b ⟨0, a⟩ := b | b ⟨n+1, a⟩ := append_array (nat.zero_lt_succ _) b a n (nat.lt_succ_self _) def iterate : Π b : buffer α, β → (fin b.size → α → β → β) → β | ⟨_, a⟩ b f := a.iterate b f def foreach : Π b : buffer α, (fin b.size → α → α) → buffer α | ⟨n, a⟩ f := ⟨n, a.foreach f⟩ /-- Monadically map a function over the buffer. -/ @[inline] def mmap {m} [monad m] (b : buffer α) (f : α → m β) : m (buffer β) := do b' ← b.2.mmap f, return b'.to_buffer /-- Map a function over the buffer. -/ @[inline] def map : buffer α → (α → β) → buffer β | ⟨n, a⟩ f := ⟨n, a.map f⟩ def foldl : buffer α → β → (α → β → β) → β | ⟨_, a⟩ b f := a.foldl b f def rev_iterate : Π (b : buffer α), β → (fin b.size → α → β → β) → β | ⟨_, a⟩ b f := a.rev_iterate b f def take (b : buffer α) (n : nat) : buffer α := if h : n ≤ b.size then ⟨n, b.to_array.take n h⟩ else b def take_right (b : buffer α) (n : nat) : buffer α := if h : n ≤ b.size then ⟨n, b.to_array.take_right n h⟩ else b def drop (b : buffer α) (n : nat) : buffer α := if h : n ≤ b.size then ⟨_, b.to_array.drop n h⟩ else b def reverse (b : buffer α) : buffer α := ⟨b.size, b.to_array.reverse⟩ protected def mem (v : α) (a : buffer α) : Prop := ∃i, read a i = v instance : has_mem α (buffer α) := ⟨buffer.mem⟩ instance : has_append (buffer α) := ⟨buffer.append⟩ instance [has_repr α] : has_repr (buffer α) := ⟨repr ∘ to_list⟩ meta instance [has_to_format α] : has_to_format (buffer α) := ⟨to_fmt ∘ to_list⟩ meta instance [has_to_tactic_format α] : has_to_tactic_format (buffer α) := ⟨tactic.pp ∘ to_list⟩ end buffer def list.to_buffer {α : Type u} (l : list α) : buffer α := mk_buffer.append_list l @[reducible] def char_buffer := buffer char /-- Convert a format object into a character buffer with the provided formatting options. -/ meta constant format.to_buffer : format → options → buffer char def string.to_char_buffer (s : string) : char_buffer := buffer.nil.append_string s
12f8014f1e37866160f7679d29b29ddc4639b8fd
59aed81a2ce7741e690907fc374be338f4f88b6f
/src/math-688/lectures/lec-4.lean
7549697e965fb8c3b2b19299fbe272c63b830942
[]
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
55
lean
/- 6 Sep 2019 -/ -- bipartite graphs, hamiltonian cycle
3763335c85744c5e4f9bc06c9874e7bc21cc9294
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/group/with_one/units.lean
41aff905b5f1f79fe9c87209ca184dfc73995ad4
[ "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
896
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.group.with_one.basic import algebra.group_with_zero.units.basic /-! # Isomorphism between a group and the units of itself adjoined with `0` ## Notes This is here to keep `algebra.group_with_zero.units.basic` out of the import requirements of `algebra.order.field.defs`. -/ namespace with_zero /-- Any group is isomorphic to the units of itself adjoined with `0`. -/ def units_with_zero_equiv {α : Type*} [group α] : (with_zero α)ˣ ≃* α := { to_fun := λ a, unzero a.ne_zero, inv_fun := λ a, units.mk0 a coe_ne_zero, left_inv := λ _, units.ext $ by simpa only [coe_unzero], right_inv := λ _, rfl, map_mul' := λ _ _, coe_inj.mp $ by simpa only [coe_unzero, coe_mul] } end with_zero
02693167e5946427b5a8cb71a5531537f05316e7
367134ba5a65885e863bdc4507601606690974c1
/src/data/polynomial/basic.lean
af0b3cd2baeb21264202756bc8edeedb58c81ab7
[ "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,379
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 {S₁ S₂} [semiring S₁] [semiring S₂] [semimodule S₁ R] [semimodule S₂ R] [smul_comm_class S₁ S₂ R] : smul_comm_class S₁ S₂ (polynomial R) := add_monoid_algebra.smul_comm_class instance {S₁ S₂} [has_scalar S₁ S₂] [semiring S₁] [semiring S₂] [semimodule S₁ R] [semimodule S₂ R] [is_scalar_tower S₁ S₂ R] : is_scalar_tower S₁ S₂ (polynomial R) := add_monoid_algebra.is_scalar_tower instance [subsingleton R] : unique (polynomial R) := add_monoid_algebra.unique /-- The set of all `n` such that `X^n` has a non-zero coefficient. -/ def support (p : polynomial R) : finset ℕ := p.support @[simp] lemma support_zero : (0 : polynomial R).support = ∅ := rfl @[simp] lemma support_eq_empty : p.support = ∅ ↔ p = 0 := by simp [support] lemma card_support_eq_zero : p.support.card = 0 ↔ p = 0 := by simp /-- `monomial s a` is the monomial `a * X^s` -/ def monomial (n : ℕ) : R →ₗ[R] polynomial R := finsupp.lsingle n @[simp] lemma monomial_zero_right (n : ℕ) : monomial n (0 : R) = 0 := finsupp.single_zero -- This is not a `simp` lemma as `monomial_zero_left` is more general. lemma monomial_zero_one : monomial 0 (1 : R) = 1 := rfl 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 @[simp] lemma monomial_pow (n : ℕ) (r : R) (k : ℕ) : (monomial n r)^k = monomial (n*k) (r^k) := begin rw mul_comm, convert add_monoid_algebra.single_pow k, simp only [nat.cast_id, nsmul_eq_mul], refl, end 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 _ _ _ lemma support_add : (p + q).support ⊆ p.support ∪ q.support := by convert @support_add _ _ _ p q /-- `X` is the polynomial variable (aka indeterminant). -/ def X : polynomial R := monomial 1 1 lemma monomial_one_one_eq_X : monomial 1 (1 : R) = X := rfl lemma monomial_one_right_eq_X_pow (n : ℕ) : monomial n 1 = X^n := begin induction n with n ih, { simp [monomial_zero_one], }, { rw [pow_succ, ←ih, ←monomial_one_one_eq_X, monomial_mul_monomial, add_comm, one_mul], } end /-- `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 @[simp] lemma monomial_mul_X (n : ℕ) (r : R) : monomial n r * X = monomial (n+1) r := by erw [monomial_mul_monomial, mul_one] @[simp] lemma monomial_mul_X_pow (n : ℕ) (r : R) (k : ℕ) : monomial n r * X^k = monomial (n+k) r := begin induction k with k ih, { simp, }, { simp [ih, pow_succ', ←mul_assoc, add_assoc], }, end @[simp] lemma X_mul_monomial (n : ℕ) (r : R) : X * monomial n r = monomial (n+1) r := by rw [X_mul, monomial_mul_X] @[simp] lemma X_pow_mul_monomial (k n : ℕ) (r : R) : X^k * monomial n r = monomial (n+k) r := by rw [X_pow_mul, monomial_mul_X_pow] /-- 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] @[simp] lemma support_neg {p : polynomial R} : (-p).support = p.support := by simp [support] 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
26e29725e83695e3df64b97f81245534167472a2
aa5a655c05e5359a70646b7154e7cac59f0b4132
/src/Lean/Util/ReplaceExpr.lean
2b708ba758f5ab0b4b484ad56c952fcf01e05792
[ "Apache-2.0" ]
permissive
lambdaxymox/lean4
ae943c960a42247e06eff25c35338268d07454cb
278d47c77270664ef29715faab467feac8a0f446
refs/heads/master
1,677,891,867,340
1,612,500,005,000
1,612,500,005,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,004
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.Expr namespace Lean namespace Expr namespace ReplaceImpl abbrev cacheSize : USize := 8192 structure State where keys : Array Expr -- Remark: our "unsafe" implementation relies on the fact that `()` is not a valid Expr results : Array Expr abbrev ReplaceM := StateM State @[inline] unsafe def cache (i : USize) (key : Expr) (result : Expr) : ReplaceM Expr := do modify fun s => { keys := s.keys.uset i key lcProof, results := s.results.uset i result lcProof }; pure result @[inline] unsafe def replaceUnsafeM (f? : Expr → Option Expr) (size : USize) (e : Expr) : ReplaceM Expr := do let rec @[specialize] visit (e : Expr) := do let c ← get let h := ptrAddrUnsafe e let i := h % size if ptrAddrUnsafe (c.keys.uget i lcProof) == h then pure <| c.results.uget i lcProof else match f? e with | some eNew => cache i e eNew | none => match e with | Expr.forallE _ d b _ => cache i e <| e.updateForallE! (← visit d) (← visit b) | Expr.lam _ d b _ => cache i e <| e.updateLambdaE! (← visit d) (← visit b) | Expr.mdata _ b _ => cache i e <| e.updateMData! (← visit b) | Expr.letE _ t v b _ => cache i e <| e.updateLet! (← visit t) (← visit v) (← visit b) | Expr.app f a _ => cache i e <| e.updateApp! (← visit f) (← visit a) | Expr.proj _ _ b _ => cache i e <| e.updateProj! (← visit b) | e => pure e visit e unsafe def initCache : State := { keys := mkArray cacheSize.toNat (cast lcProof ()), -- `()` is not a valid `Expr` results := mkArray cacheSize.toNat arbitrary } @[inline] unsafe def replaceUnsafe (f? : Expr → Option Expr) (e : Expr) : Expr := (replaceUnsafeM f? cacheSize e).run' initCache end ReplaceImpl /- TODO: use withPtrAddr, withPtrEq to avoid unsafe tricks above. We also need an invariant at `State` and proofs for the `uget` operations. -/ @[implementedBy ReplaceImpl.replaceUnsafe] partial def replace (f? : Expr → Option Expr) (e : Expr) : Expr := /- This is a reference implementation for the unsafe one above -/ match f? e with | some eNew => eNew | none => match e with | Expr.forallE _ d b _ => let d := replace f? d; let b := replace f? b; e.updateForallE! d b | Expr.lam _ d b _ => let d := replace f? d; let b := replace f? b; e.updateLambdaE! d b | Expr.mdata _ b _ => let b := replace f? b; e.updateMData! b | Expr.letE _ t v b _ => let t := replace f? t; let v := replace f? v; let b := replace f? b; e.updateLet! t v b | Expr.app f a _ => let f := replace f? f; let a := replace f? a; e.updateApp! f a | Expr.proj _ _ b _ => let b := replace f? b; e.updateProj! b | e => e end Expr end Lean